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