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"
35 #include <sys/param.h>
36 #include <sys/kernel.h>
37 #include <sys/domainset.h>
41 #include <sys/mutex.h>
42 #include <sys/rmlock.h>
44 #include <sys/protosw.h>
45 #include <sys/refcount.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/sysctl.h>
50 #include <sys/taskqueue.h>
51 #include <sys/kthread.h>
53 #include <sys/vmmeter.h>
54 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
55 #include <machine/pcb.h>
57 #include <machine/vmparam.h>
59 #include <net/if_var.h>
61 #include <net/netisr.h>
62 #include <net/rss_config.h>
64 #include <net/route.h>
65 #include <net/route/nhop.h>
66 #if defined(INET) || defined(INET6)
67 #include <netinet/in.h>
68 #include <netinet/in_pcb.h>
70 #include <netinet/tcp_var.h>
72 #include <netinet/tcp_offload.h>
74 #include <opencrypto/xform.h>
75 #include <vm/uma_dbg.h>
77 #include <vm/vm_pageout.h>
78 #include <vm/vm_page.h>
82 STAILQ_HEAD(, mbuf) m_head;
83 STAILQ_HEAD(, socket) so_head;
86 } __aligned(CACHE_LINE_SIZE);
88 struct ktls_domain_info {
93 struct ktls_domain_info ktls_domains[MAXMEMDOM];
94 static struct ktls_wq *ktls_wq;
95 static struct proc *ktls_proc;
96 LIST_HEAD(, ktls_crypto_backend) ktls_backends;
97 static struct rmlock ktls_backends_lock;
98 static uma_zone_t ktls_session_zone;
99 static uma_zone_t ktls_buffer_zone;
100 static uint16_t ktls_cpuid_lookup[MAXCPU];
102 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
103 "Kernel TLS offload");
104 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
105 "Kernel TLS offload stats");
107 static int ktls_allow_unload;
108 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, allow_unload, CTLFLAG_RDTUN,
109 &ktls_allow_unload, 0, "Allow software crypto modules to unload");
112 static int ktls_bind_threads = 1;
114 static int ktls_bind_threads;
116 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
117 &ktls_bind_threads, 0,
118 "Bind crypto threads to cores (1) or cores and domains (2) at boot");
120 static u_int ktls_maxlen = 16384;
121 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RDTUN,
122 &ktls_maxlen, 0, "Maximum TLS record size");
124 static int ktls_number_threads;
125 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
126 &ktls_number_threads, 0,
127 "Number of TLS threads in thread-pool");
129 static bool ktls_offload_enable;
130 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RWTUN,
131 &ktls_offload_enable, 0,
132 "Enable support for kernel TLS offload");
134 static bool ktls_cbc_enable = true;
135 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RWTUN,
137 "Enable Support of AES-CBC crypto for kernel TLS");
139 static bool ktls_sw_buffer_cache = true;
140 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, sw_buffer_cache, CTLFLAG_RDTUN,
141 &ktls_sw_buffer_cache, 1,
142 "Enable caching of output buffers for SW encryption");
144 static COUNTER_U64_DEFINE_EARLY(ktls_tasks_active);
145 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
146 &ktls_tasks_active, "Number of active tasks");
148 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_tx_queued);
149 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_inqueue, CTLFLAG_RD,
151 "Number of TLS records in queue to tasks for SW encryption");
153 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_rx_queued);
154 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_rx_inqueue, CTLFLAG_RD,
156 "Number of TLS sockets in queue to tasks for SW decryption");
158 static COUNTER_U64_DEFINE_EARLY(ktls_offload_total);
159 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
160 CTLFLAG_RD, &ktls_offload_total,
161 "Total successful TLS setups (parameters set)");
163 static COUNTER_U64_DEFINE_EARLY(ktls_offload_enable_calls);
164 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
165 CTLFLAG_RD, &ktls_offload_enable_calls,
166 "Total number of TLS enable calls made");
168 static COUNTER_U64_DEFINE_EARLY(ktls_offload_active);
169 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
170 &ktls_offload_active, "Total Active TLS sessions");
172 static COUNTER_U64_DEFINE_EARLY(ktls_offload_corrupted_records);
173 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, corrupted_records, CTLFLAG_RD,
174 &ktls_offload_corrupted_records, "Total corrupted TLS records received");
176 static COUNTER_U64_DEFINE_EARLY(ktls_offload_failed_crypto);
177 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
178 &ktls_offload_failed_crypto, "Total TLS crypto failures");
180 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_ifnet);
181 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
182 &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
184 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_sw);
185 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
186 &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
188 static COUNTER_U64_DEFINE_EARLY(ktls_switch_failed);
189 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
190 &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
192 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
193 "Software TLS session stats");
194 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
195 "Hardware (ifnet) TLS session stats");
197 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
198 "TOE TLS session stats");
201 static COUNTER_U64_DEFINE_EARLY(ktls_sw_cbc);
202 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
203 "Active number of software TLS sessions using AES-CBC");
205 static COUNTER_U64_DEFINE_EARLY(ktls_sw_gcm);
206 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
207 "Active number of software TLS sessions using AES-GCM");
209 static COUNTER_U64_DEFINE_EARLY(ktls_sw_chacha20);
210 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, chacha20, CTLFLAG_RD,
212 "Active number of software TLS sessions using Chacha20-Poly1305");
214 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_cbc);
215 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
217 "Active number of ifnet TLS sessions using AES-CBC");
219 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_gcm);
220 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
222 "Active number of ifnet TLS sessions using AES-GCM");
224 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_chacha20);
225 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, chacha20, CTLFLAG_RD,
226 &ktls_ifnet_chacha20,
227 "Active number of ifnet TLS sessions using Chacha20-Poly1305");
229 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset);
230 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
231 &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
233 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_dropped);
234 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
235 &ktls_ifnet_reset_dropped,
236 "TLS sessions dropped after failing to update ifnet send tag");
238 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_failed);
239 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
240 &ktls_ifnet_reset_failed,
241 "TLS sessions that failed to allocate a new ifnet send tag");
243 static int ktls_ifnet_permitted;
244 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
245 &ktls_ifnet_permitted, 1,
246 "Whether to permit hardware (ifnet) TLS sessions");
249 static COUNTER_U64_DEFINE_EARLY(ktls_toe_cbc);
250 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
252 "Active number of TOE TLS sessions using AES-CBC");
254 static COUNTER_U64_DEFINE_EARLY(ktls_toe_gcm);
255 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
257 "Active number of TOE TLS sessions using AES-GCM");
259 static COUNTER_U64_DEFINE_EARLY(ktls_toe_chacha20);
260 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, chacha20, CTLFLAG_RD,
262 "Active number of TOE TLS sessions using Chacha20-Poly1305");
265 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
267 static void ktls_cleanup(struct ktls_session *tls);
268 #if defined(INET) || defined(INET6)
269 static void ktls_reset_send_tag(void *context, int pending);
271 static void ktls_work_thread(void *ctx);
274 ktls_crypto_backend_register(struct ktls_crypto_backend *be)
276 struct ktls_crypto_backend *curr_be, *tmp;
278 if (be->api_version != KTLS_API_VERSION) {
279 printf("KTLS: API version mismatch (%d vs %d) for %s\n",
280 be->api_version, KTLS_API_VERSION,
285 rm_wlock(&ktls_backends_lock);
286 printf("KTLS: Registering crypto method %s with prio %d\n",
288 if (LIST_EMPTY(&ktls_backends)) {
289 LIST_INSERT_HEAD(&ktls_backends, be, next);
291 LIST_FOREACH_SAFE(curr_be, &ktls_backends, next, tmp) {
292 if (curr_be->prio < be->prio) {
293 LIST_INSERT_BEFORE(curr_be, be, next);
296 if (LIST_NEXT(curr_be, next) == NULL) {
297 LIST_INSERT_AFTER(curr_be, be, next);
302 rm_wunlock(&ktls_backends_lock);
307 ktls_crypto_backend_deregister(struct ktls_crypto_backend *be)
309 struct ktls_crypto_backend *tmp;
312 * Don't error if the backend isn't registered. This permits
313 * MOD_UNLOAD handlers to use this function unconditionally.
315 rm_wlock(&ktls_backends_lock);
316 LIST_FOREACH(tmp, &ktls_backends, next) {
321 rm_wunlock(&ktls_backends_lock);
325 if (!ktls_allow_unload) {
326 rm_wunlock(&ktls_backends_lock);
328 "KTLS: Deregistering crypto method %s is not supported\n",
334 rm_wunlock(&ktls_backends_lock);
338 LIST_REMOVE(be, next);
339 rm_wunlock(&ktls_backends_lock);
343 #if defined(INET) || defined(INET6)
345 ktls_get_cpu(struct socket *so)
349 struct ktls_domain_info *di;
355 cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
356 if (cpuid != NETISR_CPUID_NONE)
360 * Just use the flowid to shard connections in a repeatable
361 * fashion. Note that some crypto backends rely on the
362 * serialization provided by having the same connection use
366 if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
367 di = &ktls_domains[inp->inp_numa_domain];
368 cpuid = di->cpu[inp->inp_flowid % di->count];
371 cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
377 ktls_buffer_import(void *arg, void **store, int count, int domain, int flags)
382 KASSERT((ktls_maxlen & PAGE_MASK) == 0,
383 ("%s: ktls max length %d is not page size-aligned",
384 __func__, ktls_maxlen));
386 for (i = 0; i < count; i++) {
387 m = vm_page_alloc_contig_domain(NULL, 0, domain,
388 VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
389 VM_ALLOC_NODUMP | malloc2vm_flags(flags),
390 atop(ktls_maxlen), 0, ~0ul, PAGE_SIZE, 0,
394 store[i] = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
400 ktls_buffer_release(void *arg __unused, void **store, int count)
405 for (i = 0; i < count; i++) {
406 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)store[i]));
407 for (j = 0; j < atop(ktls_maxlen); j++) {
408 (void)vm_page_unwire_noq(m + j);
415 ktls_free_mext_contig(struct mbuf *m)
418 uma_zfree(ktls_buffer_zone, (void *)PHYS_TO_DMAP(m->m_epg_pa[0]));
422 ktls_init(void *dummy __unused)
427 int count, domain, error, i;
429 rm_init(&ktls_backends_lock, "ktls backends");
430 LIST_INIT(&ktls_backends);
432 ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
435 ktls_session_zone = uma_zcreate("ktls_session",
436 sizeof(struct ktls_session),
437 NULL, NULL, NULL, NULL,
440 if (ktls_sw_buffer_cache) {
441 ktls_buffer_zone = uma_zcache_create("ktls_buffers",
442 roundup2(ktls_maxlen, PAGE_SIZE), NULL, NULL, NULL, NULL,
443 ktls_buffer_import, ktls_buffer_release, NULL,
444 UMA_ZONE_FIRSTTOUCH);
448 * Initialize the workqueues to run the TLS work. We create a
449 * work queue for each CPU.
452 STAILQ_INIT(&ktls_wq[i].m_head);
453 STAILQ_INIT(&ktls_wq[i].so_head);
454 mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
455 error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
456 &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
458 panic("Can't add KTLS thread %d error %d", i, error);
461 * Bind threads to cores. If ktls_bind_threads is >
462 * 1, then we bind to the NUMA domain.
464 if (ktls_bind_threads) {
465 if (ktls_bind_threads > 1) {
467 domain = pc->pc_domain;
468 CPU_COPY(&cpuset_domain[domain], &mask);
469 count = ktls_domains[domain].count;
470 ktls_domains[domain].cpu[count] = i;
471 ktls_domains[domain].count++;
475 error = cpuset_setthread(td->td_tid, &mask);
478 "Unable to bind KTLS thread for CPU %d error %d",
481 ktls_cpuid_lookup[ktls_number_threads] = i;
482 ktls_number_threads++;
486 * If we somehow have an empty domain, fall back to choosing
487 * among all KTLS threads.
489 if (ktls_bind_threads > 1) {
490 for (i = 0; i < vm_ndomains; i++) {
491 if (ktls_domains[i].count == 0) {
492 ktls_bind_threads = 1;
499 printf("KTLS: Initialized %d threads\n", ktls_number_threads);
501 SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
503 #if defined(INET) || defined(INET6)
505 ktls_create_session(struct socket *so, struct tls_enable *en,
506 struct ktls_session **tlsp)
508 struct ktls_session *tls;
511 /* Only TLS 1.0 - 1.3 are supported. */
512 if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
514 if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
515 en->tls_vminor > TLS_MINOR_VER_THREE)
518 if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
520 if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
522 if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
525 /* All supported algorithms require a cipher key. */
526 if (en->cipher_key_len == 0)
529 /* No flags are currently supported. */
533 /* Common checks for supported algorithms. */
534 switch (en->cipher_algorithm) {
535 case CRYPTO_AES_NIST_GCM_16:
537 * auth_algorithm isn't used, but permit GMAC values
540 switch (en->auth_algorithm) {
542 #ifdef COMPAT_FREEBSD12
543 /* XXX: Really 13.0-current COMPAT. */
544 case CRYPTO_AES_128_NIST_GMAC:
545 case CRYPTO_AES_192_NIST_GMAC:
546 case CRYPTO_AES_256_NIST_GMAC:
552 if (en->auth_key_len != 0)
554 if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
555 en->iv_len != TLS_AEAD_GCM_LEN) ||
556 (en->tls_vminor == TLS_MINOR_VER_THREE &&
557 en->iv_len != TLS_1_3_GCM_IV_LEN))
561 switch (en->auth_algorithm) {
562 case CRYPTO_SHA1_HMAC:
564 * TLS 1.0 requires an implicit IV. TLS 1.1+
565 * all use explicit IVs.
567 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
568 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
574 case CRYPTO_SHA2_256_HMAC:
575 case CRYPTO_SHA2_384_HMAC:
576 /* Ignore any supplied IV. */
582 if (en->auth_key_len == 0)
585 case CRYPTO_CHACHA20_POLY1305:
586 if (en->auth_algorithm != 0 || en->auth_key_len != 0)
588 if (en->tls_vminor != TLS_MINOR_VER_TWO &&
589 en->tls_vminor != TLS_MINOR_VER_THREE)
591 if (en->iv_len != TLS_CHACHA20_IV_LEN)
598 tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
600 counter_u64_add(ktls_offload_active, 1);
602 refcount_init(&tls->refcount, 1);
603 TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
605 tls->wq_index = ktls_get_cpu(so);
607 tls->params.cipher_algorithm = en->cipher_algorithm;
608 tls->params.auth_algorithm = en->auth_algorithm;
609 tls->params.tls_vmajor = en->tls_vmajor;
610 tls->params.tls_vminor = en->tls_vminor;
611 tls->params.flags = en->flags;
612 tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
614 /* Set the header and trailer lengths. */
615 tls->params.tls_hlen = sizeof(struct tls_record_layer);
616 switch (en->cipher_algorithm) {
617 case CRYPTO_AES_NIST_GCM_16:
619 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
620 * nonce. TLS 1.3 uses a 12 byte implicit IV.
622 if (en->tls_vminor < TLS_MINOR_VER_THREE)
623 tls->params.tls_hlen += sizeof(uint64_t);
624 tls->params.tls_tlen = AES_GMAC_HASH_LEN;
625 tls->params.tls_bs = 1;
628 switch (en->auth_algorithm) {
629 case CRYPTO_SHA1_HMAC:
630 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
631 /* Implicit IV, no nonce. */
633 tls->params.tls_hlen += AES_BLOCK_LEN;
635 tls->params.tls_tlen = AES_BLOCK_LEN +
638 case CRYPTO_SHA2_256_HMAC:
639 tls->params.tls_hlen += AES_BLOCK_LEN;
640 tls->params.tls_tlen = AES_BLOCK_LEN +
643 case CRYPTO_SHA2_384_HMAC:
644 tls->params.tls_hlen += AES_BLOCK_LEN;
645 tls->params.tls_tlen = AES_BLOCK_LEN +
649 panic("invalid hmac");
651 tls->params.tls_bs = AES_BLOCK_LEN;
653 case CRYPTO_CHACHA20_POLY1305:
655 * Chacha20 uses a 12 byte implicit IV.
657 tls->params.tls_tlen = POLY1305_HASH_LEN;
658 tls->params.tls_bs = 1;
661 panic("invalid cipher");
665 * TLS 1.3 includes optional padding which we do not support,
666 * and also puts the "real" record type at the end of the
669 if (en->tls_vminor == TLS_MINOR_VER_THREE)
670 tls->params.tls_tlen += sizeof(uint8_t);
672 KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
673 ("TLS header length too long: %d", tls->params.tls_hlen));
674 KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
675 ("TLS trailer length too long: %d", tls->params.tls_tlen));
677 if (en->auth_key_len != 0) {
678 tls->params.auth_key_len = en->auth_key_len;
679 tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
681 error = copyin(en->auth_key, tls->params.auth_key,
687 tls->params.cipher_key_len = en->cipher_key_len;
688 tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
689 error = copyin(en->cipher_key, tls->params.cipher_key,
695 * This holds the implicit portion of the nonce for AEAD
696 * ciphers and the initial implicit IV for TLS 1.0. The
697 * explicit portions of the IV are generated in ktls_frame().
699 if (en->iv_len != 0) {
700 tls->params.iv_len = en->iv_len;
701 error = copyin(en->iv, tls->params.iv, en->iv_len);
706 * For TLS 1.2 with GCM, generate an 8-byte nonce as a
707 * counter to generate unique explicit IVs.
709 * Store this counter in the last 8 bytes of the IV
710 * array so that it is 8-byte aligned.
712 if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
713 en->tls_vminor == TLS_MINOR_VER_TWO)
714 arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
725 static struct ktls_session *
726 ktls_clone_session(struct ktls_session *tls)
728 struct ktls_session *tls_new;
730 tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
732 counter_u64_add(ktls_offload_active, 1);
734 refcount_init(&tls_new->refcount, 1);
736 /* Copy fields from existing session. */
737 tls_new->params = tls->params;
738 tls_new->wq_index = tls->wq_index;
740 /* Deep copy keys. */
741 if (tls_new->params.auth_key != NULL) {
742 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
744 memcpy(tls_new->params.auth_key, tls->params.auth_key,
745 tls->params.auth_key_len);
748 tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
750 memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
751 tls->params.cipher_key_len);
758 ktls_cleanup(struct ktls_session *tls)
761 counter_u64_add(ktls_offload_active, -1);
763 case TCP_TLS_MODE_SW:
764 MPASS(tls->be != NULL);
765 switch (tls->params.cipher_algorithm) {
767 counter_u64_add(ktls_sw_cbc, -1);
769 case CRYPTO_AES_NIST_GCM_16:
770 counter_u64_add(ktls_sw_gcm, -1);
772 case CRYPTO_CHACHA20_POLY1305:
773 counter_u64_add(ktls_sw_chacha20, -1);
778 case TCP_TLS_MODE_IFNET:
779 switch (tls->params.cipher_algorithm) {
781 counter_u64_add(ktls_ifnet_cbc, -1);
783 case CRYPTO_AES_NIST_GCM_16:
784 counter_u64_add(ktls_ifnet_gcm, -1);
786 case CRYPTO_CHACHA20_POLY1305:
787 counter_u64_add(ktls_ifnet_chacha20, -1);
790 if (tls->snd_tag != NULL)
791 m_snd_tag_rele(tls->snd_tag);
794 case TCP_TLS_MODE_TOE:
795 switch (tls->params.cipher_algorithm) {
797 counter_u64_add(ktls_toe_cbc, -1);
799 case CRYPTO_AES_NIST_GCM_16:
800 counter_u64_add(ktls_toe_gcm, -1);
802 case CRYPTO_CHACHA20_POLY1305:
803 counter_u64_add(ktls_toe_chacha20, -1);
809 if (tls->params.auth_key != NULL) {
810 zfree(tls->params.auth_key, M_KTLS);
811 tls->params.auth_key = NULL;
812 tls->params.auth_key_len = 0;
814 if (tls->params.cipher_key != NULL) {
815 zfree(tls->params.cipher_key, M_KTLS);
816 tls->params.cipher_key = NULL;
817 tls->params.cipher_key_len = 0;
819 explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
822 #if defined(INET) || defined(INET6)
826 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
834 if (inp->inp_flags2 & INP_FREED) {
838 if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
842 if (inp->inp_socket == NULL) {
847 if (!(tp->t_flags & TF_TOE)) {
852 error = tcp_offload_alloc_tls_session(tp, tls, direction);
855 tls->mode = TCP_TLS_MODE_TOE;
856 switch (tls->params.cipher_algorithm) {
858 counter_u64_add(ktls_toe_cbc, 1);
860 case CRYPTO_AES_NIST_GCM_16:
861 counter_u64_add(ktls_toe_gcm, 1);
863 case CRYPTO_CHACHA20_POLY1305:
864 counter_u64_add(ktls_toe_chacha20, 1);
873 * Common code used when first enabling ifnet TLS on a connection or
874 * when allocating a new ifnet TLS session due to a routing change.
875 * This function allocates a new TLS send tag on whatever interface
876 * the connection is currently routed over.
879 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
880 struct m_snd_tag **mstp)
882 union if_snd_tag_alloc_params params;
884 struct nhop_object *nh;
889 if (inp->inp_flags2 & INP_FREED) {
893 if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
897 if (inp->inp_socket == NULL) {
904 * Check administrative controls on ifnet TLS to determine if
905 * ifnet TLS should be denied.
907 * - Always permit 'force' requests.
908 * - ktls_ifnet_permitted == 0: always deny.
910 if (!force && ktls_ifnet_permitted == 0) {
916 * XXX: Use the cached route in the inpcb to find the
917 * interface. This should perhaps instead use
918 * rtalloc1_fib(dst, 0, 0, fibnum). Since KTLS is only
919 * enabled after a connection has completed key negotiation in
920 * userland, the cached route will be present in practice.
922 nh = inp->inp_route.ro_nh;
931 * Allocate a TLS + ratelimit tag if the connection has an
932 * existing pacing rate.
934 if (tp->t_pacing_rate != -1 &&
935 (ifp->if_capenable & IFCAP_TXTLS_RTLMT) != 0) {
936 params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
937 params.tls_rate_limit.inp = inp;
938 params.tls_rate_limit.tls = tls;
939 params.tls_rate_limit.max_rate = tp->t_pacing_rate;
941 params.hdr.type = IF_SND_TAG_TYPE_TLS;
942 params.tls.inp = inp;
943 params.tls.tls = tls;
945 params.hdr.flowid = inp->inp_flowid;
946 params.hdr.flowtype = inp->inp_flowtype;
947 params.hdr.numa_domain = inp->inp_numa_domain;
950 if ((ifp->if_capenable & IFCAP_MEXTPG) == 0) {
954 if (inp->inp_vflag & INP_IPV6) {
955 if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
960 if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
965 error = m_snd_tag_alloc(ifp, ¶ms, mstp);
972 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
974 struct m_snd_tag *mst;
977 error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
979 tls->mode = TCP_TLS_MODE_IFNET;
981 switch (tls->params.cipher_algorithm) {
983 counter_u64_add(ktls_ifnet_cbc, 1);
985 case CRYPTO_AES_NIST_GCM_16:
986 counter_u64_add(ktls_ifnet_gcm, 1);
988 case CRYPTO_CHACHA20_POLY1305:
989 counter_u64_add(ktls_ifnet_chacha20, 1);
997 ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
999 struct rm_priotracker prio;
1000 struct ktls_crypto_backend *be;
1003 * Choose the best software crypto backend. Backends are
1004 * stored in sorted priority order (larget value == most
1005 * important at the head of the list), so this just stops on
1006 * the first backend that claims the session by returning
1009 if (ktls_allow_unload)
1010 rm_rlock(&ktls_backends_lock, &prio);
1011 LIST_FOREACH(be, &ktls_backends, next) {
1012 if (be->try(so, tls, direction) == 0)
1014 KASSERT(tls->cipher == NULL,
1015 ("ktls backend leaked a cipher pointer"));
1018 if (ktls_allow_unload)
1022 if (ktls_allow_unload)
1023 rm_runlock(&ktls_backends_lock, &prio);
1025 return (EOPNOTSUPP);
1026 tls->mode = TCP_TLS_MODE_SW;
1027 switch (tls->params.cipher_algorithm) {
1028 case CRYPTO_AES_CBC:
1029 counter_u64_add(ktls_sw_cbc, 1);
1031 case CRYPTO_AES_NIST_GCM_16:
1032 counter_u64_add(ktls_sw_gcm, 1);
1034 case CRYPTO_CHACHA20_POLY1305:
1035 counter_u64_add(ktls_sw_chacha20, 1);
1042 * KTLS RX stores data in the socket buffer as a list of TLS records,
1043 * where each record is stored as a control message containg the TLS
1044 * header followed by data mbufs containing the decrypted data. This
1045 * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
1046 * both encrypted and decrypted data. TLS records decrypted by a NIC
1047 * should be queued to the socket buffer as records, but encrypted
1048 * data which needs to be decrypted by software arrives as a stream of
1049 * regular mbufs which need to be converted. In addition, there may
1050 * already be pending encrypted data in the socket buffer when KTLS RX
1053 * To manage not-yet-decrypted data for KTLS RX, the following scheme
1056 * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
1058 * - ktls_check_rx checks this chain of mbufs reading the TLS header
1059 * from the first mbuf. Once all of the data for that TLS record is
1060 * queued, the socket is queued to a worker thread.
1062 * - The worker thread calls ktls_decrypt to decrypt TLS records in
1063 * the TLS chain. Each TLS record is detached from the TLS chain,
1064 * decrypted, and inserted into the regular socket buffer chain as
1065 * record starting with a control message holding the TLS header and
1066 * a chain of mbufs holding the encrypted data.
1070 sb_mark_notready(struct sockbuf *sb)
1077 sb->sb_mbtail = NULL;
1078 sb->sb_lastrecord = NULL;
1079 for (; m != NULL; m = m->m_next) {
1080 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
1082 KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
1084 KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
1086 m->m_flags |= M_NOTREADY;
1087 sb->sb_acc -= m->m_len;
1088 sb->sb_tlscc += m->m_len;
1089 sb->sb_mtlstail = m;
1091 KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
1092 ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
1097 ktls_enable_rx(struct socket *so, struct tls_enable *en)
1099 struct ktls_session *tls;
1102 if (!ktls_offload_enable)
1104 if (SOLISTENING(so))
1107 counter_u64_add(ktls_offload_enable_calls, 1);
1110 * This should always be true since only the TCP socket option
1111 * invokes this function.
1113 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1117 * XXX: Don't overwrite existing sessions. We should permit
1118 * this to support rekeying in the future.
1120 if (so->so_rcv.sb_tls_info != NULL)
1123 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1126 /* TLS 1.3 is not yet supported. */
1127 if (en->tls_vmajor == TLS_MAJOR_VER_ONE &&
1128 en->tls_vminor == TLS_MINOR_VER_THREE)
1131 error = ktls_create_session(so, en, &tls);
1136 error = ktls_try_toe(so, tls, KTLS_RX);
1139 error = ktls_try_sw(so, tls, KTLS_RX);
1146 /* Mark the socket as using TLS offload. */
1147 SOCKBUF_LOCK(&so->so_rcv);
1148 so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1149 so->so_rcv.sb_tls_info = tls;
1150 so->so_rcv.sb_flags |= SB_TLS_RX;
1152 /* Mark existing data as not ready until it can be decrypted. */
1153 sb_mark_notready(&so->so_rcv);
1154 ktls_check_rx(&so->so_rcv);
1155 SOCKBUF_UNLOCK(&so->so_rcv);
1157 counter_u64_add(ktls_offload_total, 1);
1163 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1165 struct ktls_session *tls;
1169 if (!ktls_offload_enable)
1171 if (SOLISTENING(so))
1174 counter_u64_add(ktls_offload_enable_calls, 1);
1177 * This should always be true since only the TCP socket option
1178 * invokes this function.
1180 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1184 * XXX: Don't overwrite existing sessions. We should permit
1185 * this to support rekeying in the future.
1187 if (so->so_snd.sb_tls_info != NULL)
1190 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1193 /* TLS requires ext pgs */
1194 if (mb_use_ext_pgs == 0)
1197 error = ktls_create_session(so, en, &tls);
1201 /* Prefer TOE -> ifnet TLS -> software TLS. */
1203 error = ktls_try_toe(so, tls, KTLS_TX);
1206 error = ktls_try_ifnet(so, tls, false);
1208 error = ktls_try_sw(so, tls, KTLS_TX);
1215 error = sblock(&so->so_snd, SBL_WAIT);
1222 * Write lock the INP when setting sb_tls_info so that
1223 * routines in tcp_ratelimit.c can read sb_tls_info while
1224 * holding the INP lock.
1228 SOCKBUF_LOCK(&so->so_snd);
1229 so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1230 so->so_snd.sb_tls_info = tls;
1231 if (tls->mode != TCP_TLS_MODE_SW)
1232 so->so_snd.sb_flags |= SB_TLS_IFNET;
1233 SOCKBUF_UNLOCK(&so->so_snd);
1235 sbunlock(&so->so_snd);
1237 counter_u64_add(ktls_offload_total, 1);
1243 ktls_get_rx_mode(struct socket *so)
1245 struct ktls_session *tls;
1249 if (SOLISTENING(so))
1252 INP_WLOCK_ASSERT(inp);
1253 SOCKBUF_LOCK(&so->so_rcv);
1254 tls = so->so_rcv.sb_tls_info;
1256 mode = TCP_TLS_MODE_NONE;
1259 SOCKBUF_UNLOCK(&so->so_rcv);
1264 ktls_get_tx_mode(struct socket *so)
1266 struct ktls_session *tls;
1270 if (SOLISTENING(so))
1273 INP_WLOCK_ASSERT(inp);
1274 SOCKBUF_LOCK(&so->so_snd);
1275 tls = so->so_snd.sb_tls_info;
1277 mode = TCP_TLS_MODE_NONE;
1280 SOCKBUF_UNLOCK(&so->so_snd);
1285 * Switch between SW and ifnet TLS sessions as requested.
1288 ktls_set_tx_mode(struct socket *so, int mode)
1290 struct ktls_session *tls, *tls_new;
1294 if (SOLISTENING(so))
1297 case TCP_TLS_MODE_SW:
1298 case TCP_TLS_MODE_IFNET:
1305 INP_WLOCK_ASSERT(inp);
1306 SOCKBUF_LOCK(&so->so_snd);
1307 tls = so->so_snd.sb_tls_info;
1309 SOCKBUF_UNLOCK(&so->so_snd);
1313 if (tls->mode == mode) {
1314 SOCKBUF_UNLOCK(&so->so_snd);
1318 tls = ktls_hold(tls);
1319 SOCKBUF_UNLOCK(&so->so_snd);
1322 tls_new = ktls_clone_session(tls);
1324 if (mode == TCP_TLS_MODE_IFNET)
1325 error = ktls_try_ifnet(so, tls_new, true);
1327 error = ktls_try_sw(so, tls_new, KTLS_TX);
1329 counter_u64_add(ktls_switch_failed, 1);
1336 error = sblock(&so->so_snd, SBL_WAIT);
1338 counter_u64_add(ktls_switch_failed, 1);
1346 * If we raced with another session change, keep the existing
1349 if (tls != so->so_snd.sb_tls_info) {
1350 counter_u64_add(ktls_switch_failed, 1);
1351 sbunlock(&so->so_snd);
1358 SOCKBUF_LOCK(&so->so_snd);
1359 so->so_snd.sb_tls_info = tls_new;
1360 if (tls_new->mode != TCP_TLS_MODE_SW)
1361 so->so_snd.sb_flags |= SB_TLS_IFNET;
1362 SOCKBUF_UNLOCK(&so->so_snd);
1363 sbunlock(&so->so_snd);
1366 * Drop two references on 'tls'. The first is for the
1367 * ktls_hold() above. The second drops the reference from the
1370 KASSERT(tls->refcount >= 2, ("too few references on old session"));
1374 if (mode == TCP_TLS_MODE_IFNET)
1375 counter_u64_add(ktls_switch_to_ifnet, 1);
1377 counter_u64_add(ktls_switch_to_sw, 1);
1384 * Try to allocate a new TLS send tag. This task is scheduled when
1385 * ip_output detects a route change while trying to transmit a packet
1386 * holding a TLS record. If a new tag is allocated, replace the tag
1387 * in the TLS session. Subsequent packets on the connection will use
1388 * the new tag. If a new tag cannot be allocated, drop the
1392 ktls_reset_send_tag(void *context, int pending)
1394 struct epoch_tracker et;
1395 struct ktls_session *tls;
1396 struct m_snd_tag *old, *new;
1401 MPASS(pending == 1);
1407 * Free the old tag first before allocating a new one.
1408 * ip[6]_output_send() will treat a NULL send tag the same as
1409 * an ifp mismatch and drop packets until a new tag is
1412 * Write-lock the INP when changing tls->snd_tag since
1413 * ip[6]_output_send() holds a read-lock when reading the
1418 tls->snd_tag = NULL;
1421 m_snd_tag_rele(old);
1423 error = ktls_alloc_snd_tag(inp, tls, true, &new);
1428 mtx_pool_lock(mtxpool_sleep, tls);
1429 tls->reset_pending = false;
1430 mtx_pool_unlock(mtxpool_sleep, tls);
1431 if (!in_pcbrele_wlocked(inp))
1434 counter_u64_add(ktls_ifnet_reset, 1);
1437 * XXX: Should we kick tcp_output explicitly now that
1438 * the send tag is fixed or just rely on timers?
1441 NET_EPOCH_ENTER(et);
1443 if (!in_pcbrele_wlocked(inp)) {
1444 if (!(inp->inp_flags & INP_TIMEWAIT) &&
1445 !(inp->inp_flags & INP_DROPPED)) {
1446 tp = intotcpcb(inp);
1447 CURVNET_SET(tp->t_vnet);
1448 tp = tcp_drop(tp, ECONNABORTED);
1452 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1458 counter_u64_add(ktls_ifnet_reset_failed, 1);
1461 * Leave reset_pending true to avoid future tasks while
1462 * the socket goes away.
1470 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1476 INP_LOCK_ASSERT(inp);
1479 * See if we should schedule a task to update the send tag for
1482 mtx_pool_lock(mtxpool_sleep, tls);
1483 if (!tls->reset_pending) {
1484 (void) ktls_hold(tls);
1487 tls->reset_pending = true;
1488 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1490 mtx_pool_unlock(mtxpool_sleep, tls);
1496 ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1498 union if_snd_tag_modify_params params = {
1499 .rate_limit.max_rate = max_pacing_rate,
1500 .rate_limit.flags = M_NOWAIT,
1502 struct m_snd_tag *mst;
1506 /* Can't get to the inp, but it should be locked. */
1507 /* INP_LOCK_ASSERT(inp); */
1509 MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1511 if (tls->snd_tag == NULL) {
1513 * Resetting send tag, ignore this change. The
1514 * pending reset may or may not see this updated rate
1515 * in the tcpcb. If it doesn't, we will just lose
1521 MPASS(tls->snd_tag != NULL);
1522 MPASS(tls->snd_tag->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1526 return (ifp->if_snd_tag_modify(mst, ¶ms));
1532 ktls_destroy(struct ktls_session *tls)
1534 struct rm_priotracker prio;
1537 if (tls->be != NULL && ktls_allow_unload) {
1538 rm_rlock(&ktls_backends_lock, &prio);
1539 tls->be->use_count--;
1540 rm_runlock(&ktls_backends_lock, &prio);
1542 uma_zfree(ktls_session_zone, tls);
1546 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1549 for (; m != NULL; m = m->m_next) {
1550 KASSERT((m->m_flags & M_EXTPG) != 0,
1551 ("ktls_seq: mapped mbuf %p", m));
1553 m->m_epg_seqno = sb->sb_tls_seqno;
1559 * Add TLS framing (headers and trailers) to a chain of mbufs. Each
1560 * mbuf in the chain must be an unmapped mbuf. The payload of the
1561 * mbuf must be populated with the payload of each TLS record.
1563 * The record_type argument specifies the TLS record type used when
1564 * populating the TLS header.
1566 * The enq_count argument on return is set to the number of pages of
1567 * payload data for this entire chain that need to be encrypted via SW
1568 * encryption. The returned value should be passed to ktls_enqueue
1569 * when scheduling encryption of this chain of mbufs. To handle the
1570 * special case of empty fragments for TLS 1.0 sessions, an empty
1571 * fragment counts as one page.
1574 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1575 uint8_t record_type)
1577 struct tls_record_layer *tlshdr;
1583 maxlen = tls->params.max_frame_len;
1585 for (m = top; m != NULL; m = m->m_next) {
1587 * All mbufs in the chain should be TLS records whose
1588 * payload does not exceed the maximum frame length.
1590 * Empty TLS records are permitted when using CBC.
1592 KASSERT(m->m_len <= maxlen &&
1593 (tls->params.cipher_algorithm == CRYPTO_AES_CBC ?
1594 m->m_len >= 0 : m->m_len > 0),
1595 ("ktls_frame: m %p len %d\n", m, m->m_len));
1598 * TLS frames require unmapped mbufs to store session
1601 KASSERT((m->m_flags & M_EXTPG) != 0,
1602 ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1606 /* Save a reference to the session. */
1607 m->m_epg_tls = ktls_hold(tls);
1609 m->m_epg_hdrlen = tls->params.tls_hlen;
1610 m->m_epg_trllen = tls->params.tls_tlen;
1611 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1615 * AES-CBC pads messages to a multiple of the
1616 * block size. Note that the padding is
1617 * applied after the digest and the encryption
1618 * is done on the "plaintext || mac || padding".
1619 * At least one byte of padding is always
1622 * Compute the final trailer length assuming
1623 * at most one block of padding.
1624 * tls->params.sb_tls_tlen is the maximum
1625 * possible trailer length (padding + digest).
1626 * delta holds the number of excess padding
1627 * bytes if the maximum were used. Those
1628 * extra bytes are removed.
1630 bs = tls->params.tls_bs;
1631 delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1632 m->m_epg_trllen -= delta;
1634 m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1636 /* Populate the TLS header. */
1637 tlshdr = (void *)m->m_epg_hdr;
1638 tlshdr->tls_vmajor = tls->params.tls_vmajor;
1641 * TLS 1.3 masquarades as TLS 1.2 with a record type
1642 * of TLS_RLTYPE_APP.
1644 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1645 tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1646 tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1647 tlshdr->tls_type = TLS_RLTYPE_APP;
1648 /* save the real record type for later */
1649 m->m_epg_record_type = record_type;
1650 m->m_epg_trail[0] = record_type;
1652 tlshdr->tls_vminor = tls->params.tls_vminor;
1653 tlshdr->tls_type = record_type;
1655 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1658 * Store nonces / explicit IVs after the end of the
1661 * For GCM with TLS 1.2, an 8 byte nonce is copied
1662 * from the end of the IV. The nonce is then
1663 * incremented for use by the next record.
1665 * For CBC, a random nonce is inserted for TLS 1.1+.
1667 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
1668 tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
1669 noncep = (uint64_t *)(tls->params.iv + 8);
1670 be64enc(tlshdr + 1, *noncep);
1672 } else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1673 tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1674 arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1677 * When using SW encryption, mark the mbuf not ready.
1678 * It will be marked ready via sbready() after the
1679 * record has been encrypted.
1681 * When using ifnet TLS, unencrypted TLS records are
1682 * sent down the stack to the NIC.
1684 if (tls->mode == TCP_TLS_MODE_SW) {
1685 m->m_flags |= M_NOTREADY;
1686 m->m_epg_nrdy = m->m_epg_npgs;
1687 if (__predict_false(tls_len == 0)) {
1688 /* TLS 1.0 empty fragment. */
1691 *enq_cnt += m->m_epg_npgs;
1697 ktls_check_rx(struct sockbuf *sb)
1699 struct tls_record_layer hdr;
1704 SOCKBUF_LOCK_ASSERT(sb);
1705 KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1707 so = __containerof(sb, struct socket, so_rcv);
1709 if (sb->sb_flags & SB_TLS_RX_RUNNING)
1712 /* Is there enough queued for a TLS header? */
1713 if (sb->sb_tlscc < sizeof(hdr)) {
1714 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
1715 so->so_error = EMSGSIZE;
1719 m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
1721 /* Is the entire record queued? */
1722 if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
1723 if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
1724 so->so_error = EMSGSIZE;
1728 sb->sb_flags |= SB_TLS_RX_RUNNING;
1731 wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
1733 STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
1734 running = wq->running;
1735 mtx_unlock(&wq->mtx);
1738 counter_u64_add(ktls_cnt_rx_queued, 1);
1741 static struct mbuf *
1742 ktls_detach_record(struct sockbuf *sb, int len)
1744 struct mbuf *m, *n, *top;
1747 SOCKBUF_LOCK_ASSERT(sb);
1748 MPASS(len <= sb->sb_tlscc);
1751 * If TLS chain is the exact size of the record,
1752 * just grab the whole record.
1755 if (sb->sb_tlscc == len) {
1757 sb->sb_mtlstail = NULL;
1762 * While it would be nice to use m_split() here, we need
1763 * to know exactly what m_split() allocates to update the
1764 * accounting, so do it inline instead.
1767 for (m = top; remain > m->m_len; m = m->m_next)
1770 /* Easy case: don't have to split 'm'. */
1771 if (remain == m->m_len) {
1772 sb->sb_mtls = m->m_next;
1773 if (sb->sb_mtls == NULL)
1774 sb->sb_mtlstail = NULL;
1780 * Need to allocate an mbuf to hold the remainder of 'm'. Try
1781 * with M_NOWAIT first.
1783 n = m_get(M_NOWAIT, MT_DATA);
1786 * Use M_WAITOK with socket buffer unlocked. If
1787 * 'sb_mtls' changes while the lock is dropped, return
1788 * NULL to force the caller to retry.
1792 n = m_get(M_WAITOK, MT_DATA);
1795 if (sb->sb_mtls != top) {
1800 n->m_flags |= M_NOTREADY;
1802 /* Store remainder in 'n'. */
1803 n->m_len = m->m_len - remain;
1804 if (m->m_flags & M_EXT) {
1805 n->m_data = m->m_data + remain;
1808 bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
1811 /* Trim 'm' and update accounting. */
1812 m->m_len -= n->m_len;
1813 sb->sb_tlscc -= n->m_len;
1814 sb->sb_ccc -= n->m_len;
1816 /* Account for 'n'. */
1817 sballoc_ktls_rx(sb, n);
1819 /* Insert 'n' into the TLS chain. */
1821 n->m_next = m->m_next;
1822 if (sb->sb_mtlstail == m)
1823 sb->sb_mtlstail = n;
1825 /* Detach the record from the TLS chain. */
1829 MPASS(m_length(top, NULL) == len);
1830 for (m = top; m != NULL; m = m->m_next)
1831 sbfree_ktls_rx(sb, m);
1832 sb->sb_tlsdcc = len;
1839 ktls_decrypt(struct socket *so)
1841 char tls_header[MBUF_PEXT_HDR_LEN];
1842 struct ktls_session *tls;
1844 struct tls_record_layer *hdr;
1845 struct tls_get_record tgr;
1846 struct mbuf *control, *data, *m;
1848 int error, remain, tls_len, trail_len;
1850 hdr = (struct tls_record_layer *)tls_header;
1853 KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
1854 ("%s: socket %p not running", __func__, so));
1856 tls = sb->sb_tls_info;
1860 /* Is there enough queued for a TLS header? */
1861 if (sb->sb_tlscc < tls->params.tls_hlen)
1864 m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
1865 tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
1867 if (hdr->tls_vmajor != tls->params.tls_vmajor ||
1868 hdr->tls_vminor != tls->params.tls_vminor)
1870 else if (tls_len < tls->params.tls_hlen || tls_len >
1871 tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
1872 tls->params.tls_tlen)
1876 if (__predict_false(error != 0)) {
1878 * We have a corrupted record and are likely
1879 * out of sync. The connection isn't
1880 * recoverable at this point, so abort it.
1883 counter_u64_add(ktls_offload_corrupted_records, 1);
1885 CURVNET_SET(so->so_vnet);
1886 so->so_proto->pr_usrreqs->pru_abort(so);
1887 so->so_error = error;
1892 /* Is the entire record queued? */
1893 if (sb->sb_tlscc < tls_len)
1897 * Split out the portion of the mbuf chain containing
1900 data = ktls_detach_record(sb, tls_len);
1903 MPASS(sb->sb_tlsdcc == tls_len);
1905 seqno = sb->sb_tls_seqno;
1910 error = tls->sw_decrypt(tls, hdr, data, seqno, &trail_len);
1912 counter_u64_add(ktls_offload_failed_crypto, 1);
1915 if (sb->sb_tlsdcc == 0) {
1917 * sbcut/drop/flush discarded these
1925 * Drop this TLS record's data, but keep
1926 * decrypting subsequent records.
1928 sb->sb_ccc -= tls_len;
1931 CURVNET_SET(so->so_vnet);
1932 so->so_error = EBADMSG;
1933 sorwakeup_locked(so);
1942 /* Allocate the control mbuf. */
1943 tgr.tls_type = hdr->tls_type;
1944 tgr.tls_vmajor = hdr->tls_vmajor;
1945 tgr.tls_vminor = hdr->tls_vminor;
1946 tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
1948 control = sbcreatecontrol_how(&tgr, sizeof(tgr),
1949 TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
1952 if (sb->sb_tlsdcc == 0) {
1953 /* sbcut/drop/flush discarded these mbufs. */
1954 MPASS(sb->sb_tlscc == 0);
1961 * Clear the 'dcc' accounting in preparation for
1962 * adding the decrypted record.
1964 sb->sb_ccc -= tls_len;
1968 /* If there is no payload, drop all of the data. */
1969 if (tgr.tls_length == htobe16(0)) {
1974 remain = tls->params.tls_hlen;
1975 while (remain > 0) {
1976 if (data->m_len > remain) {
1977 data->m_data += remain;
1978 data->m_len -= remain;
1981 remain -= data->m_len;
1982 data = m_free(data);
1985 /* Trim trailer and clear M_NOTREADY. */
1986 remain = be16toh(tgr.tls_length);
1988 for (m = data; remain > m->m_len; m = m->m_next) {
1989 m->m_flags &= ~M_NOTREADY;
1995 m->m_flags &= ~M_NOTREADY;
1997 /* Set EOR on the final mbuf. */
1998 m->m_flags |= M_EOR;
2001 sbappendcontrol_locked(sb, data, control, 0);
2004 sb->sb_flags &= ~SB_TLS_RX_RUNNING;
2006 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
2007 so->so_error = EMSGSIZE;
2009 sorwakeup_locked(so);
2012 SOCKBUF_UNLOCK_ASSERT(sb);
2014 CURVNET_SET(so->so_vnet);
2021 ktls_enqueue_to_free(struct mbuf *m)
2026 /* Mark it for freeing. */
2027 m->m_epg_flags |= EPG_FLAG_2FREE;
2028 wq = &ktls_wq[m->m_epg_tls->wq_index];
2030 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2031 running = wq->running;
2032 mtx_unlock(&wq->mtx);
2038 ktls_buffer_alloc(struct ktls_wq *wq, struct mbuf *m)
2042 if (m->m_epg_npgs <= 2)
2044 if (ktls_buffer_zone == NULL)
2046 if ((u_int)(ticks - wq->lastallocfail) < hz) {
2048 * Rate-limit allocation attempts after a failure.
2049 * ktls_buffer_import() will acquire a per-domain mutex to check
2050 * the free page queues and may fail consistently if memory is
2055 buf = uma_zalloc(ktls_buffer_zone, M_NOWAIT | M_NORECLAIM);
2057 wq->lastallocfail = ticks;
2062 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
2067 KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2068 (M_EXTPG | M_NOTREADY)),
2069 ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
2070 KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
2072 KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
2074 m->m_epg_enc_cnt = page_count;
2077 * Save a pointer to the socket. The caller is responsible
2078 * for taking an additional reference via soref().
2082 wq = &ktls_wq[m->m_epg_tls->wq_index];
2084 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2085 running = wq->running;
2086 mtx_unlock(&wq->mtx);
2089 counter_u64_add(ktls_cnt_tx_queued, 1);
2092 static __noinline void
2093 ktls_encrypt(struct ktls_wq *wq, struct mbuf *top)
2095 struct ktls_session *tls;
2098 vm_paddr_t parray[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
2099 struct iovec src_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
2100 struct iovec dst_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
2103 int error, i, len, npages, off, total_pages;
2107 tls = top->m_epg_tls;
2108 KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
2109 KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
2111 top->m_epg_so = NULL;
2113 total_pages = top->m_epg_enc_cnt;
2117 * Encrypt the TLS records in the chain of mbufs starting with
2118 * 'top'. 'total_pages' gives us a total count of pages and is
2119 * used to know when we have finished encrypting the TLS
2120 * records originally queued with 'top'.
2122 * NB: These mbufs are queued in the socket buffer and
2123 * 'm_next' is traversing the mbufs in the socket buffer. The
2124 * socket buffer lock is not held while traversing this chain.
2125 * Since the mbufs are all marked M_NOTREADY their 'm_next'
2126 * pointers should be stable. However, the 'm_next' of the
2127 * last mbuf encrypted is not necessarily NULL. It can point
2128 * to other mbufs appended while 'top' was on the TLS work
2131 * Each mbuf holds an entire TLS record.
2134 for (m = top; npages != total_pages; m = m->m_next) {
2135 KASSERT(m->m_epg_tls == tls,
2136 ("different TLS sessions in a single mbuf chain: %p vs %p",
2137 tls, m->m_epg_tls));
2138 KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2139 (M_EXTPG | M_NOTREADY),
2140 ("%p not unready & nomap mbuf (top = %p)\n", m, top));
2141 KASSERT(npages + m->m_epg_npgs <= total_pages,
2142 ("page count mismatch: top %p, total_pages %d, m %p", top,
2144 KASSERT(ptoa(m->m_epg_npgs) <= ktls_maxlen,
2145 ("page count %d larger than maximum frame length %d",
2146 m->m_epg_npgs, ktls_maxlen));
2149 * Generate source and destination ivoecs to pass to
2150 * the SW encryption backend. For writable mbufs, the
2151 * destination iovec is a copy of the source and
2152 * encryption is done in place. For file-backed mbufs
2153 * (from sendfile), anonymous wired pages are
2154 * allocated and assigned to the destination iovec.
2156 is_anon = (m->m_epg_flags & EPG_FLAG_ANON) != 0;
2158 off = m->m_epg_1st_off;
2159 for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2160 len = m_epg_pagelen(m, i, off);
2161 src_iov[i].iov_len = len;
2162 src_iov[i].iov_base =
2163 (char *)(void *)PHYS_TO_DMAP(m->m_epg_pa[i]) + off;
2167 memcpy(dst_iov, src_iov, i * sizeof(struct iovec));
2168 } else if ((cbuf = ktls_buffer_alloc(wq, m)) != NULL) {
2169 len = ptoa(m->m_epg_npgs - 1) + m->m_epg_last_len -
2171 dst_iov[0].iov_base = (char *)cbuf + m->m_epg_1st_off;
2172 dst_iov[0].iov_len = len;
2173 parray[0] = DMAP_TO_PHYS((vm_offset_t)cbuf);
2177 off = m->m_epg_1st_off;
2178 for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2180 pg = vm_page_alloc(NULL, 0,
2186 } while (pg == NULL);
2188 len = m_epg_pagelen(m, i, off);
2189 parray[i] = VM_PAGE_TO_PHYS(pg);
2190 dst_iov[i].iov_base =
2191 (char *)(void *)PHYS_TO_DMAP(
2193 dst_iov[i].iov_len = len;
2197 if (__predict_false(m->m_epg_npgs == 0)) {
2198 /* TLS 1.0 empty fragment. */
2201 npages += m->m_epg_npgs;
2203 error = (*tls->sw_encrypt)(tls,
2204 (const struct tls_record_layer *)m->m_epg_hdr,
2205 m->m_epg_trail, src_iov, dst_iov, m->m_epg_npgs, i,
2206 m->m_epg_seqno, m->m_epg_record_type);
2208 counter_u64_add(ktls_offload_failed_crypto, 1);
2213 * For file-backed mbufs, release the file-backed
2214 * pages and replace them in the ext_pgs array with
2215 * the anonymous wired pages allocated above.
2218 /* Free the old pages. */
2219 m->m_ext.ext_free(m);
2221 /* Replace them with the new pages. */
2223 for (i = 0; i < m->m_epg_npgs; i++)
2224 m->m_epg_pa[i] = parray[0] + ptoa(i);
2226 /* Contig pages should go back to the cache. */
2227 m->m_ext.ext_free = ktls_free_mext_contig;
2229 for (i = 0; i < m->m_epg_npgs; i++)
2230 m->m_epg_pa[i] = parray[i];
2232 /* Use the basic free routine. */
2233 m->m_ext.ext_free = mb_free_mext_pgs;
2236 /* Pages are now writable. */
2237 m->m_epg_flags |= EPG_FLAG_ANON;
2241 * Drop a reference to the session now that it is no
2242 * longer needed. Existing code depends on encrypted
2243 * records having no associated session vs
2244 * yet-to-be-encrypted records having an associated
2247 m->m_epg_tls = NULL;
2251 CURVNET_SET(so->so_vnet);
2253 (void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
2255 so->so_proto->pr_usrreqs->pru_abort(so);
2257 mb_free_notready(top, total_pages);
2266 ktls_work_thread(void *ctx)
2268 struct ktls_wq *wq = ctx;
2270 struct socket *so, *son;
2271 STAILQ_HEAD(, mbuf) local_m_head;
2272 STAILQ_HEAD(, socket) local_so_head;
2274 if (ktls_bind_threads > 1) {
2275 curthread->td_domain.dr_policy =
2276 DOMAINSET_PREF(PCPU_GET(domain));
2278 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
2283 while (STAILQ_EMPTY(&wq->m_head) &&
2284 STAILQ_EMPTY(&wq->so_head)) {
2285 wq->running = false;
2286 mtx_sleep(wq, &wq->mtx, 0, "-", 0);
2290 STAILQ_INIT(&local_m_head);
2291 STAILQ_CONCAT(&local_m_head, &wq->m_head);
2292 STAILQ_INIT(&local_so_head);
2293 STAILQ_CONCAT(&local_so_head, &wq->so_head);
2294 mtx_unlock(&wq->mtx);
2296 STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
2297 if (m->m_epg_flags & EPG_FLAG_2FREE) {
2298 ktls_free(m->m_epg_tls);
2299 uma_zfree(zone_mbuf, m);
2301 ktls_encrypt(wq, m);
2302 counter_u64_add(ktls_cnt_tx_queued, -1);
2306 STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
2308 counter_u64_add(ktls_cnt_rx_queued, -1);