xref: /freebsd/sys/kern/uipc_ktls.c (revision a63752cce6462d08bbec08cad931d70dec2f5b4c)
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"
3328d0a740SAndrew Gallatin #include "opt_kern_tls.h"
34ed5e13cfSAndrew Gallatin #include "opt_ratelimit.h"
35b2e60773SJohn Baldwin #include "opt_rss.h"
36b2e60773SJohn Baldwin 
37b2e60773SJohn Baldwin #include <sys/param.h>
38b2e60773SJohn Baldwin #include <sys/kernel.h>
3902bc3865SAndrew Gallatin #include <sys/domainset.h>
40470e851cSJohn Baldwin #include <sys/endian.h>
41b2e60773SJohn Baldwin #include <sys/ktls.h>
42b2e60773SJohn Baldwin #include <sys/lock.h>
43b2e60773SJohn Baldwin #include <sys/mbuf.h>
44b2e60773SJohn Baldwin #include <sys/mutex.h>
45b2e60773SJohn Baldwin #include <sys/rmlock.h>
46b2e60773SJohn Baldwin #include <sys/proc.h>
47b2e60773SJohn Baldwin #include <sys/protosw.h>
48b2e60773SJohn Baldwin #include <sys/refcount.h>
49b2e60773SJohn Baldwin #include <sys/smp.h>
50b2e60773SJohn Baldwin #include <sys/socket.h>
51b2e60773SJohn Baldwin #include <sys/socketvar.h>
52b2e60773SJohn Baldwin #include <sys/sysctl.h>
53b2e60773SJohn Baldwin #include <sys/taskqueue.h>
54b2e60773SJohn Baldwin #include <sys/kthread.h>
55b2e60773SJohn Baldwin #include <sys/uio.h>
56b2e60773SJohn Baldwin #include <sys/vmmeter.h>
57b2e60773SJohn Baldwin #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
58b2e60773SJohn Baldwin #include <machine/pcb.h>
59b2e60773SJohn Baldwin #endif
60b2e60773SJohn Baldwin #include <machine/vmparam.h>
6190746943SGleb Smirnoff #include <net/if.h>
6290746943SGleb Smirnoff #include <net/if_var.h>
63b2e60773SJohn Baldwin #ifdef RSS
64b2e60773SJohn Baldwin #include <net/netisr.h>
65b2e60773SJohn Baldwin #include <net/rss_config.h>
66b2e60773SJohn Baldwin #endif
67454d3896SAlexander V. Chernikov #include <net/route.h>
68454d3896SAlexander V. Chernikov #include <net/route/nhop.h>
69b2e60773SJohn Baldwin #if defined(INET) || defined(INET6)
70b2e60773SJohn Baldwin #include <netinet/in.h>
71b2e60773SJohn Baldwin #include <netinet/in_pcb.h>
72b2e60773SJohn Baldwin #endif
73b2e60773SJohn Baldwin #include <netinet/tcp_var.h>
749e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
759e14430dSJohn Baldwin #include <netinet/tcp_offload.h>
769e14430dSJohn Baldwin #endif
77470e851cSJohn Baldwin #include <opencrypto/cryptodev.h>
78470e851cSJohn Baldwin #include <opencrypto/ktls.h>
79b2e60773SJohn Baldwin #include <vm/uma_dbg.h>
80b2e60773SJohn Baldwin #include <vm/vm.h>
81b2e60773SJohn Baldwin #include <vm/vm_pageout.h>
82b2e60773SJohn Baldwin #include <vm/vm_page.h>
8398215005SAndrew Gallatin #include <vm/vm_pagequeue.h>
84b2e60773SJohn Baldwin 
85b2e60773SJohn Baldwin struct ktls_wq {
86b2e60773SJohn Baldwin 	struct mtx	mtx;
873c0e5685SJohn Baldwin 	STAILQ_HEAD(, mbuf) m_head;
883c0e5685SJohn Baldwin 	STAILQ_HEAD(, socket) so_head;
89b2e60773SJohn Baldwin 	bool		running;
9049f6925cSMark Johnston 	int		lastallocfail;
91b2e60773SJohn Baldwin } __aligned(CACHE_LINE_SIZE);
92b2e60773SJohn Baldwin 
9398215005SAndrew Gallatin struct ktls_alloc_thread {
9498215005SAndrew Gallatin 	uint64_t wakeups;
9598215005SAndrew Gallatin 	uint64_t allocs;
9698215005SAndrew Gallatin 	struct thread *td;
9798215005SAndrew Gallatin 	int running;
9898215005SAndrew Gallatin };
9998215005SAndrew Gallatin 
10002bc3865SAndrew Gallatin struct ktls_domain_info {
10102bc3865SAndrew Gallatin 	int count;
10202bc3865SAndrew Gallatin 	int cpu[MAXCPU];
10398215005SAndrew Gallatin 	struct ktls_alloc_thread alloc_td;
10402bc3865SAndrew Gallatin };
10502bc3865SAndrew Gallatin 
10602bc3865SAndrew Gallatin struct ktls_domain_info ktls_domains[MAXMEMDOM];
107b2e60773SJohn Baldwin static struct ktls_wq *ktls_wq;
108b2e60773SJohn Baldwin static struct proc *ktls_proc;
109b2e60773SJohn Baldwin static uma_zone_t ktls_session_zone;
11049f6925cSMark Johnston static uma_zone_t ktls_buffer_zone;
111b2e60773SJohn Baldwin static uint16_t ktls_cpuid_lookup[MAXCPU];
112b2e60773SJohn Baldwin 
1137029da5cSPawel Biernacki SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
114b2e60773SJohn Baldwin     "Kernel TLS offload");
1157029da5cSPawel Biernacki SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
116b2e60773SJohn Baldwin     "Kernel TLS offload stats");
117b2e60773SJohn Baldwin 
118b2e60773SJohn Baldwin #ifdef RSS
119b2e60773SJohn Baldwin static int ktls_bind_threads = 1;
120b2e60773SJohn Baldwin #else
121b2e60773SJohn Baldwin static int ktls_bind_threads;
122b2e60773SJohn Baldwin #endif
123b2e60773SJohn Baldwin SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
124b2e60773SJohn Baldwin     &ktls_bind_threads, 0,
1254dc1b17dSMark Johnston     "Bind crypto threads to cores (1) or cores and domains (2) at boot");
126b2e60773SJohn Baldwin 
127b2e60773SJohn Baldwin static u_int ktls_maxlen = 16384;
12849f6925cSMark Johnston SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RDTUN,
129b2e60773SJohn Baldwin     &ktls_maxlen, 0, "Maximum TLS record size");
130b2e60773SJohn Baldwin 
131b2e60773SJohn Baldwin static int ktls_number_threads;
132b2e60773SJohn Baldwin SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
133b2e60773SJohn Baldwin     &ktls_number_threads, 0,
134b2e60773SJohn Baldwin     "Number of TLS threads in thread-pool");
135b2e60773SJohn Baldwin 
13628d0a740SAndrew Gallatin unsigned int ktls_ifnet_max_rexmit_pct = 2;
13728d0a740SAndrew Gallatin SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, ifnet_max_rexmit_pct, CTLFLAG_RWTUN,
13828d0a740SAndrew Gallatin     &ktls_ifnet_max_rexmit_pct, 2,
13928d0a740SAndrew Gallatin     "Max percent bytes retransmitted before ifnet TLS is disabled");
14028d0a740SAndrew Gallatin 
141b2e60773SJohn Baldwin static bool ktls_offload_enable;
142b5aa9ad4SMark Johnston SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RWTUN,
143b2e60773SJohn Baldwin     &ktls_offload_enable, 0,
144b2e60773SJohn Baldwin     "Enable support for kernel TLS offload");
145b2e60773SJohn Baldwin 
146b2e60773SJohn Baldwin static bool ktls_cbc_enable = true;
147b5aa9ad4SMark Johnston SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RWTUN,
148b2e60773SJohn Baldwin     &ktls_cbc_enable, 1,
149b2e60773SJohn Baldwin     "Enable Support of AES-CBC crypto for kernel TLS");
150b2e60773SJohn Baldwin 
15149f6925cSMark Johnston static bool ktls_sw_buffer_cache = true;
15249f6925cSMark Johnston SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, sw_buffer_cache, CTLFLAG_RDTUN,
15349f6925cSMark Johnston     &ktls_sw_buffer_cache, 1,
15449f6925cSMark Johnston     "Enable caching of output buffers for SW encryption");
15549f6925cSMark Johnston 
15698215005SAndrew Gallatin static int ktls_max_alloc = 128;
15798215005SAndrew Gallatin SYSCTL_INT(_kern_ipc_tls, OID_AUTO, max_alloc, CTLFLAG_RWTUN,
15898215005SAndrew Gallatin     &ktls_max_alloc, 128,
15998215005SAndrew Gallatin     "Max number of 16k buffers to allocate in thread context");
16098215005SAndrew Gallatin 
1611755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_tasks_active);
162b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
163b2e60773SJohn Baldwin     &ktls_tasks_active, "Number of active tasks");
164b2e60773SJohn Baldwin 
1651755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_cnt_tx_queued);
1663c0e5685SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_inqueue, CTLFLAG_RD,
1673c0e5685SJohn Baldwin     &ktls_cnt_tx_queued,
1683c0e5685SJohn Baldwin     "Number of TLS records in queue to tasks for SW encryption");
1693c0e5685SJohn Baldwin 
1701755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_cnt_rx_queued);
1713c0e5685SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_rx_inqueue, CTLFLAG_RD,
1723c0e5685SJohn Baldwin     &ktls_cnt_rx_queued,
1733c0e5685SJohn Baldwin     "Number of TLS sockets in queue to tasks for SW decryption");
174b2e60773SJohn Baldwin 
1751755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_offload_total);
176b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
177b2e60773SJohn Baldwin     CTLFLAG_RD, &ktls_offload_total,
178b2e60773SJohn Baldwin     "Total successful TLS setups (parameters set)");
179b2e60773SJohn Baldwin 
1801755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_offload_enable_calls);
181b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
182b2e60773SJohn Baldwin     CTLFLAG_RD, &ktls_offload_enable_calls,
183b2e60773SJohn Baldwin     "Total number of TLS enable calls made");
184b2e60773SJohn Baldwin 
1851755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_offload_active);
186b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
187b2e60773SJohn Baldwin     &ktls_offload_active, "Total Active TLS sessions");
188b2e60773SJohn Baldwin 
1891755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_offload_corrupted_records);
1903c0e5685SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, corrupted_records, CTLFLAG_RD,
1913c0e5685SJohn Baldwin     &ktls_offload_corrupted_records, "Total corrupted TLS records received");
1923c0e5685SJohn Baldwin 
1931755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_offload_failed_crypto);
194b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
195b2e60773SJohn Baldwin     &ktls_offload_failed_crypto, "Total TLS crypto failures");
196b2e60773SJohn Baldwin 
1971755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_ifnet);
198b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
199b2e60773SJohn Baldwin     &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
200b2e60773SJohn Baldwin 
2011755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_sw);
202b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
203b2e60773SJohn Baldwin     &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
204b2e60773SJohn Baldwin 
2051755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_switch_failed);
206b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
207b2e60773SJohn Baldwin     &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
208b2e60773SJohn Baldwin 
20928d0a740SAndrew Gallatin static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_disable_fail);
21028d0a740SAndrew Gallatin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, ifnet_disable_failed, CTLFLAG_RD,
21128d0a740SAndrew Gallatin     &ktls_ifnet_disable_fail, "TLS sessions unable to switch to SW from ifnet");
21228d0a740SAndrew Gallatin 
21328d0a740SAndrew Gallatin static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_disable_ok);
21428d0a740SAndrew Gallatin SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, ifnet_disable_ok, CTLFLAG_RD,
21528d0a740SAndrew Gallatin     &ktls_ifnet_disable_ok, "TLS sessions able to switch to SW from ifnet");
21628d0a740SAndrew Gallatin 
2177029da5cSPawel Biernacki SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
218b2e60773SJohn Baldwin     "Software TLS session stats");
2197029da5cSPawel Biernacki SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
220b2e60773SJohn Baldwin     "Hardware (ifnet) TLS session stats");
2219e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
2227029da5cSPawel Biernacki SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2239e14430dSJohn Baldwin     "TOE TLS session stats");
2249e14430dSJohn Baldwin #endif
225b2e60773SJohn Baldwin 
2261755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_sw_cbc);
227b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
228b2e60773SJohn Baldwin     "Active number of software TLS sessions using AES-CBC");
229b2e60773SJohn Baldwin 
2301755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_sw_gcm);
231b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
232b2e60773SJohn Baldwin     "Active number of software TLS sessions using AES-GCM");
233b2e60773SJohn Baldwin 
2349c64fc40SJohn Baldwin static COUNTER_U64_DEFINE_EARLY(ktls_sw_chacha20);
2359c64fc40SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, chacha20, CTLFLAG_RD,
2369c64fc40SJohn Baldwin     &ktls_sw_chacha20,
2379c64fc40SJohn Baldwin     "Active number of software TLS sessions using Chacha20-Poly1305");
2389c64fc40SJohn Baldwin 
2391755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_cbc);
240b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
241b2e60773SJohn Baldwin     &ktls_ifnet_cbc,
242b2e60773SJohn Baldwin     "Active number of ifnet TLS sessions using AES-CBC");
243b2e60773SJohn Baldwin 
2441755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_gcm);
245b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
246b2e60773SJohn Baldwin     &ktls_ifnet_gcm,
247b2e60773SJohn Baldwin     "Active number of ifnet TLS sessions using AES-GCM");
248b2e60773SJohn Baldwin 
2499c64fc40SJohn Baldwin static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_chacha20);
2509c64fc40SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, chacha20, CTLFLAG_RD,
2519c64fc40SJohn Baldwin     &ktls_ifnet_chacha20,
2529c64fc40SJohn Baldwin     "Active number of ifnet TLS sessions using Chacha20-Poly1305");
2539c64fc40SJohn Baldwin 
2541755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset);
255b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
256b2e60773SJohn Baldwin     &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
257b2e60773SJohn Baldwin 
2581755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_dropped);
259b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
260b2e60773SJohn Baldwin     &ktls_ifnet_reset_dropped,
261b2e60773SJohn Baldwin     "TLS sessions dropped after failing to update ifnet send tag");
262b2e60773SJohn Baldwin 
2631755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_failed);
264b2e60773SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
265b2e60773SJohn Baldwin     &ktls_ifnet_reset_failed,
266b2e60773SJohn Baldwin     "TLS sessions that failed to allocate a new ifnet send tag");
267b2e60773SJohn Baldwin 
268b2e60773SJohn Baldwin static int ktls_ifnet_permitted;
269b2e60773SJohn Baldwin SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
270b2e60773SJohn Baldwin     &ktls_ifnet_permitted, 1,
271b2e60773SJohn Baldwin     "Whether to permit hardware (ifnet) TLS sessions");
272b2e60773SJohn Baldwin 
2739e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
2741755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_toe_cbc);
2759e14430dSJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
2769e14430dSJohn Baldwin     &ktls_toe_cbc,
2779e14430dSJohn Baldwin     "Active number of TOE TLS sessions using AES-CBC");
2789e14430dSJohn Baldwin 
2791755b2b9SMark Johnston static COUNTER_U64_DEFINE_EARLY(ktls_toe_gcm);
2809e14430dSJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
2819e14430dSJohn Baldwin     &ktls_toe_gcm,
2829e14430dSJohn Baldwin     "Active number of TOE TLS sessions using AES-GCM");
2839c64fc40SJohn Baldwin 
28490972f04SJohn Baldwin static COUNTER_U64_DEFINE_EARLY(ktls_toe_chacha20);
2859c64fc40SJohn Baldwin SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, chacha20, CTLFLAG_RD,
2869c64fc40SJohn Baldwin     &ktls_toe_chacha20,
2879c64fc40SJohn Baldwin     "Active number of TOE TLS sessions using Chacha20-Poly1305");
2889e14430dSJohn Baldwin #endif
2899e14430dSJohn Baldwin 
290b2e60773SJohn Baldwin static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
291b2e60773SJohn Baldwin 
292b2e60773SJohn Baldwin static void ktls_cleanup(struct ktls_session *tls);
293b2e60773SJohn Baldwin #if defined(INET) || defined(INET6)
294b2e60773SJohn Baldwin static void ktls_reset_send_tag(void *context, int pending);
295b2e60773SJohn Baldwin #endif
296b2e60773SJohn Baldwin static void ktls_work_thread(void *ctx);
29798215005SAndrew Gallatin static void ktls_alloc_thread(void *ctx);
298b2e60773SJohn Baldwin 
299b2e60773SJohn Baldwin #if defined(INET) || defined(INET6)
300a2fba2a7SBjoern A. Zeeb static u_int
301b2e60773SJohn Baldwin ktls_get_cpu(struct socket *so)
302b2e60773SJohn Baldwin {
303b2e60773SJohn Baldwin 	struct inpcb *inp;
30402bc3865SAndrew Gallatin #ifdef NUMA
30502bc3865SAndrew Gallatin 	struct ktls_domain_info *di;
30602bc3865SAndrew Gallatin #endif
307a2fba2a7SBjoern A. Zeeb 	u_int cpuid;
308b2e60773SJohn Baldwin 
309b2e60773SJohn Baldwin 	inp = sotoinpcb(so);
310b2e60773SJohn Baldwin #ifdef RSS
311b2e60773SJohn Baldwin 	cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
312b2e60773SJohn Baldwin 	if (cpuid != NETISR_CPUID_NONE)
313b2e60773SJohn Baldwin 		return (cpuid);
314b2e60773SJohn Baldwin #endif
315b2e60773SJohn Baldwin 	/*
316b2e60773SJohn Baldwin 	 * Just use the flowid to shard connections in a repeatable
31721e3c1fbSJohn Baldwin 	 * fashion.  Note that TLS 1.0 sessions rely on the
318b2e60773SJohn Baldwin 	 * serialization provided by having the same connection use
319b2e60773SJohn Baldwin 	 * the same queue.
320b2e60773SJohn Baldwin 	 */
32102bc3865SAndrew Gallatin #ifdef NUMA
32202bc3865SAndrew Gallatin 	if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
32302bc3865SAndrew Gallatin 		di = &ktls_domains[inp->inp_numa_domain];
32402bc3865SAndrew Gallatin 		cpuid = di->cpu[inp->inp_flowid % di->count];
32502bc3865SAndrew Gallatin 	} else
32602bc3865SAndrew Gallatin #endif
327b2e60773SJohn Baldwin 		cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
328b2e60773SJohn Baldwin 	return (cpuid);
329b2e60773SJohn Baldwin }
330b2e60773SJohn Baldwin #endif
331b2e60773SJohn Baldwin 
33249f6925cSMark Johnston static int
33349f6925cSMark Johnston ktls_buffer_import(void *arg, void **store, int count, int domain, int flags)
33449f6925cSMark Johnston {
33549f6925cSMark Johnston 	vm_page_t m;
33649f6925cSMark Johnston 	int i;
33749f6925cSMark Johnston 
33849f6925cSMark Johnston 	KASSERT((ktls_maxlen & PAGE_MASK) == 0,
33949f6925cSMark Johnston 	    ("%s: ktls max length %d is not page size-aligned",
34049f6925cSMark Johnston 	    __func__, ktls_maxlen));
34149f6925cSMark Johnston 
34249f6925cSMark Johnston 	for (i = 0; i < count; i++) {
34349f6925cSMark Johnston 		m = vm_page_alloc_contig_domain(NULL, 0, domain,
34449f6925cSMark Johnston 		    VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
34549f6925cSMark Johnston 		    VM_ALLOC_NODUMP | malloc2vm_flags(flags),
34649f6925cSMark Johnston 		    atop(ktls_maxlen), 0, ~0ul, PAGE_SIZE, 0,
34749f6925cSMark Johnston 		    VM_MEMATTR_DEFAULT);
34849f6925cSMark Johnston 		if (m == NULL)
34949f6925cSMark Johnston 			break;
35049f6925cSMark Johnston 		store[i] = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
35149f6925cSMark Johnston 	}
35249f6925cSMark Johnston 	return (i);
35349f6925cSMark Johnston }
35449f6925cSMark Johnston 
35549f6925cSMark Johnston static void
35649f6925cSMark Johnston ktls_buffer_release(void *arg __unused, void **store, int count)
35749f6925cSMark Johnston {
35849f6925cSMark Johnston 	vm_page_t m;
35949f6925cSMark Johnston 	int i, j;
36049f6925cSMark Johnston 
36149f6925cSMark Johnston 	for (i = 0; i < count; i++) {
36249f6925cSMark Johnston 		m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)store[i]));
36349f6925cSMark Johnston 		for (j = 0; j < atop(ktls_maxlen); j++) {
36449f6925cSMark Johnston 			(void)vm_page_unwire_noq(m + j);
36549f6925cSMark Johnston 			vm_page_free(m + j);
36649f6925cSMark Johnston 		}
36749f6925cSMark Johnston 	}
36849f6925cSMark Johnston }
36949f6925cSMark Johnston 
37049f6925cSMark Johnston static void
37149f6925cSMark Johnston ktls_free_mext_contig(struct mbuf *m)
37249f6925cSMark Johnston {
37349f6925cSMark Johnston 	M_ASSERTEXTPG(m);
37449f6925cSMark Johnston 	uma_zfree(ktls_buffer_zone, (void *)PHYS_TO_DMAP(m->m_epg_pa[0]));
37549f6925cSMark Johnston }
37649f6925cSMark Johnston 
377b2e60773SJohn Baldwin static void
378b2e60773SJohn Baldwin ktls_init(void *dummy __unused)
379b2e60773SJohn Baldwin {
380b2e60773SJohn Baldwin 	struct thread *td;
381b2e60773SJohn Baldwin 	struct pcpu *pc;
382b2e60773SJohn Baldwin 	cpuset_t mask;
38302bc3865SAndrew Gallatin 	int count, domain, error, i;
384b2e60773SJohn Baldwin 
385b2e60773SJohn Baldwin 	ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
386b2e60773SJohn Baldwin 	    M_WAITOK | M_ZERO);
387b2e60773SJohn Baldwin 
388b2e60773SJohn Baldwin 	ktls_session_zone = uma_zcreate("ktls_session",
389b2e60773SJohn Baldwin 	    sizeof(struct ktls_session),
390b2e60773SJohn Baldwin 	    NULL, NULL, NULL, NULL,
391b2e60773SJohn Baldwin 	    UMA_ALIGN_CACHE, 0);
392b2e60773SJohn Baldwin 
39349f6925cSMark Johnston 	if (ktls_sw_buffer_cache) {
39449f6925cSMark Johnston 		ktls_buffer_zone = uma_zcache_create("ktls_buffers",
39549f6925cSMark Johnston 		    roundup2(ktls_maxlen, PAGE_SIZE), NULL, NULL, NULL, NULL,
39649f6925cSMark Johnston 		    ktls_buffer_import, ktls_buffer_release, NULL,
39749f6925cSMark Johnston 		    UMA_ZONE_FIRSTTOUCH);
39849f6925cSMark Johnston 	}
39949f6925cSMark Johnston 
400b2e60773SJohn Baldwin 	/*
401b2e60773SJohn Baldwin 	 * Initialize the workqueues to run the TLS work.  We create a
402b2e60773SJohn Baldwin 	 * work queue for each CPU.
403b2e60773SJohn Baldwin 	 */
404b2e60773SJohn Baldwin 	CPU_FOREACH(i) {
4053c0e5685SJohn Baldwin 		STAILQ_INIT(&ktls_wq[i].m_head);
4063c0e5685SJohn Baldwin 		STAILQ_INIT(&ktls_wq[i].so_head);
407b2e60773SJohn Baldwin 		mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
408b2e60773SJohn Baldwin 		error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
40961b8a4afSAndrew Gallatin 		    &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
410b2e60773SJohn Baldwin 		if (error)
411b2e60773SJohn Baldwin 			panic("Can't add KTLS thread %d error %d", i, error);
412b2e60773SJohn Baldwin 
413b2e60773SJohn Baldwin 		/*
414b2e60773SJohn Baldwin 		 * Bind threads to cores.  If ktls_bind_threads is >
415b2e60773SJohn Baldwin 		 * 1, then we bind to the NUMA domain.
416b2e60773SJohn Baldwin 		 */
417b2e60773SJohn Baldwin 		if (ktls_bind_threads) {
418b2e60773SJohn Baldwin 			if (ktls_bind_threads > 1) {
419b2e60773SJohn Baldwin 				pc = pcpu_find(i);
42002bc3865SAndrew Gallatin 				domain = pc->pc_domain;
42102bc3865SAndrew Gallatin 				CPU_COPY(&cpuset_domain[domain], &mask);
42202bc3865SAndrew Gallatin 				count = ktls_domains[domain].count;
42302bc3865SAndrew Gallatin 				ktls_domains[domain].cpu[count] = i;
42402bc3865SAndrew Gallatin 				ktls_domains[domain].count++;
425b2e60773SJohn Baldwin 			} else {
426b2e60773SJohn Baldwin 				CPU_SETOF(i, &mask);
427b2e60773SJohn Baldwin 			}
428b2e60773SJohn Baldwin 			error = cpuset_setthread(td->td_tid, &mask);
429b2e60773SJohn Baldwin 			if (error)
430b2e60773SJohn Baldwin 				panic(
431b2e60773SJohn Baldwin 			    "Unable to bind KTLS thread for CPU %d error %d",
432b2e60773SJohn Baldwin 				     i, error);
433b2e60773SJohn Baldwin 		}
434b2e60773SJohn Baldwin 		ktls_cpuid_lookup[ktls_number_threads] = i;
435b2e60773SJohn Baldwin 		ktls_number_threads++;
436b2e60773SJohn Baldwin 	}
43702bc3865SAndrew Gallatin 
43802bc3865SAndrew Gallatin 	/*
43998215005SAndrew Gallatin 	 * Start an allocation thread per-domain to perform blocking allocations
44098215005SAndrew Gallatin 	 * of 16k physically contiguous TLS crypto destination buffers.
44198215005SAndrew Gallatin 	 */
44298215005SAndrew Gallatin 	if (ktls_sw_buffer_cache) {
44398215005SAndrew Gallatin 		for (domain = 0; domain < vm_ndomains; domain++) {
44498215005SAndrew Gallatin 			if (VM_DOMAIN_EMPTY(domain))
44598215005SAndrew Gallatin 				continue;
44698215005SAndrew Gallatin 			if (CPU_EMPTY(&cpuset_domain[domain]))
44798215005SAndrew Gallatin 				continue;
44898215005SAndrew Gallatin 			error = kproc_kthread_add(ktls_alloc_thread,
44998215005SAndrew Gallatin 			    &ktls_domains[domain], &ktls_proc,
45098215005SAndrew Gallatin 			    &ktls_domains[domain].alloc_td.td,
45198215005SAndrew Gallatin 			    0, 0, "KTLS", "alloc_%d", domain);
45298215005SAndrew Gallatin 			if (error)
45398215005SAndrew Gallatin 				panic("Can't add KTLS alloc thread %d error %d",
45498215005SAndrew Gallatin 				    domain, error);
45598215005SAndrew Gallatin 			CPU_COPY(&cpuset_domain[domain], &mask);
45698215005SAndrew Gallatin 			error = cpuset_setthread(ktls_domains[domain].alloc_td.td->td_tid,
45798215005SAndrew Gallatin 			    &mask);
45898215005SAndrew Gallatin 			if (error)
45998215005SAndrew Gallatin 				panic("Unable to bind KTLS alloc %d error %d",
46098215005SAndrew Gallatin 				    domain, error);
46198215005SAndrew Gallatin 		}
46298215005SAndrew Gallatin 	}
46398215005SAndrew Gallatin 
46498215005SAndrew Gallatin 	/*
46502bc3865SAndrew Gallatin 	 * If we somehow have an empty domain, fall back to choosing
46602bc3865SAndrew Gallatin 	 * among all KTLS threads.
46702bc3865SAndrew Gallatin 	 */
4684dc1b17dSMark Johnston 	if (ktls_bind_threads > 1) {
46902bc3865SAndrew Gallatin 		for (i = 0; i < vm_ndomains; i++) {
47002bc3865SAndrew Gallatin 			if (ktls_domains[i].count == 0) {
4714dc1b17dSMark Johnston 				ktls_bind_threads = 1;
47202bc3865SAndrew Gallatin 				break;
47302bc3865SAndrew Gallatin 			}
47402bc3865SAndrew Gallatin 		}
4754dc1b17dSMark Johnston 	}
47602bc3865SAndrew Gallatin 
47789b65087SMark Johnston 	if (bootverbose)
478b2e60773SJohn Baldwin 		printf("KTLS: Initialized %d threads\n", ktls_number_threads);
479b2e60773SJohn Baldwin }
480b2e60773SJohn Baldwin SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
481b2e60773SJohn Baldwin 
482b2e60773SJohn Baldwin #if defined(INET) || defined(INET6)
483b2e60773SJohn Baldwin static int
484b2e60773SJohn Baldwin ktls_create_session(struct socket *so, struct tls_enable *en,
485b2e60773SJohn Baldwin     struct ktls_session **tlsp)
486b2e60773SJohn Baldwin {
487b2e60773SJohn Baldwin 	struct ktls_session *tls;
488b2e60773SJohn Baldwin 	int error;
489b2e60773SJohn Baldwin 
4907d29eb9aSJohn Baldwin 	/* Only TLS 1.0 - 1.3 are supported. */
491b2e60773SJohn Baldwin 	if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
492b2e60773SJohn Baldwin 		return (EINVAL);
493b2e60773SJohn Baldwin 	if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
4946554362cSAndrew Gallatin 	    en->tls_vminor > TLS_MINOR_VER_THREE)
495b2e60773SJohn Baldwin 		return (EINVAL);
496b2e60773SJohn Baldwin 
497b2e60773SJohn Baldwin 	if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
498b2e60773SJohn Baldwin 		return (EINVAL);
499b2e60773SJohn Baldwin 	if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
500b2e60773SJohn Baldwin 		return (EINVAL);
5016554362cSAndrew Gallatin 	if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
502b2e60773SJohn Baldwin 		return (EINVAL);
503b2e60773SJohn Baldwin 
504b2e60773SJohn Baldwin 	/* All supported algorithms require a cipher key. */
505b2e60773SJohn Baldwin 	if (en->cipher_key_len == 0)
506b2e60773SJohn Baldwin 		return (EINVAL);
507b2e60773SJohn Baldwin 
508b2e60773SJohn Baldwin 	/* No flags are currently supported. */
509b2e60773SJohn Baldwin 	if (en->flags != 0)
510b2e60773SJohn Baldwin 		return (EINVAL);
511b2e60773SJohn Baldwin 
512b2e60773SJohn Baldwin 	/* Common checks for supported algorithms. */
513b2e60773SJohn Baldwin 	switch (en->cipher_algorithm) {
514b2e60773SJohn Baldwin 	case CRYPTO_AES_NIST_GCM_16:
515b2e60773SJohn Baldwin 		/*
516b2e60773SJohn Baldwin 		 * auth_algorithm isn't used, but permit GMAC values
517b2e60773SJohn Baldwin 		 * for compatibility.
518b2e60773SJohn Baldwin 		 */
519b2e60773SJohn Baldwin 		switch (en->auth_algorithm) {
520b2e60773SJohn Baldwin 		case 0:
521c0341432SJohn Baldwin #ifdef COMPAT_FREEBSD12
522c0341432SJohn Baldwin 		/* XXX: Really 13.0-current COMPAT. */
523b2e60773SJohn Baldwin 		case CRYPTO_AES_128_NIST_GMAC:
524b2e60773SJohn Baldwin 		case CRYPTO_AES_192_NIST_GMAC:
525b2e60773SJohn Baldwin 		case CRYPTO_AES_256_NIST_GMAC:
526c0341432SJohn Baldwin #endif
527b2e60773SJohn Baldwin 			break;
528b2e60773SJohn Baldwin 		default:
529b2e60773SJohn Baldwin 			return (EINVAL);
530b2e60773SJohn Baldwin 		}
531b2e60773SJohn Baldwin 		if (en->auth_key_len != 0)
532b2e60773SJohn Baldwin 			return (EINVAL);
5336554362cSAndrew Gallatin 		if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
5346554362cSAndrew Gallatin 			en->iv_len != TLS_AEAD_GCM_LEN) ||
5356554362cSAndrew Gallatin 		    (en->tls_vminor == TLS_MINOR_VER_THREE &&
5366554362cSAndrew Gallatin 			en->iv_len != TLS_1_3_GCM_IV_LEN))
537b2e60773SJohn Baldwin 			return (EINVAL);
538b2e60773SJohn Baldwin 		break;
539b2e60773SJohn Baldwin 	case CRYPTO_AES_CBC:
540b2e60773SJohn Baldwin 		switch (en->auth_algorithm) {
541b2e60773SJohn Baldwin 		case CRYPTO_SHA1_HMAC:
542b2e60773SJohn Baldwin 			/*
543b2e60773SJohn Baldwin 			 * TLS 1.0 requires an implicit IV.  TLS 1.1+
544b2e60773SJohn Baldwin 			 * all use explicit IVs.
545b2e60773SJohn Baldwin 			 */
546b2e60773SJohn Baldwin 			if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
547b2e60773SJohn Baldwin 				if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
548b2e60773SJohn Baldwin 					return (EINVAL);
549b2e60773SJohn Baldwin 				break;
550b2e60773SJohn Baldwin 			}
551b2e60773SJohn Baldwin 
552b2e60773SJohn Baldwin 			/* FALLTHROUGH */
553b2e60773SJohn Baldwin 		case CRYPTO_SHA2_256_HMAC:
554b2e60773SJohn Baldwin 		case CRYPTO_SHA2_384_HMAC:
555b2e60773SJohn Baldwin 			/* Ignore any supplied IV. */
556b2e60773SJohn Baldwin 			en->iv_len = 0;
557b2e60773SJohn Baldwin 			break;
558b2e60773SJohn Baldwin 		default:
559b2e60773SJohn Baldwin 			return (EINVAL);
560b2e60773SJohn Baldwin 		}
561b2e60773SJohn Baldwin 		if (en->auth_key_len == 0)
562b2e60773SJohn Baldwin 			return (EINVAL);
563*a63752ccSJohn Baldwin 		if (en->tls_vminor != TLS_MINOR_VER_ZERO &&
564*a63752ccSJohn Baldwin 		    en->tls_vminor != TLS_MINOR_VER_ONE &&
565*a63752ccSJohn Baldwin 		    en->tls_vminor != TLS_MINOR_VER_TWO)
566*a63752ccSJohn Baldwin 			return (EINVAL);
567b2e60773SJohn Baldwin 		break;
5689c64fc40SJohn Baldwin 	case CRYPTO_CHACHA20_POLY1305:
5699c64fc40SJohn Baldwin 		if (en->auth_algorithm != 0 || en->auth_key_len != 0)
5709c64fc40SJohn Baldwin 			return (EINVAL);
5719c64fc40SJohn Baldwin 		if (en->tls_vminor != TLS_MINOR_VER_TWO &&
5729c64fc40SJohn Baldwin 		    en->tls_vminor != TLS_MINOR_VER_THREE)
5739c64fc40SJohn Baldwin 			return (EINVAL);
5749c64fc40SJohn Baldwin 		if (en->iv_len != TLS_CHACHA20_IV_LEN)
5759c64fc40SJohn Baldwin 			return (EINVAL);
5769c64fc40SJohn Baldwin 		break;
577b2e60773SJohn Baldwin 	default:
578b2e60773SJohn Baldwin 		return (EINVAL);
579b2e60773SJohn Baldwin 	}
580b2e60773SJohn Baldwin 
581b2e60773SJohn Baldwin 	tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
582b2e60773SJohn Baldwin 
583b2e60773SJohn Baldwin 	counter_u64_add(ktls_offload_active, 1);
584b2e60773SJohn Baldwin 
585b2e60773SJohn Baldwin 	refcount_init(&tls->refcount, 1);
586b2e60773SJohn Baldwin 	TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
587b2e60773SJohn Baldwin 
588b2e60773SJohn Baldwin 	tls->wq_index = ktls_get_cpu(so);
589b2e60773SJohn Baldwin 
590b2e60773SJohn Baldwin 	tls->params.cipher_algorithm = en->cipher_algorithm;
591b2e60773SJohn Baldwin 	tls->params.auth_algorithm = en->auth_algorithm;
592b2e60773SJohn Baldwin 	tls->params.tls_vmajor = en->tls_vmajor;
593b2e60773SJohn Baldwin 	tls->params.tls_vminor = en->tls_vminor;
594b2e60773SJohn Baldwin 	tls->params.flags = en->flags;
595b2e60773SJohn Baldwin 	tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
596b2e60773SJohn Baldwin 
597b2e60773SJohn Baldwin 	/* Set the header and trailer lengths. */
598b2e60773SJohn Baldwin 	tls->params.tls_hlen = sizeof(struct tls_record_layer);
599b2e60773SJohn Baldwin 	switch (en->cipher_algorithm) {
600b2e60773SJohn Baldwin 	case CRYPTO_AES_NIST_GCM_16:
6016554362cSAndrew Gallatin 		/*
6026554362cSAndrew Gallatin 		 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
6036554362cSAndrew Gallatin 		 * nonce.  TLS 1.3 uses a 12 byte implicit IV.
6046554362cSAndrew Gallatin 		 */
6056554362cSAndrew Gallatin 		if (en->tls_vminor < TLS_MINOR_VER_THREE)
6066554362cSAndrew Gallatin 			tls->params.tls_hlen += sizeof(uint64_t);
607b2e60773SJohn Baldwin 		tls->params.tls_tlen = AES_GMAC_HASH_LEN;
608b2e60773SJohn Baldwin 		tls->params.tls_bs = 1;
609b2e60773SJohn Baldwin 		break;
610b2e60773SJohn Baldwin 	case CRYPTO_AES_CBC:
611b2e60773SJohn Baldwin 		switch (en->auth_algorithm) {
612b2e60773SJohn Baldwin 		case CRYPTO_SHA1_HMAC:
613b2e60773SJohn Baldwin 			if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
614b2e60773SJohn Baldwin 				/* Implicit IV, no nonce. */
615b2e60773SJohn Baldwin 			} else {
616b2e60773SJohn Baldwin 				tls->params.tls_hlen += AES_BLOCK_LEN;
617b2e60773SJohn Baldwin 			}
618b2e60773SJohn Baldwin 			tls->params.tls_tlen = AES_BLOCK_LEN +
619b2e60773SJohn Baldwin 			    SHA1_HASH_LEN;
620b2e60773SJohn Baldwin 			break;
621b2e60773SJohn Baldwin 		case CRYPTO_SHA2_256_HMAC:
622b2e60773SJohn Baldwin 			tls->params.tls_hlen += AES_BLOCK_LEN;
623b2e60773SJohn Baldwin 			tls->params.tls_tlen = AES_BLOCK_LEN +
624b2e60773SJohn Baldwin 			    SHA2_256_HASH_LEN;
625b2e60773SJohn Baldwin 			break;
626b2e60773SJohn Baldwin 		case CRYPTO_SHA2_384_HMAC:
627b2e60773SJohn Baldwin 			tls->params.tls_hlen += AES_BLOCK_LEN;
628b2e60773SJohn Baldwin 			tls->params.tls_tlen = AES_BLOCK_LEN +
629b2e60773SJohn Baldwin 			    SHA2_384_HASH_LEN;
630b2e60773SJohn Baldwin 			break;
631b2e60773SJohn Baldwin 		default:
632b2e60773SJohn Baldwin 			panic("invalid hmac");
633b2e60773SJohn Baldwin 		}
634b2e60773SJohn Baldwin 		tls->params.tls_bs = AES_BLOCK_LEN;
635b2e60773SJohn Baldwin 		break;
6369c64fc40SJohn Baldwin 	case CRYPTO_CHACHA20_POLY1305:
6379c64fc40SJohn Baldwin 		/*
6389c64fc40SJohn Baldwin 		 * Chacha20 uses a 12 byte implicit IV.
6399c64fc40SJohn Baldwin 		 */
6409c64fc40SJohn Baldwin 		tls->params.tls_tlen = POLY1305_HASH_LEN;
6419c64fc40SJohn Baldwin 		tls->params.tls_bs = 1;
6429c64fc40SJohn Baldwin 		break;
643b2e60773SJohn Baldwin 	default:
644b2e60773SJohn Baldwin 		panic("invalid cipher");
645b2e60773SJohn Baldwin 	}
646b2e60773SJohn Baldwin 
6479c64fc40SJohn Baldwin 	/*
6489c64fc40SJohn Baldwin 	 * TLS 1.3 includes optional padding which we do not support,
6499c64fc40SJohn Baldwin 	 * and also puts the "real" record type at the end of the
6509c64fc40SJohn Baldwin 	 * encrypted data.
6519c64fc40SJohn Baldwin 	 */
6529c64fc40SJohn Baldwin 	if (en->tls_vminor == TLS_MINOR_VER_THREE)
6539c64fc40SJohn Baldwin 		tls->params.tls_tlen += sizeof(uint8_t);
6549c64fc40SJohn Baldwin 
655b2e60773SJohn Baldwin 	KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
656b2e60773SJohn Baldwin 	    ("TLS header length too long: %d", tls->params.tls_hlen));
657b2e60773SJohn Baldwin 	KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
658b2e60773SJohn Baldwin 	    ("TLS trailer length too long: %d", tls->params.tls_tlen));
659b2e60773SJohn Baldwin 
660b2e60773SJohn Baldwin 	if (en->auth_key_len != 0) {
661b2e60773SJohn Baldwin 		tls->params.auth_key_len = en->auth_key_len;
662b2e60773SJohn Baldwin 		tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
663b2e60773SJohn Baldwin 		    M_WAITOK);
664b2e60773SJohn Baldwin 		error = copyin(en->auth_key, tls->params.auth_key,
665b2e60773SJohn Baldwin 		    en->auth_key_len);
666b2e60773SJohn Baldwin 		if (error)
667b2e60773SJohn Baldwin 			goto out;
668b2e60773SJohn Baldwin 	}
669b2e60773SJohn Baldwin 
670b2e60773SJohn Baldwin 	tls->params.cipher_key_len = en->cipher_key_len;
671b2e60773SJohn Baldwin 	tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
672b2e60773SJohn Baldwin 	error = copyin(en->cipher_key, tls->params.cipher_key,
673b2e60773SJohn Baldwin 	    en->cipher_key_len);
674b2e60773SJohn Baldwin 	if (error)
675b2e60773SJohn Baldwin 		goto out;
676b2e60773SJohn Baldwin 
677b2e60773SJohn Baldwin 	/*
6789c64fc40SJohn Baldwin 	 * This holds the implicit portion of the nonce for AEAD
6799c64fc40SJohn Baldwin 	 * ciphers and the initial implicit IV for TLS 1.0.  The
6809c64fc40SJohn Baldwin 	 * explicit portions of the IV are generated in ktls_frame().
681b2e60773SJohn Baldwin 	 */
682b2e60773SJohn Baldwin 	if (en->iv_len != 0) {
683b2e60773SJohn Baldwin 		tls->params.iv_len = en->iv_len;
684b2e60773SJohn Baldwin 		error = copyin(en->iv, tls->params.iv, en->iv_len);
685b2e60773SJohn Baldwin 		if (error)
686b2e60773SJohn Baldwin 			goto out;
6877d29eb9aSJohn Baldwin 
6887d29eb9aSJohn Baldwin 		/*
6899c64fc40SJohn Baldwin 		 * For TLS 1.2 with GCM, generate an 8-byte nonce as a
6909c64fc40SJohn Baldwin 		 * counter to generate unique explicit IVs.
6917d29eb9aSJohn Baldwin 		 *
6927d29eb9aSJohn Baldwin 		 * Store this counter in the last 8 bytes of the IV
6937d29eb9aSJohn Baldwin 		 * array so that it is 8-byte aligned.
6947d29eb9aSJohn Baldwin 		 */
6957d29eb9aSJohn Baldwin 		if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
6967d29eb9aSJohn Baldwin 		    en->tls_vminor == TLS_MINOR_VER_TWO)
6977d29eb9aSJohn Baldwin 			arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
698b2e60773SJohn Baldwin 	}
699b2e60773SJohn Baldwin 
700b2e60773SJohn Baldwin 	*tlsp = tls;
701b2e60773SJohn Baldwin 	return (0);
702b2e60773SJohn Baldwin 
703b2e60773SJohn Baldwin out:
704b2e60773SJohn Baldwin 	ktls_cleanup(tls);
705b2e60773SJohn Baldwin 	return (error);
706b2e60773SJohn Baldwin }
707b2e60773SJohn Baldwin 
708b2e60773SJohn Baldwin static struct ktls_session *
709b2e60773SJohn Baldwin ktls_clone_session(struct ktls_session *tls)
710b2e60773SJohn Baldwin {
711b2e60773SJohn Baldwin 	struct ktls_session *tls_new;
712b2e60773SJohn Baldwin 
713b2e60773SJohn Baldwin 	tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
714b2e60773SJohn Baldwin 
715b2e60773SJohn Baldwin 	counter_u64_add(ktls_offload_active, 1);
716b2e60773SJohn Baldwin 
717b2e60773SJohn Baldwin 	refcount_init(&tls_new->refcount, 1);
71895c51fafSAndrew Gallatin 	TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_send_tag, tls_new);
719b2e60773SJohn Baldwin 
720b2e60773SJohn Baldwin 	/* Copy fields from existing session. */
721b2e60773SJohn Baldwin 	tls_new->params = tls->params;
722b2e60773SJohn Baldwin 	tls_new->wq_index = tls->wq_index;
723b2e60773SJohn Baldwin 
724b2e60773SJohn Baldwin 	/* Deep copy keys. */
725b2e60773SJohn Baldwin 	if (tls_new->params.auth_key != NULL) {
726b2e60773SJohn Baldwin 		tls_new->params.auth_key = malloc(tls->params.auth_key_len,
727b2e60773SJohn Baldwin 		    M_KTLS, M_WAITOK);
728b2e60773SJohn Baldwin 		memcpy(tls_new->params.auth_key, tls->params.auth_key,
729b2e60773SJohn Baldwin 		    tls->params.auth_key_len);
730b2e60773SJohn Baldwin 	}
731b2e60773SJohn Baldwin 
732b2e60773SJohn Baldwin 	tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
733b2e60773SJohn Baldwin 	    M_WAITOK);
734b2e60773SJohn Baldwin 	memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
735b2e60773SJohn Baldwin 	    tls->params.cipher_key_len);
736b2e60773SJohn Baldwin 
737b2e60773SJohn Baldwin 	return (tls_new);
738b2e60773SJohn Baldwin }
739b2e60773SJohn Baldwin #endif
740b2e60773SJohn Baldwin 
741b2e60773SJohn Baldwin static void
742b2e60773SJohn Baldwin ktls_cleanup(struct ktls_session *tls)
743b2e60773SJohn Baldwin {
744b2e60773SJohn Baldwin 
745b2e60773SJohn Baldwin 	counter_u64_add(ktls_offload_active, -1);
7469e14430dSJohn Baldwin 	switch (tls->mode) {
7479e14430dSJohn Baldwin 	case TCP_TLS_MODE_SW:
748b2e60773SJohn Baldwin 		switch (tls->params.cipher_algorithm) {
749b2e60773SJohn Baldwin 		case CRYPTO_AES_CBC:
750b2e60773SJohn Baldwin 			counter_u64_add(ktls_sw_cbc, -1);
751b2e60773SJohn Baldwin 			break;
752b2e60773SJohn Baldwin 		case CRYPTO_AES_NIST_GCM_16:
753b2e60773SJohn Baldwin 			counter_u64_add(ktls_sw_gcm, -1);
754b2e60773SJohn Baldwin 			break;
7559c64fc40SJohn Baldwin 		case CRYPTO_CHACHA20_POLY1305:
7569c64fc40SJohn Baldwin 			counter_u64_add(ktls_sw_chacha20, -1);
7579c64fc40SJohn Baldwin 			break;
758b2e60773SJohn Baldwin 		}
75921e3c1fbSJohn Baldwin 		ktls_ocf_free(tls);
7609e14430dSJohn Baldwin 		break;
7619e14430dSJohn Baldwin 	case TCP_TLS_MODE_IFNET:
762b2e60773SJohn Baldwin 		switch (tls->params.cipher_algorithm) {
763b2e60773SJohn Baldwin 		case CRYPTO_AES_CBC:
764b2e60773SJohn Baldwin 			counter_u64_add(ktls_ifnet_cbc, -1);
765b2e60773SJohn Baldwin 			break;
766b2e60773SJohn Baldwin 		case CRYPTO_AES_NIST_GCM_16:
767b2e60773SJohn Baldwin 			counter_u64_add(ktls_ifnet_gcm, -1);
768b2e60773SJohn Baldwin 			break;
7699c64fc40SJohn Baldwin 		case CRYPTO_CHACHA20_POLY1305:
7709c64fc40SJohn Baldwin 			counter_u64_add(ktls_ifnet_chacha20, -1);
7719c64fc40SJohn Baldwin 			break;
772b2e60773SJohn Baldwin 		}
7739675d889SAndrew Gallatin 		if (tls->snd_tag != NULL)
774b2e60773SJohn Baldwin 			m_snd_tag_rele(tls->snd_tag);
7759e14430dSJohn Baldwin 		break;
7769e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
7779e14430dSJohn Baldwin 	case TCP_TLS_MODE_TOE:
7789e14430dSJohn Baldwin 		switch (tls->params.cipher_algorithm) {
7799e14430dSJohn Baldwin 		case CRYPTO_AES_CBC:
7809e14430dSJohn Baldwin 			counter_u64_add(ktls_toe_cbc, -1);
7819e14430dSJohn Baldwin 			break;
7829e14430dSJohn Baldwin 		case CRYPTO_AES_NIST_GCM_16:
7839e14430dSJohn Baldwin 			counter_u64_add(ktls_toe_gcm, -1);
7849e14430dSJohn Baldwin 			break;
7859c64fc40SJohn Baldwin 		case CRYPTO_CHACHA20_POLY1305:
7869c64fc40SJohn Baldwin 			counter_u64_add(ktls_toe_chacha20, -1);
7879c64fc40SJohn Baldwin 			break;
7889e14430dSJohn Baldwin 		}
7899e14430dSJohn Baldwin 		break;
7909e14430dSJohn Baldwin #endif
791b2e60773SJohn Baldwin 	}
792b2e60773SJohn Baldwin 	if (tls->params.auth_key != NULL) {
7934a711b8dSJohn Baldwin 		zfree(tls->params.auth_key, M_KTLS);
794b2e60773SJohn Baldwin 		tls->params.auth_key = NULL;
795b2e60773SJohn Baldwin 		tls->params.auth_key_len = 0;
796b2e60773SJohn Baldwin 	}
797b2e60773SJohn Baldwin 	if (tls->params.cipher_key != NULL) {
7984a711b8dSJohn Baldwin 		zfree(tls->params.cipher_key, M_KTLS);
799b2e60773SJohn Baldwin 		tls->params.cipher_key = NULL;
800b2e60773SJohn Baldwin 		tls->params.cipher_key_len = 0;
801b2e60773SJohn Baldwin 	}
802b2e60773SJohn Baldwin 	explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
803b2e60773SJohn Baldwin }
804b2e60773SJohn Baldwin 
805b2e60773SJohn Baldwin #if defined(INET) || defined(INET6)
8069e14430dSJohn Baldwin 
8079e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
8089e14430dSJohn Baldwin static int
809f1f93475SJohn Baldwin ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
8109e14430dSJohn Baldwin {
8119e14430dSJohn Baldwin 	struct inpcb *inp;
8129e14430dSJohn Baldwin 	struct tcpcb *tp;
8139e14430dSJohn Baldwin 	int error;
8149e14430dSJohn Baldwin 
8159e14430dSJohn Baldwin 	inp = so->so_pcb;
8169e14430dSJohn Baldwin 	INP_WLOCK(inp);
8179e14430dSJohn Baldwin 	if (inp->inp_flags2 & INP_FREED) {
8189e14430dSJohn Baldwin 		INP_WUNLOCK(inp);
8199e14430dSJohn Baldwin 		return (ECONNRESET);
8209e14430dSJohn Baldwin 	}
8219e14430dSJohn Baldwin 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
8229e14430dSJohn Baldwin 		INP_WUNLOCK(inp);
8239e14430dSJohn Baldwin 		return (ECONNRESET);
8249e14430dSJohn Baldwin 	}
8259e14430dSJohn Baldwin 	if (inp->inp_socket == NULL) {
8269e14430dSJohn Baldwin 		INP_WUNLOCK(inp);
8279e14430dSJohn Baldwin 		return (ECONNRESET);
8289e14430dSJohn Baldwin 	}
8299e14430dSJohn Baldwin 	tp = intotcpcb(inp);
8306bcf3c46SJohn Baldwin 	if (!(tp->t_flags & TF_TOE)) {
8319e14430dSJohn Baldwin 		INP_WUNLOCK(inp);
8329e14430dSJohn Baldwin 		return (EOPNOTSUPP);
8339e14430dSJohn Baldwin 	}
8349e14430dSJohn Baldwin 
835f1f93475SJohn Baldwin 	error = tcp_offload_alloc_tls_session(tp, tls, direction);
8369e14430dSJohn Baldwin 	INP_WUNLOCK(inp);
8379e14430dSJohn Baldwin 	if (error == 0) {
8389e14430dSJohn Baldwin 		tls->mode = TCP_TLS_MODE_TOE;
8399e14430dSJohn Baldwin 		switch (tls->params.cipher_algorithm) {
8409e14430dSJohn Baldwin 		case CRYPTO_AES_CBC:
8419e14430dSJohn Baldwin 			counter_u64_add(ktls_toe_cbc, 1);
8429e14430dSJohn Baldwin 			break;
8439e14430dSJohn Baldwin 		case CRYPTO_AES_NIST_GCM_16:
8449e14430dSJohn Baldwin 			counter_u64_add(ktls_toe_gcm, 1);
8459e14430dSJohn Baldwin 			break;
8469c64fc40SJohn Baldwin 		case CRYPTO_CHACHA20_POLY1305:
8479c64fc40SJohn Baldwin 			counter_u64_add(ktls_toe_chacha20, 1);
8489c64fc40SJohn Baldwin 			break;
8499e14430dSJohn Baldwin 		}
8509e14430dSJohn Baldwin 	}
8519e14430dSJohn Baldwin 	return (error);
8529e14430dSJohn Baldwin }
8539e14430dSJohn Baldwin #endif
8549e14430dSJohn Baldwin 
855b2e60773SJohn Baldwin /*
856b2e60773SJohn Baldwin  * Common code used when first enabling ifnet TLS on a connection or
857b2e60773SJohn Baldwin  * when allocating a new ifnet TLS session due to a routing change.
858b2e60773SJohn Baldwin  * This function allocates a new TLS send tag on whatever interface
859b2e60773SJohn Baldwin  * the connection is currently routed over.
860b2e60773SJohn Baldwin  */
861b2e60773SJohn Baldwin static int
862b2e60773SJohn Baldwin ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
863b2e60773SJohn Baldwin     struct m_snd_tag **mstp)
864b2e60773SJohn Baldwin {
865b2e60773SJohn Baldwin 	union if_snd_tag_alloc_params params;
866b2e60773SJohn Baldwin 	struct ifnet *ifp;
867983066f0SAlexander V. Chernikov 	struct nhop_object *nh;
868b2e60773SJohn Baldwin 	struct tcpcb *tp;
869b2e60773SJohn Baldwin 	int error;
870b2e60773SJohn Baldwin 
871b2e60773SJohn Baldwin 	INP_RLOCK(inp);
872b2e60773SJohn Baldwin 	if (inp->inp_flags2 & INP_FREED) {
873b2e60773SJohn Baldwin 		INP_RUNLOCK(inp);
874b2e60773SJohn Baldwin 		return (ECONNRESET);
875b2e60773SJohn Baldwin 	}
876b2e60773SJohn Baldwin 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
877b2e60773SJohn Baldwin 		INP_RUNLOCK(inp);
878b2e60773SJohn Baldwin 		return (ECONNRESET);
879b2e60773SJohn Baldwin 	}
880b2e60773SJohn Baldwin 	if (inp->inp_socket == NULL) {
881b2e60773SJohn Baldwin 		INP_RUNLOCK(inp);
882b2e60773SJohn Baldwin 		return (ECONNRESET);
883b2e60773SJohn Baldwin 	}
884b2e60773SJohn Baldwin 	tp = intotcpcb(inp);
885b2e60773SJohn Baldwin 
886b2e60773SJohn Baldwin 	/*
887b2e60773SJohn Baldwin 	 * Check administrative controls on ifnet TLS to determine if
888b2e60773SJohn Baldwin 	 * ifnet TLS should be denied.
889b2e60773SJohn Baldwin 	 *
890b2e60773SJohn Baldwin 	 * - Always permit 'force' requests.
891b2e60773SJohn Baldwin 	 * - ktls_ifnet_permitted == 0: always deny.
892b2e60773SJohn Baldwin 	 */
893b2e60773SJohn Baldwin 	if (!force && ktls_ifnet_permitted == 0) {
894b2e60773SJohn Baldwin 		INP_RUNLOCK(inp);
895b2e60773SJohn Baldwin 		return (ENXIO);
896b2e60773SJohn Baldwin 	}
897b2e60773SJohn Baldwin 
898b2e60773SJohn Baldwin 	/*
899b2e60773SJohn Baldwin 	 * XXX: Use the cached route in the inpcb to find the
900b2e60773SJohn Baldwin 	 * interface.  This should perhaps instead use
901b2e60773SJohn Baldwin 	 * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
902b2e60773SJohn Baldwin 	 * enabled after a connection has completed key negotiation in
903b2e60773SJohn Baldwin 	 * userland, the cached route will be present in practice.
904b2e60773SJohn Baldwin 	 */
905983066f0SAlexander V. Chernikov 	nh = inp->inp_route.ro_nh;
906983066f0SAlexander V. Chernikov 	if (nh == NULL) {
907b2e60773SJohn Baldwin 		INP_RUNLOCK(inp);
908b2e60773SJohn Baldwin 		return (ENXIO);
909b2e60773SJohn Baldwin 	}
910983066f0SAlexander V. Chernikov 	ifp = nh->nh_ifp;
911b2e60773SJohn Baldwin 	if_ref(ifp);
912b2e60773SJohn Baldwin 
913521eac97SJohn Baldwin 	/*
914521eac97SJohn Baldwin 	 * Allocate a TLS + ratelimit tag if the connection has an
915521eac97SJohn Baldwin 	 * existing pacing rate.
916521eac97SJohn Baldwin 	 */
917521eac97SJohn Baldwin 	if (tp->t_pacing_rate != -1 &&
918521eac97SJohn Baldwin 	    (ifp->if_capenable & IFCAP_TXTLS_RTLMT) != 0) {
919521eac97SJohn Baldwin 		params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
920521eac97SJohn Baldwin 		params.tls_rate_limit.inp = inp;
921521eac97SJohn Baldwin 		params.tls_rate_limit.tls = tls;
922521eac97SJohn Baldwin 		params.tls_rate_limit.max_rate = tp->t_pacing_rate;
923521eac97SJohn Baldwin 	} else {
924b2e60773SJohn Baldwin 		params.hdr.type = IF_SND_TAG_TYPE_TLS;
925521eac97SJohn Baldwin 		params.tls.inp = inp;
926521eac97SJohn Baldwin 		params.tls.tls = tls;
927521eac97SJohn Baldwin 	}
928b2e60773SJohn Baldwin 	params.hdr.flowid = inp->inp_flowid;
929b2e60773SJohn Baldwin 	params.hdr.flowtype = inp->inp_flowtype;
93098085baeSAndrew Gallatin 	params.hdr.numa_domain = inp->inp_numa_domain;
931b2e60773SJohn Baldwin 	INP_RUNLOCK(inp);
932b2e60773SJohn Baldwin 
9333f43ada9SGleb Smirnoff 	if ((ifp->if_capenable & IFCAP_MEXTPG) == 0) {
934b2e60773SJohn Baldwin 		error = EOPNOTSUPP;
935b2e60773SJohn Baldwin 		goto out;
936b2e60773SJohn Baldwin 	}
937b2e60773SJohn Baldwin 	if (inp->inp_vflag & INP_IPV6) {
938b2e60773SJohn Baldwin 		if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
939b2e60773SJohn Baldwin 			error = EOPNOTSUPP;
940b2e60773SJohn Baldwin 			goto out;
941b2e60773SJohn Baldwin 		}
942b2e60773SJohn Baldwin 	} else {
943b2e60773SJohn Baldwin 		if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
944b2e60773SJohn Baldwin 			error = EOPNOTSUPP;
945b2e60773SJohn Baldwin 			goto out;
946b2e60773SJohn Baldwin 		}
947b2e60773SJohn Baldwin 	}
94836e0a362SJohn Baldwin 	error = m_snd_tag_alloc(ifp, &params, mstp);
949b2e60773SJohn Baldwin out:
950b2e60773SJohn Baldwin 	if_rele(ifp);
951b2e60773SJohn Baldwin 	return (error);
952b2e60773SJohn Baldwin }
953b2e60773SJohn Baldwin 
954b2e60773SJohn Baldwin static int
955b2e60773SJohn Baldwin ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
956b2e60773SJohn Baldwin {
957b2e60773SJohn Baldwin 	struct m_snd_tag *mst;
958b2e60773SJohn Baldwin 	int error;
959b2e60773SJohn Baldwin 
960b2e60773SJohn Baldwin 	error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
961b2e60773SJohn Baldwin 	if (error == 0) {
9629e14430dSJohn Baldwin 		tls->mode = TCP_TLS_MODE_IFNET;
963b2e60773SJohn Baldwin 		tls->snd_tag = mst;
964b2e60773SJohn Baldwin 		switch (tls->params.cipher_algorithm) {
965b2e60773SJohn Baldwin 		case CRYPTO_AES_CBC:
966b2e60773SJohn Baldwin 			counter_u64_add(ktls_ifnet_cbc, 1);
967b2e60773SJohn Baldwin 			break;
968b2e60773SJohn Baldwin 		case CRYPTO_AES_NIST_GCM_16:
969b2e60773SJohn Baldwin 			counter_u64_add(ktls_ifnet_gcm, 1);
970b2e60773SJohn Baldwin 			break;
9719c64fc40SJohn Baldwin 		case CRYPTO_CHACHA20_POLY1305:
9729c64fc40SJohn Baldwin 			counter_u64_add(ktls_ifnet_chacha20, 1);
9739c64fc40SJohn Baldwin 			break;
974b2e60773SJohn Baldwin 		}
975b2e60773SJohn Baldwin 	}
976b2e60773SJohn Baldwin 	return (error);
977b2e60773SJohn Baldwin }
978b2e60773SJohn Baldwin 
979b2e60773SJohn Baldwin static int
9803c0e5685SJohn Baldwin ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
981b2e60773SJohn Baldwin {
98221e3c1fbSJohn Baldwin 	int error;
983b2e60773SJohn Baldwin 
98421e3c1fbSJohn Baldwin 	error = ktls_ocf_try(so, tls, direction);
98521e3c1fbSJohn Baldwin 	if (error)
98621e3c1fbSJohn Baldwin 		return (error);
9879e14430dSJohn Baldwin 	tls->mode = TCP_TLS_MODE_SW;
988b2e60773SJohn Baldwin 	switch (tls->params.cipher_algorithm) {
989b2e60773SJohn Baldwin 	case CRYPTO_AES_CBC:
990b2e60773SJohn Baldwin 		counter_u64_add(ktls_sw_cbc, 1);
991b2e60773SJohn Baldwin 		break;
992b2e60773SJohn Baldwin 	case CRYPTO_AES_NIST_GCM_16:
993b2e60773SJohn Baldwin 		counter_u64_add(ktls_sw_gcm, 1);
994b2e60773SJohn Baldwin 		break;
9959c64fc40SJohn Baldwin 	case CRYPTO_CHACHA20_POLY1305:
9969c64fc40SJohn Baldwin 		counter_u64_add(ktls_sw_chacha20, 1);
9979c64fc40SJohn Baldwin 		break;
998b2e60773SJohn Baldwin 	}
999b2e60773SJohn Baldwin 	return (0);
1000b2e60773SJohn Baldwin }
1001b2e60773SJohn Baldwin 
10023c0e5685SJohn Baldwin /*
10033c0e5685SJohn Baldwin  * KTLS RX stores data in the socket buffer as a list of TLS records,
10043c0e5685SJohn Baldwin  * where each record is stored as a control message containg the TLS
10053c0e5685SJohn Baldwin  * header followed by data mbufs containing the decrypted data.  This
10063c0e5685SJohn Baldwin  * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
10073c0e5685SJohn Baldwin  * both encrypted and decrypted data.  TLS records decrypted by a NIC
10083c0e5685SJohn Baldwin  * should be queued to the socket buffer as records, but encrypted
10093c0e5685SJohn Baldwin  * data which needs to be decrypted by software arrives as a stream of
10103c0e5685SJohn Baldwin  * regular mbufs which need to be converted.  In addition, there may
10113c0e5685SJohn Baldwin  * already be pending encrypted data in the socket buffer when KTLS RX
10123c0e5685SJohn Baldwin  * is enabled.
10133c0e5685SJohn Baldwin  *
10143c0e5685SJohn Baldwin  * To manage not-yet-decrypted data for KTLS RX, the following scheme
10153c0e5685SJohn Baldwin  * is used:
10163c0e5685SJohn Baldwin  *
10173c0e5685SJohn Baldwin  * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
10183c0e5685SJohn Baldwin  *
10193c0e5685SJohn Baldwin  * - ktls_check_rx checks this chain of mbufs reading the TLS header
10203c0e5685SJohn Baldwin  *   from the first mbuf.  Once all of the data for that TLS record is
10213c0e5685SJohn Baldwin  *   queued, the socket is queued to a worker thread.
10223c0e5685SJohn Baldwin  *
10233c0e5685SJohn Baldwin  * - The worker thread calls ktls_decrypt to decrypt TLS records in
10243c0e5685SJohn Baldwin  *   the TLS chain.  Each TLS record is detached from the TLS chain,
10253c0e5685SJohn Baldwin  *   decrypted, and inserted into the regular socket buffer chain as
10263c0e5685SJohn Baldwin  *   record starting with a control message holding the TLS header and
10273c0e5685SJohn Baldwin  *   a chain of mbufs holding the encrypted data.
10283c0e5685SJohn Baldwin  */
10293c0e5685SJohn Baldwin 
10303c0e5685SJohn Baldwin static void
10313c0e5685SJohn Baldwin sb_mark_notready(struct sockbuf *sb)
10323c0e5685SJohn Baldwin {
10333c0e5685SJohn Baldwin 	struct mbuf *m;
10343c0e5685SJohn Baldwin 
10353c0e5685SJohn Baldwin 	m = sb->sb_mb;
10363c0e5685SJohn Baldwin 	sb->sb_mtls = m;
10373c0e5685SJohn Baldwin 	sb->sb_mb = NULL;
10383c0e5685SJohn Baldwin 	sb->sb_mbtail = NULL;
10393c0e5685SJohn Baldwin 	sb->sb_lastrecord = NULL;
10403c0e5685SJohn Baldwin 	for (; m != NULL; m = m->m_next) {
10413c0e5685SJohn Baldwin 		KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
10423c0e5685SJohn Baldwin 		    __func__));
10433c0e5685SJohn Baldwin 		KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
10443c0e5685SJohn Baldwin 		    __func__));
10453c0e5685SJohn Baldwin 		KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
10463c0e5685SJohn Baldwin 		    __func__));
10473c0e5685SJohn Baldwin 		m->m_flags |= M_NOTREADY;
10483c0e5685SJohn Baldwin 		sb->sb_acc -= m->m_len;
10493c0e5685SJohn Baldwin 		sb->sb_tlscc += m->m_len;
10503c0e5685SJohn Baldwin 		sb->sb_mtlstail = m;
10513c0e5685SJohn Baldwin 	}
10523c0e5685SJohn Baldwin 	KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
10533c0e5685SJohn Baldwin 	    ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
10543c0e5685SJohn Baldwin 	    sb->sb_ccc));
10553c0e5685SJohn Baldwin }
10563c0e5685SJohn Baldwin 
1057b2e60773SJohn Baldwin int
1058f1f93475SJohn Baldwin ktls_enable_rx(struct socket *so, struct tls_enable *en)
1059f1f93475SJohn Baldwin {
1060f1f93475SJohn Baldwin 	struct ktls_session *tls;
1061f1f93475SJohn Baldwin 	int error;
1062f1f93475SJohn Baldwin 
1063f1f93475SJohn Baldwin 	if (!ktls_offload_enable)
1064f1f93475SJohn Baldwin 		return (ENOTSUP);
10656685e259SMichael Tuexen 	if (SOLISTENING(so))
10666685e259SMichael Tuexen 		return (EINVAL);
1067f1f93475SJohn Baldwin 
1068f1f93475SJohn Baldwin 	counter_u64_add(ktls_offload_enable_calls, 1);
1069f1f93475SJohn Baldwin 
1070f1f93475SJohn Baldwin 	/*
1071f1f93475SJohn Baldwin 	 * This should always be true since only the TCP socket option
1072f1f93475SJohn Baldwin 	 * invokes this function.
1073f1f93475SJohn Baldwin 	 */
1074f1f93475SJohn Baldwin 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1075f1f93475SJohn Baldwin 		return (EINVAL);
1076f1f93475SJohn Baldwin 
1077f1f93475SJohn Baldwin 	/*
1078f1f93475SJohn Baldwin 	 * XXX: Don't overwrite existing sessions.  We should permit
1079f1f93475SJohn Baldwin 	 * this to support rekeying in the future.
1080f1f93475SJohn Baldwin 	 */
1081f1f93475SJohn Baldwin 	if (so->so_rcv.sb_tls_info != NULL)
1082f1f93475SJohn Baldwin 		return (EALREADY);
1083f1f93475SJohn Baldwin 
1084f1f93475SJohn Baldwin 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1085f1f93475SJohn Baldwin 		return (ENOTSUP);
1086f1f93475SJohn Baldwin 
10873c0e5685SJohn Baldwin 	/* TLS 1.3 is not yet supported. */
10883c0e5685SJohn Baldwin 	if (en->tls_vmajor == TLS_MAJOR_VER_ONE &&
10893c0e5685SJohn Baldwin 	    en->tls_vminor == TLS_MINOR_VER_THREE)
10903c0e5685SJohn Baldwin 		return (ENOTSUP);
10913c0e5685SJohn Baldwin 
1092f1f93475SJohn Baldwin 	error = ktls_create_session(so, en, &tls);
1093f1f93475SJohn Baldwin 	if (error)
1094f1f93475SJohn Baldwin 		return (error);
1095f1f93475SJohn Baldwin 
1096f1f93475SJohn Baldwin #ifdef TCP_OFFLOAD
1097f1f93475SJohn Baldwin 	error = ktls_try_toe(so, tls, KTLS_RX);
10983c0e5685SJohn Baldwin 	if (error)
1099f1f93475SJohn Baldwin #endif
11003c0e5685SJohn Baldwin 		error = ktls_try_sw(so, tls, KTLS_RX);
1101f1f93475SJohn Baldwin 
1102f1f93475SJohn Baldwin 	if (error) {
1103f1f93475SJohn Baldwin 		ktls_cleanup(tls);
1104f1f93475SJohn Baldwin 		return (error);
1105f1f93475SJohn Baldwin 	}
1106f1f93475SJohn Baldwin 
1107f1f93475SJohn Baldwin 	/* Mark the socket as using TLS offload. */
1108f1f93475SJohn Baldwin 	SOCKBUF_LOCK(&so->so_rcv);
11093c0e5685SJohn Baldwin 	so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1110f1f93475SJohn Baldwin 	so->so_rcv.sb_tls_info = tls;
11113c0e5685SJohn Baldwin 	so->so_rcv.sb_flags |= SB_TLS_RX;
11123c0e5685SJohn Baldwin 
11133c0e5685SJohn Baldwin 	/* Mark existing data as not ready until it can be decrypted. */
1114faf0224fSJohn Baldwin 	if (tls->mode != TCP_TLS_MODE_TOE) {
11153c0e5685SJohn Baldwin 		sb_mark_notready(&so->so_rcv);
11163c0e5685SJohn Baldwin 		ktls_check_rx(&so->so_rcv);
1117faf0224fSJohn Baldwin 	}
1118f1f93475SJohn Baldwin 	SOCKBUF_UNLOCK(&so->so_rcv);
1119f1f93475SJohn Baldwin 
1120f1f93475SJohn Baldwin 	counter_u64_add(ktls_offload_total, 1);
1121f1f93475SJohn Baldwin 
1122f1f93475SJohn Baldwin 	return (0);
1123f1f93475SJohn Baldwin }
1124f1f93475SJohn Baldwin 
1125f1f93475SJohn Baldwin int
1126b2e60773SJohn Baldwin ktls_enable_tx(struct socket *so, struct tls_enable *en)
1127b2e60773SJohn Baldwin {
1128b2e60773SJohn Baldwin 	struct ktls_session *tls;
1129521eac97SJohn Baldwin 	struct inpcb *inp;
1130b2e60773SJohn Baldwin 	int error;
1131b2e60773SJohn Baldwin 
1132b2e60773SJohn Baldwin 	if (!ktls_offload_enable)
1133b2e60773SJohn Baldwin 		return (ENOTSUP);
11346685e259SMichael Tuexen 	if (SOLISTENING(so))
11356685e259SMichael Tuexen 		return (EINVAL);
1136b2e60773SJohn Baldwin 
1137b2e60773SJohn Baldwin 	counter_u64_add(ktls_offload_enable_calls, 1);
1138b2e60773SJohn Baldwin 
1139b2e60773SJohn Baldwin 	/*
1140b2e60773SJohn Baldwin 	 * This should always be true since only the TCP socket option
1141b2e60773SJohn Baldwin 	 * invokes this function.
1142b2e60773SJohn Baldwin 	 */
1143b2e60773SJohn Baldwin 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1144b2e60773SJohn Baldwin 		return (EINVAL);
1145b2e60773SJohn Baldwin 
1146b2e60773SJohn Baldwin 	/*
1147b2e60773SJohn Baldwin 	 * XXX: Don't overwrite existing sessions.  We should permit
1148b2e60773SJohn Baldwin 	 * this to support rekeying in the future.
1149b2e60773SJohn Baldwin 	 */
1150b2e60773SJohn Baldwin 	if (so->so_snd.sb_tls_info != NULL)
1151b2e60773SJohn Baldwin 		return (EALREADY);
1152b2e60773SJohn Baldwin 
1153b2e60773SJohn Baldwin 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1154b2e60773SJohn Baldwin 		return (ENOTSUP);
1155b2e60773SJohn Baldwin 
1156b2e60773SJohn Baldwin 	/* TLS requires ext pgs */
1157b2e60773SJohn Baldwin 	if (mb_use_ext_pgs == 0)
1158b2e60773SJohn Baldwin 		return (ENXIO);
1159b2e60773SJohn Baldwin 
1160b2e60773SJohn Baldwin 	error = ktls_create_session(so, en, &tls);
1161b2e60773SJohn Baldwin 	if (error)
1162b2e60773SJohn Baldwin 		return (error);
1163b2e60773SJohn Baldwin 
11649e14430dSJohn Baldwin 	/* Prefer TOE -> ifnet TLS -> software TLS. */
11659e14430dSJohn Baldwin #ifdef TCP_OFFLOAD
1166f1f93475SJohn Baldwin 	error = ktls_try_toe(so, tls, KTLS_TX);
11679e14430dSJohn Baldwin 	if (error)
11689e14430dSJohn Baldwin #endif
1169b2e60773SJohn Baldwin 		error = ktls_try_ifnet(so, tls, false);
1170b2e60773SJohn Baldwin 	if (error)
11713c0e5685SJohn Baldwin 		error = ktls_try_sw(so, tls, KTLS_TX);
1172b2e60773SJohn Baldwin 
1173b2e60773SJohn Baldwin 	if (error) {
1174b2e60773SJohn Baldwin 		ktls_cleanup(tls);
1175b2e60773SJohn Baldwin 		return (error);
1176b2e60773SJohn Baldwin 	}
1177b2e60773SJohn Baldwin 
1178f94acf52SMark Johnston 	error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1179b2e60773SJohn Baldwin 	if (error) {
1180b2e60773SJohn Baldwin 		ktls_cleanup(tls);
1181b2e60773SJohn Baldwin 		return (error);
1182b2e60773SJohn Baldwin 	}
1183b2e60773SJohn Baldwin 
1184521eac97SJohn Baldwin 	/*
1185521eac97SJohn Baldwin 	 * Write lock the INP when setting sb_tls_info so that
1186521eac97SJohn Baldwin 	 * routines in tcp_ratelimit.c can read sb_tls_info while
1187521eac97SJohn Baldwin 	 * holding the INP lock.
1188521eac97SJohn Baldwin 	 */
1189521eac97SJohn Baldwin 	inp = so->so_pcb;
1190521eac97SJohn Baldwin 	INP_WLOCK(inp);
1191b2e60773SJohn Baldwin 	SOCKBUF_LOCK(&so->so_snd);
1192ec1db6e1SJohn Baldwin 	so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1193b2e60773SJohn Baldwin 	so->so_snd.sb_tls_info = tls;
11949e14430dSJohn Baldwin 	if (tls->mode != TCP_TLS_MODE_SW)
1195b2e60773SJohn Baldwin 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1196b2e60773SJohn Baldwin 	SOCKBUF_UNLOCK(&so->so_snd);
1197521eac97SJohn Baldwin 	INP_WUNLOCK(inp);
1198f94acf52SMark Johnston 	SOCK_IO_SEND_UNLOCK(so);
1199b2e60773SJohn Baldwin 
1200b2e60773SJohn Baldwin 	counter_u64_add(ktls_offload_total, 1);
1201b2e60773SJohn Baldwin 
1202b2e60773SJohn Baldwin 	return (0);
1203b2e60773SJohn Baldwin }
1204b2e60773SJohn Baldwin 
1205b2e60773SJohn Baldwin int
1206bf256782SMark Johnston ktls_get_rx_mode(struct socket *so, int *modep)
1207f1f93475SJohn Baldwin {
1208f1f93475SJohn Baldwin 	struct ktls_session *tls;
1209f1f93475SJohn Baldwin 	struct inpcb *inp;
1210f1f93475SJohn Baldwin 
12116685e259SMichael Tuexen 	if (SOLISTENING(so))
12126685e259SMichael Tuexen 		return (EINVAL);
1213f1f93475SJohn Baldwin 	inp = so->so_pcb;
1214f1f93475SJohn Baldwin 	INP_WLOCK_ASSERT(inp);
1215bf256782SMark Johnston 	SOCK_RECVBUF_LOCK(so);
1216f1f93475SJohn Baldwin 	tls = so->so_rcv.sb_tls_info;
1217f1f93475SJohn Baldwin 	if (tls == NULL)
1218bf256782SMark Johnston 		*modep = TCP_TLS_MODE_NONE;
1219f1f93475SJohn Baldwin 	else
1220bf256782SMark Johnston 		*modep = tls->mode;
1221bf256782SMark Johnston 	SOCK_RECVBUF_UNLOCK(so);
1222bf256782SMark Johnston 	return (0);
1223f1f93475SJohn Baldwin }
1224f1f93475SJohn Baldwin 
1225f1f93475SJohn Baldwin int
1226bf256782SMark Johnston ktls_get_tx_mode(struct socket *so, int *modep)
1227b2e60773SJohn Baldwin {
1228b2e60773SJohn Baldwin 	struct ktls_session *tls;
1229b2e60773SJohn Baldwin 	struct inpcb *inp;
1230b2e60773SJohn Baldwin 
12316685e259SMichael Tuexen 	if (SOLISTENING(so))
12326685e259SMichael Tuexen 		return (EINVAL);
1233b2e60773SJohn Baldwin 	inp = so->so_pcb;
1234b2e60773SJohn Baldwin 	INP_WLOCK_ASSERT(inp);
1235bf256782SMark Johnston 	SOCK_SENDBUF_LOCK(so);
1236b2e60773SJohn Baldwin 	tls = so->so_snd.sb_tls_info;
1237b2e60773SJohn Baldwin 	if (tls == NULL)
1238bf256782SMark Johnston 		*modep = TCP_TLS_MODE_NONE;
1239b2e60773SJohn Baldwin 	else
1240bf256782SMark Johnston 		*modep = tls->mode;
1241bf256782SMark Johnston 	SOCK_SENDBUF_UNLOCK(so);
1242bf256782SMark Johnston 	return (0);
1243b2e60773SJohn Baldwin }
1244b2e60773SJohn Baldwin 
1245b2e60773SJohn Baldwin /*
1246b2e60773SJohn Baldwin  * Switch between SW and ifnet TLS sessions as requested.
1247b2e60773SJohn Baldwin  */
1248b2e60773SJohn Baldwin int
1249b2e60773SJohn Baldwin ktls_set_tx_mode(struct socket *so, int mode)
1250b2e60773SJohn Baldwin {
1251b2e60773SJohn Baldwin 	struct ktls_session *tls, *tls_new;
1252b2e60773SJohn Baldwin 	struct inpcb *inp;
1253b2e60773SJohn Baldwin 	int error;
1254b2e60773SJohn Baldwin 
12556685e259SMichael Tuexen 	if (SOLISTENING(so))
12566685e259SMichael Tuexen 		return (EINVAL);
12579e14430dSJohn Baldwin 	switch (mode) {
12589e14430dSJohn Baldwin 	case TCP_TLS_MODE_SW:
12599e14430dSJohn Baldwin 	case TCP_TLS_MODE_IFNET:
12609e14430dSJohn Baldwin 		break;
12619e14430dSJohn Baldwin 	default:
12629e14430dSJohn Baldwin 		return (EINVAL);
12639e14430dSJohn Baldwin 	}
1264b2e60773SJohn Baldwin 
1265b2e60773SJohn Baldwin 	inp = so->so_pcb;
1266b2e60773SJohn Baldwin 	INP_WLOCK_ASSERT(inp);
1267b2e60773SJohn Baldwin 	SOCKBUF_LOCK(&so->so_snd);
1268b2e60773SJohn Baldwin 	tls = so->so_snd.sb_tls_info;
1269b2e60773SJohn Baldwin 	if (tls == NULL) {
1270b2e60773SJohn Baldwin 		SOCKBUF_UNLOCK(&so->so_snd);
1271b2e60773SJohn Baldwin 		return (0);
1272b2e60773SJohn Baldwin 	}
1273b2e60773SJohn Baldwin 
12749e14430dSJohn Baldwin 	if (tls->mode == mode) {
1275b2e60773SJohn Baldwin 		SOCKBUF_UNLOCK(&so->so_snd);
1276b2e60773SJohn Baldwin 		return (0);
1277b2e60773SJohn Baldwin 	}
1278b2e60773SJohn Baldwin 
1279b2e60773SJohn Baldwin 	tls = ktls_hold(tls);
1280b2e60773SJohn Baldwin 	SOCKBUF_UNLOCK(&so->so_snd);
1281b2e60773SJohn Baldwin 	INP_WUNLOCK(inp);
1282b2e60773SJohn Baldwin 
1283b2e60773SJohn Baldwin 	tls_new = ktls_clone_session(tls);
1284b2e60773SJohn Baldwin 
1285b2e60773SJohn Baldwin 	if (mode == TCP_TLS_MODE_IFNET)
1286b2e60773SJohn Baldwin 		error = ktls_try_ifnet(so, tls_new, true);
1287b2e60773SJohn Baldwin 	else
12883c0e5685SJohn Baldwin 		error = ktls_try_sw(so, tls_new, KTLS_TX);
1289b2e60773SJohn Baldwin 	if (error) {
1290b2e60773SJohn Baldwin 		counter_u64_add(ktls_switch_failed, 1);
1291b2e60773SJohn Baldwin 		ktls_free(tls_new);
1292b2e60773SJohn Baldwin 		ktls_free(tls);
1293b2e60773SJohn Baldwin 		INP_WLOCK(inp);
1294b2e60773SJohn Baldwin 		return (error);
1295b2e60773SJohn Baldwin 	}
1296b2e60773SJohn Baldwin 
1297f94acf52SMark Johnston 	error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1298b2e60773SJohn Baldwin 	if (error) {
1299b2e60773SJohn Baldwin 		counter_u64_add(ktls_switch_failed, 1);
1300b2e60773SJohn Baldwin 		ktls_free(tls_new);
1301b2e60773SJohn Baldwin 		ktls_free(tls);
1302b2e60773SJohn Baldwin 		INP_WLOCK(inp);
1303b2e60773SJohn Baldwin 		return (error);
1304b2e60773SJohn Baldwin 	}
1305b2e60773SJohn Baldwin 
1306b2e60773SJohn Baldwin 	/*
1307b2e60773SJohn Baldwin 	 * If we raced with another session change, keep the existing
1308b2e60773SJohn Baldwin 	 * session.
1309b2e60773SJohn Baldwin 	 */
1310b2e60773SJohn Baldwin 	if (tls != so->so_snd.sb_tls_info) {
1311b2e60773SJohn Baldwin 		counter_u64_add(ktls_switch_failed, 1);
1312f94acf52SMark Johnston 		SOCK_IO_SEND_UNLOCK(so);
1313b2e60773SJohn Baldwin 		ktls_free(tls_new);
1314b2e60773SJohn Baldwin 		ktls_free(tls);
1315b2e60773SJohn Baldwin 		INP_WLOCK(inp);
1316b2e60773SJohn Baldwin 		return (EBUSY);
1317b2e60773SJohn Baldwin 	}
1318b2e60773SJohn Baldwin 
1319b2e60773SJohn Baldwin 	SOCKBUF_LOCK(&so->so_snd);
1320b2e60773SJohn Baldwin 	so->so_snd.sb_tls_info = tls_new;
13219e14430dSJohn Baldwin 	if (tls_new->mode != TCP_TLS_MODE_SW)
1322b2e60773SJohn Baldwin 		so->so_snd.sb_flags |= SB_TLS_IFNET;
1323b2e60773SJohn Baldwin 	SOCKBUF_UNLOCK(&so->so_snd);
1324f94acf52SMark Johnston 	SOCK_IO_SEND_UNLOCK(so);
1325b2e60773SJohn Baldwin 
1326b2e60773SJohn Baldwin 	/*
1327b2e60773SJohn Baldwin 	 * Drop two references on 'tls'.  The first is for the
1328b2e60773SJohn Baldwin 	 * ktls_hold() above.  The second drops the reference from the
1329b2e60773SJohn Baldwin 	 * socket buffer.
1330b2e60773SJohn Baldwin 	 */
1331b2e60773SJohn Baldwin 	KASSERT(tls->refcount >= 2, ("too few references on old session"));
1332b2e60773SJohn Baldwin 	ktls_free(tls);
1333b2e60773SJohn Baldwin 	ktls_free(tls);
1334b2e60773SJohn Baldwin 
1335b2e60773SJohn Baldwin 	if (mode == TCP_TLS_MODE_IFNET)
1336b2e60773SJohn Baldwin 		counter_u64_add(ktls_switch_to_ifnet, 1);
1337b2e60773SJohn Baldwin 	else
1338b2e60773SJohn Baldwin 		counter_u64_add(ktls_switch_to_sw, 1);
1339b2e60773SJohn Baldwin 
1340b2e60773SJohn Baldwin 	INP_WLOCK(inp);
1341b2e60773SJohn Baldwin 	return (0);
1342b2e60773SJohn Baldwin }
1343b2e60773SJohn Baldwin 
1344b2e60773SJohn Baldwin /*
1345b2e60773SJohn Baldwin  * Try to allocate a new TLS send tag.  This task is scheduled when
1346b2e60773SJohn Baldwin  * ip_output detects a route change while trying to transmit a packet
1347b2e60773SJohn Baldwin  * holding a TLS record.  If a new tag is allocated, replace the tag
1348b2e60773SJohn Baldwin  * in the TLS session.  Subsequent packets on the connection will use
1349b2e60773SJohn Baldwin  * the new tag.  If a new tag cannot be allocated, drop the
1350b2e60773SJohn Baldwin  * connection.
1351b2e60773SJohn Baldwin  */
1352b2e60773SJohn Baldwin static void
1353b2e60773SJohn Baldwin ktls_reset_send_tag(void *context, int pending)
1354b2e60773SJohn Baldwin {
1355b2e60773SJohn Baldwin 	struct epoch_tracker et;
1356b2e60773SJohn Baldwin 	struct ktls_session *tls;
1357b2e60773SJohn Baldwin 	struct m_snd_tag *old, *new;
1358b2e60773SJohn Baldwin 	struct inpcb *inp;
1359b2e60773SJohn Baldwin 	struct tcpcb *tp;
1360b2e60773SJohn Baldwin 	int error;
1361b2e60773SJohn Baldwin 
1362b2e60773SJohn Baldwin 	MPASS(pending == 1);
1363b2e60773SJohn Baldwin 
1364b2e60773SJohn Baldwin 	tls = context;
1365b2e60773SJohn Baldwin 	inp = tls->inp;
1366b2e60773SJohn Baldwin 
1367b2e60773SJohn Baldwin 	/*
1368b2e60773SJohn Baldwin 	 * Free the old tag first before allocating a new one.
1369b2e60773SJohn Baldwin 	 * ip[6]_output_send() will treat a NULL send tag the same as
1370b2e60773SJohn Baldwin 	 * an ifp mismatch and drop packets until a new tag is
1371b2e60773SJohn Baldwin 	 * allocated.
1372b2e60773SJohn Baldwin 	 *
1373b2e60773SJohn Baldwin 	 * Write-lock the INP when changing tls->snd_tag since
1374b2e60773SJohn Baldwin 	 * ip[6]_output_send() holds a read-lock when reading the
1375b2e60773SJohn Baldwin 	 * pointer.
1376b2e60773SJohn Baldwin 	 */
1377b2e60773SJohn Baldwin 	INP_WLOCK(inp);
1378b2e60773SJohn Baldwin 	old = tls->snd_tag;
1379b2e60773SJohn Baldwin 	tls->snd_tag = NULL;
1380b2e60773SJohn Baldwin 	INP_WUNLOCK(inp);
1381b2e60773SJohn Baldwin 	if (old != NULL)
1382b2e60773SJohn Baldwin 		m_snd_tag_rele(old);
1383b2e60773SJohn Baldwin 
1384b2e60773SJohn Baldwin 	error = ktls_alloc_snd_tag(inp, tls, true, &new);
1385b2e60773SJohn Baldwin 
1386b2e60773SJohn Baldwin 	if (error == 0) {
1387b2e60773SJohn Baldwin 		INP_WLOCK(inp);
1388b2e60773SJohn Baldwin 		tls->snd_tag = new;
1389b2e60773SJohn Baldwin 		mtx_pool_lock(mtxpool_sleep, tls);
1390b2e60773SJohn Baldwin 		tls->reset_pending = false;
1391b2e60773SJohn Baldwin 		mtx_pool_unlock(mtxpool_sleep, tls);
1392b2e60773SJohn Baldwin 		if (!in_pcbrele_wlocked(inp))
1393b2e60773SJohn Baldwin 			INP_WUNLOCK(inp);
1394b2e60773SJohn Baldwin 
1395b2e60773SJohn Baldwin 		counter_u64_add(ktls_ifnet_reset, 1);
1396b2e60773SJohn Baldwin 
1397b2e60773SJohn Baldwin 		/*
1398b2e60773SJohn Baldwin 		 * XXX: Should we kick tcp_output explicitly now that
1399b2e60773SJohn Baldwin 		 * the send tag is fixed or just rely on timers?
1400b2e60773SJohn Baldwin 		 */
1401b2e60773SJohn Baldwin 	} else {
14021a496125SGleb Smirnoff 		NET_EPOCH_ENTER(et);
1403b2e60773SJohn Baldwin 		INP_WLOCK(inp);
1404b2e60773SJohn Baldwin 		if (!in_pcbrele_wlocked(inp)) {
1405b2e60773SJohn Baldwin 			if (!(inp->inp_flags & INP_TIMEWAIT) &&
1406b2e60773SJohn Baldwin 			    !(inp->inp_flags & INP_DROPPED)) {
1407b2e60773SJohn Baldwin 				tp = intotcpcb(inp);
14081f69a509SHans Petter Selasky 				CURVNET_SET(tp->t_vnet);
1409b2e60773SJohn Baldwin 				tp = tcp_drop(tp, ECONNABORTED);
14101f69a509SHans Petter Selasky 				CURVNET_RESTORE();
1411b2e60773SJohn Baldwin 				if (tp != NULL)
1412b2e60773SJohn Baldwin 					INP_WUNLOCK(inp);
1413b2e60773SJohn Baldwin 				counter_u64_add(ktls_ifnet_reset_dropped, 1);
1414b2e60773SJohn Baldwin 			} else
1415b2e60773SJohn Baldwin 				INP_WUNLOCK(inp);
1416b2e60773SJohn Baldwin 		}
14171a496125SGleb Smirnoff 		NET_EPOCH_EXIT(et);
1418b2e60773SJohn Baldwin 
1419b2e60773SJohn Baldwin 		counter_u64_add(ktls_ifnet_reset_failed, 1);
1420b2e60773SJohn Baldwin 
1421b2e60773SJohn Baldwin 		/*
1422b2e60773SJohn Baldwin 		 * Leave reset_pending true to avoid future tasks while
1423b2e60773SJohn Baldwin 		 * the socket goes away.
1424b2e60773SJohn Baldwin 		 */
1425b2e60773SJohn Baldwin 	}
1426b2e60773SJohn Baldwin 
1427b2e60773SJohn Baldwin 	ktls_free(tls);
1428b2e60773SJohn Baldwin }
1429b2e60773SJohn Baldwin 
1430b2e60773SJohn Baldwin int
1431b2e60773SJohn Baldwin ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1432b2e60773SJohn Baldwin {
1433b2e60773SJohn Baldwin 
1434b2e60773SJohn Baldwin 	if (inp == NULL)
1435b2e60773SJohn Baldwin 		return (ENOBUFS);
1436b2e60773SJohn Baldwin 
1437b2e60773SJohn Baldwin 	INP_LOCK_ASSERT(inp);
1438b2e60773SJohn Baldwin 
1439b2e60773SJohn Baldwin 	/*
1440b2e60773SJohn Baldwin 	 * See if we should schedule a task to update the send tag for
1441b2e60773SJohn Baldwin 	 * this session.
1442b2e60773SJohn Baldwin 	 */
1443b2e60773SJohn Baldwin 	mtx_pool_lock(mtxpool_sleep, tls);
1444b2e60773SJohn Baldwin 	if (!tls->reset_pending) {
1445b2e60773SJohn Baldwin 		(void) ktls_hold(tls);
1446b2e60773SJohn Baldwin 		in_pcbref(inp);
1447b2e60773SJohn Baldwin 		tls->inp = inp;
1448b2e60773SJohn Baldwin 		tls->reset_pending = true;
1449b2e60773SJohn Baldwin 		taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1450b2e60773SJohn Baldwin 	}
1451b2e60773SJohn Baldwin 	mtx_pool_unlock(mtxpool_sleep, tls);
1452b2e60773SJohn Baldwin 	return (ENOBUFS);
1453b2e60773SJohn Baldwin }
1454521eac97SJohn Baldwin 
1455521eac97SJohn Baldwin #ifdef RATELIMIT
1456521eac97SJohn Baldwin int
1457521eac97SJohn Baldwin ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1458521eac97SJohn Baldwin {
1459521eac97SJohn Baldwin 	union if_snd_tag_modify_params params = {
1460521eac97SJohn Baldwin 		.rate_limit.max_rate = max_pacing_rate,
1461521eac97SJohn Baldwin 		.rate_limit.flags = M_NOWAIT,
1462521eac97SJohn Baldwin 	};
1463521eac97SJohn Baldwin 	struct m_snd_tag *mst;
1464521eac97SJohn Baldwin 
1465521eac97SJohn Baldwin 	/* Can't get to the inp, but it should be locked. */
1466521eac97SJohn Baldwin 	/* INP_LOCK_ASSERT(inp); */
1467521eac97SJohn Baldwin 
1468521eac97SJohn Baldwin 	MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1469521eac97SJohn Baldwin 
1470521eac97SJohn Baldwin 	if (tls->snd_tag == NULL) {
1471521eac97SJohn Baldwin 		/*
1472521eac97SJohn Baldwin 		 * Resetting send tag, ignore this change.  The
1473521eac97SJohn Baldwin 		 * pending reset may or may not see this updated rate
1474521eac97SJohn Baldwin 		 * in the tcpcb.  If it doesn't, we will just lose
1475521eac97SJohn Baldwin 		 * this rate change.
1476521eac97SJohn Baldwin 		 */
1477521eac97SJohn Baldwin 		return (0);
1478521eac97SJohn Baldwin 	}
1479521eac97SJohn Baldwin 
1480521eac97SJohn Baldwin 	MPASS(tls->snd_tag != NULL);
1481c782ea8bSJohn Baldwin 	MPASS(tls->snd_tag->sw->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1482521eac97SJohn Baldwin 
1483521eac97SJohn Baldwin 	mst = tls->snd_tag;
1484c782ea8bSJohn Baldwin 	return (mst->sw->snd_tag_modify(mst, &params));
1485521eac97SJohn Baldwin }
1486521eac97SJohn Baldwin #endif
1487b2e60773SJohn Baldwin #endif
1488b2e60773SJohn Baldwin 
1489b2e60773SJohn Baldwin void
1490b2e60773SJohn Baldwin ktls_destroy(struct ktls_session *tls)
1491b2e60773SJohn Baldwin {
1492b2e60773SJohn Baldwin 
1493b2e60773SJohn Baldwin 	ktls_cleanup(tls);
1494b2e60773SJohn Baldwin 	uma_zfree(ktls_session_zone, tls);
1495b2e60773SJohn Baldwin }
1496b2e60773SJohn Baldwin 
1497b2e60773SJohn Baldwin void
1498b2e60773SJohn Baldwin ktls_seq(struct sockbuf *sb, struct mbuf *m)
1499b2e60773SJohn Baldwin {
1500b2e60773SJohn Baldwin 
1501b2e60773SJohn Baldwin 	for (; m != NULL; m = m->m_next) {
15026edfd179SGleb Smirnoff 		KASSERT((m->m_flags & M_EXTPG) != 0,
1503b2e60773SJohn Baldwin 		    ("ktls_seq: mapped mbuf %p", m));
1504b2e60773SJohn Baldwin 
15057b6c99d0SGleb Smirnoff 		m->m_epg_seqno = sb->sb_tls_seqno;
1506b2e60773SJohn Baldwin 		sb->sb_tls_seqno++;
1507b2e60773SJohn Baldwin 	}
1508b2e60773SJohn Baldwin }
1509b2e60773SJohn Baldwin 
1510b2e60773SJohn Baldwin /*
1511b2e60773SJohn Baldwin  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
1512b2e60773SJohn Baldwin  * mbuf in the chain must be an unmapped mbuf.  The payload of the
1513b2e60773SJohn Baldwin  * mbuf must be populated with the payload of each TLS record.
1514b2e60773SJohn Baldwin  *
1515b2e60773SJohn Baldwin  * The record_type argument specifies the TLS record type used when
1516b2e60773SJohn Baldwin  * populating the TLS header.
1517b2e60773SJohn Baldwin  *
1518b2e60773SJohn Baldwin  * The enq_count argument on return is set to the number of pages of
1519b2e60773SJohn Baldwin  * payload data for this entire chain that need to be encrypted via SW
1520b2e60773SJohn Baldwin  * encryption.  The returned value should be passed to ktls_enqueue
1521c2a8fd6fSJohn Baldwin  * when scheduling encryption of this chain of mbufs.  To handle the
1522c2a8fd6fSJohn Baldwin  * special case of empty fragments for TLS 1.0 sessions, an empty
1523c2a8fd6fSJohn Baldwin  * fragment counts as one page.
1524b2e60773SJohn Baldwin  */
1525f85e1a80SGleb Smirnoff void
1526b2e60773SJohn Baldwin ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1527b2e60773SJohn Baldwin     uint8_t record_type)
1528b2e60773SJohn Baldwin {
1529b2e60773SJohn Baldwin 	struct tls_record_layer *tlshdr;
1530b2e60773SJohn Baldwin 	struct mbuf *m;
15317d29eb9aSJohn Baldwin 	uint64_t *noncep;
1532b2e60773SJohn Baldwin 	uint16_t tls_len;
1533b2e60773SJohn Baldwin 	int maxlen;
1534b2e60773SJohn Baldwin 
1535b2e60773SJohn Baldwin 	maxlen = tls->params.max_frame_len;
1536b2e60773SJohn Baldwin 	*enq_cnt = 0;
1537b2e60773SJohn Baldwin 	for (m = top; m != NULL; m = m->m_next) {
1538b2e60773SJohn Baldwin 		/*
1539c2a8fd6fSJohn Baldwin 		 * All mbufs in the chain should be TLS records whose
1540c2a8fd6fSJohn Baldwin 		 * payload does not exceed the maximum frame length.
1541c2a8fd6fSJohn Baldwin 		 *
1542c2a8fd6fSJohn Baldwin 		 * Empty TLS records are permitted when using CBC.
1543b2e60773SJohn Baldwin 		 */
1544c2a8fd6fSJohn Baldwin 		KASSERT(m->m_len <= maxlen &&
1545c2a8fd6fSJohn Baldwin 		    (tls->params.cipher_algorithm == CRYPTO_AES_CBC ?
1546c2a8fd6fSJohn Baldwin 		    m->m_len >= 0 : m->m_len > 0),
1547f85e1a80SGleb Smirnoff 		    ("ktls_frame: m %p len %d\n", m, m->m_len));
1548c2a8fd6fSJohn Baldwin 
1549b2e60773SJohn Baldwin 		/*
1550b2e60773SJohn Baldwin 		 * TLS frames require unmapped mbufs to store session
1551b2e60773SJohn Baldwin 		 * info.
1552b2e60773SJohn Baldwin 		 */
15536edfd179SGleb Smirnoff 		KASSERT((m->m_flags & M_EXTPG) != 0,
1554b2e60773SJohn Baldwin 		    ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1555b2e60773SJohn Baldwin 
1556f85e1a80SGleb Smirnoff 		tls_len = m->m_len;
1557b2e60773SJohn Baldwin 
1558b2e60773SJohn Baldwin 		/* Save a reference to the session. */
15597b6c99d0SGleb Smirnoff 		m->m_epg_tls = ktls_hold(tls);
1560b2e60773SJohn Baldwin 
15617b6c99d0SGleb Smirnoff 		m->m_epg_hdrlen = tls->params.tls_hlen;
15627b6c99d0SGleb Smirnoff 		m->m_epg_trllen = tls->params.tls_tlen;
1563b2e60773SJohn Baldwin 		if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1564b2e60773SJohn Baldwin 			int bs, delta;
1565b2e60773SJohn Baldwin 
1566b2e60773SJohn Baldwin 			/*
1567b2e60773SJohn Baldwin 			 * AES-CBC pads messages to a multiple of the
1568b2e60773SJohn Baldwin 			 * block size.  Note that the padding is
1569b2e60773SJohn Baldwin 			 * applied after the digest and the encryption
1570b2e60773SJohn Baldwin 			 * is done on the "plaintext || mac || padding".
1571b2e60773SJohn Baldwin 			 * At least one byte of padding is always
1572b2e60773SJohn Baldwin 			 * present.
1573b2e60773SJohn Baldwin 			 *
1574b2e60773SJohn Baldwin 			 * Compute the final trailer length assuming
1575b2e60773SJohn Baldwin 			 * at most one block of padding.
157621e3c1fbSJohn Baldwin 			 * tls->params.tls_tlen is the maximum
1577b2e60773SJohn Baldwin 			 * possible trailer length (padding + digest).
1578b2e60773SJohn Baldwin 			 * delta holds the number of excess padding
1579b2e60773SJohn Baldwin 			 * bytes if the maximum were used.  Those
1580b2e60773SJohn Baldwin 			 * extra bytes are removed.
1581b2e60773SJohn Baldwin 			 */
1582b2e60773SJohn Baldwin 			bs = tls->params.tls_bs;
1583b2e60773SJohn Baldwin 			delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
15847b6c99d0SGleb Smirnoff 			m->m_epg_trllen -= delta;
1585b2e60773SJohn Baldwin 		}
15867b6c99d0SGleb Smirnoff 		m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1587b2e60773SJohn Baldwin 
1588b2e60773SJohn Baldwin 		/* Populate the TLS header. */
15890c103266SGleb Smirnoff 		tlshdr = (void *)m->m_epg_hdr;
1590b2e60773SJohn Baldwin 		tlshdr->tls_vmajor = tls->params.tls_vmajor;
15916554362cSAndrew Gallatin 
15926554362cSAndrew Gallatin 		/*
15936554362cSAndrew Gallatin 		 * TLS 1.3 masquarades as TLS 1.2 with a record type
15946554362cSAndrew Gallatin 		 * of TLS_RLTYPE_APP.
15956554362cSAndrew Gallatin 		 */
15966554362cSAndrew Gallatin 		if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
15976554362cSAndrew Gallatin 		    tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
15986554362cSAndrew Gallatin 			tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
15996554362cSAndrew Gallatin 			tlshdr->tls_type = TLS_RLTYPE_APP;
16006554362cSAndrew Gallatin 			/* save the real record type for later */
16017b6c99d0SGleb Smirnoff 			m->m_epg_record_type = record_type;
16020c103266SGleb Smirnoff 			m->m_epg_trail[0] = record_type;
16036554362cSAndrew Gallatin 		} else {
1604b2e60773SJohn Baldwin 			tlshdr->tls_vminor = tls->params.tls_vminor;
1605b2e60773SJohn Baldwin 			tlshdr->tls_type = record_type;
16066554362cSAndrew Gallatin 		}
1607b2e60773SJohn Baldwin 		tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1608b2e60773SJohn Baldwin 
1609b2e60773SJohn Baldwin 		/*
16107d29eb9aSJohn Baldwin 		 * Store nonces / explicit IVs after the end of the
16117d29eb9aSJohn Baldwin 		 * TLS header.
16127d29eb9aSJohn Baldwin 		 *
16137d29eb9aSJohn Baldwin 		 * For GCM with TLS 1.2, an 8 byte nonce is copied
16147d29eb9aSJohn Baldwin 		 * from the end of the IV.  The nonce is then
16157d29eb9aSJohn Baldwin 		 * incremented for use by the next record.
16167d29eb9aSJohn Baldwin 		 *
16177d29eb9aSJohn Baldwin 		 * For CBC, a random nonce is inserted for TLS 1.1+.
1618b2e60773SJohn Baldwin 		 */
16197d29eb9aSJohn Baldwin 		if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
16207d29eb9aSJohn Baldwin 		    tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
16217d29eb9aSJohn Baldwin 			noncep = (uint64_t *)(tls->params.iv + 8);
16227d29eb9aSJohn Baldwin 			be64enc(tlshdr + 1, *noncep);
16237d29eb9aSJohn Baldwin 			(*noncep)++;
16247d29eb9aSJohn Baldwin 		} else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1625b2e60773SJohn Baldwin 		    tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1626b2e60773SJohn Baldwin 			arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1627b2e60773SJohn Baldwin 
1628b2e60773SJohn Baldwin 		/*
1629b2e60773SJohn Baldwin 		 * When using SW encryption, mark the mbuf not ready.
1630b2e60773SJohn Baldwin 		 * It will be marked ready via sbready() after the
1631b2e60773SJohn Baldwin 		 * record has been encrypted.
1632b2e60773SJohn Baldwin 		 *
1633b2e60773SJohn Baldwin 		 * When using ifnet TLS, unencrypted TLS records are
1634b2e60773SJohn Baldwin 		 * sent down the stack to the NIC.
1635b2e60773SJohn Baldwin 		 */
16369e14430dSJohn Baldwin 		if (tls->mode == TCP_TLS_MODE_SW) {
1637b2e60773SJohn Baldwin 			m->m_flags |= M_NOTREADY;
1638c2a8fd6fSJohn Baldwin 			if (__predict_false(tls_len == 0)) {
1639c2a8fd6fSJohn Baldwin 				/* TLS 1.0 empty fragment. */
1640d16cb228SJohn Baldwin 				m->m_epg_nrdy = 1;
1641c2a8fd6fSJohn Baldwin 			} else
1642d16cb228SJohn Baldwin 				m->m_epg_nrdy = m->m_epg_npgs;
1643d16cb228SJohn Baldwin 			*enq_cnt += m->m_epg_nrdy;
1644b2e60773SJohn Baldwin 		}
1645b2e60773SJohn Baldwin 	}
1646b2e60773SJohn Baldwin }
1647b2e60773SJohn Baldwin 
1648b2e60773SJohn Baldwin void
16493c0e5685SJohn Baldwin ktls_check_rx(struct sockbuf *sb)
16503c0e5685SJohn Baldwin {
16513c0e5685SJohn Baldwin 	struct tls_record_layer hdr;
16523c0e5685SJohn Baldwin 	struct ktls_wq *wq;
16533c0e5685SJohn Baldwin 	struct socket *so;
16543c0e5685SJohn Baldwin 	bool running;
16553c0e5685SJohn Baldwin 
16563c0e5685SJohn Baldwin 	SOCKBUF_LOCK_ASSERT(sb);
16573c0e5685SJohn Baldwin 	KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
16583c0e5685SJohn Baldwin 	    __func__, sb));
16593c0e5685SJohn Baldwin 	so = __containerof(sb, struct socket, so_rcv);
16603c0e5685SJohn Baldwin 
16613c0e5685SJohn Baldwin 	if (sb->sb_flags & SB_TLS_RX_RUNNING)
16623c0e5685SJohn Baldwin 		return;
16633c0e5685SJohn Baldwin 
16643c0e5685SJohn Baldwin 	/* Is there enough queued for a TLS header? */
16653c0e5685SJohn Baldwin 	if (sb->sb_tlscc < sizeof(hdr)) {
16663c0e5685SJohn Baldwin 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
16673c0e5685SJohn Baldwin 			so->so_error = EMSGSIZE;
16683c0e5685SJohn Baldwin 		return;
16693c0e5685SJohn Baldwin 	}
16703c0e5685SJohn Baldwin 
16713c0e5685SJohn Baldwin 	m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
16723c0e5685SJohn Baldwin 
16733c0e5685SJohn Baldwin 	/* Is the entire record queued? */
16743c0e5685SJohn Baldwin 	if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
16753c0e5685SJohn Baldwin 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
16763c0e5685SJohn Baldwin 			so->so_error = EMSGSIZE;
16773c0e5685SJohn Baldwin 		return;
16783c0e5685SJohn Baldwin 	}
16793c0e5685SJohn Baldwin 
16803c0e5685SJohn Baldwin 	sb->sb_flags |= SB_TLS_RX_RUNNING;
16813c0e5685SJohn Baldwin 
16823c0e5685SJohn Baldwin 	soref(so);
16833c0e5685SJohn Baldwin 	wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
16843c0e5685SJohn Baldwin 	mtx_lock(&wq->mtx);
16853c0e5685SJohn Baldwin 	STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
16863c0e5685SJohn Baldwin 	running = wq->running;
16873c0e5685SJohn Baldwin 	mtx_unlock(&wq->mtx);
16883c0e5685SJohn Baldwin 	if (!running)
16893c0e5685SJohn Baldwin 		wakeup(wq);
16903c0e5685SJohn Baldwin 	counter_u64_add(ktls_cnt_rx_queued, 1);
16913c0e5685SJohn Baldwin }
16923c0e5685SJohn Baldwin 
16933c0e5685SJohn Baldwin static struct mbuf *
16943c0e5685SJohn Baldwin ktls_detach_record(struct sockbuf *sb, int len)
16953c0e5685SJohn Baldwin {
16963c0e5685SJohn Baldwin 	struct mbuf *m, *n, *top;
16973c0e5685SJohn Baldwin 	int remain;
16983c0e5685SJohn Baldwin 
16993c0e5685SJohn Baldwin 	SOCKBUF_LOCK_ASSERT(sb);
17003c0e5685SJohn Baldwin 	MPASS(len <= sb->sb_tlscc);
17013c0e5685SJohn Baldwin 
17023c0e5685SJohn Baldwin 	/*
17033c0e5685SJohn Baldwin 	 * If TLS chain is the exact size of the record,
17043c0e5685SJohn Baldwin 	 * just grab the whole record.
17053c0e5685SJohn Baldwin 	 */
17063c0e5685SJohn Baldwin 	top = sb->sb_mtls;
17073c0e5685SJohn Baldwin 	if (sb->sb_tlscc == len) {
17083c0e5685SJohn Baldwin 		sb->sb_mtls = NULL;
17093c0e5685SJohn Baldwin 		sb->sb_mtlstail = NULL;
17103c0e5685SJohn Baldwin 		goto out;
17113c0e5685SJohn Baldwin 	}
17123c0e5685SJohn Baldwin 
17133c0e5685SJohn Baldwin 	/*
17143c0e5685SJohn Baldwin 	 * While it would be nice to use m_split() here, we need
17153c0e5685SJohn Baldwin 	 * to know exactly what m_split() allocates to update the
17163c0e5685SJohn Baldwin 	 * accounting, so do it inline instead.
17173c0e5685SJohn Baldwin 	 */
17183c0e5685SJohn Baldwin 	remain = len;
17193c0e5685SJohn Baldwin 	for (m = top; remain > m->m_len; m = m->m_next)
17203c0e5685SJohn Baldwin 		remain -= m->m_len;
17213c0e5685SJohn Baldwin 
17223c0e5685SJohn Baldwin 	/* Easy case: don't have to split 'm'. */
17233c0e5685SJohn Baldwin 	if (remain == m->m_len) {
17243c0e5685SJohn Baldwin 		sb->sb_mtls = m->m_next;
17253c0e5685SJohn Baldwin 		if (sb->sb_mtls == NULL)
17263c0e5685SJohn Baldwin 			sb->sb_mtlstail = NULL;
17273c0e5685SJohn Baldwin 		m->m_next = NULL;
17283c0e5685SJohn Baldwin 		goto out;
17293c0e5685SJohn Baldwin 	}
17303c0e5685SJohn Baldwin 
17313c0e5685SJohn Baldwin 	/*
17323c0e5685SJohn Baldwin 	 * Need to allocate an mbuf to hold the remainder of 'm'.  Try
17333c0e5685SJohn Baldwin 	 * with M_NOWAIT first.
17343c0e5685SJohn Baldwin 	 */
17353c0e5685SJohn Baldwin 	n = m_get(M_NOWAIT, MT_DATA);
17363c0e5685SJohn Baldwin 	if (n == NULL) {
17373c0e5685SJohn Baldwin 		/*
17383c0e5685SJohn Baldwin 		 * Use M_WAITOK with socket buffer unlocked.  If
17393c0e5685SJohn Baldwin 		 * 'sb_mtls' changes while the lock is dropped, return
17403c0e5685SJohn Baldwin 		 * NULL to force the caller to retry.
17413c0e5685SJohn Baldwin 		 */
17423c0e5685SJohn Baldwin 		SOCKBUF_UNLOCK(sb);
17433c0e5685SJohn Baldwin 
17443c0e5685SJohn Baldwin 		n = m_get(M_WAITOK, MT_DATA);
17453c0e5685SJohn Baldwin 
17463c0e5685SJohn Baldwin 		SOCKBUF_LOCK(sb);
17473c0e5685SJohn Baldwin 		if (sb->sb_mtls != top) {
17483c0e5685SJohn Baldwin 			m_free(n);
17493c0e5685SJohn Baldwin 			return (NULL);
17503c0e5685SJohn Baldwin 		}
17513c0e5685SJohn Baldwin 	}
17523c0e5685SJohn Baldwin 	n->m_flags |= M_NOTREADY;
17533c0e5685SJohn Baldwin 
17543c0e5685SJohn Baldwin 	/* Store remainder in 'n'. */
17553c0e5685SJohn Baldwin 	n->m_len = m->m_len - remain;
17563c0e5685SJohn Baldwin 	if (m->m_flags & M_EXT) {
17573c0e5685SJohn Baldwin 		n->m_data = m->m_data + remain;
17583c0e5685SJohn Baldwin 		mb_dupcl(n, m);
17593c0e5685SJohn Baldwin 	} else {
17603c0e5685SJohn Baldwin 		bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
17613c0e5685SJohn Baldwin 	}
17623c0e5685SJohn Baldwin 
17633c0e5685SJohn Baldwin 	/* Trim 'm' and update accounting. */
17643c0e5685SJohn Baldwin 	m->m_len -= n->m_len;
17653c0e5685SJohn Baldwin 	sb->sb_tlscc -= n->m_len;
17663c0e5685SJohn Baldwin 	sb->sb_ccc -= n->m_len;
17673c0e5685SJohn Baldwin 
17683c0e5685SJohn Baldwin 	/* Account for 'n'. */
17693c0e5685SJohn Baldwin 	sballoc_ktls_rx(sb, n);
17703c0e5685SJohn Baldwin 
17713c0e5685SJohn Baldwin 	/* Insert 'n' into the TLS chain. */
17723c0e5685SJohn Baldwin 	sb->sb_mtls = n;
17733c0e5685SJohn Baldwin 	n->m_next = m->m_next;
17743c0e5685SJohn Baldwin 	if (sb->sb_mtlstail == m)
17753c0e5685SJohn Baldwin 		sb->sb_mtlstail = n;
17763c0e5685SJohn Baldwin 
17773c0e5685SJohn Baldwin 	/* Detach the record from the TLS chain. */
17783c0e5685SJohn Baldwin 	m->m_next = NULL;
17793c0e5685SJohn Baldwin 
17803c0e5685SJohn Baldwin out:
17813c0e5685SJohn Baldwin 	MPASS(m_length(top, NULL) == len);
17823c0e5685SJohn Baldwin 	for (m = top; m != NULL; m = m->m_next)
17833c0e5685SJohn Baldwin 		sbfree_ktls_rx(sb, m);
17843c0e5685SJohn Baldwin 	sb->sb_tlsdcc = len;
17853c0e5685SJohn Baldwin 	sb->sb_ccc += len;
17863c0e5685SJohn Baldwin 	SBCHECK(sb);
17873c0e5685SJohn Baldwin 	return (top);
17883c0e5685SJohn Baldwin }
17893c0e5685SJohn Baldwin 
17903c0e5685SJohn Baldwin static void
17913c0e5685SJohn Baldwin ktls_decrypt(struct socket *so)
17923c0e5685SJohn Baldwin {
17933c0e5685SJohn Baldwin 	char tls_header[MBUF_PEXT_HDR_LEN];
17943c0e5685SJohn Baldwin 	struct ktls_session *tls;
17953c0e5685SJohn Baldwin 	struct sockbuf *sb;
17963c0e5685SJohn Baldwin 	struct tls_record_layer *hdr;
17973c0e5685SJohn Baldwin 	struct tls_get_record tgr;
17983c0e5685SJohn Baldwin 	struct mbuf *control, *data, *m;
17993c0e5685SJohn Baldwin 	uint64_t seqno;
18003c0e5685SJohn Baldwin 	int error, remain, tls_len, trail_len;
18013c0e5685SJohn Baldwin 
18023c0e5685SJohn Baldwin 	hdr = (struct tls_record_layer *)tls_header;
18033c0e5685SJohn Baldwin 	sb = &so->so_rcv;
18043c0e5685SJohn Baldwin 	SOCKBUF_LOCK(sb);
18053c0e5685SJohn Baldwin 	KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
18063c0e5685SJohn Baldwin 	    ("%s: socket %p not running", __func__, so));
18073c0e5685SJohn Baldwin 
18083c0e5685SJohn Baldwin 	tls = sb->sb_tls_info;
18093c0e5685SJohn Baldwin 	MPASS(tls != NULL);
18103c0e5685SJohn Baldwin 
18113c0e5685SJohn Baldwin 	for (;;) {
18123c0e5685SJohn Baldwin 		/* Is there enough queued for a TLS header? */
18133c0e5685SJohn Baldwin 		if (sb->sb_tlscc < tls->params.tls_hlen)
18143c0e5685SJohn Baldwin 			break;
18153c0e5685SJohn Baldwin 
18163c0e5685SJohn Baldwin 		m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
18173c0e5685SJohn Baldwin 		tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
18183c0e5685SJohn Baldwin 
18193c0e5685SJohn Baldwin 		if (hdr->tls_vmajor != tls->params.tls_vmajor ||
18203c0e5685SJohn Baldwin 		    hdr->tls_vminor != tls->params.tls_vminor)
18213c0e5685SJohn Baldwin 			error = EINVAL;
18223c0e5685SJohn Baldwin 		else if (tls_len < tls->params.tls_hlen || tls_len >
18233c0e5685SJohn Baldwin 		    tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
18243c0e5685SJohn Baldwin 		    tls->params.tls_tlen)
18253c0e5685SJohn Baldwin 			error = EMSGSIZE;
18263c0e5685SJohn Baldwin 		else
18273c0e5685SJohn Baldwin 			error = 0;
18283c0e5685SJohn Baldwin 		if (__predict_false(error != 0)) {
18293c0e5685SJohn Baldwin 			/*
18303c0e5685SJohn Baldwin 			 * We have a corrupted record and are likely
18313c0e5685SJohn Baldwin 			 * out of sync.  The connection isn't
18323c0e5685SJohn Baldwin 			 * recoverable at this point, so abort it.
18333c0e5685SJohn Baldwin 			 */
18343c0e5685SJohn Baldwin 			SOCKBUF_UNLOCK(sb);
18353c0e5685SJohn Baldwin 			counter_u64_add(ktls_offload_corrupted_records, 1);
18363c0e5685SJohn Baldwin 
18373c0e5685SJohn Baldwin 			CURVNET_SET(so->so_vnet);
18383c0e5685SJohn Baldwin 			so->so_proto->pr_usrreqs->pru_abort(so);
18393c0e5685SJohn Baldwin 			so->so_error = error;
18403c0e5685SJohn Baldwin 			CURVNET_RESTORE();
18413c0e5685SJohn Baldwin 			goto deref;
18423c0e5685SJohn Baldwin 		}
18433c0e5685SJohn Baldwin 
18443c0e5685SJohn Baldwin 		/* Is the entire record queued? */
18453c0e5685SJohn Baldwin 		if (sb->sb_tlscc < tls_len)
18463c0e5685SJohn Baldwin 			break;
18473c0e5685SJohn Baldwin 
18483c0e5685SJohn Baldwin 		/*
18493c0e5685SJohn Baldwin 		 * Split out the portion of the mbuf chain containing
18503c0e5685SJohn Baldwin 		 * this TLS record.
18513c0e5685SJohn Baldwin 		 */
18523c0e5685SJohn Baldwin 		data = ktls_detach_record(sb, tls_len);
18533c0e5685SJohn Baldwin 		if (data == NULL)
18543c0e5685SJohn Baldwin 			continue;
18553c0e5685SJohn Baldwin 		MPASS(sb->sb_tlsdcc == tls_len);
18563c0e5685SJohn Baldwin 
18573c0e5685SJohn Baldwin 		seqno = sb->sb_tls_seqno;
18583c0e5685SJohn Baldwin 		sb->sb_tls_seqno++;
18593c0e5685SJohn Baldwin 		SBCHECK(sb);
18603c0e5685SJohn Baldwin 		SOCKBUF_UNLOCK(sb);
18613c0e5685SJohn Baldwin 
18623c0e5685SJohn Baldwin 		error = tls->sw_decrypt(tls, hdr, data, seqno, &trail_len);
18633c0e5685SJohn Baldwin 		if (error) {
18643c0e5685SJohn Baldwin 			counter_u64_add(ktls_offload_failed_crypto, 1);
18653c0e5685SJohn Baldwin 
18663c0e5685SJohn Baldwin 			SOCKBUF_LOCK(sb);
18673c0e5685SJohn Baldwin 			if (sb->sb_tlsdcc == 0) {
18683c0e5685SJohn Baldwin 				/*
18693c0e5685SJohn Baldwin 				 * sbcut/drop/flush discarded these
18703c0e5685SJohn Baldwin 				 * mbufs.
18713c0e5685SJohn Baldwin 				 */
18723c0e5685SJohn Baldwin 				m_freem(data);
18733c0e5685SJohn Baldwin 				break;
18743c0e5685SJohn Baldwin 			}
18753c0e5685SJohn Baldwin 
18763c0e5685SJohn Baldwin 			/*
18773c0e5685SJohn Baldwin 			 * Drop this TLS record's data, but keep
18783c0e5685SJohn Baldwin 			 * decrypting subsequent records.
18793c0e5685SJohn Baldwin 			 */
18803c0e5685SJohn Baldwin 			sb->sb_ccc -= tls_len;
18813c0e5685SJohn Baldwin 			sb->sb_tlsdcc = 0;
18823c0e5685SJohn Baldwin 
18833c0e5685SJohn Baldwin 			CURVNET_SET(so->so_vnet);
18843c0e5685SJohn Baldwin 			so->so_error = EBADMSG;
18853c0e5685SJohn Baldwin 			sorwakeup_locked(so);
18863c0e5685SJohn Baldwin 			CURVNET_RESTORE();
18873c0e5685SJohn Baldwin 
18883c0e5685SJohn Baldwin 			m_freem(data);
18893c0e5685SJohn Baldwin 
18903c0e5685SJohn Baldwin 			SOCKBUF_LOCK(sb);
18913c0e5685SJohn Baldwin 			continue;
18923c0e5685SJohn Baldwin 		}
18933c0e5685SJohn Baldwin 
18943c0e5685SJohn Baldwin 		/* Allocate the control mbuf. */
18953c0e5685SJohn Baldwin 		tgr.tls_type = hdr->tls_type;
18963c0e5685SJohn Baldwin 		tgr.tls_vmajor = hdr->tls_vmajor;
18973c0e5685SJohn Baldwin 		tgr.tls_vminor = hdr->tls_vminor;
18983c0e5685SJohn Baldwin 		tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
18993c0e5685SJohn Baldwin 		    trail_len);
19003c0e5685SJohn Baldwin 		control = sbcreatecontrol_how(&tgr, sizeof(tgr),
19013c0e5685SJohn Baldwin 		    TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
19023c0e5685SJohn Baldwin 
19033c0e5685SJohn Baldwin 		SOCKBUF_LOCK(sb);
19043c0e5685SJohn Baldwin 		if (sb->sb_tlsdcc == 0) {
19053c0e5685SJohn Baldwin 			/* sbcut/drop/flush discarded these mbufs. */
19063c0e5685SJohn Baldwin 			MPASS(sb->sb_tlscc == 0);
19073c0e5685SJohn Baldwin 			m_freem(data);
19083c0e5685SJohn Baldwin 			m_freem(control);
19093c0e5685SJohn Baldwin 			break;
19103c0e5685SJohn Baldwin 		}
19113c0e5685SJohn Baldwin 
19123c0e5685SJohn Baldwin 		/*
19133c0e5685SJohn Baldwin 		 * Clear the 'dcc' accounting in preparation for
19143c0e5685SJohn Baldwin 		 * adding the decrypted record.
19153c0e5685SJohn Baldwin 		 */
19163c0e5685SJohn Baldwin 		sb->sb_ccc -= tls_len;
19173c0e5685SJohn Baldwin 		sb->sb_tlsdcc = 0;
19183c0e5685SJohn Baldwin 		SBCHECK(sb);
19193c0e5685SJohn Baldwin 
19203c0e5685SJohn Baldwin 		/* If there is no payload, drop all of the data. */
19213c0e5685SJohn Baldwin 		if (tgr.tls_length == htobe16(0)) {
19223c0e5685SJohn Baldwin 			m_freem(data);
19233c0e5685SJohn Baldwin 			data = NULL;
19243c0e5685SJohn Baldwin 		} else {
19253c0e5685SJohn Baldwin 			/* Trim header. */
19263c0e5685SJohn Baldwin 			remain = tls->params.tls_hlen;
19273c0e5685SJohn Baldwin 			while (remain > 0) {
19283c0e5685SJohn Baldwin 				if (data->m_len > remain) {
19293c0e5685SJohn Baldwin 					data->m_data += remain;
19303c0e5685SJohn Baldwin 					data->m_len -= remain;
19313c0e5685SJohn Baldwin 					break;
19323c0e5685SJohn Baldwin 				}
19333c0e5685SJohn Baldwin 				remain -= data->m_len;
19343c0e5685SJohn Baldwin 				data = m_free(data);
19353c0e5685SJohn Baldwin 			}
19363c0e5685SJohn Baldwin 
19373c0e5685SJohn Baldwin 			/* Trim trailer and clear M_NOTREADY. */
19383c0e5685SJohn Baldwin 			remain = be16toh(tgr.tls_length);
19393c0e5685SJohn Baldwin 			m = data;
19403c0e5685SJohn Baldwin 			for (m = data; remain > m->m_len; m = m->m_next) {
19413c0e5685SJohn Baldwin 				m->m_flags &= ~M_NOTREADY;
19423c0e5685SJohn Baldwin 				remain -= m->m_len;
19433c0e5685SJohn Baldwin 			}
19443c0e5685SJohn Baldwin 			m->m_len = remain;
19453c0e5685SJohn Baldwin 			m_freem(m->m_next);
19463c0e5685SJohn Baldwin 			m->m_next = NULL;
19473c0e5685SJohn Baldwin 			m->m_flags &= ~M_NOTREADY;
19483c0e5685SJohn Baldwin 
19493c0e5685SJohn Baldwin 			/* Set EOR on the final mbuf. */
19503c0e5685SJohn Baldwin 			m->m_flags |= M_EOR;
19513c0e5685SJohn Baldwin 		}
19523c0e5685SJohn Baldwin 
19533c0e5685SJohn Baldwin 		sbappendcontrol_locked(sb, data, control, 0);
19543c0e5685SJohn Baldwin 	}
19553c0e5685SJohn Baldwin 
19563c0e5685SJohn Baldwin 	sb->sb_flags &= ~SB_TLS_RX_RUNNING;
19573c0e5685SJohn Baldwin 
19583c0e5685SJohn Baldwin 	if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
19593c0e5685SJohn Baldwin 		so->so_error = EMSGSIZE;
19603c0e5685SJohn Baldwin 
19613c0e5685SJohn Baldwin 	sorwakeup_locked(so);
19623c0e5685SJohn Baldwin 
19633c0e5685SJohn Baldwin deref:
19643c0e5685SJohn Baldwin 	SOCKBUF_UNLOCK_ASSERT(sb);
19653c0e5685SJohn Baldwin 
19663c0e5685SJohn Baldwin 	CURVNET_SET(so->so_vnet);
19673c0e5685SJohn Baldwin 	SOCK_LOCK(so);
19683c0e5685SJohn Baldwin 	sorele(so);
19693c0e5685SJohn Baldwin 	CURVNET_RESTORE();
19703c0e5685SJohn Baldwin }
19713c0e5685SJohn Baldwin 
19723c0e5685SJohn Baldwin void
1973d90fe9d0SGleb Smirnoff ktls_enqueue_to_free(struct mbuf *m)
1974b2e60773SJohn Baldwin {
1975b2e60773SJohn Baldwin 	struct ktls_wq *wq;
1976b2e60773SJohn Baldwin 	bool running;
1977b2e60773SJohn Baldwin 
1978b2e60773SJohn Baldwin 	/* Mark it for freeing. */
19797b6c99d0SGleb Smirnoff 	m->m_epg_flags |= EPG_FLAG_2FREE;
19807b6c99d0SGleb Smirnoff 	wq = &ktls_wq[m->m_epg_tls->wq_index];
1981b2e60773SJohn Baldwin 	mtx_lock(&wq->mtx);
19823c0e5685SJohn Baldwin 	STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1983b2e60773SJohn Baldwin 	running = wq->running;
1984b2e60773SJohn Baldwin 	mtx_unlock(&wq->mtx);
1985b2e60773SJohn Baldwin 	if (!running)
1986b2e60773SJohn Baldwin 		wakeup(wq);
1987b2e60773SJohn Baldwin }
1988b2e60773SJohn Baldwin 
198949f6925cSMark Johnston static void *
199049f6925cSMark Johnston ktls_buffer_alloc(struct ktls_wq *wq, struct mbuf *m)
199149f6925cSMark Johnston {
199249f6925cSMark Johnston 	void *buf;
199398215005SAndrew Gallatin 	int domain, running;
199449f6925cSMark Johnston 
199549f6925cSMark Johnston 	if (m->m_epg_npgs <= 2)
199649f6925cSMark Johnston 		return (NULL);
199749f6925cSMark Johnston 	if (ktls_buffer_zone == NULL)
199849f6925cSMark Johnston 		return (NULL);
199949f6925cSMark Johnston 	if ((u_int)(ticks - wq->lastallocfail) < hz) {
200049f6925cSMark Johnston 		/*
200149f6925cSMark Johnston 		 * Rate-limit allocation attempts after a failure.
200249f6925cSMark Johnston 		 * ktls_buffer_import() will acquire a per-domain mutex to check
200349f6925cSMark Johnston 		 * the free page queues and may fail consistently if memory is
200449f6925cSMark Johnston 		 * fragmented.
200549f6925cSMark Johnston 		 */
200649f6925cSMark Johnston 		return (NULL);
200749f6925cSMark Johnston 	}
200849f6925cSMark Johnston 	buf = uma_zalloc(ktls_buffer_zone, M_NOWAIT | M_NORECLAIM);
200998215005SAndrew Gallatin 	if (buf == NULL) {
201098215005SAndrew Gallatin 		domain = PCPU_GET(domain);
201149f6925cSMark Johnston 		wq->lastallocfail = ticks;
201298215005SAndrew Gallatin 
201398215005SAndrew Gallatin 		/*
201498215005SAndrew Gallatin 		 * Note that this check is "racy", but the races are
201598215005SAndrew Gallatin 		 * harmless, and are either a spurious wakeup if
201698215005SAndrew Gallatin 		 * multiple threads fail allocations before the alloc
201798215005SAndrew Gallatin 		 * thread wakes, or waiting an extra second in case we
201898215005SAndrew Gallatin 		 * see an old value of running == true.
201998215005SAndrew Gallatin 		 */
202098215005SAndrew Gallatin 		if (!VM_DOMAIN_EMPTY(domain)) {
202198215005SAndrew Gallatin 			running = atomic_load_int(&ktls_domains[domain].alloc_td.running);
202298215005SAndrew Gallatin 			if (!running)
202398215005SAndrew Gallatin 				wakeup(&ktls_domains[domain].alloc_td);
202498215005SAndrew Gallatin 		}
202598215005SAndrew Gallatin 	}
202649f6925cSMark Johnston 	return (buf);
202749f6925cSMark Johnston }
202849f6925cSMark Johnston 
2029470e851cSJohn Baldwin static int
2030470e851cSJohn Baldwin ktls_encrypt_record(struct ktls_wq *wq, struct mbuf *m,
2031470e851cSJohn Baldwin     struct ktls_session *tls, struct ktls_ocf_encrypt_state *state)
2032470e851cSJohn Baldwin {
2033470e851cSJohn Baldwin 	vm_page_t pg;
2034470e851cSJohn Baldwin 	int error, i, len, off;
2035470e851cSJohn Baldwin 
2036470e851cSJohn Baldwin 	KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) == (M_EXTPG | M_NOTREADY),
2037470e851cSJohn Baldwin 	    ("%p not unready & nomap mbuf\n", m));
2038470e851cSJohn Baldwin 	KASSERT(ptoa(m->m_epg_npgs) <= ktls_maxlen,
2039470e851cSJohn Baldwin 	    ("page count %d larger than maximum frame length %d", m->m_epg_npgs,
2040470e851cSJohn Baldwin 	    ktls_maxlen));
2041470e851cSJohn Baldwin 
2042470e851cSJohn Baldwin 	/* Anonymous mbufs are encrypted in place. */
2043470e851cSJohn Baldwin 	if ((m->m_epg_flags & EPG_FLAG_ANON) != 0)
2044470e851cSJohn Baldwin 		return (tls->sw_encrypt(state, tls, m, NULL, 0));
2045470e851cSJohn Baldwin 
2046470e851cSJohn Baldwin 	/*
2047470e851cSJohn Baldwin 	 * For file-backed mbufs (from sendfile), anonymous wired
2048470e851cSJohn Baldwin 	 * pages are allocated and used as the encryption destination.
2049470e851cSJohn Baldwin 	 */
2050470e851cSJohn Baldwin 	if ((state->cbuf = ktls_buffer_alloc(wq, m)) != NULL) {
2051470e851cSJohn Baldwin 		len = ptoa(m->m_epg_npgs - 1) + m->m_epg_last_len -
2052470e851cSJohn Baldwin 		    m->m_epg_1st_off;
2053470e851cSJohn Baldwin 		state->dst_iov[0].iov_base = (char *)state->cbuf +
2054470e851cSJohn Baldwin 		    m->m_epg_1st_off;
2055470e851cSJohn Baldwin 		state->dst_iov[0].iov_len = len;
2056470e851cSJohn Baldwin 		state->parray[0] = DMAP_TO_PHYS((vm_offset_t)state->cbuf);
2057470e851cSJohn Baldwin 		i = 1;
2058470e851cSJohn Baldwin 	} else {
2059470e851cSJohn Baldwin 		off = m->m_epg_1st_off;
2060470e851cSJohn Baldwin 		for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2061470e851cSJohn Baldwin 			do {
2062470e851cSJohn Baldwin 				pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2063470e851cSJohn Baldwin 				    VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP |
2064470e851cSJohn Baldwin 				    VM_ALLOC_WIRED | VM_ALLOC_WAITFAIL);
2065470e851cSJohn Baldwin 			} while (pg == NULL);
2066470e851cSJohn Baldwin 
2067470e851cSJohn Baldwin 			len = m_epg_pagelen(m, i, off);
2068470e851cSJohn Baldwin 			state->parray[i] = VM_PAGE_TO_PHYS(pg);
2069470e851cSJohn Baldwin 			state->dst_iov[i].iov_base =
2070470e851cSJohn Baldwin 			    (char *)PHYS_TO_DMAP(state->parray[i]) + off;
2071470e851cSJohn Baldwin 			state->dst_iov[i].iov_len = len;
2072470e851cSJohn Baldwin 		}
2073470e851cSJohn Baldwin 	}
2074470e851cSJohn Baldwin 	KASSERT(i + 1 <= nitems(state->dst_iov), ("dst_iov is too small"));
2075470e851cSJohn Baldwin 	state->dst_iov[i].iov_base = m->m_epg_trail;
2076470e851cSJohn Baldwin 	state->dst_iov[i].iov_len = m->m_epg_trllen;
2077470e851cSJohn Baldwin 
2078470e851cSJohn Baldwin 	error = tls->sw_encrypt(state, tls, m, state->dst_iov, i + 1);
2079470e851cSJohn Baldwin 
2080470e851cSJohn Baldwin 	if (__predict_false(error != 0)) {
2081470e851cSJohn Baldwin 		/* Free the anonymous pages. */
2082470e851cSJohn Baldwin 		if (state->cbuf != NULL)
2083470e851cSJohn Baldwin 			uma_zfree(ktls_buffer_zone, state->cbuf);
2084470e851cSJohn Baldwin 		else {
2085470e851cSJohn Baldwin 			for (i = 0; i < m->m_epg_npgs; i++) {
2086470e851cSJohn Baldwin 				pg = PHYS_TO_VM_PAGE(state->parray[i]);
2087470e851cSJohn Baldwin 				(void)vm_page_unwire_noq(pg);
2088470e851cSJohn Baldwin 				vm_page_free(pg);
2089470e851cSJohn Baldwin 			}
2090470e851cSJohn Baldwin 		}
2091470e851cSJohn Baldwin 	}
2092470e851cSJohn Baldwin 	return (error);
2093470e851cSJohn Baldwin }
2094470e851cSJohn Baldwin 
2095b2e60773SJohn Baldwin void
2096b2e60773SJohn Baldwin ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
2097b2e60773SJohn Baldwin {
2098b2e60773SJohn Baldwin 	struct ktls_wq *wq;
2099b2e60773SJohn Baldwin 	bool running;
2100b2e60773SJohn Baldwin 
21016edfd179SGleb Smirnoff 	KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
21026edfd179SGleb Smirnoff 	    (M_EXTPG | M_NOTREADY)),
2103b2e60773SJohn Baldwin 	    ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
2104b2e60773SJohn Baldwin 	KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
2105b2e60773SJohn Baldwin 
21067b6c99d0SGleb Smirnoff 	KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
2107b2e60773SJohn Baldwin 
21087b6c99d0SGleb Smirnoff 	m->m_epg_enc_cnt = page_count;
2109b2e60773SJohn Baldwin 
2110b2e60773SJohn Baldwin 	/*
2111b2e60773SJohn Baldwin 	 * Save a pointer to the socket.  The caller is responsible
2112b2e60773SJohn Baldwin 	 * for taking an additional reference via soref().
2113b2e60773SJohn Baldwin 	 */
21147b6c99d0SGleb Smirnoff 	m->m_epg_so = so;
2115b2e60773SJohn Baldwin 
21167b6c99d0SGleb Smirnoff 	wq = &ktls_wq[m->m_epg_tls->wq_index];
2117b2e60773SJohn Baldwin 	mtx_lock(&wq->mtx);
21183c0e5685SJohn Baldwin 	STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2119b2e60773SJohn Baldwin 	running = wq->running;
2120b2e60773SJohn Baldwin 	mtx_unlock(&wq->mtx);
2121b2e60773SJohn Baldwin 	if (!running)
2122b2e60773SJohn Baldwin 		wakeup(wq);
21233c0e5685SJohn Baldwin 	counter_u64_add(ktls_cnt_tx_queued, 1);
2124b2e60773SJohn Baldwin }
2125b2e60773SJohn Baldwin 
2126470e851cSJohn Baldwin /*
2127470e851cSJohn Baldwin  * Once a file-backed mbuf (from sendfile) has been encrypted, free
2128470e851cSJohn Baldwin  * the pages from the file and replace them with the anonymous pages
2129470e851cSJohn Baldwin  * allocated in ktls_encrypt_record().
2130470e851cSJohn Baldwin  */
2131470e851cSJohn Baldwin static void
2132470e851cSJohn Baldwin ktls_finish_nonanon(struct mbuf *m, struct ktls_ocf_encrypt_state *state)
2133470e851cSJohn Baldwin {
2134470e851cSJohn Baldwin 	int i;
2135470e851cSJohn Baldwin 
2136470e851cSJohn Baldwin 	MPASS((m->m_epg_flags & EPG_FLAG_ANON) == 0);
2137470e851cSJohn Baldwin 
2138470e851cSJohn Baldwin 	/* Free the old pages. */
2139470e851cSJohn Baldwin 	m->m_ext.ext_free(m);
2140470e851cSJohn Baldwin 
2141470e851cSJohn Baldwin 	/* Replace them with the new pages. */
2142470e851cSJohn Baldwin 	if (state->cbuf != NULL) {
2143470e851cSJohn Baldwin 		for (i = 0; i < m->m_epg_npgs; i++)
2144470e851cSJohn Baldwin 			m->m_epg_pa[i] = state->parray[0] + ptoa(i);
2145470e851cSJohn Baldwin 
2146470e851cSJohn Baldwin 		/* Contig pages should go back to the cache. */
2147470e851cSJohn Baldwin 		m->m_ext.ext_free = ktls_free_mext_contig;
2148470e851cSJohn Baldwin 	} else {
2149470e851cSJohn Baldwin 		for (i = 0; i < m->m_epg_npgs; i++)
2150470e851cSJohn Baldwin 			m->m_epg_pa[i] = state->parray[i];
2151470e851cSJohn Baldwin 
2152470e851cSJohn Baldwin 		/* Use the basic free routine. */
2153470e851cSJohn Baldwin 		m->m_ext.ext_free = mb_free_mext_pgs;
2154470e851cSJohn Baldwin 	}
2155470e851cSJohn Baldwin 
2156470e851cSJohn Baldwin 	/* Pages are now writable. */
2157470e851cSJohn Baldwin 	m->m_epg_flags |= EPG_FLAG_ANON;
2158470e851cSJohn Baldwin }
21596b313a3aSJohn Baldwin 
2160b2e60773SJohn Baldwin static __noinline void
216149f6925cSMark Johnston ktls_encrypt(struct ktls_wq *wq, struct mbuf *top)
2162b2e60773SJohn Baldwin {
2163470e851cSJohn Baldwin 	struct ktls_ocf_encrypt_state state;
2164b2e60773SJohn Baldwin 	struct ktls_session *tls;
2165b2e60773SJohn Baldwin 	struct socket *so;
2166d90fe9d0SGleb Smirnoff 	struct mbuf *m;
2167470e851cSJohn Baldwin 	int error, npages, total_pages;
2168b2e60773SJohn Baldwin 
21697b6c99d0SGleb Smirnoff 	so = top->m_epg_so;
21707b6c99d0SGleb Smirnoff 	tls = top->m_epg_tls;
2171d90fe9d0SGleb Smirnoff 	KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
2172d90fe9d0SGleb Smirnoff 	KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
2173b2e60773SJohn Baldwin #ifdef INVARIANTS
21747b6c99d0SGleb Smirnoff 	top->m_epg_so = NULL;
2175b2e60773SJohn Baldwin #endif
21767b6c99d0SGleb Smirnoff 	total_pages = top->m_epg_enc_cnt;
2177b2e60773SJohn Baldwin 	npages = 0;
2178b2e60773SJohn Baldwin 
2179b2e60773SJohn Baldwin 	/*
2180b2e60773SJohn Baldwin 	 * Encrypt the TLS records in the chain of mbufs starting with
2181b2e60773SJohn Baldwin 	 * 'top'.  'total_pages' gives us a total count of pages and is
2182b2e60773SJohn Baldwin 	 * used to know when we have finished encrypting the TLS
2183b2e60773SJohn Baldwin 	 * records originally queued with 'top'.
2184b2e60773SJohn Baldwin 	 *
2185b2e60773SJohn Baldwin 	 * NB: These mbufs are queued in the socket buffer and
2186b2e60773SJohn Baldwin 	 * 'm_next' is traversing the mbufs in the socket buffer.  The
2187b2e60773SJohn Baldwin 	 * socket buffer lock is not held while traversing this chain.
2188b2e60773SJohn Baldwin 	 * Since the mbufs are all marked M_NOTREADY their 'm_next'
2189b2e60773SJohn Baldwin 	 * pointers should be stable.  However, the 'm_next' of the
2190b2e60773SJohn Baldwin 	 * last mbuf encrypted is not necessarily NULL.  It can point
2191b2e60773SJohn Baldwin 	 * to other mbufs appended while 'top' was on the TLS work
2192b2e60773SJohn Baldwin 	 * queue.
2193b2e60773SJohn Baldwin 	 *
2194b2e60773SJohn Baldwin 	 * Each mbuf holds an entire TLS record.
2195b2e60773SJohn Baldwin 	 */
2196b2e60773SJohn Baldwin 	error = 0;
2197b2e60773SJohn Baldwin 	for (m = top; npages != total_pages; m = m->m_next) {
21987b6c99d0SGleb Smirnoff 		KASSERT(m->m_epg_tls == tls,
2199b2e60773SJohn Baldwin 		    ("different TLS sessions in a single mbuf chain: %p vs %p",
22007b6c99d0SGleb Smirnoff 		    tls, m->m_epg_tls));
22017b6c99d0SGleb Smirnoff 		KASSERT(npages + m->m_epg_npgs <= total_pages,
2202b2e60773SJohn Baldwin 		    ("page count mismatch: top %p, total_pages %d, m %p", top,
2203b2e60773SJohn Baldwin 		    total_pages, m));
2204b2e60773SJohn Baldwin 
2205470e851cSJohn Baldwin 		error = ktls_encrypt_record(wq, m, tls, &state);
220621e3c1fbSJohn Baldwin 		if (error) {
220721e3c1fbSJohn Baldwin 			counter_u64_add(ktls_offload_failed_crypto, 1);
220821e3c1fbSJohn Baldwin 			break;
220921e3c1fbSJohn Baldwin 		}
221021e3c1fbSJohn Baldwin 
2211470e851cSJohn Baldwin 		if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
2212470e851cSJohn Baldwin 			ktls_finish_nonanon(m, &state);
2213470e851cSJohn Baldwin 
2214d16cb228SJohn Baldwin 		npages += m->m_epg_nrdy;
2215b2e60773SJohn Baldwin 
2216b2e60773SJohn Baldwin 		/*
2217b2e60773SJohn Baldwin 		 * Drop a reference to the session now that it is no
2218b2e60773SJohn Baldwin 		 * longer needed.  Existing code depends on encrypted
2219b2e60773SJohn Baldwin 		 * records having no associated session vs
2220b2e60773SJohn Baldwin 		 * yet-to-be-encrypted records having an associated
2221b2e60773SJohn Baldwin 		 * session.
2222b2e60773SJohn Baldwin 		 */
22237b6c99d0SGleb Smirnoff 		m->m_epg_tls = NULL;
2224b2e60773SJohn Baldwin 		ktls_free(tls);
2225b2e60773SJohn Baldwin 	}
2226b2e60773SJohn Baldwin 
2227b2e60773SJohn Baldwin 	CURVNET_SET(so->so_vnet);
2228b2e60773SJohn Baldwin 	if (error == 0) {
2229b2e60773SJohn Baldwin 		(void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
2230b2e60773SJohn Baldwin 	} else {
2231b2e60773SJohn Baldwin 		so->so_proto->pr_usrreqs->pru_abort(so);
2232b2e60773SJohn Baldwin 		so->so_error = EIO;
2233b2e60773SJohn Baldwin 		mb_free_notready(top, total_pages);
2234b2e60773SJohn Baldwin 	}
2235b2e60773SJohn Baldwin 
2236b2e60773SJohn Baldwin 	SOCK_LOCK(so);
2237b2e60773SJohn Baldwin 	sorele(so);
2238b2e60773SJohn Baldwin 	CURVNET_RESTORE();
2239b2e60773SJohn Baldwin }
2240b2e60773SJohn Baldwin 
2241470e851cSJohn Baldwin void
2242470e851cSJohn Baldwin ktls_encrypt_cb(struct ktls_ocf_encrypt_state *state, int error)
2243470e851cSJohn Baldwin {
2244470e851cSJohn Baldwin 	struct ktls_session *tls;
2245470e851cSJohn Baldwin 	struct socket *so;
2246470e851cSJohn Baldwin 	struct mbuf *m;
2247470e851cSJohn Baldwin 	int npages;
2248470e851cSJohn Baldwin 
2249470e851cSJohn Baldwin 	m = state->m;
2250470e851cSJohn Baldwin 
2251470e851cSJohn Baldwin 	if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
2252470e851cSJohn Baldwin 		ktls_finish_nonanon(m, state);
2253470e851cSJohn Baldwin 
2254470e851cSJohn Baldwin 	so = state->so;
2255470e851cSJohn Baldwin 	free(state, M_KTLS);
2256470e851cSJohn Baldwin 
2257470e851cSJohn Baldwin 	/*
2258470e851cSJohn Baldwin 	 * Drop a reference to the session now that it is no longer
2259470e851cSJohn Baldwin 	 * needed.  Existing code depends on encrypted records having
2260470e851cSJohn Baldwin 	 * no associated session vs yet-to-be-encrypted records having
2261470e851cSJohn Baldwin 	 * an associated session.
2262470e851cSJohn Baldwin 	 */
2263470e851cSJohn Baldwin 	tls = m->m_epg_tls;
2264470e851cSJohn Baldwin 	m->m_epg_tls = NULL;
2265470e851cSJohn Baldwin 	ktls_free(tls);
2266470e851cSJohn Baldwin 
2267470e851cSJohn Baldwin 	if (error != 0)
2268470e851cSJohn Baldwin 		counter_u64_add(ktls_offload_failed_crypto, 1);
2269470e851cSJohn Baldwin 
2270470e851cSJohn Baldwin 	CURVNET_SET(so->so_vnet);
2271470e851cSJohn Baldwin 	npages = m->m_epg_nrdy;
2272470e851cSJohn Baldwin 
2273470e851cSJohn Baldwin 	if (error == 0) {
2274470e851cSJohn Baldwin 		(void)(*so->so_proto->pr_usrreqs->pru_ready)(so, m, npages);
2275470e851cSJohn Baldwin 	} else {
2276470e851cSJohn Baldwin 		so->so_proto->pr_usrreqs->pru_abort(so);
2277470e851cSJohn Baldwin 		so->so_error = EIO;
2278470e851cSJohn Baldwin 		mb_free_notready(m, npages);
2279470e851cSJohn Baldwin 	}
2280470e851cSJohn Baldwin 
2281470e851cSJohn Baldwin 	SOCK_LOCK(so);
2282470e851cSJohn Baldwin 	sorele(so);
2283470e851cSJohn Baldwin 	CURVNET_RESTORE();
2284470e851cSJohn Baldwin }
2285470e851cSJohn Baldwin 
2286470e851cSJohn Baldwin /*
2287470e851cSJohn Baldwin  * Similar to ktls_encrypt, but used with asynchronous OCF backends
2288470e851cSJohn Baldwin  * (coprocessors) where encryption does not use host CPU resources and
2289470e851cSJohn Baldwin  * it can be beneficial to queue more requests than CPUs.
2290470e851cSJohn Baldwin  */
2291470e851cSJohn Baldwin static __noinline void
2292470e851cSJohn Baldwin ktls_encrypt_async(struct ktls_wq *wq, struct mbuf *top)
2293470e851cSJohn Baldwin {
2294470e851cSJohn Baldwin 	struct ktls_ocf_encrypt_state *state;
2295470e851cSJohn Baldwin 	struct ktls_session *tls;
2296470e851cSJohn Baldwin 	struct socket *so;
2297470e851cSJohn Baldwin 	struct mbuf *m, *n;
2298470e851cSJohn Baldwin 	int error, mpages, npages, total_pages;
2299470e851cSJohn Baldwin 
2300470e851cSJohn Baldwin 	so = top->m_epg_so;
2301470e851cSJohn Baldwin 	tls = top->m_epg_tls;
2302470e851cSJohn Baldwin 	KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
2303470e851cSJohn Baldwin 	KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
2304470e851cSJohn Baldwin #ifdef INVARIANTS
2305470e851cSJohn Baldwin 	top->m_epg_so = NULL;
2306470e851cSJohn Baldwin #endif
2307470e851cSJohn Baldwin 	total_pages = top->m_epg_enc_cnt;
2308470e851cSJohn Baldwin 	npages = 0;
2309470e851cSJohn Baldwin 
2310470e851cSJohn Baldwin 	error = 0;
2311470e851cSJohn Baldwin 	for (m = top; npages != total_pages; m = n) {
2312470e851cSJohn Baldwin 		KASSERT(m->m_epg_tls == tls,
2313470e851cSJohn Baldwin 		    ("different TLS sessions in a single mbuf chain: %p vs %p",
2314470e851cSJohn Baldwin 		    tls, m->m_epg_tls));
2315470e851cSJohn Baldwin 		KASSERT(npages + m->m_epg_npgs <= total_pages,
2316470e851cSJohn Baldwin 		    ("page count mismatch: top %p, total_pages %d, m %p", top,
2317470e851cSJohn Baldwin 		    total_pages, m));
2318470e851cSJohn Baldwin 
2319470e851cSJohn Baldwin 		state = malloc(sizeof(*state), M_KTLS, M_WAITOK | M_ZERO);
2320470e851cSJohn Baldwin 		soref(so);
2321470e851cSJohn Baldwin 		state->so = so;
2322470e851cSJohn Baldwin 		state->m = m;
2323470e851cSJohn Baldwin 
2324470e851cSJohn Baldwin 		mpages = m->m_epg_nrdy;
2325470e851cSJohn Baldwin 		n = m->m_next;
2326470e851cSJohn Baldwin 
2327470e851cSJohn Baldwin 		error = ktls_encrypt_record(wq, m, tls, state);
2328470e851cSJohn Baldwin 		if (error) {
2329470e851cSJohn Baldwin 			counter_u64_add(ktls_offload_failed_crypto, 1);
2330470e851cSJohn Baldwin 			free(state, M_KTLS);
2331470e851cSJohn Baldwin 			CURVNET_SET(so->so_vnet);
2332470e851cSJohn Baldwin 			SOCK_LOCK(so);
2333470e851cSJohn Baldwin 			sorele(so);
2334470e851cSJohn Baldwin 			CURVNET_RESTORE();
2335470e851cSJohn Baldwin 			break;
2336470e851cSJohn Baldwin 		}
2337470e851cSJohn Baldwin 
2338470e851cSJohn Baldwin 		npages += mpages;
2339470e851cSJohn Baldwin 	}
2340470e851cSJohn Baldwin 
2341470e851cSJohn Baldwin 	CURVNET_SET(so->so_vnet);
2342470e851cSJohn Baldwin 	if (error != 0) {
2343470e851cSJohn Baldwin 		so->so_proto->pr_usrreqs->pru_abort(so);
2344470e851cSJohn Baldwin 		so->so_error = EIO;
2345470e851cSJohn Baldwin 		mb_free_notready(m, total_pages - npages);
2346470e851cSJohn Baldwin 	}
2347470e851cSJohn Baldwin 
2348470e851cSJohn Baldwin 	SOCK_LOCK(so);
2349470e851cSJohn Baldwin 	sorele(so);
2350470e851cSJohn Baldwin 	CURVNET_RESTORE();
2351470e851cSJohn Baldwin }
2352470e851cSJohn Baldwin 
2353b2e60773SJohn Baldwin static void
235498215005SAndrew Gallatin ktls_alloc_thread(void *ctx)
235598215005SAndrew Gallatin {
235698215005SAndrew Gallatin 	struct ktls_domain_info *ktls_domain = ctx;
235798215005SAndrew Gallatin 	struct ktls_alloc_thread *sc = &ktls_domain->alloc_td;
235898215005SAndrew Gallatin 	void **buf;
235998215005SAndrew Gallatin 	struct sysctl_oid *oid;
236098215005SAndrew Gallatin 	char name[80];
236198215005SAndrew Gallatin 	int i, nbufs;
236298215005SAndrew Gallatin 
236398215005SAndrew Gallatin 	curthread->td_domain.dr_policy =
236498215005SAndrew Gallatin 	    DOMAINSET_PREF(PCPU_GET(domain));
236598215005SAndrew Gallatin 	snprintf(name, sizeof(name), "domain%d", PCPU_GET(domain));
236698215005SAndrew Gallatin 	if (bootverbose)
236798215005SAndrew Gallatin 		printf("Starting KTLS alloc thread for domain %d\n",
236898215005SAndrew Gallatin 		    PCPU_GET(domain));
236998215005SAndrew Gallatin 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_kern_ipc_tls), OID_AUTO,
237098215005SAndrew Gallatin 	    name, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
237198215005SAndrew Gallatin 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "allocs",
237298215005SAndrew Gallatin 	    CTLFLAG_RD,  &sc->allocs, 0, "buffers allocated");
237398215005SAndrew Gallatin 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "wakeups",
237498215005SAndrew Gallatin 	    CTLFLAG_RD,  &sc->wakeups, 0, "thread wakeups");
237598215005SAndrew Gallatin 	SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "running",
237698215005SAndrew Gallatin 	    CTLFLAG_RD,  &sc->running, 0, "thread running");
237798215005SAndrew Gallatin 
237898215005SAndrew Gallatin 	buf = NULL;
237998215005SAndrew Gallatin 	nbufs = 0;
238098215005SAndrew Gallatin 	for (;;) {
238198215005SAndrew Gallatin 		atomic_store_int(&sc->running, 0);
238209066b98SAndrew Gallatin 		tsleep(sc, PZERO | PNOLOCK, "-",  0);
238398215005SAndrew Gallatin 		atomic_store_int(&sc->running, 1);
238498215005SAndrew Gallatin 		sc->wakeups++;
238598215005SAndrew Gallatin 		if (nbufs != ktls_max_alloc) {
238698215005SAndrew Gallatin 			free(buf, M_KTLS);
238798215005SAndrew Gallatin 			nbufs = atomic_load_int(&ktls_max_alloc);
238898215005SAndrew Gallatin 			buf = malloc(sizeof(void *) * nbufs, M_KTLS,
238998215005SAndrew Gallatin 			    M_WAITOK | M_ZERO);
239098215005SAndrew Gallatin 		}
239198215005SAndrew Gallatin 		/*
239298215005SAndrew Gallatin 		 * Below we allocate nbufs with different allocation
239398215005SAndrew Gallatin 		 * flags than we use when allocating normally during
239498215005SAndrew Gallatin 		 * encryption in the ktls worker thread.  We specify
239598215005SAndrew Gallatin 		 * M_NORECLAIM in the worker thread. However, we omit
239698215005SAndrew Gallatin 		 * that flag here and add M_WAITOK so that the VM
239798215005SAndrew Gallatin 		 * system is permitted to perform expensive work to
239898215005SAndrew Gallatin 		 * defragment memory.  We do this here, as it does not
239998215005SAndrew Gallatin 		 * matter if this thread blocks.  If we block a ktls
240098215005SAndrew Gallatin 		 * worker thread, we risk developing backlogs of
240198215005SAndrew Gallatin 		 * buffers to be encrypted, leading to surges of
240298215005SAndrew Gallatin 		 * traffic and potential NIC output drops.
240398215005SAndrew Gallatin 		 */
240498215005SAndrew Gallatin 		for (i = 0; i < nbufs; i++) {
240598215005SAndrew Gallatin 			buf[i] = uma_zalloc(ktls_buffer_zone, M_WAITOK);
240698215005SAndrew Gallatin 			sc->allocs++;
240798215005SAndrew Gallatin 		}
240898215005SAndrew Gallatin 		for (i = 0; i < nbufs; i++) {
240998215005SAndrew Gallatin 			uma_zfree(ktls_buffer_zone, buf[i]);
241098215005SAndrew Gallatin 			buf[i] = NULL;
241198215005SAndrew Gallatin 		}
241298215005SAndrew Gallatin 	}
241398215005SAndrew Gallatin }
241498215005SAndrew Gallatin 
241598215005SAndrew Gallatin static void
2416b2e60773SJohn Baldwin ktls_work_thread(void *ctx)
2417b2e60773SJohn Baldwin {
2418b2e60773SJohn Baldwin 	struct ktls_wq *wq = ctx;
2419d90fe9d0SGleb Smirnoff 	struct mbuf *m, *n;
24203c0e5685SJohn Baldwin 	struct socket *so, *son;
24213c0e5685SJohn Baldwin 	STAILQ_HEAD(, mbuf) local_m_head;
24223c0e5685SJohn Baldwin 	STAILQ_HEAD(, socket) local_so_head;
2423b2e60773SJohn Baldwin 
242402bc3865SAndrew Gallatin 	if (ktls_bind_threads > 1) {
242502bc3865SAndrew Gallatin 		curthread->td_domain.dr_policy =
242602bc3865SAndrew Gallatin 			DOMAINSET_PREF(PCPU_GET(domain));
242702bc3865SAndrew Gallatin 	}
2428b2e60773SJohn Baldwin #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
2429b2e60773SJohn Baldwin 	fpu_kern_thread(0);
2430b2e60773SJohn Baldwin #endif
2431b2e60773SJohn Baldwin 	for (;;) {
2432b2e60773SJohn Baldwin 		mtx_lock(&wq->mtx);
24333c0e5685SJohn Baldwin 		while (STAILQ_EMPTY(&wq->m_head) &&
24343c0e5685SJohn Baldwin 		    STAILQ_EMPTY(&wq->so_head)) {
2435b2e60773SJohn Baldwin 			wq->running = false;
2436b2e60773SJohn Baldwin 			mtx_sleep(wq, &wq->mtx, 0, "-", 0);
2437b2e60773SJohn Baldwin 			wq->running = true;
2438b2e60773SJohn Baldwin 		}
2439b2e60773SJohn Baldwin 
24403c0e5685SJohn Baldwin 		STAILQ_INIT(&local_m_head);
24413c0e5685SJohn Baldwin 		STAILQ_CONCAT(&local_m_head, &wq->m_head);
24423c0e5685SJohn Baldwin 		STAILQ_INIT(&local_so_head);
24433c0e5685SJohn Baldwin 		STAILQ_CONCAT(&local_so_head, &wq->so_head);
2444b2e60773SJohn Baldwin 		mtx_unlock(&wq->mtx);
2445b2e60773SJohn Baldwin 
24463c0e5685SJohn Baldwin 		STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
24477b6c99d0SGleb Smirnoff 			if (m->m_epg_flags & EPG_FLAG_2FREE) {
24487b6c99d0SGleb Smirnoff 				ktls_free(m->m_epg_tls);
2449904a08f3SMateusz Guzik 				m_free_raw(m);
2450eeec8348SGleb Smirnoff 			} else {
2451470e851cSJohn Baldwin 				if (m->m_epg_tls->sync_dispatch)
245249f6925cSMark Johnston 					ktls_encrypt(wq, m);
2453470e851cSJohn Baldwin 				else
2454470e851cSJohn Baldwin 					ktls_encrypt_async(wq, m);
24553c0e5685SJohn Baldwin 				counter_u64_add(ktls_cnt_tx_queued, -1);
2456b2e60773SJohn Baldwin 			}
2457b2e60773SJohn Baldwin 		}
24583c0e5685SJohn Baldwin 
24593c0e5685SJohn Baldwin 		STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
24603c0e5685SJohn Baldwin 			ktls_decrypt(so);
24613c0e5685SJohn Baldwin 			counter_u64_add(ktls_cnt_rx_queued, -1);
24623c0e5685SJohn Baldwin 		}
2463b2e60773SJohn Baldwin 	}
2464b2e60773SJohn Baldwin }
246528d0a740SAndrew Gallatin 
24664150a5a8SAndrew Gallatin #if defined(INET) || defined(INET6)
246728d0a740SAndrew Gallatin static void
246828d0a740SAndrew Gallatin ktls_disable_ifnet_help(void *context, int pending __unused)
246928d0a740SAndrew Gallatin {
247028d0a740SAndrew Gallatin 	struct ktls_session *tls;
247128d0a740SAndrew Gallatin 	struct inpcb *inp;
247228d0a740SAndrew Gallatin 	struct tcpcb *tp;
247328d0a740SAndrew Gallatin 	struct socket *so;
247428d0a740SAndrew Gallatin 	int err;
247528d0a740SAndrew Gallatin 
247628d0a740SAndrew Gallatin 	tls = context;
247728d0a740SAndrew Gallatin 	inp = tls->inp;
247828d0a740SAndrew Gallatin 	if (inp == NULL)
247928d0a740SAndrew Gallatin 		return;
248028d0a740SAndrew Gallatin 	INP_WLOCK(inp);
248128d0a740SAndrew Gallatin 	so = inp->inp_socket;
248228d0a740SAndrew Gallatin 	MPASS(so != NULL);
248328d0a740SAndrew Gallatin 	if ((inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) ||
248428d0a740SAndrew Gallatin 	    (inp->inp_flags2 & INP_FREED)) {
248528d0a740SAndrew Gallatin 		goto out;
248628d0a740SAndrew Gallatin 	}
248728d0a740SAndrew Gallatin 
248828d0a740SAndrew Gallatin 	if (so->so_snd.sb_tls_info != NULL)
248928d0a740SAndrew Gallatin 		err = ktls_set_tx_mode(so, TCP_TLS_MODE_SW);
249028d0a740SAndrew Gallatin 	else
249128d0a740SAndrew Gallatin 		err = ENXIO;
249228d0a740SAndrew Gallatin 	if (err == 0) {
249328d0a740SAndrew Gallatin 		counter_u64_add(ktls_ifnet_disable_ok, 1);
249428d0a740SAndrew Gallatin 		/* ktls_set_tx_mode() drops inp wlock, so recheck flags */
249528d0a740SAndrew Gallatin 		if ((inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) == 0 &&
249628d0a740SAndrew Gallatin 		    (inp->inp_flags2 & INP_FREED) == 0 &&
249728d0a740SAndrew Gallatin 		    (tp = intotcpcb(inp)) != NULL &&
249828d0a740SAndrew Gallatin 		    tp->t_fb->tfb_hwtls_change != NULL)
249928d0a740SAndrew Gallatin 			(*tp->t_fb->tfb_hwtls_change)(tp, 0);
250028d0a740SAndrew Gallatin 	} else {
250128d0a740SAndrew Gallatin 		counter_u64_add(ktls_ifnet_disable_fail, 1);
250228d0a740SAndrew Gallatin 	}
250328d0a740SAndrew Gallatin 
250428d0a740SAndrew Gallatin out:
250528d0a740SAndrew Gallatin 	SOCK_LOCK(so);
250628d0a740SAndrew Gallatin 	sorele(so);
250728d0a740SAndrew Gallatin 	if (!in_pcbrele_wlocked(inp))
250828d0a740SAndrew Gallatin 		INP_WUNLOCK(inp);
250928d0a740SAndrew Gallatin 	ktls_free(tls);
251028d0a740SAndrew Gallatin }
251128d0a740SAndrew Gallatin 
251228d0a740SAndrew Gallatin /*
251328d0a740SAndrew Gallatin  * Called when re-transmits are becoming a substantial portion of the
251428d0a740SAndrew Gallatin  * sends on this connection.  When this happens, we transition the
251528d0a740SAndrew Gallatin  * connection to software TLS.  This is needed because most inline TLS
251628d0a740SAndrew Gallatin  * NICs keep crypto state only for in-order transmits.  This means
251728d0a740SAndrew Gallatin  * that to handle a TCP rexmit (which is out-of-order), the NIC must
251828d0a740SAndrew Gallatin  * re-DMA the entire TLS record up to and including the current
251928d0a740SAndrew Gallatin  * segment.  This means that when re-transmitting the last ~1448 byte
252028d0a740SAndrew Gallatin  * segment of a 16KB TLS record, we could wind up re-DMA'ing an order
252128d0a740SAndrew Gallatin  * of magnitude more data than we are sending.  This can cause the
252228d0a740SAndrew Gallatin  * PCIe link to saturate well before the network, which can cause
252328d0a740SAndrew Gallatin  * output drops, and a general loss of capacity.
252428d0a740SAndrew Gallatin  */
252528d0a740SAndrew Gallatin void
252628d0a740SAndrew Gallatin ktls_disable_ifnet(void *arg)
252728d0a740SAndrew Gallatin {
252828d0a740SAndrew Gallatin 	struct tcpcb *tp;
252928d0a740SAndrew Gallatin 	struct inpcb *inp;
253028d0a740SAndrew Gallatin 	struct socket *so;
253128d0a740SAndrew Gallatin 	struct ktls_session *tls;
253228d0a740SAndrew Gallatin 
253328d0a740SAndrew Gallatin 	tp = arg;
253428d0a740SAndrew Gallatin 	inp = tp->t_inpcb;
253528d0a740SAndrew Gallatin 	INP_WLOCK_ASSERT(inp);
253628d0a740SAndrew Gallatin 	so = inp->inp_socket;
253728d0a740SAndrew Gallatin 	SOCK_LOCK(so);
253828d0a740SAndrew Gallatin 	tls = so->so_snd.sb_tls_info;
253928d0a740SAndrew Gallatin 	if (tls->disable_ifnet_pending) {
254028d0a740SAndrew Gallatin 		SOCK_UNLOCK(so);
254128d0a740SAndrew Gallatin 		return;
254228d0a740SAndrew Gallatin 	}
254328d0a740SAndrew Gallatin 
254428d0a740SAndrew Gallatin 	/*
254528d0a740SAndrew Gallatin 	 * note that disable_ifnet_pending is never cleared; disabling
254628d0a740SAndrew Gallatin 	 * ifnet can only be done once per session, so we never want
254728d0a740SAndrew Gallatin 	 * to do it again
254828d0a740SAndrew Gallatin 	 */
254928d0a740SAndrew Gallatin 
255028d0a740SAndrew Gallatin 	(void)ktls_hold(tls);
255128d0a740SAndrew Gallatin 	in_pcbref(inp);
255228d0a740SAndrew Gallatin 	soref(so);
255328d0a740SAndrew Gallatin 	tls->disable_ifnet_pending = true;
255428d0a740SAndrew Gallatin 	tls->inp = inp;
255528d0a740SAndrew Gallatin 	SOCK_UNLOCK(so);
255628d0a740SAndrew Gallatin 	TASK_INIT(&tls->disable_ifnet_task, 0, ktls_disable_ifnet_help, tls);
255728d0a740SAndrew Gallatin 	(void)taskqueue_enqueue(taskqueue_thread, &tls->disable_ifnet_task);
255828d0a740SAndrew Gallatin }
25594150a5a8SAndrew Gallatin #endif
2560