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