xref: /openbmc/linux/net/mptcp/protocol.c (revision 911b8eac)
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 "protocol.h"
25 #include "mib.h"
26 
27 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
28 struct mptcp6_sock {
29 	struct mptcp_sock msk;
30 	struct ipv6_pinfo np;
31 };
32 #endif
33 
34 struct mptcp_skb_cb {
35 	u64 map_seq;
36 	u64 end_seq;
37 	u32 offset;
38 };
39 
40 #define MPTCP_SKB_CB(__skb)	((struct mptcp_skb_cb *)&((__skb)->cb[0]))
41 
42 static struct percpu_counter mptcp_sockets_allocated;
43 
44 /* If msk has an initial subflow socket, and the MP_CAPABLE handshake has not
45  * completed yet or has failed, return the subflow socket.
46  * Otherwise return NULL.
47  */
48 static struct socket *__mptcp_nmpc_socket(const struct mptcp_sock *msk)
49 {
50 	if (!msk->subflow || READ_ONCE(msk->can_ack))
51 		return NULL;
52 
53 	return msk->subflow;
54 }
55 
56 static bool mptcp_is_tcpsk(struct sock *sk)
57 {
58 	struct socket *sock = sk->sk_socket;
59 
60 	if (unlikely(sk->sk_prot == &tcp_prot)) {
61 		/* we are being invoked after mptcp_accept() has
62 		 * accepted a non-mp-capable flow: sk is a tcp_sk,
63 		 * not an mptcp one.
64 		 *
65 		 * Hand the socket over to tcp so all further socket ops
66 		 * bypass mptcp.
67 		 */
68 		sock->ops = &inet_stream_ops;
69 		return true;
70 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
71 	} else if (unlikely(sk->sk_prot == &tcpv6_prot)) {
72 		sock->ops = &inet6_stream_ops;
73 		return true;
74 #endif
75 	}
76 
77 	return false;
78 }
79 
80 static struct sock *__mptcp_tcp_fallback(struct mptcp_sock *msk)
81 {
82 	sock_owned_by_me((const struct sock *)msk);
83 
84 	if (likely(!__mptcp_check_fallback(msk)))
85 		return NULL;
86 
87 	return msk->first;
88 }
89 
90 static int __mptcp_socket_create(struct mptcp_sock *msk)
91 {
92 	struct mptcp_subflow_context *subflow;
93 	struct sock *sk = (struct sock *)msk;
94 	struct socket *ssock;
95 	int err;
96 
97 	err = mptcp_subflow_create_socket(sk, &ssock);
98 	if (err)
99 		return err;
100 
101 	msk->first = ssock->sk;
102 	msk->subflow = ssock;
103 	subflow = mptcp_subflow_ctx(ssock->sk);
104 	list_add(&subflow->node, &msk->conn_list);
105 	subflow->request_mptcp = 1;
106 
107 	/* accept() will wait on first subflow sk_wq, and we always wakes up
108 	 * via msk->sk_socket
109 	 */
110 	RCU_INIT_POINTER(msk->first->sk_wq, &sk->sk_socket->wq);
111 
112 	return 0;
113 }
114 
115 static void mptcp_drop(struct sock *sk, struct sk_buff *skb)
116 {
117 	sk_drops_add(sk, skb);
118 	__kfree_skb(skb);
119 }
120 
121 static bool mptcp_try_coalesce(struct sock *sk, struct sk_buff *to,
122 			       struct sk_buff *from)
123 {
124 	bool fragstolen;
125 	int delta;
126 
127 	if (MPTCP_SKB_CB(from)->offset ||
128 	    !skb_try_coalesce(to, from, &fragstolen, &delta))
129 		return false;
130 
131 	pr_debug("colesced seq %llx into %llx new len %d new end seq %llx",
132 		 MPTCP_SKB_CB(from)->map_seq, MPTCP_SKB_CB(to)->map_seq,
133 		 to->len, MPTCP_SKB_CB(from)->end_seq);
134 	MPTCP_SKB_CB(to)->end_seq = MPTCP_SKB_CB(from)->end_seq;
135 	kfree_skb_partial(from, fragstolen);
136 	atomic_add(delta, &sk->sk_rmem_alloc);
137 	sk_mem_charge(sk, delta);
138 	return true;
139 }
140 
141 static bool mptcp_ooo_try_coalesce(struct mptcp_sock *msk, struct sk_buff *to,
142 				   struct sk_buff *from)
143 {
144 	if (MPTCP_SKB_CB(from)->map_seq != MPTCP_SKB_CB(to)->end_seq)
145 		return false;
146 
147 	return mptcp_try_coalesce((struct sock *)msk, to, from);
148 }
149 
150 /* "inspired" by tcp_data_queue_ofo(), main differences:
151  * - use mptcp seqs
152  * - don't cope with sacks
153  */
154 static void mptcp_data_queue_ofo(struct mptcp_sock *msk, struct sk_buff *skb)
155 {
156 	struct sock *sk = (struct sock *)msk;
157 	struct rb_node **p, *parent;
158 	u64 seq, end_seq, max_seq;
159 	struct sk_buff *skb1;
160 	int space;
161 
162 	seq = MPTCP_SKB_CB(skb)->map_seq;
163 	end_seq = MPTCP_SKB_CB(skb)->end_seq;
164 	space = tcp_space(sk);
165 	max_seq = space > 0 ? space + msk->ack_seq : msk->ack_seq;
166 
167 	pr_debug("msk=%p seq=%llx limit=%llx empty=%d", msk, seq, max_seq,
168 		 RB_EMPTY_ROOT(&msk->out_of_order_queue));
169 	if (after64(seq, max_seq)) {
170 		/* out of window */
171 		mptcp_drop(sk, skb);
172 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_NODSSWINDOW);
173 		return;
174 	}
175 
176 	p = &msk->out_of_order_queue.rb_node;
177 	MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUE);
178 	if (RB_EMPTY_ROOT(&msk->out_of_order_queue)) {
179 		rb_link_node(&skb->rbnode, NULL, p);
180 		rb_insert_color(&skb->rbnode, &msk->out_of_order_queue);
181 		msk->ooo_last_skb = skb;
182 		goto end;
183 	}
184 
185 	/* with 2 subflows, adding at end of ooo queue is quite likely
186 	 * Use of ooo_last_skb avoids the O(Log(N)) rbtree lookup.
187 	 */
188 	if (mptcp_ooo_try_coalesce(msk, msk->ooo_last_skb, skb)) {
189 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOMERGE);
190 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUETAIL);
191 		return;
192 	}
193 
194 	/* Can avoid an rbtree lookup if we are adding skb after ooo_last_skb */
195 	if (!before64(seq, MPTCP_SKB_CB(msk->ooo_last_skb)->end_seq)) {
196 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUETAIL);
197 		parent = &msk->ooo_last_skb->rbnode;
198 		p = &parent->rb_right;
199 		goto insert;
200 	}
201 
202 	/* Find place to insert this segment. Handle overlaps on the way. */
203 	parent = NULL;
204 	while (*p) {
205 		parent = *p;
206 		skb1 = rb_to_skb(parent);
207 		if (before64(seq, MPTCP_SKB_CB(skb1)->map_seq)) {
208 			p = &parent->rb_left;
209 			continue;
210 		}
211 		if (before64(seq, MPTCP_SKB_CB(skb1)->end_seq)) {
212 			if (!after64(end_seq, MPTCP_SKB_CB(skb1)->end_seq)) {
213 				/* All the bits are present. Drop. */
214 				mptcp_drop(sk, skb);
215 				MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
216 				return;
217 			}
218 			if (after64(seq, MPTCP_SKB_CB(skb1)->map_seq)) {
219 				/* partial overlap:
220 				 *     |     skb      |
221 				 *  |     skb1    |
222 				 * continue traversing
223 				 */
224 			} else {
225 				/* skb's seq == skb1's seq and skb covers skb1.
226 				 * Replace skb1 with skb.
227 				 */
228 				rb_replace_node(&skb1->rbnode, &skb->rbnode,
229 						&msk->out_of_order_queue);
230 				mptcp_drop(sk, skb1);
231 				MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
232 				goto merge_right;
233 			}
234 		} else if (mptcp_ooo_try_coalesce(msk, skb1, skb)) {
235 			MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOMERGE);
236 			return;
237 		}
238 		p = &parent->rb_right;
239 	}
240 
241 insert:
242 	/* Insert segment into RB tree. */
243 	rb_link_node(&skb->rbnode, parent, p);
244 	rb_insert_color(&skb->rbnode, &msk->out_of_order_queue);
245 
246 merge_right:
247 	/* Remove other segments covered by skb. */
248 	while ((skb1 = skb_rb_next(skb)) != NULL) {
249 		if (before64(end_seq, MPTCP_SKB_CB(skb1)->end_seq))
250 			break;
251 		rb_erase(&skb1->rbnode, &msk->out_of_order_queue);
252 		mptcp_drop(sk, skb1);
253 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
254 	}
255 	/* If there is no skb after us, we are the last_skb ! */
256 	if (!skb1)
257 		msk->ooo_last_skb = skb;
258 
259 end:
260 	skb_condense(skb);
261 	skb_set_owner_r(skb, sk);
262 }
263 
264 static bool __mptcp_move_skb(struct mptcp_sock *msk, struct sock *ssk,
265 			     struct sk_buff *skb, unsigned int offset,
266 			     size_t copy_len)
267 {
268 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
269 	struct sock *sk = (struct sock *)msk;
270 	struct sk_buff *tail;
271 
272 	__skb_unlink(skb, &ssk->sk_receive_queue);
273 
274 	skb_ext_reset(skb);
275 	skb_orphan(skb);
276 
277 	/* the skb map_seq accounts for the skb offset:
278 	 * mptcp_subflow_get_mapped_dsn() is based on the current tp->copied_seq
279 	 * value
280 	 */
281 	MPTCP_SKB_CB(skb)->map_seq = mptcp_subflow_get_mapped_dsn(subflow);
282 	MPTCP_SKB_CB(skb)->end_seq = MPTCP_SKB_CB(skb)->map_seq + copy_len;
283 	MPTCP_SKB_CB(skb)->offset = offset;
284 
285 	if (MPTCP_SKB_CB(skb)->map_seq == msk->ack_seq) {
286 		/* in sequence */
287 		msk->ack_seq += copy_len;
288 		tail = skb_peek_tail(&sk->sk_receive_queue);
289 		if (tail && mptcp_try_coalesce(sk, tail, skb))
290 			return true;
291 
292 		skb_set_owner_r(skb, sk);
293 		__skb_queue_tail(&sk->sk_receive_queue, skb);
294 		return true;
295 	} else if (after64(MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq)) {
296 		mptcp_data_queue_ofo(msk, skb);
297 		return false;
298 	}
299 
300 	/* old data, keep it simple and drop the whole pkt, sender
301 	 * will retransmit as needed, if needed.
302 	 */
303 	MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
304 	mptcp_drop(sk, skb);
305 	return false;
306 }
307 
308 static void mptcp_stop_timer(struct sock *sk)
309 {
310 	struct inet_connection_sock *icsk = inet_csk(sk);
311 
312 	sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
313 	mptcp_sk(sk)->timer_ival = 0;
314 }
315 
316 static void mptcp_check_data_fin_ack(struct sock *sk)
317 {
318 	struct mptcp_sock *msk = mptcp_sk(sk);
319 
320 	if (__mptcp_check_fallback(msk))
321 		return;
322 
323 	/* Look for an acknowledged DATA_FIN */
324 	if (((1 << sk->sk_state) &
325 	     (TCPF_FIN_WAIT1 | TCPF_CLOSING | TCPF_LAST_ACK)) &&
326 	    msk->write_seq == atomic64_read(&msk->snd_una)) {
327 		mptcp_stop_timer(sk);
328 
329 		WRITE_ONCE(msk->snd_data_fin_enable, 0);
330 
331 		switch (sk->sk_state) {
332 		case TCP_FIN_WAIT1:
333 			inet_sk_state_store(sk, TCP_FIN_WAIT2);
334 			sk->sk_state_change(sk);
335 			break;
336 		case TCP_CLOSING:
337 		case TCP_LAST_ACK:
338 			inet_sk_state_store(sk, TCP_CLOSE);
339 			sk->sk_state_change(sk);
340 			break;
341 		}
342 
343 		if (sk->sk_shutdown == SHUTDOWN_MASK ||
344 		    sk->sk_state == TCP_CLOSE)
345 			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
346 		else
347 			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
348 	}
349 }
350 
351 static bool mptcp_pending_data_fin(struct sock *sk, u64 *seq)
352 {
353 	struct mptcp_sock *msk = mptcp_sk(sk);
354 
355 	if (READ_ONCE(msk->rcv_data_fin) &&
356 	    ((1 << sk->sk_state) &
357 	     (TCPF_ESTABLISHED | TCPF_FIN_WAIT1 | TCPF_FIN_WAIT2))) {
358 		u64 rcv_data_fin_seq = READ_ONCE(msk->rcv_data_fin_seq);
359 
360 		if (msk->ack_seq == rcv_data_fin_seq) {
361 			if (seq)
362 				*seq = rcv_data_fin_seq;
363 
364 			return true;
365 		}
366 	}
367 
368 	return false;
369 }
370 
371 static void mptcp_set_timeout(const struct sock *sk, const struct sock *ssk)
372 {
373 	long tout = ssk && inet_csk(ssk)->icsk_pending ?
374 				      inet_csk(ssk)->icsk_timeout - jiffies : 0;
375 
376 	if (tout <= 0)
377 		tout = mptcp_sk(sk)->timer_ival;
378 	mptcp_sk(sk)->timer_ival = tout > 0 ? tout : TCP_RTO_MIN;
379 }
380 
381 static void mptcp_check_data_fin(struct sock *sk)
382 {
383 	struct mptcp_sock *msk = mptcp_sk(sk);
384 	u64 rcv_data_fin_seq;
385 
386 	if (__mptcp_check_fallback(msk) || !msk->first)
387 		return;
388 
389 	/* Need to ack a DATA_FIN received from a peer while this side
390 	 * of the connection is in ESTABLISHED, FIN_WAIT1, or FIN_WAIT2.
391 	 * msk->rcv_data_fin was set when parsing the incoming options
392 	 * at the subflow level and the msk lock was not held, so this
393 	 * is the first opportunity to act on the DATA_FIN and change
394 	 * the msk state.
395 	 *
396 	 * If we are caught up to the sequence number of the incoming
397 	 * DATA_FIN, send the DATA_ACK now and do state transition.  If
398 	 * not caught up, do nothing and let the recv code send DATA_ACK
399 	 * when catching up.
400 	 */
401 
402 	if (mptcp_pending_data_fin(sk, &rcv_data_fin_seq)) {
403 		struct mptcp_subflow_context *subflow;
404 
405 		msk->ack_seq++;
406 		WRITE_ONCE(msk->rcv_data_fin, 0);
407 
408 		sk->sk_shutdown |= RCV_SHUTDOWN;
409 		smp_mb__before_atomic(); /* SHUTDOWN must be visible first */
410 		set_bit(MPTCP_DATA_READY, &msk->flags);
411 
412 		switch (sk->sk_state) {
413 		case TCP_ESTABLISHED:
414 			inet_sk_state_store(sk, TCP_CLOSE_WAIT);
415 			break;
416 		case TCP_FIN_WAIT1:
417 			inet_sk_state_store(sk, TCP_CLOSING);
418 			break;
419 		case TCP_FIN_WAIT2:
420 			inet_sk_state_store(sk, TCP_CLOSE);
421 			// @@ Close subflows now?
422 			break;
423 		default:
424 			/* Other states not expected */
425 			WARN_ON_ONCE(1);
426 			break;
427 		}
428 
429 		mptcp_set_timeout(sk, NULL);
430 		mptcp_for_each_subflow(msk, subflow) {
431 			struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
432 
433 			lock_sock(ssk);
434 			tcp_send_ack(ssk);
435 			release_sock(ssk);
436 		}
437 
438 		sk->sk_state_change(sk);
439 
440 		if (sk->sk_shutdown == SHUTDOWN_MASK ||
441 		    sk->sk_state == TCP_CLOSE)
442 			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
443 		else
444 			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
445 	}
446 }
447 
448 static bool __mptcp_move_skbs_from_subflow(struct mptcp_sock *msk,
449 					   struct sock *ssk,
450 					   unsigned int *bytes)
451 {
452 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
453 	struct sock *sk = (struct sock *)msk;
454 	unsigned int moved = 0;
455 	bool more_data_avail;
456 	struct tcp_sock *tp;
457 	bool done = false;
458 
459 	pr_debug("msk=%p ssk=%p", msk, ssk);
460 	tp = tcp_sk(ssk);
461 	do {
462 		u32 map_remaining, offset;
463 		u32 seq = tp->copied_seq;
464 		struct sk_buff *skb;
465 		bool fin;
466 
467 		/* try to move as much data as available */
468 		map_remaining = subflow->map_data_len -
469 				mptcp_subflow_get_map_offset(subflow);
470 
471 		skb = skb_peek(&ssk->sk_receive_queue);
472 		if (!skb)
473 			break;
474 
475 		if (__mptcp_check_fallback(msk)) {
476 			/* if we are running under the workqueue, TCP could have
477 			 * collapsed skbs between dummy map creation and now
478 			 * be sure to adjust the size
479 			 */
480 			map_remaining = skb->len;
481 			subflow->map_data_len = skb->len;
482 		}
483 
484 		offset = seq - TCP_SKB_CB(skb)->seq;
485 		fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
486 		if (fin) {
487 			done = true;
488 			seq++;
489 		}
490 
491 		if (offset < skb->len) {
492 			size_t len = skb->len - offset;
493 
494 			if (tp->urg_data)
495 				done = true;
496 
497 			if (__mptcp_move_skb(msk, ssk, skb, offset, len))
498 				moved += len;
499 			seq += len;
500 
501 			if (WARN_ON_ONCE(map_remaining < len))
502 				break;
503 		} else {
504 			WARN_ON_ONCE(!fin);
505 			sk_eat_skb(ssk, skb);
506 			done = true;
507 		}
508 
509 		WRITE_ONCE(tp->copied_seq, seq);
510 		more_data_avail = mptcp_subflow_data_available(ssk);
511 
512 		if (atomic_read(&sk->sk_rmem_alloc) > READ_ONCE(sk->sk_rcvbuf)) {
513 			done = true;
514 			break;
515 		}
516 	} while (more_data_avail);
517 
518 	*bytes += moved;
519 	if (moved)
520 		tcp_cleanup_rbuf(ssk, moved);
521 
522 	return done;
523 }
524 
525 static bool mptcp_ofo_queue(struct mptcp_sock *msk)
526 {
527 	struct sock *sk = (struct sock *)msk;
528 	struct sk_buff *skb, *tail;
529 	bool moved = false;
530 	struct rb_node *p;
531 	u64 end_seq;
532 
533 	p = rb_first(&msk->out_of_order_queue);
534 	pr_debug("msk=%p empty=%d", msk, RB_EMPTY_ROOT(&msk->out_of_order_queue));
535 	while (p) {
536 		skb = rb_to_skb(p);
537 		if (after64(MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq))
538 			break;
539 
540 		p = rb_next(p);
541 		rb_erase(&skb->rbnode, &msk->out_of_order_queue);
542 
543 		if (unlikely(!after64(MPTCP_SKB_CB(skb)->end_seq,
544 				      msk->ack_seq))) {
545 			mptcp_drop(sk, skb);
546 			MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
547 			continue;
548 		}
549 
550 		end_seq = MPTCP_SKB_CB(skb)->end_seq;
551 		tail = skb_peek_tail(&sk->sk_receive_queue);
552 		if (!tail || !mptcp_ooo_try_coalesce(msk, tail, skb)) {
553 			int delta = msk->ack_seq - MPTCP_SKB_CB(skb)->map_seq;
554 
555 			/* skip overlapping data, if any */
556 			pr_debug("uncoalesced seq=%llx ack seq=%llx delta=%d",
557 				 MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq,
558 				 delta);
559 			MPTCP_SKB_CB(skb)->offset += delta;
560 			__skb_queue_tail(&sk->sk_receive_queue, skb);
561 		}
562 		msk->ack_seq = end_seq;
563 		moved = true;
564 	}
565 	return moved;
566 }
567 
568 /* In most cases we will be able to lock the mptcp socket.  If its already
569  * owned, we need to defer to the work queue to avoid ABBA deadlock.
570  */
571 static bool move_skbs_to_msk(struct mptcp_sock *msk, struct sock *ssk)
572 {
573 	struct sock *sk = (struct sock *)msk;
574 	unsigned int moved = 0;
575 
576 	if (READ_ONCE(sk->sk_lock.owned))
577 		return false;
578 
579 	if (unlikely(!spin_trylock_bh(&sk->sk_lock.slock)))
580 		return false;
581 
582 	/* must re-check after taking the lock */
583 	if (!READ_ONCE(sk->sk_lock.owned)) {
584 		__mptcp_move_skbs_from_subflow(msk, ssk, &moved);
585 		mptcp_ofo_queue(msk);
586 
587 		/* If the moves have caught up with the DATA_FIN sequence number
588 		 * it's time to ack the DATA_FIN and change socket state, but
589 		 * this is not a good place to change state. Let the workqueue
590 		 * do it.
591 		 */
592 		if (mptcp_pending_data_fin(sk, NULL) &&
593 		    schedule_work(&msk->work))
594 			sock_hold(sk);
595 	}
596 
597 	spin_unlock_bh(&sk->sk_lock.slock);
598 
599 	return moved > 0;
600 }
601 
602 void mptcp_data_ready(struct sock *sk, struct sock *ssk)
603 {
604 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
605 	struct mptcp_sock *msk = mptcp_sk(sk);
606 	bool wake;
607 
608 	/* move_skbs_to_msk below can legitly clear the data_avail flag,
609 	 * but we will need later to properly woke the reader, cache its
610 	 * value
611 	 */
612 	wake = subflow->data_avail == MPTCP_SUBFLOW_DATA_AVAIL;
613 	if (wake)
614 		set_bit(MPTCP_DATA_READY, &msk->flags);
615 
616 	if (atomic_read(&sk->sk_rmem_alloc) < READ_ONCE(sk->sk_rcvbuf) &&
617 	    move_skbs_to_msk(msk, ssk))
618 		goto wake;
619 
620 	/* don't schedule if mptcp sk is (still) over limit */
621 	if (atomic_read(&sk->sk_rmem_alloc) > READ_ONCE(sk->sk_rcvbuf))
622 		goto wake;
623 
624 	/* mptcp socket is owned, release_cb should retry */
625 	if (!test_and_set_bit(TCP_DELACK_TIMER_DEFERRED,
626 			      &sk->sk_tsq_flags)) {
627 		sock_hold(sk);
628 
629 		/* need to try again, its possible release_cb() has already
630 		 * been called after the test_and_set_bit() above.
631 		 */
632 		move_skbs_to_msk(msk, ssk);
633 	}
634 wake:
635 	if (wake)
636 		sk->sk_data_ready(sk);
637 }
638 
639 static void __mptcp_flush_join_list(struct mptcp_sock *msk)
640 {
641 	if (likely(list_empty(&msk->join_list)))
642 		return;
643 
644 	spin_lock_bh(&msk->join_list_lock);
645 	list_splice_tail_init(&msk->join_list, &msk->conn_list);
646 	spin_unlock_bh(&msk->join_list_lock);
647 }
648 
649 static bool mptcp_timer_pending(struct sock *sk)
650 {
651 	return timer_pending(&inet_csk(sk)->icsk_retransmit_timer);
652 }
653 
654 static void mptcp_reset_timer(struct sock *sk)
655 {
656 	struct inet_connection_sock *icsk = inet_csk(sk);
657 	unsigned long tout;
658 
659 	/* should never be called with mptcp level timer cleared */
660 	tout = READ_ONCE(mptcp_sk(sk)->timer_ival);
661 	if (WARN_ON_ONCE(!tout))
662 		tout = TCP_RTO_MIN;
663 	sk_reset_timer(sk, &icsk->icsk_retransmit_timer, jiffies + tout);
664 }
665 
666 void mptcp_data_acked(struct sock *sk)
667 {
668 	mptcp_reset_timer(sk);
669 
670 	if ((!test_bit(MPTCP_SEND_SPACE, &mptcp_sk(sk)->flags) ||
671 	     (inet_sk_state_load(sk) != TCP_ESTABLISHED)) &&
672 	    schedule_work(&mptcp_sk(sk)->work))
673 		sock_hold(sk);
674 }
675 
676 void mptcp_subflow_eof(struct sock *sk)
677 {
678 	struct mptcp_sock *msk = mptcp_sk(sk);
679 
680 	if (!test_and_set_bit(MPTCP_WORK_EOF, &msk->flags) &&
681 	    schedule_work(&msk->work))
682 		sock_hold(sk);
683 }
684 
685 static void mptcp_check_for_eof(struct mptcp_sock *msk)
686 {
687 	struct mptcp_subflow_context *subflow;
688 	struct sock *sk = (struct sock *)msk;
689 	int receivers = 0;
690 
691 	mptcp_for_each_subflow(msk, subflow)
692 		receivers += !subflow->rx_eof;
693 
694 	if (!receivers && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
695 		/* hopefully temporary hack: propagate shutdown status
696 		 * to msk, when all subflows agree on it
697 		 */
698 		sk->sk_shutdown |= RCV_SHUTDOWN;
699 
700 		smp_mb__before_atomic(); /* SHUTDOWN must be visible first */
701 		set_bit(MPTCP_DATA_READY, &msk->flags);
702 		sk->sk_data_ready(sk);
703 	}
704 }
705 
706 static bool mptcp_ext_cache_refill(struct mptcp_sock *msk)
707 {
708 	const struct sock *sk = (const struct sock *)msk;
709 
710 	if (!msk->cached_ext)
711 		msk->cached_ext = __skb_ext_alloc(sk->sk_allocation);
712 
713 	return !!msk->cached_ext;
714 }
715 
716 static struct sock *mptcp_subflow_recv_lookup(const struct mptcp_sock *msk)
717 {
718 	struct mptcp_subflow_context *subflow;
719 	struct sock *sk = (struct sock *)msk;
720 
721 	sock_owned_by_me(sk);
722 
723 	mptcp_for_each_subflow(msk, subflow) {
724 		if (subflow->data_avail)
725 			return mptcp_subflow_tcp_sock(subflow);
726 	}
727 
728 	return NULL;
729 }
730 
731 static bool mptcp_skb_can_collapse_to(u64 write_seq,
732 				      const struct sk_buff *skb,
733 				      const struct mptcp_ext *mpext)
734 {
735 	if (!tcp_skb_can_collapse_to(skb))
736 		return false;
737 
738 	/* can collapse only if MPTCP level sequence is in order */
739 	return mpext && mpext->data_seq + mpext->data_len == write_seq;
740 }
741 
742 static bool mptcp_frag_can_collapse_to(const struct mptcp_sock *msk,
743 				       const struct page_frag *pfrag,
744 				       const struct mptcp_data_frag *df)
745 {
746 	return df && pfrag->page == df->page &&
747 		df->data_seq + df->data_len == msk->write_seq;
748 }
749 
750 static void dfrag_uncharge(struct sock *sk, int len)
751 {
752 	sk_mem_uncharge(sk, len);
753 	sk_wmem_queued_add(sk, -len);
754 }
755 
756 static void dfrag_clear(struct sock *sk, struct mptcp_data_frag *dfrag)
757 {
758 	int len = dfrag->data_len + dfrag->overhead;
759 
760 	list_del(&dfrag->list);
761 	dfrag_uncharge(sk, len);
762 	put_page(dfrag->page);
763 }
764 
765 static bool mptcp_is_writeable(struct mptcp_sock *msk)
766 {
767 	struct mptcp_subflow_context *subflow;
768 
769 	if (!sk_stream_is_writeable((struct sock *)msk))
770 		return false;
771 
772 	mptcp_for_each_subflow(msk, subflow) {
773 		if (sk_stream_is_writeable(subflow->tcp_sock))
774 			return true;
775 	}
776 	return false;
777 }
778 
779 static void mptcp_clean_una(struct sock *sk)
780 {
781 	struct mptcp_sock *msk = mptcp_sk(sk);
782 	struct mptcp_data_frag *dtmp, *dfrag;
783 	bool cleaned = false;
784 	u64 snd_una;
785 
786 	/* on fallback we just need to ignore snd_una, as this is really
787 	 * plain TCP
788 	 */
789 	if (__mptcp_check_fallback(msk))
790 		atomic64_set(&msk->snd_una, msk->write_seq);
791 	snd_una = atomic64_read(&msk->snd_una);
792 
793 	list_for_each_entry_safe(dfrag, dtmp, &msk->rtx_queue, list) {
794 		if (after64(dfrag->data_seq + dfrag->data_len, snd_una))
795 			break;
796 
797 		dfrag_clear(sk, dfrag);
798 		cleaned = true;
799 	}
800 
801 	dfrag = mptcp_rtx_head(sk);
802 	if (dfrag && after64(snd_una, dfrag->data_seq)) {
803 		u64 delta = snd_una - dfrag->data_seq;
804 
805 		if (WARN_ON_ONCE(delta > dfrag->data_len))
806 			goto out;
807 
808 		dfrag->data_seq += delta;
809 		dfrag->offset += delta;
810 		dfrag->data_len -= delta;
811 
812 		dfrag_uncharge(sk, delta);
813 		cleaned = true;
814 	}
815 
816 out:
817 	if (cleaned) {
818 		sk_mem_reclaim_partial(sk);
819 
820 		/* Only wake up writers if a subflow is ready */
821 		if (mptcp_is_writeable(msk)) {
822 			set_bit(MPTCP_SEND_SPACE, &mptcp_sk(sk)->flags);
823 			smp_mb__after_atomic();
824 
825 			/* set SEND_SPACE before sk_stream_write_space clears
826 			 * NOSPACE
827 			 */
828 			sk_stream_write_space(sk);
829 		}
830 	}
831 }
832 
833 /* ensure we get enough memory for the frag hdr, beyond some minimal amount of
834  * data
835  */
836 static bool mptcp_page_frag_refill(struct sock *sk, struct page_frag *pfrag)
837 {
838 	if (likely(skb_page_frag_refill(32U + sizeof(struct mptcp_data_frag),
839 					pfrag, sk->sk_allocation)))
840 		return true;
841 
842 	sk->sk_prot->enter_memory_pressure(sk);
843 	sk_stream_moderate_sndbuf(sk);
844 	return false;
845 }
846 
847 static struct mptcp_data_frag *
848 mptcp_carve_data_frag(const struct mptcp_sock *msk, struct page_frag *pfrag,
849 		      int orig_offset)
850 {
851 	int offset = ALIGN(orig_offset, sizeof(long));
852 	struct mptcp_data_frag *dfrag;
853 
854 	dfrag = (struct mptcp_data_frag *)(page_to_virt(pfrag->page) + offset);
855 	dfrag->data_len = 0;
856 	dfrag->data_seq = msk->write_seq;
857 	dfrag->overhead = offset - orig_offset + sizeof(struct mptcp_data_frag);
858 	dfrag->offset = offset + sizeof(struct mptcp_data_frag);
859 	dfrag->page = pfrag->page;
860 
861 	return dfrag;
862 }
863 
864 static int mptcp_sendmsg_frag(struct sock *sk, struct sock *ssk,
865 			      struct msghdr *msg, struct mptcp_data_frag *dfrag,
866 			      long *timeo, int *pmss_now,
867 			      int *ps_goal)
868 {
869 	int mss_now, avail_size, size_goal, offset, ret, frag_truesize = 0;
870 	bool dfrag_collapsed, can_collapse = false;
871 	struct mptcp_sock *msk = mptcp_sk(sk);
872 	struct mptcp_ext *mpext = NULL;
873 	bool retransmission = !!dfrag;
874 	struct sk_buff *skb, *tail;
875 	struct page_frag *pfrag;
876 	struct page *page;
877 	u64 *write_seq;
878 	size_t psize;
879 
880 	/* use the mptcp page cache so that we can easily move the data
881 	 * from one substream to another, but do per subflow memory accounting
882 	 * Note: pfrag is used only !retransmission, but the compiler if
883 	 * fooled into a warning if we don't init here
884 	 */
885 	pfrag = sk_page_frag(sk);
886 	if (!retransmission) {
887 		write_seq = &msk->write_seq;
888 		page = pfrag->page;
889 	} else {
890 		write_seq = &dfrag->data_seq;
891 		page = dfrag->page;
892 	}
893 
894 	/* compute copy limit */
895 	mss_now = tcp_send_mss(ssk, &size_goal, msg->msg_flags);
896 	*pmss_now = mss_now;
897 	*ps_goal = size_goal;
898 	avail_size = size_goal;
899 	skb = tcp_write_queue_tail(ssk);
900 	if (skb) {
901 		mpext = skb_ext_find(skb, SKB_EXT_MPTCP);
902 
903 		/* Limit the write to the size available in the
904 		 * current skb, if any, so that we create at most a new skb.
905 		 * Explicitly tells TCP internals to avoid collapsing on later
906 		 * queue management operation, to avoid breaking the ext <->
907 		 * SSN association set here
908 		 */
909 		can_collapse = (size_goal - skb->len > 0) &&
910 			      mptcp_skb_can_collapse_to(*write_seq, skb, mpext);
911 		if (!can_collapse)
912 			TCP_SKB_CB(skb)->eor = 1;
913 		else
914 			avail_size = size_goal - skb->len;
915 	}
916 
917 	if (!retransmission) {
918 		/* reuse tail pfrag, if possible, or carve a new one from the
919 		 * page allocator
920 		 */
921 		dfrag = mptcp_rtx_tail(sk);
922 		offset = pfrag->offset;
923 		dfrag_collapsed = mptcp_frag_can_collapse_to(msk, pfrag, dfrag);
924 		if (!dfrag_collapsed) {
925 			dfrag = mptcp_carve_data_frag(msk, pfrag, offset);
926 			offset = dfrag->offset;
927 			frag_truesize = dfrag->overhead;
928 		}
929 		psize = min_t(size_t, pfrag->size - offset, avail_size);
930 
931 		/* Copy to page */
932 		pr_debug("left=%zu", msg_data_left(msg));
933 		psize = copy_page_from_iter(pfrag->page, offset,
934 					    min_t(size_t, msg_data_left(msg),
935 						  psize),
936 					    &msg->msg_iter);
937 		pr_debug("left=%zu", msg_data_left(msg));
938 		if (!psize)
939 			return -EINVAL;
940 
941 		if (!sk_wmem_schedule(sk, psize + dfrag->overhead)) {
942 			iov_iter_revert(&msg->msg_iter, psize);
943 			return -ENOMEM;
944 		}
945 	} else {
946 		offset = dfrag->offset;
947 		psize = min_t(size_t, dfrag->data_len, avail_size);
948 	}
949 
950 	/* tell the TCP stack to delay the push so that we can safely
951 	 * access the skb after the sendpages call
952 	 */
953 	ret = do_tcp_sendpages(ssk, page, offset, psize,
954 			       msg->msg_flags | MSG_SENDPAGE_NOTLAST | MSG_DONTWAIT);
955 	if (ret <= 0) {
956 		if (!retransmission)
957 			iov_iter_revert(&msg->msg_iter, psize);
958 		return ret;
959 	}
960 
961 	frag_truesize += ret;
962 	if (!retransmission) {
963 		if (unlikely(ret < psize))
964 			iov_iter_revert(&msg->msg_iter, psize - ret);
965 
966 		/* send successful, keep track of sent data for mptcp-level
967 		 * retransmission
968 		 */
969 		dfrag->data_len += ret;
970 		if (!dfrag_collapsed) {
971 			get_page(dfrag->page);
972 			list_add_tail(&dfrag->list, &msk->rtx_queue);
973 			sk_wmem_queued_add(sk, frag_truesize);
974 		} else {
975 			sk_wmem_queued_add(sk, ret);
976 		}
977 
978 		/* charge data on mptcp rtx queue to the master socket
979 		 * Note: we charge such data both to sk and ssk
980 		 */
981 		sk->sk_forward_alloc -= frag_truesize;
982 	}
983 
984 	/* if the tail skb extension is still the cached one, collapsing
985 	 * really happened. Note: we can't check for 'same skb' as the sk_buff
986 	 * hdr on tail can be transmitted, freed and re-allocated by the
987 	 * do_tcp_sendpages() call
988 	 */
989 	tail = tcp_write_queue_tail(ssk);
990 	if (mpext && tail && mpext == skb_ext_find(tail, SKB_EXT_MPTCP)) {
991 		WARN_ON_ONCE(!can_collapse);
992 		mpext->data_len += ret;
993 		goto out;
994 	}
995 
996 	skb = tcp_write_queue_tail(ssk);
997 	mpext = __skb_ext_set(skb, SKB_EXT_MPTCP, msk->cached_ext);
998 	msk->cached_ext = NULL;
999 
1000 	memset(mpext, 0, sizeof(*mpext));
1001 	mpext->data_seq = *write_seq;
1002 	mpext->subflow_seq = mptcp_subflow_ctx(ssk)->rel_write_seq;
1003 	mpext->data_len = ret;
1004 	mpext->use_map = 1;
1005 	mpext->dsn64 = 1;
1006 
1007 	pr_debug("data_seq=%llu subflow_seq=%u data_len=%u dsn64=%d",
1008 		 mpext->data_seq, mpext->subflow_seq, mpext->data_len,
1009 		 mpext->dsn64);
1010 
1011 out:
1012 	if (!retransmission)
1013 		pfrag->offset += frag_truesize;
1014 	WRITE_ONCE(*write_seq, *write_seq + ret);
1015 	mptcp_subflow_ctx(ssk)->rel_write_seq += ret;
1016 
1017 	return ret;
1018 }
1019 
1020 static void mptcp_nospace(struct mptcp_sock *msk)
1021 {
1022 	struct mptcp_subflow_context *subflow;
1023 
1024 	clear_bit(MPTCP_SEND_SPACE, &msk->flags);
1025 	smp_mb__after_atomic(); /* msk->flags is changed by write_space cb */
1026 
1027 	mptcp_for_each_subflow(msk, subflow) {
1028 		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
1029 		struct socket *sock = READ_ONCE(ssk->sk_socket);
1030 
1031 		/* enables ssk->write_space() callbacks */
1032 		if (sock)
1033 			set_bit(SOCK_NOSPACE, &sock->flags);
1034 	}
1035 }
1036 
1037 static bool mptcp_subflow_active(struct mptcp_subflow_context *subflow)
1038 {
1039 	struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
1040 
1041 	/* can't send if JOIN hasn't completed yet (i.e. is usable for mptcp) */
1042 	if (subflow->request_join && !subflow->fully_established)
1043 		return false;
1044 
1045 	/* only send if our side has not closed yet */
1046 	return ((1 << ssk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT));
1047 }
1048 
1049 #define MPTCP_SEND_BURST_SIZE		((1 << 16) - \
1050 					 sizeof(struct tcphdr) - \
1051 					 MAX_TCP_OPTION_SPACE - \
1052 					 sizeof(struct ipv6hdr) - \
1053 					 sizeof(struct frag_hdr))
1054 
1055 struct subflow_send_info {
1056 	struct sock *ssk;
1057 	u64 ratio;
1058 };
1059 
1060 static struct sock *mptcp_subflow_get_send(struct mptcp_sock *msk,
1061 					   u32 *sndbuf)
1062 {
1063 	struct subflow_send_info send_info[2];
1064 	struct mptcp_subflow_context *subflow;
1065 	int i, nr_active = 0;
1066 	struct sock *ssk;
1067 	u64 ratio;
1068 	u32 pace;
1069 
1070 	sock_owned_by_me((struct sock *)msk);
1071 
1072 	*sndbuf = 0;
1073 	if (!mptcp_ext_cache_refill(msk))
1074 		return NULL;
1075 
1076 	if (__mptcp_check_fallback(msk)) {
1077 		if (!msk->first)
1078 			return NULL;
1079 		*sndbuf = msk->first->sk_sndbuf;
1080 		return sk_stream_memory_free(msk->first) ? msk->first : NULL;
1081 	}
1082 
1083 	/* re-use last subflow, if the burst allow that */
1084 	if (msk->last_snd && msk->snd_burst > 0 &&
1085 	    sk_stream_memory_free(msk->last_snd) &&
1086 	    mptcp_subflow_active(mptcp_subflow_ctx(msk->last_snd))) {
1087 		mptcp_for_each_subflow(msk, subflow) {
1088 			ssk =  mptcp_subflow_tcp_sock(subflow);
1089 			*sndbuf = max(tcp_sk(ssk)->snd_wnd, *sndbuf);
1090 		}
1091 		return msk->last_snd;
1092 	}
1093 
1094 	/* pick the subflow with the lower wmem/wspace ratio */
1095 	for (i = 0; i < 2; ++i) {
1096 		send_info[i].ssk = NULL;
1097 		send_info[i].ratio = -1;
1098 	}
1099 	mptcp_for_each_subflow(msk, subflow) {
1100 		ssk =  mptcp_subflow_tcp_sock(subflow);
1101 		if (!mptcp_subflow_active(subflow))
1102 			continue;
1103 
1104 		nr_active += !subflow->backup;
1105 		*sndbuf = max(tcp_sk(ssk)->snd_wnd, *sndbuf);
1106 		if (!sk_stream_memory_free(subflow->tcp_sock))
1107 			continue;
1108 
1109 		pace = READ_ONCE(ssk->sk_pacing_rate);
1110 		if (!pace)
1111 			continue;
1112 
1113 		ratio = div_u64((u64)READ_ONCE(ssk->sk_wmem_queued) << 32,
1114 				pace);
1115 		if (ratio < send_info[subflow->backup].ratio) {
1116 			send_info[subflow->backup].ssk = ssk;
1117 			send_info[subflow->backup].ratio = ratio;
1118 		}
1119 	}
1120 
1121 	pr_debug("msk=%p nr_active=%d ssk=%p:%lld backup=%p:%lld",
1122 		 msk, nr_active, send_info[0].ssk, send_info[0].ratio,
1123 		 send_info[1].ssk, send_info[1].ratio);
1124 
1125 	/* pick the best backup if no other subflow is active */
1126 	if (!nr_active)
1127 		send_info[0].ssk = send_info[1].ssk;
1128 
1129 	if (send_info[0].ssk) {
1130 		msk->last_snd = send_info[0].ssk;
1131 		msk->snd_burst = min_t(int, MPTCP_SEND_BURST_SIZE,
1132 				       sk_stream_wspace(msk->last_snd));
1133 		return msk->last_snd;
1134 	}
1135 	return NULL;
1136 }
1137 
1138 static void ssk_check_wmem(struct mptcp_sock *msk)
1139 {
1140 	if (unlikely(!mptcp_is_writeable(msk)))
1141 		mptcp_nospace(msk);
1142 }
1143 
1144 static int mptcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1145 {
1146 	int mss_now = 0, size_goal = 0, ret = 0;
1147 	struct mptcp_sock *msk = mptcp_sk(sk);
1148 	struct page_frag *pfrag;
1149 	size_t copied = 0;
1150 	struct sock *ssk;
1151 	u32 sndbuf;
1152 	bool tx_ok;
1153 	long timeo;
1154 
1155 	if (msg->msg_flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL))
1156 		return -EOPNOTSUPP;
1157 
1158 	lock_sock(sk);
1159 
1160 	timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1161 
1162 	if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) {
1163 		ret = sk_stream_wait_connect(sk, &timeo);
1164 		if (ret)
1165 			goto out;
1166 	}
1167 
1168 	pfrag = sk_page_frag(sk);
1169 restart:
1170 	mptcp_clean_una(sk);
1171 
1172 	if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) {
1173 		ret = -EPIPE;
1174 		goto out;
1175 	}
1176 
1177 	__mptcp_flush_join_list(msk);
1178 	ssk = mptcp_subflow_get_send(msk, &sndbuf);
1179 	while (!sk_stream_memory_free(sk) ||
1180 	       !ssk ||
1181 	       !mptcp_page_frag_refill(ssk, pfrag)) {
1182 		if (ssk) {
1183 			/* make sure retransmit timer is
1184 			 * running before we wait for memory.
1185 			 *
1186 			 * The retransmit timer might be needed
1187 			 * to make the peer send an up-to-date
1188 			 * MPTCP Ack.
1189 			 */
1190 			mptcp_set_timeout(sk, ssk);
1191 			if (!mptcp_timer_pending(sk))
1192 				mptcp_reset_timer(sk);
1193 		}
1194 
1195 		mptcp_nospace(msk);
1196 		ret = sk_stream_wait_memory(sk, &timeo);
1197 		if (ret)
1198 			goto out;
1199 
1200 		mptcp_clean_una(sk);
1201 
1202 		ssk = mptcp_subflow_get_send(msk, &sndbuf);
1203 		if (list_empty(&msk->conn_list)) {
1204 			ret = -ENOTCONN;
1205 			goto out;
1206 		}
1207 	}
1208 
1209 	/* do auto tuning */
1210 	if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK) &&
1211 	    sndbuf > READ_ONCE(sk->sk_sndbuf))
1212 		WRITE_ONCE(sk->sk_sndbuf, sndbuf);
1213 
1214 	pr_debug("conn_list->subflow=%p", ssk);
1215 
1216 	lock_sock(ssk);
1217 	tx_ok = msg_data_left(msg);
1218 	while (tx_ok) {
1219 		ret = mptcp_sendmsg_frag(sk, ssk, msg, NULL, &timeo, &mss_now,
1220 					 &size_goal);
1221 		if (ret < 0) {
1222 			if (ret == -EAGAIN && timeo > 0) {
1223 				mptcp_set_timeout(sk, ssk);
1224 				release_sock(ssk);
1225 				goto restart;
1226 			}
1227 			break;
1228 		}
1229 
1230 		/* burst can be negative, we will try move to the next subflow
1231 		 * at selection time, if possible.
1232 		 */
1233 		msk->snd_burst -= ret;
1234 		copied += ret;
1235 
1236 		tx_ok = msg_data_left(msg);
1237 		if (!tx_ok)
1238 			break;
1239 
1240 		if (!sk_stream_memory_free(ssk) ||
1241 		    !mptcp_page_frag_refill(ssk, pfrag) ||
1242 		    !mptcp_ext_cache_refill(msk)) {
1243 			tcp_push(ssk, msg->msg_flags, mss_now,
1244 				 tcp_sk(ssk)->nonagle, size_goal);
1245 			mptcp_set_timeout(sk, ssk);
1246 			release_sock(ssk);
1247 			goto restart;
1248 		}
1249 
1250 		/* memory is charged to mptcp level socket as well, i.e.
1251 		 * if msg is very large, mptcp socket may run out of buffer
1252 		 * space.  mptcp_clean_una() will release data that has
1253 		 * been acked at mptcp level in the mean time, so there is
1254 		 * a good chance we can continue sending data right away.
1255 		 *
1256 		 * Normally, when the tcp subflow can accept more data, then
1257 		 * so can the MPTCP socket.  However, we need to cope with
1258 		 * peers that might lag behind in their MPTCP-level
1259 		 * acknowledgements, i.e.  data might have been acked at
1260 		 * tcp level only.  So, we must also check the MPTCP socket
1261 		 * limits before we send more data.
1262 		 */
1263 		if (unlikely(!sk_stream_memory_free(sk))) {
1264 			tcp_push(ssk, msg->msg_flags, mss_now,
1265 				 tcp_sk(ssk)->nonagle, size_goal);
1266 			mptcp_clean_una(sk);
1267 			if (!sk_stream_memory_free(sk)) {
1268 				/* can't send more for now, need to wait for
1269 				 * MPTCP-level ACKs from peer.
1270 				 *
1271 				 * Wakeup will happen via mptcp_clean_una().
1272 				 */
1273 				mptcp_set_timeout(sk, ssk);
1274 				release_sock(ssk);
1275 				goto restart;
1276 			}
1277 		}
1278 	}
1279 
1280 	mptcp_set_timeout(sk, ssk);
1281 	if (copied) {
1282 		tcp_push(ssk, msg->msg_flags, mss_now, tcp_sk(ssk)->nonagle,
1283 			 size_goal);
1284 
1285 		/* start the timer, if it's not pending */
1286 		if (!mptcp_timer_pending(sk))
1287 			mptcp_reset_timer(sk);
1288 	}
1289 
1290 	release_sock(ssk);
1291 out:
1292 	ssk_check_wmem(msk);
1293 	release_sock(sk);
1294 	return copied ? : ret;
1295 }
1296 
1297 static void mptcp_wait_data(struct sock *sk, long *timeo)
1298 {
1299 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1300 	struct mptcp_sock *msk = mptcp_sk(sk);
1301 
1302 	add_wait_queue(sk_sleep(sk), &wait);
1303 	sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1304 
1305 	sk_wait_event(sk, timeo,
1306 		      test_and_clear_bit(MPTCP_DATA_READY, &msk->flags), &wait);
1307 
1308 	sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1309 	remove_wait_queue(sk_sleep(sk), &wait);
1310 }
1311 
1312 static int __mptcp_recvmsg_mskq(struct mptcp_sock *msk,
1313 				struct msghdr *msg,
1314 				size_t len)
1315 {
1316 	struct sock *sk = (struct sock *)msk;
1317 	struct sk_buff *skb;
1318 	int copied = 0;
1319 
1320 	while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
1321 		u32 offset = MPTCP_SKB_CB(skb)->offset;
1322 		u32 data_len = skb->len - offset;
1323 		u32 count = min_t(size_t, len - copied, data_len);
1324 		int err;
1325 
1326 		err = skb_copy_datagram_msg(skb, offset, msg, count);
1327 		if (unlikely(err < 0)) {
1328 			if (!copied)
1329 				return err;
1330 			break;
1331 		}
1332 
1333 		copied += count;
1334 
1335 		if (count < data_len) {
1336 			MPTCP_SKB_CB(skb)->offset += count;
1337 			break;
1338 		}
1339 
1340 		__skb_unlink(skb, &sk->sk_receive_queue);
1341 		__kfree_skb(skb);
1342 
1343 		if (copied >= len)
1344 			break;
1345 	}
1346 
1347 	return copied;
1348 }
1349 
1350 /* receive buffer autotuning.  See tcp_rcv_space_adjust for more information.
1351  *
1352  * Only difference: Use highest rtt estimate of the subflows in use.
1353  */
1354 static void mptcp_rcv_space_adjust(struct mptcp_sock *msk, int copied)
1355 {
1356 	struct mptcp_subflow_context *subflow;
1357 	struct sock *sk = (struct sock *)msk;
1358 	u32 time, advmss = 1;
1359 	u64 rtt_us, mstamp;
1360 
1361 	sock_owned_by_me(sk);
1362 
1363 	if (copied <= 0)
1364 		return;
1365 
1366 	msk->rcvq_space.copied += copied;
1367 
1368 	mstamp = div_u64(tcp_clock_ns(), NSEC_PER_USEC);
1369 	time = tcp_stamp_us_delta(mstamp, msk->rcvq_space.time);
1370 
1371 	rtt_us = msk->rcvq_space.rtt_us;
1372 	if (rtt_us && time < (rtt_us >> 3))
1373 		return;
1374 
1375 	rtt_us = 0;
1376 	mptcp_for_each_subflow(msk, subflow) {
1377 		const struct tcp_sock *tp;
1378 		u64 sf_rtt_us;
1379 		u32 sf_advmss;
1380 
1381 		tp = tcp_sk(mptcp_subflow_tcp_sock(subflow));
1382 
1383 		sf_rtt_us = READ_ONCE(tp->rcv_rtt_est.rtt_us);
1384 		sf_advmss = READ_ONCE(tp->advmss);
1385 
1386 		rtt_us = max(sf_rtt_us, rtt_us);
1387 		advmss = max(sf_advmss, advmss);
1388 	}
1389 
1390 	msk->rcvq_space.rtt_us = rtt_us;
1391 	if (time < (rtt_us >> 3) || rtt_us == 0)
1392 		return;
1393 
1394 	if (msk->rcvq_space.copied <= msk->rcvq_space.space)
1395 		goto new_measure;
1396 
1397 	if (sock_net(sk)->ipv4.sysctl_tcp_moderate_rcvbuf &&
1398 	    !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
1399 		int rcvmem, rcvbuf;
1400 		u64 rcvwin, grow;
1401 
1402 		rcvwin = ((u64)msk->rcvq_space.copied << 1) + 16 * advmss;
1403 
1404 		grow = rcvwin * (msk->rcvq_space.copied - msk->rcvq_space.space);
1405 
1406 		do_div(grow, msk->rcvq_space.space);
1407 		rcvwin += (grow << 1);
1408 
1409 		rcvmem = SKB_TRUESIZE(advmss + MAX_TCP_HEADER);
1410 		while (tcp_win_from_space(sk, rcvmem) < advmss)
1411 			rcvmem += 128;
1412 
1413 		do_div(rcvwin, advmss);
1414 		rcvbuf = min_t(u64, rcvwin * rcvmem,
1415 			       sock_net(sk)->ipv4.sysctl_tcp_rmem[2]);
1416 
1417 		if (rcvbuf > sk->sk_rcvbuf) {
1418 			u32 window_clamp;
1419 
1420 			window_clamp = tcp_win_from_space(sk, rcvbuf);
1421 			WRITE_ONCE(sk->sk_rcvbuf, rcvbuf);
1422 
1423 			/* Make subflows follow along.  If we do not do this, we
1424 			 * get drops at subflow level if skbs can't be moved to
1425 			 * the mptcp rx queue fast enough (announced rcv_win can
1426 			 * exceed ssk->sk_rcvbuf).
1427 			 */
1428 			mptcp_for_each_subflow(msk, subflow) {
1429 				struct sock *ssk;
1430 				bool slow;
1431 
1432 				ssk = mptcp_subflow_tcp_sock(subflow);
1433 				slow = lock_sock_fast(ssk);
1434 				WRITE_ONCE(ssk->sk_rcvbuf, rcvbuf);
1435 				tcp_sk(ssk)->window_clamp = window_clamp;
1436 				tcp_cleanup_rbuf(ssk, 1);
1437 				unlock_sock_fast(ssk, slow);
1438 			}
1439 		}
1440 	}
1441 
1442 	msk->rcvq_space.space = msk->rcvq_space.copied;
1443 new_measure:
1444 	msk->rcvq_space.copied = 0;
1445 	msk->rcvq_space.time = mstamp;
1446 }
1447 
1448 static bool __mptcp_move_skbs(struct mptcp_sock *msk)
1449 {
1450 	unsigned int moved = 0;
1451 	bool done;
1452 
1453 	/* avoid looping forever below on racing close */
1454 	if (((struct sock *)msk)->sk_state == TCP_CLOSE)
1455 		return false;
1456 
1457 	__mptcp_flush_join_list(msk);
1458 	do {
1459 		struct sock *ssk = mptcp_subflow_recv_lookup(msk);
1460 
1461 		if (!ssk)
1462 			break;
1463 
1464 		lock_sock(ssk);
1465 		done = __mptcp_move_skbs_from_subflow(msk, ssk, &moved);
1466 		release_sock(ssk);
1467 	} while (!done);
1468 
1469 	if (mptcp_ofo_queue(msk) || moved > 0) {
1470 		mptcp_check_data_fin((struct sock *)msk);
1471 		return true;
1472 	}
1473 	return false;
1474 }
1475 
1476 static int mptcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
1477 			 int nonblock, int flags, int *addr_len)
1478 {
1479 	struct mptcp_sock *msk = mptcp_sk(sk);
1480 	int copied = 0;
1481 	int target;
1482 	long timeo;
1483 
1484 	if (msg->msg_flags & ~(MSG_WAITALL | MSG_DONTWAIT))
1485 		return -EOPNOTSUPP;
1486 
1487 	lock_sock(sk);
1488 	timeo = sock_rcvtimeo(sk, nonblock);
1489 
1490 	len = min_t(size_t, len, INT_MAX);
1491 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
1492 	__mptcp_flush_join_list(msk);
1493 
1494 	while (len > (size_t)copied) {
1495 		int bytes_read;
1496 
1497 		bytes_read = __mptcp_recvmsg_mskq(msk, msg, len - copied);
1498 		if (unlikely(bytes_read < 0)) {
1499 			if (!copied)
1500 				copied = bytes_read;
1501 			goto out_err;
1502 		}
1503 
1504 		copied += bytes_read;
1505 
1506 		if (skb_queue_empty(&sk->sk_receive_queue) &&
1507 		    __mptcp_move_skbs(msk))
1508 			continue;
1509 
1510 		/* only the master socket status is relevant here. The exit
1511 		 * conditions mirror closely tcp_recvmsg()
1512 		 */
1513 		if (copied >= target)
1514 			break;
1515 
1516 		if (copied) {
1517 			if (sk->sk_err ||
1518 			    sk->sk_state == TCP_CLOSE ||
1519 			    (sk->sk_shutdown & RCV_SHUTDOWN) ||
1520 			    !timeo ||
1521 			    signal_pending(current))
1522 				break;
1523 		} else {
1524 			if (sk->sk_err) {
1525 				copied = sock_error(sk);
1526 				break;
1527 			}
1528 
1529 			if (test_and_clear_bit(MPTCP_WORK_EOF, &msk->flags))
1530 				mptcp_check_for_eof(msk);
1531 
1532 			if (sk->sk_shutdown & RCV_SHUTDOWN)
1533 				break;
1534 
1535 			if (sk->sk_state == TCP_CLOSE) {
1536 				copied = -ENOTCONN;
1537 				break;
1538 			}
1539 
1540 			if (!timeo) {
1541 				copied = -EAGAIN;
1542 				break;
1543 			}
1544 
1545 			if (signal_pending(current)) {
1546 				copied = sock_intr_errno(timeo);
1547 				break;
1548 			}
1549 		}
1550 
1551 		pr_debug("block timeout %ld", timeo);
1552 		mptcp_wait_data(sk, &timeo);
1553 	}
1554 
1555 	if (skb_queue_empty(&sk->sk_receive_queue)) {
1556 		/* entire backlog drained, clear DATA_READY. */
1557 		clear_bit(MPTCP_DATA_READY, &msk->flags);
1558 
1559 		/* .. race-breaker: ssk might have gotten new data
1560 		 * after last __mptcp_move_skbs() returned false.
1561 		 */
1562 		if (unlikely(__mptcp_move_skbs(msk)))
1563 			set_bit(MPTCP_DATA_READY, &msk->flags);
1564 	} else if (unlikely(!test_bit(MPTCP_DATA_READY, &msk->flags))) {
1565 		/* data to read but mptcp_wait_data() cleared DATA_READY */
1566 		set_bit(MPTCP_DATA_READY, &msk->flags);
1567 	}
1568 out_err:
1569 	pr_debug("msk=%p data_ready=%d rx queue empty=%d copied=%d",
1570 		 msk, test_bit(MPTCP_DATA_READY, &msk->flags),
1571 		 skb_queue_empty(&sk->sk_receive_queue), copied);
1572 	mptcp_rcv_space_adjust(msk, copied);
1573 
1574 	release_sock(sk);
1575 	return copied;
1576 }
1577 
1578 static void mptcp_retransmit_handler(struct sock *sk)
1579 {
1580 	struct mptcp_sock *msk = mptcp_sk(sk);
1581 
1582 	if (atomic64_read(&msk->snd_una) == READ_ONCE(msk->write_seq)) {
1583 		mptcp_stop_timer(sk);
1584 	} else {
1585 		set_bit(MPTCP_WORK_RTX, &msk->flags);
1586 		if (schedule_work(&msk->work))
1587 			sock_hold(sk);
1588 	}
1589 }
1590 
1591 static void mptcp_retransmit_timer(struct timer_list *t)
1592 {
1593 	struct inet_connection_sock *icsk = from_timer(icsk, t,
1594 						       icsk_retransmit_timer);
1595 	struct sock *sk = &icsk->icsk_inet.sk;
1596 
1597 	bh_lock_sock(sk);
1598 	if (!sock_owned_by_user(sk)) {
1599 		mptcp_retransmit_handler(sk);
1600 	} else {
1601 		/* delegate our work to tcp_release_cb() */
1602 		if (!test_and_set_bit(TCP_WRITE_TIMER_DEFERRED,
1603 				      &sk->sk_tsq_flags))
1604 			sock_hold(sk);
1605 	}
1606 	bh_unlock_sock(sk);
1607 	sock_put(sk);
1608 }
1609 
1610 /* Find an idle subflow.  Return NULL if there is unacked data at tcp
1611  * level.
1612  *
1613  * A backup subflow is returned only if that is the only kind available.
1614  */
1615 static struct sock *mptcp_subflow_get_retrans(const struct mptcp_sock *msk)
1616 {
1617 	struct mptcp_subflow_context *subflow;
1618 	struct sock *backup = NULL;
1619 
1620 	sock_owned_by_me((const struct sock *)msk);
1621 
1622 	if (__mptcp_check_fallback(msk))
1623 		return msk->first;
1624 
1625 	mptcp_for_each_subflow(msk, subflow) {
1626 		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
1627 
1628 		if (!mptcp_subflow_active(subflow))
1629 			continue;
1630 
1631 		/* still data outstanding at TCP level?  Don't retransmit. */
1632 		if (!tcp_write_queue_empty(ssk))
1633 			return NULL;
1634 
1635 		if (subflow->backup) {
1636 			if (!backup)
1637 				backup = ssk;
1638 			continue;
1639 		}
1640 
1641 		return ssk;
1642 	}
1643 
1644 	return backup;
1645 }
1646 
1647 /* subflow sockets can be either outgoing (connect) or incoming
1648  * (accept).
1649  *
1650  * Outgoing subflows use in-kernel sockets.
1651  * Incoming subflows do not have their own 'struct socket' allocated,
1652  * so we need to use tcp_close() after detaching them from the mptcp
1653  * parent socket.
1654  */
1655 void __mptcp_close_ssk(struct sock *sk, struct sock *ssk,
1656 		       struct mptcp_subflow_context *subflow,
1657 		       long timeout)
1658 {
1659 	struct socket *sock = READ_ONCE(ssk->sk_socket);
1660 
1661 	list_del(&subflow->node);
1662 
1663 	if (sock && sock != sk->sk_socket) {
1664 		/* outgoing subflow */
1665 		sock_release(sock);
1666 	} else {
1667 		/* incoming subflow */
1668 		tcp_close(ssk, timeout);
1669 	}
1670 }
1671 
1672 static unsigned int mptcp_sync_mss(struct sock *sk, u32 pmtu)
1673 {
1674 	return 0;
1675 }
1676 
1677 static void pm_work(struct mptcp_sock *msk)
1678 {
1679 	struct mptcp_pm_data *pm = &msk->pm;
1680 
1681 	spin_lock_bh(&msk->pm.lock);
1682 
1683 	pr_debug("msk=%p status=%x", msk, pm->status);
1684 	if (pm->status & BIT(MPTCP_PM_ADD_ADDR_RECEIVED)) {
1685 		pm->status &= ~BIT(MPTCP_PM_ADD_ADDR_RECEIVED);
1686 		mptcp_pm_nl_add_addr_received(msk);
1687 	}
1688 	if (pm->status & BIT(MPTCP_PM_RM_ADDR_RECEIVED)) {
1689 		pm->status &= ~BIT(MPTCP_PM_RM_ADDR_RECEIVED);
1690 		mptcp_pm_nl_rm_addr_received(msk);
1691 	}
1692 	if (pm->status & BIT(MPTCP_PM_ESTABLISHED)) {
1693 		pm->status &= ~BIT(MPTCP_PM_ESTABLISHED);
1694 		mptcp_pm_nl_fully_established(msk);
1695 	}
1696 	if (pm->status & BIT(MPTCP_PM_SUBFLOW_ESTABLISHED)) {
1697 		pm->status &= ~BIT(MPTCP_PM_SUBFLOW_ESTABLISHED);
1698 		mptcp_pm_nl_subflow_established(msk);
1699 	}
1700 
1701 	spin_unlock_bh(&msk->pm.lock);
1702 }
1703 
1704 static void mptcp_worker(struct work_struct *work)
1705 {
1706 	struct mptcp_sock *msk = container_of(work, struct mptcp_sock, work);
1707 	struct sock *ssk, *sk = &msk->sk.icsk_inet.sk;
1708 	int orig_len, orig_offset, mss_now = 0, size_goal = 0;
1709 	struct mptcp_data_frag *dfrag;
1710 	u64 orig_write_seq;
1711 	size_t copied = 0;
1712 	struct msghdr msg = {
1713 		.msg_flags = MSG_DONTWAIT,
1714 	};
1715 	long timeo = 0;
1716 
1717 	lock_sock(sk);
1718 	mptcp_clean_una(sk);
1719 	mptcp_check_data_fin_ack(sk);
1720 	__mptcp_flush_join_list(msk);
1721 	__mptcp_move_skbs(msk);
1722 
1723 	if (msk->pm.status)
1724 		pm_work(msk);
1725 
1726 	if (test_and_clear_bit(MPTCP_WORK_EOF, &msk->flags))
1727 		mptcp_check_for_eof(msk);
1728 
1729 	mptcp_check_data_fin(sk);
1730 
1731 	if (!test_and_clear_bit(MPTCP_WORK_RTX, &msk->flags))
1732 		goto unlock;
1733 
1734 	dfrag = mptcp_rtx_head(sk);
1735 	if (!dfrag)
1736 		goto unlock;
1737 
1738 	if (!mptcp_ext_cache_refill(msk))
1739 		goto reset_unlock;
1740 
1741 	ssk = mptcp_subflow_get_retrans(msk);
1742 	if (!ssk)
1743 		goto reset_unlock;
1744 
1745 	lock_sock(ssk);
1746 
1747 	orig_len = dfrag->data_len;
1748 	orig_offset = dfrag->offset;
1749 	orig_write_seq = dfrag->data_seq;
1750 	while (dfrag->data_len > 0) {
1751 		int ret = mptcp_sendmsg_frag(sk, ssk, &msg, dfrag, &timeo,
1752 					     &mss_now, &size_goal);
1753 		if (ret < 0)
1754 			break;
1755 
1756 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_RETRANSSEGS);
1757 		copied += ret;
1758 		dfrag->data_len -= ret;
1759 		dfrag->offset += ret;
1760 
1761 		if (!mptcp_ext_cache_refill(msk))
1762 			break;
1763 	}
1764 	if (copied)
1765 		tcp_push(ssk, msg.msg_flags, mss_now, tcp_sk(ssk)->nonagle,
1766 			 size_goal);
1767 
1768 	dfrag->data_seq = orig_write_seq;
1769 	dfrag->offset = orig_offset;
1770 	dfrag->data_len = orig_len;
1771 
1772 	mptcp_set_timeout(sk, ssk);
1773 	release_sock(ssk);
1774 
1775 reset_unlock:
1776 	if (!mptcp_timer_pending(sk))
1777 		mptcp_reset_timer(sk);
1778 
1779 unlock:
1780 	release_sock(sk);
1781 	sock_put(sk);
1782 }
1783 
1784 static int __mptcp_init_sock(struct sock *sk)
1785 {
1786 	struct mptcp_sock *msk = mptcp_sk(sk);
1787 
1788 	spin_lock_init(&msk->join_list_lock);
1789 
1790 	INIT_LIST_HEAD(&msk->conn_list);
1791 	INIT_LIST_HEAD(&msk->join_list);
1792 	INIT_LIST_HEAD(&msk->rtx_queue);
1793 	__set_bit(MPTCP_SEND_SPACE, &msk->flags);
1794 	INIT_WORK(&msk->work, mptcp_worker);
1795 	msk->out_of_order_queue = RB_ROOT;
1796 
1797 	msk->first = NULL;
1798 	inet_csk(sk)->icsk_sync_mss = mptcp_sync_mss;
1799 
1800 	mptcp_pm_data_init(msk);
1801 
1802 	/* re-use the csk retrans timer for MPTCP-level retrans */
1803 	timer_setup(&msk->sk.icsk_retransmit_timer, mptcp_retransmit_timer, 0);
1804 
1805 	return 0;
1806 }
1807 
1808 static int mptcp_init_sock(struct sock *sk)
1809 {
1810 	struct net *net = sock_net(sk);
1811 	int ret;
1812 
1813 	ret = __mptcp_init_sock(sk);
1814 	if (ret)
1815 		return ret;
1816 
1817 	if (!mptcp_is_enabled(net))
1818 		return -ENOPROTOOPT;
1819 
1820 	if (unlikely(!net->mib.mptcp_statistics) && !mptcp_mib_alloc(net))
1821 		return -ENOMEM;
1822 
1823 	ret = __mptcp_socket_create(mptcp_sk(sk));
1824 	if (ret)
1825 		return ret;
1826 
1827 	sk_sockets_allocated_inc(sk);
1828 	sk->sk_rcvbuf = sock_net(sk)->ipv4.sysctl_tcp_rmem[1];
1829 	sk->sk_sndbuf = sock_net(sk)->ipv4.sysctl_tcp_wmem[1];
1830 
1831 	return 0;
1832 }
1833 
1834 static void __mptcp_clear_xmit(struct sock *sk)
1835 {
1836 	struct mptcp_sock *msk = mptcp_sk(sk);
1837 	struct mptcp_data_frag *dtmp, *dfrag;
1838 
1839 	sk_stop_timer(sk, &msk->sk.icsk_retransmit_timer);
1840 
1841 	list_for_each_entry_safe(dfrag, dtmp, &msk->rtx_queue, list)
1842 		dfrag_clear(sk, dfrag);
1843 }
1844 
1845 static void mptcp_cancel_work(struct sock *sk)
1846 {
1847 	struct mptcp_sock *msk = mptcp_sk(sk);
1848 
1849 	if (cancel_work_sync(&msk->work))
1850 		sock_put(sk);
1851 }
1852 
1853 void mptcp_subflow_shutdown(struct sock *sk, struct sock *ssk, int how)
1854 {
1855 	lock_sock(ssk);
1856 
1857 	switch (ssk->sk_state) {
1858 	case TCP_LISTEN:
1859 		if (!(how & RCV_SHUTDOWN))
1860 			break;
1861 		fallthrough;
1862 	case TCP_SYN_SENT:
1863 		tcp_disconnect(ssk, O_NONBLOCK);
1864 		break;
1865 	default:
1866 		if (__mptcp_check_fallback(mptcp_sk(sk))) {
1867 			pr_debug("Fallback");
1868 			ssk->sk_shutdown |= how;
1869 			tcp_shutdown(ssk, how);
1870 		} else {
1871 			pr_debug("Sending DATA_FIN on subflow %p", ssk);
1872 			mptcp_set_timeout(sk, ssk);
1873 			tcp_send_ack(ssk);
1874 		}
1875 		break;
1876 	}
1877 
1878 	release_sock(ssk);
1879 }
1880 
1881 static const unsigned char new_state[16] = {
1882 	/* current state:     new state:      action:	*/
1883 	[0 /* (Invalid) */] = TCP_CLOSE,
1884 	[TCP_ESTABLISHED]   = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
1885 	[TCP_SYN_SENT]      = TCP_CLOSE,
1886 	[TCP_SYN_RECV]      = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
1887 	[TCP_FIN_WAIT1]     = TCP_FIN_WAIT1,
1888 	[TCP_FIN_WAIT2]     = TCP_FIN_WAIT2,
1889 	[TCP_TIME_WAIT]     = TCP_CLOSE,	/* should not happen ! */
1890 	[TCP_CLOSE]         = TCP_CLOSE,
1891 	[TCP_CLOSE_WAIT]    = TCP_LAST_ACK  | TCP_ACTION_FIN,
1892 	[TCP_LAST_ACK]      = TCP_LAST_ACK,
1893 	[TCP_LISTEN]        = TCP_CLOSE,
1894 	[TCP_CLOSING]       = TCP_CLOSING,
1895 	[TCP_NEW_SYN_RECV]  = TCP_CLOSE,	/* should not happen ! */
1896 };
1897 
1898 static int mptcp_close_state(struct sock *sk)
1899 {
1900 	int next = (int)new_state[sk->sk_state];
1901 	int ns = next & TCP_STATE_MASK;
1902 
1903 	inet_sk_state_store(sk, ns);
1904 
1905 	return next & TCP_ACTION_FIN;
1906 }
1907 
1908 static void mptcp_close(struct sock *sk, long timeout)
1909 {
1910 	struct mptcp_subflow_context *subflow, *tmp;
1911 	struct mptcp_sock *msk = mptcp_sk(sk);
1912 	LIST_HEAD(conn_list);
1913 
1914 	lock_sock(sk);
1915 	sk->sk_shutdown = SHUTDOWN_MASK;
1916 
1917 	if (sk->sk_state == TCP_LISTEN) {
1918 		inet_sk_state_store(sk, TCP_CLOSE);
1919 		goto cleanup;
1920 	} else if (sk->sk_state == TCP_CLOSE) {
1921 		goto cleanup;
1922 	}
1923 
1924 	if (__mptcp_check_fallback(msk)) {
1925 		goto update_state;
1926 	} else if (mptcp_close_state(sk)) {
1927 		pr_debug("Sending DATA_FIN sk=%p", sk);
1928 		WRITE_ONCE(msk->write_seq, msk->write_seq + 1);
1929 		WRITE_ONCE(msk->snd_data_fin_enable, 1);
1930 
1931 		mptcp_for_each_subflow(msk, subflow) {
1932 			struct sock *tcp_sk = mptcp_subflow_tcp_sock(subflow);
1933 
1934 			mptcp_subflow_shutdown(sk, tcp_sk, SHUTDOWN_MASK);
1935 		}
1936 	}
1937 
1938 	sk_stream_wait_close(sk, timeout);
1939 
1940 update_state:
1941 	inet_sk_state_store(sk, TCP_CLOSE);
1942 
1943 cleanup:
1944 	/* be sure to always acquire the join list lock, to sync vs
1945 	 * mptcp_finish_join().
1946 	 */
1947 	spin_lock_bh(&msk->join_list_lock);
1948 	list_splice_tail_init(&msk->join_list, &msk->conn_list);
1949 	spin_unlock_bh(&msk->join_list_lock);
1950 	list_splice_init(&msk->conn_list, &conn_list);
1951 
1952 	__mptcp_clear_xmit(sk);
1953 
1954 	release_sock(sk);
1955 
1956 	list_for_each_entry_safe(subflow, tmp, &conn_list, node) {
1957 		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
1958 		__mptcp_close_ssk(sk, ssk, subflow, timeout);
1959 	}
1960 
1961 	mptcp_cancel_work(sk);
1962 
1963 	__skb_queue_purge(&sk->sk_receive_queue);
1964 
1965 	sk_common_release(sk);
1966 }
1967 
1968 static void mptcp_copy_inaddrs(struct sock *msk, const struct sock *ssk)
1969 {
1970 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
1971 	const struct ipv6_pinfo *ssk6 = inet6_sk(ssk);
1972 	struct ipv6_pinfo *msk6 = inet6_sk(msk);
1973 
1974 	msk->sk_v6_daddr = ssk->sk_v6_daddr;
1975 	msk->sk_v6_rcv_saddr = ssk->sk_v6_rcv_saddr;
1976 
1977 	if (msk6 && ssk6) {
1978 		msk6->saddr = ssk6->saddr;
1979 		msk6->flow_label = ssk6->flow_label;
1980 	}
1981 #endif
1982 
1983 	inet_sk(msk)->inet_num = inet_sk(ssk)->inet_num;
1984 	inet_sk(msk)->inet_dport = inet_sk(ssk)->inet_dport;
1985 	inet_sk(msk)->inet_sport = inet_sk(ssk)->inet_sport;
1986 	inet_sk(msk)->inet_daddr = inet_sk(ssk)->inet_daddr;
1987 	inet_sk(msk)->inet_saddr = inet_sk(ssk)->inet_saddr;
1988 	inet_sk(msk)->inet_rcv_saddr = inet_sk(ssk)->inet_rcv_saddr;
1989 }
1990 
1991 static int mptcp_disconnect(struct sock *sk, int flags)
1992 {
1993 	/* Should never be called.
1994 	 * inet_stream_connect() calls ->disconnect, but that
1995 	 * refers to the subflow socket, not the mptcp one.
1996 	 */
1997 	WARN_ON_ONCE(1);
1998 	return 0;
1999 }
2000 
2001 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2002 static struct ipv6_pinfo *mptcp_inet6_sk(const struct sock *sk)
2003 {
2004 	unsigned int offset = sizeof(struct mptcp6_sock) - sizeof(struct ipv6_pinfo);
2005 
2006 	return (struct ipv6_pinfo *)(((u8 *)sk) + offset);
2007 }
2008 #endif
2009 
2010 struct sock *mptcp_sk_clone(const struct sock *sk,
2011 			    const struct mptcp_options_received *mp_opt,
2012 			    struct request_sock *req)
2013 {
2014 	struct mptcp_subflow_request_sock *subflow_req = mptcp_subflow_rsk(req);
2015 	struct sock *nsk = sk_clone_lock(sk, GFP_ATOMIC);
2016 	struct mptcp_sock *msk;
2017 	u64 ack_seq;
2018 
2019 	if (!nsk)
2020 		return NULL;
2021 
2022 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2023 	if (nsk->sk_family == AF_INET6)
2024 		inet_sk(nsk)->pinet6 = mptcp_inet6_sk(nsk);
2025 #endif
2026 
2027 	__mptcp_init_sock(nsk);
2028 
2029 	msk = mptcp_sk(nsk);
2030 	msk->local_key = subflow_req->local_key;
2031 	msk->token = subflow_req->token;
2032 	msk->subflow = NULL;
2033 	WRITE_ONCE(msk->fully_established, false);
2034 
2035 	msk->write_seq = subflow_req->idsn + 1;
2036 	atomic64_set(&msk->snd_una, msk->write_seq);
2037 	if (mp_opt->mp_capable) {
2038 		msk->can_ack = true;
2039 		msk->remote_key = mp_opt->sndr_key;
2040 		mptcp_crypto_key_sha(msk->remote_key, NULL, &ack_seq);
2041 		ack_seq++;
2042 		msk->ack_seq = ack_seq;
2043 	}
2044 
2045 	sock_reset_flag(nsk, SOCK_RCU_FREE);
2046 	/* will be fully established after successful MPC subflow creation */
2047 	inet_sk_state_store(nsk, TCP_SYN_RECV);
2048 	bh_unlock_sock(nsk);
2049 
2050 	/* keep a single reference */
2051 	__sock_put(nsk);
2052 	return nsk;
2053 }
2054 
2055 void mptcp_rcv_space_init(struct mptcp_sock *msk, const struct sock *ssk)
2056 {
2057 	const struct tcp_sock *tp = tcp_sk(ssk);
2058 
2059 	msk->rcvq_space.copied = 0;
2060 	msk->rcvq_space.rtt_us = 0;
2061 
2062 	msk->rcvq_space.time = tp->tcp_mstamp;
2063 
2064 	/* initial rcv_space offering made to peer */
2065 	msk->rcvq_space.space = min_t(u32, tp->rcv_wnd,
2066 				      TCP_INIT_CWND * tp->advmss);
2067 	if (msk->rcvq_space.space == 0)
2068 		msk->rcvq_space.space = TCP_INIT_CWND * TCP_MSS_DEFAULT;
2069 }
2070 
2071 static struct sock *mptcp_accept(struct sock *sk, int flags, int *err,
2072 				 bool kern)
2073 {
2074 	struct mptcp_sock *msk = mptcp_sk(sk);
2075 	struct socket *listener;
2076 	struct sock *newsk;
2077 
2078 	listener = __mptcp_nmpc_socket(msk);
2079 	if (WARN_ON_ONCE(!listener)) {
2080 		*err = -EINVAL;
2081 		return NULL;
2082 	}
2083 
2084 	pr_debug("msk=%p, listener=%p", msk, mptcp_subflow_ctx(listener->sk));
2085 	newsk = inet_csk_accept(listener->sk, flags, err, kern);
2086 	if (!newsk)
2087 		return NULL;
2088 
2089 	pr_debug("msk=%p, subflow is mptcp=%d", msk, sk_is_mptcp(newsk));
2090 	if (sk_is_mptcp(newsk)) {
2091 		struct mptcp_subflow_context *subflow;
2092 		struct sock *new_mptcp_sock;
2093 		struct sock *ssk = newsk;
2094 
2095 		subflow = mptcp_subflow_ctx(newsk);
2096 		new_mptcp_sock = subflow->conn;
2097 
2098 		/* is_mptcp should be false if subflow->conn is missing, see
2099 		 * subflow_syn_recv_sock()
2100 		 */
2101 		if (WARN_ON_ONCE(!new_mptcp_sock)) {
2102 			tcp_sk(newsk)->is_mptcp = 0;
2103 			return newsk;
2104 		}
2105 
2106 		/* acquire the 2nd reference for the owning socket */
2107 		sock_hold(new_mptcp_sock);
2108 
2109 		local_bh_disable();
2110 		bh_lock_sock(new_mptcp_sock);
2111 		msk = mptcp_sk(new_mptcp_sock);
2112 		msk->first = newsk;
2113 
2114 		newsk = new_mptcp_sock;
2115 		mptcp_copy_inaddrs(newsk, ssk);
2116 		list_add(&subflow->node, &msk->conn_list);
2117 
2118 		mptcp_rcv_space_init(msk, ssk);
2119 		bh_unlock_sock(new_mptcp_sock);
2120 
2121 		__MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_MPCAPABLEPASSIVEACK);
2122 		local_bh_enable();
2123 	} else {
2124 		MPTCP_INC_STATS(sock_net(sk),
2125 				MPTCP_MIB_MPCAPABLEPASSIVEFALLBACK);
2126 	}
2127 
2128 	return newsk;
2129 }
2130 
2131 void mptcp_destroy_common(struct mptcp_sock *msk)
2132 {
2133 	skb_rbtree_purge(&msk->out_of_order_queue);
2134 	mptcp_token_destroy(msk);
2135 	mptcp_pm_free_anno_list(msk);
2136 }
2137 
2138 static void mptcp_destroy(struct sock *sk)
2139 {
2140 	struct mptcp_sock *msk = mptcp_sk(sk);
2141 
2142 	if (msk->cached_ext)
2143 		__skb_ext_put(msk->cached_ext);
2144 
2145 	mptcp_destroy_common(msk);
2146 	sk_sockets_allocated_dec(sk);
2147 }
2148 
2149 static int mptcp_setsockopt_sol_socket(struct mptcp_sock *msk, int optname,
2150 				       sockptr_t optval, unsigned int optlen)
2151 {
2152 	struct sock *sk = (struct sock *)msk;
2153 	struct socket *ssock;
2154 	int ret;
2155 
2156 	switch (optname) {
2157 	case SO_REUSEPORT:
2158 	case SO_REUSEADDR:
2159 		lock_sock(sk);
2160 		ssock = __mptcp_nmpc_socket(msk);
2161 		if (!ssock) {
2162 			release_sock(sk);
2163 			return -EINVAL;
2164 		}
2165 
2166 		ret = sock_setsockopt(ssock, SOL_SOCKET, optname, optval, optlen);
2167 		if (ret == 0) {
2168 			if (optname == SO_REUSEPORT)
2169 				sk->sk_reuseport = ssock->sk->sk_reuseport;
2170 			else if (optname == SO_REUSEADDR)
2171 				sk->sk_reuse = ssock->sk->sk_reuse;
2172 		}
2173 		release_sock(sk);
2174 		return ret;
2175 	}
2176 
2177 	return sock_setsockopt(sk->sk_socket, SOL_SOCKET, optname, optval, optlen);
2178 }
2179 
2180 static int mptcp_setsockopt_v6(struct mptcp_sock *msk, int optname,
2181 			       sockptr_t optval, unsigned int optlen)
2182 {
2183 	struct sock *sk = (struct sock *)msk;
2184 	int ret = -EOPNOTSUPP;
2185 	struct socket *ssock;
2186 
2187 	switch (optname) {
2188 	case IPV6_V6ONLY:
2189 		lock_sock(sk);
2190 		ssock = __mptcp_nmpc_socket(msk);
2191 		if (!ssock) {
2192 			release_sock(sk);
2193 			return -EINVAL;
2194 		}
2195 
2196 		ret = tcp_setsockopt(ssock->sk, SOL_IPV6, optname, optval, optlen);
2197 		if (ret == 0)
2198 			sk->sk_ipv6only = ssock->sk->sk_ipv6only;
2199 
2200 		release_sock(sk);
2201 		break;
2202 	}
2203 
2204 	return ret;
2205 }
2206 
2207 static int mptcp_setsockopt(struct sock *sk, int level, int optname,
2208 			    sockptr_t optval, unsigned int optlen)
2209 {
2210 	struct mptcp_sock *msk = mptcp_sk(sk);
2211 	struct sock *ssk;
2212 
2213 	pr_debug("msk=%p", msk);
2214 
2215 	if (level == SOL_SOCKET)
2216 		return mptcp_setsockopt_sol_socket(msk, optname, optval, optlen);
2217 
2218 	/* @@ the meaning of setsockopt() when the socket is connected and
2219 	 * there are multiple subflows is not yet defined. It is up to the
2220 	 * MPTCP-level socket to configure the subflows until the subflow
2221 	 * is in TCP fallback, when TCP socket options are passed through
2222 	 * to the one remaining subflow.
2223 	 */
2224 	lock_sock(sk);
2225 	ssk = __mptcp_tcp_fallback(msk);
2226 	release_sock(sk);
2227 	if (ssk)
2228 		return tcp_setsockopt(ssk, level, optname, optval, optlen);
2229 
2230 	if (level == SOL_IPV6)
2231 		return mptcp_setsockopt_v6(msk, optname, optval, optlen);
2232 
2233 	return -EOPNOTSUPP;
2234 }
2235 
2236 static int mptcp_getsockopt(struct sock *sk, int level, int optname,
2237 			    char __user *optval, int __user *option)
2238 {
2239 	struct mptcp_sock *msk = mptcp_sk(sk);
2240 	struct sock *ssk;
2241 
2242 	pr_debug("msk=%p", msk);
2243 
2244 	/* @@ the meaning of setsockopt() when the socket is connected and
2245 	 * there are multiple subflows is not yet defined. It is up to the
2246 	 * MPTCP-level socket to configure the subflows until the subflow
2247 	 * is in TCP fallback, when socket options are passed through
2248 	 * to the one remaining subflow.
2249 	 */
2250 	lock_sock(sk);
2251 	ssk = __mptcp_tcp_fallback(msk);
2252 	release_sock(sk);
2253 	if (ssk)
2254 		return tcp_getsockopt(ssk, level, optname, optval, option);
2255 
2256 	return -EOPNOTSUPP;
2257 }
2258 
2259 #define MPTCP_DEFERRED_ALL (TCPF_DELACK_TIMER_DEFERRED | \
2260 			    TCPF_WRITE_TIMER_DEFERRED)
2261 
2262 /* this is very alike tcp_release_cb() but we must handle differently a
2263  * different set of events
2264  */
2265 static void mptcp_release_cb(struct sock *sk)
2266 {
2267 	unsigned long flags, nflags;
2268 
2269 	do {
2270 		flags = sk->sk_tsq_flags;
2271 		if (!(flags & MPTCP_DEFERRED_ALL))
2272 			return;
2273 		nflags = flags & ~MPTCP_DEFERRED_ALL;
2274 	} while (cmpxchg(&sk->sk_tsq_flags, flags, nflags) != flags);
2275 
2276 	sock_release_ownership(sk);
2277 
2278 	if (flags & TCPF_DELACK_TIMER_DEFERRED) {
2279 		struct mptcp_sock *msk = mptcp_sk(sk);
2280 		struct sock *ssk;
2281 
2282 		ssk = mptcp_subflow_recv_lookup(msk);
2283 		if (!ssk || !schedule_work(&msk->work))
2284 			__sock_put(sk);
2285 	}
2286 
2287 	if (flags & TCPF_WRITE_TIMER_DEFERRED) {
2288 		mptcp_retransmit_handler(sk);
2289 		__sock_put(sk);
2290 	}
2291 }
2292 
2293 static int mptcp_hash(struct sock *sk)
2294 {
2295 	/* should never be called,
2296 	 * we hash the TCP subflows not the master socket
2297 	 */
2298 	WARN_ON_ONCE(1);
2299 	return 0;
2300 }
2301 
2302 static void mptcp_unhash(struct sock *sk)
2303 {
2304 	/* called from sk_common_release(), but nothing to do here */
2305 }
2306 
2307 static int mptcp_get_port(struct sock *sk, unsigned short snum)
2308 {
2309 	struct mptcp_sock *msk = mptcp_sk(sk);
2310 	struct socket *ssock;
2311 
2312 	ssock = __mptcp_nmpc_socket(msk);
2313 	pr_debug("msk=%p, subflow=%p", msk, ssock);
2314 	if (WARN_ON_ONCE(!ssock))
2315 		return -EINVAL;
2316 
2317 	return inet_csk_get_port(ssock->sk, snum);
2318 }
2319 
2320 void mptcp_finish_connect(struct sock *ssk)
2321 {
2322 	struct mptcp_subflow_context *subflow;
2323 	struct mptcp_sock *msk;
2324 	struct sock *sk;
2325 	u64 ack_seq;
2326 
2327 	subflow = mptcp_subflow_ctx(ssk);
2328 	sk = subflow->conn;
2329 	msk = mptcp_sk(sk);
2330 
2331 	pr_debug("msk=%p, token=%u", sk, subflow->token);
2332 
2333 	mptcp_crypto_key_sha(subflow->remote_key, NULL, &ack_seq);
2334 	ack_seq++;
2335 	subflow->map_seq = ack_seq;
2336 	subflow->map_subflow_seq = 1;
2337 
2338 	/* the socket is not connected yet, no msk/subflow ops can access/race
2339 	 * accessing the field below
2340 	 */
2341 	WRITE_ONCE(msk->remote_key, subflow->remote_key);
2342 	WRITE_ONCE(msk->local_key, subflow->local_key);
2343 	WRITE_ONCE(msk->write_seq, subflow->idsn + 1);
2344 	WRITE_ONCE(msk->ack_seq, ack_seq);
2345 	WRITE_ONCE(msk->can_ack, 1);
2346 	atomic64_set(&msk->snd_una, msk->write_seq);
2347 
2348 	mptcp_pm_new_connection(msk, 0);
2349 
2350 	mptcp_rcv_space_init(msk, ssk);
2351 }
2352 
2353 static void mptcp_sock_graft(struct sock *sk, struct socket *parent)
2354 {
2355 	write_lock_bh(&sk->sk_callback_lock);
2356 	rcu_assign_pointer(sk->sk_wq, &parent->wq);
2357 	sk_set_socket(sk, parent);
2358 	sk->sk_uid = SOCK_INODE(parent)->i_uid;
2359 	write_unlock_bh(&sk->sk_callback_lock);
2360 }
2361 
2362 bool mptcp_finish_join(struct sock *sk)
2363 {
2364 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(sk);
2365 	struct mptcp_sock *msk = mptcp_sk(subflow->conn);
2366 	struct sock *parent = (void *)msk;
2367 	struct socket *parent_sock;
2368 	bool ret;
2369 
2370 	pr_debug("msk=%p, subflow=%p", msk, subflow);
2371 
2372 	/* mptcp socket already closing? */
2373 	if (!mptcp_is_fully_established(parent))
2374 		return false;
2375 
2376 	if (!msk->pm.server_side)
2377 		return true;
2378 
2379 	if (!mptcp_pm_allow_new_subflow(msk))
2380 		return false;
2381 
2382 	/* active connections are already on conn_list, and we can't acquire
2383 	 * msk lock here.
2384 	 * use the join list lock as synchronization point and double-check
2385 	 * msk status to avoid racing with mptcp_close()
2386 	 */
2387 	spin_lock_bh(&msk->join_list_lock);
2388 	ret = inet_sk_state_load(parent) == TCP_ESTABLISHED;
2389 	if (ret && !WARN_ON_ONCE(!list_empty(&subflow->node)))
2390 		list_add_tail(&subflow->node, &msk->join_list);
2391 	spin_unlock_bh(&msk->join_list_lock);
2392 	if (!ret)
2393 		return false;
2394 
2395 	/* attach to msk socket only after we are sure he will deal with us
2396 	 * at close time
2397 	 */
2398 	parent_sock = READ_ONCE(parent->sk_socket);
2399 	if (parent_sock && !sk->sk_socket)
2400 		mptcp_sock_graft(sk, parent_sock);
2401 	subflow->map_seq = msk->ack_seq;
2402 	return true;
2403 }
2404 
2405 static bool mptcp_memory_free(const struct sock *sk, int wake)
2406 {
2407 	struct mptcp_sock *msk = mptcp_sk(sk);
2408 
2409 	return wake ? test_bit(MPTCP_SEND_SPACE, &msk->flags) : true;
2410 }
2411 
2412 static struct proto mptcp_prot = {
2413 	.name		= "MPTCP",
2414 	.owner		= THIS_MODULE,
2415 	.init		= mptcp_init_sock,
2416 	.disconnect	= mptcp_disconnect,
2417 	.close		= mptcp_close,
2418 	.accept		= mptcp_accept,
2419 	.setsockopt	= mptcp_setsockopt,
2420 	.getsockopt	= mptcp_getsockopt,
2421 	.shutdown	= tcp_shutdown,
2422 	.destroy	= mptcp_destroy,
2423 	.sendmsg	= mptcp_sendmsg,
2424 	.recvmsg	= mptcp_recvmsg,
2425 	.release_cb	= mptcp_release_cb,
2426 	.hash		= mptcp_hash,
2427 	.unhash		= mptcp_unhash,
2428 	.get_port	= mptcp_get_port,
2429 	.sockets_allocated	= &mptcp_sockets_allocated,
2430 	.memory_allocated	= &tcp_memory_allocated,
2431 	.memory_pressure	= &tcp_memory_pressure,
2432 	.stream_memory_free	= mptcp_memory_free,
2433 	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_tcp_wmem),
2434 	.sysctl_mem	= sysctl_tcp_mem,
2435 	.obj_size	= sizeof(struct mptcp_sock),
2436 	.slab_flags	= SLAB_TYPESAFE_BY_RCU,
2437 	.no_autobind	= true,
2438 };
2439 
2440 static int mptcp_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
2441 {
2442 	struct mptcp_sock *msk = mptcp_sk(sock->sk);
2443 	struct socket *ssock;
2444 	int err;
2445 
2446 	lock_sock(sock->sk);
2447 	ssock = __mptcp_nmpc_socket(msk);
2448 	if (!ssock) {
2449 		err = -EINVAL;
2450 		goto unlock;
2451 	}
2452 
2453 	err = ssock->ops->bind(ssock, uaddr, addr_len);
2454 	if (!err)
2455 		mptcp_copy_inaddrs(sock->sk, ssock->sk);
2456 
2457 unlock:
2458 	release_sock(sock->sk);
2459 	return err;
2460 }
2461 
2462 static void mptcp_subflow_early_fallback(struct mptcp_sock *msk,
2463 					 struct mptcp_subflow_context *subflow)
2464 {
2465 	subflow->request_mptcp = 0;
2466 	__mptcp_do_fallback(msk);
2467 }
2468 
2469 static int mptcp_stream_connect(struct socket *sock, struct sockaddr *uaddr,
2470 				int addr_len, int flags)
2471 {
2472 	struct mptcp_sock *msk = mptcp_sk(sock->sk);
2473 	struct mptcp_subflow_context *subflow;
2474 	struct socket *ssock;
2475 	int err;
2476 
2477 	lock_sock(sock->sk);
2478 	if (sock->state != SS_UNCONNECTED && msk->subflow) {
2479 		/* pending connection or invalid state, let existing subflow
2480 		 * cope with that
2481 		 */
2482 		ssock = msk->subflow;
2483 		goto do_connect;
2484 	}
2485 
2486 	ssock = __mptcp_nmpc_socket(msk);
2487 	if (!ssock) {
2488 		err = -EINVAL;
2489 		goto unlock;
2490 	}
2491 
2492 	mptcp_token_destroy(msk);
2493 	inet_sk_state_store(sock->sk, TCP_SYN_SENT);
2494 	subflow = mptcp_subflow_ctx(ssock->sk);
2495 #ifdef CONFIG_TCP_MD5SIG
2496 	/* no MPTCP if MD5SIG is enabled on this socket or we may run out of
2497 	 * TCP option space.
2498 	 */
2499 	if (rcu_access_pointer(tcp_sk(ssock->sk)->md5sig_info))
2500 		mptcp_subflow_early_fallback(msk, subflow);
2501 #endif
2502 	if (subflow->request_mptcp && mptcp_token_new_connect(ssock->sk))
2503 		mptcp_subflow_early_fallback(msk, subflow);
2504 
2505 do_connect:
2506 	err = ssock->ops->connect(ssock, uaddr, addr_len, flags);
2507 	sock->state = ssock->state;
2508 
2509 	/* on successful connect, the msk state will be moved to established by
2510 	 * subflow_finish_connect()
2511 	 */
2512 	if (!err || err == -EINPROGRESS)
2513 		mptcp_copy_inaddrs(sock->sk, ssock->sk);
2514 	else
2515 		inet_sk_state_store(sock->sk, inet_sk_state_load(ssock->sk));
2516 
2517 unlock:
2518 	release_sock(sock->sk);
2519 	return err;
2520 }
2521 
2522 static int mptcp_listen(struct socket *sock, int backlog)
2523 {
2524 	struct mptcp_sock *msk = mptcp_sk(sock->sk);
2525 	struct socket *ssock;
2526 	int err;
2527 
2528 	pr_debug("msk=%p", msk);
2529 
2530 	lock_sock(sock->sk);
2531 	ssock = __mptcp_nmpc_socket(msk);
2532 	if (!ssock) {
2533 		err = -EINVAL;
2534 		goto unlock;
2535 	}
2536 
2537 	mptcp_token_destroy(msk);
2538 	inet_sk_state_store(sock->sk, TCP_LISTEN);
2539 	sock_set_flag(sock->sk, SOCK_RCU_FREE);
2540 
2541 	err = ssock->ops->listen(ssock, backlog);
2542 	inet_sk_state_store(sock->sk, inet_sk_state_load(ssock->sk));
2543 	if (!err)
2544 		mptcp_copy_inaddrs(sock->sk, ssock->sk);
2545 
2546 unlock:
2547 	release_sock(sock->sk);
2548 	return err;
2549 }
2550 
2551 static int mptcp_stream_accept(struct socket *sock, struct socket *newsock,
2552 			       int flags, bool kern)
2553 {
2554 	struct mptcp_sock *msk = mptcp_sk(sock->sk);
2555 	struct socket *ssock;
2556 	int err;
2557 
2558 	pr_debug("msk=%p", msk);
2559 
2560 	lock_sock(sock->sk);
2561 	if (sock->sk->sk_state != TCP_LISTEN)
2562 		goto unlock_fail;
2563 
2564 	ssock = __mptcp_nmpc_socket(msk);
2565 	if (!ssock)
2566 		goto unlock_fail;
2567 
2568 	clear_bit(MPTCP_DATA_READY, &msk->flags);
2569 	sock_hold(ssock->sk);
2570 	release_sock(sock->sk);
2571 
2572 	err = ssock->ops->accept(sock, newsock, flags, kern);
2573 	if (err == 0 && !mptcp_is_tcpsk(newsock->sk)) {
2574 		struct mptcp_sock *msk = mptcp_sk(newsock->sk);
2575 		struct mptcp_subflow_context *subflow;
2576 
2577 		/* set ssk->sk_socket of accept()ed flows to mptcp socket.
2578 		 * This is needed so NOSPACE flag can be set from tcp stack.
2579 		 */
2580 		__mptcp_flush_join_list(msk);
2581 		mptcp_for_each_subflow(msk, subflow) {
2582 			struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
2583 
2584 			if (!ssk->sk_socket)
2585 				mptcp_sock_graft(ssk, newsock);
2586 		}
2587 	}
2588 
2589 	if (inet_csk_listen_poll(ssock->sk))
2590 		set_bit(MPTCP_DATA_READY, &msk->flags);
2591 	sock_put(ssock->sk);
2592 	return err;
2593 
2594 unlock_fail:
2595 	release_sock(sock->sk);
2596 	return -EINVAL;
2597 }
2598 
2599 static __poll_t mptcp_check_readable(struct mptcp_sock *msk)
2600 {
2601 	return test_bit(MPTCP_DATA_READY, &msk->flags) ? EPOLLIN | EPOLLRDNORM :
2602 	       0;
2603 }
2604 
2605 static __poll_t mptcp_poll(struct file *file, struct socket *sock,
2606 			   struct poll_table_struct *wait)
2607 {
2608 	struct sock *sk = sock->sk;
2609 	struct mptcp_sock *msk;
2610 	__poll_t mask = 0;
2611 	int state;
2612 
2613 	msk = mptcp_sk(sk);
2614 	sock_poll_wait(file, sock, wait);
2615 
2616 	state = inet_sk_state_load(sk);
2617 	pr_debug("msk=%p state=%d flags=%lx", msk, state, msk->flags);
2618 	if (state == TCP_LISTEN)
2619 		return mptcp_check_readable(msk);
2620 
2621 	if (state != TCP_SYN_SENT && state != TCP_SYN_RECV) {
2622 		mask |= mptcp_check_readable(msk);
2623 		if (test_bit(MPTCP_SEND_SPACE, &msk->flags))
2624 			mask |= EPOLLOUT | EPOLLWRNORM;
2625 	}
2626 	if (sk->sk_shutdown & RCV_SHUTDOWN)
2627 		mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
2628 
2629 	return mask;
2630 }
2631 
2632 static int mptcp_shutdown(struct socket *sock, int how)
2633 {
2634 	struct mptcp_sock *msk = mptcp_sk(sock->sk);
2635 	struct mptcp_subflow_context *subflow;
2636 	int ret = 0;
2637 
2638 	pr_debug("sk=%p, how=%d", msk, how);
2639 
2640 	lock_sock(sock->sk);
2641 
2642 	how++;
2643 	if ((how & ~SHUTDOWN_MASK) || !how) {
2644 		ret = -EINVAL;
2645 		goto out_unlock;
2646 	}
2647 
2648 	if (sock->state == SS_CONNECTING) {
2649 		if ((1 << sock->sk->sk_state) &
2650 		    (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE))
2651 			sock->state = SS_DISCONNECTING;
2652 		else
2653 			sock->state = SS_CONNECTED;
2654 	}
2655 
2656 	/* If we've already sent a FIN, or it's a closed state, skip this. */
2657 	if (__mptcp_check_fallback(msk)) {
2658 		if (how == SHUT_WR || how == SHUT_RDWR)
2659 			inet_sk_state_store(sock->sk, TCP_FIN_WAIT1);
2660 
2661 		mptcp_for_each_subflow(msk, subflow) {
2662 			struct sock *tcp_sk = mptcp_subflow_tcp_sock(subflow);
2663 
2664 			mptcp_subflow_shutdown(sock->sk, tcp_sk, how);
2665 		}
2666 	} else if ((how & SEND_SHUTDOWN) &&
2667 		   ((1 << sock->sk->sk_state) &
2668 		    (TCPF_ESTABLISHED | TCPF_SYN_SENT |
2669 		     TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) &&
2670 		   mptcp_close_state(sock->sk)) {
2671 		__mptcp_flush_join_list(msk);
2672 
2673 		WRITE_ONCE(msk->write_seq, msk->write_seq + 1);
2674 		WRITE_ONCE(msk->snd_data_fin_enable, 1);
2675 
2676 		mptcp_for_each_subflow(msk, subflow) {
2677 			struct sock *tcp_sk = mptcp_subflow_tcp_sock(subflow);
2678 
2679 			mptcp_subflow_shutdown(sock->sk, tcp_sk, how);
2680 		}
2681 	}
2682 
2683 	/* Wake up anyone sleeping in poll. */
2684 	sock->sk->sk_state_change(sock->sk);
2685 
2686 out_unlock:
2687 	release_sock(sock->sk);
2688 
2689 	return ret;
2690 }
2691 
2692 static const struct proto_ops mptcp_stream_ops = {
2693 	.family		   = PF_INET,
2694 	.owner		   = THIS_MODULE,
2695 	.release	   = inet_release,
2696 	.bind		   = mptcp_bind,
2697 	.connect	   = mptcp_stream_connect,
2698 	.socketpair	   = sock_no_socketpair,
2699 	.accept		   = mptcp_stream_accept,
2700 	.getname	   = inet_getname,
2701 	.poll		   = mptcp_poll,
2702 	.ioctl		   = inet_ioctl,
2703 	.gettstamp	   = sock_gettstamp,
2704 	.listen		   = mptcp_listen,
2705 	.shutdown	   = mptcp_shutdown,
2706 	.setsockopt	   = sock_common_setsockopt,
2707 	.getsockopt	   = sock_common_getsockopt,
2708 	.sendmsg	   = inet_sendmsg,
2709 	.recvmsg	   = inet_recvmsg,
2710 	.mmap		   = sock_no_mmap,
2711 	.sendpage	   = inet_sendpage,
2712 };
2713 
2714 static struct inet_protosw mptcp_protosw = {
2715 	.type		= SOCK_STREAM,
2716 	.protocol	= IPPROTO_MPTCP,
2717 	.prot		= &mptcp_prot,
2718 	.ops		= &mptcp_stream_ops,
2719 	.flags		= INET_PROTOSW_ICSK,
2720 };
2721 
2722 void __init mptcp_proto_init(void)
2723 {
2724 	mptcp_prot.h.hashinfo = tcp_prot.h.hashinfo;
2725 
2726 	if (percpu_counter_init(&mptcp_sockets_allocated, 0, GFP_KERNEL))
2727 		panic("Failed to allocate MPTCP pcpu counter\n");
2728 
2729 	mptcp_subflow_init();
2730 	mptcp_pm_init();
2731 	mptcp_token_init();
2732 
2733 	if (proto_register(&mptcp_prot, 1) != 0)
2734 		panic("Failed to register MPTCP proto.\n");
2735 
2736 	inet_register_protosw(&mptcp_protosw);
2737 
2738 	BUILD_BUG_ON(sizeof(struct mptcp_skb_cb) > sizeof_field(struct sk_buff, cb));
2739 }
2740 
2741 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2742 static const struct proto_ops mptcp_v6_stream_ops = {
2743 	.family		   = PF_INET6,
2744 	.owner		   = THIS_MODULE,
2745 	.release	   = inet6_release,
2746 	.bind		   = mptcp_bind,
2747 	.connect	   = mptcp_stream_connect,
2748 	.socketpair	   = sock_no_socketpair,
2749 	.accept		   = mptcp_stream_accept,
2750 	.getname	   = inet6_getname,
2751 	.poll		   = mptcp_poll,
2752 	.ioctl		   = inet6_ioctl,
2753 	.gettstamp	   = sock_gettstamp,
2754 	.listen		   = mptcp_listen,
2755 	.shutdown	   = mptcp_shutdown,
2756 	.setsockopt	   = sock_common_setsockopt,
2757 	.getsockopt	   = sock_common_getsockopt,
2758 	.sendmsg	   = inet6_sendmsg,
2759 	.recvmsg	   = inet6_recvmsg,
2760 	.mmap		   = sock_no_mmap,
2761 	.sendpage	   = inet_sendpage,
2762 #ifdef CONFIG_COMPAT
2763 	.compat_ioctl	   = inet6_compat_ioctl,
2764 #endif
2765 };
2766 
2767 static struct proto mptcp_v6_prot;
2768 
2769 static void mptcp_v6_destroy(struct sock *sk)
2770 {
2771 	mptcp_destroy(sk);
2772 	inet6_destroy_sock(sk);
2773 }
2774 
2775 static struct inet_protosw mptcp_v6_protosw = {
2776 	.type		= SOCK_STREAM,
2777 	.protocol	= IPPROTO_MPTCP,
2778 	.prot		= &mptcp_v6_prot,
2779 	.ops		= &mptcp_v6_stream_ops,
2780 	.flags		= INET_PROTOSW_ICSK,
2781 };
2782 
2783 int __init mptcp_proto_v6_init(void)
2784 {
2785 	int err;
2786 
2787 	mptcp_v6_prot = mptcp_prot;
2788 	strcpy(mptcp_v6_prot.name, "MPTCPv6");
2789 	mptcp_v6_prot.slab = NULL;
2790 	mptcp_v6_prot.destroy = mptcp_v6_destroy;
2791 	mptcp_v6_prot.obj_size = sizeof(struct mptcp6_sock);
2792 
2793 	err = proto_register(&mptcp_v6_prot, 1);
2794 	if (err)
2795 		return err;
2796 
2797 	err = inet6_register_protosw(&mptcp_v6_protosw);
2798 	if (err)
2799 		proto_unregister(&mptcp_v6_prot);
2800 
2801 	return err;
2802 }
2803 #endif
2804