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