xref: /openbmc/linux/net/tls/tls_sw.c (revision 11696c5e)
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 	ret = mutex_lock_interruptible(&tls_ctx->tx_lock);
960 	if (ret)
961 		return ret;
962 	lock_sock(sk);
963 
964 	if (unlikely(msg->msg_controllen)) {
965 		ret = tls_process_cmsg(sk, msg, &record_type);
966 		if (ret) {
967 			if (ret == -EINPROGRESS)
968 				num_async++;
969 			else if (ret != -EAGAIN)
970 				goto send_end;
971 		}
972 	}
973 
974 	while (msg_data_left(msg)) {
975 		if (sk->sk_err) {
976 			ret = -sk->sk_err;
977 			goto send_end;
978 		}
979 
980 		if (ctx->open_rec)
981 			rec = ctx->open_rec;
982 		else
983 			rec = ctx->open_rec = tls_get_rec(sk);
984 		if (!rec) {
985 			ret = -ENOMEM;
986 			goto send_end;
987 		}
988 
989 		msg_pl = &rec->msg_plaintext;
990 		msg_en = &rec->msg_encrypted;
991 
992 		orig_size = msg_pl->sg.size;
993 		full_record = false;
994 		try_to_copy = msg_data_left(msg);
995 		record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
996 		if (try_to_copy >= record_room) {
997 			try_to_copy = record_room;
998 			full_record = true;
999 		}
1000 
1001 		required_size = msg_pl->sg.size + try_to_copy +
1002 				prot->overhead_size;
1003 
1004 		if (!sk_stream_memory_free(sk))
1005 			goto wait_for_sndbuf;
1006 
1007 alloc_encrypted:
1008 		ret = tls_alloc_encrypted_msg(sk, required_size);
1009 		if (ret) {
1010 			if (ret != -ENOSPC)
1011 				goto wait_for_memory;
1012 
1013 			/* Adjust try_to_copy according to the amount that was
1014 			 * actually allocated. The difference is due
1015 			 * to max sg elements limit
1016 			 */
1017 			try_to_copy -= required_size - msg_en->sg.size;
1018 			full_record = true;
1019 		}
1020 
1021 		if (!is_kvec && (full_record || eor) && !async_capable) {
1022 			u32 first = msg_pl->sg.end;
1023 
1024 			ret = sk_msg_zerocopy_from_iter(sk, &msg->msg_iter,
1025 							msg_pl, try_to_copy);
1026 			if (ret)
1027 				goto fallback_to_reg_send;
1028 
1029 			num_zc++;
1030 			copied += try_to_copy;
1031 
1032 			sk_msg_sg_copy_set(msg_pl, first);
1033 			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1034 						  record_type, &copied,
1035 						  msg->msg_flags);
1036 			if (ret) {
1037 				if (ret == -EINPROGRESS)
1038 					num_async++;
1039 				else if (ret == -ENOMEM)
1040 					goto wait_for_memory;
1041 				else if (ctx->open_rec && ret == -ENOSPC)
1042 					goto rollback_iter;
1043 				else if (ret != -EAGAIN)
1044 					goto send_end;
1045 			}
1046 			continue;
1047 rollback_iter:
1048 			copied -= try_to_copy;
1049 			sk_msg_sg_copy_clear(msg_pl, first);
1050 			iov_iter_revert(&msg->msg_iter,
1051 					msg_pl->sg.size - orig_size);
1052 fallback_to_reg_send:
1053 			sk_msg_trim(sk, msg_pl, orig_size);
1054 		}
1055 
1056 		required_size = msg_pl->sg.size + try_to_copy;
1057 
1058 		ret = tls_clone_plaintext_msg(sk, required_size);
1059 		if (ret) {
1060 			if (ret != -ENOSPC)
1061 				goto send_end;
1062 
1063 			/* Adjust try_to_copy according to the amount that was
1064 			 * actually allocated. The difference is due
1065 			 * to max sg elements limit
1066 			 */
1067 			try_to_copy -= required_size - msg_pl->sg.size;
1068 			full_record = true;
1069 			sk_msg_trim(sk, msg_en,
1070 				    msg_pl->sg.size + prot->overhead_size);
1071 		}
1072 
1073 		if (try_to_copy) {
1074 			ret = sk_msg_memcopy_from_iter(sk, &msg->msg_iter,
1075 						       msg_pl, try_to_copy);
1076 			if (ret < 0)
1077 				goto trim_sgl;
1078 		}
1079 
1080 		/* Open records defined only if successfully copied, otherwise
1081 		 * we would trim the sg but not reset the open record frags.
1082 		 */
1083 		tls_ctx->pending_open_record_frags = true;
1084 		copied += try_to_copy;
1085 		if (full_record || eor) {
1086 			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1087 						  record_type, &copied,
1088 						  msg->msg_flags);
1089 			if (ret) {
1090 				if (ret == -EINPROGRESS)
1091 					num_async++;
1092 				else if (ret == -ENOMEM)
1093 					goto wait_for_memory;
1094 				else if (ret != -EAGAIN) {
1095 					if (ret == -ENOSPC)
1096 						ret = 0;
1097 					goto send_end;
1098 				}
1099 			}
1100 		}
1101 
1102 		continue;
1103 
1104 wait_for_sndbuf:
1105 		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1106 wait_for_memory:
1107 		ret = sk_stream_wait_memory(sk, &timeo);
1108 		if (ret) {
1109 trim_sgl:
1110 			if (ctx->open_rec)
1111 				tls_trim_both_msgs(sk, orig_size);
1112 			goto send_end;
1113 		}
1114 
1115 		if (ctx->open_rec && msg_en->sg.size < required_size)
1116 			goto alloc_encrypted;
1117 	}
1118 
1119 	if (!num_async) {
1120 		goto send_end;
1121 	} else if (num_zc) {
1122 		/* Wait for pending encryptions to get completed */
1123 		spin_lock_bh(&ctx->encrypt_compl_lock);
1124 		ctx->async_notify = true;
1125 
1126 		pending = atomic_read(&ctx->encrypt_pending);
1127 		spin_unlock_bh(&ctx->encrypt_compl_lock);
1128 		if (pending)
1129 			crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
1130 		else
1131 			reinit_completion(&ctx->async_wait.completion);
1132 
1133 		/* There can be no concurrent accesses, since we have no
1134 		 * pending encrypt operations
1135 		 */
1136 		WRITE_ONCE(ctx->async_notify, false);
1137 
1138 		if (ctx->async_wait.err) {
1139 			ret = ctx->async_wait.err;
1140 			copied = 0;
1141 		}
1142 	}
1143 
1144 	/* Transmit if any encryptions have completed */
1145 	if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1146 		cancel_delayed_work(&ctx->tx_work.work);
1147 		tls_tx_records(sk, msg->msg_flags);
1148 	}
1149 
1150 send_end:
1151 	ret = sk_stream_error(sk, msg->msg_flags, ret);
1152 
1153 	release_sock(sk);
1154 	mutex_unlock(&tls_ctx->tx_lock);
1155 	return copied > 0 ? copied : ret;
1156 }
1157 
1158 static int tls_sw_do_sendpage(struct sock *sk, struct page *page,
1159 			      int offset, size_t size, int flags)
1160 {
1161 	long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
1162 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1163 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
1164 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1165 	unsigned char record_type = TLS_RECORD_TYPE_DATA;
1166 	struct sk_msg *msg_pl;
1167 	struct tls_rec *rec;
1168 	int num_async = 0;
1169 	ssize_t copied = 0;
1170 	bool full_record;
1171 	int record_room;
1172 	int ret = 0;
1173 	bool eor;
1174 
1175 	eor = !(flags & MSG_SENDPAGE_NOTLAST);
1176 	sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
1177 
1178 	/* Call the sk_stream functions to manage the sndbuf mem. */
1179 	while (size > 0) {
1180 		size_t copy, required_size;
1181 
1182 		if (sk->sk_err) {
1183 			ret = -sk->sk_err;
1184 			goto sendpage_end;
1185 		}
1186 
1187 		if (ctx->open_rec)
1188 			rec = ctx->open_rec;
1189 		else
1190 			rec = ctx->open_rec = tls_get_rec(sk);
1191 		if (!rec) {
1192 			ret = -ENOMEM;
1193 			goto sendpage_end;
1194 		}
1195 
1196 		msg_pl = &rec->msg_plaintext;
1197 
1198 		full_record = false;
1199 		record_room = TLS_MAX_PAYLOAD_SIZE - msg_pl->sg.size;
1200 		copy = size;
1201 		if (copy >= record_room) {
1202 			copy = record_room;
1203 			full_record = true;
1204 		}
1205 
1206 		required_size = msg_pl->sg.size + copy + prot->overhead_size;
1207 
1208 		if (!sk_stream_memory_free(sk))
1209 			goto wait_for_sndbuf;
1210 alloc_payload:
1211 		ret = tls_alloc_encrypted_msg(sk, required_size);
1212 		if (ret) {
1213 			if (ret != -ENOSPC)
1214 				goto wait_for_memory;
1215 
1216 			/* Adjust copy according to the amount that was
1217 			 * actually allocated. The difference is due
1218 			 * to max sg elements limit
1219 			 */
1220 			copy -= required_size - msg_pl->sg.size;
1221 			full_record = true;
1222 		}
1223 
1224 		sk_msg_page_add(msg_pl, page, copy, offset);
1225 		sk_mem_charge(sk, copy);
1226 
1227 		offset += copy;
1228 		size -= copy;
1229 		copied += copy;
1230 
1231 		tls_ctx->pending_open_record_frags = true;
1232 		if (full_record || eor || sk_msg_full(msg_pl)) {
1233 			ret = bpf_exec_tx_verdict(msg_pl, sk, full_record,
1234 						  record_type, &copied, flags);
1235 			if (ret) {
1236 				if (ret == -EINPROGRESS)
1237 					num_async++;
1238 				else if (ret == -ENOMEM)
1239 					goto wait_for_memory;
1240 				else if (ret != -EAGAIN) {
1241 					if (ret == -ENOSPC)
1242 						ret = 0;
1243 					goto sendpage_end;
1244 				}
1245 			}
1246 		}
1247 		continue;
1248 wait_for_sndbuf:
1249 		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1250 wait_for_memory:
1251 		ret = sk_stream_wait_memory(sk, &timeo);
1252 		if (ret) {
1253 			if (ctx->open_rec)
1254 				tls_trim_both_msgs(sk, msg_pl->sg.size);
1255 			goto sendpage_end;
1256 		}
1257 
1258 		if (ctx->open_rec)
1259 			goto alloc_payload;
1260 	}
1261 
1262 	if (num_async) {
1263 		/* Transmit if any encryptions have completed */
1264 		if (test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
1265 			cancel_delayed_work(&ctx->tx_work.work);
1266 			tls_tx_records(sk, flags);
1267 		}
1268 	}
1269 sendpage_end:
1270 	ret = sk_stream_error(sk, flags, ret);
1271 	return copied > 0 ? copied : ret;
1272 }
1273 
1274 int tls_sw_sendpage_locked(struct sock *sk, struct page *page,
1275 			   int offset, size_t size, int flags)
1276 {
1277 	if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
1278 		      MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY |
1279 		      MSG_NO_SHARED_FRAGS))
1280 		return -EOPNOTSUPP;
1281 
1282 	return tls_sw_do_sendpage(sk, page, offset, size, flags);
1283 }
1284 
1285 int tls_sw_sendpage(struct sock *sk, struct page *page,
1286 		    int offset, size_t size, int flags)
1287 {
1288 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1289 	int ret;
1290 
1291 	if (flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL |
1292 		      MSG_SENDPAGE_NOTLAST | MSG_SENDPAGE_NOPOLICY))
1293 		return -EOPNOTSUPP;
1294 
1295 	ret = mutex_lock_interruptible(&tls_ctx->tx_lock);
1296 	if (ret)
1297 		return ret;
1298 	lock_sock(sk);
1299 	ret = tls_sw_do_sendpage(sk, page, offset, size, flags);
1300 	release_sock(sk);
1301 	mutex_unlock(&tls_ctx->tx_lock);
1302 	return ret;
1303 }
1304 
1305 static int
1306 tls_rx_rec_wait(struct sock *sk, struct sk_psock *psock, bool nonblock,
1307 		bool released)
1308 {
1309 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1310 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1311 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1312 	long timeo;
1313 
1314 	timeo = sock_rcvtimeo(sk, nonblock);
1315 
1316 	while (!tls_strp_msg_ready(ctx)) {
1317 		if (!sk_psock_queue_empty(psock))
1318 			return 0;
1319 
1320 		if (sk->sk_err)
1321 			return sock_error(sk);
1322 
1323 		if (!skb_queue_empty(&sk->sk_receive_queue)) {
1324 			tls_strp_check_rcv(&ctx->strp);
1325 			if (tls_strp_msg_ready(ctx))
1326 				break;
1327 		}
1328 
1329 		if (sk->sk_shutdown & RCV_SHUTDOWN)
1330 			return 0;
1331 
1332 		if (sock_flag(sk, SOCK_DONE))
1333 			return 0;
1334 
1335 		if (!timeo)
1336 			return -EAGAIN;
1337 
1338 		released = true;
1339 		add_wait_queue(sk_sleep(sk), &wait);
1340 		sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1341 		sk_wait_event(sk, &timeo,
1342 			      tls_strp_msg_ready(ctx) ||
1343 			      !sk_psock_queue_empty(psock),
1344 			      &wait);
1345 		sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1346 		remove_wait_queue(sk_sleep(sk), &wait);
1347 
1348 		/* Handle signals */
1349 		if (signal_pending(current))
1350 			return sock_intr_errno(timeo);
1351 	}
1352 
1353 	tls_strp_msg_load(&ctx->strp, released);
1354 
1355 	return 1;
1356 }
1357 
1358 static int tls_setup_from_iter(struct iov_iter *from,
1359 			       int length, int *pages_used,
1360 			       struct scatterlist *to,
1361 			       int to_max_pages)
1362 {
1363 	int rc = 0, i = 0, num_elem = *pages_used, maxpages;
1364 	struct page *pages[MAX_SKB_FRAGS];
1365 	unsigned int size = 0;
1366 	ssize_t copied, use;
1367 	size_t offset;
1368 
1369 	while (length > 0) {
1370 		i = 0;
1371 		maxpages = to_max_pages - num_elem;
1372 		if (maxpages == 0) {
1373 			rc = -EFAULT;
1374 			goto out;
1375 		}
1376 		copied = iov_iter_get_pages2(from, pages,
1377 					    length,
1378 					    maxpages, &offset);
1379 		if (copied <= 0) {
1380 			rc = -EFAULT;
1381 			goto out;
1382 		}
1383 
1384 		length -= copied;
1385 		size += copied;
1386 		while (copied) {
1387 			use = min_t(int, copied, PAGE_SIZE - offset);
1388 
1389 			sg_set_page(&to[num_elem],
1390 				    pages[i], use, offset);
1391 			sg_unmark_end(&to[num_elem]);
1392 			/* We do not uncharge memory from this API */
1393 
1394 			offset = 0;
1395 			copied -= use;
1396 
1397 			i++;
1398 			num_elem++;
1399 		}
1400 	}
1401 	/* Mark the end in the last sg entry if newly added */
1402 	if (num_elem > *pages_used)
1403 		sg_mark_end(&to[num_elem - 1]);
1404 out:
1405 	if (rc)
1406 		iov_iter_revert(from, size);
1407 	*pages_used = num_elem;
1408 
1409 	return rc;
1410 }
1411 
1412 static struct sk_buff *
1413 tls_alloc_clrtxt_skb(struct sock *sk, struct sk_buff *skb,
1414 		     unsigned int full_len)
1415 {
1416 	struct strp_msg *clr_rxm;
1417 	struct sk_buff *clr_skb;
1418 	int err;
1419 
1420 	clr_skb = alloc_skb_with_frags(0, full_len, TLS_PAGE_ORDER,
1421 				       &err, sk->sk_allocation);
1422 	if (!clr_skb)
1423 		return NULL;
1424 
1425 	skb_copy_header(clr_skb, skb);
1426 	clr_skb->len = full_len;
1427 	clr_skb->data_len = full_len;
1428 
1429 	clr_rxm = strp_msg(clr_skb);
1430 	clr_rxm->offset = 0;
1431 
1432 	return clr_skb;
1433 }
1434 
1435 /* Decrypt handlers
1436  *
1437  * tls_decrypt_sw() and tls_decrypt_device() are decrypt handlers.
1438  * They must transform the darg in/out argument are as follows:
1439  *       |          Input            |         Output
1440  * -------------------------------------------------------------------
1441  *    zc | Zero-copy decrypt allowed | Zero-copy performed
1442  * async | Async decrypt allowed     | Async crypto used / in progress
1443  *   skb |            *              | Output skb
1444  *
1445  * If ZC decryption was performed darg.skb will point to the input skb.
1446  */
1447 
1448 /* This function decrypts the input skb into either out_iov or in out_sg
1449  * or in skb buffers itself. The input parameter 'darg->zc' indicates if
1450  * zero-copy mode needs to be tried or not. With zero-copy mode, either
1451  * out_iov or out_sg must be non-NULL. In case both out_iov and out_sg are
1452  * NULL, then the decryption happens inside skb buffers itself, i.e.
1453  * zero-copy gets disabled and 'darg->zc' is updated.
1454  */
1455 static int tls_decrypt_sg(struct sock *sk, struct iov_iter *out_iov,
1456 			  struct scatterlist *out_sg,
1457 			  struct tls_decrypt_arg *darg)
1458 {
1459 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1460 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1461 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1462 	int n_sgin, n_sgout, aead_size, err, pages = 0;
1463 	struct sk_buff *skb = tls_strp_msg(ctx);
1464 	const struct strp_msg *rxm = strp_msg(skb);
1465 	const struct tls_msg *tlm = tls_msg(skb);
1466 	struct aead_request *aead_req;
1467 	struct scatterlist *sgin = NULL;
1468 	struct scatterlist *sgout = NULL;
1469 	const int data_len = rxm->full_len - prot->overhead_size;
1470 	int tail_pages = !!prot->tail_size;
1471 	struct tls_decrypt_ctx *dctx;
1472 	struct sk_buff *clear_skb;
1473 	int iv_offset = 0;
1474 	u8 *mem;
1475 
1476 	n_sgin = skb_nsg(skb, rxm->offset + prot->prepend_size,
1477 			 rxm->full_len - prot->prepend_size);
1478 	if (n_sgin < 1)
1479 		return n_sgin ?: -EBADMSG;
1480 
1481 	if (darg->zc && (out_iov || out_sg)) {
1482 		clear_skb = NULL;
1483 
1484 		if (out_iov)
1485 			n_sgout = 1 + tail_pages +
1486 				iov_iter_npages_cap(out_iov, INT_MAX, data_len);
1487 		else
1488 			n_sgout = sg_nents(out_sg);
1489 	} else {
1490 		darg->zc = false;
1491 
1492 		clear_skb = tls_alloc_clrtxt_skb(sk, skb, rxm->full_len);
1493 		if (!clear_skb)
1494 			return -ENOMEM;
1495 
1496 		n_sgout = 1 + skb_shinfo(clear_skb)->nr_frags;
1497 	}
1498 
1499 	/* Increment to accommodate AAD */
1500 	n_sgin = n_sgin + 1;
1501 
1502 	/* Allocate a single block of memory which contains
1503 	 *   aead_req || tls_decrypt_ctx.
1504 	 * Both structs are variable length.
1505 	 */
1506 	aead_size = sizeof(*aead_req) + crypto_aead_reqsize(ctx->aead_recv);
1507 	aead_size = ALIGN(aead_size, __alignof__(*dctx));
1508 	mem = kmalloc(aead_size + struct_size(dctx, sg, n_sgin + n_sgout),
1509 		      sk->sk_allocation);
1510 	if (!mem) {
1511 		err = -ENOMEM;
1512 		goto exit_free_skb;
1513 	}
1514 
1515 	/* Segment the allocated memory */
1516 	aead_req = (struct aead_request *)mem;
1517 	dctx = (struct tls_decrypt_ctx *)(mem + aead_size);
1518 	dctx->sk = sk;
1519 	sgin = &dctx->sg[0];
1520 	sgout = &dctx->sg[n_sgin];
1521 
1522 	/* For CCM based ciphers, first byte of nonce+iv is a constant */
1523 	switch (prot->cipher_type) {
1524 	case TLS_CIPHER_AES_CCM_128:
1525 		dctx->iv[0] = TLS_AES_CCM_IV_B0_BYTE;
1526 		iv_offset = 1;
1527 		break;
1528 	case TLS_CIPHER_SM4_CCM:
1529 		dctx->iv[0] = TLS_SM4_CCM_IV_B0_BYTE;
1530 		iv_offset = 1;
1531 		break;
1532 	}
1533 
1534 	/* Prepare IV */
1535 	if (prot->version == TLS_1_3_VERSION ||
1536 	    prot->cipher_type == TLS_CIPHER_CHACHA20_POLY1305) {
1537 		memcpy(&dctx->iv[iv_offset], tls_ctx->rx.iv,
1538 		       prot->iv_size + prot->salt_size);
1539 	} else {
1540 		err = skb_copy_bits(skb, rxm->offset + TLS_HEADER_SIZE,
1541 				    &dctx->iv[iv_offset] + prot->salt_size,
1542 				    prot->iv_size);
1543 		if (err < 0)
1544 			goto exit_free;
1545 		memcpy(&dctx->iv[iv_offset], tls_ctx->rx.iv, prot->salt_size);
1546 	}
1547 	tls_xor_iv_with_seq(prot, &dctx->iv[iv_offset], tls_ctx->rx.rec_seq);
1548 
1549 	/* Prepare AAD */
1550 	tls_make_aad(dctx->aad, rxm->full_len - prot->overhead_size +
1551 		     prot->tail_size,
1552 		     tls_ctx->rx.rec_seq, tlm->control, prot);
1553 
1554 	/* Prepare sgin */
1555 	sg_init_table(sgin, n_sgin);
1556 	sg_set_buf(&sgin[0], dctx->aad, prot->aad_size);
1557 	err = skb_to_sgvec(skb, &sgin[1],
1558 			   rxm->offset + prot->prepend_size,
1559 			   rxm->full_len - prot->prepend_size);
1560 	if (err < 0)
1561 		goto exit_free;
1562 
1563 	if (clear_skb) {
1564 		sg_init_table(sgout, n_sgout);
1565 		sg_set_buf(&sgout[0], dctx->aad, prot->aad_size);
1566 
1567 		err = skb_to_sgvec(clear_skb, &sgout[1], prot->prepend_size,
1568 				   data_len + prot->tail_size);
1569 		if (err < 0)
1570 			goto exit_free;
1571 	} else if (out_iov) {
1572 		sg_init_table(sgout, n_sgout);
1573 		sg_set_buf(&sgout[0], dctx->aad, prot->aad_size);
1574 
1575 		err = tls_setup_from_iter(out_iov, data_len, &pages, &sgout[1],
1576 					  (n_sgout - 1 - tail_pages));
1577 		if (err < 0)
1578 			goto exit_free_pages;
1579 
1580 		if (prot->tail_size) {
1581 			sg_unmark_end(&sgout[pages]);
1582 			sg_set_buf(&sgout[pages + 1], &dctx->tail,
1583 				   prot->tail_size);
1584 			sg_mark_end(&sgout[pages + 1]);
1585 		}
1586 	} else if (out_sg) {
1587 		memcpy(sgout, out_sg, n_sgout * sizeof(*sgout));
1588 	}
1589 
1590 	/* Prepare and submit AEAD request */
1591 	err = tls_do_decryption(sk, sgin, sgout, dctx->iv,
1592 				data_len + prot->tail_size, aead_req, darg);
1593 	if (err)
1594 		goto exit_free_pages;
1595 
1596 	darg->skb = clear_skb ?: tls_strp_msg(ctx);
1597 	clear_skb = NULL;
1598 
1599 	if (unlikely(darg->async)) {
1600 		err = tls_strp_msg_hold(&ctx->strp, &ctx->async_hold);
1601 		if (err)
1602 			__skb_queue_tail(&ctx->async_hold, darg->skb);
1603 		return err;
1604 	}
1605 
1606 	if (prot->tail_size)
1607 		darg->tail = dctx->tail;
1608 
1609 exit_free_pages:
1610 	/* Release the pages in case iov was mapped to pages */
1611 	for (; pages > 0; pages--)
1612 		put_page(sg_page(&sgout[pages]));
1613 exit_free:
1614 	kfree(mem);
1615 exit_free_skb:
1616 	consume_skb(clear_skb);
1617 	return err;
1618 }
1619 
1620 static int
1621 tls_decrypt_sw(struct sock *sk, struct tls_context *tls_ctx,
1622 	       struct msghdr *msg, struct tls_decrypt_arg *darg)
1623 {
1624 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1625 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1626 	struct strp_msg *rxm;
1627 	int pad, err;
1628 
1629 	err = tls_decrypt_sg(sk, &msg->msg_iter, NULL, darg);
1630 	if (err < 0) {
1631 		if (err == -EBADMSG)
1632 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTERROR);
1633 		return err;
1634 	}
1635 	/* keep going even for ->async, the code below is TLS 1.3 */
1636 
1637 	/* If opportunistic TLS 1.3 ZC failed retry without ZC */
1638 	if (unlikely(darg->zc && prot->version == TLS_1_3_VERSION &&
1639 		     darg->tail != TLS_RECORD_TYPE_DATA)) {
1640 		darg->zc = false;
1641 		if (!darg->tail)
1642 			TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXNOPADVIOL);
1643 		TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSDECRYPTRETRY);
1644 		return tls_decrypt_sw(sk, tls_ctx, msg, darg);
1645 	}
1646 
1647 	pad = tls_padding_length(prot, darg->skb, darg);
1648 	if (pad < 0) {
1649 		if (darg->skb != tls_strp_msg(ctx))
1650 			consume_skb(darg->skb);
1651 		return pad;
1652 	}
1653 
1654 	rxm = strp_msg(darg->skb);
1655 	rxm->full_len -= pad;
1656 
1657 	return 0;
1658 }
1659 
1660 static int
1661 tls_decrypt_device(struct sock *sk, struct msghdr *msg,
1662 		   struct tls_context *tls_ctx, struct tls_decrypt_arg *darg)
1663 {
1664 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
1665 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1666 	struct strp_msg *rxm;
1667 	int pad, err;
1668 
1669 	if (tls_ctx->rx_conf != TLS_HW)
1670 		return 0;
1671 
1672 	err = tls_device_decrypted(sk, tls_ctx);
1673 	if (err <= 0)
1674 		return err;
1675 
1676 	pad = tls_padding_length(prot, tls_strp_msg(ctx), darg);
1677 	if (pad < 0)
1678 		return pad;
1679 
1680 	darg->async = false;
1681 	darg->skb = tls_strp_msg(ctx);
1682 	/* ->zc downgrade check, in case TLS 1.3 gets here */
1683 	darg->zc &= !(prot->version == TLS_1_3_VERSION &&
1684 		      tls_msg(darg->skb)->control != TLS_RECORD_TYPE_DATA);
1685 
1686 	rxm = strp_msg(darg->skb);
1687 	rxm->full_len -= pad;
1688 
1689 	if (!darg->zc) {
1690 		/* Non-ZC case needs a real skb */
1691 		darg->skb = tls_strp_msg_detach(ctx);
1692 		if (!darg->skb)
1693 			return -ENOMEM;
1694 	} else {
1695 		unsigned int off, len;
1696 
1697 		/* In ZC case nobody cares about the output skb.
1698 		 * Just copy the data here. Note the skb is not fully trimmed.
1699 		 */
1700 		off = rxm->offset + prot->prepend_size;
1701 		len = rxm->full_len - prot->overhead_size;
1702 
1703 		err = skb_copy_datagram_msg(darg->skb, off, msg, len);
1704 		if (err)
1705 			return err;
1706 	}
1707 	return 1;
1708 }
1709 
1710 static int tls_rx_one_record(struct sock *sk, struct msghdr *msg,
1711 			     struct tls_decrypt_arg *darg)
1712 {
1713 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1714 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1715 	struct strp_msg *rxm;
1716 	int err;
1717 
1718 	err = tls_decrypt_device(sk, msg, tls_ctx, darg);
1719 	if (!err)
1720 		err = tls_decrypt_sw(sk, tls_ctx, msg, darg);
1721 	if (err < 0)
1722 		return err;
1723 
1724 	rxm = strp_msg(darg->skb);
1725 	rxm->offset += prot->prepend_size;
1726 	rxm->full_len -= prot->overhead_size;
1727 	tls_advance_record_sn(sk, prot, &tls_ctx->rx);
1728 
1729 	return 0;
1730 }
1731 
1732 int decrypt_skb(struct sock *sk, struct scatterlist *sgout)
1733 {
1734 	struct tls_decrypt_arg darg = { .zc = true, };
1735 
1736 	return tls_decrypt_sg(sk, NULL, sgout, &darg);
1737 }
1738 
1739 static int tls_record_content_type(struct msghdr *msg, struct tls_msg *tlm,
1740 				   u8 *control)
1741 {
1742 	int err;
1743 
1744 	if (!*control) {
1745 		*control = tlm->control;
1746 		if (!*control)
1747 			return -EBADMSG;
1748 
1749 		err = put_cmsg(msg, SOL_TLS, TLS_GET_RECORD_TYPE,
1750 			       sizeof(*control), control);
1751 		if (*control != TLS_RECORD_TYPE_DATA) {
1752 			if (err || msg->msg_flags & MSG_CTRUNC)
1753 				return -EIO;
1754 		}
1755 	} else if (*control != tlm->control) {
1756 		return 0;
1757 	}
1758 
1759 	return 1;
1760 }
1761 
1762 static void tls_rx_rec_done(struct tls_sw_context_rx *ctx)
1763 {
1764 	tls_strp_msg_done(&ctx->strp);
1765 }
1766 
1767 /* This function traverses the rx_list in tls receive context to copies the
1768  * decrypted records into the buffer provided by caller zero copy is not
1769  * true. Further, the records are removed from the rx_list if it is not a peek
1770  * case and the record has been consumed completely.
1771  */
1772 static int process_rx_list(struct tls_sw_context_rx *ctx,
1773 			   struct msghdr *msg,
1774 			   u8 *control,
1775 			   size_t skip,
1776 			   size_t len,
1777 			   bool is_peek)
1778 {
1779 	struct sk_buff *skb = skb_peek(&ctx->rx_list);
1780 	struct tls_msg *tlm;
1781 	ssize_t copied = 0;
1782 	int err;
1783 
1784 	while (skip && skb) {
1785 		struct strp_msg *rxm = strp_msg(skb);
1786 		tlm = tls_msg(skb);
1787 
1788 		err = tls_record_content_type(msg, tlm, control);
1789 		if (err <= 0)
1790 			goto out;
1791 
1792 		if (skip < rxm->full_len)
1793 			break;
1794 
1795 		skip = skip - rxm->full_len;
1796 		skb = skb_peek_next(skb, &ctx->rx_list);
1797 	}
1798 
1799 	while (len && skb) {
1800 		struct sk_buff *next_skb;
1801 		struct strp_msg *rxm = strp_msg(skb);
1802 		int chunk = min_t(unsigned int, rxm->full_len - skip, len);
1803 
1804 		tlm = tls_msg(skb);
1805 
1806 		err = tls_record_content_type(msg, tlm, control);
1807 		if (err <= 0)
1808 			goto out;
1809 
1810 		err = skb_copy_datagram_msg(skb, rxm->offset + skip,
1811 					    msg, chunk);
1812 		if (err < 0)
1813 			goto out;
1814 
1815 		len = len - chunk;
1816 		copied = copied + chunk;
1817 
1818 		/* Consume the data from record if it is non-peek case*/
1819 		if (!is_peek) {
1820 			rxm->offset = rxm->offset + chunk;
1821 			rxm->full_len = rxm->full_len - chunk;
1822 
1823 			/* Return if there is unconsumed data in the record */
1824 			if (rxm->full_len - skip)
1825 				break;
1826 		}
1827 
1828 		/* The remaining skip-bytes must lie in 1st record in rx_list.
1829 		 * So from the 2nd record, 'skip' should be 0.
1830 		 */
1831 		skip = 0;
1832 
1833 		if (msg)
1834 			msg->msg_flags |= MSG_EOR;
1835 
1836 		next_skb = skb_peek_next(skb, &ctx->rx_list);
1837 
1838 		if (!is_peek) {
1839 			__skb_unlink(skb, &ctx->rx_list);
1840 			consume_skb(skb);
1841 		}
1842 
1843 		skb = next_skb;
1844 	}
1845 	err = 0;
1846 
1847 out:
1848 	return copied ? : err;
1849 }
1850 
1851 static bool
1852 tls_read_flush_backlog(struct sock *sk, struct tls_prot_info *prot,
1853 		       size_t len_left, size_t decrypted, ssize_t done,
1854 		       size_t *flushed_at)
1855 {
1856 	size_t max_rec;
1857 
1858 	if (len_left <= decrypted)
1859 		return false;
1860 
1861 	max_rec = prot->overhead_size - prot->tail_size + TLS_MAX_PAYLOAD_SIZE;
1862 	if (done - *flushed_at < SZ_128K && tcp_inq(sk) > max_rec)
1863 		return false;
1864 
1865 	*flushed_at = done;
1866 	return sk_flush_backlog(sk);
1867 }
1868 
1869 static int tls_rx_reader_lock(struct sock *sk, struct tls_sw_context_rx *ctx,
1870 			      bool nonblock)
1871 {
1872 	long timeo;
1873 	int err;
1874 
1875 	lock_sock(sk);
1876 
1877 	timeo = sock_rcvtimeo(sk, nonblock);
1878 
1879 	while (unlikely(ctx->reader_present)) {
1880 		DEFINE_WAIT_FUNC(wait, woken_wake_function);
1881 
1882 		ctx->reader_contended = 1;
1883 
1884 		add_wait_queue(&ctx->wq, &wait);
1885 		sk_wait_event(sk, &timeo,
1886 			      !READ_ONCE(ctx->reader_present), &wait);
1887 		remove_wait_queue(&ctx->wq, &wait);
1888 
1889 		if (timeo <= 0) {
1890 			err = -EAGAIN;
1891 			goto err_unlock;
1892 		}
1893 		if (signal_pending(current)) {
1894 			err = sock_intr_errno(timeo);
1895 			goto err_unlock;
1896 		}
1897 	}
1898 
1899 	WRITE_ONCE(ctx->reader_present, 1);
1900 
1901 	return 0;
1902 
1903 err_unlock:
1904 	release_sock(sk);
1905 	return err;
1906 }
1907 
1908 static void tls_rx_reader_unlock(struct sock *sk, struct tls_sw_context_rx *ctx)
1909 {
1910 	if (unlikely(ctx->reader_contended)) {
1911 		if (wq_has_sleeper(&ctx->wq))
1912 			wake_up(&ctx->wq);
1913 		else
1914 			ctx->reader_contended = 0;
1915 
1916 		WARN_ON_ONCE(!ctx->reader_present);
1917 	}
1918 
1919 	WRITE_ONCE(ctx->reader_present, 0);
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 bool tls_sw_sock_is_readable(struct sock *sk)
2218 {
2219 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2220 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2221 	bool ingress_empty = true;
2222 	struct sk_psock *psock;
2223 
2224 	rcu_read_lock();
2225 	psock = sk_psock(sk);
2226 	if (psock)
2227 		ingress_empty = list_empty(&psock->ingress_msg);
2228 	rcu_read_unlock();
2229 
2230 	return !ingress_empty || tls_strp_msg_ready(ctx) ||
2231 		!skb_queue_empty(&ctx->rx_list);
2232 }
2233 
2234 int tls_rx_msg_size(struct tls_strparser *strp, struct sk_buff *skb)
2235 {
2236 	struct tls_context *tls_ctx = tls_get_ctx(strp->sk);
2237 	struct tls_prot_info *prot = &tls_ctx->prot_info;
2238 	char header[TLS_HEADER_SIZE + MAX_IV_SIZE];
2239 	size_t cipher_overhead;
2240 	size_t data_len = 0;
2241 	int ret;
2242 
2243 	/* Verify that we have a full TLS header, or wait for more data */
2244 	if (strp->stm.offset + prot->prepend_size > skb->len)
2245 		return 0;
2246 
2247 	/* Sanity-check size of on-stack buffer. */
2248 	if (WARN_ON(prot->prepend_size > sizeof(header))) {
2249 		ret = -EINVAL;
2250 		goto read_failure;
2251 	}
2252 
2253 	/* Linearize header to local buffer */
2254 	ret = skb_copy_bits(skb, strp->stm.offset, header, prot->prepend_size);
2255 	if (ret < 0)
2256 		goto read_failure;
2257 
2258 	strp->mark = header[0];
2259 
2260 	data_len = ((header[4] & 0xFF) | (header[3] << 8));
2261 
2262 	cipher_overhead = prot->tag_size;
2263 	if (prot->version != TLS_1_3_VERSION &&
2264 	    prot->cipher_type != TLS_CIPHER_CHACHA20_POLY1305)
2265 		cipher_overhead += prot->iv_size;
2266 
2267 	if (data_len > TLS_MAX_PAYLOAD_SIZE + cipher_overhead +
2268 	    prot->tail_size) {
2269 		ret = -EMSGSIZE;
2270 		goto read_failure;
2271 	}
2272 	if (data_len < cipher_overhead) {
2273 		ret = -EBADMSG;
2274 		goto read_failure;
2275 	}
2276 
2277 	/* Note that both TLS1.3 and TLS1.2 use TLS_1_2 version here */
2278 	if (header[1] != TLS_1_2_VERSION_MINOR ||
2279 	    header[2] != TLS_1_2_VERSION_MAJOR) {
2280 		ret = -EINVAL;
2281 		goto read_failure;
2282 	}
2283 
2284 	tls_device_rx_resync_new_rec(strp->sk, data_len + TLS_HEADER_SIZE,
2285 				     TCP_SKB_CB(skb)->seq + strp->stm.offset);
2286 	return data_len + TLS_HEADER_SIZE;
2287 
2288 read_failure:
2289 	tls_err_abort(strp->sk, ret);
2290 
2291 	return ret;
2292 }
2293 
2294 void tls_rx_msg_ready(struct tls_strparser *strp)
2295 {
2296 	struct tls_sw_context_rx *ctx;
2297 
2298 	ctx = container_of(strp, struct tls_sw_context_rx, strp);
2299 	ctx->saved_data_ready(strp->sk);
2300 }
2301 
2302 static void tls_data_ready(struct sock *sk)
2303 {
2304 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2305 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2306 	struct sk_psock *psock;
2307 
2308 	trace_sk_data_ready(sk);
2309 
2310 	tls_strp_data_ready(&ctx->strp);
2311 
2312 	psock = sk_psock_get(sk);
2313 	if (psock) {
2314 		if (!list_empty(&psock->ingress_msg))
2315 			ctx->saved_data_ready(sk);
2316 		sk_psock_put(sk, psock);
2317 	}
2318 }
2319 
2320 void tls_sw_cancel_work_tx(struct tls_context *tls_ctx)
2321 {
2322 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2323 
2324 	set_bit(BIT_TX_CLOSING, &ctx->tx_bitmask);
2325 	set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask);
2326 	cancel_delayed_work_sync(&ctx->tx_work.work);
2327 }
2328 
2329 void tls_sw_release_resources_tx(struct sock *sk)
2330 {
2331 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2332 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2333 	struct tls_rec *rec, *tmp;
2334 	int pending;
2335 
2336 	/* Wait for any pending async encryptions to complete */
2337 	spin_lock_bh(&ctx->encrypt_compl_lock);
2338 	ctx->async_notify = true;
2339 	pending = atomic_read(&ctx->encrypt_pending);
2340 	spin_unlock_bh(&ctx->encrypt_compl_lock);
2341 
2342 	if (pending)
2343 		crypto_wait_req(-EINPROGRESS, &ctx->async_wait);
2344 
2345 	tls_tx_records(sk, -1);
2346 
2347 	/* Free up un-sent records in tx_list. First, free
2348 	 * the partially sent record if any at head of tx_list.
2349 	 */
2350 	if (tls_ctx->partially_sent_record) {
2351 		tls_free_partial_record(sk, tls_ctx);
2352 		rec = list_first_entry(&ctx->tx_list,
2353 				       struct tls_rec, list);
2354 		list_del(&rec->list);
2355 		sk_msg_free(sk, &rec->msg_plaintext);
2356 		kfree(rec);
2357 	}
2358 
2359 	list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) {
2360 		list_del(&rec->list);
2361 		sk_msg_free(sk, &rec->msg_encrypted);
2362 		sk_msg_free(sk, &rec->msg_plaintext);
2363 		kfree(rec);
2364 	}
2365 
2366 	crypto_free_aead(ctx->aead_send);
2367 	tls_free_open_rec(sk);
2368 }
2369 
2370 void tls_sw_free_ctx_tx(struct tls_context *tls_ctx)
2371 {
2372 	struct tls_sw_context_tx *ctx = tls_sw_ctx_tx(tls_ctx);
2373 
2374 	kfree(ctx);
2375 }
2376 
2377 void tls_sw_release_resources_rx(struct sock *sk)
2378 {
2379 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2380 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2381 
2382 	kfree(tls_ctx->rx.rec_seq);
2383 	kfree(tls_ctx->rx.iv);
2384 
2385 	if (ctx->aead_recv) {
2386 		__skb_queue_purge(&ctx->rx_list);
2387 		crypto_free_aead(ctx->aead_recv);
2388 		tls_strp_stop(&ctx->strp);
2389 		/* If tls_sw_strparser_arm() was not called (cleanup paths)
2390 		 * we still want to tls_strp_stop(), but sk->sk_data_ready was
2391 		 * never swapped.
2392 		 */
2393 		if (ctx->saved_data_ready) {
2394 			write_lock_bh(&sk->sk_callback_lock);
2395 			sk->sk_data_ready = ctx->saved_data_ready;
2396 			write_unlock_bh(&sk->sk_callback_lock);
2397 		}
2398 	}
2399 }
2400 
2401 void tls_sw_strparser_done(struct tls_context *tls_ctx)
2402 {
2403 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2404 
2405 	tls_strp_done(&ctx->strp);
2406 }
2407 
2408 void tls_sw_free_ctx_rx(struct tls_context *tls_ctx)
2409 {
2410 	struct tls_sw_context_rx *ctx = tls_sw_ctx_rx(tls_ctx);
2411 
2412 	kfree(ctx);
2413 }
2414 
2415 void tls_sw_free_resources_rx(struct sock *sk)
2416 {
2417 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2418 
2419 	tls_sw_release_resources_rx(sk);
2420 	tls_sw_free_ctx_rx(tls_ctx);
2421 }
2422 
2423 /* The work handler to transmitt the encrypted records in tx_list */
2424 static void tx_work_handler(struct work_struct *work)
2425 {
2426 	struct delayed_work *delayed_work = to_delayed_work(work);
2427 	struct tx_work *tx_work = container_of(delayed_work,
2428 					       struct tx_work, work);
2429 	struct sock *sk = tx_work->sk;
2430 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2431 	struct tls_sw_context_tx *ctx;
2432 
2433 	if (unlikely(!tls_ctx))
2434 		return;
2435 
2436 	ctx = tls_sw_ctx_tx(tls_ctx);
2437 	if (test_bit(BIT_TX_CLOSING, &ctx->tx_bitmask))
2438 		return;
2439 
2440 	if (!test_and_clear_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask))
2441 		return;
2442 
2443 	if (mutex_trylock(&tls_ctx->tx_lock)) {
2444 		lock_sock(sk);
2445 		tls_tx_records(sk, -1);
2446 		release_sock(sk);
2447 		mutex_unlock(&tls_ctx->tx_lock);
2448 	} else if (!test_and_set_bit(BIT_TX_SCHEDULED, &ctx->tx_bitmask)) {
2449 		/* Someone is holding the tx_lock, they will likely run Tx
2450 		 * and cancel the work on their way out of the lock section.
2451 		 * Schedule a long delay just in case.
2452 		 */
2453 		schedule_delayed_work(&ctx->tx_work.work, msecs_to_jiffies(10));
2454 	}
2455 }
2456 
2457 static bool tls_is_tx_ready(struct tls_sw_context_tx *ctx)
2458 {
2459 	struct tls_rec *rec;
2460 
2461 	rec = list_first_entry_or_null(&ctx->tx_list, struct tls_rec, list);
2462 	if (!rec)
2463 		return false;
2464 
2465 	return READ_ONCE(rec->tx_ready);
2466 }
2467 
2468 void tls_sw_write_space(struct sock *sk, struct tls_context *ctx)
2469 {
2470 	struct tls_sw_context_tx *tx_ctx = tls_sw_ctx_tx(ctx);
2471 
2472 	/* Schedule the transmission if tx list is ready */
2473 	if (tls_is_tx_ready(tx_ctx) &&
2474 	    !test_and_set_bit(BIT_TX_SCHEDULED, &tx_ctx->tx_bitmask))
2475 		schedule_delayed_work(&tx_ctx->tx_work.work, 0);
2476 }
2477 
2478 void tls_sw_strparser_arm(struct sock *sk, struct tls_context *tls_ctx)
2479 {
2480 	struct tls_sw_context_rx *rx_ctx = tls_sw_ctx_rx(tls_ctx);
2481 
2482 	write_lock_bh(&sk->sk_callback_lock);
2483 	rx_ctx->saved_data_ready = sk->sk_data_ready;
2484 	sk->sk_data_ready = tls_data_ready;
2485 	write_unlock_bh(&sk->sk_callback_lock);
2486 }
2487 
2488 void tls_update_rx_zc_capable(struct tls_context *tls_ctx)
2489 {
2490 	struct tls_sw_context_rx *rx_ctx = tls_sw_ctx_rx(tls_ctx);
2491 
2492 	rx_ctx->zc_capable = tls_ctx->rx_no_pad ||
2493 		tls_ctx->prot_info.version != TLS_1_3_VERSION;
2494 }
2495 
2496 int tls_set_sw_offload(struct sock *sk, struct tls_context *ctx, int tx)
2497 {
2498 	struct tls_context *tls_ctx = tls_get_ctx(sk);
2499 	struct tls_prot_info *prot = &tls_ctx->prot_info;
2500 	struct tls_crypto_info *crypto_info;
2501 	struct tls_sw_context_tx *sw_ctx_tx = NULL;
2502 	struct tls_sw_context_rx *sw_ctx_rx = NULL;
2503 	struct cipher_context *cctx;
2504 	struct crypto_aead **aead;
2505 	u16 nonce_size, tag_size, iv_size, rec_seq_size, salt_size;
2506 	struct crypto_tfm *tfm;
2507 	char *iv, *rec_seq, *key, *salt, *cipher_name;
2508 	size_t keysize;
2509 	int rc = 0;
2510 
2511 	if (!ctx) {
2512 		rc = -EINVAL;
2513 		goto out;
2514 	}
2515 
2516 	if (tx) {
2517 		if (!ctx->priv_ctx_tx) {
2518 			sw_ctx_tx = kzalloc(sizeof(*sw_ctx_tx), GFP_KERNEL);
2519 			if (!sw_ctx_tx) {
2520 				rc = -ENOMEM;
2521 				goto out;
2522 			}
2523 			ctx->priv_ctx_tx = sw_ctx_tx;
2524 		} else {
2525 			sw_ctx_tx =
2526 				(struct tls_sw_context_tx *)ctx->priv_ctx_tx;
2527 		}
2528 	} else {
2529 		if (!ctx->priv_ctx_rx) {
2530 			sw_ctx_rx = kzalloc(sizeof(*sw_ctx_rx), GFP_KERNEL);
2531 			if (!sw_ctx_rx) {
2532 				rc = -ENOMEM;
2533 				goto out;
2534 			}
2535 			ctx->priv_ctx_rx = sw_ctx_rx;
2536 		} else {
2537 			sw_ctx_rx =
2538 				(struct tls_sw_context_rx *)ctx->priv_ctx_rx;
2539 		}
2540 	}
2541 
2542 	if (tx) {
2543 		crypto_init_wait(&sw_ctx_tx->async_wait);
2544 		spin_lock_init(&sw_ctx_tx->encrypt_compl_lock);
2545 		crypto_info = &ctx->crypto_send.info;
2546 		cctx = &ctx->tx;
2547 		aead = &sw_ctx_tx->aead_send;
2548 		INIT_LIST_HEAD(&sw_ctx_tx->tx_list);
2549 		INIT_DELAYED_WORK(&sw_ctx_tx->tx_work.work, tx_work_handler);
2550 		sw_ctx_tx->tx_work.sk = sk;
2551 	} else {
2552 		crypto_init_wait(&sw_ctx_rx->async_wait);
2553 		spin_lock_init(&sw_ctx_rx->decrypt_compl_lock);
2554 		init_waitqueue_head(&sw_ctx_rx->wq);
2555 		crypto_info = &ctx->crypto_recv.info;
2556 		cctx = &ctx->rx;
2557 		skb_queue_head_init(&sw_ctx_rx->rx_list);
2558 		skb_queue_head_init(&sw_ctx_rx->async_hold);
2559 		aead = &sw_ctx_rx->aead_recv;
2560 	}
2561 
2562 	switch (crypto_info->cipher_type) {
2563 	case TLS_CIPHER_AES_GCM_128: {
2564 		struct tls12_crypto_info_aes_gcm_128 *gcm_128_info;
2565 
2566 		gcm_128_info = (void *)crypto_info;
2567 		nonce_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
2568 		tag_size = TLS_CIPHER_AES_GCM_128_TAG_SIZE;
2569 		iv_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
2570 		iv = gcm_128_info->iv;
2571 		rec_seq_size = TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE;
2572 		rec_seq = gcm_128_info->rec_seq;
2573 		keysize = TLS_CIPHER_AES_GCM_128_KEY_SIZE;
2574 		key = gcm_128_info->key;
2575 		salt = gcm_128_info->salt;
2576 		salt_size = TLS_CIPHER_AES_GCM_128_SALT_SIZE;
2577 		cipher_name = "gcm(aes)";
2578 		break;
2579 	}
2580 	case TLS_CIPHER_AES_GCM_256: {
2581 		struct tls12_crypto_info_aes_gcm_256 *gcm_256_info;
2582 
2583 		gcm_256_info = (void *)crypto_info;
2584 		nonce_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
2585 		tag_size = TLS_CIPHER_AES_GCM_256_TAG_SIZE;
2586 		iv_size = TLS_CIPHER_AES_GCM_256_IV_SIZE;
2587 		iv = gcm_256_info->iv;
2588 		rec_seq_size = TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE;
2589 		rec_seq = gcm_256_info->rec_seq;
2590 		keysize = TLS_CIPHER_AES_GCM_256_KEY_SIZE;
2591 		key = gcm_256_info->key;
2592 		salt = gcm_256_info->salt;
2593 		salt_size = TLS_CIPHER_AES_GCM_256_SALT_SIZE;
2594 		cipher_name = "gcm(aes)";
2595 		break;
2596 	}
2597 	case TLS_CIPHER_AES_CCM_128: {
2598 		struct tls12_crypto_info_aes_ccm_128 *ccm_128_info;
2599 
2600 		ccm_128_info = (void *)crypto_info;
2601 		nonce_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
2602 		tag_size = TLS_CIPHER_AES_CCM_128_TAG_SIZE;
2603 		iv_size = TLS_CIPHER_AES_CCM_128_IV_SIZE;
2604 		iv = ccm_128_info->iv;
2605 		rec_seq_size = TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE;
2606 		rec_seq = ccm_128_info->rec_seq;
2607 		keysize = TLS_CIPHER_AES_CCM_128_KEY_SIZE;
2608 		key = ccm_128_info->key;
2609 		salt = ccm_128_info->salt;
2610 		salt_size = TLS_CIPHER_AES_CCM_128_SALT_SIZE;
2611 		cipher_name = "ccm(aes)";
2612 		break;
2613 	}
2614 	case TLS_CIPHER_CHACHA20_POLY1305: {
2615 		struct tls12_crypto_info_chacha20_poly1305 *chacha20_poly1305_info;
2616 
2617 		chacha20_poly1305_info = (void *)crypto_info;
2618 		nonce_size = 0;
2619 		tag_size = TLS_CIPHER_CHACHA20_POLY1305_TAG_SIZE;
2620 		iv_size = TLS_CIPHER_CHACHA20_POLY1305_IV_SIZE;
2621 		iv = chacha20_poly1305_info->iv;
2622 		rec_seq_size = TLS_CIPHER_CHACHA20_POLY1305_REC_SEQ_SIZE;
2623 		rec_seq = chacha20_poly1305_info->rec_seq;
2624 		keysize = TLS_CIPHER_CHACHA20_POLY1305_KEY_SIZE;
2625 		key = chacha20_poly1305_info->key;
2626 		salt = chacha20_poly1305_info->salt;
2627 		salt_size = TLS_CIPHER_CHACHA20_POLY1305_SALT_SIZE;
2628 		cipher_name = "rfc7539(chacha20,poly1305)";
2629 		break;
2630 	}
2631 	case TLS_CIPHER_SM4_GCM: {
2632 		struct tls12_crypto_info_sm4_gcm *sm4_gcm_info;
2633 
2634 		sm4_gcm_info = (void *)crypto_info;
2635 		nonce_size = TLS_CIPHER_SM4_GCM_IV_SIZE;
2636 		tag_size = TLS_CIPHER_SM4_GCM_TAG_SIZE;
2637 		iv_size = TLS_CIPHER_SM4_GCM_IV_SIZE;
2638 		iv = sm4_gcm_info->iv;
2639 		rec_seq_size = TLS_CIPHER_SM4_GCM_REC_SEQ_SIZE;
2640 		rec_seq = sm4_gcm_info->rec_seq;
2641 		keysize = TLS_CIPHER_SM4_GCM_KEY_SIZE;
2642 		key = sm4_gcm_info->key;
2643 		salt = sm4_gcm_info->salt;
2644 		salt_size = TLS_CIPHER_SM4_GCM_SALT_SIZE;
2645 		cipher_name = "gcm(sm4)";
2646 		break;
2647 	}
2648 	case TLS_CIPHER_SM4_CCM: {
2649 		struct tls12_crypto_info_sm4_ccm *sm4_ccm_info;
2650 
2651 		sm4_ccm_info = (void *)crypto_info;
2652 		nonce_size = TLS_CIPHER_SM4_CCM_IV_SIZE;
2653 		tag_size = TLS_CIPHER_SM4_CCM_TAG_SIZE;
2654 		iv_size = TLS_CIPHER_SM4_CCM_IV_SIZE;
2655 		iv = sm4_ccm_info->iv;
2656 		rec_seq_size = TLS_CIPHER_SM4_CCM_REC_SEQ_SIZE;
2657 		rec_seq = sm4_ccm_info->rec_seq;
2658 		keysize = TLS_CIPHER_SM4_CCM_KEY_SIZE;
2659 		key = sm4_ccm_info->key;
2660 		salt = sm4_ccm_info->salt;
2661 		salt_size = TLS_CIPHER_SM4_CCM_SALT_SIZE;
2662 		cipher_name = "ccm(sm4)";
2663 		break;
2664 	}
2665 	case TLS_CIPHER_ARIA_GCM_128: {
2666 		struct tls12_crypto_info_aria_gcm_128 *aria_gcm_128_info;
2667 
2668 		aria_gcm_128_info = (void *)crypto_info;
2669 		nonce_size = TLS_CIPHER_ARIA_GCM_128_IV_SIZE;
2670 		tag_size = TLS_CIPHER_ARIA_GCM_128_TAG_SIZE;
2671 		iv_size = TLS_CIPHER_ARIA_GCM_128_IV_SIZE;
2672 		iv = aria_gcm_128_info->iv;
2673 		rec_seq_size = TLS_CIPHER_ARIA_GCM_128_REC_SEQ_SIZE;
2674 		rec_seq = aria_gcm_128_info->rec_seq;
2675 		keysize = TLS_CIPHER_ARIA_GCM_128_KEY_SIZE;
2676 		key = aria_gcm_128_info->key;
2677 		salt = aria_gcm_128_info->salt;
2678 		salt_size = TLS_CIPHER_ARIA_GCM_128_SALT_SIZE;
2679 		cipher_name = "gcm(aria)";
2680 		break;
2681 	}
2682 	case TLS_CIPHER_ARIA_GCM_256: {
2683 		struct tls12_crypto_info_aria_gcm_256 *gcm_256_info;
2684 
2685 		gcm_256_info = (void *)crypto_info;
2686 		nonce_size = TLS_CIPHER_ARIA_GCM_256_IV_SIZE;
2687 		tag_size = TLS_CIPHER_ARIA_GCM_256_TAG_SIZE;
2688 		iv_size = TLS_CIPHER_ARIA_GCM_256_IV_SIZE;
2689 		iv = gcm_256_info->iv;
2690 		rec_seq_size = TLS_CIPHER_ARIA_GCM_256_REC_SEQ_SIZE;
2691 		rec_seq = gcm_256_info->rec_seq;
2692 		keysize = TLS_CIPHER_ARIA_GCM_256_KEY_SIZE;
2693 		key = gcm_256_info->key;
2694 		salt = gcm_256_info->salt;
2695 		salt_size = TLS_CIPHER_ARIA_GCM_256_SALT_SIZE;
2696 		cipher_name = "gcm(aria)";
2697 		break;
2698 	}
2699 	default:
2700 		rc = -EINVAL;
2701 		goto free_priv;
2702 	}
2703 
2704 	if (crypto_info->version == TLS_1_3_VERSION) {
2705 		nonce_size = 0;
2706 		prot->aad_size = TLS_HEADER_SIZE;
2707 		prot->tail_size = 1;
2708 	} else {
2709 		prot->aad_size = TLS_AAD_SPACE_SIZE;
2710 		prot->tail_size = 0;
2711 	}
2712 
2713 	/* Sanity-check the sizes for stack allocations. */
2714 	if (iv_size > MAX_IV_SIZE || nonce_size > MAX_IV_SIZE ||
2715 	    rec_seq_size > TLS_MAX_REC_SEQ_SIZE || tag_size != TLS_TAG_SIZE ||
2716 	    prot->aad_size > TLS_MAX_AAD_SIZE) {
2717 		rc = -EINVAL;
2718 		goto free_priv;
2719 	}
2720 
2721 	prot->version = crypto_info->version;
2722 	prot->cipher_type = crypto_info->cipher_type;
2723 	prot->prepend_size = TLS_HEADER_SIZE + nonce_size;
2724 	prot->tag_size = tag_size;
2725 	prot->overhead_size = prot->prepend_size +
2726 			      prot->tag_size + prot->tail_size;
2727 	prot->iv_size = iv_size;
2728 	prot->salt_size = salt_size;
2729 	cctx->iv = kmalloc(iv_size + salt_size, GFP_KERNEL);
2730 	if (!cctx->iv) {
2731 		rc = -ENOMEM;
2732 		goto free_priv;
2733 	}
2734 	/* Note: 128 & 256 bit salt are the same size */
2735 	prot->rec_seq_size = rec_seq_size;
2736 	memcpy(cctx->iv, salt, salt_size);
2737 	memcpy(cctx->iv + salt_size, iv, iv_size);
2738 	cctx->rec_seq = kmemdup(rec_seq, rec_seq_size, GFP_KERNEL);
2739 	if (!cctx->rec_seq) {
2740 		rc = -ENOMEM;
2741 		goto free_iv;
2742 	}
2743 
2744 	if (!*aead) {
2745 		*aead = crypto_alloc_aead(cipher_name, 0, 0);
2746 		if (IS_ERR(*aead)) {
2747 			rc = PTR_ERR(*aead);
2748 			*aead = NULL;
2749 			goto free_rec_seq;
2750 		}
2751 	}
2752 
2753 	ctx->push_pending_record = tls_sw_push_pending_record;
2754 
2755 	rc = crypto_aead_setkey(*aead, key, keysize);
2756 
2757 	if (rc)
2758 		goto free_aead;
2759 
2760 	rc = crypto_aead_setauthsize(*aead, prot->tag_size);
2761 	if (rc)
2762 		goto free_aead;
2763 
2764 	if (sw_ctx_rx) {
2765 		tfm = crypto_aead_tfm(sw_ctx_rx->aead_recv);
2766 
2767 		tls_update_rx_zc_capable(ctx);
2768 		sw_ctx_rx->async_capable =
2769 			crypto_info->version != TLS_1_3_VERSION &&
2770 			!!(tfm->__crt_alg->cra_flags & CRYPTO_ALG_ASYNC);
2771 
2772 		rc = tls_strp_init(&sw_ctx_rx->strp, sk);
2773 		if (rc)
2774 			goto free_aead;
2775 	}
2776 
2777 	goto out;
2778 
2779 free_aead:
2780 	crypto_free_aead(*aead);
2781 	*aead = NULL;
2782 free_rec_seq:
2783 	kfree(cctx->rec_seq);
2784 	cctx->rec_seq = NULL;
2785 free_iv:
2786 	kfree(cctx->iv);
2787 	cctx->iv = NULL;
2788 free_priv:
2789 	if (tx) {
2790 		kfree(ctx->priv_ctx_tx);
2791 		ctx->priv_ctx_tx = NULL;
2792 	} else {
2793 		kfree(ctx->priv_ctx_rx);
2794 		ctx->priv_ctx_rx = NULL;
2795 	}
2796 out:
2797 	return rc;
2798 }
2799