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