xref: /linux/net/mptcp/subflow.c (revision d1e879ec600f9b3bdd253167533959facfefb17b)
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 <crypto/sha2.h>
13 #include <crypto/utils.h>
14 #include <net/sock.h>
15 #include <net/inet_common.h>
16 #include <net/inet_hashtables.h>
17 #include <net/protocol.h>
18 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
19 #include <net/ip6_route.h>
20 #include <net/transp_v6.h>
21 #endif
22 #include <net/mptcp.h>
23 
24 #include "protocol.h"
25 #include "mib.h"
26 
27 #include <trace/events/mptcp.h>
28 #include <trace/events/sock.h>
29 
30 static void mptcp_subflow_ops_undo_override(struct sock *ssk);
31 
32 static void SUBFLOW_REQ_INC_STATS(struct request_sock *req,
33 				  enum linux_mptcp_mib_field field)
34 {
35 	MPTCP_INC_STATS(sock_net(req_to_sk(req)), field);
36 }
37 
38 static void subflow_req_destructor(struct request_sock *req)
39 {
40 	struct mptcp_subflow_request_sock *subflow_req = mptcp_subflow_rsk(req);
41 
42 	pr_debug("subflow_req=%p\n", subflow_req);
43 
44 	if (subflow_req->msk)
45 		sock_put((struct sock *)subflow_req->msk);
46 
47 	mptcp_token_destroy_request(req);
48 }
49 
50 static void subflow_generate_hmac(u64 key1, u64 key2, u32 nonce1, u32 nonce2,
51 				  void *hmac)
52 {
53 	u8 msg[8];
54 
55 	put_unaligned_be32(nonce1, &msg[0]);
56 	put_unaligned_be32(nonce2, &msg[4]);
57 
58 	mptcp_crypto_hmac_sha(key1, key2, msg, 8, hmac);
59 }
60 
61 static bool mptcp_can_accept_new_subflow(const struct mptcp_sock *msk)
62 {
63 	return mptcp_is_fully_established((void *)msk) &&
64 		((mptcp_pm_is_userspace(msk) &&
65 		  mptcp_userspace_pm_active(msk)) ||
66 		 READ_ONCE(msk->pm.accept_subflow));
67 }
68 
69 /* validate received token and create truncated hmac and nonce for SYN-ACK */
70 static void subflow_req_create_thmac(struct mptcp_subflow_request_sock *subflow_req)
71 {
72 	struct mptcp_sock *msk = subflow_req->msk;
73 	u8 hmac[SHA256_DIGEST_SIZE];
74 
75 	get_random_bytes(&subflow_req->local_nonce, sizeof(u32));
76 
77 	subflow_generate_hmac(READ_ONCE(msk->local_key),
78 			      READ_ONCE(msk->remote_key),
79 			      subflow_req->local_nonce,
80 			      subflow_req->remote_nonce, hmac);
81 
82 	subflow_req->thmac = get_unaligned_be64(hmac);
83 }
84 
85 static struct mptcp_sock *subflow_token_join_request(struct request_sock *req)
86 {
87 	struct mptcp_subflow_request_sock *subflow_req = mptcp_subflow_rsk(req);
88 	struct mptcp_sock *msk;
89 	int local_id;
90 
91 	msk = mptcp_token_get_sock(sock_net(req_to_sk(req)), subflow_req->token);
92 	if (!msk) {
93 		SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINNOTOKEN);
94 		return NULL;
95 	}
96 
97 	local_id = mptcp_pm_get_local_id(msk, (struct sock_common *)req);
98 	if (local_id < 0) {
99 		sock_put((struct sock *)msk);
100 		return NULL;
101 	}
102 	subflow_req->local_id = local_id;
103 	subflow_req->request_bkup = mptcp_pm_is_backup(msk, (struct sock_common *)req);
104 
105 	return msk;
106 }
107 
108 static void subflow_init_req(struct request_sock *req, const struct sock *sk_listener)
109 {
110 	struct mptcp_subflow_request_sock *subflow_req = mptcp_subflow_rsk(req);
111 
112 	subflow_req->mp_capable = 0;
113 	subflow_req->mp_join = 0;
114 	subflow_req->csum_reqd = mptcp_is_checksum_enabled(sock_net(sk_listener));
115 	subflow_req->allow_join_id0 = mptcp_allow_join_id0(sock_net(sk_listener));
116 	subflow_req->msk = NULL;
117 	mptcp_token_init_request(req);
118 }
119 
120 static bool subflow_use_different_sport(struct mptcp_sock *msk, const struct sock *sk)
121 {
122 	return inet_sk(sk)->inet_sport != inet_sk((struct sock *)msk)->inet_sport;
123 }
124 
125 static void subflow_add_reset_reason(struct sk_buff *skb, u8 reason)
126 {
127 	struct mptcp_ext *mpext = skb_ext_add(skb, SKB_EXT_MPTCP);
128 
129 	if (mpext) {
130 		memset(mpext, 0, sizeof(*mpext));
131 		mpext->reset_reason = reason;
132 	}
133 }
134 
135 static int subflow_reset_req_endp(struct request_sock *req, struct sk_buff *skb)
136 {
137 	SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_MPCAPABLEENDPATTEMPT);
138 	subflow_add_reset_reason(skb, MPTCP_RST_EPROHIBIT);
139 	return -EPERM;
140 }
141 
142 /* Init mptcp request socket.
143  *
144  * Returns an error code if a JOIN has failed and a TCP reset
145  * should be sent.
146  */
147 static int subflow_check_req(struct request_sock *req,
148 			     const struct sock *sk_listener,
149 			     struct sk_buff *skb)
150 {
151 	struct mptcp_subflow_context *listener = mptcp_subflow_ctx(sk_listener);
152 	struct mptcp_subflow_request_sock *subflow_req = mptcp_subflow_rsk(req);
153 	struct mptcp_options_received mp_opt;
154 	bool opt_mp_capable, opt_mp_join;
155 
156 	pr_debug("subflow_req=%p, listener=%p\n", subflow_req, listener);
157 
158 #ifdef CONFIG_TCP_MD5SIG
159 	/* no MPTCP if MD5SIG is enabled on this socket or we may run out of
160 	 * TCP option space.
161 	 */
162 	if (rcu_access_pointer(tcp_sk(sk_listener)->md5sig_info)) {
163 		subflow_add_reset_reason(skb, MPTCP_RST_EMPTCP);
164 		return -EINVAL;
165 	}
166 #endif
167 
168 	mptcp_get_options(skb, &mp_opt);
169 
170 	opt_mp_capable = !!(mp_opt.suboptions & OPTION_MPTCP_MPC_SYN);
171 	opt_mp_join = !!(mp_opt.suboptions & OPTION_MPTCP_MPJ_SYN);
172 	if (opt_mp_capable) {
173 		SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_MPCAPABLEPASSIVE);
174 
175 		if (unlikely(listener->pm_listener))
176 			return subflow_reset_req_endp(req, skb);
177 		if (opt_mp_join)
178 			return 0;
179 	} else if (opt_mp_join) {
180 		SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINSYNRX);
181 
182 		if (mp_opt.backup)
183 			SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINSYNBACKUPRX);
184 	} else if (unlikely(listener->pm_listener)) {
185 		return subflow_reset_req_endp(req, skb);
186 	}
187 
188 	if (opt_mp_capable && listener->request_mptcp) {
189 		int err, retries = MPTCP_TOKEN_MAX_RETRIES;
190 
191 		subflow_req->ssn_offset = TCP_SKB_CB(skb)->seq;
192 again:
193 		do {
194 			get_random_bytes(&subflow_req->local_key, sizeof(subflow_req->local_key));
195 		} while (subflow_req->local_key == 0);
196 
197 		if (unlikely(req->syncookie)) {
198 			mptcp_crypto_key_sha(subflow_req->local_key,
199 					     &subflow_req->token,
200 					     &subflow_req->idsn);
201 			if (mptcp_token_exists(subflow_req->token)) {
202 				if (retries-- > 0)
203 					goto again;
204 				SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_TOKENFALLBACKINIT);
205 			} else {
206 				subflow_req->mp_capable = 1;
207 			}
208 			return 0;
209 		}
210 
211 		err = mptcp_token_new_request(req);
212 		if (err == 0)
213 			subflow_req->mp_capable = 1;
214 		else if (retries-- > 0)
215 			goto again;
216 		else
217 			SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_TOKENFALLBACKINIT);
218 
219 	} else if (opt_mp_join && listener->request_mptcp) {
220 		subflow_req->ssn_offset = TCP_SKB_CB(skb)->seq;
221 		subflow_req->mp_join = 1;
222 		subflow_req->backup = mp_opt.backup;
223 		subflow_req->remote_id = mp_opt.join_id;
224 		subflow_req->token = mp_opt.token;
225 		subflow_req->remote_nonce = mp_opt.nonce;
226 		subflow_req->msk = subflow_token_join_request(req);
227 
228 		/* Can't fall back to TCP in this case. */
229 		if (!subflow_req->msk) {
230 			subflow_add_reset_reason(skb, MPTCP_RST_EMPTCP);
231 			return -EPERM;
232 		}
233 
234 		if (subflow_use_different_sport(subflow_req->msk, sk_listener)) {
235 			pr_debug("syn inet_sport=%d %d\n",
236 				 ntohs(inet_sk(sk_listener)->inet_sport),
237 				 ntohs(inet_sk((struct sock *)subflow_req->msk)->inet_sport));
238 			if (!mptcp_pm_sport_in_anno_list(subflow_req->msk, sk_listener)) {
239 				SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_MISMATCHPORTSYNRX);
240 				subflow_add_reset_reason(skb, MPTCP_RST_EPROHIBIT);
241 				return -EPERM;
242 			}
243 			SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINPORTSYNRX);
244 		}
245 
246 		subflow_req_create_thmac(subflow_req);
247 
248 		if (unlikely(req->syncookie)) {
249 			if (!mptcp_can_accept_new_subflow(subflow_req->msk)) {
250 				subflow_add_reset_reason(skb, MPTCP_RST_EPROHIBIT);
251 				return -EPERM;
252 			}
253 
254 			subflow_init_req_cookie_join_save(subflow_req, skb);
255 		}
256 
257 		pr_debug("token=%u, remote_nonce=%u msk=%p\n", subflow_req->token,
258 			 subflow_req->remote_nonce, subflow_req->msk);
259 	}
260 
261 	return 0;
262 }
263 
264 int mptcp_subflow_init_cookie_req(struct request_sock *req,
265 				  const struct sock *sk_listener,
266 				  struct sk_buff *skb)
267 {
268 	struct mptcp_subflow_context *listener = mptcp_subflow_ctx(sk_listener);
269 	struct mptcp_subflow_request_sock *subflow_req = mptcp_subflow_rsk(req);
270 	struct mptcp_options_received mp_opt;
271 	bool opt_mp_capable, opt_mp_join;
272 	int err;
273 
274 	subflow_init_req(req, sk_listener);
275 	mptcp_get_options(skb, &mp_opt);
276 
277 	opt_mp_capable = !!(mp_opt.suboptions & OPTION_MPTCP_MPC_ACK);
278 	opt_mp_join = !!(mp_opt.suboptions & OPTION_MPTCP_MPJ_ACK);
279 	if (opt_mp_capable && opt_mp_join)
280 		return -EINVAL;
281 
282 	if (opt_mp_capable && listener->request_mptcp) {
283 		if (mp_opt.sndr_key == 0)
284 			return -EINVAL;
285 
286 		subflow_req->local_key = mp_opt.rcvr_key;
287 		err = mptcp_token_new_request(req);
288 		if (err)
289 			return err;
290 
291 		subflow_req->mp_capable = 1;
292 		subflow_req->ssn_offset = TCP_SKB_CB(skb)->seq - 1;
293 	} else if (opt_mp_join && listener->request_mptcp) {
294 		if (!mptcp_token_join_cookie_init_state(subflow_req, skb))
295 			return -EINVAL;
296 
297 		subflow_req->mp_join = 1;
298 		subflow_req->ssn_offset = TCP_SKB_CB(skb)->seq - 1;
299 	}
300 
301 	return 0;
302 }
303 EXPORT_SYMBOL_GPL(mptcp_subflow_init_cookie_req);
304 
305 static enum sk_rst_reason mptcp_get_rst_reason(const struct sk_buff *skb)
306 {
307 	const struct mptcp_ext *mpext = mptcp_get_ext(skb);
308 
309 	if (!mpext)
310 		return SK_RST_REASON_NOT_SPECIFIED;
311 
312 	return sk_rst_convert_mptcp_reason(mpext->reset_reason);
313 }
314 
315 static struct dst_entry *subflow_v4_route_req(const struct sock *sk,
316 					      struct sk_buff *skb,
317 					      struct flowi *fl,
318 					      struct request_sock *req,
319 					      u32 tw_isn)
320 {
321 	struct dst_entry *dst;
322 	int err;
323 
324 	tcp_rsk(req)->is_mptcp = 1;
325 	subflow_init_req(req, sk);
326 
327 	dst = tcp_request_sock_ipv4_ops.route_req(sk, skb, fl, req, tw_isn);
328 	if (!dst)
329 		return NULL;
330 
331 	err = subflow_check_req(req, sk, skb);
332 	if (err == 0)
333 		return dst;
334 
335 	dst_release(dst);
336 	if (!req->syncookie)
337 		tcp_request_sock_ops.send_reset(sk, skb,
338 						mptcp_get_rst_reason(skb));
339 	return NULL;
340 }
341 
342 static void subflow_prep_synack(const struct sock *sk, struct request_sock *req,
343 				struct tcp_fastopen_cookie *foc,
344 				enum tcp_synack_type synack_type)
345 {
346 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(sk);
347 	struct inet_request_sock *ireq = inet_rsk(req);
348 
349 	/* clear tstamp_ok, as needed depending on cookie */
350 	if (foc && foc->len > -1)
351 		ireq->tstamp_ok = 0;
352 
353 	if (synack_type == TCP_SYNACK_FASTOPEN)
354 		mptcp_fastopen_subflow_synack_set_params(subflow, req);
355 }
356 
357 static int subflow_v4_send_synack(const struct sock *sk, struct dst_entry *dst,
358 				  struct flowi *fl,
359 				  struct request_sock *req,
360 				  struct tcp_fastopen_cookie *foc,
361 				  enum tcp_synack_type synack_type,
362 				  struct sk_buff *syn_skb)
363 {
364 	subflow_prep_synack(sk, req, foc, synack_type);
365 
366 	return tcp_request_sock_ipv4_ops.send_synack(sk, dst, fl, req, foc,
367 						     synack_type, syn_skb);
368 }
369 
370 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
371 static int subflow_v6_send_synack(const struct sock *sk, struct dst_entry *dst,
372 				  struct flowi *fl,
373 				  struct request_sock *req,
374 				  struct tcp_fastopen_cookie *foc,
375 				  enum tcp_synack_type synack_type,
376 				  struct sk_buff *syn_skb)
377 {
378 	subflow_prep_synack(sk, req, foc, synack_type);
379 
380 	return tcp_request_sock_ipv6_ops.send_synack(sk, dst, fl, req, foc,
381 						     synack_type, syn_skb);
382 }
383 
384 static struct dst_entry *subflow_v6_route_req(const struct sock *sk,
385 					      struct sk_buff *skb,
386 					      struct flowi *fl,
387 					      struct request_sock *req,
388 					      u32 tw_isn)
389 {
390 	struct dst_entry *dst;
391 	int err;
392 
393 	tcp_rsk(req)->is_mptcp = 1;
394 	subflow_init_req(req, sk);
395 
396 	dst = tcp_request_sock_ipv6_ops.route_req(sk, skb, fl, req, tw_isn);
397 	if (!dst)
398 		return NULL;
399 
400 	err = subflow_check_req(req, sk, skb);
401 	if (err == 0)
402 		return dst;
403 
404 	dst_release(dst);
405 	if (!req->syncookie)
406 		tcp6_request_sock_ops.send_reset(sk, skb,
407 						 mptcp_get_rst_reason(skb));
408 	return NULL;
409 }
410 #endif
411 
412 /* validate received truncated hmac and create hmac for third ACK */
413 static bool subflow_thmac_valid(struct mptcp_subflow_context *subflow)
414 {
415 	u8 hmac[SHA256_DIGEST_SIZE];
416 	u64 thmac;
417 
418 	subflow_generate_hmac(subflow->remote_key, subflow->local_key,
419 			      subflow->remote_nonce, subflow->local_nonce,
420 			      hmac);
421 
422 	thmac = get_unaligned_be64(hmac);
423 	pr_debug("subflow=%p, token=%u, thmac=%llu, subflow->thmac=%llu\n",
424 		 subflow, subflow->token, thmac, subflow->thmac);
425 
426 	return thmac == subflow->thmac;
427 }
428 
429 void mptcp_subflow_reset(struct sock *ssk)
430 {
431 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
432 	struct sock *sk = subflow->conn;
433 
434 	/* mptcp_mp_fail_no_response() can reach here on an already closed
435 	 * socket
436 	 */
437 	if (ssk->sk_state == TCP_CLOSE)
438 		return;
439 
440 	/* must hold: tcp_done() could drop last reference on parent */
441 	sock_hold(sk);
442 
443 	mptcp_send_active_reset_reason(ssk);
444 	tcp_done(ssk);
445 	if (!test_and_set_bit(MPTCP_WORK_CLOSE_SUBFLOW, &mptcp_sk(sk)->flags))
446 		mptcp_schedule_work(sk);
447 
448 	sock_put(sk);
449 }
450 
451 static bool subflow_use_different_dport(struct mptcp_sock *msk, const struct sock *sk)
452 {
453 	return inet_sk(sk)->inet_dport != inet_sk((struct sock *)msk)->inet_dport;
454 }
455 
456 void __mptcp_sync_state(struct sock *sk, int state)
457 {
458 	struct mptcp_subflow_context *subflow;
459 	struct mptcp_sock *msk = mptcp_sk(sk);
460 	struct sock *ssk = msk->first;
461 
462 	subflow = mptcp_subflow_ctx(ssk);
463 	__mptcp_propagate_sndbuf(sk, ssk);
464 	if (!msk->rcvspace_init)
465 		mptcp_rcv_space_init(msk, ssk);
466 
467 	if (sk->sk_state == TCP_SYN_SENT) {
468 		/* subflow->idsn is always available is TCP_SYN_SENT state,
469 		 * even for the FASTOPEN scenarios
470 		 */
471 		WRITE_ONCE(msk->write_seq, subflow->idsn + 1);
472 		WRITE_ONCE(msk->snd_nxt, msk->write_seq);
473 		mptcp_set_state(sk, state);
474 		sk->sk_state_change(sk);
475 	}
476 }
477 
478 static void subflow_set_remote_key(struct mptcp_sock *msk,
479 				   struct mptcp_subflow_context *subflow,
480 				   const struct mptcp_options_received *mp_opt)
481 {
482 	/* active MPC subflow will reach here multiple times:
483 	 * at subflow_finish_connect() time and at 4th ack time
484 	 */
485 	if (subflow->remote_key_valid)
486 		return;
487 
488 	subflow->remote_key_valid = 1;
489 	subflow->remote_key = mp_opt->sndr_key;
490 	mptcp_crypto_key_sha(subflow->remote_key, NULL, &subflow->iasn);
491 	subflow->iasn++;
492 
493 	WRITE_ONCE(msk->remote_key, subflow->remote_key);
494 	WRITE_ONCE(msk->ack_seq, subflow->iasn);
495 	WRITE_ONCE(msk->can_ack, true);
496 	atomic64_set(&msk->rcv_wnd_sent, subflow->iasn);
497 }
498 
499 static void mptcp_propagate_state(struct sock *sk, struct sock *ssk,
500 				  struct mptcp_subflow_context *subflow,
501 				  const struct mptcp_options_received *mp_opt)
502 {
503 	struct mptcp_sock *msk = mptcp_sk(sk);
504 
505 	mptcp_data_lock(sk);
506 	if (mp_opt) {
507 		/* Options are available only in the non fallback cases
508 		 * avoid updating rx path fields otherwise
509 		 */
510 		WRITE_ONCE(msk->snd_una, subflow->idsn + 1);
511 		WRITE_ONCE(msk->wnd_end, subflow->idsn + 1 + tcp_sk(ssk)->snd_wnd);
512 		subflow_set_remote_key(msk, subflow, mp_opt);
513 	}
514 
515 	if (!sock_owned_by_user(sk)) {
516 		__mptcp_sync_state(sk, ssk->sk_state);
517 	} else {
518 		msk->pending_state = ssk->sk_state;
519 		__set_bit(MPTCP_SYNC_STATE, &msk->cb_flags);
520 	}
521 	mptcp_data_unlock(sk);
522 }
523 
524 static void subflow_finish_connect(struct sock *sk, const struct sk_buff *skb)
525 {
526 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(sk);
527 	struct mptcp_options_received mp_opt;
528 	struct sock *parent = subflow->conn;
529 	struct mptcp_sock *msk;
530 
531 	subflow->icsk_af_ops->sk_rx_dst_set(sk, skb);
532 
533 	/* be sure no special action on any packet other than syn-ack */
534 	if (subflow->conn_finished)
535 		return;
536 
537 	msk = mptcp_sk(parent);
538 	subflow->rel_write_seq = 1;
539 	subflow->conn_finished = 1;
540 	subflow->ssn_offset = TCP_SKB_CB(skb)->seq;
541 	pr_debug("subflow=%p synack seq=%x\n", subflow, subflow->ssn_offset);
542 
543 	mptcp_get_options(skb, &mp_opt);
544 	if (subflow->request_mptcp) {
545 		if (!(mp_opt.suboptions & OPTION_MPTCP_MPC_SYNACK)) {
546 			MPTCP_INC_STATS(sock_net(sk),
547 					MPTCP_MIB_MPCAPABLEACTIVEFALLBACK);
548 			mptcp_do_fallback(sk);
549 			pr_fallback(msk);
550 			goto fallback;
551 		}
552 
553 		if (mp_opt.suboptions & OPTION_MPTCP_CSUMREQD)
554 			WRITE_ONCE(msk->csum_enabled, true);
555 		if (mp_opt.deny_join_id0)
556 			WRITE_ONCE(msk->pm.remote_deny_join_id0, true);
557 		subflow->mp_capable = 1;
558 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_MPCAPABLEACTIVEACK);
559 		mptcp_finish_connect(sk);
560 		mptcp_active_enable(parent);
561 		mptcp_propagate_state(parent, sk, subflow, &mp_opt);
562 	} else if (subflow->request_join) {
563 		u8 hmac[SHA256_DIGEST_SIZE];
564 
565 		if (!(mp_opt.suboptions & OPTION_MPTCP_MPJ_SYNACK)) {
566 			subflow->reset_reason = MPTCP_RST_EMPTCP;
567 			goto do_reset;
568 		}
569 
570 		subflow->backup = mp_opt.backup;
571 		subflow->thmac = mp_opt.thmac;
572 		subflow->remote_nonce = mp_opt.nonce;
573 		WRITE_ONCE(subflow->remote_id, mp_opt.join_id);
574 		pr_debug("subflow=%p, thmac=%llu, remote_nonce=%u backup=%d\n",
575 			 subflow, subflow->thmac, subflow->remote_nonce,
576 			 subflow->backup);
577 
578 		if (!subflow_thmac_valid(subflow)) {
579 			MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_JOINACKMAC);
580 			subflow->reset_reason = MPTCP_RST_EMPTCP;
581 			goto do_reset;
582 		}
583 
584 		if (!mptcp_finish_join(sk))
585 			goto do_reset;
586 
587 		subflow_generate_hmac(subflow->local_key, subflow->remote_key,
588 				      subflow->local_nonce,
589 				      subflow->remote_nonce,
590 				      hmac);
591 		memcpy(subflow->hmac, hmac, MPTCPOPT_HMAC_LEN);
592 
593 		subflow->mp_join = 1;
594 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_JOINSYNACKRX);
595 
596 		if (subflow->backup)
597 			MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_JOINSYNACKBACKUPRX);
598 
599 		if (subflow_use_different_dport(msk, sk)) {
600 			pr_debug("synack inet_dport=%d %d\n",
601 				 ntohs(inet_sk(sk)->inet_dport),
602 				 ntohs(inet_sk(parent)->inet_dport));
603 			MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_JOINPORTSYNACKRX);
604 		}
605 	} else if (mptcp_check_fallback(sk)) {
606 		/* It looks like MPTCP is blocked, while TCP is not */
607 		if (subflow->mpc_drop)
608 			mptcp_active_disable(parent);
609 fallback:
610 		mptcp_propagate_state(parent, sk, subflow, NULL);
611 	}
612 	return;
613 
614 do_reset:
615 	subflow->reset_transient = 0;
616 	mptcp_subflow_reset(sk);
617 }
618 
619 static void subflow_set_local_id(struct mptcp_subflow_context *subflow, int local_id)
620 {
621 	WARN_ON_ONCE(local_id < 0 || local_id > 255);
622 	WRITE_ONCE(subflow->local_id, local_id);
623 }
624 
625 static int subflow_chk_local_id(struct sock *sk)
626 {
627 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(sk);
628 	struct mptcp_sock *msk = mptcp_sk(subflow->conn);
629 	int err;
630 
631 	if (likely(subflow->local_id >= 0))
632 		return 0;
633 
634 	err = mptcp_pm_get_local_id(msk, (struct sock_common *)sk);
635 	if (err < 0)
636 		return err;
637 
638 	subflow_set_local_id(subflow, err);
639 	subflow->request_bkup = mptcp_pm_is_backup(msk, (struct sock_common *)sk);
640 
641 	return 0;
642 }
643 
644 static int subflow_rebuild_header(struct sock *sk)
645 {
646 	int err = subflow_chk_local_id(sk);
647 
648 	if (unlikely(err < 0))
649 		return err;
650 
651 	return inet_sk_rebuild_header(sk);
652 }
653 
654 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
655 static int subflow_v6_rebuild_header(struct sock *sk)
656 {
657 	int err = subflow_chk_local_id(sk);
658 
659 	if (unlikely(err < 0))
660 		return err;
661 
662 	return inet6_sk_rebuild_header(sk);
663 }
664 #endif
665 
666 static struct request_sock_ops mptcp_subflow_v4_request_sock_ops __ro_after_init;
667 static struct tcp_request_sock_ops subflow_request_sock_ipv4_ops __ro_after_init;
668 
669 static int subflow_v4_conn_request(struct sock *sk, struct sk_buff *skb)
670 {
671 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(sk);
672 
673 	pr_debug("subflow=%p\n", subflow);
674 
675 	/* Never answer to SYNs sent to broadcast or multicast */
676 	if (skb_rtable(skb)->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
677 		goto drop;
678 
679 	return tcp_conn_request(&mptcp_subflow_v4_request_sock_ops,
680 				&subflow_request_sock_ipv4_ops,
681 				sk, skb);
682 drop:
683 	tcp_listendrop(sk);
684 	return 0;
685 }
686 
687 static void subflow_v4_req_destructor(struct request_sock *req)
688 {
689 	subflow_req_destructor(req);
690 	tcp_request_sock_ops.destructor(req);
691 }
692 
693 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
694 static struct request_sock_ops mptcp_subflow_v6_request_sock_ops __ro_after_init;
695 static struct tcp_request_sock_ops subflow_request_sock_ipv6_ops __ro_after_init;
696 static struct inet_connection_sock_af_ops subflow_v6_specific __ro_after_init;
697 static struct inet_connection_sock_af_ops subflow_v6m_specific __ro_after_init;
698 static struct proto tcpv6_prot_override __ro_after_init;
699 
700 static int subflow_v6_conn_request(struct sock *sk, struct sk_buff *skb)
701 {
702 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(sk);
703 
704 	pr_debug("subflow=%p\n", subflow);
705 
706 	if (skb->protocol == htons(ETH_P_IP))
707 		return subflow_v4_conn_request(sk, skb);
708 
709 	if (!ipv6_unicast_destination(skb))
710 		goto drop;
711 
712 	if (ipv6_addr_v4mapped(&ipv6_hdr(skb)->saddr)) {
713 		__IP6_INC_STATS(sock_net(sk), NULL, IPSTATS_MIB_INHDRERRORS);
714 		return 0;
715 	}
716 
717 	return tcp_conn_request(&mptcp_subflow_v6_request_sock_ops,
718 				&subflow_request_sock_ipv6_ops, sk, skb);
719 
720 drop:
721 	tcp_listendrop(sk);
722 	return 0; /* don't send reset */
723 }
724 
725 static void subflow_v6_req_destructor(struct request_sock *req)
726 {
727 	subflow_req_destructor(req);
728 	tcp6_request_sock_ops.destructor(req);
729 }
730 #endif
731 
732 struct request_sock *mptcp_subflow_reqsk_alloc(const struct request_sock_ops *ops,
733 					       struct sock *sk_listener,
734 					       bool attach_listener)
735 {
736 	if (ops->family == AF_INET)
737 		ops = &mptcp_subflow_v4_request_sock_ops;
738 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
739 	else if (ops->family == AF_INET6)
740 		ops = &mptcp_subflow_v6_request_sock_ops;
741 #endif
742 
743 	return inet_reqsk_alloc(ops, sk_listener, attach_listener);
744 }
745 EXPORT_SYMBOL(mptcp_subflow_reqsk_alloc);
746 
747 /* validate hmac received in third ACK */
748 static bool subflow_hmac_valid(const struct request_sock *req,
749 			       const struct mptcp_options_received *mp_opt)
750 {
751 	const struct mptcp_subflow_request_sock *subflow_req;
752 	u8 hmac[SHA256_DIGEST_SIZE];
753 	struct mptcp_sock *msk;
754 
755 	subflow_req = mptcp_subflow_rsk(req);
756 	msk = subflow_req->msk;
757 	if (!msk)
758 		return false;
759 
760 	subflow_generate_hmac(READ_ONCE(msk->remote_key),
761 			      READ_ONCE(msk->local_key),
762 			      subflow_req->remote_nonce,
763 			      subflow_req->local_nonce, hmac);
764 
765 	return !crypto_memneq(hmac, mp_opt->hmac, MPTCPOPT_HMAC_LEN);
766 }
767 
768 static void subflow_ulp_fallback(struct sock *sk,
769 				 struct mptcp_subflow_context *old_ctx)
770 {
771 	struct inet_connection_sock *icsk = inet_csk(sk);
772 
773 	mptcp_subflow_tcp_fallback(sk, old_ctx);
774 	icsk->icsk_ulp_ops = NULL;
775 	rcu_assign_pointer(icsk->icsk_ulp_data, NULL);
776 	tcp_sk(sk)->is_mptcp = 0;
777 
778 	mptcp_subflow_ops_undo_override(sk);
779 }
780 
781 void mptcp_subflow_drop_ctx(struct sock *ssk)
782 {
783 	struct mptcp_subflow_context *ctx = mptcp_subflow_ctx(ssk);
784 
785 	if (!ctx)
786 		return;
787 
788 	list_del(&mptcp_subflow_ctx(ssk)->node);
789 	if (inet_csk(ssk)->icsk_ulp_ops) {
790 		subflow_ulp_fallback(ssk, ctx);
791 		if (ctx->conn)
792 			sock_put(ctx->conn);
793 	}
794 
795 	kfree_rcu(ctx, rcu);
796 }
797 
798 void __mptcp_subflow_fully_established(struct mptcp_sock *msk,
799 				       struct mptcp_subflow_context *subflow,
800 				       const struct mptcp_options_received *mp_opt)
801 {
802 	subflow_set_remote_key(msk, subflow, mp_opt);
803 	WRITE_ONCE(subflow->fully_established, true);
804 	WRITE_ONCE(msk->fully_established, true);
805 }
806 
807 static struct sock *subflow_syn_recv_sock(const struct sock *sk,
808 					  struct sk_buff *skb,
809 					  struct request_sock *req,
810 					  struct dst_entry *dst,
811 					  struct request_sock *req_unhash,
812 					  bool *own_req)
813 {
814 	struct mptcp_subflow_context *listener = mptcp_subflow_ctx(sk);
815 	struct mptcp_subflow_request_sock *subflow_req;
816 	struct mptcp_options_received mp_opt;
817 	bool fallback, fallback_is_fatal;
818 	enum sk_rst_reason reason;
819 	struct mptcp_sock *owner;
820 	struct sock *child;
821 
822 	pr_debug("listener=%p, req=%p, conn=%p\n", listener, req, listener->conn);
823 
824 	/* After child creation we must look for MPC even when options
825 	 * are not parsed
826 	 */
827 	mp_opt.suboptions = 0;
828 
829 	/* hopefully temporary handling for MP_JOIN+syncookie */
830 	subflow_req = mptcp_subflow_rsk(req);
831 	fallback_is_fatal = tcp_rsk(req)->is_mptcp && subflow_req->mp_join;
832 	fallback = !tcp_rsk(req)->is_mptcp;
833 	if (fallback)
834 		goto create_child;
835 
836 	/* if the sk is MP_CAPABLE, we try to fetch the client key */
837 	if (subflow_req->mp_capable) {
838 		/* we can receive and accept an in-window, out-of-order pkt,
839 		 * which may not carry the MP_CAPABLE opt even on mptcp enabled
840 		 * paths: always try to extract the peer key, and fallback
841 		 * for packets missing it.
842 		 * Even OoO DSS packets coming legitly after dropped or
843 		 * reordered MPC will cause fallback, but we don't have other
844 		 * options.
845 		 */
846 		mptcp_get_options(skb, &mp_opt);
847 		if (!(mp_opt.suboptions &
848 		      (OPTION_MPTCP_MPC_SYN | OPTION_MPTCP_MPC_ACK)))
849 			fallback = true;
850 
851 	} else if (subflow_req->mp_join) {
852 		mptcp_get_options(skb, &mp_opt);
853 		if (!(mp_opt.suboptions & OPTION_MPTCP_MPJ_ACK) ||
854 		    !subflow_hmac_valid(req, &mp_opt) ||
855 		    !mptcp_can_accept_new_subflow(subflow_req->msk)) {
856 			SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINACKMAC);
857 			fallback = true;
858 		}
859 	}
860 
861 create_child:
862 	child = listener->icsk_af_ops->syn_recv_sock(sk, skb, req, dst,
863 						     req_unhash, own_req);
864 
865 	if (child && *own_req) {
866 		struct mptcp_subflow_context *ctx = mptcp_subflow_ctx(child);
867 
868 		tcp_rsk(req)->drop_req = false;
869 
870 		/* we need to fallback on ctx allocation failure and on pre-reqs
871 		 * checking above. In the latter scenario we additionally need
872 		 * to reset the context to non MPTCP status.
873 		 */
874 		if (!ctx || fallback) {
875 			if (fallback_is_fatal) {
876 				subflow_add_reset_reason(skb, MPTCP_RST_EMPTCP);
877 				goto dispose_child;
878 			}
879 			goto fallback;
880 		}
881 
882 		/* ssk inherits options of listener sk */
883 		ctx->setsockopt_seq = listener->setsockopt_seq;
884 
885 		if (ctx->mp_capable) {
886 			ctx->conn = mptcp_sk_clone_init(listener->conn, &mp_opt, child, req);
887 			if (!ctx->conn)
888 				goto fallback;
889 
890 			ctx->subflow_id = 1;
891 			owner = mptcp_sk(ctx->conn);
892 			mptcp_pm_new_connection(owner, child, 1);
893 
894 			/* with OoO packets we can reach here without ingress
895 			 * mpc option
896 			 */
897 			if (mp_opt.suboptions & OPTION_MPTCP_MPC_ACK) {
898 				mptcp_pm_fully_established(owner, child);
899 				ctx->pm_notified = 1;
900 			}
901 		} else if (ctx->mp_join) {
902 			owner = subflow_req->msk;
903 			if (!owner) {
904 				subflow_add_reset_reason(skb, MPTCP_RST_EPROHIBIT);
905 				goto dispose_child;
906 			}
907 
908 			/* move the msk reference ownership to the subflow */
909 			subflow_req->msk = NULL;
910 			ctx->conn = (struct sock *)owner;
911 
912 			if (subflow_use_different_sport(owner, sk)) {
913 				pr_debug("ack inet_sport=%d %d\n",
914 					 ntohs(inet_sk(sk)->inet_sport),
915 					 ntohs(inet_sk((struct sock *)owner)->inet_sport));
916 				if (!mptcp_pm_sport_in_anno_list(owner, sk)) {
917 					SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_MISMATCHPORTACKRX);
918 					subflow_add_reset_reason(skb, MPTCP_RST_EPROHIBIT);
919 					goto dispose_child;
920 				}
921 				SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINPORTACKRX);
922 			}
923 
924 			if (!mptcp_finish_join(child)) {
925 				struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(child);
926 
927 				subflow_add_reset_reason(skb, subflow->reset_reason);
928 				goto dispose_child;
929 			}
930 
931 			SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINACKRX);
932 			tcp_rsk(req)->drop_req = true;
933 		}
934 	}
935 
936 	/* check for expected invariant - should never trigger, just help
937 	 * catching earlier subtle bugs
938 	 */
939 	WARN_ON_ONCE(child && *own_req && tcp_sk(child)->is_mptcp &&
940 		     (!mptcp_subflow_ctx(child) ||
941 		      !mptcp_subflow_ctx(child)->conn));
942 	return child;
943 
944 dispose_child:
945 	mptcp_subflow_drop_ctx(child);
946 	tcp_rsk(req)->drop_req = true;
947 	inet_csk_prepare_for_destroy_sock(child);
948 	tcp_done(child);
949 	reason = mptcp_get_rst_reason(skb);
950 	req->rsk_ops->send_reset(sk, skb, reason);
951 
952 	/* The last child reference will be released by the caller */
953 	return child;
954 
955 fallback:
956 	if (fallback)
957 		SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_MPCAPABLEPASSIVEFALLBACK);
958 	mptcp_subflow_drop_ctx(child);
959 	return child;
960 }
961 
962 static struct inet_connection_sock_af_ops subflow_specific __ro_after_init;
963 static struct proto tcp_prot_override __ro_after_init;
964 
965 enum mapping_status {
966 	MAPPING_OK,
967 	MAPPING_INVALID,
968 	MAPPING_EMPTY,
969 	MAPPING_DATA_FIN,
970 	MAPPING_DUMMY,
971 	MAPPING_BAD_CSUM,
972 	MAPPING_NODSS
973 };
974 
975 static void dbg_bad_map(struct mptcp_subflow_context *subflow, u32 ssn)
976 {
977 	pr_debug("Bad mapping: ssn=%d map_seq=%d map_data_len=%d\n",
978 		 ssn, subflow->map_subflow_seq, subflow->map_data_len);
979 }
980 
981 static bool skb_is_fully_mapped(struct sock *ssk, struct sk_buff *skb)
982 {
983 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
984 	unsigned int skb_consumed;
985 
986 	skb_consumed = tcp_sk(ssk)->copied_seq - TCP_SKB_CB(skb)->seq;
987 	if (unlikely(skb_consumed >= skb->len)) {
988 		DEBUG_NET_WARN_ON_ONCE(1);
989 		return true;
990 	}
991 
992 	return skb->len - skb_consumed <= subflow->map_data_len -
993 					  mptcp_subflow_get_map_offset(subflow);
994 }
995 
996 static bool validate_mapping(struct sock *ssk, struct sk_buff *skb)
997 {
998 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
999 	u32 ssn = tcp_sk(ssk)->copied_seq - subflow->ssn_offset;
1000 
1001 	if (unlikely(before(ssn, subflow->map_subflow_seq))) {
1002 		/* Mapping covers data later in the subflow stream,
1003 		 * currently unsupported.
1004 		 */
1005 		dbg_bad_map(subflow, ssn);
1006 		return false;
1007 	}
1008 	if (unlikely(!before(ssn, subflow->map_subflow_seq +
1009 				  subflow->map_data_len))) {
1010 		/* Mapping does covers past subflow data, invalid */
1011 		dbg_bad_map(subflow, ssn);
1012 		return false;
1013 	}
1014 	return true;
1015 }
1016 
1017 static enum mapping_status validate_data_csum(struct sock *ssk, struct sk_buff *skb,
1018 					      bool csum_reqd)
1019 {
1020 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
1021 	u32 offset, seq, delta;
1022 	__sum16 csum;
1023 	int len;
1024 
1025 	if (!csum_reqd)
1026 		return MAPPING_OK;
1027 
1028 	/* mapping already validated on previous traversal */
1029 	if (subflow->map_csum_len == subflow->map_data_len)
1030 		return MAPPING_OK;
1031 
1032 	/* traverse the receive queue, ensuring it contains a full
1033 	 * DSS mapping and accumulating the related csum.
1034 	 * Preserve the accoumlate csum across multiple calls, to compute
1035 	 * the csum only once
1036 	 */
1037 	delta = subflow->map_data_len - subflow->map_csum_len;
1038 	for (;;) {
1039 		seq = tcp_sk(ssk)->copied_seq + subflow->map_csum_len;
1040 		offset = seq - TCP_SKB_CB(skb)->seq;
1041 
1042 		/* if the current skb has not been accounted yet, csum its contents
1043 		 * up to the amount covered by the current DSS
1044 		 */
1045 		if (offset < skb->len) {
1046 			__wsum csum;
1047 
1048 			len = min(skb->len - offset, delta);
1049 			csum = skb_checksum(skb, offset, len, 0);
1050 			subflow->map_data_csum = csum_block_add(subflow->map_data_csum, csum,
1051 								subflow->map_csum_len);
1052 
1053 			delta -= len;
1054 			subflow->map_csum_len += len;
1055 		}
1056 		if (delta == 0)
1057 			break;
1058 
1059 		if (skb_queue_is_last(&ssk->sk_receive_queue, skb)) {
1060 			/* if this subflow is closed, the partial mapping
1061 			 * will be never completed; flush the pending skbs, so
1062 			 * that subflow_sched_work_if_closed() can kick in
1063 			 */
1064 			if (unlikely(ssk->sk_state == TCP_CLOSE))
1065 				while ((skb = skb_peek(&ssk->sk_receive_queue)))
1066 					sk_eat_skb(ssk, skb);
1067 
1068 			/* not enough data to validate the csum */
1069 			return MAPPING_EMPTY;
1070 		}
1071 
1072 		/* the DSS mapping for next skbs will be validated later,
1073 		 * when a get_mapping_status call will process such skb
1074 		 */
1075 		skb = skb->next;
1076 	}
1077 
1078 	/* note that 'map_data_len' accounts only for the carried data, does
1079 	 * not include the eventual seq increment due to the data fin,
1080 	 * while the pseudo header requires the original DSS data len,
1081 	 * including that
1082 	 */
1083 	csum = __mptcp_make_csum(subflow->map_seq,
1084 				 subflow->map_subflow_seq,
1085 				 subflow->map_data_len + subflow->map_data_fin,
1086 				 subflow->map_data_csum);
1087 	if (unlikely(csum)) {
1088 		MPTCP_INC_STATS(sock_net(ssk), MPTCP_MIB_DATACSUMERR);
1089 		return MAPPING_BAD_CSUM;
1090 	}
1091 
1092 	subflow->valid_csum_seen = 1;
1093 	return MAPPING_OK;
1094 }
1095 
1096 static enum mapping_status get_mapping_status(struct sock *ssk,
1097 					      struct mptcp_sock *msk)
1098 {
1099 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
1100 	bool csum_reqd = READ_ONCE(msk->csum_enabled);
1101 	struct mptcp_ext *mpext;
1102 	struct sk_buff *skb;
1103 	u16 data_len;
1104 	u64 map_seq;
1105 
1106 	skb = skb_peek(&ssk->sk_receive_queue);
1107 	if (!skb)
1108 		return MAPPING_EMPTY;
1109 
1110 	if (mptcp_check_fallback(ssk))
1111 		return MAPPING_DUMMY;
1112 
1113 	mpext = mptcp_get_ext(skb);
1114 	if (!mpext || !mpext->use_map) {
1115 		if (!subflow->map_valid && !skb->len) {
1116 			/* the TCP stack deliver 0 len FIN pkt to the receive
1117 			 * queue, that is the only 0len pkts ever expected here,
1118 			 * and we can admit no mapping only for 0 len pkts
1119 			 */
1120 			if (!(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN))
1121 				WARN_ONCE(1, "0len seq %d:%d flags %x",
1122 					  TCP_SKB_CB(skb)->seq,
1123 					  TCP_SKB_CB(skb)->end_seq,
1124 					  TCP_SKB_CB(skb)->tcp_flags);
1125 			sk_eat_skb(ssk, skb);
1126 			return MAPPING_EMPTY;
1127 		}
1128 
1129 		/* If the required DSS has likely been dropped by a middlebox */
1130 		if (!subflow->map_valid)
1131 			return MAPPING_NODSS;
1132 
1133 		goto validate_seq;
1134 	}
1135 
1136 	trace_get_mapping_status(mpext);
1137 
1138 	data_len = mpext->data_len;
1139 	if (data_len == 0) {
1140 		pr_debug("infinite mapping received\n");
1141 		MPTCP_INC_STATS(sock_net(ssk), MPTCP_MIB_INFINITEMAPRX);
1142 		return MAPPING_INVALID;
1143 	}
1144 
1145 	if (mpext->data_fin == 1) {
1146 		u64 data_fin_seq;
1147 
1148 		if (data_len == 1) {
1149 			bool updated = mptcp_update_rcv_data_fin(msk, mpext->data_seq,
1150 								 mpext->dsn64);
1151 			pr_debug("DATA_FIN with no payload seq=%llu\n", mpext->data_seq);
1152 			if (subflow->map_valid) {
1153 				/* A DATA_FIN might arrive in a DSS
1154 				 * option before the previous mapping
1155 				 * has been fully consumed. Continue
1156 				 * handling the existing mapping.
1157 				 */
1158 				skb_ext_del(skb, SKB_EXT_MPTCP);
1159 				return MAPPING_OK;
1160 			}
1161 
1162 			if (updated)
1163 				mptcp_schedule_work((struct sock *)msk);
1164 
1165 			return MAPPING_DATA_FIN;
1166 		}
1167 
1168 		data_fin_seq = mpext->data_seq + data_len - 1;
1169 
1170 		/* If mpext->data_seq is a 32-bit value, data_fin_seq must also
1171 		 * be limited to 32 bits.
1172 		 */
1173 		if (!mpext->dsn64)
1174 			data_fin_seq &= GENMASK_ULL(31, 0);
1175 
1176 		mptcp_update_rcv_data_fin(msk, data_fin_seq, mpext->dsn64);
1177 		pr_debug("DATA_FIN with mapping seq=%llu dsn64=%d\n",
1178 			 data_fin_seq, mpext->dsn64);
1179 
1180 		/* Adjust for DATA_FIN using 1 byte of sequence space */
1181 		data_len--;
1182 	}
1183 
1184 	map_seq = mptcp_expand_seq(READ_ONCE(msk->ack_seq), mpext->data_seq, mpext->dsn64);
1185 	WRITE_ONCE(mptcp_sk(subflow->conn)->use_64bit_ack, !!mpext->dsn64);
1186 
1187 	if (subflow->map_valid) {
1188 		/* Allow replacing only with an identical map */
1189 		if (subflow->map_seq == map_seq &&
1190 		    subflow->map_subflow_seq == mpext->subflow_seq &&
1191 		    subflow->map_data_len == data_len &&
1192 		    subflow->map_csum_reqd == mpext->csum_reqd) {
1193 			skb_ext_del(skb, SKB_EXT_MPTCP);
1194 			goto validate_csum;
1195 		}
1196 
1197 		/* If this skb data are fully covered by the current mapping,
1198 		 * the new map would need caching, which is not supported
1199 		 */
1200 		if (skb_is_fully_mapped(ssk, skb)) {
1201 			MPTCP_INC_STATS(sock_net(ssk), MPTCP_MIB_DSSNOMATCH);
1202 			return MAPPING_INVALID;
1203 		}
1204 
1205 		/* will validate the next map after consuming the current one */
1206 		goto validate_csum;
1207 	}
1208 
1209 	subflow->map_seq = map_seq;
1210 	subflow->map_subflow_seq = mpext->subflow_seq;
1211 	subflow->map_data_len = data_len;
1212 	subflow->map_valid = 1;
1213 	subflow->map_data_fin = mpext->data_fin;
1214 	subflow->mpc_map = mpext->mpc_map;
1215 	subflow->map_csum_reqd = mpext->csum_reqd;
1216 	subflow->map_csum_len = 0;
1217 	subflow->map_data_csum = csum_unfold(mpext->csum);
1218 
1219 	/* Cfr RFC 8684 Section 3.3.0 */
1220 	if (unlikely(subflow->map_csum_reqd != csum_reqd))
1221 		return MAPPING_INVALID;
1222 
1223 	pr_debug("new map seq=%llu subflow_seq=%u data_len=%u csum=%d:%u\n",
1224 		 subflow->map_seq, subflow->map_subflow_seq,
1225 		 subflow->map_data_len, subflow->map_csum_reqd,
1226 		 subflow->map_data_csum);
1227 
1228 validate_seq:
1229 	/* we revalidate valid mapping on new skb, because we must ensure
1230 	 * the current skb is completely covered by the available mapping
1231 	 */
1232 	if (!validate_mapping(ssk, skb)) {
1233 		MPTCP_INC_STATS(sock_net(ssk), MPTCP_MIB_DSSTCPMISMATCH);
1234 		return MAPPING_INVALID;
1235 	}
1236 
1237 	skb_ext_del(skb, SKB_EXT_MPTCP);
1238 
1239 validate_csum:
1240 	return validate_data_csum(ssk, skb, csum_reqd);
1241 }
1242 
1243 static void mptcp_subflow_discard_data(struct sock *ssk, struct sk_buff *skb,
1244 				       u64 limit)
1245 {
1246 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
1247 	bool fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
1248 	struct tcp_sock *tp = tcp_sk(ssk);
1249 	u32 offset, incr, avail_len;
1250 
1251 	offset = tp->copied_seq - TCP_SKB_CB(skb)->seq;
1252 	if (WARN_ON_ONCE(offset > skb->len))
1253 		goto out;
1254 
1255 	avail_len = skb->len - offset;
1256 	incr = limit >= avail_len ? avail_len + fin : limit;
1257 
1258 	pr_debug("discarding=%d len=%d offset=%d seq=%d\n", incr, skb->len,
1259 		 offset, subflow->map_subflow_seq);
1260 	MPTCP_INC_STATS(sock_net(ssk), MPTCP_MIB_DUPDATA);
1261 	tcp_sk(ssk)->copied_seq += incr;
1262 
1263 out:
1264 	if (!before(tcp_sk(ssk)->copied_seq, TCP_SKB_CB(skb)->end_seq))
1265 		sk_eat_skb(ssk, skb);
1266 	if (mptcp_subflow_get_map_offset(subflow) >= subflow->map_data_len)
1267 		subflow->map_valid = 0;
1268 }
1269 
1270 static bool subflow_is_done(const struct sock *sk)
1271 {
1272 	return sk->sk_shutdown & RCV_SHUTDOWN || sk->sk_state == TCP_CLOSE;
1273 }
1274 
1275 /* sched mptcp worker for subflow cleanup if no more data is pending */
1276 static void subflow_sched_work_if_closed(struct mptcp_sock *msk, struct sock *ssk)
1277 {
1278 	struct sock *sk = (struct sock *)msk;
1279 
1280 	if (likely(ssk->sk_state != TCP_CLOSE &&
1281 		   (ssk->sk_state != TCP_CLOSE_WAIT ||
1282 		    inet_sk_state_load(sk) != TCP_ESTABLISHED)))
1283 		return;
1284 
1285 	if (!skb_queue_empty(&ssk->sk_receive_queue))
1286 		return;
1287 
1288 	if (!test_and_set_bit(MPTCP_WORK_CLOSE_SUBFLOW, &msk->flags))
1289 		mptcp_schedule_work(sk);
1290 
1291 	/* when the fallback subflow closes the rx side, trigger a 'dummy'
1292 	 * ingress data fin, so that the msk state will follow along
1293 	 */
1294 	if (__mptcp_check_fallback(msk) && subflow_is_done(ssk) &&
1295 	    msk->first == ssk &&
1296 	    mptcp_update_rcv_data_fin(msk, READ_ONCE(msk->ack_seq), true))
1297 		mptcp_schedule_work(sk);
1298 }
1299 
1300 static void mptcp_subflow_fail(struct mptcp_sock *msk, struct sock *ssk)
1301 {
1302 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
1303 	unsigned long fail_tout;
1304 
1305 	/* graceful failure can happen only on the MPC subflow */
1306 	if (WARN_ON_ONCE(ssk != READ_ONCE(msk->first)))
1307 		return;
1308 
1309 	/* since the close timeout take precedence on the fail one,
1310 	 * no need to start the latter when the first is already set
1311 	 */
1312 	if (sock_flag((struct sock *)msk, SOCK_DEAD))
1313 		return;
1314 
1315 	/* we don't need extreme accuracy here, use a zero fail_tout as special
1316 	 * value meaning no fail timeout at all;
1317 	 */
1318 	fail_tout = jiffies + TCP_RTO_MAX;
1319 	if (!fail_tout)
1320 		fail_tout = 1;
1321 	WRITE_ONCE(subflow->fail_tout, fail_tout);
1322 	tcp_send_ack(ssk);
1323 
1324 	mptcp_reset_tout_timer(msk, subflow->fail_tout);
1325 }
1326 
1327 static bool subflow_check_data_avail(struct sock *ssk)
1328 {
1329 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
1330 	enum mapping_status status;
1331 	struct mptcp_sock *msk;
1332 	struct sk_buff *skb;
1333 
1334 	if (!skb_peek(&ssk->sk_receive_queue))
1335 		WRITE_ONCE(subflow->data_avail, false);
1336 	if (subflow->data_avail)
1337 		return true;
1338 
1339 	msk = mptcp_sk(subflow->conn);
1340 	for (;;) {
1341 		u64 ack_seq;
1342 		u64 old_ack;
1343 
1344 		status = get_mapping_status(ssk, msk);
1345 		trace_subflow_check_data_avail(status, skb_peek(&ssk->sk_receive_queue));
1346 		if (unlikely(status == MAPPING_INVALID || status == MAPPING_DUMMY ||
1347 			     status == MAPPING_BAD_CSUM || status == MAPPING_NODSS))
1348 			goto fallback;
1349 
1350 		if (status != MAPPING_OK)
1351 			goto no_data;
1352 
1353 		skb = skb_peek(&ssk->sk_receive_queue);
1354 		if (WARN_ON_ONCE(!skb))
1355 			goto no_data;
1356 
1357 		if (unlikely(!READ_ONCE(msk->can_ack)))
1358 			goto fallback;
1359 
1360 		old_ack = READ_ONCE(msk->ack_seq);
1361 		ack_seq = mptcp_subflow_get_mapped_dsn(subflow);
1362 		pr_debug("msk ack_seq=%llx subflow ack_seq=%llx\n", old_ack,
1363 			 ack_seq);
1364 		if (unlikely(before64(ack_seq, old_ack))) {
1365 			mptcp_subflow_discard_data(ssk, skb, old_ack - ack_seq);
1366 			continue;
1367 		}
1368 
1369 		WRITE_ONCE(subflow->data_avail, true);
1370 		break;
1371 	}
1372 	return true;
1373 
1374 no_data:
1375 	subflow_sched_work_if_closed(msk, ssk);
1376 	return false;
1377 
1378 fallback:
1379 	if (!__mptcp_check_fallback(msk)) {
1380 		/* RFC 8684 section 3.7. */
1381 		if (status == MAPPING_BAD_CSUM &&
1382 		    (subflow->mp_join || subflow->valid_csum_seen)) {
1383 			subflow->send_mp_fail = 1;
1384 
1385 			if (!READ_ONCE(msk->allow_infinite_fallback)) {
1386 				subflow->reset_transient = 0;
1387 				subflow->reset_reason = MPTCP_RST_EMIDDLEBOX;
1388 				goto reset;
1389 			}
1390 			mptcp_subflow_fail(msk, ssk);
1391 			WRITE_ONCE(subflow->data_avail, true);
1392 			return true;
1393 		}
1394 
1395 		if (!READ_ONCE(msk->allow_infinite_fallback)) {
1396 			/* fatal protocol error, close the socket.
1397 			 * subflow_error_report() will introduce the appropriate barriers
1398 			 */
1399 			subflow->reset_transient = 0;
1400 			subflow->reset_reason = status == MAPPING_NODSS ?
1401 						MPTCP_RST_EMIDDLEBOX :
1402 						MPTCP_RST_EMPTCP;
1403 
1404 reset:
1405 			WRITE_ONCE(ssk->sk_err, EBADMSG);
1406 			tcp_set_state(ssk, TCP_CLOSE);
1407 			while ((skb = skb_peek(&ssk->sk_receive_queue)))
1408 				sk_eat_skb(ssk, skb);
1409 			mptcp_send_active_reset_reason(ssk);
1410 			WRITE_ONCE(subflow->data_avail, false);
1411 			return false;
1412 		}
1413 
1414 		mptcp_do_fallback(ssk);
1415 	}
1416 
1417 	skb = skb_peek(&ssk->sk_receive_queue);
1418 	subflow->map_valid = 1;
1419 	subflow->map_seq = READ_ONCE(msk->ack_seq);
1420 	subflow->map_data_len = skb->len;
1421 	subflow->map_subflow_seq = tcp_sk(ssk)->copied_seq - subflow->ssn_offset;
1422 	WRITE_ONCE(subflow->data_avail, true);
1423 	return true;
1424 }
1425 
1426 bool mptcp_subflow_data_available(struct sock *sk)
1427 {
1428 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(sk);
1429 
1430 	/* check if current mapping is still valid */
1431 	if (subflow->map_valid &&
1432 	    mptcp_subflow_get_map_offset(subflow) >= subflow->map_data_len) {
1433 		subflow->map_valid = 0;
1434 		WRITE_ONCE(subflow->data_avail, false);
1435 
1436 		pr_debug("Done with mapping: seq=%u data_len=%u\n",
1437 			 subflow->map_subflow_seq,
1438 			 subflow->map_data_len);
1439 	}
1440 
1441 	return subflow_check_data_avail(sk);
1442 }
1443 
1444 /* If ssk has an mptcp parent socket, use the mptcp rcvbuf occupancy,
1445  * not the ssk one.
1446  *
1447  * In mptcp, rwin is about the mptcp-level connection data.
1448  *
1449  * Data that is still on the ssk rx queue can thus be ignored,
1450  * as far as mptcp peer is concerned that data is still inflight.
1451  * DSS ACK is updated when skb is moved to the mptcp rx queue.
1452  */
1453 void mptcp_space(const struct sock *ssk, int *space, int *full_space)
1454 {
1455 	const struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
1456 	const struct sock *sk = subflow->conn;
1457 
1458 	*space = __mptcp_space(sk);
1459 	*full_space = mptcp_win_from_space(sk, READ_ONCE(sk->sk_rcvbuf));
1460 }
1461 
1462 static void subflow_error_report(struct sock *ssk)
1463 {
1464 	struct sock *sk = mptcp_subflow_ctx(ssk)->conn;
1465 
1466 	/* bail early if this is a no-op, so that we avoid introducing a
1467 	 * problematic lockdep dependency between TCP accept queue lock
1468 	 * and msk socket spinlock
1469 	 */
1470 	if (!sk->sk_socket)
1471 		return;
1472 
1473 	mptcp_data_lock(sk);
1474 	if (!sock_owned_by_user(sk))
1475 		__mptcp_error_report(sk);
1476 	else
1477 		__set_bit(MPTCP_ERROR_REPORT,  &mptcp_sk(sk)->cb_flags);
1478 	mptcp_data_unlock(sk);
1479 }
1480 
1481 static void subflow_data_ready(struct sock *sk)
1482 {
1483 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(sk);
1484 	u16 state = 1 << inet_sk_state_load(sk);
1485 	struct sock *parent = subflow->conn;
1486 	struct mptcp_sock *msk;
1487 
1488 	trace_sk_data_ready(sk);
1489 
1490 	msk = mptcp_sk(parent);
1491 	if (state & TCPF_LISTEN) {
1492 		/* MPJ subflow are removed from accept queue before reaching here,
1493 		 * avoid stray wakeups
1494 		 */
1495 		if (reqsk_queue_empty(&inet_csk(sk)->icsk_accept_queue))
1496 			return;
1497 
1498 		parent->sk_data_ready(parent);
1499 		return;
1500 	}
1501 
1502 	WARN_ON_ONCE(!__mptcp_check_fallback(msk) && !subflow->mp_capable &&
1503 		     !subflow->mp_join && !(state & TCPF_CLOSE));
1504 
1505 	if (mptcp_subflow_data_available(sk)) {
1506 		mptcp_data_ready(parent, sk);
1507 
1508 		/* subflow-level lowat test are not relevant.
1509 		 * respect the msk-level threshold eventually mandating an immediate ack
1510 		 */
1511 		if (mptcp_data_avail(msk) < parent->sk_rcvlowat &&
1512 		    (tcp_sk(sk)->rcv_nxt - tcp_sk(sk)->rcv_wup) > inet_csk(sk)->icsk_ack.rcv_mss)
1513 			inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_NOW;
1514 	} else if (unlikely(sk->sk_err)) {
1515 		subflow_error_report(sk);
1516 	}
1517 }
1518 
1519 static void subflow_write_space(struct sock *ssk)
1520 {
1521 	struct sock *sk = mptcp_subflow_ctx(ssk)->conn;
1522 
1523 	mptcp_propagate_sndbuf(sk, ssk);
1524 	mptcp_write_space(sk);
1525 }
1526 
1527 static const struct inet_connection_sock_af_ops *
1528 subflow_default_af_ops(struct sock *sk)
1529 {
1530 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
1531 	if (sk->sk_family == AF_INET6)
1532 		return &subflow_v6_specific;
1533 #endif
1534 	return &subflow_specific;
1535 }
1536 
1537 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
1538 void mptcpv6_handle_mapped(struct sock *sk, bool mapped)
1539 {
1540 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(sk);
1541 	struct inet_connection_sock *icsk = inet_csk(sk);
1542 	const struct inet_connection_sock_af_ops *target;
1543 
1544 	target = mapped ? &subflow_v6m_specific : subflow_default_af_ops(sk);
1545 
1546 	pr_debug("subflow=%p family=%d ops=%p target=%p mapped=%d\n",
1547 		 subflow, sk->sk_family, icsk->icsk_af_ops, target, mapped);
1548 
1549 	if (likely(icsk->icsk_af_ops == target))
1550 		return;
1551 
1552 	subflow->icsk_af_ops = icsk->icsk_af_ops;
1553 	icsk->icsk_af_ops = target;
1554 }
1555 #endif
1556 
1557 void mptcp_info2sockaddr(const struct mptcp_addr_info *info,
1558 			 struct sockaddr_storage *addr,
1559 			 unsigned short family)
1560 {
1561 	memset(addr, 0, sizeof(*addr));
1562 	addr->ss_family = family;
1563 	if (addr->ss_family == AF_INET) {
1564 		struct sockaddr_in *in_addr = (struct sockaddr_in *)addr;
1565 
1566 		if (info->family == AF_INET)
1567 			in_addr->sin_addr = info->addr;
1568 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
1569 		else if (ipv6_addr_v4mapped(&info->addr6))
1570 			in_addr->sin_addr.s_addr = info->addr6.s6_addr32[3];
1571 #endif
1572 		in_addr->sin_port = info->port;
1573 	}
1574 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
1575 	else if (addr->ss_family == AF_INET6) {
1576 		struct sockaddr_in6 *in6_addr = (struct sockaddr_in6 *)addr;
1577 
1578 		if (info->family == AF_INET)
1579 			ipv6_addr_set_v4mapped(info->addr.s_addr,
1580 					       &in6_addr->sin6_addr);
1581 		else
1582 			in6_addr->sin6_addr = info->addr6;
1583 		in6_addr->sin6_port = info->port;
1584 	}
1585 #endif
1586 }
1587 
1588 int __mptcp_subflow_connect(struct sock *sk, const struct mptcp_pm_local *local,
1589 			    const struct mptcp_addr_info *remote)
1590 {
1591 	struct mptcp_sock *msk = mptcp_sk(sk);
1592 	struct mptcp_subflow_context *subflow;
1593 	int local_id = local->addr.id;
1594 	struct sockaddr_storage addr;
1595 	int remote_id = remote->id;
1596 	int err = -ENOTCONN;
1597 	struct socket *sf;
1598 	struct sock *ssk;
1599 	u32 remote_token;
1600 	int addrlen;
1601 
1602 	/* The userspace PM sent the request too early? */
1603 	if (!mptcp_is_fully_established(sk))
1604 		goto err_out;
1605 
1606 	err = mptcp_subflow_create_socket(sk, local->addr.family, &sf);
1607 	if (err) {
1608 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_JOINSYNTXCREATSKERR);
1609 		pr_debug("msk=%p local=%d remote=%d create sock error: %d\n",
1610 			 msk, local_id, remote_id, err);
1611 		goto err_out;
1612 	}
1613 
1614 	ssk = sf->sk;
1615 	subflow = mptcp_subflow_ctx(ssk);
1616 	do {
1617 		get_random_bytes(&subflow->local_nonce, sizeof(u32));
1618 	} while (!subflow->local_nonce);
1619 
1620 	/* if 'IPADDRANY', the ID will be set later, after the routing */
1621 	if (local->addr.family == AF_INET) {
1622 		if (!local->addr.addr.s_addr)
1623 			local_id = -1;
1624 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
1625 	} else if (sk->sk_family == AF_INET6) {
1626 		if (ipv6_addr_any(&local->addr.addr6))
1627 			local_id = -1;
1628 #endif
1629 	}
1630 
1631 	if (local_id >= 0)
1632 		subflow_set_local_id(subflow, local_id);
1633 
1634 	subflow->remote_key_valid = 1;
1635 	subflow->remote_key = READ_ONCE(msk->remote_key);
1636 	subflow->local_key = READ_ONCE(msk->local_key);
1637 	subflow->token = msk->token;
1638 	mptcp_info2sockaddr(&local->addr, &addr, ssk->sk_family);
1639 
1640 	addrlen = sizeof(struct sockaddr_in);
1641 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
1642 	if (addr.ss_family == AF_INET6)
1643 		addrlen = sizeof(struct sockaddr_in6);
1644 #endif
1645 	ssk->sk_bound_dev_if = local->ifindex;
1646 	err = kernel_bind(sf, (struct sockaddr *)&addr, addrlen);
1647 	if (err) {
1648 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_JOINSYNTXBINDERR);
1649 		pr_debug("msk=%p local=%d remote=%d bind error: %d\n",
1650 			 msk, local_id, remote_id, err);
1651 		goto failed;
1652 	}
1653 
1654 	mptcp_crypto_key_sha(subflow->remote_key, &remote_token, NULL);
1655 	pr_debug("msk=%p remote_token=%u local_id=%d remote_id=%d\n", msk,
1656 		 remote_token, local_id, remote_id);
1657 	subflow->remote_token = remote_token;
1658 	WRITE_ONCE(subflow->remote_id, remote_id);
1659 	subflow->request_join = 1;
1660 	subflow->request_bkup = !!(local->flags & MPTCP_PM_ADDR_FLAG_BACKUP);
1661 	subflow->subflow_id = msk->subflow_id++;
1662 	mptcp_info2sockaddr(remote, &addr, ssk->sk_family);
1663 
1664 	sock_hold(ssk);
1665 	list_add_tail(&subflow->node, &msk->conn_list);
1666 	err = kernel_connect(sf, (struct sockaddr *)&addr, addrlen, O_NONBLOCK);
1667 	if (err && err != -EINPROGRESS) {
1668 		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_JOINSYNTXCONNECTERR);
1669 		pr_debug("msk=%p local=%d remote=%d connect error: %d\n",
1670 			 msk, local_id, remote_id, err);
1671 		goto failed_unlink;
1672 	}
1673 
1674 	MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_JOINSYNTX);
1675 
1676 	/* discard the subflow socket */
1677 	mptcp_sock_graft(ssk, sk->sk_socket);
1678 	iput(SOCK_INODE(sf));
1679 	WRITE_ONCE(msk->allow_infinite_fallback, false);
1680 	mptcp_stop_tout_timer(sk);
1681 	return 0;
1682 
1683 failed_unlink:
1684 	list_del(&subflow->node);
1685 	sock_put(mptcp_subflow_tcp_sock(subflow));
1686 
1687 failed:
1688 	subflow->disposable = 1;
1689 	sock_release(sf);
1690 
1691 err_out:
1692 	/* we account subflows before the creation, and this failures will not
1693 	 * be caught by sk_state_change()
1694 	 */
1695 	mptcp_pm_close_subflow(msk);
1696 	return err;
1697 }
1698 
1699 static void mptcp_attach_cgroup(struct sock *parent, struct sock *child)
1700 {
1701 #ifdef CONFIG_SOCK_CGROUP_DATA
1702 	struct sock_cgroup_data *parent_skcd = &parent->sk_cgrp_data,
1703 				*child_skcd = &child->sk_cgrp_data;
1704 
1705 	/* only the additional subflows created by kworkers have to be modified */
1706 	if (cgroup_id(sock_cgroup_ptr(parent_skcd)) !=
1707 	    cgroup_id(sock_cgroup_ptr(child_skcd))) {
1708 #ifdef CONFIG_MEMCG
1709 		struct mem_cgroup *memcg = parent->sk_memcg;
1710 
1711 		mem_cgroup_sk_free(child);
1712 		if (memcg && css_tryget(&memcg->css))
1713 			child->sk_memcg = memcg;
1714 #endif /* CONFIG_MEMCG */
1715 
1716 		cgroup_sk_free(child_skcd);
1717 		*child_skcd = *parent_skcd;
1718 		cgroup_sk_clone(child_skcd);
1719 	}
1720 #endif /* CONFIG_SOCK_CGROUP_DATA */
1721 }
1722 
1723 static void mptcp_subflow_ops_override(struct sock *ssk)
1724 {
1725 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
1726 	if (ssk->sk_prot == &tcpv6_prot)
1727 		ssk->sk_prot = &tcpv6_prot_override;
1728 	else
1729 #endif
1730 		ssk->sk_prot = &tcp_prot_override;
1731 }
1732 
1733 static void mptcp_subflow_ops_undo_override(struct sock *ssk)
1734 {
1735 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
1736 	if (ssk->sk_prot == &tcpv6_prot_override)
1737 		ssk->sk_prot = &tcpv6_prot;
1738 	else
1739 #endif
1740 		ssk->sk_prot = &tcp_prot;
1741 }
1742 
1743 int mptcp_subflow_create_socket(struct sock *sk, unsigned short family,
1744 				struct socket **new_sock)
1745 {
1746 	struct mptcp_subflow_context *subflow;
1747 	struct net *net = sock_net(sk);
1748 	struct socket *sf;
1749 	int err;
1750 
1751 	/* un-accepted server sockets can reach here - on bad configuration
1752 	 * bail early to avoid greater trouble later
1753 	 */
1754 	if (unlikely(!sk->sk_socket))
1755 		return -EINVAL;
1756 
1757 	err = sock_create_kern(net, family, SOCK_STREAM, IPPROTO_TCP, &sf);
1758 	if (err)
1759 		return err;
1760 
1761 	lock_sock_nested(sf->sk, SINGLE_DEPTH_NESTING);
1762 
1763 	err = security_mptcp_add_subflow(sk, sf->sk);
1764 	if (err)
1765 		goto err_free;
1766 
1767 	/* the newly created socket has to be in the same cgroup as its parent */
1768 	mptcp_attach_cgroup(sk, sf->sk);
1769 
1770 	/* kernel sockets do not by default acquire net ref, but TCP timer
1771 	 * needs it.
1772 	 * Update ns_tracker to current stack trace and refcounted tracker.
1773 	 */
1774 	sk_net_refcnt_upgrade(sf->sk);
1775 	err = tcp_set_ulp(sf->sk, "mptcp");
1776 	if (err)
1777 		goto err_free;
1778 
1779 	mptcp_sockopt_sync_locked(mptcp_sk(sk), sf->sk);
1780 	release_sock(sf->sk);
1781 
1782 	/* the newly created socket really belongs to the owning MPTCP
1783 	 * socket, even if for additional subflows the allocation is performed
1784 	 * by a kernel workqueue. Adjust inode references, so that the
1785 	 * procfs/diag interfaces really show this one belonging to the correct
1786 	 * user.
1787 	 */
1788 	SOCK_INODE(sf)->i_ino = SOCK_INODE(sk->sk_socket)->i_ino;
1789 	SOCK_INODE(sf)->i_uid = SOCK_INODE(sk->sk_socket)->i_uid;
1790 	SOCK_INODE(sf)->i_gid = SOCK_INODE(sk->sk_socket)->i_gid;
1791 
1792 	subflow = mptcp_subflow_ctx(sf->sk);
1793 	pr_debug("subflow=%p\n", subflow);
1794 
1795 	*new_sock = sf;
1796 	sock_hold(sk);
1797 	subflow->conn = sk;
1798 	mptcp_subflow_ops_override(sf->sk);
1799 
1800 	return 0;
1801 
1802 err_free:
1803 	release_sock(sf->sk);
1804 	sock_release(sf);
1805 	return err;
1806 }
1807 
1808 static struct mptcp_subflow_context *subflow_create_ctx(struct sock *sk,
1809 							gfp_t priority)
1810 {
1811 	struct inet_connection_sock *icsk = inet_csk(sk);
1812 	struct mptcp_subflow_context *ctx;
1813 
1814 	ctx = kzalloc(sizeof(*ctx), priority);
1815 	if (!ctx)
1816 		return NULL;
1817 
1818 	rcu_assign_pointer(icsk->icsk_ulp_data, ctx);
1819 	INIT_LIST_HEAD(&ctx->node);
1820 	INIT_LIST_HEAD(&ctx->delegated_node);
1821 
1822 	pr_debug("subflow=%p\n", ctx);
1823 
1824 	ctx->tcp_sock = sk;
1825 	WRITE_ONCE(ctx->local_id, -1);
1826 
1827 	return ctx;
1828 }
1829 
1830 static void __subflow_state_change(struct sock *sk)
1831 {
1832 	struct socket_wq *wq;
1833 
1834 	rcu_read_lock();
1835 	wq = rcu_dereference(sk->sk_wq);
1836 	if (skwq_has_sleeper(wq))
1837 		wake_up_interruptible_all(&wq->wait);
1838 	rcu_read_unlock();
1839 }
1840 
1841 static void subflow_state_change(struct sock *sk)
1842 {
1843 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(sk);
1844 	struct sock *parent = subflow->conn;
1845 	struct mptcp_sock *msk;
1846 
1847 	__subflow_state_change(sk);
1848 
1849 	msk = mptcp_sk(parent);
1850 	if (subflow_simultaneous_connect(sk)) {
1851 		mptcp_do_fallback(sk);
1852 		pr_fallback(msk);
1853 		subflow->conn_finished = 1;
1854 		mptcp_propagate_state(parent, sk, subflow, NULL);
1855 	}
1856 
1857 	/* as recvmsg() does not acquire the subflow socket for ssk selection
1858 	 * a fin packet carrying a DSS can be unnoticed if we don't trigger
1859 	 * the data available machinery here.
1860 	 */
1861 	if (mptcp_subflow_data_available(sk))
1862 		mptcp_data_ready(parent, sk);
1863 	else if (unlikely(sk->sk_err))
1864 		subflow_error_report(sk);
1865 
1866 	subflow_sched_work_if_closed(mptcp_sk(parent), sk);
1867 }
1868 
1869 void mptcp_subflow_queue_clean(struct sock *listener_sk, struct sock *listener_ssk)
1870 {
1871 	struct request_sock_queue *queue = &inet_csk(listener_ssk)->icsk_accept_queue;
1872 	struct request_sock *req, *head, *tail;
1873 	struct mptcp_subflow_context *subflow;
1874 	struct sock *sk, *ssk;
1875 
1876 	/* Due to lock dependencies no relevant lock can be acquired under rskq_lock.
1877 	 * Splice the req list, so that accept() can not reach the pending ssk after
1878 	 * the listener socket is released below.
1879 	 */
1880 	spin_lock_bh(&queue->rskq_lock);
1881 	head = queue->rskq_accept_head;
1882 	tail = queue->rskq_accept_tail;
1883 	queue->rskq_accept_head = NULL;
1884 	queue->rskq_accept_tail = NULL;
1885 	spin_unlock_bh(&queue->rskq_lock);
1886 
1887 	if (!head)
1888 		return;
1889 
1890 	/* can't acquire the msk socket lock under the subflow one,
1891 	 * or will cause ABBA deadlock
1892 	 */
1893 	release_sock(listener_ssk);
1894 
1895 	for (req = head; req; req = req->dl_next) {
1896 		ssk = req->sk;
1897 		if (!sk_is_mptcp(ssk))
1898 			continue;
1899 
1900 		subflow = mptcp_subflow_ctx(ssk);
1901 		if (!subflow || !subflow->conn)
1902 			continue;
1903 
1904 		sk = subflow->conn;
1905 		sock_hold(sk);
1906 
1907 		lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
1908 		__mptcp_unaccepted_force_close(sk);
1909 		release_sock(sk);
1910 
1911 		/* lockdep will report a false positive ABBA deadlock
1912 		 * between cancel_work_sync and the listener socket.
1913 		 * The involved locks belong to different sockets WRT
1914 		 * the existing AB chain.
1915 		 * Using a per socket key is problematic as key
1916 		 * deregistration requires process context and must be
1917 		 * performed at socket disposal time, in atomic
1918 		 * context.
1919 		 * Just tell lockdep to consider the listener socket
1920 		 * released here.
1921 		 */
1922 		mutex_release(&listener_sk->sk_lock.dep_map, _RET_IP_);
1923 		mptcp_cancel_work(sk);
1924 		mutex_acquire(&listener_sk->sk_lock.dep_map, 0, 0, _RET_IP_);
1925 
1926 		sock_put(sk);
1927 	}
1928 
1929 	/* we are still under the listener msk socket lock */
1930 	lock_sock_nested(listener_ssk, SINGLE_DEPTH_NESTING);
1931 
1932 	/* restore the listener queue, to let the TCP code clean it up */
1933 	spin_lock_bh(&queue->rskq_lock);
1934 	WARN_ON_ONCE(queue->rskq_accept_head);
1935 	queue->rskq_accept_head = head;
1936 	queue->rskq_accept_tail = tail;
1937 	spin_unlock_bh(&queue->rskq_lock);
1938 }
1939 
1940 static int subflow_ulp_init(struct sock *sk)
1941 {
1942 	struct inet_connection_sock *icsk = inet_csk(sk);
1943 	struct mptcp_subflow_context *ctx;
1944 	struct tcp_sock *tp = tcp_sk(sk);
1945 	int err = 0;
1946 
1947 	/* disallow attaching ULP to a socket unless it has been
1948 	 * created with sock_create_kern()
1949 	 */
1950 	if (!sk->sk_kern_sock) {
1951 		err = -EOPNOTSUPP;
1952 		goto out;
1953 	}
1954 
1955 	ctx = subflow_create_ctx(sk, GFP_KERNEL);
1956 	if (!ctx) {
1957 		err = -ENOMEM;
1958 		goto out;
1959 	}
1960 
1961 	pr_debug("subflow=%p, family=%d\n", ctx, sk->sk_family);
1962 
1963 	tp->is_mptcp = 1;
1964 	ctx->icsk_af_ops = icsk->icsk_af_ops;
1965 	icsk->icsk_af_ops = subflow_default_af_ops(sk);
1966 	ctx->tcp_state_change = sk->sk_state_change;
1967 	ctx->tcp_error_report = sk->sk_error_report;
1968 
1969 	WARN_ON_ONCE(sk->sk_data_ready != sock_def_readable);
1970 	WARN_ON_ONCE(sk->sk_write_space != sk_stream_write_space);
1971 
1972 	sk->sk_data_ready = subflow_data_ready;
1973 	sk->sk_write_space = subflow_write_space;
1974 	sk->sk_state_change = subflow_state_change;
1975 	sk->sk_error_report = subflow_error_report;
1976 out:
1977 	return err;
1978 }
1979 
1980 static void subflow_ulp_release(struct sock *ssk)
1981 {
1982 	struct mptcp_subflow_context *ctx = mptcp_subflow_ctx(ssk);
1983 	bool release = true;
1984 	struct sock *sk;
1985 
1986 	if (!ctx)
1987 		return;
1988 
1989 	sk = ctx->conn;
1990 	if (sk) {
1991 		/* if the msk has been orphaned, keep the ctx
1992 		 * alive, will be freed by __mptcp_close_ssk(),
1993 		 * when the subflow is still unaccepted
1994 		 */
1995 		release = ctx->disposable || list_empty(&ctx->node);
1996 
1997 		/* inet_child_forget() does not call sk_state_change(),
1998 		 * explicitly trigger the socket close machinery
1999 		 */
2000 		if (!release && !test_and_set_bit(MPTCP_WORK_CLOSE_SUBFLOW,
2001 						  &mptcp_sk(sk)->flags))
2002 			mptcp_schedule_work(sk);
2003 		sock_put(sk);
2004 	}
2005 
2006 	mptcp_subflow_ops_undo_override(ssk);
2007 	if (release)
2008 		kfree_rcu(ctx, rcu);
2009 }
2010 
2011 static void subflow_ulp_clone(const struct request_sock *req,
2012 			      struct sock *newsk,
2013 			      const gfp_t priority)
2014 {
2015 	struct mptcp_subflow_request_sock *subflow_req = mptcp_subflow_rsk(req);
2016 	struct mptcp_subflow_context *old_ctx = mptcp_subflow_ctx(newsk);
2017 	struct mptcp_subflow_context *new_ctx;
2018 
2019 	if (!tcp_rsk(req)->is_mptcp ||
2020 	    (!subflow_req->mp_capable && !subflow_req->mp_join)) {
2021 		subflow_ulp_fallback(newsk, old_ctx);
2022 		return;
2023 	}
2024 
2025 	new_ctx = subflow_create_ctx(newsk, priority);
2026 	if (!new_ctx) {
2027 		subflow_ulp_fallback(newsk, old_ctx);
2028 		return;
2029 	}
2030 
2031 	new_ctx->conn_finished = 1;
2032 	new_ctx->icsk_af_ops = old_ctx->icsk_af_ops;
2033 	new_ctx->tcp_state_change = old_ctx->tcp_state_change;
2034 	new_ctx->tcp_error_report = old_ctx->tcp_error_report;
2035 	new_ctx->rel_write_seq = 1;
2036 
2037 	if (subflow_req->mp_capable) {
2038 		/* see comments in subflow_syn_recv_sock(), MPTCP connection
2039 		 * is fully established only after we receive the remote key
2040 		 */
2041 		new_ctx->mp_capable = 1;
2042 		new_ctx->local_key = subflow_req->local_key;
2043 		new_ctx->token = subflow_req->token;
2044 		new_ctx->ssn_offset = subflow_req->ssn_offset;
2045 		new_ctx->idsn = subflow_req->idsn;
2046 
2047 		/* this is the first subflow, id is always 0 */
2048 		subflow_set_local_id(new_ctx, 0);
2049 	} else if (subflow_req->mp_join) {
2050 		new_ctx->ssn_offset = subflow_req->ssn_offset;
2051 		new_ctx->mp_join = 1;
2052 		WRITE_ONCE(new_ctx->fully_established, true);
2053 		new_ctx->remote_key_valid = 1;
2054 		new_ctx->backup = subflow_req->backup;
2055 		new_ctx->request_bkup = subflow_req->request_bkup;
2056 		WRITE_ONCE(new_ctx->remote_id, subflow_req->remote_id);
2057 		new_ctx->token = subflow_req->token;
2058 		new_ctx->thmac = subflow_req->thmac;
2059 
2060 		/* the subflow req id is valid, fetched via subflow_check_req()
2061 		 * and subflow_token_join_request()
2062 		 */
2063 		subflow_set_local_id(new_ctx, subflow_req->local_id);
2064 	}
2065 }
2066 
2067 static void tcp_release_cb_override(struct sock *ssk)
2068 {
2069 	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
2070 	long status;
2071 
2072 	/* process and clear all the pending actions, but leave the subflow into
2073 	 * the napi queue. To respect locking, only the same CPU that originated
2074 	 * the action can touch the list. mptcp_napi_poll will take care of it.
2075 	 */
2076 	status = set_mask_bits(&subflow->delegated_status, MPTCP_DELEGATE_ACTIONS_MASK, 0);
2077 	if (status)
2078 		mptcp_subflow_process_delegated(ssk, status);
2079 
2080 	tcp_release_cb(ssk);
2081 }
2082 
2083 static int tcp_abort_override(struct sock *ssk, int err)
2084 {
2085 	/* closing a listener subflow requires a great deal of care.
2086 	 * keep it simple and just prevent such operation
2087 	 */
2088 	if (inet_sk_state_load(ssk) == TCP_LISTEN)
2089 		return -EINVAL;
2090 
2091 	return tcp_abort(ssk, err);
2092 }
2093 
2094 static struct tcp_ulp_ops subflow_ulp_ops __read_mostly = {
2095 	.name		= "mptcp",
2096 	.owner		= THIS_MODULE,
2097 	.init		= subflow_ulp_init,
2098 	.release	= subflow_ulp_release,
2099 	.clone		= subflow_ulp_clone,
2100 };
2101 
2102 static int subflow_ops_init(struct request_sock_ops *subflow_ops)
2103 {
2104 	subflow_ops->obj_size = sizeof(struct mptcp_subflow_request_sock);
2105 
2106 	subflow_ops->slab = kmem_cache_create(subflow_ops->slab_name,
2107 					      subflow_ops->obj_size, 0,
2108 					      SLAB_ACCOUNT |
2109 					      SLAB_TYPESAFE_BY_RCU,
2110 					      NULL);
2111 	if (!subflow_ops->slab)
2112 		return -ENOMEM;
2113 
2114 	return 0;
2115 }
2116 
2117 void __init mptcp_subflow_init(void)
2118 {
2119 	mptcp_subflow_v4_request_sock_ops = tcp_request_sock_ops;
2120 	mptcp_subflow_v4_request_sock_ops.slab_name = "request_sock_subflow_v4";
2121 	mptcp_subflow_v4_request_sock_ops.destructor = subflow_v4_req_destructor;
2122 
2123 	if (subflow_ops_init(&mptcp_subflow_v4_request_sock_ops) != 0)
2124 		panic("MPTCP: failed to init subflow v4 request sock ops\n");
2125 
2126 	subflow_request_sock_ipv4_ops = tcp_request_sock_ipv4_ops;
2127 	subflow_request_sock_ipv4_ops.route_req = subflow_v4_route_req;
2128 	subflow_request_sock_ipv4_ops.send_synack = subflow_v4_send_synack;
2129 
2130 	subflow_specific = ipv4_specific;
2131 	subflow_specific.conn_request = subflow_v4_conn_request;
2132 	subflow_specific.syn_recv_sock = subflow_syn_recv_sock;
2133 	subflow_specific.sk_rx_dst_set = subflow_finish_connect;
2134 	subflow_specific.rebuild_header = subflow_rebuild_header;
2135 
2136 	tcp_prot_override = tcp_prot;
2137 	tcp_prot_override.release_cb = tcp_release_cb_override;
2138 	tcp_prot_override.diag_destroy = tcp_abort_override;
2139 
2140 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2141 	/* In struct mptcp_subflow_request_sock, we assume the TCP request sock
2142 	 * structures for v4 and v6 have the same size. It should not changed in
2143 	 * the future but better to make sure to be warned if it is no longer
2144 	 * the case.
2145 	 */
2146 	BUILD_BUG_ON(sizeof(struct tcp_request_sock) != sizeof(struct tcp6_request_sock));
2147 
2148 	mptcp_subflow_v6_request_sock_ops = tcp6_request_sock_ops;
2149 	mptcp_subflow_v6_request_sock_ops.slab_name = "request_sock_subflow_v6";
2150 	mptcp_subflow_v6_request_sock_ops.destructor = subflow_v6_req_destructor;
2151 
2152 	if (subflow_ops_init(&mptcp_subflow_v6_request_sock_ops) != 0)
2153 		panic("MPTCP: failed to init subflow v6 request sock ops\n");
2154 
2155 	subflow_request_sock_ipv6_ops = tcp_request_sock_ipv6_ops;
2156 	subflow_request_sock_ipv6_ops.route_req = subflow_v6_route_req;
2157 	subflow_request_sock_ipv6_ops.send_synack = subflow_v6_send_synack;
2158 
2159 	subflow_v6_specific = ipv6_specific;
2160 	subflow_v6_specific.conn_request = subflow_v6_conn_request;
2161 	subflow_v6_specific.syn_recv_sock = subflow_syn_recv_sock;
2162 	subflow_v6_specific.sk_rx_dst_set = subflow_finish_connect;
2163 	subflow_v6_specific.rebuild_header = subflow_v6_rebuild_header;
2164 
2165 	subflow_v6m_specific = subflow_v6_specific;
2166 	subflow_v6m_specific.queue_xmit = ipv4_specific.queue_xmit;
2167 	subflow_v6m_specific.send_check = ipv4_specific.send_check;
2168 	subflow_v6m_specific.net_header_len = ipv4_specific.net_header_len;
2169 	subflow_v6m_specific.mtu_reduced = ipv4_specific.mtu_reduced;
2170 	subflow_v6m_specific.rebuild_header = subflow_rebuild_header;
2171 
2172 	tcpv6_prot_override = tcpv6_prot;
2173 	tcpv6_prot_override.release_cb = tcp_release_cb_override;
2174 	tcpv6_prot_override.diag_destroy = tcp_abort_override;
2175 #endif
2176 
2177 	mptcp_diag_subflow_init(&subflow_ulp_ops);
2178 
2179 	if (tcp_register_ulp(&subflow_ulp_ops) != 0)
2180 		panic("MPTCP: failed to register subflows to ULP\n");
2181 }
2182