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