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