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