]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_ktls.c
MFV r362254: file 5.39.
[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                 explicit_bzero(tls->params.auth_key, tls->params.auth_key_len);
686                 free(tls->params.auth_key, M_KTLS);
687                 tls->params.auth_key = NULL;
688                 tls->params.auth_key_len = 0;
689         }
690         if (tls->params.cipher_key != NULL) {
691                 explicit_bzero(tls->params.cipher_key,
692                     tls->params.cipher_key_len);
693                 free(tls->params.cipher_key, M_KTLS);
694                 tls->params.cipher_key = NULL;
695                 tls->params.cipher_key_len = 0;
696         }
697         explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
698 }
699
700 #if defined(INET) || defined(INET6)
701
702 #ifdef TCP_OFFLOAD
703 static int
704 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
705 {
706         struct inpcb *inp;
707         struct tcpcb *tp;
708         int error;
709
710         inp = so->so_pcb;
711         INP_WLOCK(inp);
712         if (inp->inp_flags2 & INP_FREED) {
713                 INP_WUNLOCK(inp);
714                 return (ECONNRESET);
715         }
716         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
717                 INP_WUNLOCK(inp);
718                 return (ECONNRESET);
719         }
720         if (inp->inp_socket == NULL) {
721                 INP_WUNLOCK(inp);
722                 return (ECONNRESET);
723         }
724         tp = intotcpcb(inp);
725         if (tp->tod == NULL) {
726                 INP_WUNLOCK(inp);
727                 return (EOPNOTSUPP);
728         }
729
730         error = tcp_offload_alloc_tls_session(tp, tls, direction);
731         INP_WUNLOCK(inp);
732         if (error == 0) {
733                 tls->mode = TCP_TLS_MODE_TOE;
734                 switch (tls->params.cipher_algorithm) {
735                 case CRYPTO_AES_CBC:
736                         counter_u64_add(ktls_toe_cbc, 1);
737                         break;
738                 case CRYPTO_AES_NIST_GCM_16:
739                         counter_u64_add(ktls_toe_gcm, 1);
740                         break;
741                 }
742         }
743         return (error);
744 }
745 #endif
746
747 /*
748  * Common code used when first enabling ifnet TLS on a connection or
749  * when allocating a new ifnet TLS session due to a routing change.
750  * This function allocates a new TLS send tag on whatever interface
751  * the connection is currently routed over.
752  */
753 static int
754 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
755     struct m_snd_tag **mstp)
756 {
757         union if_snd_tag_alloc_params params;
758         struct ifnet *ifp;
759         struct nhop_object *nh;
760         struct tcpcb *tp;
761         int error;
762
763         INP_RLOCK(inp);
764         if (inp->inp_flags2 & INP_FREED) {
765                 INP_RUNLOCK(inp);
766                 return (ECONNRESET);
767         }
768         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
769                 INP_RUNLOCK(inp);
770                 return (ECONNRESET);
771         }
772         if (inp->inp_socket == NULL) {
773                 INP_RUNLOCK(inp);
774                 return (ECONNRESET);
775         }
776         tp = intotcpcb(inp);
777
778         /*
779          * Check administrative controls on ifnet TLS to determine if
780          * ifnet TLS should be denied.
781          *
782          * - Always permit 'force' requests.
783          * - ktls_ifnet_permitted == 0: always deny.
784          */
785         if (!force && ktls_ifnet_permitted == 0) {
786                 INP_RUNLOCK(inp);
787                 return (ENXIO);
788         }
789
790         /*
791          * XXX: Use the cached route in the inpcb to find the
792          * interface.  This should perhaps instead use
793          * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
794          * enabled after a connection has completed key negotiation in
795          * userland, the cached route will be present in practice.
796          */
797         nh = inp->inp_route.ro_nh;
798         if (nh == NULL) {
799                 INP_RUNLOCK(inp);
800                 return (ENXIO);
801         }
802         ifp = nh->nh_ifp;
803         if_ref(ifp);
804
805         params.hdr.type = IF_SND_TAG_TYPE_TLS;
806         params.hdr.flowid = inp->inp_flowid;
807         params.hdr.flowtype = inp->inp_flowtype;
808         params.hdr.numa_domain = inp->inp_numa_domain;
809         params.tls.inp = inp;
810         params.tls.tls = tls;
811         INP_RUNLOCK(inp);
812
813         if (ifp->if_snd_tag_alloc == NULL) {
814                 error = EOPNOTSUPP;
815                 goto out;
816         }
817         if ((ifp->if_capenable & IFCAP_NOMAP) == 0) {   
818                 error = EOPNOTSUPP;
819                 goto out;
820         }
821         if (inp->inp_vflag & INP_IPV6) {
822                 if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
823                         error = EOPNOTSUPP;
824                         goto out;
825                 }
826         } else {
827                 if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
828                         error = EOPNOTSUPP;
829                         goto out;
830                 }
831         }
832         error = ifp->if_snd_tag_alloc(ifp, &params, mstp);
833 out:
834         if_rele(ifp);
835         return (error);
836 }
837
838 static int
839 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
840 {
841         struct m_snd_tag *mst;
842         int error;
843
844         error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
845         if (error == 0) {
846                 tls->mode = TCP_TLS_MODE_IFNET;
847                 tls->snd_tag = mst;
848                 switch (tls->params.cipher_algorithm) {
849                 case CRYPTO_AES_CBC:
850                         counter_u64_add(ktls_ifnet_cbc, 1);
851                         break;
852                 case CRYPTO_AES_NIST_GCM_16:
853                         counter_u64_add(ktls_ifnet_gcm, 1);
854                         break;
855                 }
856         }
857         return (error);
858 }
859
860 static int
861 ktls_try_sw(struct socket *so, struct ktls_session *tls)
862 {
863         struct rm_priotracker prio;
864         struct ktls_crypto_backend *be;
865
866         /*
867          * Choose the best software crypto backend.  Backends are
868          * stored in sorted priority order (larget value == most
869          * important at the head of the list), so this just stops on
870          * the first backend that claims the session by returning
871          * success.
872          */
873         if (ktls_allow_unload)
874                 rm_rlock(&ktls_backends_lock, &prio);
875         LIST_FOREACH(be, &ktls_backends, next) {
876                 if (be->try(so, tls) == 0)
877                         break;
878                 KASSERT(tls->cipher == NULL,
879                     ("ktls backend leaked a cipher pointer"));
880         }
881         if (be != NULL) {
882                 if (ktls_allow_unload)
883                         be->use_count++;
884                 tls->be = be;
885         }
886         if (ktls_allow_unload)
887                 rm_runlock(&ktls_backends_lock, &prio);
888         if (be == NULL)
889                 return (EOPNOTSUPP);
890         tls->mode = TCP_TLS_MODE_SW;
891         switch (tls->params.cipher_algorithm) {
892         case CRYPTO_AES_CBC:
893                 counter_u64_add(ktls_sw_cbc, 1);
894                 break;
895         case CRYPTO_AES_NIST_GCM_16:
896                 counter_u64_add(ktls_sw_gcm, 1);
897                 break;
898         }
899         return (0);
900 }
901
902 int
903 ktls_enable_rx(struct socket *so, struct tls_enable *en)
904 {
905         struct ktls_session *tls;
906         int error;
907
908         if (!ktls_offload_enable)
909                 return (ENOTSUP);
910
911         counter_u64_add(ktls_offload_enable_calls, 1);
912
913         /*
914          * This should always be true since only the TCP socket option
915          * invokes this function.
916          */
917         if (so->so_proto->pr_protocol != IPPROTO_TCP)
918                 return (EINVAL);
919
920         /*
921          * XXX: Don't overwrite existing sessions.  We should permit
922          * this to support rekeying in the future.
923          */
924         if (so->so_rcv.sb_tls_info != NULL)
925                 return (EALREADY);
926
927         if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
928                 return (ENOTSUP);
929
930         error = ktls_create_session(so, en, &tls);
931         if (error)
932                 return (error);
933
934         /* TLS RX offload is only supported on TOE currently. */
935 #ifdef TCP_OFFLOAD
936         error = ktls_try_toe(so, tls, KTLS_RX);
937 #else
938         error = EOPNOTSUPP;
939 #endif
940
941         if (error) {
942                 ktls_cleanup(tls);
943                 return (error);
944         }
945
946         /* Mark the socket as using TLS offload. */
947         SOCKBUF_LOCK(&so->so_rcv);
948         so->so_rcv.sb_tls_info = tls;
949         SOCKBUF_UNLOCK(&so->so_rcv);
950
951         counter_u64_add(ktls_offload_total, 1);
952
953         return (0);
954 }
955
956 int
957 ktls_enable_tx(struct socket *so, struct tls_enable *en)
958 {
959         struct ktls_session *tls;
960         int error;
961
962         if (!ktls_offload_enable)
963                 return (ENOTSUP);
964
965         counter_u64_add(ktls_offload_enable_calls, 1);
966
967         /*
968          * This should always be true since only the TCP socket option
969          * invokes this function.
970          */
971         if (so->so_proto->pr_protocol != IPPROTO_TCP)
972                 return (EINVAL);
973
974         /*
975          * XXX: Don't overwrite existing sessions.  We should permit
976          * this to support rekeying in the future.
977          */
978         if (so->so_snd.sb_tls_info != NULL)
979                 return (EALREADY);
980
981         if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
982                 return (ENOTSUP);
983
984         /* TLS requires ext pgs */
985         if (mb_use_ext_pgs == 0)
986                 return (ENXIO);
987
988         error = ktls_create_session(so, en, &tls);
989         if (error)
990                 return (error);
991
992         /* Prefer TOE -> ifnet TLS -> software TLS. */
993 #ifdef TCP_OFFLOAD
994         error = ktls_try_toe(so, tls, KTLS_TX);
995         if (error)
996 #endif
997                 error = ktls_try_ifnet(so, tls, false);
998         if (error)
999                 error = ktls_try_sw(so, tls);
1000
1001         if (error) {
1002                 ktls_cleanup(tls);
1003                 return (error);
1004         }
1005
1006         error = sblock(&so->so_snd, SBL_WAIT);
1007         if (error) {
1008                 ktls_cleanup(tls);
1009                 return (error);
1010         }
1011
1012         SOCKBUF_LOCK(&so->so_snd);
1013         so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1014         so->so_snd.sb_tls_info = tls;
1015         if (tls->mode != TCP_TLS_MODE_SW)
1016                 so->so_snd.sb_flags |= SB_TLS_IFNET;
1017         SOCKBUF_UNLOCK(&so->so_snd);
1018         sbunlock(&so->so_snd);
1019
1020         counter_u64_add(ktls_offload_total, 1);
1021
1022         return (0);
1023 }
1024
1025 int
1026 ktls_get_rx_mode(struct socket *so)
1027 {
1028         struct ktls_session *tls;
1029         struct inpcb *inp;
1030         int mode;
1031
1032         inp = so->so_pcb;
1033         INP_WLOCK_ASSERT(inp);
1034         SOCKBUF_LOCK(&so->so_rcv);
1035         tls = so->so_rcv.sb_tls_info;
1036         if (tls == NULL)
1037                 mode = TCP_TLS_MODE_NONE;
1038         else
1039                 mode = tls->mode;
1040         SOCKBUF_UNLOCK(&so->so_rcv);
1041         return (mode);
1042 }
1043
1044 int
1045 ktls_get_tx_mode(struct socket *so)
1046 {
1047         struct ktls_session *tls;
1048         struct inpcb *inp;
1049         int mode;
1050
1051         inp = so->so_pcb;
1052         INP_WLOCK_ASSERT(inp);
1053         SOCKBUF_LOCK(&so->so_snd);
1054         tls = so->so_snd.sb_tls_info;
1055         if (tls == NULL)
1056                 mode = TCP_TLS_MODE_NONE;
1057         else
1058                 mode = tls->mode;
1059         SOCKBUF_UNLOCK(&so->so_snd);
1060         return (mode);
1061 }
1062
1063 /*
1064  * Switch between SW and ifnet TLS sessions as requested.
1065  */
1066 int
1067 ktls_set_tx_mode(struct socket *so, int mode)
1068 {
1069         struct ktls_session *tls, *tls_new;
1070         struct inpcb *inp;
1071         int error;
1072
1073         switch (mode) {
1074         case TCP_TLS_MODE_SW:
1075         case TCP_TLS_MODE_IFNET:
1076                 break;
1077         default:
1078                 return (EINVAL);
1079         }
1080
1081         inp = so->so_pcb;
1082         INP_WLOCK_ASSERT(inp);
1083         SOCKBUF_LOCK(&so->so_snd);
1084         tls = so->so_snd.sb_tls_info;
1085         if (tls == NULL) {
1086                 SOCKBUF_UNLOCK(&so->so_snd);
1087                 return (0);
1088         }
1089
1090         if (tls->mode == mode) {
1091                 SOCKBUF_UNLOCK(&so->so_snd);
1092                 return (0);
1093         }
1094
1095         tls = ktls_hold(tls);
1096         SOCKBUF_UNLOCK(&so->so_snd);
1097         INP_WUNLOCK(inp);
1098
1099         tls_new = ktls_clone_session(tls);
1100
1101         if (mode == TCP_TLS_MODE_IFNET)
1102                 error = ktls_try_ifnet(so, tls_new, true);
1103         else
1104                 error = ktls_try_sw(so, tls_new);
1105         if (error) {
1106                 counter_u64_add(ktls_switch_failed, 1);
1107                 ktls_free(tls_new);
1108                 ktls_free(tls);
1109                 INP_WLOCK(inp);
1110                 return (error);
1111         }
1112
1113         error = sblock(&so->so_snd, SBL_WAIT);
1114         if (error) {
1115                 counter_u64_add(ktls_switch_failed, 1);
1116                 ktls_free(tls_new);
1117                 ktls_free(tls);
1118                 INP_WLOCK(inp);
1119                 return (error);
1120         }
1121
1122         /*
1123          * If we raced with another session change, keep the existing
1124          * session.
1125          */
1126         if (tls != so->so_snd.sb_tls_info) {
1127                 counter_u64_add(ktls_switch_failed, 1);
1128                 sbunlock(&so->so_snd);
1129                 ktls_free(tls_new);
1130                 ktls_free(tls);
1131                 INP_WLOCK(inp);
1132                 return (EBUSY);
1133         }
1134
1135         SOCKBUF_LOCK(&so->so_snd);
1136         so->so_snd.sb_tls_info = tls_new;
1137         if (tls_new->mode != TCP_TLS_MODE_SW)
1138                 so->so_snd.sb_flags |= SB_TLS_IFNET;
1139         SOCKBUF_UNLOCK(&so->so_snd);
1140         sbunlock(&so->so_snd);
1141
1142         /*
1143          * Drop two references on 'tls'.  The first is for the
1144          * ktls_hold() above.  The second drops the reference from the
1145          * socket buffer.
1146          */
1147         KASSERT(tls->refcount >= 2, ("too few references on old session"));
1148         ktls_free(tls);
1149         ktls_free(tls);
1150
1151         if (mode == TCP_TLS_MODE_IFNET)
1152                 counter_u64_add(ktls_switch_to_ifnet, 1);
1153         else
1154                 counter_u64_add(ktls_switch_to_sw, 1);
1155
1156         INP_WLOCK(inp);
1157         return (0);
1158 }
1159
1160 /*
1161  * Try to allocate a new TLS send tag.  This task is scheduled when
1162  * ip_output detects a route change while trying to transmit a packet
1163  * holding a TLS record.  If a new tag is allocated, replace the tag
1164  * in the TLS session.  Subsequent packets on the connection will use
1165  * the new tag.  If a new tag cannot be allocated, drop the
1166  * connection.
1167  */
1168 static void
1169 ktls_reset_send_tag(void *context, int pending)
1170 {
1171         struct epoch_tracker et;
1172         struct ktls_session *tls;
1173         struct m_snd_tag *old, *new;
1174         struct inpcb *inp;
1175         struct tcpcb *tp;
1176         int error;
1177
1178         MPASS(pending == 1);
1179
1180         tls = context;
1181         inp = tls->inp;
1182
1183         /*
1184          * Free the old tag first before allocating a new one.
1185          * ip[6]_output_send() will treat a NULL send tag the same as
1186          * an ifp mismatch and drop packets until a new tag is
1187          * allocated.
1188          *
1189          * Write-lock the INP when changing tls->snd_tag since
1190          * ip[6]_output_send() holds a read-lock when reading the
1191          * pointer.
1192          */
1193         INP_WLOCK(inp);
1194         old = tls->snd_tag;
1195         tls->snd_tag = NULL;
1196         INP_WUNLOCK(inp);
1197         if (old != NULL)
1198                 m_snd_tag_rele(old);
1199
1200         error = ktls_alloc_snd_tag(inp, tls, true, &new);
1201
1202         if (error == 0) {
1203                 INP_WLOCK(inp);
1204                 tls->snd_tag = new;
1205                 mtx_pool_lock(mtxpool_sleep, tls);
1206                 tls->reset_pending = false;
1207                 mtx_pool_unlock(mtxpool_sleep, tls);
1208                 if (!in_pcbrele_wlocked(inp))
1209                         INP_WUNLOCK(inp);
1210
1211                 counter_u64_add(ktls_ifnet_reset, 1);
1212
1213                 /*
1214                  * XXX: Should we kick tcp_output explicitly now that
1215                  * the send tag is fixed or just rely on timers?
1216                  */
1217         } else {
1218                 NET_EPOCH_ENTER(et);
1219                 INP_WLOCK(inp);
1220                 if (!in_pcbrele_wlocked(inp)) {
1221                         if (!(inp->inp_flags & INP_TIMEWAIT) &&
1222                             !(inp->inp_flags & INP_DROPPED)) {
1223                                 tp = intotcpcb(inp);
1224                                 CURVNET_SET(tp->t_vnet);
1225                                 tp = tcp_drop(tp, ECONNABORTED);
1226                                 CURVNET_RESTORE();
1227                                 if (tp != NULL)
1228                                         INP_WUNLOCK(inp);
1229                                 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1230                         } else
1231                                 INP_WUNLOCK(inp);
1232                 }
1233                 NET_EPOCH_EXIT(et);
1234
1235                 counter_u64_add(ktls_ifnet_reset_failed, 1);
1236
1237                 /*
1238                  * Leave reset_pending true to avoid future tasks while
1239                  * the socket goes away.
1240                  */
1241         }
1242
1243         ktls_free(tls);
1244 }
1245
1246 int
1247 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1248 {
1249
1250         if (inp == NULL)
1251                 return (ENOBUFS);
1252
1253         INP_LOCK_ASSERT(inp);
1254
1255         /*
1256          * See if we should schedule a task to update the send tag for
1257          * this session.
1258          */
1259         mtx_pool_lock(mtxpool_sleep, tls);
1260         if (!tls->reset_pending) {
1261                 (void) ktls_hold(tls);
1262                 in_pcbref(inp);
1263                 tls->inp = inp;
1264                 tls->reset_pending = true;
1265                 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1266         }
1267         mtx_pool_unlock(mtxpool_sleep, tls);
1268         return (ENOBUFS);
1269 }
1270 #endif
1271
1272 void
1273 ktls_destroy(struct ktls_session *tls)
1274 {
1275         struct rm_priotracker prio;
1276
1277         ktls_cleanup(tls);
1278         if (tls->be != NULL && ktls_allow_unload) {
1279                 rm_rlock(&ktls_backends_lock, &prio);
1280                 tls->be->use_count--;
1281                 rm_runlock(&ktls_backends_lock, &prio);
1282         }
1283         uma_zfree(ktls_session_zone, tls);
1284 }
1285
1286 void
1287 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1288 {
1289
1290         for (; m != NULL; m = m->m_next) {
1291                 KASSERT((m->m_flags & M_EXTPG) != 0,
1292                     ("ktls_seq: mapped mbuf %p", m));
1293
1294                 m->m_epg_seqno = sb->sb_tls_seqno;
1295                 sb->sb_tls_seqno++;
1296         }
1297 }
1298
1299 /*
1300  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
1301  * mbuf in the chain must be an unmapped mbuf.  The payload of the
1302  * mbuf must be populated with the payload of each TLS record.
1303  *
1304  * The record_type argument specifies the TLS record type used when
1305  * populating the TLS header.
1306  *
1307  * The enq_count argument on return is set to the number of pages of
1308  * payload data for this entire chain that need to be encrypted via SW
1309  * encryption.  The returned value should be passed to ktls_enqueue
1310  * when scheduling encryption of this chain of mbufs.
1311  */
1312 void
1313 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1314     uint8_t record_type)
1315 {
1316         struct tls_record_layer *tlshdr;
1317         struct mbuf *m;
1318         uint64_t *noncep;
1319         uint16_t tls_len;
1320         int maxlen;
1321
1322         maxlen = tls->params.max_frame_len;
1323         *enq_cnt = 0;
1324         for (m = top; m != NULL; m = m->m_next) {
1325                 /*
1326                  * All mbufs in the chain should be non-empty TLS
1327                  * records whose payload does not exceed the maximum
1328                  * frame length.
1329                  */
1330                 KASSERT(m->m_len <= maxlen && m->m_len > 0,
1331                     ("ktls_frame: m %p len %d\n", m, m->m_len));
1332                 /*
1333                  * TLS frames require unmapped mbufs to store session
1334                  * info.
1335                  */
1336                 KASSERT((m->m_flags & M_EXTPG) != 0,
1337                     ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1338
1339                 tls_len = m->m_len;
1340
1341                 /* Save a reference to the session. */
1342                 m->m_epg_tls = ktls_hold(tls);
1343
1344                 m->m_epg_hdrlen = tls->params.tls_hlen;
1345                 m->m_epg_trllen = tls->params.tls_tlen;
1346                 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1347                         int bs, delta;
1348
1349                         /*
1350                          * AES-CBC pads messages to a multiple of the
1351                          * block size.  Note that the padding is
1352                          * applied after the digest and the encryption
1353                          * is done on the "plaintext || mac || padding".
1354                          * At least one byte of padding is always
1355                          * present.
1356                          *
1357                          * Compute the final trailer length assuming
1358                          * at most one block of padding.
1359                          * tls->params.sb_tls_tlen is the maximum
1360                          * possible trailer length (padding + digest).
1361                          * delta holds the number of excess padding
1362                          * bytes if the maximum were used.  Those
1363                          * extra bytes are removed.
1364                          */
1365                         bs = tls->params.tls_bs;
1366                         delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1367                         m->m_epg_trllen -= delta;
1368                 }
1369                 m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1370
1371                 /* Populate the TLS header. */
1372                 tlshdr = (void *)m->m_epg_hdr;
1373                 tlshdr->tls_vmajor = tls->params.tls_vmajor;
1374
1375                 /*
1376                  * TLS 1.3 masquarades as TLS 1.2 with a record type
1377                  * of TLS_RLTYPE_APP.
1378                  */
1379                 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1380                     tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1381                         tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1382                         tlshdr->tls_type = TLS_RLTYPE_APP;
1383                         /* save the real record type for later */
1384                         m->m_epg_record_type = record_type;
1385                         m->m_epg_trail[0] = record_type;
1386                 } else {
1387                         tlshdr->tls_vminor = tls->params.tls_vminor;
1388                         tlshdr->tls_type = record_type;
1389                 }
1390                 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1391
1392                 /*
1393                  * Store nonces / explicit IVs after the end of the
1394                  * TLS header.
1395                  *
1396                  * For GCM with TLS 1.2, an 8 byte nonce is copied
1397                  * from the end of the IV.  The nonce is then
1398                  * incremented for use by the next record.
1399                  *
1400                  * For CBC, a random nonce is inserted for TLS 1.1+.
1401                  */
1402                 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
1403                     tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
1404                         noncep = (uint64_t *)(tls->params.iv + 8);
1405                         be64enc(tlshdr + 1, *noncep);
1406                         (*noncep)++;
1407                 } else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1408                     tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1409                         arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1410
1411                 /*
1412                  * When using SW encryption, mark the mbuf not ready.
1413                  * It will be marked ready via sbready() after the
1414                  * record has been encrypted.
1415                  *
1416                  * When using ifnet TLS, unencrypted TLS records are
1417                  * sent down the stack to the NIC.
1418                  */
1419                 if (tls->mode == TCP_TLS_MODE_SW) {
1420                         m->m_flags |= M_NOTREADY;
1421                         m->m_epg_nrdy = m->m_epg_npgs;
1422                         *enq_cnt += m->m_epg_npgs;
1423                 }
1424         }
1425 }
1426
1427 void
1428 ktls_enqueue_to_free(struct mbuf *m)
1429 {
1430         struct ktls_wq *wq;
1431         bool running;
1432
1433         /* Mark it for freeing. */
1434         m->m_epg_flags |= EPG_FLAG_2FREE;
1435         wq = &ktls_wq[m->m_epg_tls->wq_index];
1436         mtx_lock(&wq->mtx);
1437         STAILQ_INSERT_TAIL(&wq->head, m, m_epg_stailq);
1438         running = wq->running;
1439         mtx_unlock(&wq->mtx);
1440         if (!running)
1441                 wakeup(wq);
1442 }
1443
1444 void
1445 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1446 {
1447         struct ktls_wq *wq;
1448         bool running;
1449
1450         KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
1451             (M_EXTPG | M_NOTREADY)),
1452             ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
1453         KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
1454
1455         KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1456
1457         m->m_epg_enc_cnt = page_count;
1458
1459         /*
1460          * Save a pointer to the socket.  The caller is responsible
1461          * for taking an additional reference via soref().
1462          */
1463         m->m_epg_so = so;
1464
1465         wq = &ktls_wq[m->m_epg_tls->wq_index];
1466         mtx_lock(&wq->mtx);
1467         STAILQ_INSERT_TAIL(&wq->head, m, m_epg_stailq);
1468         running = wq->running;
1469         mtx_unlock(&wq->mtx);
1470         if (!running)
1471                 wakeup(wq);
1472         counter_u64_add(ktls_cnt_on, 1);
1473 }
1474
1475 static __noinline void
1476 ktls_encrypt(struct mbuf *top)
1477 {
1478         struct ktls_session *tls;
1479         struct socket *so;
1480         struct mbuf *m;
1481         vm_paddr_t parray[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1482         struct iovec src_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1483         struct iovec dst_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
1484         vm_page_t pg;
1485         int error, i, len, npages, off, total_pages;
1486         bool is_anon;
1487
1488         so = top->m_epg_so;
1489         tls = top->m_epg_tls;
1490         KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
1491         KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
1492 #ifdef INVARIANTS
1493         top->m_epg_so = NULL;
1494 #endif
1495         total_pages = top->m_epg_enc_cnt;
1496         npages = 0;
1497
1498         /*
1499          * Encrypt the TLS records in the chain of mbufs starting with
1500          * 'top'.  'total_pages' gives us a total count of pages and is
1501          * used to know when we have finished encrypting the TLS
1502          * records originally queued with 'top'.
1503          *
1504          * NB: These mbufs are queued in the socket buffer and
1505          * 'm_next' is traversing the mbufs in the socket buffer.  The
1506          * socket buffer lock is not held while traversing this chain.
1507          * Since the mbufs are all marked M_NOTREADY their 'm_next'
1508          * pointers should be stable.  However, the 'm_next' of the
1509          * last mbuf encrypted is not necessarily NULL.  It can point
1510          * to other mbufs appended while 'top' was on the TLS work
1511          * queue.
1512          *
1513          * Each mbuf holds an entire TLS record.
1514          */
1515         error = 0;
1516         for (m = top; npages != total_pages; m = m->m_next) {
1517                 KASSERT(m->m_epg_tls == tls,
1518                     ("different TLS sessions in a single mbuf chain: %p vs %p",
1519                     tls, m->m_epg_tls));
1520                 KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
1521                     (M_EXTPG | M_NOTREADY),
1522                     ("%p not unready & nomap mbuf (top = %p)\n", m, top));
1523                 KASSERT(npages + m->m_epg_npgs <= total_pages,
1524                     ("page count mismatch: top %p, total_pages %d, m %p", top,
1525                     total_pages, m));
1526
1527                 /*
1528                  * Generate source and destination ivoecs to pass to
1529                  * the SW encryption backend.  For writable mbufs, the
1530                  * destination iovec is a copy of the source and
1531                  * encryption is done in place.  For file-backed mbufs
1532                  * (from sendfile), anonymous wired pages are
1533                  * allocated and assigned to the destination iovec.
1534                  */
1535                 is_anon = (m->m_epg_flags & EPG_FLAG_ANON) != 0;
1536
1537                 off = m->m_epg_1st_off;
1538                 for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
1539                         len = m_epg_pagelen(m, i, off);
1540                         src_iov[i].iov_len = len;
1541                         src_iov[i].iov_base =
1542                             (char *)(void *)PHYS_TO_DMAP(m->m_epg_pa[i]) +
1543                                 off;
1544
1545                         if (is_anon) {
1546                                 dst_iov[i].iov_base = src_iov[i].iov_base;
1547                                 dst_iov[i].iov_len = src_iov[i].iov_len;
1548                                 continue;
1549                         }
1550 retry_page:
1551                         pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
1552                             VM_ALLOC_NOOBJ | VM_ALLOC_NODUMP | VM_ALLOC_WIRED);
1553                         if (pg == NULL) {
1554                                 vm_wait(NULL);
1555                                 goto retry_page;
1556                         }
1557                         parray[i] = VM_PAGE_TO_PHYS(pg);
1558                         dst_iov[i].iov_base =
1559                             (char *)(void *)PHYS_TO_DMAP(parray[i]) + off;
1560                         dst_iov[i].iov_len = len;
1561                 }
1562
1563                 npages += i;
1564
1565                 error = (*tls->sw_encrypt)(tls,
1566                     (const struct tls_record_layer *)m->m_epg_hdr,
1567                     m->m_epg_trail, src_iov, dst_iov, i, m->m_epg_seqno,
1568                     m->m_epg_record_type);
1569                 if (error) {
1570                         counter_u64_add(ktls_offload_failed_crypto, 1);
1571                         break;
1572                 }
1573
1574                 /*
1575                  * For file-backed mbufs, release the file-backed
1576                  * pages and replace them in the ext_pgs array with
1577                  * the anonymous wired pages allocated above.
1578                  */
1579                 if (!is_anon) {
1580                         /* Free the old pages. */
1581                         m->m_ext.ext_free(m);
1582
1583                         /* Replace them with the new pages. */
1584                         for (i = 0; i < m->m_epg_npgs; i++)
1585                                 m->m_epg_pa[i] = parray[i];
1586
1587                         /* Use the basic free routine. */
1588                         m->m_ext.ext_free = mb_free_mext_pgs;
1589
1590                         /* Pages are now writable. */
1591                         m->m_epg_flags |= EPG_FLAG_ANON;
1592                 }
1593
1594                 /*
1595                  * Drop a reference to the session now that it is no
1596                  * longer needed.  Existing code depends on encrypted
1597                  * records having no associated session vs
1598                  * yet-to-be-encrypted records having an associated
1599                  * session.
1600                  */
1601                 m->m_epg_tls = NULL;
1602                 ktls_free(tls);
1603         }
1604
1605         CURVNET_SET(so->so_vnet);
1606         if (error == 0) {
1607                 (void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
1608         } else {
1609                 so->so_proto->pr_usrreqs->pru_abort(so);
1610                 so->so_error = EIO;
1611                 mb_free_notready(top, total_pages);
1612         }
1613
1614         SOCK_LOCK(so);
1615         sorele(so);
1616         CURVNET_RESTORE();
1617 }
1618
1619 static void
1620 ktls_work_thread(void *ctx)
1621 {
1622         struct ktls_wq *wq = ctx;
1623         struct mbuf *m, *n;
1624         STAILQ_HEAD(, mbuf) local_head;
1625
1626 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
1627         fpu_kern_thread(0);
1628 #endif
1629         for (;;) {
1630                 mtx_lock(&wq->mtx);
1631                 while (STAILQ_EMPTY(&wq->head)) {
1632                         wq->running = false;
1633                         mtx_sleep(wq, &wq->mtx, 0, "-", 0);
1634                         wq->running = true;
1635                 }
1636
1637                 STAILQ_INIT(&local_head);
1638                 STAILQ_CONCAT(&local_head, &wq->head);
1639                 mtx_unlock(&wq->mtx);
1640
1641                 STAILQ_FOREACH_SAFE(m, &local_head, m_epg_stailq, n) {
1642                         if (m->m_epg_flags & EPG_FLAG_2FREE) {
1643                                 ktls_free(m->m_epg_tls);
1644                                 uma_zfree(zone_mbuf, m);
1645                         } else {
1646                                 ktls_encrypt(m);
1647                                 counter_u64_add(ktls_cnt_on, -1);
1648                         }
1649                 }
1650         }
1651 }