]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/cxgbe/tom/t4_tls.c
cxgbe tom: Remove orphaned function max_imm_tls_space().
[FreeBSD/FreeBSD.git] / sys / dev / cxgbe / tom / t4_tls.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2017-2018 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: John Baldwin <jhb@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #include "opt_inet.h"
31 #include "opt_kern_tls.h"
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 #ifdef KERN_TLS
37 #include <sys/param.h>
38 #include <sys/ktr.h>
39 #include <sys/ktls.h>
40 #include <sys/sglist.h>
41 #include <sys/socket.h>
42 #include <sys/socketvar.h>
43 #include <sys/systm.h>
44 #include <netinet/in.h>
45 #include <netinet/in_pcb.h>
46 #include <netinet/tcp_var.h>
47 #include <netinet/toecore.h>
48 #include <opencrypto/cryptodev.h>
49 #include <opencrypto/xform.h>
50
51 #ifdef TCP_OFFLOAD
52 #include "common/common.h"
53 #include "common/t4_tcb.h"
54 #include "crypto/t4_crypto.h"
55 #include "tom/t4_tom_l2t.h"
56 #include "tom/t4_tom.h"
57
58 /*
59  * The TCP sequence number of a CPL_TLS_DATA mbuf is saved here while
60  * the mbuf is in the ulp_pdu_reclaimq.
61  */
62 #define tls_tcp_seq     PH_loc.thirtytwo[0]
63
64 static void
65 t4_set_tls_tcb_field(struct toepcb *toep, uint16_t word, uint64_t mask,
66     uint64_t val)
67 {
68         struct adapter *sc = td_adapter(toep->td);
69
70         t4_set_tcb_field(sc, &toep->ofld_txq->wrq, toep, word, mask, val, 0, 0);
71 }
72
73 /* TLS and DTLS common routines */
74 bool
75 can_tls_offload(struct adapter *sc)
76 {
77
78         return (sc->tt.tls && sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS);
79 }
80
81 int
82 tls_tx_key(struct toepcb *toep)
83 {
84         struct tls_ofld_info *tls_ofld = &toep->tls;
85
86         return (tls_ofld->tx_key_addr >= 0);
87 }
88
89 /* Set TLS Key-Id in TCB */
90 static void
91 t4_set_tls_keyid(struct toepcb *toep, unsigned int key_id)
92 {
93
94         t4_set_tls_tcb_field(toep, W_TCB_RX_TLS_KEY_TAG,
95                          V_TCB_RX_TLS_KEY_TAG(M_TCB_RX_TLS_BUF_TAG),
96                          V_TCB_RX_TLS_KEY_TAG(key_id));
97 }
98
99 /* Clear TF_RX_QUIESCE to re-enable receive. */
100 static void
101 t4_clear_rx_quiesce(struct toepcb *toep)
102 {
103
104         t4_set_tls_tcb_field(toep, W_TCB_T_FLAGS, V_TF_RX_QUIESCE(1), 0);
105 }
106
107 static void
108 tls_clr_ofld_mode(struct toepcb *toep)
109 {
110
111         tls_stop_handshake_timer(toep);
112
113         KASSERT(toep->tls.rx_key_addr == -1,
114             ("%s: tid %d has RX key", __func__, toep->tid));
115
116         /* Switch to plain TOE mode. */
117         t4_set_tls_tcb_field(toep, W_TCB_ULP_RAW,
118             V_TCB_ULP_RAW(V_TF_TLS_ENABLE(1)),
119             V_TCB_ULP_RAW(V_TF_TLS_ENABLE(0)));
120         t4_set_tls_tcb_field(toep, W_TCB_ULP_TYPE,
121             V_TCB_ULP_TYPE(M_TCB_ULP_TYPE), V_TCB_ULP_TYPE(ULP_MODE_NONE));
122         t4_clear_rx_quiesce(toep);
123
124         toep->flags &= ~(TPF_FORCE_CREDITS | TPF_TLS_ESTABLISHED);
125         toep->params.ulp_mode = ULP_MODE_NONE;
126 }
127
128 /* TLS/DTLS content type  for CPL SFO */
129 static inline unsigned char
130 tls_content_type(unsigned char content_type)
131 {
132         switch (content_type) {
133         case CONTENT_TYPE_CCS:
134                 return CPL_TX_TLS_SFO_TYPE_CCS;
135         case CONTENT_TYPE_ALERT:
136                 return CPL_TX_TLS_SFO_TYPE_ALERT;
137         case CONTENT_TYPE_HANDSHAKE:
138                 return CPL_TX_TLS_SFO_TYPE_HANDSHAKE;
139         case CONTENT_TYPE_APP_DATA:
140                 return CPL_TX_TLS_SFO_TYPE_DATA;
141         default:
142                 return CPL_TX_TLS_SFO_TYPE_CUSTOM;
143         }
144 }
145
146 static int
147 tls_key_info_size(struct ktls_session *tls)
148 {
149         u_int key_info_size, mac_key_size;
150
151         key_info_size = sizeof(struct tx_keyctx_hdr) +
152             tls->params.cipher_key_len;
153         if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16) {
154                 key_info_size += GMAC_BLOCK_LEN;
155         } else {
156                 switch (tls->params.auth_algorithm) {
157                 case CRYPTO_SHA1_HMAC:
158                         mac_key_size = SHA1_HASH_LEN;
159                         break;
160                 case CRYPTO_SHA2_256_HMAC:
161                         mac_key_size = SHA2_256_HASH_LEN;
162                         break;
163                 case CRYPTO_SHA2_384_HMAC:
164                         mac_key_size = SHA2_512_HASH_LEN;
165                         break;
166                 default:
167                         __assert_unreachable();
168                 }
169                 key_info_size += roundup2(mac_key_size, 16) * 2;
170         }
171         return (key_info_size);
172 }
173
174 static int
175 tls_proto_ver(struct ktls_session *tls)
176 {
177         if (tls->params.tls_vminor == TLS_MINOR_VER_ONE)
178                 return (SCMD_PROTO_VERSION_TLS_1_1);
179         else
180                 return (SCMD_PROTO_VERSION_TLS_1_2);
181 }
182
183 static int
184 tls_cipher_mode(struct ktls_session *tls)
185 {
186         switch (tls->params.cipher_algorithm) {
187         case CRYPTO_AES_CBC:
188                 return (SCMD_CIPH_MODE_AES_CBC);
189         case CRYPTO_AES_NIST_GCM_16:
190                 return (SCMD_CIPH_MODE_AES_GCM);
191         default:
192                 return (SCMD_CIPH_MODE_NOP);
193         }
194 }
195
196 static int
197 tls_auth_mode(struct ktls_session *tls)
198 {
199         switch (tls->params.cipher_algorithm) {
200         case CRYPTO_AES_CBC:
201                 switch (tls->params.auth_algorithm) {
202                 case CRYPTO_SHA1_HMAC:
203                         return (SCMD_AUTH_MODE_SHA1);
204                 case CRYPTO_SHA2_256_HMAC:
205                         return (SCMD_AUTH_MODE_SHA256);
206                 case CRYPTO_SHA2_384_HMAC:
207                         return (SCMD_AUTH_MODE_SHA512_384);
208                 default:
209                         return (SCMD_AUTH_MODE_NOP);
210                 }
211         case CRYPTO_AES_NIST_GCM_16:
212                 return (SCMD_AUTH_MODE_GHASH);
213         default:
214                 return (SCMD_AUTH_MODE_NOP);
215         }
216 }
217
218 static int
219 tls_hmac_ctrl(struct ktls_session *tls)
220 {
221         switch (tls->params.cipher_algorithm) {
222         case CRYPTO_AES_CBC:
223                 return (SCMD_HMAC_CTRL_NO_TRUNC);
224         case CRYPTO_AES_NIST_GCM_16:
225                 return (SCMD_HMAC_CTRL_NOP);
226         default:
227                 return (SCMD_HMAC_CTRL_NOP);
228         }
229 }
230
231 static int
232 tls_cipher_key_size(struct ktls_session *tls)
233 {
234         switch (tls->params.cipher_key_len) {
235         case 128 / 8:
236                 return (CHCR_KEYCTX_CIPHER_KEY_SIZE_128);
237         case 192 / 8:
238                 return (CHCR_KEYCTX_CIPHER_KEY_SIZE_192);
239         case 256 / 8:
240                 return (CHCR_KEYCTX_CIPHER_KEY_SIZE_256);
241         default:
242                 __assert_unreachable();
243         }
244 }
245
246 static int
247 tls_mac_key_size(struct ktls_session *tls)
248 {
249         if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16)
250                 /*
251                  * XXX: This used to use 128 (SHA_NOP) for TOE,
252                  * but NIC TLS has always used 512.
253                  */
254                 return (CHCR_KEYCTX_MAC_KEY_SIZE_512);
255         else {
256                 switch (tls->params.auth_algorithm) {
257                 case CRYPTO_SHA1_HMAC:
258                         return (CHCR_KEYCTX_MAC_KEY_SIZE_160);
259                 case CRYPTO_SHA2_256_HMAC:
260                         return (CHCR_KEYCTX_MAC_KEY_SIZE_256);
261                 case CRYPTO_SHA2_384_HMAC:
262                         return (CHCR_KEYCTX_MAC_KEY_SIZE_512);
263                 default:
264                         __assert_unreachable();
265                 }
266         }
267 }
268
269 static void
270 prepare_tls_keys(char *key, char *salt, struct ktls_session *tls,
271     int direction)
272 {
273         struct auth_hash *axf;
274         u_int mac_key_size;
275         char *hash;
276
277         if (direction == KTLS_RX &&
278             tls->params.cipher_algorithm == CRYPTO_AES_CBC)
279                 t4_aes_getdeckey(key, tls->params.cipher_key,
280                     tls->params.cipher_key_len * 8);
281         else
282                 memcpy(key, tls->params.cipher_key,
283                     tls->params.cipher_key_len);
284         hash = key + tls->params.cipher_key_len;
285         if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16) {
286                 memcpy(salt, tls->params.iv, SALT_SIZE);
287                 t4_init_gmac_hash(tls->params.cipher_key,
288                     tls->params.cipher_key_len, hash);
289         } else {
290                 switch (tls->params.auth_algorithm) {
291                 case CRYPTO_SHA1_HMAC:
292                         axf = &auth_hash_hmac_sha1;
293                         mac_key_size = SHA1_HASH_LEN;
294                         break;
295                 case CRYPTO_SHA2_256_HMAC:
296                         axf = &auth_hash_hmac_sha2_256;
297                         mac_key_size = SHA2_256_HASH_LEN;
298                         break;
299                 case CRYPTO_SHA2_384_HMAC:
300                         axf = &auth_hash_hmac_sha2_384;
301                         mac_key_size = SHA2_512_HASH_LEN;
302                         break;
303                 default:
304                         __assert_unreachable();
305                 }
306                 t4_init_hmac_digest(axf, mac_key_size, tls->params.auth_key,
307                     tls->params.auth_key_len, hash);
308         }
309 }
310
311 /* Rx key */
312 static void
313 prepare_rxkey_wr(struct tls_keyctx *kwr, struct ktls_session *tls)
314 {
315
316         kwr->u.rxhdr.flitcnt_hmacctrl =
317                 ((tls_key_info_size(tls) / 16) << 3) | tls_hmac_ctrl(tls);
318
319         kwr->u.rxhdr.protover_ciphmode =
320                 V_TLS_KEYCTX_TX_WR_PROTOVER(tls_proto_ver(tls)) |
321                 V_TLS_KEYCTX_TX_WR_CIPHMODE(tls_cipher_mode(tls));
322
323         kwr->u.rxhdr.authmode_to_rxvalid =
324                 V_TLS_KEYCTX_TX_WR_AUTHMODE(tls_auth_mode(tls)) |
325                 V_TLS_KEYCTX_TX_WR_SEQNUMCTRL(3) |
326                 V_TLS_KEYCTX_TX_WR_RXVALID(1);
327
328         kwr->u.rxhdr.ivpresent_to_rxmk_size =
329                 V_TLS_KEYCTX_TX_WR_IVPRESENT(0) |
330                 V_TLS_KEYCTX_TX_WR_RXCK_SIZE(tls_cipher_key_size(tls)) |
331                 V_TLS_KEYCTX_TX_WR_RXMK_SIZE(tls_mac_key_size(tls));
332
333         if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16) {
334                 kwr->u.rxhdr.ivinsert_to_authinsrt =
335                     htobe64(V_TLS_KEYCTX_TX_WR_IVINSERT(6ULL) |
336                         V_TLS_KEYCTX_TX_WR_AADSTRTOFST(1ULL) |
337                         V_TLS_KEYCTX_TX_WR_AADSTOPOFST(5ULL) |
338                         V_TLS_KEYCTX_TX_WR_AUTHSRTOFST(14ULL) |
339                         V_TLS_KEYCTX_TX_WR_AUTHSTOPOFST(16ULL) |
340                         V_TLS_KEYCTX_TX_WR_CIPHERSRTOFST(14ULL) |
341                         V_TLS_KEYCTX_TX_WR_CIPHERSTOPOFST(0ULL) |
342                         V_TLS_KEYCTX_TX_WR_AUTHINSRT(16ULL));
343         } else {
344                 kwr->u.rxhdr.authmode_to_rxvalid |=
345                         V_TLS_KEYCTX_TX_WR_CIPHAUTHSEQCTRL(1);
346                 kwr->u.rxhdr.ivpresent_to_rxmk_size |=
347                         V_TLS_KEYCTX_TX_WR_RXOPAD_PRESENT(1);
348                 kwr->u.rxhdr.ivinsert_to_authinsrt =
349                     htobe64(V_TLS_KEYCTX_TX_WR_IVINSERT(6ULL) |
350                         V_TLS_KEYCTX_TX_WR_AADSTRTOFST(1ULL) |
351                         V_TLS_KEYCTX_TX_WR_AADSTOPOFST(5ULL) |
352                         V_TLS_KEYCTX_TX_WR_AUTHSRTOFST(22ULL) |
353                         V_TLS_KEYCTX_TX_WR_AUTHSTOPOFST(0ULL) |
354                         V_TLS_KEYCTX_TX_WR_CIPHERSRTOFST(22ULL) |
355                         V_TLS_KEYCTX_TX_WR_CIPHERSTOPOFST(0ULL) |
356                         V_TLS_KEYCTX_TX_WR_AUTHINSRT(0ULL));
357         }
358
359         prepare_tls_keys(kwr->keys.edkey, kwr->u.rxhdr.rxsalt, tls, KTLS_RX);
360 }
361
362 /* Tx key */
363 static void
364 prepare_txkey_wr(struct tls_keyctx *kwr, struct ktls_session *tls)
365 {
366
367         kwr->u.txhdr.ctxlen = tls_key_info_size(tls) / 16;
368         kwr->u.txhdr.dualck_to_txvalid =
369                 V_TLS_KEYCTX_TX_WR_SALT_PRESENT(1) |
370                 V_TLS_KEYCTX_TX_WR_TXCK_SIZE(tls_cipher_key_size(tls)) |
371                 V_TLS_KEYCTX_TX_WR_TXMK_SIZE(tls_mac_key_size(tls)) |
372                 V_TLS_KEYCTX_TX_WR_TXVALID(1);
373         if (tls->params.cipher_algorithm == CRYPTO_AES_CBC)
374                 kwr->u.txhdr.dualck_to_txvalid |=
375                     V_TLS_KEYCTX_TX_WR_TXOPAD_PRESENT(1);
376         kwr->u.txhdr.dualck_to_txvalid = htons(kwr->u.txhdr.dualck_to_txvalid);
377
378         prepare_tls_keys(kwr->keys.edkey, kwr->u.txhdr.txsalt, tls, KTLS_TX);
379 }
380
381 /* TLS Key memory management */
382 static int
383 get_new_keyid(struct toepcb *toep)
384 {
385         struct adapter *sc = td_adapter(toep->td);
386         vmem_addr_t addr;
387
388         if (vmem_alloc(sc->key_map, TLS_KEY_CONTEXT_SZ, M_NOWAIT | M_FIRSTFIT,
389             &addr) != 0)
390                 return (-1);
391
392         return (addr);
393 }
394
395 static void
396 free_keyid(struct toepcb *toep, int keyid)
397 {
398         struct adapter *sc = td_adapter(toep->td);
399
400         vmem_free(sc->key_map, keyid, TLS_KEY_CONTEXT_SZ);
401 }
402
403 static void
404 clear_tls_keyid(struct toepcb *toep)
405 {
406         struct tls_ofld_info *tls_ofld = &toep->tls;
407
408         if (tls_ofld->rx_key_addr >= 0) {
409                 free_keyid(toep, tls_ofld->rx_key_addr);
410                 tls_ofld->rx_key_addr = -1;
411         }
412         if (tls_ofld->tx_key_addr >= 0) {
413                 free_keyid(toep, tls_ofld->tx_key_addr);
414                 tls_ofld->tx_key_addr = -1;
415         }
416 }
417
418 static int
419 get_tp_plen_max(struct ktls_session *tls)
420 {
421         int plen = ((min(3*4096, TP_TX_PG_SZ))/1448) * 1448;
422
423         return (tls->params.max_frame_len <= 8192 ? plen : FC_TP_PLEN_MAX);
424 }
425
426 /* Send request to get the key-id */
427 static int
428 tls_program_key_id(struct toepcb *toep, struct ktls_session *tls,
429     int direction)
430 {
431         struct tls_ofld_info *tls_ofld = &toep->tls;
432         struct adapter *sc = td_adapter(toep->td);
433         struct ofld_tx_sdesc *txsd;
434         int kwrlen, kctxlen, keyid, len;
435         struct wrqe *wr;
436         struct tls_key_req *kwr;
437         struct tls_keyctx *kctx;
438
439         kwrlen = sizeof(*kwr);
440         kctxlen = roundup2(sizeof(*kctx), 32);
441         len = roundup2(kwrlen + kctxlen, 16);
442
443         if (toep->txsd_avail == 0)
444                 return (EAGAIN);
445
446         if ((keyid = get_new_keyid(toep)) < 0) {
447                 return (ENOSPC);
448         }
449
450         wr = alloc_wrqe(len, &toep->ofld_txq->wrq);
451         if (wr == NULL) {
452                 free_keyid(toep, keyid);
453                 return (ENOMEM);
454         }
455         kwr = wrtod(wr);
456         memset(kwr, 0, kwrlen);
457
458         kwr->wr_hi = htobe32(V_FW_WR_OP(FW_ULPTX_WR) | F_FW_WR_COMPL |
459             F_FW_WR_ATOMIC);
460         kwr->wr_mid = htobe32(V_FW_WR_LEN16(DIV_ROUND_UP(len, 16)) |
461             V_FW_WR_FLOWID(toep->tid));
462         kwr->protocol = tls_proto_ver(tls);
463         kwr->mfs = htons(tls->params.max_frame_len);
464         kwr->reneg_to_write_rx = V_KEY_GET_LOC(direction == KTLS_TX ?
465             KEY_WRITE_TX : KEY_WRITE_RX);
466
467         /* master command */
468         kwr->cmd = htobe32(V_ULPTX_CMD(ULP_TX_MEM_WRITE) |
469             V_T5_ULP_MEMIO_ORDER(1) | V_T5_ULP_MEMIO_IMM(1));
470         kwr->dlen = htobe32(V_ULP_MEMIO_DATA_LEN(kctxlen >> 5));
471         kwr->len16 = htobe32((toep->tid << 8) |
472             DIV_ROUND_UP(len - sizeof(struct work_request_hdr), 16));
473         kwr->kaddr = htobe32(V_ULP_MEMIO_ADDR(keyid >> 5));
474
475         /* sub command */
476         kwr->sc_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_IMM));
477         kwr->sc_len = htobe32(kctxlen);
478
479         kctx = (struct tls_keyctx *)(kwr + 1);
480         memset(kctx, 0, kctxlen);
481
482         if (direction == KTLS_TX) {
483                 tls_ofld->tx_key_addr = keyid;
484                 prepare_txkey_wr(kctx, tls);
485         } else {
486                 tls_ofld->rx_key_addr = keyid;
487                 prepare_rxkey_wr(kctx, tls);
488         }
489
490         txsd = &toep->txsd[toep->txsd_pidx];
491         txsd->tx_credits = DIV_ROUND_UP(len, 16);
492         txsd->plen = 0;
493         toep->tx_credits -= txsd->tx_credits;
494         if (__predict_false(++toep->txsd_pidx == toep->txsd_total))
495                 toep->txsd_pidx = 0;
496         toep->txsd_avail--;
497
498         t4_wrq_tx(sc, wr);
499
500         return (0);
501 }
502
503 /*
504  * In some cases a client connection can hang without sending the
505  * ServerHelloDone message from the NIC to the host.  Send a dummy
506  * RX_DATA_ACK with RX_MODULATE to unstick the connection.
507  */
508 static void
509 tls_send_handshake_ack(void *arg)
510 {
511         struct toepcb *toep = arg;
512         struct tls_ofld_info *tls_ofld = &toep->tls;
513         struct adapter *sc = td_adapter(toep->td);
514
515         /* Bail without rescheduling if the connection has closed. */
516         if ((toep->flags & (TPF_FIN_SENT | TPF_ABORT_SHUTDOWN)) != 0)
517                 return;
518
519         /*
520          * If this connection has timed out without receiving more
521          * data, downgrade to plain TOE mode and don't re-arm the
522          * timer.
523          */
524         if (sc->tt.tls_rx_timeout != 0) {
525                 struct inpcb *inp;
526                 struct tcpcb *tp;
527
528                 inp = toep->inp;
529                 tp = intotcpcb(inp);
530                 if ((ticks - tp->t_rcvtime) >= sc->tt.tls_rx_timeout) {
531                         CTR2(KTR_CXGBE, "%s: tid %d clr_ofld_mode", __func__,
532                             toep->tid);
533                         tls_clr_ofld_mode(toep);
534                         return;
535                 }
536         }
537
538         /*
539          * XXX: Does not have the t4_get_tcb() checks to refine the
540          * workaround.
541          */
542         callout_schedule(&tls_ofld->handshake_timer, TLS_SRV_HELLO_RD_TM * hz);
543
544         CTR2(KTR_CXGBE, "%s: tid %d sending RX_DATA_ACK", __func__, toep->tid);
545         send_rx_modulate(sc, toep);
546 }
547
548 static void
549 tls_start_handshake_timer(struct toepcb *toep)
550 {
551         struct tls_ofld_info *tls_ofld = &toep->tls;
552
553         INP_WLOCK_ASSERT(toep->inp);
554         callout_reset(&tls_ofld->handshake_timer, TLS_SRV_HELLO_BKOFF_TM * hz,
555             tls_send_handshake_ack, toep);
556 }
557
558 void
559 tls_stop_handshake_timer(struct toepcb *toep)
560 {
561         struct tls_ofld_info *tls_ofld = &toep->tls;
562
563         INP_WLOCK_ASSERT(toep->inp);
564         callout_stop(&tls_ofld->handshake_timer);
565 }
566
567 int
568 tls_alloc_ktls(struct toepcb *toep, struct ktls_session *tls, int direction)
569 {
570         struct adapter *sc = td_adapter(toep->td);
571         int error, explicit_iv_size, key_offset, mac_first;
572
573         if (!can_tls_offload(td_adapter(toep->td)))
574                 return (EINVAL);
575         switch (ulp_mode(toep)) {
576         case ULP_MODE_TLS:
577                 break;
578         case ULP_MODE_NONE:
579         case ULP_MODE_TCPDDP:
580                 if (direction != KTLS_TX)
581                         return (EINVAL);
582                 break;
583         default:
584                 return (EINVAL);
585         }
586
587         switch (tls->params.cipher_algorithm) {
588         case CRYPTO_AES_CBC:
589                 /* XXX: Explicitly ignore any provided IV. */
590                 switch (tls->params.cipher_key_len) {
591                 case 128 / 8:
592                 case 192 / 8:
593                 case 256 / 8:
594                         break;
595                 default:
596                         error = EINVAL;
597                         goto clr_ofld;
598                 }
599                 switch (tls->params.auth_algorithm) {
600                 case CRYPTO_SHA1_HMAC:
601                 case CRYPTO_SHA2_256_HMAC:
602                 case CRYPTO_SHA2_384_HMAC:
603                         break;
604                 default:
605                         error = EPROTONOSUPPORT;
606                         goto clr_ofld;
607                 }
608                 explicit_iv_size = AES_BLOCK_LEN;
609                 mac_first = 1;
610                 break;
611         case CRYPTO_AES_NIST_GCM_16:
612                 if (tls->params.iv_len != SALT_SIZE) {
613                         error = EINVAL;
614                         goto clr_ofld;
615                 }
616                 switch (tls->params.cipher_key_len) {
617                 case 128 / 8:
618                 case 192 / 8:
619                 case 256 / 8:
620                         break;
621                 default:
622                         error = EINVAL;
623                         goto clr_ofld;
624                 }
625                 explicit_iv_size = 8;
626                 mac_first = 0;
627                 break;
628         default:
629                 error = EPROTONOSUPPORT;
630                 goto clr_ofld;
631         }
632
633         /* Only TLS 1.1 and TLS 1.2 are currently supported. */
634         if (tls->params.tls_vmajor != TLS_MAJOR_VER_ONE ||
635             tls->params.tls_vminor < TLS_MINOR_VER_ONE ||
636             tls->params.tls_vminor > TLS_MINOR_VER_TWO) {
637                 error = EPROTONOSUPPORT;
638                 goto clr_ofld;
639         }
640
641         /* Bail if we already have a key. */
642         if (direction == KTLS_TX) {
643                 if (toep->tls.tx_key_addr != -1)
644                         return (EOPNOTSUPP);
645         } else {
646                 if (toep->tls.rx_key_addr != -1)
647                         return (EOPNOTSUPP);
648         }
649
650         error = tls_program_key_id(toep, tls, direction);
651         if (error) {
652                 if (direction == KTLS_RX)
653                         goto clr_ofld;
654                 return (error);
655         }
656
657         if (direction == KTLS_TX) {
658                 toep->tls.scmd0.seqno_numivs =
659                         (V_SCMD_SEQ_NO_CTRL(3) |
660                          V_SCMD_PROTO_VERSION(tls_proto_ver(tls)) |
661                          V_SCMD_ENC_DEC_CTRL(SCMD_ENCDECCTRL_ENCRYPT) |
662                          V_SCMD_CIPH_AUTH_SEQ_CTRL((mac_first == 0)) |
663                          V_SCMD_CIPH_MODE(tls_cipher_mode(tls)) |
664                          V_SCMD_AUTH_MODE(tls_auth_mode(tls)) |
665                          V_SCMD_HMAC_CTRL(tls_hmac_ctrl(tls)) |
666                          V_SCMD_IV_SIZE(explicit_iv_size / 2));
667
668                 toep->tls.scmd0.ivgen_hdrlen =
669                         (V_SCMD_IV_GEN_CTRL(1) |
670                          V_SCMD_KEY_CTX_INLINE(0) |
671                          V_SCMD_TLS_FRAG_ENABLE(1));
672
673                 if (tls->params.cipher_algorithm == CRYPTO_AES_NIST_GCM_16)
674                         toep->tls.iv_len = 8;
675                 else
676                         toep->tls.iv_len = AES_BLOCK_LEN;
677
678                 toep->tls.frag_size = tls->params.max_frame_len;
679                 toep->tls.fcplenmax = get_tp_plen_max(tls);
680                 toep->tls.expn_per_ulp = tls->params.tls_hlen +
681                     tls->params.tls_tlen;
682                 toep->tls.pdus_per_ulp = 1;
683                 toep->tls.adjusted_plen = toep->tls.expn_per_ulp +
684                     tls->params.max_frame_len;
685                 toep->tls.tx_key_info_size = tls_key_info_size(tls);
686         } else {
687                 /* Stop timer on handshake completion */
688                 tls_stop_handshake_timer(toep);
689
690                 toep->flags &= ~TPF_FORCE_CREDITS;
691                 toep->flags |= TPF_TLS_RECEIVE;
692                 toep->tls.rx_version = tls->params.tls_vmajor << 8 |
693                     tls->params.tls_vminor;
694
695                 /*
696                  * RX key tags are an index into the key portion of MA
697                  * memory stored as an offset from the base address in
698                  * units of 64 bytes.
699                  */
700                 key_offset = toep->tls.rx_key_addr - sc->vres.key.start;
701                 t4_set_tls_keyid(toep, key_offset / 64);
702                 t4_set_tls_tcb_field(toep, W_TCB_ULP_RAW,
703                                  V_TCB_ULP_RAW(M_TCB_ULP_RAW),
704                                  V_TCB_ULP_RAW((V_TF_TLS_KEY_SIZE(3) |
705                                                 V_TF_TLS_CONTROL(1) |
706                                                 V_TF_TLS_ACTIVE(1) |
707                                                 V_TF_TLS_ENABLE(1))));
708                 t4_set_tls_tcb_field(toep, W_TCB_TLS_SEQ,
709                                  V_TCB_TLS_SEQ(M_TCB_TLS_SEQ),
710                                  V_TCB_TLS_SEQ(0));
711                 t4_clear_rx_quiesce(toep);
712         }
713
714         return (0);
715
716 clr_ofld:
717         if (ulp_mode(toep) == ULP_MODE_TLS) {
718                 CTR2(KTR_CXGBE, "%s: tid %d clr_ofld_mode", __func__,
719                     toep->tid);
720                 tls_clr_ofld_mode(toep);
721         }
722         return (error);
723 }
724
725 void
726 tls_init_toep(struct toepcb *toep)
727 {
728         struct tls_ofld_info *tls_ofld = &toep->tls;
729
730         tls_ofld->rx_key_addr = -1;
731         tls_ofld->tx_key_addr = -1;
732 }
733
734 void
735 tls_establish(struct toepcb *toep)
736 {
737
738         /*
739          * Enable PDU extraction.
740          *
741          * XXX: Supposedly this should be done by the firmware when
742          * the ULP_MODE FLOWC parameter is set in send_flowc_wr(), but
743          * in practice this seems to be required.
744          */
745         CTR2(KTR_CXGBE, "%s: tid %d setting TLS_ENABLE", __func__, toep->tid);
746         t4_set_tls_tcb_field(toep, W_TCB_ULP_RAW, V_TCB_ULP_RAW(M_TCB_ULP_RAW),
747             V_TCB_ULP_RAW(V_TF_TLS_ENABLE(1)));
748
749         toep->flags |= TPF_FORCE_CREDITS | TPF_TLS_ESTABLISHED;
750
751         callout_init_rw(&toep->tls.handshake_timer, &toep->inp->inp_lock, 0);
752         tls_start_handshake_timer(toep);
753 }
754
755 void
756 tls_detach(struct toepcb *toep)
757 {
758
759         if (toep->flags & TPF_TLS_ESTABLISHED) {
760                 tls_stop_handshake_timer(toep);
761                 toep->flags &= ~TPF_TLS_ESTABLISHED;
762         }
763 }
764
765 void
766 tls_uninit_toep(struct toepcb *toep)
767 {
768
769         MPASS((toep->flags & TPF_TLS_ESTABLISHED) == 0);
770         clear_tls_keyid(toep);
771 }
772
773 #define MAX_OFLD_TX_CREDITS (SGE_MAX_WR_LEN / 16)
774 #define MIN_OFLD_TLSTX_CREDITS(toep)                                    \
775         (howmany(sizeof(struct fw_tlstx_data_wr) +                      \
776             sizeof(struct cpl_tx_tls_sfo) + sizeof(struct ulptx_idata) + \
777             sizeof(struct ulptx_sc_memrd) +                             \
778             AES_BLOCK_LEN + 1, 16))
779
780 static void
781 write_tlstx_wr(struct fw_tlstx_data_wr *txwr, struct toepcb *toep,
782     unsigned int immdlen, unsigned int plen, unsigned int expn,
783     unsigned int pdus, uint8_t credits, int shove, int imm_ivs)
784 {
785         struct tls_ofld_info *tls_ofld = &toep->tls;
786         unsigned int len = plen + expn;
787
788         txwr->op_to_immdlen = htobe32(V_WR_OP(FW_TLSTX_DATA_WR) |
789             V_FW_TLSTX_DATA_WR_COMPL(1) |
790             V_FW_TLSTX_DATA_WR_IMMDLEN(immdlen));
791         txwr->flowid_len16 = htobe32(V_FW_TLSTX_DATA_WR_FLOWID(toep->tid) |
792             V_FW_TLSTX_DATA_WR_LEN16(credits));
793         txwr->plen = htobe32(len);
794         txwr->lsodisable_to_flags = htobe32(V_TX_ULP_MODE(ULP_MODE_TLS) |
795             V_TX_URG(0) | /* F_T6_TX_FORCE | */ V_TX_SHOVE(shove));
796         txwr->ctxloc_to_exp = htobe32(V_FW_TLSTX_DATA_WR_NUMIVS(pdus) |
797             V_FW_TLSTX_DATA_WR_EXP(expn) |
798             V_FW_TLSTX_DATA_WR_CTXLOC(TLS_SFO_WR_CONTEXTLOC_DDR) |
799             V_FW_TLSTX_DATA_WR_IVDSGL(!imm_ivs) |
800             V_FW_TLSTX_DATA_WR_KEYSIZE(tls_ofld->tx_key_info_size >> 4));
801         txwr->mfs = htobe16(tls_ofld->frag_size);
802         txwr->adjustedplen_pkd = htobe16(
803             V_FW_TLSTX_DATA_WR_ADJUSTEDPLEN(tls_ofld->adjusted_plen));
804         txwr->expinplenmax_pkd = htobe16(
805             V_FW_TLSTX_DATA_WR_EXPINPLENMAX(tls_ofld->expn_per_ulp));
806         txwr->pdusinplenmax_pkd = 
807             V_FW_TLSTX_DATA_WR_PDUSINPLENMAX(tls_ofld->pdus_per_ulp);
808 }
809
810 static void
811 write_tlstx_cpl(struct cpl_tx_tls_sfo *cpl, struct toepcb *toep,
812     struct tls_hdr *tls_hdr, unsigned int plen, unsigned int pdus)
813 {
814         struct tls_ofld_info *tls_ofld = &toep->tls;
815         int data_type, seglen;
816
817         if (plen < tls_ofld->frag_size)
818                 seglen = plen;
819         else
820                 seglen = tls_ofld->frag_size;
821         data_type = tls_content_type(tls_hdr->type);
822         cpl->op_to_seg_len = htobe32(V_CPL_TX_TLS_SFO_OPCODE(CPL_TX_TLS_SFO) |
823             V_CPL_TX_TLS_SFO_DATA_TYPE(data_type) |
824             V_CPL_TX_TLS_SFO_CPL_LEN(2) | V_CPL_TX_TLS_SFO_SEG_LEN(seglen));
825         cpl->pld_len = htobe32(plen);
826         if (data_type == CPL_TX_TLS_SFO_TYPE_CUSTOM)
827                 cpl->type_protover = htobe32(
828                     V_CPL_TX_TLS_SFO_TYPE(tls_hdr->type));
829         cpl->seqno_numivs = htobe32(tls_ofld->scmd0.seqno_numivs |
830             V_SCMD_NUM_IVS(pdus));
831         cpl->ivgen_hdrlen = htobe32(tls_ofld->scmd0.ivgen_hdrlen);
832         cpl->scmd1 = htobe64(tls_ofld->tx_seq_no);
833         tls_ofld->tx_seq_no += pdus;
834 }
835
836 static int
837 count_ext_pgs_segs(struct mbuf *m)
838 {
839         vm_paddr_t nextpa;
840         u_int i, nsegs;
841
842         MPASS(m->m_epg_npgs > 0);
843         nsegs = 1;
844         nextpa = m->m_epg_pa[0] + PAGE_SIZE;
845         for (i = 1; i < m->m_epg_npgs; i++) {
846                 if (nextpa != m->m_epg_pa[i])
847                         nsegs++;
848                 nextpa = m->m_epg_pa[i] + PAGE_SIZE;
849         }
850         return (nsegs);
851 }
852
853 static void
854 write_ktlstx_sgl(void *dst, struct mbuf *m, int nsegs)
855 {
856         struct ulptx_sgl *usgl = dst;
857         vm_paddr_t pa;
858         uint32_t len;
859         int i, j;
860
861         KASSERT(nsegs > 0, ("%s: nsegs 0", __func__));
862
863         usgl->cmd_nsge = htobe32(V_ULPTX_CMD(ULP_TX_SC_DSGL) |
864             V_ULPTX_NSGE(nsegs));
865
866         /* Figure out the first S/G length. */
867         pa = m->m_epg_pa[0] + m->m_epg_1st_off;
868         usgl->addr0 = htobe64(pa);
869         len = m_epg_pagelen(m, 0, m->m_epg_1st_off);
870         pa += len;
871         for (i = 1; i < m->m_epg_npgs; i++) {
872                 if (m->m_epg_pa[i] != pa)
873                         break;
874                 len += m_epg_pagelen(m, i, 0);
875                 pa += m_epg_pagelen(m, i, 0);
876         }
877         usgl->len0 = htobe32(len);
878 #ifdef INVARIANTS
879         nsegs--;
880 #endif
881
882         j = -1;
883         for (; i < m->m_epg_npgs; i++) {
884                 if (j == -1 || m->m_epg_pa[i] != pa) {
885                         if (j >= 0)
886                                 usgl->sge[j / 2].len[j & 1] = htobe32(len);
887                         j++;
888 #ifdef INVARIANTS
889                         nsegs--;
890 #endif
891                         pa = m->m_epg_pa[i];
892                         usgl->sge[j / 2].addr[j & 1] = htobe64(pa);
893                         len = m_epg_pagelen(m, i, 0);
894                         pa += len;
895                 } else {
896                         len += m_epg_pagelen(m, i, 0);
897                         pa += m_epg_pagelen(m, i, 0);
898                 }
899         }
900         if (j >= 0) {
901                 usgl->sge[j / 2].len[j & 1] = htobe32(len);
902
903                 if ((j & 1) == 0)
904                         usgl->sge[j / 2].len[1] = htobe32(0);
905         }
906         KASSERT(nsegs == 0, ("%s: nsegs %d, m %p", __func__, nsegs, m));
907 }
908
909 /*
910  * Similar to t4_push_frames() but handles sockets that contain TLS
911  * record mbufs.
912  */
913 void
914 t4_push_ktls(struct adapter *sc, struct toepcb *toep, int drop)
915 {
916         struct tls_hdr *thdr;
917         struct fw_tlstx_data_wr *txwr;
918         struct cpl_tx_tls_sfo *cpl;
919         struct ulptx_idata *idata;
920         struct ulptx_sc_memrd *memrd;
921         struct wrqe *wr;
922         struct mbuf *m;
923         u_int nsegs, credits, wr_len;
924         u_int expn_size;
925         struct inpcb *inp = toep->inp;
926         struct tcpcb *tp = intotcpcb(inp);
927         struct socket *so = inp->inp_socket;
928         struct sockbuf *sb = &so->so_snd;
929         int tls_size, tx_credits, shove, sowwakeup;
930         struct ofld_tx_sdesc *txsd;
931         char *buf;
932
933         INP_WLOCK_ASSERT(inp);
934         KASSERT(toep->flags & TPF_FLOWC_WR_SENT,
935             ("%s: flowc_wr not sent for tid %u.", __func__, toep->tid));
936
937         KASSERT(ulp_mode(toep) == ULP_MODE_NONE ||
938             ulp_mode(toep) == ULP_MODE_TCPDDP || ulp_mode(toep) == ULP_MODE_TLS,
939             ("%s: ulp_mode %u for toep %p", __func__, ulp_mode(toep), toep));
940         KASSERT(tls_tx_key(toep),
941             ("%s: TX key not set for toep %p", __func__, toep));
942
943 #ifdef VERBOSE_TRACES
944         CTR4(KTR_CXGBE, "%s: tid %d toep flags %#x tp flags %#x drop %d",
945             __func__, toep->tid, toep->flags, tp->t_flags);
946 #endif
947         if (__predict_false(toep->flags & TPF_ABORT_SHUTDOWN))
948                 return;
949
950 #ifdef RATELIMIT
951         if (__predict_false(inp->inp_flags2 & INP_RATE_LIMIT_CHANGED) &&
952             (update_tx_rate_limit(sc, toep, so->so_max_pacing_rate) == 0)) {
953                 inp->inp_flags2 &= ~INP_RATE_LIMIT_CHANGED;
954         }
955 #endif
956
957         /*
958          * This function doesn't resume by itself.  Someone else must clear the
959          * flag and call this function.
960          */
961         if (__predict_false(toep->flags & TPF_TX_SUSPENDED)) {
962                 KASSERT(drop == 0,
963                     ("%s: drop (%d) != 0 but tx is suspended", __func__, drop));
964                 return;
965         }
966
967         txsd = &toep->txsd[toep->txsd_pidx];
968         for (;;) {
969                 tx_credits = min(toep->tx_credits, MAX_OFLD_TX_CREDITS);
970
971                 SOCKBUF_LOCK(sb);
972                 sowwakeup = drop;
973                 if (drop) {
974                         sbdrop_locked(sb, drop);
975                         drop = 0;
976                 }
977
978                 m = sb->sb_sndptr != NULL ? sb->sb_sndptr->m_next : sb->sb_mb;
979
980                 /*
981                  * Send a FIN if requested, but only if there's no
982                  * more data to send.
983                  */
984                 if (m == NULL && toep->flags & TPF_SEND_FIN) {
985                         if (sowwakeup)
986                                 sowwakeup_locked(so);
987                         else
988                                 SOCKBUF_UNLOCK(sb);
989                         SOCKBUF_UNLOCK_ASSERT(sb);
990                         t4_close_conn(sc, toep);
991                         return;
992                 }
993
994                 /*
995                  * If there is no ready data to send, wait until more
996                  * data arrives.
997                  */
998                 if (m == NULL || (m->m_flags & M_NOTAVAIL) != 0) {
999                         if (sowwakeup)
1000                                 sowwakeup_locked(so);
1001                         else
1002                                 SOCKBUF_UNLOCK(sb);
1003                         SOCKBUF_UNLOCK_ASSERT(sb);
1004 #ifdef VERBOSE_TRACES
1005                         CTR2(KTR_CXGBE, "%s: tid %d no ready data to send",
1006                             __func__, toep->tid);
1007 #endif
1008                         return;
1009                 }
1010
1011                 KASSERT(m->m_flags & M_EXTPG, ("%s: mbuf %p is not NOMAP",
1012                     __func__, m));
1013                 KASSERT(m->m_epg_tls != NULL,
1014                     ("%s: mbuf %p doesn't have TLS session", __func__, m));
1015
1016                 /* Calculate WR length. */
1017                 wr_len = sizeof(struct fw_tlstx_data_wr) +
1018                     sizeof(struct cpl_tx_tls_sfo) +
1019                     sizeof(struct ulptx_idata) + sizeof(struct ulptx_sc_memrd);
1020
1021                 /* Explicit IVs for AES-CBC and AES-GCM are <= 16. */
1022                 MPASS(toep->tls.iv_len <= AES_BLOCK_LEN);
1023                 wr_len += AES_BLOCK_LEN;
1024
1025                 /* Account for SGL in work request length. */
1026                 nsegs = count_ext_pgs_segs(m);
1027                 wr_len += sizeof(struct ulptx_sgl) +
1028                     ((3 * (nsegs - 1)) / 2 + ((nsegs - 1) & 1)) * 8;
1029
1030                 /* Not enough credits for this work request. */
1031                 if (howmany(wr_len, 16) > tx_credits) {
1032                         if (sowwakeup)
1033                                 sowwakeup_locked(so);
1034                         else
1035                                 SOCKBUF_UNLOCK(sb);
1036                         SOCKBUF_UNLOCK_ASSERT(sb);
1037 #ifdef VERBOSE_TRACES
1038                         CTR5(KTR_CXGBE,
1039             "%s: tid %d mbuf %p requires %d credits, but only %d available",
1040                             __func__, toep->tid, m, howmany(wr_len, 16),
1041                             tx_credits);
1042 #endif
1043                         toep->flags |= TPF_TX_SUSPENDED;
1044                         return;
1045                 }
1046         
1047                 /* Shove if there is no additional data pending. */
1048                 shove = ((m->m_next == NULL ||
1049                     (m->m_next->m_flags & M_NOTAVAIL) != 0)) &&
1050                     (tp->t_flags & TF_MORETOCOME) == 0;
1051
1052                 if (sb->sb_flags & SB_AUTOSIZE &&
1053                     V_tcp_do_autosndbuf &&
1054                     sb->sb_hiwat < V_tcp_autosndbuf_max &&
1055                     sbused(sb) >= sb->sb_hiwat * 7 / 8) {
1056                         int newsize = min(sb->sb_hiwat + V_tcp_autosndbuf_inc,
1057                             V_tcp_autosndbuf_max);
1058
1059                         if (!sbreserve_locked(sb, newsize, so, NULL))
1060                                 sb->sb_flags &= ~SB_AUTOSIZE;
1061                         else
1062                                 sowwakeup = 1;  /* room available */
1063                 }
1064                 if (sowwakeup)
1065                         sowwakeup_locked(so);
1066                 else
1067                         SOCKBUF_UNLOCK(sb);
1068                 SOCKBUF_UNLOCK_ASSERT(sb);
1069
1070                 if (__predict_false(toep->flags & TPF_FIN_SENT))
1071                         panic("%s: excess tx.", __func__);
1072
1073                 wr = alloc_wrqe(roundup2(wr_len, 16), &toep->ofld_txq->wrq);
1074                 if (wr == NULL) {
1075                         /* XXX: how will we recover from this? */
1076                         toep->flags |= TPF_TX_SUSPENDED;
1077                         return;
1078                 }
1079
1080                 thdr = (struct tls_hdr *)&m->m_epg_hdr;
1081 #ifdef VERBOSE_TRACES
1082                 CTR5(KTR_CXGBE, "%s: tid %d TLS record %ju type %d len %#x",
1083                     __func__, toep->tid, m->m_epg_seqno, thdr->type,
1084                     m->m_len);
1085 #endif
1086                 txwr = wrtod(wr);
1087                 cpl = (struct cpl_tx_tls_sfo *)(txwr + 1);
1088                 memset(txwr, 0, roundup2(wr_len, 16));
1089                 credits = howmany(wr_len, 16);
1090                 expn_size = m->m_epg_hdrlen +
1091                     m->m_epg_trllen;
1092                 tls_size = m->m_len - expn_size;
1093                 write_tlstx_wr(txwr, toep, 0,
1094                     tls_size, expn_size, 1, credits, shove, 1);
1095                 toep->tls.tx_seq_no = m->m_epg_seqno;
1096                 write_tlstx_cpl(cpl, toep, thdr, tls_size, 1);
1097
1098                 idata = (struct ulptx_idata *)(cpl + 1);
1099                 idata->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_NOOP));
1100                 idata->len = htobe32(0);
1101                 memrd = (struct ulptx_sc_memrd *)(idata + 1);
1102                 memrd->cmd_to_len = htobe32(V_ULPTX_CMD(ULP_TX_SC_MEMRD) |
1103                     V_ULP_TX_SC_MORE(1) |
1104                     V_ULPTX_LEN16(toep->tls.tx_key_info_size >> 4));
1105                 memrd->addr = htobe32(toep->tls.tx_key_addr >> 5);
1106
1107                 /* Copy IV. */
1108                 buf = (char *)(memrd + 1);
1109                 memcpy(buf, thdr + 1, toep->tls.iv_len);
1110                 buf += AES_BLOCK_LEN;
1111
1112                 write_ktlstx_sgl(buf, m, nsegs);
1113
1114                 KASSERT(toep->tx_credits >= credits,
1115                         ("%s: not enough credits", __func__));
1116
1117                 toep->tx_credits -= credits;
1118
1119                 tp->snd_nxt += m->m_len;
1120                 tp->snd_max += m->m_len;
1121
1122                 SOCKBUF_LOCK(sb);
1123                 sb->sb_sndptr = m;
1124                 SOCKBUF_UNLOCK(sb);
1125
1126                 toep->flags |= TPF_TX_DATA_SENT;
1127                 if (toep->tx_credits < MIN_OFLD_TLSTX_CREDITS(toep))
1128                         toep->flags |= TPF_TX_SUSPENDED;
1129
1130                 KASSERT(toep->txsd_avail > 0, ("%s: no txsd", __func__));
1131                 txsd->plen = m->m_len;
1132                 txsd->tx_credits = credits;
1133                 txsd++;
1134                 if (__predict_false(++toep->txsd_pidx == toep->txsd_total)) {
1135                         toep->txsd_pidx = 0;
1136                         txsd = &toep->txsd[0];
1137                 }
1138                 toep->txsd_avail--;
1139
1140                 counter_u64_add(toep->ofld_txq->tx_toe_tls_records, 1);
1141                 counter_u64_add(toep->ofld_txq->tx_toe_tls_octets, m->m_len);
1142
1143                 t4_l2t_send(sc, wr, toep->l2te);
1144         }
1145 }
1146
1147 /*
1148  * For TLS data we place received mbufs received via CPL_TLS_DATA into
1149  * an mbufq in the TLS offload state.  When CPL_RX_TLS_CMP is
1150  * received, the completed PDUs are placed into the socket receive
1151  * buffer.
1152  *
1153  * The TLS code reuses the ulp_pdu_reclaimq to hold the pending mbufs.
1154  */
1155 static int
1156 do_tls_data(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
1157 {
1158         struct adapter *sc = iq->adapter;
1159         const struct cpl_tls_data *cpl = mtod(m, const void *);
1160         unsigned int tid = GET_TID(cpl);
1161         struct toepcb *toep = lookup_tid(sc, tid);
1162         struct inpcb *inp = toep->inp;
1163         struct tcpcb *tp;
1164         int len;
1165
1166         /* XXX: Should this match do_rx_data instead? */
1167         KASSERT(!(toep->flags & TPF_SYNQE),
1168             ("%s: toep %p claims to be a synq entry", __func__, toep));
1169
1170         KASSERT(toep->tid == tid, ("%s: toep tid/atid mismatch", __func__));
1171
1172         /* strip off CPL header */
1173         m_adj(m, sizeof(*cpl));
1174         len = m->m_pkthdr.len;
1175
1176         toep->ofld_rxq->rx_toe_tls_octets += len;
1177
1178         KASSERT(len == G_CPL_TLS_DATA_LENGTH(be32toh(cpl->length_pkd)),
1179             ("%s: payload length mismatch", __func__));
1180
1181         INP_WLOCK(inp);
1182         if (inp->inp_flags & (INP_DROPPED | INP_TIMEWAIT)) {
1183                 CTR4(KTR_CXGBE, "%s: tid %u, rx (%d bytes), inp_flags 0x%x",
1184                     __func__, tid, len, inp->inp_flags);
1185                 INP_WUNLOCK(inp);
1186                 m_freem(m);
1187                 return (0);
1188         }
1189
1190         /* Save TCP sequence number. */
1191         m->m_pkthdr.tls_tcp_seq = be32toh(cpl->seq);
1192
1193         if (mbufq_enqueue(&toep->ulp_pdu_reclaimq, m)) {
1194 #ifdef INVARIANTS
1195                 panic("Failed to queue TLS data packet");
1196 #else
1197                 printf("%s: Failed to queue TLS data packet\n", __func__);
1198                 INP_WUNLOCK(inp);
1199                 m_freem(m);
1200                 return (0);
1201 #endif
1202         }
1203
1204         tp = intotcpcb(inp);
1205         tp->t_rcvtime = ticks;
1206
1207 #ifdef VERBOSE_TRACES
1208         CTR4(KTR_CXGBE, "%s: tid %u len %d seq %u", __func__, tid, len,
1209             be32toh(cpl->seq));
1210 #endif
1211
1212         INP_WUNLOCK(inp);
1213         return (0);
1214 }
1215
1216 static int
1217 do_rx_tls_cmp(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
1218 {
1219         struct adapter *sc = iq->adapter;
1220         const struct cpl_rx_tls_cmp *cpl = mtod(m, const void *);
1221         struct tlsrx_hdr_pkt *tls_hdr_pkt;
1222         unsigned int tid = GET_TID(cpl);
1223         struct toepcb *toep = lookup_tid(sc, tid);
1224         struct inpcb *inp = toep->inp;
1225         struct tcpcb *tp;
1226         struct socket *so;
1227         struct sockbuf *sb;
1228         struct mbuf *tls_data;
1229         struct tls_get_record *tgr;
1230         struct mbuf *control;
1231         int pdu_length, rx_credits;
1232 #if defined(KTR) || defined(INVARIANTS)
1233         int len;
1234 #endif
1235
1236         KASSERT(toep->tid == tid, ("%s: toep tid/atid mismatch", __func__));
1237         KASSERT(!(toep->flags & TPF_SYNQE),
1238             ("%s: toep %p claims to be a synq entry", __func__, toep));
1239
1240         /* strip off CPL header */
1241         m_adj(m, sizeof(*cpl));
1242 #if defined(KTR) || defined(INVARIANTS)
1243         len = m->m_pkthdr.len;
1244 #endif
1245
1246         toep->ofld_rxq->rx_toe_tls_records++;
1247
1248         KASSERT(len == G_CPL_RX_TLS_CMP_LENGTH(be32toh(cpl->pdulength_length)),
1249             ("%s: payload length mismatch", __func__));
1250
1251         INP_WLOCK(inp);
1252         if (inp->inp_flags & (INP_DROPPED | INP_TIMEWAIT)) {
1253                 CTR4(KTR_CXGBE, "%s: tid %u, rx (%d bytes), inp_flags 0x%x",
1254                     __func__, tid, len, inp->inp_flags);
1255                 INP_WUNLOCK(inp);
1256                 m_freem(m);
1257                 return (0);
1258         }
1259
1260         pdu_length = G_CPL_RX_TLS_CMP_PDULENGTH(be32toh(cpl->pdulength_length));
1261
1262         so = inp_inpcbtosocket(inp);
1263         tp = intotcpcb(inp);
1264
1265 #ifdef VERBOSE_TRACES
1266         CTR6(KTR_CXGBE, "%s: tid %u PDU len %d len %d seq %u, rcv_nxt %u",
1267             __func__, tid, pdu_length, len, be32toh(cpl->seq), tp->rcv_nxt);
1268 #endif
1269
1270         tp->rcv_nxt += pdu_length;
1271         KASSERT(tp->rcv_wnd >= pdu_length,
1272             ("%s: negative window size", __func__));
1273         tp->rcv_wnd -= pdu_length;
1274
1275         /* XXX: Not sure what to do about urgent data. */
1276
1277         /*
1278          * The payload of this CPL is the TLS header followed by
1279          * additional fields.
1280          */
1281         KASSERT(m->m_len >= sizeof(*tls_hdr_pkt),
1282             ("%s: payload too small", __func__));
1283         tls_hdr_pkt = mtod(m, void *);
1284
1285         tls_data = mbufq_dequeue(&toep->ulp_pdu_reclaimq);
1286         if (tls_data != NULL) {
1287                 KASSERT(be32toh(cpl->seq) == tls_data->m_pkthdr.tls_tcp_seq,
1288                     ("%s: sequence mismatch", __func__));
1289         }
1290
1291         /* Report decryption errors as EBADMSG. */
1292         if ((tls_hdr_pkt->res_to_mac_error & M_TLSRX_HDR_PKT_ERROR) != 0) {
1293                 m_freem(m);
1294                 m_freem(tls_data);
1295
1296                 CURVNET_SET(toep->vnet);
1297                 so->so_error = EBADMSG;
1298                 sorwakeup(so);
1299
1300                 INP_WUNLOCK(inp);
1301                 CURVNET_RESTORE();
1302
1303                 return (0);
1304         }
1305
1306         /* Allocate the control message mbuf. */
1307         control = sbcreatecontrol(NULL, sizeof(*tgr), TLS_GET_RECORD,
1308             IPPROTO_TCP);
1309         if (control == NULL) {
1310                 m_freem(m);
1311                 m_freem(tls_data);
1312
1313                 CURVNET_SET(toep->vnet);
1314                 so->so_error = ENOBUFS;
1315                 sorwakeup(so);
1316
1317                 INP_WUNLOCK(inp);
1318                 CURVNET_RESTORE();
1319
1320                 return (0);
1321         }
1322
1323         tgr = (struct tls_get_record *)
1324             CMSG_DATA(mtod(control, struct cmsghdr *));
1325         memset(tgr, 0, sizeof(*tgr));
1326         tgr->tls_type = tls_hdr_pkt->type;
1327         tgr->tls_vmajor = be16toh(tls_hdr_pkt->version) >> 8;
1328         tgr->tls_vminor = be16toh(tls_hdr_pkt->version) & 0xff;
1329
1330         m_freem(m);
1331
1332         if (tls_data != NULL) {
1333                 m_last(tls_data)->m_flags |= M_EOR;
1334                 tgr->tls_length = htobe16(tls_data->m_pkthdr.len);
1335         } else
1336                 tgr->tls_length = 0;
1337         m = tls_data;
1338
1339         sb = &so->so_rcv;
1340         SOCKBUF_LOCK(sb);
1341
1342         if (__predict_false(sb->sb_state & SBS_CANTRCVMORE)) {
1343                 struct epoch_tracker et;
1344
1345                 CTR3(KTR_CXGBE, "%s: tid %u, excess rx (%d bytes)",
1346                     __func__, tid, pdu_length);
1347                 m_freem(m);
1348                 m_freem(control);
1349                 SOCKBUF_UNLOCK(sb);
1350                 INP_WUNLOCK(inp);
1351
1352                 CURVNET_SET(toep->vnet);
1353                 NET_EPOCH_ENTER(et);
1354                 INP_WLOCK(inp);
1355                 tp = tcp_drop(tp, ECONNRESET);
1356                 if (tp)
1357                         INP_WUNLOCK(inp);
1358                 NET_EPOCH_EXIT(et);
1359                 CURVNET_RESTORE();
1360
1361                 return (0);
1362         }
1363
1364         /*
1365          * Not all of the bytes on the wire are included in the socket buffer
1366          * (e.g. the MAC of the TLS record).  However, those bytes are included
1367          * in the TCP sequence space.
1368          */
1369
1370         /* receive buffer autosize */
1371         MPASS(toep->vnet == so->so_vnet);
1372         CURVNET_SET(toep->vnet);
1373         if (sb->sb_flags & SB_AUTOSIZE &&
1374             V_tcp_do_autorcvbuf &&
1375             sb->sb_hiwat < V_tcp_autorcvbuf_max &&
1376             m->m_pkthdr.len > (sbspace(sb) / 8 * 7)) {
1377                 unsigned int hiwat = sb->sb_hiwat;
1378                 unsigned int newsize = min(hiwat + sc->tt.autorcvbuf_inc,
1379                     V_tcp_autorcvbuf_max);
1380
1381                 if (!sbreserve_locked(sb, newsize, so, NULL))
1382                         sb->sb_flags &= ~SB_AUTOSIZE;
1383         }
1384
1385         sbappendcontrol_locked(sb, m, control, 0);
1386         rx_credits = sbspace(sb) > tp->rcv_wnd ? sbspace(sb) - tp->rcv_wnd : 0;
1387 #ifdef VERBOSE_TRACES
1388         CTR4(KTR_CXGBE, "%s: tid %u rx_credits %u rcv_wnd %u",
1389             __func__, tid, rx_credits, tp->rcv_wnd);
1390 #endif
1391         if (rx_credits > 0 && sbused(sb) + tp->rcv_wnd < sb->sb_lowat) {
1392                 rx_credits = send_rx_credits(sc, toep, rx_credits);
1393                 tp->rcv_wnd += rx_credits;
1394                 tp->rcv_adv += rx_credits;
1395         }
1396
1397         sorwakeup_locked(so);
1398         SOCKBUF_UNLOCK_ASSERT(sb);
1399
1400         INP_WUNLOCK(inp);
1401         CURVNET_RESTORE();
1402         return (0);
1403 }
1404
1405 void
1406 do_rx_data_tls(const struct cpl_rx_data *cpl, struct toepcb *toep,
1407     struct mbuf *m)
1408 {
1409         struct inpcb *inp = toep->inp;
1410         struct tls_ofld_info *tls_ofld = &toep->tls;
1411         struct tls_hdr *hdr;
1412         struct tcpcb *tp;
1413         struct socket *so;
1414         struct sockbuf *sb;
1415         int len, rx_credits;
1416
1417         len = m->m_pkthdr.len;
1418
1419         INP_WLOCK_ASSERT(inp);
1420
1421         so = inp_inpcbtosocket(inp);
1422         tp = intotcpcb(inp);
1423         sb = &so->so_rcv;
1424         SOCKBUF_LOCK(sb);
1425         CURVNET_SET(toep->vnet);
1426
1427         tp->rcv_nxt += len;
1428         KASSERT(tp->rcv_wnd >= len, ("%s: negative window size", __func__));
1429         tp->rcv_wnd -= len;
1430
1431         /* Do we have a full TLS header? */
1432         if (len < sizeof(*hdr)) {
1433                 CTR3(KTR_CXGBE, "%s: tid %u len %d: too short for a TLS header",
1434                     __func__, toep->tid, len);
1435                 so->so_error = EMSGSIZE;
1436                 goto out;
1437         }
1438         hdr = mtod(m, struct tls_hdr *);
1439
1440         /* Is the header valid? */
1441         if (be16toh(hdr->version) != tls_ofld->rx_version) {
1442                 CTR3(KTR_CXGBE, "%s: tid %u invalid version %04x",
1443                     __func__, toep->tid, be16toh(hdr->version));
1444                 so->so_error = EINVAL;
1445                 goto out;
1446         }
1447         if (be16toh(hdr->length) < sizeof(*hdr)) {
1448                 CTR3(KTR_CXGBE, "%s: tid %u invalid length %u",
1449                     __func__, toep->tid, be16toh(hdr->length));
1450                 so->so_error = EBADMSG;
1451                 goto out;
1452         }
1453
1454         /* Did we get a truncated record? */
1455         if (len < be16toh(hdr->length)) {
1456                 CTR4(KTR_CXGBE, "%s: tid %u truncated TLS record (%d vs %u)",
1457                     __func__, toep->tid, len, be16toh(hdr->length));
1458
1459                 so->so_error = EMSGSIZE;
1460                 goto out;
1461         }
1462
1463         /* Is the header type unknown? */
1464         switch (hdr->type) {
1465         case CONTENT_TYPE_CCS:
1466         case CONTENT_TYPE_ALERT:
1467         case CONTENT_TYPE_APP_DATA:
1468         case CONTENT_TYPE_HANDSHAKE:
1469                 break;
1470         default:
1471                 CTR3(KTR_CXGBE, "%s: tid %u invalid TLS record type %u",
1472                     __func__, toep->tid, hdr->type);
1473                 so->so_error = EBADMSG;
1474                 goto out;
1475         }
1476
1477         /*
1478          * Just punt.  Although this could fall back to software
1479          * decryption, this case should never really happen.
1480          */
1481         CTR4(KTR_CXGBE, "%s: tid %u dropping TLS record type %u, length %u",
1482             __func__, toep->tid, hdr->type, be16toh(hdr->length));
1483         so->so_error = EBADMSG;
1484
1485 out:
1486         /*
1487          * This connection is going to die anyway, so probably don't
1488          * need to bother with returning credits.
1489          */
1490         rx_credits = sbspace(sb) > tp->rcv_wnd ? sbspace(sb) - tp->rcv_wnd : 0;
1491 #ifdef VERBOSE_TRACES
1492         CTR4(KTR_CXGBE, "%s: tid %u rx_credits %u rcv_wnd %u",
1493             __func__, toep->tid, rx_credits, tp->rcv_wnd);
1494 #endif
1495         if (rx_credits > 0 && sbused(sb) + tp->rcv_wnd < sb->sb_lowat) {
1496                 rx_credits = send_rx_credits(toep->vi->adapter, toep,
1497                     rx_credits);
1498                 tp->rcv_wnd += rx_credits;
1499                 tp->rcv_adv += rx_credits;
1500         }
1501
1502         sorwakeup_locked(so);
1503         SOCKBUF_UNLOCK_ASSERT(sb);
1504
1505         INP_WUNLOCK(inp);
1506         CURVNET_RESTORE();
1507
1508         m_freem(m);
1509 }
1510
1511 void
1512 t4_tls_mod_load(void)
1513 {
1514
1515         t4_register_cpl_handler(CPL_TLS_DATA, do_tls_data);
1516         t4_register_cpl_handler(CPL_RX_TLS_CMP, do_rx_tls_cmp);
1517 }
1518
1519 void
1520 t4_tls_mod_unload(void)
1521 {
1522
1523         t4_register_cpl_handler(CPL_TLS_DATA, NULL);
1524         t4_register_cpl_handler(CPL_RX_TLS_CMP, NULL);
1525 }
1526 #endif  /* TCP_OFFLOAD */
1527 #endif  /* KERN_TLS */