xref: /freebsd/sys/dev/cxgbe/tom/t4_tom.c (revision 2d0d168606f477d58d1a9aa72f94915da2f1733a)
1 /*-
2  * Copyright (c) 2012 Chelsio Communications, Inc.
3  * All rights reserved.
4  * Written by: Navdeep Parhar <np@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 
34 #include <sys/param.h>
35 #include <sys/types.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/ktr.h>
39 #include <sys/module.h>
40 #include <sys/protosw.h>
41 #include <sys/domain.h>
42 #include <sys/socket.h>
43 #include <sys/socketvar.h>
44 #include <sys/taskqueue.h>
45 #include <net/if.h>
46 #include <netinet/in.h>
47 #include <netinet/in_pcb.h>
48 #include <netinet/in_var.h>
49 #include <netinet/ip.h>
50 #include <netinet/ip6.h>
51 #include <netinet/tcp_var.h>
52 #include <netinet6/scope6_var.h>
53 #define TCPSTATES
54 #include <netinet/tcp_fsm.h>
55 #include <netinet/toecore.h>
56 
57 #ifdef TCP_OFFLOAD
58 #include "common/common.h"
59 #include "common/t4_msg.h"
60 #include "common/t4_regs.h"
61 #include "common/t4_regs_values.h"
62 #include "common/t4_tcb.h"
63 #include "tom/t4_tom_l2t.h"
64 #include "tom/t4_tom.h"
65 
66 static struct protosw ddp_protosw;
67 static struct pr_usrreqs ddp_usrreqs;
68 
69 static struct protosw ddp6_protosw;
70 static struct pr_usrreqs ddp6_usrreqs;
71 
72 /* Module ops */
73 static int t4_tom_mod_load(void);
74 static int t4_tom_mod_unload(void);
75 static int t4_tom_modevent(module_t, int, void *);
76 
77 /* ULD ops and helpers */
78 static int t4_tom_activate(struct adapter *);
79 static int t4_tom_deactivate(struct adapter *);
80 
81 static struct uld_info tom_uld_info = {
82 	.uld_id = ULD_TOM,
83 	.activate = t4_tom_activate,
84 	.deactivate = t4_tom_deactivate,
85 };
86 
87 static void queue_tid_release(struct adapter *, int);
88 static void release_offload_resources(struct toepcb *);
89 static int alloc_tid_tabs(struct tid_info *);
90 static void free_tid_tabs(struct tid_info *);
91 static int add_lip(struct adapter *, struct in6_addr *);
92 static int delete_lip(struct adapter *, struct in6_addr *);
93 static struct clip_entry *search_lip(struct tom_data *, struct in6_addr *);
94 static void init_clip_table(struct adapter *, struct tom_data *);
95 static void update_clip(struct adapter *, void *);
96 static void t4_clip_task(void *, int);
97 static void update_clip_table(struct adapter *, struct tom_data *);
98 static void destroy_clip_table(struct adapter *, struct tom_data *);
99 static void free_tom_data(struct adapter *, struct tom_data *);
100 
101 static int in6_ifaddr_gen;
102 static eventhandler_tag ifaddr_evhandler;
103 static struct timeout_task clip_task;
104 
105 struct toepcb *
106 alloc_toepcb(struct port_info *pi, int txqid, int rxqid, int flags)
107 {
108 	struct adapter *sc = pi->adapter;
109 	struct toepcb *toep;
110 	int tx_credits, txsd_total, len;
111 
112 	/*
113 	 * The firmware counts tx work request credits in units of 16 bytes
114 	 * each.  Reserve room for an ABORT_REQ so the driver never has to worry
115 	 * about tx credits if it wants to abort a connection.
116 	 */
117 	tx_credits = sc->params.ofldq_wr_cred;
118 	tx_credits -= howmany(sizeof(struct cpl_abort_req), 16);
119 
120 	/*
121 	 * Shortest possible tx work request is a fw_ofld_tx_data_wr + 1 byte
122 	 * immediate payload, and firmware counts tx work request credits in
123 	 * units of 16 byte.  Calculate the maximum work requests possible.
124 	 */
125 	txsd_total = tx_credits /
126 	    howmany((sizeof(struct fw_ofld_tx_data_wr) + 1), 16);
127 
128 	if (txqid < 0)
129 		txqid = (arc4random() % pi->nofldtxq) + pi->first_ofld_txq;
130 	KASSERT(txqid >= pi->first_ofld_txq &&
131 	    txqid < pi->first_ofld_txq + pi->nofldtxq,
132 	    ("%s: txqid %d for port %p (first %d, n %d)", __func__, txqid, pi,
133 		pi->first_ofld_txq, pi->nofldtxq));
134 
135 	if (rxqid < 0)
136 		rxqid = (arc4random() % pi->nofldrxq) + pi->first_ofld_rxq;
137 	KASSERT(rxqid >= pi->first_ofld_rxq &&
138 	    rxqid < pi->first_ofld_rxq + pi->nofldrxq,
139 	    ("%s: rxqid %d for port %p (first %d, n %d)", __func__, rxqid, pi,
140 		pi->first_ofld_rxq, pi->nofldrxq));
141 
142 	len = offsetof(struct toepcb, txsd) +
143 	    txsd_total * sizeof(struct ofld_tx_sdesc);
144 
145 	toep = malloc(len, M_CXGBE, M_ZERO | flags);
146 	if (toep == NULL)
147 		return (NULL);
148 
149 	toep->td = sc->tom_softc;
150 	toep->port = pi;
151 	toep->tx_total = tx_credits;
152 	toep->tx_credits = tx_credits;
153 	toep->ofld_txq = &sc->sge.ofld_txq[txqid];
154 	toep->ofld_rxq = &sc->sge.ofld_rxq[rxqid];
155 	toep->ctrlq = &sc->sge.ctrlq[pi->port_id];
156 	toep->txsd_total = txsd_total;
157 	toep->txsd_avail = txsd_total;
158 	toep->txsd_pidx = 0;
159 	toep->txsd_cidx = 0;
160 
161 	return (toep);
162 }
163 
164 void
165 free_toepcb(struct toepcb *toep)
166 {
167 
168 	KASSERT(!(toep->flags & TPF_ATTACHED),
169 	    ("%s: attached to an inpcb", __func__));
170 	KASSERT(!(toep->flags & TPF_CPL_PENDING),
171 	    ("%s: CPL pending", __func__));
172 
173 	free(toep, M_CXGBE);
174 }
175 
176 /*
177  * Set up the socket for TCP offload.
178  */
179 void
180 offload_socket(struct socket *so, struct toepcb *toep)
181 {
182 	struct tom_data *td = toep->td;
183 	struct inpcb *inp = sotoinpcb(so);
184 	struct tcpcb *tp = intotcpcb(inp);
185 	struct sockbuf *sb;
186 
187 	INP_WLOCK_ASSERT(inp);
188 
189 	/* Update socket */
190 	sb = &so->so_snd;
191 	SOCKBUF_LOCK(sb);
192 	sb->sb_flags |= SB_NOCOALESCE;
193 	SOCKBUF_UNLOCK(sb);
194 	sb = &so->so_rcv;
195 	SOCKBUF_LOCK(sb);
196 	sb->sb_flags |= SB_NOCOALESCE;
197 	if (toep->ulp_mode == ULP_MODE_TCPDDP) {
198 		if (inp->inp_vflag & INP_IPV6)
199 			so->so_proto = &ddp6_protosw;
200 		else
201 			so->so_proto = &ddp_protosw;
202 	}
203 	SOCKBUF_UNLOCK(sb);
204 
205 	/* Update TCP PCB */
206 	tp->tod = &td->tod;
207 	tp->t_toe = toep;
208 	tp->t_flags |= TF_TOE;
209 
210 	/* Install an extra hold on inp */
211 	toep->inp = inp;
212 	toep->flags |= TPF_ATTACHED;
213 	in_pcbref(inp);
214 
215 	/* Add the TOE PCB to the active list */
216 	mtx_lock(&td->toep_list_lock);
217 	TAILQ_INSERT_HEAD(&td->toep_list, toep, link);
218 	mtx_unlock(&td->toep_list_lock);
219 }
220 
221 /* This is _not_ the normal way to "unoffload" a socket. */
222 void
223 undo_offload_socket(struct socket *so)
224 {
225 	struct inpcb *inp = sotoinpcb(so);
226 	struct tcpcb *tp = intotcpcb(inp);
227 	struct toepcb *toep = tp->t_toe;
228 	struct tom_data *td = toep->td;
229 	struct sockbuf *sb;
230 
231 	INP_WLOCK_ASSERT(inp);
232 
233 	sb = &so->so_snd;
234 	SOCKBUF_LOCK(sb);
235 	sb->sb_flags &= ~SB_NOCOALESCE;
236 	SOCKBUF_UNLOCK(sb);
237 	sb = &so->so_rcv;
238 	SOCKBUF_LOCK(sb);
239 	sb->sb_flags &= ~SB_NOCOALESCE;
240 	SOCKBUF_UNLOCK(sb);
241 
242 	tp->tod = NULL;
243 	tp->t_toe = NULL;
244 	tp->t_flags &= ~TF_TOE;
245 
246 	toep->inp = NULL;
247 	toep->flags &= ~TPF_ATTACHED;
248 	if (in_pcbrele_wlocked(inp))
249 		panic("%s: inp freed.", __func__);
250 
251 	mtx_lock(&td->toep_list_lock);
252 	TAILQ_REMOVE(&td->toep_list, toep, link);
253 	mtx_unlock(&td->toep_list_lock);
254 }
255 
256 static void
257 release_offload_resources(struct toepcb *toep)
258 {
259 	struct tom_data *td = toep->td;
260 	struct adapter *sc = td_adapter(td);
261 	int tid = toep->tid;
262 
263 	KASSERT(!(toep->flags & TPF_CPL_PENDING),
264 	    ("%s: %p has CPL pending.", __func__, toep));
265 	KASSERT(!(toep->flags & TPF_ATTACHED),
266 	    ("%s: %p is still attached.", __func__, toep));
267 
268 	CTR5(KTR_CXGBE, "%s: toep %p (tid %d, l2te %p, ce %p)",
269 	    __func__, toep, tid, toep->l2te, toep->ce);
270 
271 	if (toep->ulp_mode == ULP_MODE_TCPDDP)
272 		release_ddp_resources(toep);
273 
274 	if (toep->l2te)
275 		t4_l2t_release(toep->l2te);
276 
277 	if (tid >= 0) {
278 		remove_tid(sc, tid);
279 		release_tid(sc, tid, toep->ctrlq);
280 	}
281 
282 	if (toep->ce)
283 		release_lip(td, toep->ce);
284 
285 	mtx_lock(&td->toep_list_lock);
286 	TAILQ_REMOVE(&td->toep_list, toep, link);
287 	mtx_unlock(&td->toep_list_lock);
288 
289 	free_toepcb(toep);
290 }
291 
292 /*
293  * The kernel is done with the TCP PCB and this is our opportunity to unhook the
294  * toepcb hanging off of it.  If the TOE driver is also done with the toepcb (no
295  * pending CPL) then it is time to release all resources tied to the toepcb.
296  *
297  * Also gets called when an offloaded active open fails and the TOM wants the
298  * kernel to take the TCP PCB back.
299  */
300 static void
301 t4_pcb_detach(struct toedev *tod __unused, struct tcpcb *tp)
302 {
303 #if defined(KTR) || defined(INVARIANTS)
304 	struct inpcb *inp = tp->t_inpcb;
305 #endif
306 	struct toepcb *toep = tp->t_toe;
307 
308 	INP_WLOCK_ASSERT(inp);
309 
310 	KASSERT(toep != NULL, ("%s: toep is NULL", __func__));
311 	KASSERT(toep->flags & TPF_ATTACHED,
312 	    ("%s: not attached", __func__));
313 
314 #ifdef KTR
315 	if (tp->t_state == TCPS_SYN_SENT) {
316 		CTR6(KTR_CXGBE, "%s: atid %d, toep %p (0x%x), inp %p (0x%x)",
317 		    __func__, toep->tid, toep, toep->flags, inp,
318 		    inp->inp_flags);
319 	} else {
320 		CTR6(KTR_CXGBE,
321 		    "t4_pcb_detach: tid %d (%s), toep %p (0x%x), inp %p (0x%x)",
322 		    toep->tid, tcpstates[tp->t_state], toep, toep->flags, inp,
323 		    inp->inp_flags);
324 	}
325 #endif
326 
327 	tp->t_toe = NULL;
328 	tp->t_flags &= ~TF_TOE;
329 	toep->flags &= ~TPF_ATTACHED;
330 
331 	if (!(toep->flags & TPF_CPL_PENDING))
332 		release_offload_resources(toep);
333 }
334 
335 /*
336  * setsockopt handler.
337  */
338 static void
339 t4_ctloutput(struct toedev *tod, struct tcpcb *tp, int dir, int name)
340 {
341 	struct adapter *sc = tod->tod_softc;
342 	struct toepcb *toep = tp->t_toe;
343 
344 	if (dir == SOPT_GET)
345 		return;
346 
347 	CTR4(KTR_CXGBE, "%s: tp %p, dir %u, name %u", __func__, tp, dir, name);
348 
349 	switch (name) {
350 	case TCP_NODELAY:
351 		t4_set_tcb_field(sc, toep, 1, W_TCB_T_FLAGS, V_TF_NAGLE(1),
352 		    V_TF_NAGLE(tp->t_flags & TF_NODELAY ? 0 : 1));
353 		break;
354 	default:
355 		break;
356 	}
357 }
358 
359 /*
360  * The TOE driver will not receive any more CPLs for the tid associated with the
361  * toepcb; release the hold on the inpcb.
362  */
363 void
364 final_cpl_received(struct toepcb *toep)
365 {
366 	struct inpcb *inp = toep->inp;
367 
368 	KASSERT(inp != NULL, ("%s: inp is NULL", __func__));
369 	INP_WLOCK_ASSERT(inp);
370 	KASSERT(toep->flags & TPF_CPL_PENDING,
371 	    ("%s: CPL not pending already?", __func__));
372 
373 	CTR6(KTR_CXGBE, "%s: tid %d, toep %p (0x%x), inp %p (0x%x)",
374 	    __func__, toep->tid, toep, toep->flags, inp, inp->inp_flags);
375 
376 	toep->inp = NULL;
377 	toep->flags &= ~TPF_CPL_PENDING;
378 
379 	if (!(toep->flags & TPF_ATTACHED))
380 		release_offload_resources(toep);
381 
382 	if (!in_pcbrele_wlocked(inp))
383 		INP_WUNLOCK(inp);
384 }
385 
386 void
387 insert_tid(struct adapter *sc, int tid, void *ctx)
388 {
389 	struct tid_info *t = &sc->tids;
390 
391 	t->tid_tab[tid] = ctx;
392 	atomic_add_int(&t->tids_in_use, 1);
393 }
394 
395 void *
396 lookup_tid(struct adapter *sc, int tid)
397 {
398 	struct tid_info *t = &sc->tids;
399 
400 	return (t->tid_tab[tid]);
401 }
402 
403 void
404 update_tid(struct adapter *sc, int tid, void *ctx)
405 {
406 	struct tid_info *t = &sc->tids;
407 
408 	t->tid_tab[tid] = ctx;
409 }
410 
411 void
412 remove_tid(struct adapter *sc, int tid)
413 {
414 	struct tid_info *t = &sc->tids;
415 
416 	t->tid_tab[tid] = NULL;
417 	atomic_subtract_int(&t->tids_in_use, 1);
418 }
419 
420 void
421 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
422 {
423 	struct wrqe *wr;
424 	struct cpl_tid_release *req;
425 
426 	wr = alloc_wrqe(sizeof(*req), ctrlq);
427 	if (wr == NULL) {
428 		queue_tid_release(sc, tid);	/* defer */
429 		return;
430 	}
431 	req = wrtod(wr);
432 
433 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
434 
435 	t4_wrq_tx(sc, wr);
436 }
437 
438 static void
439 queue_tid_release(struct adapter *sc, int tid)
440 {
441 
442 	CXGBE_UNIMPLEMENTED("deferred tid release");
443 }
444 
445 /*
446  * What mtu_idx to use, given a 4-tuple and/or an MSS cap
447  */
448 int
449 find_best_mtu_idx(struct adapter *sc, struct in_conninfo *inc, int pmss)
450 {
451 	unsigned short *mtus = &sc->params.mtus[0];
452 	int i, mss, n;
453 
454 	KASSERT(inc != NULL || pmss > 0,
455 	    ("%s: at least one of inc/pmss must be specified", __func__));
456 
457 	mss = inc ? tcp_mssopt(inc) : pmss;
458 	if (pmss > 0 && mss > pmss)
459 		mss = pmss;
460 
461 	if (inc->inc_flags & INC_ISIPV6)
462 		n = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
463 	else
464 		n = sizeof(struct ip) + sizeof(struct tcphdr);
465 
466 	for (i = 0; i < NMTUS - 1 && mtus[i + 1] <= mss + n; i++)
467 		continue;
468 
469 	return (i);
470 }
471 
472 /*
473  * Determine the receive window size for a socket.
474  */
475 u_long
476 select_rcv_wnd(struct socket *so)
477 {
478 	unsigned long wnd;
479 
480 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
481 
482 	wnd = sbspace(&so->so_rcv);
483 	if (wnd < MIN_RCV_WND)
484 		wnd = MIN_RCV_WND;
485 
486 	return min(wnd, MAX_RCV_WND);
487 }
488 
489 int
490 select_rcv_wscale(void)
491 {
492 	int wscale = 0;
493 	unsigned long space = sb_max;
494 
495 	if (space > MAX_RCV_WND)
496 		space = MAX_RCV_WND;
497 
498 	while (wscale < TCP_MAX_WINSHIFT && (TCP_MAXWIN << wscale) < space)
499 		wscale++;
500 
501 	return (wscale);
502 }
503 
504 extern int always_keepalive;
505 #define VIID_SMACIDX(v)	(((unsigned int)(v) & 0x7f) << 1)
506 
507 /*
508  * socket so could be a listening socket too.
509  */
510 uint64_t
511 calc_opt0(struct socket *so, struct port_info *pi, struct l2t_entry *e,
512     int mtu_idx, int rscale, int rx_credits, int ulp_mode)
513 {
514 	uint64_t opt0;
515 
516 	KASSERT(rx_credits <= M_RCV_BUFSIZ,
517 	    ("%s: rcv_bufsiz too high", __func__));
518 
519 	opt0 = F_TCAM_BYPASS | V_WND_SCALE(rscale) | V_MSS_IDX(mtu_idx) |
520 	    V_ULP_MODE(ulp_mode) | V_RCV_BUFSIZ(rx_credits);
521 
522 	if (so != NULL) {
523 		struct inpcb *inp = sotoinpcb(so);
524 		struct tcpcb *tp = intotcpcb(inp);
525 		int keepalive = always_keepalive ||
526 		    so_options_get(so) & SO_KEEPALIVE;
527 
528 		opt0 |= V_NAGLE((tp->t_flags & TF_NODELAY) == 0);
529 		opt0 |= V_KEEP_ALIVE(keepalive != 0);
530 	}
531 
532 	if (e != NULL)
533 		opt0 |= V_L2T_IDX(e->idx);
534 
535 	if (pi != NULL) {
536 		opt0 |= V_SMAC_SEL(VIID_SMACIDX(pi->viid));
537 		opt0 |= V_TX_CHAN(pi->tx_chan);
538 	}
539 
540 	return htobe64(opt0);
541 }
542 
543 uint64_t
544 select_ntuple(struct port_info *pi, struct l2t_entry *e)
545 {
546 	struct adapter *sc = pi->adapter;
547 	struct tp_params *tp = &sc->params.tp;
548 	uint16_t viid = pi->viid;
549 	uint64_t ntuple = 0;
550 
551 	/*
552 	 * Initialize each of the fields which we care about which are present
553 	 * in the Compressed Filter Tuple.
554 	 */
555 	if (tp->vlan_shift >= 0 && e->vlan != CPL_L2T_VLAN_NONE)
556 		ntuple |= (uint64_t)(F_FT_VLAN_VLD | e->vlan) << tp->vlan_shift;
557 
558 	if (tp->port_shift >= 0)
559 		ntuple |= (uint64_t)e->lport << tp->port_shift;
560 
561 	if (tp->protocol_shift >= 0)
562 		ntuple |= (uint64_t)IPPROTO_TCP << tp->protocol_shift;
563 
564 	if (tp->vnic_shift >= 0) {
565 		uint32_t vf = G_FW_VIID_VIN(viid);
566 		uint32_t pf = G_FW_VIID_PFN(viid);
567 		uint32_t vld = G_FW_VIID_VIVLD(viid);
568 
569 		ntuple |= (uint64_t)(V_FT_VNID_ID_VF(vf) | V_FT_VNID_ID_PF(pf) |
570 		    V_FT_VNID_ID_VLD(vld)) << tp->vnic_shift;
571 	}
572 
573 	if (is_t4(sc))
574 		return (htobe32((uint32_t)ntuple));
575 	else
576 		return (htobe64(V_FILTER_TUPLE(ntuple)));
577 }
578 
579 void
580 set_tcpddp_ulp_mode(struct toepcb *toep)
581 {
582 
583 	toep->ulp_mode = ULP_MODE_TCPDDP;
584 	toep->ddp_flags = DDP_OK;
585 	toep->ddp_score = DDP_LOW_SCORE;
586 }
587 
588 int
589 negative_advice(int status)
590 {
591 
592 	return (status == CPL_ERR_RTX_NEG_ADVICE ||
593 	    status == CPL_ERR_PERSIST_NEG_ADVICE ||
594 	    status == CPL_ERR_KEEPALV_NEG_ADVICE);
595 }
596 
597 static int
598 alloc_tid_tabs(struct tid_info *t)
599 {
600 	size_t size;
601 	unsigned int i;
602 
603 	size = t->ntids * sizeof(*t->tid_tab) +
604 	    t->natids * sizeof(*t->atid_tab) +
605 	    t->nstids * sizeof(*t->stid_tab);
606 
607 	t->tid_tab = malloc(size, M_CXGBE, M_ZERO | M_NOWAIT);
608 	if (t->tid_tab == NULL)
609 		return (ENOMEM);
610 
611 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
612 	t->atid_tab = (union aopen_entry *)&t->tid_tab[t->ntids];
613 	t->afree = t->atid_tab;
614 	t->atids_in_use = 0;
615 	for (i = 1; i < t->natids; i++)
616 		t->atid_tab[i - 1].next = &t->atid_tab[i];
617 	t->atid_tab[t->natids - 1].next = NULL;
618 
619 	mtx_init(&t->stid_lock, "stid lock", NULL, MTX_DEF);
620 	t->stid_tab = (struct listen_ctx **)&t->atid_tab[t->natids];
621 	t->stids_in_use = 0;
622 	TAILQ_INIT(&t->stids);
623 	t->nstids_free_head = t->nstids;
624 
625 	atomic_store_rel_int(&t->tids_in_use, 0);
626 
627 	return (0);
628 }
629 
630 static void
631 free_tid_tabs(struct tid_info *t)
632 {
633 	KASSERT(t->tids_in_use == 0,
634 	    ("%s: %d tids still in use.", __func__, t->tids_in_use));
635 	KASSERT(t->atids_in_use == 0,
636 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
637 	KASSERT(t->stids_in_use == 0,
638 	    ("%s: %d tids still in use.", __func__, t->stids_in_use));
639 
640 	free(t->tid_tab, M_CXGBE);
641 	t->tid_tab = NULL;
642 
643 	if (mtx_initialized(&t->atid_lock))
644 		mtx_destroy(&t->atid_lock);
645 	if (mtx_initialized(&t->stid_lock))
646 		mtx_destroy(&t->stid_lock);
647 }
648 
649 static int
650 add_lip(struct adapter *sc, struct in6_addr *lip)
651 {
652         struct fw_clip_cmd c;
653 
654 	ASSERT_SYNCHRONIZED_OP(sc);
655 	/* mtx_assert(&td->clip_table_lock, MA_OWNED); */
656 
657         memset(&c, 0, sizeof(c));
658 	c.op_to_write = htonl(V_FW_CMD_OP(FW_CLIP_CMD) | F_FW_CMD_REQUEST |
659 	    F_FW_CMD_WRITE);
660         c.alloc_to_len16 = htonl(F_FW_CLIP_CMD_ALLOC | FW_LEN16(c));
661         c.ip_hi = *(uint64_t *)&lip->s6_addr[0];
662         c.ip_lo = *(uint64_t *)&lip->s6_addr[8];
663 
664 	return (-t4_wr_mbox_ns(sc, sc->mbox, &c, sizeof(c), &c));
665 }
666 
667 static int
668 delete_lip(struct adapter *sc, struct in6_addr *lip)
669 {
670 	struct fw_clip_cmd c;
671 
672 	ASSERT_SYNCHRONIZED_OP(sc);
673 	/* mtx_assert(&td->clip_table_lock, MA_OWNED); */
674 
675 	memset(&c, 0, sizeof(c));
676 	c.op_to_write = htonl(V_FW_CMD_OP(FW_CLIP_CMD) | F_FW_CMD_REQUEST |
677 	    F_FW_CMD_READ);
678         c.alloc_to_len16 = htonl(F_FW_CLIP_CMD_FREE | FW_LEN16(c));
679         c.ip_hi = *(uint64_t *)&lip->s6_addr[0];
680         c.ip_lo = *(uint64_t *)&lip->s6_addr[8];
681 
682 	return (-t4_wr_mbox_ns(sc, sc->mbox, &c, sizeof(c), &c));
683 }
684 
685 static struct clip_entry *
686 search_lip(struct tom_data *td, struct in6_addr *lip)
687 {
688 	struct clip_entry *ce;
689 
690 	mtx_assert(&td->clip_table_lock, MA_OWNED);
691 
692 	TAILQ_FOREACH(ce, &td->clip_table, link) {
693 		if (IN6_ARE_ADDR_EQUAL(&ce->lip, lip))
694 			return (ce);
695 	}
696 
697 	return (NULL);
698 }
699 
700 struct clip_entry *
701 hold_lip(struct tom_data *td, struct in6_addr *lip)
702 {
703 	struct clip_entry *ce;
704 
705 	mtx_lock(&td->clip_table_lock);
706 	ce = search_lip(td, lip);
707 	if (ce != NULL)
708 		ce->refcount++;
709 	mtx_unlock(&td->clip_table_lock);
710 
711 	return (ce);
712 }
713 
714 void
715 release_lip(struct tom_data *td, struct clip_entry *ce)
716 {
717 
718 	mtx_lock(&td->clip_table_lock);
719 	KASSERT(search_lip(td, &ce->lip) == ce,
720 	    ("%s: CLIP entry %p p not in CLIP table.", __func__, ce));
721 	KASSERT(ce->refcount > 0,
722 	    ("%s: CLIP entry %p has refcount 0", __func__, ce));
723 	--ce->refcount;
724 	mtx_unlock(&td->clip_table_lock);
725 }
726 
727 static void
728 init_clip_table(struct adapter *sc, struct tom_data *td)
729 {
730 
731 	ASSERT_SYNCHRONIZED_OP(sc);
732 
733 	mtx_init(&td->clip_table_lock, "CLIP table lock", NULL, MTX_DEF);
734 	TAILQ_INIT(&td->clip_table);
735 	td->clip_gen = -1;
736 
737 	update_clip_table(sc, td);
738 }
739 
740 static void
741 update_clip(struct adapter *sc, void *arg __unused)
742 {
743 
744 	if (begin_synchronized_op(sc, NULL, HOLD_LOCK, "t4tomuc"))
745 		return;
746 
747 	if (sc->flags & TOM_INIT_DONE)
748 		update_clip_table(sc, sc->tom_softc);
749 
750 	end_synchronized_op(sc, LOCK_HELD);
751 }
752 
753 static void
754 t4_clip_task(void *arg, int count)
755 {
756 
757 	t4_iterate(update_clip, NULL);
758 }
759 
760 static void
761 update_clip_table(struct adapter *sc, struct tom_data *td)
762 {
763 	struct in6_ifaddr *ia;
764 	struct in6_addr *lip, tlip;
765 	struct clip_head stale;
766 	struct clip_entry *ce, *ce_temp;
767 	int rc, gen = atomic_load_acq_int(&in6_ifaddr_gen);
768 
769 	ASSERT_SYNCHRONIZED_OP(sc);
770 
771 	IN6_IFADDR_RLOCK();
772 	mtx_lock(&td->clip_table_lock);
773 
774 	if (gen == td->clip_gen)
775 		goto done;
776 
777 	TAILQ_INIT(&stale);
778 	TAILQ_CONCAT(&stale, &td->clip_table, link);
779 
780 	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
781 		lip = &ia->ia_addr.sin6_addr;
782 
783 		KASSERT(!IN6_IS_ADDR_MULTICAST(lip),
784 		    ("%s: mcast address in in6_ifaddr list", __func__));
785 
786 		if (IN6_IS_ADDR_LOOPBACK(lip))
787 			continue;
788 		if (IN6_IS_SCOPE_EMBED(lip)) {
789 			/* Remove the embedded scope */
790 			tlip = *lip;
791 			lip = &tlip;
792 			in6_clearscope(lip);
793 		}
794 		/*
795 		 * XXX: how to weed out the link local address for the loopback
796 		 * interface?  It's fe80::1 usually (always?).
797 		 */
798 
799 		/*
800 		 * If it's in the main list then we already know it's not stale.
801 		 */
802 		TAILQ_FOREACH(ce, &td->clip_table, link) {
803 			if (IN6_ARE_ADDR_EQUAL(&ce->lip, lip))
804 				goto next;
805 		}
806 
807 		/*
808 		 * If it's in the stale list we should move it to the main list.
809 		 */
810 		TAILQ_FOREACH(ce, &stale, link) {
811 			if (IN6_ARE_ADDR_EQUAL(&ce->lip, lip)) {
812 				TAILQ_REMOVE(&stale, ce, link);
813 				TAILQ_INSERT_TAIL(&td->clip_table, ce, link);
814 				goto next;
815 			}
816 		}
817 
818 		/* A new IP6 address; add it to the CLIP table */
819 		ce = malloc(sizeof(*ce), M_CXGBE, M_NOWAIT);
820 		memcpy(&ce->lip, lip, sizeof(ce->lip));
821 		ce->refcount = 0;
822 		rc = add_lip(sc, lip);
823 		if (rc == 0)
824 			TAILQ_INSERT_TAIL(&td->clip_table, ce, link);
825 		else {
826 			char ip[INET6_ADDRSTRLEN];
827 
828 			inet_ntop(AF_INET6, &ce->lip, &ip[0], sizeof(ip));
829 			log(LOG_ERR, "%s: could not add %s (%d)\n",
830 			    __func__, ip, rc);
831 			free(ce, M_CXGBE);
832 		}
833 next:
834 		continue;
835 	}
836 
837 	/*
838 	 * Remove stale addresses (those no longer in V_in6_ifaddrhead) that are
839 	 * no longer referenced by the driver.
840 	 */
841 	TAILQ_FOREACH_SAFE(ce, &stale, link, ce_temp) {
842 		if (ce->refcount == 0) {
843 			rc = delete_lip(sc, &ce->lip);
844 			if (rc == 0) {
845 				TAILQ_REMOVE(&stale, ce, link);
846 				free(ce, M_CXGBE);
847 			} else {
848 				char ip[INET6_ADDRSTRLEN];
849 
850 				inet_ntop(AF_INET6, &ce->lip, &ip[0],
851 				    sizeof(ip));
852 				log(LOG_ERR, "%s: could not delete %s (%d)\n",
853 				    __func__, ip, rc);
854 			}
855 		}
856 	}
857 	/* The ones that are still referenced need to stay in the CLIP table */
858 	TAILQ_CONCAT(&td->clip_table, &stale, link);
859 
860 	td->clip_gen = gen;
861 done:
862 	mtx_unlock(&td->clip_table_lock);
863 	IN6_IFADDR_RUNLOCK();
864 }
865 
866 static void
867 destroy_clip_table(struct adapter *sc, struct tom_data *td)
868 {
869 	struct clip_entry *ce, *ce_temp;
870 
871 	if (mtx_initialized(&td->clip_table_lock)) {
872 		mtx_lock(&td->clip_table_lock);
873 		TAILQ_FOREACH_SAFE(ce, &td->clip_table, link, ce_temp) {
874 			KASSERT(ce->refcount == 0,
875 			    ("%s: CLIP entry %p still in use (%d)", __func__,
876 			    ce, ce->refcount));
877 			TAILQ_REMOVE(&td->clip_table, ce, link);
878 			delete_lip(sc, &ce->lip);
879 			free(ce, M_CXGBE);
880 		}
881 		mtx_unlock(&td->clip_table_lock);
882 		mtx_destroy(&td->clip_table_lock);
883 	}
884 }
885 
886 static void
887 free_tom_data(struct adapter *sc, struct tom_data *td)
888 {
889 
890 	ASSERT_SYNCHRONIZED_OP(sc);
891 
892 	KASSERT(TAILQ_EMPTY(&td->toep_list),
893 	    ("%s: TOE PCB list is not empty.", __func__));
894 	KASSERT(td->lctx_count == 0,
895 	    ("%s: lctx hash table is not empty.", __func__));
896 
897 	t4_uninit_l2t_cpl_handlers(sc);
898 	t4_uninit_cpl_io_handlers(sc);
899 	t4_uninit_ddp(sc, td);
900 	destroy_clip_table(sc, td);
901 
902 	if (td->listen_mask != 0)
903 		hashdestroy(td->listen_hash, M_CXGBE, td->listen_mask);
904 
905 	if (mtx_initialized(&td->lctx_hash_lock))
906 		mtx_destroy(&td->lctx_hash_lock);
907 	if (mtx_initialized(&td->toep_list_lock))
908 		mtx_destroy(&td->toep_list_lock);
909 
910 	free_tid_tabs(&sc->tids);
911 	free(td, M_CXGBE);
912 }
913 
914 /*
915  * Ground control to Major TOM
916  * Commencing countdown, engines on
917  */
918 static int
919 t4_tom_activate(struct adapter *sc)
920 {
921 	struct tom_data *td;
922 	struct toedev *tod;
923 	int i, rc;
924 
925 	ASSERT_SYNCHRONIZED_OP(sc);
926 
927 	/* per-adapter softc for TOM */
928 	td = malloc(sizeof(*td), M_CXGBE, M_ZERO | M_NOWAIT);
929 	if (td == NULL)
930 		return (ENOMEM);
931 
932 	/* List of TOE PCBs and associated lock */
933 	mtx_init(&td->toep_list_lock, "PCB list lock", NULL, MTX_DEF);
934 	TAILQ_INIT(&td->toep_list);
935 
936 	/* Listen context */
937 	mtx_init(&td->lctx_hash_lock, "lctx hash lock", NULL, MTX_DEF);
938 	td->listen_hash = hashinit_flags(LISTEN_HASH_SIZE, M_CXGBE,
939 	    &td->listen_mask, HASH_NOWAIT);
940 
941 	/* TID tables */
942 	rc = alloc_tid_tabs(&sc->tids);
943 	if (rc != 0)
944 		goto done;
945 
946 	/* DDP page pods and CPL handlers */
947 	t4_init_ddp(sc, td);
948 
949 	/* CLIP table for IPv6 offload */
950 	init_clip_table(sc, td);
951 
952 	/* CPL handlers */
953 	t4_init_connect_cpl_handlers(sc);
954 	t4_init_l2t_cpl_handlers(sc);
955 	t4_init_listen_cpl_handlers(sc);
956 	t4_init_cpl_io_handlers(sc);
957 
958 	/* toedev ops */
959 	tod = &td->tod;
960 	init_toedev(tod);
961 	tod->tod_softc = sc;
962 	tod->tod_connect = t4_connect;
963 	tod->tod_listen_start = t4_listen_start;
964 	tod->tod_listen_stop = t4_listen_stop;
965 	tod->tod_rcvd = t4_rcvd;
966 	tod->tod_output = t4_tod_output;
967 	tod->tod_send_rst = t4_send_rst;
968 	tod->tod_send_fin = t4_send_fin;
969 	tod->tod_pcb_detach = t4_pcb_detach;
970 	tod->tod_l2_update = t4_l2_update;
971 	tod->tod_syncache_added = t4_syncache_added;
972 	tod->tod_syncache_removed = t4_syncache_removed;
973 	tod->tod_syncache_respond = t4_syncache_respond;
974 	tod->tod_offload_socket = t4_offload_socket;
975 	tod->tod_ctloutput = t4_ctloutput;
976 
977 	for_each_port(sc, i)
978 		TOEDEV(sc->port[i]->ifp) = &td->tod;
979 
980 	sc->tom_softc = td;
981 	sc->flags |= TOM_INIT_DONE;
982 	register_toedev(sc->tom_softc);
983 
984 done:
985 	if (rc != 0)
986 		free_tom_data(sc, td);
987 	return (rc);
988 }
989 
990 static int
991 t4_tom_deactivate(struct adapter *sc)
992 {
993 	int rc = 0;
994 	struct tom_data *td = sc->tom_softc;
995 
996 	ASSERT_SYNCHRONIZED_OP(sc);
997 
998 	if (td == NULL)
999 		return (0);	/* XXX. KASSERT? */
1000 
1001 	if (sc->offload_map != 0)
1002 		return (EBUSY);	/* at least one port has IFCAP_TOE enabled */
1003 
1004 	mtx_lock(&td->toep_list_lock);
1005 	if (!TAILQ_EMPTY(&td->toep_list))
1006 		rc = EBUSY;
1007 	mtx_unlock(&td->toep_list_lock);
1008 
1009 	mtx_lock(&td->lctx_hash_lock);
1010 	if (td->lctx_count > 0)
1011 		rc = EBUSY;
1012 	mtx_unlock(&td->lctx_hash_lock);
1013 
1014 	if (rc == 0) {
1015 		unregister_toedev(sc->tom_softc);
1016 		free_tom_data(sc, td);
1017 		sc->tom_softc = NULL;
1018 		sc->flags &= ~TOM_INIT_DONE;
1019 	}
1020 
1021 	return (rc);
1022 }
1023 
1024 static void
1025 t4_tom_ifaddr_event(void *arg __unused, struct ifnet *ifp)
1026 {
1027 
1028 	atomic_add_rel_int(&in6_ifaddr_gen, 1);
1029 	taskqueue_enqueue_timeout(taskqueue_thread, &clip_task, -hz / 4);
1030 }
1031 
1032 static int
1033 t4_tom_mod_load(void)
1034 {
1035 	int rc;
1036 	struct protosw *tcp_protosw, *tcp6_protosw;
1037 
1038 	tcp_protosw = pffindproto(PF_INET, IPPROTO_TCP, SOCK_STREAM);
1039 	if (tcp_protosw == NULL)
1040 		return (ENOPROTOOPT);
1041 	bcopy(tcp_protosw, &ddp_protosw, sizeof(ddp_protosw));
1042 	bcopy(tcp_protosw->pr_usrreqs, &ddp_usrreqs, sizeof(ddp_usrreqs));
1043 	ddp_usrreqs.pru_soreceive = t4_soreceive_ddp;
1044 	ddp_protosw.pr_usrreqs = &ddp_usrreqs;
1045 
1046 	tcp6_protosw = pffindproto(PF_INET6, IPPROTO_TCP, SOCK_STREAM);
1047 	if (tcp6_protosw == NULL)
1048 		return (ENOPROTOOPT);
1049 	bcopy(tcp6_protosw, &ddp6_protosw, sizeof(ddp6_protosw));
1050 	bcopy(tcp6_protosw->pr_usrreqs, &ddp6_usrreqs, sizeof(ddp6_usrreqs));
1051 	ddp6_usrreqs.pru_soreceive = t4_soreceive_ddp;
1052 	ddp6_protosw.pr_usrreqs = &ddp6_usrreqs;
1053 
1054 	TIMEOUT_TASK_INIT(taskqueue_thread, &clip_task, 0, t4_clip_task, NULL);
1055 	ifaddr_evhandler = EVENTHANDLER_REGISTER(ifaddr_event,
1056 	    t4_tom_ifaddr_event, NULL, EVENTHANDLER_PRI_ANY);
1057 
1058 	rc = t4_register_uld(&tom_uld_info);
1059 	if (rc != 0)
1060 		t4_tom_mod_unload();
1061 
1062 	return (rc);
1063 }
1064 
1065 static void
1066 tom_uninit(struct adapter *sc, void *arg __unused)
1067 {
1068 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4tomun"))
1069 		return;
1070 
1071 	/* Try to free resources (works only if no port has IFCAP_TOE) */
1072 	if (sc->flags & TOM_INIT_DONE)
1073 		t4_deactivate_uld(sc, ULD_TOM);
1074 
1075 	end_synchronized_op(sc, 0);
1076 }
1077 
1078 static int
1079 t4_tom_mod_unload(void)
1080 {
1081 	t4_iterate(tom_uninit, NULL);
1082 
1083 	if (t4_unregister_uld(&tom_uld_info) == EBUSY)
1084 		return (EBUSY);
1085 
1086 	if (ifaddr_evhandler) {
1087 		EVENTHANDLER_DEREGISTER(ifaddr_event, ifaddr_evhandler);
1088 		taskqueue_cancel_timeout(taskqueue_thread, &clip_task, NULL);
1089 	}
1090 
1091 	return (0);
1092 }
1093 #endif	/* TCP_OFFLOAD */
1094 
1095 static int
1096 t4_tom_modevent(module_t mod, int cmd, void *arg)
1097 {
1098 	int rc = 0;
1099 
1100 #ifdef TCP_OFFLOAD
1101 	switch (cmd) {
1102 	case MOD_LOAD:
1103 		rc = t4_tom_mod_load();
1104 		break;
1105 
1106 	case MOD_UNLOAD:
1107 		rc = t4_tom_mod_unload();
1108 		break;
1109 
1110 	default:
1111 		rc = EINVAL;
1112 	}
1113 #else
1114 	printf("t4_tom: compiled without TCP_OFFLOAD support.\n");
1115 	rc = EOPNOTSUPP;
1116 #endif
1117 	return (rc);
1118 }
1119 
1120 static moduledata_t t4_tom_moddata= {
1121 	"t4_tom",
1122 	t4_tom_modevent,
1123 	0
1124 };
1125 
1126 MODULE_VERSION(t4_tom, 1);
1127 MODULE_DEPEND(t4_tom, toecore, 1, 1, 1);
1128 MODULE_DEPEND(t4_tom, t4nex, 1, 1, 1);
1129 DECLARE_MODULE(t4_tom, t4_tom_moddata, SI_SUB_EXEC, SI_ORDER_ANY);
1130