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