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