xref: /freebsd/sys/kern/uipc_ktls.c (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
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/domainset.h>
38 #include <sys/ktls.h>
39 #include <sys/lock.h>
40 #include <sys/mbuf.h>
41 #include <sys/mutex.h>
42 #include <sys/rmlock.h>
43 #include <sys/proc.h>
44 #include <sys/protosw.h>
45 #include <sys/refcount.h>
46 #include <sys/smp.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/sysctl.h>
50 #include <sys/taskqueue.h>
51 #include <sys/kthread.h>
52 #include <sys/uio.h>
53 #include <sys/vmmeter.h>
54 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
55 #include <machine/pcb.h>
56 #endif
57 #include <machine/vmparam.h>
58 #include <net/if.h>
59 #include <net/if_var.h>
60 #ifdef RSS
61 #include <net/netisr.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) m_head;
83 	STAILQ_HEAD(, socket) so_head;
84 	bool		running;
85 } __aligned(CACHE_LINE_SIZE);
86 
87 struct ktls_domain_info {
88 	int count;
89 	int cpu[MAXCPU];
90 };
91 
92 struct ktls_domain_info ktls_domains[MAXMEMDOM];
93 static struct ktls_wq *ktls_wq;
94 static struct proc *ktls_proc;
95 LIST_HEAD(, ktls_crypto_backend) ktls_backends;
96 static struct rmlock ktls_backends_lock;
97 static uma_zone_t ktls_session_zone;
98 static uint16_t ktls_cpuid_lookup[MAXCPU];
99 
100 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
101     "Kernel TLS offload");
102 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
103     "Kernel TLS offload stats");
104 
105 static int ktls_allow_unload;
106 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, allow_unload, CTLFLAG_RDTUN,
107     &ktls_allow_unload, 0, "Allow software crypto modules to unload");
108 
109 #ifdef RSS
110 static int ktls_bind_threads = 1;
111 #else
112 static int ktls_bind_threads;
113 #endif
114 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
115     &ktls_bind_threads, 0,
116     "Bind crypto threads to cores or domains at boot");
117 
118 static u_int ktls_maxlen = 16384;
119 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RWTUN,
120     &ktls_maxlen, 0, "Maximum TLS record size");
121 
122 static int ktls_number_threads;
123 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
124     &ktls_number_threads, 0,
125     "Number of TLS threads in thread-pool");
126 
127 static bool ktls_offload_enable;
128 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RW,
129     &ktls_offload_enable, 0,
130     "Enable support for kernel TLS offload");
131 
132 static bool ktls_cbc_enable = true;
133 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RW,
134     &ktls_cbc_enable, 1,
135     "Enable Support of AES-CBC crypto for kernel TLS");
136 
137 static counter_u64_t ktls_tasks_active;
138 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
139     &ktls_tasks_active, "Number of active tasks");
140 
141 static counter_u64_t ktls_cnt_tx_queued;
142 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_inqueue, CTLFLAG_RD,
143     &ktls_cnt_tx_queued,
144     "Number of TLS records in queue to tasks for SW encryption");
145 
146 static counter_u64_t ktls_cnt_rx_queued;
147 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_rx_inqueue, CTLFLAG_RD,
148     &ktls_cnt_rx_queued,
149     "Number of TLS sockets in queue to tasks for SW decryption");
150 
151 static counter_u64_t ktls_offload_total;
152 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
153     CTLFLAG_RD, &ktls_offload_total,
154     "Total successful TLS setups (parameters set)");
155 
156 static counter_u64_t ktls_offload_enable_calls;
157 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
158     CTLFLAG_RD, &ktls_offload_enable_calls,
159     "Total number of TLS enable calls made");
160 
161 static counter_u64_t ktls_offload_active;
162 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
163     &ktls_offload_active, "Total Active TLS sessions");
164 
165 static counter_u64_t ktls_offload_corrupted_records;
166 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, corrupted_records, CTLFLAG_RD,
167     &ktls_offload_corrupted_records, "Total corrupted TLS records received");
168 
169 static counter_u64_t ktls_offload_failed_crypto;
170 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
171     &ktls_offload_failed_crypto, "Total TLS crypto failures");
172 
173 static counter_u64_t ktls_switch_to_ifnet;
174 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
175     &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
176 
177 static counter_u64_t ktls_switch_to_sw;
178 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
179     &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
180 
181 static counter_u64_t ktls_switch_failed;
182 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
183     &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
184 
185 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
186     "Software TLS session stats");
187 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
188     "Hardware (ifnet) TLS session stats");
189 #ifdef TCP_OFFLOAD
190 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
191     "TOE TLS session stats");
192 #endif
193 
194 static counter_u64_t ktls_sw_cbc;
195 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
196     "Active number of software TLS sessions using AES-CBC");
197 
198 static counter_u64_t ktls_sw_gcm;
199 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
200     "Active number of software TLS sessions using AES-GCM");
201 
202 static counter_u64_t ktls_ifnet_cbc;
203 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
204     &ktls_ifnet_cbc,
205     "Active number of ifnet TLS sessions using AES-CBC");
206 
207 static counter_u64_t ktls_ifnet_gcm;
208 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
209     &ktls_ifnet_gcm,
210     "Active number of ifnet TLS sessions using AES-GCM");
211 
212 static counter_u64_t ktls_ifnet_reset;
213 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
214     &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
215 
216 static counter_u64_t ktls_ifnet_reset_dropped;
217 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
218     &ktls_ifnet_reset_dropped,
219     "TLS sessions dropped after failing to update ifnet send tag");
220 
221 static counter_u64_t ktls_ifnet_reset_failed;
222 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
223     &ktls_ifnet_reset_failed,
224     "TLS sessions that failed to allocate a new ifnet send tag");
225 
226 static int ktls_ifnet_permitted;
227 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
228     &ktls_ifnet_permitted, 1,
229     "Whether to permit hardware (ifnet) TLS sessions");
230 
231 #ifdef TCP_OFFLOAD
232 static counter_u64_t ktls_toe_cbc;
233 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
234     &ktls_toe_cbc,
235     "Active number of TOE TLS sessions using AES-CBC");
236 
237 static counter_u64_t ktls_toe_gcm;
238 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
239     &ktls_toe_gcm,
240     "Active number of TOE TLS sessions using AES-GCM");
241 #endif
242 
243 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
244 
245 static void ktls_cleanup(struct ktls_session *tls);
246 #if defined(INET) || defined(INET6)
247 static void ktls_reset_send_tag(void *context, int pending);
248 #endif
249 static void ktls_work_thread(void *ctx);
250 
251 int
252 ktls_crypto_backend_register(struct ktls_crypto_backend *be)
253 {
254 	struct ktls_crypto_backend *curr_be, *tmp;
255 
256 	if (be->api_version != KTLS_API_VERSION) {
257 		printf("KTLS: API version mismatch (%d vs %d) for %s\n",
258 		    be->api_version, KTLS_API_VERSION,
259 		    be->name);
260 		return (EINVAL);
261 	}
262 
263 	rm_wlock(&ktls_backends_lock);
264 	printf("KTLS: Registering crypto method %s with prio %d\n",
265 	       be->name, be->prio);
266 	if (LIST_EMPTY(&ktls_backends)) {
267 		LIST_INSERT_HEAD(&ktls_backends, be, next);
268 	} else {
269 		LIST_FOREACH_SAFE(curr_be, &ktls_backends, next, tmp) {
270 			if (curr_be->prio < be->prio) {
271 				LIST_INSERT_BEFORE(curr_be, be, next);
272 				break;
273 			}
274 			if (LIST_NEXT(curr_be, next) == NULL) {
275 				LIST_INSERT_AFTER(curr_be, be, next);
276 				break;
277 			}
278 		}
279 	}
280 	rm_wunlock(&ktls_backends_lock);
281 	return (0);
282 }
283 
284 int
285 ktls_crypto_backend_deregister(struct ktls_crypto_backend *be)
286 {
287 	struct ktls_crypto_backend *tmp;
288 
289 	/*
290 	 * Don't error if the backend isn't registered.  This permits
291 	 * MOD_UNLOAD handlers to use this function unconditionally.
292 	 */
293 	rm_wlock(&ktls_backends_lock);
294 	LIST_FOREACH(tmp, &ktls_backends, next) {
295 		if (tmp == be)
296 			break;
297 	}
298 	if (tmp == NULL) {
299 		rm_wunlock(&ktls_backends_lock);
300 		return (0);
301 	}
302 
303 	if (!ktls_allow_unload) {
304 		rm_wunlock(&ktls_backends_lock);
305 		printf(
306 		    "KTLS: Deregistering crypto method %s is not supported\n",
307 		    be->name);
308 		return (EBUSY);
309 	}
310 
311 	if (be->use_count) {
312 		rm_wunlock(&ktls_backends_lock);
313 		return (EBUSY);
314 	}
315 
316 	LIST_REMOVE(be, next);
317 	rm_wunlock(&ktls_backends_lock);
318 	return (0);
319 }
320 
321 #if defined(INET) || defined(INET6)
322 static u_int
323 ktls_get_cpu(struct socket *so)
324 {
325 	struct inpcb *inp;
326 #ifdef NUMA
327 	struct ktls_domain_info *di;
328 #endif
329 	u_int cpuid;
330 
331 	inp = sotoinpcb(so);
332 #ifdef RSS
333 	cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
334 	if (cpuid != NETISR_CPUID_NONE)
335 		return (cpuid);
336 #endif
337 	/*
338 	 * Just use the flowid to shard connections in a repeatable
339 	 * fashion.  Note that some crypto backends rely on the
340 	 * serialization provided by having the same connection use
341 	 * the same queue.
342 	 */
343 #ifdef NUMA
344 	if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
345 		di = &ktls_domains[inp->inp_numa_domain];
346 		cpuid = di->cpu[inp->inp_flowid % di->count];
347 	} else
348 #endif
349 		cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
350 	return (cpuid);
351 }
352 #endif
353 
354 static void
355 ktls_init(void *dummy __unused)
356 {
357 	struct thread *td;
358 	struct pcpu *pc;
359 	cpuset_t mask;
360 	int count, domain, error, i;
361 
362 	ktls_tasks_active = counter_u64_alloc(M_WAITOK);
363 	ktls_cnt_tx_queued = counter_u64_alloc(M_WAITOK);
364 	ktls_cnt_rx_queued = counter_u64_alloc(M_WAITOK);
365 	ktls_offload_total = counter_u64_alloc(M_WAITOK);
366 	ktls_offload_enable_calls = counter_u64_alloc(M_WAITOK);
367 	ktls_offload_active = counter_u64_alloc(M_WAITOK);
368 	ktls_offload_corrupted_records = counter_u64_alloc(M_WAITOK);
369 	ktls_offload_failed_crypto = counter_u64_alloc(M_WAITOK);
370 	ktls_switch_to_ifnet = counter_u64_alloc(M_WAITOK);
371 	ktls_switch_to_sw = counter_u64_alloc(M_WAITOK);
372 	ktls_switch_failed = counter_u64_alloc(M_WAITOK);
373 	ktls_sw_cbc = counter_u64_alloc(M_WAITOK);
374 	ktls_sw_gcm = counter_u64_alloc(M_WAITOK);
375 	ktls_ifnet_cbc = counter_u64_alloc(M_WAITOK);
376 	ktls_ifnet_gcm = counter_u64_alloc(M_WAITOK);
377 	ktls_ifnet_reset = counter_u64_alloc(M_WAITOK);
378 	ktls_ifnet_reset_dropped = counter_u64_alloc(M_WAITOK);
379 	ktls_ifnet_reset_failed = counter_u64_alloc(M_WAITOK);
380 #ifdef TCP_OFFLOAD
381 	ktls_toe_cbc = counter_u64_alloc(M_WAITOK);
382 	ktls_toe_gcm = counter_u64_alloc(M_WAITOK);
383 #endif
384 
385 	rm_init(&ktls_backends_lock, "ktls backends");
386 	LIST_INIT(&ktls_backends);
387 
388 	ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
389 	    M_WAITOK | M_ZERO);
390 
391 	ktls_session_zone = uma_zcreate("ktls_session",
392 	    sizeof(struct ktls_session),
393 	    NULL, NULL, NULL, NULL,
394 	    UMA_ALIGN_CACHE, 0);
395 
396 	/*
397 	 * Initialize the workqueues to run the TLS work.  We create a
398 	 * work queue for each CPU.
399 	 */
400 	CPU_FOREACH(i) {
401 		STAILQ_INIT(&ktls_wq[i].m_head);
402 		STAILQ_INIT(&ktls_wq[i].so_head);
403 		mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
404 		error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
405 		    &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
406 		if (error)
407 			panic("Can't add KTLS thread %d error %d", i, error);
408 
409 		/*
410 		 * Bind threads to cores.  If ktls_bind_threads is >
411 		 * 1, then we bind to the NUMA domain.
412 		 */
413 		if (ktls_bind_threads) {
414 			if (ktls_bind_threads > 1) {
415 				pc = pcpu_find(i);
416 				domain = pc->pc_domain;
417 				CPU_COPY(&cpuset_domain[domain], &mask);
418 				count = ktls_domains[domain].count;
419 				ktls_domains[domain].cpu[count] = i;
420 				ktls_domains[domain].count++;
421 			} else {
422 				CPU_SETOF(i, &mask);
423 			}
424 			error = cpuset_setthread(td->td_tid, &mask);
425 			if (error)
426 				panic(
427 			    "Unable to bind KTLS thread for CPU %d error %d",
428 				     i, error);
429 		}
430 		ktls_cpuid_lookup[ktls_number_threads] = i;
431 		ktls_number_threads++;
432 	}
433 
434 	/*
435 	 * If we somehow have an empty domain, fall back to choosing
436 	 * among all KTLS threads.
437 	 */
438 	for (i = 0; i < vm_ndomains; i++) {
439 		if (ktls_domains[i].count == 0) {
440 			ktls_bind_threads = 0;
441 			break;
442 		}
443 	}
444 
445 	printf("KTLS: Initialized %d threads\n", ktls_number_threads);
446 }
447 SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
448 
449 #if defined(INET) || defined(INET6)
450 static int
451 ktls_create_session(struct socket *so, struct tls_enable *en,
452     struct ktls_session **tlsp)
453 {
454 	struct ktls_session *tls;
455 	int error;
456 
457 	/* Only TLS 1.0 - 1.3 are supported. */
458 	if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
459 		return (EINVAL);
460 	if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
461 	    en->tls_vminor > TLS_MINOR_VER_THREE)
462 		return (EINVAL);
463 
464 	if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
465 		return (EINVAL);
466 	if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
467 		return (EINVAL);
468 	if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
469 		return (EINVAL);
470 
471 	/* All supported algorithms require a cipher key. */
472 	if (en->cipher_key_len == 0)
473 		return (EINVAL);
474 
475 	/* No flags are currently supported. */
476 	if (en->flags != 0)
477 		return (EINVAL);
478 
479 	/* Common checks for supported algorithms. */
480 	switch (en->cipher_algorithm) {
481 	case CRYPTO_AES_NIST_GCM_16:
482 		/*
483 		 * auth_algorithm isn't used, but permit GMAC values
484 		 * for compatibility.
485 		 */
486 		switch (en->auth_algorithm) {
487 		case 0:
488 #ifdef COMPAT_FREEBSD12
489 		/* XXX: Really 13.0-current COMPAT. */
490 		case CRYPTO_AES_128_NIST_GMAC:
491 		case CRYPTO_AES_192_NIST_GMAC:
492 		case CRYPTO_AES_256_NIST_GMAC:
493 #endif
494 			break;
495 		default:
496 			return (EINVAL);
497 		}
498 		if (en->auth_key_len != 0)
499 			return (EINVAL);
500 		if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
501 			en->iv_len != TLS_AEAD_GCM_LEN) ||
502 		    (en->tls_vminor == TLS_MINOR_VER_THREE &&
503 			en->iv_len != TLS_1_3_GCM_IV_LEN))
504 			return (EINVAL);
505 		break;
506 	case CRYPTO_AES_CBC:
507 		switch (en->auth_algorithm) {
508 		case CRYPTO_SHA1_HMAC:
509 			/*
510 			 * TLS 1.0 requires an implicit IV.  TLS 1.1+
511 			 * all use explicit IVs.
512 			 */
513 			if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
514 				if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
515 					return (EINVAL);
516 				break;
517 			}
518 
519 			/* FALLTHROUGH */
520 		case CRYPTO_SHA2_256_HMAC:
521 		case CRYPTO_SHA2_384_HMAC:
522 			/* Ignore any supplied IV. */
523 			en->iv_len = 0;
524 			break;
525 		default:
526 			return (EINVAL);
527 		}
528 		if (en->auth_key_len == 0)
529 			return (EINVAL);
530 		break;
531 	default:
532 		return (EINVAL);
533 	}
534 
535 	tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
536 
537 	counter_u64_add(ktls_offload_active, 1);
538 
539 	refcount_init(&tls->refcount, 1);
540 	TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
541 
542 	tls->wq_index = ktls_get_cpu(so);
543 
544 	tls->params.cipher_algorithm = en->cipher_algorithm;
545 	tls->params.auth_algorithm = en->auth_algorithm;
546 	tls->params.tls_vmajor = en->tls_vmajor;
547 	tls->params.tls_vminor = en->tls_vminor;
548 	tls->params.flags = en->flags;
549 	tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
550 
551 	/* Set the header and trailer lengths. */
552 	tls->params.tls_hlen = sizeof(struct tls_record_layer);
553 	switch (en->cipher_algorithm) {
554 	case CRYPTO_AES_NIST_GCM_16:
555 		/*
556 		 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
557 		 * nonce.  TLS 1.3 uses a 12 byte implicit IV.
558 		 */
559 		if (en->tls_vminor < TLS_MINOR_VER_THREE)
560 			tls->params.tls_hlen += sizeof(uint64_t);
561 		tls->params.tls_tlen = AES_GMAC_HASH_LEN;
562 
563 		/*
564 		 * TLS 1.3 includes optional padding which we
565 		 * do not support, and also puts the "real" record
566 		 * type at the end of the encrypted data.
567 		 */
568 		if (en->tls_vminor == TLS_MINOR_VER_THREE)
569 			tls->params.tls_tlen += sizeof(uint8_t);
570 
571 		tls->params.tls_bs = 1;
572 		break;
573 	case CRYPTO_AES_CBC:
574 		switch (en->auth_algorithm) {
575 		case CRYPTO_SHA1_HMAC:
576 			if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
577 				/* Implicit IV, no nonce. */
578 			} else {
579 				tls->params.tls_hlen += AES_BLOCK_LEN;
580 			}
581 			tls->params.tls_tlen = AES_BLOCK_LEN +
582 			    SHA1_HASH_LEN;
583 			break;
584 		case CRYPTO_SHA2_256_HMAC:
585 			tls->params.tls_hlen += AES_BLOCK_LEN;
586 			tls->params.tls_tlen = AES_BLOCK_LEN +
587 			    SHA2_256_HASH_LEN;
588 			break;
589 		case CRYPTO_SHA2_384_HMAC:
590 			tls->params.tls_hlen += AES_BLOCK_LEN;
591 			tls->params.tls_tlen = AES_BLOCK_LEN +
592 			    SHA2_384_HASH_LEN;
593 			break;
594 		default:
595 			panic("invalid hmac");
596 		}
597 		tls->params.tls_bs = AES_BLOCK_LEN;
598 		break;
599 	default:
600 		panic("invalid cipher");
601 	}
602 
603 	KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
604 	    ("TLS header length too long: %d", tls->params.tls_hlen));
605 	KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
606 	    ("TLS trailer length too long: %d", tls->params.tls_tlen));
607 
608 	if (en->auth_key_len != 0) {
609 		tls->params.auth_key_len = en->auth_key_len;
610 		tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
611 		    M_WAITOK);
612 		error = copyin(en->auth_key, tls->params.auth_key,
613 		    en->auth_key_len);
614 		if (error)
615 			goto out;
616 	}
617 
618 	tls->params.cipher_key_len = en->cipher_key_len;
619 	tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
620 	error = copyin(en->cipher_key, tls->params.cipher_key,
621 	    en->cipher_key_len);
622 	if (error)
623 		goto out;
624 
625 	/*
626 	 * This holds the implicit portion of the nonce for GCM and
627 	 * the initial implicit IV for TLS 1.0.  The explicit portions
628 	 * of the IV are generated in ktls_frame().
629 	 */
630 	if (en->iv_len != 0) {
631 		tls->params.iv_len = en->iv_len;
632 		error = copyin(en->iv, tls->params.iv, en->iv_len);
633 		if (error)
634 			goto out;
635 
636 		/*
637 		 * For TLS 1.2, generate an 8-byte nonce as a counter
638 		 * to generate unique explicit IVs.
639 		 *
640 		 * Store this counter in the last 8 bytes of the IV
641 		 * array so that it is 8-byte aligned.
642 		 */
643 		if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
644 		    en->tls_vminor == TLS_MINOR_VER_TWO)
645 			arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
646 	}
647 
648 	*tlsp = tls;
649 	return (0);
650 
651 out:
652 	ktls_cleanup(tls);
653 	return (error);
654 }
655 
656 static struct ktls_session *
657 ktls_clone_session(struct ktls_session *tls)
658 {
659 	struct ktls_session *tls_new;
660 
661 	tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
662 
663 	counter_u64_add(ktls_offload_active, 1);
664 
665 	refcount_init(&tls_new->refcount, 1);
666 
667 	/* Copy fields from existing session. */
668 	tls_new->params = tls->params;
669 	tls_new->wq_index = tls->wq_index;
670 
671 	/* Deep copy keys. */
672 	if (tls_new->params.auth_key != NULL) {
673 		tls_new->params.auth_key = malloc(tls->params.auth_key_len,
674 		    M_KTLS, M_WAITOK);
675 		memcpy(tls_new->params.auth_key, tls->params.auth_key,
676 		    tls->params.auth_key_len);
677 	}
678 
679 	tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
680 	    M_WAITOK);
681 	memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
682 	    tls->params.cipher_key_len);
683 
684 	return (tls_new);
685 }
686 #endif
687 
688 static void
689 ktls_cleanup(struct ktls_session *tls)
690 {
691 
692 	counter_u64_add(ktls_offload_active, -1);
693 	switch (tls->mode) {
694 	case TCP_TLS_MODE_SW:
695 		MPASS(tls->be != NULL);
696 		switch (tls->params.cipher_algorithm) {
697 		case CRYPTO_AES_CBC:
698 			counter_u64_add(ktls_sw_cbc, -1);
699 			break;
700 		case CRYPTO_AES_NIST_GCM_16:
701 			counter_u64_add(ktls_sw_gcm, -1);
702 			break;
703 		}
704 		tls->free(tls);
705 		break;
706 	case TCP_TLS_MODE_IFNET:
707 		switch (tls->params.cipher_algorithm) {
708 		case CRYPTO_AES_CBC:
709 			counter_u64_add(ktls_ifnet_cbc, -1);
710 			break;
711 		case CRYPTO_AES_NIST_GCM_16:
712 			counter_u64_add(ktls_ifnet_gcm, -1);
713 			break;
714 		}
715 		if (tls->snd_tag != NULL)
716 			m_snd_tag_rele(tls->snd_tag);
717 		break;
718 #ifdef TCP_OFFLOAD
719 	case TCP_TLS_MODE_TOE:
720 		switch (tls->params.cipher_algorithm) {
721 		case CRYPTO_AES_CBC:
722 			counter_u64_add(ktls_toe_cbc, -1);
723 			break;
724 		case CRYPTO_AES_NIST_GCM_16:
725 			counter_u64_add(ktls_toe_gcm, -1);
726 			break;
727 		}
728 		break;
729 #endif
730 	}
731 	if (tls->params.auth_key != NULL) {
732 		zfree(tls->params.auth_key, M_KTLS);
733 		tls->params.auth_key = NULL;
734 		tls->params.auth_key_len = 0;
735 	}
736 	if (tls->params.cipher_key != NULL) {
737 		zfree(tls->params.cipher_key, M_KTLS);
738 		tls->params.cipher_key = NULL;
739 		tls->params.cipher_key_len = 0;
740 	}
741 	explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
742 }
743 
744 #if defined(INET) || defined(INET6)
745 
746 #ifdef TCP_OFFLOAD
747 static int
748 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
749 {
750 	struct inpcb *inp;
751 	struct tcpcb *tp;
752 	int error;
753 
754 	inp = so->so_pcb;
755 	INP_WLOCK(inp);
756 	if (inp->inp_flags2 & INP_FREED) {
757 		INP_WUNLOCK(inp);
758 		return (ECONNRESET);
759 	}
760 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
761 		INP_WUNLOCK(inp);
762 		return (ECONNRESET);
763 	}
764 	if (inp->inp_socket == NULL) {
765 		INP_WUNLOCK(inp);
766 		return (ECONNRESET);
767 	}
768 	tp = intotcpcb(inp);
769 	if (!(tp->t_flags & TF_TOE)) {
770 		INP_WUNLOCK(inp);
771 		return (EOPNOTSUPP);
772 	}
773 
774 	error = tcp_offload_alloc_tls_session(tp, tls, direction);
775 	INP_WUNLOCK(inp);
776 	if (error == 0) {
777 		tls->mode = TCP_TLS_MODE_TOE;
778 		switch (tls->params.cipher_algorithm) {
779 		case CRYPTO_AES_CBC:
780 			counter_u64_add(ktls_toe_cbc, 1);
781 			break;
782 		case CRYPTO_AES_NIST_GCM_16:
783 			counter_u64_add(ktls_toe_gcm, 1);
784 			break;
785 		}
786 	}
787 	return (error);
788 }
789 #endif
790 
791 /*
792  * Common code used when first enabling ifnet TLS on a connection or
793  * when allocating a new ifnet TLS session due to a routing change.
794  * This function allocates a new TLS send tag on whatever interface
795  * the connection is currently routed over.
796  */
797 static int
798 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
799     struct m_snd_tag **mstp)
800 {
801 	union if_snd_tag_alloc_params params;
802 	struct ifnet *ifp;
803 	struct nhop_object *nh;
804 	struct tcpcb *tp;
805 	int error;
806 
807 	INP_RLOCK(inp);
808 	if (inp->inp_flags2 & INP_FREED) {
809 		INP_RUNLOCK(inp);
810 		return (ECONNRESET);
811 	}
812 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
813 		INP_RUNLOCK(inp);
814 		return (ECONNRESET);
815 	}
816 	if (inp->inp_socket == NULL) {
817 		INP_RUNLOCK(inp);
818 		return (ECONNRESET);
819 	}
820 	tp = intotcpcb(inp);
821 
822 	/*
823 	 * Check administrative controls on ifnet TLS to determine if
824 	 * ifnet TLS should be denied.
825 	 *
826 	 * - Always permit 'force' requests.
827 	 * - ktls_ifnet_permitted == 0: always deny.
828 	 */
829 	if (!force && ktls_ifnet_permitted == 0) {
830 		INP_RUNLOCK(inp);
831 		return (ENXIO);
832 	}
833 
834 	/*
835 	 * XXX: Use the cached route in the inpcb to find the
836 	 * interface.  This should perhaps instead use
837 	 * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
838 	 * enabled after a connection has completed key negotiation in
839 	 * userland, the cached route will be present in practice.
840 	 */
841 	nh = inp->inp_route.ro_nh;
842 	if (nh == NULL) {
843 		INP_RUNLOCK(inp);
844 		return (ENXIO);
845 	}
846 	ifp = nh->nh_ifp;
847 	if_ref(ifp);
848 
849 	/*
850 	 * Allocate a TLS + ratelimit tag if the connection has an
851 	 * existing pacing rate.
852 	 */
853 	if (tp->t_pacing_rate != -1 &&
854 	    (ifp->if_capenable & IFCAP_TXTLS_RTLMT) != 0) {
855 		params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
856 		params.tls_rate_limit.inp = inp;
857 		params.tls_rate_limit.tls = tls;
858 		params.tls_rate_limit.max_rate = tp->t_pacing_rate;
859 	} else {
860 		params.hdr.type = IF_SND_TAG_TYPE_TLS;
861 		params.tls.inp = inp;
862 		params.tls.tls = tls;
863 	}
864 	params.hdr.flowid = inp->inp_flowid;
865 	params.hdr.flowtype = inp->inp_flowtype;
866 	params.hdr.numa_domain = inp->inp_numa_domain;
867 	INP_RUNLOCK(inp);
868 
869 	if ((ifp->if_capenable & IFCAP_NOMAP) == 0) {
870 		error = EOPNOTSUPP;
871 		goto out;
872 	}
873 	if (inp->inp_vflag & INP_IPV6) {
874 		if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
875 			error = EOPNOTSUPP;
876 			goto out;
877 		}
878 	} else {
879 		if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
880 			error = EOPNOTSUPP;
881 			goto out;
882 		}
883 	}
884 	error = m_snd_tag_alloc(ifp, &params, mstp);
885 out:
886 	if_rele(ifp);
887 	return (error);
888 }
889 
890 static int
891 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
892 {
893 	struct m_snd_tag *mst;
894 	int error;
895 
896 	error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
897 	if (error == 0) {
898 		tls->mode = TCP_TLS_MODE_IFNET;
899 		tls->snd_tag = mst;
900 		switch (tls->params.cipher_algorithm) {
901 		case CRYPTO_AES_CBC:
902 			counter_u64_add(ktls_ifnet_cbc, 1);
903 			break;
904 		case CRYPTO_AES_NIST_GCM_16:
905 			counter_u64_add(ktls_ifnet_gcm, 1);
906 			break;
907 		}
908 	}
909 	return (error);
910 }
911 
912 static int
913 ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
914 {
915 	struct rm_priotracker prio;
916 	struct ktls_crypto_backend *be;
917 
918 	/*
919 	 * Choose the best software crypto backend.  Backends are
920 	 * stored in sorted priority order (larget value == most
921 	 * important at the head of the list), so this just stops on
922 	 * the first backend that claims the session by returning
923 	 * success.
924 	 */
925 	if (ktls_allow_unload)
926 		rm_rlock(&ktls_backends_lock, &prio);
927 	LIST_FOREACH(be, &ktls_backends, next) {
928 		if (be->try(so, tls, direction) == 0)
929 			break;
930 		KASSERT(tls->cipher == NULL,
931 		    ("ktls backend leaked a cipher pointer"));
932 	}
933 	if (be != NULL) {
934 		if (ktls_allow_unload)
935 			be->use_count++;
936 		tls->be = be;
937 	}
938 	if (ktls_allow_unload)
939 		rm_runlock(&ktls_backends_lock, &prio);
940 	if (be == NULL)
941 		return (EOPNOTSUPP);
942 	tls->mode = TCP_TLS_MODE_SW;
943 	switch (tls->params.cipher_algorithm) {
944 	case CRYPTO_AES_CBC:
945 		counter_u64_add(ktls_sw_cbc, 1);
946 		break;
947 	case CRYPTO_AES_NIST_GCM_16:
948 		counter_u64_add(ktls_sw_gcm, 1);
949 		break;
950 	}
951 	return (0);
952 }
953 
954 /*
955  * KTLS RX stores data in the socket buffer as a list of TLS records,
956  * where each record is stored as a control message containg the TLS
957  * header followed by data mbufs containing the decrypted data.  This
958  * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
959  * both encrypted and decrypted data.  TLS records decrypted by a NIC
960  * should be queued to the socket buffer as records, but encrypted
961  * data which needs to be decrypted by software arrives as a stream of
962  * regular mbufs which need to be converted.  In addition, there may
963  * already be pending encrypted data in the socket buffer when KTLS RX
964  * is enabled.
965  *
966  * To manage not-yet-decrypted data for KTLS RX, the following scheme
967  * is used:
968  *
969  * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
970  *
971  * - ktls_check_rx checks this chain of mbufs reading the TLS header
972  *   from the first mbuf.  Once all of the data for that TLS record is
973  *   queued, the socket is queued to a worker thread.
974  *
975  * - The worker thread calls ktls_decrypt to decrypt TLS records in
976  *   the TLS chain.  Each TLS record is detached from the TLS chain,
977  *   decrypted, and inserted into the regular socket buffer chain as
978  *   record starting with a control message holding the TLS header and
979  *   a chain of mbufs holding the encrypted data.
980  */
981 
982 static void
983 sb_mark_notready(struct sockbuf *sb)
984 {
985 	struct mbuf *m;
986 
987 	m = sb->sb_mb;
988 	sb->sb_mtls = m;
989 	sb->sb_mb = NULL;
990 	sb->sb_mbtail = NULL;
991 	sb->sb_lastrecord = NULL;
992 	for (; m != NULL; m = m->m_next) {
993 		KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
994 		    __func__));
995 		KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
996 		    __func__));
997 		KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
998 		    __func__));
999 		m->m_flags |= M_NOTREADY;
1000 		sb->sb_acc -= m->m_len;
1001 		sb->sb_tlscc += m->m_len;
1002 		sb->sb_mtlstail = m;
1003 	}
1004 	KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
1005 	    ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
1006 	    sb->sb_ccc));
1007 }
1008 
1009 int
1010 ktls_enable_rx(struct socket *so, struct tls_enable *en)
1011 {
1012 	struct ktls_session *tls;
1013 	int error;
1014 
1015 	if (!ktls_offload_enable)
1016 		return (ENOTSUP);
1017 	if (SOLISTENING(so))
1018 		return (EINVAL);
1019 
1020 	counter_u64_add(ktls_offload_enable_calls, 1);
1021 
1022 	/*
1023 	 * This should always be true since only the TCP socket option
1024 	 * invokes this function.
1025 	 */
1026 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1027 		return (EINVAL);
1028 
1029 	/*
1030 	 * XXX: Don't overwrite existing sessions.  We should permit
1031 	 * this to support rekeying in the future.
1032 	 */
1033 	if (so->so_rcv.sb_tls_info != NULL)
1034 		return (EALREADY);
1035 
1036 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1037 		return (ENOTSUP);
1038 
1039 	/* TLS 1.3 is not yet supported. */
1040 	if (en->tls_vmajor == TLS_MAJOR_VER_ONE &&
1041 	    en->tls_vminor == TLS_MINOR_VER_THREE)
1042 		return (ENOTSUP);
1043 
1044 	error = ktls_create_session(so, en, &tls);
1045 	if (error)
1046 		return (error);
1047 
1048 #ifdef TCP_OFFLOAD
1049 	error = ktls_try_toe(so, tls, KTLS_RX);
1050 	if (error)
1051 #endif
1052 		error = ktls_try_sw(so, tls, KTLS_RX);
1053 
1054 	if (error) {
1055 		ktls_cleanup(tls);
1056 		return (error);
1057 	}
1058 
1059 	/* Mark the socket as using TLS offload. */
1060 	SOCKBUF_LOCK(&so->so_rcv);
1061 	so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1062 	so->so_rcv.sb_tls_info = tls;
1063 	so->so_rcv.sb_flags |= SB_TLS_RX;
1064 
1065 	/* Mark existing data as not ready until it can be decrypted. */
1066 	sb_mark_notready(&so->so_rcv);
1067 	ktls_check_rx(&so->so_rcv);
1068 	SOCKBUF_UNLOCK(&so->so_rcv);
1069 
1070 	counter_u64_add(ktls_offload_total, 1);
1071 
1072 	return (0);
1073 }
1074 
1075 int
1076 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1077 {
1078 	struct ktls_session *tls;
1079 	struct inpcb *inp;
1080 	int error;
1081 
1082 	if (!ktls_offload_enable)
1083 		return (ENOTSUP);
1084 	if (SOLISTENING(so))
1085 		return (EINVAL);
1086 
1087 	counter_u64_add(ktls_offload_enable_calls, 1);
1088 
1089 	/*
1090 	 * This should always be true since only the TCP socket option
1091 	 * invokes this function.
1092 	 */
1093 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1094 		return (EINVAL);
1095 
1096 	/*
1097 	 * XXX: Don't overwrite existing sessions.  We should permit
1098 	 * this to support rekeying in the future.
1099 	 */
1100 	if (so->so_snd.sb_tls_info != NULL)
1101 		return (EALREADY);
1102 
1103 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1104 		return (ENOTSUP);
1105 
1106 	/* TLS requires ext pgs */
1107 	if (mb_use_ext_pgs == 0)
1108 		return (ENXIO);
1109 
1110 	error = ktls_create_session(so, en, &tls);
1111 	if (error)
1112 		return (error);
1113 
1114 	/* Prefer TOE -> ifnet TLS -> software TLS. */
1115 #ifdef TCP_OFFLOAD
1116 	error = ktls_try_toe(so, tls, KTLS_TX);
1117 	if (error)
1118 #endif
1119 		error = ktls_try_ifnet(so, tls, false);
1120 	if (error)
1121 		error = ktls_try_sw(so, tls, KTLS_TX);
1122 
1123 	if (error) {
1124 		ktls_cleanup(tls);
1125 		return (error);
1126 	}
1127 
1128 	error = sblock(&so->so_snd, SBL_WAIT);
1129 	if (error) {
1130 		ktls_cleanup(tls);
1131 		return (error);
1132 	}
1133 
1134 	/*
1135 	 * Write lock the INP when setting sb_tls_info so that
1136 	 * routines in tcp_ratelimit.c can read sb_tls_info while
1137 	 * holding the INP lock.
1138 	 */
1139 	inp = so->so_pcb;
1140 	INP_WLOCK(inp);
1141 	SOCKBUF_LOCK(&so->so_snd);
1142 	so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1143 	so->so_snd.sb_tls_info = tls;
1144 	if (tls->mode != TCP_TLS_MODE_SW)
1145 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1146 	SOCKBUF_UNLOCK(&so->so_snd);
1147 	INP_WUNLOCK(inp);
1148 	sbunlock(&so->so_snd);
1149 
1150 	counter_u64_add(ktls_offload_total, 1);
1151 
1152 	return (0);
1153 }
1154 
1155 int
1156 ktls_get_rx_mode(struct socket *so)
1157 {
1158 	struct ktls_session *tls;
1159 	struct inpcb *inp;
1160 	int mode;
1161 
1162 	if (SOLISTENING(so))
1163 		return (EINVAL);
1164 	inp = so->so_pcb;
1165 	INP_WLOCK_ASSERT(inp);
1166 	SOCKBUF_LOCK(&so->so_rcv);
1167 	tls = so->so_rcv.sb_tls_info;
1168 	if (tls == NULL)
1169 		mode = TCP_TLS_MODE_NONE;
1170 	else
1171 		mode = tls->mode;
1172 	SOCKBUF_UNLOCK(&so->so_rcv);
1173 	return (mode);
1174 }
1175 
1176 int
1177 ktls_get_tx_mode(struct socket *so)
1178 {
1179 	struct ktls_session *tls;
1180 	struct inpcb *inp;
1181 	int mode;
1182 
1183 	if (SOLISTENING(so))
1184 		return (EINVAL);
1185 	inp = so->so_pcb;
1186 	INP_WLOCK_ASSERT(inp);
1187 	SOCKBUF_LOCK(&so->so_snd);
1188 	tls = so->so_snd.sb_tls_info;
1189 	if (tls == NULL)
1190 		mode = TCP_TLS_MODE_NONE;
1191 	else
1192 		mode = tls->mode;
1193 	SOCKBUF_UNLOCK(&so->so_snd);
1194 	return (mode);
1195 }
1196 
1197 /*
1198  * Switch between SW and ifnet TLS sessions as requested.
1199  */
1200 int
1201 ktls_set_tx_mode(struct socket *so, int mode)
1202 {
1203 	struct ktls_session *tls, *tls_new;
1204 	struct inpcb *inp;
1205 	int error;
1206 
1207 	if (SOLISTENING(so))
1208 		return (EINVAL);
1209 	switch (mode) {
1210 	case TCP_TLS_MODE_SW:
1211 	case TCP_TLS_MODE_IFNET:
1212 		break;
1213 	default:
1214 		return (EINVAL);
1215 	}
1216 
1217 	inp = so->so_pcb;
1218 	INP_WLOCK_ASSERT(inp);
1219 	SOCKBUF_LOCK(&so->so_snd);
1220 	tls = so->so_snd.sb_tls_info;
1221 	if (tls == NULL) {
1222 		SOCKBUF_UNLOCK(&so->so_snd);
1223 		return (0);
1224 	}
1225 
1226 	if (tls->mode == mode) {
1227 		SOCKBUF_UNLOCK(&so->so_snd);
1228 		return (0);
1229 	}
1230 
1231 	tls = ktls_hold(tls);
1232 	SOCKBUF_UNLOCK(&so->so_snd);
1233 	INP_WUNLOCK(inp);
1234 
1235 	tls_new = ktls_clone_session(tls);
1236 
1237 	if (mode == TCP_TLS_MODE_IFNET)
1238 		error = ktls_try_ifnet(so, tls_new, true);
1239 	else
1240 		error = ktls_try_sw(so, tls_new, KTLS_TX);
1241 	if (error) {
1242 		counter_u64_add(ktls_switch_failed, 1);
1243 		ktls_free(tls_new);
1244 		ktls_free(tls);
1245 		INP_WLOCK(inp);
1246 		return (error);
1247 	}
1248 
1249 	error = sblock(&so->so_snd, SBL_WAIT);
1250 	if (error) {
1251 		counter_u64_add(ktls_switch_failed, 1);
1252 		ktls_free(tls_new);
1253 		ktls_free(tls);
1254 		INP_WLOCK(inp);
1255 		return (error);
1256 	}
1257 
1258 	/*
1259 	 * If we raced with another session change, keep the existing
1260 	 * session.
1261 	 */
1262 	if (tls != so->so_snd.sb_tls_info) {
1263 		counter_u64_add(ktls_switch_failed, 1);
1264 		sbunlock(&so->so_snd);
1265 		ktls_free(tls_new);
1266 		ktls_free(tls);
1267 		INP_WLOCK(inp);
1268 		return (EBUSY);
1269 	}
1270 
1271 	SOCKBUF_LOCK(&so->so_snd);
1272 	so->so_snd.sb_tls_info = tls_new;
1273 	if (tls_new->mode != TCP_TLS_MODE_SW)
1274 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1275 	SOCKBUF_UNLOCK(&so->so_snd);
1276 	sbunlock(&so->so_snd);
1277 
1278 	/*
1279 	 * Drop two references on 'tls'.  The first is for the
1280 	 * ktls_hold() above.  The second drops the reference from the
1281 	 * socket buffer.
1282 	 */
1283 	KASSERT(tls->refcount >= 2, ("too few references on old session"));
1284 	ktls_free(tls);
1285 	ktls_free(tls);
1286 
1287 	if (mode == TCP_TLS_MODE_IFNET)
1288 		counter_u64_add(ktls_switch_to_ifnet, 1);
1289 	else
1290 		counter_u64_add(ktls_switch_to_sw, 1);
1291 
1292 	INP_WLOCK(inp);
1293 	return (0);
1294 }
1295 
1296 /*
1297  * Try to allocate a new TLS send tag.  This task is scheduled when
1298  * ip_output detects a route change while trying to transmit a packet
1299  * holding a TLS record.  If a new tag is allocated, replace the tag
1300  * in the TLS session.  Subsequent packets on the connection will use
1301  * the new tag.  If a new tag cannot be allocated, drop the
1302  * connection.
1303  */
1304 static void
1305 ktls_reset_send_tag(void *context, int pending)
1306 {
1307 	struct epoch_tracker et;
1308 	struct ktls_session *tls;
1309 	struct m_snd_tag *old, *new;
1310 	struct inpcb *inp;
1311 	struct tcpcb *tp;
1312 	int error;
1313 
1314 	MPASS(pending == 1);
1315 
1316 	tls = context;
1317 	inp = tls->inp;
1318 
1319 	/*
1320 	 * Free the old tag first before allocating a new one.
1321 	 * ip[6]_output_send() will treat a NULL send tag the same as
1322 	 * an ifp mismatch and drop packets until a new tag is
1323 	 * allocated.
1324 	 *
1325 	 * Write-lock the INP when changing tls->snd_tag since
1326 	 * ip[6]_output_send() holds a read-lock when reading the
1327 	 * pointer.
1328 	 */
1329 	INP_WLOCK(inp);
1330 	old = tls->snd_tag;
1331 	tls->snd_tag = NULL;
1332 	INP_WUNLOCK(inp);
1333 	if (old != NULL)
1334 		m_snd_tag_rele(old);
1335 
1336 	error = ktls_alloc_snd_tag(inp, tls, true, &new);
1337 
1338 	if (error == 0) {
1339 		INP_WLOCK(inp);
1340 		tls->snd_tag = new;
1341 		mtx_pool_lock(mtxpool_sleep, tls);
1342 		tls->reset_pending = false;
1343 		mtx_pool_unlock(mtxpool_sleep, tls);
1344 		if (!in_pcbrele_wlocked(inp))
1345 			INP_WUNLOCK(inp);
1346 
1347 		counter_u64_add(ktls_ifnet_reset, 1);
1348 
1349 		/*
1350 		 * XXX: Should we kick tcp_output explicitly now that
1351 		 * the send tag is fixed or just rely on timers?
1352 		 */
1353 	} else {
1354 		NET_EPOCH_ENTER(et);
1355 		INP_WLOCK(inp);
1356 		if (!in_pcbrele_wlocked(inp)) {
1357 			if (!(inp->inp_flags & INP_TIMEWAIT) &&
1358 			    !(inp->inp_flags & INP_DROPPED)) {
1359 				tp = intotcpcb(inp);
1360 				CURVNET_SET(tp->t_vnet);
1361 				tp = tcp_drop(tp, ECONNABORTED);
1362 				CURVNET_RESTORE();
1363 				if (tp != NULL)
1364 					INP_WUNLOCK(inp);
1365 				counter_u64_add(ktls_ifnet_reset_dropped, 1);
1366 			} else
1367 				INP_WUNLOCK(inp);
1368 		}
1369 		NET_EPOCH_EXIT(et);
1370 
1371 		counter_u64_add(ktls_ifnet_reset_failed, 1);
1372 
1373 		/*
1374 		 * Leave reset_pending true to avoid future tasks while
1375 		 * the socket goes away.
1376 		 */
1377 	}
1378 
1379 	ktls_free(tls);
1380 }
1381 
1382 int
1383 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1384 {
1385 
1386 	if (inp == NULL)
1387 		return (ENOBUFS);
1388 
1389 	INP_LOCK_ASSERT(inp);
1390 
1391 	/*
1392 	 * See if we should schedule a task to update the send tag for
1393 	 * this session.
1394 	 */
1395 	mtx_pool_lock(mtxpool_sleep, tls);
1396 	if (!tls->reset_pending) {
1397 		(void) ktls_hold(tls);
1398 		in_pcbref(inp);
1399 		tls->inp = inp;
1400 		tls->reset_pending = true;
1401 		taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1402 	}
1403 	mtx_pool_unlock(mtxpool_sleep, tls);
1404 	return (ENOBUFS);
1405 }
1406 
1407 #ifdef RATELIMIT
1408 int
1409 ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1410 {
1411 	union if_snd_tag_modify_params params = {
1412 		.rate_limit.max_rate = max_pacing_rate,
1413 		.rate_limit.flags = M_NOWAIT,
1414 	};
1415 	struct m_snd_tag *mst;
1416 	struct ifnet *ifp;
1417 	int error;
1418 
1419 	/* Can't get to the inp, but it should be locked. */
1420 	/* INP_LOCK_ASSERT(inp); */
1421 
1422 	MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1423 
1424 	if (tls->snd_tag == NULL) {
1425 		/*
1426 		 * Resetting send tag, ignore this change.  The
1427 		 * pending reset may or may not see this updated rate
1428 		 * in the tcpcb.  If it doesn't, we will just lose
1429 		 * this rate change.
1430 		 */
1431 		return (0);
1432 	}
1433 
1434 	MPASS(tls->snd_tag != NULL);
1435 	MPASS(tls->snd_tag->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1436 
1437 	mst = tls->snd_tag;
1438 	ifp = mst->ifp;
1439 	return (ifp->if_snd_tag_modify(mst, &params));
1440 }
1441 #endif
1442 #endif
1443 
1444 void
1445 ktls_destroy(struct ktls_session *tls)
1446 {
1447 	struct rm_priotracker prio;
1448 
1449 	ktls_cleanup(tls);
1450 	if (tls->be != NULL && ktls_allow_unload) {
1451 		rm_rlock(&ktls_backends_lock, &prio);
1452 		tls->be->use_count--;
1453 		rm_runlock(&ktls_backends_lock, &prio);
1454 	}
1455 	uma_zfree(ktls_session_zone, tls);
1456 }
1457 
1458 void
1459 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1460 {
1461 
1462 	for (; m != NULL; m = m->m_next) {
1463 		KASSERT((m->m_flags & M_EXTPG) != 0,
1464 		    ("ktls_seq: mapped mbuf %p", m));
1465 
1466 		m->m_epg_seqno = sb->sb_tls_seqno;
1467 		sb->sb_tls_seqno++;
1468 	}
1469 }
1470 
1471 /*
1472  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
1473  * mbuf in the chain must be an unmapped mbuf.  The payload of the
1474  * mbuf must be populated with the payload of each TLS record.
1475  *
1476  * The record_type argument specifies the TLS record type used when
1477  * populating the TLS header.
1478  *
1479  * The enq_count argument on return is set to the number of pages of
1480  * payload data for this entire chain that need to be encrypted via SW
1481  * encryption.  The returned value should be passed to ktls_enqueue
1482  * when scheduling encryption of this chain of mbufs.  To handle the
1483  * special case of empty fragments for TLS 1.0 sessions, an empty
1484  * fragment counts as one page.
1485  */
1486 void
1487 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1488     uint8_t record_type)
1489 {
1490 	struct tls_record_layer *tlshdr;
1491 	struct mbuf *m;
1492 	uint64_t *noncep;
1493 	uint16_t tls_len;
1494 	int maxlen;
1495 
1496 	maxlen = tls->params.max_frame_len;
1497 	*enq_cnt = 0;
1498 	for (m = top; m != NULL; m = m->m_next) {
1499 		/*
1500 		 * All mbufs in the chain should be TLS records whose
1501 		 * payload does not exceed the maximum frame length.
1502 		 *
1503 		 * Empty TLS records are permitted when using CBC.
1504 		 */
1505 		KASSERT(m->m_len <= maxlen &&
1506 		    (tls->params.cipher_algorithm == CRYPTO_AES_CBC ?
1507 		    m->m_len >= 0 : m->m_len > 0),
1508 		    ("ktls_frame: m %p len %d\n", m, m->m_len));
1509 
1510 		/*
1511 		 * TLS frames require unmapped mbufs to store session
1512 		 * info.
1513 		 */
1514 		KASSERT((m->m_flags & M_EXTPG) != 0,
1515 		    ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1516 
1517 		tls_len = m->m_len;
1518 
1519 		/* Save a reference to the session. */
1520 		m->m_epg_tls = ktls_hold(tls);
1521 
1522 		m->m_epg_hdrlen = tls->params.tls_hlen;
1523 		m->m_epg_trllen = tls->params.tls_tlen;
1524 		if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1525 			int bs, delta;
1526 
1527 			/*
1528 			 * AES-CBC pads messages to a multiple of the
1529 			 * block size.  Note that the padding is
1530 			 * applied after the digest and the encryption
1531 			 * is done on the "plaintext || mac || padding".
1532 			 * At least one byte of padding is always
1533 			 * present.
1534 			 *
1535 			 * Compute the final trailer length assuming
1536 			 * at most one block of padding.
1537 			 * tls->params.sb_tls_tlen is the maximum
1538 			 * possible trailer length (padding + digest).
1539 			 * delta holds the number of excess padding
1540 			 * bytes if the maximum were used.  Those
1541 			 * extra bytes are removed.
1542 			 */
1543 			bs = tls->params.tls_bs;
1544 			delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1545 			m->m_epg_trllen -= delta;
1546 		}
1547 		m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1548 
1549 		/* Populate the TLS header. */
1550 		tlshdr = (void *)m->m_epg_hdr;
1551 		tlshdr->tls_vmajor = tls->params.tls_vmajor;
1552 
1553 		/*
1554 		 * TLS 1.3 masquarades as TLS 1.2 with a record type
1555 		 * of TLS_RLTYPE_APP.
1556 		 */
1557 		if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1558 		    tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1559 			tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1560 			tlshdr->tls_type = TLS_RLTYPE_APP;
1561 			/* save the real record type for later */
1562 			m->m_epg_record_type = record_type;
1563 			m->m_epg_trail[0] = record_type;
1564 		} else {
1565 			tlshdr->tls_vminor = tls->params.tls_vminor;
1566 			tlshdr->tls_type = record_type;
1567 		}
1568 		tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1569 
1570 		/*
1571 		 * Store nonces / explicit IVs after the end of the
1572 		 * TLS header.
1573 		 *
1574 		 * For GCM with TLS 1.2, an 8 byte nonce is copied
1575 		 * from the end of the IV.  The nonce is then
1576 		 * incremented for use by the next record.
1577 		 *
1578 		 * For CBC, a random nonce is inserted for TLS 1.1+.
1579 		 */
1580 		if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
1581 		    tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
1582 			noncep = (uint64_t *)(tls->params.iv + 8);
1583 			be64enc(tlshdr + 1, *noncep);
1584 			(*noncep)++;
1585 		} else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1586 		    tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1587 			arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1588 
1589 		/*
1590 		 * When using SW encryption, mark the mbuf not ready.
1591 		 * It will be marked ready via sbready() after the
1592 		 * record has been encrypted.
1593 		 *
1594 		 * When using ifnet TLS, unencrypted TLS records are
1595 		 * sent down the stack to the NIC.
1596 		 */
1597 		if (tls->mode == TCP_TLS_MODE_SW) {
1598 			m->m_flags |= M_NOTREADY;
1599 			m->m_epg_nrdy = m->m_epg_npgs;
1600 			if (__predict_false(tls_len == 0)) {
1601 				/* TLS 1.0 empty fragment. */
1602 				*enq_cnt += 1;
1603 			} else
1604 				*enq_cnt += m->m_epg_npgs;
1605 		}
1606 	}
1607 }
1608 
1609 void
1610 ktls_check_rx(struct sockbuf *sb)
1611 {
1612 	struct tls_record_layer hdr;
1613 	struct ktls_wq *wq;
1614 	struct socket *so;
1615 	bool running;
1616 
1617 	SOCKBUF_LOCK_ASSERT(sb);
1618 	KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1619 	    __func__, sb));
1620 	so = __containerof(sb, struct socket, so_rcv);
1621 
1622 	if (sb->sb_flags & SB_TLS_RX_RUNNING)
1623 		return;
1624 
1625 	/* Is there enough queued for a TLS header? */
1626 	if (sb->sb_tlscc < sizeof(hdr)) {
1627 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
1628 			so->so_error = EMSGSIZE;
1629 		return;
1630 	}
1631 
1632 	m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
1633 
1634 	/* Is the entire record queued? */
1635 	if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
1636 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
1637 			so->so_error = EMSGSIZE;
1638 		return;
1639 	}
1640 
1641 	sb->sb_flags |= SB_TLS_RX_RUNNING;
1642 
1643 	soref(so);
1644 	wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
1645 	mtx_lock(&wq->mtx);
1646 	STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
1647 	running = wq->running;
1648 	mtx_unlock(&wq->mtx);
1649 	if (!running)
1650 		wakeup(wq);
1651 	counter_u64_add(ktls_cnt_rx_queued, 1);
1652 }
1653 
1654 static struct mbuf *
1655 ktls_detach_record(struct sockbuf *sb, int len)
1656 {
1657 	struct mbuf *m, *n, *top;
1658 	int remain;
1659 
1660 	SOCKBUF_LOCK_ASSERT(sb);
1661 	MPASS(len <= sb->sb_tlscc);
1662 
1663 	/*
1664 	 * If TLS chain is the exact size of the record,
1665 	 * just grab the whole record.
1666 	 */
1667 	top = sb->sb_mtls;
1668 	if (sb->sb_tlscc == len) {
1669 		sb->sb_mtls = NULL;
1670 		sb->sb_mtlstail = NULL;
1671 		goto out;
1672 	}
1673 
1674 	/*
1675 	 * While it would be nice to use m_split() here, we need
1676 	 * to know exactly what m_split() allocates to update the
1677 	 * accounting, so do it inline instead.
1678 	 */
1679 	remain = len;
1680 	for (m = top; remain > m->m_len; m = m->m_next)
1681 		remain -= m->m_len;
1682 
1683 	/* Easy case: don't have to split 'm'. */
1684 	if (remain == m->m_len) {
1685 		sb->sb_mtls = m->m_next;
1686 		if (sb->sb_mtls == NULL)
1687 			sb->sb_mtlstail = NULL;
1688 		m->m_next = NULL;
1689 		goto out;
1690 	}
1691 
1692 	/*
1693 	 * Need to allocate an mbuf to hold the remainder of 'm'.  Try
1694 	 * with M_NOWAIT first.
1695 	 */
1696 	n = m_get(M_NOWAIT, MT_DATA);
1697 	if (n == NULL) {
1698 		/*
1699 		 * Use M_WAITOK with socket buffer unlocked.  If
1700 		 * 'sb_mtls' changes while the lock is dropped, return
1701 		 * NULL to force the caller to retry.
1702 		 */
1703 		SOCKBUF_UNLOCK(sb);
1704 
1705 		n = m_get(M_WAITOK, MT_DATA);
1706 
1707 		SOCKBUF_LOCK(sb);
1708 		if (sb->sb_mtls != top) {
1709 			m_free(n);
1710 			return (NULL);
1711 		}
1712 	}
1713 	n->m_flags |= M_NOTREADY;
1714 
1715 	/* Store remainder in 'n'. */
1716 	n->m_len = m->m_len - remain;
1717 	if (m->m_flags & M_EXT) {
1718 		n->m_data = m->m_data + remain;
1719 		mb_dupcl(n, m);
1720 	} else {
1721 		bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
1722 	}
1723 
1724 	/* Trim 'm' and update accounting. */
1725 	m->m_len -= n->m_len;
1726 	sb->sb_tlscc -= n->m_len;
1727 	sb->sb_ccc -= n->m_len;
1728 
1729 	/* Account for 'n'. */
1730 	sballoc_ktls_rx(sb, n);
1731 
1732 	/* Insert 'n' into the TLS chain. */
1733 	sb->sb_mtls = n;
1734 	n->m_next = m->m_next;
1735 	if (sb->sb_mtlstail == m)
1736 		sb->sb_mtlstail = n;
1737 
1738 	/* Detach the record from the TLS chain. */
1739 	m->m_next = NULL;
1740 
1741 out:
1742 	MPASS(m_length(top, NULL) == len);
1743 	for (m = top; m != NULL; m = m->m_next)
1744 		sbfree_ktls_rx(sb, m);
1745 	sb->sb_tlsdcc = len;
1746 	sb->sb_ccc += len;
1747 	SBCHECK(sb);
1748 	return (top);
1749 }
1750 
1751 static void
1752 ktls_decrypt(struct socket *so)
1753 {
1754 	char tls_header[MBUF_PEXT_HDR_LEN];
1755 	struct ktls_session *tls;
1756 	struct sockbuf *sb;
1757 	struct tls_record_layer *hdr;
1758 	struct tls_get_record tgr;
1759 	struct mbuf *control, *data, *m;
1760 	uint64_t seqno;
1761 	int error, remain, tls_len, trail_len;
1762 
1763 	hdr = (struct tls_record_layer *)tls_header;
1764 	sb = &so->so_rcv;
1765 	SOCKBUF_LOCK(sb);
1766 	KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
1767 	    ("%s: socket %p not running", __func__, so));
1768 
1769 	tls = sb->sb_tls_info;
1770 	MPASS(tls != NULL);
1771 
1772 	for (;;) {
1773 		/* Is there enough queued for a TLS header? */
1774 		if (sb->sb_tlscc < tls->params.tls_hlen)
1775 			break;
1776 
1777 		m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
1778 		tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
1779 
1780 		if (hdr->tls_vmajor != tls->params.tls_vmajor ||
1781 		    hdr->tls_vminor != tls->params.tls_vminor)
1782 			error = EINVAL;
1783 		else if (tls_len < tls->params.tls_hlen || tls_len >
1784 		    tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
1785 		    tls->params.tls_tlen)
1786 			error = EMSGSIZE;
1787 		else
1788 			error = 0;
1789 		if (__predict_false(error != 0)) {
1790 			/*
1791 			 * We have a corrupted record and are likely
1792 			 * out of sync.  The connection isn't
1793 			 * recoverable at this point, so abort it.
1794 			 */
1795 			SOCKBUF_UNLOCK(sb);
1796 			counter_u64_add(ktls_offload_corrupted_records, 1);
1797 
1798 			CURVNET_SET(so->so_vnet);
1799 			so->so_proto->pr_usrreqs->pru_abort(so);
1800 			so->so_error = error;
1801 			CURVNET_RESTORE();
1802 			goto deref;
1803 		}
1804 
1805 		/* Is the entire record queued? */
1806 		if (sb->sb_tlscc < tls_len)
1807 			break;
1808 
1809 		/*
1810 		 * Split out the portion of the mbuf chain containing
1811 		 * this TLS record.
1812 		 */
1813 		data = ktls_detach_record(sb, tls_len);
1814 		if (data == NULL)
1815 			continue;
1816 		MPASS(sb->sb_tlsdcc == tls_len);
1817 
1818 		seqno = sb->sb_tls_seqno;
1819 		sb->sb_tls_seqno++;
1820 		SBCHECK(sb);
1821 		SOCKBUF_UNLOCK(sb);
1822 
1823 		error = tls->sw_decrypt(tls, hdr, data, seqno, &trail_len);
1824 		if (error) {
1825 			counter_u64_add(ktls_offload_failed_crypto, 1);
1826 
1827 			SOCKBUF_LOCK(sb);
1828 			if (sb->sb_tlsdcc == 0) {
1829 				/*
1830 				 * sbcut/drop/flush discarded these
1831 				 * mbufs.
1832 				 */
1833 				m_freem(data);
1834 				break;
1835 			}
1836 
1837 			/*
1838 			 * Drop this TLS record's data, but keep
1839 			 * decrypting subsequent records.
1840 			 */
1841 			sb->sb_ccc -= tls_len;
1842 			sb->sb_tlsdcc = 0;
1843 
1844 			CURVNET_SET(so->so_vnet);
1845 			so->so_error = EBADMSG;
1846 			sorwakeup_locked(so);
1847 			CURVNET_RESTORE();
1848 
1849 			m_freem(data);
1850 
1851 			SOCKBUF_LOCK(sb);
1852 			continue;
1853 		}
1854 
1855 		/* Allocate the control mbuf. */
1856 		tgr.tls_type = hdr->tls_type;
1857 		tgr.tls_vmajor = hdr->tls_vmajor;
1858 		tgr.tls_vminor = hdr->tls_vminor;
1859 		tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
1860 		    trail_len);
1861 		control = sbcreatecontrol_how(&tgr, sizeof(tgr),
1862 		    TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
1863 
1864 		SOCKBUF_LOCK(sb);
1865 		if (sb->sb_tlsdcc == 0) {
1866 			/* sbcut/drop/flush discarded these mbufs. */
1867 			MPASS(sb->sb_tlscc == 0);
1868 			m_freem(data);
1869 			m_freem(control);
1870 			break;
1871 		}
1872 
1873 		/*
1874 		 * Clear the 'dcc' accounting in preparation for
1875 		 * adding the decrypted record.
1876 		 */
1877 		sb->sb_ccc -= tls_len;
1878 		sb->sb_tlsdcc = 0;
1879 		SBCHECK(sb);
1880 
1881 		/* If there is no payload, drop all of the data. */
1882 		if (tgr.tls_length == htobe16(0)) {
1883 			m_freem(data);
1884 			data = NULL;
1885 		} else {
1886 			/* Trim header. */
1887 			remain = tls->params.tls_hlen;
1888 			while (remain > 0) {
1889 				if (data->m_len > remain) {
1890 					data->m_data += remain;
1891 					data->m_len -= remain;
1892 					break;
1893 				}
1894 				remain -= data->m_len;
1895 				data = m_free(data);
1896 			}
1897 
1898 			/* Trim trailer and clear M_NOTREADY. */
1899 			remain = be16toh(tgr.tls_length);
1900 			m = data;
1901 			for (m = data; remain > m->m_len; m = m->m_next) {
1902 				m->m_flags &= ~M_NOTREADY;
1903 				remain -= m->m_len;
1904 			}
1905 			m->m_len = remain;
1906 			m_freem(m->m_next);
1907 			m->m_next = NULL;
1908 			m->m_flags &= ~M_NOTREADY;
1909 
1910 			/* Set EOR on the final mbuf. */
1911 			m->m_flags |= M_EOR;
1912 		}
1913 
1914 		sbappendcontrol_locked(sb, data, control, 0);
1915 	}
1916 
1917 	sb->sb_flags &= ~SB_TLS_RX_RUNNING;
1918 
1919 	if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
1920 		so->so_error = EMSGSIZE;
1921 
1922 	sorwakeup_locked(so);
1923 
1924 deref:
1925 	SOCKBUF_UNLOCK_ASSERT(sb);
1926 
1927 	CURVNET_SET(so->so_vnet);
1928 	SOCK_LOCK(so);
1929 	sorele(so);
1930 	CURVNET_RESTORE();
1931 }
1932 
1933 void
1934 ktls_enqueue_to_free(struct mbuf *m)
1935 {
1936 	struct ktls_wq *wq;
1937 	bool running;
1938 
1939 	/* Mark it for freeing. */
1940 	m->m_epg_flags |= EPG_FLAG_2FREE;
1941 	wq = &ktls_wq[m->m_epg_tls->wq_index];
1942 	mtx_lock(&wq->mtx);
1943 	STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1944 	running = wq->running;
1945 	mtx_unlock(&wq->mtx);
1946 	if (!running)
1947 		wakeup(wq);
1948 }
1949 
1950 void
1951 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1952 {
1953 	struct ktls_wq *wq;
1954 	bool running;
1955 
1956 	KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
1957 	    (M_EXTPG | M_NOTREADY)),
1958 	    ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
1959 	KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
1960 
1961 	KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1962 
1963 	m->m_epg_enc_cnt = page_count;
1964 
1965 	/*
1966 	 * Save a pointer to the socket.  The caller is responsible
1967 	 * for taking an additional reference via soref().
1968 	 */
1969 	m->m_epg_so = so;
1970 
1971 	wq = &ktls_wq[m->m_epg_tls->wq_index];
1972 	mtx_lock(&wq->mtx);
1973 	STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1974 	running = wq->running;
1975 	mtx_unlock(&wq->mtx);
1976 	if (!running)
1977 		wakeup(wq);
1978 	counter_u64_add(ktls_cnt_tx_queued, 1);
1979 }
1980 
1981 static __noinline void
1982 ktls_encrypt(struct mbuf *top)
1983 {
1984 	struct ktls_session *tls;
1985 	struct socket *so;
1986 	struct mbuf *m;
1987 	vm_paddr_t parray[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1988 	struct iovec src_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1989 	struct iovec dst_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1990 	vm_page_t pg;
1991 	int error, i, len, npages, off, total_pages;
1992 	bool is_anon;
1993 
1994 	so = top->m_epg_so;
1995 	tls = top->m_epg_tls;
1996 	KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
1997 	KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
1998 #ifdef INVARIANTS
1999 	top->m_epg_so = NULL;
2000 #endif
2001 	total_pages = top->m_epg_enc_cnt;
2002 	npages = 0;
2003 
2004 	/*
2005 	 * Encrypt the TLS records in the chain of mbufs starting with
2006 	 * 'top'.  'total_pages' gives us a total count of pages and is
2007 	 * used to know when we have finished encrypting the TLS
2008 	 * records originally queued with 'top'.
2009 	 *
2010 	 * NB: These mbufs are queued in the socket buffer and
2011 	 * 'm_next' is traversing the mbufs in the socket buffer.  The
2012 	 * socket buffer lock is not held while traversing this chain.
2013 	 * Since the mbufs are all marked M_NOTREADY their 'm_next'
2014 	 * pointers should be stable.  However, the 'm_next' of the
2015 	 * last mbuf encrypted is not necessarily NULL.  It can point
2016 	 * to other mbufs appended while 'top' was on the TLS work
2017 	 * queue.
2018 	 *
2019 	 * Each mbuf holds an entire TLS record.
2020 	 */
2021 	error = 0;
2022 	for (m = top; npages != total_pages; m = m->m_next) {
2023 		KASSERT(m->m_epg_tls == tls,
2024 		    ("different TLS sessions in a single mbuf chain: %p vs %p",
2025 		    tls, m->m_epg_tls));
2026 		KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2027 		    (M_EXTPG | M_NOTREADY),
2028 		    ("%p not unready & nomap mbuf (top = %p)\n", m, top));
2029 		KASSERT(npages + m->m_epg_npgs <= total_pages,
2030 		    ("page count mismatch: top %p, total_pages %d, m %p", top,
2031 		    total_pages, m));
2032 
2033 		/*
2034 		 * Generate source and destination ivoecs to pass to
2035 		 * the SW encryption backend.  For writable mbufs, the
2036 		 * destination iovec is a copy of the source and
2037 		 * encryption is done in place.  For file-backed mbufs
2038 		 * (from sendfile), anonymous wired pages are
2039 		 * allocated and assigned to the destination iovec.
2040 		 */
2041 		is_anon = (m->m_epg_flags & EPG_FLAG_ANON) != 0;
2042 
2043 		off = m->m_epg_1st_off;
2044 		for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2045 			len = m_epg_pagelen(m, i, off);
2046 			src_iov[i].iov_len = len;
2047 			src_iov[i].iov_base =
2048 			    (char *)(void *)PHYS_TO_DMAP(m->m_epg_pa[i]) +
2049 				off;
2050 
2051 			if (is_anon) {
2052 				dst_iov[i].iov_base = src_iov[i].iov_base;
2053 				dst_iov[i].iov_len = src_iov[i].iov_len;
2054 				continue;
2055 			}
2056 retry_page:
2057 			pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2058 			    VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP | VM_ALLOC_WIRED);
2059 			if (pg == NULL) {
2060 				vm_wait(NULL);
2061 				goto retry_page;
2062 			}
2063 			parray[i] = VM_PAGE_TO_PHYS(pg);
2064 			dst_iov[i].iov_base =
2065 			    (char *)(void *)PHYS_TO_DMAP(parray[i]) + off;
2066 			dst_iov[i].iov_len = len;
2067 		}
2068 
2069 		if (__predict_false(m->m_epg_npgs == 0)) {
2070 			/* TLS 1.0 empty fragment. */
2071 			npages++;
2072 		} else
2073 			npages += i;
2074 
2075 		error = (*tls->sw_encrypt)(tls,
2076 		    (const struct tls_record_layer *)m->m_epg_hdr,
2077 		    m->m_epg_trail, src_iov, dst_iov, i, m->m_epg_seqno,
2078 		    m->m_epg_record_type);
2079 		if (error) {
2080 			counter_u64_add(ktls_offload_failed_crypto, 1);
2081 			break;
2082 		}
2083 
2084 		/*
2085 		 * For file-backed mbufs, release the file-backed
2086 		 * pages and replace them in the ext_pgs array with
2087 		 * the anonymous wired pages allocated above.
2088 		 */
2089 		if (!is_anon) {
2090 			/* Free the old pages. */
2091 			m->m_ext.ext_free(m);
2092 
2093 			/* Replace them with the new pages. */
2094 			for (i = 0; i < m->m_epg_npgs; i++)
2095 				m->m_epg_pa[i] = parray[i];
2096 
2097 			/* Use the basic free routine. */
2098 			m->m_ext.ext_free = mb_free_mext_pgs;
2099 
2100 			/* Pages are now writable. */
2101 			m->m_epg_flags |= EPG_FLAG_ANON;
2102 		}
2103 
2104 		/*
2105 		 * Drop a reference to the session now that it is no
2106 		 * longer needed.  Existing code depends on encrypted
2107 		 * records having no associated session vs
2108 		 * yet-to-be-encrypted records having an associated
2109 		 * session.
2110 		 */
2111 		m->m_epg_tls = NULL;
2112 		ktls_free(tls);
2113 	}
2114 
2115 	CURVNET_SET(so->so_vnet);
2116 	if (error == 0) {
2117 		(void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
2118 	} else {
2119 		so->so_proto->pr_usrreqs->pru_abort(so);
2120 		so->so_error = EIO;
2121 		mb_free_notready(top, total_pages);
2122 	}
2123 
2124 	SOCK_LOCK(so);
2125 	sorele(so);
2126 	CURVNET_RESTORE();
2127 }
2128 
2129 static void
2130 ktls_work_thread(void *ctx)
2131 {
2132 	struct ktls_wq *wq = ctx;
2133 	struct mbuf *m, *n;
2134 	struct socket *so, *son;
2135 	STAILQ_HEAD(, mbuf) local_m_head;
2136 	STAILQ_HEAD(, socket) local_so_head;
2137 
2138 	if (ktls_bind_threads > 1) {
2139 		curthread->td_domain.dr_policy =
2140 			DOMAINSET_PREF(PCPU_GET(domain));
2141 	}
2142 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
2143 	fpu_kern_thread(0);
2144 #endif
2145 	for (;;) {
2146 		mtx_lock(&wq->mtx);
2147 		while (STAILQ_EMPTY(&wq->m_head) &&
2148 		    STAILQ_EMPTY(&wq->so_head)) {
2149 			wq->running = false;
2150 			mtx_sleep(wq, &wq->mtx, 0, "-", 0);
2151 			wq->running = true;
2152 		}
2153 
2154 		STAILQ_INIT(&local_m_head);
2155 		STAILQ_CONCAT(&local_m_head, &wq->m_head);
2156 		STAILQ_INIT(&local_so_head);
2157 		STAILQ_CONCAT(&local_so_head, &wq->so_head);
2158 		mtx_unlock(&wq->mtx);
2159 
2160 		STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
2161 			if (m->m_epg_flags & EPG_FLAG_2FREE) {
2162 				ktls_free(m->m_epg_tls);
2163 				uma_zfree(zone_mbuf, m);
2164 			} else {
2165 				ktls_encrypt(m);
2166 				counter_u64_add(ktls_cnt_tx_queued, -1);
2167 			}
2168 		}
2169 
2170 		STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
2171 			ktls_decrypt(so);
2172 			counter_u64_add(ktls_cnt_rx_queued, -1);
2173 		}
2174 	}
2175 }
2176