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