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