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