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