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