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