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