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