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