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