Add the rt linux 4.1.3-rt3 as base
[kvmfornfv.git] / kernel / 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         {
1827                 .procname       = "conn_reuse_mode",
1828                 .maxlen         = sizeof(int),
1829                 .mode           = 0644,
1830                 .proc_handler   = proc_dointvec,
1831         },
1832 #ifdef CONFIG_IP_VS_DEBUG
1833         {
1834                 .procname       = "debug_level",
1835                 .data           = &sysctl_ip_vs_debug_level,
1836                 .maxlen         = sizeof(int),
1837                 .mode           = 0644,
1838                 .proc_handler   = proc_dointvec,
1839         },
1840 #endif
1841         { }
1842 };
1843
1844 #endif
1845
1846 #ifdef CONFIG_PROC_FS
1847
1848 struct ip_vs_iter {
1849         struct seq_net_private p;  /* Do not move this, netns depends upon it*/
1850         struct hlist_head *table;
1851         int bucket;
1852 };
1853
1854 /*
1855  *      Write the contents of the VS rule table to a PROCfs file.
1856  *      (It is kept just for backward compatibility)
1857  */
1858 static inline const char *ip_vs_fwd_name(unsigned int flags)
1859 {
1860         switch (flags & IP_VS_CONN_F_FWD_MASK) {
1861         case IP_VS_CONN_F_LOCALNODE:
1862                 return "Local";
1863         case IP_VS_CONN_F_TUNNEL:
1864                 return "Tunnel";
1865         case IP_VS_CONN_F_DROUTE:
1866                 return "Route";
1867         default:
1868                 return "Masq";
1869         }
1870 }
1871
1872
1873 /* Get the Nth entry in the two lists */
1874 static struct ip_vs_service *ip_vs_info_array(struct seq_file *seq, loff_t pos)
1875 {
1876         struct net *net = seq_file_net(seq);
1877         struct ip_vs_iter *iter = seq->private;
1878         int idx;
1879         struct ip_vs_service *svc;
1880
1881         /* look in hash by protocol */
1882         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1883                 hlist_for_each_entry_rcu(svc, &ip_vs_svc_table[idx], s_list) {
1884                         if (net_eq(svc->net, net) && pos-- == 0) {
1885                                 iter->table = ip_vs_svc_table;
1886                                 iter->bucket = idx;
1887                                 return svc;
1888                         }
1889                 }
1890         }
1891
1892         /* keep looking in fwmark */
1893         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1894                 hlist_for_each_entry_rcu(svc, &ip_vs_svc_fwm_table[idx],
1895                                          f_list) {
1896                         if (net_eq(svc->net, net) && pos-- == 0) {
1897                                 iter->table = ip_vs_svc_fwm_table;
1898                                 iter->bucket = idx;
1899                                 return svc;
1900                         }
1901                 }
1902         }
1903
1904         return NULL;
1905 }
1906
1907 static void *ip_vs_info_seq_start(struct seq_file *seq, loff_t *pos)
1908         __acquires(RCU)
1909 {
1910         rcu_read_lock();
1911         return *pos ? ip_vs_info_array(seq, *pos - 1) : SEQ_START_TOKEN;
1912 }
1913
1914
1915 static void *ip_vs_info_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1916 {
1917         struct hlist_node *e;
1918         struct ip_vs_iter *iter;
1919         struct ip_vs_service *svc;
1920
1921         ++*pos;
1922         if (v == SEQ_START_TOKEN)
1923                 return ip_vs_info_array(seq,0);
1924
1925         svc = v;
1926         iter = seq->private;
1927
1928         if (iter->table == ip_vs_svc_table) {
1929                 /* next service in table hashed by protocol */
1930                 e = rcu_dereference(hlist_next_rcu(&svc->s_list));
1931                 if (e)
1932                         return hlist_entry(e, struct ip_vs_service, s_list);
1933
1934                 while (++iter->bucket < IP_VS_SVC_TAB_SIZE) {
1935                         hlist_for_each_entry_rcu(svc,
1936                                                  &ip_vs_svc_table[iter->bucket],
1937                                                  s_list) {
1938                                 return svc;
1939                         }
1940                 }
1941
1942                 iter->table = ip_vs_svc_fwm_table;
1943                 iter->bucket = -1;
1944                 goto scan_fwmark;
1945         }
1946
1947         /* next service in hashed by fwmark */
1948         e = rcu_dereference(hlist_next_rcu(&svc->f_list));
1949         if (e)
1950                 return hlist_entry(e, struct ip_vs_service, f_list);
1951
1952  scan_fwmark:
1953         while (++iter->bucket < IP_VS_SVC_TAB_SIZE) {
1954                 hlist_for_each_entry_rcu(svc,
1955                                          &ip_vs_svc_fwm_table[iter->bucket],
1956                                          f_list)
1957                         return svc;
1958         }
1959
1960         return NULL;
1961 }
1962
1963 static void ip_vs_info_seq_stop(struct seq_file *seq, void *v)
1964         __releases(RCU)
1965 {
1966         rcu_read_unlock();
1967 }
1968
1969
1970 static int ip_vs_info_seq_show(struct seq_file *seq, void *v)
1971 {
1972         if (v == SEQ_START_TOKEN) {
1973                 seq_printf(seq,
1974                         "IP Virtual Server version %d.%d.%d (size=%d)\n",
1975                         NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
1976                 seq_puts(seq,
1977                          "Prot LocalAddress:Port Scheduler Flags\n");
1978                 seq_puts(seq,
1979                          "  -> RemoteAddress:Port Forward Weight ActiveConn InActConn\n");
1980         } else {
1981                 const struct ip_vs_service *svc = v;
1982                 const struct ip_vs_iter *iter = seq->private;
1983                 const struct ip_vs_dest *dest;
1984                 struct ip_vs_scheduler *sched = rcu_dereference(svc->scheduler);
1985
1986                 if (iter->table == ip_vs_svc_table) {
1987 #ifdef CONFIG_IP_VS_IPV6
1988                         if (svc->af == AF_INET6)
1989                                 seq_printf(seq, "%s  [%pI6]:%04X %s ",
1990                                            ip_vs_proto_name(svc->protocol),
1991                                            &svc->addr.in6,
1992                                            ntohs(svc->port),
1993                                            sched->name);
1994                         else
1995 #endif
1996                                 seq_printf(seq, "%s  %08X:%04X %s %s ",
1997                                            ip_vs_proto_name(svc->protocol),
1998                                            ntohl(svc->addr.ip),
1999                                            ntohs(svc->port),
2000                                            sched->name,
2001                                            (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":"");
2002                 } else {
2003                         seq_printf(seq, "FWM  %08X %s %s",
2004                                    svc->fwmark, sched->name,
2005                                    (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":"");
2006                 }
2007
2008                 if (svc->flags & IP_VS_SVC_F_PERSISTENT)
2009                         seq_printf(seq, "persistent %d %08X\n",
2010                                 svc->timeout,
2011                                 ntohl(svc->netmask));
2012                 else
2013                         seq_putc(seq, '\n');
2014
2015                 list_for_each_entry_rcu(dest, &svc->destinations, n_list) {
2016 #ifdef CONFIG_IP_VS_IPV6
2017                         if (dest->af == AF_INET6)
2018                                 seq_printf(seq,
2019                                            "  -> [%pI6]:%04X"
2020                                            "      %-7s %-6d %-10d %-10d\n",
2021                                            &dest->addr.in6,
2022                                            ntohs(dest->port),
2023                                            ip_vs_fwd_name(atomic_read(&dest->conn_flags)),
2024                                            atomic_read(&dest->weight),
2025                                            atomic_read(&dest->activeconns),
2026                                            atomic_read(&dest->inactconns));
2027                         else
2028 #endif
2029                                 seq_printf(seq,
2030                                            "  -> %08X:%04X      "
2031                                            "%-7s %-6d %-10d %-10d\n",
2032                                            ntohl(dest->addr.ip),
2033                                            ntohs(dest->port),
2034                                            ip_vs_fwd_name(atomic_read(&dest->conn_flags)),
2035                                            atomic_read(&dest->weight),
2036                                            atomic_read(&dest->activeconns),
2037                                            atomic_read(&dest->inactconns));
2038
2039                 }
2040         }
2041         return 0;
2042 }
2043
2044 static const struct seq_operations ip_vs_info_seq_ops = {
2045         .start = ip_vs_info_seq_start,
2046         .next  = ip_vs_info_seq_next,
2047         .stop  = ip_vs_info_seq_stop,
2048         .show  = ip_vs_info_seq_show,
2049 };
2050
2051 static int ip_vs_info_open(struct inode *inode, struct file *file)
2052 {
2053         return seq_open_net(inode, file, &ip_vs_info_seq_ops,
2054                         sizeof(struct ip_vs_iter));
2055 }
2056
2057 static const struct file_operations ip_vs_info_fops = {
2058         .owner   = THIS_MODULE,
2059         .open    = ip_vs_info_open,
2060         .read    = seq_read,
2061         .llseek  = seq_lseek,
2062         .release = seq_release_net,
2063 };
2064
2065 static int ip_vs_stats_show(struct seq_file *seq, void *v)
2066 {
2067         struct net *net = seq_file_single_net(seq);
2068         struct ip_vs_kstats show;
2069
2070 /*               01234567 01234567 01234567 0123456701234567 0123456701234567 */
2071         seq_puts(seq,
2072                  "   Total Incoming Outgoing         Incoming         Outgoing\n");
2073         seq_printf(seq,
2074                    "   Conns  Packets  Packets            Bytes            Bytes\n");
2075
2076         ip_vs_copy_stats(&show, &net_ipvs(net)->tot_stats);
2077         seq_printf(seq, "%8LX %8LX %8LX %16LX %16LX\n\n",
2078                    (unsigned long long)show.conns,
2079                    (unsigned long long)show.inpkts,
2080                    (unsigned long long)show.outpkts,
2081                    (unsigned long long)show.inbytes,
2082                    (unsigned long long)show.outbytes);
2083
2084 /*                01234567 01234567 01234567 0123456701234567 0123456701234567*/
2085         seq_puts(seq,
2086                  " Conns/s   Pkts/s   Pkts/s          Bytes/s          Bytes/s\n");
2087         seq_printf(seq, "%8LX %8LX %8LX %16LX %16LX\n",
2088                    (unsigned long long)show.cps,
2089                    (unsigned long long)show.inpps,
2090                    (unsigned long long)show.outpps,
2091                    (unsigned long long)show.inbps,
2092                    (unsigned long long)show.outbps);
2093
2094         return 0;
2095 }
2096
2097 static int ip_vs_stats_seq_open(struct inode *inode, struct file *file)
2098 {
2099         return single_open_net(inode, file, ip_vs_stats_show);
2100 }
2101
2102 static const struct file_operations ip_vs_stats_fops = {
2103         .owner = THIS_MODULE,
2104         .open = ip_vs_stats_seq_open,
2105         .read = seq_read,
2106         .llseek = seq_lseek,
2107         .release = single_release_net,
2108 };
2109
2110 static int ip_vs_stats_percpu_show(struct seq_file *seq, void *v)
2111 {
2112         struct net *net = seq_file_single_net(seq);
2113         struct ip_vs_stats *tot_stats = &net_ipvs(net)->tot_stats;
2114         struct ip_vs_cpu_stats __percpu *cpustats = tot_stats->cpustats;
2115         struct ip_vs_kstats kstats;
2116         int i;
2117
2118 /*               01234567 01234567 01234567 0123456701234567 0123456701234567 */
2119         seq_puts(seq,
2120                  "       Total Incoming Outgoing         Incoming         Outgoing\n");
2121         seq_printf(seq,
2122                    "CPU    Conns  Packets  Packets            Bytes            Bytes\n");
2123
2124         for_each_possible_cpu(i) {
2125                 struct ip_vs_cpu_stats *u = per_cpu_ptr(cpustats, i);
2126                 unsigned int start;
2127                 u64 conns, inpkts, outpkts, inbytes, outbytes;
2128
2129                 do {
2130                         start = u64_stats_fetch_begin_irq(&u->syncp);
2131                         conns = u->cnt.conns;
2132                         inpkts = u->cnt.inpkts;
2133                         outpkts = u->cnt.outpkts;
2134                         inbytes = u->cnt.inbytes;
2135                         outbytes = u->cnt.outbytes;
2136                 } while (u64_stats_fetch_retry_irq(&u->syncp, start));
2137
2138                 seq_printf(seq, "%3X %8LX %8LX %8LX %16LX %16LX\n",
2139                            i, (u64)conns, (u64)inpkts,
2140                            (u64)outpkts, (u64)inbytes,
2141                            (u64)outbytes);
2142         }
2143
2144         ip_vs_copy_stats(&kstats, tot_stats);
2145
2146         seq_printf(seq, "  ~ %8LX %8LX %8LX %16LX %16LX\n\n",
2147                    (unsigned long long)kstats.conns,
2148                    (unsigned long long)kstats.inpkts,
2149                    (unsigned long long)kstats.outpkts,
2150                    (unsigned long long)kstats.inbytes,
2151                    (unsigned long long)kstats.outbytes);
2152
2153 /*                ... 01234567 01234567 01234567 0123456701234567 0123456701234567 */
2154         seq_puts(seq,
2155                  "     Conns/s   Pkts/s   Pkts/s          Bytes/s          Bytes/s\n");
2156         seq_printf(seq, "    %8LX %8LX %8LX %16LX %16LX\n",
2157                    kstats.cps,
2158                    kstats.inpps,
2159                    kstats.outpps,
2160                    kstats.inbps,
2161                    kstats.outbps);
2162
2163         return 0;
2164 }
2165
2166 static int ip_vs_stats_percpu_seq_open(struct inode *inode, struct file *file)
2167 {
2168         return single_open_net(inode, file, ip_vs_stats_percpu_show);
2169 }
2170
2171 static const struct file_operations ip_vs_stats_percpu_fops = {
2172         .owner = THIS_MODULE,
2173         .open = ip_vs_stats_percpu_seq_open,
2174         .read = seq_read,
2175         .llseek = seq_lseek,
2176         .release = single_release_net,
2177 };
2178 #endif
2179
2180 /*
2181  *      Set timeout values for tcp tcpfin udp in the timeout_table.
2182  */
2183 static int ip_vs_set_timeout(struct net *net, struct ip_vs_timeout_user *u)
2184 {
2185 #if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP)
2186         struct ip_vs_proto_data *pd;
2187 #endif
2188
2189         IP_VS_DBG(2, "Setting timeout tcp:%d tcpfin:%d udp:%d\n",
2190                   u->tcp_timeout,
2191                   u->tcp_fin_timeout,
2192                   u->udp_timeout);
2193
2194 #ifdef CONFIG_IP_VS_PROTO_TCP
2195         if (u->tcp_timeout) {
2196                 pd = ip_vs_proto_data_get(net, IPPROTO_TCP);
2197                 pd->timeout_table[IP_VS_TCP_S_ESTABLISHED]
2198                         = u->tcp_timeout * HZ;
2199         }
2200
2201         if (u->tcp_fin_timeout) {
2202                 pd = ip_vs_proto_data_get(net, IPPROTO_TCP);
2203                 pd->timeout_table[IP_VS_TCP_S_FIN_WAIT]
2204                         = u->tcp_fin_timeout * HZ;
2205         }
2206 #endif
2207
2208 #ifdef CONFIG_IP_VS_PROTO_UDP
2209         if (u->udp_timeout) {
2210                 pd = ip_vs_proto_data_get(net, IPPROTO_UDP);
2211                 pd->timeout_table[IP_VS_UDP_S_NORMAL]
2212                         = u->udp_timeout * HZ;
2213         }
2214 #endif
2215         return 0;
2216 }
2217
2218 #define CMDID(cmd)              (cmd - IP_VS_BASE_CTL)
2219
2220 struct ip_vs_svcdest_user {
2221         struct ip_vs_service_user       s;
2222         struct ip_vs_dest_user          d;
2223 };
2224
2225 static const unsigned char set_arglen[CMDID(IP_VS_SO_SET_MAX) + 1] = {
2226         [CMDID(IP_VS_SO_SET_ADD)]         = sizeof(struct ip_vs_service_user),
2227         [CMDID(IP_VS_SO_SET_EDIT)]        = sizeof(struct ip_vs_service_user),
2228         [CMDID(IP_VS_SO_SET_DEL)]         = sizeof(struct ip_vs_service_user),
2229         [CMDID(IP_VS_SO_SET_ADDDEST)]     = sizeof(struct ip_vs_svcdest_user),
2230         [CMDID(IP_VS_SO_SET_DELDEST)]     = sizeof(struct ip_vs_svcdest_user),
2231         [CMDID(IP_VS_SO_SET_EDITDEST)]    = sizeof(struct ip_vs_svcdest_user),
2232         [CMDID(IP_VS_SO_SET_TIMEOUT)]     = sizeof(struct ip_vs_timeout_user),
2233         [CMDID(IP_VS_SO_SET_STARTDAEMON)] = sizeof(struct ip_vs_daemon_user),
2234         [CMDID(IP_VS_SO_SET_STOPDAEMON)]  = sizeof(struct ip_vs_daemon_user),
2235         [CMDID(IP_VS_SO_SET_ZERO)]        = sizeof(struct ip_vs_service_user),
2236 };
2237
2238 union ip_vs_set_arglen {
2239         struct ip_vs_service_user       field_IP_VS_SO_SET_ADD;
2240         struct ip_vs_service_user       field_IP_VS_SO_SET_EDIT;
2241         struct ip_vs_service_user       field_IP_VS_SO_SET_DEL;
2242         struct ip_vs_svcdest_user       field_IP_VS_SO_SET_ADDDEST;
2243         struct ip_vs_svcdest_user       field_IP_VS_SO_SET_DELDEST;
2244         struct ip_vs_svcdest_user       field_IP_VS_SO_SET_EDITDEST;
2245         struct ip_vs_timeout_user       field_IP_VS_SO_SET_TIMEOUT;
2246         struct ip_vs_daemon_user        field_IP_VS_SO_SET_STARTDAEMON;
2247         struct ip_vs_daemon_user        field_IP_VS_SO_SET_STOPDAEMON;
2248         struct ip_vs_service_user       field_IP_VS_SO_SET_ZERO;
2249 };
2250
2251 #define MAX_SET_ARGLEN  sizeof(union ip_vs_set_arglen)
2252
2253 static void ip_vs_copy_usvc_compat(struct ip_vs_service_user_kern *usvc,
2254                                   struct ip_vs_service_user *usvc_compat)
2255 {
2256         memset(usvc, 0, sizeof(*usvc));
2257
2258         usvc->af                = AF_INET;
2259         usvc->protocol          = usvc_compat->protocol;
2260         usvc->addr.ip           = usvc_compat->addr;
2261         usvc->port              = usvc_compat->port;
2262         usvc->fwmark            = usvc_compat->fwmark;
2263
2264         /* Deep copy of sched_name is not needed here */
2265         usvc->sched_name        = usvc_compat->sched_name;
2266
2267         usvc->flags             = usvc_compat->flags;
2268         usvc->timeout           = usvc_compat->timeout;
2269         usvc->netmask           = usvc_compat->netmask;
2270 }
2271
2272 static void ip_vs_copy_udest_compat(struct ip_vs_dest_user_kern *udest,
2273                                    struct ip_vs_dest_user *udest_compat)
2274 {
2275         memset(udest, 0, sizeof(*udest));
2276
2277         udest->addr.ip          = udest_compat->addr;
2278         udest->port             = udest_compat->port;
2279         udest->conn_flags       = udest_compat->conn_flags;
2280         udest->weight           = udest_compat->weight;
2281         udest->u_threshold      = udest_compat->u_threshold;
2282         udest->l_threshold      = udest_compat->l_threshold;
2283         udest->af               = AF_INET;
2284 }
2285
2286 static int
2287 do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
2288 {
2289         struct net *net = sock_net(sk);
2290         int ret;
2291         unsigned char arg[MAX_SET_ARGLEN];
2292         struct ip_vs_service_user *usvc_compat;
2293         struct ip_vs_service_user_kern usvc;
2294         struct ip_vs_service *svc;
2295         struct ip_vs_dest_user *udest_compat;
2296         struct ip_vs_dest_user_kern udest;
2297         struct netns_ipvs *ipvs = net_ipvs(net);
2298
2299         BUILD_BUG_ON(sizeof(arg) > 255);
2300         if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2301                 return -EPERM;
2302
2303         if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_SET_MAX)
2304                 return -EINVAL;
2305         if (len != set_arglen[CMDID(cmd)]) {
2306                 IP_VS_DBG(1, "set_ctl: len %u != %u\n",
2307                           len, set_arglen[CMDID(cmd)]);
2308                 return -EINVAL;
2309         }
2310
2311         if (copy_from_user(arg, user, len) != 0)
2312                 return -EFAULT;
2313
2314         /* increase the module use count */
2315         ip_vs_use_count_inc();
2316
2317         /* Handle daemons since they have another lock */
2318         if (cmd == IP_VS_SO_SET_STARTDAEMON ||
2319             cmd == IP_VS_SO_SET_STOPDAEMON) {
2320                 struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
2321
2322                 mutex_lock(&ipvs->sync_mutex);
2323                 if (cmd == IP_VS_SO_SET_STARTDAEMON)
2324                         ret = start_sync_thread(net, dm->state, dm->mcast_ifn,
2325                                                 dm->syncid);
2326                 else
2327                         ret = stop_sync_thread(net, dm->state);
2328                 mutex_unlock(&ipvs->sync_mutex);
2329                 goto out_dec;
2330         }
2331
2332         mutex_lock(&__ip_vs_mutex);
2333         if (cmd == IP_VS_SO_SET_FLUSH) {
2334                 /* Flush the virtual service */
2335                 ret = ip_vs_flush(net, false);
2336                 goto out_unlock;
2337         } else if (cmd == IP_VS_SO_SET_TIMEOUT) {
2338                 /* Set timeout values for (tcp tcpfin udp) */
2339                 ret = ip_vs_set_timeout(net, (struct ip_vs_timeout_user *)arg);
2340                 goto out_unlock;
2341         }
2342
2343         usvc_compat = (struct ip_vs_service_user *)arg;
2344         udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1);
2345
2346         /* We only use the new structs internally, so copy userspace compat
2347          * structs to extended internal versions */
2348         ip_vs_copy_usvc_compat(&usvc, usvc_compat);
2349         ip_vs_copy_udest_compat(&udest, udest_compat);
2350
2351         if (cmd == IP_VS_SO_SET_ZERO) {
2352                 /* if no service address is set, zero counters in all */
2353                 if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) {
2354                         ret = ip_vs_zero_all(net);
2355                         goto out_unlock;
2356                 }
2357         }
2358
2359         /* Check for valid protocol: TCP or UDP or SCTP, even for fwmark!=0 */
2360         if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP &&
2361             usvc.protocol != IPPROTO_SCTP) {
2362                 pr_err("set_ctl: invalid protocol: %d %pI4:%d %s\n",
2363                        usvc.protocol, &usvc.addr.ip,
2364                        ntohs(usvc.port), usvc.sched_name);
2365                 ret = -EFAULT;
2366                 goto out_unlock;
2367         }
2368
2369         /* Lookup the exact service by <protocol, addr, port> or fwmark */
2370         rcu_read_lock();
2371         if (usvc.fwmark == 0)
2372                 svc = __ip_vs_service_find(net, usvc.af, usvc.protocol,
2373                                            &usvc.addr, usvc.port);
2374         else
2375                 svc = __ip_vs_svc_fwm_find(net, usvc.af, usvc.fwmark);
2376         rcu_read_unlock();
2377
2378         if (cmd != IP_VS_SO_SET_ADD
2379             && (svc == NULL || svc->protocol != usvc.protocol)) {
2380                 ret = -ESRCH;
2381                 goto out_unlock;
2382         }
2383
2384         switch (cmd) {
2385         case IP_VS_SO_SET_ADD:
2386                 if (svc != NULL)
2387                         ret = -EEXIST;
2388                 else
2389                         ret = ip_vs_add_service(net, &usvc, &svc);
2390                 break;
2391         case IP_VS_SO_SET_EDIT:
2392                 ret = ip_vs_edit_service(svc, &usvc);
2393                 break;
2394         case IP_VS_SO_SET_DEL:
2395                 ret = ip_vs_del_service(svc);
2396                 if (!ret)
2397                         goto out_unlock;
2398                 break;
2399         case IP_VS_SO_SET_ZERO:
2400                 ret = ip_vs_zero_service(svc);
2401                 break;
2402         case IP_VS_SO_SET_ADDDEST:
2403                 ret = ip_vs_add_dest(svc, &udest);
2404                 break;
2405         case IP_VS_SO_SET_EDITDEST:
2406                 ret = ip_vs_edit_dest(svc, &udest);
2407                 break;
2408         case IP_VS_SO_SET_DELDEST:
2409                 ret = ip_vs_del_dest(svc, &udest);
2410                 break;
2411         default:
2412                 ret = -EINVAL;
2413         }
2414
2415   out_unlock:
2416         mutex_unlock(&__ip_vs_mutex);
2417   out_dec:
2418         /* decrease the module use count */
2419         ip_vs_use_count_dec();
2420
2421         return ret;
2422 }
2423
2424
2425 static void
2426 ip_vs_copy_service(struct ip_vs_service_entry *dst, struct ip_vs_service *src)
2427 {
2428         struct ip_vs_scheduler *sched;
2429         struct ip_vs_kstats kstats;
2430
2431         sched = rcu_dereference_protected(src->scheduler, 1);
2432         dst->protocol = src->protocol;
2433         dst->addr = src->addr.ip;
2434         dst->port = src->port;
2435         dst->fwmark = src->fwmark;
2436         strlcpy(dst->sched_name, sched->name, sizeof(dst->sched_name));
2437         dst->flags = src->flags;
2438         dst->timeout = src->timeout / HZ;
2439         dst->netmask = src->netmask;
2440         dst->num_dests = src->num_dests;
2441         ip_vs_copy_stats(&kstats, &src->stats);
2442         ip_vs_export_stats_user(&dst->stats, &kstats);
2443 }
2444
2445 static inline int
2446 __ip_vs_get_service_entries(struct net *net,
2447                             const struct ip_vs_get_services *get,
2448                             struct ip_vs_get_services __user *uptr)
2449 {
2450         int idx, count=0;
2451         struct ip_vs_service *svc;
2452         struct ip_vs_service_entry entry;
2453         int ret = 0;
2454
2455         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2456                 hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
2457                         /* Only expose IPv4 entries to old interface */
2458                         if (svc->af != AF_INET || !net_eq(svc->net, net))
2459                                 continue;
2460
2461                         if (count >= get->num_services)
2462                                 goto out;
2463                         memset(&entry, 0, sizeof(entry));
2464                         ip_vs_copy_service(&entry, svc);
2465                         if (copy_to_user(&uptr->entrytable[count],
2466                                          &entry, sizeof(entry))) {
2467                                 ret = -EFAULT;
2468                                 goto out;
2469                         }
2470                         count++;
2471                 }
2472         }
2473
2474         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2475                 hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
2476                         /* Only expose IPv4 entries to old interface */
2477                         if (svc->af != AF_INET || !net_eq(svc->net, net))
2478                                 continue;
2479
2480                         if (count >= get->num_services)
2481                                 goto out;
2482                         memset(&entry, 0, sizeof(entry));
2483                         ip_vs_copy_service(&entry, svc);
2484                         if (copy_to_user(&uptr->entrytable[count],
2485                                          &entry, sizeof(entry))) {
2486                                 ret = -EFAULT;
2487                                 goto out;
2488                         }
2489                         count++;
2490                 }
2491         }
2492 out:
2493         return ret;
2494 }
2495
2496 static inline int
2497 __ip_vs_get_dest_entries(struct net *net, const struct ip_vs_get_dests *get,
2498                          struct ip_vs_get_dests __user *uptr)
2499 {
2500         struct ip_vs_service *svc;
2501         union nf_inet_addr addr = { .ip = get->addr };
2502         int ret = 0;
2503
2504         rcu_read_lock();
2505         if (get->fwmark)
2506                 svc = __ip_vs_svc_fwm_find(net, AF_INET, get->fwmark);
2507         else
2508                 svc = __ip_vs_service_find(net, AF_INET, get->protocol, &addr,
2509                                            get->port);
2510         rcu_read_unlock();
2511
2512         if (svc) {
2513                 int count = 0;
2514                 struct ip_vs_dest *dest;
2515                 struct ip_vs_dest_entry entry;
2516                 struct ip_vs_kstats kstats;
2517
2518                 memset(&entry, 0, sizeof(entry));
2519                 list_for_each_entry(dest, &svc->destinations, n_list) {
2520                         if (count >= get->num_dests)
2521                                 break;
2522
2523                         /* Cannot expose heterogeneous members via sockopt
2524                          * interface
2525                          */
2526                         if (dest->af != svc->af)
2527                                 continue;
2528
2529                         entry.addr = dest->addr.ip;
2530                         entry.port = dest->port;
2531                         entry.conn_flags = atomic_read(&dest->conn_flags);
2532                         entry.weight = atomic_read(&dest->weight);
2533                         entry.u_threshold = dest->u_threshold;
2534                         entry.l_threshold = dest->l_threshold;
2535                         entry.activeconns = atomic_read(&dest->activeconns);
2536                         entry.inactconns = atomic_read(&dest->inactconns);
2537                         entry.persistconns = atomic_read(&dest->persistconns);
2538                         ip_vs_copy_stats(&kstats, &dest->stats);
2539                         ip_vs_export_stats_user(&entry.stats, &kstats);
2540                         if (copy_to_user(&uptr->entrytable[count],
2541                                          &entry, sizeof(entry))) {
2542                                 ret = -EFAULT;
2543                                 break;
2544                         }
2545                         count++;
2546                 }
2547         } else
2548                 ret = -ESRCH;
2549         return ret;
2550 }
2551
2552 static inline void
2553 __ip_vs_get_timeouts(struct net *net, struct ip_vs_timeout_user *u)
2554 {
2555 #if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP)
2556         struct ip_vs_proto_data *pd;
2557 #endif
2558
2559         memset(u, 0, sizeof (*u));
2560
2561 #ifdef CONFIG_IP_VS_PROTO_TCP
2562         pd = ip_vs_proto_data_get(net, IPPROTO_TCP);
2563         u->tcp_timeout = pd->timeout_table[IP_VS_TCP_S_ESTABLISHED] / HZ;
2564         u->tcp_fin_timeout = pd->timeout_table[IP_VS_TCP_S_FIN_WAIT] / HZ;
2565 #endif
2566 #ifdef CONFIG_IP_VS_PROTO_UDP
2567         pd = ip_vs_proto_data_get(net, IPPROTO_UDP);
2568         u->udp_timeout =
2569                         pd->timeout_table[IP_VS_UDP_S_NORMAL] / HZ;
2570 #endif
2571 }
2572
2573 static const unsigned char get_arglen[CMDID(IP_VS_SO_GET_MAX) + 1] = {
2574         [CMDID(IP_VS_SO_GET_VERSION)]  = 64,
2575         [CMDID(IP_VS_SO_GET_INFO)]     = sizeof(struct ip_vs_getinfo),
2576         [CMDID(IP_VS_SO_GET_SERVICES)] = sizeof(struct ip_vs_get_services),
2577         [CMDID(IP_VS_SO_GET_SERVICE)]  = sizeof(struct ip_vs_service_entry),
2578         [CMDID(IP_VS_SO_GET_DESTS)]    = sizeof(struct ip_vs_get_dests),
2579         [CMDID(IP_VS_SO_GET_TIMEOUT)]  = sizeof(struct ip_vs_timeout_user),
2580         [CMDID(IP_VS_SO_GET_DAEMON)]   = 2 * sizeof(struct ip_vs_daemon_user),
2581 };
2582
2583 union ip_vs_get_arglen {
2584         char                            field_IP_VS_SO_GET_VERSION[64];
2585         struct ip_vs_getinfo            field_IP_VS_SO_GET_INFO;
2586         struct ip_vs_get_services       field_IP_VS_SO_GET_SERVICES;
2587         struct ip_vs_service_entry      field_IP_VS_SO_GET_SERVICE;
2588         struct ip_vs_get_dests          field_IP_VS_SO_GET_DESTS;
2589         struct ip_vs_timeout_user       field_IP_VS_SO_GET_TIMEOUT;
2590         struct ip_vs_daemon_user        field_IP_VS_SO_GET_DAEMON[2];
2591 };
2592
2593 #define MAX_GET_ARGLEN  sizeof(union ip_vs_get_arglen)
2594
2595 static int
2596 do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
2597 {
2598         unsigned char arg[MAX_GET_ARGLEN];
2599         int ret = 0;
2600         unsigned int copylen;
2601         struct net *net = sock_net(sk);
2602         struct netns_ipvs *ipvs = net_ipvs(net);
2603
2604         BUG_ON(!net);
2605         BUILD_BUG_ON(sizeof(arg) > 255);
2606         if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2607                 return -EPERM;
2608
2609         if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)
2610                 return -EINVAL;
2611
2612         copylen = get_arglen[CMDID(cmd)];
2613         if (*len < (int) copylen) {
2614                 IP_VS_DBG(1, "get_ctl: len %d < %u\n", *len, copylen);
2615                 return -EINVAL;
2616         }
2617
2618         if (copy_from_user(arg, user, copylen) != 0)
2619                 return -EFAULT;
2620         /*
2621          * Handle daemons first since it has its own locking
2622          */
2623         if (cmd == IP_VS_SO_GET_DAEMON) {
2624                 struct ip_vs_daemon_user d[2];
2625
2626                 memset(&d, 0, sizeof(d));
2627                 mutex_lock(&ipvs->sync_mutex);
2628                 if (ipvs->sync_state & IP_VS_STATE_MASTER) {
2629                         d[0].state = IP_VS_STATE_MASTER;
2630                         strlcpy(d[0].mcast_ifn, ipvs->master_mcast_ifn,
2631                                 sizeof(d[0].mcast_ifn));
2632                         d[0].syncid = ipvs->master_syncid;
2633                 }
2634                 if (ipvs->sync_state & IP_VS_STATE_BACKUP) {
2635                         d[1].state = IP_VS_STATE_BACKUP;
2636                         strlcpy(d[1].mcast_ifn, ipvs->backup_mcast_ifn,
2637                                 sizeof(d[1].mcast_ifn));
2638                         d[1].syncid = ipvs->backup_syncid;
2639                 }
2640                 if (copy_to_user(user, &d, sizeof(d)) != 0)
2641                         ret = -EFAULT;
2642                 mutex_unlock(&ipvs->sync_mutex);
2643                 return ret;
2644         }
2645
2646         mutex_lock(&__ip_vs_mutex);
2647         switch (cmd) {
2648         case IP_VS_SO_GET_VERSION:
2649         {
2650                 char buf[64];
2651
2652                 sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
2653                         NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
2654                 if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
2655                         ret = -EFAULT;
2656                         goto out;
2657                 }
2658                 *len = strlen(buf)+1;
2659         }
2660         break;
2661
2662         case IP_VS_SO_GET_INFO:
2663         {
2664                 struct ip_vs_getinfo info;
2665                 info.version = IP_VS_VERSION_CODE;
2666                 info.size = ip_vs_conn_tab_size;
2667                 info.num_services = ipvs->num_services;
2668                 if (copy_to_user(user, &info, sizeof(info)) != 0)
2669                         ret = -EFAULT;
2670         }
2671         break;
2672
2673         case IP_VS_SO_GET_SERVICES:
2674         {
2675                 struct ip_vs_get_services *get;
2676                 int size;
2677
2678                 get = (struct ip_vs_get_services *)arg;
2679                 size = sizeof(*get) +
2680                         sizeof(struct ip_vs_service_entry) * get->num_services;
2681                 if (*len != size) {
2682                         pr_err("length: %u != %u\n", *len, size);
2683                         ret = -EINVAL;
2684                         goto out;
2685                 }
2686                 ret = __ip_vs_get_service_entries(net, get, user);
2687         }
2688         break;
2689
2690         case IP_VS_SO_GET_SERVICE:
2691         {
2692                 struct ip_vs_service_entry *entry;
2693                 struct ip_vs_service *svc;
2694                 union nf_inet_addr addr;
2695
2696                 entry = (struct ip_vs_service_entry *)arg;
2697                 addr.ip = entry->addr;
2698                 rcu_read_lock();
2699                 if (entry->fwmark)
2700                         svc = __ip_vs_svc_fwm_find(net, AF_INET, entry->fwmark);
2701                 else
2702                         svc = __ip_vs_service_find(net, AF_INET,
2703                                                    entry->protocol, &addr,
2704                                                    entry->port);
2705                 rcu_read_unlock();
2706                 if (svc) {
2707                         ip_vs_copy_service(entry, svc);
2708                         if (copy_to_user(user, entry, sizeof(*entry)) != 0)
2709                                 ret = -EFAULT;
2710                 } else
2711                         ret = -ESRCH;
2712         }
2713         break;
2714
2715         case IP_VS_SO_GET_DESTS:
2716         {
2717                 struct ip_vs_get_dests *get;
2718                 int size;
2719
2720                 get = (struct ip_vs_get_dests *)arg;
2721                 size = sizeof(*get) +
2722                         sizeof(struct ip_vs_dest_entry) * get->num_dests;
2723                 if (*len != size) {
2724                         pr_err("length: %u != %u\n", *len, size);
2725                         ret = -EINVAL;
2726                         goto out;
2727                 }
2728                 ret = __ip_vs_get_dest_entries(net, get, user);
2729         }
2730         break;
2731
2732         case IP_VS_SO_GET_TIMEOUT:
2733         {
2734                 struct ip_vs_timeout_user t;
2735
2736                 __ip_vs_get_timeouts(net, &t);
2737                 if (copy_to_user(user, &t, sizeof(t)) != 0)
2738                         ret = -EFAULT;
2739         }
2740         break;
2741
2742         default:
2743                 ret = -EINVAL;
2744         }
2745
2746 out:
2747         mutex_unlock(&__ip_vs_mutex);
2748         return ret;
2749 }
2750
2751
2752 static struct nf_sockopt_ops ip_vs_sockopts = {
2753         .pf             = PF_INET,
2754         .set_optmin     = IP_VS_BASE_CTL,
2755         .set_optmax     = IP_VS_SO_SET_MAX+1,
2756         .set            = do_ip_vs_set_ctl,
2757         .get_optmin     = IP_VS_BASE_CTL,
2758         .get_optmax     = IP_VS_SO_GET_MAX+1,
2759         .get            = do_ip_vs_get_ctl,
2760         .owner          = THIS_MODULE,
2761 };
2762
2763 /*
2764  * Generic Netlink interface
2765  */
2766
2767 /* IPVS genetlink family */
2768 static struct genl_family ip_vs_genl_family = {
2769         .id             = GENL_ID_GENERATE,
2770         .hdrsize        = 0,
2771         .name           = IPVS_GENL_NAME,
2772         .version        = IPVS_GENL_VERSION,
2773         .maxattr        = IPVS_CMD_MAX,
2774         .netnsok        = true,         /* Make ipvsadm to work on netns */
2775 };
2776
2777 /* Policy used for first-level command attributes */
2778 static const struct nla_policy ip_vs_cmd_policy[IPVS_CMD_ATTR_MAX + 1] = {
2779         [IPVS_CMD_ATTR_SERVICE]         = { .type = NLA_NESTED },
2780         [IPVS_CMD_ATTR_DEST]            = { .type = NLA_NESTED },
2781         [IPVS_CMD_ATTR_DAEMON]          = { .type = NLA_NESTED },
2782         [IPVS_CMD_ATTR_TIMEOUT_TCP]     = { .type = NLA_U32 },
2783         [IPVS_CMD_ATTR_TIMEOUT_TCP_FIN] = { .type = NLA_U32 },
2784         [IPVS_CMD_ATTR_TIMEOUT_UDP]     = { .type = NLA_U32 },
2785 };
2786
2787 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DAEMON */
2788 static const struct nla_policy ip_vs_daemon_policy[IPVS_DAEMON_ATTR_MAX + 1] = {
2789         [IPVS_DAEMON_ATTR_STATE]        = { .type = NLA_U32 },
2790         [IPVS_DAEMON_ATTR_MCAST_IFN]    = { .type = NLA_NUL_STRING,
2791                                             .len = IP_VS_IFNAME_MAXLEN },
2792         [IPVS_DAEMON_ATTR_SYNC_ID]      = { .type = NLA_U32 },
2793 };
2794
2795 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_SERVICE */
2796 static const struct nla_policy ip_vs_svc_policy[IPVS_SVC_ATTR_MAX + 1] = {
2797         [IPVS_SVC_ATTR_AF]              = { .type = NLA_U16 },
2798         [IPVS_SVC_ATTR_PROTOCOL]        = { .type = NLA_U16 },
2799         [IPVS_SVC_ATTR_ADDR]            = { .type = NLA_BINARY,
2800                                             .len = sizeof(union nf_inet_addr) },
2801         [IPVS_SVC_ATTR_PORT]            = { .type = NLA_U16 },
2802         [IPVS_SVC_ATTR_FWMARK]          = { .type = NLA_U32 },
2803         [IPVS_SVC_ATTR_SCHED_NAME]      = { .type = NLA_NUL_STRING,
2804                                             .len = IP_VS_SCHEDNAME_MAXLEN },
2805         [IPVS_SVC_ATTR_PE_NAME]         = { .type = NLA_NUL_STRING,
2806                                             .len = IP_VS_PENAME_MAXLEN },
2807         [IPVS_SVC_ATTR_FLAGS]           = { .type = NLA_BINARY,
2808                                             .len = sizeof(struct ip_vs_flags) },
2809         [IPVS_SVC_ATTR_TIMEOUT]         = { .type = NLA_U32 },
2810         [IPVS_SVC_ATTR_NETMASK]         = { .type = NLA_U32 },
2811         [IPVS_SVC_ATTR_STATS]           = { .type = NLA_NESTED },
2812 };
2813
2814 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DEST */
2815 static const struct nla_policy ip_vs_dest_policy[IPVS_DEST_ATTR_MAX + 1] = {
2816         [IPVS_DEST_ATTR_ADDR]           = { .type = NLA_BINARY,
2817                                             .len = sizeof(union nf_inet_addr) },
2818         [IPVS_DEST_ATTR_PORT]           = { .type = NLA_U16 },
2819         [IPVS_DEST_ATTR_FWD_METHOD]     = { .type = NLA_U32 },
2820         [IPVS_DEST_ATTR_WEIGHT]         = { .type = NLA_U32 },
2821         [IPVS_DEST_ATTR_U_THRESH]       = { .type = NLA_U32 },
2822         [IPVS_DEST_ATTR_L_THRESH]       = { .type = NLA_U32 },
2823         [IPVS_DEST_ATTR_ACTIVE_CONNS]   = { .type = NLA_U32 },
2824         [IPVS_DEST_ATTR_INACT_CONNS]    = { .type = NLA_U32 },
2825         [IPVS_DEST_ATTR_PERSIST_CONNS]  = { .type = NLA_U32 },
2826         [IPVS_DEST_ATTR_STATS]          = { .type = NLA_NESTED },
2827         [IPVS_DEST_ATTR_ADDR_FAMILY]    = { .type = NLA_U16 },
2828 };
2829
2830 static int ip_vs_genl_fill_stats(struct sk_buff *skb, int container_type,
2831                                  struct ip_vs_kstats *kstats)
2832 {
2833         struct nlattr *nl_stats = nla_nest_start(skb, container_type);
2834
2835         if (!nl_stats)
2836                 return -EMSGSIZE;
2837
2838         if (nla_put_u32(skb, IPVS_STATS_ATTR_CONNS, (u32)kstats->conns) ||
2839             nla_put_u32(skb, IPVS_STATS_ATTR_INPKTS, (u32)kstats->inpkts) ||
2840             nla_put_u32(skb, IPVS_STATS_ATTR_OUTPKTS, (u32)kstats->outpkts) ||
2841             nla_put_u64(skb, IPVS_STATS_ATTR_INBYTES, kstats->inbytes) ||
2842             nla_put_u64(skb, IPVS_STATS_ATTR_OUTBYTES, kstats->outbytes) ||
2843             nla_put_u32(skb, IPVS_STATS_ATTR_CPS, (u32)kstats->cps) ||
2844             nla_put_u32(skb, IPVS_STATS_ATTR_INPPS, (u32)kstats->inpps) ||
2845             nla_put_u32(skb, IPVS_STATS_ATTR_OUTPPS, (u32)kstats->outpps) ||
2846             nla_put_u32(skb, IPVS_STATS_ATTR_INBPS, (u32)kstats->inbps) ||
2847             nla_put_u32(skb, IPVS_STATS_ATTR_OUTBPS, (u32)kstats->outbps))
2848                 goto nla_put_failure;
2849         nla_nest_end(skb, nl_stats);
2850
2851         return 0;
2852
2853 nla_put_failure:
2854         nla_nest_cancel(skb, nl_stats);
2855         return -EMSGSIZE;
2856 }
2857
2858 static int ip_vs_genl_fill_stats64(struct sk_buff *skb, int container_type,
2859                                    struct ip_vs_kstats *kstats)
2860 {
2861         struct nlattr *nl_stats = nla_nest_start(skb, container_type);
2862
2863         if (!nl_stats)
2864                 return -EMSGSIZE;
2865
2866         if (nla_put_u64(skb, IPVS_STATS_ATTR_CONNS, kstats->conns) ||
2867             nla_put_u64(skb, IPVS_STATS_ATTR_INPKTS, kstats->inpkts) ||
2868             nla_put_u64(skb, IPVS_STATS_ATTR_OUTPKTS, kstats->outpkts) ||
2869             nla_put_u64(skb, IPVS_STATS_ATTR_INBYTES, kstats->inbytes) ||
2870             nla_put_u64(skb, IPVS_STATS_ATTR_OUTBYTES, kstats->outbytes) ||
2871             nla_put_u64(skb, IPVS_STATS_ATTR_CPS, kstats->cps) ||
2872             nla_put_u64(skb, IPVS_STATS_ATTR_INPPS, kstats->inpps) ||
2873             nla_put_u64(skb, IPVS_STATS_ATTR_OUTPPS, kstats->outpps) ||
2874             nla_put_u64(skb, IPVS_STATS_ATTR_INBPS, kstats->inbps) ||
2875             nla_put_u64(skb, IPVS_STATS_ATTR_OUTBPS, kstats->outbps))
2876                 goto nla_put_failure;
2877         nla_nest_end(skb, nl_stats);
2878
2879         return 0;
2880
2881 nla_put_failure:
2882         nla_nest_cancel(skb, nl_stats);
2883         return -EMSGSIZE;
2884 }
2885
2886 static int ip_vs_genl_fill_service(struct sk_buff *skb,
2887                                    struct ip_vs_service *svc)
2888 {
2889         struct ip_vs_scheduler *sched;
2890         struct ip_vs_pe *pe;
2891         struct nlattr *nl_service;
2892         struct ip_vs_flags flags = { .flags = svc->flags,
2893                                      .mask = ~0 };
2894         struct ip_vs_kstats kstats;
2895
2896         nl_service = nla_nest_start(skb, IPVS_CMD_ATTR_SERVICE);
2897         if (!nl_service)
2898                 return -EMSGSIZE;
2899
2900         if (nla_put_u16(skb, IPVS_SVC_ATTR_AF, svc->af))
2901                 goto nla_put_failure;
2902         if (svc->fwmark) {
2903                 if (nla_put_u32(skb, IPVS_SVC_ATTR_FWMARK, svc->fwmark))
2904                         goto nla_put_failure;
2905         } else {
2906                 if (nla_put_u16(skb, IPVS_SVC_ATTR_PROTOCOL, svc->protocol) ||
2907                     nla_put(skb, IPVS_SVC_ATTR_ADDR, sizeof(svc->addr), &svc->addr) ||
2908                     nla_put_be16(skb, IPVS_SVC_ATTR_PORT, svc->port))
2909                         goto nla_put_failure;
2910         }
2911
2912         sched = rcu_dereference_protected(svc->scheduler, 1);
2913         pe = rcu_dereference_protected(svc->pe, 1);
2914         if (nla_put_string(skb, IPVS_SVC_ATTR_SCHED_NAME, sched->name) ||
2915             (pe && nla_put_string(skb, IPVS_SVC_ATTR_PE_NAME, pe->name)) ||
2916             nla_put(skb, IPVS_SVC_ATTR_FLAGS, sizeof(flags), &flags) ||
2917             nla_put_u32(skb, IPVS_SVC_ATTR_TIMEOUT, svc->timeout / HZ) ||
2918             nla_put_be32(skb, IPVS_SVC_ATTR_NETMASK, svc->netmask))
2919                 goto nla_put_failure;
2920         ip_vs_copy_stats(&kstats, &svc->stats);
2921         if (ip_vs_genl_fill_stats(skb, IPVS_SVC_ATTR_STATS, &kstats))
2922                 goto nla_put_failure;
2923         if (ip_vs_genl_fill_stats64(skb, IPVS_SVC_ATTR_STATS64, &kstats))
2924                 goto nla_put_failure;
2925
2926         nla_nest_end(skb, nl_service);
2927
2928         return 0;
2929
2930 nla_put_failure:
2931         nla_nest_cancel(skb, nl_service);
2932         return -EMSGSIZE;
2933 }
2934
2935 static int ip_vs_genl_dump_service(struct sk_buff *skb,
2936                                    struct ip_vs_service *svc,
2937                                    struct netlink_callback *cb)
2938 {
2939         void *hdr;
2940
2941         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
2942                           &ip_vs_genl_family, NLM_F_MULTI,
2943                           IPVS_CMD_NEW_SERVICE);
2944         if (!hdr)
2945                 return -EMSGSIZE;
2946
2947         if (ip_vs_genl_fill_service(skb, svc) < 0)
2948                 goto nla_put_failure;
2949
2950         genlmsg_end(skb, hdr);
2951         return 0;
2952
2953 nla_put_failure:
2954         genlmsg_cancel(skb, hdr);
2955         return -EMSGSIZE;
2956 }
2957
2958 static int ip_vs_genl_dump_services(struct sk_buff *skb,
2959                                     struct netlink_callback *cb)
2960 {
2961         int idx = 0, i;
2962         int start = cb->args[0];
2963         struct ip_vs_service *svc;
2964         struct net *net = skb_sknet(skb);
2965
2966         mutex_lock(&__ip_vs_mutex);
2967         for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) {
2968                 hlist_for_each_entry(svc, &ip_vs_svc_table[i], s_list) {
2969                         if (++idx <= start || !net_eq(svc->net, net))
2970                                 continue;
2971                         if (ip_vs_genl_dump_service(skb, svc, cb) < 0) {
2972                                 idx--;
2973                                 goto nla_put_failure;
2974                         }
2975                 }
2976         }
2977
2978         for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) {
2979                 hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[i], f_list) {
2980                         if (++idx <= start || !net_eq(svc->net, net))
2981                                 continue;
2982                         if (ip_vs_genl_dump_service(skb, svc, cb) < 0) {
2983                                 idx--;
2984                                 goto nla_put_failure;
2985                         }
2986                 }
2987         }
2988
2989 nla_put_failure:
2990         mutex_unlock(&__ip_vs_mutex);
2991         cb->args[0] = idx;
2992
2993         return skb->len;
2994 }
2995
2996 static int ip_vs_genl_parse_service(struct net *net,
2997                                     struct ip_vs_service_user_kern *usvc,
2998                                     struct nlattr *nla, int full_entry,
2999                                     struct ip_vs_service **ret_svc)
3000 {
3001         struct nlattr *attrs[IPVS_SVC_ATTR_MAX + 1];
3002         struct nlattr *nla_af, *nla_port, *nla_fwmark, *nla_protocol, *nla_addr;
3003         struct ip_vs_service *svc;
3004
3005         /* Parse mandatory identifying service fields first */
3006         if (nla == NULL ||
3007             nla_parse_nested(attrs, IPVS_SVC_ATTR_MAX, nla, ip_vs_svc_policy))
3008                 return -EINVAL;
3009
3010         nla_af          = attrs[IPVS_SVC_ATTR_AF];
3011         nla_protocol    = attrs[IPVS_SVC_ATTR_PROTOCOL];
3012         nla_addr        = attrs[IPVS_SVC_ATTR_ADDR];
3013         nla_port        = attrs[IPVS_SVC_ATTR_PORT];
3014         nla_fwmark      = attrs[IPVS_SVC_ATTR_FWMARK];
3015
3016         if (!(nla_af && (nla_fwmark || (nla_port && nla_protocol && nla_addr))))
3017                 return -EINVAL;
3018
3019         memset(usvc, 0, sizeof(*usvc));
3020
3021         usvc->af = nla_get_u16(nla_af);
3022 #ifdef CONFIG_IP_VS_IPV6
3023         if (usvc->af != AF_INET && usvc->af != AF_INET6)
3024 #else
3025         if (usvc->af != AF_INET)
3026 #endif
3027                 return -EAFNOSUPPORT;
3028
3029         if (nla_fwmark) {
3030                 usvc->protocol = IPPROTO_TCP;
3031                 usvc->fwmark = nla_get_u32(nla_fwmark);
3032         } else {
3033                 usvc->protocol = nla_get_u16(nla_protocol);
3034                 nla_memcpy(&usvc->addr, nla_addr, sizeof(usvc->addr));
3035                 usvc->port = nla_get_be16(nla_port);
3036                 usvc->fwmark = 0;
3037         }
3038
3039         rcu_read_lock();
3040         if (usvc->fwmark)
3041                 svc = __ip_vs_svc_fwm_find(net, usvc->af, usvc->fwmark);
3042         else
3043                 svc = __ip_vs_service_find(net, usvc->af, usvc->protocol,
3044                                            &usvc->addr, usvc->port);
3045         rcu_read_unlock();
3046         *ret_svc = svc;
3047
3048         /* If a full entry was requested, check for the additional fields */
3049         if (full_entry) {
3050                 struct nlattr *nla_sched, *nla_flags, *nla_pe, *nla_timeout,
3051                               *nla_netmask;
3052                 struct ip_vs_flags flags;
3053
3054                 nla_sched = attrs[IPVS_SVC_ATTR_SCHED_NAME];
3055                 nla_pe = attrs[IPVS_SVC_ATTR_PE_NAME];
3056                 nla_flags = attrs[IPVS_SVC_ATTR_FLAGS];
3057                 nla_timeout = attrs[IPVS_SVC_ATTR_TIMEOUT];
3058                 nla_netmask = attrs[IPVS_SVC_ATTR_NETMASK];
3059
3060                 if (!(nla_sched && nla_flags && nla_timeout && nla_netmask))
3061                         return -EINVAL;
3062
3063                 nla_memcpy(&flags, nla_flags, sizeof(flags));
3064
3065                 /* prefill flags from service if it already exists */
3066                 if (svc)
3067                         usvc->flags = svc->flags;
3068
3069                 /* set new flags from userland */
3070                 usvc->flags = (usvc->flags & ~flags.mask) |
3071                               (flags.flags & flags.mask);
3072                 usvc->sched_name = nla_data(nla_sched);
3073                 usvc->pe_name = nla_pe ? nla_data(nla_pe) : NULL;
3074                 usvc->timeout = nla_get_u32(nla_timeout);
3075                 usvc->netmask = nla_get_be32(nla_netmask);
3076         }
3077
3078         return 0;
3079 }
3080
3081 static struct ip_vs_service *ip_vs_genl_find_service(struct net *net,
3082                                                      struct nlattr *nla)
3083 {
3084         struct ip_vs_service_user_kern usvc;
3085         struct ip_vs_service *svc;
3086         int ret;
3087
3088         ret = ip_vs_genl_parse_service(net, &usvc, nla, 0, &svc);
3089         return ret ? ERR_PTR(ret) : svc;
3090 }
3091
3092 static int ip_vs_genl_fill_dest(struct sk_buff *skb, struct ip_vs_dest *dest)
3093 {
3094         struct nlattr *nl_dest;
3095         struct ip_vs_kstats kstats;
3096
3097         nl_dest = nla_nest_start(skb, IPVS_CMD_ATTR_DEST);
3098         if (!nl_dest)
3099                 return -EMSGSIZE;
3100
3101         if (nla_put(skb, IPVS_DEST_ATTR_ADDR, sizeof(dest->addr), &dest->addr) ||
3102             nla_put_be16(skb, IPVS_DEST_ATTR_PORT, dest->port) ||
3103             nla_put_u32(skb, IPVS_DEST_ATTR_FWD_METHOD,
3104                         (atomic_read(&dest->conn_flags) &
3105                          IP_VS_CONN_F_FWD_MASK)) ||
3106             nla_put_u32(skb, IPVS_DEST_ATTR_WEIGHT,
3107                         atomic_read(&dest->weight)) ||
3108             nla_put_u32(skb, IPVS_DEST_ATTR_U_THRESH, dest->u_threshold) ||
3109             nla_put_u32(skb, IPVS_DEST_ATTR_L_THRESH, dest->l_threshold) ||
3110             nla_put_u32(skb, IPVS_DEST_ATTR_ACTIVE_CONNS,
3111                         atomic_read(&dest->activeconns)) ||
3112             nla_put_u32(skb, IPVS_DEST_ATTR_INACT_CONNS,
3113                         atomic_read(&dest->inactconns)) ||
3114             nla_put_u32(skb, IPVS_DEST_ATTR_PERSIST_CONNS,
3115                         atomic_read(&dest->persistconns)) ||
3116             nla_put_u16(skb, IPVS_DEST_ATTR_ADDR_FAMILY, dest->af))
3117                 goto nla_put_failure;
3118         ip_vs_copy_stats(&kstats, &dest->stats);
3119         if (ip_vs_genl_fill_stats(skb, IPVS_DEST_ATTR_STATS, &kstats))
3120                 goto nla_put_failure;
3121         if (ip_vs_genl_fill_stats64(skb, IPVS_DEST_ATTR_STATS64, &kstats))
3122                 goto nla_put_failure;
3123
3124         nla_nest_end(skb, nl_dest);
3125
3126         return 0;
3127
3128 nla_put_failure:
3129         nla_nest_cancel(skb, nl_dest);
3130         return -EMSGSIZE;
3131 }
3132
3133 static int ip_vs_genl_dump_dest(struct sk_buff *skb, struct ip_vs_dest *dest,
3134                                 struct netlink_callback *cb)
3135 {
3136         void *hdr;
3137
3138         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3139                           &ip_vs_genl_family, NLM_F_MULTI,
3140                           IPVS_CMD_NEW_DEST);
3141         if (!hdr)
3142                 return -EMSGSIZE;
3143
3144         if (ip_vs_genl_fill_dest(skb, dest) < 0)
3145                 goto nla_put_failure;
3146
3147         genlmsg_end(skb, hdr);
3148         return 0;
3149
3150 nla_put_failure:
3151         genlmsg_cancel(skb, hdr);
3152         return -EMSGSIZE;
3153 }
3154
3155 static int ip_vs_genl_dump_dests(struct sk_buff *skb,
3156                                  struct netlink_callback *cb)
3157 {
3158         int idx = 0;
3159         int start = cb->args[0];
3160         struct ip_vs_service *svc;
3161         struct ip_vs_dest *dest;
3162         struct nlattr *attrs[IPVS_CMD_ATTR_MAX + 1];
3163         struct net *net = skb_sknet(skb);
3164
3165         mutex_lock(&__ip_vs_mutex);
3166
3167         /* Try to find the service for which to dump destinations */
3168         if (nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs,
3169                         IPVS_CMD_ATTR_MAX, ip_vs_cmd_policy))
3170                 goto out_err;
3171
3172
3173         svc = ip_vs_genl_find_service(net, attrs[IPVS_CMD_ATTR_SERVICE]);
3174         if (IS_ERR(svc) || svc == NULL)
3175                 goto out_err;
3176
3177         /* Dump the destinations */
3178         list_for_each_entry(dest, &svc->destinations, n_list) {
3179                 if (++idx <= start)
3180                         continue;
3181                 if (ip_vs_genl_dump_dest(skb, dest, cb) < 0) {
3182                         idx--;
3183                         goto nla_put_failure;
3184                 }
3185         }
3186
3187 nla_put_failure:
3188         cb->args[0] = idx;
3189
3190 out_err:
3191         mutex_unlock(&__ip_vs_mutex);
3192
3193         return skb->len;
3194 }
3195
3196 static int ip_vs_genl_parse_dest(struct ip_vs_dest_user_kern *udest,
3197                                  struct nlattr *nla, int full_entry)
3198 {
3199         struct nlattr *attrs[IPVS_DEST_ATTR_MAX + 1];
3200         struct nlattr *nla_addr, *nla_port;
3201         struct nlattr *nla_addr_family;
3202
3203         /* Parse mandatory identifying destination fields first */
3204         if (nla == NULL ||
3205             nla_parse_nested(attrs, IPVS_DEST_ATTR_MAX, nla, ip_vs_dest_policy))
3206                 return -EINVAL;
3207
3208         nla_addr        = attrs[IPVS_DEST_ATTR_ADDR];
3209         nla_port        = attrs[IPVS_DEST_ATTR_PORT];
3210         nla_addr_family = attrs[IPVS_DEST_ATTR_ADDR_FAMILY];
3211
3212         if (!(nla_addr && nla_port))
3213                 return -EINVAL;
3214
3215         memset(udest, 0, sizeof(*udest));
3216
3217         nla_memcpy(&udest->addr, nla_addr, sizeof(udest->addr));
3218         udest->port = nla_get_be16(nla_port);
3219
3220         if (nla_addr_family)
3221                 udest->af = nla_get_u16(nla_addr_family);
3222         else
3223                 udest->af = 0;
3224
3225         /* If a full entry was requested, check for the additional fields */
3226         if (full_entry) {
3227                 struct nlattr *nla_fwd, *nla_weight, *nla_u_thresh,
3228                               *nla_l_thresh;
3229
3230                 nla_fwd         = attrs[IPVS_DEST_ATTR_FWD_METHOD];
3231                 nla_weight      = attrs[IPVS_DEST_ATTR_WEIGHT];
3232                 nla_u_thresh    = attrs[IPVS_DEST_ATTR_U_THRESH];
3233                 nla_l_thresh    = attrs[IPVS_DEST_ATTR_L_THRESH];
3234
3235                 if (!(nla_fwd && nla_weight && nla_u_thresh && nla_l_thresh))
3236                         return -EINVAL;
3237
3238                 udest->conn_flags = nla_get_u32(nla_fwd)
3239                                     & IP_VS_CONN_F_FWD_MASK;
3240                 udest->weight = nla_get_u32(nla_weight);
3241                 udest->u_threshold = nla_get_u32(nla_u_thresh);
3242                 udest->l_threshold = nla_get_u32(nla_l_thresh);
3243         }
3244
3245         return 0;
3246 }
3247
3248 static int ip_vs_genl_fill_daemon(struct sk_buff *skb, __u32 state,
3249                                   const char *mcast_ifn, __u32 syncid)
3250 {
3251         struct nlattr *nl_daemon;
3252
3253         nl_daemon = nla_nest_start(skb, IPVS_CMD_ATTR_DAEMON);
3254         if (!nl_daemon)
3255                 return -EMSGSIZE;
3256
3257         if (nla_put_u32(skb, IPVS_DAEMON_ATTR_STATE, state) ||
3258             nla_put_string(skb, IPVS_DAEMON_ATTR_MCAST_IFN, mcast_ifn) ||
3259             nla_put_u32(skb, IPVS_DAEMON_ATTR_SYNC_ID, syncid))
3260                 goto nla_put_failure;
3261         nla_nest_end(skb, nl_daemon);
3262
3263         return 0;
3264
3265 nla_put_failure:
3266         nla_nest_cancel(skb, nl_daemon);
3267         return -EMSGSIZE;
3268 }
3269
3270 static int ip_vs_genl_dump_daemon(struct sk_buff *skb, __u32 state,
3271                                   const char *mcast_ifn, __u32 syncid,
3272                                   struct netlink_callback *cb)
3273 {
3274         void *hdr;
3275         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3276                           &ip_vs_genl_family, NLM_F_MULTI,
3277                           IPVS_CMD_NEW_DAEMON);
3278         if (!hdr)
3279                 return -EMSGSIZE;
3280
3281         if (ip_vs_genl_fill_daemon(skb, state, mcast_ifn, syncid))
3282                 goto nla_put_failure;
3283
3284         genlmsg_end(skb, hdr);
3285         return 0;
3286
3287 nla_put_failure:
3288         genlmsg_cancel(skb, hdr);
3289         return -EMSGSIZE;
3290 }
3291
3292 static int ip_vs_genl_dump_daemons(struct sk_buff *skb,
3293                                    struct netlink_callback *cb)
3294 {
3295         struct net *net = skb_sknet(skb);
3296         struct netns_ipvs *ipvs = net_ipvs(net);
3297
3298         mutex_lock(&ipvs->sync_mutex);
3299         if ((ipvs->sync_state & IP_VS_STATE_MASTER) && !cb->args[0]) {
3300                 if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_MASTER,
3301                                            ipvs->master_mcast_ifn,
3302                                            ipvs->master_syncid, cb) < 0)
3303                         goto nla_put_failure;
3304
3305                 cb->args[0] = 1;
3306         }
3307
3308         if ((ipvs->sync_state & IP_VS_STATE_BACKUP) && !cb->args[1]) {
3309                 if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_BACKUP,
3310                                            ipvs->backup_mcast_ifn,
3311                                            ipvs->backup_syncid, cb) < 0)
3312                         goto nla_put_failure;
3313
3314                 cb->args[1] = 1;
3315         }
3316
3317 nla_put_failure:
3318         mutex_unlock(&ipvs->sync_mutex);
3319
3320         return skb->len;
3321 }
3322
3323 static int ip_vs_genl_new_daemon(struct net *net, struct nlattr **attrs)
3324 {
3325         if (!(attrs[IPVS_DAEMON_ATTR_STATE] &&
3326               attrs[IPVS_DAEMON_ATTR_MCAST_IFN] &&
3327               attrs[IPVS_DAEMON_ATTR_SYNC_ID]))
3328                 return -EINVAL;
3329
3330         /* The synchronization protocol is incompatible with mixed family
3331          * services
3332          */
3333         if (net_ipvs(net)->mixed_address_family_dests > 0)
3334                 return -EINVAL;
3335
3336         return start_sync_thread(net,
3337                                  nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]),
3338                                  nla_data(attrs[IPVS_DAEMON_ATTR_MCAST_IFN]),
3339                                  nla_get_u32(attrs[IPVS_DAEMON_ATTR_SYNC_ID]));
3340 }
3341
3342 static int ip_vs_genl_del_daemon(struct net *net, struct nlattr **attrs)
3343 {
3344         if (!attrs[IPVS_DAEMON_ATTR_STATE])
3345                 return -EINVAL;
3346
3347         return stop_sync_thread(net,
3348                                 nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]));
3349 }
3350
3351 static int ip_vs_genl_set_config(struct net *net, struct nlattr **attrs)
3352 {
3353         struct ip_vs_timeout_user t;
3354
3355         __ip_vs_get_timeouts(net, &t);
3356
3357         if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP])
3358                 t.tcp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP]);
3359
3360         if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN])
3361                 t.tcp_fin_timeout =
3362                         nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN]);
3363
3364         if (attrs[IPVS_CMD_ATTR_TIMEOUT_UDP])
3365                 t.udp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_UDP]);
3366
3367         return ip_vs_set_timeout(net, &t);
3368 }
3369
3370 static int ip_vs_genl_set_daemon(struct sk_buff *skb, struct genl_info *info)
3371 {
3372         int ret = 0, cmd;
3373         struct net *net;
3374         struct netns_ipvs *ipvs;
3375
3376         net = skb_sknet(skb);
3377         ipvs = net_ipvs(net);
3378         cmd = info->genlhdr->cmd;
3379
3380         if (cmd == IPVS_CMD_NEW_DAEMON || cmd == IPVS_CMD_DEL_DAEMON) {
3381                 struct nlattr *daemon_attrs[IPVS_DAEMON_ATTR_MAX + 1];
3382
3383                 mutex_lock(&ipvs->sync_mutex);
3384                 if (!info->attrs[IPVS_CMD_ATTR_DAEMON] ||
3385                     nla_parse_nested(daemon_attrs, IPVS_DAEMON_ATTR_MAX,
3386                                      info->attrs[IPVS_CMD_ATTR_DAEMON],
3387                                      ip_vs_daemon_policy)) {
3388                         ret = -EINVAL;
3389                         goto out;
3390                 }
3391
3392                 if (cmd == IPVS_CMD_NEW_DAEMON)
3393                         ret = ip_vs_genl_new_daemon(net, daemon_attrs);
3394                 else
3395                         ret = ip_vs_genl_del_daemon(net, daemon_attrs);
3396 out:
3397                 mutex_unlock(&ipvs->sync_mutex);
3398         }
3399         return ret;
3400 }
3401
3402 static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info)
3403 {
3404         struct ip_vs_service *svc = NULL;
3405         struct ip_vs_service_user_kern usvc;
3406         struct ip_vs_dest_user_kern udest;
3407         int ret = 0, cmd;
3408         int need_full_svc = 0, need_full_dest = 0;
3409         struct net *net;
3410
3411         net = skb_sknet(skb);
3412         cmd = info->genlhdr->cmd;
3413
3414         mutex_lock(&__ip_vs_mutex);
3415
3416         if (cmd == IPVS_CMD_FLUSH) {
3417                 ret = ip_vs_flush(net, false);
3418                 goto out;
3419         } else if (cmd == IPVS_CMD_SET_CONFIG) {
3420                 ret = ip_vs_genl_set_config(net, info->attrs);
3421                 goto out;
3422         } else if (cmd == IPVS_CMD_ZERO &&
3423                    !info->attrs[IPVS_CMD_ATTR_SERVICE]) {
3424                 ret = ip_vs_zero_all(net);
3425                 goto out;
3426         }
3427
3428         /* All following commands require a service argument, so check if we
3429          * received a valid one. We need a full service specification when
3430          * adding / editing a service. Only identifying members otherwise. */
3431         if (cmd == IPVS_CMD_NEW_SERVICE || cmd == IPVS_CMD_SET_SERVICE)
3432                 need_full_svc = 1;
3433
3434         ret = ip_vs_genl_parse_service(net, &usvc,
3435                                        info->attrs[IPVS_CMD_ATTR_SERVICE],
3436                                        need_full_svc, &svc);
3437         if (ret)
3438                 goto out;
3439
3440         /* Unless we're adding a new service, the service must already exist */
3441         if ((cmd != IPVS_CMD_NEW_SERVICE) && (svc == NULL)) {
3442                 ret = -ESRCH;
3443                 goto out;
3444         }
3445
3446         /* Destination commands require a valid destination argument. For
3447          * adding / editing a destination, we need a full destination
3448          * specification. */
3449         if (cmd == IPVS_CMD_NEW_DEST || cmd == IPVS_CMD_SET_DEST ||
3450             cmd == IPVS_CMD_DEL_DEST) {
3451                 if (cmd != IPVS_CMD_DEL_DEST)
3452                         need_full_dest = 1;
3453
3454                 ret = ip_vs_genl_parse_dest(&udest,
3455                                             info->attrs[IPVS_CMD_ATTR_DEST],
3456                                             need_full_dest);
3457                 if (ret)
3458                         goto out;
3459
3460                 /* Old protocols did not allow the user to specify address
3461                  * family, so we set it to zero instead.  We also didn't
3462                  * allow heterogeneous pools in the old code, so it's safe
3463                  * to assume that this will have the same address family as
3464                  * the service.
3465                  */
3466                 if (udest.af == 0)
3467                         udest.af = svc->af;
3468
3469                 if (udest.af != svc->af && cmd != IPVS_CMD_DEL_DEST) {
3470                         /* The synchronization protocol is incompatible
3471                          * with mixed family services
3472                          */
3473                         if (net_ipvs(net)->sync_state) {
3474                                 ret = -EINVAL;
3475                                 goto out;
3476                         }
3477
3478                         /* Which connection types do we support? */
3479                         switch (udest.conn_flags) {
3480                         case IP_VS_CONN_F_TUNNEL:
3481                                 /* We are able to forward this */
3482                                 break;
3483                         default:
3484                                 ret = -EINVAL;
3485                                 goto out;
3486                         }
3487                 }
3488         }
3489
3490         switch (cmd) {
3491         case IPVS_CMD_NEW_SERVICE:
3492                 if (svc == NULL)
3493                         ret = ip_vs_add_service(net, &usvc, &svc);
3494                 else
3495                         ret = -EEXIST;
3496                 break;
3497         case IPVS_CMD_SET_SERVICE:
3498                 ret = ip_vs_edit_service(svc, &usvc);
3499                 break;
3500         case IPVS_CMD_DEL_SERVICE:
3501                 ret = ip_vs_del_service(svc);
3502                 /* do not use svc, it can be freed */
3503                 break;
3504         case IPVS_CMD_NEW_DEST:
3505                 ret = ip_vs_add_dest(svc, &udest);
3506                 break;
3507         case IPVS_CMD_SET_DEST:
3508                 ret = ip_vs_edit_dest(svc, &udest);
3509                 break;
3510         case IPVS_CMD_DEL_DEST:
3511                 ret = ip_vs_del_dest(svc, &udest);
3512                 break;
3513         case IPVS_CMD_ZERO:
3514                 ret = ip_vs_zero_service(svc);
3515                 break;
3516         default:
3517                 ret = -EINVAL;
3518         }
3519
3520 out:
3521         mutex_unlock(&__ip_vs_mutex);
3522
3523         return ret;
3524 }
3525
3526 static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info)
3527 {
3528         struct sk_buff *msg;
3529         void *reply;
3530         int ret, cmd, reply_cmd;
3531         struct net *net;
3532
3533         net = skb_sknet(skb);
3534         cmd = info->genlhdr->cmd;
3535
3536         if (cmd == IPVS_CMD_GET_SERVICE)
3537                 reply_cmd = IPVS_CMD_NEW_SERVICE;
3538         else if (cmd == IPVS_CMD_GET_INFO)
3539                 reply_cmd = IPVS_CMD_SET_INFO;
3540         else if (cmd == IPVS_CMD_GET_CONFIG)
3541                 reply_cmd = IPVS_CMD_SET_CONFIG;
3542         else {
3543                 pr_err("unknown Generic Netlink command\n");
3544                 return -EINVAL;
3545         }
3546
3547         msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
3548         if (!msg)
3549                 return -ENOMEM;
3550
3551         mutex_lock(&__ip_vs_mutex);
3552
3553         reply = genlmsg_put_reply(msg, info, &ip_vs_genl_family, 0, reply_cmd);
3554         if (reply == NULL)
3555                 goto nla_put_failure;
3556
3557         switch (cmd) {
3558         case IPVS_CMD_GET_SERVICE:
3559         {
3560                 struct ip_vs_service *svc;
3561
3562                 svc = ip_vs_genl_find_service(net,
3563                                               info->attrs[IPVS_CMD_ATTR_SERVICE]);
3564                 if (IS_ERR(svc)) {
3565                         ret = PTR_ERR(svc);
3566                         goto out_err;
3567                 } else if (svc) {
3568                         ret = ip_vs_genl_fill_service(msg, svc);
3569                         if (ret)
3570                                 goto nla_put_failure;
3571                 } else {
3572                         ret = -ESRCH;
3573                         goto out_err;
3574                 }
3575
3576                 break;
3577         }
3578
3579         case IPVS_CMD_GET_CONFIG:
3580         {
3581                 struct ip_vs_timeout_user t;
3582
3583                 __ip_vs_get_timeouts(net, &t);
3584 #ifdef CONFIG_IP_VS_PROTO_TCP
3585                 if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP,
3586                                 t.tcp_timeout) ||
3587                     nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP_FIN,
3588                                 t.tcp_fin_timeout))
3589                         goto nla_put_failure;
3590 #endif
3591 #ifdef CONFIG_IP_VS_PROTO_UDP
3592                 if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_UDP, t.udp_timeout))
3593                         goto nla_put_failure;
3594 #endif
3595
3596                 break;
3597         }
3598
3599         case IPVS_CMD_GET_INFO:
3600                 if (nla_put_u32(msg, IPVS_INFO_ATTR_VERSION,
3601                                 IP_VS_VERSION_CODE) ||
3602                     nla_put_u32(msg, IPVS_INFO_ATTR_CONN_TAB_SIZE,
3603                                 ip_vs_conn_tab_size))
3604                         goto nla_put_failure;
3605                 break;
3606         }
3607
3608         genlmsg_end(msg, reply);
3609         ret = genlmsg_reply(msg, info);
3610         goto out;
3611
3612 nla_put_failure:
3613         pr_err("not enough space in Netlink message\n");
3614         ret = -EMSGSIZE;
3615
3616 out_err:
3617         nlmsg_free(msg);
3618 out:
3619         mutex_unlock(&__ip_vs_mutex);
3620
3621         return ret;
3622 }
3623
3624
3625 static const struct genl_ops ip_vs_genl_ops[] = {
3626         {
3627                 .cmd    = IPVS_CMD_NEW_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_SET_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_DEL_SERVICE,
3640                 .flags  = GENL_ADMIN_PERM,
3641                 .policy = ip_vs_cmd_policy,
3642                 .doit   = ip_vs_genl_set_cmd,
3643         },
3644         {
3645                 .cmd    = IPVS_CMD_GET_SERVICE,
3646                 .flags  = GENL_ADMIN_PERM,
3647                 .doit   = ip_vs_genl_get_cmd,
3648                 .dumpit = ip_vs_genl_dump_services,
3649                 .policy = ip_vs_cmd_policy,
3650         },
3651         {
3652                 .cmd    = IPVS_CMD_NEW_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_SET_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_DEL_DEST,
3665                 .flags  = GENL_ADMIN_PERM,
3666                 .policy = ip_vs_cmd_policy,
3667                 .doit   = ip_vs_genl_set_cmd,
3668         },
3669         {
3670                 .cmd    = IPVS_CMD_GET_DEST,
3671                 .flags  = GENL_ADMIN_PERM,
3672                 .policy = ip_vs_cmd_policy,
3673                 .dumpit = ip_vs_genl_dump_dests,
3674         },
3675         {
3676                 .cmd    = IPVS_CMD_NEW_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_DEL_DAEMON,
3683                 .flags  = GENL_ADMIN_PERM,
3684                 .policy = ip_vs_cmd_policy,
3685                 .doit   = ip_vs_genl_set_daemon,
3686         },
3687         {
3688                 .cmd    = IPVS_CMD_GET_DAEMON,
3689                 .flags  = GENL_ADMIN_PERM,
3690                 .dumpit = ip_vs_genl_dump_daemons,
3691         },
3692         {
3693                 .cmd    = IPVS_CMD_SET_CONFIG,
3694                 .flags  = GENL_ADMIN_PERM,
3695                 .policy = ip_vs_cmd_policy,
3696                 .doit   = ip_vs_genl_set_cmd,
3697         },
3698         {
3699                 .cmd    = IPVS_CMD_GET_CONFIG,
3700                 .flags  = GENL_ADMIN_PERM,
3701                 .doit   = ip_vs_genl_get_cmd,
3702         },
3703         {
3704                 .cmd    = IPVS_CMD_GET_INFO,
3705                 .flags  = GENL_ADMIN_PERM,
3706                 .doit   = ip_vs_genl_get_cmd,
3707         },
3708         {
3709                 .cmd    = IPVS_CMD_ZERO,
3710                 .flags  = GENL_ADMIN_PERM,
3711                 .policy = ip_vs_cmd_policy,
3712                 .doit   = ip_vs_genl_set_cmd,
3713         },
3714         {
3715                 .cmd    = IPVS_CMD_FLUSH,
3716                 .flags  = GENL_ADMIN_PERM,
3717                 .doit   = ip_vs_genl_set_cmd,
3718         },
3719 };
3720
3721 static int __init ip_vs_genl_register(void)
3722 {
3723         return genl_register_family_with_ops(&ip_vs_genl_family,
3724                                              ip_vs_genl_ops);
3725 }
3726
3727 static void ip_vs_genl_unregister(void)
3728 {
3729         genl_unregister_family(&ip_vs_genl_family);
3730 }
3731
3732 /* End of Generic Netlink interface definitions */
3733
3734 /*
3735  * per netns intit/exit func.
3736  */
3737 #ifdef CONFIG_SYSCTL
3738 static int __net_init ip_vs_control_net_init_sysctl(struct net *net)
3739 {
3740         int idx;
3741         struct netns_ipvs *ipvs = net_ipvs(net);
3742         struct ctl_table *tbl;
3743
3744         atomic_set(&ipvs->dropentry, 0);
3745         spin_lock_init(&ipvs->dropentry_lock);
3746         spin_lock_init(&ipvs->droppacket_lock);
3747         spin_lock_init(&ipvs->securetcp_lock);
3748
3749         if (!net_eq(net, &init_net)) {
3750                 tbl = kmemdup(vs_vars, sizeof(vs_vars), GFP_KERNEL);
3751                 if (tbl == NULL)
3752                         return -ENOMEM;
3753
3754                 /* Don't export sysctls to unprivileged users */
3755                 if (net->user_ns != &init_user_ns)
3756                         tbl[0].procname = NULL;
3757         } else
3758                 tbl = vs_vars;
3759         /* Initialize sysctl defaults */
3760         idx = 0;
3761         ipvs->sysctl_amemthresh = 1024;
3762         tbl[idx++].data = &ipvs->sysctl_amemthresh;
3763         ipvs->sysctl_am_droprate = 10;
3764         tbl[idx++].data = &ipvs->sysctl_am_droprate;
3765         tbl[idx++].data = &ipvs->sysctl_drop_entry;
3766         tbl[idx++].data = &ipvs->sysctl_drop_packet;
3767 #ifdef CONFIG_IP_VS_NFCT
3768         tbl[idx++].data = &ipvs->sysctl_conntrack;
3769 #endif
3770         tbl[idx++].data = &ipvs->sysctl_secure_tcp;
3771         ipvs->sysctl_snat_reroute = 1;
3772         tbl[idx++].data = &ipvs->sysctl_snat_reroute;
3773         ipvs->sysctl_sync_ver = 1;
3774         tbl[idx++].data = &ipvs->sysctl_sync_ver;
3775         ipvs->sysctl_sync_ports = 1;
3776         tbl[idx++].data = &ipvs->sysctl_sync_ports;
3777         tbl[idx++].data = &ipvs->sysctl_sync_persist_mode;
3778         ipvs->sysctl_sync_qlen_max = nr_free_buffer_pages() / 32;
3779         tbl[idx++].data = &ipvs->sysctl_sync_qlen_max;
3780         ipvs->sysctl_sync_sock_size = 0;
3781         tbl[idx++].data = &ipvs->sysctl_sync_sock_size;
3782         tbl[idx++].data = &ipvs->sysctl_cache_bypass;
3783         tbl[idx++].data = &ipvs->sysctl_expire_nodest_conn;
3784         tbl[idx++].data = &ipvs->sysctl_sloppy_tcp;
3785         tbl[idx++].data = &ipvs->sysctl_sloppy_sctp;
3786         tbl[idx++].data = &ipvs->sysctl_expire_quiescent_template;
3787         ipvs->sysctl_sync_threshold[0] = DEFAULT_SYNC_THRESHOLD;
3788         ipvs->sysctl_sync_threshold[1] = DEFAULT_SYNC_PERIOD;
3789         tbl[idx].data = &ipvs->sysctl_sync_threshold;
3790         tbl[idx++].maxlen = sizeof(ipvs->sysctl_sync_threshold);
3791         ipvs->sysctl_sync_refresh_period = DEFAULT_SYNC_REFRESH_PERIOD;
3792         tbl[idx++].data = &ipvs->sysctl_sync_refresh_period;
3793         ipvs->sysctl_sync_retries = clamp_t(int, DEFAULT_SYNC_RETRIES, 0, 3);
3794         tbl[idx++].data = &ipvs->sysctl_sync_retries;
3795         tbl[idx++].data = &ipvs->sysctl_nat_icmp_send;
3796         ipvs->sysctl_pmtu_disc = 1;
3797         tbl[idx++].data = &ipvs->sysctl_pmtu_disc;
3798         tbl[idx++].data = &ipvs->sysctl_backup_only;
3799         ipvs->sysctl_conn_reuse_mode = 1;
3800         tbl[idx++].data = &ipvs->sysctl_conn_reuse_mode;
3801
3802
3803         ipvs->sysctl_hdr = register_net_sysctl(net, "net/ipv4/vs", tbl);
3804         if (ipvs->sysctl_hdr == NULL) {
3805                 if (!net_eq(net, &init_net))
3806                         kfree(tbl);
3807                 return -ENOMEM;
3808         }
3809         ip_vs_start_estimator(net, &ipvs->tot_stats);
3810         ipvs->sysctl_tbl = tbl;
3811         /* Schedule defense work */
3812         INIT_DELAYED_WORK(&ipvs->defense_work, defense_work_handler);
3813         schedule_delayed_work(&ipvs->defense_work, DEFENSE_TIMER_PERIOD);
3814
3815         return 0;
3816 }
3817
3818 static void __net_exit ip_vs_control_net_cleanup_sysctl(struct net *net)
3819 {
3820         struct netns_ipvs *ipvs = net_ipvs(net);
3821
3822         cancel_delayed_work_sync(&ipvs->defense_work);
3823         cancel_work_sync(&ipvs->defense_work.work);
3824         unregister_net_sysctl_table(ipvs->sysctl_hdr);
3825         ip_vs_stop_estimator(net, &ipvs->tot_stats);
3826
3827         if (!net_eq(net, &init_net))
3828                 kfree(ipvs->sysctl_tbl);
3829 }
3830
3831 #else
3832
3833 static int __net_init ip_vs_control_net_init_sysctl(struct net *net) { return 0; }
3834 static void __net_exit ip_vs_control_net_cleanup_sysctl(struct net *net) { }
3835
3836 #endif
3837
3838 static struct notifier_block ip_vs_dst_notifier = {
3839         .notifier_call = ip_vs_dst_event,
3840 };
3841
3842 int __net_init ip_vs_control_net_init(struct net *net)
3843 {
3844         int i, idx;
3845         struct netns_ipvs *ipvs = net_ipvs(net);
3846
3847         /* Initialize rs_table */
3848         for (idx = 0; idx < IP_VS_RTAB_SIZE; idx++)
3849                 INIT_HLIST_HEAD(&ipvs->rs_table[idx]);
3850
3851         INIT_LIST_HEAD(&ipvs->dest_trash);
3852         spin_lock_init(&ipvs->dest_trash_lock);
3853         setup_timer(&ipvs->dest_trash_timer, ip_vs_dest_trash_expire,
3854                     (unsigned long) net);
3855         atomic_set(&ipvs->ftpsvc_counter, 0);
3856         atomic_set(&ipvs->nullsvc_counter, 0);
3857
3858         /* procfs stats */
3859         ipvs->tot_stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
3860         if (!ipvs->tot_stats.cpustats)
3861                 return -ENOMEM;
3862
3863         for_each_possible_cpu(i) {
3864                 struct ip_vs_cpu_stats *ipvs_tot_stats;
3865                 ipvs_tot_stats = per_cpu_ptr(ipvs->tot_stats.cpustats, i);
3866                 u64_stats_init(&ipvs_tot_stats->syncp);
3867         }
3868
3869         spin_lock_init(&ipvs->tot_stats.lock);
3870
3871         proc_create("ip_vs", 0, net->proc_net, &ip_vs_info_fops);
3872         proc_create("ip_vs_stats", 0, net->proc_net, &ip_vs_stats_fops);
3873         proc_create("ip_vs_stats_percpu", 0, net->proc_net,
3874                     &ip_vs_stats_percpu_fops);
3875
3876         if (ip_vs_control_net_init_sysctl(net))
3877                 goto err;
3878
3879         return 0;
3880
3881 err:
3882         free_percpu(ipvs->tot_stats.cpustats);
3883         return -ENOMEM;
3884 }
3885
3886 void __net_exit ip_vs_control_net_cleanup(struct net *net)
3887 {
3888         struct netns_ipvs *ipvs = net_ipvs(net);
3889
3890         ip_vs_trash_cleanup(net);
3891         ip_vs_control_net_cleanup_sysctl(net);
3892         remove_proc_entry("ip_vs_stats_percpu", net->proc_net);
3893         remove_proc_entry("ip_vs_stats", net->proc_net);
3894         remove_proc_entry("ip_vs", net->proc_net);
3895         free_percpu(ipvs->tot_stats.cpustats);
3896 }
3897
3898 int __init ip_vs_register_nl_ioctl(void)
3899 {
3900         int ret;
3901
3902         ret = nf_register_sockopt(&ip_vs_sockopts);
3903         if (ret) {
3904                 pr_err("cannot register sockopt.\n");
3905                 goto err_sock;
3906         }
3907
3908         ret = ip_vs_genl_register();
3909         if (ret) {
3910                 pr_err("cannot register Generic Netlink interface.\n");
3911                 goto err_genl;
3912         }
3913         return 0;
3914
3915 err_genl:
3916         nf_unregister_sockopt(&ip_vs_sockopts);
3917 err_sock:
3918         return ret;
3919 }
3920
3921 void ip_vs_unregister_nl_ioctl(void)
3922 {
3923         ip_vs_genl_unregister();
3924         nf_unregister_sockopt(&ip_vs_sockopts);
3925 }
3926
3927 int __init ip_vs_control_init(void)
3928 {
3929         int idx;
3930         int ret;
3931
3932         EnterFunction(2);
3933
3934         /* Initialize svc_table, ip_vs_svc_fwm_table */
3935         for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
3936                 INIT_HLIST_HEAD(&ip_vs_svc_table[idx]);
3937                 INIT_HLIST_HEAD(&ip_vs_svc_fwm_table[idx]);
3938         }
3939
3940         smp_wmb();      /* Do we really need it now ? */
3941
3942         ret = register_netdevice_notifier(&ip_vs_dst_notifier);
3943         if (ret < 0)
3944                 return ret;
3945
3946         LeaveFunction(2);
3947         return 0;
3948 }
3949
3950
3951 void ip_vs_control_cleanup(void)
3952 {
3953         EnterFunction(2);
3954         unregister_netdevice_notifier(&ip_vs_dst_notifier);
3955         LeaveFunction(2);
3956 }