xref: /freebsd/sys/net/iflib.c (revision 23f6875a43f7ce365f2d52cf857da010c47fb03b)
1 /*-
2  * Copyright (c) 2014-2016, Matthew Macy <mmacy@nextbsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *  1. Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *
11  *  2. Neither the name of Matthew Macy nor the names of its
12  *     contributors may be used to endorse or promote products derived from
13  *     this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16  * AND 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 COPYRIGHT OWNER OR CONTRIBUTORS BE
19  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25  * POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_acpi.h"
34 
35 #include <sys/param.h>
36 #include <sys/types.h>
37 #include <sys/bus.h>
38 #include <sys/eventhandler.h>
39 #include <sys/sockio.h>
40 #include <sys/kernel.h>
41 #include <sys/lock.h>
42 #include <sys/mutex.h>
43 #include <sys/module.h>
44 #include <sys/kobj.h>
45 #include <sys/rman.h>
46 #include <sys/sbuf.h>
47 #include <sys/smp.h>
48 #include <sys/socket.h>
49 #include <sys/sysctl.h>
50 #include <sys/syslog.h>
51 #include <sys/taskqueue.h>
52 #include <sys/limits.h>
53 
54 
55 #include <net/if.h>
56 #include <net/if_var.h>
57 #include <net/if_types.h>
58 #include <net/if_media.h>
59 #include <net/bpf.h>
60 #include <net/ethernet.h>
61 #include <net/mp_ring.h>
62 
63 #include <netinet/in.h>
64 #include <netinet/in_pcb.h>
65 #include <netinet/tcp_lro.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/if_ether.h>
68 #include <netinet/ip.h>
69 #include <netinet/ip6.h>
70 #include <netinet/tcp.h>
71 
72 #include <machine/bus.h>
73 #include <machine/in_cksum.h>
74 
75 #include <vm/vm.h>
76 #include <vm/pmap.h>
77 
78 #include <dev/led/led.h>
79 #include <dev/pci/pcireg.h>
80 #include <dev/pci/pcivar.h>
81 #include <dev/pci/pci_private.h>
82 
83 #include <net/iflib.h>
84 
85 #include "ifdi_if.h"
86 
87 #if defined(__i386__) || defined(__amd64__)
88 #include <sys/memdesc.h>
89 #include <machine/bus.h>
90 #include <machine/md_var.h>
91 #include <machine/specialreg.h>
92 #include <x86/include/busdma_impl.h>
93 #include <x86/iommu/busdma_dmar.h>
94 #endif
95 
96 /*
97  * enable accounting of every mbuf as it comes in to and goes out of iflib's software descriptor references
98  */
99 #define MEMORY_LOGGING 0
100 /*
101  * Enable mbuf vectors for compressing long mbuf chains
102  */
103 
104 /*
105  * NB:
106  * - Prefetching in tx cleaning should perhaps be a tunable. The distance ahead
107  *   we prefetch needs to be determined by the time spent in m_free vis a vis
108  *   the cost of a prefetch. This will of course vary based on the workload:
109  *      - NFLX's m_free path is dominated by vm-based M_EXT manipulation which
110  *        is quite expensive, thus suggesting very little prefetch.
111  *      - small packet forwarding which is just returning a single mbuf to
112  *        UMA will typically be very fast vis a vis the cost of a memory
113  *        access.
114  */
115 
116 
117 /*
118  * File organization:
119  *  - private structures
120  *  - iflib private utility functions
121  *  - ifnet functions
122  *  - vlan registry and other exported functions
123  *  - iflib public core functions
124  *
125  *
126  */
127 static MALLOC_DEFINE(M_IFLIB, "iflib", "ifnet library");
128 
129 struct iflib_txq;
130 typedef struct iflib_txq *iflib_txq_t;
131 struct iflib_rxq;
132 typedef struct iflib_rxq *iflib_rxq_t;
133 struct iflib_fl;
134 typedef struct iflib_fl *iflib_fl_t;
135 
136 struct iflib_ctx;
137 
138 typedef struct iflib_filter_info {
139 	driver_filter_t *ifi_filter;
140 	void *ifi_filter_arg;
141 	struct grouptask *ifi_task;
142 	struct iflib_ctx *ifi_ctx;
143 } *iflib_filter_info_t;
144 
145 struct iflib_ctx {
146 	KOBJ_FIELDS;
147    /*
148    * Pointer to hardware driver's softc
149    */
150 	void *ifc_softc;
151 	device_t ifc_dev;
152 	if_t ifc_ifp;
153 
154 	cpuset_t ifc_cpus;
155 	if_shared_ctx_t ifc_sctx;
156 	struct if_softc_ctx ifc_softc_ctx;
157 
158 	struct mtx ifc_mtx;
159 
160 	uint16_t ifc_nhwtxqs;
161 	uint16_t ifc_nhwrxqs;
162 
163 	iflib_txq_t ifc_txqs;
164 	iflib_rxq_t ifc_rxqs;
165 	uint32_t ifc_if_flags;
166 	uint32_t ifc_flags;
167 	uint32_t ifc_max_fl_buf_size;
168 	int ifc_in_detach;
169 
170 	int ifc_link_state;
171 	int ifc_link_irq;
172 	int ifc_pause_frames;
173 	int ifc_watchdog_events;
174 	struct cdev *ifc_led_dev;
175 	struct resource *ifc_msix_mem;
176 
177 	struct if_irq ifc_legacy_irq;
178 	struct grouptask ifc_admin_task;
179 	struct grouptask ifc_vflr_task;
180 	struct iflib_filter_info ifc_filter_info;
181 	struct ifmedia	ifc_media;
182 
183 	struct sysctl_oid *ifc_sysctl_node;
184 	uint16_t ifc_sysctl_ntxqs;
185 	uint16_t ifc_sysctl_nrxqs;
186 	uint16_t ifc_sysctl_qs_eq_override;
187 
188 	uint16_t ifc_sysctl_ntxds[8];
189 	uint16_t ifc_sysctl_nrxds[8];
190 	struct if_txrx ifc_txrx;
191 #define isc_txd_encap  ifc_txrx.ift_txd_encap
192 #define isc_txd_flush  ifc_txrx.ift_txd_flush
193 #define isc_txd_credits_update  ifc_txrx.ift_txd_credits_update
194 #define isc_rxd_available ifc_txrx.ift_rxd_available
195 #define isc_rxd_pkt_get ifc_txrx.ift_rxd_pkt_get
196 #define isc_rxd_refill ifc_txrx.ift_rxd_refill
197 #define isc_rxd_flush ifc_txrx.ift_rxd_flush
198 #define isc_rxd_refill ifc_txrx.ift_rxd_refill
199 #define isc_rxd_refill ifc_txrx.ift_rxd_refill
200 #define isc_legacy_intr ifc_txrx.ift_legacy_intr
201 	eventhandler_tag ifc_vlan_attach_event;
202 	eventhandler_tag ifc_vlan_detach_event;
203 	uint8_t ifc_mac[ETHER_ADDR_LEN];
204 	char ifc_mtx_name[16];
205 };
206 
207 
208 void *
209 iflib_get_softc(if_ctx_t ctx)
210 {
211 
212 	return (ctx->ifc_softc);
213 }
214 
215 device_t
216 iflib_get_dev(if_ctx_t ctx)
217 {
218 
219 	return (ctx->ifc_dev);
220 }
221 
222 if_t
223 iflib_get_ifp(if_ctx_t ctx)
224 {
225 
226 	return (ctx->ifc_ifp);
227 }
228 
229 struct ifmedia *
230 iflib_get_media(if_ctx_t ctx)
231 {
232 
233 	return (&ctx->ifc_media);
234 }
235 
236 void
237 iflib_set_mac(if_ctx_t ctx, uint8_t mac[ETHER_ADDR_LEN])
238 {
239 
240 	bcopy(mac, ctx->ifc_mac, ETHER_ADDR_LEN);
241 }
242 
243 if_softc_ctx_t
244 iflib_get_softc_ctx(if_ctx_t ctx)
245 {
246 
247 	return (&ctx->ifc_softc_ctx);
248 }
249 
250 if_shared_ctx_t
251 iflib_get_sctx(if_ctx_t ctx)
252 {
253 
254 	return (ctx->ifc_sctx);
255 }
256 
257 #define CACHE_PTR_INCREMENT (CACHE_LINE_SIZE/sizeof(void*))
258 
259 #define LINK_ACTIVE(ctx) ((ctx)->ifc_link_state == LINK_STATE_UP)
260 #define CTX_IS_VF(ctx) ((ctx)->ifc_sctx->isc_flags & IFLIB_IS_VF)
261 
262 #define RX_SW_DESC_MAP_CREATED	(1 << 0)
263 #define TX_SW_DESC_MAP_CREATED	(1 << 1)
264 #define RX_SW_DESC_INUSE        (1 << 3)
265 #define TX_SW_DESC_MAPPED       (1 << 4)
266 
267 typedef struct iflib_sw_rx_desc {
268 	bus_dmamap_t    ifsd_map;         /* bus_dma map for packet */
269 	struct mbuf    *ifsd_m;           /* rx: uninitialized mbuf */
270 	caddr_t         ifsd_cl;          /* direct cluster pointer for rx */
271 	uint16_t	ifsd_flags;
272 } *iflib_rxsd_t;
273 
274 typedef struct iflib_sw_tx_desc_val {
275 	bus_dmamap_t    ifsd_map;         /* bus_dma map for packet */
276 	struct mbuf    *ifsd_m;           /* pkthdr mbuf */
277 	uint8_t		ifsd_flags;
278 } *iflib_txsd_val_t;
279 
280 typedef struct iflib_sw_tx_desc_array {
281 	bus_dmamap_t    *ifsd_map;         /* bus_dma maps for packet */
282 	struct mbuf    **ifsd_m;           /* pkthdr mbufs */
283 	uint8_t		*ifsd_flags;
284 } iflib_txsd_array_t;
285 
286 
287 /* magic number that should be high enough for any hardware */
288 #define IFLIB_MAX_TX_SEGS		128
289 #define IFLIB_MAX_RX_SEGS		32
290 #define IFLIB_RX_COPY_THRESH		128
291 #define IFLIB_MAX_RX_REFRESH		32
292 #define IFLIB_QUEUE_IDLE		0
293 #define IFLIB_QUEUE_HUNG		1
294 #define IFLIB_QUEUE_WORKING		2
295 
296 /* this should really scale with ring size - 32 is a fairly arbitrary value for this */
297 #define TX_BATCH_SIZE			16
298 
299 #define IFLIB_RESTART_BUDGET		8
300 
301 #define	IFC_LEGACY		0x01
302 #define	IFC_QFLUSH		0x02
303 #define	IFC_MULTISEG		0x04
304 #define	IFC_DMAR		0x08
305 #define	IFC_SC_ALLOCATED	0x10
306 #define	IFC_INIT_DONE		0x20
307 
308 
309 #define CSUM_OFFLOAD		(CSUM_IP_TSO|CSUM_IP6_TSO|CSUM_IP| \
310 				 CSUM_IP_UDP|CSUM_IP_TCP|CSUM_IP_SCTP| \
311 				 CSUM_IP6_UDP|CSUM_IP6_TCP|CSUM_IP6_SCTP)
312 struct iflib_txq {
313 	uint16_t	ift_in_use;
314 	uint16_t	ift_cidx;
315 	uint16_t	ift_cidx_processed;
316 	uint16_t	ift_pidx;
317 	uint8_t		ift_gen;
318 	uint8_t		ift_db_pending;
319 	uint8_t		ift_db_pending_queued;
320 	uint8_t		ift_npending;
321 	uint8_t		ift_br_offset;
322 	/* implicit pad */
323 	uint64_t	ift_processed;
324 	uint64_t	ift_cleaned;
325 #if MEMORY_LOGGING
326 	uint64_t	ift_enqueued;
327 	uint64_t	ift_dequeued;
328 #endif
329 	uint64_t	ift_no_tx_dma_setup;
330 	uint64_t	ift_no_desc_avail;
331 	uint64_t	ift_mbuf_defrag_failed;
332 	uint64_t	ift_mbuf_defrag;
333 	uint64_t	ift_map_failed;
334 	uint64_t	ift_txd_encap_efbig;
335 	uint64_t	ift_pullups;
336 
337 	struct mtx	ift_mtx;
338 	struct mtx	ift_db_mtx;
339 
340 	/* constant values */
341 	if_ctx_t	ift_ctx;
342 	struct ifmp_ring        **ift_br;
343 	struct grouptask	ift_task;
344 	uint16_t	ift_size;
345 	uint16_t	ift_id;
346 	struct callout	ift_timer;
347 	struct callout	ift_db_check;
348 
349 	iflib_txsd_array_t	ift_sds;
350 	uint8_t			ift_nbr;
351 	uint8_t			ift_qstatus;
352 	uint8_t			ift_active;
353 	uint8_t			ift_closed;
354 	int			ift_watchdog_time;
355 	struct iflib_filter_info ift_filter_info;
356 	bus_dma_tag_t		ift_desc_tag;
357 	bus_dma_tag_t		ift_tso_desc_tag;
358 	iflib_dma_info_t	ift_ifdi;
359 #define MTX_NAME_LEN 16
360 	char                    ift_mtx_name[MTX_NAME_LEN];
361 	char                    ift_db_mtx_name[MTX_NAME_LEN];
362 	bus_dma_segment_t	ift_segs[IFLIB_MAX_TX_SEGS]  __aligned(CACHE_LINE_SIZE);
363 #ifdef IFLIB_DIAGNOSTICS
364 	uint64_t ift_cpu_exec_count[256];
365 #endif
366 } __aligned(CACHE_LINE_SIZE);
367 
368 struct iflib_fl {
369 	uint16_t	ifl_cidx;
370 	uint16_t	ifl_pidx;
371 	uint16_t	ifl_credits;
372 	uint8_t		ifl_gen;
373 #if MEMORY_LOGGING
374 	uint64_t	ifl_m_enqueued;
375 	uint64_t	ifl_m_dequeued;
376 	uint64_t	ifl_cl_enqueued;
377 	uint64_t	ifl_cl_dequeued;
378 #endif
379 	/* implicit pad */
380 
381 	/* constant */
382 	uint16_t	ifl_size;
383 	uint16_t	ifl_buf_size;
384 	uint16_t	ifl_cltype;
385 	uma_zone_t	ifl_zone;
386 	iflib_rxsd_t	ifl_sds;
387 	iflib_rxq_t	ifl_rxq;
388 	uint8_t		ifl_id;
389 	bus_dma_tag_t           ifl_desc_tag;
390 	iflib_dma_info_t	ifl_ifdi;
391 	uint64_t	ifl_bus_addrs[IFLIB_MAX_RX_REFRESH] __aligned(CACHE_LINE_SIZE);
392 	caddr_t		ifl_vm_addrs[IFLIB_MAX_RX_REFRESH];
393 }  __aligned(CACHE_LINE_SIZE);
394 
395 static inline int
396 get_inuse(int size, int cidx, int pidx, int gen)
397 {
398 	int used;
399 
400 	if (pidx > cidx)
401 		used = pidx - cidx;
402 	else if (pidx < cidx)
403 		used = size - cidx + pidx;
404 	else if (gen == 0 && pidx == cidx)
405 		used = 0;
406 	else if (gen == 1 && pidx == cidx)
407 		used = size;
408 	else
409 		panic("bad state");
410 
411 	return (used);
412 }
413 
414 #define TXQ_AVAIL(txq) (txq->ift_size - get_inuse(txq->ift_size, txq->ift_cidx, txq->ift_pidx, txq->ift_gen))
415 
416 #define IDXDIFF(head, tail, wrap) \
417 	((head) >= (tail) ? (head) - (tail) : (wrap) - (tail) + (head))
418 
419 struct iflib_rxq {
420 	/* If there is a separate completion queue -
421 	 * these are the cq cidx and pidx. Otherwise
422 	 * these are unused.
423 	 */
424 	uint16_t	ifr_size;
425 	uint16_t	ifr_cq_cidx;
426 	uint16_t	ifr_cq_pidx;
427 	uint8_t		ifr_cq_gen;
428 	uint8_t		ifr_fl_offset;
429 
430 	if_ctx_t	ifr_ctx;
431 	iflib_fl_t	ifr_fl;
432 	uint64_t	ifr_rx_irq;
433 	uint16_t	ifr_id;
434 	uint8_t		ifr_lro_enabled;
435 	uint8_t		ifr_nfl;
436 	struct lro_ctrl			ifr_lc;
437 	struct grouptask        ifr_task;
438 	struct iflib_filter_info ifr_filter_info;
439 	iflib_dma_info_t		ifr_ifdi;
440 	/* dynamically allocate if any drivers need a value substantially larger than this */
441 	struct if_rxd_frag	ifr_frags[IFLIB_MAX_RX_SEGS] __aligned(CACHE_LINE_SIZE);
442 #ifdef IFLIB_DIAGNOSTICS
443 	uint64_t ifr_cpu_exec_count[256];
444 #endif
445 }  __aligned(CACHE_LINE_SIZE);
446 
447 /*
448  * Only allow a single packet to take up most 1/nth of the tx ring
449  */
450 #define MAX_SINGLE_PACKET_FRACTION 12
451 #define IF_BAD_DMA (bus_addr_t)-1
452 
453 static int enable_msix = 1;
454 
455 #define CTX_ACTIVE(ctx) ((if_getdrvflags((ctx)->ifc_ifp) & IFF_DRV_RUNNING))
456 
457 #define CTX_LOCK_INIT(_sc, _name)  mtx_init(&(_sc)->ifc_mtx, _name, "iflib ctx lock", MTX_DEF)
458 
459 #define CTX_LOCK(ctx) mtx_lock(&(ctx)->ifc_mtx)
460 #define CTX_UNLOCK(ctx) mtx_unlock(&(ctx)->ifc_mtx)
461 #define CTX_LOCK_DESTROY(ctx) mtx_destroy(&(ctx)->ifc_mtx)
462 
463 
464 #define TXDB_LOCK_INIT(txq)  mtx_init(&(txq)->ift_db_mtx, (txq)->ift_db_mtx_name, NULL, MTX_DEF)
465 #define TXDB_TRYLOCK(txq) mtx_trylock(&(txq)->ift_db_mtx)
466 #define TXDB_LOCK(txq) mtx_lock(&(txq)->ift_db_mtx)
467 #define TXDB_UNLOCK(txq) mtx_unlock(&(txq)->ift_db_mtx)
468 #define TXDB_LOCK_DESTROY(txq) mtx_destroy(&(txq)->ift_db_mtx)
469 
470 #define CALLOUT_LOCK(txq)	mtx_lock(&txq->ift_mtx)
471 #define CALLOUT_UNLOCK(txq) 	mtx_unlock(&txq->ift_mtx)
472 
473 
474 /* Our boot-time initialization hook */
475 static int	iflib_module_event_handler(module_t, int, void *);
476 
477 static moduledata_t iflib_moduledata = {
478 	"iflib",
479 	iflib_module_event_handler,
480 	NULL
481 };
482 
483 DECLARE_MODULE(iflib, iflib_moduledata, SI_SUB_INIT_IF, SI_ORDER_ANY);
484 MODULE_VERSION(iflib, 1);
485 
486 MODULE_DEPEND(iflib, pci, 1, 1, 1);
487 MODULE_DEPEND(iflib, ether, 1, 1, 1);
488 
489 TASKQGROUP_DEFINE(if_io_tqg, mp_ncpus, 1);
490 TASKQGROUP_DEFINE(if_config_tqg, 1, 1);
491 
492 #ifndef IFLIB_DEBUG_COUNTERS
493 #ifdef INVARIANTS
494 #define IFLIB_DEBUG_COUNTERS 1
495 #else
496 #define IFLIB_DEBUG_COUNTERS 0
497 #endif /* !INVARIANTS */
498 #endif
499 
500 static SYSCTL_NODE(_net, OID_AUTO, iflib, CTLFLAG_RD, 0,
501                    "iflib driver parameters");
502 
503 /*
504  * XXX need to ensure that this can't accidentally cause the head to be moved backwards
505  */
506 static int iflib_min_tx_latency = 0;
507 
508 SYSCTL_INT(_net_iflib, OID_AUTO, min_tx_latency, CTLFLAG_RW,
509 		   &iflib_min_tx_latency, 0, "minimize transmit latency at the possible expense of throughput");
510 
511 
512 #if IFLIB_DEBUG_COUNTERS
513 
514 static int iflib_tx_seen;
515 static int iflib_tx_sent;
516 static int iflib_tx_encap;
517 static int iflib_rx_allocs;
518 static int iflib_fl_refills;
519 static int iflib_fl_refills_large;
520 static int iflib_tx_frees;
521 
522 SYSCTL_INT(_net_iflib, OID_AUTO, tx_seen, CTLFLAG_RD,
523 		   &iflib_tx_seen, 0, "# tx mbufs seen");
524 SYSCTL_INT(_net_iflib, OID_AUTO, tx_sent, CTLFLAG_RD,
525 		   &iflib_tx_sent, 0, "# tx mbufs sent");
526 SYSCTL_INT(_net_iflib, OID_AUTO, tx_encap, CTLFLAG_RD,
527 		   &iflib_tx_encap, 0, "# tx mbufs encapped");
528 SYSCTL_INT(_net_iflib, OID_AUTO, tx_frees, CTLFLAG_RD,
529 		   &iflib_tx_frees, 0, "# tx frees");
530 SYSCTL_INT(_net_iflib, OID_AUTO, rx_allocs, CTLFLAG_RD,
531 		   &iflib_rx_allocs, 0, "# rx allocations");
532 SYSCTL_INT(_net_iflib, OID_AUTO, fl_refills, CTLFLAG_RD,
533 		   &iflib_fl_refills, 0, "# refills");
534 SYSCTL_INT(_net_iflib, OID_AUTO, fl_refills_large, CTLFLAG_RD,
535 		   &iflib_fl_refills_large, 0, "# large refills");
536 
537 
538 static int iflib_txq_drain_flushing;
539 static int iflib_txq_drain_oactive;
540 static int iflib_txq_drain_notready;
541 static int iflib_txq_drain_encapfail;
542 
543 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_flushing, CTLFLAG_RD,
544 		   &iflib_txq_drain_flushing, 0, "# drain flushes");
545 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_oactive, CTLFLAG_RD,
546 		   &iflib_txq_drain_oactive, 0, "# drain oactives");
547 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_notready, CTLFLAG_RD,
548 		   &iflib_txq_drain_notready, 0, "# drain notready");
549 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_encapfail, CTLFLAG_RD,
550 		   &iflib_txq_drain_encapfail, 0, "# drain encap fails");
551 
552 
553 static int iflib_encap_load_mbuf_fail;
554 static int iflib_encap_txq_avail_fail;
555 static int iflib_encap_txd_encap_fail;
556 
557 SYSCTL_INT(_net_iflib, OID_AUTO, encap_load_mbuf_fail, CTLFLAG_RD,
558 		   &iflib_encap_load_mbuf_fail, 0, "# busdma load failures");
559 SYSCTL_INT(_net_iflib, OID_AUTO, encap_txq_avail_fail, CTLFLAG_RD,
560 		   &iflib_encap_txq_avail_fail, 0, "# txq avail failures");
561 SYSCTL_INT(_net_iflib, OID_AUTO, encap_txd_encap_fail, CTLFLAG_RD,
562 		   &iflib_encap_txd_encap_fail, 0, "# driver encap failures");
563 
564 static int iflib_task_fn_rxs;
565 static int iflib_rx_intr_enables;
566 static int iflib_fast_intrs;
567 static int iflib_intr_link;
568 static int iflib_intr_msix;
569 static int iflib_rx_unavail;
570 static int iflib_rx_ctx_inactive;
571 static int iflib_rx_zero_len;
572 static int iflib_rx_if_input;
573 static int iflib_rx_mbuf_null;
574 static int iflib_rxd_flush;
575 
576 static int iflib_verbose_debug;
577 
578 SYSCTL_INT(_net_iflib, OID_AUTO, intr_link, CTLFLAG_RD,
579 		   &iflib_intr_link, 0, "# intr link calls");
580 SYSCTL_INT(_net_iflib, OID_AUTO, intr_msix, CTLFLAG_RD,
581 		   &iflib_intr_msix, 0, "# intr msix calls");
582 SYSCTL_INT(_net_iflib, OID_AUTO, task_fn_rx, CTLFLAG_RD,
583 		   &iflib_task_fn_rxs, 0, "# task_fn_rx calls");
584 SYSCTL_INT(_net_iflib, OID_AUTO, rx_intr_enables, CTLFLAG_RD,
585 		   &iflib_rx_intr_enables, 0, "# rx intr enables");
586 SYSCTL_INT(_net_iflib, OID_AUTO, fast_intrs, CTLFLAG_RD,
587 		   &iflib_fast_intrs, 0, "# fast_intr calls");
588 SYSCTL_INT(_net_iflib, OID_AUTO, rx_unavail, CTLFLAG_RD,
589 		   &iflib_rx_unavail, 0, "# times rxeof called with no available data");
590 SYSCTL_INT(_net_iflib, OID_AUTO, rx_ctx_inactive, CTLFLAG_RD,
591 		   &iflib_rx_ctx_inactive, 0, "# times rxeof called with inactive context");
592 SYSCTL_INT(_net_iflib, OID_AUTO, rx_zero_len, CTLFLAG_RD,
593 		   &iflib_rx_zero_len, 0, "# times rxeof saw zero len mbuf");
594 SYSCTL_INT(_net_iflib, OID_AUTO, rx_if_input, CTLFLAG_RD,
595 		   &iflib_rx_if_input, 0, "# times rxeof called if_input");
596 SYSCTL_INT(_net_iflib, OID_AUTO, rx_mbuf_null, CTLFLAG_RD,
597 		   &iflib_rx_mbuf_null, 0, "# times rxeof got null mbuf");
598 SYSCTL_INT(_net_iflib, OID_AUTO, rxd_flush, CTLFLAG_RD,
599 	         &iflib_rxd_flush, 0, "# times rxd_flush called");
600 SYSCTL_INT(_net_iflib, OID_AUTO, verbose_debug, CTLFLAG_RW,
601 		   &iflib_verbose_debug, 0, "enable verbose debugging");
602 
603 #define DBG_COUNTER_INC(name) atomic_add_int(&(iflib_ ## name), 1)
604 static void
605 iflib_debug_reset(void)
606 {
607 	iflib_tx_seen = iflib_tx_sent = iflib_tx_encap = iflib_rx_allocs =
608 		iflib_fl_refills = iflib_fl_refills_large = iflib_tx_frees =
609 		iflib_txq_drain_flushing = iflib_txq_drain_oactive =
610 		iflib_txq_drain_notready = iflib_txq_drain_encapfail =
611 		iflib_encap_load_mbuf_fail = iflib_encap_txq_avail_fail =
612 		iflib_encap_txd_encap_fail = iflib_task_fn_rxs = iflib_rx_intr_enables =
613 		iflib_fast_intrs = iflib_intr_link = iflib_intr_msix = iflib_rx_unavail =
614 		iflib_rx_ctx_inactive = iflib_rx_zero_len = iflib_rx_if_input =
615 		iflib_rx_mbuf_null = iflib_rxd_flush = 0;
616 }
617 
618 #else
619 #define DBG_COUNTER_INC(name)
620 static void iflib_debug_reset(void) {}
621 #endif
622 
623 
624 
625 #define IFLIB_DEBUG 0
626 
627 static void iflib_tx_structures_free(if_ctx_t ctx);
628 static void iflib_rx_structures_free(if_ctx_t ctx);
629 static int iflib_queues_alloc(if_ctx_t ctx);
630 static int iflib_tx_credits_update(if_ctx_t ctx, iflib_txq_t txq);
631 static int iflib_rxd_avail(if_ctx_t ctx, iflib_rxq_t rxq, int cidx, int budget);
632 static int iflib_qset_structures_setup(if_ctx_t ctx);
633 static int iflib_msix_init(if_ctx_t ctx);
634 static int iflib_legacy_setup(if_ctx_t ctx, driver_filter_t filter, void *filterarg, int *rid, char *str);
635 static void iflib_txq_check_drain(iflib_txq_t txq, int budget);
636 static uint32_t iflib_txq_can_drain(struct ifmp_ring *);
637 static int iflib_register(if_ctx_t);
638 static void iflib_init_locked(if_ctx_t ctx);
639 static void iflib_add_device_sysctl_pre(if_ctx_t ctx);
640 static void iflib_add_device_sysctl_post(if_ctx_t ctx);
641 static void iflib_ifmp_purge(iflib_txq_t txq);
642 static void _iflib_pre_assert(if_softc_ctx_t scctx);
643 
644 #ifdef DEV_NETMAP
645 #include <sys/selinfo.h>
646 #include <net/netmap.h>
647 #include <dev/netmap/netmap_kern.h>
648 
649 MODULE_DEPEND(iflib, netmap, 1, 1, 1);
650 
651 /*
652  * device-specific sysctl variables:
653  *
654  * iflib_crcstrip: 0: keep CRC in rx frames (default), 1: strip it.
655  *	During regular operations the CRC is stripped, but on some
656  *	hardware reception of frames not multiple of 64 is slower,
657  *	so using crcstrip=0 helps in benchmarks.
658  *
659  * iflib_rx_miss, iflib_rx_miss_bufs:
660  *	count packets that might be missed due to lost interrupts.
661  */
662 SYSCTL_DECL(_dev_netmap);
663 /*
664  * The xl driver by default strips CRCs and we do not override it.
665  */
666 
667 int iflib_crcstrip = 1;
668 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_crcstrip,
669     CTLFLAG_RW, &iflib_crcstrip, 1, "strip CRC on rx frames");
670 
671 int iflib_rx_miss, iflib_rx_miss_bufs;
672 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_rx_miss,
673     CTLFLAG_RW, &iflib_rx_miss, 0, "potentially missed rx intr");
674 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_rx_miss_bufs,
675     CTLFLAG_RW, &iflib_rx_miss_bufs, 0, "potentially missed rx intr bufs");
676 
677 /*
678  * Register/unregister. We are already under netmap lock.
679  * Only called on the first register or the last unregister.
680  */
681 static int
682 iflib_netmap_register(struct netmap_adapter *na, int onoff)
683 {
684 	struct ifnet *ifp = na->ifp;
685 	if_ctx_t ctx = ifp->if_softc;
686 
687 	CTX_LOCK(ctx);
688 	IFDI_INTR_DISABLE(ctx);
689 
690 	/* Tell the stack that the interface is no longer active */
691 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
692 
693 	if (!CTX_IS_VF(ctx))
694 		IFDI_CRCSTRIP_SET(ctx, onoff, iflib_crcstrip);
695 
696 	/* enable or disable flags and callbacks in na and ifp */
697 	if (onoff) {
698 		nm_set_native_flags(na);
699 	} else {
700 		nm_clear_native_flags(na);
701 	}
702 	IFDI_INIT(ctx);
703 	IFDI_CRCSTRIP_SET(ctx, onoff, iflib_crcstrip); // XXX why twice ?
704 	CTX_UNLOCK(ctx);
705 	return (ifp->if_drv_flags & IFF_DRV_RUNNING ? 0 : 1);
706 }
707 
708 /*
709  * Reconcile kernel and user view of the transmit ring.
710  *
711  * All information is in the kring.
712  * Userspace wants to send packets up to the one before kring->rhead,
713  * kernel knows kring->nr_hwcur is the first unsent packet.
714  *
715  * Here we push packets out (as many as possible), and possibly
716  * reclaim buffers from previously completed transmission.
717  *
718  * The caller (netmap) guarantees that there is only one instance
719  * running at any time. Any interference with other driver
720  * methods should be handled by the individual drivers.
721  */
722 static int
723 iflib_netmap_txsync(struct netmap_kring *kring, int flags)
724 {
725 	struct netmap_adapter *na = kring->na;
726 	struct ifnet *ifp = na->ifp;
727 	struct netmap_ring *ring = kring->ring;
728 	u_int nm_i;	/* index into the netmap ring */
729 	u_int nic_i;	/* index into the NIC ring */
730 	u_int n;
731 	u_int const lim = kring->nkr_num_slots - 1;
732 	u_int const head = kring->rhead;
733 	struct if_pkt_info pi;
734 
735 	/*
736 	 * interrupts on every tx packet are expensive so request
737 	 * them every half ring, or where NS_REPORT is set
738 	 */
739 	u_int report_frequency = kring->nkr_num_slots >> 1;
740 	/* device-specific */
741 	if_ctx_t ctx = ifp->if_softc;
742 	iflib_txq_t txq = &ctx->ifc_txqs[kring->ring_id];
743 
744 	pi.ipi_segs = txq->ift_segs;
745 	pi.ipi_qsidx = kring->ring_id;
746 	pi.ipi_ndescs = 0;
747 
748 	bus_dmamap_sync(txq->ift_desc_tag, txq->ift_ifdi->idi_map,
749 					BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
750 
751 
752 	/*
753 	 * First part: process new packets to send.
754 	 * nm_i is the current index in the netmap ring,
755 	 * nic_i is the corresponding index in the NIC ring.
756 	 *
757 	 * If we have packets to send (nm_i != head)
758 	 * iterate over the netmap ring, fetch length and update
759 	 * the corresponding slot in the NIC ring. Some drivers also
760 	 * need to update the buffer's physical address in the NIC slot
761 	 * even NS_BUF_CHANGED is not set (PNMB computes the addresses).
762 	 *
763 	 * The netmap_reload_map() calls is especially expensive,
764 	 * even when (as in this case) the tag is 0, so do only
765 	 * when the buffer has actually changed.
766 	 *
767 	 * If possible do not set the report/intr bit on all slots,
768 	 * but only a few times per ring or when NS_REPORT is set.
769 	 *
770 	 * Finally, on 10G and faster drivers, it might be useful
771 	 * to prefetch the next slot and txr entry.
772 	 */
773 
774 	nm_i = kring->nr_hwcur;
775 	if (nm_i != head) {	/* we have new packets to send */
776 		nic_i = netmap_idx_k2n(kring, nm_i);
777 
778 		__builtin_prefetch(&ring->slot[nm_i]);
779 		__builtin_prefetch(&txq->ift_sds.ifsd_m[nic_i]);
780 		__builtin_prefetch(&txq->ift_sds.ifsd_map[nic_i]);
781 
782 		for (n = 0; nm_i != head; n++) {
783 			struct netmap_slot *slot = &ring->slot[nm_i];
784 			u_int len = slot->len;
785 			uint64_t paddr;
786 			void *addr = PNMB(na, slot, &paddr);
787 			int flags = (slot->flags & NS_REPORT ||
788 				nic_i == 0 || nic_i == report_frequency) ?
789 				IPI_TX_INTR : 0;
790 
791 			/* device-specific */
792 			pi.ipi_pidx = nic_i;
793 			pi.ipi_flags = flags;
794 
795 			/* Fill the slot in the NIC ring. */
796 			ctx->isc_txd_encap(ctx->ifc_softc, &pi);
797 
798 			/* prefetch for next round */
799 			__builtin_prefetch(&ring->slot[nm_i + 1]);
800 			__builtin_prefetch(&txq->ift_sds.ifsd_m[nic_i + 1]);
801 			__builtin_prefetch(&txq->ift_sds.ifsd_map[nic_i + 1]);
802 
803 			NM_CHECK_ADDR_LEN(na, addr, len);
804 
805 			if (slot->flags & NS_BUF_CHANGED) {
806 				/* buffer has changed, reload map */
807 				netmap_reload_map(na, txq->ift_desc_tag, txq->ift_sds.ifsd_map[nic_i], addr);
808 			}
809 			slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED);
810 
811 			/* make sure changes to the buffer are synced */
812 			bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_sds.ifsd_map[nic_i],
813 							BUS_DMASYNC_PREWRITE);
814 
815 			nm_i = nm_next(nm_i, lim);
816 			nic_i = nm_next(nic_i, lim);
817 		}
818 		kring->nr_hwcur = head;
819 
820 		/* synchronize the NIC ring */
821 		bus_dmamap_sync(txq->ift_desc_tag, txq->ift_ifdi->idi_map,
822 						BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
823 
824 		/* (re)start the tx unit up to slot nic_i (excluded) */
825 		ctx->isc_txd_flush(ctx->ifc_softc, txq->ift_id, nic_i);
826 	}
827 
828 	/*
829 	 * Second part: reclaim buffers for completed transmissions.
830 	 */
831 	if (iflib_tx_credits_update(ctx, txq)) {
832 		/* some tx completed, increment avail */
833 		nic_i = txq->ift_cidx_processed;
834 		kring->nr_hwtail = nm_prev(netmap_idx_n2k(kring, nic_i), lim);
835 	}
836 	return (0);
837 }
838 
839 /*
840  * Reconcile kernel and user view of the receive ring.
841  * Same as for the txsync, this routine must be efficient.
842  * The caller guarantees a single invocations, but races against
843  * the rest of the driver should be handled here.
844  *
845  * On call, kring->rhead is the first packet that userspace wants
846  * to keep, and kring->rcur is the wakeup point.
847  * The kernel has previously reported packets up to kring->rtail.
848  *
849  * If (flags & NAF_FORCE_READ) also check for incoming packets irrespective
850  * of whether or not we received an interrupt.
851  */
852 static int
853 iflib_netmap_rxsync(struct netmap_kring *kring, int flags)
854 {
855 	struct netmap_adapter *na = kring->na;
856 	struct ifnet *ifp = na->ifp;
857 	struct netmap_ring *ring = kring->ring;
858 	u_int nm_i;	/* index into the netmap ring */
859 	u_int nic_i;	/* index into the NIC ring */
860 	u_int i, n;
861 	u_int const lim = kring->nkr_num_slots - 1;
862 	u_int const head = kring->rhead;
863 	int force_update = (flags & NAF_FORCE_READ) || kring->nr_kflags & NKR_PENDINTR;
864 	struct if_rxd_info ri;
865 	/* device-specific */
866 	if_ctx_t ctx = ifp->if_softc;
867 	iflib_rxq_t rxq = &ctx->ifc_rxqs[kring->ring_id];
868 	iflib_fl_t fl = rxq->ifr_fl;
869 	if (head > lim)
870 		return netmap_ring_reinit(kring);
871 
872 	bzero(&ri, sizeof(ri));
873 	ri.iri_qsidx = kring->ring_id;
874 	ri.iri_ifp = ctx->ifc_ifp;
875 	/* XXX check sync modes */
876 	for (i = 0, fl = rxq->ifr_fl; i < rxq->ifr_nfl; i++, fl++)
877 		bus_dmamap_sync(rxq->ifr_fl[i].ifl_desc_tag, fl->ifl_ifdi->idi_map,
878 				BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
879 
880 	/*
881 	 * First part: import newly received packets.
882 	 *
883 	 * nm_i is the index of the next free slot in the netmap ring,
884 	 * nic_i is the index of the next received packet in the NIC ring,
885 	 * and they may differ in case if_init() has been called while
886 	 * in netmap mode. For the receive ring we have
887 	 *
888 	 *	nic_i = rxr->next_check;
889 	 *	nm_i = kring->nr_hwtail (previous)
890 	 * and
891 	 *	nm_i == (nic_i + kring->nkr_hwofs) % ring_size
892 	 *
893 	 * rxr->next_check is set to 0 on a ring reinit
894 	 */
895 	if (netmap_no_pendintr || force_update) {
896 		int crclen = iflib_crcstrip ? 0 : 4;
897 		int error, avail;
898 		uint16_t slot_flags = kring->nkr_slot_flags;
899 
900 		for (fl = rxq->ifr_fl, i = 0; i < rxq->ifr_nfl; i++, fl++) {
901 			nic_i = fl->ifl_cidx;
902 			nm_i = netmap_idx_n2k(kring, nic_i);
903 			avail = ctx->isc_rxd_available(ctx->ifc_softc, kring->ring_id, nic_i, INT_MAX);
904 			for (n = 0; avail > 0; n++, avail--) {
905 				error = ctx->isc_rxd_pkt_get(ctx->ifc_softc, &ri);
906 				if (error)
907 					ring->slot[nm_i].len = 0;
908 				else
909 					ring->slot[nm_i].len = ri.iri_len - crclen;
910 				ring->slot[nm_i].flags = slot_flags;
911 				bus_dmamap_sync(fl->ifl_ifdi->idi_tag,
912 								fl->ifl_sds[nic_i].ifsd_map, BUS_DMASYNC_POSTREAD);
913 				nm_i = nm_next(nm_i, lim);
914 				nic_i = nm_next(nic_i, lim);
915 			}
916 			if (n) { /* update the state variables */
917 				if (netmap_no_pendintr && !force_update) {
918 					/* diagnostics */
919 					iflib_rx_miss ++;
920 					iflib_rx_miss_bufs += n;
921 				}
922 				fl->ifl_cidx = nic_i;
923 				kring->nr_hwtail = nm_i;
924 			}
925 			kring->nr_kflags &= ~NKR_PENDINTR;
926 		}
927 	}
928 	/*
929 	 * Second part: skip past packets that userspace has released.
930 	 * (kring->nr_hwcur to head excluded),
931 	 * and make the buffers available for reception.
932 	 * As usual nm_i is the index in the netmap ring,
933 	 * nic_i is the index in the NIC ring, and
934 	 * nm_i == (nic_i + kring->nkr_hwofs) % ring_size
935 	 */
936 	/* XXX not sure how this will work with multiple free lists */
937 	nm_i = kring->nr_hwcur;
938 	if (nm_i != head) {
939 		nic_i = netmap_idx_k2n(kring, nm_i);
940 		for (n = 0; nm_i != head; n++) {
941 			struct netmap_slot *slot = &ring->slot[nm_i];
942 			uint64_t paddr;
943 			caddr_t vaddr;
944 			void *addr = PNMB(na, slot, &paddr);
945 
946 			if (addr == NETMAP_BUF_BASE(na)) /* bad buf */
947 				goto ring_reset;
948 
949 			vaddr = addr;
950 			if (slot->flags & NS_BUF_CHANGED) {
951 				/* buffer has changed, reload map */
952 				netmap_reload_map(na, fl->ifl_ifdi->idi_tag, fl->ifl_sds[nic_i].ifsd_map, addr);
953 				slot->flags &= ~NS_BUF_CHANGED;
954 			}
955 			/*
956 			 * XXX we should be batching this operation - TODO
957 			 */
958 			ctx->isc_rxd_refill(ctx->ifc_softc, rxq->ifr_id, fl->ifl_id, nic_i, &paddr, &vaddr, 1, fl->ifl_buf_size);
959 			bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_sds[nic_i].ifsd_map,
960 			    BUS_DMASYNC_PREREAD);
961 			nm_i = nm_next(nm_i, lim);
962 			nic_i = nm_next(nic_i, lim);
963 		}
964 		kring->nr_hwcur = head;
965 
966 		bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
967 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
968 		/*
969 		 * IMPORTANT: we must leave one free slot in the ring,
970 		 * so move nic_i back by one unit
971 		 */
972 		nic_i = nm_prev(nic_i, lim);
973 		ctx->isc_rxd_flush(ctx->ifc_softc, rxq->ifr_id, fl->ifl_id, nic_i);
974 	}
975 
976 	return 0;
977 
978 ring_reset:
979 	return netmap_ring_reinit(kring);
980 }
981 
982 static int
983 iflib_netmap_attach(if_ctx_t ctx)
984 {
985 	struct netmap_adapter na;
986 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
987 
988 	bzero(&na, sizeof(na));
989 
990 	na.ifp = ctx->ifc_ifp;
991 	na.na_flags = NAF_BDG_MAYSLEEP;
992 	MPASS(ctx->ifc_softc_ctx.isc_ntxqsets);
993 	MPASS(ctx->ifc_softc_ctx.isc_nrxqsets);
994 
995 	na.num_tx_desc = scctx->isc_ntxd[0];
996 	na.num_rx_desc = scctx->isc_nrxd[0];
997 	na.nm_txsync = iflib_netmap_txsync;
998 	na.nm_rxsync = iflib_netmap_rxsync;
999 	na.nm_register = iflib_netmap_register;
1000 	na.num_tx_rings = ctx->ifc_softc_ctx.isc_ntxqsets;
1001 	na.num_rx_rings = ctx->ifc_softc_ctx.isc_nrxqsets;
1002 	return (netmap_attach(&na));
1003 }
1004 
1005 static void
1006 iflib_netmap_txq_init(if_ctx_t ctx, iflib_txq_t txq)
1007 {
1008 	struct netmap_adapter *na = NA(ctx->ifc_ifp);
1009 	struct netmap_slot *slot;
1010 
1011 	slot = netmap_reset(na, NR_TX, txq->ift_id, 0);
1012 	if (slot == 0)
1013 		return;
1014 
1015 	for (int i = 0; i < ctx->ifc_softc_ctx.isc_ntxd[0]; i++) {
1016 
1017 		/*
1018 		 * In netmap mode, set the map for the packet buffer.
1019 		 * NOTE: Some drivers (not this one) also need to set
1020 		 * the physical buffer address in the NIC ring.
1021 		 * netmap_idx_n2k() maps a nic index, i, into the corresponding
1022 		 * netmap slot index, si
1023 		 */
1024 		int si = netmap_idx_n2k(&na->tx_rings[txq->ift_id], i);
1025 		netmap_load_map(na, txq->ift_desc_tag, txq->ift_sds.ifsd_map[i], NMB(na, slot + si));
1026 	}
1027 }
1028 static void
1029 iflib_netmap_rxq_init(if_ctx_t ctx, iflib_rxq_t rxq)
1030 {
1031 	struct netmap_adapter *na = NA(ctx->ifc_ifp);
1032 	struct netmap_slot *slot;
1033 	iflib_rxsd_t sd;
1034 	int nrxd;
1035 
1036 	slot = netmap_reset(na, NR_RX, rxq->ifr_id, 0);
1037 	if (slot == 0)
1038 		return;
1039 	sd = rxq->ifr_fl[0].ifl_sds;
1040 	nrxd = ctx->ifc_softc_ctx.isc_nrxd[0];
1041 	for (int i = 0; i < nrxd; i++, sd++) {
1042 			int sj = netmap_idx_n2k(&na->rx_rings[rxq->ifr_id], i);
1043 			uint64_t paddr;
1044 			void *addr;
1045 			caddr_t vaddr;
1046 
1047 			vaddr = addr = PNMB(na, slot + sj, &paddr);
1048 			netmap_load_map(na, rxq->ifr_fl[0].ifl_ifdi->idi_tag, sd->ifsd_map, addr);
1049 			/* Update descriptor and the cached value */
1050 			ctx->isc_rxd_refill(ctx->ifc_softc, rxq->ifr_id, 0 /* fl_id */, i, &paddr, &vaddr, 1, rxq->ifr_fl[0].ifl_buf_size);
1051 	}
1052 	/* preserve queue */
1053 	if (ctx->ifc_ifp->if_capenable & IFCAP_NETMAP) {
1054 		struct netmap_kring *kring = &na->rx_rings[rxq->ifr_id];
1055 		int t = na->num_rx_desc - 1 - nm_kr_rxspace(kring);
1056 		ctx->isc_rxd_flush(ctx->ifc_softc, rxq->ifr_id, 0 /* fl_id */, t);
1057 	} else
1058 		ctx->isc_rxd_flush(ctx->ifc_softc, rxq->ifr_id, 0 /* fl_id */, nrxd-1);
1059 }
1060 
1061 #define iflib_netmap_detach(ifp) netmap_detach(ifp)
1062 
1063 #else
1064 #define iflib_netmap_txq_init(ctx, txq)
1065 #define iflib_netmap_rxq_init(ctx, rxq)
1066 #define iflib_netmap_detach(ifp)
1067 
1068 #define iflib_netmap_attach(ctx) (0)
1069 #define netmap_rx_irq(ifp, qid, budget) (0)
1070 
1071 #endif
1072 
1073 #if defined(__i386__) || defined(__amd64__)
1074 static __inline void
1075 prefetch(void *x)
1076 {
1077 	__asm volatile("prefetcht0 %0" :: "m" (*(unsigned long *)x));
1078 }
1079 #else
1080 #define prefetch(x)
1081 #endif
1082 
1083 static void
1084 _iflib_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int err)
1085 {
1086 	if (err)
1087 		return;
1088 	*(bus_addr_t *) arg = segs[0].ds_addr;
1089 }
1090 
1091 int
1092 iflib_dma_alloc(if_ctx_t ctx, int size, iflib_dma_info_t dma, int mapflags)
1093 {
1094 	int err;
1095 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1096 	device_t dev = ctx->ifc_dev;
1097 
1098 	KASSERT(sctx->isc_q_align != 0, ("alignment value not initialized"));
1099 
1100 	err = bus_dma_tag_create(bus_get_dma_tag(dev), /* parent */
1101 				sctx->isc_q_align, 0,	/* alignment, bounds */
1102 				BUS_SPACE_MAXADDR,	/* lowaddr */
1103 				BUS_SPACE_MAXADDR,	/* highaddr */
1104 				NULL, NULL,		/* filter, filterarg */
1105 				size,			/* maxsize */
1106 				1,			/* nsegments */
1107 				size,			/* maxsegsize */
1108 				BUS_DMA_ALLOCNOW,	/* flags */
1109 				NULL,			/* lockfunc */
1110 				NULL,			/* lockarg */
1111 				&dma->idi_tag);
1112 	if (err) {
1113 		device_printf(dev,
1114 		    "%s: bus_dma_tag_create failed: %d\n",
1115 		    __func__, err);
1116 		goto fail_0;
1117 	}
1118 
1119 	err = bus_dmamem_alloc(dma->idi_tag, (void**) &dma->idi_vaddr,
1120 	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT | BUS_DMA_ZERO, &dma->idi_map);
1121 	if (err) {
1122 		device_printf(dev,
1123 		    "%s: bus_dmamem_alloc(%ju) failed: %d\n",
1124 		    __func__, (uintmax_t)size, err);
1125 		goto fail_1;
1126 	}
1127 
1128 	dma->idi_paddr = IF_BAD_DMA;
1129 	err = bus_dmamap_load(dma->idi_tag, dma->idi_map, dma->idi_vaddr,
1130 	    size, _iflib_dmamap_cb, &dma->idi_paddr, mapflags | BUS_DMA_NOWAIT);
1131 	if (err || dma->idi_paddr == IF_BAD_DMA) {
1132 		device_printf(dev,
1133 		    "%s: bus_dmamap_load failed: %d\n",
1134 		    __func__, err);
1135 		goto fail_2;
1136 	}
1137 
1138 	dma->idi_size = size;
1139 	return (0);
1140 
1141 fail_2:
1142 	bus_dmamem_free(dma->idi_tag, dma->idi_vaddr, dma->idi_map);
1143 fail_1:
1144 	bus_dma_tag_destroy(dma->idi_tag);
1145 fail_0:
1146 	dma->idi_tag = NULL;
1147 
1148 	return (err);
1149 }
1150 
1151 int
1152 iflib_dma_alloc_multi(if_ctx_t ctx, int *sizes, iflib_dma_info_t *dmalist, int mapflags, int count)
1153 {
1154 	int i, err;
1155 	iflib_dma_info_t *dmaiter;
1156 
1157 	dmaiter = dmalist;
1158 	for (i = 0; i < count; i++, dmaiter++) {
1159 		if ((err = iflib_dma_alloc(ctx, sizes[i], *dmaiter, mapflags)) != 0)
1160 			break;
1161 	}
1162 	if (err)
1163 		iflib_dma_free_multi(dmalist, i);
1164 	return (err);
1165 }
1166 
1167 void
1168 iflib_dma_free(iflib_dma_info_t dma)
1169 {
1170 	if (dma->idi_tag == NULL)
1171 		return;
1172 	if (dma->idi_paddr != IF_BAD_DMA) {
1173 		bus_dmamap_sync(dma->idi_tag, dma->idi_map,
1174 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1175 		bus_dmamap_unload(dma->idi_tag, dma->idi_map);
1176 		dma->idi_paddr = IF_BAD_DMA;
1177 	}
1178 	if (dma->idi_vaddr != NULL) {
1179 		bus_dmamem_free(dma->idi_tag, dma->idi_vaddr, dma->idi_map);
1180 		dma->idi_vaddr = NULL;
1181 	}
1182 	bus_dma_tag_destroy(dma->idi_tag);
1183 	dma->idi_tag = NULL;
1184 }
1185 
1186 void
1187 iflib_dma_free_multi(iflib_dma_info_t *dmalist, int count)
1188 {
1189 	int i;
1190 	iflib_dma_info_t *dmaiter = dmalist;
1191 
1192 	for (i = 0; i < count; i++, dmaiter++)
1193 		iflib_dma_free(*dmaiter);
1194 }
1195 
1196 static int
1197 iflib_fast_intr(void *arg)
1198 {
1199 	iflib_filter_info_t info = arg;
1200 	struct grouptask *gtask = info->ifi_task;
1201 
1202 	if (!smp_started && mp_ncpus > 1)
1203 		return (FILTER_HANDLED);
1204 
1205 	DBG_COUNTER_INC(fast_intrs);
1206 	if (info->ifi_filter != NULL && info->ifi_filter(info->ifi_filter_arg) == FILTER_HANDLED)
1207 		return (FILTER_HANDLED);
1208 
1209 	GROUPTASK_ENQUEUE(gtask);
1210 	return (FILTER_HANDLED);
1211 }
1212 
1213 static int
1214 _iflib_irq_alloc(if_ctx_t ctx, if_irq_t irq, int rid,
1215 	driver_filter_t filter, driver_intr_t handler, void *arg,
1216 				 char *name)
1217 {
1218 	int rc;
1219 	struct resource *res;
1220 	void *tag;
1221 	device_t dev = ctx->ifc_dev;
1222 
1223 	MPASS(rid < 512);
1224 	irq->ii_rid = rid;
1225 	res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &irq->ii_rid,
1226 				     RF_SHAREABLE | RF_ACTIVE);
1227 	if (res == NULL) {
1228 		device_printf(dev,
1229 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
1230 		return (ENOMEM);
1231 	}
1232 	irq->ii_res = res;
1233 	KASSERT(filter == NULL || handler == NULL, ("filter and handler can't both be non-NULL"));
1234 	rc = bus_setup_intr(dev, res, INTR_MPSAFE | INTR_TYPE_NET,
1235 						filter, handler, arg, &tag);
1236 	if (rc != 0) {
1237 		device_printf(dev,
1238 		    "failed to setup interrupt for rid %d, name %s: %d\n",
1239 					  rid, name ? name : "unknown", rc);
1240 		return (rc);
1241 	} else if (name)
1242 		bus_describe_intr(dev, res, tag, "%s", name);
1243 
1244 	irq->ii_tag = tag;
1245 	return (0);
1246 }
1247 
1248 
1249 /*********************************************************************
1250  *
1251  *  Allocate memory for tx_buffer structures. The tx_buffer stores all
1252  *  the information needed to transmit a packet on the wire. This is
1253  *  called only once at attach, setup is done every reset.
1254  *
1255  **********************************************************************/
1256 
1257 static int
1258 iflib_txsd_alloc(iflib_txq_t txq)
1259 {
1260 	if_ctx_t ctx = txq->ift_ctx;
1261 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1262 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1263 	device_t dev = ctx->ifc_dev;
1264 	int err, nsegments, ntsosegments;
1265 
1266 	nsegments = scctx->isc_tx_nsegments;
1267 	ntsosegments = scctx->isc_tx_tso_segments_max;
1268 	MPASS(scctx->isc_ntxd[0] > 0);
1269 	MPASS(scctx->isc_ntxd[txq->ift_br_offset] > 0);
1270 	MPASS(nsegments > 0);
1271 	MPASS(ntsosegments > 0);
1272 	/*
1273 	 * Setup DMA descriptor areas.
1274 	 */
1275 	if ((err = bus_dma_tag_create(bus_get_dma_tag(dev),
1276 			       1, 0,			/* alignment, bounds */
1277 			       BUS_SPACE_MAXADDR,	/* lowaddr */
1278 			       BUS_SPACE_MAXADDR,	/* highaddr */
1279 			       NULL, NULL,		/* filter, filterarg */
1280 			       sctx->isc_tx_maxsize,		/* maxsize */
1281 			       nsegments,	/* nsegments */
1282 			       sctx->isc_tx_maxsegsize,	/* maxsegsize */
1283 			       0,			/* flags */
1284 			       NULL,			/* lockfunc */
1285 			       NULL,			/* lockfuncarg */
1286 			       &txq->ift_desc_tag))) {
1287 		device_printf(dev,"Unable to allocate TX DMA tag: %d\n", err);
1288 		device_printf(dev,"maxsize: %zd nsegments: %d maxsegsize: %zd\n",
1289 					  sctx->isc_tx_maxsize, nsegments, sctx->isc_tx_maxsegsize);
1290 		goto fail;
1291 	}
1292 	if ((err = bus_dma_tag_create(bus_get_dma_tag(dev),
1293 			       1, 0,			/* alignment, bounds */
1294 			       BUS_SPACE_MAXADDR,	/* lowaddr */
1295 			       BUS_SPACE_MAXADDR,	/* highaddr */
1296 			       NULL, NULL,		/* filter, filterarg */
1297 			       scctx->isc_tx_tso_size_max,		/* maxsize */
1298 			       ntsosegments,	/* nsegments */
1299 			       scctx->isc_tx_tso_segsize_max,	/* maxsegsize */
1300 			       0,			/* flags */
1301 			       NULL,			/* lockfunc */
1302 			       NULL,			/* lockfuncarg */
1303 			       &txq->ift_tso_desc_tag))) {
1304 		device_printf(dev,"Unable to allocate TX TSO DMA tag: %d\n", err);
1305 
1306 		goto fail;
1307 	}
1308 	if (!(txq->ift_sds.ifsd_flags =
1309 	    (uint8_t *) malloc(sizeof(uint8_t) *
1310 	    scctx->isc_ntxd[txq->ift_br_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1311 		device_printf(dev, "Unable to allocate tx_buffer memory\n");
1312 		err = ENOMEM;
1313 		goto fail;
1314 	}
1315 	if (!(txq->ift_sds.ifsd_m =
1316 	    (struct mbuf **) malloc(sizeof(struct mbuf *) *
1317 	    scctx->isc_ntxd[txq->ift_br_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1318 		device_printf(dev, "Unable to allocate tx_buffer memory\n");
1319 		err = ENOMEM;
1320 		goto fail;
1321 	}
1322 
1323         /* Create the descriptor buffer dma maps */
1324 #if defined(ACPI_DMAR) || (!(defined(__i386__) && !defined(__amd64__)))
1325 	if ((ctx->ifc_flags & IFC_DMAR) == 0)
1326 		return (0);
1327 
1328 	if (!(txq->ift_sds.ifsd_map =
1329 	    (bus_dmamap_t *) malloc(sizeof(bus_dmamap_t) * scctx->isc_ntxd[txq->ift_br_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1330 		device_printf(dev, "Unable to allocate tx_buffer map memory\n");
1331 		err = ENOMEM;
1332 		goto fail;
1333 	}
1334 
1335 	for (int i = 0; i < scctx->isc_ntxd[txq->ift_br_offset]; i++) {
1336 		err = bus_dmamap_create(txq->ift_desc_tag, 0, &txq->ift_sds.ifsd_map[i]);
1337 		if (err != 0) {
1338 			device_printf(dev, "Unable to create TX DMA map\n");
1339 			goto fail;
1340 		}
1341 	}
1342 #endif
1343 	return (0);
1344 fail:
1345 	/* We free all, it handles case where we are in the middle */
1346 	iflib_tx_structures_free(ctx);
1347 	return (err);
1348 }
1349 
1350 static void
1351 iflib_txsd_destroy(if_ctx_t ctx, iflib_txq_t txq, int i)
1352 {
1353 	bus_dmamap_t map;
1354 
1355 	map = NULL;
1356 	if (txq->ift_sds.ifsd_map != NULL)
1357 		map = txq->ift_sds.ifsd_map[i];
1358 	if (map != NULL) {
1359 		bus_dmamap_unload(txq->ift_desc_tag, map);
1360 		bus_dmamap_destroy(txq->ift_desc_tag, map);
1361 		txq->ift_sds.ifsd_map[i] = NULL;
1362 	}
1363 }
1364 
1365 static void
1366 iflib_txq_destroy(iflib_txq_t txq)
1367 {
1368 	if_ctx_t ctx = txq->ift_ctx;
1369 
1370 	for (int i = 0; i < txq->ift_size; i++)
1371 		iflib_txsd_destroy(ctx, txq, i);
1372 	if (txq->ift_sds.ifsd_map != NULL) {
1373 		free(txq->ift_sds.ifsd_map, M_IFLIB);
1374 		txq->ift_sds.ifsd_map = NULL;
1375 	}
1376 	if (txq->ift_sds.ifsd_m != NULL) {
1377 		free(txq->ift_sds.ifsd_m, M_IFLIB);
1378 		txq->ift_sds.ifsd_m = NULL;
1379 	}
1380 	if (txq->ift_sds.ifsd_flags != NULL) {
1381 		free(txq->ift_sds.ifsd_flags, M_IFLIB);
1382 		txq->ift_sds.ifsd_flags = NULL;
1383 	}
1384 	if (txq->ift_desc_tag != NULL) {
1385 		bus_dma_tag_destroy(txq->ift_desc_tag);
1386 		txq->ift_desc_tag = NULL;
1387 	}
1388 	if (txq->ift_tso_desc_tag != NULL) {
1389 		bus_dma_tag_destroy(txq->ift_tso_desc_tag);
1390 		txq->ift_tso_desc_tag = NULL;
1391 	}
1392 }
1393 
1394 static void
1395 iflib_txsd_free(if_ctx_t ctx, iflib_txq_t txq, int i)
1396 {
1397 	struct mbuf **mp;
1398 
1399 	mp = &txq->ift_sds.ifsd_m[i];
1400 	if (*mp == NULL)
1401 		return;
1402 
1403 	if (txq->ift_sds.ifsd_map != NULL) {
1404 		bus_dmamap_sync(txq->ift_desc_tag,
1405 				txq->ift_sds.ifsd_map[i],
1406 				BUS_DMASYNC_POSTWRITE);
1407 		bus_dmamap_unload(txq->ift_desc_tag,
1408 				  txq->ift_sds.ifsd_map[i]);
1409 	}
1410 	m_free(*mp);
1411 	DBG_COUNTER_INC(tx_frees);
1412 	*mp = NULL;
1413 }
1414 
1415 static int
1416 iflib_txq_setup(iflib_txq_t txq)
1417 {
1418 	if_ctx_t ctx = txq->ift_ctx;
1419 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1420 	iflib_dma_info_t di;
1421 	int i;
1422 
1423 	/* Set number of descriptors available */
1424 	txq->ift_qstatus = IFLIB_QUEUE_IDLE;
1425 
1426 	/* Reset indices */
1427 	txq->ift_cidx_processed = txq->ift_pidx = txq->ift_cidx = txq->ift_npending = 0;
1428 	txq->ift_size = scctx->isc_ntxd[txq->ift_br_offset];
1429 
1430 	for (i = 0, di = txq->ift_ifdi; i < ctx->ifc_nhwtxqs; i++, di++)
1431 		bzero((void *)di->idi_vaddr, di->idi_size);
1432 
1433 	IFDI_TXQ_SETUP(ctx, txq->ift_id);
1434 	for (i = 0, di = txq->ift_ifdi; i < ctx->ifc_nhwtxqs; i++, di++)
1435 		bus_dmamap_sync(di->idi_tag, di->idi_map,
1436 						BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1437 	return (0);
1438 }
1439 
1440 /*********************************************************************
1441  *
1442  *  Allocate memory for rx_buffer structures. Since we use one
1443  *  rx_buffer per received packet, the maximum number of rx_buffer's
1444  *  that we'll need is equal to the number of receive descriptors
1445  *  that we've allocated.
1446  *
1447  **********************************************************************/
1448 static int
1449 iflib_rxsd_alloc(iflib_rxq_t rxq)
1450 {
1451 	if_ctx_t ctx = rxq->ifr_ctx;
1452 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1453 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1454 	device_t dev = ctx->ifc_dev;
1455 	iflib_fl_t fl;
1456 	iflib_rxsd_t	rxsd;
1457 	int			err;
1458 
1459 	MPASS(scctx->isc_nrxd[0] > 0);
1460 	MPASS(scctx->isc_nrxd[rxq->ifr_fl_offset] > 0);
1461 
1462 	fl = rxq->ifr_fl;
1463 	for (int i = 0; i <  rxq->ifr_nfl; i++, fl++) {
1464 		fl->ifl_sds = malloc(sizeof(struct iflib_sw_rx_desc) *
1465 		    scctx->isc_nrxd[rxq->ifr_fl_offset], M_IFLIB,
1466 		    M_WAITOK | M_ZERO);
1467 		if (fl->ifl_sds == NULL) {
1468 			device_printf(dev, "Unable to allocate rx sw desc memory\n");
1469 			return (ENOMEM);
1470 		}
1471 		fl->ifl_size = scctx->isc_nrxd[rxq->ifr_fl_offset]; /* this isn't necessarily the same */
1472 		err = bus_dma_tag_create(bus_get_dma_tag(dev), /* parent */
1473 					 1, 0,			/* alignment, bounds */
1474 					 BUS_SPACE_MAXADDR,	/* lowaddr */
1475 					 BUS_SPACE_MAXADDR,	/* highaddr */
1476 					 NULL, NULL,		/* filter, filterarg */
1477 					 sctx->isc_rx_maxsize,	/* maxsize */
1478 					 sctx->isc_rx_nsegments,	/* nsegments */
1479 					 sctx->isc_rx_maxsegsize,	/* maxsegsize */
1480 					 0,			/* flags */
1481 					 NULL,			/* lockfunc */
1482 					 NULL,			/* lockarg */
1483 					 &fl->ifl_desc_tag);
1484 		if (err) {
1485 			device_printf(dev, "%s: bus_dma_tag_create failed %d\n",
1486 				__func__, err);
1487 			goto fail;
1488 		}
1489 
1490 		rxsd = fl->ifl_sds;
1491 		for (int i = 0; i < scctx->isc_nrxd[rxq->ifr_fl_offset]; i++, rxsd++) {
1492 			err = bus_dmamap_create(fl->ifl_desc_tag, 0, &rxsd->ifsd_map);
1493 			if (err) {
1494 				device_printf(dev, "%s: bus_dmamap_create failed: %d\n",
1495 					__func__, err);
1496 				goto fail;
1497 			}
1498 		}
1499 	}
1500 	return (0);
1501 
1502 fail:
1503 	iflib_rx_structures_free(ctx);
1504 	return (err);
1505 }
1506 
1507 
1508 /*
1509  * Internal service routines
1510  */
1511 
1512 struct rxq_refill_cb_arg {
1513 	int               error;
1514 	bus_dma_segment_t seg;
1515 	int               nseg;
1516 };
1517 
1518 static void
1519 _rxq_refill_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1520 {
1521 	struct rxq_refill_cb_arg *cb_arg = arg;
1522 
1523 	cb_arg->error = error;
1524 	cb_arg->seg = segs[0];
1525 	cb_arg->nseg = nseg;
1526 }
1527 
1528 
1529 #ifdef ACPI_DMAR
1530 #define IS_DMAR(ctx) (ctx->ifc_flags & IFC_DMAR)
1531 #else
1532 #define IS_DMAR(ctx) (0)
1533 #endif
1534 
1535 /**
1536  *	rxq_refill - refill an rxq  free-buffer list
1537  *	@ctx: the iflib context
1538  *	@rxq: the free-list to refill
1539  *	@n: the number of new buffers to allocate
1540  *
1541  *	(Re)populate an rxq free-buffer list with up to @n new packet buffers.
1542  *	The caller must assure that @n does not exceed the queue's capacity.
1543  */
1544 static void
1545 _iflib_fl_refill(if_ctx_t ctx, iflib_fl_t fl, int count)
1546 {
1547 	struct mbuf *m;
1548 	int pidx = fl->ifl_pidx;
1549 	iflib_rxsd_t rxsd = &fl->ifl_sds[pidx];
1550 	caddr_t cl;
1551 	int n, i = 0;
1552 	uint64_t bus_addr;
1553 	int err;
1554 
1555 	n  = count;
1556 	MPASS(n > 0);
1557 	MPASS(fl->ifl_credits + n <= fl->ifl_size);
1558 
1559 	if (pidx < fl->ifl_cidx)
1560 		MPASS(pidx + n <= fl->ifl_cidx);
1561 	if (pidx == fl->ifl_cidx && (fl->ifl_credits < fl->ifl_size))
1562 		MPASS(fl->ifl_gen == 0);
1563 	if (pidx > fl->ifl_cidx)
1564 		MPASS(n <= fl->ifl_size - pidx + fl->ifl_cidx);
1565 
1566 	DBG_COUNTER_INC(fl_refills);
1567 	if (n > 8)
1568 		DBG_COUNTER_INC(fl_refills_large);
1569 
1570 	while (n--) {
1571 		/*
1572 		 * We allocate an uninitialized mbuf + cluster, mbuf is
1573 		 * initialized after rx.
1574 		 *
1575 		 * If the cluster is still set then we know a minimum sized packet was received
1576 		 */
1577 		if ((cl = rxsd->ifsd_cl) == NULL) {
1578 			if ((cl = rxsd->ifsd_cl = m_cljget(NULL, M_NOWAIT, fl->ifl_buf_size)) == NULL)
1579 				break;
1580 #if MEMORY_LOGGING
1581 			fl->ifl_cl_enqueued++;
1582 #endif
1583 		}
1584 		if ((m = m_gethdr(M_NOWAIT, MT_NOINIT)) == NULL) {
1585 			break;
1586 		}
1587 #if MEMORY_LOGGING
1588 		fl->ifl_m_enqueued++;
1589 #endif
1590 
1591 		DBG_COUNTER_INC(rx_allocs);
1592 #ifdef notyet
1593 		if ((rxsd->ifsd_flags & RX_SW_DESC_MAP_CREATED) == 0) {
1594 			int err;
1595 
1596 			if ((err = bus_dmamap_create(fl->ifl_ifdi->idi_tag, 0, &rxsd->ifsd_map))) {
1597 				log(LOG_WARNING, "bus_dmamap_create failed %d\n", err);
1598 				uma_zfree(fl->ifl_zone, cl);
1599 				n = 0;
1600 				goto done;
1601 			}
1602 			rxsd->ifsd_flags |= RX_SW_DESC_MAP_CREATED;
1603 		}
1604 #endif
1605 #if defined(__i386__) || defined(__amd64__)
1606 		if (!IS_DMAR(ctx)) {
1607 			bus_addr = pmap_kextract((vm_offset_t)cl);
1608 		} else
1609 #endif
1610 		{
1611 			struct rxq_refill_cb_arg cb_arg;
1612 			iflib_rxq_t q;
1613 
1614 			cb_arg.error = 0;
1615 			q = fl->ifl_rxq;
1616 			err = bus_dmamap_load(fl->ifl_desc_tag, rxsd->ifsd_map,
1617 		         cl, fl->ifl_buf_size, _rxq_refill_cb, &cb_arg, 0);
1618 
1619 			if (err != 0 || cb_arg.error) {
1620 				/*
1621 				 * !zone_pack ?
1622 				 */
1623 				if (fl->ifl_zone == zone_pack)
1624 					uma_zfree(fl->ifl_zone, cl);
1625 				m_free(m);
1626 				n = 0;
1627 				goto done;
1628 			}
1629 			bus_addr = cb_arg.seg.ds_addr;
1630 		}
1631 		rxsd->ifsd_flags |= RX_SW_DESC_INUSE;
1632 
1633 		MPASS(rxsd->ifsd_m == NULL);
1634 		rxsd->ifsd_cl = cl;
1635 		rxsd->ifsd_m = m;
1636 		fl->ifl_bus_addrs[i] = bus_addr;
1637 		fl->ifl_vm_addrs[i] = cl;
1638 		rxsd++;
1639 		fl->ifl_credits++;
1640 		i++;
1641 		MPASS(fl->ifl_credits <= fl->ifl_size);
1642 		if (++fl->ifl_pidx == fl->ifl_size) {
1643 			fl->ifl_pidx = 0;
1644 			fl->ifl_gen = 1;
1645 			rxsd = fl->ifl_sds;
1646 		}
1647 		if (n == 0 || i == IFLIB_MAX_RX_REFRESH) {
1648 			ctx->isc_rxd_refill(ctx->ifc_softc, fl->ifl_rxq->ifr_id, fl->ifl_id, pidx,
1649 								 fl->ifl_bus_addrs, fl->ifl_vm_addrs, i, fl->ifl_buf_size);
1650 			i = 0;
1651 			pidx = fl->ifl_pidx;
1652 		}
1653 	}
1654 done:
1655 	DBG_COUNTER_INC(rxd_flush);
1656 	if (fl->ifl_pidx == 0)
1657 		pidx = fl->ifl_size - 1;
1658 	else
1659 		pidx = fl->ifl_pidx - 1;
1660 	ctx->isc_rxd_flush(ctx->ifc_softc, fl->ifl_rxq->ifr_id, fl->ifl_id, pidx);
1661 }
1662 
1663 static __inline void
1664 __iflib_fl_refill_lt(if_ctx_t ctx, iflib_fl_t fl, int max)
1665 {
1666 	/* we avoid allowing pidx to catch up with cidx as it confuses ixl */
1667 	int32_t reclaimable = fl->ifl_size - fl->ifl_credits - 1;
1668 #ifdef INVARIANTS
1669 	int32_t delta = fl->ifl_size - get_inuse(fl->ifl_size, fl->ifl_cidx, fl->ifl_pidx, fl->ifl_gen) - 1;
1670 #endif
1671 
1672 	MPASS(fl->ifl_credits <= fl->ifl_size);
1673 	MPASS(reclaimable == delta);
1674 
1675 	if (reclaimable > 0)
1676 		_iflib_fl_refill(ctx, fl, min(max, reclaimable));
1677 }
1678 
1679 static void
1680 iflib_fl_bufs_free(iflib_fl_t fl)
1681 {
1682 	iflib_dma_info_t idi = fl->ifl_ifdi;
1683 	uint32_t i;
1684 
1685 	for (i = 0; i < fl->ifl_size; i++) {
1686 		iflib_rxsd_t d = &fl->ifl_sds[i];
1687 
1688 		if (d->ifsd_flags & RX_SW_DESC_INUSE) {
1689 			bus_dmamap_unload(fl->ifl_desc_tag, d->ifsd_map);
1690 			bus_dmamap_destroy(fl->ifl_desc_tag, d->ifsd_map);
1691 			if (d->ifsd_m != NULL) {
1692 				m_init(d->ifsd_m, M_NOWAIT, MT_DATA, 0);
1693 				uma_zfree(zone_mbuf, d->ifsd_m);
1694 			}
1695 			if (d->ifsd_cl != NULL)
1696 				uma_zfree(fl->ifl_zone, d->ifsd_cl);
1697 			d->ifsd_flags = 0;
1698 		} else {
1699 			MPASS(d->ifsd_cl == NULL);
1700 			MPASS(d->ifsd_m == NULL);
1701 		}
1702 #if MEMORY_LOGGING
1703 		fl->ifl_m_dequeued++;
1704 		fl->ifl_cl_dequeued++;
1705 #endif
1706 		d->ifsd_cl = NULL;
1707 		d->ifsd_m = NULL;
1708 	}
1709 	/*
1710 	 * Reset free list values
1711 	 */
1712 	fl->ifl_credits = fl->ifl_cidx = fl->ifl_pidx = fl->ifl_gen = 0;;
1713 	bzero(idi->idi_vaddr, idi->idi_size);
1714 }
1715 
1716 /*********************************************************************
1717  *
1718  *  Initialize a receive ring and its buffers.
1719  *
1720  **********************************************************************/
1721 static int
1722 iflib_fl_setup(iflib_fl_t fl)
1723 {
1724 	iflib_rxq_t rxq = fl->ifl_rxq;
1725 	if_ctx_t ctx = rxq->ifr_ctx;
1726 	if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
1727 
1728 	/*
1729 	** Free current RX buffer structs and their mbufs
1730 	*/
1731 	iflib_fl_bufs_free(fl);
1732 	/* Now replenish the mbufs */
1733 	MPASS(fl->ifl_credits == 0);
1734 	/*
1735 	 * XXX don't set the max_frame_size to larger
1736 	 * than the hardware can handle
1737 	 */
1738 	if (sctx->isc_max_frame_size <= 2048)
1739 		fl->ifl_buf_size = MCLBYTES;
1740 	else if (sctx->isc_max_frame_size <= 4096)
1741 		fl->ifl_buf_size = MJUMPAGESIZE;
1742 	else if (sctx->isc_max_frame_size <= 9216)
1743 		fl->ifl_buf_size = MJUM9BYTES;
1744 	else
1745 		fl->ifl_buf_size = MJUM16BYTES;
1746 	if (fl->ifl_buf_size > ctx->ifc_max_fl_buf_size)
1747 		ctx->ifc_max_fl_buf_size = fl->ifl_buf_size;
1748 	fl->ifl_cltype = m_gettype(fl->ifl_buf_size);
1749 	fl->ifl_zone = m_getzone(fl->ifl_buf_size);
1750 
1751 
1752 	/* avoid pre-allocating zillions of clusters to an idle card
1753 	 * potentially speeding up attach
1754 	 */
1755 	_iflib_fl_refill(ctx, fl, min(128, fl->ifl_size));
1756 	MPASS(min(128, fl->ifl_size) == fl->ifl_credits);
1757 	if (min(128, fl->ifl_size) != fl->ifl_credits)
1758 		return (ENOBUFS);
1759 	/*
1760 	 * handle failure
1761 	 */
1762 	MPASS(rxq != NULL);
1763 	MPASS(fl->ifl_ifdi != NULL);
1764 	bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
1765 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1766 	return (0);
1767 }
1768 
1769 /*********************************************************************
1770  *
1771  *  Free receive ring data structures
1772  *
1773  **********************************************************************/
1774 static void
1775 iflib_rx_sds_free(iflib_rxq_t rxq)
1776 {
1777 	iflib_fl_t fl;
1778 	int i;
1779 
1780 	if (rxq->ifr_fl != NULL) {
1781 		for (i = 0; i < rxq->ifr_nfl; i++) {
1782 			fl = &rxq->ifr_fl[i];
1783 			if (fl->ifl_desc_tag != NULL) {
1784 				bus_dma_tag_destroy(fl->ifl_desc_tag);
1785 				fl->ifl_desc_tag = NULL;
1786 			}
1787 		}
1788 		if (rxq->ifr_fl->ifl_sds != NULL)
1789 			free(rxq->ifr_fl->ifl_sds, M_IFLIB);
1790 
1791 		free(rxq->ifr_fl, M_IFLIB);
1792 		rxq->ifr_fl = NULL;
1793 		rxq->ifr_cq_gen = rxq->ifr_cq_cidx = rxq->ifr_cq_pidx = 0;
1794 	}
1795 }
1796 
1797 /*
1798  * MI independent logic
1799  *
1800  */
1801 static void
1802 iflib_timer(void *arg)
1803 {
1804 	iflib_txq_t txq = arg;
1805 	if_ctx_t ctx = txq->ift_ctx;
1806 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1807 
1808 	if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING))
1809 		return;
1810 	/*
1811 	** Check on the state of the TX queue(s), this
1812 	** can be done without the lock because its RO
1813 	** and the HUNG state will be static if set.
1814 	*/
1815 	IFDI_TIMER(ctx, txq->ift_id);
1816 	if ((txq->ift_qstatus == IFLIB_QUEUE_HUNG) &&
1817 		(ctx->ifc_pause_frames == 0))
1818 		goto hung;
1819 
1820 	if (TXQ_AVAIL(txq) <= 2*scctx->isc_tx_nsegments ||
1821 	    ifmp_ring_is_stalled(txq->ift_br[0]))
1822 		GROUPTASK_ENQUEUE(&txq->ift_task);
1823 
1824 	ctx->ifc_pause_frames = 0;
1825 	if (if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)
1826 		callout_reset_on(&txq->ift_timer, hz/2, iflib_timer, txq, txq->ift_timer.c_cpu);
1827 	return;
1828 hung:
1829 	CTX_LOCK(ctx);
1830 	if_setdrvflagbits(ctx->ifc_ifp, 0, IFF_DRV_RUNNING);
1831 	device_printf(ctx->ifc_dev,  "TX(%d) desc avail = %d, pidx = %d\n",
1832 				  txq->ift_id, TXQ_AVAIL(txq), txq->ift_pidx);
1833 
1834 	IFDI_WATCHDOG_RESET(ctx);
1835 	ctx->ifc_watchdog_events++;
1836 	ctx->ifc_pause_frames = 0;
1837 
1838 	iflib_init_locked(ctx);
1839 	CTX_UNLOCK(ctx);
1840 }
1841 
1842 static void
1843 iflib_init_locked(if_ctx_t ctx)
1844 {
1845 	if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
1846 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1847 	if_t ifp = ctx->ifc_ifp;
1848 	iflib_fl_t fl;
1849 	iflib_txq_t txq;
1850 	iflib_rxq_t rxq;
1851 	int i, j, tx_ip_csum_flags, tx_ip6_csum_flags;
1852 
1853 
1854 	if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
1855 	IFDI_INTR_DISABLE(ctx);
1856 
1857 	tx_ip_csum_flags = scctx->isc_tx_csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP | CSUM_SCTP);
1858 	tx_ip6_csum_flags = scctx->isc_tx_csum_flags & (CSUM_IP6_TCP | CSUM_IP6_UDP | CSUM_IP6_SCTP);
1859 	/* Set hardware offload abilities */
1860 	if_clearhwassist(ifp);
1861 	if (if_getcapenable(ifp) & IFCAP_TXCSUM)
1862 		if_sethwassistbits(ifp, tx_ip_csum_flags, 0);
1863 	if (if_getcapenable(ifp) & IFCAP_TXCSUM_IPV6)
1864 		if_sethwassistbits(ifp,  tx_ip6_csum_flags, 0);
1865 	if (if_getcapenable(ifp) & IFCAP_TSO4)
1866 		if_sethwassistbits(ifp, CSUM_IP_TSO, 0);
1867 	if (if_getcapenable(ifp) & IFCAP_TSO6)
1868 		if_sethwassistbits(ifp, CSUM_IP6_TSO, 0);
1869 
1870 	for (i = 0, txq = ctx->ifc_txqs; i < sctx->isc_ntxqsets; i++, txq++) {
1871 		CALLOUT_LOCK(txq);
1872 		callout_stop(&txq->ift_timer);
1873 		callout_stop(&txq->ift_db_check);
1874 		CALLOUT_UNLOCK(txq);
1875 		iflib_netmap_txq_init(ctx, txq);
1876 	}
1877 	for (i = 0, rxq = ctx->ifc_rxqs; i < sctx->isc_nrxqsets; i++, rxq++) {
1878 		iflib_netmap_rxq_init(ctx, rxq);
1879 	}
1880 #ifdef INVARIANTS
1881 	i = if_getdrvflags(ifp);
1882 #endif
1883 	IFDI_INIT(ctx);
1884 	MPASS(if_getdrvflags(ifp) == i);
1885 	for (i = 0, rxq = ctx->ifc_rxqs; i < sctx->isc_nrxqsets; i++, rxq++) {
1886 		for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++) {
1887 			if (iflib_fl_setup(fl)) {
1888 				device_printf(ctx->ifc_dev, "freelist setup failed - check cluster settings\n");
1889 				goto done;
1890 			}
1891 		}
1892 	}
1893 	done:
1894 	if_setdrvflagbits(ctx->ifc_ifp, IFF_DRV_RUNNING, IFF_DRV_OACTIVE);
1895 	IFDI_INTR_ENABLE(ctx);
1896 	txq = ctx->ifc_txqs;
1897 	for (i = 0; i < sctx->isc_ntxqsets; i++, txq++)
1898 		callout_reset_on(&txq->ift_timer, hz/2, iflib_timer, txq,
1899 			txq->ift_timer.c_cpu);
1900 }
1901 
1902 static int
1903 iflib_media_change(if_t ifp)
1904 {
1905 	if_ctx_t ctx = if_getsoftc(ifp);
1906 	int err;
1907 
1908 	CTX_LOCK(ctx);
1909 	if ((err = IFDI_MEDIA_CHANGE(ctx)) == 0)
1910 		iflib_init_locked(ctx);
1911 	CTX_UNLOCK(ctx);
1912 	return (err);
1913 }
1914 
1915 static void
1916 iflib_media_status(if_t ifp, struct ifmediareq *ifmr)
1917 {
1918 	if_ctx_t ctx = if_getsoftc(ifp);
1919 
1920 	CTX_LOCK(ctx);
1921 	IFDI_UPDATE_ADMIN_STATUS(ctx);
1922 	IFDI_MEDIA_STATUS(ctx, ifmr);
1923 	CTX_UNLOCK(ctx);
1924 }
1925 
1926 static void
1927 iflib_stop(if_ctx_t ctx)
1928 {
1929 	iflib_txq_t txq = ctx->ifc_txqs;
1930 	iflib_rxq_t rxq = ctx->ifc_rxqs;
1931 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1932 	iflib_dma_info_t di;
1933 	iflib_fl_t fl;
1934 	int i, j;
1935 
1936 	/* Tell the stack that the interface is no longer active */
1937 	if_setdrvflagbits(ctx->ifc_ifp, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
1938 
1939 	IFDI_INTR_DISABLE(ctx);
1940 	DELAY(100000);
1941 	IFDI_STOP(ctx);
1942 	DELAY(100000);
1943 
1944 	iflib_debug_reset();
1945 	/* Wait for current tx queue users to exit to disarm watchdog timer. */
1946 	for (i = 0; i < scctx->isc_ntxqsets; i++, txq++) {
1947 		/* make sure all transmitters have completed before proceeding XXX */
1948 
1949 		/* clean any enqueued buffers */
1950 		iflib_ifmp_purge(txq);
1951 		/* Free any existing tx buffers. */
1952 		for (j = 0; j < txq->ift_size; j++) {
1953 			iflib_txsd_free(ctx, txq, j);
1954 		}
1955 		txq->ift_processed = txq->ift_cleaned = txq->ift_cidx_processed = 0;
1956 		txq->ift_in_use = txq->ift_gen = txq->ift_cidx = txq->ift_pidx = txq->ift_no_desc_avail = 0;
1957 		txq->ift_closed = txq->ift_mbuf_defrag = txq->ift_mbuf_defrag_failed = 0;
1958 		txq->ift_no_tx_dma_setup = txq->ift_txd_encap_efbig = txq->ift_map_failed = 0;
1959 		txq->ift_pullups = 0;
1960 		ifmp_ring_reset_stats(txq->ift_br[0]);
1961 		for (j = 0, di = txq->ift_ifdi; j < ctx->ifc_nhwtxqs; j++, di++)
1962 			bzero((void *)di->idi_vaddr, di->idi_size);
1963 	}
1964 	for (i = 0; i < scctx->isc_nrxqsets; i++, rxq++) {
1965 		/* make sure all transmitters have completed before proceeding XXX */
1966 
1967 		for (j = 0, di = txq->ift_ifdi; j < ctx->ifc_nhwrxqs; j++, di++)
1968 			bzero((void *)di->idi_vaddr, di->idi_size);
1969 		/* also resets the free lists pidx/cidx */
1970 		for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++)
1971 			iflib_fl_bufs_free(fl);
1972 	}
1973 }
1974 
1975 static iflib_rxsd_t
1976 rxd_frag_to_sd(iflib_rxq_t rxq, if_rxd_frag_t irf, int *cltype, int unload)
1977 {
1978 	int flid, cidx;
1979 	iflib_rxsd_t sd;
1980 	iflib_fl_t fl;
1981 	iflib_dma_info_t di;
1982 
1983 	flid = irf->irf_flid;
1984 	cidx = irf->irf_idx;
1985 	fl = &rxq->ifr_fl[flid];
1986 	fl->ifl_credits--;
1987 #if MEMORY_LOGGING
1988 	fl->ifl_m_dequeued++;
1989 	if (cltype)
1990 		fl->ifl_cl_dequeued++;
1991 #endif
1992 	sd = &fl->ifl_sds[cidx];
1993 	di = fl->ifl_ifdi;
1994 	bus_dmamap_sync(di->idi_tag, di->idi_map,
1995 			BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1996 
1997 	/* not valid assert if bxe really does SGE from non-contiguous elements */
1998 	MPASS(fl->ifl_cidx == cidx);
1999 	if (unload)
2000 		bus_dmamap_unload(fl->ifl_desc_tag, sd->ifsd_map);
2001 
2002 	if (__predict_false(++fl->ifl_cidx == fl->ifl_size)) {
2003 		fl->ifl_cidx = 0;
2004 		fl->ifl_gen = 0;
2005 	}
2006 	/* YES ick */
2007 	if (cltype)
2008 		*cltype = fl->ifl_cltype;
2009 	return (sd);
2010 }
2011 
2012 static struct mbuf *
2013 assemble_segments(iflib_rxq_t rxq, if_rxd_info_t ri)
2014 {
2015 	int i, padlen , flags, cltype;
2016 	struct mbuf *m, *mh, *mt;
2017 	iflib_rxsd_t sd;
2018 	caddr_t cl;
2019 
2020 	i = 0;
2021 	mh = NULL;
2022 	do {
2023 		sd = rxd_frag_to_sd(rxq, &ri->iri_frags[i], &cltype, TRUE);
2024 
2025 		MPASS(sd->ifsd_cl != NULL);
2026 		MPASS(sd->ifsd_m != NULL);
2027 
2028 		/* Don't include zero-length frags */
2029 		if (ri->iri_frags[i].irf_len == 0) {
2030 			/* XXX we can save the cluster here, but not the mbuf */
2031 			m_init(sd->ifsd_m, M_NOWAIT, MT_DATA, 0);
2032 			m_free(sd->ifsd_m);
2033 			sd->ifsd_m = NULL;
2034 			continue;
2035 		}
2036 
2037 		m = sd->ifsd_m;
2038 		if (mh == NULL) {
2039 			flags = M_PKTHDR|M_EXT;
2040 			mh = mt = m;
2041 			padlen = ri->iri_pad;
2042 		} else {
2043 			flags = M_EXT;
2044 			mt->m_next = m;
2045 			mt = m;
2046 			/* assuming padding is only on the first fragment */
2047 			padlen = 0;
2048 		}
2049 		sd->ifsd_m = NULL;
2050 		cl = sd->ifsd_cl;
2051 		sd->ifsd_cl = NULL;
2052 
2053 		/* Can these two be made one ? */
2054 		m_init(m, M_NOWAIT, MT_DATA, flags);
2055 		m_cljset(m, cl, cltype);
2056 		/*
2057 		 * These must follow m_init and m_cljset
2058 		 */
2059 		m->m_data += padlen;
2060 		ri->iri_len -= padlen;
2061 		m->m_len = ri->iri_frags[i].irf_len;
2062 	} while (++i < ri->iri_nfrags);
2063 
2064 	return (mh);
2065 }
2066 
2067 /*
2068  * Process one software descriptor
2069  */
2070 static struct mbuf *
2071 iflib_rxd_pkt_get(iflib_rxq_t rxq, if_rxd_info_t ri)
2072 {
2073 	struct mbuf *m;
2074 	iflib_rxsd_t sd;
2075 
2076 	/* should I merge this back in now that the two paths are basically duplicated? */
2077 	if (ri->iri_nfrags == 1 &&
2078 	    ri->iri_frags[0].irf_len <= IFLIB_RX_COPY_THRESH) {
2079 		sd = rxd_frag_to_sd(rxq, &ri->iri_frags[0], NULL, FALSE);
2080 		m = sd->ifsd_m;
2081 		sd->ifsd_m = NULL;
2082 		m_init(m, M_NOWAIT, MT_DATA, M_PKTHDR);
2083 		memcpy(m->m_data, sd->ifsd_cl, ri->iri_len);
2084 		m->m_len = ri->iri_frags[0].irf_len;
2085        } else {
2086 		m = assemble_segments(rxq, ri);
2087 	}
2088 	m->m_pkthdr.len = ri->iri_len;
2089 	m->m_pkthdr.rcvif = ri->iri_ifp;
2090 	m->m_flags |= ri->iri_flags;
2091 	m->m_pkthdr.ether_vtag = ri->iri_vtag;
2092 	m->m_pkthdr.flowid = ri->iri_flowid;
2093 	M_HASHTYPE_SET(m, ri->iri_rsstype);
2094 	m->m_pkthdr.csum_flags = ri->iri_csum_flags;
2095 	m->m_pkthdr.csum_data = ri->iri_csum_data;
2096 	return (m);
2097 }
2098 
2099 static bool
2100 iflib_rxeof(iflib_rxq_t rxq, int budget)
2101 {
2102 	if_ctx_t ctx = rxq->ifr_ctx;
2103 	if_shared_ctx_t sctx = ctx->ifc_sctx;
2104 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
2105 	int avail, i;
2106 	uint16_t *cidxp;
2107 	struct if_rxd_info ri;
2108 	int err, budget_left, rx_bytes, rx_pkts;
2109 	iflib_fl_t fl;
2110 	struct ifnet *ifp;
2111 	int lro_enabled;
2112 	/*
2113 	 * XXX early demux data packets so that if_input processing only handles
2114 	 * acks in interrupt context
2115 	 */
2116 	struct mbuf *m, *mh, *mt;
2117 
2118 	if (netmap_rx_irq(ctx->ifc_ifp, rxq->ifr_id, &budget)) {
2119 		return (FALSE);
2120 	}
2121 
2122 	mh = mt = NULL;
2123 	MPASS(budget > 0);
2124 	rx_pkts	= rx_bytes = 0;
2125 	if (sctx->isc_flags & IFLIB_HAS_RXCQ)
2126 		cidxp = &rxq->ifr_cq_cidx;
2127 	else
2128 		cidxp = &rxq->ifr_fl[0].ifl_cidx;
2129 	if ((avail = iflib_rxd_avail(ctx, rxq, *cidxp, budget)) == 0) {
2130 		for (i = 0, fl = &rxq->ifr_fl[0]; i < sctx->isc_nfl; i++, fl++)
2131 			__iflib_fl_refill_lt(ctx, fl, budget + 8);
2132 		DBG_COUNTER_INC(rx_unavail);
2133 		return (false);
2134 	}
2135 
2136 	for (budget_left = budget; (budget_left > 0) && (avail > 0); budget_left--, avail--) {
2137 		if (__predict_false(!CTX_ACTIVE(ctx))) {
2138 			DBG_COUNTER_INC(rx_ctx_inactive);
2139 			break;
2140 		}
2141 		/*
2142 		 * Reset client set fields to their default values
2143 		 */
2144 		bzero(&ri, sizeof(ri));
2145 		ri.iri_qsidx = rxq->ifr_id;
2146 		ri.iri_cidx = *cidxp;
2147 		ri.iri_ifp = ctx->ifc_ifp;
2148 		ri.iri_frags = rxq->ifr_frags;
2149 		err = ctx->isc_rxd_pkt_get(ctx->ifc_softc, &ri);
2150 
2151 		/* in lieu of handling correctly - make sure it isn't being unhandled */
2152 		MPASS(err == 0);
2153 		if (sctx->isc_flags & IFLIB_HAS_RXCQ) {
2154 			*cidxp = ri.iri_cidx;
2155 			/* Update our consumer index */
2156 			while (rxq->ifr_cq_cidx >= scctx->isc_nrxd[0]) {
2157 				rxq->ifr_cq_cidx -= scctx->isc_nrxd[0];
2158 				rxq->ifr_cq_gen = 0;
2159 			}
2160 			/* was this only a completion queue message? */
2161 			if (__predict_false(ri.iri_nfrags == 0))
2162 				continue;
2163 		}
2164 		MPASS(ri.iri_nfrags != 0);
2165 		MPASS(ri.iri_len != 0);
2166 
2167 		/* will advance the cidx on the corresponding free lists */
2168 		m = iflib_rxd_pkt_get(rxq, &ri);
2169 		if (avail == 0 && budget_left)
2170 			avail = iflib_rxd_avail(ctx, rxq, *cidxp, budget_left);
2171 
2172 		if (__predict_false(m == NULL)) {
2173 			DBG_COUNTER_INC(rx_mbuf_null);
2174 			continue;
2175 		}
2176 		/* imm_pkt: -- cxgb */
2177 		if (mh == NULL)
2178 			mh = mt = m;
2179 		else {
2180 			mt->m_nextpkt = m;
2181 			mt = m;
2182 		}
2183 	}
2184 	/* make sure that we can refill faster than drain */
2185 	for (i = 0, fl = &rxq->ifr_fl[0]; i < sctx->isc_nfl; i++, fl++)
2186 		__iflib_fl_refill_lt(ctx, fl, budget + 8);
2187 
2188 	ifp = ctx->ifc_ifp;
2189 	lro_enabled = (if_getcapenable(ifp) & IFCAP_LRO);
2190 	while (mh != NULL) {
2191 		m = mh;
2192 		mh = mh->m_nextpkt;
2193 		m->m_nextpkt = NULL;
2194 		rx_bytes += m->m_pkthdr.len;
2195 		rx_pkts++;
2196 #if defined(INET6) || defined(INET)
2197 		if (lro_enabled && tcp_lro_rx(&rxq->ifr_lc, m, 0) == 0)
2198 			continue;
2199 #endif
2200 		DBG_COUNTER_INC(rx_if_input);
2201 		ifp->if_input(ifp, m);
2202 	}
2203 
2204 	if_inc_counter(ifp, IFCOUNTER_IBYTES, rx_bytes);
2205 	if_inc_counter(ifp, IFCOUNTER_IPACKETS, rx_pkts);
2206 
2207 	/*
2208 	 * Flush any outstanding LRO work
2209 	 */
2210 #if defined(INET6) || defined(INET)
2211 	tcp_lro_flush_all(&rxq->ifr_lc);
2212 #endif
2213 	if (avail)
2214 		return true;
2215 	return (iflib_rxd_avail(ctx, rxq, *cidxp, 1));
2216 }
2217 
2218 #define M_CSUM_FLAGS(m) ((m)->m_pkthdr.csum_flags)
2219 #define M_HAS_VLANTAG(m) (m->m_flags & M_VLANTAG)
2220 #define TXQ_MAX_DB_DEFERRED(size) (size >> 5)
2221 #define TXQ_MAX_DB_CONSUMED(size) (size >> 4)
2222 
2223 static __inline void
2224 iflib_txd_db_check(if_ctx_t ctx, iflib_txq_t txq, int ring)
2225 {
2226 	uint32_t dbval;
2227 
2228 	if (ring || txq->ift_db_pending >=
2229 	    TXQ_MAX_DB_DEFERRED(txq->ift_size)) {
2230 
2231 		/* the lock will only ever be contended in the !min_latency case */
2232 		if (!TXDB_TRYLOCK(txq))
2233 			return;
2234 		dbval = txq->ift_npending ? txq->ift_npending : txq->ift_pidx;
2235 		ctx->isc_txd_flush(ctx->ifc_softc, txq->ift_id, dbval);
2236 		txq->ift_db_pending = txq->ift_npending = 0;
2237 		TXDB_UNLOCK(txq);
2238 	}
2239 }
2240 
2241 static void
2242 iflib_txd_deferred_db_check(void * arg)
2243 {
2244 	iflib_txq_t txq = arg;
2245 
2246 	/* simple non-zero boolean so use bitwise OR */
2247 	if ((txq->ift_db_pending | txq->ift_npending) &&
2248 	    txq->ift_db_pending >= txq->ift_db_pending_queued)
2249 		iflib_txd_db_check(txq->ift_ctx, txq, TRUE);
2250 	txq->ift_db_pending_queued = 0;
2251 	if (ifmp_ring_is_stalled(txq->ift_br[0]))
2252 		iflib_txq_check_drain(txq, 4);
2253 }
2254 
2255 #ifdef PKT_DEBUG
2256 static void
2257 print_pkt(if_pkt_info_t pi)
2258 {
2259 	printf("pi len:  %d qsidx: %d nsegs: %d ndescs: %d flags: %x pidx: %d\n",
2260 	       pi->ipi_len, pi->ipi_qsidx, pi->ipi_nsegs, pi->ipi_ndescs, pi->ipi_flags, pi->ipi_pidx);
2261 	printf("pi new_pidx: %d csum_flags: %lx tso_segsz: %d mflags: %x vtag: %d\n",
2262 	       pi->ipi_new_pidx, pi->ipi_csum_flags, pi->ipi_tso_segsz, pi->ipi_mflags, pi->ipi_vtag);
2263 	printf("pi etype: %d ehdrlen: %d ip_hlen: %d ipproto: %d\n",
2264 	       pi->ipi_etype, pi->ipi_ehdrlen, pi->ipi_ip_hlen, pi->ipi_ipproto);
2265 }
2266 #endif
2267 
2268 #define IS_TSO4(pi) ((pi)->ipi_csum_flags & CSUM_IP_TSO)
2269 #define IS_TSO6(pi) ((pi)->ipi_csum_flags & CSUM_IP6_TSO)
2270 
2271 static int
2272 iflib_parse_header(iflib_txq_t txq, if_pkt_info_t pi, struct mbuf **mp)
2273 {
2274 	if_shared_ctx_t sctx = txq->ift_ctx->ifc_sctx;
2275 	struct ether_vlan_header *eh;
2276 	struct mbuf *m, *n;
2277 
2278 	n = m = *mp;
2279 	if ((sctx->isc_flags & IFLIB_NEED_SCRATCH) &&
2280 	    M_WRITABLE(m) == 0) {
2281 		if ((m = m_dup(m, M_NOWAIT)) == NULL) {
2282 			return (ENOMEM);
2283 		} else {
2284 			m_freem(*mp);
2285 			n = *mp = m;
2286 		}
2287 	}
2288 
2289 	/*
2290 	 * Determine where frame payload starts.
2291 	 * Jump over vlan headers if already present,
2292 	 * helpful for QinQ too.
2293 	 */
2294 	if (__predict_false(m->m_len < sizeof(*eh))) {
2295 		txq->ift_pullups++;
2296 		if (__predict_false((m = m_pullup(m, sizeof(*eh))) == NULL))
2297 			return (ENOMEM);
2298 	}
2299 	eh = mtod(m, struct ether_vlan_header *);
2300 	if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
2301 		pi->ipi_etype = ntohs(eh->evl_proto);
2302 		pi->ipi_ehdrlen = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
2303 	} else {
2304 		pi->ipi_etype = ntohs(eh->evl_encap_proto);
2305 		pi->ipi_ehdrlen = ETHER_HDR_LEN;
2306 	}
2307 
2308 	switch (pi->ipi_etype) {
2309 #ifdef INET
2310 	case ETHERTYPE_IP:
2311 	{
2312 		struct ip *ip = NULL;
2313 		struct tcphdr *th = NULL;
2314 		int minthlen;
2315 
2316 		minthlen = min(m->m_pkthdr.len, pi->ipi_ehdrlen + sizeof(*ip) + sizeof(*th));
2317 		if (__predict_false(m->m_len < minthlen)) {
2318 			/*
2319 			 * if this code bloat is causing too much of a hit
2320 			 * move it to a separate function and mark it noinline
2321 			 */
2322 			if (m->m_len == pi->ipi_ehdrlen) {
2323 				n = m->m_next;
2324 				MPASS(n);
2325 				if (n->m_len >= sizeof(*ip))  {
2326 					ip = (struct ip *)n->m_data;
2327 					if (n->m_len >= (ip->ip_hl << 2) + sizeof(*th))
2328 						th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2329 				} else {
2330 					txq->ift_pullups++;
2331 					if (__predict_false((m = m_pullup(m, minthlen)) == NULL))
2332 						return (ENOMEM);
2333 					ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
2334 				}
2335 			} else {
2336 				txq->ift_pullups++;
2337 				if (__predict_false((m = m_pullup(m, minthlen)) == NULL))
2338 					return (ENOMEM);
2339 				ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
2340 				if (m->m_len >= (ip->ip_hl << 2) + sizeof(*th))
2341 					th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2342 			}
2343 		} else {
2344 			ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
2345 			if (m->m_len >= (ip->ip_hl << 2) + sizeof(*th))
2346 				th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2347 		}
2348 		pi->ipi_ip_hlen = ip->ip_hl << 2;
2349 		pi->ipi_ipproto = ip->ip_p;
2350 		pi->ipi_flags |= IPI_TX_IPV4;
2351 
2352 		if (pi->ipi_csum_flags & CSUM_IP)
2353                        ip->ip_sum = 0;
2354 
2355 		if (pi->ipi_ipproto == IPPROTO_TCP) {
2356 			if (__predict_false(th == NULL)) {
2357 				txq->ift_pullups++;
2358 				if (__predict_false((m = m_pullup(m, (ip->ip_hl << 2) + sizeof(*th))) == NULL))
2359 					return (ENOMEM);
2360 				th = (struct tcphdr *)((caddr_t)ip + pi->ipi_ip_hlen);
2361 			}
2362 			pi->ipi_tcp_hflags = th->th_flags;
2363 			pi->ipi_tcp_hlen = th->th_off << 2;
2364 			pi->ipi_tcp_seq = th->th_seq;
2365 		}
2366 		if (IS_TSO4(pi)) {
2367 			if (__predict_false(ip->ip_p != IPPROTO_TCP))
2368 				return (ENXIO);
2369 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
2370 					       ip->ip_dst.s_addr, htons(IPPROTO_TCP));
2371 			pi->ipi_tso_segsz = m->m_pkthdr.tso_segsz;
2372 			if (sctx->isc_flags & IFLIB_TSO_INIT_IP) {
2373 				ip->ip_sum = 0;
2374 				ip->ip_len = htons(pi->ipi_ip_hlen + pi->ipi_tcp_hlen + pi->ipi_tso_segsz);
2375 			}
2376 		}
2377 		break;
2378 	}
2379 #endif
2380 #ifdef INET6
2381 	case ETHERTYPE_IPV6:
2382 	{
2383 		struct ip6_hdr *ip6 = (struct ip6_hdr *)(m->m_data + pi->ipi_ehdrlen);
2384 		struct tcphdr *th;
2385 		pi->ipi_ip_hlen = sizeof(struct ip6_hdr);
2386 
2387 		if (__predict_false(m->m_len < pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) {
2388 			if (__predict_false((m = m_pullup(m, pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) == NULL))
2389 				return (ENOMEM);
2390 		}
2391 		th = (struct tcphdr *)((caddr_t)ip6 + pi->ipi_ip_hlen);
2392 
2393 		/* XXX-BZ this will go badly in case of ext hdrs. */
2394 		pi->ipi_ipproto = ip6->ip6_nxt;
2395 		pi->ipi_flags |= IPI_TX_IPV6;
2396 
2397 		if (pi->ipi_ipproto == IPPROTO_TCP) {
2398 			if (__predict_false(m->m_len < pi->ipi_ehdrlen + sizeof(struct ip6_hdr) + sizeof(struct tcphdr))) {
2399 				if (__predict_false((m = m_pullup(m, pi->ipi_ehdrlen + sizeof(struct ip6_hdr) + sizeof(struct tcphdr))) == NULL))
2400 					return (ENOMEM);
2401 			}
2402 			pi->ipi_tcp_hflags = th->th_flags;
2403 			pi->ipi_tcp_hlen = th->th_off << 2;
2404 		}
2405 		if (IS_TSO6(pi)) {
2406 
2407 			if (__predict_false(ip6->ip6_nxt != IPPROTO_TCP))
2408 				return (ENXIO);
2409 			/*
2410 			 * The corresponding flag is set by the stack in the IPv4
2411 			 * TSO case, but not in IPv6 (at least in FreeBSD 10.2).
2412 			 * So, set it here because the rest of the flow requires it.
2413 			 */
2414 			pi->ipi_csum_flags |= CSUM_TCP_IPV6;
2415 			th->th_sum = in6_cksum_pseudo(ip6, 0, IPPROTO_TCP, 0);
2416 			pi->ipi_tso_segsz = m->m_pkthdr.tso_segsz;
2417 		}
2418 		break;
2419 	}
2420 #endif
2421 	default:
2422 		pi->ipi_csum_flags &= ~CSUM_OFFLOAD;
2423 		pi->ipi_ip_hlen = 0;
2424 		break;
2425 	}
2426 	*mp = m;
2427 
2428 	return (0);
2429 }
2430 
2431 static  __noinline  struct mbuf *
2432 collapse_pkthdr(struct mbuf *m0)
2433 {
2434 	struct mbuf *m, *m_next, *tmp;
2435 
2436 	m = m0;
2437 	m_next = m->m_next;
2438 	while (m_next != NULL && m_next->m_len == 0) {
2439 		m = m_next;
2440 		m->m_next = NULL;
2441 		m_free(m);
2442 		m_next = m_next->m_next;
2443 	}
2444 	m = m0;
2445 	m->m_next = m_next;
2446 	if ((m_next->m_flags & M_EXT) == 0) {
2447 		m = m_defrag(m, M_NOWAIT);
2448 	} else {
2449 		tmp = m_next->m_next;
2450 		memcpy(m_next, m, MPKTHSIZE);
2451 		m = m_next;
2452 		m->m_next = tmp;
2453 	}
2454 	return (m);
2455 }
2456 
2457 /*
2458  * If dodgy hardware rejects the scatter gather chain we've handed it
2459  * we'll need to remove the mbuf chain from ifsg_m[] before we can add the
2460  * m_defrag'd mbufs
2461  */
2462 static __noinline struct mbuf *
2463 iflib_remove_mbuf(iflib_txq_t txq)
2464 {
2465 	int ntxd, i, pidx;
2466 	struct mbuf *m, *mh, **ifsd_m;
2467 
2468 	pidx = txq->ift_pidx;
2469 	ifsd_m = txq->ift_sds.ifsd_m;
2470 	ntxd = txq->ift_size;
2471 	mh = m = ifsd_m[pidx];
2472 	ifsd_m[pidx] = NULL;
2473 #if MEMORY_LOGGING
2474 	txq->ift_dequeued++;
2475 #endif
2476 	i = 1;
2477 
2478 	while (m) {
2479 		ifsd_m[(pidx + i) & (ntxd -1)] = NULL;
2480 #if MEMORY_LOGGING
2481 		txq->ift_dequeued++;
2482 #endif
2483 		m = m->m_next;
2484 		i++;
2485 	}
2486 	return (mh);
2487 }
2488 
2489 static int
2490 iflib_busdma_load_mbuf_sg(iflib_txq_t txq, bus_dma_tag_t tag, bus_dmamap_t map,
2491 			  struct mbuf **m0, bus_dma_segment_t *segs, int *nsegs,
2492 			  int max_segs, int flags)
2493 {
2494 	if_ctx_t ctx;
2495 	if_shared_ctx_t		sctx;
2496 	if_softc_ctx_t		scctx;
2497 	int i, next, pidx, mask, err, maxsegsz, ntxd, count;
2498 	struct mbuf *m, *tmp, **ifsd_m, **mp;
2499 
2500 	m = *m0;
2501 
2502 	/*
2503 	 * Please don't ever do this
2504 	 */
2505 	if (__predict_false(m->m_len == 0))
2506 		*m0 = m = collapse_pkthdr(m);
2507 
2508 	ctx = txq->ift_ctx;
2509 	sctx = ctx->ifc_sctx;
2510 	scctx = &ctx->ifc_softc_ctx;
2511 	ifsd_m = txq->ift_sds.ifsd_m;
2512 	ntxd = txq->ift_size;
2513 	pidx = txq->ift_pidx;
2514 	if (map != NULL) {
2515 		uint8_t *ifsd_flags = txq->ift_sds.ifsd_flags;
2516 
2517 		err = bus_dmamap_load_mbuf_sg(tag, map,
2518 					      *m0, segs, nsegs, BUS_DMA_NOWAIT);
2519 		if (err)
2520 			return (err);
2521 		ifsd_flags[pidx] |= TX_SW_DESC_MAPPED;
2522 		i = 0;
2523 		next = pidx;
2524 		mask = (txq->ift_size-1);
2525 		m = *m0;
2526 		do {
2527 			mp = &ifsd_m[next];
2528 			*mp = m;
2529 			m = m->m_next;
2530 			if (__predict_false((*mp)->m_len == 0)) {
2531 				m_free(*mp);
2532 				*mp = NULL;
2533 			} else
2534 				next = (pidx + i) & (ntxd-1);
2535 		} while (m != NULL);
2536 	} else {
2537 		int buflen, sgsize, max_sgsize;
2538 		vm_offset_t vaddr;
2539 		vm_paddr_t curaddr;
2540 
2541 		count = i = 0;
2542 		maxsegsz = sctx->isc_tx_maxsize;
2543 		m = *m0;
2544 		do {
2545 			if (__predict_false(m->m_len <= 0)) {
2546 				tmp = m;
2547 				m = m->m_next;
2548 				tmp->m_next = NULL;
2549 				m_free(tmp);
2550 				continue;
2551 			}
2552 			buflen = m->m_len;
2553 			vaddr = (vm_offset_t)m->m_data;
2554 			/*
2555 			 * see if we can't be smarter about physically
2556 			 * contiguous mappings
2557 			 */
2558 			next = (pidx + count) & (ntxd-1);
2559 			MPASS(ifsd_m[next] == NULL);
2560 #if MEMORY_LOGGING
2561 			txq->ift_enqueued++;
2562 #endif
2563 			ifsd_m[next] = m;
2564 			while (buflen > 0) {
2565 				max_sgsize = MIN(buflen, maxsegsz);
2566 				curaddr = pmap_kextract(vaddr);
2567 				sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
2568 				sgsize = MIN(sgsize, max_sgsize);
2569 				segs[i].ds_addr = curaddr;
2570 				segs[i].ds_len = sgsize;
2571 				vaddr += sgsize;
2572 				buflen -= sgsize;
2573 				i++;
2574 				if (i >= max_segs)
2575 					goto err;
2576 			}
2577 			count++;
2578 			tmp = m;
2579 			m = m->m_next;
2580 		} while (m != NULL);
2581 		*nsegs = i;
2582 	}
2583 	return (0);
2584 err:
2585 	*m0 = iflib_remove_mbuf(txq);
2586 	return (EFBIG);
2587 }
2588 
2589 static int
2590 iflib_encap(iflib_txq_t txq, struct mbuf **m_headp)
2591 {
2592 	if_ctx_t		ctx;
2593 	if_shared_ctx_t		sctx;
2594 	if_softc_ctx_t		scctx;
2595 	bus_dma_segment_t	*segs;
2596 	struct mbuf		*m_head;
2597 	bus_dmamap_t		map;
2598 	struct if_pkt_info	pi;
2599 	int remap = 0;
2600 	int err, nsegs, ndesc, max_segs, pidx, cidx, next, ntxd;
2601 	bus_dma_tag_t desc_tag;
2602 
2603 	segs = txq->ift_segs;
2604 	ctx = txq->ift_ctx;
2605 	sctx = ctx->ifc_sctx;
2606 	scctx = &ctx->ifc_softc_ctx;
2607 	segs = txq->ift_segs;
2608 	ntxd = txq->ift_size;
2609 	m_head = *m_headp;
2610 	map = NULL;
2611 
2612 	/*
2613 	 * If we're doing TSO the next descriptor to clean may be quite far ahead
2614 	 */
2615 	cidx = txq->ift_cidx;
2616 	pidx = txq->ift_pidx;
2617 	next = (cidx + CACHE_PTR_INCREMENT) & (ntxd-1);
2618 
2619 	/* prefetch the next cache line of mbuf pointers and flags */
2620 	prefetch(&txq->ift_sds.ifsd_m[next]);
2621 	if (txq->ift_sds.ifsd_map != NULL) {
2622 		prefetch(&txq->ift_sds.ifsd_map[next]);
2623 		map = txq->ift_sds.ifsd_map[pidx];
2624 		next = (cidx + CACHE_LINE_SIZE) & (ntxd-1);
2625 		prefetch(&txq->ift_sds.ifsd_flags[next]);
2626 	}
2627 
2628 
2629 	if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
2630 		desc_tag = txq->ift_tso_desc_tag;
2631 		max_segs = scctx->isc_tx_tso_segments_max;
2632 	} else {
2633 		desc_tag = txq->ift_desc_tag;
2634 		max_segs = scctx->isc_tx_nsegments;
2635 	}
2636 	m_head = *m_headp;
2637 	bzero(&pi, sizeof(pi));
2638 	pi.ipi_len = m_head->m_pkthdr.len;
2639 	pi.ipi_mflags = (m_head->m_flags & (M_VLANTAG|M_BCAST|M_MCAST));
2640 	pi.ipi_csum_flags = m_head->m_pkthdr.csum_flags;
2641 	pi.ipi_vtag = (m_head->m_flags & M_VLANTAG) ? m_head->m_pkthdr.ether_vtag : 0;
2642 	pi.ipi_pidx = pidx;
2643 	pi.ipi_qsidx = txq->ift_id;
2644 
2645 	/* deliberate bitwise OR to make one condition */
2646 	if (__predict_true((pi.ipi_csum_flags | pi.ipi_vtag))) {
2647 		if (__predict_false((err = iflib_parse_header(txq, &pi, m_headp)) != 0))
2648 			return (err);
2649 		m_head = *m_headp;
2650 	}
2651 
2652 retry:
2653 	err = iflib_busdma_load_mbuf_sg(txq, desc_tag, map, m_headp, segs, &nsegs, max_segs, BUS_DMA_NOWAIT);
2654 defrag:
2655 	if (__predict_false(err)) {
2656 		switch (err) {
2657 		case EFBIG:
2658 			/* try collapse once and defrag once */
2659 			if (remap == 0)
2660 				m_head = m_collapse(*m_headp, M_NOWAIT, max_segs);
2661 			if (remap == 1)
2662 				m_head = m_defrag(*m_headp, M_NOWAIT);
2663 			remap++;
2664 			if (__predict_false(m_head == NULL))
2665 				goto defrag_failed;
2666 			txq->ift_mbuf_defrag++;
2667 			*m_headp = m_head;
2668 			goto retry;
2669 			break;
2670 		case ENOMEM:
2671 			txq->ift_no_tx_dma_setup++;
2672 			break;
2673 		default:
2674 			txq->ift_no_tx_dma_setup++;
2675 			m_freem(*m_headp);
2676 			DBG_COUNTER_INC(tx_frees);
2677 			*m_headp = NULL;
2678 			break;
2679 		}
2680 		txq->ift_map_failed++;
2681 		DBG_COUNTER_INC(encap_load_mbuf_fail);
2682 		return (err);
2683 	}
2684 
2685 	/*
2686 	 * XXX assumes a 1 to 1 relationship between segments and
2687 	 *        descriptors - this does not hold true on all drivers, e.g.
2688 	 *        cxgb
2689 	 */
2690 	if (__predict_false(nsegs + 2 > TXQ_AVAIL(txq))) {
2691 		txq->ift_no_desc_avail++;
2692 		if (map != NULL)
2693 			bus_dmamap_unload(desc_tag, map);
2694 		DBG_COUNTER_INC(encap_txq_avail_fail);
2695 		if ((txq->ift_task.gt_task.ta_flags & TASK_ENQUEUED) == 0)
2696 			GROUPTASK_ENQUEUE(&txq->ift_task);
2697 		return (ENOBUFS);
2698 	}
2699 	pi.ipi_segs = segs;
2700 	pi.ipi_nsegs = nsegs;
2701 
2702 	MPASS(pidx >= 0 && pidx < txq->ift_size);
2703 #ifdef PKT_DEBUG
2704 	print_pkt(&pi);
2705 #endif
2706 	if ((err = ctx->isc_txd_encap(ctx->ifc_softc, &pi)) == 0) {
2707 		bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
2708 						BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2709 
2710 		DBG_COUNTER_INC(tx_encap);
2711 		MPASS(pi.ipi_new_pidx >= 0 &&
2712 		    pi.ipi_new_pidx < txq->ift_size);
2713 
2714 		ndesc = pi.ipi_new_pidx - pi.ipi_pidx;
2715 		if (pi.ipi_new_pidx < pi.ipi_pidx) {
2716 			ndesc += txq->ift_size;
2717 			txq->ift_gen = 1;
2718 		}
2719 		/*
2720 		 * drivers can need as many as
2721 		 * two sentinels
2722 		 */
2723 		MPASS(ndesc <= pi.ipi_nsegs + 2);
2724 		MPASS(pi.ipi_new_pidx != pidx);
2725 		MPASS(ndesc > 0);
2726 		txq->ift_in_use += ndesc;
2727 		/*
2728 		 * We update the last software descriptor again here because there may
2729 		 * be a sentinel and/or there may be more mbufs than segments
2730 		 */
2731 		txq->ift_pidx = pi.ipi_new_pidx;
2732 		txq->ift_npending += pi.ipi_ndescs;
2733 	} else if (__predict_false(err == EFBIG && remap < 2)) {
2734 		*m_headp = m_head = iflib_remove_mbuf(txq);
2735 		remap = 1;
2736 		txq->ift_txd_encap_efbig++;
2737 		goto defrag;
2738 	} else
2739 		DBG_COUNTER_INC(encap_txd_encap_fail);
2740 	return (err);
2741 
2742 defrag_failed:
2743 	txq->ift_mbuf_defrag_failed++;
2744 	txq->ift_map_failed++;
2745 	m_freem(*m_headp);
2746 	DBG_COUNTER_INC(tx_frees);
2747 	*m_headp = NULL;
2748 	return (ENOMEM);
2749 }
2750 
2751 /* forward compatibility for cxgb */
2752 #define FIRST_QSET(ctx) 0
2753 
2754 #define NTXQSETS(ctx) ((ctx)->ifc_softc_ctx.isc_ntxqsets)
2755 #define NRXQSETS(ctx) ((ctx)->ifc_softc_ctx.isc_nrxqsets)
2756 #define QIDX(ctx, m) ((((m)->m_pkthdr.flowid & ctx->ifc_softc_ctx.isc_rss_table_mask) % NTXQSETS(ctx)) + FIRST_QSET(ctx))
2757 #define DESC_RECLAIMABLE(q) ((int)((q)->ift_processed - (q)->ift_cleaned - (q)->ift_ctx->ifc_softc_ctx.isc_tx_nsegments))
2758 #define RECLAIM_THRESH(ctx) ((ctx)->ifc_sctx->isc_tx_reclaim_thresh)
2759 #define MAX_TX_DESC(ctx) ((ctx)->ifc_softc_ctx.isc_tx_tso_segments_max)
2760 
2761 
2762 
2763 /* if there are more than TXQ_MIN_OCCUPANCY packets pending we consider deferring
2764  * doorbell writes
2765  *
2766  * ORing with 2 assures that min occupancy is never less than 2 without any conditional logic
2767  */
2768 #define TXQ_MIN_OCCUPANCY(size) ((size >> 6)| 0x2)
2769 
2770 static inline int
2771 iflib_txq_min_occupancy(iflib_txq_t txq)
2772 {
2773 	if_ctx_t ctx;
2774 
2775 	ctx = txq->ift_ctx;
2776 	return (get_inuse(txq->ift_size, txq->ift_cidx, txq->ift_pidx,
2777 	    txq->ift_gen) < TXQ_MIN_OCCUPANCY(txq->ift_size) +
2778 	    MAX_TX_DESC(ctx));
2779 }
2780 
2781 static void
2782 iflib_tx_desc_free(iflib_txq_t txq, int n)
2783 {
2784 	int hasmap;
2785 	uint32_t qsize, cidx, mask, gen;
2786 	struct mbuf *m, **ifsd_m;
2787 	uint8_t *ifsd_flags;
2788 	bus_dmamap_t *ifsd_map;
2789 
2790 	cidx = txq->ift_cidx;
2791 	gen = txq->ift_gen;
2792 	qsize = txq->ift_size;
2793 	mask = qsize-1;
2794 	hasmap = txq->ift_sds.ifsd_map != NULL;
2795 	ifsd_flags = txq->ift_sds.ifsd_flags;
2796 	ifsd_m = txq->ift_sds.ifsd_m;
2797 	ifsd_map = txq->ift_sds.ifsd_map;
2798 
2799 	while (n--) {
2800 		prefetch(ifsd_m[(cidx + 3) & mask]);
2801 		prefetch(ifsd_m[(cidx + 4) & mask]);
2802 
2803 		if (ifsd_m[cidx] != NULL) {
2804 			prefetch(&ifsd_m[(cidx + CACHE_PTR_INCREMENT) & mask]);
2805 			prefetch(&ifsd_flags[(cidx + CACHE_PTR_INCREMENT) & mask]);
2806 			if (hasmap && (ifsd_flags[cidx] & TX_SW_DESC_MAPPED)) {
2807 				/*
2808 				 * does it matter if it's not the TSO tag? If so we'll
2809 				 * have to add the type to flags
2810 				 */
2811 				bus_dmamap_unload(txq->ift_desc_tag, ifsd_map[cidx]);
2812 				ifsd_flags[cidx] &= ~TX_SW_DESC_MAPPED;
2813 			}
2814 			if ((m = ifsd_m[cidx]) != NULL) {
2815 				/* XXX we don't support any drivers that batch packets yet */
2816 				MPASS(m->m_nextpkt == NULL);
2817 
2818 				m_free(m);
2819 				ifsd_m[cidx] = NULL;
2820 #if MEMORY_LOGGING
2821 				txq->ift_dequeued++;
2822 #endif
2823 				DBG_COUNTER_INC(tx_frees);
2824 			}
2825 		}
2826 		if (__predict_false(++cidx == qsize)) {
2827 			cidx = 0;
2828 			gen = 0;
2829 		}
2830 	}
2831 	txq->ift_cidx = cidx;
2832 	txq->ift_gen = gen;
2833 }
2834 
2835 static __inline int
2836 iflib_completed_tx_reclaim(iflib_txq_t txq, int thresh)
2837 {
2838 	int reclaim;
2839 	if_ctx_t ctx = txq->ift_ctx;
2840 
2841 	KASSERT(thresh >= 0, ("invalid threshold to reclaim"));
2842 	MPASS(thresh /*+ MAX_TX_DESC(txq->ift_ctx) */ < txq->ift_size);
2843 
2844 	/*
2845 	 * Need a rate-limiting check so that this isn't called every time
2846 	 */
2847 	iflib_tx_credits_update(ctx, txq);
2848 	reclaim = DESC_RECLAIMABLE(txq);
2849 
2850 	if (reclaim <= thresh /* + MAX_TX_DESC(txq->ift_ctx) */) {
2851 #ifdef INVARIANTS
2852 		if (iflib_verbose_debug) {
2853 			printf("%s processed=%ju cleaned=%ju tx_nsegments=%d reclaim=%d thresh=%d\n", __FUNCTION__,
2854 			       txq->ift_processed, txq->ift_cleaned, txq->ift_ctx->ifc_softc_ctx.isc_tx_nsegments,
2855 			       reclaim, thresh);
2856 
2857 		}
2858 #endif
2859 		return (0);
2860 	}
2861 	iflib_tx_desc_free(txq, reclaim);
2862 	txq->ift_cleaned += reclaim;
2863 	txq->ift_in_use -= reclaim;
2864 
2865 	if (txq->ift_active == FALSE)
2866 		txq->ift_active = TRUE;
2867 
2868 	return (reclaim);
2869 }
2870 
2871 static struct mbuf **
2872 _ring_peek_one(struct ifmp_ring *r, int cidx, int offset)
2873 {
2874 
2875 	return (__DEVOLATILE(struct mbuf **, &r->items[(cidx + offset) & (r->size-1)]));
2876 }
2877 
2878 static void
2879 iflib_txq_check_drain(iflib_txq_t txq, int budget)
2880 {
2881 
2882 	ifmp_ring_check_drainage(txq->ift_br[0], budget);
2883 }
2884 
2885 static uint32_t
2886 iflib_txq_can_drain(struct ifmp_ring *r)
2887 {
2888 	iflib_txq_t txq = r->cookie;
2889 	if_ctx_t ctx = txq->ift_ctx;
2890 
2891 	return ((TXQ_AVAIL(txq) > MAX_TX_DESC(ctx) + 2) ||
2892 		ctx->isc_txd_credits_update(ctx->ifc_softc, txq->ift_id, txq->ift_cidx_processed, false));
2893 }
2894 
2895 static uint32_t
2896 iflib_txq_drain(struct ifmp_ring *r, uint32_t cidx, uint32_t pidx)
2897 {
2898 	iflib_txq_t txq = r->cookie;
2899 	if_ctx_t ctx = txq->ift_ctx;
2900 	if_t ifp = ctx->ifc_ifp;
2901 	struct mbuf **mp, *m;
2902 	int i, count, consumed, pkt_sent, bytes_sent, mcast_sent, avail, err, in_use_prev, desc_used;
2903 
2904 	if (__predict_false(!(if_getdrvflags(ifp) & IFF_DRV_RUNNING) ||
2905 			    !LINK_ACTIVE(ctx))) {
2906 		DBG_COUNTER_INC(txq_drain_notready);
2907 		return (0);
2908 	}
2909 
2910 	avail = IDXDIFF(pidx, cidx, r->size);
2911 	if (__predict_false(ctx->ifc_flags & IFC_QFLUSH)) {
2912 		DBG_COUNTER_INC(txq_drain_flushing);
2913 		for (i = 0; i < avail; i++) {
2914 			m_free(r->items[(cidx + i) & (r->size-1)]);
2915 			r->items[(cidx + i) & (r->size-1)] = NULL;
2916 		}
2917 		return (avail);
2918 	}
2919 	iflib_completed_tx_reclaim(txq, RECLAIM_THRESH(ctx));
2920 	if (__predict_false(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_OACTIVE)) {
2921 		txq->ift_qstatus = IFLIB_QUEUE_IDLE;
2922 		CALLOUT_LOCK(txq);
2923 		callout_stop(&txq->ift_timer);
2924 		callout_stop(&txq->ift_db_check);
2925 		CALLOUT_UNLOCK(txq);
2926 		DBG_COUNTER_INC(txq_drain_oactive);
2927 		return (0);
2928 	}
2929 	consumed = mcast_sent = bytes_sent = pkt_sent = 0;
2930 	count = MIN(avail, TX_BATCH_SIZE);
2931 #ifdef INVARIANTS
2932 	if (iflib_verbose_debug)
2933 		printf("%s avail=%d ifc_flags=%x txq_avail=%d ", __FUNCTION__,
2934 		       avail, ctx->ifc_flags, TXQ_AVAIL(txq));
2935 #endif
2936 
2937 	for (desc_used = i = 0; i < count && TXQ_AVAIL(txq) > MAX_TX_DESC(ctx) + 2; i++) {
2938 		mp = _ring_peek_one(r, cidx, i);
2939 		MPASS(mp != NULL && *mp != NULL);
2940 		in_use_prev = txq->ift_in_use;
2941 		if ((err = iflib_encap(txq, mp)) == ENOBUFS) {
2942 			DBG_COUNTER_INC(txq_drain_encapfail);
2943 			/* no room - bail out */
2944 			break;
2945 		}
2946 		consumed++;
2947 		if (err) {
2948 			DBG_COUNTER_INC(txq_drain_encapfail);
2949 			/* we can't send this packet - skip it */
2950 			continue;
2951 		}
2952 		pkt_sent++;
2953 		m = *mp;
2954 		DBG_COUNTER_INC(tx_sent);
2955 		bytes_sent += m->m_pkthdr.len;
2956 		if (m->m_flags & M_MCAST)
2957 			mcast_sent++;
2958 
2959 		txq->ift_db_pending += (txq->ift_in_use - in_use_prev);
2960 		desc_used += (txq->ift_in_use - in_use_prev);
2961 		iflib_txd_db_check(ctx, txq, FALSE);
2962 		ETHER_BPF_MTAP(ifp, m);
2963 		if (__predict_false(!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)))
2964 			break;
2965 
2966 		if (desc_used >= TXQ_MAX_DB_CONSUMED(txq->ift_size))
2967 			break;
2968 	}
2969 
2970 	if ((iflib_min_tx_latency || iflib_txq_min_occupancy(txq)) && txq->ift_db_pending)
2971 		iflib_txd_db_check(ctx, txq, TRUE);
2972 	else if ((txq->ift_db_pending || TXQ_AVAIL(txq) <= MAX_TX_DESC(ctx) + 2) &&
2973 		 (callout_pending(&txq->ift_db_check) == 0)) {
2974 		txq->ift_db_pending_queued = txq->ift_db_pending;
2975 		callout_reset_on(&txq->ift_db_check, 1, iflib_txd_deferred_db_check,
2976 				 txq, txq->ift_db_check.c_cpu);
2977 	}
2978 	if_inc_counter(ifp, IFCOUNTER_OBYTES, bytes_sent);
2979 	if_inc_counter(ifp, IFCOUNTER_OPACKETS, pkt_sent);
2980 	if (mcast_sent)
2981 		if_inc_counter(ifp, IFCOUNTER_OMCASTS, mcast_sent);
2982 #ifdef INVARIANTS
2983 	if (iflib_verbose_debug)
2984 		printf("consumed=%d\n", consumed);
2985 #endif
2986 	return (consumed);
2987 }
2988 
2989 static uint32_t
2990 iflib_txq_drain_always(struct ifmp_ring *r)
2991 {
2992 	return (1);
2993 }
2994 
2995 static uint32_t
2996 iflib_txq_drain_free(struct ifmp_ring *r, uint32_t cidx, uint32_t pidx)
2997 {
2998 	int i, avail;
2999 	struct mbuf **mp;
3000 	iflib_txq_t txq;
3001 
3002 	txq = r->cookie;
3003 
3004 	txq->ift_qstatus = IFLIB_QUEUE_IDLE;
3005 	CALLOUT_LOCK(txq);
3006 	callout_stop(&txq->ift_timer);
3007 	callout_stop(&txq->ift_db_check);
3008 	CALLOUT_UNLOCK(txq);
3009 
3010 	avail = IDXDIFF(pidx, cidx, r->size);
3011 	for (i = 0; i < avail; i++) {
3012 		mp = _ring_peek_one(r, cidx, i);
3013 		m_freem(*mp);
3014 	}
3015 	MPASS(ifmp_ring_is_stalled(r) == 0);
3016 	return (avail);
3017 }
3018 
3019 static void
3020 iflib_ifmp_purge(iflib_txq_t txq)
3021 {
3022 	struct ifmp_ring *r;
3023 
3024 	r = txq->ift_br[0];
3025 	r->drain = iflib_txq_drain_free;
3026 	r->can_drain = iflib_txq_drain_always;
3027 
3028 	ifmp_ring_check_drainage(r, r->size);
3029 
3030 	r->drain = iflib_txq_drain;
3031 	r->can_drain = iflib_txq_can_drain;
3032 }
3033 
3034 static void
3035 _task_fn_tx(void *context)
3036 {
3037 	iflib_txq_t txq = context;
3038 	if_ctx_t ctx = txq->ift_ctx;
3039 
3040 #ifdef IFLIB_DIAGNOSTICS
3041 	txq->ift_cpu_exec_count[curcpu]++;
3042 #endif
3043 	if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING))
3044 		return;
3045 	ifmp_ring_check_drainage(txq->ift_br[0], TX_BATCH_SIZE);
3046 }
3047 
3048 static void
3049 _task_fn_rx(void *context)
3050 {
3051 	iflib_rxq_t rxq = context;
3052 	if_ctx_t ctx = rxq->ifr_ctx;
3053 	bool more;
3054 	int rc;
3055 
3056 #ifdef IFLIB_DIAGNOSTICS
3057 	rxq->ifr_cpu_exec_count[curcpu]++;
3058 #endif
3059 	DBG_COUNTER_INC(task_fn_rxs);
3060 	if (__predict_false(!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)))
3061 		return;
3062 
3063 	if ((more = iflib_rxeof(rxq, 16 /* XXX */)) == false) {
3064 		if (ctx->ifc_flags & IFC_LEGACY)
3065 			IFDI_INTR_ENABLE(ctx);
3066 		else {
3067 			DBG_COUNTER_INC(rx_intr_enables);
3068 			rc = IFDI_QUEUE_INTR_ENABLE(ctx, rxq->ifr_id);
3069 			KASSERT(rc != ENOTSUP, ("MSI-X support requires queue_intr_enable, but not implemented in driver"));
3070 		}
3071 	}
3072 	if (__predict_false(!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)))
3073 		return;
3074 	if (more)
3075 		GROUPTASK_ENQUEUE(&rxq->ifr_task);
3076 }
3077 
3078 static void
3079 _task_fn_admin(void *context)
3080 {
3081 	if_ctx_t ctx = context;
3082 	if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
3083 	iflib_txq_t txq;
3084 	int i;
3085 
3086 	if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING))
3087 		return;
3088 
3089 	CTX_LOCK(ctx);
3090 	for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++) {
3091 		CALLOUT_LOCK(txq);
3092 		callout_stop(&txq->ift_timer);
3093 		CALLOUT_UNLOCK(txq);
3094 	}
3095 	IFDI_UPDATE_ADMIN_STATUS(ctx);
3096 	for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++)
3097 		callout_reset_on(&txq->ift_timer, hz/2, iflib_timer, txq, txq->ift_timer.c_cpu);
3098 	IFDI_LINK_INTR_ENABLE(ctx);
3099 	CTX_UNLOCK(ctx);
3100 
3101 	if (LINK_ACTIVE(ctx) == 0)
3102 		return;
3103 	for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++)
3104 		iflib_txq_check_drain(txq, IFLIB_RESTART_BUDGET);
3105 }
3106 
3107 
3108 static void
3109 _task_fn_iov(void *context)
3110 {
3111 	if_ctx_t ctx = context;
3112 
3113 	if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING))
3114 		return;
3115 
3116 	CTX_LOCK(ctx);
3117 	IFDI_VFLR_HANDLE(ctx);
3118 	CTX_UNLOCK(ctx);
3119 }
3120 
3121 static int
3122 iflib_sysctl_int_delay(SYSCTL_HANDLER_ARGS)
3123 {
3124 	int err;
3125 	if_int_delay_info_t info;
3126 	if_ctx_t ctx;
3127 
3128 	info = (if_int_delay_info_t)arg1;
3129 	ctx = info->iidi_ctx;
3130 	info->iidi_req = req;
3131 	info->iidi_oidp = oidp;
3132 	CTX_LOCK(ctx);
3133 	err = IFDI_SYSCTL_INT_DELAY(ctx, info);
3134 	CTX_UNLOCK(ctx);
3135 	return (err);
3136 }
3137 
3138 /*********************************************************************
3139  *
3140  *  IFNET FUNCTIONS
3141  *
3142  **********************************************************************/
3143 
3144 static void
3145 iflib_if_init_locked(if_ctx_t ctx)
3146 {
3147 	iflib_stop(ctx);
3148 	iflib_init_locked(ctx);
3149 }
3150 
3151 
3152 static void
3153 iflib_if_init(void *arg)
3154 {
3155 	if_ctx_t ctx = arg;
3156 
3157 	CTX_LOCK(ctx);
3158 	iflib_if_init_locked(ctx);
3159 	CTX_UNLOCK(ctx);
3160 }
3161 
3162 static int
3163 iflib_if_transmit(if_t ifp, struct mbuf *m)
3164 {
3165 	if_ctx_t	ctx = if_getsoftc(ifp);
3166 
3167 	iflib_txq_t txq;
3168 	int err, qidx;
3169 
3170 	if (__predict_false((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || !LINK_ACTIVE(ctx))) {
3171 		DBG_COUNTER_INC(tx_frees);
3172 		m_freem(m);
3173 		return (ENOBUFS);
3174 	}
3175 
3176 	MPASS(m->m_nextpkt == NULL);
3177 	qidx = 0;
3178 	if ((NTXQSETS(ctx) > 1) && M_HASHTYPE_GET(m))
3179 		qidx = QIDX(ctx, m);
3180 	/*
3181 	 * XXX calculate buf_ring based on flowid (divvy up bits?)
3182 	 */
3183 	txq = &ctx->ifc_txqs[qidx];
3184 
3185 #ifdef DRIVER_BACKPRESSURE
3186 	if (txq->ift_closed) {
3187 		while (m != NULL) {
3188 			next = m->m_nextpkt;
3189 			m->m_nextpkt = NULL;
3190 			m_freem(m);
3191 			m = next;
3192 		}
3193 		return (ENOBUFS);
3194 	}
3195 #endif
3196 #ifdef notyet
3197 	qidx = count = 0;
3198 	mp = marr;
3199 	next = m;
3200 	do {
3201 		count++;
3202 		next = next->m_nextpkt;
3203 	} while (next != NULL);
3204 
3205 	if (count > nitems(marr))
3206 		if ((mp = malloc(count*sizeof(struct mbuf *), M_IFLIB, M_NOWAIT)) == NULL) {
3207 			/* XXX check nextpkt */
3208 			m_freem(m);
3209 			/* XXX simplify for now */
3210 			DBG_COUNTER_INC(tx_frees);
3211 			return (ENOBUFS);
3212 		}
3213 	for (next = m, i = 0; next != NULL; i++) {
3214 		mp[i] = next;
3215 		next = next->m_nextpkt;
3216 		mp[i]->m_nextpkt = NULL;
3217 	}
3218 #endif
3219 	DBG_COUNTER_INC(tx_seen);
3220 	err = ifmp_ring_enqueue(txq->ift_br[0], (void **)&m, 1, TX_BATCH_SIZE);
3221 
3222 	if (err) {
3223 		GROUPTASK_ENQUEUE(&txq->ift_task);
3224 		/* support forthcoming later */
3225 #ifdef DRIVER_BACKPRESSURE
3226 		txq->ift_closed = TRUE;
3227 #endif
3228 		ifmp_ring_check_drainage(txq->ift_br[0], TX_BATCH_SIZE);
3229 		m_freem(m);
3230 	} else if (TXQ_AVAIL(txq) < (txq->ift_size >> 1)) {
3231 		GROUPTASK_ENQUEUE(&txq->ift_task);
3232 	}
3233 
3234 	return (err);
3235 }
3236 
3237 static void
3238 iflib_if_qflush(if_t ifp)
3239 {
3240 	if_ctx_t ctx = if_getsoftc(ifp);
3241 	iflib_txq_t txq = ctx->ifc_txqs;
3242 	int i;
3243 
3244 	CTX_LOCK(ctx);
3245 	ctx->ifc_flags |= IFC_QFLUSH;
3246 	CTX_UNLOCK(ctx);
3247 	for (i = 0; i < NTXQSETS(ctx); i++, txq++)
3248 		while (!(ifmp_ring_is_idle(txq->ift_br[0]) || ifmp_ring_is_stalled(txq->ift_br[0])))
3249 			iflib_txq_check_drain(txq, 0);
3250 	CTX_LOCK(ctx);
3251 	ctx->ifc_flags &= ~IFC_QFLUSH;
3252 	CTX_UNLOCK(ctx);
3253 
3254 	if_qflush(ifp);
3255 }
3256 
3257 
3258 #define IFCAP_FLAGS (IFCAP_TXCSUM_IPV6 | IFCAP_RXCSUM_IPV6 | IFCAP_HWCSUM | IFCAP_LRO | \
3259 		     IFCAP_TSO4 | IFCAP_TSO6 | IFCAP_VLAN_HWTAGGING |	\
3260 		     IFCAP_VLAN_MTU | IFCAP_VLAN_HWFILTER | IFCAP_VLAN_HWTSO)
3261 
3262 static int
3263 iflib_if_ioctl(if_t ifp, u_long command, caddr_t data)
3264 {
3265 	if_ctx_t ctx = if_getsoftc(ifp);
3266 	struct ifreq	*ifr = (struct ifreq *)data;
3267 #if defined(INET) || defined(INET6)
3268 	struct ifaddr	*ifa = (struct ifaddr *)data;
3269 #endif
3270 	bool		avoid_reset = FALSE;
3271 	int		err = 0, reinit = 0, bits;
3272 
3273 	switch (command) {
3274 	case SIOCSIFADDR:
3275 #ifdef INET
3276 		if (ifa->ifa_addr->sa_family == AF_INET)
3277 			avoid_reset = TRUE;
3278 #endif
3279 #ifdef INET6
3280 		if (ifa->ifa_addr->sa_family == AF_INET6)
3281 			avoid_reset = TRUE;
3282 #endif
3283 		/*
3284 		** Calling init results in link renegotiation,
3285 		** so we avoid doing it when possible.
3286 		*/
3287 		if (avoid_reset) {
3288 			if_setflagbits(ifp, IFF_UP,0);
3289 			if (!(if_getdrvflags(ifp)& IFF_DRV_RUNNING))
3290 				reinit = 1;
3291 #ifdef INET
3292 			if (!(if_getflags(ifp) & IFF_NOARP))
3293 				arp_ifinit(ifp, ifa);
3294 #endif
3295 		} else
3296 			err = ether_ioctl(ifp, command, data);
3297 		break;
3298 	case SIOCSIFMTU:
3299 		CTX_LOCK(ctx);
3300 		if (ifr->ifr_mtu == if_getmtu(ifp)) {
3301 			CTX_UNLOCK(ctx);
3302 			break;
3303 		}
3304 		bits = if_getdrvflags(ifp);
3305 		/* stop the driver and free any clusters before proceeding */
3306 		iflib_stop(ctx);
3307 
3308 		if ((err = IFDI_MTU_SET(ctx, ifr->ifr_mtu)) == 0) {
3309 			if (ifr->ifr_mtu > ctx->ifc_max_fl_buf_size)
3310 				ctx->ifc_flags |= IFC_MULTISEG;
3311 			else
3312 				ctx->ifc_flags &= ~IFC_MULTISEG;
3313 			err = if_setmtu(ifp, ifr->ifr_mtu);
3314 		}
3315 		iflib_init_locked(ctx);
3316 		if_setdrvflags(ifp, bits);
3317 		CTX_UNLOCK(ctx);
3318 		break;
3319 	case SIOCSIFFLAGS:
3320 		CTX_LOCK(ctx);
3321 		if (if_getflags(ifp) & IFF_UP) {
3322 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3323 				if ((if_getflags(ifp) ^ ctx->ifc_if_flags) &
3324 				    (IFF_PROMISC | IFF_ALLMULTI)) {
3325 					err = IFDI_PROMISC_SET(ctx, if_getflags(ifp));
3326 				}
3327 			} else
3328 				reinit = 1;
3329 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3330 			iflib_stop(ctx);
3331 		}
3332 		ctx->ifc_if_flags = if_getflags(ifp);
3333 		CTX_UNLOCK(ctx);
3334 		break;
3335 
3336 		break;
3337 	case SIOCADDMULTI:
3338 	case SIOCDELMULTI:
3339 		if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3340 			CTX_LOCK(ctx);
3341 			IFDI_INTR_DISABLE(ctx);
3342 			IFDI_MULTI_SET(ctx);
3343 			IFDI_INTR_ENABLE(ctx);
3344 			CTX_UNLOCK(ctx);
3345 		}
3346 		break;
3347 	case SIOCSIFMEDIA:
3348 		CTX_LOCK(ctx);
3349 		IFDI_MEDIA_SET(ctx);
3350 		CTX_UNLOCK(ctx);
3351 		/* falls thru */
3352 	case SIOCGIFMEDIA:
3353 		err = ifmedia_ioctl(ifp, ifr, &ctx->ifc_media, command);
3354 		break;
3355 	case SIOCGI2C:
3356 	{
3357 		struct ifi2creq i2c;
3358 
3359 		err = copyin(ifr->ifr_data, &i2c, sizeof(i2c));
3360 		if (err != 0)
3361 			break;
3362 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3363 			err = EINVAL;
3364 			break;
3365 		}
3366 		if (i2c.len > sizeof(i2c.data)) {
3367 			err = EINVAL;
3368 			break;
3369 		}
3370 
3371 		if ((err = IFDI_I2C_REQ(ctx, &i2c)) == 0)
3372 			err = copyout(&i2c, ifr->ifr_data, sizeof(i2c));
3373 		break;
3374 	}
3375 	case SIOCSIFCAP:
3376 	{
3377 		int mask, setmask;
3378 
3379 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
3380 		setmask = 0;
3381 #ifdef TCP_OFFLOAD
3382 		setmask |= mask & (IFCAP_TOE4|IFCAP_TOE6);
3383 #endif
3384 		setmask |= (mask & IFCAP_FLAGS);
3385 
3386 		if (setmask  & (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6))
3387 			setmask |= (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
3388 		if ((mask & IFCAP_WOL) &&
3389 		    (if_getcapabilities(ifp) & IFCAP_WOL) != 0)
3390 			setmask |= (mask & (IFCAP_WOL_MCAST|IFCAP_WOL_MAGIC));
3391 		if_vlancap(ifp);
3392 		/*
3393 		 * want to ensure that traffic has stopped before we change any of the flags
3394 		 */
3395 		if (setmask) {
3396 			CTX_LOCK(ctx);
3397 			bits = if_getdrvflags(ifp);
3398 			if (bits & IFF_DRV_RUNNING)
3399 				iflib_stop(ctx);
3400 			if_togglecapenable(ifp, setmask);
3401 			if (bits & IFF_DRV_RUNNING)
3402 				iflib_init_locked(ctx);
3403 			if_setdrvflags(ifp, bits);
3404 			CTX_UNLOCK(ctx);
3405 		}
3406 		break;
3407 	    }
3408 	case SIOCGPRIVATE_0:
3409 	case SIOCSDRVSPEC:
3410 	case SIOCGDRVSPEC:
3411 		CTX_LOCK(ctx);
3412 		err = IFDI_PRIV_IOCTL(ctx, command, data);
3413 		CTX_UNLOCK(ctx);
3414 		break;
3415 	default:
3416 		err = ether_ioctl(ifp, command, data);
3417 		break;
3418 	}
3419 	if (reinit)
3420 		iflib_if_init(ctx);
3421 	return (err);
3422 }
3423 
3424 static uint64_t
3425 iflib_if_get_counter(if_t ifp, ift_counter cnt)
3426 {
3427 	if_ctx_t ctx = if_getsoftc(ifp);
3428 
3429 	return (IFDI_GET_COUNTER(ctx, cnt));
3430 }
3431 
3432 /*********************************************************************
3433  *
3434  *  OTHER FUNCTIONS EXPORTED TO THE STACK
3435  *
3436  **********************************************************************/
3437 
3438 static void
3439 iflib_vlan_register(void *arg, if_t ifp, uint16_t vtag)
3440 {
3441 	if_ctx_t ctx = if_getsoftc(ifp);
3442 
3443 	if ((void *)ctx != arg)
3444 		return;
3445 
3446 	if ((vtag == 0) || (vtag > 4095))
3447 		return;
3448 
3449 	CTX_LOCK(ctx);
3450 	IFDI_VLAN_REGISTER(ctx, vtag);
3451 	/* Re-init to load the changes */
3452 	if (if_getcapenable(ifp) & IFCAP_VLAN_HWFILTER)
3453 		iflib_init_locked(ctx);
3454 	CTX_UNLOCK(ctx);
3455 }
3456 
3457 static void
3458 iflib_vlan_unregister(void *arg, if_t ifp, uint16_t vtag)
3459 {
3460 	if_ctx_t ctx = if_getsoftc(ifp);
3461 
3462 	if ((void *)ctx != arg)
3463 		return;
3464 
3465 	if ((vtag == 0) || (vtag > 4095))
3466 		return;
3467 
3468 	CTX_LOCK(ctx);
3469 	IFDI_VLAN_UNREGISTER(ctx, vtag);
3470 	/* Re-init to load the changes */
3471 	if (if_getcapenable(ifp) & IFCAP_VLAN_HWFILTER)
3472 		iflib_init_locked(ctx);
3473 	CTX_UNLOCK(ctx);
3474 }
3475 
3476 static void
3477 iflib_led_func(void *arg, int onoff)
3478 {
3479 	if_ctx_t ctx = arg;
3480 
3481 	CTX_LOCK(ctx);
3482 	IFDI_LED_FUNC(ctx, onoff);
3483 	CTX_UNLOCK(ctx);
3484 }
3485 
3486 /*********************************************************************
3487  *
3488  *  BUS FUNCTION DEFINITIONS
3489  *
3490  **********************************************************************/
3491 
3492 int
3493 iflib_device_probe(device_t dev)
3494 {
3495 	pci_vendor_info_t *ent;
3496 
3497 	uint16_t	pci_vendor_id, pci_device_id;
3498 	uint16_t	pci_subvendor_id, pci_subdevice_id;
3499 	uint16_t	pci_rev_id;
3500 	if_shared_ctx_t sctx;
3501 
3502 	if ((sctx = DEVICE_REGISTER(dev)) == NULL || sctx->isc_magic != IFLIB_MAGIC)
3503 		return (ENOTSUP);
3504 
3505 	pci_vendor_id = pci_get_vendor(dev);
3506 	pci_device_id = pci_get_device(dev);
3507 	pci_subvendor_id = pci_get_subvendor(dev);
3508 	pci_subdevice_id = pci_get_subdevice(dev);
3509 	pci_rev_id = pci_get_revid(dev);
3510 	if (sctx->isc_parse_devinfo != NULL)
3511 		sctx->isc_parse_devinfo(&pci_device_id, &pci_subvendor_id, &pci_subdevice_id, &pci_rev_id);
3512 
3513 	ent = sctx->isc_vendor_info;
3514 	while (ent->pvi_vendor_id != 0) {
3515 		if (pci_vendor_id != ent->pvi_vendor_id) {
3516 			ent++;
3517 			continue;
3518 		}
3519 		if ((pci_device_id == ent->pvi_device_id) &&
3520 		    ((pci_subvendor_id == ent->pvi_subvendor_id) ||
3521 		     (ent->pvi_subvendor_id == 0)) &&
3522 		    ((pci_subdevice_id == ent->pvi_subdevice_id) ||
3523 		     (ent->pvi_subdevice_id == 0)) &&
3524 		    ((pci_rev_id == ent->pvi_rev_id) ||
3525 		     (ent->pvi_rev_id == 0))) {
3526 
3527 			device_set_desc_copy(dev, ent->pvi_name);
3528 			/* this needs to be changed to zero if the bus probing code
3529 			 * ever stops re-probing on best match because the sctx
3530 			 * may have its values over written by register calls
3531 			 * in subsequent probes
3532 			 */
3533 			return (BUS_PROBE_DEFAULT);
3534 		}
3535 		ent++;
3536 	}
3537 	return (ENXIO);
3538 }
3539 
3540 int
3541 iflib_device_register(device_t dev, void *sc, if_shared_ctx_t sctx, if_ctx_t *ctxp)
3542 {
3543 	int err, rid, msix, msix_bar;
3544 	if_ctx_t ctx;
3545 	if_t ifp;
3546 	if_softc_ctx_t scctx;
3547 	int i;
3548 	uint16_t main_txq;
3549 	uint16_t main_rxq;
3550 
3551 
3552 	ctx = malloc(sizeof(* ctx), M_IFLIB, M_WAITOK|M_ZERO);
3553 
3554 	if (sc == NULL) {
3555 		sc = malloc(sctx->isc_driver->size, M_IFLIB, M_WAITOK|M_ZERO);
3556 		device_set_softc(dev, ctx);
3557 		ctx->ifc_flags |= IFC_SC_ALLOCATED;
3558 	}
3559 
3560 	ctx->ifc_sctx = sctx;
3561 	ctx->ifc_dev = dev;
3562 	ctx->ifc_softc = sc;
3563 
3564 	if ((err = iflib_register(ctx)) != 0) {
3565 		device_printf(dev, "iflib_register failed %d\n", err);
3566 		return (err);
3567 	}
3568 	iflib_add_device_sysctl_pre(ctx);
3569 
3570 	scctx = &ctx->ifc_softc_ctx;
3571 	ifp = ctx->ifc_ifp;
3572 
3573 	/*
3574 	 * XXX sanity check that ntxd & nrxd are a power of 2
3575 	 */
3576 	if (ctx->ifc_sysctl_ntxqs != 0)
3577 		scctx->isc_ntxqsets = ctx->ifc_sysctl_ntxqs;
3578 	if (ctx->ifc_sysctl_nrxqs != 0)
3579 		scctx->isc_nrxqsets = ctx->ifc_sysctl_nrxqs;
3580 
3581 	for (i = 0; i < sctx->isc_ntxqs; i++) {
3582 		if (ctx->ifc_sysctl_ntxds[i] != 0)
3583 			scctx->isc_ntxd[i] = ctx->ifc_sysctl_ntxds[i];
3584 		else
3585 			scctx->isc_ntxd[i] = sctx->isc_ntxd_default[i];
3586 	}
3587 
3588 	for (i = 0; i < sctx->isc_nrxqs; i++) {
3589 		if (ctx->ifc_sysctl_nrxds[i] != 0)
3590 			scctx->isc_nrxd[i] = ctx->ifc_sysctl_nrxds[i];
3591 		else
3592 			scctx->isc_nrxd[i] = sctx->isc_nrxd_default[i];
3593 	}
3594 
3595 	for (i = 0; i < sctx->isc_nrxqs; i++) {
3596 		if (scctx->isc_nrxd[i] < sctx->isc_nrxd_min[i]) {
3597 			device_printf(dev, "nrxd%d: %d less than nrxd_min %d - resetting to min\n",
3598 				      i, scctx->isc_nrxd[i], sctx->isc_nrxd_min[i]);
3599 			scctx->isc_nrxd[i] = sctx->isc_nrxd_min[i];
3600 		}
3601 		if (scctx->isc_nrxd[i] > sctx->isc_nrxd_max[i]) {
3602 			device_printf(dev, "nrxd%d: %d greater than nrxd_max %d - resetting to max\n",
3603 				      i, scctx->isc_nrxd[i], sctx->isc_nrxd_max[i]);
3604 			scctx->isc_nrxd[i] = sctx->isc_nrxd_max[i];
3605 		}
3606 	}
3607 
3608 	for (i = 0; i < sctx->isc_ntxqs; i++) {
3609 		if (scctx->isc_ntxd[i] < sctx->isc_ntxd_min[i]) {
3610 			device_printf(dev, "ntxd%d: %d less than ntxd_min %d - resetting to min\n",
3611 				      i, scctx->isc_ntxd[i], sctx->isc_ntxd_min[i]);
3612 			scctx->isc_ntxd[i] = sctx->isc_ntxd_min[i];
3613 		}
3614 		if (scctx->isc_ntxd[i] > sctx->isc_ntxd_max[i]) {
3615 			device_printf(dev, "ntxd%d: %d greater than ntxd_max %d - resetting to max\n",
3616 				      i, scctx->isc_ntxd[i], sctx->isc_ntxd_max[i]);
3617 			scctx->isc_ntxd[i] = sctx->isc_ntxd_max[i];
3618 		}
3619 	}
3620 
3621 	if ((err = IFDI_ATTACH_PRE(ctx)) != 0) {
3622 		device_printf(dev, "IFDI_ATTACH_PRE failed %d\n", err);
3623 		return (err);
3624 	}
3625 	_iflib_pre_assert(scctx);
3626 	ctx->ifc_txrx = *scctx->isc_txrx;
3627 
3628 #ifdef INVARIANTS
3629 	MPASS(scctx->isc_capenable);
3630 	if (scctx->isc_capenable & IFCAP_TXCSUM)
3631 		MPASS(scctx->isc_tx_csum_flags);
3632 #endif
3633 
3634 	if_setcapabilities(ifp, scctx->isc_capenable);
3635 	if_setcapenable(ifp, scctx->isc_capenable);
3636 
3637 	if (scctx->isc_ntxqsets == 0 || (scctx->isc_ntxqsets_max && scctx->isc_ntxqsets_max < scctx->isc_ntxqsets))
3638 		scctx->isc_ntxqsets = scctx->isc_ntxqsets_max;
3639 	if (scctx->isc_nrxqsets == 0 || (scctx->isc_nrxqsets_max && scctx->isc_nrxqsets_max < scctx->isc_nrxqsets))
3640 		scctx->isc_nrxqsets = scctx->isc_nrxqsets_max;
3641 
3642 #ifdef ACPI_DMAR
3643 	if (dmar_get_dma_tag(device_get_parent(dev), dev) != NULL)
3644 		ctx->ifc_flags |= IFC_DMAR;
3645 #endif
3646 
3647 	msix_bar = scctx->isc_msix_bar;
3648 
3649 	if(sctx->isc_flags & IFLIB_HAS_TXCQ)
3650 		main_txq = 1;
3651 	else
3652 		main_txq = 0;
3653 
3654 	if(sctx->isc_flags & IFLIB_HAS_RXCQ)
3655 		main_rxq = 1;
3656 	else
3657 		main_rxq = 0;
3658 
3659 	/* XXX change for per-queue sizes */
3660 	device_printf(dev, "using %d tx descriptors and %d rx descriptors\n",
3661 		      scctx->isc_ntxd[main_txq], scctx->isc_nrxd[main_rxq]);
3662 	for (i = 0; i < sctx->isc_nrxqs; i++) {
3663 		if (!powerof2(scctx->isc_nrxd[i])) {
3664 			/* round down instead? */
3665 			device_printf(dev, "# rx descriptors must be a power of 2\n");
3666 			err = EINVAL;
3667 			goto fail;
3668 		}
3669 	}
3670 	for (i = 0; i < sctx->isc_ntxqs; i++) {
3671 		if (!powerof2(scctx->isc_ntxd[i])) {
3672 			device_printf(dev,
3673 			    "# tx descriptors must be a power of 2");
3674 			err = EINVAL;
3675 			goto fail;
3676 		}
3677 	}
3678 
3679 	if (scctx->isc_tx_nsegments > scctx->isc_ntxd[main_txq] /
3680 	    MAX_SINGLE_PACKET_FRACTION)
3681 		scctx->isc_tx_nsegments = max(1, scctx->isc_ntxd[main_txq] /
3682 		    MAX_SINGLE_PACKET_FRACTION);
3683 	if (scctx->isc_tx_tso_segments_max > scctx->isc_ntxd[main_txq] /
3684 	    MAX_SINGLE_PACKET_FRACTION)
3685 		scctx->isc_tx_tso_segments_max = max(1,
3686 		    scctx->isc_ntxd[main_txq] / MAX_SINGLE_PACKET_FRACTION);
3687 
3688 	/*
3689 	 * Protect the stack against modern hardware
3690 	 */
3691 	if (scctx->isc_tx_tso_size_max > FREEBSD_TSO_SIZE_MAX)
3692 		scctx->isc_tx_tso_size_max = FREEBSD_TSO_SIZE_MAX;
3693 
3694 	/* TSO parameters - dig these out of the data sheet - simply correspond to tag setup */
3695 	ifp->if_hw_tsomaxsegcount = scctx->isc_tx_tso_segments_max;
3696 	ifp->if_hw_tsomax = scctx->isc_tx_tso_size_max;
3697 	ifp->if_hw_tsomaxsegsize = scctx->isc_tx_tso_segsize_max;
3698 	if (scctx->isc_rss_table_size == 0)
3699 		scctx->isc_rss_table_size = 64;
3700 	scctx->isc_rss_table_mask = scctx->isc_rss_table_size-1;
3701 
3702 	GROUPTASK_INIT(&ctx->ifc_admin_task, 0, _task_fn_admin, ctx);
3703 	/* XXX format name */
3704 	taskqgroup_attach(qgroup_if_config_tqg, &ctx->ifc_admin_task, ctx, -1, "admin");
3705 	/*
3706 	** Now setup MSI or MSI/X, should
3707 	** return us the number of supported
3708 	** vectors. (Will be 1 for MSI)
3709 	*/
3710 	if (sctx->isc_flags & IFLIB_SKIP_MSIX) {
3711 		msix = scctx->isc_vectors;
3712 	} else if (scctx->isc_msix_bar != 0)
3713 		msix = iflib_msix_init(ctx);
3714 	else {
3715 		scctx->isc_vectors = 1;
3716 		scctx->isc_ntxqsets = 1;
3717 		scctx->isc_nrxqsets = 1;
3718 		scctx->isc_intr = IFLIB_INTR_LEGACY;
3719 		msix = 0;
3720 	}
3721 	/* Get memory for the station queues */
3722 	if ((err = iflib_queues_alloc(ctx))) {
3723 		device_printf(dev, "Unable to allocate queue memory\n");
3724 		goto fail;
3725 	}
3726 
3727 	if ((err = iflib_qset_structures_setup(ctx))) {
3728 		device_printf(dev, "qset structure setup failed %d\n", err);
3729 		goto fail_queues;
3730 	}
3731 
3732 	IFDI_INTR_DISABLE(ctx);
3733 	if (msix > 1 && (err = IFDI_MSIX_INTR_ASSIGN(ctx, msix)) != 0) {
3734 		device_printf(dev, "IFDI_MSIX_INTR_ASSIGN failed %d\n", err);
3735 		goto fail_intr_free;
3736 	}
3737 	if (msix <= 1) {
3738 		rid = 0;
3739 		if (scctx->isc_intr == IFLIB_INTR_MSI) {
3740 			MPASS(msix == 1);
3741 			rid = 1;
3742 		}
3743 		if ((err = iflib_legacy_setup(ctx, ctx->isc_legacy_intr, ctx->ifc_softc, &rid, "irq0")) != 0) {
3744 			device_printf(dev, "iflib_legacy_setup failed %d\n", err);
3745 			goto fail_intr_free;
3746 		}
3747 	}
3748 	ether_ifattach(ctx->ifc_ifp, ctx->ifc_mac);
3749 	if ((err = IFDI_ATTACH_POST(ctx)) != 0) {
3750 		device_printf(dev, "IFDI_ATTACH_POST failed %d\n", err);
3751 		goto fail_detach;
3752 	}
3753 	if ((err = iflib_netmap_attach(ctx))) {
3754 		device_printf(ctx->ifc_dev, "netmap attach failed: %d\n", err);
3755 		goto fail_detach;
3756 	}
3757 	*ctxp = ctx;
3758 
3759 	if_setgetcounterfn(ctx->ifc_ifp, iflib_if_get_counter);
3760 	iflib_add_device_sysctl_post(ctx);
3761 	ctx->ifc_flags |= IFC_INIT_DONE;
3762 	return (0);
3763 fail_detach:
3764 	ether_ifdetach(ctx->ifc_ifp);
3765 fail_intr_free:
3766 	if (scctx->isc_intr == IFLIB_INTR_MSIX || scctx->isc_intr == IFLIB_INTR_MSI)
3767 		pci_release_msi(ctx->ifc_dev);
3768 fail_queues:
3769 	/* XXX free queues */
3770 fail:
3771 	IFDI_DETACH(ctx);
3772 	return (err);
3773 }
3774 
3775 int
3776 iflib_device_attach(device_t dev)
3777 {
3778 	if_ctx_t ctx;
3779 	if_shared_ctx_t sctx;
3780 
3781 	if ((sctx = DEVICE_REGISTER(dev)) == NULL || sctx->isc_magic != IFLIB_MAGIC)
3782 		return (ENOTSUP);
3783 
3784 	pci_enable_busmaster(dev);
3785 
3786 	return (iflib_device_register(dev, NULL, sctx, &ctx));
3787 }
3788 
3789 int
3790 iflib_device_deregister(if_ctx_t ctx)
3791 {
3792 	if_t ifp = ctx->ifc_ifp;
3793 	iflib_txq_t txq;
3794 	iflib_rxq_t rxq;
3795 	device_t dev = ctx->ifc_dev;
3796 	int i;
3797 	struct taskqgroup *tqg;
3798 
3799 	/* Make sure VLANS are not using driver */
3800 	if (if_vlantrunkinuse(ifp)) {
3801 		device_printf(dev,"Vlan in use, detach first\n");
3802 		return (EBUSY);
3803 	}
3804 
3805 	CTX_LOCK(ctx);
3806 	ctx->ifc_in_detach = 1;
3807 	iflib_stop(ctx);
3808 	CTX_UNLOCK(ctx);
3809 
3810 	/* Unregister VLAN events */
3811 	if (ctx->ifc_vlan_attach_event != NULL)
3812 		EVENTHANDLER_DEREGISTER(vlan_config, ctx->ifc_vlan_attach_event);
3813 	if (ctx->ifc_vlan_detach_event != NULL)
3814 		EVENTHANDLER_DEREGISTER(vlan_unconfig, ctx->ifc_vlan_detach_event);
3815 
3816 	iflib_netmap_detach(ifp);
3817 	ether_ifdetach(ifp);
3818 	/* ether_ifdetach calls if_qflush - lock must be destroy afterwards*/
3819 	CTX_LOCK_DESTROY(ctx);
3820 	if (ctx->ifc_led_dev != NULL)
3821 		led_destroy(ctx->ifc_led_dev);
3822 	/* XXX drain any dependent tasks */
3823 	tqg = qgroup_if_io_tqg;
3824 	for (txq = ctx->ifc_txqs, i = 0; i < NTXQSETS(ctx); i++, txq++) {
3825 		callout_drain(&txq->ift_timer);
3826 		callout_drain(&txq->ift_db_check);
3827 		if (txq->ift_task.gt_uniq != NULL)
3828 			taskqgroup_detach(tqg, &txq->ift_task);
3829 	}
3830 	for (i = 0, rxq = ctx->ifc_rxqs; i < NRXQSETS(ctx); i++, rxq++) {
3831 		if (rxq->ifr_task.gt_uniq != NULL)
3832 			taskqgroup_detach(tqg, &rxq->ifr_task);
3833 	}
3834 	tqg = qgroup_if_config_tqg;
3835 	if (ctx->ifc_admin_task.gt_uniq != NULL)
3836 		taskqgroup_detach(tqg, &ctx->ifc_admin_task);
3837 	if (ctx->ifc_vflr_task.gt_uniq != NULL)
3838 		taskqgroup_detach(tqg, &ctx->ifc_vflr_task);
3839 
3840 	IFDI_DETACH(ctx);
3841 	device_set_softc(ctx->ifc_dev, NULL);
3842 	if (ctx->ifc_softc_ctx.isc_intr != IFLIB_INTR_LEGACY) {
3843 		pci_release_msi(dev);
3844 	}
3845 	if (ctx->ifc_softc_ctx.isc_intr != IFLIB_INTR_MSIX) {
3846 		iflib_irq_free(ctx, &ctx->ifc_legacy_irq);
3847 	}
3848 	if (ctx->ifc_msix_mem != NULL) {
3849 		bus_release_resource(ctx->ifc_dev, SYS_RES_MEMORY,
3850 			ctx->ifc_softc_ctx.isc_msix_bar, ctx->ifc_msix_mem);
3851 		ctx->ifc_msix_mem = NULL;
3852 	}
3853 
3854 	bus_generic_detach(dev);
3855 	if_free(ifp);
3856 
3857 	iflib_tx_structures_free(ctx);
3858 	iflib_rx_structures_free(ctx);
3859 	if (ctx->ifc_flags & IFC_SC_ALLOCATED)
3860 		free(ctx->ifc_softc, M_IFLIB);
3861 	free(ctx, M_IFLIB);
3862 	return (0);
3863 }
3864 
3865 
3866 int
3867 iflib_device_detach(device_t dev)
3868 {
3869 	if_ctx_t ctx = device_get_softc(dev);
3870 
3871 	return (iflib_device_deregister(ctx));
3872 }
3873 
3874 int
3875 iflib_device_suspend(device_t dev)
3876 {
3877 	if_ctx_t ctx = device_get_softc(dev);
3878 
3879 	CTX_LOCK(ctx);
3880 	IFDI_SUSPEND(ctx);
3881 	CTX_UNLOCK(ctx);
3882 
3883 	return bus_generic_suspend(dev);
3884 }
3885 int
3886 iflib_device_shutdown(device_t dev)
3887 {
3888 	if_ctx_t ctx = device_get_softc(dev);
3889 
3890 	CTX_LOCK(ctx);
3891 	IFDI_SHUTDOWN(ctx);
3892 	CTX_UNLOCK(ctx);
3893 
3894 	return bus_generic_suspend(dev);
3895 }
3896 
3897 
3898 int
3899 iflib_device_resume(device_t dev)
3900 {
3901 	if_ctx_t ctx = device_get_softc(dev);
3902 	iflib_txq_t txq = ctx->ifc_txqs;
3903 
3904 	CTX_LOCK(ctx);
3905 	IFDI_RESUME(ctx);
3906 	iflib_init_locked(ctx);
3907 	CTX_UNLOCK(ctx);
3908 	for (int i = 0; i < NTXQSETS(ctx); i++, txq++)
3909 		iflib_txq_check_drain(txq, IFLIB_RESTART_BUDGET);
3910 
3911 	return (bus_generic_resume(dev));
3912 }
3913 
3914 int
3915 iflib_device_iov_init(device_t dev, uint16_t num_vfs, const nvlist_t *params)
3916 {
3917 	int error;
3918 	if_ctx_t ctx = device_get_softc(dev);
3919 
3920 	CTX_LOCK(ctx);
3921 	error = IFDI_IOV_INIT(ctx, num_vfs, params);
3922 	CTX_UNLOCK(ctx);
3923 
3924 	return (error);
3925 }
3926 
3927 void
3928 iflib_device_iov_uninit(device_t dev)
3929 {
3930 	if_ctx_t ctx = device_get_softc(dev);
3931 
3932 	CTX_LOCK(ctx);
3933 	IFDI_IOV_UNINIT(ctx);
3934 	CTX_UNLOCK(ctx);
3935 }
3936 
3937 int
3938 iflib_device_iov_add_vf(device_t dev, uint16_t vfnum, const nvlist_t *params)
3939 {
3940 	int error;
3941 	if_ctx_t ctx = device_get_softc(dev);
3942 
3943 	CTX_LOCK(ctx);
3944 	error = IFDI_IOV_VF_ADD(ctx, vfnum, params);
3945 	CTX_UNLOCK(ctx);
3946 
3947 	return (error);
3948 }
3949 
3950 /*********************************************************************
3951  *
3952  *  MODULE FUNCTION DEFINITIONS
3953  *
3954  **********************************************************************/
3955 
3956 /*
3957  * - Start a fast taskqueue thread for each core
3958  * - Start a taskqueue for control operations
3959  */
3960 static int
3961 iflib_module_init(void)
3962 {
3963 	return (0);
3964 }
3965 
3966 static int
3967 iflib_module_event_handler(module_t mod, int what, void *arg)
3968 {
3969 	int err;
3970 
3971 	switch (what) {
3972 	case MOD_LOAD:
3973 		if ((err = iflib_module_init()) != 0)
3974 			return (err);
3975 		break;
3976 	case MOD_UNLOAD:
3977 		return (EBUSY);
3978 	default:
3979 		return (EOPNOTSUPP);
3980 	}
3981 
3982 	return (0);
3983 }
3984 
3985 /*********************************************************************
3986  *
3987  *  PUBLIC FUNCTION DEFINITIONS
3988  *     ordered as in iflib.h
3989  *
3990  **********************************************************************/
3991 
3992 
3993 static void
3994 _iflib_assert(if_shared_ctx_t sctx)
3995 {
3996 	MPASS(sctx->isc_tx_maxsize);
3997 	MPASS(sctx->isc_tx_maxsegsize);
3998 
3999 	MPASS(sctx->isc_rx_maxsize);
4000 	MPASS(sctx->isc_rx_nsegments);
4001 	MPASS(sctx->isc_rx_maxsegsize);
4002 
4003 	MPASS(sctx->isc_nrxd_min[0]);
4004 	MPASS(sctx->isc_nrxd_max[0]);
4005 	MPASS(sctx->isc_nrxd_default[0]);
4006 	MPASS(sctx->isc_ntxd_min[0]);
4007 	MPASS(sctx->isc_ntxd_max[0]);
4008 	MPASS(sctx->isc_ntxd_default[0]);
4009 }
4010 
4011 static void
4012 _iflib_pre_assert(if_softc_ctx_t scctx)
4013 {
4014 
4015 	MPASS(scctx->isc_txrx->ift_txd_encap);
4016 	MPASS(scctx->isc_txrx->ift_txd_flush);
4017 	MPASS(scctx->isc_txrx->ift_txd_credits_update);
4018 	MPASS(scctx->isc_txrx->ift_rxd_available);
4019 	MPASS(scctx->isc_txrx->ift_rxd_pkt_get);
4020 	MPASS(scctx->isc_txrx->ift_rxd_refill);
4021 	MPASS(scctx->isc_txrx->ift_rxd_flush);
4022 }
4023 
4024 static int
4025 iflib_register(if_ctx_t ctx)
4026 {
4027 	if_shared_ctx_t sctx = ctx->ifc_sctx;
4028 	driver_t *driver = sctx->isc_driver;
4029 	device_t dev = ctx->ifc_dev;
4030 	if_t ifp;
4031 
4032 	_iflib_assert(sctx);
4033 
4034 	CTX_LOCK_INIT(ctx, device_get_nameunit(ctx->ifc_dev));
4035 
4036 	ifp = ctx->ifc_ifp = if_gethandle(IFT_ETHER);
4037 	if (ifp == NULL) {
4038 		device_printf(dev, "can not allocate ifnet structure\n");
4039 		return (ENOMEM);
4040 	}
4041 
4042 	/*
4043 	 * Initialize our context's device specific methods
4044 	 */
4045 	kobj_init((kobj_t) ctx, (kobj_class_t) driver);
4046 	kobj_class_compile((kobj_class_t) driver);
4047 	driver->refs++;
4048 
4049 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
4050 	if_setsoftc(ifp, ctx);
4051 	if_setdev(ifp, dev);
4052 	if_setinitfn(ifp, iflib_if_init);
4053 	if_setioctlfn(ifp, iflib_if_ioctl);
4054 	if_settransmitfn(ifp, iflib_if_transmit);
4055 	if_setqflushfn(ifp, iflib_if_qflush);
4056 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
4057 
4058 	ctx->ifc_vlan_attach_event =
4059 		EVENTHANDLER_REGISTER(vlan_config, iflib_vlan_register, ctx,
4060 							  EVENTHANDLER_PRI_FIRST);
4061 	ctx->ifc_vlan_detach_event =
4062 		EVENTHANDLER_REGISTER(vlan_unconfig, iflib_vlan_unregister, ctx,
4063 							  EVENTHANDLER_PRI_FIRST);
4064 
4065 	ifmedia_init(&ctx->ifc_media, IFM_IMASK,
4066 					 iflib_media_change, iflib_media_status);
4067 
4068 	return (0);
4069 }
4070 
4071 
4072 static int
4073 iflib_queues_alloc(if_ctx_t ctx)
4074 {
4075 	if_shared_ctx_t sctx = ctx->ifc_sctx;
4076 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
4077 	device_t dev = ctx->ifc_dev;
4078 	int nrxqsets = scctx->isc_nrxqsets;
4079 	int ntxqsets = scctx->isc_ntxqsets;
4080 	iflib_txq_t txq;
4081 	iflib_rxq_t rxq;
4082 	iflib_fl_t fl = NULL;
4083 	int i, j, cpu, err, txconf, rxconf;
4084 	iflib_dma_info_t ifdip;
4085 	uint32_t *rxqsizes = scctx->isc_rxqsizes;
4086 	uint32_t *txqsizes = scctx->isc_txqsizes;
4087 	uint8_t nrxqs = sctx->isc_nrxqs;
4088 	uint8_t ntxqs = sctx->isc_ntxqs;
4089 	int nfree_lists = sctx->isc_nfl ? sctx->isc_nfl : 1;
4090 	caddr_t *vaddrs;
4091 	uint64_t *paddrs;
4092 	struct ifmp_ring **brscp;
4093 	int nbuf_rings = 1; /* XXX determine dynamically */
4094 
4095 	KASSERT(ntxqs > 0, ("number of queues per qset must be at least 1"));
4096 	KASSERT(nrxqs > 0, ("number of queues per qset must be at least 1"));
4097 
4098 	brscp = NULL;
4099 	txq = NULL;
4100 	rxq = NULL;
4101 
4102 /* Allocate the TX ring struct memory */
4103 	if (!(txq =
4104 	    (iflib_txq_t) malloc(sizeof(struct iflib_txq) *
4105 	    ntxqsets, M_IFLIB, M_NOWAIT | M_ZERO))) {
4106 		device_printf(dev, "Unable to allocate TX ring memory\n");
4107 		err = ENOMEM;
4108 		goto fail;
4109 	}
4110 
4111 	/* Now allocate the RX */
4112 	if (!(rxq =
4113 	    (iflib_rxq_t) malloc(sizeof(struct iflib_rxq) *
4114 	    nrxqsets, M_IFLIB, M_NOWAIT | M_ZERO))) {
4115 		device_printf(dev, "Unable to allocate RX ring memory\n");
4116 		err = ENOMEM;
4117 		goto rx_fail;
4118 	}
4119 	if (!(brscp = malloc(sizeof(void *) * nbuf_rings * nrxqsets, M_IFLIB, M_NOWAIT | M_ZERO))) {
4120 		device_printf(dev, "Unable to buf_ring_sc * memory\n");
4121 		err = ENOMEM;
4122 		goto rx_fail;
4123 	}
4124 
4125 	ctx->ifc_txqs = txq;
4126 	ctx->ifc_rxqs = rxq;
4127 
4128 	/*
4129 	 * XXX handle allocation failure
4130 	 */
4131 	for (txconf = i = 0, cpu = CPU_FIRST(); i < ntxqsets; i++, txconf++, txq++, cpu = CPU_NEXT(cpu)) {
4132 		/* Set up some basics */
4133 
4134 		if ((ifdip = malloc(sizeof(struct iflib_dma_info) * ntxqs, M_IFLIB, M_WAITOK|M_ZERO)) == NULL) {
4135 			device_printf(dev, "failed to allocate iflib_dma_info\n");
4136 			err = ENOMEM;
4137 			goto err_tx_desc;
4138 		}
4139 		txq->ift_ifdi = ifdip;
4140 		for (j = 0; j < ntxqs; j++, ifdip++) {
4141 			if (iflib_dma_alloc(ctx, txqsizes[j], ifdip, BUS_DMA_NOWAIT)) {
4142 				device_printf(dev, "Unable to allocate Descriptor memory\n");
4143 				err = ENOMEM;
4144 				goto err_tx_desc;
4145 			}
4146 			bzero((void *)ifdip->idi_vaddr, txqsizes[j]);
4147 		}
4148 		txq->ift_ctx = ctx;
4149 		txq->ift_id = i;
4150 		if (sctx->isc_flags & IFLIB_HAS_TXCQ) {
4151 			txq->ift_br_offset = 1;
4152 		} else {
4153 			txq->ift_br_offset = 0;
4154 		}
4155 		/* XXX fix this */
4156 		txq->ift_timer.c_cpu = cpu;
4157 		txq->ift_db_check.c_cpu = cpu;
4158 		txq->ift_nbr = nbuf_rings;
4159 
4160 		if (iflib_txsd_alloc(txq)) {
4161 			device_printf(dev, "Critical Failure setting up TX buffers\n");
4162 			err = ENOMEM;
4163 			goto err_tx_desc;
4164 		}
4165 
4166 		/* Initialize the TX lock */
4167 		snprintf(txq->ift_mtx_name, MTX_NAME_LEN, "%s:tx(%d):callout",
4168 		    device_get_nameunit(dev), txq->ift_id);
4169 		mtx_init(&txq->ift_mtx, txq->ift_mtx_name, NULL, MTX_DEF);
4170 		callout_init_mtx(&txq->ift_timer, &txq->ift_mtx, 0);
4171 		callout_init_mtx(&txq->ift_db_check, &txq->ift_mtx, 0);
4172 
4173 		snprintf(txq->ift_db_mtx_name, MTX_NAME_LEN, "%s:tx(%d):db",
4174 			 device_get_nameunit(dev), txq->ift_id);
4175 		TXDB_LOCK_INIT(txq);
4176 
4177 		txq->ift_br = brscp + i*nbuf_rings;
4178 		for (j = 0; j < nbuf_rings; j++) {
4179 			err = ifmp_ring_alloc(&txq->ift_br[j], 2048, txq, iflib_txq_drain,
4180 					      iflib_txq_can_drain, M_IFLIB, M_WAITOK);
4181 			if (err) {
4182 				/* XXX free any allocated rings */
4183 				device_printf(dev, "Unable to allocate buf_ring\n");
4184 				goto err_tx_desc;
4185 			}
4186 		}
4187 	}
4188 
4189 	for (rxconf = i = 0; i < nrxqsets; i++, rxconf++, rxq++) {
4190 		/* Set up some basics */
4191 
4192 		if ((ifdip = malloc(sizeof(struct iflib_dma_info) * nrxqs, M_IFLIB, M_WAITOK|M_ZERO)) == NULL) {
4193 			device_printf(dev, "failed to allocate iflib_dma_info\n");
4194 			err = ENOMEM;
4195 			goto err_tx_desc;
4196 		}
4197 
4198 		rxq->ifr_ifdi = ifdip;
4199 		for (j = 0; j < nrxqs; j++, ifdip++) {
4200 			if (iflib_dma_alloc(ctx, rxqsizes[j], ifdip, BUS_DMA_NOWAIT)) {
4201 				device_printf(dev, "Unable to allocate Descriptor memory\n");
4202 				err = ENOMEM;
4203 				goto err_tx_desc;
4204 			}
4205 			bzero((void *)ifdip->idi_vaddr, rxqsizes[j]);
4206 		}
4207 		rxq->ifr_ctx = ctx;
4208 		rxq->ifr_id = i;
4209 		if (sctx->isc_flags & IFLIB_HAS_RXCQ) {
4210 			rxq->ifr_fl_offset = 1;
4211 		} else {
4212 			rxq->ifr_fl_offset = 0;
4213 		}
4214 		rxq->ifr_nfl = nfree_lists;
4215 		if (!(fl =
4216 			  (iflib_fl_t) malloc(sizeof(struct iflib_fl) * nfree_lists, M_IFLIB, M_NOWAIT | M_ZERO))) {
4217 			device_printf(dev, "Unable to allocate free list memory\n");
4218 			err = ENOMEM;
4219 			goto err_tx_desc;
4220 		}
4221 		rxq->ifr_fl = fl;
4222 		for (j = 0; j < nfree_lists; j++) {
4223 			rxq->ifr_fl[j].ifl_rxq = rxq;
4224 			rxq->ifr_fl[j].ifl_id = j;
4225 			rxq->ifr_fl[j].ifl_ifdi =
4226 			    &rxq->ifr_ifdi[j + rxq->ifr_fl_offset];
4227 		}
4228         /* Allocate receive buffers for the ring*/
4229 		if (iflib_rxsd_alloc(rxq)) {
4230 			device_printf(dev,
4231 			    "Critical Failure setting up receive buffers\n");
4232 			err = ENOMEM;
4233 			goto err_rx_desc;
4234 		}
4235 	}
4236 
4237 	/* TXQs */
4238 	vaddrs = malloc(sizeof(caddr_t)*ntxqsets*ntxqs, M_IFLIB, M_WAITOK);
4239 	paddrs = malloc(sizeof(uint64_t)*ntxqsets*ntxqs, M_IFLIB, M_WAITOK);
4240 	for (i = 0; i < ntxqsets; i++) {
4241 		iflib_dma_info_t di = ctx->ifc_txqs[i].ift_ifdi;
4242 
4243 		for (j = 0; j < ntxqs; j++, di++) {
4244 			vaddrs[i*ntxqs + j] = di->idi_vaddr;
4245 			paddrs[i*ntxqs + j] = di->idi_paddr;
4246 		}
4247 	}
4248 	if ((err = IFDI_TX_QUEUES_ALLOC(ctx, vaddrs, paddrs, ntxqs, ntxqsets)) != 0) {
4249 		device_printf(ctx->ifc_dev, "device queue allocation failed\n");
4250 		iflib_tx_structures_free(ctx);
4251 		free(vaddrs, M_IFLIB);
4252 		free(paddrs, M_IFLIB);
4253 		goto err_rx_desc;
4254 	}
4255 	free(vaddrs, M_IFLIB);
4256 	free(paddrs, M_IFLIB);
4257 
4258 	/* RXQs */
4259 	vaddrs = malloc(sizeof(caddr_t)*nrxqsets*nrxqs, M_IFLIB, M_WAITOK);
4260 	paddrs = malloc(sizeof(uint64_t)*nrxqsets*nrxqs, M_IFLIB, M_WAITOK);
4261 	for (i = 0; i < nrxqsets; i++) {
4262 		iflib_dma_info_t di = ctx->ifc_rxqs[i].ifr_ifdi;
4263 
4264 		for (j = 0; j < nrxqs; j++, di++) {
4265 			vaddrs[i*nrxqs + j] = di->idi_vaddr;
4266 			paddrs[i*nrxqs + j] = di->idi_paddr;
4267 		}
4268 	}
4269 	if ((err = IFDI_RX_QUEUES_ALLOC(ctx, vaddrs, paddrs, nrxqs, nrxqsets)) != 0) {
4270 		device_printf(ctx->ifc_dev, "device queue allocation failed\n");
4271 		iflib_tx_structures_free(ctx);
4272 		free(vaddrs, M_IFLIB);
4273 		free(paddrs, M_IFLIB);
4274 		goto err_rx_desc;
4275 	}
4276 	free(vaddrs, M_IFLIB);
4277 	free(paddrs, M_IFLIB);
4278 
4279 	return (0);
4280 
4281 /* XXX handle allocation failure changes */
4282 err_rx_desc:
4283 err_tx_desc:
4284 	if (ctx->ifc_rxqs != NULL)
4285 		free(ctx->ifc_rxqs, M_IFLIB);
4286 	ctx->ifc_rxqs = NULL;
4287 	if (ctx->ifc_txqs != NULL)
4288 		free(ctx->ifc_txqs, M_IFLIB);
4289 	ctx->ifc_txqs = NULL;
4290 rx_fail:
4291 	if (brscp != NULL)
4292 		free(brscp, M_IFLIB);
4293 	if (rxq != NULL)
4294 		free(rxq, M_IFLIB);
4295 	if (txq != NULL)
4296 		free(txq, M_IFLIB);
4297 fail:
4298 	return (err);
4299 }
4300 
4301 static int
4302 iflib_tx_structures_setup(if_ctx_t ctx)
4303 {
4304 	iflib_txq_t txq = ctx->ifc_txqs;
4305 	int i;
4306 
4307 	for (i = 0; i < NTXQSETS(ctx); i++, txq++)
4308 		iflib_txq_setup(txq);
4309 
4310 	return (0);
4311 }
4312 
4313 static void
4314 iflib_tx_structures_free(if_ctx_t ctx)
4315 {
4316 	iflib_txq_t txq = ctx->ifc_txqs;
4317 	int i, j;
4318 
4319 	for (i = 0; i < NTXQSETS(ctx); i++, txq++) {
4320 		iflib_txq_destroy(txq);
4321 		for (j = 0; j < ctx->ifc_nhwtxqs; j++)
4322 			iflib_dma_free(&txq->ift_ifdi[j]);
4323 	}
4324 	free(ctx->ifc_txqs, M_IFLIB);
4325 	ctx->ifc_txqs = NULL;
4326 	IFDI_QUEUES_FREE(ctx);
4327 }
4328 
4329 /*********************************************************************
4330  *
4331  *  Initialize all receive rings.
4332  *
4333  **********************************************************************/
4334 static int
4335 iflib_rx_structures_setup(if_ctx_t ctx)
4336 {
4337 	iflib_rxq_t rxq = ctx->ifc_rxqs;
4338 	int q;
4339 #if defined(INET6) || defined(INET)
4340 	int i, err;
4341 #endif
4342 
4343 	for (q = 0; q < ctx->ifc_softc_ctx.isc_nrxqsets; q++, rxq++) {
4344 #if defined(INET6) || defined(INET)
4345 		tcp_lro_free(&rxq->ifr_lc);
4346 		if ((err = tcp_lro_init_args(&rxq->ifr_lc, ctx->ifc_ifp,
4347 		    TCP_LRO_ENTRIES, min(1024,
4348 		    ctx->ifc_softc_ctx.isc_nrxd[rxq->ifr_fl_offset]))) != 0) {
4349 			device_printf(ctx->ifc_dev, "LRO Initialization failed!\n");
4350 			goto fail;
4351 		}
4352 		rxq->ifr_lro_enabled = TRUE;
4353 #endif
4354 		IFDI_RXQ_SETUP(ctx, rxq->ifr_id);
4355 	}
4356 	return (0);
4357 #if defined(INET6) || defined(INET)
4358 fail:
4359 	/*
4360 	 * Free RX software descriptors allocated so far, we will only handle
4361 	 * the rings that completed, the failing case will have
4362 	 * cleaned up for itself. 'q' failed, so its the terminus.
4363 	 */
4364 	rxq = ctx->ifc_rxqs;
4365 	for (i = 0; i < q; ++i, rxq++) {
4366 		iflib_rx_sds_free(rxq);
4367 		rxq->ifr_cq_gen = rxq->ifr_cq_cidx = rxq->ifr_cq_pidx = 0;
4368 	}
4369 	return (err);
4370 #endif
4371 }
4372 
4373 /*********************************************************************
4374  *
4375  *  Free all receive rings.
4376  *
4377  **********************************************************************/
4378 static void
4379 iflib_rx_structures_free(if_ctx_t ctx)
4380 {
4381 	iflib_rxq_t rxq = ctx->ifc_rxqs;
4382 
4383 	for (int i = 0; i < ctx->ifc_softc_ctx.isc_nrxqsets; i++, rxq++) {
4384 		iflib_rx_sds_free(rxq);
4385 	}
4386 }
4387 
4388 static int
4389 iflib_qset_structures_setup(if_ctx_t ctx)
4390 {
4391 	int err;
4392 
4393 	if ((err = iflib_tx_structures_setup(ctx)) != 0)
4394 		return (err);
4395 
4396 	if ((err = iflib_rx_structures_setup(ctx)) != 0) {
4397 		device_printf(ctx->ifc_dev, "iflib_rx_structures_setup failed: %d\n", err);
4398 		iflib_tx_structures_free(ctx);
4399 		iflib_rx_structures_free(ctx);
4400 	}
4401 	return (err);
4402 }
4403 
4404 int
4405 iflib_irq_alloc(if_ctx_t ctx, if_irq_t irq, int rid,
4406 				driver_filter_t filter, void *filter_arg, driver_intr_t handler, void *arg, char *name)
4407 {
4408 
4409 	return (_iflib_irq_alloc(ctx, irq, rid, filter, handler, arg, name));
4410 }
4411 
4412 static int
4413 find_nth(if_ctx_t ctx, cpuset_t *cpus, int qid)
4414 {
4415 	int i, cpuid, eqid, count;
4416 
4417 	CPU_COPY(&ctx->ifc_cpus, cpus);
4418 	count = CPU_COUNT(&ctx->ifc_cpus);
4419 	eqid = qid % count;
4420 	/* clear up to the qid'th bit */
4421 	for (i = 0; i < eqid; i++) {
4422 		cpuid = CPU_FFS(cpus);
4423 		MPASS(cpuid != 0);
4424 		CPU_CLR(cpuid-1, cpus);
4425 	}
4426 	cpuid = CPU_FFS(cpus);
4427 	MPASS(cpuid != 0);
4428 	return (cpuid-1);
4429 }
4430 
4431 int
4432 iflib_irq_alloc_generic(if_ctx_t ctx, if_irq_t irq, int rid,
4433 						iflib_intr_type_t type, driver_filter_t *filter,
4434 						void *filter_arg, int qid, char *name)
4435 {
4436 	struct grouptask *gtask;
4437 	struct taskqgroup *tqg;
4438 	iflib_filter_info_t info;
4439 	cpuset_t cpus;
4440 	gtask_fn_t *fn;
4441 	int tqrid, err, cpuid;
4442 	void *q;
4443 
4444 	info = &ctx->ifc_filter_info;
4445 	tqrid = rid;
4446 
4447 	switch (type) {
4448 	/* XXX merge tx/rx for netmap? */
4449 	case IFLIB_INTR_TX:
4450 		q = &ctx->ifc_txqs[qid];
4451 		info = &ctx->ifc_txqs[qid].ift_filter_info;
4452 		gtask = &ctx->ifc_txqs[qid].ift_task;
4453 		tqg = qgroup_if_io_tqg;
4454 		fn = _task_fn_tx;
4455 		GROUPTASK_INIT(gtask, 0, fn, q);
4456 		break;
4457 	case IFLIB_INTR_RX:
4458 		q = &ctx->ifc_rxqs[qid];
4459 		info = &ctx->ifc_rxqs[qid].ifr_filter_info;
4460 		gtask = &ctx->ifc_rxqs[qid].ifr_task;
4461 		tqg = qgroup_if_io_tqg;
4462 		fn = _task_fn_rx;
4463 		GROUPTASK_INIT(gtask, 0, fn, q);
4464 		break;
4465 	case IFLIB_INTR_ADMIN:
4466 		q = ctx;
4467 		tqrid = -1;
4468 		info = &ctx->ifc_filter_info;
4469 		gtask = &ctx->ifc_admin_task;
4470 		tqg = qgroup_if_config_tqg;
4471 		fn = _task_fn_admin;
4472 		break;
4473 	default:
4474 		panic("unknown net intr type");
4475 	}
4476 
4477 	info->ifi_filter = filter;
4478 	info->ifi_filter_arg = filter_arg;
4479 	info->ifi_task = gtask;
4480 	info->ifi_ctx = ctx;
4481 
4482 	err = _iflib_irq_alloc(ctx, irq, rid, iflib_fast_intr, NULL, info,  name);
4483 	if (err != 0) {
4484 		device_printf(ctx->ifc_dev, "_iflib_irq_alloc failed %d\n", err);
4485 		return (err);
4486 	}
4487 	if (type == IFLIB_INTR_ADMIN)
4488 		return (0);
4489 
4490 	if (tqrid != -1) {
4491 		cpuid = find_nth(ctx, &cpus, qid);
4492 		taskqgroup_attach_cpu(tqg, gtask, q, cpuid, irq->ii_rid, name);
4493 	} else {
4494 		taskqgroup_attach(tqg, gtask, q, tqrid, name);
4495 	}
4496 
4497 	return (0);
4498 }
4499 
4500 void
4501 iflib_softirq_alloc_generic(if_ctx_t ctx, int rid, iflib_intr_type_t type,  void *arg, int qid, char *name)
4502 {
4503 	struct grouptask *gtask;
4504 	struct taskqgroup *tqg;
4505 	gtask_fn_t *fn;
4506 	void *q;
4507 
4508 	switch (type) {
4509 	case IFLIB_INTR_TX:
4510 		q = &ctx->ifc_txqs[qid];
4511 		gtask = &ctx->ifc_txqs[qid].ift_task;
4512 		tqg = qgroup_if_io_tqg;
4513 		fn = _task_fn_tx;
4514 		break;
4515 	case IFLIB_INTR_RX:
4516 		q = &ctx->ifc_rxqs[qid];
4517 		gtask = &ctx->ifc_rxqs[qid].ifr_task;
4518 		tqg = qgroup_if_io_tqg;
4519 		fn = _task_fn_rx;
4520 		break;
4521 	case IFLIB_INTR_IOV:
4522 		q = ctx;
4523 		gtask = &ctx->ifc_vflr_task;
4524 		tqg = qgroup_if_config_tqg;
4525 		rid = -1;
4526 		fn = _task_fn_iov;
4527 		break;
4528 	default:
4529 		panic("unknown net intr type");
4530 	}
4531 	GROUPTASK_INIT(gtask, 0, fn, q);
4532 	taskqgroup_attach(tqg, gtask, q, rid, name);
4533 }
4534 
4535 void
4536 iflib_irq_free(if_ctx_t ctx, if_irq_t irq)
4537 {
4538 	if (irq->ii_tag)
4539 		bus_teardown_intr(ctx->ifc_dev, irq->ii_res, irq->ii_tag);
4540 
4541 	if (irq->ii_res)
4542 		bus_release_resource(ctx->ifc_dev, SYS_RES_IRQ, irq->ii_rid, irq->ii_res);
4543 }
4544 
4545 static int
4546 iflib_legacy_setup(if_ctx_t ctx, driver_filter_t filter, void *filter_arg, int *rid, char *name)
4547 {
4548 	iflib_txq_t txq = ctx->ifc_txqs;
4549 	iflib_rxq_t rxq = ctx->ifc_rxqs;
4550 	if_irq_t irq = &ctx->ifc_legacy_irq;
4551 	iflib_filter_info_t info;
4552 	struct grouptask *gtask;
4553 	struct taskqgroup *tqg;
4554 	gtask_fn_t *fn;
4555 	int tqrid;
4556 	void *q;
4557 	int err;
4558 
4559 	/*
4560 	 * group taskqueues aren't properly set up until SMP is started
4561 	 * so we disable interrupts until we can handle them post
4562 	 * SI_SUB_SMP
4563 	 */
4564 	IFDI_INTR_DISABLE(ctx);
4565 
4566 	q = &ctx->ifc_rxqs[0];
4567 	info = &rxq[0].ifr_filter_info;
4568 	gtask = &rxq[0].ifr_task;
4569 	tqg = qgroup_if_io_tqg;
4570 	tqrid = irq->ii_rid = *rid;
4571 	fn = _task_fn_rx;
4572 
4573 	ctx->ifc_flags |= IFC_LEGACY;
4574 	info->ifi_filter = filter;
4575 	info->ifi_filter_arg = filter_arg;
4576 	info->ifi_task = gtask;
4577 	info->ifi_ctx = ctx;
4578 
4579 	/* We allocate a single interrupt resource */
4580 	if ((err = _iflib_irq_alloc(ctx, irq, tqrid, iflib_fast_intr, NULL, info, name)) != 0)
4581 		return (err);
4582 	GROUPTASK_INIT(gtask, 0, fn, q);
4583 	taskqgroup_attach(tqg, gtask, q, tqrid, name);
4584 
4585 	GROUPTASK_INIT(&txq->ift_task, 0, _task_fn_tx, txq);
4586 	taskqgroup_attach(qgroup_if_io_tqg, &txq->ift_task, txq, tqrid, "tx");
4587 	return (0);
4588 }
4589 
4590 void
4591 iflib_led_create(if_ctx_t ctx)
4592 {
4593 
4594 	ctx->ifc_led_dev = led_create(iflib_led_func, ctx,
4595 								  device_get_nameunit(ctx->ifc_dev));
4596 }
4597 
4598 void
4599 iflib_tx_intr_deferred(if_ctx_t ctx, int txqid)
4600 {
4601 
4602 	GROUPTASK_ENQUEUE(&ctx->ifc_txqs[txqid].ift_task);
4603 }
4604 
4605 void
4606 iflib_rx_intr_deferred(if_ctx_t ctx, int rxqid)
4607 {
4608 
4609 	GROUPTASK_ENQUEUE(&ctx->ifc_rxqs[rxqid].ifr_task);
4610 }
4611 
4612 void
4613 iflib_admin_intr_deferred(if_ctx_t ctx)
4614 {
4615 #ifdef INVARIANTS
4616 	struct grouptask *gtask;
4617 
4618 	gtask = &ctx->ifc_admin_task;
4619 	MPASS(gtask->gt_taskqueue != NULL);
4620 #endif
4621 
4622 	GROUPTASK_ENQUEUE(&ctx->ifc_admin_task);
4623 }
4624 
4625 void
4626 iflib_iov_intr_deferred(if_ctx_t ctx)
4627 {
4628 
4629 	GROUPTASK_ENQUEUE(&ctx->ifc_vflr_task);
4630 }
4631 
4632 void
4633 iflib_io_tqg_attach(struct grouptask *gt, void *uniq, int cpu, char *name)
4634 {
4635 
4636 	taskqgroup_attach_cpu(qgroup_if_io_tqg, gt, uniq, cpu, -1, name);
4637 }
4638 
4639 void
4640 iflib_config_gtask_init(if_ctx_t ctx, struct grouptask *gtask, gtask_fn_t *fn,
4641 	char *name)
4642 {
4643 
4644 	GROUPTASK_INIT(gtask, 0, fn, ctx);
4645 	taskqgroup_attach(qgroup_if_config_tqg, gtask, gtask, -1, name);
4646 }
4647 
4648 void
4649 iflib_config_gtask_deinit(struct grouptask *gtask)
4650 {
4651 
4652 	taskqgroup_detach(qgroup_if_config_tqg, gtask);
4653 }
4654 
4655 void
4656 iflib_link_state_change(if_ctx_t ctx, int link_state, uint64_t baudrate)
4657 {
4658 	if_t ifp = ctx->ifc_ifp;
4659 	iflib_txq_t txq = ctx->ifc_txqs;
4660 
4661 	if_setbaudrate(ifp, baudrate);
4662 
4663 	/* If link down, disable watchdog */
4664 	if ((ctx->ifc_link_state == LINK_STATE_UP) && (link_state == LINK_STATE_DOWN)) {
4665 		for (int i = 0; i < ctx->ifc_softc_ctx.isc_ntxqsets; i++, txq++)
4666 			txq->ift_qstatus = IFLIB_QUEUE_IDLE;
4667 	}
4668 	ctx->ifc_link_state = link_state;
4669 	if_link_state_change(ifp, link_state);
4670 }
4671 
4672 static int
4673 iflib_tx_credits_update(if_ctx_t ctx, iflib_txq_t txq)
4674 {
4675 	int credits;
4676 #ifdef INVARIANTS
4677 	int credits_pre = txq->ift_cidx_processed;
4678 #endif
4679 
4680 	if (ctx->isc_txd_credits_update == NULL)
4681 		return (0);
4682 
4683 	if ((credits = ctx->isc_txd_credits_update(ctx->ifc_softc, txq->ift_id, txq->ift_cidx_processed, true)) == 0)
4684 		return (0);
4685 
4686 	txq->ift_processed += credits;
4687 	txq->ift_cidx_processed += credits;
4688 
4689 	MPASS(credits_pre + credits == txq->ift_cidx_processed);
4690 	if (txq->ift_cidx_processed >= txq->ift_size)
4691 		txq->ift_cidx_processed -= txq->ift_size;
4692 	return (credits);
4693 }
4694 
4695 static int
4696 iflib_rxd_avail(if_ctx_t ctx, iflib_rxq_t rxq, int cidx, int budget)
4697 {
4698 
4699 	return (ctx->isc_rxd_available(ctx->ifc_softc, rxq->ifr_id, cidx,
4700 	    budget));
4701 }
4702 
4703 void
4704 iflib_add_int_delay_sysctl(if_ctx_t ctx, const char *name,
4705 	const char *description, if_int_delay_info_t info,
4706 	int offset, int value)
4707 {
4708 	info->iidi_ctx = ctx;
4709 	info->iidi_offset = offset;
4710 	info->iidi_value = value;
4711 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(ctx->ifc_dev),
4712 	    SYSCTL_CHILDREN(device_get_sysctl_tree(ctx->ifc_dev)),
4713 	    OID_AUTO, name, CTLTYPE_INT|CTLFLAG_RW,
4714 	    info, 0, iflib_sysctl_int_delay, "I", description);
4715 }
4716 
4717 struct mtx *
4718 iflib_ctx_lock_get(if_ctx_t ctx)
4719 {
4720 
4721 	return (&ctx->ifc_mtx);
4722 }
4723 
4724 static int
4725 iflib_msix_init(if_ctx_t ctx)
4726 {
4727 	device_t dev = ctx->ifc_dev;
4728 	if_shared_ctx_t sctx = ctx->ifc_sctx;
4729 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
4730 	int vectors, queues, rx_queues, tx_queues, queuemsgs, msgs;
4731 	int iflib_num_tx_queues, iflib_num_rx_queues;
4732 	int err, admincnt, bar;
4733 
4734 	iflib_num_tx_queues = scctx->isc_ntxqsets;
4735 	iflib_num_rx_queues = scctx->isc_nrxqsets;
4736 
4737 	device_printf(dev, "msix_init qsets capped at %d\n", iflib_num_tx_queues);
4738 
4739 	bar = ctx->ifc_softc_ctx.isc_msix_bar;
4740 	admincnt = sctx->isc_admin_intrcnt;
4741 	/* Override by tuneable */
4742 	if (enable_msix == 0)
4743 		goto msi;
4744 
4745 	/*
4746 	** When used in a virtualized environment
4747 	** PCI BUSMASTER capability may not be set
4748 	** so explicity set it here and rewrite
4749 	** the ENABLE in the MSIX control register
4750 	** at this point to cause the host to
4751 	** successfully initialize us.
4752 	*/
4753 	{
4754 		uint16_t pci_cmd_word;
4755 		int msix_ctrl, rid;
4756 
4757 		rid = 0;
4758 		pci_cmd_word = pci_read_config(dev, PCIR_COMMAND, 2);
4759 		pci_cmd_word |= PCIM_CMD_BUSMASTEREN;
4760 		pci_write_config(dev, PCIR_COMMAND, pci_cmd_word, 2);
4761 		pci_find_cap(dev, PCIY_MSIX, &rid);
4762 		rid += PCIR_MSIX_CTRL;
4763 		msix_ctrl = pci_read_config(dev, rid, 2);
4764 		msix_ctrl |= PCIM_MSIXCTRL_MSIX_ENABLE;
4765 		pci_write_config(dev, rid, msix_ctrl, 2);
4766 	}
4767 
4768 	/*
4769 	 * bar == -1 => "trust me I know what I'm doing"
4770 	 * https://www.youtube.com/watch?v=nnwWKkNau4I
4771 	 * Some drivers are for hardware that is so shoddily
4772 	 * documented that no one knows which bars are which
4773 	 * so the developer has to map all bars. This hack
4774 	 * allows shoddy garbage to use msix in this framework.
4775 	 */
4776 	if (bar != -1) {
4777 		ctx->ifc_msix_mem = bus_alloc_resource_any(dev,
4778 	            SYS_RES_MEMORY, &bar, RF_ACTIVE);
4779 		if (ctx->ifc_msix_mem == NULL) {
4780 			/* May not be enabled */
4781 			device_printf(dev, "Unable to map MSIX table \n");
4782 			goto msi;
4783 		}
4784 	}
4785 	/* First try MSI/X */
4786 	if ((msgs = pci_msix_count(dev)) == 0) { /* system has msix disabled */
4787 		device_printf(dev, "System has MSIX disabled \n");
4788 		bus_release_resource(dev, SYS_RES_MEMORY,
4789 		    bar, ctx->ifc_msix_mem);
4790 		ctx->ifc_msix_mem = NULL;
4791 		goto msi;
4792 	}
4793 #if IFLIB_DEBUG
4794 	/* use only 1 qset in debug mode */
4795 	queuemsgs = min(msgs - admincnt, 1);
4796 #else
4797 	queuemsgs = msgs - admincnt;
4798 #endif
4799 	if (bus_get_cpus(dev, INTR_CPUS, sizeof(ctx->ifc_cpus), &ctx->ifc_cpus) == 0) {
4800 #ifdef RSS
4801 		queues = imin(queuemsgs, rss_getnumbuckets());
4802 #else
4803 		queues = queuemsgs;
4804 #endif
4805 		queues = imin(CPU_COUNT(&ctx->ifc_cpus), queues);
4806 		device_printf(dev, "pxm cpus: %d queue msgs: %d admincnt: %d\n",
4807 					  CPU_COUNT(&ctx->ifc_cpus), queuemsgs, admincnt);
4808 	} else {
4809 		device_printf(dev, "Unable to fetch CPU list\n");
4810 		/* Figure out a reasonable auto config value */
4811 		queues = min(queuemsgs, mp_ncpus);
4812 	}
4813 #ifdef  RSS
4814 	/* If we're doing RSS, clamp at the number of RSS buckets */
4815 	if (queues > rss_getnumbuckets())
4816 		queues = rss_getnumbuckets();
4817 #endif
4818 	if (iflib_num_rx_queues > 0 && iflib_num_rx_queues < queuemsgs - admincnt)
4819 		rx_queues = iflib_num_rx_queues;
4820 	else
4821 		rx_queues = queues;
4822 	/*
4823 	 * We want this to be all logical CPUs by default
4824 	 */
4825 	if (iflib_num_tx_queues > 0 && iflib_num_tx_queues < queues)
4826 		tx_queues = iflib_num_tx_queues;
4827 	else
4828 		tx_queues = mp_ncpus;
4829 
4830 	if (ctx->ifc_sysctl_qs_eq_override == 0) {
4831 #ifdef INVARIANTS
4832 		if (tx_queues != rx_queues)
4833 			device_printf(dev, "queue equality override not set, capping rx_queues at %d and tx_queues at %d\n",
4834 				      min(rx_queues, tx_queues), min(rx_queues, tx_queues));
4835 #endif
4836 		tx_queues = min(rx_queues, tx_queues);
4837 		rx_queues = min(rx_queues, tx_queues);
4838 	}
4839 
4840 	device_printf(dev, "using %d rx queues %d tx queues \n", rx_queues, tx_queues);
4841 
4842 	vectors = rx_queues + admincnt;
4843 	if ((err = pci_alloc_msix(dev, &vectors)) == 0) {
4844 		device_printf(dev,
4845 					  "Using MSIX interrupts with %d vectors\n", vectors);
4846 		scctx->isc_vectors = vectors;
4847 		scctx->isc_nrxqsets = rx_queues;
4848 		scctx->isc_ntxqsets = tx_queues;
4849 		scctx->isc_intr = IFLIB_INTR_MSIX;
4850 
4851 		return (vectors);
4852 	} else {
4853 		device_printf(dev, "failed to allocate %d msix vectors, err: %d - using MSI\n", vectors, err);
4854 	}
4855 msi:
4856 	vectors = pci_msi_count(dev);
4857 	scctx->isc_nrxqsets = 1;
4858 	scctx->isc_ntxqsets = 1;
4859 	scctx->isc_vectors = vectors;
4860 	if (vectors == 1 && pci_alloc_msi(dev, &vectors) == 0) {
4861 		device_printf(dev,"Using an MSI interrupt\n");
4862 		scctx->isc_intr = IFLIB_INTR_MSI;
4863 	} else {
4864 		device_printf(dev,"Using a Legacy interrupt\n");
4865 		scctx->isc_intr = IFLIB_INTR_LEGACY;
4866 	}
4867 
4868 	return (vectors);
4869 }
4870 
4871 char * ring_states[] = { "IDLE", "BUSY", "STALLED", "ABDICATED" };
4872 
4873 static int
4874 mp_ring_state_handler(SYSCTL_HANDLER_ARGS)
4875 {
4876 	int rc;
4877 	uint16_t *state = ((uint16_t *)oidp->oid_arg1);
4878 	struct sbuf *sb;
4879 	char *ring_state = "UNKNOWN";
4880 
4881 	/* XXX needed ? */
4882 	rc = sysctl_wire_old_buffer(req, 0);
4883 	MPASS(rc == 0);
4884 	if (rc != 0)
4885 		return (rc);
4886 	sb = sbuf_new_for_sysctl(NULL, NULL, 80, req);
4887 	MPASS(sb != NULL);
4888 	if (sb == NULL)
4889 		return (ENOMEM);
4890 	if (state[3] <= 3)
4891 		ring_state = ring_states[state[3]];
4892 
4893 	sbuf_printf(sb, "pidx_head: %04hd pidx_tail: %04hd cidx: %04hd state: %s",
4894 		    state[0], state[1], state[2], ring_state);
4895 	rc = sbuf_finish(sb);
4896 	sbuf_delete(sb);
4897         return(rc);
4898 }
4899 
4900 enum iflib_ndesc_handler {
4901 	IFLIB_NTXD_HANDLER,
4902 	IFLIB_NRXD_HANDLER,
4903 };
4904 
4905 static int
4906 mp_ndesc_handler(SYSCTL_HANDLER_ARGS)
4907 {
4908 	if_ctx_t ctx = (void *)arg1;
4909 	enum iflib_ndesc_handler type = arg2;
4910 	char buf[256] = {0};
4911 	uint16_t *ndesc;
4912 	char *p, *next;
4913 	int nqs, rc, i;
4914 
4915 	MPASS(type == IFLIB_NTXD_HANDLER || type == IFLIB_NRXD_HANDLER);
4916 
4917 	nqs = 8;
4918 	switch(type) {
4919 	case IFLIB_NTXD_HANDLER:
4920 		ndesc = ctx->ifc_sysctl_ntxds;
4921 		if (ctx->ifc_sctx)
4922 			nqs = ctx->ifc_sctx->isc_ntxqs;
4923 		break;
4924 	case IFLIB_NRXD_HANDLER:
4925 		ndesc = ctx->ifc_sysctl_nrxds;
4926 		if (ctx->ifc_sctx)
4927 			nqs = ctx->ifc_sctx->isc_nrxqs;
4928 		break;
4929 	}
4930 	if (nqs == 0)
4931 		nqs = 8;
4932 
4933 	for (i=0; i<8; i++) {
4934 		if (i >= nqs)
4935 			break;
4936 		if (i)
4937 			strcat(buf, ",");
4938 		sprintf(strchr(buf, 0), "%d", ndesc[i]);
4939 	}
4940 
4941 	rc = sysctl_handle_string(oidp, buf, sizeof(buf), req);
4942 	if (rc || req->newptr == NULL)
4943 		return rc;
4944 
4945 	for (i = 0, next = buf, p = strsep(&next, " ,"); i < 8 && p;
4946 	    i++, p = strsep(&next, " ,")) {
4947 		ndesc[i] = strtoul(p, NULL, 10);
4948 	}
4949 
4950 	return(rc);
4951 }
4952 
4953 #define NAME_BUFLEN 32
4954 static void
4955 iflib_add_device_sysctl_pre(if_ctx_t ctx)
4956 {
4957         device_t dev = iflib_get_dev(ctx);
4958 	struct sysctl_oid_list *child, *oid_list;
4959 	struct sysctl_ctx_list *ctx_list;
4960 	struct sysctl_oid *node;
4961 
4962 	ctx_list = device_get_sysctl_ctx(dev);
4963 	child = SYSCTL_CHILDREN(device_get_sysctl_tree(dev));
4964 	ctx->ifc_sysctl_node = node = SYSCTL_ADD_NODE(ctx_list, child, OID_AUTO, "iflib",
4965 						      CTLFLAG_RD, NULL, "IFLIB fields");
4966 	oid_list = SYSCTL_CHILDREN(node);
4967 
4968 	SYSCTL_ADD_STRING(ctx_list, oid_list, OID_AUTO, "driver_version",
4969 		       CTLFLAG_RD, ctx->ifc_sctx->isc_driver_version, 0,
4970 		       "driver version");
4971 
4972 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_ntxqs",
4973 		       CTLFLAG_RWTUN, &ctx->ifc_sysctl_ntxqs, 0,
4974 			"# of txqs to use, 0 => use default #");
4975 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_nrxqs",
4976 		       CTLFLAG_RWTUN, &ctx->ifc_sysctl_nrxqs, 0,
4977 			"# of rxqs to use, 0 => use default #");
4978 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_qs_enable",
4979 		       CTLFLAG_RWTUN, &ctx->ifc_sysctl_qs_eq_override, 0,
4980                        "permit #txq != #rxq");
4981 
4982 	/* XXX change for per-queue sizes */
4983 	SYSCTL_ADD_PROC(ctx_list, oid_list, OID_AUTO, "override_ntxds",
4984 		       CTLTYPE_STRING|CTLFLAG_RWTUN, ctx, IFLIB_NTXD_HANDLER,
4985                        mp_ndesc_handler, "A",
4986                        "list of # of tx descriptors to use, 0 = use default #");
4987 	SYSCTL_ADD_PROC(ctx_list, oid_list, OID_AUTO, "override_nrxds",
4988 		       CTLTYPE_STRING|CTLFLAG_RWTUN, ctx, IFLIB_NRXD_HANDLER,
4989                        mp_ndesc_handler, "A",
4990                        "list of # of rx descriptors to use, 0 = use default #");
4991 }
4992 
4993 static void
4994 iflib_add_device_sysctl_post(if_ctx_t ctx)
4995 {
4996 	if_shared_ctx_t sctx = ctx->ifc_sctx;
4997 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
4998         device_t dev = iflib_get_dev(ctx);
4999 	struct sysctl_oid_list *child;
5000 	struct sysctl_ctx_list *ctx_list;
5001 	iflib_fl_t fl;
5002 	iflib_txq_t txq;
5003 	iflib_rxq_t rxq;
5004 	int i, j;
5005 	char namebuf[NAME_BUFLEN];
5006 	char *qfmt;
5007 	struct sysctl_oid *queue_node, *fl_node, *node;
5008 	struct sysctl_oid_list *queue_list, *fl_list;
5009 	ctx_list = device_get_sysctl_ctx(dev);
5010 
5011 	node = ctx->ifc_sysctl_node;
5012 	child = SYSCTL_CHILDREN(node);
5013 
5014 	if (scctx->isc_ntxqsets > 100)
5015 		qfmt = "txq%03d";
5016 	else if (scctx->isc_ntxqsets > 10)
5017 		qfmt = "txq%02d";
5018 	else
5019 		qfmt = "txq%d";
5020 	for (i = 0, txq = ctx->ifc_txqs; i < scctx->isc_ntxqsets; i++, txq++) {
5021 		snprintf(namebuf, NAME_BUFLEN, qfmt, i);
5022 		queue_node = SYSCTL_ADD_NODE(ctx_list, child, OID_AUTO, namebuf,
5023 					     CTLFLAG_RD, NULL, "Queue Name");
5024 		queue_list = SYSCTL_CHILDREN(queue_node);
5025 #if MEMORY_LOGGING
5026 		SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "txq_dequeued",
5027 				CTLFLAG_RD,
5028 				&txq->ift_dequeued, "total mbufs freed");
5029 		SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "txq_enqueued",
5030 				CTLFLAG_RD,
5031 				&txq->ift_enqueued, "total mbufs enqueued");
5032 #endif
5033 		SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "mbuf_defrag",
5034 				   CTLFLAG_RD,
5035 				   &txq->ift_mbuf_defrag, "# of times m_defrag was called");
5036 		SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "m_pullups",
5037 				   CTLFLAG_RD,
5038 				   &txq->ift_pullups, "# of times m_pullup was called");
5039 		SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "mbuf_defrag_failed",
5040 				   CTLFLAG_RD,
5041 				   &txq->ift_mbuf_defrag_failed, "# of times m_defrag failed");
5042 		SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "no_desc_avail",
5043 				   CTLFLAG_RD,
5044 				   &txq->ift_no_desc_avail, "# of times no descriptors were available");
5045 		SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "tx_map_failed",
5046 				   CTLFLAG_RD,
5047 				   &txq->ift_map_failed, "# of times dma map failed");
5048 		SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "txd_encap_efbig",
5049 				   CTLFLAG_RD,
5050 				   &txq->ift_txd_encap_efbig, "# of times txd_encap returned EFBIG");
5051 		SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "no_tx_dma_setup",
5052 				   CTLFLAG_RD,
5053 				   &txq->ift_no_tx_dma_setup, "# of times map failed for other than EFBIG");
5054 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_pidx",
5055 				   CTLFLAG_RD,
5056 				   &txq->ift_pidx, 1, "Producer Index");
5057 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_cidx",
5058 				   CTLFLAG_RD,
5059 				   &txq->ift_cidx, 1, "Consumer Index");
5060 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_cidx_processed",
5061 				   CTLFLAG_RD,
5062 				   &txq->ift_cidx_processed, 1, "Consumer Index seen by credit update");
5063 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_in_use",
5064 				   CTLFLAG_RD,
5065 				   &txq->ift_in_use, 1, "descriptors in use");
5066 		SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "txq_processed",
5067 				   CTLFLAG_RD,
5068 				   &txq->ift_processed, "descriptors procesed for clean");
5069 		SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "txq_cleaned",
5070 				   CTLFLAG_RD,
5071 				   &txq->ift_cleaned, "total cleaned");
5072 		SYSCTL_ADD_PROC(ctx_list, queue_list, OID_AUTO, "ring_state",
5073 				CTLTYPE_STRING | CTLFLAG_RD, __DEVOLATILE(uint64_t *, &txq->ift_br[0]->state),
5074 				0, mp_ring_state_handler, "A", "soft ring state");
5075 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_enqueues",
5076 				       CTLFLAG_RD, &txq->ift_br[0]->enqueues,
5077 				       "# of enqueues to the mp_ring for this queue");
5078 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_drops",
5079 				       CTLFLAG_RD, &txq->ift_br[0]->drops,
5080 				       "# of drops in the mp_ring for this queue");
5081 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_starts",
5082 				       CTLFLAG_RD, &txq->ift_br[0]->starts,
5083 				       "# of normal consumer starts in the mp_ring for this queue");
5084 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_stalls",
5085 				       CTLFLAG_RD, &txq->ift_br[0]->stalls,
5086 					       "# of consumer stalls in the mp_ring for this queue");
5087 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_restarts",
5088 			       CTLFLAG_RD, &txq->ift_br[0]->restarts,
5089 				       "# of consumer restarts in the mp_ring for this queue");
5090 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_abdications",
5091 				       CTLFLAG_RD, &txq->ift_br[0]->abdications,
5092 				       "# of consumer abdications in the mp_ring for this queue");
5093 	}
5094 
5095 	if (scctx->isc_nrxqsets > 100)
5096 		qfmt = "rxq%03d";
5097 	else if (scctx->isc_nrxqsets > 10)
5098 		qfmt = "rxq%02d";
5099 	else
5100 		qfmt = "rxq%d";
5101 	for (i = 0, rxq = ctx->ifc_rxqs; i < scctx->isc_nrxqsets; i++, rxq++) {
5102 		snprintf(namebuf, NAME_BUFLEN, qfmt, i);
5103 		queue_node = SYSCTL_ADD_NODE(ctx_list, child, OID_AUTO, namebuf,
5104 					     CTLFLAG_RD, NULL, "Queue Name");
5105 		queue_list = SYSCTL_CHILDREN(queue_node);
5106 		if (sctx->isc_flags & IFLIB_HAS_RXCQ) {
5107 			SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "rxq_cq_pidx",
5108 				       CTLFLAG_RD,
5109 				       &rxq->ifr_cq_pidx, 1, "Producer Index");
5110 			SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "rxq_cq_cidx",
5111 				       CTLFLAG_RD,
5112 				       &rxq->ifr_cq_cidx, 1, "Consumer Index");
5113 		}
5114 
5115 		for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++) {
5116 			snprintf(namebuf, NAME_BUFLEN, "rxq_fl%d", j);
5117 			fl_node = SYSCTL_ADD_NODE(ctx_list, queue_list, OID_AUTO, namebuf,
5118 						     CTLFLAG_RD, NULL, "freelist Name");
5119 			fl_list = SYSCTL_CHILDREN(fl_node);
5120 			SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "pidx",
5121 				       CTLFLAG_RD,
5122 				       &fl->ifl_pidx, 1, "Producer Index");
5123 			SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "cidx",
5124 				       CTLFLAG_RD,
5125 				       &fl->ifl_cidx, 1, "Consumer Index");
5126 			SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "credits",
5127 				       CTLFLAG_RD,
5128 				       &fl->ifl_credits, 1, "credits available");
5129 #if MEMORY_LOGGING
5130 			SYSCTL_ADD_QUAD(ctx_list, fl_list, OID_AUTO, "fl_m_enqueued",
5131 					CTLFLAG_RD,
5132 					&fl->ifl_m_enqueued, "mbufs allocated");
5133 			SYSCTL_ADD_QUAD(ctx_list, fl_list, OID_AUTO, "fl_m_dequeued",
5134 					CTLFLAG_RD,
5135 					&fl->ifl_m_dequeued, "mbufs freed");
5136 			SYSCTL_ADD_QUAD(ctx_list, fl_list, OID_AUTO, "fl_cl_enqueued",
5137 					CTLFLAG_RD,
5138 					&fl->ifl_cl_enqueued, "clusters allocated");
5139 			SYSCTL_ADD_QUAD(ctx_list, fl_list, OID_AUTO, "fl_cl_dequeued",
5140 					CTLFLAG_RD,
5141 					&fl->ifl_cl_dequeued, "clusters freed");
5142 #endif
5143 
5144 		}
5145 	}
5146 
5147 }
5148