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