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