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