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