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