xref: /linux/net/ipv4/inet_timewait_sock.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * INET		An implementation of the TCP/IP protocol suite for the LINUX
4  *		operating system.  INET is implemented using the  BSD Socket
5  *		interface as the means of communication with the user level.
6  *
7  *		Generic TIME_WAIT sockets functions
8  *
9  *		From code orinally in TCP
10  */
11 
12 #include <linux/kernel.h>
13 #include <linux/slab.h>
14 #include <linux/module.h>
15 #include <net/inet_hashtables.h>
16 #include <net/inet_timewait_sock.h>
17 #include <net/ip.h>
18 #include <net/tcp.h>
19 #include <net/psp.h>
20 
21 /**
22  *	inet_twsk_bind_unhash - unhash a timewait socket from bind hash
23  *	@tw: timewait socket
24  *	@hashinfo: hashinfo pointer
25  *
26  *	unhash a timewait socket from bind hash, if hashed.
27  *	bind hash lock must be held by caller.
28  *	Returns 1 if caller should call inet_twsk_put() after lock release.
29  */
30 void inet_twsk_bind_unhash(struct inet_timewait_sock *tw,
31 			  struct inet_hashinfo *hashinfo)
32 {
33 	struct inet_bind2_bucket *tb2 = tw->tw_tb2;
34 	struct inet_bind_bucket *tb = tw->tw_tb;
35 
36 	if (!tb)
37 		return;
38 
39 	__sk_del_bind_node((struct sock *)tw);
40 	tw->tw_tb = NULL;
41 	tw->tw_tb2 = NULL;
42 	inet_bind2_bucket_destroy(hashinfo->bind2_bucket_cachep, tb2);
43 	inet_bind_bucket_destroy(tb);
44 
45 	__sock_put((struct sock *)tw);
46 }
47 
48 /* Must be called with locally disabled BHs. */
49 static void inet_twsk_kill(struct inet_timewait_sock *tw)
50 {
51 	struct inet_hashinfo *hashinfo = tw->tw_dr->hashinfo;
52 	spinlock_t *lock = inet_ehash_lockp(hashinfo, tw->tw_hash);
53 	struct inet_bind_hashbucket *bhead, *bhead2;
54 
55 	spin_lock(lock);
56 	sk_nulls_del_node_init_rcu((struct sock *)tw);
57 	spin_unlock(lock);
58 
59 	/* Disassociate with bind bucket. */
60 	bhead = &hashinfo->bhash[inet_bhashfn(twsk_net(tw), tw->tw_num,
61 			hashinfo->bhash_size)];
62 	bhead2 = inet_bhashfn_portaddr(hashinfo, (struct sock *)tw,
63 				       twsk_net(tw), tw->tw_num);
64 
65 	spin_lock(&bhead->lock);
66 	spin_lock(&bhead2->lock);
67 	inet_twsk_bind_unhash(tw, hashinfo);
68 	spin_unlock(&bhead2->lock);
69 	spin_unlock(&bhead->lock);
70 
71 	refcount_dec(&tw->tw_dr->tw_refcount);
72 	inet_twsk_put(tw);
73 }
74 
75 void inet_twsk_free(struct inet_timewait_sock *tw)
76 {
77 	struct module *owner = tw->tw_prot->owner;
78 
79 	tcp_twsk_destructor((struct sock *)tw);
80 	kmem_cache_free(tw->tw_prot->twsk_prot->twsk_slab, tw);
81 	module_put(owner);
82 }
83 
84 void inet_twsk_put(struct inet_timewait_sock *tw)
85 {
86 	if (refcount_dec_and_test(&tw->tw_refcnt))
87 		inet_twsk_free(tw);
88 }
89 EXPORT_SYMBOL_GPL(inet_twsk_put);
90 
91 static void inet_twsk_schedule(struct inet_timewait_sock *tw, int timeo)
92 {
93 	__inet_twsk_schedule(tw, timeo, false);
94 }
95 
96 /*
97  * Enter the time wait state.
98  * Essentially we whip up a timewait bucket, copy the relevant info into it
99  * from the SK, and mess with hash chains and list linkage.
100  *
101  * The caller must not access @tw anymore after this function returns.
102  */
103 void inet_twsk_hashdance_schedule(struct inet_timewait_sock *tw,
104 				  struct sock *sk,
105 				  struct inet_hashinfo *hashinfo,
106 				  int timeo)
107 {
108 	spinlock_t *lock = inet_ehash_lockp(hashinfo, sk->sk_hash);
109 	struct inet_connection_sock *icsk = inet_csk(sk);
110 	struct inet_bind_hashbucket *bhead, *bhead2;
111 	const struct inet_sock *inet = inet_sk(sk);
112 
113 	icsk->unhashed_state = sk->sk_state;
114 
115 	/* Put TW into bind hash. Original socket stays there too.
116 	 * Note, that any socket with inet->num != 0 MUST be bound in
117 	 * binding cache, even if it is closed.
118 	 */
119 	bhead = &hashinfo->bhash[inet_bhashfn(twsk_net(tw), inet->inet_num,
120 			hashinfo->bhash_size)];
121 	bhead2 = inet_bhashfn_portaddr(hashinfo, sk, twsk_net(tw), inet->inet_num);
122 
123 	local_bh_disable();
124 	spin_lock(&bhead->lock);
125 	spin_lock(&bhead2->lock);
126 
127 	tw->tw_tb = icsk->icsk_bind_hash;
128 	WARN_ON(!icsk->icsk_bind_hash);
129 
130 	tw->tw_tb2 = icsk->icsk_bind2_hash;
131 	WARN_ON(!icsk->icsk_bind2_hash);
132 	sk_add_bind_node((struct sock *)tw, &tw->tw_tb2->owners);
133 
134 	spin_unlock(&bhead2->lock);
135 	spin_unlock(&bhead->lock);
136 
137 	spin_lock(lock);
138 
139 	/* tw_refcnt is set to 3 because we have :
140 	 * - one reference for bhash chain.
141 	 * - one reference for ehash chain.
142 	 * - one reference for timer.
143 	 * Also note that after this point, we lost our implicit reference
144 	 * so we are not allowed to use tw anymore.
145 	 */
146 	refcount_set_release(&tw->tw_refcnt, 3);
147 
148 	/* Ensure tw_refcnt has been set before tw is published.
149 	 * smp_wmb() provides the necessary memory barrier to enforce this
150 	 * ordering.
151 	 */
152 	smp_wmb();
153 
154 	hlist_nulls_replace_init_rcu(&sk->sk_nulls_node, &tw->tw_node);
155 	sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
156 
157 	inet_twsk_schedule(tw, timeo);
158 
159 	spin_unlock(lock);
160 	local_bh_enable();
161 }
162 
163 static void tw_timer_handler(struct timer_list *t)
164 {
165 	struct inet_timewait_sock *tw = timer_container_of(tw, t, tw_timer);
166 
167 	inet_twsk_kill(tw);
168 }
169 
170 struct inet_timewait_sock *inet_twsk_alloc(const struct sock *sk,
171 					   struct inet_timewait_death_row *dr,
172 					   const int state)
173 {
174 	struct inet_timewait_sock *tw;
175 
176 	if (refcount_read(&dr->tw_refcount) - 1 >=
177 	    READ_ONCE(dr->sysctl_max_tw_buckets))
178 		return NULL;
179 
180 	tw = kmem_cache_alloc(sk->sk_prot_creator->twsk_prot->twsk_slab,
181 			      GFP_ATOMIC);
182 	if (tw) {
183 		const struct inet_sock *inet = inet_sk(sk);
184 
185 		tw->tw_dr	    = dr;
186 		/* Give us an identity. */
187 		tw->tw_daddr	    = inet->inet_daddr;
188 		tw->tw_rcv_saddr    = inet->inet_rcv_saddr;
189 		tw->tw_bound_dev_if = sk->sk_bound_dev_if;
190 		tw->tw_tos	    = inet->tos;
191 		tw->tw_num	    = inet->inet_num;
192 		tw->tw_state	    = TCP_TIME_WAIT;
193 		tw->tw_substate	    = state;
194 		tw->tw_sport	    = inet->inet_sport;
195 		tw->tw_dport	    = inet->inet_dport;
196 		tw->tw_family	    = sk->sk_family;
197 		tw->tw_reuse	    = sk->sk_reuse;
198 		tw->tw_reuseport    = sk->sk_reuseport;
199 		tw->tw_hash	    = sk->sk_hash;
200 		tw->tw_ipv6only	    = 0;
201 		tw->tw_transparent  = inet_test_bit(TRANSPARENT, sk);
202 		tw->tw_connect_bind = !!(sk->sk_userlocks & SOCK_CONNECT_BIND);
203 		tw->tw_prot	    = sk->sk_prot_creator;
204 		atomic64_set(&tw->tw_cookie, atomic64_read(&sk->sk_cookie));
205 		twsk_net_set(tw, sock_net(sk));
206 		timer_setup(&tw->tw_timer, tw_timer_handler, 0);
207 #ifdef CONFIG_SOCK_VALIDATE_XMIT
208 		tw->tw_validate_xmit_skb = NULL;
209 #endif
210 		/*
211 		 * Because we use RCU lookups, we should not set tw_refcnt
212 		 * to a non null value before everything is setup for this
213 		 * timewait socket.
214 		 */
215 		refcount_set(&tw->tw_refcnt, 0);
216 
217 		__module_get(tw->tw_prot->owner);
218 		psp_twsk_init(tw, sk);
219 	}
220 
221 	return tw;
222 }
223 
224 /* These are always called from BH context.  See callers in
225  * tcp_input.c to verify this.
226  */
227 
228 /* This is for handling early-kills of TIME_WAIT sockets.
229  * Warning : consume reference.
230  * Caller should not access tw anymore.
231  */
232 void inet_twsk_deschedule_put(struct inet_timewait_sock *tw)
233 {
234 	struct inet_hashinfo *hashinfo = tw->tw_dr->hashinfo;
235 	spinlock_t *lock = inet_ehash_lockp(hashinfo, tw->tw_hash);
236 
237 	/* inet_twsk_purge() walks over all sockets, including tw ones,
238 	 * and removes them via inet_twsk_deschedule_put() after a
239 	 * refcount_inc_not_zero().
240 	 *
241 	 * inet_twsk_hashdance_schedule() must (re)init the refcount before
242 	 * arming the timer, i.e. inet_twsk_purge can obtain a reference to
243 	 * a twsk that did not yet schedule the timer.
244 	 *
245 	 * The ehash lock synchronizes these two:
246 	 * After acquiring the lock, the timer is always scheduled (else
247 	 * timer_shutdown returns false), because hashdance_schedule releases
248 	 * the ehash lock only after completing the timer initialization.
249 	 *
250 	 * Without grabbing the ehash lock, we get:
251 	 * 1) cpu x sets twsk refcount to 3
252 	 * 2) cpu y bumps refcount to 4
253 	 * 3) cpu y calls inet_twsk_deschedule_put() and shuts timer down
254 	 * 4) cpu x tries to start timer, but mod_timer is a noop post-shutdown
255 	 * -> timer refcount is never decremented.
256 	 */
257 	spin_lock(lock);
258 	/*  Makes sure hashdance_schedule() has completed */
259 	spin_unlock(lock);
260 
261 	if (timer_shutdown_sync(&tw->tw_timer))
262 		inet_twsk_kill(tw);
263 	inet_twsk_put(tw);
264 }
265 EXPORT_SYMBOL(inet_twsk_deschedule_put);
266 
267 void __inet_twsk_schedule(struct inet_timewait_sock *tw, int timeo, bool rearm)
268 {
269 	/* timeout := RTO * 3.5
270 	 *
271 	 * 3.5 = 1+2+0.5 to wait for two retransmits.
272 	 *
273 	 * RATIONALE: if FIN arrived and we entered TIME-WAIT state,
274 	 * our ACK acking that FIN can be lost. If N subsequent retransmitted
275 	 * FINs (or previous seqments) are lost (probability of such event
276 	 * is p^(N+1), where p is probability to lose single packet and
277 	 * time to detect the loss is about RTO*(2^N - 1) with exponential
278 	 * backoff). Normal timewait length is calculated so, that we
279 	 * waited at least for one retransmitted FIN (maximal RTO is 120sec).
280 	 * [ BTW Linux. following BSD, violates this requirement waiting
281 	 *   only for 60sec, we should wait at least for 240 secs.
282 	 *   Well, 240 consumes too much of resources 8)
283 	 * ]
284 	 * This interval is not reduced to catch old duplicate and
285 	 * responces to our wandering segments living for two MSLs.
286 	 * However, if we use PAWS to detect
287 	 * old duplicates, we can reduce the interval to bounds required
288 	 * by RTO, rather than MSL. So, if peer understands PAWS, we
289 	 * kill tw bucket after 3.5*RTO (it is important that this number
290 	 * is greater than TS tick!) and detect old duplicates with help
291 	 * of PAWS.
292 	 */
293 
294 	if (!rearm) {
295 		bool kill = timeo <= 4*HZ;
296 
297 		__NET_INC_STATS(twsk_net(tw), kill ? LINUX_MIB_TIMEWAITKILLED :
298 						     LINUX_MIB_TIMEWAITED);
299 		BUG_ON(mod_timer(&tw->tw_timer, jiffies + timeo));
300 		refcount_inc(&tw->tw_dr->tw_refcount);
301 	} else {
302 		mod_timer_pending(&tw->tw_timer, jiffies + timeo);
303 	}
304 }
305 
306 /* Remove all non full sockets (TIME_WAIT and NEW_SYN_RECV) for dead netns */
307 void inet_twsk_purge(struct inet_hashinfo *hashinfo)
308 {
309 	struct inet_ehash_bucket *head = &hashinfo->ehash[0];
310 	unsigned int ehash_mask = hashinfo->ehash_mask;
311 	struct hlist_nulls_node *node;
312 	unsigned int slot;
313 	struct sock *sk;
314 
315 	for (slot = 0; slot <= ehash_mask; slot++, head++) {
316 		if (hlist_nulls_empty(&head->chain))
317 			continue;
318 
319 restart_rcu:
320 		cond_resched();
321 		rcu_read_lock();
322 restart:
323 		sk_nulls_for_each_rcu(sk, node, &head->chain) {
324 			int state = inet_sk_state_load(sk);
325 
326 			if ((1 << state) & ~(TCPF_TIME_WAIT |
327 					     TCPF_NEW_SYN_RECV))
328 				continue;
329 
330 			if (check_net(sock_net(sk)))
331 				continue;
332 
333 			if (unlikely(!refcount_inc_not_zero_acquire(&sk->sk_refcnt)))
334 				continue;
335 
336 			if (check_net(sock_net(sk))) {
337 				sock_gen_put(sk);
338 				goto restart;
339 			}
340 
341 			rcu_read_unlock();
342 			local_bh_disable();
343 			if (state == TCP_TIME_WAIT) {
344 				inet_twsk_deschedule_put(inet_twsk(sk));
345 			} else {
346 				struct request_sock *req = inet_reqsk(sk);
347 
348 				inet_csk_reqsk_queue_drop_and_put(req->rsk_listener,
349 								  req);
350 			}
351 			local_bh_enable();
352 			goto restart_rcu;
353 		}
354 		/* If the nulls value we got at the end of this lookup is
355 		 * not the expected one, we must restart lookup.
356 		 * We probably met an item that was moved to another chain.
357 		 */
358 		if (get_nulls_value(node) != slot)
359 			goto restart;
360 		rcu_read_unlock();
361 	}
362 }
363