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