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