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