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