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