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