tls: rx: read the input skb from ctx->recv_pkt
[linux-2.6-microblaze.git] / net / tls / tls_sw.c
1 /*
2  * Copyright (c) 2016-2017, Mellanox Technologies. All rights reserved.
3  * Copyright (c) 2016-2017, Dave Watson <davejwatson@fb.com>. All rights reserved.
4  * Copyright (c) 2016-2017, Lance Chao <lancerchao@fb.com>. All rights reserved.
5  * Copyright (c) 2016, Fridolin Pokorny <fridolin.pokorny@gmail.com>. All rights reserved.
6  * Copyright (c) 2016, Nikos Mavrogiannopoulos <nmav@gnutls.org>. All rights reserved.
7  * Copyright (c) 2018, Covalent IO, Inc. http://covalent.io
8  *
9  * This software is available to you under a choice of one of two
10  * licenses.  You may choose to be licensed under the terms of the GNU
11  * General Public License (GPL) Version 2, available from the file
12  * COPYING in the main directory of this source tree, or the
13  * OpenIB.org BSD license below:
14  *
15  *     Redistribution and use in source and binary forms, with or
16  *     without modification, are permitted provided that the following
17  *     conditions are met:
18  *
19  *      - Redistributions of source code must retain the above
20  *        copyright notice, this list of conditions and the following
21  *        disclaimer.
22  *
23  *      - Redistributions in binary form must reproduce the above
24  *        copyright notice, this list of conditions and the following
25  *        disclaimer in the documentation and/or other materials
26  *        provided with the distribution.
27  *
28  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
29  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
31  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
32  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
33  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35  * SOFTWARE.
36  */
37
38 #include <linux/bug.h>
39 #include <linux/sched/signal.h>
40 #include <linux/module.h>
41 #include <linux/splice.h>
42 #include <crypto/aead.h>
43
44 #include <net/strparser.h>
45 #include <net/tls.h>
46
47 #include "tls.h"
48
49 struct tls_decrypt_arg {
50         bool zc;
51         bool async;
52         u8 tail;
53 };
54
55 struct tls_decrypt_ctx {
56         u8 iv[MAX_IV_SIZE];
57         u8 aad[TLS_MAX_AAD_SIZE];
58         u8 tail;
59         struct scatterlist sg[];
60 };
61
62 noinline void tls_err_abort(struct sock *sk, int err)
63 {
64         WARN_ON_ONCE(err >= 0);
65         /* sk->sk_err should contain a positive error code. */
66         sk->sk_err = -err;
67         sk_error_report(sk);
68 }
69
70 static int __skb_nsg(struct sk_buff *skb, int offset, int len,
71                      unsigned int recursion_level)
72 {
73         int start = skb_headlen(skb);
74         int i, chunk = start - offset;
75         struct sk_buff *frag_iter;
76         int elt = 0;
77
78         if (unlikely(recursion_level >= 24))
79                 return -EMSGSIZE;
80
81         if (chunk > 0) {
82                 if (chunk > len)
83                         chunk = len;
84                 elt++;
85                 len -= chunk;
86                 if (len == 0)
87                         return elt;
88                 offset += chunk;
89         }
90
91         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
92                 int end;
93
94                 WARN_ON(start > offset + len);
95
96                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
97                 chunk = end - offset;
98                 if (chunk > 0) {
99                         if (chunk > len)
100                                 chunk = len;
101                         elt++;
102                         len -= chunk;
103                         if (len == 0)
104                                 return elt;
105                         offset += chunk;
106                 }
107                 start = end;
108         }
109
110         if (unlikely(skb_has_frag_list(skb))) {
111                 skb_walk_frags(skb, frag_iter) {
112                         int end, ret;
113
114                         WARN_ON(start > offset + len);
115
116                         end = start + frag_iter->len;
117                         chunk = end - offset;
118                         if (chunk > 0) {
119                                 if (chunk > len)
120                                         chunk = len;
121                                 ret = __skb_nsg(frag_iter, offset - start, chunk,
122                                                 recursion_level + 1);
123                                 if (unlikely(ret < 0))
124                                         return ret;
125                                 elt += ret;
126                                 len -= chunk;
127                                 if (len == 0)
128                                         return elt;
129                                 offset += chunk;
130                         }
131                         start = end;
132                 }
133         }
134         BUG_ON(len);
135         return elt;
136 }
137
138 /* Return the number of scatterlist elements required to completely map the
139  * skb, or -EMSGSIZE if the recursion depth is exceeded.
140  */
141 static int skb_nsg(struct sk_buff *skb, int offset, int len)
142 {
143         return __skb_nsg(skb, offset, len, 0);
144 }
145
146 static int tls_padding_length(struct tls_prot_info *prot, struct sk_buff *skb,
147                               struct tls_decrypt_arg *darg)
148 {
149         struct strp_msg *rxm = strp_msg(skb);
150         struct tls_msg *tlm = tls_msg(skb);
151         int sub = 0;
152
153         /* Determine zero-padding length */
154         if (prot->version == TLS_1_3_VERSION) {
155                 int offset = rxm->full_len - TLS_TAG_SIZE - 1;
156                 char content_type = darg->zc ? darg->tail : 0;
157                 int err;
158
159                 while (content_type == 0) {
160                         if (offset < prot->prepend_size)
161                                 return -EBADMSG;
162                         err = skb_copy_bits(skb, rxm->offset + offset,
163                                             &content_type, 1);
164                         if (err)
165                                 return err;
166                         if (content_type)
167                                 break;
168                         sub++;
169                         offset--;
170                 }
171                 tlm->control = content_type;
172         }
173         return sub;
174 }
175
176 static void tls_decrypt_done(struct crypto_async_request *req, int err)
177 {
178         struct aead_request *aead_req = (struct aead_request *)req;
179         struct scatterlist *sgout = aead_req->dst;
180         struct scatterlist *sgin = aead_req->src;
181         struct tls_sw_context_rx *ctx;
182         struct tls_context *tls_ctx;
183         struct tls_prot_info *prot;
184         struct scatterlist *sg;
185         struct sk_buff *skb;
186         unsigned int pages;
187
188         skb = (struct sk_buff *)req->data;
189         tls_ctx = tls_get_ctx(skb->sk);
190         ctx = tls_sw_ctx_rx(tls_ctx);
191         prot = &tls_ctx->prot_info;
192
193         /* Propagate if there was an err */
194         if (err) {
195                 if (err == -EBADMSG)
196                         TLS_INC_STATS(sock_net(skb->sk),
197                                       LINUX_MIB_TLSDECRYPTERROR);
198                 ctx->async_wait.err = err;
199                 tls_err_abort(skb->sk, err);
200         } else {
201                 struct strp_msg *rxm = strp_msg(skb);
202
203                 /* No TLS 1.3 support with async crypto */
204                 WARN_ON(prot->tail_size);
205
206                 rxm->offset += prot->prepend_size;
207                 rxm->full_len -= prot->overhead_size;
208         }
209
210         /* After using skb->sk to propagate sk through crypto async callback
211          * we need to NULL it again.
212          */
213         skb->sk = NULL;
214
215
216         /* Free the destination pages if skb was not decrypted inplace */
217         if (sgout != sgin) {
218                 /* Skip the first S/G entry as it points to AAD */
219                 for_each_sg(sg_next(sgout), sg, UINT_MAX, pages) {
220                         if (!sg)
221                                 break;
222                         put_page(sg_page(sg));
223                 }
224         }
225
226         kfree(aead_req);
227
228         spin_lock_bh(&ctx->decrypt_compl_lock);
229         if (!atomic_dec_return(&ctx->decrypt_pending))
230                 complete(&ctx->async_wait.completion);
231         spin_unlock_bh(&ctx->decrypt_compl_lock);
232 }
233
234 static int tls_do_decryption(struct sock *sk,
235                              struct sk_buff *skb,
236                              struct scatterlist *sgin,
237                              struct scatterlist *sgout,
238                              char *iv_recv,
239                              size_t data_len,
240                              struct aead_request *aead_req,
241                              struct tls_decrypt_arg *darg)
242 {
243         struct tls_context *tls_ctx = tls_get_ctx(sk);
244         struct tls_prot_info *prot = &tls_ctx->prot_info;
245         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
246         int ret;
247
248         aead_request_set_tfm(aead_req, ctx->aead_recv);
249         aead_request_set_ad(aead_req, prot->aad_size);
250         aead_request_set_crypt(aead_req, sgin, sgout,
251                                data_len + prot->tag_size,
252                                (u8 *)iv_recv);
253
254         if (darg->async) {
255                 /* Using skb->sk to push sk through to crypto async callback
256                  * handler. This allows propagating errors up to the socket
257                  * if needed. It _must_ be cleared in the async handler
258                  * before consume_skb is called. We _know_ skb->sk is NULL
259                  * because it is a clone from strparser.
260                  */
261                 skb->sk = sk;
262                 aead_request_set_callback(aead_req,
263                                           CRYPTO_TFM_REQ_MAY_BACKLOG,
264                                           tls_decrypt_done, skb);
265                 atomic_inc(&ctx->decrypt_pending);
266         } else {
267                 aead_request_set_callback(aead_req,
268                                           CRYPTO_TFM_REQ_MAY_BACKLOG,
269                                           crypto_req_done, &ctx->async_wait);
270         }
271
272         ret = crypto_aead_decrypt(aead_req);
273         if (ret == -EINPROGRESS) {
274                 if (darg->async)
275                         return 0;
276
277                 ret = crypto_wait_req(ret, &ctx->async_wait);
278         }
279         darg->async = false;
280
281         return ret;
282 }
283
284 static void tls_trim_both_msgs(struct sock *sk, int target_size)
285 {
286         struct tls_context *tls_ctx = tls_get_ctx(sk);
287         struct tls_prot_info *prot = &tls_ctx->prot_info;
288         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
289         struct tls_rec *rec = ctx->open_rec;
290
291         sk_msg_trim(sk, &rec->msg_plaintext, target_size);
292         if (target_size > 0)
293                 target_size += prot->overhead_size;
294         sk_msg_trim(sk, &rec->msg_encrypted, target_size);
295 }
296
297 static int tls_alloc_encrypted_msg(struct sock *sk, int len)
298 {
299         struct tls_context *tls_ctx = tls_get_ctx(sk);
300         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
301         struct tls_rec *rec = ctx->open_rec;
302         struct sk_msg *msg_en = &rec->msg_encrypted;
303
304         return sk_msg_alloc(sk, msg_en, len, 0);
305 }
306
307 static int tls_clone_plaintext_msg(struct sock *sk, int required)
308 {
309         struct tls_context *tls_ctx = tls_get_ctx(sk);
310         struct tls_prot_info *prot = &tls_ctx->prot_info;
311         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
312         struct tls_rec *rec = ctx->open_rec;
313         struct sk_msg *msg_pl = &rec->msg_plaintext;
314         struct sk_msg *msg_en = &rec->msg_encrypted;
315         int skip, len;
316
317         /* We add page references worth len bytes from encrypted sg
318          * at the end of plaintext sg. It is guaranteed that msg_en
319          * has enough required room (ensured by caller).
320          */
321         len = required - msg_pl->sg.size;
322
323         /* Skip initial bytes in msg_en's data to be able to use
324          * same offset of both plain and encrypted data.
325          */
326         skip = prot->prepend_size + msg_pl->sg.size;
327
328         return sk_msg_clone(sk, msg_pl, msg_en, skip, len);
329 }
330
331 static struct tls_rec *tls_get_rec(struct sock *sk)
332 {
333         struct tls_context *tls_ctx = tls_get_ctx(sk);
334         struct tls_prot_info *prot = &tls_ctx->prot_info;
335         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
336         struct sk_msg *msg_pl, *msg_en;
337         struct tls_rec *rec;
338         int mem_size;
339
340         mem_size = sizeof(struct tls_rec) + crypto_aead_reqsize(ctx->aead_send);
341
342         rec = kzalloc(mem_size, sk->sk_allocation);
343         if (!rec)
344                 return NULL;
345
346         msg_pl = &rec->msg_plaintext;
347         msg_en = &rec->msg_encrypted;
348
349         sk_msg_init(msg_pl);
350         sk_msg_init(msg_en);
351
352         sg_init_table(rec->sg_aead_in, 2);
353         sg_set_buf(&rec->sg_aead_in[0], rec->aad_space, prot->aad_size);
354         sg_unmark_end(&rec->sg_aead_in[1]);
355
356         sg_init_table(rec->sg_aead_out, 2);
357         sg_set_buf(&rec->sg_aead_out[0], rec->aad_space, prot->aad_size);
358         sg_unmark_end(&rec->sg_aead_out[1]);
359
360         return rec;
361 }
362
363 static void tls_free_rec(struct sock *sk, struct tls_rec *rec)
364 {
365         sk_msg_free(sk, &rec->msg_encrypted);
366         sk_msg_free(sk, &rec->msg_plaintext);
367         kfree(rec);
368 }
369
370 static void tls_free_open_rec(struct sock *sk)
371 {
372         struct tls_context *tls_ctx = tls_get_ctx(sk);
373         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
374         struct tls_rec *rec = ctx->open_rec;
375
376         if (rec) {
377                 tls_free_rec(sk, rec);
378                 ctx->open_rec = NULL;
379         }
380 }
381
382 int tls_tx_records(struct sock *sk, int flags)
383 {
384         struct tls_context *tls_ctx = tls_get_ctx(sk);
385         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
386         struct tls_rec *rec, *tmp;
387         struct sk_msg *msg_en;
388         int tx_flags, rc = 0;
389
390         if (tls_is_partially_sent_record(tls_ctx)) {
391                 rec = list_first_entry(&ctx->tx_list,
392                                        struct tls_rec, list);
393
394                 if (flags == -1)
395                         tx_flags = rec->tx_flags;
396                 else
397                         tx_flags = flags;
398
399                 rc = tls_push_partial_record(sk, tls_ctx, tx_flags);
400                 if (rc)
401                         goto tx_err;
402
403                 /* Full record has been transmitted.
404                  * Remove the head of tx_list
405                  */
406                 list_del(&rec->list);
407                 sk_msg_free(sk, &rec->msg_plaintext);
408                 kfree(rec);
409         }
410
411         /* Tx all ready records */
412         list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
413                 if (READ_ONCE(rec->tx_ready)) {
414                         if (flags == -1)
415                                 tx_flags = rec->tx_flags;
416                         else
417                                 tx_flags = flags;
418
419                         msg_en = &rec->msg_encrypted;
420                         rc = tls_push_sg(sk, tls_ctx,
421                                          &msg_en->sg.data[msg_en->sg.curr],
422                                          0, tx_flags);
423                         if (rc)
424                                 goto tx_err;
425
426                         list_del(&rec->list);
427                         sk_msg_free(sk, &rec->msg_plaintext);
428                         kfree(rec);
429                 } else {
430                         break;
431                 }
432         }
433
434 tx_err:
435         if (rc < 0 && rc != -EAGAIN)
436                 tls_err_abort(sk, -EBADMSG);
437
438         return rc;
439 }
440
441 static void tls_encrypt_done(struct crypto_async_request *req, int err)
442 {
443         struct aead_request *aead_req = (struct aead_request *)req;
444         struct sock *sk = req->data;
445         struct tls_context *tls_ctx = tls_get_ctx(sk);
446         struct tls_prot_info *prot = &tls_ctx->prot_info;
447         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
448         struct scatterlist *sge;
449         struct sk_msg *msg_en;
450         struct tls_rec *rec;
451         bool ready = false;
452         int pending;
453
454         rec = container_of(aead_req, struct tls_rec, aead_req);
455         msg_en = &rec->msg_encrypted;
456
457         sge = sk_msg_elem(msg_en, msg_en->sg.curr);
458         sge->offset -= prot->prepend_size;
459         sge->length += prot->prepend_size;
460
461         /* Check if error is previously set on socket */
462         if (err || sk->sk_err) {
463                 rec = NULL;
464
465                 /* If err is already set on socket, return the same code */
466                 if (sk->sk_err) {
467                         ctx->async_wait.err = -sk->sk_err;
468                 } else {
469                         ctx->async_wait.err = err;
470                         tls_err_abort(sk, err);
471                 }
472         }
473
474         if (rec) {
475                 struct tls_rec *first_rec;
476
477                 /* Mark the record as ready for transmission */
478                 smp_store_mb(rec->tx_ready, true);
479
480                 /* If received record is at head of tx_list, schedule tx */
481                 first_rec = list_first_entry(&ctx->tx_list,
482                                              struct tls_rec, list);
483                 if (rec == first_rec)
484                         ready = true;
485         }
486
487         spin_lock_bh(&ctx->encrypt_compl_lock);
488         pending = atomic_dec_return(&ctx->encrypt_pending);
489
490         if (!pending && ctx->async_notify)
491                 complete(&ctx->async_wait.completion);
492         spin_unlock_bh(&ctx->encrypt_compl_lock);
493
494         if (!ready)
495                 return;
496
497         /* Schedule the transmission */
498         if (!test_and_set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
499                 schedule_delayed_work(&ctx->tx_work.work, 1);
500 }
501
502 static int tls_do_encryption(struct sock *sk,
503                              struct tls_context *tls_ctx,
504                              struct tls_sw_context_tx *ctx,
505                              struct aead_request *aead_req,
506                              size_t data_len, u32 start)
507 {
508         struct tls_prot_info *prot = &tls_ctx->prot_info;
509         struct tls_rec *rec = ctx->open_rec;
510         struct sk_msg *msg_en = &rec->msg_encrypted;
511         struct scatterlist *sge = sk_msg_elem(msg_en, start);
512         int rc, iv_offset = 0;
513
514         /* For CCM based ciphers, first byte of IV is a constant */
515         switch (prot->cipher_type) {
516         case TLS_CIPHER_AES_CCM_128:
517                 rec->iv_data[0] = TLS_AES_CCM_IV_B0_BYTE;
518                 iv_offset = 1;
519                 break;
520         case TLS_CIPHER_SM4_CCM:
521                 rec->iv_data[0] = TLS_SM4_CCM_IV_B0_BYTE;
522                 iv_offset = 1;
523                 break;
524         }
525
526         memcpy(&rec->iv_data[iv_offset], tls_ctx->tx.iv,
527                prot->iv_size + prot->salt_size);
528
529         tls_xor_iv_with_seq(prot, rec->iv_data + iv_offset,
530                             tls_ctx->tx.rec_seq);
531
532         sge->offset += prot->prepend_size;
533         sge->length -= prot->prepend_size;
534
535         msg_en->sg.curr = start;
536
537         aead_request_set_tfm(aead_req, ctx->aead_send);
538         aead_request_set_ad(aead_req, prot->aad_size);
539         aead_request_set_crypt(aead_req, rec->sg_aead_in,
540                                rec->sg_aead_out,
541                                data_len, rec->iv_data);
542
543         aead_request_set_callback(aead_req, CRYPTO_TFM_REQ_MAY_BACKLOG,
544                                   tls_encrypt_done, sk);
545
546         /* Add the record in tx_list */
547         list_add_tail((struct list_head *)&rec->list, &ctx->tx_list);
548         atomic_inc(&ctx->encrypt_pending);
549
550         rc = crypto_aead_encrypt(aead_req);
551         if (!rc || rc != -EINPROGRESS) {
552                 atomic_dec(&ctx->encrypt_pending);
553                 sge->offset -= prot->prepend_size;
554                 sge->length += prot->prepend_size;
555         }
556
557         if (!rc) {
558                 WRITE_ONCE(rec->tx_ready, true);
559         } else if (rc != -EINPROGRESS) {
560                 list_del(&rec->list);
561                 return rc;
562         }
563
564         /* Unhook the record from context if encryption is not failure */
565         ctx->open_rec = NULL;
566         tls_advance_record_sn(sk, prot, &tls_ctx->tx);
567         return rc;
568 }
569
570 static int tls_split_open_record(struct sock *sk, struct tls_rec *from,
571                                  struct tls_rec **to, struct sk_msg *msg_opl,
572                                  struct sk_msg *msg_oen, u32 split_point,
573                                  u32 tx_overhead_size, u32 *orig_end)
574 {
575         u32 i, j, bytes = 0, apply = msg_opl->apply_bytes;
576         struct scatterlist *sge, *osge, *nsge;
577         u32 orig_size = msg_opl->sg.size;
578         struct scatterlist tmp = { };
579         struct sk_msg *msg_npl;
580         struct tls_rec *new;
581         int ret;
582
583         new = tls_get_rec(sk);
584         if (!new)
585                 return -ENOMEM;
586         ret = sk_msg_alloc(sk, &new->msg_encrypted, msg_opl->sg.size +
587                            tx_overhead_size, 0);
588         if (ret < 0) {
589                 tls_free_rec(sk, new);
590                 return ret;
591         }
592
593         *orig_end = msg_opl->sg.end;
594         i = msg_opl->sg.start;
595         sge = sk_msg_elem(msg_opl, i);
596         while (apply && sge->length) {
597                 if (sge->length > apply) {
598                         u32 len = sge->length - apply;
599
600                         get_page(sg_page(sge));
601                         sg_set_page(&tmp, sg_page(sge), len,
602                                     sge->offset + apply);
603                         sge->length = apply;
604                         bytes += apply;
605                         apply = 0;
606                 } else {
607                         apply -= sge->length;
608                         bytes += sge->length;
609                 }
610
611                 sk_msg_iter_var_next(i);
612                 if (i == msg_opl->sg.end)
613                         break;
614                 sge = sk_msg_elem(msg_opl, i);
615         }
616
617         msg_opl->sg.end = i;
618         msg_opl->sg.curr = i;
619         msg_opl->sg.copybreak = 0;
620         msg_opl->apply_bytes = 0;
621         msg_opl->sg.size = bytes;
622
623         msg_npl = &new->msg_plaintext;
624         msg_npl->apply_bytes = apply;
625         msg_npl->sg.size = orig_size - bytes;
626
627         j = msg_npl->sg.start;
628         nsge = sk_msg_elem(msg_npl, j);
629         if (tmp.length) {
630                 memcpy(nsge, &tmp, sizeof(*nsge));
631                 sk_msg_iter_var_next(j);
632                 nsge = sk_msg_elem(msg_npl, j);
633         }
634
635         osge = sk_msg_elem(msg_opl, i);
636         while (osge->length) {
637                 memcpy(nsge, osge, sizeof(*nsge));
638                 sg_unmark_end(nsge);
639                 sk_msg_iter_var_next(i);
640                 sk_msg_iter_var_next(j);
641                 if (i == *orig_end)
642                         break;
643                 osge = sk_msg_elem(msg_opl, i);
644                 nsge = sk_msg_elem(msg_npl, j);
645         }
646
647         msg_npl->sg.end = j;
648         msg_npl->sg.curr = j;
649         msg_npl->sg.copybreak = 0;
650
651         *to = new;
652         return 0;
653 }
654
655 static void tls_merge_open_record(struct sock *sk, struct tls_rec *to,
656                                   struct tls_rec *from, u32 orig_end)
657 {
658         struct sk_msg *msg_npl = &from->msg_plaintext;
659         struct sk_msg *msg_opl = &to->msg_plaintext;
660         struct scatterlist *osge, *nsge;
661         u32 i, j;
662
663         i = msg_opl->sg.end;
664         sk_msg_iter_var_prev(i);
665         j = msg_npl->sg.start;
666
667         osge = sk_msg_elem(msg_opl, i);
668         nsge = sk_msg_elem(msg_npl, j);
669
670         if (sg_page(osge) == sg_page(nsge) &&
671             osge->offset + osge->length == nsge->offset) {
672                 osge->length += nsge->length;
673                 put_page(sg_page(nsge));
674         }
675
676         msg_opl->sg.end = orig_end;
677         msg_opl->sg.curr = orig_end;
678         msg_opl->sg.copybreak = 0;
679         msg_opl->apply_bytes = msg_opl->sg.size + msg_npl->sg.size;
680         msg_opl->sg.size += msg_npl->sg.size;
681
682         sk_msg_free(sk, &to->msg_encrypted);
683         sk_msg_xfer_full(&to->msg_encrypted, &from->msg_encrypted);
684
685         kfree(from);
686 }
687
688 static int tls_push_record(struct sock *sk, int flags,
689                            unsigned char record_type)
690 {
691         struct tls_context *tls_ctx = tls_get_ctx(sk);
692         struct tls_prot_info *prot = &tls_ctx->prot_info;
693         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
694         struct tls_rec *rec = ctx->open_rec, *tmp = NULL;
695         u32 i, split_point, orig_end;
696         struct sk_msg *msg_pl, *msg_en;
697         struct aead_request *req;
698         bool split;
699         int rc;
700
701         if (!rec)
702                 return 0;
703
704         msg_pl = &rec->msg_plaintext;
705         msg_en = &rec->msg_encrypted;
706
707         split_point = msg_pl->apply_bytes;
708         split = split_point && split_point < msg_pl->sg.size;
709         if (unlikely((!split &&
710                       msg_pl->sg.size +
711                       prot->overhead_size > msg_en->sg.size) ||
712                      (split &&
713                       split_point +
714                       prot->overhead_size > msg_en->sg.size))) {
715                 split = true;
716                 split_point = msg_en->sg.size;
717         }
718         if (split) {
719                 rc = tls_split_open_record(sk, rec, &tmp, msg_pl, msg_en,
720                                            split_point, prot->overhead_size,
721                                            &orig_end);
722                 if (rc < 0)
723                         return rc;
724                 /* This can happen if above tls_split_open_record allocates
725                  * a single large encryption buffer instead of two smaller
726                  * ones. In this case adjust pointers and continue without
727                  * split.
728                  */
729                 if (!msg_pl->sg.size) {
730                         tls_merge_open_record(sk, rec, tmp, orig_end);
731                         msg_pl = &rec->msg_plaintext;
732                         msg_en = &rec->msg_encrypted;
733                         split = false;
734                 }
735                 sk_msg_trim(sk, msg_en, msg_pl->sg.size +
736                             prot->overhead_size);
737         }
738
739         rec->tx_flags = flags;
740         req = &rec->aead_req;
741
742         i = msg_pl->sg.end;
743         sk_msg_iter_var_prev(i);
744
745         rec->content_type = record_type;
746         if (prot->version == TLS_1_3_VERSION) {
747                 /* Add content type to end of message.  No padding added */
748                 sg_set_buf(&rec->sg_content_type, &rec->content_type, 1);
749                 sg_mark_end(&rec->sg_content_type);
750                 sg_chain(msg_pl->sg.data, msg_pl->sg.end + 1,
751                          &rec->sg_content_type);
752         } else {
753                 sg_mark_end(sk_msg_elem(msg_pl, i));
754         }
755
756         if (msg_pl->sg.end < msg_pl->sg.start) {
757                 sg_chain(&msg_pl->sg.data[msg_pl->sg.start],
758                          MAX_SKB_FRAGS - msg_pl->sg.start + 1,
759                          msg_pl->sg.data);
760         }
761
762         i = msg_pl->sg.start;
763         sg_chain(rec->sg_aead_in, 2, &msg_pl->sg.data[i]);
764
765         i = msg_en->sg.end;
766         sk_msg_iter_var_prev(i);
767         sg_mark_end(sk_msg_elem(msg_en, i));
768
769         i = msg_en->sg.start;
770         sg_chain(rec->sg_aead_out, 2, &msg_en->sg.data[i]);
771
772         tls_make_aad(rec->aad_space, msg_pl->sg.size + prot->tail_size,
773                      tls_ctx->tx.rec_seq, record_type, prot);
774
775         tls_fill_prepend(tls_ctx,
776                          page_address(sg_page(&msg_en->sg.data[i])) +
777                          msg_en->sg.data[i].offset,
778                          msg_pl->sg.size + prot->tail_size,
779                          record_type);
780
781         tls_ctx->pending_open_record_frags = false;
782
783         rc = tls_do_encryption(sk, tls_ctx, ctx, req,
784                                msg_pl->sg.size + prot->tail_size, i);
785         if (rc < 0) {
786                 if (rc != -EINPROGRESS) {
787                         tls_err_abort(sk, -EBADMSG);
788                         if (split) {
789                                 tls_ctx->pending_open_record_frags = true;
790                                 tls_merge_open_record(sk, rec, tmp, orig_end);
791                         }
792                 }
793                 ctx->async_capable = 1;
794                 return rc;
795         } else if (split) {
796                 msg_pl = &tmp->msg_plaintext;
797                 msg_en = &tmp->msg_encrypted;
798                 sk_msg_trim(sk, msg_en, msg_pl->sg.size + prot->overhead_size);
799                 tls_ctx->pending_open_record_frags = true;
800                 ctx->open_rec = tmp;
801         }
802
803         return tls_tx_records(sk, flags);
804 }
805
806 static int bpf_exec_tx_verdict(struct sk_msg *msg, struct sock *sk,
807                                bool full_record, u8 record_type,
808                                ssize_t *copied, int flags)
809 {
810         struct tls_context *tls_ctx = tls_get_ctx(sk);
811         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
812         struct sk_msg msg_redir = { };
813         struct sk_psock *psock;
814         struct sock *sk_redir;
815         struct tls_rec *rec;
816         bool enospc, policy;
817         int err = 0, send;
818         u32 delta = 0;
819
820         policy = !(flags & MSG_SENDPAGE_NOPOLICY);
821         psock = sk_psock_get(sk);
822         if (!psock || !policy) {
823                 err = tls_push_record(sk, flags, record_type);
824                 if (err && sk->sk_err == EBADMSG) {
825                         *copied -= sk_msg_free(sk, msg);
826                         tls_free_open_rec(sk);
827                         err = -sk->sk_err;
828                 }
829                 if (psock)
830                         sk_psock_put(sk, psock);
831                 return err;
832         }
833 more_data:
834         enospc = sk_msg_full(msg);
835         if (psock->eval == __SK_NONE) {
836                 delta = msg->sg.size;
837                 psock->eval = sk_psock_msg_verdict(sk, psock, msg);
838                 delta -= msg->sg.size;
839         }
840         if (msg->cork_bytes && msg->cork_bytes > msg->sg.size &&
841             !enospc && !full_record) {
842                 err = -ENOSPC;
843                 goto out_err;
844         }
845         msg->cork_bytes = 0;
846         send = msg->sg.size;
847         if (msg->apply_bytes && msg->apply_bytes < send)
848                 send = msg->apply_bytes;
849
850         switch (psock->eval) {
851         case __SK_PASS:
852                 err = tls_push_record(sk, flags, record_type);
853                 if (err && sk->sk_err == EBADMSG) {
854                         *copied -= sk_msg_free(sk, msg);
855                         tls_free_open_rec(sk);
856                         err = -sk->sk_err;
857                         goto out_err;
858                 }
859                 break;
860         case __SK_REDIRECT:
861                 sk_redir = psock->sk_redir;
862                 memcpy(&msg_redir, msg, sizeof(*msg));
863                 if (msg->apply_bytes < send)
864                         msg->apply_bytes = 0;
865                 else
866                         msg->apply_bytes -= send;
867                 sk_msg_return_zero(sk, msg, send);
868                 msg->sg.size -= send;
869                 release_sock(sk);
870                 err = tcp_bpf_sendmsg_redir(sk_redir, &msg_redir, send, flags);
871                 lock_sock(sk);
872                 if (err < 0) {
873                         *copied -= sk_msg_free_nocharge(sk, &msg_redir);
874                         msg->sg.size = 0;
875                 }
876                 if (msg->sg.size == 0)
877                         tls_free_open_rec(sk);
878                 break;
879         case __SK_DROP:
880         default:
881                 sk_msg_free_partial(sk, msg, send);
882                 if (msg->apply_bytes < send)
883                         msg->apply_bytes = 0;
884                 else
885                         msg->apply_bytes -= send;
886                 if (msg->sg.size == 0)
887                         tls_free_open_rec(sk);
888                 *copied -= (send + delta);
889                 err = -EACCES;
890         }
891
892         if (likely(!err)) {
893                 bool reset_eval = !ctx->open_rec;
894
895                 rec = ctx->open_rec;
896                 if (rec) {
897                         msg = &rec->msg_plaintext;
898                         if (!msg->apply_bytes)
899                                 reset_eval = true;
900                 }
901                 if (reset_eval) {
902                         psock->eval = __SK_NONE;
903                         if (psock->sk_redir) {
904                                 sock_put(psock->sk_redir);
905                                 psock->sk_redir = NULL;
906                         }
907                 }
908                 if (rec)
909                         goto more_data;
910         }
911  out_err:
912         sk_psock_put(sk, psock);
913         return err;
914 }
915
916 static int tls_sw_push_pending_record(struct sock *sk, int flags)
917 {
918         struct tls_context *tls_ctx = tls_get_ctx(sk);
919         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
920         struct tls_rec *rec = ctx->open_rec;
921         struct sk_msg *msg_pl;
922         size_t copied;
923
924         if (!rec)
925                 return 0;
926
927         msg_pl = &rec->msg_plaintext;
928         copied = msg_pl->sg.size;
929         if (!copied)
930                 return 0;
931
932         return bpf_exec_tx_verdict(msg_pl, sk, true, TLS_RECORD_TYPE_DATA,
933                                    &copied, flags);
934 }
935
936 int tls_sw_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
937 {
938         long timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
939         struct tls_context *tls_ctx = tls_get_ctx(sk);
940         struct tls_prot_info *prot = &tls_ctx->prot_info;
941         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
942         bool async_capable = ctx->async_capable;
943         unsigned char record_type = TLS_RECORD_TYPE_DATA;
944         bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
945         bool eor = !(msg->msg_flags & MSG_MORE);
946         size_t try_to_copy;
947         ssize_t copied = 0;
948         struct sk_msg *msg_pl, *msg_en;
949         struct tls_rec *rec;
950         int required_size;
951         int num_async = 0;
952         bool full_record;
953         int record_room;
954         int num_zc = 0;
955         int orig_size;
956         int ret = 0;
957         int pending;
958
959         if (msg->msg_flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
960                                MSG_CMSG_COMPAT))
961                 return -EOPNOTSUPP;
962
963         mutex_lock(&tls_ctx->tx_lock);
964         lock_sock(sk);
965
966         if (unlikely(msg->msg_controllen)) {
967                 ret = tls_process_cmsg(sk, msg, &record_type);
968                 if (ret) {
969                         if (ret == -EINPROGRESS)
970                                 num_async++;
971                         else if (ret != -EAGAIN)
972                                 goto send_end;
973                 }
974         }
975
976         while (msg_data_left(msg)) {
977                 if (sk->sk_err) {
978                         ret = -sk->sk_err;
979                         goto send_end;
980                 }
981
982                 if (ctx->open_rec)
983                         rec = ctx->open_rec;
984                 else
985                         rec = ctx->open_rec = tls_get_rec(sk);
986                 if (!rec) {
987                         ret = -ENOMEM;
988                         goto send_end;
989                 }
990
991                 msg_pl = &rec->msg_plaintext;
992                 msg_en = &rec->msg_encrypted;
993
994                 orig_size = msg_pl->sg.size;
995                 full_record = false;
996                 try_to_copy = msg_data_left(msg);
997                 record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
998                 if (try_to_copy >= record_room) {
999                         try_to_copy = record_room;
1000                         full_record = true;
1001                 }
1002
1003                 required_size = msg_pl->sg.size + try_to_copy +
1004                                 prot->overhead_size;
1005
1006                 if (!sk_stream_memory_free(sk))
1007                         goto wait_for_sndbuf;
1008
1009 alloc_encrypted:
1010                 ret = tls_alloc_encrypted_msg(sk, required_size);
1011                 if (ret) {
1012                         if (ret != -ENOSPC)
1013                                 goto wait_for_memory;
1014
1015                         /* Adjust try_to_copy according to the amount that was
1016                          * actually allocated. The difference is due
1017                          * to max sg elements limit
1018                          */
1019                         try_to_copy -= required_size - msg_en->sg.size;
1020                         full_record = true;
1021                 }
1022
1023                 if (!is_kvec && (full_record || eor) && !async_capable) {
1024                         u32 first = msg_pl->sg.end;
1025
1026                         ret = sk_msg_zerocopy_from_iter(sk, &msg->msg_iter,
1027                                                         msg_pl, try_to_copy);
1028                         if (ret)
1029                                 goto fallback_to_reg_send;
1030
1031                         num_zc++;
1032                         copied += try_to_copy;
1033
1034                         sk_msg_sg_copy_set(msg_pl, first);
1035                         ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1036                                                   record_type, &copied,
1037                                                   msg->msg_flags);
1038                         if (ret) {
1039                                 if (ret == -EINPROGRESS)
1040                                         num_async++;
1041                                 else if (ret == -ENOMEM)
1042                                         goto wait_for_memory;
1043                                 else if (ctx->open_rec && ret == -ENOSPC)
1044                                         goto rollback_iter;
1045                                 else if (ret != -EAGAIN)
1046                                         goto send_end;
1047                         }
1048                         continue;
1049 rollback_iter:
1050                         copied -= try_to_copy;
1051                         sk_msg_sg_copy_clear(msg_pl, first);
1052                         iov_iter_revert(&msg->msg_iter,
1053                                         msg_pl->sg.size - orig_size);
1054 fallback_to_reg_send:
1055                         sk_msg_trim(sk, msg_pl, orig_size);
1056                 }
1057
1058                 required_size = msg_pl->sg.size + try_to_copy;
1059
1060                 ret = tls_clone_plaintext_msg(sk, required_size);
1061                 if (ret) {
1062                         if (ret != -ENOSPC)
1063                                 goto send_end;
1064
1065                         /* Adjust try_to_copy according to the amount that was
1066                          * actually allocated. The difference is due
1067                          * to max sg elements limit
1068                          */
1069                         try_to_copy -= required_size - msg_pl->sg.size;
1070                         full_record = true;
1071                         sk_msg_trim(sk, msg_en,
1072                                     msg_pl->sg.size + prot->overhead_size);
1073                 }
1074
1075                 if (try_to_copy) {
1076                         ret = sk_msg_memcopy_from_iter(sk, &msg->msg_iter,
1077                                                        msg_pl, try_to_copy);
1078                         if (ret < 0)
1079                                 goto trim_sgl;
1080                 }
1081
1082                 /* Open records defined only if successfully copied, otherwise
1083                  * we would trim the sg but not reset the open record frags.
1084                  */
1085                 tls_ctx->pending_open_record_frags = true;
1086                 copied += try_to_copy;
1087                 if (full_record || eor) {
1088                         ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1089                                                   record_type, &copied,
1090                                                   msg->msg_flags);
1091                         if (ret) {
1092                                 if (ret == -EINPROGRESS)
1093                                         num_async++;
1094                                 else if (ret == -ENOMEM)
1095                                         goto wait_for_memory;
1096                                 else if (ret != -EAGAIN) {
1097                                         if (ret == -ENOSPC)
1098                                                 ret = 0;
1099                                         goto send_end;
1100                                 }
1101                         }
1102                 }
1103
1104                 continue;
1105
1106 wait_for_sndbuf:
1107                 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1108 wait_for_memory:
1109                 ret = sk_stream_wait_memory(sk, &timeo);
1110                 if (ret) {
1111 trim_sgl:
1112                         if (ctx->open_rec)
1113                                 tls_trim_both_msgs(sk, orig_size);
1114                         goto send_end;
1115                 }
1116
1117                 if (ctx->open_rec && msg_en->sg.size < required_size)
1118                         goto alloc_encrypted;
1119         }
1120
1121         if (!num_async) {
1122                 goto send_end;
1123         } else if (num_zc) {
1124                 /* Wait for pending encryptions to get completed */
1125                 spin_lock_bh(&ctx->encrypt_compl_lock);
1126                 ctx->async_notify = true;
1127
1128                 pending = atomic_read(&ctx->encrypt_pending);
1129                 spin_unlock_bh(&ctx->encrypt_compl_lock);
1130                 if (pending)
1131                         crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
1132                 else
1133                         reinit_completion(&ctx->async_wait.completion);
1134
1135                 /* There can be no concurrent accesses, since we have no
1136                  * pending encrypt operations
1137                  */
1138                 WRITE_ONCE(ctx->async_notify, false);
1139
1140                 if (ctx->async_wait.err) {
1141                         ret = ctx->async_wait.err;
1142                         copied = 0;
1143                 }
1144         }
1145
1146         /* Transmit if any encryptions have completed */
1147         if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1148                 cancel_delayed_work(&ctx->tx_work.work);
1149                 tls_tx_records(sk, msg->msg_flags);
1150         }
1151
1152 send_end:
1153         ret = sk_stream_error(sk, msg->msg_flags, ret);
1154
1155         release_sock(sk);
1156         mutex_unlock(&tls_ctx->tx_lock);
1157         return copied > 0 ? copied : ret;
1158 }
1159
1160 static int tls_sw_do_sendpage(struct sock *sk, struct page *page,
1161                               int offset, size_t size, int flags)
1162 {
1163         long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
1164         struct tls_context *tls_ctx = tls_get_ctx(sk);
1165         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1166         struct tls_prot_info *prot = &tls_ctx->prot_info;
1167         unsigned char record_type = TLS_RECORD_TYPE_DATA;
1168         struct sk_msg *msg_pl;
1169         struct tls_rec *rec;
1170         int num_async = 0;
1171         ssize_t copied = 0;
1172         bool full_record;
1173         int record_room;
1174         int ret = 0;
1175         bool eor;
1176
1177         eor = !(flags & MSG_SENDPAGE_NOTLAST);
1178         sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
1179
1180         /* Call the sk_stream functions to manage the sndbuf mem. */
1181         while (size > 0) {
1182                 size_t copy, required_size;
1183
1184                 if (sk->sk_err) {
1185                         ret = -sk->sk_err;
1186                         goto sendpage_end;
1187                 }
1188
1189                 if (ctx->open_rec)
1190                         rec = ctx->open_rec;
1191                 else
1192                         rec = ctx->open_rec = tls_get_rec(sk);
1193                 if (!rec) {
1194                         ret = -ENOMEM;
1195                         goto sendpage_end;
1196                 }
1197
1198                 msg_pl = &rec->msg_plaintext;
1199
1200                 full_record = false;
1201                 record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
1202                 copy = size;
1203                 if (copy >= record_room) {
1204                         copy = record_room;
1205                         full_record = true;
1206                 }
1207
1208                 required_size = msg_pl->sg.size + copy + prot->overhead_size;
1209
1210                 if (!sk_stream_memory_free(sk))
1211                         goto wait_for_sndbuf;
1212 alloc_payload:
1213                 ret = tls_alloc_encrypted_msg(sk, required_size);
1214                 if (ret) {
1215                         if (ret != -ENOSPC)
1216                                 goto wait_for_memory;
1217
1218                         /* Adjust copy according to the amount that was
1219                          * actually allocated. The difference is due
1220                          * to max sg elements limit
1221                          */
1222                         copy -= required_size - msg_pl->sg.size;
1223                         full_record = true;
1224                 }
1225
1226                 sk_msg_page_add(msg_pl, page, copy, offset);
1227                 sk_mem_charge(sk, copy);
1228
1229                 offset += copy;
1230                 size -= copy;
1231                 copied += copy;
1232
1233                 tls_ctx->pending_open_record_frags = true;
1234                 if (full_record || eor || sk_msg_full(msg_pl)) {
1235                         ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1236                                                   record_type, &copied, flags);
1237                         if (ret) {
1238                                 if (ret == -EINPROGRESS)
1239                                         num_async++;
1240                                 else if (ret == -ENOMEM)
1241                                         goto wait_for_memory;
1242                                 else if (ret != -EAGAIN) {
1243                                         if (ret == -ENOSPC)
1244                                                 ret = 0;
1245                                         goto sendpage_end;
1246                                 }
1247                         }
1248                 }
1249                 continue;
1250 wait_for_sndbuf:
1251                 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1252 wait_for_memory:
1253                 ret = sk_stream_wait_memory(sk, &timeo);
1254                 if (ret) {
1255                         if (ctx->open_rec)
1256                                 tls_trim_both_msgs(sk, msg_pl->sg.size);
1257                         goto sendpage_end;
1258                 }
1259
1260                 if (ctx->open_rec)
1261                         goto alloc_payload;
1262         }
1263
1264         if (num_async) {
1265                 /* Transmit if any encryptions have completed */
1266                 if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1267                         cancel_delayed_work(&ctx->tx_work.work);
1268                         tls_tx_records(sk, flags);
1269                 }
1270         }
1271 sendpage_end:
1272         ret = sk_stream_error(sk, flags, ret);
1273         return copied > 0 ? copied : ret;
1274 }
1275
1276 int tls_sw_sendpage_locked(struct sock *sk, struct page *page,
1277                            int offset, size_t size, int flags)
1278 {
1279         if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
1280                       MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY |
1281                       MSG_NO_SHARED_FRAGS))
1282                 return -EOPNOTSUPP;
1283
1284         return tls_sw_do_sendpage(sk, page, offset, size, flags);
1285 }
1286
1287 int tls_sw_sendpage(struct sock *sk, struct page *page,
1288                     int offset, size_t size, int flags)
1289 {
1290         struct tls_context *tls_ctx = tls_get_ctx(sk);
1291         int ret;
1292
1293         if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
1294                       MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY))
1295                 return -EOPNOTSUPP;
1296
1297         mutex_lock(&tls_ctx->tx_lock);
1298         lock_sock(sk);
1299         ret = tls_sw_do_sendpage(sk, page, offset, size, flags);
1300         release_sock(sk);
1301         mutex_unlock(&tls_ctx->tx_lock);
1302         return ret;
1303 }
1304
1305 static int
1306 tls_rx_rec_wait(struct sock *sk, struct sk_psock *psock, bool nonblock,
1307                 long timeo)
1308 {
1309         struct tls_context *tls_ctx = tls_get_ctx(sk);
1310         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1311         DEFINE_WAIT_FUNC(wait, woken_wake_function);
1312
1313         while (!ctx->recv_pkt) {
1314                 if (!sk_psock_queue_empty(psock))
1315                         return 0;
1316
1317                 if (sk->sk_err)
1318                         return sock_error(sk);
1319
1320                 if (!skb_queue_empty(&sk->sk_receive_queue)) {
1321                         __strp_unpause(&ctx->strp);
1322                         if (ctx->recv_pkt)
1323                                 break;
1324                 }
1325
1326                 if (sk->sk_shutdown & RCV_SHUTDOWN)
1327                         return 0;
1328
1329                 if (sock_flag(sk, SOCK_DONE))
1330                         return 0;
1331
1332                 if (nonblock || !timeo)
1333                         return -EAGAIN;
1334
1335                 add_wait_queue(sk_sleep(sk), &wait);
1336                 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1337                 sk_wait_event(sk, &timeo,
1338                               ctx->recv_pkt || !sk_psock_queue_empty(psock),
1339                               &wait);
1340                 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1341                 remove_wait_queue(sk_sleep(sk), &wait);
1342
1343                 /* Handle signals */
1344                 if (signal_pending(current))
1345                         return sock_intr_errno(timeo);
1346         }
1347
1348         return 1;
1349 }
1350
1351 static int tls_setup_from_iter(struct iov_iter *from,
1352                                int length, int *pages_used,
1353                                struct scatterlist *to,
1354                                int to_max_pages)
1355 {
1356         int rc = 0, i = 0, num_elem = *pages_used, maxpages;
1357         struct page *pages[MAX_SKB_FRAGS];
1358         unsigned int size = 0;
1359         ssize_t copied, use;
1360         size_t offset;
1361
1362         while (length > 0) {
1363                 i = 0;
1364                 maxpages = to_max_pages - num_elem;
1365                 if (maxpages == 0) {
1366                         rc = -EFAULT;
1367                         goto out;
1368                 }
1369                 copied = iov_iter_get_pages(from, pages,
1370                                             length,
1371                                             maxpages, &offset);
1372                 if (copied <= 0) {
1373                         rc = -EFAULT;
1374                         goto out;
1375                 }
1376
1377                 iov_iter_advance(from, copied);
1378
1379                 length -= copied;
1380                 size += copied;
1381                 while (copied) {
1382                         use = min_t(int, copied, PAGE_SIZE - offset);
1383
1384                         sg_set_page(&to[num_elem],
1385                                     pages[i], use, offset);
1386                         sg_unmark_end(&to[num_elem]);
1387                         /* We do not uncharge memory from this API */
1388
1389                         offset = 0;
1390                         copied -= use;
1391
1392                         i++;
1393                         num_elem++;
1394                 }
1395         }
1396         /* Mark the end in the last sg entry if newly added */
1397         if (num_elem > *pages_used)
1398                 sg_mark_end(&to[num_elem - 1]);
1399 out:
1400         if (rc)
1401                 iov_iter_revert(from, size);
1402         *pages_used = num_elem;
1403
1404         return rc;
1405 }
1406
1407 /* Decrypt handlers
1408  *
1409  * tls_decrypt_sg() and tls_decrypt_device() are decrypt handlers.
1410  * They must transform the darg in/out argument are as follows:
1411  *       |          Input            |         Output
1412  * -------------------------------------------------------------------
1413  *    zc | Zero-copy decrypt allowed | Zero-copy performed
1414  * async | Async decrypt allowed     | Async crypto used / in progress
1415  */
1416
1417 /* This function decrypts the input skb into either out_iov or in out_sg
1418  * or in skb buffers itself. The input parameter 'darg->zc' indicates if
1419  * zero-copy mode needs to be tried or not. With zero-copy mode, either
1420  * out_iov or out_sg must be non-NULL. In case both out_iov and out_sg are
1421  * NULL, then the decryption happens inside skb buffers itself, i.e.
1422  * zero-copy gets disabled and 'darg->zc' is updated.
1423  */
1424 static int tls_decrypt_sg(struct sock *sk, struct iov_iter *out_iov,
1425                           struct scatterlist *out_sg,
1426                           struct tls_decrypt_arg *darg)
1427 {
1428         struct tls_context *tls_ctx = tls_get_ctx(sk);
1429         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1430         struct tls_prot_info *prot = &tls_ctx->prot_info;
1431         int n_sgin, n_sgout, aead_size, err, pages = 0;
1432         struct sk_buff *skb = tls_strp_msg(ctx);
1433         struct strp_msg *rxm = strp_msg(skb);
1434         struct tls_msg *tlm = tls_msg(skb);
1435         struct aead_request *aead_req;
1436         struct sk_buff *unused;
1437         struct scatterlist *sgin = NULL;
1438         struct scatterlist *sgout = NULL;
1439         const int data_len = rxm->full_len - prot->overhead_size;
1440         int tail_pages = !!prot->tail_size;
1441         struct tls_decrypt_ctx *dctx;
1442         int iv_offset = 0;
1443         u8 *mem;
1444
1445         if (darg->zc && (out_iov || out_sg)) {
1446                 if (out_iov)
1447                         n_sgout = 1 + tail_pages +
1448                                 iov_iter_npages_cap(out_iov, INT_MAX, data_len);
1449                 else
1450                         n_sgout = sg_nents(out_sg);
1451                 n_sgin = skb_nsg(skb, rxm->offset + prot->prepend_size,
1452                                  rxm->full_len - prot->prepend_size);
1453         } else {
1454                 n_sgout = 0;
1455                 darg->zc = false;
1456                 n_sgin = skb_cow_data(skb, 0, &unused);
1457         }
1458
1459         if (n_sgin < 1)
1460                 return -EBADMSG;
1461
1462         /* Increment to accommodate AAD */
1463         n_sgin = n_sgin + 1;
1464
1465         /* Allocate a single block of memory which contains
1466          *   aead_req || tls_decrypt_ctx.
1467          * Both structs are variable length.
1468          */
1469         aead_size = sizeof(*aead_req) + crypto_aead_reqsize(ctx->aead_recv);
1470         mem = kmalloc(aead_size + struct_size(dctx, sg, n_sgin + n_sgout),
1471                       sk->sk_allocation);
1472         if (!mem)
1473                 return -ENOMEM;
1474
1475         /* Segment the allocated memory */
1476         aead_req = (struct aead_request *)mem;
1477         dctx = (struct tls_decrypt_ctx *)(mem + aead_size);
1478         sgin = &dctx->sg[0];
1479         sgout = &dctx->sg[n_sgin];
1480
1481         /* For CCM based ciphers, first byte of nonce+iv is a constant */
1482         switch (prot->cipher_type) {
1483         case TLS_CIPHER_AES_CCM_128:
1484                 dctx->iv[0] = TLS_AES_CCM_IV_B0_BYTE;
1485                 iv_offset = 1;
1486                 break;
1487         case TLS_CIPHER_SM4_CCM:
1488                 dctx->iv[0] = TLS_SM4_CCM_IV_B0_BYTE;
1489                 iv_offset = 1;
1490                 break;
1491         }
1492
1493         /* Prepare IV */
1494         if (prot->version == TLS_1_3_VERSION ||
1495             prot->cipher_type == TLS_CIPHER_CHACHA20_POLY1305) {
1496                 memcpy(&dctx->iv[iv_offset], tls_ctx->rx.iv,
1497                        prot->iv_size + prot->salt_size);
1498         } else {
1499                 err = skb_copy_bits(skb, rxm->offset + TLS_HEADER_SIZE,
1500                                     &dctx->iv[iv_offset] + prot->salt_size,
1501                                     prot->iv_size);
1502                 if (err < 0)
1503                         goto exit_free;
1504                 memcpy(&dctx->iv[iv_offset], tls_ctx->rx.iv, prot->salt_size);
1505         }
1506         tls_xor_iv_with_seq(prot, &dctx->iv[iv_offset], tls_ctx->rx.rec_seq);
1507
1508         /* Prepare AAD */
1509         tls_make_aad(dctx->aad, rxm->full_len - prot->overhead_size +
1510                      prot->tail_size,
1511                      tls_ctx->rx.rec_seq, tlm->control, prot);
1512
1513         /* Prepare sgin */
1514         sg_init_table(sgin, n_sgin);
1515         sg_set_buf(&sgin[0], dctx->aad, prot->aad_size);
1516         err = skb_to_sgvec(skb, &sgin[1],
1517                            rxm->offset + prot->prepend_size,
1518                            rxm->full_len - prot->prepend_size);
1519         if (err < 0)
1520                 goto exit_free;
1521
1522         if (n_sgout) {
1523                 if (out_iov) {
1524                         sg_init_table(sgout, n_sgout);
1525                         sg_set_buf(&sgout[0], dctx->aad, prot->aad_size);
1526
1527                         err = tls_setup_from_iter(out_iov, data_len,
1528                                                   &pages, &sgout[1],
1529                                                   (n_sgout - 1 - tail_pages));
1530                         if (err < 0)
1531                                 goto fallback_to_reg_recv;
1532
1533                         if (prot->tail_size) {
1534                                 sg_unmark_end(&sgout[pages]);
1535                                 sg_set_buf(&sgout[pages + 1], &dctx->tail,
1536                                            prot->tail_size);
1537                                 sg_mark_end(&sgout[pages + 1]);
1538                         }
1539                 } else if (out_sg) {
1540                         memcpy(sgout, out_sg, n_sgout * sizeof(*sgout));
1541                 } else {
1542                         goto fallback_to_reg_recv;
1543                 }
1544         } else {
1545 fallback_to_reg_recv:
1546                 sgout = sgin;
1547                 pages = 0;
1548                 darg->zc = false;
1549         }
1550
1551         /* Prepare and submit AEAD request */
1552         err = tls_do_decryption(sk, skb, sgin, sgout, dctx->iv,
1553                                 data_len + prot->tail_size, aead_req, darg);
1554         if (darg->async)
1555                 return 0;
1556
1557         if (prot->tail_size)
1558                 darg->tail = dctx->tail;
1559
1560         /* Release the pages in case iov was mapped to pages */
1561         for (; pages > 0; pages--)
1562                 put_page(sg_page(&sgout[pages]));
1563 exit_free:
1564         kfree(mem);
1565         return err;
1566 }
1567
1568 static int
1569 tls_decrypt_device(struct sock *sk, struct tls_context *tls_ctx,
1570                    struct tls_decrypt_arg *darg)
1571 {
1572         int err;
1573
1574         if (tls_ctx->rx_conf != TLS_HW)
1575                 return 0;
1576
1577         err = tls_device_decrypted(sk, tls_ctx);
1578         if (err <= 0)
1579                 return err;
1580
1581         darg->zc = false;
1582         darg->async = false;
1583         return 1;
1584 }
1585
1586 static int tls_rx_one_record(struct sock *sk, struct iov_iter *dest,
1587                              struct tls_decrypt_arg *darg)
1588 {
1589         struct tls_context *tls_ctx = tls_get_ctx(sk);
1590         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1591         struct tls_prot_info *prot = &tls_ctx->prot_info;
1592         struct strp_msg *rxm;
1593         int pad, err;
1594
1595         err = tls_decrypt_device(sk, tls_ctx, darg);
1596         if (err < 0)
1597                 return err;
1598         if (err)
1599                 goto decrypt_done;
1600
1601         err = tls_decrypt_sg(sk, dest, NULL, darg);
1602         if (err < 0) {
1603                 if (err == -EBADMSG)
1604                         TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTERROR);
1605                 return err;
1606         }
1607         if (darg->async)
1608                 goto decrypt_next;
1609         /* If opportunistic TLS 1.3 ZC failed retry without ZC */
1610         if (unlikely(darg->zc && prot->version == TLS_1_3_VERSION &&
1611                      darg->tail != TLS_RECORD_TYPE_DATA)) {
1612                 darg->zc = false;
1613                 if (!darg->tail)
1614                         TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXNOPADVIOL);
1615                 TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTRETRY);
1616                 return tls_rx_one_record(sk, dest, darg);
1617         }
1618
1619 decrypt_done:
1620         pad = tls_padding_length(prot, ctx->recv_pkt, darg);
1621         if (pad < 0)
1622                 return pad;
1623
1624         rxm = strp_msg(ctx->recv_pkt);
1625         rxm->full_len -= pad;
1626         rxm->offset += prot->prepend_size;
1627         rxm->full_len -= prot->overhead_size;
1628 decrypt_next:
1629         tls_advance_record_sn(sk, prot, &tls_ctx->rx);
1630
1631         return 0;
1632 }
1633
1634 int decrypt_skb(struct sock *sk, struct scatterlist *sgout)
1635 {
1636         struct tls_decrypt_arg darg = { .zc = true, };
1637
1638         return tls_decrypt_sg(sk, NULL, sgout, &darg);
1639 }
1640
1641 static int tls_record_content_type(struct msghdr *msg, struct tls_msg *tlm,
1642                                    u8 *control)
1643 {
1644         int err;
1645
1646         if (!*control) {
1647                 *control = tlm->control;
1648                 if (!*control)
1649                         return -EBADMSG;
1650
1651                 err = put_cmsg(msg, SOL_TLS, TLS_GET_RECORD_TYPE,
1652                                sizeof(*control), control);
1653                 if (*control != TLS_RECORD_TYPE_DATA) {
1654                         if (err || msg->msg_flags & MSG_CTRUNC)
1655                                 return -EIO;
1656                 }
1657         } else if (*control != tlm->control) {
1658                 return 0;
1659         }
1660
1661         return 1;
1662 }
1663
1664 static void tls_rx_rec_done(struct tls_sw_context_rx *ctx)
1665 {
1666         ctx->recv_pkt = NULL;
1667         __strp_unpause(&ctx->strp);
1668 }
1669
1670 /* This function traverses the rx_list in tls receive context to copies the
1671  * decrypted records into the buffer provided by caller zero copy is not
1672  * true. Further, the records are removed from the rx_list if it is not a peek
1673  * case and the record has been consumed completely.
1674  */
1675 static int process_rx_list(struct tls_sw_context_rx *ctx,
1676                            struct msghdr *msg,
1677                            u8 *control,
1678                            size_t skip,
1679                            size_t len,
1680                            bool zc,
1681                            bool is_peek)
1682 {
1683         struct sk_buff *skb = skb_peek(&ctx->rx_list);
1684         struct tls_msg *tlm;
1685         ssize_t copied = 0;
1686         int err;
1687
1688         while (skip && skb) {
1689                 struct strp_msg *rxm = strp_msg(skb);
1690                 tlm = tls_msg(skb);
1691
1692                 err = tls_record_content_type(msg, tlm, control);
1693                 if (err <= 0)
1694                         goto out;
1695
1696                 if (skip < rxm->full_len)
1697                         break;
1698
1699                 skip = skip - rxm->full_len;
1700                 skb = skb_peek_next(skb, &ctx->rx_list);
1701         }
1702
1703         while (len && skb) {
1704                 struct sk_buff *next_skb;
1705                 struct strp_msg *rxm = strp_msg(skb);
1706                 int chunk = min_t(unsigned int, rxm->full_len - skip, len);
1707
1708                 tlm = tls_msg(skb);
1709
1710                 err = tls_record_content_type(msg, tlm, control);
1711                 if (err <= 0)
1712                         goto out;
1713
1714                 if (!zc || (rxm->full_len - skip) > len) {
1715                         err = skb_copy_datagram_msg(skb, rxm->offset + skip,
1716                                                     msg, chunk);
1717                         if (err < 0)
1718                                 goto out;
1719                 }
1720
1721                 len = len - chunk;
1722                 copied = copied + chunk;
1723
1724                 /* Consume the data from record if it is non-peek case*/
1725                 if (!is_peek) {
1726                         rxm->offset = rxm->offset + chunk;
1727                         rxm->full_len = rxm->full_len - chunk;
1728
1729                         /* Return if there is unconsumed data in the record */
1730                         if (rxm->full_len - skip)
1731                                 break;
1732                 }
1733
1734                 /* The remaining skip-bytes must lie in 1st record in rx_list.
1735                  * So from the 2nd record, 'skip' should be 0.
1736                  */
1737                 skip = 0;
1738
1739                 if (msg)
1740                         msg->msg_flags |= MSG_EOR;
1741
1742                 next_skb = skb_peek_next(skb, &ctx->rx_list);
1743
1744                 if (!is_peek) {
1745                         __skb_unlink(skb, &ctx->rx_list);
1746                         consume_skb(skb);
1747                 }
1748
1749                 skb = next_skb;
1750         }
1751         err = 0;
1752
1753 out:
1754         return copied ? : err;
1755 }
1756
1757 static void
1758 tls_read_flush_backlog(struct sock *sk, struct tls_prot_info *prot,
1759                        size_t len_left, size_t decrypted, ssize_t done,
1760                        size_t *flushed_at)
1761 {
1762         size_t max_rec;
1763
1764         if (len_left <= decrypted)
1765                 return;
1766
1767         max_rec = prot->overhead_size - prot->tail_size + TLS_MAX_PAYLOAD_SIZE;
1768         if (done - *flushed_at < SZ_128K && tcp_inq(sk) > max_rec)
1769                 return;
1770
1771         *flushed_at = done;
1772         sk_flush_backlog(sk);
1773 }
1774
1775 static long tls_rx_reader_lock(struct sock *sk, struct tls_sw_context_rx *ctx,
1776                                bool nonblock)
1777 {
1778         long timeo;
1779
1780         lock_sock(sk);
1781
1782         timeo = sock_rcvtimeo(sk, nonblock);
1783
1784         while (unlikely(ctx->reader_present)) {
1785                 DEFINE_WAIT_FUNC(wait, woken_wake_function);
1786
1787                 ctx->reader_contended = 1;
1788
1789                 add_wait_queue(&ctx->wq, &wait);
1790                 sk_wait_event(sk, &timeo,
1791                               !READ_ONCE(ctx->reader_present), &wait);
1792                 remove_wait_queue(&ctx->wq, &wait);
1793
1794                 if (!timeo)
1795                         return -EAGAIN;
1796                 if (signal_pending(current))
1797                         return sock_intr_errno(timeo);
1798         }
1799
1800         WRITE_ONCE(ctx->reader_present, 1);
1801
1802         return timeo;
1803 }
1804
1805 static void tls_rx_reader_unlock(struct sock *sk, struct tls_sw_context_rx *ctx)
1806 {
1807         if (unlikely(ctx->reader_contended)) {
1808                 if (wq_has_sleeper(&ctx->wq))
1809                         wake_up(&ctx->wq);
1810                 else
1811                         ctx->reader_contended = 0;
1812
1813                 WARN_ON_ONCE(!ctx->reader_present);
1814         }
1815
1816         WRITE_ONCE(ctx->reader_present, 0);
1817         release_sock(sk);
1818 }
1819
1820 int tls_sw_recvmsg(struct sock *sk,
1821                    struct msghdr *msg,
1822                    size_t len,
1823                    int flags,
1824                    int *addr_len)
1825 {
1826         struct tls_context *tls_ctx = tls_get_ctx(sk);
1827         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1828         struct tls_prot_info *prot = &tls_ctx->prot_info;
1829         struct sk_psock *psock;
1830         unsigned char control = 0;
1831         ssize_t decrypted = 0;
1832         size_t flushed_at = 0;
1833         struct strp_msg *rxm;
1834         struct tls_msg *tlm;
1835         struct sk_buff *skb;
1836         ssize_t copied = 0;
1837         bool async = false;
1838         int target, err = 0;
1839         long timeo;
1840         bool is_kvec = iov_iter_is_kvec(&msg->msg_iter);
1841         bool is_peek = flags & MSG_PEEK;
1842         bool bpf_strp_enabled;
1843         bool zc_capable;
1844
1845         if (unlikely(flags & MSG_ERRQUEUE))
1846                 return sock_recv_errqueue(sk, msg, len, SOL_IP, IP_RECVERR);
1847
1848         psock = sk_psock_get(sk);
1849         timeo = tls_rx_reader_lock(sk, ctx, flags & MSG_DONTWAIT);
1850         if (timeo < 0)
1851                 return timeo;
1852         bpf_strp_enabled = sk_psock_strp_enabled(psock);
1853
1854         /* If crypto failed the connection is broken */
1855         err = ctx->async_wait.err;
1856         if (err)
1857                 goto end;
1858
1859         /* Process pending decrypted records. It must be non-zero-copy */
1860         err = process_rx_list(ctx, msg, &control, 0, len, false, is_peek);
1861         if (err < 0)
1862                 goto end;
1863
1864         copied = err;
1865         if (len <= copied)
1866                 goto end;
1867
1868         target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
1869         len = len - copied;
1870
1871         zc_capable = !bpf_strp_enabled && !is_kvec && !is_peek &&
1872                 ctx->zc_capable;
1873         decrypted = 0;
1874         while (len && (decrypted + copied < target || ctx->recv_pkt)) {
1875                 struct tls_decrypt_arg darg = {};
1876                 int to_decrypt, chunk;
1877
1878                 err = tls_rx_rec_wait(sk, psock, flags & MSG_DONTWAIT, timeo);
1879                 if (err <= 0) {
1880                         if (psock) {
1881                                 chunk = sk_msg_recvmsg(sk, psock, msg, len,
1882                                                        flags);
1883                                 if (chunk > 0) {
1884                                         decrypted += chunk;
1885                                         len -= chunk;
1886                                         continue;
1887                                 }
1888                         }
1889                         goto recv_end;
1890                 }
1891
1892                 skb = ctx->recv_pkt;
1893                 rxm = strp_msg(skb);
1894                 tlm = tls_msg(skb);
1895
1896                 to_decrypt = rxm->full_len - prot->overhead_size;
1897
1898                 if (zc_capable && to_decrypt <= len &&
1899                     tlm->control == TLS_RECORD_TYPE_DATA)
1900                         darg.zc = true;
1901
1902                 /* Do not use async mode if record is non-data */
1903                 if (tlm->control == TLS_RECORD_TYPE_DATA && !bpf_strp_enabled)
1904                         darg.async = ctx->async_capable;
1905                 else
1906                         darg.async = false;
1907
1908                 err = tls_rx_one_record(sk, &msg->msg_iter, &darg);
1909                 if (err < 0) {
1910                         tls_err_abort(sk, -EBADMSG);
1911                         goto recv_end;
1912                 }
1913
1914                 async |= darg.async;
1915
1916                 /* If the type of records being processed is not known yet,
1917                  * set it to record type just dequeued. If it is already known,
1918                  * but does not match the record type just dequeued, go to end.
1919                  * We always get record type here since for tls1.2, record type
1920                  * is known just after record is dequeued from stream parser.
1921                  * For tls1.3, we disable async.
1922                  */
1923                 err = tls_record_content_type(msg, tlm, &control);
1924                 if (err <= 0) {
1925                         tls_rx_rec_done(ctx);
1926 put_on_rx_list_err:
1927                         __skb_queue_tail(&ctx->rx_list, skb);
1928                         goto recv_end;
1929                 }
1930
1931                 /* periodically flush backlog, and feed strparser */
1932                 tls_read_flush_backlog(sk, prot, len, to_decrypt,
1933                                        decrypted + copied, &flushed_at);
1934
1935                 /* TLS 1.3 may have updated the length by more than overhead */
1936                 chunk = rxm->full_len;
1937                 tls_rx_rec_done(ctx);
1938
1939                 if (async) {
1940                         /* TLS 1.2-only, to_decrypt must be text length */
1941                         chunk = min_t(int, to_decrypt, len);
1942 put_on_rx_list:
1943                         decrypted += chunk;
1944                         len -= chunk;
1945                         __skb_queue_tail(&ctx->rx_list, skb);
1946                         continue;
1947                 }
1948
1949                 if (!darg.zc) {
1950                         bool partially_consumed = chunk > len;
1951
1952                         if (bpf_strp_enabled) {
1953                                 err = sk_psock_tls_strp_read(psock, skb);
1954                                 if (err != __SK_PASS) {
1955                                         rxm->offset = rxm->offset + rxm->full_len;
1956                                         rxm->full_len = 0;
1957                                         if (err == __SK_DROP)
1958                                                 consume_skb(skb);
1959                                         continue;
1960                                 }
1961                         }
1962
1963                         if (partially_consumed)
1964                                 chunk = len;
1965
1966                         err = skb_copy_datagram_msg(skb, rxm->offset,
1967                                                     msg, chunk);
1968                         if (err < 0)
1969                                 goto put_on_rx_list_err;
1970
1971                         if (is_peek)
1972                                 goto put_on_rx_list;
1973
1974                         if (partially_consumed) {
1975                                 rxm->offset += chunk;
1976                                 rxm->full_len -= chunk;
1977                                 goto put_on_rx_list;
1978                         }
1979                 }
1980
1981                 decrypted += chunk;
1982                 len -= chunk;
1983
1984                 consume_skb(skb);
1985
1986                 /* Return full control message to userspace before trying
1987                  * to parse another message type
1988                  */
1989                 msg->msg_flags |= MSG_EOR;
1990                 if (control != TLS_RECORD_TYPE_DATA)
1991                         break;
1992         }
1993
1994 recv_end:
1995         if (async) {
1996                 int ret, pending;
1997
1998                 /* Wait for all previously submitted records to be decrypted */
1999                 spin_lock_bh(&ctx->decrypt_compl_lock);
2000                 reinit_completion(&ctx->async_wait.completion);
2001                 pending = atomic_read(&ctx->decrypt_pending);
2002                 spin_unlock_bh(&ctx->decrypt_compl_lock);
2003                 if (pending) {
2004                         ret = crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
2005                         if (ret) {
2006                                 if (err >= 0 || err == -EINPROGRESS)
2007                                         err = ret;
2008                                 decrypted = 0;
2009                                 goto end;
2010                         }
2011                 }
2012
2013                 /* Drain records from the rx_list & copy if required */
2014                 if (is_peek || is_kvec)
2015                         err = process_rx_list(ctx, msg, &control, copied,
2016                                               decrypted, false, is_peek);
2017                 else
2018                         err = process_rx_list(ctx, msg, &control, 0,
2019                                               decrypted, true, is_peek);
2020                 decrypted = max(err, 0);
2021         }
2022
2023         copied += decrypted;
2024
2025 end:
2026         tls_rx_reader_unlock(sk, ctx);
2027         if (psock)
2028                 sk_psock_put(sk, psock);
2029         return copied ? : err;
2030 }
2031
2032 ssize_t tls_sw_splice_read(struct socket *sock,  loff_t *ppos,
2033                            struct pipe_inode_info *pipe,
2034                            size_t len, unsigned int flags)
2035 {
2036         struct tls_context *tls_ctx = tls_get_ctx(sock->sk);
2037         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2038         struct strp_msg *rxm = NULL;
2039         struct sock *sk = sock->sk;
2040         struct tls_msg *tlm;
2041         struct sk_buff *skb;
2042         ssize_t copied = 0;
2043         int err = 0;
2044         long timeo;
2045         int chunk;
2046
2047         timeo = tls_rx_reader_lock(sk, ctx, flags & SPLICE_F_NONBLOCK);
2048         if (timeo < 0)
2049                 return timeo;
2050
2051         if (!skb_queue_empty(&ctx->rx_list)) {
2052                 skb = __skb_dequeue(&ctx->rx_list);
2053         } else {
2054                 struct tls_decrypt_arg darg = {};
2055
2056                 err = tls_rx_rec_wait(sk, NULL, flags & SPLICE_F_NONBLOCK,
2057                                       timeo);
2058                 if (err <= 0)
2059                         goto splice_read_end;
2060
2061                 err = tls_rx_one_record(sk, NULL, &darg);
2062                 if (err < 0) {
2063                         tls_err_abort(sk, -EBADMSG);
2064                         goto splice_read_end;
2065                 }
2066
2067                 skb = ctx->recv_pkt;
2068                 tls_rx_rec_done(ctx);
2069         }
2070
2071         rxm = strp_msg(skb);
2072         tlm = tls_msg(skb);
2073
2074         /* splice does not support reading control messages */
2075         if (tlm->control != TLS_RECORD_TYPE_DATA) {
2076                 err = -EINVAL;
2077                 goto splice_requeue;
2078         }
2079
2080         chunk = min_t(unsigned int, rxm->full_len, len);
2081         copied = skb_splice_bits(skb, sk, rxm->offset, pipe, chunk, flags);
2082         if (copied < 0)
2083                 goto splice_requeue;
2084
2085         if (chunk < rxm->full_len) {
2086                 rxm->offset += len;
2087                 rxm->full_len -= len;
2088                 goto splice_requeue;
2089         }
2090
2091         consume_skb(skb);
2092
2093 splice_read_end:
2094         tls_rx_reader_unlock(sk, ctx);
2095         return copied ? : err;
2096
2097 splice_requeue:
2098         __skb_queue_head(&ctx->rx_list, skb);
2099         goto splice_read_end;
2100 }
2101
2102 bool tls_sw_sock_is_readable(struct sock *sk)
2103 {
2104         struct tls_context *tls_ctx = tls_get_ctx(sk);
2105         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2106         bool ingress_empty = true;
2107         struct sk_psock *psock;
2108
2109         rcu_read_lock();
2110         psock = sk_psock(sk);
2111         if (psock)
2112                 ingress_empty = list_empty(&psock->ingress_msg);
2113         rcu_read_unlock();
2114
2115         return !ingress_empty || ctx->recv_pkt ||
2116                 !skb_queue_empty(&ctx->rx_list);
2117 }
2118
2119 static int tls_read_size(struct strparser *strp, struct sk_buff *skb)
2120 {
2121         struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
2122         struct tls_prot_info *prot = &tls_ctx->prot_info;
2123         char header[TLS_HEADER_SIZE + MAX_IV_SIZE];
2124         struct strp_msg *rxm = strp_msg(skb);
2125         struct tls_msg *tlm = tls_msg(skb);
2126         size_t cipher_overhead;
2127         size_t data_len = 0;
2128         int ret;
2129
2130         /* Verify that we have a full TLS header, or wait for more data */
2131         if (rxm->offset + prot->prepend_size > skb->len)
2132                 return 0;
2133
2134         /* Sanity-check size of on-stack buffer. */
2135         if (WARN_ON(prot->prepend_size > sizeof(header))) {
2136                 ret = -EINVAL;
2137                 goto read_failure;
2138         }
2139
2140         /* Linearize header to local buffer */
2141         ret = skb_copy_bits(skb, rxm->offset, header, prot->prepend_size);
2142         if (ret < 0)
2143                 goto read_failure;
2144
2145         tlm->control = header[0];
2146
2147         data_len = ((header[4] & 0xFF) | (header[3] << 8));
2148
2149         cipher_overhead = prot->tag_size;
2150         if (prot->version != TLS_1_3_VERSION &&
2151             prot->cipher_type != TLS_CIPHER_CHACHA20_POLY1305)
2152                 cipher_overhead += prot->iv_size;
2153
2154         if (data_len > TLS_MAX_PAYLOAD_SIZE + cipher_overhead +
2155             prot->tail_size) {
2156                 ret = -EMSGSIZE;
2157                 goto read_failure;
2158         }
2159         if (data_len < cipher_overhead) {
2160                 ret = -EBADMSG;
2161                 goto read_failure;
2162         }
2163
2164         /* Note that both TLS1.3 and TLS1.2 use TLS_1_2 version here */
2165         if (header[1] != TLS_1_2_VERSION_MINOR ||
2166             header[2] != TLS_1_2_VERSION_MAJOR) {
2167                 ret = -EINVAL;
2168                 goto read_failure;
2169         }
2170
2171         tls_device_rx_resync_new_rec(strp->sk, data_len + TLS_HEADER_SIZE,
2172                                      TCP_SKB_CB(skb)->seq + rxm->offset);
2173         return data_len + TLS_HEADER_SIZE;
2174
2175 read_failure:
2176         tls_err_abort(strp->sk, ret);
2177
2178         return ret;
2179 }
2180
2181 static void tls_queue(struct strparser *strp, struct sk_buff *skb)
2182 {
2183         struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
2184         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2185
2186         ctx->recv_pkt = skb;
2187         strp_pause(strp);
2188
2189         ctx->saved_data_ready(strp->sk);
2190 }
2191
2192 static void tls_data_ready(struct sock *sk)
2193 {
2194         struct tls_context *tls_ctx = tls_get_ctx(sk);
2195         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2196         struct sk_psock *psock;
2197
2198         strp_data_ready(&ctx->strp);
2199
2200         psock = sk_psock_get(sk);
2201         if (psock) {
2202                 if (!list_empty(&psock->ingress_msg))
2203                         ctx->saved_data_ready(sk);
2204                 sk_psock_put(sk, psock);
2205         }
2206 }
2207
2208 void tls_sw_cancel_work_tx(struct tls_context *tls_ctx)
2209 {
2210         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2211
2212         set_bit(BIT_TX_CLOSING, &ctx->tx_bitmask);
2213         set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask);
2214         cancel_delayed_work_sync(&ctx->tx_work.work);
2215 }
2216
2217 void tls_sw_release_resources_tx(struct sock *sk)
2218 {
2219         struct tls_context *tls_ctx = tls_get_ctx(sk);
2220         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2221         struct tls_rec *rec, *tmp;
2222         int pending;
2223
2224         /* Wait for any pending async encryptions to complete */
2225         spin_lock_bh(&ctx->encrypt_compl_lock);
2226         ctx->async_notify = true;
2227         pending = atomic_read(&ctx->encrypt_pending);
2228         spin_unlock_bh(&ctx->encrypt_compl_lock);
2229
2230         if (pending)
2231                 crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
2232
2233         tls_tx_records(sk, -1);
2234
2235         /* Free up un-sent records in tx_list. First, free
2236          * the partially sent record if any at head of tx_list.
2237          */
2238         if (tls_ctx->partially_sent_record) {
2239                 tls_free_partial_record(sk, tls_ctx);
2240                 rec = list_first_entry(&ctx->tx_list,
2241                                        struct tls_rec, list);
2242                 list_del(&rec->list);
2243                 sk_msg_free(sk, &rec->msg_plaintext);
2244                 kfree(rec);
2245         }
2246
2247         list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
2248                 list_del(&rec->list);
2249                 sk_msg_free(sk, &rec->msg_encrypted);
2250                 sk_msg_free(sk, &rec->msg_plaintext);
2251                 kfree(rec);
2252         }
2253
2254         crypto_free_aead(ctx->aead_send);
2255         tls_free_open_rec(sk);
2256 }
2257
2258 void tls_sw_free_ctx_tx(struct tls_context *tls_ctx)
2259 {
2260         struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2261
2262         kfree(ctx);
2263 }
2264
2265 void tls_sw_release_resources_rx(struct sock *sk)
2266 {
2267         struct tls_context *tls_ctx = tls_get_ctx(sk);
2268         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2269
2270         kfree(tls_ctx->rx.rec_seq);
2271         kfree(tls_ctx->rx.iv);
2272
2273         if (ctx->aead_recv) {
2274                 kfree_skb(ctx->recv_pkt);
2275                 ctx->recv_pkt = NULL;
2276                 __skb_queue_purge(&ctx->rx_list);
2277                 crypto_free_aead(ctx->aead_recv);
2278                 strp_stop(&ctx->strp);
2279                 /* If tls_sw_strparser_arm() was not called (cleanup paths)
2280                  * we still want to strp_stop(), but sk->sk_data_ready was
2281                  * never swapped.
2282                  */
2283                 if (ctx->saved_data_ready) {
2284                         write_lock_bh(&sk->sk_callback_lock);
2285                         sk->sk_data_ready = ctx->saved_data_ready;
2286                         write_unlock_bh(&sk->sk_callback_lock);
2287                 }
2288         }
2289 }
2290
2291 void tls_sw_strparser_done(struct tls_context *tls_ctx)
2292 {
2293         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2294
2295         strp_done(&ctx->strp);
2296 }
2297
2298 void tls_sw_free_ctx_rx(struct tls_context *tls_ctx)
2299 {
2300         struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2301
2302         kfree(ctx);
2303 }
2304
2305 void tls_sw_free_resources_rx(struct sock *sk)
2306 {
2307         struct tls_context *tls_ctx = tls_get_ctx(sk);
2308
2309         tls_sw_release_resources_rx(sk);
2310         tls_sw_free_ctx_rx(tls_ctx);
2311 }
2312
2313 /* The work handler to transmitt the encrypted records in tx_list */
2314 static void tx_work_handler(struct work_struct *work)
2315 {
2316         struct delayed_work *delayed_work = to_delayed_work(work);
2317         struct tx_work *tx_work = container_of(delayed_work,
2318                                                struct tx_work, work);
2319         struct sock *sk = tx_work->sk;
2320         struct tls_context *tls_ctx = tls_get_ctx(sk);
2321         struct tls_sw_context_tx *ctx;
2322
2323         if (unlikely(!tls_ctx))
2324                 return;
2325
2326         ctx = tls_sw_ctx_tx(tls_ctx);
2327         if (test_bit(BIT_TX_CLOSING, &ctx->tx_bitmask))
2328                 return;
2329
2330         if (!test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
2331                 return;
2332         mutex_lock(&tls_ctx->tx_lock);
2333         lock_sock(sk);
2334         tls_tx_records(sk, -1);
2335         release_sock(sk);
2336         mutex_unlock(&tls_ctx->tx_lock);
2337 }
2338
2339 static bool tls_is_tx_ready(struct tls_sw_context_tx *ctx)
2340 {
2341         struct tls_rec *rec;
2342
2343         rec = list_first_entry(&ctx->tx_list, struct tls_rec, list);
2344         if (!rec)
2345                 return false;
2346
2347         return READ_ONCE(rec->tx_ready);
2348 }
2349
2350 void tls_sw_write_space(struct sock *sk, struct tls_context *ctx)
2351 {
2352         struct tls_sw_context_tx *tx_ctx = tls_sw_ctx_tx(ctx);
2353
2354         /* Schedule the transmission if tx list is ready */
2355         if (tls_is_tx_ready(tx_ctx) &&
2356             !test_and_set_bit(BIT_TX_SCHEDULED, &tx_ctx->tx_bitmask))
2357                 schedule_delayed_work(&tx_ctx->tx_work.work, 0);
2358 }
2359
2360 void tls_sw_strparser_arm(struct sock *sk, struct tls_context *tls_ctx)
2361 {
2362         struct tls_sw_context_rx *rx_ctx = tls_sw_ctx_rx(tls_ctx);
2363
2364         write_lock_bh(&sk->sk_callback_lock);
2365         rx_ctx->saved_data_ready = sk->sk_data_ready;
2366         sk->sk_data_ready = tls_data_ready;
2367         write_unlock_bh(&sk->sk_callback_lock);
2368
2369         strp_check_rcv(&rx_ctx->strp);
2370 }
2371
2372 void tls_update_rx_zc_capable(struct tls_context *tls_ctx)
2373 {
2374         struct tls_sw_context_rx *rx_ctx = tls_sw_ctx_rx(tls_ctx);
2375
2376         rx_ctx->zc_capable = tls_ctx->rx_no_pad ||
2377                 tls_ctx->prot_info.version != TLS_1_3_VERSION;
2378 }
2379
2380 int tls_set_sw_offload(struct sock *sk, struct tls_context *ctx, int tx)
2381 {
2382         struct tls_context *tls_ctx = tls_get_ctx(sk);
2383         struct tls_prot_info *prot = &tls_ctx->prot_info;
2384         struct tls_crypto_info *crypto_info;
2385         struct tls_sw_context_tx *sw_ctx_tx = NULL;
2386         struct tls_sw_context_rx *sw_ctx_rx = NULL;
2387         struct cipher_context *cctx;
2388         struct crypto_aead **aead;
2389         struct strp_callbacks cb;
2390         u16 nonce_size, tag_size, iv_size, rec_seq_size, salt_size;
2391         struct crypto_tfm *tfm;
2392         char *iv, *rec_seq, *key, *salt, *cipher_name;
2393         size_t keysize;
2394         int rc = 0;
2395
2396         if (!ctx) {
2397                 rc = -EINVAL;
2398                 goto out;
2399         }
2400
2401         if (tx) {
2402                 if (!ctx->priv_ctx_tx) {
2403                         sw_ctx_tx = kzalloc(sizeof(*sw_ctx_tx), GFP_KERNEL);
2404                         if (!sw_ctx_tx) {
2405                                 rc = -ENOMEM;
2406                                 goto out;
2407                         }
2408                         ctx->priv_ctx_tx = sw_ctx_tx;
2409                 } else {
2410                         sw_ctx_tx =
2411                                 (struct tls_sw_context_tx *)ctx->priv_ctx_tx;
2412                 }
2413         } else {
2414                 if (!ctx->priv_ctx_rx) {
2415                         sw_ctx_rx = kzalloc(sizeof(*sw_ctx_rx), GFP_KERNEL);
2416                         if (!sw_ctx_rx) {
2417                                 rc = -ENOMEM;
2418                                 goto out;
2419                         }
2420                         ctx->priv_ctx_rx = sw_ctx_rx;
2421                 } else {
2422                         sw_ctx_rx =
2423                                 (struct tls_sw_context_rx *)ctx->priv_ctx_rx;
2424                 }
2425         }
2426
2427         if (tx) {
2428                 crypto_init_wait(&sw_ctx_tx->async_wait);
2429                 spin_lock_init(&sw_ctx_tx->encrypt_compl_lock);
2430                 crypto_info = &ctx->crypto_send.info;
2431                 cctx = &ctx->tx;
2432                 aead = &sw_ctx_tx->aead_send;
2433                 INIT_LIST_HEAD(&sw_ctx_tx->tx_list);
2434                 INIT_DELAYED_WORK(&sw_ctx_tx->tx_work.work, tx_work_handler);
2435                 sw_ctx_tx->tx_work.sk = sk;
2436         } else {
2437                 crypto_init_wait(&sw_ctx_rx->async_wait);
2438                 spin_lock_init(&sw_ctx_rx->decrypt_compl_lock);
2439                 init_waitqueue_head(&sw_ctx_rx->wq);
2440                 crypto_info = &ctx->crypto_recv.info;
2441                 cctx = &ctx->rx;
2442                 skb_queue_head_init(&sw_ctx_rx->rx_list);
2443                 aead = &sw_ctx_rx->aead_recv;
2444         }
2445
2446         switch (crypto_info->cipher_type) {
2447         case TLS_CIPHER_AES_GCM_128: {
2448                 struct tls12_crypto_info_aes_gcm_128 *gcm_128_info;
2449
2450                 gcm_128_info = (void *)crypto_info;
2451                 nonce_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
2452                 tag_size = TLS_CIPHER_AES_GCM_128_TAG_SIZE;
2453                 iv_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
2454                 iv = gcm_128_info->iv;
2455                 rec_seq_size = TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE;
2456                 rec_seq = gcm_128_info->rec_seq;
2457                 keysize = TLS_CIPHER_AES_GCM_128_KEY_SIZE;
2458                 key = gcm_128_info->key;
2459                 salt = gcm_128_info->salt;
2460                 salt_size = TLS_CIPHER_AES_GCM_128_SALT_SIZE;
2461                 cipher_name = "gcm(aes)";
2462                 break;
2463         }
2464         case TLS_CIPHER_AES_GCM_256: {
2465                 struct tls12_crypto_info_aes_gcm_256 *gcm_256_info;
2466
2467                 gcm_256_info = (void *)crypto_info;
2468                 nonce_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
2469                 tag_size = TLS_CIPHER_AES_GCM_256_TAG_SIZE;
2470                 iv_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
2471                 iv = gcm_256_info->iv;
2472                 rec_seq_size = TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE;
2473                 rec_seq = gcm_256_info->rec_seq;
2474                 keysize = TLS_CIPHER_AES_GCM_256_KEY_SIZE;
2475                 key = gcm_256_info->key;
2476                 salt = gcm_256_info->salt;
2477                 salt_size = TLS_CIPHER_AES_GCM_256_SALT_SIZE;
2478                 cipher_name = "gcm(aes)";
2479                 break;
2480         }
2481         case TLS_CIPHER_AES_CCM_128: {
2482                 struct tls12_crypto_info_aes_ccm_128 *ccm_128_info;
2483
2484                 ccm_128_info = (void *)crypto_info;
2485                 nonce_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
2486                 tag_size = TLS_CIPHER_AES_CCM_128_TAG_SIZE;
2487                 iv_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
2488                 iv = ccm_128_info->iv;
2489                 rec_seq_size = TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE;
2490                 rec_seq = ccm_128_info->rec_seq;
2491                 keysize = TLS_CIPHER_AES_CCM_128_KEY_SIZE;
2492                 key = ccm_128_info->key;
2493                 salt = ccm_128_info->salt;
2494                 salt_size = TLS_CIPHER_AES_CCM_128_SALT_SIZE;
2495                 cipher_name = "ccm(aes)";
2496                 break;
2497         }
2498         case TLS_CIPHER_CHACHA20_POLY1305: {
2499                 struct tls12_crypto_info_chacha20_poly1305 *chacha20_poly1305_info;
2500
2501                 chacha20_poly1305_info = (void *)crypto_info;
2502                 nonce_size = 0;
2503                 tag_size = TLS_CIPHER_CHACHA20_POLY1305_TAG_SIZE;
2504                 iv_size = TLS_CIPHER_CHACHA20_POLY1305_IV_SIZE;
2505                 iv = chacha20_poly1305_info->iv;
2506                 rec_seq_size = TLS_CIPHER_CHACHA20_POLY1305_REC_SEQ_SIZE;
2507                 rec_seq = chacha20_poly1305_info->rec_seq;
2508                 keysize = TLS_CIPHER_CHACHA20_POLY1305_KEY_SIZE;
2509                 key = chacha20_poly1305_info->key;
2510                 salt = chacha20_poly1305_info->salt;
2511                 salt_size = TLS_CIPHER_CHACHA20_POLY1305_SALT_SIZE;
2512                 cipher_name = "rfc7539(chacha20,poly1305)";
2513                 break;
2514         }
2515         case TLS_CIPHER_SM4_GCM: {
2516                 struct tls12_crypto_info_sm4_gcm *sm4_gcm_info;
2517
2518                 sm4_gcm_info = (void *)crypto_info;
2519                 nonce_size = TLS_CIPHER_SM4_GCM_IV_SIZE;
2520                 tag_size = TLS_CIPHER_SM4_GCM_TAG_SIZE;
2521                 iv_size = TLS_CIPHER_SM4_GCM_IV_SIZE;
2522                 iv = sm4_gcm_info->iv;
2523                 rec_seq_size = TLS_CIPHER_SM4_GCM_REC_SEQ_SIZE;
2524                 rec_seq = sm4_gcm_info->rec_seq;
2525                 keysize = TLS_CIPHER_SM4_GCM_KEY_SIZE;
2526                 key = sm4_gcm_info->key;
2527                 salt = sm4_gcm_info->salt;
2528                 salt_size = TLS_CIPHER_SM4_GCM_SALT_SIZE;
2529                 cipher_name = "gcm(sm4)";
2530                 break;
2531         }
2532         case TLS_CIPHER_SM4_CCM: {
2533                 struct tls12_crypto_info_sm4_ccm *sm4_ccm_info;
2534
2535                 sm4_ccm_info = (void *)crypto_info;
2536                 nonce_size = TLS_CIPHER_SM4_CCM_IV_SIZE;
2537                 tag_size = TLS_CIPHER_SM4_CCM_TAG_SIZE;
2538                 iv_size = TLS_CIPHER_SM4_CCM_IV_SIZE;
2539                 iv = sm4_ccm_info->iv;
2540                 rec_seq_size = TLS_CIPHER_SM4_CCM_REC_SEQ_SIZE;
2541                 rec_seq = sm4_ccm_info->rec_seq;
2542                 keysize = TLS_CIPHER_SM4_CCM_KEY_SIZE;
2543                 key = sm4_ccm_info->key;
2544                 salt = sm4_ccm_info->salt;
2545                 salt_size = TLS_CIPHER_SM4_CCM_SALT_SIZE;
2546                 cipher_name = "ccm(sm4)";
2547                 break;
2548         }
2549         default:
2550                 rc = -EINVAL;
2551                 goto free_priv;
2552         }
2553
2554         if (crypto_info->version == TLS_1_3_VERSION) {
2555                 nonce_size = 0;
2556                 prot->aad_size = TLS_HEADER_SIZE;
2557                 prot->tail_size = 1;
2558         } else {
2559                 prot->aad_size = TLS_AAD_SPACE_SIZE;
2560                 prot->tail_size = 0;
2561         }
2562
2563         /* Sanity-check the sizes for stack allocations. */
2564         if (iv_size > MAX_IV_SIZE || nonce_size > MAX_IV_SIZE ||
2565             rec_seq_size > TLS_MAX_REC_SEQ_SIZE || tag_size != TLS_TAG_SIZE ||
2566             prot->aad_size > TLS_MAX_AAD_SIZE) {
2567                 rc = -EINVAL;
2568                 goto free_priv;
2569         }
2570
2571         prot->version = crypto_info->version;
2572         prot->cipher_type = crypto_info->cipher_type;
2573         prot->prepend_size = TLS_HEADER_SIZE + nonce_size;
2574         prot->tag_size = tag_size;
2575         prot->overhead_size = prot->prepend_size +
2576                               prot->tag_size + prot->tail_size;
2577         prot->iv_size = iv_size;
2578         prot->salt_size = salt_size;
2579         cctx->iv = kmalloc(iv_size + salt_size, GFP_KERNEL);
2580         if (!cctx->iv) {
2581                 rc = -ENOMEM;
2582                 goto free_priv;
2583         }
2584         /* Note: 128 & 256 bit salt are the same size */
2585         prot->rec_seq_size = rec_seq_size;
2586         memcpy(cctx->iv, salt, salt_size);
2587         memcpy(cctx->iv + salt_size, iv, iv_size);
2588         cctx->rec_seq = kmemdup(rec_seq, rec_seq_size, GFP_KERNEL);
2589         if (!cctx->rec_seq) {
2590                 rc = -ENOMEM;
2591                 goto free_iv;
2592         }
2593
2594         if (!*aead) {
2595                 *aead = crypto_alloc_aead(cipher_name, 0, 0);
2596                 if (IS_ERR(*aead)) {
2597                         rc = PTR_ERR(*aead);
2598                         *aead = NULL;
2599                         goto free_rec_seq;
2600                 }
2601         }
2602
2603         ctx->push_pending_record = tls_sw_push_pending_record;
2604
2605         rc = crypto_aead_setkey(*aead, key, keysize);
2606
2607         if (rc)
2608                 goto free_aead;
2609
2610         rc = crypto_aead_setauthsize(*aead, prot->tag_size);
2611         if (rc)
2612                 goto free_aead;
2613
2614         if (sw_ctx_rx) {
2615                 tfm = crypto_aead_tfm(sw_ctx_rx->aead_recv);
2616
2617                 tls_update_rx_zc_capable(ctx);
2618                 sw_ctx_rx->async_capable =
2619                         crypto_info->version != TLS_1_3_VERSION &&
2620                         !!(tfm->__crt_alg->cra_flags & CRYPTO_ALG_ASYNC);
2621
2622                 /* Set up strparser */
2623                 memset(&cb, 0, sizeof(cb));
2624                 cb.rcv_msg = tls_queue;
2625                 cb.parse_msg = tls_read_size;
2626
2627                 strp_init(&sw_ctx_rx->strp, sk, &cb);
2628         }
2629
2630         goto out;
2631
2632 free_aead:
2633         crypto_free_aead(*aead);
2634         *aead = NULL;
2635 free_rec_seq:
2636         kfree(cctx->rec_seq);
2637         cctx->rec_seq = NULL;
2638 free_iv:
2639         kfree(cctx->iv);
2640         cctx->iv = NULL;
2641 free_priv:
2642         if (tx) {
2643                 kfree(ctx->priv_ctx_tx);
2644                 ctx->priv_ctx_tx = NULL;
2645         } else {
2646                 kfree(ctx->priv_ctx_rx);
2647                 ctx->priv_ctx_rx = NULL;
2648         }
2649 out:
2650         return rc;
2651 }