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