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