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