xref: /linux/net/tls/tls_device.c (revision 2c63221cd9e5c0dad0424029aeb1c40faada8330)
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 "trace.h"
42 
43 /* device_offload_lock is used to synchronize tls_dev_add
44  * against NETDEV_DOWN notifications.
45  */
46 static DECLARE_RWSEM(device_offload_lock);
47 
48 static void tls_device_gc_task(struct work_struct *work);
49 
50 static DECLARE_WORK(tls_device_gc_work, tls_device_gc_task);
51 static LIST_HEAD(tls_device_gc_list);
52 static LIST_HEAD(tls_device_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_gc_task(struct work_struct *work)
70 {
71 	struct tls_context *ctx, *tmp;
72 	unsigned long flags;
73 	LIST_HEAD(gc_list);
74 
75 	spin_lock_irqsave(&tls_device_lock, flags);
76 	list_splice_init(&tls_device_gc_list, &gc_list);
77 	spin_unlock_irqrestore(&tls_device_lock, flags);
78 
79 	list_for_each_entry_safe(ctx, tmp, &gc_list, list) {
80 		struct net_device *netdev = ctx->netdev;
81 
82 		if (netdev && ctx->tx_conf == TLS_HW) {
83 			netdev->tlsdev_ops->tls_dev_del(netdev, ctx,
84 							TLS_OFFLOAD_CTX_DIR_TX);
85 			dev_put(netdev);
86 			ctx->netdev = NULL;
87 		}
88 
89 		list_del(&ctx->list);
90 		tls_device_free_ctx(ctx);
91 	}
92 }
93 
94 static void tls_device_queue_ctx_destruction(struct tls_context *ctx)
95 {
96 	unsigned long flags;
97 
98 	spin_lock_irqsave(&tls_device_lock, flags);
99 	list_move_tail(&ctx->list, &tls_device_gc_list);
100 
101 	/* schedule_work inside the spinlock
102 	 * to make sure tls_device_down waits for that work.
103 	 */
104 	schedule_work(&tls_device_gc_work);
105 
106 	spin_unlock_irqrestore(&tls_device_lock, flags);
107 }
108 
109 /* We assume that the socket is already connected */
110 static struct net_device *get_netdev_for_sock(struct sock *sk)
111 {
112 	struct dst_entry *dst = sk_dst_get(sk);
113 	struct net_device *netdev = NULL;
114 
115 	if (likely(dst)) {
116 		netdev = dst->dev;
117 		dev_hold(netdev);
118 	}
119 
120 	dst_release(dst);
121 
122 	return netdev;
123 }
124 
125 static void destroy_record(struct tls_record_info *record)
126 {
127 	int i;
128 
129 	for (i = 0; i < record->num_frags; i++)
130 		__skb_frag_unref(&record->frags[i]);
131 	kfree(record);
132 }
133 
134 static void delete_all_records(struct tls_offload_context_tx *offload_ctx)
135 {
136 	struct tls_record_info *info, *temp;
137 
138 	list_for_each_entry_safe(info, temp, &offload_ctx->records_list, list) {
139 		list_del(&info->list);
140 		destroy_record(info);
141 	}
142 
143 	offload_ctx->retransmit_hint = NULL;
144 }
145 
146 static void tls_icsk_clean_acked(struct sock *sk, u32 acked_seq)
147 {
148 	struct tls_context *tls_ctx = tls_get_ctx(sk);
149 	struct tls_record_info *info, *temp;
150 	struct tls_offload_context_tx *ctx;
151 	u64 deleted_records = 0;
152 	unsigned long flags;
153 
154 	if (!tls_ctx)
155 		return;
156 
157 	ctx = tls_offload_ctx_tx(tls_ctx);
158 
159 	spin_lock_irqsave(&ctx->lock, flags);
160 	info = ctx->retransmit_hint;
161 	if (info && !before(acked_seq, info->end_seq))
162 		ctx->retransmit_hint = NULL;
163 
164 	list_for_each_entry_safe(info, temp, &ctx->records_list, list) {
165 		if (before(acked_seq, info->end_seq))
166 			break;
167 		list_del(&info->list);
168 
169 		destroy_record(info);
170 		deleted_records++;
171 	}
172 
173 	ctx->unacked_record_sn += deleted_records;
174 	spin_unlock_irqrestore(&ctx->lock, flags);
175 }
176 
177 /* At this point, there should be no references on this
178  * socket and no in-flight SKBs associated with this
179  * socket, so it is safe to free all the resources.
180  */
181 static void tls_device_sk_destruct(struct sock *sk)
182 {
183 	struct tls_context *tls_ctx = tls_get_ctx(sk);
184 	struct tls_offload_context_tx *ctx = tls_offload_ctx_tx(tls_ctx);
185 
186 	tls_ctx->sk_destruct(sk);
187 
188 	if (tls_ctx->tx_conf == TLS_HW) {
189 		if (ctx->open_record)
190 			destroy_record(ctx->open_record);
191 		delete_all_records(ctx);
192 		crypto_free_aead(ctx->aead_send);
193 		clean_acked_data_disable(inet_csk(sk));
194 	}
195 
196 	if (refcount_dec_and_test(&tls_ctx->refcount))
197 		tls_device_queue_ctx_destruction(tls_ctx);
198 }
199 
200 void tls_device_free_resources_tx(struct sock *sk)
201 {
202 	struct tls_context *tls_ctx = tls_get_ctx(sk);
203 
204 	tls_free_partial_record(sk, tls_ctx);
205 }
206 
207 void tls_offload_tx_resync_request(struct sock *sk, u32 got_seq, u32 exp_seq)
208 {
209 	struct tls_context *tls_ctx = tls_get_ctx(sk);
210 
211 	trace_tls_device_tx_resync_req(sk, got_seq, exp_seq);
212 	WARN_ON(test_and_set_bit(TLS_TX_SYNC_SCHED, &tls_ctx->flags));
213 }
214 EXPORT_SYMBOL_GPL(tls_offload_tx_resync_request);
215 
216 static void tls_device_resync_tx(struct sock *sk, struct tls_context *tls_ctx,
217 				 u32 seq)
218 {
219 	struct net_device *netdev;
220 	struct sk_buff *skb;
221 	int err = 0;
222 	u8 *rcd_sn;
223 
224 	skb = tcp_write_queue_tail(sk);
225 	if (skb)
226 		TCP_SKB_CB(skb)->eor = 1;
227 
228 	rcd_sn = tls_ctx->tx.rec_seq;
229 
230 	trace_tls_device_tx_resync_send(sk, seq, rcd_sn);
231 	down_read(&device_offload_lock);
232 	netdev = tls_ctx->netdev;
233 	if (netdev)
234 		err = netdev->tlsdev_ops->tls_dev_resync(netdev, sk, seq,
235 							 rcd_sn,
236 							 TLS_OFFLOAD_CTX_DIR_TX);
237 	up_read(&device_offload_lock);
238 	if (err)
239 		return;
240 
241 	clear_bit_unlock(TLS_TX_SYNC_SCHED, &tls_ctx->flags);
242 }
243 
244 static void tls_append_frag(struct tls_record_info *record,
245 			    struct page_frag *pfrag,
246 			    int size)
247 {
248 	skb_frag_t *frag;
249 
250 	frag = &record->frags[record->num_frags - 1];
251 	if (skb_frag_page(frag) == pfrag->page &&
252 	    skb_frag_off(frag) + skb_frag_size(frag) == pfrag->offset) {
253 		skb_frag_size_add(frag, size);
254 	} else {
255 		++frag;
256 		__skb_frag_set_page(frag, pfrag->page);
257 		skb_frag_off_set(frag, pfrag->offset);
258 		skb_frag_size_set(frag, size);
259 		++record->num_frags;
260 		get_page(pfrag->page);
261 	}
262 
263 	pfrag->offset += size;
264 	record->len += size;
265 }
266 
267 static int tls_push_record(struct sock *sk,
268 			   struct tls_context *ctx,
269 			   struct tls_offload_context_tx *offload_ctx,
270 			   struct tls_record_info *record,
271 			   int flags)
272 {
273 	struct tls_prot_info *prot = &ctx->prot_info;
274 	struct tcp_sock *tp = tcp_sk(sk);
275 	skb_frag_t *frag;
276 	int i;
277 
278 	record->end_seq = tp->write_seq + record->len;
279 	list_add_tail_rcu(&record->list, &offload_ctx->records_list);
280 	offload_ctx->open_record = NULL;
281 
282 	if (test_bit(TLS_TX_SYNC_SCHED, &ctx->flags))
283 		tls_device_resync_tx(sk, ctx, tp->write_seq);
284 
285 	tls_advance_record_sn(sk, prot, &ctx->tx);
286 
287 	for (i = 0; i < record->num_frags; i++) {
288 		frag = &record->frags[i];
289 		sg_unmark_end(&offload_ctx->sg_tx_data[i]);
290 		sg_set_page(&offload_ctx->sg_tx_data[i], skb_frag_page(frag),
291 			    skb_frag_size(frag), skb_frag_off(frag));
292 		sk_mem_charge(sk, skb_frag_size(frag));
293 		get_page(skb_frag_page(frag));
294 	}
295 	sg_mark_end(&offload_ctx->sg_tx_data[record->num_frags - 1]);
296 
297 	/* all ready, send */
298 	return tls_push_sg(sk, ctx, offload_ctx->sg_tx_data, 0, flags);
299 }
300 
301 static int tls_device_record_close(struct sock *sk,
302 				   struct tls_context *ctx,
303 				   struct tls_record_info *record,
304 				   struct page_frag *pfrag,
305 				   unsigned char record_type)
306 {
307 	struct tls_prot_info *prot = &ctx->prot_info;
308 	int ret;
309 
310 	/* append tag
311 	 * device will fill in the tag, we just need to append a placeholder
312 	 * use socket memory to improve coalescing (re-using a single buffer
313 	 * increases frag count)
314 	 * if we can't allocate memory now, steal some back from data
315 	 */
316 	if (likely(skb_page_frag_refill(prot->tag_size, pfrag,
317 					sk->sk_allocation))) {
318 		ret = 0;
319 		tls_append_frag(record, pfrag, prot->tag_size);
320 	} else {
321 		ret = prot->tag_size;
322 		if (record->len <= prot->overhead_size)
323 			return -ENOMEM;
324 	}
325 
326 	/* fill prepend */
327 	tls_fill_prepend(ctx, skb_frag_address(&record->frags[0]),
328 			 record->len - prot->overhead_size,
329 			 record_type, prot->version);
330 	return ret;
331 }
332 
333 static int tls_create_new_record(struct tls_offload_context_tx *offload_ctx,
334 				 struct page_frag *pfrag,
335 				 size_t prepend_size)
336 {
337 	struct tls_record_info *record;
338 	skb_frag_t *frag;
339 
340 	record = kmalloc(sizeof(*record), GFP_KERNEL);
341 	if (!record)
342 		return -ENOMEM;
343 
344 	frag = &record->frags[0];
345 	__skb_frag_set_page(frag, pfrag->page);
346 	skb_frag_off_set(frag, pfrag->offset);
347 	skb_frag_size_set(frag, prepend_size);
348 
349 	get_page(pfrag->page);
350 	pfrag->offset += prepend_size;
351 
352 	record->num_frags = 1;
353 	record->len = prepend_size;
354 	offload_ctx->open_record = record;
355 	return 0;
356 }
357 
358 static int tls_do_allocation(struct sock *sk,
359 			     struct tls_offload_context_tx *offload_ctx,
360 			     struct page_frag *pfrag,
361 			     size_t prepend_size)
362 {
363 	int ret;
364 
365 	if (!offload_ctx->open_record) {
366 		if (unlikely(!skb_page_frag_refill(prepend_size, pfrag,
367 						   sk->sk_allocation))) {
368 			sk->sk_prot->enter_memory_pressure(sk);
369 			sk_stream_moderate_sndbuf(sk);
370 			return -ENOMEM;
371 		}
372 
373 		ret = tls_create_new_record(offload_ctx, pfrag, prepend_size);
374 		if (ret)
375 			return ret;
376 
377 		if (pfrag->size > pfrag->offset)
378 			return 0;
379 	}
380 
381 	if (!sk_page_frag_refill(sk, pfrag))
382 		return -ENOMEM;
383 
384 	return 0;
385 }
386 
387 static int tls_device_copy_data(void *addr, size_t bytes, struct iov_iter *i)
388 {
389 	size_t pre_copy, nocache;
390 
391 	pre_copy = ~((unsigned long)addr - 1) & (SMP_CACHE_BYTES - 1);
392 	if (pre_copy) {
393 		pre_copy = min(pre_copy, bytes);
394 		if (copy_from_iter(addr, pre_copy, i) != pre_copy)
395 			return -EFAULT;
396 		bytes -= pre_copy;
397 		addr += pre_copy;
398 	}
399 
400 	nocache = round_down(bytes, SMP_CACHE_BYTES);
401 	if (copy_from_iter_nocache(addr, nocache, i) != nocache)
402 		return -EFAULT;
403 	bytes -= nocache;
404 	addr += nocache;
405 
406 	if (bytes && copy_from_iter(addr, bytes, i) != bytes)
407 		return -EFAULT;
408 
409 	return 0;
410 }
411 
412 static int tls_push_data(struct sock *sk,
413 			 struct iov_iter *msg_iter,
414 			 size_t size, int flags,
415 			 unsigned char record_type)
416 {
417 	struct tls_context *tls_ctx = tls_get_ctx(sk);
418 	struct tls_prot_info *prot = &tls_ctx->prot_info;
419 	struct tls_offload_context_tx *ctx = tls_offload_ctx_tx(tls_ctx);
420 	int more = flags & (MSG_SENDPAGE_NOTLAST | MSG_MORE);
421 	struct tls_record_info *record = ctx->open_record;
422 	int tls_push_record_flags;
423 	struct page_frag *pfrag;
424 	size_t orig_size = size;
425 	u32 max_open_record_len;
426 	int copy, rc = 0;
427 	bool done = false;
428 	long timeo;
429 
430 	if (flags &
431 	    ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL | MSG_SENDPAGE_NOTLAST))
432 		return -ENOTSUPP;
433 
434 	if (unlikely(sk->sk_err))
435 		return -sk->sk_err;
436 
437 	flags |= MSG_SENDPAGE_DECRYPTED;
438 	tls_push_record_flags = flags | MSG_SENDPAGE_NOTLAST;
439 
440 	timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
441 	if (tls_is_partially_sent_record(tls_ctx)) {
442 		rc = tls_push_partial_record(sk, tls_ctx, flags);
443 		if (rc < 0)
444 			return rc;
445 	}
446 
447 	pfrag = sk_page_frag(sk);
448 
449 	/* TLS_HEADER_SIZE is not counted as part of the TLS record, and
450 	 * we need to leave room for an authentication tag.
451 	 */
452 	max_open_record_len = TLS_MAX_PAYLOAD_SIZE +
453 			      prot->prepend_size;
454 	do {
455 		rc = tls_do_allocation(sk, ctx, pfrag, prot->prepend_size);
456 		if (unlikely(rc)) {
457 			rc = sk_stream_wait_memory(sk, &timeo);
458 			if (!rc)
459 				continue;
460 
461 			record = ctx->open_record;
462 			if (!record)
463 				break;
464 handle_error:
465 			if (record_type != TLS_RECORD_TYPE_DATA) {
466 				/* avoid sending partial
467 				 * record with type !=
468 				 * application_data
469 				 */
470 				size = orig_size;
471 				destroy_record(record);
472 				ctx->open_record = NULL;
473 			} else if (record->len > prot->prepend_size) {
474 				goto last_record;
475 			}
476 
477 			break;
478 		}
479 
480 		record = ctx->open_record;
481 		copy = min_t(size_t, size, (pfrag->size - pfrag->offset));
482 		copy = min_t(size_t, copy, (max_open_record_len - record->len));
483 
484 		rc = tls_device_copy_data(page_address(pfrag->page) +
485 					  pfrag->offset, copy, msg_iter);
486 		if (rc)
487 			goto handle_error;
488 		tls_append_frag(record, pfrag, copy);
489 
490 		size -= copy;
491 		if (!size) {
492 last_record:
493 			tls_push_record_flags = flags;
494 			if (more) {
495 				tls_ctx->pending_open_record_frags =
496 						!!record->num_frags;
497 				break;
498 			}
499 
500 			done = true;
501 		}
502 
503 		if (done || record->len >= max_open_record_len ||
504 		    (record->num_frags >= MAX_SKB_FRAGS - 1)) {
505 			rc = tls_device_record_close(sk, tls_ctx, record,
506 						     pfrag, record_type);
507 			if (rc) {
508 				if (rc > 0) {
509 					size += rc;
510 				} else {
511 					size = orig_size;
512 					destroy_record(record);
513 					ctx->open_record = NULL;
514 					break;
515 				}
516 			}
517 
518 			rc = tls_push_record(sk,
519 					     tls_ctx,
520 					     ctx,
521 					     record,
522 					     tls_push_record_flags);
523 			if (rc < 0)
524 				break;
525 		}
526 	} while (!done);
527 
528 	if (orig_size - size > 0)
529 		rc = orig_size - size;
530 
531 	return rc;
532 }
533 
534 int tls_device_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
535 {
536 	unsigned char record_type = TLS_RECORD_TYPE_DATA;
537 	int rc;
538 
539 	lock_sock(sk);
540 
541 	if (unlikely(msg->msg_controllen)) {
542 		rc = tls_proccess_cmsg(sk, msg, &record_type);
543 		if (rc)
544 			goto out;
545 	}
546 
547 	rc = tls_push_data(sk, &msg->msg_iter, size,
548 			   msg->msg_flags, record_type);
549 
550 out:
551 	release_sock(sk);
552 	return rc;
553 }
554 
555 int tls_device_sendpage(struct sock *sk, struct page *page,
556 			int offset, size_t size, int flags)
557 {
558 	struct iov_iter	msg_iter;
559 	char *kaddr = kmap(page);
560 	struct kvec iov;
561 	int rc;
562 
563 	if (flags & MSG_SENDPAGE_NOTLAST)
564 		flags |= MSG_MORE;
565 
566 	lock_sock(sk);
567 
568 	if (flags & MSG_OOB) {
569 		rc = -ENOTSUPP;
570 		goto out;
571 	}
572 
573 	iov.iov_base = kaddr + offset;
574 	iov.iov_len = size;
575 	iov_iter_kvec(&msg_iter, WRITE, &iov, 1, size);
576 	rc = tls_push_data(sk, &msg_iter, size,
577 			   flags, TLS_RECORD_TYPE_DATA);
578 	kunmap(page);
579 
580 out:
581 	release_sock(sk);
582 	return rc;
583 }
584 
585 struct tls_record_info *tls_get_record(struct tls_offload_context_tx *context,
586 				       u32 seq, u64 *p_record_sn)
587 {
588 	u64 record_sn = context->hint_record_sn;
589 	struct tls_record_info *info;
590 
591 	info = context->retransmit_hint;
592 	if (!info ||
593 	    before(seq, info->end_seq - info->len)) {
594 		/* if retransmit_hint is irrelevant start
595 		 * from the beggining of the list
596 		 */
597 		info = list_first_entry_or_null(&context->records_list,
598 						struct tls_record_info, list);
599 		if (!info)
600 			return NULL;
601 		record_sn = context->unacked_record_sn;
602 	}
603 
604 	/* We just need the _rcu for the READ_ONCE() */
605 	rcu_read_lock();
606 	list_for_each_entry_from_rcu(info, &context->records_list, list) {
607 		if (before(seq, info->end_seq)) {
608 			if (!context->retransmit_hint ||
609 			    after(info->end_seq,
610 				  context->retransmit_hint->end_seq)) {
611 				context->hint_record_sn = record_sn;
612 				context->retransmit_hint = info;
613 			}
614 			*p_record_sn = record_sn;
615 			goto exit_rcu_unlock;
616 		}
617 		record_sn++;
618 	}
619 	info = NULL;
620 
621 exit_rcu_unlock:
622 	rcu_read_unlock();
623 	return info;
624 }
625 EXPORT_SYMBOL(tls_get_record);
626 
627 static int tls_device_push_pending_record(struct sock *sk, int flags)
628 {
629 	struct iov_iter	msg_iter;
630 
631 	iov_iter_kvec(&msg_iter, WRITE, NULL, 0, 0);
632 	return tls_push_data(sk, &msg_iter, 0, flags, TLS_RECORD_TYPE_DATA);
633 }
634 
635 void tls_device_write_space(struct sock *sk, struct tls_context *ctx)
636 {
637 	if (!sk->sk_write_pending && tls_is_partially_sent_record(ctx)) {
638 		gfp_t sk_allocation = sk->sk_allocation;
639 
640 		sk->sk_allocation = GFP_ATOMIC;
641 		tls_push_partial_record(sk, ctx,
642 					MSG_DONTWAIT | MSG_NOSIGNAL |
643 					MSG_SENDPAGE_DECRYPTED);
644 		sk->sk_allocation = sk_allocation;
645 	}
646 }
647 
648 static void tls_device_resync_rx(struct tls_context *tls_ctx,
649 				 struct sock *sk, u32 seq, u8 *rcd_sn)
650 {
651 	struct tls_offload_context_rx *rx_ctx = tls_offload_ctx_rx(tls_ctx);
652 	struct net_device *netdev;
653 
654 	if (WARN_ON(test_and_set_bit(TLS_RX_SYNC_RUNNING, &tls_ctx->flags)))
655 		return;
656 
657 	trace_tls_device_rx_resync_send(sk, seq, rcd_sn, rx_ctx->resync_type);
658 	netdev = READ_ONCE(tls_ctx->netdev);
659 	if (netdev)
660 		netdev->tlsdev_ops->tls_dev_resync(netdev, sk, seq, rcd_sn,
661 						   TLS_OFFLOAD_CTX_DIR_RX);
662 	clear_bit_unlock(TLS_RX_SYNC_RUNNING, &tls_ctx->flags);
663 	TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXDEVICERESYNC);
664 }
665 
666 void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq)
667 {
668 	struct tls_context *tls_ctx = tls_get_ctx(sk);
669 	struct tls_offload_context_rx *rx_ctx;
670 	u8 rcd_sn[TLS_MAX_REC_SEQ_SIZE];
671 	u32 sock_data, is_req_pending;
672 	struct tls_prot_info *prot;
673 	s64 resync_req;
674 	u32 req_seq;
675 
676 	if (tls_ctx->rx_conf != TLS_HW)
677 		return;
678 
679 	prot = &tls_ctx->prot_info;
680 	rx_ctx = tls_offload_ctx_rx(tls_ctx);
681 	memcpy(rcd_sn, tls_ctx->rx.rec_seq, prot->rec_seq_size);
682 
683 	switch (rx_ctx->resync_type) {
684 	case TLS_OFFLOAD_SYNC_TYPE_DRIVER_REQ:
685 		resync_req = atomic64_read(&rx_ctx->resync_req);
686 		req_seq = resync_req >> 32;
687 		seq += TLS_HEADER_SIZE - 1;
688 		is_req_pending = resync_req;
689 
690 		if (likely(!is_req_pending) || req_seq != seq ||
691 		    !atomic64_try_cmpxchg(&rx_ctx->resync_req, &resync_req, 0))
692 			return;
693 		break;
694 	case TLS_OFFLOAD_SYNC_TYPE_CORE_NEXT_HINT:
695 		if (likely(!rx_ctx->resync_nh_do_now))
696 			return;
697 
698 		/* head of next rec is already in, note that the sock_inq will
699 		 * include the currently parsed message when called from parser
700 		 */
701 		sock_data = tcp_inq(sk);
702 		if (sock_data > rcd_len) {
703 			trace_tls_device_rx_resync_nh_delay(sk, sock_data,
704 							    rcd_len);
705 			return;
706 		}
707 
708 		rx_ctx->resync_nh_do_now = 0;
709 		seq += rcd_len;
710 		tls_bigint_increment(rcd_sn, prot->rec_seq_size);
711 		break;
712 	}
713 
714 	tls_device_resync_rx(tls_ctx, sk, seq, rcd_sn);
715 }
716 
717 static void tls_device_core_ctrl_rx_resync(struct tls_context *tls_ctx,
718 					   struct tls_offload_context_rx *ctx,
719 					   struct sock *sk, struct sk_buff *skb)
720 {
721 	struct strp_msg *rxm;
722 
723 	/* device will request resyncs by itself based on stream scan */
724 	if (ctx->resync_type != TLS_OFFLOAD_SYNC_TYPE_CORE_NEXT_HINT)
725 		return;
726 	/* already scheduled */
727 	if (ctx->resync_nh_do_now)
728 		return;
729 	/* seen decrypted fragments since last fully-failed record */
730 	if (ctx->resync_nh_reset) {
731 		ctx->resync_nh_reset = 0;
732 		ctx->resync_nh.decrypted_failed = 1;
733 		ctx->resync_nh.decrypted_tgt = TLS_DEVICE_RESYNC_NH_START_IVAL;
734 		return;
735 	}
736 
737 	if (++ctx->resync_nh.decrypted_failed <= ctx->resync_nh.decrypted_tgt)
738 		return;
739 
740 	/* doing resync, bump the next target in case it fails */
741 	if (ctx->resync_nh.decrypted_tgt < TLS_DEVICE_RESYNC_NH_MAX_IVAL)
742 		ctx->resync_nh.decrypted_tgt *= 2;
743 	else
744 		ctx->resync_nh.decrypted_tgt += TLS_DEVICE_RESYNC_NH_MAX_IVAL;
745 
746 	rxm = strp_msg(skb);
747 
748 	/* head of next rec is already in, parser will sync for us */
749 	if (tcp_inq(sk) > rxm->full_len) {
750 		trace_tls_device_rx_resync_nh_schedule(sk);
751 		ctx->resync_nh_do_now = 1;
752 	} else {
753 		struct tls_prot_info *prot = &tls_ctx->prot_info;
754 		u8 rcd_sn[TLS_MAX_REC_SEQ_SIZE];
755 
756 		memcpy(rcd_sn, tls_ctx->rx.rec_seq, prot->rec_seq_size);
757 		tls_bigint_increment(rcd_sn, prot->rec_seq_size);
758 
759 		tls_device_resync_rx(tls_ctx, sk, tcp_sk(sk)->copied_seq,
760 				     rcd_sn);
761 	}
762 }
763 
764 static int tls_device_reencrypt(struct sock *sk, struct sk_buff *skb)
765 {
766 	struct strp_msg *rxm = strp_msg(skb);
767 	int err = 0, offset = rxm->offset, copy, nsg, data_len, pos;
768 	struct sk_buff *skb_iter, *unused;
769 	struct scatterlist sg[1];
770 	char *orig_buf, *buf;
771 
772 	orig_buf = kmalloc(rxm->full_len + TLS_HEADER_SIZE +
773 			   TLS_CIPHER_AES_GCM_128_IV_SIZE, sk->sk_allocation);
774 	if (!orig_buf)
775 		return -ENOMEM;
776 	buf = orig_buf;
777 
778 	nsg = skb_cow_data(skb, 0, &unused);
779 	if (unlikely(nsg < 0)) {
780 		err = nsg;
781 		goto free_buf;
782 	}
783 
784 	sg_init_table(sg, 1);
785 	sg_set_buf(&sg[0], buf,
786 		   rxm->full_len + TLS_HEADER_SIZE +
787 		   TLS_CIPHER_AES_GCM_128_IV_SIZE);
788 	err = skb_copy_bits(skb, offset, buf,
789 			    TLS_HEADER_SIZE + TLS_CIPHER_AES_GCM_128_IV_SIZE);
790 	if (err)
791 		goto free_buf;
792 
793 	/* We are interested only in the decrypted data not the auth */
794 	err = decrypt_skb(sk, skb, sg);
795 	if (err != -EBADMSG)
796 		goto free_buf;
797 	else
798 		err = 0;
799 
800 	data_len = rxm->full_len - TLS_CIPHER_AES_GCM_128_TAG_SIZE;
801 
802 	if (skb_pagelen(skb) > offset) {
803 		copy = min_t(int, skb_pagelen(skb) - offset, data_len);
804 
805 		if (skb->decrypted) {
806 			err = skb_store_bits(skb, offset, buf, copy);
807 			if (err)
808 				goto free_buf;
809 		}
810 
811 		offset += copy;
812 		buf += copy;
813 	}
814 
815 	pos = skb_pagelen(skb);
816 	skb_walk_frags(skb, skb_iter) {
817 		int frag_pos;
818 
819 		/* Practically all frags must belong to msg if reencrypt
820 		 * is needed with current strparser and coalescing logic,
821 		 * but strparser may "get optimized", so let's be safe.
822 		 */
823 		if (pos + skb_iter->len <= offset)
824 			goto done_with_frag;
825 		if (pos >= data_len + rxm->offset)
826 			break;
827 
828 		frag_pos = offset - pos;
829 		copy = min_t(int, skb_iter->len - frag_pos,
830 			     data_len + rxm->offset - offset);
831 
832 		if (skb_iter->decrypted) {
833 			err = skb_store_bits(skb_iter, frag_pos, buf, copy);
834 			if (err)
835 				goto free_buf;
836 		}
837 
838 		offset += copy;
839 		buf += copy;
840 done_with_frag:
841 		pos += skb_iter->len;
842 	}
843 
844 free_buf:
845 	kfree(orig_buf);
846 	return err;
847 }
848 
849 int tls_device_decrypted(struct sock *sk, struct tls_context *tls_ctx,
850 			 struct sk_buff *skb, struct strp_msg *rxm)
851 {
852 	struct tls_offload_context_rx *ctx = tls_offload_ctx_rx(tls_ctx);
853 	int is_decrypted = skb->decrypted;
854 	int is_encrypted = !is_decrypted;
855 	struct sk_buff *skb_iter;
856 
857 	/* Check if all the data is decrypted already */
858 	skb_walk_frags(skb, skb_iter) {
859 		is_decrypted &= skb_iter->decrypted;
860 		is_encrypted &= !skb_iter->decrypted;
861 	}
862 
863 	trace_tls_device_decrypted(sk, tcp_sk(sk)->copied_seq - rxm->full_len,
864 				   tls_ctx->rx.rec_seq, rxm->full_len,
865 				   is_encrypted, is_decrypted);
866 
867 	ctx->sw.decrypted |= is_decrypted;
868 
869 	/* Return immediately if the record is either entirely plaintext or
870 	 * entirely ciphertext. Otherwise handle reencrypt partially decrypted
871 	 * record.
872 	 */
873 	if (is_decrypted) {
874 		ctx->resync_nh_reset = 1;
875 		return 0;
876 	}
877 	if (is_encrypted) {
878 		tls_device_core_ctrl_rx_resync(tls_ctx, ctx, sk, skb);
879 		return 0;
880 	}
881 
882 	ctx->resync_nh_reset = 1;
883 	return tls_device_reencrypt(sk, skb);
884 }
885 
886 static void tls_device_attach(struct tls_context *ctx, struct sock *sk,
887 			      struct net_device *netdev)
888 {
889 	if (sk->sk_destruct != tls_device_sk_destruct) {
890 		refcount_set(&ctx->refcount, 1);
891 		dev_hold(netdev);
892 		ctx->netdev = netdev;
893 		spin_lock_irq(&tls_device_lock);
894 		list_add_tail(&ctx->list, &tls_device_list);
895 		spin_unlock_irq(&tls_device_lock);
896 
897 		ctx->sk_destruct = sk->sk_destruct;
898 		sk->sk_destruct = tls_device_sk_destruct;
899 	}
900 }
901 
902 int tls_set_device_offload(struct sock *sk, struct tls_context *ctx)
903 {
904 	u16 nonce_size, tag_size, iv_size, rec_seq_size;
905 	struct tls_context *tls_ctx = tls_get_ctx(sk);
906 	struct tls_prot_info *prot = &tls_ctx->prot_info;
907 	struct tls_record_info *start_marker_record;
908 	struct tls_offload_context_tx *offload_ctx;
909 	struct tls_crypto_info *crypto_info;
910 	struct net_device *netdev;
911 	char *iv, *rec_seq;
912 	struct sk_buff *skb;
913 	__be64 rcd_sn;
914 	int rc;
915 
916 	if (!ctx)
917 		return -EINVAL;
918 
919 	if (ctx->priv_ctx_tx)
920 		return -EEXIST;
921 
922 	start_marker_record = kmalloc(sizeof(*start_marker_record), GFP_KERNEL);
923 	if (!start_marker_record)
924 		return -ENOMEM;
925 
926 	offload_ctx = kzalloc(TLS_OFFLOAD_CONTEXT_SIZE_TX, GFP_KERNEL);
927 	if (!offload_ctx) {
928 		rc = -ENOMEM;
929 		goto free_marker_record;
930 	}
931 
932 	crypto_info = &ctx->crypto_send.info;
933 	if (crypto_info->version != TLS_1_2_VERSION) {
934 		rc = -EOPNOTSUPP;
935 		goto free_offload_ctx;
936 	}
937 
938 	switch (crypto_info->cipher_type) {
939 	case TLS_CIPHER_AES_GCM_128:
940 		nonce_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
941 		tag_size = TLS_CIPHER_AES_GCM_128_TAG_SIZE;
942 		iv_size = TLS_CIPHER_AES_GCM_128_IV_SIZE;
943 		iv = ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->iv;
944 		rec_seq_size = TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE;
945 		rec_seq =
946 		 ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->rec_seq;
947 		break;
948 	default:
949 		rc = -EINVAL;
950 		goto free_offload_ctx;
951 	}
952 
953 	/* Sanity-check the rec_seq_size for stack allocations */
954 	if (rec_seq_size > TLS_MAX_REC_SEQ_SIZE) {
955 		rc = -EINVAL;
956 		goto free_offload_ctx;
957 	}
958 
959 	prot->version = crypto_info->version;
960 	prot->cipher_type = crypto_info->cipher_type;
961 	prot->prepend_size = TLS_HEADER_SIZE + nonce_size;
962 	prot->tag_size = tag_size;
963 	prot->overhead_size = prot->prepend_size + prot->tag_size;
964 	prot->iv_size = iv_size;
965 	ctx->tx.iv = kmalloc(iv_size + TLS_CIPHER_AES_GCM_128_SALT_SIZE,
966 			     GFP_KERNEL);
967 	if (!ctx->tx.iv) {
968 		rc = -ENOMEM;
969 		goto free_offload_ctx;
970 	}
971 
972 	memcpy(ctx->tx.iv + TLS_CIPHER_AES_GCM_128_SALT_SIZE, iv, iv_size);
973 
974 	prot->rec_seq_size = rec_seq_size;
975 	ctx->tx.rec_seq = kmemdup(rec_seq, rec_seq_size, GFP_KERNEL);
976 	if (!ctx->tx.rec_seq) {
977 		rc = -ENOMEM;
978 		goto free_iv;
979 	}
980 
981 	rc = tls_sw_fallback_init(sk, offload_ctx, crypto_info);
982 	if (rc)
983 		goto free_rec_seq;
984 
985 	/* start at rec_seq - 1 to account for the start marker record */
986 	memcpy(&rcd_sn, ctx->tx.rec_seq, sizeof(rcd_sn));
987 	offload_ctx->unacked_record_sn = be64_to_cpu(rcd_sn) - 1;
988 
989 	start_marker_record->end_seq = tcp_sk(sk)->write_seq;
990 	start_marker_record->len = 0;
991 	start_marker_record->num_frags = 0;
992 
993 	INIT_LIST_HEAD(&offload_ctx->records_list);
994 	list_add_tail(&start_marker_record->list, &offload_ctx->records_list);
995 	spin_lock_init(&offload_ctx->lock);
996 	sg_init_table(offload_ctx->sg_tx_data,
997 		      ARRAY_SIZE(offload_ctx->sg_tx_data));
998 
999 	clean_acked_data_enable(inet_csk(sk), &tls_icsk_clean_acked);
1000 	ctx->push_pending_record = tls_device_push_pending_record;
1001 
1002 	/* TLS offload is greatly simplified if we don't send
1003 	 * SKBs where only part of the payload needs to be encrypted.
1004 	 * So mark the last skb in the write queue as end of record.
1005 	 */
1006 	skb = tcp_write_queue_tail(sk);
1007 	if (skb)
1008 		TCP_SKB_CB(skb)->eor = 1;
1009 
1010 	netdev = get_netdev_for_sock(sk);
1011 	if (!netdev) {
1012 		pr_err_ratelimited("%s: netdev not found\n", __func__);
1013 		rc = -EINVAL;
1014 		goto disable_cad;
1015 	}
1016 
1017 	if (!(netdev->features & NETIF_F_HW_TLS_TX)) {
1018 		rc = -ENOTSUPP;
1019 		goto release_netdev;
1020 	}
1021 
1022 	/* Avoid offloading if the device is down
1023 	 * We don't want to offload new flows after
1024 	 * the NETDEV_DOWN event
1025 	 *
1026 	 * device_offload_lock is taken in tls_devices's NETDEV_DOWN
1027 	 * handler thus protecting from the device going down before
1028 	 * ctx was added to tls_device_list.
1029 	 */
1030 	down_read(&device_offload_lock);
1031 	if (!(netdev->flags & IFF_UP)) {
1032 		rc = -EINVAL;
1033 		goto release_lock;
1034 	}
1035 
1036 	ctx->priv_ctx_tx = offload_ctx;
1037 	rc = netdev->tlsdev_ops->tls_dev_add(netdev, sk, TLS_OFFLOAD_CTX_DIR_TX,
1038 					     &ctx->crypto_send.info,
1039 					     tcp_sk(sk)->write_seq);
1040 	trace_tls_device_offload_set(sk, TLS_OFFLOAD_CTX_DIR_TX,
1041 				     tcp_sk(sk)->write_seq, rec_seq, rc);
1042 	if (rc)
1043 		goto release_lock;
1044 
1045 	tls_device_attach(ctx, sk, netdev);
1046 	up_read(&device_offload_lock);
1047 
1048 	/* following this assignment tls_is_sk_tx_device_offloaded
1049 	 * will return true and the context might be accessed
1050 	 * by the netdev's xmit function.
1051 	 */
1052 	smp_store_release(&sk->sk_validate_xmit_skb, tls_validate_xmit_skb);
1053 	dev_put(netdev);
1054 
1055 	return 0;
1056 
1057 release_lock:
1058 	up_read(&device_offload_lock);
1059 release_netdev:
1060 	dev_put(netdev);
1061 disable_cad:
1062 	clean_acked_data_disable(inet_csk(sk));
1063 	crypto_free_aead(offload_ctx->aead_send);
1064 free_rec_seq:
1065 	kfree(ctx->tx.rec_seq);
1066 free_iv:
1067 	kfree(ctx->tx.iv);
1068 free_offload_ctx:
1069 	kfree(offload_ctx);
1070 	ctx->priv_ctx_tx = NULL;
1071 free_marker_record:
1072 	kfree(start_marker_record);
1073 	return rc;
1074 }
1075 
1076 int tls_set_device_offload_rx(struct sock *sk, struct tls_context *ctx)
1077 {
1078 	struct tls12_crypto_info_aes_gcm_128 *info;
1079 	struct tls_offload_context_rx *context;
1080 	struct net_device *netdev;
1081 	int rc = 0;
1082 
1083 	if (ctx->crypto_recv.info.version != TLS_1_2_VERSION)
1084 		return -EOPNOTSUPP;
1085 
1086 	netdev = get_netdev_for_sock(sk);
1087 	if (!netdev) {
1088 		pr_err_ratelimited("%s: netdev not found\n", __func__);
1089 		return -EINVAL;
1090 	}
1091 
1092 	if (!(netdev->features & NETIF_F_HW_TLS_RX)) {
1093 		rc = -ENOTSUPP;
1094 		goto release_netdev;
1095 	}
1096 
1097 	/* Avoid offloading if the device is down
1098 	 * We don't want to offload new flows after
1099 	 * the NETDEV_DOWN event
1100 	 *
1101 	 * device_offload_lock is taken in tls_devices's NETDEV_DOWN
1102 	 * handler thus protecting from the device going down before
1103 	 * ctx was added to tls_device_list.
1104 	 */
1105 	down_read(&device_offload_lock);
1106 	if (!(netdev->flags & IFF_UP)) {
1107 		rc = -EINVAL;
1108 		goto release_lock;
1109 	}
1110 
1111 	context = kzalloc(TLS_OFFLOAD_CONTEXT_SIZE_RX, GFP_KERNEL);
1112 	if (!context) {
1113 		rc = -ENOMEM;
1114 		goto release_lock;
1115 	}
1116 	context->resync_nh_reset = 1;
1117 
1118 	ctx->priv_ctx_rx = context;
1119 	rc = tls_set_sw_offload(sk, ctx, 0);
1120 	if (rc)
1121 		goto release_ctx;
1122 
1123 	rc = netdev->tlsdev_ops->tls_dev_add(netdev, sk, TLS_OFFLOAD_CTX_DIR_RX,
1124 					     &ctx->crypto_recv.info,
1125 					     tcp_sk(sk)->copied_seq);
1126 	info = (void *)&ctx->crypto_recv.info;
1127 	trace_tls_device_offload_set(sk, TLS_OFFLOAD_CTX_DIR_RX,
1128 				     tcp_sk(sk)->copied_seq, info->rec_seq, rc);
1129 	if (rc)
1130 		goto free_sw_resources;
1131 
1132 	tls_device_attach(ctx, sk, netdev);
1133 	up_read(&device_offload_lock);
1134 
1135 	dev_put(netdev);
1136 
1137 	return 0;
1138 
1139 free_sw_resources:
1140 	up_read(&device_offload_lock);
1141 	tls_sw_free_resources_rx(sk);
1142 	down_read(&device_offload_lock);
1143 release_ctx:
1144 	ctx->priv_ctx_rx = NULL;
1145 release_lock:
1146 	up_read(&device_offload_lock);
1147 release_netdev:
1148 	dev_put(netdev);
1149 	return rc;
1150 }
1151 
1152 void tls_device_offload_cleanup_rx(struct sock *sk)
1153 {
1154 	struct tls_context *tls_ctx = tls_get_ctx(sk);
1155 	struct net_device *netdev;
1156 
1157 	down_read(&device_offload_lock);
1158 	netdev = tls_ctx->netdev;
1159 	if (!netdev)
1160 		goto out;
1161 
1162 	netdev->tlsdev_ops->tls_dev_del(netdev, tls_ctx,
1163 					TLS_OFFLOAD_CTX_DIR_RX);
1164 
1165 	if (tls_ctx->tx_conf != TLS_HW) {
1166 		dev_put(netdev);
1167 		tls_ctx->netdev = NULL;
1168 	}
1169 out:
1170 	up_read(&device_offload_lock);
1171 	tls_sw_release_resources_rx(sk);
1172 }
1173 
1174 static int tls_device_down(struct net_device *netdev)
1175 {
1176 	struct tls_context *ctx, *tmp;
1177 	unsigned long flags;
1178 	LIST_HEAD(list);
1179 
1180 	/* Request a write lock to block new offload attempts */
1181 	down_write(&device_offload_lock);
1182 
1183 	spin_lock_irqsave(&tls_device_lock, flags);
1184 	list_for_each_entry_safe(ctx, tmp, &tls_device_list, list) {
1185 		if (ctx->netdev != netdev ||
1186 		    !refcount_inc_not_zero(&ctx->refcount))
1187 			continue;
1188 
1189 		list_move(&ctx->list, &list);
1190 	}
1191 	spin_unlock_irqrestore(&tls_device_lock, flags);
1192 
1193 	list_for_each_entry_safe(ctx, tmp, &list, list)	{
1194 		if (ctx->tx_conf == TLS_HW)
1195 			netdev->tlsdev_ops->tls_dev_del(netdev, ctx,
1196 							TLS_OFFLOAD_CTX_DIR_TX);
1197 		if (ctx->rx_conf == TLS_HW)
1198 			netdev->tlsdev_ops->tls_dev_del(netdev, ctx,
1199 							TLS_OFFLOAD_CTX_DIR_RX);
1200 		WRITE_ONCE(ctx->netdev, NULL);
1201 		smp_mb__before_atomic(); /* pairs with test_and_set_bit() */
1202 		while (test_bit(TLS_RX_SYNC_RUNNING, &ctx->flags))
1203 			usleep_range(10, 200);
1204 		dev_put(netdev);
1205 		list_del_init(&ctx->list);
1206 
1207 		if (refcount_dec_and_test(&ctx->refcount))
1208 			tls_device_free_ctx(ctx);
1209 	}
1210 
1211 	up_write(&device_offload_lock);
1212 
1213 	flush_work(&tls_device_gc_work);
1214 
1215 	return NOTIFY_DONE;
1216 }
1217 
1218 static int tls_dev_event(struct notifier_block *this, unsigned long event,
1219 			 void *ptr)
1220 {
1221 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1222 
1223 	if (!dev->tlsdev_ops &&
1224 	    !(dev->features & (NETIF_F_HW_TLS_RX | NETIF_F_HW_TLS_TX)))
1225 		return NOTIFY_DONE;
1226 
1227 	switch (event) {
1228 	case NETDEV_REGISTER:
1229 	case NETDEV_FEAT_CHANGE:
1230 		if ((dev->features & NETIF_F_HW_TLS_RX) &&
1231 		    !dev->tlsdev_ops->tls_dev_resync)
1232 			return NOTIFY_BAD;
1233 
1234 		if  (dev->tlsdev_ops &&
1235 		     dev->tlsdev_ops->tls_dev_add &&
1236 		     dev->tlsdev_ops->tls_dev_del)
1237 			return NOTIFY_DONE;
1238 		else
1239 			return NOTIFY_BAD;
1240 	case NETDEV_DOWN:
1241 		return tls_device_down(dev);
1242 	}
1243 	return NOTIFY_DONE;
1244 }
1245 
1246 static struct notifier_block tls_dev_notifier = {
1247 	.notifier_call	= tls_dev_event,
1248 };
1249 
1250 void __init tls_device_init(void)
1251 {
1252 	register_netdevice_notifier(&tls_dev_notifier);
1253 }
1254 
1255 void __exit tls_device_cleanup(void)
1256 {
1257 	unregister_netdevice_notifier(&tls_dev_notifier);
1258 	flush_work(&tls_device_gc_work);
1259 	clean_acked_data_flush();
1260 }
1261