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