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