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