]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_ktls.c
MFV r353623: 10473 zfs(1M) missing cross-reference to zfs-program(1M)
[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 #ifdef RSS
58 #include <net/netisr.h>
59 #include <net/rss_config.h>
60 #endif
61 #if defined(INET) || defined(INET6)
62 #include <netinet/in.h>
63 #include <netinet/in_pcb.h>
64 #endif
65 #include <netinet/tcp_var.h>
66 #ifdef TCP_OFFLOAD
67 #include <netinet/tcp_offload.h>
68 #endif
69 #include <opencrypto/xform.h>
70 #include <vm/uma_dbg.h>
71 #include <vm/vm.h>
72 #include <vm/vm_pageout.h>
73 #include <vm/vm_page.h>
74
75 struct ktls_wq {
76         struct mtx      mtx;
77         STAILQ_HEAD(, mbuf_ext_pgs) head;
78         bool            running;
79 } __aligned(CACHE_LINE_SIZE);
80
81 static struct ktls_wq *ktls_wq;
82 static struct proc *ktls_proc;
83 LIST_HEAD(, ktls_crypto_backend) ktls_backends;
84 static struct rmlock ktls_backends_lock;
85 static uma_zone_t ktls_session_zone;
86 static uint16_t ktls_cpuid_lookup[MAXCPU];
87
88 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW, 0,
89     "Kernel TLS offload");
90 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW, 0,
91     "Kernel TLS offload stats");
92
93 static int ktls_allow_unload;
94 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, allow_unload, CTLFLAG_RDTUN,
95     &ktls_allow_unload, 0, "Allow software crypto modules to unload");
96
97 #ifdef RSS
98 static int ktls_bind_threads = 1;
99 #else
100 static int ktls_bind_threads;
101 #endif
102 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
103     &ktls_bind_threads, 0,
104     "Bind crypto threads to cores or domains at boot");
105
106 static u_int ktls_maxlen = 16384;
107 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RWTUN,
108     &ktls_maxlen, 0, "Maximum TLS record size");
109
110 static int ktls_number_threads;
111 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
112     &ktls_number_threads, 0,
113     "Number of TLS threads in thread-pool");
114
115 static bool ktls_offload_enable;
116 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RW,
117     &ktls_offload_enable, 0,
118     "Enable support for kernel TLS offload");
119
120 static bool ktls_cbc_enable = true;
121 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RW,
122     &ktls_cbc_enable, 1,
123     "Enable Support of AES-CBC crypto for kernel TLS");
124
125 static counter_u64_t ktls_tasks_active;
126 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
127     &ktls_tasks_active, "Number of active tasks");
128
129 static counter_u64_t ktls_cnt_on;
130 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, so_inqueue, CTLFLAG_RD,
131     &ktls_cnt_on, "Number of TLS records in queue to tasks for SW crypto");
132
133 static counter_u64_t ktls_offload_total;
134 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
135     CTLFLAG_RD, &ktls_offload_total,
136     "Total successful TLS setups (parameters set)");
137
138 static counter_u64_t ktls_offload_enable_calls;
139 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
140     CTLFLAG_RD, &ktls_offload_enable_calls,
141     "Total number of TLS enable calls made");
142
143 static counter_u64_t ktls_offload_active;
144 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
145     &ktls_offload_active, "Total Active TLS sessions");
146
147 static counter_u64_t ktls_offload_failed_crypto;
148 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
149     &ktls_offload_failed_crypto, "Total TLS crypto failures");
150
151 static counter_u64_t ktls_switch_to_ifnet;
152 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
153     &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
154
155 static counter_u64_t ktls_switch_to_sw;
156 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
157     &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
158
159 static counter_u64_t ktls_switch_failed;
160 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
161     &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
162
163 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD, 0,
164     "Software TLS session stats");
165 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD, 0,
166     "Hardware (ifnet) TLS session stats");
167 #ifdef TCP_OFFLOAD
168 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD, 0,
169     "TOE TLS session stats");
170 #endif
171
172 static counter_u64_t ktls_sw_cbc;
173 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
174     "Active number of software TLS sessions using AES-CBC");
175
176 static counter_u64_t ktls_sw_gcm;
177 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
178     "Active number of software TLS sessions using AES-GCM");
179
180 static counter_u64_t ktls_ifnet_cbc;
181 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
182     &ktls_ifnet_cbc,
183     "Active number of ifnet TLS sessions using AES-CBC");
184
185 static counter_u64_t ktls_ifnet_gcm;
186 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
187     &ktls_ifnet_gcm,
188     "Active number of ifnet TLS sessions using AES-GCM");
189
190 static counter_u64_t ktls_ifnet_reset;
191 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
192     &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
193
194 static counter_u64_t ktls_ifnet_reset_dropped;
195 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
196     &ktls_ifnet_reset_dropped,
197     "TLS sessions dropped after failing to update ifnet send tag");
198
199 static counter_u64_t ktls_ifnet_reset_failed;
200 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
201     &ktls_ifnet_reset_failed,
202     "TLS sessions that failed to allocate a new ifnet send tag");
203
204 static int ktls_ifnet_permitted;
205 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
206     &ktls_ifnet_permitted, 1,
207     "Whether to permit hardware (ifnet) TLS sessions");
208
209 #ifdef TCP_OFFLOAD
210 static counter_u64_t ktls_toe_cbc;
211 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
212     &ktls_toe_cbc,
213     "Active number of TOE TLS sessions using AES-CBC");
214
215 static counter_u64_t ktls_toe_gcm;
216 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
217     &ktls_toe_gcm,
218     "Active number of TOE TLS sessions using AES-GCM");
219 #endif
220
221 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
222
223 static void ktls_cleanup(struct ktls_session *tls);
224 #if defined(INET) || defined(INET6)
225 static void ktls_reset_send_tag(void *context, int pending);
226 #endif
227 static void ktls_work_thread(void *ctx);
228
229 int
230 ktls_crypto_backend_register(struct ktls_crypto_backend *be)
231 {
232         struct ktls_crypto_backend *curr_be, *tmp;
233
234         if (be->api_version != KTLS_API_VERSION) {
235                 printf("KTLS: API version mismatch (%d vs %d) for %s\n",
236                     be->api_version, KTLS_API_VERSION,
237                     be->name);
238                 return (EINVAL);
239         }
240
241         rm_wlock(&ktls_backends_lock);
242         printf("KTLS: Registering crypto method %s with prio %d\n",
243                be->name, be->prio);
244         if (LIST_EMPTY(&ktls_backends)) {
245                 LIST_INSERT_HEAD(&ktls_backends, be, next);
246         } else {
247                 LIST_FOREACH_SAFE(curr_be, &ktls_backends, next, tmp) {
248                         if (curr_be->prio < be->prio) {
249                                 LIST_INSERT_BEFORE(curr_be, be, next);
250                                 break;
251                         }
252                         if (LIST_NEXT(curr_be, next) == NULL) {
253                                 LIST_INSERT_AFTER(curr_be, be, next);
254                                 break;
255                         }
256                 }
257         }
258         rm_wunlock(&ktls_backends_lock);
259         return (0);
260 }
261
262 int
263 ktls_crypto_backend_deregister(struct ktls_crypto_backend *be)
264 {
265         struct ktls_crypto_backend *tmp;
266
267         /*
268          * Don't error if the backend isn't registered.  This permits
269          * MOD_UNLOAD handlers to use this function unconditionally.
270          */
271         rm_wlock(&ktls_backends_lock);
272         LIST_FOREACH(tmp, &ktls_backends, next) {
273                 if (tmp == be)
274                         break;
275         }
276         if (tmp == NULL) {
277                 rm_wunlock(&ktls_backends_lock);
278                 return (0);
279         }
280
281         if (!ktls_allow_unload) {
282                 rm_wunlock(&ktls_backends_lock);
283                 printf(
284                     "KTLS: Deregistering crypto method %s is not supported\n",
285                     be->name);
286                 return (EBUSY);
287         }
288
289         if (be->use_count) {
290                 rm_wunlock(&ktls_backends_lock);
291                 return (EBUSY);
292         }
293
294         LIST_REMOVE(be, next);
295         rm_wunlock(&ktls_backends_lock);
296         return (0);
297 }
298
299 #if defined(INET) || defined(INET6)
300 static uint16_t
301 ktls_get_cpu(struct socket *so)
302 {
303         struct inpcb *inp;
304         uint16_t cpuid;
305
306         inp = sotoinpcb(so);
307 #ifdef RSS
308         cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
309         if (cpuid != NETISR_CPUID_NONE)
310                 return (cpuid);
311 #endif
312         /*
313          * Just use the flowid to shard connections in a repeatable
314          * fashion.  Note that some crypto backends rely on the
315          * serialization provided by having the same connection use
316          * the same queue.
317          */
318         cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
319         return (cpuid);
320 }
321 #endif
322
323 static void
324 ktls_init(void *dummy __unused)
325 {
326         struct thread *td;
327         struct pcpu *pc;
328         cpuset_t mask;
329         int error, i;
330
331         ktls_tasks_active = counter_u64_alloc(M_WAITOK);
332         ktls_cnt_on = counter_u64_alloc(M_WAITOK);
333         ktls_offload_total = counter_u64_alloc(M_WAITOK);
334         ktls_offload_enable_calls = counter_u64_alloc(M_WAITOK);
335         ktls_offload_active = counter_u64_alloc(M_WAITOK);
336         ktls_offload_failed_crypto = counter_u64_alloc(M_WAITOK);
337         ktls_switch_to_ifnet = counter_u64_alloc(M_WAITOK);
338         ktls_switch_to_sw = counter_u64_alloc(M_WAITOK);
339         ktls_switch_failed = counter_u64_alloc(M_WAITOK);
340         ktls_sw_cbc = counter_u64_alloc(M_WAITOK);
341         ktls_sw_gcm = counter_u64_alloc(M_WAITOK);
342         ktls_ifnet_cbc = counter_u64_alloc(M_WAITOK);
343         ktls_ifnet_gcm = counter_u64_alloc(M_WAITOK);
344         ktls_ifnet_reset = counter_u64_alloc(M_WAITOK);
345         ktls_ifnet_reset_dropped = counter_u64_alloc(M_WAITOK);
346         ktls_ifnet_reset_failed = counter_u64_alloc(M_WAITOK);
347 #ifdef TCP_OFFLOAD
348         ktls_toe_cbc = counter_u64_alloc(M_WAITOK);
349         ktls_toe_gcm = counter_u64_alloc(M_WAITOK);
350 #endif
351
352         rm_init(&ktls_backends_lock, "ktls backends");
353         LIST_INIT(&ktls_backends);
354
355         ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
356             M_WAITOK | M_ZERO);
357
358         ktls_session_zone = uma_zcreate("ktls_session",
359             sizeof(struct ktls_session),
360 #ifdef INVARIANTS
361             trash_ctor, trash_dtor, trash_init, trash_fini,
362 #else
363             NULL, NULL, NULL, NULL,
364 #endif
365             UMA_ALIGN_CACHE, 0);
366
367         /*
368          * Initialize the workqueues to run the TLS work.  We create a
369          * work queue for each CPU.
370          */
371         CPU_FOREACH(i) {
372                 STAILQ_INIT(&ktls_wq[i].head);
373                 mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
374                 error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
375                     &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
376                 if (error)
377                         panic("Can't add KTLS thread %d error %d", i, error);
378
379                 /*
380                  * Bind threads to cores.  If ktls_bind_threads is >
381                  * 1, then we bind to the NUMA domain.
382                  */
383                 if (ktls_bind_threads) {
384                         if (ktls_bind_threads > 1) {
385                                 pc = pcpu_find(i);
386                                 CPU_COPY(&cpuset_domain[pc->pc_domain], &mask);
387                         } else {
388                                 CPU_SETOF(i, &mask);
389                         }
390                         error = cpuset_setthread(td->td_tid, &mask);
391                         if (error)
392                                 panic(
393                             "Unable to bind KTLS thread for CPU %d error %d",
394                                      i, error);
395                 }
396                 ktls_cpuid_lookup[ktls_number_threads] = i;
397                 ktls_number_threads++;
398         }
399         printf("KTLS: Initialized %d threads\n", ktls_number_threads);
400 }
401 SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
402
403 #if defined(INET) || defined(INET6)
404 static int
405 ktls_create_session(struct socket *so, struct tls_enable *en,
406     struct ktls_session **tlsp)
407 {
408         struct ktls_session *tls;
409         int error;
410
411         /* Only TLS 1.0 - 1.2 are supported. */
412         if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
413                 return (EINVAL);
414         if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
415             en->tls_vminor > TLS_MINOR_VER_THREE)
416                 return (EINVAL);
417
418         if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
419                 return (EINVAL);
420         if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
421                 return (EINVAL);
422         if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
423                 return (EINVAL);
424
425         /* All supported algorithms require a cipher key. */
426         if (en->cipher_key_len == 0)
427                 return (EINVAL);
428
429         /* No flags are currently supported. */
430         if (en->flags != 0)
431                 return (EINVAL);
432
433         /* Common checks for supported algorithms. */
434         switch (en->cipher_algorithm) {
435         case CRYPTO_AES_NIST_GCM_16:
436                 /*
437                  * auth_algorithm isn't used, but permit GMAC values
438                  * for compatibility.
439                  */
440                 switch (en->auth_algorithm) {
441                 case 0:
442                 case CRYPTO_AES_128_NIST_GMAC:
443                 case CRYPTO_AES_192_NIST_GMAC:
444                 case CRYPTO_AES_256_NIST_GMAC:
445                         break;
446                 default:
447                         return (EINVAL);
448                 }
449                 if (en->auth_key_len != 0)
450                         return (EINVAL);
451                 if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
452                         en->iv_len != TLS_AEAD_GCM_LEN) ||
453                     (en->tls_vminor == TLS_MINOR_VER_THREE &&
454                         en->iv_len != TLS_1_3_GCM_IV_LEN))
455                         return (EINVAL);
456                 break;
457         case CRYPTO_AES_CBC:
458                 switch (en->auth_algorithm) {
459                 case CRYPTO_SHA1_HMAC:
460                         /*
461                          * TLS 1.0 requires an implicit IV.  TLS 1.1+
462                          * all use explicit IVs.
463                          */
464                         if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
465                                 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
466                                         return (EINVAL);
467                                 break;
468                         }
469
470                         /* FALLTHROUGH */
471                 case CRYPTO_SHA2_256_HMAC:
472                 case CRYPTO_SHA2_384_HMAC:
473                         /* Ignore any supplied IV. */
474                         en->iv_len = 0;
475                         break;
476                 default:
477                         return (EINVAL);
478                 }
479                 if (en->auth_key_len == 0)
480                         return (EINVAL);
481                 break;
482         default:
483                 return (EINVAL);
484         }
485
486         tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
487
488         counter_u64_add(ktls_offload_active, 1);
489
490         refcount_init(&tls->refcount, 1);
491         TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
492
493         tls->wq_index = ktls_get_cpu(so);
494
495         tls->params.cipher_algorithm = en->cipher_algorithm;
496         tls->params.auth_algorithm = en->auth_algorithm;
497         tls->params.tls_vmajor = en->tls_vmajor;
498         tls->params.tls_vminor = en->tls_vminor;
499         tls->params.flags = en->flags;
500         tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
501
502         /* Set the header and trailer lengths. */
503         tls->params.tls_hlen = sizeof(struct tls_record_layer);
504         switch (en->cipher_algorithm) {
505         case CRYPTO_AES_NIST_GCM_16:
506                 /*
507                  * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
508                  * nonce.  TLS 1.3 uses a 12 byte implicit IV.
509                  */
510                 if (en->tls_vminor < TLS_MINOR_VER_THREE)
511                         tls->params.tls_hlen += sizeof(uint64_t);
512                 tls->params.tls_tlen = AES_GMAC_HASH_LEN;
513
514                 /*
515                  * TLS 1.3 includes optional padding which we
516                  * do not support, and also puts the "real" record
517                  * type at the end of the encrypted data.
518                  */
519                 if (en->tls_vminor == TLS_MINOR_VER_THREE)
520                         tls->params.tls_tlen += sizeof(uint8_t);
521
522                 tls->params.tls_bs = 1;
523                 break;
524         case CRYPTO_AES_CBC:
525                 switch (en->auth_algorithm) {
526                 case CRYPTO_SHA1_HMAC:
527                         if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
528                                 /* Implicit IV, no nonce. */
529                         } else {
530                                 tls->params.tls_hlen += AES_BLOCK_LEN;
531                         }
532                         tls->params.tls_tlen = AES_BLOCK_LEN +
533                             SHA1_HASH_LEN;
534                         break;
535                 case CRYPTO_SHA2_256_HMAC:
536                         tls->params.tls_hlen += AES_BLOCK_LEN;
537                         tls->params.tls_tlen = AES_BLOCK_LEN +
538                             SHA2_256_HASH_LEN;
539                         break;
540                 case CRYPTO_SHA2_384_HMAC:
541                         tls->params.tls_hlen += AES_BLOCK_LEN;
542                         tls->params.tls_tlen = AES_BLOCK_LEN +
543                             SHA2_384_HASH_LEN;
544                         break;
545                 default:
546                         panic("invalid hmac");
547                 }
548                 tls->params.tls_bs = AES_BLOCK_LEN;
549                 break;
550         default:
551                 panic("invalid cipher");
552         }
553
554         KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
555             ("TLS header length too long: %d", tls->params.tls_hlen));
556         KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
557             ("TLS trailer length too long: %d", tls->params.tls_tlen));
558
559         if (en->auth_key_len != 0) {
560                 tls->params.auth_key_len = en->auth_key_len;
561                 tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
562                     M_WAITOK);
563                 error = copyin(en->auth_key, tls->params.auth_key,
564                     en->auth_key_len);
565                 if (error)
566                         goto out;
567         }
568
569         tls->params.cipher_key_len = en->cipher_key_len;
570         tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
571         error = copyin(en->cipher_key, tls->params.cipher_key,
572             en->cipher_key_len);
573         if (error)
574                 goto out;
575
576         /*
577          * This holds the implicit portion of the nonce for GCM and
578          * the initial implicit IV for TLS 1.0.  The explicit portions
579          * of the IV are generated in ktls_frame() and ktls_seq().
580          */
581         if (en->iv_len != 0) {
582                 tls->params.iv_len = en->iv_len;
583                 error = copyin(en->iv, tls->params.iv, en->iv_len);
584                 if (error)
585                         goto out;
586         }
587
588         *tlsp = tls;
589         return (0);
590
591 out:
592         ktls_cleanup(tls);
593         return (error);
594 }
595
596 static struct ktls_session *
597 ktls_clone_session(struct ktls_session *tls)
598 {
599         struct ktls_session *tls_new;
600
601         tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
602
603         counter_u64_add(ktls_offload_active, 1);
604
605         refcount_init(&tls_new->refcount, 1);
606
607         /* Copy fields from existing session. */
608         tls_new->params = tls->params;
609         tls_new->wq_index = tls->wq_index;
610
611         /* Deep copy keys. */
612         if (tls_new->params.auth_key != NULL) {
613                 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
614                     M_KTLS, M_WAITOK);
615                 memcpy(tls_new->params.auth_key, tls->params.auth_key,
616                     tls->params.auth_key_len);
617         }
618
619         tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
620             M_WAITOK);
621         memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
622             tls->params.cipher_key_len);
623
624         return (tls_new);
625 }
626 #endif
627
628 static void
629 ktls_cleanup(struct ktls_session *tls)
630 {
631
632         counter_u64_add(ktls_offload_active, -1);
633         switch (tls->mode) {
634         case TCP_TLS_MODE_SW:
635                 MPASS(tls->be != NULL);
636                 switch (tls->params.cipher_algorithm) {
637                 case CRYPTO_AES_CBC:
638                         counter_u64_add(ktls_sw_cbc, -1);
639                         break;
640                 case CRYPTO_AES_NIST_GCM_16:
641                         counter_u64_add(ktls_sw_gcm, -1);
642                         break;
643                 }
644                 tls->free(tls);
645                 break;
646         case TCP_TLS_MODE_IFNET:
647                 switch (tls->params.cipher_algorithm) {
648                 case CRYPTO_AES_CBC:
649                         counter_u64_add(ktls_ifnet_cbc, -1);
650                         break;
651                 case CRYPTO_AES_NIST_GCM_16:
652                         counter_u64_add(ktls_ifnet_gcm, -1);
653                         break;
654                 }
655                 m_snd_tag_rele(tls->snd_tag);
656                 break;
657 #ifdef TCP_OFFLOAD
658         case TCP_TLS_MODE_TOE:
659                 switch (tls->params.cipher_algorithm) {
660                 case CRYPTO_AES_CBC:
661                         counter_u64_add(ktls_toe_cbc, -1);
662                         break;
663                 case CRYPTO_AES_NIST_GCM_16:
664                         counter_u64_add(ktls_toe_gcm, -1);
665                         break;
666                 }
667                 break;
668 #endif
669         }
670         if (tls->params.auth_key != NULL) {
671                 explicit_bzero(tls->params.auth_key, tls->params.auth_key_len);
672                 free(tls->params.auth_key, M_KTLS);
673                 tls->params.auth_key = NULL;
674                 tls->params.auth_key_len = 0;
675         }
676         if (tls->params.cipher_key != NULL) {
677                 explicit_bzero(tls->params.cipher_key,
678                     tls->params.cipher_key_len);
679                 free(tls->params.cipher_key, M_KTLS);
680                 tls->params.cipher_key = NULL;
681                 tls->params.cipher_key_len = 0;
682         }
683         explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
684 }
685
686 #if defined(INET) || defined(INET6)
687
688 #ifdef TCP_OFFLOAD
689 static int
690 ktls_try_toe(struct socket *so, struct ktls_session *tls)
691 {
692         struct inpcb *inp;
693         struct tcpcb *tp;
694         int error;
695
696         inp = so->so_pcb;
697         INP_WLOCK(inp);
698         if (inp->inp_flags2 & INP_FREED) {
699                 INP_WUNLOCK(inp);
700                 return (ECONNRESET);
701         }
702         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
703                 INP_WUNLOCK(inp);
704                 return (ECONNRESET);
705         }
706         if (inp->inp_socket == NULL) {
707                 INP_WUNLOCK(inp);
708                 return (ECONNRESET);
709         }
710         tp = intotcpcb(inp);
711         if (tp->tod == NULL) {
712                 INP_WUNLOCK(inp);
713                 return (EOPNOTSUPP);
714         }
715
716         error = tcp_offload_alloc_tls_session(tp, tls);
717         INP_WUNLOCK(inp);
718         if (error == 0) {
719                 tls->mode = TCP_TLS_MODE_TOE;
720                 switch (tls->params.cipher_algorithm) {
721                 case CRYPTO_AES_CBC:
722                         counter_u64_add(ktls_toe_cbc, 1);
723                         break;
724                 case CRYPTO_AES_NIST_GCM_16:
725                         counter_u64_add(ktls_toe_gcm, 1);
726                         break;
727                 }
728         }
729         return (error);
730 }
731 #endif
732
733 /*
734  * Common code used when first enabling ifnet TLS on a connection or
735  * when allocating a new ifnet TLS session due to a routing change.
736  * This function allocates a new TLS send tag on whatever interface
737  * the connection is currently routed over.
738  */
739 static int
740 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
741     struct m_snd_tag **mstp)
742 {
743         union if_snd_tag_alloc_params params;
744         struct ifnet *ifp;
745         struct rtentry *rt;
746         struct tcpcb *tp;
747         int error;
748
749         INP_RLOCK(inp);
750         if (inp->inp_flags2 & INP_FREED) {
751                 INP_RUNLOCK(inp);
752                 return (ECONNRESET);
753         }
754         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
755                 INP_RUNLOCK(inp);
756                 return (ECONNRESET);
757         }
758         if (inp->inp_socket == NULL) {
759                 INP_RUNLOCK(inp);
760                 return (ECONNRESET);
761         }
762         tp = intotcpcb(inp);
763
764         /*
765          * Check administrative controls on ifnet TLS to determine if
766          * ifnet TLS should be denied.
767          *
768          * - Always permit 'force' requests.
769          * - ktls_ifnet_permitted == 0: always deny.
770          */
771         if (!force && ktls_ifnet_permitted == 0) {
772                 INP_RUNLOCK(inp);
773                 return (ENXIO);
774         }
775
776         /*
777          * XXX: Use the cached route in the inpcb to find the
778          * interface.  This should perhaps instead use
779          * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
780          * enabled after a connection has completed key negotiation in
781          * userland, the cached route will be present in practice.
782          */
783         rt = inp->inp_route.ro_rt;
784         if (rt == NULL || rt->rt_ifp == NULL) {
785                 INP_RUNLOCK(inp);
786                 return (ENXIO);
787         }
788         ifp = rt->rt_ifp;
789         if_ref(ifp);
790
791         params.hdr.type = IF_SND_TAG_TYPE_TLS;
792         params.hdr.flowid = inp->inp_flowid;
793         params.hdr.flowtype = inp->inp_flowtype;
794         params.tls.inp = inp;
795         params.tls.tls = tls;
796         INP_RUNLOCK(inp);
797
798         if (ifp->if_snd_tag_alloc == NULL) {
799                 error = EOPNOTSUPP;
800                 goto out;
801         }
802         if ((ifp->if_capenable & IFCAP_NOMAP) == 0) {   
803                 error = EOPNOTSUPP;
804                 goto out;
805         }
806         if (inp->inp_vflag & INP_IPV6) {
807                 if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
808                         error = EOPNOTSUPP;
809                         goto out;
810                 }
811         } else {
812                 if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
813                         error = EOPNOTSUPP;
814                         goto out;
815                 }
816         }
817         error = ifp->if_snd_tag_alloc(ifp, &params, mstp);
818 out:
819         if_rele(ifp);
820         return (error);
821 }
822
823 static int
824 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
825 {
826         struct m_snd_tag *mst;
827         int error;
828
829         error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
830         if (error == 0) {
831                 tls->mode = TCP_TLS_MODE_IFNET;
832                 tls->snd_tag = mst;
833                 switch (tls->params.cipher_algorithm) {
834                 case CRYPTO_AES_CBC:
835                         counter_u64_add(ktls_ifnet_cbc, 1);
836                         break;
837                 case CRYPTO_AES_NIST_GCM_16:
838                         counter_u64_add(ktls_ifnet_gcm, 1);
839                         break;
840                 }
841         }
842         return (error);
843 }
844
845 static int
846 ktls_try_sw(struct socket *so, struct ktls_session *tls)
847 {
848         struct rm_priotracker prio;
849         struct ktls_crypto_backend *be;
850
851         /*
852          * Choose the best software crypto backend.  Backends are
853          * stored in sorted priority order (larget value == most
854          * important at the head of the list), so this just stops on
855          * the first backend that claims the session by returning
856          * success.
857          */
858         if (ktls_allow_unload)
859                 rm_rlock(&ktls_backends_lock, &prio);
860         LIST_FOREACH(be, &ktls_backends, next) {
861                 if (be->try(so, tls) == 0)
862                         break;
863                 KASSERT(tls->cipher == NULL,
864                     ("ktls backend leaked a cipher pointer"));
865         }
866         if (be != NULL) {
867                 if (ktls_allow_unload)
868                         be->use_count++;
869                 tls->be = be;
870         }
871         if (ktls_allow_unload)
872                 rm_runlock(&ktls_backends_lock, &prio);
873         if (be == NULL)
874                 return (EOPNOTSUPP);
875         tls->mode = TCP_TLS_MODE_SW;
876         switch (tls->params.cipher_algorithm) {
877         case CRYPTO_AES_CBC:
878                 counter_u64_add(ktls_sw_cbc, 1);
879                 break;
880         case CRYPTO_AES_NIST_GCM_16:
881                 counter_u64_add(ktls_sw_gcm, 1);
882                 break;
883         }
884         return (0);
885 }
886
887 int
888 ktls_enable_tx(struct socket *so, struct tls_enable *en)
889 {
890         struct ktls_session *tls;
891         int error;
892
893         if (!ktls_offload_enable)
894                 return (ENOTSUP);
895
896         counter_u64_add(ktls_offload_enable_calls, 1);
897
898         /*
899          * This should always be true since only the TCP socket option
900          * invokes this function.
901          */
902         if (so->so_proto->pr_protocol != IPPROTO_TCP)
903                 return (EINVAL);
904
905         /*
906          * XXX: Don't overwrite existing sessions.  We should permit
907          * this to support rekeying in the future.
908          */
909         if (so->so_snd.sb_tls_info != NULL)
910                 return (EALREADY);
911
912         if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
913                 return (ENOTSUP);
914
915         /* TLS requires ext pgs */
916         if (mb_use_ext_pgs == 0)
917                 return (ENXIO);
918
919         error = ktls_create_session(so, en, &tls);
920         if (error)
921                 return (error);
922
923         /* Prefer TOE -> ifnet TLS -> software TLS. */
924 #ifdef TCP_OFFLOAD
925         error = ktls_try_toe(so, tls);
926         if (error)
927 #endif
928                 error = ktls_try_ifnet(so, tls, false);
929         if (error)
930                 error = ktls_try_sw(so, tls);
931
932         if (error) {
933                 ktls_cleanup(tls);
934                 return (error);
935         }
936
937         error = sblock(&so->so_snd, SBL_WAIT);
938         if (error) {
939                 ktls_cleanup(tls);
940                 return (error);
941         }
942
943         SOCKBUF_LOCK(&so->so_snd);
944         so->so_snd.sb_tls_info = tls;
945         if (tls->mode != TCP_TLS_MODE_SW)
946                 so->so_snd.sb_flags |= SB_TLS_IFNET;
947         SOCKBUF_UNLOCK(&so->so_snd);
948         sbunlock(&so->so_snd);
949
950         counter_u64_add(ktls_offload_total, 1);
951
952         return (0);
953 }
954
955 int
956 ktls_get_tx_mode(struct socket *so)
957 {
958         struct ktls_session *tls;
959         struct inpcb *inp;
960         int mode;
961
962         inp = so->so_pcb;
963         INP_WLOCK_ASSERT(inp);
964         SOCKBUF_LOCK(&so->so_snd);
965         tls = so->so_snd.sb_tls_info;
966         if (tls == NULL)
967                 mode = TCP_TLS_MODE_NONE;
968         else
969                 mode = tls->mode;
970         SOCKBUF_UNLOCK(&so->so_snd);
971         return (mode);
972 }
973
974 /*
975  * Switch between SW and ifnet TLS sessions as requested.
976  */
977 int
978 ktls_set_tx_mode(struct socket *so, int mode)
979 {
980         struct ktls_session *tls, *tls_new;
981         struct inpcb *inp;
982         int error;
983
984         switch (mode) {
985         case TCP_TLS_MODE_SW:
986         case TCP_TLS_MODE_IFNET:
987                 break;
988         default:
989                 return (EINVAL);
990         }
991
992         inp = so->so_pcb;
993         INP_WLOCK_ASSERT(inp);
994         SOCKBUF_LOCK(&so->so_snd);
995         tls = so->so_snd.sb_tls_info;
996         if (tls == NULL) {
997                 SOCKBUF_UNLOCK(&so->so_snd);
998                 return (0);
999         }
1000
1001         if (tls->mode == mode) {
1002                 SOCKBUF_UNLOCK(&so->so_snd);
1003                 return (0);
1004         }
1005
1006         tls = ktls_hold(tls);
1007         SOCKBUF_UNLOCK(&so->so_snd);
1008         INP_WUNLOCK(inp);
1009
1010         tls_new = ktls_clone_session(tls);
1011
1012         if (mode == TCP_TLS_MODE_IFNET)
1013                 error = ktls_try_ifnet(so, tls_new, true);
1014         else
1015                 error = ktls_try_sw(so, tls_new);
1016         if (error) {
1017                 counter_u64_add(ktls_switch_failed, 1);
1018                 ktls_free(tls_new);
1019                 ktls_free(tls);
1020                 INP_WLOCK(inp);
1021                 return (error);
1022         }
1023
1024         error = sblock(&so->so_snd, SBL_WAIT);
1025         if (error) {
1026                 counter_u64_add(ktls_switch_failed, 1);
1027                 ktls_free(tls_new);
1028                 ktls_free(tls);
1029                 INP_WLOCK(inp);
1030                 return (error);
1031         }
1032
1033         /*
1034          * If we raced with another session change, keep the existing
1035          * session.
1036          */
1037         if (tls != so->so_snd.sb_tls_info) {
1038                 counter_u64_add(ktls_switch_failed, 1);
1039                 sbunlock(&so->so_snd);
1040                 ktls_free(tls_new);
1041                 ktls_free(tls);
1042                 INP_WLOCK(inp);
1043                 return (EBUSY);
1044         }
1045
1046         SOCKBUF_LOCK(&so->so_snd);
1047         so->so_snd.sb_tls_info = tls_new;
1048         if (tls_new->mode != TCP_TLS_MODE_SW)
1049                 so->so_snd.sb_flags |= SB_TLS_IFNET;
1050         SOCKBUF_UNLOCK(&so->so_snd);
1051         sbunlock(&so->so_snd);
1052
1053         /*
1054          * Drop two references on 'tls'.  The first is for the
1055          * ktls_hold() above.  The second drops the reference from the
1056          * socket buffer.
1057          */
1058         KASSERT(tls->refcount >= 2, ("too few references on old session"));
1059         ktls_free(tls);
1060         ktls_free(tls);
1061
1062         if (mode == TCP_TLS_MODE_IFNET)
1063                 counter_u64_add(ktls_switch_to_ifnet, 1);
1064         else
1065                 counter_u64_add(ktls_switch_to_sw, 1);
1066
1067         INP_WLOCK(inp);
1068         return (0);
1069 }
1070
1071 /*
1072  * Try to allocate a new TLS send tag.  This task is scheduled when
1073  * ip_output detects a route change while trying to transmit a packet
1074  * holding a TLS record.  If a new tag is allocated, replace the tag
1075  * in the TLS session.  Subsequent packets on the connection will use
1076  * the new tag.  If a new tag cannot be allocated, drop the
1077  * connection.
1078  */
1079 static void
1080 ktls_reset_send_tag(void *context, int pending)
1081 {
1082         struct epoch_tracker et;
1083         struct ktls_session *tls;
1084         struct m_snd_tag *old, *new;
1085         struct inpcb *inp;
1086         struct tcpcb *tp;
1087         int error;
1088
1089         MPASS(pending == 1);
1090
1091         tls = context;
1092         inp = tls->inp;
1093
1094         /*
1095          * Free the old tag first before allocating a new one.
1096          * ip[6]_output_send() will treat a NULL send tag the same as
1097          * an ifp mismatch and drop packets until a new tag is
1098          * allocated.
1099          *
1100          * Write-lock the INP when changing tls->snd_tag since
1101          * ip[6]_output_send() holds a read-lock when reading the
1102          * pointer.
1103          */
1104         INP_WLOCK(inp);
1105         old = tls->snd_tag;
1106         tls->snd_tag = NULL;
1107         INP_WUNLOCK(inp);
1108         if (old != NULL)
1109                 m_snd_tag_rele(old);
1110
1111         error = ktls_alloc_snd_tag(inp, tls, true, &new);
1112
1113         if (error == 0) {
1114                 INP_WLOCK(inp);
1115                 tls->snd_tag = new;
1116                 mtx_pool_lock(mtxpool_sleep, tls);
1117                 tls->reset_pending = false;
1118                 mtx_pool_unlock(mtxpool_sleep, tls);
1119                 if (!in_pcbrele_wlocked(inp))
1120                         INP_WUNLOCK(inp);
1121
1122                 counter_u64_add(ktls_ifnet_reset, 1);
1123
1124                 /*
1125                  * XXX: Should we kick tcp_output explicitly now that
1126                  * the send tag is fixed or just rely on timers?
1127                  */
1128         } else {
1129                 INP_INFO_RLOCK_ET(&V_tcbinfo, et);
1130                 INP_WLOCK(inp);
1131                 if (!in_pcbrele_wlocked(inp)) {
1132                         if (!(inp->inp_flags & INP_TIMEWAIT) &&
1133                             !(inp->inp_flags & INP_DROPPED)) {
1134                                 tp = intotcpcb(inp);
1135                                 tp = tcp_drop(tp, ECONNABORTED);
1136                                 if (tp != NULL)
1137                                         INP_WUNLOCK(inp);
1138                                 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1139                         } else
1140                                 INP_WUNLOCK(inp);
1141                 }
1142                 INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
1143
1144                 counter_u64_add(ktls_ifnet_reset_failed, 1);
1145
1146                 /*
1147                  * Leave reset_pending true to avoid future tasks while
1148                  * the socket goes away.
1149                  */
1150         }
1151
1152         ktls_free(tls);
1153 }
1154
1155 int
1156 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1157 {
1158
1159         if (inp == NULL)
1160                 return (ENOBUFS);
1161
1162         INP_LOCK_ASSERT(inp);
1163
1164         /*
1165          * See if we should schedule a task to update the send tag for
1166          * this session.
1167          */
1168         mtx_pool_lock(mtxpool_sleep, tls);
1169         if (!tls->reset_pending) {
1170                 (void) ktls_hold(tls);
1171                 in_pcbref(inp);
1172                 tls->inp = inp;
1173                 tls->reset_pending = true;
1174                 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1175         }
1176         mtx_pool_unlock(mtxpool_sleep, tls);
1177         return (ENOBUFS);
1178 }
1179 #endif
1180
1181 void
1182 ktls_destroy(struct ktls_session *tls)
1183 {
1184         struct rm_priotracker prio;
1185
1186         ktls_cleanup(tls);
1187         if (tls->be != NULL && ktls_allow_unload) {
1188                 rm_rlock(&ktls_backends_lock, &prio);
1189                 tls->be->use_count--;
1190                 rm_runlock(&ktls_backends_lock, &prio);
1191         }
1192         uma_zfree(ktls_session_zone, tls);
1193 }
1194
1195 void
1196 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1197 {
1198         struct mbuf_ext_pgs *pgs;
1199         struct tls_record_layer *tlshdr;
1200         uint64_t seqno;
1201
1202         for (; m != NULL; m = m->m_next) {
1203                 KASSERT((m->m_flags & M_NOMAP) != 0,
1204                     ("ktls_seq: mapped mbuf %p", m));
1205
1206                 pgs = m->m_ext.ext_pgs;
1207                 pgs->seqno = sb->sb_tls_seqno;
1208
1209                 /*
1210                  * Store the sequence number in the TLS header as the
1211                  * explicit part of the IV for GCM.
1212                  */
1213                 if (pgs->tls->params.cipher_algorithm ==
1214                     CRYPTO_AES_NIST_GCM_16) {
1215                         tlshdr = (void *)pgs->hdr;
1216                         seqno = htobe64(pgs->seqno);
1217                         memcpy(tlshdr + 1, &seqno, sizeof(seqno));
1218                 }
1219                 sb->sb_tls_seqno++;
1220         }
1221 }
1222
1223 /*
1224  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
1225  * mbuf in the chain must be an unmapped mbuf.  The payload of the
1226  * mbuf must be populated with the payload of each TLS record.
1227  *
1228  * The record_type argument specifies the TLS record type used when
1229  * populating the TLS header.
1230  *
1231  * The enq_count argument on return is set to the number of pages of
1232  * payload data for this entire chain that need to be encrypted via SW
1233  * encryption.  The returned value should be passed to ktls_enqueue
1234  * when scheduling encryption of this chain of mbufs.
1235  */
1236 int
1237 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1238     uint8_t record_type)
1239 {
1240         struct tls_record_layer *tlshdr;
1241         struct mbuf *m;
1242         struct mbuf_ext_pgs *pgs;
1243         uint16_t tls_len;
1244         int maxlen;
1245
1246         maxlen = tls->params.max_frame_len;
1247         *enq_cnt = 0;
1248         for (m = top; m != NULL; m = m->m_next) {
1249                 /*
1250                  * All mbufs in the chain should be non-empty TLS
1251                  * records whose payload does not exceed the maximum
1252                  * frame length.
1253                  */
1254                 if (m->m_len > maxlen || m->m_len == 0)
1255                         return (EINVAL);
1256                 tls_len = m->m_len;
1257
1258                 /*
1259                  * TLS frames require unmapped mbufs to store session
1260                  * info.
1261                  */
1262                 KASSERT((m->m_flags & M_NOMAP) != 0,
1263                     ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1264
1265                 pgs = m->m_ext.ext_pgs;
1266
1267                 /* Save a reference to the session. */
1268                 pgs->tls = ktls_hold(tls);
1269
1270                 pgs->hdr_len = tls->params.tls_hlen;
1271                 pgs->trail_len = tls->params.tls_tlen;
1272                 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1273                         int bs, delta;
1274
1275                         /*
1276                          * AES-CBC pads messages to a multiple of the
1277                          * block size.  Note that the padding is
1278                          * applied after the digest and the encryption
1279                          * is done on the "plaintext || mac || padding".
1280                          * At least one byte of padding is always
1281                          * present.
1282                          *
1283                          * Compute the final trailer length assuming
1284                          * at most one block of padding.
1285                          * tls->params.sb_tls_tlen is the maximum
1286                          * possible trailer length (padding + digest).
1287                          * delta holds the number of excess padding
1288                          * bytes if the maximum were used.  Those
1289                          * extra bytes are removed.
1290                          */
1291                         bs = tls->params.tls_bs;
1292                         delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1293                         pgs->trail_len -= delta;
1294                 }
1295                 m->m_len += pgs->hdr_len + pgs->trail_len;
1296
1297                 /* Populate the TLS header. */
1298                 tlshdr = (void *)pgs->hdr;
1299                 tlshdr->tls_vmajor = tls->params.tls_vmajor;
1300
1301                 /*
1302                  * TLS 1.3 masquarades as TLS 1.2 with a record type
1303                  * of TLS_RLTYPE_APP.
1304                  */
1305                 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1306                     tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1307                         tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1308                         tlshdr->tls_type = TLS_RLTYPE_APP;
1309                         /* save the real record type for later */
1310                         pgs->record_type = record_type;
1311                 } else {
1312                         tlshdr->tls_vminor = tls->params.tls_vminor;
1313                         tlshdr->tls_type = record_type;
1314                 }
1315                 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1316
1317                 /*
1318                  * For GCM, the sequence number is stored in the
1319                  * header by ktls_seq().  For CBC, a random nonce is
1320                  * inserted for TLS 1.1+.
1321                  */
1322                 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1323                     tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1324                         arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1325
1326                 /*
1327                  * When using SW encryption, mark the mbuf not ready.
1328                  * It will be marked ready via sbready() after the
1329                  * record has been encrypted.
1330                  *
1331                  * When using ifnet TLS, unencrypted TLS records are
1332                  * sent down the stack to the NIC.
1333                  */
1334                 if (tls->mode == TCP_TLS_MODE_SW) {
1335                         m->m_flags |= M_NOTREADY;
1336                         pgs->nrdy = pgs->npgs;
1337                         *enq_cnt += pgs->npgs;
1338                 }
1339         }
1340         return (0);
1341 }
1342
1343 void
1344 ktls_enqueue_to_free(struct mbuf_ext_pgs *pgs)
1345 {
1346         struct ktls_wq *wq;
1347         bool running;
1348
1349         /* Mark it for freeing. */
1350         pgs->mbuf = NULL;
1351         wq = &ktls_wq[pgs->tls->wq_index];
1352         mtx_lock(&wq->mtx);
1353         STAILQ_INSERT_TAIL(&wq->head, pgs, stailq);
1354         running = wq->running;
1355         mtx_unlock(&wq->mtx);
1356         if (!running)
1357                 wakeup(wq);
1358 }
1359
1360 void
1361 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1362 {
1363         struct mbuf_ext_pgs *pgs;
1364         struct ktls_wq *wq;
1365         bool running;
1366
1367         KASSERT(((m->m_flags & (M_NOMAP | M_NOTREADY)) ==
1368             (M_NOMAP | M_NOTREADY)),
1369             ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
1370         KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
1371
1372         pgs = m->m_ext.ext_pgs;
1373
1374         KASSERT(pgs->tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1375
1376         pgs->enc_cnt = page_count;
1377         pgs->mbuf = m;
1378
1379         /*
1380          * Save a pointer to the socket.  The caller is responsible
1381          * for taking an additional reference via soref().
1382          */
1383         pgs->so = so;
1384
1385         wq = &ktls_wq[pgs->tls->wq_index];
1386         mtx_lock(&wq->mtx);
1387         STAILQ_INSERT_TAIL(&wq->head, pgs, stailq);
1388         running = wq->running;
1389         mtx_unlock(&wq->mtx);
1390         if (!running)
1391                 wakeup(wq);
1392         counter_u64_add(ktls_cnt_on, 1);
1393 }
1394
1395 static __noinline void
1396 ktls_encrypt(struct mbuf_ext_pgs *pgs)
1397 {
1398         struct ktls_session *tls;
1399         struct socket *so;
1400         struct mbuf *m, *top;
1401         vm_paddr_t parray[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1402         struct iovec src_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1403         struct iovec dst_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1404         vm_page_t pg;
1405         int error, i, len, npages, off, total_pages;
1406         bool is_anon;
1407
1408         so = pgs->so;
1409         tls = pgs->tls;
1410         top = pgs->mbuf;
1411         KASSERT(tls != NULL, ("tls = NULL, top = %p, pgs = %p\n", top, pgs));
1412         KASSERT(so != NULL, ("so = NULL, top = %p, pgs = %p\n", top, pgs));
1413 #ifdef INVARIANTS
1414         pgs->so = NULL;
1415         pgs->mbuf = NULL;
1416 #endif
1417         total_pages = pgs->enc_cnt;
1418         npages = 0;
1419
1420         /*
1421          * Encrypt the TLS records in the chain of mbufs starting with
1422          * 'top'.  'total_pages' gives us a total count of pages and is
1423          * used to know when we have finished encrypting the TLS
1424          * records originally queued with 'top'.
1425          *
1426          * NB: These mbufs are queued in the socket buffer and
1427          * 'm_next' is traversing the mbufs in the socket buffer.  The
1428          * socket buffer lock is not held while traversing this chain.
1429          * Since the mbufs are all marked M_NOTREADY their 'm_next'
1430          * pointers should be stable.  However, the 'm_next' of the
1431          * last mbuf encrypted is not necessarily NULL.  It can point
1432          * to other mbufs appended while 'top' was on the TLS work
1433          * queue.
1434          *
1435          * Each mbuf holds an entire TLS record.
1436          */
1437         error = 0;
1438         for (m = top; npages != total_pages; m = m->m_next) {
1439                 pgs = m->m_ext.ext_pgs;
1440
1441                 KASSERT(pgs->tls == tls,
1442                     ("different TLS sessions in a single mbuf chain: %p vs %p",
1443                     tls, pgs->tls));
1444                 KASSERT((m->m_flags & (M_NOMAP | M_NOTREADY)) ==
1445                     (M_NOMAP | M_NOTREADY),
1446                     ("%p not unready & nomap mbuf (top = %p)\n", m, top));
1447                 KASSERT(npages + pgs->npgs <= total_pages,
1448                     ("page count mismatch: top %p, total_pages %d, m %p", top,
1449                     total_pages, m));
1450
1451                 /*
1452                  * Generate source and destination ivoecs to pass to
1453                  * the SW encryption backend.  For writable mbufs, the
1454                  * destination iovec is a copy of the source and
1455                  * encryption is done in place.  For file-backed mbufs
1456                  * (from sendfile), anonymous wired pages are
1457                  * allocated and assigned to the destination iovec.
1458                  */
1459                 is_anon = (pgs->flags & MBUF_PEXT_FLAG_ANON) != 0;
1460
1461                 off = pgs->first_pg_off;
1462                 for (i = 0; i < pgs->npgs; i++, off = 0) {
1463                         len = mbuf_ext_pg_len(pgs, i, off);
1464                         src_iov[i].iov_len = len;
1465                         src_iov[i].iov_base =
1466                             (char *)(void *)PHYS_TO_DMAP(pgs->pa[i]) + off;
1467
1468                         if (is_anon) {
1469                                 dst_iov[i].iov_base = src_iov[i].iov_base;
1470                                 dst_iov[i].iov_len = src_iov[i].iov_len;
1471                                 continue;
1472                         }
1473 retry_page:
1474                         pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
1475                             VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP | VM_ALLOC_WIRED);
1476                         if (pg == NULL) {
1477                                 vm_wait(NULL);
1478                                 goto retry_page;
1479                         }
1480                         parray[i] = VM_PAGE_TO_PHYS(pg);
1481                         dst_iov[i].iov_base =
1482                             (char *)(void *)PHYS_TO_DMAP(parray[i]) + off;
1483                         dst_iov[i].iov_len = len;
1484                 }
1485
1486                 npages += i;
1487
1488                 error = (*tls->sw_encrypt)(tls,
1489                     (const struct tls_record_layer *)pgs->hdr,
1490                     pgs->trail, src_iov, dst_iov, i, pgs->seqno,
1491                     pgs->record_type);
1492                 if (error) {
1493                         counter_u64_add(ktls_offload_failed_crypto, 1);
1494                         break;
1495                 }
1496
1497                 /*
1498                  * For file-backed mbufs, release the file-backed
1499                  * pages and replace them in the ext_pgs array with
1500                  * the anonymous wired pages allocated above.
1501                  */
1502                 if (!is_anon) {
1503                         /* Free the old pages. */
1504                         m->m_ext.ext_free(m);
1505
1506                         /* Replace them with the new pages. */
1507                         for (i = 0; i < pgs->npgs; i++)
1508                                 pgs->pa[i] = parray[i];
1509
1510                         /* Use the basic free routine. */
1511                         m->m_ext.ext_free = mb_free_mext_pgs;
1512
1513                         /* Pages are now writable. */
1514                         pgs->flags |= MBUF_PEXT_FLAG_ANON;
1515                 }
1516
1517                 /*
1518                  * Drop a reference to the session now that it is no
1519                  * longer needed.  Existing code depends on encrypted
1520                  * records having no associated session vs
1521                  * yet-to-be-encrypted records having an associated
1522                  * session.
1523                  */
1524                 pgs->tls = NULL;
1525                 ktls_free(tls);
1526         }
1527
1528         CURVNET_SET(so->so_vnet);
1529         if (error == 0) {
1530                 (void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
1531         } else {
1532                 so->so_proto->pr_usrreqs->pru_abort(so);
1533                 so->so_error = EIO;
1534                 mb_free_notready(top, total_pages);
1535         }
1536
1537         SOCK_LOCK(so);
1538         sorele(so);
1539         CURVNET_RESTORE();
1540 }
1541
1542 static void
1543 ktls_work_thread(void *ctx)
1544 {
1545         struct ktls_wq *wq = ctx;
1546         struct mbuf_ext_pgs *p, *n;
1547         struct ktls_session *tls;
1548         STAILQ_HEAD(, mbuf_ext_pgs) local_head;
1549
1550 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
1551         fpu_kern_thread(0);
1552 #endif
1553         for (;;) {
1554                 mtx_lock(&wq->mtx);
1555                 while (STAILQ_EMPTY(&wq->head)) {
1556                         wq->running = false;
1557                         mtx_sleep(wq, &wq->mtx, 0, "-", 0);
1558                         wq->running = true;
1559                 }
1560
1561                 STAILQ_INIT(&local_head);
1562                 STAILQ_CONCAT(&local_head, &wq->head);
1563                 mtx_unlock(&wq->mtx);
1564
1565                 STAILQ_FOREACH_SAFE(p, &local_head, stailq, n) {
1566                         if (p->mbuf != NULL) {
1567                                 ktls_encrypt(p);
1568                                 counter_u64_add(ktls_cnt_on, -1);
1569                         } else {
1570                                 tls = p->tls;
1571                                 ktls_free(tls);
1572                                 uma_zfree(zone_extpgs, p);
1573                         }
1574                 }
1575         }
1576 }