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