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