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