xref: /freebsd/sys/kern/uipc_ktls.c (revision 1a03b40a134318f26c93d85087de6a588b65f217)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2014-2019 Netflix Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 #include "opt_inet.h"
30 #include "opt_inet6.h"
31 #include "opt_kern_tls.h"
32 #include "opt_ratelimit.h"
33 #include "opt_rss.h"
34 
35 #include <sys/param.h>
36 #include <sys/kernel.h>
37 #include <sys/domainset.h>
38 #include <sys/endian.h>
39 #include <sys/ktls.h>
40 #include <sys/lock.h>
41 #include <sys/mbuf.h>
42 #include <sys/mutex.h>
43 #include <sys/rmlock.h>
44 #include <sys/proc.h>
45 #include <sys/protosw.h>
46 #include <sys/refcount.h>
47 #include <sys/smp.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/taskqueue.h>
52 #include <sys/kthread.h>
53 #include <sys/uio.h>
54 #include <sys/vmmeter.h>
55 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
56 #include <machine/pcb.h>
57 #endif
58 #include <machine/vmparam.h>
59 #include <net/if.h>
60 #include <net/if_var.h>
61 #ifdef RSS
62 #include <net/netisr.h>
63 #include <net/rss_config.h>
64 #endif
65 #include <net/route.h>
66 #include <net/route/nhop.h>
67 #include <netinet/in.h>
68 #include <netinet/in_pcb.h>
69 #include <netinet/tcp_var.h>
70 #ifdef TCP_OFFLOAD
71 #include <netinet/tcp_offload.h>
72 #endif
73 #include <opencrypto/cryptodev.h>
74 #include <opencrypto/ktls.h>
75 #include <vm/vm.h>
76 #include <vm/vm_pageout.h>
77 #include <vm/vm_page.h>
78 #include <vm/vm_pagequeue.h>
79 
80 typedef enum {
81 	KTLS_MBUF_CRYPTO_ST_MIXED = 0,
82 	KTLS_MBUF_CRYPTO_ST_ENCRYPTED = 1,
83 	KTLS_MBUF_CRYPTO_ST_DECRYPTED = -1,
84 	KTLS_MBUF_CRYPTO_ST_SHAREDMBUF = -2,
85 } ktls_mbuf_crypto_st_t;
86 
87 struct ktls_wq {
88 	struct mtx	mtx;
89 	STAILQ_HEAD(, mbuf) m_head;
90 	STAILQ_HEAD(, socket) so_head;
91 	bool		running;
92 	int		lastallocfail;
93 } __aligned(CACHE_LINE_SIZE);
94 
95 struct ktls_reclaim_thread {
96 	uint64_t wakeups;
97 	uint64_t reclaims;
98 	struct thread *td;
99 	int running;
100 };
101 
102 struct ktls_domain_info {
103 	int count;
104 	int cpu[MAXCPU];
105 	struct ktls_reclaim_thread reclaim_td;
106 };
107 
108 struct ktls_domain_info ktls_domains[MAXMEMDOM];
109 static struct ktls_wq *ktls_wq;
110 static struct proc *ktls_proc;
111 static uma_zone_t ktls_session_zone;
112 static uma_zone_t ktls_buffer_zone;
113 static uint16_t ktls_cpuid_lookup[MAXCPU];
114 static int ktls_init_state;
115 static struct sx ktls_init_lock;
116 SX_SYSINIT(ktls_init_lock, &ktls_init_lock, "ktls init");
117 
118 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
119     "Kernel TLS offload");
120 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
121     "Kernel TLS offload stats");
122 
123 #ifdef RSS
124 static int ktls_bind_threads = 1;
125 #else
126 static int ktls_bind_threads;
127 #endif
128 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
129     &ktls_bind_threads, 0,
130     "Bind crypto threads to cores (1) or cores and domains (2) at boot");
131 
132 static u_int ktls_maxlen = 16384;
133 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RDTUN,
134     &ktls_maxlen, 0, "Maximum TLS record size");
135 
136 static int ktls_number_threads;
137 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
138     &ktls_number_threads, 0,
139     "Number of TLS threads in thread-pool");
140 
141 unsigned int ktls_ifnet_max_rexmit_pct = 2;
142 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, ifnet_max_rexmit_pct, CTLFLAG_RWTUN,
143     &ktls_ifnet_max_rexmit_pct, 2,
144     "Max percent bytes retransmitted before ifnet TLS is disabled");
145 
146 static bool ktls_offload_enable = true;
147 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RWTUN,
148     &ktls_offload_enable, 0,
149     "Enable support for kernel TLS offload");
150 
151 static bool ktls_cbc_enable = true;
152 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RWTUN,
153     &ktls_cbc_enable, 1,
154     "Enable support of AES-CBC crypto for kernel TLS");
155 
156 static bool ktls_sw_buffer_cache = true;
157 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, sw_buffer_cache, CTLFLAG_RDTUN,
158     &ktls_sw_buffer_cache, 1,
159     "Enable caching of output buffers for SW encryption");
160 
161 static int ktls_max_reclaim = 1024;
162 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, max_reclaim, CTLFLAG_RWTUN,
163     &ktls_max_reclaim, 128,
164     "Max number of 16k buffers to reclaim in thread context");
165 
166 static COUNTER_U64_DEFINE_EARLY(ktls_tasks_active);
167 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
168     &ktls_tasks_active, "Number of active tasks");
169 
170 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_tx_pending);
171 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_pending, CTLFLAG_RD,
172     &ktls_cnt_tx_pending,
173     "Number of TLS 1.0 records waiting for earlier TLS records");
174 
175 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_tx_queued);
176 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_inqueue, CTLFLAG_RD,
177     &ktls_cnt_tx_queued,
178     "Number of TLS records in queue to tasks for SW encryption");
179 
180 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_rx_queued);
181 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_rx_inqueue, CTLFLAG_RD,
182     &ktls_cnt_rx_queued,
183     "Number of TLS sockets in queue to tasks for SW decryption");
184 
185 static COUNTER_U64_DEFINE_EARLY(ktls_offload_total);
186 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
187     CTLFLAG_RD, &ktls_offload_total,
188     "Total successful TLS setups (parameters set)");
189 
190 static COUNTER_U64_DEFINE_EARLY(ktls_offload_enable_calls);
191 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
192     CTLFLAG_RD, &ktls_offload_enable_calls,
193     "Total number of TLS enable calls made");
194 
195 static COUNTER_U64_DEFINE_EARLY(ktls_offload_active);
196 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
197     &ktls_offload_active, "Total Active TLS sessions");
198 
199 static COUNTER_U64_DEFINE_EARLY(ktls_offload_corrupted_records);
200 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, corrupted_records, CTLFLAG_RD,
201     &ktls_offload_corrupted_records, "Total corrupted TLS records received");
202 
203 static COUNTER_U64_DEFINE_EARLY(ktls_offload_failed_crypto);
204 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
205     &ktls_offload_failed_crypto, "Total TLS crypto failures");
206 
207 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_ifnet);
208 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
209     &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
210 
211 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_sw);
212 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
213     &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
214 
215 static COUNTER_U64_DEFINE_EARLY(ktls_switch_failed);
216 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
217     &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
218 
219 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_disable_fail);
220 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, ifnet_disable_failed, CTLFLAG_RD,
221     &ktls_ifnet_disable_fail, "TLS sessions unable to switch to SW from ifnet");
222 
223 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_disable_ok);
224 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, ifnet_disable_ok, CTLFLAG_RD,
225     &ktls_ifnet_disable_ok, "TLS sessions able to switch to SW from ifnet");
226 
227 static COUNTER_U64_DEFINE_EARLY(ktls_destroy_task);
228 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, destroy_task, CTLFLAG_RD,
229     &ktls_destroy_task,
230     "Number of times ktls session was destroyed via taskqueue");
231 
232 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
233     "Software TLS session stats");
234 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
235     "Hardware (ifnet) TLS session stats");
236 #ifdef TCP_OFFLOAD
237 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
238     "TOE TLS session stats");
239 #endif
240 
241 static COUNTER_U64_DEFINE_EARLY(ktls_sw_cbc);
242 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
243     "Active number of software TLS sessions using AES-CBC");
244 
245 static COUNTER_U64_DEFINE_EARLY(ktls_sw_gcm);
246 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
247     "Active number of software TLS sessions using AES-GCM");
248 
249 static COUNTER_U64_DEFINE_EARLY(ktls_sw_chacha20);
250 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, chacha20, CTLFLAG_RD,
251     &ktls_sw_chacha20,
252     "Active number of software TLS sessions using Chacha20-Poly1305");
253 
254 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_cbc);
255 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
256     &ktls_ifnet_cbc,
257     "Active number of ifnet TLS sessions using AES-CBC");
258 
259 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_gcm);
260 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
261     &ktls_ifnet_gcm,
262     "Active number of ifnet TLS sessions using AES-GCM");
263 
264 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_chacha20);
265 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, chacha20, CTLFLAG_RD,
266     &ktls_ifnet_chacha20,
267     "Active number of ifnet TLS sessions using Chacha20-Poly1305");
268 
269 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset);
270 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
271     &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
272 
273 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_dropped);
274 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
275     &ktls_ifnet_reset_dropped,
276     "TLS sessions dropped after failing to update ifnet send tag");
277 
278 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_failed);
279 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
280     &ktls_ifnet_reset_failed,
281     "TLS sessions that failed to allocate a new ifnet send tag");
282 
283 static int ktls_ifnet_permitted = 1;
284 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
285     &ktls_ifnet_permitted, 1,
286     "Whether to permit hardware (ifnet) TLS sessions");
287 
288 #ifdef TCP_OFFLOAD
289 static COUNTER_U64_DEFINE_EARLY(ktls_toe_cbc);
290 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
291     &ktls_toe_cbc,
292     "Active number of TOE TLS sessions using AES-CBC");
293 
294 static COUNTER_U64_DEFINE_EARLY(ktls_toe_gcm);
295 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
296     &ktls_toe_gcm,
297     "Active number of TOE TLS sessions using AES-GCM");
298 
299 static COUNTER_U64_DEFINE_EARLY(ktls_toe_chacha20);
300 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, chacha20, CTLFLAG_RD,
301     &ktls_toe_chacha20,
302     "Active number of TOE TLS sessions using Chacha20-Poly1305");
303 #endif
304 
305 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
306 
307 static void ktls_reclaim_thread(void *ctx);
308 static void ktls_reset_receive_tag(void *context, int pending);
309 static void ktls_reset_send_tag(void *context, int pending);
310 static void ktls_work_thread(void *ctx);
311 
312 int
ktls_copyin_tls_enable(struct sockopt * sopt,struct tls_enable * tls)313 ktls_copyin_tls_enable(struct sockopt *sopt, struct tls_enable *tls)
314 {
315 	struct tls_enable_v0 tls_v0;
316 	int error;
317 	uint8_t *cipher_key = NULL, *iv = NULL, *auth_key = NULL;
318 
319 	if (sopt->sopt_valsize == sizeof(tls_v0)) {
320 		error = sooptcopyin(sopt, &tls_v0, sizeof(tls_v0), sizeof(tls_v0));
321 		if (error != 0)
322 			goto done;
323 		memset(tls, 0, sizeof(*tls));
324 		tls->cipher_key = tls_v0.cipher_key;
325 		tls->iv = tls_v0.iv;
326 		tls->auth_key = tls_v0.auth_key;
327 		tls->cipher_algorithm = tls_v0.cipher_algorithm;
328 		tls->cipher_key_len = tls_v0.cipher_key_len;
329 		tls->iv_len = tls_v0.iv_len;
330 		tls->auth_algorithm = tls_v0.auth_algorithm;
331 		tls->auth_key_len = tls_v0.auth_key_len;
332 		tls->flags = tls_v0.flags;
333 		tls->tls_vmajor = tls_v0.tls_vmajor;
334 		tls->tls_vminor = tls_v0.tls_vminor;
335 	} else
336 		error = sooptcopyin(sopt, tls, sizeof(*tls), sizeof(*tls));
337 
338 	if (error != 0)
339 		return (error);
340 
341 	if (tls->cipher_key_len < 0 || tls->cipher_key_len > TLS_MAX_PARAM_SIZE)
342 		return (EINVAL);
343 	if (tls->iv_len < 0 || tls->iv_len > sizeof(((struct ktls_session *)NULL)->params.iv))
344 		return (EINVAL);
345 	if (tls->auth_key_len < 0 || tls->auth_key_len > TLS_MAX_PARAM_SIZE)
346 		return (EINVAL);
347 
348 	/* All supported algorithms require a cipher key. */
349 	if (tls->cipher_key_len == 0)
350 		return (EINVAL);
351 
352 	/*
353 	 * Now do a deep copy of the variable-length arrays in the struct, so that
354 	 * subsequent consumers of it can reliably assume kernel memory. This
355 	 * requires doing our own allocations, which we will free in the
356 	 * error paths so that our caller need only worry about outstanding
357 	 * allocations existing on successful return.
358 	 */
359 	if (tls->cipher_key_len != 0) {
360 		cipher_key = malloc(tls->cipher_key_len, M_KTLS, M_WAITOK);
361 		if (sopt->sopt_td != NULL) {
362 			error = copyin(tls->cipher_key, cipher_key, tls->cipher_key_len);
363 			if (error != 0)
364 				goto done;
365 		} else {
366 			bcopy(tls->cipher_key, cipher_key, tls->cipher_key_len);
367 		}
368 	}
369 	if (tls->iv_len != 0) {
370 		iv = malloc(tls->iv_len, M_KTLS, M_WAITOK);
371 		if (sopt->sopt_td != NULL) {
372 			error = copyin(tls->iv, iv, tls->iv_len);
373 			if (error != 0)
374 				goto done;
375 		} else {
376 			bcopy(tls->iv, iv, tls->iv_len);
377 		}
378 	}
379 	if (tls->auth_key_len != 0) {
380 		auth_key = malloc(tls->auth_key_len, M_KTLS, M_WAITOK);
381 		if (sopt->sopt_td != NULL) {
382 			error = copyin(tls->auth_key, auth_key, tls->auth_key_len);
383 			if (error != 0)
384 				goto done;
385 		} else {
386 			bcopy(tls->auth_key, auth_key, tls->auth_key_len);
387 		}
388 	}
389 	tls->cipher_key = cipher_key;
390 	tls->iv = iv;
391 	tls->auth_key = auth_key;
392 
393 done:
394 	if (error != 0) {
395 		zfree(cipher_key, M_KTLS);
396 		zfree(iv, M_KTLS);
397 		zfree(auth_key, M_KTLS);
398 	}
399 
400 	return (error);
401 }
402 
403 void
ktls_cleanup_tls_enable(struct tls_enable * tls)404 ktls_cleanup_tls_enable(struct tls_enable *tls)
405 {
406 	zfree(__DECONST(void *, tls->cipher_key), M_KTLS);
407 	zfree(__DECONST(void *, tls->iv), M_KTLS);
408 	zfree(__DECONST(void *, tls->auth_key), M_KTLS);
409 }
410 
411 static u_int
ktls_get_cpu(struct socket * so)412 ktls_get_cpu(struct socket *so)
413 {
414 	struct inpcb *inp;
415 #ifdef NUMA
416 	struct ktls_domain_info *di;
417 #endif
418 	u_int cpuid;
419 
420 	inp = sotoinpcb(so);
421 #ifdef RSS
422 	cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
423 	if (cpuid != NETISR_CPUID_NONE)
424 		return (cpuid);
425 #endif
426 	/*
427 	 * Just use the flowid to shard connections in a repeatable
428 	 * fashion.  Note that TLS 1.0 sessions rely on the
429 	 * serialization provided by having the same connection use
430 	 * the same queue.
431 	 */
432 #ifdef NUMA
433 	if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
434 		di = &ktls_domains[inp->inp_numa_domain];
435 		cpuid = di->cpu[inp->inp_flowid % di->count];
436 	} else
437 #endif
438 		cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
439 	return (cpuid);
440 }
441 
442 static int
ktls_buffer_import(void * arg,void ** store,int count,int domain,int flags)443 ktls_buffer_import(void *arg, void **store, int count, int domain, int flags)
444 {
445 	vm_page_t m;
446 	int i, req;
447 
448 	KASSERT((ktls_maxlen & PAGE_MASK) == 0,
449 	    ("%s: ktls max length %d is not page size-aligned",
450 	    __func__, ktls_maxlen));
451 
452 	req = VM_ALLOC_WIRED | VM_ALLOC_NODUMP | malloc2vm_flags(flags);
453 	for (i = 0; i < count; i++) {
454 		m = vm_page_alloc_noobj_contig_domain(domain, req,
455 		    atop(ktls_maxlen), 0, ~0ul, PAGE_SIZE, 0,
456 		    VM_MEMATTR_DEFAULT);
457 		if (m == NULL)
458 			break;
459 		store[i] = VM_PAGE_TO_DMAP(m);
460 	}
461 	return (i);
462 }
463 
464 static void
ktls_buffer_release(void * arg __unused,void ** store,int count)465 ktls_buffer_release(void *arg __unused, void **store, int count)
466 {
467 	vm_page_t m;
468 	int i, j;
469 
470 	for (i = 0; i < count; i++) {
471 		m = DMAP_TO_VM_PAGE(store[i]);
472 		for (j = 0; j < atop(ktls_maxlen); j++) {
473 			(void)vm_page_unwire_noq(m + j);
474 			vm_page_free(m + j);
475 		}
476 	}
477 }
478 
479 static void
ktls_free_mext_contig(struct mbuf * m)480 ktls_free_mext_contig(struct mbuf *m)
481 {
482 	M_ASSERTEXTPG(m);
483 	uma_zfree(ktls_buffer_zone, PHYS_TO_DMAP(m->m_epg_pa[0]));
484 }
485 
486 static int
ktls_init(void)487 ktls_init(void)
488 {
489 	struct thread *td;
490 	struct pcpu *pc;
491 	int count, domain, error, i;
492 
493 	ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
494 	    M_WAITOK | M_ZERO);
495 
496 	ktls_session_zone = uma_zcreate("ktls_session",
497 	    sizeof(struct ktls_session),
498 	    NULL, NULL, NULL, NULL,
499 	    UMA_ALIGN_CACHE, 0);
500 
501 	if (ktls_sw_buffer_cache) {
502 		ktls_buffer_zone = uma_zcache_create("ktls_buffers",
503 		    roundup2(ktls_maxlen, PAGE_SIZE), NULL, NULL, NULL, NULL,
504 		    ktls_buffer_import, ktls_buffer_release, NULL,
505 		    UMA_ZONE_FIRSTTOUCH | UMA_ZONE_NOTRIM);
506 	}
507 
508 	/*
509 	 * Initialize the workqueues to run the TLS work.  We create a
510 	 * work queue for each CPU.
511 	 */
512 	CPU_FOREACH(i) {
513 		STAILQ_INIT(&ktls_wq[i].m_head);
514 		STAILQ_INIT(&ktls_wq[i].so_head);
515 		mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
516 		if (ktls_bind_threads > 1) {
517 			pc = pcpu_find(i);
518 			domain = pc->pc_domain;
519 			count = ktls_domains[domain].count;
520 			ktls_domains[domain].cpu[count] = i;
521 			ktls_domains[domain].count++;
522 		}
523 		ktls_cpuid_lookup[ktls_number_threads] = i;
524 		ktls_number_threads++;
525 	}
526 
527 	/*
528 	 * If we somehow have an empty domain, fall back to choosing
529 	 * among all KTLS threads.
530 	 */
531 	if (ktls_bind_threads > 1) {
532 		for (i = 0; i < vm_ndomains; i++) {
533 			if (ktls_domains[i].count == 0) {
534 				ktls_bind_threads = 1;
535 				break;
536 			}
537 		}
538 	}
539 
540 	/* Start kthreads for each workqueue. */
541 	CPU_FOREACH(i) {
542 		error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
543 		    &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
544 		if (error) {
545 			printf("Can't add KTLS thread %d error %d\n", i, error);
546 			return (error);
547 		}
548 	}
549 
550 	/*
551 	 * Start an allocation thread per-domain to perform blocking allocations
552 	 * of 16k physically contiguous TLS crypto destination buffers.
553 	 */
554 	if (ktls_sw_buffer_cache) {
555 		for (domain = 0; domain < vm_ndomains; domain++) {
556 			if (VM_DOMAIN_EMPTY(domain))
557 				continue;
558 			if (CPU_EMPTY(&cpuset_domain[domain]))
559 				continue;
560 			error = kproc_kthread_add(ktls_reclaim_thread,
561 			    &ktls_domains[domain], &ktls_proc,
562 			    &ktls_domains[domain].reclaim_td.td,
563 			    0, 0, "KTLS", "reclaim_%d", domain);
564 			if (error) {
565 				printf("Can't add KTLS reclaim thread %d error %d\n",
566 				    domain, error);
567 				return (error);
568 			}
569 		}
570 	}
571 
572 	if (bootverbose)
573 		printf("KTLS: Initialized %d threads\n", ktls_number_threads);
574 	return (0);
575 }
576 
577 static int
ktls_start_kthreads(void)578 ktls_start_kthreads(void)
579 {
580 	int error, state;
581 
582 start:
583 	state = atomic_load_acq_int(&ktls_init_state);
584 	if (__predict_true(state > 0))
585 		return (0);
586 	if (state < 0)
587 		return (ENXIO);
588 
589 	sx_xlock(&ktls_init_lock);
590 	if (ktls_init_state != 0) {
591 		sx_xunlock(&ktls_init_lock);
592 		goto start;
593 	}
594 
595 	error = ktls_init();
596 	if (error == 0)
597 		state = 1;
598 	else
599 		state = -1;
600 	atomic_store_rel_int(&ktls_init_state, state);
601 	sx_xunlock(&ktls_init_lock);
602 	return (error);
603 }
604 
605 static int
ktls_create_session(struct socket * so,struct tls_enable * en,struct ktls_session ** tlsp,int direction)606 ktls_create_session(struct socket *so, struct tls_enable *en,
607     struct ktls_session **tlsp, int direction)
608 {
609 	struct ktls_session *tls;
610 	int error;
611 
612 	/* Only TLS 1.0 - 1.3 are supported. */
613 	if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
614 		return (EINVAL);
615 	if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
616 	    en->tls_vminor > TLS_MINOR_VER_THREE)
617 		return (EINVAL);
618 
619 
620 	/* No flags are currently supported. */
621 	if (en->flags != 0)
622 		return (EINVAL);
623 
624 	/* Common checks for supported algorithms. */
625 	switch (en->cipher_algorithm) {
626 	case CRYPTO_AES_NIST_GCM_16:
627 		/*
628 		 * auth_algorithm isn't used, but permit GMAC values
629 		 * for compatibility.
630 		 */
631 		switch (en->auth_algorithm) {
632 		case 0:
633 #ifdef COMPAT_FREEBSD12
634 		/* XXX: Really 13.0-current COMPAT. */
635 		case CRYPTO_AES_128_NIST_GMAC:
636 		case CRYPTO_AES_192_NIST_GMAC:
637 		case CRYPTO_AES_256_NIST_GMAC:
638 #endif
639 			break;
640 		default:
641 			return (EINVAL);
642 		}
643 		if (en->auth_key_len != 0)
644 			return (EINVAL);
645 		switch (en->tls_vminor) {
646 		case TLS_MINOR_VER_TWO:
647 			if (en->iv_len != TLS_AEAD_GCM_LEN)
648 				return (EINVAL);
649 			break;
650 		case TLS_MINOR_VER_THREE:
651 			if (en->iv_len != TLS_1_3_GCM_IV_LEN)
652 				return (EINVAL);
653 			break;
654 		default:
655 			return (EINVAL);
656 		}
657 		break;
658 	case CRYPTO_AES_CBC:
659 		switch (en->auth_algorithm) {
660 		case CRYPTO_SHA1_HMAC:
661 			break;
662 		case CRYPTO_SHA2_256_HMAC:
663 		case CRYPTO_SHA2_384_HMAC:
664 			if (en->tls_vminor != TLS_MINOR_VER_TWO)
665 				return (EINVAL);
666 			break;
667 		default:
668 			return (EINVAL);
669 		}
670 		if (en->auth_key_len == 0)
671 			return (EINVAL);
672 
673 		/*
674 		 * TLS 1.0 requires an implicit IV.  TLS 1.1 and 1.2
675 		 * use explicit IVs.
676 		 */
677 		switch (en->tls_vminor) {
678 		case TLS_MINOR_VER_ZERO:
679 			if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
680 				return (EINVAL);
681 			break;
682 		case TLS_MINOR_VER_ONE:
683 		case TLS_MINOR_VER_TWO:
684 			/* Ignore any supplied IV. */
685 			en->iv_len = 0;
686 			break;
687 		default:
688 			return (EINVAL);
689 		}
690 		break;
691 	case CRYPTO_CHACHA20_POLY1305:
692 		if (en->auth_algorithm != 0 || en->auth_key_len != 0)
693 			return (EINVAL);
694 		if (en->tls_vminor != TLS_MINOR_VER_TWO &&
695 		    en->tls_vminor != TLS_MINOR_VER_THREE)
696 			return (EINVAL);
697 		if (en->iv_len != TLS_CHACHA20_IV_LEN)
698 			return (EINVAL);
699 		break;
700 	default:
701 		return (EINVAL);
702 	}
703 
704 	error = ktls_start_kthreads();
705 	if (error != 0)
706 		return (error);
707 
708 	tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
709 
710 	counter_u64_add(ktls_offload_active, 1);
711 
712 	refcount_init(&tls->refcount, 1);
713 	if (direction == KTLS_RX) {
714 		TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_receive_tag, tls);
715 	} else {
716 		TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
717 		tls->inp = so->so_pcb;
718 		in_pcbref(tls->inp);
719 		tls->tx = true;
720 	}
721 
722 	tls->wq_index = ktls_get_cpu(so);
723 
724 	tls->params.cipher_algorithm = en->cipher_algorithm;
725 	tls->params.auth_algorithm = en->auth_algorithm;
726 	tls->params.tls_vmajor = en->tls_vmajor;
727 	tls->params.tls_vminor = en->tls_vminor;
728 	tls->params.flags = en->flags;
729 	tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
730 
731 	/* Set the header and trailer lengths. */
732 	tls->params.tls_hlen = sizeof(struct tls_record_layer);
733 	switch (en->cipher_algorithm) {
734 	case CRYPTO_AES_NIST_GCM_16:
735 		/*
736 		 * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
737 		 * nonce.  TLS 1.3 uses a 12 byte implicit IV.
738 		 */
739 		if (en->tls_vminor < TLS_MINOR_VER_THREE)
740 			tls->params.tls_hlen += sizeof(uint64_t);
741 		tls->params.tls_tlen = AES_GMAC_HASH_LEN;
742 		tls->params.tls_bs = 1;
743 		break;
744 	case CRYPTO_AES_CBC:
745 		switch (en->auth_algorithm) {
746 		case CRYPTO_SHA1_HMAC:
747 			if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
748 				/* Implicit IV, no nonce. */
749 				tls->sequential_records = true;
750 				tls->next_seqno = be64dec(en->rec_seq);
751 				STAILQ_INIT(&tls->pending_records);
752 			} else {
753 				tls->params.tls_hlen += AES_BLOCK_LEN;
754 			}
755 			tls->params.tls_tlen = AES_BLOCK_LEN +
756 			    SHA1_HASH_LEN;
757 			break;
758 		case CRYPTO_SHA2_256_HMAC:
759 			tls->params.tls_hlen += AES_BLOCK_LEN;
760 			tls->params.tls_tlen = AES_BLOCK_LEN +
761 			    SHA2_256_HASH_LEN;
762 			break;
763 		case CRYPTO_SHA2_384_HMAC:
764 			tls->params.tls_hlen += AES_BLOCK_LEN;
765 			tls->params.tls_tlen = AES_BLOCK_LEN +
766 			    SHA2_384_HASH_LEN;
767 			break;
768 		default:
769 			panic("invalid hmac");
770 		}
771 		tls->params.tls_bs = AES_BLOCK_LEN;
772 		break;
773 	case CRYPTO_CHACHA20_POLY1305:
774 		/*
775 		 * Chacha20 uses a 12 byte implicit IV.
776 		 */
777 		tls->params.tls_tlen = POLY1305_HASH_LEN;
778 		tls->params.tls_bs = 1;
779 		break;
780 	default:
781 		panic("invalid cipher");
782 	}
783 
784 	/*
785 	 * TLS 1.3 includes optional padding which we do not support,
786 	 * and also puts the "real" record type at the end of the
787 	 * encrypted data.
788 	 */
789 	if (en->tls_vminor == TLS_MINOR_VER_THREE)
790 		tls->params.tls_tlen += sizeof(uint8_t);
791 
792 	KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
793 	    ("TLS header length too long: %d", tls->params.tls_hlen));
794 	KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
795 	    ("TLS trailer length too long: %d", tls->params.tls_tlen));
796 
797 	if (en->auth_key_len != 0) {
798 		tls->params.auth_key_len = en->auth_key_len;
799 		tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
800 		    M_WAITOK);
801 		bcopy(en->auth_key, tls->params.auth_key, en->auth_key_len);
802 	}
803 
804 	tls->params.cipher_key_len = en->cipher_key_len;
805 	tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
806 	bcopy(en->cipher_key, tls->params.cipher_key, en->cipher_key_len);
807 
808 	/*
809 	 * This holds the implicit portion of the nonce for AEAD
810 	 * ciphers and the initial implicit IV for TLS 1.0.  The
811 	 * explicit portions of the IV are generated in ktls_frame().
812 	 */
813 	if (en->iv_len != 0) {
814 		tls->params.iv_len = en->iv_len;
815 		bcopy(en->iv, tls->params.iv, en->iv_len);
816 
817 		/*
818 		 * For TLS 1.2 with GCM, generate an 8-byte nonce as a
819 		 * counter to generate unique explicit IVs.
820 		 *
821 		 * Store this counter in the last 8 bytes of the IV
822 		 * array so that it is 8-byte aligned.
823 		 */
824 		if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
825 		    en->tls_vminor == TLS_MINOR_VER_TWO)
826 			arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
827 	}
828 
829 	tls->gen = 0;
830 	*tlsp = tls;
831 	return (0);
832 }
833 
834 static struct ktls_session *
ktls_clone_session(struct ktls_session * tls,int direction)835 ktls_clone_session(struct ktls_session *tls, int direction)
836 {
837 	struct ktls_session *tls_new;
838 
839 	tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
840 
841 	counter_u64_add(ktls_offload_active, 1);
842 
843 	refcount_init(&tls_new->refcount, 1);
844 	if (direction == KTLS_RX) {
845 		TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_receive_tag,
846 		    tls_new);
847 	} else {
848 		TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_send_tag,
849 		    tls_new);
850 		tls_new->inp = tls->inp;
851 		tls_new->tx = true;
852 		in_pcbref(tls_new->inp);
853 	}
854 
855 	/* Copy fields from existing session. */
856 	tls_new->params = tls->params;
857 	tls_new->wq_index = tls->wq_index;
858 
859 	/* Deep copy keys. */
860 	if (tls_new->params.auth_key != NULL) {
861 		tls_new->params.auth_key = malloc(tls->params.auth_key_len,
862 		    M_KTLS, M_WAITOK);
863 		memcpy(tls_new->params.auth_key, tls->params.auth_key,
864 		    tls->params.auth_key_len);
865 	}
866 
867 	tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
868 	    M_WAITOK);
869 	memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
870 	    tls->params.cipher_key_len);
871 
872 	tls_new->gen = 0;
873 	return (tls_new);
874 }
875 
876 #ifdef TCP_OFFLOAD
877 static int
ktls_try_toe(struct socket * so,struct ktls_session * tls,int direction)878 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
879 {
880 	struct inpcb *inp = sotoinpcb(so);
881 	struct tcpcb *tp = intotcpcb(inp);
882 	int error;
883 
884 	INP_WLOCK(inp);
885 	if (tp->t_flags & TF_DISCONNECTED) {
886 		INP_WUNLOCK(inp);
887 		return (ECONNRESET);
888 	}
889 	if (!(tp->t_flags & TF_TOE)) {
890 		INP_WUNLOCK(inp);
891 		return (EOPNOTSUPP);
892 	}
893 
894 	error = tcp_offload_alloc_tls_session(tp, tls, direction);
895 	INP_WUNLOCK(inp);
896 	if (error == 0) {
897 		tls->mode = TCP_TLS_MODE_TOE;
898 		switch (tls->params.cipher_algorithm) {
899 		case CRYPTO_AES_CBC:
900 			counter_u64_add(ktls_toe_cbc, 1);
901 			break;
902 		case CRYPTO_AES_NIST_GCM_16:
903 			counter_u64_add(ktls_toe_gcm, 1);
904 			break;
905 		case CRYPTO_CHACHA20_POLY1305:
906 			counter_u64_add(ktls_toe_chacha20, 1);
907 			break;
908 		}
909 	}
910 	return (error);
911 }
912 #endif
913 
914 /*
915  * Common code used when first enabling ifnet TLS on a connection or
916  * when allocating a new ifnet TLS session due to a routing change.
917  * This function allocates a new TLS send tag on whatever interface
918  * the connection is currently routed over.
919  */
920 static int
ktls_alloc_snd_tag(struct inpcb * inp,struct ktls_session * tls,bool force,struct m_snd_tag ** mstp)921 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
922     struct m_snd_tag **mstp)
923 {
924 	union if_snd_tag_alloc_params params;
925 	struct ifnet *ifp;
926 	struct nhop_object *nh;
927 	struct tcpcb *tp = intotcpcb(inp);
928 	int error;
929 
930 	INP_RLOCK(inp);
931 	if (tp->t_flags & TF_DISCONNECTED) {
932 		INP_RUNLOCK(inp);
933 		return (ECONNRESET);
934 	}
935 
936 	/*
937 	 * Check administrative controls on ifnet TLS to determine if
938 	 * ifnet TLS should be denied.
939 	 *
940 	 * - Always permit 'force' requests.
941 	 * - ktls_ifnet_permitted == 0: always deny.
942 	 */
943 	if (!force && ktls_ifnet_permitted == 0) {
944 		INP_RUNLOCK(inp);
945 		return (ENXIO);
946 	}
947 
948 	/*
949 	 * XXX: Use the cached route in the inpcb to find the
950 	 * interface.  This should perhaps instead use
951 	 * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
952 	 * enabled after a connection has completed key negotiation in
953 	 * userland, the cached route will be present in practice.
954 	 */
955 	nh = inp->inp_route.ro_nh;
956 	if (nh == NULL) {
957 		INP_RUNLOCK(inp);
958 		return (ENXIO);
959 	}
960 	ifp = nh->nh_ifp;
961 	if_ref(ifp);
962 
963 	/*
964 	 * Allocate a TLS + ratelimit tag if the connection has an
965 	 * existing pacing rate.
966 	 */
967 	if (tp->t_pacing_rate != -1 &&
968 	    (if_getcapenable(ifp) & IFCAP_TXTLS_RTLMT) != 0) {
969 		params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
970 		params.tls_rate_limit.inp = inp;
971 		params.tls_rate_limit.tls = tls;
972 		params.tls_rate_limit.max_rate = tp->t_pacing_rate;
973 	} else {
974 		params.hdr.type = IF_SND_TAG_TYPE_TLS;
975 		params.tls.inp = inp;
976 		params.tls.tls = tls;
977 	}
978 	params.hdr.flowid = inp->inp_flowid;
979 	params.hdr.flowtype = inp->inp_flowtype;
980 	params.hdr.numa_domain = inp->inp_numa_domain;
981 	INP_RUNLOCK(inp);
982 
983 	if ((if_getcapenable(ifp) & IFCAP_MEXTPG) == 0) {
984 		error = EOPNOTSUPP;
985 		goto out;
986 	}
987 	if (inp->inp_vflag & INP_IPV6) {
988 		if ((if_getcapenable(ifp) & IFCAP_TXTLS6) == 0) {
989 			error = EOPNOTSUPP;
990 			goto out;
991 		}
992 	} else {
993 		if ((if_getcapenable(ifp) & IFCAP_TXTLS4) == 0) {
994 			error = EOPNOTSUPP;
995 			goto out;
996 		}
997 	}
998 	error = m_snd_tag_alloc(ifp, &params, mstp);
999 out:
1000 	if_rele(ifp);
1001 	return (error);
1002 }
1003 
1004 /*
1005  * Allocate an initial TLS receive tag for doing HW decryption of TLS
1006  * data.
1007  *
1008  * This function allocates a new TLS receive tag on whatever interface
1009  * the connection is currently routed over.  If the connection ends up
1010  * using a different interface for receive this will get fixed up via
1011  * ktls_input_ifp_mismatch as future packets arrive.
1012  */
1013 static int
ktls_alloc_rcv_tag(struct inpcb * inp,struct ktls_session * tls,struct m_snd_tag ** mstp)1014 ktls_alloc_rcv_tag(struct inpcb *inp, struct ktls_session *tls,
1015     struct m_snd_tag **mstp)
1016 {
1017 	union if_snd_tag_alloc_params params;
1018 	struct ifnet *ifp;
1019 	struct nhop_object *nh;
1020 	int error;
1021 
1022 	if (!ktls_ocf_recrypt_supported(tls))
1023 		return (ENXIO);
1024 
1025 	INP_RLOCK(inp);
1026 	if (intotcpcb(inp)->t_flags & TF_DISCONNECTED) {
1027 		INP_RUNLOCK(inp);
1028 		return (ECONNRESET);
1029 	}
1030 
1031 	/*
1032 	 * Check administrative controls on ifnet TLS to determine if
1033 	 * ifnet TLS should be denied.
1034 	 */
1035 	if (ktls_ifnet_permitted == 0) {
1036 		INP_RUNLOCK(inp);
1037 		return (ENXIO);
1038 	}
1039 
1040 	/*
1041 	 * XXX: As with ktls_alloc_snd_tag, use the cached route in
1042 	 * the inpcb to find the interface.
1043 	 */
1044 	nh = inp->inp_route.ro_nh;
1045 	if (nh == NULL) {
1046 		INP_RUNLOCK(inp);
1047 		return (ENXIO);
1048 	}
1049 	ifp = nh->nh_ifp;
1050 	if_ref(ifp);
1051 	tls->rx_ifp = ifp;
1052 
1053 	params.hdr.type = IF_SND_TAG_TYPE_TLS_RX;
1054 	params.hdr.flowid = inp->inp_flowid;
1055 	params.hdr.flowtype = inp->inp_flowtype;
1056 	params.hdr.numa_domain = inp->inp_numa_domain;
1057 	params.tls_rx.inp = inp;
1058 	params.tls_rx.tls = tls;
1059 	params.tls_rx.vlan_id = 0;
1060 
1061 	INP_RUNLOCK(inp);
1062 
1063 	if (inp->inp_vflag & INP_IPV6) {
1064 		if ((if_getcapenable2(ifp) & IFCAP2_BIT(IFCAP2_RXTLS6)) == 0) {
1065 			error = EOPNOTSUPP;
1066 			goto out;
1067 		}
1068 	} else {
1069 		if ((if_getcapenable2(ifp) & IFCAP2_BIT(IFCAP2_RXTLS4)) == 0) {
1070 			error = EOPNOTSUPP;
1071 			goto out;
1072 		}
1073 	}
1074 	error = m_snd_tag_alloc(ifp, &params, mstp);
1075 
1076 	/*
1077 	 * If this connection is over a vlan, vlan_snd_tag_alloc
1078 	 * rewrites vlan_id with the saved interface.  Save the VLAN
1079 	 * ID for use in ktls_reset_receive_tag which allocates new
1080 	 * receive tags directly from the leaf interface bypassing
1081 	 * if_vlan.
1082 	 */
1083 	if (error == 0)
1084 		tls->rx_vlan_id = params.tls_rx.vlan_id;
1085 out:
1086 	return (error);
1087 }
1088 
1089 static int
ktls_try_ifnet(struct socket * so,struct ktls_session * tls,int direction,bool force)1090 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, int direction,
1091     bool force)
1092 {
1093 	struct m_snd_tag *mst;
1094 	int error;
1095 
1096 	switch (direction) {
1097 	case KTLS_TX:
1098 		error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
1099 		if (__predict_false(error != 0))
1100 			goto done;
1101 		break;
1102 	case KTLS_RX:
1103 		KASSERT(!force, ("%s: forced receive tag", __func__));
1104 		error = ktls_alloc_rcv_tag(so->so_pcb, tls, &mst);
1105 		if (__predict_false(error != 0))
1106 			goto done;
1107 		break;
1108 	default:
1109 		__assert_unreachable();
1110 	}
1111 
1112 	tls->mode = TCP_TLS_MODE_IFNET;
1113 	tls->snd_tag = mst;
1114 
1115 	switch (tls->params.cipher_algorithm) {
1116 	case CRYPTO_AES_CBC:
1117 		counter_u64_add(ktls_ifnet_cbc, 1);
1118 		break;
1119 	case CRYPTO_AES_NIST_GCM_16:
1120 		counter_u64_add(ktls_ifnet_gcm, 1);
1121 		break;
1122 	case CRYPTO_CHACHA20_POLY1305:
1123 		counter_u64_add(ktls_ifnet_chacha20, 1);
1124 		break;
1125 	default:
1126 		break;
1127 	}
1128 done:
1129 	return (error);
1130 }
1131 
1132 static void
ktls_use_sw(struct ktls_session * tls)1133 ktls_use_sw(struct ktls_session *tls)
1134 {
1135 	tls->mode = TCP_TLS_MODE_SW;
1136 	switch (tls->params.cipher_algorithm) {
1137 	case CRYPTO_AES_CBC:
1138 		counter_u64_add(ktls_sw_cbc, 1);
1139 		break;
1140 	case CRYPTO_AES_NIST_GCM_16:
1141 		counter_u64_add(ktls_sw_gcm, 1);
1142 		break;
1143 	case CRYPTO_CHACHA20_POLY1305:
1144 		counter_u64_add(ktls_sw_chacha20, 1);
1145 		break;
1146 	}
1147 }
1148 
1149 static int
ktls_try_sw(struct ktls_session * tls,int direction)1150 ktls_try_sw(struct ktls_session *tls, int direction)
1151 {
1152 	int error;
1153 
1154 	error = ktls_ocf_try(tls, direction);
1155 	if (error)
1156 		return (error);
1157 	ktls_use_sw(tls);
1158 	return (0);
1159 }
1160 
1161 /*
1162  * KTLS RX stores data in the socket buffer as a list of TLS records,
1163  * where each record is stored as a control message containg the TLS
1164  * header followed by data mbufs containing the decrypted data.  This
1165  * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
1166  * both encrypted and decrypted data.  TLS records decrypted by a NIC
1167  * should be queued to the socket buffer as records, but encrypted
1168  * data which needs to be decrypted by software arrives as a stream of
1169  * regular mbufs which need to be converted.  In addition, there may
1170  * already be pending encrypted data in the socket buffer when KTLS RX
1171  * is enabled.
1172  *
1173  * To manage not-yet-decrypted data for KTLS RX, the following scheme
1174  * is used:
1175  *
1176  * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
1177  *
1178  * - ktls_check_rx checks this chain of mbufs reading the TLS header
1179  *   from the first mbuf.  Once all of the data for that TLS record is
1180  *   queued, the socket is queued to a worker thread.
1181  *
1182  * - The worker thread calls ktls_decrypt to decrypt TLS records in
1183  *   the TLS chain.  Each TLS record is detached from the TLS chain,
1184  *   decrypted, and inserted into the regular socket buffer chain as
1185  *   record starting with a control message holding the TLS header and
1186  *   a chain of mbufs holding the encrypted data.
1187  */
1188 
1189 static void
sb_mark_notready(struct sockbuf * sb)1190 sb_mark_notready(struct sockbuf *sb)
1191 {
1192 	struct mbuf *m;
1193 
1194 	m = sb->sb_mb;
1195 	sb->sb_mtls = m;
1196 	sb->sb_mb = NULL;
1197 	sb->sb_mbtail = NULL;
1198 	sb->sb_lastrecord = NULL;
1199 	for (; m != NULL; m = m->m_next) {
1200 		KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
1201 		    __func__));
1202 		KASSERT((m->m_flags & M_NOTREADY) == 0, ("%s: mbuf not ready",
1203 		    __func__));
1204 		KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
1205 		    __func__));
1206 		m->m_flags |= M_NOTREADY;
1207 		sb->sb_acc -= m->m_len;
1208 		sb->sb_tlscc += m->m_len;
1209 		sb->sb_mtlstail = m;
1210 	}
1211 	KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
1212 	    ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
1213 	    sb->sb_ccc));
1214 }
1215 
1216 /*
1217  * Return information about the pending TLS data in a socket
1218  * buffer.  On return, 'seqno' is set to the sequence number
1219  * of the next TLS record to be received, 'resid' is set to
1220  * the amount of bytes still needed for the last pending
1221  * record.  The function returns 'false' if the last pending
1222  * record contains a partial TLS header.  In that case, 'resid'
1223  * is the number of bytes needed to complete the TLS header.
1224  */
1225 bool
ktls_pending_rx_info(struct sockbuf * sb,uint64_t * seqnop,size_t * residp)1226 ktls_pending_rx_info(struct sockbuf *sb, uint64_t *seqnop, size_t *residp)
1227 {
1228 	struct tls_record_layer hdr;
1229 	struct mbuf *m;
1230 	uint64_t seqno;
1231 	size_t resid;
1232 	u_int offset, record_len;
1233 
1234 	SOCKBUF_LOCK_ASSERT(sb);
1235 	MPASS(sb->sb_flags & SB_TLS_RX);
1236 	seqno = sb->sb_tls_seqno;
1237 	resid = sb->sb_tlscc;
1238 	m = sb->sb_mtls;
1239 	offset = 0;
1240 
1241 	if (resid == 0) {
1242 		*seqnop = seqno;
1243 		*residp = 0;
1244 		return (true);
1245 	}
1246 
1247 	for (;;) {
1248 		seqno++;
1249 
1250 		if (resid < sizeof(hdr)) {
1251 			*seqnop = seqno;
1252 			*residp = sizeof(hdr) - resid;
1253 			return (false);
1254 		}
1255 
1256 		m_copydata(m, offset, sizeof(hdr), (void *)&hdr);
1257 
1258 		record_len = sizeof(hdr) + ntohs(hdr.tls_length);
1259 		if (resid <= record_len) {
1260 			*seqnop = seqno;
1261 			*residp = record_len - resid;
1262 			return (true);
1263 		}
1264 		resid -= record_len;
1265 
1266 		while (record_len != 0) {
1267 			if (m->m_len - offset > record_len) {
1268 				offset += record_len;
1269 				break;
1270 			}
1271 
1272 			record_len -= (m->m_len - offset);
1273 			offset = 0;
1274 			m = m->m_next;
1275 		}
1276 	}
1277 }
1278 
1279 int
ktls_enable_rx(struct socket * so,struct tls_enable * en)1280 ktls_enable_rx(struct socket *so, struct tls_enable *en)
1281 {
1282 	struct ktls_session *tls;
1283 	int error;
1284 
1285 	if (!ktls_offload_enable)
1286 		return (ENOTSUP);
1287 
1288 	counter_u64_add(ktls_offload_enable_calls, 1);
1289 
1290 	/*
1291 	 * This should always be true since only the TCP socket option
1292 	 * invokes this function.
1293 	 */
1294 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1295 		return (EINVAL);
1296 
1297 	/*
1298 	 * XXX: Don't overwrite existing sessions.  We should permit
1299 	 * this to support rekeying in the future.
1300 	 */
1301 	if (so->so_rcv.sb_tls_info != NULL)
1302 		return (EALREADY);
1303 
1304 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1305 		return (ENOTSUP);
1306 
1307 	error = ktls_create_session(so, en, &tls, KTLS_RX);
1308 	if (error)
1309 		return (error);
1310 
1311 	error = ktls_ocf_try(tls, KTLS_RX);
1312 	if (error) {
1313 		ktls_free(tls);
1314 		return (error);
1315 	}
1316 
1317 	/*
1318 	 * Serialize with soreceive_generic() and make sure that we're not
1319 	 * operating on a listening socket.
1320 	 */
1321 	error = SOCK_IO_RECV_LOCK(so, SBL_WAIT);
1322 	if (error) {
1323 		ktls_free(tls);
1324 		return (error);
1325 	}
1326 
1327 	/* Mark the socket as using TLS offload. */
1328 	SOCK_RECVBUF_LOCK(so);
1329 	if (__predict_false(so->so_rcv.sb_tls_info != NULL))
1330 		error = EALREADY;
1331 	else if ((so->so_rcv.sb_flags & SB_SPLICED) != 0)
1332 		error = EINVAL;
1333 	if (error != 0) {
1334 		SOCK_RECVBUF_UNLOCK(so);
1335 		SOCK_IO_RECV_UNLOCK(so);
1336 		ktls_free(tls);
1337 		return (EALREADY);
1338 	}
1339 	so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1340 	so->so_rcv.sb_tls_info = tls;
1341 	so->so_rcv.sb_flags |= SB_TLS_RX;
1342 
1343 	/* Mark existing data as not ready until it can be decrypted. */
1344 	sb_mark_notready(&so->so_rcv);
1345 	ktls_check_rx(&so->so_rcv);
1346 	SOCK_RECVBUF_UNLOCK(so);
1347 	SOCK_IO_RECV_UNLOCK(so);
1348 
1349 	/* Prefer TOE -> ifnet TLS -> software TLS. */
1350 #ifdef TCP_OFFLOAD
1351 	error = ktls_try_toe(so, tls, KTLS_RX);
1352 	if (error)
1353 #endif
1354 		error = ktls_try_ifnet(so, tls, KTLS_RX, false);
1355 	if (error)
1356 		ktls_use_sw(tls);
1357 
1358 	counter_u64_add(ktls_offload_total, 1);
1359 
1360 	return (0);
1361 }
1362 
1363 int
ktls_enable_tx(struct socket * so,struct tls_enable * en)1364 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1365 {
1366 	struct ktls_session *tls;
1367 	struct inpcb *inp;
1368 	struct tcpcb *tp;
1369 	int error;
1370 
1371 	if (!ktls_offload_enable)
1372 		return (ENOTSUP);
1373 
1374 	counter_u64_add(ktls_offload_enable_calls, 1);
1375 
1376 	/*
1377 	 * This should always be true since only the TCP socket option
1378 	 * invokes this function.
1379 	 */
1380 	if (so->so_proto->pr_protocol != IPPROTO_TCP)
1381 		return (EINVAL);
1382 
1383 	/*
1384 	 * XXX: Don't overwrite existing sessions.  We should permit
1385 	 * this to support rekeying in the future.
1386 	 */
1387 	if (so->so_snd.sb_tls_info != NULL)
1388 		return (EALREADY);
1389 
1390 	if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1391 		return (ENOTSUP);
1392 
1393 	/* TLS requires ext pgs */
1394 	if (mb_use_ext_pgs == 0)
1395 		return (ENXIO);
1396 
1397 	error = ktls_create_session(so, en, &tls, KTLS_TX);
1398 	if (error)
1399 		return (error);
1400 
1401 	/* some ktls offload NICs require initial seqno to start offload */
1402 	tls->initial_offload_seqno = be64dec(en->rec_seq);
1403 
1404 	/* Prefer TOE -> ifnet TLS -> software TLS. */
1405 #ifdef TCP_OFFLOAD
1406 	error = ktls_try_toe(so, tls, KTLS_TX);
1407 	if (error)
1408 #endif
1409 		error = ktls_try_ifnet(so, tls, KTLS_TX, false);
1410 	if (error)
1411 		error = ktls_try_sw(tls, KTLS_TX);
1412 
1413 	if (error) {
1414 		ktls_free(tls);
1415 		return (error);
1416 	}
1417 
1418 	/*
1419 	 * Serialize with sosend_generic() and make sure that we're not
1420 	 * operating on a listening socket.
1421 	 */
1422 	error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1423 	if (error) {
1424 		ktls_free(tls);
1425 		return (error);
1426 	}
1427 
1428 	/*
1429 	 * Write lock the INP when setting sb_tls_info so that
1430 	 * routines in tcp_ratelimit.c can read sb_tls_info while
1431 	 * holding the INP lock.
1432 	 */
1433 	inp = so->so_pcb;
1434 	INP_WLOCK(inp);
1435 	SOCK_SENDBUF_LOCK(so);
1436 	if (__predict_false(so->so_snd.sb_tls_info != NULL))
1437 		error = EALREADY;
1438 	else if ((so->so_snd.sb_flags & SB_SPLICED) != 0)
1439 		error = EINVAL;
1440 	if (error != 0) {
1441 		SOCK_SENDBUF_UNLOCK(so);
1442 		INP_WUNLOCK(inp);
1443 		SOCK_IO_SEND_UNLOCK(so);
1444 		ktls_free(tls);
1445 		return (error);
1446 	}
1447 	so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1448 	so->so_snd.sb_tls_info = tls;
1449 	if (tls->mode != TCP_TLS_MODE_SW) {
1450 		tp = intotcpcb(inp);
1451 		MPASS(tp->t_nic_ktls_xmit == 0);
1452 		tp->t_nic_ktls_xmit = 1;
1453 		if (tp->t_fb->tfb_hwtls_change != NULL)
1454 			(*tp->t_fb->tfb_hwtls_change)(tp, 1);
1455 	}
1456 	SOCK_SENDBUF_UNLOCK(so);
1457 	INP_WUNLOCK(inp);
1458 	SOCK_IO_SEND_UNLOCK(so);
1459 
1460 	counter_u64_add(ktls_offload_total, 1);
1461 
1462 	return (0);
1463 }
1464 
1465 int
ktls_get_rx_mode(struct socket * so,int * modep)1466 ktls_get_rx_mode(struct socket *so, int *modep)
1467 {
1468 	struct ktls_session *tls;
1469 	struct inpcb *inp __diagused;
1470 
1471 	if (SOLISTENING(so))
1472 		return (EINVAL);
1473 	inp = so->so_pcb;
1474 	INP_WLOCK_ASSERT(inp);
1475 	SOCK_RECVBUF_LOCK(so);
1476 	tls = so->so_rcv.sb_tls_info;
1477 	if (tls == NULL)
1478 		*modep = TCP_TLS_MODE_NONE;
1479 	else
1480 		*modep = tls->mode;
1481 	SOCK_RECVBUF_UNLOCK(so);
1482 	return (0);
1483 }
1484 
1485 /*
1486  * ktls_get_rx_sequence - get the next TCP- and TLS- sequence number.
1487  *
1488  * This function gets information about the next TCP- and TLS-
1489  * sequence number to be processed by the TLS receive worker
1490  * thread. The information is extracted from the given "inpcb"
1491  * structure. The values are stored in host endian format at the two
1492  * given output pointer locations. The TCP sequence number points to
1493  * the beginning of the TLS header.
1494  *
1495  * This function returns zero on success, else a non-zero error code
1496  * is returned.
1497  */
1498 int
ktls_get_rx_sequence(struct inpcb * inp,uint32_t * tcpseq,uint64_t * tlsseq)1499 ktls_get_rx_sequence(struct inpcb *inp, uint32_t *tcpseq, uint64_t *tlsseq)
1500 {
1501 	struct socket *so = inp->inp_socket;
1502 	struct tcpcb *tp = intotcpcb(inp);
1503 
1504 	INP_RLOCK(inp);
1505 	if (tp->t_flags & TF_DISCONNECTED) {
1506 		INP_RUNLOCK(inp);
1507 		return (ECONNRESET);
1508 	}
1509 
1510 	SOCKBUF_LOCK(&so->so_rcv);
1511 	*tcpseq = tp->rcv_nxt - so->so_rcv.sb_tlscc;
1512 	*tlsseq = so->so_rcv.sb_tls_seqno;
1513 	SOCKBUF_UNLOCK(&so->so_rcv);
1514 
1515 	INP_RUNLOCK(inp);
1516 
1517 	return (0);
1518 }
1519 
1520 int
ktls_get_tx_mode(struct socket * so,int * modep)1521 ktls_get_tx_mode(struct socket *so, int *modep)
1522 {
1523 	struct ktls_session *tls;
1524 	struct inpcb *inp __diagused;
1525 
1526 	if (SOLISTENING(so))
1527 		return (EINVAL);
1528 	inp = so->so_pcb;
1529 	INP_WLOCK_ASSERT(inp);
1530 	SOCK_SENDBUF_LOCK(so);
1531 	tls = so->so_snd.sb_tls_info;
1532 	if (tls == NULL)
1533 		*modep = TCP_TLS_MODE_NONE;
1534 	else
1535 		*modep = tls->mode;
1536 	SOCK_SENDBUF_UNLOCK(so);
1537 	return (0);
1538 }
1539 
1540 /*
1541  * Switch between SW and ifnet TLS sessions as requested.
1542  */
1543 int
ktls_set_tx_mode(struct socket * so,int mode)1544 ktls_set_tx_mode(struct socket *so, int mode)
1545 {
1546 	struct ktls_session *tls, *tls_new;
1547 	struct inpcb *inp;
1548 	struct tcpcb *tp;
1549 	int error;
1550 
1551 	if (SOLISTENING(so))
1552 		return (EINVAL);
1553 	switch (mode) {
1554 	case TCP_TLS_MODE_SW:
1555 	case TCP_TLS_MODE_IFNET:
1556 		break;
1557 	default:
1558 		return (EINVAL);
1559 	}
1560 
1561 	inp = so->so_pcb;
1562 	INP_WLOCK_ASSERT(inp);
1563 	tp = intotcpcb(inp);
1564 
1565 	if (mode == TCP_TLS_MODE_IFNET) {
1566 		/* Don't allow enabling ifnet ktls multiple times */
1567 		if (tp->t_nic_ktls_xmit)
1568 			return (EALREADY);
1569 
1570 		/*
1571 		 * Don't enable ifnet ktls if we disabled it due to an
1572 		 * excessive retransmission rate
1573 		 */
1574 		if (tp->t_nic_ktls_xmit_dis)
1575 			return (ENXIO);
1576 	}
1577 
1578 	SOCKBUF_LOCK(&so->so_snd);
1579 	tls = so->so_snd.sb_tls_info;
1580 	if (tls == NULL) {
1581 		SOCKBUF_UNLOCK(&so->so_snd);
1582 		return (0);
1583 	}
1584 
1585 	if (tls->mode == mode) {
1586 		SOCKBUF_UNLOCK(&so->so_snd);
1587 		return (0);
1588 	}
1589 
1590 	tls = ktls_hold(tls);
1591 	SOCKBUF_UNLOCK(&so->so_snd);
1592 	INP_WUNLOCK(inp);
1593 
1594 	tls_new = ktls_clone_session(tls, KTLS_TX);
1595 
1596 	if (mode == TCP_TLS_MODE_IFNET)
1597 		error = ktls_try_ifnet(so, tls_new, KTLS_TX, true);
1598 	else
1599 		error = ktls_try_sw(tls_new, KTLS_TX);
1600 	if (error) {
1601 		counter_u64_add(ktls_switch_failed, 1);
1602 		ktls_free(tls_new);
1603 		ktls_free(tls);
1604 		INP_WLOCK(inp);
1605 		return (error);
1606 	}
1607 
1608 	error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1609 	if (error) {
1610 		counter_u64_add(ktls_switch_failed, 1);
1611 		ktls_free(tls_new);
1612 		ktls_free(tls);
1613 		INP_WLOCK(inp);
1614 		return (error);
1615 	}
1616 
1617 	/*
1618 	 * If we raced with another session change, keep the existing
1619 	 * session.
1620 	 */
1621 	if (tls != so->so_snd.sb_tls_info) {
1622 		counter_u64_add(ktls_switch_failed, 1);
1623 		SOCK_IO_SEND_UNLOCK(so);
1624 		ktls_free(tls_new);
1625 		ktls_free(tls);
1626 		INP_WLOCK(inp);
1627 		return (EBUSY);
1628 	}
1629 
1630 	INP_WLOCK(inp);
1631 	SOCKBUF_LOCK(&so->so_snd);
1632 	so->so_snd.sb_tls_info = tls_new;
1633 	if (tls_new->mode != TCP_TLS_MODE_SW) {
1634 		MPASS(tp->t_nic_ktls_xmit == 0);
1635 		tp->t_nic_ktls_xmit = 1;
1636 		if (tp->t_fb->tfb_hwtls_change != NULL)
1637 			(*tp->t_fb->tfb_hwtls_change)(tp, 1);
1638 	}
1639 	SOCKBUF_UNLOCK(&so->so_snd);
1640 	SOCK_IO_SEND_UNLOCK(so);
1641 
1642 	/*
1643 	 * Drop two references on 'tls'.  The first is for the
1644 	 * ktls_hold() above.  The second drops the reference from the
1645 	 * socket buffer.
1646 	 */
1647 	KASSERT(tls->refcount >= 2, ("too few references on old session"));
1648 	ktls_free(tls);
1649 	ktls_free(tls);
1650 
1651 	if (mode == TCP_TLS_MODE_IFNET)
1652 		counter_u64_add(ktls_switch_to_ifnet, 1);
1653 	else
1654 		counter_u64_add(ktls_switch_to_sw, 1);
1655 
1656 	return (0);
1657 }
1658 
1659 /*
1660  * Try to allocate a new TLS receive tag.  This task is scheduled when
1661  * sbappend_ktls_rx detects an input path change.  If a new tag is
1662  * allocated, replace the tag in the TLS session.  If a new tag cannot
1663  * be allocated, let the session fall back to software decryption.
1664  */
1665 static void
ktls_reset_receive_tag(void * context,int pending)1666 ktls_reset_receive_tag(void *context, int pending)
1667 {
1668 	union if_snd_tag_alloc_params params;
1669 	struct ktls_session *tls;
1670 	struct m_snd_tag *mst;
1671 	struct inpcb *inp;
1672 	struct ifnet *ifp;
1673 	struct socket *so;
1674 	int error;
1675 
1676 	MPASS(pending == 1);
1677 
1678 	tls = context;
1679 	so = tls->so;
1680 	inp = so->so_pcb;
1681 	ifp = NULL;
1682 
1683 	INP_RLOCK(inp);
1684 	if (intotcpcb(inp)->t_flags & TF_DISCONNECTED) {
1685 		INP_RUNLOCK(inp);
1686 		goto out;
1687 	}
1688 
1689 	SOCKBUF_LOCK(&so->so_rcv);
1690 	mst = tls->snd_tag;
1691 	tls->snd_tag = NULL;
1692 	if (mst != NULL)
1693 		m_snd_tag_rele(mst);
1694 
1695 	ifp = tls->rx_ifp;
1696 	if_ref(ifp);
1697 	SOCKBUF_UNLOCK(&so->so_rcv);
1698 
1699 	params.hdr.type = IF_SND_TAG_TYPE_TLS_RX;
1700 	params.hdr.flowid = inp->inp_flowid;
1701 	params.hdr.flowtype = inp->inp_flowtype;
1702 	params.hdr.numa_domain = inp->inp_numa_domain;
1703 	params.tls_rx.inp = inp;
1704 	params.tls_rx.tls = tls;
1705 	params.tls_rx.vlan_id = tls->rx_vlan_id;
1706 	INP_RUNLOCK(inp);
1707 
1708 	if (inp->inp_vflag & INP_IPV6) {
1709 		if ((if_getcapenable2(ifp) & IFCAP2_RXTLS6) == 0)
1710 			goto out;
1711 	} else {
1712 		if ((if_getcapenable2(ifp) & IFCAP2_RXTLS4) == 0)
1713 			goto out;
1714 	}
1715 
1716 	error = m_snd_tag_alloc(ifp, &params, &mst);
1717 	if (error == 0) {
1718 		SOCKBUF_LOCK(&so->so_rcv);
1719 		tls->snd_tag = mst;
1720 		SOCKBUF_UNLOCK(&so->so_rcv);
1721 
1722 		counter_u64_add(ktls_ifnet_reset, 1);
1723 	} else {
1724 		/*
1725 		 * Just fall back to software decryption if a tag
1726 		 * cannot be allocated leaving the connection intact.
1727 		 * If a future input path change switches to another
1728 		 * interface this connection will resume ifnet TLS.
1729 		 */
1730 		counter_u64_add(ktls_ifnet_reset_failed, 1);
1731 	}
1732 
1733 out:
1734 	mtx_pool_lock(mtxpool_sleep, tls);
1735 	tls->reset_pending = false;
1736 	mtx_pool_unlock(mtxpool_sleep, tls);
1737 
1738 	if (ifp != NULL)
1739 		if_rele(ifp);
1740 	CURVNET_SET(so->so_vnet);
1741 	sorele(so);
1742 	CURVNET_RESTORE();
1743 	ktls_free(tls);
1744 }
1745 
1746 /*
1747  * Try to allocate a new TLS send tag.  This task is scheduled when
1748  * ip_output detects a route change while trying to transmit a packet
1749  * holding a TLS record.  If a new tag is allocated, replace the tag
1750  * in the TLS session.  Subsequent packets on the connection will use
1751  * the new tag.  If a new tag cannot be allocated, drop the
1752  * connection.
1753  */
1754 static void
ktls_reset_send_tag(void * context,int pending)1755 ktls_reset_send_tag(void *context, int pending)
1756 {
1757 	struct epoch_tracker et;
1758 	struct ktls_session *tls;
1759 	struct m_snd_tag *old, *new;
1760 	struct inpcb *inp;
1761 	struct tcpcb *tp;
1762 	int error;
1763 
1764 	MPASS(pending == 1);
1765 
1766 	tls = context;
1767 	inp = tls->inp;
1768 
1769 	/*
1770 	 * Free the old tag first before allocating a new one.
1771 	 * ip[6]_output_send() will treat a NULL send tag the same as
1772 	 * an ifp mismatch and drop packets until a new tag is
1773 	 * allocated.
1774 	 *
1775 	 * Write-lock the INP when changing tls->snd_tag since
1776 	 * ip[6]_output_send() holds a read-lock when reading the
1777 	 * pointer.
1778 	 */
1779 	INP_WLOCK(inp);
1780 	old = tls->snd_tag;
1781 	tls->snd_tag = NULL;
1782 	INP_WUNLOCK(inp);
1783 	if (old != NULL)
1784 		m_snd_tag_rele(old);
1785 
1786 	error = ktls_alloc_snd_tag(inp, tls, true, &new);
1787 
1788 	if (error == 0) {
1789 		INP_WLOCK(inp);
1790 		tls->snd_tag = new;
1791 		mtx_pool_lock(mtxpool_sleep, tls);
1792 		tls->reset_pending = false;
1793 		mtx_pool_unlock(mtxpool_sleep, tls);
1794 		INP_WUNLOCK(inp);
1795 
1796 		counter_u64_add(ktls_ifnet_reset, 1);
1797 
1798 		/*
1799 		 * XXX: Should we kick tcp_output explicitly now that
1800 		 * the send tag is fixed or just rely on timers?
1801 		 */
1802 	} else {
1803 		NET_EPOCH_ENTER(et);
1804 		INP_WLOCK(inp);
1805 		tp = intotcpcb(inp);
1806 		if (!(tp->t_flags & TF_DISCONNECTED)) {
1807 			CURVNET_SET(inp->inp_socket->so_vnet);
1808 			tp = tcp_drop(tp, ECONNABORTED);
1809 			CURVNET_RESTORE();
1810 			if (tp != NULL) {
1811 				counter_u64_add(ktls_ifnet_reset_dropped, 1);
1812 				INP_WUNLOCK(inp);
1813 			}
1814 		} else
1815 			INP_WUNLOCK(inp);
1816 		NET_EPOCH_EXIT(et);
1817 
1818 		counter_u64_add(ktls_ifnet_reset_failed, 1);
1819 
1820 		/*
1821 		 * Leave reset_pending true to avoid future tasks while
1822 		 * the socket goes away.
1823 		 */
1824 	}
1825 
1826 	ktls_free(tls);
1827 }
1828 
1829 void
ktls_input_ifp_mismatch(struct sockbuf * sb,struct ifnet * ifp)1830 ktls_input_ifp_mismatch(struct sockbuf *sb, struct ifnet *ifp)
1831 {
1832 	struct ktls_session *tls;
1833 	struct socket *so;
1834 
1835 	SOCKBUF_LOCK_ASSERT(sb);
1836 	KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1837 	    __func__, sb));
1838 	so = __containerof(sb, struct socket, so_rcv);
1839 
1840 	tls = sb->sb_tls_info;
1841 	if_rele(tls->rx_ifp);
1842 	if_ref(ifp);
1843 	tls->rx_ifp = ifp;
1844 
1845 	/*
1846 	 * See if we should schedule a task to update the receive tag for
1847 	 * this session.
1848 	 */
1849 	mtx_pool_lock(mtxpool_sleep, tls);
1850 	if (!tls->reset_pending) {
1851 		(void) ktls_hold(tls);
1852 		soref(so);
1853 		tls->so = so;
1854 		tls->reset_pending = true;
1855 		taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1856 	}
1857 	mtx_pool_unlock(mtxpool_sleep, tls);
1858 }
1859 
1860 int
ktls_output_eagain(struct inpcb * inp,struct ktls_session * tls)1861 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1862 {
1863 
1864 	if (inp == NULL)
1865 		return (ENOBUFS);
1866 
1867 	INP_LOCK_ASSERT(inp);
1868 
1869 	/*
1870 	 * See if we should schedule a task to update the send tag for
1871 	 * this session.
1872 	 */
1873 	mtx_pool_lock(mtxpool_sleep, tls);
1874 	if (!tls->reset_pending) {
1875 		(void) ktls_hold(tls);
1876 		tls->reset_pending = true;
1877 		taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1878 	}
1879 	mtx_pool_unlock(mtxpool_sleep, tls);
1880 	return (ENOBUFS);
1881 }
1882 
1883 #ifdef RATELIMIT
1884 int
ktls_modify_txrtlmt(struct ktls_session * tls,uint64_t max_pacing_rate)1885 ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1886 {
1887 	union if_snd_tag_modify_params params = {
1888 		.rate_limit.max_rate = max_pacing_rate,
1889 		.rate_limit.flags = M_NOWAIT,
1890 	};
1891 	struct m_snd_tag *mst;
1892 
1893 	/* Can't get to the inp, but it should be locked. */
1894 	/* INP_LOCK_ASSERT(inp); */
1895 
1896 	MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1897 
1898 	if (tls->snd_tag == NULL) {
1899 		/*
1900 		 * Resetting send tag, ignore this change.  The
1901 		 * pending reset may or may not see this updated rate
1902 		 * in the tcpcb.  If it doesn't, we will just lose
1903 		 * this rate change.
1904 		 */
1905 		return (0);
1906 	}
1907 
1908 	mst = tls->snd_tag;
1909 
1910 	MPASS(mst != NULL);
1911 	MPASS(mst->sw->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1912 
1913 	return (mst->sw->snd_tag_modify(mst, &params));
1914 }
1915 #endif
1916 
1917 static void
ktls_destroy_help(void * context,int pending __unused)1918 ktls_destroy_help(void *context, int pending __unused)
1919 {
1920 	ktls_destroy(context);
1921 }
1922 
1923 void
ktls_destroy(struct ktls_session * tls)1924 ktls_destroy(struct ktls_session *tls)
1925 {
1926 	struct inpcb *inp;
1927 	struct tcpcb *tp;
1928 	bool wlocked;
1929 
1930 	MPASS(tls->refcount == 0);
1931 
1932 	inp = tls->inp;
1933 	if (tls->tx) {
1934 		wlocked = INP_WLOCKED(inp);
1935 		if (!wlocked && !INP_TRY_WLOCK(inp)) {
1936 			/*
1937 			 * rwlocks read locks are anonymous, and there
1938 			 * is no way to know if our current thread
1939 			 * holds an rlock on the inp.  As a rough
1940 			 * estimate, check to see if the thread holds
1941 			 * *any* rlocks at all.  If it does not, then we
1942 			 * know that we don't hold the inp rlock, and
1943 			 * can safely take the wlock
1944 			 */
1945 			if (curthread->td_rw_rlocks == 0) {
1946 				INP_WLOCK(inp);
1947 			} else {
1948 				/*
1949 				 * We might hold the rlock, so let's
1950 				 * do the destroy in a taskqueue
1951 				 * context to avoid a potential
1952 				 * deadlock.  This should be very
1953 				 * rare.
1954 				 */
1955 				counter_u64_add(ktls_destroy_task, 1);
1956 				TASK_INIT(&tls->destroy_task, 0,
1957 				    ktls_destroy_help, tls);
1958 				(void)taskqueue_enqueue(taskqueue_thread,
1959 				    &tls->destroy_task);
1960 				return;
1961 			}
1962 		}
1963 	}
1964 
1965 	if (tls->sequential_records) {
1966 		struct mbuf *m, *n;
1967 		int page_count;
1968 
1969 		STAILQ_FOREACH_SAFE(m, &tls->pending_records, m_epg_stailq, n) {
1970 			page_count = m->m_epg_enc_cnt;
1971 			while (page_count > 0) {
1972 				KASSERT(page_count >= m->m_epg_nrdy,
1973 				    ("%s: too few pages", __func__));
1974 				page_count -= m->m_epg_nrdy;
1975 				m = m_free(m);
1976 			}
1977 		}
1978 	}
1979 
1980 	counter_u64_add(ktls_offload_active, -1);
1981 	switch (tls->mode) {
1982 	case TCP_TLS_MODE_SW:
1983 		switch (tls->params.cipher_algorithm) {
1984 		case CRYPTO_AES_CBC:
1985 			counter_u64_add(ktls_sw_cbc, -1);
1986 			break;
1987 		case CRYPTO_AES_NIST_GCM_16:
1988 			counter_u64_add(ktls_sw_gcm, -1);
1989 			break;
1990 		case CRYPTO_CHACHA20_POLY1305:
1991 			counter_u64_add(ktls_sw_chacha20, -1);
1992 			break;
1993 		}
1994 		break;
1995 	case TCP_TLS_MODE_IFNET:
1996 		switch (tls->params.cipher_algorithm) {
1997 		case CRYPTO_AES_CBC:
1998 			counter_u64_add(ktls_ifnet_cbc, -1);
1999 			break;
2000 		case CRYPTO_AES_NIST_GCM_16:
2001 			counter_u64_add(ktls_ifnet_gcm, -1);
2002 			break;
2003 		case CRYPTO_CHACHA20_POLY1305:
2004 			counter_u64_add(ktls_ifnet_chacha20, -1);
2005 			break;
2006 		}
2007 		if (tls->snd_tag != NULL)
2008 			m_snd_tag_rele(tls->snd_tag);
2009 		if (tls->rx_ifp != NULL)
2010 			if_rele(tls->rx_ifp);
2011 		if (tls->tx) {
2012 			INP_WLOCK_ASSERT(inp);
2013 			tp = intotcpcb(inp);
2014 			MPASS(tp->t_nic_ktls_xmit == 1);
2015 			tp->t_nic_ktls_xmit = 0;
2016 		}
2017 		break;
2018 #ifdef TCP_OFFLOAD
2019 	case TCP_TLS_MODE_TOE:
2020 		switch (tls->params.cipher_algorithm) {
2021 		case CRYPTO_AES_CBC:
2022 			counter_u64_add(ktls_toe_cbc, -1);
2023 			break;
2024 		case CRYPTO_AES_NIST_GCM_16:
2025 			counter_u64_add(ktls_toe_gcm, -1);
2026 			break;
2027 		case CRYPTO_CHACHA20_POLY1305:
2028 			counter_u64_add(ktls_toe_chacha20, -1);
2029 			break;
2030 		}
2031 		break;
2032 #endif
2033 	}
2034 	if (tls->ocf_session != NULL)
2035 		ktls_ocf_free(tls);
2036 	if (tls->params.auth_key != NULL) {
2037 		zfree(tls->params.auth_key, M_KTLS);
2038 		tls->params.auth_key = NULL;
2039 		tls->params.auth_key_len = 0;
2040 	}
2041 	if (tls->params.cipher_key != NULL) {
2042 		zfree(tls->params.cipher_key, M_KTLS);
2043 		tls->params.cipher_key = NULL;
2044 		tls->params.cipher_key_len = 0;
2045 	}
2046 	if (tls->tx) {
2047 		INP_WLOCK_ASSERT(inp);
2048 		if (!in_pcbrele_wlocked(inp) && !wlocked)
2049 			INP_WUNLOCK(inp);
2050 	}
2051 	explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
2052 
2053 	uma_zfree(ktls_session_zone, tls);
2054 }
2055 
2056 void
ktls_seq(struct sockbuf * sb,struct mbuf * m)2057 ktls_seq(struct sockbuf *sb, struct mbuf *m)
2058 {
2059 
2060 	for (; m != NULL; m = m->m_next) {
2061 		KASSERT((m->m_flags & M_EXTPG) != 0,
2062 		    ("ktls_seq: mapped mbuf %p", m));
2063 
2064 		m->m_epg_seqno = sb->sb_tls_seqno;
2065 		sb->sb_tls_seqno++;
2066 	}
2067 }
2068 
2069 /*
2070  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
2071  * mbuf in the chain must be an unmapped mbuf.  The payload of the
2072  * mbuf must be populated with the payload of each TLS record.
2073  *
2074  * The record_type argument specifies the TLS record type used when
2075  * populating the TLS header.
2076  *
2077  * The enq_count argument on return is set to the number of pages of
2078  * payload data for this entire chain that need to be encrypted via SW
2079  * encryption.  The returned value should be passed to ktls_enqueue
2080  * when scheduling encryption of this chain of mbufs.  To handle the
2081  * special case of empty fragments for TLS 1.0 sessions, an empty
2082  * fragment counts as one page.
2083  */
2084 void
ktls_frame(struct mbuf * top,struct ktls_session * tls,int * enq_cnt,uint8_t record_type)2085 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
2086     uint8_t record_type)
2087 {
2088 	struct tls_record_layer *tlshdr;
2089 	struct mbuf *m;
2090 	uint64_t *noncep;
2091 	uint16_t tls_len;
2092 	int maxlen __diagused;
2093 
2094 	maxlen = tls->params.max_frame_len;
2095 	*enq_cnt = 0;
2096 	for (m = top; m != NULL; m = m->m_next) {
2097 		/*
2098 		 * All mbufs in the chain should be TLS records whose
2099 		 * payload does not exceed the maximum frame length.
2100 		 *
2101 		 * Empty TLS 1.0 records are permitted when using CBC.
2102 		 */
2103 		KASSERT(m->m_len <= maxlen && m->m_len >= 0 &&
2104 		    (m->m_len > 0 || ktls_permit_empty_frames(tls)),
2105 		    ("ktls_frame: m %p len %d", m, m->m_len));
2106 
2107 		/*
2108 		 * TLS frames require unmapped mbufs to store session
2109 		 * info.
2110 		 */
2111 		KASSERT((m->m_flags & M_EXTPG) != 0,
2112 		    ("ktls_frame: mapped mbuf %p (top = %p)", m, top));
2113 
2114 		tls_len = m->m_len;
2115 
2116 		/* Save a reference to the session. */
2117 		m->m_epg_tls = ktls_hold(tls);
2118 
2119 		m->m_epg_hdrlen = tls->params.tls_hlen;
2120 		m->m_epg_trllen = tls->params.tls_tlen;
2121 		if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
2122 			int bs, delta;
2123 
2124 			/*
2125 			 * AES-CBC pads messages to a multiple of the
2126 			 * block size.  Note that the padding is
2127 			 * applied after the digest and the encryption
2128 			 * is done on the "plaintext || mac || padding".
2129 			 * At least one byte of padding is always
2130 			 * present.
2131 			 *
2132 			 * Compute the final trailer length assuming
2133 			 * at most one block of padding.
2134 			 * tls->params.tls_tlen is the maximum
2135 			 * possible trailer length (padding + digest).
2136 			 * delta holds the number of excess padding
2137 			 * bytes if the maximum were used.  Those
2138 			 * extra bytes are removed.
2139 			 */
2140 			bs = tls->params.tls_bs;
2141 			delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
2142 			m->m_epg_trllen -= delta;
2143 		}
2144 		m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
2145 
2146 		/* Populate the TLS header. */
2147 		tlshdr = (void *)m->m_epg_hdr;
2148 		tlshdr->tls_vmajor = tls->params.tls_vmajor;
2149 
2150 		/*
2151 		 * TLS 1.3 masquarades as TLS 1.2 with a record type
2152 		 * of TLS_RLTYPE_APP.
2153 		 */
2154 		if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
2155 		    tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
2156 			tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
2157 			tlshdr->tls_type = TLS_RLTYPE_APP;
2158 			/* save the real record type for later */
2159 			m->m_epg_record_type = record_type;
2160 			m->m_epg_trail[0] = record_type;
2161 		} else {
2162 			tlshdr->tls_vminor = tls->params.tls_vminor;
2163 			tlshdr->tls_type = record_type;
2164 		}
2165 		tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
2166 
2167 		/*
2168 		 * Store nonces / explicit IVs after the end of the
2169 		 * TLS header.
2170 		 *
2171 		 * For GCM with TLS 1.2, an 8 byte nonce is copied
2172 		 * from the end of the IV.  The nonce is then
2173 		 * incremented for use by the next record.
2174 		 *
2175 		 * For CBC, a random nonce is inserted for TLS 1.1+.
2176 		 */
2177 		if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
2178 		    tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
2179 			noncep = (uint64_t *)(tls->params.iv + 8);
2180 			be64enc(tlshdr + 1, *noncep);
2181 			(*noncep)++;
2182 		} else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
2183 		    tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
2184 			arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
2185 
2186 		/*
2187 		 * When using SW encryption, mark the mbuf not ready.
2188 		 * It will be marked ready via sbready() after the
2189 		 * record has been encrypted.
2190 		 *
2191 		 * When using ifnet TLS, unencrypted TLS records are
2192 		 * sent down the stack to the NIC.
2193 		 */
2194 		if (tls->mode == TCP_TLS_MODE_SW) {
2195 			m->m_flags |= M_NOTREADY;
2196 			if (__predict_false(tls_len == 0)) {
2197 				/* TLS 1.0 empty fragment. */
2198 				m->m_epg_nrdy = 1;
2199 			} else
2200 				m->m_epg_nrdy = m->m_epg_npgs;
2201 			*enq_cnt += m->m_epg_nrdy;
2202 		}
2203 	}
2204 }
2205 
2206 bool
ktls_permit_empty_frames(struct ktls_session * tls)2207 ktls_permit_empty_frames(struct ktls_session *tls)
2208 {
2209 	return (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
2210 	    tls->params.tls_vminor == TLS_MINOR_VER_ZERO);
2211 }
2212 
2213 void
ktls_check_rx(struct sockbuf * sb)2214 ktls_check_rx(struct sockbuf *sb)
2215 {
2216 	struct tls_record_layer hdr;
2217 	struct ktls_wq *wq;
2218 	struct socket *so;
2219 	bool running;
2220 
2221 	SOCKBUF_LOCK_ASSERT(sb);
2222 	KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
2223 	    __func__, sb));
2224 	so = __containerof(sb, struct socket, so_rcv);
2225 
2226 	if (sb->sb_flags & SB_TLS_RX_RUNNING)
2227 		return;
2228 
2229 	/* Is there enough queued for a TLS header? */
2230 	if (sb->sb_tlscc < sizeof(hdr)) {
2231 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
2232 			so->so_error = EMSGSIZE;
2233 		return;
2234 	}
2235 
2236 	m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
2237 
2238 	/* Is the entire record queued? */
2239 	if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
2240 		if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
2241 			so->so_error = EMSGSIZE;
2242 		return;
2243 	}
2244 
2245 	sb->sb_flags |= SB_TLS_RX_RUNNING;
2246 
2247 	soref(so);
2248 	wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
2249 	mtx_lock(&wq->mtx);
2250 	STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
2251 	running = wq->running;
2252 	mtx_unlock(&wq->mtx);
2253 	if (!running)
2254 		wakeup(wq);
2255 	counter_u64_add(ktls_cnt_rx_queued, 1);
2256 }
2257 
2258 static struct mbuf *
ktls_detach_record(struct sockbuf * sb,int len)2259 ktls_detach_record(struct sockbuf *sb, int len)
2260 {
2261 	struct mbuf *m, *n, *top;
2262 	int remain;
2263 
2264 	SOCKBUF_LOCK_ASSERT(sb);
2265 	MPASS(len <= sb->sb_tlscc);
2266 
2267 	/*
2268 	 * If TLS chain is the exact size of the record,
2269 	 * just grab the whole record.
2270 	 */
2271 	top = sb->sb_mtls;
2272 	if (sb->sb_tlscc == len) {
2273 		sb->sb_mtls = NULL;
2274 		sb->sb_mtlstail = NULL;
2275 		goto out;
2276 	}
2277 
2278 	/*
2279 	 * While it would be nice to use m_split() here, we need
2280 	 * to know exactly what m_split() allocates to update the
2281 	 * accounting, so do it inline instead.
2282 	 */
2283 	remain = len;
2284 	for (m = top; remain > m->m_len; m = m->m_next)
2285 		remain -= m->m_len;
2286 
2287 	/* Easy case: don't have to split 'm'. */
2288 	if (remain == m->m_len) {
2289 		sb->sb_mtls = m->m_next;
2290 		if (sb->sb_mtls == NULL)
2291 			sb->sb_mtlstail = NULL;
2292 		m->m_next = NULL;
2293 		goto out;
2294 	}
2295 
2296 	/*
2297 	 * Need to allocate an mbuf to hold the remainder of 'm'.  Try
2298 	 * with M_NOWAIT first.
2299 	 */
2300 	n = m_get(M_NOWAIT, MT_DATA);
2301 	if (n == NULL) {
2302 		/*
2303 		 * Use M_WAITOK with socket buffer unlocked.  If
2304 		 * 'sb_mtls' changes while the lock is dropped, return
2305 		 * NULL to force the caller to retry.
2306 		 */
2307 		SOCKBUF_UNLOCK(sb);
2308 
2309 		n = m_get(M_WAITOK, MT_DATA);
2310 
2311 		SOCKBUF_LOCK(sb);
2312 		if (sb->sb_mtls != top) {
2313 			m_free(n);
2314 			return (NULL);
2315 		}
2316 	}
2317 	n->m_flags |= (m->m_flags & (M_NOTREADY | M_DECRYPTED));
2318 
2319 	/* Store remainder in 'n'. */
2320 	n->m_len = m->m_len - remain;
2321 	if (m->m_flags & M_EXT) {
2322 		n->m_data = m->m_data + remain;
2323 		mb_dupcl(n, m);
2324 	} else {
2325 		bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
2326 	}
2327 
2328 	/* Trim 'm' and update accounting. */
2329 	m->m_len -= n->m_len;
2330 	sb->sb_tlscc -= n->m_len;
2331 	sb->sb_ccc -= n->m_len;
2332 
2333 	/* Account for 'n'. */
2334 	sballoc_ktls_rx(sb, n);
2335 
2336 	/* Insert 'n' into the TLS chain. */
2337 	sb->sb_mtls = n;
2338 	n->m_next = m->m_next;
2339 	if (sb->sb_mtlstail == m)
2340 		sb->sb_mtlstail = n;
2341 
2342 	/* Detach the record from the TLS chain. */
2343 	m->m_next = NULL;
2344 
2345 out:
2346 	MPASS(m_length(top, NULL) == len);
2347 	for (m = top; m != NULL; m = m->m_next)
2348 		sbfree_ktls_rx(sb, m);
2349 	sb->sb_tlsdcc = len;
2350 	sb->sb_ccc += len;
2351 	SBCHECK(sb);
2352 	return (top);
2353 }
2354 
2355 /*
2356  * Determine the length of the trailing zero padding and find the real
2357  * record type in the byte before the padding.
2358  *
2359  * Walking the mbuf chain backwards is clumsy, so another option would
2360  * be to scan forwards remembering the last non-zero byte before the
2361  * trailer.  However, it would be expensive to scan the entire record.
2362  * Instead, find the last non-zero byte of each mbuf in the chain
2363  * keeping track of the relative offset of that nonzero byte.
2364  *
2365  * trail_len is the size of the MAC/tag on input and is set to the
2366  * size of the full trailer including padding and the record type on
2367  * return.
2368  */
2369 static int
tls13_find_record_type(struct ktls_session * tls,struct mbuf * m,int tls_len,int * trailer_len,uint8_t * record_typep)2370 tls13_find_record_type(struct ktls_session *tls, struct mbuf *m, int tls_len,
2371     int *trailer_len, uint8_t *record_typep)
2372 {
2373 	char *cp;
2374 	u_int digest_start, last_offset, m_len, offset;
2375 	uint8_t record_type;
2376 
2377 	digest_start = tls_len - *trailer_len;
2378 	last_offset = 0;
2379 	offset = 0;
2380 	for (; m != NULL && offset < digest_start;
2381 	     offset += m->m_len, m = m->m_next) {
2382 		/* Don't look for padding in the tag. */
2383 		m_len = min(digest_start - offset, m->m_len);
2384 		cp = mtod(m, char *);
2385 
2386 		/* Find last non-zero byte in this mbuf. */
2387 		while (m_len > 0 && cp[m_len - 1] == 0)
2388 			m_len--;
2389 		if (m_len > 0) {
2390 			record_type = cp[m_len - 1];
2391 			last_offset = offset + m_len;
2392 		}
2393 	}
2394 	if (last_offset < tls->params.tls_hlen)
2395 		return (EBADMSG);
2396 
2397 	*record_typep = record_type;
2398 	*trailer_len = tls_len - last_offset + 1;
2399 	return (0);
2400 }
2401 
2402 /*
2403  * Check if a mbuf chain is fully decrypted.  Returns
2404  * KTLS_MBUF_CRYPTO_ST_DECRYPTED if all data is decrypted.
2405  * KTLS_MBUF_CRYPTO_ST_MIXED if there is a mix of encrypted and
2406  * decrypted data.  KTLS_MBUF_CRYPTO_ST_ENCRYPTED if all data is
2407  * encrypted.  KTLS_MBUF_CRYPTO_ST_SHAREDMBUF if any mbuf points at
2408  * shared data that must not be modified in place (non-anonymous
2409  * M_EXTPG or sendfile M_EXT buffers).
2410  */
2411 static ktls_mbuf_crypto_st_t
ktls_mbuf_crypto_state(struct mbuf * mb)2412 ktls_mbuf_crypto_state(struct mbuf *mb)
2413 {
2414 	bool seen_decrypted, seen_encrypted;
2415 
2416 	seen_decrypted = false;
2417 	seen_encrypted = false;
2418 
2419 	for (; mb != NULL; mb = mb->m_next) {
2420 		if ((mb->m_flags & M_EXTPG) != 0 &&
2421 		    (mb->m_epg_flags & EPG_FLAG_ANON) == 0)
2422 			return (KTLS_MBUF_CRYPTO_ST_SHAREDMBUF);
2423 		if ((mb->m_flags & M_EXT) != 0 &&
2424 		    mb->m_ext.ext_type == EXT_SFBUF)
2425 			return (KTLS_MBUF_CRYPTO_ST_SHAREDMBUF);
2426 
2427 		if (mb->m_flags & M_DECRYPTED)
2428 			seen_decrypted = true;
2429 		else
2430 			seen_encrypted = true;
2431 	}
2432 
2433 	if (seen_decrypted && seen_encrypted)
2434 		return (KTLS_MBUF_CRYPTO_ST_MIXED);
2435 	else
2436 		return (seen_decrypted ?
2437 		    KTLS_MBUF_CRYPTO_ST_DECRYPTED :
2438 		    KTLS_MBUF_CRYPTO_ST_ENCRYPTED);
2439 }
2440 
2441 /*
2442  * ktls_resync_ifnet - get HW TLS RX back on track after packet loss
2443  */
2444 static int
ktls_resync_ifnet(struct socket * so,uint32_t tls_len,uint64_t tls_rcd_num)2445 ktls_resync_ifnet(struct socket *so, uint32_t tls_len, uint64_t tls_rcd_num)
2446 {
2447 	union if_snd_tag_modify_params params;
2448 	struct m_snd_tag *mst;
2449 	struct inpcb *inp = sotoinpcb(so);
2450 	struct tcpcb *tp = intotcpcb(inp);
2451 
2452 	mst = so->so_rcv.sb_tls_info->snd_tag;
2453 	if (__predict_false(mst == NULL))
2454 		return (EINVAL);
2455 
2456 	INP_RLOCK(inp);
2457 	if (tp->t_flags & TF_DISCONNECTED) {
2458 		INP_RUNLOCK(inp);
2459 		return (ECONNRESET);
2460 	}
2461 
2462 	/* Get the TCP sequence number of the next valid TLS header. */
2463 	SOCKBUF_LOCK(&so->so_rcv);
2464 	params.tls_rx.tls_hdr_tcp_sn =
2465 	    tp->rcv_nxt - so->so_rcv.sb_tlscc - tls_len;
2466 	params.tls_rx.tls_rec_length = tls_len;
2467 	params.tls_rx.tls_seq_number = tls_rcd_num;
2468 	SOCKBUF_UNLOCK(&so->so_rcv);
2469 
2470 	INP_RUNLOCK(inp);
2471 
2472 	MPASS(mst->sw->type == IF_SND_TAG_TYPE_TLS_RX);
2473 	return (mst->sw->snd_tag_modify(mst, &params));
2474 }
2475 
2476 static void
ktls_drop(struct socket * so,int error)2477 ktls_drop(struct socket *so, int error)
2478 {
2479 	struct epoch_tracker et;
2480 	struct inpcb *inp = sotoinpcb(so);
2481 	struct tcpcb *tp = intotcpcb(inp);
2482 
2483 	NET_EPOCH_ENTER(et);
2484 	INP_WLOCK(inp);
2485 	if (!(tp->t_flags & TF_DISCONNECTED)) {
2486 		CURVNET_SET(inp->inp_socket->so_vnet);
2487 		tp = tcp_drop(tp, error);
2488 		CURVNET_RESTORE();
2489 		if (tp != NULL)
2490 			INP_WUNLOCK(inp);
2491 	} else {
2492 		so->so_error = error;
2493 		SOCK_RECVBUF_LOCK(so);
2494 		sorwakeup_locked(so);
2495 		INP_WUNLOCK(inp);
2496 	}
2497 	NET_EPOCH_EXIT(et);
2498 }
2499 
2500 static void
ktls_decrypt(struct socket * so)2501 ktls_decrypt(struct socket *so)
2502 {
2503 	char tls_header[MBUF_PEXT_HDR_LEN];
2504 	struct ktls_session *tls;
2505 	struct sockbuf *sb;
2506 	struct tls_record_layer *hdr;
2507 	struct tls_get_record tgr;
2508 	struct mbuf *control, *data, *m;
2509 	ktls_mbuf_crypto_st_t state;
2510 	uint64_t seqno;
2511 	int error, remain, tls_len, trail_len;
2512 	bool tls13;
2513 	uint8_t vminor, record_type;
2514 
2515 	hdr = (struct tls_record_layer *)tls_header;
2516 	sb = &so->so_rcv;
2517 	SOCKBUF_LOCK(sb);
2518 	KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
2519 	    ("%s: socket %p not running", __func__, so));
2520 
2521 	tls = sb->sb_tls_info;
2522 	MPASS(tls != NULL);
2523 
2524 	tls13 = (tls->params.tls_vminor == TLS_MINOR_VER_THREE);
2525 	if (tls13)
2526 		vminor = TLS_MINOR_VER_TWO;
2527 	else
2528 		vminor = tls->params.tls_vminor;
2529 	for (;;) {
2530 		/* Is there enough queued for a TLS header? */
2531 		if (sb->sb_tlscc < tls->params.tls_hlen)
2532 			break;
2533 
2534 		m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
2535 		tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
2536 
2537 		if (hdr->tls_vmajor != tls->params.tls_vmajor ||
2538 		    hdr->tls_vminor != vminor)
2539 			error = EINVAL;
2540 		else if (tls13 && hdr->tls_type != TLS_RLTYPE_APP)
2541 			error = EINVAL;
2542 		else if (tls_len < tls->params.tls_hlen || tls_len >
2543 		    tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
2544 		    tls->params.tls_tlen)
2545 			error = EMSGSIZE;
2546 		else
2547 			error = 0;
2548 		if (__predict_false(error != 0)) {
2549 			/*
2550 			 * We have a corrupted record and are likely
2551 			 * out of sync.  The connection isn't
2552 			 * recoverable at this point, so abort it.
2553 			 */
2554 			SOCKBUF_UNLOCK(sb);
2555 			counter_u64_add(ktls_offload_corrupted_records, 1);
2556 
2557 			ktls_drop(so, error);
2558 			goto deref;
2559 		}
2560 
2561 		/* Is the entire record queued? */
2562 		if (sb->sb_tlscc < tls_len)
2563 			break;
2564 
2565 		/*
2566 		 * Split out the portion of the mbuf chain containing
2567 		 * this TLS record.
2568 		 */
2569 		data = ktls_detach_record(sb, tls_len);
2570 		if (data == NULL)
2571 			continue;
2572 		MPASS(sb->sb_tlsdcc == tls_len);
2573 
2574 		seqno = sb->sb_tls_seqno;
2575 		sb->sb_tls_seqno++;
2576 		SBCHECK(sb);
2577 		SOCKBUF_UNLOCK(sb);
2578 
2579 		/* get crypto state for this TLS record */
2580 		state = ktls_mbuf_crypto_state(data);
2581 
2582 		switch (state) {
2583 		case KTLS_MBUF_CRYPTO_ST_MIXED:
2584 			error = ktls_ocf_recrypt(tls, hdr, data, seqno);
2585 			if (error)
2586 				break;
2587 			/* FALLTHROUGH */
2588 		case KTLS_MBUF_CRYPTO_ST_ENCRYPTED:
2589 			error = ktls_ocf_decrypt(tls, hdr, data, seqno,
2590 			    &trail_len);
2591 			if (__predict_true(error == 0)) {
2592 				if (tls13) {
2593 					error = tls13_find_record_type(tls, data,
2594 					    tls_len, &trail_len, &record_type);
2595 				} else {
2596 					record_type = hdr->tls_type;
2597 				}
2598 			}
2599 			break;
2600 		case KTLS_MBUF_CRYPTO_ST_DECRYPTED:
2601 			/*
2602 			 * NIC TLS is only supported for AEAD
2603 			 * ciphersuites which used a fixed sized
2604 			 * trailer.
2605 			 */
2606 			if (tls13) {
2607 				trail_len = tls->params.tls_tlen - 1;
2608 				error = tls13_find_record_type(tls, data,
2609 				    tls_len, &trail_len, &record_type);
2610 			} else {
2611 				trail_len = tls->params.tls_tlen;
2612 				error = 0;
2613 				record_type = hdr->tls_type;
2614 			}
2615 			break;
2616 		case KTLS_MBUF_CRYPTO_ST_SHAREDMBUF:
2617 			error = EINVAL;
2618 			break;
2619 		default:
2620 			__assert_unreachable();
2621 		}
2622 		if (error) {
2623 			counter_u64_add(ktls_offload_failed_crypto, 1);
2624 
2625 			SOCKBUF_LOCK(sb);
2626 			if (sb->sb_tlsdcc == 0) {
2627 				/*
2628 				 * sbcut/drop/flush discarded these
2629 				 * mbufs.
2630 				 */
2631 				m_freem(data);
2632 				break;
2633 			}
2634 
2635 			/*
2636 			 * Drop this TLS record's data, but keep
2637 			 * decrypting subsequent records.
2638 			 */
2639 			sb->sb_ccc -= tls_len;
2640 			sb->sb_tlsdcc = 0;
2641 
2642 			if (error != EMSGSIZE)
2643 				error = EBADMSG;
2644 			CURVNET_SET(so->so_vnet);
2645 			so->so_error = error;
2646 			sorwakeup_locked(so);
2647 			CURVNET_RESTORE();
2648 
2649 			m_freem(data);
2650 
2651 			SOCKBUF_LOCK(sb);
2652 			continue;
2653 		}
2654 
2655 		/* Allocate the control mbuf. */
2656 		memset(&tgr, 0, sizeof(tgr));
2657 		tgr.tls_type = record_type;
2658 		tgr.tls_vmajor = hdr->tls_vmajor;
2659 		tgr.tls_vminor = hdr->tls_vminor;
2660 		tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
2661 		    trail_len);
2662 		control = sbcreatecontrol(&tgr, sizeof(tgr),
2663 		    TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
2664 
2665 		SOCKBUF_LOCK(sb);
2666 		if (sb->sb_tlsdcc == 0) {
2667 			/* sbcut/drop/flush discarded these mbufs. */
2668 			MPASS(sb->sb_tlscc == 0);
2669 			m_freem(data);
2670 			m_freem(control);
2671 			break;
2672 		}
2673 
2674 		/*
2675 		 * Clear the 'dcc' accounting in preparation for
2676 		 * adding the decrypted record.
2677 		 */
2678 		sb->sb_ccc -= tls_len;
2679 		sb->sb_tlsdcc = 0;
2680 		SBCHECK(sb);
2681 
2682 		/* If there is no payload, drop all of the data. */
2683 		if (tgr.tls_length == htobe16(0)) {
2684 			m_freem(data);
2685 			data = NULL;
2686 		} else {
2687 			/* Trim header. */
2688 			remain = tls->params.tls_hlen;
2689 			while (remain > 0) {
2690 				if (data->m_len > remain) {
2691 					data->m_data += remain;
2692 					data->m_len -= remain;
2693 					break;
2694 				}
2695 				remain -= data->m_len;
2696 				data = m_free(data);
2697 			}
2698 
2699 			/* Trim trailer and clear M_NOTREADY. */
2700 			remain = be16toh(tgr.tls_length);
2701 			m = data;
2702 			for (m = data; remain > m->m_len; m = m->m_next) {
2703 				m->m_flags &= ~(M_NOTREADY | M_DECRYPTED);
2704 				remain -= m->m_len;
2705 			}
2706 			m->m_len = remain;
2707 			m_freem(m->m_next);
2708 			m->m_next = NULL;
2709 			m->m_flags &= ~(M_NOTREADY | M_DECRYPTED);
2710 
2711 			/* Set EOR on the final mbuf. */
2712 			m->m_flags |= M_EOR;
2713 		}
2714 
2715 		sbappendcontrol_locked(sb, data, control, 0);
2716 
2717 		if (__predict_false(state != KTLS_MBUF_CRYPTO_ST_DECRYPTED)) {
2718 			sb->sb_flags |= SB_TLS_RX_RESYNC;
2719 			SOCKBUF_UNLOCK(sb);
2720 			ktls_resync_ifnet(so, tls_len, seqno);
2721 			SOCKBUF_LOCK(sb);
2722 		} else if (__predict_false(sb->sb_flags & SB_TLS_RX_RESYNC)) {
2723 			sb->sb_flags &= ~SB_TLS_RX_RESYNC;
2724 			SOCKBUF_UNLOCK(sb);
2725 			ktls_resync_ifnet(so, 0, seqno);
2726 			SOCKBUF_LOCK(sb);
2727 		}
2728 	}
2729 
2730 	sb->sb_flags &= ~SB_TLS_RX_RUNNING;
2731 
2732 	if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
2733 		so->so_error = EMSGSIZE;
2734 
2735 	sorwakeup_locked(so);
2736 
2737 deref:
2738 	SOCKBUF_UNLOCK_ASSERT(sb);
2739 
2740 	CURVNET_SET(so->so_vnet);
2741 	sorele(so);
2742 	CURVNET_RESTORE();
2743 }
2744 
2745 void
ktls_enqueue_to_free(struct mbuf * m)2746 ktls_enqueue_to_free(struct mbuf *m)
2747 {
2748 	struct ktls_wq *wq;
2749 	bool running;
2750 
2751 	/* Mark it for freeing. */
2752 	m->m_epg_flags |= EPG_FLAG_2FREE;
2753 	wq = &ktls_wq[m->m_epg_tls->wq_index];
2754 	mtx_lock(&wq->mtx);
2755 	STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2756 	running = wq->running;
2757 	mtx_unlock(&wq->mtx);
2758 	if (!running)
2759 		wakeup(wq);
2760 }
2761 
2762 static void *
ktls_buffer_alloc(struct ktls_wq * wq,struct mbuf * m)2763 ktls_buffer_alloc(struct ktls_wq *wq, struct mbuf *m)
2764 {
2765 	void *buf;
2766 	int domain, running;
2767 
2768 	if (m->m_epg_npgs <= 2)
2769 		return (NULL);
2770 	if (ktls_buffer_zone == NULL)
2771 		return (NULL);
2772 	if ((u_int)(ticks - wq->lastallocfail) < hz) {
2773 		/*
2774 		 * Rate-limit allocation attempts after a failure.
2775 		 * ktls_buffer_import() will acquire a per-domain mutex to check
2776 		 * the free page queues and may fail consistently if memory is
2777 		 * fragmented.
2778 		 */
2779 		return (NULL);
2780 	}
2781 	buf = uma_zalloc(ktls_buffer_zone, M_NOWAIT | M_NORECLAIM);
2782 	if (buf == NULL) {
2783 		domain = PCPU_GET(domain);
2784 		wq->lastallocfail = ticks;
2785 
2786 		/*
2787 		 * Note that this check is "racy", but the races are
2788 		 * harmless, and are either a spurious wakeup if
2789 		 * multiple threads fail allocations before the alloc
2790 		 * thread wakes, or waiting an extra second in case we
2791 		 * see an old value of running == true.
2792 		 */
2793 		if (!VM_DOMAIN_EMPTY(domain)) {
2794 			running = atomic_load_int(&ktls_domains[domain].reclaim_td.running);
2795 			if (!running)
2796 				wakeup(&ktls_domains[domain].reclaim_td);
2797 		}
2798 	}
2799 	return (buf);
2800 }
2801 
2802 static int
ktls_encrypt_record(struct ktls_wq * wq,struct mbuf * m,struct ktls_session * tls,struct ktls_ocf_encrypt_state * state)2803 ktls_encrypt_record(struct ktls_wq *wq, struct mbuf *m,
2804     struct ktls_session *tls, struct ktls_ocf_encrypt_state *state)
2805 {
2806 	vm_page_t pg;
2807 	int error, i, len, off;
2808 
2809 	KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) == (M_EXTPG | M_NOTREADY),
2810 	    ("%p not unready & nomap mbuf\n", m));
2811 	KASSERT(ptoa(m->m_epg_npgs) <= ktls_maxlen,
2812 	    ("page count %d larger than maximum frame length %d", m->m_epg_npgs,
2813 	    ktls_maxlen));
2814 
2815 	/* Anonymous mbufs are encrypted in place. */
2816 	if ((m->m_epg_flags & EPG_FLAG_ANON) != 0)
2817 		return (ktls_ocf_encrypt(state, tls, m, NULL, 0));
2818 
2819 	/*
2820 	 * For file-backed mbufs (from sendfile), anonymous wired
2821 	 * pages are allocated and used as the encryption destination.
2822 	 */
2823 	if ((state->cbuf = ktls_buffer_alloc(wq, m)) != NULL) {
2824 		len = ptoa(m->m_epg_npgs - 1) + m->m_epg_last_len -
2825 		    m->m_epg_1st_off;
2826 		state->dst_iov[0].iov_base = (char *)state->cbuf +
2827 		    m->m_epg_1st_off;
2828 		state->dst_iov[0].iov_len = len;
2829 		state->parray[0] = DMAP_TO_PHYS(state->cbuf);
2830 		i = 1;
2831 	} else {
2832 		off = m->m_epg_1st_off;
2833 		for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2834 			pg = vm_page_alloc_noobj(VM_ALLOC_NODUMP |
2835 			    VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2836 			len = m_epg_pagelen(m, i, off);
2837 			state->parray[i] = VM_PAGE_TO_PHYS(pg);
2838 			state->dst_iov[i].iov_base =
2839 			    (char *)PHYS_TO_DMAP(state->parray[i]) + off;
2840 			state->dst_iov[i].iov_len = len;
2841 		}
2842 	}
2843 	KASSERT(i + 1 <= nitems(state->dst_iov), ("dst_iov is too small"));
2844 	state->dst_iov[i].iov_base = m->m_epg_trail;
2845 	state->dst_iov[i].iov_len = m->m_epg_trllen;
2846 
2847 	error = ktls_ocf_encrypt(state, tls, m, state->dst_iov, i + 1);
2848 
2849 	if (__predict_false(error != 0)) {
2850 		/* Free the anonymous pages. */
2851 		if (state->cbuf != NULL)
2852 			uma_zfree(ktls_buffer_zone, state->cbuf);
2853 		else {
2854 			for (i = 0; i < m->m_epg_npgs; i++) {
2855 				pg = PHYS_TO_VM_PAGE(state->parray[i]);
2856 				(void)vm_page_unwire_noq(pg);
2857 				vm_page_free(pg);
2858 			}
2859 		}
2860 	}
2861 	return (error);
2862 }
2863 
2864 /* Number of TLS records in a batch passed to ktls_enqueue(). */
2865 static u_int
ktls_batched_records(struct mbuf * m)2866 ktls_batched_records(struct mbuf *m)
2867 {
2868 	int page_count, records;
2869 
2870 	records = 0;
2871 	page_count = m->m_epg_enc_cnt;
2872 	while (page_count > 0) {
2873 		records++;
2874 		page_count -= m->m_epg_nrdy;
2875 		m = m->m_next;
2876 	}
2877 	KASSERT(page_count == 0, ("%s: mismatched page count", __func__));
2878 	return (records);
2879 }
2880 
2881 void
ktls_enqueue(struct mbuf * m,struct socket * so,int page_count)2882 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
2883 {
2884 	struct ktls_session *tls;
2885 	struct ktls_wq *wq;
2886 	int queued;
2887 	bool running;
2888 
2889 	KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2890 	    (M_EXTPG | M_NOTREADY)),
2891 	    ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
2892 	KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
2893 
2894 	KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
2895 
2896 	m->m_epg_enc_cnt = page_count;
2897 
2898 	/*
2899 	 * Save a pointer to the socket.  The caller is responsible
2900 	 * for taking an additional reference via soref().
2901 	 */
2902 	m->m_epg_so = so;
2903 
2904 	queued = 1;
2905 	tls = m->m_epg_tls;
2906 	wq = &ktls_wq[tls->wq_index];
2907 	mtx_lock(&wq->mtx);
2908 	if (__predict_false(tls->sequential_records)) {
2909 		/*
2910 		 * For TLS 1.0, records must be encrypted
2911 		 * sequentially.  For a given connection, all records
2912 		 * queued to the associated work queue are processed
2913 		 * sequentially.  However, sendfile(2) might complete
2914 		 * I/O requests spanning multiple TLS records out of
2915 		 * order.  Here we ensure TLS records are enqueued to
2916 		 * the work queue in FIFO order.
2917 		 *
2918 		 * tls->next_seqno holds the sequence number of the
2919 		 * next TLS record that should be enqueued to the work
2920 		 * queue.  If this next record is not tls->next_seqno,
2921 		 * it must be a future record, so insert it, sorted by
2922 		 * TLS sequence number, into tls->pending_records and
2923 		 * return.
2924 		 *
2925 		 * If this TLS record matches tls->next_seqno, place
2926 		 * it in the work queue and then check
2927 		 * tls->pending_records to see if any
2928 		 * previously-queued records are now ready for
2929 		 * encryption.
2930 		 */
2931 		if (m->m_epg_seqno != tls->next_seqno) {
2932 			struct mbuf *n, *p;
2933 
2934 			p = NULL;
2935 			STAILQ_FOREACH(n, &tls->pending_records, m_epg_stailq) {
2936 				if (n->m_epg_seqno > m->m_epg_seqno)
2937 					break;
2938 				p = n;
2939 			}
2940 			if (n == NULL)
2941 				STAILQ_INSERT_TAIL(&tls->pending_records, m,
2942 				    m_epg_stailq);
2943 			else if (p == NULL)
2944 				STAILQ_INSERT_HEAD(&tls->pending_records, m,
2945 				    m_epg_stailq);
2946 			else
2947 				STAILQ_INSERT_AFTER(&tls->pending_records, p, m,
2948 				    m_epg_stailq);
2949 			mtx_unlock(&wq->mtx);
2950 			counter_u64_add(ktls_cnt_tx_pending, 1);
2951 			return;
2952 		}
2953 
2954 		tls->next_seqno += ktls_batched_records(m);
2955 		STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2956 
2957 		while (!STAILQ_EMPTY(&tls->pending_records)) {
2958 			struct mbuf *n;
2959 
2960 			n = STAILQ_FIRST(&tls->pending_records);
2961 			if (n->m_epg_seqno != tls->next_seqno)
2962 				break;
2963 
2964 			queued++;
2965 			STAILQ_REMOVE_HEAD(&tls->pending_records, m_epg_stailq);
2966 			tls->next_seqno += ktls_batched_records(n);
2967 			STAILQ_INSERT_TAIL(&wq->m_head, n, m_epg_stailq);
2968 		}
2969 		counter_u64_add(ktls_cnt_tx_pending, -(queued - 1));
2970 	} else
2971 		STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2972 
2973 	running = wq->running;
2974 	mtx_unlock(&wq->mtx);
2975 	if (!running)
2976 		wakeup(wq);
2977 	counter_u64_add(ktls_cnt_tx_queued, queued);
2978 }
2979 
2980 /*
2981  * Once a file-backed mbuf (from sendfile) has been encrypted, free
2982  * the pages from the file and replace them with the anonymous pages
2983  * allocated in ktls_encrypt_record().
2984  */
2985 static void
ktls_finish_nonanon(struct mbuf * m,struct ktls_ocf_encrypt_state * state)2986 ktls_finish_nonanon(struct mbuf *m, struct ktls_ocf_encrypt_state *state)
2987 {
2988 	int i;
2989 
2990 	MPASS((m->m_epg_flags & EPG_FLAG_ANON) == 0);
2991 
2992 	/* Free the old pages. */
2993 	m->m_ext.ext_free(m);
2994 
2995 	/* Replace them with the new pages. */
2996 	if (state->cbuf != NULL) {
2997 		for (i = 0; i < m->m_epg_npgs; i++)
2998 			m->m_epg_pa[i] = state->parray[0] + ptoa(i);
2999 
3000 		/* Contig pages should go back to the cache. */
3001 		m->m_ext.ext_free = ktls_free_mext_contig;
3002 	} else {
3003 		for (i = 0; i < m->m_epg_npgs; i++)
3004 			m->m_epg_pa[i] = state->parray[i];
3005 
3006 		/* Use the basic free routine. */
3007 		m->m_ext.ext_free = mb_free_mext_pgs;
3008 	}
3009 
3010 	/* Pages are now writable. */
3011 	m->m_epg_flags |= EPG_FLAG_ANON;
3012 }
3013 
3014 static __noinline void
ktls_encrypt(struct ktls_wq * wq,struct mbuf * top)3015 ktls_encrypt(struct ktls_wq *wq, struct mbuf *top)
3016 {
3017 	struct ktls_ocf_encrypt_state state;
3018 	struct ktls_session *tls;
3019 	struct socket *so;
3020 	struct mbuf *m;
3021 	int error, npages, total_pages;
3022 
3023 	so = top->m_epg_so;
3024 	tls = top->m_epg_tls;
3025 	KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
3026 	KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
3027 #ifdef INVARIANTS
3028 	top->m_epg_so = NULL;
3029 #endif
3030 	total_pages = top->m_epg_enc_cnt;
3031 	npages = 0;
3032 
3033 	/*
3034 	 * Encrypt the TLS records in the chain of mbufs starting with
3035 	 * 'top'.  'total_pages' gives us a total count of pages and is
3036 	 * used to know when we have finished encrypting the TLS
3037 	 * records originally queued with 'top'.
3038 	 *
3039 	 * NB: These mbufs are queued in the socket buffer and
3040 	 * 'm_next' is traversing the mbufs in the socket buffer.  The
3041 	 * socket buffer lock is not held while traversing this chain.
3042 	 * Since the mbufs are all marked M_NOTREADY their 'm_next'
3043 	 * pointers should be stable.  However, the 'm_next' of the
3044 	 * last mbuf encrypted is not necessarily NULL.  It can point
3045 	 * to other mbufs appended while 'top' was on the TLS work
3046 	 * queue.
3047 	 *
3048 	 * Each mbuf holds an entire TLS record.
3049 	 */
3050 	error = 0;
3051 	for (m = top; npages != total_pages; m = m->m_next) {
3052 		KASSERT(m->m_epg_tls == tls,
3053 		    ("different TLS sessions in a single mbuf chain: %p vs %p",
3054 		    tls, m->m_epg_tls));
3055 		KASSERT(npages + m->m_epg_npgs <= total_pages,
3056 		    ("page count mismatch: top %p, total_pages %d, m %p", top,
3057 		    total_pages, m));
3058 
3059 		error = ktls_encrypt_record(wq, m, tls, &state);
3060 		if (error) {
3061 			counter_u64_add(ktls_offload_failed_crypto, 1);
3062 			break;
3063 		}
3064 
3065 		if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
3066 			ktls_finish_nonanon(m, &state);
3067 		m->m_flags |= M_RDONLY;
3068 
3069 		npages += m->m_epg_nrdy;
3070 
3071 		/*
3072 		 * Drop a reference to the session now that it is no
3073 		 * longer needed.  Existing code depends on encrypted
3074 		 * records having no associated session vs
3075 		 * yet-to-be-encrypted records having an associated
3076 		 * session.
3077 		 */
3078 		m->m_epg_tls = NULL;
3079 		ktls_free(tls);
3080 	}
3081 
3082 	CURVNET_SET(so->so_vnet);
3083 	if (error == 0) {
3084 		(void)so->so_proto->pr_ready(so, top, npages);
3085 	} else {
3086 		ktls_drop(so, EIO);
3087 		mb_free_notready(top, total_pages);
3088 	}
3089 
3090 	sorele(so);
3091 	CURVNET_RESTORE();
3092 }
3093 
3094 void
ktls_encrypt_cb(struct ktls_ocf_encrypt_state * state,int error)3095 ktls_encrypt_cb(struct ktls_ocf_encrypt_state *state, int error)
3096 {
3097 	struct ktls_session *tls;
3098 	struct socket *so;
3099 	struct mbuf *m;
3100 	int npages;
3101 
3102 	m = state->m;
3103 
3104 	if ((m->m_epg_flags & EPG_FLAG_ANON) == 0)
3105 		ktls_finish_nonanon(m, state);
3106 	m->m_flags |= M_RDONLY;
3107 
3108 	so = state->so;
3109 	free(state, M_KTLS);
3110 
3111 	/*
3112 	 * Drop a reference to the session now that it is no longer
3113 	 * needed.  Existing code depends on encrypted records having
3114 	 * no associated session vs yet-to-be-encrypted records having
3115 	 * an associated session.
3116 	 */
3117 	tls = m->m_epg_tls;
3118 	m->m_epg_tls = NULL;
3119 	ktls_free(tls);
3120 
3121 	if (error != 0)
3122 		counter_u64_add(ktls_offload_failed_crypto, 1);
3123 
3124 	CURVNET_SET(so->so_vnet);
3125 	npages = m->m_epg_nrdy;
3126 
3127 	if (error == 0) {
3128 		(void)so->so_proto->pr_ready(so, m, npages);
3129 	} else {
3130 		ktls_drop(so, EIO);
3131 		mb_free_notready(m, npages);
3132 	}
3133 
3134 	sorele(so);
3135 	CURVNET_RESTORE();
3136 }
3137 
3138 /*
3139  * Similar to ktls_encrypt, but used with asynchronous OCF backends
3140  * (coprocessors) where encryption does not use host CPU resources and
3141  * it can be beneficial to queue more requests than CPUs.
3142  */
3143 static __noinline void
ktls_encrypt_async(struct ktls_wq * wq,struct mbuf * top)3144 ktls_encrypt_async(struct ktls_wq *wq, struct mbuf *top)
3145 {
3146 	struct ktls_ocf_encrypt_state *state;
3147 	struct ktls_session *tls;
3148 	struct socket *so;
3149 	struct mbuf *m, *n;
3150 	int error, mpages, npages, total_pages;
3151 
3152 	so = top->m_epg_so;
3153 	tls = top->m_epg_tls;
3154 	KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
3155 	KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
3156 #ifdef INVARIANTS
3157 	top->m_epg_so = NULL;
3158 #endif
3159 	total_pages = top->m_epg_enc_cnt;
3160 	npages = 0;
3161 
3162 	error = 0;
3163 	for (m = top; npages != total_pages; m = n) {
3164 		KASSERT(m->m_epg_tls == tls,
3165 		    ("different TLS sessions in a single mbuf chain: %p vs %p",
3166 		    tls, m->m_epg_tls));
3167 		KASSERT(npages + m->m_epg_npgs <= total_pages,
3168 		    ("page count mismatch: top %p, total_pages %d, m %p", top,
3169 		    total_pages, m));
3170 
3171 		state = malloc(sizeof(*state), M_KTLS, M_WAITOK | M_ZERO);
3172 		soref(so);
3173 		state->so = so;
3174 		state->m = m;
3175 
3176 		mpages = m->m_epg_nrdy;
3177 		n = m->m_next;
3178 
3179 		error = ktls_encrypt_record(wq, m, tls, state);
3180 		if (error) {
3181 			counter_u64_add(ktls_offload_failed_crypto, 1);
3182 			free(state, M_KTLS);
3183 			CURVNET_SET(so->so_vnet);
3184 			sorele(so);
3185 			CURVNET_RESTORE();
3186 			break;
3187 		}
3188 
3189 		npages += mpages;
3190 	}
3191 
3192 	CURVNET_SET(so->so_vnet);
3193 	if (error != 0) {
3194 		ktls_drop(so, EIO);
3195 		mb_free_notready(m, total_pages - npages);
3196 	}
3197 
3198 	sorele(so);
3199 	CURVNET_RESTORE();
3200 }
3201 
3202 static int
ktls_bind_domain(int domain)3203 ktls_bind_domain(int domain)
3204 {
3205 	int error;
3206 
3207 	error = cpuset_setthread(curthread->td_tid, &cpuset_domain[domain]);
3208 	if (error != 0)
3209 		return (error);
3210 	curthread->td_domain.dr_policy = DOMAINSET_PREF(domain);
3211 	return (0);
3212 }
3213 
3214 static void
ktls_reclaim_thread(void * ctx)3215 ktls_reclaim_thread(void *ctx)
3216 {
3217 	struct ktls_domain_info *ktls_domain = ctx;
3218 	struct ktls_reclaim_thread *sc = &ktls_domain->reclaim_td;
3219 	struct sysctl_oid *oid;
3220 	char name[80];
3221 	int error, domain;
3222 
3223 	domain = ktls_domain - ktls_domains;
3224 	if (bootverbose)
3225 		printf("Starting KTLS reclaim thread for domain %d\n", domain);
3226 	error = ktls_bind_domain(domain);
3227 	if (error)
3228 		printf("Unable to bind KTLS reclaim thread for domain %d: error %d\n",
3229 		    domain, error);
3230 	snprintf(name, sizeof(name), "domain%d", domain);
3231 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_kern_ipc_tls), OID_AUTO,
3232 	    name, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
3233 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "reclaims",
3234 	    CTLFLAG_RD,  &sc->reclaims, 0, "buffers reclaimed");
3235 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "wakeups",
3236 	    CTLFLAG_RD,  &sc->wakeups, 0, "thread wakeups");
3237 	SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(oid), OID_AUTO, "running",
3238 	    CTLFLAG_RD,  &sc->running, 0, "thread running");
3239 
3240 	for (;;) {
3241 		atomic_store_int(&sc->running, 0);
3242 		tsleep(sc, PZERO | PNOLOCK, "-",  0);
3243 		atomic_store_int(&sc->running, 1);
3244 		sc->wakeups++;
3245 		/*
3246 		 * Below we attempt to reclaim ktls_max_reclaim
3247 		 * buffers using vm_page_reclaim_contig_domain_ext().
3248 		 * We do this here, as this function can take several
3249 		 * seconds to scan all of memory and it does not
3250 		 * matter if this thread pauses for a while.  If we
3251 		 * block a ktls worker thread, we risk developing
3252 		 * backlogs of buffers to be encrypted, leading to
3253 		 * surges of traffic and potential NIC output drops.
3254 		 */
3255 		if (vm_page_reclaim_contig_domain_ext(domain, VM_ALLOC_NORMAL,
3256 		    atop(ktls_maxlen), 0, ~0ul, PAGE_SIZE, 0,
3257 		    ktls_max_reclaim) != 0) {
3258 			vm_wait_domain(domain);
3259 		} else {
3260 			sc->reclaims += ktls_max_reclaim;
3261 		}
3262 	}
3263 }
3264 
3265 static void
ktls_work_thread(void * ctx)3266 ktls_work_thread(void *ctx)
3267 {
3268 	struct ktls_wq *wq = ctx;
3269 	struct mbuf *m, *n;
3270 	struct socket *so, *son;
3271 	STAILQ_HEAD(, mbuf) local_m_head;
3272 	STAILQ_HEAD(, socket) local_so_head;
3273 	int cpu;
3274 
3275 	cpu = wq - ktls_wq;
3276 	if (bootverbose)
3277 		printf("Starting KTLS worker thread for CPU %d\n", cpu);
3278 
3279 	/*
3280 	 * Bind to a core.  If ktls_bind_threads is > 1, then
3281 	 * we bind to the NUMA domain instead.
3282 	 */
3283 	if (ktls_bind_threads) {
3284 		int error;
3285 
3286 		if (ktls_bind_threads > 1) {
3287 			struct pcpu *pc = pcpu_find(cpu);
3288 
3289 			error = ktls_bind_domain(pc->pc_domain);
3290 		} else {
3291 			cpuset_t mask;
3292 
3293 			CPU_SETOF(cpu, &mask);
3294 			error = cpuset_setthread(curthread->td_tid, &mask);
3295 		}
3296 		if (error)
3297 			printf("Unable to bind KTLS worker thread for CPU %d: error %d\n",
3298 				cpu, error);
3299 	}
3300 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
3301 	fpu_kern_thread(0);
3302 #endif
3303 	for (;;) {
3304 		mtx_lock(&wq->mtx);
3305 		while (STAILQ_EMPTY(&wq->m_head) &&
3306 		    STAILQ_EMPTY(&wq->so_head)) {
3307 			wq->running = false;
3308 			mtx_sleep(wq, &wq->mtx, 0, "-", 0);
3309 			wq->running = true;
3310 		}
3311 
3312 		STAILQ_INIT(&local_m_head);
3313 		STAILQ_CONCAT(&local_m_head, &wq->m_head);
3314 		STAILQ_INIT(&local_so_head);
3315 		STAILQ_CONCAT(&local_so_head, &wq->so_head);
3316 		mtx_unlock(&wq->mtx);
3317 
3318 		STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
3319 			if (m->m_epg_flags & EPG_FLAG_2FREE) {
3320 				ktls_free(m->m_epg_tls);
3321 				m_free_raw(m);
3322 			} else {
3323 				if (m->m_epg_tls->sync_dispatch)
3324 					ktls_encrypt(wq, m);
3325 				else
3326 					ktls_encrypt_async(wq, m);
3327 				counter_u64_add(ktls_cnt_tx_queued, -1);
3328 			}
3329 		}
3330 
3331 		STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
3332 			ktls_decrypt(so);
3333 			counter_u64_add(ktls_cnt_rx_queued, -1);
3334 		}
3335 	}
3336 }
3337 
3338 static void
ktls_disable_ifnet_help(void * context,int pending __unused)3339 ktls_disable_ifnet_help(void *context, int pending __unused)
3340 {
3341 	struct ktls_session *tls;
3342 	struct inpcb *inp;
3343 	struct tcpcb *tp;
3344 	struct socket *so;
3345 	int err;
3346 
3347 	tls = context;
3348 	inp = tls->inp;
3349 	if (inp == NULL)
3350 		return;
3351 	INP_WLOCK(inp);
3352 	so = inp->inp_socket;
3353 	MPASS(so != NULL);
3354 	tp = intotcpcb(inp);
3355 	if (tp->t_flags & TF_DISCONNECTED) {
3356 		goto out;
3357 	}
3358 
3359 	if (so->so_snd.sb_tls_info != NULL)
3360 		err = ktls_set_tx_mode(so, TCP_TLS_MODE_SW);
3361 	else
3362 		err = ENXIO;
3363 	if (err == 0) {
3364 		counter_u64_add(ktls_ifnet_disable_ok, 1);
3365 		/* ktls_set_tx_mode() drops inp wlock, so recheck flags */
3366 		if ((tp->t_flags & TF_DISCONNECTED) == 0 &&
3367 		    tp->t_fb->tfb_hwtls_change != NULL)
3368 			(*tp->t_fb->tfb_hwtls_change)(tp, 0);
3369 	} else {
3370 		counter_u64_add(ktls_ifnet_disable_fail, 1);
3371 	}
3372 
3373 out:
3374 	CURVNET_SET(so->so_vnet);
3375 	sorele(so);
3376 	CURVNET_RESTORE();
3377 	INP_WUNLOCK(inp);
3378 	ktls_free(tls);
3379 }
3380 
3381 /*
3382  * Called when re-transmits are becoming a substantial portion of the
3383  * sends on this connection.  When this happens, we transition the
3384  * connection to software TLS.  This is needed because most inline TLS
3385  * NICs keep crypto state only for in-order transmits.  This means
3386  * that to handle a TCP rexmit (which is out-of-order), the NIC must
3387  * re-DMA the entire TLS record up to and including the current
3388  * segment.  This means that when re-transmitting the last ~1448 byte
3389  * segment of a 16KB TLS record, we could wind up re-DMA'ing an order
3390  * of magnitude more data than we are sending.  This can cause the
3391  * PCIe link to saturate well before the network, which can cause
3392  * output drops, and a general loss of capacity.
3393  */
3394 void
ktls_disable_ifnet(void * arg)3395 ktls_disable_ifnet(void *arg)
3396 {
3397 	struct tcpcb *tp;
3398 	struct inpcb *inp;
3399 	struct socket *so;
3400 	struct ktls_session *tls;
3401 
3402 	tp = arg;
3403 	inp = tptoinpcb(tp);
3404 	INP_WLOCK_ASSERT(inp);
3405 	so = inp->inp_socket;
3406 	SOCK_LOCK(so);
3407 	tls = so->so_snd.sb_tls_info;
3408 	if (tp->t_nic_ktls_xmit_dis == 1) {
3409 		SOCK_UNLOCK(so);
3410 		return;
3411 	}
3412 
3413 	/*
3414 	 * note that t_nic_ktls_xmit_dis is never cleared; disabling
3415 	 * ifnet can only be done once per connection, so we never want
3416 	 * to do it again
3417 	 */
3418 
3419 	(void)ktls_hold(tls);
3420 	soref(so);
3421 	tp->t_nic_ktls_xmit_dis = 1;
3422 	SOCK_UNLOCK(so);
3423 	TASK_INIT(&tls->disable_ifnet_task, 0, ktls_disable_ifnet_help, tls);
3424 	(void)taskqueue_enqueue(taskqueue_thread, &tls->disable_ifnet_task);
3425 }
3426 
3427 void
ktls_session_to_xktls_onedir(const struct ktls_session * ktls,bool export_keys,struct xktls_session_onedir * xk)3428 ktls_session_to_xktls_onedir(const struct ktls_session *ktls, bool export_keys,
3429     struct xktls_session_onedir *xk)
3430 {
3431 	if_t ifp;
3432 	struct m_snd_tag *st;
3433 
3434 	xk->gen = ktls->gen;
3435 #define	A(m) xk->m = ktls->params.m
3436 	A(cipher_algorithm);
3437 	A(auth_algorithm);
3438 	A(cipher_key_len);
3439 	A(auth_key_len);
3440 	A(max_frame_len);
3441 	A(tls_vmajor);
3442 	A(tls_vminor);
3443 	A(tls_hlen);
3444 	A(tls_tlen);
3445 	A(tls_bs);
3446 	A(flags);
3447 	if (export_keys) {
3448 		memcpy(&xk->iv, &ktls->params.iv, XKTLS_SESSION_IV_BUF_LEN);
3449 		A(iv_len);
3450 	} else {
3451 		memset(&xk->iv, 0, XKTLS_SESSION_IV_BUF_LEN);
3452 		xk->iv_len = 0;
3453 	}
3454 #undef A
3455 	if ((st = ktls->snd_tag) != NULL &&
3456 	    (ifp = ktls->snd_tag->ifp) != NULL)
3457 		strncpy(xk->ifnet, if_name(ifp), sizeof(xk->ifnet));
3458 }
3459 
3460 void
ktls_session_copy_keys(const struct ktls_session * ktls,uint8_t * data,size_t * sz)3461 ktls_session_copy_keys(const struct ktls_session *ktls,
3462     uint8_t *data, size_t *sz)
3463 {
3464 	size_t t, ta, tc;
3465 
3466 	if (ktls == NULL) {
3467 		*sz = 0;
3468 		return;
3469 	}
3470 	t = *sz;
3471 	tc = MIN(t, ktls->params.cipher_key_len);
3472 	if (data != NULL)
3473 		memcpy(data, ktls->params.cipher_key, tc);
3474 	ta = MIN(t - tc, ktls->params.auth_key_len);
3475 	if (data != NULL)
3476 		memcpy(data + tc, ktls->params.auth_key, ta);
3477 	*sz = ta + tc;
3478 }
3479