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