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