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;
85 } __aligned(CACHE_LINE_SIZE);
87 struct ktls_domain_info {
92 struct ktls_domain_info ktls_domains[MAXMEMDOM];
93 static struct ktls_wq *ktls_wq;
94 static struct proc *ktls_proc;
95 LIST_HEAD(, ktls_crypto_backend) ktls_backends;
96 static struct rmlock ktls_backends_lock;
97 static uma_zone_t ktls_session_zone;
98 static uint16_t ktls_cpuid_lookup[MAXCPU];
100 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
101 "Kernel TLS offload");
102 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
103 "Kernel TLS offload stats");
105 static int ktls_allow_unload;
106 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, allow_unload, CTLFLAG_RDTUN,
107 &ktls_allow_unload, 0, "Allow software crypto modules to unload");
110 static int ktls_bind_threads = 1;
112 static int ktls_bind_threads;
114 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
115 &ktls_bind_threads, 0,
116 "Bind crypto threads to cores or domains at boot");
118 static u_int ktls_maxlen = 16384;
119 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RWTUN,
120 &ktls_maxlen, 0, "Maximum TLS record size");
122 static int ktls_number_threads;
123 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
124 &ktls_number_threads, 0,
125 "Number of TLS threads in thread-pool");
127 static bool ktls_offload_enable;
128 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RW,
129 &ktls_offload_enable, 0,
130 "Enable support for kernel TLS offload");
132 static bool ktls_cbc_enable = true;
133 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RW,
135 "Enable Support of AES-CBC crypto for kernel TLS");
137 static counter_u64_t ktls_tasks_active;
138 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
139 &ktls_tasks_active, "Number of active tasks");
141 static counter_u64_t ktls_cnt_tx_queued;
142 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_inqueue, CTLFLAG_RD,
144 "Number of TLS records in queue to tasks for SW encryption");
146 static counter_u64_t ktls_cnt_rx_queued;
147 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_rx_inqueue, CTLFLAG_RD,
149 "Number of TLS sockets in queue to tasks for SW decryption");
151 static counter_u64_t ktls_offload_total;
152 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
153 CTLFLAG_RD, &ktls_offload_total,
154 "Total successful TLS setups (parameters set)");
156 static counter_u64_t ktls_offload_enable_calls;
157 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
158 CTLFLAG_RD, &ktls_offload_enable_calls,
159 "Total number of TLS enable calls made");
161 static counter_u64_t ktls_offload_active;
162 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
163 &ktls_offload_active, "Total Active TLS sessions");
165 static counter_u64_t ktls_offload_corrupted_records;
166 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, corrupted_records, CTLFLAG_RD,
167 &ktls_offload_corrupted_records, "Total corrupted TLS records received");
169 static counter_u64_t ktls_offload_failed_crypto;
170 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
171 &ktls_offload_failed_crypto, "Total TLS crypto failures");
173 static counter_u64_t ktls_switch_to_ifnet;
174 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
175 &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
177 static counter_u64_t ktls_switch_to_sw;
178 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
179 &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
181 static counter_u64_t ktls_switch_failed;
182 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
183 &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
185 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
186 "Software TLS session stats");
187 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
188 "Hardware (ifnet) TLS session stats");
190 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
191 "TOE TLS session stats");
194 static counter_u64_t ktls_sw_cbc;
195 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
196 "Active number of software TLS sessions using AES-CBC");
198 static counter_u64_t ktls_sw_gcm;
199 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
200 "Active number of software TLS sessions using AES-GCM");
202 static counter_u64_t ktls_ifnet_cbc;
203 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
205 "Active number of ifnet TLS sessions using AES-CBC");
207 static counter_u64_t ktls_ifnet_gcm;
208 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
210 "Active number of ifnet TLS sessions using AES-GCM");
212 static counter_u64_t ktls_ifnet_reset;
213 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
214 &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
216 static counter_u64_t ktls_ifnet_reset_dropped;
217 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
218 &ktls_ifnet_reset_dropped,
219 "TLS sessions dropped after failing to update ifnet send tag");
221 static counter_u64_t ktls_ifnet_reset_failed;
222 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
223 &ktls_ifnet_reset_failed,
224 "TLS sessions that failed to allocate a new ifnet send tag");
226 static int ktls_ifnet_permitted;
227 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
228 &ktls_ifnet_permitted, 1,
229 "Whether to permit hardware (ifnet) TLS sessions");
232 static counter_u64_t ktls_toe_cbc;
233 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
235 "Active number of TOE TLS sessions using AES-CBC");
237 static counter_u64_t ktls_toe_gcm;
238 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
240 "Active number of TOE TLS sessions using AES-GCM");
243 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
245 static void ktls_cleanup(struct ktls_session *tls);
246 #if defined(INET) || defined(INET6)
247 static void ktls_reset_send_tag(void *context, int pending);
249 static void ktls_work_thread(void *ctx);
252 ktls_crypto_backend_register(struct ktls_crypto_backend *be)
254 struct ktls_crypto_backend *curr_be, *tmp;
256 if (be->api_version != KTLS_API_VERSION) {
257 printf("KTLS: API version mismatch (%d vs %d) for %s\n",
258 be->api_version, KTLS_API_VERSION,
263 rm_wlock(&ktls_backends_lock);
264 printf("KTLS: Registering crypto method %s with prio %d\n",
266 if (LIST_EMPTY(&ktls_backends)) {
267 LIST_INSERT_HEAD(&ktls_backends, be, next);
269 LIST_FOREACH_SAFE(curr_be, &ktls_backends, next, tmp) {
270 if (curr_be->prio < be->prio) {
271 LIST_INSERT_BEFORE(curr_be, be, next);
274 if (LIST_NEXT(curr_be, next) == NULL) {
275 LIST_INSERT_AFTER(curr_be, be, next);
280 rm_wunlock(&ktls_backends_lock);
285 ktls_crypto_backend_deregister(struct ktls_crypto_backend *be)
287 struct ktls_crypto_backend *tmp;
290 * Don't error if the backend isn't registered. This permits
291 * MOD_UNLOAD handlers to use this function unconditionally.
293 rm_wlock(&ktls_backends_lock);
294 LIST_FOREACH(tmp, &ktls_backends, next) {
299 rm_wunlock(&ktls_backends_lock);
303 if (!ktls_allow_unload) {
304 rm_wunlock(&ktls_backends_lock);
306 "KTLS: Deregistering crypto method %s is not supported\n",
312 rm_wunlock(&ktls_backends_lock);
316 LIST_REMOVE(be, next);
317 rm_wunlock(&ktls_backends_lock);
321 #if defined(INET) || defined(INET6)
323 ktls_get_cpu(struct socket *so)
327 struct ktls_domain_info *di;
333 cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
334 if (cpuid != NETISR_CPUID_NONE)
338 * Just use the flowid to shard connections in a repeatable
339 * fashion. Note that some crypto backends rely on the
340 * serialization provided by having the same connection use
344 if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
345 di = &ktls_domains[inp->inp_numa_domain];
346 cpuid = di->cpu[inp->inp_flowid % di->count];
349 cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
355 ktls_init(void *dummy __unused)
360 int count, domain, error, i;
362 ktls_tasks_active = counter_u64_alloc(M_WAITOK);
363 ktls_cnt_tx_queued = counter_u64_alloc(M_WAITOK);
364 ktls_cnt_rx_queued = counter_u64_alloc(M_WAITOK);
365 ktls_offload_total = counter_u64_alloc(M_WAITOK);
366 ktls_offload_enable_calls = counter_u64_alloc(M_WAITOK);
367 ktls_offload_active = counter_u64_alloc(M_WAITOK);
368 ktls_offload_corrupted_records = counter_u64_alloc(M_WAITOK);
369 ktls_offload_failed_crypto = counter_u64_alloc(M_WAITOK);
370 ktls_switch_to_ifnet = counter_u64_alloc(M_WAITOK);
371 ktls_switch_to_sw = counter_u64_alloc(M_WAITOK);
372 ktls_switch_failed = counter_u64_alloc(M_WAITOK);
373 ktls_sw_cbc = counter_u64_alloc(M_WAITOK);
374 ktls_sw_gcm = counter_u64_alloc(M_WAITOK);
375 ktls_ifnet_cbc = counter_u64_alloc(M_WAITOK);
376 ktls_ifnet_gcm = counter_u64_alloc(M_WAITOK);
377 ktls_ifnet_reset = counter_u64_alloc(M_WAITOK);
378 ktls_ifnet_reset_dropped = counter_u64_alloc(M_WAITOK);
379 ktls_ifnet_reset_failed = counter_u64_alloc(M_WAITOK);
381 ktls_toe_cbc = counter_u64_alloc(M_WAITOK);
382 ktls_toe_gcm = counter_u64_alloc(M_WAITOK);
385 rm_init(&ktls_backends_lock, "ktls backends");
386 LIST_INIT(&ktls_backends);
388 ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
391 ktls_session_zone = uma_zcreate("ktls_session",
392 sizeof(struct ktls_session),
393 NULL, NULL, NULL, NULL,
397 * Initialize the workqueues to run the TLS work. We create a
398 * work queue for each CPU.
401 STAILQ_INIT(&ktls_wq[i].m_head);
402 STAILQ_INIT(&ktls_wq[i].so_head);
403 mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
404 error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
405 &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
407 panic("Can't add KTLS thread %d error %d", i, error);
410 * Bind threads to cores. If ktls_bind_threads is >
411 * 1, then we bind to the NUMA domain.
413 if (ktls_bind_threads) {
414 if (ktls_bind_threads > 1) {
416 domain = pc->pc_domain;
417 CPU_COPY(&cpuset_domain[domain], &mask);
418 count = ktls_domains[domain].count;
419 ktls_domains[domain].cpu[count] = i;
420 ktls_domains[domain].count++;
424 error = cpuset_setthread(td->td_tid, &mask);
427 "Unable to bind KTLS thread for CPU %d error %d",
430 ktls_cpuid_lookup[ktls_number_threads] = i;
431 ktls_number_threads++;
435 * If we somehow have an empty domain, fall back to choosing
436 * among all KTLS threads.
438 for (i = 0; i < vm_ndomains; i++) {
439 if (ktls_domains[i].count == 0) {
440 ktls_bind_threads = 0;
445 printf("KTLS: Initialized %d threads\n", ktls_number_threads);
447 SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
449 #if defined(INET) || defined(INET6)
451 ktls_create_session(struct socket *so, struct tls_enable *en,
452 struct ktls_session **tlsp)
454 struct ktls_session *tls;
457 /* Only TLS 1.0 - 1.3 are supported. */
458 if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
460 if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
461 en->tls_vminor > TLS_MINOR_VER_THREE)
464 if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
466 if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
468 if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
471 /* All supported algorithms require a cipher key. */
472 if (en->cipher_key_len == 0)
475 /* No flags are currently supported. */
479 /* Common checks for supported algorithms. */
480 switch (en->cipher_algorithm) {
481 case CRYPTO_AES_NIST_GCM_16:
483 * auth_algorithm isn't used, but permit GMAC values
486 switch (en->auth_algorithm) {
488 #ifdef COMPAT_FREEBSD12
489 /* XXX: Really 13.0-current COMPAT. */
490 case CRYPTO_AES_128_NIST_GMAC:
491 case CRYPTO_AES_192_NIST_GMAC:
492 case CRYPTO_AES_256_NIST_GMAC:
498 if (en->auth_key_len != 0)
500 if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
501 en->iv_len != TLS_AEAD_GCM_LEN) ||
502 (en->tls_vminor == TLS_MINOR_VER_THREE &&
503 en->iv_len != TLS_1_3_GCM_IV_LEN))
507 switch (en->auth_algorithm) {
508 case CRYPTO_SHA1_HMAC:
510 * TLS 1.0 requires an implicit IV. TLS 1.1+
511 * all use explicit IVs.
513 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
514 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
520 case CRYPTO_SHA2_256_HMAC:
521 case CRYPTO_SHA2_384_HMAC:
522 /* Ignore any supplied IV. */
528 if (en->auth_key_len == 0)
535 tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
537 counter_u64_add(ktls_offload_active, 1);
539 refcount_init(&tls->refcount, 1);
540 TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
542 tls->wq_index = ktls_get_cpu(so);
544 tls->params.cipher_algorithm = en->cipher_algorithm;
545 tls->params.auth_algorithm = en->auth_algorithm;
546 tls->params.tls_vmajor = en->tls_vmajor;
547 tls->params.tls_vminor = en->tls_vminor;
548 tls->params.flags = en->flags;
549 tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
551 /* Set the header and trailer lengths. */
552 tls->params.tls_hlen = sizeof(struct tls_record_layer);
553 switch (en->cipher_algorithm) {
554 case CRYPTO_AES_NIST_GCM_16:
556 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
557 * nonce. TLS 1.3 uses a 12 byte implicit IV.
559 if (en->tls_vminor < TLS_MINOR_VER_THREE)
560 tls->params.tls_hlen += sizeof(uint64_t);
561 tls->params.tls_tlen = AES_GMAC_HASH_LEN;
564 * TLS 1.3 includes optional padding which we
565 * do not support, and also puts the "real" record
566 * type at the end of the encrypted data.
568 if (en->tls_vminor == TLS_MINOR_VER_THREE)
569 tls->params.tls_tlen += sizeof(uint8_t);
571 tls->params.tls_bs = 1;
574 switch (en->auth_algorithm) {
575 case CRYPTO_SHA1_HMAC:
576 if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
577 /* Implicit IV, no nonce. */
579 tls->params.tls_hlen += AES_BLOCK_LEN;
581 tls->params.tls_tlen = AES_BLOCK_LEN +
584 case CRYPTO_SHA2_256_HMAC:
585 tls->params.tls_hlen += AES_BLOCK_LEN;
586 tls->params.tls_tlen = AES_BLOCK_LEN +
589 case CRYPTO_SHA2_384_HMAC:
590 tls->params.tls_hlen += AES_BLOCK_LEN;
591 tls->params.tls_tlen = AES_BLOCK_LEN +
595 panic("invalid hmac");
597 tls->params.tls_bs = AES_BLOCK_LEN;
600 panic("invalid cipher");
603 KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
604 ("TLS header length too long: %d", tls->params.tls_hlen));
605 KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
606 ("TLS trailer length too long: %d", tls->params.tls_tlen));
608 if (en->auth_key_len != 0) {
609 tls->params.auth_key_len = en->auth_key_len;
610 tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
612 error = copyin(en->auth_key, tls->params.auth_key,
618 tls->params.cipher_key_len = en->cipher_key_len;
619 tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
620 error = copyin(en->cipher_key, tls->params.cipher_key,
626 * This holds the implicit portion of the nonce for GCM and
627 * the initial implicit IV for TLS 1.0. The explicit portions
628 * of the IV are generated in ktls_frame().
630 if (en->iv_len != 0) {
631 tls->params.iv_len = en->iv_len;
632 error = copyin(en->iv, tls->params.iv, en->iv_len);
637 * For TLS 1.2, generate an 8-byte nonce as a counter
638 * to generate unique explicit IVs.
640 * Store this counter in the last 8 bytes of the IV
641 * array so that it is 8-byte aligned.
643 if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
644 en->tls_vminor == TLS_MINOR_VER_TWO)
645 arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
656 static struct ktls_session *
657 ktls_clone_session(struct ktls_session *tls)
659 struct ktls_session *tls_new;
661 tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
663 counter_u64_add(ktls_offload_active, 1);
665 refcount_init(&tls_new->refcount, 1);
667 /* Copy fields from existing session. */
668 tls_new->params = tls->params;
669 tls_new->wq_index = tls->wq_index;
671 /* Deep copy keys. */
672 if (tls_new->params.auth_key != NULL) {
673 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
675 memcpy(tls_new->params.auth_key, tls->params.auth_key,
676 tls->params.auth_key_len);
679 tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
681 memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
682 tls->params.cipher_key_len);
689 ktls_cleanup(struct ktls_session *tls)
692 counter_u64_add(ktls_offload_active, -1);
694 case TCP_TLS_MODE_SW:
695 MPASS(tls->be != NULL);
696 switch (tls->params.cipher_algorithm) {
698 counter_u64_add(ktls_sw_cbc, -1);
700 case CRYPTO_AES_NIST_GCM_16:
701 counter_u64_add(ktls_sw_gcm, -1);
706 case TCP_TLS_MODE_IFNET:
707 switch (tls->params.cipher_algorithm) {
709 counter_u64_add(ktls_ifnet_cbc, -1);
711 case CRYPTO_AES_NIST_GCM_16:
712 counter_u64_add(ktls_ifnet_gcm, -1);
715 if (tls->snd_tag != NULL)
716 m_snd_tag_rele(tls->snd_tag);
719 case TCP_TLS_MODE_TOE:
720 switch (tls->params.cipher_algorithm) {
722 counter_u64_add(ktls_toe_cbc, -1);
724 case CRYPTO_AES_NIST_GCM_16:
725 counter_u64_add(ktls_toe_gcm, -1);
731 if (tls->params.auth_key != NULL) {
732 zfree(tls->params.auth_key, M_KTLS);
733 tls->params.auth_key = NULL;
734 tls->params.auth_key_len = 0;
736 if (tls->params.cipher_key != NULL) {
737 zfree(tls->params.cipher_key, M_KTLS);
738 tls->params.cipher_key = NULL;
739 tls->params.cipher_key_len = 0;
741 explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
744 #if defined(INET) || defined(INET6)
748 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
756 if (inp->inp_flags2 & INP_FREED) {
760 if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
764 if (inp->inp_socket == NULL) {
769 if (!(tp->t_flags & TF_TOE)) {
774 error = tcp_offload_alloc_tls_session(tp, tls, direction);
777 tls->mode = TCP_TLS_MODE_TOE;
778 switch (tls->params.cipher_algorithm) {
780 counter_u64_add(ktls_toe_cbc, 1);
782 case CRYPTO_AES_NIST_GCM_16:
783 counter_u64_add(ktls_toe_gcm, 1);
792 * Common code used when first enabling ifnet TLS on a connection or
793 * when allocating a new ifnet TLS session due to a routing change.
794 * This function allocates a new TLS send tag on whatever interface
795 * the connection is currently routed over.
798 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
799 struct m_snd_tag **mstp)
801 union if_snd_tag_alloc_params params;
803 struct nhop_object *nh;
808 if (inp->inp_flags2 & INP_FREED) {
812 if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
816 if (inp->inp_socket == NULL) {
823 * Check administrative controls on ifnet TLS to determine if
824 * ifnet TLS should be denied.
826 * - Always permit 'force' requests.
827 * - ktls_ifnet_permitted == 0: always deny.
829 if (!force && ktls_ifnet_permitted == 0) {
835 * XXX: Use the cached route in the inpcb to find the
836 * interface. This should perhaps instead use
837 * rtalloc1_fib(dst, 0, 0, fibnum). Since KTLS is only
838 * enabled after a connection has completed key negotiation in
839 * userland, the cached route will be present in practice.
841 nh = inp->inp_route.ro_nh;
850 * Allocate a TLS + ratelimit tag if the connection has an
851 * existing pacing rate.
853 if (tp->t_pacing_rate != -1 &&
854 (ifp->if_capenable & IFCAP_TXTLS_RTLMT) != 0) {
855 params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
856 params.tls_rate_limit.inp = inp;
857 params.tls_rate_limit.tls = tls;
858 params.tls_rate_limit.max_rate = tp->t_pacing_rate;
860 params.hdr.type = IF_SND_TAG_TYPE_TLS;
861 params.tls.inp = inp;
862 params.tls.tls = tls;
864 params.hdr.flowid = inp->inp_flowid;
865 params.hdr.flowtype = inp->inp_flowtype;
866 params.hdr.numa_domain = inp->inp_numa_domain;
869 if ((ifp->if_capenable & IFCAP_NOMAP) == 0) {
873 if (inp->inp_vflag & INP_IPV6) {
874 if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
879 if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
884 error = m_snd_tag_alloc(ifp, ¶ms, mstp);
891 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
893 struct m_snd_tag *mst;
896 error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
898 tls->mode = TCP_TLS_MODE_IFNET;
900 switch (tls->params.cipher_algorithm) {
902 counter_u64_add(ktls_ifnet_cbc, 1);
904 case CRYPTO_AES_NIST_GCM_16:
905 counter_u64_add(ktls_ifnet_gcm, 1);
913 ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
915 struct rm_priotracker prio;
916 struct ktls_crypto_backend *be;
919 * Choose the best software crypto backend. Backends are
920 * stored in sorted priority order (larget value == most
921 * important at the head of the list), so this just stops on
922 * the first backend that claims the session by returning
925 if (ktls_allow_unload)
926 rm_rlock(&ktls_backends_lock, &prio);
927 LIST_FOREACH(be, &ktls_backends, next) {
928 if (be->try(so, tls, direction) == 0)
930 KASSERT(tls->cipher == NULL,
931 ("ktls backend leaked a cipher pointer"));
934 if (ktls_allow_unload)
938 if (ktls_allow_unload)
939 rm_runlock(&ktls_backends_lock, &prio);
942 tls->mode = TCP_TLS_MODE_SW;
943 switch (tls->params.cipher_algorithm) {
945 counter_u64_add(ktls_sw_cbc, 1);
947 case CRYPTO_AES_NIST_GCM_16:
948 counter_u64_add(ktls_sw_gcm, 1);
955 * KTLS RX stores data in the socket buffer as a list of TLS records,
956 * where each record is stored as a control message containg the TLS
957 * header followed by data mbufs containing the decrypted data. This
958 * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
959 * both encrypted and decrypted data. TLS records decrypted by a NIC
960 * should be queued to the socket buffer as records, but encrypted
961 * data which needs to be decrypted by software arrives as a stream of
962 * regular mbufs which need to be converted. In addition, there may
963 * already be pending encrypted data in the socket buffer when KTLS RX
966 * To manage not-yet-decrypted data for KTLS RX, the following scheme
969 * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
971 * - ktls_check_rx checks this chain of mbufs reading the TLS header
972 * from the first mbuf. Once all of the data for that TLS record is
973 * queued, the socket is queued to a worker thread.
975 * - The worker thread calls ktls_decrypt to decrypt TLS records in
976 * the TLS chain. Each TLS record is detached from the TLS chain,
977 * decrypted, and inserted into the regular socket buffer chain as
978 * record starting with a control message holding the TLS header and
979 * a chain of mbufs holding the encrypted data.
983 sb_mark_notready(struct sockbuf *sb)
990 sb->sb_mbtail = NULL;
991 sb->sb_lastrecord = NULL;
992 for (; m != NULL; m = m->m_next) {
993 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
995 KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
997 KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
999 m->m_flags |= M_NOTREADY;
1000 sb->sb_acc -= m->m_len;
1001 sb->sb_tlscc += m->m_len;
1002 sb->sb_mtlstail = m;
1004 KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
1005 ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
1010 ktls_enable_rx(struct socket *so, struct tls_enable *en)
1012 struct ktls_session *tls;
1015 if (!ktls_offload_enable)
1018 counter_u64_add(ktls_offload_enable_calls, 1);
1021 * This should always be true since only the TCP socket option
1022 * invokes this function.
1024 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1028 * XXX: Don't overwrite existing sessions. We should permit
1029 * this to support rekeying in the future.
1031 if (so->so_rcv.sb_tls_info != NULL)
1034 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1037 /* TLS 1.3 is not yet supported. */
1038 if (en->tls_vmajor == TLS_MAJOR_VER_ONE &&
1039 en->tls_vminor == TLS_MINOR_VER_THREE)
1042 error = ktls_create_session(so, en, &tls);
1047 error = ktls_try_toe(so, tls, KTLS_RX);
1050 error = ktls_try_sw(so, tls, KTLS_RX);
1057 /* Mark the socket as using TLS offload. */
1058 SOCKBUF_LOCK(&so->so_rcv);
1059 so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1060 so->so_rcv.sb_tls_info = tls;
1061 so->so_rcv.sb_flags |= SB_TLS_RX;
1063 /* Mark existing data as not ready until it can be decrypted. */
1064 sb_mark_notready(&so->so_rcv);
1065 ktls_check_rx(&so->so_rcv);
1066 SOCKBUF_UNLOCK(&so->so_rcv);
1068 counter_u64_add(ktls_offload_total, 1);
1074 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1076 struct ktls_session *tls;
1080 if (!ktls_offload_enable)
1083 counter_u64_add(ktls_offload_enable_calls, 1);
1086 * This should always be true since only the TCP socket option
1087 * invokes this function.
1089 if (so->so_proto->pr_protocol != IPPROTO_TCP)
1093 * XXX: Don't overwrite existing sessions. We should permit
1094 * this to support rekeying in the future.
1096 if (so->so_snd.sb_tls_info != NULL)
1099 if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1102 /* TLS requires ext pgs */
1103 if (mb_use_ext_pgs == 0)
1106 error = ktls_create_session(so, en, &tls);
1110 /* Prefer TOE -> ifnet TLS -> software TLS. */
1112 error = ktls_try_toe(so, tls, KTLS_TX);
1115 error = ktls_try_ifnet(so, tls, false);
1117 error = ktls_try_sw(so, tls, KTLS_TX);
1124 error = sblock(&so->so_snd, SBL_WAIT);
1131 * Write lock the INP when setting sb_tls_info so that
1132 * routines in tcp_ratelimit.c can read sb_tls_info while
1133 * holding the INP lock.
1137 SOCKBUF_LOCK(&so->so_snd);
1138 so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1139 so->so_snd.sb_tls_info = tls;
1140 if (tls->mode != TCP_TLS_MODE_SW)
1141 so->so_snd.sb_flags |= SB_TLS_IFNET;
1142 SOCKBUF_UNLOCK(&so->so_snd);
1144 sbunlock(&so->so_snd);
1146 counter_u64_add(ktls_offload_total, 1);
1152 ktls_get_rx_mode(struct socket *so)
1154 struct ktls_session *tls;
1159 INP_WLOCK_ASSERT(inp);
1160 SOCKBUF_LOCK(&so->so_rcv);
1161 tls = so->so_rcv.sb_tls_info;
1163 mode = TCP_TLS_MODE_NONE;
1166 SOCKBUF_UNLOCK(&so->so_rcv);
1171 ktls_get_tx_mode(struct socket *so)
1173 struct ktls_session *tls;
1178 INP_WLOCK_ASSERT(inp);
1179 SOCKBUF_LOCK(&so->so_snd);
1180 tls = so->so_snd.sb_tls_info;
1182 mode = TCP_TLS_MODE_NONE;
1185 SOCKBUF_UNLOCK(&so->so_snd);
1190 * Switch between SW and ifnet TLS sessions as requested.
1193 ktls_set_tx_mode(struct socket *so, int mode)
1195 struct ktls_session *tls, *tls_new;
1200 case TCP_TLS_MODE_SW:
1201 case TCP_TLS_MODE_IFNET:
1208 INP_WLOCK_ASSERT(inp);
1209 SOCKBUF_LOCK(&so->so_snd);
1210 tls = so->so_snd.sb_tls_info;
1212 SOCKBUF_UNLOCK(&so->so_snd);
1216 if (tls->mode == mode) {
1217 SOCKBUF_UNLOCK(&so->so_snd);
1221 tls = ktls_hold(tls);
1222 SOCKBUF_UNLOCK(&so->so_snd);
1225 tls_new = ktls_clone_session(tls);
1227 if (mode == TCP_TLS_MODE_IFNET)
1228 error = ktls_try_ifnet(so, tls_new, true);
1230 error = ktls_try_sw(so, tls_new, KTLS_TX);
1232 counter_u64_add(ktls_switch_failed, 1);
1239 error = sblock(&so->so_snd, SBL_WAIT);
1241 counter_u64_add(ktls_switch_failed, 1);
1249 * If we raced with another session change, keep the existing
1252 if (tls != so->so_snd.sb_tls_info) {
1253 counter_u64_add(ktls_switch_failed, 1);
1254 sbunlock(&so->so_snd);
1261 SOCKBUF_LOCK(&so->so_snd);
1262 so->so_snd.sb_tls_info = tls_new;
1263 if (tls_new->mode != TCP_TLS_MODE_SW)
1264 so->so_snd.sb_flags |= SB_TLS_IFNET;
1265 SOCKBUF_UNLOCK(&so->so_snd);
1266 sbunlock(&so->so_snd);
1269 * Drop two references on 'tls'. The first is for the
1270 * ktls_hold() above. The second drops the reference from the
1273 KASSERT(tls->refcount >= 2, ("too few references on old session"));
1277 if (mode == TCP_TLS_MODE_IFNET)
1278 counter_u64_add(ktls_switch_to_ifnet, 1);
1280 counter_u64_add(ktls_switch_to_sw, 1);
1287 * Try to allocate a new TLS send tag. This task is scheduled when
1288 * ip_output detects a route change while trying to transmit a packet
1289 * holding a TLS record. If a new tag is allocated, replace the tag
1290 * in the TLS session. Subsequent packets on the connection will use
1291 * the new tag. If a new tag cannot be allocated, drop the
1295 ktls_reset_send_tag(void *context, int pending)
1297 struct epoch_tracker et;
1298 struct ktls_session *tls;
1299 struct m_snd_tag *old, *new;
1304 MPASS(pending == 1);
1310 * Free the old tag first before allocating a new one.
1311 * ip[6]_output_send() will treat a NULL send tag the same as
1312 * an ifp mismatch and drop packets until a new tag is
1315 * Write-lock the INP when changing tls->snd_tag since
1316 * ip[6]_output_send() holds a read-lock when reading the
1321 tls->snd_tag = NULL;
1324 m_snd_tag_rele(old);
1326 error = ktls_alloc_snd_tag(inp, tls, true, &new);
1331 mtx_pool_lock(mtxpool_sleep, tls);
1332 tls->reset_pending = false;
1333 mtx_pool_unlock(mtxpool_sleep, tls);
1334 if (!in_pcbrele_wlocked(inp))
1337 counter_u64_add(ktls_ifnet_reset, 1);
1340 * XXX: Should we kick tcp_output explicitly now that
1341 * the send tag is fixed or just rely on timers?
1344 NET_EPOCH_ENTER(et);
1346 if (!in_pcbrele_wlocked(inp)) {
1347 if (!(inp->inp_flags & INP_TIMEWAIT) &&
1348 !(inp->inp_flags & INP_DROPPED)) {
1349 tp = intotcpcb(inp);
1350 CURVNET_SET(tp->t_vnet);
1351 tp = tcp_drop(tp, ECONNABORTED);
1355 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1361 counter_u64_add(ktls_ifnet_reset_failed, 1);
1364 * Leave reset_pending true to avoid future tasks while
1365 * the socket goes away.
1373 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1379 INP_LOCK_ASSERT(inp);
1382 * See if we should schedule a task to update the send tag for
1385 mtx_pool_lock(mtxpool_sleep, tls);
1386 if (!tls->reset_pending) {
1387 (void) ktls_hold(tls);
1390 tls->reset_pending = true;
1391 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1393 mtx_pool_unlock(mtxpool_sleep, tls);
1399 ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1401 union if_snd_tag_modify_params params = {
1402 .rate_limit.max_rate = max_pacing_rate,
1403 .rate_limit.flags = M_NOWAIT,
1405 struct m_snd_tag *mst;
1409 /* Can't get to the inp, but it should be locked. */
1410 /* INP_LOCK_ASSERT(inp); */
1412 MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1414 if (tls->snd_tag == NULL) {
1416 * Resetting send tag, ignore this change. The
1417 * pending reset may or may not see this updated rate
1418 * in the tcpcb. If it doesn't, we will just lose
1424 MPASS(tls->snd_tag != NULL);
1425 MPASS(tls->snd_tag->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1429 return (ifp->if_snd_tag_modify(mst, ¶ms));
1435 ktls_destroy(struct ktls_session *tls)
1437 struct rm_priotracker prio;
1440 if (tls->be != NULL && ktls_allow_unload) {
1441 rm_rlock(&ktls_backends_lock, &prio);
1442 tls->be->use_count--;
1443 rm_runlock(&ktls_backends_lock, &prio);
1445 uma_zfree(ktls_session_zone, tls);
1449 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1452 for (; m != NULL; m = m->m_next) {
1453 KASSERT((m->m_flags & M_EXTPG) != 0,
1454 ("ktls_seq: mapped mbuf %p", m));
1456 m->m_epg_seqno = sb->sb_tls_seqno;
1462 * Add TLS framing (headers and trailers) to a chain of mbufs. Each
1463 * mbuf in the chain must be an unmapped mbuf. The payload of the
1464 * mbuf must be populated with the payload of each TLS record.
1466 * The record_type argument specifies the TLS record type used when
1467 * populating the TLS header.
1469 * The enq_count argument on return is set to the number of pages of
1470 * payload data for this entire chain that need to be encrypted via SW
1471 * encryption. The returned value should be passed to ktls_enqueue
1472 * when scheduling encryption of this chain of mbufs. To handle the
1473 * special case of empty fragments for TLS 1.0 sessions, an empty
1474 * fragment counts as one page.
1477 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1478 uint8_t record_type)
1480 struct tls_record_layer *tlshdr;
1486 maxlen = tls->params.max_frame_len;
1488 for (m = top; m != NULL; m = m->m_next) {
1490 * All mbufs in the chain should be TLS records whose
1491 * payload does not exceed the maximum frame length.
1493 * Empty TLS records are permitted when using CBC.
1495 KASSERT(m->m_len <= maxlen &&
1496 (tls->params.cipher_algorithm == CRYPTO_AES_CBC ?
1497 m->m_len >= 0 : m->m_len > 0),
1498 ("ktls_frame: m %p len %d\n", m, m->m_len));
1501 * TLS frames require unmapped mbufs to store session
1504 KASSERT((m->m_flags & M_EXTPG) != 0,
1505 ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1509 /* Save a reference to the session. */
1510 m->m_epg_tls = ktls_hold(tls);
1512 m->m_epg_hdrlen = tls->params.tls_hlen;
1513 m->m_epg_trllen = tls->params.tls_tlen;
1514 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1518 * AES-CBC pads messages to a multiple of the
1519 * block size. Note that the padding is
1520 * applied after the digest and the encryption
1521 * is done on the "plaintext || mac || padding".
1522 * At least one byte of padding is always
1525 * Compute the final trailer length assuming
1526 * at most one block of padding.
1527 * tls->params.sb_tls_tlen is the maximum
1528 * possible trailer length (padding + digest).
1529 * delta holds the number of excess padding
1530 * bytes if the maximum were used. Those
1531 * extra bytes are removed.
1533 bs = tls->params.tls_bs;
1534 delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1535 m->m_epg_trllen -= delta;
1537 m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1539 /* Populate the TLS header. */
1540 tlshdr = (void *)m->m_epg_hdr;
1541 tlshdr->tls_vmajor = tls->params.tls_vmajor;
1544 * TLS 1.3 masquarades as TLS 1.2 with a record type
1545 * of TLS_RLTYPE_APP.
1547 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1548 tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1549 tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1550 tlshdr->tls_type = TLS_RLTYPE_APP;
1551 /* save the real record type for later */
1552 m->m_epg_record_type = record_type;
1553 m->m_epg_trail[0] = record_type;
1555 tlshdr->tls_vminor = tls->params.tls_vminor;
1556 tlshdr->tls_type = record_type;
1558 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1561 * Store nonces / explicit IVs after the end of the
1564 * For GCM with TLS 1.2, an 8 byte nonce is copied
1565 * from the end of the IV. The nonce is then
1566 * incremented for use by the next record.
1568 * For CBC, a random nonce is inserted for TLS 1.1+.
1570 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
1571 tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
1572 noncep = (uint64_t *)(tls->params.iv + 8);
1573 be64enc(tlshdr + 1, *noncep);
1575 } else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1576 tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1577 arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1580 * When using SW encryption, mark the mbuf not ready.
1581 * It will be marked ready via sbready() after the
1582 * record has been encrypted.
1584 * When using ifnet TLS, unencrypted TLS records are
1585 * sent down the stack to the NIC.
1587 if (tls->mode == TCP_TLS_MODE_SW) {
1588 m->m_flags |= M_NOTREADY;
1589 m->m_epg_nrdy = m->m_epg_npgs;
1590 if (__predict_false(tls_len == 0)) {
1591 /* TLS 1.0 empty fragment. */
1594 *enq_cnt += m->m_epg_npgs;
1600 ktls_check_rx(struct sockbuf *sb)
1602 struct tls_record_layer hdr;
1607 SOCKBUF_LOCK_ASSERT(sb);
1608 KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1610 so = __containerof(sb, struct socket, so_rcv);
1612 if (sb->sb_flags & SB_TLS_RX_RUNNING)
1615 /* Is there enough queued for a TLS header? */
1616 if (sb->sb_tlscc < sizeof(hdr)) {
1617 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
1618 so->so_error = EMSGSIZE;
1622 m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
1624 /* Is the entire record queued? */
1625 if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
1626 if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
1627 so->so_error = EMSGSIZE;
1631 sb->sb_flags |= SB_TLS_RX_RUNNING;
1634 wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
1636 STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
1637 running = wq->running;
1638 mtx_unlock(&wq->mtx);
1641 counter_u64_add(ktls_cnt_rx_queued, 1);
1644 static struct mbuf *
1645 ktls_detach_record(struct sockbuf *sb, int len)
1647 struct mbuf *m, *n, *top;
1650 SOCKBUF_LOCK_ASSERT(sb);
1651 MPASS(len <= sb->sb_tlscc);
1654 * If TLS chain is the exact size of the record,
1655 * just grab the whole record.
1658 if (sb->sb_tlscc == len) {
1660 sb->sb_mtlstail = NULL;
1665 * While it would be nice to use m_split() here, we need
1666 * to know exactly what m_split() allocates to update the
1667 * accounting, so do it inline instead.
1670 for (m = top; remain > m->m_len; m = m->m_next)
1673 /* Easy case: don't have to split 'm'. */
1674 if (remain == m->m_len) {
1675 sb->sb_mtls = m->m_next;
1676 if (sb->sb_mtls == NULL)
1677 sb->sb_mtlstail = NULL;
1683 * Need to allocate an mbuf to hold the remainder of 'm'. Try
1684 * with M_NOWAIT first.
1686 n = m_get(M_NOWAIT, MT_DATA);
1689 * Use M_WAITOK with socket buffer unlocked. If
1690 * 'sb_mtls' changes while the lock is dropped, return
1691 * NULL to force the caller to retry.
1695 n = m_get(M_WAITOK, MT_DATA);
1698 if (sb->sb_mtls != top) {
1703 n->m_flags |= M_NOTREADY;
1705 /* Store remainder in 'n'. */
1706 n->m_len = m->m_len - remain;
1707 if (m->m_flags & M_EXT) {
1708 n->m_data = m->m_data + remain;
1711 bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
1714 /* Trim 'm' and update accounting. */
1715 m->m_len -= n->m_len;
1716 sb->sb_tlscc -= n->m_len;
1717 sb->sb_ccc -= n->m_len;
1719 /* Account for 'n'. */
1720 sballoc_ktls_rx(sb, n);
1722 /* Insert 'n' into the TLS chain. */
1724 n->m_next = m->m_next;
1725 if (sb->sb_mtlstail == m)
1726 sb->sb_mtlstail = n;
1728 /* Detach the record from the TLS chain. */
1732 MPASS(m_length(top, NULL) == len);
1733 for (m = top; m != NULL; m = m->m_next)
1734 sbfree_ktls_rx(sb, m);
1735 sb->sb_tlsdcc = len;
1742 ktls_decrypt(struct socket *so)
1744 char tls_header[MBUF_PEXT_HDR_LEN];
1745 struct ktls_session *tls;
1747 struct tls_record_layer *hdr;
1748 struct tls_get_record tgr;
1749 struct mbuf *control, *data, *m;
1751 int error, remain, tls_len, trail_len;
1753 hdr = (struct tls_record_layer *)tls_header;
1756 KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
1757 ("%s: socket %p not running", __func__, so));
1759 tls = sb->sb_tls_info;
1763 /* Is there enough queued for a TLS header? */
1764 if (sb->sb_tlscc < tls->params.tls_hlen)
1767 m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
1768 tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
1770 if (hdr->tls_vmajor != tls->params.tls_vmajor ||
1771 hdr->tls_vminor != tls->params.tls_vminor)
1773 else if (tls_len < tls->params.tls_hlen || tls_len >
1774 tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
1775 tls->params.tls_tlen)
1779 if (__predict_false(error != 0)) {
1781 * We have a corrupted record and are likely
1782 * out of sync. The connection isn't
1783 * recoverable at this point, so abort it.
1786 counter_u64_add(ktls_offload_corrupted_records, 1);
1788 CURVNET_SET(so->so_vnet);
1789 so->so_proto->pr_usrreqs->pru_abort(so);
1790 so->so_error = error;
1795 /* Is the entire record queued? */
1796 if (sb->sb_tlscc < tls_len)
1800 * Split out the portion of the mbuf chain containing
1803 data = ktls_detach_record(sb, tls_len);
1806 MPASS(sb->sb_tlsdcc == tls_len);
1808 seqno = sb->sb_tls_seqno;
1813 error = tls->sw_decrypt(tls, hdr, data, seqno, &trail_len);
1815 counter_u64_add(ktls_offload_failed_crypto, 1);
1818 if (sb->sb_tlsdcc == 0) {
1820 * sbcut/drop/flush discarded these
1828 * Drop this TLS record's data, but keep
1829 * decrypting subsequent records.
1831 sb->sb_ccc -= tls_len;
1834 CURVNET_SET(so->so_vnet);
1835 so->so_error = EBADMSG;
1836 sorwakeup_locked(so);
1845 /* Allocate the control mbuf. */
1846 tgr.tls_type = hdr->tls_type;
1847 tgr.tls_vmajor = hdr->tls_vmajor;
1848 tgr.tls_vminor = hdr->tls_vminor;
1849 tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
1851 control = sbcreatecontrol_how(&tgr, sizeof(tgr),
1852 TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
1855 if (sb->sb_tlsdcc == 0) {
1856 /* sbcut/drop/flush discarded these mbufs. */
1857 MPASS(sb->sb_tlscc == 0);
1864 * Clear the 'dcc' accounting in preparation for
1865 * adding the decrypted record.
1867 sb->sb_ccc -= tls_len;
1871 /* If there is no payload, drop all of the data. */
1872 if (tgr.tls_length == htobe16(0)) {
1877 remain = tls->params.tls_hlen;
1878 while (remain > 0) {
1879 if (data->m_len > remain) {
1880 data->m_data += remain;
1881 data->m_len -= remain;
1884 remain -= data->m_len;
1885 data = m_free(data);
1888 /* Trim trailer and clear M_NOTREADY. */
1889 remain = be16toh(tgr.tls_length);
1891 for (m = data; remain > m->m_len; m = m->m_next) {
1892 m->m_flags &= ~M_NOTREADY;
1898 m->m_flags &= ~M_NOTREADY;
1900 /* Set EOR on the final mbuf. */
1901 m->m_flags |= M_EOR;
1904 sbappendcontrol_locked(sb, data, control, 0);
1907 sb->sb_flags &= ~SB_TLS_RX_RUNNING;
1909 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
1910 so->so_error = EMSGSIZE;
1912 sorwakeup_locked(so);
1915 SOCKBUF_UNLOCK_ASSERT(sb);
1917 CURVNET_SET(so->so_vnet);
1924 ktls_enqueue_to_free(struct mbuf *m)
1929 /* Mark it for freeing. */
1930 m->m_epg_flags |= EPG_FLAG_2FREE;
1931 wq = &ktls_wq[m->m_epg_tls->wq_index];
1933 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1934 running = wq->running;
1935 mtx_unlock(&wq->mtx);
1941 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1946 KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
1947 (M_EXTPG | M_NOTREADY)),
1948 ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
1949 KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
1951 KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1953 m->m_epg_enc_cnt = page_count;
1956 * Save a pointer to the socket. The caller is responsible
1957 * for taking an additional reference via soref().
1961 wq = &ktls_wq[m->m_epg_tls->wq_index];
1963 STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1964 running = wq->running;
1965 mtx_unlock(&wq->mtx);
1968 counter_u64_add(ktls_cnt_tx_queued, 1);
1971 static __noinline void
1972 ktls_encrypt(struct mbuf *top)
1974 struct ktls_session *tls;
1977 vm_paddr_t parray[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1978 struct iovec src_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1979 struct iovec dst_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1981 int error, i, len, npages, off, total_pages;
1985 tls = top->m_epg_tls;
1986 KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
1987 KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
1989 top->m_epg_so = NULL;
1991 total_pages = top->m_epg_enc_cnt;
1995 * Encrypt the TLS records in the chain of mbufs starting with
1996 * 'top'. 'total_pages' gives us a total count of pages and is
1997 * used to know when we have finished encrypting the TLS
1998 * records originally queued with 'top'.
2000 * NB: These mbufs are queued in the socket buffer and
2001 * 'm_next' is traversing the mbufs in the socket buffer. The
2002 * socket buffer lock is not held while traversing this chain.
2003 * Since the mbufs are all marked M_NOTREADY their 'm_next'
2004 * pointers should be stable. However, the 'm_next' of the
2005 * last mbuf encrypted is not necessarily NULL. It can point
2006 * to other mbufs appended while 'top' was on the TLS work
2009 * Each mbuf holds an entire TLS record.
2012 for (m = top; npages != total_pages; m = m->m_next) {
2013 KASSERT(m->m_epg_tls == tls,
2014 ("different TLS sessions in a single mbuf chain: %p vs %p",
2015 tls, m->m_epg_tls));
2016 KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2017 (M_EXTPG | M_NOTREADY),
2018 ("%p not unready & nomap mbuf (top = %p)\n", m, top));
2019 KASSERT(npages + m->m_epg_npgs <= total_pages,
2020 ("page count mismatch: top %p, total_pages %d, m %p", top,
2024 * Generate source and destination ivoecs to pass to
2025 * the SW encryption backend. For writable mbufs, the
2026 * destination iovec is a copy of the source and
2027 * encryption is done in place. For file-backed mbufs
2028 * (from sendfile), anonymous wired pages are
2029 * allocated and assigned to the destination iovec.
2031 is_anon = (m->m_epg_flags & EPG_FLAG_ANON) != 0;
2033 off = m->m_epg_1st_off;
2034 for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2035 len = m_epg_pagelen(m, i, off);
2036 src_iov[i].iov_len = len;
2037 src_iov[i].iov_base =
2038 (char *)(void *)PHYS_TO_DMAP(m->m_epg_pa[i]) +
2042 dst_iov[i].iov_base = src_iov[i].iov_base;
2043 dst_iov[i].iov_len = src_iov[i].iov_len;
2047 pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2048 VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP | VM_ALLOC_WIRED);
2053 parray[i] = VM_PAGE_TO_PHYS(pg);
2054 dst_iov[i].iov_base =
2055 (char *)(void *)PHYS_TO_DMAP(parray[i]) + off;
2056 dst_iov[i].iov_len = len;
2059 if (__predict_false(m->m_epg_npgs == 0)) {
2060 /* TLS 1.0 empty fragment. */
2065 error = (*tls->sw_encrypt)(tls,
2066 (const struct tls_record_layer *)m->m_epg_hdr,
2067 m->m_epg_trail, src_iov, dst_iov, i, m->m_epg_seqno,
2068 m->m_epg_record_type);
2070 counter_u64_add(ktls_offload_failed_crypto, 1);
2075 * For file-backed mbufs, release the file-backed
2076 * pages and replace them in the ext_pgs array with
2077 * the anonymous wired pages allocated above.
2080 /* Free the old pages. */
2081 m->m_ext.ext_free(m);
2083 /* Replace them with the new pages. */
2084 for (i = 0; i < m->m_epg_npgs; i++)
2085 m->m_epg_pa[i] = parray[i];
2087 /* Use the basic free routine. */
2088 m->m_ext.ext_free = mb_free_mext_pgs;
2090 /* Pages are now writable. */
2091 m->m_epg_flags |= EPG_FLAG_ANON;
2095 * Drop a reference to the session now that it is no
2096 * longer needed. Existing code depends on encrypted
2097 * records having no associated session vs
2098 * yet-to-be-encrypted records having an associated
2101 m->m_epg_tls = NULL;
2105 CURVNET_SET(so->so_vnet);
2107 (void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
2109 so->so_proto->pr_usrreqs->pru_abort(so);
2111 mb_free_notready(top, total_pages);
2120 ktls_work_thread(void *ctx)
2122 struct ktls_wq *wq = ctx;
2124 struct socket *so, *son;
2125 STAILQ_HEAD(, mbuf) local_m_head;
2126 STAILQ_HEAD(, socket) local_so_head;
2128 if (ktls_bind_threads > 1) {
2129 curthread->td_domain.dr_policy =
2130 DOMAINSET_PREF(PCPU_GET(domain));
2132 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
2137 while (STAILQ_EMPTY(&wq->m_head) &&
2138 STAILQ_EMPTY(&wq->so_head)) {
2139 wq->running = false;
2140 mtx_sleep(wq, &wq->mtx, 0, "-", 0);
2144 STAILQ_INIT(&local_m_head);
2145 STAILQ_CONCAT(&local_m_head, &wq->m_head);
2146 STAILQ_INIT(&local_so_head);
2147 STAILQ_CONCAT(&local_so_head, &wq->so_head);
2148 mtx_unlock(&wq->mtx);
2150 STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
2151 if (m->m_epg_flags & EPG_FLAG_2FREE) {
2152 ktls_free(m->m_epg_tls);
2153 uma_zfree(zone_mbuf, m);
2156 counter_u64_add(ktls_cnt_tx_queued, -1);
2160 STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
2162 counter_u64_add(ktls_cnt_rx_queued, -1);