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