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