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