xref: /openbmc/linux/net/tls/tls_device.c (revision 26b32974)
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_SPLICE_PAGES))
445 		return -EOPNOTSUPP;
446 
447 	if (unlikely(sk->sk_err))
448 		return -sk->sk_err;
449 
450 	flags |= MSG_SENDPAGE_DECRYPTED;
451 	tls_push_record_flags = flags | MSG_MORE;
452 
453 	timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
454 	if (tls_is_partially_sent_record(tls_ctx)) {
455 		rc = tls_push_partial_record(sk, tls_ctx, flags);
456 		if (rc < 0)
457 			return rc;
458 	}
459 
460 	pfrag = sk_page_frag(sk);
461 
462 	/* TLS_HEADER_SIZE is not counted as part of the TLS record, and
463 	 * we need to leave room for an authentication tag.
464 	 */
465 	max_open_record_len = TLS_MAX_PAYLOAD_SIZE +
466 			      prot->prepend_size;
467 	do {
468 		rc = tls_do_allocation(sk, ctx, pfrag, prot->prepend_size);
469 		if (unlikely(rc)) {
470 			rc = sk_stream_wait_memory(sk, &timeo);
471 			if (!rc)
472 				continue;
473 
474 			record = ctx->open_record;
475 			if (!record)
476 				break;
477 handle_error:
478 			if (record_type != TLS_RECORD_TYPE_DATA) {
479 				/* avoid sending partial
480 				 * record with type !=
481 				 * application_data
482 				 */
483 				size = orig_size;
484 				destroy_record(record);
485 				ctx->open_record = NULL;
486 			} else if (record->len > prot->prepend_size) {
487 				goto last_record;
488 			}
489 
490 			break;
491 		}
492 
493 		record = ctx->open_record;
494 
495 		copy = min_t(size_t, size, max_open_record_len - record->len);
496 		if (copy && (flags & MSG_SPLICE_PAGES)) {
497 			struct page_frag zc_pfrag;
498 			struct page **pages = &zc_pfrag.page;
499 			size_t off;
500 
501 			rc = iov_iter_extract_pages(iter, &pages,
502 						    copy, 1, 0, &off);
503 			if (rc <= 0) {
504 				if (rc == 0)
505 					rc = -EIO;
506 				goto handle_error;
507 			}
508 			copy = rc;
509 
510 			if (WARN_ON_ONCE(!sendpage_ok(zc_pfrag.page))) {
511 				iov_iter_revert(iter, copy);
512 				rc = -EIO;
513 				goto handle_error;
514 			}
515 
516 			zc_pfrag.offset = off;
517 			zc_pfrag.size = copy;
518 			tls_append_frag(record, &zc_pfrag, copy);
519 		} else if (copy) {
520 			copy = min_t(size_t, copy, pfrag->size - pfrag->offset);
521 
522 			rc = tls_device_copy_data(page_address(pfrag->page) +
523 						  pfrag->offset, copy,
524 						  iter);
525 			if (rc)
526 				goto handle_error;
527 			tls_append_frag(record, pfrag, copy);
528 		}
529 
530 		size -= copy;
531 		if (!size) {
532 last_record:
533 			tls_push_record_flags = flags;
534 			if (flags & MSG_MORE) {
535 				more = true;
536 				break;
537 			}
538 
539 			done = true;
540 		}
541 
542 		if (done || record->len >= max_open_record_len ||
543 		    (record->num_frags >= MAX_SKB_FRAGS - 1)) {
544 			rc = tls_device_record_close(sk, tls_ctx, record,
545 						     pfrag, record_type);
546 			if (rc) {
547 				if (rc > 0) {
548 					size += rc;
549 				} else {
550 					size = orig_size;
551 					destroy_record(record);
552 					ctx->open_record = NULL;
553 					break;
554 				}
555 			}
556 
557 			rc = tls_push_record(sk,
558 					     tls_ctx,
559 					     ctx,
560 					     record,
561 					     tls_push_record_flags);
562 			if (rc < 0)
563 				break;
564 		}
565 	} while (!done);
566 
567 	tls_ctx->pending_open_record_frags = more;
568 
569 	if (orig_size - size > 0)
570 		rc = orig_size - size;
571 
572 	return rc;
573 }
574 
575 int tls_device_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
576 {
577 	unsigned char record_type = TLS_RECORD_TYPE_DATA;
578 	struct tls_context *tls_ctx = tls_get_ctx(sk);
579 	int rc;
580 
581 	if (!tls_ctx->zerocopy_sendfile)
582 		msg->msg_flags &= ~MSG_SPLICE_PAGES;
583 
584 	mutex_lock(&tls_ctx->tx_lock);
585 	lock_sock(sk);
586 
587 	if (unlikely(msg->msg_controllen)) {
588 		rc = tls_process_cmsg(sk, msg, &record_type);
589 		if (rc)
590 			goto out;
591 	}
592 
593 	rc = tls_push_data(sk, &msg->msg_iter, size, msg->msg_flags,
594 			   record_type);
595 
596 out:
597 	release_sock(sk);
598 	mutex_unlock(&tls_ctx->tx_lock);
599 	return rc;
600 }
601 
602 void tls_device_splice_eof(struct socket *sock)
603 {
604 	struct sock *sk = sock->sk;
605 	struct tls_context *tls_ctx = tls_get_ctx(sk);
606 	struct iov_iter iter = {};
607 
608 	if (!tls_is_partially_sent_record(tls_ctx))
609 		return;
610 
611 	mutex_lock(&tls_ctx->tx_lock);
612 	lock_sock(sk);
613 
614 	if (tls_is_partially_sent_record(tls_ctx)) {
615 		iov_iter_bvec(&iter, ITER_SOURCE, NULL, 0, 0);
616 		tls_push_data(sk, &iter, 0, 0, TLS_RECORD_TYPE_DATA);
617 	}
618 
619 	release_sock(sk);
620 	mutex_unlock(&tls_ctx->tx_lock);
621 }
622 
623 struct tls_record_info *tls_get_record(struct tls_offload_context_tx *context,
624 				       u32 seq, u64 *p_record_sn)
625 {
626 	u64 record_sn = context->hint_record_sn;
627 	struct tls_record_info *info, *last;
628 
629 	info = context->retransmit_hint;
630 	if (!info ||
631 	    before(seq, info->end_seq - info->len)) {
632 		/* if retransmit_hint is irrelevant start
633 		 * from the beginning of the list
634 		 */
635 		info = list_first_entry_or_null(&context->records_list,
636 						struct tls_record_info, list);
637 		if (!info)
638 			return NULL;
639 		/* send the start_marker record if seq number is before the
640 		 * tls offload start marker sequence number. This record is
641 		 * required to handle TCP packets which are before TLS offload
642 		 * started.
643 		 *  And if it's not start marker, look if this seq number
644 		 * belongs to the list.
645 		 */
646 		if (likely(!tls_record_is_start_marker(info))) {
647 			/* we have the first record, get the last record to see
648 			 * if this seq number belongs to the list.
649 			 */
650 			last = list_last_entry(&context->records_list,
651 					       struct tls_record_info, list);
652 
653 			if (!between(seq, tls_record_start_seq(info),
654 				     last->end_seq))
655 				return NULL;
656 		}
657 		record_sn = context->unacked_record_sn;
658 	}
659 
660 	/* We just need the _rcu for the READ_ONCE() */
661 	rcu_read_lock();
662 	list_for_each_entry_from_rcu(info, &context->records_list, list) {
663 		if (before(seq, info->end_seq)) {
664 			if (!context->retransmit_hint ||
665 			    after(info->end_seq,
666 				  context->retransmit_hint->end_seq)) {
667 				context->hint_record_sn = record_sn;
668 				context->retransmit_hint = info;
669 			}
670 			*p_record_sn = record_sn;
671 			goto exit_rcu_unlock;
672 		}
673 		record_sn++;
674 	}
675 	info = NULL;
676 
677 exit_rcu_unlock:
678 	rcu_read_unlock();
679 	return info;
680 }
681 EXPORT_SYMBOL(tls_get_record);
682 
683 static int tls_device_push_pending_record(struct sock *sk, int flags)
684 {
685 	struct iov_iter iter;
686 
687 	iov_iter_kvec(&iter, ITER_SOURCE, NULL, 0, 0);
688 	return tls_push_data(sk, &iter, 0, flags, TLS_RECORD_TYPE_DATA);
689 }
690 
691 void tls_device_write_space(struct sock *sk, struct tls_context *ctx)
692 {
693 	if (tls_is_partially_sent_record(ctx)) {
694 		gfp_t sk_allocation = sk->sk_allocation;
695 
696 		WARN_ON_ONCE(sk->sk_write_pending);
697 
698 		sk->sk_allocation = GFP_ATOMIC;
699 		tls_push_partial_record(sk, ctx,
700 					MSG_DONTWAIT | MSG_NOSIGNAL |
701 					MSG_SENDPAGE_DECRYPTED);
702 		sk->sk_allocation = sk_allocation;
703 	}
704 }
705 
706 static void tls_device_resync_rx(struct tls_context *tls_ctx,
707 				 struct sock *sk, u32 seq, u8 *rcd_sn)
708 {
709 	struct tls_offload_context_rx *rx_ctx = tls_offload_ctx_rx(tls_ctx);
710 	struct net_device *netdev;
711 
712 	trace_tls_device_rx_resync_send(sk, seq, rcd_sn, rx_ctx->resync_type);
713 	rcu_read_lock();
714 	netdev = rcu_dereference(tls_ctx->netdev);
715 	if (netdev)
716 		netdev->tlsdev_ops->tls_dev_resync(netdev, sk, seq, rcd_sn,
717 						   TLS_OFFLOAD_CTX_DIR_RX);
718 	rcu_read_unlock();
719 	TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXDEVICERESYNC);
720 }
721 
722 static bool
723 tls_device_rx_resync_async(struct tls_offload_resync_async *resync_async,
724 			   s64 resync_req, u32 *seq, u16 *rcd_delta)
725 {
726 	u32 is_async = resync_req & RESYNC_REQ_ASYNC;
727 	u32 req_seq = resync_req >> 32;
728 	u32 req_end = req_seq + ((resync_req >> 16) & 0xffff);
729 	u16 i;
730 
731 	*rcd_delta = 0;
732 
733 	if (is_async) {
734 		/* shouldn't get to wraparound:
735 		 * too long in async stage, something bad happened
736 		 */
737 		if (WARN_ON_ONCE(resync_async->rcd_delta == USHRT_MAX))
738 			return false;
739 
740 		/* asynchronous stage: log all headers seq such that
741 		 * req_seq <= seq <= end_seq, and wait for real resync request
742 		 */
743 		if (before(*seq, req_seq))
744 			return false;
745 		if (!after(*seq, req_end) &&
746 		    resync_async->loglen < TLS_DEVICE_RESYNC_ASYNC_LOGMAX)
747 			resync_async->log[resync_async->loglen++] = *seq;
748 
749 		resync_async->rcd_delta++;
750 
751 		return false;
752 	}
753 
754 	/* synchronous stage: check against the logged entries and
755 	 * proceed to check the next entries if no match was found
756 	 */
757 	for (i = 0; i < resync_async->loglen; i++)
758 		if (req_seq == resync_async->log[i] &&
759 		    atomic64_try_cmpxchg(&resync_async->req, &resync_req, 0)) {
760 			*rcd_delta = resync_async->rcd_delta - i;
761 			*seq = req_seq;
762 			resync_async->loglen = 0;
763 			resync_async->rcd_delta = 0;
764 			return true;
765 		}
766 
767 	resync_async->loglen = 0;
768 	resync_async->rcd_delta = 0;
769 
770 	if (req_seq == *seq &&
771 	    atomic64_try_cmpxchg(&resync_async->req,
772 				 &resync_req, 0))
773 		return true;
774 
775 	return false;
776 }
777 
778 void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq)
779 {
780 	struct tls_context *tls_ctx = tls_get_ctx(sk);
781 	struct tls_offload_context_rx *rx_ctx;
782 	u8 rcd_sn[TLS_MAX_REC_SEQ_SIZE];
783 	u32 sock_data, is_req_pending;
784 	struct tls_prot_info *prot;
785 	s64 resync_req;
786 	u16 rcd_delta;
787 	u32 req_seq;
788 
789 	if (tls_ctx->rx_conf != TLS_HW)
790 		return;
791 	if (unlikely(test_bit(TLS_RX_DEV_DEGRADED, &tls_ctx->flags)))
792 		return;
793 
794 	prot = &tls_ctx->prot_info;
795 	rx_ctx = tls_offload_ctx_rx(tls_ctx);
796 	memcpy(rcd_sn, tls_ctx->rx.rec_seq, prot->rec_seq_size);
797 
798 	switch (rx_ctx->resync_type) {
799 	case TLS_OFFLOAD_SYNC_TYPE_DRIVER_REQ:
800 		resync_req = atomic64_read(&rx_ctx->resync_req);
801 		req_seq = resync_req >> 32;
802 		seq += TLS_HEADER_SIZE - 1;
803 		is_req_pending = resync_req;
804 
805 		if (likely(!is_req_pending) || req_seq != seq ||
806 		    !atomic64_try_cmpxchg(&rx_ctx->resync_req, &resync_req, 0))
807 			return;
808 		break;
809 	case TLS_OFFLOAD_SYNC_TYPE_CORE_NEXT_HINT:
810 		if (likely(!rx_ctx->resync_nh_do_now))
811 			return;
812 
813 		/* head of next rec is already in, note that the sock_inq will
814 		 * include the currently parsed message when called from parser
815 		 */
816 		sock_data = tcp_inq(sk);
817 		if (sock_data > rcd_len) {
818 			trace_tls_device_rx_resync_nh_delay(sk, sock_data,
819 							    rcd_len);
820 			return;
821 		}
822 
823 		rx_ctx->resync_nh_do_now = 0;
824 		seq += rcd_len;
825 		tls_bigint_increment(rcd_sn, prot->rec_seq_size);
826 		break;
827 	case TLS_OFFLOAD_SYNC_TYPE_DRIVER_REQ_ASYNC:
828 		resync_req = atomic64_read(&rx_ctx->resync_async->req);
829 		is_req_pending = resync_req;
830 		if (likely(!is_req_pending))
831 			return;
832 
833 		if (!tls_device_rx_resync_async(rx_ctx->resync_async,
834 						resync_req, &seq, &rcd_delta))
835 			return;
836 		tls_bigint_subtract(rcd_sn, rcd_delta);
837 		break;
838 	}
839 
840 	tls_device_resync_rx(tls_ctx, sk, seq, rcd_sn);
841 }
842 
843 static void tls_device_core_ctrl_rx_resync(struct tls_context *tls_ctx,
844 					   struct tls_offload_context_rx *ctx,
845 					   struct sock *sk, struct sk_buff *skb)
846 {
847 	struct strp_msg *rxm;
848 
849 	/* device will request resyncs by itself based on stream scan */
850 	if (ctx->resync_type != TLS_OFFLOAD_SYNC_TYPE_CORE_NEXT_HINT)
851 		return;
852 	/* already scheduled */
853 	if (ctx->resync_nh_do_now)
854 		return;
855 	/* seen decrypted fragments since last fully-failed record */
856 	if (ctx->resync_nh_reset) {
857 		ctx->resync_nh_reset = 0;
858 		ctx->resync_nh.decrypted_failed = 1;
859 		ctx->resync_nh.decrypted_tgt = TLS_DEVICE_RESYNC_NH_START_IVAL;
860 		return;
861 	}
862 
863 	if (++ctx->resync_nh.decrypted_failed <= ctx->resync_nh.decrypted_tgt)
864 		return;
865 
866 	/* doing resync, bump the next target in case it fails */
867 	if (ctx->resync_nh.decrypted_tgt < TLS_DEVICE_RESYNC_NH_MAX_IVAL)
868 		ctx->resync_nh.decrypted_tgt *= 2;
869 	else
870 		ctx->resync_nh.decrypted_tgt += TLS_DEVICE_RESYNC_NH_MAX_IVAL;
871 
872 	rxm = strp_msg(skb);
873 
874 	/* head of next rec is already in, parser will sync for us */
875 	if (tcp_inq(sk) > rxm->full_len) {
876 		trace_tls_device_rx_resync_nh_schedule(sk);
877 		ctx->resync_nh_do_now = 1;
878 	} else {
879 		struct tls_prot_info *prot = &tls_ctx->prot_info;
880 		u8 rcd_sn[TLS_MAX_REC_SEQ_SIZE];
881 
882 		memcpy(rcd_sn, tls_ctx->rx.rec_seq, prot->rec_seq_size);
883 		tls_bigint_increment(rcd_sn, prot->rec_seq_size);
884 
885 		tls_device_resync_rx(tls_ctx, sk, tcp_sk(sk)->copied_seq,
886 				     rcd_sn);
887 	}
888 }
889 
890 static int
891 tls_device_reencrypt(struct sock *sk, struct tls_context *tls_ctx)
892 {
893 	struct tls_sw_context_rx *sw_ctx = tls_sw_ctx_rx(tls_ctx);
894 	const struct tls_cipher_size_desc *cipher_sz;
895 	int err, offset, copy, data_len, pos;
896 	struct sk_buff *skb, *skb_iter;
897 	struct scatterlist sg[1];
898 	struct strp_msg *rxm;
899 	char *orig_buf, *buf;
900 
901 	switch (tls_ctx->crypto_recv.info.cipher_type) {
902 	case TLS_CIPHER_AES_GCM_128:
903 	case TLS_CIPHER_AES_GCM_256:
904 		break;
905 	default:
906 		return -EINVAL;
907 	}
908 	cipher_sz = &tls_cipher_size_desc[tls_ctx->crypto_recv.info.cipher_type];
909 
910 	rxm = strp_msg(tls_strp_msg(sw_ctx));
911 	orig_buf = kmalloc(rxm->full_len + TLS_HEADER_SIZE + cipher_sz->iv,
912 			   sk->sk_allocation);
913 	if (!orig_buf)
914 		return -ENOMEM;
915 	buf = orig_buf;
916 
917 	err = tls_strp_msg_cow(sw_ctx);
918 	if (unlikely(err))
919 		goto free_buf;
920 
921 	skb = tls_strp_msg(sw_ctx);
922 	rxm = strp_msg(skb);
923 	offset = rxm->offset;
924 
925 	sg_init_table(sg, 1);
926 	sg_set_buf(&sg[0], buf,
927 		   rxm->full_len + TLS_HEADER_SIZE + cipher_sz->iv);
928 	err = skb_copy_bits(skb, offset, buf, TLS_HEADER_SIZE + cipher_sz->iv);
929 	if (err)
930 		goto free_buf;
931 
932 	/* We are interested only in the decrypted data not the auth */
933 	err = decrypt_skb(sk, sg);
934 	if (err != -EBADMSG)
935 		goto free_buf;
936 	else
937 		err = 0;
938 
939 	data_len = rxm->full_len - cipher_sz->tag;
940 
941 	if (skb_pagelen(skb) > offset) {
942 		copy = min_t(int, skb_pagelen(skb) - offset, data_len);
943 
944 		if (skb->decrypted) {
945 			err = skb_store_bits(skb, offset, buf, copy);
946 			if (err)
947 				goto free_buf;
948 		}
949 
950 		offset += copy;
951 		buf += copy;
952 	}
953 
954 	pos = skb_pagelen(skb);
955 	skb_walk_frags(skb, skb_iter) {
956 		int frag_pos;
957 
958 		/* Practically all frags must belong to msg if reencrypt
959 		 * is needed with current strparser and coalescing logic,
960 		 * but strparser may "get optimized", so let's be safe.
961 		 */
962 		if (pos + skb_iter->len <= offset)
963 			goto done_with_frag;
964 		if (pos >= data_len + rxm->offset)
965 			break;
966 
967 		frag_pos = offset - pos;
968 		copy = min_t(int, skb_iter->len - frag_pos,
969 			     data_len + rxm->offset - offset);
970 
971 		if (skb_iter->decrypted) {
972 			err = skb_store_bits(skb_iter, frag_pos, buf, copy);
973 			if (err)
974 				goto free_buf;
975 		}
976 
977 		offset += copy;
978 		buf += copy;
979 done_with_frag:
980 		pos += skb_iter->len;
981 	}
982 
983 free_buf:
984 	kfree(orig_buf);
985 	return err;
986 }
987 
988 int tls_device_decrypted(struct sock *sk, struct tls_context *tls_ctx)
989 {
990 	struct tls_offload_context_rx *ctx = tls_offload_ctx_rx(tls_ctx);
991 	struct tls_sw_context_rx *sw_ctx = tls_sw_ctx_rx(tls_ctx);
992 	struct sk_buff *skb = tls_strp_msg(sw_ctx);
993 	struct strp_msg *rxm = strp_msg(skb);
994 	int is_decrypted, is_encrypted;
995 
996 	if (!tls_strp_msg_mixed_decrypted(sw_ctx)) {
997 		is_decrypted = skb->decrypted;
998 		is_encrypted = !is_decrypted;
999 	} else {
1000 		is_decrypted = 0;
1001 		is_encrypted = 0;
1002 	}
1003 
1004 	trace_tls_device_decrypted(sk, tcp_sk(sk)->copied_seq - rxm->full_len,
1005 				   tls_ctx->rx.rec_seq, rxm->full_len,
1006 				   is_encrypted, is_decrypted);
1007 
1008 	if (unlikely(test_bit(TLS_RX_DEV_DEGRADED, &tls_ctx->flags))) {
1009 		if (likely(is_encrypted || is_decrypted))
1010 			return is_decrypted;
1011 
1012 		/* After tls_device_down disables the offload, the next SKB will
1013 		 * likely have initial fragments decrypted, and final ones not
1014 		 * decrypted. We need to reencrypt that single SKB.
1015 		 */
1016 		return tls_device_reencrypt(sk, tls_ctx);
1017 	}
1018 
1019 	/* Return immediately if the record is either entirely plaintext or
1020 	 * entirely ciphertext. Otherwise handle reencrypt partially decrypted
1021 	 * record.
1022 	 */
1023 	if (is_decrypted) {
1024 		ctx->resync_nh_reset = 1;
1025 		return is_decrypted;
1026 	}
1027 	if (is_encrypted) {
1028 		tls_device_core_ctrl_rx_resync(tls_ctx, ctx, sk, skb);
1029 		return 0;
1030 	}
1031 
1032 	ctx->resync_nh_reset = 1;
1033 	return tls_device_reencrypt(sk, tls_ctx);
1034 }
1035 
1036 static void tls_device_attach(struct tls_context *ctx, struct sock *sk,
1037 			      struct net_device *netdev)
1038 {
1039 	if (sk->sk_destruct != tls_device_sk_destruct) {
1040 		refcount_set(&ctx->refcount, 1);
1041 		dev_hold(netdev);
1042 		RCU_INIT_POINTER(ctx->netdev, netdev);
1043 		spin_lock_irq(&tls_device_lock);
1044 		list_add_tail(&ctx->list, &tls_device_list);
1045 		spin_unlock_irq(&tls_device_lock);
1046 
1047 		ctx->sk_destruct = sk->sk_destruct;
1048 		smp_store_release(&sk->sk_destruct, tls_device_sk_destruct);
1049 	}
1050 }
1051 
1052 int tls_set_device_offload(struct sock *sk, struct tls_context *ctx)
1053 {
1054 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1055 	struct tls_prot_info *prot = &tls_ctx->prot_info;
1056 	const struct tls_cipher_size_desc *cipher_sz;
1057 	struct tls_record_info *start_marker_record;
1058 	struct tls_offload_context_tx *offload_ctx;
1059 	struct tls_crypto_info *crypto_info;
1060 	struct net_device *netdev;
1061 	char *iv, *rec_seq;
1062 	struct sk_buff *skb;
1063 	__be64 rcd_sn;
1064 	int rc;
1065 
1066 	if (!ctx)
1067 		return -EINVAL;
1068 
1069 	if (ctx->priv_ctx_tx)
1070 		return -EEXIST;
1071 
1072 	netdev = get_netdev_for_sock(sk);
1073 	if (!netdev) {
1074 		pr_err_ratelimited("%s: netdev not found\n", __func__);
1075 		return -EINVAL;
1076 	}
1077 
1078 	if (!(netdev->features & NETIF_F_HW_TLS_TX)) {
1079 		rc = -EOPNOTSUPP;
1080 		goto release_netdev;
1081 	}
1082 
1083 	crypto_info = &ctx->crypto_send.info;
1084 	if (crypto_info->version != TLS_1_2_VERSION) {
1085 		rc = -EOPNOTSUPP;
1086 		goto release_netdev;
1087 	}
1088 
1089 	switch (crypto_info->cipher_type) {
1090 	case TLS_CIPHER_AES_GCM_128:
1091 		iv = ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->iv;
1092 		rec_seq =
1093 		 ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->rec_seq;
1094 		break;
1095 	case TLS_CIPHER_AES_GCM_256:
1096 		iv = ((struct tls12_crypto_info_aes_gcm_256 *)crypto_info)->iv;
1097 		rec_seq =
1098 		 ((struct tls12_crypto_info_aes_gcm_256 *)crypto_info)->rec_seq;
1099 		break;
1100 	default:
1101 		rc = -EINVAL;
1102 		goto release_netdev;
1103 	}
1104 	cipher_sz = &tls_cipher_size_desc[crypto_info->cipher_type];
1105 
1106 	/* Sanity-check the rec_seq_size for stack allocations */
1107 	if (cipher_sz->rec_seq > TLS_MAX_REC_SEQ_SIZE) {
1108 		rc = -EINVAL;
1109 		goto release_netdev;
1110 	}
1111 
1112 	prot->version = crypto_info->version;
1113 	prot->cipher_type = crypto_info->cipher_type;
1114 	prot->prepend_size = TLS_HEADER_SIZE + cipher_sz->iv;
1115 	prot->tag_size = cipher_sz->tag;
1116 	prot->overhead_size = prot->prepend_size + prot->tag_size;
1117 	prot->iv_size = cipher_sz->iv;
1118 	prot->salt_size = cipher_sz->salt;
1119 	ctx->tx.iv = kmalloc(cipher_sz->iv + cipher_sz->salt, GFP_KERNEL);
1120 	if (!ctx->tx.iv) {
1121 		rc = -ENOMEM;
1122 		goto release_netdev;
1123 	}
1124 
1125 	memcpy(ctx->tx.iv + cipher_sz->salt, iv, cipher_sz->iv);
1126 
1127 	prot->rec_seq_size = cipher_sz->rec_seq;
1128 	ctx->tx.rec_seq = kmemdup(rec_seq, cipher_sz->rec_seq, GFP_KERNEL);
1129 	if (!ctx->tx.rec_seq) {
1130 		rc = -ENOMEM;
1131 		goto free_iv;
1132 	}
1133 
1134 	start_marker_record = kmalloc(sizeof(*start_marker_record), GFP_KERNEL);
1135 	if (!start_marker_record) {
1136 		rc = -ENOMEM;
1137 		goto free_rec_seq;
1138 	}
1139 
1140 	offload_ctx = kzalloc(TLS_OFFLOAD_CONTEXT_SIZE_TX, GFP_KERNEL);
1141 	if (!offload_ctx) {
1142 		rc = -ENOMEM;
1143 		goto free_marker_record;
1144 	}
1145 
1146 	rc = tls_sw_fallback_init(sk, offload_ctx, crypto_info);
1147 	if (rc)
1148 		goto free_offload_ctx;
1149 
1150 	/* start at rec_seq - 1 to account for the start marker record */
1151 	memcpy(&rcd_sn, ctx->tx.rec_seq, sizeof(rcd_sn));
1152 	offload_ctx->unacked_record_sn = be64_to_cpu(rcd_sn) - 1;
1153 
1154 	start_marker_record->end_seq = tcp_sk(sk)->write_seq;
1155 	start_marker_record->len = 0;
1156 	start_marker_record->num_frags = 0;
1157 
1158 	INIT_WORK(&offload_ctx->destruct_work, tls_device_tx_del_task);
1159 	offload_ctx->ctx = ctx;
1160 
1161 	INIT_LIST_HEAD(&offload_ctx->records_list);
1162 	list_add_tail(&start_marker_record->list, &offload_ctx->records_list);
1163 	spin_lock_init(&offload_ctx->lock);
1164 	sg_init_table(offload_ctx->sg_tx_data,
1165 		      ARRAY_SIZE(offload_ctx->sg_tx_data));
1166 
1167 	clean_acked_data_enable(inet_csk(sk), &tls_icsk_clean_acked);
1168 	ctx->push_pending_record = tls_device_push_pending_record;
1169 
1170 	/* TLS offload is greatly simplified if we don't send
1171 	 * SKBs where only part of the payload needs to be encrypted.
1172 	 * So mark the last skb in the write queue as end of record.
1173 	 */
1174 	skb = tcp_write_queue_tail(sk);
1175 	if (skb)
1176 		TCP_SKB_CB(skb)->eor = 1;
1177 
1178 	/* Avoid offloading if the device is down
1179 	 * We don't want to offload new flows after
1180 	 * the NETDEV_DOWN event
1181 	 *
1182 	 * device_offload_lock is taken in tls_devices's NETDEV_DOWN
1183 	 * handler thus protecting from the device going down before
1184 	 * ctx was added to tls_device_list.
1185 	 */
1186 	down_read(&device_offload_lock);
1187 	if (!(netdev->flags & IFF_UP)) {
1188 		rc = -EINVAL;
1189 		goto release_lock;
1190 	}
1191 
1192 	ctx->priv_ctx_tx = offload_ctx;
1193 	rc = netdev->tlsdev_ops->tls_dev_add(netdev, sk, TLS_OFFLOAD_CTX_DIR_TX,
1194 					     &ctx->crypto_send.info,
1195 					     tcp_sk(sk)->write_seq);
1196 	trace_tls_device_offload_set(sk, TLS_OFFLOAD_CTX_DIR_TX,
1197 				     tcp_sk(sk)->write_seq, rec_seq, rc);
1198 	if (rc)
1199 		goto release_lock;
1200 
1201 	tls_device_attach(ctx, sk, netdev);
1202 	up_read(&device_offload_lock);
1203 
1204 	/* following this assignment tls_is_skb_tx_device_offloaded
1205 	 * will return true and the context might be accessed
1206 	 * by the netdev's xmit function.
1207 	 */
1208 	smp_store_release(&sk->sk_validate_xmit_skb, tls_validate_xmit_skb);
1209 	dev_put(netdev);
1210 
1211 	return 0;
1212 
1213 release_lock:
1214 	up_read(&device_offload_lock);
1215 	clean_acked_data_disable(inet_csk(sk));
1216 	crypto_free_aead(offload_ctx->aead_send);
1217 free_offload_ctx:
1218 	kfree(offload_ctx);
1219 	ctx->priv_ctx_tx = NULL;
1220 free_marker_record:
1221 	kfree(start_marker_record);
1222 free_rec_seq:
1223 	kfree(ctx->tx.rec_seq);
1224 free_iv:
1225 	kfree(ctx->tx.iv);
1226 release_netdev:
1227 	dev_put(netdev);
1228 	return rc;
1229 }
1230 
1231 int tls_set_device_offload_rx(struct sock *sk, struct tls_context *ctx)
1232 {
1233 	struct tls12_crypto_info_aes_gcm_128 *info;
1234 	struct tls_offload_context_rx *context;
1235 	struct net_device *netdev;
1236 	int rc = 0;
1237 
1238 	if (ctx->crypto_recv.info.version != TLS_1_2_VERSION)
1239 		return -EOPNOTSUPP;
1240 
1241 	netdev = get_netdev_for_sock(sk);
1242 	if (!netdev) {
1243 		pr_err_ratelimited("%s: netdev not found\n", __func__);
1244 		return -EINVAL;
1245 	}
1246 
1247 	if (!(netdev->features & NETIF_F_HW_TLS_RX)) {
1248 		rc = -EOPNOTSUPP;
1249 		goto release_netdev;
1250 	}
1251 
1252 	/* Avoid offloading if the device is down
1253 	 * We don't want to offload new flows after
1254 	 * the NETDEV_DOWN event
1255 	 *
1256 	 * device_offload_lock is taken in tls_devices's NETDEV_DOWN
1257 	 * handler thus protecting from the device going down before
1258 	 * ctx was added to tls_device_list.
1259 	 */
1260 	down_read(&device_offload_lock);
1261 	if (!(netdev->flags & IFF_UP)) {
1262 		rc = -EINVAL;
1263 		goto release_lock;
1264 	}
1265 
1266 	context = kzalloc(TLS_OFFLOAD_CONTEXT_SIZE_RX, GFP_KERNEL);
1267 	if (!context) {
1268 		rc = -ENOMEM;
1269 		goto release_lock;
1270 	}
1271 	context->resync_nh_reset = 1;
1272 
1273 	ctx->priv_ctx_rx = context;
1274 	rc = tls_set_sw_offload(sk, ctx, 0);
1275 	if (rc)
1276 		goto release_ctx;
1277 
1278 	rc = netdev->tlsdev_ops->tls_dev_add(netdev, sk, TLS_OFFLOAD_CTX_DIR_RX,
1279 					     &ctx->crypto_recv.info,
1280 					     tcp_sk(sk)->copied_seq);
1281 	info = (void *)&ctx->crypto_recv.info;
1282 	trace_tls_device_offload_set(sk, TLS_OFFLOAD_CTX_DIR_RX,
1283 				     tcp_sk(sk)->copied_seq, info->rec_seq, rc);
1284 	if (rc)
1285 		goto free_sw_resources;
1286 
1287 	tls_device_attach(ctx, sk, netdev);
1288 	up_read(&device_offload_lock);
1289 
1290 	dev_put(netdev);
1291 
1292 	return 0;
1293 
1294 free_sw_resources:
1295 	up_read(&device_offload_lock);
1296 	tls_sw_free_resources_rx(sk);
1297 	down_read(&device_offload_lock);
1298 release_ctx:
1299 	ctx->priv_ctx_rx = NULL;
1300 release_lock:
1301 	up_read(&device_offload_lock);
1302 release_netdev:
1303 	dev_put(netdev);
1304 	return rc;
1305 }
1306 
1307 void tls_device_offload_cleanup_rx(struct sock *sk)
1308 {
1309 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1310 	struct net_device *netdev;
1311 
1312 	down_read(&device_offload_lock);
1313 	netdev = rcu_dereference_protected(tls_ctx->netdev,
1314 					   lockdep_is_held(&device_offload_lock));
1315 	if (!netdev)
1316 		goto out;
1317 
1318 	netdev->tlsdev_ops->tls_dev_del(netdev, tls_ctx,
1319 					TLS_OFFLOAD_CTX_DIR_RX);
1320 
1321 	if (tls_ctx->tx_conf != TLS_HW) {
1322 		dev_put(netdev);
1323 		rcu_assign_pointer(tls_ctx->netdev, NULL);
1324 	} else {
1325 		set_bit(TLS_RX_DEV_CLOSED, &tls_ctx->flags);
1326 	}
1327 out:
1328 	up_read(&device_offload_lock);
1329 	tls_sw_release_resources_rx(sk);
1330 }
1331 
1332 static int tls_device_down(struct net_device *netdev)
1333 {
1334 	struct tls_context *ctx, *tmp;
1335 	unsigned long flags;
1336 	LIST_HEAD(list);
1337 
1338 	/* Request a write lock to block new offload attempts */
1339 	down_write(&device_offload_lock);
1340 
1341 	spin_lock_irqsave(&tls_device_lock, flags);
1342 	list_for_each_entry_safe(ctx, tmp, &tls_device_list, list) {
1343 		struct net_device *ctx_netdev =
1344 			rcu_dereference_protected(ctx->netdev,
1345 						  lockdep_is_held(&device_offload_lock));
1346 
1347 		if (ctx_netdev != netdev ||
1348 		    !refcount_inc_not_zero(&ctx->refcount))
1349 			continue;
1350 
1351 		list_move(&ctx->list, &list);
1352 	}
1353 	spin_unlock_irqrestore(&tls_device_lock, flags);
1354 
1355 	list_for_each_entry_safe(ctx, tmp, &list, list)	{
1356 		/* Stop offloaded TX and switch to the fallback.
1357 		 * tls_is_skb_tx_device_offloaded will return false.
1358 		 */
1359 		WRITE_ONCE(ctx->sk->sk_validate_xmit_skb, tls_validate_xmit_skb_sw);
1360 
1361 		/* Stop the RX and TX resync.
1362 		 * tls_dev_resync must not be called after tls_dev_del.
1363 		 */
1364 		rcu_assign_pointer(ctx->netdev, NULL);
1365 
1366 		/* Start skipping the RX resync logic completely. */
1367 		set_bit(TLS_RX_DEV_DEGRADED, &ctx->flags);
1368 
1369 		/* Sync with inflight packets. After this point:
1370 		 * TX: no non-encrypted packets will be passed to the driver.
1371 		 * RX: resync requests from the driver will be ignored.
1372 		 */
1373 		synchronize_net();
1374 
1375 		/* Release the offload context on the driver side. */
1376 		if (ctx->tx_conf == TLS_HW)
1377 			netdev->tlsdev_ops->tls_dev_del(netdev, ctx,
1378 							TLS_OFFLOAD_CTX_DIR_TX);
1379 		if (ctx->rx_conf == TLS_HW &&
1380 		    !test_bit(TLS_RX_DEV_CLOSED, &ctx->flags))
1381 			netdev->tlsdev_ops->tls_dev_del(netdev, ctx,
1382 							TLS_OFFLOAD_CTX_DIR_RX);
1383 
1384 		dev_put(netdev);
1385 
1386 		/* Move the context to a separate list for two reasons:
1387 		 * 1. When the context is deallocated, list_del is called.
1388 		 * 2. It's no longer an offloaded context, so we don't want to
1389 		 *    run offload-specific code on this context.
1390 		 */
1391 		spin_lock_irqsave(&tls_device_lock, flags);
1392 		list_move_tail(&ctx->list, &tls_device_down_list);
1393 		spin_unlock_irqrestore(&tls_device_lock, flags);
1394 
1395 		/* Device contexts for RX and TX will be freed in on sk_destruct
1396 		 * by tls_device_free_ctx. rx_conf and tx_conf stay in TLS_HW.
1397 		 * Now release the ref taken above.
1398 		 */
1399 		if (refcount_dec_and_test(&ctx->refcount)) {
1400 			/* sk_destruct ran after tls_device_down took a ref, and
1401 			 * it returned early. Complete the destruction here.
1402 			 */
1403 			list_del(&ctx->list);
1404 			tls_device_free_ctx(ctx);
1405 		}
1406 	}
1407 
1408 	up_write(&device_offload_lock);
1409 
1410 	flush_workqueue(destruct_wq);
1411 
1412 	return NOTIFY_DONE;
1413 }
1414 
1415 static int tls_dev_event(struct notifier_block *this, unsigned long event,
1416 			 void *ptr)
1417 {
1418 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1419 
1420 	if (!dev->tlsdev_ops &&
1421 	    !(dev->features & (NETIF_F_HW_TLS_RX | NETIF_F_HW_TLS_TX)))
1422 		return NOTIFY_DONE;
1423 
1424 	switch (event) {
1425 	case NETDEV_REGISTER:
1426 	case NETDEV_FEAT_CHANGE:
1427 		if (netif_is_bond_master(dev))
1428 			return NOTIFY_DONE;
1429 		if ((dev->features & NETIF_F_HW_TLS_RX) &&
1430 		    !dev->tlsdev_ops->tls_dev_resync)
1431 			return NOTIFY_BAD;
1432 
1433 		if  (dev->tlsdev_ops &&
1434 		     dev->tlsdev_ops->tls_dev_add &&
1435 		     dev->tlsdev_ops->tls_dev_del)
1436 			return NOTIFY_DONE;
1437 		else
1438 			return NOTIFY_BAD;
1439 	case NETDEV_DOWN:
1440 		return tls_device_down(dev);
1441 	}
1442 	return NOTIFY_DONE;
1443 }
1444 
1445 static struct notifier_block tls_dev_notifier = {
1446 	.notifier_call	= tls_dev_event,
1447 };
1448 
1449 int __init tls_device_init(void)
1450 {
1451 	int err;
1452 
1453 	destruct_wq = alloc_workqueue("ktls_device_destruct", 0, 0);
1454 	if (!destruct_wq)
1455 		return -ENOMEM;
1456 
1457 	err = register_netdevice_notifier(&tls_dev_notifier);
1458 	if (err)
1459 		destroy_workqueue(destruct_wq);
1460 
1461 	return err;
1462 }
1463 
1464 void __exit tls_device_cleanup(void)
1465 {
1466 	unregister_netdevice_notifier(&tls_dev_notifier);
1467 	destroy_workqueue(destruct_wq);
1468 	clean_acked_data_flush();
1469 }
1470