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