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_reset_receive_tag(void *context, int pending);
301 static void ktls_reset_send_tag(void *context, int pending);
302 static void ktls_work_thread(void *ctx);
303 static void ktls_reclaim_thread(void *ctx);
306 ktls_get_cpu(struct socket *so)
310 struct ktls_domain_info *di;
316 cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
317 if (cpuid != NETISR_CPUID_NONE)
321 * Just use the flowid to shard connections in a repeatable
322 * fashion. Note that TLS 1.0 sessions rely on the
323 * serialization provided by having the same connection use
327 if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
328 di = &ktls_domains[inp->inp_numa_domain];
329 cpuid = di->cpu[inp->inp_flowid % di->count];
332 cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
337 ktls_buffer_import(void *arg, void **store, int count, int domain, int flags)
342 KASSERT((ktls_maxlen & PAGE_MASK) == 0,
343 ("%s: ktls max length %d is not page size-aligned",
344 __func__, ktls_maxlen));
346 req = VM_ALLOC_WIRED | VM_ALLOC_NODUMP | malloc2vm_flags(flags);
347 for (i = 0; i < count; i++) {
348 m = vm_page_alloc_noobj_contig_domain(domain, req,
349 atop(ktls_maxlen), 0, ~0ul, PAGE_SIZE, 0,
353 store[i] = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
359 ktls_buffer_release(void *arg __unused, void **store, int count)
364 for (i = 0; i < count; i++) {
365 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)store[i]));
366 for (j = 0; j < atop(ktls_maxlen); j++) {
367 (void)vm_page_unwire_noq(m + j);
374 ktls_free_mext_contig(struct mbuf *m)
377 uma_zfree(ktls_buffer_zone, (void *)PHYS_TO_DMAP(m->m_epg_pa[0]));
385 int count, domain, error, i;
387 ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
390 ktls_session_zone = uma_zcreate("ktls_session",
391 sizeof(struct ktls_session),
392 NULL, NULL, NULL, NULL,
395 if (ktls_sw_buffer_cache) {
396 ktls_buffer_zone = uma_zcache_create("ktls_buffers",
397 roundup2(ktls_maxlen, PAGE_SIZE), NULL, NULL, NULL, NULL,
398 ktls_buffer_import, ktls_buffer_release, NULL,
399 UMA_ZONE_FIRSTTOUCH);
403 * Initialize the workqueues to run the TLS work. We create a
404 * work queue for each CPU.
407 STAILQ_INIT(&ktls_wq[i].m_head);
408 STAILQ_INIT(&ktls_wq[i].so_head);
409 mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
410 if (ktls_bind_threads > 1) {
412 domain = pc->pc_domain;
413 count = ktls_domains[domain].count;
414 ktls_domains[domain].cpu[count] = i;
415 ktls_domains[domain].count++;
417 ktls_cpuid_lookup[ktls_number_threads] = i;
418 ktls_number_threads++;
422 * If we somehow have an empty domain, fall back to choosing
423 * among all KTLS threads.
425 if (ktls_bind_threads > 1) {
426 for (i = 0; i < vm_ndomains; i++) {
427 if (ktls_domains[i].count == 0) {
428 ktls_bind_threads = 1;
434 /* Start kthreads for each workqueue. */
436 error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
437 &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
439 printf("Can't add KTLS thread %d error %d\n", i, error);
445 * Start an allocation thread per-domain to perform blocking allocations
446 * of 16k physically contiguous TLS crypto destination buffers.
448 if (ktls_sw_buffer_cache) {
449 for (domain = 0; domain < vm_ndomains; domain++) {
450 if (VM_DOMAIN_EMPTY(domain))
452 if (CPU_EMPTY(&cpuset_domain[domain]))
454 error = kproc_kthread_add(ktls_reclaim_thread,
455 &ktls_domains[domain], &ktls_proc,
456 &ktls_domains[domain].reclaim_td.td,
457 0, 0, "KTLS", "reclaim_%d", domain);
459 printf("Can't add KTLS reclaim thread %d error %d\n",
467 printf("KTLS: Initialized %d threads\n", ktls_number_threads);
472 ktls_start_kthreads(void)
477 state = atomic_load_acq_int(&ktls_init_state);
478 if (__predict_true(state > 0))
483 sx_xlock(&ktls_init_lock);
484 if (ktls_init_state != 0) {
485 sx_xunlock(&ktls_init_lock);
494 atomic_store_rel_int(&ktls_init_state, state);
495 sx_xunlock(&ktls_init_lock);
500 ktls_create_session(struct socket *so, struct tls_enable *en,
501 struct ktls_session **tlsp, int direction)
503 struct ktls_session *tls;
506 /* Only TLS 1.0 - 1.3 are supported. */
507 if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
509 if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
510 en->tls_vminor > TLS_MINOR_VER_THREE)
513 if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
515 if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
517 if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
520 /* All supported algorithms require a cipher key. */
521 if (en->cipher_key_len == 0)
524 /* No flags are currently supported. */
528 /* Common checks for supported algorithms. */
529 switch (en->cipher_algorithm) {
530 case CRYPTO_AES_NIST_GCM_16:
532 * auth_algorithm isn't used, but permit GMAC values
535 switch (en->auth_algorithm) {
537 #ifdef COMPAT_FREEBSD12
538 /* XXX: Really 13.0-current COMPAT. */
539 case CRYPTO_AES_128_NIST_GMAC:
540 case CRYPTO_AES_192_NIST_GMAC:
541 case CRYPTO_AES_256_NIST_GMAC:
547 if (en->auth_key_len != 0)
549 switch (en->tls_vminor) {
550 case TLS_MINOR_VER_TWO:
551 if (en->iv_len != TLS_AEAD_GCM_LEN)
554 case TLS_MINOR_VER_THREE:
555 if (en->iv_len != TLS_1_3_GCM_IV_LEN)
563 switch (en->auth_algorithm) {
564 case CRYPTO_SHA1_HMAC:
566 case CRYPTO_SHA2_256_HMAC:
567 case CRYPTO_SHA2_384_HMAC:
568 if (en->tls_vminor != TLS_MINOR_VER_TWO)
574 if (en->auth_key_len == 0)
578 * TLS 1.0 requires an implicit IV. TLS 1.1 and 1.2
581 switch (en->tls_vminor) {
582 case TLS_MINOR_VER_ZERO:
583 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
586 case TLS_MINOR_VER_ONE:
587 case TLS_MINOR_VER_TWO:
588 /* Ignore any supplied IV. */
595 case CRYPTO_CHACHA20_POLY1305:
596 if (en->auth_algorithm != 0 || en->auth_key_len != 0)
598 if (en->tls_vminor != TLS_MINOR_VER_TWO &&
599 en->tls_vminor != TLS_MINOR_VER_THREE)
601 if (en->iv_len != TLS_CHACHA20_IV_LEN)
608 error = ktls_start_kthreads();
612 tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
614 counter_u64_add(ktls_offload_active, 1);
616 refcount_init(&tls->refcount, 1);
617 if (direction == KTLS_RX) {
618 TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_receive_tag, tls);
620 TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
621 tls->inp = so->so_pcb;
626 tls->wq_index = ktls_get_cpu(so);
628 tls->params.cipher_algorithm = en->cipher_algorithm;
629 tls->params.auth_algorithm = en->auth_algorithm;
630 tls->params.tls_vmajor = en->tls_vmajor;
631 tls->params.tls_vminor = en->tls_vminor;
632 tls->params.flags = en->flags;
633 tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
635 /* Set the header and trailer lengths. */
636 tls->params.tls_hlen = sizeof(struct tls_record_layer);
637 switch (en->cipher_algorithm) {
638 case CRYPTO_AES_NIST_GCM_16:
640 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
641 * nonce. TLS 1.3 uses a 12 byte implicit IV.
643 if (en->tls_vminor < TLS_MINOR_VER_THREE)
644 tls->params.tls_hlen += sizeof(uint64_t);
645 tls->params.tls_tlen = AES_GMAC_HASH_LEN;
646 tls->params.tls_bs = 1;
649 switch (en->auth_algorithm) {
650 case CRYPTO_SHA1_HMAC:
651 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
652 /* Implicit IV, no nonce. */
653 tls->sequential_records = true;
654 tls->next_seqno = be64dec(en->rec_seq);
655 STAILQ_INIT(&tls->pending_records);
657 tls->params.tls_hlen += AES_BLOCK_LEN;
659 tls->params.tls_tlen = AES_BLOCK_LEN +
662 case CRYPTO_SHA2_256_HMAC:
663 tls->params.tls_hlen += AES_BLOCK_LEN;
664 tls->params.tls_tlen = AES_BLOCK_LEN +
667 case CRYPTO_SHA2_384_HMAC:
668 tls->params.tls_hlen += AES_BLOCK_LEN;
669 tls->params.tls_tlen = AES_BLOCK_LEN +
673 panic("invalid hmac");
675 tls->params.tls_bs = AES_BLOCK_LEN;
677 case CRYPTO_CHACHA20_POLY1305:
679 * Chacha20 uses a 12 byte implicit IV.
681 tls->params.tls_tlen = POLY1305_HASH_LEN;
682 tls->params.tls_bs = 1;
685 panic("invalid cipher");
689 * TLS 1.3 includes optional padding which we do not support,
690 * and also puts the "real" record type at the end of the
693 if (en->tls_vminor == TLS_MINOR_VER_THREE)
694 tls->params.tls_tlen += sizeof(uint8_t);
696 KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
697 ("TLS header length too long: %d", tls->params.tls_hlen));
698 KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
699 ("TLS trailer length too long: %d", tls->params.tls_tlen));
701 if (en->auth_key_len != 0) {
702 tls->params.auth_key_len = en->auth_key_len;
703 tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
705 error = copyin(en->auth_key, tls->params.auth_key,
711 tls->params.cipher_key_len = en->cipher_key_len;
712 tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
713 error = copyin(en->cipher_key, tls->params.cipher_key,
719 * This holds the implicit portion of the nonce for AEAD
720 * ciphers and the initial implicit IV for TLS 1.0. The
721 * explicit portions of the IV are generated in ktls_frame().
723 if (en->iv_len != 0) {
724 tls->params.iv_len = en->iv_len;
725 error = copyin(en->iv, tls->params.iv, en->iv_len);
730 * For TLS 1.2 with GCM, generate an 8-byte nonce as a
731 * counter to generate unique explicit IVs.
733 * Store this counter in the last 8 bytes of the IV
734 * array so that it is 8-byte aligned.
736 if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
737 en->tls_vminor == TLS_MINOR_VER_TWO)
738 arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
749 static struct ktls_session *
750 ktls_clone_session(struct ktls_session *tls, int direction)
752 struct ktls_session *tls_new;
754 tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
756 counter_u64_add(ktls_offload_active, 1);
758 refcount_init(&tls_new->refcount, 1);
759 if (direction == KTLS_RX) {
760 TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_receive_tag,
763 TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_send_tag,
765 tls_new->inp = tls->inp;
767 in_pcbref(tls_new->inp);
770 /* Copy fields from existing session. */
771 tls_new->params = tls->params;
772 tls_new->wq_index = tls->wq_index;
774 /* Deep copy keys. */
775 if (tls_new->params.auth_key != NULL) {
776 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
778 memcpy(tls_new->params.auth_key, tls->params.auth_key,
779 tls->params.auth_key_len);
782 tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
784 memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
785 tls->params.cipher_key_len);
792 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
800 if (inp->inp_flags & INP_DROPPED) {
804 if (inp->inp_socket == NULL) {
809 if (!(tp->t_flags & TF_TOE)) {
814 error = tcp_offload_alloc_tls_session(tp, tls, direction);
817 tls->mode = TCP_TLS_MODE_TOE;
818 switch (tls->params.cipher_algorithm) {
820 counter_u64_add(ktls_toe_cbc, 1);
822 case CRYPTO_AES_NIST_GCM_16:
823 counter_u64_add(ktls_toe_gcm, 1);
825 case CRYPTO_CHACHA20_POLY1305:
826 counter_u64_add(ktls_toe_chacha20, 1);
835 * Common code used when first enabling ifnet TLS on a connection or
836 * when allocating a new ifnet TLS session due to a routing change.
837 * This function allocates a new TLS send tag on whatever interface
838 * the connection is currently routed over.
841 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
842 struct m_snd_tag **mstp)
844 union if_snd_tag_alloc_params params;
846 struct nhop_object *nh;
851 if (inp->inp_flags & INP_DROPPED) {
855 if (inp->inp_socket == NULL) {
862 * Check administrative controls on ifnet TLS to determine if
863 * ifnet TLS should be denied.
865 * - Always permit 'force' requests.
866 * - ktls_ifnet_permitted == 0: always deny.
868 if (!force && ktls_ifnet_permitted == 0) {
874 * XXX: Use the cached route in the inpcb to find the
875 * interface. This should perhaps instead use
876 * rtalloc1_fib(dst, 0, 0, fibnum). Since KTLS is only
877 * enabled after a connection has completed key negotiation in
878 * userland, the cached route will be present in practice.
880 nh = inp->inp_route.ro_nh;
889 * Allocate a TLS + ratelimit tag if the connection has an
890 * existing pacing rate.
892 if (tp->t_pacing_rate != -1 &&
893 (if_getcapenable(ifp) & IFCAP_TXTLS_RTLMT) != 0) {
894 params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
895 params.tls_rate_limit.inp = inp;
896 params.tls_rate_limit.tls = tls;
897 params.tls_rate_limit.max_rate = tp->t_pacing_rate;
899 params.hdr.type = IF_SND_TAG_TYPE_TLS;
900 params.tls.inp = inp;
901 params.tls.tls = tls;
903 params.hdr.flowid = inp->inp_flowid;
904 params.hdr.flowtype = inp->inp_flowtype;
905 params.hdr.numa_domain = inp->inp_numa_domain;
908 if ((if_getcapenable(ifp) & IFCAP_MEXTPG) == 0) {
912 if (inp->inp_vflag & INP_IPV6) {
913 if ((if_getcapenable(ifp) & IFCAP_TXTLS6) == 0) {
918 if ((if_getcapenable(ifp) & IFCAP_TXTLS4) == 0) {
923 error = m_snd_tag_alloc(ifp, ¶ms, mstp);
930 * Allocate an initial TLS receive tag for doing HW decryption of TLS
933 * This function allocates a new TLS receive tag on whatever interface
934 * the connection is currently routed over. If the connection ends up
935 * using a different interface for receive this will get fixed up via
936 * ktls_input_ifp_mismatch as future packets arrive.
939 ktls_alloc_rcv_tag(struct inpcb *inp, struct ktls_session *tls,
940 struct m_snd_tag **mstp)
942 union if_snd_tag_alloc_params params;
944 struct nhop_object *nh;
947 if (!ktls_ocf_recrypt_supported(tls))
951 if (inp->inp_flags & INP_DROPPED) {
955 if (inp->inp_socket == NULL) {
961 * Check administrative controls on ifnet TLS to determine if
962 * ifnet TLS should be denied.
964 if (ktls_ifnet_permitted == 0) {
970 * XXX: As with ktls_alloc_snd_tag, use the cached route in
971 * the inpcb to find the interface.
973 nh = inp->inp_route.ro_nh;
982 params.hdr.type = IF_SND_TAG_TYPE_TLS_RX;
983 params.hdr.flowid = inp->inp_flowid;
984 params.hdr.flowtype = inp->inp_flowtype;
985 params.hdr.numa_domain = inp->inp_numa_domain;
986 params.tls_rx.inp = inp;
987 params.tls_rx.tls = tls;
988 params.tls_rx.vlan_id = 0;
992 if (inp->inp_vflag & INP_IPV6) {
993 if ((if_getcapenable2(ifp) & IFCAP2_BIT(IFCAP2_RXTLS6)) == 0) {
998 if ((if_getcapenable2(ifp) & IFCAP2_BIT(IFCAP2_RXTLS4)) == 0) {
1003 error = m_snd_tag_alloc(ifp, ¶ms, mstp);
1006 * If this connection is over a vlan, vlan_snd_tag_alloc
1007 * rewrites vlan_id with the saved interface. Save the VLAN
1008 * ID for use in ktls_reset_receive_tag which allocates new
1009 * receive tags directly from the leaf interface bypassing
1013 tls->rx_vlan_id = params.tls_rx.vlan_id;
1019 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, int direction,
1022 struct m_snd_tag *mst;
1025 switch (direction) {
1027 error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
1028 if (__predict_false(error != 0))
1032 KASSERT(!force, ("%s: forced receive tag", __func__));
1033 error = ktls_alloc_rcv_tag(so->so_pcb, tls, &mst);
1034 if (__predict_false(error != 0))
1038 __assert_unreachable();
1041 tls->mode = TCP_TLS_MODE_IFNET;
1044 switch (tls->params.cipher_algorithm) {
1045 case CRYPTO_AES_CBC:
1046 counter_u64_add(ktls_ifnet_cbc, 1);
1048 case CRYPTO_AES_NIST_GCM_16:
1049 counter_u64_add(ktls_ifnet_gcm, 1);
1051 case CRYPTO_CHACHA20_POLY1305:
1052 counter_u64_add(ktls_ifnet_chacha20, 1);
1062 ktls_use_sw(struct ktls_session *tls)
1064 tls->mode = TCP_TLS_MODE_SW;
1065 switch (tls->params.cipher_algorithm) {
1066 case CRYPTO_AES_CBC:
1067 counter_u64_add(ktls_sw_cbc, 1);
1069 case CRYPTO_AES_NIST_GCM_16:
1070 counter_u64_add(ktls_sw_gcm, 1);
1072 case CRYPTO_CHACHA20_POLY1305:
1073 counter_u64_add(ktls_sw_chacha20, 1);
1079 ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
1083 error = ktls_ocf_try(so, tls, direction);
1091 * KTLS RX stores data in the socket buffer as a list of TLS records,
1092 * where each record is stored as a control message containg the TLS
1093 * header followed by data mbufs containing the decrypted data. This
1094 * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
1095 * both encrypted and decrypted data. TLS records decrypted by a NIC
1096 * should be queued to the socket buffer as records, but encrypted
1097 * data which needs to be decrypted by software arrives as a stream of
1098 * regular mbufs which need to be converted. In addition, there may
1099 * already be pending encrypted data in the socket buffer when KTLS RX
1102 * To manage not-yet-decrypted data for KTLS RX, the following scheme
1105 * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
1107 * - ktls_check_rx checks this chain of mbufs reading the TLS header
1108 * from the first mbuf. Once all of the data for that TLS record is
1109 * queued, the socket is queued to a worker thread.
1111 * - The worker thread calls ktls_decrypt to decrypt TLS records in
1112 * the TLS chain. Each TLS record is detached from the TLS chain,
1113 * decrypted, and inserted into the regular socket buffer chain as
1114 * record starting with a control message holding the TLS header and
1115 * a chain of mbufs holding the encrypted data.
1119 sb_mark_notready(struct sockbuf *sb)
1126 sb->sb_mbtail = NULL;
1127 sb->sb_lastrecord = NULL;
1128 for (; m != NULL; m = m->m_next) {
1129 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
1131 KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
1133 KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
1135 m->m_flags |= M_NOTREADY;
1136 sb->sb_acc -= m->m_len;
1137 sb->sb_tlscc += m->m_len;
1138 sb->sb_mtlstail = m;
1140 KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
1141 ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
1146 * Return information about the pending TLS data in a socket
1147 * buffer. On return, 'seqno' is set to the sequence number
1148 * of the next TLS record to be received, 'resid' is set to
1149 * the amount of bytes still needed for the last pending
1150 * record. The function returns 'false' if the last pending
1151 * record contains a partial TLS header. In that case, 'resid'
1152 * is the number of bytes needed to complete the TLS header.
1155 ktls_pending_rx_info(struct sockbuf *sb, uint64_t *seqnop, size_t *residp)
1157 struct tls_record_layer hdr;
1161 u_int offset, record_len;
1163 SOCKBUF_LOCK_ASSERT(sb);
1164 MPASS(sb->sb_flags & SB_TLS_RX);
1165 seqno = sb->sb_tls_seqno;
1166 resid = sb->sb_tlscc;
1179 if (resid < sizeof(hdr)) {
1181 *residp = sizeof(hdr) - resid;
1185 m_copydata(m, offset, sizeof(hdr), (void *)&hdr);
1187 record_len = sizeof(hdr) + ntohs(hdr.tls_length);
1188 if (resid <= record_len) {
1190 *residp = record_len - resid;
1193 resid -= record_len;
1195 while (record_len != 0) {
1196 if (m->m_len - offset > record_len) {
1197 offset += record_len;
1201 record_len -= (m->m_len - offset);
1209 ktls_enable_rx(struct socket *so, struct tls_enable *en)
1211 struct ktls_session *tls;
1214 if (!ktls_offload_enable)
1217 counter_u64_add(ktls_offload_enable_calls, 1);
1220 * This should always be true since only the TCP socket option
1221 * invokes this function.
1223 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1227 * XXX: Don't overwrite existing sessions. We should permit
1228 * this to support rekeying in the future.
1230 if (so->so_rcv.sb_tls_info != NULL)
1233 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1236 error = ktls_create_session(so, en, &tls, KTLS_RX);
1240 error = ktls_ocf_try(so, tls, KTLS_RX);
1246 /* Mark the socket as using TLS offload. */
1247 SOCK_RECVBUF_LOCK(so);
1248 if (SOLISTENING(so)) {
1249 SOCK_RECVBUF_UNLOCK(so);
1253 so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1254 so->so_rcv.sb_tls_info = tls;
1255 so->so_rcv.sb_flags |= SB_TLS_RX;
1257 /* Mark existing data as not ready until it can be decrypted. */
1258 sb_mark_notready(&so->so_rcv);
1259 ktls_check_rx(&so->so_rcv);
1260 SOCK_RECVBUF_UNLOCK(so);
1262 /* Prefer TOE -> ifnet TLS -> software TLS. */
1264 error = ktls_try_toe(so, tls, KTLS_RX);
1267 error = ktls_try_ifnet(so, tls, KTLS_RX, false);
1271 counter_u64_add(ktls_offload_total, 1);
1277 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1279 struct ktls_session *tls;
1284 if (!ktls_offload_enable)
1287 counter_u64_add(ktls_offload_enable_calls, 1);
1290 * This should always be true since only the TCP socket option
1291 * invokes this function.
1293 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1297 * XXX: Don't overwrite existing sessions. We should permit
1298 * this to support rekeying in the future.
1300 if (so->so_snd.sb_tls_info != NULL)
1303 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1306 /* TLS requires ext pgs */
1307 if (mb_use_ext_pgs == 0)
1310 error = ktls_create_session(so, en, &tls, KTLS_TX);
1314 /* Prefer TOE -> ifnet TLS -> software TLS. */
1316 error = ktls_try_toe(so, tls, KTLS_TX);
1319 error = ktls_try_ifnet(so, tls, KTLS_TX, false);
1321 error = ktls_try_sw(so, tls, KTLS_TX);
1329 * Serialize with sosend_generic() and make sure that we're not
1330 * operating on a listening socket.
1332 error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1339 * Write lock the INP when setting sb_tls_info so that
1340 * routines in tcp_ratelimit.c can read sb_tls_info while
1341 * holding the INP lock.
1345 SOCK_SENDBUF_LOCK(so);
1346 so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1347 so->so_snd.sb_tls_info = tls;
1348 if (tls->mode != TCP_TLS_MODE_SW) {
1349 tp = intotcpcb(inp);
1350 MPASS(tp->t_nic_ktls_xmit == 0);
1351 tp->t_nic_ktls_xmit = 1;
1352 if (tp->t_fb->tfb_hwtls_change != NULL)
1353 (*tp->t_fb->tfb_hwtls_change)(tp, 1);
1355 SOCK_SENDBUF_UNLOCK(so);
1357 SOCK_IO_SEND_UNLOCK(so);
1359 counter_u64_add(ktls_offload_total, 1);
1365 ktls_get_rx_mode(struct socket *so, int *modep)
1367 struct ktls_session *tls;
1368 struct inpcb *inp __diagused;
1370 if (SOLISTENING(so))
1373 INP_WLOCK_ASSERT(inp);
1374 SOCK_RECVBUF_LOCK(so);
1375 tls = so->so_rcv.sb_tls_info;
1377 *modep = TCP_TLS_MODE_NONE;
1380 SOCK_RECVBUF_UNLOCK(so);
1385 * ktls_get_rx_sequence - get the next TCP- and TLS- sequence number.
1387 * This function gets information about the next TCP- and TLS-
1388 * sequence number to be processed by the TLS receive worker
1389 * thread. The information is extracted from the given "inpcb"
1390 * structure. The values are stored in host endian format at the two
1391 * given output pointer locations. The TCP sequence number points to
1392 * the beginning of the TLS header.
1394 * This function returns zero on success, else a non-zero error code
1398 ktls_get_rx_sequence(struct inpcb *inp, uint32_t *tcpseq, uint64_t *tlsseq)
1404 so = inp->inp_socket;
1405 if (__predict_false(so == NULL)) {
1409 if (inp->inp_flags & INP_DROPPED) {
1411 return (ECONNRESET);
1414 tp = intotcpcb(inp);
1417 SOCKBUF_LOCK(&so->so_rcv);
1418 *tcpseq = tp->rcv_nxt - so->so_rcv.sb_tlscc;
1419 *tlsseq = so->so_rcv.sb_tls_seqno;
1420 SOCKBUF_UNLOCK(&so->so_rcv);
1428 ktls_get_tx_mode(struct socket *so, int *modep)
1430 struct ktls_session *tls;
1431 struct inpcb *inp __diagused;
1433 if (SOLISTENING(so))
1436 INP_WLOCK_ASSERT(inp);
1437 SOCK_SENDBUF_LOCK(so);
1438 tls = so->so_snd.sb_tls_info;
1440 *modep = TCP_TLS_MODE_NONE;
1443 SOCK_SENDBUF_UNLOCK(so);
1448 * Switch between SW and ifnet TLS sessions as requested.
1451 ktls_set_tx_mode(struct socket *so, int mode)
1453 struct ktls_session *tls, *tls_new;
1458 if (SOLISTENING(so))
1461 case TCP_TLS_MODE_SW:
1462 case TCP_TLS_MODE_IFNET:
1469 INP_WLOCK_ASSERT(inp);
1470 tp = intotcpcb(inp);
1472 if (mode == TCP_TLS_MODE_IFNET) {
1473 /* Don't allow enabling ifnet ktls multiple times */
1474 if (tp->t_nic_ktls_xmit)
1478 * Don't enable ifnet ktls if we disabled it due to an
1479 * excessive retransmission rate
1481 if (tp->t_nic_ktls_xmit_dis)
1485 SOCKBUF_LOCK(&so->so_snd);
1486 tls = so->so_snd.sb_tls_info;
1488 SOCKBUF_UNLOCK(&so->so_snd);
1492 if (tls->mode == mode) {
1493 SOCKBUF_UNLOCK(&so->so_snd);
1497 tls = ktls_hold(tls);
1498 SOCKBUF_UNLOCK(&so->so_snd);
1501 tls_new = ktls_clone_session(tls, KTLS_TX);
1503 if (mode == TCP_TLS_MODE_IFNET)
1504 error = ktls_try_ifnet(so, tls_new, KTLS_TX, true);
1506 error = ktls_try_sw(so, tls_new, KTLS_TX);
1508 counter_u64_add(ktls_switch_failed, 1);
1515 error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1517 counter_u64_add(ktls_switch_failed, 1);
1525 * If we raced with another session change, keep the existing
1528 if (tls != so->so_snd.sb_tls_info) {
1529 counter_u64_add(ktls_switch_failed, 1);
1530 SOCK_IO_SEND_UNLOCK(so);
1538 SOCKBUF_LOCK(&so->so_snd);
1539 so->so_snd.sb_tls_info = tls_new;
1540 if (tls_new->mode != TCP_TLS_MODE_SW) {
1541 MPASS(tp->t_nic_ktls_xmit == 0);
1542 tp->t_nic_ktls_xmit = 1;
1543 if (tp->t_fb->tfb_hwtls_change != NULL)
1544 (*tp->t_fb->tfb_hwtls_change)(tp, 1);
1546 SOCKBUF_UNLOCK(&so->so_snd);
1547 SOCK_IO_SEND_UNLOCK(so);
1550 * Drop two references on 'tls'. The first is for the
1551 * ktls_hold() above. The second drops the reference from the
1554 KASSERT(tls->refcount >= 2, ("too few references on old session"));
1558 if (mode == TCP_TLS_MODE_IFNET)
1559 counter_u64_add(ktls_switch_to_ifnet, 1);
1561 counter_u64_add(ktls_switch_to_sw, 1);
1567 * Try to allocate a new TLS receive tag. This task is scheduled when
1568 * sbappend_ktls_rx detects an input path change. If a new tag is
1569 * allocated, replace the tag in the TLS session. If a new tag cannot
1570 * be allocated, let the session fall back to software decryption.
1573 ktls_reset_receive_tag(void *context, int pending)
1575 union if_snd_tag_alloc_params params;
1576 struct ktls_session *tls;
1577 struct m_snd_tag *mst;
1583 MPASS(pending == 1);
1591 if (inp->inp_flags & INP_DROPPED) {
1596 SOCKBUF_LOCK(&so->so_rcv);
1598 tls->snd_tag = NULL;
1600 m_snd_tag_rele(mst);
1604 SOCKBUF_UNLOCK(&so->so_rcv);
1606 params.hdr.type = IF_SND_TAG_TYPE_TLS_RX;
1607 params.hdr.flowid = inp->inp_flowid;
1608 params.hdr.flowtype = inp->inp_flowtype;
1609 params.hdr.numa_domain = inp->inp_numa_domain;
1610 params.tls_rx.inp = inp;
1611 params.tls_rx.tls = tls;
1612 params.tls_rx.vlan_id = tls->rx_vlan_id;
1615 if (inp->inp_vflag & INP_IPV6) {
1616 if ((if_getcapenable2(ifp) & IFCAP2_RXTLS6) == 0)
1619 if ((if_getcapenable2(ifp) & IFCAP2_RXTLS4) == 0)
1623 error = m_snd_tag_alloc(ifp, ¶ms, &mst);
1625 SOCKBUF_LOCK(&so->so_rcv);
1627 SOCKBUF_UNLOCK(&so->so_rcv);
1629 counter_u64_add(ktls_ifnet_reset, 1);
1632 * Just fall back to software decryption if a tag
1633 * cannot be allocated leaving the connection intact.
1634 * If a future input path change switches to another
1635 * interface this connection will resume ifnet TLS.
1637 counter_u64_add(ktls_ifnet_reset_failed, 1);
1641 mtx_pool_lock(mtxpool_sleep, tls);
1642 tls->reset_pending = false;
1643 mtx_pool_unlock(mtxpool_sleep, tls);
1652 * Try to allocate a new TLS send tag. This task is scheduled when
1653 * ip_output detects a route change while trying to transmit a packet
1654 * holding a TLS record. If a new tag is allocated, replace the tag
1655 * in the TLS session. Subsequent packets on the connection will use
1656 * the new tag. If a new tag cannot be allocated, drop the
1660 ktls_reset_send_tag(void *context, int pending)
1662 struct epoch_tracker et;
1663 struct ktls_session *tls;
1664 struct m_snd_tag *old, *new;
1669 MPASS(pending == 1);
1675 * Free the old tag first before allocating a new one.
1676 * ip[6]_output_send() will treat a NULL send tag the same as
1677 * an ifp mismatch and drop packets until a new tag is
1680 * Write-lock the INP when changing tls->snd_tag since
1681 * ip[6]_output_send() holds a read-lock when reading the
1686 tls->snd_tag = NULL;
1689 m_snd_tag_rele(old);
1691 error = ktls_alloc_snd_tag(inp, tls, true, &new);
1696 mtx_pool_lock(mtxpool_sleep, tls);
1697 tls->reset_pending = false;
1698 mtx_pool_unlock(mtxpool_sleep, tls);
1701 counter_u64_add(ktls_ifnet_reset, 1);
1704 * XXX: Should we kick tcp_output explicitly now that
1705 * the send tag is fixed or just rely on timers?
1708 NET_EPOCH_ENTER(et);
1710 if (!(inp->inp_flags & INP_DROPPED)) {
1711 tp = intotcpcb(inp);
1712 CURVNET_SET(inp->inp_vnet);
1713 tp = tcp_drop(tp, ECONNABORTED);
1716 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1723 counter_u64_add(ktls_ifnet_reset_failed, 1);
1726 * Leave reset_pending true to avoid future tasks while
1727 * the socket goes away.
1735 ktls_input_ifp_mismatch(struct sockbuf *sb, struct ifnet *ifp)
1737 struct ktls_session *tls;
1740 SOCKBUF_LOCK_ASSERT(sb);
1741 KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1743 so = __containerof(sb, struct socket, so_rcv);
1745 tls = sb->sb_tls_info;
1746 if_rele(tls->rx_ifp);
1751 * See if we should schedule a task to update the receive tag for
1754 mtx_pool_lock(mtxpool_sleep, tls);
1755 if (!tls->reset_pending) {
1756 (void) ktls_hold(tls);
1759 tls->reset_pending = true;
1760 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1762 mtx_pool_unlock(mtxpool_sleep, tls);
1766 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1772 INP_LOCK_ASSERT(inp);
1775 * See if we should schedule a task to update the send tag for
1778 mtx_pool_lock(mtxpool_sleep, tls);
1779 if (!tls->reset_pending) {
1780 (void) ktls_hold(tls);
1781 tls->reset_pending = true;
1782 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1784 mtx_pool_unlock(mtxpool_sleep, tls);
1790 ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1792 union if_snd_tag_modify_params params = {
1793 .rate_limit.max_rate = max_pacing_rate,
1794 .rate_limit.flags = M_NOWAIT,
1796 struct m_snd_tag *mst;
1798 /* Can't get to the inp, but it should be locked. */
1799 /* INP_LOCK_ASSERT(inp); */
1801 MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1803 if (tls->snd_tag == NULL) {
1805 * Resetting send tag, ignore this change. The
1806 * pending reset may or may not see this updated rate
1807 * in the tcpcb. If it doesn't, we will just lose
1816 MPASS(mst->sw->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1818 return (mst->sw->snd_tag_modify(mst, ¶ms));
1823 ktls_destroy_help(void *context, int pending __unused)
1825 ktls_destroy(context);
1829 ktls_destroy(struct ktls_session *tls)
1835 MPASS(tls->refcount == 0);
1839 wlocked = INP_WLOCKED(inp);
1840 if (!wlocked && !INP_TRY_WLOCK(inp)) {
1842 * rwlocks read locks are anonymous, and there
1843 * is no way to know if our current thread
1844 * holds an rlock on the inp. As a rough
1845 * estimate, check to see if the thread holds
1846 * *any* rlocks at all. If it does not, then we
1847 * know that we don't hold the inp rlock, and
1848 * can safely take the wlock
1850 if (curthread->td_rw_rlocks == 0) {
1854 * We might hold the rlock, so let's
1855 * do the destroy in a taskqueue
1856 * context to avoid a potential
1857 * deadlock. This should be very
1860 counter_u64_add(ktls_destroy_task, 1);
1861 TASK_INIT(&tls->destroy_task, 0,
1862 ktls_destroy_help, tls);
1863 (void)taskqueue_enqueue(taskqueue_thread,
1864 &tls->destroy_task);
1870 if (tls->sequential_records) {
1874 STAILQ_FOREACH_SAFE(m, &tls->pending_records, m_epg_stailq, n) {
1875 page_count = m->m_epg_enc_cnt;
1876 while (page_count > 0) {
1877 KASSERT(page_count >= m->m_epg_nrdy,
1878 ("%s: too few pages", __func__));
1879 page_count -= m->m_epg_nrdy;
1885 counter_u64_add(ktls_offload_active, -1);
1886 switch (tls->mode) {
1887 case TCP_TLS_MODE_SW:
1888 switch (tls->params.cipher_algorithm) {
1889 case CRYPTO_AES_CBC:
1890 counter_u64_add(ktls_sw_cbc, -1);
1892 case CRYPTO_AES_NIST_GCM_16:
1893 counter_u64_add(ktls_sw_gcm, -1);
1895 case CRYPTO_CHACHA20_POLY1305:
1896 counter_u64_add(ktls_sw_chacha20, -1);
1900 case TCP_TLS_MODE_IFNET:
1901 switch (tls->params.cipher_algorithm) {
1902 case CRYPTO_AES_CBC:
1903 counter_u64_add(ktls_ifnet_cbc, -1);
1905 case CRYPTO_AES_NIST_GCM_16:
1906 counter_u64_add(ktls_ifnet_gcm, -1);
1908 case CRYPTO_CHACHA20_POLY1305:
1909 counter_u64_add(ktls_ifnet_chacha20, -1);
1912 if (tls->snd_tag != NULL)
1913 m_snd_tag_rele(tls->snd_tag);
1914 if (tls->rx_ifp != NULL)
1915 if_rele(tls->rx_ifp);
1917 INP_WLOCK_ASSERT(inp);
1918 tp = intotcpcb(inp);
1919 MPASS(tp->t_nic_ktls_xmit == 1);
1920 tp->t_nic_ktls_xmit = 0;
1924 case TCP_TLS_MODE_TOE:
1925 switch (tls->params.cipher_algorithm) {
1926 case CRYPTO_AES_CBC:
1927 counter_u64_add(ktls_toe_cbc, -1);
1929 case CRYPTO_AES_NIST_GCM_16:
1930 counter_u64_add(ktls_toe_gcm, -1);
1932 case CRYPTO_CHACHA20_POLY1305:
1933 counter_u64_add(ktls_toe_chacha20, -1);
1939 if (tls->ocf_session != NULL)
1941 if (tls->params.auth_key != NULL) {
1942 zfree(tls->params.auth_key, M_KTLS);
1943 tls->params.auth_key = NULL;
1944 tls->params.auth_key_len = 0;
1946 if (tls->params.cipher_key != NULL) {
1947 zfree(tls->params.cipher_key, M_KTLS);
1948 tls->params.cipher_key = NULL;
1949 tls->params.cipher_key_len = 0;
1952 INP_WLOCK_ASSERT(inp);
1953 if (!in_pcbrele_wlocked(inp) && !wlocked)
1956 explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
1958 uma_zfree(ktls_session_zone, tls);
1962 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1965 for (; m != NULL; m = m->m_next) {
1966 KASSERT((m->m_flags & M_EXTPG) != 0,
1967 ("ktls_seq: mapped mbuf %p", m));
1969 m->m_epg_seqno = sb->sb_tls_seqno;
1975 * Add TLS framing (headers and trailers) to a chain of mbufs. Each
1976 * mbuf in the chain must be an unmapped mbuf. The payload of the
1977 * mbuf must be populated with the payload of each TLS record.
1979 * The record_type argument specifies the TLS record type used when
1980 * populating the TLS header.
1982 * The enq_count argument on return is set to the number of pages of
1983 * payload data for this entire chain that need to be encrypted via SW
1984 * encryption. The returned value should be passed to ktls_enqueue
1985 * when scheduling encryption of this chain of mbufs. To handle the
1986 * special case of empty fragments for TLS 1.0 sessions, an empty
1987 * fragment counts as one page.
1990 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1991 uint8_t record_type)
1993 struct tls_record_layer *tlshdr;
1997 int maxlen __diagused;
1999 maxlen = tls->params.max_frame_len;
2001 for (m = top; m != NULL; m = m->m_next) {
2003 * All mbufs in the chain should be TLS records whose
2004 * payload does not exceed the maximum frame length.
2006 * Empty TLS 1.0 records are permitted when using CBC.
2008 KASSERT(m->m_len <= maxlen && m->m_len >= 0 &&
2009 (m->m_len > 0 || ktls_permit_empty_frames(tls)),
2010 ("ktls_frame: m %p len %d", m, m->m_len));
2013 * TLS frames require unmapped mbufs to store session
2016 KASSERT((m->m_flags & M_EXTPG) != 0,
2017 ("ktls_frame: mapped mbuf %p (top = %p)", m, top));
2021 /* Save a reference to the session. */
2022 m->m_epg_tls = ktls_hold(tls);
2024 m->m_epg_hdrlen = tls->params.tls_hlen;
2025 m->m_epg_trllen = tls->params.tls_tlen;
2026 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
2030 * AES-CBC pads messages to a multiple of the
2031 * block size. Note that the padding is
2032 * applied after the digest and the encryption
2033 * is done on the "plaintext || mac || padding".
2034 * At least one byte of padding is always
2037 * Compute the final trailer length assuming
2038 * at most one block of padding.
2039 * tls->params.tls_tlen is the maximum
2040 * possible trailer length (padding + digest).
2041 * delta holds the number of excess padding
2042 * bytes if the maximum were used. Those
2043 * extra bytes are removed.
2045 bs = tls->params.tls_bs;
2046 delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
2047 m->m_epg_trllen -= delta;
2049 m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
2051 /* Populate the TLS header. */
2052 tlshdr = (void *)m->m_epg_hdr;
2053 tlshdr->tls_vmajor = tls->params.tls_vmajor;
2056 * TLS 1.3 masquarades as TLS 1.2 with a record type
2057 * of TLS_RLTYPE_APP.
2059 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
2060 tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
2061 tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
2062 tlshdr->tls_type = TLS_RLTYPE_APP;
2063 /* save the real record type for later */
2064 m->m_epg_record_type = record_type;
2065 m->m_epg_trail[0] = record_type;
2067 tlshdr->tls_vminor = tls->params.tls_vminor;
2068 tlshdr->tls_type = record_type;
2070 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
2073 * Store nonces / explicit IVs after the end of the
2076 * For GCM with TLS 1.2, an 8 byte nonce is copied
2077 * from the end of the IV. The nonce is then
2078 * incremented for use by the next record.
2080 * For CBC, a random nonce is inserted for TLS 1.1+.
2082 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
2083 tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
2084 noncep = (uint64_t *)(tls->params.iv + 8);
2085 be64enc(tlshdr + 1, *noncep);
2087 } else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
2088 tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
2089 arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
2092 * When using SW encryption, mark the mbuf not ready.
2093 * It will be marked ready via sbready() after the
2094 * record has been encrypted.
2096 * When using ifnet TLS, unencrypted TLS records are
2097 * sent down the stack to the NIC.
2099 if (tls->mode == TCP_TLS_MODE_SW) {
2100 m->m_flags |= M_NOTREADY;
2101 if (__predict_false(tls_len == 0)) {
2102 /* TLS 1.0 empty fragment. */
2105 m->m_epg_nrdy = m->m_epg_npgs;
2106 *enq_cnt += m->m_epg_nrdy;
2112 ktls_permit_empty_frames(struct ktls_session *tls)
2114 return (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
2115 tls->params.tls_vminor == TLS_MINOR_VER_ZERO);
2119 ktls_check_rx(struct sockbuf *sb)
2121 struct tls_record_layer hdr;
2126 SOCKBUF_LOCK_ASSERT(sb);
2127 KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
2129 so = __containerof(sb, struct socket, so_rcv);
2131 if (sb->sb_flags & SB_TLS_RX_RUNNING)
2134 /* Is there enough queued for a TLS header? */
2135 if (sb->sb_tlscc < sizeof(hdr)) {
2136 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
2137 so->so_error = EMSGSIZE;
2141 m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
2143 /* Is the entire record queued? */
2144 if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
2145 if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
2146 so->so_error = EMSGSIZE;
2150 sb->sb_flags |= SB_TLS_RX_RUNNING;
2153 wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
2155 STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
2156 running = wq->running;
2157 mtx_unlock(&wq->mtx);
2160 counter_u64_add(ktls_cnt_rx_queued, 1);
2163 static struct mbuf *
2164 ktls_detach_record(struct sockbuf *sb, int len)
2166 struct mbuf *m, *n, *top;
2169 SOCKBUF_LOCK_ASSERT(sb);
2170 MPASS(len <= sb->sb_tlscc);
2173 * If TLS chain is the exact size of the record,
2174 * just grab the whole record.
2177 if (sb->sb_tlscc == len) {
2179 sb->sb_mtlstail = NULL;
2184 * While it would be nice to use m_split() here, we need
2185 * to know exactly what m_split() allocates to update the
2186 * accounting, so do it inline instead.
2189 for (m = top; remain > m->m_len; m = m->m_next)
2192 /* Easy case: don't have to split 'm'. */
2193 if (remain == m->m_len) {
2194 sb->sb_mtls = m->m_next;
2195 if (sb->sb_mtls == NULL)
2196 sb->sb_mtlstail = NULL;
2202 * Need to allocate an mbuf to hold the remainder of 'm'. Try
2203 * with M_NOWAIT first.
2205 n = m_get(M_NOWAIT, MT_DATA);
2208 * Use M_WAITOK with socket buffer unlocked. If
2209 * 'sb_mtls' changes while the lock is dropped, return
2210 * NULL to force the caller to retry.
2214 n = m_get(M_WAITOK, MT_DATA);
2217 if (sb->sb_mtls != top) {
2222 n->m_flags |= (m->m_flags & (M_NOTREADY | M_DECRYPTED));
2224 /* Store remainder in 'n'. */
2225 n->m_len = m->m_len - remain;
2226 if (m->m_flags & M_EXT) {
2227 n->m_data = m->m_data + remain;
2230 bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
2233 /* Trim 'm' and update accounting. */
2234 m->m_len -= n->m_len;
2235 sb->sb_tlscc -= n->m_len;
2236 sb->sb_ccc -= n->m_len;
2238 /* Account for 'n'. */
2239 sballoc_ktls_rx(sb, n);
2241 /* Insert 'n' into the TLS chain. */
2243 n->m_next = m->m_next;
2244 if (sb->sb_mtlstail == m)
2245 sb->sb_mtlstail = n;
2247 /* Detach the record from the TLS chain. */
2251 MPASS(m_length(top, NULL) == len);
2252 for (m = top; m != NULL; m = m->m_next)
2253 sbfree_ktls_rx(sb, m);
2254 sb->sb_tlsdcc = len;
2261 * Determine the length of the trailing zero padding and find the real
2262 * record type in the byte before the padding.
2264 * Walking the mbuf chain backwards is clumsy, so another option would
2265 * be to scan forwards remembering the last non-zero byte before the
2266 * trailer. However, it would be expensive to scan the entire record.
2267 * Instead, find the last non-zero byte of each mbuf in the chain
2268 * keeping track of the relative offset of that nonzero byte.
2270 * trail_len is the size of the MAC/tag on input and is set to the
2271 * size of the full trailer including padding and the record type on
2275 tls13_find_record_type(struct ktls_session *tls, struct mbuf *m, int tls_len,
2276 int *trailer_len, uint8_t *record_typep)
2279 u_int digest_start, last_offset, m_len, offset;
2280 uint8_t record_type;
2282 digest_start = tls_len - *trailer_len;
2285 for (; m != NULL && offset < digest_start;
2286 offset += m->m_len, m = m->m_next) {
2287 /* Don't look for padding in the tag. */
2288 m_len = min(digest_start - offset, m->m_len);
2289 cp = mtod(m, char *);
2291 /* Find last non-zero byte in this mbuf. */
2292 while (m_len > 0 && cp[m_len - 1] == 0)
2295 record_type = cp[m_len - 1];
2296 last_offset = offset + m_len;
2299 if (last_offset < tls->params.tls_hlen)
2302 *record_typep = record_type;
2303 *trailer_len = tls_len - last_offset + 1;
2308 * Check if a mbuf chain is fully decrypted at the given offset and
2309 * length. Returns KTLS_MBUF_CRYPTO_ST_DECRYPTED if all data is
2310 * decrypted. KTLS_MBUF_CRYPTO_ST_MIXED if there is a mix of encrypted
2311 * and decrypted data. Else KTLS_MBUF_CRYPTO_ST_ENCRYPTED if all data
2314 ktls_mbuf_crypto_st_t
2315 ktls_mbuf_crypto_state(struct mbuf *mb, int offset, int len)
2317 int m_flags_ored = 0;
2318 int m_flags_anded = -1;
2320 for (; mb != NULL; mb = mb->m_next) {
2321 if (offset < mb->m_len)
2323 offset -= mb->m_len;
2327 for (; mb != NULL; mb = mb->m_next) {
2328 m_flags_ored |= mb->m_flags;
2329 m_flags_anded &= mb->m_flags;
2331 if (offset <= mb->m_len)
2333 offset -= mb->m_len;
2335 MPASS(mb != NULL || offset == 0);
2337 if ((m_flags_ored ^ m_flags_anded) & M_DECRYPTED)
2338 return (KTLS_MBUF_CRYPTO_ST_MIXED);
2340 return ((m_flags_ored & M_DECRYPTED) ?
2341 KTLS_MBUF_CRYPTO_ST_DECRYPTED :
2342 KTLS_MBUF_CRYPTO_ST_ENCRYPTED);
2346 * ktls_resync_ifnet - get HW TLS RX back on track after packet loss
2349 ktls_resync_ifnet(struct socket *so, uint32_t tls_len, uint64_t tls_rcd_num)
2351 union if_snd_tag_modify_params params;
2352 struct m_snd_tag *mst;
2356 mst = so->so_rcv.sb_tls_info->snd_tag;
2357 if (__predict_false(mst == NULL))
2360 inp = sotoinpcb(so);
2361 if (__predict_false(inp == NULL))
2365 if (inp->inp_flags & INP_DROPPED) {
2367 return (ECONNRESET);
2370 tp = intotcpcb(inp);
2373 /* Get the TCP sequence number of the next valid TLS header. */
2374 SOCKBUF_LOCK(&so->so_rcv);
2375 params.tls_rx.tls_hdr_tcp_sn =
2376 tp->rcv_nxt - so->so_rcv.sb_tlscc - tls_len;
2377 params.tls_rx.tls_rec_length = tls_len;
2378 params.tls_rx.tls_seq_number = tls_rcd_num;
2379 SOCKBUF_UNLOCK(&so->so_rcv);
2383 MPASS(mst->sw->type == IF_SND_TAG_TYPE_TLS_RX);
2384 return (mst->sw->snd_tag_modify(mst, ¶ms));
2388 ktls_drop(struct socket *so, int error)
2390 struct epoch_tracker et;
2391 struct inpcb *inp = sotoinpcb(so);
2394 NET_EPOCH_ENTER(et);
2396 if (!(inp->inp_flags & INP_DROPPED)) {
2397 tp = intotcpcb(inp);
2398 CURVNET_SET(inp->inp_vnet);
2399 tp = tcp_drop(tp, error);
2404 so->so_error = error;
2405 SOCK_RECVBUF_LOCK(so);
2406 sorwakeup_locked(so);
2413 ktls_decrypt(struct socket *so)
2415 char tls_header[MBUF_PEXT_HDR_LEN];
2416 struct ktls_session *tls;
2418 struct tls_record_layer *hdr;
2419 struct tls_get_record tgr;
2420 struct mbuf *control, *data, *m;
2421 ktls_mbuf_crypto_st_t state;
2423 int error, remain, tls_len, trail_len;
2425 uint8_t vminor, record_type;
2427 hdr = (struct tls_record_layer *)tls_header;
2430 KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
2431 ("%s: socket %p not running", __func__, so));
2433 tls = sb->sb_tls_info;
2436 tls13 = (tls->params.tls_vminor == TLS_MINOR_VER_THREE);
2438 vminor = TLS_MINOR_VER_TWO;
2440 vminor = tls->params.tls_vminor;
2442 /* Is there enough queued for a TLS header? */
2443 if (sb->sb_tlscc < tls->params.tls_hlen)
2446 m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
2447 tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
2449 if (hdr->tls_vmajor != tls->params.tls_vmajor ||
2450 hdr->tls_vminor != vminor)
2452 else if (tls13 && hdr->tls_type != TLS_RLTYPE_APP)
2454 else if (tls_len < tls->params.tls_hlen || tls_len >
2455 tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
2456 tls->params.tls_tlen)
2460 if (__predict_false(error != 0)) {
2462 * We have a corrupted record and are likely
2463 * out of sync. The connection isn't
2464 * recoverable at this point, so abort it.
2467 counter_u64_add(ktls_offload_corrupted_records, 1);
2469 ktls_drop(so, error);
2473 /* Is the entire record queued? */
2474 if (sb->sb_tlscc < tls_len)
2478 * Split out the portion of the mbuf chain containing
2481 data = ktls_detach_record(sb, tls_len);
2484 MPASS(sb->sb_tlsdcc == tls_len);
2486 seqno = sb->sb_tls_seqno;
2491 /* get crypto state for this TLS record */
2492 state = ktls_mbuf_crypto_state(data, 0, tls_len);
2495 case KTLS_MBUF_CRYPTO_ST_MIXED:
2496 error = ktls_ocf_recrypt(tls, hdr, data, seqno);
2500 case KTLS_MBUF_CRYPTO_ST_ENCRYPTED:
2501 error = ktls_ocf_decrypt(tls, hdr, data, seqno,
2503 if (__predict_true(error == 0)) {
2505 error = tls13_find_record_type(tls, data,
2506 tls_len, &trail_len, &record_type);
2508 record_type = hdr->tls_type;
2512 case KTLS_MBUF_CRYPTO_ST_DECRYPTED:
2514 * NIC TLS is only supported for AEAD
2515 * ciphersuites which used a fixed sized
2519 trail_len = tls->params.tls_tlen - 1;
2520 error = tls13_find_record_type(tls, data,
2521 tls_len, &trail_len, &record_type);
2523 trail_len = tls->params.tls_tlen;
2525 record_type = hdr->tls_type;
2533 counter_u64_add(ktls_offload_failed_crypto, 1);
2536 if (sb->sb_tlsdcc == 0) {
2538 * sbcut/drop/flush discarded these
2546 * Drop this TLS record's data, but keep
2547 * decrypting subsequent records.
2549 sb->sb_ccc -= tls_len;
2552 if (error != EMSGSIZE)
2554 CURVNET_SET(so->so_vnet);
2555 so->so_error = error;
2556 sorwakeup_locked(so);
2565 /* Allocate the control mbuf. */
2566 memset(&tgr, 0, sizeof(tgr));
2567 tgr.tls_type = record_type;
2568 tgr.tls_vmajor = hdr->tls_vmajor;
2569 tgr.tls_vminor = hdr->tls_vminor;
2570 tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
2572 control = sbcreatecontrol(&tgr, sizeof(tgr),
2573 TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
2576 if (sb->sb_tlsdcc == 0) {
2577 /* sbcut/drop/flush discarded these mbufs. */
2578 MPASS(sb->sb_tlscc == 0);
2585 * Clear the 'dcc' accounting in preparation for
2586 * adding the decrypted record.
2588 sb->sb_ccc -= tls_len;
2592 /* If there is no payload, drop all of the data. */
2593 if (tgr.tls_length == htobe16(0)) {
2598 remain = tls->params.tls_hlen;
2599 while (remain > 0) {
2600 if (data->m_len > remain) {
2601 data->m_data += remain;
2602 data->m_len -= remain;
2605 remain -= data->m_len;
2606 data = m_free(data);
2609 /* Trim trailer and clear M_NOTREADY. */
2610 remain = be16toh(tgr.tls_length);
2612 for (m = data; remain > m->m_len; m = m->m_next) {
2613 m->m_flags &= ~(M_NOTREADY | M_DECRYPTED);
2619 m->m_flags &= ~(M_NOTREADY | M_DECRYPTED);
2621 /* Set EOR on the final mbuf. */
2622 m->m_flags |= M_EOR;
2625 sbappendcontrol_locked(sb, data, control, 0);
2627 if (__predict_false(state != KTLS_MBUF_CRYPTO_ST_DECRYPTED)) {
2628 sb->sb_flags |= SB_TLS_RX_RESYNC;
2630 ktls_resync_ifnet(so, tls_len, seqno);
2632 } else if (__predict_false(sb->sb_flags & SB_TLS_RX_RESYNC)) {
2633 sb->sb_flags &= ~SB_TLS_RX_RESYNC;
2635 ktls_resync_ifnet(so, 0, seqno);
2640 sb->sb_flags &= ~SB_TLS_RX_RUNNING;
2642 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
2643 so->so_error = EMSGSIZE;
2645 sorwakeup_locked(so);
2648 SOCKBUF_UNLOCK_ASSERT(sb);
2650 CURVNET_SET(so->so_vnet);
2656 ktls_enqueue_to_free(struct mbuf *m)
2661 /* Mark it for freeing. */
2662 m->m_epg_flags |= EPG_FLAG_2FREE;
2663 wq = &ktls_wq[m->m_epg_tls->wq_index];
2665 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2666 running = wq->running;
2667 mtx_unlock(&wq->mtx);
2673 ktls_buffer_alloc(struct ktls_wq *wq, struct mbuf *m)
2676 int domain, running;
2678 if (m->m_epg_npgs <= 2)
2680 if (ktls_buffer_zone == NULL)
2682 if ((u_int)(ticks - wq->lastallocfail) < hz) {
2684 * Rate-limit allocation attempts after a failure.
2685 * ktls_buffer_import() will acquire a per-domain mutex to check
2686 * the free page queues and may fail consistently if memory is
2691 buf = uma_zalloc(ktls_buffer_zone, M_NOWAIT | M_NORECLAIM);
2693 domain = PCPU_GET(domain);
2694 wq->lastallocfail = ticks;
2697 * Note that this check is "racy", but the races are
2698 * harmless, and are either a spurious wakeup if
2699 * multiple threads fail allocations before the alloc
2700 * thread wakes, or waiting an extra second in case we
2701 * see an old value of running == true.
2703 if (!VM_DOMAIN_EMPTY(domain)) {
2704 running = atomic_load_int(&ktls_domains[domain].reclaim_td.running);
2706 wakeup(&ktls_domains[domain].reclaim_td);
2713 ktls_encrypt_record(struct ktls_wq *wq, struct mbuf *m,
2714 struct ktls_session *tls, struct ktls_ocf_encrypt_state *state)
2717 int error, i, len, off;
2719 KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) == (M_EXTPG | M_NOTREADY),
2720 ("%p not unready & nomap mbuf\n", m));
2721 KASSERT(ptoa(m->m_epg_npgs) <= ktls_maxlen,
2722 ("page count %d larger than maximum frame length %d", m->m_epg_npgs,
2725 /* Anonymous mbufs are encrypted in place. */
2726 if ((m->m_epg_flags & EPG_FLAG_ANON) != 0)
2727 return (ktls_ocf_encrypt(state, tls, m, NULL, 0));
2730 * For file-backed mbufs (from sendfile), anonymous wired
2731 * pages are allocated and used as the encryption destination.
2733 if ((state->cbuf = ktls_buffer_alloc(wq, m)) != NULL) {
2734 len = ptoa(m->m_epg_npgs - 1) + m->m_epg_last_len -
2736 state->dst_iov[0].iov_base = (char *)state->cbuf +
2738 state->dst_iov[0].iov_len = len;
2739 state->parray[0] = DMAP_TO_PHYS((vm_offset_t)state->cbuf);
2742 off = m->m_epg_1st_off;
2743 for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2744 pg = vm_page_alloc_noobj(VM_ALLOC_NODUMP |
2745 VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2746 len = m_epg_pagelen(m, i, off);
2747 state->parray[i] = VM_PAGE_TO_PHYS(pg);
2748 state->dst_iov[i].iov_base =
2749 (char *)PHYS_TO_DMAP(state->parray[i]) + off;
2750 state->dst_iov[i].iov_len = len;
2753 KASSERT(i + 1 <= nitems(state->dst_iov), ("dst_iov is too small"));
2754 state->dst_iov[i].iov_base = m->m_epg_trail;
2755 state->dst_iov[i].iov_len = m->m_epg_trllen;
2757 error = ktls_ocf_encrypt(state, tls, m, state->dst_iov, i + 1);
2759 if (__predict_false(error != 0)) {
2760 /* Free the anonymous pages. */
2761 if (state->cbuf != NULL)
2762 uma_zfree(ktls_buffer_zone, state->cbuf);
2764 for (i = 0; i < m->m_epg_npgs; i++) {
2765 pg = PHYS_TO_VM_PAGE(state->parray[i]);
2766 (void)vm_page_unwire_noq(pg);
2774 /* Number of TLS records in a batch passed to ktls_enqueue(). */
2776 ktls_batched_records(struct mbuf *m)
2778 int page_count, records;
2781 page_count = m->m_epg_enc_cnt;
2782 while (page_count > 0) {
2784 page_count -= m->m_epg_nrdy;
2787 KASSERT(page_count == 0, ("%s: mismatched page count", __func__));
2792 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
2794 struct ktls_session *tls;
2799 KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2800 (M_EXTPG | M_NOTREADY)),
2801 ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
2802 KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
2804 KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
2806 m->m_epg_enc_cnt = page_count;
2809 * Save a pointer to the socket. The caller is responsible
2810 * for taking an additional reference via soref().
2816 wq = &ktls_wq[tls->wq_index];
2818 if (__predict_false(tls->sequential_records)) {
2820 * For TLS 1.0, records must be encrypted
2821 * sequentially. For a given connection, all records
2822 * queued to the associated work queue are processed
2823 * sequentially. However, sendfile(2) might complete
2824 * I/O requests spanning multiple TLS records out of
2825 * order. Here we ensure TLS records are enqueued to
2826 * the work queue in FIFO order.
2828 * tls->next_seqno holds the sequence number of the
2829 * next TLS record that should be enqueued to the work
2830 * queue. If this next record is not tls->next_seqno,
2831 * it must be a future record, so insert it, sorted by
2832 * TLS sequence number, into tls->pending_records and
2835 * If this TLS record matches tls->next_seqno, place
2836 * it in the work queue and then check
2837 * tls->pending_records to see if any
2838 * previously-queued records are now ready for
2841 if (m->m_epg_seqno != tls->next_seqno) {
2845 STAILQ_FOREACH(n, &tls->pending_records, m_epg_stailq) {
2846 if (n->m_epg_seqno > m->m_epg_seqno)
2851 STAILQ_INSERT_TAIL(&tls->pending_records, m,
2854 STAILQ_INSERT_HEAD(&tls->pending_records, m,
2857 STAILQ_INSERT_AFTER(&tls->pending_records, p, m,
2859 mtx_unlock(&wq->mtx);
2860 counter_u64_add(ktls_cnt_tx_pending, 1);
2864 tls->next_seqno += ktls_batched_records(m);
2865 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2867 while (!STAILQ_EMPTY(&tls->pending_records)) {
2870 n = STAILQ_FIRST(&tls->pending_records);
2871 if (n->m_epg_seqno != tls->next_seqno)
2875 STAILQ_REMOVE_HEAD(&tls->pending_records, m_epg_stailq);
2876 tls->next_seqno += ktls_batched_records(n);
2877 STAILQ_INSERT_TAIL(&wq->m_head, n, m_epg_stailq);
2879 counter_u64_add(ktls_cnt_tx_pending, -(queued - 1));
2881 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2883 running = wq->running;
2884 mtx_unlock(&wq->mtx);
2887 counter_u64_add(ktls_cnt_tx_queued, queued);
2891 * Once a file-backed mbuf (from sendfile) has been encrypted, free
2892 * the pages from the file and replace them with the anonymous pages
2893 * allocated in ktls_encrypt_record().
2896 ktls_finish_nonanon(struct mbuf *m, struct ktls_ocf_encrypt_state *state)
2900 MPASS((m->m_epg_flags & EPG_FLAG_ANON) == 0);
2902 /* Free the old pages. */
2903 m->m_ext.ext_free(m);
2905 /* Replace them with the new pages. */
2906 if (state->cbuf != NULL) {
2907 for (i = 0; i < m->m_epg_npgs; i++)
2908 m->m_epg_pa[i] = state->parray[0] + ptoa(i);
2910 /* Contig pages should go back to the cache. */
2911 m->m_ext.ext_free = ktls_free_mext_contig;
2913 for (i = 0; i < m->m_epg_npgs; i++)
2914 m->m_epg_pa[i] = state->parray[i];
2916 /* Use the basic free routine. */
2917 m->m_ext.ext_free = mb_free_mext_pgs;
2920 /* Pages are now writable. */
2921 m->m_epg_flags |= EPG_FLAG_ANON;
2924 static __noinline void
2925 ktls_encrypt(struct ktls_wq *wq, struct mbuf *top)
2927 struct ktls_ocf_encrypt_state state;
2928 struct ktls_session *tls;
2931 int error, npages, total_pages;
2934 tls = top->m_epg_tls;
2935 KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
2936 KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
2938 top->m_epg_so = NULL;
2940 total_pages = top->m_epg_enc_cnt;
2944 * Encrypt the TLS records in the chain of mbufs starting with
2945 * 'top'. 'total_pages' gives us a total count of pages and is
2946 * used to know when we have finished encrypting the TLS
2947 * records originally queued with 'top'.
2949 * NB: These mbufs are queued in the socket buffer and
2950 * 'm_next' is traversing the mbufs in the socket buffer. The
2951 * socket buffer lock is not held while traversing this chain.
2952 * Since the mbufs are all marked M_NOTREADY their 'm_next'
2953 * pointers should be stable. However, the 'm_next' of the
2954 * last mbuf encrypted is not necessarily NULL. It can point
2955 * to other mbufs appended while 'top' was on the TLS work
2958 * Each mbuf holds an entire TLS record.
2961 for (m = top; npages != total_pages; m = m->m_next) {
2962 KASSERT(m->m_epg_tls == tls,
2963 ("different TLS sessions in a single mbuf chain: %p vs %p",
2964 tls, m->m_epg_tls));
2965 KASSERT(npages + m->m_epg_npgs <= total_pages,
2966 ("page count mismatch: top %p, total_pages %d, m %p", top,
2969 error = ktls_encrypt_record(wq, m, tls, &state);
2971 counter_u64_add(ktls_offload_failed_crypto, 1);
2975 if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
2976 ktls_finish_nonanon(m, &state);
2978 npages += m->m_epg_nrdy;
2981 * Drop a reference to the session now that it is no
2982 * longer needed. Existing code depends on encrypted
2983 * records having no associated session vs
2984 * yet-to-be-encrypted records having an associated
2987 m->m_epg_tls = NULL;
2991 CURVNET_SET(so->so_vnet);
2993 (void)so->so_proto->pr_ready(so, top, npages);
2996 mb_free_notready(top, total_pages);
3004 ktls_encrypt_cb(struct ktls_ocf_encrypt_state *state, int error)
3006 struct ktls_session *tls;
3013 if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
3014 ktls_finish_nonanon(m, state);
3017 free(state, M_KTLS);
3020 * Drop a reference to the session now that it is no longer
3021 * needed. Existing code depends on encrypted records having
3022 * no associated session vs yet-to-be-encrypted records having
3023 * an associated session.
3026 m->m_epg_tls = NULL;
3030 counter_u64_add(ktls_offload_failed_crypto, 1);
3032 CURVNET_SET(so->so_vnet);
3033 npages = m->m_epg_nrdy;
3036 (void)so->so_proto->pr_ready(so, m, npages);
3039 mb_free_notready(m, npages);
3047 * Similar to ktls_encrypt, but used with asynchronous OCF backends
3048 * (coprocessors) where encryption does not use host CPU resources and
3049 * it can be beneficial to queue more requests than CPUs.
3051 static __noinline void
3052 ktls_encrypt_async(struct ktls_wq *wq, struct mbuf *top)
3054 struct ktls_ocf_encrypt_state *state;
3055 struct ktls_session *tls;
3058 int error, mpages, npages, total_pages;
3061 tls = top->m_epg_tls;
3062 KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
3063 KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
3065 top->m_epg_so = NULL;
3067 total_pages = top->m_epg_enc_cnt;
3071 for (m = top; npages != total_pages; m = n) {
3072 KASSERT(m->m_epg_tls == tls,
3073 ("different TLS sessions in a single mbuf chain: %p vs %p",
3074 tls, m->m_epg_tls));
3075 KASSERT(npages + m->m_epg_npgs <= total_pages,
3076 ("page count mismatch: top %p, total_pages %d, m %p", top,
3079 state = malloc(sizeof(*state), M_KTLS, M_WAITOK | M_ZERO);
3084 mpages = m->m_epg_nrdy;
3087 error = ktls_encrypt_record(wq, m, tls, state);
3089 counter_u64_add(ktls_offload_failed_crypto, 1);
3090 free(state, M_KTLS);
3091 CURVNET_SET(so->so_vnet);
3100 CURVNET_SET(so->so_vnet);
3103 mb_free_notready(m, total_pages - npages);
3111 ktls_bind_domain(int domain)
3115 error = cpuset_setthread(curthread->td_tid, &cpuset_domain[domain]);
3118 curthread->td_domain.dr_policy = DOMAINSET_PREF(domain);
3123 ktls_reclaim_thread(void *ctx)
3125 struct ktls_domain_info *ktls_domain = ctx;
3126 struct ktls_reclaim_thread *sc = &ktls_domain->reclaim_td;
3127 struct sysctl_oid *oid;
3131 domain = ktls_domain - ktls_domains;
3133 printf("Starting KTLS reclaim thread for domain %d\n", domain);
3134 error = ktls_bind_domain(domain);
3136 printf("Unable to bind KTLS reclaim thread for domain %d: error %d\n",
3138 snprintf(name, sizeof(name), "domain%d", domain);
3139 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_kern_ipc_tls), OID_AUTO,
3140 name, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
3141 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "reclaims",
3142 CTLFLAG_RD, &sc->reclaims, 0, "buffers reclaimed");
3143 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "wakeups",
3144 CTLFLAG_RD, &sc->wakeups, 0, "thread wakeups");
3145 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "running",
3146 CTLFLAG_RD, &sc->running, 0, "thread running");
3149 atomic_store_int(&sc->running, 0);
3150 tsleep(sc, PZERO | PNOLOCK, "-", 0);
3151 atomic_store_int(&sc->running, 1);
3154 * Below we attempt to reclaim ktls_max_reclaim
3155 * buffers using vm_page_reclaim_contig_domain_ext().
3156 * We do this here, as this function can take several
3157 * seconds to scan all of memory and it does not
3158 * matter if this thread pauses for a while. If we
3159 * block a ktls worker thread, we risk developing
3160 * backlogs of buffers to be encrypted, leading to
3161 * surges of traffic and potential NIC output drops.
3163 if (!vm_page_reclaim_contig_domain_ext(domain, VM_ALLOC_NORMAL,
3164 atop(ktls_maxlen), 0, ~0ul, PAGE_SIZE, 0, ktls_max_reclaim)) {
3165 vm_wait_domain(domain);
3167 sc->reclaims += ktls_max_reclaim;
3173 ktls_work_thread(void *ctx)
3175 struct ktls_wq *wq = ctx;
3177 struct socket *so, *son;
3178 STAILQ_HEAD(, mbuf) local_m_head;
3179 STAILQ_HEAD(, socket) local_so_head;
3184 printf("Starting KTLS worker thread for CPU %d\n", cpu);
3187 * Bind to a core. If ktls_bind_threads is > 1, then
3188 * we bind to the NUMA domain instead.
3190 if (ktls_bind_threads) {
3193 if (ktls_bind_threads > 1) {
3194 struct pcpu *pc = pcpu_find(cpu);
3196 error = ktls_bind_domain(pc->pc_domain);
3200 CPU_SETOF(cpu, &mask);
3201 error = cpuset_setthread(curthread->td_tid, &mask);
3204 printf("Unable to bind KTLS worker thread for CPU %d: error %d\n",
3207 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
3212 while (STAILQ_EMPTY(&wq->m_head) &&
3213 STAILQ_EMPTY(&wq->so_head)) {
3214 wq->running = false;
3215 mtx_sleep(wq, &wq->mtx, 0, "-", 0);
3219 STAILQ_INIT(&local_m_head);
3220 STAILQ_CONCAT(&local_m_head, &wq->m_head);
3221 STAILQ_INIT(&local_so_head);
3222 STAILQ_CONCAT(&local_so_head, &wq->so_head);
3223 mtx_unlock(&wq->mtx);
3225 STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
3226 if (m->m_epg_flags & EPG_FLAG_2FREE) {
3227 ktls_free(m->m_epg_tls);
3230 if (m->m_epg_tls->sync_dispatch)
3231 ktls_encrypt(wq, m);
3233 ktls_encrypt_async(wq, m);
3234 counter_u64_add(ktls_cnt_tx_queued, -1);
3238 STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
3240 counter_u64_add(ktls_cnt_rx_queued, -1);
3246 ktls_disable_ifnet_help(void *context, int pending __unused)
3248 struct ktls_session *tls;
3259 so = inp->inp_socket;
3261 if (inp->inp_flags & INP_DROPPED) {
3265 if (so->so_snd.sb_tls_info != NULL)
3266 err = ktls_set_tx_mode(so, TCP_TLS_MODE_SW);
3270 counter_u64_add(ktls_ifnet_disable_ok, 1);
3271 /* ktls_set_tx_mode() drops inp wlock, so recheck flags */
3272 if ((inp->inp_flags & INP_DROPPED) == 0 &&
3273 (tp = intotcpcb(inp)) != NULL &&
3274 tp->t_fb->tfb_hwtls_change != NULL)
3275 (*tp->t_fb->tfb_hwtls_change)(tp, 0);
3277 counter_u64_add(ktls_ifnet_disable_fail, 1);
3281 CURVNET_SET(so->so_vnet);
3289 * Called when re-transmits are becoming a substantial portion of the
3290 * sends on this connection. When this happens, we transition the
3291 * connection to software TLS. This is needed because most inline TLS
3292 * NICs keep crypto state only for in-order transmits. This means
3293 * that to handle a TCP rexmit (which is out-of-order), the NIC must
3294 * re-DMA the entire TLS record up to and including the current
3295 * segment. This means that when re-transmitting the last ~1448 byte
3296 * segment of a 16KB TLS record, we could wind up re-DMA'ing an order
3297 * of magnitude more data than we are sending. This can cause the
3298 * PCIe link to saturate well before the network, which can cause
3299 * output drops, and a general loss of capacity.
3302 ktls_disable_ifnet(void *arg)
3307 struct ktls_session *tls;
3310 inp = tptoinpcb(tp);
3311 INP_WLOCK_ASSERT(inp);
3312 so = inp->inp_socket;
3314 tls = so->so_snd.sb_tls_info;
3315 if (tp->t_nic_ktls_xmit_dis == 1) {
3321 * note that t_nic_ktls_xmit_dis is never cleared; disabling
3322 * ifnet can only be done once per connection, so we never want
3326 (void)ktls_hold(tls);
3328 tp->t_nic_ktls_xmit_dis = 1;
3330 TASK_INIT(&tls->disable_ifnet_task, 0, ktls_disable_ifnet_help, tls);
3331 (void)taskqueue_enqueue(taskqueue_thread, &tls->disable_ifnet_task);