xref: /linux/net/netfilter/ipvs/ip_vs_conn.c (revision fab183d632628381b466a41479489541ac0e29a0)
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  * The IPVS code for kernel 2.2 was done by Wensong Zhang and Peter Kese,
14  * with changes/fixes from Julian Anastasov, Lars Marowsky-Bree, Horms
15  * and others. Many code here is taken from IP MASQ code of kernel 2.2.
16  *
17  * Changes:
18  */
19 
20 #define pr_fmt(fmt) "IPVS: " fmt
21 
22 #include <linux/interrupt.h>
23 #include <linux/in.h>
24 #include <linux/inet.h>
25 #include <linux/net.h>
26 #include <linux/kernel.h>
27 #include <linux/module.h>
28 #include <linux/proc_fs.h>		/* for proc_net_* */
29 #include <linux/slab.h>
30 #include <linux/seq_file.h>
31 #include <linux/jhash.h>
32 #include <linux/random.h>
33 #include <linux/rcupdate_wait.h>
34 
35 #include <net/net_namespace.h>
36 #include <net/ip_vs.h>
37 
38 
39 #ifndef CONFIG_IP_VS_TAB_BITS
40 #define CONFIG_IP_VS_TAB_BITS	12
41 #endif
42 
43 /*
44  * Connection hash size. Default is what was selected at compile time.
45 */
46 static int ip_vs_conn_tab_bits = CONFIG_IP_VS_TAB_BITS;
47 module_param_named(conn_tab_bits, ip_vs_conn_tab_bits, int, 0444);
48 MODULE_PARM_DESC(conn_tab_bits, "Set connections' hash size");
49 
50 /* Max table size */
51 int ip_vs_conn_tab_size __read_mostly;
52 
53 /*  SLAB cache for IPVS connections */
54 static struct kmem_cache *ip_vs_conn_cachep __read_mostly;
55 
56 /* We need an addrstrlen that works with or without v6 */
57 #ifdef CONFIG_IP_VS_IPV6
58 #define IP_VS_ADDRSTRLEN INET6_ADDRSTRLEN
59 #else
60 #define IP_VS_ADDRSTRLEN (8+1)
61 #endif
62 
63 /* Connection hashing:
64  * - hash (add conn) and unhash (del conn) are safe for RCU readers walking
65  * the bucket, they will not jump to another bucket or hash table and to miss
66  * conns
67  * - rehash (fill cport) hashes the conn to new bucket or even new table,
68  * so we use seqcount to retry lookups on buckets where we delete
69  * conns (unhash) because after hashing their next ptr can point to another
70  * bucket or hash table
71  * - hash table resize works like rehash but always rehashes into new table
72  * - bit lock on bucket serializes all operations that modify the chain
73  * - on resize, bucket from the old table is locked before bucket from the
74  * new table
75  * - cp->lock protects conn fields like cp->flags, cp->dest
76  */
77 
78 /**
79  * conn_tab_lock - Lock conn_tab buckets for conn hash/unhash, not for rehash
80  * @t:		hash table for hn0, new_tbl when new_hash=true
81  * @t2:		hash table for hn1, new_tbl when new_hash2=true
82  * @cp:		connection
83  * @hash_key:	hash key for hn0
84  * @hash_key2:	hash key for hn1
85  * @use2:	using hn1 (double hashing) based on the forwarding method
86  * @new_hash:	mode for hn0, hash node (true) or seek node (false)
87  * @new_hash2:	mode for hn1, hash node (true) or seek node (false)
88  * @head_ret:	returned head for hn0
89  * @head2_ret:	returned head for hn1
90  *
91  * We support 3 modes:
92  * - seek mode for both nodes, used for unhashing
93  * - hash mode for both nodes, used for hashing
94  * - seek hn0 and hash hn1, used when forwarding method is changed
95  */
96 static __always_inline void
conn_tab_lock(struct ip_vs_rht * t,struct ip_vs_rht * t2,struct ip_vs_conn * cp,u32 hash_key,u32 hash_key2,bool use2,bool new_hash,bool new_hash2,struct hlist_bl_head ** head_ret,struct hlist_bl_head ** head2_ret)97 conn_tab_lock(struct ip_vs_rht *t, struct ip_vs_rht *t2, struct ip_vs_conn *cp,
98 	      u32 hash_key, u32 hash_key2, bool use2, bool new_hash,
99 	      bool new_hash2, struct hlist_bl_head **head_ret,
100 	      struct hlist_bl_head **head2_ret)
101 {
102 	struct hlist_bl_head *head, *head2;
103 	u32 hash_key_new, hash_key_new2;
104 	int idx = 0, idx2 = 0;
105 
106 	/* Advance idx2 when new_hash is not set but hash_key2
107 	 * is for new table
108 	 */
109 	if (new_hash2 && use2 && t != t2)
110 		idx2++;
111 
112 	if (!new_hash) {
113 		/* We need to lock the bucket in the right table */
114 
115 retry:
116 		if (!ip_vs_rht_same_table(t, hash_key)) {
117 			/* It is already moved to new table */
118 			t = rcu_dereference(t->new_tbl);
119 			/* Rehashing works in two steps and we may detect
120 			 * both nodes in different tables, use idx/idx2
121 			 * for proper lock ordering for heads.
122 			 */
123 			idx++;
124 		}
125 	}
126 	if (use2 && !new_hash2 && !ip_vs_rht_same_table(t2, hash_key2)) {
127 		/* It is already moved to new table */
128 		t2 = rcu_dereference(t2->new_tbl);
129 		idx2++;
130 	}
131 
132 	if (!use2)
133 		idx2 = idx;
134 	head = t->buckets + (hash_key & t->mask);
135 	head2 = use2 ? t2->buckets + (hash_key2 & t2->mask) : head;
136 
137 	if (idx > idx2 || (head > head2 && idx == idx2)) {
138 		hlist_bl_lock(head2);
139 		hlist_bl_lock(head);
140 	} else {
141 		hlist_bl_lock(head);
142 		if (head != head2)
143 			hlist_bl_lock(head2);
144 	}
145 	if (!new_hash) {
146 		bool changed;
147 
148 		/* Ensure hash_key is read under lock */
149 		hash_key_new = READ_ONCE(cp->hn0.hash_key);
150 		changed = hash_key != hash_key_new;
151 		if (use2 && !new_hash2) {
152 			hash_key_new2 = READ_ONCE(cp->hn1.hash_key);
153 			changed |= hash_key2 != hash_key_new2;
154 		} else {
155 			hash_key_new2 = hash_key2;
156 		}
157 		/* Hash changed ? */
158 		if (changed) {
159 			if (head != head2)
160 				hlist_bl_unlock(head2);
161 			hlist_bl_unlock(head);
162 			hash_key = hash_key_new;
163 			hash_key2 = hash_key_new2;
164 			goto retry;
165 		}
166 	}
167 	*head_ret = head;
168 	*head2_ret = head2;
169 }
170 
conn_tab_unlock(struct hlist_bl_head * head,struct hlist_bl_head * head2)171 static inline void conn_tab_unlock(struct hlist_bl_head *head,
172 				   struct hlist_bl_head *head2)
173 {
174 	if (head != head2)
175 		hlist_bl_unlock(head2);
176 	hlist_bl_unlock(head);
177 }
178 
179 static void ip_vs_conn_expire(struct timer_list *t);
180 
181 /*
182  *	Returns hash value for IPVS connection entry
183  */
ip_vs_conn_hashkey(struct ip_vs_rht * t,int af,unsigned int proto,const union nf_inet_addr * addr,__be16 port,const union nf_inet_addr * laddr,__be16 lport)184 static u32 ip_vs_conn_hashkey(struct ip_vs_rht *t, int af, unsigned int proto,
185 			      const union nf_inet_addr *addr, __be16 port,
186 			      const union nf_inet_addr *laddr, __be16 lport)
187 {
188 	u64 a = (u32)proto << 16 | (__force u32)port;
189 	u64 d;
190 
191 #ifdef CONFIG_IP_VS_IPV6
192 	if (af == AF_INET6) {
193 		u64 b = (u64)addr->all[0] << 32 | addr->all[1];
194 		u64 c = (u64)addr->all[2] << 32 | addr->all[3];
195 
196 		a |= (u64)laddr->all[2] << 32 ^ (__force u32)lport;
197 		c ^= laddr->all[1];
198 		d = (u64)laddr->all[0] << 32 | laddr->all[3];
199 		return (u32)siphash_4u64(a, b, c, d, &t->hash_key);
200 	}
201 #endif
202 	a |= (u64)addr->all[0] << 32;
203 	d = (u64)laddr->all[0] << 32 | (__force u32)lport;
204 	return (u32)siphash_2u64(a, d, &t->hash_key);
205 }
206 
ip_vs_conn_hashkey_param(const struct ip_vs_conn_param * p,struct ip_vs_rht * t,bool inverse)207 static unsigned int ip_vs_conn_hashkey_param(const struct ip_vs_conn_param *p,
208 					     struct ip_vs_rht *t, bool inverse)
209 {
210 	const union nf_inet_addr *laddr;
211 	const union nf_inet_addr *addr;
212 	__be16 lport;
213 	__be16 port;
214 
215 	if (p->pe_data && p->pe->hashkey_raw)
216 		return p->pe->hashkey_raw(p, t, inverse);
217 
218 	if (likely(!inverse)) {
219 		addr = p->caddr;
220 		port = p->cport;
221 		laddr = p->vaddr;
222 		lport = p->vport;
223 	} else {
224 		addr = p->vaddr;
225 		port = p->vport;
226 		laddr = p->caddr;
227 		lport = p->cport;
228 	}
229 
230 	return ip_vs_conn_hashkey(t, p->af, p->protocol, addr, port, laddr,
231 				  lport);
232 }
233 
ip_vs_conn_hashkey_conn(struct ip_vs_rht * t,const struct ip_vs_conn * cp,bool out)234 static unsigned int ip_vs_conn_hashkey_conn(struct ip_vs_rht *t,
235 					    const struct ip_vs_conn *cp,
236 					    bool out)
237 {
238 	struct ip_vs_conn_param p;
239 
240 	if (!out)
241 		ip_vs_conn_fill_param(cp->ipvs, cp->af, cp->protocol,
242 				      &cp->caddr, cp->cport, &cp->vaddr,
243 				      cp->vport, &p);
244 	else
245 		ip_vs_conn_fill_param(cp->ipvs, cp->af, cp->protocol,
246 				      &cp->daddr, cp->dport, &cp->caddr,
247 				      cp->cport, &p);
248 
249 	if (cp->pe) {
250 		p.pe = cp->pe;
251 		p.pe_data = cp->pe_data;
252 		p.pe_data_len = cp->pe_data_len;
253 	}
254 
255 	return ip_vs_conn_hashkey_param(&p, t, out);
256 }
257 
258 /*	Hashes ip_vs_conn in conn_tab
259  *	returns bool success.
260  */
ip_vs_conn_hash(struct ip_vs_conn * cp)261 static inline int ip_vs_conn_hash(struct ip_vs_conn *cp)
262 {
263 	struct netns_ipvs *ipvs = cp->ipvs;
264 	struct hlist_bl_head *head, *head2;
265 	u32 hash_key, hash_key2;
266 	struct ip_vs_rht *t;
267 	u32 hash, hash2;
268 	bool use2;
269 	int ret;
270 
271 	if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
272 		return 0;
273 
274 	/* New entries go into recent table */
275 	t = rcu_dereference(ipvs->conn_tab);
276 	t = rcu_dereference(t->new_tbl);
277 
278 	hash = ip_vs_conn_hashkey_conn(t, cp, false);
279 	hash_key = ip_vs_rht_build_hash_key(t, hash);
280 	if (ip_vs_conn_use_hash2(cp)) {
281 		hash2 = ip_vs_conn_hashkey_conn(t, cp, true);
282 		hash_key2 = ip_vs_rht_build_hash_key(t, hash2);
283 		use2 = true;
284 	} else {
285 		hash_key2 = hash_key;
286 		use2 = false;
287 	}
288 
289 	local_bh_disable();
290 	conn_tab_lock(t, t, cp, hash_key, hash_key2, use2, true /* new_hash */,
291 		      true /* new_hash2 */, &head, &head2);
292 
293 	cp->flags |= IP_VS_CONN_F_HASHED;
294 	WRITE_ONCE(cp->hn0.hash_key, hash_key);
295 	WRITE_ONCE(cp->hn1.hash_key, hash_key2);
296 	refcount_inc(&cp->refcnt);
297 	hlist_bl_add_head_rcu(&cp->hn0.node, head);
298 	if (use2)
299 		hlist_bl_add_head_rcu(&cp->hn1.node, head2);
300 
301 	conn_tab_unlock(head, head2);
302 	local_bh_enable();
303 	ret = 1;
304 
305 	/* Schedule resizing if load increases */
306 	if (atomic_read(&ipvs->conn_count) > t->u_thresh &&
307 	    !test_and_set_bit(IP_VS_WORK_CONN_RESIZE, &ipvs->work_flags))
308 		mod_delayed_work(system_dfl_long_wq, &ipvs->conn_resize_work, 0);
309 
310 	return ret;
311 }
312 
313 /* Try to unlink ip_vs_conn from conn_tab.
314  * returns bool success.
315  */
ip_vs_conn_unlink(struct ip_vs_conn * cp)316 static inline bool ip_vs_conn_unlink(struct ip_vs_conn *cp)
317 {
318 	struct netns_ipvs *ipvs = cp->ipvs;
319 	struct hlist_bl_head *head, *head2;
320 	u32 hash_key, hash_key2;
321 	struct ip_vs_rht *t;
322 	bool ret = false;
323 	bool use2;
324 
325 	if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
326 		return refcount_dec_if_one(&cp->refcnt);
327 
328 	rcu_read_lock();
329 	local_bh_disable();
330 
331 	t = rcu_dereference(ipvs->conn_tab);
332 	hash_key = READ_ONCE(cp->hn0.hash_key);
333 	hash_key2 = READ_ONCE(cp->hn1.hash_key);
334 	use2 = ip_vs_conn_use_hash2(cp);
335 
336 	conn_tab_lock(t, t, cp, hash_key, hash_key2, use2, false /* new_hash */,
337 		      false /* new_hash2 */, &head, &head2);
338 
339 	if (cp->flags & IP_VS_CONN_F_HASHED) {
340 		/* Decrease refcnt and unlink conn only if we are last user */
341 		if (use2 == ip_vs_conn_use_hash2(cp) &&
342 		    refcount_dec_if_one(&cp->refcnt)) {
343 			hlist_bl_del_rcu(&cp->hn0.node);
344 			if (use2)
345 				hlist_bl_del_rcu(&cp->hn1.node);
346 			cp->flags &= ~IP_VS_CONN_F_HASHED;
347 			ret = true;
348 		}
349 	}
350 
351 	conn_tab_unlock(head, head2);
352 
353 	local_bh_enable();
354 	rcu_read_unlock();
355 
356 	return ret;
357 }
358 
359 
360 /*
361  *  Gets ip_vs_conn associated with supplied parameters in the conn_tab.
362  *  Called for pkts coming from OUTside-to-INside.
363  *	p->caddr, p->cport: pkt source address (foreign host)
364  *	p->vaddr, p->vport: pkt dest address (load balancer)
365  */
366 static inline struct ip_vs_conn *
__ip_vs_conn_in_get(const struct ip_vs_conn_param * p)367 __ip_vs_conn_in_get(const struct ip_vs_conn_param *p)
368 {
369 	DECLARE_IP_VS_RHT_WALK_BUCKET_RCU();
370 	struct netns_ipvs *ipvs = p->ipvs;
371 	struct ip_vs_conn_hnode *hn;
372 	struct hlist_bl_head *head;
373 	struct ip_vs_rht *t, *pt;
374 	struct hlist_bl_node *e;
375 	struct ip_vs_conn *cp;
376 	u32 hash, hash_key;
377 
378 	rcu_read_lock();
379 
380 	ip_vs_rht_for_each_table_rcu(ipvs->conn_tab, t, pt) {
381 		hash = ip_vs_conn_hashkey_param(p, t, false);
382 		hash_key = ip_vs_rht_build_hash_key(t, hash);
383 		ip_vs_rht_walk_bucket_rcu(t, hash_key, head) {
384 			hlist_bl_for_each_entry_rcu(hn, e, head, node) {
385 				if (READ_ONCE(hn->hash_key) != hash_key ||
386 				    hn->dir != 0)
387 					continue;
388 				cp = ip_vs_hn0_to_conn(hn);
389 				if (p->cport == cp->cport &&
390 				    p->vport == cp->vport && cp->af == p->af &&
391 				    ip_vs_addr_equal(p->af, p->caddr,
392 						     &cp->caddr) &&
393 				    ip_vs_addr_equal(p->af, p->vaddr,
394 						     &cp->vaddr) &&
395 				    (!p->cport ^
396 				     (!(cp->flags & IP_VS_CONN_F_NO_CPORT))) &&
397 				    p->protocol == cp->protocol) {
398 					if (__ip_vs_conn_get(cp)) {
399 						/* HIT */
400 						rcu_read_unlock();
401 						return cp;
402 					}
403 				}
404 			}
405 		}
406 	}
407 
408 	rcu_read_unlock();
409 
410 	return NULL;
411 }
412 
ip_vs_conn_in_get(const struct ip_vs_conn_param * p)413 struct ip_vs_conn *ip_vs_conn_in_get(const struct ip_vs_conn_param *p)
414 {
415 	struct ip_vs_conn *cp;
416 
417 	cp = __ip_vs_conn_in_get(p);
418 	if (!cp) {
419 		struct netns_ipvs *ipvs = p->ipvs;
420 		int af_id = ip_vs_af_index(p->af);
421 
422 		if (atomic_read(&ipvs->no_cport_conns[af_id])) {
423 			struct ip_vs_conn_param cport_zero_p = *p;
424 
425 			cport_zero_p.cport = 0;
426 			cp = __ip_vs_conn_in_get(&cport_zero_p);
427 		}
428 	}
429 
430 	IP_VS_DBG_BUF(9, "lookup/in %s %s:%d->%s:%d %s\n",
431 		      ip_vs_proto_name(p->protocol),
432 		      IP_VS_DBG_ADDR(p->af, p->caddr), ntohs(p->cport),
433 		      IP_VS_DBG_ADDR(p->af, p->vaddr), ntohs(p->vport),
434 		      cp ? "hit" : "not hit");
435 
436 	return cp;
437 }
438 
439 static int
ip_vs_conn_fill_param_proto(struct netns_ipvs * ipvs,int af,const struct sk_buff * skb,const struct ip_vs_iphdr * iph,struct ip_vs_conn_param * p)440 ip_vs_conn_fill_param_proto(struct netns_ipvs *ipvs,
441 			    int af, const struct sk_buff *skb,
442 			    const struct ip_vs_iphdr *iph,
443 			    struct ip_vs_conn_param *p)
444 {
445 	__be16 _ports[2], *pptr;
446 
447 	pptr = frag_safe_skb_hp(skb, iph->len, sizeof(_ports), _ports);
448 	if (pptr == NULL)
449 		return 1;
450 
451 	if (likely(!ip_vs_iph_inverse(iph)))
452 		ip_vs_conn_fill_param(ipvs, af, iph->protocol, &iph->saddr,
453 				      pptr[0], &iph->daddr, pptr[1], p);
454 	else
455 		ip_vs_conn_fill_param(ipvs, af, iph->protocol, &iph->daddr,
456 				      pptr[1], &iph->saddr, pptr[0], p);
457 	return 0;
458 }
459 
460 struct ip_vs_conn *
ip_vs_conn_in_get_proto(struct netns_ipvs * ipvs,int af,const struct sk_buff * skb,const struct ip_vs_iphdr * iph)461 ip_vs_conn_in_get_proto(struct netns_ipvs *ipvs, int af,
462 			const struct sk_buff *skb,
463 			const struct ip_vs_iphdr *iph)
464 {
465 	struct ip_vs_conn_param p;
466 
467 	if (ip_vs_conn_fill_param_proto(ipvs, af, skb, iph, &p))
468 		return NULL;
469 
470 	return ip_vs_conn_in_get(&p);
471 }
472 EXPORT_SYMBOL_GPL(ip_vs_conn_in_get_proto);
473 
474 /* Get reference to connection template */
ip_vs_ct_in_get(const struct ip_vs_conn_param * p)475 struct ip_vs_conn *ip_vs_ct_in_get(const struct ip_vs_conn_param *p)
476 {
477 	DECLARE_IP_VS_RHT_WALK_BUCKET_RCU();
478 	struct netns_ipvs *ipvs = p->ipvs;
479 	struct ip_vs_conn_hnode *hn;
480 	struct hlist_bl_head *head;
481 	struct ip_vs_rht *t, *pt;
482 	struct hlist_bl_node *e;
483 	struct ip_vs_conn *cp;
484 	u32 hash, hash_key;
485 
486 	rcu_read_lock();
487 
488 	ip_vs_rht_for_each_table_rcu(ipvs->conn_tab, t, pt) {
489 		hash = ip_vs_conn_hashkey_param(p, t, false);
490 		hash_key = ip_vs_rht_build_hash_key(t, hash);
491 		ip_vs_rht_walk_bucket_rcu(t, hash_key, head) {
492 			hlist_bl_for_each_entry_rcu(hn, e, head, node) {
493 				if (READ_ONCE(hn->hash_key) != hash_key ||
494 				    hn->dir != 0)
495 					continue;
496 				cp = ip_vs_hn0_to_conn(hn);
497 				if (unlikely(p->pe_data && p->pe->ct_match)) {
498 					if (p->pe == cp->pe &&
499 					    p->pe->ct_match(p, cp) &&
500 					    __ip_vs_conn_get(cp))
501 						goto out;
502 					continue;
503 				}
504 				if (cp->af == p->af &&
505 				    ip_vs_addr_equal(p->af, p->caddr,
506 						     &cp->caddr) &&
507 				    /* protocol should only be IPPROTO_IP if
508 				     * p->vaddr is a fwmark
509 				     */
510 				    ip_vs_addr_equal(p->protocol == IPPROTO_IP ?
511 						     AF_UNSPEC : p->af,
512 						     p->vaddr, &cp->vaddr) &&
513 				    p->vport == cp->vport &&
514 				    p->cport == cp->cport &&
515 				    cp->flags & IP_VS_CONN_F_TEMPLATE &&
516 				    p->protocol == cp->protocol &&
517 				    cp->dport != htons(0xffff)) {
518 					if (__ip_vs_conn_get(cp))
519 						goto out;
520 				}
521 			}
522 		}
523 
524 	}
525 	cp = NULL;
526 
527   out:
528 	rcu_read_unlock();
529 
530 	IP_VS_DBG_BUF(9, "template lookup/in %s %s:%d->%s:%d %s\n",
531 		      ip_vs_proto_name(p->protocol),
532 		      IP_VS_DBG_ADDR(p->af, p->caddr), ntohs(p->cport),
533 		      IP_VS_DBG_ADDR(p->af, p->vaddr), ntohs(p->vport),
534 		      cp ? "hit" : "not hit");
535 
536 	return cp;
537 }
538 
539 /* Gets ip_vs_conn associated with supplied parameters in the conn_tab.
540  * Called for pkts coming from inside-to-OUTside.
541  *	p->caddr, p->cport: pkt source address (inside host)
542  *	p->vaddr, p->vport: pkt dest address (foreign host) */
ip_vs_conn_out_get(const struct ip_vs_conn_param * p)543 struct ip_vs_conn *ip_vs_conn_out_get(const struct ip_vs_conn_param *p)
544 {
545 	DECLARE_IP_VS_RHT_WALK_BUCKET_RCU();
546 	struct netns_ipvs *ipvs = p->ipvs;
547 	const union nf_inet_addr *saddr;
548 	struct ip_vs_conn_hnode *hn;
549 	struct hlist_bl_head *head;
550 	struct ip_vs_rht *t, *pt;
551 	struct hlist_bl_node *e;
552 	struct ip_vs_conn *cp;
553 	u32 hash, hash_key;
554 	__be16 sport;
555 
556 	rcu_read_lock();
557 
558 	ip_vs_rht_for_each_table_rcu(ipvs->conn_tab, t, pt) {
559 		hash = ip_vs_conn_hashkey_param(p, t, true);
560 		hash_key = ip_vs_rht_build_hash_key(t, hash);
561 		ip_vs_rht_walk_bucket_rcu(t, hash_key, head) {
562 			hlist_bl_for_each_entry_rcu(hn, e, head, node) {
563 				/* dir can be 0 for DR/TUN */
564 				if (READ_ONCE(hn->hash_key) != hash_key)
565 					continue;
566 				cp = ip_vs_hn_to_conn(hn);
567 				if (p->vport != cp->cport)
568 					continue;
569 
570 				if (IP_VS_FWD_METHOD(cp) != IP_VS_CONN_F_MASQ) {
571 					sport = cp->vport;
572 					saddr = &cp->vaddr;
573 				} else {
574 					sport = cp->dport;
575 					saddr = &cp->daddr;
576 				}
577 
578 				if (p->cport == sport && cp->af == p->af &&
579 				    ip_vs_addr_equal(p->af, p->vaddr,
580 						     &cp->caddr) &&
581 				    ip_vs_addr_equal(p->af, p->caddr, saddr) &&
582 				    p->protocol == cp->protocol) {
583 					if (__ip_vs_conn_get(cp))
584 						goto out;
585 				}
586 			}
587 		}
588 	}
589 	cp = NULL;
590 
591 out:
592 	rcu_read_unlock();
593 
594 	IP_VS_DBG_BUF(9, "lookup/out %s %s:%d->%s:%d %s\n",
595 		      ip_vs_proto_name(p->protocol),
596 		      IP_VS_DBG_ADDR(p->af, p->caddr), ntohs(p->cport),
597 		      IP_VS_DBG_ADDR(p->af, p->vaddr), ntohs(p->vport),
598 		      cp ? "hit" : "not hit");
599 
600 	return cp;
601 }
602 
603 struct ip_vs_conn *
ip_vs_conn_out_get_proto(struct netns_ipvs * ipvs,int af,const struct sk_buff * skb,const struct ip_vs_iphdr * iph)604 ip_vs_conn_out_get_proto(struct netns_ipvs *ipvs, int af,
605 			 const struct sk_buff *skb,
606 			 const struct ip_vs_iphdr *iph)
607 {
608 	struct ip_vs_conn_param p;
609 
610 	if (ip_vs_conn_fill_param_proto(ipvs, af, skb, iph, &p))
611 		return NULL;
612 
613 	return ip_vs_conn_out_get(&p);
614 }
615 EXPORT_SYMBOL_GPL(ip_vs_conn_out_get_proto);
616 
617 /*
618  *      Put back the conn and restart its timer with its timeout
619  */
__ip_vs_conn_put_timer(struct ip_vs_conn * cp)620 static void __ip_vs_conn_put_timer(struct ip_vs_conn *cp)
621 {
622 	unsigned long t = (cp->flags & IP_VS_CONN_F_ONE_PACKET) ?
623 		0 : cp->timeout;
624 	mod_timer(&cp->timer, jiffies+t);
625 
626 	__ip_vs_conn_put(cp);
627 }
628 
ip_vs_conn_put(struct ip_vs_conn * cp)629 void ip_vs_conn_put(struct ip_vs_conn *cp)
630 {
631 	if ((cp->flags & IP_VS_CONN_F_ONE_PACKET) &&
632 	    (refcount_read(&cp->refcnt) == 1) &&
633 	    !timer_pending(&cp->timer))
634 		/* expire connection immediately */
635 		ip_vs_conn_expire(&cp->timer);
636 	else
637 		__ip_vs_conn_put_timer(cp);
638 }
639 
640 /*
641  *	Fill a no_client_port connection with a client port number
642  */
ip_vs_conn_fill_cport(struct ip_vs_conn * cp,__be16 cport)643 void ip_vs_conn_fill_cport(struct ip_vs_conn *cp, __be16 cport)
644 {
645 	struct hlist_bl_head *head, *head2, *head_new;
646 	bool use2 = ip_vs_conn_use_hash2(cp);
647 	struct netns_ipvs *ipvs = cp->ipvs;
648 	int af_id = ip_vs_af_index(cp->af);
649 	u32 hash_r = 0, hash_key_r = 0;
650 	struct ip_vs_rht *t, *tp, *t2;
651 	struct ip_vs_conn_hnode *hn;
652 	u32 hash_key, hash_key_new;
653 	struct ip_vs_conn_param p;
654 	bool by_me = false;
655 	int ntbl;
656 	int dir;
657 
658 restart:
659 	/* No packets from inside, so we can do it in 2 steps. */
660 	dir = use2 ? 1 : 0;
661 
662 next_dir:
663 	if (dir)
664 		ip_vs_conn_fill_param(ipvs, cp->af, cp->protocol, &cp->daddr,
665 				      cp->dport, &cp->caddr, cport, &p);
666 	else
667 		ip_vs_conn_fill_param(ipvs, cp->af, cp->protocol, &cp->caddr,
668 				      cport, &cp->vaddr, cp->vport, &p);
669 	hn = dir ? &cp->hn1 : &cp->hn0;
670 	ntbl = 0;
671 
672 	/* Attempt to rehash cp safely, by informing seqcount readers */
673 	t = rcu_dereference(ipvs->conn_tab);
674 	hash_key = READ_ONCE(hn->hash_key);
675 	tp = NULL;
676 
677 retry:
678 	/* Moved to new table ? */
679 	if (!ip_vs_rht_same_table(t, hash_key)) {
680 		t = rcu_dereference(t->new_tbl);
681 		ntbl++;
682 		/* We are lost? */
683 		if (ntbl >= 2) {
684 			spin_lock_bh(&cp->lock);
685 			if (cp->flags & IP_VS_CONN_F_NO_CPORT && by_me)
686 				cp->cport = 0;
687 			/* hn1 will be rehashed on next packet */
688 			spin_unlock_bh(&cp->lock);
689 			IP_VS_ERR_RL("%s(): Too many ht changes for dir %d\n",
690 				     __func__, dir);
691 			return;
692 		}
693 	}
694 
695 	/* Rehashing during resize? Use the recent table for adds */
696 	t2 = rcu_dereference(t->new_tbl);
697 	/* Calc new hash once per table */
698 	if (tp != t2) {
699 		hash_r = ip_vs_conn_hashkey_param(&p, t2, dir);
700 		hash_key_r = ip_vs_rht_build_hash_key(t2, hash_r);
701 		tp = t2;
702 	}
703 	head = t->buckets + (hash_key & t->mask);
704 	head2 = t2->buckets + (hash_key_r & t2->mask);
705 	head_new = head2;
706 
707 	if (head > head2 && t == t2)
708 		swap(head, head2);
709 
710 	/* Protect the cp->flags modification */
711 	spin_lock_bh(&cp->lock);
712 
713 	/* Recheck the forwarding method under lock */
714 	if (use2 != ip_vs_conn_use_hash2(cp)) {
715 		use2 = !use2;
716 		if (use2) {
717 			spin_unlock_bh(&cp->lock);
718 			/* Restart with new use2 value */
719 			goto restart;
720 		}
721 		if (dir) {
722 			/* Not started yet, so just skip dir 1 */
723 			spin_unlock_bh(&cp->lock);
724 			dir--;
725 			goto next_dir;
726 		}
727 		/* Just finish dir 0 */
728 	}
729 
730 	/* Lock seqcount only for the old bucket, even if we are on new table
731 	 * because it affects the del operation, not the adding.
732 	 */
733 	spin_lock(&t->lock[hash_key & t->lock_mask].l);
734 	preempt_disable_nested();
735 	write_seqcount_begin(&t->seqc[hash_key & t->seqc_mask]);
736 
737 	/* Lock buckets in same (increasing) order */
738 	hlist_bl_lock(head);
739 	if (head != head2)
740 		hlist_bl_lock(head2);
741 
742 	/* Ensure hash_key is read under lock */
743 	hash_key_new = READ_ONCE(hn->hash_key);
744 	/* Racing with another rehashing ? */
745 	if (unlikely(hash_key != hash_key_new)) {
746 		if (head != head2)
747 			hlist_bl_unlock(head2);
748 		hlist_bl_unlock(head);
749 		write_seqcount_end(&t->seqc[hash_key & t->seqc_mask]);
750 		preempt_enable_nested();
751 		spin_unlock(&t->lock[hash_key & t->lock_mask].l);
752 		spin_unlock_bh(&cp->lock);
753 		hash_key = hash_key_new;
754 		goto retry;
755 	}
756 
757 	/* Fill cport once, even if multiple packets try to do it */
758 	if (cp->flags & IP_VS_CONN_F_NO_CPORT && (!cp->cport || by_me)) {
759 		/* If we race with resizing make sure cport is set for dir 1 */
760 		if (!cp->cport) {
761 			cp->cport = cport;
762 			by_me = true;
763 		}
764 		if (!dir) {
765 			atomic_dec(&ipvs->no_cport_conns[af_id]);
766 			cp->flags &= ~IP_VS_CONN_F_NO_CPORT;
767 		}
768 		/* We do not recalc hash_key_r under lock, we assume the
769 		 * parameters in cp do not change, i.e. cport is
770 		 * the only possible change.
771 		 */
772 		WRITE_ONCE(hn->hash_key, hash_key_r);
773 		if (!use2)
774 			WRITE_ONCE(cp->hn1.hash_key, hash_key_r);
775 		/* For dir=1 we do not check in flags if hn is already
776 		 * rehashed but this check will do it.
777 		 */
778 		if (head != head2) {
779 			hlist_bl_del_rcu(&hn->node);
780 			hlist_bl_add_head_rcu(&hn->node, head_new);
781 		}
782 	}
783 
784 	if (head != head2)
785 		hlist_bl_unlock(head2);
786 	hlist_bl_unlock(head);
787 	write_seqcount_end(&t->seqc[hash_key & t->seqc_mask]);
788 	preempt_enable_nested();
789 	spin_unlock(&t->lock[hash_key & t->lock_mask].l);
790 
791 	spin_unlock_bh(&cp->lock);
792 	if (dir-- && by_me)
793 		goto next_dir;
794 }
795 
796 /* Change forwarding method for hashed conn */
ip_vs_conn_change_fwd_mask(struct ip_vs_conn * cp,u32 new_flags)797 static void ip_vs_conn_change_fwd_mask(struct ip_vs_conn *cp, u32 new_flags)
798 {
799 	struct netns_ipvs *ipvs = cp->ipvs;
800 	struct hlist_bl_head *head, *head2;
801 	u32 hash2, hash_key, hash_key2;
802 	struct ip_vs_rht *t, *t2;
803 
804 	/* See ip_vs_conn_use_hash2() for reference */
805 	if ((cp->flags & IP_VS_CONN_F_TEMPLATE) ||
806 	    /* No change in double hashing ? */
807 	    (IP_VS_FWD_METHOD(cp) == IP_VS_CONN_F_MASQ) ==
808 	    ((new_flags & IP_VS_CONN_F_FWD_MASK) == IP_VS_CONN_F_MASQ)) {
809 		cp->flags = new_flags;
810 		return;
811 	}
812 	t = rcu_dereference(ipvs->conn_tab);
813 	if (ip_vs_conn_use_hash2(cp)) {
814 		/* Stop double hashing */
815 		hash_key = READ_ONCE(cp->hn0.hash_key);
816 		hash_key2 = READ_ONCE(cp->hn1.hash_key);
817 
818 		conn_tab_lock(t, t, cp, hash_key, hash_key2, true /* use2 */,
819 			      false /* new_hash */, false /* new_hash2 */,
820 			      &head, &head2);
821 
822 		/* Keep both hash keys in same table */
823 		hash_key = READ_ONCE(cp->hn0.hash_key);
824 		WRITE_ONCE(cp->hn1.hash_key, hash_key);
825 		hlist_bl_del_rcu(&cp->hn1.node);
826 		cp->flags = new_flags;
827 
828 		conn_tab_unlock(head, head2);
829 	} else {
830 		/* Start double hashing */
831 
832 		hash_key = READ_ONCE(cp->hn0.hash_key);
833 
834 		t2 = rcu_dereference(t->new_tbl);
835 		hash2 = ip_vs_conn_hashkey_conn(t2, cp, true);
836 		hash_key2 = ip_vs_rht_build_hash_key(t2, hash2);
837 
838 		/* Change the forwarding method under locked hn0 */
839 		conn_tab_lock(t, t2, cp, hash_key, hash_key2, true /* use2 */,
840 			      false /* new_hash */, true /* new_hash2 */,
841 			      &head, &head2);
842 
843 		WRITE_ONCE(cp->hn1.hash_key, hash_key2);
844 		cp->flags = new_flags;
845 		hlist_bl_add_head_rcu(&cp->hn1.node, head2);
846 
847 		conn_tab_unlock(head, head2);
848 	}
849 }
850 
851 /* Get default load factor to map conn_count/u_thresh to t->size */
ip_vs_conn_default_load_factor(struct netns_ipvs * ipvs)852 static int ip_vs_conn_default_load_factor(struct netns_ipvs *ipvs)
853 {
854 	int factor;
855 
856 	if (net_eq(ipvs->net, &init_net))
857 		factor = -3;
858 	else
859 		factor = -1;
860 	/* Double hashing adds twice more nodes for NAT */
861 	factor--;
862 	return factor;
863 }
864 
865 /* Get the desired conn_tab size */
ip_vs_conn_desired_size(struct netns_ipvs * ipvs,struct ip_vs_rht * t,int lfactor)866 int ip_vs_conn_desired_size(struct netns_ipvs *ipvs, struct ip_vs_rht *t,
867 			    int lfactor)
868 {
869 	return ip_vs_rht_desired_size(ipvs, t, atomic_read(&ipvs->conn_count),
870 				      lfactor, IP_VS_CONN_TAB_MIN_BITS,
871 				      ip_vs_conn_tab_bits);
872 }
873 
874 /* Allocate conn_tab */
ip_vs_conn_tab_alloc(struct netns_ipvs * ipvs,int buckets,int lfactor)875 struct ip_vs_rht *ip_vs_conn_tab_alloc(struct netns_ipvs *ipvs, int buckets,
876 				       int lfactor)
877 {
878 	struct ip_vs_rht *t;
879 	int scounts, locks;
880 
881 	/* scounts: affects readers during resize */
882 	scounts = clamp(buckets >> 6, 1, 256);
883 	/* locks: based on parallel IP_VS_CONN_F_NO_CPORT operations + resize */
884 	locks = clamp(8, 1, scounts);
885 
886 	t = ip_vs_rht_alloc(buckets, scounts, locks);
887 	if (!t)
888 		return NULL;
889 	t->lfactor = lfactor;
890 	ip_vs_rht_set_thresholds(t, t->size, lfactor, IP_VS_CONN_TAB_MIN_BITS,
891 				 ip_vs_conn_tab_bits);
892 	return t;
893 }
894 
895 /* conn_tab resizer work */
conn_resize_work_handler(struct work_struct * work)896 static void conn_resize_work_handler(struct work_struct *work)
897 {
898 	struct hlist_bl_head *head, *head2;
899 	unsigned int resched_score = 0;
900 	struct hlist_bl_node *cn, *nn;
901 	struct ip_vs_rht *t, *t_new;
902 	struct ip_vs_conn_hnode *hn;
903 	struct netns_ipvs *ipvs;
904 	struct ip_vs_conn *cp;
905 	bool more_work = false;
906 	u32 hash, hash_key;
907 	int limit = 0;
908 	int new_size;
909 	int lfactor;
910 	u32 bucket;
911 
912 	ipvs = container_of(work, struct netns_ipvs, conn_resize_work.work);
913 
914 	/* Allow work to be queued again */
915 	clear_bit(IP_VS_WORK_CONN_RESIZE, &ipvs->work_flags);
916 	t = rcu_dereference_protected(ipvs->conn_tab, 1);
917 	/* Do nothing if table is removed */
918 	if (!t)
919 		goto out;
920 	/* New table needs to be registered? BUG! */
921 	if (t != rcu_dereference_protected(t->new_tbl, 1))
922 		goto out;
923 
924 	lfactor = sysctl_conn_lfactor(ipvs);
925 	/* Should we resize ? */
926 	new_size = ip_vs_conn_desired_size(ipvs, t, lfactor);
927 	if (new_size == t->size && lfactor == t->lfactor)
928 		goto out;
929 
930 	t_new = ip_vs_conn_tab_alloc(ipvs, new_size, lfactor);
931 	if (!t_new) {
932 		more_work = true;
933 		goto out;
934 	}
935 	/* Flip the table_id */
936 	t_new->table_id = t->table_id ^ IP_VS_RHT_TABLE_ID_MASK;
937 
938 	rcu_assign_pointer(t->new_tbl, t_new);
939 
940 	/* Wait RCU readers to see the new table, we do not want new
941 	 * conns to go into old table and to be left there.
942 	 */
943 	synchronize_rcu();
944 
945 	ip_vs_rht_for_each_bucket(t, bucket, head) {
946 same_bucket:
947 		if (++limit >= 16) {
948 			if (resched_score >= 100) {
949 				resched_score = 0;
950 				cond_resched();
951 			}
952 			limit = 0;
953 		}
954 		if (hlist_bl_empty(head)) {
955 			resched_score++;
956 			continue;
957 		}
958 		/* Preemption calls ahead... */
959 		resched_score = 0;
960 
961 		/* seqcount_t usage considering PREEMPT_RT rules:
962 		 * - other writers (SoftIRQ) => serialize with spin_lock_bh
963 		 * - readers (SoftIRQ) => disable BHs
964 		 * - readers (processes) => preemption should be disabled
965 		 */
966 		spin_lock_bh(&t->lock[bucket & t->lock_mask].l);
967 		preempt_disable_nested();
968 		write_seqcount_begin(&t->seqc[bucket & t->seqc_mask]);
969 		hlist_bl_lock(head);
970 
971 		hlist_bl_for_each_entry_safe(hn, cn, nn, head, node) {
972 			cp = ip_vs_hn_to_conn(hn);
973 			hash = ip_vs_conn_hashkey_conn(t_new, cp, hn->dir);
974 			hash_key = ip_vs_rht_build_hash_key(t_new, hash);
975 
976 			head2 = t_new->buckets + (hash & t_new->mask);
977 			hlist_bl_lock(head2);
978 			/* t_new->seqc are not used at this stage, we race
979 			 * only with add/del, so only lock the bucket.
980 			 */
981 			hlist_bl_del_rcu(&hn->node);
982 			WRITE_ONCE(hn->hash_key, hash_key);
983 			/* Keep both hash keys in sync if no double hashing */
984 			if (!ip_vs_conn_use_hash2(cp))
985 				WRITE_ONCE(cp->hn1.hash_key, hash_key);
986 			hlist_bl_add_head_rcu(&hn->node, head2);
987 			hlist_bl_unlock(head2);
988 			/* Too long chain? Do it in steps */
989 			if (++limit >= 64)
990 				break;
991 		}
992 
993 		hlist_bl_unlock(head);
994 		write_seqcount_end(&t->seqc[bucket & t->seqc_mask]);
995 		preempt_enable_nested();
996 		spin_unlock_bh(&t->lock[bucket & t->lock_mask].l);
997 		if (limit >= 64)
998 			goto same_bucket;
999 	}
1000 
1001 	rcu_assign_pointer(ipvs->conn_tab, t_new);
1002 	/* Inform readers that new table is installed */
1003 	smp_mb__before_atomic();
1004 	atomic_inc(&ipvs->conn_tab_changes);
1005 
1006 	/* RCU readers should not see more than two tables in chain.
1007 	 * To prevent new table to be attached wait here instead of
1008 	 * freeing the old table in RCU callback.
1009 	 */
1010 	synchronize_rcu();
1011 	ip_vs_rht_free(t);
1012 
1013 out:
1014 	/* Monitor if we need to shrink table */
1015 	queue_delayed_work(system_dfl_long_wq, &ipvs->conn_resize_work,
1016 			   more_work ? 1 : 2 * HZ);
1017 }
1018 
1019 /*
1020  *	Bind a connection entry with the corresponding packet_xmit.
1021  *	Called by ip_vs_conn_new.
1022  */
ip_vs_bind_xmit(struct ip_vs_conn * cp)1023 static inline void ip_vs_bind_xmit(struct ip_vs_conn *cp)
1024 {
1025 	switch (IP_VS_FWD_METHOD(cp)) {
1026 	case IP_VS_CONN_F_MASQ:
1027 		cp->packet_xmit = ip_vs_nat_xmit;
1028 		break;
1029 
1030 	case IP_VS_CONN_F_TUNNEL:
1031 #ifdef CONFIG_IP_VS_IPV6
1032 		if (cp->daf == AF_INET6)
1033 			cp->packet_xmit = ip_vs_tunnel_xmit_v6;
1034 		else
1035 #endif
1036 			cp->packet_xmit = ip_vs_tunnel_xmit;
1037 		break;
1038 
1039 	case IP_VS_CONN_F_DROUTE:
1040 		cp->packet_xmit = ip_vs_dr_xmit;
1041 		break;
1042 
1043 	case IP_VS_CONN_F_LOCALNODE:
1044 		cp->packet_xmit = ip_vs_null_xmit;
1045 		break;
1046 
1047 	case IP_VS_CONN_F_BYPASS:
1048 		cp->packet_xmit = ip_vs_bypass_xmit;
1049 		break;
1050 	}
1051 }
1052 
1053 #ifdef CONFIG_IP_VS_IPV6
ip_vs_bind_xmit_v6(struct ip_vs_conn * cp)1054 static inline void ip_vs_bind_xmit_v6(struct ip_vs_conn *cp)
1055 {
1056 	switch (IP_VS_FWD_METHOD(cp)) {
1057 	case IP_VS_CONN_F_MASQ:
1058 		cp->packet_xmit = ip_vs_nat_xmit_v6;
1059 		break;
1060 
1061 	case IP_VS_CONN_F_TUNNEL:
1062 		if (cp->daf == AF_INET6)
1063 			cp->packet_xmit = ip_vs_tunnel_xmit_v6;
1064 		else
1065 			cp->packet_xmit = ip_vs_tunnel_xmit;
1066 		break;
1067 
1068 	case IP_VS_CONN_F_DROUTE:
1069 		cp->packet_xmit = ip_vs_dr_xmit_v6;
1070 		break;
1071 
1072 	case IP_VS_CONN_F_LOCALNODE:
1073 		cp->packet_xmit = ip_vs_null_xmit;
1074 		break;
1075 
1076 	case IP_VS_CONN_F_BYPASS:
1077 		cp->packet_xmit = ip_vs_bypass_xmit_v6;
1078 		break;
1079 	}
1080 }
1081 #endif
1082 
1083 
1084 /*
1085  *	Bind a connection entry with a virtual service destination
1086  *	Called just after a new connection entry is created.
1087  */
1088 static inline void
ip_vs_bind_dest(struct ip_vs_conn * cp,struct ip_vs_dest * dest)1089 ip_vs_bind_dest(struct ip_vs_conn *cp, struct ip_vs_dest *dest)
1090 {
1091 	unsigned int conn_flags;
1092 	__u32 flags;
1093 
1094 	/* if dest is NULL, then return directly */
1095 	if (!dest)
1096 		return;
1097 
1098 	/* Increase the refcnt counter of the dest */
1099 	ip_vs_dest_hold(dest);
1100 
1101 	conn_flags = atomic_read(&dest->conn_flags);
1102 	if (cp->protocol != IPPROTO_UDP)
1103 		conn_flags &= ~IP_VS_CONN_F_ONE_PACKET;
1104 	flags = cp->flags;
1105 	/* Bind with the destination and its corresponding transmitter */
1106 	if (flags & IP_VS_CONN_F_SYNC) {
1107 		/* Synced conns are hashed, so they can not get this flag */
1108 		conn_flags &= ~IP_VS_CONN_F_ONE_PACKET;
1109 
1110 		/* if the connection is not template and is created
1111 		 * by sync, preserve the activity flag.
1112 		 */
1113 		if (!(flags & IP_VS_CONN_F_TEMPLATE))
1114 			conn_flags &= ~IP_VS_CONN_F_INACTIVE;
1115 		/* connections inherit forwarding method from dest */
1116 		flags &= ~(IP_VS_CONN_F_FWD_MASK | IP_VS_CONN_F_NOOUTPUT);
1117 		flags |= conn_flags;
1118 		/* Changing forwarding method for hashed conn can
1119 		 * happen only under locks
1120 		 */
1121 		if (cp->flags & IP_VS_CONN_F_HASHED)
1122 			ip_vs_conn_change_fwd_mask(cp, flags);
1123 		else
1124 			cp->flags = flags;
1125 	} else {
1126 		flags |= conn_flags;
1127 		cp->flags = flags;
1128 	}
1129 	cp->dest = dest;
1130 
1131 	IP_VS_DBG_BUF(7, "Bind-dest %s c:%s:%d v:%s:%d "
1132 		      "d:%s:%d fwd:%c s:%u conn->flags:%X conn->refcnt:%d "
1133 		      "dest->refcnt:%d\n",
1134 		      ip_vs_proto_name(cp->protocol),
1135 		      IP_VS_DBG_ADDR(cp->af, &cp->caddr), ntohs(cp->cport),
1136 		      IP_VS_DBG_ADDR(cp->af, &cp->vaddr), ntohs(cp->vport),
1137 		      IP_VS_DBG_ADDR(cp->daf, &cp->daddr), ntohs(cp->dport),
1138 		      ip_vs_fwd_tag(cp), cp->state,
1139 		      cp->flags, refcount_read(&cp->refcnt),
1140 		      refcount_read(&dest->refcnt));
1141 
1142 	/* Update the connection counters */
1143 	if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
1144 		int tc;
1145 
1146 		/* It is a normal connection, so modify the counters
1147 		 * according to the flags, later the protocol can
1148 		 * update them on state change
1149 		 */
1150 		if (!(flags & IP_VS_CONN_F_INACTIVE))
1151 			atomic_inc(&dest->activeconns);
1152 		tc = atomic_inc_return(&dest->totalconns);
1153 		if (tc == READ_ONCE(dest->u_threshold))
1154 			ip_vs_dest_update_overload(dest, 1);
1155 	} else {
1156 		/* It is a persistent connection/template, so increase
1157 		   the persistent connection counter */
1158 		atomic_inc(&dest->persistconns);
1159 	}
1160 }
1161 
1162 
1163 /*
1164  * Check if there is a destination for the connection, if so
1165  * bind the connection to the destination.
1166  */
ip_vs_try_bind_dest(struct ip_vs_conn * cp)1167 void ip_vs_try_bind_dest(struct ip_vs_conn *cp)
1168 {
1169 	struct ip_vs_dest *dest;
1170 
1171 	rcu_read_lock();
1172 
1173 	/* This function is only invoked by the synchronization code. We do
1174 	 * not currently support heterogeneous pools with synchronization,
1175 	 * so we can make the assumption that the svc_af is the same as the
1176 	 * dest_af
1177 	 */
1178 	dest = ip_vs_find_dest(cp->ipvs, cp->af, cp->af, &cp->daddr,
1179 			       cp->dport, &cp->vaddr, cp->vport,
1180 			       cp->protocol, cp->fwmark, cp->flags);
1181 	if (dest) {
1182 		struct ip_vs_proto_data *pd;
1183 
1184 		spin_lock_bh(&cp->lock);
1185 		if (cp->dest) {
1186 			spin_unlock_bh(&cp->lock);
1187 			rcu_read_unlock();
1188 			return;
1189 		}
1190 
1191 		/* Applications work depending on the forwarding method
1192 		 * but better to reassign them always when binding dest */
1193 		if (cp->app)
1194 			ip_vs_unbind_app(cp);
1195 
1196 		ip_vs_bind_dest(cp, dest);
1197 		spin_unlock_bh(&cp->lock);
1198 
1199 		/* Update its packet transmitter */
1200 		cp->packet_xmit = NULL;
1201 #ifdef CONFIG_IP_VS_IPV6
1202 		if (cp->af == AF_INET6)
1203 			ip_vs_bind_xmit_v6(cp);
1204 		else
1205 #endif
1206 			ip_vs_bind_xmit(cp);
1207 
1208 		pd = ip_vs_proto_data_get(cp->ipvs, cp->protocol);
1209 		if (pd && atomic_read(&pd->appcnt))
1210 			ip_vs_bind_app(cp, pd->pp);
1211 	}
1212 	rcu_read_unlock();
1213 }
1214 
1215 
1216 /*
1217  *	Unbind a connection entry with its VS destination
1218  *	Called by the ip_vs_conn_expire function.
1219  */
ip_vs_unbind_dest(struct ip_vs_conn * cp)1220 static inline void ip_vs_unbind_dest(struct ip_vs_conn *cp)
1221 {
1222 	struct ip_vs_dest *dest = cp->dest;
1223 
1224 	if (!dest)
1225 		return;
1226 
1227 	IP_VS_DBG_BUF(7, "Unbind-dest %s c:%s:%d v:%s:%d "
1228 		      "d:%s:%d fwd:%c s:%u conn->flags:%X conn->refcnt:%d "
1229 		      "dest->refcnt:%d\n",
1230 		      ip_vs_proto_name(cp->protocol),
1231 		      IP_VS_DBG_ADDR(cp->af, &cp->caddr), ntohs(cp->cport),
1232 		      IP_VS_DBG_ADDR(cp->af, &cp->vaddr), ntohs(cp->vport),
1233 		      IP_VS_DBG_ADDR(cp->daf, &cp->daddr), ntohs(cp->dport),
1234 		      ip_vs_fwd_tag(cp), cp->state,
1235 		      cp->flags, refcount_read(&cp->refcnt),
1236 		      refcount_read(&dest->refcnt));
1237 
1238 	/* Update the connection counters */
1239 	if (!(cp->flags & IP_VS_CONN_F_TEMPLATE)) {
1240 		int tc;
1241 
1242 		/* It is a normal connection, so decrease the counters */
1243 		if (!(cp->flags & IP_VS_CONN_F_INACTIVE))
1244 			atomic_dec(&dest->activeconns);
1245 		tc = atomic_fetch_dec(&dest->totalconns);
1246 		if (tc == READ_ONCE(dest->l_threshold_val))
1247 			ip_vs_dest_update_overload(dest, -1);
1248 	} else {
1249 		/* It is a persistent connection/template, so decrease
1250 		   the persistent connection counter */
1251 		atomic_dec(&dest->persistconns);
1252 	}
1253 
1254 	ip_vs_dest_put(dest);
1255 }
1256 
expire_quiescent_template(struct netns_ipvs * ipvs,struct ip_vs_dest * dest)1257 static int expire_quiescent_template(struct netns_ipvs *ipvs,
1258 				     struct ip_vs_dest *dest)
1259 {
1260 #ifdef CONFIG_SYSCTL
1261 	return ipvs->sysctl_expire_quiescent_template &&
1262 		(atomic_read(&dest->weight) == 0);
1263 #else
1264 	return 0;
1265 #endif
1266 }
1267 
1268 /*
1269  *	Checking if the destination of a connection template is available.
1270  *	If available, return 1, otherwise invalidate this connection
1271  *	template and return 0.
1272  */
ip_vs_check_template(struct ip_vs_conn * ct,struct ip_vs_dest * cdest)1273 int ip_vs_check_template(struct ip_vs_conn *ct, struct ip_vs_dest *cdest)
1274 {
1275 	struct ip_vs_dest *dest = ct->dest;
1276 	struct netns_ipvs *ipvs = ct->ipvs;
1277 
1278 	/*
1279 	 * Checking the dest server status.
1280 	 */
1281 	if ((dest == NULL) ||
1282 	    !(dest->cflags & IP_VS_DEST_CF_AVAILABLE) ||
1283 	    expire_quiescent_template(ipvs, dest) ||
1284 	    (cdest && (dest != cdest))) {
1285 		IP_VS_DBG_BUF(9, "check_template: dest not available for "
1286 			      "protocol %s s:%s:%d v:%s:%d "
1287 			      "-> d:%s:%d\n",
1288 			      ip_vs_proto_name(ct->protocol),
1289 			      IP_VS_DBG_ADDR(ct->af, &ct->caddr),
1290 			      ntohs(ct->cport),
1291 			      IP_VS_DBG_ADDR(ct->af, &ct->vaddr),
1292 			      ntohs(ct->vport),
1293 			      IP_VS_DBG_ADDR(ct->daf, &ct->daddr),
1294 			      ntohs(ct->dport));
1295 
1296 		/* Invalidate the connection template. Prefer to avoid
1297 		 * rehashing, it will move it as first in chain, so use
1298 		 * only dport as indication, it is not a hash key.
1299 		 */
1300 		ct->dport = htons(0xffff);
1301 
1302 		/*
1303 		 * Simply decrease the refcnt of the template,
1304 		 * don't restart its timer.
1305 		 */
1306 		__ip_vs_conn_put(ct);
1307 		return 0;
1308 	}
1309 	return 1;
1310 }
1311 
ip_vs_conn_rcu_free(struct rcu_head * head)1312 static void ip_vs_conn_rcu_free(struct rcu_head *head)
1313 {
1314 	struct ip_vs_conn *cp = container_of(head, struct ip_vs_conn,
1315 					     rcu_head);
1316 
1317 	ip_vs_pe_put(cp->pe);
1318 	kfree(cp->pe_data);
1319 	kmem_cache_free(ip_vs_conn_cachep, cp);
1320 }
1321 
1322 /* Try to delete connection while not holding reference */
ip_vs_conn_del(struct ip_vs_conn * cp)1323 static void ip_vs_conn_del(struct ip_vs_conn *cp)
1324 {
1325 	if (timer_delete(&cp->timer)) {
1326 		/* Drop cp->control chain too */
1327 		if (cp->control)
1328 			cp->timeout = 0;
1329 		ip_vs_conn_expire(&cp->timer);
1330 	}
1331 }
1332 
1333 /* Try to delete connection while holding reference */
ip_vs_conn_del_put(struct ip_vs_conn * cp)1334 static void ip_vs_conn_del_put(struct ip_vs_conn *cp)
1335 {
1336 	if (timer_delete(&cp->timer)) {
1337 		/* Drop cp->control chain too */
1338 		if (cp->control)
1339 			cp->timeout = 0;
1340 		__ip_vs_conn_put(cp);
1341 		ip_vs_conn_expire(&cp->timer);
1342 	} else {
1343 		__ip_vs_conn_put(cp);
1344 	}
1345 }
1346 
ip_vs_conn_expire(struct timer_list * t)1347 static void ip_vs_conn_expire(struct timer_list *t)
1348 {
1349 	struct ip_vs_conn *cp = timer_container_of(cp, t, timer);
1350 	struct netns_ipvs *ipvs = cp->ipvs;
1351 
1352 	/*
1353 	 *	do I control anybody?
1354 	 */
1355 	if (atomic_read(&cp->n_control))
1356 		goto expire_later;
1357 
1358 	/* Unlink conn if not referenced anymore */
1359 	if (likely(ip_vs_conn_unlink(cp))) {
1360 		struct ip_vs_conn *ct = cp->control;
1361 
1362 		/* delete the timer if it is activated by other users */
1363 		timer_delete(&cp->timer);
1364 
1365 		/* does anybody control me? */
1366 		if (ct) {
1367 			bool has_ref = !cp->timeout && __ip_vs_conn_get(ct);
1368 
1369 			ip_vs_control_del(cp);
1370 			/* Drop CTL or non-assured TPL if not used anymore */
1371 			if (has_ref && !atomic_read(&ct->n_control) &&
1372 			    (!(ct->flags & IP_VS_CONN_F_TEMPLATE) ||
1373 			     !(ct->state & IP_VS_CTPL_S_ASSURED))) {
1374 				IP_VS_DBG(4, "drop controlling connection\n");
1375 				ip_vs_conn_del_put(ct);
1376 			} else if (has_ref) {
1377 				__ip_vs_conn_put(ct);
1378 			}
1379 		}
1380 
1381 		if ((cp->flags & IP_VS_CONN_F_NFCT) &&
1382 		    !(cp->flags & IP_VS_CONN_F_ONE_PACKET)) {
1383 			/* Do not access conntracks during subsys cleanup
1384 			 * because nf_conntrack_find_get can not be used after
1385 			 * conntrack cleanup for the net.
1386 			 */
1387 			smp_rmb();
1388 			if (READ_ONCE(ipvs->enable))
1389 				ip_vs_conn_drop_conntrack(cp);
1390 		}
1391 
1392 		if (unlikely(cp->app != NULL))
1393 			ip_vs_unbind_app(cp);
1394 		ip_vs_unbind_dest(cp);
1395 		if (unlikely(cp->flags & IP_VS_CONN_F_NO_CPORT)) {
1396 			int af_id = ip_vs_af_index(cp->af);
1397 
1398 			atomic_dec(&ipvs->no_cport_conns[af_id]);
1399 		}
1400 		if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
1401 			ip_vs_conn_rcu_free(&cp->rcu_head);
1402 		else
1403 			call_rcu(&cp->rcu_head, ip_vs_conn_rcu_free);
1404 		atomic_dec(&ipvs->conn_count);
1405 		return;
1406 	}
1407 
1408   expire_later:
1409 	IP_VS_DBG(7, "delayed: conn->refcnt=%d conn->n_control=%d\n",
1410 		  refcount_read(&cp->refcnt),
1411 		  atomic_read(&cp->n_control));
1412 
1413 	refcount_inc(&cp->refcnt);
1414 	cp->timeout = 60*HZ;
1415 
1416 	if (ipvs->sync_state & IP_VS_STATE_MASTER)
1417 		ip_vs_sync_conn(ipvs, cp, sysctl_sync_threshold(ipvs));
1418 
1419 	__ip_vs_conn_put_timer(cp);
1420 }
1421 
1422 /* Modify timer, so that it expires as soon as possible.
1423  * Can be called without reference only if under RCU lock.
1424  * We can have such chain of conns linked with ->control: DATA->CTL->TPL
1425  * - DATA (eg. FTP) and TPL (persistence) can be present depending on setup
1426  * - cp->timeout=0 indicates all conns from chain should be dropped but
1427  * TPL is not dropped if in assured state
1428  */
ip_vs_conn_expire_now(struct ip_vs_conn * cp)1429 void ip_vs_conn_expire_now(struct ip_vs_conn *cp)
1430 {
1431 	/* Using mod_timer_pending will ensure the timer is not
1432 	 * modified after the final timer_delete in ip_vs_conn_expire.
1433 	 */
1434 	if (timer_pending(&cp->timer) &&
1435 	    time_after(cp->timer.expires, jiffies))
1436 		mod_timer_pending(&cp->timer, jiffies);
1437 }
1438 
1439 
1440 /*
1441  *	Create a new connection entry and hash it into the conn_tab
1442  */
1443 struct ip_vs_conn *
ip_vs_conn_new(const struct ip_vs_conn_param * p,int dest_af,const union nf_inet_addr * daddr,__be16 dport,unsigned int flags,struct ip_vs_dest * dest,__u32 fwmark)1444 ip_vs_conn_new(const struct ip_vs_conn_param *p, int dest_af,
1445 	       const union nf_inet_addr *daddr, __be16 dport, unsigned int flags,
1446 	       struct ip_vs_dest *dest, __u32 fwmark)
1447 {
1448 	struct ip_vs_conn *cp;
1449 	struct netns_ipvs *ipvs = p->ipvs;
1450 	struct ip_vs_proto_data *pd = ip_vs_proto_data_get(p->ipvs,
1451 							   p->protocol);
1452 	/* Increment conn_count up to conn_max */
1453 	int count = atomic_read(&ipvs->conn_count);
1454 	int max = sysctl_conn_max(ipvs);
1455 
1456 	do {
1457 		if (count >= max)
1458 			return NULL;
1459 	} while (!atomic_try_cmpxchg(&ipvs->conn_count, &count, count + 1));
1460 
1461 	cp = kmem_cache_alloc(ip_vs_conn_cachep, GFP_ATOMIC);
1462 	if (cp == NULL) {
1463 		atomic_dec(&ipvs->conn_count);
1464 		IP_VS_ERR_RL("%s(): no memory\n", __func__);
1465 		return NULL;
1466 	}
1467 
1468 	INIT_HLIST_BL_NODE(&cp->hn0.node);
1469 	INIT_HLIST_BL_NODE(&cp->hn1.node);
1470 	timer_setup(&cp->timer, ip_vs_conn_expire, 0);
1471 	cp->ipvs	   = ipvs;
1472 	cp->hn0.dir	   = 0;
1473 	cp->af		   = p->af;
1474 	cp->hn1.dir	   = 1;
1475 	cp->daf		   = dest_af;
1476 	cp->protocol	   = p->protocol;
1477 	ip_vs_addr_set(p->af, &cp->caddr, p->caddr);
1478 	cp->cport	   = p->cport;
1479 	/* proto should only be IPPROTO_IP if p->vaddr is a fwmark */
1480 	ip_vs_addr_set(p->protocol == IPPROTO_IP ? AF_UNSPEC : p->af,
1481 		       &cp->vaddr, p->vaddr);
1482 	cp->vport	   = p->vport;
1483 	ip_vs_addr_set(cp->daf, &cp->daddr, daddr);
1484 	cp->dport          = dport;
1485 	cp->flags	   = flags;
1486 	cp->fwmark         = fwmark;
1487 	if (flags & IP_VS_CONN_F_TEMPLATE && p->pe) {
1488 		ip_vs_pe_get(p->pe);
1489 		cp->pe = p->pe;
1490 		cp->pe_data = p->pe_data;
1491 		cp->pe_data_len = p->pe_data_len;
1492 	} else {
1493 		cp->pe = NULL;
1494 		cp->pe_data = NULL;
1495 		cp->pe_data_len = 0;
1496 	}
1497 	spin_lock_init(&cp->lock);
1498 
1499 	/*
1500 	 * Set the entry is referenced by the current thread before hashing
1501 	 * it in the table, so that other thread run ip_vs_random_dropentry
1502 	 * but cannot drop this entry.
1503 	 */
1504 	refcount_set(&cp->refcnt, 1);
1505 
1506 	cp->control = NULL;
1507 	atomic_set(&cp->n_control, 0);
1508 	atomic_set(&cp->in_pkts, 0);
1509 
1510 	cp->packet_xmit = NULL;
1511 	cp->app = NULL;
1512 	cp->app_data = NULL;
1513 	/* reset struct ip_vs_seq */
1514 	memset(&cp->in_seq, 0, sizeof(cp->in_seq));
1515 	memset(&cp->out_seq, 0, sizeof(cp->out_seq));
1516 
1517 	if (unlikely(flags & IP_VS_CONN_F_NO_CPORT)) {
1518 		int af_id = ip_vs_af_index(cp->af);
1519 
1520 		atomic_inc(&ipvs->no_cport_conns[af_id]);
1521 	}
1522 
1523 	/* Bind the connection with a destination server */
1524 	cp->dest = NULL;
1525 	ip_vs_bind_dest(cp, dest);
1526 
1527 	/* Set its state and timeout */
1528 	cp->state = 0;
1529 	cp->old_state = 0;
1530 	cp->timeout = 3*HZ;
1531 	cp->sync_endtime = jiffies & ~3UL;
1532 
1533 	/* Bind its packet transmitter */
1534 #ifdef CONFIG_IP_VS_IPV6
1535 	if (p->af == AF_INET6)
1536 		ip_vs_bind_xmit_v6(cp);
1537 	else
1538 #endif
1539 		ip_vs_bind_xmit(cp);
1540 
1541 	if (unlikely(pd && atomic_read(&pd->appcnt)))
1542 		ip_vs_bind_app(cp, pd->pp);
1543 
1544 	/*
1545 	 * Allow conntrack to be preserved. By default, conntrack
1546 	 * is created and destroyed for every packet.
1547 	 * Sometimes keeping conntrack can be useful for
1548 	 * IP_VS_CONN_F_ONE_PACKET too.
1549 	 */
1550 
1551 	if (ip_vs_conntrack_enabled(ipvs))
1552 		cp->flags |= IP_VS_CONN_F_NFCT;
1553 
1554 	/* Hash it in the conn_tab finally */
1555 	ip_vs_conn_hash(cp);
1556 
1557 	return cp;
1558 }
1559 
1560 /*
1561  *	/proc/net/ip_vs_conn entries
1562  */
1563 #ifdef CONFIG_PROC_FS
1564 struct ip_vs_iter_state {
1565 	struct seq_net_private	p;
1566 	struct ip_vs_rht	*t;
1567 	int			gen;
1568 	u32			bucket;
1569 	unsigned int		skip_elems;
1570 };
1571 
ip_vs_conn_array(struct seq_file * seq)1572 static void *ip_vs_conn_array(struct seq_file *seq)
1573 {
1574 	struct ip_vs_iter_state *iter = seq->private;
1575 	struct net *net = seq_file_net(seq);
1576 	struct netns_ipvs *ipvs = net_ipvs(net);
1577 	struct ip_vs_rht *t = iter->t;
1578 	struct ip_vs_conn_hnode *hn;
1579 	struct hlist_bl_node *e;
1580 	int idx;
1581 
1582 	if (!t)
1583 		return NULL;
1584 	for (idx = iter->bucket; idx < t->size; idx++) {
1585 		unsigned int skip = 0;
1586 
1587 		hlist_bl_for_each_entry_rcu(hn, e, &t->buckets[idx], node) {
1588 			/* __ip_vs_conn_get() is not needed by
1589 			 * ip_vs_conn_seq_show and ip_vs_conn_sync_seq_show
1590 			 */
1591 			if (!ip_vs_rht_same_table(t, READ_ONCE(hn->hash_key)))
1592 				break;
1593 			if (hn->dir != 0)
1594 				continue;
1595 			if (skip >= iter->skip_elems) {
1596 				iter->bucket = idx;
1597 				return hn;
1598 			}
1599 
1600 			++skip;
1601 		}
1602 
1603 		if (!(idx & 31)) {
1604 			cond_resched_rcu();
1605 			/* New table installed ? */
1606 			if (iter->gen != atomic_read(&ipvs->conn_tab_changes))
1607 				break;
1608 		}
1609 		iter->skip_elems = 0;
1610 	}
1611 
1612 	iter->bucket = idx;
1613 	return NULL;
1614 }
1615 
ip_vs_conn_seq_start(struct seq_file * seq,loff_t * pos)1616 static void *ip_vs_conn_seq_start(struct seq_file *seq, loff_t *pos)
1617 	__acquires(RCU)
1618 {
1619 	struct ip_vs_iter_state *iter = seq->private;
1620 	struct net *net = seq_file_net(seq);
1621 	struct netns_ipvs *ipvs = net_ipvs(net);
1622 
1623 	rcu_read_lock();
1624 	iter->gen = atomic_read(&ipvs->conn_tab_changes);
1625 	smp_rmb(); /* ipvs->conn_tab and conn_tab_changes */
1626 	iter->t = rcu_dereference(ipvs->conn_tab);
1627 	if (*pos == 0) {
1628 		iter->skip_elems = 0;
1629 		iter->bucket = 0;
1630 		return SEQ_START_TOKEN;
1631 	}
1632 
1633 	return ip_vs_conn_array(seq);
1634 }
1635 
ip_vs_conn_seq_next(struct seq_file * seq,void * v,loff_t * pos)1636 static void *ip_vs_conn_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1637 {
1638 	struct ip_vs_iter_state *iter = seq->private;
1639 	struct ip_vs_conn_hnode *hn = v;
1640 	struct hlist_bl_node *e;
1641 	struct ip_vs_rht *t;
1642 
1643 	++*pos;
1644 	if (v == SEQ_START_TOKEN)
1645 		return ip_vs_conn_array(seq);
1646 
1647 	t = iter->t;
1648 	if (!t)
1649 		return NULL;
1650 
1651 	/* more on same hash chain? */
1652 	hlist_bl_for_each_entry_continue_rcu(hn, e, node) {
1653 		/* Our cursor was moved to new table ? */
1654 		if (!ip_vs_rht_same_table(t, READ_ONCE(hn->hash_key)))
1655 			break;
1656 		if (hn->dir != 0)
1657 			continue;
1658 		iter->skip_elems++;
1659 		return hn;
1660 	}
1661 
1662 	iter->skip_elems = 0;
1663 	iter->bucket++;
1664 
1665 	return ip_vs_conn_array(seq);
1666 }
1667 
ip_vs_conn_seq_stop(struct seq_file * seq,void * v)1668 static void ip_vs_conn_seq_stop(struct seq_file *seq, void *v)
1669 	__releases(RCU)
1670 {
1671 	rcu_read_unlock();
1672 }
1673 
ip_vs_conn_seq_show(struct seq_file * seq,void * v)1674 static int ip_vs_conn_seq_show(struct seq_file *seq, void *v)
1675 {
1676 
1677 	if (v == SEQ_START_TOKEN)
1678 		seq_puts(seq,
1679    "Pro FromIP   FPrt ToIP     TPrt DestIP   DPrt State       Expires PEName PEData\n");
1680 	else {
1681 		struct ip_vs_conn_hnode *hn = v;
1682 		const struct ip_vs_conn *cp = ip_vs_hn0_to_conn(hn);
1683 		char pe_data[IP_VS_PENAME_MAXLEN + IP_VS_PEDATA_MAXLEN + 3];
1684 		size_t len = 0;
1685 		char dbuf[IP_VS_ADDRSTRLEN];
1686 
1687 		if (cp->pe_data) {
1688 			pe_data[0] = ' ';
1689 			len = strlen(cp->pe->name);
1690 			memcpy(pe_data + 1, cp->pe->name, len);
1691 			pe_data[len + 1] = ' ';
1692 			len += 2;
1693 			len += cp->pe->show_pe_data(cp, pe_data + len);
1694 		}
1695 		pe_data[len] = '\0';
1696 
1697 #ifdef CONFIG_IP_VS_IPV6
1698 		if (cp->daf == AF_INET6)
1699 			snprintf(dbuf, sizeof(dbuf), "%pI6", &cp->daddr.in6);
1700 		else
1701 #endif
1702 			snprintf(dbuf, sizeof(dbuf), "%08X",
1703 				 ntohl(cp->daddr.ip));
1704 
1705 #ifdef CONFIG_IP_VS_IPV6
1706 		if (cp->af == AF_INET6)
1707 			seq_printf(seq, "%-3s %pI6 %04X %pI6 %04X "
1708 				"%s %04X %-11s %7u%s\n",
1709 				ip_vs_proto_name(cp->protocol),
1710 				&cp->caddr.in6, ntohs(cp->cport),
1711 				&cp->vaddr.in6, ntohs(cp->vport),
1712 				dbuf, ntohs(cp->dport),
1713 				ip_vs_state_name(cp),
1714 				jiffies_delta_to_msecs(cp->timer.expires -
1715 						       jiffies) / 1000,
1716 				pe_data);
1717 		else
1718 #endif
1719 			seq_printf(seq,
1720 				"%-3s %08X %04X %08X %04X"
1721 				" %s %04X %-11s %7u%s\n",
1722 				ip_vs_proto_name(cp->protocol),
1723 				ntohl(cp->caddr.ip), ntohs(cp->cport),
1724 				ntohl(cp->vaddr.ip), ntohs(cp->vport),
1725 				dbuf, ntohs(cp->dport),
1726 				ip_vs_state_name(cp),
1727 				jiffies_delta_to_msecs(cp->timer.expires -
1728 						       jiffies) / 1000,
1729 				pe_data);
1730 	}
1731 	return 0;
1732 }
1733 
1734 static const struct seq_operations ip_vs_conn_seq_ops = {
1735 	.start = ip_vs_conn_seq_start,
1736 	.next  = ip_vs_conn_seq_next,
1737 	.stop  = ip_vs_conn_seq_stop,
1738 	.show  = ip_vs_conn_seq_show,
1739 };
1740 
ip_vs_origin_name(unsigned int flags)1741 static const char *ip_vs_origin_name(unsigned int flags)
1742 {
1743 	if (flags & IP_VS_CONN_F_SYNC)
1744 		return "SYNC";
1745 	else
1746 		return "LOCAL";
1747 }
1748 
ip_vs_conn_sync_seq_show(struct seq_file * seq,void * v)1749 static int ip_vs_conn_sync_seq_show(struct seq_file *seq, void *v)
1750 {
1751 	char dbuf[IP_VS_ADDRSTRLEN];
1752 
1753 	if (v == SEQ_START_TOKEN)
1754 		seq_puts(seq,
1755    "Pro FromIP   FPrt ToIP     TPrt DestIP   DPrt State       Origin Expires\n");
1756 	else {
1757 		const struct ip_vs_conn *cp = v;
1758 
1759 #ifdef CONFIG_IP_VS_IPV6
1760 		if (cp->daf == AF_INET6)
1761 			snprintf(dbuf, sizeof(dbuf), "%pI6", &cp->daddr.in6);
1762 		else
1763 #endif
1764 			snprintf(dbuf, sizeof(dbuf), "%08X",
1765 				 ntohl(cp->daddr.ip));
1766 
1767 #ifdef CONFIG_IP_VS_IPV6
1768 		if (cp->af == AF_INET6)
1769 			seq_printf(seq, "%-3s %pI6 %04X %pI6 %04X "
1770 				"%s %04X %-11s %-6s %7u\n",
1771 				ip_vs_proto_name(cp->protocol),
1772 				&cp->caddr.in6, ntohs(cp->cport),
1773 				&cp->vaddr.in6, ntohs(cp->vport),
1774 				dbuf, ntohs(cp->dport),
1775 				ip_vs_state_name(cp),
1776 				ip_vs_origin_name(cp->flags),
1777 				jiffies_delta_to_msecs(cp->timer.expires -
1778 						       jiffies) / 1000);
1779 		else
1780 #endif
1781 			seq_printf(seq,
1782 				"%-3s %08X %04X %08X %04X "
1783 				"%s %04X %-11s %-6s %7u\n",
1784 				ip_vs_proto_name(cp->protocol),
1785 				ntohl(cp->caddr.ip), ntohs(cp->cport),
1786 				ntohl(cp->vaddr.ip), ntohs(cp->vport),
1787 				dbuf, ntohs(cp->dport),
1788 				ip_vs_state_name(cp),
1789 				ip_vs_origin_name(cp->flags),
1790 				jiffies_delta_to_msecs(cp->timer.expires -
1791 						       jiffies) / 1000);
1792 	}
1793 	return 0;
1794 }
1795 
1796 static const struct seq_operations ip_vs_conn_sync_seq_ops = {
1797 	.start = ip_vs_conn_seq_start,
1798 	.next  = ip_vs_conn_seq_next,
1799 	.stop  = ip_vs_conn_seq_stop,
1800 	.show  = ip_vs_conn_sync_seq_show,
1801 };
1802 #endif
1803 
1804 #ifdef CONFIG_SYSCTL
1805 
1806 /* Randomly drop connection entries before running out of memory
1807  * Can be used for DATA and CTL conns. For TPL conns there are exceptions:
1808  * - traffic for services in OPS mode increases ct->in_pkts, so it is supported
1809  * - traffic for services not in OPS mode does not increase ct->in_pkts in
1810  * all cases, so it is not supported
1811  */
todrop_entry(struct ip_vs_conn * cp)1812 static inline int todrop_entry(struct ip_vs_conn *cp)
1813 {
1814 	struct netns_ipvs *ipvs = cp->ipvs;
1815 	int i;
1816 
1817 	/* if the conn entry hasn't lasted for 60 seconds, don't drop it.
1818 	   This will leave enough time for normal connection to get
1819 	   through. */
1820 	if (time_before(cp->timeout + jiffies, cp->timer.expires + 60*HZ))
1821 		return 0;
1822 
1823 	/* Drop only conns with number of incoming packets in [1..8] range */
1824 	i = atomic_read(&cp->in_pkts);
1825 	if (i > 8 || i < 1)
1826 		return 0;
1827 
1828 	i--;
1829 	if (--ipvs->dropentry_counters[i] > 0)
1830 		return 0;
1831 
1832 	/* Prefer to drop conns with less number of incoming packets */
1833 	ipvs->dropentry_counters[i] = i + 1;
1834 	return 1;
1835 }
1836 
ip_vs_conn_ops_mode(struct ip_vs_conn * cp)1837 static inline bool ip_vs_conn_ops_mode(struct ip_vs_conn *cp)
1838 {
1839 	struct ip_vs_service *svc;
1840 
1841 	if (!cp->dest)
1842 		return false;
1843 	svc = rcu_dereference(cp->dest->svc);
1844 	return svc && (svc->flags & IP_VS_SVC_F_ONEPACKET);
1845 }
1846 
ip_vs_random_dropentry(struct netns_ipvs * ipvs)1847 void ip_vs_random_dropentry(struct netns_ipvs *ipvs)
1848 {
1849 	struct ip_vs_conn_hnode *hn;
1850 	struct hlist_bl_node *e;
1851 	struct ip_vs_conn *cp;
1852 	struct ip_vs_rht *t;
1853 	unsigned int r;
1854 	int idx;
1855 
1856 	r = get_random_u32();
1857 	rcu_read_lock();
1858 	t = rcu_dereference(ipvs->conn_tab);
1859 	if (!t)
1860 		goto out;
1861 	/*
1862 	 * Randomly scan 1/32 of the whole table every second
1863 	 */
1864 	for (idx = 0; idx < (t->size >> 5); idx++) {
1865 		unsigned int hash = (r + idx) & t->mask;
1866 
1867 		/* Don't care if due to moved entry we jump to another bucket
1868 		 * and even to new table
1869 		 */
1870 		hlist_bl_for_each_entry_rcu(hn, e, &t->buckets[hash], node) {
1871 			if (hn->dir != 0)
1872 				continue;
1873 			cp = ip_vs_hn0_to_conn(hn);
1874 			if (atomic_read(&cp->n_control))
1875 				continue;
1876 			if (cp->flags & IP_VS_CONN_F_TEMPLATE) {
1877 				/* connection template of OPS */
1878 				if (ip_vs_conn_ops_mode(cp))
1879 					goto try_drop;
1880 				if (!(cp->state & IP_VS_CTPL_S_ASSURED))
1881 					goto drop;
1882 				continue;
1883 			}
1884 			if (cp->protocol == IPPROTO_TCP) {
1885 				switch(cp->state) {
1886 				case IP_VS_TCP_S_SYN_RECV:
1887 				case IP_VS_TCP_S_SYNACK:
1888 					break;
1889 
1890 				case IP_VS_TCP_S_ESTABLISHED:
1891 					if (todrop_entry(cp))
1892 						break;
1893 					continue;
1894 
1895 				default:
1896 					continue;
1897 				}
1898 			} else if (cp->protocol == IPPROTO_SCTP) {
1899 				switch (cp->state) {
1900 				case IP_VS_SCTP_S_INIT1:
1901 				case IP_VS_SCTP_S_INIT:
1902 					break;
1903 				case IP_VS_SCTP_S_ESTABLISHED:
1904 					if (todrop_entry(cp))
1905 						break;
1906 					continue;
1907 				default:
1908 					continue;
1909 				}
1910 			} else {
1911 try_drop:
1912 				if (!todrop_entry(cp))
1913 					continue;
1914 			}
1915 
1916 drop:
1917 			IP_VS_DBG(4, "drop connection\n");
1918 			ip_vs_conn_del(cp);
1919 		}
1920 		if (!(idx & 31)) {
1921 			cond_resched_rcu();
1922 			t = rcu_dereference(ipvs->conn_tab);
1923 			if (!t)
1924 				goto out;
1925 		}
1926 	}
1927 
1928 out:
1929 	rcu_read_unlock();
1930 }
1931 #endif
1932 
1933 /* Flush all the connection entries in the conn_tab */
ip_vs_conn_flush(struct netns_ipvs * ipvs)1934 static void ip_vs_conn_flush(struct netns_ipvs *ipvs)
1935 {
1936 	DECLARE_IP_VS_RHT_WALK_BUCKETS_SAFE_RCU();
1937 	struct ip_vs_conn *cp, *cp_c;
1938 	struct ip_vs_conn_hnode *hn;
1939 	struct hlist_bl_head *head;
1940 	struct ip_vs_rht *t, *p;
1941 	struct hlist_bl_node *e;
1942 
1943 	if (!rcu_dereference_protected(ipvs->conn_tab, 1))
1944 		return;
1945 	disable_delayed_work_sync(&ipvs->conn_resize_work);
1946 	if (!atomic_read(&ipvs->conn_count))
1947 		goto unreg;
1948 
1949 flush_again:
1950 	/* Rely on RCU grace period while accessing cp after ip_vs_conn_del */
1951 	rcu_read_lock();
1952 	ip_vs_rht_walk_buckets_safe_rcu(ipvs->conn_tab, head) {
1953 		hlist_bl_for_each_entry_rcu(hn, e, head, node) {
1954 			if (hn->dir != 0)
1955 				continue;
1956 			cp = ip_vs_hn0_to_conn(hn);
1957 			if (atomic_read(&cp->n_control))
1958 				continue;
1959 			cp_c = cp->control;
1960 			IP_VS_DBG(4, "del connection\n");
1961 			ip_vs_conn_del(cp);
1962 			if (cp_c && !atomic_read(&cp_c->n_control)) {
1963 				IP_VS_DBG(4, "del controlling connection\n");
1964 				ip_vs_conn_del(cp_c);
1965 			}
1966 		}
1967 		cond_resched_rcu();
1968 	}
1969 	rcu_read_unlock();
1970 
1971 	/* the counter may be not NULL, because maybe some conn entries
1972 	   are run by slow timer handler or unhashed but still referred */
1973 	if (atomic_read(&ipvs->conn_count) != 0) {
1974 		schedule();
1975 		goto flush_again;
1976 	}
1977 
1978 unreg:
1979 	/* Unregister the hash table and release it after RCU grace period.
1980 	 * This is needed because other works may not be stopped yet and
1981 	 * they may walk the tables.
1982 	 */
1983 	t = rcu_dereference_protected(ipvs->conn_tab, 1);
1984 	rcu_assign_pointer(ipvs->conn_tab, NULL);
1985 	/* Inform readers that conn_tab is changed */
1986 	smp_mb__before_atomic();
1987 	atomic_inc(&ipvs->conn_tab_changes);
1988 	while (1) {
1989 		p = rcu_dereference_protected(t->new_tbl, 1);
1990 		call_rcu(&t->rcu_head, ip_vs_rht_rcu_free);
1991 		if (p == t)
1992 			break;
1993 		t = p;
1994 	}
1995 }
1996 
1997 #ifdef CONFIG_SYSCTL
ip_vs_expire_nodest_conn_flush(struct netns_ipvs * ipvs)1998 void ip_vs_expire_nodest_conn_flush(struct netns_ipvs *ipvs)
1999 {
2000 	DECLARE_IP_VS_RHT_WALK_BUCKETS_RCU();
2001 	unsigned int resched_score = 0;
2002 	struct ip_vs_conn *cp, *cp_c;
2003 	struct ip_vs_conn_hnode *hn;
2004 	struct hlist_bl_head *head;
2005 	struct ip_vs_dest *dest;
2006 	struct hlist_bl_node *e;
2007 	int old_gen, new_gen;
2008 
2009 	if (!atomic_read(&ipvs->conn_count))
2010 		return;
2011 	old_gen = atomic_read(&ipvs->conn_tab_changes);
2012 	rcu_read_lock();
2013 
2014 repeat:
2015 	smp_rmb(); /* ipvs->conn_tab and conn_tab_changes */
2016 	ip_vs_rht_walk_buckets_rcu(ipvs->conn_tab, head) {
2017 		hlist_bl_for_each_entry_rcu(hn, e, head, node) {
2018 			if (hn->dir != 0)
2019 				continue;
2020 			cp = ip_vs_hn0_to_conn(hn);
2021 			resched_score++;
2022 			dest = cp->dest;
2023 			if (!dest || (dest->cflags & IP_VS_DEST_CF_AVAILABLE))
2024 				continue;
2025 
2026 			if (atomic_read(&cp->n_control))
2027 				continue;
2028 
2029 			cp_c = cp->control;
2030 			IP_VS_DBG(4, "del connection\n");
2031 			ip_vs_conn_del(cp);
2032 			if (cp_c && !atomic_read(&cp_c->n_control)) {
2033 				IP_VS_DBG(4, "del controlling connection\n");
2034 				ip_vs_conn_del(cp_c);
2035 			}
2036 			resched_score += 10;
2037 		}
2038 		resched_score++;
2039 		if (resched_score >= 100) {
2040 			resched_score = 0;
2041 			cond_resched_rcu();
2042 			/* netns clean up started, abort delayed work */
2043 			if (!READ_ONCE(ipvs->enable))
2044 				goto out;
2045 			new_gen = atomic_read(&ipvs->conn_tab_changes);
2046 			/* New table installed ? */
2047 			if (old_gen != new_gen) {
2048 				old_gen = new_gen;
2049 				goto repeat;
2050 			}
2051 		}
2052 	}
2053 
2054 out:
2055 	rcu_read_unlock();
2056 }
2057 #endif
2058 
2059 /*
2060  * per netns init and exit
2061  */
ip_vs_conn_net_init(struct netns_ipvs * ipvs)2062 int __net_init ip_vs_conn_net_init(struct netns_ipvs *ipvs)
2063 {
2064 	int idx;
2065 
2066 	atomic_set(&ipvs->conn_count, 0);
2067 	for (idx = 0; idx < IP_VS_AF_MAX; idx++)
2068 		atomic_set(&ipvs->no_cport_conns[idx], 0);
2069 	INIT_DELAYED_WORK(&ipvs->conn_resize_work, conn_resize_work_handler);
2070 	RCU_INIT_POINTER(ipvs->conn_tab, NULL);
2071 	atomic_set(&ipvs->conn_tab_changes, 0);
2072 	ipvs->sysctl_conn_lfactor = ip_vs_conn_default_load_factor(ipvs);
2073 
2074 #ifdef CONFIG_PROC_FS
2075 	if (!proc_create_net("ip_vs_conn", 0, ipvs->net->proc_net,
2076 			     &ip_vs_conn_seq_ops,
2077 			     sizeof(struct ip_vs_iter_state)))
2078 		goto err_conn;
2079 
2080 	if (!proc_create_net("ip_vs_conn_sync", 0, ipvs->net->proc_net,
2081 			     &ip_vs_conn_sync_seq_ops,
2082 			     sizeof(struct ip_vs_iter_state)))
2083 		goto err_conn_sync;
2084 #endif
2085 
2086 	return 0;
2087 
2088 #ifdef CONFIG_PROC_FS
2089 err_conn_sync:
2090 	remove_proc_entry("ip_vs_conn", ipvs->net->proc_net);
2091 err_conn:
2092 	return -ENOMEM;
2093 #endif
2094 }
2095 
ip_vs_conn_net_cleanup(struct netns_ipvs * ipvs)2096 void __net_exit ip_vs_conn_net_cleanup(struct netns_ipvs *ipvs)
2097 {
2098 	/* flush all the connection entries first */
2099 	ip_vs_conn_flush(ipvs);
2100 #ifdef CONFIG_PROC_FS
2101 	remove_proc_entry("ip_vs_conn", ipvs->net->proc_net);
2102 	remove_proc_entry("ip_vs_conn_sync", ipvs->net->proc_net);
2103 #endif
2104 }
2105 
ip_vs_conn_init(void)2106 int __init ip_vs_conn_init(void)
2107 {
2108 	int min = IP_VS_CONN_TAB_MIN_BITS;
2109 	int max = IP_VS_CONN_TAB_MAX_BITS;
2110 	size_t tab_array_size;
2111 	int max_avail;
2112 
2113 	max_avail = order_base_2(totalram_pages()) + PAGE_SHIFT;
2114 	/* 64-bit: 27 bits at 64GB, 32-bit: 20 bits at 512MB */
2115 	max_avail += 1;		/* hash table loaded at 50% */
2116 	max_avail -= 1;		/* IPVS up to 1/2 of mem */
2117 	max_avail -= order_base_2(sizeof(struct ip_vs_conn));
2118 	max = clamp(max_avail, min, max);
2119 	ip_vs_conn_tab_bits = clamp(ip_vs_conn_tab_bits, min, max);
2120 	ip_vs_conn_tab_size = 1 << ip_vs_conn_tab_bits;
2121 
2122 	/*
2123 	 * Allocate the connection hash table and initialize its list heads
2124 	 */
2125 	tab_array_size = array_size(ip_vs_conn_tab_size,
2126 				    sizeof(struct hlist_bl_head));
2127 
2128 	/* Allocate ip_vs_conn slab cache */
2129 	ip_vs_conn_cachep = KMEM_CACHE(ip_vs_conn, SLAB_HWCACHE_ALIGN);
2130 	if (!ip_vs_conn_cachep)
2131 		return -ENOMEM;
2132 
2133 	pr_info("Connection hash table configured (size=%d, memory=%zdKbytes)\n",
2134 		ip_vs_conn_tab_size, tab_array_size / 1024);
2135 	IP_VS_DBG(0, "Each connection entry needs %zd bytes at least\n",
2136 		  sizeof(struct ip_vs_conn));
2137 
2138 	return 0;
2139 }
2140 
ip_vs_conn_cleanup(void)2141 void ip_vs_conn_cleanup(void)
2142 {
2143 	/* Wait all ip_vs_conn_rcu_free() callbacks to complete */
2144 	rcu_barrier();
2145 	/* Release the empty cache */
2146 	kmem_cache_destroy(ip_vs_conn_cachep);
2147 }
2148