xref: /freebsd/sys/dev/cxgbe/tom/t4_tom.c (revision 35b883ccf36521a46ba1cd959c144328cce223c5)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_kern_tls.h"
34 #include "opt_ratelimit.h"
35 
36 #include <sys/param.h>
37 #include <sys/types.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/ktr.h>
41 #include <sys/lock.h>
42 #include <sys/limits.h>
43 #include <sys/module.h>
44 #include <sys/protosw.h>
45 #include <sys/domain.h>
46 #include <sys/refcount.h>
47 #include <sys/rmlock.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/taskqueue.h>
52 #include <net/if.h>
53 #include <net/if_var.h>
54 #include <net/if_types.h>
55 #include <net/if_vlan_var.h>
56 #include <netinet/in.h>
57 #include <netinet/in_pcb.h>
58 #include <netinet/in_var.h>
59 #include <netinet/ip.h>
60 #include <netinet/ip6.h>
61 #include <netinet6/scope6_var.h>
62 #define TCPSTATES
63 #include <netinet/tcp_fsm.h>
64 #include <netinet/tcp_seq.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 protosw toe6_protosw;
83 
84 /* Module ops */
85 static int t4_tom_mod_load(void);
86 static int t4_tom_mod_unload(void);
87 static int t4_tom_modevent(module_t, int, void *);
88 
89 /* ULD ops and helpers */
90 static int t4_tom_activate(struct adapter *);
91 static int t4_tom_deactivate(struct adapter *);
92 static int t4_tom_stop(struct adapter *);
93 static int t4_tom_restart(struct adapter *);
94 
95 static struct uld_info tom_uld_info = {
96 	.uld_activate = t4_tom_activate,
97 	.uld_deactivate = t4_tom_deactivate,
98 	.uld_stop = t4_tom_stop,
99 	.uld_restart = t4_tom_restart,
100 };
101 
102 static void release_offload_resources(struct toepcb *);
103 static void done_with_toepcb(struct toepcb *);
104 static int alloc_tid_tabs(struct adapter *);
105 static void free_tid_tabs(struct adapter *);
106 static void free_tom_data(struct adapter *, struct tom_data *);
107 static void reclaim_wr_resources(void *, int);
108 static void cleanup_stranded_tids(void *, int);
109 
110 struct toepcb *
111 alloc_toepcb(struct vi_info *vi, int flags)
112 {
113 	struct port_info *pi = vi->pi;
114 	struct adapter *sc = pi->adapter;
115 	struct toepcb *toep;
116 	int tx_credits, txsd_total, len;
117 
118 	/*
119 	 * The firmware counts tx work request credits in units of 16 bytes
120 	 * each.  Reserve room for an ABORT_REQ so the driver never has to worry
121 	 * about tx credits if it wants to abort a connection.
122 	 */
123 	tx_credits = sc->params.ofldq_wr_cred;
124 	tx_credits -= howmany(sizeof(struct cpl_abort_req), 16);
125 
126 	/*
127 	 * Shortest possible tx work request is a fw_ofld_tx_data_wr + 1 byte
128 	 * immediate payload, and firmware counts tx work request credits in
129 	 * units of 16 byte.  Calculate the maximum work requests possible.
130 	 */
131 	txsd_total = tx_credits /
132 	    howmany(sizeof(struct fw_ofld_tx_data_wr) + 1, 16);
133 
134 	len = offsetof(struct toepcb, txsd) +
135 	    txsd_total * sizeof(struct ofld_tx_sdesc);
136 
137 	toep = malloc(len, M_CXGBE, M_ZERO | flags);
138 	if (toep == NULL)
139 		return (NULL);
140 
141 	refcount_init(&toep->refcount, 1);
142 	toep->td = sc->tom_softc;
143 	toep->incarnation = sc->incarnation;
144 	toep->vi = vi;
145 	toep->tid = -1;
146 	toep->tx_total = tx_credits;
147 	toep->tx_credits = tx_credits;
148 	mbufq_init(&toep->ulp_pduq, INT_MAX);
149 	mbufq_init(&toep->ulp_pdu_reclaimq, INT_MAX);
150 	toep->txsd_total = txsd_total;
151 	toep->txsd_avail = txsd_total;
152 	toep->txsd_pidx = 0;
153 	toep->txsd_cidx = 0;
154 	aiotx_init_toep(toep);
155 
156 	return (toep);
157 }
158 
159 /*
160  * Initialize a toepcb after its params have been filled out.
161  */
162 int
163 init_toepcb(struct vi_info *vi, struct toepcb *toep)
164 {
165 	struct conn_params *cp = &toep->params;
166 	struct port_info *pi = vi->pi;
167 	struct adapter *sc = pi->adapter;
168 	struct tx_cl_rl_params *tc;
169 
170 	if (cp->tc_idx >= 0 && cp->tc_idx < sc->params.nsched_cls) {
171 		tc = &pi->sched_params->cl_rl[cp->tc_idx];
172 		mtx_lock(&sc->tc_lock);
173 		if (tc->state != CS_HW_CONFIGURED) {
174 			CH_ERR(vi, "tid %d cannot be bound to traffic class %d "
175 			    "because it is not configured (its state is %d)\n",
176 			    toep->tid, cp->tc_idx, tc->state);
177 			cp->tc_idx = -1;
178 		} else {
179 			tc->refcount++;
180 		}
181 		mtx_unlock(&sc->tc_lock);
182 	}
183 	toep->ofld_txq = &sc->sge.ofld_txq[cp->txq_idx];
184 	toep->ofld_rxq = &sc->sge.ofld_rxq[cp->rxq_idx];
185 	toep->ctrlq = &sc->sge.ctrlq[cp->ctrlq_idx];
186 
187 	tls_init_toep(toep);
188 	MPASS(ulp_mode(toep) != ULP_MODE_TCPDDP);
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 
261 void
262 restore_so_proto(struct socket *so, bool v6)
263 {
264 	if (v6)
265 		so->so_proto = &tcp6_protosw;
266 	else
267 		so->so_proto = &tcp_protosw;
268 }
269 
270 /* This is _not_ the normal way to "unoffload" a socket. */
271 void
272 undo_offload_socket(struct socket *so)
273 {
274 	struct inpcb *inp = sotoinpcb(so);
275 	struct tcpcb *tp = intotcpcb(inp);
276 	struct toepcb *toep = tp->t_toe;
277 	struct sockbuf *sb;
278 
279 	INP_WLOCK_ASSERT(inp);
280 
281 	sb = &so->so_snd;
282 	SOCKBUF_LOCK(sb);
283 	sb->sb_flags &= ~SB_NOCOALESCE;
284 	SOCKBUF_UNLOCK(sb);
285 	sb = &so->so_rcv;
286 	SOCKBUF_LOCK(sb);
287 	sb->sb_flags &= ~SB_NOCOALESCE;
288 	restore_so_proto(so, inp->inp_vflag & INP_IPV6);
289 	SOCKBUF_UNLOCK(sb);
290 
291 	tp->tod = NULL;
292 	tp->t_toe = NULL;
293 	tp->t_flags &= ~TF_TOE;
294 
295 	toep->inp = NULL;
296 	toep->flags &= ~TPF_ATTACHED;
297 	if (in_pcbrele_wlocked(inp))
298 		panic("%s: inp freed.", __func__);
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 
311 	CTR5(KTR_CXGBE, "%s: toep %p (tid %d, l2te %p, ce %p)",
312 	    __func__, toep, tid, toep->l2te, toep->ce);
313 
314 	if (toep->l2te) {
315 		t4_l2t_release(toep->l2te);
316 		toep->l2te = NULL;
317 	}
318 	if (tid >= 0) {
319 		remove_tid(sc, tid, toep->ce ? 2 : 1);
320 		release_tid(sc, tid, toep->ctrlq);
321 		toep->tid = -1;
322 		mtx_lock(&td->toep_list_lock);
323 		if (toep->flags & TPF_IN_TOEP_LIST) {
324 			toep->flags &= ~TPF_IN_TOEP_LIST;
325 			TAILQ_REMOVE(&td->toep_list, toep, link);
326 		}
327 		mtx_unlock(&td->toep_list_lock);
328 	}
329 	if (toep->ce) {
330 		t4_release_clip_entry(sc, toep->ce);
331 		toep->ce = NULL;
332 	}
333 	if (toep->params.tc_idx != -1)
334 		t4_release_cl_rl(sc, toep->vi->pi->port_id, toep->params.tc_idx);
335 }
336 
337 /*
338  * Both the driver and kernel are done with the toepcb.
339  */
340 static void
341 done_with_toepcb(struct toepcb *toep)
342 {
343 	KASSERT(!(toep->flags & TPF_CPL_PENDING),
344 	    ("%s: %p has CPL pending.", __func__, toep));
345 	KASSERT(!(toep->flags & TPF_ATTACHED),
346 	    ("%s: %p is still attached.", __func__, toep));
347 
348 	CTR(KTR_CXGBE, "%s: toep %p (0x%x)", __func__, toep, toep->flags);
349 
350 	/*
351 	 * These queues should have been emptied at approximately the same time
352 	 * that a normal connection's socket's so_snd would have been purged or
353 	 * drained.  Do _not_ clean up here.
354 	 */
355 	MPASS(mbufq_empty(&toep->ulp_pduq));
356 	MPASS(mbufq_empty(&toep->ulp_pdu_reclaimq));
357 #ifdef INVARIANTS
358 	if (ulp_mode(toep) == ULP_MODE_TCPDDP)
359 		ddp_assert_empty(toep);
360 #endif
361 	MPASS(TAILQ_EMPTY(&toep->aiotx_jobq));
362 	MPASS(toep->tid == -1);
363 	MPASS(toep->l2te == NULL);
364 	MPASS(toep->ce == NULL);
365 	MPASS((toep->flags & TPF_IN_TOEP_LIST) == 0);
366 
367 	free_toepcb(toep);
368 }
369 
370 /*
371  * The kernel is done with the TCP PCB and this is our opportunity to unhook the
372  * toepcb hanging off of it.  If the TOE driver is also done with the toepcb (no
373  * pending CPL) then it is time to release all resources tied to the toepcb.
374  *
375  * Also gets called when an offloaded active open fails and the TOM wants the
376  * kernel to take the TCP PCB back.
377  */
378 void
379 t4_pcb_detach(struct toedev *tod __unused, struct tcpcb *tp)
380 {
381 #if defined(KTR) || defined(INVARIANTS)
382 	struct inpcb *inp = tptoinpcb(tp);
383 #endif
384 	struct toepcb *toep = tp->t_toe;
385 
386 	INP_WLOCK_ASSERT(inp);
387 
388 	KASSERT(toep != NULL, ("%s: toep is NULL", __func__));
389 	KASSERT(toep->flags & TPF_ATTACHED,
390 	    ("%s: not attached", __func__));
391 
392 #ifdef KTR
393 	if (tp->t_state == TCPS_SYN_SENT) {
394 		CTR6(KTR_CXGBE, "%s: atid %d, toep %p (0x%x), inp %p (0x%x)",
395 		    __func__, toep->tid, toep, toep->flags, inp,
396 		    inp->inp_flags);
397 	} else {
398 		CTR6(KTR_CXGBE,
399 		    "t4_pcb_detach: tid %d (%s), toep %p (0x%x), inp %p (0x%x)",
400 		    toep->tid, tcpstates[tp->t_state], toep, toep->flags, inp,
401 		    inp->inp_flags);
402 	}
403 #endif
404 
405 	tp->tod = NULL;
406 	tp->t_toe = NULL;
407 	tp->t_flags &= ~TF_TOE;
408 	toep->flags &= ~TPF_ATTACHED;
409 
410 	if (!(toep->flags & TPF_CPL_PENDING))
411 		done_with_toepcb(toep);
412 }
413 
414 /*
415  * setsockopt handler.
416  */
417 static void
418 t4_ctloutput(struct toedev *tod, struct tcpcb *tp, int dir, int name)
419 {
420 	struct adapter *sc = tod->tod_softc;
421 	struct toepcb *toep = tp->t_toe;
422 
423 	if (dir == SOPT_GET)
424 		return;
425 
426 	CTR4(KTR_CXGBE, "%s: tp %p, dir %u, name %u", __func__, tp, dir, name);
427 
428 	switch (name) {
429 	case TCP_NODELAY:
430 		if (tp->t_state != TCPS_ESTABLISHED)
431 			break;
432 		toep->params.nagle = tp->t_flags & TF_NODELAY ? 0 : 1;
433 		t4_set_tcb_field(sc, toep->ctrlq, toep, W_TCB_T_FLAGS,
434 		    V_TF_NAGLE(1), V_TF_NAGLE(toep->params.nagle), 0, 0);
435 		break;
436 	default:
437 		break;
438 	}
439 }
440 
441 static inline uint64_t
442 get_tcb_tflags(const uint64_t *tcb)
443 {
444 
445 	return ((be64toh(tcb[14]) << 32) | (be64toh(tcb[15]) >> 32));
446 }
447 
448 static inline uint32_t
449 get_tcb_field(const uint64_t *tcb, u_int word, uint32_t mask, u_int shift)
450 {
451 #define LAST_WORD ((TCB_SIZE / 4) - 1)
452 	uint64_t t1, t2;
453 	int flit_idx;
454 
455 	MPASS(mask != 0);
456 	MPASS(word <= LAST_WORD);
457 	MPASS(shift < 32);
458 
459 	flit_idx = (LAST_WORD - word) / 2;
460 	if (word & 0x1)
461 		shift += 32;
462 	t1 = be64toh(tcb[flit_idx]) >> shift;
463 	t2 = 0;
464 	if (fls(mask) > 64 - shift) {
465 		/*
466 		 * Will spill over into the next logical flit, which is the flit
467 		 * before this one.  The flit_idx before this one must be valid.
468 		 */
469 		MPASS(flit_idx > 0);
470 		t2 = be64toh(tcb[flit_idx - 1]) << (64 - shift);
471 	}
472 	return ((t2 | t1) & mask);
473 #undef LAST_WORD
474 }
475 #define GET_TCB_FIELD(tcb, F) \
476     get_tcb_field(tcb, W_TCB_##F, M_TCB_##F, S_TCB_##F)
477 
478 /*
479  * Issues a CPL_GET_TCB to read the entire TCB for the tid.
480  */
481 static int
482 send_get_tcb(struct adapter *sc, u_int tid)
483 {
484 	struct cpl_get_tcb *cpl;
485 	struct wrq_cookie cookie;
486 
487 	MPASS(tid >= sc->tids.tid_base);
488 	MPASS(tid - sc->tids.tid_base < sc->tids.ntids);
489 
490 	cpl = start_wrq_wr(&sc->sge.ctrlq[0], howmany(sizeof(*cpl), 16),
491 	    &cookie);
492 	if (__predict_false(cpl == NULL))
493 		return (ENOMEM);
494 	bzero(cpl, sizeof(*cpl));
495 	INIT_TP_WR(cpl, tid);
496 	OPCODE_TID(cpl) = htobe32(MK_OPCODE_TID(CPL_GET_TCB, tid));
497 	if (chip_id(sc) >= CHELSIO_T7) {
498 		cpl->reply_ctrl =
499 		    htobe16(V_T7_QUEUENO(sc->sge.ofld_rxq[0].iq.cntxt_id) |
500 			V_T7_REPLY_CHAN(0) | V_NO_REPLY(0));
501 	} else {
502 		cpl->reply_ctrl =
503 		    htobe16(V_QUEUENO(sc->sge.ofld_rxq[0].iq.cntxt_id) |
504 			V_REPLY_CHAN(0) | V_NO_REPLY(0));
505 	}
506 	cpl->cookie = 0xff;
507 	commit_wrq_wr(&sc->sge.ctrlq[0], cpl, &cookie);
508 
509 	return (0);
510 }
511 
512 static struct tcb_histent *
513 alloc_tcb_histent(struct adapter *sc, u_int tid, int flags)
514 {
515 	struct tcb_histent *te;
516 
517 	MPASS(flags == M_NOWAIT || flags == M_WAITOK);
518 
519 	te = malloc(sizeof(*te), M_CXGBE, M_ZERO | flags);
520 	if (te == NULL)
521 		return (NULL);
522 	mtx_init(&te->te_lock, "TCB entry", NULL, MTX_DEF);
523 	callout_init_mtx(&te->te_callout, &te->te_lock, 0);
524 	te->te_adapter = sc;
525 	te->te_tid = tid;
526 
527 	return (te);
528 }
529 
530 static void
531 free_tcb_histent(struct tcb_histent *te)
532 {
533 
534 	mtx_destroy(&te->te_lock);
535 	free(te, M_CXGBE);
536 }
537 
538 /*
539  * Start tracking the tid in the TCB history.
540  */
541 int
542 add_tid_to_history(struct adapter *sc, u_int tid)
543 {
544 	struct tcb_histent *te = NULL;
545 	struct tom_data *td = sc->tom_softc;
546 	int rc;
547 
548 	MPASS(tid >= sc->tids.tid_base);
549 	MPASS(tid - sc->tids.tid_base < sc->tids.ntids);
550 
551 	if (td->tcb_history == NULL)
552 		return (ENXIO);
553 
554 	rw_wlock(&td->tcb_history_lock);
555 	if (td->tcb_history[tid] != NULL) {
556 		rc = EEXIST;
557 		goto done;
558 	}
559 	te = alloc_tcb_histent(sc, tid, M_NOWAIT);
560 	if (te == NULL) {
561 		rc = ENOMEM;
562 		goto done;
563 	}
564 	mtx_lock(&te->te_lock);
565 	rc = send_get_tcb(sc, tid);
566 	if (rc == 0) {
567 		te->te_flags |= TE_RPL_PENDING;
568 		td->tcb_history[tid] = te;
569 	} else {
570 		free(te, M_CXGBE);
571 	}
572 	mtx_unlock(&te->te_lock);
573 done:
574 	rw_wunlock(&td->tcb_history_lock);
575 	return (rc);
576 }
577 
578 static void
579 remove_tcb_histent(struct tcb_histent *te)
580 {
581 	struct adapter *sc = te->te_adapter;
582 	struct tom_data *td = sc->tom_softc;
583 
584 	rw_assert(&td->tcb_history_lock, RA_WLOCKED);
585 	mtx_assert(&te->te_lock, MA_OWNED);
586 	MPASS(td->tcb_history[te->te_tid] == te);
587 
588 	td->tcb_history[te->te_tid] = NULL;
589 	free_tcb_histent(te);
590 	rw_wunlock(&td->tcb_history_lock);
591 }
592 
593 static inline struct tcb_histent *
594 lookup_tcb_histent(struct adapter *sc, u_int tid, bool addrem)
595 {
596 	struct tcb_histent *te;
597 	struct tom_data *td = sc->tom_softc;
598 
599 	MPASS(tid >= sc->tids.tid_base);
600 	MPASS(tid - sc->tids.tid_base < sc->tids.ntids);
601 
602 	if (td->tcb_history == NULL)
603 		return (NULL);
604 
605 	if (addrem)
606 		rw_wlock(&td->tcb_history_lock);
607 	else
608 		rw_rlock(&td->tcb_history_lock);
609 	te = td->tcb_history[tid];
610 	if (te != NULL) {
611 		mtx_lock(&te->te_lock);
612 		return (te);	/* with both locks held */
613 	}
614 	if (addrem)
615 		rw_wunlock(&td->tcb_history_lock);
616 	else
617 		rw_runlock(&td->tcb_history_lock);
618 
619 	return (te);
620 }
621 
622 static inline void
623 release_tcb_histent(struct tcb_histent *te)
624 {
625 	struct adapter *sc = te->te_adapter;
626 	struct tom_data *td = sc->tom_softc;
627 
628 	mtx_assert(&te->te_lock, MA_OWNED);
629 	mtx_unlock(&te->te_lock);
630 	rw_assert(&td->tcb_history_lock, RA_RLOCKED);
631 	rw_runlock(&td->tcb_history_lock);
632 }
633 
634 static void
635 request_tcb(void *arg)
636 {
637 	struct tcb_histent *te = arg;
638 
639 	mtx_assert(&te->te_lock, MA_OWNED);
640 
641 	/* Noone else is supposed to update the histent. */
642 	MPASS(!(te->te_flags & TE_RPL_PENDING));
643 	if (send_get_tcb(te->te_adapter, te->te_tid) == 0)
644 		te->te_flags |= TE_RPL_PENDING;
645 	else
646 		callout_schedule(&te->te_callout, hz / 100);
647 }
648 
649 static void
650 update_tcb_histent(struct tcb_histent *te, const uint64_t *tcb)
651 {
652 	struct tom_data *td = te->te_adapter->tom_softc;
653 	uint64_t tflags = get_tcb_tflags(tcb);
654 	uint8_t sample = 0;
655 
656 	if (GET_TCB_FIELD(tcb, SND_MAX_RAW) != GET_TCB_FIELD(tcb, SND_UNA_RAW)) {
657 		if (GET_TCB_FIELD(tcb, T_RXTSHIFT) != 0)
658 			sample |= TS_RTO;
659 		if (GET_TCB_FIELD(tcb, T_DUPACKS) != 0)
660 			sample |= TS_DUPACKS;
661 		if (GET_TCB_FIELD(tcb, T_DUPACKS) >= td->dupack_threshold)
662 			sample |= TS_FASTREXMT;
663 	}
664 
665 	if (GET_TCB_FIELD(tcb, SND_MAX_RAW) != 0) {
666 		uint32_t snd_wnd;
667 
668 		sample |= TS_SND_BACKLOGGED;	/* for whatever reason. */
669 
670 		snd_wnd = GET_TCB_FIELD(tcb, RCV_ADV);
671 		if (tflags & V_TF_RECV_SCALE(1))
672 			snd_wnd <<= GET_TCB_FIELD(tcb, RCV_SCALE);
673 		if (GET_TCB_FIELD(tcb, SND_CWND) < snd_wnd)
674 			sample |= TS_CWND_LIMITED;	/* maybe due to CWND */
675 	}
676 
677 	if (tflags & V_TF_CCTRL_ECN(1)) {
678 
679 		/*
680 		 * CE marker on incoming IP hdr, echoing ECE back in the TCP
681 		 * hdr.  Indicates congestion somewhere on the way from the peer
682 		 * to this node.
683 		 */
684 		if (tflags & V_TF_CCTRL_ECE(1))
685 			sample |= TS_ECN_ECE;
686 
687 		/*
688 		 * ECE seen and CWR sent (or about to be sent).  Might indicate
689 		 * congestion on the way to the peer.  This node is reducing its
690 		 * congestion window in response.
691 		 */
692 		if (tflags & (V_TF_CCTRL_CWR(1) | V_TF_CCTRL_RFR(1)))
693 			sample |= TS_ECN_CWR;
694 	}
695 
696 	te->te_sample[te->te_pidx] = sample;
697 	if (++te->te_pidx == nitems(te->te_sample))
698 		te->te_pidx = 0;
699 	memcpy(te->te_tcb, tcb, TCB_SIZE);
700 	te->te_flags |= TE_ACTIVE;
701 }
702 
703 static int
704 do_get_tcb_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
705 {
706 	struct adapter *sc = iq->adapter;
707 	const struct cpl_get_tcb_rpl *cpl = mtod(m, const void *);
708 	const uint64_t *tcb = (const uint64_t *)(const void *)(cpl + 1);
709 	struct tcb_histent *te;
710 	const u_int tid = GET_TID(cpl);
711 	bool remove;
712 
713 	remove = GET_TCB_FIELD(tcb, T_STATE) == TCPS_CLOSED;
714 	te = lookup_tcb_histent(sc, tid, remove);
715 	if (te == NULL) {
716 		/* Not in the history.  Who issued the GET_TCB for this? */
717 		device_printf(sc->dev, "tcb %u: flags 0x%016jx, state %u, "
718 		    "srtt %u, sscale %u, rscale %u, cookie 0x%x\n", tid,
719 		    (uintmax_t)get_tcb_tflags(tcb), GET_TCB_FIELD(tcb, T_STATE),
720 		    GET_TCB_FIELD(tcb, T_SRTT), GET_TCB_FIELD(tcb, SND_SCALE),
721 		    GET_TCB_FIELD(tcb, RCV_SCALE), cpl->cookie);
722 		goto done;
723 	}
724 
725 	MPASS(te->te_flags & TE_RPL_PENDING);
726 	te->te_flags &= ~TE_RPL_PENDING;
727 	if (remove) {
728 		remove_tcb_histent(te);
729 	} else {
730 		update_tcb_histent(te, tcb);
731 		callout_reset(&te->te_callout, hz / 10, request_tcb, te);
732 		release_tcb_histent(te);
733 	}
734 done:
735 	m_freem(m);
736 	return (0);
737 }
738 
739 static void
740 fill_tcp_info_from_tcb(struct adapter *sc, uint64_t *tcb, struct tcp_info *ti)
741 {
742 	uint32_t v;
743 
744 	ti->tcpi_state = GET_TCB_FIELD(tcb, T_STATE);
745 
746 	v = GET_TCB_FIELD(tcb, T_SRTT);
747 	ti->tcpi_rtt = tcp_ticks_to_us(sc, v);
748 
749 	v = GET_TCB_FIELD(tcb, T_RTTVAR);
750 	ti->tcpi_rttvar = tcp_ticks_to_us(sc, v);
751 
752 	ti->tcpi_snd_ssthresh = GET_TCB_FIELD(tcb, SND_SSTHRESH);
753 	ti->tcpi_snd_cwnd = GET_TCB_FIELD(tcb, SND_CWND);
754 	ti->tcpi_rcv_nxt = GET_TCB_FIELD(tcb, RCV_NXT);
755 	ti->tcpi_rcv_adv = GET_TCB_FIELD(tcb, RCV_ADV);
756 	ti->tcpi_dupacks = GET_TCB_FIELD(tcb, T_DUPACKS);
757 
758 	v = GET_TCB_FIELD(tcb, TX_MAX);
759 	ti->tcpi_snd_nxt = v - GET_TCB_FIELD(tcb, SND_NXT_RAW);
760 	ti->tcpi_snd_una = v - GET_TCB_FIELD(tcb, SND_UNA_RAW);
761 	ti->tcpi_snd_max = v - GET_TCB_FIELD(tcb, SND_MAX_RAW);
762 
763 	/* Receive window being advertised by us. */
764 	ti->tcpi_rcv_wscale = GET_TCB_FIELD(tcb, SND_SCALE);	/* Yes, SND. */
765 	ti->tcpi_rcv_space = GET_TCB_FIELD(tcb, RCV_WND);
766 
767 	/* Send window */
768 	ti->tcpi_snd_wscale = GET_TCB_FIELD(tcb, RCV_SCALE);	/* Yes, RCV. */
769 	ti->tcpi_snd_wnd = GET_TCB_FIELD(tcb, RCV_ADV);
770 	if (get_tcb_tflags(tcb) & V_TF_RECV_SCALE(1))
771 		ti->tcpi_snd_wnd <<= ti->tcpi_snd_wscale;
772 	else
773 		ti->tcpi_snd_wscale = 0;
774 
775 }
776 
777 static void
778 fill_tcp_info_from_history(struct adapter *sc, struct tcb_histent *te,
779     struct tcp_info *ti)
780 {
781 
782 	fill_tcp_info_from_tcb(sc, te->te_tcb, ti);
783 }
784 
785 /*
786  * Reads the TCB for the given tid using a memory window and copies it to 'buf'
787  * in the same format as CPL_GET_TCB_RPL.
788  */
789 static void
790 read_tcb_using_memwin(struct adapter *sc, u_int tid, uint64_t *buf)
791 {
792 	int i, j, k, rc;
793 	uint32_t addr;
794 	u_char *tcb, tmp;
795 
796 	MPASS(tid >= sc->tids.tid_base);
797 	MPASS(tid - sc->tids.tid_base < sc->tids.ntids);
798 
799 	addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE) + tid * TCB_SIZE;
800 	rc = read_via_memwin(sc, 2, addr, (uint32_t *)buf, TCB_SIZE);
801 	if (rc != 0)
802 		return;
803 
804 	tcb = (u_char *)buf;
805 	for (i = 0, j = TCB_SIZE - 16; i < j; i += 16, j -= 16) {
806 		for (k = 0; k < 16; k++) {
807 			tmp = tcb[i + k];
808 			tcb[i + k] = tcb[j + k];
809 			tcb[j + k] = tmp;
810 		}
811 	}
812 }
813 
814 static void
815 fill_tcp_info(struct adapter *sc, u_int tid, struct tcp_info *ti)
816 {
817 	uint64_t tcb[TCB_SIZE / sizeof(uint64_t)];
818 	struct tcb_histent *te;
819 
820 	ti->tcpi_toe_tid = tid;
821 	te = lookup_tcb_histent(sc, tid, false);
822 	if (te != NULL) {
823 		fill_tcp_info_from_history(sc, te, ti);
824 		release_tcb_histent(te);
825 	} else {
826 		if (!(sc->debug_flags & DF_DISABLE_TCB_CACHE)) {
827 			/* XXX: tell firmware to flush TCB cache. */
828 		}
829 		read_tcb_using_memwin(sc, tid, tcb);
830 		fill_tcp_info_from_tcb(sc, tcb, ti);
831 	}
832 }
833 
834 /*
835  * Called by the kernel to allow the TOE driver to "refine" values filled up in
836  * the tcp_info for an offloaded connection.
837  */
838 static void
839 t4_tcp_info(struct toedev *tod, const struct tcpcb *tp, struct tcp_info *ti)
840 {
841 	struct adapter *sc = tod->tod_softc;
842 	struct toepcb *toep = tp->t_toe;
843 
844 	INP_LOCK_ASSERT(tptoinpcb(tp));
845 	MPASS(ti != NULL);
846 
847 	fill_tcp_info(sc, toep->tid, ti);
848 }
849 
850 #ifdef KERN_TLS
851 static int
852 t4_alloc_tls_session(struct toedev *tod, struct tcpcb *tp,
853     struct ktls_session *tls, int direction)
854 {
855 	struct toepcb *toep = tp->t_toe;
856 
857 	INP_WLOCK_ASSERT(tptoinpcb(tp));
858 	MPASS(tls != NULL);
859 
860 	return (tls_alloc_ktls(toep, tls, direction));
861 }
862 #endif
863 
864 static void
865 send_mss_flowc_wr(struct adapter *sc, struct toepcb *toep)
866 {
867 	struct wrq_cookie cookie;
868 	struct fw_flowc_wr *flowc;
869 	struct ofld_tx_sdesc *txsd;
870 	const int flowclen = sizeof(*flowc) + sizeof(struct fw_flowc_mnemval);
871 	const int flowclen16 = howmany(flowclen, 16);
872 
873 	if (toep->tx_credits < flowclen16 || toep->txsd_avail == 0) {
874 		CH_ERR(sc, "%s: tid %u out of tx credits (%d, %d).\n", __func__,
875 		    toep->tid, toep->tx_credits, toep->txsd_avail);
876 		return;
877 	}
878 
879 	flowc = start_wrq_wr(&toep->ofld_txq->wrq, flowclen16, &cookie);
880 	if (__predict_false(flowc == NULL)) {
881 		CH_ERR(sc, "ENOMEM in %s for tid %u.\n", __func__, toep->tid);
882 		return;
883 	}
884 	flowc->op_to_nparams = htobe32(V_FW_WR_OP(FW_FLOWC_WR) |
885 	    V_FW_FLOWC_WR_NPARAMS(1));
886 	flowc->flowid_len16 = htonl(V_FW_WR_LEN16(flowclen16) |
887 	    V_FW_WR_FLOWID(toep->tid));
888 	flowc->mnemval[0].mnemonic = FW_FLOWC_MNEM_MSS;
889 	flowc->mnemval[0].val = htobe32(toep->params.emss);
890 
891 	txsd = &toep->txsd[toep->txsd_pidx];
892 	_Static_assert(flowclen16 <= MAX_OFLD_TX_SDESC_CREDITS,
893 	    "MAX_OFLD_TX_SDESC_CREDITS too small");
894 	txsd->tx_credits = flowclen16;
895 	txsd->plen = 0;
896 	toep->tx_credits -= txsd->tx_credits;
897 	if (__predict_false(++toep->txsd_pidx == toep->txsd_total))
898 		toep->txsd_pidx = 0;
899 	toep->txsd_avail--;
900 	commit_wrq_wr(&toep->ofld_txq->wrq, flowc, &cookie);
901 }
902 
903 static void
904 t4_pmtu_update(struct toedev *tod, struct tcpcb *tp, tcp_seq seq, int mtu)
905 {
906 	struct work_request_hdr *wrh;
907 	struct ulp_txpkt *ulpmc;
908 	int idx, len;
909 	struct wrq_cookie cookie;
910 	struct inpcb *inp = tptoinpcb(tp);
911 	struct toepcb *toep = tp->t_toe;
912 	struct adapter *sc = td_adapter(toep->td);
913 	unsigned short *mtus = &sc->params.mtus[0];
914 
915 	INP_WLOCK_ASSERT(inp);
916 	MPASS(mtu > 0);	/* kernel is supposed to provide something usable. */
917 
918 	/* tp->snd_una and snd_max are in host byte order too. */
919 	seq = be32toh(seq);
920 
921 	CTR6(KTR_CXGBE, "%s: tid %d, seq 0x%08x, mtu %u, mtu_idx %u (%d)",
922 	    __func__, toep->tid, seq, mtu, toep->params.mtu_idx,
923 	    mtus[toep->params.mtu_idx]);
924 
925 	if (ulp_mode(toep) == ULP_MODE_NONE &&	/* XXX: Read TCB otherwise? */
926 	    (SEQ_LT(seq, tp->snd_una) || SEQ_GEQ(seq, tp->snd_max))) {
927 		CTR5(KTR_CXGBE,
928 		    "%s: tid %d, seq 0x%08x not in range [0x%08x, 0x%08x).",
929 		    __func__, toep->tid, seq, tp->snd_una, tp->snd_max);
930 		return;
931 	}
932 
933 	/* Find the best mtu_idx for the suggested MTU. */
934 	for (idx = 0; idx < NMTUS - 1 && mtus[idx + 1] <= mtu; idx++)
935 		continue;
936 	if (idx >= toep->params.mtu_idx)
937 		return;	/* Never increase the PMTU (just like the kernel). */
938 
939 	/*
940 	 * We'll send a compound work request with 2 SET_TCB_FIELDs -- the first
941 	 * one updates the mtu_idx and the second one triggers a retransmit.
942 	 */
943 	len = sizeof(*wrh) + 2 * roundup2(LEN__SET_TCB_FIELD_ULP, 16);
944 	wrh = start_wrq_wr(toep->ctrlq, howmany(len, 16), &cookie);
945 	if (wrh == NULL) {
946 		CH_ERR(sc, "failed to change mtu_idx of tid %d (%u -> %u).\n",
947 		    toep->tid, toep->params.mtu_idx, idx);
948 		return;
949 	}
950 	INIT_ULPTX_WRH(wrh, len, 1, 0);	/* atomic */
951 	ulpmc = (struct ulp_txpkt *)(wrh + 1);
952 	ulpmc = mk_set_tcb_field_ulp(sc, ulpmc, toep->tid, W_TCB_T_MAXSEG,
953 	    V_TCB_T_MAXSEG(M_TCB_T_MAXSEG), V_TCB_T_MAXSEG(idx));
954 	ulpmc = mk_set_tcb_field_ulp(sc, ulpmc, toep->tid, W_TCB_TIMESTAMP,
955 	    V_TCB_TIMESTAMP(0x7FFFFULL << 11), 0);
956 	commit_wrq_wr(toep->ctrlq, wrh, &cookie);
957 
958 	/* Update the software toepcb and tcpcb. */
959 	toep->params.mtu_idx = idx;
960 	tp->t_maxseg = mtus[toep->params.mtu_idx];
961 	if (inp->inp_inc.inc_flags & INC_ISIPV6)
962 		tp->t_maxseg -= sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
963 	else
964 		tp->t_maxseg -= sizeof(struct ip) + sizeof(struct tcphdr);
965 	toep->params.emss = tp->t_maxseg;
966 	if (tp->t_flags & TF_RCVD_TSTMP)
967 		toep->params.emss -= TCPOLEN_TSTAMP_APPA;
968 
969 	/* Update the firmware flowc. */
970 	send_mss_flowc_wr(sc, toep);
971 
972 	/* Update the MTU in the kernel's hostcache. */
973 	if (sc->tt.update_hc_on_pmtu_change != 0) {
974 		struct in_conninfo inc = {0};
975 
976 		inc.inc_fibnum = inp->inp_inc.inc_fibnum;
977 		if (inp->inp_inc.inc_flags & INC_ISIPV6) {
978 			inc.inc_flags |= INC_ISIPV6;
979 			inc.inc6_faddr = inp->inp_inc.inc6_faddr;
980 		} else {
981 			inc.inc_faddr = inp->inp_inc.inc_faddr;
982 		}
983 		tcp_hc_updatemtu(&inc, mtu);
984 	}
985 
986 	CTR6(KTR_CXGBE, "%s: tid %d, mtu_idx %u (%u), t_maxseg %u, emss %u",
987 	    __func__, toep->tid, toep->params.mtu_idx,
988 	    mtus[toep->params.mtu_idx], tp->t_maxseg, toep->params.emss);
989 }
990 
991 /*
992  * The TOE driver will not receive any more CPLs for the tid associated with the
993  * toepcb; release the hold on the inpcb.
994  */
995 void
996 final_cpl_received(struct toepcb *toep)
997 {
998 	struct inpcb *inp = toep->inp;
999 	bool need_wakeup;
1000 
1001 	KASSERT(inp != NULL, ("%s: inp is NULL", __func__));
1002 	INP_WLOCK_ASSERT(inp);
1003 	KASSERT(toep->flags & TPF_CPL_PENDING,
1004 	    ("%s: CPL not pending already?", __func__));
1005 
1006 	CTR6(KTR_CXGBE, "%s: tid %d, toep %p (0x%x), inp %p (0x%x)",
1007 	    __func__, toep->tid, toep, toep->flags, inp, inp->inp_flags);
1008 
1009 	if (ulp_mode(toep) == ULP_MODE_TCPDDP)
1010 		release_ddp_resources(toep);
1011 	toep->inp = NULL;
1012 	need_wakeup = (toep->flags & TPF_WAITING_FOR_FINAL) != 0;
1013 	toep->flags &= ~(TPF_CPL_PENDING | TPF_WAITING_FOR_FINAL);
1014 	mbufq_drain(&toep->ulp_pduq);
1015 	mbufq_drain(&toep->ulp_pdu_reclaimq);
1016 	release_offload_resources(toep);
1017 	if (!(toep->flags & TPF_ATTACHED))
1018 		done_with_toepcb(toep);
1019 
1020 	if (!in_pcbrele_wlocked(inp))
1021 		INP_WUNLOCK(inp);
1022 
1023 	if (need_wakeup) {
1024 		struct mtx *lock = mtx_pool_find(mtxpool_sleep, toep);
1025 
1026 		mtx_lock(lock);
1027 		wakeup(toep);
1028 		mtx_unlock(lock);
1029 	}
1030 }
1031 
1032 void
1033 insert_tid(struct adapter *sc, int tid, void *ctx, int ntids)
1034 {
1035 	struct tid_info *t = &sc->tids;
1036 
1037 	MPASS(tid >= t->tid_base);
1038 	MPASS(tid - t->tid_base < t->ntids);
1039 
1040 	t->tid_tab[tid - t->tid_base] = ctx;
1041 	atomic_add_int(&t->tids_in_use, ntids);
1042 }
1043 
1044 void *
1045 lookup_tid(struct adapter *sc, int tid)
1046 {
1047 	struct tid_info *t = &sc->tids;
1048 
1049 	return (t->tid_tab[tid - t->tid_base]);
1050 }
1051 
1052 void
1053 update_tid(struct adapter *sc, int tid, void *ctx)
1054 {
1055 	struct tid_info *t = &sc->tids;
1056 
1057 	t->tid_tab[tid - t->tid_base] = ctx;
1058 }
1059 
1060 void
1061 remove_tid(struct adapter *sc, int tid, int ntids)
1062 {
1063 	struct tid_info *t = &sc->tids;
1064 
1065 	t->tid_tab[tid - t->tid_base] = NULL;
1066 	atomic_subtract_int(&t->tids_in_use, ntids);
1067 }
1068 
1069 /*
1070  * What mtu_idx to use, given a 4-tuple.  Note that both s->mss and tcp_mssopt
1071  * have the MSS that we should advertise in our SYN.  Advertised MSS doesn't
1072  * account for any TCP options so the effective MSS (only payload, no headers or
1073  * options) could be different.
1074  */
1075 static int
1076 find_best_mtu_idx(struct adapter *sc, struct in_conninfo *inc,
1077     struct offload_settings *s)
1078 {
1079 	unsigned short *mtus = &sc->params.mtus[0];
1080 	int i, mss, mtu;
1081 
1082 	MPASS(inc != NULL);
1083 
1084 	mss = s->mss > 0 ? s->mss : tcp_mssopt(inc);
1085 	if (inc->inc_flags & INC_ISIPV6)
1086 		mtu = mss + sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1087 	else
1088 		mtu = mss + sizeof(struct ip) + sizeof(struct tcphdr);
1089 
1090 	for (i = 0; i < NMTUS - 1 && mtus[i + 1] <= mtu; i++)
1091 		continue;
1092 
1093 	return (i);
1094 }
1095 
1096 /*
1097  * Determine the receive window size for a socket.
1098  */
1099 u_long
1100 select_rcv_wnd(struct socket *so)
1101 {
1102 	unsigned long wnd;
1103 
1104 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1105 
1106 	wnd = sbspace(&so->so_rcv);
1107 	if (wnd < MIN_RCV_WND)
1108 		wnd = MIN_RCV_WND;
1109 
1110 	return min(wnd, MAX_RCV_WND);
1111 }
1112 
1113 int
1114 select_rcv_wscale(void)
1115 {
1116 	int wscale = 0;
1117 	unsigned long space = sb_max;
1118 
1119 	if (space > MAX_RCV_WND)
1120 		space = MAX_RCV_WND;
1121 
1122 	while (wscale < TCP_MAX_WINSHIFT && (TCP_MAXWIN << wscale) < space)
1123 		wscale++;
1124 
1125 	return (wscale);
1126 }
1127 
1128 __be64
1129 calc_options0(struct vi_info *vi, struct conn_params *cp)
1130 {
1131 	uint64_t opt0 = 0;
1132 
1133 	opt0 |= F_TCAM_BYPASS;
1134 
1135 	MPASS(cp->wscale >= 0 && cp->wscale <= M_WND_SCALE);
1136 	opt0 |= V_WND_SCALE(cp->wscale);
1137 
1138 	MPASS(cp->mtu_idx >= 0 && cp->mtu_idx < NMTUS);
1139 	opt0 |= V_MSS_IDX(cp->mtu_idx);
1140 
1141 	MPASS(cp->ulp_mode >= 0 && cp->ulp_mode <= M_ULP_MODE);
1142 	opt0 |= V_ULP_MODE(cp->ulp_mode);
1143 
1144 	MPASS(cp->opt0_bufsize >= 0 && cp->opt0_bufsize <= M_RCV_BUFSIZ);
1145 	opt0 |= V_RCV_BUFSIZ(cp->opt0_bufsize);
1146 
1147 	MPASS(cp->l2t_idx >= 0 && cp->l2t_idx < vi->adapter->vres.l2t.size);
1148 	opt0 |= V_L2T_IDX(cp->l2t_idx);
1149 
1150 	opt0 |= V_SMAC_SEL(vi->smt_idx);
1151 	opt0 |= V_TX_CHAN(vi->pi->tx_chan);
1152 
1153 	MPASS(cp->keepalive == 0 || cp->keepalive == 1);
1154 	opt0 |= V_KEEP_ALIVE(cp->keepalive);
1155 
1156 	MPASS(cp->nagle == 0 || cp->nagle == 1);
1157 	opt0 |= V_NAGLE(cp->nagle);
1158 
1159 	return (htobe64(opt0));
1160 }
1161 
1162 __be32
1163 calc_options2(struct vi_info *vi, struct conn_params *cp)
1164 {
1165 	uint32_t opt2 = 0;
1166 	struct port_info *pi = vi->pi;
1167 	struct adapter *sc = pi->adapter;
1168 
1169 	/*
1170 	 * rx flow control, rx coalesce, congestion control, and tx pace are all
1171 	 * explicitly set by the driver.  On T5+ the ISS is also set by the
1172 	 * driver to the value picked by the kernel.
1173 	 */
1174 	if (is_t4(sc)) {
1175 		opt2 |= F_RX_FC_VALID | F_RX_COALESCE_VALID;
1176 		opt2 |= F_CONG_CNTRL_VALID | F_PACE_VALID;
1177 	} else {
1178 		opt2 |= F_T5_OPT_2_VALID;	/* all 4 valid */
1179 		opt2 |= F_T5_ISS;		/* ISS provided in CPL */
1180 	}
1181 
1182 	MPASS(cp->sack == 0 || cp->sack == 1);
1183 	opt2 |= V_SACK_EN(cp->sack);
1184 
1185 	MPASS(cp->tstamp == 0 || cp->tstamp == 1);
1186 	opt2 |= V_TSTAMPS_EN(cp->tstamp);
1187 
1188 	if (cp->wscale > 0)
1189 		opt2 |= F_WND_SCALE_EN;
1190 
1191 	MPASS(cp->ecn == 0 || cp->ecn == 1);
1192 	opt2 |= V_CCTRL_ECN(cp->ecn);
1193 
1194 	opt2 |= V_TX_QUEUE(TX_MODQ(pi->tx_chan));
1195 	opt2 |= V_PACE(0);
1196 	opt2 |= F_RSS_QUEUE_VALID;
1197 	opt2 |= V_RSS_QUEUE(sc->sge.ofld_rxq[cp->rxq_idx].iq.abs_id);
1198 	if (chip_id(sc) <= CHELSIO_T6) {
1199 		MPASS(pi->rx_chan == 0 || pi->rx_chan == 1);
1200 		opt2 |= V_RX_CHANNEL(pi->rx_chan);
1201 	}
1202 
1203 	MPASS(cp->cong_algo >= 0 && cp->cong_algo <= M_CONG_CNTRL);
1204 	opt2 |= V_CONG_CNTRL(cp->cong_algo);
1205 
1206 	MPASS(cp->rx_coalesce == 0 || cp->rx_coalesce == 1);
1207 	if (cp->rx_coalesce == 1)
1208 		opt2 |= V_RX_COALESCE(M_RX_COALESCE);
1209 
1210 	opt2 |= V_RX_FC_DDP(0) | V_RX_FC_DISABLE(0);
1211 	MPASS(cp->ulp_mode != ULP_MODE_TCPDDP);
1212 
1213 	return (htobe32(opt2));
1214 }
1215 
1216 uint64_t
1217 select_ntuple(struct vi_info *vi, struct l2t_entry *e)
1218 {
1219 	struct adapter *sc = vi->adapter;
1220 	struct tp_params *tp = &sc->params.tp;
1221 	uint64_t ntuple = 0;
1222 
1223 	/*
1224 	 * Initialize each of the fields which we care about which are present
1225 	 * in the Compressed Filter Tuple.
1226 	 */
1227 	if (tp->vlan_shift >= 0 && EVL_VLANOFTAG(e->vlan) != CPL_L2T_VLAN_NONE)
1228 		ntuple |= (uint64_t)(F_FT_VLAN_VLD | e->vlan) << tp->vlan_shift;
1229 
1230 	if (tp->port_shift >= 0)
1231 		ntuple |= (uint64_t)e->hw_port << tp->port_shift;
1232 
1233 	if (tp->protocol_shift >= 0)
1234 		ntuple |= (uint64_t)IPPROTO_TCP << tp->protocol_shift;
1235 
1236 	if (tp->vnic_shift >= 0 && tp->vnic_mode == FW_VNIC_MODE_PF_VF) {
1237 		ntuple |= (uint64_t)(V_FT_VNID_ID_VF(vi->vin) |
1238 		    V_FT_VNID_ID_PF(sc->pf) | V_FT_VNID_ID_VLD(vi->vfvld)) <<
1239 		    tp->vnic_shift;
1240 	}
1241 
1242 	return (ntuple);
1243 }
1244 
1245 /*
1246  * Initialize various connection parameters.
1247  */
1248 void
1249 init_conn_params(struct vi_info *vi , struct offload_settings *s,
1250     struct in_conninfo *inc, struct socket *so,
1251     const struct tcp_options *tcpopt, int16_t l2t_idx, struct conn_params *cp)
1252 {
1253 	struct port_info *pi = vi->pi;
1254 	struct adapter *sc = pi->adapter;
1255 	struct tom_tunables *tt = &sc->tt;
1256 	struct inpcb *inp = sotoinpcb(so);
1257 	struct tcpcb *tp = intotcpcb(inp);
1258 	u_long wnd;
1259 	u_int q_idx;
1260 
1261 	MPASS(s->offload != 0);
1262 
1263 	/* Congestion control algorithm */
1264 	if (s->cong_algo >= 0)
1265 		cp->cong_algo = s->cong_algo & M_CONG_CNTRL;
1266 	else if (sc->tt.cong_algorithm >= 0)
1267 		cp->cong_algo = tt->cong_algorithm & M_CONG_CNTRL;
1268 	else {
1269 		struct cc_algo *cc = CC_ALGO(tp);
1270 
1271 		if (strcasecmp(cc->name, "reno") == 0)
1272 			cp->cong_algo = CONG_ALG_RENO;
1273 		else if (strcasecmp(cc->name, "tahoe") == 0)
1274 			cp->cong_algo = CONG_ALG_TAHOE;
1275 		if (strcasecmp(cc->name, "newreno") == 0)
1276 			cp->cong_algo = CONG_ALG_NEWRENO;
1277 		if (strcasecmp(cc->name, "highspeed") == 0)
1278 			cp->cong_algo = CONG_ALG_HIGHSPEED;
1279 		else {
1280 			/*
1281 			 * Use newreno in case the algorithm selected by the
1282 			 * host stack is not supported by the hardware.
1283 			 */
1284 			cp->cong_algo = CONG_ALG_NEWRENO;
1285 		}
1286 	}
1287 
1288 	/* Tx traffic scheduling class. */
1289 	if (s->sched_class >= 0 && s->sched_class < sc->params.nsched_cls)
1290 		cp->tc_idx = s->sched_class;
1291 	else
1292 		cp->tc_idx = -1;
1293 
1294 	/* Nagle's algorithm. */
1295 	if (s->nagle >= 0)
1296 		cp->nagle = s->nagle > 0 ? 1 : 0;
1297 	else
1298 		cp->nagle = tp->t_flags & TF_NODELAY ? 0 : 1;
1299 
1300 	/* TCP Keepalive. */
1301 	if (V_tcp_always_keepalive || so_options_get(so) & SO_KEEPALIVE)
1302 		cp->keepalive = 1;
1303 	else
1304 		cp->keepalive = 0;
1305 
1306 	/* Optimization that's specific to T5 @ 40G. */
1307 	if (tt->tx_align >= 0)
1308 		cp->tx_align =  tt->tx_align > 0 ? 1 : 0;
1309 	else if (chip_id(sc) == CHELSIO_T5 &&
1310 	    (port_top_speed(pi) > 10 || sc->params.nports > 2))
1311 		cp->tx_align = 1;
1312 	else
1313 		cp->tx_align = 0;
1314 
1315 	/* ULP mode. */
1316 	cp->ulp_mode = ULP_MODE_NONE;
1317 
1318 	/* Rx coalescing. */
1319 	if (s->rx_coalesce >= 0)
1320 		cp->rx_coalesce = s->rx_coalesce > 0 ? 1 : 0;
1321 	else if (tt->rx_coalesce >= 0)
1322 		cp->rx_coalesce = tt->rx_coalesce > 0 ? 1 : 0;
1323 	else
1324 		cp->rx_coalesce = 1;	/* default */
1325 
1326 	/*
1327 	 * Index in the PMTU table.  This controls the MSS that we announce in
1328 	 * our SYN initially, but after ESTABLISHED it controls the MSS that we
1329 	 * use to send data.
1330 	 */
1331 	cp->mtu_idx = find_best_mtu_idx(sc, inc, s);
1332 
1333 	/* Control queue. */
1334 	cp->ctrlq_idx = vi->pi->port_id;
1335 
1336 	/* Tx queue for this connection. */
1337 	if (s->txq == QUEUE_RANDOM)
1338 		q_idx = arc4random();
1339 	else if (s->txq == QUEUE_ROUNDROBIN)
1340 		q_idx = atomic_fetchadd_int(&vi->txq_rr, 1);
1341 	else
1342 		q_idx = s->txq;
1343 	cp->txq_idx = vi->first_ofld_txq + q_idx % vi->nofldtxq;
1344 
1345 	/* Rx queue for this connection. */
1346 	if (s->rxq == QUEUE_RANDOM)
1347 		q_idx = arc4random();
1348 	else if (s->rxq == QUEUE_ROUNDROBIN)
1349 		q_idx = atomic_fetchadd_int(&vi->rxq_rr, 1);
1350 	else
1351 		q_idx = s->rxq;
1352 	cp->rxq_idx = vi->first_ofld_rxq + q_idx % vi->nofldrxq;
1353 
1354 	if (SOLISTENING(so)) {
1355 		/* Passive open */
1356 		MPASS(tcpopt != NULL);
1357 
1358 		/* TCP timestamp option */
1359 		if (tcpopt->tstamp &&
1360 		    (s->tstamp > 0 || (s->tstamp < 0 && V_tcp_do_rfc1323)))
1361 			cp->tstamp = 1;
1362 		else
1363 			cp->tstamp = 0;
1364 
1365 		/* SACK */
1366 		if (tcpopt->sack &&
1367 		    (s->sack > 0 || (s->sack < 0 && V_tcp_do_sack)))
1368 			cp->sack = 1;
1369 		else
1370 			cp->sack = 0;
1371 
1372 		/* Receive window scaling. */
1373 		if (tcpopt->wsf > 0 && tcpopt->wsf < 15 && V_tcp_do_rfc1323)
1374 			cp->wscale = select_rcv_wscale();
1375 		else
1376 			cp->wscale = 0;
1377 
1378 		/* ECN */
1379 		if (tcpopt->ecn &&	/* XXX: review. */
1380 		    (s->ecn > 0 || (s->ecn < 0 && V_tcp_do_ecn)))
1381 			cp->ecn = 1;
1382 		else
1383 			cp->ecn = 0;
1384 
1385 		wnd = max(so->sol_sbrcv_hiwat, MIN_RCV_WND);
1386 		cp->opt0_bufsize = min(wnd >> 10, M_RCV_BUFSIZ);
1387 
1388 		if (tt->sndbuf > 0)
1389 			cp->sndbuf = tt->sndbuf;
1390 		else if (so->sol_sbsnd_flags & SB_AUTOSIZE &&
1391 		    V_tcp_do_autosndbuf)
1392 			cp->sndbuf = 256 * 1024;
1393 		else
1394 			cp->sndbuf = so->sol_sbsnd_hiwat;
1395 	} else {
1396 		/* Active open */
1397 
1398 		/* TCP timestamp option */
1399 		if (s->tstamp > 0 ||
1400 		    (s->tstamp < 0 && (tp->t_flags & TF_REQ_TSTMP)))
1401 			cp->tstamp = 1;
1402 		else
1403 			cp->tstamp = 0;
1404 
1405 		/* SACK */
1406 		if (s->sack > 0 ||
1407 		    (s->sack < 0 && (tp->t_flags & TF_SACK_PERMIT)))
1408 			cp->sack = 1;
1409 		else
1410 			cp->sack = 0;
1411 
1412 		/* Receive window scaling */
1413 		if (tp->t_flags & TF_REQ_SCALE)
1414 			cp->wscale = select_rcv_wscale();
1415 		else
1416 			cp->wscale = 0;
1417 
1418 		/* ECN */
1419 		if (s->ecn > 0 || (s->ecn < 0 && V_tcp_do_ecn == 1))
1420 			cp->ecn = 1;
1421 		else
1422 			cp->ecn = 0;
1423 
1424 		SOCKBUF_LOCK(&so->so_rcv);
1425 		wnd = max(select_rcv_wnd(so), MIN_RCV_WND);
1426 		SOCKBUF_UNLOCK(&so->so_rcv);
1427 		cp->opt0_bufsize = min(wnd >> 10, M_RCV_BUFSIZ);
1428 
1429 		if (tt->sndbuf > 0)
1430 			cp->sndbuf = tt->sndbuf;
1431 		else {
1432 			SOCKBUF_LOCK(&so->so_snd);
1433 			if (so->so_snd.sb_flags & SB_AUTOSIZE &&
1434 			    V_tcp_do_autosndbuf)
1435 				cp->sndbuf = 256 * 1024;
1436 			else
1437 				cp->sndbuf = so->so_snd.sb_hiwat;
1438 			SOCKBUF_UNLOCK(&so->so_snd);
1439 		}
1440 	}
1441 
1442 	cp->l2t_idx = l2t_idx;
1443 
1444 	/* This will be initialized on ESTABLISHED. */
1445 	cp->emss = 0;
1446 }
1447 
1448 void
1449 update_tid_qid_sel(struct vi_info *vi, struct conn_params *cp, int tid)
1450 {
1451 	struct adapter *sc = vi->adapter;
1452 	const int mask = sc->params.tid_qid_sel_mask;
1453 	struct sge_ofld_txq *ofld_txq = &sc->sge.ofld_txq[cp->txq_idx];
1454 	uint32_t ngroup;
1455 	int g, nqpg;
1456 
1457 	cp->ctrlq_idx = ofld_txq_group(tid, mask);
1458 	CTR(KTR_CXGBE, "tid %u is on core %u", tid, cp->ctrlq_idx);
1459 	if ((ofld_txq->wrq.eq.cntxt_id & mask) == (tid & mask))
1460 		return;
1461 
1462 	ngroup = 1 << bitcount32(mask);
1463 	MPASS(vi->nofldtxq % ngroup == 0);
1464 	g = ofld_txq_group(tid, mask);
1465 	nqpg = vi->nofldtxq / ngroup;
1466 	cp->txq_idx = vi->first_ofld_txq + g * nqpg + arc4random() % nqpg;
1467 #ifdef INVARIANTS
1468 	MPASS(cp->txq_idx < vi->first_ofld_txq + vi->nofldtxq);
1469 	ofld_txq = &sc->sge.ofld_txq[cp->txq_idx];
1470 	MPASS((ofld_txq->wrq.eq.cntxt_id & mask) == (tid & mask));
1471 #endif
1472 }
1473 
1474 int
1475 negative_advice(int status)
1476 {
1477 
1478 	return (status == CPL_ERR_RTX_NEG_ADVICE ||
1479 	    status == CPL_ERR_PERSIST_NEG_ADVICE ||
1480 	    status == CPL_ERR_KEEPALV_NEG_ADVICE);
1481 }
1482 
1483 static int
1484 alloc_tid_tab(struct adapter *sc)
1485 {
1486 	struct tid_info *t = &sc->tids;
1487 
1488 	MPASS(t->ntids > 0);
1489 	MPASS(t->tid_tab == NULL);
1490 
1491 	t->tid_tab = malloc(t->ntids * sizeof(*t->tid_tab), M_CXGBE,
1492 	    M_ZERO | M_NOWAIT);
1493 	if (t->tid_tab == NULL)
1494 		return (ENOMEM);
1495 	atomic_store_rel_int(&t->tids_in_use, 0);
1496 
1497 	return (0);
1498 }
1499 
1500 static void
1501 free_tid_tab(struct adapter *sc)
1502 {
1503 	struct tid_info *t = &sc->tids;
1504 
1505 	KASSERT(t->tids_in_use == 0,
1506 	    ("%s: %d tids still in use.", __func__, t->tids_in_use));
1507 
1508 	free(t->tid_tab, M_CXGBE);
1509 	t->tid_tab = NULL;
1510 }
1511 
1512 static void
1513 free_tid_tabs(struct adapter *sc)
1514 {
1515 	free_tid_tab(sc);
1516 	free_stid_tab(sc);
1517 }
1518 
1519 static int
1520 alloc_tid_tabs(struct adapter *sc)
1521 {
1522 	int rc;
1523 
1524 	rc = alloc_tid_tab(sc);
1525 	if (rc != 0)
1526 		goto failed;
1527 
1528 	rc = alloc_stid_tab(sc);
1529 	if (rc != 0)
1530 		goto failed;
1531 
1532 	return (0);
1533 failed:
1534 	free_tid_tabs(sc);
1535 	return (rc);
1536 }
1537 
1538 static inline void
1539 alloc_tcb_history(struct adapter *sc, struct tom_data *td)
1540 {
1541 
1542 	if (sc->tids.ntids == 0 || sc->tids.ntids > 1024)
1543 		return;
1544 	rw_init(&td->tcb_history_lock, "TCB history");
1545 	td->tcb_history = malloc(sc->tids.ntids * sizeof(*td->tcb_history),
1546 	    M_CXGBE, M_ZERO | M_NOWAIT);
1547 	td->dupack_threshold = G_DUPACKTHRESH(t4_read_reg(sc, A_TP_PARA_REG0));
1548 }
1549 
1550 static inline void
1551 free_tcb_history(struct adapter *sc, struct tom_data *td)
1552 {
1553 #ifdef INVARIANTS
1554 	int i;
1555 
1556 	if (td->tcb_history != NULL) {
1557 		for (i = 0; i < sc->tids.ntids; i++) {
1558 			MPASS(td->tcb_history[i] == NULL);
1559 		}
1560 	}
1561 #endif
1562 	free(td->tcb_history, M_CXGBE);
1563 	if (rw_initialized(&td->tcb_history_lock))
1564 		rw_destroy(&td->tcb_history_lock);
1565 }
1566 
1567 static void
1568 free_tom_data(struct adapter *sc, struct tom_data *td)
1569 {
1570 
1571 	ASSERT_SYNCHRONIZED_OP(sc);
1572 
1573 	KASSERT(TAILQ_EMPTY(&td->toep_list),
1574 	    ("%s: TOE PCB list is not empty.", __func__));
1575 	KASSERT(td->lctx_count == 0,
1576 	    ("%s: lctx hash table is not empty.", __func__));
1577 
1578 	t4_free_ppod_region(&td->pr);
1579 
1580 	if (td->listen_mask != 0)
1581 		hashdestroy(td->listen_hash, M_CXGBE, td->listen_mask);
1582 
1583 	if (mtx_initialized(&td->unsent_wr_lock))
1584 		mtx_destroy(&td->unsent_wr_lock);
1585 	if (mtx_initialized(&td->lctx_hash_lock))
1586 		mtx_destroy(&td->lctx_hash_lock);
1587 	if (mtx_initialized(&td->toep_list_lock))
1588 		mtx_destroy(&td->toep_list_lock);
1589 
1590 	free_tcb_history(sc, td);
1591 	free_tid_tabs(sc);
1592 	free(td, M_CXGBE);
1593 }
1594 
1595 static char *
1596 prepare_pkt(int open_type, uint16_t vtag, struct inpcb *inp, int *pktlen,
1597     int *buflen)
1598 {
1599 	char *pkt;
1600 	struct tcphdr *th;
1601 	int ipv6, len;
1602 	const int maxlen =
1603 	    max(sizeof(struct ether_header), sizeof(struct ether_vlan_header)) +
1604 	    max(sizeof(struct ip), sizeof(struct ip6_hdr)) +
1605 	    sizeof(struct tcphdr);
1606 
1607 	MPASS(open_type == OPEN_TYPE_ACTIVE || open_type == OPEN_TYPE_LISTEN);
1608 
1609 	pkt = malloc(maxlen, M_CXGBE, M_ZERO | M_NOWAIT);
1610 	if (pkt == NULL)
1611 		return (NULL);
1612 
1613 	ipv6 = inp->inp_vflag & INP_IPV6;
1614 	len = 0;
1615 
1616 	if (EVL_VLANOFTAG(vtag) == 0xfff) {
1617 		struct ether_header *eh = (void *)pkt;
1618 
1619 		if (ipv6)
1620 			eh->ether_type = htons(ETHERTYPE_IPV6);
1621 		else
1622 			eh->ether_type = htons(ETHERTYPE_IP);
1623 
1624 		len += sizeof(*eh);
1625 	} else {
1626 		struct ether_vlan_header *evh = (void *)pkt;
1627 
1628 		evh->evl_encap_proto = htons(ETHERTYPE_VLAN);
1629 		evh->evl_tag = htons(vtag);
1630 		if (ipv6)
1631 			evh->evl_proto = htons(ETHERTYPE_IPV6);
1632 		else
1633 			evh->evl_proto = htons(ETHERTYPE_IP);
1634 
1635 		len += sizeof(*evh);
1636 	}
1637 
1638 	if (ipv6) {
1639 		struct ip6_hdr *ip6 = (void *)&pkt[len];
1640 
1641 		ip6->ip6_vfc = IPV6_VERSION;
1642 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
1643 		ip6->ip6_nxt = IPPROTO_TCP;
1644 		if (open_type == OPEN_TYPE_ACTIVE) {
1645 			ip6->ip6_src = inp->in6p_laddr;
1646 			ip6->ip6_dst = inp->in6p_faddr;
1647 		} else if (open_type == OPEN_TYPE_LISTEN) {
1648 			ip6->ip6_src = inp->in6p_laddr;
1649 			ip6->ip6_dst = ip6->ip6_src;
1650 		}
1651 
1652 		len += sizeof(*ip6);
1653 	} else {
1654 		struct ip *ip = (void *)&pkt[len];
1655 
1656 		ip->ip_v = IPVERSION;
1657 		ip->ip_hl = sizeof(*ip) >> 2;
1658 		ip->ip_tos = inp->inp_ip_tos;
1659 		ip->ip_len = htons(sizeof(struct ip) + sizeof(struct tcphdr));
1660 		ip->ip_ttl = inp->inp_ip_ttl;
1661 		ip->ip_p = IPPROTO_TCP;
1662 		if (open_type == OPEN_TYPE_ACTIVE) {
1663 			ip->ip_src = inp->inp_laddr;
1664 			ip->ip_dst = inp->inp_faddr;
1665 		} else if (open_type == OPEN_TYPE_LISTEN) {
1666 			ip->ip_src = inp->inp_laddr;
1667 			ip->ip_dst = ip->ip_src;
1668 		}
1669 
1670 		len += sizeof(*ip);
1671 	}
1672 
1673 	th = (void *)&pkt[len];
1674 	if (open_type == OPEN_TYPE_ACTIVE) {
1675 		th->th_sport = inp->inp_lport;	/* network byte order already */
1676 		th->th_dport = inp->inp_fport;	/* ditto */
1677 	} else if (open_type == OPEN_TYPE_LISTEN) {
1678 		th->th_sport = inp->inp_lport;	/* network byte order already */
1679 		th->th_dport = th->th_sport;
1680 	}
1681 	len += sizeof(th);
1682 
1683 	*pktlen = *buflen = len;
1684 	return (pkt);
1685 }
1686 
1687 const struct offload_settings *
1688 lookup_offload_policy(struct adapter *sc, int open_type, struct mbuf *m,
1689     uint16_t vtag, struct inpcb *inp)
1690 {
1691 	const struct t4_offload_policy *op;
1692 	char *pkt;
1693 	struct offload_rule *r;
1694 	int i, matched, pktlen, buflen;
1695 	static const struct offload_settings allow_offloading_settings = {
1696 		.offload = 1,
1697 		.rx_coalesce = -1,
1698 		.cong_algo = -1,
1699 		.sched_class = -1,
1700 		.tstamp = -1,
1701 		.sack = -1,
1702 		.nagle = -1,
1703 		.ecn = -1,
1704 		.ddp = -1,
1705 		.tls = -1,
1706 		.txq = QUEUE_RANDOM,
1707 		.rxq = QUEUE_RANDOM,
1708 		.mss = -1,
1709 	};
1710 	static const struct offload_settings disallow_offloading_settings = {
1711 		.offload = 0,
1712 		/* rest is irrelevant when offload is off. */
1713 	};
1714 
1715 	rw_assert(&sc->policy_lock, RA_LOCKED);
1716 
1717 	/*
1718 	 * If there's no Connection Offloading Policy attached to the device
1719 	 * then we need to return a default static policy.  If
1720 	 * "cop_managed_offloading" is true, then we need to disallow
1721 	 * offloading until a COP is attached to the device.  Otherwise we
1722 	 * allow offloading ...
1723 	 */
1724 	op = sc->policy;
1725 	if (op == NULL) {
1726 		if (sc->tt.cop_managed_offloading)
1727 			return (&disallow_offloading_settings);
1728 		else
1729 			return (&allow_offloading_settings);
1730 	}
1731 
1732 	switch (open_type) {
1733 	case OPEN_TYPE_ACTIVE:
1734 	case OPEN_TYPE_LISTEN:
1735 		pkt = prepare_pkt(open_type, vtag, inp, &pktlen, &buflen);
1736 		break;
1737 	case OPEN_TYPE_PASSIVE:
1738 		MPASS(m != NULL);
1739 		pkt = mtod(m, char *);
1740 		MPASS(*pkt == CPL_PASS_ACCEPT_REQ);
1741 		pkt += sizeof(struct cpl_pass_accept_req);
1742 		pktlen = m->m_pkthdr.len - sizeof(struct cpl_pass_accept_req);
1743 		buflen = m->m_len - sizeof(struct cpl_pass_accept_req);
1744 		break;
1745 	default:
1746 		MPASS(0);
1747 		return (&disallow_offloading_settings);
1748 	}
1749 
1750 	if (pkt == NULL || pktlen == 0 || buflen == 0)
1751 		return (&disallow_offloading_settings);
1752 
1753 	matched = 0;
1754 	r = &op->rule[0];
1755 	for (i = 0; i < op->nrules; i++, r++) {
1756 		if (r->open_type != open_type &&
1757 		    r->open_type != OPEN_TYPE_DONTCARE) {
1758 			continue;
1759 		}
1760 		matched = bpf_filter(r->bpf_prog.bf_insns, pkt, pktlen, buflen);
1761 		if (matched)
1762 			break;
1763 	}
1764 
1765 	if (open_type == OPEN_TYPE_ACTIVE || open_type == OPEN_TYPE_LISTEN)
1766 		free(pkt, M_CXGBE);
1767 
1768 	return (matched ? &r->settings : &disallow_offloading_settings);
1769 }
1770 
1771 static void
1772 reclaim_wr_resources(void *arg, int count)
1773 {
1774 	struct tom_data *td = arg;
1775 	STAILQ_HEAD(, wrqe) twr_list = STAILQ_HEAD_INITIALIZER(twr_list);
1776 	struct cpl_act_open_req *cpl;
1777 	u_int opcode, atid, tid;
1778 	struct wrqe *wr;
1779 	struct adapter *sc = td_adapter(td);
1780 
1781 	mtx_lock(&td->unsent_wr_lock);
1782 	STAILQ_SWAP(&td->unsent_wr_list, &twr_list, wrqe);
1783 	mtx_unlock(&td->unsent_wr_lock);
1784 
1785 	while ((wr = STAILQ_FIRST(&twr_list)) != NULL) {
1786 		STAILQ_REMOVE_HEAD(&twr_list, link);
1787 
1788 		cpl = wrtod(wr);
1789 		opcode = GET_OPCODE(cpl);
1790 
1791 		switch (opcode) {
1792 		case CPL_ACT_OPEN_REQ:
1793 		case CPL_ACT_OPEN_REQ6:
1794 			atid = G_TID_TID(be32toh(OPCODE_TID(cpl)));
1795 			CTR2(KTR_CXGBE, "%s: atid %u ", __func__, atid);
1796 			act_open_failure_cleanup(sc, lookup_atid(sc, atid),
1797 						 EHOSTUNREACH);
1798 			free(wr, M_CXGBE);
1799 			break;
1800 		case CPL_PASS_ACCEPT_RPL:
1801 			tid = GET_TID(cpl);
1802 			CTR2(KTR_CXGBE, "%s: tid %u ", __func__, tid);
1803 			synack_failure_cleanup(sc, lookup_tid(sc, tid));
1804 			free(wr, M_CXGBE);
1805 			break;
1806 		default:
1807 			log(LOG_ERR, "%s: leaked work request %p, wr_len %d, "
1808 			    "opcode %x\n", __func__, wr, wr->wr_len, opcode);
1809 			/* WR not freed here; go look at it with a debugger.  */
1810 		}
1811 	}
1812 }
1813 
1814 /*
1815  * Based on do_abort_req.  We treat an abrupt hardware stop as a connection
1816  * abort from the hardware.
1817  */
1818 static void
1819 live_tid_failure_cleanup(struct adapter *sc, struct toepcb *toep, u_int status)
1820 {
1821 	struct inpcb *inp;
1822 	struct tcpcb *tp;
1823 	struct epoch_tracker et;
1824 
1825 	MPASS(!(toep->flags & TPF_SYNQE));
1826 
1827 	inp = toep->inp;
1828 	CURVNET_SET(toep->vnet);
1829 	NET_EPOCH_ENTER(et);	/* for tcp_close */
1830 	INP_WLOCK(inp);
1831 	tp = intotcpcb(inp);
1832 	toep->flags |= TPF_ABORT_SHUTDOWN;
1833 	if ((inp->inp_flags & INP_DROPPED) == 0) {
1834 		struct socket *so = inp->inp_socket;
1835 
1836 		if (so != NULL)
1837 			so_error_set(so, status);
1838 		tp = tcp_close(tp);
1839 		if (tp == NULL)
1840 			INP_WLOCK(inp);	/* re-acquire */
1841 	}
1842 	final_cpl_received(toep);
1843 	NET_EPOCH_EXIT(et);
1844 	CURVNET_RESTORE();
1845 }
1846 
1847 static void
1848 cleanup_stranded_tids(void *arg, int count)
1849 {
1850 	TAILQ_HEAD(, toepcb) tlist = TAILQ_HEAD_INITIALIZER(tlist);
1851 	TAILQ_HEAD(, synq_entry) slist = TAILQ_HEAD_INITIALIZER(slist);
1852 	struct tom_data *td = arg;
1853 	struct adapter *sc = td_adapter(td);
1854 	struct toepcb *toep;
1855 	struct synq_entry *synqe;
1856 
1857 	/* Clean up synq entries. */
1858 	mtx_lock(&td->toep_list_lock);
1859 	TAILQ_SWAP(&td->stranded_synqe, &slist, synq_entry, link);
1860 	mtx_unlock(&td->toep_list_lock);
1861 	while ((synqe = TAILQ_FIRST(&slist)) != NULL) {
1862 		TAILQ_REMOVE(&slist, synqe, link);
1863 		MPASS(synqe->tid >= 0);	/* stale, was kept around for debug */
1864 		synqe->tid = -1;
1865 		synack_failure_cleanup(sc, synqe);
1866 	}
1867 
1868 	/* Clean up in-flight active opens. */
1869 	mtx_lock(&td->toep_list_lock);
1870 	TAILQ_SWAP(&td->stranded_atids, &tlist, toepcb, link);
1871 	mtx_unlock(&td->toep_list_lock);
1872 	while ((toep = TAILQ_FIRST(&tlist)) != NULL) {
1873 		TAILQ_REMOVE(&tlist, toep, link);
1874 		MPASS(toep->tid >= 0);	/* stale, was kept around for debug */
1875 		toep->tid = -1;
1876 		act_open_failure_cleanup(sc, toep, EHOSTUNREACH);
1877 	}
1878 
1879 	/* Clean up live connections. */
1880 	mtx_lock(&td->toep_list_lock);
1881 	TAILQ_SWAP(&td->stranded_tids, &tlist, toepcb, link);
1882 	mtx_unlock(&td->toep_list_lock);
1883 	while ((toep = TAILQ_FIRST(&tlist)) != NULL) {
1884 		TAILQ_REMOVE(&tlist, toep, link);
1885 		MPASS(toep->tid >= 0);	/* stale, was kept around for debug */
1886 		toep->tid = -1;
1887 		live_tid_failure_cleanup(sc, toep, ECONNABORTED);
1888 	}
1889 }
1890 
1891 /*
1892  * Ground control to Major TOM
1893  * Commencing countdown, engines on
1894  */
1895 static int
1896 t4_tom_activate(struct adapter *sc)
1897 {
1898 	struct tom_data *td;
1899 	struct toedev *tod;
1900 	struct vi_info *vi;
1901 	int i, rc, v;
1902 
1903 	ASSERT_SYNCHRONIZED_OP(sc);
1904 
1905 	/* per-adapter softc for TOM */
1906 	td = malloc(sizeof(*td), M_CXGBE, M_ZERO | M_NOWAIT);
1907 	if (td == NULL)
1908 		return (ENOMEM);
1909 
1910 	/* List of TOE PCBs and associated lock */
1911 	mtx_init(&td->toep_list_lock, "PCB list lock", NULL, MTX_DEF);
1912 	TAILQ_INIT(&td->toep_list);
1913 	TAILQ_INIT(&td->synqe_list);
1914 	TAILQ_INIT(&td->stranded_atids);
1915 	TAILQ_INIT(&td->stranded_tids);
1916 	TASK_INIT(&td->cleanup_stranded_tids, 0, cleanup_stranded_tids, td);
1917 
1918 	/* Listen context */
1919 	mtx_init(&td->lctx_hash_lock, "lctx hash lock", NULL, MTX_DEF);
1920 	td->listen_hash = hashinit_flags(LISTEN_HASH_SIZE, M_CXGBE,
1921 	    &td->listen_mask, HASH_NOWAIT);
1922 
1923 	/* List of WRs for which L2 resolution failed */
1924 	mtx_init(&td->unsent_wr_lock, "Unsent WR list lock", NULL, MTX_DEF);
1925 	STAILQ_INIT(&td->unsent_wr_list);
1926 	TASK_INIT(&td->reclaim_wr_resources, 0, reclaim_wr_resources, td);
1927 
1928 	/* TID tables */
1929 	rc = alloc_tid_tabs(sc);
1930 	if (rc != 0)
1931 		goto done;
1932 
1933 	rc = t4_init_ppod_region(&td->pr, &sc->vres.ddp,
1934 	    t4_read_reg(sc, A_ULP_RX_TDDP_PSZ), "TDDP page pods");
1935 	if (rc != 0)
1936 		goto done;
1937 	t4_set_reg_field(sc, A_ULP_RX_TDDP_TAGMASK,
1938 	    V_TDDPTAGMASK(M_TDDPTAGMASK), td->pr.pr_tag_mask);
1939 
1940 	alloc_tcb_history(sc, td);
1941 
1942 	/* toedev ops */
1943 	tod = &td->tod;
1944 	init_toedev(tod);
1945 	tod->tod_softc = sc;
1946 	tod->tod_connect = t4_connect;
1947 	tod->tod_listen_start = t4_listen_start;
1948 	tod->tod_listen_stop = t4_listen_stop;
1949 	tod->tod_rcvd = t4_rcvd;
1950 	tod->tod_output = t4_tod_output;
1951 	tod->tod_send_rst = t4_send_rst;
1952 	tod->tod_send_fin = t4_send_fin;
1953 	tod->tod_pcb_detach = t4_pcb_detach;
1954 	tod->tod_l2_update = t4_l2_update;
1955 	tod->tod_syncache_added = t4_syncache_added;
1956 	tod->tod_syncache_removed = t4_syncache_removed;
1957 	tod->tod_syncache_respond = t4_syncache_respond;
1958 	tod->tod_offload_socket = t4_offload_socket;
1959 	tod->tod_ctloutput = t4_ctloutput;
1960 	tod->tod_tcp_info = t4_tcp_info;
1961 #ifdef KERN_TLS
1962 	tod->tod_alloc_tls_session = t4_alloc_tls_session;
1963 #endif
1964 	tod->tod_pmtu_update = t4_pmtu_update;
1965 
1966 	for_each_port(sc, i) {
1967 		for_each_vi(sc->port[i], v, vi) {
1968 			SETTOEDEV(vi->ifp, &td->tod);
1969 		}
1970 	}
1971 
1972 	sc->tom_softc = td;
1973 	register_toedev(sc->tom_softc);
1974 
1975 done:
1976 	if (rc != 0)
1977 		free_tom_data(sc, td);
1978 	return (rc);
1979 }
1980 
1981 static int
1982 t4_tom_deactivate(struct adapter *sc)
1983 {
1984 	int rc = 0, i, v;
1985 	struct tom_data *td = sc->tom_softc;
1986 	struct vi_info *vi;
1987 
1988 	ASSERT_SYNCHRONIZED_OP(sc);
1989 
1990 	if (td == NULL)
1991 		return (0);	/* XXX. KASSERT? */
1992 
1993 	if (uld_active(sc, ULD_IWARP) || uld_active(sc, ULD_ISCSI))
1994 		return (EBUSY);	/* both iWARP and iSCSI rely on the TOE. */
1995 
1996 	if (sc->offload_map != 0) {
1997 		for_each_port(sc, i) {
1998 			for_each_vi(sc->port[i], v, vi) {
1999 				toe_capability(vi, false);
2000 				if_setcapenablebit(vi->ifp, 0, IFCAP_TOE);
2001 				SETTOEDEV(vi->ifp, NULL);
2002 			}
2003 		}
2004 		MPASS(sc->offload_map == 0);
2005 	}
2006 
2007 	mtx_lock(&td->toep_list_lock);
2008 	if (!TAILQ_EMPTY(&td->toep_list))
2009 		rc = EBUSY;
2010 	MPASS(TAILQ_EMPTY(&td->synqe_list));
2011 	MPASS(TAILQ_EMPTY(&td->stranded_tids));
2012 	mtx_unlock(&td->toep_list_lock);
2013 
2014 	mtx_lock(&td->lctx_hash_lock);
2015 	if (td->lctx_count > 0)
2016 		rc = EBUSY;
2017 	mtx_unlock(&td->lctx_hash_lock);
2018 
2019 	taskqueue_drain(taskqueue_thread, &td->reclaim_wr_resources);
2020 	taskqueue_drain(taskqueue_thread, &td->cleanup_stranded_tids);
2021 	mtx_lock(&td->unsent_wr_lock);
2022 	if (!STAILQ_EMPTY(&td->unsent_wr_list))
2023 		rc = EBUSY;
2024 	mtx_unlock(&td->unsent_wr_lock);
2025 
2026 	if (rc == 0) {
2027 		unregister_toedev(sc->tom_softc);
2028 		free_tom_data(sc, td);
2029 		sc->tom_softc = NULL;
2030 	}
2031 
2032 	return (rc);
2033 }
2034 
2035 static void
2036 stop_atids(struct adapter *sc)
2037 {
2038 	struct tom_data *td = sc->tom_softc;
2039 	struct tid_info *t = &sc->tids;
2040 	struct toepcb *toep;
2041 	int atid;
2042 
2043 	/*
2044 	 * Hashfilters and T6-KTLS are the only other users of atids but they're
2045 	 * both mutually exclusive with TOE.  That means t4_tom owns all the
2046 	 * atids in the table.
2047 	 */
2048 	MPASS(!is_hashfilter(sc));
2049 	if (is_t6(sc))
2050 		MPASS(!(sc->flags & KERN_TLS_ON));
2051 
2052 	/* New atids are not being allocated. */
2053 #ifdef INVARIANTS
2054 	mtx_lock(&t->atid_lock);
2055 	MPASS(t->atid_alloc_stopped == true);
2056 	mtx_unlock(&t->atid_lock);
2057 #endif
2058 
2059 	/*
2060 	 * In-use atids fall in one of these two categories:
2061 	 * a) Those waiting for L2 resolution before being submitted to
2062 	 *    hardware.
2063 	 * b) Those that have been submitted to hardware and are awaiting
2064 	 *    replies that will never arrive because the LLD is stopped.
2065 	 */
2066 	for (atid = 0; atid < t->natids; atid++) {
2067 		toep = lookup_atid(sc, atid);
2068 		if ((uintptr_t)toep >= (uintptr_t)&t->atid_tab[0] &&
2069 		    (uintptr_t)toep < (uintptr_t)&t->atid_tab[t->natids])
2070 			continue;
2071 		if (__predict_false(toep == NULL))
2072 			continue;
2073 		MPASS(toep->tid == atid);
2074 		MPASS(toep->incarnation == sc->incarnation);
2075 		/*
2076 		 * Take the atid out of the lookup table.  toep->tid is stale
2077 		 * after this but useful for debug.
2078 		 */
2079 		CTR(KTR_CXGBE, "%s: atid %d@%d STRANDED, removed from table",
2080 		    __func__, atid, toep->incarnation);
2081 		free_atid(sc, toep->tid);
2082 #if 0
2083 		toep->tid = -1;
2084 #endif
2085 		mtx_lock(&td->toep_list_lock);
2086 		toep->flags &= ~TPF_IN_TOEP_LIST;
2087 		TAILQ_REMOVE(&td->toep_list, toep, link);
2088 		TAILQ_INSERT_TAIL(&td->stranded_atids, toep, link);
2089 		mtx_unlock(&td->toep_list_lock);
2090 	}
2091 	MPASS(atomic_load_int(&t->atids_in_use) == 0);
2092 }
2093 
2094 static void
2095 stop_tids(struct adapter *sc)
2096 {
2097 	struct tom_data *td = sc->tom_softc;
2098 	struct toepcb *toep;
2099 #ifdef INVARIANTS
2100 	struct tid_info *t = &sc->tids;
2101 #endif
2102 
2103 	/*
2104 	 * The LLD's offload queues are stopped so do_act_establish and
2105 	 * do_pass_accept_req cannot run and insert tids in parallel with this
2106 	 * thread.  stop_stid_tab has also run and removed the synq entries'
2107 	 * tids from the table.  The only tids in the table are for connections
2108 	 * at or beyond ESTABLISHED that are still waiting for the final CPL.
2109 	 */
2110 	mtx_lock(&td->toep_list_lock);
2111 	TAILQ_FOREACH(toep, &td->toep_list, link) {
2112 		MPASS(sc->incarnation == toep->incarnation);
2113 		MPASS(toep->tid >= 0);
2114 		MPASS(toep == lookup_tid(sc, toep->tid));
2115 		/* Remove tid from the lookup table immediately. */
2116 		CTR(KTR_CXGBE, "%s: tid %d@%d STRANDED, removed from table",
2117 		    __func__, toep->tid, toep->incarnation);
2118 		remove_tid(sc, toep->tid, toep->ce ? 2 : 1);
2119 #if 0
2120 		/* toep->tid is stale now but left alone for debug. */
2121 		toep->tid = -1;
2122 #endif
2123 		/* All toep in this list will get bulk moved to stranded_tids */
2124 		toep->flags &= ~TPF_IN_TOEP_LIST;
2125 	}
2126 	MPASS(TAILQ_EMPTY(&td->stranded_tids));
2127 	TAILQ_CONCAT(&td->stranded_tids, &td->toep_list, link);
2128 	MPASS(TAILQ_EMPTY(&td->toep_list));
2129 	mtx_unlock(&td->toep_list_lock);
2130 
2131 	MPASS(atomic_load_int(&t->tids_in_use) == 0);
2132 }
2133 
2134 /*
2135  * L2T is stable because
2136  * 1. stop_lld stopped all new allocations.
2137  * 2. stop_lld also stopped the tx wrq so nothing is enqueueing new WRs to the
2138  *    queue or to l2t_entry->wr_list.
2139  * 3. t4_l2t_update is ignoring all L2 updates.
2140  */
2141 static void
2142 stop_tom_l2t(struct adapter *sc)
2143 {
2144 	struct l2t_data *d = sc->l2t;
2145 	struct tom_data *td = sc->tom_softc;
2146 	struct l2t_entry *e;
2147 	struct wrqe *wr;
2148 	int i;
2149 
2150 	/*
2151 	 * This task cannot be enqueued because L2 state changes are not being
2152 	 * processed.  But if it's already scheduled or running then we need to
2153 	 * wait for it to cleanup the atids in the unsent_wr_list.
2154 	 */
2155 	taskqueue_drain(taskqueue_thread, &td->reclaim_wr_resources);
2156 	MPASS(STAILQ_EMPTY(&td->unsent_wr_list));
2157 
2158 	for (i = 0; i < d->l2t_size; i++) {
2159 		e = &d->l2tab[i];
2160 		mtx_lock(&e->lock);
2161 		if (e->state == L2T_STATE_VALID || e->state == L2T_STATE_STALE)
2162 			e->state = L2T_STATE_RESOLVING;
2163 		/*
2164 		 * stop_atids is going to clean up _all_ atids in use, including
2165 		 * these that were pending L2 resolution.  Just discard the WRs.
2166 		 */
2167 		while ((wr = STAILQ_FIRST(&e->wr_list)) != NULL) {
2168 			STAILQ_REMOVE_HEAD(&e->wr_list, link);
2169 			free(wr, M_CXGBE);
2170 		}
2171 		mtx_unlock(&e->lock);
2172 	}
2173 }
2174 
2175 static int
2176 t4_tom_stop(struct adapter *sc)
2177 {
2178 	struct tid_info *t = &sc->tids;
2179 	struct tom_data *td = sc->tom_softc;
2180 
2181 	ASSERT_SYNCHRONIZED_OP(sc);
2182 
2183 	stop_tom_l2t(sc);
2184 	if (atomic_load_int(&t->atids_in_use) > 0)
2185 		stop_atids(sc);
2186 	if (atomic_load_int(&t->stids_in_use) > 0)
2187 		stop_stid_tab(sc);
2188 	if (atomic_load_int(&t->tids_in_use) > 0)
2189 		stop_tids(sc);
2190 	taskqueue_enqueue(taskqueue_thread, &td->cleanup_stranded_tids);
2191 
2192 	/*
2193 	 * L2T and atid_tab are restarted before t4_tom_restart so this assert
2194 	 * is not valid in t4_tom_restart.  This is the next best place for it.
2195 	 */
2196 	MPASS(STAILQ_EMPTY(&td->unsent_wr_list));
2197 
2198 	return (0);
2199 }
2200 
2201 static int
2202 t4_tom_restart(struct adapter *sc)
2203 {
2204 	ASSERT_SYNCHRONIZED_OP(sc);
2205 
2206 	restart_stid_tab(sc);
2207 
2208 	return (0);
2209 }
2210 
2211 static int
2212 t4_ctloutput_tom(struct socket *so, struct sockopt *sopt)
2213 {
2214 	struct tcpcb *tp = sototcpcb(so);
2215 	struct toepcb *toep = tp->t_toe;
2216 	int error, optval;
2217 
2218 	if (sopt->sopt_level == IPPROTO_TCP && sopt->sopt_name == TCP_USE_DDP) {
2219 		if (sopt->sopt_dir != SOPT_SET)
2220 			return (EOPNOTSUPP);
2221 
2222 		if (sopt->sopt_td != NULL) {
2223 			/* Only settable by the kernel. */
2224 			return (EPERM);
2225 		}
2226 
2227 		error = sooptcopyin(sopt, &optval, sizeof(optval),
2228 		    sizeof(optval));
2229 		if (error != 0)
2230 			return (error);
2231 
2232 		if (optval != 0)
2233 			return (t4_enable_ddp_rcv(so, toep));
2234 		else
2235 			return (EOPNOTSUPP);
2236 	}
2237 	return (tcp_ctloutput(so, sopt));
2238 }
2239 
2240 static int
2241 t4_aio_queue_tom(struct socket *so, struct kaiocb *job)
2242 {
2243 	struct tcpcb *tp = sototcpcb(so);
2244 	struct toepcb *toep = tp->t_toe;
2245 	int error;
2246 
2247 	/*
2248 	 * No lock is needed as TOE sockets never change between
2249 	 * active and passive.
2250 	 */
2251 	if (SOLISTENING(so))
2252 		return (EINVAL);
2253 
2254 	if (ulp_mode(toep) == ULP_MODE_TCPDDP ||
2255 	    ulp_mode(toep) == ULP_MODE_NONE) {
2256 		error = t4_aio_queue_ddp(so, job);
2257 		if (error == 0)
2258 			return (0);
2259 		else if (error != EOPNOTSUPP)
2260 			return (soaio_queue_generic(so, job));
2261 	}
2262 
2263 	if (t4_aio_queue_aiotx(so, job) != 0)
2264 		return (soaio_queue_generic(so, job));
2265 	else
2266 		return (0);
2267 }
2268 
2269 /*
2270  * Request/response structure used to find out the adapter offloading
2271  * a socket.
2272  */
2273 struct find_offload_adapter_data {
2274 	struct socket *so;
2275 	struct adapter *sc;	/* result */
2276 };
2277 
2278 static void
2279 find_offload_adapter_cb(struct adapter *sc, void *arg)
2280 {
2281 	struct find_offload_adapter_data *fa = arg;
2282 	struct socket *so = fa->so;
2283 	struct tom_data *td = sc->tom_softc;
2284 	struct tcpcb *tp;
2285 	struct inpcb *inp;
2286 
2287 	/* Non-TCP were filtered out earlier. */
2288 	MPASS(so->so_proto->pr_protocol == IPPROTO_TCP);
2289 
2290 	if (fa->sc != NULL)
2291 		return;	/* Found already. */
2292 
2293 	if (td == NULL)
2294 		return;	/* TOE not enabled on this adapter. */
2295 
2296 	inp = sotoinpcb(so);
2297 	INP_WLOCK(inp);
2298 	if ((inp->inp_flags & INP_DROPPED) == 0) {
2299 		tp = intotcpcb(inp);
2300 		if (tp->t_flags & TF_TOE && tp->tod == &td->tod)
2301 			fa->sc = sc;	/* Found. */
2302 	}
2303 	INP_WUNLOCK(inp);
2304 }
2305 
2306 struct adapter *
2307 find_offload_adapter(struct socket *so)
2308 {
2309 	struct find_offload_adapter_data fa;
2310 
2311 	fa.sc = NULL;
2312 	fa.so = so;
2313 	t4_iterate(find_offload_adapter_cb, &fa);
2314 	return (fa.sc);
2315 }
2316 
2317 void
2318 send_txdataplen_max_flowc_wr(struct adapter *sc, struct toepcb *toep,
2319     int maxlen)
2320 {
2321 	struct wrqe *wr;
2322 	struct fw_flowc_wr *flowc;
2323 	const u_int nparams = 1;
2324 	u_int flowclen;
2325 	struct ofld_tx_sdesc *txsd = &toep->txsd[toep->txsd_pidx];
2326 
2327 	CTR(KTR_CXGBE, "%s: tid %u maxlen=%d", __func__, toep->tid, maxlen);
2328 
2329 	flowclen = sizeof(*flowc) + nparams * sizeof(struct fw_flowc_mnemval);
2330 
2331 	wr = alloc_wrqe(roundup2(flowclen, 16), &toep->ofld_txq->wrq);
2332 	if (wr == NULL) {
2333 		/* XXX */
2334 		panic("%s: allocation failure.", __func__);
2335 	}
2336 	flowc = wrtod(wr);
2337 	memset(flowc, 0, wr->wr_len);
2338 
2339 	flowc->op_to_nparams = htobe32(V_FW_WR_OP(FW_FLOWC_WR) |
2340 	    V_FW_FLOWC_WR_NPARAMS(nparams));
2341 	flowc->flowid_len16 = htonl(V_FW_WR_LEN16(howmany(flowclen, 16)) |
2342 	    V_FW_WR_FLOWID(toep->tid));
2343 
2344 	flowc->mnemval[0].mnemonic = FW_FLOWC_MNEM_TXDATAPLEN_MAX;
2345 	flowc->mnemval[0].val = htobe32(maxlen);
2346 
2347 	KASSERT(howmany(flowclen, 16) <= MAX_OFLD_TX_SDESC_CREDITS,
2348 	    ("%s: tx_credits %u too large", __func__, howmany(flowclen, 16)));
2349 	txsd->tx_credits = howmany(flowclen, 16);
2350 	txsd->plen = 0;
2351 	KASSERT(toep->tx_credits >= txsd->tx_credits && toep->txsd_avail > 0,
2352 	    ("%s: not enough credits (%d)", __func__, toep->tx_credits));
2353 	toep->tx_credits -= txsd->tx_credits;
2354 	if (__predict_false(++toep->txsd_pidx == toep->txsd_total))
2355 		toep->txsd_pidx = 0;
2356 	toep->txsd_avail--;
2357 
2358 	t4_wrq_tx(sc, wr);
2359 }
2360 
2361 static int
2362 t4_tom_mod_load(void)
2363 {
2364 	/* CPL handlers */
2365 	t4_register_cpl_handler(CPL_GET_TCB_RPL, do_get_tcb_rpl);
2366 	t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL, do_l2t_write_rpl2,
2367 	    CPL_COOKIE_TOM);
2368 	t4_init_connect_cpl_handlers();
2369 	t4_init_listen_cpl_handlers();
2370 	t4_init_cpl_io_handlers();
2371 
2372 	t4_ddp_mod_load();
2373 	t4_tls_mod_load();
2374 
2375 	bcopy(&tcp_protosw, &toe_protosw, sizeof(toe_protosw));
2376 	toe_protosw.pr_ctloutput = t4_ctloutput_tom;
2377 	toe_protosw.pr_aio_queue = t4_aio_queue_tom;
2378 
2379 	bcopy(&tcp6_protosw, &toe6_protosw, sizeof(toe6_protosw));
2380 	toe6_protosw.pr_ctloutput = t4_ctloutput_tom;
2381 	toe6_protosw.pr_aio_queue = t4_aio_queue_tom;
2382 
2383 	return (t4_register_uld(&tom_uld_info, ULD_TOM));
2384 }
2385 
2386 static void
2387 tom_uninit(struct adapter *sc, void *arg)
2388 {
2389 	bool *ok_to_unload = arg;
2390 
2391 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tomun"))
2392 		return;
2393 
2394 	/* Try to free resources (works only if no port has IFCAP_TOE) */
2395 	if (uld_active(sc, ULD_TOM) && t4_deactivate_uld(sc, ULD_TOM) != 0)
2396 		*ok_to_unload = false;
2397 
2398 	end_synchronized_op(sc, 0);
2399 }
2400 
2401 static int
2402 t4_tom_mod_unload(void)
2403 {
2404 	bool ok_to_unload = true;
2405 
2406 	t4_iterate(tom_uninit, &ok_to_unload);
2407 	if (!ok_to_unload)
2408 		return (EBUSY);
2409 
2410 	if (t4_unregister_uld(&tom_uld_info, ULD_TOM) == EBUSY)
2411 		return (EBUSY);
2412 
2413 	t4_tls_mod_unload();
2414 	t4_ddp_mod_unload();
2415 
2416 	t4_uninit_connect_cpl_handlers();
2417 	t4_uninit_listen_cpl_handlers();
2418 	t4_uninit_cpl_io_handlers();
2419 	t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL, NULL, CPL_COOKIE_TOM);
2420 	t4_register_cpl_handler(CPL_GET_TCB_RPL, NULL);
2421 
2422 	return (0);
2423 }
2424 #endif	/* TCP_OFFLOAD */
2425 
2426 static int
2427 t4_tom_modevent(module_t mod, int cmd, void *arg)
2428 {
2429 	int rc = 0;
2430 
2431 #ifdef TCP_OFFLOAD
2432 	switch (cmd) {
2433 	case MOD_LOAD:
2434 		rc = t4_tom_mod_load();
2435 		break;
2436 
2437 	case MOD_UNLOAD:
2438 		rc = t4_tom_mod_unload();
2439 		break;
2440 
2441 	default:
2442 		rc = EINVAL;
2443 	}
2444 #else
2445 	printf("t4_tom: compiled without TCP_OFFLOAD support.\n");
2446 	rc = EOPNOTSUPP;
2447 #endif
2448 	return (rc);
2449 }
2450 
2451 static moduledata_t t4_tom_moddata= {
2452 	"t4_tom",
2453 	t4_tom_modevent,
2454 	0
2455 };
2456 
2457 MODULE_VERSION(t4_tom, 1);
2458 MODULE_DEPEND(t4_tom, toecore, 1, 1, 1);
2459 MODULE_DEPEND(t4_tom, t4nex, 1, 1, 1);
2460 DECLARE_MODULE(t4_tom, t4_tom_moddata, SI_SUB_EXEC, SI_ORDER_ANY);
2461