xref: /freebsd/sys/kern/uipc_ktls.c (revision d65cd7a57bf0600b722afc770838a5d0c1c3a8e1)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2014-2019 Netflix Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_rss.h"
34 
35 #include <sys/param.h>
36 #include <sys/kernel.h>
37 #include <sys/ktls.h>
38 #include <sys/lock.h>
39 #include <sys/mbuf.h>
40 #include <sys/mutex.h>
41 #include <sys/rmlock.h>
42 #include <sys/proc.h>
43 #include <sys/protosw.h>
44 #include <sys/refcount.h>
45 #include <sys/smp.h>
46 #include <sys/socket.h>
47 #include <sys/socketvar.h>
48 #include <sys/sysctl.h>
49 #include <sys/taskqueue.h>
50 #include <sys/kthread.h>
51 #include <sys/uio.h>
52 #include <sys/vmmeter.h>
53 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
54 #include <machine/pcb.h>
55 #endif
56 #include <machine/vmparam.h>
57 #include <net/if.h>
58 #include <net/if_var.h>
59 #ifdef RSS
60 #include <net/netisr.h>
61 #include <net/nhop.h>
62 #include <net/rss_config.h>
63 #endif
64 #include <net/route.h>
65 #include <net/route/nhop.h>
66 #if defined(INET) || defined(INET6)
67 #include <netinet/in.h>
68 #include <netinet/in_pcb.h>
69 #endif
70 #include <netinet/tcp_var.h>
71 #ifdef TCP_OFFLOAD
72 #include <netinet/tcp_offload.h>
73 #endif
74 #include <opencrypto/xform.h>
75 #include <vm/uma_dbg.h>
76 #include <vm/vm.h>
77 #include <vm/vm_pageout.h>
78 #include <vm/vm_page.h>
79 
80 struct ktls_wq {
81 	struct mtx	mtx;
82 	STAILQ_HEAD(, mbuf) head;
83 	bool		running;
84 } __aligned(CACHE_LINE_SIZE);
85 
86 static struct ktls_wq *ktls_wq;
87 static struct proc *ktls_proc;
88 LIST_HEAD(, ktls_crypto_backend) ktls_backends;
89 static struct rmlock ktls_backends_lock;
90 static uma_zone_t ktls_session_zone;
91 static uint16_t ktls_cpuid_lookup[MAXCPU];
92 
93 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
94     "Kernel TLS offload");
95 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
96     "Kernel TLS offload stats");
97 
98 static int ktls_allow_unload;
99 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, allow_unload, CTLFLAG_RDTUN,
100     &ktls_allow_unload, 0, "Allow software crypto modules to unload");
101 
102 #ifdef RSS
103 static int ktls_bind_threads = 1;
104 #else
105 static int ktls_bind_threads;
106 #endif
107 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
108     &ktls_bind_threads, 0,
109     "Bind crypto threads to cores or domains at boot");
110 
111 static u_int ktls_maxlen = 16384;
112 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RWTUN,
113     &ktls_maxlen, 0, "Maximum TLS record size");
114 
115 static int ktls_number_threads;
116 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
117     &ktls_number_threads, 0,
118     "Number of TLS threads in thread-pool");
119 
120 static bool ktls_offload_enable;
121 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RW,
122     &ktls_offload_enable, 0,
123     "Enable support for kernel TLS offload");
124 
125 static bool ktls_cbc_enable = true;
126 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RW,
127     &ktls_cbc_enable, 1,
128     "Enable Support of AES-CBC crypto for kernel TLS");
129 
130 static counter_u64_t ktls_tasks_active;
131 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
132     &ktls_tasks_active, "Number of active tasks");
133 
134 static counter_u64_t ktls_cnt_on;
135 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, so_inqueue, CTLFLAG_RD,
136     &ktls_cnt_on, "Number of TLS records in queue to tasks for SW crypto");
137 
138 static counter_u64_t ktls_offload_total;
139 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
140     CTLFLAG_RD, &ktls_offload_total,
141     "Total successful TLS setups (parameters set)");
142 
143 static counter_u64_t ktls_offload_enable_calls;
144 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
145     CTLFLAG_RD, &ktls_offload_enable_calls,
146     "Total number of TLS enable calls made");
147 
148 static counter_u64_t ktls_offload_active;
149 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
150     &ktls_offload_active, "Total Active TLS sessions");
151 
152 static counter_u64_t ktls_offload_failed_crypto;
153 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
154     &ktls_offload_failed_crypto, "Total TLS crypto failures");
155 
156 static counter_u64_t ktls_switch_to_ifnet;
157 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
158     &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
159 
160 static counter_u64_t ktls_switch_to_sw;
161 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
162     &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
163 
164 static counter_u64_t ktls_switch_failed;
165 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
166     &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
167 
168 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
169     "Software TLS session stats");
170 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
171     "Hardware (ifnet) TLS session stats");
172 #ifdef TCP_OFFLOAD
173 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
174     "TOE TLS session stats");
175 #endif
176 
177 static counter_u64_t ktls_sw_cbc;
178 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
179     "Active number of software TLS sessions using AES-CBC");
180 
181 static counter_u64_t ktls_sw_gcm;
182 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
183     "Active number of software TLS sessions using AES-GCM");
184 
185 static counter_u64_t ktls_ifnet_cbc;
186 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
187     &ktls_ifnet_cbc,
188     "Active number of ifnet TLS sessions using AES-CBC");
189 
190 static counter_u64_t ktls_ifnet_gcm;
191 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
192     &ktls_ifnet_gcm,
193     "Active number of ifnet TLS sessions using AES-GCM");
194 
195 static counter_u64_t ktls_ifnet_reset;
196 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
197     &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
198 
199 static counter_u64_t ktls_ifnet_reset_dropped;
200 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
201     &ktls_ifnet_reset_dropped,
202     "TLS sessions dropped after failing to update ifnet send tag");
203 
204 static counter_u64_t ktls_ifnet_reset_failed;
205 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
206     &ktls_ifnet_reset_failed,
207     "TLS sessions that failed to allocate a new ifnet send tag");
208 
209 static int ktls_ifnet_permitted;
210 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
211     &ktls_ifnet_permitted, 1,
212     "Whether to permit hardware (ifnet) TLS sessions");
213 
214 #ifdef TCP_OFFLOAD
215 static counter_u64_t ktls_toe_cbc;
216 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
217     &ktls_toe_cbc,
218     "Active number of TOE TLS sessions using AES-CBC");
219 
220 static counter_u64_t ktls_toe_gcm;
221 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
222     &ktls_toe_gcm,
223     "Active number of TOE TLS sessions using AES-GCM");
224 #endif
225 
226 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
227 
228 static void ktls_cleanup(struct ktls_session *tls);
229 #if defined(INET) || defined(INET6)
230 static void ktls_reset_send_tag(void *context, int pending);
231 #endif
232 static void ktls_work_thread(void *ctx);
233 
234 int
235 ktls_crypto_backend_register(struct ktls_crypto_backend *be)
236 {
237 	struct ktls_crypto_backend *curr_be, *tmp;
238 
239 	if (be->api_version != KTLS_API_VERSION) {
240 		printf("KTLS: API version mismatch (%d vs %d) for %s\n",
241 		    be->api_version, KTLS_API_VERSION,
242 		    be->name);
243 		return (EINVAL);
244 	}
245 
246 	rm_wlock(&ktls_backends_lock);
247 	printf("KTLS: Registering crypto method %s with prio %d\n",
248 	       be->name, be->prio);
249 	if (LIST_EMPTY(&ktls_backends)) {
250 		LIST_INSERT_HEAD(&ktls_backends, be, next);
251 	} else {
252 		LIST_FOREACH_SAFE(curr_be, &ktls_backends, next, tmp) {
253 			if (curr_be->prio < be->prio) {
254 				LIST_INSERT_BEFORE(curr_be, be, next);
255 				break;
256 			}
257 			if (LIST_NEXT(curr_be, next) == NULL) {
258 				LIST_INSERT_AFTER(curr_be, be, next);
259 				break;
260 			}
261 		}
262 	}
263 	rm_wunlock(&ktls_backends_lock);
264 	return (0);
265 }
266 
267 int
268 ktls_crypto_backend_deregister(struct ktls_crypto_backend *be)
269 {
270 	struct ktls_crypto_backend *tmp;
271 
272 	/*
273 	 * Don't error if the backend isn't registered.  This permits
274 	 * MOD_UNLOAD handlers to use this function unconditionally.
275 	 */
276 	rm_wlock(&ktls_backends_lock);
277 	LIST_FOREACH(tmp, &ktls_backends, next) {
278 		if (tmp == be)
279 			break;
280 	}
281 	if (tmp == NULL) {
282 		rm_wunlock(&ktls_backends_lock);
283 		return (0);
284 	}
285 
286 	if (!ktls_allow_unload) {
287 		rm_wunlock(&ktls_backends_lock);
288 		printf(
289 		    "KTLS: Deregistering crypto method %s is not supported\n",
290 		    be->name);
291 		return (EBUSY);
292 	}
293 
294 	if (be->use_count) {
295 		rm_wunlock(&ktls_backends_lock);
296 		return (EBUSY);
297 	}
298 
299 	LIST_REMOVE(be, next);
300 	rm_wunlock(&ktls_backends_lock);
301 	return (0);
302 }
303 
304 #if defined(INET) || defined(INET6)
305 static u_int
306 ktls_get_cpu(struct socket *so)
307 {
308 	struct inpcb *inp;
309 	u_int cpuid;
310 
311 	inp = sotoinpcb(so);
312 #ifdef RSS
313 	cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
314 	if (cpuid != NETISR_CPUID_NONE)
315 		return (cpuid);
316 #endif
317 	/*
318 	 * Just use the flowid to shard connections in a repeatable
319 	 * fashion.  Note that some crypto backends rely on the
320 	 * serialization provided by having the same connection use
321 	 * the same queue.
322 	 */
323 	cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
324 	return (cpuid);
325 }
326 #endif
327 
328 static void
329 ktls_init(void *dummy __unused)
330 {
331 	struct thread *td;
332 	struct pcpu *pc;
333 	cpuset_t mask;
334 	int error, i;
335 
336 	ktls_tasks_active = counter_u64_alloc(M_WAITOK);
337 	ktls_cnt_on = counter_u64_alloc(M_WAITOK);
338 	ktls_offload_total = counter_u64_alloc(M_WAITOK);
339 	ktls_offload_enable_calls = counter_u64_alloc(M_WAITOK);
340 	ktls_offload_active = counter_u64_alloc(M_WAITOK);
341 	ktls_offload_failed_crypto = counter_u64_alloc(M_WAITOK);
342 	ktls_switch_to_ifnet = counter_u64_alloc(M_WAITOK);
343 	ktls_switch_to_sw = counter_u64_alloc(M_WAITOK);
344 	ktls_switch_failed = counter_u64_alloc(M_WAITOK);
345 	ktls_sw_cbc = counter_u64_alloc(M_WAITOK);
346 	ktls_sw_gcm = counter_u64_alloc(M_WAITOK);
347 	ktls_ifnet_cbc = counter_u64_alloc(M_WAITOK);
348 	ktls_ifnet_gcm = counter_u64_alloc(M_WAITOK);
349 	ktls_ifnet_reset = counter_u64_alloc(M_WAITOK);
350 	ktls_ifnet_reset_dropped = counter_u64_alloc(M_WAITOK);
351 	ktls_ifnet_reset_failed = counter_u64_alloc(M_WAITOK);
352 #ifdef TCP_OFFLOAD
353 	ktls_toe_cbc = counter_u64_alloc(M_WAITOK);
354 	ktls_toe_gcm = counter_u64_alloc(M_WAITOK);
355 #endif
356 
357 	rm_init(&ktls_backends_lock, "ktls backends");
358 	LIST_INIT(&ktls_backends);
359 
360 	ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
361 	    M_WAITOK | M_ZERO);
362 
363 	ktls_session_zone = uma_zcreate("ktls_session",
364 	    sizeof(struct ktls_session),
365 	    NULL, NULL, NULL, NULL,
366 	    UMA_ALIGN_CACHE, 0);
367 
368 	/*
369 	 * Initialize the workqueues to run the TLS work.  We create a
370 	 * work queue for each CPU.
371 	 */
372 	CPU_FOREACH(i) {
373 		STAILQ_INIT(&ktls_wq[i].head);
374 		mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
375 		error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
376 		    &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
377 		if (error)
378 			panic("Can't add KTLS thread %d error %d", i, error);
379 
380 		/*
381 		 * Bind threads to cores.  If ktls_bind_threads is >
382 		 * 1, then we bind to the NUMA domain.
383 		 */
384 		if (ktls_bind_threads) {
385 			if (ktls_bind_threads > 1) {
386 				pc = pcpu_find(i);
387 				CPU_COPY(&cpuset_domain[pc->pc_domain], &mask);
388 			} else {
389 				CPU_SETOF(i, &mask);
390 			}
391 			error = cpuset_setthread(td->td_tid, &mask);
392 			if (error)
393 				panic(
394 			    "Unable to bind KTLS thread for CPU %d error %d",
395 				     i, error);
396 		}
397 		ktls_cpuid_lookup[ktls_number_threads] = i;
398 		ktls_number_threads++;
399 	}
400 	printf("KTLS: Initialized %d threads\n", ktls_number_threads);
401 }
402 SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
403 
404 #if defined(INET) || defined(INET6)
405 static int
406 ktls_create_session(struct socket *so, struct tls_enable *en,
407     struct ktls_session **tlsp)
408 {
409 	struct ktls_session *tls;
410 	int error;
411 
412 	/* Only TLS 1.0 - 1.3 are supported. */
413 	if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
414 		return (EINVAL);
415 	if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
416 	    en->tls_vminor > TLS_MINOR_VER_THREE)
417 		return (EINVAL);
418 
419 	if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
420 		return (EINVAL);
421 	if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
422 		return (EINVAL);
423 	if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
424 		return (EINVAL);
425 
426 	/* All supported algorithms require a cipher key. */
427 	if (en->cipher_key_len == 0)
428 		return (EINVAL);
429 
430 	/* No flags are currently supported. */
431 	if (en->flags != 0)
432 		return (EINVAL);
433 
434 	/* Common checks for supported algorithms. */
435 	switch (en->cipher_algorithm) {
436 	case CRYPTO_AES_NIST_GCM_16:
437 		/*
438 		 * auth_algorithm isn't used, but permit GMAC values
439 		 * for compatibility.
440 		 */
441 		switch (en->auth_algorithm) {
442 		case 0:
443 #ifdef COMPAT_FREEBSD12
444 		/* XXX: Really 13.0-current COMPAT. */
445 		case CRYPTO_AES_128_NIST_GMAC:
446 		case CRYPTO_AES_192_NIST_GMAC:
447 		case CRYPTO_AES_256_NIST_GMAC:
448 #endif
449 			break;
450 		default:
451 			return (EINVAL);
452 		}
453 		if (en->auth_key_len != 0)
454 			return (EINVAL);
455 		if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
456 			en->iv_len != TLS_AEAD_GCM_LEN) ||
457 		    (en->tls_vminor == TLS_MINOR_VER_THREE &&
458 			en->iv_len != TLS_1_3_GCM_IV_LEN))
459 			return (EINVAL);
460 		break;
461 	case CRYPTO_AES_CBC:
462 		switch (en->auth_algorithm) {
463 		case CRYPTO_SHA1_HMAC:
464 			/*
465 			 * TLS 1.0 requires an implicit IV.  TLS 1.1+
466 			 * all use explicit IVs.
467 			 */
468 			if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
469 				if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
470 					return (EINVAL);
471 				break;
472 			}
473 
474 			/* FALLTHROUGH */
475 		case CRYPTO_SHA2_256_HMAC:
476 		case CRYPTO_SHA2_384_HMAC:
477 			/* Ignore any supplied IV. */
478 			en->iv_len = 0;
479 			break;
480 		default:
481 			return (EINVAL);
482 		}
483 		if (en->auth_key_len == 0)
484 			return (EINVAL);
485 		break;
486 	default:
487 		return (EINVAL);
488 	}
489 
490 	tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
491 
492 	counter_u64_add(ktls_offload_active, 1);
493 
494 	refcount_init(&tls->refcount, 1);
495 	TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
496 
497 	tls->wq_index = ktls_get_cpu(so);
498 
499 	tls->params.cipher_algorithm = en->cipher_algorithm;
500 	tls->params.auth_algorithm = en->auth_algorithm;
501 	tls->params.tls_vmajor = en->tls_vmajor;
502 	tls->params.tls_vminor = en->tls_vminor;
503 	tls->params.flags = en->flags;
504 	tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
505 
506 	/* Set the header and trailer lengths. */
507 	tls->params.tls_hlen = sizeof(struct tls_record_layer);
508 	switch (en->cipher_algorithm) {
509 	case CRYPTO_AES_NIST_GCM_16:
510 		/*
511 		 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
512 		 * nonce.  TLS 1.3 uses a 12 byte implicit IV.
513 		 */
514 		if (en->tls_vminor < TLS_MINOR_VER_THREE)
515 			tls->params.tls_hlen += sizeof(uint64_t);
516 		tls->params.tls_tlen = AES_GMAC_HASH_LEN;
517 
518 		/*
519 		 * TLS 1.3 includes optional padding which we
520 		 * do not support, and also puts the "real" record
521 		 * type at the end of the encrypted data.
522 		 */
523 		if (en->tls_vminor == TLS_MINOR_VER_THREE)
524 			tls->params.tls_tlen += sizeof(uint8_t);
525 
526 		tls->params.tls_bs = 1;
527 		break;
528 	case CRYPTO_AES_CBC:
529 		switch (en->auth_algorithm) {
530 		case CRYPTO_SHA1_HMAC:
531 			if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
532 				/* Implicit IV, no nonce. */
533 			} else {
534 				tls->params.tls_hlen += AES_BLOCK_LEN;
535 			}
536 			tls->params.tls_tlen = AES_BLOCK_LEN +
537 			    SHA1_HASH_LEN;
538 			break;
539 		case CRYPTO_SHA2_256_HMAC:
540 			tls->params.tls_hlen += AES_BLOCK_LEN;
541 			tls->params.tls_tlen = AES_BLOCK_LEN +
542 			    SHA2_256_HASH_LEN;
543 			break;
544 		case CRYPTO_SHA2_384_HMAC:
545 			tls->params.tls_hlen += AES_BLOCK_LEN;
546 			tls->params.tls_tlen = AES_BLOCK_LEN +
547 			    SHA2_384_HASH_LEN;
548 			break;
549 		default:
550 			panic("invalid hmac");
551 		}
552 		tls->params.tls_bs = AES_BLOCK_LEN;
553 		break;
554 	default:
555 		panic("invalid cipher");
556 	}
557 
558 	KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
559 	    ("TLS header length too long: %d", tls->params.tls_hlen));
560 	KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
561 	    ("TLS trailer length too long: %d", tls->params.tls_tlen));
562 
563 	if (en->auth_key_len != 0) {
564 		tls->params.auth_key_len = en->auth_key_len;
565 		tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
566 		    M_WAITOK);
567 		error = copyin(en->auth_key, tls->params.auth_key,
568 		    en->auth_key_len);
569 		if (error)
570 			goto out;
571 	}
572 
573 	tls->params.cipher_key_len = en->cipher_key_len;
574 	tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
575 	error = copyin(en->cipher_key, tls->params.cipher_key,
576 	    en->cipher_key_len);
577 	if (error)
578 		goto out;
579 
580 	/*
581 	 * This holds the implicit portion of the nonce for GCM and
582 	 * the initial implicit IV for TLS 1.0.  The explicit portions
583 	 * of the IV are generated in ktls_frame().
584 	 */
585 	if (en->iv_len != 0) {
586 		tls->params.iv_len = en->iv_len;
587 		error = copyin(en->iv, tls->params.iv, en->iv_len);
588 		if (error)
589 			goto out;
590 
591 		/*
592 		 * For TLS 1.2, generate an 8-byte nonce as a counter
593 		 * to generate unique explicit IVs.
594 		 *
595 		 * Store this counter in the last 8 bytes of the IV
596 		 * array so that it is 8-byte aligned.
597 		 */
598 		if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
599 		    en->tls_vminor == TLS_MINOR_VER_TWO)
600 			arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
601 	}
602 
603 	*tlsp = tls;
604 	return (0);
605 
606 out:
607 	ktls_cleanup(tls);
608 	return (error);
609 }
610 
611 static struct ktls_session *
612 ktls_clone_session(struct ktls_session *tls)
613 {
614 	struct ktls_session *tls_new;
615 
616 	tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
617 
618 	counter_u64_add(ktls_offload_active, 1);
619 
620 	refcount_init(&tls_new->refcount, 1);
621 
622 	/* Copy fields from existing session. */
623 	tls_new->params = tls->params;
624 	tls_new->wq_index = tls->wq_index;
625 
626 	/* Deep copy keys. */
627 	if (tls_new->params.auth_key != NULL) {
628 		tls_new->params.auth_key = malloc(tls->params.auth_key_len,
629 		    M_KTLS, M_WAITOK);
630 		memcpy(tls_new->params.auth_key, tls->params.auth_key,
631 		    tls->params.auth_key_len);
632 	}
633 
634 	tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
635 	    M_WAITOK);
636 	memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
637 	    tls->params.cipher_key_len);
638 
639 	return (tls_new);
640 }
641 #endif
642 
643 static void
644 ktls_cleanup(struct ktls_session *tls)
645 {
646 
647 	counter_u64_add(ktls_offload_active, -1);
648 	switch (tls->mode) {
649 	case TCP_TLS_MODE_SW:
650 		MPASS(tls->be != NULL);
651 		switch (tls->params.cipher_algorithm) {
652 		case CRYPTO_AES_CBC:
653 			counter_u64_add(ktls_sw_cbc, -1);
654 			break;
655 		case CRYPTO_AES_NIST_GCM_16:
656 			counter_u64_add(ktls_sw_gcm, -1);
657 			break;
658 		}
659 		tls->free(tls);
660 		break;
661 	case TCP_TLS_MODE_IFNET:
662 		switch (tls->params.cipher_algorithm) {
663 		case CRYPTO_AES_CBC:
664 			counter_u64_add(ktls_ifnet_cbc, -1);
665 			break;
666 		case CRYPTO_AES_NIST_GCM_16:
667 			counter_u64_add(ktls_ifnet_gcm, -1);
668 			break;
669 		}
670 		m_snd_tag_rele(tls->snd_tag);
671 		break;
672 #ifdef TCP_OFFLOAD
673 	case TCP_TLS_MODE_TOE:
674 		switch (tls->params.cipher_algorithm) {
675 		case CRYPTO_AES_CBC:
676 			counter_u64_add(ktls_toe_cbc, -1);
677 			break;
678 		case CRYPTO_AES_NIST_GCM_16:
679 			counter_u64_add(ktls_toe_gcm, -1);
680 			break;
681 		}
682 		break;
683 #endif
684 	}
685 	if (tls->params.auth_key != NULL) {
686 		explicit_bzero(tls->params.auth_key, tls->params.auth_key_len);
687 		free(tls->params.auth_key, M_KTLS);
688 		tls->params.auth_key = NULL;
689 		tls->params.auth_key_len = 0;
690 	}
691 	if (tls->params.cipher_key != NULL) {
692 		explicit_bzero(tls->params.cipher_key,
693 		    tls->params.cipher_key_len);
694 		free(tls->params.cipher_key, M_KTLS);
695 		tls->params.cipher_key = NULL;
696 		tls->params.cipher_key_len = 0;
697 	}
698 	explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
699 }
700 
701 #if defined(INET) || defined(INET6)
702 
703 #ifdef TCP_OFFLOAD
704 static int
705 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
706 {
707 	struct inpcb *inp;
708 	struct tcpcb *tp;
709 	int error;
710 
711 	inp = so->so_pcb;
712 	INP_WLOCK(inp);
713 	if (inp->inp_flags2 & INP_FREED) {
714 		INP_WUNLOCK(inp);
715 		return (ECONNRESET);
716 	}
717 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
718 		INP_WUNLOCK(inp);
719 		return (ECONNRESET);
720 	}
721 	if (inp->inp_socket == NULL) {
722 		INP_WUNLOCK(inp);
723 		return (ECONNRESET);
724 	}
725 	tp = intotcpcb(inp);
726 	if (tp->tod == NULL) {
727 		INP_WUNLOCK(inp);
728 		return (EOPNOTSUPP);
729 	}
730 
731 	error = tcp_offload_alloc_tls_session(tp, tls, direction);
732 	INP_WUNLOCK(inp);
733 	if (error == 0) {
734 		tls->mode = TCP_TLS_MODE_TOE;
735 		switch (tls->params.cipher_algorithm) {
736 		case CRYPTO_AES_CBC:
737 			counter_u64_add(ktls_toe_cbc, 1);
738 			break;
739 		case CRYPTO_AES_NIST_GCM_16:
740 			counter_u64_add(ktls_toe_gcm, 1);
741 			break;
742 		}
743 	}
744 	return (error);
745 }
746 #endif
747 
748 /*
749  * Common code used when first enabling ifnet TLS on a connection or
750  * when allocating a new ifnet TLS session due to a routing change.
751  * This function allocates a new TLS send tag on whatever interface
752  * the connection is currently routed over.
753  */
754 static int
755 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
756     struct m_snd_tag **mstp)
757 {
758 	union if_snd_tag_alloc_params params;
759 	struct ifnet *ifp;
760 	struct nhop_object *nh;
761 	struct tcpcb *tp;
762 	int error;
763 
764 	INP_RLOCK(inp);
765 	if (inp->inp_flags2 & INP_FREED) {
766 		INP_RUNLOCK(inp);
767 		return (ECONNRESET);
768 	}
769 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
770 		INP_RUNLOCK(inp);
771 		return (ECONNRESET);
772 	}
773 	if (inp->inp_socket == NULL) {
774 		INP_RUNLOCK(inp);
775 		return (ECONNRESET);
776 	}
777 	tp = intotcpcb(inp);
778 
779 	/*
780 	 * Check administrative controls on ifnet TLS to determine if
781 	 * ifnet TLS should be denied.
782 	 *
783 	 * - Always permit 'force' requests.
784 	 * - ktls_ifnet_permitted == 0: always deny.
785 	 */
786 	if (!force && ktls_ifnet_permitted == 0) {
787 		INP_RUNLOCK(inp);
788 		return (ENXIO);
789 	}
790 
791 	/*
792 	 * XXX: Use the cached route in the inpcb to find the
793 	 * interface.  This should perhaps instead use
794 	 * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
795 	 * enabled after a connection has completed key negotiation in
796 	 * userland, the cached route will be present in practice.
797 	 */
798 	nh = inp->inp_route.ro_nh;
799 	if (nh == NULL) {
800 		INP_RUNLOCK(inp);
801 		return (ENXIO);
802 	}
803 	ifp = nh->nh_ifp;
804 	if_ref(ifp);
805 
806 	params.hdr.type = IF_SND_TAG_TYPE_TLS;
807 	params.hdr.flowid = inp->inp_flowid;
808 	params.hdr.flowtype = inp->inp_flowtype;
809 	params.hdr.numa_domain = inp->inp_numa_domain;
810 	params.tls.inp = inp;
811 	params.tls.tls = tls;
812 	INP_RUNLOCK(inp);
813 
814 	if (ifp->if_snd_tag_alloc == NULL) {
815 		error = EOPNOTSUPP;
816 		goto out;
817 	}
818 	if ((ifp->if_capenable & IFCAP_NOMAP) == 0) {
819 		error = EOPNOTSUPP;
820 		goto out;
821 	}
822 	if (inp->inp_vflag & INP_IPV6) {
823 		if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
824 			error = EOPNOTSUPP;
825 			goto out;
826 		}
827 	} else {
828 		if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
829 			error = EOPNOTSUPP;
830 			goto out;
831 		}
832 	}
833 	error = ifp->if_snd_tag_alloc(ifp, &params, mstp);
834 out:
835 	if_rele(ifp);
836 	return (error);
837 }
838 
839 static int
840 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
841 {
842 	struct m_snd_tag *mst;
843 	int error;
844 
845 	error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
846 	if (error == 0) {
847 		tls->mode = TCP_TLS_MODE_IFNET;
848 		tls->snd_tag = mst;
849 		switch (tls->params.cipher_algorithm) {
850 		case CRYPTO_AES_CBC:
851 			counter_u64_add(ktls_ifnet_cbc, 1);
852 			break;
853 		case CRYPTO_AES_NIST_GCM_16:
854 			counter_u64_add(ktls_ifnet_gcm, 1);
855 			break;
856 		}
857 	}
858 	return (error);
859 }
860 
861 static int
862 ktls_try_sw(struct socket *so, struct ktls_session *tls)
863 {
864 	struct rm_priotracker prio;
865 	struct ktls_crypto_backend *be;
866 
867 	/*
868 	 * Choose the best software crypto backend.  Backends are
869 	 * stored in sorted priority order (larget value == most
870 	 * important at the head of the list), so this just stops on
871 	 * the first backend that claims the session by returning
872 	 * success.
873 	 */
874 	if (ktls_allow_unload)
875 		rm_rlock(&ktls_backends_lock, &prio);
876 	LIST_FOREACH(be, &ktls_backends, next) {
877 		if (be->try(so, tls) == 0)
878 			break;
879 		KASSERT(tls->cipher == NULL,
880 		    ("ktls backend leaked a cipher pointer"));
881 	}
882 	if (be != NULL) {
883 		if (ktls_allow_unload)
884 			be->use_count++;
885 		tls->be = be;
886 	}
887 	if (ktls_allow_unload)
888 		rm_runlock(&ktls_backends_lock, &prio);
889 	if (be == NULL)
890 		return (EOPNOTSUPP);
891 	tls->mode = TCP_TLS_MODE_SW;
892 	switch (tls->params.cipher_algorithm) {
893 	case CRYPTO_AES_CBC:
894 		counter_u64_add(ktls_sw_cbc, 1);
895 		break;
896 	case CRYPTO_AES_NIST_GCM_16:
897 		counter_u64_add(ktls_sw_gcm, 1);
898 		break;
899 	}
900 	return (0);
901 }
902 
903 int
904 ktls_enable_rx(struct socket *so, struct tls_enable *en)
905 {
906 	struct ktls_session *tls;
907 	int error;
908 
909 	if (!ktls_offload_enable)
910 		return (ENOTSUP);
911 
912 	counter_u64_add(ktls_offload_enable_calls, 1);
913 
914 	/*
915 	 * This should always be true since only the TCP socket option
916 	 * invokes this function.
917 	 */
918 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
919 		return (EINVAL);
920 
921 	/*
922 	 * XXX: Don't overwrite existing sessions.  We should permit
923 	 * this to support rekeying in the future.
924 	 */
925 	if (so->so_rcv.sb_tls_info != NULL)
926 		return (EALREADY);
927 
928 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
929 		return (ENOTSUP);
930 
931 	error = ktls_create_session(so, en, &tls);
932 	if (error)
933 		return (error);
934 
935 	/* TLS RX offload is only supported on TOE currently. */
936 #ifdef TCP_OFFLOAD
937 	error = ktls_try_toe(so, tls, KTLS_RX);
938 #else
939 	error = EOPNOTSUPP;
940 #endif
941 
942 	if (error) {
943 		ktls_cleanup(tls);
944 		return (error);
945 	}
946 
947 	/* Mark the socket as using TLS offload. */
948 	SOCKBUF_LOCK(&so->so_rcv);
949 	so->so_rcv.sb_tls_info = tls;
950 	SOCKBUF_UNLOCK(&so->so_rcv);
951 
952 	counter_u64_add(ktls_offload_total, 1);
953 
954 	return (0);
955 }
956 
957 int
958 ktls_enable_tx(struct socket *so, struct tls_enable *en)
959 {
960 	struct ktls_session *tls;
961 	int error;
962 
963 	if (!ktls_offload_enable)
964 		return (ENOTSUP);
965 
966 	counter_u64_add(ktls_offload_enable_calls, 1);
967 
968 	/*
969 	 * This should always be true since only the TCP socket option
970 	 * invokes this function.
971 	 */
972 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
973 		return (EINVAL);
974 
975 	/*
976 	 * XXX: Don't overwrite existing sessions.  We should permit
977 	 * this to support rekeying in the future.
978 	 */
979 	if (so->so_snd.sb_tls_info != NULL)
980 		return (EALREADY);
981 
982 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
983 		return (ENOTSUP);
984 
985 	/* TLS requires ext pgs */
986 	if (mb_use_ext_pgs == 0)
987 		return (ENXIO);
988 
989 	error = ktls_create_session(so, en, &tls);
990 	if (error)
991 		return (error);
992 
993 	/* Prefer TOE -> ifnet TLS -> software TLS. */
994 #ifdef TCP_OFFLOAD
995 	error = ktls_try_toe(so, tls, KTLS_TX);
996 	if (error)
997 #endif
998 		error = ktls_try_ifnet(so, tls, false);
999 	if (error)
1000 		error = ktls_try_sw(so, tls);
1001 
1002 	if (error) {
1003 		ktls_cleanup(tls);
1004 		return (error);
1005 	}
1006 
1007 	error = sblock(&so->so_snd, SBL_WAIT);
1008 	if (error) {
1009 		ktls_cleanup(tls);
1010 		return (error);
1011 	}
1012 
1013 	SOCKBUF_LOCK(&so->so_snd);
1014 	so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1015 	so->so_snd.sb_tls_info = tls;
1016 	if (tls->mode != TCP_TLS_MODE_SW)
1017 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1018 	SOCKBUF_UNLOCK(&so->so_snd);
1019 	sbunlock(&so->so_snd);
1020 
1021 	counter_u64_add(ktls_offload_total, 1);
1022 
1023 	return (0);
1024 }
1025 
1026 int
1027 ktls_get_rx_mode(struct socket *so)
1028 {
1029 	struct ktls_session *tls;
1030 	struct inpcb *inp;
1031 	int mode;
1032 
1033 	inp = so->so_pcb;
1034 	INP_WLOCK_ASSERT(inp);
1035 	SOCKBUF_LOCK(&so->so_rcv);
1036 	tls = so->so_rcv.sb_tls_info;
1037 	if (tls == NULL)
1038 		mode = TCP_TLS_MODE_NONE;
1039 	else
1040 		mode = tls->mode;
1041 	SOCKBUF_UNLOCK(&so->so_rcv);
1042 	return (mode);
1043 }
1044 
1045 int
1046 ktls_get_tx_mode(struct socket *so)
1047 {
1048 	struct ktls_session *tls;
1049 	struct inpcb *inp;
1050 	int mode;
1051 
1052 	inp = so->so_pcb;
1053 	INP_WLOCK_ASSERT(inp);
1054 	SOCKBUF_LOCK(&so->so_snd);
1055 	tls = so->so_snd.sb_tls_info;
1056 	if (tls == NULL)
1057 		mode = TCP_TLS_MODE_NONE;
1058 	else
1059 		mode = tls->mode;
1060 	SOCKBUF_UNLOCK(&so->so_snd);
1061 	return (mode);
1062 }
1063 
1064 /*
1065  * Switch between SW and ifnet TLS sessions as requested.
1066  */
1067 int
1068 ktls_set_tx_mode(struct socket *so, int mode)
1069 {
1070 	struct ktls_session *tls, *tls_new;
1071 	struct inpcb *inp;
1072 	int error;
1073 
1074 	switch (mode) {
1075 	case TCP_TLS_MODE_SW:
1076 	case TCP_TLS_MODE_IFNET:
1077 		break;
1078 	default:
1079 		return (EINVAL);
1080 	}
1081 
1082 	inp = so->so_pcb;
1083 	INP_WLOCK_ASSERT(inp);
1084 	SOCKBUF_LOCK(&so->so_snd);
1085 	tls = so->so_snd.sb_tls_info;
1086 	if (tls == NULL) {
1087 		SOCKBUF_UNLOCK(&so->so_snd);
1088 		return (0);
1089 	}
1090 
1091 	if (tls->mode == mode) {
1092 		SOCKBUF_UNLOCK(&so->so_snd);
1093 		return (0);
1094 	}
1095 
1096 	tls = ktls_hold(tls);
1097 	SOCKBUF_UNLOCK(&so->so_snd);
1098 	INP_WUNLOCK(inp);
1099 
1100 	tls_new = ktls_clone_session(tls);
1101 
1102 	if (mode == TCP_TLS_MODE_IFNET)
1103 		error = ktls_try_ifnet(so, tls_new, true);
1104 	else
1105 		error = ktls_try_sw(so, tls_new);
1106 	if (error) {
1107 		counter_u64_add(ktls_switch_failed, 1);
1108 		ktls_free(tls_new);
1109 		ktls_free(tls);
1110 		INP_WLOCK(inp);
1111 		return (error);
1112 	}
1113 
1114 	error = sblock(&so->so_snd, SBL_WAIT);
1115 	if (error) {
1116 		counter_u64_add(ktls_switch_failed, 1);
1117 		ktls_free(tls_new);
1118 		ktls_free(tls);
1119 		INP_WLOCK(inp);
1120 		return (error);
1121 	}
1122 
1123 	/*
1124 	 * If we raced with another session change, keep the existing
1125 	 * session.
1126 	 */
1127 	if (tls != so->so_snd.sb_tls_info) {
1128 		counter_u64_add(ktls_switch_failed, 1);
1129 		sbunlock(&so->so_snd);
1130 		ktls_free(tls_new);
1131 		ktls_free(tls);
1132 		INP_WLOCK(inp);
1133 		return (EBUSY);
1134 	}
1135 
1136 	SOCKBUF_LOCK(&so->so_snd);
1137 	so->so_snd.sb_tls_info = tls_new;
1138 	if (tls_new->mode != TCP_TLS_MODE_SW)
1139 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1140 	SOCKBUF_UNLOCK(&so->so_snd);
1141 	sbunlock(&so->so_snd);
1142 
1143 	/*
1144 	 * Drop two references on 'tls'.  The first is for the
1145 	 * ktls_hold() above.  The second drops the reference from the
1146 	 * socket buffer.
1147 	 */
1148 	KASSERT(tls->refcount >= 2, ("too few references on old session"));
1149 	ktls_free(tls);
1150 	ktls_free(tls);
1151 
1152 	if (mode == TCP_TLS_MODE_IFNET)
1153 		counter_u64_add(ktls_switch_to_ifnet, 1);
1154 	else
1155 		counter_u64_add(ktls_switch_to_sw, 1);
1156 
1157 	INP_WLOCK(inp);
1158 	return (0);
1159 }
1160 
1161 /*
1162  * Try to allocate a new TLS send tag.  This task is scheduled when
1163  * ip_output detects a route change while trying to transmit a packet
1164  * holding a TLS record.  If a new tag is allocated, replace the tag
1165  * in the TLS session.  Subsequent packets on the connection will use
1166  * the new tag.  If a new tag cannot be allocated, drop the
1167  * connection.
1168  */
1169 static void
1170 ktls_reset_send_tag(void *context, int pending)
1171 {
1172 	struct epoch_tracker et;
1173 	struct ktls_session *tls;
1174 	struct m_snd_tag *old, *new;
1175 	struct inpcb *inp;
1176 	struct tcpcb *tp;
1177 	int error;
1178 
1179 	MPASS(pending == 1);
1180 
1181 	tls = context;
1182 	inp = tls->inp;
1183 
1184 	/*
1185 	 * Free the old tag first before allocating a new one.
1186 	 * ip[6]_output_send() will treat a NULL send tag the same as
1187 	 * an ifp mismatch and drop packets until a new tag is
1188 	 * allocated.
1189 	 *
1190 	 * Write-lock the INP when changing tls->snd_tag since
1191 	 * ip[6]_output_send() holds a read-lock when reading the
1192 	 * pointer.
1193 	 */
1194 	INP_WLOCK(inp);
1195 	old = tls->snd_tag;
1196 	tls->snd_tag = NULL;
1197 	INP_WUNLOCK(inp);
1198 	if (old != NULL)
1199 		m_snd_tag_rele(old);
1200 
1201 	error = ktls_alloc_snd_tag(inp, tls, true, &new);
1202 
1203 	if (error == 0) {
1204 		INP_WLOCK(inp);
1205 		tls->snd_tag = new;
1206 		mtx_pool_lock(mtxpool_sleep, tls);
1207 		tls->reset_pending = false;
1208 		mtx_pool_unlock(mtxpool_sleep, tls);
1209 		if (!in_pcbrele_wlocked(inp))
1210 			INP_WUNLOCK(inp);
1211 
1212 		counter_u64_add(ktls_ifnet_reset, 1);
1213 
1214 		/*
1215 		 * XXX: Should we kick tcp_output explicitly now that
1216 		 * the send tag is fixed or just rely on timers?
1217 		 */
1218 	} else {
1219 		NET_EPOCH_ENTER(et);
1220 		INP_WLOCK(inp);
1221 		if (!in_pcbrele_wlocked(inp)) {
1222 			if (!(inp->inp_flags & INP_TIMEWAIT) &&
1223 			    !(inp->inp_flags & INP_DROPPED)) {
1224 				tp = intotcpcb(inp);
1225 				CURVNET_SET(tp->t_vnet);
1226 				tp = tcp_drop(tp, ECONNABORTED);
1227 				CURVNET_RESTORE();
1228 				if (tp != NULL)
1229 					INP_WUNLOCK(inp);
1230 				counter_u64_add(ktls_ifnet_reset_dropped, 1);
1231 			} else
1232 				INP_WUNLOCK(inp);
1233 		}
1234 		NET_EPOCH_EXIT(et);
1235 
1236 		counter_u64_add(ktls_ifnet_reset_failed, 1);
1237 
1238 		/*
1239 		 * Leave reset_pending true to avoid future tasks while
1240 		 * the socket goes away.
1241 		 */
1242 	}
1243 
1244 	ktls_free(tls);
1245 }
1246 
1247 int
1248 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1249 {
1250 
1251 	if (inp == NULL)
1252 		return (ENOBUFS);
1253 
1254 	INP_LOCK_ASSERT(inp);
1255 
1256 	/*
1257 	 * See if we should schedule a task to update the send tag for
1258 	 * this session.
1259 	 */
1260 	mtx_pool_lock(mtxpool_sleep, tls);
1261 	if (!tls->reset_pending) {
1262 		(void) ktls_hold(tls);
1263 		in_pcbref(inp);
1264 		tls->inp = inp;
1265 		tls->reset_pending = true;
1266 		taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1267 	}
1268 	mtx_pool_unlock(mtxpool_sleep, tls);
1269 	return (ENOBUFS);
1270 }
1271 #endif
1272 
1273 void
1274 ktls_destroy(struct ktls_session *tls)
1275 {
1276 	struct rm_priotracker prio;
1277 
1278 	ktls_cleanup(tls);
1279 	if (tls->be != NULL && ktls_allow_unload) {
1280 		rm_rlock(&ktls_backends_lock, &prio);
1281 		tls->be->use_count--;
1282 		rm_runlock(&ktls_backends_lock, &prio);
1283 	}
1284 	uma_zfree(ktls_session_zone, tls);
1285 }
1286 
1287 void
1288 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1289 {
1290 
1291 	for (; m != NULL; m = m->m_next) {
1292 		KASSERT((m->m_flags & M_EXTPG) != 0,
1293 		    ("ktls_seq: mapped mbuf %p", m));
1294 
1295 		m->m_epg_seqno = sb->sb_tls_seqno;
1296 		sb->sb_tls_seqno++;
1297 	}
1298 }
1299 
1300 /*
1301  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
1302  * mbuf in the chain must be an unmapped mbuf.  The payload of the
1303  * mbuf must be populated with the payload of each TLS record.
1304  *
1305  * The record_type argument specifies the TLS record type used when
1306  * populating the TLS header.
1307  *
1308  * The enq_count argument on return is set to the number of pages of
1309  * payload data for this entire chain that need to be encrypted via SW
1310  * encryption.  The returned value should be passed to ktls_enqueue
1311  * when scheduling encryption of this chain of mbufs.
1312  */
1313 void
1314 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1315     uint8_t record_type)
1316 {
1317 	struct tls_record_layer *tlshdr;
1318 	struct mbuf *m;
1319 	uint64_t *noncep;
1320 	uint16_t tls_len;
1321 	int maxlen;
1322 
1323 	maxlen = tls->params.max_frame_len;
1324 	*enq_cnt = 0;
1325 	for (m = top; m != NULL; m = m->m_next) {
1326 		/*
1327 		 * All mbufs in the chain should be non-empty TLS
1328 		 * records whose payload does not exceed the maximum
1329 		 * frame length.
1330 		 */
1331 		KASSERT(m->m_len <= maxlen && m->m_len > 0,
1332 		    ("ktls_frame: m %p len %d\n", m, m->m_len));
1333 		/*
1334 		 * TLS frames require unmapped mbufs to store session
1335 		 * info.
1336 		 */
1337 		KASSERT((m->m_flags & M_EXTPG) != 0,
1338 		    ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1339 
1340 		tls_len = m->m_len;
1341 
1342 		/* Save a reference to the session. */
1343 		m->m_epg_tls = ktls_hold(tls);
1344 
1345 		m->m_epg_hdrlen = tls->params.tls_hlen;
1346 		m->m_epg_trllen = tls->params.tls_tlen;
1347 		if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1348 			int bs, delta;
1349 
1350 			/*
1351 			 * AES-CBC pads messages to a multiple of the
1352 			 * block size.  Note that the padding is
1353 			 * applied after the digest and the encryption
1354 			 * is done on the "plaintext || mac || padding".
1355 			 * At least one byte of padding is always
1356 			 * present.
1357 			 *
1358 			 * Compute the final trailer length assuming
1359 			 * at most one block of padding.
1360 			 * tls->params.sb_tls_tlen is the maximum
1361 			 * possible trailer length (padding + digest).
1362 			 * delta holds the number of excess padding
1363 			 * bytes if the maximum were used.  Those
1364 			 * extra bytes are removed.
1365 			 */
1366 			bs = tls->params.tls_bs;
1367 			delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1368 			m->m_epg_trllen -= delta;
1369 		}
1370 		m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1371 
1372 		/* Populate the TLS header. */
1373 		tlshdr = (void *)m->m_epg_hdr;
1374 		tlshdr->tls_vmajor = tls->params.tls_vmajor;
1375 
1376 		/*
1377 		 * TLS 1.3 masquarades as TLS 1.2 with a record type
1378 		 * of TLS_RLTYPE_APP.
1379 		 */
1380 		if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1381 		    tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1382 			tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1383 			tlshdr->tls_type = TLS_RLTYPE_APP;
1384 			/* save the real record type for later */
1385 			m->m_epg_record_type = record_type;
1386 			m->m_epg_trail[0] = record_type;
1387 		} else {
1388 			tlshdr->tls_vminor = tls->params.tls_vminor;
1389 			tlshdr->tls_type = record_type;
1390 		}
1391 		tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1392 
1393 		/*
1394 		 * Store nonces / explicit IVs after the end of the
1395 		 * TLS header.
1396 		 *
1397 		 * For GCM with TLS 1.2, an 8 byte nonce is copied
1398 		 * from the end of the IV.  The nonce is then
1399 		 * incremented for use by the next record.
1400 		 *
1401 		 * For CBC, a random nonce is inserted for TLS 1.1+.
1402 		 */
1403 		if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
1404 		    tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
1405 			noncep = (uint64_t *)(tls->params.iv + 8);
1406 			be64enc(tlshdr + 1, *noncep);
1407 			(*noncep)++;
1408 		} else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1409 		    tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1410 			arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1411 
1412 		/*
1413 		 * When using SW encryption, mark the mbuf not ready.
1414 		 * It will be marked ready via sbready() after the
1415 		 * record has been encrypted.
1416 		 *
1417 		 * When using ifnet TLS, unencrypted TLS records are
1418 		 * sent down the stack to the NIC.
1419 		 */
1420 		if (tls->mode == TCP_TLS_MODE_SW) {
1421 			m->m_flags |= M_NOTREADY;
1422 			m->m_epg_nrdy = m->m_epg_npgs;
1423 			*enq_cnt += m->m_epg_npgs;
1424 		}
1425 	}
1426 }
1427 
1428 void
1429 ktls_enqueue_to_free(struct mbuf *m)
1430 {
1431 	struct ktls_wq *wq;
1432 	bool running;
1433 
1434 	/* Mark it for freeing. */
1435 	m->m_epg_flags |= EPG_FLAG_2FREE;
1436 	wq = &ktls_wq[m->m_epg_tls->wq_index];
1437 	mtx_lock(&wq->mtx);
1438 	STAILQ_INSERT_TAIL(&wq->head, m, m_epg_stailq);
1439 	running = wq->running;
1440 	mtx_unlock(&wq->mtx);
1441 	if (!running)
1442 		wakeup(wq);
1443 }
1444 
1445 void
1446 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1447 {
1448 	struct ktls_wq *wq;
1449 	bool running;
1450 
1451 	KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
1452 	    (M_EXTPG | M_NOTREADY)),
1453 	    ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
1454 	KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
1455 
1456 	KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1457 
1458 	m->m_epg_enc_cnt = page_count;
1459 
1460 	/*
1461 	 * Save a pointer to the socket.  The caller is responsible
1462 	 * for taking an additional reference via soref().
1463 	 */
1464 	m->m_epg_so = so;
1465 
1466 	wq = &ktls_wq[m->m_epg_tls->wq_index];
1467 	mtx_lock(&wq->mtx);
1468 	STAILQ_INSERT_TAIL(&wq->head, m, m_epg_stailq);
1469 	running = wq->running;
1470 	mtx_unlock(&wq->mtx);
1471 	if (!running)
1472 		wakeup(wq);
1473 	counter_u64_add(ktls_cnt_on, 1);
1474 }
1475 
1476 static __noinline void
1477 ktls_encrypt(struct mbuf *top)
1478 {
1479 	struct ktls_session *tls;
1480 	struct socket *so;
1481 	struct mbuf *m;
1482 	vm_paddr_t parray[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1483 	struct iovec src_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1484 	struct iovec dst_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1485 	vm_page_t pg;
1486 	int error, i, len, npages, off, total_pages;
1487 	bool is_anon;
1488 
1489 	so = top->m_epg_so;
1490 	tls = top->m_epg_tls;
1491 	KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
1492 	KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
1493 #ifdef INVARIANTS
1494 	top->m_epg_so = NULL;
1495 #endif
1496 	total_pages = top->m_epg_enc_cnt;
1497 	npages = 0;
1498 
1499 	/*
1500 	 * Encrypt the TLS records in the chain of mbufs starting with
1501 	 * 'top'.  'total_pages' gives us a total count of pages and is
1502 	 * used to know when we have finished encrypting the TLS
1503 	 * records originally queued with 'top'.
1504 	 *
1505 	 * NB: These mbufs are queued in the socket buffer and
1506 	 * 'm_next' is traversing the mbufs in the socket buffer.  The
1507 	 * socket buffer lock is not held while traversing this chain.
1508 	 * Since the mbufs are all marked M_NOTREADY their 'm_next'
1509 	 * pointers should be stable.  However, the 'm_next' of the
1510 	 * last mbuf encrypted is not necessarily NULL.  It can point
1511 	 * to other mbufs appended while 'top' was on the TLS work
1512 	 * queue.
1513 	 *
1514 	 * Each mbuf holds an entire TLS record.
1515 	 */
1516 	error = 0;
1517 	for (m = top; npages != total_pages; m = m->m_next) {
1518 		KASSERT(m->m_epg_tls == tls,
1519 		    ("different TLS sessions in a single mbuf chain: %p vs %p",
1520 		    tls, m->m_epg_tls));
1521 		KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
1522 		    (M_EXTPG | M_NOTREADY),
1523 		    ("%p not unready & nomap mbuf (top = %p)\n", m, top));
1524 		KASSERT(npages + m->m_epg_npgs <= total_pages,
1525 		    ("page count mismatch: top %p, total_pages %d, m %p", top,
1526 		    total_pages, m));
1527 
1528 		/*
1529 		 * Generate source and destination ivoecs to pass to
1530 		 * the SW encryption backend.  For writable mbufs, the
1531 		 * destination iovec is a copy of the source and
1532 		 * encryption is done in place.  For file-backed mbufs
1533 		 * (from sendfile), anonymous wired pages are
1534 		 * allocated and assigned to the destination iovec.
1535 		 */
1536 		is_anon = (m->m_epg_flags & EPG_FLAG_ANON) != 0;
1537 
1538 		off = m->m_epg_1st_off;
1539 		for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
1540 			len = m_epg_pagelen(m, i, off);
1541 			src_iov[i].iov_len = len;
1542 			src_iov[i].iov_base =
1543 			    (char *)(void *)PHYS_TO_DMAP(m->m_epg_pa[i]) +
1544 				off;
1545 
1546 			if (is_anon) {
1547 				dst_iov[i].iov_base = src_iov[i].iov_base;
1548 				dst_iov[i].iov_len = src_iov[i].iov_len;
1549 				continue;
1550 			}
1551 retry_page:
1552 			pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
1553 			    VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP | VM_ALLOC_WIRED);
1554 			if (pg == NULL) {
1555 				vm_wait(NULL);
1556 				goto retry_page;
1557 			}
1558 			parray[i] = VM_PAGE_TO_PHYS(pg);
1559 			dst_iov[i].iov_base =
1560 			    (char *)(void *)PHYS_TO_DMAP(parray[i]) + off;
1561 			dst_iov[i].iov_len = len;
1562 		}
1563 
1564 		npages += i;
1565 
1566 		error = (*tls->sw_encrypt)(tls,
1567 		    (const struct tls_record_layer *)m->m_epg_hdr,
1568 		    m->m_epg_trail, src_iov, dst_iov, i, m->m_epg_seqno,
1569 		    m->m_epg_record_type);
1570 		if (error) {
1571 			counter_u64_add(ktls_offload_failed_crypto, 1);
1572 			break;
1573 		}
1574 
1575 		/*
1576 		 * For file-backed mbufs, release the file-backed
1577 		 * pages and replace them in the ext_pgs array with
1578 		 * the anonymous wired pages allocated above.
1579 		 */
1580 		if (!is_anon) {
1581 			/* Free the old pages. */
1582 			m->m_ext.ext_free(m);
1583 
1584 			/* Replace them with the new pages. */
1585 			for (i = 0; i < m->m_epg_npgs; i++)
1586 				m->m_epg_pa[i] = parray[i];
1587 
1588 			/* Use the basic free routine. */
1589 			m->m_ext.ext_free = mb_free_mext_pgs;
1590 
1591 			/* Pages are now writable. */
1592 			m->m_epg_flags |= EPG_FLAG_ANON;
1593 		}
1594 
1595 		/*
1596 		 * Drop a reference to the session now that it is no
1597 		 * longer needed.  Existing code depends on encrypted
1598 		 * records having no associated session vs
1599 		 * yet-to-be-encrypted records having an associated
1600 		 * session.
1601 		 */
1602 		m->m_epg_tls = NULL;
1603 		ktls_free(tls);
1604 	}
1605 
1606 	CURVNET_SET(so->so_vnet);
1607 	if (error == 0) {
1608 		(void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
1609 	} else {
1610 		so->so_proto->pr_usrreqs->pru_abort(so);
1611 		so->so_error = EIO;
1612 		mb_free_notready(top, total_pages);
1613 	}
1614 
1615 	SOCK_LOCK(so);
1616 	sorele(so);
1617 	CURVNET_RESTORE();
1618 }
1619 
1620 static void
1621 ktls_work_thread(void *ctx)
1622 {
1623 	struct ktls_wq *wq = ctx;
1624 	struct mbuf *m, *n;
1625 	STAILQ_HEAD(, mbuf) local_head;
1626 
1627 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
1628 	fpu_kern_thread(0);
1629 #endif
1630 	for (;;) {
1631 		mtx_lock(&wq->mtx);
1632 		while (STAILQ_EMPTY(&wq->head)) {
1633 			wq->running = false;
1634 			mtx_sleep(wq, &wq->mtx, 0, "-", 0);
1635 			wq->running = true;
1636 		}
1637 
1638 		STAILQ_INIT(&local_head);
1639 		STAILQ_CONCAT(&local_head, &wq->head);
1640 		mtx_unlock(&wq->mtx);
1641 
1642 		STAILQ_FOREACH_SAFE(m, &local_head, m_epg_stailq, n) {
1643 			if (m->m_epg_flags & EPG_FLAG_2FREE) {
1644 				ktls_free(m->m_epg_tls);
1645 				uma_zfree(zone_mbuf, m);
1646 			} else {
1647 				ktls_encrypt(m);
1648 				counter_u64_add(ktls_cnt_on, -1);
1649 			}
1650 		}
1651 	}
1652 }
1653