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