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