xref: /openbmc/linux/net/mptcp/protocol.c (revision 9b358af7)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Multipath TCP
3  *
4  * Copyright (c) 2017 - 2019, Intel Corporation.
5  */
6 
7 #define pr_fmt(fmt) "MPTCP: " fmt
8 
9 #include <linux/kernel.h>
10 #include <linux/module.h>
11 #include <linux/netdevice.h>
12 #include <linux/sched/signal.h>
13 #include <linux/atomic.h>
14 #include <net/sock.h>
15 #include <net/inet_common.h>
16 #include <net/inet_hashtables.h>
17 #include <net/protocol.h>
18 #include <net/tcp.h>
19 #include <net/tcp_states.h>
20 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
21 #include <net/transp_v6.h>
22 #endif
23 #include <net/mptcp.h>
24 #include <net/xfrm.h>
25 #include "protocol.h"
26 #include "mib.h"
27 
28 #define CREATE_TRACE_POINTS
29 #include <trace/events/mptcp.h>
30 
31 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
32 struct mptcp6_sock {
33 	struct mptcp_sock msk;
34 	struct ipv6_pinfo np;
35 };
36 #endif
37 
38 struct mptcp_skb_cb {
39 	u64 map_seq;
40 	u64 end_seq;
41 	u32 offset;
42 };
43 
44 #define MPTCP_SKB_CB(__skb)	((struct mptcp_skb_cb *)&((__skb)->cb[0]))
45 
46 static struct percpu_counter mptcp_sockets_allocated;
47 
48 static void __mptcp_destroy_sock(struct sock *sk);
49 static void __mptcp_check_send_data_fin(struct sock *sk);
50 
51 DEFINE_PER_CPU(struct mptcp_delegated_action, mptcp_delegated_actions);
52 static struct net_device mptcp_napi_dev;
53 
54 /* If msk has an initial subflow socket, and the MP_CAPABLE handshake has not
55  * completed yet or has failed, return the subflow socket.
56  * Otherwise return NULL.
57  */
58 struct socket *__mptcp_nmpc_socket(const struct mptcp_sock *msk)
59 {
60 	if (!msk->subflow || READ_ONCE(msk->can_ack))
61 		return NULL;
62 
63 	return msk->subflow;
64 }
65 
66 /* Returns end sequence number of the receiver's advertised window */
67 static u64 mptcp_wnd_end(const struct mptcp_sock *msk)
68 {
69 	return READ_ONCE(msk->wnd_end);
70 }
71 
72 static bool mptcp_is_tcpsk(struct sock *sk)
73 {
74 	struct socket *sock = sk->sk_socket;
75 
76 	if (unlikely(sk->sk_prot == &tcp_prot)) {
77 		/* we are being invoked after mptcp_accept() has
78 		 * accepted a non-mp-capable flow: sk is a tcp_sk,
79 		 * not an mptcp one.
80 		 *
81 		 * Hand the socket over to tcp so all further socket ops
82 		 * bypass mptcp.
83 		 */
84 		sock->ops = &inet_stream_ops;
85 		return true;
86 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
87 	} else if (unlikely(sk->sk_prot == &tcpv6_prot)) {
88 		sock->ops = &inet6_stream_ops;
89 		return true;
90 #endif
91 	}
92 
93 	return false;
94 }
95 
96 static int __mptcp_socket_create(struct mptcp_sock *msk)
97 {
98 	struct mptcp_subflow_context *subflow;
99 	struct sock *sk = (struct sock *)msk;
100 	struct socket *ssock;
101 	int err;
102 
103 	err = mptcp_subflow_create_socket(sk, &ssock);
104 	if (err)
105 		return err;
106 
107 	msk->first = ssock->sk;
108 	msk->subflow = ssock;
109 	subflow = mptcp_subflow_ctx(ssock->sk);
110 	list_add(&subflow->node, &msk->conn_list);
111 	sock_hold(ssock->sk);
112 	subflow->request_mptcp = 1;
113 	mptcp_sock_graft(msk->first, sk->sk_socket);
114 
115 	return 0;
116 }
117 
118 static void mptcp_drop(struct sock *sk, struct sk_buff *skb)
119 {
120 	sk_drops_add(sk, skb);
121 	__kfree_skb(skb);
122 }
123 
124 static bool mptcp_try_coalesce(struct sock *sk, struct sk_buff *to,
125 			       struct sk_buff *from)
126 {
127 	bool fragstolen;
128 	int delta;
129 
130 	if (MPTCP_SKB_CB(from)->offset ||
131 	    !skb_try_coalesce(to, from, &fragstolen, &delta))
132 		return false;
133 
134 	pr_debug("colesced seq %llx into %llx new len %d new end seq %llx",
135 		 MPTCP_SKB_CB(from)->map_seq, MPTCP_SKB_CB(to)->map_seq,
136 		 to->len, MPTCP_SKB_CB(from)->end_seq);
137 	MPTCP_SKB_CB(to)->end_seq = MPTCP_SKB_CB(from)->end_seq;
138 	kfree_skb_partial(from, fragstolen);
139 	atomic_add(delta, &sk->sk_rmem_alloc);
140 	sk_mem_charge(sk, delta);
141 	return true;
142 }
143 
144 static bool mptcp_ooo_try_coalesce(struct mptcp_sock *msk, struct sk_buff *to,
145 				   struct sk_buff *from)
146 {
147 	if (MPTCP_SKB_CB(from)->map_seq != MPTCP_SKB_CB(to)->end_seq)
148 		return false;
149 
150 	return mptcp_try_coalesce((struct sock *)msk, to, from);
151 }
152 
153 /* "inspired" by tcp_data_queue_ofo(), main differences:
154  * - use mptcp seqs
155  * - don't cope with sacks
156  */
157 static void mptcp_data_queue_ofo(struct mptcp_sock *msk, struct sk_buff *skb)
158 {
159 	struct sock *sk = (struct sock *)msk;
160 	struct rb_node **p, *parent;
161 	u64 seq, end_seq, max_seq;
162 	struct sk_buff *skb1;
163 
164 	seq = MPTCP_SKB_CB(skb)->map_seq;
165 	end_seq = MPTCP_SKB_CB(skb)->end_seq;
166 	max_seq = READ_ONCE(msk->rcv_wnd_sent);
167 
168 	pr_debug("msk=%p seq=%llx limit=%llx empty=%d", msk, seq, max_seq,
169 		 RB_EMPTY_ROOT(&msk->out_of_order_queue));
170 	if (after64(end_seq, max_seq)) {
171 		/* out of window */
172 		mptcp_drop(sk, skb);
173 		pr_debug("oow by %lld, rcv_wnd_sent %llu\n",
174 			 (unsigned long long)end_seq - (unsigned long)max_seq,
175 			 (unsigned long long)msk->rcv_wnd_sent);
176 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_NODSSWINDOW);
177 		return;
178 	}
179 
180 	p = &msk->out_of_order_queue.rb_node;
181 	MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUE);
182 	if (RB_EMPTY_ROOT(&msk->out_of_order_queue)) {
183 		rb_link_node(&skb->rbnode, NULL, p);
184 		rb_insert_color(&skb->rbnode, &msk->out_of_order_queue);
185 		msk->ooo_last_skb = skb;
186 		goto end;
187 	}
188 
189 	/* with 2 subflows, adding at end of ooo queue is quite likely
190 	 * Use of ooo_last_skb avoids the O(Log(N)) rbtree lookup.
191 	 */
192 	if (mptcp_ooo_try_coalesce(msk, msk->ooo_last_skb, skb)) {
193 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOMERGE);
194 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUETAIL);
195 		return;
196 	}
197 
198 	/* Can avoid an rbtree lookup if we are adding skb after ooo_last_skb */
199 	if (!before64(seq, MPTCP_SKB_CB(msk->ooo_last_skb)->end_seq)) {
200 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUETAIL);
201 		parent = &msk->ooo_last_skb->rbnode;
202 		p = &parent->rb_right;
203 		goto insert;
204 	}
205 
206 	/* Find place to insert this segment. Handle overlaps on the way. */
207 	parent = NULL;
208 	while (*p) {
209 		parent = *p;
210 		skb1 = rb_to_skb(parent);
211 		if (before64(seq, MPTCP_SKB_CB(skb1)->map_seq)) {
212 			p = &parent->rb_left;
213 			continue;
214 		}
215 		if (before64(seq, MPTCP_SKB_CB(skb1)->end_seq)) {
216 			if (!after64(end_seq, MPTCP_SKB_CB(skb1)->end_seq)) {
217 				/* All the bits are present. Drop. */
218 				mptcp_drop(sk, skb);
219 				MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
220 				return;
221 			}
222 			if (after64(seq, MPTCP_SKB_CB(skb1)->map_seq)) {
223 				/* partial overlap:
224 				 *     |     skb      |
225 				 *  |     skb1    |
226 				 * continue traversing
227 				 */
228 			} else {
229 				/* skb's seq == skb1's seq and skb covers skb1.
230 				 * Replace skb1 with skb.
231 				 */
232 				rb_replace_node(&skb1->rbnode, &skb->rbnode,
233 						&msk->out_of_order_queue);
234 				mptcp_drop(sk, skb1);
235 				MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
236 				goto merge_right;
237 			}
238 		} else if (mptcp_ooo_try_coalesce(msk, skb1, skb)) {
239 			MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOMERGE);
240 			return;
241 		}
242 		p = &parent->rb_right;
243 	}
244 
245 insert:
246 	/* Insert segment into RB tree. */
247 	rb_link_node(&skb->rbnode, parent, p);
248 	rb_insert_color(&skb->rbnode, &msk->out_of_order_queue);
249 
250 merge_right:
251 	/* Remove other segments covered by skb. */
252 	while ((skb1 = skb_rb_next(skb)) != NULL) {
253 		if (before64(end_seq, MPTCP_SKB_CB(skb1)->end_seq))
254 			break;
255 		rb_erase(&skb1->rbnode, &msk->out_of_order_queue);
256 		mptcp_drop(sk, skb1);
257 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
258 	}
259 	/* If there is no skb after us, we are the last_skb ! */
260 	if (!skb1)
261 		msk->ooo_last_skb = skb;
262 
263 end:
264 	skb_condense(skb);
265 	skb_set_owner_r(skb, sk);
266 }
267 
268 static bool __mptcp_move_skb(struct mptcp_sock *msk, struct sock *ssk,
269 			     struct sk_buff *skb, unsigned int offset,
270 			     size_t copy_len)
271 {
272 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
273 	struct sock *sk = (struct sock *)msk;
274 	struct sk_buff *tail;
275 
276 	__skb_unlink(skb, &ssk->sk_receive_queue);
277 
278 	skb_ext_reset(skb);
279 	skb_orphan(skb);
280 
281 	/* try to fetch required memory from subflow */
282 	if (!sk_rmem_schedule(sk, skb, skb->truesize)) {
283 		if (ssk->sk_forward_alloc < skb->truesize)
284 			goto drop;
285 		__sk_mem_reclaim(ssk, skb->truesize);
286 		if (!sk_rmem_schedule(sk, skb, skb->truesize))
287 			goto drop;
288 	}
289 
290 	/* the skb map_seq accounts for the skb offset:
291 	 * mptcp_subflow_get_mapped_dsn() is based on the current tp->copied_seq
292 	 * value
293 	 */
294 	MPTCP_SKB_CB(skb)->map_seq = mptcp_subflow_get_mapped_dsn(subflow);
295 	MPTCP_SKB_CB(skb)->end_seq = MPTCP_SKB_CB(skb)->map_seq + copy_len;
296 	MPTCP_SKB_CB(skb)->offset = offset;
297 
298 	if (MPTCP_SKB_CB(skb)->map_seq == msk->ack_seq) {
299 		/* in sequence */
300 		WRITE_ONCE(msk->ack_seq, msk->ack_seq + copy_len);
301 		tail = skb_peek_tail(&sk->sk_receive_queue);
302 		if (tail && mptcp_try_coalesce(sk, tail, skb))
303 			return true;
304 
305 		skb_set_owner_r(skb, sk);
306 		__skb_queue_tail(&sk->sk_receive_queue, skb);
307 		return true;
308 	} else if (after64(MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq)) {
309 		mptcp_data_queue_ofo(msk, skb);
310 		return false;
311 	}
312 
313 	/* old data, keep it simple and drop the whole pkt, sender
314 	 * will retransmit as needed, if needed.
315 	 */
316 	MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
317 drop:
318 	mptcp_drop(sk, skb);
319 	return false;
320 }
321 
322 static void mptcp_stop_timer(struct sock *sk)
323 {
324 	struct inet_connection_sock *icsk = inet_csk(sk);
325 
326 	sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
327 	mptcp_sk(sk)->timer_ival = 0;
328 }
329 
330 static void mptcp_close_wake_up(struct sock *sk)
331 {
332 	if (sock_flag(sk, SOCK_DEAD))
333 		return;
334 
335 	sk->sk_state_change(sk);
336 	if (sk->sk_shutdown == SHUTDOWN_MASK ||
337 	    sk->sk_state == TCP_CLOSE)
338 		sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
339 	else
340 		sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
341 }
342 
343 static bool mptcp_pending_data_fin_ack(struct sock *sk)
344 {
345 	struct mptcp_sock *msk = mptcp_sk(sk);
346 
347 	return !__mptcp_check_fallback(msk) &&
348 	       ((1 << sk->sk_state) &
349 		(TCPF_FIN_WAIT1 | TCPF_CLOSING | TCPF_LAST_ACK)) &&
350 	       msk->write_seq == READ_ONCE(msk->snd_una);
351 }
352 
353 static void mptcp_check_data_fin_ack(struct sock *sk)
354 {
355 	struct mptcp_sock *msk = mptcp_sk(sk);
356 
357 	/* Look for an acknowledged DATA_FIN */
358 	if (mptcp_pending_data_fin_ack(sk)) {
359 		WRITE_ONCE(msk->snd_data_fin_enable, 0);
360 
361 		switch (sk->sk_state) {
362 		case TCP_FIN_WAIT1:
363 			inet_sk_state_store(sk, TCP_FIN_WAIT2);
364 			break;
365 		case TCP_CLOSING:
366 		case TCP_LAST_ACK:
367 			inet_sk_state_store(sk, TCP_CLOSE);
368 			break;
369 		}
370 
371 		mptcp_close_wake_up(sk);
372 	}
373 }
374 
375 static bool mptcp_pending_data_fin(struct sock *sk, u64 *seq)
376 {
377 	struct mptcp_sock *msk = mptcp_sk(sk);
378 
379 	if (READ_ONCE(msk->rcv_data_fin) &&
380 	    ((1 << sk->sk_state) &
381 	     (TCPF_ESTABLISHED | TCPF_FIN_WAIT1 | TCPF_FIN_WAIT2))) {
382 		u64 rcv_data_fin_seq = READ_ONCE(msk->rcv_data_fin_seq);
383 
384 		if (msk->ack_seq == rcv_data_fin_seq) {
385 			if (seq)
386 				*seq = rcv_data_fin_seq;
387 
388 			return true;
389 		}
390 	}
391 
392 	return false;
393 }
394 
395 static void mptcp_set_datafin_timeout(const struct sock *sk)
396 {
397 	struct inet_connection_sock *icsk = inet_csk(sk);
398 
399 	mptcp_sk(sk)->timer_ival = min(TCP_RTO_MAX,
400 				       TCP_RTO_MIN << icsk->icsk_retransmits);
401 }
402 
403 static void mptcp_set_timeout(const struct sock *sk, const struct sock *ssk)
404 {
405 	long tout = ssk && inet_csk(ssk)->icsk_pending ?
406 				      inet_csk(ssk)->icsk_timeout - jiffies : 0;
407 
408 	if (tout <= 0)
409 		tout = mptcp_sk(sk)->timer_ival;
410 	mptcp_sk(sk)->timer_ival = tout > 0 ? tout : TCP_RTO_MIN;
411 }
412 
413 static bool tcp_can_send_ack(const struct sock *ssk)
414 {
415 	return !((1 << inet_sk_state_load(ssk)) &
416 	       (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_TIME_WAIT | TCPF_CLOSE | TCPF_LISTEN));
417 }
418 
419 static void mptcp_send_ack(struct mptcp_sock *msk)
420 {
421 	struct mptcp_subflow_context *subflow;
422 
423 	mptcp_for_each_subflow(msk, subflow) {
424 		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
425 
426 		lock_sock(ssk);
427 		if (tcp_can_send_ack(ssk))
428 			tcp_send_ack(ssk);
429 		release_sock(ssk);
430 	}
431 }
432 
433 static bool mptcp_subflow_cleanup_rbuf(struct sock *ssk)
434 {
435 	int ret;
436 
437 	lock_sock(ssk);
438 	ret = tcp_can_send_ack(ssk);
439 	if (ret)
440 		tcp_cleanup_rbuf(ssk, 1);
441 	release_sock(ssk);
442 	return ret;
443 }
444 
445 static void mptcp_cleanup_rbuf(struct mptcp_sock *msk)
446 {
447 	struct sock *ack_hint = READ_ONCE(msk->ack_hint);
448 	int old_space = READ_ONCE(msk->old_wspace);
449 	struct mptcp_subflow_context *subflow;
450 	struct sock *sk = (struct sock *)msk;
451 	bool cleanup;
452 
453 	/* this is a simple superset of what tcp_cleanup_rbuf() implements
454 	 * so that we don't have to acquire the ssk socket lock most of the time
455 	 * to do actually nothing
456 	 */
457 	cleanup = __mptcp_space(sk) - old_space >= max(0, old_space);
458 	if (!cleanup)
459 		return;
460 
461 	/* if the hinted ssk is still active, try to use it */
462 	if (likely(ack_hint)) {
463 		mptcp_for_each_subflow(msk, subflow) {
464 			struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
465 
466 			if (ack_hint == ssk && mptcp_subflow_cleanup_rbuf(ssk))
467 				return;
468 		}
469 	}
470 
471 	/* otherwise pick the first active subflow */
472 	mptcp_for_each_subflow(msk, subflow)
473 		if (mptcp_subflow_cleanup_rbuf(mptcp_subflow_tcp_sock(subflow)))
474 			return;
475 }
476 
477 static bool mptcp_check_data_fin(struct sock *sk)
478 {
479 	struct mptcp_sock *msk = mptcp_sk(sk);
480 	u64 rcv_data_fin_seq;
481 	bool ret = false;
482 
483 	if (__mptcp_check_fallback(msk))
484 		return ret;
485 
486 	/* Need to ack a DATA_FIN received from a peer while this side
487 	 * of the connection is in ESTABLISHED, FIN_WAIT1, or FIN_WAIT2.
488 	 * msk->rcv_data_fin was set when parsing the incoming options
489 	 * at the subflow level and the msk lock was not held, so this
490 	 * is the first opportunity to act on the DATA_FIN and change
491 	 * the msk state.
492 	 *
493 	 * If we are caught up to the sequence number of the incoming
494 	 * DATA_FIN, send the DATA_ACK now and do state transition.  If
495 	 * not caught up, do nothing and let the recv code send DATA_ACK
496 	 * when catching up.
497 	 */
498 
499 	if (mptcp_pending_data_fin(sk, &rcv_data_fin_seq)) {
500 		WRITE_ONCE(msk->ack_seq, msk->ack_seq + 1);
501 		WRITE_ONCE(msk->rcv_data_fin, 0);
502 
503 		sk->sk_shutdown |= RCV_SHUTDOWN;
504 		smp_mb__before_atomic(); /* SHUTDOWN must be visible first */
505 		set_bit(MPTCP_DATA_READY, &msk->flags);
506 
507 		switch (sk->sk_state) {
508 		case TCP_ESTABLISHED:
509 			inet_sk_state_store(sk, TCP_CLOSE_WAIT);
510 			break;
511 		case TCP_FIN_WAIT1:
512 			inet_sk_state_store(sk, TCP_CLOSING);
513 			break;
514 		case TCP_FIN_WAIT2:
515 			inet_sk_state_store(sk, TCP_CLOSE);
516 			break;
517 		default:
518 			/* Other states not expected */
519 			WARN_ON_ONCE(1);
520 			break;
521 		}
522 
523 		ret = true;
524 		mptcp_set_timeout(sk, NULL);
525 		mptcp_send_ack(msk);
526 		mptcp_close_wake_up(sk);
527 	}
528 	return ret;
529 }
530 
531 static bool __mptcp_move_skbs_from_subflow(struct mptcp_sock *msk,
532 					   struct sock *ssk,
533 					   unsigned int *bytes)
534 {
535 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
536 	struct sock *sk = (struct sock *)msk;
537 	unsigned int moved = 0;
538 	bool more_data_avail;
539 	struct tcp_sock *tp;
540 	bool done = false;
541 	int sk_rbuf;
542 
543 	sk_rbuf = READ_ONCE(sk->sk_rcvbuf);
544 
545 	if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
546 		int ssk_rbuf = READ_ONCE(ssk->sk_rcvbuf);
547 
548 		if (unlikely(ssk_rbuf > sk_rbuf)) {
549 			WRITE_ONCE(sk->sk_rcvbuf, ssk_rbuf);
550 			sk_rbuf = ssk_rbuf;
551 		}
552 	}
553 
554 	pr_debug("msk=%p ssk=%p", msk, ssk);
555 	tp = tcp_sk(ssk);
556 	do {
557 		u32 map_remaining, offset;
558 		u32 seq = tp->copied_seq;
559 		struct sk_buff *skb;
560 		bool fin;
561 
562 		/* try to move as much data as available */
563 		map_remaining = subflow->map_data_len -
564 				mptcp_subflow_get_map_offset(subflow);
565 
566 		skb = skb_peek(&ssk->sk_receive_queue);
567 		if (!skb) {
568 			/* if no data is found, a racing workqueue/recvmsg
569 			 * already processed the new data, stop here or we
570 			 * can enter an infinite loop
571 			 */
572 			if (!moved)
573 				done = true;
574 			break;
575 		}
576 
577 		if (__mptcp_check_fallback(msk)) {
578 			/* if we are running under the workqueue, TCP could have
579 			 * collapsed skbs between dummy map creation and now
580 			 * be sure to adjust the size
581 			 */
582 			map_remaining = skb->len;
583 			subflow->map_data_len = skb->len;
584 		}
585 
586 		offset = seq - TCP_SKB_CB(skb)->seq;
587 		fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
588 		if (fin) {
589 			done = true;
590 			seq++;
591 		}
592 
593 		if (offset < skb->len) {
594 			size_t len = skb->len - offset;
595 
596 			if (tp->urg_data)
597 				done = true;
598 
599 			if (__mptcp_move_skb(msk, ssk, skb, offset, len))
600 				moved += len;
601 			seq += len;
602 
603 			if (WARN_ON_ONCE(map_remaining < len))
604 				break;
605 		} else {
606 			WARN_ON_ONCE(!fin);
607 			sk_eat_skb(ssk, skb);
608 			done = true;
609 		}
610 
611 		WRITE_ONCE(tp->copied_seq, seq);
612 		more_data_avail = mptcp_subflow_data_available(ssk);
613 
614 		if (atomic_read(&sk->sk_rmem_alloc) > sk_rbuf) {
615 			done = true;
616 			break;
617 		}
618 	} while (more_data_avail);
619 	WRITE_ONCE(msk->ack_hint, ssk);
620 
621 	*bytes += moved;
622 	return done;
623 }
624 
625 static bool __mptcp_ofo_queue(struct mptcp_sock *msk)
626 {
627 	struct sock *sk = (struct sock *)msk;
628 	struct sk_buff *skb, *tail;
629 	bool moved = false;
630 	struct rb_node *p;
631 	u64 end_seq;
632 
633 	p = rb_first(&msk->out_of_order_queue);
634 	pr_debug("msk=%p empty=%d", msk, RB_EMPTY_ROOT(&msk->out_of_order_queue));
635 	while (p) {
636 		skb = rb_to_skb(p);
637 		if (after64(MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq))
638 			break;
639 
640 		p = rb_next(p);
641 		rb_erase(&skb->rbnode, &msk->out_of_order_queue);
642 
643 		if (unlikely(!after64(MPTCP_SKB_CB(skb)->end_seq,
644 				      msk->ack_seq))) {
645 			mptcp_drop(sk, skb);
646 			MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
647 			continue;
648 		}
649 
650 		end_seq = MPTCP_SKB_CB(skb)->end_seq;
651 		tail = skb_peek_tail(&sk->sk_receive_queue);
652 		if (!tail || !mptcp_ooo_try_coalesce(msk, tail, skb)) {
653 			int delta = msk->ack_seq - MPTCP_SKB_CB(skb)->map_seq;
654 
655 			/* skip overlapping data, if any */
656 			pr_debug("uncoalesced seq=%llx ack seq=%llx delta=%d",
657 				 MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq,
658 				 delta);
659 			MPTCP_SKB_CB(skb)->offset += delta;
660 			__skb_queue_tail(&sk->sk_receive_queue, skb);
661 		}
662 		msk->ack_seq = end_seq;
663 		moved = true;
664 	}
665 	return moved;
666 }
667 
668 /* In most cases we will be able to lock the mptcp socket.  If its already
669  * owned, we need to defer to the work queue to avoid ABBA deadlock.
670  */
671 static void move_skbs_to_msk(struct mptcp_sock *msk, struct sock *ssk)
672 {
673 	struct sock *sk = (struct sock *)msk;
674 	unsigned int moved = 0;
675 
676 	if (inet_sk_state_load(sk) == TCP_CLOSE)
677 		return;
678 
679 	mptcp_data_lock(sk);
680 
681 	__mptcp_move_skbs_from_subflow(msk, ssk, &moved);
682 	__mptcp_ofo_queue(msk);
683 
684 	/* If the moves have caught up with the DATA_FIN sequence number
685 	 * it's time to ack the DATA_FIN and change socket state, but
686 	 * this is not a good place to change state. Let the workqueue
687 	 * do it.
688 	 */
689 	if (mptcp_pending_data_fin(sk, NULL))
690 		mptcp_schedule_work(sk);
691 	mptcp_data_unlock(sk);
692 }
693 
694 void mptcp_data_ready(struct sock *sk, struct sock *ssk)
695 {
696 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
697 	struct mptcp_sock *msk = mptcp_sk(sk);
698 	int sk_rbuf, ssk_rbuf;
699 	bool wake;
700 
701 	/* The peer can send data while we are shutting down this
702 	 * subflow at msk destruction time, but we must avoid enqueuing
703 	 * more data to the msk receive queue
704 	 */
705 	if (unlikely(subflow->disposable))
706 		return;
707 
708 	/* move_skbs_to_msk below can legitly clear the data_avail flag,
709 	 * but we will need later to properly woke the reader, cache its
710 	 * value
711 	 */
712 	wake = subflow->data_avail == MPTCP_SUBFLOW_DATA_AVAIL;
713 	if (wake)
714 		set_bit(MPTCP_DATA_READY, &msk->flags);
715 
716 	ssk_rbuf = READ_ONCE(ssk->sk_rcvbuf);
717 	sk_rbuf = READ_ONCE(sk->sk_rcvbuf);
718 	if (unlikely(ssk_rbuf > sk_rbuf))
719 		sk_rbuf = ssk_rbuf;
720 
721 	/* over limit? can't append more skbs to msk */
722 	if (atomic_read(&sk->sk_rmem_alloc) > sk_rbuf)
723 		goto wake;
724 
725 	move_skbs_to_msk(msk, ssk);
726 
727 wake:
728 	if (wake)
729 		sk->sk_data_ready(sk);
730 }
731 
732 static bool mptcp_do_flush_join_list(struct mptcp_sock *msk)
733 {
734 	struct mptcp_subflow_context *subflow;
735 	bool ret = false;
736 
737 	if (likely(list_empty(&msk->join_list)))
738 		return false;
739 
740 	spin_lock_bh(&msk->join_list_lock);
741 	list_for_each_entry(subflow, &msk->join_list, node) {
742 		u32 sseq = READ_ONCE(subflow->setsockopt_seq);
743 
744 		mptcp_propagate_sndbuf((struct sock *)msk, mptcp_subflow_tcp_sock(subflow));
745 		if (READ_ONCE(msk->setsockopt_seq) != sseq)
746 			ret = true;
747 	}
748 	list_splice_tail_init(&msk->join_list, &msk->conn_list);
749 	spin_unlock_bh(&msk->join_list_lock);
750 
751 	return ret;
752 }
753 
754 void __mptcp_flush_join_list(struct mptcp_sock *msk)
755 {
756 	if (likely(!mptcp_do_flush_join_list(msk)))
757 		return;
758 
759 	if (!test_and_set_bit(MPTCP_WORK_SYNC_SETSOCKOPT, &msk->flags))
760 		mptcp_schedule_work((struct sock *)msk);
761 }
762 
763 static void mptcp_flush_join_list(struct mptcp_sock *msk)
764 {
765 	bool sync_needed = test_and_clear_bit(MPTCP_WORK_SYNC_SETSOCKOPT, &msk->flags);
766 
767 	might_sleep();
768 
769 	if (!mptcp_do_flush_join_list(msk) && !sync_needed)
770 		return;
771 
772 	mptcp_sockopt_sync_all(msk);
773 }
774 
775 static bool mptcp_timer_pending(struct sock *sk)
776 {
777 	return timer_pending(&inet_csk(sk)->icsk_retransmit_timer);
778 }
779 
780 static void mptcp_reset_timer(struct sock *sk)
781 {
782 	struct inet_connection_sock *icsk = inet_csk(sk);
783 	unsigned long tout;
784 
785 	/* prevent rescheduling on close */
786 	if (unlikely(inet_sk_state_load(sk) == TCP_CLOSE))
787 		return;
788 
789 	/* should never be called with mptcp level timer cleared */
790 	tout = READ_ONCE(mptcp_sk(sk)->timer_ival);
791 	if (WARN_ON_ONCE(!tout))
792 		tout = TCP_RTO_MIN;
793 	sk_reset_timer(sk, &icsk->icsk_retransmit_timer, jiffies + tout);
794 }
795 
796 bool mptcp_schedule_work(struct sock *sk)
797 {
798 	if (inet_sk_state_load(sk) != TCP_CLOSE &&
799 	    schedule_work(&mptcp_sk(sk)->work)) {
800 		/* each subflow already holds a reference to the sk, and the
801 		 * workqueue is invoked by a subflow, so sk can't go away here.
802 		 */
803 		sock_hold(sk);
804 		return true;
805 	}
806 	return false;
807 }
808 
809 void mptcp_subflow_eof(struct sock *sk)
810 {
811 	if (!test_and_set_bit(MPTCP_WORK_EOF, &mptcp_sk(sk)->flags))
812 		mptcp_schedule_work(sk);
813 }
814 
815 static void mptcp_check_for_eof(struct mptcp_sock *msk)
816 {
817 	struct mptcp_subflow_context *subflow;
818 	struct sock *sk = (struct sock *)msk;
819 	int receivers = 0;
820 
821 	mptcp_for_each_subflow(msk, subflow)
822 		receivers += !subflow->rx_eof;
823 	if (receivers)
824 		return;
825 
826 	if (!(sk->sk_shutdown & RCV_SHUTDOWN)) {
827 		/* hopefully temporary hack: propagate shutdown status
828 		 * to msk, when all subflows agree on it
829 		 */
830 		sk->sk_shutdown |= RCV_SHUTDOWN;
831 
832 		smp_mb__before_atomic(); /* SHUTDOWN must be visible first */
833 		set_bit(MPTCP_DATA_READY, &msk->flags);
834 		sk->sk_data_ready(sk);
835 	}
836 
837 	switch (sk->sk_state) {
838 	case TCP_ESTABLISHED:
839 		inet_sk_state_store(sk, TCP_CLOSE_WAIT);
840 		break;
841 	case TCP_FIN_WAIT1:
842 		inet_sk_state_store(sk, TCP_CLOSING);
843 		break;
844 	case TCP_FIN_WAIT2:
845 		inet_sk_state_store(sk, TCP_CLOSE);
846 		break;
847 	default:
848 		return;
849 	}
850 	mptcp_close_wake_up(sk);
851 }
852 
853 static struct sock *mptcp_subflow_recv_lookup(const struct mptcp_sock *msk)
854 {
855 	struct mptcp_subflow_context *subflow;
856 	struct sock *sk = (struct sock *)msk;
857 
858 	sock_owned_by_me(sk);
859 
860 	mptcp_for_each_subflow(msk, subflow) {
861 		if (subflow->data_avail)
862 			return mptcp_subflow_tcp_sock(subflow);
863 	}
864 
865 	return NULL;
866 }
867 
868 static bool mptcp_skb_can_collapse_to(u64 write_seq,
869 				      const struct sk_buff *skb,
870 				      const struct mptcp_ext *mpext)
871 {
872 	if (!tcp_skb_can_collapse_to(skb))
873 		return false;
874 
875 	/* can collapse only if MPTCP level sequence is in order and this
876 	 * mapping has not been xmitted yet
877 	 */
878 	return mpext && mpext->data_seq + mpext->data_len == write_seq &&
879 	       !mpext->frozen;
880 }
881 
882 static bool mptcp_frag_can_collapse_to(const struct mptcp_sock *msk,
883 				       const struct page_frag *pfrag,
884 				       const struct mptcp_data_frag *df)
885 {
886 	return df && pfrag->page == df->page &&
887 		pfrag->size - pfrag->offset > 0 &&
888 		df->data_seq + df->data_len == msk->write_seq;
889 }
890 
891 static int mptcp_wmem_with_overhead(struct sock *sk, int size)
892 {
893 	struct mptcp_sock *msk = mptcp_sk(sk);
894 	int ret, skbs;
895 
896 	ret = size + ((sizeof(struct mptcp_data_frag) * size) >> PAGE_SHIFT);
897 	skbs = (msk->tx_pending_data + size) / msk->size_goal_cache;
898 	if (skbs < msk->skb_tx_cache.qlen)
899 		return ret;
900 
901 	return ret + (skbs - msk->skb_tx_cache.qlen) * SKB_TRUESIZE(MAX_TCP_HEADER);
902 }
903 
904 static void __mptcp_wmem_reserve(struct sock *sk, int size)
905 {
906 	int amount = mptcp_wmem_with_overhead(sk, size);
907 	struct mptcp_sock *msk = mptcp_sk(sk);
908 
909 	WARN_ON_ONCE(msk->wmem_reserved);
910 	if (WARN_ON_ONCE(amount < 0))
911 		amount = 0;
912 
913 	if (amount <= sk->sk_forward_alloc)
914 		goto reserve;
915 
916 	/* under memory pressure try to reserve at most a single page
917 	 * otherwise try to reserve the full estimate and fallback
918 	 * to a single page before entering the error path
919 	 */
920 	if ((tcp_under_memory_pressure(sk) && amount > PAGE_SIZE) ||
921 	    !sk_wmem_schedule(sk, amount)) {
922 		if (amount <= PAGE_SIZE)
923 			goto nomem;
924 
925 		amount = PAGE_SIZE;
926 		if (!sk_wmem_schedule(sk, amount))
927 			goto nomem;
928 	}
929 
930 reserve:
931 	msk->wmem_reserved = amount;
932 	sk->sk_forward_alloc -= amount;
933 	return;
934 
935 nomem:
936 	/* we will wait for memory on next allocation */
937 	msk->wmem_reserved = -1;
938 }
939 
940 static void __mptcp_update_wmem(struct sock *sk)
941 {
942 	struct mptcp_sock *msk = mptcp_sk(sk);
943 
944 	if (!msk->wmem_reserved)
945 		return;
946 
947 	if (msk->wmem_reserved < 0)
948 		msk->wmem_reserved = 0;
949 	if (msk->wmem_reserved > 0) {
950 		sk->sk_forward_alloc += msk->wmem_reserved;
951 		msk->wmem_reserved = 0;
952 	}
953 }
954 
955 static bool mptcp_wmem_alloc(struct sock *sk, int size)
956 {
957 	struct mptcp_sock *msk = mptcp_sk(sk);
958 
959 	/* check for pre-existing error condition */
960 	if (msk->wmem_reserved < 0)
961 		return false;
962 
963 	if (msk->wmem_reserved >= size)
964 		goto account;
965 
966 	mptcp_data_lock(sk);
967 	if (!sk_wmem_schedule(sk, size)) {
968 		mptcp_data_unlock(sk);
969 		return false;
970 	}
971 
972 	sk->sk_forward_alloc -= size;
973 	msk->wmem_reserved += size;
974 	mptcp_data_unlock(sk);
975 
976 account:
977 	msk->wmem_reserved -= size;
978 	return true;
979 }
980 
981 static void mptcp_wmem_uncharge(struct sock *sk, int size)
982 {
983 	struct mptcp_sock *msk = mptcp_sk(sk);
984 
985 	if (msk->wmem_reserved < 0)
986 		msk->wmem_reserved = 0;
987 	msk->wmem_reserved += size;
988 }
989 
990 static void mptcp_mem_reclaim_partial(struct sock *sk)
991 {
992 	struct mptcp_sock *msk = mptcp_sk(sk);
993 
994 	/* if we are experiencing a transint allocation error,
995 	 * the forward allocation memory has been already
996 	 * released
997 	 */
998 	if (msk->wmem_reserved < 0)
999 		return;
1000 
1001 	mptcp_data_lock(sk);
1002 	sk->sk_forward_alloc += msk->wmem_reserved;
1003 	sk_mem_reclaim_partial(sk);
1004 	msk->wmem_reserved = sk->sk_forward_alloc;
1005 	sk->sk_forward_alloc = 0;
1006 	mptcp_data_unlock(sk);
1007 }
1008 
1009 static void dfrag_uncharge(struct sock *sk, int len)
1010 {
1011 	sk_mem_uncharge(sk, len);
1012 	sk_wmem_queued_add(sk, -len);
1013 }
1014 
1015 static void dfrag_clear(struct sock *sk, struct mptcp_data_frag *dfrag)
1016 {
1017 	int len = dfrag->data_len + dfrag->overhead;
1018 
1019 	list_del(&dfrag->list);
1020 	dfrag_uncharge(sk, len);
1021 	put_page(dfrag->page);
1022 }
1023 
1024 static void __mptcp_clean_una(struct sock *sk)
1025 {
1026 	struct mptcp_sock *msk = mptcp_sk(sk);
1027 	struct mptcp_data_frag *dtmp, *dfrag;
1028 	bool cleaned = false;
1029 	u64 snd_una;
1030 
1031 	/* on fallback we just need to ignore snd_una, as this is really
1032 	 * plain TCP
1033 	 */
1034 	if (__mptcp_check_fallback(msk))
1035 		msk->snd_una = READ_ONCE(msk->snd_nxt);
1036 
1037 	snd_una = msk->snd_una;
1038 	list_for_each_entry_safe(dfrag, dtmp, &msk->rtx_queue, list) {
1039 		if (after64(dfrag->data_seq + dfrag->data_len, snd_una))
1040 			break;
1041 
1042 		if (WARN_ON_ONCE(dfrag == msk->first_pending))
1043 			break;
1044 		dfrag_clear(sk, dfrag);
1045 		cleaned = true;
1046 	}
1047 
1048 	dfrag = mptcp_rtx_head(sk);
1049 	if (dfrag && after64(snd_una, dfrag->data_seq)) {
1050 		u64 delta = snd_una - dfrag->data_seq;
1051 
1052 		if (WARN_ON_ONCE(delta > dfrag->already_sent))
1053 			goto out;
1054 
1055 		dfrag->data_seq += delta;
1056 		dfrag->offset += delta;
1057 		dfrag->data_len -= delta;
1058 		dfrag->already_sent -= delta;
1059 
1060 		dfrag_uncharge(sk, delta);
1061 		cleaned = true;
1062 	}
1063 
1064 out:
1065 	if (cleaned) {
1066 		if (tcp_under_memory_pressure(sk)) {
1067 			__mptcp_update_wmem(sk);
1068 			sk_mem_reclaim_partial(sk);
1069 		}
1070 	}
1071 
1072 	if (snd_una == READ_ONCE(msk->snd_nxt)) {
1073 		if (msk->timer_ival && !mptcp_data_fin_enabled(msk))
1074 			mptcp_stop_timer(sk);
1075 	} else {
1076 		mptcp_reset_timer(sk);
1077 	}
1078 }
1079 
1080 static void __mptcp_clean_una_wakeup(struct sock *sk)
1081 {
1082 	__mptcp_clean_una(sk);
1083 	mptcp_write_space(sk);
1084 }
1085 
1086 static void mptcp_enter_memory_pressure(struct sock *sk)
1087 {
1088 	struct mptcp_subflow_context *subflow;
1089 	struct mptcp_sock *msk = mptcp_sk(sk);
1090 	bool first = true;
1091 
1092 	sk_stream_moderate_sndbuf(sk);
1093 	mptcp_for_each_subflow(msk, subflow) {
1094 		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
1095 
1096 		if (first)
1097 			tcp_enter_memory_pressure(ssk);
1098 		sk_stream_moderate_sndbuf(ssk);
1099 		first = false;
1100 	}
1101 }
1102 
1103 /* ensure we get enough memory for the frag hdr, beyond some minimal amount of
1104  * data
1105  */
1106 static bool mptcp_page_frag_refill(struct sock *sk, struct page_frag *pfrag)
1107 {
1108 	if (likely(skb_page_frag_refill(32U + sizeof(struct mptcp_data_frag),
1109 					pfrag, sk->sk_allocation)))
1110 		return true;
1111 
1112 	mptcp_enter_memory_pressure(sk);
1113 	return false;
1114 }
1115 
1116 static struct mptcp_data_frag *
1117 mptcp_carve_data_frag(const struct mptcp_sock *msk, struct page_frag *pfrag,
1118 		      int orig_offset)
1119 {
1120 	int offset = ALIGN(orig_offset, sizeof(long));
1121 	struct mptcp_data_frag *dfrag;
1122 
1123 	dfrag = (struct mptcp_data_frag *)(page_to_virt(pfrag->page) + offset);
1124 	dfrag->data_len = 0;
1125 	dfrag->data_seq = msk->write_seq;
1126 	dfrag->overhead = offset - orig_offset + sizeof(struct mptcp_data_frag);
1127 	dfrag->offset = offset + sizeof(struct mptcp_data_frag);
1128 	dfrag->already_sent = 0;
1129 	dfrag->page = pfrag->page;
1130 
1131 	return dfrag;
1132 }
1133 
1134 struct mptcp_sendmsg_info {
1135 	int mss_now;
1136 	int size_goal;
1137 	u16 limit;
1138 	u16 sent;
1139 	unsigned int flags;
1140 };
1141 
1142 static int mptcp_check_allowed_size(struct mptcp_sock *msk, u64 data_seq,
1143 				    int avail_size)
1144 {
1145 	u64 window_end = mptcp_wnd_end(msk);
1146 
1147 	if (__mptcp_check_fallback(msk))
1148 		return avail_size;
1149 
1150 	if (!before64(data_seq + avail_size, window_end)) {
1151 		u64 allowed_size = window_end - data_seq;
1152 
1153 		return min_t(unsigned int, allowed_size, avail_size);
1154 	}
1155 
1156 	return avail_size;
1157 }
1158 
1159 static bool __mptcp_add_ext(struct sk_buff *skb, gfp_t gfp)
1160 {
1161 	struct skb_ext *mpext = __skb_ext_alloc(gfp);
1162 
1163 	if (!mpext)
1164 		return false;
1165 	__skb_ext_set(skb, SKB_EXT_MPTCP, mpext);
1166 	return true;
1167 }
1168 
1169 static struct sk_buff *__mptcp_do_alloc_tx_skb(struct sock *sk, gfp_t gfp)
1170 {
1171 	struct sk_buff *skb;
1172 
1173 	skb = alloc_skb_fclone(MAX_TCP_HEADER, gfp);
1174 	if (likely(skb)) {
1175 		if (likely(__mptcp_add_ext(skb, gfp))) {
1176 			skb_reserve(skb, MAX_TCP_HEADER);
1177 			skb->reserved_tailroom = skb->end - skb->tail;
1178 			return skb;
1179 		}
1180 		__kfree_skb(skb);
1181 	} else {
1182 		mptcp_enter_memory_pressure(sk);
1183 	}
1184 	return NULL;
1185 }
1186 
1187 static bool mptcp_tx_cache_refill(struct sock *sk, int size,
1188 				  struct sk_buff_head *skbs, int *total_ts)
1189 {
1190 	struct mptcp_sock *msk = mptcp_sk(sk);
1191 	struct sk_buff *skb;
1192 	int space_needed;
1193 
1194 	if (unlikely(tcp_under_memory_pressure(sk))) {
1195 		mptcp_mem_reclaim_partial(sk);
1196 
1197 		/* under pressure pre-allocate at most a single skb */
1198 		if (msk->skb_tx_cache.qlen)
1199 			return true;
1200 		space_needed = msk->size_goal_cache;
1201 	} else {
1202 		space_needed = msk->tx_pending_data + size -
1203 			       msk->skb_tx_cache.qlen * msk->size_goal_cache;
1204 	}
1205 
1206 	while (space_needed > 0) {
1207 		skb = __mptcp_do_alloc_tx_skb(sk, sk->sk_allocation);
1208 		if (unlikely(!skb)) {
1209 			/* under memory pressure, try to pass the caller a
1210 			 * single skb to allow forward progress
1211 			 */
1212 			while (skbs->qlen > 1) {
1213 				skb = __skb_dequeue_tail(skbs);
1214 				*total_ts -= skb->truesize;
1215 				__kfree_skb(skb);
1216 			}
1217 			return skbs->qlen > 0;
1218 		}
1219 
1220 		*total_ts += skb->truesize;
1221 		__skb_queue_tail(skbs, skb);
1222 		space_needed -= msk->size_goal_cache;
1223 	}
1224 	return true;
1225 }
1226 
1227 static bool __mptcp_alloc_tx_skb(struct sock *sk, struct sock *ssk, gfp_t gfp)
1228 {
1229 	struct mptcp_sock *msk = mptcp_sk(sk);
1230 	struct sk_buff *skb;
1231 
1232 	if (ssk->sk_tx_skb_cache) {
1233 		skb = ssk->sk_tx_skb_cache;
1234 		if (unlikely(!skb_ext_find(skb, SKB_EXT_MPTCP) &&
1235 			     !__mptcp_add_ext(skb, gfp)))
1236 			return false;
1237 		return true;
1238 	}
1239 
1240 	skb = skb_peek(&msk->skb_tx_cache);
1241 	if (skb) {
1242 		if (likely(sk_wmem_schedule(ssk, skb->truesize))) {
1243 			skb = __skb_dequeue(&msk->skb_tx_cache);
1244 			if (WARN_ON_ONCE(!skb))
1245 				return false;
1246 
1247 			mptcp_wmem_uncharge(sk, skb->truesize);
1248 			ssk->sk_tx_skb_cache = skb;
1249 			return true;
1250 		}
1251 
1252 		/* over memory limit, no point to try to allocate a new skb */
1253 		return false;
1254 	}
1255 
1256 	skb = __mptcp_do_alloc_tx_skb(sk, gfp);
1257 	if (!skb)
1258 		return false;
1259 
1260 	if (likely(sk_wmem_schedule(ssk, skb->truesize))) {
1261 		ssk->sk_tx_skb_cache = skb;
1262 		return true;
1263 	}
1264 	kfree_skb(skb);
1265 	return false;
1266 }
1267 
1268 static bool mptcp_must_reclaim_memory(struct sock *sk, struct sock *ssk)
1269 {
1270 	return !ssk->sk_tx_skb_cache &&
1271 	       !skb_peek(&mptcp_sk(sk)->skb_tx_cache) &&
1272 	       tcp_under_memory_pressure(sk);
1273 }
1274 
1275 static bool mptcp_alloc_tx_skb(struct sock *sk, struct sock *ssk)
1276 {
1277 	if (unlikely(mptcp_must_reclaim_memory(sk, ssk)))
1278 		mptcp_mem_reclaim_partial(sk);
1279 	return __mptcp_alloc_tx_skb(sk, ssk, sk->sk_allocation);
1280 }
1281 
1282 static int mptcp_sendmsg_frag(struct sock *sk, struct sock *ssk,
1283 			      struct mptcp_data_frag *dfrag,
1284 			      struct mptcp_sendmsg_info *info)
1285 {
1286 	u64 data_seq = dfrag->data_seq + info->sent;
1287 	struct mptcp_sock *msk = mptcp_sk(sk);
1288 	bool zero_window_probe = false;
1289 	struct mptcp_ext *mpext = NULL;
1290 	struct sk_buff *skb, *tail;
1291 	bool can_collapse = false;
1292 	int size_bias = 0;
1293 	int avail_size;
1294 	size_t ret = 0;
1295 
1296 	pr_debug("msk=%p ssk=%p sending dfrag at seq=%llu len=%u already sent=%u",
1297 		 msk, ssk, dfrag->data_seq, dfrag->data_len, info->sent);
1298 
1299 	/* compute send limit */
1300 	info->mss_now = tcp_send_mss(ssk, &info->size_goal, info->flags);
1301 	avail_size = info->size_goal;
1302 	msk->size_goal_cache = info->size_goal;
1303 	skb = tcp_write_queue_tail(ssk);
1304 	if (skb) {
1305 		/* Limit the write to the size available in the
1306 		 * current skb, if any, so that we create at most a new skb.
1307 		 * Explicitly tells TCP internals to avoid collapsing on later
1308 		 * queue management operation, to avoid breaking the ext <->
1309 		 * SSN association set here
1310 		 */
1311 		mpext = skb_ext_find(skb, SKB_EXT_MPTCP);
1312 		can_collapse = (info->size_goal - skb->len > 0) &&
1313 			 mptcp_skb_can_collapse_to(data_seq, skb, mpext);
1314 		if (!can_collapse) {
1315 			TCP_SKB_CB(skb)->eor = 1;
1316 		} else {
1317 			size_bias = skb->len;
1318 			avail_size = info->size_goal - skb->len;
1319 		}
1320 	}
1321 
1322 	/* Zero window and all data acked? Probe. */
1323 	avail_size = mptcp_check_allowed_size(msk, data_seq, avail_size);
1324 	if (avail_size == 0) {
1325 		u64 snd_una = READ_ONCE(msk->snd_una);
1326 
1327 		if (skb || snd_una != msk->snd_nxt)
1328 			return 0;
1329 		zero_window_probe = true;
1330 		data_seq = snd_una - 1;
1331 		avail_size = 1;
1332 	}
1333 
1334 	if (WARN_ON_ONCE(info->sent > info->limit ||
1335 			 info->limit > dfrag->data_len))
1336 		return 0;
1337 
1338 	ret = info->limit - info->sent;
1339 	tail = tcp_build_frag(ssk, avail_size + size_bias, info->flags,
1340 			      dfrag->page, dfrag->offset + info->sent, &ret);
1341 	if (!tail) {
1342 		tcp_remove_empty_skb(sk, tcp_write_queue_tail(ssk));
1343 		return -ENOMEM;
1344 	}
1345 
1346 	/* if the tail skb is still the cached one, collapsing really happened.
1347 	 */
1348 	if (skb == tail) {
1349 		TCP_SKB_CB(tail)->tcp_flags &= ~TCPHDR_PSH;
1350 		mpext->data_len += ret;
1351 		WARN_ON_ONCE(!can_collapse);
1352 		WARN_ON_ONCE(zero_window_probe);
1353 		goto out;
1354 	}
1355 
1356 	mpext = skb_ext_find(tail, SKB_EXT_MPTCP);
1357 	if (WARN_ON_ONCE(!mpext)) {
1358 		/* should never reach here, stream corrupted */
1359 		return -EINVAL;
1360 	}
1361 
1362 	memset(mpext, 0, sizeof(*mpext));
1363 	mpext->data_seq = data_seq;
1364 	mpext->subflow_seq = mptcp_subflow_ctx(ssk)->rel_write_seq;
1365 	mpext->data_len = ret;
1366 	mpext->use_map = 1;
1367 	mpext->dsn64 = 1;
1368 
1369 	pr_debug("data_seq=%llu subflow_seq=%u data_len=%u dsn64=%d",
1370 		 mpext->data_seq, mpext->subflow_seq, mpext->data_len,
1371 		 mpext->dsn64);
1372 
1373 	if (zero_window_probe) {
1374 		mptcp_subflow_ctx(ssk)->rel_write_seq += ret;
1375 		mpext->frozen = 1;
1376 		ret = 0;
1377 		tcp_push_pending_frames(ssk);
1378 	}
1379 out:
1380 	mptcp_subflow_ctx(ssk)->rel_write_seq += ret;
1381 	return ret;
1382 }
1383 
1384 #define MPTCP_SEND_BURST_SIZE		((1 << 16) - \
1385 					 sizeof(struct tcphdr) - \
1386 					 MAX_TCP_OPTION_SPACE - \
1387 					 sizeof(struct ipv6hdr) - \
1388 					 sizeof(struct frag_hdr))
1389 
1390 struct subflow_send_info {
1391 	struct sock *ssk;
1392 	u64 ratio;
1393 };
1394 
1395 static struct sock *mptcp_subflow_get_send(struct mptcp_sock *msk)
1396 {
1397 	struct subflow_send_info send_info[2];
1398 	struct mptcp_subflow_context *subflow;
1399 	int i, nr_active = 0;
1400 	struct sock *ssk;
1401 	u64 ratio;
1402 	u32 pace;
1403 
1404 	sock_owned_by_me((struct sock *)msk);
1405 
1406 	if (__mptcp_check_fallback(msk)) {
1407 		if (!msk->first)
1408 			return NULL;
1409 		return sk_stream_memory_free(msk->first) ? msk->first : NULL;
1410 	}
1411 
1412 	/* re-use last subflow, if the burst allow that */
1413 	if (msk->last_snd && msk->snd_burst > 0 &&
1414 	    sk_stream_memory_free(msk->last_snd) &&
1415 	    mptcp_subflow_active(mptcp_subflow_ctx(msk->last_snd)))
1416 		return msk->last_snd;
1417 
1418 	/* pick the subflow with the lower wmem/wspace ratio */
1419 	for (i = 0; i < 2; ++i) {
1420 		send_info[i].ssk = NULL;
1421 		send_info[i].ratio = -1;
1422 	}
1423 	mptcp_for_each_subflow(msk, subflow) {
1424 		trace_mptcp_subflow_get_send(subflow);
1425 		ssk =  mptcp_subflow_tcp_sock(subflow);
1426 		if (!mptcp_subflow_active(subflow))
1427 			continue;
1428 
1429 		nr_active += !subflow->backup;
1430 		if (!sk_stream_memory_free(subflow->tcp_sock) || !tcp_sk(ssk)->snd_wnd)
1431 			continue;
1432 
1433 		pace = READ_ONCE(ssk->sk_pacing_rate);
1434 		if (!pace)
1435 			continue;
1436 
1437 		ratio = div_u64((u64)READ_ONCE(ssk->sk_wmem_queued) << 32,
1438 				pace);
1439 		if (ratio < send_info[subflow->backup].ratio) {
1440 			send_info[subflow->backup].ssk = ssk;
1441 			send_info[subflow->backup].ratio = ratio;
1442 		}
1443 	}
1444 
1445 	/* pick the best backup if no other subflow is active */
1446 	if (!nr_active)
1447 		send_info[0].ssk = send_info[1].ssk;
1448 
1449 	if (send_info[0].ssk) {
1450 		msk->last_snd = send_info[0].ssk;
1451 		msk->snd_burst = min_t(int, MPTCP_SEND_BURST_SIZE,
1452 				       tcp_sk(msk->last_snd)->snd_wnd);
1453 		return msk->last_snd;
1454 	}
1455 
1456 	return NULL;
1457 }
1458 
1459 static void mptcp_push_release(struct sock *sk, struct sock *ssk,
1460 			       struct mptcp_sendmsg_info *info)
1461 {
1462 	mptcp_set_timeout(sk, ssk);
1463 	tcp_push(ssk, 0, info->mss_now, tcp_sk(ssk)->nonagle, info->size_goal);
1464 	release_sock(ssk);
1465 }
1466 
1467 static void __mptcp_push_pending(struct sock *sk, unsigned int flags)
1468 {
1469 	struct sock *prev_ssk = NULL, *ssk = NULL;
1470 	struct mptcp_sock *msk = mptcp_sk(sk);
1471 	struct mptcp_sendmsg_info info = {
1472 				.flags = flags,
1473 	};
1474 	struct mptcp_data_frag *dfrag;
1475 	int len, copied = 0;
1476 
1477 	while ((dfrag = mptcp_send_head(sk))) {
1478 		info.sent = dfrag->already_sent;
1479 		info.limit = dfrag->data_len;
1480 		len = dfrag->data_len - dfrag->already_sent;
1481 		while (len > 0) {
1482 			int ret = 0;
1483 
1484 			prev_ssk = ssk;
1485 			mptcp_flush_join_list(msk);
1486 			ssk = mptcp_subflow_get_send(msk);
1487 
1488 			/* try to keep the subflow socket lock across
1489 			 * consecutive xmit on the same socket
1490 			 */
1491 			if (ssk != prev_ssk && prev_ssk)
1492 				mptcp_push_release(sk, prev_ssk, &info);
1493 			if (!ssk)
1494 				goto out;
1495 
1496 			if (ssk != prev_ssk || !prev_ssk)
1497 				lock_sock(ssk);
1498 
1499 			/* keep it simple and always provide a new skb for the
1500 			 * subflow, even if we will not use it when collapsing
1501 			 * on the pending one
1502 			 */
1503 			if (!mptcp_alloc_tx_skb(sk, ssk)) {
1504 				mptcp_push_release(sk, ssk, &info);
1505 				goto out;
1506 			}
1507 
1508 			ret = mptcp_sendmsg_frag(sk, ssk, dfrag, &info);
1509 			if (ret <= 0) {
1510 				mptcp_push_release(sk, ssk, &info);
1511 				goto out;
1512 			}
1513 
1514 			info.sent += ret;
1515 			dfrag->already_sent += ret;
1516 			msk->snd_nxt += ret;
1517 			msk->snd_burst -= ret;
1518 			msk->tx_pending_data -= ret;
1519 			copied += ret;
1520 			len -= ret;
1521 		}
1522 		WRITE_ONCE(msk->first_pending, mptcp_send_next(sk));
1523 	}
1524 
1525 	/* at this point we held the socket lock for the last subflow we used */
1526 	if (ssk)
1527 		mptcp_push_release(sk, ssk, &info);
1528 
1529 out:
1530 	if (copied) {
1531 		/* start the timer, if it's not pending */
1532 		if (!mptcp_timer_pending(sk))
1533 			mptcp_reset_timer(sk);
1534 		__mptcp_check_send_data_fin(sk);
1535 	}
1536 }
1537 
1538 static void __mptcp_subflow_push_pending(struct sock *sk, struct sock *ssk)
1539 {
1540 	struct mptcp_sock *msk = mptcp_sk(sk);
1541 	struct mptcp_sendmsg_info info;
1542 	struct mptcp_data_frag *dfrag;
1543 	struct sock *xmit_ssk;
1544 	int len, copied = 0;
1545 	bool first = true;
1546 
1547 	info.flags = 0;
1548 	while ((dfrag = mptcp_send_head(sk))) {
1549 		info.sent = dfrag->already_sent;
1550 		info.limit = dfrag->data_len;
1551 		len = dfrag->data_len - dfrag->already_sent;
1552 		while (len > 0) {
1553 			int ret = 0;
1554 
1555 			/* the caller already invoked the packet scheduler,
1556 			 * check for a different subflow usage only after
1557 			 * spooling the first chunk of data
1558 			 */
1559 			xmit_ssk = first ? ssk : mptcp_subflow_get_send(mptcp_sk(sk));
1560 			if (!xmit_ssk)
1561 				goto out;
1562 			if (xmit_ssk != ssk) {
1563 				mptcp_subflow_delegate(mptcp_subflow_ctx(xmit_ssk));
1564 				goto out;
1565 			}
1566 
1567 			if (unlikely(mptcp_must_reclaim_memory(sk, ssk))) {
1568 				__mptcp_update_wmem(sk);
1569 				sk_mem_reclaim_partial(sk);
1570 			}
1571 			if (!__mptcp_alloc_tx_skb(sk, ssk, GFP_ATOMIC))
1572 				goto out;
1573 
1574 			ret = mptcp_sendmsg_frag(sk, ssk, dfrag, &info);
1575 			if (ret <= 0)
1576 				goto out;
1577 
1578 			info.sent += ret;
1579 			dfrag->already_sent += ret;
1580 			msk->snd_nxt += ret;
1581 			msk->snd_burst -= ret;
1582 			msk->tx_pending_data -= ret;
1583 			copied += ret;
1584 			len -= ret;
1585 			first = false;
1586 		}
1587 		WRITE_ONCE(msk->first_pending, mptcp_send_next(sk));
1588 	}
1589 
1590 out:
1591 	/* __mptcp_alloc_tx_skb could have released some wmem and we are
1592 	 * not going to flush it via release_sock()
1593 	 */
1594 	__mptcp_update_wmem(sk);
1595 	if (copied) {
1596 		mptcp_set_timeout(sk, ssk);
1597 		tcp_push(ssk, 0, info.mss_now, tcp_sk(ssk)->nonagle,
1598 			 info.size_goal);
1599 		if (!mptcp_timer_pending(sk))
1600 			mptcp_reset_timer(sk);
1601 
1602 		if (msk->snd_data_fin_enable &&
1603 		    msk->snd_nxt + 1 == msk->write_seq)
1604 			mptcp_schedule_work(sk);
1605 	}
1606 }
1607 
1608 static void mptcp_set_nospace(struct sock *sk)
1609 {
1610 	/* enable autotune */
1611 	set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1612 
1613 	/* will be cleared on avail space */
1614 	set_bit(MPTCP_NOSPACE, &mptcp_sk(sk)->flags);
1615 }
1616 
1617 static int mptcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1618 {
1619 	struct mptcp_sock *msk = mptcp_sk(sk);
1620 	struct page_frag *pfrag;
1621 	size_t copied = 0;
1622 	int ret = 0;
1623 	long timeo;
1624 
1625 	/* we don't support FASTOPEN yet */
1626 	if (msg->msg_flags & MSG_FASTOPEN)
1627 		return -EOPNOTSUPP;
1628 
1629 	/* silently ignore everything else */
1630 	msg->msg_flags &= MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL;
1631 
1632 	mptcp_lock_sock(sk, __mptcp_wmem_reserve(sk, min_t(size_t, 1 << 20, len)));
1633 
1634 	timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1635 
1636 	if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) {
1637 		ret = sk_stream_wait_connect(sk, &timeo);
1638 		if (ret)
1639 			goto out;
1640 	}
1641 
1642 	pfrag = sk_page_frag(sk);
1643 
1644 	while (msg_data_left(msg)) {
1645 		int total_ts, frag_truesize = 0;
1646 		struct mptcp_data_frag *dfrag;
1647 		struct sk_buff_head skbs;
1648 		bool dfrag_collapsed;
1649 		size_t psize, offset;
1650 
1651 		if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) {
1652 			ret = -EPIPE;
1653 			goto out;
1654 		}
1655 
1656 		/* reuse tail pfrag, if possible, or carve a new one from the
1657 		 * page allocator
1658 		 */
1659 		dfrag = mptcp_pending_tail(sk);
1660 		dfrag_collapsed = mptcp_frag_can_collapse_to(msk, pfrag, dfrag);
1661 		if (!dfrag_collapsed) {
1662 			if (!sk_stream_memory_free(sk))
1663 				goto wait_for_memory;
1664 
1665 			if (!mptcp_page_frag_refill(sk, pfrag))
1666 				goto wait_for_memory;
1667 
1668 			dfrag = mptcp_carve_data_frag(msk, pfrag, pfrag->offset);
1669 			frag_truesize = dfrag->overhead;
1670 		}
1671 
1672 		/* we do not bound vs wspace, to allow a single packet.
1673 		 * memory accounting will prevent execessive memory usage
1674 		 * anyway
1675 		 */
1676 		offset = dfrag->offset + dfrag->data_len;
1677 		psize = pfrag->size - offset;
1678 		psize = min_t(size_t, psize, msg_data_left(msg));
1679 		total_ts = psize + frag_truesize;
1680 		__skb_queue_head_init(&skbs);
1681 		if (!mptcp_tx_cache_refill(sk, psize, &skbs, &total_ts))
1682 			goto wait_for_memory;
1683 
1684 		if (!mptcp_wmem_alloc(sk, total_ts)) {
1685 			__skb_queue_purge(&skbs);
1686 			goto wait_for_memory;
1687 		}
1688 
1689 		skb_queue_splice_tail(&skbs, &msk->skb_tx_cache);
1690 		if (copy_page_from_iter(dfrag->page, offset, psize,
1691 					&msg->msg_iter) != psize) {
1692 			mptcp_wmem_uncharge(sk, psize + frag_truesize);
1693 			ret = -EFAULT;
1694 			goto out;
1695 		}
1696 
1697 		/* data successfully copied into the write queue */
1698 		copied += psize;
1699 		dfrag->data_len += psize;
1700 		frag_truesize += psize;
1701 		pfrag->offset += frag_truesize;
1702 		WRITE_ONCE(msk->write_seq, msk->write_seq + psize);
1703 		msk->tx_pending_data += psize;
1704 
1705 		/* charge data on mptcp pending queue to the msk socket
1706 		 * Note: we charge such data both to sk and ssk
1707 		 */
1708 		sk_wmem_queued_add(sk, frag_truesize);
1709 		if (!dfrag_collapsed) {
1710 			get_page(dfrag->page);
1711 			list_add_tail(&dfrag->list, &msk->rtx_queue);
1712 			if (!msk->first_pending)
1713 				WRITE_ONCE(msk->first_pending, dfrag);
1714 		}
1715 		pr_debug("msk=%p dfrag at seq=%llu len=%u sent=%u new=%d", msk,
1716 			 dfrag->data_seq, dfrag->data_len, dfrag->already_sent,
1717 			 !dfrag_collapsed);
1718 
1719 		continue;
1720 
1721 wait_for_memory:
1722 		mptcp_set_nospace(sk);
1723 		__mptcp_push_pending(sk, msg->msg_flags);
1724 		ret = sk_stream_wait_memory(sk, &timeo);
1725 		if (ret)
1726 			goto out;
1727 	}
1728 
1729 	if (copied)
1730 		__mptcp_push_pending(sk, msg->msg_flags);
1731 
1732 out:
1733 	release_sock(sk);
1734 	return copied ? : ret;
1735 }
1736 
1737 static void mptcp_wait_data(struct sock *sk, long *timeo)
1738 {
1739 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1740 	struct mptcp_sock *msk = mptcp_sk(sk);
1741 
1742 	add_wait_queue(sk_sleep(sk), &wait);
1743 	sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1744 
1745 	sk_wait_event(sk, timeo,
1746 		      test_and_clear_bit(MPTCP_DATA_READY, &msk->flags), &wait);
1747 
1748 	sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1749 	remove_wait_queue(sk_sleep(sk), &wait);
1750 }
1751 
1752 static int __mptcp_recvmsg_mskq(struct mptcp_sock *msk,
1753 				struct msghdr *msg,
1754 				size_t len, int flags)
1755 {
1756 	struct sk_buff *skb, *tmp;
1757 	int copied = 0;
1758 
1759 	skb_queue_walk_safe(&msk->receive_queue, skb, tmp) {
1760 		u32 offset = MPTCP_SKB_CB(skb)->offset;
1761 		u32 data_len = skb->len - offset;
1762 		u32 count = min_t(size_t, len - copied, data_len);
1763 		int err;
1764 
1765 		if (!(flags & MSG_TRUNC)) {
1766 			err = skb_copy_datagram_msg(skb, offset, msg, count);
1767 			if (unlikely(err < 0)) {
1768 				if (!copied)
1769 					return err;
1770 				break;
1771 			}
1772 		}
1773 
1774 		copied += count;
1775 
1776 		if (count < data_len) {
1777 			if (!(flags & MSG_PEEK))
1778 				MPTCP_SKB_CB(skb)->offset += count;
1779 			break;
1780 		}
1781 
1782 		if (!(flags & MSG_PEEK)) {
1783 			/* we will bulk release the skb memory later */
1784 			skb->destructor = NULL;
1785 			msk->rmem_released += skb->truesize;
1786 			__skb_unlink(skb, &msk->receive_queue);
1787 			__kfree_skb(skb);
1788 		}
1789 
1790 		if (copied >= len)
1791 			break;
1792 	}
1793 
1794 	return copied;
1795 }
1796 
1797 /* receive buffer autotuning.  See tcp_rcv_space_adjust for more information.
1798  *
1799  * Only difference: Use highest rtt estimate of the subflows in use.
1800  */
1801 static void mptcp_rcv_space_adjust(struct mptcp_sock *msk, int copied)
1802 {
1803 	struct mptcp_subflow_context *subflow;
1804 	struct sock *sk = (struct sock *)msk;
1805 	u32 time, advmss = 1;
1806 	u64 rtt_us, mstamp;
1807 
1808 	sock_owned_by_me(sk);
1809 
1810 	if (copied <= 0)
1811 		return;
1812 
1813 	msk->rcvq_space.copied += copied;
1814 
1815 	mstamp = div_u64(tcp_clock_ns(), NSEC_PER_USEC);
1816 	time = tcp_stamp_us_delta(mstamp, msk->rcvq_space.time);
1817 
1818 	rtt_us = msk->rcvq_space.rtt_us;
1819 	if (rtt_us && time < (rtt_us >> 3))
1820 		return;
1821 
1822 	rtt_us = 0;
1823 	mptcp_for_each_subflow(msk, subflow) {
1824 		const struct tcp_sock *tp;
1825 		u64 sf_rtt_us;
1826 		u32 sf_advmss;
1827 
1828 		tp = tcp_sk(mptcp_subflow_tcp_sock(subflow));
1829 
1830 		sf_rtt_us = READ_ONCE(tp->rcv_rtt_est.rtt_us);
1831 		sf_advmss = READ_ONCE(tp->advmss);
1832 
1833 		rtt_us = max(sf_rtt_us, rtt_us);
1834 		advmss = max(sf_advmss, advmss);
1835 	}
1836 
1837 	msk->rcvq_space.rtt_us = rtt_us;
1838 	if (time < (rtt_us >> 3) || rtt_us == 0)
1839 		return;
1840 
1841 	if (msk->rcvq_space.copied <= msk->rcvq_space.space)
1842 		goto new_measure;
1843 
1844 	if (sock_net(sk)->ipv4.sysctl_tcp_moderate_rcvbuf &&
1845 	    !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
1846 		int rcvmem, rcvbuf;
1847 		u64 rcvwin, grow;
1848 
1849 		rcvwin = ((u64)msk->rcvq_space.copied << 1) + 16 * advmss;
1850 
1851 		grow = rcvwin * (msk->rcvq_space.copied - msk->rcvq_space.space);
1852 
1853 		do_div(grow, msk->rcvq_space.space);
1854 		rcvwin += (grow << 1);
1855 
1856 		rcvmem = SKB_TRUESIZE(advmss + MAX_TCP_HEADER);
1857 		while (tcp_win_from_space(sk, rcvmem) < advmss)
1858 			rcvmem += 128;
1859 
1860 		do_div(rcvwin, advmss);
1861 		rcvbuf = min_t(u64, rcvwin * rcvmem,
1862 			       sock_net(sk)->ipv4.sysctl_tcp_rmem[2]);
1863 
1864 		if (rcvbuf > sk->sk_rcvbuf) {
1865 			u32 window_clamp;
1866 
1867 			window_clamp = tcp_win_from_space(sk, rcvbuf);
1868 			WRITE_ONCE(sk->sk_rcvbuf, rcvbuf);
1869 
1870 			/* Make subflows follow along.  If we do not do this, we
1871 			 * get drops at subflow level if skbs can't be moved to
1872 			 * the mptcp rx queue fast enough (announced rcv_win can
1873 			 * exceed ssk->sk_rcvbuf).
1874 			 */
1875 			mptcp_for_each_subflow(msk, subflow) {
1876 				struct sock *ssk;
1877 				bool slow;
1878 
1879 				ssk = mptcp_subflow_tcp_sock(subflow);
1880 				slow = lock_sock_fast(ssk);
1881 				WRITE_ONCE(ssk->sk_rcvbuf, rcvbuf);
1882 				tcp_sk(ssk)->window_clamp = window_clamp;
1883 				tcp_cleanup_rbuf(ssk, 1);
1884 				unlock_sock_fast(ssk, slow);
1885 			}
1886 		}
1887 	}
1888 
1889 	msk->rcvq_space.space = msk->rcvq_space.copied;
1890 new_measure:
1891 	msk->rcvq_space.copied = 0;
1892 	msk->rcvq_space.time = mstamp;
1893 }
1894 
1895 static void __mptcp_update_rmem(struct sock *sk)
1896 {
1897 	struct mptcp_sock *msk = mptcp_sk(sk);
1898 
1899 	if (!msk->rmem_released)
1900 		return;
1901 
1902 	atomic_sub(msk->rmem_released, &sk->sk_rmem_alloc);
1903 	sk_mem_uncharge(sk, msk->rmem_released);
1904 	msk->rmem_released = 0;
1905 }
1906 
1907 static void __mptcp_splice_receive_queue(struct sock *sk)
1908 {
1909 	struct mptcp_sock *msk = mptcp_sk(sk);
1910 
1911 	skb_queue_splice_tail_init(&sk->sk_receive_queue, &msk->receive_queue);
1912 }
1913 
1914 static bool __mptcp_move_skbs(struct mptcp_sock *msk)
1915 {
1916 	struct sock *sk = (struct sock *)msk;
1917 	unsigned int moved = 0;
1918 	bool ret, done;
1919 
1920 	mptcp_flush_join_list(msk);
1921 	do {
1922 		struct sock *ssk = mptcp_subflow_recv_lookup(msk);
1923 		bool slowpath;
1924 
1925 		/* we can have data pending in the subflows only if the msk
1926 		 * receive buffer was full at subflow_data_ready() time,
1927 		 * that is an unlikely slow path.
1928 		 */
1929 		if (likely(!ssk))
1930 			break;
1931 
1932 		slowpath = lock_sock_fast(ssk);
1933 		mptcp_data_lock(sk);
1934 		__mptcp_update_rmem(sk);
1935 		done = __mptcp_move_skbs_from_subflow(msk, ssk, &moved);
1936 		mptcp_data_unlock(sk);
1937 		tcp_cleanup_rbuf(ssk, moved);
1938 		unlock_sock_fast(ssk, slowpath);
1939 	} while (!done);
1940 
1941 	/* acquire the data lock only if some input data is pending */
1942 	ret = moved > 0;
1943 	if (!RB_EMPTY_ROOT(&msk->out_of_order_queue) ||
1944 	    !skb_queue_empty_lockless(&sk->sk_receive_queue)) {
1945 		mptcp_data_lock(sk);
1946 		__mptcp_update_rmem(sk);
1947 		ret |= __mptcp_ofo_queue(msk);
1948 		__mptcp_splice_receive_queue(sk);
1949 		mptcp_data_unlock(sk);
1950 		mptcp_cleanup_rbuf(msk);
1951 	}
1952 	if (ret)
1953 		mptcp_check_data_fin((struct sock *)msk);
1954 	return !skb_queue_empty(&msk->receive_queue);
1955 }
1956 
1957 static int mptcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
1958 			 int nonblock, int flags, int *addr_len)
1959 {
1960 	struct mptcp_sock *msk = mptcp_sk(sk);
1961 	int copied = 0;
1962 	int target;
1963 	long timeo;
1964 
1965 	/* MSG_ERRQUEUE is really a no-op till we support IP_RECVERR */
1966 	if (unlikely(flags & MSG_ERRQUEUE))
1967 		return inet_recv_error(sk, msg, len, addr_len);
1968 
1969 	mptcp_lock_sock(sk, __mptcp_splice_receive_queue(sk));
1970 	if (unlikely(sk->sk_state == TCP_LISTEN)) {
1971 		copied = -ENOTCONN;
1972 		goto out_err;
1973 	}
1974 
1975 	timeo = sock_rcvtimeo(sk, nonblock);
1976 
1977 	len = min_t(size_t, len, INT_MAX);
1978 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
1979 
1980 	while (copied < len) {
1981 		int bytes_read;
1982 
1983 		bytes_read = __mptcp_recvmsg_mskq(msk, msg, len - copied, flags);
1984 		if (unlikely(bytes_read < 0)) {
1985 			if (!copied)
1986 				copied = bytes_read;
1987 			goto out_err;
1988 		}
1989 
1990 		copied += bytes_read;
1991 
1992 		/* be sure to advertise window change */
1993 		mptcp_cleanup_rbuf(msk);
1994 
1995 		if (skb_queue_empty(&msk->receive_queue) && __mptcp_move_skbs(msk))
1996 			continue;
1997 
1998 		/* only the master socket status is relevant here. The exit
1999 		 * conditions mirror closely tcp_recvmsg()
2000 		 */
2001 		if (copied >= target)
2002 			break;
2003 
2004 		if (copied) {
2005 			if (sk->sk_err ||
2006 			    sk->sk_state == TCP_CLOSE ||
2007 			    (sk->sk_shutdown & RCV_SHUTDOWN) ||
2008 			    !timeo ||
2009 			    signal_pending(current))
2010 				break;
2011 		} else {
2012 			if (sk->sk_err) {
2013 				copied = sock_error(sk);
2014 				break;
2015 			}
2016 
2017 			if (test_and_clear_bit(MPTCP_WORK_EOF, &msk->flags))
2018 				mptcp_check_for_eof(msk);
2019 
2020 			if (sk->sk_shutdown & RCV_SHUTDOWN) {
2021 				/* race breaker: the shutdown could be after the
2022 				 * previous receive queue check
2023 				 */
2024 				if (__mptcp_move_skbs(msk))
2025 					continue;
2026 				break;
2027 			}
2028 
2029 			if (sk->sk_state == TCP_CLOSE) {
2030 				copied = -ENOTCONN;
2031 				break;
2032 			}
2033 
2034 			if (!timeo) {
2035 				copied = -EAGAIN;
2036 				break;
2037 			}
2038 
2039 			if (signal_pending(current)) {
2040 				copied = sock_intr_errno(timeo);
2041 				break;
2042 			}
2043 		}
2044 
2045 		pr_debug("block timeout %ld", timeo);
2046 		mptcp_wait_data(sk, &timeo);
2047 	}
2048 
2049 	if (skb_queue_empty_lockless(&sk->sk_receive_queue) &&
2050 	    skb_queue_empty(&msk->receive_queue)) {
2051 		/* entire backlog drained, clear DATA_READY. */
2052 		clear_bit(MPTCP_DATA_READY, &msk->flags);
2053 
2054 		/* .. race-breaker: ssk might have gotten new data
2055 		 * after last __mptcp_move_skbs() returned false.
2056 		 */
2057 		if (unlikely(__mptcp_move_skbs(msk)))
2058 			set_bit(MPTCP_DATA_READY, &msk->flags);
2059 	} else if (unlikely(!test_bit(MPTCP_DATA_READY, &msk->flags))) {
2060 		/* data to read but mptcp_wait_data() cleared DATA_READY */
2061 		set_bit(MPTCP_DATA_READY, &msk->flags);
2062 	}
2063 out_err:
2064 	pr_debug("msk=%p data_ready=%d rx queue empty=%d copied=%d",
2065 		 msk, test_bit(MPTCP_DATA_READY, &msk->flags),
2066 		 skb_queue_empty_lockless(&sk->sk_receive_queue), copied);
2067 	if (!(flags & MSG_PEEK))
2068 		mptcp_rcv_space_adjust(msk, copied);
2069 
2070 	release_sock(sk);
2071 	return copied;
2072 }
2073 
2074 static void mptcp_retransmit_timer(struct timer_list *t)
2075 {
2076 	struct inet_connection_sock *icsk = from_timer(icsk, t,
2077 						       icsk_retransmit_timer);
2078 	struct sock *sk = &icsk->icsk_inet.sk;
2079 	struct mptcp_sock *msk = mptcp_sk(sk);
2080 
2081 	bh_lock_sock(sk);
2082 	if (!sock_owned_by_user(sk)) {
2083 		/* we need a process context to retransmit */
2084 		if (!test_and_set_bit(MPTCP_WORK_RTX, &msk->flags))
2085 			mptcp_schedule_work(sk);
2086 	} else {
2087 		/* delegate our work to tcp_release_cb() */
2088 		set_bit(MPTCP_RETRANSMIT, &msk->flags);
2089 	}
2090 	bh_unlock_sock(sk);
2091 	sock_put(sk);
2092 }
2093 
2094 static void mptcp_timeout_timer(struct timer_list *t)
2095 {
2096 	struct sock *sk = from_timer(sk, t, sk_timer);
2097 
2098 	mptcp_schedule_work(sk);
2099 	sock_put(sk);
2100 }
2101 
2102 /* Find an idle subflow.  Return NULL if there is unacked data at tcp
2103  * level.
2104  *
2105  * A backup subflow is returned only if that is the only kind available.
2106  */
2107 static struct sock *mptcp_subflow_get_retrans(const struct mptcp_sock *msk)
2108 {
2109 	struct mptcp_subflow_context *subflow;
2110 	struct sock *backup = NULL;
2111 
2112 	sock_owned_by_me((const struct sock *)msk);
2113 
2114 	if (__mptcp_check_fallback(msk))
2115 		return NULL;
2116 
2117 	mptcp_for_each_subflow(msk, subflow) {
2118 		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
2119 
2120 		if (!mptcp_subflow_active(subflow))
2121 			continue;
2122 
2123 		/* still data outstanding at TCP level?  Don't retransmit. */
2124 		if (!tcp_write_queue_empty(ssk)) {
2125 			if (inet_csk(ssk)->icsk_ca_state >= TCP_CA_Loss)
2126 				continue;
2127 			return NULL;
2128 		}
2129 
2130 		if (subflow->backup) {
2131 			if (!backup)
2132 				backup = ssk;
2133 			continue;
2134 		}
2135 
2136 		return ssk;
2137 	}
2138 
2139 	return backup;
2140 }
2141 
2142 static void mptcp_dispose_initial_subflow(struct mptcp_sock *msk)
2143 {
2144 	if (msk->subflow) {
2145 		iput(SOCK_INODE(msk->subflow));
2146 		msk->subflow = NULL;
2147 	}
2148 }
2149 
2150 /* subflow sockets can be either outgoing (connect) or incoming
2151  * (accept).
2152  *
2153  * Outgoing subflows use in-kernel sockets.
2154  * Incoming subflows do not have their own 'struct socket' allocated,
2155  * so we need to use tcp_close() after detaching them from the mptcp
2156  * parent socket.
2157  */
2158 static void __mptcp_close_ssk(struct sock *sk, struct sock *ssk,
2159 			      struct mptcp_subflow_context *subflow)
2160 {
2161 	struct mptcp_sock *msk = mptcp_sk(sk);
2162 
2163 	list_del(&subflow->node);
2164 
2165 	lock_sock_nested(ssk, SINGLE_DEPTH_NESTING);
2166 
2167 	/* if we are invoked by the msk cleanup code, the subflow is
2168 	 * already orphaned
2169 	 */
2170 	if (ssk->sk_socket)
2171 		sock_orphan(ssk);
2172 
2173 	subflow->disposable = 1;
2174 
2175 	/* if ssk hit tcp_done(), tcp_cleanup_ulp() cleared the related ops
2176 	 * the ssk has been already destroyed, we just need to release the
2177 	 * reference owned by msk;
2178 	 */
2179 	if (!inet_csk(ssk)->icsk_ulp_ops) {
2180 		kfree_rcu(subflow, rcu);
2181 	} else {
2182 		/* otherwise tcp will dispose of the ssk and subflow ctx */
2183 		__tcp_close(ssk, 0);
2184 
2185 		/* close acquired an extra ref */
2186 		__sock_put(ssk);
2187 	}
2188 	release_sock(ssk);
2189 
2190 	sock_put(ssk);
2191 
2192 	if (ssk == msk->last_snd)
2193 		msk->last_snd = NULL;
2194 
2195 	if (ssk == msk->ack_hint)
2196 		msk->ack_hint = NULL;
2197 
2198 	if (ssk == msk->first)
2199 		msk->first = NULL;
2200 
2201 	if (msk->subflow && ssk == msk->subflow->sk)
2202 		mptcp_dispose_initial_subflow(msk);
2203 }
2204 
2205 void mptcp_close_ssk(struct sock *sk, struct sock *ssk,
2206 		     struct mptcp_subflow_context *subflow)
2207 {
2208 	if (sk->sk_state == TCP_ESTABLISHED)
2209 		mptcp_event(MPTCP_EVENT_SUB_CLOSED, mptcp_sk(sk), ssk, GFP_KERNEL);
2210 	__mptcp_close_ssk(sk, ssk, subflow);
2211 }
2212 
2213 static unsigned int mptcp_sync_mss(struct sock *sk, u32 pmtu)
2214 {
2215 	return 0;
2216 }
2217 
2218 static void __mptcp_close_subflow(struct mptcp_sock *msk)
2219 {
2220 	struct mptcp_subflow_context *subflow, *tmp;
2221 
2222 	might_sleep();
2223 
2224 	list_for_each_entry_safe(subflow, tmp, &msk->conn_list, node) {
2225 		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
2226 
2227 		if (inet_sk_state_load(ssk) != TCP_CLOSE)
2228 			continue;
2229 
2230 		/* 'subflow_data_ready' will re-sched once rx queue is empty */
2231 		if (!skb_queue_empty_lockless(&ssk->sk_receive_queue))
2232 			continue;
2233 
2234 		mptcp_close_ssk((struct sock *)msk, ssk, subflow);
2235 	}
2236 }
2237 
2238 static bool mptcp_check_close_timeout(const struct sock *sk)
2239 {
2240 	s32 delta = tcp_jiffies32 - inet_csk(sk)->icsk_mtup.probe_timestamp;
2241 	struct mptcp_subflow_context *subflow;
2242 
2243 	if (delta >= TCP_TIMEWAIT_LEN)
2244 		return true;
2245 
2246 	/* if all subflows are in closed status don't bother with additional
2247 	 * timeout
2248 	 */
2249 	mptcp_for_each_subflow(mptcp_sk(sk), subflow) {
2250 		if (inet_sk_state_load(mptcp_subflow_tcp_sock(subflow)) !=
2251 		    TCP_CLOSE)
2252 			return false;
2253 	}
2254 	return true;
2255 }
2256 
2257 static void mptcp_check_fastclose(struct mptcp_sock *msk)
2258 {
2259 	struct mptcp_subflow_context *subflow, *tmp;
2260 	struct sock *sk = &msk->sk.icsk_inet.sk;
2261 
2262 	if (likely(!READ_ONCE(msk->rcv_fastclose)))
2263 		return;
2264 
2265 	mptcp_token_destroy(msk);
2266 
2267 	list_for_each_entry_safe(subflow, tmp, &msk->conn_list, node) {
2268 		struct sock *tcp_sk = mptcp_subflow_tcp_sock(subflow);
2269 
2270 		lock_sock(tcp_sk);
2271 		if (tcp_sk->sk_state != TCP_CLOSE) {
2272 			tcp_send_active_reset(tcp_sk, GFP_ATOMIC);
2273 			tcp_set_state(tcp_sk, TCP_CLOSE);
2274 		}
2275 		release_sock(tcp_sk);
2276 	}
2277 
2278 	inet_sk_state_store(sk, TCP_CLOSE);
2279 	sk->sk_shutdown = SHUTDOWN_MASK;
2280 	smp_mb__before_atomic(); /* SHUTDOWN must be visible first */
2281 	set_bit(MPTCP_DATA_READY, &msk->flags);
2282 	set_bit(MPTCP_WORK_CLOSE_SUBFLOW, &msk->flags);
2283 
2284 	mptcp_close_wake_up(sk);
2285 }
2286 
2287 static void __mptcp_retrans(struct sock *sk)
2288 {
2289 	struct mptcp_sock *msk = mptcp_sk(sk);
2290 	struct mptcp_sendmsg_info info = {};
2291 	struct mptcp_data_frag *dfrag;
2292 	size_t copied = 0;
2293 	struct sock *ssk;
2294 	int ret;
2295 
2296 	__mptcp_clean_una_wakeup(sk);
2297 	dfrag = mptcp_rtx_head(sk);
2298 	if (!dfrag) {
2299 		if (mptcp_data_fin_enabled(msk)) {
2300 			struct inet_connection_sock *icsk = inet_csk(sk);
2301 
2302 			icsk->icsk_retransmits++;
2303 			mptcp_set_datafin_timeout(sk);
2304 			mptcp_send_ack(msk);
2305 
2306 			goto reset_timer;
2307 		}
2308 
2309 		return;
2310 	}
2311 
2312 	ssk = mptcp_subflow_get_retrans(msk);
2313 	if (!ssk)
2314 		goto reset_timer;
2315 
2316 	lock_sock(ssk);
2317 
2318 	/* limit retransmission to the bytes already sent on some subflows */
2319 	info.sent = 0;
2320 	info.limit = dfrag->already_sent;
2321 	while (info.sent < dfrag->already_sent) {
2322 		if (!mptcp_alloc_tx_skb(sk, ssk))
2323 			break;
2324 
2325 		ret = mptcp_sendmsg_frag(sk, ssk, dfrag, &info);
2326 		if (ret <= 0)
2327 			break;
2328 
2329 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_RETRANSSEGS);
2330 		copied += ret;
2331 		info.sent += ret;
2332 	}
2333 	if (copied)
2334 		tcp_push(ssk, 0, info.mss_now, tcp_sk(ssk)->nonagle,
2335 			 info.size_goal);
2336 
2337 	mptcp_set_timeout(sk, ssk);
2338 	release_sock(ssk);
2339 
2340 reset_timer:
2341 	if (!mptcp_timer_pending(sk))
2342 		mptcp_reset_timer(sk);
2343 }
2344 
2345 static void mptcp_worker(struct work_struct *work)
2346 {
2347 	struct mptcp_sock *msk = container_of(work, struct mptcp_sock, work);
2348 	struct sock *sk = &msk->sk.icsk_inet.sk;
2349 	int state;
2350 
2351 	lock_sock(sk);
2352 	state = sk->sk_state;
2353 	if (unlikely(state == TCP_CLOSE))
2354 		goto unlock;
2355 
2356 	mptcp_check_data_fin_ack(sk);
2357 	mptcp_flush_join_list(msk);
2358 
2359 	mptcp_check_fastclose(msk);
2360 
2361 	if (msk->pm.status)
2362 		mptcp_pm_nl_work(msk);
2363 
2364 	if (test_and_clear_bit(MPTCP_WORK_EOF, &msk->flags))
2365 		mptcp_check_for_eof(msk);
2366 
2367 	__mptcp_check_send_data_fin(sk);
2368 	mptcp_check_data_fin(sk);
2369 
2370 	/* There is no point in keeping around an orphaned sk timedout or
2371 	 * closed, but we need the msk around to reply to incoming DATA_FIN,
2372 	 * even if it is orphaned and in FIN_WAIT2 state
2373 	 */
2374 	if (sock_flag(sk, SOCK_DEAD) &&
2375 	    (mptcp_check_close_timeout(sk) || sk->sk_state == TCP_CLOSE)) {
2376 		inet_sk_state_store(sk, TCP_CLOSE);
2377 		__mptcp_destroy_sock(sk);
2378 		goto unlock;
2379 	}
2380 
2381 	if (test_and_clear_bit(MPTCP_WORK_CLOSE_SUBFLOW, &msk->flags))
2382 		__mptcp_close_subflow(msk);
2383 
2384 	if (test_and_clear_bit(MPTCP_WORK_RTX, &msk->flags))
2385 		__mptcp_retrans(sk);
2386 
2387 unlock:
2388 	release_sock(sk);
2389 	sock_put(sk);
2390 }
2391 
2392 static int __mptcp_init_sock(struct sock *sk)
2393 {
2394 	struct mptcp_sock *msk = mptcp_sk(sk);
2395 
2396 	spin_lock_init(&msk->join_list_lock);
2397 
2398 	INIT_LIST_HEAD(&msk->conn_list);
2399 	INIT_LIST_HEAD(&msk->join_list);
2400 	INIT_LIST_HEAD(&msk->rtx_queue);
2401 	INIT_WORK(&msk->work, mptcp_worker);
2402 	__skb_queue_head_init(&msk->receive_queue);
2403 	__skb_queue_head_init(&msk->skb_tx_cache);
2404 	msk->out_of_order_queue = RB_ROOT;
2405 	msk->first_pending = NULL;
2406 	msk->wmem_reserved = 0;
2407 	msk->rmem_released = 0;
2408 	msk->tx_pending_data = 0;
2409 	msk->size_goal_cache = TCP_BASE_MSS;
2410 
2411 	msk->ack_hint = NULL;
2412 	msk->first = NULL;
2413 	inet_csk(sk)->icsk_sync_mss = mptcp_sync_mss;
2414 
2415 	mptcp_pm_data_init(msk);
2416 
2417 	/* re-use the csk retrans timer for MPTCP-level retrans */
2418 	timer_setup(&msk->sk.icsk_retransmit_timer, mptcp_retransmit_timer, 0);
2419 	timer_setup(&sk->sk_timer, mptcp_timeout_timer, 0);
2420 
2421 	tcp_assign_congestion_control(sk);
2422 
2423 	return 0;
2424 }
2425 
2426 static int mptcp_init_sock(struct sock *sk)
2427 {
2428 	struct net *net = sock_net(sk);
2429 	int ret;
2430 
2431 	ret = __mptcp_init_sock(sk);
2432 	if (ret)
2433 		return ret;
2434 
2435 	if (!mptcp_is_enabled(net))
2436 		return -ENOPROTOOPT;
2437 
2438 	if (unlikely(!net->mib.mptcp_statistics) && !mptcp_mib_alloc(net))
2439 		return -ENOMEM;
2440 
2441 	ret = __mptcp_socket_create(mptcp_sk(sk));
2442 	if (ret)
2443 		return ret;
2444 
2445 	sk_sockets_allocated_inc(sk);
2446 	sk->sk_rcvbuf = sock_net(sk)->ipv4.sysctl_tcp_rmem[1];
2447 	sk->sk_sndbuf = sock_net(sk)->ipv4.sysctl_tcp_wmem[1];
2448 
2449 	return 0;
2450 }
2451 
2452 static void __mptcp_clear_xmit(struct sock *sk)
2453 {
2454 	struct mptcp_sock *msk = mptcp_sk(sk);
2455 	struct mptcp_data_frag *dtmp, *dfrag;
2456 	struct sk_buff *skb;
2457 
2458 	WRITE_ONCE(msk->first_pending, NULL);
2459 	list_for_each_entry_safe(dfrag, dtmp, &msk->rtx_queue, list)
2460 		dfrag_clear(sk, dfrag);
2461 	while ((skb = __skb_dequeue(&msk->skb_tx_cache)) != NULL) {
2462 		sk->sk_forward_alloc += skb->truesize;
2463 		kfree_skb(skb);
2464 	}
2465 }
2466 
2467 static void mptcp_cancel_work(struct sock *sk)
2468 {
2469 	struct mptcp_sock *msk = mptcp_sk(sk);
2470 
2471 	if (cancel_work_sync(&msk->work))
2472 		__sock_put(sk);
2473 }
2474 
2475 void mptcp_subflow_shutdown(struct sock *sk, struct sock *ssk, int how)
2476 {
2477 	lock_sock(ssk);
2478 
2479 	switch (ssk->sk_state) {
2480 	case TCP_LISTEN:
2481 		if (!(how & RCV_SHUTDOWN))
2482 			break;
2483 		fallthrough;
2484 	case TCP_SYN_SENT:
2485 		tcp_disconnect(ssk, O_NONBLOCK);
2486 		break;
2487 	default:
2488 		if (__mptcp_check_fallback(mptcp_sk(sk))) {
2489 			pr_debug("Fallback");
2490 			ssk->sk_shutdown |= how;
2491 			tcp_shutdown(ssk, how);
2492 		} else {
2493 			pr_debug("Sending DATA_FIN on subflow %p", ssk);
2494 			mptcp_set_timeout(sk, ssk);
2495 			tcp_send_ack(ssk);
2496 			if (!mptcp_timer_pending(sk))
2497 				mptcp_reset_timer(sk);
2498 		}
2499 		break;
2500 	}
2501 
2502 	release_sock(ssk);
2503 }
2504 
2505 static const unsigned char new_state[16] = {
2506 	/* current state:     new state:      action:	*/
2507 	[0 /* (Invalid) */] = TCP_CLOSE,
2508 	[TCP_ESTABLISHED]   = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
2509 	[TCP_SYN_SENT]      = TCP_CLOSE,
2510 	[TCP_SYN_RECV]      = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
2511 	[TCP_FIN_WAIT1]     = TCP_FIN_WAIT1,
2512 	[TCP_FIN_WAIT2]     = TCP_FIN_WAIT2,
2513 	[TCP_TIME_WAIT]     = TCP_CLOSE,	/* should not happen ! */
2514 	[TCP_CLOSE]         = TCP_CLOSE,
2515 	[TCP_CLOSE_WAIT]    = TCP_LAST_ACK  | TCP_ACTION_FIN,
2516 	[TCP_LAST_ACK]      = TCP_LAST_ACK,
2517 	[TCP_LISTEN]        = TCP_CLOSE,
2518 	[TCP_CLOSING]       = TCP_CLOSING,
2519 	[TCP_NEW_SYN_RECV]  = TCP_CLOSE,	/* should not happen ! */
2520 };
2521 
2522 static int mptcp_close_state(struct sock *sk)
2523 {
2524 	int next = (int)new_state[sk->sk_state];
2525 	int ns = next & TCP_STATE_MASK;
2526 
2527 	inet_sk_state_store(sk, ns);
2528 
2529 	return next & TCP_ACTION_FIN;
2530 }
2531 
2532 static void __mptcp_check_send_data_fin(struct sock *sk)
2533 {
2534 	struct mptcp_subflow_context *subflow;
2535 	struct mptcp_sock *msk = mptcp_sk(sk);
2536 
2537 	pr_debug("msk=%p snd_data_fin_enable=%d pending=%d snd_nxt=%llu write_seq=%llu",
2538 		 msk, msk->snd_data_fin_enable, !!mptcp_send_head(sk),
2539 		 msk->snd_nxt, msk->write_seq);
2540 
2541 	/* we still need to enqueue subflows or not really shutting down,
2542 	 * skip this
2543 	 */
2544 	if (!msk->snd_data_fin_enable || msk->snd_nxt + 1 != msk->write_seq ||
2545 	    mptcp_send_head(sk))
2546 		return;
2547 
2548 	WRITE_ONCE(msk->snd_nxt, msk->write_seq);
2549 
2550 	/* fallback socket will not get data_fin/ack, can move to the next
2551 	 * state now
2552 	 */
2553 	if (__mptcp_check_fallback(msk)) {
2554 		if ((1 << sk->sk_state) & (TCPF_CLOSING | TCPF_LAST_ACK)) {
2555 			inet_sk_state_store(sk, TCP_CLOSE);
2556 			mptcp_close_wake_up(sk);
2557 		} else if (sk->sk_state == TCP_FIN_WAIT1) {
2558 			inet_sk_state_store(sk, TCP_FIN_WAIT2);
2559 		}
2560 	}
2561 
2562 	mptcp_flush_join_list(msk);
2563 	mptcp_for_each_subflow(msk, subflow) {
2564 		struct sock *tcp_sk = mptcp_subflow_tcp_sock(subflow);
2565 
2566 		mptcp_subflow_shutdown(sk, tcp_sk, SEND_SHUTDOWN);
2567 	}
2568 }
2569 
2570 static void __mptcp_wr_shutdown(struct sock *sk)
2571 {
2572 	struct mptcp_sock *msk = mptcp_sk(sk);
2573 
2574 	pr_debug("msk=%p snd_data_fin_enable=%d shutdown=%x state=%d pending=%d",
2575 		 msk, msk->snd_data_fin_enable, sk->sk_shutdown, sk->sk_state,
2576 		 !!mptcp_send_head(sk));
2577 
2578 	/* will be ignored by fallback sockets */
2579 	WRITE_ONCE(msk->write_seq, msk->write_seq + 1);
2580 	WRITE_ONCE(msk->snd_data_fin_enable, 1);
2581 
2582 	__mptcp_check_send_data_fin(sk);
2583 }
2584 
2585 static void __mptcp_destroy_sock(struct sock *sk)
2586 {
2587 	struct mptcp_subflow_context *subflow, *tmp;
2588 	struct mptcp_sock *msk = mptcp_sk(sk);
2589 	LIST_HEAD(conn_list);
2590 
2591 	pr_debug("msk=%p", msk);
2592 
2593 	might_sleep();
2594 
2595 	/* be sure to always acquire the join list lock, to sync vs
2596 	 * mptcp_finish_join().
2597 	 */
2598 	spin_lock_bh(&msk->join_list_lock);
2599 	list_splice_tail_init(&msk->join_list, &msk->conn_list);
2600 	spin_unlock_bh(&msk->join_list_lock);
2601 	list_splice_init(&msk->conn_list, &conn_list);
2602 
2603 	sk_stop_timer(sk, &msk->sk.icsk_retransmit_timer);
2604 	sk_stop_timer(sk, &sk->sk_timer);
2605 	msk->pm.status = 0;
2606 
2607 	list_for_each_entry_safe(subflow, tmp, &conn_list, node) {
2608 		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
2609 		__mptcp_close_ssk(sk, ssk, subflow);
2610 	}
2611 
2612 	sk->sk_prot->destroy(sk);
2613 
2614 	WARN_ON_ONCE(msk->wmem_reserved);
2615 	WARN_ON_ONCE(msk->rmem_released);
2616 	sk_stream_kill_queues(sk);
2617 	xfrm_sk_free_policy(sk);
2618 
2619 	tcp_cleanup_congestion_control(sk);
2620 	sk_refcnt_debug_release(sk);
2621 	mptcp_dispose_initial_subflow(msk);
2622 	sock_put(sk);
2623 }
2624 
2625 static void mptcp_close(struct sock *sk, long timeout)
2626 {
2627 	struct mptcp_subflow_context *subflow;
2628 	bool do_cancel_work = false;
2629 
2630 	lock_sock(sk);
2631 	sk->sk_shutdown = SHUTDOWN_MASK;
2632 
2633 	if ((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) {
2634 		inet_sk_state_store(sk, TCP_CLOSE);
2635 		goto cleanup;
2636 	}
2637 
2638 	if (mptcp_close_state(sk))
2639 		__mptcp_wr_shutdown(sk);
2640 
2641 	sk_stream_wait_close(sk, timeout);
2642 
2643 cleanup:
2644 	/* orphan all the subflows */
2645 	inet_csk(sk)->icsk_mtup.probe_timestamp = tcp_jiffies32;
2646 	mptcp_for_each_subflow(mptcp_sk(sk), subflow) {
2647 		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
2648 		bool slow = lock_sock_fast(ssk);
2649 
2650 		sock_orphan(ssk);
2651 		unlock_sock_fast(ssk, slow);
2652 	}
2653 	sock_orphan(sk);
2654 
2655 	sock_hold(sk);
2656 	pr_debug("msk=%p state=%d", sk, sk->sk_state);
2657 	if (sk->sk_state == TCP_CLOSE) {
2658 		__mptcp_destroy_sock(sk);
2659 		do_cancel_work = true;
2660 	} else {
2661 		sk_reset_timer(sk, &sk->sk_timer, jiffies + TCP_TIMEWAIT_LEN);
2662 	}
2663 	release_sock(sk);
2664 	if (do_cancel_work)
2665 		mptcp_cancel_work(sk);
2666 
2667 	if (mptcp_sk(sk)->token)
2668 		mptcp_event(MPTCP_EVENT_CLOSED, mptcp_sk(sk), NULL, GFP_KERNEL);
2669 
2670 	sock_put(sk);
2671 }
2672 
2673 static void mptcp_copy_inaddrs(struct sock *msk, const struct sock *ssk)
2674 {
2675 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2676 	const struct ipv6_pinfo *ssk6 = inet6_sk(ssk);
2677 	struct ipv6_pinfo *msk6 = inet6_sk(msk);
2678 
2679 	msk->sk_v6_daddr = ssk->sk_v6_daddr;
2680 	msk->sk_v6_rcv_saddr = ssk->sk_v6_rcv_saddr;
2681 
2682 	if (msk6 && ssk6) {
2683 		msk6->saddr = ssk6->saddr;
2684 		msk6->flow_label = ssk6->flow_label;
2685 	}
2686 #endif
2687 
2688 	inet_sk(msk)->inet_num = inet_sk(ssk)->inet_num;
2689 	inet_sk(msk)->inet_dport = inet_sk(ssk)->inet_dport;
2690 	inet_sk(msk)->inet_sport = inet_sk(ssk)->inet_sport;
2691 	inet_sk(msk)->inet_daddr = inet_sk(ssk)->inet_daddr;
2692 	inet_sk(msk)->inet_saddr = inet_sk(ssk)->inet_saddr;
2693 	inet_sk(msk)->inet_rcv_saddr = inet_sk(ssk)->inet_rcv_saddr;
2694 }
2695 
2696 static int mptcp_disconnect(struct sock *sk, int flags)
2697 {
2698 	struct mptcp_subflow_context *subflow;
2699 	struct mptcp_sock *msk = mptcp_sk(sk);
2700 
2701 	mptcp_do_flush_join_list(msk);
2702 
2703 	mptcp_for_each_subflow(msk, subflow) {
2704 		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
2705 
2706 		lock_sock(ssk);
2707 		tcp_disconnect(ssk, flags);
2708 		release_sock(ssk);
2709 	}
2710 	return 0;
2711 }
2712 
2713 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2714 static struct ipv6_pinfo *mptcp_inet6_sk(const struct sock *sk)
2715 {
2716 	unsigned int offset = sizeof(struct mptcp6_sock) - sizeof(struct ipv6_pinfo);
2717 
2718 	return (struct ipv6_pinfo *)(((u8 *)sk) + offset);
2719 }
2720 #endif
2721 
2722 struct sock *mptcp_sk_clone(const struct sock *sk,
2723 			    const struct mptcp_options_received *mp_opt,
2724 			    struct request_sock *req)
2725 {
2726 	struct mptcp_subflow_request_sock *subflow_req = mptcp_subflow_rsk(req);
2727 	struct sock *nsk = sk_clone_lock(sk, GFP_ATOMIC);
2728 	struct mptcp_sock *msk;
2729 	u64 ack_seq;
2730 
2731 	if (!nsk)
2732 		return NULL;
2733 
2734 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2735 	if (nsk->sk_family == AF_INET6)
2736 		inet_sk(nsk)->pinet6 = mptcp_inet6_sk(nsk);
2737 #endif
2738 
2739 	__mptcp_init_sock(nsk);
2740 
2741 	msk = mptcp_sk(nsk);
2742 	msk->local_key = subflow_req->local_key;
2743 	msk->token = subflow_req->token;
2744 	msk->subflow = NULL;
2745 	WRITE_ONCE(msk->fully_established, false);
2746 
2747 	msk->write_seq = subflow_req->idsn + 1;
2748 	msk->snd_nxt = msk->write_seq;
2749 	msk->snd_una = msk->write_seq;
2750 	msk->wnd_end = msk->snd_nxt + req->rsk_rcv_wnd;
2751 	msk->setsockopt_seq = mptcp_sk(sk)->setsockopt_seq;
2752 
2753 	if (mp_opt->mp_capable) {
2754 		msk->can_ack = true;
2755 		msk->remote_key = mp_opt->sndr_key;
2756 		mptcp_crypto_key_sha(msk->remote_key, NULL, &ack_seq);
2757 		ack_seq++;
2758 		WRITE_ONCE(msk->ack_seq, ack_seq);
2759 		WRITE_ONCE(msk->rcv_wnd_sent, ack_seq);
2760 	}
2761 
2762 	sock_reset_flag(nsk, SOCK_RCU_FREE);
2763 	/* will be fully established after successful MPC subflow creation */
2764 	inet_sk_state_store(nsk, TCP_SYN_RECV);
2765 
2766 	security_inet_csk_clone(nsk, req);
2767 	bh_unlock_sock(nsk);
2768 
2769 	/* keep a single reference */
2770 	__sock_put(nsk);
2771 	return nsk;
2772 }
2773 
2774 void mptcp_rcv_space_init(struct mptcp_sock *msk, const struct sock *ssk)
2775 {
2776 	const struct tcp_sock *tp = tcp_sk(ssk);
2777 
2778 	msk->rcvq_space.copied = 0;
2779 	msk->rcvq_space.rtt_us = 0;
2780 
2781 	msk->rcvq_space.time = tp->tcp_mstamp;
2782 
2783 	/* initial rcv_space offering made to peer */
2784 	msk->rcvq_space.space = min_t(u32, tp->rcv_wnd,
2785 				      TCP_INIT_CWND * tp->advmss);
2786 	if (msk->rcvq_space.space == 0)
2787 		msk->rcvq_space.space = TCP_INIT_CWND * TCP_MSS_DEFAULT;
2788 
2789 	WRITE_ONCE(msk->wnd_end, msk->snd_nxt + tcp_sk(ssk)->snd_wnd);
2790 }
2791 
2792 static struct sock *mptcp_accept(struct sock *sk, int flags, int *err,
2793 				 bool kern)
2794 {
2795 	struct mptcp_sock *msk = mptcp_sk(sk);
2796 	struct socket *listener;
2797 	struct sock *newsk;
2798 
2799 	listener = __mptcp_nmpc_socket(msk);
2800 	if (WARN_ON_ONCE(!listener)) {
2801 		*err = -EINVAL;
2802 		return NULL;
2803 	}
2804 
2805 	pr_debug("msk=%p, listener=%p", msk, mptcp_subflow_ctx(listener->sk));
2806 	newsk = inet_csk_accept(listener->sk, flags, err, kern);
2807 	if (!newsk)
2808 		return NULL;
2809 
2810 	pr_debug("msk=%p, subflow is mptcp=%d", msk, sk_is_mptcp(newsk));
2811 	if (sk_is_mptcp(newsk)) {
2812 		struct mptcp_subflow_context *subflow;
2813 		struct sock *new_mptcp_sock;
2814 
2815 		subflow = mptcp_subflow_ctx(newsk);
2816 		new_mptcp_sock = subflow->conn;
2817 
2818 		/* is_mptcp should be false if subflow->conn is missing, see
2819 		 * subflow_syn_recv_sock()
2820 		 */
2821 		if (WARN_ON_ONCE(!new_mptcp_sock)) {
2822 			tcp_sk(newsk)->is_mptcp = 0;
2823 			return newsk;
2824 		}
2825 
2826 		/* acquire the 2nd reference for the owning socket */
2827 		sock_hold(new_mptcp_sock);
2828 		newsk = new_mptcp_sock;
2829 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_MPCAPABLEPASSIVEACK);
2830 	} else {
2831 		MPTCP_INC_STATS(sock_net(sk),
2832 				MPTCP_MIB_MPCAPABLEPASSIVEFALLBACK);
2833 	}
2834 
2835 	return newsk;
2836 }
2837 
2838 void mptcp_destroy_common(struct mptcp_sock *msk)
2839 {
2840 	struct sock *sk = (struct sock *)msk;
2841 
2842 	__mptcp_clear_xmit(sk);
2843 
2844 	/* move to sk_receive_queue, sk_stream_kill_queues will purge it */
2845 	skb_queue_splice_tail_init(&msk->receive_queue, &sk->sk_receive_queue);
2846 
2847 	skb_rbtree_purge(&msk->out_of_order_queue);
2848 	mptcp_token_destroy(msk);
2849 	mptcp_pm_free_anno_list(msk);
2850 }
2851 
2852 static void mptcp_destroy(struct sock *sk)
2853 {
2854 	struct mptcp_sock *msk = mptcp_sk(sk);
2855 
2856 	mptcp_destroy_common(msk);
2857 	sk_sockets_allocated_dec(sk);
2858 }
2859 
2860 void __mptcp_data_acked(struct sock *sk)
2861 {
2862 	if (!sock_owned_by_user(sk))
2863 		__mptcp_clean_una(sk);
2864 	else
2865 		set_bit(MPTCP_CLEAN_UNA, &mptcp_sk(sk)->flags);
2866 
2867 	if (mptcp_pending_data_fin_ack(sk))
2868 		mptcp_schedule_work(sk);
2869 }
2870 
2871 void __mptcp_check_push(struct sock *sk, struct sock *ssk)
2872 {
2873 	if (!mptcp_send_head(sk))
2874 		return;
2875 
2876 	if (!sock_owned_by_user(sk)) {
2877 		struct sock *xmit_ssk = mptcp_subflow_get_send(mptcp_sk(sk));
2878 
2879 		if (xmit_ssk == ssk)
2880 			__mptcp_subflow_push_pending(sk, ssk);
2881 		else if (xmit_ssk)
2882 			mptcp_subflow_delegate(mptcp_subflow_ctx(xmit_ssk));
2883 	} else {
2884 		set_bit(MPTCP_PUSH_PENDING, &mptcp_sk(sk)->flags);
2885 	}
2886 }
2887 
2888 /* processes deferred events and flush wmem */
2889 static void mptcp_release_cb(struct sock *sk)
2890 {
2891 	for (;;) {
2892 		unsigned long flags = 0;
2893 
2894 		if (test_and_clear_bit(MPTCP_PUSH_PENDING, &mptcp_sk(sk)->flags))
2895 			flags |= BIT(MPTCP_PUSH_PENDING);
2896 		if (test_and_clear_bit(MPTCP_RETRANSMIT, &mptcp_sk(sk)->flags))
2897 			flags |= BIT(MPTCP_RETRANSMIT);
2898 		if (!flags)
2899 			break;
2900 
2901 		/* the following actions acquire the subflow socket lock
2902 		 *
2903 		 * 1) can't be invoked in atomic scope
2904 		 * 2) must avoid ABBA deadlock with msk socket spinlock: the RX
2905 		 *    datapath acquires the msk socket spinlock while helding
2906 		 *    the subflow socket lock
2907 		 */
2908 
2909 		spin_unlock_bh(&sk->sk_lock.slock);
2910 		if (flags & BIT(MPTCP_PUSH_PENDING))
2911 			__mptcp_push_pending(sk, 0);
2912 		if (flags & BIT(MPTCP_RETRANSMIT))
2913 			__mptcp_retrans(sk);
2914 
2915 		cond_resched();
2916 		spin_lock_bh(&sk->sk_lock.slock);
2917 	}
2918 
2919 	if (test_and_clear_bit(MPTCP_CLEAN_UNA, &mptcp_sk(sk)->flags))
2920 		__mptcp_clean_una_wakeup(sk);
2921 	if (test_and_clear_bit(MPTCP_ERROR_REPORT, &mptcp_sk(sk)->flags))
2922 		__mptcp_error_report(sk);
2923 
2924 	/* push_pending may touch wmem_reserved, ensure we do the cleanup
2925 	 * later
2926 	 */
2927 	__mptcp_update_wmem(sk);
2928 	__mptcp_update_rmem(sk);
2929 }
2930 
2931 void mptcp_subflow_process_delegated(struct sock *ssk)
2932 {
2933 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
2934 	struct sock *sk = subflow->conn;
2935 
2936 	mptcp_data_lock(sk);
2937 	if (!sock_owned_by_user(sk))
2938 		__mptcp_subflow_push_pending(sk, ssk);
2939 	else
2940 		set_bit(MPTCP_PUSH_PENDING, &mptcp_sk(sk)->flags);
2941 	mptcp_data_unlock(sk);
2942 	mptcp_subflow_delegated_done(subflow);
2943 }
2944 
2945 static int mptcp_hash(struct sock *sk)
2946 {
2947 	/* should never be called,
2948 	 * we hash the TCP subflows not the master socket
2949 	 */
2950 	WARN_ON_ONCE(1);
2951 	return 0;
2952 }
2953 
2954 static void mptcp_unhash(struct sock *sk)
2955 {
2956 	/* called from sk_common_release(), but nothing to do here */
2957 }
2958 
2959 static int mptcp_get_port(struct sock *sk, unsigned short snum)
2960 {
2961 	struct mptcp_sock *msk = mptcp_sk(sk);
2962 	struct socket *ssock;
2963 
2964 	ssock = __mptcp_nmpc_socket(msk);
2965 	pr_debug("msk=%p, subflow=%p", msk, ssock);
2966 	if (WARN_ON_ONCE(!ssock))
2967 		return -EINVAL;
2968 
2969 	return inet_csk_get_port(ssock->sk, snum);
2970 }
2971 
2972 void mptcp_finish_connect(struct sock *ssk)
2973 {
2974 	struct mptcp_subflow_context *subflow;
2975 	struct mptcp_sock *msk;
2976 	struct sock *sk;
2977 	u64 ack_seq;
2978 
2979 	subflow = mptcp_subflow_ctx(ssk);
2980 	sk = subflow->conn;
2981 	msk = mptcp_sk(sk);
2982 
2983 	pr_debug("msk=%p, token=%u", sk, subflow->token);
2984 
2985 	mptcp_crypto_key_sha(subflow->remote_key, NULL, &ack_seq);
2986 	ack_seq++;
2987 	subflow->map_seq = ack_seq;
2988 	subflow->map_subflow_seq = 1;
2989 
2990 	/* the socket is not connected yet, no msk/subflow ops can access/race
2991 	 * accessing the field below
2992 	 */
2993 	WRITE_ONCE(msk->remote_key, subflow->remote_key);
2994 	WRITE_ONCE(msk->local_key, subflow->local_key);
2995 	WRITE_ONCE(msk->write_seq, subflow->idsn + 1);
2996 	WRITE_ONCE(msk->snd_nxt, msk->write_seq);
2997 	WRITE_ONCE(msk->ack_seq, ack_seq);
2998 	WRITE_ONCE(msk->rcv_wnd_sent, ack_seq);
2999 	WRITE_ONCE(msk->can_ack, 1);
3000 	WRITE_ONCE(msk->snd_una, msk->write_seq);
3001 
3002 	mptcp_pm_new_connection(msk, ssk, 0);
3003 
3004 	mptcp_rcv_space_init(msk, ssk);
3005 }
3006 
3007 void mptcp_sock_graft(struct sock *sk, struct socket *parent)
3008 {
3009 	write_lock_bh(&sk->sk_callback_lock);
3010 	rcu_assign_pointer(sk->sk_wq, &parent->wq);
3011 	sk_set_socket(sk, parent);
3012 	sk->sk_uid = SOCK_INODE(parent)->i_uid;
3013 	write_unlock_bh(&sk->sk_callback_lock);
3014 }
3015 
3016 bool mptcp_finish_join(struct sock *ssk)
3017 {
3018 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
3019 	struct mptcp_sock *msk = mptcp_sk(subflow->conn);
3020 	struct sock *parent = (void *)msk;
3021 	struct socket *parent_sock;
3022 	bool ret;
3023 
3024 	pr_debug("msk=%p, subflow=%p", msk, subflow);
3025 
3026 	/* mptcp socket already closing? */
3027 	if (!mptcp_is_fully_established(parent)) {
3028 		subflow->reset_reason = MPTCP_RST_EMPTCP;
3029 		return false;
3030 	}
3031 
3032 	if (!msk->pm.server_side)
3033 		goto out;
3034 
3035 	if (!mptcp_pm_allow_new_subflow(msk)) {
3036 		subflow->reset_reason = MPTCP_RST_EPROHIBIT;
3037 		return false;
3038 	}
3039 
3040 	/* active connections are already on conn_list, and we can't acquire
3041 	 * msk lock here.
3042 	 * use the join list lock as synchronization point and double-check
3043 	 * msk status to avoid racing with __mptcp_destroy_sock()
3044 	 */
3045 	spin_lock_bh(&msk->join_list_lock);
3046 	ret = inet_sk_state_load(parent) == TCP_ESTABLISHED;
3047 	if (ret && !WARN_ON_ONCE(!list_empty(&subflow->node))) {
3048 		list_add_tail(&subflow->node, &msk->join_list);
3049 		sock_hold(ssk);
3050 	}
3051 	spin_unlock_bh(&msk->join_list_lock);
3052 	if (!ret) {
3053 		subflow->reset_reason = MPTCP_RST_EPROHIBIT;
3054 		return false;
3055 	}
3056 
3057 	/* attach to msk socket only after we are sure he will deal with us
3058 	 * at close time
3059 	 */
3060 	parent_sock = READ_ONCE(parent->sk_socket);
3061 	if (parent_sock && !ssk->sk_socket)
3062 		mptcp_sock_graft(ssk, parent_sock);
3063 	subflow->map_seq = READ_ONCE(msk->ack_seq);
3064 out:
3065 	mptcp_event(MPTCP_EVENT_SUB_ESTABLISHED, msk, ssk, GFP_ATOMIC);
3066 	return true;
3067 }
3068 
3069 static void mptcp_shutdown(struct sock *sk, int how)
3070 {
3071 	pr_debug("sk=%p, how=%d", sk, how);
3072 
3073 	if ((how & SEND_SHUTDOWN) && mptcp_close_state(sk))
3074 		__mptcp_wr_shutdown(sk);
3075 }
3076 
3077 static struct proto mptcp_prot = {
3078 	.name		= "MPTCP",
3079 	.owner		= THIS_MODULE,
3080 	.init		= mptcp_init_sock,
3081 	.disconnect	= mptcp_disconnect,
3082 	.close		= mptcp_close,
3083 	.accept		= mptcp_accept,
3084 	.setsockopt	= mptcp_setsockopt,
3085 	.getsockopt	= mptcp_getsockopt,
3086 	.shutdown	= mptcp_shutdown,
3087 	.destroy	= mptcp_destroy,
3088 	.sendmsg	= mptcp_sendmsg,
3089 	.recvmsg	= mptcp_recvmsg,
3090 	.release_cb	= mptcp_release_cb,
3091 	.hash		= mptcp_hash,
3092 	.unhash		= mptcp_unhash,
3093 	.get_port	= mptcp_get_port,
3094 	.sockets_allocated	= &mptcp_sockets_allocated,
3095 	.memory_allocated	= &tcp_memory_allocated,
3096 	.memory_pressure	= &tcp_memory_pressure,
3097 	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_tcp_wmem),
3098 	.sysctl_rmem_offset	= offsetof(struct net, ipv4.sysctl_tcp_rmem),
3099 	.sysctl_mem	= sysctl_tcp_mem,
3100 	.obj_size	= sizeof(struct mptcp_sock),
3101 	.slab_flags	= SLAB_TYPESAFE_BY_RCU,
3102 	.no_autobind	= true,
3103 };
3104 
3105 static int mptcp_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
3106 {
3107 	struct mptcp_sock *msk = mptcp_sk(sock->sk);
3108 	struct socket *ssock;
3109 	int err;
3110 
3111 	lock_sock(sock->sk);
3112 	ssock = __mptcp_nmpc_socket(msk);
3113 	if (!ssock) {
3114 		err = -EINVAL;
3115 		goto unlock;
3116 	}
3117 
3118 	err = ssock->ops->bind(ssock, uaddr, addr_len);
3119 	if (!err)
3120 		mptcp_copy_inaddrs(sock->sk, ssock->sk);
3121 
3122 unlock:
3123 	release_sock(sock->sk);
3124 	return err;
3125 }
3126 
3127 static void mptcp_subflow_early_fallback(struct mptcp_sock *msk,
3128 					 struct mptcp_subflow_context *subflow)
3129 {
3130 	subflow->request_mptcp = 0;
3131 	__mptcp_do_fallback(msk);
3132 }
3133 
3134 static int mptcp_stream_connect(struct socket *sock, struct sockaddr *uaddr,
3135 				int addr_len, int flags)
3136 {
3137 	struct mptcp_sock *msk = mptcp_sk(sock->sk);
3138 	struct mptcp_subflow_context *subflow;
3139 	struct socket *ssock;
3140 	int err;
3141 
3142 	lock_sock(sock->sk);
3143 	if (sock->state != SS_UNCONNECTED && msk->subflow) {
3144 		/* pending connection or invalid state, let existing subflow
3145 		 * cope with that
3146 		 */
3147 		ssock = msk->subflow;
3148 		goto do_connect;
3149 	}
3150 
3151 	ssock = __mptcp_nmpc_socket(msk);
3152 	if (!ssock) {
3153 		err = -EINVAL;
3154 		goto unlock;
3155 	}
3156 
3157 	mptcp_token_destroy(msk);
3158 	inet_sk_state_store(sock->sk, TCP_SYN_SENT);
3159 	subflow = mptcp_subflow_ctx(ssock->sk);
3160 #ifdef CONFIG_TCP_MD5SIG
3161 	/* no MPTCP if MD5SIG is enabled on this socket or we may run out of
3162 	 * TCP option space.
3163 	 */
3164 	if (rcu_access_pointer(tcp_sk(ssock->sk)->md5sig_info))
3165 		mptcp_subflow_early_fallback(msk, subflow);
3166 #endif
3167 	if (subflow->request_mptcp && mptcp_token_new_connect(ssock->sk)) {
3168 		MPTCP_INC_STATS(sock_net(ssock->sk), MPTCP_MIB_TOKENFALLBACKINIT);
3169 		mptcp_subflow_early_fallback(msk, subflow);
3170 	}
3171 	if (likely(!__mptcp_check_fallback(msk)))
3172 		MPTCP_INC_STATS(sock_net(sock->sk), MPTCP_MIB_MPCAPABLEACTIVE);
3173 
3174 do_connect:
3175 	err = ssock->ops->connect(ssock, uaddr, addr_len, flags);
3176 	sock->state = ssock->state;
3177 
3178 	/* on successful connect, the msk state will be moved to established by
3179 	 * subflow_finish_connect()
3180 	 */
3181 	if (!err || err == -EINPROGRESS)
3182 		mptcp_copy_inaddrs(sock->sk, ssock->sk);
3183 	else
3184 		inet_sk_state_store(sock->sk, inet_sk_state_load(ssock->sk));
3185 
3186 unlock:
3187 	release_sock(sock->sk);
3188 	return err;
3189 }
3190 
3191 static int mptcp_listen(struct socket *sock, int backlog)
3192 {
3193 	struct mptcp_sock *msk = mptcp_sk(sock->sk);
3194 	struct socket *ssock;
3195 	int err;
3196 
3197 	pr_debug("msk=%p", msk);
3198 
3199 	lock_sock(sock->sk);
3200 	ssock = __mptcp_nmpc_socket(msk);
3201 	if (!ssock) {
3202 		err = -EINVAL;
3203 		goto unlock;
3204 	}
3205 
3206 	mptcp_token_destroy(msk);
3207 	inet_sk_state_store(sock->sk, TCP_LISTEN);
3208 	sock_set_flag(sock->sk, SOCK_RCU_FREE);
3209 
3210 	err = ssock->ops->listen(ssock, backlog);
3211 	inet_sk_state_store(sock->sk, inet_sk_state_load(ssock->sk));
3212 	if (!err)
3213 		mptcp_copy_inaddrs(sock->sk, ssock->sk);
3214 
3215 unlock:
3216 	release_sock(sock->sk);
3217 	return err;
3218 }
3219 
3220 static int mptcp_stream_accept(struct socket *sock, struct socket *newsock,
3221 			       int flags, bool kern)
3222 {
3223 	struct mptcp_sock *msk = mptcp_sk(sock->sk);
3224 	struct socket *ssock;
3225 	int err;
3226 
3227 	pr_debug("msk=%p", msk);
3228 
3229 	lock_sock(sock->sk);
3230 	if (sock->sk->sk_state != TCP_LISTEN)
3231 		goto unlock_fail;
3232 
3233 	ssock = __mptcp_nmpc_socket(msk);
3234 	if (!ssock)
3235 		goto unlock_fail;
3236 
3237 	clear_bit(MPTCP_DATA_READY, &msk->flags);
3238 	sock_hold(ssock->sk);
3239 	release_sock(sock->sk);
3240 
3241 	err = ssock->ops->accept(sock, newsock, flags, kern);
3242 	if (err == 0 && !mptcp_is_tcpsk(newsock->sk)) {
3243 		struct mptcp_sock *msk = mptcp_sk(newsock->sk);
3244 		struct mptcp_subflow_context *subflow;
3245 		struct sock *newsk = newsock->sk;
3246 
3247 		lock_sock(newsk);
3248 
3249 		/* PM/worker can now acquire the first subflow socket
3250 		 * lock without racing with listener queue cleanup,
3251 		 * we can notify it, if needed.
3252 		 *
3253 		 * Even if remote has reset the initial subflow by now
3254 		 * the refcnt is still at least one.
3255 		 */
3256 		subflow = mptcp_subflow_ctx(msk->first);
3257 		list_add(&subflow->node, &msk->conn_list);
3258 		sock_hold(msk->first);
3259 		if (mptcp_is_fully_established(newsk))
3260 			mptcp_pm_fully_established(msk, msk->first, GFP_KERNEL);
3261 
3262 		mptcp_copy_inaddrs(newsk, msk->first);
3263 		mptcp_rcv_space_init(msk, msk->first);
3264 		mptcp_propagate_sndbuf(newsk, msk->first);
3265 
3266 		/* set ssk->sk_socket of accept()ed flows to mptcp socket.
3267 		 * This is needed so NOSPACE flag can be set from tcp stack.
3268 		 */
3269 		mptcp_flush_join_list(msk);
3270 		mptcp_for_each_subflow(msk, subflow) {
3271 			struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
3272 
3273 			if (!ssk->sk_socket)
3274 				mptcp_sock_graft(ssk, newsock);
3275 		}
3276 		release_sock(newsk);
3277 	}
3278 
3279 	if (inet_csk_listen_poll(ssock->sk))
3280 		set_bit(MPTCP_DATA_READY, &msk->flags);
3281 	sock_put(ssock->sk);
3282 	return err;
3283 
3284 unlock_fail:
3285 	release_sock(sock->sk);
3286 	return -EINVAL;
3287 }
3288 
3289 static __poll_t mptcp_check_readable(struct mptcp_sock *msk)
3290 {
3291 	return test_bit(MPTCP_DATA_READY, &msk->flags) ? EPOLLIN | EPOLLRDNORM :
3292 	       0;
3293 }
3294 
3295 static __poll_t mptcp_check_writeable(struct mptcp_sock *msk)
3296 {
3297 	struct sock *sk = (struct sock *)msk;
3298 
3299 	if (unlikely(sk->sk_shutdown & SEND_SHUTDOWN))
3300 		return EPOLLOUT | EPOLLWRNORM;
3301 
3302 	if (sk_stream_is_writeable(sk))
3303 		return EPOLLOUT | EPOLLWRNORM;
3304 
3305 	mptcp_set_nospace(sk);
3306 	smp_mb__after_atomic(); /* msk->flags is changed by write_space cb */
3307 	if (sk_stream_is_writeable(sk))
3308 		return EPOLLOUT | EPOLLWRNORM;
3309 
3310 	return 0;
3311 }
3312 
3313 static __poll_t mptcp_poll(struct file *file, struct socket *sock,
3314 			   struct poll_table_struct *wait)
3315 {
3316 	struct sock *sk = sock->sk;
3317 	struct mptcp_sock *msk;
3318 	__poll_t mask = 0;
3319 	int state;
3320 
3321 	msk = mptcp_sk(sk);
3322 	sock_poll_wait(file, sock, wait);
3323 
3324 	state = inet_sk_state_load(sk);
3325 	pr_debug("msk=%p state=%d flags=%lx", msk, state, msk->flags);
3326 	if (state == TCP_LISTEN)
3327 		return mptcp_check_readable(msk);
3328 
3329 	if (state != TCP_SYN_SENT && state != TCP_SYN_RECV) {
3330 		mask |= mptcp_check_readable(msk);
3331 		mask |= mptcp_check_writeable(msk);
3332 	}
3333 	if (sk->sk_shutdown == SHUTDOWN_MASK || state == TCP_CLOSE)
3334 		mask |= EPOLLHUP;
3335 	if (sk->sk_shutdown & RCV_SHUTDOWN)
3336 		mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
3337 
3338 	/* This barrier is coupled with smp_wmb() in tcp_reset() */
3339 	smp_rmb();
3340 	if (sk->sk_err)
3341 		mask |= EPOLLERR;
3342 
3343 	return mask;
3344 }
3345 
3346 static const struct proto_ops mptcp_stream_ops = {
3347 	.family		   = PF_INET,
3348 	.owner		   = THIS_MODULE,
3349 	.release	   = inet_release,
3350 	.bind		   = mptcp_bind,
3351 	.connect	   = mptcp_stream_connect,
3352 	.socketpair	   = sock_no_socketpair,
3353 	.accept		   = mptcp_stream_accept,
3354 	.getname	   = inet_getname,
3355 	.poll		   = mptcp_poll,
3356 	.ioctl		   = inet_ioctl,
3357 	.gettstamp	   = sock_gettstamp,
3358 	.listen		   = mptcp_listen,
3359 	.shutdown	   = inet_shutdown,
3360 	.setsockopt	   = sock_common_setsockopt,
3361 	.getsockopt	   = sock_common_getsockopt,
3362 	.sendmsg	   = inet_sendmsg,
3363 	.recvmsg	   = inet_recvmsg,
3364 	.mmap		   = sock_no_mmap,
3365 	.sendpage	   = inet_sendpage,
3366 };
3367 
3368 static struct inet_protosw mptcp_protosw = {
3369 	.type		= SOCK_STREAM,
3370 	.protocol	= IPPROTO_MPTCP,
3371 	.prot		= &mptcp_prot,
3372 	.ops		= &mptcp_stream_ops,
3373 	.flags		= INET_PROTOSW_ICSK,
3374 };
3375 
3376 static int mptcp_napi_poll(struct napi_struct *napi, int budget)
3377 {
3378 	struct mptcp_delegated_action *delegated;
3379 	struct mptcp_subflow_context *subflow;
3380 	int work_done = 0;
3381 
3382 	delegated = container_of(napi, struct mptcp_delegated_action, napi);
3383 	while ((subflow = mptcp_subflow_delegated_next(delegated)) != NULL) {
3384 		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
3385 
3386 		bh_lock_sock_nested(ssk);
3387 		if (!sock_owned_by_user(ssk) &&
3388 		    mptcp_subflow_has_delegated_action(subflow))
3389 			mptcp_subflow_process_delegated(ssk);
3390 		/* ... elsewhere tcp_release_cb_override already processed
3391 		 * the action or will do at next release_sock().
3392 		 * In both case must dequeue the subflow here - on the same
3393 		 * CPU that scheduled it.
3394 		 */
3395 		bh_unlock_sock(ssk);
3396 		sock_put(ssk);
3397 
3398 		if (++work_done == budget)
3399 			return budget;
3400 	}
3401 
3402 	/* always provide a 0 'work_done' argument, so that napi_complete_done
3403 	 * will not try accessing the NULL napi->dev ptr
3404 	 */
3405 	napi_complete_done(napi, 0);
3406 	return work_done;
3407 }
3408 
3409 void __init mptcp_proto_init(void)
3410 {
3411 	struct mptcp_delegated_action *delegated;
3412 	int cpu;
3413 
3414 	mptcp_prot.h.hashinfo = tcp_prot.h.hashinfo;
3415 
3416 	if (percpu_counter_init(&mptcp_sockets_allocated, 0, GFP_KERNEL))
3417 		panic("Failed to allocate MPTCP pcpu counter\n");
3418 
3419 	init_dummy_netdev(&mptcp_napi_dev);
3420 	for_each_possible_cpu(cpu) {
3421 		delegated = per_cpu_ptr(&mptcp_delegated_actions, cpu);
3422 		INIT_LIST_HEAD(&delegated->head);
3423 		netif_tx_napi_add(&mptcp_napi_dev, &delegated->napi, mptcp_napi_poll,
3424 				  NAPI_POLL_WEIGHT);
3425 		napi_enable(&delegated->napi);
3426 	}
3427 
3428 	mptcp_subflow_init();
3429 	mptcp_pm_init();
3430 	mptcp_token_init();
3431 
3432 	if (proto_register(&mptcp_prot, 1) != 0)
3433 		panic("Failed to register MPTCP proto.\n");
3434 
3435 	inet_register_protosw(&mptcp_protosw);
3436 
3437 	BUILD_BUG_ON(sizeof(struct mptcp_skb_cb) > sizeof_field(struct sk_buff, cb));
3438 }
3439 
3440 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
3441 static const struct proto_ops mptcp_v6_stream_ops = {
3442 	.family		   = PF_INET6,
3443 	.owner		   = THIS_MODULE,
3444 	.release	   = inet6_release,
3445 	.bind		   = mptcp_bind,
3446 	.connect	   = mptcp_stream_connect,
3447 	.socketpair	   = sock_no_socketpair,
3448 	.accept		   = mptcp_stream_accept,
3449 	.getname	   = inet6_getname,
3450 	.poll		   = mptcp_poll,
3451 	.ioctl		   = inet6_ioctl,
3452 	.gettstamp	   = sock_gettstamp,
3453 	.listen		   = mptcp_listen,
3454 	.shutdown	   = inet_shutdown,
3455 	.setsockopt	   = sock_common_setsockopt,
3456 	.getsockopt	   = sock_common_getsockopt,
3457 	.sendmsg	   = inet6_sendmsg,
3458 	.recvmsg	   = inet6_recvmsg,
3459 	.mmap		   = sock_no_mmap,
3460 	.sendpage	   = inet_sendpage,
3461 #ifdef CONFIG_COMPAT
3462 	.compat_ioctl	   = inet6_compat_ioctl,
3463 #endif
3464 };
3465 
3466 static struct proto mptcp_v6_prot;
3467 
3468 static void mptcp_v6_destroy(struct sock *sk)
3469 {
3470 	mptcp_destroy(sk);
3471 	inet6_destroy_sock(sk);
3472 }
3473 
3474 static struct inet_protosw mptcp_v6_protosw = {
3475 	.type		= SOCK_STREAM,
3476 	.protocol	= IPPROTO_MPTCP,
3477 	.prot		= &mptcp_v6_prot,
3478 	.ops		= &mptcp_v6_stream_ops,
3479 	.flags		= INET_PROTOSW_ICSK,
3480 };
3481 
3482 int __init mptcp_proto_v6_init(void)
3483 {
3484 	int err;
3485 
3486 	mptcp_v6_prot = mptcp_prot;
3487 	strcpy(mptcp_v6_prot.name, "MPTCPv6");
3488 	mptcp_v6_prot.slab = NULL;
3489 	mptcp_v6_prot.destroy = mptcp_v6_destroy;
3490 	mptcp_v6_prot.obj_size = sizeof(struct mptcp6_sock);
3491 
3492 	err = proto_register(&mptcp_v6_prot, 1);
3493 	if (err)
3494 		return err;
3495 
3496 	err = inet6_register_protosw(&mptcp_v6_protosw);
3497 	if (err)
3498 		proto_unregister(&mptcp_v6_prot);
3499 
3500 	return err;
3501 }
3502 #endif
3503