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