xref: /freebsd/sys/kern/uipc_ktls.c (revision c7046f76c2c027b00c0e6ba57cfd28f1a78f5e23)
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_receive_tag(void *context, int pending);
303 static void ktls_reset_send_tag(void *context, int pending);
304 #endif
305 static void ktls_work_thread(void *ctx);
306 static void ktls_alloc_thread(void *ctx);
307 
308 #if defined(INET) || defined(INET6)
309 static u_int
310 ktls_get_cpu(struct socket *so)
311 {
312 	struct inpcb *inp;
313 #ifdef NUMA
314 	struct ktls_domain_info *di;
315 #endif
316 	u_int cpuid;
317 
318 	inp = sotoinpcb(so);
319 #ifdef RSS
320 	cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
321 	if (cpuid != NETISR_CPUID_NONE)
322 		return (cpuid);
323 #endif
324 	/*
325 	 * Just use the flowid to shard connections in a repeatable
326 	 * fashion.  Note that TLS 1.0 sessions rely on the
327 	 * serialization provided by having the same connection use
328 	 * the same queue.
329 	 */
330 #ifdef NUMA
331 	if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
332 		di = &ktls_domains[inp->inp_numa_domain];
333 		cpuid = di->cpu[inp->inp_flowid % di->count];
334 	} else
335 #endif
336 		cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
337 	return (cpuid);
338 }
339 #endif
340 
341 static int
342 ktls_buffer_import(void *arg, void **store, int count, int domain, int flags)
343 {
344 	vm_page_t m;
345 	int i, req;
346 
347 	KASSERT((ktls_maxlen & PAGE_MASK) == 0,
348 	    ("%s: ktls max length %d is not page size-aligned",
349 	    __func__, ktls_maxlen));
350 
351 	req = VM_ALLOC_WIRED | VM_ALLOC_NODUMP | malloc2vm_flags(flags);
352 	for (i = 0; i < count; i++) {
353 		m = vm_page_alloc_noobj_contig_domain(domain, req,
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, int direction)
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 		switch (en->tls_vminor) {
556 		case TLS_MINOR_VER_TWO:
557 			if (en->iv_len != TLS_AEAD_GCM_LEN)
558 				return (EINVAL);
559 			break;
560 		case TLS_MINOR_VER_THREE:
561 			if (en->iv_len != TLS_1_3_GCM_IV_LEN)
562 				return (EINVAL);
563 			break;
564 		default:
565 			return (EINVAL);
566 		}
567 		break;
568 	case CRYPTO_AES_CBC:
569 		switch (en->auth_algorithm) {
570 		case CRYPTO_SHA1_HMAC:
571 			break;
572 		case CRYPTO_SHA2_256_HMAC:
573 		case CRYPTO_SHA2_384_HMAC:
574 			if (en->tls_vminor != TLS_MINOR_VER_TWO)
575 				return (EINVAL);
576 			break;
577 		default:
578 			return (EINVAL);
579 		}
580 		if (en->auth_key_len == 0)
581 			return (EINVAL);
582 
583 		/*
584 		 * TLS 1.0 requires an implicit IV.  TLS 1.1 and 1.2
585 		 * use explicit IVs.
586 		 */
587 		switch (en->tls_vminor) {
588 		case TLS_MINOR_VER_ZERO:
589 			if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
590 				return (EINVAL);
591 			break;
592 		case TLS_MINOR_VER_ONE:
593 		case TLS_MINOR_VER_TWO:
594 			/* Ignore any supplied IV. */
595 			en->iv_len = 0;
596 			break;
597 		default:
598 			return (EINVAL);
599 		}
600 		break;
601 	case CRYPTO_CHACHA20_POLY1305:
602 		if (en->auth_algorithm != 0 || en->auth_key_len != 0)
603 			return (EINVAL);
604 		if (en->tls_vminor != TLS_MINOR_VER_TWO &&
605 		    en->tls_vminor != TLS_MINOR_VER_THREE)
606 			return (EINVAL);
607 		if (en->iv_len != TLS_CHACHA20_IV_LEN)
608 			return (EINVAL);
609 		break;
610 	default:
611 		return (EINVAL);
612 	}
613 
614 	error = ktls_start_kthreads();
615 	if (error != 0)
616 		return (error);
617 
618 	tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
619 
620 	counter_u64_add(ktls_offload_active, 1);
621 
622 	refcount_init(&tls->refcount, 1);
623 	if (direction == KTLS_RX)
624 		TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_receive_tag, tls);
625 	else
626 		TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
627 
628 	tls->wq_index = ktls_get_cpu(so);
629 
630 	tls->params.cipher_algorithm = en->cipher_algorithm;
631 	tls->params.auth_algorithm = en->auth_algorithm;
632 	tls->params.tls_vmajor = en->tls_vmajor;
633 	tls->params.tls_vminor = en->tls_vminor;
634 	tls->params.flags = en->flags;
635 	tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
636 
637 	/* Set the header and trailer lengths. */
638 	tls->params.tls_hlen = sizeof(struct tls_record_layer);
639 	switch (en->cipher_algorithm) {
640 	case CRYPTO_AES_NIST_GCM_16:
641 		/*
642 		 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
643 		 * nonce.  TLS 1.3 uses a 12 byte implicit IV.
644 		 */
645 		if (en->tls_vminor < TLS_MINOR_VER_THREE)
646 			tls->params.tls_hlen += sizeof(uint64_t);
647 		tls->params.tls_tlen = AES_GMAC_HASH_LEN;
648 		tls->params.tls_bs = 1;
649 		break;
650 	case CRYPTO_AES_CBC:
651 		switch (en->auth_algorithm) {
652 		case CRYPTO_SHA1_HMAC:
653 			if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
654 				/* Implicit IV, no nonce. */
655 				tls->sequential_records = true;
656 				tls->next_seqno = be64dec(en->rec_seq);
657 				STAILQ_INIT(&tls->pending_records);
658 			} else {
659 				tls->params.tls_hlen += AES_BLOCK_LEN;
660 			}
661 			tls->params.tls_tlen = AES_BLOCK_LEN +
662 			    SHA1_HASH_LEN;
663 			break;
664 		case CRYPTO_SHA2_256_HMAC:
665 			tls->params.tls_hlen += AES_BLOCK_LEN;
666 			tls->params.tls_tlen = AES_BLOCK_LEN +
667 			    SHA2_256_HASH_LEN;
668 			break;
669 		case CRYPTO_SHA2_384_HMAC:
670 			tls->params.tls_hlen += AES_BLOCK_LEN;
671 			tls->params.tls_tlen = AES_BLOCK_LEN +
672 			    SHA2_384_HASH_LEN;
673 			break;
674 		default:
675 			panic("invalid hmac");
676 		}
677 		tls->params.tls_bs = AES_BLOCK_LEN;
678 		break;
679 	case CRYPTO_CHACHA20_POLY1305:
680 		/*
681 		 * Chacha20 uses a 12 byte implicit IV.
682 		 */
683 		tls->params.tls_tlen = POLY1305_HASH_LEN;
684 		tls->params.tls_bs = 1;
685 		break;
686 	default:
687 		panic("invalid cipher");
688 	}
689 
690 	/*
691 	 * TLS 1.3 includes optional padding which we do not support,
692 	 * and also puts the "real" record type at the end of the
693 	 * encrypted data.
694 	 */
695 	if (en->tls_vminor == TLS_MINOR_VER_THREE)
696 		tls->params.tls_tlen += sizeof(uint8_t);
697 
698 	KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
699 	    ("TLS header length too long: %d", tls->params.tls_hlen));
700 	KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
701 	    ("TLS trailer length too long: %d", tls->params.tls_tlen));
702 
703 	if (en->auth_key_len != 0) {
704 		tls->params.auth_key_len = en->auth_key_len;
705 		tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
706 		    M_WAITOK);
707 		error = copyin(en->auth_key, tls->params.auth_key,
708 		    en->auth_key_len);
709 		if (error)
710 			goto out;
711 	}
712 
713 	tls->params.cipher_key_len = en->cipher_key_len;
714 	tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
715 	error = copyin(en->cipher_key, tls->params.cipher_key,
716 	    en->cipher_key_len);
717 	if (error)
718 		goto out;
719 
720 	/*
721 	 * This holds the implicit portion of the nonce for AEAD
722 	 * ciphers and the initial implicit IV for TLS 1.0.  The
723 	 * explicit portions of the IV are generated in ktls_frame().
724 	 */
725 	if (en->iv_len != 0) {
726 		tls->params.iv_len = en->iv_len;
727 		error = copyin(en->iv, tls->params.iv, en->iv_len);
728 		if (error)
729 			goto out;
730 
731 		/*
732 		 * For TLS 1.2 with GCM, generate an 8-byte nonce as a
733 		 * counter to generate unique explicit IVs.
734 		 *
735 		 * Store this counter in the last 8 bytes of the IV
736 		 * array so that it is 8-byte aligned.
737 		 */
738 		if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
739 		    en->tls_vminor == TLS_MINOR_VER_TWO)
740 			arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
741 	}
742 
743 	*tlsp = tls;
744 	return (0);
745 
746 out:
747 	ktls_cleanup(tls);
748 	return (error);
749 }
750 
751 static struct ktls_session *
752 ktls_clone_session(struct ktls_session *tls, int direction)
753 {
754 	struct ktls_session *tls_new;
755 
756 	tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
757 
758 	counter_u64_add(ktls_offload_active, 1);
759 
760 	refcount_init(&tls_new->refcount, 1);
761 	if (direction == KTLS_RX)
762 		TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_receive_tag,
763 		    tls_new);
764 	else
765 		TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_send_tag,
766 		    tls_new);
767 
768 	/* Copy fields from existing session. */
769 	tls_new->params = tls->params;
770 	tls_new->wq_index = tls->wq_index;
771 
772 	/* Deep copy keys. */
773 	if (tls_new->params.auth_key != NULL) {
774 		tls_new->params.auth_key = malloc(tls->params.auth_key_len,
775 		    M_KTLS, M_WAITOK);
776 		memcpy(tls_new->params.auth_key, tls->params.auth_key,
777 		    tls->params.auth_key_len);
778 	}
779 
780 	tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
781 	    M_WAITOK);
782 	memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
783 	    tls->params.cipher_key_len);
784 
785 	return (tls_new);
786 }
787 #endif
788 
789 static void
790 ktls_cleanup(struct ktls_session *tls)
791 {
792 
793 	counter_u64_add(ktls_offload_active, -1);
794 	switch (tls->mode) {
795 	case TCP_TLS_MODE_SW:
796 		switch (tls->params.cipher_algorithm) {
797 		case CRYPTO_AES_CBC:
798 			counter_u64_add(ktls_sw_cbc, -1);
799 			break;
800 		case CRYPTO_AES_NIST_GCM_16:
801 			counter_u64_add(ktls_sw_gcm, -1);
802 			break;
803 		case CRYPTO_CHACHA20_POLY1305:
804 			counter_u64_add(ktls_sw_chacha20, -1);
805 			break;
806 		}
807 		break;
808 	case TCP_TLS_MODE_IFNET:
809 		switch (tls->params.cipher_algorithm) {
810 		case CRYPTO_AES_CBC:
811 			counter_u64_add(ktls_ifnet_cbc, -1);
812 			break;
813 		case CRYPTO_AES_NIST_GCM_16:
814 			counter_u64_add(ktls_ifnet_gcm, -1);
815 			break;
816 		case CRYPTO_CHACHA20_POLY1305:
817 			counter_u64_add(ktls_ifnet_chacha20, -1);
818 			break;
819 		}
820 		if (tls->snd_tag != NULL)
821 			m_snd_tag_rele(tls->snd_tag);
822 		if (tls->rx_ifp != NULL)
823 			if_rele(tls->rx_ifp);
824 		break;
825 #ifdef TCP_OFFLOAD
826 	case TCP_TLS_MODE_TOE:
827 		switch (tls->params.cipher_algorithm) {
828 		case CRYPTO_AES_CBC:
829 			counter_u64_add(ktls_toe_cbc, -1);
830 			break;
831 		case CRYPTO_AES_NIST_GCM_16:
832 			counter_u64_add(ktls_toe_gcm, -1);
833 			break;
834 		case CRYPTO_CHACHA20_POLY1305:
835 			counter_u64_add(ktls_toe_chacha20, -1);
836 			break;
837 		}
838 		break;
839 #endif
840 	}
841 	if (tls->ocf_session != NULL)
842 		ktls_ocf_free(tls);
843 	if (tls->params.auth_key != NULL) {
844 		zfree(tls->params.auth_key, M_KTLS);
845 		tls->params.auth_key = NULL;
846 		tls->params.auth_key_len = 0;
847 	}
848 	if (tls->params.cipher_key != NULL) {
849 		zfree(tls->params.cipher_key, M_KTLS);
850 		tls->params.cipher_key = NULL;
851 		tls->params.cipher_key_len = 0;
852 	}
853 	explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
854 }
855 
856 #if defined(INET) || defined(INET6)
857 
858 #ifdef TCP_OFFLOAD
859 static int
860 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
861 {
862 	struct inpcb *inp;
863 	struct tcpcb *tp;
864 	int error;
865 
866 	inp = so->so_pcb;
867 	INP_WLOCK(inp);
868 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
869 		INP_WUNLOCK(inp);
870 		return (ECONNRESET);
871 	}
872 	if (inp->inp_socket == NULL) {
873 		INP_WUNLOCK(inp);
874 		return (ECONNRESET);
875 	}
876 	tp = intotcpcb(inp);
877 	if (!(tp->t_flags & TF_TOE)) {
878 		INP_WUNLOCK(inp);
879 		return (EOPNOTSUPP);
880 	}
881 
882 	error = tcp_offload_alloc_tls_session(tp, tls, direction);
883 	INP_WUNLOCK(inp);
884 	if (error == 0) {
885 		tls->mode = TCP_TLS_MODE_TOE;
886 		switch (tls->params.cipher_algorithm) {
887 		case CRYPTO_AES_CBC:
888 			counter_u64_add(ktls_toe_cbc, 1);
889 			break;
890 		case CRYPTO_AES_NIST_GCM_16:
891 			counter_u64_add(ktls_toe_gcm, 1);
892 			break;
893 		case CRYPTO_CHACHA20_POLY1305:
894 			counter_u64_add(ktls_toe_chacha20, 1);
895 			break;
896 		}
897 	}
898 	return (error);
899 }
900 #endif
901 
902 /*
903  * Common code used when first enabling ifnet TLS on a connection or
904  * when allocating a new ifnet TLS session due to a routing change.
905  * This function allocates a new TLS send tag on whatever interface
906  * the connection is currently routed over.
907  */
908 static int
909 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
910     struct m_snd_tag **mstp)
911 {
912 	union if_snd_tag_alloc_params params;
913 	struct ifnet *ifp;
914 	struct nhop_object *nh;
915 	struct tcpcb *tp;
916 	int error;
917 
918 	INP_RLOCK(inp);
919 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
920 		INP_RUNLOCK(inp);
921 		return (ECONNRESET);
922 	}
923 	if (inp->inp_socket == NULL) {
924 		INP_RUNLOCK(inp);
925 		return (ECONNRESET);
926 	}
927 	tp = intotcpcb(inp);
928 
929 	/*
930 	 * Check administrative controls on ifnet TLS to determine if
931 	 * ifnet TLS should be denied.
932 	 *
933 	 * - Always permit 'force' requests.
934 	 * - ktls_ifnet_permitted == 0: always deny.
935 	 */
936 	if (!force && ktls_ifnet_permitted == 0) {
937 		INP_RUNLOCK(inp);
938 		return (ENXIO);
939 	}
940 
941 	/*
942 	 * XXX: Use the cached route in the inpcb to find the
943 	 * interface.  This should perhaps instead use
944 	 * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
945 	 * enabled after a connection has completed key negotiation in
946 	 * userland, the cached route will be present in practice.
947 	 */
948 	nh = inp->inp_route.ro_nh;
949 	if (nh == NULL) {
950 		INP_RUNLOCK(inp);
951 		return (ENXIO);
952 	}
953 	ifp = nh->nh_ifp;
954 	if_ref(ifp);
955 
956 	/*
957 	 * Allocate a TLS + ratelimit tag if the connection has an
958 	 * existing pacing rate.
959 	 */
960 	if (tp->t_pacing_rate != -1 &&
961 	    (ifp->if_capenable & IFCAP_TXTLS_RTLMT) != 0) {
962 		params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
963 		params.tls_rate_limit.inp = inp;
964 		params.tls_rate_limit.tls = tls;
965 		params.tls_rate_limit.max_rate = tp->t_pacing_rate;
966 	} else {
967 		params.hdr.type = IF_SND_TAG_TYPE_TLS;
968 		params.tls.inp = inp;
969 		params.tls.tls = tls;
970 	}
971 	params.hdr.flowid = inp->inp_flowid;
972 	params.hdr.flowtype = inp->inp_flowtype;
973 	params.hdr.numa_domain = inp->inp_numa_domain;
974 	INP_RUNLOCK(inp);
975 
976 	if ((ifp->if_capenable & IFCAP_MEXTPG) == 0) {
977 		error = EOPNOTSUPP;
978 		goto out;
979 	}
980 	if (inp->inp_vflag & INP_IPV6) {
981 		if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
982 			error = EOPNOTSUPP;
983 			goto out;
984 		}
985 	} else {
986 		if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
987 			error = EOPNOTSUPP;
988 			goto out;
989 		}
990 	}
991 	error = m_snd_tag_alloc(ifp, &params, mstp);
992 out:
993 	if_rele(ifp);
994 	return (error);
995 }
996 
997 /*
998  * Allocate an initial TLS receive tag for doing HW decryption of TLS
999  * data.
1000  *
1001  * This function allocates a new TLS receive tag on whatever interface
1002  * the connection is currently routed over.  If the connection ends up
1003  * using a different interface for receive this will get fixed up via
1004  * ktls_input_ifp_mismatch as future packets arrive.
1005  */
1006 static int
1007 ktls_alloc_rcv_tag(struct inpcb *inp, struct ktls_session *tls,
1008     struct m_snd_tag **mstp)
1009 {
1010 	union if_snd_tag_alloc_params params;
1011 	struct ifnet *ifp;
1012 	struct nhop_object *nh;
1013 	int error;
1014 
1015 	if (!ktls_ocf_recrypt_supported(tls))
1016 		return (ENXIO);
1017 
1018 	INP_RLOCK(inp);
1019 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1020 		INP_RUNLOCK(inp);
1021 		return (ECONNRESET);
1022 	}
1023 	if (inp->inp_socket == NULL) {
1024 		INP_RUNLOCK(inp);
1025 		return (ECONNRESET);
1026 	}
1027 
1028 	/*
1029 	 * Check administrative controls on ifnet TLS to determine if
1030 	 * ifnet TLS should be denied.
1031 	 */
1032 	if (ktls_ifnet_permitted == 0) {
1033 		INP_RUNLOCK(inp);
1034 		return (ENXIO);
1035 	}
1036 
1037 	/*
1038 	 * XXX: As with ktls_alloc_snd_tag, use the cached route in
1039 	 * the inpcb to find the interface.
1040 	 */
1041 	nh = inp->inp_route.ro_nh;
1042 	if (nh == NULL) {
1043 		INP_RUNLOCK(inp);
1044 		return (ENXIO);
1045 	}
1046 	ifp = nh->nh_ifp;
1047 	if_ref(ifp);
1048 	tls->rx_ifp = ifp;
1049 
1050 	params.hdr.type = IF_SND_TAG_TYPE_TLS_RX;
1051 	params.hdr.flowid = inp->inp_flowid;
1052 	params.hdr.flowtype = inp->inp_flowtype;
1053 	params.hdr.numa_domain = inp->inp_numa_domain;
1054 	params.tls_rx.inp = inp;
1055 	params.tls_rx.tls = tls;
1056 	params.tls_rx.vlan_id = 0;
1057 
1058 	INP_RUNLOCK(inp);
1059 
1060 	if (inp->inp_vflag & INP_IPV6) {
1061 		if ((ifp->if_capenable2 & IFCAP2_RXTLS6) == 0) {
1062 			error = EOPNOTSUPP;
1063 			goto out;
1064 		}
1065 	} else {
1066 		if ((ifp->if_capenable2 & IFCAP2_RXTLS4) == 0) {
1067 			error = EOPNOTSUPP;
1068 			goto out;
1069 		}
1070 	}
1071 	error = m_snd_tag_alloc(ifp, &params, mstp);
1072 
1073 	/*
1074 	 * If this connection is over a vlan, vlan_snd_tag_alloc
1075 	 * rewrites vlan_id with the saved interface.  Save the VLAN
1076 	 * ID for use in ktls_reset_receive_tag which allocates new
1077 	 * receive tags directly from the leaf interface bypassing
1078 	 * if_vlan.
1079 	 */
1080 	if (error == 0)
1081 		tls->rx_vlan_id = params.tls_rx.vlan_id;
1082 out:
1083 	return (error);
1084 }
1085 
1086 static int
1087 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, int direction,
1088     bool force)
1089 {
1090 	struct m_snd_tag *mst;
1091 	int error;
1092 
1093 	switch (direction) {
1094 	case KTLS_TX:
1095 		error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
1096 		if (__predict_false(error != 0))
1097 			goto done;
1098 		break;
1099 	case KTLS_RX:
1100 		KASSERT(!force, ("%s: forced receive tag", __func__));
1101 		error = ktls_alloc_rcv_tag(so->so_pcb, tls, &mst);
1102 		if (__predict_false(error != 0))
1103 			goto done;
1104 		break;
1105 	default:
1106 		__assert_unreachable();
1107 	}
1108 
1109 	tls->mode = TCP_TLS_MODE_IFNET;
1110 	tls->snd_tag = mst;
1111 
1112 	switch (tls->params.cipher_algorithm) {
1113 	case CRYPTO_AES_CBC:
1114 		counter_u64_add(ktls_ifnet_cbc, 1);
1115 		break;
1116 	case CRYPTO_AES_NIST_GCM_16:
1117 		counter_u64_add(ktls_ifnet_gcm, 1);
1118 		break;
1119 	case CRYPTO_CHACHA20_POLY1305:
1120 		counter_u64_add(ktls_ifnet_chacha20, 1);
1121 		break;
1122 	default:
1123 		break;
1124 	}
1125 done:
1126 	return (error);
1127 }
1128 
1129 static void
1130 ktls_use_sw(struct ktls_session *tls)
1131 {
1132 	tls->mode = TCP_TLS_MODE_SW;
1133 	switch (tls->params.cipher_algorithm) {
1134 	case CRYPTO_AES_CBC:
1135 		counter_u64_add(ktls_sw_cbc, 1);
1136 		break;
1137 	case CRYPTO_AES_NIST_GCM_16:
1138 		counter_u64_add(ktls_sw_gcm, 1);
1139 		break;
1140 	case CRYPTO_CHACHA20_POLY1305:
1141 		counter_u64_add(ktls_sw_chacha20, 1);
1142 		break;
1143 	}
1144 }
1145 
1146 static int
1147 ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
1148 {
1149 	int error;
1150 
1151 	error = ktls_ocf_try(so, tls, direction);
1152 	if (error)
1153 		return (error);
1154 	ktls_use_sw(tls);
1155 	return (0);
1156 }
1157 
1158 /*
1159  * KTLS RX stores data in the socket buffer as a list of TLS records,
1160  * where each record is stored as a control message containg the TLS
1161  * header followed by data mbufs containing the decrypted data.  This
1162  * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
1163  * both encrypted and decrypted data.  TLS records decrypted by a NIC
1164  * should be queued to the socket buffer as records, but encrypted
1165  * data which needs to be decrypted by software arrives as a stream of
1166  * regular mbufs which need to be converted.  In addition, there may
1167  * already be pending encrypted data in the socket buffer when KTLS RX
1168  * is enabled.
1169  *
1170  * To manage not-yet-decrypted data for KTLS RX, the following scheme
1171  * is used:
1172  *
1173  * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
1174  *
1175  * - ktls_check_rx checks this chain of mbufs reading the TLS header
1176  *   from the first mbuf.  Once all of the data for that TLS record is
1177  *   queued, the socket is queued to a worker thread.
1178  *
1179  * - The worker thread calls ktls_decrypt to decrypt TLS records in
1180  *   the TLS chain.  Each TLS record is detached from the TLS chain,
1181  *   decrypted, and inserted into the regular socket buffer chain as
1182  *   record starting with a control message holding the TLS header and
1183  *   a chain of mbufs holding the encrypted data.
1184  */
1185 
1186 static void
1187 sb_mark_notready(struct sockbuf *sb)
1188 {
1189 	struct mbuf *m;
1190 
1191 	m = sb->sb_mb;
1192 	sb->sb_mtls = m;
1193 	sb->sb_mb = NULL;
1194 	sb->sb_mbtail = NULL;
1195 	sb->sb_lastrecord = NULL;
1196 	for (; m != NULL; m = m->m_next) {
1197 		KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
1198 		    __func__));
1199 		KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
1200 		    __func__));
1201 		KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
1202 		    __func__));
1203 		m->m_flags |= M_NOTREADY;
1204 		sb->sb_acc -= m->m_len;
1205 		sb->sb_tlscc += m->m_len;
1206 		sb->sb_mtlstail = m;
1207 	}
1208 	KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
1209 	    ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
1210 	    sb->sb_ccc));
1211 }
1212 
1213 /*
1214  * Return information about the pending TLS data in a socket
1215  * buffer.  On return, 'seqno' is set to the sequence number
1216  * of the next TLS record to be received, 'resid' is set to
1217  * the amount of bytes still needed for the last pending
1218  * record.  The function returns 'false' if the last pending
1219  * record contains a partial TLS header.  In that case, 'resid'
1220  * is the number of bytes needed to complete the TLS header.
1221  */
1222 bool
1223 ktls_pending_rx_info(struct sockbuf *sb, uint64_t *seqnop, size_t *residp)
1224 {
1225 	struct tls_record_layer hdr;
1226 	struct mbuf *m;
1227 	uint64_t seqno;
1228 	size_t resid;
1229 	u_int offset, record_len;
1230 
1231 	SOCKBUF_LOCK_ASSERT(sb);
1232 	MPASS(sb->sb_flags & SB_TLS_RX);
1233 	seqno = sb->sb_tls_seqno;
1234 	resid = sb->sb_tlscc;
1235 	m = sb->sb_mtls;
1236 	offset = 0;
1237 
1238 	if (resid == 0) {
1239 		*seqnop = seqno;
1240 		*residp = 0;
1241 		return (true);
1242 	}
1243 
1244 	for (;;) {
1245 		seqno++;
1246 
1247 		if (resid < sizeof(hdr)) {
1248 			*seqnop = seqno;
1249 			*residp = sizeof(hdr) - resid;
1250 			return (false);
1251 		}
1252 
1253 		m_copydata(m, offset, sizeof(hdr), (void *)&hdr);
1254 
1255 		record_len = sizeof(hdr) + ntohs(hdr.tls_length);
1256 		if (resid <= record_len) {
1257 			*seqnop = seqno;
1258 			*residp = record_len - resid;
1259 			return (true);
1260 		}
1261 		resid -= record_len;
1262 
1263 		while (record_len != 0) {
1264 			if (m->m_len - offset > record_len) {
1265 				offset += record_len;
1266 				break;
1267 			}
1268 
1269 			record_len -= (m->m_len - offset);
1270 			offset = 0;
1271 			m = m->m_next;
1272 		}
1273 	}
1274 }
1275 
1276 int
1277 ktls_enable_rx(struct socket *so, struct tls_enable *en)
1278 {
1279 	struct ktls_session *tls;
1280 	int error;
1281 
1282 	if (!ktls_offload_enable)
1283 		return (ENOTSUP);
1284 	if (SOLISTENING(so))
1285 		return (EINVAL);
1286 
1287 	counter_u64_add(ktls_offload_enable_calls, 1);
1288 
1289 	/*
1290 	 * This should always be true since only the TCP socket option
1291 	 * invokes this function.
1292 	 */
1293 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1294 		return (EINVAL);
1295 
1296 	/*
1297 	 * XXX: Don't overwrite existing sessions.  We should permit
1298 	 * this to support rekeying in the future.
1299 	 */
1300 	if (so->so_rcv.sb_tls_info != NULL)
1301 		return (EALREADY);
1302 
1303 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1304 		return (ENOTSUP);
1305 
1306 	error = ktls_create_session(so, en, &tls, KTLS_RX);
1307 	if (error)
1308 		return (error);
1309 
1310 	error = ktls_ocf_try(so, tls, KTLS_RX);
1311 	if (error) {
1312 		ktls_cleanup(tls);
1313 		return (error);
1314 	}
1315 
1316 	/* Mark the socket as using TLS offload. */
1317 	SOCKBUF_LOCK(&so->so_rcv);
1318 	so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1319 	so->so_rcv.sb_tls_info = tls;
1320 	so->so_rcv.sb_flags |= SB_TLS_RX;
1321 
1322 	/* Mark existing data as not ready until it can be decrypted. */
1323 	sb_mark_notready(&so->so_rcv);
1324 	ktls_check_rx(&so->so_rcv);
1325 	SOCKBUF_UNLOCK(&so->so_rcv);
1326 
1327 	/* Prefer TOE -> ifnet TLS -> software TLS. */
1328 #ifdef TCP_OFFLOAD
1329 	error = ktls_try_toe(so, tls, KTLS_RX);
1330 	if (error)
1331 #endif
1332 		error = ktls_try_ifnet(so, tls, KTLS_RX, false);
1333 	if (error)
1334 		ktls_use_sw(tls);
1335 
1336 	counter_u64_add(ktls_offload_total, 1);
1337 
1338 	return (0);
1339 }
1340 
1341 int
1342 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1343 {
1344 	struct ktls_session *tls;
1345 	struct inpcb *inp;
1346 	int error;
1347 
1348 	if (!ktls_offload_enable)
1349 		return (ENOTSUP);
1350 	if (SOLISTENING(so))
1351 		return (EINVAL);
1352 
1353 	counter_u64_add(ktls_offload_enable_calls, 1);
1354 
1355 	/*
1356 	 * This should always be true since only the TCP socket option
1357 	 * invokes this function.
1358 	 */
1359 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1360 		return (EINVAL);
1361 
1362 	/*
1363 	 * XXX: Don't overwrite existing sessions.  We should permit
1364 	 * this to support rekeying in the future.
1365 	 */
1366 	if (so->so_snd.sb_tls_info != NULL)
1367 		return (EALREADY);
1368 
1369 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1370 		return (ENOTSUP);
1371 
1372 	/* TLS requires ext pgs */
1373 	if (mb_use_ext_pgs == 0)
1374 		return (ENXIO);
1375 
1376 	error = ktls_create_session(so, en, &tls, KTLS_TX);
1377 	if (error)
1378 		return (error);
1379 
1380 	/* Prefer TOE -> ifnet TLS -> software TLS. */
1381 #ifdef TCP_OFFLOAD
1382 	error = ktls_try_toe(so, tls, KTLS_TX);
1383 	if (error)
1384 #endif
1385 		error = ktls_try_ifnet(so, tls, KTLS_TX, false);
1386 	if (error)
1387 		error = ktls_try_sw(so, tls, KTLS_TX);
1388 
1389 	if (error) {
1390 		ktls_cleanup(tls);
1391 		return (error);
1392 	}
1393 
1394 	error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1395 	if (error) {
1396 		ktls_cleanup(tls);
1397 		return (error);
1398 	}
1399 
1400 	/*
1401 	 * Write lock the INP when setting sb_tls_info so that
1402 	 * routines in tcp_ratelimit.c can read sb_tls_info while
1403 	 * holding the INP lock.
1404 	 */
1405 	inp = so->so_pcb;
1406 	INP_WLOCK(inp);
1407 	SOCKBUF_LOCK(&so->so_snd);
1408 	so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1409 	so->so_snd.sb_tls_info = tls;
1410 	if (tls->mode != TCP_TLS_MODE_SW)
1411 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1412 	SOCKBUF_UNLOCK(&so->so_snd);
1413 	INP_WUNLOCK(inp);
1414 	SOCK_IO_SEND_UNLOCK(so);
1415 
1416 	counter_u64_add(ktls_offload_total, 1);
1417 
1418 	return (0);
1419 }
1420 
1421 int
1422 ktls_get_rx_mode(struct socket *so, int *modep)
1423 {
1424 	struct ktls_session *tls;
1425 	struct inpcb *inp __diagused;
1426 
1427 	if (SOLISTENING(so))
1428 		return (EINVAL);
1429 	inp = so->so_pcb;
1430 	INP_WLOCK_ASSERT(inp);
1431 	SOCK_RECVBUF_LOCK(so);
1432 	tls = so->so_rcv.sb_tls_info;
1433 	if (tls == NULL)
1434 		*modep = TCP_TLS_MODE_NONE;
1435 	else
1436 		*modep = tls->mode;
1437 	SOCK_RECVBUF_UNLOCK(so);
1438 	return (0);
1439 }
1440 
1441 /*
1442  * ktls_get_rx_sequence - get the next TCP- and TLS- sequence number.
1443  *
1444  * This function gets information about the next TCP- and TLS-
1445  * sequence number to be processed by the TLS receive worker
1446  * thread. The information is extracted from the given "inpcb"
1447  * structure. The values are stored in host endian format at the two
1448  * given output pointer locations. The TCP sequence number points to
1449  * the beginning of the TLS header.
1450  *
1451  * This function returns zero on success, else a non-zero error code
1452  * is returned.
1453  */
1454 int
1455 ktls_get_rx_sequence(struct inpcb *inp, uint32_t *tcpseq, uint64_t *tlsseq)
1456 {
1457 	struct socket *so;
1458 	struct tcpcb *tp;
1459 
1460 	INP_RLOCK(inp);
1461 	so = inp->inp_socket;
1462 	if (__predict_false(so == NULL)) {
1463 		INP_RUNLOCK(inp);
1464 		return (EINVAL);
1465 	}
1466 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1467 		INP_RUNLOCK(inp);
1468 		return (ECONNRESET);
1469 	}
1470 
1471 	tp = intotcpcb(inp);
1472 	MPASS(tp != NULL);
1473 
1474 	SOCKBUF_LOCK(&so->so_rcv);
1475 	*tcpseq = tp->rcv_nxt - so->so_rcv.sb_tlscc;
1476 	*tlsseq = so->so_rcv.sb_tls_seqno;
1477 	SOCKBUF_UNLOCK(&so->so_rcv);
1478 
1479 	INP_RUNLOCK(inp);
1480 
1481 	return (0);
1482 }
1483 
1484 int
1485 ktls_get_tx_mode(struct socket *so, int *modep)
1486 {
1487 	struct ktls_session *tls;
1488 	struct inpcb *inp __diagused;
1489 
1490 	if (SOLISTENING(so))
1491 		return (EINVAL);
1492 	inp = so->so_pcb;
1493 	INP_WLOCK_ASSERT(inp);
1494 	SOCK_SENDBUF_LOCK(so);
1495 	tls = so->so_snd.sb_tls_info;
1496 	if (tls == NULL)
1497 		*modep = TCP_TLS_MODE_NONE;
1498 	else
1499 		*modep = tls->mode;
1500 	SOCK_SENDBUF_UNLOCK(so);
1501 	return (0);
1502 }
1503 
1504 /*
1505  * Switch between SW and ifnet TLS sessions as requested.
1506  */
1507 int
1508 ktls_set_tx_mode(struct socket *so, int mode)
1509 {
1510 	struct ktls_session *tls, *tls_new;
1511 	struct inpcb *inp;
1512 	int error;
1513 
1514 	if (SOLISTENING(so))
1515 		return (EINVAL);
1516 	switch (mode) {
1517 	case TCP_TLS_MODE_SW:
1518 	case TCP_TLS_MODE_IFNET:
1519 		break;
1520 	default:
1521 		return (EINVAL);
1522 	}
1523 
1524 	inp = so->so_pcb;
1525 	INP_WLOCK_ASSERT(inp);
1526 	SOCKBUF_LOCK(&so->so_snd);
1527 	tls = so->so_snd.sb_tls_info;
1528 	if (tls == NULL) {
1529 		SOCKBUF_UNLOCK(&so->so_snd);
1530 		return (0);
1531 	}
1532 
1533 	if (tls->mode == mode) {
1534 		SOCKBUF_UNLOCK(&so->so_snd);
1535 		return (0);
1536 	}
1537 
1538 	tls = ktls_hold(tls);
1539 	SOCKBUF_UNLOCK(&so->so_snd);
1540 	INP_WUNLOCK(inp);
1541 
1542 	tls_new = ktls_clone_session(tls, KTLS_TX);
1543 
1544 	if (mode == TCP_TLS_MODE_IFNET)
1545 		error = ktls_try_ifnet(so, tls_new, KTLS_TX, true);
1546 	else
1547 		error = ktls_try_sw(so, tls_new, KTLS_TX);
1548 	if (error) {
1549 		counter_u64_add(ktls_switch_failed, 1);
1550 		ktls_free(tls_new);
1551 		ktls_free(tls);
1552 		INP_WLOCK(inp);
1553 		return (error);
1554 	}
1555 
1556 	error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1557 	if (error) {
1558 		counter_u64_add(ktls_switch_failed, 1);
1559 		ktls_free(tls_new);
1560 		ktls_free(tls);
1561 		INP_WLOCK(inp);
1562 		return (error);
1563 	}
1564 
1565 	/*
1566 	 * If we raced with another session change, keep the existing
1567 	 * session.
1568 	 */
1569 	if (tls != so->so_snd.sb_tls_info) {
1570 		counter_u64_add(ktls_switch_failed, 1);
1571 		SOCK_IO_SEND_UNLOCK(so);
1572 		ktls_free(tls_new);
1573 		ktls_free(tls);
1574 		INP_WLOCK(inp);
1575 		return (EBUSY);
1576 	}
1577 
1578 	INP_WLOCK(inp);
1579 	SOCKBUF_LOCK(&so->so_snd);
1580 	so->so_snd.sb_tls_info = tls_new;
1581 	if (tls_new->mode != TCP_TLS_MODE_SW)
1582 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1583 	SOCKBUF_UNLOCK(&so->so_snd);
1584 	SOCK_IO_SEND_UNLOCK(so);
1585 
1586 	/*
1587 	 * Drop two references on 'tls'.  The first is for the
1588 	 * ktls_hold() above.  The second drops the reference from the
1589 	 * socket buffer.
1590 	 */
1591 	KASSERT(tls->refcount >= 2, ("too few references on old session"));
1592 	ktls_free(tls);
1593 	ktls_free(tls);
1594 
1595 	if (mode == TCP_TLS_MODE_IFNET)
1596 		counter_u64_add(ktls_switch_to_ifnet, 1);
1597 	else
1598 		counter_u64_add(ktls_switch_to_sw, 1);
1599 
1600 	return (0);
1601 }
1602 
1603 /*
1604  * Try to allocate a new TLS receive tag.  This task is scheduled when
1605  * sbappend_ktls_rx detects an input path change.  If a new tag is
1606  * allocated, replace the tag in the TLS session.  If a new tag cannot
1607  * be allocated, let the session fall back to software decryption.
1608  */
1609 static void
1610 ktls_reset_receive_tag(void *context, int pending)
1611 {
1612 	union if_snd_tag_alloc_params params;
1613 	struct ktls_session *tls;
1614 	struct m_snd_tag *mst;
1615 	struct inpcb *inp;
1616 	struct ifnet *ifp;
1617 	struct socket *so;
1618 	int error;
1619 
1620 	MPASS(pending == 1);
1621 
1622 	tls = context;
1623 	so = tls->so;
1624 	inp = so->so_pcb;
1625 	ifp = NULL;
1626 
1627 	INP_RLOCK(inp);
1628 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1629 		INP_RUNLOCK(inp);
1630 		goto out;
1631 	}
1632 
1633 	SOCKBUF_LOCK(&so->so_rcv);
1634 	mst = tls->snd_tag;
1635 	tls->snd_tag = NULL;
1636 	if (mst != NULL)
1637 		m_snd_tag_rele(mst);
1638 
1639 	ifp = tls->rx_ifp;
1640 	if_ref(ifp);
1641 	SOCKBUF_UNLOCK(&so->so_rcv);
1642 
1643 	params.hdr.type = IF_SND_TAG_TYPE_TLS_RX;
1644 	params.hdr.flowid = inp->inp_flowid;
1645 	params.hdr.flowtype = inp->inp_flowtype;
1646 	params.hdr.numa_domain = inp->inp_numa_domain;
1647 	params.tls_rx.inp = inp;
1648 	params.tls_rx.tls = tls;
1649 	params.tls_rx.vlan_id = tls->rx_vlan_id;
1650 	INP_RUNLOCK(inp);
1651 
1652 	if (inp->inp_vflag & INP_IPV6) {
1653 		if ((ifp->if_capenable2 & IFCAP2_RXTLS6) == 0)
1654 			goto out;
1655 	} else {
1656 		if ((ifp->if_capenable2 & IFCAP2_RXTLS4) == 0)
1657 			goto out;
1658 	}
1659 
1660 	error = m_snd_tag_alloc(ifp, &params, &mst);
1661 	if (error == 0) {
1662 		SOCKBUF_LOCK(&so->so_rcv);
1663 		tls->snd_tag = mst;
1664 		SOCKBUF_UNLOCK(&so->so_rcv);
1665 
1666 		counter_u64_add(ktls_ifnet_reset, 1);
1667 	} else {
1668 		/*
1669 		 * Just fall back to software decryption if a tag
1670 		 * cannot be allocated leaving the connection intact.
1671 		 * If a future input path change switches to another
1672 		 * interface this connection will resume ifnet TLS.
1673 		 */
1674 		counter_u64_add(ktls_ifnet_reset_failed, 1);
1675 	}
1676 
1677 out:
1678 	mtx_pool_lock(mtxpool_sleep, tls);
1679 	tls->reset_pending = false;
1680 	mtx_pool_unlock(mtxpool_sleep, tls);
1681 
1682 	if (ifp != NULL)
1683 		if_rele(ifp);
1684 	sorele(so);
1685 	ktls_free(tls);
1686 }
1687 
1688 /*
1689  * Try to allocate a new TLS send tag.  This task is scheduled when
1690  * ip_output detects a route change while trying to transmit a packet
1691  * holding a TLS record.  If a new tag is allocated, replace the tag
1692  * in the TLS session.  Subsequent packets on the connection will use
1693  * the new tag.  If a new tag cannot be allocated, drop the
1694  * connection.
1695  */
1696 static void
1697 ktls_reset_send_tag(void *context, int pending)
1698 {
1699 	struct epoch_tracker et;
1700 	struct ktls_session *tls;
1701 	struct m_snd_tag *old, *new;
1702 	struct inpcb *inp;
1703 	struct tcpcb *tp;
1704 	int error;
1705 
1706 	MPASS(pending == 1);
1707 
1708 	tls = context;
1709 	inp = tls->inp;
1710 
1711 	/*
1712 	 * Free the old tag first before allocating a new one.
1713 	 * ip[6]_output_send() will treat a NULL send tag the same as
1714 	 * an ifp mismatch and drop packets until a new tag is
1715 	 * allocated.
1716 	 *
1717 	 * Write-lock the INP when changing tls->snd_tag since
1718 	 * ip[6]_output_send() holds a read-lock when reading the
1719 	 * pointer.
1720 	 */
1721 	INP_WLOCK(inp);
1722 	old = tls->snd_tag;
1723 	tls->snd_tag = NULL;
1724 	INP_WUNLOCK(inp);
1725 	if (old != NULL)
1726 		m_snd_tag_rele(old);
1727 
1728 	error = ktls_alloc_snd_tag(inp, tls, true, &new);
1729 
1730 	if (error == 0) {
1731 		INP_WLOCK(inp);
1732 		tls->snd_tag = new;
1733 		mtx_pool_lock(mtxpool_sleep, tls);
1734 		tls->reset_pending = false;
1735 		mtx_pool_unlock(mtxpool_sleep, tls);
1736 		if (!in_pcbrele_wlocked(inp))
1737 			INP_WUNLOCK(inp);
1738 
1739 		counter_u64_add(ktls_ifnet_reset, 1);
1740 
1741 		/*
1742 		 * XXX: Should we kick tcp_output explicitly now that
1743 		 * the send tag is fixed or just rely on timers?
1744 		 */
1745 	} else {
1746 		NET_EPOCH_ENTER(et);
1747 		INP_WLOCK(inp);
1748 		if (!in_pcbrele_wlocked(inp)) {
1749 			if (!(inp->inp_flags & INP_TIMEWAIT) &&
1750 			    !(inp->inp_flags & INP_DROPPED)) {
1751 				tp = intotcpcb(inp);
1752 				CURVNET_SET(tp->t_vnet);
1753 				tp = tcp_drop(tp, ECONNABORTED);
1754 				CURVNET_RESTORE();
1755 				if (tp != NULL)
1756 					INP_WUNLOCK(inp);
1757 				counter_u64_add(ktls_ifnet_reset_dropped, 1);
1758 			} else
1759 				INP_WUNLOCK(inp);
1760 		}
1761 		NET_EPOCH_EXIT(et);
1762 
1763 		counter_u64_add(ktls_ifnet_reset_failed, 1);
1764 
1765 		/*
1766 		 * Leave reset_pending true to avoid future tasks while
1767 		 * the socket goes away.
1768 		 */
1769 	}
1770 
1771 	ktls_free(tls);
1772 }
1773 
1774 void
1775 ktls_input_ifp_mismatch(struct sockbuf *sb, struct ifnet *ifp)
1776 {
1777 	struct ktls_session *tls;
1778 	struct socket *so;
1779 
1780 	SOCKBUF_LOCK_ASSERT(sb);
1781 	KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1782 	    __func__, sb));
1783 	so = __containerof(sb, struct socket, so_rcv);
1784 
1785 	tls = sb->sb_tls_info;
1786 	if_rele(tls->rx_ifp);
1787 	if_ref(ifp);
1788 	tls->rx_ifp = ifp;
1789 
1790 	/*
1791 	 * See if we should schedule a task to update the receive tag for
1792 	 * this session.
1793 	 */
1794 	mtx_pool_lock(mtxpool_sleep, tls);
1795 	if (!tls->reset_pending) {
1796 		(void) ktls_hold(tls);
1797 		soref(so);
1798 		tls->so = so;
1799 		tls->reset_pending = true;
1800 		taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1801 	}
1802 	mtx_pool_unlock(mtxpool_sleep, tls);
1803 }
1804 
1805 int
1806 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1807 {
1808 
1809 	if (inp == NULL)
1810 		return (ENOBUFS);
1811 
1812 	INP_LOCK_ASSERT(inp);
1813 
1814 	/*
1815 	 * See if we should schedule a task to update the send tag for
1816 	 * this session.
1817 	 */
1818 	mtx_pool_lock(mtxpool_sleep, tls);
1819 	if (!tls->reset_pending) {
1820 		(void) ktls_hold(tls);
1821 		in_pcbref(inp);
1822 		tls->inp = inp;
1823 		tls->reset_pending = true;
1824 		taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1825 	}
1826 	mtx_pool_unlock(mtxpool_sleep, tls);
1827 	return (ENOBUFS);
1828 }
1829 
1830 #ifdef RATELIMIT
1831 int
1832 ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1833 {
1834 	union if_snd_tag_modify_params params = {
1835 		.rate_limit.max_rate = max_pacing_rate,
1836 		.rate_limit.flags = M_NOWAIT,
1837 	};
1838 	struct m_snd_tag *mst;
1839 
1840 	/* Can't get to the inp, but it should be locked. */
1841 	/* INP_LOCK_ASSERT(inp); */
1842 
1843 	MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1844 
1845 	if (tls->snd_tag == NULL) {
1846 		/*
1847 		 * Resetting send tag, ignore this change.  The
1848 		 * pending reset may or may not see this updated rate
1849 		 * in the tcpcb.  If it doesn't, we will just lose
1850 		 * this rate change.
1851 		 */
1852 		return (0);
1853 	}
1854 
1855 	mst = tls->snd_tag;
1856 
1857 	MPASS(mst != NULL);
1858 	MPASS(mst->sw->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1859 
1860 	return (mst->sw->snd_tag_modify(mst, &params));
1861 }
1862 #endif
1863 #endif
1864 
1865 void
1866 ktls_destroy(struct ktls_session *tls)
1867 {
1868 
1869 	if (tls->sequential_records) {
1870 		struct mbuf *m, *n;
1871 		int page_count;
1872 
1873 		STAILQ_FOREACH_SAFE(m, &tls->pending_records, m_epg_stailq, n) {
1874 			page_count = m->m_epg_enc_cnt;
1875 			while (page_count > 0) {
1876 				KASSERT(page_count >= m->m_epg_nrdy,
1877 				    ("%s: too few pages", __func__));
1878 				page_count -= m->m_epg_nrdy;
1879 				m = m_free(m);
1880 			}
1881 		}
1882 	}
1883 	ktls_cleanup(tls);
1884 	uma_zfree(ktls_session_zone, tls);
1885 }
1886 
1887 void
1888 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1889 {
1890 
1891 	for (; m != NULL; m = m->m_next) {
1892 		KASSERT((m->m_flags & M_EXTPG) != 0,
1893 		    ("ktls_seq: mapped mbuf %p", m));
1894 
1895 		m->m_epg_seqno = sb->sb_tls_seqno;
1896 		sb->sb_tls_seqno++;
1897 	}
1898 }
1899 
1900 /*
1901  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
1902  * mbuf in the chain must be an unmapped mbuf.  The payload of the
1903  * mbuf must be populated with the payload of each TLS record.
1904  *
1905  * The record_type argument specifies the TLS record type used when
1906  * populating the TLS header.
1907  *
1908  * The enq_count argument on return is set to the number of pages of
1909  * payload data for this entire chain that need to be encrypted via SW
1910  * encryption.  The returned value should be passed to ktls_enqueue
1911  * when scheduling encryption of this chain of mbufs.  To handle the
1912  * special case of empty fragments for TLS 1.0 sessions, an empty
1913  * fragment counts as one page.
1914  */
1915 void
1916 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1917     uint8_t record_type)
1918 {
1919 	struct tls_record_layer *tlshdr;
1920 	struct mbuf *m;
1921 	uint64_t *noncep;
1922 	uint16_t tls_len;
1923 	int maxlen __diagused;
1924 
1925 	maxlen = tls->params.max_frame_len;
1926 	*enq_cnt = 0;
1927 	for (m = top; m != NULL; m = m->m_next) {
1928 		/*
1929 		 * All mbufs in the chain should be TLS records whose
1930 		 * payload does not exceed the maximum frame length.
1931 		 *
1932 		 * Empty TLS 1.0 records are permitted when using CBC.
1933 		 */
1934 		KASSERT(m->m_len <= maxlen && m->m_len >= 0 &&
1935 		    (m->m_len > 0 || ktls_permit_empty_frames(tls)),
1936 		    ("ktls_frame: m %p len %d", m, m->m_len));
1937 
1938 		/*
1939 		 * TLS frames require unmapped mbufs to store session
1940 		 * info.
1941 		 */
1942 		KASSERT((m->m_flags & M_EXTPG) != 0,
1943 		    ("ktls_frame: mapped mbuf %p (top = %p)", m, top));
1944 
1945 		tls_len = m->m_len;
1946 
1947 		/* Save a reference to the session. */
1948 		m->m_epg_tls = ktls_hold(tls);
1949 
1950 		m->m_epg_hdrlen = tls->params.tls_hlen;
1951 		m->m_epg_trllen = tls->params.tls_tlen;
1952 		if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1953 			int bs, delta;
1954 
1955 			/*
1956 			 * AES-CBC pads messages to a multiple of the
1957 			 * block size.  Note that the padding is
1958 			 * applied after the digest and the encryption
1959 			 * is done on the "plaintext || mac || padding".
1960 			 * At least one byte of padding is always
1961 			 * present.
1962 			 *
1963 			 * Compute the final trailer length assuming
1964 			 * at most one block of padding.
1965 			 * tls->params.tls_tlen is the maximum
1966 			 * possible trailer length (padding + digest).
1967 			 * delta holds the number of excess padding
1968 			 * bytes if the maximum were used.  Those
1969 			 * extra bytes are removed.
1970 			 */
1971 			bs = tls->params.tls_bs;
1972 			delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1973 			m->m_epg_trllen -= delta;
1974 		}
1975 		m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1976 
1977 		/* Populate the TLS header. */
1978 		tlshdr = (void *)m->m_epg_hdr;
1979 		tlshdr->tls_vmajor = tls->params.tls_vmajor;
1980 
1981 		/*
1982 		 * TLS 1.3 masquarades as TLS 1.2 with a record type
1983 		 * of TLS_RLTYPE_APP.
1984 		 */
1985 		if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1986 		    tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1987 			tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1988 			tlshdr->tls_type = TLS_RLTYPE_APP;
1989 			/* save the real record type for later */
1990 			m->m_epg_record_type = record_type;
1991 			m->m_epg_trail[0] = record_type;
1992 		} else {
1993 			tlshdr->tls_vminor = tls->params.tls_vminor;
1994 			tlshdr->tls_type = record_type;
1995 		}
1996 		tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1997 
1998 		/*
1999 		 * Store nonces / explicit IVs after the end of the
2000 		 * TLS header.
2001 		 *
2002 		 * For GCM with TLS 1.2, an 8 byte nonce is copied
2003 		 * from the end of the IV.  The nonce is then
2004 		 * incremented for use by the next record.
2005 		 *
2006 		 * For CBC, a random nonce is inserted for TLS 1.1+.
2007 		 */
2008 		if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
2009 		    tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
2010 			noncep = (uint64_t *)(tls->params.iv + 8);
2011 			be64enc(tlshdr + 1, *noncep);
2012 			(*noncep)++;
2013 		} else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
2014 		    tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
2015 			arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
2016 
2017 		/*
2018 		 * When using SW encryption, mark the mbuf not ready.
2019 		 * It will be marked ready via sbready() after the
2020 		 * record has been encrypted.
2021 		 *
2022 		 * When using ifnet TLS, unencrypted TLS records are
2023 		 * sent down the stack to the NIC.
2024 		 */
2025 		if (tls->mode == TCP_TLS_MODE_SW) {
2026 			m->m_flags |= M_NOTREADY;
2027 			if (__predict_false(tls_len == 0)) {
2028 				/* TLS 1.0 empty fragment. */
2029 				m->m_epg_nrdy = 1;
2030 			} else
2031 				m->m_epg_nrdy = m->m_epg_npgs;
2032 			*enq_cnt += m->m_epg_nrdy;
2033 		}
2034 	}
2035 }
2036 
2037 bool
2038 ktls_permit_empty_frames(struct ktls_session *tls)
2039 {
2040 	return (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
2041 	    tls->params.tls_vminor == TLS_MINOR_VER_ZERO);
2042 }
2043 
2044 void
2045 ktls_check_rx(struct sockbuf *sb)
2046 {
2047 	struct tls_record_layer hdr;
2048 	struct ktls_wq *wq;
2049 	struct socket *so;
2050 	bool running;
2051 
2052 	SOCKBUF_LOCK_ASSERT(sb);
2053 	KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
2054 	    __func__, sb));
2055 	so = __containerof(sb, struct socket, so_rcv);
2056 
2057 	if (sb->sb_flags & SB_TLS_RX_RUNNING)
2058 		return;
2059 
2060 	/* Is there enough queued for a TLS header? */
2061 	if (sb->sb_tlscc < sizeof(hdr)) {
2062 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
2063 			so->so_error = EMSGSIZE;
2064 		return;
2065 	}
2066 
2067 	m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
2068 
2069 	/* Is the entire record queued? */
2070 	if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
2071 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
2072 			so->so_error = EMSGSIZE;
2073 		return;
2074 	}
2075 
2076 	sb->sb_flags |= SB_TLS_RX_RUNNING;
2077 
2078 	soref(so);
2079 	wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
2080 	mtx_lock(&wq->mtx);
2081 	STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
2082 	running = wq->running;
2083 	mtx_unlock(&wq->mtx);
2084 	if (!running)
2085 		wakeup(wq);
2086 	counter_u64_add(ktls_cnt_rx_queued, 1);
2087 }
2088 
2089 static struct mbuf *
2090 ktls_detach_record(struct sockbuf *sb, int len)
2091 {
2092 	struct mbuf *m, *n, *top;
2093 	int remain;
2094 
2095 	SOCKBUF_LOCK_ASSERT(sb);
2096 	MPASS(len <= sb->sb_tlscc);
2097 
2098 	/*
2099 	 * If TLS chain is the exact size of the record,
2100 	 * just grab the whole record.
2101 	 */
2102 	top = sb->sb_mtls;
2103 	if (sb->sb_tlscc == len) {
2104 		sb->sb_mtls = NULL;
2105 		sb->sb_mtlstail = NULL;
2106 		goto out;
2107 	}
2108 
2109 	/*
2110 	 * While it would be nice to use m_split() here, we need
2111 	 * to know exactly what m_split() allocates to update the
2112 	 * accounting, so do it inline instead.
2113 	 */
2114 	remain = len;
2115 	for (m = top; remain > m->m_len; m = m->m_next)
2116 		remain -= m->m_len;
2117 
2118 	/* Easy case: don't have to split 'm'. */
2119 	if (remain == m->m_len) {
2120 		sb->sb_mtls = m->m_next;
2121 		if (sb->sb_mtls == NULL)
2122 			sb->sb_mtlstail = NULL;
2123 		m->m_next = NULL;
2124 		goto out;
2125 	}
2126 
2127 	/*
2128 	 * Need to allocate an mbuf to hold the remainder of 'm'.  Try
2129 	 * with M_NOWAIT first.
2130 	 */
2131 	n = m_get(M_NOWAIT, MT_DATA);
2132 	if (n == NULL) {
2133 		/*
2134 		 * Use M_WAITOK with socket buffer unlocked.  If
2135 		 * 'sb_mtls' changes while the lock is dropped, return
2136 		 * NULL to force the caller to retry.
2137 		 */
2138 		SOCKBUF_UNLOCK(sb);
2139 
2140 		n = m_get(M_WAITOK, MT_DATA);
2141 
2142 		SOCKBUF_LOCK(sb);
2143 		if (sb->sb_mtls != top) {
2144 			m_free(n);
2145 			return (NULL);
2146 		}
2147 	}
2148 	n->m_flags |= (m->m_flags & (M_NOTREADY | M_DECRYPTED));
2149 
2150 	/* Store remainder in 'n'. */
2151 	n->m_len = m->m_len - remain;
2152 	if (m->m_flags & M_EXT) {
2153 		n->m_data = m->m_data + remain;
2154 		mb_dupcl(n, m);
2155 	} else {
2156 		bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
2157 	}
2158 
2159 	/* Trim 'm' and update accounting. */
2160 	m->m_len -= n->m_len;
2161 	sb->sb_tlscc -= n->m_len;
2162 	sb->sb_ccc -= n->m_len;
2163 
2164 	/* Account for 'n'. */
2165 	sballoc_ktls_rx(sb, n);
2166 
2167 	/* Insert 'n' into the TLS chain. */
2168 	sb->sb_mtls = n;
2169 	n->m_next = m->m_next;
2170 	if (sb->sb_mtlstail == m)
2171 		sb->sb_mtlstail = n;
2172 
2173 	/* Detach the record from the TLS chain. */
2174 	m->m_next = NULL;
2175 
2176 out:
2177 	MPASS(m_length(top, NULL) == len);
2178 	for (m = top; m != NULL; m = m->m_next)
2179 		sbfree_ktls_rx(sb, m);
2180 	sb->sb_tlsdcc = len;
2181 	sb->sb_ccc += len;
2182 	SBCHECK(sb);
2183 	return (top);
2184 }
2185 
2186 /*
2187  * Determine the length of the trailing zero padding and find the real
2188  * record type in the byte before the padding.
2189  *
2190  * Walking the mbuf chain backwards is clumsy, so another option would
2191  * be to scan forwards remembering the last non-zero byte before the
2192  * trailer.  However, it would be expensive to scan the entire record.
2193  * Instead, find the last non-zero byte of each mbuf in the chain
2194  * keeping track of the relative offset of that nonzero byte.
2195  *
2196  * trail_len is the size of the MAC/tag on input and is set to the
2197  * size of the full trailer including padding and the record type on
2198  * return.
2199  */
2200 static int
2201 tls13_find_record_type(struct ktls_session *tls, struct mbuf *m, int tls_len,
2202     int *trailer_len, uint8_t *record_typep)
2203 {
2204 	char *cp;
2205 	u_int digest_start, last_offset, m_len, offset;
2206 	uint8_t record_type;
2207 
2208 	digest_start = tls_len - *trailer_len;
2209 	last_offset = 0;
2210 	offset = 0;
2211 	for (; m != NULL && offset < digest_start;
2212 	     offset += m->m_len, m = m->m_next) {
2213 		/* Don't look for padding in the tag. */
2214 		m_len = min(digest_start - offset, m->m_len);
2215 		cp = mtod(m, char *);
2216 
2217 		/* Find last non-zero byte in this mbuf. */
2218 		while (m_len > 0 && cp[m_len - 1] == 0)
2219 			m_len--;
2220 		if (m_len > 0) {
2221 			record_type = cp[m_len - 1];
2222 			last_offset = offset + m_len;
2223 		}
2224 	}
2225 	if (last_offset < tls->params.tls_hlen)
2226 		return (EBADMSG);
2227 
2228 	*record_typep = record_type;
2229 	*trailer_len = tls_len - last_offset + 1;
2230 	return (0);
2231 }
2232 
2233 /*
2234  * Check if a mbuf chain is fully decrypted at the given offset and
2235  * length. Returns KTLS_MBUF_CRYPTO_ST_DECRYPTED if all data is
2236  * decrypted. KTLS_MBUF_CRYPTO_ST_MIXED if there is a mix of encrypted
2237  * and decrypted data. Else KTLS_MBUF_CRYPTO_ST_ENCRYPTED if all data
2238  * is encrypted.
2239  */
2240 ktls_mbuf_crypto_st_t
2241 ktls_mbuf_crypto_state(struct mbuf *mb, int offset, int len)
2242 {
2243 	int m_flags_ored = 0;
2244 	int m_flags_anded = -1;
2245 
2246 	for (; mb != NULL; mb = mb->m_next) {
2247 		if (offset < mb->m_len)
2248 			break;
2249 		offset -= mb->m_len;
2250 	}
2251 	offset += len;
2252 
2253 	for (; mb != NULL; mb = mb->m_next) {
2254 		m_flags_ored |= mb->m_flags;
2255 		m_flags_anded &= mb->m_flags;
2256 
2257 		if (offset <= mb->m_len)
2258 			break;
2259 		offset -= mb->m_len;
2260 	}
2261 	MPASS(mb != NULL || offset == 0);
2262 
2263 	if ((m_flags_ored ^ m_flags_anded) & M_DECRYPTED)
2264 		return (KTLS_MBUF_CRYPTO_ST_MIXED);
2265 	else
2266 		return ((m_flags_ored & M_DECRYPTED) ?
2267 		    KTLS_MBUF_CRYPTO_ST_DECRYPTED :
2268 		    KTLS_MBUF_CRYPTO_ST_ENCRYPTED);
2269 }
2270 
2271 /*
2272  * ktls_resync_ifnet - get HW TLS RX back on track after packet loss
2273  */
2274 static int
2275 ktls_resync_ifnet(struct socket *so, uint32_t tls_len, uint64_t tls_rcd_num)
2276 {
2277 	union if_snd_tag_modify_params params;
2278 	struct m_snd_tag *mst;
2279 	struct inpcb *inp;
2280 	struct tcpcb *tp;
2281 
2282 	mst = so->so_rcv.sb_tls_info->snd_tag;
2283 	if (__predict_false(mst == NULL))
2284 		return (EINVAL);
2285 
2286 	inp = sotoinpcb(so);
2287 	if (__predict_false(inp == NULL))
2288 		return (EINVAL);
2289 
2290 	INP_RLOCK(inp);
2291 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
2292 		INP_RUNLOCK(inp);
2293 		return (ECONNRESET);
2294 	}
2295 
2296 	tp = intotcpcb(inp);
2297 	MPASS(tp != NULL);
2298 
2299 	/* Get the TCP sequence number of the next valid TLS header. */
2300 	SOCKBUF_LOCK(&so->so_rcv);
2301 	params.tls_rx.tls_hdr_tcp_sn =
2302 	    tp->rcv_nxt - so->so_rcv.sb_tlscc - tls_len;
2303 	params.tls_rx.tls_rec_length = tls_len;
2304 	params.tls_rx.tls_seq_number = tls_rcd_num;
2305 	SOCKBUF_UNLOCK(&so->so_rcv);
2306 
2307 	INP_RUNLOCK(inp);
2308 
2309 	MPASS(mst->sw->type == IF_SND_TAG_TYPE_TLS_RX);
2310 	return (mst->sw->snd_tag_modify(mst, &params));
2311 }
2312 
2313 static void
2314 ktls_decrypt(struct socket *so)
2315 {
2316 	char tls_header[MBUF_PEXT_HDR_LEN];
2317 	struct ktls_session *tls;
2318 	struct sockbuf *sb;
2319 	struct tls_record_layer *hdr;
2320 	struct tls_get_record tgr;
2321 	struct mbuf *control, *data, *m;
2322 	ktls_mbuf_crypto_st_t state;
2323 	uint64_t seqno;
2324 	int error, remain, tls_len, trail_len;
2325 	bool tls13;
2326 	uint8_t vminor, record_type;
2327 
2328 	hdr = (struct tls_record_layer *)tls_header;
2329 	sb = &so->so_rcv;
2330 	SOCKBUF_LOCK(sb);
2331 	KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
2332 	    ("%s: socket %p not running", __func__, so));
2333 
2334 	tls = sb->sb_tls_info;
2335 	MPASS(tls != NULL);
2336 
2337 	tls13 = (tls->params.tls_vminor == TLS_MINOR_VER_THREE);
2338 	if (tls13)
2339 		vminor = TLS_MINOR_VER_TWO;
2340 	else
2341 		vminor = tls->params.tls_vminor;
2342 	for (;;) {
2343 		/* Is there enough queued for a TLS header? */
2344 		if (sb->sb_tlscc < tls->params.tls_hlen)
2345 			break;
2346 
2347 		m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
2348 		tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
2349 
2350 		if (hdr->tls_vmajor != tls->params.tls_vmajor ||
2351 		    hdr->tls_vminor != vminor)
2352 			error = EINVAL;
2353 		else if (tls13 && hdr->tls_type != TLS_RLTYPE_APP)
2354 			error = EINVAL;
2355 		else if (tls_len < tls->params.tls_hlen || tls_len >
2356 		    tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
2357 		    tls->params.tls_tlen)
2358 			error = EMSGSIZE;
2359 		else
2360 			error = 0;
2361 		if (__predict_false(error != 0)) {
2362 			/*
2363 			 * We have a corrupted record and are likely
2364 			 * out of sync.  The connection isn't
2365 			 * recoverable at this point, so abort it.
2366 			 */
2367 			SOCKBUF_UNLOCK(sb);
2368 			counter_u64_add(ktls_offload_corrupted_records, 1);
2369 
2370 			CURVNET_SET(so->so_vnet);
2371 			so->so_proto->pr_abort(so);
2372 			so->so_error = error;
2373 			CURVNET_RESTORE();
2374 			goto deref;
2375 		}
2376 
2377 		/* Is the entire record queued? */
2378 		if (sb->sb_tlscc < tls_len)
2379 			break;
2380 
2381 		/*
2382 		 * Split out the portion of the mbuf chain containing
2383 		 * this TLS record.
2384 		 */
2385 		data = ktls_detach_record(sb, tls_len);
2386 		if (data == NULL)
2387 			continue;
2388 		MPASS(sb->sb_tlsdcc == tls_len);
2389 
2390 		seqno = sb->sb_tls_seqno;
2391 		sb->sb_tls_seqno++;
2392 		SBCHECK(sb);
2393 		SOCKBUF_UNLOCK(sb);
2394 
2395 		/* get crypto state for this TLS record */
2396 		state = ktls_mbuf_crypto_state(data, 0, tls_len);
2397 
2398 		switch (state) {
2399 		case KTLS_MBUF_CRYPTO_ST_MIXED:
2400 			error = ktls_ocf_recrypt(tls, hdr, data, seqno);
2401 			if (error)
2402 				break;
2403 			/* FALLTHROUGH */
2404 		case KTLS_MBUF_CRYPTO_ST_ENCRYPTED:
2405 			error = ktls_ocf_decrypt(tls, hdr, data, seqno,
2406 			    &trail_len);
2407 			if (__predict_true(error == 0)) {
2408 				if (tls13) {
2409 					error = tls13_find_record_type(tls, data,
2410 					    tls_len, &trail_len, &record_type);
2411 				} else {
2412 					record_type = hdr->tls_type;
2413 				}
2414 			}
2415 			break;
2416 		case KTLS_MBUF_CRYPTO_ST_DECRYPTED:
2417 			/*
2418 			 * NIC TLS is only supported for AEAD
2419 			 * ciphersuites which used a fixed sized
2420 			 * trailer.
2421 			 */
2422 			if (tls13) {
2423 				trail_len = tls->params.tls_tlen - 1;
2424 				error = tls13_find_record_type(tls, data,
2425 				    tls_len, &trail_len, &record_type);
2426 			} else {
2427 				trail_len = tls->params.tls_tlen;
2428 				error = 0;
2429 				record_type = hdr->tls_type;
2430 			}
2431 			break;
2432 		default:
2433 			error = EINVAL;
2434 			break;
2435 		}
2436 		if (error) {
2437 			counter_u64_add(ktls_offload_failed_crypto, 1);
2438 
2439 			SOCKBUF_LOCK(sb);
2440 			if (sb->sb_tlsdcc == 0) {
2441 				/*
2442 				 * sbcut/drop/flush discarded these
2443 				 * mbufs.
2444 				 */
2445 				m_freem(data);
2446 				break;
2447 			}
2448 
2449 			/*
2450 			 * Drop this TLS record's data, but keep
2451 			 * decrypting subsequent records.
2452 			 */
2453 			sb->sb_ccc -= tls_len;
2454 			sb->sb_tlsdcc = 0;
2455 
2456 			CURVNET_SET(so->so_vnet);
2457 			so->so_error = EBADMSG;
2458 			sorwakeup_locked(so);
2459 			CURVNET_RESTORE();
2460 
2461 			m_freem(data);
2462 
2463 			SOCKBUF_LOCK(sb);
2464 			continue;
2465 		}
2466 
2467 		/* Allocate the control mbuf. */
2468 		memset(&tgr, 0, sizeof(tgr));
2469 		tgr.tls_type = record_type;
2470 		tgr.tls_vmajor = hdr->tls_vmajor;
2471 		tgr.tls_vminor = hdr->tls_vminor;
2472 		tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
2473 		    trail_len);
2474 		control = sbcreatecontrol(&tgr, sizeof(tgr),
2475 		    TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
2476 
2477 		SOCKBUF_LOCK(sb);
2478 		if (sb->sb_tlsdcc == 0) {
2479 			/* sbcut/drop/flush discarded these mbufs. */
2480 			MPASS(sb->sb_tlscc == 0);
2481 			m_freem(data);
2482 			m_freem(control);
2483 			break;
2484 		}
2485 
2486 		/*
2487 		 * Clear the 'dcc' accounting in preparation for
2488 		 * adding the decrypted record.
2489 		 */
2490 		sb->sb_ccc -= tls_len;
2491 		sb->sb_tlsdcc = 0;
2492 		SBCHECK(sb);
2493 
2494 		/* If there is no payload, drop all of the data. */
2495 		if (tgr.tls_length == htobe16(0)) {
2496 			m_freem(data);
2497 			data = NULL;
2498 		} else {
2499 			/* Trim header. */
2500 			remain = tls->params.tls_hlen;
2501 			while (remain > 0) {
2502 				if (data->m_len > remain) {
2503 					data->m_data += remain;
2504 					data->m_len -= remain;
2505 					break;
2506 				}
2507 				remain -= data->m_len;
2508 				data = m_free(data);
2509 			}
2510 
2511 			/* Trim trailer and clear M_NOTREADY. */
2512 			remain = be16toh(tgr.tls_length);
2513 			m = data;
2514 			for (m = data; remain > m->m_len; m = m->m_next) {
2515 				m->m_flags &= ~(M_NOTREADY | M_DECRYPTED);
2516 				remain -= m->m_len;
2517 			}
2518 			m->m_len = remain;
2519 			m_freem(m->m_next);
2520 			m->m_next = NULL;
2521 			m->m_flags &= ~(M_NOTREADY | M_DECRYPTED);
2522 
2523 			/* Set EOR on the final mbuf. */
2524 			m->m_flags |= M_EOR;
2525 		}
2526 
2527 		sbappendcontrol_locked(sb, data, control, 0);
2528 
2529 		if (__predict_false(state != KTLS_MBUF_CRYPTO_ST_DECRYPTED)) {
2530 			sb->sb_flags |= SB_TLS_RX_RESYNC;
2531 			SOCKBUF_UNLOCK(sb);
2532 			ktls_resync_ifnet(so, tls_len, seqno);
2533 			SOCKBUF_LOCK(sb);
2534 		} else if (__predict_false(sb->sb_flags & SB_TLS_RX_RESYNC)) {
2535 			sb->sb_flags &= ~SB_TLS_RX_RESYNC;
2536 			SOCKBUF_UNLOCK(sb);
2537 			ktls_resync_ifnet(so, 0, seqno);
2538 			SOCKBUF_LOCK(sb);
2539 		}
2540 	}
2541 
2542 	sb->sb_flags &= ~SB_TLS_RX_RUNNING;
2543 
2544 	if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
2545 		so->so_error = EMSGSIZE;
2546 
2547 	sorwakeup_locked(so);
2548 
2549 deref:
2550 	SOCKBUF_UNLOCK_ASSERT(sb);
2551 
2552 	CURVNET_SET(so->so_vnet);
2553 	sorele(so);
2554 	CURVNET_RESTORE();
2555 }
2556 
2557 void
2558 ktls_enqueue_to_free(struct mbuf *m)
2559 {
2560 	struct ktls_wq *wq;
2561 	bool running;
2562 
2563 	/* Mark it for freeing. */
2564 	m->m_epg_flags |= EPG_FLAG_2FREE;
2565 	wq = &ktls_wq[m->m_epg_tls->wq_index];
2566 	mtx_lock(&wq->mtx);
2567 	STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2568 	running = wq->running;
2569 	mtx_unlock(&wq->mtx);
2570 	if (!running)
2571 		wakeup(wq);
2572 }
2573 
2574 static void *
2575 ktls_buffer_alloc(struct ktls_wq *wq, struct mbuf *m)
2576 {
2577 	void *buf;
2578 	int domain, running;
2579 
2580 	if (m->m_epg_npgs <= 2)
2581 		return (NULL);
2582 	if (ktls_buffer_zone == NULL)
2583 		return (NULL);
2584 	if ((u_int)(ticks - wq->lastallocfail) < hz) {
2585 		/*
2586 		 * Rate-limit allocation attempts after a failure.
2587 		 * ktls_buffer_import() will acquire a per-domain mutex to check
2588 		 * the free page queues and may fail consistently if memory is
2589 		 * fragmented.
2590 		 */
2591 		return (NULL);
2592 	}
2593 	buf = uma_zalloc(ktls_buffer_zone, M_NOWAIT | M_NORECLAIM);
2594 	if (buf == NULL) {
2595 		domain = PCPU_GET(domain);
2596 		wq->lastallocfail = ticks;
2597 
2598 		/*
2599 		 * Note that this check is "racy", but the races are
2600 		 * harmless, and are either a spurious wakeup if
2601 		 * multiple threads fail allocations before the alloc
2602 		 * thread wakes, or waiting an extra second in case we
2603 		 * see an old value of running == true.
2604 		 */
2605 		if (!VM_DOMAIN_EMPTY(domain)) {
2606 			running = atomic_load_int(&ktls_domains[domain].alloc_td.running);
2607 			if (!running)
2608 				wakeup(&ktls_domains[domain].alloc_td);
2609 		}
2610 	}
2611 	return (buf);
2612 }
2613 
2614 static int
2615 ktls_encrypt_record(struct ktls_wq *wq, struct mbuf *m,
2616     struct ktls_session *tls, struct ktls_ocf_encrypt_state *state)
2617 {
2618 	vm_page_t pg;
2619 	int error, i, len, off;
2620 
2621 	KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) == (M_EXTPG | M_NOTREADY),
2622 	    ("%p not unready & nomap mbuf\n", m));
2623 	KASSERT(ptoa(m->m_epg_npgs) <= ktls_maxlen,
2624 	    ("page count %d larger than maximum frame length %d", m->m_epg_npgs,
2625 	    ktls_maxlen));
2626 
2627 	/* Anonymous mbufs are encrypted in place. */
2628 	if ((m->m_epg_flags & EPG_FLAG_ANON) != 0)
2629 		return (ktls_ocf_encrypt(state, tls, m, NULL, 0));
2630 
2631 	/*
2632 	 * For file-backed mbufs (from sendfile), anonymous wired
2633 	 * pages are allocated and used as the encryption destination.
2634 	 */
2635 	if ((state->cbuf = ktls_buffer_alloc(wq, m)) != NULL) {
2636 		len = ptoa(m->m_epg_npgs - 1) + m->m_epg_last_len -
2637 		    m->m_epg_1st_off;
2638 		state->dst_iov[0].iov_base = (char *)state->cbuf +
2639 		    m->m_epg_1st_off;
2640 		state->dst_iov[0].iov_len = len;
2641 		state->parray[0] = DMAP_TO_PHYS((vm_offset_t)state->cbuf);
2642 		i = 1;
2643 	} else {
2644 		off = m->m_epg_1st_off;
2645 		for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2646 			pg = vm_page_alloc_noobj(VM_ALLOC_NODUMP |
2647 			    VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2648 			len = m_epg_pagelen(m, i, off);
2649 			state->parray[i] = VM_PAGE_TO_PHYS(pg);
2650 			state->dst_iov[i].iov_base =
2651 			    (char *)PHYS_TO_DMAP(state->parray[i]) + off;
2652 			state->dst_iov[i].iov_len = len;
2653 		}
2654 	}
2655 	KASSERT(i + 1 <= nitems(state->dst_iov), ("dst_iov is too small"));
2656 	state->dst_iov[i].iov_base = m->m_epg_trail;
2657 	state->dst_iov[i].iov_len = m->m_epg_trllen;
2658 
2659 	error = ktls_ocf_encrypt(state, tls, m, state->dst_iov, i + 1);
2660 
2661 	if (__predict_false(error != 0)) {
2662 		/* Free the anonymous pages. */
2663 		if (state->cbuf != NULL)
2664 			uma_zfree(ktls_buffer_zone, state->cbuf);
2665 		else {
2666 			for (i = 0; i < m->m_epg_npgs; i++) {
2667 				pg = PHYS_TO_VM_PAGE(state->parray[i]);
2668 				(void)vm_page_unwire_noq(pg);
2669 				vm_page_free(pg);
2670 			}
2671 		}
2672 	}
2673 	return (error);
2674 }
2675 
2676 /* Number of TLS records in a batch passed to ktls_enqueue(). */
2677 static u_int
2678 ktls_batched_records(struct mbuf *m)
2679 {
2680 	int page_count, records;
2681 
2682 	records = 0;
2683 	page_count = m->m_epg_enc_cnt;
2684 	while (page_count > 0) {
2685 		records++;
2686 		page_count -= m->m_epg_nrdy;
2687 		m = m->m_next;
2688 	}
2689 	KASSERT(page_count == 0, ("%s: mismatched page count", __func__));
2690 	return (records);
2691 }
2692 
2693 void
2694 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
2695 {
2696 	struct ktls_session *tls;
2697 	struct ktls_wq *wq;
2698 	int queued;
2699 	bool running;
2700 
2701 	KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2702 	    (M_EXTPG | M_NOTREADY)),
2703 	    ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
2704 	KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
2705 
2706 	KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
2707 
2708 	m->m_epg_enc_cnt = page_count;
2709 
2710 	/*
2711 	 * Save a pointer to the socket.  The caller is responsible
2712 	 * for taking an additional reference via soref().
2713 	 */
2714 	m->m_epg_so = so;
2715 
2716 	queued = 1;
2717 	tls = m->m_epg_tls;
2718 	wq = &ktls_wq[tls->wq_index];
2719 	mtx_lock(&wq->mtx);
2720 	if (__predict_false(tls->sequential_records)) {
2721 		/*
2722 		 * For TLS 1.0, records must be encrypted
2723 		 * sequentially.  For a given connection, all records
2724 		 * queued to the associated work queue are processed
2725 		 * sequentially.  However, sendfile(2) might complete
2726 		 * I/O requests spanning multiple TLS records out of
2727 		 * order.  Here we ensure TLS records are enqueued to
2728 		 * the work queue in FIFO order.
2729 		 *
2730 		 * tls->next_seqno holds the sequence number of the
2731 		 * next TLS record that should be enqueued to the work
2732 		 * queue.  If this next record is not tls->next_seqno,
2733 		 * it must be a future record, so insert it, sorted by
2734 		 * TLS sequence number, into tls->pending_records and
2735 		 * return.
2736 		 *
2737 		 * If this TLS record matches tls->next_seqno, place
2738 		 * it in the work queue and then check
2739 		 * tls->pending_records to see if any
2740 		 * previously-queued records are now ready for
2741 		 * encryption.
2742 		 */
2743 		if (m->m_epg_seqno != tls->next_seqno) {
2744 			struct mbuf *n, *p;
2745 
2746 			p = NULL;
2747 			STAILQ_FOREACH(n, &tls->pending_records, m_epg_stailq) {
2748 				if (n->m_epg_seqno > m->m_epg_seqno)
2749 					break;
2750 				p = n;
2751 			}
2752 			if (n == NULL)
2753 				STAILQ_INSERT_TAIL(&tls->pending_records, m,
2754 				    m_epg_stailq);
2755 			else if (p == NULL)
2756 				STAILQ_INSERT_HEAD(&tls->pending_records, m,
2757 				    m_epg_stailq);
2758 			else
2759 				STAILQ_INSERT_AFTER(&tls->pending_records, p, m,
2760 				    m_epg_stailq);
2761 			mtx_unlock(&wq->mtx);
2762 			counter_u64_add(ktls_cnt_tx_pending, 1);
2763 			return;
2764 		}
2765 
2766 		tls->next_seqno += ktls_batched_records(m);
2767 		STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2768 
2769 		while (!STAILQ_EMPTY(&tls->pending_records)) {
2770 			struct mbuf *n;
2771 
2772 			n = STAILQ_FIRST(&tls->pending_records);
2773 			if (n->m_epg_seqno != tls->next_seqno)
2774 				break;
2775 
2776 			queued++;
2777 			STAILQ_REMOVE_HEAD(&tls->pending_records, m_epg_stailq);
2778 			tls->next_seqno += ktls_batched_records(n);
2779 			STAILQ_INSERT_TAIL(&wq->m_head, n, m_epg_stailq);
2780 		}
2781 		counter_u64_add(ktls_cnt_tx_pending, -(queued - 1));
2782 	} else
2783 		STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2784 
2785 	running = wq->running;
2786 	mtx_unlock(&wq->mtx);
2787 	if (!running)
2788 		wakeup(wq);
2789 	counter_u64_add(ktls_cnt_tx_queued, queued);
2790 }
2791 
2792 /*
2793  * Once a file-backed mbuf (from sendfile) has been encrypted, free
2794  * the pages from the file and replace them with the anonymous pages
2795  * allocated in ktls_encrypt_record().
2796  */
2797 static void
2798 ktls_finish_nonanon(struct mbuf *m, struct ktls_ocf_encrypt_state *state)
2799 {
2800 	int i;
2801 
2802 	MPASS((m->m_epg_flags & EPG_FLAG_ANON) == 0);
2803 
2804 	/* Free the old pages. */
2805 	m->m_ext.ext_free(m);
2806 
2807 	/* Replace them with the new pages. */
2808 	if (state->cbuf != NULL) {
2809 		for (i = 0; i < m->m_epg_npgs; i++)
2810 			m->m_epg_pa[i] = state->parray[0] + ptoa(i);
2811 
2812 		/* Contig pages should go back to the cache. */
2813 		m->m_ext.ext_free = ktls_free_mext_contig;
2814 	} else {
2815 		for (i = 0; i < m->m_epg_npgs; i++)
2816 			m->m_epg_pa[i] = state->parray[i];
2817 
2818 		/* Use the basic free routine. */
2819 		m->m_ext.ext_free = mb_free_mext_pgs;
2820 	}
2821 
2822 	/* Pages are now writable. */
2823 	m->m_epg_flags |= EPG_FLAG_ANON;
2824 }
2825 
2826 static __noinline void
2827 ktls_encrypt(struct ktls_wq *wq, struct mbuf *top)
2828 {
2829 	struct ktls_ocf_encrypt_state state;
2830 	struct ktls_session *tls;
2831 	struct socket *so;
2832 	struct mbuf *m;
2833 	int error, npages, total_pages;
2834 
2835 	so = top->m_epg_so;
2836 	tls = top->m_epg_tls;
2837 	KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
2838 	KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
2839 #ifdef INVARIANTS
2840 	top->m_epg_so = NULL;
2841 #endif
2842 	total_pages = top->m_epg_enc_cnt;
2843 	npages = 0;
2844 
2845 	/*
2846 	 * Encrypt the TLS records in the chain of mbufs starting with
2847 	 * 'top'.  'total_pages' gives us a total count of pages and is
2848 	 * used to know when we have finished encrypting the TLS
2849 	 * records originally queued with 'top'.
2850 	 *
2851 	 * NB: These mbufs are queued in the socket buffer and
2852 	 * 'm_next' is traversing the mbufs in the socket buffer.  The
2853 	 * socket buffer lock is not held while traversing this chain.
2854 	 * Since the mbufs are all marked M_NOTREADY their 'm_next'
2855 	 * pointers should be stable.  However, the 'm_next' of the
2856 	 * last mbuf encrypted is not necessarily NULL.  It can point
2857 	 * to other mbufs appended while 'top' was on the TLS work
2858 	 * queue.
2859 	 *
2860 	 * Each mbuf holds an entire TLS record.
2861 	 */
2862 	error = 0;
2863 	for (m = top; npages != total_pages; m = m->m_next) {
2864 		KASSERT(m->m_epg_tls == tls,
2865 		    ("different TLS sessions in a single mbuf chain: %p vs %p",
2866 		    tls, m->m_epg_tls));
2867 		KASSERT(npages + m->m_epg_npgs <= total_pages,
2868 		    ("page count mismatch: top %p, total_pages %d, m %p", top,
2869 		    total_pages, m));
2870 
2871 		error = ktls_encrypt_record(wq, m, tls, &state);
2872 		if (error) {
2873 			counter_u64_add(ktls_offload_failed_crypto, 1);
2874 			break;
2875 		}
2876 
2877 		if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
2878 			ktls_finish_nonanon(m, &state);
2879 
2880 		npages += m->m_epg_nrdy;
2881 
2882 		/*
2883 		 * Drop a reference to the session now that it is no
2884 		 * longer needed.  Existing code depends on encrypted
2885 		 * records having no associated session vs
2886 		 * yet-to-be-encrypted records having an associated
2887 		 * session.
2888 		 */
2889 		m->m_epg_tls = NULL;
2890 		ktls_free(tls);
2891 	}
2892 
2893 	CURVNET_SET(so->so_vnet);
2894 	if (error == 0) {
2895 		(void)so->so_proto->pr_ready(so, top, npages);
2896 	} else {
2897 		so->so_proto->pr_abort(so);
2898 		so->so_error = EIO;
2899 		mb_free_notready(top, total_pages);
2900 	}
2901 
2902 	sorele(so);
2903 	CURVNET_RESTORE();
2904 }
2905 
2906 void
2907 ktls_encrypt_cb(struct ktls_ocf_encrypt_state *state, int error)
2908 {
2909 	struct ktls_session *tls;
2910 	struct socket *so;
2911 	struct mbuf *m;
2912 	int npages;
2913 
2914 	m = state->m;
2915 
2916 	if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
2917 		ktls_finish_nonanon(m, state);
2918 
2919 	so = state->so;
2920 	free(state, M_KTLS);
2921 
2922 	/*
2923 	 * Drop a reference to the session now that it is no longer
2924 	 * needed.  Existing code depends on encrypted records having
2925 	 * no associated session vs yet-to-be-encrypted records having
2926 	 * an associated session.
2927 	 */
2928 	tls = m->m_epg_tls;
2929 	m->m_epg_tls = NULL;
2930 	ktls_free(tls);
2931 
2932 	if (error != 0)
2933 		counter_u64_add(ktls_offload_failed_crypto, 1);
2934 
2935 	CURVNET_SET(so->so_vnet);
2936 	npages = m->m_epg_nrdy;
2937 
2938 	if (error == 0) {
2939 		(void)so->so_proto->pr_ready(so, m, npages);
2940 	} else {
2941 		so->so_proto->pr_abort(so);
2942 		so->so_error = EIO;
2943 		mb_free_notready(m, npages);
2944 	}
2945 
2946 	sorele(so);
2947 	CURVNET_RESTORE();
2948 }
2949 
2950 /*
2951  * Similar to ktls_encrypt, but used with asynchronous OCF backends
2952  * (coprocessors) where encryption does not use host CPU resources and
2953  * it can be beneficial to queue more requests than CPUs.
2954  */
2955 static __noinline void
2956 ktls_encrypt_async(struct ktls_wq *wq, struct mbuf *top)
2957 {
2958 	struct ktls_ocf_encrypt_state *state;
2959 	struct ktls_session *tls;
2960 	struct socket *so;
2961 	struct mbuf *m, *n;
2962 	int error, mpages, npages, total_pages;
2963 
2964 	so = top->m_epg_so;
2965 	tls = top->m_epg_tls;
2966 	KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
2967 	KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
2968 #ifdef INVARIANTS
2969 	top->m_epg_so = NULL;
2970 #endif
2971 	total_pages = top->m_epg_enc_cnt;
2972 	npages = 0;
2973 
2974 	error = 0;
2975 	for (m = top; npages != total_pages; m = n) {
2976 		KASSERT(m->m_epg_tls == tls,
2977 		    ("different TLS sessions in a single mbuf chain: %p vs %p",
2978 		    tls, m->m_epg_tls));
2979 		KASSERT(npages + m->m_epg_npgs <= total_pages,
2980 		    ("page count mismatch: top %p, total_pages %d, m %p", top,
2981 		    total_pages, m));
2982 
2983 		state = malloc(sizeof(*state), M_KTLS, M_WAITOK | M_ZERO);
2984 		soref(so);
2985 		state->so = so;
2986 		state->m = m;
2987 
2988 		mpages = m->m_epg_nrdy;
2989 		n = m->m_next;
2990 
2991 		error = ktls_encrypt_record(wq, m, tls, state);
2992 		if (error) {
2993 			counter_u64_add(ktls_offload_failed_crypto, 1);
2994 			free(state, M_KTLS);
2995 			CURVNET_SET(so->so_vnet);
2996 			sorele(so);
2997 			CURVNET_RESTORE();
2998 			break;
2999 		}
3000 
3001 		npages += mpages;
3002 	}
3003 
3004 	CURVNET_SET(so->so_vnet);
3005 	if (error != 0) {
3006 		so->so_proto->pr_abort(so);
3007 		so->so_error = EIO;
3008 		mb_free_notready(m, total_pages - npages);
3009 	}
3010 
3011 	sorele(so);
3012 	CURVNET_RESTORE();
3013 }
3014 
3015 static int
3016 ktls_bind_domain(int domain)
3017 {
3018 	int error;
3019 
3020 	error = cpuset_setthread(curthread->td_tid, &cpuset_domain[domain]);
3021 	if (error != 0)
3022 		return (error);
3023 	curthread->td_domain.dr_policy = DOMAINSET_PREF(domain);
3024 	return (0);
3025 }
3026 
3027 static void
3028 ktls_alloc_thread(void *ctx)
3029 {
3030 	struct ktls_domain_info *ktls_domain = ctx;
3031 	struct ktls_alloc_thread *sc = &ktls_domain->alloc_td;
3032 	void **buf;
3033 	struct sysctl_oid *oid;
3034 	char name[80];
3035 	int domain, error, i, nbufs;
3036 
3037 	domain = ktls_domain - ktls_domains;
3038 	if (bootverbose)
3039 		printf("Starting KTLS alloc thread for domain %d\n", domain);
3040 	error = ktls_bind_domain(domain);
3041 	if (error)
3042 		printf("Unable to bind KTLS alloc thread for domain %d: error %d\n",
3043 		    domain, error);
3044 	snprintf(name, sizeof(name), "domain%d", domain);
3045 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_kern_ipc_tls), OID_AUTO,
3046 	    name, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
3047 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "allocs",
3048 	    CTLFLAG_RD,  &sc->allocs, 0, "buffers allocated");
3049 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "wakeups",
3050 	    CTLFLAG_RD,  &sc->wakeups, 0, "thread wakeups");
3051 	SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "running",
3052 	    CTLFLAG_RD,  &sc->running, 0, "thread running");
3053 
3054 	buf = NULL;
3055 	nbufs = 0;
3056 	for (;;) {
3057 		atomic_store_int(&sc->running, 0);
3058 		tsleep(sc, PZERO | PNOLOCK, "-",  0);
3059 		atomic_store_int(&sc->running, 1);
3060 		sc->wakeups++;
3061 		if (nbufs != ktls_max_alloc) {
3062 			free(buf, M_KTLS);
3063 			nbufs = atomic_load_int(&ktls_max_alloc);
3064 			buf = malloc(sizeof(void *) * nbufs, M_KTLS,
3065 			    M_WAITOK | M_ZERO);
3066 		}
3067 		/*
3068 		 * Below we allocate nbufs with different allocation
3069 		 * flags than we use when allocating normally during
3070 		 * encryption in the ktls worker thread.  We specify
3071 		 * M_NORECLAIM in the worker thread. However, we omit
3072 		 * that flag here and add M_WAITOK so that the VM
3073 		 * system is permitted to perform expensive work to
3074 		 * defragment memory.  We do this here, as it does not
3075 		 * matter if this thread blocks.  If we block a ktls
3076 		 * worker thread, we risk developing backlogs of
3077 		 * buffers to be encrypted, leading to surges of
3078 		 * traffic and potential NIC output drops.
3079 		 */
3080 		for (i = 0; i < nbufs; i++) {
3081 			buf[i] = uma_zalloc(ktls_buffer_zone, M_WAITOK);
3082 			sc->allocs++;
3083 		}
3084 		for (i = 0; i < nbufs; i++) {
3085 			uma_zfree(ktls_buffer_zone, buf[i]);
3086 			buf[i] = NULL;
3087 		}
3088 	}
3089 }
3090 
3091 static void
3092 ktls_work_thread(void *ctx)
3093 {
3094 	struct ktls_wq *wq = ctx;
3095 	struct mbuf *m, *n;
3096 	struct socket *so, *son;
3097 	STAILQ_HEAD(, mbuf) local_m_head;
3098 	STAILQ_HEAD(, socket) local_so_head;
3099 	int cpu;
3100 
3101 	cpu = wq - ktls_wq;
3102 	if (bootverbose)
3103 		printf("Starting KTLS worker thread for CPU %d\n", cpu);
3104 
3105 	/*
3106 	 * Bind to a core.  If ktls_bind_threads is > 1, then
3107 	 * we bind to the NUMA domain instead.
3108 	 */
3109 	if (ktls_bind_threads) {
3110 		int error;
3111 
3112 		if (ktls_bind_threads > 1) {
3113 			struct pcpu *pc = pcpu_find(cpu);
3114 
3115 			error = ktls_bind_domain(pc->pc_domain);
3116 		} else {
3117 			cpuset_t mask;
3118 
3119 			CPU_SETOF(cpu, &mask);
3120 			error = cpuset_setthread(curthread->td_tid, &mask);
3121 		}
3122 		if (error)
3123 			printf("Unable to bind KTLS worker thread for CPU %d: error %d\n",
3124 				cpu, error);
3125 	}
3126 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
3127 	fpu_kern_thread(0);
3128 #endif
3129 	for (;;) {
3130 		mtx_lock(&wq->mtx);
3131 		while (STAILQ_EMPTY(&wq->m_head) &&
3132 		    STAILQ_EMPTY(&wq->so_head)) {
3133 			wq->running = false;
3134 			mtx_sleep(wq, &wq->mtx, 0, "-", 0);
3135 			wq->running = true;
3136 		}
3137 
3138 		STAILQ_INIT(&local_m_head);
3139 		STAILQ_CONCAT(&local_m_head, &wq->m_head);
3140 		STAILQ_INIT(&local_so_head);
3141 		STAILQ_CONCAT(&local_so_head, &wq->so_head);
3142 		mtx_unlock(&wq->mtx);
3143 
3144 		STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
3145 			if (m->m_epg_flags & EPG_FLAG_2FREE) {
3146 				ktls_free(m->m_epg_tls);
3147 				m_free_raw(m);
3148 			} else {
3149 				if (m->m_epg_tls->sync_dispatch)
3150 					ktls_encrypt(wq, m);
3151 				else
3152 					ktls_encrypt_async(wq, m);
3153 				counter_u64_add(ktls_cnt_tx_queued, -1);
3154 			}
3155 		}
3156 
3157 		STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
3158 			ktls_decrypt(so);
3159 			counter_u64_add(ktls_cnt_rx_queued, -1);
3160 		}
3161 	}
3162 }
3163 
3164 #if defined(INET) || defined(INET6)
3165 static void
3166 ktls_disable_ifnet_help(void *context, int pending __unused)
3167 {
3168 	struct ktls_session *tls;
3169 	struct inpcb *inp;
3170 	struct tcpcb *tp;
3171 	struct socket *so;
3172 	int err;
3173 
3174 	tls = context;
3175 	inp = tls->inp;
3176 	if (inp == NULL)
3177 		return;
3178 	INP_WLOCK(inp);
3179 	so = inp->inp_socket;
3180 	MPASS(so != NULL);
3181 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
3182 		goto out;
3183 	}
3184 
3185 	if (so->so_snd.sb_tls_info != NULL)
3186 		err = ktls_set_tx_mode(so, TCP_TLS_MODE_SW);
3187 	else
3188 		err = ENXIO;
3189 	if (err == 0) {
3190 		counter_u64_add(ktls_ifnet_disable_ok, 1);
3191 		/* ktls_set_tx_mode() drops inp wlock, so recheck flags */
3192 		if ((inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) == 0 &&
3193 		    (tp = intotcpcb(inp)) != NULL &&
3194 		    tp->t_fb->tfb_hwtls_change != NULL)
3195 			(*tp->t_fb->tfb_hwtls_change)(tp, 0);
3196 	} else {
3197 		counter_u64_add(ktls_ifnet_disable_fail, 1);
3198 	}
3199 
3200 out:
3201 	sorele(so);
3202 	if (!in_pcbrele_wlocked(inp))
3203 		INP_WUNLOCK(inp);
3204 	ktls_free(tls);
3205 }
3206 
3207 /*
3208  * Called when re-transmits are becoming a substantial portion of the
3209  * sends on this connection.  When this happens, we transition the
3210  * connection to software TLS.  This is needed because most inline TLS
3211  * NICs keep crypto state only for in-order transmits.  This means
3212  * that to handle a TCP rexmit (which is out-of-order), the NIC must
3213  * re-DMA the entire TLS record up to and including the current
3214  * segment.  This means that when re-transmitting the last ~1448 byte
3215  * segment of a 16KB TLS record, we could wind up re-DMA'ing an order
3216  * of magnitude more data than we are sending.  This can cause the
3217  * PCIe link to saturate well before the network, which can cause
3218  * output drops, and a general loss of capacity.
3219  */
3220 void
3221 ktls_disable_ifnet(void *arg)
3222 {
3223 	struct tcpcb *tp;
3224 	struct inpcb *inp;
3225 	struct socket *so;
3226 	struct ktls_session *tls;
3227 
3228 	tp = arg;
3229 	inp = tp->t_inpcb;
3230 	INP_WLOCK_ASSERT(inp);
3231 	so = inp->inp_socket;
3232 	SOCK_LOCK(so);
3233 	tls = so->so_snd.sb_tls_info;
3234 	if (tls->disable_ifnet_pending) {
3235 		SOCK_UNLOCK(so);
3236 		return;
3237 	}
3238 
3239 	/*
3240 	 * note that disable_ifnet_pending is never cleared; disabling
3241 	 * ifnet can only be done once per session, so we never want
3242 	 * to do it again
3243 	 */
3244 
3245 	(void)ktls_hold(tls);
3246 	in_pcbref(inp);
3247 	soref(so);
3248 	tls->disable_ifnet_pending = true;
3249 	tls->inp = inp;
3250 	SOCK_UNLOCK(so);
3251 	TASK_INIT(&tls->disable_ifnet_task, 0, ktls_disable_ifnet_help, tls);
3252 	(void)taskqueue_enqueue(taskqueue_thread, &tls->disable_ifnet_task);
3253 }
3254 #endif
3255