xref: /freebsd/sys/kern/uipc_ktls.c (revision 6b313a3a60453e87f0a224361dad6284550395de)
1b2e60773SJohn Baldwin /*-
2b2e60773SJohn Baldwin  * SPDX-License-Identifier: BSD-2-Clause
3b2e60773SJohn Baldwin  *
4b2e60773SJohn Baldwin  * Copyright (c) 2014-2019 Netflix Inc.
5b2e60773SJohn Baldwin  *
6b2e60773SJohn Baldwin  * Redistribution and use in source and binary forms, with or without
7b2e60773SJohn Baldwin  * modification, are permitted provided that the following conditions
8b2e60773SJohn Baldwin  * are met:
9b2e60773SJohn Baldwin  * 1. Redistributions of source code must retain the above copyright
10b2e60773SJohn Baldwin  *    notice, this list of conditions and the following disclaimer.
11b2e60773SJohn Baldwin  * 2. Redistributions in binary form must reproduce the above copyright
12b2e60773SJohn Baldwin  *    notice, this list of conditions and the following disclaimer in the
13b2e60773SJohn Baldwin  *    documentation and/or other materials provided with the distribution.
14b2e60773SJohn Baldwin  *
15b2e60773SJohn Baldwin  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16b2e60773SJohn Baldwin  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17b2e60773SJohn Baldwin  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18b2e60773SJohn Baldwin  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19b2e60773SJohn Baldwin  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20b2e60773SJohn Baldwin  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21b2e60773SJohn Baldwin  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22b2e60773SJohn Baldwin  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23b2e60773SJohn Baldwin  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24b2e60773SJohn Baldwin  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25b2e60773SJohn Baldwin  * SUCH DAMAGE.
26b2e60773SJohn Baldwin  */
27b2e60773SJohn Baldwin 
28b2e60773SJohn Baldwin #include <sys/cdefs.h>
29b2e60773SJohn Baldwin __FBSDID("$FreeBSD$");
30b2e60773SJohn Baldwin 
31b2e60773SJohn Baldwin #include "opt_inet.h"
32b2e60773SJohn Baldwin #include "opt_inet6.h"
33b2e60773SJohn Baldwin #include "opt_rss.h"
34b2e60773SJohn Baldwin 
35b2e60773SJohn Baldwin #include <sys/param.h>
36b2e60773SJohn Baldwin #include <sys/kernel.h>
3702bc3865SAndrew Gallatin #include <sys/domainset.h>
38b2e60773SJohn Baldwin #include <sys/ktls.h>
39b2e60773SJohn Baldwin #include <sys/lock.h>
40b2e60773SJohn Baldwin #include <sys/mbuf.h>
41b2e60773SJohn Baldwin #include <sys/mutex.h>
42b2e60773SJohn Baldwin #include <sys/rmlock.h>
43b2e60773SJohn Baldwin #include <sys/proc.h>
44b2e60773SJohn Baldwin #include <sys/protosw.h>
45b2e60773SJohn Baldwin #include <sys/refcount.h>
46b2e60773SJohn Baldwin #include <sys/smp.h>
47b2e60773SJohn Baldwin #include <sys/socket.h>
48b2e60773SJohn Baldwin #include <sys/socketvar.h>
49b2e60773SJohn Baldwin #include <sys/sysctl.h>
50b2e60773SJohn Baldwin #include <sys/taskqueue.h>
51b2e60773SJohn Baldwin #include <sys/kthread.h>
52b2e60773SJohn Baldwin #include <sys/uio.h>
53b2e60773SJohn Baldwin #include <sys/vmmeter.h>
54b2e60773SJohn Baldwin #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
55b2e60773SJohn Baldwin #include <machine/pcb.h>
56b2e60773SJohn Baldwin #endif
57b2e60773SJohn Baldwin #include <machine/vmparam.h>
5890746943SGleb Smirnoff #include <net/if.h>
5990746943SGleb Smirnoff #include <net/if_var.h>
60b2e60773SJohn Baldwin #ifdef RSS
61b2e60773SJohn Baldwin #include <net/netisr.h>
62b2e60773SJohn Baldwin #include <net/rss_config.h>
63b2e60773SJohn Baldwin #endif
64454d3896SAlexander V. Chernikov #include <net/route.h>
65454d3896SAlexander V. Chernikov #include <net/route/nhop.h>
66b2e60773SJohn Baldwin #if defined(INET) || defined(INET6)
67b2e60773SJohn Baldwin #include <netinet/in.h>
68b2e60773SJohn Baldwin #include <netinet/in_pcb.h>
69b2e60773SJohn Baldwin #endif
70b2e60773SJohn Baldwin #include <netinet/tcp_var.h>
719e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
729e14430dSJohn Baldwin #include <netinet/tcp_offload.h>
739e14430dSJohn Baldwin #endif
74b2e60773SJohn Baldwin #include <opencrypto/xform.h>
75b2e60773SJohn Baldwin #include <vm/uma_dbg.h>
76b2e60773SJohn Baldwin #include <vm/vm.h>
77b2e60773SJohn Baldwin #include <vm/vm_pageout.h>
78b2e60773SJohn Baldwin #include <vm/vm_page.h>
79b2e60773SJohn Baldwin 
80b2e60773SJohn Baldwin struct ktls_wq {
81b2e60773SJohn Baldwin 	struct mtx	mtx;
823c0e5685SJohn Baldwin 	STAILQ_HEAD(, mbuf) m_head;
833c0e5685SJohn Baldwin 	STAILQ_HEAD(, socket) so_head;
84b2e60773SJohn Baldwin 	bool		running;
8549f6925cSMark Johnston 	int		lastallocfail;
86b2e60773SJohn Baldwin } __aligned(CACHE_LINE_SIZE);
87b2e60773SJohn Baldwin 
8802bc3865SAndrew Gallatin struct ktls_domain_info {
8902bc3865SAndrew Gallatin 	int count;
9002bc3865SAndrew Gallatin 	int cpu[MAXCPU];
9102bc3865SAndrew Gallatin };
9202bc3865SAndrew Gallatin 
9302bc3865SAndrew Gallatin struct ktls_domain_info ktls_domains[MAXMEMDOM];
94b2e60773SJohn Baldwin static struct ktls_wq *ktls_wq;
95b2e60773SJohn Baldwin static struct proc *ktls_proc;
96b2e60773SJohn Baldwin static uma_zone_t ktls_session_zone;
9749f6925cSMark Johnston static uma_zone_t ktls_buffer_zone;
98b2e60773SJohn Baldwin static uint16_t ktls_cpuid_lookup[MAXCPU];
99b2e60773SJohn Baldwin 
1007029da5cSPawel Biernacki SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
101b2e60773SJohn Baldwin     "Kernel TLS offload");
1027029da5cSPawel Biernacki SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
103b2e60773SJohn Baldwin     "Kernel TLS offload stats");
104b2e60773SJohn Baldwin 
105b2e60773SJohn Baldwin #ifdef RSS
106b2e60773SJohn Baldwin static int ktls_bind_threads = 1;
107b2e60773SJohn Baldwin #else
108b2e60773SJohn Baldwin static int ktls_bind_threads;
109b2e60773SJohn Baldwin #endif
110b2e60773SJohn Baldwin SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
111b2e60773SJohn Baldwin     &ktls_bind_threads, 0,
1124dc1b17dSMark Johnston     "Bind crypto threads to cores (1) or cores and domains (2) at boot");
113b2e60773SJohn Baldwin 
114b2e60773SJohn Baldwin static u_int ktls_maxlen = 16384;
11549f6925cSMark Johnston SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RDTUN,
116b2e60773SJohn Baldwin     &ktls_maxlen, 0, "Maximum TLS record size");
117b2e60773SJohn Baldwin 
118b2e60773SJohn Baldwin static int ktls_number_threads;
119b2e60773SJohn Baldwin SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
120b2e60773SJohn Baldwin     &ktls_number_threads, 0,
121b2e60773SJohn Baldwin     "Number of TLS threads in thread-pool");
122b2e60773SJohn Baldwin 
123b2e60773SJohn Baldwin static bool ktls_offload_enable;
124b5aa9ad4SMark Johnston SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RWTUN,
125b2e60773SJohn Baldwin     &ktls_offload_enable, 0,
126b2e60773SJohn Baldwin     "Enable support for kernel TLS offload");
127b2e60773SJohn Baldwin 
128b2e60773SJohn Baldwin static bool ktls_cbc_enable = true;
129b5aa9ad4SMark Johnston SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RWTUN,
130b2e60773SJohn Baldwin     &ktls_cbc_enable, 1,
131b2e60773SJohn Baldwin     "Enable Support of AES-CBC crypto for kernel TLS");
132b2e60773SJohn Baldwin 
13349f6925cSMark Johnston static bool ktls_sw_buffer_cache = true;
13449f6925cSMark Johnston SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, sw_buffer_cache, CTLFLAG_RDTUN,
13549f6925cSMark Johnston     &ktls_sw_buffer_cache, 1,
13649f6925cSMark Johnston     "Enable caching of output buffers for SW encryption");
13749f6925cSMark Johnston 
1381755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_tasks_active);
139b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
140b2e60773SJohn Baldwin     &ktls_tasks_active, "Number of active tasks");
141b2e60773SJohn Baldwin 
1421755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_cnt_tx_queued);
1433c0e5685SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_inqueue, CTLFLAG_RD,
1443c0e5685SJohn Baldwin     &ktls_cnt_tx_queued,
1453c0e5685SJohn Baldwin     "Number of TLS records in queue to tasks for SW encryption");
1463c0e5685SJohn Baldwin 
1471755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_cnt_rx_queued);
1483c0e5685SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_rx_inqueue, CTLFLAG_RD,
1493c0e5685SJohn Baldwin     &ktls_cnt_rx_queued,
1503c0e5685SJohn Baldwin     "Number of TLS sockets in queue to tasks for SW decryption");
151b2e60773SJohn Baldwin 
1521755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_offload_total);
153b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
154b2e60773SJohn Baldwin     CTLFLAG_RD, &ktls_offload_total,
155b2e60773SJohn Baldwin     "Total successful TLS setups (parameters set)");
156b2e60773SJohn Baldwin 
1571755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_offload_enable_calls);
158b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
159b2e60773SJohn Baldwin     CTLFLAG_RD, &ktls_offload_enable_calls,
160b2e60773SJohn Baldwin     "Total number of TLS enable calls made");
161b2e60773SJohn Baldwin 
1621755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_offload_active);
163b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
164b2e60773SJohn Baldwin     &ktls_offload_active, "Total Active TLS sessions");
165b2e60773SJohn Baldwin 
1661755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_offload_corrupted_records);
1673c0e5685SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, corrupted_records, CTLFLAG_RD,
1683c0e5685SJohn Baldwin     &ktls_offload_corrupted_records, "Total corrupted TLS records received");
1693c0e5685SJohn Baldwin 
1701755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_offload_failed_crypto);
171b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
172b2e60773SJohn Baldwin     &ktls_offload_failed_crypto, "Total TLS crypto failures");
173b2e60773SJohn Baldwin 
1741755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_ifnet);
175b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
176b2e60773SJohn Baldwin     &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
177b2e60773SJohn Baldwin 
1781755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_sw);
179b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
180b2e60773SJohn Baldwin     &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
181b2e60773SJohn Baldwin 
1821755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_switch_failed);
183b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
184b2e60773SJohn Baldwin     &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
185b2e60773SJohn Baldwin 
1867029da5cSPawel Biernacki SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
187b2e60773SJohn Baldwin     "Software TLS session stats");
1887029da5cSPawel Biernacki SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
189b2e60773SJohn Baldwin     "Hardware (ifnet) TLS session stats");
1909e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
1917029da5cSPawel Biernacki SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1929e14430dSJohn Baldwin     "TOE TLS session stats");
1939e14430dSJohn Baldwin #endif
194b2e60773SJohn Baldwin 
1951755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_sw_cbc);
196b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
197b2e60773SJohn Baldwin     "Active number of software TLS sessions using AES-CBC");
198b2e60773SJohn Baldwin 
1991755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_sw_gcm);
200b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
201b2e60773SJohn Baldwin     "Active number of software TLS sessions using AES-GCM");
202b2e60773SJohn Baldwin 
2039c64fc40SJohn Baldwin static COUNTER_U64_DEFINE_EARLY(ktls_sw_chacha20);
2049c64fc40SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, chacha20, CTLFLAG_RD,
2059c64fc40SJohn Baldwin     &ktls_sw_chacha20,
2069c64fc40SJohn Baldwin     "Active number of software TLS sessions using Chacha20-Poly1305");
2079c64fc40SJohn Baldwin 
2081755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_cbc);
209b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
210b2e60773SJohn Baldwin     &ktls_ifnet_cbc,
211b2e60773SJohn Baldwin     "Active number of ifnet TLS sessions using AES-CBC");
212b2e60773SJohn Baldwin 
2131755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_gcm);
214b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
215b2e60773SJohn Baldwin     &ktls_ifnet_gcm,
216b2e60773SJohn Baldwin     "Active number of ifnet TLS sessions using AES-GCM");
217b2e60773SJohn Baldwin 
2189c64fc40SJohn Baldwin static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_chacha20);
2199c64fc40SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, chacha20, CTLFLAG_RD,
2209c64fc40SJohn Baldwin     &ktls_ifnet_chacha20,
2219c64fc40SJohn Baldwin     "Active number of ifnet TLS sessions using Chacha20-Poly1305");
2229c64fc40SJohn Baldwin 
2231755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset);
224b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
225b2e60773SJohn Baldwin     &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
226b2e60773SJohn Baldwin 
2271755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_dropped);
228b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
229b2e60773SJohn Baldwin     &ktls_ifnet_reset_dropped,
230b2e60773SJohn Baldwin     "TLS sessions dropped after failing to update ifnet send tag");
231b2e60773SJohn Baldwin 
2321755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_failed);
233b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
234b2e60773SJohn Baldwin     &ktls_ifnet_reset_failed,
235b2e60773SJohn Baldwin     "TLS sessions that failed to allocate a new ifnet send tag");
236b2e60773SJohn Baldwin 
237b2e60773SJohn Baldwin static int ktls_ifnet_permitted;
238b2e60773SJohn Baldwin SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
239b2e60773SJohn Baldwin     &ktls_ifnet_permitted, 1,
240b2e60773SJohn Baldwin     "Whether to permit hardware (ifnet) TLS sessions");
241b2e60773SJohn Baldwin 
2429e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
2431755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_toe_cbc);
2449e14430dSJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
2459e14430dSJohn Baldwin     &ktls_toe_cbc,
2469e14430dSJohn Baldwin     "Active number of TOE TLS sessions using AES-CBC");
2479e14430dSJohn Baldwin 
2481755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_toe_gcm);
2499e14430dSJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
2509e14430dSJohn Baldwin     &ktls_toe_gcm,
2519e14430dSJohn Baldwin     "Active number of TOE TLS sessions using AES-GCM");
2529c64fc40SJohn Baldwin 
25390972f04SJohn Baldwin static COUNTER_U64_DEFINE_EARLY(ktls_toe_chacha20);
2549c64fc40SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, chacha20, CTLFLAG_RD,
2559c64fc40SJohn Baldwin     &ktls_toe_chacha20,
2569c64fc40SJohn Baldwin     "Active number of TOE TLS sessions using Chacha20-Poly1305");
2579e14430dSJohn Baldwin #endif
2589e14430dSJohn Baldwin 
259b2e60773SJohn Baldwin static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
260b2e60773SJohn Baldwin 
261b2e60773SJohn Baldwin static void ktls_cleanup(struct ktls_session *tls);
262b2e60773SJohn Baldwin #if defined(INET) || defined(INET6)
263b2e60773SJohn Baldwin static void ktls_reset_send_tag(void *context, int pending);
264b2e60773SJohn Baldwin #endif
265b2e60773SJohn Baldwin static void ktls_work_thread(void *ctx);
266b2e60773SJohn Baldwin 
267b2e60773SJohn Baldwin #if defined(INET) || defined(INET6)
268a2fba2a7SBjoern A. Zeeb static u_int
269b2e60773SJohn Baldwin ktls_get_cpu(struct socket *so)
270b2e60773SJohn Baldwin {
271b2e60773SJohn Baldwin 	struct inpcb *inp;
27202bc3865SAndrew Gallatin #ifdef NUMA
27302bc3865SAndrew Gallatin 	struct ktls_domain_info *di;
27402bc3865SAndrew Gallatin #endif
275a2fba2a7SBjoern A. Zeeb 	u_int cpuid;
276b2e60773SJohn Baldwin 
277b2e60773SJohn Baldwin 	inp = sotoinpcb(so);
278b2e60773SJohn Baldwin #ifdef RSS
279b2e60773SJohn Baldwin 	cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
280b2e60773SJohn Baldwin 	if (cpuid != NETISR_CPUID_NONE)
281b2e60773SJohn Baldwin 		return (cpuid);
282b2e60773SJohn Baldwin #endif
283b2e60773SJohn Baldwin 	/*
284b2e60773SJohn Baldwin 	 * Just use the flowid to shard connections in a repeatable
28521e3c1fbSJohn Baldwin 	 * fashion.  Note that TLS 1.0 sessions rely on the
286b2e60773SJohn Baldwin 	 * serialization provided by having the same connection use
287b2e60773SJohn Baldwin 	 * the same queue.
288b2e60773SJohn Baldwin 	 */
28902bc3865SAndrew Gallatin #ifdef NUMA
29002bc3865SAndrew Gallatin 	if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
29102bc3865SAndrew Gallatin 		di = &ktls_domains[inp->inp_numa_domain];
29202bc3865SAndrew Gallatin 		cpuid = di->cpu[inp->inp_flowid % di->count];
29302bc3865SAndrew Gallatin 	} else
29402bc3865SAndrew Gallatin #endif
295b2e60773SJohn Baldwin 		cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
296b2e60773SJohn Baldwin 	return (cpuid);
297b2e60773SJohn Baldwin }
298b2e60773SJohn Baldwin #endif
299b2e60773SJohn Baldwin 
30049f6925cSMark Johnston static int
30149f6925cSMark Johnston ktls_buffer_import(void *arg, void **store, int count, int domain, int flags)
30249f6925cSMark Johnston {
30349f6925cSMark Johnston 	vm_page_t m;
30449f6925cSMark Johnston 	int i;
30549f6925cSMark Johnston 
30649f6925cSMark Johnston 	KASSERT((ktls_maxlen & PAGE_MASK) == 0,
30749f6925cSMark Johnston 	    ("%s: ktls max length %d is not page size-aligned",
30849f6925cSMark Johnston 	    __func__, ktls_maxlen));
30949f6925cSMark Johnston 
31049f6925cSMark Johnston 	for (i = 0; i < count; i++) {
31149f6925cSMark Johnston 		m = vm_page_alloc_contig_domain(NULL, 0, domain,
31249f6925cSMark Johnston 		    VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
31349f6925cSMark Johnston 		    VM_ALLOC_NODUMP | malloc2vm_flags(flags),
31449f6925cSMark Johnston 		    atop(ktls_maxlen), 0, ~0ul, PAGE_SIZE, 0,
31549f6925cSMark Johnston 		    VM_MEMATTR_DEFAULT);
31649f6925cSMark Johnston 		if (m == NULL)
31749f6925cSMark Johnston 			break;
31849f6925cSMark Johnston 		store[i] = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
31949f6925cSMark Johnston 	}
32049f6925cSMark Johnston 	return (i);
32149f6925cSMark Johnston }
32249f6925cSMark Johnston 
32349f6925cSMark Johnston static void
32449f6925cSMark Johnston ktls_buffer_release(void *arg __unused, void **store, int count)
32549f6925cSMark Johnston {
32649f6925cSMark Johnston 	vm_page_t m;
32749f6925cSMark Johnston 	int i, j;
32849f6925cSMark Johnston 
32949f6925cSMark Johnston 	for (i = 0; i < count; i++) {
33049f6925cSMark Johnston 		m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)store[i]));
33149f6925cSMark Johnston 		for (j = 0; j < atop(ktls_maxlen); j++) {
33249f6925cSMark Johnston 			(void)vm_page_unwire_noq(m + j);
33349f6925cSMark Johnston 			vm_page_free(m + j);
33449f6925cSMark Johnston 		}
33549f6925cSMark Johnston 	}
33649f6925cSMark Johnston }
33749f6925cSMark Johnston 
33849f6925cSMark Johnston static void
33949f6925cSMark Johnston ktls_free_mext_contig(struct mbuf *m)
34049f6925cSMark Johnston {
34149f6925cSMark Johnston 	M_ASSERTEXTPG(m);
34249f6925cSMark Johnston 	uma_zfree(ktls_buffer_zone, (void *)PHYS_TO_DMAP(m->m_epg_pa[0]));
34349f6925cSMark Johnston }
34449f6925cSMark Johnston 
345b2e60773SJohn Baldwin static void
346b2e60773SJohn Baldwin ktls_init(void *dummy __unused)
347b2e60773SJohn Baldwin {
348b2e60773SJohn Baldwin 	struct thread *td;
349b2e60773SJohn Baldwin 	struct pcpu *pc;
350b2e60773SJohn Baldwin 	cpuset_t mask;
35102bc3865SAndrew Gallatin 	int count, domain, error, i;
352b2e60773SJohn Baldwin 
353b2e60773SJohn Baldwin 	ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
354b2e60773SJohn Baldwin 	    M_WAITOK | M_ZERO);
355b2e60773SJohn Baldwin 
356b2e60773SJohn Baldwin 	ktls_session_zone = uma_zcreate("ktls_session",
357b2e60773SJohn Baldwin 	    sizeof(struct ktls_session),
358b2e60773SJohn Baldwin 	    NULL, NULL, NULL, NULL,
359b2e60773SJohn Baldwin 	    UMA_ALIGN_CACHE, 0);
360b2e60773SJohn Baldwin 
36149f6925cSMark Johnston 	if (ktls_sw_buffer_cache) {
36249f6925cSMark Johnston 		ktls_buffer_zone = uma_zcache_create("ktls_buffers",
36349f6925cSMark Johnston 		    roundup2(ktls_maxlen, PAGE_SIZE), NULL, NULL, NULL, NULL,
36449f6925cSMark Johnston 		    ktls_buffer_import, ktls_buffer_release, NULL,
36549f6925cSMark Johnston 		    UMA_ZONE_FIRSTTOUCH);
36649f6925cSMark Johnston 	}
36749f6925cSMark Johnston 
368b2e60773SJohn Baldwin 	/*
369b2e60773SJohn Baldwin 	 * Initialize the workqueues to run the TLS work.  We create a
370b2e60773SJohn Baldwin 	 * work queue for each CPU.
371b2e60773SJohn Baldwin 	 */
372b2e60773SJohn Baldwin 	CPU_FOREACH(i) {
3733c0e5685SJohn Baldwin 		STAILQ_INIT(&ktls_wq[i].m_head);
3743c0e5685SJohn Baldwin 		STAILQ_INIT(&ktls_wq[i].so_head);
375b2e60773SJohn Baldwin 		mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
376b2e60773SJohn Baldwin 		error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
37761b8a4afSAndrew Gallatin 		    &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
378b2e60773SJohn Baldwin 		if (error)
379b2e60773SJohn Baldwin 			panic("Can't add KTLS thread %d error %d", i, error);
380b2e60773SJohn Baldwin 
381b2e60773SJohn Baldwin 		/*
382b2e60773SJohn Baldwin 		 * Bind threads to cores.  If ktls_bind_threads is >
383b2e60773SJohn Baldwin 		 * 1, then we bind to the NUMA domain.
384b2e60773SJohn Baldwin 		 */
385b2e60773SJohn Baldwin 		if (ktls_bind_threads) {
386b2e60773SJohn Baldwin 			if (ktls_bind_threads > 1) {
387b2e60773SJohn Baldwin 				pc = pcpu_find(i);
38802bc3865SAndrew Gallatin 				domain = pc->pc_domain;
38902bc3865SAndrew Gallatin 				CPU_COPY(&cpuset_domain[domain], &mask);
39002bc3865SAndrew Gallatin 				count = ktls_domains[domain].count;
39102bc3865SAndrew Gallatin 				ktls_domains[domain].cpu[count] = i;
39202bc3865SAndrew Gallatin 				ktls_domains[domain].count++;
393b2e60773SJohn Baldwin 			} else {
394b2e60773SJohn Baldwin 				CPU_SETOF(i, &mask);
395b2e60773SJohn Baldwin 			}
396b2e60773SJohn Baldwin 			error = cpuset_setthread(td->td_tid, &mask);
397b2e60773SJohn Baldwin 			if (error)
398b2e60773SJohn Baldwin 				panic(
399b2e60773SJohn Baldwin 			    "Unable to bind KTLS thread for CPU %d error %d",
400b2e60773SJohn Baldwin 				     i, error);
401b2e60773SJohn Baldwin 		}
402b2e60773SJohn Baldwin 		ktls_cpuid_lookup[ktls_number_threads] = i;
403b2e60773SJohn Baldwin 		ktls_number_threads++;
404b2e60773SJohn Baldwin 	}
40502bc3865SAndrew Gallatin 
40602bc3865SAndrew Gallatin 	/*
40702bc3865SAndrew Gallatin 	 * If we somehow have an empty domain, fall back to choosing
40802bc3865SAndrew Gallatin 	 * among all KTLS threads.
40902bc3865SAndrew Gallatin 	 */
4104dc1b17dSMark Johnston 	if (ktls_bind_threads > 1) {
41102bc3865SAndrew Gallatin 		for (i = 0; i < vm_ndomains; i++) {
41202bc3865SAndrew Gallatin 			if (ktls_domains[i].count == 0) {
4134dc1b17dSMark Johnston 				ktls_bind_threads = 1;
41402bc3865SAndrew Gallatin 				break;
41502bc3865SAndrew Gallatin 			}
41602bc3865SAndrew Gallatin 		}
4174dc1b17dSMark Johnston 	}
41802bc3865SAndrew Gallatin 
41989b65087SMark Johnston 	if (bootverbose)
420b2e60773SJohn Baldwin 		printf("KTLS: Initialized %d threads\n", ktls_number_threads);
421b2e60773SJohn Baldwin }
422b2e60773SJohn Baldwin SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
423b2e60773SJohn Baldwin 
424b2e60773SJohn Baldwin #if defined(INET) || defined(INET6)
425b2e60773SJohn Baldwin static int
426b2e60773SJohn Baldwin ktls_create_session(struct socket *so, struct tls_enable *en,
427b2e60773SJohn Baldwin     struct ktls_session **tlsp)
428b2e60773SJohn Baldwin {
429b2e60773SJohn Baldwin 	struct ktls_session *tls;
430b2e60773SJohn Baldwin 	int error;
431b2e60773SJohn Baldwin 
4327d29eb9aSJohn Baldwin 	/* Only TLS 1.0 - 1.3 are supported. */
433b2e60773SJohn Baldwin 	if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
434b2e60773SJohn Baldwin 		return (EINVAL);
435b2e60773SJohn Baldwin 	if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
4366554362cSAndrew Gallatin 	    en->tls_vminor > TLS_MINOR_VER_THREE)
437b2e60773SJohn Baldwin 		return (EINVAL);
438b2e60773SJohn Baldwin 
439b2e60773SJohn Baldwin 	if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
440b2e60773SJohn Baldwin 		return (EINVAL);
441b2e60773SJohn Baldwin 	if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
442b2e60773SJohn Baldwin 		return (EINVAL);
4436554362cSAndrew Gallatin 	if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
444b2e60773SJohn Baldwin 		return (EINVAL);
445b2e60773SJohn Baldwin 
446b2e60773SJohn Baldwin 	/* All supported algorithms require a cipher key. */
447b2e60773SJohn Baldwin 	if (en->cipher_key_len == 0)
448b2e60773SJohn Baldwin 		return (EINVAL);
449b2e60773SJohn Baldwin 
450b2e60773SJohn Baldwin 	/* No flags are currently supported. */
451b2e60773SJohn Baldwin 	if (en->flags != 0)
452b2e60773SJohn Baldwin 		return (EINVAL);
453b2e60773SJohn Baldwin 
454b2e60773SJohn Baldwin 	/* Common checks for supported algorithms. */
455b2e60773SJohn Baldwin 	switch (en->cipher_algorithm) {
456b2e60773SJohn Baldwin 	case CRYPTO_AES_NIST_GCM_16:
457b2e60773SJohn Baldwin 		/*
458b2e60773SJohn Baldwin 		 * auth_algorithm isn't used, but permit GMAC values
459b2e60773SJohn Baldwin 		 * for compatibility.
460b2e60773SJohn Baldwin 		 */
461b2e60773SJohn Baldwin 		switch (en->auth_algorithm) {
462b2e60773SJohn Baldwin 		case 0:
463c0341432SJohn Baldwin #ifdef COMPAT_FREEBSD12
464c0341432SJohn Baldwin 		/* XXX: Really 13.0-current COMPAT. */
465b2e60773SJohn Baldwin 		case CRYPTO_AES_128_NIST_GMAC:
466b2e60773SJohn Baldwin 		case CRYPTO_AES_192_NIST_GMAC:
467b2e60773SJohn Baldwin 		case CRYPTO_AES_256_NIST_GMAC:
468c0341432SJohn Baldwin #endif
469b2e60773SJohn Baldwin 			break;
470b2e60773SJohn Baldwin 		default:
471b2e60773SJohn Baldwin 			return (EINVAL);
472b2e60773SJohn Baldwin 		}
473b2e60773SJohn Baldwin 		if (en->auth_key_len != 0)
474b2e60773SJohn Baldwin 			return (EINVAL);
4756554362cSAndrew Gallatin 		if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
4766554362cSAndrew Gallatin 			en->iv_len != TLS_AEAD_GCM_LEN) ||
4776554362cSAndrew Gallatin 		    (en->tls_vminor == TLS_MINOR_VER_THREE &&
4786554362cSAndrew Gallatin 			en->iv_len != TLS_1_3_GCM_IV_LEN))
479b2e60773SJohn Baldwin 			return (EINVAL);
480b2e60773SJohn Baldwin 		break;
481b2e60773SJohn Baldwin 	case CRYPTO_AES_CBC:
482b2e60773SJohn Baldwin 		switch (en->auth_algorithm) {
483b2e60773SJohn Baldwin 		case CRYPTO_SHA1_HMAC:
484b2e60773SJohn Baldwin 			/*
485b2e60773SJohn Baldwin 			 * TLS 1.0 requires an implicit IV.  TLS 1.1+
486b2e60773SJohn Baldwin 			 * all use explicit IVs.
487b2e60773SJohn Baldwin 			 */
488b2e60773SJohn Baldwin 			if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
489b2e60773SJohn Baldwin 				if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
490b2e60773SJohn Baldwin 					return (EINVAL);
491b2e60773SJohn Baldwin 				break;
492b2e60773SJohn Baldwin 			}
493b2e60773SJohn Baldwin 
494b2e60773SJohn Baldwin 			/* FALLTHROUGH */
495b2e60773SJohn Baldwin 		case CRYPTO_SHA2_256_HMAC:
496b2e60773SJohn Baldwin 		case CRYPTO_SHA2_384_HMAC:
497b2e60773SJohn Baldwin 			/* Ignore any supplied IV. */
498b2e60773SJohn Baldwin 			en->iv_len = 0;
499b2e60773SJohn Baldwin 			break;
500b2e60773SJohn Baldwin 		default:
501b2e60773SJohn Baldwin 			return (EINVAL);
502b2e60773SJohn Baldwin 		}
503b2e60773SJohn Baldwin 		if (en->auth_key_len == 0)
504b2e60773SJohn Baldwin 			return (EINVAL);
505b2e60773SJohn Baldwin 		break;
5069c64fc40SJohn Baldwin 	case CRYPTO_CHACHA20_POLY1305:
5079c64fc40SJohn Baldwin 		if (en->auth_algorithm != 0 || en->auth_key_len != 0)
5089c64fc40SJohn Baldwin 			return (EINVAL);
5099c64fc40SJohn Baldwin 		if (en->tls_vminor != TLS_MINOR_VER_TWO &&
5109c64fc40SJohn Baldwin 		    en->tls_vminor != TLS_MINOR_VER_THREE)
5119c64fc40SJohn Baldwin 			return (EINVAL);
5129c64fc40SJohn Baldwin 		if (en->iv_len != TLS_CHACHA20_IV_LEN)
5139c64fc40SJohn Baldwin 			return (EINVAL);
5149c64fc40SJohn Baldwin 		break;
515b2e60773SJohn Baldwin 	default:
516b2e60773SJohn Baldwin 		return (EINVAL);
517b2e60773SJohn Baldwin 	}
518b2e60773SJohn Baldwin 
519b2e60773SJohn Baldwin 	tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
520b2e60773SJohn Baldwin 
521b2e60773SJohn Baldwin 	counter_u64_add(ktls_offload_active, 1);
522b2e60773SJohn Baldwin 
523b2e60773SJohn Baldwin 	refcount_init(&tls->refcount, 1);
524b2e60773SJohn Baldwin 	TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
525b2e60773SJohn Baldwin 
526b2e60773SJohn Baldwin 	tls->wq_index = ktls_get_cpu(so);
527b2e60773SJohn Baldwin 
528b2e60773SJohn Baldwin 	tls->params.cipher_algorithm = en->cipher_algorithm;
529b2e60773SJohn Baldwin 	tls->params.auth_algorithm = en->auth_algorithm;
530b2e60773SJohn Baldwin 	tls->params.tls_vmajor = en->tls_vmajor;
531b2e60773SJohn Baldwin 	tls->params.tls_vminor = en->tls_vminor;
532b2e60773SJohn Baldwin 	tls->params.flags = en->flags;
533b2e60773SJohn Baldwin 	tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
534b2e60773SJohn Baldwin 
535b2e60773SJohn Baldwin 	/* Set the header and trailer lengths. */
536b2e60773SJohn Baldwin 	tls->params.tls_hlen = sizeof(struct tls_record_layer);
537b2e60773SJohn Baldwin 	switch (en->cipher_algorithm) {
538b2e60773SJohn Baldwin 	case CRYPTO_AES_NIST_GCM_16:
5396554362cSAndrew Gallatin 		/*
5406554362cSAndrew Gallatin 		 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
5416554362cSAndrew Gallatin 		 * nonce.  TLS 1.3 uses a 12 byte implicit IV.
5426554362cSAndrew Gallatin 		 */
5436554362cSAndrew Gallatin 		if (en->tls_vminor < TLS_MINOR_VER_THREE)
5446554362cSAndrew Gallatin 			tls->params.tls_hlen += sizeof(uint64_t);
545b2e60773SJohn Baldwin 		tls->params.tls_tlen = AES_GMAC_HASH_LEN;
546b2e60773SJohn Baldwin 		tls->params.tls_bs = 1;
547b2e60773SJohn Baldwin 		break;
548b2e60773SJohn Baldwin 	case CRYPTO_AES_CBC:
549b2e60773SJohn Baldwin 		switch (en->auth_algorithm) {
550b2e60773SJohn Baldwin 		case CRYPTO_SHA1_HMAC:
551b2e60773SJohn Baldwin 			if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
552b2e60773SJohn Baldwin 				/* Implicit IV, no nonce. */
553b2e60773SJohn Baldwin 			} else {
554b2e60773SJohn Baldwin 				tls->params.tls_hlen += AES_BLOCK_LEN;
555b2e60773SJohn Baldwin 			}
556b2e60773SJohn Baldwin 			tls->params.tls_tlen = AES_BLOCK_LEN +
557b2e60773SJohn Baldwin 			    SHA1_HASH_LEN;
558b2e60773SJohn Baldwin 			break;
559b2e60773SJohn Baldwin 		case CRYPTO_SHA2_256_HMAC:
560b2e60773SJohn Baldwin 			tls->params.tls_hlen += AES_BLOCK_LEN;
561b2e60773SJohn Baldwin 			tls->params.tls_tlen = AES_BLOCK_LEN +
562b2e60773SJohn Baldwin 			    SHA2_256_HASH_LEN;
563b2e60773SJohn Baldwin 			break;
564b2e60773SJohn Baldwin 		case CRYPTO_SHA2_384_HMAC:
565b2e60773SJohn Baldwin 			tls->params.tls_hlen += AES_BLOCK_LEN;
566b2e60773SJohn Baldwin 			tls->params.tls_tlen = AES_BLOCK_LEN +
567b2e60773SJohn Baldwin 			    SHA2_384_HASH_LEN;
568b2e60773SJohn Baldwin 			break;
569b2e60773SJohn Baldwin 		default:
570b2e60773SJohn Baldwin 			panic("invalid hmac");
571b2e60773SJohn Baldwin 		}
572b2e60773SJohn Baldwin 		tls->params.tls_bs = AES_BLOCK_LEN;
573b2e60773SJohn Baldwin 		break;
5749c64fc40SJohn Baldwin 	case CRYPTO_CHACHA20_POLY1305:
5759c64fc40SJohn Baldwin 		/*
5769c64fc40SJohn Baldwin 		 * Chacha20 uses a 12 byte implicit IV.
5779c64fc40SJohn Baldwin 		 */
5789c64fc40SJohn Baldwin 		tls->params.tls_tlen = POLY1305_HASH_LEN;
5799c64fc40SJohn Baldwin 		tls->params.tls_bs = 1;
5809c64fc40SJohn Baldwin 		break;
581b2e60773SJohn Baldwin 	default:
582b2e60773SJohn Baldwin 		panic("invalid cipher");
583b2e60773SJohn Baldwin 	}
584b2e60773SJohn Baldwin 
5859c64fc40SJohn Baldwin 	/*
5869c64fc40SJohn Baldwin 	 * TLS 1.3 includes optional padding which we do not support,
5879c64fc40SJohn Baldwin 	 * and also puts the "real" record type at the end of the
5889c64fc40SJohn Baldwin 	 * encrypted data.
5899c64fc40SJohn Baldwin 	 */
5909c64fc40SJohn Baldwin 	if (en->tls_vminor == TLS_MINOR_VER_THREE)
5919c64fc40SJohn Baldwin 		tls->params.tls_tlen += sizeof(uint8_t);
5929c64fc40SJohn Baldwin 
593b2e60773SJohn Baldwin 	KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
594b2e60773SJohn Baldwin 	    ("TLS header length too long: %d", tls->params.tls_hlen));
595b2e60773SJohn Baldwin 	KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
596b2e60773SJohn Baldwin 	    ("TLS trailer length too long: %d", tls->params.tls_tlen));
597b2e60773SJohn Baldwin 
598b2e60773SJohn Baldwin 	if (en->auth_key_len != 0) {
599b2e60773SJohn Baldwin 		tls->params.auth_key_len = en->auth_key_len;
600b2e60773SJohn Baldwin 		tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
601b2e60773SJohn Baldwin 		    M_WAITOK);
602b2e60773SJohn Baldwin 		error = copyin(en->auth_key, tls->params.auth_key,
603b2e60773SJohn Baldwin 		    en->auth_key_len);
604b2e60773SJohn Baldwin 		if (error)
605b2e60773SJohn Baldwin 			goto out;
606b2e60773SJohn Baldwin 	}
607b2e60773SJohn Baldwin 
608b2e60773SJohn Baldwin 	tls->params.cipher_key_len = en->cipher_key_len;
609b2e60773SJohn Baldwin 	tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
610b2e60773SJohn Baldwin 	error = copyin(en->cipher_key, tls->params.cipher_key,
611b2e60773SJohn Baldwin 	    en->cipher_key_len);
612b2e60773SJohn Baldwin 	if (error)
613b2e60773SJohn Baldwin 		goto out;
614b2e60773SJohn Baldwin 
615b2e60773SJohn Baldwin 	/*
6169c64fc40SJohn Baldwin 	 * This holds the implicit portion of the nonce for AEAD
6179c64fc40SJohn Baldwin 	 * ciphers and the initial implicit IV for TLS 1.0.  The
6189c64fc40SJohn Baldwin 	 * explicit portions of the IV are generated in ktls_frame().
619b2e60773SJohn Baldwin 	 */
620b2e60773SJohn Baldwin 	if (en->iv_len != 0) {
621b2e60773SJohn Baldwin 		tls->params.iv_len = en->iv_len;
622b2e60773SJohn Baldwin 		error = copyin(en->iv, tls->params.iv, en->iv_len);
623b2e60773SJohn Baldwin 		if (error)
624b2e60773SJohn Baldwin 			goto out;
6257d29eb9aSJohn Baldwin 
6267d29eb9aSJohn Baldwin 		/*
6279c64fc40SJohn Baldwin 		 * For TLS 1.2 with GCM, generate an 8-byte nonce as a
6289c64fc40SJohn Baldwin 		 * counter to generate unique explicit IVs.
6297d29eb9aSJohn Baldwin 		 *
6307d29eb9aSJohn Baldwin 		 * Store this counter in the last 8 bytes of the IV
6317d29eb9aSJohn Baldwin 		 * array so that it is 8-byte aligned.
6327d29eb9aSJohn Baldwin 		 */
6337d29eb9aSJohn Baldwin 		if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
6347d29eb9aSJohn Baldwin 		    en->tls_vminor == TLS_MINOR_VER_TWO)
6357d29eb9aSJohn Baldwin 			arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
636b2e60773SJohn Baldwin 	}
637b2e60773SJohn Baldwin 
638b2e60773SJohn Baldwin 	*tlsp = tls;
639b2e60773SJohn Baldwin 	return (0);
640b2e60773SJohn Baldwin 
641b2e60773SJohn Baldwin out:
642b2e60773SJohn Baldwin 	ktls_cleanup(tls);
643b2e60773SJohn Baldwin 	return (error);
644b2e60773SJohn Baldwin }
645b2e60773SJohn Baldwin 
646b2e60773SJohn Baldwin static struct ktls_session *
647b2e60773SJohn Baldwin ktls_clone_session(struct ktls_session *tls)
648b2e60773SJohn Baldwin {
649b2e60773SJohn Baldwin 	struct ktls_session *tls_new;
650b2e60773SJohn Baldwin 
651b2e60773SJohn Baldwin 	tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
652b2e60773SJohn Baldwin 
653b2e60773SJohn Baldwin 	counter_u64_add(ktls_offload_active, 1);
654b2e60773SJohn Baldwin 
655b2e60773SJohn Baldwin 	refcount_init(&tls_new->refcount, 1);
656b2e60773SJohn Baldwin 
657b2e60773SJohn Baldwin 	/* Copy fields from existing session. */
658b2e60773SJohn Baldwin 	tls_new->params = tls->params;
659b2e60773SJohn Baldwin 	tls_new->wq_index = tls->wq_index;
660b2e60773SJohn Baldwin 
661b2e60773SJohn Baldwin 	/* Deep copy keys. */
662b2e60773SJohn Baldwin 	if (tls_new->params.auth_key != NULL) {
663b2e60773SJohn Baldwin 		tls_new->params.auth_key = malloc(tls->params.auth_key_len,
664b2e60773SJohn Baldwin 		    M_KTLS, M_WAITOK);
665b2e60773SJohn Baldwin 		memcpy(tls_new->params.auth_key, tls->params.auth_key,
666b2e60773SJohn Baldwin 		    tls->params.auth_key_len);
667b2e60773SJohn Baldwin 	}
668b2e60773SJohn Baldwin 
669b2e60773SJohn Baldwin 	tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
670b2e60773SJohn Baldwin 	    M_WAITOK);
671b2e60773SJohn Baldwin 	memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
672b2e60773SJohn Baldwin 	    tls->params.cipher_key_len);
673b2e60773SJohn Baldwin 
674b2e60773SJohn Baldwin 	return (tls_new);
675b2e60773SJohn Baldwin }
676b2e60773SJohn Baldwin #endif
677b2e60773SJohn Baldwin 
678b2e60773SJohn Baldwin static void
679b2e60773SJohn Baldwin ktls_cleanup(struct ktls_session *tls)
680b2e60773SJohn Baldwin {
681b2e60773SJohn Baldwin 
682b2e60773SJohn Baldwin 	counter_u64_add(ktls_offload_active, -1);
6839e14430dSJohn Baldwin 	switch (tls->mode) {
6849e14430dSJohn Baldwin 	case TCP_TLS_MODE_SW:
685b2e60773SJohn Baldwin 		switch (tls->params.cipher_algorithm) {
686b2e60773SJohn Baldwin 		case CRYPTO_AES_CBC:
687b2e60773SJohn Baldwin 			counter_u64_add(ktls_sw_cbc, -1);
688b2e60773SJohn Baldwin 			break;
689b2e60773SJohn Baldwin 		case CRYPTO_AES_NIST_GCM_16:
690b2e60773SJohn Baldwin 			counter_u64_add(ktls_sw_gcm, -1);
691b2e60773SJohn Baldwin 			break;
6929c64fc40SJohn Baldwin 		case CRYPTO_CHACHA20_POLY1305:
6939c64fc40SJohn Baldwin 			counter_u64_add(ktls_sw_chacha20, -1);
6949c64fc40SJohn Baldwin 			break;
695b2e60773SJohn Baldwin 		}
69621e3c1fbSJohn Baldwin 		ktls_ocf_free(tls);
6979e14430dSJohn Baldwin 		break;
6989e14430dSJohn Baldwin 	case TCP_TLS_MODE_IFNET:
699b2e60773SJohn Baldwin 		switch (tls->params.cipher_algorithm) {
700b2e60773SJohn Baldwin 		case CRYPTO_AES_CBC:
701b2e60773SJohn Baldwin 			counter_u64_add(ktls_ifnet_cbc, -1);
702b2e60773SJohn Baldwin 			break;
703b2e60773SJohn Baldwin 		case CRYPTO_AES_NIST_GCM_16:
704b2e60773SJohn Baldwin 			counter_u64_add(ktls_ifnet_gcm, -1);
705b2e60773SJohn Baldwin 			break;
7069c64fc40SJohn Baldwin 		case CRYPTO_CHACHA20_POLY1305:
7079c64fc40SJohn Baldwin 			counter_u64_add(ktls_ifnet_chacha20, -1);
7089c64fc40SJohn Baldwin 			break;
709b2e60773SJohn Baldwin 		}
7109675d889SAndrew Gallatin 		if (tls->snd_tag != NULL)
711b2e60773SJohn Baldwin 			m_snd_tag_rele(tls->snd_tag);
7129e14430dSJohn Baldwin 		break;
7139e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
7149e14430dSJohn Baldwin 	case TCP_TLS_MODE_TOE:
7159e14430dSJohn Baldwin 		switch (tls->params.cipher_algorithm) {
7169e14430dSJohn Baldwin 		case CRYPTO_AES_CBC:
7179e14430dSJohn Baldwin 			counter_u64_add(ktls_toe_cbc, -1);
7189e14430dSJohn Baldwin 			break;
7199e14430dSJohn Baldwin 		case CRYPTO_AES_NIST_GCM_16:
7209e14430dSJohn Baldwin 			counter_u64_add(ktls_toe_gcm, -1);
7219e14430dSJohn Baldwin 			break;
7229c64fc40SJohn Baldwin 		case CRYPTO_CHACHA20_POLY1305:
7239c64fc40SJohn Baldwin 			counter_u64_add(ktls_toe_chacha20, -1);
7249c64fc40SJohn Baldwin 			break;
7259e14430dSJohn Baldwin 		}
7269e14430dSJohn Baldwin 		break;
7279e14430dSJohn Baldwin #endif
728b2e60773SJohn Baldwin 	}
729b2e60773SJohn Baldwin 	if (tls->params.auth_key != NULL) {
7304a711b8dSJohn Baldwin 		zfree(tls->params.auth_key, M_KTLS);
731b2e60773SJohn Baldwin 		tls->params.auth_key = NULL;
732b2e60773SJohn Baldwin 		tls->params.auth_key_len = 0;
733b2e60773SJohn Baldwin 	}
734b2e60773SJohn Baldwin 	if (tls->params.cipher_key != NULL) {
7354a711b8dSJohn Baldwin 		zfree(tls->params.cipher_key, M_KTLS);
736b2e60773SJohn Baldwin 		tls->params.cipher_key = NULL;
737b2e60773SJohn Baldwin 		tls->params.cipher_key_len = 0;
738b2e60773SJohn Baldwin 	}
739b2e60773SJohn Baldwin 	explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
740b2e60773SJohn Baldwin }
741b2e60773SJohn Baldwin 
742b2e60773SJohn Baldwin #if defined(INET) || defined(INET6)
7439e14430dSJohn Baldwin 
7449e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
7459e14430dSJohn Baldwin static int
746f1f93475SJohn Baldwin ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
7479e14430dSJohn Baldwin {
7489e14430dSJohn Baldwin 	struct inpcb *inp;
7499e14430dSJohn Baldwin 	struct tcpcb *tp;
7509e14430dSJohn Baldwin 	int error;
7519e14430dSJohn Baldwin 
7529e14430dSJohn Baldwin 	inp = so->so_pcb;
7539e14430dSJohn Baldwin 	INP_WLOCK(inp);
7549e14430dSJohn Baldwin 	if (inp->inp_flags2 & INP_FREED) {
7559e14430dSJohn Baldwin 		INP_WUNLOCK(inp);
7569e14430dSJohn Baldwin 		return (ECONNRESET);
7579e14430dSJohn Baldwin 	}
7589e14430dSJohn Baldwin 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
7599e14430dSJohn Baldwin 		INP_WUNLOCK(inp);
7609e14430dSJohn Baldwin 		return (ECONNRESET);
7619e14430dSJohn Baldwin 	}
7629e14430dSJohn Baldwin 	if (inp->inp_socket == NULL) {
7639e14430dSJohn Baldwin 		INP_WUNLOCK(inp);
7649e14430dSJohn Baldwin 		return (ECONNRESET);
7659e14430dSJohn Baldwin 	}
7669e14430dSJohn Baldwin 	tp = intotcpcb(inp);
7676bcf3c46SJohn Baldwin 	if (!(tp->t_flags & TF_TOE)) {
7689e14430dSJohn Baldwin 		INP_WUNLOCK(inp);
7699e14430dSJohn Baldwin 		return (EOPNOTSUPP);
7709e14430dSJohn Baldwin 	}
7719e14430dSJohn Baldwin 
772f1f93475SJohn Baldwin 	error = tcp_offload_alloc_tls_session(tp, tls, direction);
7739e14430dSJohn Baldwin 	INP_WUNLOCK(inp);
7749e14430dSJohn Baldwin 	if (error == 0) {
7759e14430dSJohn Baldwin 		tls->mode = TCP_TLS_MODE_TOE;
7769e14430dSJohn Baldwin 		switch (tls->params.cipher_algorithm) {
7779e14430dSJohn Baldwin 		case CRYPTO_AES_CBC:
7789e14430dSJohn Baldwin 			counter_u64_add(ktls_toe_cbc, 1);
7799e14430dSJohn Baldwin 			break;
7809e14430dSJohn Baldwin 		case CRYPTO_AES_NIST_GCM_16:
7819e14430dSJohn Baldwin 			counter_u64_add(ktls_toe_gcm, 1);
7829e14430dSJohn Baldwin 			break;
7839c64fc40SJohn Baldwin 		case CRYPTO_CHACHA20_POLY1305:
7849c64fc40SJohn Baldwin 			counter_u64_add(ktls_toe_chacha20, 1);
7859c64fc40SJohn Baldwin 			break;
7869e14430dSJohn Baldwin 		}
7879e14430dSJohn Baldwin 	}
7889e14430dSJohn Baldwin 	return (error);
7899e14430dSJohn Baldwin }
7909e14430dSJohn Baldwin #endif
7919e14430dSJohn Baldwin 
792b2e60773SJohn Baldwin /*
793b2e60773SJohn Baldwin  * Common code used when first enabling ifnet TLS on a connection or
794b2e60773SJohn Baldwin  * when allocating a new ifnet TLS session due to a routing change.
795b2e60773SJohn Baldwin  * This function allocates a new TLS send tag on whatever interface
796b2e60773SJohn Baldwin  * the connection is currently routed over.
797b2e60773SJohn Baldwin  */
798b2e60773SJohn Baldwin static int
799b2e60773SJohn Baldwin ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
800b2e60773SJohn Baldwin     struct m_snd_tag **mstp)
801b2e60773SJohn Baldwin {
802b2e60773SJohn Baldwin 	union if_snd_tag_alloc_params params;
803b2e60773SJohn Baldwin 	struct ifnet *ifp;
804983066f0SAlexander V. Chernikov 	struct nhop_object *nh;
805b2e60773SJohn Baldwin 	struct tcpcb *tp;
806b2e60773SJohn Baldwin 	int error;
807b2e60773SJohn Baldwin 
808b2e60773SJohn Baldwin 	INP_RLOCK(inp);
809b2e60773SJohn Baldwin 	if (inp->inp_flags2 & INP_FREED) {
810b2e60773SJohn Baldwin 		INP_RUNLOCK(inp);
811b2e60773SJohn Baldwin 		return (ECONNRESET);
812b2e60773SJohn Baldwin 	}
813b2e60773SJohn Baldwin 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
814b2e60773SJohn Baldwin 		INP_RUNLOCK(inp);
815b2e60773SJohn Baldwin 		return (ECONNRESET);
816b2e60773SJohn Baldwin 	}
817b2e60773SJohn Baldwin 	if (inp->inp_socket == NULL) {
818b2e60773SJohn Baldwin 		INP_RUNLOCK(inp);
819b2e60773SJohn Baldwin 		return (ECONNRESET);
820b2e60773SJohn Baldwin 	}
821b2e60773SJohn Baldwin 	tp = intotcpcb(inp);
822b2e60773SJohn Baldwin 
823b2e60773SJohn Baldwin 	/*
824b2e60773SJohn Baldwin 	 * Check administrative controls on ifnet TLS to determine if
825b2e60773SJohn Baldwin 	 * ifnet TLS should be denied.
826b2e60773SJohn Baldwin 	 *
827b2e60773SJohn Baldwin 	 * - Always permit 'force' requests.
828b2e60773SJohn Baldwin 	 * - ktls_ifnet_permitted == 0: always deny.
829b2e60773SJohn Baldwin 	 */
830b2e60773SJohn Baldwin 	if (!force && ktls_ifnet_permitted == 0) {
831b2e60773SJohn Baldwin 		INP_RUNLOCK(inp);
832b2e60773SJohn Baldwin 		return (ENXIO);
833b2e60773SJohn Baldwin 	}
834b2e60773SJohn Baldwin 
835b2e60773SJohn Baldwin 	/*
836b2e60773SJohn Baldwin 	 * XXX: Use the cached route in the inpcb to find the
837b2e60773SJohn Baldwin 	 * interface.  This should perhaps instead use
838b2e60773SJohn Baldwin 	 * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
839b2e60773SJohn Baldwin 	 * enabled after a connection has completed key negotiation in
840b2e60773SJohn Baldwin 	 * userland, the cached route will be present in practice.
841b2e60773SJohn Baldwin 	 */
842983066f0SAlexander V. Chernikov 	nh = inp->inp_route.ro_nh;
843983066f0SAlexander V. Chernikov 	if (nh == NULL) {
844b2e60773SJohn Baldwin 		INP_RUNLOCK(inp);
845b2e60773SJohn Baldwin 		return (ENXIO);
846b2e60773SJohn Baldwin 	}
847983066f0SAlexander V. Chernikov 	ifp = nh->nh_ifp;
848b2e60773SJohn Baldwin 	if_ref(ifp);
849b2e60773SJohn Baldwin 
850521eac97SJohn Baldwin 	/*
851521eac97SJohn Baldwin 	 * Allocate a TLS + ratelimit tag if the connection has an
852521eac97SJohn Baldwin 	 * existing pacing rate.
853521eac97SJohn Baldwin 	 */
854521eac97SJohn Baldwin 	if (tp->t_pacing_rate != -1 &&
855521eac97SJohn Baldwin 	    (ifp->if_capenable & IFCAP_TXTLS_RTLMT) != 0) {
856521eac97SJohn Baldwin 		params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
857521eac97SJohn Baldwin 		params.tls_rate_limit.inp = inp;
858521eac97SJohn Baldwin 		params.tls_rate_limit.tls = tls;
859521eac97SJohn Baldwin 		params.tls_rate_limit.max_rate = tp->t_pacing_rate;
860521eac97SJohn Baldwin 	} else {
861b2e60773SJohn Baldwin 		params.hdr.type = IF_SND_TAG_TYPE_TLS;
862521eac97SJohn Baldwin 		params.tls.inp = inp;
863521eac97SJohn Baldwin 		params.tls.tls = tls;
864521eac97SJohn Baldwin 	}
865b2e60773SJohn Baldwin 	params.hdr.flowid = inp->inp_flowid;
866b2e60773SJohn Baldwin 	params.hdr.flowtype = inp->inp_flowtype;
86798085baeSAndrew Gallatin 	params.hdr.numa_domain = inp->inp_numa_domain;
868b2e60773SJohn Baldwin 	INP_RUNLOCK(inp);
869b2e60773SJohn Baldwin 
8703f43ada9SGleb Smirnoff 	if ((ifp->if_capenable & IFCAP_MEXTPG) == 0) {
871b2e60773SJohn Baldwin 		error = EOPNOTSUPP;
872b2e60773SJohn Baldwin 		goto out;
873b2e60773SJohn Baldwin 	}
874b2e60773SJohn Baldwin 	if (inp->inp_vflag & INP_IPV6) {
875b2e60773SJohn Baldwin 		if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
876b2e60773SJohn Baldwin 			error = EOPNOTSUPP;
877b2e60773SJohn Baldwin 			goto out;
878b2e60773SJohn Baldwin 		}
879b2e60773SJohn Baldwin 	} else {
880b2e60773SJohn Baldwin 		if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
881b2e60773SJohn Baldwin 			error = EOPNOTSUPP;
882b2e60773SJohn Baldwin 			goto out;
883b2e60773SJohn Baldwin 		}
884b2e60773SJohn Baldwin 	}
88536e0a362SJohn Baldwin 	error = m_snd_tag_alloc(ifp, &params, mstp);
886b2e60773SJohn Baldwin out:
887b2e60773SJohn Baldwin 	if_rele(ifp);
888b2e60773SJohn Baldwin 	return (error);
889b2e60773SJohn Baldwin }
890b2e60773SJohn Baldwin 
891b2e60773SJohn Baldwin static int
892b2e60773SJohn Baldwin ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
893b2e60773SJohn Baldwin {
894b2e60773SJohn Baldwin 	struct m_snd_tag *mst;
895b2e60773SJohn Baldwin 	int error;
896b2e60773SJohn Baldwin 
897b2e60773SJohn Baldwin 	error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
898b2e60773SJohn Baldwin 	if (error == 0) {
8999e14430dSJohn Baldwin 		tls->mode = TCP_TLS_MODE_IFNET;
900b2e60773SJohn Baldwin 		tls->snd_tag = mst;
901b2e60773SJohn Baldwin 		switch (tls->params.cipher_algorithm) {
902b2e60773SJohn Baldwin 		case CRYPTO_AES_CBC:
903b2e60773SJohn Baldwin 			counter_u64_add(ktls_ifnet_cbc, 1);
904b2e60773SJohn Baldwin 			break;
905b2e60773SJohn Baldwin 		case CRYPTO_AES_NIST_GCM_16:
906b2e60773SJohn Baldwin 			counter_u64_add(ktls_ifnet_gcm, 1);
907b2e60773SJohn Baldwin 			break;
9089c64fc40SJohn Baldwin 		case CRYPTO_CHACHA20_POLY1305:
9099c64fc40SJohn Baldwin 			counter_u64_add(ktls_ifnet_chacha20, 1);
9109c64fc40SJohn Baldwin 			break;
911b2e60773SJohn Baldwin 		}
912b2e60773SJohn Baldwin 	}
913b2e60773SJohn Baldwin 	return (error);
914b2e60773SJohn Baldwin }
915b2e60773SJohn Baldwin 
916b2e60773SJohn Baldwin static int
9173c0e5685SJohn Baldwin ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
918b2e60773SJohn Baldwin {
91921e3c1fbSJohn Baldwin 	int error;
920b2e60773SJohn Baldwin 
92121e3c1fbSJohn Baldwin 	error = ktls_ocf_try(so, tls, direction);
92221e3c1fbSJohn Baldwin 	if (error)
92321e3c1fbSJohn Baldwin 		return (error);
9249e14430dSJohn Baldwin 	tls->mode = TCP_TLS_MODE_SW;
925b2e60773SJohn Baldwin 	switch (tls->params.cipher_algorithm) {
926b2e60773SJohn Baldwin 	case CRYPTO_AES_CBC:
927b2e60773SJohn Baldwin 		counter_u64_add(ktls_sw_cbc, 1);
928b2e60773SJohn Baldwin 		break;
929b2e60773SJohn Baldwin 	case CRYPTO_AES_NIST_GCM_16:
930b2e60773SJohn Baldwin 		counter_u64_add(ktls_sw_gcm, 1);
931b2e60773SJohn Baldwin 		break;
9329c64fc40SJohn Baldwin 	case CRYPTO_CHACHA20_POLY1305:
9339c64fc40SJohn Baldwin 		counter_u64_add(ktls_sw_chacha20, 1);
9349c64fc40SJohn Baldwin 		break;
935b2e60773SJohn Baldwin 	}
936b2e60773SJohn Baldwin 	return (0);
937b2e60773SJohn Baldwin }
938b2e60773SJohn Baldwin 
9393c0e5685SJohn Baldwin /*
9403c0e5685SJohn Baldwin  * KTLS RX stores data in the socket buffer as a list of TLS records,
9413c0e5685SJohn Baldwin  * where each record is stored as a control message containg the TLS
9423c0e5685SJohn Baldwin  * header followed by data mbufs containing the decrypted data.  This
9433c0e5685SJohn Baldwin  * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
9443c0e5685SJohn Baldwin  * both encrypted and decrypted data.  TLS records decrypted by a NIC
9453c0e5685SJohn Baldwin  * should be queued to the socket buffer as records, but encrypted
9463c0e5685SJohn Baldwin  * data which needs to be decrypted by software arrives as a stream of
9473c0e5685SJohn Baldwin  * regular mbufs which need to be converted.  In addition, there may
9483c0e5685SJohn Baldwin  * already be pending encrypted data in the socket buffer when KTLS RX
9493c0e5685SJohn Baldwin  * is enabled.
9503c0e5685SJohn Baldwin  *
9513c0e5685SJohn Baldwin  * To manage not-yet-decrypted data for KTLS RX, the following scheme
9523c0e5685SJohn Baldwin  * is used:
9533c0e5685SJohn Baldwin  *
9543c0e5685SJohn Baldwin  * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
9553c0e5685SJohn Baldwin  *
9563c0e5685SJohn Baldwin  * - ktls_check_rx checks this chain of mbufs reading the TLS header
9573c0e5685SJohn Baldwin  *   from the first mbuf.  Once all of the data for that TLS record is
9583c0e5685SJohn Baldwin  *   queued, the socket is queued to a worker thread.
9593c0e5685SJohn Baldwin  *
9603c0e5685SJohn Baldwin  * - The worker thread calls ktls_decrypt to decrypt TLS records in
9613c0e5685SJohn Baldwin  *   the TLS chain.  Each TLS record is detached from the TLS chain,
9623c0e5685SJohn Baldwin  *   decrypted, and inserted into the regular socket buffer chain as
9633c0e5685SJohn Baldwin  *   record starting with a control message holding the TLS header and
9643c0e5685SJohn Baldwin  *   a chain of mbufs holding the encrypted data.
9653c0e5685SJohn Baldwin  */
9663c0e5685SJohn Baldwin 
9673c0e5685SJohn Baldwin static void
9683c0e5685SJohn Baldwin sb_mark_notready(struct sockbuf *sb)
9693c0e5685SJohn Baldwin {
9703c0e5685SJohn Baldwin 	struct mbuf *m;
9713c0e5685SJohn Baldwin 
9723c0e5685SJohn Baldwin 	m = sb->sb_mb;
9733c0e5685SJohn Baldwin 	sb->sb_mtls = m;
9743c0e5685SJohn Baldwin 	sb->sb_mb = NULL;
9753c0e5685SJohn Baldwin 	sb->sb_mbtail = NULL;
9763c0e5685SJohn Baldwin 	sb->sb_lastrecord = NULL;
9773c0e5685SJohn Baldwin 	for (; m != NULL; m = m->m_next) {
9783c0e5685SJohn Baldwin 		KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
9793c0e5685SJohn Baldwin 		    __func__));
9803c0e5685SJohn Baldwin 		KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
9813c0e5685SJohn Baldwin 		    __func__));
9823c0e5685SJohn Baldwin 		KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
9833c0e5685SJohn Baldwin 		    __func__));
9843c0e5685SJohn Baldwin 		m->m_flags |= M_NOTREADY;
9853c0e5685SJohn Baldwin 		sb->sb_acc -= m->m_len;
9863c0e5685SJohn Baldwin 		sb->sb_tlscc += m->m_len;
9873c0e5685SJohn Baldwin 		sb->sb_mtlstail = m;
9883c0e5685SJohn Baldwin 	}
9893c0e5685SJohn Baldwin 	KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
9903c0e5685SJohn Baldwin 	    ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
9913c0e5685SJohn Baldwin 	    sb->sb_ccc));
9923c0e5685SJohn Baldwin }
9933c0e5685SJohn Baldwin 
994b2e60773SJohn Baldwin int
995f1f93475SJohn Baldwin ktls_enable_rx(struct socket *so, struct tls_enable *en)
996f1f93475SJohn Baldwin {
997f1f93475SJohn Baldwin 	struct ktls_session *tls;
998f1f93475SJohn Baldwin 	int error;
999f1f93475SJohn Baldwin 
1000f1f93475SJohn Baldwin 	if (!ktls_offload_enable)
1001f1f93475SJohn Baldwin 		return (ENOTSUP);
10026685e259SMichael Tuexen 	if (SOLISTENING(so))
10036685e259SMichael Tuexen 		return (EINVAL);
1004f1f93475SJohn Baldwin 
1005f1f93475SJohn Baldwin 	counter_u64_add(ktls_offload_enable_calls, 1);
1006f1f93475SJohn Baldwin 
1007f1f93475SJohn Baldwin 	/*
1008f1f93475SJohn Baldwin 	 * This should always be true since only the TCP socket option
1009f1f93475SJohn Baldwin 	 * invokes this function.
1010f1f93475SJohn Baldwin 	 */
1011f1f93475SJohn Baldwin 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1012f1f93475SJohn Baldwin 		return (EINVAL);
1013f1f93475SJohn Baldwin 
1014f1f93475SJohn Baldwin 	/*
1015f1f93475SJohn Baldwin 	 * XXX: Don't overwrite existing sessions.  We should permit
1016f1f93475SJohn Baldwin 	 * this to support rekeying in the future.
1017f1f93475SJohn Baldwin 	 */
1018f1f93475SJohn Baldwin 	if (so->so_rcv.sb_tls_info != NULL)
1019f1f93475SJohn Baldwin 		return (EALREADY);
1020f1f93475SJohn Baldwin 
1021f1f93475SJohn Baldwin 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1022f1f93475SJohn Baldwin 		return (ENOTSUP);
1023f1f93475SJohn Baldwin 
10243c0e5685SJohn Baldwin 	/* TLS 1.3 is not yet supported. */
10253c0e5685SJohn Baldwin 	if (en->tls_vmajor == TLS_MAJOR_VER_ONE &&
10263c0e5685SJohn Baldwin 	    en->tls_vminor == TLS_MINOR_VER_THREE)
10273c0e5685SJohn Baldwin 		return (ENOTSUP);
10283c0e5685SJohn Baldwin 
1029f1f93475SJohn Baldwin 	error = ktls_create_session(so, en, &tls);
1030f1f93475SJohn Baldwin 	if (error)
1031f1f93475SJohn Baldwin 		return (error);
1032f1f93475SJohn Baldwin 
1033f1f93475SJohn Baldwin #ifdef TCP_OFFLOAD
1034f1f93475SJohn Baldwin 	error = ktls_try_toe(so, tls, KTLS_RX);
10353c0e5685SJohn Baldwin 	if (error)
1036f1f93475SJohn Baldwin #endif
10373c0e5685SJohn Baldwin 		error = ktls_try_sw(so, tls, KTLS_RX);
1038f1f93475SJohn Baldwin 
1039f1f93475SJohn Baldwin 	if (error) {
1040f1f93475SJohn Baldwin 		ktls_cleanup(tls);
1041f1f93475SJohn Baldwin 		return (error);
1042f1f93475SJohn Baldwin 	}
1043f1f93475SJohn Baldwin 
1044f1f93475SJohn Baldwin 	/* Mark the socket as using TLS offload. */
1045f1f93475SJohn Baldwin 	SOCKBUF_LOCK(&so->so_rcv);
10463c0e5685SJohn Baldwin 	so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1047f1f93475SJohn Baldwin 	so->so_rcv.sb_tls_info = tls;
10483c0e5685SJohn Baldwin 	so->so_rcv.sb_flags |= SB_TLS_RX;
10493c0e5685SJohn Baldwin 
10503c0e5685SJohn Baldwin 	/* Mark existing data as not ready until it can be decrypted. */
10513c0e5685SJohn Baldwin 	sb_mark_notready(&so->so_rcv);
10523c0e5685SJohn Baldwin 	ktls_check_rx(&so->so_rcv);
1053f1f93475SJohn Baldwin 	SOCKBUF_UNLOCK(&so->so_rcv);
1054f1f93475SJohn Baldwin 
1055f1f93475SJohn Baldwin 	counter_u64_add(ktls_offload_total, 1);
1056f1f93475SJohn Baldwin 
1057f1f93475SJohn Baldwin 	return (0);
1058f1f93475SJohn Baldwin }
1059f1f93475SJohn Baldwin 
1060f1f93475SJohn Baldwin int
1061b2e60773SJohn Baldwin ktls_enable_tx(struct socket *so, struct tls_enable *en)
1062b2e60773SJohn Baldwin {
1063b2e60773SJohn Baldwin 	struct ktls_session *tls;
1064521eac97SJohn Baldwin 	struct inpcb *inp;
1065b2e60773SJohn Baldwin 	int error;
1066b2e60773SJohn Baldwin 
1067b2e60773SJohn Baldwin 	if (!ktls_offload_enable)
1068b2e60773SJohn Baldwin 		return (ENOTSUP);
10696685e259SMichael Tuexen 	if (SOLISTENING(so))
10706685e259SMichael Tuexen 		return (EINVAL);
1071b2e60773SJohn Baldwin 
1072b2e60773SJohn Baldwin 	counter_u64_add(ktls_offload_enable_calls, 1);
1073b2e60773SJohn Baldwin 
1074b2e60773SJohn Baldwin 	/*
1075b2e60773SJohn Baldwin 	 * This should always be true since only the TCP socket option
1076b2e60773SJohn Baldwin 	 * invokes this function.
1077b2e60773SJohn Baldwin 	 */
1078b2e60773SJohn Baldwin 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1079b2e60773SJohn Baldwin 		return (EINVAL);
1080b2e60773SJohn Baldwin 
1081b2e60773SJohn Baldwin 	/*
1082b2e60773SJohn Baldwin 	 * XXX: Don't overwrite existing sessions.  We should permit
1083b2e60773SJohn Baldwin 	 * this to support rekeying in the future.
1084b2e60773SJohn Baldwin 	 */
1085b2e60773SJohn Baldwin 	if (so->so_snd.sb_tls_info != NULL)
1086b2e60773SJohn Baldwin 		return (EALREADY);
1087b2e60773SJohn Baldwin 
1088b2e60773SJohn Baldwin 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1089b2e60773SJohn Baldwin 		return (ENOTSUP);
1090b2e60773SJohn Baldwin 
1091b2e60773SJohn Baldwin 	/* TLS requires ext pgs */
1092b2e60773SJohn Baldwin 	if (mb_use_ext_pgs == 0)
1093b2e60773SJohn Baldwin 		return (ENXIO);
1094b2e60773SJohn Baldwin 
1095b2e60773SJohn Baldwin 	error = ktls_create_session(so, en, &tls);
1096b2e60773SJohn Baldwin 	if (error)
1097b2e60773SJohn Baldwin 		return (error);
1098b2e60773SJohn Baldwin 
10999e14430dSJohn Baldwin 	/* Prefer TOE -> ifnet TLS -> software TLS. */
11009e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
1101f1f93475SJohn Baldwin 	error = ktls_try_toe(so, tls, KTLS_TX);
11029e14430dSJohn Baldwin 	if (error)
11039e14430dSJohn Baldwin #endif
1104b2e60773SJohn Baldwin 		error = ktls_try_ifnet(so, tls, false);
1105b2e60773SJohn Baldwin 	if (error)
11063c0e5685SJohn Baldwin 		error = ktls_try_sw(so, tls, KTLS_TX);
1107b2e60773SJohn Baldwin 
1108b2e60773SJohn Baldwin 	if (error) {
1109b2e60773SJohn Baldwin 		ktls_cleanup(tls);
1110b2e60773SJohn Baldwin 		return (error);
1111b2e60773SJohn Baldwin 	}
1112b2e60773SJohn Baldwin 
1113b2e60773SJohn Baldwin 	error = sblock(&so->so_snd, SBL_WAIT);
1114b2e60773SJohn Baldwin 	if (error) {
1115b2e60773SJohn Baldwin 		ktls_cleanup(tls);
1116b2e60773SJohn Baldwin 		return (error);
1117b2e60773SJohn Baldwin 	}
1118b2e60773SJohn Baldwin 
1119521eac97SJohn Baldwin 	/*
1120521eac97SJohn Baldwin 	 * Write lock the INP when setting sb_tls_info so that
1121521eac97SJohn Baldwin 	 * routines in tcp_ratelimit.c can read sb_tls_info while
1122521eac97SJohn Baldwin 	 * holding the INP lock.
1123521eac97SJohn Baldwin 	 */
1124521eac97SJohn Baldwin 	inp = so->so_pcb;
1125521eac97SJohn Baldwin 	INP_WLOCK(inp);
1126b2e60773SJohn Baldwin 	SOCKBUF_LOCK(&so->so_snd);
1127ec1db6e1SJohn Baldwin 	so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1128b2e60773SJohn Baldwin 	so->so_snd.sb_tls_info = tls;
11299e14430dSJohn Baldwin 	if (tls->mode != TCP_TLS_MODE_SW)
1130b2e60773SJohn Baldwin 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1131b2e60773SJohn Baldwin 	SOCKBUF_UNLOCK(&so->so_snd);
1132521eac97SJohn Baldwin 	INP_WUNLOCK(inp);
1133b2e60773SJohn Baldwin 	sbunlock(&so->so_snd);
1134b2e60773SJohn Baldwin 
1135b2e60773SJohn Baldwin 	counter_u64_add(ktls_offload_total, 1);
1136b2e60773SJohn Baldwin 
1137b2e60773SJohn Baldwin 	return (0);
1138b2e60773SJohn Baldwin }
1139b2e60773SJohn Baldwin 
1140b2e60773SJohn Baldwin int
1141f1f93475SJohn Baldwin ktls_get_rx_mode(struct socket *so)
1142f1f93475SJohn Baldwin {
1143f1f93475SJohn Baldwin 	struct ktls_session *tls;
1144f1f93475SJohn Baldwin 	struct inpcb *inp;
1145f1f93475SJohn Baldwin 	int mode;
1146f1f93475SJohn Baldwin 
11476685e259SMichael Tuexen 	if (SOLISTENING(so))
11486685e259SMichael Tuexen 		return (EINVAL);
1149f1f93475SJohn Baldwin 	inp = so->so_pcb;
1150f1f93475SJohn Baldwin 	INP_WLOCK_ASSERT(inp);
1151f1f93475SJohn Baldwin 	SOCKBUF_LOCK(&so->so_rcv);
1152f1f93475SJohn Baldwin 	tls = so->so_rcv.sb_tls_info;
1153f1f93475SJohn Baldwin 	if (tls == NULL)
1154f1f93475SJohn Baldwin 		mode = TCP_TLS_MODE_NONE;
1155f1f93475SJohn Baldwin 	else
1156f1f93475SJohn Baldwin 		mode = tls->mode;
1157f1f93475SJohn Baldwin 	SOCKBUF_UNLOCK(&so->so_rcv);
1158f1f93475SJohn Baldwin 	return (mode);
1159f1f93475SJohn Baldwin }
1160f1f93475SJohn Baldwin 
1161f1f93475SJohn Baldwin int
1162b2e60773SJohn Baldwin ktls_get_tx_mode(struct socket *so)
1163b2e60773SJohn Baldwin {
1164b2e60773SJohn Baldwin 	struct ktls_session *tls;
1165b2e60773SJohn Baldwin 	struct inpcb *inp;
1166b2e60773SJohn Baldwin 	int mode;
1167b2e60773SJohn Baldwin 
11686685e259SMichael Tuexen 	if (SOLISTENING(so))
11696685e259SMichael Tuexen 		return (EINVAL);
1170b2e60773SJohn Baldwin 	inp = so->so_pcb;
1171b2e60773SJohn Baldwin 	INP_WLOCK_ASSERT(inp);
1172b2e60773SJohn Baldwin 	SOCKBUF_LOCK(&so->so_snd);
1173b2e60773SJohn Baldwin 	tls = so->so_snd.sb_tls_info;
1174b2e60773SJohn Baldwin 	if (tls == NULL)
1175b2e60773SJohn Baldwin 		mode = TCP_TLS_MODE_NONE;
1176b2e60773SJohn Baldwin 	else
11779e14430dSJohn Baldwin 		mode = tls->mode;
1178b2e60773SJohn Baldwin 	SOCKBUF_UNLOCK(&so->so_snd);
1179b2e60773SJohn Baldwin 	return (mode);
1180b2e60773SJohn Baldwin }
1181b2e60773SJohn Baldwin 
1182b2e60773SJohn Baldwin /*
1183b2e60773SJohn Baldwin  * Switch between SW and ifnet TLS sessions as requested.
1184b2e60773SJohn Baldwin  */
1185b2e60773SJohn Baldwin int
1186b2e60773SJohn Baldwin ktls_set_tx_mode(struct socket *so, int mode)
1187b2e60773SJohn Baldwin {
1188b2e60773SJohn Baldwin 	struct ktls_session *tls, *tls_new;
1189b2e60773SJohn Baldwin 	struct inpcb *inp;
1190b2e60773SJohn Baldwin 	int error;
1191b2e60773SJohn Baldwin 
11926685e259SMichael Tuexen 	if (SOLISTENING(so))
11936685e259SMichael Tuexen 		return (EINVAL);
11949e14430dSJohn Baldwin 	switch (mode) {
11959e14430dSJohn Baldwin 	case TCP_TLS_MODE_SW:
11969e14430dSJohn Baldwin 	case TCP_TLS_MODE_IFNET:
11979e14430dSJohn Baldwin 		break;
11989e14430dSJohn Baldwin 	default:
11999e14430dSJohn Baldwin 		return (EINVAL);
12009e14430dSJohn Baldwin 	}
1201b2e60773SJohn Baldwin 
1202b2e60773SJohn Baldwin 	inp = so->so_pcb;
1203b2e60773SJohn Baldwin 	INP_WLOCK_ASSERT(inp);
1204b2e60773SJohn Baldwin 	SOCKBUF_LOCK(&so->so_snd);
1205b2e60773SJohn Baldwin 	tls = so->so_snd.sb_tls_info;
1206b2e60773SJohn Baldwin 	if (tls == NULL) {
1207b2e60773SJohn Baldwin 		SOCKBUF_UNLOCK(&so->so_snd);
1208b2e60773SJohn Baldwin 		return (0);
1209b2e60773SJohn Baldwin 	}
1210b2e60773SJohn Baldwin 
12119e14430dSJohn Baldwin 	if (tls->mode == mode) {
1212b2e60773SJohn Baldwin 		SOCKBUF_UNLOCK(&so->so_snd);
1213b2e60773SJohn Baldwin 		return (0);
1214b2e60773SJohn Baldwin 	}
1215b2e60773SJohn Baldwin 
1216b2e60773SJohn Baldwin 	tls = ktls_hold(tls);
1217b2e60773SJohn Baldwin 	SOCKBUF_UNLOCK(&so->so_snd);
1218b2e60773SJohn Baldwin 	INP_WUNLOCK(inp);
1219b2e60773SJohn Baldwin 
1220b2e60773SJohn Baldwin 	tls_new = ktls_clone_session(tls);
1221b2e60773SJohn Baldwin 
1222b2e60773SJohn Baldwin 	if (mode == TCP_TLS_MODE_IFNET)
1223b2e60773SJohn Baldwin 		error = ktls_try_ifnet(so, tls_new, true);
1224b2e60773SJohn Baldwin 	else
12253c0e5685SJohn Baldwin 		error = ktls_try_sw(so, tls_new, KTLS_TX);
1226b2e60773SJohn Baldwin 	if (error) {
1227b2e60773SJohn Baldwin 		counter_u64_add(ktls_switch_failed, 1);
1228b2e60773SJohn Baldwin 		ktls_free(tls_new);
1229b2e60773SJohn Baldwin 		ktls_free(tls);
1230b2e60773SJohn Baldwin 		INP_WLOCK(inp);
1231b2e60773SJohn Baldwin 		return (error);
1232b2e60773SJohn Baldwin 	}
1233b2e60773SJohn Baldwin 
1234b2e60773SJohn Baldwin 	error = sblock(&so->so_snd, SBL_WAIT);
1235b2e60773SJohn Baldwin 	if (error) {
1236b2e60773SJohn Baldwin 		counter_u64_add(ktls_switch_failed, 1);
1237b2e60773SJohn Baldwin 		ktls_free(tls_new);
1238b2e60773SJohn Baldwin 		ktls_free(tls);
1239b2e60773SJohn Baldwin 		INP_WLOCK(inp);
1240b2e60773SJohn Baldwin 		return (error);
1241b2e60773SJohn Baldwin 	}
1242b2e60773SJohn Baldwin 
1243b2e60773SJohn Baldwin 	/*
1244b2e60773SJohn Baldwin 	 * If we raced with another session change, keep the existing
1245b2e60773SJohn Baldwin 	 * session.
1246b2e60773SJohn Baldwin 	 */
1247b2e60773SJohn Baldwin 	if (tls != so->so_snd.sb_tls_info) {
1248b2e60773SJohn Baldwin 		counter_u64_add(ktls_switch_failed, 1);
1249b2e60773SJohn Baldwin 		sbunlock(&so->so_snd);
1250b2e60773SJohn Baldwin 		ktls_free(tls_new);
1251b2e60773SJohn Baldwin 		ktls_free(tls);
1252b2e60773SJohn Baldwin 		INP_WLOCK(inp);
1253b2e60773SJohn Baldwin 		return (EBUSY);
1254b2e60773SJohn Baldwin 	}
1255b2e60773SJohn Baldwin 
1256b2e60773SJohn Baldwin 	SOCKBUF_LOCK(&so->so_snd);
1257b2e60773SJohn Baldwin 	so->so_snd.sb_tls_info = tls_new;
12589e14430dSJohn Baldwin 	if (tls_new->mode != TCP_TLS_MODE_SW)
1259b2e60773SJohn Baldwin 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1260b2e60773SJohn Baldwin 	SOCKBUF_UNLOCK(&so->so_snd);
1261b2e60773SJohn Baldwin 	sbunlock(&so->so_snd);
1262b2e60773SJohn Baldwin 
1263b2e60773SJohn Baldwin 	/*
1264b2e60773SJohn Baldwin 	 * Drop two references on 'tls'.  The first is for the
1265b2e60773SJohn Baldwin 	 * ktls_hold() above.  The second drops the reference from the
1266b2e60773SJohn Baldwin 	 * socket buffer.
1267b2e60773SJohn Baldwin 	 */
1268b2e60773SJohn Baldwin 	KASSERT(tls->refcount >= 2, ("too few references on old session"));
1269b2e60773SJohn Baldwin 	ktls_free(tls);
1270b2e60773SJohn Baldwin 	ktls_free(tls);
1271b2e60773SJohn Baldwin 
1272b2e60773SJohn Baldwin 	if (mode == TCP_TLS_MODE_IFNET)
1273b2e60773SJohn Baldwin 		counter_u64_add(ktls_switch_to_ifnet, 1);
1274b2e60773SJohn Baldwin 	else
1275b2e60773SJohn Baldwin 		counter_u64_add(ktls_switch_to_sw, 1);
1276b2e60773SJohn Baldwin 
1277b2e60773SJohn Baldwin 	INP_WLOCK(inp);
1278b2e60773SJohn Baldwin 	return (0);
1279b2e60773SJohn Baldwin }
1280b2e60773SJohn Baldwin 
1281b2e60773SJohn Baldwin /*
1282b2e60773SJohn Baldwin  * Try to allocate a new TLS send tag.  This task is scheduled when
1283b2e60773SJohn Baldwin  * ip_output detects a route change while trying to transmit a packet
1284b2e60773SJohn Baldwin  * holding a TLS record.  If a new tag is allocated, replace the tag
1285b2e60773SJohn Baldwin  * in the TLS session.  Subsequent packets on the connection will use
1286b2e60773SJohn Baldwin  * the new tag.  If a new tag cannot be allocated, drop the
1287b2e60773SJohn Baldwin  * connection.
1288b2e60773SJohn Baldwin  */
1289b2e60773SJohn Baldwin static void
1290b2e60773SJohn Baldwin ktls_reset_send_tag(void *context, int pending)
1291b2e60773SJohn Baldwin {
1292b2e60773SJohn Baldwin 	struct epoch_tracker et;
1293b2e60773SJohn Baldwin 	struct ktls_session *tls;
1294b2e60773SJohn Baldwin 	struct m_snd_tag *old, *new;
1295b2e60773SJohn Baldwin 	struct inpcb *inp;
1296b2e60773SJohn Baldwin 	struct tcpcb *tp;
1297b2e60773SJohn Baldwin 	int error;
1298b2e60773SJohn Baldwin 
1299b2e60773SJohn Baldwin 	MPASS(pending == 1);
1300b2e60773SJohn Baldwin 
1301b2e60773SJohn Baldwin 	tls = context;
1302b2e60773SJohn Baldwin 	inp = tls->inp;
1303b2e60773SJohn Baldwin 
1304b2e60773SJohn Baldwin 	/*
1305b2e60773SJohn Baldwin 	 * Free the old tag first before allocating a new one.
1306b2e60773SJohn Baldwin 	 * ip[6]_output_send() will treat a NULL send tag the same as
1307b2e60773SJohn Baldwin 	 * an ifp mismatch and drop packets until a new tag is
1308b2e60773SJohn Baldwin 	 * allocated.
1309b2e60773SJohn Baldwin 	 *
1310b2e60773SJohn Baldwin 	 * Write-lock the INP when changing tls->snd_tag since
1311b2e60773SJohn Baldwin 	 * ip[6]_output_send() holds a read-lock when reading the
1312b2e60773SJohn Baldwin 	 * pointer.
1313b2e60773SJohn Baldwin 	 */
1314b2e60773SJohn Baldwin 	INP_WLOCK(inp);
1315b2e60773SJohn Baldwin 	old = tls->snd_tag;
1316b2e60773SJohn Baldwin 	tls->snd_tag = NULL;
1317b2e60773SJohn Baldwin 	INP_WUNLOCK(inp);
1318b2e60773SJohn Baldwin 	if (old != NULL)
1319b2e60773SJohn Baldwin 		m_snd_tag_rele(old);
1320b2e60773SJohn Baldwin 
1321b2e60773SJohn Baldwin 	error = ktls_alloc_snd_tag(inp, tls, true, &new);
1322b2e60773SJohn Baldwin 
1323b2e60773SJohn Baldwin 	if (error == 0) {
1324b2e60773SJohn Baldwin 		INP_WLOCK(inp);
1325b2e60773SJohn Baldwin 		tls->snd_tag = new;
1326b2e60773SJohn Baldwin 		mtx_pool_lock(mtxpool_sleep, tls);
1327b2e60773SJohn Baldwin 		tls->reset_pending = false;
1328b2e60773SJohn Baldwin 		mtx_pool_unlock(mtxpool_sleep, tls);
1329b2e60773SJohn Baldwin 		if (!in_pcbrele_wlocked(inp))
1330b2e60773SJohn Baldwin 			INP_WUNLOCK(inp);
1331b2e60773SJohn Baldwin 
1332b2e60773SJohn Baldwin 		counter_u64_add(ktls_ifnet_reset, 1);
1333b2e60773SJohn Baldwin 
1334b2e60773SJohn Baldwin 		/*
1335b2e60773SJohn Baldwin 		 * XXX: Should we kick tcp_output explicitly now that
1336b2e60773SJohn Baldwin 		 * the send tag is fixed or just rely on timers?
1337b2e60773SJohn Baldwin 		 */
1338b2e60773SJohn Baldwin 	} else {
13391a496125SGleb Smirnoff 		NET_EPOCH_ENTER(et);
1340b2e60773SJohn Baldwin 		INP_WLOCK(inp);
1341b2e60773SJohn Baldwin 		if (!in_pcbrele_wlocked(inp)) {
1342b2e60773SJohn Baldwin 			if (!(inp->inp_flags & INP_TIMEWAIT) &&
1343b2e60773SJohn Baldwin 			    !(inp->inp_flags & INP_DROPPED)) {
1344b2e60773SJohn Baldwin 				tp = intotcpcb(inp);
13451f69a509SHans Petter Selasky 				CURVNET_SET(tp->t_vnet);
1346b2e60773SJohn Baldwin 				tp = tcp_drop(tp, ECONNABORTED);
13471f69a509SHans Petter Selasky 				CURVNET_RESTORE();
1348b2e60773SJohn Baldwin 				if (tp != NULL)
1349b2e60773SJohn Baldwin 					INP_WUNLOCK(inp);
1350b2e60773SJohn Baldwin 				counter_u64_add(ktls_ifnet_reset_dropped, 1);
1351b2e60773SJohn Baldwin 			} else
1352b2e60773SJohn Baldwin 				INP_WUNLOCK(inp);
1353b2e60773SJohn Baldwin 		}
13541a496125SGleb Smirnoff 		NET_EPOCH_EXIT(et);
1355b2e60773SJohn Baldwin 
1356b2e60773SJohn Baldwin 		counter_u64_add(ktls_ifnet_reset_failed, 1);
1357b2e60773SJohn Baldwin 
1358b2e60773SJohn Baldwin 		/*
1359b2e60773SJohn Baldwin 		 * Leave reset_pending true to avoid future tasks while
1360b2e60773SJohn Baldwin 		 * the socket goes away.
1361b2e60773SJohn Baldwin 		 */
1362b2e60773SJohn Baldwin 	}
1363b2e60773SJohn Baldwin 
1364b2e60773SJohn Baldwin 	ktls_free(tls);
1365b2e60773SJohn Baldwin }
1366b2e60773SJohn Baldwin 
1367b2e60773SJohn Baldwin int
1368b2e60773SJohn Baldwin ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1369b2e60773SJohn Baldwin {
1370b2e60773SJohn Baldwin 
1371b2e60773SJohn Baldwin 	if (inp == NULL)
1372b2e60773SJohn Baldwin 		return (ENOBUFS);
1373b2e60773SJohn Baldwin 
1374b2e60773SJohn Baldwin 	INP_LOCK_ASSERT(inp);
1375b2e60773SJohn Baldwin 
1376b2e60773SJohn Baldwin 	/*
1377b2e60773SJohn Baldwin 	 * See if we should schedule a task to update the send tag for
1378b2e60773SJohn Baldwin 	 * this session.
1379b2e60773SJohn Baldwin 	 */
1380b2e60773SJohn Baldwin 	mtx_pool_lock(mtxpool_sleep, tls);
1381b2e60773SJohn Baldwin 	if (!tls->reset_pending) {
1382b2e60773SJohn Baldwin 		(void) ktls_hold(tls);
1383b2e60773SJohn Baldwin 		in_pcbref(inp);
1384b2e60773SJohn Baldwin 		tls->inp = inp;
1385b2e60773SJohn Baldwin 		tls->reset_pending = true;
1386b2e60773SJohn Baldwin 		taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1387b2e60773SJohn Baldwin 	}
1388b2e60773SJohn Baldwin 	mtx_pool_unlock(mtxpool_sleep, tls);
1389b2e60773SJohn Baldwin 	return (ENOBUFS);
1390b2e60773SJohn Baldwin }
1391521eac97SJohn Baldwin 
1392521eac97SJohn Baldwin #ifdef RATELIMIT
1393521eac97SJohn Baldwin int
1394521eac97SJohn Baldwin ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1395521eac97SJohn Baldwin {
1396521eac97SJohn Baldwin 	union if_snd_tag_modify_params params = {
1397521eac97SJohn Baldwin 		.rate_limit.max_rate = max_pacing_rate,
1398521eac97SJohn Baldwin 		.rate_limit.flags = M_NOWAIT,
1399521eac97SJohn Baldwin 	};
1400521eac97SJohn Baldwin 	struct m_snd_tag *mst;
1401521eac97SJohn Baldwin 	struct ifnet *ifp;
1402521eac97SJohn Baldwin 	int error;
1403521eac97SJohn Baldwin 
1404521eac97SJohn Baldwin 	/* Can't get to the inp, but it should be locked. */
1405521eac97SJohn Baldwin 	/* INP_LOCK_ASSERT(inp); */
1406521eac97SJohn Baldwin 
1407521eac97SJohn Baldwin 	MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1408521eac97SJohn Baldwin 
1409521eac97SJohn Baldwin 	if (tls->snd_tag == NULL) {
1410521eac97SJohn Baldwin 		/*
1411521eac97SJohn Baldwin 		 * Resetting send tag, ignore this change.  The
1412521eac97SJohn Baldwin 		 * pending reset may or may not see this updated rate
1413521eac97SJohn Baldwin 		 * in the tcpcb.  If it doesn't, we will just lose
1414521eac97SJohn Baldwin 		 * this rate change.
1415521eac97SJohn Baldwin 		 */
1416521eac97SJohn Baldwin 		return (0);
1417521eac97SJohn Baldwin 	}
1418521eac97SJohn Baldwin 
1419521eac97SJohn Baldwin 	MPASS(tls->snd_tag != NULL);
1420521eac97SJohn Baldwin 	MPASS(tls->snd_tag->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1421521eac97SJohn Baldwin 
1422521eac97SJohn Baldwin 	mst = tls->snd_tag;
1423521eac97SJohn Baldwin 	ifp = mst->ifp;
1424521eac97SJohn Baldwin 	return (ifp->if_snd_tag_modify(mst, &params));
1425521eac97SJohn Baldwin }
1426521eac97SJohn Baldwin #endif
1427b2e60773SJohn Baldwin #endif
1428b2e60773SJohn Baldwin 
1429b2e60773SJohn Baldwin void
1430b2e60773SJohn Baldwin ktls_destroy(struct ktls_session *tls)
1431b2e60773SJohn Baldwin {
1432b2e60773SJohn Baldwin 
1433b2e60773SJohn Baldwin 	ktls_cleanup(tls);
1434b2e60773SJohn Baldwin 	uma_zfree(ktls_session_zone, tls);
1435b2e60773SJohn Baldwin }
1436b2e60773SJohn Baldwin 
1437b2e60773SJohn Baldwin void
1438b2e60773SJohn Baldwin ktls_seq(struct sockbuf *sb, struct mbuf *m)
1439b2e60773SJohn Baldwin {
1440b2e60773SJohn Baldwin 
1441b2e60773SJohn Baldwin 	for (; m != NULL; m = m->m_next) {
14426edfd179SGleb Smirnoff 		KASSERT((m->m_flags & M_EXTPG) != 0,
1443b2e60773SJohn Baldwin 		    ("ktls_seq: mapped mbuf %p", m));
1444b2e60773SJohn Baldwin 
14457b6c99d0SGleb Smirnoff 		m->m_epg_seqno = sb->sb_tls_seqno;
1446b2e60773SJohn Baldwin 		sb->sb_tls_seqno++;
1447b2e60773SJohn Baldwin 	}
1448b2e60773SJohn Baldwin }
1449b2e60773SJohn Baldwin 
1450b2e60773SJohn Baldwin /*
1451b2e60773SJohn Baldwin  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
1452b2e60773SJohn Baldwin  * mbuf in the chain must be an unmapped mbuf.  The payload of the
1453b2e60773SJohn Baldwin  * mbuf must be populated with the payload of each TLS record.
1454b2e60773SJohn Baldwin  *
1455b2e60773SJohn Baldwin  * The record_type argument specifies the TLS record type used when
1456b2e60773SJohn Baldwin  * populating the TLS header.
1457b2e60773SJohn Baldwin  *
1458b2e60773SJohn Baldwin  * The enq_count argument on return is set to the number of pages of
1459b2e60773SJohn Baldwin  * payload data for this entire chain that need to be encrypted via SW
1460b2e60773SJohn Baldwin  * encryption.  The returned value should be passed to ktls_enqueue
1461c2a8fd6fSJohn Baldwin  * when scheduling encryption of this chain of mbufs.  To handle the
1462c2a8fd6fSJohn Baldwin  * special case of empty fragments for TLS 1.0 sessions, an empty
1463c2a8fd6fSJohn Baldwin  * fragment counts as one page.
1464b2e60773SJohn Baldwin  */
1465f85e1a80SGleb Smirnoff void
1466b2e60773SJohn Baldwin ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1467b2e60773SJohn Baldwin     uint8_t record_type)
1468b2e60773SJohn Baldwin {
1469b2e60773SJohn Baldwin 	struct tls_record_layer *tlshdr;
1470b2e60773SJohn Baldwin 	struct mbuf *m;
14717d29eb9aSJohn Baldwin 	uint64_t *noncep;
1472b2e60773SJohn Baldwin 	uint16_t tls_len;
1473b2e60773SJohn Baldwin 	int maxlen;
1474b2e60773SJohn Baldwin 
1475b2e60773SJohn Baldwin 	maxlen = tls->params.max_frame_len;
1476b2e60773SJohn Baldwin 	*enq_cnt = 0;
1477b2e60773SJohn Baldwin 	for (m = top; m != NULL; m = m->m_next) {
1478b2e60773SJohn Baldwin 		/*
1479c2a8fd6fSJohn Baldwin 		 * All mbufs in the chain should be TLS records whose
1480c2a8fd6fSJohn Baldwin 		 * payload does not exceed the maximum frame length.
1481c2a8fd6fSJohn Baldwin 		 *
1482c2a8fd6fSJohn Baldwin 		 * Empty TLS records are permitted when using CBC.
1483b2e60773SJohn Baldwin 		 */
1484c2a8fd6fSJohn Baldwin 		KASSERT(m->m_len <= maxlen &&
1485c2a8fd6fSJohn Baldwin 		    (tls->params.cipher_algorithm == CRYPTO_AES_CBC ?
1486c2a8fd6fSJohn Baldwin 		    m->m_len >= 0 : m->m_len > 0),
1487f85e1a80SGleb Smirnoff 		    ("ktls_frame: m %p len %d\n", m, m->m_len));
1488c2a8fd6fSJohn Baldwin 
1489b2e60773SJohn Baldwin 		/*
1490b2e60773SJohn Baldwin 		 * TLS frames require unmapped mbufs to store session
1491b2e60773SJohn Baldwin 		 * info.
1492b2e60773SJohn Baldwin 		 */
14936edfd179SGleb Smirnoff 		KASSERT((m->m_flags & M_EXTPG) != 0,
1494b2e60773SJohn Baldwin 		    ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1495b2e60773SJohn Baldwin 
1496f85e1a80SGleb Smirnoff 		tls_len = m->m_len;
1497b2e60773SJohn Baldwin 
1498b2e60773SJohn Baldwin 		/* Save a reference to the session. */
14997b6c99d0SGleb Smirnoff 		m->m_epg_tls = ktls_hold(tls);
1500b2e60773SJohn Baldwin 
15017b6c99d0SGleb Smirnoff 		m->m_epg_hdrlen = tls->params.tls_hlen;
15027b6c99d0SGleb Smirnoff 		m->m_epg_trllen = tls->params.tls_tlen;
1503b2e60773SJohn Baldwin 		if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1504b2e60773SJohn Baldwin 			int bs, delta;
1505b2e60773SJohn Baldwin 
1506b2e60773SJohn Baldwin 			/*
1507b2e60773SJohn Baldwin 			 * AES-CBC pads messages to a multiple of the
1508b2e60773SJohn Baldwin 			 * block size.  Note that the padding is
1509b2e60773SJohn Baldwin 			 * applied after the digest and the encryption
1510b2e60773SJohn Baldwin 			 * is done on the "plaintext || mac || padding".
1511b2e60773SJohn Baldwin 			 * At least one byte of padding is always
1512b2e60773SJohn Baldwin 			 * present.
1513b2e60773SJohn Baldwin 			 *
1514b2e60773SJohn Baldwin 			 * Compute the final trailer length assuming
1515b2e60773SJohn Baldwin 			 * at most one block of padding.
151621e3c1fbSJohn Baldwin 			 * tls->params.tls_tlen is the maximum
1517b2e60773SJohn Baldwin 			 * possible trailer length (padding + digest).
1518b2e60773SJohn Baldwin 			 * delta holds the number of excess padding
1519b2e60773SJohn Baldwin 			 * bytes if the maximum were used.  Those
1520b2e60773SJohn Baldwin 			 * extra bytes are removed.
1521b2e60773SJohn Baldwin 			 */
1522b2e60773SJohn Baldwin 			bs = tls->params.tls_bs;
1523b2e60773SJohn Baldwin 			delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
15247b6c99d0SGleb Smirnoff 			m->m_epg_trllen -= delta;
1525b2e60773SJohn Baldwin 		}
15267b6c99d0SGleb Smirnoff 		m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1527b2e60773SJohn Baldwin 
1528b2e60773SJohn Baldwin 		/* Populate the TLS header. */
15290c103266SGleb Smirnoff 		tlshdr = (void *)m->m_epg_hdr;
1530b2e60773SJohn Baldwin 		tlshdr->tls_vmajor = tls->params.tls_vmajor;
15316554362cSAndrew Gallatin 
15326554362cSAndrew Gallatin 		/*
15336554362cSAndrew Gallatin 		 * TLS 1.3 masquarades as TLS 1.2 with a record type
15346554362cSAndrew Gallatin 		 * of TLS_RLTYPE_APP.
15356554362cSAndrew Gallatin 		 */
15366554362cSAndrew Gallatin 		if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
15376554362cSAndrew Gallatin 		    tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
15386554362cSAndrew Gallatin 			tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
15396554362cSAndrew Gallatin 			tlshdr->tls_type = TLS_RLTYPE_APP;
15406554362cSAndrew Gallatin 			/* save the real record type for later */
15417b6c99d0SGleb Smirnoff 			m->m_epg_record_type = record_type;
15420c103266SGleb Smirnoff 			m->m_epg_trail[0] = record_type;
15436554362cSAndrew Gallatin 		} else {
1544b2e60773SJohn Baldwin 			tlshdr->tls_vminor = tls->params.tls_vminor;
1545b2e60773SJohn Baldwin 			tlshdr->tls_type = record_type;
15466554362cSAndrew Gallatin 		}
1547b2e60773SJohn Baldwin 		tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1548b2e60773SJohn Baldwin 
1549b2e60773SJohn Baldwin 		/*
15507d29eb9aSJohn Baldwin 		 * Store nonces / explicit IVs after the end of the
15517d29eb9aSJohn Baldwin 		 * TLS header.
15527d29eb9aSJohn Baldwin 		 *
15537d29eb9aSJohn Baldwin 		 * For GCM with TLS 1.2, an 8 byte nonce is copied
15547d29eb9aSJohn Baldwin 		 * from the end of the IV.  The nonce is then
15557d29eb9aSJohn Baldwin 		 * incremented for use by the next record.
15567d29eb9aSJohn Baldwin 		 *
15577d29eb9aSJohn Baldwin 		 * For CBC, a random nonce is inserted for TLS 1.1+.
1558b2e60773SJohn Baldwin 		 */
15597d29eb9aSJohn Baldwin 		if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
15607d29eb9aSJohn Baldwin 		    tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
15617d29eb9aSJohn Baldwin 			noncep = (uint64_t *)(tls->params.iv + 8);
15627d29eb9aSJohn Baldwin 			be64enc(tlshdr + 1, *noncep);
15637d29eb9aSJohn Baldwin 			(*noncep)++;
15647d29eb9aSJohn Baldwin 		} else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1565b2e60773SJohn Baldwin 		    tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1566b2e60773SJohn Baldwin 			arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1567b2e60773SJohn Baldwin 
1568b2e60773SJohn Baldwin 		/*
1569b2e60773SJohn Baldwin 		 * When using SW encryption, mark the mbuf not ready.
1570b2e60773SJohn Baldwin 		 * It will be marked ready via sbready() after the
1571b2e60773SJohn Baldwin 		 * record has been encrypted.
1572b2e60773SJohn Baldwin 		 *
1573b2e60773SJohn Baldwin 		 * When using ifnet TLS, unencrypted TLS records are
1574b2e60773SJohn Baldwin 		 * sent down the stack to the NIC.
1575b2e60773SJohn Baldwin 		 */
15769e14430dSJohn Baldwin 		if (tls->mode == TCP_TLS_MODE_SW) {
1577b2e60773SJohn Baldwin 			m->m_flags |= M_NOTREADY;
15787b6c99d0SGleb Smirnoff 			m->m_epg_nrdy = m->m_epg_npgs;
1579c2a8fd6fSJohn Baldwin 			if (__predict_false(tls_len == 0)) {
1580c2a8fd6fSJohn Baldwin 				/* TLS 1.0 empty fragment. */
1581c2a8fd6fSJohn Baldwin 				*enq_cnt += 1;
1582c2a8fd6fSJohn Baldwin 			} else
15837b6c99d0SGleb Smirnoff 				*enq_cnt += m->m_epg_npgs;
1584b2e60773SJohn Baldwin 		}
1585b2e60773SJohn Baldwin 	}
1586b2e60773SJohn Baldwin }
1587b2e60773SJohn Baldwin 
1588b2e60773SJohn Baldwin void
15893c0e5685SJohn Baldwin ktls_check_rx(struct sockbuf *sb)
15903c0e5685SJohn Baldwin {
15913c0e5685SJohn Baldwin 	struct tls_record_layer hdr;
15923c0e5685SJohn Baldwin 	struct ktls_wq *wq;
15933c0e5685SJohn Baldwin 	struct socket *so;
15943c0e5685SJohn Baldwin 	bool running;
15953c0e5685SJohn Baldwin 
15963c0e5685SJohn Baldwin 	SOCKBUF_LOCK_ASSERT(sb);
15973c0e5685SJohn Baldwin 	KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
15983c0e5685SJohn Baldwin 	    __func__, sb));
15993c0e5685SJohn Baldwin 	so = __containerof(sb, struct socket, so_rcv);
16003c0e5685SJohn Baldwin 
16013c0e5685SJohn Baldwin 	if (sb->sb_flags & SB_TLS_RX_RUNNING)
16023c0e5685SJohn Baldwin 		return;
16033c0e5685SJohn Baldwin 
16043c0e5685SJohn Baldwin 	/* Is there enough queued for a TLS header? */
16053c0e5685SJohn Baldwin 	if (sb->sb_tlscc < sizeof(hdr)) {
16063c0e5685SJohn Baldwin 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
16073c0e5685SJohn Baldwin 			so->so_error = EMSGSIZE;
16083c0e5685SJohn Baldwin 		return;
16093c0e5685SJohn Baldwin 	}
16103c0e5685SJohn Baldwin 
16113c0e5685SJohn Baldwin 	m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
16123c0e5685SJohn Baldwin 
16133c0e5685SJohn Baldwin 	/* Is the entire record queued? */
16143c0e5685SJohn Baldwin 	if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
16153c0e5685SJohn Baldwin 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
16163c0e5685SJohn Baldwin 			so->so_error = EMSGSIZE;
16173c0e5685SJohn Baldwin 		return;
16183c0e5685SJohn Baldwin 	}
16193c0e5685SJohn Baldwin 
16203c0e5685SJohn Baldwin 	sb->sb_flags |= SB_TLS_RX_RUNNING;
16213c0e5685SJohn Baldwin 
16223c0e5685SJohn Baldwin 	soref(so);
16233c0e5685SJohn Baldwin 	wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
16243c0e5685SJohn Baldwin 	mtx_lock(&wq->mtx);
16253c0e5685SJohn Baldwin 	STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
16263c0e5685SJohn Baldwin 	running = wq->running;
16273c0e5685SJohn Baldwin 	mtx_unlock(&wq->mtx);
16283c0e5685SJohn Baldwin 	if (!running)
16293c0e5685SJohn Baldwin 		wakeup(wq);
16303c0e5685SJohn Baldwin 	counter_u64_add(ktls_cnt_rx_queued, 1);
16313c0e5685SJohn Baldwin }
16323c0e5685SJohn Baldwin 
16333c0e5685SJohn Baldwin static struct mbuf *
16343c0e5685SJohn Baldwin ktls_detach_record(struct sockbuf *sb, int len)
16353c0e5685SJohn Baldwin {
16363c0e5685SJohn Baldwin 	struct mbuf *m, *n, *top;
16373c0e5685SJohn Baldwin 	int remain;
16383c0e5685SJohn Baldwin 
16393c0e5685SJohn Baldwin 	SOCKBUF_LOCK_ASSERT(sb);
16403c0e5685SJohn Baldwin 	MPASS(len <= sb->sb_tlscc);
16413c0e5685SJohn Baldwin 
16423c0e5685SJohn Baldwin 	/*
16433c0e5685SJohn Baldwin 	 * If TLS chain is the exact size of the record,
16443c0e5685SJohn Baldwin 	 * just grab the whole record.
16453c0e5685SJohn Baldwin 	 */
16463c0e5685SJohn Baldwin 	top = sb->sb_mtls;
16473c0e5685SJohn Baldwin 	if (sb->sb_tlscc == len) {
16483c0e5685SJohn Baldwin 		sb->sb_mtls = NULL;
16493c0e5685SJohn Baldwin 		sb->sb_mtlstail = NULL;
16503c0e5685SJohn Baldwin 		goto out;
16513c0e5685SJohn Baldwin 	}
16523c0e5685SJohn Baldwin 
16533c0e5685SJohn Baldwin 	/*
16543c0e5685SJohn Baldwin 	 * While it would be nice to use m_split() here, we need
16553c0e5685SJohn Baldwin 	 * to know exactly what m_split() allocates to update the
16563c0e5685SJohn Baldwin 	 * accounting, so do it inline instead.
16573c0e5685SJohn Baldwin 	 */
16583c0e5685SJohn Baldwin 	remain = len;
16593c0e5685SJohn Baldwin 	for (m = top; remain > m->m_len; m = m->m_next)
16603c0e5685SJohn Baldwin 		remain -= m->m_len;
16613c0e5685SJohn Baldwin 
16623c0e5685SJohn Baldwin 	/* Easy case: don't have to split 'm'. */
16633c0e5685SJohn Baldwin 	if (remain == m->m_len) {
16643c0e5685SJohn Baldwin 		sb->sb_mtls = m->m_next;
16653c0e5685SJohn Baldwin 		if (sb->sb_mtls == NULL)
16663c0e5685SJohn Baldwin 			sb->sb_mtlstail = NULL;
16673c0e5685SJohn Baldwin 		m->m_next = NULL;
16683c0e5685SJohn Baldwin 		goto out;
16693c0e5685SJohn Baldwin 	}
16703c0e5685SJohn Baldwin 
16713c0e5685SJohn Baldwin 	/*
16723c0e5685SJohn Baldwin 	 * Need to allocate an mbuf to hold the remainder of 'm'.  Try
16733c0e5685SJohn Baldwin 	 * with M_NOWAIT first.
16743c0e5685SJohn Baldwin 	 */
16753c0e5685SJohn Baldwin 	n = m_get(M_NOWAIT, MT_DATA);
16763c0e5685SJohn Baldwin 	if (n == NULL) {
16773c0e5685SJohn Baldwin 		/*
16783c0e5685SJohn Baldwin 		 * Use M_WAITOK with socket buffer unlocked.  If
16793c0e5685SJohn Baldwin 		 * 'sb_mtls' changes while the lock is dropped, return
16803c0e5685SJohn Baldwin 		 * NULL to force the caller to retry.
16813c0e5685SJohn Baldwin 		 */
16823c0e5685SJohn Baldwin 		SOCKBUF_UNLOCK(sb);
16833c0e5685SJohn Baldwin 
16843c0e5685SJohn Baldwin 		n = m_get(M_WAITOK, MT_DATA);
16853c0e5685SJohn Baldwin 
16863c0e5685SJohn Baldwin 		SOCKBUF_LOCK(sb);
16873c0e5685SJohn Baldwin 		if (sb->sb_mtls != top) {
16883c0e5685SJohn Baldwin 			m_free(n);
16893c0e5685SJohn Baldwin 			return (NULL);
16903c0e5685SJohn Baldwin 		}
16913c0e5685SJohn Baldwin 	}
16923c0e5685SJohn Baldwin 	n->m_flags |= M_NOTREADY;
16933c0e5685SJohn Baldwin 
16943c0e5685SJohn Baldwin 	/* Store remainder in 'n'. */
16953c0e5685SJohn Baldwin 	n->m_len = m->m_len - remain;
16963c0e5685SJohn Baldwin 	if (m->m_flags & M_EXT) {
16973c0e5685SJohn Baldwin 		n->m_data = m->m_data + remain;
16983c0e5685SJohn Baldwin 		mb_dupcl(n, m);
16993c0e5685SJohn Baldwin 	} else {
17003c0e5685SJohn Baldwin 		bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
17013c0e5685SJohn Baldwin 	}
17023c0e5685SJohn Baldwin 
17033c0e5685SJohn Baldwin 	/* Trim 'm' and update accounting. */
17043c0e5685SJohn Baldwin 	m->m_len -= n->m_len;
17053c0e5685SJohn Baldwin 	sb->sb_tlscc -= n->m_len;
17063c0e5685SJohn Baldwin 	sb->sb_ccc -= n->m_len;
17073c0e5685SJohn Baldwin 
17083c0e5685SJohn Baldwin 	/* Account for 'n'. */
17093c0e5685SJohn Baldwin 	sballoc_ktls_rx(sb, n);
17103c0e5685SJohn Baldwin 
17113c0e5685SJohn Baldwin 	/* Insert 'n' into the TLS chain. */
17123c0e5685SJohn Baldwin 	sb->sb_mtls = n;
17133c0e5685SJohn Baldwin 	n->m_next = m->m_next;
17143c0e5685SJohn Baldwin 	if (sb->sb_mtlstail == m)
17153c0e5685SJohn Baldwin 		sb->sb_mtlstail = n;
17163c0e5685SJohn Baldwin 
17173c0e5685SJohn Baldwin 	/* Detach the record from the TLS chain. */
17183c0e5685SJohn Baldwin 	m->m_next = NULL;
17193c0e5685SJohn Baldwin 
17203c0e5685SJohn Baldwin out:
17213c0e5685SJohn Baldwin 	MPASS(m_length(top, NULL) == len);
17223c0e5685SJohn Baldwin 	for (m = top; m != NULL; m = m->m_next)
17233c0e5685SJohn Baldwin 		sbfree_ktls_rx(sb, m);
17243c0e5685SJohn Baldwin 	sb->sb_tlsdcc = len;
17253c0e5685SJohn Baldwin 	sb->sb_ccc += len;
17263c0e5685SJohn Baldwin 	SBCHECK(sb);
17273c0e5685SJohn Baldwin 	return (top);
17283c0e5685SJohn Baldwin }
17293c0e5685SJohn Baldwin 
17303c0e5685SJohn Baldwin static void
17313c0e5685SJohn Baldwin ktls_decrypt(struct socket *so)
17323c0e5685SJohn Baldwin {
17333c0e5685SJohn Baldwin 	char tls_header[MBUF_PEXT_HDR_LEN];
17343c0e5685SJohn Baldwin 	struct ktls_session *tls;
17353c0e5685SJohn Baldwin 	struct sockbuf *sb;
17363c0e5685SJohn Baldwin 	struct tls_record_layer *hdr;
17373c0e5685SJohn Baldwin 	struct tls_get_record tgr;
17383c0e5685SJohn Baldwin 	struct mbuf *control, *data, *m;
17393c0e5685SJohn Baldwin 	uint64_t seqno;
17403c0e5685SJohn Baldwin 	int error, remain, tls_len, trail_len;
17413c0e5685SJohn Baldwin 
17423c0e5685SJohn Baldwin 	hdr = (struct tls_record_layer *)tls_header;
17433c0e5685SJohn Baldwin 	sb = &so->so_rcv;
17443c0e5685SJohn Baldwin 	SOCKBUF_LOCK(sb);
17453c0e5685SJohn Baldwin 	KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
17463c0e5685SJohn Baldwin 	    ("%s: socket %p not running", __func__, so));
17473c0e5685SJohn Baldwin 
17483c0e5685SJohn Baldwin 	tls = sb->sb_tls_info;
17493c0e5685SJohn Baldwin 	MPASS(tls != NULL);
17503c0e5685SJohn Baldwin 
17513c0e5685SJohn Baldwin 	for (;;) {
17523c0e5685SJohn Baldwin 		/* Is there enough queued for a TLS header? */
17533c0e5685SJohn Baldwin 		if (sb->sb_tlscc < tls->params.tls_hlen)
17543c0e5685SJohn Baldwin 			break;
17553c0e5685SJohn Baldwin 
17563c0e5685SJohn Baldwin 		m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
17573c0e5685SJohn Baldwin 		tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
17583c0e5685SJohn Baldwin 
17593c0e5685SJohn Baldwin 		if (hdr->tls_vmajor != tls->params.tls_vmajor ||
17603c0e5685SJohn Baldwin 		    hdr->tls_vminor != tls->params.tls_vminor)
17613c0e5685SJohn Baldwin 			error = EINVAL;
17623c0e5685SJohn Baldwin 		else if (tls_len < tls->params.tls_hlen || tls_len >
17633c0e5685SJohn Baldwin 		    tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
17643c0e5685SJohn Baldwin 		    tls->params.tls_tlen)
17653c0e5685SJohn Baldwin 			error = EMSGSIZE;
17663c0e5685SJohn Baldwin 		else
17673c0e5685SJohn Baldwin 			error = 0;
17683c0e5685SJohn Baldwin 		if (__predict_false(error != 0)) {
17693c0e5685SJohn Baldwin 			/*
17703c0e5685SJohn Baldwin 			 * We have a corrupted record and are likely
17713c0e5685SJohn Baldwin 			 * out of sync.  The connection isn't
17723c0e5685SJohn Baldwin 			 * recoverable at this point, so abort it.
17733c0e5685SJohn Baldwin 			 */
17743c0e5685SJohn Baldwin 			SOCKBUF_UNLOCK(sb);
17753c0e5685SJohn Baldwin 			counter_u64_add(ktls_offload_corrupted_records, 1);
17763c0e5685SJohn Baldwin 
17773c0e5685SJohn Baldwin 			CURVNET_SET(so->so_vnet);
17783c0e5685SJohn Baldwin 			so->so_proto->pr_usrreqs->pru_abort(so);
17793c0e5685SJohn Baldwin 			so->so_error = error;
17803c0e5685SJohn Baldwin 			CURVNET_RESTORE();
17813c0e5685SJohn Baldwin 			goto deref;
17823c0e5685SJohn Baldwin 		}
17833c0e5685SJohn Baldwin 
17843c0e5685SJohn Baldwin 		/* Is the entire record queued? */
17853c0e5685SJohn Baldwin 		if (sb->sb_tlscc < tls_len)
17863c0e5685SJohn Baldwin 			break;
17873c0e5685SJohn Baldwin 
17883c0e5685SJohn Baldwin 		/*
17893c0e5685SJohn Baldwin 		 * Split out the portion of the mbuf chain containing
17903c0e5685SJohn Baldwin 		 * this TLS record.
17913c0e5685SJohn Baldwin 		 */
17923c0e5685SJohn Baldwin 		data = ktls_detach_record(sb, tls_len);
17933c0e5685SJohn Baldwin 		if (data == NULL)
17943c0e5685SJohn Baldwin 			continue;
17953c0e5685SJohn Baldwin 		MPASS(sb->sb_tlsdcc == tls_len);
17963c0e5685SJohn Baldwin 
17973c0e5685SJohn Baldwin 		seqno = sb->sb_tls_seqno;
17983c0e5685SJohn Baldwin 		sb->sb_tls_seqno++;
17993c0e5685SJohn Baldwin 		SBCHECK(sb);
18003c0e5685SJohn Baldwin 		SOCKBUF_UNLOCK(sb);
18013c0e5685SJohn Baldwin 
18023c0e5685SJohn Baldwin 		error = tls->sw_decrypt(tls, hdr, data, seqno, &trail_len);
18033c0e5685SJohn Baldwin 		if (error) {
18043c0e5685SJohn Baldwin 			counter_u64_add(ktls_offload_failed_crypto, 1);
18053c0e5685SJohn Baldwin 
18063c0e5685SJohn Baldwin 			SOCKBUF_LOCK(sb);
18073c0e5685SJohn Baldwin 			if (sb->sb_tlsdcc == 0) {
18083c0e5685SJohn Baldwin 				/*
18093c0e5685SJohn Baldwin 				 * sbcut/drop/flush discarded these
18103c0e5685SJohn Baldwin 				 * mbufs.
18113c0e5685SJohn Baldwin 				 */
18123c0e5685SJohn Baldwin 				m_freem(data);
18133c0e5685SJohn Baldwin 				break;
18143c0e5685SJohn Baldwin 			}
18153c0e5685SJohn Baldwin 
18163c0e5685SJohn Baldwin 			/*
18173c0e5685SJohn Baldwin 			 * Drop this TLS record's data, but keep
18183c0e5685SJohn Baldwin 			 * decrypting subsequent records.
18193c0e5685SJohn Baldwin 			 */
18203c0e5685SJohn Baldwin 			sb->sb_ccc -= tls_len;
18213c0e5685SJohn Baldwin 			sb->sb_tlsdcc = 0;
18223c0e5685SJohn Baldwin 
18233c0e5685SJohn Baldwin 			CURVNET_SET(so->so_vnet);
18243c0e5685SJohn Baldwin 			so->so_error = EBADMSG;
18253c0e5685SJohn Baldwin 			sorwakeup_locked(so);
18263c0e5685SJohn Baldwin 			CURVNET_RESTORE();
18273c0e5685SJohn Baldwin 
18283c0e5685SJohn Baldwin 			m_freem(data);
18293c0e5685SJohn Baldwin 
18303c0e5685SJohn Baldwin 			SOCKBUF_LOCK(sb);
18313c0e5685SJohn Baldwin 			continue;
18323c0e5685SJohn Baldwin 		}
18333c0e5685SJohn Baldwin 
18343c0e5685SJohn Baldwin 		/* Allocate the control mbuf. */
18353c0e5685SJohn Baldwin 		tgr.tls_type = hdr->tls_type;
18363c0e5685SJohn Baldwin 		tgr.tls_vmajor = hdr->tls_vmajor;
18373c0e5685SJohn Baldwin 		tgr.tls_vminor = hdr->tls_vminor;
18383c0e5685SJohn Baldwin 		tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
18393c0e5685SJohn Baldwin 		    trail_len);
18403c0e5685SJohn Baldwin 		control = sbcreatecontrol_how(&tgr, sizeof(tgr),
18413c0e5685SJohn Baldwin 		    TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
18423c0e5685SJohn Baldwin 
18433c0e5685SJohn Baldwin 		SOCKBUF_LOCK(sb);
18443c0e5685SJohn Baldwin 		if (sb->sb_tlsdcc == 0) {
18453c0e5685SJohn Baldwin 			/* sbcut/drop/flush discarded these mbufs. */
18463c0e5685SJohn Baldwin 			MPASS(sb->sb_tlscc == 0);
18473c0e5685SJohn Baldwin 			m_freem(data);
18483c0e5685SJohn Baldwin 			m_freem(control);
18493c0e5685SJohn Baldwin 			break;
18503c0e5685SJohn Baldwin 		}
18513c0e5685SJohn Baldwin 
18523c0e5685SJohn Baldwin 		/*
18533c0e5685SJohn Baldwin 		 * Clear the 'dcc' accounting in preparation for
18543c0e5685SJohn Baldwin 		 * adding the decrypted record.
18553c0e5685SJohn Baldwin 		 */
18563c0e5685SJohn Baldwin 		sb->sb_ccc -= tls_len;
18573c0e5685SJohn Baldwin 		sb->sb_tlsdcc = 0;
18583c0e5685SJohn Baldwin 		SBCHECK(sb);
18593c0e5685SJohn Baldwin 
18603c0e5685SJohn Baldwin 		/* If there is no payload, drop all of the data. */
18613c0e5685SJohn Baldwin 		if (tgr.tls_length == htobe16(0)) {
18623c0e5685SJohn Baldwin 			m_freem(data);
18633c0e5685SJohn Baldwin 			data = NULL;
18643c0e5685SJohn Baldwin 		} else {
18653c0e5685SJohn Baldwin 			/* Trim header. */
18663c0e5685SJohn Baldwin 			remain = tls->params.tls_hlen;
18673c0e5685SJohn Baldwin 			while (remain > 0) {
18683c0e5685SJohn Baldwin 				if (data->m_len > remain) {
18693c0e5685SJohn Baldwin 					data->m_data += remain;
18703c0e5685SJohn Baldwin 					data->m_len -= remain;
18713c0e5685SJohn Baldwin 					break;
18723c0e5685SJohn Baldwin 				}
18733c0e5685SJohn Baldwin 				remain -= data->m_len;
18743c0e5685SJohn Baldwin 				data = m_free(data);
18753c0e5685SJohn Baldwin 			}
18763c0e5685SJohn Baldwin 
18773c0e5685SJohn Baldwin 			/* Trim trailer and clear M_NOTREADY. */
18783c0e5685SJohn Baldwin 			remain = be16toh(tgr.tls_length);
18793c0e5685SJohn Baldwin 			m = data;
18803c0e5685SJohn Baldwin 			for (m = data; remain > m->m_len; m = m->m_next) {
18813c0e5685SJohn Baldwin 				m->m_flags &= ~M_NOTREADY;
18823c0e5685SJohn Baldwin 				remain -= m->m_len;
18833c0e5685SJohn Baldwin 			}
18843c0e5685SJohn Baldwin 			m->m_len = remain;
18853c0e5685SJohn Baldwin 			m_freem(m->m_next);
18863c0e5685SJohn Baldwin 			m->m_next = NULL;
18873c0e5685SJohn Baldwin 			m->m_flags &= ~M_NOTREADY;
18883c0e5685SJohn Baldwin 
18893c0e5685SJohn Baldwin 			/* Set EOR on the final mbuf. */
18903c0e5685SJohn Baldwin 			m->m_flags |= M_EOR;
18913c0e5685SJohn Baldwin 		}
18923c0e5685SJohn Baldwin 
18933c0e5685SJohn Baldwin 		sbappendcontrol_locked(sb, data, control, 0);
18943c0e5685SJohn Baldwin 	}
18953c0e5685SJohn Baldwin 
18963c0e5685SJohn Baldwin 	sb->sb_flags &= ~SB_TLS_RX_RUNNING;
18973c0e5685SJohn Baldwin 
18983c0e5685SJohn Baldwin 	if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
18993c0e5685SJohn Baldwin 		so->so_error = EMSGSIZE;
19003c0e5685SJohn Baldwin 
19013c0e5685SJohn Baldwin 	sorwakeup_locked(so);
19023c0e5685SJohn Baldwin 
19033c0e5685SJohn Baldwin deref:
19043c0e5685SJohn Baldwin 	SOCKBUF_UNLOCK_ASSERT(sb);
19053c0e5685SJohn Baldwin 
19063c0e5685SJohn Baldwin 	CURVNET_SET(so->so_vnet);
19073c0e5685SJohn Baldwin 	SOCK_LOCK(so);
19083c0e5685SJohn Baldwin 	sorele(so);
19093c0e5685SJohn Baldwin 	CURVNET_RESTORE();
19103c0e5685SJohn Baldwin }
19113c0e5685SJohn Baldwin 
19123c0e5685SJohn Baldwin void
1913d90fe9d0SGleb Smirnoff ktls_enqueue_to_free(struct mbuf *m)
1914b2e60773SJohn Baldwin {
1915b2e60773SJohn Baldwin 	struct ktls_wq *wq;
1916b2e60773SJohn Baldwin 	bool running;
1917b2e60773SJohn Baldwin 
1918b2e60773SJohn Baldwin 	/* Mark it for freeing. */
19197b6c99d0SGleb Smirnoff 	m->m_epg_flags |= EPG_FLAG_2FREE;
19207b6c99d0SGleb Smirnoff 	wq = &ktls_wq[m->m_epg_tls->wq_index];
1921b2e60773SJohn Baldwin 	mtx_lock(&wq->mtx);
19223c0e5685SJohn Baldwin 	STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1923b2e60773SJohn Baldwin 	running = wq->running;
1924b2e60773SJohn Baldwin 	mtx_unlock(&wq->mtx);
1925b2e60773SJohn Baldwin 	if (!running)
1926b2e60773SJohn Baldwin 		wakeup(wq);
1927b2e60773SJohn Baldwin }
1928b2e60773SJohn Baldwin 
192949f6925cSMark Johnston static void *
193049f6925cSMark Johnston ktls_buffer_alloc(struct ktls_wq *wq, struct mbuf *m)
193149f6925cSMark Johnston {
193249f6925cSMark Johnston 	void *buf;
193349f6925cSMark Johnston 
193449f6925cSMark Johnston 	if (m->m_epg_npgs <= 2)
193549f6925cSMark Johnston 		return (NULL);
193649f6925cSMark Johnston 	if (ktls_buffer_zone == NULL)
193749f6925cSMark Johnston 		return (NULL);
193849f6925cSMark Johnston 	if ((u_int)(ticks - wq->lastallocfail) < hz) {
193949f6925cSMark Johnston 		/*
194049f6925cSMark Johnston 		 * Rate-limit allocation attempts after a failure.
194149f6925cSMark Johnston 		 * ktls_buffer_import() will acquire a per-domain mutex to check
194249f6925cSMark Johnston 		 * the free page queues and may fail consistently if memory is
194349f6925cSMark Johnston 		 * fragmented.
194449f6925cSMark Johnston 		 */
194549f6925cSMark Johnston 		return (NULL);
194649f6925cSMark Johnston 	}
194749f6925cSMark Johnston 	buf = uma_zalloc(ktls_buffer_zone, M_NOWAIT | M_NORECLAIM);
194849f6925cSMark Johnston 	if (buf == NULL)
194949f6925cSMark Johnston 		wq->lastallocfail = ticks;
195049f6925cSMark Johnston 	return (buf);
195149f6925cSMark Johnston }
195249f6925cSMark Johnston 
1953b2e60773SJohn Baldwin void
1954b2e60773SJohn Baldwin ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1955b2e60773SJohn Baldwin {
1956b2e60773SJohn Baldwin 	struct ktls_wq *wq;
1957b2e60773SJohn Baldwin 	bool running;
1958b2e60773SJohn Baldwin 
19596edfd179SGleb Smirnoff 	KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
19606edfd179SGleb Smirnoff 	    (M_EXTPG | M_NOTREADY)),
1961b2e60773SJohn Baldwin 	    ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
1962b2e60773SJohn Baldwin 	KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
1963b2e60773SJohn Baldwin 
19647b6c99d0SGleb Smirnoff 	KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1965b2e60773SJohn Baldwin 
19667b6c99d0SGleb Smirnoff 	m->m_epg_enc_cnt = page_count;
1967b2e60773SJohn Baldwin 
1968b2e60773SJohn Baldwin 	/*
1969b2e60773SJohn Baldwin 	 * Save a pointer to the socket.  The caller is responsible
1970b2e60773SJohn Baldwin 	 * for taking an additional reference via soref().
1971b2e60773SJohn Baldwin 	 */
19727b6c99d0SGleb Smirnoff 	m->m_epg_so = so;
1973b2e60773SJohn Baldwin 
19747b6c99d0SGleb Smirnoff 	wq = &ktls_wq[m->m_epg_tls->wq_index];
1975b2e60773SJohn Baldwin 	mtx_lock(&wq->mtx);
19763c0e5685SJohn Baldwin 	STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1977b2e60773SJohn Baldwin 	running = wq->running;
1978b2e60773SJohn Baldwin 	mtx_unlock(&wq->mtx);
1979b2e60773SJohn Baldwin 	if (!running)
1980b2e60773SJohn Baldwin 		wakeup(wq);
19813c0e5685SJohn Baldwin 	counter_u64_add(ktls_cnt_tx_queued, 1);
1982b2e60773SJohn Baldwin }
1983b2e60773SJohn Baldwin 
1984*6b313a3aSJohn Baldwin #define	MAX_TLS_PAGES	(1 + btoc(TLS_MAX_MSG_SIZE_V10_2))
1985*6b313a3aSJohn Baldwin 
1986b2e60773SJohn Baldwin static __noinline void
198749f6925cSMark Johnston ktls_encrypt(struct ktls_wq *wq, struct mbuf *top)
1988b2e60773SJohn Baldwin {
1989b2e60773SJohn Baldwin 	struct ktls_session *tls;
1990b2e60773SJohn Baldwin 	struct socket *so;
1991d90fe9d0SGleb Smirnoff 	struct mbuf *m;
1992*6b313a3aSJohn Baldwin 	vm_paddr_t parray[MAX_TLS_PAGES + 1];
1993*6b313a3aSJohn Baldwin 	struct iovec dst_iov[MAX_TLS_PAGES + 2];
1994b2e60773SJohn Baldwin 	vm_page_t pg;
199549f6925cSMark Johnston 	void *cbuf;
1996b2e60773SJohn Baldwin 	int error, i, len, npages, off, total_pages;
1997b2e60773SJohn Baldwin 
19987b6c99d0SGleb Smirnoff 	so = top->m_epg_so;
19997b6c99d0SGleb Smirnoff 	tls = top->m_epg_tls;
2000d90fe9d0SGleb Smirnoff 	KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
2001d90fe9d0SGleb Smirnoff 	KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
2002b2e60773SJohn Baldwin #ifdef INVARIANTS
20037b6c99d0SGleb Smirnoff 	top->m_epg_so = NULL;
2004b2e60773SJohn Baldwin #endif
20057b6c99d0SGleb Smirnoff 	total_pages = top->m_epg_enc_cnt;
2006b2e60773SJohn Baldwin 	npages = 0;
2007b2e60773SJohn Baldwin 
2008b2e60773SJohn Baldwin 	/*
2009b2e60773SJohn Baldwin 	 * Encrypt the TLS records in the chain of mbufs starting with
2010b2e60773SJohn Baldwin 	 * 'top'.  'total_pages' gives us a total count of pages and is
2011b2e60773SJohn Baldwin 	 * used to know when we have finished encrypting the TLS
2012b2e60773SJohn Baldwin 	 * records originally queued with 'top'.
2013b2e60773SJohn Baldwin 	 *
2014b2e60773SJohn Baldwin 	 * NB: These mbufs are queued in the socket buffer and
2015b2e60773SJohn Baldwin 	 * 'm_next' is traversing the mbufs in the socket buffer.  The
2016b2e60773SJohn Baldwin 	 * socket buffer lock is not held while traversing this chain.
2017b2e60773SJohn Baldwin 	 * Since the mbufs are all marked M_NOTREADY their 'm_next'
2018b2e60773SJohn Baldwin 	 * pointers should be stable.  However, the 'm_next' of the
2019b2e60773SJohn Baldwin 	 * last mbuf encrypted is not necessarily NULL.  It can point
2020b2e60773SJohn Baldwin 	 * to other mbufs appended while 'top' was on the TLS work
2021b2e60773SJohn Baldwin 	 * queue.
2022b2e60773SJohn Baldwin 	 *
2023b2e60773SJohn Baldwin 	 * Each mbuf holds an entire TLS record.
2024b2e60773SJohn Baldwin 	 */
2025b2e60773SJohn Baldwin 	error = 0;
2026b2e60773SJohn Baldwin 	for (m = top; npages != total_pages; m = m->m_next) {
20277b6c99d0SGleb Smirnoff 		KASSERT(m->m_epg_tls == tls,
2028b2e60773SJohn Baldwin 		    ("different TLS sessions in a single mbuf chain: %p vs %p",
20297b6c99d0SGleb Smirnoff 		    tls, m->m_epg_tls));
20306edfd179SGleb Smirnoff 		KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
20316edfd179SGleb Smirnoff 		    (M_EXTPG | M_NOTREADY),
2032b2e60773SJohn Baldwin 		    ("%p not unready & nomap mbuf (top = %p)\n", m, top));
20337b6c99d0SGleb Smirnoff 		KASSERT(npages + m->m_epg_npgs <= total_pages,
2034b2e60773SJohn Baldwin 		    ("page count mismatch: top %p, total_pages %d, m %p", top,
2035b2e60773SJohn Baldwin 		    total_pages, m));
203649f6925cSMark Johnston 		KASSERT(ptoa(m->m_epg_npgs) <= ktls_maxlen,
203749f6925cSMark Johnston 		    ("page count %d larger than maximum frame length %d",
203849f6925cSMark Johnston 		    m->m_epg_npgs, ktls_maxlen));
2039b2e60773SJohn Baldwin 
2040b2e60773SJohn Baldwin 		/*
204121e3c1fbSJohn Baldwin 		 * For anonymous mbufs, encryption is done in place.
204221e3c1fbSJohn Baldwin 		 * For file-backed mbufs (from sendfile), anonymous
204321e3c1fbSJohn Baldwin 		 * wired pages are allocated and used as the
204421e3c1fbSJohn Baldwin 		 * encryption destination.
2045b2e60773SJohn Baldwin 		 */
204621e3c1fbSJohn Baldwin 		if ((m->m_epg_flags & EPG_FLAG_ANON) != 0) {
204721e3c1fbSJohn Baldwin 			error = (*tls->sw_encrypt)(tls, m, NULL, 0);
204821e3c1fbSJohn Baldwin 		} else {
204921e3c1fbSJohn Baldwin 			if ((cbuf = ktls_buffer_alloc(wq, m)) != NULL) {
205021e3c1fbSJohn Baldwin 				len = ptoa(m->m_epg_npgs - 1) +
205121e3c1fbSJohn Baldwin 				    m->m_epg_last_len - m->m_epg_1st_off;
205221e3c1fbSJohn Baldwin 				dst_iov[0].iov_base = (char *)cbuf +
205349f6925cSMark Johnston 				    m->m_epg_1st_off;
205449f6925cSMark Johnston 				dst_iov[0].iov_len = len;
205549f6925cSMark Johnston 				parray[0] = DMAP_TO_PHYS((vm_offset_t)cbuf);
205649f6925cSMark Johnston 				i = 1;
205749f6925cSMark Johnston 			} else {
205849f6925cSMark Johnston 				off = m->m_epg_1st_off;
205949f6925cSMark Johnston 				for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
206049f6925cSMark Johnston 					do {
206149f6925cSMark Johnston 						pg = vm_page_alloc(NULL, 0,
206249f6925cSMark Johnston 						    VM_ALLOC_NORMAL |
206349f6925cSMark Johnston 						    VM_ALLOC_NOOBJ |
206449f6925cSMark Johnston 						    VM_ALLOC_NODUMP |
206549f6925cSMark Johnston 						    VM_ALLOC_WIRED |
206649f6925cSMark Johnston 						    VM_ALLOC_WAITFAIL);
206749f6925cSMark Johnston 					} while (pg == NULL);
206849f6925cSMark Johnston 
206949f6925cSMark Johnston 					len = m_epg_pagelen(m, i, off);
2070b2e60773SJohn Baldwin 					parray[i] = VM_PAGE_TO_PHYS(pg);
2071b2e60773SJohn Baldwin 					dst_iov[i].iov_base =
207249f6925cSMark Johnston 					    (char *)(void *)PHYS_TO_DMAP(
207349f6925cSMark Johnston 					    parray[i]) + off;
2074b2e60773SJohn Baldwin 					dst_iov[i].iov_len = len;
2075b2e60773SJohn Baldwin 				}
207649f6925cSMark Johnston 			}
2077*6b313a3aSJohn Baldwin 			KASSERT(i + 1 <= nitems(dst_iov),
2078*6b313a3aSJohn Baldwin 			    ("dst_iov is too small"));
2079*6b313a3aSJohn Baldwin 			dst_iov[i].iov_base = m->m_epg_trail;
2080*6b313a3aSJohn Baldwin 			dst_iov[i].iov_len = m->m_epg_trllen;
2081b2e60773SJohn Baldwin 
2082*6b313a3aSJohn Baldwin 			error = (*tls->sw_encrypt)(tls, m, dst_iov, i + 1);
2083b2e60773SJohn Baldwin 
2084b2e60773SJohn Baldwin 			/* Free the old pages. */
2085b2e60773SJohn Baldwin 			m->m_ext.ext_free(m);
2086b2e60773SJohn Baldwin 
2087b2e60773SJohn Baldwin 			/* Replace them with the new pages. */
208849f6925cSMark Johnston 			if (cbuf != NULL) {
208949f6925cSMark Johnston 				for (i = 0; i < m->m_epg_npgs; i++)
209049f6925cSMark Johnston 					m->m_epg_pa[i] = parray[0] + ptoa(i);
209149f6925cSMark Johnston 
209249f6925cSMark Johnston 				/* Contig pages should go back to the cache. */
209349f6925cSMark Johnston 				m->m_ext.ext_free = ktls_free_mext_contig;
209449f6925cSMark Johnston 			} else {
20957b6c99d0SGleb Smirnoff 				for (i = 0; i < m->m_epg_npgs; i++)
20960c103266SGleb Smirnoff 					m->m_epg_pa[i] = parray[i];
2097b2e60773SJohn Baldwin 
2098b2e60773SJohn Baldwin 				/* Use the basic free routine. */
2099b2e60773SJohn Baldwin 				m->m_ext.ext_free = mb_free_mext_pgs;
210049f6925cSMark Johnston 			}
2101b2dba663SAndrew Gallatin 
2102b2dba663SAndrew Gallatin 			/* Pages are now writable. */
21037b6c99d0SGleb Smirnoff 			m->m_epg_flags |= EPG_FLAG_ANON;
2104b2e60773SJohn Baldwin 		}
210521e3c1fbSJohn Baldwin 		if (error) {
210621e3c1fbSJohn Baldwin 			counter_u64_add(ktls_offload_failed_crypto, 1);
210721e3c1fbSJohn Baldwin 			break;
210821e3c1fbSJohn Baldwin 		}
210921e3c1fbSJohn Baldwin 
211021e3c1fbSJohn Baldwin 		if (__predict_false(m->m_epg_npgs == 0)) {
211121e3c1fbSJohn Baldwin 			/* TLS 1.0 empty fragment. */
211221e3c1fbSJohn Baldwin 			npages++;
211321e3c1fbSJohn Baldwin 		} else
211421e3c1fbSJohn Baldwin 			npages += m->m_epg_npgs;
2115b2e60773SJohn Baldwin 
2116b2e60773SJohn Baldwin 		/*
2117b2e60773SJohn Baldwin 		 * Drop a reference to the session now that it is no
2118b2e60773SJohn Baldwin 		 * longer needed.  Existing code depends on encrypted
2119b2e60773SJohn Baldwin 		 * records having no associated session vs
2120b2e60773SJohn Baldwin 		 * yet-to-be-encrypted records having an associated
2121b2e60773SJohn Baldwin 		 * session.
2122b2e60773SJohn Baldwin 		 */
21237b6c99d0SGleb Smirnoff 		m->m_epg_tls = NULL;
2124b2e60773SJohn Baldwin 		ktls_free(tls);
2125b2e60773SJohn Baldwin 	}
2126b2e60773SJohn Baldwin 
2127b2e60773SJohn Baldwin 	CURVNET_SET(so->so_vnet);
2128b2e60773SJohn Baldwin 	if (error == 0) {
2129b2e60773SJohn Baldwin 		(void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
2130b2e60773SJohn Baldwin 	} else {
2131b2e60773SJohn Baldwin 		so->so_proto->pr_usrreqs->pru_abort(so);
2132b2e60773SJohn Baldwin 		so->so_error = EIO;
2133b2e60773SJohn Baldwin 		mb_free_notready(top, total_pages);
2134b2e60773SJohn Baldwin 	}
2135b2e60773SJohn Baldwin 
2136b2e60773SJohn Baldwin 	SOCK_LOCK(so);
2137b2e60773SJohn Baldwin 	sorele(so);
2138b2e60773SJohn Baldwin 	CURVNET_RESTORE();
2139b2e60773SJohn Baldwin }
2140b2e60773SJohn Baldwin 
2141b2e60773SJohn Baldwin static void
2142b2e60773SJohn Baldwin ktls_work_thread(void *ctx)
2143b2e60773SJohn Baldwin {
2144b2e60773SJohn Baldwin 	struct ktls_wq *wq = ctx;
2145d90fe9d0SGleb Smirnoff 	struct mbuf *m, *n;
21463c0e5685SJohn Baldwin 	struct socket *so, *son;
21473c0e5685SJohn Baldwin 	STAILQ_HEAD(, mbuf) local_m_head;
21483c0e5685SJohn Baldwin 	STAILQ_HEAD(, socket) local_so_head;
2149b2e60773SJohn Baldwin 
215002bc3865SAndrew Gallatin 	if (ktls_bind_threads > 1) {
215102bc3865SAndrew Gallatin 		curthread->td_domain.dr_policy =
215202bc3865SAndrew Gallatin 			DOMAINSET_PREF(PCPU_GET(domain));
215302bc3865SAndrew Gallatin 	}
2154b2e60773SJohn Baldwin #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
2155b2e60773SJohn Baldwin 	fpu_kern_thread(0);
2156b2e60773SJohn Baldwin #endif
2157b2e60773SJohn Baldwin 	for (;;) {
2158b2e60773SJohn Baldwin 		mtx_lock(&wq->mtx);
21593c0e5685SJohn Baldwin 		while (STAILQ_EMPTY(&wq->m_head) &&
21603c0e5685SJohn Baldwin 		    STAILQ_EMPTY(&wq->so_head)) {
2161b2e60773SJohn Baldwin 			wq->running = false;
2162b2e60773SJohn Baldwin 			mtx_sleep(wq, &wq->mtx, 0, "-", 0);
2163b2e60773SJohn Baldwin 			wq->running = true;
2164b2e60773SJohn Baldwin 		}
2165b2e60773SJohn Baldwin 
21663c0e5685SJohn Baldwin 		STAILQ_INIT(&local_m_head);
21673c0e5685SJohn Baldwin 		STAILQ_CONCAT(&local_m_head, &wq->m_head);
21683c0e5685SJohn Baldwin 		STAILQ_INIT(&local_so_head);
21693c0e5685SJohn Baldwin 		STAILQ_CONCAT(&local_so_head, &wq->so_head);
2170b2e60773SJohn Baldwin 		mtx_unlock(&wq->mtx);
2171b2e60773SJohn Baldwin 
21723c0e5685SJohn Baldwin 		STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
21737b6c99d0SGleb Smirnoff 			if (m->m_epg_flags & EPG_FLAG_2FREE) {
21747b6c99d0SGleb Smirnoff 				ktls_free(m->m_epg_tls);
217523feb563SAndrew Gallatin 				uma_zfree(zone_mbuf, m);
2176eeec8348SGleb Smirnoff 			} else {
217749f6925cSMark Johnston 				ktls_encrypt(wq, m);
21783c0e5685SJohn Baldwin 				counter_u64_add(ktls_cnt_tx_queued, -1);
2179b2e60773SJohn Baldwin 			}
2180b2e60773SJohn Baldwin 		}
21813c0e5685SJohn Baldwin 
21823c0e5685SJohn Baldwin 		STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
21833c0e5685SJohn Baldwin 			ktls_decrypt(so);
21843c0e5685SJohn Baldwin 			counter_u64_add(ktls_cnt_rx_queued, -1);
21853c0e5685SJohn Baldwin 		}
2186b2e60773SJohn Baldwin 	}
2187b2e60773SJohn Baldwin }
2188