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