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