]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_ktls.c
Add Chacha20-Poly1305 as a KTLS cipher suite.
[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/domainset.h>
38 #include <sys/ktls.h>
39 #include <sys/lock.h>
40 #include <sys/mbuf.h>
41 #include <sys/mutex.h>
42 #include <sys/rmlock.h>
43 #include <sys/proc.h>
44 #include <sys/protosw.h>
45 #include <sys/refcount.h>
46 #include <sys/smp.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/sysctl.h>
50 #include <sys/taskqueue.h>
51 #include <sys/kthread.h>
52 #include <sys/uio.h>
53 #include <sys/vmmeter.h>
54 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
55 #include <machine/pcb.h>
56 #endif
57 #include <machine/vmparam.h>
58 #include <net/if.h>
59 #include <net/if_var.h>
60 #ifdef RSS
61 #include <net/netisr.h>
62 #include <net/rss_config.h>
63 #endif
64 #include <net/route.h>
65 #include <net/route/nhop.h>
66 #if defined(INET) || defined(INET6)
67 #include <netinet/in.h>
68 #include <netinet/in_pcb.h>
69 #endif
70 #include <netinet/tcp_var.h>
71 #ifdef TCP_OFFLOAD
72 #include <netinet/tcp_offload.h>
73 #endif
74 #include <opencrypto/xform.h>
75 #include <vm/uma_dbg.h>
76 #include <vm/vm.h>
77 #include <vm/vm_pageout.h>
78 #include <vm/vm_page.h>
79
80 struct ktls_wq {
81         struct mtx      mtx;
82         STAILQ_HEAD(, mbuf) m_head;
83         STAILQ_HEAD(, socket) so_head;
84         bool            running;
85 } __aligned(CACHE_LINE_SIZE);
86
87 struct ktls_domain_info {
88         int count;
89         int cpu[MAXCPU];
90 };
91
92 struct ktls_domain_info ktls_domains[MAXMEMDOM];
93 static struct ktls_wq *ktls_wq;
94 static struct proc *ktls_proc;
95 LIST_HEAD(, ktls_crypto_backend) ktls_backends;
96 static struct rmlock ktls_backends_lock;
97 static uma_zone_t ktls_session_zone;
98 static uint16_t ktls_cpuid_lookup[MAXCPU];
99
100 SYSCTL_NODE(_kern_ipc, OID_AUTO, tls, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
101     "Kernel TLS offload");
102 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
103     "Kernel TLS offload stats");
104
105 static int ktls_allow_unload;
106 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, allow_unload, CTLFLAG_RDTUN,
107     &ktls_allow_unload, 0, "Allow software crypto modules to unload");
108
109 #ifdef RSS
110 static int ktls_bind_threads = 1;
111 #else
112 static int ktls_bind_threads;
113 #endif
114 SYSCTL_INT(_kern_ipc_tls, OID_AUTO, bind_threads, CTLFLAG_RDTUN,
115     &ktls_bind_threads, 0,
116     "Bind crypto threads to cores (1) or cores and domains (2) at boot");
117
118 static u_int ktls_maxlen = 16384;
119 SYSCTL_UINT(_kern_ipc_tls, OID_AUTO, maxlen, CTLFLAG_RWTUN,
120     &ktls_maxlen, 0, "Maximum TLS record size");
121
122 static int ktls_number_threads;
123 SYSCTL_INT(_kern_ipc_tls_stats, OID_AUTO, threads, CTLFLAG_RD,
124     &ktls_number_threads, 0,
125     "Number of TLS threads in thread-pool");
126
127 static bool ktls_offload_enable;
128 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, enable, CTLFLAG_RWTUN,
129     &ktls_offload_enable, 0,
130     "Enable support for kernel TLS offload");
131
132 static bool ktls_cbc_enable = true;
133 SYSCTL_BOOL(_kern_ipc_tls, OID_AUTO, cbc_enable, CTLFLAG_RWTUN,
134     &ktls_cbc_enable, 1,
135     "Enable Support of AES-CBC crypto for kernel TLS");
136
137 static COUNTER_U64_DEFINE_EARLY(ktls_tasks_active);
138 SYSCTL_COUNTER_U64(_kern_ipc_tls, OID_AUTO, tasks_active, CTLFLAG_RD,
139     &ktls_tasks_active, "Number of active tasks");
140
141 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_tx_queued);
142 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_tx_inqueue, CTLFLAG_RD,
143     &ktls_cnt_tx_queued,
144     "Number of TLS records in queue to tasks for SW encryption");
145
146 static COUNTER_U64_DEFINE_EARLY(ktls_cnt_rx_queued);
147 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, sw_rx_inqueue, CTLFLAG_RD,
148     &ktls_cnt_rx_queued,
149     "Number of TLS sockets in queue to tasks for SW decryption");
150
151 static COUNTER_U64_DEFINE_EARLY(ktls_offload_total);
152 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, offload_total,
153     CTLFLAG_RD, &ktls_offload_total,
154     "Total successful TLS setups (parameters set)");
155
156 static COUNTER_U64_DEFINE_EARLY(ktls_offload_enable_calls);
157 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, enable_calls,
158     CTLFLAG_RD, &ktls_offload_enable_calls,
159     "Total number of TLS enable calls made");
160
161 static COUNTER_U64_DEFINE_EARLY(ktls_offload_active);
162 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, active, CTLFLAG_RD,
163     &ktls_offload_active, "Total Active TLS sessions");
164
165 static COUNTER_U64_DEFINE_EARLY(ktls_offload_corrupted_records);
166 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, corrupted_records, CTLFLAG_RD,
167     &ktls_offload_corrupted_records, "Total corrupted TLS records received");
168
169 static COUNTER_U64_DEFINE_EARLY(ktls_offload_failed_crypto);
170 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, failed_crypto, CTLFLAG_RD,
171     &ktls_offload_failed_crypto, "Total TLS crypto failures");
172
173 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_ifnet);
174 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_ifnet, CTLFLAG_RD,
175     &ktls_switch_to_ifnet, "TLS sessions switched from SW to ifnet");
176
177 static COUNTER_U64_DEFINE_EARLY(ktls_switch_to_sw);
178 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_to_sw, CTLFLAG_RD,
179     &ktls_switch_to_sw, "TLS sessions switched from ifnet to SW");
180
181 static COUNTER_U64_DEFINE_EARLY(ktls_switch_failed);
182 SYSCTL_COUNTER_U64(_kern_ipc_tls_stats, OID_AUTO, switch_failed, CTLFLAG_RD,
183     &ktls_switch_failed, "TLS sessions unable to switch between SW and ifnet");
184
185 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, sw, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
186     "Software TLS session stats");
187 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, ifnet, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
188     "Hardware (ifnet) TLS session stats");
189 #ifdef TCP_OFFLOAD
190 SYSCTL_NODE(_kern_ipc_tls, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
191     "TOE TLS session stats");
192 #endif
193
194 static COUNTER_U64_DEFINE_EARLY(ktls_sw_cbc);
195 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, cbc, CTLFLAG_RD, &ktls_sw_cbc,
196     "Active number of software TLS sessions using AES-CBC");
197
198 static COUNTER_U64_DEFINE_EARLY(ktls_sw_gcm);
199 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, gcm, CTLFLAG_RD, &ktls_sw_gcm,
200     "Active number of software TLS sessions using AES-GCM");
201
202 static COUNTER_U64_DEFINE_EARLY(ktls_sw_chacha20);
203 SYSCTL_COUNTER_U64(_kern_ipc_tls_sw, OID_AUTO, chacha20, CTLFLAG_RD,
204     &ktls_sw_chacha20,
205     "Active number of software TLS sessions using Chacha20-Poly1305");
206
207 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_cbc);
208 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, cbc, CTLFLAG_RD,
209     &ktls_ifnet_cbc,
210     "Active number of ifnet TLS sessions using AES-CBC");
211
212 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_gcm);
213 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, gcm, CTLFLAG_RD,
214     &ktls_ifnet_gcm,
215     "Active number of ifnet TLS sessions using AES-GCM");
216
217 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_chacha20);
218 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, chacha20, CTLFLAG_RD,
219     &ktls_ifnet_chacha20,
220     "Active number of ifnet TLS sessions using Chacha20-Poly1305");
221
222 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset);
223 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset, CTLFLAG_RD,
224     &ktls_ifnet_reset, "TLS sessions updated to a new ifnet send tag");
225
226 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_dropped);
227 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_dropped, CTLFLAG_RD,
228     &ktls_ifnet_reset_dropped,
229     "TLS sessions dropped after failing to update ifnet send tag");
230
231 static COUNTER_U64_DEFINE_EARLY(ktls_ifnet_reset_failed);
232 SYSCTL_COUNTER_U64(_kern_ipc_tls_ifnet, OID_AUTO, reset_failed, CTLFLAG_RD,
233     &ktls_ifnet_reset_failed,
234     "TLS sessions that failed to allocate a new ifnet send tag");
235
236 static int ktls_ifnet_permitted;
237 SYSCTL_UINT(_kern_ipc_tls_ifnet, OID_AUTO, permitted, CTLFLAG_RWTUN,
238     &ktls_ifnet_permitted, 1,
239     "Whether to permit hardware (ifnet) TLS sessions");
240
241 #ifdef TCP_OFFLOAD
242 static COUNTER_U64_DEFINE_EARLY(ktls_toe_cbc);
243 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, cbc, CTLFLAG_RD,
244     &ktls_toe_cbc,
245     "Active number of TOE TLS sessions using AES-CBC");
246
247 static COUNTER_U64_DEFINE_EARLY(ktls_toe_gcm);
248 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, gcm, CTLFLAG_RD,
249     &ktls_toe_gcm,
250     "Active number of TOE TLS sessions using AES-GCM");
251
252 static counter_u64_t ktls_toe_chacha20;
253 SYSCTL_COUNTER_U64(_kern_ipc_tls_toe, OID_AUTO, chacha20, CTLFLAG_RD,
254     &ktls_toe_chacha20,
255     "Active number of TOE TLS sessions using Chacha20-Poly1305");
256 #endif
257
258 static MALLOC_DEFINE(M_KTLS, "ktls", "Kernel TLS");
259
260 static void ktls_cleanup(struct ktls_session *tls);
261 #if defined(INET) || defined(INET6)
262 static void ktls_reset_send_tag(void *context, int pending);
263 #endif
264 static void ktls_work_thread(void *ctx);
265
266 int
267 ktls_crypto_backend_register(struct ktls_crypto_backend *be)
268 {
269         struct ktls_crypto_backend *curr_be, *tmp;
270
271         if (be->api_version != KTLS_API_VERSION) {
272                 printf("KTLS: API version mismatch (%d vs %d) for %s\n",
273                     be->api_version, KTLS_API_VERSION,
274                     be->name);
275                 return (EINVAL);
276         }
277
278         rm_wlock(&ktls_backends_lock);
279         printf("KTLS: Registering crypto method %s with prio %d\n",
280                be->name, be->prio);
281         if (LIST_EMPTY(&ktls_backends)) {
282                 LIST_INSERT_HEAD(&ktls_backends, be, next);
283         } else {
284                 LIST_FOREACH_SAFE(curr_be, &ktls_backends, next, tmp) {
285                         if (curr_be->prio < be->prio) {
286                                 LIST_INSERT_BEFORE(curr_be, be, next);
287                                 break;
288                         }
289                         if (LIST_NEXT(curr_be, next) == NULL) {
290                                 LIST_INSERT_AFTER(curr_be, be, next);
291                                 break;
292                         }
293                 }
294         }
295         rm_wunlock(&ktls_backends_lock);
296         return (0);
297 }
298
299 int
300 ktls_crypto_backend_deregister(struct ktls_crypto_backend *be)
301 {
302         struct ktls_crypto_backend *tmp;
303
304         /*
305          * Don't error if the backend isn't registered.  This permits
306          * MOD_UNLOAD handlers to use this function unconditionally.
307          */
308         rm_wlock(&ktls_backends_lock);
309         LIST_FOREACH(tmp, &ktls_backends, next) {
310                 if (tmp == be)
311                         break;
312         }
313         if (tmp == NULL) {
314                 rm_wunlock(&ktls_backends_lock);
315                 return (0);
316         }
317
318         if (!ktls_allow_unload) {
319                 rm_wunlock(&ktls_backends_lock);
320                 printf(
321                     "KTLS: Deregistering crypto method %s is not supported\n",
322                     be->name);
323                 return (EBUSY);
324         }
325
326         if (be->use_count) {
327                 rm_wunlock(&ktls_backends_lock);
328                 return (EBUSY);
329         }
330
331         LIST_REMOVE(be, next);
332         rm_wunlock(&ktls_backends_lock);
333         return (0);
334 }
335
336 #if defined(INET) || defined(INET6)
337 static u_int
338 ktls_get_cpu(struct socket *so)
339 {
340         struct inpcb *inp;
341 #ifdef NUMA
342         struct ktls_domain_info *di;
343 #endif
344         u_int cpuid;
345
346         inp = sotoinpcb(so);
347 #ifdef RSS
348         cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
349         if (cpuid != NETISR_CPUID_NONE)
350                 return (cpuid);
351 #endif
352         /*
353          * Just use the flowid to shard connections in a repeatable
354          * fashion.  Note that some crypto backends rely on the
355          * serialization provided by having the same connection use
356          * the same queue.
357          */
358 #ifdef NUMA
359         if (ktls_bind_threads > 1 && inp->inp_numa_domain != M_NODOM) {
360                 di = &ktls_domains[inp->inp_numa_domain];
361                 cpuid = di->cpu[inp->inp_flowid % di->count];
362         } else
363 #endif
364                 cpuid = ktls_cpuid_lookup[inp->inp_flowid % ktls_number_threads];
365         return (cpuid);
366 }
367 #endif
368
369 static void
370 ktls_init(void *dummy __unused)
371 {
372         struct thread *td;
373         struct pcpu *pc;
374         cpuset_t mask;
375         int count, domain, error, i;
376
377         rm_init(&ktls_backends_lock, "ktls backends");
378         LIST_INIT(&ktls_backends);
379
380         ktls_wq = malloc(sizeof(*ktls_wq) * (mp_maxid + 1), M_KTLS,
381             M_WAITOK | M_ZERO);
382
383         ktls_session_zone = uma_zcreate("ktls_session",
384             sizeof(struct ktls_session),
385             NULL, NULL, NULL, NULL,
386             UMA_ALIGN_CACHE, 0);
387
388         /*
389          * Initialize the workqueues to run the TLS work.  We create a
390          * work queue for each CPU.
391          */
392         CPU_FOREACH(i) {
393                 STAILQ_INIT(&ktls_wq[i].m_head);
394                 STAILQ_INIT(&ktls_wq[i].so_head);
395                 mtx_init(&ktls_wq[i].mtx, "ktls work queue", NULL, MTX_DEF);
396                 error = kproc_kthread_add(ktls_work_thread, &ktls_wq[i],
397                     &ktls_proc, &td, 0, 0, "KTLS", "thr_%d", i);
398                 if (error)
399                         panic("Can't add KTLS thread %d error %d", i, error);
400
401                 /*
402                  * Bind threads to cores.  If ktls_bind_threads is >
403                  * 1, then we bind to the NUMA domain.
404                  */
405                 if (ktls_bind_threads) {
406                         if (ktls_bind_threads > 1) {
407                                 pc = pcpu_find(i);
408                                 domain = pc->pc_domain;
409                                 CPU_COPY(&cpuset_domain[domain], &mask);
410                                 count = ktls_domains[domain].count;
411                                 ktls_domains[domain].cpu[count] = i;
412                                 ktls_domains[domain].count++;
413                         } else {
414                                 CPU_SETOF(i, &mask);
415                         }
416                         error = cpuset_setthread(td->td_tid, &mask);
417                         if (error)
418                                 panic(
419                             "Unable to bind KTLS thread for CPU %d error %d",
420                                      i, error);
421                 }
422                 ktls_cpuid_lookup[ktls_number_threads] = i;
423                 ktls_number_threads++;
424         }
425
426         /*
427          * If we somehow have an empty domain, fall back to choosing
428          * among all KTLS threads.
429          */
430         if (ktls_bind_threads > 1) {
431                 for (i = 0; i < vm_ndomains; i++) {
432                         if (ktls_domains[i].count == 0) {
433                                 ktls_bind_threads = 1;
434                                 break;
435                         }
436                 }
437         }
438
439         if (bootverbose)
440                 printf("KTLS: Initialized %d threads\n", ktls_number_threads);
441 }
442 SYSINIT(ktls, SI_SUB_SMP + 1, SI_ORDER_ANY, ktls_init, NULL);
443
444 #if defined(INET) || defined(INET6)
445 static int
446 ktls_create_session(struct socket *so, struct tls_enable *en,
447     struct ktls_session **tlsp)
448 {
449         struct ktls_session *tls;
450         int error;
451
452         /* Only TLS 1.0 - 1.3 are supported. */
453         if (en->tls_vmajor != TLS_MAJOR_VER_ONE)
454                 return (EINVAL);
455         if (en->tls_vminor < TLS_MINOR_VER_ZERO ||
456             en->tls_vminor > TLS_MINOR_VER_THREE)
457                 return (EINVAL);
458
459         if (en->auth_key_len < 0 || en->auth_key_len > TLS_MAX_PARAM_SIZE)
460                 return (EINVAL);
461         if (en->cipher_key_len < 0 || en->cipher_key_len > TLS_MAX_PARAM_SIZE)
462                 return (EINVAL);
463         if (en->iv_len < 0 || en->iv_len > sizeof(tls->params.iv))
464                 return (EINVAL);
465
466         /* All supported algorithms require a cipher key. */
467         if (en->cipher_key_len == 0)
468                 return (EINVAL);
469
470         /* No flags are currently supported. */
471         if (en->flags != 0)
472                 return (EINVAL);
473
474         /* Common checks for supported algorithms. */
475         switch (en->cipher_algorithm) {
476         case CRYPTO_AES_NIST_GCM_16:
477                 /*
478                  * auth_algorithm isn't used, but permit GMAC values
479                  * for compatibility.
480                  */
481                 switch (en->auth_algorithm) {
482                 case 0:
483 #ifdef COMPAT_FREEBSD12
484                 /* XXX: Really 13.0-current COMPAT. */
485                 case CRYPTO_AES_128_NIST_GMAC:
486                 case CRYPTO_AES_192_NIST_GMAC:
487                 case CRYPTO_AES_256_NIST_GMAC:
488 #endif
489                         break;
490                 default:
491                         return (EINVAL);
492                 }
493                 if (en->auth_key_len != 0)
494                         return (EINVAL);
495                 if ((en->tls_vminor == TLS_MINOR_VER_TWO &&
496                         en->iv_len != TLS_AEAD_GCM_LEN) ||
497                     (en->tls_vminor == TLS_MINOR_VER_THREE &&
498                         en->iv_len != TLS_1_3_GCM_IV_LEN))
499                         return (EINVAL);
500                 break;
501         case CRYPTO_AES_CBC:
502                 switch (en->auth_algorithm) {
503                 case CRYPTO_SHA1_HMAC:
504                         /*
505                          * TLS 1.0 requires an implicit IV.  TLS 1.1+
506                          * all use explicit IVs.
507                          */
508                         if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
509                                 if (en->iv_len != TLS_CBC_IMPLICIT_IV_LEN)
510                                         return (EINVAL);
511                                 break;
512                         }
513
514                         /* FALLTHROUGH */
515                 case CRYPTO_SHA2_256_HMAC:
516                 case CRYPTO_SHA2_384_HMAC:
517                         /* Ignore any supplied IV. */
518                         en->iv_len = 0;
519                         break;
520                 default:
521                         return (EINVAL);
522                 }
523                 if (en->auth_key_len == 0)
524                         return (EINVAL);
525                 break;
526         case CRYPTO_CHACHA20_POLY1305:
527                 if (en->auth_algorithm != 0 || en->auth_key_len != 0)
528                         return (EINVAL);
529                 if (en->tls_vminor != TLS_MINOR_VER_TWO &&
530                     en->tls_vminor != TLS_MINOR_VER_THREE)
531                         return (EINVAL);
532                 if (en->iv_len != TLS_CHACHA20_IV_LEN)
533                         return (EINVAL);
534                 break;
535         default:
536                 return (EINVAL);
537         }
538
539         tls = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
540
541         counter_u64_add(ktls_offload_active, 1);
542
543         refcount_init(&tls->refcount, 1);
544         TASK_INIT(&tls->reset_tag_task, 0, ktls_reset_send_tag, tls);
545
546         tls->wq_index = ktls_get_cpu(so);
547
548         tls->params.cipher_algorithm = en->cipher_algorithm;
549         tls->params.auth_algorithm = en->auth_algorithm;
550         tls->params.tls_vmajor = en->tls_vmajor;
551         tls->params.tls_vminor = en->tls_vminor;
552         tls->params.flags = en->flags;
553         tls->params.max_frame_len = min(TLS_MAX_MSG_SIZE_V10_2, ktls_maxlen);
554
555         /* Set the header and trailer lengths. */
556         tls->params.tls_hlen = sizeof(struct tls_record_layer);
557         switch (en->cipher_algorithm) {
558         case CRYPTO_AES_NIST_GCM_16:
559                 /*
560                  * TLS 1.2 uses a 4 byte implicit IV with an explicit 8 byte
561                  * nonce.  TLS 1.3 uses a 12 byte implicit IV.
562                  */
563                 if (en->tls_vminor < TLS_MINOR_VER_THREE)
564                         tls->params.tls_hlen += sizeof(uint64_t);
565                 tls->params.tls_tlen = AES_GMAC_HASH_LEN;
566                 tls->params.tls_bs = 1;
567                 break;
568         case CRYPTO_AES_CBC:
569                 switch (en->auth_algorithm) {
570                 case CRYPTO_SHA1_HMAC:
571                         if (en->tls_vminor == TLS_MINOR_VER_ZERO) {
572                                 /* Implicit IV, no nonce. */
573                         } else {
574                                 tls->params.tls_hlen += AES_BLOCK_LEN;
575                         }
576                         tls->params.tls_tlen = AES_BLOCK_LEN +
577                             SHA1_HASH_LEN;
578                         break;
579                 case CRYPTO_SHA2_256_HMAC:
580                         tls->params.tls_hlen += AES_BLOCK_LEN;
581                         tls->params.tls_tlen = AES_BLOCK_LEN +
582                             SHA2_256_HASH_LEN;
583                         break;
584                 case CRYPTO_SHA2_384_HMAC:
585                         tls->params.tls_hlen += AES_BLOCK_LEN;
586                         tls->params.tls_tlen = AES_BLOCK_LEN +
587                             SHA2_384_HASH_LEN;
588                         break;
589                 default:
590                         panic("invalid hmac");
591                 }
592                 tls->params.tls_bs = AES_BLOCK_LEN;
593                 break;
594         case CRYPTO_CHACHA20_POLY1305:
595                 /*
596                  * Chacha20 uses a 12 byte implicit IV.
597                  */
598                 tls->params.tls_tlen = POLY1305_HASH_LEN;
599                 tls->params.tls_bs = 1;
600                 break;
601         default:
602                 panic("invalid cipher");
603         }
604
605         /*
606          * TLS 1.3 includes optional padding which we do not support,
607          * and also puts the "real" record type at the end of the
608          * encrypted data.
609          */
610         if (en->tls_vminor == TLS_MINOR_VER_THREE)
611                 tls->params.tls_tlen += sizeof(uint8_t);
612
613         KASSERT(tls->params.tls_hlen <= MBUF_PEXT_HDR_LEN,
614             ("TLS header length too long: %d", tls->params.tls_hlen));
615         KASSERT(tls->params.tls_tlen <= MBUF_PEXT_TRAIL_LEN,
616             ("TLS trailer length too long: %d", tls->params.tls_tlen));
617
618         if (en->auth_key_len != 0) {
619                 tls->params.auth_key_len = en->auth_key_len;
620                 tls->params.auth_key = malloc(en->auth_key_len, M_KTLS,
621                     M_WAITOK);
622                 error = copyin(en->auth_key, tls->params.auth_key,
623                     en->auth_key_len);
624                 if (error)
625                         goto out;
626         }
627
628         tls->params.cipher_key_len = en->cipher_key_len;
629         tls->params.cipher_key = malloc(en->cipher_key_len, M_KTLS, M_WAITOK);
630         error = copyin(en->cipher_key, tls->params.cipher_key,
631             en->cipher_key_len);
632         if (error)
633                 goto out;
634
635         /*
636          * This holds the implicit portion of the nonce for AEAD
637          * ciphers and the initial implicit IV for TLS 1.0.  The
638          * explicit portions of the IV are generated in ktls_frame().
639          */
640         if (en->iv_len != 0) {
641                 tls->params.iv_len = en->iv_len;
642                 error = copyin(en->iv, tls->params.iv, en->iv_len);
643                 if (error)
644                         goto out;
645
646                 /*
647                  * For TLS 1.2 with GCM, generate an 8-byte nonce as a
648                  * counter to generate unique explicit IVs.
649                  *
650                  * Store this counter in the last 8 bytes of the IV
651                  * array so that it is 8-byte aligned.
652                  */
653                 if (en->cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
654                     en->tls_vminor == TLS_MINOR_VER_TWO)
655                         arc4rand(tls->params.iv + 8, sizeof(uint64_t), 0);
656         }
657
658         *tlsp = tls;
659         return (0);
660
661 out:
662         ktls_cleanup(tls);
663         return (error);
664 }
665
666 static struct ktls_session *
667 ktls_clone_session(struct ktls_session *tls)
668 {
669         struct ktls_session *tls_new;
670
671         tls_new = uma_zalloc(ktls_session_zone, M_WAITOK | M_ZERO);
672
673         counter_u64_add(ktls_offload_active, 1);
674
675         refcount_init(&tls_new->refcount, 1);
676         TASK_INIT(&tls_new->reset_tag_task, 0, ktls_reset_send_tag, tls_new);
677
678         /* Copy fields from existing session. */
679         tls_new->params = tls->params;
680         tls_new->wq_index = tls->wq_index;
681
682         /* Deep copy keys. */
683         if (tls_new->params.auth_key != NULL) {
684                 tls_new->params.auth_key = malloc(tls->params.auth_key_len,
685                     M_KTLS, M_WAITOK);
686                 memcpy(tls_new->params.auth_key, tls->params.auth_key,
687                     tls->params.auth_key_len);
688         }
689
690         tls_new->params.cipher_key = malloc(tls->params.cipher_key_len, M_KTLS,
691             M_WAITOK);
692         memcpy(tls_new->params.cipher_key, tls->params.cipher_key,
693             tls->params.cipher_key_len);
694
695         return (tls_new);
696 }
697 #endif
698
699 static void
700 ktls_cleanup(struct ktls_session *tls)
701 {
702
703         counter_u64_add(ktls_offload_active, -1);
704         switch (tls->mode) {
705         case TCP_TLS_MODE_SW:
706                 MPASS(tls->be != NULL);
707                 switch (tls->params.cipher_algorithm) {
708                 case CRYPTO_AES_CBC:
709                         counter_u64_add(ktls_sw_cbc, -1);
710                         break;
711                 case CRYPTO_AES_NIST_GCM_16:
712                         counter_u64_add(ktls_sw_gcm, -1);
713                         break;
714                 case CRYPTO_CHACHA20_POLY1305:
715                         counter_u64_add(ktls_sw_chacha20, -1);
716                         break;
717                 }
718                 tls->free(tls);
719                 break;
720         case TCP_TLS_MODE_IFNET:
721                 switch (tls->params.cipher_algorithm) {
722                 case CRYPTO_AES_CBC:
723                         counter_u64_add(ktls_ifnet_cbc, -1);
724                         break;
725                 case CRYPTO_AES_NIST_GCM_16:
726                         counter_u64_add(ktls_ifnet_gcm, -1);
727                         break;
728                 case CRYPTO_CHACHA20_POLY1305:
729                         counter_u64_add(ktls_ifnet_chacha20, -1);
730                         break;
731                 }
732                 if (tls->snd_tag != NULL)
733                         m_snd_tag_rele(tls->snd_tag);
734                 break;
735 #ifdef TCP_OFFLOAD
736         case TCP_TLS_MODE_TOE:
737                 switch (tls->params.cipher_algorithm) {
738                 case CRYPTO_AES_CBC:
739                         counter_u64_add(ktls_toe_cbc, -1);
740                         break;
741                 case CRYPTO_AES_NIST_GCM_16:
742                         counter_u64_add(ktls_toe_gcm, -1);
743                         break;
744                 case CRYPTO_CHACHA20_POLY1305:
745                         counter_u64_add(ktls_toe_chacha20, -1);
746                         break;
747                 }
748                 break;
749 #endif
750         }
751         if (tls->params.auth_key != NULL) {
752                 zfree(tls->params.auth_key, M_KTLS);
753                 tls->params.auth_key = NULL;
754                 tls->params.auth_key_len = 0;
755         }
756         if (tls->params.cipher_key != NULL) {
757                 zfree(tls->params.cipher_key, M_KTLS);
758                 tls->params.cipher_key = NULL;
759                 tls->params.cipher_key_len = 0;
760         }
761         explicit_bzero(tls->params.iv, sizeof(tls->params.iv));
762 }
763
764 #if defined(INET) || defined(INET6)
765
766 #ifdef TCP_OFFLOAD
767 static int
768 ktls_try_toe(struct socket *so, struct ktls_session *tls, int direction)
769 {
770         struct inpcb *inp;
771         struct tcpcb *tp;
772         int error;
773
774         inp = so->so_pcb;
775         INP_WLOCK(inp);
776         if (inp->inp_flags2 & INP_FREED) {
777                 INP_WUNLOCK(inp);
778                 return (ECONNRESET);
779         }
780         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
781                 INP_WUNLOCK(inp);
782                 return (ECONNRESET);
783         }
784         if (inp->inp_socket == NULL) {
785                 INP_WUNLOCK(inp);
786                 return (ECONNRESET);
787         }
788         tp = intotcpcb(inp);
789         if (!(tp->t_flags & TF_TOE)) {
790                 INP_WUNLOCK(inp);
791                 return (EOPNOTSUPP);
792         }
793
794         error = tcp_offload_alloc_tls_session(tp, tls, direction);
795         INP_WUNLOCK(inp);
796         if (error == 0) {
797                 tls->mode = TCP_TLS_MODE_TOE;
798                 switch (tls->params.cipher_algorithm) {
799                 case CRYPTO_AES_CBC:
800                         counter_u64_add(ktls_toe_cbc, 1);
801                         break;
802                 case CRYPTO_AES_NIST_GCM_16:
803                         counter_u64_add(ktls_toe_gcm, 1);
804                         break;
805                 case CRYPTO_CHACHA20_POLY1305:
806                         counter_u64_add(ktls_toe_chacha20, 1);
807                         break;
808                 }
809         }
810         return (error);
811 }
812 #endif
813
814 /*
815  * Common code used when first enabling ifnet TLS on a connection or
816  * when allocating a new ifnet TLS session due to a routing change.
817  * This function allocates a new TLS send tag on whatever interface
818  * the connection is currently routed over.
819  */
820 static int
821 ktls_alloc_snd_tag(struct inpcb *inp, struct ktls_session *tls, bool force,
822     struct m_snd_tag **mstp)
823 {
824         union if_snd_tag_alloc_params params;
825         struct ifnet *ifp;
826         struct nhop_object *nh;
827         struct tcpcb *tp;
828         int error;
829
830         INP_RLOCK(inp);
831         if (inp->inp_flags2 & INP_FREED) {
832                 INP_RUNLOCK(inp);
833                 return (ECONNRESET);
834         }
835         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
836                 INP_RUNLOCK(inp);
837                 return (ECONNRESET);
838         }
839         if (inp->inp_socket == NULL) {
840                 INP_RUNLOCK(inp);
841                 return (ECONNRESET);
842         }
843         tp = intotcpcb(inp);
844
845         /*
846          * Check administrative controls on ifnet TLS to determine if
847          * ifnet TLS should be denied.
848          *
849          * - Always permit 'force' requests.
850          * - ktls_ifnet_permitted == 0: always deny.
851          */
852         if (!force && ktls_ifnet_permitted == 0) {
853                 INP_RUNLOCK(inp);
854                 return (ENXIO);
855         }
856
857         /*
858          * XXX: Use the cached route in the inpcb to find the
859          * interface.  This should perhaps instead use
860          * rtalloc1_fib(dst, 0, 0, fibnum).  Since KTLS is only
861          * enabled after a connection has completed key negotiation in
862          * userland, the cached route will be present in practice.
863          */
864         nh = inp->inp_route.ro_nh;
865         if (nh == NULL) {
866                 INP_RUNLOCK(inp);
867                 return (ENXIO);
868         }
869         ifp = nh->nh_ifp;
870         if_ref(ifp);
871
872         /*
873          * Allocate a TLS + ratelimit tag if the connection has an
874          * existing pacing rate.
875          */
876         if (tp->t_pacing_rate != -1 &&
877             (ifp->if_capenable & IFCAP_TXTLS_RTLMT) != 0) {
878                 params.hdr.type = IF_SND_TAG_TYPE_TLS_RATE_LIMIT;
879                 params.tls_rate_limit.inp = inp;
880                 params.tls_rate_limit.tls = tls;
881                 params.tls_rate_limit.max_rate = tp->t_pacing_rate;
882         } else {
883                 params.hdr.type = IF_SND_TAG_TYPE_TLS;
884                 params.tls.inp = inp;
885                 params.tls.tls = tls;
886         }
887         params.hdr.flowid = inp->inp_flowid;
888         params.hdr.flowtype = inp->inp_flowtype;
889         params.hdr.numa_domain = inp->inp_numa_domain;
890         INP_RUNLOCK(inp);
891
892         if ((ifp->if_capenable & IFCAP_MEXTPG) == 0) {
893                 error = EOPNOTSUPP;
894                 goto out;
895         }
896         if (inp->inp_vflag & INP_IPV6) {
897                 if ((ifp->if_capenable & IFCAP_TXTLS6) == 0) {
898                         error = EOPNOTSUPP;
899                         goto out;
900                 }
901         } else {
902                 if ((ifp->if_capenable & IFCAP_TXTLS4) == 0) {
903                         error = EOPNOTSUPP;
904                         goto out;
905                 }
906         }
907         error = m_snd_tag_alloc(ifp, &params, mstp);
908 out:
909         if_rele(ifp);
910         return (error);
911 }
912
913 static int
914 ktls_try_ifnet(struct socket *so, struct ktls_session *tls, bool force)
915 {
916         struct m_snd_tag *mst;
917         int error;
918
919         error = ktls_alloc_snd_tag(so->so_pcb, tls, force, &mst);
920         if (error == 0) {
921                 tls->mode = TCP_TLS_MODE_IFNET;
922                 tls->snd_tag = mst;
923                 switch (tls->params.cipher_algorithm) {
924                 case CRYPTO_AES_CBC:
925                         counter_u64_add(ktls_ifnet_cbc, 1);
926                         break;
927                 case CRYPTO_AES_NIST_GCM_16:
928                         counter_u64_add(ktls_ifnet_gcm, 1);
929                         break;
930                 case CRYPTO_CHACHA20_POLY1305:
931                         counter_u64_add(ktls_ifnet_chacha20, 1);
932                         break;
933                 }
934         }
935         return (error);
936 }
937
938 static int
939 ktls_try_sw(struct socket *so, struct ktls_session *tls, int direction)
940 {
941         struct rm_priotracker prio;
942         struct ktls_crypto_backend *be;
943
944         /*
945          * Choose the best software crypto backend.  Backends are
946          * stored in sorted priority order (larget value == most
947          * important at the head of the list), so this just stops on
948          * the first backend that claims the session by returning
949          * success.
950          */
951         if (ktls_allow_unload)
952                 rm_rlock(&ktls_backends_lock, &prio);
953         LIST_FOREACH(be, &ktls_backends, next) {
954                 if (be->try(so, tls, direction) == 0)
955                         break;
956                 KASSERT(tls->cipher == NULL,
957                     ("ktls backend leaked a cipher pointer"));
958         }
959         if (be != NULL) {
960                 if (ktls_allow_unload)
961                         be->use_count++;
962                 tls->be = be;
963         }
964         if (ktls_allow_unload)
965                 rm_runlock(&ktls_backends_lock, &prio);
966         if (be == NULL)
967                 return (EOPNOTSUPP);
968         tls->mode = TCP_TLS_MODE_SW;
969         switch (tls->params.cipher_algorithm) {
970         case CRYPTO_AES_CBC:
971                 counter_u64_add(ktls_sw_cbc, 1);
972                 break;
973         case CRYPTO_AES_NIST_GCM_16:
974                 counter_u64_add(ktls_sw_gcm, 1);
975                 break;
976         case CRYPTO_CHACHA20_POLY1305:
977                 counter_u64_add(ktls_sw_chacha20, 1);
978                 break;
979         }
980         return (0);
981 }
982
983 /*
984  * KTLS RX stores data in the socket buffer as a list of TLS records,
985  * where each record is stored as a control message containg the TLS
986  * header followed by data mbufs containing the decrypted data.  This
987  * is different from KTLS TX which always uses an mb_ext_pgs mbuf for
988  * both encrypted and decrypted data.  TLS records decrypted by a NIC
989  * should be queued to the socket buffer as records, but encrypted
990  * data which needs to be decrypted by software arrives as a stream of
991  * regular mbufs which need to be converted.  In addition, there may
992  * already be pending encrypted data in the socket buffer when KTLS RX
993  * is enabled.
994  *
995  * To manage not-yet-decrypted data for KTLS RX, the following scheme
996  * is used:
997  *
998  * - A single chain of NOTREADY mbufs is hung off of sb_mtls.
999  *
1000  * - ktls_check_rx checks this chain of mbufs reading the TLS header
1001  *   from the first mbuf.  Once all of the data for that TLS record is
1002  *   queued, the socket is queued to a worker thread.
1003  *
1004  * - The worker thread calls ktls_decrypt to decrypt TLS records in
1005  *   the TLS chain.  Each TLS record is detached from the TLS chain,
1006  *   decrypted, and inserted into the regular socket buffer chain as
1007  *   record starting with a control message holding the TLS header and
1008  *   a chain of mbufs holding the encrypted data.
1009  */
1010
1011 static void
1012 sb_mark_notready(struct sockbuf *sb)
1013 {
1014         struct mbuf *m;
1015
1016         m = sb->sb_mb;
1017         sb->sb_mtls = m;
1018         sb->sb_mb = NULL;
1019         sb->sb_mbtail = NULL;
1020         sb->sb_lastrecord = NULL;
1021         for (; m != NULL; m = m->m_next) {
1022                 KASSERT(m->m_nextpkt == NULL, ("%s: m_nextpkt != NULL",
1023                     __func__));
1024                 KASSERT((m->m_flags & M_NOTAVAIL) == 0, ("%s: mbuf not avail",
1025                     __func__));
1026                 KASSERT(sb->sb_acc >= m->m_len, ("%s: sb_acc < m->m_len",
1027                     __func__));
1028                 m->m_flags |= M_NOTREADY;
1029                 sb->sb_acc -= m->m_len;
1030                 sb->sb_tlscc += m->m_len;
1031                 sb->sb_mtlstail = m;
1032         }
1033         KASSERT(sb->sb_acc == 0 && sb->sb_tlscc == sb->sb_ccc,
1034             ("%s: acc %u tlscc %u ccc %u", __func__, sb->sb_acc, sb->sb_tlscc,
1035             sb->sb_ccc));
1036 }
1037
1038 int
1039 ktls_enable_rx(struct socket *so, struct tls_enable *en)
1040 {
1041         struct ktls_session *tls;
1042         int error;
1043
1044         if (!ktls_offload_enable)
1045                 return (ENOTSUP);
1046         if (SOLISTENING(so))
1047                 return (EINVAL);
1048
1049         counter_u64_add(ktls_offload_enable_calls, 1);
1050
1051         /*
1052          * This should always be true since only the TCP socket option
1053          * invokes this function.
1054          */
1055         if (so->so_proto->pr_protocol != IPPROTO_TCP)
1056                 return (EINVAL);
1057
1058         /*
1059          * XXX: Don't overwrite existing sessions.  We should permit
1060          * this to support rekeying in the future.
1061          */
1062         if (so->so_rcv.sb_tls_info != NULL)
1063                 return (EALREADY);
1064
1065         if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1066                 return (ENOTSUP);
1067
1068         /* TLS 1.3 is not yet supported. */
1069         if (en->tls_vmajor == TLS_MAJOR_VER_ONE &&
1070             en->tls_vminor == TLS_MINOR_VER_THREE)
1071                 return (ENOTSUP);
1072
1073         error = ktls_create_session(so, en, &tls);
1074         if (error)
1075                 return (error);
1076
1077 #ifdef TCP_OFFLOAD
1078         error = ktls_try_toe(so, tls, KTLS_RX);
1079         if (error)
1080 #endif
1081                 error = ktls_try_sw(so, tls, KTLS_RX);
1082
1083         if (error) {
1084                 ktls_cleanup(tls);
1085                 return (error);
1086         }
1087
1088         /* Mark the socket as using TLS offload. */
1089         SOCKBUF_LOCK(&so->so_rcv);
1090         so->so_rcv.sb_tls_seqno = be64dec(en->rec_seq);
1091         so->so_rcv.sb_tls_info = tls;
1092         so->so_rcv.sb_flags |= SB_TLS_RX;
1093
1094         /* Mark existing data as not ready until it can be decrypted. */
1095         if (tls->mode != TCP_TLS_MODE_TOE) {
1096                 sb_mark_notready(&so->so_rcv);
1097                 ktls_check_rx(&so->so_rcv);
1098         }
1099         SOCKBUF_UNLOCK(&so->so_rcv);
1100
1101         counter_u64_add(ktls_offload_total, 1);
1102
1103         return (0);
1104 }
1105
1106 int
1107 ktls_enable_tx(struct socket *so, struct tls_enable *en)
1108 {
1109         struct ktls_session *tls;
1110         struct inpcb *inp;
1111         int error;
1112
1113         if (!ktls_offload_enable)
1114                 return (ENOTSUP);
1115         if (SOLISTENING(so))
1116                 return (EINVAL);
1117
1118         counter_u64_add(ktls_offload_enable_calls, 1);
1119
1120         /*
1121          * This should always be true since only the TCP socket option
1122          * invokes this function.
1123          */
1124         if (so->so_proto->pr_protocol != IPPROTO_TCP)
1125                 return (EINVAL);
1126
1127         /*
1128          * XXX: Don't overwrite existing sessions.  We should permit
1129          * this to support rekeying in the future.
1130          */
1131         if (so->so_snd.sb_tls_info != NULL)
1132                 return (EALREADY);
1133
1134         if (en->cipher_algorithm == CRYPTO_AES_CBC && !ktls_cbc_enable)
1135                 return (ENOTSUP);
1136
1137         /* TLS requires ext pgs */
1138         if (mb_use_ext_pgs == 0)
1139                 return (ENXIO);
1140
1141         error = ktls_create_session(so, en, &tls);
1142         if (error)
1143                 return (error);
1144
1145         /* Prefer TOE -> ifnet TLS -> software TLS. */
1146 #ifdef TCP_OFFLOAD
1147         error = ktls_try_toe(so, tls, KTLS_TX);
1148         if (error)
1149 #endif
1150                 error = ktls_try_ifnet(so, tls, false);
1151         if (error)
1152                 error = ktls_try_sw(so, tls, KTLS_TX);
1153
1154         if (error) {
1155                 ktls_cleanup(tls);
1156                 return (error);
1157         }
1158
1159         error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1160         if (error) {
1161                 ktls_cleanup(tls);
1162                 return (error);
1163         }
1164
1165         /*
1166          * Write lock the INP when setting sb_tls_info so that
1167          * routines in tcp_ratelimit.c can read sb_tls_info while
1168          * holding the INP lock.
1169          */
1170         inp = so->so_pcb;
1171         INP_WLOCK(inp);
1172         SOCKBUF_LOCK(&so->so_snd);
1173         so->so_snd.sb_tls_seqno = be64dec(en->rec_seq);
1174         so->so_snd.sb_tls_info = tls;
1175         if (tls->mode != TCP_TLS_MODE_SW)
1176                 so->so_snd.sb_flags |= SB_TLS_IFNET;
1177         SOCKBUF_UNLOCK(&so->so_snd);
1178         INP_WUNLOCK(inp);
1179         SOCK_IO_SEND_UNLOCK(so);
1180
1181         counter_u64_add(ktls_offload_total, 1);
1182
1183         return (0);
1184 }
1185
1186 int
1187 ktls_get_rx_mode(struct socket *so)
1188 {
1189         struct ktls_session *tls;
1190         struct inpcb *inp;
1191         int mode;
1192
1193         if (SOLISTENING(so))
1194                 return (EINVAL);
1195         inp = so->so_pcb;
1196         INP_WLOCK_ASSERT(inp);
1197         SOCKBUF_LOCK(&so->so_rcv);
1198         tls = so->so_rcv.sb_tls_info;
1199         if (tls == NULL)
1200                 mode = TCP_TLS_MODE_NONE;
1201         else
1202                 mode = tls->mode;
1203         SOCKBUF_UNLOCK(&so->so_rcv);
1204         return (mode);
1205 }
1206
1207 int
1208 ktls_get_tx_mode(struct socket *so)
1209 {
1210         struct ktls_session *tls;
1211         struct inpcb *inp;
1212         int mode;
1213
1214         if (SOLISTENING(so))
1215                 return (EINVAL);
1216         inp = so->so_pcb;
1217         INP_WLOCK_ASSERT(inp);
1218         SOCKBUF_LOCK(&so->so_snd);
1219         tls = so->so_snd.sb_tls_info;
1220         if (tls == NULL)
1221                 mode = TCP_TLS_MODE_NONE;
1222         else
1223                 mode = tls->mode;
1224         SOCKBUF_UNLOCK(&so->so_snd);
1225         return (mode);
1226 }
1227
1228 /*
1229  * Switch between SW and ifnet TLS sessions as requested.
1230  */
1231 int
1232 ktls_set_tx_mode(struct socket *so, int mode)
1233 {
1234         struct ktls_session *tls, *tls_new;
1235         struct inpcb *inp;
1236         int error;
1237
1238         if (SOLISTENING(so))
1239                 return (EINVAL);
1240         switch (mode) {
1241         case TCP_TLS_MODE_SW:
1242         case TCP_TLS_MODE_IFNET:
1243                 break;
1244         default:
1245                 return (EINVAL);
1246         }
1247
1248         inp = so->so_pcb;
1249         INP_WLOCK_ASSERT(inp);
1250         SOCKBUF_LOCK(&so->so_snd);
1251         tls = so->so_snd.sb_tls_info;
1252         if (tls == NULL) {
1253                 SOCKBUF_UNLOCK(&so->so_snd);
1254                 return (0);
1255         }
1256
1257         if (tls->mode == mode) {
1258                 SOCKBUF_UNLOCK(&so->so_snd);
1259                 return (0);
1260         }
1261
1262         tls = ktls_hold(tls);
1263         SOCKBUF_UNLOCK(&so->so_snd);
1264         INP_WUNLOCK(inp);
1265
1266         tls_new = ktls_clone_session(tls);
1267
1268         if (mode == TCP_TLS_MODE_IFNET)
1269                 error = ktls_try_ifnet(so, tls_new, true);
1270         else
1271                 error = ktls_try_sw(so, tls_new, KTLS_TX);
1272         if (error) {
1273                 counter_u64_add(ktls_switch_failed, 1);
1274                 ktls_free(tls_new);
1275                 ktls_free(tls);
1276                 INP_WLOCK(inp);
1277                 return (error);
1278         }
1279
1280         error = SOCK_IO_SEND_LOCK(so, SBL_WAIT);
1281         if (error) {
1282                 counter_u64_add(ktls_switch_failed, 1);
1283                 ktls_free(tls_new);
1284                 ktls_free(tls);
1285                 INP_WLOCK(inp);
1286                 return (error);
1287         }
1288
1289         /*
1290          * If we raced with another session change, keep the existing
1291          * session.
1292          */
1293         if (tls != so->so_snd.sb_tls_info) {
1294                 counter_u64_add(ktls_switch_failed, 1);
1295                 SOCK_IO_SEND_UNLOCK(so);
1296                 ktls_free(tls_new);
1297                 ktls_free(tls);
1298                 INP_WLOCK(inp);
1299                 return (EBUSY);
1300         }
1301
1302         SOCKBUF_LOCK(&so->so_snd);
1303         so->so_snd.sb_tls_info = tls_new;
1304         if (tls_new->mode != TCP_TLS_MODE_SW)
1305                 so->so_snd.sb_flags |= SB_TLS_IFNET;
1306         SOCKBUF_UNLOCK(&so->so_snd);
1307         SOCK_IO_SEND_UNLOCK(so);
1308
1309         /*
1310          * Drop two references on 'tls'.  The first is for the
1311          * ktls_hold() above.  The second drops the reference from the
1312          * socket buffer.
1313          */
1314         KASSERT(tls->refcount >= 2, ("too few references on old session"));
1315         ktls_free(tls);
1316         ktls_free(tls);
1317
1318         if (mode == TCP_TLS_MODE_IFNET)
1319                 counter_u64_add(ktls_switch_to_ifnet, 1);
1320         else
1321                 counter_u64_add(ktls_switch_to_sw, 1);
1322
1323         INP_WLOCK(inp);
1324         return (0);
1325 }
1326
1327 /*
1328  * Try to allocate a new TLS send tag.  This task is scheduled when
1329  * ip_output detects a route change while trying to transmit a packet
1330  * holding a TLS record.  If a new tag is allocated, replace the tag
1331  * in the TLS session.  Subsequent packets on the connection will use
1332  * the new tag.  If a new tag cannot be allocated, drop the
1333  * connection.
1334  */
1335 static void
1336 ktls_reset_send_tag(void *context, int pending)
1337 {
1338         struct epoch_tracker et;
1339         struct ktls_session *tls;
1340         struct m_snd_tag *old, *new;
1341         struct inpcb *inp;
1342         struct tcpcb *tp;
1343         int error;
1344
1345         MPASS(pending == 1);
1346
1347         tls = context;
1348         inp = tls->inp;
1349
1350         /*
1351          * Free the old tag first before allocating a new one.
1352          * ip[6]_output_send() will treat a NULL send tag the same as
1353          * an ifp mismatch and drop packets until a new tag is
1354          * allocated.
1355          *
1356          * Write-lock the INP when changing tls->snd_tag since
1357          * ip[6]_output_send() holds a read-lock when reading the
1358          * pointer.
1359          */
1360         INP_WLOCK(inp);
1361         old = tls->snd_tag;
1362         tls->snd_tag = NULL;
1363         INP_WUNLOCK(inp);
1364         if (old != NULL)
1365                 m_snd_tag_rele(old);
1366
1367         error = ktls_alloc_snd_tag(inp, tls, true, &new);
1368
1369         if (error == 0) {
1370                 INP_WLOCK(inp);
1371                 tls->snd_tag = new;
1372                 mtx_pool_lock(mtxpool_sleep, tls);
1373                 tls->reset_pending = false;
1374                 mtx_pool_unlock(mtxpool_sleep, tls);
1375                 if (!in_pcbrele_wlocked(inp))
1376                         INP_WUNLOCK(inp);
1377
1378                 counter_u64_add(ktls_ifnet_reset, 1);
1379
1380                 /*
1381                  * XXX: Should we kick tcp_output explicitly now that
1382                  * the send tag is fixed or just rely on timers?
1383                  */
1384         } else {
1385                 NET_EPOCH_ENTER(et);
1386                 INP_WLOCK(inp);
1387                 if (!in_pcbrele_wlocked(inp)) {
1388                         if (!(inp->inp_flags & INP_TIMEWAIT) &&
1389                             !(inp->inp_flags & INP_DROPPED)) {
1390                                 tp = intotcpcb(inp);
1391                                 CURVNET_SET(tp->t_vnet);
1392                                 tp = tcp_drop(tp, ECONNABORTED);
1393                                 CURVNET_RESTORE();
1394                                 if (tp != NULL)
1395                                         INP_WUNLOCK(inp);
1396                                 counter_u64_add(ktls_ifnet_reset_dropped, 1);
1397                         } else
1398                                 INP_WUNLOCK(inp);
1399                 }
1400                 NET_EPOCH_EXIT(et);
1401
1402                 counter_u64_add(ktls_ifnet_reset_failed, 1);
1403
1404                 /*
1405                  * Leave reset_pending true to avoid future tasks while
1406                  * the socket goes away.
1407                  */
1408         }
1409
1410         ktls_free(tls);
1411 }
1412
1413 int
1414 ktls_output_eagain(struct inpcb *inp, struct ktls_session *tls)
1415 {
1416
1417         if (inp == NULL)
1418                 return (ENOBUFS);
1419
1420         INP_LOCK_ASSERT(inp);
1421
1422         /*
1423          * See if we should schedule a task to update the send tag for
1424          * this session.
1425          */
1426         mtx_pool_lock(mtxpool_sleep, tls);
1427         if (!tls->reset_pending) {
1428                 (void) ktls_hold(tls);
1429                 in_pcbref(inp);
1430                 tls->inp = inp;
1431                 tls->reset_pending = true;
1432                 taskqueue_enqueue(taskqueue_thread, &tls->reset_tag_task);
1433         }
1434         mtx_pool_unlock(mtxpool_sleep, tls);
1435         return (ENOBUFS);
1436 }
1437
1438 #ifdef RATELIMIT
1439 int
1440 ktls_modify_txrtlmt(struct ktls_session *tls, uint64_t max_pacing_rate)
1441 {
1442         union if_snd_tag_modify_params params = {
1443                 .rate_limit.max_rate = max_pacing_rate,
1444                 .rate_limit.flags = M_NOWAIT,
1445         };
1446         struct m_snd_tag *mst;
1447         struct ifnet *ifp;
1448         int error;
1449
1450         /* Can't get to the inp, but it should be locked. */
1451         /* INP_LOCK_ASSERT(inp); */
1452
1453         MPASS(tls->mode == TCP_TLS_MODE_IFNET);
1454
1455         if (tls->snd_tag == NULL) {
1456                 /*
1457                  * Resetting send tag, ignore this change.  The
1458                  * pending reset may or may not see this updated rate
1459                  * in the tcpcb.  If it doesn't, we will just lose
1460                  * this rate change.
1461                  */
1462                 return (0);
1463         }
1464
1465         MPASS(tls->snd_tag != NULL);
1466         MPASS(tls->snd_tag->type == IF_SND_TAG_TYPE_TLS_RATE_LIMIT);
1467
1468         mst = tls->snd_tag;
1469         ifp = mst->ifp;
1470         return (ifp->if_snd_tag_modify(mst, &params));
1471 }
1472 #endif
1473 #endif
1474
1475 void
1476 ktls_destroy(struct ktls_session *tls)
1477 {
1478         struct rm_priotracker prio;
1479
1480         ktls_cleanup(tls);
1481         if (tls->be != NULL && ktls_allow_unload) {
1482                 rm_rlock(&ktls_backends_lock, &prio);
1483                 tls->be->use_count--;
1484                 rm_runlock(&ktls_backends_lock, &prio);
1485         }
1486         uma_zfree(ktls_session_zone, tls);
1487 }
1488
1489 void
1490 ktls_seq(struct sockbuf *sb, struct mbuf *m)
1491 {
1492
1493         for (; m != NULL; m = m->m_next) {
1494                 KASSERT((m->m_flags & M_EXTPG) != 0,
1495                     ("ktls_seq: mapped mbuf %p", m));
1496
1497                 m->m_epg_seqno = sb->sb_tls_seqno;
1498                 sb->sb_tls_seqno++;
1499         }
1500 }
1501
1502 /*
1503  * Add TLS framing (headers and trailers) to a chain of mbufs.  Each
1504  * mbuf in the chain must be an unmapped mbuf.  The payload of the
1505  * mbuf must be populated with the payload of each TLS record.
1506  *
1507  * The record_type argument specifies the TLS record type used when
1508  * populating the TLS header.
1509  *
1510  * The enq_count argument on return is set to the number of pages of
1511  * payload data for this entire chain that need to be encrypted via SW
1512  * encryption.  The returned value should be passed to ktls_enqueue
1513  * when scheduling encryption of this chain of mbufs.  To handle the
1514  * special case of empty fragments for TLS 1.0 sessions, an empty
1515  * fragment counts as one page.
1516  */
1517 void
1518 ktls_frame(struct mbuf *top, struct ktls_session *tls, int *enq_cnt,
1519     uint8_t record_type)
1520 {
1521         struct tls_record_layer *tlshdr;
1522         struct mbuf *m;
1523         uint64_t *noncep;
1524         uint16_t tls_len;
1525         int maxlen;
1526
1527         maxlen = tls->params.max_frame_len;
1528         *enq_cnt = 0;
1529         for (m = top; m != NULL; m = m->m_next) {
1530                 /*
1531                  * All mbufs in the chain should be TLS records whose
1532                  * payload does not exceed the maximum frame length.
1533                  *
1534                  * Empty TLS records are permitted when using CBC.
1535                  */
1536                 KASSERT(m->m_len <= maxlen &&
1537                     (tls->params.cipher_algorithm == CRYPTO_AES_CBC ?
1538                     m->m_len >= 0 : m->m_len > 0),
1539                     ("ktls_frame: m %p len %d\n", m, m->m_len));
1540
1541                 /*
1542                  * TLS frames require unmapped mbufs to store session
1543                  * info.
1544                  */
1545                 KASSERT((m->m_flags & M_EXTPG) != 0,
1546                     ("ktls_frame: mapped mbuf %p (top = %p)\n", m, top));
1547
1548                 tls_len = m->m_len;
1549
1550                 /* Save a reference to the session. */
1551                 m->m_epg_tls = ktls_hold(tls);
1552
1553                 m->m_epg_hdrlen = tls->params.tls_hlen;
1554                 m->m_epg_trllen = tls->params.tls_tlen;
1555                 if (tls->params.cipher_algorithm == CRYPTO_AES_CBC) {
1556                         int bs, delta;
1557
1558                         /*
1559                          * AES-CBC pads messages to a multiple of the
1560                          * block size.  Note that the padding is
1561                          * applied after the digest and the encryption
1562                          * is done on the "plaintext || mac || padding".
1563                          * At least one byte of padding is always
1564                          * present.
1565                          *
1566                          * Compute the final trailer length assuming
1567                          * at most one block of padding.
1568                          * tls->params.sb_tls_tlen is the maximum
1569                          * possible trailer length (padding + digest).
1570                          * delta holds the number of excess padding
1571                          * bytes if the maximum were used.  Those
1572                          * extra bytes are removed.
1573                          */
1574                         bs = tls->params.tls_bs;
1575                         delta = (tls_len + tls->params.tls_tlen) & (bs - 1);
1576                         m->m_epg_trllen -= delta;
1577                 }
1578                 m->m_len += m->m_epg_hdrlen + m->m_epg_trllen;
1579
1580                 /* Populate the TLS header. */
1581                 tlshdr = (void *)m->m_epg_hdr;
1582                 tlshdr->tls_vmajor = tls->params.tls_vmajor;
1583
1584                 /*
1585                  * TLS 1.3 masquarades as TLS 1.2 with a record type
1586                  * of TLS_RLTYPE_APP.
1587                  */
1588                 if (tls->params.tls_vminor == TLS_MINOR_VER_THREE &&
1589                     tls->params.tls_vmajor == TLS_MAJOR_VER_ONE) {
1590                         tlshdr->tls_vminor = TLS_MINOR_VER_TWO;
1591                         tlshdr->tls_type = TLS_RLTYPE_APP;
1592                         /* save the real record type for later */
1593                         m->m_epg_record_type = record_type;
1594                         m->m_epg_trail[0] = record_type;
1595                 } else {
1596                         tlshdr->tls_vminor = tls->params.tls_vminor;
1597                         tlshdr->tls_type = record_type;
1598                 }
1599                 tlshdr->tls_length = htons(m->m_len - sizeof(*tlshdr));
1600
1601                 /*
1602                  * Store nonces / explicit IVs after the end of the
1603                  * TLS header.
1604                  *
1605                  * For GCM with TLS 1.2, an 8 byte nonce is copied
1606                  * from the end of the IV.  The nonce is then
1607                  * incremented for use by the next record.
1608                  *
1609                  * For CBC, a random nonce is inserted for TLS 1.1+.
1610                  */
1611                 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16 &&
1612                     tls->params.tls_vminor == TLS_MINOR_VER_TWO) {
1613                         noncep = (uint64_t *)(tls->params.iv + 8);
1614                         be64enc(tlshdr + 1, *noncep);
1615                         (*noncep)++;
1616                 } else if (tls->params.cipher_algorithm == CRYPTO_AES_CBC &&
1617                     tls->params.tls_vminor >= TLS_MINOR_VER_ONE)
1618                         arc4rand(tlshdr + 1, AES_BLOCK_LEN, 0);
1619
1620                 /*
1621                  * When using SW encryption, mark the mbuf not ready.
1622                  * It will be marked ready via sbready() after the
1623                  * record has been encrypted.
1624                  *
1625                  * When using ifnet TLS, unencrypted TLS records are
1626                  * sent down the stack to the NIC.
1627                  */
1628                 if (tls->mode == TCP_TLS_MODE_SW) {
1629                         m->m_flags |= M_NOTREADY;
1630                         if (__predict_false(tls_len == 0)) {
1631                                 /* TLS 1.0 empty fragment. */
1632                                 m->m_epg_nrdy = 1;
1633                         } else
1634                                 m->m_epg_nrdy = m->m_epg_npgs;
1635                         *enq_cnt += m->m_epg_nrdy;
1636                 }
1637         }
1638 }
1639
1640 void
1641 ktls_check_rx(struct sockbuf *sb)
1642 {
1643         struct tls_record_layer hdr;
1644         struct ktls_wq *wq;
1645         struct socket *so;
1646         bool running;
1647
1648         SOCKBUF_LOCK_ASSERT(sb);
1649         KASSERT(sb->sb_flags & SB_TLS_RX, ("%s: sockbuf %p isn't TLS RX",
1650             __func__, sb));
1651         so = __containerof(sb, struct socket, so_rcv);
1652
1653         if (sb->sb_flags & SB_TLS_RX_RUNNING)
1654                 return;
1655
1656         /* Is there enough queued for a TLS header? */
1657         if (sb->sb_tlscc < sizeof(hdr)) {
1658                 if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc != 0)
1659                         so->so_error = EMSGSIZE;
1660                 return;
1661         }
1662
1663         m_copydata(sb->sb_mtls, 0, sizeof(hdr), (void *)&hdr);
1664
1665         /* Is the entire record queued? */
1666         if (sb->sb_tlscc < sizeof(hdr) + ntohs(hdr.tls_length)) {
1667                 if ((sb->sb_state & SBS_CANTRCVMORE) != 0)
1668                         so->so_error = EMSGSIZE;
1669                 return;
1670         }
1671
1672         sb->sb_flags |= SB_TLS_RX_RUNNING;
1673
1674         soref(so);
1675         wq = &ktls_wq[so->so_rcv.sb_tls_info->wq_index];
1676         mtx_lock(&wq->mtx);
1677         STAILQ_INSERT_TAIL(&wq->so_head, so, so_ktls_rx_list);
1678         running = wq->running;
1679         mtx_unlock(&wq->mtx);
1680         if (!running)
1681                 wakeup(wq);
1682         counter_u64_add(ktls_cnt_rx_queued, 1);
1683 }
1684
1685 static struct mbuf *
1686 ktls_detach_record(struct sockbuf *sb, int len)
1687 {
1688         struct mbuf *m, *n, *top;
1689         int remain;
1690
1691         SOCKBUF_LOCK_ASSERT(sb);
1692         MPASS(len <= sb->sb_tlscc);
1693
1694         /*
1695          * If TLS chain is the exact size of the record,
1696          * just grab the whole record.
1697          */
1698         top = sb->sb_mtls;
1699         if (sb->sb_tlscc == len) {
1700                 sb->sb_mtls = NULL;
1701                 sb->sb_mtlstail = NULL;
1702                 goto out;
1703         }
1704
1705         /*
1706          * While it would be nice to use m_split() here, we need
1707          * to know exactly what m_split() allocates to update the
1708          * accounting, so do it inline instead.
1709          */
1710         remain = len;
1711         for (m = top; remain > m->m_len; m = m->m_next)
1712                 remain -= m->m_len;
1713
1714         /* Easy case: don't have to split 'm'. */
1715         if (remain == m->m_len) {
1716                 sb->sb_mtls = m->m_next;
1717                 if (sb->sb_mtls == NULL)
1718                         sb->sb_mtlstail = NULL;
1719                 m->m_next = NULL;
1720                 goto out;
1721         }
1722
1723         /*
1724          * Need to allocate an mbuf to hold the remainder of 'm'.  Try
1725          * with M_NOWAIT first.
1726          */
1727         n = m_get(M_NOWAIT, MT_DATA);
1728         if (n == NULL) {
1729                 /*
1730                  * Use M_WAITOK with socket buffer unlocked.  If
1731                  * 'sb_mtls' changes while the lock is dropped, return
1732                  * NULL to force the caller to retry.
1733                  */
1734                 SOCKBUF_UNLOCK(sb);
1735
1736                 n = m_get(M_WAITOK, MT_DATA);
1737
1738                 SOCKBUF_LOCK(sb);
1739                 if (sb->sb_mtls != top) {
1740                         m_free(n);
1741                         return (NULL);
1742                 }
1743         }
1744         n->m_flags |= M_NOTREADY;
1745
1746         /* Store remainder in 'n'. */
1747         n->m_len = m->m_len - remain;
1748         if (m->m_flags & M_EXT) {
1749                 n->m_data = m->m_data + remain;
1750                 mb_dupcl(n, m);
1751         } else {
1752                 bcopy(mtod(m, caddr_t) + remain, mtod(n, caddr_t), n->m_len);
1753         }
1754
1755         /* Trim 'm' and update accounting. */
1756         m->m_len -= n->m_len;
1757         sb->sb_tlscc -= n->m_len;
1758         sb->sb_ccc -= n->m_len;
1759
1760         /* Account for 'n'. */
1761         sballoc_ktls_rx(sb, n);
1762
1763         /* Insert 'n' into the TLS chain. */
1764         sb->sb_mtls = n;
1765         n->m_next = m->m_next;
1766         if (sb->sb_mtlstail == m)
1767                 sb->sb_mtlstail = n;
1768
1769         /* Detach the record from the TLS chain. */
1770         m->m_next = NULL;
1771
1772 out:
1773         MPASS(m_length(top, NULL) == len);
1774         for (m = top; m != NULL; m = m->m_next)
1775                 sbfree_ktls_rx(sb, m);
1776         sb->sb_tlsdcc = len;
1777         sb->sb_ccc += len;
1778         SBCHECK(sb);
1779         return (top);
1780 }
1781
1782 static void
1783 ktls_decrypt(struct socket *so)
1784 {
1785         char tls_header[MBUF_PEXT_HDR_LEN];
1786         struct ktls_session *tls;
1787         struct sockbuf *sb;
1788         struct tls_record_layer *hdr;
1789         struct tls_get_record tgr;
1790         struct mbuf *control, *data, *m;
1791         uint64_t seqno;
1792         int error, remain, tls_len, trail_len;
1793
1794         hdr = (struct tls_record_layer *)tls_header;
1795         sb = &so->so_rcv;
1796         SOCKBUF_LOCK(sb);
1797         KASSERT(sb->sb_flags & SB_TLS_RX_RUNNING,
1798             ("%s: socket %p not running", __func__, so));
1799
1800         tls = sb->sb_tls_info;
1801         MPASS(tls != NULL);
1802
1803         for (;;) {
1804                 /* Is there enough queued for a TLS header? */
1805                 if (sb->sb_tlscc < tls->params.tls_hlen)
1806                         break;
1807
1808                 m_copydata(sb->sb_mtls, 0, tls->params.tls_hlen, tls_header);
1809                 tls_len = sizeof(*hdr) + ntohs(hdr->tls_length);
1810
1811                 if (hdr->tls_vmajor != tls->params.tls_vmajor ||
1812                     hdr->tls_vminor != tls->params.tls_vminor)
1813                         error = EINVAL;
1814                 else if (tls_len < tls->params.tls_hlen || tls_len >
1815                     tls->params.tls_hlen + TLS_MAX_MSG_SIZE_V10_2 +
1816                     tls->params.tls_tlen)
1817                         error = EMSGSIZE;
1818                 else
1819                         error = 0;
1820                 if (__predict_false(error != 0)) {
1821                         /*
1822                          * We have a corrupted record and are likely
1823                          * out of sync.  The connection isn't
1824                          * recoverable at this point, so abort it.
1825                          */
1826                         SOCKBUF_UNLOCK(sb);
1827                         counter_u64_add(ktls_offload_corrupted_records, 1);
1828
1829                         CURVNET_SET(so->so_vnet);
1830                         so->so_proto->pr_usrreqs->pru_abort(so);
1831                         so->so_error = error;
1832                         CURVNET_RESTORE();
1833                         goto deref;
1834                 }
1835
1836                 /* Is the entire record queued? */
1837                 if (sb->sb_tlscc < tls_len)
1838                         break;
1839
1840                 /*
1841                  * Split out the portion of the mbuf chain containing
1842                  * this TLS record.
1843                  */
1844                 data = ktls_detach_record(sb, tls_len);
1845                 if (data == NULL)
1846                         continue;
1847                 MPASS(sb->sb_tlsdcc == tls_len);
1848
1849                 seqno = sb->sb_tls_seqno;
1850                 sb->sb_tls_seqno++;
1851                 SBCHECK(sb);
1852                 SOCKBUF_UNLOCK(sb);
1853
1854                 error = tls->sw_decrypt(tls, hdr, data, seqno, &trail_len);
1855                 if (error) {
1856                         counter_u64_add(ktls_offload_failed_crypto, 1);
1857
1858                         SOCKBUF_LOCK(sb);
1859                         if (sb->sb_tlsdcc == 0) {
1860                                 /*
1861                                  * sbcut/drop/flush discarded these
1862                                  * mbufs.
1863                                  */
1864                                 m_freem(data);
1865                                 break;
1866                         }
1867
1868                         /*
1869                          * Drop this TLS record's data, but keep
1870                          * decrypting subsequent records.
1871                          */
1872                         sb->sb_ccc -= tls_len;
1873                         sb->sb_tlsdcc = 0;
1874
1875                         CURVNET_SET(so->so_vnet);
1876                         so->so_error = EBADMSG;
1877                         sorwakeup_locked(so);
1878                         CURVNET_RESTORE();
1879
1880                         m_freem(data);
1881
1882                         SOCKBUF_LOCK(sb);
1883                         continue;
1884                 }
1885
1886                 /* Allocate the control mbuf. */
1887                 tgr.tls_type = hdr->tls_type;
1888                 tgr.tls_vmajor = hdr->tls_vmajor;
1889                 tgr.tls_vminor = hdr->tls_vminor;
1890                 tgr.tls_length = htobe16(tls_len - tls->params.tls_hlen -
1891                     trail_len);
1892                 control = sbcreatecontrol_how(&tgr, sizeof(tgr),
1893                     TLS_GET_RECORD, IPPROTO_TCP, M_WAITOK);
1894
1895                 SOCKBUF_LOCK(sb);
1896                 if (sb->sb_tlsdcc == 0) {
1897                         /* sbcut/drop/flush discarded these mbufs. */
1898                         MPASS(sb->sb_tlscc == 0);
1899                         m_freem(data);
1900                         m_freem(control);
1901                         break;
1902                 }
1903
1904                 /*
1905                  * Clear the 'dcc' accounting in preparation for
1906                  * adding the decrypted record.
1907                  */
1908                 sb->sb_ccc -= tls_len;
1909                 sb->sb_tlsdcc = 0;
1910                 SBCHECK(sb);
1911
1912                 /* If there is no payload, drop all of the data. */
1913                 if (tgr.tls_length == htobe16(0)) {
1914                         m_freem(data);
1915                         data = NULL;
1916                 } else {
1917                         /* Trim header. */
1918                         remain = tls->params.tls_hlen;
1919                         while (remain > 0) {
1920                                 if (data->m_len > remain) {
1921                                         data->m_data += remain;
1922                                         data->m_len -= remain;
1923                                         break;
1924                                 }
1925                                 remain -= data->m_len;
1926                                 data = m_free(data);
1927                         }
1928
1929                         /* Trim trailer and clear M_NOTREADY. */
1930                         remain = be16toh(tgr.tls_length);
1931                         m = data;
1932                         for (m = data; remain > m->m_len; m = m->m_next) {
1933                                 m->m_flags &= ~M_NOTREADY;
1934                                 remain -= m->m_len;
1935                         }
1936                         m->m_len = remain;
1937                         m_freem(m->m_next);
1938                         m->m_next = NULL;
1939                         m->m_flags &= ~M_NOTREADY;
1940
1941                         /* Set EOR on the final mbuf. */
1942                         m->m_flags |= M_EOR;
1943                 }
1944
1945                 sbappendcontrol_locked(sb, data, control, 0);
1946         }
1947
1948         sb->sb_flags &= ~SB_TLS_RX_RUNNING;
1949
1950         if ((sb->sb_state & SBS_CANTRCVMORE) != 0 && sb->sb_tlscc > 0)
1951                 so->so_error = EMSGSIZE;
1952
1953         sorwakeup_locked(so);
1954
1955 deref:
1956         SOCKBUF_UNLOCK_ASSERT(sb);
1957
1958         CURVNET_SET(so->so_vnet);
1959         SOCK_LOCK(so);
1960         sorele(so);
1961         CURVNET_RESTORE();
1962 }
1963
1964 void
1965 ktls_enqueue_to_free(struct mbuf *m)
1966 {
1967         struct ktls_wq *wq;
1968         bool running;
1969
1970         /* Mark it for freeing. */
1971         m->m_epg_flags |= EPG_FLAG_2FREE;
1972         wq = &ktls_wq[m->m_epg_tls->wq_index];
1973         mtx_lock(&wq->mtx);
1974         STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
1975         running = wq->running;
1976         mtx_unlock(&wq->mtx);
1977         if (!running)
1978                 wakeup(wq);
1979 }
1980
1981 void
1982 ktls_enqueue(struct mbuf *m, struct socket *so, int page_count)
1983 {
1984         struct ktls_wq *wq;
1985         bool running;
1986
1987         KASSERT(((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
1988             (M_EXTPG | M_NOTREADY)),
1989             ("ktls_enqueue: %p not unready & nomap mbuf\n", m));
1990         KASSERT(page_count != 0, ("enqueueing TLS mbuf with zero page count"));
1991
1992         KASSERT(m->m_epg_tls->mode == TCP_TLS_MODE_SW, ("!SW TLS mbuf"));
1993
1994         m->m_epg_enc_cnt = page_count;
1995
1996         /*
1997          * Save a pointer to the socket.  The caller is responsible
1998          * for taking an additional reference via soref().
1999          */
2000         m->m_epg_so = so;
2001
2002         wq = &ktls_wq[m->m_epg_tls->wq_index];
2003         mtx_lock(&wq->mtx);
2004         STAILQ_INSERT_TAIL(&wq->m_head, m, m_epg_stailq);
2005         running = wq->running;
2006         mtx_unlock(&wq->mtx);
2007         if (!running)
2008                 wakeup(wq);
2009         counter_u64_add(ktls_cnt_tx_queued, 1);
2010 }
2011
2012 static __noinline void
2013 ktls_encrypt(struct mbuf *top)
2014 {
2015         struct ktls_session *tls;
2016         struct socket *so;
2017         struct mbuf *m;
2018         vm_paddr_t parray[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
2019         struct iovec src_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
2020         struct iovec dst_iov[1 + btoc(TLS_MAX_MSG_SIZE_V10_2)];
2021         vm_page_t pg;
2022         int error, i, len, npages, off, total_pages;
2023         bool is_anon;
2024
2025         so = top->m_epg_so;
2026         tls = top->m_epg_tls;
2027         KASSERT(tls != NULL, ("tls = NULL, top = %p\n", top));
2028         KASSERT(so != NULL, ("so = NULL, top = %p\n", top));
2029 #ifdef INVARIANTS
2030         top->m_epg_so = NULL;
2031 #endif
2032         total_pages = top->m_epg_enc_cnt;
2033         npages = 0;
2034
2035         /*
2036          * Encrypt the TLS records in the chain of mbufs starting with
2037          * 'top'.  'total_pages' gives us a total count of pages and is
2038          * used to know when we have finished encrypting the TLS
2039          * records originally queued with 'top'.
2040          *
2041          * NB: These mbufs are queued in the socket buffer and
2042          * 'm_next' is traversing the mbufs in the socket buffer.  The
2043          * socket buffer lock is not held while traversing this chain.
2044          * Since the mbufs are all marked M_NOTREADY their 'm_next'
2045          * pointers should be stable.  However, the 'm_next' of the
2046          * last mbuf encrypted is not necessarily NULL.  It can point
2047          * to other mbufs appended while 'top' was on the TLS work
2048          * queue.
2049          *
2050          * Each mbuf holds an entire TLS record.
2051          */
2052         error = 0;
2053         for (m = top; npages != total_pages; m = m->m_next) {
2054                 KASSERT(m->m_epg_tls == tls,
2055                     ("different TLS sessions in a single mbuf chain: %p vs %p",
2056                     tls, m->m_epg_tls));
2057                 KASSERT((m->m_flags & (M_EXTPG | M_NOTREADY)) ==
2058                     (M_EXTPG | M_NOTREADY),
2059                     ("%p not unready & nomap mbuf (top = %p)\n", m, top));
2060                 KASSERT(npages + m->m_epg_npgs <= total_pages,
2061                     ("page count mismatch: top %p, total_pages %d, m %p", top,
2062                     total_pages, m));
2063
2064                 /*
2065                  * Generate source and destination ivoecs to pass to
2066                  * the SW encryption backend.  For writable mbufs, the
2067                  * destination iovec is a copy of the source and
2068                  * encryption is done in place.  For file-backed mbufs
2069                  * (from sendfile), anonymous wired pages are
2070                  * allocated and assigned to the destination iovec.
2071                  */
2072                 is_anon = (m->m_epg_flags & EPG_FLAG_ANON) != 0;
2073
2074                 off = m->m_epg_1st_off;
2075                 for (i = 0; i < m->m_epg_npgs; i++, off = 0) {
2076                         len = m_epg_pagelen(m, i, off);
2077                         src_iov[i].iov_len = len;
2078                         src_iov[i].iov_base =
2079                             (char *)(void *)PHYS_TO_DMAP(m->m_epg_pa[i]) +
2080                                 off;
2081
2082                         if (is_anon) {
2083                                 dst_iov[i].iov_base = src_iov[i].iov_base;
2084                                 dst_iov[i].iov_len = src_iov[i].iov_len;
2085                                 continue;
2086                         }
2087 retry_page:
2088                         pg = vm_page_alloc_noobj(VM_ALLOC_NODUMP |
2089                             VM_ALLOC_WIRED);
2090                         if (pg == NULL) {
2091                                 vm_wait(NULL);
2092                                 goto retry_page;
2093                         }
2094                         parray[i] = VM_PAGE_TO_PHYS(pg);
2095                         dst_iov[i].iov_base =
2096                             (char *)(void *)PHYS_TO_DMAP(parray[i]) + off;
2097                         dst_iov[i].iov_len = len;
2098                 }
2099
2100                 npages += m->m_epg_nrdy;
2101
2102                 error = (*tls->sw_encrypt)(tls,
2103                     (const struct tls_record_layer *)m->m_epg_hdr,
2104                     m->m_epg_trail, src_iov, dst_iov, i, m->m_epg_seqno,
2105                     m->m_epg_record_type);
2106                 if (error) {
2107                         counter_u64_add(ktls_offload_failed_crypto, 1);
2108                         break;
2109                 }
2110
2111                 /*
2112                  * For file-backed mbufs, release the file-backed
2113                  * pages and replace them in the ext_pgs array with
2114                  * the anonymous wired pages allocated above.
2115                  */
2116                 if (!is_anon) {
2117                         /* Free the old pages. */
2118                         m->m_ext.ext_free(m);
2119
2120                         /* Replace them with the new pages. */
2121                         for (i = 0; i < m->m_epg_npgs; i++)
2122                                 m->m_epg_pa[i] = parray[i];
2123
2124                         /* Use the basic free routine. */
2125                         m->m_ext.ext_free = mb_free_mext_pgs;
2126
2127                         /* Pages are now writable. */
2128                         m->m_epg_flags |= EPG_FLAG_ANON;
2129                 }
2130
2131                 /*
2132                  * Drop a reference to the session now that it is no
2133                  * longer needed.  Existing code depends on encrypted
2134                  * records having no associated session vs
2135                  * yet-to-be-encrypted records having an associated
2136                  * session.
2137                  */
2138                 m->m_epg_tls = NULL;
2139                 ktls_free(tls);
2140         }
2141
2142         CURVNET_SET(so->so_vnet);
2143         if (error == 0) {
2144                 (void)(*so->so_proto->pr_usrreqs->pru_ready)(so, top, npages);
2145         } else {
2146                 so->so_proto->pr_usrreqs->pru_abort(so);
2147                 so->so_error = EIO;
2148                 mb_free_notready(top, total_pages);
2149         }
2150
2151         SOCK_LOCK(so);
2152         sorele(so);
2153         CURVNET_RESTORE();
2154 }
2155
2156 static void
2157 ktls_work_thread(void *ctx)
2158 {
2159         struct ktls_wq *wq = ctx;
2160         struct mbuf *m, *n;
2161         struct socket *so, *son;
2162         STAILQ_HEAD(, mbuf) local_m_head;
2163         STAILQ_HEAD(, socket) local_so_head;
2164
2165         if (ktls_bind_threads > 1) {
2166                 curthread->td_domain.dr_policy =
2167                         DOMAINSET_PREF(PCPU_GET(domain));
2168         }
2169 #if defined(__aarch64__) || defined(__amd64__) || defined(__i386__)
2170         fpu_kern_thread(0);
2171 #endif
2172         for (;;) {
2173                 mtx_lock(&wq->mtx);
2174                 while (STAILQ_EMPTY(&wq->m_head) &&
2175                     STAILQ_EMPTY(&wq->so_head)) {
2176                         wq->running = false;
2177                         mtx_sleep(wq, &wq->mtx, 0, "-", 0);
2178                         wq->running = true;
2179                 }
2180
2181                 STAILQ_INIT(&local_m_head);
2182                 STAILQ_CONCAT(&local_m_head, &wq->m_head);
2183                 STAILQ_INIT(&local_so_head);
2184                 STAILQ_CONCAT(&local_so_head, &wq->so_head);
2185                 mtx_unlock(&wq->mtx);
2186
2187                 STAILQ_FOREACH_SAFE(m, &local_m_head, m_epg_stailq, n) {
2188                         if (m->m_epg_flags & EPG_FLAG_2FREE) {
2189                                 ktls_free(m->m_epg_tls);
2190                                 m_free_raw(m);
2191                         } else {
2192                                 ktls_encrypt(m);
2193                                 counter_u64_add(ktls_cnt_tx_queued, -1);
2194                         }
2195                 }
2196
2197                 STAILQ_FOREACH_SAFE(so, &local_so_head, so_ktls_rx_list, son) {
2198                         ktls_decrypt(so);
2199                         counter_u64_add(ktls_cnt_rx_queued, -1);
2200                 }
2201         }
2202 }