]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_ktls.c
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / sys / kern / uipc_ktls.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2014-2019 Netflix Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_rss.h"
34
35 #include <sys/param.h>
36 #include <sys/kernel.h>
37 #include <sys/ktls.h>
38 #include <sys/lock.h>
39 #include <sys/mbuf.h>
40 #include <sys/mutex.h>
41 #include <sys/rmlock.h>
42 #include <sys/proc.h>
43 #include <sys/protosw.h>
44 #include <sys/refcount.h>
45 #include <sys/smp.h>
46 #include <sys/socket.h>
47 #include <sys/socketvar.h>
48 #include <sys/sysctl.h>
49 #include <sys/taskqueue.h>
50 #include <sys/kthread.h>
51 #include <sys/uio.h>
52 #include <sys/vmmeter.h>
53 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
54 #include <machine/pcb.h>
55 #endif
56 #include <machine/vmparam.h>
57 #include <net/if.h>
58 #include <net/if_var.h>
59 #ifdef RSS
60 #include <net/netisr.h>
61 #include <net/rss_config.h>
62 #endif
63 #include <net/route.h>
64 #include <net/route/nhop.h>
65 #if defined(INET) || defined(INET6)
66 #include <netinet/in.h>
67 #include <netinet/in_pcb.h>
68 #endif
69 #include <netinet/tcp_var.h>
70 #ifdef TCP_OFFLOAD
71 #include <netinet/tcp_offload.h>
72 #endif
73 #include <opencrypto/xform.h>
74 #include <vm/uma_dbg.h>
75 #include <vm/vm.h>
76 #include <vm/vm_pageout.h>
77 #include <vm/vm_page.h>
78
79 struct ktls_wq {
80         struct mtx      mtx;
81         STAILQ_HEAD(, mbuf) m_head;
82         STAILQ_HEAD(, socket) so_head;
83         bool            running;
84 } __aligned(CACHE_LINE_SIZE);
85
86 static struct ktls_wq *ktls_wq;
87 static struct proc *ktls_proc;
88 LIST_HEAD(, ktls_crypto_backend) ktls_backends;
89 static struct rmlock ktls_backends_lock;
90 static uma_zone_t ktls_session_zone;
91 static uint16_t ktls_cpuid_lookup[MAXCPU];
92
93 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
94     "Kernel TLS offload");
95 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
96     "Kernel TLS offload stats");
97
98 static int ktls_allow_unload;
99 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, allow_unload, CTLFLAG_RDTUN,
100     &ktls_allow_unload, 0, "Allow software crypto modules to unload");
101
102 #ifdef RSS
103 static int ktls_bind_threads = 1;
104 #else
105 static int ktls_bind_threads;
106 #endif
107 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
108     &ktls_bind_threads, 0,
109     "Bind crypto threads to cores or domains at boot");
110
111 static u_int ktls_maxlen = 16384;
112 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RWTUN,
113     &ktls_maxlen, 0, "Maximum TLS record size");
114
115 static int ktls_number_threads;
116 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
117     &ktls_number_threads, 0,
118     "Number of TLS threads in thread-pool");
119
120 static bool ktls_offload_enable;
121 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RW,
122     &ktls_offload_enable, 0,
123     "Enable support for kernel TLS offload");
124
125 static bool ktls_cbc_enable = true;
126 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RW,
127     &ktls_cbc_enable, 1,
128     "Enable Support of AES-CBC crypto for kernel TLS");
129
130 static counter_u64_t ktls_tasks_active;
131 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
132     &ktls_tasks_active, "Number of active tasks");
133
134 static counter_u64_t ktls_cnt_tx_queued;
135 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_inqueue, CTLFLAG_RD,
136     &ktls_cnt_tx_queued,
137     "Number of TLS records in queue to tasks for SW encryption");
138
139 static counter_u64_t ktls_cnt_rx_queued;
140 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_rx_inqueue, CTLFLAG_RD,
141     &ktls_cnt_rx_queued,
142     "Number of TLS sockets in queue to tasks for SW decryption");
143
144 static counter_u64_t ktls_offload_total;
145 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
146     CTLFLAG_RD, &ktls_offload_total,
147     "Total successful TLS setups (parameters set)");
148
149 static counter_u64_t ktls_offload_enable_calls;
150 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
151     CTLFLAG_RD, &ktls_offload_enable_calls,
152     "Total number of TLS enable calls made");
153
154 static counter_u64_t ktls_offload_active;
155 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
156     &ktls_offload_active, "Total Active TLS sessions");
157
158 static counter_u64_t ktls_offload_corrupted_records;
159 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, corrupted_records, CTLFLAG_RD,
160     &ktls_offload_corrupted_records, "Total corrupted TLS records received");
161
162 static counter_u64_t ktls_offload_failed_crypto;
163 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
164     &ktls_offload_failed_crypto, "Total TLS crypto failures");
165
166 static counter_u64_t ktls_switch_to_ifnet;
167 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
168     &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
169
170 static counter_u64_t ktls_switch_to_sw;
171 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
172     &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
173
174 static counter_u64_t ktls_switch_failed;
175 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
176     &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
177
178 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
179     "Software TLS session stats");
180 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
181     "Hardware (ifnet) TLS session stats");
182 #ifdef TCP_OFFLOAD
183 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
184     "TOE TLS session stats");
185 #endif
186
187 static counter_u64_t ktls_sw_cbc;
188 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
189     "Active number of software TLS sessions using AES-CBC");
190
191 static counter_u64_t ktls_sw_gcm;
192 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
193     "Active number of software TLS sessions using AES-GCM");
194
195 static counter_u64_t ktls_ifnet_cbc;
196 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
197     &ktls_ifnet_cbc,
198     "Active number of ifnet TLS sessions using AES-CBC");
199
200 static counter_u64_t ktls_ifnet_gcm;
201 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
202     &ktls_ifnet_gcm,
203     "Active number of ifnet TLS sessions using AES-GCM");
204
205 static counter_u64_t ktls_ifnet_reset;
206 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
207     &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
208
209 static counter_u64_t ktls_ifnet_reset_dropped;
210 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
211     &ktls_ifnet_reset_dropped,
212     "TLS sessions dropped after failing to update ifnet send tag");
213
214 static counter_u64_t ktls_ifnet_reset_failed;
215 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
216     &ktls_ifnet_reset_failed,
217     "TLS sessions that failed to allocate a new ifnet send tag");
218
219 static int ktls_ifnet_permitted;
220 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
221     &ktls_ifnet_permitted, 1,
222     "Whether to permit hardware (ifnet) TLS sessions");
223
224 #ifdef TCP_OFFLOAD
225 static counter_u64_t ktls_toe_cbc;
226 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
227     &ktls_toe_cbc,
228     "Active number of TOE TLS sessions using AES-CBC");
229
230 static counter_u64_t ktls_toe_gcm;
231 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
232     &ktls_toe_gcm,
233     "Active number of TOE TLS sessions using AES-GCM");
234 #endif
235
236 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
237
238 static void ktls_cleanup(struct ktls_session *tls);
239 #if defined(INET) || defined(INET6)
240 static void ktls_reset_send_tag(void *context, int pending);
241 #endif
242 static void ktls_work_thread(void *ctx);
243
244 int
245 ktls_crypto_backend_register(struct ktls_crypto_backend *be)
246 {
247         struct ktls_crypto_backend *curr_be, *tmp;
248
249         if (be->api_version != KTLS_API_VERSION) {
250                 printf("KTLS: API version mismatch (%d vs %d) for %s\n",
251                     be->api_version, KTLS_API_VERSION,
252                     be->name);
253                 return (EINVAL);
254         }
255
256         rm_wlock(&ktls_backends_lock);
257         printf("KTLS: Registering crypto method %s with prio %d\n",
258                be->name, be->prio);
259         if (LIST_EMPTY(&ktls_backends)) {
260                 LIST_INSERT_HEAD(&ktls_backends, be, next);
261         } else {
262                 LIST_FOREACH_SAFE(curr_be, &ktls_backends, next, tmp) {
263                         if (curr_be->prio < be->prio) {
264                                 LIST_INSERT_BEFORE(curr_be, be, next);
265                                 break;
266                         }
267                         if (LIST_NEXT(curr_be, next) == NULL) {
268                                 LIST_INSERT_AFTER(curr_be, be, next);
269                                 break;
270                         }
271                 }
272         }
273         rm_wunlock(&ktls_backends_lock);
274         return (0);
275 }
276
277 int
278 ktls_crypto_backend_deregister(struct ktls_crypto_backend *be)
279 {
280         struct ktls_crypto_backend *tmp;
281
282         /*
283          * Don't error if the backend isn't registered.  This permits
284          * MOD_UNLOAD handlers to use this function unconditionally.
285          */
286         rm_wlock(&ktls_backends_lock);
287         LIST_FOREACH(tmp, &ktls_backends, next) {
288                 if (tmp == be)
289                         break;
290         }
291         if (tmp == NULL) {
292                 rm_wunlock(&ktls_backends_lock);
293                 return (0);
294         }
295
296         if (!ktls_allow_unload) {
297                 rm_wunlock(&ktls_backends_lock);
298                 printf(
299                     "KTLS: Deregistering crypto method %s is not supported\n",
300                     be->name);
301                 return (EBUSY);
302         }
303
304         if (be->use_count) {
305                 rm_wunlock(&ktls_backends_lock);
306                 return (EBUSY);
307         }
308
309         LIST_REMOVE(be, next);
310         rm_wunlock(&ktls_backends_lock);
311         return (0);
312 }
313
314 #if defined(INET) || defined(INET6)
315 static u_int
316 ktls_get_cpu(struct socket *so)
317 {
318         struct inpcb *inp;
319         u_int cpuid;
320
321         inp = sotoinpcb(so);
322 #ifdef RSS
323         cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
324         if (cpuid != NETISR_CPUID_NONE)
325                 return (cpuid);
326 #endif
327         /*
328          * Just use the flowid to shard connections in a repeatable
329          * fashion.  Note that some crypto backends rely on the
330          * serialization provided by having the same connection use
331          * the same queue.
332          */
333         cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
334         return (cpuid);
335 }
336 #endif
337
338 static void
339 ktls_init(void *dummy __unused)
340 {
341         struct thread *td;
342         struct pcpu *pc;
343         cpuset_t mask;
344         int error, i;
345
346         ktls_tasks_active = counter_u64_alloc(M_WAITOK);
347         ktls_cnt_tx_queued = counter_u64_alloc(M_WAITOK);
348         ktls_cnt_rx_queued = counter_u64_alloc(M_WAITOK);
349         ktls_offload_total = counter_u64_alloc(M_WAITOK);
350         ktls_offload_enable_calls = counter_u64_alloc(M_WAITOK);
351         ktls_offload_active = counter_u64_alloc(M_WAITOK);
352         ktls_offload_corrupted_records = counter_u64_alloc(M_WAITOK);
353         ktls_offload_failed_crypto = counter_u64_alloc(M_WAITOK);
354         ktls_switch_to_ifnet = counter_u64_alloc(M_WAITOK);
355         ktls_switch_to_sw = counter_u64_alloc(M_WAITOK);
356         ktls_switch_failed = counter_u64_alloc(M_WAITOK);
357         ktls_sw_cbc = counter_u64_alloc(M_WAITOK);
358         ktls_sw_gcm = counter_u64_alloc(M_WAITOK);
359         ktls_ifnet_cbc = counter_u64_alloc(M_WAITOK);
360         ktls_ifnet_gcm = counter_u64_alloc(M_WAITOK);
361         ktls_ifnet_reset = counter_u64_alloc(M_WAITOK);
362         ktls_ifnet_reset_dropped = counter_u64_alloc(M_WAITOK);
363         ktls_ifnet_reset_failed = counter_u64_alloc(M_WAITOK);
364 #ifdef TCP_OFFLOAD
365         ktls_toe_cbc = counter_u64_alloc(M_WAITOK);
366         ktls_toe_gcm = counter_u64_alloc(M_WAITOK);
367 #endif
368
369         rm_init(&ktls_backends_lock, "ktls backends");
370         LIST_INIT(&ktls_backends);
371
372         ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
373             M_WAITOK | M_ZERO);
374
375         ktls_session_zone = uma_zcreate("ktls_session",
376             sizeof(struct ktls_session),
377             NULL, NULL, NULL, NULL,
378             UMA_ALIGN_CACHE, 0);
379
380         /*
381          * Initialize the workqueues to run the TLS work.  We create a
382          * work queue for each CPU.
383          */
384         CPU_FOREACH(i) {
385                 STAILQ_INIT(&ktls_wq[i].m_head);
386                 STAILQ_INIT(&ktls_wq[i].so_head);
387                 mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
388                 error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
389                     &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
390                 if (error)
391                         panic("Can't add KTLS thread %d error %d", i, error);
392
393                 /*
394                  * Bind threads to cores.  If ktls_bind_threads is >
395                  * 1, then we bind to the NUMA domain.
396                  */
397                 if (ktls_bind_threads) {
398                         if (ktls_bind_threads > 1) {
399                                 pc = pcpu_find(i);
400                                 CPU_COPY(&cpuset_domain[pc->pc_domain], &mask);
401                         } else {
402                                 CPU_SETOF(i, &mask);
403                         }
404                         error = cpuset_setthread(td->td_tid, &mask);
405                         if (error)
406                                 panic(
407                             "Unable to bind KTLS thread for CPU %d error %d",
408                                      i, error);
409                 }
410                 ktls_cpuid_lookup[ktls_number_threads] = i;
411                 ktls_number_threads++;
412         }
413         printf("KTLS: Initialized %d threads\n", ktls_number_threads);
414 }
415 SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
416
417 #if defined(INET) || defined(INET6)
418 static int
419 ktls_create_session(struct socket *so, struct tls_enable *en,
420     struct ktls_session **tlsp)
421 {
422         struct ktls_session *tls;
423         int error;
424
425         /* Only TLS 1.0 - 1.3 are supported. */
426         if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
427                 return (EINVAL);
428         if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
429             en->tls_vminor > TLS_MINOR_VER_THREE)
430                 return (EINVAL);
431
432         if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
433                 return (EINVAL);
434         if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
435                 return (EINVAL);
436         if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
437                 return (EINVAL);
438
439         /* All supported algorithms require a cipher key. */
440         if (en->cipher_key_len == 0)
441                 return (EINVAL);
442
443         /* No flags are currently supported. */
444         if (en->flags != 0)
445                 return (EINVAL);
446
447         /* Common checks for supported algorithms. */
448         switch (en->cipher_algorithm) {
449         case CRYPTO_AES_NIST_GCM_16:
450                 /*
451                  * auth_algorithm isn't used, but permit GMAC values
452                  * for compatibility.
453                  */
454                 switch (en->auth_algorithm) {
455                 case 0:
456 #ifdef COMPAT_FREEBSD12
457                 /* XXX: Really 13.0-current COMPAT. */
458                 case CRYPTO_AES_128_NIST_GMAC:
459                 case CRYPTO_AES_192_NIST_GMAC:
460                 case CRYPTO_AES_256_NIST_GMAC:
461 #endif
462                         break;
463                 default:
464                         return (EINVAL);
465                 }
466                 if (en->auth_key_len != 0)
467                         return (EINVAL);
468                 if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
469                         en->iv_len != TLS_AEAD_GCM_LEN) ||
470                     (en->tls_vminor == TLS_MINOR_VER_THREE &&
471                         en->iv_len != TLS_1_3_GCM_IV_LEN))
472                         return (EINVAL);
473                 break;
474         case CRYPTO_AES_CBC:
475                 switch (en->auth_algorithm) {
476                 case CRYPTO_SHA1_HMAC:
477                         /*
478                          * TLS 1.0 requires an implicit IV.  TLS 1.1+
479                          * all use explicit IVs.
480                          */
481                         if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
482                                 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
483                                         return (EINVAL);
484                                 break;
485                         }
486
487                         /* FALLTHROUGH */
488                 case CRYPTO_SHA2_256_HMAC:
489                 case CRYPTO_SHA2_384_HMAC:
490                         /* Ignore any supplied IV. */
491                         en->iv_len = 0;
492                         break;
493                 default:
494                         return (EINVAL);
495                 }
496                 if (en->auth_key_len == 0)
497                         return (EINVAL);
498                 break;
499         default:
500                 return (EINVAL);
501         }
502
503         tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
504
505         counter_u64_add(ktls_offload_active, 1);
506
507         refcount_init(&tls->refcount, 1);
508         TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
509
510         tls->wq_index = ktls_get_cpu(so);
511
512         tls->params.cipher_algorithm = en->cipher_algorithm;
513         tls->params.auth_algorithm = en->auth_algorithm;
514         tls->params.tls_vmajor = en->tls_vmajor;
515         tls->params.tls_vminor = en->tls_vminor;
516         tls->params.flags = en->flags;
517         tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
518
519         /* Set the header and trailer lengths. */
520         tls->params.tls_hlen = sizeof(struct tls_record_layer);
521         switch (en->cipher_algorithm) {
522         case CRYPTO_AES_NIST_GCM_16:
523                 /*
524                  * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
525                  * nonce.  TLS 1.3 uses a 12 byte implicit IV.
526                  */
527                 if (en->tls_vminor < TLS_MINOR_VER_THREE)
528                         tls->params.tls_hlen += sizeof(uint64_t);
529                 tls->params.tls_tlen = AES_GMAC_HASH_LEN;
530
531                 /*
532                  * TLS 1.3 includes optional padding which we
533                  * do not support, and also puts the "real" record
534                  * type at the end of the encrypted data.
535                  */
536                 if (en->tls_vminor == TLS_MINOR_VER_THREE)
537                         tls->params.tls_tlen += sizeof(uint8_t);
538
539                 tls->params.tls_bs = 1;
540                 break;
541         case CRYPTO_AES_CBC:
542                 switch (en->auth_algorithm) {
543                 case CRYPTO_SHA1_HMAC:
544                         if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
545                                 /* Implicit IV, no nonce. */
546                         } else {
547                                 tls->params.tls_hlen += AES_BLOCK_LEN;
548                         }
549                         tls->params.tls_tlen = AES_BLOCK_LEN +
550                             SHA1_HASH_LEN;
551                         break;
552                 case CRYPTO_SHA2_256_HMAC:
553                         tls->params.tls_hlen += AES_BLOCK_LEN;
554                         tls->params.tls_tlen = AES_BLOCK_LEN +
555                             SHA2_256_HASH_LEN;
556                         break;
557                 case CRYPTO_SHA2_384_HMAC:
558                         tls->params.tls_hlen += AES_BLOCK_LEN;
559                         tls->params.tls_tlen = AES_BLOCK_LEN +
560                             SHA2_384_HASH_LEN;
561                         break;
562                 default:
563                         panic("invalid hmac");
564                 }
565                 tls->params.tls_bs = AES_BLOCK_LEN;
566                 break;
567         default:
568                 panic("invalid cipher");
569         }
570
571         KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
572             ("TLS header length too long: %d", tls->params.tls_hlen));
573         KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
574             ("TLS trailer length too long: %d", tls->params.tls_tlen));
575
576         if (en->auth_key_len != 0) {
577                 tls->params.auth_key_len = en->auth_key_len;
578                 tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
579                     M_WAITOK);
580                 error = copyin(en->auth_key, tls->params.auth_key,
581                     en->auth_key_len);
582                 if (error)
583                         goto out;
584         }
585
586         tls->params.cipher_key_len = en->cipher_key_len;
587         tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
588         error = copyin(en->cipher_key, tls->params.cipher_key,
589             en->cipher_key_len);
590         if (error)
591                 goto out;
592
593         /*
594          * This holds the implicit portion of the nonce for GCM and
595          * the initial implicit IV for TLS 1.0.  The explicit portions
596          * of the IV are generated in ktls_frame().
597          */
598         if (en->iv_len != 0) {
599                 tls->params.iv_len = en->iv_len;
600                 error = copyin(en->iv, tls->params.iv, en->iv_len);
601                 if (error)
602                         goto out;
603
604                 /*
605                  * For TLS 1.2, generate an 8-byte nonce as a counter
606                  * to generate unique explicit IVs.
607                  *
608                  * Store this counter in the last 8 bytes of the IV
609                  * array so that it is 8-byte aligned.
610                  */
611                 if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
612                     en->tls_vminor == TLS_MINOR_VER_TWO)
613                         arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
614         }
615
616         *tlsp = tls;
617         return (0);
618
619 out:
620         ktls_cleanup(tls);
621         return (error);
622 }
623
624 static struct ktls_session *
625 ktls_clone_session(struct ktls_session *tls)
626 {
627         struct ktls_session *tls_new;
628
629         tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
630
631         counter_u64_add(ktls_offload_active, 1);
632
633         refcount_init(&tls_new->refcount, 1);
634
635         /* Copy fields from existing session. */
636         tls_new->params = tls->params;
637         tls_new->wq_index = tls->wq_index;
638
639         /* Deep copy keys. */
640         if (tls_new->params.auth_key != NULL) {
641                 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
642                     M_KTLS, M_WAITOK);
643                 memcpy(tls_new->params.auth_key, tls->params.auth_key,
644                     tls->params.auth_key_len);
645         }
646
647         tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
648             M_WAITOK);
649         memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
650             tls->params.cipher_key_len);
651
652         return (tls_new);
653 }
654 #endif
655
656 static void
657 ktls_cleanup(struct ktls_session *tls)
658 {
659
660         counter_u64_add(ktls_offload_active, -1);
661         switch (tls->mode) {
662         case TCP_TLS_MODE_SW:
663                 MPASS(tls->be != NULL);
664                 switch (tls->params.cipher_algorithm) {
665                 case CRYPTO_AES_CBC:
666                         counter_u64_add(ktls_sw_cbc, -1);
667                         break;
668                 case CRYPTO_AES_NIST_GCM_16:
669                         counter_u64_add(ktls_sw_gcm, -1);
670                         break;
671                 }
672                 tls->free(tls);
673                 break;
674         case TCP_TLS_MODE_IFNET:
675                 switch (tls->params.cipher_algorithm) {
676                 case CRYPTO_AES_CBC:
677                         counter_u64_add(ktls_ifnet_cbc, -1);
678                         break;
679                 case CRYPTO_AES_NIST_GCM_16:
680                         counter_u64_add(ktls_ifnet_gcm, -1);
681                         break;
682                 }
683                 m_snd_tag_rele(tls->snd_tag);
684                 break;
685 #ifdef TCP_OFFLOAD
686         case TCP_TLS_MODE_TOE:
687                 switch (tls->params.cipher_algorithm) {
688                 case CRYPTO_AES_CBC:
689                         counter_u64_add(ktls_toe_cbc, -1);
690                         break;
691                 case CRYPTO_AES_NIST_GCM_16:
692                         counter_u64_add(ktls_toe_gcm, -1);
693                         break;
694                 }
695                 break;
696 #endif
697         }
698         if (tls->params.auth_key != NULL) {
699                 zfree(tls->params.auth_key, M_KTLS);
700                 tls->params.auth_key = NULL;
701                 tls->params.auth_key_len = 0;
702         }
703         if (tls->params.cipher_key != NULL) {
704                 zfree(tls->params.cipher_key, M_KTLS);
705                 tls->params.cipher_key = NULL;
706                 tls->params.cipher_key_len = 0;
707         }
708         explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
709 }
710
711 #if defined(INET) || defined(INET6)
712
713 #ifdef TCP_OFFLOAD
714 static int
715 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
716 {
717         struct inpcb *inp;
718         struct tcpcb *tp;
719         int error;
720
721         inp = so->so_pcb;
722         INP_WLOCK(inp);
723         if (inp->inp_flags2 & INP_FREED) {
724                 INP_WUNLOCK(inp);
725                 return (ECONNRESET);
726         }
727         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
728                 INP_WUNLOCK(inp);
729                 return (ECONNRESET);
730         }
731         if (inp->inp_socket == NULL) {
732                 INP_WUNLOCK(inp);
733                 return (ECONNRESET);
734         }
735         tp = intotcpcb(inp);
736         if (tp->tod == NULL) {
737                 INP_WUNLOCK(inp);
738                 return (EOPNOTSUPP);
739         }
740
741         error = tcp_offload_alloc_tls_session(tp, tls, direction);
742         INP_WUNLOCK(inp);
743         if (error == 0) {
744                 tls->mode = TCP_TLS_MODE_TOE;
745                 switch (tls->params.cipher_algorithm) {
746                 case CRYPTO_AES_CBC:
747                         counter_u64_add(ktls_toe_cbc, 1);
748                         break;
749                 case CRYPTO_AES_NIST_GCM_16:
750                         counter_u64_add(ktls_toe_gcm, 1);
751                         break;
752                 }
753         }
754         return (error);
755 }
756 #endif
757
758 /*
759  * Common code used when first enabling ifnet TLS on a connection or
760  * when allocating a new ifnet TLS session due to a routing change.
761  * This function allocates a new TLS send tag on whatever interface
762  * the connection is currently routed over.
763  */
764 static int
765 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
766     struct m_snd_tag **mstp)
767 {
768         union if_snd_tag_alloc_params params;
769         struct ifnet *ifp;
770         struct nhop_object *nh;
771         struct tcpcb *tp;
772         int error;
773
774         INP_RLOCK(inp);
775         if (inp->inp_flags2 & INP_FREED) {
776                 INP_RUNLOCK(inp);
777                 return (ECONNRESET);
778         }
779         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
780                 INP_RUNLOCK(inp);
781                 return (ECONNRESET);
782         }
783         if (inp->inp_socket == NULL) {
784                 INP_RUNLOCK(inp);
785                 return (ECONNRESET);
786         }
787         tp = intotcpcb(inp);
788
789         /*
790          * Check administrative controls on ifnet TLS to determine if
791          * ifnet TLS should be denied.
792          *
793          * - Always permit 'force' requests.
794          * - ktls_ifnet_permitted == 0: always deny.
795          */
796         if (!force && ktls_ifnet_permitted == 0) {
797                 INP_RUNLOCK(inp);
798                 return (ENXIO);
799         }
800
801         /*
802          * XXX: Use the cached route in the inpcb to find the
803          * interface.  This should perhaps instead use
804          * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
805          * enabled after a connection has completed key negotiation in
806          * userland, the cached route will be present in practice.
807          */
808         nh = inp->inp_route.ro_nh;
809         if (nh == NULL) {
810                 INP_RUNLOCK(inp);
811                 return (ENXIO);
812         }
813         ifp = nh->nh_ifp;
814         if_ref(ifp);
815
816         params.hdr.type = IF_SND_TAG_TYPE_TLS;
817         params.hdr.flowid = inp->inp_flowid;
818         params.hdr.flowtype = inp->inp_flowtype;
819         params.hdr.numa_domain = inp->inp_numa_domain;
820         params.tls.inp = inp;
821         params.tls.tls = tls;
822         INP_RUNLOCK(inp);
823
824         if (ifp->if_snd_tag_alloc == NULL) {
825                 error = EOPNOTSUPP;
826                 goto out;
827         }
828         if ((ifp->if_capenable & IFCAP_NOMAP) == 0) {   
829                 error = EOPNOTSUPP;
830                 goto out;
831         }
832         if (inp->inp_vflag & INP_IPV6) {
833                 if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
834                         error = EOPNOTSUPP;
835                         goto out;
836                 }
837         } else {
838                 if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
839                         error = EOPNOTSUPP;
840                         goto out;
841                 }
842         }
843         error = ifp->if_snd_tag_alloc(ifp, &params, mstp);
844 out:
845         if_rele(ifp);
846         return (error);
847 }
848
849 static int
850 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
851 {
852         struct m_snd_tag *mst;
853         int error;
854
855         error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
856         if (error == 0) {
857                 tls->mode = TCP_TLS_MODE_IFNET;
858                 tls->snd_tag = mst;
859                 switch (tls->params.cipher_algorithm) {
860                 case CRYPTO_AES_CBC:
861                         counter_u64_add(ktls_ifnet_cbc, 1);
862                         break;
863                 case CRYPTO_AES_NIST_GCM_16:
864                         counter_u64_add(ktls_ifnet_gcm, 1);
865                         break;
866                 }
867         }
868         return (error);
869 }
870
871 static int
872 ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
873 {
874         struct rm_priotracker prio;
875         struct ktls_crypto_backend *be;
876
877         /*
878          * Choose the best software crypto backend.  Backends are
879          * stored in sorted priority order (larget value == most
880          * important at the head of the list), so this just stops on
881          * the first backend that claims the session by returning
882          * success.
883          */
884         if (ktls_allow_unload)
885                 rm_rlock(&ktls_backends_lock, &prio);
886         LIST_FOREACH(be, &ktls_backends, next) {
887                 if (be->try(so, tls, direction) == 0)
888                         break;
889                 KASSERT(tls->cipher == NULL,
890                     ("ktls backend leaked a cipher pointer"));
891         }
892         if (be != NULL) {
893                 if (ktls_allow_unload)
894                         be->use_count++;
895                 tls->be = be;
896         }
897         if (ktls_allow_unload)
898                 rm_runlock(&ktls_backends_lock, &prio);
899         if (be == NULL)
900                 return (EOPNOTSUPP);
901         tls->mode = TCP_TLS_MODE_SW;
902         switch (tls->params.cipher_algorithm) {
903         case CRYPTO_AES_CBC:
904                 counter_u64_add(ktls_sw_cbc, 1);
905                 break;
906         case CRYPTO_AES_NIST_GCM_16:
907                 counter_u64_add(ktls_sw_gcm, 1);
908                 break;
909         }
910         return (0);
911 }
912
913 /*
914  * KTLS RX stores data in the socket buffer as a list of TLS records,
915  * where each record is stored as a control message containg the TLS
916  * header followed by data mbufs containing the decrypted data.  This
917  * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
918  * both encrypted and decrypted data.  TLS records decrypted by a NIC
919  * should be queued to the socket buffer as records, but encrypted
920  * data which needs to be decrypted by software arrives as a stream of
921  * regular mbufs which need to be converted.  In addition, there may
922  * already be pending encrypted data in the socket buffer when KTLS RX
923  * is enabled.
924  *
925  * To manage not-yet-decrypted data for KTLS RX, the following scheme
926  * is used:
927  *
928  * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
929  *
930  * - ktls_check_rx checks this chain of mbufs reading the TLS header
931  *   from the first mbuf.  Once all of the data for that TLS record is
932  *   queued, the socket is queued to a worker thread.
933  *
934  * - The worker thread calls ktls_decrypt to decrypt TLS records in
935  *   the TLS chain.  Each TLS record is detached from the TLS chain,
936  *   decrypted, and inserted into the regular socket buffer chain as
937  *   record starting with a control message holding the TLS header and
938  *   a chain of mbufs holding the encrypted data.
939  */
940
941 static void
942 sb_mark_notready(struct sockbuf *sb)
943 {
944         struct mbuf *m;
945
946         m = sb->sb_mb;
947         sb->sb_mtls = m;
948         sb->sb_mb = NULL;
949         sb->sb_mbtail = NULL;
950         sb->sb_lastrecord = NULL;
951         for (; m != NULL; m = m->m_next) {
952                 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
953                     __func__));
954                 KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
955                     __func__));
956                 KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
957                     __func__));
958                 m->m_flags |= M_NOTREADY;
959                 sb->sb_acc -= m->m_len;
960                 sb->sb_tlscc += m->m_len;
961                 sb->sb_mtlstail = m;
962         }
963         KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
964             ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
965             sb->sb_ccc));
966 }
967
968 int
969 ktls_enable_rx(struct socket *so, struct tls_enable *en)
970 {
971         struct ktls_session *tls;
972         int error;
973
974         if (!ktls_offload_enable)
975                 return (ENOTSUP);
976
977         counter_u64_add(ktls_offload_enable_calls, 1);
978
979         /*
980          * This should always be true since only the TCP socket option
981          * invokes this function.
982          */
983         if (so->so_proto->pr_protocol != IPPROTO_TCP)
984                 return (EINVAL);
985
986         /*
987          * XXX: Don't overwrite existing sessions.  We should permit
988          * this to support rekeying in the future.
989          */
990         if (so->so_rcv.sb_tls_info != NULL)
991                 return (EALREADY);
992
993         if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
994                 return (ENOTSUP);
995
996         /* TLS 1.3 is not yet supported. */
997         if (en->tls_vmajor == TLS_MAJOR_VER_ONE &&
998             en->tls_vminor == TLS_MINOR_VER_THREE)
999                 return (ENOTSUP);
1000
1001         error = ktls_create_session(so, en, &tls);
1002         if (error)
1003                 return (error);
1004
1005 #ifdef TCP_OFFLOAD
1006         error = ktls_try_toe(so, tls, KTLS_RX);
1007         if (error)
1008 #endif
1009                 error = ktls_try_sw(so, tls, KTLS_RX);
1010
1011         if (error) {
1012                 ktls_cleanup(tls);
1013                 return (error);
1014         }
1015
1016         /* Mark the socket as using TLS offload. */
1017         SOCKBUF_LOCK(&so->so_rcv);
1018         so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1019         so->so_rcv.sb_tls_info = tls;
1020         so->so_rcv.sb_flags |= SB_TLS_RX;
1021
1022         /* Mark existing data as not ready until it can be decrypted. */
1023         sb_mark_notready(&so->so_rcv);
1024         ktls_check_rx(&so->so_rcv);
1025         SOCKBUF_UNLOCK(&so->so_rcv);
1026
1027         counter_u64_add(ktls_offload_total, 1);
1028
1029         return (0);
1030 }
1031
1032 int
1033 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1034 {
1035         struct ktls_session *tls;
1036         int error;
1037
1038         if (!ktls_offload_enable)
1039                 return (ENOTSUP);
1040
1041         counter_u64_add(ktls_offload_enable_calls, 1);
1042
1043         /*
1044          * This should always be true since only the TCP socket option
1045          * invokes this function.
1046          */
1047         if (so->so_proto->pr_protocol != IPPROTO_TCP)
1048                 return (EINVAL);
1049
1050         /*
1051          * XXX: Don't overwrite existing sessions.  We should permit
1052          * this to support rekeying in the future.
1053          */
1054         if (so->so_snd.sb_tls_info != NULL)
1055                 return (EALREADY);
1056
1057         if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1058                 return (ENOTSUP);
1059
1060         /* TLS requires ext pgs */
1061         if (mb_use_ext_pgs == 0)
1062                 return (ENXIO);
1063
1064         error = ktls_create_session(so, en, &tls);
1065         if (error)
1066                 return (error);
1067
1068         /* Prefer TOE -> ifnet TLS -> software TLS. */
1069 #ifdef TCP_OFFLOAD
1070         error = ktls_try_toe(so, tls, KTLS_TX);
1071         if (error)
1072 #endif
1073                 error = ktls_try_ifnet(so, tls, false);
1074         if (error)
1075                 error = ktls_try_sw(so, tls, KTLS_TX);
1076
1077         if (error) {
1078                 ktls_cleanup(tls);
1079                 return (error);
1080         }
1081
1082         error = sblock(&so->so_snd, SBL_WAIT);
1083         if (error) {
1084                 ktls_cleanup(tls);
1085                 return (error);
1086         }
1087
1088         SOCKBUF_LOCK(&so->so_snd);
1089         so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1090         so->so_snd.sb_tls_info = tls;
1091         if (tls->mode != TCP_TLS_MODE_SW)
1092                 so->so_snd.sb_flags |= SB_TLS_IFNET;
1093         SOCKBUF_UNLOCK(&so->so_snd);
1094         sbunlock(&so->so_snd);
1095
1096         counter_u64_add(ktls_offload_total, 1);
1097
1098         return (0);
1099 }
1100
1101 int
1102 ktls_get_rx_mode(struct socket *so)
1103 {
1104         struct ktls_session *tls;
1105         struct inpcb *inp;
1106         int mode;
1107
1108         inp = so->so_pcb;
1109         INP_WLOCK_ASSERT(inp);
1110         SOCKBUF_LOCK(&so->so_rcv);
1111         tls = so->so_rcv.sb_tls_info;
1112         if (tls == NULL)
1113                 mode = TCP_TLS_MODE_NONE;
1114         else
1115                 mode = tls->mode;
1116         SOCKBUF_UNLOCK(&so->so_rcv);
1117         return (mode);
1118 }
1119
1120 int
1121 ktls_get_tx_mode(struct socket *so)
1122 {
1123         struct ktls_session *tls;
1124         struct inpcb *inp;
1125         int mode;
1126
1127         inp = so->so_pcb;
1128         INP_WLOCK_ASSERT(inp);
1129         SOCKBUF_LOCK(&so->so_snd);
1130         tls = so->so_snd.sb_tls_info;
1131         if (tls == NULL)
1132                 mode = TCP_TLS_MODE_NONE;
1133         else
1134                 mode = tls->mode;
1135         SOCKBUF_UNLOCK(&so->so_snd);
1136         return (mode);
1137 }
1138
1139 /*
1140  * Switch between SW and ifnet TLS sessions as requested.
1141  */
1142 int
1143 ktls_set_tx_mode(struct socket *so, int mode)
1144 {
1145         struct ktls_session *tls, *tls_new;
1146         struct inpcb *inp;
1147         int error;
1148
1149         switch (mode) {
1150         case TCP_TLS_MODE_SW:
1151         case TCP_TLS_MODE_IFNET:
1152                 break;
1153         default:
1154                 return (EINVAL);
1155         }
1156
1157         inp = so->so_pcb;
1158         INP_WLOCK_ASSERT(inp);
1159         SOCKBUF_LOCK(&so->so_snd);
1160         tls = so->so_snd.sb_tls_info;
1161         if (tls == NULL) {
1162                 SOCKBUF_UNLOCK(&so->so_snd);
1163                 return (0);
1164         }
1165
1166         if (tls->mode == mode) {
1167                 SOCKBUF_UNLOCK(&so->so_snd);
1168                 return (0);
1169         }
1170
1171         tls = ktls_hold(tls);
1172         SOCKBUF_UNLOCK(&so->so_snd);
1173         INP_WUNLOCK(inp);
1174
1175         tls_new = ktls_clone_session(tls);
1176
1177         if (mode == TCP_TLS_MODE_IFNET)
1178                 error = ktls_try_ifnet(so, tls_new, true);
1179         else
1180                 error = ktls_try_sw(so, tls_new, KTLS_TX);
1181         if (error) {
1182                 counter_u64_add(ktls_switch_failed, 1);
1183                 ktls_free(tls_new);
1184                 ktls_free(tls);
1185                 INP_WLOCK(inp);
1186                 return (error);
1187         }
1188
1189         error = sblock(&so->so_snd, SBL_WAIT);
1190         if (error) {
1191                 counter_u64_add(ktls_switch_failed, 1);
1192                 ktls_free(tls_new);
1193                 ktls_free(tls);
1194                 INP_WLOCK(inp);
1195                 return (error);
1196         }
1197
1198         /*
1199          * If we raced with another session change, keep the existing
1200          * session.
1201          */
1202         if (tls != so->so_snd.sb_tls_info) {
1203                 counter_u64_add(ktls_switch_failed, 1);
1204                 sbunlock(&so->so_snd);
1205                 ktls_free(tls_new);
1206                 ktls_free(tls);
1207                 INP_WLOCK(inp);
1208                 return (EBUSY);
1209         }
1210
1211         SOCKBUF_LOCK(&so->so_snd);
1212         so->so_snd.sb_tls_info = tls_new;
1213         if (tls_new->mode != TCP_TLS_MODE_SW)
1214                 so->so_snd.sb_flags |= SB_TLS_IFNET;
1215         SOCKBUF_UNLOCK(&so->so_snd);
1216         sbunlock(&so->so_snd);
1217
1218         /*
1219          * Drop two references on 'tls'.  The first is for the
1220          * ktls_hold() above.  The second drops the reference from the
1221          * socket buffer.
1222          */
1223         KASSERT(tls->refcount >= 2, ("too few references on old session"));
1224         ktls_free(tls);
1225         ktls_free(tls);
1226
1227         if (mode == TCP_TLS_MODE_IFNET)
1228                 counter_u64_add(ktls_switch_to_ifnet, 1);
1229         else
1230                 counter_u64_add(ktls_switch_to_sw, 1);
1231
1232         INP_WLOCK(inp);
1233         return (0);
1234 }
1235
1236 /*
1237  * Try to allocate a new TLS send tag.  This task is scheduled when
1238  * ip_output detects a route change while trying to transmit a packet
1239  * holding a TLS record.  If a new tag is allocated, replace the tag
1240  * in the TLS session.  Subsequent packets on the connection will use
1241  * the new tag.  If a new tag cannot be allocated, drop the
1242  * connection.
1243  */
1244 static void
1245 ktls_reset_send_tag(void *context, int pending)
1246 {
1247         struct epoch_tracker et;
1248         struct ktls_session *tls;
1249         struct m_snd_tag *old, *new;
1250         struct inpcb *inp;
1251         struct tcpcb *tp;
1252         int error;
1253
1254         MPASS(pending == 1);
1255
1256         tls = context;
1257         inp = tls->inp;
1258
1259         /*
1260          * Free the old tag first before allocating a new one.
1261          * ip[6]_output_send() will treat a NULL send tag the same as
1262          * an ifp mismatch and drop packets until a new tag is
1263          * allocated.
1264          *
1265          * Write-lock the INP when changing tls->snd_tag since
1266          * ip[6]_output_send() holds a read-lock when reading the
1267          * pointer.
1268          */
1269         INP_WLOCK(inp);
1270         old = tls->snd_tag;
1271         tls->snd_tag = NULL;
1272         INP_WUNLOCK(inp);
1273         if (old != NULL)
1274                 m_snd_tag_rele(old);
1275
1276         error = ktls_alloc_snd_tag(inp, tls, true, &new);
1277
1278         if (error == 0) {
1279                 INP_WLOCK(inp);
1280                 tls->snd_tag = new;
1281                 mtx_pool_lock(mtxpool_sleep, tls);
1282                 tls->reset_pending = false;
1283                 mtx_pool_unlock(mtxpool_sleep, tls);
1284                 if (!in_pcbrele_wlocked(inp))
1285                         INP_WUNLOCK(inp);
1286
1287                 counter_u64_add(ktls_ifnet_reset, 1);
1288
1289                 /*
1290                  * XXX: Should we kick tcp_output explicitly now that
1291                  * the send tag is fixed or just rely on timers?
1292                  */
1293         } else {
1294                 NET_EPOCH_ENTER(et);
1295                 INP_WLOCK(inp);
1296                 if (!in_pcbrele_wlocked(inp)) {
1297                         if (!(inp->inp_flags & INP_TIMEWAIT) &&
1298                             !(inp->inp_flags & INP_DROPPED)) {
1299                                 tp = intotcpcb(inp);
1300                                 CURVNET_SET(tp->t_vnet);
1301                                 tp = tcp_drop(tp, ECONNABORTED);
1302                                 CURVNET_RESTORE();
1303                                 if (tp != NULL)
1304                                         INP_WUNLOCK(inp);
1305                                 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1306                         } else
1307                                 INP_WUNLOCK(inp);
1308                 }
1309                 NET_EPOCH_EXIT(et);
1310
1311                 counter_u64_add(ktls_ifnet_reset_failed, 1);
1312
1313                 /*
1314                  * Leave reset_pending true to avoid future tasks while
1315                  * the socket goes away.
1316                  */
1317         }
1318
1319         ktls_free(tls);
1320 }
1321
1322 int
1323 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1324 {
1325
1326         if (inp == NULL)
1327                 return (ENOBUFS);
1328
1329         INP_LOCK_ASSERT(inp);
1330
1331         /*
1332          * See if we should schedule a task to update the send tag for
1333          * this session.
1334          */
1335         mtx_pool_lock(mtxpool_sleep, tls);
1336         if (!tls->reset_pending) {
1337                 (void) ktls_hold(tls);
1338                 in_pcbref(inp);
1339                 tls->inp = inp;
1340                 tls->reset_pending = true;
1341                 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1342         }
1343         mtx_pool_unlock(mtxpool_sleep, tls);
1344         return (ENOBUFS);
1345 }
1346 #endif
1347
1348 void
1349 ktls_destroy(struct ktls_session *tls)
1350 {
1351         struct rm_priotracker prio;
1352
1353         ktls_cleanup(tls);
1354         if (tls->be != NULL && ktls_allow_unload) {
1355                 rm_rlock(&ktls_backends_lock, &prio);
1356                 tls->be->use_count--;
1357                 rm_runlock(&ktls_backends_lock, &prio);
1358         }
1359         uma_zfree(ktls_session_zone, tls);
1360 }
1361
1362 void
1363 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1364 {
1365
1366         for (; m != NULL; m = m->m_next) {
1367                 KASSERT((m->m_flags & M_EXTPG) != 0,
1368                     ("ktls_seq: mapped mbuf %p", m));
1369
1370                 m->m_epg_seqno = sb->sb_tls_seqno;
1371                 sb->sb_tls_seqno++;
1372         }
1373 }
1374
1375 /*
1376  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
1377  * mbuf in the chain must be an unmapped mbuf.  The payload of the
1378  * mbuf must be populated with the payload of each TLS record.
1379  *
1380  * The record_type argument specifies the TLS record type used when
1381  * populating the TLS header.
1382  *
1383  * The enq_count argument on return is set to the number of pages of
1384  * payload data for this entire chain that need to be encrypted via SW
1385  * encryption.  The returned value should be passed to ktls_enqueue
1386  * when scheduling encryption of this chain of mbufs.
1387  */
1388 void
1389 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1390     uint8_t record_type)
1391 {
1392         struct tls_record_layer *tlshdr;
1393         struct mbuf *m;
1394         uint64_t *noncep;
1395         uint16_t tls_len;
1396         int maxlen;
1397
1398         maxlen = tls->params.max_frame_len;
1399         *enq_cnt = 0;
1400         for (m = top; m != NULL; m = m->m_next) {
1401                 /*
1402                  * All mbufs in the chain should be non-empty TLS
1403                  * records whose payload does not exceed the maximum
1404                  * frame length.
1405                  */
1406                 KASSERT(m->m_len <= maxlen && m->m_len > 0,
1407                     ("ktls_frame: m %p len %d\n", m, m->m_len));
1408                 /*
1409                  * TLS frames require unmapped mbufs to store session
1410                  * info.
1411                  */
1412                 KASSERT((m->m_flags & M_EXTPG) != 0,
1413                     ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1414
1415                 tls_len = m->m_len;
1416
1417                 /* Save a reference to the session. */
1418                 m->m_epg_tls = ktls_hold(tls);
1419
1420                 m->m_epg_hdrlen = tls->params.tls_hlen;
1421                 m->m_epg_trllen = tls->params.tls_tlen;
1422                 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1423                         int bs, delta;
1424
1425                         /*
1426                          * AES-CBC pads messages to a multiple of the
1427                          * block size.  Note that the padding is
1428                          * applied after the digest and the encryption
1429                          * is done on the "plaintext || mac || padding".
1430                          * At least one byte of padding is always
1431                          * present.
1432                          *
1433                          * Compute the final trailer length assuming
1434                          * at most one block of padding.
1435                          * tls->params.sb_tls_tlen is the maximum
1436                          * possible trailer length (padding + digest).
1437                          * delta holds the number of excess padding
1438                          * bytes if the maximum were used.  Those
1439                          * extra bytes are removed.
1440                          */
1441                         bs = tls->params.tls_bs;
1442                         delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1443                         m->m_epg_trllen -= delta;
1444                 }
1445                 m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1446
1447                 /* Populate the TLS header. */
1448                 tlshdr = (void *)m->m_epg_hdr;
1449                 tlshdr->tls_vmajor = tls->params.tls_vmajor;
1450
1451                 /*
1452                  * TLS 1.3 masquarades as TLS 1.2 with a record type
1453                  * of TLS_RLTYPE_APP.
1454                  */
1455                 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1456                     tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1457                         tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1458                         tlshdr->tls_type = TLS_RLTYPE_APP;
1459                         /* save the real record type for later */
1460                         m->m_epg_record_type = record_type;
1461                         m->m_epg_trail[0] = record_type;
1462                 } else {
1463                         tlshdr->tls_vminor = tls->params.tls_vminor;
1464                         tlshdr->tls_type = record_type;
1465                 }
1466                 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1467
1468                 /*
1469                  * Store nonces / explicit IVs after the end of the
1470                  * TLS header.
1471                  *
1472                  * For GCM with TLS 1.2, an 8 byte nonce is copied
1473                  * from the end of the IV.  The nonce is then
1474                  * incremented for use by the next record.
1475                  *
1476                  * For CBC, a random nonce is inserted for TLS 1.1+.
1477                  */
1478                 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
1479                     tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
1480                         noncep = (uint64_t *)(tls->params.iv + 8);
1481                         be64enc(tlshdr + 1, *noncep);
1482                         (*noncep)++;
1483                 } else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1484                     tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1485                         arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1486
1487                 /*
1488                  * When using SW encryption, mark the mbuf not ready.
1489                  * It will be marked ready via sbready() after the
1490                  * record has been encrypted.
1491                  *
1492                  * When using ifnet TLS, unencrypted TLS records are
1493                  * sent down the stack to the NIC.
1494                  */
1495                 if (tls->mode == TCP_TLS_MODE_SW) {
1496                         m->m_flags |= M_NOTREADY;
1497                         m->m_epg_nrdy = m->m_epg_npgs;
1498                         *enq_cnt += m->m_epg_npgs;
1499                 }
1500         }
1501 }
1502
1503 void
1504 ktls_check_rx(struct sockbuf *sb)
1505 {
1506         struct tls_record_layer hdr;
1507         struct ktls_wq *wq;
1508         struct socket *so;
1509         bool running;
1510
1511         SOCKBUF_LOCK_ASSERT(sb);
1512         KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1513             __func__, sb));
1514         so = __containerof(sb, struct socket, so_rcv);
1515
1516         if (sb->sb_flags & SB_TLS_RX_RUNNING)
1517                 return;
1518
1519         /* Is there enough queued for a TLS header? */
1520         if (sb->sb_tlscc < sizeof(hdr)) {
1521                 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
1522                         so->so_error = EMSGSIZE;
1523                 return;
1524         }
1525
1526         m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
1527
1528         /* Is the entire record queued? */
1529         if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
1530                 if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
1531                         so->so_error = EMSGSIZE;
1532                 return;
1533         }
1534
1535         sb->sb_flags |= SB_TLS_RX_RUNNING;
1536
1537         soref(so);
1538         wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
1539         mtx_lock(&wq->mtx);
1540         STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
1541         running = wq->running;
1542         mtx_unlock(&wq->mtx);
1543         if (!running)
1544                 wakeup(wq);
1545         counter_u64_add(ktls_cnt_rx_queued, 1);
1546 }
1547
1548 static struct mbuf *
1549 ktls_detach_record(struct sockbuf *sb, int len)
1550 {
1551         struct mbuf *m, *n, *top;
1552         int remain;
1553
1554         SOCKBUF_LOCK_ASSERT(sb);
1555         MPASS(len <= sb->sb_tlscc);
1556
1557         /*
1558          * If TLS chain is the exact size of the record,
1559          * just grab the whole record.
1560          */
1561         top = sb->sb_mtls;
1562         if (sb->sb_tlscc == len) {
1563                 sb->sb_mtls = NULL;
1564                 sb->sb_mtlstail = NULL;
1565                 goto out;
1566         }
1567
1568         /*
1569          * While it would be nice to use m_split() here, we need
1570          * to know exactly what m_split() allocates to update the
1571          * accounting, so do it inline instead.
1572          */
1573         remain = len;
1574         for (m = top; remain > m->m_len; m = m->m_next)
1575                 remain -= m->m_len;
1576
1577         /* Easy case: don't have to split 'm'. */
1578         if (remain == m->m_len) {
1579                 sb->sb_mtls = m->m_next;
1580                 if (sb->sb_mtls == NULL)
1581                         sb->sb_mtlstail = NULL;
1582                 m->m_next = NULL;
1583                 goto out;
1584         }
1585
1586         /*
1587          * Need to allocate an mbuf to hold the remainder of 'm'.  Try
1588          * with M_NOWAIT first.
1589          */
1590         n = m_get(M_NOWAIT, MT_DATA);
1591         if (n == NULL) {
1592                 /*
1593                  * Use M_WAITOK with socket buffer unlocked.  If
1594                  * 'sb_mtls' changes while the lock is dropped, return
1595                  * NULL to force the caller to retry.
1596                  */
1597                 SOCKBUF_UNLOCK(sb);
1598
1599                 n = m_get(M_WAITOK, MT_DATA);
1600
1601                 SOCKBUF_LOCK(sb);
1602                 if (sb->sb_mtls != top) {
1603                         m_free(n);
1604                         return (NULL);
1605                 }
1606         }
1607         n->m_flags |= M_NOTREADY;
1608
1609         /* Store remainder in 'n'. */
1610         n->m_len = m->m_len - remain;
1611         if (m->m_flags & M_EXT) {
1612                 n->m_data = m->m_data + remain;
1613                 mb_dupcl(n, m);
1614         } else {
1615                 bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
1616         }
1617
1618         /* Trim 'm' and update accounting. */
1619         m->m_len -= n->m_len;
1620         sb->sb_tlscc -= n->m_len;
1621         sb->sb_ccc -= n->m_len;
1622
1623         /* Account for 'n'. */
1624         sballoc_ktls_rx(sb, n);
1625
1626         /* Insert 'n' into the TLS chain. */
1627         sb->sb_mtls = n;
1628         n->m_next = m->m_next;
1629         if (sb->sb_mtlstail == m)
1630                 sb->sb_mtlstail = n;
1631
1632         /* Detach the record from the TLS chain. */
1633         m->m_next = NULL;
1634
1635 out:
1636         MPASS(m_length(top, NULL) == len);
1637         for (m = top; m != NULL; m = m->m_next)
1638                 sbfree_ktls_rx(sb, m);
1639         sb->sb_tlsdcc = len;
1640         sb->sb_ccc += len;
1641         SBCHECK(sb);
1642         return (top);
1643 }
1644
1645 static int
1646 m_segments(struct mbuf *m, int skip)
1647 {
1648         int count;
1649
1650         while (skip >= m->m_len) {
1651                 skip -= m->m_len;
1652                 m = m->m_next;
1653         }
1654
1655         for (count = 0; m != NULL; count++)
1656                 m = m->m_next;
1657         return (count);
1658 }
1659
1660 static void
1661 ktls_decrypt(struct socket *so)
1662 {
1663         char tls_header[MBUF_PEXT_HDR_LEN];
1664         struct ktls_session *tls;
1665         struct sockbuf *sb;
1666         struct tls_record_layer *hdr;
1667         struct tls_get_record tgr;
1668         struct mbuf *control, *data, *m;
1669         uint64_t seqno;
1670         int error, remain, tls_len, trail_len;
1671
1672         hdr = (struct tls_record_layer *)tls_header;
1673         sb = &so->so_rcv;
1674         SOCKBUF_LOCK(sb);
1675         KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
1676             ("%s: socket %p not running", __func__, so));
1677
1678         tls = sb->sb_tls_info;
1679         MPASS(tls != NULL);
1680
1681         for (;;) {
1682                 /* Is there enough queued for a TLS header? */
1683                 if (sb->sb_tlscc < tls->params.tls_hlen)
1684                         break;
1685
1686                 m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
1687                 tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
1688
1689                 if (hdr->tls_vmajor != tls->params.tls_vmajor ||
1690                     hdr->tls_vminor != tls->params.tls_vminor)
1691                         error = EINVAL;
1692                 else if (tls_len < tls->params.tls_hlen || tls_len >
1693                     tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
1694                     tls->params.tls_tlen)
1695                         error = EMSGSIZE;
1696                 else
1697                         error = 0;
1698                 if (__predict_false(error != 0)) {
1699                         /*
1700                          * We have a corrupted record and are likely
1701                          * out of sync.  The connection isn't
1702                          * recoverable at this point, so abort it.
1703                          */
1704                         SOCKBUF_UNLOCK(sb);
1705                         counter_u64_add(ktls_offload_corrupted_records, 1);
1706
1707                         CURVNET_SET(so->so_vnet);
1708                         so->so_proto->pr_usrreqs->pru_abort(so);
1709                         so->so_error = error;
1710                         CURVNET_RESTORE();
1711                         goto deref;
1712                 }
1713
1714                 /* Is the entire record queued? */
1715                 if (sb->sb_tlscc < tls_len)
1716                         break;
1717
1718                 /*
1719                  * Split out the portion of the mbuf chain containing
1720                  * this TLS record.
1721                  */
1722                 data = ktls_detach_record(sb, tls_len);
1723                 if (data == NULL)
1724                         continue;
1725                 MPASS(sb->sb_tlsdcc == tls_len);
1726
1727                 seqno = sb->sb_tls_seqno;
1728                 sb->sb_tls_seqno++;
1729                 SBCHECK(sb);
1730                 SOCKBUF_UNLOCK(sb);
1731
1732                 error = tls->sw_decrypt(tls, hdr, data, seqno, &trail_len);
1733                 if (error) {
1734                         counter_u64_add(ktls_offload_failed_crypto, 1);
1735
1736                         SOCKBUF_LOCK(sb);
1737                         if (sb->sb_tlsdcc == 0) {
1738                                 /*
1739                                  * sbcut/drop/flush discarded these
1740                                  * mbufs.
1741                                  */
1742                                 m_freem(data);
1743                                 break;
1744                         }
1745
1746                         /*
1747                          * Drop this TLS record's data, but keep
1748                          * decrypting subsequent records.
1749                          */
1750                         sb->sb_ccc -= tls_len;
1751                         sb->sb_tlsdcc = 0;
1752
1753                         CURVNET_SET(so->so_vnet);
1754                         so->so_error = EBADMSG;
1755                         sorwakeup_locked(so);
1756                         CURVNET_RESTORE();
1757
1758                         m_freem(data);
1759
1760                         SOCKBUF_LOCK(sb);
1761                         continue;
1762                 }
1763
1764                 /* Allocate the control mbuf. */
1765                 tgr.tls_type = hdr->tls_type;
1766                 tgr.tls_vmajor = hdr->tls_vmajor;
1767                 tgr.tls_vminor = hdr->tls_vminor;
1768                 tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
1769                     trail_len);
1770                 control = sbcreatecontrol_how(&tgr, sizeof(tgr),
1771                     TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
1772
1773                 SOCKBUF_LOCK(sb);
1774                 if (sb->sb_tlsdcc == 0) {
1775                         /* sbcut/drop/flush discarded these mbufs. */
1776                         MPASS(sb->sb_tlscc == 0);
1777                         m_freem(data);
1778                         m_freem(control);
1779                         break;
1780                 }
1781
1782                 /*
1783                  * Clear the 'dcc' accounting in preparation for
1784                  * adding the decrypted record.
1785                  */
1786                 sb->sb_ccc -= tls_len;
1787                 sb->sb_tlsdcc = 0;
1788                 SBCHECK(sb);
1789
1790                 /* If there is no payload, drop all of the data. */
1791                 if (tgr.tls_length == htobe16(0)) {
1792                         m_freem(data);
1793                         data = NULL;
1794                 } else {
1795                         /* Trim header. */
1796                         remain = tls->params.tls_hlen;
1797                         while (remain > 0) {
1798                                 if (data->m_len > remain) {
1799                                         data->m_data += remain;
1800                                         data->m_len -= remain;
1801                                         break;
1802                                 }
1803                                 remain -= data->m_len;
1804                                 data = m_free(data);
1805                         }
1806
1807                         /* Trim trailer and clear M_NOTREADY. */
1808                         remain = be16toh(tgr.tls_length);
1809                         m = data;
1810                         for (m = data; remain > m->m_len; m = m->m_next) {
1811                                 m->m_flags &= ~M_NOTREADY;
1812                                 remain -= m->m_len;
1813                         }
1814                         m->m_len = remain;
1815                         m_freem(m->m_next);
1816                         m->m_next = NULL;
1817                         m->m_flags &= ~M_NOTREADY;
1818
1819                         /* Set EOR on the final mbuf. */
1820                         m->m_flags |= M_EOR;
1821                 }
1822
1823                 sbappendcontrol_locked(sb, data, control, 0);
1824         }
1825
1826         sb->sb_flags &= ~SB_TLS_RX_RUNNING;
1827
1828         if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
1829                 so->so_error = EMSGSIZE;
1830
1831         sorwakeup_locked(so);
1832
1833 deref:
1834         SOCKBUF_UNLOCK_ASSERT(sb);
1835
1836         CURVNET_SET(so->so_vnet);
1837         SOCK_LOCK(so);
1838         sorele(so);
1839         CURVNET_RESTORE();
1840 }
1841
1842 void
1843 ktls_enqueue_to_free(struct mbuf *m)
1844 {
1845         struct ktls_wq *wq;
1846         bool running;
1847
1848         /* Mark it for freeing. */
1849         m->m_epg_flags |= EPG_FLAG_2FREE;
1850         wq = &ktls_wq[m->m_epg_tls->wq_index];
1851         mtx_lock(&wq->mtx);
1852         STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1853         running = wq->running;
1854         mtx_unlock(&wq->mtx);
1855         if (!running)
1856                 wakeup(wq);
1857 }
1858
1859 void
1860 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1861 {
1862         struct ktls_wq *wq;
1863         bool running;
1864
1865         KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
1866             (M_EXTPG | M_NOTREADY)),
1867             ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
1868         KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
1869
1870         KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1871
1872         m->m_epg_enc_cnt = page_count;
1873
1874         /*
1875          * Save a pointer to the socket.  The caller is responsible
1876          * for taking an additional reference via soref().
1877          */
1878         m->m_epg_so = so;
1879
1880         wq = &ktls_wq[m->m_epg_tls->wq_index];
1881         mtx_lock(&wq->mtx);
1882         STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1883         running = wq->running;
1884         mtx_unlock(&wq->mtx);
1885         if (!running)
1886                 wakeup(wq);
1887         counter_u64_add(ktls_cnt_tx_queued, 1);
1888 }
1889
1890 static __noinline void
1891 ktls_encrypt(struct mbuf *top)
1892 {
1893         struct ktls_session *tls;
1894         struct socket *so;
1895         struct mbuf *m;
1896         vm_paddr_t parray[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1897         struct iovec src_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1898         struct iovec dst_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1899         vm_page_t pg;
1900         int error, i, len, npages, off, total_pages;
1901         bool is_anon;
1902
1903         so = top->m_epg_so;
1904         tls = top->m_epg_tls;
1905         KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
1906         KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
1907 #ifdef INVARIANTS
1908         top->m_epg_so = NULL;
1909 #endif
1910         total_pages = top->m_epg_enc_cnt;
1911         npages = 0;
1912
1913         /*
1914          * Encrypt the TLS records in the chain of mbufs starting with
1915          * 'top'.  'total_pages' gives us a total count of pages and is
1916          * used to know when we have finished encrypting the TLS
1917          * records originally queued with 'top'.
1918          *
1919          * NB: These mbufs are queued in the socket buffer and
1920          * 'm_next' is traversing the mbufs in the socket buffer.  The
1921          * socket buffer lock is not held while traversing this chain.
1922          * Since the mbufs are all marked M_NOTREADY their 'm_next'
1923          * pointers should be stable.  However, the 'm_next' of the
1924          * last mbuf encrypted is not necessarily NULL.  It can point
1925          * to other mbufs appended while 'top' was on the TLS work
1926          * queue.
1927          *
1928          * Each mbuf holds an entire TLS record.
1929          */
1930         error = 0;
1931         for (m = top; npages != total_pages; m = m->m_next) {
1932                 KASSERT(m->m_epg_tls == tls,
1933                     ("different TLS sessions in a single mbuf chain: %p vs %p",
1934                     tls, m->m_epg_tls));
1935                 KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
1936                     (M_EXTPG | M_NOTREADY),
1937                     ("%p not unready & nomap mbuf (top = %p)\n", m, top));
1938                 KASSERT(npages + m->m_epg_npgs <= total_pages,
1939                     ("page count mismatch: top %p, total_pages %d, m %p", top,
1940                     total_pages, m));
1941
1942                 /*
1943                  * Generate source and destination ivoecs to pass to
1944                  * the SW encryption backend.  For writable mbufs, the
1945                  * destination iovec is a copy of the source and
1946                  * encryption is done in place.  For file-backed mbufs
1947                  * (from sendfile), anonymous wired pages are
1948                  * allocated and assigned to the destination iovec.
1949                  */
1950                 is_anon = (m->m_epg_flags & EPG_FLAG_ANON) != 0;
1951
1952                 off = m->m_epg_1st_off;
1953                 for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
1954                         len = m_epg_pagelen(m, i, off);
1955                         src_iov[i].iov_len = len;
1956                         src_iov[i].iov_base =
1957                             (char *)(void *)PHYS_TO_DMAP(m->m_epg_pa[i]) +
1958                                 off;
1959
1960                         if (is_anon) {
1961                                 dst_iov[i].iov_base = src_iov[i].iov_base;
1962                                 dst_iov[i].iov_len = src_iov[i].iov_len;
1963                                 continue;
1964                         }
1965 retry_page:
1966                         pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
1967                             VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP | VM_ALLOC_WIRED);
1968                         if (pg == NULL) {
1969                                 vm_wait(NULL);
1970                                 goto retry_page;
1971                         }
1972                         parray[i] = VM_PAGE_TO_PHYS(pg);
1973                         dst_iov[i].iov_base =
1974                             (char *)(void *)PHYS_TO_DMAP(parray[i]) + off;
1975                         dst_iov[i].iov_len = len;
1976                 }
1977
1978                 npages += i;
1979
1980                 error = (*tls->sw_encrypt)(tls,
1981                     (const struct tls_record_layer *)m->m_epg_hdr,
1982                     m->m_epg_trail, src_iov, dst_iov, i, m->m_epg_seqno,
1983                     m->m_epg_record_type);
1984                 if (error) {
1985                         counter_u64_add(ktls_offload_failed_crypto, 1);
1986                         break;
1987                 }
1988
1989                 /*
1990                  * For file-backed mbufs, release the file-backed
1991                  * pages and replace them in the ext_pgs array with
1992                  * the anonymous wired pages allocated above.
1993                  */
1994                 if (!is_anon) {
1995                         /* Free the old pages. */
1996                         m->m_ext.ext_free(m);
1997
1998                         /* Replace them with the new pages. */
1999                         for (i = 0; i < m->m_epg_npgs; i++)
2000                                 m->m_epg_pa[i] = parray[i];
2001
2002                         /* Use the basic free routine. */
2003                         m->m_ext.ext_free = mb_free_mext_pgs;
2004
2005                         /* Pages are now writable. */
2006                         m->m_epg_flags |= EPG_FLAG_ANON;
2007                 }
2008
2009                 /*
2010                  * Drop a reference to the session now that it is no
2011                  * longer needed.  Existing code depends on encrypted
2012                  * records having no associated session vs
2013                  * yet-to-be-encrypted records having an associated
2014                  * session.
2015                  */
2016                 m->m_epg_tls = NULL;
2017                 ktls_free(tls);
2018         }
2019
2020         CURVNET_SET(so->so_vnet);
2021         if (error == 0) {
2022                 (void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
2023         } else {
2024                 so->so_proto->pr_usrreqs->pru_abort(so);
2025                 so->so_error = EIO;
2026                 mb_free_notready(top, total_pages);
2027         }
2028
2029         SOCK_LOCK(so);
2030         sorele(so);
2031         CURVNET_RESTORE();
2032 }
2033
2034 static void
2035 ktls_work_thread(void *ctx)
2036 {
2037         struct ktls_wq *wq = ctx;
2038         struct mbuf *m, *n;
2039         struct socket *so, *son;
2040         STAILQ_HEAD(, mbuf) local_m_head;
2041         STAILQ_HEAD(, socket) local_so_head;
2042
2043 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
2044         fpu_kern_thread(0);
2045 #endif
2046         for (;;) {
2047                 mtx_lock(&wq->mtx);
2048                 while (STAILQ_EMPTY(&wq->m_head) &&
2049                     STAILQ_EMPTY(&wq->so_head)) {
2050                         wq->running = false;
2051                         mtx_sleep(wq, &wq->mtx, 0, "-", 0);
2052                         wq->running = true;
2053                 }
2054
2055                 STAILQ_INIT(&local_m_head);
2056                 STAILQ_CONCAT(&local_m_head, &wq->m_head);
2057                 STAILQ_INIT(&local_so_head);
2058                 STAILQ_CONCAT(&local_so_head, &wq->so_head);
2059                 mtx_unlock(&wq->mtx);
2060
2061                 STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
2062                         if (m->m_epg_flags & EPG_FLAG_2FREE) {
2063                                 ktls_free(m->m_epg_tls);
2064                                 uma_zfree(zone_mbuf, m);
2065                         } else {
2066                                 ktls_encrypt(m);
2067                                 counter_u64_add(ktls_cnt_tx_queued, -1);
2068                         }
2069                 }
2070
2071                 STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
2072                         ktls_decrypt(so);
2073                         counter_u64_add(ktls_cnt_rx_queued, -1);
2074                 }
2075         }
2076 }