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