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