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