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