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