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