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