xref: /freebsd/sys/kern/uipc_ktls.c (revision 2faf504d1ab821fe2b9df9d2afb49bb35e1334f4)
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 	TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_send_tag, tls_new);
713 
714 	/* Copy fields from existing session. */
715 	tls_new->params = tls->params;
716 	tls_new->wq_index = tls->wq_index;
717 
718 	/* Deep copy keys. */
719 	if (tls_new->params.auth_key != NULL) {
720 		tls_new->params.auth_key = malloc(tls->params.auth_key_len,
721 		    M_KTLS, M_WAITOK);
722 		memcpy(tls_new->params.auth_key, tls->params.auth_key,
723 		    tls->params.auth_key_len);
724 	}
725 
726 	tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
727 	    M_WAITOK);
728 	memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
729 	    tls->params.cipher_key_len);
730 
731 	return (tls_new);
732 }
733 #endif
734 
735 static void
736 ktls_cleanup(struct ktls_session *tls)
737 {
738 
739 	counter_u64_add(ktls_offload_active, -1);
740 	switch (tls->mode) {
741 	case TCP_TLS_MODE_SW:
742 		switch (tls->params.cipher_algorithm) {
743 		case CRYPTO_AES_CBC:
744 			counter_u64_add(ktls_sw_cbc, -1);
745 			break;
746 		case CRYPTO_AES_NIST_GCM_16:
747 			counter_u64_add(ktls_sw_gcm, -1);
748 			break;
749 		case CRYPTO_CHACHA20_POLY1305:
750 			counter_u64_add(ktls_sw_chacha20, -1);
751 			break;
752 		}
753 		ktls_ocf_free(tls);
754 		break;
755 	case TCP_TLS_MODE_IFNET:
756 		switch (tls->params.cipher_algorithm) {
757 		case CRYPTO_AES_CBC:
758 			counter_u64_add(ktls_ifnet_cbc, -1);
759 			break;
760 		case CRYPTO_AES_NIST_GCM_16:
761 			counter_u64_add(ktls_ifnet_gcm, -1);
762 			break;
763 		case CRYPTO_CHACHA20_POLY1305:
764 			counter_u64_add(ktls_ifnet_chacha20, -1);
765 			break;
766 		}
767 		if (tls->snd_tag != NULL)
768 			m_snd_tag_rele(tls->snd_tag);
769 		break;
770 #ifdef TCP_OFFLOAD
771 	case TCP_TLS_MODE_TOE:
772 		switch (tls->params.cipher_algorithm) {
773 		case CRYPTO_AES_CBC:
774 			counter_u64_add(ktls_toe_cbc, -1);
775 			break;
776 		case CRYPTO_AES_NIST_GCM_16:
777 			counter_u64_add(ktls_toe_gcm, -1);
778 			break;
779 		case CRYPTO_CHACHA20_POLY1305:
780 			counter_u64_add(ktls_toe_chacha20, -1);
781 			break;
782 		}
783 		break;
784 #endif
785 	}
786 	if (tls->params.auth_key != NULL) {
787 		zfree(tls->params.auth_key, M_KTLS);
788 		tls->params.auth_key = NULL;
789 		tls->params.auth_key_len = 0;
790 	}
791 	if (tls->params.cipher_key != NULL) {
792 		zfree(tls->params.cipher_key, M_KTLS);
793 		tls->params.cipher_key = NULL;
794 		tls->params.cipher_key_len = 0;
795 	}
796 	explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
797 }
798 
799 #if defined(INET) || defined(INET6)
800 
801 #ifdef TCP_OFFLOAD
802 static int
803 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
804 {
805 	struct inpcb *inp;
806 	struct tcpcb *tp;
807 	int error;
808 
809 	inp = so->so_pcb;
810 	INP_WLOCK(inp);
811 	if (inp->inp_flags2 & INP_FREED) {
812 		INP_WUNLOCK(inp);
813 		return (ECONNRESET);
814 	}
815 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
816 		INP_WUNLOCK(inp);
817 		return (ECONNRESET);
818 	}
819 	if (inp->inp_socket == NULL) {
820 		INP_WUNLOCK(inp);
821 		return (ECONNRESET);
822 	}
823 	tp = intotcpcb(inp);
824 	if (!(tp->t_flags & TF_TOE)) {
825 		INP_WUNLOCK(inp);
826 		return (EOPNOTSUPP);
827 	}
828 
829 	error = tcp_offload_alloc_tls_session(tp, tls, direction);
830 	INP_WUNLOCK(inp);
831 	if (error == 0) {
832 		tls->mode = TCP_TLS_MODE_TOE;
833 		switch (tls->params.cipher_algorithm) {
834 		case CRYPTO_AES_CBC:
835 			counter_u64_add(ktls_toe_cbc, 1);
836 			break;
837 		case CRYPTO_AES_NIST_GCM_16:
838 			counter_u64_add(ktls_toe_gcm, 1);
839 			break;
840 		case CRYPTO_CHACHA20_POLY1305:
841 			counter_u64_add(ktls_toe_chacha20, 1);
842 			break;
843 		}
844 	}
845 	return (error);
846 }
847 #endif
848 
849 /*
850  * Common code used when first enabling ifnet TLS on a connection or
851  * when allocating a new ifnet TLS session due to a routing change.
852  * This function allocates a new TLS send tag on whatever interface
853  * the connection is currently routed over.
854  */
855 static int
856 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
857     struct m_snd_tag **mstp)
858 {
859 	union if_snd_tag_alloc_params params;
860 	struct ifnet *ifp;
861 	struct nhop_object *nh;
862 	struct tcpcb *tp;
863 	int error;
864 
865 	INP_RLOCK(inp);
866 	if (inp->inp_flags2 & INP_FREED) {
867 		INP_RUNLOCK(inp);
868 		return (ECONNRESET);
869 	}
870 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
871 		INP_RUNLOCK(inp);
872 		return (ECONNRESET);
873 	}
874 	if (inp->inp_socket == NULL) {
875 		INP_RUNLOCK(inp);
876 		return (ECONNRESET);
877 	}
878 	tp = intotcpcb(inp);
879 
880 	/*
881 	 * Check administrative controls on ifnet TLS to determine if
882 	 * ifnet TLS should be denied.
883 	 *
884 	 * - Always permit 'force' requests.
885 	 * - ktls_ifnet_permitted == 0: always deny.
886 	 */
887 	if (!force && ktls_ifnet_permitted == 0) {
888 		INP_RUNLOCK(inp);
889 		return (ENXIO);
890 	}
891 
892 	/*
893 	 * XXX: Use the cached route in the inpcb to find the
894 	 * interface.  This should perhaps instead use
895 	 * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
896 	 * enabled after a connection has completed key negotiation in
897 	 * userland, the cached route will be present in practice.
898 	 */
899 	nh = inp->inp_route.ro_nh;
900 	if (nh == NULL) {
901 		INP_RUNLOCK(inp);
902 		return (ENXIO);
903 	}
904 	ifp = nh->nh_ifp;
905 	if_ref(ifp);
906 
907 	/*
908 	 * Allocate a TLS + ratelimit tag if the connection has an
909 	 * existing pacing rate.
910 	 */
911 	if (tp->t_pacing_rate != -1 &&
912 	    (ifp->if_capenable & IFCAP_TXTLS_RTLMT) != 0) {
913 		params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
914 		params.tls_rate_limit.inp = inp;
915 		params.tls_rate_limit.tls = tls;
916 		params.tls_rate_limit.max_rate = tp->t_pacing_rate;
917 	} else {
918 		params.hdr.type = IF_SND_TAG_TYPE_TLS;
919 		params.tls.inp = inp;
920 		params.tls.tls = tls;
921 	}
922 	params.hdr.flowid = inp->inp_flowid;
923 	params.hdr.flowtype = inp->inp_flowtype;
924 	params.hdr.numa_domain = inp->inp_numa_domain;
925 	INP_RUNLOCK(inp);
926 
927 	if ((ifp->if_capenable & IFCAP_MEXTPG) == 0) {
928 		error = EOPNOTSUPP;
929 		goto out;
930 	}
931 	if (inp->inp_vflag & INP_IPV6) {
932 		if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
933 			error = EOPNOTSUPP;
934 			goto out;
935 		}
936 	} else {
937 		if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
938 			error = EOPNOTSUPP;
939 			goto out;
940 		}
941 	}
942 	error = m_snd_tag_alloc(ifp, &params, mstp);
943 out:
944 	if_rele(ifp);
945 	return (error);
946 }
947 
948 static int
949 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
950 {
951 	struct m_snd_tag *mst;
952 	int error;
953 
954 	error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
955 	if (error == 0) {
956 		tls->mode = TCP_TLS_MODE_IFNET;
957 		tls->snd_tag = mst;
958 		switch (tls->params.cipher_algorithm) {
959 		case CRYPTO_AES_CBC:
960 			counter_u64_add(ktls_ifnet_cbc, 1);
961 			break;
962 		case CRYPTO_AES_NIST_GCM_16:
963 			counter_u64_add(ktls_ifnet_gcm, 1);
964 			break;
965 		case CRYPTO_CHACHA20_POLY1305:
966 			counter_u64_add(ktls_ifnet_chacha20, 1);
967 			break;
968 		}
969 	}
970 	return (error);
971 }
972 
973 static int
974 ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
975 {
976 	int error;
977 
978 	error = ktls_ocf_try(so, tls, direction);
979 	if (error)
980 		return (error);
981 	tls->mode = TCP_TLS_MODE_SW;
982 	switch (tls->params.cipher_algorithm) {
983 	case CRYPTO_AES_CBC:
984 		counter_u64_add(ktls_sw_cbc, 1);
985 		break;
986 	case CRYPTO_AES_NIST_GCM_16:
987 		counter_u64_add(ktls_sw_gcm, 1);
988 		break;
989 	case CRYPTO_CHACHA20_POLY1305:
990 		counter_u64_add(ktls_sw_chacha20, 1);
991 		break;
992 	}
993 	return (0);
994 }
995 
996 /*
997  * KTLS RX stores data in the socket buffer as a list of TLS records,
998  * where each record is stored as a control message containg the TLS
999  * header followed by data mbufs containing the decrypted data.  This
1000  * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
1001  * both encrypted and decrypted data.  TLS records decrypted by a NIC
1002  * should be queued to the socket buffer as records, but encrypted
1003  * data which needs to be decrypted by software arrives as a stream of
1004  * regular mbufs which need to be converted.  In addition, there may
1005  * already be pending encrypted data in the socket buffer when KTLS RX
1006  * is enabled.
1007  *
1008  * To manage not-yet-decrypted data for KTLS RX, the following scheme
1009  * is used:
1010  *
1011  * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
1012  *
1013  * - ktls_check_rx checks this chain of mbufs reading the TLS header
1014  *   from the first mbuf.  Once all of the data for that TLS record is
1015  *   queued, the socket is queued to a worker thread.
1016  *
1017  * - The worker thread calls ktls_decrypt to decrypt TLS records in
1018  *   the TLS chain.  Each TLS record is detached from the TLS chain,
1019  *   decrypted, and inserted into the regular socket buffer chain as
1020  *   record starting with a control message holding the TLS header and
1021  *   a chain of mbufs holding the encrypted data.
1022  */
1023 
1024 static void
1025 sb_mark_notready(struct sockbuf *sb)
1026 {
1027 	struct mbuf *m;
1028 
1029 	m = sb->sb_mb;
1030 	sb->sb_mtls = m;
1031 	sb->sb_mb = NULL;
1032 	sb->sb_mbtail = NULL;
1033 	sb->sb_lastrecord = NULL;
1034 	for (; m != NULL; m = m->m_next) {
1035 		KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
1036 		    __func__));
1037 		KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
1038 		    __func__));
1039 		KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
1040 		    __func__));
1041 		m->m_flags |= M_NOTREADY;
1042 		sb->sb_acc -= m->m_len;
1043 		sb->sb_tlscc += m->m_len;
1044 		sb->sb_mtlstail = m;
1045 	}
1046 	KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
1047 	    ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
1048 	    sb->sb_ccc));
1049 }
1050 
1051 int
1052 ktls_enable_rx(struct socket *so, struct tls_enable *en)
1053 {
1054 	struct ktls_session *tls;
1055 	int error;
1056 
1057 	if (!ktls_offload_enable)
1058 		return (ENOTSUP);
1059 	if (SOLISTENING(so))
1060 		return (EINVAL);
1061 
1062 	counter_u64_add(ktls_offload_enable_calls, 1);
1063 
1064 	/*
1065 	 * This should always be true since only the TCP socket option
1066 	 * invokes this function.
1067 	 */
1068 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1069 		return (EINVAL);
1070 
1071 	/*
1072 	 * XXX: Don't overwrite existing sessions.  We should permit
1073 	 * this to support rekeying in the future.
1074 	 */
1075 	if (so->so_rcv.sb_tls_info != NULL)
1076 		return (EALREADY);
1077 
1078 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1079 		return (ENOTSUP);
1080 
1081 	/* TLS 1.3 is not yet supported. */
1082 	if (en->tls_vmajor == TLS_MAJOR_VER_ONE &&
1083 	    en->tls_vminor == TLS_MINOR_VER_THREE)
1084 		return (ENOTSUP);
1085 
1086 	error = ktls_create_session(so, en, &tls);
1087 	if (error)
1088 		return (error);
1089 
1090 #ifdef TCP_OFFLOAD
1091 	error = ktls_try_toe(so, tls, KTLS_RX);
1092 	if (error)
1093 #endif
1094 		error = ktls_try_sw(so, tls, KTLS_RX);
1095 
1096 	if (error) {
1097 		ktls_cleanup(tls);
1098 		return (error);
1099 	}
1100 
1101 	/* Mark the socket as using TLS offload. */
1102 	SOCKBUF_LOCK(&so->so_rcv);
1103 	so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1104 	so->so_rcv.sb_tls_info = tls;
1105 	so->so_rcv.sb_flags |= SB_TLS_RX;
1106 
1107 	/* Mark existing data as not ready until it can be decrypted. */
1108 	if (tls->mode != TCP_TLS_MODE_TOE) {
1109 		sb_mark_notready(&so->so_rcv);
1110 		ktls_check_rx(&so->so_rcv);
1111 	}
1112 	SOCKBUF_UNLOCK(&so->so_rcv);
1113 
1114 	counter_u64_add(ktls_offload_total, 1);
1115 
1116 	return (0);
1117 }
1118 
1119 int
1120 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1121 {
1122 	struct ktls_session *tls;
1123 	struct inpcb *inp;
1124 	int error;
1125 
1126 	if (!ktls_offload_enable)
1127 		return (ENOTSUP);
1128 	if (SOLISTENING(so))
1129 		return (EINVAL);
1130 
1131 	counter_u64_add(ktls_offload_enable_calls, 1);
1132 
1133 	/*
1134 	 * This should always be true since only the TCP socket option
1135 	 * invokes this function.
1136 	 */
1137 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1138 		return (EINVAL);
1139 
1140 	/*
1141 	 * XXX: Don't overwrite existing sessions.  We should permit
1142 	 * this to support rekeying in the future.
1143 	 */
1144 	if (so->so_snd.sb_tls_info != NULL)
1145 		return (EALREADY);
1146 
1147 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1148 		return (ENOTSUP);
1149 
1150 	/* TLS requires ext pgs */
1151 	if (mb_use_ext_pgs == 0)
1152 		return (ENXIO);
1153 
1154 	error = ktls_create_session(so, en, &tls);
1155 	if (error)
1156 		return (error);
1157 
1158 	/* Prefer TOE -> ifnet TLS -> software TLS. */
1159 #ifdef TCP_OFFLOAD
1160 	error = ktls_try_toe(so, tls, KTLS_TX);
1161 	if (error)
1162 #endif
1163 		error = ktls_try_ifnet(so, tls, false);
1164 	if (error)
1165 		error = ktls_try_sw(so, tls, KTLS_TX);
1166 
1167 	if (error) {
1168 		ktls_cleanup(tls);
1169 		return (error);
1170 	}
1171 
1172 	error = sblock(&so->so_snd, SBL_WAIT);
1173 	if (error) {
1174 		ktls_cleanup(tls);
1175 		return (error);
1176 	}
1177 
1178 	/*
1179 	 * Write lock the INP when setting sb_tls_info so that
1180 	 * routines in tcp_ratelimit.c can read sb_tls_info while
1181 	 * holding the INP lock.
1182 	 */
1183 	inp = so->so_pcb;
1184 	INP_WLOCK(inp);
1185 	SOCKBUF_LOCK(&so->so_snd);
1186 	so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1187 	so->so_snd.sb_tls_info = tls;
1188 	if (tls->mode != TCP_TLS_MODE_SW)
1189 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1190 	SOCKBUF_UNLOCK(&so->so_snd);
1191 	INP_WUNLOCK(inp);
1192 	sbunlock(&so->so_snd);
1193 
1194 	counter_u64_add(ktls_offload_total, 1);
1195 
1196 	return (0);
1197 }
1198 
1199 int
1200 ktls_get_rx_mode(struct socket *so)
1201 {
1202 	struct ktls_session *tls;
1203 	struct inpcb *inp;
1204 	int mode;
1205 
1206 	if (SOLISTENING(so))
1207 		return (EINVAL);
1208 	inp = so->so_pcb;
1209 	INP_WLOCK_ASSERT(inp);
1210 	SOCKBUF_LOCK(&so->so_rcv);
1211 	tls = so->so_rcv.sb_tls_info;
1212 	if (tls == NULL)
1213 		mode = TCP_TLS_MODE_NONE;
1214 	else
1215 		mode = tls->mode;
1216 	SOCKBUF_UNLOCK(&so->so_rcv);
1217 	return (mode);
1218 }
1219 
1220 int
1221 ktls_get_tx_mode(struct socket *so)
1222 {
1223 	struct ktls_session *tls;
1224 	struct inpcb *inp;
1225 	int mode;
1226 
1227 	if (SOLISTENING(so))
1228 		return (EINVAL);
1229 	inp = so->so_pcb;
1230 	INP_WLOCK_ASSERT(inp);
1231 	SOCKBUF_LOCK(&so->so_snd);
1232 	tls = so->so_snd.sb_tls_info;
1233 	if (tls == NULL)
1234 		mode = TCP_TLS_MODE_NONE;
1235 	else
1236 		mode = tls->mode;
1237 	SOCKBUF_UNLOCK(&so->so_snd);
1238 	return (mode);
1239 }
1240 
1241 /*
1242  * Switch between SW and ifnet TLS sessions as requested.
1243  */
1244 int
1245 ktls_set_tx_mode(struct socket *so, int mode)
1246 {
1247 	struct ktls_session *tls, *tls_new;
1248 	struct inpcb *inp;
1249 	int error;
1250 
1251 	if (SOLISTENING(so))
1252 		return (EINVAL);
1253 	switch (mode) {
1254 	case TCP_TLS_MODE_SW:
1255 	case TCP_TLS_MODE_IFNET:
1256 		break;
1257 	default:
1258 		return (EINVAL);
1259 	}
1260 
1261 	inp = so->so_pcb;
1262 	INP_WLOCK_ASSERT(inp);
1263 	SOCKBUF_LOCK(&so->so_snd);
1264 	tls = so->so_snd.sb_tls_info;
1265 	if (tls == NULL) {
1266 		SOCKBUF_UNLOCK(&so->so_snd);
1267 		return (0);
1268 	}
1269 
1270 	if (tls->mode == mode) {
1271 		SOCKBUF_UNLOCK(&so->so_snd);
1272 		return (0);
1273 	}
1274 
1275 	tls = ktls_hold(tls);
1276 	SOCKBUF_UNLOCK(&so->so_snd);
1277 	INP_WUNLOCK(inp);
1278 
1279 	tls_new = ktls_clone_session(tls);
1280 
1281 	if (mode == TCP_TLS_MODE_IFNET)
1282 		error = ktls_try_ifnet(so, tls_new, true);
1283 	else
1284 		error = ktls_try_sw(so, tls_new, KTLS_TX);
1285 	if (error) {
1286 		counter_u64_add(ktls_switch_failed, 1);
1287 		ktls_free(tls_new);
1288 		ktls_free(tls);
1289 		INP_WLOCK(inp);
1290 		return (error);
1291 	}
1292 
1293 	error = sblock(&so->so_snd, SBL_WAIT);
1294 	if (error) {
1295 		counter_u64_add(ktls_switch_failed, 1);
1296 		ktls_free(tls_new);
1297 		ktls_free(tls);
1298 		INP_WLOCK(inp);
1299 		return (error);
1300 	}
1301 
1302 	/*
1303 	 * If we raced with another session change, keep the existing
1304 	 * session.
1305 	 */
1306 	if (tls != so->so_snd.sb_tls_info) {
1307 		counter_u64_add(ktls_switch_failed, 1);
1308 		sbunlock(&so->so_snd);
1309 		ktls_free(tls_new);
1310 		ktls_free(tls);
1311 		INP_WLOCK(inp);
1312 		return (EBUSY);
1313 	}
1314 
1315 	SOCKBUF_LOCK(&so->so_snd);
1316 	so->so_snd.sb_tls_info = tls_new;
1317 	if (tls_new->mode != TCP_TLS_MODE_SW)
1318 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1319 	SOCKBUF_UNLOCK(&so->so_snd);
1320 	sbunlock(&so->so_snd);
1321 
1322 	/*
1323 	 * Drop two references on 'tls'.  The first is for the
1324 	 * ktls_hold() above.  The second drops the reference from the
1325 	 * socket buffer.
1326 	 */
1327 	KASSERT(tls->refcount >= 2, ("too few references on old session"));
1328 	ktls_free(tls);
1329 	ktls_free(tls);
1330 
1331 	if (mode == TCP_TLS_MODE_IFNET)
1332 		counter_u64_add(ktls_switch_to_ifnet, 1);
1333 	else
1334 		counter_u64_add(ktls_switch_to_sw, 1);
1335 
1336 	INP_WLOCK(inp);
1337 	return (0);
1338 }
1339 
1340 /*
1341  * Try to allocate a new TLS send tag.  This task is scheduled when
1342  * ip_output detects a route change while trying to transmit a packet
1343  * holding a TLS record.  If a new tag is allocated, replace the tag
1344  * in the TLS session.  Subsequent packets on the connection will use
1345  * the new tag.  If a new tag cannot be allocated, drop the
1346  * connection.
1347  */
1348 static void
1349 ktls_reset_send_tag(void *context, int pending)
1350 {
1351 	struct epoch_tracker et;
1352 	struct ktls_session *tls;
1353 	struct m_snd_tag *old, *new;
1354 	struct inpcb *inp;
1355 	struct tcpcb *tp;
1356 	int error;
1357 
1358 	MPASS(pending == 1);
1359 
1360 	tls = context;
1361 	inp = tls->inp;
1362 
1363 	/*
1364 	 * Free the old tag first before allocating a new one.
1365 	 * ip[6]_output_send() will treat a NULL send tag the same as
1366 	 * an ifp mismatch and drop packets until a new tag is
1367 	 * allocated.
1368 	 *
1369 	 * Write-lock the INP when changing tls->snd_tag since
1370 	 * ip[6]_output_send() holds a read-lock when reading the
1371 	 * pointer.
1372 	 */
1373 	INP_WLOCK(inp);
1374 	old = tls->snd_tag;
1375 	tls->snd_tag = NULL;
1376 	INP_WUNLOCK(inp);
1377 	if (old != NULL)
1378 		m_snd_tag_rele(old);
1379 
1380 	error = ktls_alloc_snd_tag(inp, tls, true, &new);
1381 
1382 	if (error == 0) {
1383 		INP_WLOCK(inp);
1384 		tls->snd_tag = new;
1385 		mtx_pool_lock(mtxpool_sleep, tls);
1386 		tls->reset_pending = false;
1387 		mtx_pool_unlock(mtxpool_sleep, tls);
1388 		if (!in_pcbrele_wlocked(inp))
1389 			INP_WUNLOCK(inp);
1390 
1391 		counter_u64_add(ktls_ifnet_reset, 1);
1392 
1393 		/*
1394 		 * XXX: Should we kick tcp_output explicitly now that
1395 		 * the send tag is fixed or just rely on timers?
1396 		 */
1397 	} else {
1398 		NET_EPOCH_ENTER(et);
1399 		INP_WLOCK(inp);
1400 		if (!in_pcbrele_wlocked(inp)) {
1401 			if (!(inp->inp_flags & INP_TIMEWAIT) &&
1402 			    !(inp->inp_flags & INP_DROPPED)) {
1403 				tp = intotcpcb(inp);
1404 				CURVNET_SET(tp->t_vnet);
1405 				tp = tcp_drop(tp, ECONNABORTED);
1406 				CURVNET_RESTORE();
1407 				if (tp != NULL)
1408 					INP_WUNLOCK(inp);
1409 				counter_u64_add(ktls_ifnet_reset_dropped, 1);
1410 			} else
1411 				INP_WUNLOCK(inp);
1412 		}
1413 		NET_EPOCH_EXIT(et);
1414 
1415 		counter_u64_add(ktls_ifnet_reset_failed, 1);
1416 
1417 		/*
1418 		 * Leave reset_pending true to avoid future tasks while
1419 		 * the socket goes away.
1420 		 */
1421 	}
1422 
1423 	ktls_free(tls);
1424 }
1425 
1426 int
1427 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1428 {
1429 
1430 	if (inp == NULL)
1431 		return (ENOBUFS);
1432 
1433 	INP_LOCK_ASSERT(inp);
1434 
1435 	/*
1436 	 * See if we should schedule a task to update the send tag for
1437 	 * this session.
1438 	 */
1439 	mtx_pool_lock(mtxpool_sleep, tls);
1440 	if (!tls->reset_pending) {
1441 		(void) ktls_hold(tls);
1442 		in_pcbref(inp);
1443 		tls->inp = inp;
1444 		tls->reset_pending = true;
1445 		taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1446 	}
1447 	mtx_pool_unlock(mtxpool_sleep, tls);
1448 	return (ENOBUFS);
1449 }
1450 
1451 #ifdef RATELIMIT
1452 int
1453 ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1454 {
1455 	union if_snd_tag_modify_params params = {
1456 		.rate_limit.max_rate = max_pacing_rate,
1457 		.rate_limit.flags = M_NOWAIT,
1458 	};
1459 	struct m_snd_tag *mst;
1460 	struct ifnet *ifp;
1461 
1462 	/* Can't get to the inp, but it should be locked. */
1463 	/* INP_LOCK_ASSERT(inp); */
1464 
1465 	MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1466 
1467 	if (tls->snd_tag == NULL) {
1468 		/*
1469 		 * Resetting send tag, ignore this change.  The
1470 		 * pending reset may or may not see this updated rate
1471 		 * in the tcpcb.  If it doesn't, we will just lose
1472 		 * this rate change.
1473 		 */
1474 		return (0);
1475 	}
1476 
1477 	MPASS(tls->snd_tag != NULL);
1478 	MPASS(tls->snd_tag->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1479 
1480 	mst = tls->snd_tag;
1481 	ifp = mst->ifp;
1482 	return (ifp->if_snd_tag_modify(mst, &params));
1483 }
1484 #endif
1485 #endif
1486 
1487 void
1488 ktls_destroy(struct ktls_session *tls)
1489 {
1490 
1491 	ktls_cleanup(tls);
1492 	uma_zfree(ktls_session_zone, tls);
1493 }
1494 
1495 void
1496 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1497 {
1498 
1499 	for (; m != NULL; m = m->m_next) {
1500 		KASSERT((m->m_flags & M_EXTPG) != 0,
1501 		    ("ktls_seq: mapped mbuf %p", m));
1502 
1503 		m->m_epg_seqno = sb->sb_tls_seqno;
1504 		sb->sb_tls_seqno++;
1505 	}
1506 }
1507 
1508 /*
1509  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
1510  * mbuf in the chain must be an unmapped mbuf.  The payload of the
1511  * mbuf must be populated with the payload of each TLS record.
1512  *
1513  * The record_type argument specifies the TLS record type used when
1514  * populating the TLS header.
1515  *
1516  * The enq_count argument on return is set to the number of pages of
1517  * payload data for this entire chain that need to be encrypted via SW
1518  * encryption.  The returned value should be passed to ktls_enqueue
1519  * when scheduling encryption of this chain of mbufs.  To handle the
1520  * special case of empty fragments for TLS 1.0 sessions, an empty
1521  * fragment counts as one page.
1522  */
1523 void
1524 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1525     uint8_t record_type)
1526 {
1527 	struct tls_record_layer *tlshdr;
1528 	struct mbuf *m;
1529 	uint64_t *noncep;
1530 	uint16_t tls_len;
1531 	int maxlen;
1532 
1533 	maxlen = tls->params.max_frame_len;
1534 	*enq_cnt = 0;
1535 	for (m = top; m != NULL; m = m->m_next) {
1536 		/*
1537 		 * All mbufs in the chain should be TLS records whose
1538 		 * payload does not exceed the maximum frame length.
1539 		 *
1540 		 * Empty TLS records are permitted when using CBC.
1541 		 */
1542 		KASSERT(m->m_len <= maxlen &&
1543 		    (tls->params.cipher_algorithm == CRYPTO_AES_CBC ?
1544 		    m->m_len >= 0 : m->m_len > 0),
1545 		    ("ktls_frame: m %p len %d\n", m, m->m_len));
1546 
1547 		/*
1548 		 * TLS frames require unmapped mbufs to store session
1549 		 * info.
1550 		 */
1551 		KASSERT((m->m_flags & M_EXTPG) != 0,
1552 		    ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1553 
1554 		tls_len = m->m_len;
1555 
1556 		/* Save a reference to the session. */
1557 		m->m_epg_tls = ktls_hold(tls);
1558 
1559 		m->m_epg_hdrlen = tls->params.tls_hlen;
1560 		m->m_epg_trllen = tls->params.tls_tlen;
1561 		if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1562 			int bs, delta;
1563 
1564 			/*
1565 			 * AES-CBC pads messages to a multiple of the
1566 			 * block size.  Note that the padding is
1567 			 * applied after the digest and the encryption
1568 			 * is done on the "plaintext || mac || padding".
1569 			 * At least one byte of padding is always
1570 			 * present.
1571 			 *
1572 			 * Compute the final trailer length assuming
1573 			 * at most one block of padding.
1574 			 * tls->params.tls_tlen is the maximum
1575 			 * possible trailer length (padding + digest).
1576 			 * delta holds the number of excess padding
1577 			 * bytes if the maximum were used.  Those
1578 			 * extra bytes are removed.
1579 			 */
1580 			bs = tls->params.tls_bs;
1581 			delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1582 			m->m_epg_trllen -= delta;
1583 		}
1584 		m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1585 
1586 		/* Populate the TLS header. */
1587 		tlshdr = (void *)m->m_epg_hdr;
1588 		tlshdr->tls_vmajor = tls->params.tls_vmajor;
1589 
1590 		/*
1591 		 * TLS 1.3 masquarades as TLS 1.2 with a record type
1592 		 * of TLS_RLTYPE_APP.
1593 		 */
1594 		if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1595 		    tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1596 			tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1597 			tlshdr->tls_type = TLS_RLTYPE_APP;
1598 			/* save the real record type for later */
1599 			m->m_epg_record_type = record_type;
1600 			m->m_epg_trail[0] = record_type;
1601 		} else {
1602 			tlshdr->tls_vminor = tls->params.tls_vminor;
1603 			tlshdr->tls_type = record_type;
1604 		}
1605 		tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1606 
1607 		/*
1608 		 * Store nonces / explicit IVs after the end of the
1609 		 * TLS header.
1610 		 *
1611 		 * For GCM with TLS 1.2, an 8 byte nonce is copied
1612 		 * from the end of the IV.  The nonce is then
1613 		 * incremented for use by the next record.
1614 		 *
1615 		 * For CBC, a random nonce is inserted for TLS 1.1+.
1616 		 */
1617 		if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
1618 		    tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
1619 			noncep = (uint64_t *)(tls->params.iv + 8);
1620 			be64enc(tlshdr + 1, *noncep);
1621 			(*noncep)++;
1622 		} else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1623 		    tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1624 			arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1625 
1626 		/*
1627 		 * When using SW encryption, mark the mbuf not ready.
1628 		 * It will be marked ready via sbready() after the
1629 		 * record has been encrypted.
1630 		 *
1631 		 * When using ifnet TLS, unencrypted TLS records are
1632 		 * sent down the stack to the NIC.
1633 		 */
1634 		if (tls->mode == TCP_TLS_MODE_SW) {
1635 			m->m_flags |= M_NOTREADY;
1636 			if (__predict_false(tls_len == 0)) {
1637 				/* TLS 1.0 empty fragment. */
1638 				m->m_epg_nrdy = 1;
1639 			} else
1640 				m->m_epg_nrdy = m->m_epg_npgs;
1641 			*enq_cnt += m->m_epg_nrdy;
1642 		}
1643 	}
1644 }
1645 
1646 void
1647 ktls_check_rx(struct sockbuf *sb)
1648 {
1649 	struct tls_record_layer hdr;
1650 	struct ktls_wq *wq;
1651 	struct socket *so;
1652 	bool running;
1653 
1654 	SOCKBUF_LOCK_ASSERT(sb);
1655 	KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1656 	    __func__, sb));
1657 	so = __containerof(sb, struct socket, so_rcv);
1658 
1659 	if (sb->sb_flags & SB_TLS_RX_RUNNING)
1660 		return;
1661 
1662 	/* Is there enough queued for a TLS header? */
1663 	if (sb->sb_tlscc < sizeof(hdr)) {
1664 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
1665 			so->so_error = EMSGSIZE;
1666 		return;
1667 	}
1668 
1669 	m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
1670 
1671 	/* Is the entire record queued? */
1672 	if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
1673 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
1674 			so->so_error = EMSGSIZE;
1675 		return;
1676 	}
1677 
1678 	sb->sb_flags |= SB_TLS_RX_RUNNING;
1679 
1680 	soref(so);
1681 	wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
1682 	mtx_lock(&wq->mtx);
1683 	STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
1684 	running = wq->running;
1685 	mtx_unlock(&wq->mtx);
1686 	if (!running)
1687 		wakeup(wq);
1688 	counter_u64_add(ktls_cnt_rx_queued, 1);
1689 }
1690 
1691 static struct mbuf *
1692 ktls_detach_record(struct sockbuf *sb, int len)
1693 {
1694 	struct mbuf *m, *n, *top;
1695 	int remain;
1696 
1697 	SOCKBUF_LOCK_ASSERT(sb);
1698 	MPASS(len <= sb->sb_tlscc);
1699 
1700 	/*
1701 	 * If TLS chain is the exact size of the record,
1702 	 * just grab the whole record.
1703 	 */
1704 	top = sb->sb_mtls;
1705 	if (sb->sb_tlscc == len) {
1706 		sb->sb_mtls = NULL;
1707 		sb->sb_mtlstail = NULL;
1708 		goto out;
1709 	}
1710 
1711 	/*
1712 	 * While it would be nice to use m_split() here, we need
1713 	 * to know exactly what m_split() allocates to update the
1714 	 * accounting, so do it inline instead.
1715 	 */
1716 	remain = len;
1717 	for (m = top; remain > m->m_len; m = m->m_next)
1718 		remain -= m->m_len;
1719 
1720 	/* Easy case: don't have to split 'm'. */
1721 	if (remain == m->m_len) {
1722 		sb->sb_mtls = m->m_next;
1723 		if (sb->sb_mtls == NULL)
1724 			sb->sb_mtlstail = NULL;
1725 		m->m_next = NULL;
1726 		goto out;
1727 	}
1728 
1729 	/*
1730 	 * Need to allocate an mbuf to hold the remainder of 'm'.  Try
1731 	 * with M_NOWAIT first.
1732 	 */
1733 	n = m_get(M_NOWAIT, MT_DATA);
1734 	if (n == NULL) {
1735 		/*
1736 		 * Use M_WAITOK with socket buffer unlocked.  If
1737 		 * 'sb_mtls' changes while the lock is dropped, return
1738 		 * NULL to force the caller to retry.
1739 		 */
1740 		SOCKBUF_UNLOCK(sb);
1741 
1742 		n = m_get(M_WAITOK, MT_DATA);
1743 
1744 		SOCKBUF_LOCK(sb);
1745 		if (sb->sb_mtls != top) {
1746 			m_free(n);
1747 			return (NULL);
1748 		}
1749 	}
1750 	n->m_flags |= M_NOTREADY;
1751 
1752 	/* Store remainder in 'n'. */
1753 	n->m_len = m->m_len - remain;
1754 	if (m->m_flags & M_EXT) {
1755 		n->m_data = m->m_data + remain;
1756 		mb_dupcl(n, m);
1757 	} else {
1758 		bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
1759 	}
1760 
1761 	/* Trim 'm' and update accounting. */
1762 	m->m_len -= n->m_len;
1763 	sb->sb_tlscc -= n->m_len;
1764 	sb->sb_ccc -= n->m_len;
1765 
1766 	/* Account for 'n'. */
1767 	sballoc_ktls_rx(sb, n);
1768 
1769 	/* Insert 'n' into the TLS chain. */
1770 	sb->sb_mtls = n;
1771 	n->m_next = m->m_next;
1772 	if (sb->sb_mtlstail == m)
1773 		sb->sb_mtlstail = n;
1774 
1775 	/* Detach the record from the TLS chain. */
1776 	m->m_next = NULL;
1777 
1778 out:
1779 	MPASS(m_length(top, NULL) == len);
1780 	for (m = top; m != NULL; m = m->m_next)
1781 		sbfree_ktls_rx(sb, m);
1782 	sb->sb_tlsdcc = len;
1783 	sb->sb_ccc += len;
1784 	SBCHECK(sb);
1785 	return (top);
1786 }
1787 
1788 static void
1789 ktls_decrypt(struct socket *so)
1790 {
1791 	char tls_header[MBUF_PEXT_HDR_LEN];
1792 	struct ktls_session *tls;
1793 	struct sockbuf *sb;
1794 	struct tls_record_layer *hdr;
1795 	struct tls_get_record tgr;
1796 	struct mbuf *control, *data, *m;
1797 	uint64_t seqno;
1798 	int error, remain, tls_len, trail_len;
1799 
1800 	hdr = (struct tls_record_layer *)tls_header;
1801 	sb = &so->so_rcv;
1802 	SOCKBUF_LOCK(sb);
1803 	KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
1804 	    ("%s: socket %p not running", __func__, so));
1805 
1806 	tls = sb->sb_tls_info;
1807 	MPASS(tls != NULL);
1808 
1809 	for (;;) {
1810 		/* Is there enough queued for a TLS header? */
1811 		if (sb->sb_tlscc < tls->params.tls_hlen)
1812 			break;
1813 
1814 		m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
1815 		tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
1816 
1817 		if (hdr->tls_vmajor != tls->params.tls_vmajor ||
1818 		    hdr->tls_vminor != tls->params.tls_vminor)
1819 			error = EINVAL;
1820 		else if (tls_len < tls->params.tls_hlen || tls_len >
1821 		    tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
1822 		    tls->params.tls_tlen)
1823 			error = EMSGSIZE;
1824 		else
1825 			error = 0;
1826 		if (__predict_false(error != 0)) {
1827 			/*
1828 			 * We have a corrupted record and are likely
1829 			 * out of sync.  The connection isn't
1830 			 * recoverable at this point, so abort it.
1831 			 */
1832 			SOCKBUF_UNLOCK(sb);
1833 			counter_u64_add(ktls_offload_corrupted_records, 1);
1834 
1835 			CURVNET_SET(so->so_vnet);
1836 			so->so_proto->pr_usrreqs->pru_abort(so);
1837 			so->so_error = error;
1838 			CURVNET_RESTORE();
1839 			goto deref;
1840 		}
1841 
1842 		/* Is the entire record queued? */
1843 		if (sb->sb_tlscc < tls_len)
1844 			break;
1845 
1846 		/*
1847 		 * Split out the portion of the mbuf chain containing
1848 		 * this TLS record.
1849 		 */
1850 		data = ktls_detach_record(sb, tls_len);
1851 		if (data == NULL)
1852 			continue;
1853 		MPASS(sb->sb_tlsdcc == tls_len);
1854 
1855 		seqno = sb->sb_tls_seqno;
1856 		sb->sb_tls_seqno++;
1857 		SBCHECK(sb);
1858 		SOCKBUF_UNLOCK(sb);
1859 
1860 		error = tls->sw_decrypt(tls, hdr, data, seqno, &trail_len);
1861 		if (error) {
1862 			counter_u64_add(ktls_offload_failed_crypto, 1);
1863 
1864 			SOCKBUF_LOCK(sb);
1865 			if (sb->sb_tlsdcc == 0) {
1866 				/*
1867 				 * sbcut/drop/flush discarded these
1868 				 * mbufs.
1869 				 */
1870 				m_freem(data);
1871 				break;
1872 			}
1873 
1874 			/*
1875 			 * Drop this TLS record's data, but keep
1876 			 * decrypting subsequent records.
1877 			 */
1878 			sb->sb_ccc -= tls_len;
1879 			sb->sb_tlsdcc = 0;
1880 
1881 			CURVNET_SET(so->so_vnet);
1882 			so->so_error = EBADMSG;
1883 			sorwakeup_locked(so);
1884 			CURVNET_RESTORE();
1885 
1886 			m_freem(data);
1887 
1888 			SOCKBUF_LOCK(sb);
1889 			continue;
1890 		}
1891 
1892 		/* Allocate the control mbuf. */
1893 		tgr.tls_type = hdr->tls_type;
1894 		tgr.tls_vmajor = hdr->tls_vmajor;
1895 		tgr.tls_vminor = hdr->tls_vminor;
1896 		tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
1897 		    trail_len);
1898 		control = sbcreatecontrol_how(&tgr, sizeof(tgr),
1899 		    TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
1900 
1901 		SOCKBUF_LOCK(sb);
1902 		if (sb->sb_tlsdcc == 0) {
1903 			/* sbcut/drop/flush discarded these mbufs. */
1904 			MPASS(sb->sb_tlscc == 0);
1905 			m_freem(data);
1906 			m_freem(control);
1907 			break;
1908 		}
1909 
1910 		/*
1911 		 * Clear the 'dcc' accounting in preparation for
1912 		 * adding the decrypted record.
1913 		 */
1914 		sb->sb_ccc -= tls_len;
1915 		sb->sb_tlsdcc = 0;
1916 		SBCHECK(sb);
1917 
1918 		/* If there is no payload, drop all of the data. */
1919 		if (tgr.tls_length == htobe16(0)) {
1920 			m_freem(data);
1921 			data = NULL;
1922 		} else {
1923 			/* Trim header. */
1924 			remain = tls->params.tls_hlen;
1925 			while (remain > 0) {
1926 				if (data->m_len > remain) {
1927 					data->m_data += remain;
1928 					data->m_len -= remain;
1929 					break;
1930 				}
1931 				remain -= data->m_len;
1932 				data = m_free(data);
1933 			}
1934 
1935 			/* Trim trailer and clear M_NOTREADY. */
1936 			remain = be16toh(tgr.tls_length);
1937 			m = data;
1938 			for (m = data; remain > m->m_len; m = m->m_next) {
1939 				m->m_flags &= ~M_NOTREADY;
1940 				remain -= m->m_len;
1941 			}
1942 			m->m_len = remain;
1943 			m_freem(m->m_next);
1944 			m->m_next = NULL;
1945 			m->m_flags &= ~M_NOTREADY;
1946 
1947 			/* Set EOR on the final mbuf. */
1948 			m->m_flags |= M_EOR;
1949 		}
1950 
1951 		sbappendcontrol_locked(sb, data, control, 0);
1952 	}
1953 
1954 	sb->sb_flags &= ~SB_TLS_RX_RUNNING;
1955 
1956 	if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
1957 		so->so_error = EMSGSIZE;
1958 
1959 	sorwakeup_locked(so);
1960 
1961 deref:
1962 	SOCKBUF_UNLOCK_ASSERT(sb);
1963 
1964 	CURVNET_SET(so->so_vnet);
1965 	SOCK_LOCK(so);
1966 	sorele(so);
1967 	CURVNET_RESTORE();
1968 }
1969 
1970 void
1971 ktls_enqueue_to_free(struct mbuf *m)
1972 {
1973 	struct ktls_wq *wq;
1974 	bool running;
1975 
1976 	/* Mark it for freeing. */
1977 	m->m_epg_flags |= EPG_FLAG_2FREE;
1978 	wq = &ktls_wq[m->m_epg_tls->wq_index];
1979 	mtx_lock(&wq->mtx);
1980 	STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1981 	running = wq->running;
1982 	mtx_unlock(&wq->mtx);
1983 	if (!running)
1984 		wakeup(wq);
1985 }
1986 
1987 static void *
1988 ktls_buffer_alloc(struct ktls_wq *wq, struct mbuf *m)
1989 {
1990 	void *buf;
1991 	int domain, running;
1992 
1993 	if (m->m_epg_npgs <= 2)
1994 		return (NULL);
1995 	if (ktls_buffer_zone == NULL)
1996 		return (NULL);
1997 	if ((u_int)(ticks - wq->lastallocfail) < hz) {
1998 		/*
1999 		 * Rate-limit allocation attempts after a failure.
2000 		 * ktls_buffer_import() will acquire a per-domain mutex to check
2001 		 * the free page queues and may fail consistently if memory is
2002 		 * fragmented.
2003 		 */
2004 		return (NULL);
2005 	}
2006 	buf = uma_zalloc(ktls_buffer_zone, M_NOWAIT | M_NORECLAIM);
2007 	if (buf == NULL) {
2008 		domain = PCPU_GET(domain);
2009 		wq->lastallocfail = ticks;
2010 
2011 		/*
2012 		 * Note that this check is "racy", but the races are
2013 		 * harmless, and are either a spurious wakeup if
2014 		 * multiple threads fail allocations before the alloc
2015 		 * thread wakes, or waiting an extra second in case we
2016 		 * see an old value of running == true.
2017 		 */
2018 		if (!VM_DOMAIN_EMPTY(domain)) {
2019 			running = atomic_load_int(&ktls_domains[domain].alloc_td.running);
2020 			if (!running)
2021 				wakeup(&ktls_domains[domain].alloc_td);
2022 		}
2023 	}
2024 	return (buf);
2025 }
2026 
2027 void
2028 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
2029 {
2030 	struct ktls_wq *wq;
2031 	bool running;
2032 
2033 	KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2034 	    (M_EXTPG | M_NOTREADY)),
2035 	    ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
2036 	KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
2037 
2038 	KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
2039 
2040 	m->m_epg_enc_cnt = page_count;
2041 
2042 	/*
2043 	 * Save a pointer to the socket.  The caller is responsible
2044 	 * for taking an additional reference via soref().
2045 	 */
2046 	m->m_epg_so = so;
2047 
2048 	wq = &ktls_wq[m->m_epg_tls->wq_index];
2049 	mtx_lock(&wq->mtx);
2050 	STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2051 	running = wq->running;
2052 	mtx_unlock(&wq->mtx);
2053 	if (!running)
2054 		wakeup(wq);
2055 	counter_u64_add(ktls_cnt_tx_queued, 1);
2056 }
2057 
2058 #define	MAX_TLS_PAGES	(1 + btoc(TLS_MAX_MSG_SIZE_V10_2))
2059 
2060 static __noinline void
2061 ktls_encrypt(struct ktls_wq *wq, struct mbuf *top)
2062 {
2063 	struct ktls_session *tls;
2064 	struct socket *so;
2065 	struct mbuf *m;
2066 	vm_paddr_t parray[MAX_TLS_PAGES + 1];
2067 	struct iovec dst_iov[MAX_TLS_PAGES + 2];
2068 	vm_page_t pg;
2069 	void *cbuf;
2070 	int error, i, len, npages, off, total_pages;
2071 
2072 	so = top->m_epg_so;
2073 	tls = top->m_epg_tls;
2074 	KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
2075 	KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
2076 #ifdef INVARIANTS
2077 	top->m_epg_so = NULL;
2078 #endif
2079 	total_pages = top->m_epg_enc_cnt;
2080 	npages = 0;
2081 
2082 	/*
2083 	 * Encrypt the TLS records in the chain of mbufs starting with
2084 	 * 'top'.  'total_pages' gives us a total count of pages and is
2085 	 * used to know when we have finished encrypting the TLS
2086 	 * records originally queued with 'top'.
2087 	 *
2088 	 * NB: These mbufs are queued in the socket buffer and
2089 	 * 'm_next' is traversing the mbufs in the socket buffer.  The
2090 	 * socket buffer lock is not held while traversing this chain.
2091 	 * Since the mbufs are all marked M_NOTREADY their 'm_next'
2092 	 * pointers should be stable.  However, the 'm_next' of the
2093 	 * last mbuf encrypted is not necessarily NULL.  It can point
2094 	 * to other mbufs appended while 'top' was on the TLS work
2095 	 * queue.
2096 	 *
2097 	 * Each mbuf holds an entire TLS record.
2098 	 */
2099 	error = 0;
2100 	for (m = top; npages != total_pages; m = m->m_next) {
2101 		KASSERT(m->m_epg_tls == tls,
2102 		    ("different TLS sessions in a single mbuf chain: %p vs %p",
2103 		    tls, m->m_epg_tls));
2104 		KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2105 		    (M_EXTPG | M_NOTREADY),
2106 		    ("%p not unready & nomap mbuf (top = %p)\n", m, top));
2107 		KASSERT(npages + m->m_epg_npgs <= total_pages,
2108 		    ("page count mismatch: top %p, total_pages %d, m %p", top,
2109 		    total_pages, m));
2110 		KASSERT(ptoa(m->m_epg_npgs) <= ktls_maxlen,
2111 		    ("page count %d larger than maximum frame length %d",
2112 		    m->m_epg_npgs, ktls_maxlen));
2113 
2114 		/*
2115 		 * For anonymous mbufs, encryption is done in place.
2116 		 * For file-backed mbufs (from sendfile), anonymous
2117 		 * wired pages are allocated and used as the
2118 		 * encryption destination.
2119 		 */
2120 		if ((m->m_epg_flags & EPG_FLAG_ANON) != 0) {
2121 			error = (*tls->sw_encrypt)(tls, m, NULL, 0);
2122 		} else {
2123 			if ((cbuf = ktls_buffer_alloc(wq, m)) != NULL) {
2124 				len = ptoa(m->m_epg_npgs - 1) +
2125 				    m->m_epg_last_len - m->m_epg_1st_off;
2126 				dst_iov[0].iov_base = (char *)cbuf +
2127 				    m->m_epg_1st_off;
2128 				dst_iov[0].iov_len = len;
2129 				parray[0] = DMAP_TO_PHYS((vm_offset_t)cbuf);
2130 				i = 1;
2131 			} else {
2132 				off = m->m_epg_1st_off;
2133 				for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2134 					do {
2135 						pg = vm_page_alloc(NULL, 0,
2136 						    VM_ALLOC_NORMAL |
2137 						    VM_ALLOC_NOOBJ |
2138 						    VM_ALLOC_NODUMP |
2139 						    VM_ALLOC_WIRED |
2140 						    VM_ALLOC_WAITFAIL);
2141 					} while (pg == NULL);
2142 
2143 					len = m_epg_pagelen(m, i, off);
2144 					parray[i] = VM_PAGE_TO_PHYS(pg);
2145 					dst_iov[i].iov_base =
2146 					    (char *)(void *)PHYS_TO_DMAP(
2147 					    parray[i]) + off;
2148 					dst_iov[i].iov_len = len;
2149 				}
2150 			}
2151 			KASSERT(i + 1 <= nitems(dst_iov),
2152 			    ("dst_iov is too small"));
2153 			dst_iov[i].iov_base = m->m_epg_trail;
2154 			dst_iov[i].iov_len = m->m_epg_trllen;
2155 
2156 			error = (*tls->sw_encrypt)(tls, m, dst_iov, i + 1);
2157 
2158 			/* Free the old pages. */
2159 			m->m_ext.ext_free(m);
2160 
2161 			/* Replace them with the new pages. */
2162 			if (cbuf != NULL) {
2163 				for (i = 0; i < m->m_epg_npgs; i++)
2164 					m->m_epg_pa[i] = parray[0] + ptoa(i);
2165 
2166 				/* Contig pages should go back to the cache. */
2167 				m->m_ext.ext_free = ktls_free_mext_contig;
2168 			} else {
2169 				for (i = 0; i < m->m_epg_npgs; i++)
2170 					m->m_epg_pa[i] = parray[i];
2171 
2172 				/* Use the basic free routine. */
2173 				m->m_ext.ext_free = mb_free_mext_pgs;
2174 			}
2175 
2176 			/* Pages are now writable. */
2177 			m->m_epg_flags |= EPG_FLAG_ANON;
2178 		}
2179 		if (error) {
2180 			counter_u64_add(ktls_offload_failed_crypto, 1);
2181 			break;
2182 		}
2183 
2184 		npages += m->m_epg_nrdy;
2185 
2186 		/*
2187 		 * Drop a reference to the session now that it is no
2188 		 * longer needed.  Existing code depends on encrypted
2189 		 * records having no associated session vs
2190 		 * yet-to-be-encrypted records having an associated
2191 		 * session.
2192 		 */
2193 		m->m_epg_tls = NULL;
2194 		ktls_free(tls);
2195 	}
2196 
2197 	CURVNET_SET(so->so_vnet);
2198 	if (error == 0) {
2199 		(void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
2200 	} else {
2201 		so->so_proto->pr_usrreqs->pru_abort(so);
2202 		so->so_error = EIO;
2203 		mb_free_notready(top, total_pages);
2204 	}
2205 
2206 	SOCK_LOCK(so);
2207 	sorele(so);
2208 	CURVNET_RESTORE();
2209 }
2210 
2211 static void
2212 ktls_alloc_thread(void *ctx)
2213 {
2214 	struct ktls_domain_info *ktls_domain = ctx;
2215 	struct ktls_alloc_thread *sc = &ktls_domain->alloc_td;
2216 	void **buf;
2217 	struct sysctl_oid *oid;
2218 	char name[80];
2219 	int i, nbufs;
2220 
2221 	curthread->td_domain.dr_policy =
2222 	    DOMAINSET_PREF(PCPU_GET(domain));
2223 	snprintf(name, sizeof(name), "domain%d", PCPU_GET(domain));
2224 	if (bootverbose)
2225 		printf("Starting KTLS alloc thread for domain %d\n",
2226 		    PCPU_GET(domain));
2227 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_kern_ipc_tls), OID_AUTO,
2228 	    name, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2229 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "allocs",
2230 	    CTLFLAG_RD,  &sc->allocs, 0, "buffers allocated");
2231 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "wakeups",
2232 	    CTLFLAG_RD,  &sc->wakeups, 0, "thread wakeups");
2233 	SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "running",
2234 	    CTLFLAG_RD,  &sc->running, 0, "thread running");
2235 
2236 	buf = NULL;
2237 	nbufs = 0;
2238 	for (;;) {
2239 		atomic_store_int(&sc->running, 0);
2240 		tsleep(sc, PZERO | PNOLOCK, "-",  0);
2241 		atomic_store_int(&sc->running, 1);
2242 		sc->wakeups++;
2243 		if (nbufs != ktls_max_alloc) {
2244 			free(buf, M_KTLS);
2245 			nbufs = atomic_load_int(&ktls_max_alloc);
2246 			buf = malloc(sizeof(void *) * nbufs, M_KTLS,
2247 			    M_WAITOK | M_ZERO);
2248 		}
2249 		/*
2250 		 * Below we allocate nbufs with different allocation
2251 		 * flags than we use when allocating normally during
2252 		 * encryption in the ktls worker thread.  We specify
2253 		 * M_NORECLAIM in the worker thread. However, we omit
2254 		 * that flag here and add M_WAITOK so that the VM
2255 		 * system is permitted to perform expensive work to
2256 		 * defragment memory.  We do this here, as it does not
2257 		 * matter if this thread blocks.  If we block a ktls
2258 		 * worker thread, we risk developing backlogs of
2259 		 * buffers to be encrypted, leading to surges of
2260 		 * traffic and potential NIC output drops.
2261 		 */
2262 		for (i = 0; i < nbufs; i++) {
2263 			buf[i] = uma_zalloc(ktls_buffer_zone, M_WAITOK);
2264 			sc->allocs++;
2265 		}
2266 		for (i = 0; i < nbufs; i++) {
2267 			uma_zfree(ktls_buffer_zone, buf[i]);
2268 			buf[i] = NULL;
2269 		}
2270 	}
2271 }
2272 
2273 static void
2274 ktls_work_thread(void *ctx)
2275 {
2276 	struct ktls_wq *wq = ctx;
2277 	struct mbuf *m, *n;
2278 	struct socket *so, *son;
2279 	STAILQ_HEAD(, mbuf) local_m_head;
2280 	STAILQ_HEAD(, socket) local_so_head;
2281 
2282 	if (ktls_bind_threads > 1) {
2283 		curthread->td_domain.dr_policy =
2284 			DOMAINSET_PREF(PCPU_GET(domain));
2285 	}
2286 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
2287 	fpu_kern_thread(0);
2288 #endif
2289 	for (;;) {
2290 		mtx_lock(&wq->mtx);
2291 		while (STAILQ_EMPTY(&wq->m_head) &&
2292 		    STAILQ_EMPTY(&wq->so_head)) {
2293 			wq->running = false;
2294 			mtx_sleep(wq, &wq->mtx, 0, "-", 0);
2295 			wq->running = true;
2296 		}
2297 
2298 		STAILQ_INIT(&local_m_head);
2299 		STAILQ_CONCAT(&local_m_head, &wq->m_head);
2300 		STAILQ_INIT(&local_so_head);
2301 		STAILQ_CONCAT(&local_so_head, &wq->so_head);
2302 		mtx_unlock(&wq->mtx);
2303 
2304 		STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
2305 			if (m->m_epg_flags & EPG_FLAG_2FREE) {
2306 				ktls_free(m->m_epg_tls);
2307 				m_free_raw(m);
2308 			} else {
2309 				ktls_encrypt(wq, m);
2310 				counter_u64_add(ktls_cnt_tx_queued, -1);
2311 			}
2312 		}
2313 
2314 		STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
2315 			ktls_decrypt(so);
2316 			counter_u64_add(ktls_cnt_rx_queued, -1);
2317 		}
2318 	}
2319 }
2320 
2321 #if defined(INET) || defined(INET6)
2322 static void
2323 ktls_disable_ifnet_help(void *context, int pending __unused)
2324 {
2325 	struct ktls_session *tls;
2326 	struct inpcb *inp;
2327 	struct tcpcb *tp;
2328 	struct socket *so;
2329 	int err;
2330 
2331 	tls = context;
2332 	inp = tls->inp;
2333 	if (inp == NULL)
2334 		return;
2335 	INP_WLOCK(inp);
2336 	so = inp->inp_socket;
2337 	MPASS(so != NULL);
2338 	if ((inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) ||
2339 	    (inp->inp_flags2 & INP_FREED)) {
2340 		goto out;
2341 	}
2342 
2343 	if (so->so_snd.sb_tls_info != NULL)
2344 		err = ktls_set_tx_mode(so, TCP_TLS_MODE_SW);
2345 	else
2346 		err = ENXIO;
2347 	if (err == 0) {
2348 		counter_u64_add(ktls_ifnet_disable_ok, 1);
2349 		/* ktls_set_tx_mode() drops inp wlock, so recheck flags */
2350 		if ((inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) == 0 &&
2351 		    (inp->inp_flags2 & INP_FREED) == 0 &&
2352 		    (tp = intotcpcb(inp)) != NULL &&
2353 		    tp->t_fb->tfb_hwtls_change != NULL)
2354 			(*tp->t_fb->tfb_hwtls_change)(tp, 0);
2355 	} else {
2356 		counter_u64_add(ktls_ifnet_disable_fail, 1);
2357 	}
2358 
2359 out:
2360 	SOCK_LOCK(so);
2361 	sorele(so);
2362 	if (!in_pcbrele_wlocked(inp))
2363 		INP_WUNLOCK(inp);
2364 	ktls_free(tls);
2365 }
2366 
2367 /*
2368  * Called when re-transmits are becoming a substantial portion of the
2369  * sends on this connection.  When this happens, we transition the
2370  * connection to software TLS.  This is needed because most inline TLS
2371  * NICs keep crypto state only for in-order transmits.  This means
2372  * that to handle a TCP rexmit (which is out-of-order), the NIC must
2373  * re-DMA the entire TLS record up to and including the current
2374  * segment.  This means that when re-transmitting the last ~1448 byte
2375  * segment of a 16KB TLS record, we could wind up re-DMA'ing an order
2376  * of magnitude more data than we are sending.  This can cause the
2377  * PCIe link to saturate well before the network, which can cause
2378  * output drops, and a general loss of capacity.
2379  */
2380 void
2381 ktls_disable_ifnet(void *arg)
2382 {
2383 	struct tcpcb *tp;
2384 	struct inpcb *inp;
2385 	struct socket *so;
2386 	struct ktls_session *tls;
2387 
2388 	tp = arg;
2389 	inp = tp->t_inpcb;
2390 	INP_WLOCK_ASSERT(inp);
2391 	so = inp->inp_socket;
2392 	SOCK_LOCK(so);
2393 	tls = so->so_snd.sb_tls_info;
2394 	if (tls->disable_ifnet_pending) {
2395 		SOCK_UNLOCK(so);
2396 		return;
2397 	}
2398 
2399 	/*
2400 	 * note that disable_ifnet_pending is never cleared; disabling
2401 	 * ifnet can only be done once per session, so we never want
2402 	 * to do it again
2403 	 */
2404 
2405 	(void)ktls_hold(tls);
2406 	in_pcbref(inp);
2407 	soref(so);
2408 	tls->disable_ifnet_pending = true;
2409 	tls->inp = inp;
2410 	SOCK_UNLOCK(so);
2411 	TASK_INIT(&tls->disable_ifnet_task, 0, ktls_disable_ifnet_help, tls);
2412 	(void)taskqueue_enqueue(taskqueue_thread, &tls->disable_ifnet_task);
2413 }
2414 #endif
2415