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