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