2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2014-2019 Netflix Inc.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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
28 #include <sys/cdefs.h>
30 #include "opt_inet6.h"
31 #include "opt_kern_tls.h"
32 #include "opt_ratelimit.h"
35 #include <sys/param.h>
36 #include <sys/kernel.h>
37 #include <sys/domainset.h>
38 #include <sys/endian.h>
42 #include <sys/mutex.h>
43 #include <sys/rmlock.h>
45 #include <sys/protosw.h>
46 #include <sys/refcount.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/taskqueue.h>
52 #include <sys/kthread.h>
54 #include <sys/vmmeter.h>
55 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
56 #include <machine/pcb.h>
58 #include <machine/vmparam.h>
60 #include <net/if_var.h>
62 #include <net/netisr.h>
63 #include <net/rss_config.h>
65 #include <net/route.h>
66 #include <net/route/nhop.h>
67 #include <netinet/in.h>
68 #include <netinet/in_pcb.h>
69 #include <netinet/tcp_var.h>
71 #include <netinet/tcp_offload.h>
73 #include <opencrypto/cryptodev.h>
74 #include <opencrypto/ktls.h>
76 #include <vm/vm_pageout.h>
77 #include <vm/vm_page.h>
78 #include <vm/vm_pagequeue.h>
82 STAILQ_HEAD(, mbuf) m_head;
83 STAILQ_HEAD(, socket) so_head;
86 } __aligned(CACHE_LINE_SIZE);
88 struct ktls_reclaim_thread {
95 struct ktls_domain_info {
98 struct ktls_reclaim_thread reclaim_td;
101 struct ktls_domain_info ktls_domains[MAXMEMDOM];
102 static struct ktls_wq *ktls_wq;
103 static struct proc *ktls_proc;
104 static uma_zone_t ktls_session_zone;
105 static uma_zone_t ktls_buffer_zone;
106 static uint16_t ktls_cpuid_lookup[MAXCPU];
107 static int ktls_init_state;
108 static struct sx ktls_init_lock;
109 SX_SYSINIT(ktls_init_lock, &ktls_init_lock, "ktls init");
111 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
112 "Kernel TLS offload");
113 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
114 "Kernel TLS offload stats");
117 static int ktls_bind_threads = 1;
119 static int ktls_bind_threads;
121 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
122 &ktls_bind_threads, 0,
123 "Bind crypto threads to cores (1) or cores and domains (2) at boot");
125 static u_int ktls_maxlen = 16384;
126 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RDTUN,
127 &ktls_maxlen, 0, "Maximum TLS record size");
129 static int ktls_number_threads;
130 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
131 &ktls_number_threads, 0,
132 "Number of TLS threads in thread-pool");
134 unsigned int ktls_ifnet_max_rexmit_pct = 2;
135 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, ifnet_max_rexmit_pct, CTLFLAG_RWTUN,
136 &ktls_ifnet_max_rexmit_pct, 2,
137 "Max percent bytes retransmitted before ifnet TLS is disabled");
139 static bool ktls_offload_enable;
140 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RWTUN,
141 &ktls_offload_enable, 0,
142 "Enable support for kernel TLS offload");
144 static bool ktls_cbc_enable = true;
145 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RWTUN,
147 "Enable support of AES-CBC crypto for kernel TLS");
149 static bool ktls_sw_buffer_cache = true;
150 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, sw_buffer_cache, CTLFLAG_RDTUN,
151 &ktls_sw_buffer_cache, 1,
152 "Enable caching of output buffers for SW encryption");
154 static int ktls_max_reclaim = 1024;
155 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, max_reclaim, CTLFLAG_RWTUN,
156 &ktls_max_reclaim, 128,
157 "Max number of 16k buffers to reclaim in thread context");
159 static COUNTER_U64_DEFINE_EARLY(ktls_tasks_active);
160 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
161 &ktls_tasks_active, "Number of active tasks");
163 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_tx_pending);
164 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_pending, CTLFLAG_RD,
165 &ktls_cnt_tx_pending,
166 "Number of TLS 1.0 records waiting for earlier TLS records");
168 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_tx_queued);
169 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_inqueue, CTLFLAG_RD,
171 "Number of TLS records in queue to tasks for SW encryption");
173 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_rx_queued);
174 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_rx_inqueue, CTLFLAG_RD,
176 "Number of TLS sockets in queue to tasks for SW decryption");
178 static COUNTER_U64_DEFINE_EARLY(ktls_offload_total);
179 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
180 CTLFLAG_RD, &ktls_offload_total,
181 "Total successful TLS setups (parameters set)");
183 static COUNTER_U64_DEFINE_EARLY(ktls_offload_enable_calls);
184 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
185 CTLFLAG_RD, &ktls_offload_enable_calls,
186 "Total number of TLS enable calls made");
188 static COUNTER_U64_DEFINE_EARLY(ktls_offload_active);
189 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
190 &ktls_offload_active, "Total Active TLS sessions");
192 static COUNTER_U64_DEFINE_EARLY(ktls_offload_corrupted_records);
193 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, corrupted_records, CTLFLAG_RD,
194 &ktls_offload_corrupted_records, "Total corrupted TLS records received");
196 static COUNTER_U64_DEFINE_EARLY(ktls_offload_failed_crypto);
197 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
198 &ktls_offload_failed_crypto, "Total TLS crypto failures");
200 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_ifnet);
201 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
202 &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
204 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_sw);
205 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
206 &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
208 static COUNTER_U64_DEFINE_EARLY(ktls_switch_failed);
209 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
210 &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
212 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_disable_fail);
213 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, ifnet_disable_failed, CTLFLAG_RD,
214 &ktls_ifnet_disable_fail, "TLS sessions unable to switch to SW from ifnet");
216 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_disable_ok);
217 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, ifnet_disable_ok, CTLFLAG_RD,
218 &ktls_ifnet_disable_ok, "TLS sessions able to switch to SW from ifnet");
220 static COUNTER_U64_DEFINE_EARLY(ktls_destroy_task);
221 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, destroy_task, CTLFLAG_RD,
223 "Number of times ktls session was destroyed via taskqueue");
225 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
226 "Software TLS session stats");
227 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
228 "Hardware (ifnet) TLS session stats");
230 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
231 "TOE TLS session stats");
234 static COUNTER_U64_DEFINE_EARLY(ktls_sw_cbc);
235 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
236 "Active number of software TLS sessions using AES-CBC");
238 static COUNTER_U64_DEFINE_EARLY(ktls_sw_gcm);
239 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
240 "Active number of software TLS sessions using AES-GCM");
242 static COUNTER_U64_DEFINE_EARLY(ktls_sw_chacha20);
243 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, chacha20, CTLFLAG_RD,
245 "Active number of software TLS sessions using Chacha20-Poly1305");
247 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_cbc);
248 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
250 "Active number of ifnet TLS sessions using AES-CBC");
252 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_gcm);
253 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
255 "Active number of ifnet TLS sessions using AES-GCM");
257 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_chacha20);
258 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, chacha20, CTLFLAG_RD,
259 &ktls_ifnet_chacha20,
260 "Active number of ifnet TLS sessions using Chacha20-Poly1305");
262 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset);
263 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
264 &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
266 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_dropped);
267 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
268 &ktls_ifnet_reset_dropped,
269 "TLS sessions dropped after failing to update ifnet send tag");
271 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_failed);
272 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
273 &ktls_ifnet_reset_failed,
274 "TLS sessions that failed to allocate a new ifnet send tag");
276 static int ktls_ifnet_permitted;
277 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
278 &ktls_ifnet_permitted, 1,
279 "Whether to permit hardware (ifnet) TLS sessions");
282 static COUNTER_U64_DEFINE_EARLY(ktls_toe_cbc);
283 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
285 "Active number of TOE TLS sessions using AES-CBC");
287 static COUNTER_U64_DEFINE_EARLY(ktls_toe_gcm);
288 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
290 "Active number of TOE TLS sessions using AES-GCM");
292 static COUNTER_U64_DEFINE_EARLY(ktls_toe_chacha20);
293 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, chacha20, CTLFLAG_RD,
295 "Active number of TOE TLS sessions using Chacha20-Poly1305");
298 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
300 static void ktls_reclaim_thread(void *ctx);
301 static void ktls_reset_receive_tag(void *context, int pending);
302 static void ktls_reset_send_tag(void *context, int pending);
303 static void ktls_work_thread(void *ctx);
306 ktls_copyin_tls_enable(struct sockopt *sopt, struct tls_enable *tls)
308 struct tls_enable_v0 tls_v0;
310 uint8_t *cipher_key = NULL, *iv = NULL, *auth_key = NULL;
312 if (sopt->sopt_valsize == sizeof(tls_v0)) {
313 error = sooptcopyin(sopt, &tls_v0, sizeof(tls_v0), sizeof(tls_v0));
316 memset(tls, 0, sizeof(*tls));
317 tls->cipher_key = tls_v0.cipher_key;
319 tls->auth_key = tls_v0.auth_key;
320 tls->cipher_algorithm = tls_v0.cipher_algorithm;
321 tls->cipher_key_len = tls_v0.cipher_key_len;
322 tls->iv_len = tls_v0.iv_len;
323 tls->auth_algorithm = tls_v0.auth_algorithm;
324 tls->auth_key_len = tls_v0.auth_key_len;
325 tls->flags = tls_v0.flags;
326 tls->tls_vmajor = tls_v0.tls_vmajor;
327 tls->tls_vminor = tls_v0.tls_vminor;
329 error = sooptcopyin(sopt, tls, sizeof(*tls), sizeof(*tls));
334 if (tls->cipher_key_len < 0 || tls->cipher_key_len > TLS_MAX_PARAM_SIZE)
336 if (tls->iv_len < 0 || tls->iv_len > sizeof(((struct ktls_session *)NULL)->params.iv))
338 if (tls->auth_key_len < 0 || tls->auth_key_len > TLS_MAX_PARAM_SIZE)
341 /* All supported algorithms require a cipher key. */
342 if (tls->cipher_key_len == 0)
346 * Now do a deep copy of the variable-length arrays in the struct, so that
347 * subsequent consumers of it can reliably assume kernel memory. This
348 * requires doing our own allocations, which we will free in the
349 * error paths so that our caller need only worry about outstanding
350 * allocations existing on successful return.
352 if (tls->cipher_key_len != 0) {
353 cipher_key = malloc(tls->cipher_key_len, M_KTLS, M_WAITOK);
354 if (sopt->sopt_td != NULL) {
355 error = copyin(tls->cipher_key, cipher_key, tls->cipher_key_len);
359 bcopy(tls->cipher_key, cipher_key, tls->cipher_key_len);
362 if (tls->iv_len != 0) {
363 iv = malloc(tls->iv_len, M_KTLS, M_WAITOK);
364 if (sopt->sopt_td != NULL) {
365 error = copyin(tls->iv, iv, tls->iv_len);
369 bcopy(tls->iv, iv, tls->iv_len);
372 if (tls->auth_key_len != 0) {
373 auth_key = malloc(tls->auth_key_len, M_KTLS, M_WAITOK);
374 if (sopt->sopt_td != NULL) {
375 error = copyin(tls->auth_key, auth_key, tls->auth_key_len);
379 bcopy(tls->auth_key, auth_key, tls->auth_key_len);
382 tls->cipher_key = cipher_key;
384 tls->auth_key = auth_key;
388 zfree(cipher_key, M_KTLS);
390 zfree(auth_key, M_KTLS);
397 ktls_cleanup_tls_enable(struct tls_enable *tls)
399 zfree(__DECONST(void *, tls->cipher_key), M_KTLS);
400 zfree(__DECONST(void *, tls->iv), M_KTLS);
401 zfree(__DECONST(void *, tls->auth_key), M_KTLS);
405 ktls_get_cpu(struct socket *so)
409 struct ktls_domain_info *di;
415 cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
416 if (cpuid != NETISR_CPUID_NONE)
420 * Just use the flowid to shard connections in a repeatable
421 * fashion. Note that TLS 1.0 sessions rely on the
422 * serialization provided by having the same connection use
426 if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
427 di = &ktls_domains[inp->inp_numa_domain];
428 cpuid = di->cpu[inp->inp_flowid % di->count];
431 cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
436 ktls_buffer_import(void *arg, void **store, int count, int domain, int flags)
441 KASSERT((ktls_maxlen & PAGE_MASK) == 0,
442 ("%s: ktls max length %d is not page size-aligned",
443 __func__, ktls_maxlen));
445 req = VM_ALLOC_WIRED | VM_ALLOC_NODUMP | malloc2vm_flags(flags);
446 for (i = 0; i < count; i++) {
447 m = vm_page_alloc_noobj_contig_domain(domain, req,
448 atop(ktls_maxlen), 0, ~0ul, PAGE_SIZE, 0,
452 store[i] = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
458 ktls_buffer_release(void *arg __unused, void **store, int count)
463 for (i = 0; i < count; i++) {
464 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)store[i]));
465 for (j = 0; j < atop(ktls_maxlen); j++) {
466 (void)vm_page_unwire_noq(m + j);
473 ktls_free_mext_contig(struct mbuf *m)
476 uma_zfree(ktls_buffer_zone, (void *)PHYS_TO_DMAP(m->m_epg_pa[0]));
484 int count, domain, error, i;
486 ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
489 ktls_session_zone = uma_zcreate("ktls_session",
490 sizeof(struct ktls_session),
491 NULL, NULL, NULL, NULL,
494 if (ktls_sw_buffer_cache) {
495 ktls_buffer_zone = uma_zcache_create("ktls_buffers",
496 roundup2(ktls_maxlen, PAGE_SIZE), NULL, NULL, NULL, NULL,
497 ktls_buffer_import, ktls_buffer_release, NULL,
498 UMA_ZONE_FIRSTTOUCH);
502 * Initialize the workqueues to run the TLS work. We create a
503 * work queue for each CPU.
506 STAILQ_INIT(&ktls_wq[i].m_head);
507 STAILQ_INIT(&ktls_wq[i].so_head);
508 mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
509 if (ktls_bind_threads > 1) {
511 domain = pc->pc_domain;
512 count = ktls_domains[domain].count;
513 ktls_domains[domain].cpu[count] = i;
514 ktls_domains[domain].count++;
516 ktls_cpuid_lookup[ktls_number_threads] = i;
517 ktls_number_threads++;
521 * If we somehow have an empty domain, fall back to choosing
522 * among all KTLS threads.
524 if (ktls_bind_threads > 1) {
525 for (i = 0; i < vm_ndomains; i++) {
526 if (ktls_domains[i].count == 0) {
527 ktls_bind_threads = 1;
533 /* Start kthreads for each workqueue. */
535 error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
536 &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
538 printf("Can't add KTLS thread %d error %d\n", i, error);
544 * Start an allocation thread per-domain to perform blocking allocations
545 * of 16k physically contiguous TLS crypto destination buffers.
547 if (ktls_sw_buffer_cache) {
548 for (domain = 0; domain < vm_ndomains; domain++) {
549 if (VM_DOMAIN_EMPTY(domain))
551 if (CPU_EMPTY(&cpuset_domain[domain]))
553 error = kproc_kthread_add(ktls_reclaim_thread,
554 &ktls_domains[domain], &ktls_proc,
555 &ktls_domains[domain].reclaim_td.td,
556 0, 0, "KTLS", "reclaim_%d", domain);
558 printf("Can't add KTLS reclaim thread %d error %d\n",
566 printf("KTLS: Initialized %d threads\n", ktls_number_threads);
571 ktls_start_kthreads(void)
576 state = atomic_load_acq_int(&ktls_init_state);
577 if (__predict_true(state > 0))
582 sx_xlock(&ktls_init_lock);
583 if (ktls_init_state != 0) {
584 sx_xunlock(&ktls_init_lock);
593 atomic_store_rel_int(&ktls_init_state, state);
594 sx_xunlock(&ktls_init_lock);
599 ktls_create_session(struct socket *so, struct tls_enable *en,
600 struct ktls_session **tlsp, int direction)
602 struct ktls_session *tls;
605 /* Only TLS 1.0 - 1.3 are supported. */
606 if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
608 if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
609 en->tls_vminor > TLS_MINOR_VER_THREE)
613 /* No flags are currently supported. */
617 /* Common checks for supported algorithms. */
618 switch (en->cipher_algorithm) {
619 case CRYPTO_AES_NIST_GCM_16:
621 * auth_algorithm isn't used, but permit GMAC values
624 switch (en->auth_algorithm) {
626 #ifdef COMPAT_FREEBSD12
627 /* XXX: Really 13.0-current COMPAT. */
628 case CRYPTO_AES_128_NIST_GMAC:
629 case CRYPTO_AES_192_NIST_GMAC:
630 case CRYPTO_AES_256_NIST_GMAC:
636 if (en->auth_key_len != 0)
638 switch (en->tls_vminor) {
639 case TLS_MINOR_VER_TWO:
640 if (en->iv_len != TLS_AEAD_GCM_LEN)
643 case TLS_MINOR_VER_THREE:
644 if (en->iv_len != TLS_1_3_GCM_IV_LEN)
652 switch (en->auth_algorithm) {
653 case CRYPTO_SHA1_HMAC:
655 case CRYPTO_SHA2_256_HMAC:
656 case CRYPTO_SHA2_384_HMAC:
657 if (en->tls_vminor != TLS_MINOR_VER_TWO)
663 if (en->auth_key_len == 0)
667 * TLS 1.0 requires an implicit IV. TLS 1.1 and 1.2
670 switch (en->tls_vminor) {
671 case TLS_MINOR_VER_ZERO:
672 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
675 case TLS_MINOR_VER_ONE:
676 case TLS_MINOR_VER_TWO:
677 /* Ignore any supplied IV. */
684 case CRYPTO_CHACHA20_POLY1305:
685 if (en->auth_algorithm != 0 || en->auth_key_len != 0)
687 if (en->tls_vminor != TLS_MINOR_VER_TWO &&
688 en->tls_vminor != TLS_MINOR_VER_THREE)
690 if (en->iv_len != TLS_CHACHA20_IV_LEN)
697 error = ktls_start_kthreads();
701 tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
703 counter_u64_add(ktls_offload_active, 1);
705 refcount_init(&tls->refcount, 1);
706 if (direction == KTLS_RX) {
707 TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_receive_tag, tls);
709 TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
710 tls->inp = so->so_pcb;
715 tls->wq_index = ktls_get_cpu(so);
717 tls->params.cipher_algorithm = en->cipher_algorithm;
718 tls->params.auth_algorithm = en->auth_algorithm;
719 tls->params.tls_vmajor = en->tls_vmajor;
720 tls->params.tls_vminor = en->tls_vminor;
721 tls->params.flags = en->flags;
722 tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
724 /* Set the header and trailer lengths. */
725 tls->params.tls_hlen = sizeof(struct tls_record_layer);
726 switch (en->cipher_algorithm) {
727 case CRYPTO_AES_NIST_GCM_16:
729 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
730 * nonce. TLS 1.3 uses a 12 byte implicit IV.
732 if (en->tls_vminor < TLS_MINOR_VER_THREE)
733 tls->params.tls_hlen += sizeof(uint64_t);
734 tls->params.tls_tlen = AES_GMAC_HASH_LEN;
735 tls->params.tls_bs = 1;
738 switch (en->auth_algorithm) {
739 case CRYPTO_SHA1_HMAC:
740 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
741 /* Implicit IV, no nonce. */
742 tls->sequential_records = true;
743 tls->next_seqno = be64dec(en->rec_seq);
744 STAILQ_INIT(&tls->pending_records);
746 tls->params.tls_hlen += AES_BLOCK_LEN;
748 tls->params.tls_tlen = AES_BLOCK_LEN +
751 case CRYPTO_SHA2_256_HMAC:
752 tls->params.tls_hlen += AES_BLOCK_LEN;
753 tls->params.tls_tlen = AES_BLOCK_LEN +
756 case CRYPTO_SHA2_384_HMAC:
757 tls->params.tls_hlen += AES_BLOCK_LEN;
758 tls->params.tls_tlen = AES_BLOCK_LEN +
762 panic("invalid hmac");
764 tls->params.tls_bs = AES_BLOCK_LEN;
766 case CRYPTO_CHACHA20_POLY1305:
768 * Chacha20 uses a 12 byte implicit IV.
770 tls->params.tls_tlen = POLY1305_HASH_LEN;
771 tls->params.tls_bs = 1;
774 panic("invalid cipher");
778 * TLS 1.3 includes optional padding which we do not support,
779 * and also puts the "real" record type at the end of the
782 if (en->tls_vminor == TLS_MINOR_VER_THREE)
783 tls->params.tls_tlen += sizeof(uint8_t);
785 KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
786 ("TLS header length too long: %d", tls->params.tls_hlen));
787 KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
788 ("TLS trailer length too long: %d", tls->params.tls_tlen));
790 if (en->auth_key_len != 0) {
791 tls->params.auth_key_len = en->auth_key_len;
792 tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
794 bcopy(en->auth_key, tls->params.auth_key, en->auth_key_len);
797 tls->params.cipher_key_len = en->cipher_key_len;
798 tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
799 bcopy(en->cipher_key, tls->params.cipher_key, en->cipher_key_len);
802 * This holds the implicit portion of the nonce for AEAD
803 * ciphers and the initial implicit IV for TLS 1.0. The
804 * explicit portions of the IV are generated in ktls_frame().
806 if (en->iv_len != 0) {
807 tls->params.iv_len = en->iv_len;
808 bcopy(en->iv, tls->params.iv, en->iv_len);
811 * For TLS 1.2 with GCM, generate an 8-byte nonce as a
812 * counter to generate unique explicit IVs.
814 * Store this counter in the last 8 bytes of the IV
815 * array so that it is 8-byte aligned.
817 if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
818 en->tls_vminor == TLS_MINOR_VER_TWO)
819 arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
826 static struct ktls_session *
827 ktls_clone_session(struct ktls_session *tls, int direction)
829 struct ktls_session *tls_new;
831 tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
833 counter_u64_add(ktls_offload_active, 1);
835 refcount_init(&tls_new->refcount, 1);
836 if (direction == KTLS_RX) {
837 TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_receive_tag,
840 TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_send_tag,
842 tls_new->inp = tls->inp;
844 in_pcbref(tls_new->inp);
847 /* Copy fields from existing session. */
848 tls_new->params = tls->params;
849 tls_new->wq_index = tls->wq_index;
851 /* Deep copy keys. */
852 if (tls_new->params.auth_key != NULL) {
853 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
855 memcpy(tls_new->params.auth_key, tls->params.auth_key,
856 tls->params.auth_key_len);
859 tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
861 memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
862 tls->params.cipher_key_len);
869 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
877 if (inp->inp_flags & INP_DROPPED) {
881 if (inp->inp_socket == NULL) {
886 if (!(tp->t_flags & TF_TOE)) {
891 error = tcp_offload_alloc_tls_session(tp, tls, direction);
894 tls->mode = TCP_TLS_MODE_TOE;
895 switch (tls->params.cipher_algorithm) {
897 counter_u64_add(ktls_toe_cbc, 1);
899 case CRYPTO_AES_NIST_GCM_16:
900 counter_u64_add(ktls_toe_gcm, 1);
902 case CRYPTO_CHACHA20_POLY1305:
903 counter_u64_add(ktls_toe_chacha20, 1);
912 * Common code used when first enabling ifnet TLS on a connection or
913 * when allocating a new ifnet TLS session due to a routing change.
914 * This function allocates a new TLS send tag on whatever interface
915 * the connection is currently routed over.
918 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
919 struct m_snd_tag **mstp)
921 union if_snd_tag_alloc_params params;
923 struct nhop_object *nh;
928 if (inp->inp_flags & INP_DROPPED) {
932 if (inp->inp_socket == NULL) {
939 * Check administrative controls on ifnet TLS to determine if
940 * ifnet TLS should be denied.
942 * - Always permit 'force' requests.
943 * - ktls_ifnet_permitted == 0: always deny.
945 if (!force && ktls_ifnet_permitted == 0) {
951 * XXX: Use the cached route in the inpcb to find the
952 * interface. This should perhaps instead use
953 * rtalloc1_fib(dst, 0, 0, fibnum). Since KTLS is only
954 * enabled after a connection has completed key negotiation in
955 * userland, the cached route will be present in practice.
957 nh = inp->inp_route.ro_nh;
966 * Allocate a TLS + ratelimit tag if the connection has an
967 * existing pacing rate.
969 if (tp->t_pacing_rate != -1 &&
970 (if_getcapenable(ifp) & IFCAP_TXTLS_RTLMT) != 0) {
971 params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
972 params.tls_rate_limit.inp = inp;
973 params.tls_rate_limit.tls = tls;
974 params.tls_rate_limit.max_rate = tp->t_pacing_rate;
976 params.hdr.type = IF_SND_TAG_TYPE_TLS;
977 params.tls.inp = inp;
978 params.tls.tls = tls;
980 params.hdr.flowid = inp->inp_flowid;
981 params.hdr.flowtype = inp->inp_flowtype;
982 params.hdr.numa_domain = inp->inp_numa_domain;
985 if ((if_getcapenable(ifp) & IFCAP_MEXTPG) == 0) {
989 if (inp->inp_vflag & INP_IPV6) {
990 if ((if_getcapenable(ifp) & IFCAP_TXTLS6) == 0) {
995 if ((if_getcapenable(ifp) & IFCAP_TXTLS4) == 0) {
1000 error = m_snd_tag_alloc(ifp, ¶ms, mstp);
1007 * Allocate an initial TLS receive tag for doing HW decryption of TLS
1010 * This function allocates a new TLS receive tag on whatever interface
1011 * the connection is currently routed over. If the connection ends up
1012 * using a different interface for receive this will get fixed up via
1013 * ktls_input_ifp_mismatch as future packets arrive.
1016 ktls_alloc_rcv_tag(struct inpcb *inp, struct ktls_session *tls,
1017 struct m_snd_tag **mstp)
1019 union if_snd_tag_alloc_params params;
1021 struct nhop_object *nh;
1024 if (!ktls_ocf_recrypt_supported(tls))
1028 if (inp->inp_flags & INP_DROPPED) {
1030 return (ECONNRESET);
1032 if (inp->inp_socket == NULL) {
1034 return (ECONNRESET);
1038 * Check administrative controls on ifnet TLS to determine if
1039 * ifnet TLS should be denied.
1041 if (ktls_ifnet_permitted == 0) {
1047 * XXX: As with ktls_alloc_snd_tag, use the cached route in
1048 * the inpcb to find the interface.
1050 nh = inp->inp_route.ro_nh;
1059 params.hdr.type = IF_SND_TAG_TYPE_TLS_RX;
1060 params.hdr.flowid = inp->inp_flowid;
1061 params.hdr.flowtype = inp->inp_flowtype;
1062 params.hdr.numa_domain = inp->inp_numa_domain;
1063 params.tls_rx.inp = inp;
1064 params.tls_rx.tls = tls;
1065 params.tls_rx.vlan_id = 0;
1069 if (inp->inp_vflag & INP_IPV6) {
1070 if ((if_getcapenable2(ifp) & IFCAP2_BIT(IFCAP2_RXTLS6)) == 0) {
1075 if ((if_getcapenable2(ifp) & IFCAP2_BIT(IFCAP2_RXTLS4)) == 0) {
1080 error = m_snd_tag_alloc(ifp, ¶ms, mstp);
1083 * If this connection is over a vlan, vlan_snd_tag_alloc
1084 * rewrites vlan_id with the saved interface. Save the VLAN
1085 * ID for use in ktls_reset_receive_tag which allocates new
1086 * receive tags directly from the leaf interface bypassing
1090 tls->rx_vlan_id = params.tls_rx.vlan_id;
1096 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, int direction,
1099 struct m_snd_tag *mst;
1102 switch (direction) {
1104 error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
1105 if (__predict_false(error != 0))
1109 KASSERT(!force, ("%s: forced receive tag", __func__));
1110 error = ktls_alloc_rcv_tag(so->so_pcb, tls, &mst);
1111 if (__predict_false(error != 0))
1115 __assert_unreachable();
1118 tls->mode = TCP_TLS_MODE_IFNET;
1121 switch (tls->params.cipher_algorithm) {
1122 case CRYPTO_AES_CBC:
1123 counter_u64_add(ktls_ifnet_cbc, 1);
1125 case CRYPTO_AES_NIST_GCM_16:
1126 counter_u64_add(ktls_ifnet_gcm, 1);
1128 case CRYPTO_CHACHA20_POLY1305:
1129 counter_u64_add(ktls_ifnet_chacha20, 1);
1139 ktls_use_sw(struct ktls_session *tls)
1141 tls->mode = TCP_TLS_MODE_SW;
1142 switch (tls->params.cipher_algorithm) {
1143 case CRYPTO_AES_CBC:
1144 counter_u64_add(ktls_sw_cbc, 1);
1146 case CRYPTO_AES_NIST_GCM_16:
1147 counter_u64_add(ktls_sw_gcm, 1);
1149 case CRYPTO_CHACHA20_POLY1305:
1150 counter_u64_add(ktls_sw_chacha20, 1);
1156 ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
1160 error = ktls_ocf_try(so, tls, direction);
1168 * KTLS RX stores data in the socket buffer as a list of TLS records,
1169 * where each record is stored as a control message containg the TLS
1170 * header followed by data mbufs containing the decrypted data. This
1171 * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
1172 * both encrypted and decrypted data. TLS records decrypted by a NIC
1173 * should be queued to the socket buffer as records, but encrypted
1174 * data which needs to be decrypted by software arrives as a stream of
1175 * regular mbufs which need to be converted. In addition, there may
1176 * already be pending encrypted data in the socket buffer when KTLS RX
1179 * To manage not-yet-decrypted data for KTLS RX, the following scheme
1182 * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
1184 * - ktls_check_rx checks this chain of mbufs reading the TLS header
1185 * from the first mbuf. Once all of the data for that TLS record is
1186 * queued, the socket is queued to a worker thread.
1188 * - The worker thread calls ktls_decrypt to decrypt TLS records in
1189 * the TLS chain. Each TLS record is detached from the TLS chain,
1190 * decrypted, and inserted into the regular socket buffer chain as
1191 * record starting with a control message holding the TLS header and
1192 * a chain of mbufs holding the encrypted data.
1196 sb_mark_notready(struct sockbuf *sb)
1203 sb->sb_mbtail = NULL;
1204 sb->sb_lastrecord = NULL;
1205 for (; m != NULL; m = m->m_next) {
1206 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
1208 KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
1210 KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
1212 m->m_flags |= M_NOTREADY;
1213 sb->sb_acc -= m->m_len;
1214 sb->sb_tlscc += m->m_len;
1215 sb->sb_mtlstail = m;
1217 KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
1218 ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
1223 * Return information about the pending TLS data in a socket
1224 * buffer. On return, 'seqno' is set to the sequence number
1225 * of the next TLS record to be received, 'resid' is set to
1226 * the amount of bytes still needed for the last pending
1227 * record. The function returns 'false' if the last pending
1228 * record contains a partial TLS header. In that case, 'resid'
1229 * is the number of bytes needed to complete the TLS header.
1232 ktls_pending_rx_info(struct sockbuf *sb, uint64_t *seqnop, size_t *residp)
1234 struct tls_record_layer hdr;
1238 u_int offset, record_len;
1240 SOCKBUF_LOCK_ASSERT(sb);
1241 MPASS(sb->sb_flags & SB_TLS_RX);
1242 seqno = sb->sb_tls_seqno;
1243 resid = sb->sb_tlscc;
1256 if (resid < sizeof(hdr)) {
1258 *residp = sizeof(hdr) - resid;
1262 m_copydata(m, offset, sizeof(hdr), (void *)&hdr);
1264 record_len = sizeof(hdr) + ntohs(hdr.tls_length);
1265 if (resid <= record_len) {
1267 *residp = record_len - resid;
1270 resid -= record_len;
1272 while (record_len != 0) {
1273 if (m->m_len - offset > record_len) {
1274 offset += record_len;
1278 record_len -= (m->m_len - offset);
1286 ktls_enable_rx(struct socket *so, struct tls_enable *en)
1288 struct ktls_session *tls;
1291 if (!ktls_offload_enable)
1294 counter_u64_add(ktls_offload_enable_calls, 1);
1297 * This should always be true since only the TCP socket option
1298 * invokes this function.
1300 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1304 * XXX: Don't overwrite existing sessions. We should permit
1305 * this to support rekeying in the future.
1307 if (so->so_rcv.sb_tls_info != NULL)
1310 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1313 error = ktls_create_session(so, en, &tls, KTLS_RX);
1317 error = ktls_ocf_try(so, tls, KTLS_RX);
1323 /* Mark the socket as using TLS offload. */
1324 SOCK_RECVBUF_LOCK(so);
1325 if (SOLISTENING(so)) {
1326 SOCK_RECVBUF_UNLOCK(so);
1330 so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1331 so->so_rcv.sb_tls_info = tls;
1332 so->so_rcv.sb_flags |= SB_TLS_RX;
1334 /* Mark existing data as not ready until it can be decrypted. */
1335 sb_mark_notready(&so->so_rcv);
1336 ktls_check_rx(&so->so_rcv);
1337 SOCK_RECVBUF_UNLOCK(so);
1339 /* Prefer TOE -> ifnet TLS -> software TLS. */
1341 error = ktls_try_toe(so, tls, KTLS_RX);
1344 error = ktls_try_ifnet(so, tls, KTLS_RX, false);
1348 counter_u64_add(ktls_offload_total, 1);
1354 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1356 struct ktls_session *tls;
1361 if (!ktls_offload_enable)
1364 counter_u64_add(ktls_offload_enable_calls, 1);
1367 * This should always be true since only the TCP socket option
1368 * invokes this function.
1370 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1374 * XXX: Don't overwrite existing sessions. We should permit
1375 * this to support rekeying in the future.
1377 if (so->so_snd.sb_tls_info != NULL)
1380 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1383 /* TLS requires ext pgs */
1384 if (mb_use_ext_pgs == 0)
1387 error = ktls_create_session(so, en, &tls, KTLS_TX);
1391 /* Prefer TOE -> ifnet TLS -> software TLS. */
1393 error = ktls_try_toe(so, tls, KTLS_TX);
1396 error = ktls_try_ifnet(so, tls, KTLS_TX, false);
1398 error = ktls_try_sw(so, tls, KTLS_TX);
1406 * Serialize with sosend_generic() and make sure that we're not
1407 * operating on a listening socket.
1409 error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1416 * Write lock the INP when setting sb_tls_info so that
1417 * routines in tcp_ratelimit.c can read sb_tls_info while
1418 * holding the INP lock.
1422 SOCK_SENDBUF_LOCK(so);
1423 so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1424 so->so_snd.sb_tls_info = tls;
1425 if (tls->mode != TCP_TLS_MODE_SW) {
1426 tp = intotcpcb(inp);
1427 MPASS(tp->t_nic_ktls_xmit == 0);
1428 tp->t_nic_ktls_xmit = 1;
1429 if (tp->t_fb->tfb_hwtls_change != NULL)
1430 (*tp->t_fb->tfb_hwtls_change)(tp, 1);
1432 SOCK_SENDBUF_UNLOCK(so);
1434 SOCK_IO_SEND_UNLOCK(so);
1436 counter_u64_add(ktls_offload_total, 1);
1442 ktls_get_rx_mode(struct socket *so, int *modep)
1444 struct ktls_session *tls;
1445 struct inpcb *inp __diagused;
1447 if (SOLISTENING(so))
1450 INP_WLOCK_ASSERT(inp);
1451 SOCK_RECVBUF_LOCK(so);
1452 tls = so->so_rcv.sb_tls_info;
1454 *modep = TCP_TLS_MODE_NONE;
1457 SOCK_RECVBUF_UNLOCK(so);
1462 * ktls_get_rx_sequence - get the next TCP- and TLS- sequence number.
1464 * This function gets information about the next TCP- and TLS-
1465 * sequence number to be processed by the TLS receive worker
1466 * thread. The information is extracted from the given "inpcb"
1467 * structure. The values are stored in host endian format at the two
1468 * given output pointer locations. The TCP sequence number points to
1469 * the beginning of the TLS header.
1471 * This function returns zero on success, else a non-zero error code
1475 ktls_get_rx_sequence(struct inpcb *inp, uint32_t *tcpseq, uint64_t *tlsseq)
1481 so = inp->inp_socket;
1482 if (__predict_false(so == NULL)) {
1486 if (inp->inp_flags & INP_DROPPED) {
1488 return (ECONNRESET);
1491 tp = intotcpcb(inp);
1494 SOCKBUF_LOCK(&so->so_rcv);
1495 *tcpseq = tp->rcv_nxt - so->so_rcv.sb_tlscc;
1496 *tlsseq = so->so_rcv.sb_tls_seqno;
1497 SOCKBUF_UNLOCK(&so->so_rcv);
1505 ktls_get_tx_mode(struct socket *so, int *modep)
1507 struct ktls_session *tls;
1508 struct inpcb *inp __diagused;
1510 if (SOLISTENING(so))
1513 INP_WLOCK_ASSERT(inp);
1514 SOCK_SENDBUF_LOCK(so);
1515 tls = so->so_snd.sb_tls_info;
1517 *modep = TCP_TLS_MODE_NONE;
1520 SOCK_SENDBUF_UNLOCK(so);
1525 * Switch between SW and ifnet TLS sessions as requested.
1528 ktls_set_tx_mode(struct socket *so, int mode)
1530 struct ktls_session *tls, *tls_new;
1535 if (SOLISTENING(so))
1538 case TCP_TLS_MODE_SW:
1539 case TCP_TLS_MODE_IFNET:
1546 INP_WLOCK_ASSERT(inp);
1547 tp = intotcpcb(inp);
1549 if (mode == TCP_TLS_MODE_IFNET) {
1550 /* Don't allow enabling ifnet ktls multiple times */
1551 if (tp->t_nic_ktls_xmit)
1555 * Don't enable ifnet ktls if we disabled it due to an
1556 * excessive retransmission rate
1558 if (tp->t_nic_ktls_xmit_dis)
1562 SOCKBUF_LOCK(&so->so_snd);
1563 tls = so->so_snd.sb_tls_info;
1565 SOCKBUF_UNLOCK(&so->so_snd);
1569 if (tls->mode == mode) {
1570 SOCKBUF_UNLOCK(&so->so_snd);
1574 tls = ktls_hold(tls);
1575 SOCKBUF_UNLOCK(&so->so_snd);
1578 tls_new = ktls_clone_session(tls, KTLS_TX);
1580 if (mode == TCP_TLS_MODE_IFNET)
1581 error = ktls_try_ifnet(so, tls_new, KTLS_TX, true);
1583 error = ktls_try_sw(so, tls_new, KTLS_TX);
1585 counter_u64_add(ktls_switch_failed, 1);
1592 error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1594 counter_u64_add(ktls_switch_failed, 1);
1602 * If we raced with another session change, keep the existing
1605 if (tls != so->so_snd.sb_tls_info) {
1606 counter_u64_add(ktls_switch_failed, 1);
1607 SOCK_IO_SEND_UNLOCK(so);
1615 SOCKBUF_LOCK(&so->so_snd);
1616 so->so_snd.sb_tls_info = tls_new;
1617 if (tls_new->mode != TCP_TLS_MODE_SW) {
1618 MPASS(tp->t_nic_ktls_xmit == 0);
1619 tp->t_nic_ktls_xmit = 1;
1620 if (tp->t_fb->tfb_hwtls_change != NULL)
1621 (*tp->t_fb->tfb_hwtls_change)(tp, 1);
1623 SOCKBUF_UNLOCK(&so->so_snd);
1624 SOCK_IO_SEND_UNLOCK(so);
1627 * Drop two references on 'tls'. The first is for the
1628 * ktls_hold() above. The second drops the reference from the
1631 KASSERT(tls->refcount >= 2, ("too few references on old session"));
1635 if (mode == TCP_TLS_MODE_IFNET)
1636 counter_u64_add(ktls_switch_to_ifnet, 1);
1638 counter_u64_add(ktls_switch_to_sw, 1);
1644 * Try to allocate a new TLS receive tag. This task is scheduled when
1645 * sbappend_ktls_rx detects an input path change. If a new tag is
1646 * allocated, replace the tag in the TLS session. If a new tag cannot
1647 * be allocated, let the session fall back to software decryption.
1650 ktls_reset_receive_tag(void *context, int pending)
1652 union if_snd_tag_alloc_params params;
1653 struct ktls_session *tls;
1654 struct m_snd_tag *mst;
1660 MPASS(pending == 1);
1668 if (inp->inp_flags & INP_DROPPED) {
1673 SOCKBUF_LOCK(&so->so_rcv);
1675 tls->snd_tag = NULL;
1677 m_snd_tag_rele(mst);
1681 SOCKBUF_UNLOCK(&so->so_rcv);
1683 params.hdr.type = IF_SND_TAG_TYPE_TLS_RX;
1684 params.hdr.flowid = inp->inp_flowid;
1685 params.hdr.flowtype = inp->inp_flowtype;
1686 params.hdr.numa_domain = inp->inp_numa_domain;
1687 params.tls_rx.inp = inp;
1688 params.tls_rx.tls = tls;
1689 params.tls_rx.vlan_id = tls->rx_vlan_id;
1692 if (inp->inp_vflag & INP_IPV6) {
1693 if ((if_getcapenable2(ifp) & IFCAP2_RXTLS6) == 0)
1696 if ((if_getcapenable2(ifp) & IFCAP2_RXTLS4) == 0)
1700 error = m_snd_tag_alloc(ifp, ¶ms, &mst);
1702 SOCKBUF_LOCK(&so->so_rcv);
1704 SOCKBUF_UNLOCK(&so->so_rcv);
1706 counter_u64_add(ktls_ifnet_reset, 1);
1709 * Just fall back to software decryption if a tag
1710 * cannot be allocated leaving the connection intact.
1711 * If a future input path change switches to another
1712 * interface this connection will resume ifnet TLS.
1714 counter_u64_add(ktls_ifnet_reset_failed, 1);
1718 mtx_pool_lock(mtxpool_sleep, tls);
1719 tls->reset_pending = false;
1720 mtx_pool_unlock(mtxpool_sleep, tls);
1724 CURVNET_SET(so->so_vnet);
1731 * Try to allocate a new TLS send tag. This task is scheduled when
1732 * ip_output detects a route change while trying to transmit a packet
1733 * holding a TLS record. If a new tag is allocated, replace the tag
1734 * in the TLS session. Subsequent packets on the connection will use
1735 * the new tag. If a new tag cannot be allocated, drop the
1739 ktls_reset_send_tag(void *context, int pending)
1741 struct epoch_tracker et;
1742 struct ktls_session *tls;
1743 struct m_snd_tag *old, *new;
1748 MPASS(pending == 1);
1754 * Free the old tag first before allocating a new one.
1755 * ip[6]_output_send() will treat a NULL send tag the same as
1756 * an ifp mismatch and drop packets until a new tag is
1759 * Write-lock the INP when changing tls->snd_tag since
1760 * ip[6]_output_send() holds a read-lock when reading the
1765 tls->snd_tag = NULL;
1768 m_snd_tag_rele(old);
1770 error = ktls_alloc_snd_tag(inp, tls, true, &new);
1775 mtx_pool_lock(mtxpool_sleep, tls);
1776 tls->reset_pending = false;
1777 mtx_pool_unlock(mtxpool_sleep, tls);
1780 counter_u64_add(ktls_ifnet_reset, 1);
1783 * XXX: Should we kick tcp_output explicitly now that
1784 * the send tag is fixed or just rely on timers?
1787 NET_EPOCH_ENTER(et);
1789 if (!(inp->inp_flags & INP_DROPPED)) {
1790 tp = intotcpcb(inp);
1791 CURVNET_SET(inp->inp_vnet);
1792 tp = tcp_drop(tp, ECONNABORTED);
1795 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1802 counter_u64_add(ktls_ifnet_reset_failed, 1);
1805 * Leave reset_pending true to avoid future tasks while
1806 * the socket goes away.
1814 ktls_input_ifp_mismatch(struct sockbuf *sb, struct ifnet *ifp)
1816 struct ktls_session *tls;
1819 SOCKBUF_LOCK_ASSERT(sb);
1820 KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1822 so = __containerof(sb, struct socket, so_rcv);
1824 tls = sb->sb_tls_info;
1825 if_rele(tls->rx_ifp);
1830 * See if we should schedule a task to update the receive tag for
1833 mtx_pool_lock(mtxpool_sleep, tls);
1834 if (!tls->reset_pending) {
1835 (void) ktls_hold(tls);
1838 tls->reset_pending = true;
1839 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1841 mtx_pool_unlock(mtxpool_sleep, tls);
1845 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1851 INP_LOCK_ASSERT(inp);
1854 * See if we should schedule a task to update the send tag for
1857 mtx_pool_lock(mtxpool_sleep, tls);
1858 if (!tls->reset_pending) {
1859 (void) ktls_hold(tls);
1860 tls->reset_pending = true;
1861 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1863 mtx_pool_unlock(mtxpool_sleep, tls);
1869 ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1871 union if_snd_tag_modify_params params = {
1872 .rate_limit.max_rate = max_pacing_rate,
1873 .rate_limit.flags = M_NOWAIT,
1875 struct m_snd_tag *mst;
1877 /* Can't get to the inp, but it should be locked. */
1878 /* INP_LOCK_ASSERT(inp); */
1880 MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1882 if (tls->snd_tag == NULL) {
1884 * Resetting send tag, ignore this change. The
1885 * pending reset may or may not see this updated rate
1886 * in the tcpcb. If it doesn't, we will just lose
1895 MPASS(mst->sw->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1897 return (mst->sw->snd_tag_modify(mst, ¶ms));
1902 ktls_destroy_help(void *context, int pending __unused)
1904 ktls_destroy(context);
1908 ktls_destroy(struct ktls_session *tls)
1914 MPASS(tls->refcount == 0);
1918 wlocked = INP_WLOCKED(inp);
1919 if (!wlocked && !INP_TRY_WLOCK(inp)) {
1921 * rwlocks read locks are anonymous, and there
1922 * is no way to know if our current thread
1923 * holds an rlock on the inp. As a rough
1924 * estimate, check to see if the thread holds
1925 * *any* rlocks at all. If it does not, then we
1926 * know that we don't hold the inp rlock, and
1927 * can safely take the wlock
1929 if (curthread->td_rw_rlocks == 0) {
1933 * We might hold the rlock, so let's
1934 * do the destroy in a taskqueue
1935 * context to avoid a potential
1936 * deadlock. This should be very
1939 counter_u64_add(ktls_destroy_task, 1);
1940 TASK_INIT(&tls->destroy_task, 0,
1941 ktls_destroy_help, tls);
1942 (void)taskqueue_enqueue(taskqueue_thread,
1943 &tls->destroy_task);
1949 if (tls->sequential_records) {
1953 STAILQ_FOREACH_SAFE(m, &tls->pending_records, m_epg_stailq, n) {
1954 page_count = m->m_epg_enc_cnt;
1955 while (page_count > 0) {
1956 KASSERT(page_count >= m->m_epg_nrdy,
1957 ("%s: too few pages", __func__));
1958 page_count -= m->m_epg_nrdy;
1964 counter_u64_add(ktls_offload_active, -1);
1965 switch (tls->mode) {
1966 case TCP_TLS_MODE_SW:
1967 switch (tls->params.cipher_algorithm) {
1968 case CRYPTO_AES_CBC:
1969 counter_u64_add(ktls_sw_cbc, -1);
1971 case CRYPTO_AES_NIST_GCM_16:
1972 counter_u64_add(ktls_sw_gcm, -1);
1974 case CRYPTO_CHACHA20_POLY1305:
1975 counter_u64_add(ktls_sw_chacha20, -1);
1979 case TCP_TLS_MODE_IFNET:
1980 switch (tls->params.cipher_algorithm) {
1981 case CRYPTO_AES_CBC:
1982 counter_u64_add(ktls_ifnet_cbc, -1);
1984 case CRYPTO_AES_NIST_GCM_16:
1985 counter_u64_add(ktls_ifnet_gcm, -1);
1987 case CRYPTO_CHACHA20_POLY1305:
1988 counter_u64_add(ktls_ifnet_chacha20, -1);
1991 if (tls->snd_tag != NULL)
1992 m_snd_tag_rele(tls->snd_tag);
1993 if (tls->rx_ifp != NULL)
1994 if_rele(tls->rx_ifp);
1996 INP_WLOCK_ASSERT(inp);
1997 tp = intotcpcb(inp);
1998 MPASS(tp->t_nic_ktls_xmit == 1);
1999 tp->t_nic_ktls_xmit = 0;
2003 case TCP_TLS_MODE_TOE:
2004 switch (tls->params.cipher_algorithm) {
2005 case CRYPTO_AES_CBC:
2006 counter_u64_add(ktls_toe_cbc, -1);
2008 case CRYPTO_AES_NIST_GCM_16:
2009 counter_u64_add(ktls_toe_gcm, -1);
2011 case CRYPTO_CHACHA20_POLY1305:
2012 counter_u64_add(ktls_toe_chacha20, -1);
2018 if (tls->ocf_session != NULL)
2020 if (tls->params.auth_key != NULL) {
2021 zfree(tls->params.auth_key, M_KTLS);
2022 tls->params.auth_key = NULL;
2023 tls->params.auth_key_len = 0;
2025 if (tls->params.cipher_key != NULL) {
2026 zfree(tls->params.cipher_key, M_KTLS);
2027 tls->params.cipher_key = NULL;
2028 tls->params.cipher_key_len = 0;
2031 INP_WLOCK_ASSERT(inp);
2032 if (!in_pcbrele_wlocked(inp) && !wlocked)
2035 explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
2037 uma_zfree(ktls_session_zone, tls);
2041 ktls_seq(struct sockbuf *sb, struct mbuf *m)
2044 for (; m != NULL; m = m->m_next) {
2045 KASSERT((m->m_flags & M_EXTPG) != 0,
2046 ("ktls_seq: mapped mbuf %p", m));
2048 m->m_epg_seqno = sb->sb_tls_seqno;
2054 * Add TLS framing (headers and trailers) to a chain of mbufs. Each
2055 * mbuf in the chain must be an unmapped mbuf. The payload of the
2056 * mbuf must be populated with the payload of each TLS record.
2058 * The record_type argument specifies the TLS record type used when
2059 * populating the TLS header.
2061 * The enq_count argument on return is set to the number of pages of
2062 * payload data for this entire chain that need to be encrypted via SW
2063 * encryption. The returned value should be passed to ktls_enqueue
2064 * when scheduling encryption of this chain of mbufs. To handle the
2065 * special case of empty fragments for TLS 1.0 sessions, an empty
2066 * fragment counts as one page.
2069 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
2070 uint8_t record_type)
2072 struct tls_record_layer *tlshdr;
2076 int maxlen __diagused;
2078 maxlen = tls->params.max_frame_len;
2080 for (m = top; m != NULL; m = m->m_next) {
2082 * All mbufs in the chain should be TLS records whose
2083 * payload does not exceed the maximum frame length.
2085 * Empty TLS 1.0 records are permitted when using CBC.
2087 KASSERT(m->m_len <= maxlen && m->m_len >= 0 &&
2088 (m->m_len > 0 || ktls_permit_empty_frames(tls)),
2089 ("ktls_frame: m %p len %d", m, m->m_len));
2092 * TLS frames require unmapped mbufs to store session
2095 KASSERT((m->m_flags & M_EXTPG) != 0,
2096 ("ktls_frame: mapped mbuf %p (top = %p)", m, top));
2100 /* Save a reference to the session. */
2101 m->m_epg_tls = ktls_hold(tls);
2103 m->m_epg_hdrlen = tls->params.tls_hlen;
2104 m->m_epg_trllen = tls->params.tls_tlen;
2105 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
2109 * AES-CBC pads messages to a multiple of the
2110 * block size. Note that the padding is
2111 * applied after the digest and the encryption
2112 * is done on the "plaintext || mac || padding".
2113 * At least one byte of padding is always
2116 * Compute the final trailer length assuming
2117 * at most one block of padding.
2118 * tls->params.tls_tlen is the maximum
2119 * possible trailer length (padding + digest).
2120 * delta holds the number of excess padding
2121 * bytes if the maximum were used. Those
2122 * extra bytes are removed.
2124 bs = tls->params.tls_bs;
2125 delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
2126 m->m_epg_trllen -= delta;
2128 m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
2130 /* Populate the TLS header. */
2131 tlshdr = (void *)m->m_epg_hdr;
2132 tlshdr->tls_vmajor = tls->params.tls_vmajor;
2135 * TLS 1.3 masquarades as TLS 1.2 with a record type
2136 * of TLS_RLTYPE_APP.
2138 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
2139 tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
2140 tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
2141 tlshdr->tls_type = TLS_RLTYPE_APP;
2142 /* save the real record type for later */
2143 m->m_epg_record_type = record_type;
2144 m->m_epg_trail[0] = record_type;
2146 tlshdr->tls_vminor = tls->params.tls_vminor;
2147 tlshdr->tls_type = record_type;
2149 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
2152 * Store nonces / explicit IVs after the end of the
2155 * For GCM with TLS 1.2, an 8 byte nonce is copied
2156 * from the end of the IV. The nonce is then
2157 * incremented for use by the next record.
2159 * For CBC, a random nonce is inserted for TLS 1.1+.
2161 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
2162 tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
2163 noncep = (uint64_t *)(tls->params.iv + 8);
2164 be64enc(tlshdr + 1, *noncep);
2166 } else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
2167 tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
2168 arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
2171 * When using SW encryption, mark the mbuf not ready.
2172 * It will be marked ready via sbready() after the
2173 * record has been encrypted.
2175 * When using ifnet TLS, unencrypted TLS records are
2176 * sent down the stack to the NIC.
2178 if (tls->mode == TCP_TLS_MODE_SW) {
2179 m->m_flags |= M_NOTREADY;
2180 if (__predict_false(tls_len == 0)) {
2181 /* TLS 1.0 empty fragment. */
2184 m->m_epg_nrdy = m->m_epg_npgs;
2185 *enq_cnt += m->m_epg_nrdy;
2191 ktls_permit_empty_frames(struct ktls_session *tls)
2193 return (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
2194 tls->params.tls_vminor == TLS_MINOR_VER_ZERO);
2198 ktls_check_rx(struct sockbuf *sb)
2200 struct tls_record_layer hdr;
2205 SOCKBUF_LOCK_ASSERT(sb);
2206 KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
2208 so = __containerof(sb, struct socket, so_rcv);
2210 if (sb->sb_flags & SB_TLS_RX_RUNNING)
2213 /* Is there enough queued for a TLS header? */
2214 if (sb->sb_tlscc < sizeof(hdr)) {
2215 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
2216 so->so_error = EMSGSIZE;
2220 m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
2222 /* Is the entire record queued? */
2223 if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
2224 if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
2225 so->so_error = EMSGSIZE;
2229 sb->sb_flags |= SB_TLS_RX_RUNNING;
2232 wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
2234 STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
2235 running = wq->running;
2236 mtx_unlock(&wq->mtx);
2239 counter_u64_add(ktls_cnt_rx_queued, 1);
2242 static struct mbuf *
2243 ktls_detach_record(struct sockbuf *sb, int len)
2245 struct mbuf *m, *n, *top;
2248 SOCKBUF_LOCK_ASSERT(sb);
2249 MPASS(len <= sb->sb_tlscc);
2252 * If TLS chain is the exact size of the record,
2253 * just grab the whole record.
2256 if (sb->sb_tlscc == len) {
2258 sb->sb_mtlstail = NULL;
2263 * While it would be nice to use m_split() here, we need
2264 * to know exactly what m_split() allocates to update the
2265 * accounting, so do it inline instead.
2268 for (m = top; remain > m->m_len; m = m->m_next)
2271 /* Easy case: don't have to split 'm'. */
2272 if (remain == m->m_len) {
2273 sb->sb_mtls = m->m_next;
2274 if (sb->sb_mtls == NULL)
2275 sb->sb_mtlstail = NULL;
2281 * Need to allocate an mbuf to hold the remainder of 'm'. Try
2282 * with M_NOWAIT first.
2284 n = m_get(M_NOWAIT, MT_DATA);
2287 * Use M_WAITOK with socket buffer unlocked. If
2288 * 'sb_mtls' changes while the lock is dropped, return
2289 * NULL to force the caller to retry.
2293 n = m_get(M_WAITOK, MT_DATA);
2296 if (sb->sb_mtls != top) {
2301 n->m_flags |= (m->m_flags & (M_NOTREADY | M_DECRYPTED));
2303 /* Store remainder in 'n'. */
2304 n->m_len = m->m_len - remain;
2305 if (m->m_flags & M_EXT) {
2306 n->m_data = m->m_data + remain;
2309 bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
2312 /* Trim 'm' and update accounting. */
2313 m->m_len -= n->m_len;
2314 sb->sb_tlscc -= n->m_len;
2315 sb->sb_ccc -= n->m_len;
2317 /* Account for 'n'. */
2318 sballoc_ktls_rx(sb, n);
2320 /* Insert 'n' into the TLS chain. */
2322 n->m_next = m->m_next;
2323 if (sb->sb_mtlstail == m)
2324 sb->sb_mtlstail = n;
2326 /* Detach the record from the TLS chain. */
2330 MPASS(m_length(top, NULL) == len);
2331 for (m = top; m != NULL; m = m->m_next)
2332 sbfree_ktls_rx(sb, m);
2333 sb->sb_tlsdcc = len;
2340 * Determine the length of the trailing zero padding and find the real
2341 * record type in the byte before the padding.
2343 * Walking the mbuf chain backwards is clumsy, so another option would
2344 * be to scan forwards remembering the last non-zero byte before the
2345 * trailer. However, it would be expensive to scan the entire record.
2346 * Instead, find the last non-zero byte of each mbuf in the chain
2347 * keeping track of the relative offset of that nonzero byte.
2349 * trail_len is the size of the MAC/tag on input and is set to the
2350 * size of the full trailer including padding and the record type on
2354 tls13_find_record_type(struct ktls_session *tls, struct mbuf *m, int tls_len,
2355 int *trailer_len, uint8_t *record_typep)
2358 u_int digest_start, last_offset, m_len, offset;
2359 uint8_t record_type;
2361 digest_start = tls_len - *trailer_len;
2364 for (; m != NULL && offset < digest_start;
2365 offset += m->m_len, m = m->m_next) {
2366 /* Don't look for padding in the tag. */
2367 m_len = min(digest_start - offset, m->m_len);
2368 cp = mtod(m, char *);
2370 /* Find last non-zero byte in this mbuf. */
2371 while (m_len > 0 && cp[m_len - 1] == 0)
2374 record_type = cp[m_len - 1];
2375 last_offset = offset + m_len;
2378 if (last_offset < tls->params.tls_hlen)
2381 *record_typep = record_type;
2382 *trailer_len = tls_len - last_offset + 1;
2387 * Check if a mbuf chain is fully decrypted at the given offset and
2388 * length. Returns KTLS_MBUF_CRYPTO_ST_DECRYPTED if all data is
2389 * decrypted. KTLS_MBUF_CRYPTO_ST_MIXED if there is a mix of encrypted
2390 * and decrypted data. Else KTLS_MBUF_CRYPTO_ST_ENCRYPTED if all data
2393 ktls_mbuf_crypto_st_t
2394 ktls_mbuf_crypto_state(struct mbuf *mb, int offset, int len)
2396 int m_flags_ored = 0;
2397 int m_flags_anded = -1;
2399 for (; mb != NULL; mb = mb->m_next) {
2400 if (offset < mb->m_len)
2402 offset -= mb->m_len;
2406 for (; mb != NULL; mb = mb->m_next) {
2407 m_flags_ored |= mb->m_flags;
2408 m_flags_anded &= mb->m_flags;
2410 if (offset <= mb->m_len)
2412 offset -= mb->m_len;
2414 MPASS(mb != NULL || offset == 0);
2416 if ((m_flags_ored ^ m_flags_anded) & M_DECRYPTED)
2417 return (KTLS_MBUF_CRYPTO_ST_MIXED);
2419 return ((m_flags_ored & M_DECRYPTED) ?
2420 KTLS_MBUF_CRYPTO_ST_DECRYPTED :
2421 KTLS_MBUF_CRYPTO_ST_ENCRYPTED);
2425 * ktls_resync_ifnet - get HW TLS RX back on track after packet loss
2428 ktls_resync_ifnet(struct socket *so, uint32_t tls_len, uint64_t tls_rcd_num)
2430 union if_snd_tag_modify_params params;
2431 struct m_snd_tag *mst;
2435 mst = so->so_rcv.sb_tls_info->snd_tag;
2436 if (__predict_false(mst == NULL))
2439 inp = sotoinpcb(so);
2440 if (__predict_false(inp == NULL))
2444 if (inp->inp_flags & INP_DROPPED) {
2446 return (ECONNRESET);
2449 tp = intotcpcb(inp);
2452 /* Get the TCP sequence number of the next valid TLS header. */
2453 SOCKBUF_LOCK(&so->so_rcv);
2454 params.tls_rx.tls_hdr_tcp_sn =
2455 tp->rcv_nxt - so->so_rcv.sb_tlscc - tls_len;
2456 params.tls_rx.tls_rec_length = tls_len;
2457 params.tls_rx.tls_seq_number = tls_rcd_num;
2458 SOCKBUF_UNLOCK(&so->so_rcv);
2462 MPASS(mst->sw->type == IF_SND_TAG_TYPE_TLS_RX);
2463 return (mst->sw->snd_tag_modify(mst, ¶ms));
2467 ktls_drop(struct socket *so, int error)
2469 struct epoch_tracker et;
2470 struct inpcb *inp = sotoinpcb(so);
2473 NET_EPOCH_ENTER(et);
2475 if (!(inp->inp_flags & INP_DROPPED)) {
2476 tp = intotcpcb(inp);
2477 CURVNET_SET(inp->inp_vnet);
2478 tp = tcp_drop(tp, error);
2483 so->so_error = error;
2484 SOCK_RECVBUF_LOCK(so);
2485 sorwakeup_locked(so);
2492 ktls_decrypt(struct socket *so)
2494 char tls_header[MBUF_PEXT_HDR_LEN];
2495 struct ktls_session *tls;
2497 struct tls_record_layer *hdr;
2498 struct tls_get_record tgr;
2499 struct mbuf *control, *data, *m;
2500 ktls_mbuf_crypto_st_t state;
2502 int error, remain, tls_len, trail_len;
2504 uint8_t vminor, record_type;
2506 hdr = (struct tls_record_layer *)tls_header;
2509 KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
2510 ("%s: socket %p not running", __func__, so));
2512 tls = sb->sb_tls_info;
2515 tls13 = (tls->params.tls_vminor == TLS_MINOR_VER_THREE);
2517 vminor = TLS_MINOR_VER_TWO;
2519 vminor = tls->params.tls_vminor;
2521 /* Is there enough queued for a TLS header? */
2522 if (sb->sb_tlscc < tls->params.tls_hlen)
2525 m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
2526 tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
2528 if (hdr->tls_vmajor != tls->params.tls_vmajor ||
2529 hdr->tls_vminor != vminor)
2531 else if (tls13 && hdr->tls_type != TLS_RLTYPE_APP)
2533 else if (tls_len < tls->params.tls_hlen || tls_len >
2534 tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
2535 tls->params.tls_tlen)
2539 if (__predict_false(error != 0)) {
2541 * We have a corrupted record and are likely
2542 * out of sync. The connection isn't
2543 * recoverable at this point, so abort it.
2546 counter_u64_add(ktls_offload_corrupted_records, 1);
2548 ktls_drop(so, error);
2552 /* Is the entire record queued? */
2553 if (sb->sb_tlscc < tls_len)
2557 * Split out the portion of the mbuf chain containing
2560 data = ktls_detach_record(sb, tls_len);
2563 MPASS(sb->sb_tlsdcc == tls_len);
2565 seqno = sb->sb_tls_seqno;
2570 /* get crypto state for this TLS record */
2571 state = ktls_mbuf_crypto_state(data, 0, tls_len);
2574 case KTLS_MBUF_CRYPTO_ST_MIXED:
2575 error = ktls_ocf_recrypt(tls, hdr, data, seqno);
2579 case KTLS_MBUF_CRYPTO_ST_ENCRYPTED:
2580 error = ktls_ocf_decrypt(tls, hdr, data, seqno,
2582 if (__predict_true(error == 0)) {
2584 error = tls13_find_record_type(tls, data,
2585 tls_len, &trail_len, &record_type);
2587 record_type = hdr->tls_type;
2591 case KTLS_MBUF_CRYPTO_ST_DECRYPTED:
2593 * NIC TLS is only supported for AEAD
2594 * ciphersuites which used a fixed sized
2598 trail_len = tls->params.tls_tlen - 1;
2599 error = tls13_find_record_type(tls, data,
2600 tls_len, &trail_len, &record_type);
2602 trail_len = tls->params.tls_tlen;
2604 record_type = hdr->tls_type;
2612 counter_u64_add(ktls_offload_failed_crypto, 1);
2615 if (sb->sb_tlsdcc == 0) {
2617 * sbcut/drop/flush discarded these
2625 * Drop this TLS record's data, but keep
2626 * decrypting subsequent records.
2628 sb->sb_ccc -= tls_len;
2631 if (error != EMSGSIZE)
2633 CURVNET_SET(so->so_vnet);
2634 so->so_error = error;
2635 sorwakeup_locked(so);
2644 /* Allocate the control mbuf. */
2645 memset(&tgr, 0, sizeof(tgr));
2646 tgr.tls_type = record_type;
2647 tgr.tls_vmajor = hdr->tls_vmajor;
2648 tgr.tls_vminor = hdr->tls_vminor;
2649 tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
2651 control = sbcreatecontrol(&tgr, sizeof(tgr),
2652 TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
2655 if (sb->sb_tlsdcc == 0) {
2656 /* sbcut/drop/flush discarded these mbufs. */
2657 MPASS(sb->sb_tlscc == 0);
2664 * Clear the 'dcc' accounting in preparation for
2665 * adding the decrypted record.
2667 sb->sb_ccc -= tls_len;
2671 /* If there is no payload, drop all of the data. */
2672 if (tgr.tls_length == htobe16(0)) {
2677 remain = tls->params.tls_hlen;
2678 while (remain > 0) {
2679 if (data->m_len > remain) {
2680 data->m_data += remain;
2681 data->m_len -= remain;
2684 remain -= data->m_len;
2685 data = m_free(data);
2688 /* Trim trailer and clear M_NOTREADY. */
2689 remain = be16toh(tgr.tls_length);
2691 for (m = data; remain > m->m_len; m = m->m_next) {
2692 m->m_flags &= ~(M_NOTREADY | M_DECRYPTED);
2698 m->m_flags &= ~(M_NOTREADY | M_DECRYPTED);
2700 /* Set EOR on the final mbuf. */
2701 m->m_flags |= M_EOR;
2704 sbappendcontrol_locked(sb, data, control, 0);
2706 if (__predict_false(state != KTLS_MBUF_CRYPTO_ST_DECRYPTED)) {
2707 sb->sb_flags |= SB_TLS_RX_RESYNC;
2709 ktls_resync_ifnet(so, tls_len, seqno);
2711 } else if (__predict_false(sb->sb_flags & SB_TLS_RX_RESYNC)) {
2712 sb->sb_flags &= ~SB_TLS_RX_RESYNC;
2714 ktls_resync_ifnet(so, 0, seqno);
2719 sb->sb_flags &= ~SB_TLS_RX_RUNNING;
2721 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
2722 so->so_error = EMSGSIZE;
2724 sorwakeup_locked(so);
2727 SOCKBUF_UNLOCK_ASSERT(sb);
2729 CURVNET_SET(so->so_vnet);
2735 ktls_enqueue_to_free(struct mbuf *m)
2740 /* Mark it for freeing. */
2741 m->m_epg_flags |= EPG_FLAG_2FREE;
2742 wq = &ktls_wq[m->m_epg_tls->wq_index];
2744 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2745 running = wq->running;
2746 mtx_unlock(&wq->mtx);
2752 ktls_buffer_alloc(struct ktls_wq *wq, struct mbuf *m)
2755 int domain, running;
2757 if (m->m_epg_npgs <= 2)
2759 if (ktls_buffer_zone == NULL)
2761 if ((u_int)(ticks - wq->lastallocfail) < hz) {
2763 * Rate-limit allocation attempts after a failure.
2764 * ktls_buffer_import() will acquire a per-domain mutex to check
2765 * the free page queues and may fail consistently if memory is
2770 buf = uma_zalloc(ktls_buffer_zone, M_NOWAIT | M_NORECLAIM);
2772 domain = PCPU_GET(domain);
2773 wq->lastallocfail = ticks;
2776 * Note that this check is "racy", but the races are
2777 * harmless, and are either a spurious wakeup if
2778 * multiple threads fail allocations before the alloc
2779 * thread wakes, or waiting an extra second in case we
2780 * see an old value of running == true.
2782 if (!VM_DOMAIN_EMPTY(domain)) {
2783 running = atomic_load_int(&ktls_domains[domain].reclaim_td.running);
2785 wakeup(&ktls_domains[domain].reclaim_td);
2792 ktls_encrypt_record(struct ktls_wq *wq, struct mbuf *m,
2793 struct ktls_session *tls, struct ktls_ocf_encrypt_state *state)
2796 int error, i, len, off;
2798 KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) == (M_EXTPG | M_NOTREADY),
2799 ("%p not unready & nomap mbuf\n", m));
2800 KASSERT(ptoa(m->m_epg_npgs) <= ktls_maxlen,
2801 ("page count %d larger than maximum frame length %d", m->m_epg_npgs,
2804 /* Anonymous mbufs are encrypted in place. */
2805 if ((m->m_epg_flags & EPG_FLAG_ANON) != 0)
2806 return (ktls_ocf_encrypt(state, tls, m, NULL, 0));
2809 * For file-backed mbufs (from sendfile), anonymous wired
2810 * pages are allocated and used as the encryption destination.
2812 if ((state->cbuf = ktls_buffer_alloc(wq, m)) != NULL) {
2813 len = ptoa(m->m_epg_npgs - 1) + m->m_epg_last_len -
2815 state->dst_iov[0].iov_base = (char *)state->cbuf +
2817 state->dst_iov[0].iov_len = len;
2818 state->parray[0] = DMAP_TO_PHYS((vm_offset_t)state->cbuf);
2821 off = m->m_epg_1st_off;
2822 for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2823 pg = vm_page_alloc_noobj(VM_ALLOC_NODUMP |
2824 VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2825 len = m_epg_pagelen(m, i, off);
2826 state->parray[i] = VM_PAGE_TO_PHYS(pg);
2827 state->dst_iov[i].iov_base =
2828 (char *)PHYS_TO_DMAP(state->parray[i]) + off;
2829 state->dst_iov[i].iov_len = len;
2832 KASSERT(i + 1 <= nitems(state->dst_iov), ("dst_iov is too small"));
2833 state->dst_iov[i].iov_base = m->m_epg_trail;
2834 state->dst_iov[i].iov_len = m->m_epg_trllen;
2836 error = ktls_ocf_encrypt(state, tls, m, state->dst_iov, i + 1);
2838 if (__predict_false(error != 0)) {
2839 /* Free the anonymous pages. */
2840 if (state->cbuf != NULL)
2841 uma_zfree(ktls_buffer_zone, state->cbuf);
2843 for (i = 0; i < m->m_epg_npgs; i++) {
2844 pg = PHYS_TO_VM_PAGE(state->parray[i]);
2845 (void)vm_page_unwire_noq(pg);
2853 /* Number of TLS records in a batch passed to ktls_enqueue(). */
2855 ktls_batched_records(struct mbuf *m)
2857 int page_count, records;
2860 page_count = m->m_epg_enc_cnt;
2861 while (page_count > 0) {
2863 page_count -= m->m_epg_nrdy;
2866 KASSERT(page_count == 0, ("%s: mismatched page count", __func__));
2871 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
2873 struct ktls_session *tls;
2878 KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2879 (M_EXTPG | M_NOTREADY)),
2880 ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
2881 KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
2883 KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
2885 m->m_epg_enc_cnt = page_count;
2888 * Save a pointer to the socket. The caller is responsible
2889 * for taking an additional reference via soref().
2895 wq = &ktls_wq[tls->wq_index];
2897 if (__predict_false(tls->sequential_records)) {
2899 * For TLS 1.0, records must be encrypted
2900 * sequentially. For a given connection, all records
2901 * queued to the associated work queue are processed
2902 * sequentially. However, sendfile(2) might complete
2903 * I/O requests spanning multiple TLS records out of
2904 * order. Here we ensure TLS records are enqueued to
2905 * the work queue in FIFO order.
2907 * tls->next_seqno holds the sequence number of the
2908 * next TLS record that should be enqueued to the work
2909 * queue. If this next record is not tls->next_seqno,
2910 * it must be a future record, so insert it, sorted by
2911 * TLS sequence number, into tls->pending_records and
2914 * If this TLS record matches tls->next_seqno, place
2915 * it in the work queue and then check
2916 * tls->pending_records to see if any
2917 * previously-queued records are now ready for
2920 if (m->m_epg_seqno != tls->next_seqno) {
2924 STAILQ_FOREACH(n, &tls->pending_records, m_epg_stailq) {
2925 if (n->m_epg_seqno > m->m_epg_seqno)
2930 STAILQ_INSERT_TAIL(&tls->pending_records, m,
2933 STAILQ_INSERT_HEAD(&tls->pending_records, m,
2936 STAILQ_INSERT_AFTER(&tls->pending_records, p, m,
2938 mtx_unlock(&wq->mtx);
2939 counter_u64_add(ktls_cnt_tx_pending, 1);
2943 tls->next_seqno += ktls_batched_records(m);
2944 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2946 while (!STAILQ_EMPTY(&tls->pending_records)) {
2949 n = STAILQ_FIRST(&tls->pending_records);
2950 if (n->m_epg_seqno != tls->next_seqno)
2954 STAILQ_REMOVE_HEAD(&tls->pending_records, m_epg_stailq);
2955 tls->next_seqno += ktls_batched_records(n);
2956 STAILQ_INSERT_TAIL(&wq->m_head, n, m_epg_stailq);
2958 counter_u64_add(ktls_cnt_tx_pending, -(queued - 1));
2960 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2962 running = wq->running;
2963 mtx_unlock(&wq->mtx);
2966 counter_u64_add(ktls_cnt_tx_queued, queued);
2970 * Once a file-backed mbuf (from sendfile) has been encrypted, free
2971 * the pages from the file and replace them with the anonymous pages
2972 * allocated in ktls_encrypt_record().
2975 ktls_finish_nonanon(struct mbuf *m, struct ktls_ocf_encrypt_state *state)
2979 MPASS((m->m_epg_flags & EPG_FLAG_ANON) == 0);
2981 /* Free the old pages. */
2982 m->m_ext.ext_free(m);
2984 /* Replace them with the new pages. */
2985 if (state->cbuf != NULL) {
2986 for (i = 0; i < m->m_epg_npgs; i++)
2987 m->m_epg_pa[i] = state->parray[0] + ptoa(i);
2989 /* Contig pages should go back to the cache. */
2990 m->m_ext.ext_free = ktls_free_mext_contig;
2992 for (i = 0; i < m->m_epg_npgs; i++)
2993 m->m_epg_pa[i] = state->parray[i];
2995 /* Use the basic free routine. */
2996 m->m_ext.ext_free = mb_free_mext_pgs;
2999 /* Pages are now writable. */
3000 m->m_epg_flags |= EPG_FLAG_ANON;
3003 static __noinline void
3004 ktls_encrypt(struct ktls_wq *wq, struct mbuf *top)
3006 struct ktls_ocf_encrypt_state state;
3007 struct ktls_session *tls;
3010 int error, npages, total_pages;
3013 tls = top->m_epg_tls;
3014 KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
3015 KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
3017 top->m_epg_so = NULL;
3019 total_pages = top->m_epg_enc_cnt;
3023 * Encrypt the TLS records in the chain of mbufs starting with
3024 * 'top'. 'total_pages' gives us a total count of pages and is
3025 * used to know when we have finished encrypting the TLS
3026 * records originally queued with 'top'.
3028 * NB: These mbufs are queued in the socket buffer and
3029 * 'm_next' is traversing the mbufs in the socket buffer. The
3030 * socket buffer lock is not held while traversing this chain.
3031 * Since the mbufs are all marked M_NOTREADY their 'm_next'
3032 * pointers should be stable. However, the 'm_next' of the
3033 * last mbuf encrypted is not necessarily NULL. It can point
3034 * to other mbufs appended while 'top' was on the TLS work
3037 * Each mbuf holds an entire TLS record.
3040 for (m = top; npages != total_pages; m = m->m_next) {
3041 KASSERT(m->m_epg_tls == tls,
3042 ("different TLS sessions in a single mbuf chain: %p vs %p",
3043 tls, m->m_epg_tls));
3044 KASSERT(npages + m->m_epg_npgs <= total_pages,
3045 ("page count mismatch: top %p, total_pages %d, m %p", top,
3048 error = ktls_encrypt_record(wq, m, tls, &state);
3050 counter_u64_add(ktls_offload_failed_crypto, 1);
3054 if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
3055 ktls_finish_nonanon(m, &state);
3057 npages += m->m_epg_nrdy;
3060 * Drop a reference to the session now that it is no
3061 * longer needed. Existing code depends on encrypted
3062 * records having no associated session vs
3063 * yet-to-be-encrypted records having an associated
3066 m->m_epg_tls = NULL;
3070 CURVNET_SET(so->so_vnet);
3072 (void)so->so_proto->pr_ready(so, top, npages);
3075 mb_free_notready(top, total_pages);
3083 ktls_encrypt_cb(struct ktls_ocf_encrypt_state *state, int error)
3085 struct ktls_session *tls;
3092 if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
3093 ktls_finish_nonanon(m, state);
3096 free(state, M_KTLS);
3099 * Drop a reference to the session now that it is no longer
3100 * needed. Existing code depends on encrypted records having
3101 * no associated session vs yet-to-be-encrypted records having
3102 * an associated session.
3105 m->m_epg_tls = NULL;
3109 counter_u64_add(ktls_offload_failed_crypto, 1);
3111 CURVNET_SET(so->so_vnet);
3112 npages = m->m_epg_nrdy;
3115 (void)so->so_proto->pr_ready(so, m, npages);
3118 mb_free_notready(m, npages);
3126 * Similar to ktls_encrypt, but used with asynchronous OCF backends
3127 * (coprocessors) where encryption does not use host CPU resources and
3128 * it can be beneficial to queue more requests than CPUs.
3130 static __noinline void
3131 ktls_encrypt_async(struct ktls_wq *wq, struct mbuf *top)
3133 struct ktls_ocf_encrypt_state *state;
3134 struct ktls_session *tls;
3137 int error, mpages, npages, total_pages;
3140 tls = top->m_epg_tls;
3141 KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
3142 KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
3144 top->m_epg_so = NULL;
3146 total_pages = top->m_epg_enc_cnt;
3150 for (m = top; npages != total_pages; m = n) {
3151 KASSERT(m->m_epg_tls == tls,
3152 ("different TLS sessions in a single mbuf chain: %p vs %p",
3153 tls, m->m_epg_tls));
3154 KASSERT(npages + m->m_epg_npgs <= total_pages,
3155 ("page count mismatch: top %p, total_pages %d, m %p", top,
3158 state = malloc(sizeof(*state), M_KTLS, M_WAITOK | M_ZERO);
3163 mpages = m->m_epg_nrdy;
3166 error = ktls_encrypt_record(wq, m, tls, state);
3168 counter_u64_add(ktls_offload_failed_crypto, 1);
3169 free(state, M_KTLS);
3170 CURVNET_SET(so->so_vnet);
3179 CURVNET_SET(so->so_vnet);
3182 mb_free_notready(m, total_pages - npages);
3190 ktls_bind_domain(int domain)
3194 error = cpuset_setthread(curthread->td_tid, &cpuset_domain[domain]);
3197 curthread->td_domain.dr_policy = DOMAINSET_PREF(domain);
3202 ktls_reclaim_thread(void *ctx)
3204 struct ktls_domain_info *ktls_domain = ctx;
3205 struct ktls_reclaim_thread *sc = &ktls_domain->reclaim_td;
3206 struct sysctl_oid *oid;
3210 domain = ktls_domain - ktls_domains;
3212 printf("Starting KTLS reclaim thread for domain %d\n", domain);
3213 error = ktls_bind_domain(domain);
3215 printf("Unable to bind KTLS reclaim thread for domain %d: error %d\n",
3217 snprintf(name, sizeof(name), "domain%d", domain);
3218 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_kern_ipc_tls), OID_AUTO,
3219 name, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
3220 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "reclaims",
3221 CTLFLAG_RD, &sc->reclaims, 0, "buffers reclaimed");
3222 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "wakeups",
3223 CTLFLAG_RD, &sc->wakeups, 0, "thread wakeups");
3224 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "running",
3225 CTLFLAG_RD, &sc->running, 0, "thread running");
3228 atomic_store_int(&sc->running, 0);
3229 tsleep(sc, PZERO | PNOLOCK, "-", 0);
3230 atomic_store_int(&sc->running, 1);
3233 * Below we attempt to reclaim ktls_max_reclaim
3234 * buffers using vm_page_reclaim_contig_domain_ext().
3235 * We do this here, as this function can take several
3236 * seconds to scan all of memory and it does not
3237 * matter if this thread pauses for a while. If we
3238 * block a ktls worker thread, we risk developing
3239 * backlogs of buffers to be encrypted, leading to
3240 * surges of traffic and potential NIC output drops.
3242 if (vm_page_reclaim_contig_domain_ext(domain, VM_ALLOC_NORMAL,
3243 atop(ktls_maxlen), 0, ~0ul, PAGE_SIZE, 0,
3244 ktls_max_reclaim) != 0) {
3245 vm_wait_domain(domain);
3247 sc->reclaims += ktls_max_reclaim;
3253 ktls_work_thread(void *ctx)
3255 struct ktls_wq *wq = ctx;
3257 struct socket *so, *son;
3258 STAILQ_HEAD(, mbuf) local_m_head;
3259 STAILQ_HEAD(, socket) local_so_head;
3264 printf("Starting KTLS worker thread for CPU %d\n", cpu);
3267 * Bind to a core. If ktls_bind_threads is > 1, then
3268 * we bind to the NUMA domain instead.
3270 if (ktls_bind_threads) {
3273 if (ktls_bind_threads > 1) {
3274 struct pcpu *pc = pcpu_find(cpu);
3276 error = ktls_bind_domain(pc->pc_domain);
3280 CPU_SETOF(cpu, &mask);
3281 error = cpuset_setthread(curthread->td_tid, &mask);
3284 printf("Unable to bind KTLS worker thread for CPU %d: error %d\n",
3287 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
3292 while (STAILQ_EMPTY(&wq->m_head) &&
3293 STAILQ_EMPTY(&wq->so_head)) {
3294 wq->running = false;
3295 mtx_sleep(wq, &wq->mtx, 0, "-", 0);
3299 STAILQ_INIT(&local_m_head);
3300 STAILQ_CONCAT(&local_m_head, &wq->m_head);
3301 STAILQ_INIT(&local_so_head);
3302 STAILQ_CONCAT(&local_so_head, &wq->so_head);
3303 mtx_unlock(&wq->mtx);
3305 STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
3306 if (m->m_epg_flags & EPG_FLAG_2FREE) {
3307 ktls_free(m->m_epg_tls);
3310 if (m->m_epg_tls->sync_dispatch)
3311 ktls_encrypt(wq, m);
3313 ktls_encrypt_async(wq, m);
3314 counter_u64_add(ktls_cnt_tx_queued, -1);
3318 STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
3320 counter_u64_add(ktls_cnt_rx_queued, -1);
3326 ktls_disable_ifnet_help(void *context, int pending __unused)
3328 struct ktls_session *tls;
3339 so = inp->inp_socket;
3341 if (inp->inp_flags & INP_DROPPED) {
3345 if (so->so_snd.sb_tls_info != NULL)
3346 err = ktls_set_tx_mode(so, TCP_TLS_MODE_SW);
3350 counter_u64_add(ktls_ifnet_disable_ok, 1);
3351 /* ktls_set_tx_mode() drops inp wlock, so recheck flags */
3352 if ((inp->inp_flags & INP_DROPPED) == 0 &&
3353 (tp = intotcpcb(inp)) != NULL &&
3354 tp->t_fb->tfb_hwtls_change != NULL)
3355 (*tp->t_fb->tfb_hwtls_change)(tp, 0);
3357 counter_u64_add(ktls_ifnet_disable_fail, 1);
3361 CURVNET_SET(so->so_vnet);
3369 * Called when re-transmits are becoming a substantial portion of the
3370 * sends on this connection. When this happens, we transition the
3371 * connection to software TLS. This is needed because most inline TLS
3372 * NICs keep crypto state only for in-order transmits. This means
3373 * that to handle a TCP rexmit (which is out-of-order), the NIC must
3374 * re-DMA the entire TLS record up to and including the current
3375 * segment. This means that when re-transmitting the last ~1448 byte
3376 * segment of a 16KB TLS record, we could wind up re-DMA'ing an order
3377 * of magnitude more data than we are sending. This can cause the
3378 * PCIe link to saturate well before the network, which can cause
3379 * output drops, and a general loss of capacity.
3382 ktls_disable_ifnet(void *arg)
3387 struct ktls_session *tls;
3390 inp = tptoinpcb(tp);
3391 INP_WLOCK_ASSERT(inp);
3392 so = inp->inp_socket;
3394 tls = so->so_snd.sb_tls_info;
3395 if (tp->t_nic_ktls_xmit_dis == 1) {
3401 * note that t_nic_ktls_xmit_dis is never cleared; disabling
3402 * ifnet can only be done once per connection, so we never want
3406 (void)ktls_hold(tls);
3408 tp->t_nic_ktls_xmit_dis = 1;
3410 TASK_INIT(&tls->disable_ifnet_task, 0, ktls_disable_ifnet_help, tls);
3411 (void)taskqueue_enqueue(taskqueue_thread, &tls->disable_ifnet_task);