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