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>
29 __FBSDID("$FreeBSD$");
32 #include "opt_inet6.h"
33 #include "opt_kern_tls.h"
34 #include "opt_ratelimit.h"
37 #include <sys/param.h>
38 #include <sys/kernel.h>
39 #include <sys/domainset.h>
40 #include <sys/endian.h>
44 #include <sys/mutex.h>
45 #include <sys/rmlock.h>
47 #include <sys/protosw.h>
48 #include <sys/refcount.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/taskqueue.h>
54 #include <sys/kthread.h>
56 #include <sys/vmmeter.h>
57 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
58 #include <machine/pcb.h>
60 #include <machine/vmparam.h>
62 #include <net/if_var.h>
64 #include <net/netisr.h>
65 #include <net/rss_config.h>
67 #include <net/route.h>
68 #include <net/route/nhop.h>
69 #if defined(INET) || defined(INET6)
70 #include <netinet/in.h>
71 #include <netinet/in_pcb.h>
73 #include <netinet/tcp_var.h>
75 #include <netinet/tcp_offload.h>
77 #include <opencrypto/cryptodev.h>
78 #include <opencrypto/ktls.h>
79 #include <vm/uma_dbg.h>
81 #include <vm/vm_pageout.h>
82 #include <vm/vm_page.h>
83 #include <vm/vm_pagequeue.h>
87 STAILQ_HEAD(, mbuf) m_head;
88 STAILQ_HEAD(, socket) so_head;
91 } __aligned(CACHE_LINE_SIZE);
93 struct ktls_alloc_thread {
100 struct ktls_domain_info {
103 struct ktls_alloc_thread alloc_td;
106 struct ktls_domain_info ktls_domains[MAXMEMDOM];
107 static struct ktls_wq *ktls_wq;
108 static struct proc *ktls_proc;
109 static uma_zone_t ktls_session_zone;
110 static uma_zone_t ktls_buffer_zone;
111 static uint16_t ktls_cpuid_lookup[MAXCPU];
112 static int ktls_init_state;
113 static struct sx ktls_init_lock;
114 SX_SYSINIT(ktls_init_lock, &ktls_init_lock, "ktls init");
116 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
117 "Kernel TLS offload");
118 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
119 "Kernel TLS offload stats");
122 static int ktls_bind_threads = 1;
124 static int ktls_bind_threads;
126 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
127 &ktls_bind_threads, 0,
128 "Bind crypto threads to cores (1) or cores and domains (2) at boot");
130 static u_int ktls_maxlen = 16384;
131 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RDTUN,
132 &ktls_maxlen, 0, "Maximum TLS record size");
134 static int ktls_number_threads;
135 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
136 &ktls_number_threads, 0,
137 "Number of TLS threads in thread-pool");
139 unsigned int ktls_ifnet_max_rexmit_pct = 2;
140 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, ifnet_max_rexmit_pct, CTLFLAG_RWTUN,
141 &ktls_ifnet_max_rexmit_pct, 2,
142 "Max percent bytes retransmitted before ifnet TLS is disabled");
144 static bool ktls_offload_enable;
145 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RWTUN,
146 &ktls_offload_enable, 0,
147 "Enable support for kernel TLS offload");
149 static bool ktls_cbc_enable = true;
150 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RWTUN,
152 "Enable support of AES-CBC crypto for kernel TLS");
154 static bool ktls_sw_buffer_cache = true;
155 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, sw_buffer_cache, CTLFLAG_RDTUN,
156 &ktls_sw_buffer_cache, 1,
157 "Enable caching of output buffers for SW encryption");
159 static int ktls_max_alloc = 128;
160 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, max_alloc, CTLFLAG_RWTUN,
161 &ktls_max_alloc, 128,
162 "Max number of 16k buffers to allocate in thread context");
164 static COUNTER_U64_DEFINE_EARLY(ktls_tasks_active);
165 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
166 &ktls_tasks_active, "Number of active tasks");
168 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_tx_pending);
169 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_pending, CTLFLAG_RD,
170 &ktls_cnt_tx_pending,
171 "Number of TLS 1.0 records waiting for earlier TLS records");
173 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_tx_queued);
174 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_inqueue, CTLFLAG_RD,
176 "Number of TLS records in queue to tasks for SW encryption");
178 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_rx_queued);
179 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_rx_inqueue, CTLFLAG_RD,
181 "Number of TLS sockets in queue to tasks for SW decryption");
183 static COUNTER_U64_DEFINE_EARLY(ktls_offload_total);
184 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
185 CTLFLAG_RD, &ktls_offload_total,
186 "Total successful TLS setups (parameters set)");
188 static COUNTER_U64_DEFINE_EARLY(ktls_offload_enable_calls);
189 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
190 CTLFLAG_RD, &ktls_offload_enable_calls,
191 "Total number of TLS enable calls made");
193 static COUNTER_U64_DEFINE_EARLY(ktls_offload_active);
194 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
195 &ktls_offload_active, "Total Active TLS sessions");
197 static COUNTER_U64_DEFINE_EARLY(ktls_offload_corrupted_records);
198 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, corrupted_records, CTLFLAG_RD,
199 &ktls_offload_corrupted_records, "Total corrupted TLS records received");
201 static COUNTER_U64_DEFINE_EARLY(ktls_offload_failed_crypto);
202 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
203 &ktls_offload_failed_crypto, "Total TLS crypto failures");
205 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_ifnet);
206 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
207 &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
209 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_sw);
210 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
211 &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
213 static COUNTER_U64_DEFINE_EARLY(ktls_switch_failed);
214 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
215 &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
217 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_disable_fail);
218 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, ifnet_disable_failed, CTLFLAG_RD,
219 &ktls_ifnet_disable_fail, "TLS sessions unable to switch to SW from ifnet");
221 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_disable_ok);
222 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, ifnet_disable_ok, CTLFLAG_RD,
223 &ktls_ifnet_disable_ok, "TLS sessions able to switch to SW from ifnet");
225 static COUNTER_U64_DEFINE_EARLY(ktls_destroy_task);
226 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, destroy_task, CTLFLAG_RD,
228 "Number of times ktls session was destroyed via taskqueue");
230 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
231 "Software TLS session stats");
232 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
233 "Hardware (ifnet) TLS session stats");
235 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
236 "TOE TLS session stats");
239 static COUNTER_U64_DEFINE_EARLY(ktls_sw_cbc);
240 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
241 "Active number of software TLS sessions using AES-CBC");
243 static COUNTER_U64_DEFINE_EARLY(ktls_sw_gcm);
244 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
245 "Active number of software TLS sessions using AES-GCM");
247 static COUNTER_U64_DEFINE_EARLY(ktls_sw_chacha20);
248 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, chacha20, CTLFLAG_RD,
250 "Active number of software TLS sessions using Chacha20-Poly1305");
252 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_cbc);
253 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
255 "Active number of ifnet TLS sessions using AES-CBC");
257 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_gcm);
258 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
260 "Active number of ifnet TLS sessions using AES-GCM");
262 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_chacha20);
263 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, chacha20, CTLFLAG_RD,
264 &ktls_ifnet_chacha20,
265 "Active number of ifnet TLS sessions using Chacha20-Poly1305");
267 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset);
268 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
269 &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
271 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_dropped);
272 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
273 &ktls_ifnet_reset_dropped,
274 "TLS sessions dropped after failing to update ifnet send tag");
276 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_failed);
277 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
278 &ktls_ifnet_reset_failed,
279 "TLS sessions that failed to allocate a new ifnet send tag");
281 static int ktls_ifnet_permitted;
282 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
283 &ktls_ifnet_permitted, 1,
284 "Whether to permit hardware (ifnet) TLS sessions");
287 static COUNTER_U64_DEFINE_EARLY(ktls_toe_cbc);
288 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
290 "Active number of TOE TLS sessions using AES-CBC");
292 static COUNTER_U64_DEFINE_EARLY(ktls_toe_gcm);
293 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
295 "Active number of TOE TLS sessions using AES-GCM");
297 static COUNTER_U64_DEFINE_EARLY(ktls_toe_chacha20);
298 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, chacha20, CTLFLAG_RD,
300 "Active number of TOE TLS sessions using Chacha20-Poly1305");
303 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
305 #if defined(INET) || defined(INET6)
306 static void ktls_reset_receive_tag(void *context, int pending);
307 static void ktls_reset_send_tag(void *context, int pending);
309 static void ktls_work_thread(void *ctx);
310 static void ktls_alloc_thread(void *ctx);
312 #if defined(INET) || defined(INET6)
314 ktls_get_cpu(struct socket *so)
318 struct ktls_domain_info *di;
324 cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
325 if (cpuid != NETISR_CPUID_NONE)
329 * Just use the flowid to shard connections in a repeatable
330 * fashion. Note that TLS 1.0 sessions rely on the
331 * serialization provided by having the same connection use
335 if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
336 di = &ktls_domains[inp->inp_numa_domain];
337 cpuid = di->cpu[inp->inp_flowid % di->count];
340 cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
346 ktls_buffer_import(void *arg, void **store, int count, int domain, int flags)
351 KASSERT((ktls_maxlen & PAGE_MASK) == 0,
352 ("%s: ktls max length %d is not page size-aligned",
353 __func__, ktls_maxlen));
355 req = VM_ALLOC_WIRED | VM_ALLOC_NODUMP | malloc2vm_flags(flags);
356 for (i = 0; i < count; i++) {
357 m = vm_page_alloc_noobj_contig_domain(domain, req,
358 atop(ktls_maxlen), 0, ~0ul, PAGE_SIZE, 0,
362 store[i] = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
368 ktls_buffer_release(void *arg __unused, void **store, int count)
373 for (i = 0; i < count; i++) {
374 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)store[i]));
375 for (j = 0; j < atop(ktls_maxlen); j++) {
376 (void)vm_page_unwire_noq(m + j);
383 ktls_free_mext_contig(struct mbuf *m)
386 uma_zfree(ktls_buffer_zone, (void *)PHYS_TO_DMAP(m->m_epg_pa[0]));
394 int count, domain, error, i;
396 ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
399 ktls_session_zone = uma_zcreate("ktls_session",
400 sizeof(struct ktls_session),
401 NULL, NULL, NULL, NULL,
404 if (ktls_sw_buffer_cache) {
405 ktls_buffer_zone = uma_zcache_create("ktls_buffers",
406 roundup2(ktls_maxlen, PAGE_SIZE), NULL, NULL, NULL, NULL,
407 ktls_buffer_import, ktls_buffer_release, NULL,
408 UMA_ZONE_FIRSTTOUCH);
412 * Initialize the workqueues to run the TLS work. We create a
413 * work queue for each CPU.
416 STAILQ_INIT(&ktls_wq[i].m_head);
417 STAILQ_INIT(&ktls_wq[i].so_head);
418 mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
419 if (ktls_bind_threads > 1) {
421 domain = pc->pc_domain;
422 count = ktls_domains[domain].count;
423 ktls_domains[domain].cpu[count] = i;
424 ktls_domains[domain].count++;
426 ktls_cpuid_lookup[ktls_number_threads] = i;
427 ktls_number_threads++;
431 * If we somehow have an empty domain, fall back to choosing
432 * among all KTLS threads.
434 if (ktls_bind_threads > 1) {
435 for (i = 0; i < vm_ndomains; i++) {
436 if (ktls_domains[i].count == 0) {
437 ktls_bind_threads = 1;
443 /* Start kthreads for each workqueue. */
445 error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
446 &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
448 printf("Can't add KTLS thread %d error %d\n", i, error);
454 * Start an allocation thread per-domain to perform blocking allocations
455 * of 16k physically contiguous TLS crypto destination buffers.
457 if (ktls_sw_buffer_cache) {
458 for (domain = 0; domain < vm_ndomains; domain++) {
459 if (VM_DOMAIN_EMPTY(domain))
461 if (CPU_EMPTY(&cpuset_domain[domain]))
463 error = kproc_kthread_add(ktls_alloc_thread,
464 &ktls_domains[domain], &ktls_proc,
465 &ktls_domains[domain].alloc_td.td,
466 0, 0, "KTLS", "alloc_%d", domain);
468 printf("Can't add KTLS alloc thread %d error %d\n",
476 printf("KTLS: Initialized %d threads\n", ktls_number_threads);
481 ktls_start_kthreads(void)
486 state = atomic_load_acq_int(&ktls_init_state);
487 if (__predict_true(state > 0))
492 sx_xlock(&ktls_init_lock);
493 if (ktls_init_state != 0) {
494 sx_xunlock(&ktls_init_lock);
503 atomic_store_rel_int(&ktls_init_state, state);
504 sx_xunlock(&ktls_init_lock);
508 #if defined(INET) || defined(INET6)
510 ktls_create_session(struct socket *so, struct tls_enable *en,
511 struct ktls_session **tlsp, int direction)
513 struct ktls_session *tls;
516 /* Only TLS 1.0 - 1.3 are supported. */
517 if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
519 if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
520 en->tls_vminor > TLS_MINOR_VER_THREE)
523 if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
525 if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
527 if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
530 /* All supported algorithms require a cipher key. */
531 if (en->cipher_key_len == 0)
534 /* No flags are currently supported. */
538 /* Common checks for supported algorithms. */
539 switch (en->cipher_algorithm) {
540 case CRYPTO_AES_NIST_GCM_16:
542 * auth_algorithm isn't used, but permit GMAC values
545 switch (en->auth_algorithm) {
547 #ifdef COMPAT_FREEBSD12
548 /* XXX: Really 13.0-current COMPAT. */
549 case CRYPTO_AES_128_NIST_GMAC:
550 case CRYPTO_AES_192_NIST_GMAC:
551 case CRYPTO_AES_256_NIST_GMAC:
557 if (en->auth_key_len != 0)
559 switch (en->tls_vminor) {
560 case TLS_MINOR_VER_TWO:
561 if (en->iv_len != TLS_AEAD_GCM_LEN)
564 case TLS_MINOR_VER_THREE:
565 if (en->iv_len != TLS_1_3_GCM_IV_LEN)
573 switch (en->auth_algorithm) {
574 case CRYPTO_SHA1_HMAC:
576 case CRYPTO_SHA2_256_HMAC:
577 case CRYPTO_SHA2_384_HMAC:
578 if (en->tls_vminor != TLS_MINOR_VER_TWO)
584 if (en->auth_key_len == 0)
588 * TLS 1.0 requires an implicit IV. TLS 1.1 and 1.2
591 switch (en->tls_vminor) {
592 case TLS_MINOR_VER_ZERO:
593 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
596 case TLS_MINOR_VER_ONE:
597 case TLS_MINOR_VER_TWO:
598 /* Ignore any supplied IV. */
605 case CRYPTO_CHACHA20_POLY1305:
606 if (en->auth_algorithm != 0 || en->auth_key_len != 0)
608 if (en->tls_vminor != TLS_MINOR_VER_TWO &&
609 en->tls_vminor != TLS_MINOR_VER_THREE)
611 if (en->iv_len != TLS_CHACHA20_IV_LEN)
618 error = ktls_start_kthreads();
622 tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
624 counter_u64_add(ktls_offload_active, 1);
626 refcount_init(&tls->refcount, 1);
627 if (direction == KTLS_RX) {
628 TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_receive_tag, tls);
630 TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
631 tls->inp = so->so_pcb;
636 tls->wq_index = ktls_get_cpu(so);
638 tls->params.cipher_algorithm = en->cipher_algorithm;
639 tls->params.auth_algorithm = en->auth_algorithm;
640 tls->params.tls_vmajor = en->tls_vmajor;
641 tls->params.tls_vminor = en->tls_vminor;
642 tls->params.flags = en->flags;
643 tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
645 /* Set the header and trailer lengths. */
646 tls->params.tls_hlen = sizeof(struct tls_record_layer);
647 switch (en->cipher_algorithm) {
648 case CRYPTO_AES_NIST_GCM_16:
650 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
651 * nonce. TLS 1.3 uses a 12 byte implicit IV.
653 if (en->tls_vminor < TLS_MINOR_VER_THREE)
654 tls->params.tls_hlen += sizeof(uint64_t);
655 tls->params.tls_tlen = AES_GMAC_HASH_LEN;
656 tls->params.tls_bs = 1;
659 switch (en->auth_algorithm) {
660 case CRYPTO_SHA1_HMAC:
661 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
662 /* Implicit IV, no nonce. */
663 tls->sequential_records = true;
664 tls->next_seqno = be64dec(en->rec_seq);
665 STAILQ_INIT(&tls->pending_records);
667 tls->params.tls_hlen += AES_BLOCK_LEN;
669 tls->params.tls_tlen = AES_BLOCK_LEN +
672 case CRYPTO_SHA2_256_HMAC:
673 tls->params.tls_hlen += AES_BLOCK_LEN;
674 tls->params.tls_tlen = AES_BLOCK_LEN +
677 case CRYPTO_SHA2_384_HMAC:
678 tls->params.tls_hlen += AES_BLOCK_LEN;
679 tls->params.tls_tlen = AES_BLOCK_LEN +
683 panic("invalid hmac");
685 tls->params.tls_bs = AES_BLOCK_LEN;
687 case CRYPTO_CHACHA20_POLY1305:
689 * Chacha20 uses a 12 byte implicit IV.
691 tls->params.tls_tlen = POLY1305_HASH_LEN;
692 tls->params.tls_bs = 1;
695 panic("invalid cipher");
699 * TLS 1.3 includes optional padding which we do not support,
700 * and also puts the "real" record type at the end of the
703 if (en->tls_vminor == TLS_MINOR_VER_THREE)
704 tls->params.tls_tlen += sizeof(uint8_t);
706 KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
707 ("TLS header length too long: %d", tls->params.tls_hlen));
708 KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
709 ("TLS trailer length too long: %d", tls->params.tls_tlen));
711 if (en->auth_key_len != 0) {
712 tls->params.auth_key_len = en->auth_key_len;
713 tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
715 error = copyin(en->auth_key, tls->params.auth_key,
721 tls->params.cipher_key_len = en->cipher_key_len;
722 tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
723 error = copyin(en->cipher_key, tls->params.cipher_key,
729 * This holds the implicit portion of the nonce for AEAD
730 * ciphers and the initial implicit IV for TLS 1.0. The
731 * explicit portions of the IV are generated in ktls_frame().
733 if (en->iv_len != 0) {
734 tls->params.iv_len = en->iv_len;
735 error = copyin(en->iv, tls->params.iv, en->iv_len);
740 * For TLS 1.2 with GCM, generate an 8-byte nonce as a
741 * counter to generate unique explicit IVs.
743 * Store this counter in the last 8 bytes of the IV
744 * array so that it is 8-byte aligned.
746 if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
747 en->tls_vminor == TLS_MINOR_VER_TWO)
748 arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
759 static struct ktls_session *
760 ktls_clone_session(struct ktls_session *tls, int direction)
762 struct ktls_session *tls_new;
764 tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
766 counter_u64_add(ktls_offload_active, 1);
768 refcount_init(&tls_new->refcount, 1);
769 if (direction == KTLS_RX) {
770 TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_receive_tag,
773 TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_send_tag,
775 tls_new->inp = tls->inp;
777 in_pcbref(tls_new->inp);
780 /* Copy fields from existing session. */
781 tls_new->params = tls->params;
782 tls_new->wq_index = tls->wq_index;
784 /* Deep copy keys. */
785 if (tls_new->params.auth_key != NULL) {
786 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
788 memcpy(tls_new->params.auth_key, tls->params.auth_key,
789 tls->params.auth_key_len);
792 tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
794 memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
795 tls->params.cipher_key_len);
802 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
810 if (inp->inp_flags & INP_DROPPED) {
814 if (inp->inp_socket == NULL) {
819 if (!(tp->t_flags & TF_TOE)) {
824 error = tcp_offload_alloc_tls_session(tp, tls, direction);
827 tls->mode = TCP_TLS_MODE_TOE;
828 switch (tls->params.cipher_algorithm) {
830 counter_u64_add(ktls_toe_cbc, 1);
832 case CRYPTO_AES_NIST_GCM_16:
833 counter_u64_add(ktls_toe_gcm, 1);
835 case CRYPTO_CHACHA20_POLY1305:
836 counter_u64_add(ktls_toe_chacha20, 1);
845 * Common code used when first enabling ifnet TLS on a connection or
846 * when allocating a new ifnet TLS session due to a routing change.
847 * This function allocates a new TLS send tag on whatever interface
848 * the connection is currently routed over.
851 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
852 struct m_snd_tag **mstp)
854 union if_snd_tag_alloc_params params;
856 struct nhop_object *nh;
861 if (inp->inp_flags & INP_DROPPED) {
865 if (inp->inp_socket == NULL) {
872 * Check administrative controls on ifnet TLS to determine if
873 * ifnet TLS should be denied.
875 * - Always permit 'force' requests.
876 * - ktls_ifnet_permitted == 0: always deny.
878 if (!force && ktls_ifnet_permitted == 0) {
884 * XXX: Use the cached route in the inpcb to find the
885 * interface. This should perhaps instead use
886 * rtalloc1_fib(dst, 0, 0, fibnum). Since KTLS is only
887 * enabled after a connection has completed key negotiation in
888 * userland, the cached route will be present in practice.
890 nh = inp->inp_route.ro_nh;
899 * Allocate a TLS + ratelimit tag if the connection has an
900 * existing pacing rate.
902 if (tp->t_pacing_rate != -1 &&
903 (ifp->if_capenable & IFCAP_TXTLS_RTLMT) != 0) {
904 params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
905 params.tls_rate_limit.inp = inp;
906 params.tls_rate_limit.tls = tls;
907 params.tls_rate_limit.max_rate = tp->t_pacing_rate;
909 params.hdr.type = IF_SND_TAG_TYPE_TLS;
910 params.tls.inp = inp;
911 params.tls.tls = tls;
913 params.hdr.flowid = inp->inp_flowid;
914 params.hdr.flowtype = inp->inp_flowtype;
915 params.hdr.numa_domain = inp->inp_numa_domain;
918 if ((ifp->if_capenable & IFCAP_MEXTPG) == 0) {
922 if (inp->inp_vflag & INP_IPV6) {
923 if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
928 if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
933 error = m_snd_tag_alloc(ifp, ¶ms, mstp);
940 * Allocate an initial TLS receive tag for doing HW decryption of TLS
943 * This function allocates a new TLS receive tag on whatever interface
944 * the connection is currently routed over. If the connection ends up
945 * using a different interface for receive this will get fixed up via
946 * ktls_input_ifp_mismatch as future packets arrive.
949 ktls_alloc_rcv_tag(struct inpcb *inp, struct ktls_session *tls,
950 struct m_snd_tag **mstp)
952 union if_snd_tag_alloc_params params;
954 struct nhop_object *nh;
957 if (!ktls_ocf_recrypt_supported(tls))
961 if (inp->inp_flags & INP_DROPPED) {
965 if (inp->inp_socket == NULL) {
971 * Check administrative controls on ifnet TLS to determine if
972 * ifnet TLS should be denied.
974 if (ktls_ifnet_permitted == 0) {
980 * XXX: As with ktls_alloc_snd_tag, use the cached route in
981 * the inpcb to find the interface.
983 nh = inp->inp_route.ro_nh;
992 params.hdr.type = IF_SND_TAG_TYPE_TLS_RX;
993 params.hdr.flowid = inp->inp_flowid;
994 params.hdr.flowtype = inp->inp_flowtype;
995 params.hdr.numa_domain = inp->inp_numa_domain;
996 params.tls_rx.inp = inp;
997 params.tls_rx.tls = tls;
998 params.tls_rx.vlan_id = 0;
1002 if (inp->inp_vflag & INP_IPV6) {
1003 if ((ifp->if_capenable2 & IFCAP2_RXTLS6) == 0) {
1008 if ((ifp->if_capenable2 & IFCAP2_RXTLS4) == 0) {
1013 error = m_snd_tag_alloc(ifp, ¶ms, mstp);
1016 * If this connection is over a vlan, vlan_snd_tag_alloc
1017 * rewrites vlan_id with the saved interface. Save the VLAN
1018 * ID for use in ktls_reset_receive_tag which allocates new
1019 * receive tags directly from the leaf interface bypassing
1023 tls->rx_vlan_id = params.tls_rx.vlan_id;
1029 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, int direction,
1032 struct m_snd_tag *mst;
1035 switch (direction) {
1037 error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
1038 if (__predict_false(error != 0))
1042 KASSERT(!force, ("%s: forced receive tag", __func__));
1043 error = ktls_alloc_rcv_tag(so->so_pcb, tls, &mst);
1044 if (__predict_false(error != 0))
1048 __assert_unreachable();
1051 tls->mode = TCP_TLS_MODE_IFNET;
1054 switch (tls->params.cipher_algorithm) {
1055 case CRYPTO_AES_CBC:
1056 counter_u64_add(ktls_ifnet_cbc, 1);
1058 case CRYPTO_AES_NIST_GCM_16:
1059 counter_u64_add(ktls_ifnet_gcm, 1);
1061 case CRYPTO_CHACHA20_POLY1305:
1062 counter_u64_add(ktls_ifnet_chacha20, 1);
1072 ktls_use_sw(struct ktls_session *tls)
1074 tls->mode = TCP_TLS_MODE_SW;
1075 switch (tls->params.cipher_algorithm) {
1076 case CRYPTO_AES_CBC:
1077 counter_u64_add(ktls_sw_cbc, 1);
1079 case CRYPTO_AES_NIST_GCM_16:
1080 counter_u64_add(ktls_sw_gcm, 1);
1082 case CRYPTO_CHACHA20_POLY1305:
1083 counter_u64_add(ktls_sw_chacha20, 1);
1089 ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
1093 error = ktls_ocf_try(so, tls, direction);
1101 * KTLS RX stores data in the socket buffer as a list of TLS records,
1102 * where each record is stored as a control message containg the TLS
1103 * header followed by data mbufs containing the decrypted data. This
1104 * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
1105 * both encrypted and decrypted data. TLS records decrypted by a NIC
1106 * should be queued to the socket buffer as records, but encrypted
1107 * data which needs to be decrypted by software arrives as a stream of
1108 * regular mbufs which need to be converted. In addition, there may
1109 * already be pending encrypted data in the socket buffer when KTLS RX
1112 * To manage not-yet-decrypted data for KTLS RX, the following scheme
1115 * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
1117 * - ktls_check_rx checks this chain of mbufs reading the TLS header
1118 * from the first mbuf. Once all of the data for that TLS record is
1119 * queued, the socket is queued to a worker thread.
1121 * - The worker thread calls ktls_decrypt to decrypt TLS records in
1122 * the TLS chain. Each TLS record is detached from the TLS chain,
1123 * decrypted, and inserted into the regular socket buffer chain as
1124 * record starting with a control message holding the TLS header and
1125 * a chain of mbufs holding the encrypted data.
1129 sb_mark_notready(struct sockbuf *sb)
1136 sb->sb_mbtail = NULL;
1137 sb->sb_lastrecord = NULL;
1138 for (; m != NULL; m = m->m_next) {
1139 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
1141 KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
1143 KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
1145 m->m_flags |= M_NOTREADY;
1146 sb->sb_acc -= m->m_len;
1147 sb->sb_tlscc += m->m_len;
1148 sb->sb_mtlstail = m;
1150 KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
1151 ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
1156 * Return information about the pending TLS data in a socket
1157 * buffer. On return, 'seqno' is set to the sequence number
1158 * of the next TLS record to be received, 'resid' is set to
1159 * the amount of bytes still needed for the last pending
1160 * record. The function returns 'false' if the last pending
1161 * record contains a partial TLS header. In that case, 'resid'
1162 * is the number of bytes needed to complete the TLS header.
1165 ktls_pending_rx_info(struct sockbuf *sb, uint64_t *seqnop, size_t *residp)
1167 struct tls_record_layer hdr;
1171 u_int offset, record_len;
1173 SOCKBUF_LOCK_ASSERT(sb);
1174 MPASS(sb->sb_flags & SB_TLS_RX);
1175 seqno = sb->sb_tls_seqno;
1176 resid = sb->sb_tlscc;
1189 if (resid < sizeof(hdr)) {
1191 *residp = sizeof(hdr) - resid;
1195 m_copydata(m, offset, sizeof(hdr), (void *)&hdr);
1197 record_len = sizeof(hdr) + ntohs(hdr.tls_length);
1198 if (resid <= record_len) {
1200 *residp = record_len - resid;
1203 resid -= record_len;
1205 while (record_len != 0) {
1206 if (m->m_len - offset > record_len) {
1207 offset += record_len;
1211 record_len -= (m->m_len - offset);
1219 ktls_enable_rx(struct socket *so, struct tls_enable *en)
1221 struct ktls_session *tls;
1224 if (!ktls_offload_enable)
1226 if (SOLISTENING(so))
1229 counter_u64_add(ktls_offload_enable_calls, 1);
1232 * This should always be true since only the TCP socket option
1233 * invokes this function.
1235 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1239 * XXX: Don't overwrite existing sessions. We should permit
1240 * this to support rekeying in the future.
1242 if (so->so_rcv.sb_tls_info != NULL)
1245 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1248 error = ktls_create_session(so, en, &tls, KTLS_RX);
1252 error = ktls_ocf_try(so, tls, KTLS_RX);
1258 /* Mark the socket as using TLS offload. */
1259 SOCKBUF_LOCK(&so->so_rcv);
1260 so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1261 so->so_rcv.sb_tls_info = tls;
1262 so->so_rcv.sb_flags |= SB_TLS_RX;
1264 /* Mark existing data as not ready until it can be decrypted. */
1265 sb_mark_notready(&so->so_rcv);
1266 ktls_check_rx(&so->so_rcv);
1267 SOCKBUF_UNLOCK(&so->so_rcv);
1269 /* Prefer TOE -> ifnet TLS -> software TLS. */
1271 error = ktls_try_toe(so, tls, KTLS_RX);
1274 error = ktls_try_ifnet(so, tls, KTLS_RX, false);
1278 counter_u64_add(ktls_offload_total, 1);
1284 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1286 struct ktls_session *tls;
1291 if (!ktls_offload_enable)
1293 if (SOLISTENING(so))
1296 counter_u64_add(ktls_offload_enable_calls, 1);
1299 * This should always be true since only the TCP socket option
1300 * invokes this function.
1302 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1306 * XXX: Don't overwrite existing sessions. We should permit
1307 * this to support rekeying in the future.
1309 if (so->so_snd.sb_tls_info != NULL)
1312 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1315 /* TLS requires ext pgs */
1316 if (mb_use_ext_pgs == 0)
1319 error = ktls_create_session(so, en, &tls, KTLS_TX);
1323 /* Prefer TOE -> ifnet TLS -> software TLS. */
1325 error = ktls_try_toe(so, tls, KTLS_TX);
1328 error = ktls_try_ifnet(so, tls, KTLS_TX, false);
1330 error = ktls_try_sw(so, tls, KTLS_TX);
1337 error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1344 * Write lock the INP when setting sb_tls_info so that
1345 * routines in tcp_ratelimit.c can read sb_tls_info while
1346 * holding the INP lock.
1350 SOCKBUF_LOCK(&so->so_snd);
1351 so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1352 so->so_snd.sb_tls_info = tls;
1353 if (tls->mode != TCP_TLS_MODE_SW) {
1354 tp = intotcpcb(inp);
1355 MPASS(tp->t_nic_ktls_xmit == 0);
1356 tp->t_nic_ktls_xmit = 1;
1357 if (tp->t_fb->tfb_hwtls_change != NULL)
1358 (*tp->t_fb->tfb_hwtls_change)(tp, 1);
1360 SOCKBUF_UNLOCK(&so->so_snd);
1362 SOCK_IO_SEND_UNLOCK(so);
1364 counter_u64_add(ktls_offload_total, 1);
1370 ktls_get_rx_mode(struct socket *so, int *modep)
1372 struct ktls_session *tls;
1373 struct inpcb *inp __diagused;
1375 if (SOLISTENING(so))
1378 INP_WLOCK_ASSERT(inp);
1379 SOCK_RECVBUF_LOCK(so);
1380 tls = so->so_rcv.sb_tls_info;
1382 *modep = TCP_TLS_MODE_NONE;
1385 SOCK_RECVBUF_UNLOCK(so);
1390 * ktls_get_rx_sequence - get the next TCP- and TLS- sequence number.
1392 * This function gets information about the next TCP- and TLS-
1393 * sequence number to be processed by the TLS receive worker
1394 * thread. The information is extracted from the given "inpcb"
1395 * structure. The values are stored in host endian format at the two
1396 * given output pointer locations. The TCP sequence number points to
1397 * the beginning of the TLS header.
1399 * This function returns zero on success, else a non-zero error code
1403 ktls_get_rx_sequence(struct inpcb *inp, uint32_t *tcpseq, uint64_t *tlsseq)
1409 so = inp->inp_socket;
1410 if (__predict_false(so == NULL)) {
1414 if (inp->inp_flags & INP_DROPPED) {
1416 return (ECONNRESET);
1419 tp = intotcpcb(inp);
1422 SOCKBUF_LOCK(&so->so_rcv);
1423 *tcpseq = tp->rcv_nxt - so->so_rcv.sb_tlscc;
1424 *tlsseq = so->so_rcv.sb_tls_seqno;
1425 SOCKBUF_UNLOCK(&so->so_rcv);
1433 ktls_get_tx_mode(struct socket *so, int *modep)
1435 struct ktls_session *tls;
1436 struct inpcb *inp __diagused;
1438 if (SOLISTENING(so))
1441 INP_WLOCK_ASSERT(inp);
1442 SOCK_SENDBUF_LOCK(so);
1443 tls = so->so_snd.sb_tls_info;
1445 *modep = TCP_TLS_MODE_NONE;
1448 SOCK_SENDBUF_UNLOCK(so);
1453 * Switch between SW and ifnet TLS sessions as requested.
1456 ktls_set_tx_mode(struct socket *so, int mode)
1458 struct ktls_session *tls, *tls_new;
1463 if (SOLISTENING(so))
1466 case TCP_TLS_MODE_SW:
1467 case TCP_TLS_MODE_IFNET:
1474 INP_WLOCK_ASSERT(inp);
1475 tp = intotcpcb(inp);
1477 if (mode == TCP_TLS_MODE_IFNET) {
1478 /* Don't allow enabling ifnet ktls multiple times */
1479 if (tp->t_nic_ktls_xmit)
1482 * Don't enable ifnet ktls if we disabled it due to an
1483 * excessive retransmission rate
1485 if (tp->t_nic_ktls_xmit_dis)
1489 SOCKBUF_LOCK(&so->so_snd);
1490 tls = so->so_snd.sb_tls_info;
1492 SOCKBUF_UNLOCK(&so->so_snd);
1496 if (tls->mode == mode) {
1497 SOCKBUF_UNLOCK(&so->so_snd);
1501 tls = ktls_hold(tls);
1502 SOCKBUF_UNLOCK(&so->so_snd);
1505 tls_new = ktls_clone_session(tls, KTLS_TX);
1507 if (mode == TCP_TLS_MODE_IFNET)
1508 error = ktls_try_ifnet(so, tls_new, KTLS_TX, true);
1510 error = ktls_try_sw(so, tls_new, KTLS_TX);
1512 counter_u64_add(ktls_switch_failed, 1);
1519 error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1521 counter_u64_add(ktls_switch_failed, 1);
1529 * If we raced with another session change, keep the existing
1532 if (tls != so->so_snd.sb_tls_info) {
1533 counter_u64_add(ktls_switch_failed, 1);
1534 SOCK_IO_SEND_UNLOCK(so);
1542 SOCKBUF_LOCK(&so->so_snd);
1543 so->so_snd.sb_tls_info = tls_new;
1544 if (tls_new->mode != TCP_TLS_MODE_SW) {
1545 MPASS(tp->t_nic_ktls_xmit == 0);
1546 tp->t_nic_ktls_xmit = 1;
1547 if (tp->t_fb->tfb_hwtls_change != NULL)
1548 (*tp->t_fb->tfb_hwtls_change)(tp, 1);
1550 SOCKBUF_UNLOCK(&so->so_snd);
1551 SOCK_IO_SEND_UNLOCK(so);
1554 * Drop two references on 'tls'. The first is for the
1555 * ktls_hold() above. The second drops the reference from the
1558 KASSERT(tls->refcount >= 2, ("too few references on old session"));
1562 if (mode == TCP_TLS_MODE_IFNET)
1563 counter_u64_add(ktls_switch_to_ifnet, 1);
1565 counter_u64_add(ktls_switch_to_sw, 1);
1571 * Try to allocate a new TLS receive tag. This task is scheduled when
1572 * sbappend_ktls_rx detects an input path change. If a new tag is
1573 * allocated, replace the tag in the TLS session. If a new tag cannot
1574 * be allocated, let the session fall back to software decryption.
1577 ktls_reset_receive_tag(void *context, int pending)
1579 union if_snd_tag_alloc_params params;
1580 struct ktls_session *tls;
1581 struct m_snd_tag *mst;
1587 MPASS(pending == 1);
1595 if (inp->inp_flags & INP_DROPPED) {
1600 SOCKBUF_LOCK(&so->so_rcv);
1602 tls->snd_tag = NULL;
1604 m_snd_tag_rele(mst);
1608 SOCKBUF_UNLOCK(&so->so_rcv);
1610 params.hdr.type = IF_SND_TAG_TYPE_TLS_RX;
1611 params.hdr.flowid = inp->inp_flowid;
1612 params.hdr.flowtype = inp->inp_flowtype;
1613 params.hdr.numa_domain = inp->inp_numa_domain;
1614 params.tls_rx.inp = inp;
1615 params.tls_rx.tls = tls;
1616 params.tls_rx.vlan_id = tls->rx_vlan_id;
1619 if (inp->inp_vflag & INP_IPV6) {
1620 if ((ifp->if_capenable2 & IFCAP2_RXTLS6) == 0)
1623 if ((ifp->if_capenable2 & IFCAP2_RXTLS4) == 0)
1627 error = m_snd_tag_alloc(ifp, ¶ms, &mst);
1629 SOCKBUF_LOCK(&so->so_rcv);
1631 SOCKBUF_UNLOCK(&so->so_rcv);
1633 counter_u64_add(ktls_ifnet_reset, 1);
1636 * Just fall back to software decryption if a tag
1637 * cannot be allocated leaving the connection intact.
1638 * If a future input path change switches to another
1639 * interface this connection will resume ifnet TLS.
1641 counter_u64_add(ktls_ifnet_reset_failed, 1);
1645 mtx_pool_lock(mtxpool_sleep, tls);
1646 tls->reset_pending = false;
1647 mtx_pool_unlock(mtxpool_sleep, tls);
1656 * Try to allocate a new TLS send tag. This task is scheduled when
1657 * ip_output detects a route change while trying to transmit a packet
1658 * holding a TLS record. If a new tag is allocated, replace the tag
1659 * in the TLS session. Subsequent packets on the connection will use
1660 * the new tag. If a new tag cannot be allocated, drop the
1664 ktls_reset_send_tag(void *context, int pending)
1666 struct epoch_tracker et;
1667 struct ktls_session *tls;
1668 struct m_snd_tag *old, *new;
1673 MPASS(pending == 1);
1679 * Free the old tag first before allocating a new one.
1680 * ip[6]_output_send() will treat a NULL send tag the same as
1681 * an ifp mismatch and drop packets until a new tag is
1684 * Write-lock the INP when changing tls->snd_tag since
1685 * ip[6]_output_send() holds a read-lock when reading the
1690 tls->snd_tag = NULL;
1693 m_snd_tag_rele(old);
1695 error = ktls_alloc_snd_tag(inp, tls, true, &new);
1700 mtx_pool_lock(mtxpool_sleep, tls);
1701 tls->reset_pending = false;
1702 mtx_pool_unlock(mtxpool_sleep, tls);
1705 counter_u64_add(ktls_ifnet_reset, 1);
1708 * XXX: Should we kick tcp_output explicitly now that
1709 * the send tag is fixed or just rely on timers?
1712 NET_EPOCH_ENTER(et);
1714 if (!(inp->inp_flags & INP_DROPPED)) {
1715 tp = intotcpcb(inp);
1716 CURVNET_SET(inp->inp_vnet);
1717 tp = tcp_drop(tp, ECONNABORTED);
1720 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1725 counter_u64_add(ktls_ifnet_reset_failed, 1);
1728 * Leave reset_pending true to avoid future tasks while
1729 * the socket goes away.
1737 ktls_input_ifp_mismatch(struct sockbuf *sb, struct ifnet *ifp)
1739 struct ktls_session *tls;
1742 SOCKBUF_LOCK_ASSERT(sb);
1743 KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1745 so = __containerof(sb, struct socket, so_rcv);
1747 tls = sb->sb_tls_info;
1748 if_rele(tls->rx_ifp);
1753 * See if we should schedule a task to update the receive tag for
1756 mtx_pool_lock(mtxpool_sleep, tls);
1757 if (!tls->reset_pending) {
1758 (void) ktls_hold(tls);
1761 tls->reset_pending = true;
1762 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1764 mtx_pool_unlock(mtxpool_sleep, tls);
1768 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1774 INP_LOCK_ASSERT(inp);
1777 * See if we should schedule a task to update the send tag for
1780 mtx_pool_lock(mtxpool_sleep, tls);
1781 if (!tls->reset_pending) {
1782 (void) ktls_hold(tls);
1783 tls->reset_pending = true;
1784 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1786 mtx_pool_unlock(mtxpool_sleep, tls);
1792 ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1794 union if_snd_tag_modify_params params = {
1795 .rate_limit.max_rate = max_pacing_rate,
1796 .rate_limit.flags = M_NOWAIT,
1798 struct m_snd_tag *mst;
1800 /* Can't get to the inp, but it should be locked. */
1801 /* INP_LOCK_ASSERT(inp); */
1803 MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1805 if (tls->snd_tag == NULL) {
1807 * Resetting send tag, ignore this change. The
1808 * pending reset may or may not see this updated rate
1809 * in the tcpcb. If it doesn't, we will just lose
1818 MPASS(mst->sw->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1820 return (mst->sw->snd_tag_modify(mst, ¶ms));
1826 ktls_destroy_help(void *context, int pending __unused)
1828 ktls_destroy(context);
1832 ktls_destroy(struct ktls_session *tls)
1838 MPASS(tls->refcount == 0);
1842 wlocked = INP_WLOCKED(inp);
1843 if (!wlocked && !INP_TRY_WLOCK(inp)) {
1845 * rwlocks read locks are anonymous, and there
1846 * is no way to know if our current thread
1847 * holds an rlock on the inp. As a rough
1848 * estimate, check to see if the thread holds
1849 * *any* rlocks at all. If it does not, then we
1850 * know that we don't hold the inp rlock, and
1851 * can safely take the wlock
1854 if (curthread->td_rw_rlocks == 0) {
1858 * We might hold the rlock, so let's
1859 * do the destroy in a taskqueue
1860 * context to avoid a potential
1861 * deadlock. This should be very
1864 counter_u64_add(ktls_destroy_task, 1);
1865 TASK_INIT(&tls->destroy_task, 0,
1866 ktls_destroy_help, tls);
1867 (void)taskqueue_enqueue(taskqueue_thread,
1868 &tls->destroy_task);
1874 if (tls->sequential_records) {
1878 STAILQ_FOREACH_SAFE(m, &tls->pending_records, m_epg_stailq, n) {
1879 page_count = m->m_epg_enc_cnt;
1880 while (page_count > 0) {
1881 KASSERT(page_count >= m->m_epg_nrdy,
1882 ("%s: too few pages", __func__));
1883 page_count -= m->m_epg_nrdy;
1889 counter_u64_add(ktls_offload_active, -1);
1890 switch (tls->mode) {
1891 case TCP_TLS_MODE_SW:
1892 switch (tls->params.cipher_algorithm) {
1893 case CRYPTO_AES_CBC:
1894 counter_u64_add(ktls_sw_cbc, -1);
1896 case CRYPTO_AES_NIST_GCM_16:
1897 counter_u64_add(ktls_sw_gcm, -1);
1899 case CRYPTO_CHACHA20_POLY1305:
1900 counter_u64_add(ktls_sw_chacha20, -1);
1904 case TCP_TLS_MODE_IFNET:
1905 switch (tls->params.cipher_algorithm) {
1906 case CRYPTO_AES_CBC:
1907 counter_u64_add(ktls_ifnet_cbc, -1);
1909 case CRYPTO_AES_NIST_GCM_16:
1910 counter_u64_add(ktls_ifnet_gcm, -1);
1912 case CRYPTO_CHACHA20_POLY1305:
1913 counter_u64_add(ktls_ifnet_chacha20, -1);
1916 if (tls->snd_tag != NULL)
1917 m_snd_tag_rele(tls->snd_tag);
1918 if (tls->rx_ifp != NULL)
1919 if_rele(tls->rx_ifp);
1921 INP_WLOCK_ASSERT(inp);
1922 tp = intotcpcb(inp);
1923 MPASS(tp->t_nic_ktls_xmit == 1);
1924 tp->t_nic_ktls_xmit = 0;
1928 case TCP_TLS_MODE_TOE:
1929 switch (tls->params.cipher_algorithm) {
1930 case CRYPTO_AES_CBC:
1931 counter_u64_add(ktls_toe_cbc, -1);
1933 case CRYPTO_AES_NIST_GCM_16:
1934 counter_u64_add(ktls_toe_gcm, -1);
1936 case CRYPTO_CHACHA20_POLY1305:
1937 counter_u64_add(ktls_toe_chacha20, -1);
1943 if (tls->ocf_session != NULL)
1945 if (tls->params.auth_key != NULL) {
1946 zfree(tls->params.auth_key, M_KTLS);
1947 tls->params.auth_key = NULL;
1948 tls->params.auth_key_len = 0;
1950 if (tls->params.cipher_key != NULL) {
1951 zfree(tls->params.cipher_key, M_KTLS);
1952 tls->params.cipher_key = NULL;
1953 tls->params.cipher_key_len = 0;
1956 INP_WLOCK_ASSERT(inp);
1957 if (!in_pcbrele_wlocked(inp) && !wlocked)
1960 explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
1962 uma_zfree(ktls_session_zone, tls);
1966 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1969 for (; m != NULL; m = m->m_next) {
1970 KASSERT((m->m_flags & M_EXTPG) != 0,
1971 ("ktls_seq: mapped mbuf %p", m));
1973 m->m_epg_seqno = sb->sb_tls_seqno;
1979 * Add TLS framing (headers and trailers) to a chain of mbufs. Each
1980 * mbuf in the chain must be an unmapped mbuf. The payload of the
1981 * mbuf must be populated with the payload of each TLS record.
1983 * The record_type argument specifies the TLS record type used when
1984 * populating the TLS header.
1986 * The enq_count argument on return is set to the number of pages of
1987 * payload data for this entire chain that need to be encrypted via SW
1988 * encryption. The returned value should be passed to ktls_enqueue
1989 * when scheduling encryption of this chain of mbufs. To handle the
1990 * special case of empty fragments for TLS 1.0 sessions, an empty
1991 * fragment counts as one page.
1994 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1995 uint8_t record_type)
1997 struct tls_record_layer *tlshdr;
2001 int maxlen __diagused;
2003 maxlen = tls->params.max_frame_len;
2005 for (m = top; m != NULL; m = m->m_next) {
2007 * All mbufs in the chain should be TLS records whose
2008 * payload does not exceed the maximum frame length.
2010 * Empty TLS 1.0 records are permitted when using CBC.
2012 KASSERT(m->m_len <= maxlen && m->m_len >= 0 &&
2013 (m->m_len > 0 || ktls_permit_empty_frames(tls)),
2014 ("ktls_frame: m %p len %d", m, m->m_len));
2017 * TLS frames require unmapped mbufs to store session
2020 KASSERT((m->m_flags & M_EXTPG) != 0,
2021 ("ktls_frame: mapped mbuf %p (top = %p)", m, top));
2025 /* Save a reference to the session. */
2026 m->m_epg_tls = ktls_hold(tls);
2028 m->m_epg_hdrlen = tls->params.tls_hlen;
2029 m->m_epg_trllen = tls->params.tls_tlen;
2030 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
2034 * AES-CBC pads messages to a multiple of the
2035 * block size. Note that the padding is
2036 * applied after the digest and the encryption
2037 * is done on the "plaintext || mac || padding".
2038 * At least one byte of padding is always
2041 * Compute the final trailer length assuming
2042 * at most one block of padding.
2043 * tls->params.tls_tlen is the maximum
2044 * possible trailer length (padding + digest).
2045 * delta holds the number of excess padding
2046 * bytes if the maximum were used. Those
2047 * extra bytes are removed.
2049 bs = tls->params.tls_bs;
2050 delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
2051 m->m_epg_trllen -= delta;
2053 m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
2055 /* Populate the TLS header. */
2056 tlshdr = (void *)m->m_epg_hdr;
2057 tlshdr->tls_vmajor = tls->params.tls_vmajor;
2060 * TLS 1.3 masquarades as TLS 1.2 with a record type
2061 * of TLS_RLTYPE_APP.
2063 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
2064 tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
2065 tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
2066 tlshdr->tls_type = TLS_RLTYPE_APP;
2067 /* save the real record type for later */
2068 m->m_epg_record_type = record_type;
2069 m->m_epg_trail[0] = record_type;
2071 tlshdr->tls_vminor = tls->params.tls_vminor;
2072 tlshdr->tls_type = record_type;
2074 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
2077 * Store nonces / explicit IVs after the end of the
2080 * For GCM with TLS 1.2, an 8 byte nonce is copied
2081 * from the end of the IV. The nonce is then
2082 * incremented for use by the next record.
2084 * For CBC, a random nonce is inserted for TLS 1.1+.
2086 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
2087 tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
2088 noncep = (uint64_t *)(tls->params.iv + 8);
2089 be64enc(tlshdr + 1, *noncep);
2091 } else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
2092 tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
2093 arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
2096 * When using SW encryption, mark the mbuf not ready.
2097 * It will be marked ready via sbready() after the
2098 * record has been encrypted.
2100 * When using ifnet TLS, unencrypted TLS records are
2101 * sent down the stack to the NIC.
2103 if (tls->mode == TCP_TLS_MODE_SW) {
2104 m->m_flags |= M_NOTREADY;
2105 if (__predict_false(tls_len == 0)) {
2106 /* TLS 1.0 empty fragment. */
2109 m->m_epg_nrdy = m->m_epg_npgs;
2110 *enq_cnt += m->m_epg_nrdy;
2116 ktls_permit_empty_frames(struct ktls_session *tls)
2118 return (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
2119 tls->params.tls_vminor == TLS_MINOR_VER_ZERO);
2123 ktls_check_rx(struct sockbuf *sb)
2125 struct tls_record_layer hdr;
2130 SOCKBUF_LOCK_ASSERT(sb);
2131 KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
2133 so = __containerof(sb, struct socket, so_rcv);
2135 if (sb->sb_flags & SB_TLS_RX_RUNNING)
2138 /* Is there enough queued for a TLS header? */
2139 if (sb->sb_tlscc < sizeof(hdr)) {
2140 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
2141 so->so_error = EMSGSIZE;
2145 m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
2147 /* Is the entire record queued? */
2148 if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
2149 if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
2150 so->so_error = EMSGSIZE;
2154 sb->sb_flags |= SB_TLS_RX_RUNNING;
2157 wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
2159 STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
2160 running = wq->running;
2161 mtx_unlock(&wq->mtx);
2164 counter_u64_add(ktls_cnt_rx_queued, 1);
2167 static struct mbuf *
2168 ktls_detach_record(struct sockbuf *sb, int len)
2170 struct mbuf *m, *n, *top;
2173 SOCKBUF_LOCK_ASSERT(sb);
2174 MPASS(len <= sb->sb_tlscc);
2177 * If TLS chain is the exact size of the record,
2178 * just grab the whole record.
2181 if (sb->sb_tlscc == len) {
2183 sb->sb_mtlstail = NULL;
2188 * While it would be nice to use m_split() here, we need
2189 * to know exactly what m_split() allocates to update the
2190 * accounting, so do it inline instead.
2193 for (m = top; remain > m->m_len; m = m->m_next)
2196 /* Easy case: don't have to split 'm'. */
2197 if (remain == m->m_len) {
2198 sb->sb_mtls = m->m_next;
2199 if (sb->sb_mtls == NULL)
2200 sb->sb_mtlstail = NULL;
2206 * Need to allocate an mbuf to hold the remainder of 'm'. Try
2207 * with M_NOWAIT first.
2209 n = m_get(M_NOWAIT, MT_DATA);
2212 * Use M_WAITOK with socket buffer unlocked. If
2213 * 'sb_mtls' changes while the lock is dropped, return
2214 * NULL to force the caller to retry.
2218 n = m_get(M_WAITOK, MT_DATA);
2221 if (sb->sb_mtls != top) {
2226 n->m_flags |= (m->m_flags & (M_NOTREADY | M_DECRYPTED));
2228 /* Store remainder in 'n'. */
2229 n->m_len = m->m_len - remain;
2230 if (m->m_flags & M_EXT) {
2231 n->m_data = m->m_data + remain;
2234 bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
2237 /* Trim 'm' and update accounting. */
2238 m->m_len -= n->m_len;
2239 sb->sb_tlscc -= n->m_len;
2240 sb->sb_ccc -= n->m_len;
2242 /* Account for 'n'. */
2243 sballoc_ktls_rx(sb, n);
2245 /* Insert 'n' into the TLS chain. */
2247 n->m_next = m->m_next;
2248 if (sb->sb_mtlstail == m)
2249 sb->sb_mtlstail = n;
2251 /* Detach the record from the TLS chain. */
2255 MPASS(m_length(top, NULL) == len);
2256 for (m = top; m != NULL; m = m->m_next)
2257 sbfree_ktls_rx(sb, m);
2258 sb->sb_tlsdcc = len;
2265 * Determine the length of the trailing zero padding and find the real
2266 * record type in the byte before the padding.
2268 * Walking the mbuf chain backwards is clumsy, so another option would
2269 * be to scan forwards remembering the last non-zero byte before the
2270 * trailer. However, it would be expensive to scan the entire record.
2271 * Instead, find the last non-zero byte of each mbuf in the chain
2272 * keeping track of the relative offset of that nonzero byte.
2274 * trail_len is the size of the MAC/tag on input and is set to the
2275 * size of the full trailer including padding and the record type on
2279 tls13_find_record_type(struct ktls_session *tls, struct mbuf *m, int tls_len,
2280 int *trailer_len, uint8_t *record_typep)
2283 u_int digest_start, last_offset, m_len, offset;
2284 uint8_t record_type;
2286 digest_start = tls_len - *trailer_len;
2289 for (; m != NULL && offset < digest_start;
2290 offset += m->m_len, m = m->m_next) {
2291 /* Don't look for padding in the tag. */
2292 m_len = min(digest_start - offset, m->m_len);
2293 cp = mtod(m, char *);
2295 /* Find last non-zero byte in this mbuf. */
2296 while (m_len > 0 && cp[m_len - 1] == 0)
2299 record_type = cp[m_len - 1];
2300 last_offset = offset + m_len;
2303 if (last_offset < tls->params.tls_hlen)
2306 *record_typep = record_type;
2307 *trailer_len = tls_len - last_offset + 1;
2312 * Check if a mbuf chain is fully decrypted at the given offset and
2313 * length. Returns KTLS_MBUF_CRYPTO_ST_DECRYPTED if all data is
2314 * decrypted. KTLS_MBUF_CRYPTO_ST_MIXED if there is a mix of encrypted
2315 * and decrypted data. Else KTLS_MBUF_CRYPTO_ST_ENCRYPTED if all data
2318 ktls_mbuf_crypto_st_t
2319 ktls_mbuf_crypto_state(struct mbuf *mb, int offset, int len)
2321 int m_flags_ored = 0;
2322 int m_flags_anded = -1;
2324 for (; mb != NULL; mb = mb->m_next) {
2325 if (offset < mb->m_len)
2327 offset -= mb->m_len;
2331 for (; mb != NULL; mb = mb->m_next) {
2332 m_flags_ored |= mb->m_flags;
2333 m_flags_anded &= mb->m_flags;
2335 if (offset <= mb->m_len)
2337 offset -= mb->m_len;
2339 MPASS(mb != NULL || offset == 0);
2341 if ((m_flags_ored ^ m_flags_anded) & M_DECRYPTED)
2342 return (KTLS_MBUF_CRYPTO_ST_MIXED);
2344 return ((m_flags_ored & M_DECRYPTED) ?
2345 KTLS_MBUF_CRYPTO_ST_DECRYPTED :
2346 KTLS_MBUF_CRYPTO_ST_ENCRYPTED);
2350 * ktls_resync_ifnet - get HW TLS RX back on track after packet loss
2353 ktls_resync_ifnet(struct socket *so, uint32_t tls_len, uint64_t tls_rcd_num)
2355 union if_snd_tag_modify_params params;
2356 struct m_snd_tag *mst;
2360 mst = so->so_rcv.sb_tls_info->snd_tag;
2361 if (__predict_false(mst == NULL))
2364 inp = sotoinpcb(so);
2365 if (__predict_false(inp == NULL))
2369 if (inp->inp_flags & INP_DROPPED) {
2371 return (ECONNRESET);
2374 tp = intotcpcb(inp);
2377 /* Get the TCP sequence number of the next valid TLS header. */
2378 SOCKBUF_LOCK(&so->so_rcv);
2379 params.tls_rx.tls_hdr_tcp_sn =
2380 tp->rcv_nxt - so->so_rcv.sb_tlscc - tls_len;
2381 params.tls_rx.tls_rec_length = tls_len;
2382 params.tls_rx.tls_seq_number = tls_rcd_num;
2383 SOCKBUF_UNLOCK(&so->so_rcv);
2387 MPASS(mst->sw->type == IF_SND_TAG_TYPE_TLS_RX);
2388 return (mst->sw->snd_tag_modify(mst, ¶ms));
2392 ktls_drop(struct socket *so, int error)
2394 struct epoch_tracker et;
2395 struct inpcb *inp = sotoinpcb(so);
2398 NET_EPOCH_ENTER(et);
2400 if (!(inp->inp_flags & INP_DROPPED)) {
2401 tp = intotcpcb(inp);
2402 CURVNET_SET(inp->inp_vnet);
2403 tp = tcp_drop(tp, error);
2408 so->so_error = error;
2409 SOCK_RECVBUF_LOCK(so);
2410 sorwakeup_locked(so);
2417 ktls_decrypt(struct socket *so)
2419 char tls_header[MBUF_PEXT_HDR_LEN];
2420 struct ktls_session *tls;
2422 struct tls_record_layer *hdr;
2423 struct tls_get_record tgr;
2424 struct mbuf *control, *data, *m;
2425 ktls_mbuf_crypto_st_t state;
2427 int error, remain, tls_len, trail_len;
2429 uint8_t vminor, record_type;
2431 hdr = (struct tls_record_layer *)tls_header;
2434 KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
2435 ("%s: socket %p not running", __func__, so));
2437 tls = sb->sb_tls_info;
2440 tls13 = (tls->params.tls_vminor == TLS_MINOR_VER_THREE);
2442 vminor = TLS_MINOR_VER_TWO;
2444 vminor = tls->params.tls_vminor;
2446 /* Is there enough queued for a TLS header? */
2447 if (sb->sb_tlscc < tls->params.tls_hlen)
2450 m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
2451 tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
2453 if (hdr->tls_vmajor != tls->params.tls_vmajor ||
2454 hdr->tls_vminor != vminor)
2456 else if (tls13 && hdr->tls_type != TLS_RLTYPE_APP)
2458 else if (tls_len < tls->params.tls_hlen || tls_len >
2459 tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
2460 tls->params.tls_tlen)
2464 if (__predict_false(error != 0)) {
2466 * We have a corrupted record and are likely
2467 * out of sync. The connection isn't
2468 * recoverable at this point, so abort it.
2471 counter_u64_add(ktls_offload_corrupted_records, 1);
2473 ktls_drop(so, error);
2477 /* Is the entire record queued? */
2478 if (sb->sb_tlscc < tls_len)
2482 * Split out the portion of the mbuf chain containing
2485 data = ktls_detach_record(sb, tls_len);
2488 MPASS(sb->sb_tlsdcc == tls_len);
2490 seqno = sb->sb_tls_seqno;
2495 /* get crypto state for this TLS record */
2496 state = ktls_mbuf_crypto_state(data, 0, tls_len);
2499 case KTLS_MBUF_CRYPTO_ST_MIXED:
2500 error = ktls_ocf_recrypt(tls, hdr, data, seqno);
2504 case KTLS_MBUF_CRYPTO_ST_ENCRYPTED:
2505 error = ktls_ocf_decrypt(tls, hdr, data, seqno,
2507 if (__predict_true(error == 0)) {
2509 error = tls13_find_record_type(tls, data,
2510 tls_len, &trail_len, &record_type);
2512 record_type = hdr->tls_type;
2516 case KTLS_MBUF_CRYPTO_ST_DECRYPTED:
2518 * NIC TLS is only supported for AEAD
2519 * ciphersuites which used a fixed sized
2523 trail_len = tls->params.tls_tlen - 1;
2524 error = tls13_find_record_type(tls, data,
2525 tls_len, &trail_len, &record_type);
2527 trail_len = tls->params.tls_tlen;
2529 record_type = hdr->tls_type;
2537 counter_u64_add(ktls_offload_failed_crypto, 1);
2540 if (sb->sb_tlsdcc == 0) {
2542 * sbcut/drop/flush discarded these
2550 * Drop this TLS record's data, but keep
2551 * decrypting subsequent records.
2553 sb->sb_ccc -= tls_len;
2556 if (error != EMSGSIZE)
2558 CURVNET_SET(so->so_vnet);
2559 so->so_error = error;
2560 sorwakeup_locked(so);
2569 /* Allocate the control mbuf. */
2570 memset(&tgr, 0, sizeof(tgr));
2571 tgr.tls_type = record_type;
2572 tgr.tls_vmajor = hdr->tls_vmajor;
2573 tgr.tls_vminor = hdr->tls_vminor;
2574 tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
2576 control = sbcreatecontrol(&tgr, sizeof(tgr),
2577 TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
2580 if (sb->sb_tlsdcc == 0) {
2581 /* sbcut/drop/flush discarded these mbufs. */
2582 MPASS(sb->sb_tlscc == 0);
2589 * Clear the 'dcc' accounting in preparation for
2590 * adding the decrypted record.
2592 sb->sb_ccc -= tls_len;
2596 /* If there is no payload, drop all of the data. */
2597 if (tgr.tls_length == htobe16(0)) {
2602 remain = tls->params.tls_hlen;
2603 while (remain > 0) {
2604 if (data->m_len > remain) {
2605 data->m_data += remain;
2606 data->m_len -= remain;
2609 remain -= data->m_len;
2610 data = m_free(data);
2613 /* Trim trailer and clear M_NOTREADY. */
2614 remain = be16toh(tgr.tls_length);
2616 for (m = data; remain > m->m_len; m = m->m_next) {
2617 m->m_flags &= ~(M_NOTREADY | M_DECRYPTED);
2623 m->m_flags &= ~(M_NOTREADY | M_DECRYPTED);
2625 /* Set EOR on the final mbuf. */
2626 m->m_flags |= M_EOR;
2629 sbappendcontrol_locked(sb, data, control, 0);
2631 if (__predict_false(state != KTLS_MBUF_CRYPTO_ST_DECRYPTED)) {
2632 sb->sb_flags |= SB_TLS_RX_RESYNC;
2634 ktls_resync_ifnet(so, tls_len, seqno);
2636 } else if (__predict_false(sb->sb_flags & SB_TLS_RX_RESYNC)) {
2637 sb->sb_flags &= ~SB_TLS_RX_RESYNC;
2639 ktls_resync_ifnet(so, 0, seqno);
2644 sb->sb_flags &= ~SB_TLS_RX_RUNNING;
2646 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
2647 so->so_error = EMSGSIZE;
2649 sorwakeup_locked(so);
2652 SOCKBUF_UNLOCK_ASSERT(sb);
2654 CURVNET_SET(so->so_vnet);
2660 ktls_enqueue_to_free(struct mbuf *m)
2665 /* Mark it for freeing. */
2666 m->m_epg_flags |= EPG_FLAG_2FREE;
2667 wq = &ktls_wq[m->m_epg_tls->wq_index];
2669 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2670 running = wq->running;
2671 mtx_unlock(&wq->mtx);
2677 ktls_buffer_alloc(struct ktls_wq *wq, struct mbuf *m)
2680 int domain, running;
2682 if (m->m_epg_npgs <= 2)
2684 if (ktls_buffer_zone == NULL)
2686 if ((u_int)(ticks - wq->lastallocfail) < hz) {
2688 * Rate-limit allocation attempts after a failure.
2689 * ktls_buffer_import() will acquire a per-domain mutex to check
2690 * the free page queues and may fail consistently if memory is
2695 buf = uma_zalloc(ktls_buffer_zone, M_NOWAIT | M_NORECLAIM);
2697 domain = PCPU_GET(domain);
2698 wq->lastallocfail = ticks;
2701 * Note that this check is "racy", but the races are
2702 * harmless, and are either a spurious wakeup if
2703 * multiple threads fail allocations before the alloc
2704 * thread wakes, or waiting an extra second in case we
2705 * see an old value of running == true.
2707 if (!VM_DOMAIN_EMPTY(domain)) {
2708 running = atomic_load_int(&ktls_domains[domain].alloc_td.running);
2710 wakeup(&ktls_domains[domain].alloc_td);
2717 ktls_encrypt_record(struct ktls_wq *wq, struct mbuf *m,
2718 struct ktls_session *tls, struct ktls_ocf_encrypt_state *state)
2721 int error, i, len, off;
2723 KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) == (M_EXTPG | M_NOTREADY),
2724 ("%p not unready & nomap mbuf\n", m));
2725 KASSERT(ptoa(m->m_epg_npgs) <= ktls_maxlen,
2726 ("page count %d larger than maximum frame length %d", m->m_epg_npgs,
2729 /* Anonymous mbufs are encrypted in place. */
2730 if ((m->m_epg_flags & EPG_FLAG_ANON) != 0)
2731 return (ktls_ocf_encrypt(state, tls, m, NULL, 0));
2734 * For file-backed mbufs (from sendfile), anonymous wired
2735 * pages are allocated and used as the encryption destination.
2737 if ((state->cbuf = ktls_buffer_alloc(wq, m)) != NULL) {
2738 len = ptoa(m->m_epg_npgs - 1) + m->m_epg_last_len -
2740 state->dst_iov[0].iov_base = (char *)state->cbuf +
2742 state->dst_iov[0].iov_len = len;
2743 state->parray[0] = DMAP_TO_PHYS((vm_offset_t)state->cbuf);
2746 off = m->m_epg_1st_off;
2747 for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2748 pg = vm_page_alloc_noobj(VM_ALLOC_NODUMP |
2749 VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2750 len = m_epg_pagelen(m, i, off);
2751 state->parray[i] = VM_PAGE_TO_PHYS(pg);
2752 state->dst_iov[i].iov_base =
2753 (char *)PHYS_TO_DMAP(state->parray[i]) + off;
2754 state->dst_iov[i].iov_len = len;
2757 KASSERT(i + 1 <= nitems(state->dst_iov), ("dst_iov is too small"));
2758 state->dst_iov[i].iov_base = m->m_epg_trail;
2759 state->dst_iov[i].iov_len = m->m_epg_trllen;
2761 error = ktls_ocf_encrypt(state, tls, m, state->dst_iov, i + 1);
2763 if (__predict_false(error != 0)) {
2764 /* Free the anonymous pages. */
2765 if (state->cbuf != NULL)
2766 uma_zfree(ktls_buffer_zone, state->cbuf);
2768 for (i = 0; i < m->m_epg_npgs; i++) {
2769 pg = PHYS_TO_VM_PAGE(state->parray[i]);
2770 (void)vm_page_unwire_noq(pg);
2778 /* Number of TLS records in a batch passed to ktls_enqueue(). */
2780 ktls_batched_records(struct mbuf *m)
2782 int page_count, records;
2785 page_count = m->m_epg_enc_cnt;
2786 while (page_count > 0) {
2788 page_count -= m->m_epg_nrdy;
2791 KASSERT(page_count == 0, ("%s: mismatched page count", __func__));
2796 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
2798 struct ktls_session *tls;
2803 KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2804 (M_EXTPG | M_NOTREADY)),
2805 ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
2806 KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
2808 KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
2810 m->m_epg_enc_cnt = page_count;
2813 * Save a pointer to the socket. The caller is responsible
2814 * for taking an additional reference via soref().
2820 wq = &ktls_wq[tls->wq_index];
2822 if (__predict_false(tls->sequential_records)) {
2824 * For TLS 1.0, records must be encrypted
2825 * sequentially. For a given connection, all records
2826 * queued to the associated work queue are processed
2827 * sequentially. However, sendfile(2) might complete
2828 * I/O requests spanning multiple TLS records out of
2829 * order. Here we ensure TLS records are enqueued to
2830 * the work queue in FIFO order.
2832 * tls->next_seqno holds the sequence number of the
2833 * next TLS record that should be enqueued to the work
2834 * queue. If this next record is not tls->next_seqno,
2835 * it must be a future record, so insert it, sorted by
2836 * TLS sequence number, into tls->pending_records and
2839 * If this TLS record matches tls->next_seqno, place
2840 * it in the work queue and then check
2841 * tls->pending_records to see if any
2842 * previously-queued records are now ready for
2845 if (m->m_epg_seqno != tls->next_seqno) {
2849 STAILQ_FOREACH(n, &tls->pending_records, m_epg_stailq) {
2850 if (n->m_epg_seqno > m->m_epg_seqno)
2855 STAILQ_INSERT_TAIL(&tls->pending_records, m,
2858 STAILQ_INSERT_HEAD(&tls->pending_records, m,
2861 STAILQ_INSERT_AFTER(&tls->pending_records, p, m,
2863 mtx_unlock(&wq->mtx);
2864 counter_u64_add(ktls_cnt_tx_pending, 1);
2868 tls->next_seqno += ktls_batched_records(m);
2869 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2871 while (!STAILQ_EMPTY(&tls->pending_records)) {
2874 n = STAILQ_FIRST(&tls->pending_records);
2875 if (n->m_epg_seqno != tls->next_seqno)
2879 STAILQ_REMOVE_HEAD(&tls->pending_records, m_epg_stailq);
2880 tls->next_seqno += ktls_batched_records(n);
2881 STAILQ_INSERT_TAIL(&wq->m_head, n, m_epg_stailq);
2883 counter_u64_add(ktls_cnt_tx_pending, -(queued - 1));
2885 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2887 running = wq->running;
2888 mtx_unlock(&wq->mtx);
2891 counter_u64_add(ktls_cnt_tx_queued, queued);
2895 * Once a file-backed mbuf (from sendfile) has been encrypted, free
2896 * the pages from the file and replace them with the anonymous pages
2897 * allocated in ktls_encrypt_record().
2900 ktls_finish_nonanon(struct mbuf *m, struct ktls_ocf_encrypt_state *state)
2904 MPASS((m->m_epg_flags & EPG_FLAG_ANON) == 0);
2906 /* Free the old pages. */
2907 m->m_ext.ext_free(m);
2909 /* Replace them with the new pages. */
2910 if (state->cbuf != NULL) {
2911 for (i = 0; i < m->m_epg_npgs; i++)
2912 m->m_epg_pa[i] = state->parray[0] + ptoa(i);
2914 /* Contig pages should go back to the cache. */
2915 m->m_ext.ext_free = ktls_free_mext_contig;
2917 for (i = 0; i < m->m_epg_npgs; i++)
2918 m->m_epg_pa[i] = state->parray[i];
2920 /* Use the basic free routine. */
2921 m->m_ext.ext_free = mb_free_mext_pgs;
2924 /* Pages are now writable. */
2925 m->m_epg_flags |= EPG_FLAG_ANON;
2928 static __noinline void
2929 ktls_encrypt(struct ktls_wq *wq, struct mbuf *top)
2931 struct ktls_ocf_encrypt_state state;
2932 struct ktls_session *tls;
2935 int error, npages, total_pages;
2938 tls = top->m_epg_tls;
2939 KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
2940 KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
2942 top->m_epg_so = NULL;
2944 total_pages = top->m_epg_enc_cnt;
2948 * Encrypt the TLS records in the chain of mbufs starting with
2949 * 'top'. 'total_pages' gives us a total count of pages and is
2950 * used to know when we have finished encrypting the TLS
2951 * records originally queued with 'top'.
2953 * NB: These mbufs are queued in the socket buffer and
2954 * 'm_next' is traversing the mbufs in the socket buffer. The
2955 * socket buffer lock is not held while traversing this chain.
2956 * Since the mbufs are all marked M_NOTREADY their 'm_next'
2957 * pointers should be stable. However, the 'm_next' of the
2958 * last mbuf encrypted is not necessarily NULL. It can point
2959 * to other mbufs appended while 'top' was on the TLS work
2962 * Each mbuf holds an entire TLS record.
2965 for (m = top; npages != total_pages; m = m->m_next) {
2966 KASSERT(m->m_epg_tls == tls,
2967 ("different TLS sessions in a single mbuf chain: %p vs %p",
2968 tls, m->m_epg_tls));
2969 KASSERT(npages + m->m_epg_npgs <= total_pages,
2970 ("page count mismatch: top %p, total_pages %d, m %p", top,
2973 error = ktls_encrypt_record(wq, m, tls, &state);
2975 counter_u64_add(ktls_offload_failed_crypto, 1);
2979 if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
2980 ktls_finish_nonanon(m, &state);
2982 npages += m->m_epg_nrdy;
2985 * Drop a reference to the session now that it is no
2986 * longer needed. Existing code depends on encrypted
2987 * records having no associated session vs
2988 * yet-to-be-encrypted records having an associated
2991 m->m_epg_tls = NULL;
2995 CURVNET_SET(so->so_vnet);
2997 (void)so->so_proto->pr_ready(so, top, npages);
3000 mb_free_notready(top, total_pages);
3008 ktls_encrypt_cb(struct ktls_ocf_encrypt_state *state, int error)
3010 struct ktls_session *tls;
3017 if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
3018 ktls_finish_nonanon(m, state);
3021 free(state, M_KTLS);
3024 * Drop a reference to the session now that it is no longer
3025 * needed. Existing code depends on encrypted records having
3026 * no associated session vs yet-to-be-encrypted records having
3027 * an associated session.
3030 m->m_epg_tls = NULL;
3034 counter_u64_add(ktls_offload_failed_crypto, 1);
3036 CURVNET_SET(so->so_vnet);
3037 npages = m->m_epg_nrdy;
3040 (void)so->so_proto->pr_ready(so, m, npages);
3043 mb_free_notready(m, npages);
3051 * Similar to ktls_encrypt, but used with asynchronous OCF backends
3052 * (coprocessors) where encryption does not use host CPU resources and
3053 * it can be beneficial to queue more requests than CPUs.
3055 static __noinline void
3056 ktls_encrypt_async(struct ktls_wq *wq, struct mbuf *top)
3058 struct ktls_ocf_encrypt_state *state;
3059 struct ktls_session *tls;
3062 int error, mpages, npages, total_pages;
3065 tls = top->m_epg_tls;
3066 KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
3067 KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
3069 top->m_epg_so = NULL;
3071 total_pages = top->m_epg_enc_cnt;
3075 for (m = top; npages != total_pages; m = n) {
3076 KASSERT(m->m_epg_tls == tls,
3077 ("different TLS sessions in a single mbuf chain: %p vs %p",
3078 tls, m->m_epg_tls));
3079 KASSERT(npages + m->m_epg_npgs <= total_pages,
3080 ("page count mismatch: top %p, total_pages %d, m %p", top,
3083 state = malloc(sizeof(*state), M_KTLS, M_WAITOK | M_ZERO);
3088 mpages = m->m_epg_nrdy;
3091 error = ktls_encrypt_record(wq, m, tls, state);
3093 counter_u64_add(ktls_offload_failed_crypto, 1);
3094 free(state, M_KTLS);
3095 CURVNET_SET(so->so_vnet);
3104 CURVNET_SET(so->so_vnet);
3107 mb_free_notready(m, total_pages - npages);
3115 ktls_bind_domain(int domain)
3119 error = cpuset_setthread(curthread->td_tid, &cpuset_domain[domain]);
3122 curthread->td_domain.dr_policy = DOMAINSET_PREF(domain);
3127 ktls_alloc_thread(void *ctx)
3129 struct ktls_domain_info *ktls_domain = ctx;
3130 struct ktls_alloc_thread *sc = &ktls_domain->alloc_td;
3132 struct sysctl_oid *oid;
3134 int domain, error, i, nbufs;
3136 domain = ktls_domain - ktls_domains;
3138 printf("Starting KTLS alloc thread for domain %d\n", domain);
3139 error = ktls_bind_domain(domain);
3141 printf("Unable to bind KTLS alloc thread for domain %d: error %d\n",
3143 snprintf(name, sizeof(name), "domain%d", domain);
3144 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_kern_ipc_tls), OID_AUTO,
3145 name, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
3146 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "allocs",
3147 CTLFLAG_RD, &sc->allocs, 0, "buffers allocated");
3148 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "wakeups",
3149 CTLFLAG_RD, &sc->wakeups, 0, "thread wakeups");
3150 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "running",
3151 CTLFLAG_RD, &sc->running, 0, "thread running");
3156 atomic_store_int(&sc->running, 0);
3157 tsleep(sc, PZERO | PNOLOCK, "-", 0);
3158 atomic_store_int(&sc->running, 1);
3160 if (nbufs != ktls_max_alloc) {
3162 nbufs = atomic_load_int(&ktls_max_alloc);
3163 buf = malloc(sizeof(void *) * nbufs, M_KTLS,
3167 * Below we allocate nbufs with different allocation
3168 * flags than we use when allocating normally during
3169 * encryption in the ktls worker thread. We specify
3170 * M_NORECLAIM in the worker thread. However, we omit
3171 * that flag here and add M_WAITOK so that the VM
3172 * system is permitted to perform expensive work to
3173 * defragment memory. We do this here, as it does not
3174 * matter if this thread blocks. If we block a ktls
3175 * worker thread, we risk developing backlogs of
3176 * buffers to be encrypted, leading to surges of
3177 * traffic and potential NIC output drops.
3179 for (i = 0; i < nbufs; i++) {
3180 buf[i] = uma_zalloc(ktls_buffer_zone, M_WAITOK);
3183 for (i = 0; i < nbufs; i++) {
3184 uma_zfree(ktls_buffer_zone, buf[i]);
3191 ktls_work_thread(void *ctx)
3193 struct ktls_wq *wq = ctx;
3195 struct socket *so, *son;
3196 STAILQ_HEAD(, mbuf) local_m_head;
3197 STAILQ_HEAD(, socket) local_so_head;
3202 printf("Starting KTLS worker thread for CPU %d\n", cpu);
3205 * Bind to a core. If ktls_bind_threads is > 1, then
3206 * we bind to the NUMA domain instead.
3208 if (ktls_bind_threads) {
3211 if (ktls_bind_threads > 1) {
3212 struct pcpu *pc = pcpu_find(cpu);
3214 error = ktls_bind_domain(pc->pc_domain);
3218 CPU_SETOF(cpu, &mask);
3219 error = cpuset_setthread(curthread->td_tid, &mask);
3222 printf("Unable to bind KTLS worker thread for CPU %d: error %d\n",
3225 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
3230 while (STAILQ_EMPTY(&wq->m_head) &&
3231 STAILQ_EMPTY(&wq->so_head)) {
3232 wq->running = false;
3233 mtx_sleep(wq, &wq->mtx, 0, "-", 0);
3237 STAILQ_INIT(&local_m_head);
3238 STAILQ_CONCAT(&local_m_head, &wq->m_head);
3239 STAILQ_INIT(&local_so_head);
3240 STAILQ_CONCAT(&local_so_head, &wq->so_head);
3241 mtx_unlock(&wq->mtx);
3243 STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
3244 if (m->m_epg_flags & EPG_FLAG_2FREE) {
3245 ktls_free(m->m_epg_tls);
3248 if (m->m_epg_tls->sync_dispatch)
3249 ktls_encrypt(wq, m);
3251 ktls_encrypt_async(wq, m);
3252 counter_u64_add(ktls_cnt_tx_queued, -1);
3256 STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
3258 counter_u64_add(ktls_cnt_rx_queued, -1);
3263 #if defined(INET) || defined(INET6)
3265 ktls_disable_ifnet_help(void *context, int pending __unused)
3267 struct ktls_session *tls;
3278 so = inp->inp_socket;
3280 if (inp->inp_flags & INP_DROPPED) {
3284 if (so->so_snd.sb_tls_info != NULL)
3285 err = ktls_set_tx_mode(so, TCP_TLS_MODE_SW);
3289 counter_u64_add(ktls_ifnet_disable_ok, 1);
3290 /* ktls_set_tx_mode() drops inp wlock, so recheck flags */
3291 if ((inp->inp_flags & INP_DROPPED) == 0 &&
3292 (tp = intotcpcb(inp)) != NULL &&
3293 tp->t_fb->tfb_hwtls_change != NULL)
3294 (*tp->t_fb->tfb_hwtls_change)(tp, 0);
3296 counter_u64_add(ktls_ifnet_disable_fail, 1);
3300 CURVNET_SET(so->so_vnet);
3308 * Called when re-transmits are becoming a substantial portion of the
3309 * sends on this connection. When this happens, we transition the
3310 * connection to software TLS. This is needed because most inline TLS
3311 * NICs keep crypto state only for in-order transmits. This means
3312 * that to handle a TCP rexmit (which is out-of-order), the NIC must
3313 * re-DMA the entire TLS record up to and including the current
3314 * segment. This means that when re-transmitting the last ~1448 byte
3315 * segment of a 16KB TLS record, we could wind up re-DMA'ing an order
3316 * of magnitude more data than we are sending. This can cause the
3317 * PCIe link to saturate well before the network, which can cause
3318 * output drops, and a general loss of capacity.
3321 ktls_disable_ifnet(void *arg)
3326 struct ktls_session *tls;
3329 inp = tptoinpcb(tp);
3330 INP_WLOCK_ASSERT(inp);
3331 so = inp->inp_socket;
3333 tls = so->so_snd.sb_tls_info;
3334 if (tp->t_nic_ktls_xmit_dis == 1) {
3339 * note that t_nic_ktls_xmit_dis is never cleared; disabling
3340 * ifnet can only be done once per connection, so we never want
3344 (void)ktls_hold(tls);
3346 tp->t_nic_ktls_xmit_dis = 1;
3348 TASK_INIT(&tls->disable_ifnet_task, 0, ktls_disable_ifnet_help, tls);
3349 (void)taskqueue_enqueue(taskqueue_thread, &tls->disable_ifnet_task);