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