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