]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/cxgbe/tom/t4_tom.c
Merge OpenSSL 1.1.1g.
[FreeBSD/FreeBSD.git] / sys / dev / cxgbe / tom / t4_tom.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2012 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@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 <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35 #include "opt_kern_tls.h"
36 #include "opt_ratelimit.h"
37
38 #include <sys/param.h>
39 #include <sys/types.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/ktr.h>
43 #include <sys/lock.h>
44 #include <sys/limits.h>
45 #include <sys/module.h>
46 #include <sys/protosw.h>
47 #include <sys/domain.h>
48 #include <sys/refcount.h>
49 #include <sys/rmlock.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/taskqueue.h>
54 #include <net/if.h>
55 #include <net/if_var.h>
56 #include <net/if_types.h>
57 #include <net/if_vlan_var.h>
58 #include <netinet/in.h>
59 #include <netinet/in_pcb.h>
60 #include <netinet/in_var.h>
61 #include <netinet/ip.h>
62 #include <netinet/ip6.h>
63 #include <netinet6/scope6_var.h>
64 #define TCPSTATES
65 #include <netinet/tcp_fsm.h>
66 #include <netinet/tcp_timer.h>
67 #include <netinet/tcp_var.h>
68 #include <netinet/toecore.h>
69 #include <netinet/cc/cc.h>
70
71 #ifdef TCP_OFFLOAD
72 #include "common/common.h"
73 #include "common/t4_msg.h"
74 #include "common/t4_regs.h"
75 #include "common/t4_regs_values.h"
76 #include "common/t4_tcb.h"
77 #include "t4_clip.h"
78 #include "tom/t4_tom_l2t.h"
79 #include "tom/t4_tom.h"
80 #include "tom/t4_tls.h"
81
82 static struct protosw toe_protosw;
83 static struct pr_usrreqs toe_usrreqs;
84
85 static struct protosw toe6_protosw;
86 static struct pr_usrreqs toe6_usrreqs;
87
88 /* Module ops */
89 static int t4_tom_mod_load(void);
90 static int t4_tom_mod_unload(void);
91 static int t4_tom_modevent(module_t, int, void *);
92
93 /* ULD ops and helpers */
94 static int t4_tom_activate(struct adapter *);
95 static int t4_tom_deactivate(struct adapter *);
96
97 static struct uld_info tom_uld_info = {
98         .uld_id = ULD_TOM,
99         .activate = t4_tom_activate,
100         .deactivate = t4_tom_deactivate,
101 };
102
103 static void release_offload_resources(struct toepcb *);
104 static int alloc_tid_tabs(struct tid_info *);
105 static void free_tid_tabs(struct tid_info *);
106 static void free_tom_data(struct adapter *, struct tom_data *);
107 static void reclaim_wr_resources(void *, int);
108
109 struct toepcb *
110 alloc_toepcb(struct vi_info *vi, int flags)
111 {
112         struct port_info *pi = vi->pi;
113         struct adapter *sc = pi->adapter;
114         struct toepcb *toep;
115         int tx_credits, txsd_total, len;
116
117         /*
118          * The firmware counts tx work request credits in units of 16 bytes
119          * each.  Reserve room for an ABORT_REQ so the driver never has to worry
120          * about tx credits if it wants to abort a connection.
121          */
122         tx_credits = sc->params.ofldq_wr_cred;
123         tx_credits -= howmany(sizeof(struct cpl_abort_req), 16);
124
125         /*
126          * Shortest possible tx work request is a fw_ofld_tx_data_wr + 1 byte
127          * immediate payload, and firmware counts tx work request credits in
128          * units of 16 byte.  Calculate the maximum work requests possible.
129          */
130         txsd_total = tx_credits /
131             howmany(sizeof(struct fw_ofld_tx_data_wr) + 1, 16);
132
133         len = offsetof(struct toepcb, txsd) +
134             txsd_total * sizeof(struct ofld_tx_sdesc);
135
136         toep = malloc(len, M_CXGBE, M_ZERO | flags);
137         if (toep == NULL)
138                 return (NULL);
139
140         refcount_init(&toep->refcount, 1);
141         toep->td = sc->tom_softc;
142         toep->vi = vi;
143         toep->tid = -1;
144         toep->tx_total = tx_credits;
145         toep->tx_credits = tx_credits;
146         mbufq_init(&toep->ulp_pduq, INT_MAX);
147         mbufq_init(&toep->ulp_pdu_reclaimq, INT_MAX);
148         toep->txsd_total = txsd_total;
149         toep->txsd_avail = txsd_total;
150         toep->txsd_pidx = 0;
151         toep->txsd_cidx = 0;
152         aiotx_init_toep(toep);
153
154         return (toep);
155 }
156
157 /*
158  * Initialize a toepcb after its params have been filled out.
159  */
160 int
161 init_toepcb(struct vi_info *vi, struct toepcb *toep)
162 {
163         struct conn_params *cp = &toep->params;
164         struct port_info *pi = vi->pi;
165         struct adapter *sc = pi->adapter;
166         struct tx_cl_rl_params *tc;
167
168         if (cp->tc_idx >= 0 && cp->tc_idx < sc->chip_params->nsched_cls) {
169                 tc = &pi->sched_params->cl_rl[cp->tc_idx];
170                 mtx_lock(&sc->tc_lock);
171                 if (tc->flags & CLRL_ERR) {
172                         log(LOG_ERR,
173                             "%s: failed to associate traffic class %u with tid %u\n",
174                             device_get_nameunit(vi->dev), cp->tc_idx,
175                             toep->tid);
176                         cp->tc_idx = -1;
177                 } else {
178                         tc->refcount++;
179                 }
180                 mtx_unlock(&sc->tc_lock);
181         }
182         toep->ofld_txq = &sc->sge.ofld_txq[cp->txq_idx];
183         toep->ofld_rxq = &sc->sge.ofld_rxq[cp->rxq_idx];
184         toep->ctrlq = &sc->sge.ctrlq[pi->port_id];
185
186         tls_init_toep(toep);
187         if (ulp_mode(toep) == ULP_MODE_TCPDDP)
188                 ddp_init_toep(toep);
189
190         toep->flags |= TPF_INITIALIZED;
191
192         return (0);
193 }
194
195 struct toepcb *
196 hold_toepcb(struct toepcb *toep)
197 {
198
199         refcount_acquire(&toep->refcount);
200         return (toep);
201 }
202
203 void
204 free_toepcb(struct toepcb *toep)
205 {
206
207         if (refcount_release(&toep->refcount) == 0)
208                 return;
209
210         KASSERT(!(toep->flags & TPF_ATTACHED),
211             ("%s: attached to an inpcb", __func__));
212         KASSERT(!(toep->flags & TPF_CPL_PENDING),
213             ("%s: CPL pending", __func__));
214
215         if (toep->flags & TPF_INITIALIZED) {
216                 if (ulp_mode(toep) == ULP_MODE_TCPDDP)
217                         ddp_uninit_toep(toep);
218                 tls_uninit_toep(toep);
219         }
220         free(toep, M_CXGBE);
221 }
222
223 /*
224  * Set up the socket for TCP offload.
225  */
226 void
227 offload_socket(struct socket *so, struct toepcb *toep)
228 {
229         struct tom_data *td = toep->td;
230         struct inpcb *inp = sotoinpcb(so);
231         struct tcpcb *tp = intotcpcb(inp);
232         struct sockbuf *sb;
233
234         INP_WLOCK_ASSERT(inp);
235
236         /* Update socket */
237         sb = &so->so_snd;
238         SOCKBUF_LOCK(sb);
239         sb->sb_flags |= SB_NOCOALESCE;
240         SOCKBUF_UNLOCK(sb);
241         sb = &so->so_rcv;
242         SOCKBUF_LOCK(sb);
243         sb->sb_flags |= SB_NOCOALESCE;
244         if (inp->inp_vflag & INP_IPV6)
245                 so->so_proto = &toe6_protosw;
246         else
247                 so->so_proto = &toe_protosw;
248         SOCKBUF_UNLOCK(sb);
249
250         /* Update TCP PCB */
251         tp->tod = &td->tod;
252         tp->t_toe = toep;
253         tp->t_flags |= TF_TOE;
254
255         /* Install an extra hold on inp */
256         toep->inp = inp;
257         toep->flags |= TPF_ATTACHED;
258         in_pcbref(inp);
259
260         /* Add the TOE PCB to the active list */
261         mtx_lock(&td->toep_list_lock);
262         TAILQ_INSERT_HEAD(&td->toep_list, toep, link);
263         mtx_unlock(&td->toep_list_lock);
264 }
265
266 /* This is _not_ the normal way to "unoffload" a socket. */
267 void
268 undo_offload_socket(struct socket *so)
269 {
270         struct inpcb *inp = sotoinpcb(so);
271         struct tcpcb *tp = intotcpcb(inp);
272         struct toepcb *toep = tp->t_toe;
273         struct tom_data *td = toep->td;
274         struct sockbuf *sb;
275
276         INP_WLOCK_ASSERT(inp);
277
278         sb = &so->so_snd;
279         SOCKBUF_LOCK(sb);
280         sb->sb_flags &= ~SB_NOCOALESCE;
281         SOCKBUF_UNLOCK(sb);
282         sb = &so->so_rcv;
283         SOCKBUF_LOCK(sb);
284         sb->sb_flags &= ~SB_NOCOALESCE;
285         SOCKBUF_UNLOCK(sb);
286
287         tp->tod = NULL;
288         tp->t_toe = NULL;
289         tp->t_flags &= ~TF_TOE;
290
291         toep->inp = NULL;
292         toep->flags &= ~TPF_ATTACHED;
293         if (in_pcbrele_wlocked(inp))
294                 panic("%s: inp freed.", __func__);
295
296         mtx_lock(&td->toep_list_lock);
297         TAILQ_REMOVE(&td->toep_list, toep, link);
298         mtx_unlock(&td->toep_list_lock);
299 }
300
301 static void
302 release_offload_resources(struct toepcb *toep)
303 {
304         struct tom_data *td = toep->td;
305         struct adapter *sc = td_adapter(td);
306         int tid = toep->tid;
307
308         KASSERT(!(toep->flags & TPF_CPL_PENDING),
309             ("%s: %p has CPL pending.", __func__, toep));
310         KASSERT(!(toep->flags & TPF_ATTACHED),
311             ("%s: %p is still attached.", __func__, toep));
312
313         CTR5(KTR_CXGBE, "%s: toep %p (tid %d, l2te %p, ce %p)",
314             __func__, toep, tid, toep->l2te, toep->ce);
315
316         /*
317          * These queues should have been emptied at approximately the same time
318          * that a normal connection's socket's so_snd would have been purged or
319          * drained.  Do _not_ clean up here.
320          */
321         MPASS(mbufq_len(&toep->ulp_pduq) == 0);
322         MPASS(mbufq_len(&toep->ulp_pdu_reclaimq) == 0);
323 #ifdef INVARIANTS
324         if (ulp_mode(toep) == ULP_MODE_TCPDDP)
325                 ddp_assert_empty(toep);
326 #endif
327         MPASS(TAILQ_EMPTY(&toep->aiotx_jobq));
328
329         if (toep->l2te)
330                 t4_l2t_release(toep->l2te);
331
332         if (tid >= 0) {
333                 remove_tid(sc, tid, toep->ce ? 2 : 1);
334                 release_tid(sc, tid, toep->ctrlq);
335         }
336
337         if (toep->ce)
338                 t4_release_lip(sc, toep->ce);
339
340         if (toep->params.tc_idx != -1)
341                 t4_release_cl_rl(sc, toep->vi->pi->port_id, toep->params.tc_idx);
342
343         mtx_lock(&td->toep_list_lock);
344         TAILQ_REMOVE(&td->toep_list, toep, link);
345         mtx_unlock(&td->toep_list_lock);
346
347         free_toepcb(toep);
348 }
349
350 /*
351  * The kernel is done with the TCP PCB and this is our opportunity to unhook the
352  * toepcb hanging off of it.  If the TOE driver is also done with the toepcb (no
353  * pending CPL) then it is time to release all resources tied to the toepcb.
354  *
355  * Also gets called when an offloaded active open fails and the TOM wants the
356  * kernel to take the TCP PCB back.
357  */
358 static void
359 t4_pcb_detach(struct toedev *tod __unused, struct tcpcb *tp)
360 {
361 #if defined(KTR) || defined(INVARIANTS)
362         struct inpcb *inp = tp->t_inpcb;
363 #endif
364         struct toepcb *toep = tp->t_toe;
365
366         INP_WLOCK_ASSERT(inp);
367
368         KASSERT(toep != NULL, ("%s: toep is NULL", __func__));
369         KASSERT(toep->flags & TPF_ATTACHED,
370             ("%s: not attached", __func__));
371
372 #ifdef KTR
373         if (tp->t_state == TCPS_SYN_SENT) {
374                 CTR6(KTR_CXGBE, "%s: atid %d, toep %p (0x%x), inp %p (0x%x)",
375                     __func__, toep->tid, toep, toep->flags, inp,
376                     inp->inp_flags);
377         } else {
378                 CTR6(KTR_CXGBE,
379                     "t4_pcb_detach: tid %d (%s), toep %p (0x%x), inp %p (0x%x)",
380                     toep->tid, tcpstates[tp->t_state], toep, toep->flags, inp,
381                     inp->inp_flags);
382         }
383 #endif
384
385         tp->t_toe = NULL;
386         tp->t_flags &= ~TF_TOE;
387         toep->flags &= ~TPF_ATTACHED;
388
389         if (!(toep->flags & TPF_CPL_PENDING))
390                 release_offload_resources(toep);
391 }
392
393 /*
394  * setsockopt handler.
395  */
396 static void
397 t4_ctloutput(struct toedev *tod, struct tcpcb *tp, int dir, int name)
398 {
399         struct adapter *sc = tod->tod_softc;
400         struct toepcb *toep = tp->t_toe;
401
402         if (dir == SOPT_GET)
403                 return;
404
405         CTR4(KTR_CXGBE, "%s: tp %p, dir %u, name %u", __func__, tp, dir, name);
406
407         switch (name) {
408         case TCP_NODELAY:
409                 if (tp->t_state != TCPS_ESTABLISHED)
410                         break;
411                 toep->params.nagle = tp->t_flags & TF_NODELAY ? 0 : 1;
412                 t4_set_tcb_field(sc, toep->ctrlq, toep, W_TCB_T_FLAGS,
413                     V_TF_NAGLE(1), V_TF_NAGLE(toep->params.nagle), 0, 0);
414                 break;
415         default:
416                 break;
417         }
418 }
419
420 static inline uint64_t
421 get_tcb_tflags(const uint64_t *tcb)
422 {
423
424         return ((be64toh(tcb[14]) << 32) | (be64toh(tcb[15]) >> 32));
425 }
426
427 static inline uint32_t
428 get_tcb_field(const uint64_t *tcb, u_int word, uint32_t mask, u_int shift)
429 {
430 #define LAST_WORD ((TCB_SIZE / 4) - 1)
431         uint64_t t1, t2;
432         int flit_idx;
433
434         MPASS(mask != 0);
435         MPASS(word <= LAST_WORD);
436         MPASS(shift < 32);
437
438         flit_idx = (LAST_WORD - word) / 2;
439         if (word & 0x1)
440                 shift += 32;
441         t1 = be64toh(tcb[flit_idx]) >> shift;
442         t2 = 0;
443         if (fls(mask) > 64 - shift) {
444                 /*
445                  * Will spill over into the next logical flit, which is the flit
446                  * before this one.  The flit_idx before this one must be valid.
447                  */
448                 MPASS(flit_idx > 0);
449                 t2 = be64toh(tcb[flit_idx - 1]) << (64 - shift);
450         }
451         return ((t2 | t1) & mask);
452 #undef LAST_WORD
453 }
454 #define GET_TCB_FIELD(tcb, F) \
455     get_tcb_field(tcb, W_TCB_##F, M_TCB_##F, S_TCB_##F)
456
457 /*
458  * Issues a CPL_GET_TCB to read the entire TCB for the tid.
459  */
460 static int
461 send_get_tcb(struct adapter *sc, u_int tid)
462 {
463         struct cpl_get_tcb *cpl;
464         struct wrq_cookie cookie;
465
466         MPASS(tid < sc->tids.ntids);
467
468         cpl = start_wrq_wr(&sc->sge.ctrlq[0], howmany(sizeof(*cpl), 16),
469             &cookie);
470         if (__predict_false(cpl == NULL))
471                 return (ENOMEM);
472         bzero(cpl, sizeof(*cpl));
473         INIT_TP_WR(cpl, tid);
474         OPCODE_TID(cpl) = htobe32(MK_OPCODE_TID(CPL_GET_TCB, tid));
475         cpl->reply_ctrl = htobe16(V_REPLY_CHAN(0) |
476             V_QUEUENO(sc->sge.ofld_rxq[0].iq.cntxt_id));
477         cpl->cookie = 0xff;
478         commit_wrq_wr(&sc->sge.ctrlq[0], cpl, &cookie);
479
480         return (0);
481 }
482
483 static struct tcb_histent *
484 alloc_tcb_histent(struct adapter *sc, u_int tid, int flags)
485 {
486         struct tcb_histent *te;
487
488         MPASS(flags == M_NOWAIT || flags == M_WAITOK);
489
490         te = malloc(sizeof(*te), M_CXGBE, M_ZERO | flags);
491         if (te == NULL)
492                 return (NULL);
493         mtx_init(&te->te_lock, "TCB entry", NULL, MTX_DEF);
494         callout_init_mtx(&te->te_callout, &te->te_lock, 0);
495         te->te_adapter = sc;
496         te->te_tid = tid;
497
498         return (te);
499 }
500
501 static void
502 free_tcb_histent(struct tcb_histent *te)
503 {
504
505         mtx_destroy(&te->te_lock);
506         free(te, M_CXGBE);
507 }
508
509 /*
510  * Start tracking the tid in the TCB history.
511  */
512 int
513 add_tid_to_history(struct adapter *sc, u_int tid)
514 {
515         struct tcb_histent *te = NULL;
516         struct tom_data *td = sc->tom_softc;
517         int rc;
518
519         MPASS(tid < sc->tids.ntids);
520
521         if (td->tcb_history == NULL)
522                 return (ENXIO);
523
524         rw_wlock(&td->tcb_history_lock);
525         if (td->tcb_history[tid] != NULL) {
526                 rc = EEXIST;
527                 goto done;
528         }
529         te = alloc_tcb_histent(sc, tid, M_NOWAIT);
530         if (te == NULL) {
531                 rc = ENOMEM;
532                 goto done;
533         }
534         mtx_lock(&te->te_lock);
535         rc = send_get_tcb(sc, tid);
536         if (rc == 0) {
537                 te->te_flags |= TE_RPL_PENDING;
538                 td->tcb_history[tid] = te;
539         } else {
540                 free(te, M_CXGBE);
541         }
542         mtx_unlock(&te->te_lock);
543 done:
544         rw_wunlock(&td->tcb_history_lock);
545         return (rc);
546 }
547
548 static void
549 remove_tcb_histent(struct tcb_histent *te)
550 {
551         struct adapter *sc = te->te_adapter;
552         struct tom_data *td = sc->tom_softc;
553
554         rw_assert(&td->tcb_history_lock, RA_WLOCKED);
555         mtx_assert(&te->te_lock, MA_OWNED);
556         MPASS(td->tcb_history[te->te_tid] == te);
557
558         td->tcb_history[te->te_tid] = NULL;
559         free_tcb_histent(te);
560         rw_wunlock(&td->tcb_history_lock);
561 }
562
563 static inline struct tcb_histent *
564 lookup_tcb_histent(struct adapter *sc, u_int tid, bool addrem)
565 {
566         struct tcb_histent *te;
567         struct tom_data *td = sc->tom_softc;
568
569         MPASS(tid < sc->tids.ntids);
570
571         if (td->tcb_history == NULL)
572                 return (NULL);
573
574         if (addrem)
575                 rw_wlock(&td->tcb_history_lock);
576         else
577                 rw_rlock(&td->tcb_history_lock);
578         te = td->tcb_history[tid];
579         if (te != NULL) {
580                 mtx_lock(&te->te_lock);
581                 return (te);    /* with both locks held */
582         }
583         if (addrem)
584                 rw_wunlock(&td->tcb_history_lock);
585         else
586                 rw_runlock(&td->tcb_history_lock);
587
588         return (te);
589 }
590
591 static inline void
592 release_tcb_histent(struct tcb_histent *te)
593 {
594         struct adapter *sc = te->te_adapter;
595         struct tom_data *td = sc->tom_softc;
596
597         mtx_assert(&te->te_lock, MA_OWNED);
598         mtx_unlock(&te->te_lock);
599         rw_assert(&td->tcb_history_lock, RA_RLOCKED);
600         rw_runlock(&td->tcb_history_lock);
601 }
602
603 static void
604 request_tcb(void *arg)
605 {
606         struct tcb_histent *te = arg;
607
608         mtx_assert(&te->te_lock, MA_OWNED);
609
610         /* Noone else is supposed to update the histent. */
611         MPASS(!(te->te_flags & TE_RPL_PENDING));
612         if (send_get_tcb(te->te_adapter, te->te_tid) == 0)
613                 te->te_flags |= TE_RPL_PENDING;
614         else
615                 callout_schedule(&te->te_callout, hz / 100);
616 }
617
618 static void
619 update_tcb_histent(struct tcb_histent *te, const uint64_t *tcb)
620 {
621         struct tom_data *td = te->te_adapter->tom_softc;
622         uint64_t tflags = get_tcb_tflags(tcb);
623         uint8_t sample = 0;
624
625         if (GET_TCB_FIELD(tcb, SND_MAX_RAW) != GET_TCB_FIELD(tcb, SND_UNA_RAW)) {
626                 if (GET_TCB_FIELD(tcb, T_RXTSHIFT) != 0)
627                         sample |= TS_RTO;
628                 if (GET_TCB_FIELD(tcb, T_DUPACKS) != 0)
629                         sample |= TS_DUPACKS;
630                 if (GET_TCB_FIELD(tcb, T_DUPACKS) >= td->dupack_threshold)
631                         sample |= TS_FASTREXMT;
632         }
633
634         if (GET_TCB_FIELD(tcb, SND_MAX_RAW) != 0) {
635                 uint32_t snd_wnd;
636
637                 sample |= TS_SND_BACKLOGGED;    /* for whatever reason. */
638
639                 snd_wnd = GET_TCB_FIELD(tcb, RCV_ADV);
640                 if (tflags & V_TF_RECV_SCALE(1))
641                         snd_wnd <<= GET_TCB_FIELD(tcb, RCV_SCALE);
642                 if (GET_TCB_FIELD(tcb, SND_CWND) < snd_wnd)
643                         sample |= TS_CWND_LIMITED;      /* maybe due to CWND */
644         }
645
646         if (tflags & V_TF_CCTRL_ECN(1)) {
647
648                 /*
649                  * CE marker on incoming IP hdr, echoing ECE back in the TCP
650                  * hdr.  Indicates congestion somewhere on the way from the peer
651                  * to this node.
652                  */
653                 if (tflags & V_TF_CCTRL_ECE(1))
654                         sample |= TS_ECN_ECE;
655
656                 /*
657                  * ECE seen and CWR sent (or about to be sent).  Might indicate
658                  * congestion on the way to the peer.  This node is reducing its
659                  * congestion window in response.
660                  */
661                 if (tflags & (V_TF_CCTRL_CWR(1) | V_TF_CCTRL_RFR(1)))
662                         sample |= TS_ECN_CWR;
663         }
664
665         te->te_sample[te->te_pidx] = sample;
666         if (++te->te_pidx == nitems(te->te_sample))
667                 te->te_pidx = 0;
668         memcpy(te->te_tcb, tcb, TCB_SIZE);
669         te->te_flags |= TE_ACTIVE;
670 }
671
672 static int
673 do_get_tcb_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
674 {
675         struct adapter *sc = iq->adapter;
676         const struct cpl_get_tcb_rpl *cpl = mtod(m, const void *);
677         const uint64_t *tcb = (const uint64_t *)(const void *)(cpl + 1);
678         struct tcb_histent *te;
679         const u_int tid = GET_TID(cpl);
680         bool remove;
681
682         remove = GET_TCB_FIELD(tcb, T_STATE) == TCPS_CLOSED;
683         te = lookup_tcb_histent(sc, tid, remove);
684         if (te == NULL) {
685                 /* Not in the history.  Who issued the GET_TCB for this? */
686                 device_printf(sc->dev, "tcb %u: flags 0x%016jx, state %u, "
687                     "srtt %u, sscale %u, rscale %u, cookie 0x%x\n", tid,
688                     (uintmax_t)get_tcb_tflags(tcb), GET_TCB_FIELD(tcb, T_STATE),
689                     GET_TCB_FIELD(tcb, T_SRTT), GET_TCB_FIELD(tcb, SND_SCALE),
690                     GET_TCB_FIELD(tcb, RCV_SCALE), cpl->cookie);
691                 goto done;
692         }
693
694         MPASS(te->te_flags & TE_RPL_PENDING);
695         te->te_flags &= ~TE_RPL_PENDING;
696         if (remove) {
697                 remove_tcb_histent(te);
698         } else {
699                 update_tcb_histent(te, tcb);
700                 callout_reset(&te->te_callout, hz / 10, request_tcb, te);
701                 release_tcb_histent(te);
702         }
703 done:
704         m_freem(m);
705         return (0);
706 }
707
708 static void
709 fill_tcp_info_from_tcb(struct adapter *sc, uint64_t *tcb, struct tcp_info *ti)
710 {
711         uint32_t v;
712
713         ti->tcpi_state = GET_TCB_FIELD(tcb, T_STATE);
714
715         v = GET_TCB_FIELD(tcb, T_SRTT);
716         ti->tcpi_rtt = tcp_ticks_to_us(sc, v);
717
718         v = GET_TCB_FIELD(tcb, T_RTTVAR);
719         ti->tcpi_rttvar = tcp_ticks_to_us(sc, v);
720
721         ti->tcpi_snd_ssthresh = GET_TCB_FIELD(tcb, SND_SSTHRESH);
722         ti->tcpi_snd_cwnd = GET_TCB_FIELD(tcb, SND_CWND);
723         ti->tcpi_rcv_nxt = GET_TCB_FIELD(tcb, RCV_NXT);
724
725         v = GET_TCB_FIELD(tcb, TX_MAX);
726         ti->tcpi_snd_nxt = v - GET_TCB_FIELD(tcb, SND_NXT_RAW);
727
728         /* Receive window being advertised by us. */
729         ti->tcpi_rcv_wscale = GET_TCB_FIELD(tcb, SND_SCALE);    /* Yes, SND. */
730         ti->tcpi_rcv_space = GET_TCB_FIELD(tcb, RCV_WND);
731
732         /* Send window */
733         ti->tcpi_snd_wscale = GET_TCB_FIELD(tcb, RCV_SCALE);    /* Yes, RCV. */
734         ti->tcpi_snd_wnd = GET_TCB_FIELD(tcb, RCV_ADV);
735         if (get_tcb_tflags(tcb) & V_TF_RECV_SCALE(1))
736                 ti->tcpi_snd_wnd <<= ti->tcpi_snd_wscale;
737         else
738                 ti->tcpi_snd_wscale = 0;
739
740 }
741
742 static void
743 fill_tcp_info_from_history(struct adapter *sc, struct tcb_histent *te,
744     struct tcp_info *ti)
745 {
746
747         fill_tcp_info_from_tcb(sc, te->te_tcb, ti);
748 }
749
750 /*
751  * Reads the TCB for the given tid using a memory window and copies it to 'buf'
752  * in the same format as CPL_GET_TCB_RPL.
753  */
754 static void
755 read_tcb_using_memwin(struct adapter *sc, u_int tid, uint64_t *buf)
756 {
757         int i, j, k, rc;
758         uint32_t addr;
759         u_char *tcb, tmp;
760
761         MPASS(tid < sc->tids.ntids);
762
763         addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE) + tid * TCB_SIZE;
764         rc = read_via_memwin(sc, 2, addr, (uint32_t *)buf, TCB_SIZE);
765         if (rc != 0)
766                 return;
767
768         tcb = (u_char *)buf;
769         for (i = 0, j = TCB_SIZE - 16; i < j; i += 16, j -= 16) {
770                 for (k = 0; k < 16; k++) {
771                         tmp = tcb[i + k];
772                         tcb[i + k] = tcb[j + k];
773                         tcb[j + k] = tmp;
774                 }
775         }
776 }
777
778 static void
779 fill_tcp_info(struct adapter *sc, u_int tid, struct tcp_info *ti)
780 {
781         uint64_t tcb[TCB_SIZE / sizeof(uint64_t)];
782         struct tcb_histent *te;
783
784         ti->tcpi_toe_tid = tid;
785         te = lookup_tcb_histent(sc, tid, false);
786         if (te != NULL) {
787                 fill_tcp_info_from_history(sc, te, ti);
788                 release_tcb_histent(te);
789         } else {
790                 if (!(sc->debug_flags & DF_DISABLE_TCB_CACHE)) {
791                         /* XXX: tell firmware to flush TCB cache. */
792                 }
793                 read_tcb_using_memwin(sc, tid, tcb);
794                 fill_tcp_info_from_tcb(sc, tcb, ti);
795         }
796 }
797
798 /*
799  * Called by the kernel to allow the TOE driver to "refine" values filled up in
800  * the tcp_info for an offloaded connection.
801  */
802 static void
803 t4_tcp_info(struct toedev *tod, struct tcpcb *tp, struct tcp_info *ti)
804 {
805         struct adapter *sc = tod->tod_softc;
806         struct toepcb *toep = tp->t_toe;
807
808         INP_WLOCK_ASSERT(tp->t_inpcb);
809         MPASS(ti != NULL);
810
811         fill_tcp_info(sc, toep->tid, ti);
812 }
813
814 #ifdef KERN_TLS
815 static int
816 t4_alloc_tls_session(struct toedev *tod, struct tcpcb *tp,
817     struct ktls_session *tls)
818 {
819         struct toepcb *toep = tp->t_toe;
820
821         INP_WLOCK_ASSERT(tp->t_inpcb);
822         MPASS(tls != NULL);
823
824         return (tls_alloc_ktls(toep, tls));
825 }
826 #endif
827
828 /*
829  * The TOE driver will not receive any more CPLs for the tid associated with the
830  * toepcb; release the hold on the inpcb.
831  */
832 void
833 final_cpl_received(struct toepcb *toep)
834 {
835         struct inpcb *inp = toep->inp;
836
837         KASSERT(inp != NULL, ("%s: inp is NULL", __func__));
838         INP_WLOCK_ASSERT(inp);
839         KASSERT(toep->flags & TPF_CPL_PENDING,
840             ("%s: CPL not pending already?", __func__));
841
842         CTR6(KTR_CXGBE, "%s: tid %d, toep %p (0x%x), inp %p (0x%x)",
843             __func__, toep->tid, toep, toep->flags, inp, inp->inp_flags);
844
845         if (ulp_mode(toep) == ULP_MODE_TCPDDP)
846                 release_ddp_resources(toep);
847         toep->inp = NULL;
848         toep->flags &= ~TPF_CPL_PENDING;
849         mbufq_drain(&toep->ulp_pdu_reclaimq);
850
851         if (!(toep->flags & TPF_ATTACHED))
852                 release_offload_resources(toep);
853
854         if (!in_pcbrele_wlocked(inp))
855                 INP_WUNLOCK(inp);
856 }
857
858 void
859 insert_tid(struct adapter *sc, int tid, void *ctx, int ntids)
860 {
861         struct tid_info *t = &sc->tids;
862
863         MPASS(tid >= t->tid_base);
864         MPASS(tid - t->tid_base < t->ntids);
865
866         t->tid_tab[tid - t->tid_base] = ctx;
867         atomic_add_int(&t->tids_in_use, ntids);
868 }
869
870 void *
871 lookup_tid(struct adapter *sc, int tid)
872 {
873         struct tid_info *t = &sc->tids;
874
875         return (t->tid_tab[tid - t->tid_base]);
876 }
877
878 void
879 update_tid(struct adapter *sc, int tid, void *ctx)
880 {
881         struct tid_info *t = &sc->tids;
882
883         t->tid_tab[tid - t->tid_base] = ctx;
884 }
885
886 void
887 remove_tid(struct adapter *sc, int tid, int ntids)
888 {
889         struct tid_info *t = &sc->tids;
890
891         t->tid_tab[tid - t->tid_base] = NULL;
892         atomic_subtract_int(&t->tids_in_use, ntids);
893 }
894
895 /*
896  * What mtu_idx to use, given a 4-tuple.  Note that both s->mss and tcp_mssopt
897  * have the MSS that we should advertise in our SYN.  Advertised MSS doesn't
898  * account for any TCP options so the effective MSS (only payload, no headers or
899  * options) could be different.
900  */
901 static int
902 find_best_mtu_idx(struct adapter *sc, struct in_conninfo *inc,
903     struct offload_settings *s)
904 {
905         unsigned short *mtus = &sc->params.mtus[0];
906         int i, mss, mtu;
907
908         MPASS(inc != NULL);
909
910         mss = s->mss > 0 ? s->mss : tcp_mssopt(inc);
911         if (inc->inc_flags & INC_ISIPV6)
912                 mtu = mss + sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
913         else
914                 mtu = mss + sizeof(struct ip) + sizeof(struct tcphdr);
915
916         for (i = 0; i < NMTUS - 1 && mtus[i + 1] <= mtu; i++)
917                 continue;
918
919         return (i);
920 }
921
922 /*
923  * Determine the receive window size for a socket.
924  */
925 u_long
926 select_rcv_wnd(struct socket *so)
927 {
928         unsigned long wnd;
929
930         SOCKBUF_LOCK_ASSERT(&so->so_rcv);
931
932         wnd = sbspace(&so->so_rcv);
933         if (wnd < MIN_RCV_WND)
934                 wnd = MIN_RCV_WND;
935
936         return min(wnd, MAX_RCV_WND);
937 }
938
939 int
940 select_rcv_wscale(void)
941 {
942         int wscale = 0;
943         unsigned long space = sb_max;
944
945         if (space > MAX_RCV_WND)
946                 space = MAX_RCV_WND;
947
948         while (wscale < TCP_MAX_WINSHIFT && (TCP_MAXWIN << wscale) < space)
949                 wscale++;
950
951         return (wscale);
952 }
953
954 __be64
955 calc_options0(struct vi_info *vi, struct conn_params *cp)
956 {
957         uint64_t opt0 = 0;
958
959         opt0 |= F_TCAM_BYPASS;
960
961         MPASS(cp->wscale >= 0 && cp->wscale <= M_WND_SCALE);
962         opt0 |= V_WND_SCALE(cp->wscale);
963
964         MPASS(cp->mtu_idx >= 0 && cp->mtu_idx < NMTUS);
965         opt0 |= V_MSS_IDX(cp->mtu_idx);
966
967         MPASS(cp->ulp_mode >= 0 && cp->ulp_mode <= M_ULP_MODE);
968         opt0 |= V_ULP_MODE(cp->ulp_mode);
969
970         MPASS(cp->opt0_bufsize >= 0 && cp->opt0_bufsize <= M_RCV_BUFSIZ);
971         opt0 |= V_RCV_BUFSIZ(cp->opt0_bufsize);
972
973         MPASS(cp->l2t_idx >= 0 && cp->l2t_idx < vi->pi->adapter->vres.l2t.size);
974         opt0 |= V_L2T_IDX(cp->l2t_idx);
975
976         opt0 |= V_SMAC_SEL(vi->smt_idx);
977         opt0 |= V_TX_CHAN(vi->pi->tx_chan);
978
979         MPASS(cp->keepalive == 0 || cp->keepalive == 1);
980         opt0 |= V_KEEP_ALIVE(cp->keepalive);
981
982         MPASS(cp->nagle == 0 || cp->nagle == 1);
983         opt0 |= V_NAGLE(cp->nagle);
984
985         return (htobe64(opt0));
986 }
987
988 __be32
989 calc_options2(struct vi_info *vi, struct conn_params *cp)
990 {
991         uint32_t opt2 = 0;
992         struct port_info *pi = vi->pi;
993         struct adapter *sc = pi->adapter;
994
995         /*
996          * rx flow control, rx coalesce, congestion control, and tx pace are all
997          * explicitly set by the driver.  On T5+ the ISS is also set by the
998          * driver to the value picked by the kernel.
999          */
1000         if (is_t4(sc)) {
1001                 opt2 |= F_RX_FC_VALID | F_RX_COALESCE_VALID;
1002                 opt2 |= F_CONG_CNTRL_VALID | F_PACE_VALID;
1003         } else {
1004                 opt2 |= F_T5_OPT_2_VALID;       /* all 4 valid */
1005                 opt2 |= F_T5_ISS;               /* ISS provided in CPL */
1006         }
1007
1008         MPASS(cp->sack == 0 || cp->sack == 1);
1009         opt2 |= V_SACK_EN(cp->sack);
1010
1011         MPASS(cp->tstamp == 0 || cp->tstamp == 1);
1012         opt2 |= V_TSTAMPS_EN(cp->tstamp);
1013
1014         if (cp->wscale > 0)
1015                 opt2 |= F_WND_SCALE_EN;
1016
1017         MPASS(cp->ecn == 0 || cp->ecn == 1);
1018         opt2 |= V_CCTRL_ECN(cp->ecn);
1019
1020         /* XXX: F_RX_CHANNEL for multiple rx c-chan support goes here. */
1021
1022         opt2 |= V_TX_QUEUE(sc->params.tp.tx_modq[pi->tx_chan]);
1023         opt2 |= V_PACE(0);
1024         opt2 |= F_RSS_QUEUE_VALID;
1025         opt2 |= V_RSS_QUEUE(sc->sge.ofld_rxq[cp->rxq_idx].iq.abs_id);
1026
1027         MPASS(cp->cong_algo >= 0 && cp->cong_algo <= M_CONG_CNTRL);
1028         opt2 |= V_CONG_CNTRL(cp->cong_algo);
1029
1030         MPASS(cp->rx_coalesce == 0 || cp->rx_coalesce == 1);
1031         if (cp->rx_coalesce == 1)
1032                 opt2 |= V_RX_COALESCE(M_RX_COALESCE);
1033
1034         opt2 |= V_RX_FC_DDP(0) | V_RX_FC_DISABLE(0);
1035 #ifdef USE_DDP_RX_FLOW_CONTROL
1036         if (cp->ulp_mode == ULP_MODE_TCPDDP)
1037                 opt2 |= F_RX_FC_DDP;
1038 #endif
1039         if (cp->ulp_mode == ULP_MODE_TLS)
1040                 opt2 |= F_RX_FC_DISABLE;
1041
1042         return (htobe32(opt2));
1043 }
1044
1045 uint64_t
1046 select_ntuple(struct vi_info *vi, struct l2t_entry *e)
1047 {
1048         struct adapter *sc = vi->pi->adapter;
1049         struct tp_params *tp = &sc->params.tp;
1050         uint64_t ntuple = 0;
1051
1052         /*
1053          * Initialize each of the fields which we care about which are present
1054          * in the Compressed Filter Tuple.
1055          */
1056         if (tp->vlan_shift >= 0 && EVL_VLANOFTAG(e->vlan) != CPL_L2T_VLAN_NONE)
1057                 ntuple |= (uint64_t)(F_FT_VLAN_VLD | e->vlan) << tp->vlan_shift;
1058
1059         if (tp->port_shift >= 0)
1060                 ntuple |= (uint64_t)e->lport << tp->port_shift;
1061
1062         if (tp->protocol_shift >= 0)
1063                 ntuple |= (uint64_t)IPPROTO_TCP << tp->protocol_shift;
1064
1065         if (tp->vnic_shift >= 0 && tp->ingress_config & F_VNIC) {
1066                 ntuple |= (uint64_t)(V_FT_VNID_ID_VF(vi->vin) |
1067                     V_FT_VNID_ID_PF(sc->pf) | V_FT_VNID_ID_VLD(vi->vfvld)) <<
1068                     tp->vnic_shift;
1069         }
1070
1071         if (is_t4(sc))
1072                 return (htobe32((uint32_t)ntuple));
1073         else
1074                 return (htobe64(V_FILTER_TUPLE(ntuple)));
1075 }
1076
1077 static int
1078 is_tls_sock(struct socket *so, struct adapter *sc)
1079 {
1080         struct inpcb *inp = sotoinpcb(so);
1081         int i, rc;
1082
1083         /* XXX: Eventually add a SO_WANT_TLS socket option perhaps? */
1084         rc = 0;
1085         ADAPTER_LOCK(sc);
1086         for (i = 0; i < sc->tt.num_tls_rx_ports; i++) {
1087                 if (inp->inp_lport == htons(sc->tt.tls_rx_ports[i]) ||
1088                     inp->inp_fport == htons(sc->tt.tls_rx_ports[i])) {
1089                         rc = 1;
1090                         break;
1091                 }
1092         }
1093         ADAPTER_UNLOCK(sc);
1094         return (rc);
1095 }
1096
1097 /*
1098  * Initialize various connection parameters.
1099  */
1100 void
1101 init_conn_params(struct vi_info *vi , struct offload_settings *s,
1102     struct in_conninfo *inc, struct socket *so,
1103     const struct tcp_options *tcpopt, int16_t l2t_idx, struct conn_params *cp)
1104 {
1105         struct port_info *pi = vi->pi;
1106         struct adapter *sc = pi->adapter;
1107         struct tom_tunables *tt = &sc->tt;
1108         struct inpcb *inp = sotoinpcb(so);
1109         struct tcpcb *tp = intotcpcb(inp);
1110         u_long wnd;
1111
1112         MPASS(s->offload != 0);
1113
1114         /* Congestion control algorithm */
1115         if (s->cong_algo >= 0)
1116                 cp->cong_algo = s->cong_algo & M_CONG_CNTRL;
1117         else if (sc->tt.cong_algorithm >= 0)
1118                 cp->cong_algo = tt->cong_algorithm & M_CONG_CNTRL;
1119         else {
1120                 struct cc_algo *cc = CC_ALGO(tp);
1121
1122                 if (strcasecmp(cc->name, "reno") == 0)
1123                         cp->cong_algo = CONG_ALG_RENO;
1124                 else if (strcasecmp(cc->name, "tahoe") == 0)
1125                         cp->cong_algo = CONG_ALG_TAHOE;
1126                 if (strcasecmp(cc->name, "newreno") == 0)
1127                         cp->cong_algo = CONG_ALG_NEWRENO;
1128                 if (strcasecmp(cc->name, "highspeed") == 0)
1129                         cp->cong_algo = CONG_ALG_HIGHSPEED;
1130                 else {
1131                         /*
1132                          * Use newreno in case the algorithm selected by the
1133                          * host stack is not supported by the hardware.
1134                          */
1135                         cp->cong_algo = CONG_ALG_NEWRENO;
1136                 }
1137         }
1138
1139         /* Tx traffic scheduling class. */
1140         if (s->sched_class >= 0 &&
1141             s->sched_class < sc->chip_params->nsched_cls) {
1142             cp->tc_idx = s->sched_class;
1143         } else
1144             cp->tc_idx = -1;
1145
1146         /* Nagle's algorithm. */
1147         if (s->nagle >= 0)
1148                 cp->nagle = s->nagle > 0 ? 1 : 0;
1149         else
1150                 cp->nagle = tp->t_flags & TF_NODELAY ? 0 : 1;
1151
1152         /* TCP Keepalive. */
1153         if (V_tcp_always_keepalive || so_options_get(so) & SO_KEEPALIVE)
1154                 cp->keepalive = 1;
1155         else
1156                 cp->keepalive = 0;
1157
1158         /* Optimization that's specific to T5 @ 40G. */
1159         if (tt->tx_align >= 0)
1160                 cp->tx_align =  tt->tx_align > 0 ? 1 : 0;
1161         else if (chip_id(sc) == CHELSIO_T5 &&
1162             (port_top_speed(pi) > 10 || sc->params.nports > 2))
1163                 cp->tx_align = 1;
1164         else
1165                 cp->tx_align = 0;
1166
1167         /* ULP mode. */
1168         if (can_tls_offload(sc) &&
1169             (s->tls > 0 || (s->tls < 0 && is_tls_sock(so, sc))))
1170                 cp->ulp_mode = ULP_MODE_TLS;
1171         else if (s->ddp > 0 ||
1172             (s->ddp < 0 && sc->tt.ddp && (so_options_get(so) & SO_NO_DDP) == 0))
1173                 cp->ulp_mode = ULP_MODE_TCPDDP;
1174         else
1175                 cp->ulp_mode = ULP_MODE_NONE;
1176
1177         /* Rx coalescing. */
1178         if (s->rx_coalesce >= 0)
1179                 cp->rx_coalesce = s->rx_coalesce > 0 ? 1 : 0;
1180         else if (cp->ulp_mode == ULP_MODE_TLS)
1181                 cp->rx_coalesce = 0;
1182         else if (tt->rx_coalesce >= 0)
1183                 cp->rx_coalesce = tt->rx_coalesce > 0 ? 1 : 0;
1184         else
1185                 cp->rx_coalesce = 1;    /* default */
1186
1187         /*
1188          * Index in the PMTU table.  This controls the MSS that we announce in
1189          * our SYN initially, but after ESTABLISHED it controls the MSS that we
1190          * use to send data.
1191          */
1192         cp->mtu_idx = find_best_mtu_idx(sc, inc, s);
1193
1194         /* Tx queue for this connection. */
1195         if (s->txq >= 0 && s->txq < vi->nofldtxq)
1196                 cp->txq_idx = s->txq;
1197         else
1198                 cp->txq_idx = arc4random() % vi->nofldtxq;
1199         cp->txq_idx += vi->first_ofld_txq;
1200
1201         /* Rx queue for this connection. */
1202         if (s->rxq >= 0 && s->rxq < vi->nofldrxq)
1203                 cp->rxq_idx = s->rxq;
1204         else
1205                 cp->rxq_idx = arc4random() % vi->nofldrxq;
1206         cp->rxq_idx += vi->first_ofld_rxq;
1207
1208         if (SOLISTENING(so)) {
1209                 /* Passive open */
1210                 MPASS(tcpopt != NULL);
1211
1212                 /* TCP timestamp option */
1213                 if (tcpopt->tstamp &&
1214                     (s->tstamp > 0 || (s->tstamp < 0 && V_tcp_do_rfc1323)))
1215                         cp->tstamp = 1;
1216                 else
1217                         cp->tstamp = 0;
1218
1219                 /* SACK */
1220                 if (tcpopt->sack &&
1221                     (s->sack > 0 || (s->sack < 0 && V_tcp_do_sack)))
1222                         cp->sack = 1;
1223                 else
1224                         cp->sack = 0;
1225
1226                 /* Receive window scaling. */
1227                 if (tcpopt->wsf > 0 && tcpopt->wsf < 15 && V_tcp_do_rfc1323)
1228                         cp->wscale = select_rcv_wscale();
1229                 else
1230                         cp->wscale = 0;
1231
1232                 /* ECN */
1233                 if (tcpopt->ecn &&      /* XXX: review. */
1234                     (s->ecn > 0 || (s->ecn < 0 && V_tcp_do_ecn)))
1235                         cp->ecn = 1;
1236                 else
1237                         cp->ecn = 0;
1238
1239                 wnd = max(so->sol_sbrcv_hiwat, MIN_RCV_WND);
1240                 cp->opt0_bufsize = min(wnd >> 10, M_RCV_BUFSIZ);
1241
1242                 if (tt->sndbuf > 0)
1243                         cp->sndbuf = tt->sndbuf;
1244                 else if (so->sol_sbsnd_flags & SB_AUTOSIZE &&
1245                     V_tcp_do_autosndbuf)
1246                         cp->sndbuf = 256 * 1024;
1247                 else
1248                         cp->sndbuf = so->sol_sbsnd_hiwat;
1249         } else {
1250                 /* Active open */
1251
1252                 /* TCP timestamp option */
1253                 if (s->tstamp > 0 ||
1254                     (s->tstamp < 0 && (tp->t_flags & TF_REQ_TSTMP)))
1255                         cp->tstamp = 1;
1256                 else
1257                         cp->tstamp = 0;
1258
1259                 /* SACK */
1260                 if (s->sack > 0 ||
1261                     (s->sack < 0 && (tp->t_flags & TF_SACK_PERMIT)))
1262                         cp->sack = 1;
1263                 else
1264                         cp->sack = 0;
1265
1266                 /* Receive window scaling */
1267                 if (tp->t_flags & TF_REQ_SCALE)
1268                         cp->wscale = select_rcv_wscale();
1269                 else
1270                         cp->wscale = 0;
1271
1272                 /* ECN */
1273                 if (s->ecn > 0 || (s->ecn < 0 && V_tcp_do_ecn == 1))
1274                         cp->ecn = 1;
1275                 else
1276                         cp->ecn = 0;
1277
1278                 SOCKBUF_LOCK(&so->so_rcv);
1279                 wnd = max(select_rcv_wnd(so), MIN_RCV_WND);
1280                 SOCKBUF_UNLOCK(&so->so_rcv);
1281                 cp->opt0_bufsize = min(wnd >> 10, M_RCV_BUFSIZ);
1282
1283                 if (tt->sndbuf > 0)
1284                         cp->sndbuf = tt->sndbuf;
1285                 else {
1286                         SOCKBUF_LOCK(&so->so_snd);
1287                         if (so->so_snd.sb_flags & SB_AUTOSIZE &&
1288                             V_tcp_do_autosndbuf)
1289                                 cp->sndbuf = 256 * 1024;
1290                         else
1291                                 cp->sndbuf = so->so_snd.sb_hiwat;
1292                         SOCKBUF_UNLOCK(&so->so_snd);
1293                 }
1294         }
1295
1296         cp->l2t_idx = l2t_idx;
1297
1298         /* This will be initialized on ESTABLISHED. */
1299         cp->emss = 0;
1300 }
1301
1302 int
1303 negative_advice(int status)
1304 {
1305
1306         return (status == CPL_ERR_RTX_NEG_ADVICE ||
1307             status == CPL_ERR_PERSIST_NEG_ADVICE ||
1308             status == CPL_ERR_KEEPALV_NEG_ADVICE);
1309 }
1310
1311 static int
1312 alloc_tid_tab(struct tid_info *t, int flags)
1313 {
1314
1315         MPASS(t->ntids > 0);
1316         MPASS(t->tid_tab == NULL);
1317
1318         t->tid_tab = malloc(t->ntids * sizeof(*t->tid_tab), M_CXGBE,
1319             M_ZERO | flags);
1320         if (t->tid_tab == NULL)
1321                 return (ENOMEM);
1322         atomic_store_rel_int(&t->tids_in_use, 0);
1323
1324         return (0);
1325 }
1326
1327 static void
1328 free_tid_tab(struct tid_info *t)
1329 {
1330
1331         KASSERT(t->tids_in_use == 0,
1332             ("%s: %d tids still in use.", __func__, t->tids_in_use));
1333
1334         free(t->tid_tab, M_CXGBE);
1335         t->tid_tab = NULL;
1336 }
1337
1338 static int
1339 alloc_stid_tab(struct tid_info *t, int flags)
1340 {
1341
1342         MPASS(t->nstids > 0);
1343         MPASS(t->stid_tab == NULL);
1344
1345         t->stid_tab = malloc(t->nstids * sizeof(*t->stid_tab), M_CXGBE,
1346             M_ZERO | flags);
1347         if (t->stid_tab == NULL)
1348                 return (ENOMEM);
1349         mtx_init(&t->stid_lock, "stid lock", NULL, MTX_DEF);
1350         t->stids_in_use = 0;
1351         TAILQ_INIT(&t->stids);
1352         t->nstids_free_head = t->nstids;
1353
1354         return (0);
1355 }
1356
1357 static void
1358 free_stid_tab(struct tid_info *t)
1359 {
1360
1361         KASSERT(t->stids_in_use == 0,
1362             ("%s: %d tids still in use.", __func__, t->stids_in_use));
1363
1364         if (mtx_initialized(&t->stid_lock))
1365                 mtx_destroy(&t->stid_lock);
1366         free(t->stid_tab, M_CXGBE);
1367         t->stid_tab = NULL;
1368 }
1369
1370 static void
1371 free_tid_tabs(struct tid_info *t)
1372 {
1373
1374         free_tid_tab(t);
1375         free_stid_tab(t);
1376 }
1377
1378 static int
1379 alloc_tid_tabs(struct tid_info *t)
1380 {
1381         int rc;
1382
1383         rc = alloc_tid_tab(t, M_NOWAIT);
1384         if (rc != 0)
1385                 goto failed;
1386
1387         rc = alloc_stid_tab(t, M_NOWAIT);
1388         if (rc != 0)
1389                 goto failed;
1390
1391         return (0);
1392 failed:
1393         free_tid_tabs(t);
1394         return (rc);
1395 }
1396
1397 static inline void
1398 alloc_tcb_history(struct adapter *sc, struct tom_data *td)
1399 {
1400
1401         if (sc->tids.ntids == 0 || sc->tids.ntids > 1024)
1402                 return;
1403         rw_init(&td->tcb_history_lock, "TCB history");
1404         td->tcb_history = malloc(sc->tids.ntids * sizeof(*td->tcb_history),
1405             M_CXGBE, M_ZERO | M_NOWAIT);
1406         td->dupack_threshold = G_DUPACKTHRESH(t4_read_reg(sc, A_TP_PARA_REG0));
1407 }
1408
1409 static inline void
1410 free_tcb_history(struct adapter *sc, struct tom_data *td)
1411 {
1412 #ifdef INVARIANTS
1413         int i;
1414
1415         if (td->tcb_history != NULL) {
1416                 for (i = 0; i < sc->tids.ntids; i++) {
1417                         MPASS(td->tcb_history[i] == NULL);
1418                 }
1419         }
1420 #endif
1421         free(td->tcb_history, M_CXGBE);
1422         if (rw_initialized(&td->tcb_history_lock))
1423                 rw_destroy(&td->tcb_history_lock);
1424 }
1425
1426 static void
1427 free_tom_data(struct adapter *sc, struct tom_data *td)
1428 {
1429
1430         ASSERT_SYNCHRONIZED_OP(sc);
1431
1432         KASSERT(TAILQ_EMPTY(&td->toep_list),
1433             ("%s: TOE PCB list is not empty.", __func__));
1434         KASSERT(td->lctx_count == 0,
1435             ("%s: lctx hash table is not empty.", __func__));
1436
1437         t4_free_ppod_region(&td->pr);
1438
1439         if (td->listen_mask != 0)
1440                 hashdestroy(td->listen_hash, M_CXGBE, td->listen_mask);
1441
1442         if (mtx_initialized(&td->unsent_wr_lock))
1443                 mtx_destroy(&td->unsent_wr_lock);
1444         if (mtx_initialized(&td->lctx_hash_lock))
1445                 mtx_destroy(&td->lctx_hash_lock);
1446         if (mtx_initialized(&td->toep_list_lock))
1447                 mtx_destroy(&td->toep_list_lock);
1448
1449         free_tcb_history(sc, td);
1450         free_tid_tabs(&sc->tids);
1451         free(td, M_CXGBE);
1452 }
1453
1454 static char *
1455 prepare_pkt(int open_type, uint16_t vtag, struct inpcb *inp, int *pktlen,
1456     int *buflen)
1457 {
1458         char *pkt;
1459         struct tcphdr *th;
1460         int ipv6, len;
1461         const int maxlen =
1462             max(sizeof(struct ether_header), sizeof(struct ether_vlan_header)) +
1463             max(sizeof(struct ip), sizeof(struct ip6_hdr)) +
1464             sizeof(struct tcphdr);
1465
1466         MPASS(open_type == OPEN_TYPE_ACTIVE || open_type == OPEN_TYPE_LISTEN);
1467
1468         pkt = malloc(maxlen, M_CXGBE, M_ZERO | M_NOWAIT);
1469         if (pkt == NULL)
1470                 return (NULL);
1471
1472         ipv6 = inp->inp_vflag & INP_IPV6;
1473         len = 0;
1474
1475         if (EVL_VLANOFTAG(vtag) == 0xfff) {
1476                 struct ether_header *eh = (void *)pkt;
1477
1478                 if (ipv6)
1479                         eh->ether_type = htons(ETHERTYPE_IPV6);
1480                 else
1481                         eh->ether_type = htons(ETHERTYPE_IP);
1482
1483                 len += sizeof(*eh);
1484         } else {
1485                 struct ether_vlan_header *evh = (void *)pkt;
1486
1487                 evh->evl_encap_proto = htons(ETHERTYPE_VLAN);
1488                 evh->evl_tag = htons(vtag);
1489                 if (ipv6)
1490                         evh->evl_proto = htons(ETHERTYPE_IPV6);
1491                 else
1492                         evh->evl_proto = htons(ETHERTYPE_IP);
1493
1494                 len += sizeof(*evh);
1495         }
1496
1497         if (ipv6) {
1498                 struct ip6_hdr *ip6 = (void *)&pkt[len];
1499
1500                 ip6->ip6_vfc = IPV6_VERSION;
1501                 ip6->ip6_plen = htons(sizeof(struct tcphdr));
1502                 ip6->ip6_nxt = IPPROTO_TCP;
1503                 if (open_type == OPEN_TYPE_ACTIVE) {
1504                         ip6->ip6_src = inp->in6p_laddr;
1505                         ip6->ip6_dst = inp->in6p_faddr;
1506                 } else if (open_type == OPEN_TYPE_LISTEN) {
1507                         ip6->ip6_src = inp->in6p_laddr;
1508                         ip6->ip6_dst = ip6->ip6_src;
1509                 }
1510
1511                 len += sizeof(*ip6);
1512         } else {
1513                 struct ip *ip = (void *)&pkt[len];
1514
1515                 ip->ip_v = IPVERSION;
1516                 ip->ip_hl = sizeof(*ip) >> 2;
1517                 ip->ip_tos = inp->inp_ip_tos;
1518                 ip->ip_len = htons(sizeof(struct ip) + sizeof(struct tcphdr));
1519                 ip->ip_ttl = inp->inp_ip_ttl;
1520                 ip->ip_p = IPPROTO_TCP;
1521                 if (open_type == OPEN_TYPE_ACTIVE) {
1522                         ip->ip_src = inp->inp_laddr;
1523                         ip->ip_dst = inp->inp_faddr;
1524                 } else if (open_type == OPEN_TYPE_LISTEN) {
1525                         ip->ip_src = inp->inp_laddr;
1526                         ip->ip_dst = ip->ip_src;
1527                 }
1528
1529                 len += sizeof(*ip);
1530         }
1531
1532         th = (void *)&pkt[len];
1533         if (open_type == OPEN_TYPE_ACTIVE) {
1534                 th->th_sport = inp->inp_lport;  /* network byte order already */
1535                 th->th_dport = inp->inp_fport;  /* ditto */
1536         } else if (open_type == OPEN_TYPE_LISTEN) {
1537                 th->th_sport = inp->inp_lport;  /* network byte order already */
1538                 th->th_dport = th->th_sport;
1539         }
1540         len += sizeof(th);
1541
1542         *pktlen = *buflen = len;
1543         return (pkt);
1544 }
1545
1546 const struct offload_settings *
1547 lookup_offload_policy(struct adapter *sc, int open_type, struct mbuf *m,
1548     uint16_t vtag, struct inpcb *inp)
1549 {
1550         const struct t4_offload_policy *op;
1551         char *pkt;
1552         struct offload_rule *r;
1553         int i, matched, pktlen, buflen;
1554         static const struct offload_settings allow_offloading_settings = {
1555                 .offload = 1,
1556                 .rx_coalesce = -1,
1557                 .cong_algo = -1,
1558                 .sched_class = -1,
1559                 .tstamp = -1,
1560                 .sack = -1,
1561                 .nagle = -1,
1562                 .ecn = -1,
1563                 .ddp = -1,
1564                 .tls = -1,
1565                 .txq = -1,
1566                 .rxq = -1,
1567                 .mss = -1,
1568         };
1569         static const struct offload_settings disallow_offloading_settings = {
1570                 .offload = 0,
1571                 /* rest is irrelevant when offload is off. */
1572         };
1573
1574         rw_assert(&sc->policy_lock, RA_LOCKED);
1575
1576         /*
1577          * If there's no Connection Offloading Policy attached to the device
1578          * then we need to return a default static policy.  If
1579          * "cop_managed_offloading" is true, then we need to disallow
1580          * offloading until a COP is attached to the device.  Otherwise we
1581          * allow offloading ...
1582          */
1583         op = sc->policy;
1584         if (op == NULL) {
1585                 if (sc->tt.cop_managed_offloading)
1586                         return (&disallow_offloading_settings);
1587                 else
1588                         return (&allow_offloading_settings);
1589         }
1590
1591         switch (open_type) {
1592         case OPEN_TYPE_ACTIVE:
1593         case OPEN_TYPE_LISTEN:
1594                 pkt = prepare_pkt(open_type, vtag, inp, &pktlen, &buflen);
1595                 break;
1596         case OPEN_TYPE_PASSIVE:
1597                 MPASS(m != NULL);
1598                 pkt = mtod(m, char *);
1599                 MPASS(*pkt == CPL_PASS_ACCEPT_REQ);
1600                 pkt += sizeof(struct cpl_pass_accept_req);
1601                 pktlen = m->m_pkthdr.len - sizeof(struct cpl_pass_accept_req);
1602                 buflen = m->m_len - sizeof(struct cpl_pass_accept_req);
1603                 break;
1604         default:
1605                 MPASS(0);
1606                 return (&disallow_offloading_settings);
1607         }
1608
1609         if (pkt == NULL || pktlen == 0 || buflen == 0)
1610                 return (&disallow_offloading_settings);
1611
1612         matched = 0;
1613         r = &op->rule[0];
1614         for (i = 0; i < op->nrules; i++, r++) {
1615                 if (r->open_type != open_type &&
1616                     r->open_type != OPEN_TYPE_DONTCARE) {
1617                         continue;
1618                 }
1619                 matched = bpf_filter(r->bpf_prog.bf_insns, pkt, pktlen, buflen);
1620                 if (matched)
1621                         break;
1622         }
1623
1624         if (open_type == OPEN_TYPE_ACTIVE || open_type == OPEN_TYPE_LISTEN)
1625                 free(pkt, M_CXGBE);
1626
1627         return (matched ? &r->settings : &disallow_offloading_settings);
1628 }
1629
1630 static void
1631 reclaim_wr_resources(void *arg, int count)
1632 {
1633         struct tom_data *td = arg;
1634         STAILQ_HEAD(, wrqe) twr_list = STAILQ_HEAD_INITIALIZER(twr_list);
1635         struct cpl_act_open_req *cpl;
1636         u_int opcode, atid, tid;
1637         struct wrqe *wr;
1638         struct adapter *sc = td_adapter(td);
1639
1640         mtx_lock(&td->unsent_wr_lock);
1641         STAILQ_SWAP(&td->unsent_wr_list, &twr_list, wrqe);
1642         mtx_unlock(&td->unsent_wr_lock);
1643
1644         while ((wr = STAILQ_FIRST(&twr_list)) != NULL) {
1645                 STAILQ_REMOVE_HEAD(&twr_list, link);
1646
1647                 cpl = wrtod(wr);
1648                 opcode = GET_OPCODE(cpl);
1649
1650                 switch (opcode) {
1651                 case CPL_ACT_OPEN_REQ:
1652                 case CPL_ACT_OPEN_REQ6:
1653                         atid = G_TID_TID(be32toh(OPCODE_TID(cpl)));
1654                         CTR2(KTR_CXGBE, "%s: atid %u ", __func__, atid);
1655                         act_open_failure_cleanup(sc, atid, EHOSTUNREACH);
1656                         free(wr, M_CXGBE);
1657                         break;
1658                 case CPL_PASS_ACCEPT_RPL:
1659                         tid = GET_TID(cpl);
1660                         CTR2(KTR_CXGBE, "%s: tid %u ", __func__, tid);
1661                         synack_failure_cleanup(sc, tid);
1662                         free(wr, M_CXGBE);
1663                         break;
1664                 default:
1665                         log(LOG_ERR, "%s: leaked work request %p, wr_len %d, "
1666                             "opcode %x\n", __func__, wr, wr->wr_len, opcode);
1667                         /* WR not freed here; go look at it with a debugger.  */
1668                 }
1669         }
1670 }
1671
1672 /*
1673  * Ground control to Major TOM
1674  * Commencing countdown, engines on
1675  */
1676 static int
1677 t4_tom_activate(struct adapter *sc)
1678 {
1679         struct tom_data *td;
1680         struct toedev *tod;
1681         struct vi_info *vi;
1682         int i, rc, v;
1683
1684         ASSERT_SYNCHRONIZED_OP(sc);
1685
1686         /* per-adapter softc for TOM */
1687         td = malloc(sizeof(*td), M_CXGBE, M_ZERO | M_NOWAIT);
1688         if (td == NULL)
1689                 return (ENOMEM);
1690
1691         /* List of TOE PCBs and associated lock */
1692         mtx_init(&td->toep_list_lock, "PCB list lock", NULL, MTX_DEF);
1693         TAILQ_INIT(&td->toep_list);
1694
1695         /* Listen context */
1696         mtx_init(&td->lctx_hash_lock, "lctx hash lock", NULL, MTX_DEF);
1697         td->listen_hash = hashinit_flags(LISTEN_HASH_SIZE, M_CXGBE,
1698             &td->listen_mask, HASH_NOWAIT);
1699
1700         /* List of WRs for which L2 resolution failed */
1701         mtx_init(&td->unsent_wr_lock, "Unsent WR list lock", NULL, MTX_DEF);
1702         STAILQ_INIT(&td->unsent_wr_list);
1703         TASK_INIT(&td->reclaim_wr_resources, 0, reclaim_wr_resources, td);
1704
1705         /* TID tables */
1706         rc = alloc_tid_tabs(&sc->tids);
1707         if (rc != 0)
1708                 goto done;
1709
1710         rc = t4_init_ppod_region(&td->pr, &sc->vres.ddp,
1711             t4_read_reg(sc, A_ULP_RX_TDDP_PSZ), "TDDP page pods");
1712         if (rc != 0)
1713                 goto done;
1714         t4_set_reg_field(sc, A_ULP_RX_TDDP_TAGMASK,
1715             V_TDDPTAGMASK(M_TDDPTAGMASK), td->pr.pr_tag_mask);
1716
1717         alloc_tcb_history(sc, td);
1718
1719         /* toedev ops */
1720         tod = &td->tod;
1721         init_toedev(tod);
1722         tod->tod_softc = sc;
1723         tod->tod_connect = t4_connect;
1724         tod->tod_listen_start = t4_listen_start;
1725         tod->tod_listen_stop = t4_listen_stop;
1726         tod->tod_rcvd = t4_rcvd;
1727         tod->tod_output = t4_tod_output;
1728         tod->tod_send_rst = t4_send_rst;
1729         tod->tod_send_fin = t4_send_fin;
1730         tod->tod_pcb_detach = t4_pcb_detach;
1731         tod->tod_l2_update = t4_l2_update;
1732         tod->tod_syncache_added = t4_syncache_added;
1733         tod->tod_syncache_removed = t4_syncache_removed;
1734         tod->tod_syncache_respond = t4_syncache_respond;
1735         tod->tod_offload_socket = t4_offload_socket;
1736         tod->tod_ctloutput = t4_ctloutput;
1737         tod->tod_tcp_info = t4_tcp_info;
1738 #ifdef KERN_TLS
1739         tod->tod_alloc_tls_session = t4_alloc_tls_session;
1740 #endif
1741
1742         for_each_port(sc, i) {
1743                 for_each_vi(sc->port[i], v, vi) {
1744                         TOEDEV(vi->ifp) = &td->tod;
1745                 }
1746         }
1747
1748         sc->tom_softc = td;
1749         register_toedev(sc->tom_softc);
1750
1751 done:
1752         if (rc != 0)
1753                 free_tom_data(sc, td);
1754         return (rc);
1755 }
1756
1757 static int
1758 t4_tom_deactivate(struct adapter *sc)
1759 {
1760         int rc = 0;
1761         struct tom_data *td = sc->tom_softc;
1762
1763         ASSERT_SYNCHRONIZED_OP(sc);
1764
1765         if (td == NULL)
1766                 return (0);     /* XXX. KASSERT? */
1767
1768         if (sc->offload_map != 0)
1769                 return (EBUSY); /* at least one port has IFCAP_TOE enabled */
1770
1771         if (uld_active(sc, ULD_IWARP) || uld_active(sc, ULD_ISCSI))
1772                 return (EBUSY); /* both iWARP and iSCSI rely on the TOE. */
1773
1774         mtx_lock(&td->toep_list_lock);
1775         if (!TAILQ_EMPTY(&td->toep_list))
1776                 rc = EBUSY;
1777         mtx_unlock(&td->toep_list_lock);
1778
1779         mtx_lock(&td->lctx_hash_lock);
1780         if (td->lctx_count > 0)
1781                 rc = EBUSY;
1782         mtx_unlock(&td->lctx_hash_lock);
1783
1784         taskqueue_drain(taskqueue_thread, &td->reclaim_wr_resources);
1785         mtx_lock(&td->unsent_wr_lock);
1786         if (!STAILQ_EMPTY(&td->unsent_wr_list))
1787                 rc = EBUSY;
1788         mtx_unlock(&td->unsent_wr_lock);
1789
1790         if (rc == 0) {
1791                 unregister_toedev(sc->tom_softc);
1792                 free_tom_data(sc, td);
1793                 sc->tom_softc = NULL;
1794         }
1795
1796         return (rc);
1797 }
1798
1799 static int
1800 t4_aio_queue_tom(struct socket *so, struct kaiocb *job)
1801 {
1802         struct tcpcb *tp = so_sototcpcb(so);
1803         struct toepcb *toep = tp->t_toe;
1804         int error;
1805
1806         if (ulp_mode(toep) == ULP_MODE_TCPDDP) {
1807                 error = t4_aio_queue_ddp(so, job);
1808                 if (error != EOPNOTSUPP)
1809                         return (error);
1810         }
1811
1812         return (t4_aio_queue_aiotx(so, job));
1813 }
1814
1815 static int
1816 t4_ctloutput_tom(struct socket *so, struct sockopt *sopt)
1817 {
1818
1819         if (sopt->sopt_level != IPPROTO_TCP)
1820                 return (tcp_ctloutput(so, sopt));
1821
1822         switch (sopt->sopt_name) {
1823         case TCP_TLSOM_SET_TLS_CONTEXT:
1824         case TCP_TLSOM_GET_TLS_TOM:
1825         case TCP_TLSOM_CLR_TLS_TOM:
1826         case TCP_TLSOM_CLR_QUIES:
1827                 return (t4_ctloutput_tls(so, sopt));
1828         default:
1829                 return (tcp_ctloutput(so, sopt));
1830         }
1831 }
1832
1833 static int
1834 t4_tom_mod_load(void)
1835 {
1836         struct protosw *tcp_protosw, *tcp6_protosw;
1837
1838         /* CPL handlers */
1839         t4_register_cpl_handler(CPL_GET_TCB_RPL, do_get_tcb_rpl);
1840         t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL, do_l2t_write_rpl2,
1841             CPL_COOKIE_TOM);
1842         t4_init_connect_cpl_handlers();
1843         t4_init_listen_cpl_handlers();
1844         t4_init_cpl_io_handlers();
1845
1846         t4_ddp_mod_load();
1847         t4_tls_mod_load();
1848
1849         tcp_protosw = pffindproto(PF_INET, IPPROTO_TCP, SOCK_STREAM);
1850         if (tcp_protosw == NULL)
1851                 return (ENOPROTOOPT);
1852         bcopy(tcp_protosw, &toe_protosw, sizeof(toe_protosw));
1853         bcopy(tcp_protosw->pr_usrreqs, &toe_usrreqs, sizeof(toe_usrreqs));
1854         toe_usrreqs.pru_aio_queue = t4_aio_queue_tom;
1855         toe_protosw.pr_ctloutput = t4_ctloutput_tom;
1856         toe_protosw.pr_usrreqs = &toe_usrreqs;
1857
1858         tcp6_protosw = pffindproto(PF_INET6, IPPROTO_TCP, SOCK_STREAM);
1859         if (tcp6_protosw == NULL)
1860                 return (ENOPROTOOPT);
1861         bcopy(tcp6_protosw, &toe6_protosw, sizeof(toe6_protosw));
1862         bcopy(tcp6_protosw->pr_usrreqs, &toe6_usrreqs, sizeof(toe6_usrreqs));
1863         toe6_usrreqs.pru_aio_queue = t4_aio_queue_tom;
1864         toe6_protosw.pr_ctloutput = t4_ctloutput_tom;
1865         toe6_protosw.pr_usrreqs = &toe6_usrreqs;
1866
1867         return (t4_register_uld(&tom_uld_info));
1868 }
1869
1870 static void
1871 tom_uninit(struct adapter *sc, void *arg __unused)
1872 {
1873         if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tomun"))
1874                 return;
1875
1876         /* Try to free resources (works only if no port has IFCAP_TOE) */
1877         if (uld_active(sc, ULD_TOM))
1878                 t4_deactivate_uld(sc, ULD_TOM);
1879
1880         end_synchronized_op(sc, 0);
1881 }
1882
1883 static int
1884 t4_tom_mod_unload(void)
1885 {
1886         t4_iterate(tom_uninit, NULL);
1887
1888         if (t4_unregister_uld(&tom_uld_info) == EBUSY)
1889                 return (EBUSY);
1890
1891         t4_tls_mod_unload();
1892         t4_ddp_mod_unload();
1893
1894         t4_uninit_connect_cpl_handlers();
1895         t4_uninit_listen_cpl_handlers();
1896         t4_uninit_cpl_io_handlers();
1897         t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL, NULL, CPL_COOKIE_TOM);
1898         t4_register_cpl_handler(CPL_GET_TCB_RPL, NULL);
1899
1900         return (0);
1901 }
1902 #endif  /* TCP_OFFLOAD */
1903
1904 static int
1905 t4_tom_modevent(module_t mod, int cmd, void *arg)
1906 {
1907         int rc = 0;
1908
1909 #ifdef TCP_OFFLOAD
1910         switch (cmd) {
1911         case MOD_LOAD:
1912                 rc = t4_tom_mod_load();
1913                 break;
1914
1915         case MOD_UNLOAD:
1916                 rc = t4_tom_mod_unload();
1917                 break;
1918
1919         default:
1920                 rc = EINVAL;
1921         }
1922 #else
1923         printf("t4_tom: compiled without TCP_OFFLOAD support.\n");
1924         rc = EOPNOTSUPP;
1925 #endif
1926         return (rc);
1927 }
1928
1929 static moduledata_t t4_tom_moddata= {
1930         "t4_tom",
1931         t4_tom_modevent,
1932         0
1933 };
1934
1935 MODULE_VERSION(t4_tom, 1);
1936 MODULE_DEPEND(t4_tom, toecore, 1, 1, 1);
1937 MODULE_DEPEND(t4_tom, t4nex, 1, 1, 1);
1938 DECLARE_MODULE(t4_tom, t4_tom_moddata, SI_SUB_EXEC, SI_ORDER_ANY);