]> git.karo-electronics.de Git - karo-tx-linux.git/blob - net/netfilter/ipvs/ip_vs_ctl.c
netfilter: nf_tables: check for overflow of rule dlen field
[karo-tx-linux.git] / net / netfilter / ipvs / ip_vs_ctl.c
1 /*
2  * IPVS         An implementation of the IP virtual server support for the
3  *              LINUX operating system.  IPVS is now implemented as a module
4  *              over the NetFilter framework. IPVS can be used to build a
5  *              high-performance and highly available server based on a
6  *              cluster of servers.
7  *
8  * Authors:     Wensong Zhang <wensong@linuxvirtualserver.org>
9  *              Peter Kese <peter.kese@ijs.si>
10  *              Julian Anastasov <ja@ssi.bg>
11  *
12  *              This program is free software; you can redistribute it and/or
13  *              modify it under the terms of the GNU General Public License
14  *              as published by the Free Software Foundation; either version
15  *              2 of the License, or (at your option) any later version.
16  *
17  * Changes:
18  *
19  */
20
21 #define KMSG_COMPONENT "IPVS"
22 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
23
24 #include <linux/module.h>
25 #include <linux/init.h>
26 #include <linux/types.h>
27 #include <linux/capability.h>
28 #include <linux/fs.h>
29 #include <linux/sysctl.h>
30 #include <linux/proc_fs.h>
31 #include <linux/workqueue.h>
32 #include <linux/swap.h>
33 #include <linux/seq_file.h>
34 #include <linux/slab.h>
35
36 #include <linux/netfilter.h>
37 #include <linux/netfilter_ipv4.h>
38 #include <linux/mutex.h>
39
40 #include <net/net_namespace.h>
41 #include <linux/nsproxy.h>
42 #include <net/ip.h>
43 #ifdef CONFIG_IP_VS_IPV6
44 #include <net/ipv6.h>
45 #include <net/ip6_route.h>
46 #endif
47 #include <net/route.h>
48 #include <net/sock.h>
49 #include <net/genetlink.h>
50
51 #include <asm/uaccess.h>
52
53 #include <net/ip_vs.h>
54
55 /* semaphore for IPVS sockopts. And, [gs]etsockopt may sleep. */
56 static DEFINE_MUTEX(__ip_vs_mutex);
57
58 /* sysctl variables */
59
60 #ifdef CONFIG_IP_VS_DEBUG
61 static int sysctl_ip_vs_debug_level = 0;
62
63 int ip_vs_get_debug_level(void)
64 {
65         return sysctl_ip_vs_debug_level;
66 }
67 #endif
68
69
70 /*  Protos */
71 static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup);
72
73
74 #ifdef CONFIG_IP_VS_IPV6
75 /* Taken from rt6_fill_node() in net/ipv6/route.c, is there a better way? */
76 static bool __ip_vs_addr_is_local_v6(struct net *net,
77                                      const struct in6_addr *addr)
78 {
79         struct flowi6 fl6 = {
80                 .daddr = *addr,
81         };
82         struct dst_entry *dst = ip6_route_output(net, NULL, &fl6);
83         bool is_local;
84
85         is_local = !dst->error && dst->dev && (dst->dev->flags & IFF_LOOPBACK);
86
87         dst_release(dst);
88         return is_local;
89 }
90 #endif
91
92 #ifdef CONFIG_SYSCTL
93 /*
94  *      update_defense_level is called from keventd and from sysctl,
95  *      so it needs to protect itself from softirqs
96  */
97 static void update_defense_level(struct netns_ipvs *ipvs)
98 {
99         struct sysinfo i;
100         static int old_secure_tcp = 0;
101         int availmem;
102         int nomem;
103         int to_change = -1;
104
105         /* we only count free and buffered memory (in pages) */
106         si_meminfo(&i);
107         availmem = i.freeram + i.bufferram;
108         /* however in linux 2.5 the i.bufferram is total page cache size,
109            we need adjust it */
110         /* si_swapinfo(&i); */
111         /* availmem = availmem - (i.totalswap - i.freeswap); */
112
113         nomem = (availmem < ipvs->sysctl_amemthresh);
114
115         local_bh_disable();
116
117         /* drop_entry */
118         spin_lock(&ipvs->dropentry_lock);
119         switch (ipvs->sysctl_drop_entry) {
120         case 0:
121                 atomic_set(&ipvs->dropentry, 0);
122                 break;
123         case 1:
124                 if (nomem) {
125                         atomic_set(&ipvs->dropentry, 1);
126                         ipvs->sysctl_drop_entry = 2;
127                 } else {
128                         atomic_set(&ipvs->dropentry, 0);
129                 }
130                 break;
131         case 2:
132                 if (nomem) {
133                         atomic_set(&ipvs->dropentry, 1);
134                 } else {
135                         atomic_set(&ipvs->dropentry, 0);
136                         ipvs->sysctl_drop_entry = 1;
137                 };
138                 break;
139         case 3:
140                 atomic_set(&ipvs->dropentry, 1);
141                 break;
142         }
143         spin_unlock(&ipvs->dropentry_lock);
144
145         /* drop_packet */
146         spin_lock(&ipvs->droppacket_lock);
147         switch (ipvs->sysctl_drop_packet) {
148         case 0:
149                 ipvs->drop_rate = 0;
150                 break;
151         case 1:
152                 if (nomem) {
153                         ipvs->drop_rate = ipvs->drop_counter
154                                 = ipvs->sysctl_amemthresh /
155                                 (ipvs->sysctl_amemthresh-availmem);
156                         ipvs->sysctl_drop_packet = 2;
157                 } else {
158                         ipvs->drop_rate = 0;
159                 }
160                 break;
161         case 2:
162                 if (nomem) {
163                         ipvs->drop_rate = ipvs->drop_counter
164                                 = ipvs->sysctl_amemthresh /
165                                 (ipvs->sysctl_amemthresh-availmem);
166                 } else {
167                         ipvs->drop_rate = 0;
168                         ipvs->sysctl_drop_packet = 1;
169                 }
170                 break;
171         case 3:
172                 ipvs->drop_rate = ipvs->sysctl_am_droprate;
173                 break;
174         }
175         spin_unlock(&ipvs->droppacket_lock);
176
177         /* secure_tcp */
178         spin_lock(&ipvs->securetcp_lock);
179         switch (ipvs->sysctl_secure_tcp) {
180         case 0:
181                 if (old_secure_tcp >= 2)
182                         to_change = 0;
183                 break;
184         case 1:
185                 if (nomem) {
186                         if (old_secure_tcp < 2)
187                                 to_change = 1;
188                         ipvs->sysctl_secure_tcp = 2;
189                 } else {
190                         if (old_secure_tcp >= 2)
191                                 to_change = 0;
192                 }
193                 break;
194         case 2:
195                 if (nomem) {
196                         if (old_secure_tcp < 2)
197                                 to_change = 1;
198                 } else {
199                         if (old_secure_tcp >= 2)
200                                 to_change = 0;
201                         ipvs->sysctl_secure_tcp = 1;
202                 }
203                 break;
204         case 3:
205                 if (old_secure_tcp < 2)
206                         to_change = 1;
207                 break;
208         }
209         old_secure_tcp = ipvs->sysctl_secure_tcp;
210         if (to_change >= 0)
211                 ip_vs_protocol_timeout_change(ipvs,
212                                               ipvs->sysctl_secure_tcp > 1);
213         spin_unlock(&ipvs->securetcp_lock);
214
215         local_bh_enable();
216 }
217
218
219 /*
220  *      Timer for checking the defense
221  */
222 #define DEFENSE_TIMER_PERIOD    1*HZ
223
224 static void defense_work_handler(struct work_struct *work)
225 {
226         struct netns_ipvs *ipvs =
227                 container_of(work, struct netns_ipvs, defense_work.work);
228
229         update_defense_level(ipvs);
230         if (atomic_read(&ipvs->dropentry))
231                 ip_vs_random_dropentry(ipvs->net);
232         schedule_delayed_work(&ipvs->defense_work, DEFENSE_TIMER_PERIOD);
233 }
234 #endif
235
236 int
237 ip_vs_use_count_inc(void)
238 {
239         return try_module_get(THIS_MODULE);
240 }
241
242 void
243 ip_vs_use_count_dec(void)
244 {
245         module_put(THIS_MODULE);
246 }
247
248
249 /*
250  *      Hash table: for virtual service lookups
251  */
252 #define IP_VS_SVC_TAB_BITS 8
253 #define IP_VS_SVC_TAB_SIZE (1 << IP_VS_SVC_TAB_BITS)
254 #define IP_VS_SVC_TAB_MASK (IP_VS_SVC_TAB_SIZE - 1)
255
256 /* the service table hashed by <protocol, addr, port> */
257 static struct hlist_head ip_vs_svc_table[IP_VS_SVC_TAB_SIZE];
258 /* the service table hashed by fwmark */
259 static struct hlist_head ip_vs_svc_fwm_table[IP_VS_SVC_TAB_SIZE];
260
261
262 /*
263  *      Returns hash value for virtual service
264  */
265 static inline unsigned int
266 ip_vs_svc_hashkey(struct net *net, int af, unsigned int proto,
267                   const union nf_inet_addr *addr, __be16 port)
268 {
269         register unsigned int porth = ntohs(port);
270         __be32 addr_fold = addr->ip;
271         __u32 ahash;
272
273 #ifdef CONFIG_IP_VS_IPV6
274         if (af == AF_INET6)
275                 addr_fold = addr->ip6[0]^addr->ip6[1]^
276                             addr->ip6[2]^addr->ip6[3];
277 #endif
278         ahash = ntohl(addr_fold);
279         ahash ^= ((size_t) net >> 8);
280
281         return (proto ^ ahash ^ (porth >> IP_VS_SVC_TAB_BITS) ^ porth) &
282                IP_VS_SVC_TAB_MASK;
283 }
284
285 /*
286  *      Returns hash value of fwmark for virtual service lookup
287  */
288 static inline unsigned int ip_vs_svc_fwm_hashkey(struct net *net, __u32 fwmark)
289 {
290         return (((size_t)net>>8) ^ fwmark) & IP_VS_SVC_TAB_MASK;
291 }
292
293 /*
294  *      Hashes a service in the ip_vs_svc_table by <netns,proto,addr,port>
295  *      or in the ip_vs_svc_fwm_table by fwmark.
296  *      Should be called with locked tables.
297  */
298 static int ip_vs_svc_hash(struct ip_vs_service *svc)
299 {
300         unsigned int hash;
301
302         if (svc->flags & IP_VS_SVC_F_HASHED) {
303                 pr_err("%s(): request for already hashed, called from %pF\n",
304                        __func__, __builtin_return_address(0));
305                 return 0;
306         }
307
308         if (svc->fwmark == 0) {
309                 /*
310                  *  Hash it by <netns,protocol,addr,port> in ip_vs_svc_table
311                  */
312                 hash = ip_vs_svc_hashkey(svc->net, svc->af, svc->protocol,
313                                          &svc->addr, svc->port);
314                 hlist_add_head_rcu(&svc->s_list, &ip_vs_svc_table[hash]);
315         } else {
316                 /*
317                  *  Hash it by fwmark in svc_fwm_table
318                  */
319                 hash = ip_vs_svc_fwm_hashkey(svc->net, svc->fwmark);
320                 hlist_add_head_rcu(&svc->f_list, &ip_vs_svc_fwm_table[hash]);
321         }
322
323         svc->flags |= IP_VS_SVC_F_HASHED;
324         /* increase its refcnt because it is referenced by the svc table */
325         atomic_inc(&svc->refcnt);
326         return 1;
327 }
328
329
330 /*
331  *      Unhashes a service from svc_table / svc_fwm_table.
332  *      Should be called with locked tables.
333  */
334 static int ip_vs_svc_unhash(struct ip_vs_service *svc)
335 {
336         if (!(svc->flags & IP_VS_SVC_F_HASHED)) {
337                 pr_err("%s(): request for unhash flagged, called from %pF\n",
338                        __func__, __builtin_return_address(0));
339                 return 0;
340         }
341
342         if (svc->fwmark == 0) {
343                 /* Remove it from the svc_table table */
344                 hlist_del_rcu(&svc->s_list);
345         } else {
346                 /* Remove it from the svc_fwm_table table */
347                 hlist_del_rcu(&svc->f_list);
348         }
349
350         svc->flags &= ~IP_VS_SVC_F_HASHED;
351         atomic_dec(&svc->refcnt);
352         return 1;
353 }
354
355
356 /*
357  *      Get service by {netns, proto,addr,port} in the service table.
358  */
359 static inline struct ip_vs_service *
360 __ip_vs_service_find(struct net *net, int af, __u16 protocol,
361                      const union nf_inet_addr *vaddr, __be16 vport)
362 {
363         unsigned int hash;
364         struct ip_vs_service *svc;
365
366         /* Check for "full" addressed entries */
367         hash = ip_vs_svc_hashkey(net, af, protocol, vaddr, vport);
368
369         hlist_for_each_entry_rcu(svc, &ip_vs_svc_table[hash], s_list) {
370                 if ((svc->af == af)
371                     && ip_vs_addr_equal(af, &svc->addr, vaddr)
372                     && (svc->port == vport)
373                     && (svc->protocol == protocol)
374                     && net_eq(svc->net, net)) {
375                         /* HIT */
376                         return svc;
377                 }
378         }
379
380         return NULL;
381 }
382
383
384 /*
385  *      Get service by {fwmark} in the service table.
386  */
387 static inline struct ip_vs_service *
388 __ip_vs_svc_fwm_find(struct net *net, int af, __u32 fwmark)
389 {
390         unsigned int hash;
391         struct ip_vs_service *svc;
392
393         /* Check for fwmark addressed entries */
394         hash = ip_vs_svc_fwm_hashkey(net, fwmark);
395
396         hlist_for_each_entry_rcu(svc, &ip_vs_svc_fwm_table[hash], f_list) {
397                 if (svc->fwmark == fwmark && svc->af == af
398                     && net_eq(svc->net, net)) {
399                         /* HIT */
400                         return svc;
401                 }
402         }
403
404         return NULL;
405 }
406
407 /* Find service, called under RCU lock */
408 struct ip_vs_service *
409 ip_vs_service_find(struct net *net, int af, __u32 fwmark, __u16 protocol,
410                    const union nf_inet_addr *vaddr, __be16 vport)
411 {
412         struct ip_vs_service *svc;
413         struct netns_ipvs *ipvs = net_ipvs(net);
414
415         /*
416          *      Check the table hashed by fwmark first
417          */
418         if (fwmark) {
419                 svc = __ip_vs_svc_fwm_find(net, af, fwmark);
420                 if (svc)
421                         goto out;
422         }
423
424         /*
425          *      Check the table hashed by <protocol,addr,port>
426          *      for "full" addressed entries
427          */
428         svc = __ip_vs_service_find(net, af, protocol, vaddr, vport);
429
430         if (svc == NULL
431             && protocol == IPPROTO_TCP
432             && atomic_read(&ipvs->ftpsvc_counter)
433             && (vport == FTPDATA || ntohs(vport) >= PROT_SOCK)) {
434                 /*
435                  * Check if ftp service entry exists, the packet
436                  * might belong to FTP data connections.
437                  */
438                 svc = __ip_vs_service_find(net, af, protocol, vaddr, FTPPORT);
439         }
440
441         if (svc == NULL
442             && atomic_read(&ipvs->nullsvc_counter)) {
443                 /*
444                  * Check if the catch-all port (port zero) exists
445                  */
446                 svc = __ip_vs_service_find(net, af, protocol, vaddr, 0);
447         }
448
449   out:
450         IP_VS_DBG_BUF(9, "lookup service: fwm %u %s %s:%u %s\n",
451                       fwmark, ip_vs_proto_name(protocol),
452                       IP_VS_DBG_ADDR(af, vaddr), ntohs(vport),
453                       svc ? "hit" : "not hit");
454
455         return svc;
456 }
457
458
459 static inline void
460 __ip_vs_bind_svc(struct ip_vs_dest *dest, struct ip_vs_service *svc)
461 {
462         atomic_inc(&svc->refcnt);
463         rcu_assign_pointer(dest->svc, svc);
464 }
465
466 static void ip_vs_service_free(struct ip_vs_service *svc)
467 {
468         free_percpu(svc->stats.cpustats);
469         kfree(svc);
470 }
471
472 static void ip_vs_service_rcu_free(struct rcu_head *head)
473 {
474         struct ip_vs_service *svc;
475
476         svc = container_of(head, struct ip_vs_service, rcu_head);
477         ip_vs_service_free(svc);
478 }
479
480 static void __ip_vs_svc_put(struct ip_vs_service *svc, bool do_delay)
481 {
482         if (atomic_dec_and_test(&svc->refcnt)) {
483                 IP_VS_DBG_BUF(3, "Removing service %u/%s:%u\n",
484                               svc->fwmark,
485                               IP_VS_DBG_ADDR(svc->af, &svc->addr),
486                               ntohs(svc->port));
487                 if (do_delay)
488                         call_rcu(&svc->rcu_head, ip_vs_service_rcu_free);
489                 else
490                         ip_vs_service_free(svc);
491         }
492 }
493
494
495 /*
496  *      Returns hash value for real service
497  */
498 static inline unsigned int ip_vs_rs_hashkey(int af,
499                                             const union nf_inet_addr *addr,
500                                             __be16 port)
501 {
502         register unsigned int porth = ntohs(port);
503         __be32 addr_fold = addr->ip;
504
505 #ifdef CONFIG_IP_VS_IPV6
506         if (af == AF_INET6)
507                 addr_fold = addr->ip6[0]^addr->ip6[1]^
508                             addr->ip6[2]^addr->ip6[3];
509 #endif
510
511         return (ntohl(addr_fold)^(porth>>IP_VS_RTAB_BITS)^porth)
512                 & IP_VS_RTAB_MASK;
513 }
514
515 /* Hash ip_vs_dest in rs_table by <proto,addr,port>. */
516 static void ip_vs_rs_hash(struct netns_ipvs *ipvs, struct ip_vs_dest *dest)
517 {
518         unsigned int hash;
519
520         if (dest->in_rs_table)
521                 return;
522
523         /*
524          *      Hash by proto,addr,port,
525          *      which are the parameters of the real service.
526          */
527         hash = ip_vs_rs_hashkey(dest->af, &dest->addr, dest->port);
528
529         hlist_add_head_rcu(&dest->d_list, &ipvs->rs_table[hash]);
530         dest->in_rs_table = 1;
531 }
532
533 /* Unhash ip_vs_dest from rs_table. */
534 static void ip_vs_rs_unhash(struct ip_vs_dest *dest)
535 {
536         /*
537          * Remove it from the rs_table table.
538          */
539         if (dest->in_rs_table) {
540                 hlist_del_rcu(&dest->d_list);
541                 dest->in_rs_table = 0;
542         }
543 }
544
545 /* Check if real service by <proto,addr,port> is present */
546 bool ip_vs_has_real_service(struct net *net, int af, __u16 protocol,
547                             const union nf_inet_addr *daddr, __be16 dport)
548 {
549         struct netns_ipvs *ipvs = net_ipvs(net);
550         unsigned int hash;
551         struct ip_vs_dest *dest;
552
553         /* Check for "full" addressed entries */
554         hash = ip_vs_rs_hashkey(af, daddr, dport);
555
556         rcu_read_lock();
557         hlist_for_each_entry_rcu(dest, &ipvs->rs_table[hash], d_list) {
558                 if (dest->port == dport &&
559                     dest->af == af &&
560                     ip_vs_addr_equal(af, &dest->addr, daddr) &&
561                     (dest->protocol == protocol || dest->vfwmark)) {
562                         /* HIT */
563                         rcu_read_unlock();
564                         return true;
565                 }
566         }
567         rcu_read_unlock();
568
569         return false;
570 }
571
572 /* Lookup destination by {addr,port} in the given service
573  * Called under RCU lock.
574  */
575 static struct ip_vs_dest *
576 ip_vs_lookup_dest(struct ip_vs_service *svc, int dest_af,
577                   const union nf_inet_addr *daddr, __be16 dport)
578 {
579         struct ip_vs_dest *dest;
580
581         /*
582          * Find the destination for the given service
583          */
584         list_for_each_entry_rcu(dest, &svc->destinations, n_list) {
585                 if ((dest->af == dest_af) &&
586                     ip_vs_addr_equal(dest_af, &dest->addr, daddr) &&
587                     (dest->port == dport)) {
588                         /* HIT */
589                         return dest;
590                 }
591         }
592
593         return NULL;
594 }
595
596 /*
597  * Find destination by {daddr,dport,vaddr,protocol}
598  * Created to be used in ip_vs_process_message() in
599  * the backup synchronization daemon. It finds the
600  * destination to be bound to the received connection
601  * on the backup.
602  * Called under RCU lock, no refcnt is returned.
603  */
604 struct ip_vs_dest *ip_vs_find_dest(struct net  *net, int svc_af, int dest_af,
605                                    const union nf_inet_addr *daddr,
606                                    __be16 dport,
607                                    const union nf_inet_addr *vaddr,
608                                    __be16 vport, __u16 protocol, __u32 fwmark,
609                                    __u32 flags)
610 {
611         struct ip_vs_dest *dest;
612         struct ip_vs_service *svc;
613         __be16 port = dport;
614
615         svc = ip_vs_service_find(net, svc_af, fwmark, protocol, vaddr, vport);
616         if (!svc)
617                 return NULL;
618         if (fwmark && (flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_CONN_F_MASQ)
619                 port = 0;
620         dest = ip_vs_lookup_dest(svc, dest_af, daddr, port);
621         if (!dest)
622                 dest = ip_vs_lookup_dest(svc, dest_af, daddr, port ^ dport);
623         return dest;
624 }
625
626 void ip_vs_dest_dst_rcu_free(struct rcu_head *head)
627 {
628         struct ip_vs_dest_dst *dest_dst = container_of(head,
629                                                        struct ip_vs_dest_dst,
630                                                        rcu_head);
631
632         dst_release(dest_dst->dst_cache);
633         kfree(dest_dst);
634 }
635
636 /* Release dest_dst and dst_cache for dest in user context */
637 static void __ip_vs_dst_cache_reset(struct ip_vs_dest *dest)
638 {
639         struct ip_vs_dest_dst *old;
640
641         old = rcu_dereference_protected(dest->dest_dst, 1);
642         if (old) {
643                 RCU_INIT_POINTER(dest->dest_dst, NULL);
644                 call_rcu(&old->rcu_head, ip_vs_dest_dst_rcu_free);
645         }
646 }
647
648 /*
649  *  Lookup dest by {svc,addr,port} in the destination trash.
650  *  The destination trash is used to hold the destinations that are removed
651  *  from the service table but are still referenced by some conn entries.
652  *  The reason to add the destination trash is when the dest is temporary
653  *  down (either by administrator or by monitor program), the dest can be
654  *  picked back from the trash, the remaining connections to the dest can
655  *  continue, and the counting information of the dest is also useful for
656  *  scheduling.
657  */
658 static struct ip_vs_dest *
659 ip_vs_trash_get_dest(struct ip_vs_service *svc, int dest_af,
660                      const union nf_inet_addr *daddr, __be16 dport)
661 {
662         struct ip_vs_dest *dest;
663         struct netns_ipvs *ipvs = net_ipvs(svc->net);
664
665         /*
666          * Find the destination in trash
667          */
668         spin_lock_bh(&ipvs->dest_trash_lock);
669         list_for_each_entry(dest, &ipvs->dest_trash, t_list) {
670                 IP_VS_DBG_BUF(3, "Destination %u/%s:%u still in trash, "
671                               "dest->refcnt=%d\n",
672                               dest->vfwmark,
673                               IP_VS_DBG_ADDR(dest->af, &dest->addr),
674                               ntohs(dest->port),
675                               atomic_read(&dest->refcnt));
676                 if (dest->af == dest_af &&
677                     ip_vs_addr_equal(dest_af, &dest->addr, daddr) &&
678                     dest->port == dport &&
679                     dest->vfwmark == svc->fwmark &&
680                     dest->protocol == svc->protocol &&
681                     (svc->fwmark ||
682                      (ip_vs_addr_equal(svc->af, &dest->vaddr, &svc->addr) &&
683                       dest->vport == svc->port))) {
684                         /* HIT */
685                         list_del(&dest->t_list);
686                         ip_vs_dest_hold(dest);
687                         goto out;
688                 }
689         }
690
691         dest = NULL;
692
693 out:
694         spin_unlock_bh(&ipvs->dest_trash_lock);
695
696         return dest;
697 }
698
699 static void ip_vs_dest_free(struct ip_vs_dest *dest)
700 {
701         struct ip_vs_service *svc = rcu_dereference_protected(dest->svc, 1);
702
703         __ip_vs_dst_cache_reset(dest);
704         __ip_vs_svc_put(svc, false);
705         free_percpu(dest->stats.cpustats);
706         ip_vs_dest_put_and_free(dest);
707 }
708
709 /*
710  *  Clean up all the destinations in the trash
711  *  Called by the ip_vs_control_cleanup()
712  *
713  *  When the ip_vs_control_clearup is activated by ipvs module exit,
714  *  the service tables must have been flushed and all the connections
715  *  are expired, and the refcnt of each destination in the trash must
716  *  be 0, so we simply release them here.
717  */
718 static void ip_vs_trash_cleanup(struct net *net)
719 {
720         struct ip_vs_dest *dest, *nxt;
721         struct netns_ipvs *ipvs = net_ipvs(net);
722
723         del_timer_sync(&ipvs->dest_trash_timer);
724         /* No need to use dest_trash_lock */
725         list_for_each_entry_safe(dest, nxt, &ipvs->dest_trash, t_list) {
726                 list_del(&dest->t_list);
727                 ip_vs_dest_free(dest);
728         }
729 }
730
731 static void
732 ip_vs_copy_stats(struct ip_vs_stats_user *dst, struct ip_vs_stats *src)
733 {
734 #define IP_VS_SHOW_STATS_COUNTER(c) dst->c = src->ustats.c - src->ustats0.c
735
736         spin_lock_bh(&src->lock);
737
738         IP_VS_SHOW_STATS_COUNTER(conns);
739         IP_VS_SHOW_STATS_COUNTER(inpkts);
740         IP_VS_SHOW_STATS_COUNTER(outpkts);
741         IP_VS_SHOW_STATS_COUNTER(inbytes);
742         IP_VS_SHOW_STATS_COUNTER(outbytes);
743
744         ip_vs_read_estimator(dst, src);
745
746         spin_unlock_bh(&src->lock);
747 }
748
749 static void
750 ip_vs_zero_stats(struct ip_vs_stats *stats)
751 {
752         spin_lock_bh(&stats->lock);
753
754         /* get current counters as zero point, rates are zeroed */
755
756 #define IP_VS_ZERO_STATS_COUNTER(c) stats->ustats0.c = stats->ustats.c
757
758         IP_VS_ZERO_STATS_COUNTER(conns);
759         IP_VS_ZERO_STATS_COUNTER(inpkts);
760         IP_VS_ZERO_STATS_COUNTER(outpkts);
761         IP_VS_ZERO_STATS_COUNTER(inbytes);
762         IP_VS_ZERO_STATS_COUNTER(outbytes);
763
764         ip_vs_zero_estimator(stats);
765
766         spin_unlock_bh(&stats->lock);
767 }
768
769 /*
770  *      Update a destination in the given service
771  */
772 static void
773 __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest,
774                     struct ip_vs_dest_user_kern *udest, int add)
775 {
776         struct netns_ipvs *ipvs = net_ipvs(svc->net);
777         struct ip_vs_service *old_svc;
778         struct ip_vs_scheduler *sched;
779         int conn_flags;
780
781         /* We cannot modify an address and change the address family */
782         BUG_ON(!add && udest->af != dest->af);
783
784         if (add && udest->af != svc->af)
785                 ipvs->mixed_address_family_dests++;
786
787         /* set the weight and the flags */
788         atomic_set(&dest->weight, udest->weight);
789         conn_flags = udest->conn_flags & IP_VS_CONN_F_DEST_MASK;
790         conn_flags |= IP_VS_CONN_F_INACTIVE;
791
792         /* set the IP_VS_CONN_F_NOOUTPUT flag if not masquerading/NAT */
793         if ((conn_flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_CONN_F_MASQ) {
794                 conn_flags |= IP_VS_CONN_F_NOOUTPUT;
795         } else {
796                 /*
797                  *    Put the real service in rs_table if not present.
798                  *    For now only for NAT!
799                  */
800                 ip_vs_rs_hash(ipvs, dest);
801         }
802         atomic_set(&dest->conn_flags, conn_flags);
803
804         /* bind the service */
805         old_svc = rcu_dereference_protected(dest->svc, 1);
806         if (!old_svc) {
807                 __ip_vs_bind_svc(dest, svc);
808         } else {
809                 if (old_svc != svc) {
810                         ip_vs_zero_stats(&dest->stats);
811                         __ip_vs_bind_svc(dest, svc);
812                         __ip_vs_svc_put(old_svc, true);
813                 }
814         }
815
816         /* set the dest status flags */
817         dest->flags |= IP_VS_DEST_F_AVAILABLE;
818
819         if (udest->u_threshold == 0 || udest->u_threshold > dest->u_threshold)
820                 dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
821         dest->u_threshold = udest->u_threshold;
822         dest->l_threshold = udest->l_threshold;
823
824         dest->af = udest->af;
825
826         spin_lock_bh(&dest->dst_lock);
827         __ip_vs_dst_cache_reset(dest);
828         spin_unlock_bh(&dest->dst_lock);
829
830         sched = rcu_dereference_protected(svc->scheduler, 1);
831         if (add) {
832                 ip_vs_start_estimator(svc->net, &dest->stats);
833                 list_add_rcu(&dest->n_list, &svc->destinations);
834                 svc->num_dests++;
835                 if (sched->add_dest)
836                         sched->add_dest(svc, dest);
837         } else {
838                 if (sched->upd_dest)
839                         sched->upd_dest(svc, dest);
840         }
841 }
842
843
844 /*
845  *      Create a destination for the given service
846  */
847 static int
848 ip_vs_new_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest,
849                struct ip_vs_dest **dest_p)
850 {
851         struct ip_vs_dest *dest;
852         unsigned int atype, i;
853
854         EnterFunction(2);
855
856 #ifdef CONFIG_IP_VS_IPV6
857         if (udest->af == AF_INET6) {
858                 atype = ipv6_addr_type(&udest->addr.in6);
859                 if ((!(atype & IPV6_ADDR_UNICAST) ||
860                         atype & IPV6_ADDR_LINKLOCAL) &&
861                         !__ip_vs_addr_is_local_v6(svc->net, &udest->addr.in6))
862                         return -EINVAL;
863         } else
864 #endif
865         {
866                 atype = inet_addr_type(svc->net, udest->addr.ip);
867                 if (atype != RTN_LOCAL && atype != RTN_UNICAST)
868                         return -EINVAL;
869         }
870
871         dest = kzalloc(sizeof(struct ip_vs_dest), GFP_KERNEL);
872         if (dest == NULL)
873                 return -ENOMEM;
874
875         dest->stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
876         if (!dest->stats.cpustats)
877                 goto err_alloc;
878
879         for_each_possible_cpu(i) {
880                 struct ip_vs_cpu_stats *ip_vs_dest_stats;
881                 ip_vs_dest_stats = per_cpu_ptr(dest->stats.cpustats, i);
882                 u64_stats_init(&ip_vs_dest_stats->syncp);
883         }
884
885         dest->af = udest->af;
886         dest->protocol = svc->protocol;
887         dest->vaddr = svc->addr;
888         dest->vport = svc->port;
889         dest->vfwmark = svc->fwmark;
890         ip_vs_addr_copy(udest->af, &dest->addr, &udest->addr);
891         dest->port = udest->port;
892
893         atomic_set(&dest->activeconns, 0);
894         atomic_set(&dest->inactconns, 0);
895         atomic_set(&dest->persistconns, 0);
896         atomic_set(&dest->refcnt, 1);
897
898         INIT_HLIST_NODE(&dest->d_list);
899         spin_lock_init(&dest->dst_lock);
900         spin_lock_init(&dest->stats.lock);
901         __ip_vs_update_dest(svc, dest, udest, 1);
902
903         *dest_p = dest;
904
905         LeaveFunction(2);
906         return 0;
907
908 err_alloc:
909         kfree(dest);
910         return -ENOMEM;
911 }
912
913
914 /*
915  *      Add a destination into an existing service
916  */
917 static int
918 ip_vs_add_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
919 {
920         struct ip_vs_dest *dest;
921         union nf_inet_addr daddr;
922         __be16 dport = udest->port;
923         int ret;
924
925         EnterFunction(2);
926
927         if (udest->weight < 0) {
928                 pr_err("%s(): server weight less than zero\n", __func__);
929                 return -ERANGE;
930         }
931
932         if (udest->l_threshold > udest->u_threshold) {
933                 pr_err("%s(): lower threshold is higher than upper threshold\n",
934                         __func__);
935                 return -ERANGE;
936         }
937
938         ip_vs_addr_copy(udest->af, &daddr, &udest->addr);
939
940         /* We use function that requires RCU lock */
941         rcu_read_lock();
942         dest = ip_vs_lookup_dest(svc, udest->af, &daddr, dport);
943         rcu_read_unlock();
944
945         if (dest != NULL) {
946                 IP_VS_DBG(1, "%s(): dest already exists\n", __func__);
947                 return -EEXIST;
948         }
949
950         /*
951          * Check if the dest already exists in the trash and
952          * is from the same service
953          */
954         dest = ip_vs_trash_get_dest(svc, udest->af, &daddr, dport);
955
956         if (dest != NULL) {
957                 IP_VS_DBG_BUF(3, "Get destination %s:%u from trash, "
958                               "dest->refcnt=%d, service %u/%s:%u\n",
959                               IP_VS_DBG_ADDR(udest->af, &daddr), ntohs(dport),
960                               atomic_read(&dest->refcnt),
961                               dest->vfwmark,
962                               IP_VS_DBG_ADDR(svc->af, &dest->vaddr),
963                               ntohs(dest->vport));
964
965                 __ip_vs_update_dest(svc, dest, udest, 1);
966                 ret = 0;
967         } else {
968                 /*
969                  * Allocate and initialize the dest structure
970                  */
971                 ret = ip_vs_new_dest(svc, udest, &dest);
972         }
973         LeaveFunction(2);
974
975         return ret;
976 }
977
978
979 /*
980  *      Edit a destination in the given service
981  */
982 static int
983 ip_vs_edit_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
984 {
985         struct ip_vs_dest *dest;
986         union nf_inet_addr daddr;
987         __be16 dport = udest->port;
988
989         EnterFunction(2);
990
991         if (udest->weight < 0) {
992                 pr_err("%s(): server weight less than zero\n", __func__);
993                 return -ERANGE;
994         }
995
996         if (udest->l_threshold > udest->u_threshold) {
997                 pr_err("%s(): lower threshold is higher than upper threshold\n",
998                         __func__);
999                 return -ERANGE;
1000         }
1001
1002         ip_vs_addr_copy(udest->af, &daddr, &udest->addr);
1003
1004         /* We use function that requires RCU lock */
1005         rcu_read_lock();
1006         dest = ip_vs_lookup_dest(svc, udest->af, &daddr, dport);
1007         rcu_read_unlock();
1008
1009         if (dest == NULL) {
1010                 IP_VS_DBG(1, "%s(): dest doesn't exist\n", __func__);
1011                 return -ENOENT;
1012         }
1013
1014         __ip_vs_update_dest(svc, dest, udest, 0);
1015         LeaveFunction(2);
1016
1017         return 0;
1018 }
1019
1020 /*
1021  *      Delete a destination (must be already unlinked from the service)
1022  */
1023 static void __ip_vs_del_dest(struct net *net, struct ip_vs_dest *dest,
1024                              bool cleanup)
1025 {
1026         struct netns_ipvs *ipvs = net_ipvs(net);
1027
1028         ip_vs_stop_estimator(net, &dest->stats);
1029
1030         /*
1031          *  Remove it from the d-linked list with the real services.
1032          */
1033         ip_vs_rs_unhash(dest);
1034
1035         spin_lock_bh(&ipvs->dest_trash_lock);
1036         IP_VS_DBG_BUF(3, "Moving dest %s:%u into trash, dest->refcnt=%d\n",
1037                       IP_VS_DBG_ADDR(dest->af, &dest->addr), ntohs(dest->port),
1038                       atomic_read(&dest->refcnt));
1039         if (list_empty(&ipvs->dest_trash) && !cleanup)
1040                 mod_timer(&ipvs->dest_trash_timer,
1041                           jiffies + (IP_VS_DEST_TRASH_PERIOD >> 1));
1042         /* dest lives in trash without reference */
1043         list_add(&dest->t_list, &ipvs->dest_trash);
1044         dest->idle_start = 0;
1045         spin_unlock_bh(&ipvs->dest_trash_lock);
1046         ip_vs_dest_put(dest);
1047 }
1048
1049
1050 /*
1051  *      Unlink a destination from the given service
1052  */
1053 static void __ip_vs_unlink_dest(struct ip_vs_service *svc,
1054                                 struct ip_vs_dest *dest,
1055                                 int svcupd)
1056 {
1057         dest->flags &= ~IP_VS_DEST_F_AVAILABLE;
1058
1059         /*
1060          *  Remove it from the d-linked destination list.
1061          */
1062         list_del_rcu(&dest->n_list);
1063         svc->num_dests--;
1064
1065         if (dest->af != svc->af)
1066                 net_ipvs(svc->net)->mixed_address_family_dests--;
1067
1068         if (svcupd) {
1069                 struct ip_vs_scheduler *sched;
1070
1071                 sched = rcu_dereference_protected(svc->scheduler, 1);
1072                 if (sched->del_dest)
1073                         sched->del_dest(svc, dest);
1074         }
1075 }
1076
1077
1078 /*
1079  *      Delete a destination server in the given service
1080  */
1081 static int
1082 ip_vs_del_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
1083 {
1084         struct ip_vs_dest *dest;
1085         __be16 dport = udest->port;
1086
1087         EnterFunction(2);
1088
1089         /* We use function that requires RCU lock */
1090         rcu_read_lock();
1091         dest = ip_vs_lookup_dest(svc, udest->af, &udest->addr, dport);
1092         rcu_read_unlock();
1093
1094         if (dest == NULL) {
1095                 IP_VS_DBG(1, "%s(): destination not found!\n", __func__);
1096                 return -ENOENT;
1097         }
1098
1099         /*
1100          *      Unlink dest from the service
1101          */
1102         __ip_vs_unlink_dest(svc, dest, 1);
1103
1104         /*
1105          *      Delete the destination
1106          */
1107         __ip_vs_del_dest(svc->net, dest, false);
1108
1109         LeaveFunction(2);
1110
1111         return 0;
1112 }
1113
1114 static void ip_vs_dest_trash_expire(unsigned long data)
1115 {
1116         struct net *net = (struct net *) data;
1117         struct netns_ipvs *ipvs = net_ipvs(net);
1118         struct ip_vs_dest *dest, *next;
1119         unsigned long now = jiffies;
1120
1121         spin_lock(&ipvs->dest_trash_lock);
1122         list_for_each_entry_safe(dest, next, &ipvs->dest_trash, t_list) {
1123                 if (atomic_read(&dest->refcnt) > 0)
1124                         continue;
1125                 if (dest->idle_start) {
1126                         if (time_before(now, dest->idle_start +
1127                                              IP_VS_DEST_TRASH_PERIOD))
1128                                 continue;
1129                 } else {
1130                         dest->idle_start = max(1UL, now);
1131                         continue;
1132                 }
1133                 IP_VS_DBG_BUF(3, "Removing destination %u/%s:%u from trash\n",
1134                               dest->vfwmark,
1135                               IP_VS_DBG_ADDR(dest->af, &dest->addr),
1136                               ntohs(dest->port));
1137                 list_del(&dest->t_list);
1138                 ip_vs_dest_free(dest);
1139         }
1140         if (!list_empty(&ipvs->dest_trash))
1141                 mod_timer(&ipvs->dest_trash_timer,
1142                           jiffies + (IP_VS_DEST_TRASH_PERIOD >> 1));
1143         spin_unlock(&ipvs->dest_trash_lock);
1144 }
1145
1146 /*
1147  *      Add a service into the service hash table
1148  */
1149 static int
1150 ip_vs_add_service(struct net *net, struct ip_vs_service_user_kern *u,
1151                   struct ip_vs_service **svc_p)
1152 {
1153         int ret = 0, i;
1154         struct ip_vs_scheduler *sched = NULL;
1155         struct ip_vs_pe *pe = NULL;
1156         struct ip_vs_service *svc = NULL;
1157         struct netns_ipvs *ipvs = net_ipvs(net);
1158
1159         /* increase the module use count */
1160         ip_vs_use_count_inc();
1161
1162         /* Lookup the scheduler by 'u->sched_name' */
1163         sched = ip_vs_scheduler_get(u->sched_name);
1164         if (sched == NULL) {
1165                 pr_info("Scheduler module ip_vs_%s not found\n", u->sched_name);
1166                 ret = -ENOENT;
1167                 goto out_err;
1168         }
1169
1170         if (u->pe_name && *u->pe_name) {
1171                 pe = ip_vs_pe_getbyname(u->pe_name);
1172                 if (pe == NULL) {
1173                         pr_info("persistence engine module ip_vs_pe_%s "
1174                                 "not found\n", u->pe_name);
1175                         ret = -ENOENT;
1176                         goto out_err;
1177                 }
1178         }
1179
1180 #ifdef CONFIG_IP_VS_IPV6
1181         if (u->af == AF_INET6) {
1182                 __u32 plen = (__force __u32) u->netmask;
1183
1184                 if (plen < 1 || plen > 128) {
1185                         ret = -EINVAL;
1186                         goto out_err;
1187                 }
1188         }
1189 #endif
1190
1191         svc = kzalloc(sizeof(struct ip_vs_service), GFP_KERNEL);
1192         if (svc == NULL) {
1193                 IP_VS_DBG(1, "%s(): no memory\n", __func__);
1194                 ret = -ENOMEM;
1195                 goto out_err;
1196         }
1197         svc->stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
1198         if (!svc->stats.cpustats) {
1199                 ret = -ENOMEM;
1200                 goto out_err;
1201         }
1202
1203         for_each_possible_cpu(i) {
1204                 struct ip_vs_cpu_stats *ip_vs_stats;
1205                 ip_vs_stats = per_cpu_ptr(svc->stats.cpustats, i);
1206                 u64_stats_init(&ip_vs_stats->syncp);
1207         }
1208
1209
1210         /* I'm the first user of the service */
1211         atomic_set(&svc->refcnt, 0);
1212
1213         svc->af = u->af;
1214         svc->protocol = u->protocol;
1215         ip_vs_addr_copy(svc->af, &svc->addr, &u->addr);
1216         svc->port = u->port;
1217         svc->fwmark = u->fwmark;
1218         svc->flags = u->flags;
1219         svc->timeout = u->timeout * HZ;
1220         svc->netmask = u->netmask;
1221         svc->net = net;
1222
1223         INIT_LIST_HEAD(&svc->destinations);
1224         spin_lock_init(&svc->sched_lock);
1225         spin_lock_init(&svc->stats.lock);
1226
1227         /* Bind the scheduler */
1228         ret = ip_vs_bind_scheduler(svc, sched);
1229         if (ret)
1230                 goto out_err;
1231         sched = NULL;
1232
1233         /* Bind the ct retriever */
1234         RCU_INIT_POINTER(svc->pe, pe);
1235         pe = NULL;
1236
1237         /* Update the virtual service counters */
1238         if (svc->port == FTPPORT)
1239                 atomic_inc(&ipvs->ftpsvc_counter);
1240         else if (svc->port == 0)
1241                 atomic_inc(&ipvs->nullsvc_counter);
1242
1243         ip_vs_start_estimator(net, &svc->stats);
1244
1245         /* Count only IPv4 services for old get/setsockopt interface */
1246         if (svc->af == AF_INET)
1247                 ipvs->num_services++;
1248
1249         /* Hash the service into the service table */
1250         ip_vs_svc_hash(svc);
1251
1252         *svc_p = svc;
1253         /* Now there is a service - full throttle */
1254         ipvs->enable = 1;
1255         return 0;
1256
1257
1258  out_err:
1259         if (svc != NULL) {
1260                 ip_vs_unbind_scheduler(svc, sched);
1261                 ip_vs_service_free(svc);
1262         }
1263         ip_vs_scheduler_put(sched);
1264         ip_vs_pe_put(pe);
1265
1266         /* decrease the module use count */
1267         ip_vs_use_count_dec();
1268
1269         return ret;
1270 }
1271
1272
1273 /*
1274  *      Edit a service and bind it with a new scheduler
1275  */
1276 static int
1277 ip_vs_edit_service(struct ip_vs_service *svc, struct ip_vs_service_user_kern *u)
1278 {
1279         struct ip_vs_scheduler *sched, *old_sched;
1280         struct ip_vs_pe *pe = NULL, *old_pe = NULL;
1281         int ret = 0;
1282
1283         /*
1284          * Lookup the scheduler, by 'u->sched_name'
1285          */
1286         sched = ip_vs_scheduler_get(u->sched_name);
1287         if (sched == NULL) {
1288                 pr_info("Scheduler module ip_vs_%s not found\n", u->sched_name);
1289                 return -ENOENT;
1290         }
1291         old_sched = sched;
1292
1293         if (u->pe_name && *u->pe_name) {
1294                 pe = ip_vs_pe_getbyname(u->pe_name);
1295                 if (pe == NULL) {
1296                         pr_info("persistence engine module ip_vs_pe_%s "
1297                                 "not found\n", u->pe_name);
1298                         ret = -ENOENT;
1299                         goto out;
1300                 }
1301                 old_pe = pe;
1302         }
1303
1304 #ifdef CONFIG_IP_VS_IPV6
1305         if (u->af == AF_INET6) {
1306                 __u32 plen = (__force __u32) u->netmask;
1307
1308                 if (plen < 1 || plen > 128) {
1309                         ret = -EINVAL;
1310                         goto out;
1311                 }
1312         }
1313 #endif
1314
1315         old_sched = rcu_dereference_protected(svc->scheduler, 1);
1316         if (sched != old_sched) {
1317                 /* Bind the new scheduler */
1318                 ret = ip_vs_bind_scheduler(svc, sched);
1319                 if (ret) {
1320                         old_sched = sched;
1321                         goto out;
1322                 }
1323                 /* Unbind the old scheduler on success */
1324                 ip_vs_unbind_scheduler(svc, old_sched);
1325         }
1326
1327         /*
1328          * Set the flags and timeout value
1329          */
1330         svc->flags = u->flags | IP_VS_SVC_F_HASHED;
1331         svc->timeout = u->timeout * HZ;
1332         svc->netmask = u->netmask;
1333
1334         old_pe = rcu_dereference_protected(svc->pe, 1);
1335         if (pe != old_pe)
1336                 rcu_assign_pointer(svc->pe, pe);
1337
1338 out:
1339         ip_vs_scheduler_put(old_sched);
1340         ip_vs_pe_put(old_pe);
1341         return ret;
1342 }
1343
1344 /*
1345  *      Delete a service from the service list
1346  *      - The service must be unlinked, unlocked and not referenced!
1347  *      - We are called under _bh lock
1348  */
1349 static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup)
1350 {
1351         struct ip_vs_dest *dest, *nxt;
1352         struct ip_vs_scheduler *old_sched;
1353         struct ip_vs_pe *old_pe;
1354         struct netns_ipvs *ipvs = net_ipvs(svc->net);
1355
1356         pr_info("%s: enter\n", __func__);
1357
1358         /* Count only IPv4 services for old get/setsockopt interface */
1359         if (svc->af == AF_INET)
1360                 ipvs->num_services--;
1361
1362         ip_vs_stop_estimator(svc->net, &svc->stats);
1363
1364         /* Unbind scheduler */
1365         old_sched = rcu_dereference_protected(svc->scheduler, 1);
1366         ip_vs_unbind_scheduler(svc, old_sched);
1367         ip_vs_scheduler_put(old_sched);
1368
1369         /* Unbind persistence engine, keep svc->pe */
1370         old_pe = rcu_dereference_protected(svc->pe, 1);
1371         ip_vs_pe_put(old_pe);
1372
1373         /*
1374          *    Unlink the whole destination list
1375          */
1376         list_for_each_entry_safe(dest, nxt, &svc->destinations, n_list) {
1377                 __ip_vs_unlink_dest(svc, dest, 0);
1378                 __ip_vs_del_dest(svc->net, dest, cleanup);
1379         }
1380
1381         /*
1382          *    Update the virtual service counters
1383          */
1384         if (svc->port == FTPPORT)
1385                 atomic_dec(&ipvs->ftpsvc_counter);
1386         else if (svc->port == 0)
1387                 atomic_dec(&ipvs->nullsvc_counter);
1388
1389         /*
1390          *    Free the service if nobody refers to it
1391          */
1392         __ip_vs_svc_put(svc, true);
1393
1394         /* decrease the module use count */
1395         ip_vs_use_count_dec();
1396 }
1397
1398 /*
1399  * Unlink a service from list and try to delete it if its refcnt reached 0
1400  */
1401 static void ip_vs_unlink_service(struct ip_vs_service *svc, bool cleanup)
1402 {
1403         /* Hold svc to avoid double release from dest_trash */
1404         atomic_inc(&svc->refcnt);
1405         /*
1406          * Unhash it from the service table
1407          */
1408         ip_vs_svc_unhash(svc);
1409
1410         __ip_vs_del_service(svc, cleanup);
1411 }
1412
1413 /*
1414  *      Delete a service from the service list
1415  */
1416 static int ip_vs_del_service(struct ip_vs_service *svc)
1417 {
1418         if (svc == NULL)
1419                 return -EEXIST;
1420         ip_vs_unlink_service(svc, false);
1421
1422         return 0;
1423 }
1424
1425
1426 /*
1427  *      Flush all the virtual services
1428  */
1429 static int ip_vs_flush(struct net *net, bool cleanup)
1430 {
1431         int idx;
1432         struct ip_vs_service *svc;
1433         struct hlist_node *n;
1434
1435         /*
1436          * Flush the service table hashed by <netns,protocol,addr,port>
1437          */
1438         for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1439                 hlist_for_each_entry_safe(svc, n, &ip_vs_svc_table[idx],
1440                                           s_list) {
1441                         if (net_eq(svc->net, net))
1442                                 ip_vs_unlink_service(svc, cleanup);
1443                 }
1444         }
1445
1446         /*
1447          * Flush the service table hashed by fwmark
1448          */
1449         for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1450                 hlist_for_each_entry_safe(svc, n, &ip_vs_svc_fwm_table[idx],
1451                                           f_list) {
1452                         if (net_eq(svc->net, net))
1453                                 ip_vs_unlink_service(svc, cleanup);
1454                 }
1455         }
1456
1457         return 0;
1458 }
1459
1460 /*
1461  *      Delete service by {netns} in the service table.
1462  *      Called by __ip_vs_cleanup()
1463  */
1464 void ip_vs_service_net_cleanup(struct net *net)
1465 {
1466         EnterFunction(2);
1467         /* Check for "full" addressed entries */
1468         mutex_lock(&__ip_vs_mutex);
1469         ip_vs_flush(net, true);
1470         mutex_unlock(&__ip_vs_mutex);
1471         LeaveFunction(2);
1472 }
1473
1474 /* Put all references for device (dst_cache) */
1475 static inline void
1476 ip_vs_forget_dev(struct ip_vs_dest *dest, struct net_device *dev)
1477 {
1478         struct ip_vs_dest_dst *dest_dst;
1479
1480         spin_lock_bh(&dest->dst_lock);
1481         dest_dst = rcu_dereference_protected(dest->dest_dst, 1);
1482         if (dest_dst && dest_dst->dst_cache->dev == dev) {
1483                 IP_VS_DBG_BUF(3, "Reset dev:%s dest %s:%u ,dest->refcnt=%d\n",
1484                               dev->name,
1485                               IP_VS_DBG_ADDR(dest->af, &dest->addr),
1486                               ntohs(dest->port),
1487                               atomic_read(&dest->refcnt));
1488                 __ip_vs_dst_cache_reset(dest);
1489         }
1490         spin_unlock_bh(&dest->dst_lock);
1491
1492 }
1493 /* Netdev event receiver
1494  * Currently only NETDEV_DOWN is handled to release refs to cached dsts
1495  */
1496 static int ip_vs_dst_event(struct notifier_block *this, unsigned long event,
1497                            void *ptr)
1498 {
1499         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1500         struct net *net = dev_net(dev);
1501         struct netns_ipvs *ipvs = net_ipvs(net);
1502         struct ip_vs_service *svc;
1503         struct ip_vs_dest *dest;
1504         unsigned int idx;
1505
1506         if (event != NETDEV_DOWN || !ipvs)
1507                 return NOTIFY_DONE;
1508         IP_VS_DBG(3, "%s() dev=%s\n", __func__, dev->name);
1509         EnterFunction(2);
1510         mutex_lock(&__ip_vs_mutex);
1511         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1512                 hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
1513                         if (net_eq(svc->net, net)) {
1514                                 list_for_each_entry(dest, &svc->destinations,
1515                                                     n_list) {
1516                                         ip_vs_forget_dev(dest, dev);
1517                                 }
1518                         }
1519                 }
1520
1521                 hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
1522                         if (net_eq(svc->net, net)) {
1523                                 list_for_each_entry(dest, &svc->destinations,
1524                                                     n_list) {
1525                                         ip_vs_forget_dev(dest, dev);
1526                                 }
1527                         }
1528
1529                 }
1530         }
1531
1532         spin_lock_bh(&ipvs->dest_trash_lock);
1533         list_for_each_entry(dest, &ipvs->dest_trash, t_list) {
1534                 ip_vs_forget_dev(dest, dev);
1535         }
1536         spin_unlock_bh(&ipvs->dest_trash_lock);
1537         mutex_unlock(&__ip_vs_mutex);
1538         LeaveFunction(2);
1539         return NOTIFY_DONE;
1540 }
1541
1542 /*
1543  *      Zero counters in a service or all services
1544  */
1545 static int ip_vs_zero_service(struct ip_vs_service *svc)
1546 {
1547         struct ip_vs_dest *dest;
1548
1549         list_for_each_entry(dest, &svc->destinations, n_list) {
1550                 ip_vs_zero_stats(&dest->stats);
1551         }
1552         ip_vs_zero_stats(&svc->stats);
1553         return 0;
1554 }
1555
1556 static int ip_vs_zero_all(struct net *net)
1557 {
1558         int idx;
1559         struct ip_vs_service *svc;
1560
1561         for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1562                 hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
1563                         if (net_eq(svc->net, net))
1564                                 ip_vs_zero_service(svc);
1565                 }
1566         }
1567
1568         for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1569                 hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
1570                         if (net_eq(svc->net, net))
1571                                 ip_vs_zero_service(svc);
1572                 }
1573         }
1574
1575         ip_vs_zero_stats(&net_ipvs(net)->tot_stats);
1576         return 0;
1577 }
1578
1579 #ifdef CONFIG_SYSCTL
1580
1581 static int zero;
1582 static int three = 3;
1583
1584 static int
1585 proc_do_defense_mode(struct ctl_table *table, int write,
1586                      void __user *buffer, size_t *lenp, loff_t *ppos)
1587 {
1588         struct net *net = current->nsproxy->net_ns;
1589         int *valp = table->data;
1590         int val = *valp;
1591         int rc;
1592
1593         rc = proc_dointvec(table, write, buffer, lenp, ppos);
1594         if (write && (*valp != val)) {
1595                 if ((*valp < 0) || (*valp > 3)) {
1596                         /* Restore the correct value */
1597                         *valp = val;
1598                 } else {
1599                         update_defense_level(net_ipvs(net));
1600                 }
1601         }
1602         return rc;
1603 }
1604
1605 static int
1606 proc_do_sync_threshold(struct ctl_table *table, int write,
1607                        void __user *buffer, size_t *lenp, loff_t *ppos)
1608 {
1609         int *valp = table->data;
1610         int val[2];
1611         int rc;
1612
1613         /* backup the value first */
1614         memcpy(val, valp, sizeof(val));
1615
1616         rc = proc_dointvec(table, write, buffer, lenp, ppos);
1617         if (write && (valp[0] < 0 || valp[1] < 0 ||
1618             (valp[0] >= valp[1] && valp[1]))) {
1619                 /* Restore the correct value */
1620                 memcpy(valp, val, sizeof(val));
1621         }
1622         return rc;
1623 }
1624
1625 static int
1626 proc_do_sync_mode(struct ctl_table *table, int write,
1627                      void __user *buffer, size_t *lenp, loff_t *ppos)
1628 {
1629         int *valp = table->data;
1630         int val = *valp;
1631         int rc;
1632
1633         rc = proc_dointvec(table, write, buffer, lenp, ppos);
1634         if (write && (*valp != val)) {
1635                 if ((*valp < 0) || (*valp > 1)) {
1636                         /* Restore the correct value */
1637                         *valp = val;
1638                 }
1639         }
1640         return rc;
1641 }
1642
1643 static int
1644 proc_do_sync_ports(struct ctl_table *table, int write,
1645                    void __user *buffer, size_t *lenp, loff_t *ppos)
1646 {
1647         int *valp = table->data;
1648         int val = *valp;
1649         int rc;
1650
1651         rc = proc_dointvec(table, write, buffer, lenp, ppos);
1652         if (write && (*valp != val)) {
1653                 if (*valp < 1 || !is_power_of_2(*valp)) {
1654                         /* Restore the correct value */
1655                         *valp = val;
1656                 }
1657         }
1658         return rc;
1659 }
1660
1661 /*
1662  *      IPVS sysctl table (under the /proc/sys/net/ipv4/vs/)
1663  *      Do not change order or insert new entries without
1664  *      align with netns init in ip_vs_control_net_init()
1665  */
1666
1667 static struct ctl_table vs_vars[] = {
1668         {
1669                 .procname       = "amemthresh",
1670                 .maxlen         = sizeof(int),
1671                 .mode           = 0644,
1672                 .proc_handler   = proc_dointvec,
1673         },
1674         {
1675                 .procname       = "am_droprate",
1676                 .maxlen         = sizeof(int),
1677                 .mode           = 0644,
1678                 .proc_handler   = proc_dointvec,
1679         },
1680         {
1681                 .procname       = "drop_entry",
1682                 .maxlen         = sizeof(int),
1683                 .mode           = 0644,
1684                 .proc_handler   = proc_do_defense_mode,
1685         },
1686         {
1687                 .procname       = "drop_packet",
1688                 .maxlen         = sizeof(int),
1689                 .mode           = 0644,
1690                 .proc_handler   = proc_do_defense_mode,
1691         },
1692 #ifdef CONFIG_IP_VS_NFCT
1693         {
1694                 .procname       = "conntrack",
1695                 .maxlen         = sizeof(int),
1696                 .mode           = 0644,
1697                 .proc_handler   = &proc_dointvec,
1698         },
1699 #endif
1700         {
1701                 .procname       = "secure_tcp",
1702                 .maxlen         = sizeof(int),
1703                 .mode           = 0644,
1704                 .proc_handler   = proc_do_defense_mode,
1705         },
1706         {
1707                 .procname       = "snat_reroute",
1708                 .maxlen         = sizeof(int),
1709                 .mode           = 0644,
1710                 .proc_handler   = &proc_dointvec,
1711         },
1712         {
1713                 .procname       = "sync_version",
1714                 .maxlen         = sizeof(int),
1715                 .mode           = 0644,
1716                 .proc_handler   = &proc_do_sync_mode,
1717         },
1718         {
1719                 .procname       = "sync_ports",
1720                 .maxlen         = sizeof(int),
1721                 .mode           = 0644,
1722                 .proc_handler   = &proc_do_sync_ports,
1723         },
1724         {
1725                 .procname       = "sync_persist_mode",
1726                 .maxlen         = sizeof(int),
1727                 .mode           = 0644,
1728                 .proc_handler   = proc_dointvec,
1729         },
1730         {
1731                 .procname       = "sync_qlen_max",
1732                 .maxlen         = sizeof(unsigned long),
1733                 .mode           = 0644,
1734                 .proc_handler   = proc_doulongvec_minmax,
1735         },
1736         {
1737                 .procname       = "sync_sock_size",
1738                 .maxlen         = sizeof(int),
1739                 .mode           = 0644,
1740                 .proc_handler   = proc_dointvec,
1741         },
1742         {
1743                 .procname       = "cache_bypass",
1744                 .maxlen         = sizeof(int),
1745                 .mode           = 0644,
1746                 .proc_handler   = proc_dointvec,
1747         },
1748         {
1749                 .procname       = "expire_nodest_conn",
1750                 .maxlen         = sizeof(int),
1751                 .mode           = 0644,
1752                 .proc_handler   = proc_dointvec,
1753         },
1754         {
1755                 .procname       = "sloppy_tcp",
1756                 .maxlen         = sizeof(int),
1757                 .mode           = 0644,
1758                 .proc_handler   = proc_dointvec,
1759         },
1760         {
1761                 .procname       = "sloppy_sctp",
1762                 .maxlen         = sizeof(int),
1763                 .mode           = 0644,
1764                 .proc_handler   = proc_dointvec,
1765         },
1766         {
1767                 .procname       = "expire_quiescent_template",
1768                 .maxlen         = sizeof(int),
1769                 .mode           = 0644,
1770                 .proc_handler   = proc_dointvec,
1771         },
1772         {
1773                 .procname       = "sync_threshold",
1774                 .maxlen         =
1775                         sizeof(((struct netns_ipvs *)0)->sysctl_sync_threshold),
1776                 .mode           = 0644,
1777                 .proc_handler   = proc_do_sync_threshold,
1778         },
1779         {
1780                 .procname       = "sync_refresh_period",
1781                 .maxlen         = sizeof(int),
1782                 .mode           = 0644,
1783                 .proc_handler   = proc_dointvec_jiffies,
1784         },
1785         {
1786                 .procname       = "sync_retries",
1787                 .maxlen         = sizeof(int),
1788                 .mode           = 0644,
1789                 .proc_handler   = proc_dointvec_minmax,
1790                 .extra1         = &zero,
1791                 .extra2         = &three,
1792         },
1793         {
1794                 .procname       = "nat_icmp_send",
1795                 .maxlen         = sizeof(int),
1796                 .mode           = 0644,
1797                 .proc_handler   = proc_dointvec,
1798         },
1799         {
1800                 .procname       = "pmtu_disc",
1801                 .maxlen         = sizeof(int),
1802                 .mode           = 0644,
1803                 .proc_handler   = proc_dointvec,
1804         },
1805         {
1806                 .procname       = "backup_only",
1807                 .maxlen         = sizeof(int),
1808                 .mode           = 0644,
1809                 .proc_handler   = proc_dointvec,
1810         },
1811 #ifdef CONFIG_IP_VS_DEBUG
1812         {
1813                 .procname       = "debug_level",
1814                 .data           = &sysctl_ip_vs_debug_level,
1815                 .maxlen         = sizeof(int),
1816                 .mode           = 0644,
1817                 .proc_handler   = proc_dointvec,
1818         },
1819 #endif
1820         { }
1821 };
1822
1823 #endif
1824
1825 #ifdef CONFIG_PROC_FS
1826
1827 struct ip_vs_iter {
1828         struct seq_net_private p;  /* Do not move this, netns depends upon it*/
1829         struct hlist_head *table;
1830         int bucket;
1831 };
1832
1833 /*
1834  *      Write the contents of the VS rule table to a PROCfs file.
1835  *      (It is kept just for backward compatibility)
1836  */
1837 static inline const char *ip_vs_fwd_name(unsigned int flags)
1838 {
1839         switch (flags & IP_VS_CONN_F_FWD_MASK) {
1840         case IP_VS_CONN_F_LOCALNODE:
1841                 return "Local";
1842         case IP_VS_CONN_F_TUNNEL:
1843                 return "Tunnel";
1844         case IP_VS_CONN_F_DROUTE:
1845                 return "Route";
1846         default:
1847                 return "Masq";
1848         }
1849 }
1850
1851
1852 /* Get the Nth entry in the two lists */
1853 static struct ip_vs_service *ip_vs_info_array(struct seq_file *seq, loff_t pos)
1854 {
1855         struct net *net = seq_file_net(seq);
1856         struct ip_vs_iter *iter = seq->private;
1857         int idx;
1858         struct ip_vs_service *svc;
1859
1860         /* look in hash by protocol */
1861         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1862                 hlist_for_each_entry_rcu(svc, &ip_vs_svc_table[idx], s_list) {
1863                         if (net_eq(svc->net, net) && pos-- == 0) {
1864                                 iter->table = ip_vs_svc_table;
1865                                 iter->bucket = idx;
1866                                 return svc;
1867                         }
1868                 }
1869         }
1870
1871         /* keep looking in fwmark */
1872         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1873                 hlist_for_each_entry_rcu(svc, &ip_vs_svc_fwm_table[idx],
1874                                          f_list) {
1875                         if (net_eq(svc->net, net) && pos-- == 0) {
1876                                 iter->table = ip_vs_svc_fwm_table;
1877                                 iter->bucket = idx;
1878                                 return svc;
1879                         }
1880                 }
1881         }
1882
1883         return NULL;
1884 }
1885
1886 static void *ip_vs_info_seq_start(struct seq_file *seq, loff_t *pos)
1887         __acquires(RCU)
1888 {
1889         rcu_read_lock();
1890         return *pos ? ip_vs_info_array(seq, *pos - 1) : SEQ_START_TOKEN;
1891 }
1892
1893
1894 static void *ip_vs_info_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1895 {
1896         struct hlist_node *e;
1897         struct ip_vs_iter *iter;
1898         struct ip_vs_service *svc;
1899
1900         ++*pos;
1901         if (v == SEQ_START_TOKEN)
1902                 return ip_vs_info_array(seq,0);
1903
1904         svc = v;
1905         iter = seq->private;
1906
1907         if (iter->table == ip_vs_svc_table) {
1908                 /* next service in table hashed by protocol */
1909                 e = rcu_dereference(hlist_next_rcu(&svc->s_list));
1910                 if (e)
1911                         return hlist_entry(e, struct ip_vs_service, s_list);
1912
1913                 while (++iter->bucket < IP_VS_SVC_TAB_SIZE) {
1914                         hlist_for_each_entry_rcu(svc,
1915                                                  &ip_vs_svc_table[iter->bucket],
1916                                                  s_list) {
1917                                 return svc;
1918                         }
1919                 }
1920
1921                 iter->table = ip_vs_svc_fwm_table;
1922                 iter->bucket = -1;
1923                 goto scan_fwmark;
1924         }
1925
1926         /* next service in hashed by fwmark */
1927         e = rcu_dereference(hlist_next_rcu(&svc->f_list));
1928         if (e)
1929                 return hlist_entry(e, struct ip_vs_service, f_list);
1930
1931  scan_fwmark:
1932         while (++iter->bucket < IP_VS_SVC_TAB_SIZE) {
1933                 hlist_for_each_entry_rcu(svc,
1934                                          &ip_vs_svc_fwm_table[iter->bucket],
1935                                          f_list)
1936                         return svc;
1937         }
1938
1939         return NULL;
1940 }
1941
1942 static void ip_vs_info_seq_stop(struct seq_file *seq, void *v)
1943         __releases(RCU)
1944 {
1945         rcu_read_unlock();
1946 }
1947
1948
1949 static int ip_vs_info_seq_show(struct seq_file *seq, void *v)
1950 {
1951         if (v == SEQ_START_TOKEN) {
1952                 seq_printf(seq,
1953                         "IP Virtual Server version %d.%d.%d (size=%d)\n",
1954                         NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
1955                 seq_puts(seq,
1956                          "Prot LocalAddress:Port Scheduler Flags\n");
1957                 seq_puts(seq,
1958                          "  -> RemoteAddress:Port Forward Weight ActiveConn InActConn\n");
1959         } else {
1960                 const struct ip_vs_service *svc = v;
1961                 const struct ip_vs_iter *iter = seq->private;
1962                 const struct ip_vs_dest *dest;
1963                 struct ip_vs_scheduler *sched = rcu_dereference(svc->scheduler);
1964
1965                 if (iter->table == ip_vs_svc_table) {
1966 #ifdef CONFIG_IP_VS_IPV6
1967                         if (svc->af == AF_INET6)
1968                                 seq_printf(seq, "%s  [%pI6]:%04X %s ",
1969                                            ip_vs_proto_name(svc->protocol),
1970                                            &svc->addr.in6,
1971                                            ntohs(svc->port),
1972                                            sched->name);
1973                         else
1974 #endif
1975                                 seq_printf(seq, "%s  %08X:%04X %s %s ",
1976                                            ip_vs_proto_name(svc->protocol),
1977                                            ntohl(svc->addr.ip),
1978                                            ntohs(svc->port),
1979                                            sched->name,
1980                                            (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":"");
1981                 } else {
1982                         seq_printf(seq, "FWM  %08X %s %s",
1983                                    svc->fwmark, sched->name,
1984                                    (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":"");
1985                 }
1986
1987                 if (svc->flags & IP_VS_SVC_F_PERSISTENT)
1988                         seq_printf(seq, "persistent %d %08X\n",
1989                                 svc->timeout,
1990                                 ntohl(svc->netmask));
1991                 else
1992                         seq_putc(seq, '\n');
1993
1994                 list_for_each_entry_rcu(dest, &svc->destinations, n_list) {
1995 #ifdef CONFIG_IP_VS_IPV6
1996                         if (dest->af == AF_INET6)
1997                                 seq_printf(seq,
1998                                            "  -> [%pI6]:%04X"
1999                                            "      %-7s %-6d %-10d %-10d\n",
2000                                            &dest->addr.in6,
2001                                            ntohs(dest->port),
2002                                            ip_vs_fwd_name(atomic_read(&dest->conn_flags)),
2003                                            atomic_read(&dest->weight),
2004                                            atomic_read(&dest->activeconns),
2005                                            atomic_read(&dest->inactconns));
2006                         else
2007 #endif
2008                                 seq_printf(seq,
2009                                            "  -> %08X:%04X      "
2010                                            "%-7s %-6d %-10d %-10d\n",
2011                                            ntohl(dest->addr.ip),
2012                                            ntohs(dest->port),
2013                                            ip_vs_fwd_name(atomic_read(&dest->conn_flags)),
2014                                            atomic_read(&dest->weight),
2015                                            atomic_read(&dest->activeconns),
2016                                            atomic_read(&dest->inactconns));
2017
2018                 }
2019         }
2020         return 0;
2021 }
2022
2023 static const struct seq_operations ip_vs_info_seq_ops = {
2024         .start = ip_vs_info_seq_start,
2025         .next  = ip_vs_info_seq_next,
2026         .stop  = ip_vs_info_seq_stop,
2027         .show  = ip_vs_info_seq_show,
2028 };
2029
2030 static int ip_vs_info_open(struct inode *inode, struct file *file)
2031 {
2032         return seq_open_net(inode, file, &ip_vs_info_seq_ops,
2033                         sizeof(struct ip_vs_iter));
2034 }
2035
2036 static const struct file_operations ip_vs_info_fops = {
2037         .owner   = THIS_MODULE,
2038         .open    = ip_vs_info_open,
2039         .read    = seq_read,
2040         .llseek  = seq_lseek,
2041         .release = seq_release_net,
2042 };
2043
2044 static int ip_vs_stats_show(struct seq_file *seq, void *v)
2045 {
2046         struct net *net = seq_file_single_net(seq);
2047         struct ip_vs_stats_user show;
2048
2049 /*               01234567 01234567 01234567 0123456701234567 0123456701234567 */
2050         seq_puts(seq,
2051                  "   Total Incoming Outgoing         Incoming         Outgoing\n");
2052         seq_printf(seq,
2053                    "   Conns  Packets  Packets            Bytes            Bytes\n");
2054
2055         ip_vs_copy_stats(&show, &net_ipvs(net)->tot_stats);
2056         seq_printf(seq, "%8X %8X %8X %16LX %16LX\n\n", show.conns,
2057                    show.inpkts, show.outpkts,
2058                    (unsigned long long) show.inbytes,
2059                    (unsigned long long) show.outbytes);
2060
2061 /*                 01234567 01234567 01234567 0123456701234567 0123456701234567 */
2062         seq_puts(seq,
2063                    " Conns/s   Pkts/s   Pkts/s          Bytes/s          Bytes/s\n");
2064         seq_printf(seq, "%8X %8X %8X %16X %16X\n",
2065                         show.cps, show.inpps, show.outpps,
2066                         show.inbps, show.outbps);
2067
2068         return 0;
2069 }
2070
2071 static int ip_vs_stats_seq_open(struct inode *inode, struct file *file)
2072 {
2073         return single_open_net(inode, file, ip_vs_stats_show);
2074 }
2075
2076 static const struct file_operations ip_vs_stats_fops = {
2077         .owner = THIS_MODULE,
2078         .open = ip_vs_stats_seq_open,
2079         .read = seq_read,
2080         .llseek = seq_lseek,
2081         .release = single_release_net,
2082 };
2083
2084 static int ip_vs_stats_percpu_show(struct seq_file *seq, void *v)
2085 {
2086         struct net *net = seq_file_single_net(seq);
2087         struct ip_vs_stats *tot_stats = &net_ipvs(net)->tot_stats;
2088         struct ip_vs_cpu_stats __percpu *cpustats = tot_stats->cpustats;
2089         struct ip_vs_stats_user rates;
2090         int i;
2091
2092 /*               01234567 01234567 01234567 0123456701234567 0123456701234567 */
2093         seq_puts(seq,
2094                  "       Total Incoming Outgoing         Incoming         Outgoing\n");
2095         seq_printf(seq,
2096                    "CPU    Conns  Packets  Packets            Bytes            Bytes\n");
2097
2098         for_each_possible_cpu(i) {
2099                 struct ip_vs_cpu_stats *u = per_cpu_ptr(cpustats, i);
2100                 unsigned int start;
2101                 __u64 inbytes, outbytes;
2102
2103                 do {
2104                         start = u64_stats_fetch_begin_irq(&u->syncp);
2105                         inbytes = u->ustats.inbytes;
2106                         outbytes = u->ustats.outbytes;
2107                 } while (u64_stats_fetch_retry_irq(&u->syncp, start));
2108
2109                 seq_printf(seq, "%3X %8X %8X %8X %16LX %16LX\n",
2110                            i, u->ustats.conns, u->ustats.inpkts,
2111                            u->ustats.outpkts, (__u64)inbytes,
2112                            (__u64)outbytes);
2113         }
2114
2115         spin_lock_bh(&tot_stats->lock);
2116
2117         seq_printf(seq, "  ~ %8X %8X %8X %16LX %16LX\n\n",
2118                    tot_stats->ustats.conns, tot_stats->ustats.inpkts,
2119                    tot_stats->ustats.outpkts,
2120                    (unsigned long long) tot_stats->ustats.inbytes,
2121                    (unsigned long long) tot_stats->ustats.outbytes);
2122
2123         ip_vs_read_estimator(&rates, tot_stats);
2124
2125         spin_unlock_bh(&tot_stats->lock);
2126
2127 /*                 01234567 01234567 01234567 0123456701234567 0123456701234567 */
2128         seq_puts(seq,
2129                    "     Conns/s   Pkts/s   Pkts/s          Bytes/s          Bytes/s\n");
2130         seq_printf(seq, "    %8X %8X %8X %16X %16X\n",
2131                         rates.cps,
2132                         rates.inpps,
2133                         rates.outpps,
2134                         rates.inbps,
2135                         rates.outbps);
2136
2137         return 0;
2138 }
2139
2140 static int ip_vs_stats_percpu_seq_open(struct inode *inode, struct file *file)
2141 {
2142         return single_open_net(inode, file, ip_vs_stats_percpu_show);
2143 }
2144
2145 static const struct file_operations ip_vs_stats_percpu_fops = {
2146         .owner = THIS_MODULE,
2147         .open = ip_vs_stats_percpu_seq_open,
2148         .read = seq_read,
2149         .llseek = seq_lseek,
2150         .release = single_release_net,
2151 };
2152 #endif
2153
2154 /*
2155  *      Set timeout values for tcp tcpfin udp in the timeout_table.
2156  */
2157 static int ip_vs_set_timeout(struct net *net, struct ip_vs_timeout_user *u)
2158 {
2159 #if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP)
2160         struct ip_vs_proto_data *pd;
2161 #endif
2162
2163         IP_VS_DBG(2, "Setting timeout tcp:%d tcpfin:%d udp:%d\n",
2164                   u->tcp_timeout,
2165                   u->tcp_fin_timeout,
2166                   u->udp_timeout);
2167
2168 #ifdef CONFIG_IP_VS_PROTO_TCP
2169         if (u->tcp_timeout) {
2170                 pd = ip_vs_proto_data_get(net, IPPROTO_TCP);
2171                 pd->timeout_table[IP_VS_TCP_S_ESTABLISHED]
2172                         = u->tcp_timeout * HZ;
2173         }
2174
2175         if (u->tcp_fin_timeout) {
2176                 pd = ip_vs_proto_data_get(net, IPPROTO_TCP);
2177                 pd->timeout_table[IP_VS_TCP_S_FIN_WAIT]
2178                         = u->tcp_fin_timeout * HZ;
2179         }
2180 #endif
2181
2182 #ifdef CONFIG_IP_VS_PROTO_UDP
2183         if (u->udp_timeout) {
2184                 pd = ip_vs_proto_data_get(net, IPPROTO_UDP);
2185                 pd->timeout_table[IP_VS_UDP_S_NORMAL]
2186                         = u->udp_timeout * HZ;
2187         }
2188 #endif
2189         return 0;
2190 }
2191
2192 #define CMDID(cmd)              (cmd - IP_VS_BASE_CTL)
2193
2194 struct ip_vs_svcdest_user {
2195         struct ip_vs_service_user       s;
2196         struct ip_vs_dest_user          d;
2197 };
2198
2199 static const unsigned char set_arglen[CMDID(IP_VS_SO_SET_MAX) + 1] = {
2200         [CMDID(IP_VS_SO_SET_ADD)]         = sizeof(struct ip_vs_service_user),
2201         [CMDID(IP_VS_SO_SET_EDIT)]        = sizeof(struct ip_vs_service_user),
2202         [CMDID(IP_VS_SO_SET_DEL)]         = sizeof(struct ip_vs_service_user),
2203         [CMDID(IP_VS_SO_SET_ADDDEST)]     = sizeof(struct ip_vs_svcdest_user),
2204         [CMDID(IP_VS_SO_SET_DELDEST)]     = sizeof(struct ip_vs_svcdest_user),
2205         [CMDID(IP_VS_SO_SET_EDITDEST)]    = sizeof(struct ip_vs_svcdest_user),
2206         [CMDID(IP_VS_SO_SET_TIMEOUT)]     = sizeof(struct ip_vs_timeout_user),
2207         [CMDID(IP_VS_SO_SET_STARTDAEMON)] = sizeof(struct ip_vs_daemon_user),
2208         [CMDID(IP_VS_SO_SET_STOPDAEMON)]  = sizeof(struct ip_vs_daemon_user),
2209         [CMDID(IP_VS_SO_SET_ZERO)]        = sizeof(struct ip_vs_service_user),
2210 };
2211
2212 union ip_vs_set_arglen {
2213         struct ip_vs_service_user       field_IP_VS_SO_SET_ADD;
2214         struct ip_vs_service_user       field_IP_VS_SO_SET_EDIT;
2215         struct ip_vs_service_user       field_IP_VS_SO_SET_DEL;
2216         struct ip_vs_svcdest_user       field_IP_VS_SO_SET_ADDDEST;
2217         struct ip_vs_svcdest_user       field_IP_VS_SO_SET_DELDEST;
2218         struct ip_vs_svcdest_user       field_IP_VS_SO_SET_EDITDEST;
2219         struct ip_vs_timeout_user       field_IP_VS_SO_SET_TIMEOUT;
2220         struct ip_vs_daemon_user        field_IP_VS_SO_SET_STARTDAEMON;
2221         struct ip_vs_daemon_user        field_IP_VS_SO_SET_STOPDAEMON;
2222         struct ip_vs_service_user       field_IP_VS_SO_SET_ZERO;
2223 };
2224
2225 #define MAX_SET_ARGLEN  sizeof(union ip_vs_set_arglen)
2226
2227 static void ip_vs_copy_usvc_compat(struct ip_vs_service_user_kern *usvc,
2228                                   struct ip_vs_service_user *usvc_compat)
2229 {
2230         memset(usvc, 0, sizeof(*usvc));
2231
2232         usvc->af                = AF_INET;
2233         usvc->protocol          = usvc_compat->protocol;
2234         usvc->addr.ip           = usvc_compat->addr;
2235         usvc->port              = usvc_compat->port;
2236         usvc->fwmark            = usvc_compat->fwmark;
2237
2238         /* Deep copy of sched_name is not needed here */
2239         usvc->sched_name        = usvc_compat->sched_name;
2240
2241         usvc->flags             = usvc_compat->flags;
2242         usvc->timeout           = usvc_compat->timeout;
2243         usvc->netmask           = usvc_compat->netmask;
2244 }
2245
2246 static void ip_vs_copy_udest_compat(struct ip_vs_dest_user_kern *udest,
2247                                    struct ip_vs_dest_user *udest_compat)
2248 {
2249         memset(udest, 0, sizeof(*udest));
2250
2251         udest->addr.ip          = udest_compat->addr;
2252         udest->port             = udest_compat->port;
2253         udest->conn_flags       = udest_compat->conn_flags;
2254         udest->weight           = udest_compat->weight;
2255         udest->u_threshold      = udest_compat->u_threshold;
2256         udest->l_threshold      = udest_compat->l_threshold;
2257         udest->af               = AF_INET;
2258 }
2259
2260 static int
2261 do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
2262 {
2263         struct net *net = sock_net(sk);
2264         int ret;
2265         unsigned char arg[MAX_SET_ARGLEN];
2266         struct ip_vs_service_user *usvc_compat;
2267         struct ip_vs_service_user_kern usvc;
2268         struct ip_vs_service *svc;
2269         struct ip_vs_dest_user *udest_compat;
2270         struct ip_vs_dest_user_kern udest;
2271         struct netns_ipvs *ipvs = net_ipvs(net);
2272
2273         BUILD_BUG_ON(sizeof(arg) > 255);
2274         if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2275                 return -EPERM;
2276
2277         if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_SET_MAX)
2278                 return -EINVAL;
2279         if (len != set_arglen[CMDID(cmd)]) {
2280                 IP_VS_DBG(1, "set_ctl: len %u != %u\n",
2281                           len, set_arglen[CMDID(cmd)]);
2282                 return -EINVAL;
2283         }
2284
2285         if (copy_from_user(arg, user, len) != 0)
2286                 return -EFAULT;
2287
2288         /* increase the module use count */
2289         ip_vs_use_count_inc();
2290
2291         /* Handle daemons since they have another lock */
2292         if (cmd == IP_VS_SO_SET_STARTDAEMON ||
2293             cmd == IP_VS_SO_SET_STOPDAEMON) {
2294                 struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
2295
2296                 mutex_lock(&ipvs->sync_mutex);
2297                 if (cmd == IP_VS_SO_SET_STARTDAEMON)
2298                         ret = start_sync_thread(net, dm->state, dm->mcast_ifn,
2299                                                 dm->syncid);
2300                 else
2301                         ret = stop_sync_thread(net, dm->state);
2302                 mutex_unlock(&ipvs->sync_mutex);
2303                 goto out_dec;
2304         }
2305
2306         mutex_lock(&__ip_vs_mutex);
2307         if (cmd == IP_VS_SO_SET_FLUSH) {
2308                 /* Flush the virtual service */
2309                 ret = ip_vs_flush(net, false);
2310                 goto out_unlock;
2311         } else if (cmd == IP_VS_SO_SET_TIMEOUT) {
2312                 /* Set timeout values for (tcp tcpfin udp) */
2313                 ret = ip_vs_set_timeout(net, (struct ip_vs_timeout_user *)arg);
2314                 goto out_unlock;
2315         }
2316
2317         usvc_compat = (struct ip_vs_service_user *)arg;
2318         udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1);
2319
2320         /* We only use the new structs internally, so copy userspace compat
2321          * structs to extended internal versions */
2322         ip_vs_copy_usvc_compat(&usvc, usvc_compat);
2323         ip_vs_copy_udest_compat(&udest, udest_compat);
2324
2325         if (cmd == IP_VS_SO_SET_ZERO) {
2326                 /* if no service address is set, zero counters in all */
2327                 if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) {
2328                         ret = ip_vs_zero_all(net);
2329                         goto out_unlock;
2330                 }
2331         }
2332
2333         /* Check for valid protocol: TCP or UDP or SCTP, even for fwmark!=0 */
2334         if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP &&
2335             usvc.protocol != IPPROTO_SCTP) {
2336                 pr_err("set_ctl: invalid protocol: %d %pI4:%d %s\n",
2337                        usvc.protocol, &usvc.addr.ip,
2338                        ntohs(usvc.port), usvc.sched_name);
2339                 ret = -EFAULT;
2340                 goto out_unlock;
2341         }
2342
2343         /* Lookup the exact service by <protocol, addr, port> or fwmark */
2344         rcu_read_lock();
2345         if (usvc.fwmark == 0)
2346                 svc = __ip_vs_service_find(net, usvc.af, usvc.protocol,
2347                                            &usvc.addr, usvc.port);
2348         else
2349                 svc = __ip_vs_svc_fwm_find(net, usvc.af, usvc.fwmark);
2350         rcu_read_unlock();
2351
2352         if (cmd != IP_VS_SO_SET_ADD
2353             && (svc == NULL || svc->protocol != usvc.protocol)) {
2354                 ret = -ESRCH;
2355                 goto out_unlock;
2356         }
2357
2358         switch (cmd) {
2359         case IP_VS_SO_SET_ADD:
2360                 if (svc != NULL)
2361                         ret = -EEXIST;
2362                 else
2363                         ret = ip_vs_add_service(net, &usvc, &svc);
2364                 break;
2365         case IP_VS_SO_SET_EDIT:
2366                 ret = ip_vs_edit_service(svc, &usvc);
2367                 break;
2368         case IP_VS_SO_SET_DEL:
2369                 ret = ip_vs_del_service(svc);
2370                 if (!ret)
2371                         goto out_unlock;
2372                 break;
2373         case IP_VS_SO_SET_ZERO:
2374                 ret = ip_vs_zero_service(svc);
2375                 break;
2376         case IP_VS_SO_SET_ADDDEST:
2377                 ret = ip_vs_add_dest(svc, &udest);
2378                 break;
2379         case IP_VS_SO_SET_EDITDEST:
2380                 ret = ip_vs_edit_dest(svc, &udest);
2381                 break;
2382         case IP_VS_SO_SET_DELDEST:
2383                 ret = ip_vs_del_dest(svc, &udest);
2384                 break;
2385         default:
2386                 ret = -EINVAL;
2387         }
2388
2389   out_unlock:
2390         mutex_unlock(&__ip_vs_mutex);
2391   out_dec:
2392         /* decrease the module use count */
2393         ip_vs_use_count_dec();
2394
2395         return ret;
2396 }
2397
2398
2399 static void
2400 ip_vs_copy_service(struct ip_vs_service_entry *dst, struct ip_vs_service *src)
2401 {
2402         struct ip_vs_scheduler *sched;
2403
2404         sched = rcu_dereference_protected(src->scheduler, 1);
2405         dst->protocol = src->protocol;
2406         dst->addr = src->addr.ip;
2407         dst->port = src->port;
2408         dst->fwmark = src->fwmark;
2409         strlcpy(dst->sched_name, sched->name, sizeof(dst->sched_name));
2410         dst->flags = src->flags;
2411         dst->timeout = src->timeout / HZ;
2412         dst->netmask = src->netmask;
2413         dst->num_dests = src->num_dests;
2414         ip_vs_copy_stats(&dst->stats, &src->stats);
2415 }
2416
2417 static inline int
2418 __ip_vs_get_service_entries(struct net *net,
2419                             const struct ip_vs_get_services *get,
2420                             struct ip_vs_get_services __user *uptr)
2421 {
2422         int idx, count=0;
2423         struct ip_vs_service *svc;
2424         struct ip_vs_service_entry entry;
2425         int ret = 0;
2426
2427         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2428                 hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
2429                         /* Only expose IPv4 entries to old interface */
2430                         if (svc->af != AF_INET || !net_eq(svc->net, net))
2431                                 continue;
2432
2433                         if (count >= get->num_services)
2434                                 goto out;
2435                         memset(&entry, 0, sizeof(entry));
2436                         ip_vs_copy_service(&entry, svc);
2437                         if (copy_to_user(&uptr->entrytable[count],
2438                                          &entry, sizeof(entry))) {
2439                                 ret = -EFAULT;
2440                                 goto out;
2441                         }
2442                         count++;
2443                 }
2444         }
2445
2446         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2447                 hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
2448                         /* Only expose IPv4 entries to old interface */
2449                         if (svc->af != AF_INET || !net_eq(svc->net, net))
2450                                 continue;
2451
2452                         if (count >= get->num_services)
2453                                 goto out;
2454                         memset(&entry, 0, sizeof(entry));
2455                         ip_vs_copy_service(&entry, svc);
2456                         if (copy_to_user(&uptr->entrytable[count],
2457                                          &entry, sizeof(entry))) {
2458                                 ret = -EFAULT;
2459                                 goto out;
2460                         }
2461                         count++;
2462                 }
2463         }
2464 out:
2465         return ret;
2466 }
2467
2468 static inline int
2469 __ip_vs_get_dest_entries(struct net *net, const struct ip_vs_get_dests *get,
2470                          struct ip_vs_get_dests __user *uptr)
2471 {
2472         struct ip_vs_service *svc;
2473         union nf_inet_addr addr = { .ip = get->addr };
2474         int ret = 0;
2475
2476         rcu_read_lock();
2477         if (get->fwmark)
2478                 svc = __ip_vs_svc_fwm_find(net, AF_INET, get->fwmark);
2479         else
2480                 svc = __ip_vs_service_find(net, AF_INET, get->protocol, &addr,
2481                                            get->port);
2482         rcu_read_unlock();
2483
2484         if (svc) {
2485                 int count = 0;
2486                 struct ip_vs_dest *dest;
2487                 struct ip_vs_dest_entry entry;
2488
2489                 memset(&entry, 0, sizeof(entry));
2490                 list_for_each_entry(dest, &svc->destinations, n_list) {
2491                         if (count >= get->num_dests)
2492                                 break;
2493
2494                         /* Cannot expose heterogeneous members via sockopt
2495                          * interface
2496                          */
2497                         if (dest->af != svc->af)
2498                                 continue;
2499
2500                         entry.addr = dest->addr.ip;
2501                         entry.port = dest->port;
2502                         entry.conn_flags = atomic_read(&dest->conn_flags);
2503                         entry.weight = atomic_read(&dest->weight);
2504                         entry.u_threshold = dest->u_threshold;
2505                         entry.l_threshold = dest->l_threshold;
2506                         entry.activeconns = atomic_read(&dest->activeconns);
2507                         entry.inactconns = atomic_read(&dest->inactconns);
2508                         entry.persistconns = atomic_read(&dest->persistconns);
2509                         ip_vs_copy_stats(&entry.stats, &dest->stats);
2510                         if (copy_to_user(&uptr->entrytable[count],
2511                                          &entry, sizeof(entry))) {
2512                                 ret = -EFAULT;
2513                                 break;
2514                         }
2515                         count++;
2516                 }
2517         } else
2518                 ret = -ESRCH;
2519         return ret;
2520 }
2521
2522 static inline void
2523 __ip_vs_get_timeouts(struct net *net, struct ip_vs_timeout_user *u)
2524 {
2525 #if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP)
2526         struct ip_vs_proto_data *pd;
2527 #endif
2528
2529         memset(u, 0, sizeof (*u));
2530
2531 #ifdef CONFIG_IP_VS_PROTO_TCP
2532         pd = ip_vs_proto_data_get(net, IPPROTO_TCP);
2533         u->tcp_timeout = pd->timeout_table[IP_VS_TCP_S_ESTABLISHED] / HZ;
2534         u->tcp_fin_timeout = pd->timeout_table[IP_VS_TCP_S_FIN_WAIT] / HZ;
2535 #endif
2536 #ifdef CONFIG_IP_VS_PROTO_UDP
2537         pd = ip_vs_proto_data_get(net, IPPROTO_UDP);
2538         u->udp_timeout =
2539                         pd->timeout_table[IP_VS_UDP_S_NORMAL] / HZ;
2540 #endif
2541 }
2542
2543 static const unsigned char get_arglen[CMDID(IP_VS_SO_GET_MAX) + 1] = {
2544         [CMDID(IP_VS_SO_GET_VERSION)]  = 64,
2545         [CMDID(IP_VS_SO_GET_INFO)]     = sizeof(struct ip_vs_getinfo),
2546         [CMDID(IP_VS_SO_GET_SERVICES)] = sizeof(struct ip_vs_get_services),
2547         [CMDID(IP_VS_SO_GET_SERVICE)]  = sizeof(struct ip_vs_service_entry),
2548         [CMDID(IP_VS_SO_GET_DESTS)]    = sizeof(struct ip_vs_get_dests),
2549         [CMDID(IP_VS_SO_GET_TIMEOUT)]  = sizeof(struct ip_vs_timeout_user),
2550         [CMDID(IP_VS_SO_GET_DAEMON)]   = 2 * sizeof(struct ip_vs_daemon_user),
2551 };
2552
2553 union ip_vs_get_arglen {
2554         char                            field_IP_VS_SO_GET_VERSION[64];
2555         struct ip_vs_getinfo            field_IP_VS_SO_GET_INFO;
2556         struct ip_vs_get_services       field_IP_VS_SO_GET_SERVICES;
2557         struct ip_vs_service_entry      field_IP_VS_SO_GET_SERVICE;
2558         struct ip_vs_get_dests          field_IP_VS_SO_GET_DESTS;
2559         struct ip_vs_timeout_user       field_IP_VS_SO_GET_TIMEOUT;
2560         struct ip_vs_daemon_user        field_IP_VS_SO_GET_DAEMON[2];
2561 };
2562
2563 #define MAX_GET_ARGLEN  sizeof(union ip_vs_get_arglen)
2564
2565 static int
2566 do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
2567 {
2568         unsigned char arg[MAX_GET_ARGLEN];
2569         int ret = 0;
2570         unsigned int copylen;
2571         struct net *net = sock_net(sk);
2572         struct netns_ipvs *ipvs = net_ipvs(net);
2573
2574         BUG_ON(!net);
2575         BUILD_BUG_ON(sizeof(arg) > 255);
2576         if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2577                 return -EPERM;
2578
2579         if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)
2580                 return -EINVAL;
2581
2582         copylen = get_arglen[CMDID(cmd)];
2583         if (*len < (int) copylen) {
2584                 IP_VS_DBG(1, "get_ctl: len %d < %u\n", *len, copylen);
2585                 return -EINVAL;
2586         }
2587
2588         if (copy_from_user(arg, user, copylen) != 0)
2589                 return -EFAULT;
2590         /*
2591          * Handle daemons first since it has its own locking
2592          */
2593         if (cmd == IP_VS_SO_GET_DAEMON) {
2594                 struct ip_vs_daemon_user d[2];
2595
2596                 memset(&d, 0, sizeof(d));
2597                 mutex_lock(&ipvs->sync_mutex);
2598                 if (ipvs->sync_state & IP_VS_STATE_MASTER) {
2599                         d[0].state = IP_VS_STATE_MASTER;
2600                         strlcpy(d[0].mcast_ifn, ipvs->master_mcast_ifn,
2601                                 sizeof(d[0].mcast_ifn));
2602                         d[0].syncid = ipvs->master_syncid;
2603                 }
2604                 if (ipvs->sync_state & IP_VS_STATE_BACKUP) {
2605                         d[1].state = IP_VS_STATE_BACKUP;
2606                         strlcpy(d[1].mcast_ifn, ipvs->backup_mcast_ifn,
2607                                 sizeof(d[1].mcast_ifn));
2608                         d[1].syncid = ipvs->backup_syncid;
2609                 }
2610                 if (copy_to_user(user, &d, sizeof(d)) != 0)
2611                         ret = -EFAULT;
2612                 mutex_unlock(&ipvs->sync_mutex);
2613                 return ret;
2614         }
2615
2616         mutex_lock(&__ip_vs_mutex);
2617         switch (cmd) {
2618         case IP_VS_SO_GET_VERSION:
2619         {
2620                 char buf[64];
2621
2622                 sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
2623                         NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
2624                 if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
2625                         ret = -EFAULT;
2626                         goto out;
2627                 }
2628                 *len = strlen(buf)+1;
2629         }
2630         break;
2631
2632         case IP_VS_SO_GET_INFO:
2633         {
2634                 struct ip_vs_getinfo info;
2635                 info.version = IP_VS_VERSION_CODE;
2636                 info.size = ip_vs_conn_tab_size;
2637                 info.num_services = ipvs->num_services;
2638                 if (copy_to_user(user, &info, sizeof(info)) != 0)
2639                         ret = -EFAULT;
2640         }
2641         break;
2642
2643         case IP_VS_SO_GET_SERVICES:
2644         {
2645                 struct ip_vs_get_services *get;
2646                 int size;
2647
2648                 get = (struct ip_vs_get_services *)arg;
2649                 size = sizeof(*get) +
2650                         sizeof(struct ip_vs_service_entry) * get->num_services;
2651                 if (*len != size) {
2652                         pr_err("length: %u != %u\n", *len, size);
2653                         ret = -EINVAL;
2654                         goto out;
2655                 }
2656                 ret = __ip_vs_get_service_entries(net, get, user);
2657         }
2658         break;
2659
2660         case IP_VS_SO_GET_SERVICE:
2661         {
2662                 struct ip_vs_service_entry *entry;
2663                 struct ip_vs_service *svc;
2664                 union nf_inet_addr addr;
2665
2666                 entry = (struct ip_vs_service_entry *)arg;
2667                 addr.ip = entry->addr;
2668                 rcu_read_lock();
2669                 if (entry->fwmark)
2670                         svc = __ip_vs_svc_fwm_find(net, AF_INET, entry->fwmark);
2671                 else
2672                         svc = __ip_vs_service_find(net, AF_INET,
2673                                                    entry->protocol, &addr,
2674                                                    entry->port);
2675                 rcu_read_unlock();
2676                 if (svc) {
2677                         ip_vs_copy_service(entry, svc);
2678                         if (copy_to_user(user, entry, sizeof(*entry)) != 0)
2679                                 ret = -EFAULT;
2680                 } else
2681                         ret = -ESRCH;
2682         }
2683         break;
2684
2685         case IP_VS_SO_GET_DESTS:
2686         {
2687                 struct ip_vs_get_dests *get;
2688                 int size;
2689
2690                 get = (struct ip_vs_get_dests *)arg;
2691                 size = sizeof(*get) +
2692                         sizeof(struct ip_vs_dest_entry) * get->num_dests;
2693                 if (*len != size) {
2694                         pr_err("length: %u != %u\n", *len, size);
2695                         ret = -EINVAL;
2696                         goto out;
2697                 }
2698                 ret = __ip_vs_get_dest_entries(net, get, user);
2699         }
2700         break;
2701
2702         case IP_VS_SO_GET_TIMEOUT:
2703         {
2704                 struct ip_vs_timeout_user t;
2705
2706                 __ip_vs_get_timeouts(net, &t);
2707                 if (copy_to_user(user, &t, sizeof(t)) != 0)
2708                         ret = -EFAULT;
2709         }
2710         break;
2711
2712         default:
2713                 ret = -EINVAL;
2714         }
2715
2716 out:
2717         mutex_unlock(&__ip_vs_mutex);
2718         return ret;
2719 }
2720
2721
2722 static struct nf_sockopt_ops ip_vs_sockopts = {
2723         .pf             = PF_INET,
2724         .set_optmin     = IP_VS_BASE_CTL,
2725         .set_optmax     = IP_VS_SO_SET_MAX+1,
2726         .set            = do_ip_vs_set_ctl,
2727         .get_optmin     = IP_VS_BASE_CTL,
2728         .get_optmax     = IP_VS_SO_GET_MAX+1,
2729         .get            = do_ip_vs_get_ctl,
2730         .owner          = THIS_MODULE,
2731 };
2732
2733 /*
2734  * Generic Netlink interface
2735  */
2736
2737 /* IPVS genetlink family */
2738 static struct genl_family ip_vs_genl_family = {
2739         .id             = GENL_ID_GENERATE,
2740         .hdrsize        = 0,
2741         .name           = IPVS_GENL_NAME,
2742         .version        = IPVS_GENL_VERSION,
2743         .maxattr        = IPVS_CMD_MAX,
2744         .netnsok        = true,         /* Make ipvsadm to work on netns */
2745 };
2746
2747 /* Policy used for first-level command attributes */
2748 static const struct nla_policy ip_vs_cmd_policy[IPVS_CMD_ATTR_MAX + 1] = {
2749         [IPVS_CMD_ATTR_SERVICE]         = { .type = NLA_NESTED },
2750         [IPVS_CMD_ATTR_DEST]            = { .type = NLA_NESTED },
2751         [IPVS_CMD_ATTR_DAEMON]          = { .type = NLA_NESTED },
2752         [IPVS_CMD_ATTR_TIMEOUT_TCP]     = { .type = NLA_U32 },
2753         [IPVS_CMD_ATTR_TIMEOUT_TCP_FIN] = { .type = NLA_U32 },
2754         [IPVS_CMD_ATTR_TIMEOUT_UDP]     = { .type = NLA_U32 },
2755 };
2756
2757 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DAEMON */
2758 static const struct nla_policy ip_vs_daemon_policy[IPVS_DAEMON_ATTR_MAX + 1] = {
2759         [IPVS_DAEMON_ATTR_STATE]        = { .type = NLA_U32 },
2760         [IPVS_DAEMON_ATTR_MCAST_IFN]    = { .type = NLA_NUL_STRING,
2761                                             .len = IP_VS_IFNAME_MAXLEN },
2762         [IPVS_DAEMON_ATTR_SYNC_ID]      = { .type = NLA_U32 },
2763 };
2764
2765 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_SERVICE */
2766 static const struct nla_policy ip_vs_svc_policy[IPVS_SVC_ATTR_MAX + 1] = {
2767         [IPVS_SVC_ATTR_AF]              = { .type = NLA_U16 },
2768         [IPVS_SVC_ATTR_PROTOCOL]        = { .type = NLA_U16 },
2769         [IPVS_SVC_ATTR_ADDR]            = { .type = NLA_BINARY,
2770                                             .len = sizeof(union nf_inet_addr) },
2771         [IPVS_SVC_ATTR_PORT]            = { .type = NLA_U16 },
2772         [IPVS_SVC_ATTR_FWMARK]          = { .type = NLA_U32 },
2773         [IPVS_SVC_ATTR_SCHED_NAME]      = { .type = NLA_NUL_STRING,
2774                                             .len = IP_VS_SCHEDNAME_MAXLEN },
2775         [IPVS_SVC_ATTR_PE_NAME]         = { .type = NLA_NUL_STRING,
2776                                             .len = IP_VS_PENAME_MAXLEN },
2777         [IPVS_SVC_ATTR_FLAGS]           = { .type = NLA_BINARY,
2778                                             .len = sizeof(struct ip_vs_flags) },
2779         [IPVS_SVC_ATTR_TIMEOUT]         = { .type = NLA_U32 },
2780         [IPVS_SVC_ATTR_NETMASK]         = { .type = NLA_U32 },
2781         [IPVS_SVC_ATTR_STATS]           = { .type = NLA_NESTED },
2782 };
2783
2784 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DEST */
2785 static const struct nla_policy ip_vs_dest_policy[IPVS_DEST_ATTR_MAX + 1] = {
2786         [IPVS_DEST_ATTR_ADDR]           = { .type = NLA_BINARY,
2787                                             .len = sizeof(union nf_inet_addr) },
2788         [IPVS_DEST_ATTR_PORT]           = { .type = NLA_U16 },
2789         [IPVS_DEST_ATTR_FWD_METHOD]     = { .type = NLA_U32 },
2790         [IPVS_DEST_ATTR_WEIGHT]         = { .type = NLA_U32 },
2791         [IPVS_DEST_ATTR_U_THRESH]       = { .type = NLA_U32 },
2792         [IPVS_DEST_ATTR_L_THRESH]       = { .type = NLA_U32 },
2793         [IPVS_DEST_ATTR_ACTIVE_CONNS]   = { .type = NLA_U32 },
2794         [IPVS_DEST_ATTR_INACT_CONNS]    = { .type = NLA_U32 },
2795         [IPVS_DEST_ATTR_PERSIST_CONNS]  = { .type = NLA_U32 },
2796         [IPVS_DEST_ATTR_STATS]          = { .type = NLA_NESTED },
2797         [IPVS_DEST_ATTR_ADDR_FAMILY]    = { .type = NLA_U16 },
2798 };
2799
2800 static int ip_vs_genl_fill_stats(struct sk_buff *skb, int container_type,
2801                                  struct ip_vs_stats *stats)
2802 {
2803         struct ip_vs_stats_user ustats;
2804         struct nlattr *nl_stats = nla_nest_start(skb, container_type);
2805         if (!nl_stats)
2806                 return -EMSGSIZE;
2807
2808         ip_vs_copy_stats(&ustats, stats);
2809
2810         if (nla_put_u32(skb, IPVS_STATS_ATTR_CONNS, ustats.conns) ||
2811             nla_put_u32(skb, IPVS_STATS_ATTR_INPKTS, ustats.inpkts) ||
2812             nla_put_u32(skb, IPVS_STATS_ATTR_OUTPKTS, ustats.outpkts) ||
2813             nla_put_u64(skb, IPVS_STATS_ATTR_INBYTES, ustats.inbytes) ||
2814             nla_put_u64(skb, IPVS_STATS_ATTR_OUTBYTES, ustats.outbytes) ||
2815             nla_put_u32(skb, IPVS_STATS_ATTR_CPS, ustats.cps) ||
2816             nla_put_u32(skb, IPVS_STATS_ATTR_INPPS, ustats.inpps) ||
2817             nla_put_u32(skb, IPVS_STATS_ATTR_OUTPPS, ustats.outpps) ||
2818             nla_put_u32(skb, IPVS_STATS_ATTR_INBPS, ustats.inbps) ||
2819             nla_put_u32(skb, IPVS_STATS_ATTR_OUTBPS, ustats.outbps))
2820                 goto nla_put_failure;
2821         nla_nest_end(skb, nl_stats);
2822
2823         return 0;
2824
2825 nla_put_failure:
2826         nla_nest_cancel(skb, nl_stats);
2827         return -EMSGSIZE;
2828 }
2829
2830 static int ip_vs_genl_fill_service(struct sk_buff *skb,
2831                                    struct ip_vs_service *svc)
2832 {
2833         struct ip_vs_scheduler *sched;
2834         struct ip_vs_pe *pe;
2835         struct nlattr *nl_service;
2836         struct ip_vs_flags flags = { .flags = svc->flags,
2837                                      .mask = ~0 };
2838
2839         nl_service = nla_nest_start(skb, IPVS_CMD_ATTR_SERVICE);
2840         if (!nl_service)
2841                 return -EMSGSIZE;
2842
2843         if (nla_put_u16(skb, IPVS_SVC_ATTR_AF, svc->af))
2844                 goto nla_put_failure;
2845         if (svc->fwmark) {
2846                 if (nla_put_u32(skb, IPVS_SVC_ATTR_FWMARK, svc->fwmark))
2847                         goto nla_put_failure;
2848         } else {
2849                 if (nla_put_u16(skb, IPVS_SVC_ATTR_PROTOCOL, svc->protocol) ||
2850                     nla_put(skb, IPVS_SVC_ATTR_ADDR, sizeof(svc->addr), &svc->addr) ||
2851                     nla_put_be16(skb, IPVS_SVC_ATTR_PORT, svc->port))
2852                         goto nla_put_failure;
2853         }
2854
2855         sched = rcu_dereference_protected(svc->scheduler, 1);
2856         pe = rcu_dereference_protected(svc->pe, 1);
2857         if (nla_put_string(skb, IPVS_SVC_ATTR_SCHED_NAME, sched->name) ||
2858             (pe && nla_put_string(skb, IPVS_SVC_ATTR_PE_NAME, pe->name)) ||
2859             nla_put(skb, IPVS_SVC_ATTR_FLAGS, sizeof(flags), &flags) ||
2860             nla_put_u32(skb, IPVS_SVC_ATTR_TIMEOUT, svc->timeout / HZ) ||
2861             nla_put_be32(skb, IPVS_SVC_ATTR_NETMASK, svc->netmask))
2862                 goto nla_put_failure;
2863         if (ip_vs_genl_fill_stats(skb, IPVS_SVC_ATTR_STATS, &svc->stats))
2864                 goto nla_put_failure;
2865
2866         nla_nest_end(skb, nl_service);
2867
2868         return 0;
2869
2870 nla_put_failure:
2871         nla_nest_cancel(skb, nl_service);
2872         return -EMSGSIZE;
2873 }
2874
2875 static int ip_vs_genl_dump_service(struct sk_buff *skb,
2876                                    struct ip_vs_service *svc,
2877                                    struct netlink_callback *cb)
2878 {
2879         void *hdr;
2880
2881         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
2882                           &ip_vs_genl_family, NLM_F_MULTI,
2883                           IPVS_CMD_NEW_SERVICE);
2884         if (!hdr)
2885                 return -EMSGSIZE;
2886
2887         if (ip_vs_genl_fill_service(skb, svc) < 0)
2888                 goto nla_put_failure;
2889
2890         genlmsg_end(skb, hdr);
2891         return 0;
2892
2893 nla_put_failure:
2894         genlmsg_cancel(skb, hdr);
2895         return -EMSGSIZE;
2896 }
2897
2898 static int ip_vs_genl_dump_services(struct sk_buff *skb,
2899                                     struct netlink_callback *cb)
2900 {
2901         int idx = 0, i;
2902         int start = cb->args[0];
2903         struct ip_vs_service *svc;
2904         struct net *net = skb_sknet(skb);
2905
2906         mutex_lock(&__ip_vs_mutex);
2907         for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) {
2908                 hlist_for_each_entry(svc, &ip_vs_svc_table[i], s_list) {
2909                         if (++idx <= start || !net_eq(svc->net, net))
2910                                 continue;
2911                         if (ip_vs_genl_dump_service(skb, svc, cb) < 0) {
2912                                 idx--;
2913                                 goto nla_put_failure;
2914                         }
2915                 }
2916         }
2917
2918         for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) {
2919                 hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[i], f_list) {
2920                         if (++idx <= start || !net_eq(svc->net, net))
2921                                 continue;
2922                         if (ip_vs_genl_dump_service(skb, svc, cb) < 0) {
2923                                 idx--;
2924                                 goto nla_put_failure;
2925                         }
2926                 }
2927         }
2928
2929 nla_put_failure:
2930         mutex_unlock(&__ip_vs_mutex);
2931         cb->args[0] = idx;
2932
2933         return skb->len;
2934 }
2935
2936 static int ip_vs_genl_parse_service(struct net *net,
2937                                     struct ip_vs_service_user_kern *usvc,
2938                                     struct nlattr *nla, int full_entry,
2939                                     struct ip_vs_service **ret_svc)
2940 {
2941         struct nlattr *attrs[IPVS_SVC_ATTR_MAX + 1];
2942         struct nlattr *nla_af, *nla_port, *nla_fwmark, *nla_protocol, *nla_addr;
2943         struct ip_vs_service *svc;
2944
2945         /* Parse mandatory identifying service fields first */
2946         if (nla == NULL ||
2947             nla_parse_nested(attrs, IPVS_SVC_ATTR_MAX, nla, ip_vs_svc_policy))
2948                 return -EINVAL;
2949
2950         nla_af          = attrs[IPVS_SVC_ATTR_AF];
2951         nla_protocol    = attrs[IPVS_SVC_ATTR_PROTOCOL];
2952         nla_addr        = attrs[IPVS_SVC_ATTR_ADDR];
2953         nla_port        = attrs[IPVS_SVC_ATTR_PORT];
2954         nla_fwmark      = attrs[IPVS_SVC_ATTR_FWMARK];
2955
2956         if (!(nla_af && (nla_fwmark || (nla_port && nla_protocol && nla_addr))))
2957                 return -EINVAL;
2958
2959         memset(usvc, 0, sizeof(*usvc));
2960
2961         usvc->af = nla_get_u16(nla_af);
2962 #ifdef CONFIG_IP_VS_IPV6
2963         if (usvc->af != AF_INET && usvc->af != AF_INET6)
2964 #else
2965         if (usvc->af != AF_INET)
2966 #endif
2967                 return -EAFNOSUPPORT;
2968
2969         if (nla_fwmark) {
2970                 usvc->protocol = IPPROTO_TCP;
2971                 usvc->fwmark = nla_get_u32(nla_fwmark);
2972         } else {
2973                 usvc->protocol = nla_get_u16(nla_protocol);
2974                 nla_memcpy(&usvc->addr, nla_addr, sizeof(usvc->addr));
2975                 usvc->port = nla_get_be16(nla_port);
2976                 usvc->fwmark = 0;
2977         }
2978
2979         rcu_read_lock();
2980         if (usvc->fwmark)
2981                 svc = __ip_vs_svc_fwm_find(net, usvc->af, usvc->fwmark);
2982         else
2983                 svc = __ip_vs_service_find(net, usvc->af, usvc->protocol,
2984                                            &usvc->addr, usvc->port);
2985         rcu_read_unlock();
2986         *ret_svc = svc;
2987
2988         /* If a full entry was requested, check for the additional fields */
2989         if (full_entry) {
2990                 struct nlattr *nla_sched, *nla_flags, *nla_pe, *nla_timeout,
2991                               *nla_netmask;
2992                 struct ip_vs_flags flags;
2993
2994                 nla_sched = attrs[IPVS_SVC_ATTR_SCHED_NAME];
2995                 nla_pe = attrs[IPVS_SVC_ATTR_PE_NAME];
2996                 nla_flags = attrs[IPVS_SVC_ATTR_FLAGS];
2997                 nla_timeout = attrs[IPVS_SVC_ATTR_TIMEOUT];
2998                 nla_netmask = attrs[IPVS_SVC_ATTR_NETMASK];
2999
3000                 if (!(nla_sched && nla_flags && nla_timeout && nla_netmask))
3001                         return -EINVAL;
3002
3003                 nla_memcpy(&flags, nla_flags, sizeof(flags));
3004
3005                 /* prefill flags from service if it already exists */
3006                 if (svc)
3007                         usvc->flags = svc->flags;
3008
3009                 /* set new flags from userland */
3010                 usvc->flags = (usvc->flags & ~flags.mask) |
3011                               (flags.flags & flags.mask);
3012                 usvc->sched_name = nla_data(nla_sched);
3013                 usvc->pe_name = nla_pe ? nla_data(nla_pe) : NULL;
3014                 usvc->timeout = nla_get_u32(nla_timeout);
3015                 usvc->netmask = nla_get_be32(nla_netmask);
3016         }
3017
3018         return 0;
3019 }
3020
3021 static struct ip_vs_service *ip_vs_genl_find_service(struct net *net,
3022                                                      struct nlattr *nla)
3023 {
3024         struct ip_vs_service_user_kern usvc;
3025         struct ip_vs_service *svc;
3026         int ret;
3027
3028         ret = ip_vs_genl_parse_service(net, &usvc, nla, 0, &svc);
3029         return ret ? ERR_PTR(ret) : svc;
3030 }
3031
3032 static int ip_vs_genl_fill_dest(struct sk_buff *skb, struct ip_vs_dest *dest)
3033 {
3034         struct nlattr *nl_dest;
3035
3036         nl_dest = nla_nest_start(skb, IPVS_CMD_ATTR_DEST);
3037         if (!nl_dest)
3038                 return -EMSGSIZE;
3039
3040         if (nla_put(skb, IPVS_DEST_ATTR_ADDR, sizeof(dest->addr), &dest->addr) ||
3041             nla_put_be16(skb, IPVS_DEST_ATTR_PORT, dest->port) ||
3042             nla_put_u32(skb, IPVS_DEST_ATTR_FWD_METHOD,
3043                         (atomic_read(&dest->conn_flags) &
3044                          IP_VS_CONN_F_FWD_MASK)) ||
3045             nla_put_u32(skb, IPVS_DEST_ATTR_WEIGHT,
3046                         atomic_read(&dest->weight)) ||
3047             nla_put_u32(skb, IPVS_DEST_ATTR_U_THRESH, dest->u_threshold) ||
3048             nla_put_u32(skb, IPVS_DEST_ATTR_L_THRESH, dest->l_threshold) ||
3049             nla_put_u32(skb, IPVS_DEST_ATTR_ACTIVE_CONNS,
3050                         atomic_read(&dest->activeconns)) ||
3051             nla_put_u32(skb, IPVS_DEST_ATTR_INACT_CONNS,
3052                         atomic_read(&dest->inactconns)) ||
3053             nla_put_u32(skb, IPVS_DEST_ATTR_PERSIST_CONNS,
3054                         atomic_read(&dest->persistconns)) ||
3055             nla_put_u16(skb, IPVS_DEST_ATTR_ADDR_FAMILY, dest->af))
3056                 goto nla_put_failure;
3057         if (ip_vs_genl_fill_stats(skb, IPVS_DEST_ATTR_STATS, &dest->stats))
3058                 goto nla_put_failure;
3059
3060         nla_nest_end(skb, nl_dest);
3061
3062         return 0;
3063
3064 nla_put_failure:
3065         nla_nest_cancel(skb, nl_dest);
3066         return -EMSGSIZE;
3067 }
3068
3069 static int ip_vs_genl_dump_dest(struct sk_buff *skb, struct ip_vs_dest *dest,
3070                                 struct netlink_callback *cb)
3071 {
3072         void *hdr;
3073
3074         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3075                           &ip_vs_genl_family, NLM_F_MULTI,
3076                           IPVS_CMD_NEW_DEST);
3077         if (!hdr)
3078                 return -EMSGSIZE;
3079
3080         if (ip_vs_genl_fill_dest(skb, dest) < 0)
3081                 goto nla_put_failure;
3082
3083         genlmsg_end(skb, hdr);
3084         return 0;
3085
3086 nla_put_failure:
3087         genlmsg_cancel(skb, hdr);
3088         return -EMSGSIZE;
3089 }
3090
3091 static int ip_vs_genl_dump_dests(struct sk_buff *skb,
3092                                  struct netlink_callback *cb)
3093 {
3094         int idx = 0;
3095         int start = cb->args[0];
3096         struct ip_vs_service *svc;
3097         struct ip_vs_dest *dest;
3098         struct nlattr *attrs[IPVS_CMD_ATTR_MAX + 1];
3099         struct net *net = skb_sknet(skb);
3100
3101         mutex_lock(&__ip_vs_mutex);
3102
3103         /* Try to find the service for which to dump destinations */
3104         if (nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs,
3105                         IPVS_CMD_ATTR_MAX, ip_vs_cmd_policy))
3106                 goto out_err;
3107
3108
3109         svc = ip_vs_genl_find_service(net, attrs[IPVS_CMD_ATTR_SERVICE]);
3110         if (IS_ERR(svc) || svc == NULL)
3111                 goto out_err;
3112
3113         /* Dump the destinations */
3114         list_for_each_entry(dest, &svc->destinations, n_list) {
3115                 if (++idx <= start)
3116                         continue;
3117                 if (ip_vs_genl_dump_dest(skb, dest, cb) < 0) {
3118                         idx--;
3119                         goto nla_put_failure;
3120                 }
3121         }
3122
3123 nla_put_failure:
3124         cb->args[0] = idx;
3125
3126 out_err:
3127         mutex_unlock(&__ip_vs_mutex);
3128
3129         return skb->len;
3130 }
3131
3132 static int ip_vs_genl_parse_dest(struct ip_vs_dest_user_kern *udest,
3133                                  struct nlattr *nla, int full_entry)
3134 {
3135         struct nlattr *attrs[IPVS_DEST_ATTR_MAX + 1];
3136         struct nlattr *nla_addr, *nla_port;
3137         struct nlattr *nla_addr_family;
3138
3139         /* Parse mandatory identifying destination fields first */
3140         if (nla == NULL ||
3141             nla_parse_nested(attrs, IPVS_DEST_ATTR_MAX, nla, ip_vs_dest_policy))
3142                 return -EINVAL;
3143
3144         nla_addr        = attrs[IPVS_DEST_ATTR_ADDR];
3145         nla_port        = attrs[IPVS_DEST_ATTR_PORT];
3146         nla_addr_family = attrs[IPVS_DEST_ATTR_ADDR_FAMILY];
3147
3148         if (!(nla_addr && nla_port))
3149                 return -EINVAL;
3150
3151         memset(udest, 0, sizeof(*udest));
3152
3153         nla_memcpy(&udest->addr, nla_addr, sizeof(udest->addr));
3154         udest->port = nla_get_be16(nla_port);
3155
3156         if (nla_addr_family)
3157                 udest->af = nla_get_u16(nla_addr_family);
3158         else
3159                 udest->af = 0;
3160
3161         /* If a full entry was requested, check for the additional fields */
3162         if (full_entry) {
3163                 struct nlattr *nla_fwd, *nla_weight, *nla_u_thresh,
3164                               *nla_l_thresh;
3165
3166                 nla_fwd         = attrs[IPVS_DEST_ATTR_FWD_METHOD];
3167                 nla_weight      = attrs[IPVS_DEST_ATTR_WEIGHT];
3168                 nla_u_thresh    = attrs[IPVS_DEST_ATTR_U_THRESH];
3169                 nla_l_thresh    = attrs[IPVS_DEST_ATTR_L_THRESH];
3170
3171                 if (!(nla_fwd && nla_weight && nla_u_thresh && nla_l_thresh))
3172                         return -EINVAL;
3173
3174                 udest->conn_flags = nla_get_u32(nla_fwd)
3175                                     & IP_VS_CONN_F_FWD_MASK;
3176                 udest->weight = nla_get_u32(nla_weight);
3177                 udest->u_threshold = nla_get_u32(nla_u_thresh);
3178                 udest->l_threshold = nla_get_u32(nla_l_thresh);
3179         }
3180
3181         return 0;
3182 }
3183
3184 static int ip_vs_genl_fill_daemon(struct sk_buff *skb, __u32 state,
3185                                   const char *mcast_ifn, __u32 syncid)
3186 {
3187         struct nlattr *nl_daemon;
3188
3189         nl_daemon = nla_nest_start(skb, IPVS_CMD_ATTR_DAEMON);
3190         if (!nl_daemon)
3191                 return -EMSGSIZE;
3192
3193         if (nla_put_u32(skb, IPVS_DAEMON_ATTR_STATE, state) ||
3194             nla_put_string(skb, IPVS_DAEMON_ATTR_MCAST_IFN, mcast_ifn) ||
3195             nla_put_u32(skb, IPVS_DAEMON_ATTR_SYNC_ID, syncid))
3196                 goto nla_put_failure;
3197         nla_nest_end(skb, nl_daemon);
3198
3199         return 0;
3200
3201 nla_put_failure:
3202         nla_nest_cancel(skb, nl_daemon);
3203         return -EMSGSIZE;
3204 }
3205
3206 static int ip_vs_genl_dump_daemon(struct sk_buff *skb, __u32 state,
3207                                   const char *mcast_ifn, __u32 syncid,
3208                                   struct netlink_callback *cb)
3209 {
3210         void *hdr;
3211         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3212                           &ip_vs_genl_family, NLM_F_MULTI,
3213                           IPVS_CMD_NEW_DAEMON);
3214         if (!hdr)
3215                 return -EMSGSIZE;
3216
3217         if (ip_vs_genl_fill_daemon(skb, state, mcast_ifn, syncid))
3218                 goto nla_put_failure;
3219
3220         genlmsg_end(skb, hdr);
3221         return 0;
3222
3223 nla_put_failure:
3224         genlmsg_cancel(skb, hdr);
3225         return -EMSGSIZE;
3226 }
3227
3228 static int ip_vs_genl_dump_daemons(struct sk_buff *skb,
3229                                    struct netlink_callback *cb)
3230 {
3231         struct net *net = skb_sknet(skb);
3232         struct netns_ipvs *ipvs = net_ipvs(net);
3233
3234         mutex_lock(&ipvs->sync_mutex);
3235         if ((ipvs->sync_state & IP_VS_STATE_MASTER) && !cb->args[0]) {
3236                 if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_MASTER,
3237                                            ipvs->master_mcast_ifn,
3238                                            ipvs->master_syncid, cb) < 0)
3239                         goto nla_put_failure;
3240
3241                 cb->args[0] = 1;
3242         }
3243
3244         if ((ipvs->sync_state & IP_VS_STATE_BACKUP) && !cb->args[1]) {
3245                 if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_BACKUP,
3246                                            ipvs->backup_mcast_ifn,
3247                                            ipvs->backup_syncid, cb) < 0)
3248                         goto nla_put_failure;
3249
3250                 cb->args[1] = 1;
3251         }
3252
3253 nla_put_failure:
3254         mutex_unlock(&ipvs->sync_mutex);
3255
3256         return skb->len;
3257 }
3258
3259 static int ip_vs_genl_new_daemon(struct net *net, struct nlattr **attrs)
3260 {
3261         if (!(attrs[IPVS_DAEMON_ATTR_STATE] &&
3262               attrs[IPVS_DAEMON_ATTR_MCAST_IFN] &&
3263               attrs[IPVS_DAEMON_ATTR_SYNC_ID]))
3264                 return -EINVAL;
3265
3266         /* The synchronization protocol is incompatible with mixed family
3267          * services
3268          */
3269         if (net_ipvs(net)->mixed_address_family_dests > 0)
3270                 return -EINVAL;
3271
3272         return start_sync_thread(net,
3273                                  nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]),
3274                                  nla_data(attrs[IPVS_DAEMON_ATTR_MCAST_IFN]),
3275                                  nla_get_u32(attrs[IPVS_DAEMON_ATTR_SYNC_ID]));
3276 }
3277
3278 static int ip_vs_genl_del_daemon(struct net *net, struct nlattr **attrs)
3279 {
3280         if (!attrs[IPVS_DAEMON_ATTR_STATE])
3281                 return -EINVAL;
3282
3283         return stop_sync_thread(net,
3284                                 nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]));
3285 }
3286
3287 static int ip_vs_genl_set_config(struct net *net, struct nlattr **attrs)
3288 {
3289         struct ip_vs_timeout_user t;
3290
3291         __ip_vs_get_timeouts(net, &t);
3292
3293         if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP])
3294                 t.tcp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP]);
3295
3296         if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN])
3297                 t.tcp_fin_timeout =
3298                         nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN]);
3299
3300         if (attrs[IPVS_CMD_ATTR_TIMEOUT_UDP])
3301                 t.udp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_UDP]);
3302
3303         return ip_vs_set_timeout(net, &t);
3304 }
3305
3306 static int ip_vs_genl_set_daemon(struct sk_buff *skb, struct genl_info *info)
3307 {
3308         int ret = 0, cmd;
3309         struct net *net;
3310         struct netns_ipvs *ipvs;
3311
3312         net = skb_sknet(skb);
3313         ipvs = net_ipvs(net);
3314         cmd = info->genlhdr->cmd;
3315
3316         if (cmd == IPVS_CMD_NEW_DAEMON || cmd == IPVS_CMD_DEL_DAEMON) {
3317                 struct nlattr *daemon_attrs[IPVS_DAEMON_ATTR_MAX + 1];
3318
3319                 mutex_lock(&ipvs->sync_mutex);
3320                 if (!info->attrs[IPVS_CMD_ATTR_DAEMON] ||
3321                     nla_parse_nested(daemon_attrs, IPVS_DAEMON_ATTR_MAX,
3322                                      info->attrs[IPVS_CMD_ATTR_DAEMON],
3323                                      ip_vs_daemon_policy)) {
3324                         ret = -EINVAL;
3325                         goto out;
3326                 }
3327
3328                 if (cmd == IPVS_CMD_NEW_DAEMON)
3329                         ret = ip_vs_genl_new_daemon(net, daemon_attrs);
3330                 else
3331                         ret = ip_vs_genl_del_daemon(net, daemon_attrs);
3332 out:
3333                 mutex_unlock(&ipvs->sync_mutex);
3334         }
3335         return ret;
3336 }
3337
3338 static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info)
3339 {
3340         struct ip_vs_service *svc = NULL;
3341         struct ip_vs_service_user_kern usvc;
3342         struct ip_vs_dest_user_kern udest;
3343         int ret = 0, cmd;
3344         int need_full_svc = 0, need_full_dest = 0;
3345         struct net *net;
3346
3347         net = skb_sknet(skb);
3348         cmd = info->genlhdr->cmd;
3349
3350         mutex_lock(&__ip_vs_mutex);
3351
3352         if (cmd == IPVS_CMD_FLUSH) {
3353                 ret = ip_vs_flush(net, false);
3354                 goto out;
3355         } else if (cmd == IPVS_CMD_SET_CONFIG) {
3356                 ret = ip_vs_genl_set_config(net, info->attrs);
3357                 goto out;
3358         } else if (cmd == IPVS_CMD_ZERO &&
3359                    !info->attrs[IPVS_CMD_ATTR_SERVICE]) {
3360                 ret = ip_vs_zero_all(net);
3361                 goto out;
3362         }
3363
3364         /* All following commands require a service argument, so check if we
3365          * received a valid one. We need a full service specification when
3366          * adding / editing a service. Only identifying members otherwise. */
3367         if (cmd == IPVS_CMD_NEW_SERVICE || cmd == IPVS_CMD_SET_SERVICE)
3368                 need_full_svc = 1;
3369
3370         ret = ip_vs_genl_parse_service(net, &usvc,
3371                                        info->attrs[IPVS_CMD_ATTR_SERVICE],
3372                                        need_full_svc, &svc);
3373         if (ret)
3374                 goto out;
3375
3376         /* Unless we're adding a new service, the service must already exist */
3377         if ((cmd != IPVS_CMD_NEW_SERVICE) && (svc == NULL)) {
3378                 ret = -ESRCH;
3379                 goto out;
3380         }
3381
3382         /* Destination commands require a valid destination argument. For
3383          * adding / editing a destination, we need a full destination
3384          * specification. */
3385         if (cmd == IPVS_CMD_NEW_DEST || cmd == IPVS_CMD_SET_DEST ||
3386             cmd == IPVS_CMD_DEL_DEST) {
3387                 if (cmd != IPVS_CMD_DEL_DEST)
3388                         need_full_dest = 1;
3389
3390                 ret = ip_vs_genl_parse_dest(&udest,
3391                                             info->attrs[IPVS_CMD_ATTR_DEST],
3392                                             need_full_dest);
3393                 if (ret)
3394                         goto out;
3395
3396                 /* Old protocols did not allow the user to specify address
3397                  * family, so we set it to zero instead.  We also didn't
3398                  * allow heterogeneous pools in the old code, so it's safe
3399                  * to assume that this will have the same address family as
3400                  * the service.
3401                  */
3402                 if (udest.af == 0)
3403                         udest.af = svc->af;
3404
3405                 if (udest.af != svc->af && cmd != IPVS_CMD_DEL_DEST) {
3406                         /* The synchronization protocol is incompatible
3407                          * with mixed family services
3408                          */
3409                         if (net_ipvs(net)->sync_state) {
3410                                 ret = -EINVAL;
3411                                 goto out;
3412                         }
3413
3414                         /* Which connection types do we support? */
3415                         switch (udest.conn_flags) {
3416                         case IP_VS_CONN_F_TUNNEL:
3417                                 /* We are able to forward this */
3418                                 break;
3419                         default:
3420                                 ret = -EINVAL;
3421                                 goto out;
3422                         }
3423                 }
3424         }
3425
3426         switch (cmd) {
3427         case IPVS_CMD_NEW_SERVICE:
3428                 if (svc == NULL)
3429                         ret = ip_vs_add_service(net, &usvc, &svc);
3430                 else
3431                         ret = -EEXIST;
3432                 break;
3433         case IPVS_CMD_SET_SERVICE:
3434                 ret = ip_vs_edit_service(svc, &usvc);
3435                 break;
3436         case IPVS_CMD_DEL_SERVICE:
3437                 ret = ip_vs_del_service(svc);
3438                 /* do not use svc, it can be freed */
3439                 break;
3440         case IPVS_CMD_NEW_DEST:
3441                 ret = ip_vs_add_dest(svc, &udest);
3442                 break;
3443         case IPVS_CMD_SET_DEST:
3444                 ret = ip_vs_edit_dest(svc, &udest);
3445                 break;
3446         case IPVS_CMD_DEL_DEST:
3447                 ret = ip_vs_del_dest(svc, &udest);
3448                 break;
3449         case IPVS_CMD_ZERO:
3450                 ret = ip_vs_zero_service(svc);
3451                 break;
3452         default:
3453                 ret = -EINVAL;
3454         }
3455
3456 out:
3457         mutex_unlock(&__ip_vs_mutex);
3458
3459         return ret;
3460 }
3461
3462 static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info)
3463 {
3464         struct sk_buff *msg;
3465         void *reply;
3466         int ret, cmd, reply_cmd;
3467         struct net *net;
3468
3469         net = skb_sknet(skb);
3470         cmd = info->genlhdr->cmd;
3471
3472         if (cmd == IPVS_CMD_GET_SERVICE)
3473                 reply_cmd = IPVS_CMD_NEW_SERVICE;
3474         else if (cmd == IPVS_CMD_GET_INFO)
3475                 reply_cmd = IPVS_CMD_SET_INFO;
3476         else if (cmd == IPVS_CMD_GET_CONFIG)
3477                 reply_cmd = IPVS_CMD_SET_CONFIG;
3478         else {
3479                 pr_err("unknown Generic Netlink command\n");
3480                 return -EINVAL;
3481         }
3482
3483         msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
3484         if (!msg)
3485                 return -ENOMEM;
3486
3487         mutex_lock(&__ip_vs_mutex);
3488
3489         reply = genlmsg_put_reply(msg, info, &ip_vs_genl_family, 0, reply_cmd);
3490         if (reply == NULL)
3491                 goto nla_put_failure;
3492
3493         switch (cmd) {
3494         case IPVS_CMD_GET_SERVICE:
3495         {
3496                 struct ip_vs_service *svc;
3497
3498                 svc = ip_vs_genl_find_service(net,
3499                                               info->attrs[IPVS_CMD_ATTR_SERVICE]);
3500                 if (IS_ERR(svc)) {
3501                         ret = PTR_ERR(svc);
3502                         goto out_err;
3503                 } else if (svc) {
3504                         ret = ip_vs_genl_fill_service(msg, svc);
3505                         if (ret)
3506                                 goto nla_put_failure;
3507                 } else {
3508                         ret = -ESRCH;
3509                         goto out_err;
3510                 }
3511
3512                 break;
3513         }
3514
3515         case IPVS_CMD_GET_CONFIG:
3516         {
3517                 struct ip_vs_timeout_user t;
3518
3519                 __ip_vs_get_timeouts(net, &t);
3520 #ifdef CONFIG_IP_VS_PROTO_TCP
3521                 if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP,
3522                                 t.tcp_timeout) ||
3523                     nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP_FIN,
3524                                 t.tcp_fin_timeout))
3525                         goto nla_put_failure;
3526 #endif
3527 #ifdef CONFIG_IP_VS_PROTO_UDP
3528                 if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_UDP, t.udp_timeout))
3529                         goto nla_put_failure;
3530 #endif
3531
3532                 break;
3533         }
3534
3535         case IPVS_CMD_GET_INFO:
3536                 if (nla_put_u32(msg, IPVS_INFO_ATTR_VERSION,
3537                                 IP_VS_VERSION_CODE) ||
3538                     nla_put_u32(msg, IPVS_INFO_ATTR_CONN_TAB_SIZE,
3539                                 ip_vs_conn_tab_size))
3540                         goto nla_put_failure;
3541                 break;
3542         }
3543
3544         genlmsg_end(msg, reply);
3545         ret = genlmsg_reply(msg, info);
3546         goto out;
3547
3548 nla_put_failure:
3549         pr_err("not enough space in Netlink message\n");
3550         ret = -EMSGSIZE;
3551
3552 out_err:
3553         nlmsg_free(msg);
3554 out:
3555         mutex_unlock(&__ip_vs_mutex);
3556
3557         return ret;
3558 }
3559
3560
3561 static const struct genl_ops ip_vs_genl_ops[] = {
3562         {
3563                 .cmd    = IPVS_CMD_NEW_SERVICE,
3564                 .flags  = GENL_ADMIN_PERM,
3565                 .policy = ip_vs_cmd_policy,
3566                 .doit   = ip_vs_genl_set_cmd,
3567         },
3568         {
3569                 .cmd    = IPVS_CMD_SET_SERVICE,
3570                 .flags  = GENL_ADMIN_PERM,
3571                 .policy = ip_vs_cmd_policy,
3572                 .doit   = ip_vs_genl_set_cmd,
3573         },
3574         {
3575                 .cmd    = IPVS_CMD_DEL_SERVICE,
3576                 .flags  = GENL_ADMIN_PERM,
3577                 .policy = ip_vs_cmd_policy,
3578                 .doit   = ip_vs_genl_set_cmd,
3579         },
3580         {
3581                 .cmd    = IPVS_CMD_GET_SERVICE,
3582                 .flags  = GENL_ADMIN_PERM,
3583                 .doit   = ip_vs_genl_get_cmd,
3584                 .dumpit = ip_vs_genl_dump_services,
3585                 .policy = ip_vs_cmd_policy,
3586         },
3587         {
3588                 .cmd    = IPVS_CMD_NEW_DEST,
3589                 .flags  = GENL_ADMIN_PERM,
3590                 .policy = ip_vs_cmd_policy,
3591                 .doit   = ip_vs_genl_set_cmd,
3592         },
3593         {
3594                 .cmd    = IPVS_CMD_SET_DEST,
3595                 .flags  = GENL_ADMIN_PERM,
3596                 .policy = ip_vs_cmd_policy,
3597                 .doit   = ip_vs_genl_set_cmd,
3598         },
3599         {
3600                 .cmd    = IPVS_CMD_DEL_DEST,
3601                 .flags  = GENL_ADMIN_PERM,
3602                 .policy = ip_vs_cmd_policy,
3603                 .doit   = ip_vs_genl_set_cmd,
3604         },
3605         {
3606                 .cmd    = IPVS_CMD_GET_DEST,
3607                 .flags  = GENL_ADMIN_PERM,
3608                 .policy = ip_vs_cmd_policy,
3609                 .dumpit = ip_vs_genl_dump_dests,
3610         },
3611         {
3612                 .cmd    = IPVS_CMD_NEW_DAEMON,
3613                 .flags  = GENL_ADMIN_PERM,
3614                 .policy = ip_vs_cmd_policy,
3615                 .doit   = ip_vs_genl_set_daemon,
3616         },
3617         {
3618                 .cmd    = IPVS_CMD_DEL_DAEMON,
3619                 .flags  = GENL_ADMIN_PERM,
3620                 .policy = ip_vs_cmd_policy,
3621                 .doit   = ip_vs_genl_set_daemon,
3622         },
3623         {
3624                 .cmd    = IPVS_CMD_GET_DAEMON,
3625                 .flags  = GENL_ADMIN_PERM,
3626                 .dumpit = ip_vs_genl_dump_daemons,
3627         },
3628         {
3629                 .cmd    = IPVS_CMD_SET_CONFIG,
3630                 .flags  = GENL_ADMIN_PERM,
3631                 .policy = ip_vs_cmd_policy,
3632                 .doit   = ip_vs_genl_set_cmd,
3633         },
3634         {
3635                 .cmd    = IPVS_CMD_GET_CONFIG,
3636                 .flags  = GENL_ADMIN_PERM,
3637                 .doit   = ip_vs_genl_get_cmd,
3638         },
3639         {
3640                 .cmd    = IPVS_CMD_GET_INFO,
3641                 .flags  = GENL_ADMIN_PERM,
3642                 .doit   = ip_vs_genl_get_cmd,
3643         },
3644         {
3645                 .cmd    = IPVS_CMD_ZERO,
3646                 .flags  = GENL_ADMIN_PERM,
3647                 .policy = ip_vs_cmd_policy,
3648                 .doit   = ip_vs_genl_set_cmd,
3649         },
3650         {
3651                 .cmd    = IPVS_CMD_FLUSH,
3652                 .flags  = GENL_ADMIN_PERM,
3653                 .doit   = ip_vs_genl_set_cmd,
3654         },
3655 };
3656
3657 static int __init ip_vs_genl_register(void)
3658 {
3659         return genl_register_family_with_ops(&ip_vs_genl_family,
3660                                              ip_vs_genl_ops);
3661 }
3662
3663 static void ip_vs_genl_unregister(void)
3664 {
3665         genl_unregister_family(&ip_vs_genl_family);
3666 }
3667
3668 /* End of Generic Netlink interface definitions */
3669
3670 /*
3671  * per netns intit/exit func.
3672  */
3673 #ifdef CONFIG_SYSCTL
3674 static int __net_init ip_vs_control_net_init_sysctl(struct net *net)
3675 {
3676         int idx;
3677         struct netns_ipvs *ipvs = net_ipvs(net);
3678         struct ctl_table *tbl;
3679
3680         atomic_set(&ipvs->dropentry, 0);
3681         spin_lock_init(&ipvs->dropentry_lock);
3682         spin_lock_init(&ipvs->droppacket_lock);
3683         spin_lock_init(&ipvs->securetcp_lock);
3684
3685         if (!net_eq(net, &init_net)) {
3686                 tbl = kmemdup(vs_vars, sizeof(vs_vars), GFP_KERNEL);
3687                 if (tbl == NULL)
3688                         return -ENOMEM;
3689
3690                 /* Don't export sysctls to unprivileged users */
3691                 if (net->user_ns != &init_user_ns)
3692                         tbl[0].procname = NULL;
3693         } else
3694                 tbl = vs_vars;
3695         /* Initialize sysctl defaults */
3696         idx = 0;
3697         ipvs->sysctl_amemthresh = 1024;
3698         tbl[idx++].data = &ipvs->sysctl_amemthresh;
3699         ipvs->sysctl_am_droprate = 10;
3700         tbl[idx++].data = &ipvs->sysctl_am_droprate;
3701         tbl[idx++].data = &ipvs->sysctl_drop_entry;
3702         tbl[idx++].data = &ipvs->sysctl_drop_packet;
3703 #ifdef CONFIG_IP_VS_NFCT
3704         tbl[idx++].data = &ipvs->sysctl_conntrack;
3705 #endif
3706         tbl[idx++].data = &ipvs->sysctl_secure_tcp;
3707         ipvs->sysctl_snat_reroute = 1;
3708         tbl[idx++].data = &ipvs->sysctl_snat_reroute;
3709         ipvs->sysctl_sync_ver = 1;
3710         tbl[idx++].data = &ipvs->sysctl_sync_ver;
3711         ipvs->sysctl_sync_ports = 1;
3712         tbl[idx++].data = &ipvs->sysctl_sync_ports;
3713         tbl[idx++].data = &ipvs->sysctl_sync_persist_mode;
3714         ipvs->sysctl_sync_qlen_max = nr_free_buffer_pages() / 32;
3715         tbl[idx++].data = &ipvs->sysctl_sync_qlen_max;
3716         ipvs->sysctl_sync_sock_size = 0;
3717         tbl[idx++].data = &ipvs->sysctl_sync_sock_size;
3718         tbl[idx++].data = &ipvs->sysctl_cache_bypass;
3719         tbl[idx++].data = &ipvs->sysctl_expire_nodest_conn;
3720         tbl[idx++].data = &ipvs->sysctl_sloppy_tcp;
3721         tbl[idx++].data = &ipvs->sysctl_sloppy_sctp;
3722         tbl[idx++].data = &ipvs->sysctl_expire_quiescent_template;
3723         ipvs->sysctl_sync_threshold[0] = DEFAULT_SYNC_THRESHOLD;
3724         ipvs->sysctl_sync_threshold[1] = DEFAULT_SYNC_PERIOD;
3725         tbl[idx].data = &ipvs->sysctl_sync_threshold;
3726         tbl[idx++].maxlen = sizeof(ipvs->sysctl_sync_threshold);
3727         ipvs->sysctl_sync_refresh_period = DEFAULT_SYNC_REFRESH_PERIOD;
3728         tbl[idx++].data = &ipvs->sysctl_sync_refresh_period;
3729         ipvs->sysctl_sync_retries = clamp_t(int, DEFAULT_SYNC_RETRIES, 0, 3);
3730         tbl[idx++].data = &ipvs->sysctl_sync_retries;
3731         tbl[idx++].data = &ipvs->sysctl_nat_icmp_send;
3732         ipvs->sysctl_pmtu_disc = 1;
3733         tbl[idx++].data = &ipvs->sysctl_pmtu_disc;
3734         tbl[idx++].data = &ipvs->sysctl_backup_only;
3735
3736
3737         ipvs->sysctl_hdr = register_net_sysctl(net, "net/ipv4/vs", tbl);
3738         if (ipvs->sysctl_hdr == NULL) {
3739                 if (!net_eq(net, &init_net))
3740                         kfree(tbl);
3741                 return -ENOMEM;
3742         }
3743         ip_vs_start_estimator(net, &ipvs->tot_stats);
3744         ipvs->sysctl_tbl = tbl;
3745         /* Schedule defense work */
3746         INIT_DELAYED_WORK(&ipvs->defense_work, defense_work_handler);
3747         schedule_delayed_work(&ipvs->defense_work, DEFENSE_TIMER_PERIOD);
3748
3749         return 0;
3750 }
3751
3752 static void __net_exit ip_vs_control_net_cleanup_sysctl(struct net *net)
3753 {
3754         struct netns_ipvs *ipvs = net_ipvs(net);
3755
3756         cancel_delayed_work_sync(&ipvs->defense_work);
3757         cancel_work_sync(&ipvs->defense_work.work);
3758         unregister_net_sysctl_table(ipvs->sysctl_hdr);
3759         ip_vs_stop_estimator(net, &ipvs->tot_stats);
3760 }
3761
3762 #else
3763
3764 static int __net_init ip_vs_control_net_init_sysctl(struct net *net) { return 0; }
3765 static void __net_exit ip_vs_control_net_cleanup_sysctl(struct net *net) { }
3766
3767 #endif
3768
3769 static struct notifier_block ip_vs_dst_notifier = {
3770         .notifier_call = ip_vs_dst_event,
3771 };
3772
3773 int __net_init ip_vs_control_net_init(struct net *net)
3774 {
3775         int i, idx;
3776         struct netns_ipvs *ipvs = net_ipvs(net);
3777
3778         /* Initialize rs_table */
3779         for (idx = 0; idx < IP_VS_RTAB_SIZE; idx++)
3780                 INIT_HLIST_HEAD(&ipvs->rs_table[idx]);
3781
3782         INIT_LIST_HEAD(&ipvs->dest_trash);
3783         spin_lock_init(&ipvs->dest_trash_lock);
3784         setup_timer(&ipvs->dest_trash_timer, ip_vs_dest_trash_expire,
3785                     (unsigned long) net);
3786         atomic_set(&ipvs->ftpsvc_counter, 0);
3787         atomic_set(&ipvs->nullsvc_counter, 0);
3788
3789         /* procfs stats */
3790         ipvs->tot_stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
3791         if (!ipvs->tot_stats.cpustats)
3792                 return -ENOMEM;
3793
3794         for_each_possible_cpu(i) {
3795                 struct ip_vs_cpu_stats *ipvs_tot_stats;
3796                 ipvs_tot_stats = per_cpu_ptr(ipvs->tot_stats.cpustats, i);
3797                 u64_stats_init(&ipvs_tot_stats->syncp);
3798         }
3799
3800         spin_lock_init(&ipvs->tot_stats.lock);
3801
3802         proc_create("ip_vs", 0, net->proc_net, &ip_vs_info_fops);
3803         proc_create("ip_vs_stats", 0, net->proc_net, &ip_vs_stats_fops);
3804         proc_create("ip_vs_stats_percpu", 0, net->proc_net,
3805                     &ip_vs_stats_percpu_fops);
3806
3807         if (ip_vs_control_net_init_sysctl(net))
3808                 goto err;
3809
3810         return 0;
3811
3812 err:
3813         free_percpu(ipvs->tot_stats.cpustats);
3814         return -ENOMEM;
3815 }
3816
3817 void __net_exit ip_vs_control_net_cleanup(struct net *net)
3818 {
3819         struct netns_ipvs *ipvs = net_ipvs(net);
3820
3821         ip_vs_trash_cleanup(net);
3822         ip_vs_control_net_cleanup_sysctl(net);
3823         remove_proc_entry("ip_vs_stats_percpu", net->proc_net);
3824         remove_proc_entry("ip_vs_stats", net->proc_net);
3825         remove_proc_entry("ip_vs", net->proc_net);
3826         free_percpu(ipvs->tot_stats.cpustats);
3827 }
3828
3829 int __init ip_vs_register_nl_ioctl(void)
3830 {
3831         int ret;
3832
3833         ret = nf_register_sockopt(&ip_vs_sockopts);
3834         if (ret) {
3835                 pr_err("cannot register sockopt.\n");
3836                 goto err_sock;
3837         }
3838
3839         ret = ip_vs_genl_register();
3840         if (ret) {
3841                 pr_err("cannot register Generic Netlink interface.\n");
3842                 goto err_genl;
3843         }
3844         return 0;
3845
3846 err_genl:
3847         nf_unregister_sockopt(&ip_vs_sockopts);
3848 err_sock:
3849         return ret;
3850 }
3851
3852 void ip_vs_unregister_nl_ioctl(void)
3853 {
3854         ip_vs_genl_unregister();
3855         nf_unregister_sockopt(&ip_vs_sockopts);
3856 }
3857
3858 int __init ip_vs_control_init(void)
3859 {
3860         int idx;
3861         int ret;
3862
3863         EnterFunction(2);
3864
3865         /* Initialize svc_table, ip_vs_svc_fwm_table */
3866         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
3867                 INIT_HLIST_HEAD(&ip_vs_svc_table[idx]);
3868                 INIT_HLIST_HEAD(&ip_vs_svc_fwm_table[idx]);
3869         }
3870
3871         smp_wmb();      /* Do we really need it now ? */
3872
3873         ret = register_netdevice_notifier(&ip_vs_dst_notifier);
3874         if (ret < 0)
3875                 return ret;
3876
3877         LeaveFunction(2);
3878         return 0;
3879 }
3880
3881
3882 void ip_vs_control_cleanup(void)
3883 {
3884         EnterFunction(2);
3885         unregister_netdevice_notifier(&ip_vs_dst_notifier);
3886         LeaveFunction(2);
3887 }