xref: /openbmc/linux/net/tls/tls_device.c (revision 18da174d)
1 /* Copyright (c) 2018, Mellanox Technologies All rights reserved.
2  *
3  * This software is available to you under a choice of one of two
4  * licenses.  You may choose to be licensed under the terms of the GNU
5  * General Public License (GPL) Version 2, available from the file
6  * COPYING in the main directory of this source tree, or the
7  * OpenIB.org BSD license below:
8  *
9  *     Redistribution and use in source and binary forms, with or
10  *     without modification, are permitted provided that the following
11  *     conditions are met:
12  *
13  *      - Redistributions of source code must retain the above
14  *        copyright notice, this list of conditions and the following
15  *        disclaimer.
16  *
17  *      - Redistributions in binary form must reproduce the above
18  *        copyright notice, this list of conditions and the following
19  *        disclaimer in the documentation and/or other materials
20  *        provided with the distribution.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
26  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
27  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
28  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29  * SOFTWARE.
30  */
31 
32 #include <crypto/aead.h>
33 #include <linux/highmem.h>
34 #include <linux/module.h>
35 #include <linux/netdevice.h>
36 #include <net/dst.h>
37 #include <net/inet_connection_sock.h>
38 #include <net/tcp.h>
39 #include <net/tls.h>
40 
41 #include "tls.h"
42 #include "trace.h"
43 
44 /* device_offload_lock is used to synchronize tls_dev_add
45  * against NETDEV_DOWN notifications.
46  */
47 static DECLARE_RWSEM(device_offload_lock);
48 
49 static struct workqueue_struct *destruct_wq __read_mostly;
50 
51 static LIST_HEAD(tls_device_list);
52 static LIST_HEAD(tls_device_down_list);
53 static DEFINE_SPINLOCK(tls_device_lock);
54 
55 static void tls_device_free_ctx(struct tls_context *ctx)
56 {
57 	if (ctx->tx_conf == TLS_HW) {
58 		kfree(tls_offload_ctx_tx(ctx));
59 		kfree(ctx->tx.rec_seq);
60 		kfree(ctx->tx.iv);
61 	}
62 
63 	if (ctx->rx_conf == TLS_HW)
64 		kfree(tls_offload_ctx_rx(ctx));
65 
66 	tls_ctx_free(NULL, ctx);
67 }
68 
69 static void tls_device_tx_del_task(struct work_struct *work)
70 {
71 	struct tls_offload_context_tx *offload_ctx =
72 		container_of(work, struct tls_offload_context_tx, destruct_work);
73 	struct tls_context *ctx = offload_ctx->ctx;
74 	struct net_device *netdev;
75 
76 	/* Safe, because this is the destroy flow, refcount is 0, so
77 	 * tls_device_down can't store this field in parallel.
78 	 */
79 	netdev = rcu_dereference_protected(ctx->netdev,
80 					   !refcount_read(&ctx->refcount));
81 
82 	netdev->tlsdev_ops->tls_dev_del(netdev, ctx, TLS_OFFLOAD_CTX_DIR_TX);
83 	dev_put(netdev);
84 	ctx->netdev = NULL;
85 	tls_device_free_ctx(ctx);
86 }
87 
88 static void tls_device_queue_ctx_destruction(struct tls_context *ctx)
89 {
90 	struct net_device *netdev;
91 	unsigned long flags;
92 	bool async_cleanup;
93 
94 	spin_lock_irqsave(&tls_device_lock, flags);
95 	if (unlikely(!refcount_dec_and_test(&ctx->refcount))) {
96 		spin_unlock_irqrestore(&tls_device_lock, flags);
97 		return;
98 	}
99 
100 	list_del(&ctx->list); /* Remove from tls_device_list / tls_device_down_list */
101 
102 	/* Safe, because this is the destroy flow, refcount is 0, so
103 	 * tls_device_down can't store this field in parallel.
104 	 */
105 	netdev = rcu_dereference_protected(ctx->netdev,
106 					   !refcount_read(&ctx->refcount));
107 
108 	async_cleanup = netdev && ctx->tx_conf == TLS_HW;
109 	if (async_cleanup) {
110 		struct tls_offload_context_tx *offload_ctx = tls_offload_ctx_tx(ctx);
111 
112 		/* queue_work inside the spinlock
113 		 * to make sure tls_device_down waits for that work.
114 		 */
115 		queue_work(destruct_wq, &offload_ctx->destruct_work);
116 	}
117 	spin_unlock_irqrestore(&tls_device_lock, flags);
118 
119 	if (!async_cleanup)
120 		tls_device_free_ctx(ctx);
121 }
122 
123 /* We assume that the socket is already connected */
124 static struct net_device *get_netdev_for_sock(struct sock *sk)
125 {
126 	struct dst_entry *dst = sk_dst_get(sk);
127 	struct net_device *netdev = NULL;
128 
129 	if (likely(dst)) {
130 		netdev = netdev_sk_get_lowest_dev(dst->dev, sk);
131 		dev_hold(netdev);
132 	}
133 
134 	dst_release(dst);
135 
136 	return netdev;
137 }
138 
139 static void destroy_record(struct tls_record_info *record)
140 {
141 	int i;
142 
143 	for (i = 0; i < record->num_frags; i++)
144 		__skb_frag_unref(&record->frags[i], false);
145 	kfree(record);
146 }
147 
148 static void delete_all_records(struct tls_offload_context_tx *offload_ctx)
149 {
150 	struct tls_record_info *info, *temp;
151 
152 	list_for_each_entry_safe(info, temp, &offload_ctx->records_list, list) {
153 		list_del(&info->list);
154 		destroy_record(info);
155 	}
156 
157 	offload_ctx->retransmit_hint = NULL;
158 }
159 
160 static void tls_icsk_clean_acked(struct sock *sk, u32 acked_seq)
161 {
162 	struct tls_context *tls_ctx = tls_get_ctx(sk);
163 	struct tls_record_info *info, *temp;
164 	struct tls_offload_context_tx *ctx;
165 	u64 deleted_records = 0;
166 	unsigned long flags;
167 
168 	if (!tls_ctx)
169 		return;
170 
171 	ctx = tls_offload_ctx_tx(tls_ctx);
172 
173 	spin_lock_irqsave(&ctx->lock, flags);
174 	info = ctx->retransmit_hint;
175 	if (info && !before(acked_seq, info->end_seq))
176 		ctx->retransmit_hint = NULL;
177 
178 	list_for_each_entry_safe(info, temp, &ctx->records_list, list) {
179 		if (before(acked_seq, info->end_seq))
180 			break;
181 		list_del(&info->list);
182 
183 		destroy_record(info);
184 		deleted_records++;
185 	}
186 
187 	ctx->unacked_record_sn += deleted_records;
188 	spin_unlock_irqrestore(&ctx->lock, flags);
189 }
190 
191 /* At this point, there should be no references on this
192  * socket and no in-flight SKBs associated with this
193  * socket, so it is safe to free all the resources.
194  */
195 void tls_device_sk_destruct(struct sock *sk)
196 {
197 	struct tls_context *tls_ctx = tls_get_ctx(sk);
198 	struct tls_offload_context_tx *ctx = tls_offload_ctx_tx(tls_ctx);
199 
200 	tls_ctx->sk_destruct(sk);
201 
202 	if (tls_ctx->tx_conf == TLS_HW) {
203 		if (ctx->open_record)
204 			destroy_record(ctx->open_record);
205 		delete_all_records(ctx);
206 		crypto_free_aead(ctx->aead_send);
207 		clean_acked_data_disable(inet_csk(sk));
208 	}
209 
210 	tls_device_queue_ctx_destruction(tls_ctx);
211 }
212 EXPORT_SYMBOL_GPL(tls_device_sk_destruct);
213 
214 void tls_device_free_resources_tx(struct sock *sk)
215 {
216 	struct tls_context *tls_ctx = tls_get_ctx(sk);
217 
218 	tls_free_partial_record(sk, tls_ctx);
219 }
220 
221 void tls_offload_tx_resync_request(struct sock *sk, u32 got_seq, u32 exp_seq)
222 {
223 	struct tls_context *tls_ctx = tls_get_ctx(sk);
224 
225 	trace_tls_device_tx_resync_req(sk, got_seq, exp_seq);
226 	WARN_ON(test_and_set_bit(TLS_TX_SYNC_SCHED, &tls_ctx->flags));
227 }
228 EXPORT_SYMBOL_GPL(tls_offload_tx_resync_request);
229 
230 static void tls_device_resync_tx(struct sock *sk, struct tls_context *tls_ctx,
231 				 u32 seq)
232 {
233 	struct net_device *netdev;
234 	struct sk_buff *skb;
235 	int err = 0;
236 	u8 *rcd_sn;
237 
238 	skb = tcp_write_queue_tail(sk);
239 	if (skb)
240 		TCP_SKB_CB(skb)->eor = 1;
241 
242 	rcd_sn = tls_ctx->tx.rec_seq;
243 
244 	trace_tls_device_tx_resync_send(sk, seq, rcd_sn);
245 	down_read(&device_offload_lock);
246 	netdev = rcu_dereference_protected(tls_ctx->netdev,
247 					   lockdep_is_held(&device_offload_lock));
248 	if (netdev)
249 		err = netdev->tlsdev_ops->tls_dev_resync(netdev, sk, seq,
250 							 rcd_sn,
251 							 TLS_OFFLOAD_CTX_DIR_TX);
252 	up_read(&device_offload_lock);
253 	if (err)
254 		return;
255 
256 	clear_bit_unlock(TLS_TX_SYNC_SCHED, &tls_ctx->flags);
257 }
258 
259 static void tls_append_frag(struct tls_record_info *record,
260 			    struct page_frag *pfrag,
261 			    int size)
262 {
263 	skb_frag_t *frag;
264 
265 	frag = &record->frags[record->num_frags - 1];
266 	if (skb_frag_page(frag) == pfrag->page &&
267 	    skb_frag_off(frag) + skb_frag_size(frag) == pfrag->offset) {
268 		skb_frag_size_add(frag, size);
269 	} else {
270 		++frag;
271 		skb_frag_fill_page_desc(frag, pfrag->page, pfrag->offset,
272 					size);
273 		++record->num_frags;
274 		get_page(pfrag->page);
275 	}
276 
277 	pfrag->offset += size;
278 	record->len += size;
279 }
280 
281 static int tls_push_record(struct sock *sk,
282 			   struct tls_context *ctx,
283 			   struct tls_offload_context_tx *offload_ctx,
284 			   struct tls_record_info *record,
285 			   int flags)
286 {
287 	struct tls_prot_info *prot = &ctx->prot_info;
288 	struct tcp_sock *tp = tcp_sk(sk);
289 	skb_frag_t *frag;
290 	int i;
291 
292 	record->end_seq = tp->write_seq + record->len;
293 	list_add_tail_rcu(&record->list, &offload_ctx->records_list);
294 	offload_ctx->open_record = NULL;
295 
296 	if (test_bit(TLS_TX_SYNC_SCHED, &ctx->flags))
297 		tls_device_resync_tx(sk, ctx, tp->write_seq);
298 
299 	tls_advance_record_sn(sk, prot, &ctx->tx);
300 
301 	for (i = 0; i < record->num_frags; i++) {
302 		frag = &record->frags[i];
303 		sg_unmark_end(&offload_ctx->sg_tx_data[i]);
304 		sg_set_page(&offload_ctx->sg_tx_data[i], skb_frag_page(frag),
305 			    skb_frag_size(frag), skb_frag_off(frag));
306 		sk_mem_charge(sk, skb_frag_size(frag));
307 		get_page(skb_frag_page(frag));
308 	}
309 	sg_mark_end(&offload_ctx->sg_tx_data[record->num_frags - 1]);
310 
311 	/* all ready, send */
312 	return tls_push_sg(sk, ctx, offload_ctx->sg_tx_data, 0, flags);
313 }
314 
315 static int tls_device_record_close(struct sock *sk,
316 				   struct tls_context *ctx,
317 				   struct tls_record_info *record,
318 				   struct page_frag *pfrag,
319 				   unsigned char record_type)
320 {
321 	struct tls_prot_info *prot = &ctx->prot_info;
322 	int ret;
323 
324 	/* append tag
325 	 * device will fill in the tag, we just need to append a placeholder
326 	 * use socket memory to improve coalescing (re-using a single buffer
327 	 * increases frag count)
328 	 * if we can't allocate memory now, steal some back from data
329 	 */
330 	if (likely(skb_page_frag_refill(prot->tag_size, pfrag,
331 					sk->sk_allocation))) {
332 		ret = 0;
333 		tls_append_frag(record, pfrag, prot->tag_size);
334 	} else {
335 		ret = prot->tag_size;
336 		if (record->len <= prot->overhead_size)
337 			return -ENOMEM;
338 	}
339 
340 	/* fill prepend */
341 	tls_fill_prepend(ctx, skb_frag_address(&record->frags[0]),
342 			 record->len - prot->overhead_size,
343 			 record_type);
344 	return ret;
345 }
346 
347 static int tls_create_new_record(struct tls_offload_context_tx *offload_ctx,
348 				 struct page_frag *pfrag,
349 				 size_t prepend_size)
350 {
351 	struct tls_record_info *record;
352 	skb_frag_t *frag;
353 
354 	record = kmalloc(sizeof(*record), GFP_KERNEL);
355 	if (!record)
356 		return -ENOMEM;
357 
358 	frag = &record->frags[0];
359 	skb_frag_fill_page_desc(frag, pfrag->page, pfrag->offset,
360 				prepend_size);
361 
362 	get_page(pfrag->page);
363 	pfrag->offset += prepend_size;
364 
365 	record->num_frags = 1;
366 	record->len = prepend_size;
367 	offload_ctx->open_record = record;
368 	return 0;
369 }
370 
371 static int tls_do_allocation(struct sock *sk,
372 			     struct tls_offload_context_tx *offload_ctx,
373 			     struct page_frag *pfrag,
374 			     size_t prepend_size)
375 {
376 	int ret;
377 
378 	if (!offload_ctx->open_record) {
379 		if (unlikely(!skb_page_frag_refill(prepend_size, pfrag,
380 						   sk->sk_allocation))) {
381 			READ_ONCE(sk->sk_prot)->enter_memory_pressure(sk);
382 			sk_stream_moderate_sndbuf(sk);
383 			return -ENOMEM;
384 		}
385 
386 		ret = tls_create_new_record(offload_ctx, pfrag, prepend_size);
387 		if (ret)
388 			return ret;
389 
390 		if (pfrag->size > pfrag->offset)
391 			return 0;
392 	}
393 
394 	if (!sk_page_frag_refill(sk, pfrag))
395 		return -ENOMEM;
396 
397 	return 0;
398 }
399 
400 static int tls_device_copy_data(void *addr, size_t bytes, struct iov_iter *i)
401 {
402 	size_t pre_copy, nocache;
403 
404 	pre_copy = ~((unsigned long)addr - 1) & (SMP_CACHE_BYTES - 1);
405 	if (pre_copy) {
406 		pre_copy = min(pre_copy, bytes);
407 		if (copy_from_iter(addr, pre_copy, i) != pre_copy)
408 			return -EFAULT;
409 		bytes -= pre_copy;
410 		addr += pre_copy;
411 	}
412 
413 	nocache = round_down(bytes, SMP_CACHE_BYTES);
414 	if (copy_from_iter_nocache(addr, nocache, i) != nocache)
415 		return -EFAULT;
416 	bytes -= nocache;
417 	addr += nocache;
418 
419 	if (bytes && copy_from_iter(addr, bytes, i) != bytes)
420 		return -EFAULT;
421 
422 	return 0;
423 }
424 
425 static int tls_push_data(struct sock *sk,
426 			 struct iov_iter *iter,
427 			 size_t size, int flags,
428 			 unsigned char record_type)
429 {
430 	struct tls_context *tls_ctx = tls_get_ctx(sk);
431 	struct tls_prot_info *prot = &tls_ctx->prot_info;
432 	struct tls_offload_context_tx *ctx = tls_offload_ctx_tx(tls_ctx);
433 	struct tls_record_info *record;
434 	int tls_push_record_flags;
435 	struct page_frag *pfrag;
436 	size_t orig_size = size;
437 	u32 max_open_record_len;
438 	bool more = false;
439 	bool done = false;
440 	int copy, rc = 0;
441 	long timeo;
442 
443 	if (flags &
444 	    ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL | MSG_SENDPAGE_NOTLAST |
445 	      MSG_SPLICE_PAGES))
446 		return -EOPNOTSUPP;
447 
448 	if (unlikely(sk->sk_err))
449 		return -sk->sk_err;
450 
451 	flags |= MSG_SENDPAGE_DECRYPTED;
452 	tls_push_record_flags = flags | MSG_SENDPAGE_NOTLAST;
453 
454 	timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
455 	if (tls_is_partially_sent_record(tls_ctx)) {
456 		rc = tls_push_partial_record(sk, tls_ctx, flags);
457 		if (rc < 0)
458 			return rc;
459 	}
460 
461 	pfrag = sk_page_frag(sk);
462 
463 	/* TLS_HEADER_SIZE is not counted as part of the TLS record, and
464 	 * we need to leave room for an authentication tag.
465 	 */
466 	max_open_record_len = TLS_MAX_PAYLOAD_SIZE +
467 			      prot->prepend_size;
468 	do {
469 		rc = tls_do_allocation(sk, ctx, pfrag, prot->prepend_size);
470 		if (unlikely(rc)) {
471 			rc = sk_stream_wait_memory(sk, &timeo);
472 			if (!rc)
473 				continue;
474 
475 			record = ctx->open_record;
476 			if (!record)
477 				break;
478 handle_error:
479 			if (record_type != TLS_RECORD_TYPE_DATA) {
480 				/* avoid sending partial
481 				 * record with type !=
482 				 * application_data
483 				 */
484 				size = orig_size;
485 				destroy_record(record);
486 				ctx->open_record = NULL;
487 			} else if (record->len > prot->prepend_size) {
488 				goto last_record;
489 			}
490 
491 			break;
492 		}
493 
494 		record = ctx->open_record;
495 
496 		copy = min_t(size_t, size, max_open_record_len - record->len);
497 		if (copy && (flags & MSG_SPLICE_PAGES)) {
498 			struct page_frag zc_pfrag;
499 			struct page **pages = &zc_pfrag.page;
500 			size_t off;
501 
502 			rc = iov_iter_extract_pages(iter, &pages,
503 						    copy, 1, 0, &off);
504 			if (rc <= 0) {
505 				if (rc == 0)
506 					rc = -EIO;
507 				goto handle_error;
508 			}
509 			copy = rc;
510 
511 			if (WARN_ON_ONCE(!sendpage_ok(zc_pfrag.page))) {
512 				iov_iter_revert(iter, copy);
513 				rc = -EIO;
514 				goto handle_error;
515 			}
516 
517 			zc_pfrag.offset = off;
518 			zc_pfrag.size = copy;
519 			tls_append_frag(record, &zc_pfrag, copy);
520 		} else if (copy) {
521 			copy = min_t(size_t, copy, pfrag->size - pfrag->offset);
522 
523 			rc = tls_device_copy_data(page_address(pfrag->page) +
524 						  pfrag->offset, copy,
525 						  iter);
526 			if (rc)
527 				goto handle_error;
528 			tls_append_frag(record, pfrag, copy);
529 		}
530 
531 		size -= copy;
532 		if (!size) {
533 last_record:
534 			tls_push_record_flags = flags;
535 			if (flags & (MSG_SENDPAGE_NOTLAST | MSG_MORE)) {
536 				more = true;
537 				break;
538 			}
539 
540 			done = true;
541 		}
542 
543 		if (done || record->len >= max_open_record_len ||
544 		    (record->num_frags >= MAX_SKB_FRAGS - 1)) {
545 			rc = tls_device_record_close(sk, tls_ctx, record,
546 						     pfrag, record_type);
547 			if (rc) {
548 				if (rc > 0) {
549 					size += rc;
550 				} else {
551 					size = orig_size;
552 					destroy_record(record);
553 					ctx->open_record = NULL;
554 					break;
555 				}
556 			}
557 
558 			rc = tls_push_record(sk,
559 					     tls_ctx,
560 					     ctx,
561 					     record,
562 					     tls_push_record_flags);
563 			if (rc < 0)
564 				break;
565 		}
566 	} while (!done);
567 
568 	tls_ctx->pending_open_record_frags = more;
569 
570 	if (orig_size - size > 0)
571 		rc = orig_size - size;
572 
573 	return rc;
574 }
575 
576 int tls_device_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
577 {
578 	unsigned char record_type = TLS_RECORD_TYPE_DATA;
579 	struct tls_context *tls_ctx = tls_get_ctx(sk);
580 	int rc;
581 
582 	if (!tls_ctx->zerocopy_sendfile)
583 		msg->msg_flags &= ~MSG_SPLICE_PAGES;
584 
585 	mutex_lock(&tls_ctx->tx_lock);
586 	lock_sock(sk);
587 
588 	if (unlikely(msg->msg_controllen)) {
589 		rc = tls_process_cmsg(sk, msg, &record_type);
590 		if (rc)
591 			goto out;
592 	}
593 
594 	rc = tls_push_data(sk, &msg->msg_iter, size, msg->msg_flags,
595 			   record_type);
596 
597 out:
598 	release_sock(sk);
599 	mutex_unlock(&tls_ctx->tx_lock);
600 	return rc;
601 }
602 
603 void tls_device_splice_eof(struct socket *sock)
604 {
605 	struct sock *sk = sock->sk;
606 	struct tls_context *tls_ctx = tls_get_ctx(sk);
607 	struct iov_iter iter = {};
608 
609 	if (!tls_is_partially_sent_record(tls_ctx))
610 		return;
611 
612 	mutex_lock(&tls_ctx->tx_lock);
613 	lock_sock(sk);
614 
615 	if (tls_is_partially_sent_record(tls_ctx)) {
616 		iov_iter_bvec(&iter, ITER_SOURCE, NULL, 0, 0);
617 		tls_push_data(sk, &iter, 0, 0, TLS_RECORD_TYPE_DATA);
618 	}
619 
620 	release_sock(sk);
621 	mutex_unlock(&tls_ctx->tx_lock);
622 }
623 
624 int tls_device_sendpage(struct sock *sk, struct page *page,
625 			int offset, size_t size, int flags)
626 {
627 	struct bio_vec bvec;
628 	struct msghdr msg = { .msg_flags = flags | MSG_SPLICE_PAGES, };
629 
630 	if (flags & MSG_SENDPAGE_NOTLAST)
631 		msg.msg_flags |= MSG_MORE;
632 
633 	if (flags & MSG_OOB)
634 		return -EOPNOTSUPP;
635 
636 	bvec_set_page(&bvec, page, size, offset);
637 	iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1, size);
638 	return tls_device_sendmsg(sk, &msg, size);
639 }
640 
641 struct tls_record_info *tls_get_record(struct tls_offload_context_tx *context,
642 				       u32 seq, u64 *p_record_sn)
643 {
644 	u64 record_sn = context->hint_record_sn;
645 	struct tls_record_info *info, *last;
646 
647 	info = context->retransmit_hint;
648 	if (!info ||
649 	    before(seq, info->end_seq - info->len)) {
650 		/* if retransmit_hint is irrelevant start
651 		 * from the beginning of the list
652 		 */
653 		info = list_first_entry_or_null(&context->records_list,
654 						struct tls_record_info, list);
655 		if (!info)
656 			return NULL;
657 		/* send the start_marker record if seq number is before the
658 		 * tls offload start marker sequence number. This record is
659 		 * required to handle TCP packets which are before TLS offload
660 		 * started.
661 		 *  And if it's not start marker, look if this seq number
662 		 * belongs to the list.
663 		 */
664 		if (likely(!tls_record_is_start_marker(info))) {
665 			/* we have the first record, get the last record to see
666 			 * if this seq number belongs to the list.
667 			 */
668 			last = list_last_entry(&context->records_list,
669 					       struct tls_record_info, list);
670 
671 			if (!between(seq, tls_record_start_seq(info),
672 				     last->end_seq))
673 				return NULL;
674 		}
675 		record_sn = context->unacked_record_sn;
676 	}
677 
678 	/* We just need the _rcu for the READ_ONCE() */
679 	rcu_read_lock();
680 	list_for_each_entry_from_rcu(info, &context->records_list, list) {
681 		if (before(seq, info->end_seq)) {
682 			if (!context->retransmit_hint ||
683 			    after(info->end_seq,
684 				  context->retransmit_hint->end_seq)) {
685 				context->hint_record_sn = record_sn;
686 				context->retransmit_hint = info;
687 			}
688 			*p_record_sn = record_sn;
689 			goto exit_rcu_unlock;
690 		}
691 		record_sn++;
692 	}
693 	info = NULL;
694 
695 exit_rcu_unlock:
696 	rcu_read_unlock();
697 	return info;
698 }
699 EXPORT_SYMBOL(tls_get_record);
700 
701 static int tls_device_push_pending_record(struct sock *sk, int flags)
702 {
703 	struct iov_iter iter;
704 
705 	iov_iter_kvec(&iter, ITER_SOURCE, NULL, 0, 0);
706 	return tls_push_data(sk, &iter, 0, flags, TLS_RECORD_TYPE_DATA);
707 }
708 
709 void tls_device_write_space(struct sock *sk, struct tls_context *ctx)
710 {
711 	if (tls_is_partially_sent_record(ctx)) {
712 		gfp_t sk_allocation = sk->sk_allocation;
713 
714 		WARN_ON_ONCE(sk->sk_write_pending);
715 
716 		sk->sk_allocation = GFP_ATOMIC;
717 		tls_push_partial_record(sk, ctx,
718 					MSG_DONTWAIT | MSG_NOSIGNAL |
719 					MSG_SENDPAGE_DECRYPTED);
720 		sk->sk_allocation = sk_allocation;
721 	}
722 }
723 
724 static void tls_device_resync_rx(struct tls_context *tls_ctx,
725 				 struct sock *sk, u32 seq, u8 *rcd_sn)
726 {
727 	struct tls_offload_context_rx *rx_ctx = tls_offload_ctx_rx(tls_ctx);
728 	struct net_device *netdev;
729 
730 	trace_tls_device_rx_resync_send(sk, seq, rcd_sn, rx_ctx->resync_type);
731 	rcu_read_lock();
732 	netdev = rcu_dereference(tls_ctx->netdev);
733 	if (netdev)
734 		netdev->tlsdev_ops->tls_dev_resync(netdev, sk, seq, rcd_sn,
735 						   TLS_OFFLOAD_CTX_DIR_RX);
736 	rcu_read_unlock();
737 	TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXDEVICERESYNC);
738 }
739 
740 static bool
741 tls_device_rx_resync_async(struct tls_offload_resync_async *resync_async,
742 			   s64 resync_req, u32 *seq, u16 *rcd_delta)
743 {
744 	u32 is_async = resync_req & RESYNC_REQ_ASYNC;
745 	u32 req_seq = resync_req >> 32;
746 	u32 req_end = req_seq + ((resync_req >> 16) & 0xffff);
747 	u16 i;
748 
749 	*rcd_delta = 0;
750 
751 	if (is_async) {
752 		/* shouldn't get to wraparound:
753 		 * too long in async stage, something bad happened
754 		 */
755 		if (WARN_ON_ONCE(resync_async->rcd_delta == USHRT_MAX))
756 			return false;
757 
758 		/* asynchronous stage: log all headers seq such that
759 		 * req_seq <= seq <= end_seq, and wait for real resync request
760 		 */
761 		if (before(*seq, req_seq))
762 			return false;
763 		if (!after(*seq, req_end) &&
764 		    resync_async->loglen < TLS_DEVICE_RESYNC_ASYNC_LOGMAX)
765 			resync_async->log[resync_async->loglen++] = *seq;
766 
767 		resync_async->rcd_delta++;
768 
769 		return false;
770 	}
771 
772 	/* synchronous stage: check against the logged entries and
773 	 * proceed to check the next entries if no match was found
774 	 */
775 	for (i = 0; i < resync_async->loglen; i++)
776 		if (req_seq == resync_async->log[i] &&
777 		    atomic64_try_cmpxchg(&resync_async->req, &resync_req, 0)) {
778 			*rcd_delta = resync_async->rcd_delta - i;
779 			*seq = req_seq;
780 			resync_async->loglen = 0;
781 			resync_async->rcd_delta = 0;
782 			return true;
783 		}
784 
785 	resync_async->loglen = 0;
786 	resync_async->rcd_delta = 0;
787 
788 	if (req_seq == *seq &&
789 	    atomic64_try_cmpxchg(&resync_async->req,
790 				 &resync_req, 0))
791 		return true;
792 
793 	return false;
794 }
795 
796 void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq)
797 {
798 	struct tls_context *tls_ctx = tls_get_ctx(sk);
799 	struct tls_offload_context_rx *rx_ctx;
800 	u8 rcd_sn[TLS_MAX_REC_SEQ_SIZE];
801 	u32 sock_data, is_req_pending;
802 	struct tls_prot_info *prot;
803 	s64 resync_req;
804 	u16 rcd_delta;
805 	u32 req_seq;
806 
807 	if (tls_ctx->rx_conf != TLS_HW)
808 		return;
809 	if (unlikely(test_bit(TLS_RX_DEV_DEGRADED, &tls_ctx->flags)))
810 		return;
811 
812 	prot = &tls_ctx->prot_info;
813 	rx_ctx = tls_offload_ctx_rx(tls_ctx);
814 	memcpy(rcd_sn, tls_ctx->rx.rec_seq, prot->rec_seq_size);
815 
816 	switch (rx_ctx->resync_type) {
817 	case TLS_OFFLOAD_SYNC_TYPE_DRIVER_REQ:
818 		resync_req = atomic64_read(&rx_ctx->resync_req);
819 		req_seq = resync_req >> 32;
820 		seq += TLS_HEADER_SIZE - 1;
821 		is_req_pending = resync_req;
822 
823 		if (likely(!is_req_pending) || req_seq != seq ||
824 		    !atomic64_try_cmpxchg(&rx_ctx->resync_req, &resync_req, 0))
825 			return;
826 		break;
827 	case TLS_OFFLOAD_SYNC_TYPE_CORE_NEXT_HINT:
828 		if (likely(!rx_ctx->resync_nh_do_now))
829 			return;
830 
831 		/* head of next rec is already in, note that the sock_inq will
832 		 * include the currently parsed message when called from parser
833 		 */
834 		sock_data = tcp_inq(sk);
835 		if (sock_data > rcd_len) {
836 			trace_tls_device_rx_resync_nh_delay(sk, sock_data,
837 							    rcd_len);
838 			return;
839 		}
840 
841 		rx_ctx->resync_nh_do_now = 0;
842 		seq += rcd_len;
843 		tls_bigint_increment(rcd_sn, prot->rec_seq_size);
844 		break;
845 	case TLS_OFFLOAD_SYNC_TYPE_DRIVER_REQ_ASYNC:
846 		resync_req = atomic64_read(&rx_ctx->resync_async->req);
847 		is_req_pending = resync_req;
848 		if (likely(!is_req_pending))
849 			return;
850 
851 		if (!tls_device_rx_resync_async(rx_ctx->resync_async,
852 						resync_req, &seq, &rcd_delta))
853 			return;
854 		tls_bigint_subtract(rcd_sn, rcd_delta);
855 		break;
856 	}
857 
858 	tls_device_resync_rx(tls_ctx, sk, seq, rcd_sn);
859 }
860 
861 static void tls_device_core_ctrl_rx_resync(struct tls_context *tls_ctx,
862 					   struct tls_offload_context_rx *ctx,
863 					   struct sock *sk, struct sk_buff *skb)
864 {
865 	struct strp_msg *rxm;
866 
867 	/* device will request resyncs by itself based on stream scan */
868 	if (ctx->resync_type != TLS_OFFLOAD_SYNC_TYPE_CORE_NEXT_HINT)
869 		return;
870 	/* already scheduled */
871 	if (ctx->resync_nh_do_now)
872 		return;
873 	/* seen decrypted fragments since last fully-failed record */
874 	if (ctx->resync_nh_reset) {
875 		ctx->resync_nh_reset = 0;
876 		ctx->resync_nh.decrypted_failed = 1;
877 		ctx->resync_nh.decrypted_tgt = TLS_DEVICE_RESYNC_NH_START_IVAL;
878 		return;
879 	}
880 
881 	if (++ctx->resync_nh.decrypted_failed <= ctx->resync_nh.decrypted_tgt)
882 		return;
883 
884 	/* doing resync, bump the next target in case it fails */
885 	if (ctx->resync_nh.decrypted_tgt < TLS_DEVICE_RESYNC_NH_MAX_IVAL)
886 		ctx->resync_nh.decrypted_tgt *= 2;
887 	else
888 		ctx->resync_nh.decrypted_tgt += TLS_DEVICE_RESYNC_NH_MAX_IVAL;
889 
890 	rxm = strp_msg(skb);
891 
892 	/* head of next rec is already in, parser will sync for us */
893 	if (tcp_inq(sk) > rxm->full_len) {
894 		trace_tls_device_rx_resync_nh_schedule(sk);
895 		ctx->resync_nh_do_now = 1;
896 	} else {
897 		struct tls_prot_info *prot = &tls_ctx->prot_info;
898 		u8 rcd_sn[TLS_MAX_REC_SEQ_SIZE];
899 
900 		memcpy(rcd_sn, tls_ctx->rx.rec_seq, prot->rec_seq_size);
901 		tls_bigint_increment(rcd_sn, prot->rec_seq_size);
902 
903 		tls_device_resync_rx(tls_ctx, sk, tcp_sk(sk)->copied_seq,
904 				     rcd_sn);
905 	}
906 }
907 
908 static int
909 tls_device_reencrypt(struct sock *sk, struct tls_context *tls_ctx)
910 {
911 	struct tls_sw_context_rx *sw_ctx = tls_sw_ctx_rx(tls_ctx);
912 	const struct tls_cipher_size_desc *cipher_sz;
913 	int err, offset, copy, data_len, pos;
914 	struct sk_buff *skb, *skb_iter;
915 	struct scatterlist sg[1];
916 	struct strp_msg *rxm;
917 	char *orig_buf, *buf;
918 
919 	switch (tls_ctx->crypto_recv.info.cipher_type) {
920 	case TLS_CIPHER_AES_GCM_128:
921 	case TLS_CIPHER_AES_GCM_256:
922 		break;
923 	default:
924 		return -EINVAL;
925 	}
926 	cipher_sz = &tls_cipher_size_desc[tls_ctx->crypto_recv.info.cipher_type];
927 
928 	rxm = strp_msg(tls_strp_msg(sw_ctx));
929 	orig_buf = kmalloc(rxm->full_len + TLS_HEADER_SIZE + cipher_sz->iv,
930 			   sk->sk_allocation);
931 	if (!orig_buf)
932 		return -ENOMEM;
933 	buf = orig_buf;
934 
935 	err = tls_strp_msg_cow(sw_ctx);
936 	if (unlikely(err))
937 		goto free_buf;
938 
939 	skb = tls_strp_msg(sw_ctx);
940 	rxm = strp_msg(skb);
941 	offset = rxm->offset;
942 
943 	sg_init_table(sg, 1);
944 	sg_set_buf(&sg[0], buf,
945 		   rxm->full_len + TLS_HEADER_SIZE + cipher_sz->iv);
946 	err = skb_copy_bits(skb, offset, buf, TLS_HEADER_SIZE + cipher_sz->iv);
947 	if (err)
948 		goto free_buf;
949 
950 	/* We are interested only in the decrypted data not the auth */
951 	err = decrypt_skb(sk, sg);
952 	if (err != -EBADMSG)
953 		goto free_buf;
954 	else
955 		err = 0;
956 
957 	data_len = rxm->full_len - cipher_sz->tag;
958 
959 	if (skb_pagelen(skb) > offset) {
960 		copy = min_t(int, skb_pagelen(skb) - offset, data_len);
961 
962 		if (skb->decrypted) {
963 			err = skb_store_bits(skb, offset, buf, copy);
964 			if (err)
965 				goto free_buf;
966 		}
967 
968 		offset += copy;
969 		buf += copy;
970 	}
971 
972 	pos = skb_pagelen(skb);
973 	skb_walk_frags(skb, skb_iter) {
974 		int frag_pos;
975 
976 		/* Practically all frags must belong to msg if reencrypt
977 		 * is needed with current strparser and coalescing logic,
978 		 * but strparser may "get optimized", so let's be safe.
979 		 */
980 		if (pos + skb_iter->len <= offset)
981 			goto done_with_frag;
982 		if (pos >= data_len + rxm->offset)
983 			break;
984 
985 		frag_pos = offset - pos;
986 		copy = min_t(int, skb_iter->len - frag_pos,
987 			     data_len + rxm->offset - offset);
988 
989 		if (skb_iter->decrypted) {
990 			err = skb_store_bits(skb_iter, frag_pos, buf, copy);
991 			if (err)
992 				goto free_buf;
993 		}
994 
995 		offset += copy;
996 		buf += copy;
997 done_with_frag:
998 		pos += skb_iter->len;
999 	}
1000 
1001 free_buf:
1002 	kfree(orig_buf);
1003 	return err;
1004 }
1005 
1006 int tls_device_decrypted(struct sock *sk, struct tls_context *tls_ctx)
1007 {
1008 	struct tls_offload_context_rx *ctx = tls_offload_ctx_rx(tls_ctx);
1009 	struct tls_sw_context_rx *sw_ctx = tls_sw_ctx_rx(tls_ctx);
1010 	struct sk_buff *skb = tls_strp_msg(sw_ctx);
1011 	struct strp_msg *rxm = strp_msg(skb);
1012 	int is_decrypted, is_encrypted;
1013 
1014 	if (!tls_strp_msg_mixed_decrypted(sw_ctx)) {
1015 		is_decrypted = skb->decrypted;
1016 		is_encrypted = !is_decrypted;
1017 	} else {
1018 		is_decrypted = 0;
1019 		is_encrypted = 0;
1020 	}
1021 
1022 	trace_tls_device_decrypted(sk, tcp_sk(sk)->copied_seq - rxm->full_len,
1023 				   tls_ctx->rx.rec_seq, rxm->full_len,
1024 				   is_encrypted, is_decrypted);
1025 
1026 	if (unlikely(test_bit(TLS_RX_DEV_DEGRADED, &tls_ctx->flags))) {
1027 		if (likely(is_encrypted || is_decrypted))
1028 			return is_decrypted;
1029 
1030 		/* After tls_device_down disables the offload, the next SKB will
1031 		 * likely have initial fragments decrypted, and final ones not
1032 		 * decrypted. We need to reencrypt that single SKB.
1033 		 */
1034 		return tls_device_reencrypt(sk, tls_ctx);
1035 	}
1036 
1037 	/* Return immediately if the record is either entirely plaintext or
1038 	 * entirely ciphertext. Otherwise handle reencrypt partially decrypted
1039 	 * record.
1040 	 */
1041 	if (is_decrypted) {
1042 		ctx->resync_nh_reset = 1;
1043 		return is_decrypted;
1044 	}
1045 	if (is_encrypted) {
1046 		tls_device_core_ctrl_rx_resync(tls_ctx, ctx, sk, skb);
1047 		return 0;
1048 	}
1049 
1050 	ctx->resync_nh_reset = 1;
1051 	return tls_device_reencrypt(sk, tls_ctx);
1052 }
1053 
1054 static void tls_device_attach(struct tls_context *ctx, struct sock *sk,
1055 			      struct net_device *netdev)
1056 {
1057 	if (sk->sk_destruct != tls_device_sk_destruct) {
1058 		refcount_set(&ctx->refcount, 1);
1059 		dev_hold(netdev);
1060 		RCU_INIT_POINTER(ctx->netdev, netdev);
1061 		spin_lock_irq(&tls_device_lock);
1062 		list_add_tail(&ctx->list, &tls_device_list);
1063 		spin_unlock_irq(&tls_device_lock);
1064 
1065 		ctx->sk_destruct = sk->sk_destruct;
1066 		smp_store_release(&sk->sk_destruct, tls_device_sk_destruct);
1067 	}
1068 }
1069 
1070 int tls_set_device_offload(struct sock *sk, struct tls_context *ctx)
1071 {
1072 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1073 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1074 	const struct tls_cipher_size_desc *cipher_sz;
1075 	struct tls_record_info *start_marker_record;
1076 	struct tls_offload_context_tx *offload_ctx;
1077 	struct tls_crypto_info *crypto_info;
1078 	struct net_device *netdev;
1079 	char *iv, *rec_seq;
1080 	struct sk_buff *skb;
1081 	__be64 rcd_sn;
1082 	int rc;
1083 
1084 	if (!ctx)
1085 		return -EINVAL;
1086 
1087 	if (ctx->priv_ctx_tx)
1088 		return -EEXIST;
1089 
1090 	netdev = get_netdev_for_sock(sk);
1091 	if (!netdev) {
1092 		pr_err_ratelimited("%s: netdev not found\n", __func__);
1093 		return -EINVAL;
1094 	}
1095 
1096 	if (!(netdev->features & NETIF_F_HW_TLS_TX)) {
1097 		rc = -EOPNOTSUPP;
1098 		goto release_netdev;
1099 	}
1100 
1101 	crypto_info = &ctx->crypto_send.info;
1102 	if (crypto_info->version != TLS_1_2_VERSION) {
1103 		rc = -EOPNOTSUPP;
1104 		goto release_netdev;
1105 	}
1106 
1107 	switch (crypto_info->cipher_type) {
1108 	case TLS_CIPHER_AES_GCM_128:
1109 		iv = ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->iv;
1110 		rec_seq =
1111 		 ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->rec_seq;
1112 		break;
1113 	case TLS_CIPHER_AES_GCM_256:
1114 		iv = ((struct tls12_crypto_info_aes_gcm_256 *)crypto_info)->iv;
1115 		rec_seq =
1116 		 ((struct tls12_crypto_info_aes_gcm_256 *)crypto_info)->rec_seq;
1117 		break;
1118 	default:
1119 		rc = -EINVAL;
1120 		goto release_netdev;
1121 	}
1122 	cipher_sz = &tls_cipher_size_desc[crypto_info->cipher_type];
1123 
1124 	/* Sanity-check the rec_seq_size for stack allocations */
1125 	if (cipher_sz->rec_seq > TLS_MAX_REC_SEQ_SIZE) {
1126 		rc = -EINVAL;
1127 		goto release_netdev;
1128 	}
1129 
1130 	prot->version = crypto_info->version;
1131 	prot->cipher_type = crypto_info->cipher_type;
1132 	prot->prepend_size = TLS_HEADER_SIZE + cipher_sz->iv;
1133 	prot->tag_size = cipher_sz->tag;
1134 	prot->overhead_size = prot->prepend_size + prot->tag_size;
1135 	prot->iv_size = cipher_sz->iv;
1136 	prot->salt_size = cipher_sz->salt;
1137 	ctx->tx.iv = kmalloc(cipher_sz->iv + cipher_sz->salt, GFP_KERNEL);
1138 	if (!ctx->tx.iv) {
1139 		rc = -ENOMEM;
1140 		goto release_netdev;
1141 	}
1142 
1143 	memcpy(ctx->tx.iv + cipher_sz->salt, iv, cipher_sz->iv);
1144 
1145 	prot->rec_seq_size = cipher_sz->rec_seq;
1146 	ctx->tx.rec_seq = kmemdup(rec_seq, cipher_sz->rec_seq, GFP_KERNEL);
1147 	if (!ctx->tx.rec_seq) {
1148 		rc = -ENOMEM;
1149 		goto free_iv;
1150 	}
1151 
1152 	start_marker_record = kmalloc(sizeof(*start_marker_record), GFP_KERNEL);
1153 	if (!start_marker_record) {
1154 		rc = -ENOMEM;
1155 		goto free_rec_seq;
1156 	}
1157 
1158 	offload_ctx = kzalloc(TLS_OFFLOAD_CONTEXT_SIZE_TX, GFP_KERNEL);
1159 	if (!offload_ctx) {
1160 		rc = -ENOMEM;
1161 		goto free_marker_record;
1162 	}
1163 
1164 	rc = tls_sw_fallback_init(sk, offload_ctx, crypto_info);
1165 	if (rc)
1166 		goto free_offload_ctx;
1167 
1168 	/* start at rec_seq - 1 to account for the start marker record */
1169 	memcpy(&rcd_sn, ctx->tx.rec_seq, sizeof(rcd_sn));
1170 	offload_ctx->unacked_record_sn = be64_to_cpu(rcd_sn) - 1;
1171 
1172 	start_marker_record->end_seq = tcp_sk(sk)->write_seq;
1173 	start_marker_record->len = 0;
1174 	start_marker_record->num_frags = 0;
1175 
1176 	INIT_WORK(&offload_ctx->destruct_work, tls_device_tx_del_task);
1177 	offload_ctx->ctx = ctx;
1178 
1179 	INIT_LIST_HEAD(&offload_ctx->records_list);
1180 	list_add_tail(&start_marker_record->list, &offload_ctx->records_list);
1181 	spin_lock_init(&offload_ctx->lock);
1182 	sg_init_table(offload_ctx->sg_tx_data,
1183 		      ARRAY_SIZE(offload_ctx->sg_tx_data));
1184 
1185 	clean_acked_data_enable(inet_csk(sk), &tls_icsk_clean_acked);
1186 	ctx->push_pending_record = tls_device_push_pending_record;
1187 
1188 	/* TLS offload is greatly simplified if we don't send
1189 	 * SKBs where only part of the payload needs to be encrypted.
1190 	 * So mark the last skb in the write queue as end of record.
1191 	 */
1192 	skb = tcp_write_queue_tail(sk);
1193 	if (skb)
1194 		TCP_SKB_CB(skb)->eor = 1;
1195 
1196 	/* Avoid offloading if the device is down
1197 	 * We don't want to offload new flows after
1198 	 * the NETDEV_DOWN event
1199 	 *
1200 	 * device_offload_lock is taken in tls_devices's NETDEV_DOWN
1201 	 * handler thus protecting from the device going down before
1202 	 * ctx was added to tls_device_list.
1203 	 */
1204 	down_read(&device_offload_lock);
1205 	if (!(netdev->flags & IFF_UP)) {
1206 		rc = -EINVAL;
1207 		goto release_lock;
1208 	}
1209 
1210 	ctx->priv_ctx_tx = offload_ctx;
1211 	rc = netdev->tlsdev_ops->tls_dev_add(netdev, sk, TLS_OFFLOAD_CTX_DIR_TX,
1212 					     &ctx->crypto_send.info,
1213 					     tcp_sk(sk)->write_seq);
1214 	trace_tls_device_offload_set(sk, TLS_OFFLOAD_CTX_DIR_TX,
1215 				     tcp_sk(sk)->write_seq, rec_seq, rc);
1216 	if (rc)
1217 		goto release_lock;
1218 
1219 	tls_device_attach(ctx, sk, netdev);
1220 	up_read(&device_offload_lock);
1221 
1222 	/* following this assignment tls_is_skb_tx_device_offloaded
1223 	 * will return true and the context might be accessed
1224 	 * by the netdev's xmit function.
1225 	 */
1226 	smp_store_release(&sk->sk_validate_xmit_skb, tls_validate_xmit_skb);
1227 	dev_put(netdev);
1228 
1229 	return 0;
1230 
1231 release_lock:
1232 	up_read(&device_offload_lock);
1233 	clean_acked_data_disable(inet_csk(sk));
1234 	crypto_free_aead(offload_ctx->aead_send);
1235 free_offload_ctx:
1236 	kfree(offload_ctx);
1237 	ctx->priv_ctx_tx = NULL;
1238 free_marker_record:
1239 	kfree(start_marker_record);
1240 free_rec_seq:
1241 	kfree(ctx->tx.rec_seq);
1242 free_iv:
1243 	kfree(ctx->tx.iv);
1244 release_netdev:
1245 	dev_put(netdev);
1246 	return rc;
1247 }
1248 
1249 int tls_set_device_offload_rx(struct sock *sk, struct tls_context *ctx)
1250 {
1251 	struct tls12_crypto_info_aes_gcm_128 *info;
1252 	struct tls_offload_context_rx *context;
1253 	struct net_device *netdev;
1254 	int rc = 0;
1255 
1256 	if (ctx->crypto_recv.info.version != TLS_1_2_VERSION)
1257 		return -EOPNOTSUPP;
1258 
1259 	netdev = get_netdev_for_sock(sk);
1260 	if (!netdev) {
1261 		pr_err_ratelimited("%s: netdev not found\n", __func__);
1262 		return -EINVAL;
1263 	}
1264 
1265 	if (!(netdev->features & NETIF_F_HW_TLS_RX)) {
1266 		rc = -EOPNOTSUPP;
1267 		goto release_netdev;
1268 	}
1269 
1270 	/* Avoid offloading if the device is down
1271 	 * We don't want to offload new flows after
1272 	 * the NETDEV_DOWN event
1273 	 *
1274 	 * device_offload_lock is taken in tls_devices's NETDEV_DOWN
1275 	 * handler thus protecting from the device going down before
1276 	 * ctx was added to tls_device_list.
1277 	 */
1278 	down_read(&device_offload_lock);
1279 	if (!(netdev->flags & IFF_UP)) {
1280 		rc = -EINVAL;
1281 		goto release_lock;
1282 	}
1283 
1284 	context = kzalloc(TLS_OFFLOAD_CONTEXT_SIZE_RX, GFP_KERNEL);
1285 	if (!context) {
1286 		rc = -ENOMEM;
1287 		goto release_lock;
1288 	}
1289 	context->resync_nh_reset = 1;
1290 
1291 	ctx->priv_ctx_rx = context;
1292 	rc = tls_set_sw_offload(sk, ctx, 0);
1293 	if (rc)
1294 		goto release_ctx;
1295 
1296 	rc = netdev->tlsdev_ops->tls_dev_add(netdev, sk, TLS_OFFLOAD_CTX_DIR_RX,
1297 					     &ctx->crypto_recv.info,
1298 					     tcp_sk(sk)->copied_seq);
1299 	info = (void *)&ctx->crypto_recv.info;
1300 	trace_tls_device_offload_set(sk, TLS_OFFLOAD_CTX_DIR_RX,
1301 				     tcp_sk(sk)->copied_seq, info->rec_seq, rc);
1302 	if (rc)
1303 		goto free_sw_resources;
1304 
1305 	tls_device_attach(ctx, sk, netdev);
1306 	up_read(&device_offload_lock);
1307 
1308 	dev_put(netdev);
1309 
1310 	return 0;
1311 
1312 free_sw_resources:
1313 	up_read(&device_offload_lock);
1314 	tls_sw_free_resources_rx(sk);
1315 	down_read(&device_offload_lock);
1316 release_ctx:
1317 	ctx->priv_ctx_rx = NULL;
1318 release_lock:
1319 	up_read(&device_offload_lock);
1320 release_netdev:
1321 	dev_put(netdev);
1322 	return rc;
1323 }
1324 
1325 void tls_device_offload_cleanup_rx(struct sock *sk)
1326 {
1327 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1328 	struct net_device *netdev;
1329 
1330 	down_read(&device_offload_lock);
1331 	netdev = rcu_dereference_protected(tls_ctx->netdev,
1332 					   lockdep_is_held(&device_offload_lock));
1333 	if (!netdev)
1334 		goto out;
1335 
1336 	netdev->tlsdev_ops->tls_dev_del(netdev, tls_ctx,
1337 					TLS_OFFLOAD_CTX_DIR_RX);
1338 
1339 	if (tls_ctx->tx_conf != TLS_HW) {
1340 		dev_put(netdev);
1341 		rcu_assign_pointer(tls_ctx->netdev, NULL);
1342 	} else {
1343 		set_bit(TLS_RX_DEV_CLOSED, &tls_ctx->flags);
1344 	}
1345 out:
1346 	up_read(&device_offload_lock);
1347 	tls_sw_release_resources_rx(sk);
1348 }
1349 
1350 static int tls_device_down(struct net_device *netdev)
1351 {
1352 	struct tls_context *ctx, *tmp;
1353 	unsigned long flags;
1354 	LIST_HEAD(list);
1355 
1356 	/* Request a write lock to block new offload attempts */
1357 	down_write(&device_offload_lock);
1358 
1359 	spin_lock_irqsave(&tls_device_lock, flags);
1360 	list_for_each_entry_safe(ctx, tmp, &tls_device_list, list) {
1361 		struct net_device *ctx_netdev =
1362 			rcu_dereference_protected(ctx->netdev,
1363 						  lockdep_is_held(&device_offload_lock));
1364 
1365 		if (ctx_netdev != netdev ||
1366 		    !refcount_inc_not_zero(&ctx->refcount))
1367 			continue;
1368 
1369 		list_move(&ctx->list, &list);
1370 	}
1371 	spin_unlock_irqrestore(&tls_device_lock, flags);
1372 
1373 	list_for_each_entry_safe(ctx, tmp, &list, list)	{
1374 		/* Stop offloaded TX and switch to the fallback.
1375 		 * tls_is_skb_tx_device_offloaded will return false.
1376 		 */
1377 		WRITE_ONCE(ctx->sk->sk_validate_xmit_skb, tls_validate_xmit_skb_sw);
1378 
1379 		/* Stop the RX and TX resync.
1380 		 * tls_dev_resync must not be called after tls_dev_del.
1381 		 */
1382 		rcu_assign_pointer(ctx->netdev, NULL);
1383 
1384 		/* Start skipping the RX resync logic completely. */
1385 		set_bit(TLS_RX_DEV_DEGRADED, &ctx->flags);
1386 
1387 		/* Sync with inflight packets. After this point:
1388 		 * TX: no non-encrypted packets will be passed to the driver.
1389 		 * RX: resync requests from the driver will be ignored.
1390 		 */
1391 		synchronize_net();
1392 
1393 		/* Release the offload context on the driver side. */
1394 		if (ctx->tx_conf == TLS_HW)
1395 			netdev->tlsdev_ops->tls_dev_del(netdev, ctx,
1396 							TLS_OFFLOAD_CTX_DIR_TX);
1397 		if (ctx->rx_conf == TLS_HW &&
1398 		    !test_bit(TLS_RX_DEV_CLOSED, &ctx->flags))
1399 			netdev->tlsdev_ops->tls_dev_del(netdev, ctx,
1400 							TLS_OFFLOAD_CTX_DIR_RX);
1401 
1402 		dev_put(netdev);
1403 
1404 		/* Move the context to a separate list for two reasons:
1405 		 * 1. When the context is deallocated, list_del is called.
1406 		 * 2. It's no longer an offloaded context, so we don't want to
1407 		 *    run offload-specific code on this context.
1408 		 */
1409 		spin_lock_irqsave(&tls_device_lock, flags);
1410 		list_move_tail(&ctx->list, &tls_device_down_list);
1411 		spin_unlock_irqrestore(&tls_device_lock, flags);
1412 
1413 		/* Device contexts for RX and TX will be freed in on sk_destruct
1414 		 * by tls_device_free_ctx. rx_conf and tx_conf stay in TLS_HW.
1415 		 * Now release the ref taken above.
1416 		 */
1417 		if (refcount_dec_and_test(&ctx->refcount)) {
1418 			/* sk_destruct ran after tls_device_down took a ref, and
1419 			 * it returned early. Complete the destruction here.
1420 			 */
1421 			list_del(&ctx->list);
1422 			tls_device_free_ctx(ctx);
1423 		}
1424 	}
1425 
1426 	up_write(&device_offload_lock);
1427 
1428 	flush_workqueue(destruct_wq);
1429 
1430 	return NOTIFY_DONE;
1431 }
1432 
1433 static int tls_dev_event(struct notifier_block *this, unsigned long event,
1434 			 void *ptr)
1435 {
1436 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1437 
1438 	if (!dev->tlsdev_ops &&
1439 	    !(dev->features & (NETIF_F_HW_TLS_RX | NETIF_F_HW_TLS_TX)))
1440 		return NOTIFY_DONE;
1441 
1442 	switch (event) {
1443 	case NETDEV_REGISTER:
1444 	case NETDEV_FEAT_CHANGE:
1445 		if (netif_is_bond_master(dev))
1446 			return NOTIFY_DONE;
1447 		if ((dev->features & NETIF_F_HW_TLS_RX) &&
1448 		    !dev->tlsdev_ops->tls_dev_resync)
1449 			return NOTIFY_BAD;
1450 
1451 		if  (dev->tlsdev_ops &&
1452 		     dev->tlsdev_ops->tls_dev_add &&
1453 		     dev->tlsdev_ops->tls_dev_del)
1454 			return NOTIFY_DONE;
1455 		else
1456 			return NOTIFY_BAD;
1457 	case NETDEV_DOWN:
1458 		return tls_device_down(dev);
1459 	}
1460 	return NOTIFY_DONE;
1461 }
1462 
1463 static struct notifier_block tls_dev_notifier = {
1464 	.notifier_call	= tls_dev_event,
1465 };
1466 
1467 int __init tls_device_init(void)
1468 {
1469 	int err;
1470 
1471 	destruct_wq = alloc_workqueue("ktls_device_destruct", 0, 0);
1472 	if (!destruct_wq)
1473 		return -ENOMEM;
1474 
1475 	err = register_netdevice_notifier(&tls_dev_notifier);
1476 	if (err)
1477 		destroy_workqueue(destruct_wq);
1478 
1479 	return err;
1480 }
1481 
1482 void __exit tls_device_cleanup(void)
1483 {
1484 	unregister_netdevice_notifier(&tls_dev_notifier);
1485 	destroy_workqueue(destruct_wq);
1486 	clean_acked_data_flush();
1487 }
1488