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