xref: /freebsd/sys/dev/cxgbe/t4_sge.c (revision d2ce15bd43b3a1dcce08eecbff8d5d359946d972)
1 /*-
2  * Copyright (c) 2011 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/types.h>
35 #include <sys/mbuf.h>
36 #include <sys/socket.h>
37 #include <sys/kernel.h>
38 #include <sys/kdb.h>
39 #include <sys/malloc.h>
40 #include <sys/queue.h>
41 #include <sys/taskqueue.h>
42 #include <sys/sysctl.h>
43 #include <sys/smp.h>
44 #include <net/bpf.h>
45 #include <net/ethernet.h>
46 #include <net/if.h>
47 #include <net/if_vlan_var.h>
48 #include <netinet/in.h>
49 #include <netinet/ip.h>
50 #include <netinet/ip6.h>
51 #include <netinet/tcp.h>
52 
53 #include "common/common.h"
54 #include "common/t4_regs.h"
55 #include "common/t4_regs_values.h"
56 #include "common/t4_msg.h"
57 
58 struct fl_buf_info {
59 	int size;
60 	int type;
61 	uma_zone_t zone;
62 };
63 
64 /* Filled up by t4_sge_modload */
65 static struct fl_buf_info fl_buf_info[FL_BUF_SIZES];
66 
67 #define FL_BUF_SIZE(x)	(fl_buf_info[x].size)
68 #define FL_BUF_TYPE(x)	(fl_buf_info[x].type)
69 #define FL_BUF_ZONE(x)	(fl_buf_info[x].zone)
70 
71 #ifdef T4_PKT_TIMESTAMP
72 #define RX_COPY_THRESHOLD (MINCLSIZE - 8)
73 #else
74 #define RX_COPY_THRESHOLD MINCLSIZE
75 #endif
76 
77 /*
78  * Ethernet frames are DMA'd at this byte offset into the freelist buffer.
79  * 0-7 are valid values.
80  */
81 static int fl_pktshift = 2;
82 TUNABLE_INT("hw.cxgbe.fl_pktshift", &fl_pktshift);
83 
84 /*
85  * Pad ethernet payload up to this boundary.
86  * -1: driver should figure out a good value.
87  *  Any power of 2, from 32 to 4096 (both inclusive) is a valid value.
88  */
89 static int fl_pad = -1;
90 TUNABLE_INT("hw.cxgbe.fl_pad", &fl_pad);
91 
92 /*
93  * Status page length.
94  * -1: driver should figure out a good value.
95  *  64 or 128 are the only other valid values.
96  */
97 static int spg_len = -1;
98 TUNABLE_INT("hw.cxgbe.spg_len", &spg_len);
99 
100 /*
101  * Congestion drops.
102  * -1: no congestion feedback (not recommended).
103  *  0: backpressure the channel instead of dropping packets right away.
104  *  1: no backpressure, drop packets for the congested queue immediately.
105  */
106 static int cong_drop = 0;
107 TUNABLE_INT("hw.cxgbe.cong_drop", &cong_drop);
108 
109 /* Used to track coalesced tx work request */
110 struct txpkts {
111 	uint64_t *flitp;	/* ptr to flit where next pkt should start */
112 	uint8_t npkt;		/* # of packets in this work request */
113 	uint8_t nflits;		/* # of flits used by this work request */
114 	uint16_t plen;		/* total payload (sum of all packets) */
115 };
116 
117 /* A packet's SGL.  This + m_pkthdr has all info needed for tx */
118 struct sgl {
119 	int nsegs;		/* # of segments in the SGL, 0 means imm. tx */
120 	int nflits;		/* # of flits needed for the SGL */
121 	bus_dma_segment_t seg[TX_SGL_SEGS];
122 };
123 
124 static int service_iq(struct sge_iq *, int);
125 static struct mbuf *get_fl_payload(struct adapter *, struct sge_fl *, uint32_t,
126     int *);
127 static int t4_eth_rx(struct sge_iq *, const struct rss_header *, struct mbuf *);
128 static inline void init_iq(struct sge_iq *, struct adapter *, int, int, int,
129     int);
130 static inline void init_fl(struct sge_fl *, int, int, char *);
131 static inline void init_eq(struct sge_eq *, int, int, uint8_t, uint16_t,
132     char *);
133 static int alloc_ring(struct adapter *, size_t, bus_dma_tag_t *, bus_dmamap_t *,
134     bus_addr_t *, void **);
135 static int free_ring(struct adapter *, bus_dma_tag_t, bus_dmamap_t, bus_addr_t,
136     void *);
137 static int alloc_iq_fl(struct port_info *, struct sge_iq *, struct sge_fl *,
138     int, int);
139 static int free_iq_fl(struct port_info *, struct sge_iq *, struct sge_fl *);
140 static int alloc_fwq(struct adapter *);
141 static int free_fwq(struct adapter *);
142 static int alloc_mgmtq(struct adapter *);
143 static int free_mgmtq(struct adapter *);
144 static int alloc_rxq(struct port_info *, struct sge_rxq *, int, int,
145     struct sysctl_oid *);
146 static int free_rxq(struct port_info *, struct sge_rxq *);
147 #ifdef TCP_OFFLOAD
148 static int alloc_ofld_rxq(struct port_info *, struct sge_ofld_rxq *, int, int,
149     struct sysctl_oid *);
150 static int free_ofld_rxq(struct port_info *, struct sge_ofld_rxq *);
151 #endif
152 static int ctrl_eq_alloc(struct adapter *, struct sge_eq *);
153 static int eth_eq_alloc(struct adapter *, struct port_info *, struct sge_eq *);
154 #ifdef TCP_OFFLOAD
155 static int ofld_eq_alloc(struct adapter *, struct port_info *, struct sge_eq *);
156 #endif
157 static int alloc_eq(struct adapter *, struct port_info *, struct sge_eq *);
158 static int free_eq(struct adapter *, struct sge_eq *);
159 static int alloc_wrq(struct adapter *, struct port_info *, struct sge_wrq *,
160     struct sysctl_oid *);
161 static int free_wrq(struct adapter *, struct sge_wrq *);
162 static int alloc_txq(struct port_info *, struct sge_txq *, int,
163     struct sysctl_oid *);
164 static int free_txq(struct port_info *, struct sge_txq *);
165 static void oneseg_dma_callback(void *, bus_dma_segment_t *, int, int);
166 static inline bool is_new_response(const struct sge_iq *, struct rsp_ctrl **);
167 static inline void iq_next(struct sge_iq *);
168 static inline void ring_fl_db(struct adapter *, struct sge_fl *);
169 static int refill_fl(struct adapter *, struct sge_fl *, int);
170 static void refill_sfl(void *);
171 static int alloc_fl_sdesc(struct sge_fl *);
172 static void free_fl_sdesc(struct sge_fl *);
173 static void set_fl_tag_idx(struct sge_fl *, int);
174 static void add_fl_to_sfl(struct adapter *, struct sge_fl *);
175 
176 static int get_pkt_sgl(struct sge_txq *, struct mbuf **, struct sgl *, int);
177 static int free_pkt_sgl(struct sge_txq *, struct sgl *);
178 static int write_txpkt_wr(struct port_info *, struct sge_txq *, struct mbuf *,
179     struct sgl *);
180 static int add_to_txpkts(struct port_info *, struct sge_txq *, struct txpkts *,
181     struct mbuf *, struct sgl *);
182 static void write_txpkts_wr(struct sge_txq *, struct txpkts *);
183 static inline void write_ulp_cpl_sgl(struct port_info *, struct sge_txq *,
184     struct txpkts *, struct mbuf *, struct sgl *);
185 static int write_sgl_to_txd(struct sge_eq *, struct sgl *, caddr_t *);
186 static inline void copy_to_txd(struct sge_eq *, caddr_t, caddr_t *, int);
187 static inline void ring_eq_db(struct adapter *, struct sge_eq *);
188 static inline int reclaimable(struct sge_eq *);
189 static int reclaim_tx_descs(struct sge_txq *, int, int);
190 static void write_eqflush_wr(struct sge_eq *);
191 static __be64 get_flit(bus_dma_segment_t *, int, int);
192 static int handle_sge_egr_update(struct sge_iq *, const struct rss_header *,
193     struct mbuf *);
194 static int handle_fw_msg(struct sge_iq *, const struct rss_header *,
195     struct mbuf *);
196 
197 static int sysctl_uint16(SYSCTL_HANDLER_ARGS);
198 
199 #if defined(__i386__) || defined(__amd64__)
200 extern u_int cpu_clflush_line_size;
201 #endif
202 
203 /*
204  * Called on MOD_LOAD.  Fills up fl_buf_info[] and validates/calculates the SGE
205  * tunables.
206  */
207 void
208 t4_sge_modload(void)
209 {
210 	int i;
211 	int bufsize[FL_BUF_SIZES] = {
212 		MCLBYTES,
213 #if MJUMPAGESIZE != MCLBYTES
214 		MJUMPAGESIZE,
215 #endif
216 		MJUM9BYTES,
217 		MJUM16BYTES
218 	};
219 
220 	for (i = 0; i < FL_BUF_SIZES; i++) {
221 		FL_BUF_SIZE(i) = bufsize[i];
222 		FL_BUF_TYPE(i) = m_gettype(bufsize[i]);
223 		FL_BUF_ZONE(i) = m_getzone(bufsize[i]);
224 	}
225 
226 	if (fl_pktshift < 0 || fl_pktshift > 7) {
227 		printf("Invalid hw.cxgbe.fl_pktshift value (%d),"
228 		    " using 2 instead.\n", fl_pktshift);
229 		fl_pktshift = 2;
230 	}
231 
232 	if (fl_pad < 32 || fl_pad > 4096 || !powerof2(fl_pad)) {
233 		int pad;
234 
235 #if defined(__i386__) || defined(__amd64__)
236 		pad = max(cpu_clflush_line_size, 32);
237 #else
238 		pad = max(CACHE_LINE_SIZE, 32);
239 #endif
240 		pad = min(pad, 4096);
241 
242 		if (fl_pad != -1) {
243 			printf("Invalid hw.cxgbe.fl_pad value (%d),"
244 			    " using %d instead.\n", fl_pad, pad);
245 		}
246 		fl_pad = pad;
247 	}
248 
249 	if (spg_len != 64 && spg_len != 128) {
250 		int len;
251 
252 #if defined(__i386__) || defined(__amd64__)
253 		len = cpu_clflush_line_size > 64 ? 128 : 64;
254 #else
255 		len = 64;
256 #endif
257 		if (spg_len != -1) {
258 			printf("Invalid hw.cxgbe.spg_len value (%d),"
259 			    " using %d instead.\n", spg_len, len);
260 		}
261 		spg_len = len;
262 	}
263 
264 	if (cong_drop < -1 || cong_drop > 1) {
265 		printf("Invalid hw.cxgbe.cong_drop value (%d),"
266 		    " using 0 instead.\n", cong_drop);
267 		cong_drop = 0;
268 	}
269 }
270 
271 void
272 t4_init_sge_cpl_handlers(struct adapter *sc)
273 {
274 
275 	t4_register_cpl_handler(sc, CPL_FW4_MSG, handle_fw_msg);
276 	t4_register_cpl_handler(sc, CPL_FW6_MSG, handle_fw_msg);
277 	t4_register_cpl_handler(sc, CPL_SGE_EGR_UPDATE, handle_sge_egr_update);
278 	t4_register_cpl_handler(sc, CPL_RX_PKT, t4_eth_rx);
279 
280 	t4_register_fw_msg_handler(sc, FW6_TYPE_CMD_RPL, t4_handle_fw_rpl);
281 }
282 
283 void
284 t4_tweak_chip_settings(struct adapter *sc)
285 {
286 	int i;
287 	uint32_t v, m;
288 	int intr_timer[SGE_NTIMERS] = {1, 5, 10, 50, 100, 200};
289 	int intr_pktcount[SGE_NCOUNTERS] = {1, 8, 16, 32}; /* 63 max */
290 	uint16_t indsz = min(RX_COPY_THRESHOLD - 1, M_INDICATESIZE);
291 
292 	KASSERT(sc->flags & MASTER_PF,
293 	    ("%s: trying to change chip settings when not master.", __func__));
294 
295 	m = V_PKTSHIFT(M_PKTSHIFT) | F_RXPKTCPLMODE |
296 	    V_INGPADBOUNDARY(M_INGPADBOUNDARY) | F_EGRSTATUSPAGESIZE;
297 	v = V_PKTSHIFT(fl_pktshift) | F_RXPKTCPLMODE |
298 	    V_INGPADBOUNDARY(ilog2(fl_pad) - 5) |
299 	    V_EGRSTATUSPAGESIZE(spg_len == 128);
300 	t4_set_reg_field(sc, A_SGE_CONTROL, m, v);
301 
302 	v = V_HOSTPAGESIZEPF0(PAGE_SHIFT - 10) |
303 	    V_HOSTPAGESIZEPF1(PAGE_SHIFT - 10) |
304 	    V_HOSTPAGESIZEPF2(PAGE_SHIFT - 10) |
305 	    V_HOSTPAGESIZEPF3(PAGE_SHIFT - 10) |
306 	    V_HOSTPAGESIZEPF4(PAGE_SHIFT - 10) |
307 	    V_HOSTPAGESIZEPF5(PAGE_SHIFT - 10) |
308 	    V_HOSTPAGESIZEPF6(PAGE_SHIFT - 10) |
309 	    V_HOSTPAGESIZEPF7(PAGE_SHIFT - 10);
310 	t4_write_reg(sc, A_SGE_HOST_PAGE_SIZE, v);
311 
312 	for (i = 0; i < FL_BUF_SIZES; i++) {
313 		t4_write_reg(sc, A_SGE_FL_BUFFER_SIZE0 + (4 * i),
314 		    FL_BUF_SIZE(i));
315 	}
316 
317 	v = V_THRESHOLD_0(intr_pktcount[0]) | V_THRESHOLD_1(intr_pktcount[1]) |
318 	    V_THRESHOLD_2(intr_pktcount[2]) | V_THRESHOLD_3(intr_pktcount[3]);
319 	t4_write_reg(sc, A_SGE_INGRESS_RX_THRESHOLD, v);
320 
321 	/* adap->params.vpd.cclk must be set up before this */
322 	v = V_TIMERVALUE0(us_to_core_ticks(sc, intr_timer[0])) |
323 	    V_TIMERVALUE1(us_to_core_ticks(sc, intr_timer[1]));
324 	t4_write_reg(sc, A_SGE_TIMER_VALUE_0_AND_1, v);
325 	v = V_TIMERVALUE2(us_to_core_ticks(sc, intr_timer[2])) |
326 	    V_TIMERVALUE3(us_to_core_ticks(sc, intr_timer[3]));
327 	t4_write_reg(sc, A_SGE_TIMER_VALUE_2_AND_3, v);
328 	v = V_TIMERVALUE4(us_to_core_ticks(sc, intr_timer[4])) |
329 	    V_TIMERVALUE5(us_to_core_ticks(sc, intr_timer[5]));
330 	t4_write_reg(sc, A_SGE_TIMER_VALUE_4_AND_5, v);
331 
332 	if (cong_drop == 0) {
333 		m = F_TUNNELCNGDROP0 | F_TUNNELCNGDROP1 | F_TUNNELCNGDROP2 |
334 		    F_TUNNELCNGDROP3;
335 		t4_set_reg_field(sc, A_TP_PARA_REG3, m, 0);
336 	}
337 
338 	/* 4K, 16K, 64K, 256K DDP "page sizes" */
339 	v = V_HPZ0(0) | V_HPZ1(2) | V_HPZ2(4) | V_HPZ3(6);
340 	t4_write_reg(sc, A_ULP_RX_TDDP_PSZ, v);
341 
342 	m = v = F_TDDPTAGTCB;
343 	t4_set_reg_field(sc, A_ULP_RX_CTL, m, v);
344 
345 	m = V_INDICATESIZE(M_INDICATESIZE) | F_REARMDDPOFFSET |
346 	    F_RESETDDPOFFSET;
347 	v = V_INDICATESIZE(indsz) | F_REARMDDPOFFSET | F_RESETDDPOFFSET;
348 	t4_set_reg_field(sc, A_TP_PARA_REG5, m, v);
349 }
350 
351 /*
352  * XXX: driver really should be able to deal with unexpected settings.
353  */
354 int
355 t4_read_chip_settings(struct adapter *sc)
356 {
357 	struct sge *s = &sc->sge;
358 	int i, rc = 0;
359 	uint32_t m, v, r;
360 	uint16_t indsz = min(RX_COPY_THRESHOLD - 1, M_INDICATESIZE);
361 
362 	m = V_PKTSHIFT(M_PKTSHIFT) | F_RXPKTCPLMODE |
363 	    V_INGPADBOUNDARY(M_INGPADBOUNDARY) | F_EGRSTATUSPAGESIZE;
364 	v = V_PKTSHIFT(fl_pktshift) | F_RXPKTCPLMODE |
365 	    V_INGPADBOUNDARY(ilog2(fl_pad) - 5) |
366 	    V_EGRSTATUSPAGESIZE(spg_len == 128);
367 	r = t4_read_reg(sc, A_SGE_CONTROL);
368 	if ((r & m) != v) {
369 		device_printf(sc->dev, "invalid SGE_CONTROL(0x%x)\n", r);
370 		rc = EINVAL;
371 	}
372 
373 	v = V_HOSTPAGESIZEPF0(PAGE_SHIFT - 10) |
374 	    V_HOSTPAGESIZEPF1(PAGE_SHIFT - 10) |
375 	    V_HOSTPAGESIZEPF2(PAGE_SHIFT - 10) |
376 	    V_HOSTPAGESIZEPF3(PAGE_SHIFT - 10) |
377 	    V_HOSTPAGESIZEPF4(PAGE_SHIFT - 10) |
378 	    V_HOSTPAGESIZEPF5(PAGE_SHIFT - 10) |
379 	    V_HOSTPAGESIZEPF6(PAGE_SHIFT - 10) |
380 	    V_HOSTPAGESIZEPF7(PAGE_SHIFT - 10);
381 	r = t4_read_reg(sc, A_SGE_HOST_PAGE_SIZE);
382 	if (r != v) {
383 		device_printf(sc->dev, "invalid SGE_HOST_PAGE_SIZE(0x%x)\n", r);
384 		rc = EINVAL;
385 	}
386 
387 	for (i = 0; i < FL_BUF_SIZES; i++) {
388 		v = t4_read_reg(sc, A_SGE_FL_BUFFER_SIZE0 + (4 * i));
389 		if (v != FL_BUF_SIZE(i)) {
390 			device_printf(sc->dev,
391 			    "invalid SGE_FL_BUFFER_SIZE[%d](0x%x)\n", i, v);
392 			rc = EINVAL;
393 		}
394 	}
395 
396 	r = t4_read_reg(sc, A_SGE_INGRESS_RX_THRESHOLD);
397 	s->counter_val[0] = G_THRESHOLD_0(r);
398 	s->counter_val[1] = G_THRESHOLD_1(r);
399 	s->counter_val[2] = G_THRESHOLD_2(r);
400 	s->counter_val[3] = G_THRESHOLD_3(r);
401 
402 	r = t4_read_reg(sc, A_SGE_TIMER_VALUE_0_AND_1);
403 	s->timer_val[0] = G_TIMERVALUE0(r) / core_ticks_per_usec(sc);
404 	s->timer_val[1] = G_TIMERVALUE1(r) / core_ticks_per_usec(sc);
405 	r = t4_read_reg(sc, A_SGE_TIMER_VALUE_2_AND_3);
406 	s->timer_val[2] = G_TIMERVALUE2(r) / core_ticks_per_usec(sc);
407 	s->timer_val[3] = G_TIMERVALUE3(r) / core_ticks_per_usec(sc);
408 	r = t4_read_reg(sc, A_SGE_TIMER_VALUE_4_AND_5);
409 	s->timer_val[4] = G_TIMERVALUE4(r) / core_ticks_per_usec(sc);
410 	s->timer_val[5] = G_TIMERVALUE5(r) / core_ticks_per_usec(sc);
411 
412 	if (cong_drop == 0) {
413 		m = F_TUNNELCNGDROP0 | F_TUNNELCNGDROP1 | F_TUNNELCNGDROP2 |
414 		    F_TUNNELCNGDROP3;
415 		r = t4_read_reg(sc, A_TP_PARA_REG3);
416 		if (r & m) {
417 			device_printf(sc->dev,
418 			    "invalid TP_PARA_REG3(0x%x)\n", r);
419 			rc = EINVAL;
420 		}
421 	}
422 
423 	v = V_HPZ0(0) | V_HPZ1(2) | V_HPZ2(4) | V_HPZ3(6);
424 	r = t4_read_reg(sc, A_ULP_RX_TDDP_PSZ);
425 	if (r != v) {
426 		device_printf(sc->dev, "invalid ULP_RX_TDDP_PSZ(0x%x)\n", r);
427 		rc = EINVAL;
428 	}
429 
430 	m = v = F_TDDPTAGTCB;
431 	r = t4_read_reg(sc, A_ULP_RX_CTL);
432 	if ((r & m) != v) {
433 		device_printf(sc->dev, "invalid ULP_RX_CTL(0x%x)\n", r);
434 		rc = EINVAL;
435 	}
436 
437 	m = V_INDICATESIZE(M_INDICATESIZE) | F_REARMDDPOFFSET |
438 	    F_RESETDDPOFFSET;
439 	v = V_INDICATESIZE(indsz) | F_REARMDDPOFFSET | F_RESETDDPOFFSET;
440 	r = t4_read_reg(sc, A_TP_PARA_REG5);
441 	if ((r & m) != v) {
442 		device_printf(sc->dev, "invalid TP_PARA_REG5(0x%x)\n", r);
443 		rc = EINVAL;
444 	}
445 
446 	r = t4_read_reg(sc, A_SGE_CONM_CTRL);
447 	s->fl_starve_threshold = G_EGRTHRESHOLD(r) * 2 + 1;
448 
449 	if (is_t5(sc)) {
450 		r = t4_read_reg(sc, A_SGE_EGRESS_QUEUES_PER_PAGE_PF);
451 		r >>= S_QUEUESPERPAGEPF0 +
452 		    (S_QUEUESPERPAGEPF1 - S_QUEUESPERPAGEPF0) * sc->pf;
453 		s->s_qpp = r & M_QUEUESPERPAGEPF0;
454 	}
455 
456 	r = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
457 	sc->params.tp.tre = G_TIMERRESOLUTION(r);
458 	sc->params.tp.dack_re = G_DELAYEDACKRESOLUTION(r);
459 
460 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
461 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
462 
463 	t4_read_indirect(sc, A_TP_PIO_ADDR, A_TP_PIO_DATA, &sc->filter_mode, 1,
464 	    A_TP_VLAN_PRI_MAP);
465 
466 	return (rc);
467 }
468 
469 int
470 t4_create_dma_tag(struct adapter *sc)
471 {
472 	int rc;
473 
474 	rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), 1, 0,
475 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, BUS_SPACE_MAXSIZE,
476 	    BUS_SPACE_UNRESTRICTED, BUS_SPACE_MAXSIZE, BUS_DMA_ALLOCNOW, NULL,
477 	    NULL, &sc->dmat);
478 	if (rc != 0) {
479 		device_printf(sc->dev,
480 		    "failed to create main DMA tag: %d\n", rc);
481 	}
482 
483 	return (rc);
484 }
485 
486 int
487 t4_destroy_dma_tag(struct adapter *sc)
488 {
489 	if (sc->dmat)
490 		bus_dma_tag_destroy(sc->dmat);
491 
492 	return (0);
493 }
494 
495 /*
496  * Allocate and initialize the firmware event queue and the management queue.
497  *
498  * Returns errno on failure.  Resources allocated up to that point may still be
499  * allocated.  Caller is responsible for cleanup in case this function fails.
500  */
501 int
502 t4_setup_adapter_queues(struct adapter *sc)
503 {
504 	int rc;
505 
506 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
507 
508 	sysctl_ctx_init(&sc->ctx);
509 	sc->flags |= ADAP_SYSCTL_CTX;
510 
511 	/*
512 	 * Firmware event queue
513 	 */
514 	rc = alloc_fwq(sc);
515 	if (rc != 0)
516 		return (rc);
517 
518 	/*
519 	 * Management queue.  This is just a control queue that uses the fwq as
520 	 * its associated iq.
521 	 */
522 	rc = alloc_mgmtq(sc);
523 
524 	return (rc);
525 }
526 
527 /*
528  * Idempotent
529  */
530 int
531 t4_teardown_adapter_queues(struct adapter *sc)
532 {
533 
534 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
535 
536 	/* Do this before freeing the queue */
537 	if (sc->flags & ADAP_SYSCTL_CTX) {
538 		sysctl_ctx_free(&sc->ctx);
539 		sc->flags &= ~ADAP_SYSCTL_CTX;
540 	}
541 
542 	free_mgmtq(sc);
543 	free_fwq(sc);
544 
545 	return (0);
546 }
547 
548 static inline int
549 first_vector(struct port_info *pi)
550 {
551 	struct adapter *sc = pi->adapter;
552 	int rc = T4_EXTRA_INTR, i;
553 
554 	if (sc->intr_count == 1)
555 		return (0);
556 
557 	for_each_port(sc, i) {
558 		struct port_info *p = sc->port[i];
559 
560 		if (i == pi->port_id)
561 			break;
562 
563 #ifdef TCP_OFFLOAD
564 		if (sc->flags & INTR_DIRECT)
565 			rc += p->nrxq + p->nofldrxq;
566 		else
567 			rc += max(p->nrxq, p->nofldrxq);
568 #else
569 		/*
570 		 * Not compiled with offload support and intr_count > 1.  Only
571 		 * NIC queues exist and they'd better be taking direct
572 		 * interrupts.
573 		 */
574 		KASSERT(sc->flags & INTR_DIRECT,
575 		    ("%s: intr_count %d, !INTR_DIRECT", __func__,
576 		    sc->intr_count));
577 
578 		rc += p->nrxq;
579 #endif
580 	}
581 
582 	return (rc);
583 }
584 
585 /*
586  * Given an arbitrary "index," come up with an iq that can be used by other
587  * queues (of this port) for interrupt forwarding, SGE egress updates, etc.
588  * The iq returned is guaranteed to be something that takes direct interrupts.
589  */
590 static struct sge_iq *
591 port_intr_iq(struct port_info *pi, int idx)
592 {
593 	struct adapter *sc = pi->adapter;
594 	struct sge *s = &sc->sge;
595 	struct sge_iq *iq = NULL;
596 
597 	if (sc->intr_count == 1)
598 		return (&sc->sge.fwq);
599 
600 #ifdef TCP_OFFLOAD
601 	if (sc->flags & INTR_DIRECT) {
602 		idx %= pi->nrxq + pi->nofldrxq;
603 
604 		if (idx >= pi->nrxq) {
605 			idx -= pi->nrxq;
606 			iq = &s->ofld_rxq[pi->first_ofld_rxq + idx].iq;
607 		} else
608 			iq = &s->rxq[pi->first_rxq + idx].iq;
609 
610 	} else {
611 		idx %= max(pi->nrxq, pi->nofldrxq);
612 
613 		if (pi->nrxq >= pi->nofldrxq)
614 			iq = &s->rxq[pi->first_rxq + idx].iq;
615 		else
616 			iq = &s->ofld_rxq[pi->first_ofld_rxq + idx].iq;
617 	}
618 #else
619 	/*
620 	 * Not compiled with offload support and intr_count > 1.  Only NIC
621 	 * queues exist and they'd better be taking direct interrupts.
622 	 */
623 	KASSERT(sc->flags & INTR_DIRECT,
624 	    ("%s: intr_count %d, !INTR_DIRECT", __func__, sc->intr_count));
625 
626 	idx %= pi->nrxq;
627 	iq = &s->rxq[pi->first_rxq + idx].iq;
628 #endif
629 
630 	KASSERT(iq->flags & IQ_INTR, ("%s: EDOOFUS", __func__));
631 	return (iq);
632 }
633 
634 static inline int
635 mtu_to_bufsize(int mtu)
636 {
637 	int bufsize;
638 
639 	/* large enough for a frame even when VLAN extraction is disabled */
640 	bufsize = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN + mtu;
641 	bufsize = roundup2(bufsize + fl_pktshift, fl_pad);
642 
643 	return (bufsize);
644 }
645 
646 int
647 t4_setup_port_queues(struct port_info *pi)
648 {
649 	int rc = 0, i, j, intr_idx, iqid;
650 	struct sge_rxq *rxq;
651 	struct sge_txq *txq;
652 	struct sge_wrq *ctrlq;
653 #ifdef TCP_OFFLOAD
654 	struct sge_ofld_rxq *ofld_rxq;
655 	struct sge_wrq *ofld_txq;
656 	struct sysctl_oid *oid2 = NULL;
657 #endif
658 	char name[16];
659 	struct adapter *sc = pi->adapter;
660 	struct sysctl_oid *oid = device_get_sysctl_tree(pi->dev);
661 	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
662 	int bufsize = mtu_to_bufsize(pi->ifp->if_mtu);
663 
664 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "rxq", CTLFLAG_RD,
665 	    NULL, "rx queues");
666 
667 #ifdef TCP_OFFLOAD
668 	if (is_offload(sc)) {
669 		oid2 = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ofld_rxq",
670 		    CTLFLAG_RD, NULL,
671 		    "rx queues for offloaded TCP connections");
672 	}
673 #endif
674 
675 	/* Interrupt vector to start from (when using multiple vectors) */
676 	intr_idx = first_vector(pi);
677 
678 	/*
679 	 * First pass over all rx queues (NIC and TOE):
680 	 * a) initialize iq and fl
681 	 * b) allocate queue iff it will take direct interrupts.
682 	 */
683 	for_each_rxq(pi, i, rxq) {
684 
685 		init_iq(&rxq->iq, sc, pi->tmr_idx, pi->pktc_idx, pi->qsize_rxq,
686 		    RX_IQ_ESIZE);
687 
688 		snprintf(name, sizeof(name), "%s rxq%d-fl",
689 		    device_get_nameunit(pi->dev), i);
690 		init_fl(&rxq->fl, pi->qsize_rxq / 8, bufsize, name);
691 
692 		if (sc->flags & INTR_DIRECT
693 #ifdef TCP_OFFLOAD
694 		    || (sc->intr_count > 1 && pi->nrxq >= pi->nofldrxq)
695 #endif
696 		   ) {
697 			rxq->iq.flags |= IQ_INTR;
698 			rc = alloc_rxq(pi, rxq, intr_idx, i, oid);
699 			if (rc != 0)
700 				goto done;
701 			intr_idx++;
702 		}
703 	}
704 
705 #ifdef TCP_OFFLOAD
706 	for_each_ofld_rxq(pi, i, ofld_rxq) {
707 
708 		init_iq(&ofld_rxq->iq, sc, pi->tmr_idx, pi->pktc_idx,
709 		    pi->qsize_rxq, RX_IQ_ESIZE);
710 
711 		snprintf(name, sizeof(name), "%s ofld_rxq%d-fl",
712 		    device_get_nameunit(pi->dev), i);
713 		init_fl(&ofld_rxq->fl, pi->qsize_rxq / 8, OFLD_BUF_SIZE, name);
714 
715 		if (sc->flags & INTR_DIRECT ||
716 		    (sc->intr_count > 1 && pi->nofldrxq > pi->nrxq)) {
717 			ofld_rxq->iq.flags |= IQ_INTR;
718 			rc = alloc_ofld_rxq(pi, ofld_rxq, intr_idx, i, oid2);
719 			if (rc != 0)
720 				goto done;
721 			intr_idx++;
722 		}
723 	}
724 #endif
725 
726 	/*
727 	 * Second pass over all rx queues (NIC and TOE).  The queues forwarding
728 	 * their interrupts are allocated now.
729 	 */
730 	j = 0;
731 	for_each_rxq(pi, i, rxq) {
732 		if (rxq->iq.flags & IQ_INTR)
733 			continue;
734 
735 		intr_idx = port_intr_iq(pi, j)->abs_id;
736 
737 		rc = alloc_rxq(pi, rxq, intr_idx, i, oid);
738 		if (rc != 0)
739 			goto done;
740 		j++;
741 	}
742 
743 #ifdef TCP_OFFLOAD
744 	for_each_ofld_rxq(pi, i, ofld_rxq) {
745 		if (ofld_rxq->iq.flags & IQ_INTR)
746 			continue;
747 
748 		intr_idx = port_intr_iq(pi, j)->abs_id;
749 
750 		rc = alloc_ofld_rxq(pi, ofld_rxq, intr_idx, i, oid2);
751 		if (rc != 0)
752 			goto done;
753 		j++;
754 	}
755 #endif
756 
757 	/*
758 	 * Now the tx queues.  Only one pass needed.
759 	 */
760 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "txq", CTLFLAG_RD,
761 	    NULL, "tx queues");
762 	j = 0;
763 	for_each_txq(pi, i, txq) {
764 		uint16_t iqid;
765 
766 		iqid = port_intr_iq(pi, j)->cntxt_id;
767 
768 		snprintf(name, sizeof(name), "%s txq%d",
769 		    device_get_nameunit(pi->dev), i);
770 		init_eq(&txq->eq, EQ_ETH, pi->qsize_txq, pi->tx_chan, iqid,
771 		    name);
772 
773 		rc = alloc_txq(pi, txq, i, oid);
774 		if (rc != 0)
775 			goto done;
776 		j++;
777 	}
778 
779 #ifdef TCP_OFFLOAD
780 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ofld_txq",
781 	    CTLFLAG_RD, NULL, "tx queues for offloaded TCP connections");
782 	for_each_ofld_txq(pi, i, ofld_txq) {
783 		uint16_t iqid;
784 
785 		iqid = port_intr_iq(pi, j)->cntxt_id;
786 
787 		snprintf(name, sizeof(name), "%s ofld_txq%d",
788 		    device_get_nameunit(pi->dev), i);
789 		init_eq(&ofld_txq->eq, EQ_OFLD, pi->qsize_txq, pi->tx_chan,
790 		    iqid, name);
791 
792 		snprintf(name, sizeof(name), "%d", i);
793 		oid2 = SYSCTL_ADD_NODE(&pi->ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
794 		    name, CTLFLAG_RD, NULL, "offload tx queue");
795 
796 		rc = alloc_wrq(sc, pi, ofld_txq, oid2);
797 		if (rc != 0)
798 			goto done;
799 		j++;
800 	}
801 #endif
802 
803 	/*
804 	 * Finally, the control queue.
805 	 */
806 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "ctrlq", CTLFLAG_RD,
807 	    NULL, "ctrl queue");
808 	ctrlq = &sc->sge.ctrlq[pi->port_id];
809 	iqid = port_intr_iq(pi, 0)->cntxt_id;
810 	snprintf(name, sizeof(name), "%s ctrlq", device_get_nameunit(pi->dev));
811 	init_eq(&ctrlq->eq, EQ_CTRL, CTRL_EQ_QSIZE, pi->tx_chan, iqid, name);
812 	rc = alloc_wrq(sc, pi, ctrlq, oid);
813 
814 done:
815 	if (rc)
816 		t4_teardown_port_queues(pi);
817 
818 	return (rc);
819 }
820 
821 /*
822  * Idempotent
823  */
824 int
825 t4_teardown_port_queues(struct port_info *pi)
826 {
827 	int i;
828 	struct adapter *sc = pi->adapter;
829 	struct sge_rxq *rxq;
830 	struct sge_txq *txq;
831 #ifdef TCP_OFFLOAD
832 	struct sge_ofld_rxq *ofld_rxq;
833 	struct sge_wrq *ofld_txq;
834 #endif
835 
836 	/* Do this before freeing the queues */
837 	if (pi->flags & PORT_SYSCTL_CTX) {
838 		sysctl_ctx_free(&pi->ctx);
839 		pi->flags &= ~PORT_SYSCTL_CTX;
840 	}
841 
842 	/*
843 	 * Take down all the tx queues first, as they reference the rx queues
844 	 * (for egress updates, etc.).
845 	 */
846 
847 	free_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
848 
849 	for_each_txq(pi, i, txq) {
850 		free_txq(pi, txq);
851 	}
852 
853 #ifdef TCP_OFFLOAD
854 	for_each_ofld_txq(pi, i, ofld_txq) {
855 		free_wrq(sc, ofld_txq);
856 	}
857 #endif
858 
859 	/*
860 	 * Then take down the rx queues that forward their interrupts, as they
861 	 * reference other rx queues.
862 	 */
863 
864 	for_each_rxq(pi, i, rxq) {
865 		if ((rxq->iq.flags & IQ_INTR) == 0)
866 			free_rxq(pi, rxq);
867 	}
868 
869 #ifdef TCP_OFFLOAD
870 	for_each_ofld_rxq(pi, i, ofld_rxq) {
871 		if ((ofld_rxq->iq.flags & IQ_INTR) == 0)
872 			free_ofld_rxq(pi, ofld_rxq);
873 	}
874 #endif
875 
876 	/*
877 	 * Then take down the rx queues that take direct interrupts.
878 	 */
879 
880 	for_each_rxq(pi, i, rxq) {
881 		if (rxq->iq.flags & IQ_INTR)
882 			free_rxq(pi, rxq);
883 	}
884 
885 #ifdef TCP_OFFLOAD
886 	for_each_ofld_rxq(pi, i, ofld_rxq) {
887 		if (ofld_rxq->iq.flags & IQ_INTR)
888 			free_ofld_rxq(pi, ofld_rxq);
889 	}
890 #endif
891 
892 	return (0);
893 }
894 
895 /*
896  * Deals with errors and the firmware event queue.  All data rx queues forward
897  * their interrupt to the firmware event queue.
898  */
899 void
900 t4_intr_all(void *arg)
901 {
902 	struct adapter *sc = arg;
903 	struct sge_iq *fwq = &sc->sge.fwq;
904 
905 	t4_intr_err(arg);
906 	if (atomic_cmpset_int(&fwq->state, IQS_IDLE, IQS_BUSY)) {
907 		service_iq(fwq, 0);
908 		atomic_cmpset_int(&fwq->state, IQS_BUSY, IQS_IDLE);
909 	}
910 }
911 
912 /* Deals with error interrupts */
913 void
914 t4_intr_err(void *arg)
915 {
916 	struct adapter *sc = arg;
917 
918 	t4_write_reg(sc, MYPF_REG(A_PCIE_PF_CLI), 0);
919 	t4_slow_intr_handler(sc);
920 }
921 
922 void
923 t4_intr_evt(void *arg)
924 {
925 	struct sge_iq *iq = arg;
926 
927 	if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
928 		service_iq(iq, 0);
929 		atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
930 	}
931 }
932 
933 void
934 t4_intr(void *arg)
935 {
936 	struct sge_iq *iq = arg;
937 
938 	if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
939 		service_iq(iq, 0);
940 		atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
941 	}
942 }
943 
944 /*
945  * Deals with anything and everything on the given ingress queue.
946  */
947 static int
948 service_iq(struct sge_iq *iq, int budget)
949 {
950 	struct sge_iq *q;
951 	struct sge_rxq *rxq = iq_to_rxq(iq);	/* Use iff iq is part of rxq */
952 	struct sge_fl *fl = &rxq->fl;		/* Use iff IQ_HAS_FL */
953 	struct adapter *sc = iq->adapter;
954 	struct rsp_ctrl *ctrl;
955 	const struct rss_header *rss;
956 	int ndescs = 0, limit, fl_bufs_used = 0;
957 	int rsp_type;
958 	uint32_t lq;
959 	struct mbuf *m0;
960 	STAILQ_HEAD(, sge_iq) iql = STAILQ_HEAD_INITIALIZER(iql);
961 
962 	limit = budget ? budget : iq->qsize / 8;
963 
964 	KASSERT(iq->state == IQS_BUSY, ("%s: iq %p not BUSY", __func__, iq));
965 
966 	/*
967 	 * We always come back and check the descriptor ring for new indirect
968 	 * interrupts and other responses after running a single handler.
969 	 */
970 	for (;;) {
971 		while (is_new_response(iq, &ctrl)) {
972 
973 			rmb();
974 
975 			m0 = NULL;
976 			rsp_type = G_RSPD_TYPE(ctrl->u.type_gen);
977 			lq = be32toh(ctrl->pldbuflen_qid);
978 			rss = (const void *)iq->cdesc;
979 
980 			switch (rsp_type) {
981 			case X_RSPD_TYPE_FLBUF:
982 
983 				KASSERT(iq->flags & IQ_HAS_FL,
984 				    ("%s: data for an iq (%p) with no freelist",
985 				    __func__, iq));
986 
987 				m0 = get_fl_payload(sc, fl, lq, &fl_bufs_used);
988 #ifdef T4_PKT_TIMESTAMP
989 				/*
990 				 * 60 bit timestamp for the payload is
991 				 * *(uint64_t *)m0->m_pktdat.  Note that it is
992 				 * in the leading free-space in the mbuf.  The
993 				 * kernel can clobber it during a pullup,
994 				 * m_copymdata, etc.  You need to make sure that
995 				 * the mbuf reaches you unmolested if you care
996 				 * about the timestamp.
997 				 */
998 				*(uint64_t *)m0->m_pktdat =
999 				    be64toh(ctrl->u.last_flit) &
1000 				    0xfffffffffffffff;
1001 #endif
1002 
1003 				/* fall through */
1004 
1005 			case X_RSPD_TYPE_CPL:
1006 				KASSERT(rss->opcode < NUM_CPL_CMDS,
1007 				    ("%s: bad opcode %02x.", __func__,
1008 				    rss->opcode));
1009 				sc->cpl_handler[rss->opcode](iq, rss, m0);
1010 				break;
1011 
1012 			case X_RSPD_TYPE_INTR:
1013 
1014 				/*
1015 				 * Interrupts should be forwarded only to queues
1016 				 * that are not forwarding their interrupts.
1017 				 * This means service_iq can recurse but only 1
1018 				 * level deep.
1019 				 */
1020 				KASSERT(budget == 0,
1021 				    ("%s: budget %u, rsp_type %u", __func__,
1022 				    budget, rsp_type));
1023 
1024 				q = sc->sge.iqmap[lq - sc->sge.iq_start];
1025 				if (atomic_cmpset_int(&q->state, IQS_IDLE,
1026 				    IQS_BUSY)) {
1027 					if (service_iq(q, q->qsize / 8) == 0) {
1028 						atomic_cmpset_int(&q->state,
1029 						    IQS_BUSY, IQS_IDLE);
1030 					} else {
1031 						STAILQ_INSERT_TAIL(&iql, q,
1032 						    link);
1033 					}
1034 				}
1035 				break;
1036 
1037 			default:
1038 				sc->an_handler(iq, ctrl);
1039 				break;
1040 			}
1041 
1042 			iq_next(iq);
1043 			if (++ndescs == limit) {
1044 				t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS),
1045 				    V_CIDXINC(ndescs) |
1046 				    V_INGRESSQID(iq->cntxt_id) |
1047 				    V_SEINTARM(V_QINTR_TIMER_IDX(X_TIMERREG_UPDATE_CIDX)));
1048 				ndescs = 0;
1049 
1050 				if (fl_bufs_used > 0) {
1051 					FL_LOCK(fl);
1052 					fl->needed += fl_bufs_used;
1053 					refill_fl(sc, fl, fl->cap / 8);
1054 					FL_UNLOCK(fl);
1055 					fl_bufs_used = 0;
1056 				}
1057 
1058 				if (budget)
1059 					return (EINPROGRESS);
1060 			}
1061 		}
1062 
1063 		if (STAILQ_EMPTY(&iql))
1064 			break;
1065 
1066 		/*
1067 		 * Process the head only, and send it to the back of the list if
1068 		 * it's still not done.
1069 		 */
1070 		q = STAILQ_FIRST(&iql);
1071 		STAILQ_REMOVE_HEAD(&iql, link);
1072 		if (service_iq(q, q->qsize / 8) == 0)
1073 			atomic_cmpset_int(&q->state, IQS_BUSY, IQS_IDLE);
1074 		else
1075 			STAILQ_INSERT_TAIL(&iql, q, link);
1076 	}
1077 
1078 #if defined(INET) || defined(INET6)
1079 	if (iq->flags & IQ_LRO_ENABLED) {
1080 		struct lro_ctrl *lro = &rxq->lro;
1081 		struct lro_entry *l;
1082 
1083 		while (!SLIST_EMPTY(&lro->lro_active)) {
1084 			l = SLIST_FIRST(&lro->lro_active);
1085 			SLIST_REMOVE_HEAD(&lro->lro_active, next);
1086 			tcp_lro_flush(lro, l);
1087 		}
1088 	}
1089 #endif
1090 
1091 	t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS), V_CIDXINC(ndescs) |
1092 	    V_INGRESSQID((u32)iq->cntxt_id) | V_SEINTARM(iq->intr_params));
1093 
1094 	if (iq->flags & IQ_HAS_FL) {
1095 		int starved;
1096 
1097 		FL_LOCK(fl);
1098 		fl->needed += fl_bufs_used;
1099 		starved = refill_fl(sc, fl, fl->cap / 4);
1100 		FL_UNLOCK(fl);
1101 		if (__predict_false(starved != 0))
1102 			add_fl_to_sfl(sc, fl);
1103 	}
1104 
1105 	return (0);
1106 }
1107 
1108 static struct mbuf *
1109 get_fl_payload(struct adapter *sc, struct sge_fl *fl, uint32_t len_newbuf,
1110     int *fl_bufs_used)
1111 {
1112 	struct mbuf *m0, *m;
1113 	struct fl_sdesc *sd = &fl->sdesc[fl->cidx];
1114 	unsigned int nbuf, len;
1115 
1116 	/*
1117 	 * No assertion for the fl lock because we don't need it.  This routine
1118 	 * is called only from the rx interrupt handler and it only updates
1119 	 * fl->cidx.  (Contrast that with fl->pidx/fl->needed which could be
1120 	 * updated in the rx interrupt handler or the starvation helper routine.
1121 	 * That's why code that manipulates fl->pidx/fl->needed needs the fl
1122 	 * lock but this routine does not).
1123 	 */
1124 
1125 	if (__predict_false((len_newbuf & F_RSPD_NEWBUF) == 0))
1126 		panic("%s: cannot handle packed frames", __func__);
1127 	len = G_RSPD_LEN(len_newbuf);
1128 
1129 	m0 = sd->m;
1130 	sd->m = NULL;	/* consumed */
1131 
1132 	bus_dmamap_sync(fl->tag[sd->tag_idx], sd->map, BUS_DMASYNC_POSTREAD);
1133 	m_init(m0, NULL, 0, M_NOWAIT, MT_DATA, M_PKTHDR);
1134 #ifdef T4_PKT_TIMESTAMP
1135 	/* Leave room for a timestamp */
1136 	m0->m_data += 8;
1137 #endif
1138 
1139 	if (len < RX_COPY_THRESHOLD) {
1140 		/* copy data to mbuf, buffer will be recycled */
1141 		bcopy(sd->cl, mtod(m0, caddr_t), len);
1142 		m0->m_len = len;
1143 	} else {
1144 		bus_dmamap_unload(fl->tag[sd->tag_idx], sd->map);
1145 		m_cljset(m0, sd->cl, FL_BUF_TYPE(sd->tag_idx));
1146 		sd->cl = NULL;	/* consumed */
1147 		m0->m_len = min(len, FL_BUF_SIZE(sd->tag_idx));
1148 	}
1149 	m0->m_pkthdr.len = len;
1150 
1151 	sd++;
1152 	if (__predict_false(++fl->cidx == fl->cap)) {
1153 		sd = fl->sdesc;
1154 		fl->cidx = 0;
1155 	}
1156 
1157 	m = m0;
1158 	len -= m->m_len;
1159 	nbuf = 1;	/* # of fl buffers used */
1160 
1161 	while (len > 0) {
1162 		m->m_next = sd->m;
1163 		sd->m = NULL;	/* consumed */
1164 		m = m->m_next;
1165 
1166 		bus_dmamap_sync(fl->tag[sd->tag_idx], sd->map,
1167 		    BUS_DMASYNC_POSTREAD);
1168 
1169 		m_init(m, NULL, 0, M_NOWAIT, MT_DATA, 0);
1170 		if (len <= MLEN) {
1171 			bcopy(sd->cl, mtod(m, caddr_t), len);
1172 			m->m_len = len;
1173 		} else {
1174 			bus_dmamap_unload(fl->tag[sd->tag_idx],
1175 			    sd->map);
1176 			m_cljset(m, sd->cl, FL_BUF_TYPE(sd->tag_idx));
1177 			sd->cl = NULL;	/* consumed */
1178 			m->m_len = min(len, FL_BUF_SIZE(sd->tag_idx));
1179 		}
1180 
1181 		sd++;
1182 		if (__predict_false(++fl->cidx == fl->cap)) {
1183 			sd = fl->sdesc;
1184 			fl->cidx = 0;
1185 		}
1186 
1187 		len -= m->m_len;
1188 		nbuf++;
1189 	}
1190 
1191 	(*fl_bufs_used) += nbuf;
1192 
1193 	return (m0);
1194 }
1195 
1196 static int
1197 t4_eth_rx(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m0)
1198 {
1199 	struct sge_rxq *rxq = iq_to_rxq(iq);
1200 	struct ifnet *ifp = rxq->ifp;
1201 	const struct cpl_rx_pkt *cpl = (const void *)(rss + 1);
1202 #if defined(INET) || defined(INET6)
1203 	struct lro_ctrl *lro = &rxq->lro;
1204 #endif
1205 
1206 	KASSERT(m0 != NULL, ("%s: no payload with opcode %02x", __func__,
1207 	    rss->opcode));
1208 
1209 	m0->m_pkthdr.len -= fl_pktshift;
1210 	m0->m_len -= fl_pktshift;
1211 	m0->m_data += fl_pktshift;
1212 
1213 	m0->m_pkthdr.rcvif = ifp;
1214 	m0->m_flags |= M_FLOWID;
1215 	m0->m_pkthdr.flowid = rss->hash_val;
1216 
1217 	if (cpl->csum_calc && !cpl->err_vec) {
1218 		if (ifp->if_capenable & IFCAP_RXCSUM &&
1219 		    cpl->l2info & htobe32(F_RXF_IP)) {
1220 			m0->m_pkthdr.csum_flags = (CSUM_IP_CHECKED |
1221 			    CSUM_IP_VALID | CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1222 			rxq->rxcsum++;
1223 		} else if (ifp->if_capenable & IFCAP_RXCSUM_IPV6 &&
1224 		    cpl->l2info & htobe32(F_RXF_IP6)) {
1225 			m0->m_pkthdr.csum_flags = (CSUM_DATA_VALID_IPV6 |
1226 			    CSUM_PSEUDO_HDR);
1227 			rxq->rxcsum++;
1228 		}
1229 
1230 		if (__predict_false(cpl->ip_frag))
1231 			m0->m_pkthdr.csum_data = be16toh(cpl->csum);
1232 		else
1233 			m0->m_pkthdr.csum_data = 0xffff;
1234 	}
1235 
1236 	if (cpl->vlan_ex) {
1237 		m0->m_pkthdr.ether_vtag = be16toh(cpl->vlan);
1238 		m0->m_flags |= M_VLANTAG;
1239 		rxq->vlan_extraction++;
1240 	}
1241 
1242 #if defined(INET) || defined(INET6)
1243 	if (cpl->l2info & htobe32(F_RXF_LRO) &&
1244 	    iq->flags & IQ_LRO_ENABLED &&
1245 	    tcp_lro_rx(lro, m0, 0) == 0) {
1246 		/* queued for LRO */
1247 	} else
1248 #endif
1249 	ifp->if_input(ifp, m0);
1250 
1251 	return (0);
1252 }
1253 
1254 /*
1255  * Doesn't fail.  Holds on to work requests it can't send right away.
1256  */
1257 void
1258 t4_wrq_tx_locked(struct adapter *sc, struct sge_wrq *wrq, struct wrqe *wr)
1259 {
1260 	struct sge_eq *eq = &wrq->eq;
1261 	int can_reclaim;
1262 	caddr_t dst;
1263 
1264 	TXQ_LOCK_ASSERT_OWNED(wrq);
1265 #ifdef TCP_OFFLOAD
1266 	KASSERT((eq->flags & EQ_TYPEMASK) == EQ_OFLD ||
1267 	    (eq->flags & EQ_TYPEMASK) == EQ_CTRL,
1268 	    ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1269 #else
1270 	KASSERT((eq->flags & EQ_TYPEMASK) == EQ_CTRL,
1271 	    ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1272 #endif
1273 
1274 	if (__predict_true(wr != NULL))
1275 		STAILQ_INSERT_TAIL(&wrq->wr_list, wr, link);
1276 
1277 	can_reclaim = reclaimable(eq);
1278 	if (__predict_false(eq->flags & EQ_STALLED)) {
1279 		if (can_reclaim < tx_resume_threshold(eq))
1280 			return;
1281 		eq->flags &= ~EQ_STALLED;
1282 		eq->unstalled++;
1283 	}
1284 	eq->cidx += can_reclaim;
1285 	eq->avail += can_reclaim;
1286 	if (__predict_false(eq->cidx >= eq->cap))
1287 		eq->cidx -= eq->cap;
1288 
1289 	while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
1290 		int ndesc;
1291 
1292 		if (__predict_false(wr->wr_len < 0 ||
1293 		    wr->wr_len > SGE_MAX_WR_LEN || (wr->wr_len & 0x7))) {
1294 
1295 #ifdef INVARIANTS
1296 			panic("%s: work request with length %d", __func__,
1297 			    wr->wr_len);
1298 #endif
1299 #ifdef KDB
1300 			kdb_backtrace();
1301 #endif
1302 			log(LOG_ERR, "%s: %s work request with length %d",
1303 			    device_get_nameunit(sc->dev), __func__, wr->wr_len);
1304 			STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
1305 			free_wrqe(wr);
1306 			continue;
1307 		}
1308 
1309 		ndesc = howmany(wr->wr_len, EQ_ESIZE);
1310 		if (eq->avail < ndesc) {
1311 			wrq->no_desc++;
1312 			break;
1313 		}
1314 
1315 		dst = (void *)&eq->desc[eq->pidx];
1316 		copy_to_txd(eq, wrtod(wr), &dst, wr->wr_len);
1317 
1318 		eq->pidx += ndesc;
1319 		eq->avail -= ndesc;
1320 		if (__predict_false(eq->pidx >= eq->cap))
1321 			eq->pidx -= eq->cap;
1322 
1323 		eq->pending += ndesc;
1324 		if (eq->pending > 16)
1325 			ring_eq_db(sc, eq);
1326 
1327 		wrq->tx_wrs++;
1328 		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
1329 		free_wrqe(wr);
1330 
1331 		if (eq->avail < 8) {
1332 			can_reclaim = reclaimable(eq);
1333 			eq->cidx += can_reclaim;
1334 			eq->avail += can_reclaim;
1335 			if (__predict_false(eq->cidx >= eq->cap))
1336 				eq->cidx -= eq->cap;
1337 		}
1338 	}
1339 
1340 	if (eq->pending)
1341 		ring_eq_db(sc, eq);
1342 
1343 	if (wr != NULL) {
1344 		eq->flags |= EQ_STALLED;
1345 		if (callout_pending(&eq->tx_callout) == 0)
1346 			callout_reset(&eq->tx_callout, 1, t4_tx_callout, eq);
1347 	}
1348 }
1349 
1350 /* Per-packet header in a coalesced tx WR, before the SGL starts (in flits) */
1351 #define TXPKTS_PKT_HDR ((\
1352     sizeof(struct ulp_txpkt) + \
1353     sizeof(struct ulptx_idata) + \
1354     sizeof(struct cpl_tx_pkt_core) \
1355     ) / 8)
1356 
1357 /* Header of a coalesced tx WR, before SGL of first packet (in flits) */
1358 #define TXPKTS_WR_HDR (\
1359     sizeof(struct fw_eth_tx_pkts_wr) / 8 + \
1360     TXPKTS_PKT_HDR)
1361 
1362 /* Header of a tx WR, before SGL of first packet (in flits) */
1363 #define TXPKT_WR_HDR ((\
1364     sizeof(struct fw_eth_tx_pkt_wr) + \
1365     sizeof(struct cpl_tx_pkt_core) \
1366     ) / 8 )
1367 
1368 /* Header of a tx LSO WR, before SGL of first packet (in flits) */
1369 #define TXPKT_LSO_WR_HDR ((\
1370     sizeof(struct fw_eth_tx_pkt_wr) + \
1371     sizeof(struct cpl_tx_pkt_lso_core) + \
1372     sizeof(struct cpl_tx_pkt_core) \
1373     ) / 8 )
1374 
1375 int
1376 t4_eth_tx(struct ifnet *ifp, struct sge_txq *txq, struct mbuf *m)
1377 {
1378 	struct port_info *pi = (void *)ifp->if_softc;
1379 	struct adapter *sc = pi->adapter;
1380 	struct sge_eq *eq = &txq->eq;
1381 	struct buf_ring *br = txq->br;
1382 	struct mbuf *next;
1383 	int rc, coalescing, can_reclaim;
1384 	struct txpkts txpkts;
1385 	struct sgl sgl;
1386 
1387 	TXQ_LOCK_ASSERT_OWNED(txq);
1388 	KASSERT(m, ("%s: called with nothing to do.", __func__));
1389 	KASSERT((eq->flags & EQ_TYPEMASK) == EQ_ETH,
1390 	    ("%s: eq type %d", __func__, eq->flags & EQ_TYPEMASK));
1391 
1392 	prefetch(&eq->desc[eq->pidx]);
1393 	prefetch(&txq->sdesc[eq->pidx]);
1394 
1395 	txpkts.npkt = 0;/* indicates there's nothing in txpkts */
1396 	coalescing = 0;
1397 
1398 	can_reclaim = reclaimable(eq);
1399 	if (__predict_false(eq->flags & EQ_STALLED)) {
1400 		if (can_reclaim < tx_resume_threshold(eq)) {
1401 			txq->m = m;
1402 			return (0);
1403 		}
1404 		eq->flags &= ~EQ_STALLED;
1405 		eq->unstalled++;
1406 	}
1407 
1408 	if (__predict_false(eq->flags & EQ_DOOMED)) {
1409 		m_freem(m);
1410 		while ((m = buf_ring_dequeue_sc(txq->br)) != NULL)
1411 			m_freem(m);
1412 		return (ENETDOWN);
1413 	}
1414 
1415 	if (eq->avail < 8 && can_reclaim)
1416 		reclaim_tx_descs(txq, can_reclaim, 32);
1417 
1418 	for (; m; m = next ? next : drbr_dequeue(ifp, br)) {
1419 
1420 		if (eq->avail < 8)
1421 			break;
1422 
1423 		next = m->m_nextpkt;
1424 		m->m_nextpkt = NULL;
1425 
1426 		if (next || buf_ring_peek(br))
1427 			coalescing = 1;
1428 
1429 		rc = get_pkt_sgl(txq, &m, &sgl, coalescing);
1430 		if (rc != 0) {
1431 			if (rc == ENOMEM) {
1432 
1433 				/* Short of resources, suspend tx */
1434 
1435 				m->m_nextpkt = next;
1436 				break;
1437 			}
1438 
1439 			/*
1440 			 * Unrecoverable error for this packet, throw it away
1441 			 * and move on to the next.  get_pkt_sgl may already
1442 			 * have freed m (it will be NULL in that case and the
1443 			 * m_freem here is still safe).
1444 			 */
1445 
1446 			m_freem(m);
1447 			continue;
1448 		}
1449 
1450 		if (coalescing &&
1451 		    add_to_txpkts(pi, txq, &txpkts, m, &sgl) == 0) {
1452 
1453 			/* Successfully absorbed into txpkts */
1454 
1455 			write_ulp_cpl_sgl(pi, txq, &txpkts, m, &sgl);
1456 			goto doorbell;
1457 		}
1458 
1459 		/*
1460 		 * We weren't coalescing to begin with, or current frame could
1461 		 * not be coalesced (add_to_txpkts flushes txpkts if a frame
1462 		 * given to it can't be coalesced).  Either way there should be
1463 		 * nothing in txpkts.
1464 		 */
1465 		KASSERT(txpkts.npkt == 0,
1466 		    ("%s: txpkts not empty: %d", __func__, txpkts.npkt));
1467 
1468 		/* We're sending out individual packets now */
1469 		coalescing = 0;
1470 
1471 		if (eq->avail < 8)
1472 			reclaim_tx_descs(txq, 0, 8);
1473 		rc = write_txpkt_wr(pi, txq, m, &sgl);
1474 		if (rc != 0) {
1475 
1476 			/* Short of hardware descriptors, suspend tx */
1477 
1478 			/*
1479 			 * This is an unlikely but expensive failure.  We've
1480 			 * done all the hard work (DMA mappings etc.) and now we
1481 			 * can't send out the packet.  What's worse, we have to
1482 			 * spend even more time freeing up everything in sgl.
1483 			 */
1484 			txq->no_desc++;
1485 			free_pkt_sgl(txq, &sgl);
1486 
1487 			m->m_nextpkt = next;
1488 			break;
1489 		}
1490 
1491 		ETHER_BPF_MTAP(ifp, m);
1492 		if (sgl.nsegs == 0)
1493 			m_freem(m);
1494 doorbell:
1495 		if (eq->pending >= 64)
1496 		    ring_eq_db(sc, eq);
1497 
1498 		can_reclaim = reclaimable(eq);
1499 		if (can_reclaim >= 32)
1500 			reclaim_tx_descs(txq, can_reclaim, 64);
1501 	}
1502 
1503 	if (txpkts.npkt > 0)
1504 		write_txpkts_wr(txq, &txpkts);
1505 
1506 	/*
1507 	 * m not NULL means there was an error but we haven't thrown it away.
1508 	 * This can happen when we're short of tx descriptors (no_desc) or maybe
1509 	 * even DMA maps (no_dmamap).  Either way, a credit flush and reclaim
1510 	 * will get things going again.
1511 	 */
1512 	if (m && !(eq->flags & EQ_CRFLUSHED)) {
1513 		struct tx_sdesc *txsd = &txq->sdesc[eq->pidx];
1514 
1515 		/*
1516 		 * If EQ_CRFLUSHED is not set then we know we have at least one
1517 		 * available descriptor because any WR that reduces eq->avail to
1518 		 * 0 also sets EQ_CRFLUSHED.
1519 		 */
1520 		KASSERT(eq->avail > 0, ("%s: no space for eqflush.", __func__));
1521 
1522 		txsd->desc_used = 1;
1523 		txsd->credits = 0;
1524 		write_eqflush_wr(eq);
1525 	}
1526 	txq->m = m;
1527 
1528 	if (eq->pending)
1529 		ring_eq_db(sc, eq);
1530 
1531 	reclaim_tx_descs(txq, 0, 128);
1532 
1533 	if (eq->flags & EQ_STALLED && callout_pending(&eq->tx_callout) == 0)
1534 		callout_reset(&eq->tx_callout, 1, t4_tx_callout, eq);
1535 
1536 	return (0);
1537 }
1538 
1539 void
1540 t4_update_fl_bufsize(struct ifnet *ifp)
1541 {
1542 	struct port_info *pi = ifp->if_softc;
1543 	struct sge_rxq *rxq;
1544 	struct sge_fl *fl;
1545 	int i, bufsize = mtu_to_bufsize(ifp->if_mtu);
1546 
1547 	for_each_rxq(pi, i, rxq) {
1548 		fl = &rxq->fl;
1549 
1550 		FL_LOCK(fl);
1551 		set_fl_tag_idx(fl, bufsize);
1552 		FL_UNLOCK(fl);
1553 	}
1554 }
1555 
1556 int
1557 can_resume_tx(struct sge_eq *eq)
1558 {
1559 	return (reclaimable(eq) >= tx_resume_threshold(eq));
1560 }
1561 
1562 static inline void
1563 init_iq(struct sge_iq *iq, struct adapter *sc, int tmr_idx, int pktc_idx,
1564     int qsize, int esize)
1565 {
1566 	KASSERT(tmr_idx >= 0 && tmr_idx < SGE_NTIMERS,
1567 	    ("%s: bad tmr_idx %d", __func__, tmr_idx));
1568 	KASSERT(pktc_idx < SGE_NCOUNTERS,	/* -ve is ok, means don't use */
1569 	    ("%s: bad pktc_idx %d", __func__, pktc_idx));
1570 
1571 	iq->flags = 0;
1572 	iq->adapter = sc;
1573 	iq->intr_params = V_QINTR_TIMER_IDX(tmr_idx);
1574 	iq->intr_pktc_idx = SGE_NCOUNTERS - 1;
1575 	if (pktc_idx >= 0) {
1576 		iq->intr_params |= F_QINTR_CNT_EN;
1577 		iq->intr_pktc_idx = pktc_idx;
1578 	}
1579 	iq->qsize = roundup2(qsize, 16);	/* See FW_IQ_CMD/iqsize */
1580 	iq->esize = max(esize, 16);		/* See FW_IQ_CMD/iqesize */
1581 }
1582 
1583 static inline void
1584 init_fl(struct sge_fl *fl, int qsize, int bufsize, char *name)
1585 {
1586 	fl->qsize = qsize;
1587 	strlcpy(fl->lockname, name, sizeof(fl->lockname));
1588 	set_fl_tag_idx(fl, bufsize);
1589 }
1590 
1591 static inline void
1592 init_eq(struct sge_eq *eq, int eqtype, int qsize, uint8_t tx_chan,
1593     uint16_t iqid, char *name)
1594 {
1595 	KASSERT(tx_chan < NCHAN, ("%s: bad tx channel %d", __func__, tx_chan));
1596 	KASSERT(eqtype <= EQ_TYPEMASK, ("%s: bad qtype %d", __func__, eqtype));
1597 
1598 	eq->flags = eqtype & EQ_TYPEMASK;
1599 	eq->tx_chan = tx_chan;
1600 	eq->iqid = iqid;
1601 	eq->qsize = qsize;
1602 	strlcpy(eq->lockname, name, sizeof(eq->lockname));
1603 
1604 	TASK_INIT(&eq->tx_task, 0, t4_tx_task, eq);
1605 	callout_init(&eq->tx_callout, CALLOUT_MPSAFE);
1606 }
1607 
1608 static int
1609 alloc_ring(struct adapter *sc, size_t len, bus_dma_tag_t *tag,
1610     bus_dmamap_t *map, bus_addr_t *pa, void **va)
1611 {
1612 	int rc;
1613 
1614 	rc = bus_dma_tag_create(sc->dmat, 512, 0, BUS_SPACE_MAXADDR,
1615 	    BUS_SPACE_MAXADDR, NULL, NULL, len, 1, len, 0, NULL, NULL, tag);
1616 	if (rc != 0) {
1617 		device_printf(sc->dev, "cannot allocate DMA tag: %d\n", rc);
1618 		goto done;
1619 	}
1620 
1621 	rc = bus_dmamem_alloc(*tag, va,
1622 	    BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO, map);
1623 	if (rc != 0) {
1624 		device_printf(sc->dev, "cannot allocate DMA memory: %d\n", rc);
1625 		goto done;
1626 	}
1627 
1628 	rc = bus_dmamap_load(*tag, *map, *va, len, oneseg_dma_callback, pa, 0);
1629 	if (rc != 0) {
1630 		device_printf(sc->dev, "cannot load DMA map: %d\n", rc);
1631 		goto done;
1632 	}
1633 done:
1634 	if (rc)
1635 		free_ring(sc, *tag, *map, *pa, *va);
1636 
1637 	return (rc);
1638 }
1639 
1640 static int
1641 free_ring(struct adapter *sc, bus_dma_tag_t tag, bus_dmamap_t map,
1642     bus_addr_t pa, void *va)
1643 {
1644 	if (pa)
1645 		bus_dmamap_unload(tag, map);
1646 	if (va)
1647 		bus_dmamem_free(tag, va, map);
1648 	if (tag)
1649 		bus_dma_tag_destroy(tag);
1650 
1651 	return (0);
1652 }
1653 
1654 /*
1655  * Allocates the ring for an ingress queue and an optional freelist.  If the
1656  * freelist is specified it will be allocated and then associated with the
1657  * ingress queue.
1658  *
1659  * Returns errno on failure.  Resources allocated up to that point may still be
1660  * allocated.  Caller is responsible for cleanup in case this function fails.
1661  *
1662  * If the ingress queue will take interrupts directly (iq->flags & IQ_INTR) then
1663  * the intr_idx specifies the vector, starting from 0.  Otherwise it specifies
1664  * the abs_id of the ingress queue to which its interrupts should be forwarded.
1665  */
1666 static int
1667 alloc_iq_fl(struct port_info *pi, struct sge_iq *iq, struct sge_fl *fl,
1668     int intr_idx, int cong)
1669 {
1670 	int rc, i, cntxt_id;
1671 	size_t len;
1672 	struct fw_iq_cmd c;
1673 	struct adapter *sc = iq->adapter;
1674 	__be32 v = 0;
1675 
1676 	len = iq->qsize * iq->esize;
1677 	rc = alloc_ring(sc, len, &iq->desc_tag, &iq->desc_map, &iq->ba,
1678 	    (void **)&iq->desc);
1679 	if (rc != 0)
1680 		return (rc);
1681 
1682 	bzero(&c, sizeof(c));
1683 	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_IQ_CMD) | F_FW_CMD_REQUEST |
1684 	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_IQ_CMD_PFN(sc->pf) |
1685 	    V_FW_IQ_CMD_VFN(0));
1686 
1687 	c.alloc_to_len16 = htobe32(F_FW_IQ_CMD_ALLOC | F_FW_IQ_CMD_IQSTART |
1688 	    FW_LEN16(c));
1689 
1690 	/* Special handling for firmware event queue */
1691 	if (iq == &sc->sge.fwq)
1692 		v |= F_FW_IQ_CMD_IQASYNCH;
1693 
1694 	if (iq->flags & IQ_INTR) {
1695 		KASSERT(intr_idx < sc->intr_count,
1696 		    ("%s: invalid direct intr_idx %d", __func__, intr_idx));
1697 	} else
1698 		v |= F_FW_IQ_CMD_IQANDST;
1699 	v |= V_FW_IQ_CMD_IQANDSTINDEX(intr_idx);
1700 
1701 	c.type_to_iqandstindex = htobe32(v |
1702 	    V_FW_IQ_CMD_TYPE(FW_IQ_TYPE_FL_INT_CAP) |
1703 	    V_FW_IQ_CMD_VIID(pi->viid) |
1704 	    V_FW_IQ_CMD_IQANUD(X_UPDATEDELIVERY_INTERRUPT));
1705 	c.iqdroprss_to_iqesize = htobe16(V_FW_IQ_CMD_IQPCIECH(pi->tx_chan) |
1706 	    F_FW_IQ_CMD_IQGTSMODE |
1707 	    V_FW_IQ_CMD_IQINTCNTTHRESH(iq->intr_pktc_idx) |
1708 	    V_FW_IQ_CMD_IQESIZE(ilog2(iq->esize) - 4));
1709 	c.iqsize = htobe16(iq->qsize);
1710 	c.iqaddr = htobe64(iq->ba);
1711 	if (cong >= 0)
1712 		c.iqns_to_fl0congen = htobe32(F_FW_IQ_CMD_IQFLINTCONGEN);
1713 
1714 	if (fl) {
1715 		mtx_init(&fl->fl_lock, fl->lockname, NULL, MTX_DEF);
1716 
1717 		for (i = 0; i < FL_BUF_SIZES; i++) {
1718 
1719 			/*
1720 			 * A freelist buffer must be 16 byte aligned as the SGE
1721 			 * uses the low 4 bits of the bus addr to figure out the
1722 			 * buffer size.
1723 			 */
1724 			rc = bus_dma_tag_create(sc->dmat, 16, 0,
1725 			    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
1726 			    FL_BUF_SIZE(i), 1, FL_BUF_SIZE(i), BUS_DMA_ALLOCNOW,
1727 			    NULL, NULL, &fl->tag[i]);
1728 			if (rc != 0) {
1729 				device_printf(sc->dev,
1730 				    "failed to create fl DMA tag[%d]: %d\n",
1731 				    i, rc);
1732 				return (rc);
1733 			}
1734 		}
1735 		len = fl->qsize * RX_FL_ESIZE;
1736 		rc = alloc_ring(sc, len, &fl->desc_tag, &fl->desc_map,
1737 		    &fl->ba, (void **)&fl->desc);
1738 		if (rc)
1739 			return (rc);
1740 
1741 		/* Allocate space for one software descriptor per buffer. */
1742 		fl->cap = (fl->qsize - spg_len / RX_FL_ESIZE) * 8;
1743 		FL_LOCK(fl);
1744 		rc = alloc_fl_sdesc(fl);
1745 		FL_UNLOCK(fl);
1746 		if (rc != 0) {
1747 			device_printf(sc->dev,
1748 			    "failed to setup fl software descriptors: %d\n",
1749 			    rc);
1750 			return (rc);
1751 		}
1752 		fl->needed = fl->cap;
1753 		fl->lowat = roundup2(sc->sge.fl_starve_threshold, 8);
1754 
1755 		c.iqns_to_fl0congen |=
1756 		    htobe32(V_FW_IQ_CMD_FL0HOSTFCMODE(X_HOSTFCMODE_NONE) |
1757 			F_FW_IQ_CMD_FL0FETCHRO | F_FW_IQ_CMD_FL0DATARO |
1758 			F_FW_IQ_CMD_FL0PADEN);
1759 		if (cong >= 0) {
1760 			c.iqns_to_fl0congen |=
1761 				htobe32(V_FW_IQ_CMD_FL0CNGCHMAP(cong) |
1762 				    F_FW_IQ_CMD_FL0CONGCIF |
1763 				    F_FW_IQ_CMD_FL0CONGEN);
1764 		}
1765 		c.fl0dcaen_to_fl0cidxfthresh =
1766 		    htobe16(V_FW_IQ_CMD_FL0FBMIN(X_FETCHBURSTMIN_64B) |
1767 			V_FW_IQ_CMD_FL0FBMAX(X_FETCHBURSTMAX_512B));
1768 		c.fl0size = htobe16(fl->qsize);
1769 		c.fl0addr = htobe64(fl->ba);
1770 	}
1771 
1772 	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
1773 	if (rc != 0) {
1774 		device_printf(sc->dev,
1775 		    "failed to create ingress queue: %d\n", rc);
1776 		return (rc);
1777 	}
1778 
1779 	iq->cdesc = iq->desc;
1780 	iq->cidx = 0;
1781 	iq->gen = 1;
1782 	iq->intr_next = iq->intr_params;
1783 	iq->cntxt_id = be16toh(c.iqid);
1784 	iq->abs_id = be16toh(c.physiqid);
1785 	iq->flags |= IQ_ALLOCATED;
1786 
1787 	cntxt_id = iq->cntxt_id - sc->sge.iq_start;
1788 	if (cntxt_id >= sc->sge.niq) {
1789 		panic ("%s: iq->cntxt_id (%d) more than the max (%d)", __func__,
1790 		    cntxt_id, sc->sge.niq - 1);
1791 	}
1792 	sc->sge.iqmap[cntxt_id] = iq;
1793 
1794 	if (fl) {
1795 		fl->cntxt_id = be16toh(c.fl0id);
1796 		fl->pidx = fl->cidx = 0;
1797 
1798 		cntxt_id = fl->cntxt_id - sc->sge.eq_start;
1799 		if (cntxt_id >= sc->sge.neq) {
1800 			panic("%s: fl->cntxt_id (%d) more than the max (%d)",
1801 			    __func__, cntxt_id, sc->sge.neq - 1);
1802 		}
1803 		sc->sge.eqmap[cntxt_id] = (void *)fl;
1804 
1805 		FL_LOCK(fl);
1806 		/* Enough to make sure the SGE doesn't think it's starved */
1807 		refill_fl(sc, fl, fl->lowat);
1808 		FL_UNLOCK(fl);
1809 
1810 		iq->flags |= IQ_HAS_FL;
1811 	}
1812 
1813 	/* Enable IQ interrupts */
1814 	atomic_store_rel_int(&iq->state, IQS_IDLE);
1815 	t4_write_reg(sc, MYPF_REG(A_SGE_PF_GTS), V_SEINTARM(iq->intr_params) |
1816 	    V_INGRESSQID(iq->cntxt_id));
1817 
1818 	return (0);
1819 }
1820 
1821 static int
1822 free_iq_fl(struct port_info *pi, struct sge_iq *iq, struct sge_fl *fl)
1823 {
1824 	int i, rc;
1825 	struct adapter *sc = iq->adapter;
1826 	device_t dev;
1827 
1828 	if (sc == NULL)
1829 		return (0);	/* nothing to do */
1830 
1831 	dev = pi ? pi->dev : sc->dev;
1832 
1833 	if (iq->flags & IQ_ALLOCATED) {
1834 		rc = -t4_iq_free(sc, sc->mbox, sc->pf, 0,
1835 		    FW_IQ_TYPE_FL_INT_CAP, iq->cntxt_id,
1836 		    fl ? fl->cntxt_id : 0xffff, 0xffff);
1837 		if (rc != 0) {
1838 			device_printf(dev,
1839 			    "failed to free queue %p: %d\n", iq, rc);
1840 			return (rc);
1841 		}
1842 		iq->flags &= ~IQ_ALLOCATED;
1843 	}
1844 
1845 	free_ring(sc, iq->desc_tag, iq->desc_map, iq->ba, iq->desc);
1846 
1847 	bzero(iq, sizeof(*iq));
1848 
1849 	if (fl) {
1850 		free_ring(sc, fl->desc_tag, fl->desc_map, fl->ba,
1851 		    fl->desc);
1852 
1853 		if (fl->sdesc) {
1854 			FL_LOCK(fl);
1855 			free_fl_sdesc(fl);
1856 			FL_UNLOCK(fl);
1857 		}
1858 
1859 		if (mtx_initialized(&fl->fl_lock))
1860 			mtx_destroy(&fl->fl_lock);
1861 
1862 		for (i = 0; i < FL_BUF_SIZES; i++) {
1863 			if (fl->tag[i])
1864 				bus_dma_tag_destroy(fl->tag[i]);
1865 		}
1866 
1867 		bzero(fl, sizeof(*fl));
1868 	}
1869 
1870 	return (0);
1871 }
1872 
1873 static int
1874 alloc_fwq(struct adapter *sc)
1875 {
1876 	int rc, intr_idx;
1877 	struct sge_iq *fwq = &sc->sge.fwq;
1878 	struct sysctl_oid *oid = device_get_sysctl_tree(sc->dev);
1879 	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
1880 
1881 	init_iq(fwq, sc, 0, 0, FW_IQ_QSIZE, FW_IQ_ESIZE);
1882 	fwq->flags |= IQ_INTR;	/* always */
1883 	intr_idx = sc->intr_count > 1 ? 1 : 0;
1884 	rc = alloc_iq_fl(sc->port[0], fwq, NULL, intr_idx, -1);
1885 	if (rc != 0) {
1886 		device_printf(sc->dev,
1887 		    "failed to create firmware event queue: %d\n", rc);
1888 		return (rc);
1889 	}
1890 
1891 	oid = SYSCTL_ADD_NODE(&sc->ctx, children, OID_AUTO, "fwq", CTLFLAG_RD,
1892 	    NULL, "firmware event queue");
1893 	children = SYSCTL_CHILDREN(oid);
1894 
1895 	SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "abs_id",
1896 	    CTLTYPE_INT | CTLFLAG_RD, &fwq->abs_id, 0, sysctl_uint16, "I",
1897 	    "absolute id of the queue");
1898 	SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "cntxt_id",
1899 	    CTLTYPE_INT | CTLFLAG_RD, &fwq->cntxt_id, 0, sysctl_uint16, "I",
1900 	    "SGE context id of the queue");
1901 	SYSCTL_ADD_PROC(&sc->ctx, children, OID_AUTO, "cidx",
1902 	    CTLTYPE_INT | CTLFLAG_RD, &fwq->cidx, 0, sysctl_uint16, "I",
1903 	    "consumer index");
1904 
1905 	return (0);
1906 }
1907 
1908 static int
1909 free_fwq(struct adapter *sc)
1910 {
1911 	return free_iq_fl(NULL, &sc->sge.fwq, NULL);
1912 }
1913 
1914 static int
1915 alloc_mgmtq(struct adapter *sc)
1916 {
1917 	int rc;
1918 	struct sge_wrq *mgmtq = &sc->sge.mgmtq;
1919 	char name[16];
1920 	struct sysctl_oid *oid = device_get_sysctl_tree(sc->dev);
1921 	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
1922 
1923 	oid = SYSCTL_ADD_NODE(&sc->ctx, children, OID_AUTO, "mgmtq", CTLFLAG_RD,
1924 	    NULL, "management queue");
1925 
1926 	snprintf(name, sizeof(name), "%s mgmtq", device_get_nameunit(sc->dev));
1927 	init_eq(&mgmtq->eq, EQ_CTRL, CTRL_EQ_QSIZE, sc->port[0]->tx_chan,
1928 	    sc->sge.fwq.cntxt_id, name);
1929 	rc = alloc_wrq(sc, NULL, mgmtq, oid);
1930 	if (rc != 0) {
1931 		device_printf(sc->dev,
1932 		    "failed to create management queue: %d\n", rc);
1933 		return (rc);
1934 	}
1935 
1936 	return (0);
1937 }
1938 
1939 static int
1940 free_mgmtq(struct adapter *sc)
1941 {
1942 
1943 	return free_wrq(sc, &sc->sge.mgmtq);
1944 }
1945 
1946 static inline int
1947 tnl_cong(struct port_info *pi)
1948 {
1949 
1950 	if (cong_drop == -1)
1951 		return (-1);
1952 	else if (cong_drop == 1)
1953 		return (0);
1954 	else
1955 		return (1 << pi->tx_chan);
1956 }
1957 
1958 static int
1959 alloc_rxq(struct port_info *pi, struct sge_rxq *rxq, int intr_idx, int idx,
1960     struct sysctl_oid *oid)
1961 {
1962 	int rc;
1963 	struct sysctl_oid_list *children;
1964 	char name[16];
1965 
1966 	rc = alloc_iq_fl(pi, &rxq->iq, &rxq->fl, intr_idx, tnl_cong(pi));
1967 	if (rc != 0)
1968 		return (rc);
1969 
1970 	FL_LOCK(&rxq->fl);
1971 	refill_fl(pi->adapter, &rxq->fl, rxq->fl.needed / 8);
1972 	FL_UNLOCK(&rxq->fl);
1973 
1974 #if defined(INET) || defined(INET6)
1975 	rc = tcp_lro_init(&rxq->lro);
1976 	if (rc != 0)
1977 		return (rc);
1978 	rxq->lro.ifp = pi->ifp; /* also indicates LRO init'ed */
1979 
1980 	if (pi->ifp->if_capenable & IFCAP_LRO)
1981 		rxq->iq.flags |= IQ_LRO_ENABLED;
1982 #endif
1983 	rxq->ifp = pi->ifp;
1984 
1985 	children = SYSCTL_CHILDREN(oid);
1986 
1987 	snprintf(name, sizeof(name), "%d", idx);
1988 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
1989 	    NULL, "rx queue");
1990 	children = SYSCTL_CHILDREN(oid);
1991 
1992 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "abs_id",
1993 	    CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.abs_id, 0, sysctl_uint16, "I",
1994 	    "absolute id of the queue");
1995 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
1996 	    CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.cntxt_id, 0, sysctl_uint16, "I",
1997 	    "SGE context id of the queue");
1998 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
1999 	    CTLTYPE_INT | CTLFLAG_RD, &rxq->iq.cidx, 0, sysctl_uint16, "I",
2000 	    "consumer index");
2001 #if defined(INET) || defined(INET6)
2002 	SYSCTL_ADD_INT(&pi->ctx, children, OID_AUTO, "lro_queued", CTLFLAG_RD,
2003 	    &rxq->lro.lro_queued, 0, NULL);
2004 	SYSCTL_ADD_INT(&pi->ctx, children, OID_AUTO, "lro_flushed", CTLFLAG_RD,
2005 	    &rxq->lro.lro_flushed, 0, NULL);
2006 #endif
2007 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "rxcsum", CTLFLAG_RD,
2008 	    &rxq->rxcsum, "# of times hardware assisted with checksum");
2009 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "vlan_extraction",
2010 	    CTLFLAG_RD, &rxq->vlan_extraction,
2011 	    "# of times hardware extracted 802.1Q tag");
2012 
2013 	children = SYSCTL_CHILDREN(oid);
2014 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "fl", CTLFLAG_RD,
2015 	    NULL, "freelist");
2016 	children = SYSCTL_CHILDREN(oid);
2017 
2018 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
2019 	    CTLTYPE_INT | CTLFLAG_RD, &rxq->fl.cntxt_id, 0, sysctl_uint16, "I",
2020 	    "SGE context id of the queue");
2021 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cidx", CTLFLAG_RD,
2022 	    &rxq->fl.cidx, 0, "consumer index");
2023 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "pidx", CTLFLAG_RD,
2024 	    &rxq->fl.pidx, 0, "producer index");
2025 
2026 	return (rc);
2027 }
2028 
2029 static int
2030 free_rxq(struct port_info *pi, struct sge_rxq *rxq)
2031 {
2032 	int rc;
2033 
2034 #if defined(INET) || defined(INET6)
2035 	if (rxq->lro.ifp) {
2036 		tcp_lro_free(&rxq->lro);
2037 		rxq->lro.ifp = NULL;
2038 	}
2039 #endif
2040 
2041 	rc = free_iq_fl(pi, &rxq->iq, &rxq->fl);
2042 	if (rc == 0)
2043 		bzero(rxq, sizeof(*rxq));
2044 
2045 	return (rc);
2046 }
2047 
2048 #ifdef TCP_OFFLOAD
2049 static int
2050 alloc_ofld_rxq(struct port_info *pi, struct sge_ofld_rxq *ofld_rxq,
2051     int intr_idx, int idx, struct sysctl_oid *oid)
2052 {
2053 	int rc;
2054 	struct sysctl_oid_list *children;
2055 	char name[16];
2056 
2057 	rc = alloc_iq_fl(pi, &ofld_rxq->iq, &ofld_rxq->fl, intr_idx,
2058 	    1 << pi->tx_chan);
2059 	if (rc != 0)
2060 		return (rc);
2061 
2062 	children = SYSCTL_CHILDREN(oid);
2063 
2064 	snprintf(name, sizeof(name), "%d", idx);
2065 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
2066 	    NULL, "rx queue");
2067 	children = SYSCTL_CHILDREN(oid);
2068 
2069 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "abs_id",
2070 	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.abs_id, 0, sysctl_uint16,
2071 	    "I", "absolute id of the queue");
2072 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
2073 	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.cntxt_id, 0, sysctl_uint16,
2074 	    "I", "SGE context id of the queue");
2075 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
2076 	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->iq.cidx, 0, sysctl_uint16, "I",
2077 	    "consumer index");
2078 
2079 	children = SYSCTL_CHILDREN(oid);
2080 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, "fl", CTLFLAG_RD,
2081 	    NULL, "freelist");
2082 	children = SYSCTL_CHILDREN(oid);
2083 
2084 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cntxt_id",
2085 	    CTLTYPE_INT | CTLFLAG_RD, &ofld_rxq->fl.cntxt_id, 0, sysctl_uint16,
2086 	    "I", "SGE context id of the queue");
2087 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cidx", CTLFLAG_RD,
2088 	    &ofld_rxq->fl.cidx, 0, "consumer index");
2089 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "pidx", CTLFLAG_RD,
2090 	    &ofld_rxq->fl.pidx, 0, "producer index");
2091 
2092 	return (rc);
2093 }
2094 
2095 static int
2096 free_ofld_rxq(struct port_info *pi, struct sge_ofld_rxq *ofld_rxq)
2097 {
2098 	int rc;
2099 
2100 	rc = free_iq_fl(pi, &ofld_rxq->iq, &ofld_rxq->fl);
2101 	if (rc == 0)
2102 		bzero(ofld_rxq, sizeof(*ofld_rxq));
2103 
2104 	return (rc);
2105 }
2106 #endif
2107 
2108 static int
2109 ctrl_eq_alloc(struct adapter *sc, struct sge_eq *eq)
2110 {
2111 	int rc, cntxt_id;
2112 	struct fw_eq_ctrl_cmd c;
2113 
2114 	bzero(&c, sizeof(c));
2115 
2116 	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_CTRL_CMD) | F_FW_CMD_REQUEST |
2117 	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_CTRL_CMD_PFN(sc->pf) |
2118 	    V_FW_EQ_CTRL_CMD_VFN(0));
2119 	c.alloc_to_len16 = htobe32(F_FW_EQ_CTRL_CMD_ALLOC |
2120 	    F_FW_EQ_CTRL_CMD_EQSTART | FW_LEN16(c));
2121 	c.cmpliqid_eqid = htonl(V_FW_EQ_CTRL_CMD_CMPLIQID(eq->iqid)); /* XXX */
2122 	c.physeqid_pkd = htobe32(0);
2123 	c.fetchszm_to_iqid =
2124 	    htobe32(V_FW_EQ_CTRL_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
2125 		V_FW_EQ_CTRL_CMD_PCIECHN(eq->tx_chan) |
2126 		F_FW_EQ_CTRL_CMD_FETCHRO | V_FW_EQ_CTRL_CMD_IQID(eq->iqid));
2127 	c.dcaen_to_eqsize =
2128 	    htobe32(V_FW_EQ_CTRL_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2129 		V_FW_EQ_CTRL_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2130 		V_FW_EQ_CTRL_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
2131 		V_FW_EQ_CTRL_CMD_EQSIZE(eq->qsize));
2132 	c.eqaddr = htobe64(eq->ba);
2133 
2134 	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
2135 	if (rc != 0) {
2136 		device_printf(sc->dev,
2137 		    "failed to create control queue %d: %d\n", eq->tx_chan, rc);
2138 		return (rc);
2139 	}
2140 	eq->flags |= EQ_ALLOCATED;
2141 
2142 	eq->cntxt_id = G_FW_EQ_CTRL_CMD_EQID(be32toh(c.cmpliqid_eqid));
2143 	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
2144 	if (cntxt_id >= sc->sge.neq)
2145 	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
2146 		cntxt_id, sc->sge.neq - 1);
2147 	sc->sge.eqmap[cntxt_id] = eq;
2148 
2149 	return (rc);
2150 }
2151 
2152 static int
2153 eth_eq_alloc(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
2154 {
2155 	int rc, cntxt_id;
2156 	struct fw_eq_eth_cmd c;
2157 
2158 	bzero(&c, sizeof(c));
2159 
2160 	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_ETH_CMD) | F_FW_CMD_REQUEST |
2161 	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_ETH_CMD_PFN(sc->pf) |
2162 	    V_FW_EQ_ETH_CMD_VFN(0));
2163 	c.alloc_to_len16 = htobe32(F_FW_EQ_ETH_CMD_ALLOC |
2164 	    F_FW_EQ_ETH_CMD_EQSTART | FW_LEN16(c));
2165 	c.viid_pkd = htobe32(V_FW_EQ_ETH_CMD_VIID(pi->viid));
2166 	c.fetchszm_to_iqid =
2167 	    htobe32(V_FW_EQ_ETH_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
2168 		V_FW_EQ_ETH_CMD_PCIECHN(eq->tx_chan) | F_FW_EQ_ETH_CMD_FETCHRO |
2169 		V_FW_EQ_ETH_CMD_IQID(eq->iqid));
2170 	c.dcaen_to_eqsize = htobe32(V_FW_EQ_ETH_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2171 		      V_FW_EQ_ETH_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2172 		      V_FW_EQ_ETH_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
2173 		      V_FW_EQ_ETH_CMD_EQSIZE(eq->qsize));
2174 	c.eqaddr = htobe64(eq->ba);
2175 
2176 	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
2177 	if (rc != 0) {
2178 		device_printf(pi->dev,
2179 		    "failed to create Ethernet egress queue: %d\n", rc);
2180 		return (rc);
2181 	}
2182 	eq->flags |= EQ_ALLOCATED;
2183 
2184 	eq->cntxt_id = G_FW_EQ_ETH_CMD_EQID(be32toh(c.eqid_pkd));
2185 	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
2186 	if (cntxt_id >= sc->sge.neq)
2187 	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
2188 		cntxt_id, sc->sge.neq - 1);
2189 	sc->sge.eqmap[cntxt_id] = eq;
2190 
2191 	return (rc);
2192 }
2193 
2194 #ifdef TCP_OFFLOAD
2195 static int
2196 ofld_eq_alloc(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
2197 {
2198 	int rc, cntxt_id;
2199 	struct fw_eq_ofld_cmd c;
2200 
2201 	bzero(&c, sizeof(c));
2202 
2203 	c.op_to_vfn = htonl(V_FW_CMD_OP(FW_EQ_OFLD_CMD) | F_FW_CMD_REQUEST |
2204 	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_OFLD_CMD_PFN(sc->pf) |
2205 	    V_FW_EQ_OFLD_CMD_VFN(0));
2206 	c.alloc_to_len16 = htonl(F_FW_EQ_OFLD_CMD_ALLOC |
2207 	    F_FW_EQ_OFLD_CMD_EQSTART | FW_LEN16(c));
2208 	c.fetchszm_to_iqid =
2209 		htonl(V_FW_EQ_OFLD_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
2210 		    V_FW_EQ_OFLD_CMD_PCIECHN(eq->tx_chan) |
2211 		    F_FW_EQ_OFLD_CMD_FETCHRO | V_FW_EQ_OFLD_CMD_IQID(eq->iqid));
2212 	c.dcaen_to_eqsize =
2213 	    htobe32(V_FW_EQ_OFLD_CMD_FBMIN(X_FETCHBURSTMIN_64B) |
2214 		V_FW_EQ_OFLD_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
2215 		V_FW_EQ_OFLD_CMD_CIDXFTHRESH(X_CIDXFLUSHTHRESH_32) |
2216 		V_FW_EQ_OFLD_CMD_EQSIZE(eq->qsize));
2217 	c.eqaddr = htobe64(eq->ba);
2218 
2219 	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
2220 	if (rc != 0) {
2221 		device_printf(pi->dev,
2222 		    "failed to create egress queue for TCP offload: %d\n", rc);
2223 		return (rc);
2224 	}
2225 	eq->flags |= EQ_ALLOCATED;
2226 
2227 	eq->cntxt_id = G_FW_EQ_OFLD_CMD_EQID(be32toh(c.eqid_pkd));
2228 	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
2229 	if (cntxt_id >= sc->sge.neq)
2230 	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
2231 		cntxt_id, sc->sge.neq - 1);
2232 	sc->sge.eqmap[cntxt_id] = eq;
2233 
2234 	return (rc);
2235 }
2236 #endif
2237 
2238 static int
2239 alloc_eq(struct adapter *sc, struct port_info *pi, struct sge_eq *eq)
2240 {
2241 	int rc;
2242 	size_t len;
2243 
2244 	mtx_init(&eq->eq_lock, eq->lockname, NULL, MTX_DEF);
2245 
2246 	len = eq->qsize * EQ_ESIZE;
2247 	rc = alloc_ring(sc, len, &eq->desc_tag, &eq->desc_map,
2248 	    &eq->ba, (void **)&eq->desc);
2249 	if (rc)
2250 		return (rc);
2251 
2252 	eq->cap = eq->qsize - spg_len / EQ_ESIZE;
2253 	eq->spg = (void *)&eq->desc[eq->cap];
2254 	eq->avail = eq->cap - 1;	/* one less to avoid cidx = pidx */
2255 	eq->pidx = eq->cidx = 0;
2256 	eq->doorbells = sc->doorbells;
2257 
2258 	switch (eq->flags & EQ_TYPEMASK) {
2259 	case EQ_CTRL:
2260 		rc = ctrl_eq_alloc(sc, eq);
2261 		break;
2262 
2263 	case EQ_ETH:
2264 		rc = eth_eq_alloc(sc, pi, eq);
2265 		break;
2266 
2267 #ifdef TCP_OFFLOAD
2268 	case EQ_OFLD:
2269 		rc = ofld_eq_alloc(sc, pi, eq);
2270 		break;
2271 #endif
2272 
2273 	default:
2274 		panic("%s: invalid eq type %d.", __func__,
2275 		    eq->flags & EQ_TYPEMASK);
2276 	}
2277 	if (rc != 0) {
2278 		device_printf(sc->dev,
2279 		    "failed to allocate egress queue(%d): %d",
2280 		    eq->flags & EQ_TYPEMASK, rc);
2281 	}
2282 
2283 	eq->tx_callout.c_cpu = eq->cntxt_id % mp_ncpus;
2284 
2285 	if (isset(&eq->doorbells, DOORBELL_UDB) ||
2286 	    isset(&eq->doorbells, DOORBELL_UDBWC) ||
2287 	    isset(&eq->doorbells, DOORBELL_WRWC)) {
2288 		uint32_t s_qpp = sc->sge.s_qpp;
2289 		uint32_t mask = (1 << s_qpp) - 1;
2290 		volatile uint8_t *udb;
2291 
2292 		udb = sc->udbs_base + UDBS_DB_OFFSET;
2293 		udb += (eq->cntxt_id >> s_qpp) << PAGE_SHIFT;	/* pg offset */
2294 		eq->udb_qid = eq->cntxt_id & mask;		/* id in page */
2295 		if (eq->udb_qid > PAGE_SIZE / UDBS_SEG_SIZE)
2296 	    		clrbit(&eq->doorbells, DOORBELL_WRWC);
2297 		else {
2298 			udb += eq->udb_qid << UDBS_SEG_SHIFT;	/* seg offset */
2299 			eq->udb_qid = 0;
2300 		}
2301 		eq->udb = (volatile void *)udb;
2302 	}
2303 
2304 	return (rc);
2305 }
2306 
2307 static int
2308 free_eq(struct adapter *sc, struct sge_eq *eq)
2309 {
2310 	int rc;
2311 
2312 	if (eq->flags & EQ_ALLOCATED) {
2313 		switch (eq->flags & EQ_TYPEMASK) {
2314 		case EQ_CTRL:
2315 			rc = -t4_ctrl_eq_free(sc, sc->mbox, sc->pf, 0,
2316 			    eq->cntxt_id);
2317 			break;
2318 
2319 		case EQ_ETH:
2320 			rc = -t4_eth_eq_free(sc, sc->mbox, sc->pf, 0,
2321 			    eq->cntxt_id);
2322 			break;
2323 
2324 #ifdef TCP_OFFLOAD
2325 		case EQ_OFLD:
2326 			rc = -t4_ofld_eq_free(sc, sc->mbox, sc->pf, 0,
2327 			    eq->cntxt_id);
2328 			break;
2329 #endif
2330 
2331 		default:
2332 			panic("%s: invalid eq type %d.", __func__,
2333 			    eq->flags & EQ_TYPEMASK);
2334 		}
2335 		if (rc != 0) {
2336 			device_printf(sc->dev,
2337 			    "failed to free egress queue (%d): %d\n",
2338 			    eq->flags & EQ_TYPEMASK, rc);
2339 			return (rc);
2340 		}
2341 		eq->flags &= ~EQ_ALLOCATED;
2342 	}
2343 
2344 	free_ring(sc, eq->desc_tag, eq->desc_map, eq->ba, eq->desc);
2345 
2346 	if (mtx_initialized(&eq->eq_lock))
2347 		mtx_destroy(&eq->eq_lock);
2348 
2349 	bzero(eq, sizeof(*eq));
2350 	return (0);
2351 }
2352 
2353 static int
2354 alloc_wrq(struct adapter *sc, struct port_info *pi, struct sge_wrq *wrq,
2355     struct sysctl_oid *oid)
2356 {
2357 	int rc;
2358 	struct sysctl_ctx_list *ctx = pi ? &pi->ctx : &sc->ctx;
2359 	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
2360 
2361 	rc = alloc_eq(sc, pi, &wrq->eq);
2362 	if (rc)
2363 		return (rc);
2364 
2365 	wrq->adapter = sc;
2366 	STAILQ_INIT(&wrq->wr_list);
2367 
2368 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
2369 	    &wrq->eq.cntxt_id, 0, "SGE context id of the queue");
2370 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cidx",
2371 	    CTLTYPE_INT | CTLFLAG_RD, &wrq->eq.cidx, 0, sysctl_uint16, "I",
2372 	    "consumer index");
2373 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pidx",
2374 	    CTLTYPE_INT | CTLFLAG_RD, &wrq->eq.pidx, 0, sysctl_uint16, "I",
2375 	    "producer index");
2376 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "tx_wrs", CTLFLAG_RD,
2377 	    &wrq->tx_wrs, "# of work requests");
2378 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "no_desc", CTLFLAG_RD,
2379 	    &wrq->no_desc, 0,
2380 	    "# of times queue ran out of hardware descriptors");
2381 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "unstalled", CTLFLAG_RD,
2382 	    &wrq->eq.unstalled, 0, "# of times queue recovered after stall");
2383 
2384 
2385 	return (rc);
2386 }
2387 
2388 static int
2389 free_wrq(struct adapter *sc, struct sge_wrq *wrq)
2390 {
2391 	int rc;
2392 
2393 	rc = free_eq(sc, &wrq->eq);
2394 	if (rc)
2395 		return (rc);
2396 
2397 	bzero(wrq, sizeof(*wrq));
2398 	return (0);
2399 }
2400 
2401 static int
2402 alloc_txq(struct port_info *pi, struct sge_txq *txq, int idx,
2403     struct sysctl_oid *oid)
2404 {
2405 	int rc;
2406 	struct adapter *sc = pi->adapter;
2407 	struct sge_eq *eq = &txq->eq;
2408 	char name[16];
2409 	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
2410 
2411 	rc = alloc_eq(sc, pi, eq);
2412 	if (rc)
2413 		return (rc);
2414 
2415 	txq->ifp = pi->ifp;
2416 
2417 	txq->sdesc = malloc(eq->cap * sizeof(struct tx_sdesc), M_CXGBE,
2418 	    M_ZERO | M_WAITOK);
2419 	txq->br = buf_ring_alloc(eq->qsize, M_CXGBE, M_WAITOK, &eq->eq_lock);
2420 
2421 	rc = bus_dma_tag_create(sc->dmat, 1, 0, BUS_SPACE_MAXADDR,
2422 	    BUS_SPACE_MAXADDR, NULL, NULL, 64 * 1024, TX_SGL_SEGS,
2423 	    BUS_SPACE_MAXSIZE, BUS_DMA_ALLOCNOW, NULL, NULL, &txq->tx_tag);
2424 	if (rc != 0) {
2425 		device_printf(sc->dev,
2426 		    "failed to create tx DMA tag: %d\n", rc);
2427 		return (rc);
2428 	}
2429 
2430 	/*
2431 	 * We can stuff ~10 frames in an 8-descriptor txpkts WR (8 is the SGE
2432 	 * limit for any WR).  txq->no_dmamap events shouldn't occur if maps is
2433 	 * sized for the worst case.
2434 	 */
2435 	rc = t4_alloc_tx_maps(&txq->txmaps, txq->tx_tag, eq->qsize * 10 / 8,
2436 	    M_WAITOK);
2437 	if (rc != 0) {
2438 		device_printf(sc->dev, "failed to setup tx DMA maps: %d\n", rc);
2439 		return (rc);
2440 	}
2441 
2442 	snprintf(name, sizeof(name), "%d", idx);
2443 	oid = SYSCTL_ADD_NODE(&pi->ctx, children, OID_AUTO, name, CTLFLAG_RD,
2444 	    NULL, "tx queue");
2445 	children = SYSCTL_CHILDREN(oid);
2446 
2447 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
2448 	    &eq->cntxt_id, 0, "SGE context id of the queue");
2449 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "cidx",
2450 	    CTLTYPE_INT | CTLFLAG_RD, &eq->cidx, 0, sysctl_uint16, "I",
2451 	    "consumer index");
2452 	SYSCTL_ADD_PROC(&pi->ctx, children, OID_AUTO, "pidx",
2453 	    CTLTYPE_INT | CTLFLAG_RD, &eq->pidx, 0, sysctl_uint16, "I",
2454 	    "producer index");
2455 
2456 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txcsum", CTLFLAG_RD,
2457 	    &txq->txcsum, "# of times hardware assisted with checksum");
2458 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "vlan_insertion",
2459 	    CTLFLAG_RD, &txq->vlan_insertion,
2460 	    "# of times hardware inserted 802.1Q tag");
2461 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "tso_wrs", CTLFLAG_RD,
2462 	    &txq->tso_wrs, "# of TSO work requests");
2463 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "imm_wrs", CTLFLAG_RD,
2464 	    &txq->imm_wrs, "# of work requests with immediate data");
2465 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "sgl_wrs", CTLFLAG_RD,
2466 	    &txq->sgl_wrs, "# of work requests with direct SGL");
2467 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkt_wrs", CTLFLAG_RD,
2468 	    &txq->txpkt_wrs, "# of txpkt work requests (one pkt/WR)");
2469 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkts_wrs", CTLFLAG_RD,
2470 	    &txq->txpkts_wrs, "# of txpkts work requests (multiple pkts/WR)");
2471 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "txpkts_pkts", CTLFLAG_RD,
2472 	    &txq->txpkts_pkts, "# of frames tx'd using txpkts work requests");
2473 
2474 	SYSCTL_ADD_UQUAD(&pi->ctx, children, OID_AUTO, "br_drops", CTLFLAG_RD,
2475 	    &txq->br->br_drops, "# of drops in the buf_ring for this queue");
2476 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "no_dmamap", CTLFLAG_RD,
2477 	    &txq->no_dmamap, 0, "# of times txq ran out of DMA maps");
2478 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "no_desc", CTLFLAG_RD,
2479 	    &txq->no_desc, 0, "# of times txq ran out of hardware descriptors");
2480 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "egr_update", CTLFLAG_RD,
2481 	    &eq->egr_update, 0, "egress update notifications from the SGE");
2482 	SYSCTL_ADD_UINT(&pi->ctx, children, OID_AUTO, "unstalled", CTLFLAG_RD,
2483 	    &eq->unstalled, 0, "# of times txq recovered after stall");
2484 
2485 	return (rc);
2486 }
2487 
2488 static int
2489 free_txq(struct port_info *pi, struct sge_txq *txq)
2490 {
2491 	int rc;
2492 	struct adapter *sc = pi->adapter;
2493 	struct sge_eq *eq = &txq->eq;
2494 
2495 	rc = free_eq(sc, eq);
2496 	if (rc)
2497 		return (rc);
2498 
2499 	free(txq->sdesc, M_CXGBE);
2500 
2501 	if (txq->txmaps.maps)
2502 		t4_free_tx_maps(&txq->txmaps, txq->tx_tag);
2503 
2504 	buf_ring_free(txq->br, M_CXGBE);
2505 
2506 	if (txq->tx_tag)
2507 		bus_dma_tag_destroy(txq->tx_tag);
2508 
2509 	bzero(txq, sizeof(*txq));
2510 	return (0);
2511 }
2512 
2513 static void
2514 oneseg_dma_callback(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2515 {
2516 	bus_addr_t *ba = arg;
2517 
2518 	KASSERT(nseg == 1,
2519 	    ("%s meant for single segment mappings only.", __func__));
2520 
2521 	*ba = error ? 0 : segs->ds_addr;
2522 }
2523 
2524 static inline bool
2525 is_new_response(const struct sge_iq *iq, struct rsp_ctrl **ctrl)
2526 {
2527 	*ctrl = (void *)((uintptr_t)iq->cdesc +
2528 	    (iq->esize - sizeof(struct rsp_ctrl)));
2529 
2530 	return (((*ctrl)->u.type_gen >> S_RSPD_GEN) == iq->gen);
2531 }
2532 
2533 static inline void
2534 iq_next(struct sge_iq *iq)
2535 {
2536 	iq->cdesc = (void *) ((uintptr_t)iq->cdesc + iq->esize);
2537 	if (__predict_false(++iq->cidx == iq->qsize - 1)) {
2538 		iq->cidx = 0;
2539 		iq->gen ^= 1;
2540 		iq->cdesc = iq->desc;
2541 	}
2542 }
2543 
2544 #define FL_HW_IDX(x) ((x) >> 3)
2545 static inline void
2546 ring_fl_db(struct adapter *sc, struct sge_fl *fl)
2547 {
2548 	int ndesc = fl->pending / 8;
2549 	uint32_t v;
2550 
2551 	if (FL_HW_IDX(fl->pidx) == FL_HW_IDX(fl->cidx))
2552 		ndesc--;	/* hold back one credit */
2553 
2554 	if (ndesc <= 0)
2555 		return;		/* nothing to do */
2556 
2557 	v = F_DBPRIO | V_QID(fl->cntxt_id) | V_PIDX(ndesc);
2558 	if (is_t5(sc))
2559 		v |= F_DBTYPE;
2560 
2561 	wmb();
2562 
2563 	t4_write_reg(sc, MYPF_REG(A_SGE_PF_KDOORBELL), v);
2564 	fl->pending -= ndesc * 8;
2565 }
2566 
2567 /*
2568  * Fill up the freelist by upto nbufs and maybe ring its doorbell.
2569  *
2570  * Returns non-zero to indicate that it should be added to the list of starving
2571  * freelists.
2572  */
2573 static int
2574 refill_fl(struct adapter *sc, struct sge_fl *fl, int nbufs)
2575 {
2576 	__be64 *d = &fl->desc[fl->pidx];
2577 	struct fl_sdesc *sd = &fl->sdesc[fl->pidx];
2578 	bus_dma_tag_t tag;
2579 	bus_addr_t pa;
2580 	caddr_t cl;
2581 	int rc;
2582 
2583 	FL_LOCK_ASSERT_OWNED(fl);
2584 
2585 	if (nbufs > fl->needed)
2586 		nbufs = fl->needed;
2587 
2588 	while (nbufs--) {
2589 
2590 		if (sd->cl != NULL) {
2591 
2592 			/*
2593 			 * This happens when a frame small enough to fit
2594 			 * entirely in an mbuf was received in cl last time.
2595 			 * We'd held on to cl and can reuse it now.  Note that
2596 			 * we reuse a cluster of the old size if fl->tag_idx is
2597 			 * no longer the same as sd->tag_idx.
2598 			 */
2599 
2600 			KASSERT(*d == sd->ba_tag,
2601 			    ("%s: recyling problem at pidx %d",
2602 			    __func__, fl->pidx));
2603 
2604 			d++;
2605 			goto recycled;
2606 		}
2607 
2608 
2609 		if (fl->tag_idx != sd->tag_idx) {
2610 			bus_dmamap_t map;
2611 			bus_dma_tag_t newtag = fl->tag[fl->tag_idx];
2612 			bus_dma_tag_t oldtag = fl->tag[sd->tag_idx];
2613 
2614 			/*
2615 			 * An MTU change can get us here.  Discard the old map
2616 			 * which was created with the old tag, but only if
2617 			 * we're able to get a new one.
2618 			 */
2619 			rc = bus_dmamap_create(newtag, 0, &map);
2620 			if (rc == 0) {
2621 				bus_dmamap_destroy(oldtag, sd->map);
2622 				sd->map = map;
2623 				sd->tag_idx = fl->tag_idx;
2624 			}
2625 		}
2626 
2627 		tag = fl->tag[sd->tag_idx];
2628 
2629 		cl = m_cljget(NULL, M_NOWAIT, FL_BUF_SIZE(sd->tag_idx));
2630 		if (cl == NULL)
2631 			break;
2632 
2633 		rc = bus_dmamap_load(tag, sd->map, cl, FL_BUF_SIZE(sd->tag_idx),
2634 		    oneseg_dma_callback, &pa, 0);
2635 		if (rc != 0 || pa == 0) {
2636 			fl->dmamap_failed++;
2637 			uma_zfree(FL_BUF_ZONE(sd->tag_idx), cl);
2638 			break;
2639 		}
2640 
2641 		sd->cl = cl;
2642 		*d++ = htobe64(pa | sd->tag_idx);
2643 
2644 #ifdef INVARIANTS
2645 		sd->ba_tag = htobe64(pa | sd->tag_idx);
2646 #endif
2647 
2648 recycled:
2649 		/* sd->m is never recycled, should always be NULL */
2650 		KASSERT(sd->m == NULL, ("%s: stray mbuf", __func__));
2651 
2652 		sd->m = m_gethdr(M_NOWAIT, MT_NOINIT);
2653 		if (sd->m == NULL)
2654 			break;
2655 
2656 		fl->pending++;
2657 		fl->needed--;
2658 		sd++;
2659 		if (++fl->pidx == fl->cap) {
2660 			fl->pidx = 0;
2661 			sd = fl->sdesc;
2662 			d = fl->desc;
2663 		}
2664 	}
2665 
2666 	if (fl->pending >= 8)
2667 		ring_fl_db(sc, fl);
2668 
2669 	return (FL_RUNNING_LOW(fl) && !(fl->flags & FL_STARVING));
2670 }
2671 
2672 /*
2673  * Attempt to refill all starving freelists.
2674  */
2675 static void
2676 refill_sfl(void *arg)
2677 {
2678 	struct adapter *sc = arg;
2679 	struct sge_fl *fl, *fl_temp;
2680 
2681 	mtx_lock(&sc->sfl_lock);
2682 	TAILQ_FOREACH_SAFE(fl, &sc->sfl, link, fl_temp) {
2683 		FL_LOCK(fl);
2684 		refill_fl(sc, fl, 64);
2685 		if (FL_NOT_RUNNING_LOW(fl) || fl->flags & FL_DOOMED) {
2686 			TAILQ_REMOVE(&sc->sfl, fl, link);
2687 			fl->flags &= ~FL_STARVING;
2688 		}
2689 		FL_UNLOCK(fl);
2690 	}
2691 
2692 	if (!TAILQ_EMPTY(&sc->sfl))
2693 		callout_schedule(&sc->sfl_callout, hz / 5);
2694 	mtx_unlock(&sc->sfl_lock);
2695 }
2696 
2697 static int
2698 alloc_fl_sdesc(struct sge_fl *fl)
2699 {
2700 	struct fl_sdesc *sd;
2701 	bus_dma_tag_t tag;
2702 	int i, rc;
2703 
2704 	FL_LOCK_ASSERT_OWNED(fl);
2705 
2706 	fl->sdesc = malloc(fl->cap * sizeof(struct fl_sdesc), M_CXGBE,
2707 	    M_ZERO | M_WAITOK);
2708 
2709 	tag = fl->tag[fl->tag_idx];
2710 	sd = fl->sdesc;
2711 	for (i = 0; i < fl->cap; i++, sd++) {
2712 
2713 		sd->tag_idx = fl->tag_idx;
2714 		rc = bus_dmamap_create(tag, 0, &sd->map);
2715 		if (rc != 0)
2716 			goto failed;
2717 	}
2718 
2719 	return (0);
2720 failed:
2721 	while (--i >= 0) {
2722 		sd--;
2723 		bus_dmamap_destroy(tag, sd->map);
2724 		if (sd->m) {
2725 			m_init(sd->m, NULL, 0, M_NOWAIT, MT_DATA, 0);
2726 			m_free(sd->m);
2727 			sd->m = NULL;
2728 		}
2729 	}
2730 	KASSERT(sd == fl->sdesc, ("%s: EDOOFUS", __func__));
2731 
2732 	free(fl->sdesc, M_CXGBE);
2733 	fl->sdesc = NULL;
2734 
2735 	return (rc);
2736 }
2737 
2738 static void
2739 free_fl_sdesc(struct sge_fl *fl)
2740 {
2741 	struct fl_sdesc *sd;
2742 	int i;
2743 
2744 	FL_LOCK_ASSERT_OWNED(fl);
2745 
2746 	sd = fl->sdesc;
2747 	for (i = 0; i < fl->cap; i++, sd++) {
2748 
2749 		if (sd->m) {
2750 			m_init(sd->m, NULL, 0, M_NOWAIT, MT_DATA, 0);
2751 			m_free(sd->m);
2752 			sd->m = NULL;
2753 		}
2754 
2755 		if (sd->cl) {
2756 			bus_dmamap_unload(fl->tag[sd->tag_idx], sd->map);
2757 			uma_zfree(FL_BUF_ZONE(sd->tag_idx), sd->cl);
2758 			sd->cl = NULL;
2759 		}
2760 
2761 		bus_dmamap_destroy(fl->tag[sd->tag_idx], sd->map);
2762 	}
2763 
2764 	free(fl->sdesc, M_CXGBE);
2765 	fl->sdesc = NULL;
2766 }
2767 
2768 int
2769 t4_alloc_tx_maps(struct tx_maps *txmaps, bus_dma_tag_t tx_tag, int count,
2770     int flags)
2771 {
2772 	struct tx_map *txm;
2773 	int i, rc;
2774 
2775 	txmaps->map_total = txmaps->map_avail = count;
2776 	txmaps->map_cidx = txmaps->map_pidx = 0;
2777 
2778 	txmaps->maps = malloc(count * sizeof(struct tx_map), M_CXGBE,
2779 	    M_ZERO | flags);
2780 
2781 	txm = txmaps->maps;
2782 	for (i = 0; i < count; i++, txm++) {
2783 		rc = bus_dmamap_create(tx_tag, 0, &txm->map);
2784 		if (rc != 0)
2785 			goto failed;
2786 	}
2787 
2788 	return (0);
2789 failed:
2790 	while (--i >= 0) {
2791 		txm--;
2792 		bus_dmamap_destroy(tx_tag, txm->map);
2793 	}
2794 	KASSERT(txm == txmaps->maps, ("%s: EDOOFUS", __func__));
2795 
2796 	free(txmaps->maps, M_CXGBE);
2797 	txmaps->maps = NULL;
2798 
2799 	return (rc);
2800 }
2801 
2802 void
2803 t4_free_tx_maps(struct tx_maps *txmaps, bus_dma_tag_t tx_tag)
2804 {
2805 	struct tx_map *txm;
2806 	int i;
2807 
2808 	txm = txmaps->maps;
2809 	for (i = 0; i < txmaps->map_total; i++, txm++) {
2810 
2811 		if (txm->m) {
2812 			bus_dmamap_unload(tx_tag, txm->map);
2813 			m_freem(txm->m);
2814 			txm->m = NULL;
2815 		}
2816 
2817 		bus_dmamap_destroy(tx_tag, txm->map);
2818 	}
2819 
2820 	free(txmaps->maps, M_CXGBE);
2821 	txmaps->maps = NULL;
2822 }
2823 
2824 /*
2825  * We'll do immediate data tx for non-TSO, but only when not coalescing.  We're
2826  * willing to use upto 2 hardware descriptors which means a maximum of 96 bytes
2827  * of immediate data.
2828  */
2829 #define IMM_LEN ( \
2830       2 * EQ_ESIZE \
2831     - sizeof(struct fw_eth_tx_pkt_wr) \
2832     - sizeof(struct cpl_tx_pkt_core))
2833 
2834 /*
2835  * Returns non-zero on failure, no need to cleanup anything in that case.
2836  *
2837  * Note 1: We always try to defrag the mbuf if required and return EFBIG only
2838  * if the resulting chain still won't fit in a tx descriptor.
2839  *
2840  * Note 2: We'll pullup the mbuf chain if TSO is requested and the first mbuf
2841  * does not have the TCP header in it.
2842  */
2843 static int
2844 get_pkt_sgl(struct sge_txq *txq, struct mbuf **fp, struct sgl *sgl,
2845     int sgl_only)
2846 {
2847 	struct mbuf *m = *fp;
2848 	struct tx_maps *txmaps;
2849 	struct tx_map *txm;
2850 	int rc, defragged = 0, n;
2851 
2852 	TXQ_LOCK_ASSERT_OWNED(txq);
2853 
2854 	if (m->m_pkthdr.tso_segsz)
2855 		sgl_only = 1;	/* Do not allow immediate data with LSO */
2856 
2857 start:	sgl->nsegs = 0;
2858 
2859 	if (m->m_pkthdr.len <= IMM_LEN && !sgl_only)
2860 		return (0);	/* nsegs = 0 tells caller to use imm. tx */
2861 
2862 	txmaps = &txq->txmaps;
2863 	if (txmaps->map_avail == 0) {
2864 		txq->no_dmamap++;
2865 		return (ENOMEM);
2866 	}
2867 	txm = &txmaps->maps[txmaps->map_pidx];
2868 
2869 	if (m->m_pkthdr.tso_segsz && m->m_len < 50) {
2870 		*fp = m_pullup(m, 50);
2871 		m = *fp;
2872 		if (m == NULL)
2873 			return (ENOBUFS);
2874 	}
2875 
2876 	rc = bus_dmamap_load_mbuf_sg(txq->tx_tag, txm->map, m, sgl->seg,
2877 	    &sgl->nsegs, BUS_DMA_NOWAIT);
2878 	if (rc == EFBIG && defragged == 0) {
2879 		m = m_defrag(m, M_NOWAIT);
2880 		if (m == NULL)
2881 			return (EFBIG);
2882 
2883 		defragged = 1;
2884 		*fp = m;
2885 		goto start;
2886 	}
2887 	if (rc != 0)
2888 		return (rc);
2889 
2890 	txm->m = m;
2891 	txmaps->map_avail--;
2892 	if (++txmaps->map_pidx == txmaps->map_total)
2893 		txmaps->map_pidx = 0;
2894 
2895 	KASSERT(sgl->nsegs > 0 && sgl->nsegs <= TX_SGL_SEGS,
2896 	    ("%s: bad DMA mapping (%d segments)", __func__, sgl->nsegs));
2897 
2898 	/*
2899 	 * Store the # of flits required to hold this frame's SGL in nflits.  An
2900 	 * SGL has a (ULPTX header + len0, addr0) tuple optionally followed by
2901 	 * multiple (len0 + len1, addr0, addr1) tuples.  If addr1 is not used
2902 	 * then len1 must be set to 0.
2903 	 */
2904 	n = sgl->nsegs - 1;
2905 	sgl->nflits = (3 * n) / 2 + (n & 1) + 2;
2906 
2907 	return (0);
2908 }
2909 
2910 
2911 /*
2912  * Releases all the txq resources used up in the specified sgl.
2913  */
2914 static int
2915 free_pkt_sgl(struct sge_txq *txq, struct sgl *sgl)
2916 {
2917 	struct tx_maps *txmaps;
2918 	struct tx_map *txm;
2919 
2920 	TXQ_LOCK_ASSERT_OWNED(txq);
2921 
2922 	if (sgl->nsegs == 0)
2923 		return (0);	/* didn't use any map */
2924 
2925 	txmaps = &txq->txmaps;
2926 
2927 	/* 1 pkt uses exactly 1 map, back it out */
2928 
2929 	txmaps->map_avail++;
2930 	if (txmaps->map_pidx > 0)
2931 		txmaps->map_pidx--;
2932 	else
2933 		txmaps->map_pidx = txmaps->map_total - 1;
2934 
2935 	txm = &txmaps->maps[txmaps->map_pidx];
2936 	bus_dmamap_unload(txq->tx_tag, txm->map);
2937 	txm->m = NULL;
2938 
2939 	return (0);
2940 }
2941 
2942 static int
2943 write_txpkt_wr(struct port_info *pi, struct sge_txq *txq, struct mbuf *m,
2944     struct sgl *sgl)
2945 {
2946 	struct sge_eq *eq = &txq->eq;
2947 	struct fw_eth_tx_pkt_wr *wr;
2948 	struct cpl_tx_pkt_core *cpl;
2949 	uint32_t ctrl;	/* used in many unrelated places */
2950 	uint64_t ctrl1;
2951 	int nflits, ndesc, pktlen;
2952 	struct tx_sdesc *txsd;
2953 	caddr_t dst;
2954 
2955 	TXQ_LOCK_ASSERT_OWNED(txq);
2956 
2957 	pktlen = m->m_pkthdr.len;
2958 
2959 	/*
2960 	 * Do we have enough flits to send this frame out?
2961 	 */
2962 	ctrl = sizeof(struct cpl_tx_pkt_core);
2963 	if (m->m_pkthdr.tso_segsz) {
2964 		nflits = TXPKT_LSO_WR_HDR;
2965 		ctrl += sizeof(struct cpl_tx_pkt_lso_core);
2966 	} else
2967 		nflits = TXPKT_WR_HDR;
2968 	if (sgl->nsegs > 0)
2969 		nflits += sgl->nflits;
2970 	else {
2971 		nflits += howmany(pktlen, 8);
2972 		ctrl += pktlen;
2973 	}
2974 	ndesc = howmany(nflits, 8);
2975 	if (ndesc > eq->avail)
2976 		return (ENOMEM);
2977 
2978 	/* Firmware work request header */
2979 	wr = (void *)&eq->desc[eq->pidx];
2980 	wr->op_immdlen = htobe32(V_FW_WR_OP(FW_ETH_TX_PKT_WR) |
2981 	    V_FW_ETH_TX_PKT_WR_IMMDLEN(ctrl));
2982 	ctrl = V_FW_WR_LEN16(howmany(nflits, 2));
2983 	if (eq->avail == ndesc) {
2984 		if (!(eq->flags & EQ_CRFLUSHED)) {
2985 			ctrl |= F_FW_WR_EQUEQ | F_FW_WR_EQUIQ;
2986 			eq->flags |= EQ_CRFLUSHED;
2987 		}
2988 		eq->flags |= EQ_STALLED;
2989 	}
2990 
2991 	wr->equiq_to_len16 = htobe32(ctrl);
2992 	wr->r3 = 0;
2993 
2994 	if (m->m_pkthdr.tso_segsz) {
2995 		struct cpl_tx_pkt_lso_core *lso = (void *)(wr + 1);
2996 		struct ether_header *eh;
2997 		void *l3hdr;
2998 #if defined(INET) || defined(INET6)
2999 		struct tcphdr *tcp;
3000 #endif
3001 		uint16_t eh_type;
3002 
3003 		ctrl = V_LSO_OPCODE(CPL_TX_PKT_LSO) | F_LSO_FIRST_SLICE |
3004 		    F_LSO_LAST_SLICE;
3005 
3006 		eh = mtod(m, struct ether_header *);
3007 		eh_type = ntohs(eh->ether_type);
3008 		if (eh_type == ETHERTYPE_VLAN) {
3009 			struct ether_vlan_header *evh = (void *)eh;
3010 
3011 			ctrl |= V_LSO_ETHHDR_LEN(1);
3012 			l3hdr = evh + 1;
3013 			eh_type = ntohs(evh->evl_proto);
3014 		} else
3015 			l3hdr = eh + 1;
3016 
3017 		switch (eh_type) {
3018 #ifdef INET6
3019 		case ETHERTYPE_IPV6:
3020 		{
3021 			struct ip6_hdr *ip6 = l3hdr;
3022 
3023 			/*
3024 			 * XXX-BZ For now we do not pretend to support
3025 			 * IPv6 extension headers.
3026 			 */
3027 			KASSERT(ip6->ip6_nxt == IPPROTO_TCP, ("%s: CSUM_TSO "
3028 			    "with ip6_nxt != TCP: %u", __func__, ip6->ip6_nxt));
3029 			tcp = (struct tcphdr *)(ip6 + 1);
3030 			ctrl |= F_LSO_IPV6;
3031 			ctrl |= V_LSO_IPHDR_LEN(sizeof(*ip6) >> 2) |
3032 			    V_LSO_TCPHDR_LEN(tcp->th_off);
3033 			break;
3034 		}
3035 #endif
3036 #ifdef INET
3037 		case ETHERTYPE_IP:
3038 		{
3039 			struct ip *ip = l3hdr;
3040 
3041 			tcp = (void *)((uintptr_t)ip + ip->ip_hl * 4);
3042 			ctrl |= V_LSO_IPHDR_LEN(ip->ip_hl) |
3043 			    V_LSO_TCPHDR_LEN(tcp->th_off);
3044 			break;
3045 		}
3046 #endif
3047 		default:
3048 			panic("%s: CSUM_TSO but no supported IP version "
3049 			    "(0x%04x)", __func__, eh_type);
3050 		}
3051 
3052 		lso->lso_ctrl = htobe32(ctrl);
3053 		lso->ipid_ofst = htobe16(0);
3054 		lso->mss = htobe16(m->m_pkthdr.tso_segsz);
3055 		lso->seqno_offset = htobe32(0);
3056 		lso->len = htobe32(pktlen);
3057 
3058 		cpl = (void *)(lso + 1);
3059 
3060 		txq->tso_wrs++;
3061 	} else
3062 		cpl = (void *)(wr + 1);
3063 
3064 	/* Checksum offload */
3065 	ctrl1 = 0;
3066 	if (!(m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TSO)))
3067 		ctrl1 |= F_TXPKT_IPCSUM_DIS;
3068 	if (!(m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_UDP_IPV6 |
3069 	    CSUM_TCP_IPV6 | CSUM_TSO)))
3070 		ctrl1 |= F_TXPKT_L4CSUM_DIS;
3071 	if (m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP |
3072 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6 | CSUM_TSO))
3073 		txq->txcsum++;	/* some hardware assistance provided */
3074 
3075 	/* VLAN tag insertion */
3076 	if (m->m_flags & M_VLANTAG) {
3077 		ctrl1 |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(m->m_pkthdr.ether_vtag);
3078 		txq->vlan_insertion++;
3079 	}
3080 
3081 	/* CPL header */
3082 	cpl->ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT) |
3083 	    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(pi->adapter->pf));
3084 	cpl->pack = 0;
3085 	cpl->len = htobe16(pktlen);
3086 	cpl->ctrl1 = htobe64(ctrl1);
3087 
3088 	/* Software descriptor */
3089 	txsd = &txq->sdesc[eq->pidx];
3090 	txsd->desc_used = ndesc;
3091 
3092 	eq->pending += ndesc;
3093 	eq->avail -= ndesc;
3094 	eq->pidx += ndesc;
3095 	if (eq->pidx >= eq->cap)
3096 		eq->pidx -= eq->cap;
3097 
3098 	/* SGL */
3099 	dst = (void *)(cpl + 1);
3100 	if (sgl->nsegs > 0) {
3101 		txsd->credits = 1;
3102 		txq->sgl_wrs++;
3103 		write_sgl_to_txd(eq, sgl, &dst);
3104 	} else {
3105 		txsd->credits = 0;
3106 		txq->imm_wrs++;
3107 		for (; m; m = m->m_next) {
3108 			copy_to_txd(eq, mtod(m, caddr_t), &dst, m->m_len);
3109 #ifdef INVARIANTS
3110 			pktlen -= m->m_len;
3111 #endif
3112 		}
3113 #ifdef INVARIANTS
3114 		KASSERT(pktlen == 0, ("%s: %d bytes left.", __func__, pktlen));
3115 #endif
3116 
3117 	}
3118 
3119 	txq->txpkt_wrs++;
3120 	return (0);
3121 }
3122 
3123 /*
3124  * Returns 0 to indicate that m has been accepted into a coalesced tx work
3125  * request.  It has either been folded into txpkts or txpkts was flushed and m
3126  * has started a new coalesced work request (as the first frame in a fresh
3127  * txpkts).
3128  *
3129  * Returns non-zero to indicate a failure - caller is responsible for
3130  * transmitting m, if there was anything in txpkts it has been flushed.
3131  */
3132 static int
3133 add_to_txpkts(struct port_info *pi, struct sge_txq *txq, struct txpkts *txpkts,
3134     struct mbuf *m, struct sgl *sgl)
3135 {
3136 	struct sge_eq *eq = &txq->eq;
3137 	int can_coalesce;
3138 	struct tx_sdesc *txsd;
3139 	int flits;
3140 
3141 	TXQ_LOCK_ASSERT_OWNED(txq);
3142 
3143 	KASSERT(sgl->nsegs, ("%s: can't coalesce imm data", __func__));
3144 
3145 	if (txpkts->npkt > 0) {
3146 		flits = TXPKTS_PKT_HDR + sgl->nflits;
3147 		can_coalesce = m->m_pkthdr.tso_segsz == 0 &&
3148 		    txpkts->nflits + flits <= TX_WR_FLITS &&
3149 		    txpkts->nflits + flits <= eq->avail * 8 &&
3150 		    txpkts->plen + m->m_pkthdr.len < 65536;
3151 
3152 		if (can_coalesce) {
3153 			txpkts->npkt++;
3154 			txpkts->nflits += flits;
3155 			txpkts->plen += m->m_pkthdr.len;
3156 
3157 			txsd = &txq->sdesc[eq->pidx];
3158 			txsd->credits++;
3159 
3160 			return (0);
3161 		}
3162 
3163 		/*
3164 		 * Couldn't coalesce m into txpkts.  The first order of business
3165 		 * is to send txpkts on its way.  Then we'll revisit m.
3166 		 */
3167 		write_txpkts_wr(txq, txpkts);
3168 	}
3169 
3170 	/*
3171 	 * Check if we can start a new coalesced tx work request with m as
3172 	 * the first packet in it.
3173 	 */
3174 
3175 	KASSERT(txpkts->npkt == 0, ("%s: txpkts not empty", __func__));
3176 
3177 	flits = TXPKTS_WR_HDR + sgl->nflits;
3178 	can_coalesce = m->m_pkthdr.tso_segsz == 0 &&
3179 	    flits <= eq->avail * 8 && flits <= TX_WR_FLITS;
3180 
3181 	if (can_coalesce == 0)
3182 		return (EINVAL);
3183 
3184 	/*
3185 	 * Start a fresh coalesced tx WR with m as the first frame in it.
3186 	 */
3187 	txpkts->npkt = 1;
3188 	txpkts->nflits = flits;
3189 	txpkts->flitp = &eq->desc[eq->pidx].flit[2];
3190 	txpkts->plen = m->m_pkthdr.len;
3191 
3192 	txsd = &txq->sdesc[eq->pidx];
3193 	txsd->credits = 1;
3194 
3195 	return (0);
3196 }
3197 
3198 /*
3199  * Note that write_txpkts_wr can never run out of hardware descriptors (but
3200  * write_txpkt_wr can).  add_to_txpkts ensures that a frame is accepted for
3201  * coalescing only if sufficient hardware descriptors are available.
3202  */
3203 static void
3204 write_txpkts_wr(struct sge_txq *txq, struct txpkts *txpkts)
3205 {
3206 	struct sge_eq *eq = &txq->eq;
3207 	struct fw_eth_tx_pkts_wr *wr;
3208 	struct tx_sdesc *txsd;
3209 	uint32_t ctrl;
3210 	int ndesc;
3211 
3212 	TXQ_LOCK_ASSERT_OWNED(txq);
3213 
3214 	ndesc = howmany(txpkts->nflits, 8);
3215 
3216 	wr = (void *)&eq->desc[eq->pidx];
3217 	wr->op_pkd = htobe32(V_FW_WR_OP(FW_ETH_TX_PKTS_WR));
3218 	ctrl = V_FW_WR_LEN16(howmany(txpkts->nflits, 2));
3219 	if (eq->avail == ndesc) {
3220 		if (!(eq->flags & EQ_CRFLUSHED)) {
3221 			ctrl |= F_FW_WR_EQUEQ | F_FW_WR_EQUIQ;
3222 			eq->flags |= EQ_CRFLUSHED;
3223 		}
3224 		eq->flags |= EQ_STALLED;
3225 	}
3226 	wr->equiq_to_len16 = htobe32(ctrl);
3227 	wr->plen = htobe16(txpkts->plen);
3228 	wr->npkt = txpkts->npkt;
3229 	wr->r3 = wr->type = 0;
3230 
3231 	/* Everything else already written */
3232 
3233 	txsd = &txq->sdesc[eq->pidx];
3234 	txsd->desc_used = ndesc;
3235 
3236 	KASSERT(eq->avail >= ndesc, ("%s: out of descriptors", __func__));
3237 
3238 	eq->pending += ndesc;
3239 	eq->avail -= ndesc;
3240 	eq->pidx += ndesc;
3241 	if (eq->pidx >= eq->cap)
3242 		eq->pidx -= eq->cap;
3243 
3244 	txq->txpkts_pkts += txpkts->npkt;
3245 	txq->txpkts_wrs++;
3246 	txpkts->npkt = 0;	/* emptied */
3247 }
3248 
3249 static inline void
3250 write_ulp_cpl_sgl(struct port_info *pi, struct sge_txq *txq,
3251     struct txpkts *txpkts, struct mbuf *m, struct sgl *sgl)
3252 {
3253 	struct ulp_txpkt *ulpmc;
3254 	struct ulptx_idata *ulpsc;
3255 	struct cpl_tx_pkt_core *cpl;
3256 	struct sge_eq *eq = &txq->eq;
3257 	uintptr_t flitp, start, end;
3258 	uint64_t ctrl;
3259 	caddr_t dst;
3260 
3261 	KASSERT(txpkts->npkt > 0, ("%s: txpkts is empty", __func__));
3262 
3263 	start = (uintptr_t)eq->desc;
3264 	end = (uintptr_t)eq->spg;
3265 
3266 	/* Checksum offload */
3267 	ctrl = 0;
3268 	if (!(m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TSO)))
3269 		ctrl |= F_TXPKT_IPCSUM_DIS;
3270 	if (!(m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_UDP_IPV6 |
3271 	    CSUM_TCP_IPV6 | CSUM_TSO)))
3272 		ctrl |= F_TXPKT_L4CSUM_DIS;
3273 	if (m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP |
3274 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6 | CSUM_TSO))
3275 		txq->txcsum++;	/* some hardware assistance provided */
3276 
3277 	/* VLAN tag insertion */
3278 	if (m->m_flags & M_VLANTAG) {
3279 		ctrl |= F_TXPKT_VLAN_VLD | V_TXPKT_VLAN(m->m_pkthdr.ether_vtag);
3280 		txq->vlan_insertion++;
3281 	}
3282 
3283 	/*
3284 	 * The previous packet's SGL must have ended at a 16 byte boundary (this
3285 	 * is required by the firmware/hardware).  It follows that flitp cannot
3286 	 * wrap around between the ULPTX master command and ULPTX subcommand (8
3287 	 * bytes each), and that it can not wrap around in the middle of the
3288 	 * cpl_tx_pkt_core either.
3289 	 */
3290 	flitp = (uintptr_t)txpkts->flitp;
3291 	KASSERT((flitp & 0xf) == 0,
3292 	    ("%s: last SGL did not end at 16 byte boundary: %p",
3293 	    __func__, txpkts->flitp));
3294 
3295 	/* ULP master command */
3296 	ulpmc = (void *)flitp;
3297 	ulpmc->cmd_dest = htonl(V_ULPTX_CMD(ULP_TX_PKT) | V_ULP_TXPKT_DEST(0) |
3298 	    V_ULP_TXPKT_FID(eq->iqid));
3299 	ulpmc->len = htonl(howmany(sizeof(*ulpmc) + sizeof(*ulpsc) +
3300 	    sizeof(*cpl) + 8 * sgl->nflits, 16));
3301 
3302 	/* ULP subcommand */
3303 	ulpsc = (void *)(ulpmc + 1);
3304 	ulpsc->cmd_more = htobe32(V_ULPTX_CMD((u32)ULP_TX_SC_IMM) |
3305 	    F_ULP_TX_SC_MORE);
3306 	ulpsc->len = htobe32(sizeof(struct cpl_tx_pkt_core));
3307 
3308 	flitp += sizeof(*ulpmc) + sizeof(*ulpsc);
3309 	if (flitp == end)
3310 		flitp = start;
3311 
3312 	/* CPL_TX_PKT */
3313 	cpl = (void *)flitp;
3314 	cpl->ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT) |
3315 	    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(pi->adapter->pf));
3316 	cpl->pack = 0;
3317 	cpl->len = htobe16(m->m_pkthdr.len);
3318 	cpl->ctrl1 = htobe64(ctrl);
3319 
3320 	flitp += sizeof(*cpl);
3321 	if (flitp == end)
3322 		flitp = start;
3323 
3324 	/* SGL for this frame */
3325 	dst = (caddr_t)flitp;
3326 	txpkts->nflits += write_sgl_to_txd(eq, sgl, &dst);
3327 	txpkts->flitp = (void *)dst;
3328 
3329 	KASSERT(((uintptr_t)dst & 0xf) == 0,
3330 	    ("%s: SGL ends at %p (not a 16 byte boundary)", __func__, dst));
3331 }
3332 
3333 /*
3334  * If the SGL ends on an address that is not 16 byte aligned, this function will
3335  * add a 0 filled flit at the end.  It returns 1 in that case.
3336  */
3337 static int
3338 write_sgl_to_txd(struct sge_eq *eq, struct sgl *sgl, caddr_t *to)
3339 {
3340 	__be64 *flitp, *end;
3341 	struct ulptx_sgl *usgl;
3342 	bus_dma_segment_t *seg;
3343 	int i, padded;
3344 
3345 	KASSERT(sgl->nsegs > 0 && sgl->nflits > 0,
3346 	    ("%s: bad SGL - nsegs=%d, nflits=%d",
3347 	    __func__, sgl->nsegs, sgl->nflits));
3348 
3349 	KASSERT(((uintptr_t)(*to) & 0xf) == 0,
3350 	    ("%s: SGL must start at a 16 byte boundary: %p", __func__, *to));
3351 
3352 	flitp = (__be64 *)(*to);
3353 	end = flitp + sgl->nflits;
3354 	seg = &sgl->seg[0];
3355 	usgl = (void *)flitp;
3356 
3357 	/*
3358 	 * We start at a 16 byte boundary somewhere inside the tx descriptor
3359 	 * ring, so we're at least 16 bytes away from the status page.  There is
3360 	 * no chance of a wrap around in the middle of usgl (which is 16 bytes).
3361 	 */
3362 
3363 	usgl->cmd_nsge = htobe32(V_ULPTX_CMD(ULP_TX_SC_DSGL) |
3364 	    V_ULPTX_NSGE(sgl->nsegs));
3365 	usgl->len0 = htobe32(seg->ds_len);
3366 	usgl->addr0 = htobe64(seg->ds_addr);
3367 	seg++;
3368 
3369 	if ((uintptr_t)end <= (uintptr_t)eq->spg) {
3370 
3371 		/* Won't wrap around at all */
3372 
3373 		for (i = 0; i < sgl->nsegs - 1; i++, seg++) {
3374 			usgl->sge[i / 2].len[i & 1] = htobe32(seg->ds_len);
3375 			usgl->sge[i / 2].addr[i & 1] = htobe64(seg->ds_addr);
3376 		}
3377 		if (i & 1)
3378 			usgl->sge[i / 2].len[1] = htobe32(0);
3379 	} else {
3380 
3381 		/* Will wrap somewhere in the rest of the SGL */
3382 
3383 		/* 2 flits already written, write the rest flit by flit */
3384 		flitp = (void *)(usgl + 1);
3385 		for (i = 0; i < sgl->nflits - 2; i++) {
3386 			if ((uintptr_t)flitp == (uintptr_t)eq->spg)
3387 				flitp = (void *)eq->desc;
3388 			*flitp++ = get_flit(seg, sgl->nsegs - 1, i);
3389 		}
3390 		end = flitp;
3391 	}
3392 
3393 	if ((uintptr_t)end & 0xf) {
3394 		*(uint64_t *)end = 0;
3395 		end++;
3396 		padded = 1;
3397 	} else
3398 		padded = 0;
3399 
3400 	if ((uintptr_t)end == (uintptr_t)eq->spg)
3401 		*to = (void *)eq->desc;
3402 	else
3403 		*to = (void *)end;
3404 
3405 	return (padded);
3406 }
3407 
3408 static inline void
3409 copy_to_txd(struct sge_eq *eq, caddr_t from, caddr_t *to, int len)
3410 {
3411 	if (__predict_true((uintptr_t)(*to) + len <= (uintptr_t)eq->spg)) {
3412 		bcopy(from, *to, len);
3413 		(*to) += len;
3414 	} else {
3415 		int portion = (uintptr_t)eq->spg - (uintptr_t)(*to);
3416 
3417 		bcopy(from, *to, portion);
3418 		from += portion;
3419 		portion = len - portion;	/* remaining */
3420 		bcopy(from, (void *)eq->desc, portion);
3421 		(*to) = (caddr_t)eq->desc + portion;
3422 	}
3423 }
3424 
3425 static inline void
3426 ring_eq_db(struct adapter *sc, struct sge_eq *eq)
3427 {
3428 	u_int db, pending;
3429 
3430 	db = eq->doorbells;
3431 	pending = eq->pending;
3432 	if (pending > 1)
3433 		clrbit(&db, DOORBELL_WRWC);
3434 	eq->pending = 0;
3435 	wmb();
3436 
3437 	switch (ffs(db) - 1) {
3438 	case DOORBELL_UDB:
3439 		*eq->udb = htole32(V_QID(eq->udb_qid) | V_PIDX(pending));
3440 		return;
3441 
3442 	case DOORBELL_WRWC: {
3443 		volatile uint64_t *dst, *src;
3444 		int i;
3445 
3446 		/*
3447 		 * Queues whose 128B doorbell segment fits in the page do not
3448 		 * use relative qid (udb_qid is always 0).  Only queues with
3449 		 * doorbell segments can do WRWC.
3450 		 */
3451 		KASSERT(eq->udb_qid == 0 && pending == 1,
3452 		    ("%s: inappropriate doorbell (0x%x, %d, %d) for eq %p",
3453 		    __func__, eq->doorbells, pending, eq->pidx, eq));
3454 
3455 		dst = (volatile void *)((uintptr_t)eq->udb + UDBS_WR_OFFSET -
3456 		    UDBS_DB_OFFSET);
3457 		i = eq->pidx ? eq->pidx - 1 : eq->cap - 1;
3458 		src = (void *)&eq->desc[i];
3459 		while (src != (void *)&eq->desc[i + 1])
3460 			*dst++ = *src++;
3461 		wmb();
3462 		return;
3463 	}
3464 
3465 	case DOORBELL_UDBWC:
3466 		*eq->udb = htole32(V_QID(eq->udb_qid) | V_PIDX(pending));
3467 		wmb();
3468 		return;
3469 
3470 	case DOORBELL_KDB:
3471 		t4_write_reg(sc, MYPF_REG(A_SGE_PF_KDOORBELL),
3472 		    V_QID(eq->cntxt_id) | V_PIDX(pending));
3473 		return;
3474 	}
3475 }
3476 
3477 static inline int
3478 reclaimable(struct sge_eq *eq)
3479 {
3480 	unsigned int cidx;
3481 
3482 	cidx = eq->spg->cidx;	/* stable snapshot */
3483 	cidx = be16toh(cidx);
3484 
3485 	if (cidx >= eq->cidx)
3486 		return (cidx - eq->cidx);
3487 	else
3488 		return (cidx + eq->cap - eq->cidx);
3489 }
3490 
3491 /*
3492  * There are "can_reclaim" tx descriptors ready to be reclaimed.  Reclaim as
3493  * many as possible but stop when there are around "n" mbufs to free.
3494  *
3495  * The actual number reclaimed is provided as the return value.
3496  */
3497 static int
3498 reclaim_tx_descs(struct sge_txq *txq, int can_reclaim, int n)
3499 {
3500 	struct tx_sdesc *txsd;
3501 	struct tx_maps *txmaps;
3502 	struct tx_map *txm;
3503 	unsigned int reclaimed, maps;
3504 	struct sge_eq *eq = &txq->eq;
3505 
3506 	TXQ_LOCK_ASSERT_OWNED(txq);
3507 
3508 	if (can_reclaim == 0)
3509 		can_reclaim = reclaimable(eq);
3510 
3511 	maps = reclaimed = 0;
3512 	while (can_reclaim && maps < n) {
3513 		int ndesc;
3514 
3515 		txsd = &txq->sdesc[eq->cidx];
3516 		ndesc = txsd->desc_used;
3517 
3518 		/* Firmware doesn't return "partial" credits. */
3519 		KASSERT(can_reclaim >= ndesc,
3520 		    ("%s: unexpected number of credits: %d, %d",
3521 		    __func__, can_reclaim, ndesc));
3522 
3523 		maps += txsd->credits;
3524 
3525 		reclaimed += ndesc;
3526 		can_reclaim -= ndesc;
3527 
3528 		eq->cidx += ndesc;
3529 		if (__predict_false(eq->cidx >= eq->cap))
3530 			eq->cidx -= eq->cap;
3531 	}
3532 
3533 	txmaps = &txq->txmaps;
3534 	txm = &txmaps->maps[txmaps->map_cidx];
3535 	if (maps)
3536 		prefetch(txm->m);
3537 
3538 	eq->avail += reclaimed;
3539 	KASSERT(eq->avail < eq->cap,	/* avail tops out at (cap - 1) */
3540 	    ("%s: too many descriptors available", __func__));
3541 
3542 	txmaps->map_avail += maps;
3543 	KASSERT(txmaps->map_avail <= txmaps->map_total,
3544 	    ("%s: too many maps available", __func__));
3545 
3546 	while (maps--) {
3547 		struct tx_map *next;
3548 
3549 		next = txm + 1;
3550 		if (__predict_false(txmaps->map_cidx + 1 == txmaps->map_total))
3551 			next = txmaps->maps;
3552 		prefetch(next->m);
3553 
3554 		bus_dmamap_unload(txq->tx_tag, txm->map);
3555 		m_freem(txm->m);
3556 		txm->m = NULL;
3557 
3558 		txm = next;
3559 		if (__predict_false(++txmaps->map_cidx == txmaps->map_total))
3560 			txmaps->map_cidx = 0;
3561 	}
3562 
3563 	return (reclaimed);
3564 }
3565 
3566 static void
3567 write_eqflush_wr(struct sge_eq *eq)
3568 {
3569 	struct fw_eq_flush_wr *wr;
3570 
3571 	EQ_LOCK_ASSERT_OWNED(eq);
3572 	KASSERT(eq->avail > 0, ("%s: no descriptors left.", __func__));
3573 	KASSERT(!(eq->flags & EQ_CRFLUSHED), ("%s: flushed already", __func__));
3574 
3575 	wr = (void *)&eq->desc[eq->pidx];
3576 	bzero(wr, sizeof(*wr));
3577 	wr->opcode = FW_EQ_FLUSH_WR;
3578 	wr->equiq_to_len16 = htobe32(V_FW_WR_LEN16(sizeof(*wr) / 16) |
3579 	    F_FW_WR_EQUEQ | F_FW_WR_EQUIQ);
3580 
3581 	eq->flags |= (EQ_CRFLUSHED | EQ_STALLED);
3582 	eq->pending++;
3583 	eq->avail--;
3584 	if (++eq->pidx == eq->cap)
3585 		eq->pidx = 0;
3586 }
3587 
3588 static __be64
3589 get_flit(bus_dma_segment_t *sgl, int nsegs, int idx)
3590 {
3591 	int i = (idx / 3) * 2;
3592 
3593 	switch (idx % 3) {
3594 	case 0: {
3595 		__be64 rc;
3596 
3597 		rc = htobe32(sgl[i].ds_len);
3598 		if (i + 1 < nsegs)
3599 			rc |= (uint64_t)htobe32(sgl[i + 1].ds_len) << 32;
3600 
3601 		return (rc);
3602 	}
3603 	case 1:
3604 		return htobe64(sgl[i].ds_addr);
3605 	case 2:
3606 		return htobe64(sgl[i + 1].ds_addr);
3607 	}
3608 
3609 	return (0);
3610 }
3611 
3612 static void
3613 set_fl_tag_idx(struct sge_fl *fl, int bufsize)
3614 {
3615 	int i;
3616 
3617 	for (i = 0; i < FL_BUF_SIZES - 1; i++) {
3618 		if (FL_BUF_SIZE(i) >= bufsize)
3619 			break;
3620 	}
3621 
3622 	fl->tag_idx = i;
3623 }
3624 
3625 static void
3626 add_fl_to_sfl(struct adapter *sc, struct sge_fl *fl)
3627 {
3628 	mtx_lock(&sc->sfl_lock);
3629 	FL_LOCK(fl);
3630 	if ((fl->flags & FL_DOOMED) == 0) {
3631 		fl->flags |= FL_STARVING;
3632 		TAILQ_INSERT_TAIL(&sc->sfl, fl, link);
3633 		callout_reset(&sc->sfl_callout, hz / 5, refill_sfl, sc);
3634 	}
3635 	FL_UNLOCK(fl);
3636 	mtx_unlock(&sc->sfl_lock);
3637 }
3638 
3639 static int
3640 handle_sge_egr_update(struct sge_iq *iq, const struct rss_header *rss,
3641     struct mbuf *m)
3642 {
3643 	const struct cpl_sge_egr_update *cpl = (const void *)(rss + 1);
3644 	unsigned int qid = G_EGR_QID(ntohl(cpl->opcode_qid));
3645 	struct adapter *sc = iq->adapter;
3646 	struct sge *s = &sc->sge;
3647 	struct sge_eq *eq;
3648 
3649 	KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
3650 	    rss->opcode));
3651 
3652 	eq = s->eqmap[qid - s->eq_start];
3653 	EQ_LOCK(eq);
3654 	KASSERT(eq->flags & EQ_CRFLUSHED,
3655 	    ("%s: unsolicited egress update", __func__));
3656 	eq->flags &= ~EQ_CRFLUSHED;
3657 	eq->egr_update++;
3658 
3659 	if (__predict_false(eq->flags & EQ_DOOMED))
3660 		wakeup_one(eq);
3661 	else if (eq->flags & EQ_STALLED && can_resume_tx(eq))
3662 		taskqueue_enqueue(sc->tq[eq->tx_chan], &eq->tx_task);
3663 	EQ_UNLOCK(eq);
3664 
3665 	return (0);
3666 }
3667 
3668 /* handle_fw_msg works for both fw4_msg and fw6_msg because this is valid */
3669 CTASSERT(offsetof(struct cpl_fw4_msg, data) == \
3670     offsetof(struct cpl_fw6_msg, data));
3671 
3672 static int
3673 handle_fw_msg(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
3674 {
3675 	struct adapter *sc = iq->adapter;
3676 	const struct cpl_fw6_msg *cpl = (const void *)(rss + 1);
3677 
3678 	KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
3679 	    rss->opcode));
3680 
3681 	if (cpl->type == FW_TYPE_RSSCPL || cpl->type == FW6_TYPE_RSSCPL) {
3682 		const struct rss_header *rss2;
3683 
3684 		rss2 = (const struct rss_header *)&cpl->data[0];
3685 		return (sc->cpl_handler[rss2->opcode](iq, rss2, m));
3686 	}
3687 
3688 	return (sc->fw_msg_handler[cpl->type](sc, &cpl->data[0]));
3689 }
3690 
3691 static int
3692 sysctl_uint16(SYSCTL_HANDLER_ARGS)
3693 {
3694 	uint16_t *id = arg1;
3695 	int i = *id;
3696 
3697 	return sysctl_handle_int(oidp, &i, 0, req);
3698 }
3699