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