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