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