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