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