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