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