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