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