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