xref: /freebsd/sys/net/iflib.c (revision e7be843b4a162e68651d3911f0357ed464915629)
1 /*-
2  * Copyright (c) 2014-2018, Matthew Macy <mmacy@mattmacy.io>
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 #include "opt_inet.h"
30 #include "opt_inet6.h"
31 #include "opt_acpi.h"
32 #include "opt_sched.h"
33 
34 #include <sys/param.h>
35 #include <sys/types.h>
36 #include <sys/bus.h>
37 #include <sys/eventhandler.h>
38 #include <sys/kernel.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/module.h>
42 #include <sys/kobj.h>
43 #include <sys/rman.h>
44 #include <sys/sbuf.h>
45 #include <sys/smp.h>
46 #include <sys/socket.h>
47 #include <sys/sockio.h>
48 #include <sys/sysctl.h>
49 #include <sys/syslog.h>
50 #include <sys/taskqueue.h>
51 #include <sys/limits.h>
52 
53 #include <net/if.h>
54 #include <net/if_var.h>
55 #include <net/if_private.h>
56 #include <net/if_types.h>
57 #include <net/if_media.h>
58 #include <net/bpf.h>
59 #include <net/ethernet.h>
60 #include <net/mp_ring.h>
61 #include <net/debugnet.h>
62 #include <net/pfil.h>
63 #include <net/vnet.h>
64 
65 #include <netinet/in.h>
66 #include <netinet/in_pcb.h>
67 #include <netinet/tcp_lro.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/if_ether.h>
70 #include <netinet/ip.h>
71 #include <netinet/ip6.h>
72 #include <netinet/tcp.h>
73 #include <netinet/udp.h>
74 #include <netinet/ip_var.h>
75 #include <netinet6/ip6_var.h>
76 
77 #include <machine/bus.h>
78 #include <machine/in_cksum.h>
79 
80 #include <vm/vm.h>
81 #include <vm/pmap.h>
82 
83 #include <dev/led/led.h>
84 #include <dev/pci/pcireg.h>
85 #include <dev/pci/pcivar.h>
86 #include <dev/pci/pci_private.h>
87 
88 #include <net/iflib.h>
89 
90 #include "ifdi_if.h"
91 
92 #ifdef PCI_IOV
93 #include <dev/pci/pci_iov.h>
94 #endif
95 
96 #include <sys/bitstring.h>
97 /*
98  * enable accounting of every mbuf as it comes in to and goes out of
99  * iflib's software descriptor references
100  */
101 #define MEMORY_LOGGING 0
102 /*
103  * Enable mbuf vectors for compressing long mbuf chains
104  */
105 
106 /*
107  * NB:
108  * - Prefetching in tx cleaning should perhaps be a tunable. The distance ahead
109  *   we prefetch needs to be determined by the time spent in m_free vis a vis
110  *   the cost of a prefetch. This will of course vary based on the workload:
111  *      - NFLX's m_free path is dominated by vm-based M_EXT manipulation which
112  *        is quite expensive, thus suggesting very little prefetch.
113  *      - small packet forwarding which is just returning a single mbuf to
114  *        UMA will typically be very fast vis a vis the cost of a memory
115  *        access.
116  */
117 
118 /*
119  * File organization:
120  *  - private structures
121  *  - iflib private utility functions
122  *  - ifnet functions
123  *  - vlan registry and other exported functions
124  *  - iflib public core functions
125  *
126  *
127  */
128 static MALLOC_DEFINE(M_IFLIB, "iflib", "ifnet library");
129 
130 #define	IFLIB_RXEOF_MORE	(1U << 0)
131 #define	IFLIB_RXEOF_EMPTY	(2U << 0)
132 
133 struct iflib_txq;
134 typedef struct iflib_txq *iflib_txq_t;
135 struct iflib_rxq;
136 typedef struct iflib_rxq *iflib_rxq_t;
137 struct iflib_fl;
138 typedef struct iflib_fl *iflib_fl_t;
139 
140 struct iflib_ctx;
141 
142 static void iru_init(if_rxd_update_t iru, iflib_rxq_t rxq, uint8_t flid);
143 static void iflib_timer(void *arg);
144 static void iflib_tqg_detach(if_ctx_t ctx);
145 
146 typedef struct iflib_filter_info {
147 	driver_filter_t *ifi_filter;
148 	void *ifi_filter_arg;
149 	struct grouptask *ifi_task;
150 	void *ifi_ctx;
151 } *iflib_filter_info_t;
152 
153 struct iflib_ctx {
154 	KOBJ_FIELDS;
155 	/*
156 	 * Pointer to hardware driver's softc
157 	 */
158 	void *ifc_softc;
159 	device_t ifc_dev;
160 	if_t ifc_ifp;
161 
162 	cpuset_t ifc_cpus;
163 	if_shared_ctx_t ifc_sctx;
164 	struct if_softc_ctx ifc_softc_ctx;
165 
166 	struct sx ifc_ctx_sx;
167 	struct mtx ifc_state_mtx;
168 
169 	iflib_txq_t ifc_txqs;
170 	iflib_rxq_t ifc_rxqs;
171 	uint32_t ifc_if_flags;
172 	uint32_t ifc_flags;
173 	uint32_t ifc_max_fl_buf_size;
174 	uint32_t ifc_rx_mbuf_sz;
175 
176 	int ifc_link_state;
177 	int ifc_watchdog_events;
178 	struct cdev *ifc_led_dev;
179 	struct resource *ifc_msix_mem;
180 
181 	struct if_irq ifc_legacy_irq;
182 	struct task ifc_admin_task;
183 	struct task ifc_vflr_task;
184 	struct taskqueue *ifc_tq;
185 	struct iflib_filter_info ifc_filter_info;
186 	struct ifmedia	ifc_media;
187 	struct ifmedia	*ifc_mediap;
188 
189 	struct sysctl_oid *ifc_sysctl_node;
190 	uint16_t ifc_sysctl_ntxqs;
191 	uint16_t ifc_sysctl_nrxqs;
192 	uint16_t ifc_sysctl_qs_eq_override;
193 	uint16_t ifc_sysctl_rx_budget;
194 	uint16_t ifc_sysctl_tx_abdicate;
195 	uint16_t ifc_sysctl_core_offset;
196 #define	CORE_OFFSET_UNSPECIFIED	0xffff
197 	uint8_t  ifc_sysctl_separate_txrx;
198 	uint8_t  ifc_sysctl_use_logical_cores;
199 	uint16_t ifc_sysctl_extra_msix_vectors;
200 	bool     ifc_cpus_are_physical_cores;
201 
202 	qidx_t ifc_sysctl_ntxds[8];
203 	qidx_t ifc_sysctl_nrxds[8];
204 	struct if_txrx ifc_txrx;
205 #define isc_txd_encap		ifc_txrx.ift_txd_encap
206 #define isc_txd_flush		ifc_txrx.ift_txd_flush
207 #define isc_txd_credits_update	ifc_txrx.ift_txd_credits_update
208 #define isc_rxd_available	ifc_txrx.ift_rxd_available
209 #define isc_rxd_pkt_get		ifc_txrx.ift_rxd_pkt_get
210 #define isc_rxd_refill		ifc_txrx.ift_rxd_refill
211 #define isc_rxd_flush		ifc_txrx.ift_rxd_flush
212 #define isc_legacy_intr		ifc_txrx.ift_legacy_intr
213 #define isc_txq_select		ifc_txrx.ift_txq_select
214 #define isc_txq_select_v2	ifc_txrx.ift_txq_select_v2
215 
216 	eventhandler_tag ifc_vlan_attach_event;
217 	eventhandler_tag ifc_vlan_detach_event;
218 	struct ether_addr ifc_mac;
219 };
220 
221 void *
222 iflib_get_softc(if_ctx_t ctx)
223 {
224 
225 	return (ctx->ifc_softc);
226 }
227 
228 device_t
229 iflib_get_dev(if_ctx_t ctx)
230 {
231 
232 	return (ctx->ifc_dev);
233 }
234 
235 if_t
236 iflib_get_ifp(if_ctx_t ctx)
237 {
238 
239 	return (ctx->ifc_ifp);
240 }
241 
242 struct ifmedia *
243 iflib_get_media(if_ctx_t ctx)
244 {
245 
246 	return (ctx->ifc_mediap);
247 }
248 
249 void
250 iflib_set_mac(if_ctx_t ctx, uint8_t mac[ETHER_ADDR_LEN])
251 {
252 
253 	bcopy(mac, ctx->ifc_mac.octet, ETHER_ADDR_LEN);
254 }
255 
256 if_softc_ctx_t
257 iflib_get_softc_ctx(if_ctx_t ctx)
258 {
259 
260 	return (&ctx->ifc_softc_ctx);
261 }
262 
263 if_shared_ctx_t
264 iflib_get_sctx(if_ctx_t ctx)
265 {
266 
267 	return (ctx->ifc_sctx);
268 }
269 
270 uint16_t
271 iflib_get_extra_msix_vectors_sysctl(if_ctx_t ctx)
272 {
273 
274 	return (ctx->ifc_sysctl_extra_msix_vectors);
275 }
276 
277 #define IP_ALIGNED(m)		((((uintptr_t)(m)->m_data) & 0x3) == 0x2)
278 #define CACHE_PTR_INCREMENT	(CACHE_LINE_SIZE / sizeof(void *))
279 #define CACHE_PTR_NEXT(ptr)	((void *)(roundup2(ptr, CACHE_LINE_SIZE)))
280 
281 #define LINK_ACTIVE(ctx)	((ctx)->ifc_link_state == LINK_STATE_UP)
282 #define CTX_IS_VF(ctx)		((ctx)->ifc_sctx->isc_flags & IFLIB_IS_VF)
283 
284 typedef struct iflib_sw_rx_desc_array {
285 	bus_dmamap_t	*ifsd_map;	/* bus_dma maps for packet */
286 	struct mbuf	**ifsd_m;	/* pkthdr mbufs */
287 	caddr_t		*ifsd_cl;	/* direct cluster pointer for rx */
288 	bus_addr_t	*ifsd_ba;	/* bus addr of cluster for rx */
289 } iflib_rxsd_array_t;
290 
291 typedef struct iflib_sw_tx_desc_array {
292 	bus_dmamap_t	*ifsd_map;	/* bus_dma maps for packet */
293 	bus_dmamap_t	*ifsd_tso_map;	/* bus_dma maps for TSO packet */
294 	struct mbuf	**ifsd_m;	/* pkthdr mbufs */
295 } if_txsd_vec_t;
296 
297 /* magic number that should be high enough for any hardware */
298 #define IFLIB_MAX_TX_SEGS		128
299 #define IFLIB_RX_COPY_THRESH		128
300 #define IFLIB_MAX_RX_REFRESH		32
301 /* The minimum descriptors per second before we start coalescing */
302 #define IFLIB_MIN_DESC_SEC		16384
303 #define IFLIB_DEFAULT_TX_UPDATE_FREQ	16
304 #define IFLIB_QUEUE_IDLE		0
305 #define IFLIB_QUEUE_HUNG		1
306 #define IFLIB_QUEUE_WORKING		2
307 /* maximum number of txqs that can share an rx interrupt */
308 #define IFLIB_MAX_TX_SHARED_INTR	4
309 
310 /* this should really scale with ring size - this is a fairly arbitrary value */
311 #define TX_BATCH_SIZE			32
312 
313 #define IFLIB_RESTART_BUDGET		8
314 
315 #define	IFC_LEGACY		0x001
316 #define	IFC_QFLUSH		0x002
317 #define	IFC_MULTISEG		0x004
318 #define	IFC_SPARE1		0x008
319 #define	IFC_SC_ALLOCATED	0x010
320 #define	IFC_INIT_DONE		0x020
321 #define	IFC_PREFETCH		0x040
322 #define	IFC_DO_RESET		0x080
323 #define	IFC_DO_WATCHDOG		0x100
324 #define	IFC_SPARE0		0x200
325 #define	IFC_SPARE2		0x400
326 #define	IFC_IN_DETACH		0x800
327 
328 #define	IFC_NETMAP_TX_IRQ	0x80000000
329 
330 #define CSUM_OFFLOAD		(CSUM_IP_TSO | CSUM_IP6_TSO | CSUM_IP | \
331 				 CSUM_IP_UDP | CSUM_IP_TCP | CSUM_IP_SCTP | \
332 				 CSUM_IP6_UDP | CSUM_IP6_TCP | CSUM_IP6_SCTP)
333 
334 struct iflib_txq {
335 	qidx_t		ift_in_use;
336 	qidx_t		ift_cidx;
337 	qidx_t		ift_cidx_processed;
338 	qidx_t		ift_pidx;
339 	uint8_t		ift_gen;
340 	uint8_t		ift_br_offset;
341 	uint16_t	ift_npending;
342 	uint16_t	ift_db_pending;
343 	uint16_t	ift_rs_pending;
344 	/* implicit pad */
345 	uint8_t		ift_txd_size[8];
346 	uint64_t	ift_processed;
347 	uint64_t	ift_cleaned;
348 	uint64_t	ift_cleaned_prev;
349 #if MEMORY_LOGGING
350 	uint64_t	ift_enqueued;
351 	uint64_t	ift_dequeued;
352 #endif
353 	uint64_t	ift_no_tx_dma_setup;
354 	uint64_t	ift_no_desc_avail;
355 	uint64_t	ift_mbuf_defrag_failed;
356 	uint64_t	ift_mbuf_defrag;
357 	uint64_t	ift_map_failed;
358 	uint64_t	ift_txd_encap_efbig;
359 	uint64_t	ift_pullups;
360 	uint64_t	ift_last_timer_tick;
361 
362 	struct mtx	ift_mtx;
363 	struct mtx	ift_db_mtx;
364 
365 	/* constant values */
366 	if_ctx_t	ift_ctx;
367 	struct ifmp_ring	*ift_br;
368 	struct grouptask	ift_task;
369 	qidx_t		ift_size;
370 	uint16_t	ift_id;
371 	struct callout	ift_timer;
372 #ifdef DEV_NETMAP
373 	struct callout	ift_netmap_timer;
374 #endif /* DEV_NETMAP */
375 
376 	if_txsd_vec_t	ift_sds;
377 	uint8_t		ift_qstatus;
378 	uint8_t		ift_closed;
379 	uint8_t		ift_update_freq;
380 	struct iflib_filter_info ift_filter_info;
381 	bus_dma_tag_t	ift_buf_tag;
382 	bus_dma_tag_t	ift_tso_buf_tag;
383 	iflib_dma_info_t	ift_ifdi;
384 #define	MTX_NAME_LEN	32
385 	char		ift_mtx_name[MTX_NAME_LEN];
386 	bus_dma_segment_t	ift_segs[IFLIB_MAX_TX_SEGS]  __aligned(CACHE_LINE_SIZE);
387 #ifdef IFLIB_DIAGNOSTICS
388 	uint64_t ift_cpu_exec_count[256];
389 #endif
390 } __aligned(CACHE_LINE_SIZE);
391 
392 struct iflib_fl {
393 	qidx_t		ifl_cidx;
394 	qidx_t		ifl_pidx;
395 	qidx_t		ifl_credits;
396 	uint8_t		ifl_gen;
397 	uint8_t		ifl_rxd_size;
398 #if MEMORY_LOGGING
399 	uint64_t	ifl_m_enqueued;
400 	uint64_t	ifl_m_dequeued;
401 	uint64_t	ifl_cl_enqueued;
402 	uint64_t	ifl_cl_dequeued;
403 #endif
404 	/* implicit pad */
405 	bitstr_t	*ifl_rx_bitmap;
406 	qidx_t		ifl_fragidx;
407 	/* constant */
408 	qidx_t		ifl_size;
409 	uint16_t	ifl_buf_size;
410 	uint16_t	ifl_cltype;
411 	uma_zone_t	ifl_zone;
412 	iflib_rxsd_array_t	ifl_sds;
413 	iflib_rxq_t	ifl_rxq;
414 	uint8_t		ifl_id;
415 	bus_dma_tag_t	ifl_buf_tag;
416 	iflib_dma_info_t	ifl_ifdi;
417 	uint64_t	ifl_bus_addrs[IFLIB_MAX_RX_REFRESH] __aligned(CACHE_LINE_SIZE);
418 	qidx_t		ifl_rxd_idxs[IFLIB_MAX_RX_REFRESH];
419 }  __aligned(CACHE_LINE_SIZE);
420 
421 static inline qidx_t
422 get_inuse(int size, qidx_t cidx, qidx_t pidx, uint8_t gen)
423 {
424 	qidx_t used;
425 
426 	if (pidx > cidx)
427 		used = pidx - cidx;
428 	else if (pidx < cidx)
429 		used = size - cidx + pidx;
430 	else if (gen == 0 && pidx == cidx)
431 		used = 0;
432 	else if (gen == 1 && pidx == cidx)
433 		used = size;
434 	else
435 		panic("bad state");
436 
437 	return (used);
438 }
439 
440 #define TXQ_AVAIL(txq) (txq->ift_size - get_inuse(txq->ift_size, txq->ift_cidx, txq->ift_pidx, txq->ift_gen))
441 
442 #define IDXDIFF(head, tail, wrap) \
443 	((head) >= (tail) ? (head) - (tail) : (wrap) - (tail) + (head))
444 
445 struct iflib_rxq {
446 	if_ctx_t	ifr_ctx;
447 	iflib_fl_t	ifr_fl;
448 	uint64_t	ifr_rx_irq;
449 	struct pfil_head	*pfil;
450 	/*
451 	 * If there is a separate completion queue (IFLIB_HAS_RXCQ), this is
452 	 * the completion queue consumer index.  Otherwise it's unused.
453 	 */
454 	qidx_t		ifr_cq_cidx;
455 	uint16_t	ifr_id;
456 	uint8_t		ifr_nfl;
457 	uint8_t		ifr_ntxqirq;
458 	uint8_t		ifr_txqid[IFLIB_MAX_TX_SHARED_INTR];
459 	uint8_t		ifr_fl_offset;
460 	struct lro_ctrl		ifr_lc;
461 	struct grouptask	ifr_task;
462 	struct callout		ifr_watchdog;
463 	struct iflib_filter_info ifr_filter_info;
464 	iflib_dma_info_t	ifr_ifdi;
465 
466 	/* dynamically allocate if any drivers need a value substantially larger than this */
467 	struct if_rxd_frag	ifr_frags[IFLIB_MAX_RX_SEGS] __aligned(CACHE_LINE_SIZE);
468 #ifdef IFLIB_DIAGNOSTICS
469 	uint64_t ifr_cpu_exec_count[256];
470 #endif
471 }  __aligned(CACHE_LINE_SIZE);
472 
473 typedef struct if_rxsd {
474 	caddr_t *ifsd_cl;
475 	iflib_fl_t ifsd_fl;
476 } *if_rxsd_t;
477 
478 /* multiple of word size */
479 #ifdef __LP64__
480 #define PKT_INFO_SIZE	6
481 #define RXD_INFO_SIZE	5
482 #define PKT_TYPE uint64_t
483 #else
484 #define PKT_INFO_SIZE	11
485 #define RXD_INFO_SIZE	8
486 #define PKT_TYPE uint32_t
487 #endif
488 #define PKT_LOOP_BOUND	((PKT_INFO_SIZE / 3) * 3)
489 #define RXD_LOOP_BOUND	((RXD_INFO_SIZE / 4) * 4)
490 
491 typedef struct if_pkt_info_pad {
492 	PKT_TYPE pkt_val[PKT_INFO_SIZE];
493 } *if_pkt_info_pad_t;
494 typedef struct if_rxd_info_pad {
495 	PKT_TYPE rxd_val[RXD_INFO_SIZE];
496 } *if_rxd_info_pad_t;
497 
498 CTASSERT(sizeof(struct if_pkt_info_pad) == sizeof(struct if_pkt_info));
499 CTASSERT(sizeof(struct if_rxd_info_pad) == sizeof(struct if_rxd_info));
500 
501 static inline void
502 pkt_info_zero(if_pkt_info_t pi)
503 {
504 	if_pkt_info_pad_t pi_pad;
505 
506 	pi_pad = (if_pkt_info_pad_t)pi;
507 	pi_pad->pkt_val[0] = 0; pi_pad->pkt_val[1] = 0; pi_pad->pkt_val[2] = 0;
508 	pi_pad->pkt_val[3] = 0; pi_pad->pkt_val[4] = 0; pi_pad->pkt_val[5] = 0;
509 #ifndef __LP64__
510 	pi_pad->pkt_val[6] = 0; pi_pad->pkt_val[7] = 0; pi_pad->pkt_val[8] = 0;
511 	pi_pad->pkt_val[9] = 0; pi_pad->pkt_val[10] = 0;
512 #endif
513 }
514 
515 static inline void
516 rxd_info_zero(if_rxd_info_t ri)
517 {
518 	if_rxd_info_pad_t ri_pad;
519 	int i;
520 
521 	ri_pad = (if_rxd_info_pad_t)ri;
522 	for (i = 0; i < RXD_LOOP_BOUND; i += 4) {
523 		ri_pad->rxd_val[i] = 0;
524 		ri_pad->rxd_val[i + 1] = 0;
525 		ri_pad->rxd_val[i + 2] = 0;
526 		ri_pad->rxd_val[i + 3] = 0;
527 	}
528 #ifdef __LP64__
529 	ri_pad->rxd_val[RXD_INFO_SIZE - 1] = 0;
530 #endif
531 }
532 
533 /*
534  * Only allow a single packet to take up most 1/nth of the tx ring
535  */
536 #define MAX_SINGLE_PACKET_FRACTION 12
537 #define IF_BAD_DMA	((bus_addr_t)-1)
538 
539 #define CTX_ACTIVE(ctx)	((if_getdrvflags((ctx)->ifc_ifp) & IFF_DRV_RUNNING))
540 
541 #define CTX_LOCK_INIT(_sc)	sx_init(&(_sc)->ifc_ctx_sx, "iflib ctx lock")
542 #define CTX_LOCK(ctx)		sx_xlock(&(ctx)->ifc_ctx_sx)
543 #define CTX_UNLOCK(ctx)		sx_xunlock(&(ctx)->ifc_ctx_sx)
544 #define CTX_LOCK_DESTROY(ctx)	sx_destroy(&(ctx)->ifc_ctx_sx)
545 
546 #define STATE_LOCK_INIT(_sc, _name)	mtx_init(&(_sc)->ifc_state_mtx, _name, "iflib state lock", MTX_DEF)
547 #define STATE_LOCK(ctx)		mtx_lock(&(ctx)->ifc_state_mtx)
548 #define STATE_UNLOCK(ctx)	mtx_unlock(&(ctx)->ifc_state_mtx)
549 #define STATE_LOCK_DESTROY(ctx)	mtx_destroy(&(ctx)->ifc_state_mtx)
550 
551 #define CALLOUT_LOCK(txq)	mtx_lock(&txq->ift_mtx)
552 #define CALLOUT_UNLOCK(txq)	mtx_unlock(&txq->ift_mtx)
553 
554 /* Our boot-time initialization hook */
555 static int	iflib_module_event_handler(module_t, int, void *);
556 
557 static moduledata_t iflib_moduledata = {
558 	"iflib",
559 	iflib_module_event_handler,
560 	NULL
561 };
562 
563 DECLARE_MODULE(iflib, iflib_moduledata, SI_SUB_INIT_IF, SI_ORDER_ANY);
564 MODULE_VERSION(iflib, 1);
565 
566 MODULE_DEPEND(iflib, pci, 1, 1, 1);
567 MODULE_DEPEND(iflib, ether, 1, 1, 1);
568 
569 TASKQGROUP_DEFINE(if_io_tqg, mp_ncpus, 1);
570 TASKQGROUP_DEFINE(if_config_tqg, 1, 1);
571 
572 #ifndef IFLIB_DEBUG_COUNTERS
573 #ifdef INVARIANTS
574 #define IFLIB_DEBUG_COUNTERS 1
575 #else
576 #define IFLIB_DEBUG_COUNTERS 0
577 #endif /* !INVARIANTS */
578 #endif
579 
580 static SYSCTL_NODE(_net, OID_AUTO, iflib, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
581     "iflib driver parameters");
582 
583 /*
584  * XXX need to ensure that this can't accidentally cause the head to be moved backwards
585  */
586 static int iflib_min_tx_latency = 0;
587 SYSCTL_INT(_net_iflib, OID_AUTO, min_tx_latency, CTLFLAG_RW,
588     &iflib_min_tx_latency, 0,
589     "minimize transmit latency at the possible expense of throughput");
590 static int iflib_no_tx_batch = 0;
591 SYSCTL_INT(_net_iflib, OID_AUTO, no_tx_batch, CTLFLAG_RW,
592     &iflib_no_tx_batch, 0,
593     "minimize transmit latency at the possible expense of throughput");
594 static int iflib_timer_default = 1000;
595 SYSCTL_INT(_net_iflib, OID_AUTO, timer_default, CTLFLAG_RW,
596     &iflib_timer_default, 0, "number of ticks between iflib_timer calls");
597 
598 
599 #if IFLIB_DEBUG_COUNTERS
600 
601 static int iflib_tx_seen;
602 static int iflib_tx_sent;
603 static int iflib_tx_encap;
604 static int iflib_rx_allocs;
605 static int iflib_fl_refills;
606 static int iflib_fl_refills_large;
607 static int iflib_tx_frees;
608 
609 SYSCTL_INT(_net_iflib, OID_AUTO, tx_seen, CTLFLAG_RD, &iflib_tx_seen, 0,
610     "# TX mbufs seen");
611 SYSCTL_INT(_net_iflib, OID_AUTO, tx_sent, CTLFLAG_RD, &iflib_tx_sent, 0,
612     "# TX mbufs sent");
613 SYSCTL_INT(_net_iflib, OID_AUTO, tx_encap, CTLFLAG_RD, &iflib_tx_encap, 0,
614     "# TX mbufs encapped");
615 SYSCTL_INT(_net_iflib, OID_AUTO, tx_frees, CTLFLAG_RD, &iflib_tx_frees, 0,
616     "# TX frees");
617 SYSCTL_INT(_net_iflib, OID_AUTO, rx_allocs, CTLFLAG_RD, &iflib_rx_allocs, 0,
618     "# RX allocations");
619 SYSCTL_INT(_net_iflib, OID_AUTO, fl_refills, CTLFLAG_RD, &iflib_fl_refills, 0,
620     "# refills");
621 SYSCTL_INT(_net_iflib, OID_AUTO, fl_refills_large, CTLFLAG_RD,
622     &iflib_fl_refills_large, 0, "# large refills");
623 
624 static int iflib_txq_drain_flushing;
625 static int iflib_txq_drain_oactive;
626 static int iflib_txq_drain_notready;
627 
628 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_flushing, CTLFLAG_RD,
629     &iflib_txq_drain_flushing, 0, "# drain flushes");
630 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_oactive, CTLFLAG_RD,
631     &iflib_txq_drain_oactive, 0, "# drain oactives");
632 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_notready, CTLFLAG_RD,
633     &iflib_txq_drain_notready, 0, "# drain notready");
634 
635 static int iflib_encap_load_mbuf_fail;
636 static int iflib_encap_pad_mbuf_fail;
637 static int iflib_encap_txq_avail_fail;
638 static int iflib_encap_txd_encap_fail;
639 
640 SYSCTL_INT(_net_iflib, OID_AUTO, encap_load_mbuf_fail, CTLFLAG_RD,
641     &iflib_encap_load_mbuf_fail, 0, "# busdma load failures");
642 SYSCTL_INT(_net_iflib, OID_AUTO, encap_pad_mbuf_fail, CTLFLAG_RD,
643     &iflib_encap_pad_mbuf_fail, 0, "# runt frame pad failures");
644 SYSCTL_INT(_net_iflib, OID_AUTO, encap_txq_avail_fail, CTLFLAG_RD,
645     &iflib_encap_txq_avail_fail, 0, "# txq avail failures");
646 SYSCTL_INT(_net_iflib, OID_AUTO, encap_txd_encap_fail, CTLFLAG_RD,
647     &iflib_encap_txd_encap_fail, 0, "# driver encap failures");
648 
649 static int iflib_task_fn_rxs;
650 static int iflib_rx_intr_enables;
651 static int iflib_fast_intrs;
652 static int iflib_rx_unavail;
653 static int iflib_rx_ctx_inactive;
654 static int iflib_rx_if_input;
655 static int iflib_rxd_flush;
656 
657 static int iflib_verbose_debug;
658 
659 SYSCTL_INT(_net_iflib, OID_AUTO, task_fn_rx, CTLFLAG_RD, &iflib_task_fn_rxs, 0,
660     "# task_fn_rx calls");
661 SYSCTL_INT(_net_iflib, OID_AUTO, rx_intr_enables, CTLFLAG_RD,
662     &iflib_rx_intr_enables, 0, "# RX intr enables");
663 SYSCTL_INT(_net_iflib, OID_AUTO, fast_intrs, CTLFLAG_RD, &iflib_fast_intrs, 0,
664     "# fast_intr calls");
665 SYSCTL_INT(_net_iflib, OID_AUTO, rx_unavail, CTLFLAG_RD, &iflib_rx_unavail, 0,
666     "# times rxeof called with no available data");
667 SYSCTL_INT(_net_iflib, OID_AUTO, rx_ctx_inactive, CTLFLAG_RD,
668     &iflib_rx_ctx_inactive, 0, "# times rxeof called with inactive context");
669 SYSCTL_INT(_net_iflib, OID_AUTO, rx_if_input, CTLFLAG_RD, &iflib_rx_if_input,
670     0, "# times rxeof called if_input");
671 SYSCTL_INT(_net_iflib, OID_AUTO, rxd_flush, CTLFLAG_RD, &iflib_rxd_flush, 0,
672     "# times rxd_flush called");
673 SYSCTL_INT(_net_iflib, OID_AUTO, verbose_debug, CTLFLAG_RW,
674     &iflib_verbose_debug, 0, "enable verbose debugging");
675 
676 #define DBG_COUNTER_INC(name) atomic_add_int(&(iflib_ ## name), 1)
677 static void
678 iflib_debug_reset(void)
679 {
680 	iflib_tx_seen = iflib_tx_sent = iflib_tx_encap = iflib_rx_allocs =
681 		iflib_fl_refills = iflib_fl_refills_large = iflib_tx_frees =
682 		iflib_txq_drain_flushing = iflib_txq_drain_oactive =
683 		iflib_txq_drain_notready =
684 		iflib_encap_load_mbuf_fail = iflib_encap_pad_mbuf_fail =
685 		iflib_encap_txq_avail_fail = iflib_encap_txd_encap_fail =
686 		iflib_task_fn_rxs = iflib_rx_intr_enables = iflib_fast_intrs =
687 		iflib_rx_unavail =
688 		iflib_rx_ctx_inactive = iflib_rx_if_input =
689 		iflib_rxd_flush = 0;
690 }
691 
692 #else
693 #define DBG_COUNTER_INC(name)
694 static void iflib_debug_reset(void) {}
695 #endif
696 
697 #define IFLIB_DEBUG 0
698 
699 static void iflib_tx_structures_free(if_ctx_t ctx);
700 static void iflib_rx_structures_free(if_ctx_t ctx);
701 static int iflib_queues_alloc(if_ctx_t ctx);
702 static int iflib_tx_credits_update(if_ctx_t ctx, iflib_txq_t txq);
703 static int iflib_rxd_avail(if_ctx_t ctx, iflib_rxq_t rxq, qidx_t cidx, qidx_t budget);
704 static int iflib_qset_structures_setup(if_ctx_t ctx);
705 static int iflib_msix_init(if_ctx_t ctx);
706 static int iflib_legacy_setup(if_ctx_t ctx, driver_filter_t filter, void *filterarg, int *rid, const char *str);
707 static void iflib_txq_check_drain(iflib_txq_t txq, int budget);
708 static uint32_t iflib_txq_can_drain(struct ifmp_ring *);
709 #ifdef ALTQ
710 static void iflib_altq_if_start(if_t ifp);
711 static int iflib_altq_if_transmit(if_t ifp, struct mbuf *m);
712 #endif
713 static int iflib_register(if_ctx_t);
714 static void iflib_deregister(if_ctx_t);
715 static void iflib_unregister_vlan_handlers(if_ctx_t ctx);
716 static uint16_t iflib_get_mbuf_size_for(unsigned int size);
717 static void iflib_init_locked(if_ctx_t ctx);
718 static void iflib_add_device_sysctl_pre(if_ctx_t ctx);
719 static void iflib_add_device_sysctl_post(if_ctx_t ctx);
720 static void iflib_ifmp_purge(iflib_txq_t txq);
721 static void _iflib_pre_assert(if_softc_ctx_t scctx);
722 static void iflib_stop(if_ctx_t ctx);
723 static void iflib_if_init_locked(if_ctx_t ctx);
724 static void iflib_free_intr_mem(if_ctx_t ctx);
725 #ifndef __NO_STRICT_ALIGNMENT
726 static struct mbuf *iflib_fixup_rx(struct mbuf *m);
727 #endif
728 
729 static SLIST_HEAD(cpu_offset_list, cpu_offset) cpu_offsets =
730     SLIST_HEAD_INITIALIZER(cpu_offsets);
731 struct cpu_offset {
732 	SLIST_ENTRY(cpu_offset) entries;
733 	cpuset_t	set;
734 	unsigned int	refcount;
735 	uint16_t	next_cpuid;
736 };
737 static struct mtx cpu_offset_mtx;
738 MTX_SYSINIT(iflib_cpu_offset, &cpu_offset_mtx, "iflib_cpu_offset lock",
739     MTX_DEF);
740 
741 DEBUGNET_DEFINE(iflib);
742 
743 static int
744 iflib_num_rx_descs(if_ctx_t ctx)
745 {
746 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
747 	if_shared_ctx_t sctx = ctx->ifc_sctx;
748 	uint16_t first_rxq = (sctx->isc_flags & IFLIB_HAS_RXCQ) ? 1 : 0;
749 
750 	return (scctx->isc_nrxd[first_rxq]);
751 }
752 
753 static int
754 iflib_num_tx_descs(if_ctx_t ctx)
755 {
756 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
757 	if_shared_ctx_t sctx = ctx->ifc_sctx;
758 	uint16_t first_txq = (sctx->isc_flags & IFLIB_HAS_TXCQ) ? 1 : 0;
759 
760 	return (scctx->isc_ntxd[first_txq]);
761 }
762 
763 #ifdef DEV_NETMAP
764 #include <sys/selinfo.h>
765 #include <net/netmap.h>
766 #include <dev/netmap/netmap_kern.h>
767 
768 MODULE_DEPEND(iflib, netmap, 1, 1, 1);
769 
770 static int netmap_fl_refill(iflib_rxq_t rxq, struct netmap_kring *kring, bool init);
771 static void iflib_netmap_timer(void *arg);
772 
773 /*
774  * device-specific sysctl variables:
775  *
776  * iflib_crcstrip: 0: keep CRC in rx frames (default), 1: strip it.
777  *	During regular operations the CRC is stripped, but on some
778  *	hardware reception of frames not multiple of 64 is slower,
779  *	so using crcstrip=0 helps in benchmarks.
780  *
781  * iflib_rx_miss, iflib_rx_miss_bufs:
782  *	count packets that might be missed due to lost interrupts.
783  */
784 SYSCTL_DECL(_dev_netmap);
785 /*
786  * The xl driver by default strips CRCs and we do not override it.
787  */
788 
789 int iflib_crcstrip = 1;
790 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_crcstrip,
791     CTLFLAG_RW, &iflib_crcstrip, 1, "strip CRC on RX frames");
792 
793 int iflib_rx_miss, iflib_rx_miss_bufs;
794 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_rx_miss,
795     CTLFLAG_RW, &iflib_rx_miss, 0, "potentially missed RX intr");
796 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_rx_miss_bufs,
797     CTLFLAG_RW, &iflib_rx_miss_bufs, 0, "potentially missed RX intr bufs");
798 
799 /*
800  * Register/unregister. We are already under netmap lock.
801  * Only called on the first register or the last unregister.
802  */
803 static int
804 iflib_netmap_register(struct netmap_adapter *na, int onoff)
805 {
806 	if_t ifp = na->ifp;
807 	if_ctx_t ctx = if_getsoftc(ifp);
808 	int status;
809 
810 	CTX_LOCK(ctx);
811 	if (!CTX_IS_VF(ctx))
812 		IFDI_CRCSTRIP_SET(ctx, onoff, iflib_crcstrip);
813 
814 	iflib_stop(ctx);
815 
816 	/*
817 	 * Enable (or disable) netmap flags, and intercept (or restore)
818 	 * ifp->if_transmit. This is done once the device has been stopped
819 	 * to prevent race conditions. Also, this must be done after
820 	 * calling netmap_disable_all_rings() and before calling
821 	 * netmap_enable_all_rings(), so that these two functions see the
822 	 * updated state of the NAF_NETMAP_ON bit.
823 	 */
824 	if (onoff) {
825 		nm_set_native_flags(na);
826 	} else {
827 		nm_clear_native_flags(na);
828 	}
829 
830 	iflib_init_locked(ctx);
831 	IFDI_CRCSTRIP_SET(ctx, onoff, iflib_crcstrip); // XXX why twice ?
832 	status = if_getdrvflags(ifp) & IFF_DRV_RUNNING ? 0 : 1;
833 	if (status)
834 		nm_clear_native_flags(na);
835 	CTX_UNLOCK(ctx);
836 	return (status);
837 }
838 
839 static int
840 iflib_netmap_config(struct netmap_adapter *na, struct nm_config_info *info)
841 {
842 	if_t ifp = na->ifp;
843 	if_ctx_t ctx = if_getsoftc(ifp);
844 	iflib_rxq_t rxq = &ctx->ifc_rxqs[0];
845 	iflib_fl_t fl = &rxq->ifr_fl[0];
846 
847 	info->num_tx_rings = ctx->ifc_softc_ctx.isc_ntxqsets;
848 	info->num_rx_rings = ctx->ifc_softc_ctx.isc_nrxqsets;
849 	info->num_tx_descs = iflib_num_tx_descs(ctx);
850 	info->num_rx_descs = iflib_num_rx_descs(ctx);
851 	info->rx_buf_maxsize = fl->ifl_buf_size;
852 	nm_prinf("txr %u rxr %u txd %u rxd %u rbufsz %u",
853 		info->num_tx_rings, info->num_rx_rings, info->num_tx_descs,
854 		info->num_rx_descs, info->rx_buf_maxsize);
855 
856 	return (0);
857 }
858 
859 static int
860 netmap_fl_refill(iflib_rxq_t rxq, struct netmap_kring *kring, bool init)
861 {
862 	struct netmap_adapter *na = kring->na;
863 	u_int const lim = kring->nkr_num_slots - 1;
864 	struct netmap_ring *ring = kring->ring;
865 	bus_dmamap_t *map;
866 	struct if_rxd_update iru;
867 	if_ctx_t ctx = rxq->ifr_ctx;
868 	iflib_fl_t fl = &rxq->ifr_fl[0];
869 	u_int nic_i_first, nic_i;
870 	u_int nm_i;
871 	int i, n;
872 #if IFLIB_DEBUG_COUNTERS
873 	int rf_count = 0;
874 #endif
875 
876 	/*
877 	 * This function is used both at initialization and in rxsync.
878 	 * At initialization we need to prepare (with isc_rxd_refill())
879 	 * all the netmap buffers currently owned by the kernel, in
880 	 * such a way to keep fl->ifl_pidx and kring->nr_hwcur in sync
881 	 * (except for kring->nkr_hwofs). These may be less than
882 	 * kring->nkr_num_slots if netmap_reset() was called while
883 	 * an application using the kring that still owned some
884 	 * buffers.
885 	 * At rxsync time, both indexes point to the next buffer to be
886 	 * refilled.
887 	 * In any case we publish (with isc_rxd_flush()) up to
888 	 * (fl->ifl_pidx - 1) % N (included), to avoid the NIC tail/prod
889 	 * pointer to overrun the head/cons pointer, although this is
890 	 * not necessary for some NICs (e.g. vmx).
891 	 */
892 	if (__predict_false(init)) {
893 		n = kring->nkr_num_slots - nm_kr_rxspace(kring);
894 	} else {
895 		n = kring->rhead - kring->nr_hwcur;
896 		if (n == 0)
897 			return (0); /* Nothing to do. */
898 		if (n < 0)
899 			n += kring->nkr_num_slots;
900 	}
901 
902 	iru_init(&iru, rxq, 0 /* flid */);
903 	map = fl->ifl_sds.ifsd_map;
904 	nic_i = fl->ifl_pidx;
905 	nm_i = netmap_idx_n2k(kring, nic_i);
906 	if (__predict_false(init)) {
907 		/*
908 		 * On init/reset, nic_i must be 0, and we must
909 		 * start to refill from hwtail (see netmap_reset()).
910 		 */
911 		MPASS(nic_i == 0);
912 		MPASS(nm_i == kring->nr_hwtail);
913 	} else
914 		MPASS(nm_i == kring->nr_hwcur);
915 	DBG_COUNTER_INC(fl_refills);
916 	while (n > 0) {
917 #if IFLIB_DEBUG_COUNTERS
918 		if (++rf_count == 9)
919 			DBG_COUNTER_INC(fl_refills_large);
920 #endif
921 		nic_i_first = nic_i;
922 		for (i = 0; n > 0 && i < IFLIB_MAX_RX_REFRESH; n--, i++) {
923 			struct netmap_slot *slot = &ring->slot[nm_i];
924 			uint64_t paddr;
925 			void *addr = PNMB(na, slot, &paddr);
926 
927 			MPASS(i < IFLIB_MAX_RX_REFRESH);
928 
929 			if (addr == NETMAP_BUF_BASE(na)) /* bad buf */
930 				return (netmap_ring_reinit(kring));
931 
932 			fl->ifl_bus_addrs[i] = paddr +
933 			    nm_get_offset(kring, slot);
934 			fl->ifl_rxd_idxs[i] = nic_i;
935 
936 			if (__predict_false(init)) {
937 				netmap_load_map(na, fl->ifl_buf_tag,
938 				    map[nic_i], addr);
939 			} else if (slot->flags & NS_BUF_CHANGED) {
940 				/* buffer has changed, reload map */
941 				netmap_reload_map(na, fl->ifl_buf_tag,
942 				    map[nic_i], addr);
943 			}
944 			bus_dmamap_sync(fl->ifl_buf_tag, map[nic_i],
945 			    BUS_DMASYNC_PREREAD);
946 			slot->flags &= ~NS_BUF_CHANGED;
947 
948 			nm_i = nm_next(nm_i, lim);
949 			nic_i = nm_next(nic_i, lim);
950 		}
951 
952 		iru.iru_pidx = nic_i_first;
953 		iru.iru_count = i;
954 		ctx->isc_rxd_refill(ctx->ifc_softc, &iru);
955 	}
956 	fl->ifl_pidx = nic_i;
957 	/*
958 	 * At the end of the loop we must have refilled everything
959 	 * we could possibly refill.
960 	 */
961 	MPASS(nm_i == kring->rhead);
962 	kring->nr_hwcur = nm_i;
963 
964 	bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
965 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
966 	ctx->isc_rxd_flush(ctx->ifc_softc, rxq->ifr_id, fl->ifl_id,
967 	    nm_prev(nic_i, lim));
968 	DBG_COUNTER_INC(rxd_flush);
969 
970 	return (0);
971 }
972 
973 #define NETMAP_TX_TIMER_US	90
974 
975 /*
976  * Reconcile kernel and user view of the transmit ring.
977  *
978  * All information is in the kring.
979  * Userspace wants to send packets up to the one before kring->rhead,
980  * kernel knows kring->nr_hwcur is the first unsent packet.
981  *
982  * Here we push packets out (as many as possible), and possibly
983  * reclaim buffers from previously completed transmission.
984  *
985  * The caller (netmap) guarantees that there is only one instance
986  * running at any time. Any interference with other driver
987  * methods should be handled by the individual drivers.
988  */
989 static int
990 iflib_netmap_txsync(struct netmap_kring *kring, int flags)
991 {
992 	struct netmap_adapter *na = kring->na;
993 	if_t ifp = na->ifp;
994 	struct netmap_ring *ring = kring->ring;
995 	u_int nm_i;	/* index into the netmap kring */
996 	u_int nic_i;	/* index into the NIC ring */
997 	u_int const lim = kring->nkr_num_slots - 1;
998 	u_int const head = kring->rhead;
999 	struct if_pkt_info pi;
1000 	int tx_pkts = 0, tx_bytes = 0;
1001 
1002 	/*
1003 	 * interrupts on every tx packet are expensive so request
1004 	 * them every half ring, or where NS_REPORT is set
1005 	 */
1006 	u_int report_frequency = kring->nkr_num_slots >> 1;
1007 	/* device-specific */
1008 	if_ctx_t ctx = if_getsoftc(ifp);
1009 	iflib_txq_t txq = &ctx->ifc_txqs[kring->ring_id];
1010 
1011 	bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
1012 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1013 
1014 	/*
1015 	 * First part: process new packets to send.
1016 	 * nm_i is the current index in the netmap kring,
1017 	 * nic_i is the corresponding index in the NIC ring.
1018 	 *
1019 	 * If we have packets to send (nm_i != head)
1020 	 * iterate over the netmap ring, fetch length and update
1021 	 * the corresponding slot in the NIC ring. Some drivers also
1022 	 * need to update the buffer's physical address in the NIC slot
1023 	 * even NS_BUF_CHANGED is not set (PNMB computes the addresses).
1024 	 *
1025 	 * The netmap_reload_map() calls is especially expensive,
1026 	 * even when (as in this case) the tag is 0, so do only
1027 	 * when the buffer has actually changed.
1028 	 *
1029 	 * If possible do not set the report/intr bit on all slots,
1030 	 * but only a few times per ring or when NS_REPORT is set.
1031 	 *
1032 	 * Finally, on 10G and faster drivers, it might be useful
1033 	 * to prefetch the next slot and txr entry.
1034 	 */
1035 
1036 	nm_i = kring->nr_hwcur;
1037 	if (nm_i != head) {	/* we have new packets to send */
1038 		uint32_t pkt_len = 0, seg_idx = 0;
1039 		int nic_i_start = -1, flags = 0;
1040 		pkt_info_zero(&pi);
1041 		pi.ipi_segs = txq->ift_segs;
1042 		pi.ipi_qsidx = kring->ring_id;
1043 		nic_i = netmap_idx_k2n(kring, nm_i);
1044 
1045 		__builtin_prefetch(&ring->slot[nm_i]);
1046 		__builtin_prefetch(&txq->ift_sds.ifsd_m[nic_i]);
1047 		__builtin_prefetch(&txq->ift_sds.ifsd_map[nic_i]);
1048 
1049 		while (nm_i != head) {
1050 			struct netmap_slot *slot = &ring->slot[nm_i];
1051 			uint64_t offset = nm_get_offset(kring, slot);
1052 			u_int len = slot->len;
1053 			uint64_t paddr;
1054 			void *addr = PNMB(na, slot, &paddr);
1055 
1056 			flags |= (slot->flags & NS_REPORT ||
1057 				nic_i == 0 || nic_i == report_frequency) ?
1058 				IPI_TX_INTR : 0;
1059 
1060 			/*
1061 			 * If this is the first packet fragment, save the
1062 			 * index of the first NIC slot for later.
1063 			 */
1064 			if (nic_i_start < 0)
1065 				nic_i_start = nic_i;
1066 
1067 			pi.ipi_segs[seg_idx].ds_addr = paddr + offset;
1068 			pi.ipi_segs[seg_idx].ds_len = len;
1069 			if (len) {
1070 				pkt_len += len;
1071 				seg_idx++;
1072 			}
1073 
1074 			if (!(slot->flags & NS_MOREFRAG)) {
1075 				pi.ipi_len = pkt_len;
1076 				pi.ipi_nsegs = seg_idx;
1077 				pi.ipi_pidx = nic_i_start;
1078 				pi.ipi_ndescs = 0;
1079 				pi.ipi_flags = flags;
1080 
1081 				/* Prepare the NIC TX ring. */
1082 				ctx->isc_txd_encap(ctx->ifc_softc, &pi);
1083 				DBG_COUNTER_INC(tx_encap);
1084 
1085 				/* Update transmit counters */
1086 				tx_bytes += pi.ipi_len;
1087 				tx_pkts++;
1088 
1089 				/* Reinit per-packet info for the next one. */
1090 				flags = seg_idx = pkt_len = 0;
1091 				nic_i_start = -1;
1092 			}
1093 
1094 			/* prefetch for next round */
1095 			__builtin_prefetch(&ring->slot[nm_i + 1]);
1096 			__builtin_prefetch(&txq->ift_sds.ifsd_m[nic_i + 1]);
1097 			__builtin_prefetch(&txq->ift_sds.ifsd_map[nic_i + 1]);
1098 
1099 			NM_CHECK_ADDR_LEN_OFF(na, len, offset);
1100 
1101 			if (slot->flags & NS_BUF_CHANGED) {
1102 				/* buffer has changed, reload map */
1103 				netmap_reload_map(na, txq->ift_buf_tag,
1104 				    txq->ift_sds.ifsd_map[nic_i], addr);
1105 			}
1106 			/* make sure changes to the buffer are synced */
1107 			bus_dmamap_sync(txq->ift_buf_tag,
1108 			    txq->ift_sds.ifsd_map[nic_i],
1109 			    BUS_DMASYNC_PREWRITE);
1110 
1111 			slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED | NS_MOREFRAG);
1112 			nm_i = nm_next(nm_i, lim);
1113 			nic_i = nm_next(nic_i, lim);
1114 		}
1115 		kring->nr_hwcur = nm_i;
1116 
1117 		/* synchronize the NIC ring */
1118 		bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
1119 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1120 
1121 		/* (re)start the tx unit up to slot nic_i (excluded) */
1122 		ctx->isc_txd_flush(ctx->ifc_softc, txq->ift_id, nic_i);
1123 	}
1124 
1125 	/*
1126 	 * Second part: reclaim buffers for completed transmissions.
1127 	 *
1128 	 * If there are unclaimed buffers, attempt to reclaim them.
1129 	 * If we don't manage to reclaim them all, and TX IRQs are not in use,
1130 	 * trigger a per-tx-queue timer to try again later.
1131 	 */
1132 	if (kring->nr_hwtail != nm_prev(kring->nr_hwcur, lim)) {
1133 		if (iflib_tx_credits_update(ctx, txq)) {
1134 			/* some tx completed, increment avail */
1135 			nic_i = txq->ift_cidx_processed;
1136 			kring->nr_hwtail = nm_prev(netmap_idx_n2k(kring, nic_i), lim);
1137 		}
1138 	}
1139 
1140 	if (!(ctx->ifc_flags & IFC_NETMAP_TX_IRQ))
1141 		if (kring->nr_hwtail != nm_prev(kring->nr_hwcur, lim)) {
1142 			callout_reset_sbt_on(&txq->ift_netmap_timer,
1143 			    NETMAP_TX_TIMER_US * SBT_1US, SBT_1US,
1144 			    iflib_netmap_timer, txq,
1145 			    txq->ift_netmap_timer.c_cpu, 0);
1146 		}
1147 
1148 	if_inc_counter(ifp, IFCOUNTER_OBYTES, tx_bytes);
1149 	if_inc_counter(ifp, IFCOUNTER_OPACKETS, tx_pkts);
1150 
1151 	return (0);
1152 }
1153 
1154 /*
1155  * Reconcile kernel and user view of the receive ring.
1156  * Same as for the txsync, this routine must be efficient.
1157  * The caller guarantees a single invocations, but races against
1158  * the rest of the driver should be handled here.
1159  *
1160  * On call, kring->rhead is the first packet that userspace wants
1161  * to keep, and kring->rcur is the wakeup point.
1162  * The kernel has previously reported packets up to kring->rtail.
1163  *
1164  * If (flags & NAF_FORCE_READ) also check for incoming packets irrespective
1165  * of whether or not we received an interrupt.
1166  */
1167 static int
1168 iflib_netmap_rxsync(struct netmap_kring *kring, int flags)
1169 {
1170 	struct netmap_adapter *na = kring->na;
1171 	struct netmap_ring *ring = kring->ring;
1172 	if_t ifp = na->ifp;
1173 	uint32_t nm_i;	/* index into the netmap ring */
1174 	uint32_t nic_i;	/* index into the NIC ring */
1175 	u_int n;
1176 	u_int const lim = kring->nkr_num_slots - 1;
1177 	int force_update = (flags & NAF_FORCE_READ) || kring->nr_kflags & NKR_PENDINTR;
1178 	int i = 0, rx_bytes = 0, rx_pkts = 0;
1179 
1180 	if_ctx_t ctx = if_getsoftc(ifp);
1181 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1182 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1183 	iflib_rxq_t rxq = &ctx->ifc_rxqs[kring->ring_id];
1184 	iflib_fl_t fl = &rxq->ifr_fl[0];
1185 	struct if_rxd_info ri;
1186 	qidx_t *cidxp;
1187 
1188 	/*
1189 	 * netmap only uses free list 0, to avoid out of order consumption
1190 	 * of receive buffers
1191 	 */
1192 
1193 	bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
1194 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1195 
1196 	/*
1197 	 * First part: import newly received packets.
1198 	 *
1199 	 * nm_i is the index of the next free slot in the netmap ring,
1200 	 * nic_i is the index of the next received packet in the NIC ring
1201 	 * (or in the free list 0 if IFLIB_HAS_RXCQ is set), and they may
1202 	 * differ in case if_init() has been called while
1203 	 * in netmap mode. For the receive ring we have
1204 	 *
1205 	 *	nic_i = fl->ifl_cidx;
1206 	 *	nm_i = kring->nr_hwtail (previous)
1207 	 * and
1208 	 *	nm_i == (nic_i + kring->nkr_hwofs) % ring_size
1209 	 *
1210 	 * fl->ifl_cidx is set to 0 on a ring reinit
1211 	 */
1212 	if (netmap_no_pendintr || force_update) {
1213 		uint32_t hwtail_lim = nm_prev(kring->nr_hwcur, lim);
1214 		bool have_rxcq = sctx->isc_flags & IFLIB_HAS_RXCQ;
1215 		int crclen = iflib_crcstrip ? 0 : 4;
1216 		int error, avail;
1217 
1218 		/*
1219 		 * For the free list consumer index, we use the same
1220 		 * logic as in iflib_rxeof().
1221 		 */
1222 		if (have_rxcq)
1223 			cidxp = &rxq->ifr_cq_cidx;
1224 		else
1225 			cidxp = &fl->ifl_cidx;
1226 		avail = ctx->isc_rxd_available(ctx->ifc_softc,
1227 		    rxq->ifr_id, *cidxp, USHRT_MAX);
1228 
1229 		nic_i = fl->ifl_cidx;
1230 		nm_i = netmap_idx_n2k(kring, nic_i);
1231 		MPASS(nm_i == kring->nr_hwtail);
1232 		for (n = 0; avail > 0 && nm_i != hwtail_lim; n++, avail--) {
1233 			rxd_info_zero(&ri);
1234 			ri.iri_frags = rxq->ifr_frags;
1235 			ri.iri_qsidx = kring->ring_id;
1236 			ri.iri_ifp = ctx->ifc_ifp;
1237 			ri.iri_cidx = *cidxp;
1238 
1239 			error = ctx->isc_rxd_pkt_get(ctx->ifc_softc, &ri);
1240 			for (i = 0; i < ri.iri_nfrags; i++) {
1241 				if (error) {
1242 					ring->slot[nm_i].len = 0;
1243 					ring->slot[nm_i].flags = 0;
1244 				} else {
1245 					ring->slot[nm_i].len = ri.iri_frags[i].irf_len;
1246 					if (i == (ri.iri_nfrags - 1)) {
1247 						ring->slot[nm_i].len -= crclen;
1248 						ring->slot[nm_i].flags = 0;
1249 
1250 						/* Update receive counters */
1251 						rx_bytes += ri.iri_len;
1252 						rx_pkts++;
1253 					} else
1254 						ring->slot[nm_i].flags = NS_MOREFRAG;
1255 				}
1256 
1257 				bus_dmamap_sync(fl->ifl_buf_tag,
1258 				    fl->ifl_sds.ifsd_map[nic_i], BUS_DMASYNC_POSTREAD);
1259 				nm_i = nm_next(nm_i, lim);
1260 				fl->ifl_cidx = nic_i = nm_next(nic_i, lim);
1261 			}
1262 
1263 			if (have_rxcq) {
1264 				*cidxp = ri.iri_cidx;
1265 				while (*cidxp >= scctx->isc_nrxd[0])
1266 					*cidxp -= scctx->isc_nrxd[0];
1267 			}
1268 
1269 		}
1270 		if (n) { /* update the state variables */
1271 			if (netmap_no_pendintr && !force_update) {
1272 				/* diagnostics */
1273 				iflib_rx_miss++;
1274 				iflib_rx_miss_bufs += n;
1275 			}
1276 			kring->nr_hwtail = nm_i;
1277 		}
1278 		kring->nr_kflags &= ~NKR_PENDINTR;
1279 	}
1280 	/*
1281 	 * Second part: skip past packets that userspace has released.
1282 	 * (kring->nr_hwcur to head excluded),
1283 	 * and make the buffers available for reception.
1284 	 * As usual nm_i is the index in the netmap ring,
1285 	 * nic_i is the index in the NIC ring, and
1286 	 * nm_i == (nic_i + kring->nkr_hwofs) % ring_size
1287 	 */
1288 	netmap_fl_refill(rxq, kring, false);
1289 
1290 	if_inc_counter(ifp, IFCOUNTER_IBYTES, rx_bytes);
1291 	if_inc_counter(ifp, IFCOUNTER_IPACKETS, rx_pkts);
1292 
1293 	return (0);
1294 }
1295 
1296 static void
1297 iflib_netmap_intr(struct netmap_adapter *na, int onoff)
1298 {
1299 	if_ctx_t ctx = if_getsoftc(na->ifp);
1300 
1301 	CTX_LOCK(ctx);
1302 	if (onoff) {
1303 		IFDI_INTR_ENABLE(ctx);
1304 	} else {
1305 		IFDI_INTR_DISABLE(ctx);
1306 	}
1307 	CTX_UNLOCK(ctx);
1308 }
1309 
1310 static int
1311 iflib_netmap_attach(if_ctx_t ctx)
1312 {
1313 	struct netmap_adapter na;
1314 
1315 	bzero(&na, sizeof(na));
1316 
1317 	na.ifp = ctx->ifc_ifp;
1318 	na.na_flags = NAF_BDG_MAYSLEEP | NAF_MOREFRAG | NAF_OFFSETS;
1319 	MPASS(ctx->ifc_softc_ctx.isc_ntxqsets);
1320 	MPASS(ctx->ifc_softc_ctx.isc_nrxqsets);
1321 
1322 	na.num_tx_desc = iflib_num_tx_descs(ctx);
1323 	na.num_rx_desc = iflib_num_rx_descs(ctx);
1324 	na.nm_txsync = iflib_netmap_txsync;
1325 	na.nm_rxsync = iflib_netmap_rxsync;
1326 	na.nm_register = iflib_netmap_register;
1327 	na.nm_intr = iflib_netmap_intr;
1328 	na.nm_config = iflib_netmap_config;
1329 	na.num_tx_rings = ctx->ifc_softc_ctx.isc_ntxqsets;
1330 	na.num_rx_rings = ctx->ifc_softc_ctx.isc_nrxqsets;
1331 	return (netmap_attach(&na));
1332 }
1333 
1334 static int
1335 iflib_netmap_txq_init(if_ctx_t ctx, iflib_txq_t txq)
1336 {
1337 	struct netmap_adapter *na = NA(ctx->ifc_ifp);
1338 	struct netmap_slot *slot;
1339 
1340 	slot = netmap_reset(na, NR_TX, txq->ift_id, 0);
1341 	if (slot == NULL)
1342 		return (0);
1343 	for (int i = 0; i < ctx->ifc_softc_ctx.isc_ntxd[0]; i++) {
1344 		/*
1345 		 * In netmap mode, set the map for the packet buffer.
1346 		 * NOTE: Some drivers (not this one) also need to set
1347 		 * the physical buffer address in the NIC ring.
1348 		 * netmap_idx_n2k() maps a nic index, i, into the corresponding
1349 		 * netmap slot index, si
1350 		 */
1351 		int si = netmap_idx_n2k(na->tx_rings[txq->ift_id], i);
1352 		netmap_load_map(na, txq->ift_buf_tag, txq->ift_sds.ifsd_map[i],
1353 		    NMB(na, slot + si));
1354 	}
1355 	return (1);
1356 }
1357 
1358 static int
1359 iflib_netmap_rxq_init(if_ctx_t ctx, iflib_rxq_t rxq)
1360 {
1361 	struct netmap_adapter *na = NA(ctx->ifc_ifp);
1362 	struct netmap_kring *kring;
1363 	struct netmap_slot *slot;
1364 
1365 	slot = netmap_reset(na, NR_RX, rxq->ifr_id, 0);
1366 	if (slot == NULL)
1367 		return (0);
1368 	kring = na->rx_rings[rxq->ifr_id];
1369 	netmap_fl_refill(rxq, kring, true);
1370 	return (1);
1371 }
1372 
1373 static void
1374 iflib_netmap_timer(void *arg)
1375 {
1376 	iflib_txq_t txq = arg;
1377 	if_ctx_t ctx = txq->ift_ctx;
1378 
1379 	/*
1380 	 * Wake up the netmap application, to give it a chance to
1381 	 * call txsync and reclaim more completed TX buffers.
1382 	 */
1383 	netmap_tx_irq(ctx->ifc_ifp, txq->ift_id);
1384 }
1385 
1386 #define iflib_netmap_detach(ifp) netmap_detach(ifp)
1387 
1388 #else
1389 #define iflib_netmap_txq_init(ctx, txq) (0)
1390 #define iflib_netmap_rxq_init(ctx, rxq) (0)
1391 #define iflib_netmap_detach(ifp)
1392 #define netmap_enable_all_rings(ifp)
1393 #define netmap_disable_all_rings(ifp)
1394 
1395 #define iflib_netmap_attach(ctx) (0)
1396 #define netmap_rx_irq(ifp, qid, budget) (0)
1397 #endif
1398 
1399 #if defined(__i386__) || defined(__amd64__)
1400 static __inline void
1401 prefetch(void *x)
1402 {
1403 	__asm volatile("prefetcht0 %0" :: "m" (*(unsigned long *)x));
1404 }
1405 
1406 static __inline void
1407 prefetch2cachelines(void *x)
1408 {
1409 	__asm volatile("prefetcht0 %0" :: "m" (*(unsigned long *)x));
1410 #if (CACHE_LINE_SIZE < 128)
1411 	__asm volatile("prefetcht0 %0" :: "m" (*(((unsigned long *)x) + CACHE_LINE_SIZE / (sizeof(unsigned long)))));
1412 #endif
1413 }
1414 #else
1415 static __inline void
1416 prefetch(void *x)
1417 {
1418 }
1419 
1420 static __inline void
1421 prefetch2cachelines(void *x)
1422 {
1423 }
1424 #endif
1425 
1426 static void
1427 iru_init(if_rxd_update_t iru, iflib_rxq_t rxq, uint8_t flid)
1428 {
1429 	iflib_fl_t fl;
1430 
1431 	fl = &rxq->ifr_fl[flid];
1432 	iru->iru_paddrs = fl->ifl_bus_addrs;
1433 	iru->iru_idxs = fl->ifl_rxd_idxs;
1434 	iru->iru_qsidx = rxq->ifr_id;
1435 	iru->iru_buf_size = fl->ifl_buf_size;
1436 	iru->iru_flidx = fl->ifl_id;
1437 }
1438 
1439 static void
1440 _iflib_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int err)
1441 {
1442 	if (err)
1443 		return;
1444 	*(bus_addr_t *) arg = segs[0].ds_addr;
1445 }
1446 
1447 #define	DMA_WIDTH_TO_BUS_LOWADDR(width)				\
1448 	(((width) == 0) || (width) == flsll(BUS_SPACE_MAXADDR) ?	\
1449 	    BUS_SPACE_MAXADDR : (1ULL << (width)) - 1ULL)
1450 
1451 int
1452 iflib_dma_alloc_align(if_ctx_t ctx, int size, int align, iflib_dma_info_t dma, int mapflags)
1453 {
1454 	int err;
1455 	device_t dev = ctx->ifc_dev;
1456 	bus_addr_t lowaddr;
1457 
1458 	lowaddr = DMA_WIDTH_TO_BUS_LOWADDR(ctx->ifc_softc_ctx.isc_dma_width);
1459 
1460 	err = bus_dma_tag_create(bus_get_dma_tag(dev),	/* parent */
1461 		    align, 0,		/* alignment, bounds */
1462 		    lowaddr,		/* lowaddr */
1463 		    BUS_SPACE_MAXADDR,	/* highaddr */
1464 		    NULL, NULL,		/* filter, filterarg */
1465 		    size,		/* maxsize */
1466 		    1,			/* nsegments */
1467 		    size,		/* maxsegsize */
1468 		    BUS_DMA_ALLOCNOW,	/* flags */
1469 		    NULL,		/* lockfunc */
1470 		    NULL,		/* lockarg */
1471 		    &dma->idi_tag);
1472 	if (err) {
1473 		device_printf(dev,
1474 		    "%s: bus_dma_tag_create failed: %d (size=%d, align=%d)\n",
1475 		    __func__, err, size, align);
1476 		goto fail_0;
1477 	}
1478 
1479 	err = bus_dmamem_alloc(dma->idi_tag, (void **)&dma->idi_vaddr,
1480 	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT | BUS_DMA_ZERO, &dma->idi_map);
1481 	if (err) {
1482 		device_printf(dev,
1483 		    "%s: bus_dmamem_alloc(%ju) failed: %d\n",
1484 		    __func__, (uintmax_t)size, err);
1485 		goto fail_1;
1486 	}
1487 
1488 	dma->idi_paddr = IF_BAD_DMA;
1489 	err = bus_dmamap_load(dma->idi_tag, dma->idi_map, dma->idi_vaddr,
1490 	    size, _iflib_dmamap_cb, &dma->idi_paddr, mapflags | BUS_DMA_NOWAIT);
1491 	if (err || dma->idi_paddr == IF_BAD_DMA) {
1492 		device_printf(dev,
1493 		    "%s: bus_dmamap_load failed: %d\n",
1494 		    __func__, err);
1495 		goto fail_2;
1496 	}
1497 
1498 	dma->idi_size = size;
1499 	return (0);
1500 
1501 fail_2:
1502 	bus_dmamem_free(dma->idi_tag, dma->idi_vaddr, dma->idi_map);
1503 fail_1:
1504 	bus_dma_tag_destroy(dma->idi_tag);
1505 fail_0:
1506 	dma->idi_tag = NULL;
1507 
1508 	return (err);
1509 }
1510 
1511 int
1512 iflib_dma_alloc(if_ctx_t ctx, int size, iflib_dma_info_t dma, int mapflags)
1513 {
1514 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1515 
1516 	KASSERT(sctx->isc_q_align != 0, ("alignment value not initialized"));
1517 
1518 	return (iflib_dma_alloc_align(ctx, size, sctx->isc_q_align, dma, mapflags));
1519 }
1520 
1521 int
1522 iflib_dma_alloc_multi(if_ctx_t ctx, int *sizes, iflib_dma_info_t *dmalist, int mapflags, int count)
1523 {
1524 	int i, err;
1525 	iflib_dma_info_t *dmaiter;
1526 
1527 	dmaiter = dmalist;
1528 	for (i = 0; i < count; i++, dmaiter++) {
1529 		if ((err = iflib_dma_alloc(ctx, sizes[i], *dmaiter, mapflags)) != 0)
1530 			break;
1531 	}
1532 	if (err)
1533 		iflib_dma_free_multi(dmalist, i);
1534 	return (err);
1535 }
1536 
1537 void
1538 iflib_dma_free(iflib_dma_info_t dma)
1539 {
1540 	if (dma->idi_tag == NULL)
1541 		return;
1542 	if (dma->idi_paddr != IF_BAD_DMA) {
1543 		bus_dmamap_sync(dma->idi_tag, dma->idi_map,
1544 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1545 		bus_dmamap_unload(dma->idi_tag, dma->idi_map);
1546 		dma->idi_paddr = IF_BAD_DMA;
1547 	}
1548 	if (dma->idi_vaddr != NULL) {
1549 		bus_dmamem_free(dma->idi_tag, dma->idi_vaddr, dma->idi_map);
1550 		dma->idi_vaddr = NULL;
1551 	}
1552 	bus_dma_tag_destroy(dma->idi_tag);
1553 	dma->idi_tag = NULL;
1554 }
1555 
1556 void
1557 iflib_dma_free_multi(iflib_dma_info_t *dmalist, int count)
1558 {
1559 	int i;
1560 	iflib_dma_info_t *dmaiter = dmalist;
1561 
1562 	for (i = 0; i < count; i++, dmaiter++)
1563 		iflib_dma_free(*dmaiter);
1564 }
1565 
1566 static int
1567 iflib_fast_intr(void *arg)
1568 {
1569 	iflib_filter_info_t info = arg;
1570 	struct grouptask *gtask = info->ifi_task;
1571 	int result;
1572 
1573 	DBG_COUNTER_INC(fast_intrs);
1574 	if (info->ifi_filter != NULL) {
1575 		result = info->ifi_filter(info->ifi_filter_arg);
1576 		if ((result & FILTER_SCHEDULE_THREAD) == 0)
1577 			return (result);
1578 	}
1579 
1580 	GROUPTASK_ENQUEUE(gtask);
1581 	return (FILTER_HANDLED);
1582 }
1583 
1584 static int
1585 iflib_fast_intr_rxtx(void *arg)
1586 {
1587 	iflib_filter_info_t info = arg;
1588 	struct grouptask *gtask = info->ifi_task;
1589 	if_ctx_t ctx;
1590 	iflib_rxq_t rxq = (iflib_rxq_t)info->ifi_ctx;
1591 	iflib_txq_t txq;
1592 	void *sc;
1593 	int i, cidx, result;
1594 	qidx_t txqid;
1595 	bool intr_enable, intr_legacy;
1596 
1597 	DBG_COUNTER_INC(fast_intrs);
1598 	if (info->ifi_filter != NULL) {
1599 		result = info->ifi_filter(info->ifi_filter_arg);
1600 		if ((result & FILTER_SCHEDULE_THREAD) == 0)
1601 			return (result);
1602 	}
1603 
1604 	ctx = rxq->ifr_ctx;
1605 	sc = ctx->ifc_softc;
1606 	intr_enable = false;
1607 	intr_legacy = !!(ctx->ifc_flags & IFC_LEGACY);
1608 	MPASS(rxq->ifr_ntxqirq);
1609 	for (i = 0; i < rxq->ifr_ntxqirq; i++) {
1610 		txqid = rxq->ifr_txqid[i];
1611 		txq = &ctx->ifc_txqs[txqid];
1612 		bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
1613 		    BUS_DMASYNC_POSTREAD);
1614 		if (!ctx->isc_txd_credits_update(sc, txqid, false)) {
1615 			if (intr_legacy)
1616 				intr_enable = true;
1617 			else
1618 				IFDI_TX_QUEUE_INTR_ENABLE(ctx, txqid);
1619 			continue;
1620 		}
1621 		GROUPTASK_ENQUEUE(&txq->ift_task);
1622 	}
1623 	if (ctx->ifc_sctx->isc_flags & IFLIB_HAS_RXCQ)
1624 		cidx = rxq->ifr_cq_cidx;
1625 	else
1626 		cidx = rxq->ifr_fl[0].ifl_cidx;
1627 	if (iflib_rxd_avail(ctx, rxq, cidx, 1))
1628 		GROUPTASK_ENQUEUE(gtask);
1629 	else {
1630 		if (intr_legacy)
1631 			intr_enable = true;
1632 		else
1633 			IFDI_RX_QUEUE_INTR_ENABLE(ctx, rxq->ifr_id);
1634 		DBG_COUNTER_INC(rx_intr_enables);
1635 	}
1636 	if (intr_enable)
1637 		IFDI_INTR_ENABLE(ctx);
1638 	return (FILTER_HANDLED);
1639 }
1640 
1641 static int
1642 iflib_fast_intr_ctx(void *arg)
1643 {
1644 	iflib_filter_info_t info = arg;
1645 	if_ctx_t ctx = info->ifi_ctx;
1646 	int result;
1647 
1648 	DBG_COUNTER_INC(fast_intrs);
1649 	if (info->ifi_filter != NULL) {
1650 		result = info->ifi_filter(info->ifi_filter_arg);
1651 		if ((result & FILTER_SCHEDULE_THREAD) == 0)
1652 			return (result);
1653 	}
1654 
1655 	taskqueue_enqueue(ctx->ifc_tq, &ctx->ifc_admin_task);
1656 	return (FILTER_HANDLED);
1657 }
1658 
1659 static int
1660 _iflib_irq_alloc(if_ctx_t ctx, if_irq_t irq, int rid,
1661 		 driver_filter_t filter, driver_intr_t handler, void *arg,
1662 		 const char *name)
1663 {
1664 	struct resource *res;
1665 	void *tag = NULL;
1666 	device_t dev = ctx->ifc_dev;
1667 	int flags, i, rc;
1668 
1669 	flags = RF_ACTIVE;
1670 	if (ctx->ifc_flags & IFC_LEGACY)
1671 		flags |= RF_SHAREABLE;
1672 	MPASS(rid < 512);
1673 	i = rid;
1674 	res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &i, flags);
1675 	if (res == NULL) {
1676 		device_printf(dev,
1677 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
1678 		return (ENOMEM);
1679 	}
1680 	irq->ii_res = res;
1681 	KASSERT(filter == NULL || handler == NULL, ("filter and handler can't both be non-NULL"));
1682 	rc = bus_setup_intr(dev, res, INTR_MPSAFE | INTR_TYPE_NET,
1683 		    filter, handler, arg, &tag);
1684 	if (rc != 0) {
1685 		device_printf(dev,
1686 		    "failed to setup interrupt for rid %d, name %s: %d\n",
1687 		    rid, name ? name : "unknown", rc);
1688 		return (rc);
1689 	} else if (name)
1690 		bus_describe_intr(dev, res, tag, "%s", name);
1691 
1692 	irq->ii_tag = tag;
1693 	return (0);
1694 }
1695 
1696 /*********************************************************************
1697  *
1698  *  Allocate DMA resources for TX buffers as well as memory for the TX
1699  *  mbuf map.  TX DMA maps (non-TSO/TSO) and TX mbuf map are kept in a
1700  *  iflib_sw_tx_desc_array structure, storing all the information that
1701  *  is needed to transmit a packet on the wire.  This is called only
1702  *  once at attach, setup is done every reset.
1703  *
1704  **********************************************************************/
1705 static int
1706 iflib_txsd_alloc(iflib_txq_t txq)
1707 {
1708 	if_ctx_t ctx = txq->ift_ctx;
1709 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1710 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1711 	device_t dev = ctx->ifc_dev;
1712 	bus_size_t tsomaxsize;
1713 	bus_addr_t lowaddr;
1714 	int err, nsegments, ntsosegments;
1715 	bool tso;
1716 
1717 	nsegments = scctx->isc_tx_nsegments;
1718 	ntsosegments = scctx->isc_tx_tso_segments_max;
1719 	tsomaxsize = scctx->isc_tx_tso_size_max;
1720 	if (if_getcapabilities(ctx->ifc_ifp) & IFCAP_VLAN_MTU)
1721 		tsomaxsize += sizeof(struct ether_vlan_header);
1722 	MPASS(scctx->isc_ntxd[0] > 0);
1723 	MPASS(scctx->isc_ntxd[txq->ift_br_offset] > 0);
1724 	MPASS(nsegments > 0);
1725 	if (if_getcapabilities(ctx->ifc_ifp) & IFCAP_TSO) {
1726 		MPASS(ntsosegments > 0);
1727 		MPASS(sctx->isc_tso_maxsize >= tsomaxsize);
1728 	}
1729 
1730 	lowaddr = DMA_WIDTH_TO_BUS_LOWADDR(scctx->isc_dma_width);
1731 
1732 	/*
1733 	 * Set up DMA tags for TX buffers.
1734 	 */
1735 	if ((err = bus_dma_tag_create(bus_get_dma_tag(dev),
1736 		    1, 0,			/* alignment, bounds */
1737 		    lowaddr,			/* lowaddr */
1738 		    BUS_SPACE_MAXADDR,		/* highaddr */
1739 		    NULL, NULL,			/* filter, filterarg */
1740 		    sctx->isc_tx_maxsize,	/* maxsize */
1741 		    nsegments,			/* nsegments */
1742 		    sctx->isc_tx_maxsegsize,	/* maxsegsize */
1743 		    0,				/* flags */
1744 		    NULL,			/* lockfunc */
1745 		    NULL,			/* lockfuncarg */
1746 		    &txq->ift_buf_tag))) {
1747 		device_printf(dev, "Unable to allocate TX DMA tag: %d\n", err);
1748 		device_printf(dev, "maxsize: %ju nsegments: %d maxsegsize: %ju\n",
1749 		    (uintmax_t)sctx->isc_tx_maxsize, nsegments, (uintmax_t)sctx->isc_tx_maxsegsize);
1750 		goto fail;
1751 	}
1752 	tso = (if_getcapabilities(ctx->ifc_ifp) & IFCAP_TSO) != 0;
1753 	if (tso && (err = bus_dma_tag_create(bus_get_dma_tag(dev),
1754 		    1, 0,			/* alignment, bounds */
1755 		    lowaddr,			/* lowaddr */
1756 		    BUS_SPACE_MAXADDR,		/* highaddr */
1757 		    NULL, NULL,			/* filter, filterarg */
1758 		    tsomaxsize,			/* maxsize */
1759 		    ntsosegments,		/* nsegments */
1760 		    sctx->isc_tso_maxsegsize,	/* maxsegsize */
1761 		    0,				/* flags */
1762 		    NULL,			/* lockfunc */
1763 		    NULL,			/* lockfuncarg */
1764 		    &txq->ift_tso_buf_tag))) {
1765 		device_printf(dev, "Unable to allocate TSO TX DMA tag: %d\n",
1766 		    err);
1767 		goto fail;
1768 	}
1769 
1770 	/* Allocate memory for the TX mbuf map. */
1771 	if (!(txq->ift_sds.ifsd_m =
1772 	    (struct mbuf **) malloc(sizeof(struct mbuf *) *
1773 	    scctx->isc_ntxd[txq->ift_br_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1774 		device_printf(dev, "Unable to allocate TX mbuf map memory\n");
1775 		err = ENOMEM;
1776 		goto fail;
1777 	}
1778 
1779 	/*
1780 	 * Create the DMA maps for TX buffers.
1781 	 */
1782 	if ((txq->ift_sds.ifsd_map = (bus_dmamap_t *)malloc(
1783 	    sizeof(bus_dmamap_t) * scctx->isc_ntxd[txq->ift_br_offset],
1784 	    M_IFLIB, M_NOWAIT | M_ZERO)) == NULL) {
1785 		device_printf(dev,
1786 		    "Unable to allocate TX buffer DMA map memory\n");
1787 		err = ENOMEM;
1788 		goto fail;
1789 	}
1790 	if (tso && (txq->ift_sds.ifsd_tso_map = (bus_dmamap_t *)malloc(
1791 	    sizeof(bus_dmamap_t) * scctx->isc_ntxd[txq->ift_br_offset],
1792 	    M_IFLIB, M_NOWAIT | M_ZERO)) == NULL) {
1793 		device_printf(dev,
1794 		    "Unable to allocate TSO TX buffer map memory\n");
1795 		err = ENOMEM;
1796 		goto fail;
1797 	}
1798 	for (int i = 0; i < scctx->isc_ntxd[txq->ift_br_offset]; i++) {
1799 		err = bus_dmamap_create(txq->ift_buf_tag, 0,
1800 		    &txq->ift_sds.ifsd_map[i]);
1801 		if (err != 0) {
1802 			device_printf(dev, "Unable to create TX DMA map\n");
1803 			goto fail;
1804 		}
1805 		if (!tso)
1806 			continue;
1807 		err = bus_dmamap_create(txq->ift_tso_buf_tag, 0,
1808 		    &txq->ift_sds.ifsd_tso_map[i]);
1809 		if (err != 0) {
1810 			device_printf(dev, "Unable to create TSO TX DMA map\n");
1811 			goto fail;
1812 		}
1813 	}
1814 	return (0);
1815 fail:
1816 	/* We free all, it handles case where we are in the middle */
1817 	iflib_tx_structures_free(ctx);
1818 	return (err);
1819 }
1820 
1821 static void
1822 iflib_txsd_destroy(if_ctx_t ctx, iflib_txq_t txq, int i)
1823 {
1824 	bus_dmamap_t map;
1825 
1826 	if (txq->ift_sds.ifsd_map != NULL) {
1827 		map = txq->ift_sds.ifsd_map[i];
1828 		bus_dmamap_sync(txq->ift_buf_tag, map, BUS_DMASYNC_POSTWRITE);
1829 		bus_dmamap_unload(txq->ift_buf_tag, map);
1830 		bus_dmamap_destroy(txq->ift_buf_tag, map);
1831 		txq->ift_sds.ifsd_map[i] = NULL;
1832 	}
1833 
1834 	if (txq->ift_sds.ifsd_tso_map != NULL) {
1835 		map = txq->ift_sds.ifsd_tso_map[i];
1836 		bus_dmamap_sync(txq->ift_tso_buf_tag, map,
1837 		    BUS_DMASYNC_POSTWRITE);
1838 		bus_dmamap_unload(txq->ift_tso_buf_tag, map);
1839 		bus_dmamap_destroy(txq->ift_tso_buf_tag, map);
1840 		txq->ift_sds.ifsd_tso_map[i] = NULL;
1841 	}
1842 }
1843 
1844 static void
1845 iflib_txq_destroy(iflib_txq_t txq)
1846 {
1847 	if_ctx_t ctx = txq->ift_ctx;
1848 
1849 	for (int i = 0; i < txq->ift_size; i++)
1850 		iflib_txsd_destroy(ctx, txq, i);
1851 
1852 	if (txq->ift_br != NULL) {
1853 		ifmp_ring_free(txq->ift_br);
1854 		txq->ift_br = NULL;
1855 	}
1856 
1857 	mtx_destroy(&txq->ift_mtx);
1858 
1859 	if (txq->ift_sds.ifsd_map != NULL) {
1860 		free(txq->ift_sds.ifsd_map, M_IFLIB);
1861 		txq->ift_sds.ifsd_map = NULL;
1862 	}
1863 	if (txq->ift_sds.ifsd_tso_map != NULL) {
1864 		free(txq->ift_sds.ifsd_tso_map, M_IFLIB);
1865 		txq->ift_sds.ifsd_tso_map = NULL;
1866 	}
1867 	if (txq->ift_sds.ifsd_m != NULL) {
1868 		free(txq->ift_sds.ifsd_m, M_IFLIB);
1869 		txq->ift_sds.ifsd_m = NULL;
1870 	}
1871 	if (txq->ift_buf_tag != NULL) {
1872 		bus_dma_tag_destroy(txq->ift_buf_tag);
1873 		txq->ift_buf_tag = NULL;
1874 	}
1875 	if (txq->ift_tso_buf_tag != NULL) {
1876 		bus_dma_tag_destroy(txq->ift_tso_buf_tag);
1877 		txq->ift_tso_buf_tag = NULL;
1878 	}
1879 	if (txq->ift_ifdi != NULL) {
1880 		free(txq->ift_ifdi, M_IFLIB);
1881 	}
1882 }
1883 
1884 static void
1885 iflib_txsd_free(if_ctx_t ctx, iflib_txq_t txq, int i)
1886 {
1887 	struct mbuf **mp;
1888 
1889 	mp = &txq->ift_sds.ifsd_m[i];
1890 	if (*mp == NULL)
1891 		return;
1892 
1893 	if (txq->ift_sds.ifsd_map != NULL) {
1894 		bus_dmamap_sync(txq->ift_buf_tag,
1895 		    txq->ift_sds.ifsd_map[i], BUS_DMASYNC_POSTWRITE);
1896 		bus_dmamap_unload(txq->ift_buf_tag, txq->ift_sds.ifsd_map[i]);
1897 	}
1898 	if (txq->ift_sds.ifsd_tso_map != NULL) {
1899 		bus_dmamap_sync(txq->ift_tso_buf_tag,
1900 		    txq->ift_sds.ifsd_tso_map[i], BUS_DMASYNC_POSTWRITE);
1901 		bus_dmamap_unload(txq->ift_tso_buf_tag,
1902 		    txq->ift_sds.ifsd_tso_map[i]);
1903 	}
1904 	m_freem(*mp);
1905 	DBG_COUNTER_INC(tx_frees);
1906 	*mp = NULL;
1907 }
1908 
1909 static int
1910 iflib_txq_setup(iflib_txq_t txq)
1911 {
1912 	if_ctx_t ctx = txq->ift_ctx;
1913 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1914 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1915 	iflib_dma_info_t di;
1916 	int i;
1917 
1918 	/* Set number of descriptors available */
1919 	txq->ift_qstatus = IFLIB_QUEUE_IDLE;
1920 	/* XXX make configurable */
1921 	txq->ift_update_freq = IFLIB_DEFAULT_TX_UPDATE_FREQ;
1922 
1923 	/* Reset indices */
1924 	txq->ift_cidx_processed = 0;
1925 	txq->ift_pidx = txq->ift_cidx = txq->ift_npending = 0;
1926 	txq->ift_size = scctx->isc_ntxd[txq->ift_br_offset];
1927 
1928 	for (i = 0, di = txq->ift_ifdi; i < sctx->isc_ntxqs; i++, di++)
1929 		bzero((void *)di->idi_vaddr, di->idi_size);
1930 
1931 	IFDI_TXQ_SETUP(ctx, txq->ift_id);
1932 	for (i = 0, di = txq->ift_ifdi; i < sctx->isc_ntxqs; i++, di++)
1933 		bus_dmamap_sync(di->idi_tag, di->idi_map,
1934 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1935 	return (0);
1936 }
1937 
1938 /*********************************************************************
1939  *
1940  *  Allocate DMA resources for RX buffers as well as memory for the RX
1941  *  mbuf map, direct RX cluster pointer map and RX cluster bus address
1942  *  map.  RX DMA map, RX mbuf map, direct RX cluster pointer map and
1943  *  RX cluster map are kept in a iflib_sw_rx_desc_array structure.
1944  *  Since we use use one entry in iflib_sw_rx_desc_array per received
1945  *  packet, the maximum number of entries we'll need is equal to the
1946  *  number of hardware receive descriptors that we've allocated.
1947  *
1948  **********************************************************************/
1949 static int
1950 iflib_rxsd_alloc(iflib_rxq_t rxq)
1951 {
1952 	if_ctx_t ctx = rxq->ifr_ctx;
1953 	if_shared_ctx_t sctx = ctx->ifc_sctx;
1954 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1955 	device_t dev = ctx->ifc_dev;
1956 	iflib_fl_t fl;
1957 	bus_addr_t lowaddr;
1958 	int err;
1959 
1960 	MPASS(scctx->isc_nrxd[0] > 0);
1961 	MPASS(scctx->isc_nrxd[rxq->ifr_fl_offset] > 0);
1962 
1963 	lowaddr = DMA_WIDTH_TO_BUS_LOWADDR(scctx->isc_dma_width);
1964 
1965 	fl = rxq->ifr_fl;
1966 	for (int i = 0; i < rxq->ifr_nfl; i++, fl++) {
1967 		fl->ifl_size = scctx->isc_nrxd[rxq->ifr_fl_offset]; /* this isn't necessarily the same */
1968 		/* Set up DMA tag for RX buffers. */
1969 		err = bus_dma_tag_create(bus_get_dma_tag(dev), /* parent */
1970 			    1, 0,			/* alignment, bounds */
1971 			    lowaddr,			/* lowaddr */
1972 			    BUS_SPACE_MAXADDR,		/* highaddr */
1973 			    NULL, NULL,			/* filter, filterarg */
1974 			    sctx->isc_rx_maxsize,	/* maxsize */
1975 			    sctx->isc_rx_nsegments,	/* nsegments */
1976 			    sctx->isc_rx_maxsegsize,	/* maxsegsize */
1977 			    0,				/* flags */
1978 			    NULL,			/* lockfunc */
1979 			    NULL,			/* lockarg */
1980 			    &fl->ifl_buf_tag);
1981 		if (err) {
1982 			device_printf(dev,
1983 			    "Unable to allocate RX DMA tag: %d\n", err);
1984 			goto fail;
1985 		}
1986 
1987 		/* Allocate memory for the RX mbuf map. */
1988 		if (!(fl->ifl_sds.ifsd_m =
1989 		    (struct mbuf **) malloc(sizeof(struct mbuf *) *
1990 			    scctx->isc_nrxd[rxq->ifr_fl_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1991 			device_printf(dev,
1992 			    "Unable to allocate RX mbuf map memory\n");
1993 			err = ENOMEM;
1994 			goto fail;
1995 		}
1996 
1997 		/* Allocate memory for the direct RX cluster pointer map. */
1998 		if (!(fl->ifl_sds.ifsd_cl =
1999 		    (caddr_t *) malloc(sizeof(caddr_t) *
2000 			    scctx->isc_nrxd[rxq->ifr_fl_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
2001 			device_printf(dev,
2002 			    "Unable to allocate RX cluster map memory\n");
2003 			err = ENOMEM;
2004 			goto fail;
2005 		}
2006 
2007 		/* Allocate memory for the RX cluster bus address map. */
2008 		if (!(fl->ifl_sds.ifsd_ba =
2009 		    (bus_addr_t *) malloc(sizeof(bus_addr_t) *
2010 			    scctx->isc_nrxd[rxq->ifr_fl_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
2011 			device_printf(dev,
2012 			    "Unable to allocate RX bus address map memory\n");
2013 			err = ENOMEM;
2014 			goto fail;
2015 		}
2016 
2017 		/*
2018 		 * Create the DMA maps for RX buffers.
2019 		 */
2020 		if (!(fl->ifl_sds.ifsd_map =
2021 		    (bus_dmamap_t *) malloc(sizeof(bus_dmamap_t) * scctx->isc_nrxd[rxq->ifr_fl_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
2022 			device_printf(dev,
2023 			    "Unable to allocate RX buffer DMA map memory\n");
2024 			err = ENOMEM;
2025 			goto fail;
2026 		}
2027 		for (int i = 0; i < scctx->isc_nrxd[rxq->ifr_fl_offset]; i++) {
2028 			err = bus_dmamap_create(fl->ifl_buf_tag, 0,
2029 			    &fl->ifl_sds.ifsd_map[i]);
2030 			if (err != 0) {
2031 				device_printf(dev, "Unable to create RX buffer DMA map\n");
2032 				goto fail;
2033 			}
2034 		}
2035 	}
2036 	return (0);
2037 
2038 fail:
2039 	iflib_rx_structures_free(ctx);
2040 	return (err);
2041 }
2042 
2043 /*
2044  * Internal service routines
2045  */
2046 
2047 struct rxq_refill_cb_arg {
2048 	int               error;
2049 	bus_dma_segment_t seg;
2050 	int               nseg;
2051 };
2052 
2053 static void
2054 _rxq_refill_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
2055 {
2056 	struct rxq_refill_cb_arg *cb_arg = arg;
2057 
2058 	cb_arg->error = error;
2059 	cb_arg->seg = segs[0];
2060 	cb_arg->nseg = nseg;
2061 }
2062 
2063 /**
2064  * iflib_fl_refill - refill an rxq free-buffer list
2065  * @ctx: the iflib context
2066  * @fl: the free list to refill
2067  * @count: the number of new buffers to allocate
2068  *
2069  * (Re)populate an rxq free-buffer list with up to @count new packet buffers.
2070  * The caller must assure that @count does not exceed the queue's capacity
2071  * minus one (since we always leave a descriptor unavailable).
2072  */
2073 static uint8_t
2074 iflib_fl_refill(if_ctx_t ctx, iflib_fl_t fl, int count)
2075 {
2076 	struct if_rxd_update iru;
2077 	struct rxq_refill_cb_arg cb_arg;
2078 	struct mbuf *m;
2079 	caddr_t cl, *sd_cl;
2080 	struct mbuf **sd_m;
2081 	bus_dmamap_t *sd_map;
2082 	bus_addr_t bus_addr, *sd_ba;
2083 	int err, frag_idx, i, idx, n, pidx;
2084 	qidx_t credits;
2085 
2086 	MPASS(count <= fl->ifl_size - fl->ifl_credits - 1);
2087 
2088 	sd_m = fl->ifl_sds.ifsd_m;
2089 	sd_map = fl->ifl_sds.ifsd_map;
2090 	sd_cl = fl->ifl_sds.ifsd_cl;
2091 	sd_ba = fl->ifl_sds.ifsd_ba;
2092 	pidx = fl->ifl_pidx;
2093 	idx = pidx;
2094 	frag_idx = fl->ifl_fragidx;
2095 	credits = fl->ifl_credits;
2096 
2097 	i = 0;
2098 	n = count;
2099 	MPASS(n > 0);
2100 	MPASS(credits + n <= fl->ifl_size);
2101 
2102 	if (pidx < fl->ifl_cidx)
2103 		MPASS(pidx + n <= fl->ifl_cidx);
2104 	if (pidx == fl->ifl_cidx && (credits < fl->ifl_size))
2105 		MPASS(fl->ifl_gen == 0);
2106 	if (pidx > fl->ifl_cidx)
2107 		MPASS(n <= fl->ifl_size - pidx + fl->ifl_cidx);
2108 
2109 	DBG_COUNTER_INC(fl_refills);
2110 	if (n > 8)
2111 		DBG_COUNTER_INC(fl_refills_large);
2112 	iru_init(&iru, fl->ifl_rxq, fl->ifl_id);
2113 	while (n-- > 0) {
2114 		/*
2115 		 * We allocate an uninitialized mbuf + cluster, mbuf is
2116 		 * initialized after rx.
2117 		 *
2118 		 * If the cluster is still set then we know a minimum sized
2119 		 * packet was received
2120 		 */
2121 		bit_ffc_at(fl->ifl_rx_bitmap, frag_idx, fl->ifl_size,
2122 		    &frag_idx);
2123 		if (frag_idx < 0)
2124 			bit_ffc(fl->ifl_rx_bitmap, fl->ifl_size, &frag_idx);
2125 		MPASS(frag_idx >= 0);
2126 		if ((cl = sd_cl[frag_idx]) == NULL) {
2127 			cl = uma_zalloc(fl->ifl_zone, M_NOWAIT);
2128 			if (__predict_false(cl == NULL))
2129 				break;
2130 
2131 			cb_arg.error = 0;
2132 			MPASS(sd_map != NULL);
2133 			err = bus_dmamap_load(fl->ifl_buf_tag, sd_map[frag_idx],
2134 			    cl, fl->ifl_buf_size, _rxq_refill_cb, &cb_arg,
2135 			    BUS_DMA_NOWAIT);
2136 			if (__predict_false(err != 0 || cb_arg.error)) {
2137 				uma_zfree(fl->ifl_zone, cl);
2138 				break;
2139 			}
2140 
2141 			sd_ba[frag_idx] = bus_addr = cb_arg.seg.ds_addr;
2142 			sd_cl[frag_idx] = cl;
2143 #if MEMORY_LOGGING
2144 			fl->ifl_cl_enqueued++;
2145 #endif
2146 		} else {
2147 			bus_addr = sd_ba[frag_idx];
2148 		}
2149 		bus_dmamap_sync(fl->ifl_buf_tag, sd_map[frag_idx],
2150 		    BUS_DMASYNC_PREREAD);
2151 
2152 		if (sd_m[frag_idx] == NULL) {
2153 			m = m_gethdr_raw(M_NOWAIT, 0);
2154 			if (__predict_false(m == NULL))
2155 				break;
2156 			sd_m[frag_idx] = m;
2157 		}
2158 		bit_set(fl->ifl_rx_bitmap, frag_idx);
2159 #if MEMORY_LOGGING
2160 		fl->ifl_m_enqueued++;
2161 #endif
2162 
2163 		DBG_COUNTER_INC(rx_allocs);
2164 		fl->ifl_rxd_idxs[i] = frag_idx;
2165 		fl->ifl_bus_addrs[i] = bus_addr;
2166 		credits++;
2167 		i++;
2168 		MPASS(credits <= fl->ifl_size);
2169 		if (++idx == fl->ifl_size) {
2170 #ifdef INVARIANTS
2171 			fl->ifl_gen = 1;
2172 #endif
2173 			idx = 0;
2174 		}
2175 		if (n == 0 || i == IFLIB_MAX_RX_REFRESH) {
2176 			iru.iru_pidx = pidx;
2177 			iru.iru_count = i;
2178 			ctx->isc_rxd_refill(ctx->ifc_softc, &iru);
2179 			fl->ifl_pidx = idx;
2180 			fl->ifl_credits = credits;
2181 			pidx = idx;
2182 			i = 0;
2183 		}
2184 	}
2185 
2186 	if (n < count - 1) {
2187 		if (i != 0) {
2188 			iru.iru_pidx = pidx;
2189 			iru.iru_count = i;
2190 			ctx->isc_rxd_refill(ctx->ifc_softc, &iru);
2191 			fl->ifl_pidx = idx;
2192 			fl->ifl_credits = credits;
2193 		}
2194 		DBG_COUNTER_INC(rxd_flush);
2195 		bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
2196 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2197 		ctx->isc_rxd_flush(ctx->ifc_softc, fl->ifl_rxq->ifr_id,
2198 		    fl->ifl_id, fl->ifl_pidx);
2199 		if (__predict_true(bit_test(fl->ifl_rx_bitmap, frag_idx))) {
2200 			fl->ifl_fragidx = frag_idx + 1;
2201 			if (fl->ifl_fragidx == fl->ifl_size)
2202 				fl->ifl_fragidx = 0;
2203 		} else {
2204 			fl->ifl_fragidx = frag_idx;
2205 		}
2206 	}
2207 
2208 	return (n == -1 ? 0 : IFLIB_RXEOF_EMPTY);
2209 }
2210 
2211 static inline uint8_t
2212 iflib_fl_refill_all(if_ctx_t ctx, iflib_fl_t fl)
2213 {
2214 	/*
2215 	 * We leave an unused descriptor to avoid pidx to catch up with cidx.
2216 	 * This is important as it confuses most NICs. For instance,
2217 	 * Intel NICs have (per receive ring) RDH and RDT registers, where
2218 	 * RDH points to the next receive descriptor to be used by the NIC,
2219 	 * and RDT for the next receive descriptor to be published by the
2220 	 * driver to the NIC (RDT - 1 is thus the last valid one).
2221 	 * The condition RDH == RDT means no descriptors are available to
2222 	 * the NIC, and thus it would be ambiguous if it also meant that
2223 	 * all the descriptors are available to the NIC.
2224 	 */
2225 	int32_t reclaimable = fl->ifl_size - fl->ifl_credits - 1;
2226 #ifdef INVARIANTS
2227 	int32_t delta = fl->ifl_size - get_inuse(fl->ifl_size, fl->ifl_cidx, fl->ifl_pidx, fl->ifl_gen) - 1;
2228 #endif
2229 
2230 	MPASS(fl->ifl_credits <= fl->ifl_size);
2231 	MPASS(reclaimable == delta);
2232 
2233 	if (reclaimable > 0)
2234 		return (iflib_fl_refill(ctx, fl, reclaimable));
2235 	return (0);
2236 }
2237 
2238 uint8_t
2239 iflib_in_detach(if_ctx_t ctx)
2240 {
2241 	bool in_detach;
2242 
2243 	STATE_LOCK(ctx);
2244 	in_detach = !!(ctx->ifc_flags & IFC_IN_DETACH);
2245 	STATE_UNLOCK(ctx);
2246 	return (in_detach);
2247 }
2248 
2249 static void
2250 iflib_fl_bufs_free(iflib_fl_t fl)
2251 {
2252 	iflib_dma_info_t idi = fl->ifl_ifdi;
2253 	bus_dmamap_t sd_map;
2254 	uint32_t i;
2255 
2256 	for (i = 0; i < fl->ifl_size; i++) {
2257 		struct mbuf **sd_m = &fl->ifl_sds.ifsd_m[i];
2258 		caddr_t *sd_cl = &fl->ifl_sds.ifsd_cl[i];
2259 
2260 		if (*sd_cl != NULL) {
2261 			sd_map = fl->ifl_sds.ifsd_map[i];
2262 			bus_dmamap_sync(fl->ifl_buf_tag, sd_map,
2263 			    BUS_DMASYNC_POSTREAD);
2264 			bus_dmamap_unload(fl->ifl_buf_tag, sd_map);
2265 			uma_zfree(fl->ifl_zone, *sd_cl);
2266 			*sd_cl = NULL;
2267 			if (*sd_m != NULL) {
2268 				m_init(*sd_m, M_NOWAIT, MT_DATA, 0);
2269 				m_free_raw(*sd_m);
2270 				*sd_m = NULL;
2271 			}
2272 		} else {
2273 			MPASS(*sd_m == NULL);
2274 		}
2275 #if MEMORY_LOGGING
2276 		fl->ifl_m_dequeued++;
2277 		fl->ifl_cl_dequeued++;
2278 #endif
2279 	}
2280 #ifdef INVARIANTS
2281 	for (i = 0; i < fl->ifl_size; i++) {
2282 		MPASS(fl->ifl_sds.ifsd_cl[i] == NULL);
2283 		MPASS(fl->ifl_sds.ifsd_m[i] == NULL);
2284 	}
2285 #endif
2286 	/*
2287 	 * Reset free list values
2288 	 */
2289 	fl->ifl_credits = fl->ifl_cidx = fl->ifl_pidx = fl->ifl_gen = fl->ifl_fragidx = 0;
2290 	bzero(idi->idi_vaddr, idi->idi_size);
2291 }
2292 
2293 /*********************************************************************
2294  *
2295  *  Initialize a free list and its buffers.
2296  *
2297  **********************************************************************/
2298 static int
2299 iflib_fl_setup(iflib_fl_t fl)
2300 {
2301 	iflib_rxq_t rxq = fl->ifl_rxq;
2302 	if_ctx_t ctx = rxq->ifr_ctx;
2303 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
2304 	int qidx;
2305 
2306 	bit_nclear(fl->ifl_rx_bitmap, 0, fl->ifl_size - 1);
2307 	/*
2308 	 * Free current RX buffer structs and their mbufs
2309 	 */
2310 	iflib_fl_bufs_free(fl);
2311 	/* Now replenish the mbufs */
2312 	MPASS(fl->ifl_credits == 0);
2313 	qidx = rxq->ifr_fl_offset + fl->ifl_id;
2314 	if (scctx->isc_rxd_buf_size[qidx] != 0)
2315 		fl->ifl_buf_size = scctx->isc_rxd_buf_size[qidx];
2316 	else
2317 		fl->ifl_buf_size = ctx->ifc_rx_mbuf_sz;
2318 	/*
2319 	 * ifl_buf_size may be a driver-supplied value, so pull it up
2320 	 * to the selected mbuf size.
2321 	 */
2322 	fl->ifl_buf_size = iflib_get_mbuf_size_for(fl->ifl_buf_size);
2323 	if (fl->ifl_buf_size > ctx->ifc_max_fl_buf_size)
2324 		ctx->ifc_max_fl_buf_size = fl->ifl_buf_size;
2325 	fl->ifl_cltype = m_gettype(fl->ifl_buf_size);
2326 	fl->ifl_zone = m_getzone(fl->ifl_buf_size);
2327 
2328 	/*
2329 	 * Avoid pre-allocating zillions of clusters to an idle card
2330 	 * potentially speeding up attach. In any case make sure
2331 	 * to leave a descriptor unavailable. See the comment in
2332 	 * iflib_fl_refill_all().
2333 	 */
2334 	MPASS(fl->ifl_size > 0);
2335 	(void)iflib_fl_refill(ctx, fl, min(128, fl->ifl_size - 1));
2336 	if (min(128, fl->ifl_size - 1) != fl->ifl_credits)
2337 		return (ENOBUFS);
2338 	/*
2339 	 * handle failure
2340 	 */
2341 	MPASS(rxq != NULL);
2342 	MPASS(fl->ifl_ifdi != NULL);
2343 	bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
2344 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2345 	return (0);
2346 }
2347 
2348 /*********************************************************************
2349  *
2350  *  Free receive ring data structures
2351  *
2352  **********************************************************************/
2353 static void
2354 iflib_rx_sds_free(iflib_rxq_t rxq)
2355 {
2356 	iflib_fl_t fl;
2357 	int i, j;
2358 
2359 	if (rxq->ifr_fl != NULL) {
2360 		for (i = 0; i < rxq->ifr_nfl; i++) {
2361 			fl = &rxq->ifr_fl[i];
2362 			if (fl->ifl_buf_tag != NULL) {
2363 				if (fl->ifl_sds.ifsd_map != NULL) {
2364 					for (j = 0; j < fl->ifl_size; j++) {
2365 						bus_dmamap_sync(
2366 						    fl->ifl_buf_tag,
2367 						    fl->ifl_sds.ifsd_map[j],
2368 						    BUS_DMASYNC_POSTREAD);
2369 						bus_dmamap_unload(
2370 						    fl->ifl_buf_tag,
2371 						    fl->ifl_sds.ifsd_map[j]);
2372 						bus_dmamap_destroy(
2373 						    fl->ifl_buf_tag,
2374 						    fl->ifl_sds.ifsd_map[j]);
2375 					}
2376 				}
2377 				bus_dma_tag_destroy(fl->ifl_buf_tag);
2378 				fl->ifl_buf_tag = NULL;
2379 			}
2380 			free(fl->ifl_sds.ifsd_m, M_IFLIB);
2381 			free(fl->ifl_sds.ifsd_cl, M_IFLIB);
2382 			free(fl->ifl_sds.ifsd_ba, M_IFLIB);
2383 			free(fl->ifl_sds.ifsd_map, M_IFLIB);
2384 			free(fl->ifl_rx_bitmap, M_IFLIB);
2385 			fl->ifl_sds.ifsd_m = NULL;
2386 			fl->ifl_sds.ifsd_cl = NULL;
2387 			fl->ifl_sds.ifsd_ba = NULL;
2388 			fl->ifl_sds.ifsd_map = NULL;
2389 			fl->ifl_rx_bitmap = NULL;
2390 		}
2391 		free(rxq->ifr_fl, M_IFLIB);
2392 		rxq->ifr_fl = NULL;
2393 		free(rxq->ifr_ifdi, M_IFLIB);
2394 		rxq->ifr_ifdi = NULL;
2395 		rxq->ifr_cq_cidx = 0;
2396 	}
2397 }
2398 
2399 /*
2400  * Timer routine
2401  */
2402 static void
2403 iflib_timer(void *arg)
2404 {
2405 	iflib_txq_t txq = arg;
2406 	if_ctx_t ctx = txq->ift_ctx;
2407 	if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
2408 	uint64_t this_tick = ticks;
2409 
2410 	if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING))
2411 		return;
2412 
2413 	/*
2414 	** Check on the state of the TX queue(s), this
2415 	** can be done without the lock because its RO
2416 	** and the HUNG state will be static if set.
2417 	*/
2418 	if (this_tick - txq->ift_last_timer_tick >= iflib_timer_default) {
2419 		txq->ift_last_timer_tick = this_tick;
2420 		IFDI_TIMER(ctx, txq->ift_id);
2421 		if ((txq->ift_qstatus == IFLIB_QUEUE_HUNG) &&
2422 		    ((txq->ift_cleaned_prev == txq->ift_cleaned) ||
2423 		     (sctx->isc_pause_frames == 0)))
2424 			goto hung;
2425 
2426 		if (txq->ift_qstatus != IFLIB_QUEUE_IDLE &&
2427 		    ifmp_ring_is_stalled(txq->ift_br)) {
2428 			KASSERT(ctx->ifc_link_state == LINK_STATE_UP,
2429 			    ("queue can't be marked as hung if interface is down"));
2430 			txq->ift_qstatus = IFLIB_QUEUE_HUNG;
2431 		}
2432 		txq->ift_cleaned_prev = txq->ift_cleaned;
2433 	}
2434 	/* handle any laggards */
2435 	if (txq->ift_db_pending)
2436 		GROUPTASK_ENQUEUE(&txq->ift_task);
2437 
2438 	sctx->isc_pause_frames = 0;
2439 	if (if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)
2440 		callout_reset_on(&txq->ift_timer, iflib_timer_default, iflib_timer,
2441 		    txq, txq->ift_timer.c_cpu);
2442 	return;
2443 
2444  hung:
2445 	device_printf(ctx->ifc_dev,
2446 	    "Watchdog timeout (TX: %d desc avail: %d pidx: %d) -- resetting\n",
2447 	    txq->ift_id, TXQ_AVAIL(txq), txq->ift_pidx);
2448 	STATE_LOCK(ctx);
2449 	if_setdrvflagbits(ctx->ifc_ifp, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
2450 	ctx->ifc_flags |= (IFC_DO_WATCHDOG | IFC_DO_RESET);
2451 	iflib_admin_intr_deferred(ctx);
2452 	STATE_UNLOCK(ctx);
2453 }
2454 
2455 static uint16_t
2456 iflib_get_mbuf_size_for(unsigned int size)
2457 {
2458 
2459 	if (size <= MCLBYTES)
2460 		return (MCLBYTES);
2461 	else
2462 		return (MJUMPAGESIZE);
2463 }
2464 
2465 static void
2466 iflib_calc_rx_mbuf_sz(if_ctx_t ctx)
2467 {
2468 	if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
2469 
2470 	/*
2471 	 * XXX don't set the max_frame_size to larger
2472 	 * than the hardware can handle
2473 	 */
2474 	ctx->ifc_rx_mbuf_sz =
2475 	    iflib_get_mbuf_size_for(sctx->isc_max_frame_size);
2476 }
2477 
2478 uint32_t
2479 iflib_get_rx_mbuf_sz(if_ctx_t ctx)
2480 {
2481 
2482 	return (ctx->ifc_rx_mbuf_sz);
2483 }
2484 
2485 static void
2486 iflib_init_locked(if_ctx_t ctx)
2487 {
2488 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
2489 	if_t ifp = ctx->ifc_ifp;
2490 	iflib_fl_t fl;
2491 	iflib_txq_t txq;
2492 	iflib_rxq_t rxq;
2493 	int i, j, tx_ip_csum_flags, tx_ip6_csum_flags;
2494 
2495 	if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
2496 	IFDI_INTR_DISABLE(ctx);
2497 
2498 	/*
2499 	 * See iflib_stop(). Useful in case iflib_init_locked() is
2500 	 * called without first calling iflib_stop().
2501 	 */
2502 	netmap_disable_all_rings(ifp);
2503 
2504 	tx_ip_csum_flags = scctx->isc_tx_csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP | CSUM_SCTP);
2505 	tx_ip6_csum_flags = scctx->isc_tx_csum_flags & (CSUM_IP6_TCP | CSUM_IP6_UDP | CSUM_IP6_SCTP);
2506 	/* Set hardware offload abilities */
2507 	if_clearhwassist(ifp);
2508 	if (if_getcapenable(ifp) & IFCAP_TXCSUM)
2509 		if_sethwassistbits(ifp, tx_ip_csum_flags, 0);
2510 	if (if_getcapenable(ifp) & IFCAP_TXCSUM_IPV6)
2511 		if_sethwassistbits(ifp,  tx_ip6_csum_flags, 0);
2512 	if (if_getcapenable(ifp) & IFCAP_TSO4)
2513 		if_sethwassistbits(ifp, CSUM_IP_TSO, 0);
2514 	if (if_getcapenable(ifp) & IFCAP_TSO6)
2515 		if_sethwassistbits(ifp, CSUM_IP6_TSO, 0);
2516 
2517 	for (i = 0, txq = ctx->ifc_txqs; i < scctx->isc_ntxqsets; i++, txq++) {
2518 		CALLOUT_LOCK(txq);
2519 		callout_stop(&txq->ift_timer);
2520 #ifdef DEV_NETMAP
2521 		callout_stop(&txq->ift_netmap_timer);
2522 #endif /* DEV_NETMAP */
2523 		CALLOUT_UNLOCK(txq);
2524 		(void)iflib_netmap_txq_init(ctx, txq);
2525 	}
2526 
2527 	/*
2528 	 * Calculate a suitable Rx mbuf size prior to calling IFDI_INIT, so
2529 	 * that drivers can use the value when setting up the hardware receive
2530 	 * buffers.
2531 	 */
2532 	iflib_calc_rx_mbuf_sz(ctx);
2533 
2534 #ifdef INVARIANTS
2535 	i = if_getdrvflags(ifp);
2536 #endif
2537 	IFDI_INIT(ctx);
2538 	MPASS(if_getdrvflags(ifp) == i);
2539 	for (i = 0, rxq = ctx->ifc_rxqs; i < scctx->isc_nrxqsets; i++, rxq++) {
2540 		if (iflib_netmap_rxq_init(ctx, rxq) > 0) {
2541 			/* This rxq is in netmap mode. Skip normal init. */
2542 			continue;
2543 		}
2544 		for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++) {
2545 			if (iflib_fl_setup(fl)) {
2546 				device_printf(ctx->ifc_dev,
2547 				    "setting up free list %d failed - "
2548 				    "check cluster settings\n", j);
2549 				goto done;
2550 			}
2551 		}
2552 	}
2553 done:
2554 	if_setdrvflagbits(ctx->ifc_ifp, IFF_DRV_RUNNING, IFF_DRV_OACTIVE);
2555 	IFDI_INTR_ENABLE(ctx);
2556 	txq = ctx->ifc_txqs;
2557 	for (i = 0; i < scctx->isc_ntxqsets; i++, txq++)
2558 		callout_reset_on(&txq->ift_timer, iflib_timer_default, iflib_timer, txq,
2559 			txq->ift_timer.c_cpu);
2560 
2561 	/* Re-enable txsync/rxsync. */
2562 	netmap_enable_all_rings(ifp);
2563 }
2564 
2565 static int
2566 iflib_media_change(if_t ifp)
2567 {
2568 	if_ctx_t ctx = if_getsoftc(ifp);
2569 	int err;
2570 
2571 	CTX_LOCK(ctx);
2572 	if ((err = IFDI_MEDIA_CHANGE(ctx)) == 0)
2573 		iflib_if_init_locked(ctx);
2574 	CTX_UNLOCK(ctx);
2575 	return (err);
2576 }
2577 
2578 static void
2579 iflib_media_status(if_t ifp, struct ifmediareq *ifmr)
2580 {
2581 	if_ctx_t ctx = if_getsoftc(ifp);
2582 
2583 	CTX_LOCK(ctx);
2584 	IFDI_UPDATE_ADMIN_STATUS(ctx);
2585 	IFDI_MEDIA_STATUS(ctx, ifmr);
2586 	CTX_UNLOCK(ctx);
2587 }
2588 
2589 static void
2590 iflib_stop(if_ctx_t ctx)
2591 {
2592 	iflib_txq_t txq = ctx->ifc_txqs;
2593 	iflib_rxq_t rxq = ctx->ifc_rxqs;
2594 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
2595 	if_shared_ctx_t sctx = ctx->ifc_sctx;
2596 	iflib_dma_info_t di;
2597 	iflib_fl_t fl;
2598 	int i, j;
2599 
2600 	/* Tell the stack that the interface is no longer active */
2601 	if_setdrvflagbits(ctx->ifc_ifp, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
2602 
2603 	IFDI_INTR_DISABLE(ctx);
2604 	DELAY(1000);
2605 	IFDI_STOP(ctx);
2606 	DELAY(1000);
2607 
2608 	/*
2609 	 * Stop any pending txsync/rxsync and prevent new ones
2610 	 * form starting. Processes blocked in poll() will get
2611 	 * POLLERR.
2612 	 */
2613 	netmap_disable_all_rings(ctx->ifc_ifp);
2614 
2615 	iflib_debug_reset();
2616 	/* Wait for current tx queue users to exit to disarm watchdog timer. */
2617 	for (i = 0; i < scctx->isc_ntxqsets; i++, txq++) {
2618 		/* make sure all transmitters have completed before proceeding XXX */
2619 
2620 		CALLOUT_LOCK(txq);
2621 		callout_stop(&txq->ift_timer);
2622 #ifdef DEV_NETMAP
2623 		callout_stop(&txq->ift_netmap_timer);
2624 #endif /* DEV_NETMAP */
2625 		CALLOUT_UNLOCK(txq);
2626 
2627 		/* clean any enqueued buffers */
2628 		iflib_ifmp_purge(txq);
2629 		/* Free any existing tx buffers. */
2630 		for (j = 0; j < txq->ift_size; j++) {
2631 			iflib_txsd_free(ctx, txq, j);
2632 		}
2633 		txq->ift_processed = txq->ift_cleaned = txq->ift_cidx_processed = 0;
2634 		txq->ift_in_use = txq->ift_gen = txq->ift_no_desc_avail = 0;
2635 		if (sctx->isc_flags & IFLIB_PRESERVE_TX_INDICES)
2636 			txq->ift_cidx = txq->ift_pidx;
2637 		else
2638 			txq->ift_cidx = txq->ift_pidx = 0;
2639 
2640 		txq->ift_closed = txq->ift_mbuf_defrag = txq->ift_mbuf_defrag_failed = 0;
2641 		txq->ift_no_tx_dma_setup = txq->ift_txd_encap_efbig = txq->ift_map_failed = 0;
2642 		txq->ift_pullups = 0;
2643 		ifmp_ring_reset_stats(txq->ift_br);
2644 		for (j = 0, di = txq->ift_ifdi; j < sctx->isc_ntxqs; j++, di++)
2645 			bzero((void *)di->idi_vaddr, di->idi_size);
2646 	}
2647 	for (i = 0; i < scctx->isc_nrxqsets; i++, rxq++) {
2648 		if (rxq->ifr_task.gt_taskqueue != NULL)
2649 			gtaskqueue_drain(rxq->ifr_task.gt_taskqueue,
2650 				 &rxq->ifr_task.gt_task);
2651 
2652 		rxq->ifr_cq_cidx = 0;
2653 		for (j = 0, di = rxq->ifr_ifdi; j < sctx->isc_nrxqs; j++, di++)
2654 			bzero((void *)di->idi_vaddr, di->idi_size);
2655 		/* also resets the free lists pidx/cidx */
2656 		for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++)
2657 			iflib_fl_bufs_free(fl);
2658 	}
2659 }
2660 
2661 static inline caddr_t
2662 calc_next_rxd(iflib_fl_t fl, int cidx)
2663 {
2664 	qidx_t size;
2665 	int nrxd;
2666 	caddr_t start, end, cur, next;
2667 
2668 	nrxd = fl->ifl_size;
2669 	size = fl->ifl_rxd_size;
2670 	start = fl->ifl_ifdi->idi_vaddr;
2671 
2672 	if (__predict_false(size == 0))
2673 		return (start);
2674 	cur = start + size * cidx;
2675 	end = start + size * nrxd;
2676 	next = CACHE_PTR_NEXT(cur);
2677 	return (next < end ? next : start);
2678 }
2679 
2680 static inline void
2681 prefetch_pkts(iflib_fl_t fl, int cidx)
2682 {
2683 	int nextptr;
2684 	int nrxd = fl->ifl_size;
2685 	caddr_t next_rxd;
2686 
2687 	nextptr = (cidx + CACHE_PTR_INCREMENT) & (nrxd - 1);
2688 	prefetch(&fl->ifl_sds.ifsd_m[nextptr]);
2689 	prefetch(&fl->ifl_sds.ifsd_cl[nextptr]);
2690 	next_rxd = calc_next_rxd(fl, cidx);
2691 	prefetch(next_rxd);
2692 	prefetch(fl->ifl_sds.ifsd_m[(cidx + 1) & (nrxd - 1)]);
2693 	prefetch(fl->ifl_sds.ifsd_m[(cidx + 2) & (nrxd - 1)]);
2694 	prefetch(fl->ifl_sds.ifsd_m[(cidx + 3) & (nrxd - 1)]);
2695 	prefetch(fl->ifl_sds.ifsd_m[(cidx + 4) & (nrxd - 1)]);
2696 	prefetch(fl->ifl_sds.ifsd_cl[(cidx + 1) & (nrxd - 1)]);
2697 	prefetch(fl->ifl_sds.ifsd_cl[(cidx + 2) & (nrxd - 1)]);
2698 	prefetch(fl->ifl_sds.ifsd_cl[(cidx + 3) & (nrxd - 1)]);
2699 	prefetch(fl->ifl_sds.ifsd_cl[(cidx + 4) & (nrxd - 1)]);
2700 }
2701 
2702 static struct mbuf *
2703 rxd_frag_to_sd(iflib_rxq_t rxq, if_rxd_frag_t irf, bool unload, if_rxsd_t sd,
2704     int *pf_rv, if_rxd_info_t ri)
2705 {
2706 	bus_dmamap_t map;
2707 	iflib_fl_t fl;
2708 	caddr_t payload;
2709 	struct mbuf *m;
2710 	int flid, cidx, len, next;
2711 
2712 	map = NULL;
2713 	flid = irf->irf_flid;
2714 	cidx = irf->irf_idx;
2715 	fl = &rxq->ifr_fl[flid];
2716 	sd->ifsd_fl = fl;
2717 	sd->ifsd_cl = &fl->ifl_sds.ifsd_cl[cidx];
2718 	fl->ifl_credits--;
2719 #if MEMORY_LOGGING
2720 	fl->ifl_m_dequeued++;
2721 #endif
2722 	if (rxq->ifr_ctx->ifc_flags & IFC_PREFETCH)
2723 		prefetch_pkts(fl, cidx);
2724 	next = (cidx + CACHE_PTR_INCREMENT) & (fl->ifl_size - 1);
2725 	prefetch(&fl->ifl_sds.ifsd_map[next]);
2726 	map = fl->ifl_sds.ifsd_map[cidx];
2727 
2728 	bus_dmamap_sync(fl->ifl_buf_tag, map, BUS_DMASYNC_POSTREAD);
2729 
2730 	if (rxq->pfil != NULL && PFIL_HOOKED_IN(rxq->pfil) && pf_rv != NULL &&
2731 	    irf->irf_len != 0) {
2732 		payload  = *sd->ifsd_cl;
2733 		payload +=  ri->iri_pad;
2734 		len = ri->iri_len - ri->iri_pad;
2735 		*pf_rv = pfil_mem_in(rxq->pfil, payload, len, ri->iri_ifp, &m);
2736 		switch (*pf_rv) {
2737 		case PFIL_DROPPED:
2738 		case PFIL_CONSUMED:
2739 			/*
2740 			 * The filter ate it.  Everything is recycled.
2741 			 */
2742 			m = NULL;
2743 			unload = 0;
2744 			break;
2745 		case PFIL_REALLOCED:
2746 			/*
2747 			 * The filter copied it.  Everything is recycled.
2748 			 * 'm' points at new mbuf.
2749 			 */
2750 			unload = 0;
2751 			break;
2752 		case PFIL_PASS:
2753 			/*
2754 			 * Filter said it was OK, so receive like
2755 			 * normal
2756 			 */
2757 			m = fl->ifl_sds.ifsd_m[cidx];
2758 			fl->ifl_sds.ifsd_m[cidx] = NULL;
2759 			break;
2760 		default:
2761 			MPASS(0);
2762 		}
2763 	} else {
2764 		m = fl->ifl_sds.ifsd_m[cidx];
2765 		fl->ifl_sds.ifsd_m[cidx] = NULL;
2766 		if (pf_rv != NULL)
2767 			*pf_rv = PFIL_PASS;
2768 	}
2769 
2770 	if (unload && irf->irf_len != 0)
2771 		bus_dmamap_unload(fl->ifl_buf_tag, map);
2772 	fl->ifl_cidx = (fl->ifl_cidx + 1) & (fl->ifl_size - 1);
2773 	if (__predict_false(fl->ifl_cidx == 0))
2774 		fl->ifl_gen = 0;
2775 	bit_clear(fl->ifl_rx_bitmap, cidx);
2776 	return (m);
2777 }
2778 
2779 static struct mbuf *
2780 assemble_segments(iflib_rxq_t rxq, if_rxd_info_t ri, if_rxsd_t sd, int *pf_rv)
2781 {
2782 	struct mbuf *m, *mh, *mt;
2783 	caddr_t cl;
2784 	int  *pf_rv_ptr, flags, i, padlen;
2785 	bool consumed;
2786 
2787 	i = 0;
2788 	mh = NULL;
2789 	consumed = false;
2790 	*pf_rv = PFIL_PASS;
2791 	pf_rv_ptr = pf_rv;
2792 	do {
2793 		m = rxd_frag_to_sd(rxq, &ri->iri_frags[i], !consumed, sd,
2794 		    pf_rv_ptr, ri);
2795 
2796 		MPASS(*sd->ifsd_cl != NULL);
2797 
2798 		/*
2799 		 * Exclude zero-length frags & frags from
2800 		 * packets the filter has consumed or dropped
2801 		 */
2802 		if (ri->iri_frags[i].irf_len == 0 || consumed ||
2803 		    *pf_rv == PFIL_CONSUMED || *pf_rv == PFIL_DROPPED) {
2804 			if (mh == NULL) {
2805 				/* everything saved here */
2806 				consumed = true;
2807 				pf_rv_ptr = NULL;
2808 				continue;
2809 			}
2810 			/* XXX we can save the cluster here, but not the mbuf */
2811 			m_init(m, M_NOWAIT, MT_DATA, 0);
2812 			m_free(m);
2813 			continue;
2814 		}
2815 		if (mh == NULL) {
2816 			flags = M_PKTHDR | M_EXT;
2817 			mh = mt = m;
2818 			padlen = ri->iri_pad;
2819 		} else {
2820 			flags = M_EXT;
2821 			mt->m_next = m;
2822 			mt = m;
2823 			/* assuming padding is only on the first fragment */
2824 			padlen = 0;
2825 		}
2826 		cl = *sd->ifsd_cl;
2827 		*sd->ifsd_cl = NULL;
2828 
2829 		/* Can these two be made one ? */
2830 		m_init(m, M_NOWAIT, MT_DATA, flags);
2831 		m_cljset(m, cl, sd->ifsd_fl->ifl_cltype);
2832 		/*
2833 		 * These must follow m_init and m_cljset
2834 		 */
2835 		m->m_data += padlen;
2836 		ri->iri_len -= padlen;
2837 		m->m_len = ri->iri_frags[i].irf_len;
2838 	} while (++i < ri->iri_nfrags);
2839 
2840 	return (mh);
2841 }
2842 
2843 /*
2844  * Process one software descriptor
2845  */
2846 static struct mbuf *
2847 iflib_rxd_pkt_get(iflib_rxq_t rxq, if_rxd_info_t ri)
2848 {
2849 	struct if_rxsd sd;
2850 	struct mbuf *m;
2851 	int pf_rv;
2852 
2853 	/* should I merge this back in now that the two paths are basically duplicated? */
2854 	if (ri->iri_nfrags == 1 &&
2855 	    ri->iri_frags[0].irf_len != 0 &&
2856 	    ri->iri_frags[0].irf_len <= MIN(IFLIB_RX_COPY_THRESH, MHLEN)) {
2857 		m = rxd_frag_to_sd(rxq, &ri->iri_frags[0], false, &sd,
2858 		    &pf_rv, ri);
2859 		if (pf_rv != PFIL_PASS && pf_rv != PFIL_REALLOCED)
2860 			return (m);
2861 		if (pf_rv == PFIL_PASS) {
2862 			m_init(m, M_NOWAIT, MT_DATA, M_PKTHDR);
2863 #ifndef __NO_STRICT_ALIGNMENT
2864 			if (!IP_ALIGNED(m) && ri->iri_pad == 0)
2865 				m->m_data += 2;
2866 #endif
2867 			memcpy(m->m_data, *sd.ifsd_cl, ri->iri_len);
2868 			m->m_len = ri->iri_frags[0].irf_len;
2869 			m->m_data += ri->iri_pad;
2870 			ri->iri_len -= ri->iri_pad;
2871 		}
2872 	} else {
2873 		m = assemble_segments(rxq, ri, &sd, &pf_rv);
2874 		if (m == NULL)
2875 			return (NULL);
2876 		if (pf_rv != PFIL_PASS && pf_rv != PFIL_REALLOCED)
2877 			return (m);
2878 	}
2879 	m->m_pkthdr.len = ri->iri_len;
2880 	m->m_pkthdr.rcvif = ri->iri_ifp;
2881 	m->m_flags |= ri->iri_flags;
2882 	m->m_pkthdr.ether_vtag = ri->iri_vtag;
2883 	m->m_pkthdr.flowid = ri->iri_flowid;
2884 #ifdef NUMA
2885 	m->m_pkthdr.numa_domain = if_getnumadomain(ri->iri_ifp);
2886 #endif
2887 	M_HASHTYPE_SET(m, ri->iri_rsstype);
2888 	m->m_pkthdr.csum_flags = ri->iri_csum_flags;
2889 	m->m_pkthdr.csum_data = ri->iri_csum_data;
2890 	return (m);
2891 }
2892 
2893 #if defined(INET6) || defined(INET)
2894 static void
2895 iflib_get_ip_forwarding(struct lro_ctrl *lc, bool *v4, bool *v6)
2896 {
2897 	CURVNET_SET(if_getvnet(lc->ifp));
2898 #if defined(INET6)
2899 	*v6 = V_ip6_forwarding;
2900 #endif
2901 #if defined(INET)
2902 	*v4 = V_ipforwarding;
2903 #endif
2904 	CURVNET_RESTORE();
2905 }
2906 
2907 /*
2908  * Returns true if it's possible this packet could be LROed.
2909  * if it returns false, it is guaranteed that tcp_lro_rx()
2910  * would not return zero.
2911  */
2912 static bool
2913 iflib_check_lro_possible(struct mbuf *m, bool v4_forwarding, bool v6_forwarding)
2914 {
2915 	struct ether_header *eh;
2916 
2917 	eh = mtod(m, struct ether_header *);
2918 	switch (eh->ether_type) {
2919 #if defined(INET6)
2920 	case htons(ETHERTYPE_IPV6):
2921 		return (!v6_forwarding);
2922 #endif
2923 #if defined(INET)
2924 	case htons(ETHERTYPE_IP):
2925 		return (!v4_forwarding);
2926 #endif
2927 	}
2928 
2929 	return (false);
2930 }
2931 #else
2932 static void
2933 iflib_get_ip_forwarding(struct lro_ctrl *lc __unused, bool *v4 __unused, bool *v6 __unused)
2934 {
2935 }
2936 #endif
2937 
2938 static void
2939 _task_fn_rx_watchdog(void *context)
2940 {
2941 	iflib_rxq_t rxq = context;
2942 
2943 	GROUPTASK_ENQUEUE(&rxq->ifr_task);
2944 }
2945 
2946 static uint8_t
2947 iflib_rxeof(iflib_rxq_t rxq, qidx_t budget)
2948 {
2949 	if_t ifp;
2950 	if_ctx_t ctx = rxq->ifr_ctx;
2951 	if_shared_ctx_t sctx = ctx->ifc_sctx;
2952 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
2953 	int avail, i;
2954 	qidx_t *cidxp;
2955 	struct if_rxd_info ri;
2956 	int err, budget_left, rx_bytes, rx_pkts;
2957 	iflib_fl_t fl;
2958 	int lro_enabled;
2959 	bool v4_forwarding, v6_forwarding, lro_possible;
2960 	uint8_t retval = 0;
2961 
2962 	/*
2963 	 * XXX early demux data packets so that if_input processing only handles
2964 	 * acks in interrupt context
2965 	 */
2966 	struct mbuf *m, *mh, *mt, *mf;
2967 
2968 	NET_EPOCH_ASSERT();
2969 
2970 	lro_possible = v4_forwarding = v6_forwarding = false;
2971 	ifp = ctx->ifc_ifp;
2972 	mh = mt = NULL;
2973 	MPASS(budget > 0);
2974 	rx_pkts	= rx_bytes = 0;
2975 	if (sctx->isc_flags & IFLIB_HAS_RXCQ)
2976 		cidxp = &rxq->ifr_cq_cidx;
2977 	else
2978 		cidxp = &rxq->ifr_fl[0].ifl_cidx;
2979 	if ((avail = iflib_rxd_avail(ctx, rxq, *cidxp, budget)) == 0) {
2980 		for (i = 0, fl = &rxq->ifr_fl[0]; i < sctx->isc_nfl; i++, fl++)
2981 			retval |= iflib_fl_refill_all(ctx, fl);
2982 		DBG_COUNTER_INC(rx_unavail);
2983 		return (retval);
2984 	}
2985 
2986 	/* pfil needs the vnet to be set */
2987 	CURVNET_SET_QUIET(if_getvnet(ifp));
2988 	for (budget_left = budget; budget_left > 0 && avail > 0;) {
2989 		if (__predict_false(!CTX_ACTIVE(ctx))) {
2990 			DBG_COUNTER_INC(rx_ctx_inactive);
2991 			break;
2992 		}
2993 		/*
2994 		 * Reset client set fields to their default values
2995 		 */
2996 		rxd_info_zero(&ri);
2997 		ri.iri_qsidx = rxq->ifr_id;
2998 		ri.iri_cidx = *cidxp;
2999 		ri.iri_ifp = ifp;
3000 		ri.iri_frags = rxq->ifr_frags;
3001 		err = ctx->isc_rxd_pkt_get(ctx->ifc_softc, &ri);
3002 
3003 		if (err)
3004 			goto err;
3005 		rx_pkts += 1;
3006 		rx_bytes += ri.iri_len;
3007 		if (sctx->isc_flags & IFLIB_HAS_RXCQ) {
3008 			*cidxp = ri.iri_cidx;
3009 			/* Update our consumer index */
3010 			/* XXX NB: shurd - check if this is still safe */
3011 			while (rxq->ifr_cq_cidx >= scctx->isc_nrxd[0])
3012 				rxq->ifr_cq_cidx -= scctx->isc_nrxd[0];
3013 			/* was this only a completion queue message? */
3014 			if (__predict_false(ri.iri_nfrags == 0))
3015 				continue;
3016 		}
3017 		MPASS(ri.iri_nfrags != 0);
3018 		MPASS(ri.iri_len != 0);
3019 
3020 		/* will advance the cidx on the corresponding free lists */
3021 		m = iflib_rxd_pkt_get(rxq, &ri);
3022 		avail--;
3023 		budget_left--;
3024 		if (avail == 0 && budget_left)
3025 			avail = iflib_rxd_avail(ctx, rxq, *cidxp, budget_left);
3026 
3027 		if (__predict_false(m == NULL))
3028 			continue;
3029 
3030 		/* imm_pkt: -- cxgb */
3031 		if (mh == NULL)
3032 			mh = mt = m;
3033 		else {
3034 			mt->m_nextpkt = m;
3035 			mt = m;
3036 		}
3037 	}
3038 	CURVNET_RESTORE();
3039 	/* make sure that we can refill faster than drain */
3040 	for (i = 0, fl = &rxq->ifr_fl[0]; i < sctx->isc_nfl; i++, fl++)
3041 		retval |= iflib_fl_refill_all(ctx, fl);
3042 
3043 	lro_enabled = (if_getcapenable(ifp) & IFCAP_LRO);
3044 	if (lro_enabled)
3045 		iflib_get_ip_forwarding(&rxq->ifr_lc, &v4_forwarding, &v6_forwarding);
3046 	mt = mf = NULL;
3047 	while (mh != NULL) {
3048 		m = mh;
3049 		mh = mh->m_nextpkt;
3050 		m->m_nextpkt = NULL;
3051 #ifndef __NO_STRICT_ALIGNMENT
3052 		if (!IP_ALIGNED(m) && (m = iflib_fixup_rx(m)) == NULL)
3053 			continue;
3054 #endif
3055 #if defined(INET6) || defined(INET)
3056 		if (lro_enabled) {
3057 			if (!lro_possible) {
3058 				lro_possible = iflib_check_lro_possible(m, v4_forwarding, v6_forwarding);
3059 				if (lro_possible && mf != NULL) {
3060 					if_input(ifp, mf);
3061 					DBG_COUNTER_INC(rx_if_input);
3062 					mt = mf = NULL;
3063 				}
3064 			}
3065 			if ((m->m_pkthdr.csum_flags & (CSUM_L4_CALC | CSUM_L4_VALID)) ==
3066 			    (CSUM_L4_CALC | CSUM_L4_VALID)) {
3067 				if (lro_possible && tcp_lro_rx(&rxq->ifr_lc, m, 0) == 0)
3068 					continue;
3069 			}
3070 		}
3071 #endif
3072 		if (lro_possible) {
3073 			if_input(ifp, m);
3074 			DBG_COUNTER_INC(rx_if_input);
3075 			continue;
3076 		}
3077 
3078 		if (mf == NULL)
3079 			mf = m;
3080 		if (mt != NULL)
3081 			mt->m_nextpkt = m;
3082 		mt = m;
3083 	}
3084 	if (mf != NULL) {
3085 		if_input(ifp, mf);
3086 		DBG_COUNTER_INC(rx_if_input);
3087 	}
3088 
3089 	if_inc_counter(ifp, IFCOUNTER_IBYTES, rx_bytes);
3090 	if_inc_counter(ifp, IFCOUNTER_IPACKETS, rx_pkts);
3091 
3092 	/*
3093 	 * Flush any outstanding LRO work
3094 	 */
3095 #if defined(INET6) || defined(INET)
3096 	tcp_lro_flush_all(&rxq->ifr_lc);
3097 #endif
3098 	if (avail != 0 || iflib_rxd_avail(ctx, rxq, *cidxp, 1) != 0)
3099 		retval |= IFLIB_RXEOF_MORE;
3100 	return (retval);
3101 err:
3102 	STATE_LOCK(ctx);
3103 	ctx->ifc_flags |= IFC_DO_RESET;
3104 	iflib_admin_intr_deferred(ctx);
3105 	STATE_UNLOCK(ctx);
3106 	return (0);
3107 }
3108 
3109 #define TXD_NOTIFY_COUNT(txq) (((txq)->ift_size / (txq)->ift_update_freq) - 1)
3110 static inline qidx_t
3111 txq_max_db_deferred(iflib_txq_t txq, qidx_t in_use)
3112 {
3113 	qidx_t notify_count = TXD_NOTIFY_COUNT(txq);
3114 	qidx_t minthresh = txq->ift_size / 8;
3115 	if (in_use > 4 * minthresh)
3116 		return (notify_count);
3117 	if (in_use > 2 * minthresh)
3118 		return (notify_count >> 1);
3119 	if (in_use > minthresh)
3120 		return (notify_count >> 3);
3121 	return (0);
3122 }
3123 
3124 static inline qidx_t
3125 txq_max_rs_deferred(iflib_txq_t txq)
3126 {
3127 	qidx_t notify_count = TXD_NOTIFY_COUNT(txq);
3128 	qidx_t minthresh = txq->ift_size / 8;
3129 	if (txq->ift_in_use > 4 * minthresh)
3130 		return (notify_count);
3131 	if (txq->ift_in_use > 2 * minthresh)
3132 		return (notify_count >> 1);
3133 	if (txq->ift_in_use > minthresh)
3134 		return (notify_count >> 2);
3135 	return (2);
3136 }
3137 
3138 #define M_CSUM_FLAGS(m)		((m)->m_pkthdr.csum_flags)
3139 #define M_HAS_VLANTAG(m)	(m->m_flags & M_VLANTAG)
3140 
3141 #define TXQ_MAX_DB_DEFERRED(txq, in_use)	txq_max_db_deferred((txq), (in_use))
3142 #define TXQ_MAX_RS_DEFERRED(txq)	txq_max_rs_deferred(txq)
3143 #define TXQ_MAX_DB_CONSUMED(size)	(size >> 4)
3144 
3145 /* forward compatibility for cxgb */
3146 #define FIRST_QSET(ctx) 0
3147 #define NTXQSETS(ctx) ((ctx)->ifc_softc_ctx.isc_ntxqsets)
3148 #define NRXQSETS(ctx) ((ctx)->ifc_softc_ctx.isc_nrxqsets)
3149 #define QIDX(ctx, m) ((((m)->m_pkthdr.flowid & ctx->ifc_softc_ctx.isc_rss_table_mask) % NTXQSETS(ctx)) + FIRST_QSET(ctx))
3150 #define DESC_RECLAIMABLE(q) ((int)((q)->ift_processed - (q)->ift_cleaned - (q)->ift_ctx->ifc_softc_ctx.isc_tx_nsegments))
3151 
3152 /* XXX we should be setting this to something other than zero */
3153 #define RECLAIM_THRESH(ctx) ((ctx)->ifc_sctx->isc_tx_reclaim_thresh)
3154 #define	MAX_TX_DESC(ctx) MAX((ctx)->ifc_softc_ctx.isc_tx_tso_segments_max, \
3155     (ctx)->ifc_softc_ctx.isc_tx_nsegments)
3156 
3157 static inline bool
3158 iflib_txd_db_check(iflib_txq_t txq, int ring)
3159 {
3160 	if_ctx_t ctx = txq->ift_ctx;
3161 	qidx_t dbval, max;
3162 
3163 	max = TXQ_MAX_DB_DEFERRED(txq, txq->ift_in_use);
3164 
3165 	/* force || threshold exceeded || at the edge of the ring */
3166 	if (ring || (txq->ift_db_pending >= max) || (TXQ_AVAIL(txq) <= MAX_TX_DESC(ctx) + 2)) {
3167 
3168 		/*
3169 		 * 'npending' is used if the card's doorbell is in terms of the number of descriptors
3170 		 * pending flush (BRCM). 'pidx' is used in cases where the card's doorbeel uses the
3171 		 * producer index explicitly (INTC).
3172 		 */
3173 		dbval = txq->ift_npending ? txq->ift_npending : txq->ift_pidx;
3174 		bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
3175 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
3176 		ctx->isc_txd_flush(ctx->ifc_softc, txq->ift_id, dbval);
3177 
3178 		/*
3179 		 * Absent bugs there are zero packets pending so reset pending counts to zero.
3180 		 */
3181 		txq->ift_db_pending = txq->ift_npending = 0;
3182 		return (true);
3183 	}
3184 	return (false);
3185 }
3186 
3187 #ifdef PKT_DEBUG
3188 static void
3189 print_pkt(if_pkt_info_t pi)
3190 {
3191 	printf("pi len:  %d qsidx: %d nsegs: %d ndescs: %d flags: %x pidx: %d\n",
3192 	    pi->ipi_len, pi->ipi_qsidx, pi->ipi_nsegs, pi->ipi_ndescs, pi->ipi_flags, pi->ipi_pidx);
3193 	printf("pi new_pidx: %d csum_flags: %lx tso_segsz: %d mflags: %x vtag: %d\n",
3194 	    pi->ipi_new_pidx, pi->ipi_csum_flags, pi->ipi_tso_segsz, pi->ipi_mflags, pi->ipi_vtag);
3195 	printf("pi etype: %d ehdrlen: %d ip_hlen: %d ipproto: %d\n",
3196 	    pi->ipi_etype, pi->ipi_ehdrlen, pi->ipi_ip_hlen, pi->ipi_ipproto);
3197 }
3198 #endif
3199 
3200 #define IS_TSO4(pi) ((pi)->ipi_csum_flags & CSUM_IP_TSO)
3201 #define IS_TX_OFFLOAD4(pi) ((pi)->ipi_csum_flags & (CSUM_IP_TCP | CSUM_IP_TSO))
3202 #define IS_TSO6(pi) ((pi)->ipi_csum_flags & CSUM_IP6_TSO)
3203 #define IS_TX_OFFLOAD6(pi) ((pi)->ipi_csum_flags & (CSUM_IP6_TCP | CSUM_IP6_TSO))
3204 
3205 /**
3206  * Parses out ethernet header information in the given mbuf.
3207  * Returns in pi: ipi_etype (EtherType) and ipi_ehdrlen (Ethernet header length)
3208  *
3209  * This will account for the VLAN header if present.
3210  *
3211  * XXX: This doesn't handle QinQ, which could prevent TX offloads for those
3212  * types of packets.
3213  */
3214 static int
3215 iflib_parse_ether_header(if_pkt_info_t pi, struct mbuf **mp, uint64_t *pullups)
3216 {
3217 	struct ether_vlan_header *eh;
3218 	struct mbuf *m;
3219 
3220 	m = *mp;
3221 	if (__predict_false(m->m_len < sizeof(*eh))) {
3222 		(*pullups)++;
3223 		if (__predict_false((m = m_pullup(m, sizeof(*eh))) == NULL))
3224 			return (ENOMEM);
3225 	}
3226 	eh = mtod(m, struct ether_vlan_header *);
3227 	if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
3228 		pi->ipi_etype = ntohs(eh->evl_proto);
3229 		pi->ipi_ehdrlen = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
3230 	} else {
3231 		pi->ipi_etype = ntohs(eh->evl_encap_proto);
3232 		pi->ipi_ehdrlen = ETHER_HDR_LEN;
3233 	}
3234 	*mp = m;
3235 
3236 	return (0);
3237 }
3238 
3239 /**
3240  * Parse up to the L3 header and extract IPv4/IPv6 header information into pi.
3241  * Currently this information includes: IP ToS value, IP header version/presence
3242  *
3243  * This is missing some checks and doesn't edit the packet content as it goes,
3244  * unlike iflib_parse_header(), in order to keep the amount of code here minimal.
3245  */
3246 static int
3247 iflib_parse_header_partial(if_pkt_info_t pi, struct mbuf **mp, uint64_t *pullups)
3248 {
3249 	struct mbuf *m;
3250 	int err;
3251 
3252 	*pullups = 0;
3253 	m = *mp;
3254 	if (!M_WRITABLE(m)) {
3255 		if ((m = m_dup(m, M_NOWAIT)) == NULL) {
3256 			return (ENOMEM);
3257 		} else {
3258 			m_freem(*mp);
3259 			DBG_COUNTER_INC(tx_frees);
3260 			*mp = m;
3261 		}
3262 	}
3263 
3264 	/* Fills out pi->ipi_etype */
3265 	err = iflib_parse_ether_header(pi, mp, pullups);
3266 	if (err)
3267 		return (err);
3268 	m = *mp;
3269 
3270 	switch (pi->ipi_etype) {
3271 #ifdef INET
3272 	case ETHERTYPE_IP:
3273 	{
3274 		struct mbuf *n;
3275 		struct ip *ip = NULL;
3276 		int miniplen;
3277 
3278 		miniplen = min(m->m_pkthdr.len, pi->ipi_ehdrlen + sizeof(*ip));
3279 		if (__predict_false(m->m_len < miniplen)) {
3280 			/*
3281 			 * Check for common case where the first mbuf only contains
3282 			 * the Ethernet header
3283 			 */
3284 			if (m->m_len == pi->ipi_ehdrlen) {
3285 				n = m->m_next;
3286 				MPASS(n);
3287 				/* If next mbuf contains at least the minimal IP header, then stop */
3288 				if (n->m_len >= sizeof(*ip)) {
3289 					ip = (struct ip *)n->m_data;
3290 				} else {
3291 					(*pullups)++;
3292 					if (__predict_false((m = m_pullup(m, miniplen)) == NULL))
3293 						return (ENOMEM);
3294 					ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
3295 				}
3296 			} else {
3297 				(*pullups)++;
3298 				if (__predict_false((m = m_pullup(m, miniplen)) == NULL))
3299 					return (ENOMEM);
3300 				ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
3301 			}
3302 		} else {
3303 			ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
3304 		}
3305 
3306 		/* Have the IPv4 header w/ no options here */
3307 		pi->ipi_ip_hlen = ip->ip_hl << 2;
3308 		pi->ipi_ipproto = ip->ip_p;
3309 		pi->ipi_ip_tos = ip->ip_tos;
3310 		pi->ipi_flags |= IPI_TX_IPV4;
3311 
3312 		break;
3313 	}
3314 #endif
3315 #ifdef INET6
3316 	case ETHERTYPE_IPV6:
3317 	{
3318 		struct ip6_hdr *ip6;
3319 
3320 		if (__predict_false(m->m_len < pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) {
3321 			(*pullups)++;
3322 			if (__predict_false((m = m_pullup(m, pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) == NULL))
3323 				return (ENOMEM);
3324 		}
3325 		ip6 = (struct ip6_hdr *)(m->m_data + pi->ipi_ehdrlen);
3326 
3327 		/* Have the IPv6 fixed header here */
3328 		pi->ipi_ip_hlen = sizeof(struct ip6_hdr);
3329 		pi->ipi_ipproto = ip6->ip6_nxt;
3330 		pi->ipi_ip_tos = IPV6_TRAFFIC_CLASS(ip6);
3331 		pi->ipi_flags |= IPI_TX_IPV6;
3332 
3333 		break;
3334 	}
3335 #endif
3336 	default:
3337 		pi->ipi_csum_flags &= ~CSUM_OFFLOAD;
3338 		pi->ipi_ip_hlen = 0;
3339 		break;
3340 	}
3341 	*mp = m;
3342 
3343 	return (0);
3344 
3345 }
3346 
3347 static int
3348 iflib_parse_header(iflib_txq_t txq, if_pkt_info_t pi, struct mbuf **mp)
3349 {
3350 	if_shared_ctx_t sctx = txq->ift_ctx->ifc_sctx;
3351 	struct mbuf *m;
3352 	int err;
3353 
3354 	m = *mp;
3355 	if ((sctx->isc_flags & IFLIB_NEED_SCRATCH) &&
3356 	    M_WRITABLE(m) == 0) {
3357 		if ((m = m_dup(m, M_NOWAIT)) == NULL) {
3358 			return (ENOMEM);
3359 		} else {
3360 			m_freem(*mp);
3361 			DBG_COUNTER_INC(tx_frees);
3362 			*mp = m;
3363 		}
3364 	}
3365 
3366 	/* Fills out pi->ipi_etype */
3367 	err = iflib_parse_ether_header(pi, mp, &txq->ift_pullups);
3368 	if (__predict_false(err))
3369 		return (err);
3370 	m = *mp;
3371 
3372 	switch (pi->ipi_etype) {
3373 #ifdef INET
3374 	case ETHERTYPE_IP:
3375 	{
3376 		struct ip *ip;
3377 		struct tcphdr *th;
3378 		uint8_t hlen;
3379 
3380 		hlen = pi->ipi_ehdrlen + sizeof(*ip);
3381 		if (__predict_false(m->m_len < hlen)) {
3382 			txq->ift_pullups++;
3383 			if (__predict_false((m = m_pullup(m, hlen)) == NULL))
3384 				return (ENOMEM);
3385 		}
3386 		ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
3387 		hlen = pi->ipi_ehdrlen + (ip->ip_hl << 2);
3388 		if (ip->ip_p == IPPROTO_TCP) {
3389 			hlen += sizeof(*th);
3390 			th = (struct tcphdr *)((char *)ip + (ip->ip_hl << 2));
3391 		} else if (ip->ip_p == IPPROTO_UDP) {
3392 			hlen += sizeof(struct udphdr);
3393 		}
3394 		if (__predict_false(m->m_len < hlen)) {
3395 			txq->ift_pullups++;
3396 			if ((m = m_pullup(m, hlen)) == NULL)
3397 				return (ENOMEM);
3398 		}
3399 		pi->ipi_ip_hlen = ip->ip_hl << 2;
3400 		pi->ipi_ipproto = ip->ip_p;
3401 		pi->ipi_ip_tos = ip->ip_tos;
3402 		pi->ipi_flags |= IPI_TX_IPV4;
3403 
3404 		/* TCP checksum offload may require TCP header length */
3405 		if (IS_TX_OFFLOAD4(pi)) {
3406 			if (__predict_true(pi->ipi_ipproto == IPPROTO_TCP)) {
3407 				pi->ipi_tcp_hflags = tcp_get_flags(th);
3408 				pi->ipi_tcp_hlen = th->th_off << 2;
3409 				pi->ipi_tcp_seq = th->th_seq;
3410 			}
3411 			if (IS_TSO4(pi)) {
3412 				if (__predict_false(ip->ip_p != IPPROTO_TCP))
3413 					return (ENXIO);
3414 				/*
3415 				 * TSO always requires hardware checksum offload.
3416 				 */
3417 				pi->ipi_csum_flags |= (CSUM_IP_TCP | CSUM_IP);
3418 				th->th_sum = in_pseudo(ip->ip_src.s_addr,
3419 						       ip->ip_dst.s_addr, htons(IPPROTO_TCP));
3420 				pi->ipi_tso_segsz = m->m_pkthdr.tso_segsz;
3421 				if (sctx->isc_flags & IFLIB_TSO_INIT_IP) {
3422 					ip->ip_sum = 0;
3423 					ip->ip_len = htons(pi->ipi_ip_hlen + pi->ipi_tcp_hlen + pi->ipi_tso_segsz);
3424 				}
3425 			}
3426 		}
3427 		if ((sctx->isc_flags & IFLIB_NEED_ZERO_CSUM) && (pi->ipi_csum_flags & CSUM_IP))
3428 			ip->ip_sum = 0;
3429 
3430 		break;
3431 	}
3432 #endif
3433 #ifdef INET6
3434 	case ETHERTYPE_IPV6:
3435 	{
3436 		struct ip6_hdr *ip6 = (struct ip6_hdr *)(m->m_data + pi->ipi_ehdrlen);
3437 		struct tcphdr *th;
3438 		pi->ipi_ip_hlen = sizeof(struct ip6_hdr);
3439 
3440 		if (__predict_false(m->m_len < pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) {
3441 			txq->ift_pullups++;
3442 			if (__predict_false((m = m_pullup(m, pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) == NULL))
3443 				return (ENOMEM);
3444 		}
3445 		th = (struct tcphdr *)((caddr_t)ip6 + pi->ipi_ip_hlen);
3446 
3447 		/* XXX-BZ this will go badly in case of ext hdrs. */
3448 		pi->ipi_ipproto = ip6->ip6_nxt;
3449 		pi->ipi_ip_tos = IPV6_TRAFFIC_CLASS(ip6);
3450 		pi->ipi_flags |= IPI_TX_IPV6;
3451 
3452 		/* TCP checksum offload may require TCP header length */
3453 		if (IS_TX_OFFLOAD6(pi)) {
3454 			if (pi->ipi_ipproto == IPPROTO_TCP) {
3455 				if (__predict_false(m->m_len < pi->ipi_ehdrlen + sizeof(struct ip6_hdr) + sizeof(struct tcphdr))) {
3456 					txq->ift_pullups++;
3457 					if (__predict_false((m = m_pullup(m, pi->ipi_ehdrlen + sizeof(struct ip6_hdr) + sizeof(struct tcphdr))) == NULL))
3458 						return (ENOMEM);
3459 				}
3460 				pi->ipi_tcp_hflags = tcp_get_flags(th);
3461 				pi->ipi_tcp_hlen = th->th_off << 2;
3462 				pi->ipi_tcp_seq = th->th_seq;
3463 			}
3464 			if (IS_TSO6(pi)) {
3465 				if (__predict_false(ip6->ip6_nxt != IPPROTO_TCP))
3466 					return (ENXIO);
3467 				/*
3468 				 * TSO always requires hardware checksum offload.
3469 				 */
3470 				pi->ipi_csum_flags |= CSUM_IP6_TCP;
3471 				th->th_sum = in6_cksum_pseudo(ip6, 0, IPPROTO_TCP, 0);
3472 				pi->ipi_tso_segsz = m->m_pkthdr.tso_segsz;
3473 			}
3474 		}
3475 		break;
3476 	}
3477 #endif
3478 	default:
3479 		pi->ipi_csum_flags &= ~CSUM_OFFLOAD;
3480 		pi->ipi_ip_hlen = 0;
3481 		break;
3482 	}
3483 	*mp = m;
3484 
3485 	return (0);
3486 }
3487 
3488 /*
3489  * If dodgy hardware rejects the scatter gather chain we've handed it
3490  * we'll need to remove the mbuf chain from ifsg_m[] before we can add the
3491  * m_defrag'd mbufs
3492  */
3493 static __noinline struct mbuf *
3494 iflib_remove_mbuf(iflib_txq_t txq)
3495 {
3496 	int ntxd, pidx;
3497 	struct mbuf *m, **ifsd_m;
3498 
3499 	ifsd_m = txq->ift_sds.ifsd_m;
3500 	ntxd = txq->ift_size;
3501 	pidx = txq->ift_pidx & (ntxd - 1);
3502 	ifsd_m = txq->ift_sds.ifsd_m;
3503 	m = ifsd_m[pidx];
3504 	ifsd_m[pidx] = NULL;
3505 	bus_dmamap_unload(txq->ift_buf_tag, txq->ift_sds.ifsd_map[pidx]);
3506 	if (txq->ift_sds.ifsd_tso_map != NULL)
3507 		bus_dmamap_unload(txq->ift_tso_buf_tag,
3508 		    txq->ift_sds.ifsd_tso_map[pidx]);
3509 #if MEMORY_LOGGING
3510 	txq->ift_dequeued++;
3511 #endif
3512 	return (m);
3513 }
3514 
3515 static inline caddr_t
3516 calc_next_txd(iflib_txq_t txq, int cidx, uint8_t qid)
3517 {
3518 	qidx_t size;
3519 	int ntxd;
3520 	caddr_t start, end, cur, next;
3521 
3522 	ntxd = txq->ift_size;
3523 	size = txq->ift_txd_size[qid];
3524 	start = txq->ift_ifdi[qid].idi_vaddr;
3525 
3526 	if (__predict_false(size == 0))
3527 		return (start);
3528 	cur = start + size * cidx;
3529 	end = start + size * ntxd;
3530 	next = CACHE_PTR_NEXT(cur);
3531 	return (next < end ? next : start);
3532 }
3533 
3534 /*
3535  * Pad an mbuf to ensure a minimum ethernet frame size.
3536  * min_frame_size is the frame size (less CRC) to pad the mbuf to
3537  */
3538 static __noinline int
3539 iflib_ether_pad(device_t dev, struct mbuf **m_head, uint16_t min_frame_size)
3540 {
3541 	/*
3542 	 * 18 is enough bytes to pad an ARP packet to 46 bytes, and
3543 	 * and ARP message is the smallest common payload I can think of
3544 	 */
3545 	static char pad[18];	/* just zeros */
3546 	int n;
3547 	struct mbuf *new_head;
3548 
3549 	if (!M_WRITABLE(*m_head)) {
3550 		new_head = m_dup(*m_head, M_NOWAIT);
3551 		if (new_head == NULL) {
3552 			m_freem(*m_head);
3553 			device_printf(dev, "cannot pad short frame, m_dup() failed");
3554 			DBG_COUNTER_INC(encap_pad_mbuf_fail);
3555 			DBG_COUNTER_INC(tx_frees);
3556 			return (ENOMEM);
3557 		}
3558 		m_freem(*m_head);
3559 		*m_head = new_head;
3560 	}
3561 
3562 	for (n = min_frame_size - (*m_head)->m_pkthdr.len;
3563 	     n > 0; n -= sizeof(pad))
3564 		if (!m_append(*m_head, min(n, sizeof(pad)), pad))
3565 			break;
3566 
3567 	if (n > 0) {
3568 		m_freem(*m_head);
3569 		device_printf(dev, "cannot pad short frame\n");
3570 		DBG_COUNTER_INC(encap_pad_mbuf_fail);
3571 		DBG_COUNTER_INC(tx_frees);
3572 		return (ENOBUFS);
3573 	}
3574 
3575 	return (0);
3576 }
3577 
3578 static int
3579 iflib_encap(iflib_txq_t txq, struct mbuf **m_headp)
3580 {
3581 	if_ctx_t		ctx;
3582 	if_shared_ctx_t		sctx;
3583 	if_softc_ctx_t		scctx;
3584 	bus_dma_tag_t		buf_tag;
3585 	bus_dma_segment_t	*segs;
3586 	struct mbuf		*m_head, **ifsd_m;
3587 	void			*next_txd;
3588 	bus_dmamap_t		map;
3589 	struct if_pkt_info	pi;
3590 	int remap = 0;
3591 	int err, nsegs, ndesc, max_segs, pidx, cidx, next, ntxd;
3592 
3593 	ctx = txq->ift_ctx;
3594 	sctx = ctx->ifc_sctx;
3595 	scctx = &ctx->ifc_softc_ctx;
3596 	segs = txq->ift_segs;
3597 	ntxd = txq->ift_size;
3598 	m_head = *m_headp;
3599 	map = NULL;
3600 
3601 	/*
3602 	 * If we're doing TSO the next descriptor to clean may be quite far ahead
3603 	 */
3604 	cidx = txq->ift_cidx;
3605 	pidx = txq->ift_pidx;
3606 	if (ctx->ifc_flags & IFC_PREFETCH) {
3607 		next = (cidx + CACHE_PTR_INCREMENT) & (ntxd - 1);
3608 		if (!(ctx->ifc_flags & IFLIB_HAS_TXCQ)) {
3609 			next_txd = calc_next_txd(txq, cidx, 0);
3610 			prefetch(next_txd);
3611 		}
3612 
3613 		/* prefetch the next cache line of mbuf pointers and flags */
3614 		prefetch(&txq->ift_sds.ifsd_m[next]);
3615 		prefetch(&txq->ift_sds.ifsd_map[next]);
3616 		next = (cidx + CACHE_LINE_SIZE) & (ntxd - 1);
3617 	}
3618 	map = txq->ift_sds.ifsd_map[pidx];
3619 	ifsd_m = txq->ift_sds.ifsd_m;
3620 
3621 	if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
3622 		buf_tag = txq->ift_tso_buf_tag;
3623 		max_segs = scctx->isc_tx_tso_segments_max;
3624 		map = txq->ift_sds.ifsd_tso_map[pidx];
3625 		MPASS(buf_tag != NULL);
3626 		MPASS(max_segs > 0);
3627 	} else {
3628 		buf_tag = txq->ift_buf_tag;
3629 		max_segs = scctx->isc_tx_nsegments;
3630 		map = txq->ift_sds.ifsd_map[pidx];
3631 	}
3632 	if ((sctx->isc_flags & IFLIB_NEED_ETHER_PAD) &&
3633 	    __predict_false(m_head->m_pkthdr.len < scctx->isc_min_frame_size)) {
3634 		err = iflib_ether_pad(ctx->ifc_dev, m_headp, scctx->isc_min_frame_size);
3635 		if (err) {
3636 			DBG_COUNTER_INC(encap_txd_encap_fail);
3637 			return (err);
3638 		}
3639 	}
3640 	m_head = *m_headp;
3641 
3642 	pkt_info_zero(&pi);
3643 	pi.ipi_mflags = (m_head->m_flags & (M_VLANTAG | M_BCAST | M_MCAST));
3644 	pi.ipi_pidx = pidx;
3645 	pi.ipi_qsidx = txq->ift_id;
3646 	pi.ipi_len = m_head->m_pkthdr.len;
3647 	pi.ipi_csum_flags = m_head->m_pkthdr.csum_flags;
3648 	pi.ipi_vtag = M_HAS_VLANTAG(m_head) ? m_head->m_pkthdr.ether_vtag : 0;
3649 
3650 	/* deliberate bitwise OR to make one condition */
3651 	if (__predict_true((pi.ipi_csum_flags | pi.ipi_vtag))) {
3652 		if (__predict_false((err = iflib_parse_header(txq, &pi, m_headp)) != 0)) {
3653 			DBG_COUNTER_INC(encap_txd_encap_fail);
3654 			return (err);
3655 		}
3656 		m_head = *m_headp;
3657 	}
3658 
3659 retry:
3660 	err = bus_dmamap_load_mbuf_sg(buf_tag, map, m_head, segs, &nsegs,
3661 	    BUS_DMA_NOWAIT);
3662 defrag:
3663 	if (__predict_false(err)) {
3664 		switch (err) {
3665 		case EFBIG:
3666 			/* try collapse once and defrag once */
3667 			if (remap == 0) {
3668 				m_head = m_collapse(*m_headp, M_NOWAIT, max_segs);
3669 				/* try defrag if collapsing fails */
3670 				if (m_head == NULL)
3671 					remap++;
3672 			}
3673 			if (remap == 1) {
3674 				txq->ift_mbuf_defrag++;
3675 				m_head = m_defrag(*m_headp, M_NOWAIT);
3676 			}
3677 			/*
3678 			 * remap should never be >1 unless bus_dmamap_load_mbuf_sg
3679 			 * failed to map an mbuf that was run through m_defrag
3680 			 */
3681 			MPASS(remap <= 1);
3682 			if (__predict_false(m_head == NULL || remap > 1))
3683 				goto defrag_failed;
3684 			remap++;
3685 			*m_headp = m_head;
3686 			goto retry;
3687 			break;
3688 		case ENOMEM:
3689 			txq->ift_no_tx_dma_setup++;
3690 			break;
3691 		default:
3692 			txq->ift_no_tx_dma_setup++;
3693 			m_freem(*m_headp);
3694 			DBG_COUNTER_INC(tx_frees);
3695 			*m_headp = NULL;
3696 			break;
3697 		}
3698 		txq->ift_map_failed++;
3699 		DBG_COUNTER_INC(encap_load_mbuf_fail);
3700 		DBG_COUNTER_INC(encap_txd_encap_fail);
3701 		return (err);
3702 	}
3703 	ifsd_m[pidx] = m_head;
3704 	/*
3705 	 * XXX assumes a 1 to 1 relationship between segments and
3706 	 *        descriptors - this does not hold true on all drivers, e.g.
3707 	 *        cxgb
3708 	 */
3709 	if (__predict_false(nsegs + 2 > TXQ_AVAIL(txq))) {
3710 		txq->ift_no_desc_avail++;
3711 		bus_dmamap_unload(buf_tag, map);
3712 		DBG_COUNTER_INC(encap_txq_avail_fail);
3713 		DBG_COUNTER_INC(encap_txd_encap_fail);
3714 		if ((txq->ift_task.gt_task.ta_flags & TASK_ENQUEUED) == 0)
3715 			GROUPTASK_ENQUEUE(&txq->ift_task);
3716 		return (ENOBUFS);
3717 	}
3718 	/*
3719 	 * On Intel cards we can greatly reduce the number of TX interrupts
3720 	 * we see by only setting report status on every Nth descriptor.
3721 	 * However, this also means that the driver will need to keep track
3722 	 * of the descriptors that RS was set on to check them for the DD bit.
3723 	 */
3724 	txq->ift_rs_pending += nsegs + 1;
3725 	if (txq->ift_rs_pending > TXQ_MAX_RS_DEFERRED(txq) ||
3726 	    iflib_no_tx_batch || (TXQ_AVAIL(txq) - nsegs) <= MAX_TX_DESC(ctx) + 2) {
3727 		pi.ipi_flags |= IPI_TX_INTR;
3728 		txq->ift_rs_pending = 0;
3729 	}
3730 
3731 	pi.ipi_segs = segs;
3732 	pi.ipi_nsegs = nsegs;
3733 
3734 	MPASS(pidx >= 0 && pidx < txq->ift_size);
3735 #ifdef PKT_DEBUG
3736 	print_pkt(&pi);
3737 #endif
3738 	if ((err = ctx->isc_txd_encap(ctx->ifc_softc, &pi)) == 0) {
3739 		bus_dmamap_sync(buf_tag, map, BUS_DMASYNC_PREWRITE);
3740 		DBG_COUNTER_INC(tx_encap);
3741 		MPASS(pi.ipi_new_pidx < txq->ift_size);
3742 
3743 		ndesc = pi.ipi_new_pidx - pi.ipi_pidx;
3744 		if (pi.ipi_new_pidx < pi.ipi_pidx) {
3745 			ndesc += txq->ift_size;
3746 			txq->ift_gen = 1;
3747 		}
3748 		/*
3749 		 * drivers can need as many as
3750 		 * two sentinels
3751 		 */
3752 		MPASS(ndesc <= pi.ipi_nsegs + 2);
3753 		MPASS(pi.ipi_new_pidx != pidx);
3754 		MPASS(ndesc > 0);
3755 		txq->ift_in_use += ndesc;
3756 		txq->ift_db_pending += ndesc;
3757 
3758 		/*
3759 		 * We update the last software descriptor again here because there may
3760 		 * be a sentinel and/or there may be more mbufs than segments
3761 		 */
3762 		txq->ift_pidx = pi.ipi_new_pidx;
3763 		txq->ift_npending += pi.ipi_ndescs;
3764 	} else {
3765 		*m_headp = m_head = iflib_remove_mbuf(txq);
3766 		if (err == EFBIG) {
3767 			txq->ift_txd_encap_efbig++;
3768 			if (remap < 2) {
3769 				remap = 1;
3770 				goto defrag;
3771 			}
3772 		}
3773 		goto defrag_failed;
3774 	}
3775 	/*
3776 	 * err can't possibly be non-zero here, so we don't neet to test it
3777 	 * to see if we need to DBG_COUNTER_INC(encap_txd_encap_fail).
3778 	 */
3779 	return (err);
3780 
3781 defrag_failed:
3782 	txq->ift_mbuf_defrag_failed++;
3783 	txq->ift_map_failed++;
3784 	m_freem(*m_headp);
3785 	DBG_COUNTER_INC(tx_frees);
3786 	*m_headp = NULL;
3787 	DBG_COUNTER_INC(encap_txd_encap_fail);
3788 	return (ENOMEM);
3789 }
3790 
3791 static void
3792 iflib_tx_desc_free(iflib_txq_t txq, int n)
3793 {
3794 	uint32_t qsize, cidx, mask, gen;
3795 	struct mbuf *m, **ifsd_m;
3796 	bool do_prefetch;
3797 
3798 	cidx = txq->ift_cidx;
3799 	gen = txq->ift_gen;
3800 	qsize = txq->ift_size;
3801 	mask = qsize - 1;
3802 	ifsd_m = txq->ift_sds.ifsd_m;
3803 	do_prefetch = (txq->ift_ctx->ifc_flags & IFC_PREFETCH);
3804 
3805 	while (n-- > 0) {
3806 		if (do_prefetch) {
3807 			prefetch(ifsd_m[(cidx + 3) & mask]);
3808 			prefetch(ifsd_m[(cidx + 4) & mask]);
3809 		}
3810 		if ((m = ifsd_m[cidx]) != NULL) {
3811 			prefetch(&ifsd_m[(cidx + CACHE_PTR_INCREMENT) & mask]);
3812 			if (m->m_pkthdr.csum_flags & CSUM_TSO) {
3813 				bus_dmamap_sync(txq->ift_tso_buf_tag,
3814 				    txq->ift_sds.ifsd_tso_map[cidx],
3815 				    BUS_DMASYNC_POSTWRITE);
3816 				bus_dmamap_unload(txq->ift_tso_buf_tag,
3817 				    txq->ift_sds.ifsd_tso_map[cidx]);
3818 			} else {
3819 				bus_dmamap_sync(txq->ift_buf_tag,
3820 				    txq->ift_sds.ifsd_map[cidx],
3821 				    BUS_DMASYNC_POSTWRITE);
3822 				bus_dmamap_unload(txq->ift_buf_tag,
3823 				    txq->ift_sds.ifsd_map[cidx]);
3824 			}
3825 			/* XXX we don't support any drivers that batch packets yet */
3826 			MPASS(m->m_nextpkt == NULL);
3827 			m_freem(m);
3828 			ifsd_m[cidx] = NULL;
3829 #if MEMORY_LOGGING
3830 			txq->ift_dequeued++;
3831 #endif
3832 			DBG_COUNTER_INC(tx_frees);
3833 		}
3834 		if (__predict_false(++cidx == qsize)) {
3835 			cidx = 0;
3836 			gen = 0;
3837 		}
3838 	}
3839 	txq->ift_cidx = cidx;
3840 	txq->ift_gen = gen;
3841 }
3842 
3843 static __inline int
3844 iflib_completed_tx_reclaim(iflib_txq_t txq, int thresh)
3845 {
3846 	int reclaim;
3847 	if_ctx_t ctx = txq->ift_ctx;
3848 
3849 	KASSERT(thresh >= 0, ("invalid threshold to reclaim"));
3850 	MPASS(thresh /*+ MAX_TX_DESC(txq->ift_ctx) */ < txq->ift_size);
3851 
3852 	/*
3853 	 * Need a rate-limiting check so that this isn't called every time
3854 	 */
3855 	iflib_tx_credits_update(ctx, txq);
3856 	reclaim = DESC_RECLAIMABLE(txq);
3857 
3858 	if (reclaim <= thresh /* + MAX_TX_DESC(txq->ift_ctx) */) {
3859 #ifdef INVARIANTS
3860 		if (iflib_verbose_debug) {
3861 			printf("%s processed=%ju cleaned=%ju tx_nsegments=%d reclaim=%d thresh=%d\n", __func__,
3862 			    txq->ift_processed, txq->ift_cleaned, txq->ift_ctx->ifc_softc_ctx.isc_tx_nsegments,
3863 			    reclaim, thresh);
3864 		}
3865 #endif
3866 		return (0);
3867 	}
3868 	iflib_tx_desc_free(txq, reclaim);
3869 	txq->ift_cleaned += reclaim;
3870 	txq->ift_in_use -= reclaim;
3871 
3872 	return (reclaim);
3873 }
3874 
3875 static struct mbuf **
3876 _ring_peek_one(struct ifmp_ring *r, int cidx, int offset, int remaining)
3877 {
3878 	int next, size;
3879 	struct mbuf **items;
3880 
3881 	size = r->size;
3882 	next = (cidx + CACHE_PTR_INCREMENT) & (size - 1);
3883 	items = __DEVOLATILE(struct mbuf **, &r->items[0]);
3884 
3885 	prefetch(items[(cidx + offset) & (size - 1)]);
3886 	if (remaining > 1) {
3887 		prefetch2cachelines(&items[next]);
3888 		prefetch2cachelines(items[(cidx + offset + 1) & (size - 1)]);
3889 		prefetch2cachelines(items[(cidx + offset + 2) & (size - 1)]);
3890 		prefetch2cachelines(items[(cidx + offset + 3) & (size - 1)]);
3891 	}
3892 	return (__DEVOLATILE(struct mbuf **, &r->items[(cidx + offset) & (size - 1)]));
3893 }
3894 
3895 static void
3896 iflib_txq_check_drain(iflib_txq_t txq, int budget)
3897 {
3898 
3899 	ifmp_ring_check_drainage(txq->ift_br, budget);
3900 }
3901 
3902 static uint32_t
3903 iflib_txq_can_drain(struct ifmp_ring *r)
3904 {
3905 	iflib_txq_t txq = r->cookie;
3906 	if_ctx_t ctx = txq->ift_ctx;
3907 
3908 	if (TXQ_AVAIL(txq) > MAX_TX_DESC(ctx) + 2)
3909 		return (1);
3910 	bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
3911 	    BUS_DMASYNC_POSTREAD);
3912 	return (ctx->isc_txd_credits_update(ctx->ifc_softc, txq->ift_id,
3913 	    false));
3914 }
3915 
3916 static uint32_t
3917 iflib_txq_drain(struct ifmp_ring *r, uint32_t cidx, uint32_t pidx)
3918 {
3919 	iflib_txq_t txq = r->cookie;
3920 	if_ctx_t ctx = txq->ift_ctx;
3921 	if_t ifp = ctx->ifc_ifp;
3922 	struct mbuf *m, **mp;
3923 	int avail, bytes_sent, skipped, count, err, i;
3924 	int mcast_sent, pkt_sent, reclaimed;
3925 	bool do_prefetch, rang, ring;
3926 
3927 	if (__predict_false(!(if_getdrvflags(ifp) & IFF_DRV_RUNNING) ||
3928 			    !LINK_ACTIVE(ctx))) {
3929 		DBG_COUNTER_INC(txq_drain_notready);
3930 		return (0);
3931 	}
3932 	reclaimed = iflib_completed_tx_reclaim(txq, RECLAIM_THRESH(ctx));
3933 	rang = iflib_txd_db_check(txq, reclaimed && txq->ift_db_pending);
3934 	avail = IDXDIFF(pidx, cidx, r->size);
3935 
3936 	if (__predict_false(ctx->ifc_flags & IFC_QFLUSH)) {
3937 		/*
3938 		 * The driver is unloading so we need to free all pending packets.
3939 		 */
3940 		DBG_COUNTER_INC(txq_drain_flushing);
3941 		for (i = 0; i < avail; i++) {
3942 			if (__predict_true(r->items[(cidx + i) & (r->size - 1)] != (void *)txq))
3943 				m_freem(r->items[(cidx + i) & (r->size - 1)]);
3944 			r->items[(cidx + i) & (r->size - 1)] = NULL;
3945 		}
3946 		return (avail);
3947 	}
3948 
3949 	if (__predict_false(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_OACTIVE)) {
3950 		txq->ift_qstatus = IFLIB_QUEUE_IDLE;
3951 		CALLOUT_LOCK(txq);
3952 		callout_stop(&txq->ift_timer);
3953 		CALLOUT_UNLOCK(txq);
3954 		DBG_COUNTER_INC(txq_drain_oactive);
3955 		return (0);
3956 	}
3957 
3958 	/*
3959 	 * If we've reclaimed any packets this queue cannot be hung.
3960 	 */
3961 	if (reclaimed)
3962 		txq->ift_qstatus = IFLIB_QUEUE_IDLE;
3963 	skipped = mcast_sent = bytes_sent = pkt_sent = 0;
3964 	count = MIN(avail, TX_BATCH_SIZE);
3965 #ifdef INVARIANTS
3966 	if (iflib_verbose_debug)
3967 		printf("%s avail=%d ifc_flags=%x txq_avail=%d ", __func__,
3968 		    avail, ctx->ifc_flags, TXQ_AVAIL(txq));
3969 #endif
3970 	do_prefetch = (ctx->ifc_flags & IFC_PREFETCH);
3971 	err = 0;
3972 	for (i = 0; i < count && TXQ_AVAIL(txq) >= MAX_TX_DESC(ctx) + 2; i++) {
3973 		int rem = do_prefetch ? count - i : 0;
3974 
3975 		mp = _ring_peek_one(r, cidx, i, rem);
3976 		MPASS(mp != NULL && *mp != NULL);
3977 
3978 		/*
3979 		 * Completion interrupts will use the address of the txq
3980 		 * as a sentinel to enqueue _something_ in order to acquire
3981 		 * the lock on the mp_ring (there's no direct lock call).
3982 		 * We obviously whave to check for these sentinel cases
3983 		 * and skip them.
3984 		 */
3985 		if (__predict_false(*mp == (struct mbuf *)txq)) {
3986 			skipped++;
3987 			continue;
3988 		}
3989 		err = iflib_encap(txq, mp);
3990 		if (__predict_false(err)) {
3991 			/* no room - bail out */
3992 			if (err == ENOBUFS)
3993 				break;
3994 			skipped++;
3995 			/* we can't send this packet - skip it */
3996 			continue;
3997 		}
3998 		pkt_sent++;
3999 		m = *mp;
4000 		DBG_COUNTER_INC(tx_sent);
4001 		bytes_sent += m->m_pkthdr.len;
4002 		mcast_sent += !!(m->m_flags & M_MCAST);
4003 
4004 		if (__predict_false(!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)))
4005 			break;
4006 		ETHER_BPF_MTAP(ifp, m);
4007 		rang = iflib_txd_db_check(txq, false);
4008 	}
4009 
4010 	/* deliberate use of bitwise or to avoid gratuitous short-circuit */
4011 	ring = rang ? false  : (iflib_min_tx_latency | err);
4012 	iflib_txd_db_check(txq, ring);
4013 	if_inc_counter(ifp, IFCOUNTER_OBYTES, bytes_sent);
4014 	if_inc_counter(ifp, IFCOUNTER_OPACKETS, pkt_sent);
4015 	if (mcast_sent)
4016 		if_inc_counter(ifp, IFCOUNTER_OMCASTS, mcast_sent);
4017 #ifdef INVARIANTS
4018 	if (iflib_verbose_debug)
4019 		printf("consumed=%d\n", skipped + pkt_sent);
4020 #endif
4021 	return (skipped + pkt_sent);
4022 }
4023 
4024 static uint32_t
4025 iflib_txq_drain_always(struct ifmp_ring *r)
4026 {
4027 	return (1);
4028 }
4029 
4030 static uint32_t
4031 iflib_txq_drain_free(struct ifmp_ring *r, uint32_t cidx, uint32_t pidx)
4032 {
4033 	int i, avail;
4034 	struct mbuf **mp;
4035 	iflib_txq_t txq;
4036 
4037 	txq = r->cookie;
4038 
4039 	txq->ift_qstatus = IFLIB_QUEUE_IDLE;
4040 	CALLOUT_LOCK(txq);
4041 	callout_stop(&txq->ift_timer);
4042 	CALLOUT_UNLOCK(txq);
4043 
4044 	avail = IDXDIFF(pidx, cidx, r->size);
4045 	for (i = 0; i < avail; i++) {
4046 		mp = _ring_peek_one(r, cidx, i, avail - i);
4047 		if (__predict_false(*mp == (struct mbuf *)txq))
4048 			continue;
4049 		m_freem(*mp);
4050 		DBG_COUNTER_INC(tx_frees);
4051 	}
4052 	MPASS(ifmp_ring_is_stalled(r) == 0);
4053 	return (avail);
4054 }
4055 
4056 static void
4057 iflib_ifmp_purge(iflib_txq_t txq)
4058 {
4059 	struct ifmp_ring *r;
4060 
4061 	r = txq->ift_br;
4062 	r->drain = iflib_txq_drain_free;
4063 	r->can_drain = iflib_txq_drain_always;
4064 
4065 	ifmp_ring_check_drainage(r, r->size);
4066 
4067 	r->drain = iflib_txq_drain;
4068 	r->can_drain = iflib_txq_can_drain;
4069 }
4070 
4071 static void
4072 _task_fn_tx(void *context)
4073 {
4074 	iflib_txq_t txq = context;
4075 	if_ctx_t ctx = txq->ift_ctx;
4076 	if_t ifp = ctx->ifc_ifp;
4077 	int abdicate = ctx->ifc_sysctl_tx_abdicate;
4078 
4079 #ifdef IFLIB_DIAGNOSTICS
4080 	txq->ift_cpu_exec_count[curcpu]++;
4081 #endif
4082 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
4083 		return;
4084 #ifdef DEV_NETMAP
4085 	if ((if_getcapenable(ifp) & IFCAP_NETMAP) &&
4086 	    netmap_tx_irq(ifp, txq->ift_id))
4087 		goto skip_ifmp;
4088 #endif
4089 #ifdef ALTQ
4090 	if (if_altq_is_enabled(ifp))
4091 		iflib_altq_if_start(ifp);
4092 #endif
4093 	if (txq->ift_db_pending)
4094 		ifmp_ring_enqueue(txq->ift_br, (void **)&txq, 1, TX_BATCH_SIZE, abdicate);
4095 	else if (!abdicate)
4096 		ifmp_ring_check_drainage(txq->ift_br, TX_BATCH_SIZE);
4097 	/*
4098 	 * When abdicating, we always need to check drainage, not just when we don't enqueue
4099 	 */
4100 	if (abdicate)
4101 		ifmp_ring_check_drainage(txq->ift_br, TX_BATCH_SIZE);
4102 #ifdef DEV_NETMAP
4103 skip_ifmp:
4104 #endif
4105 	if (ctx->ifc_flags & IFC_LEGACY)
4106 		IFDI_INTR_ENABLE(ctx);
4107 	else
4108 		IFDI_TX_QUEUE_INTR_ENABLE(ctx, txq->ift_id);
4109 }
4110 
4111 static void
4112 _task_fn_rx(void *context)
4113 {
4114 	iflib_rxq_t rxq = context;
4115 	if_ctx_t ctx = rxq->ifr_ctx;
4116 	uint8_t more;
4117 	uint16_t budget;
4118 #ifdef DEV_NETMAP
4119 	u_int work = 0;
4120 	int nmirq;
4121 #endif
4122 
4123 #ifdef IFLIB_DIAGNOSTICS
4124 	rxq->ifr_cpu_exec_count[curcpu]++;
4125 #endif
4126 	DBG_COUNTER_INC(task_fn_rxs);
4127 	if (__predict_false(!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)))
4128 		return;
4129 #ifdef DEV_NETMAP
4130 	nmirq = netmap_rx_irq(ctx->ifc_ifp, rxq->ifr_id, &work);
4131 	if (nmirq != NM_IRQ_PASS) {
4132 		more = (nmirq == NM_IRQ_RESCHED) ? IFLIB_RXEOF_MORE : 0;
4133 		goto skip_rxeof;
4134 	}
4135 #endif
4136 	budget = ctx->ifc_sysctl_rx_budget;
4137 	if (budget == 0)
4138 		budget = 16;	/* XXX */
4139 	more = iflib_rxeof(rxq, budget);
4140 #ifdef DEV_NETMAP
4141 skip_rxeof:
4142 #endif
4143 	if ((more & IFLIB_RXEOF_MORE) == 0) {
4144 		if (ctx->ifc_flags & IFC_LEGACY)
4145 			IFDI_INTR_ENABLE(ctx);
4146 		else
4147 			IFDI_RX_QUEUE_INTR_ENABLE(ctx, rxq->ifr_id);
4148 		DBG_COUNTER_INC(rx_intr_enables);
4149 	}
4150 	if (__predict_false(!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)))
4151 		return;
4152 
4153 	if (more & IFLIB_RXEOF_MORE)
4154 		GROUPTASK_ENQUEUE(&rxq->ifr_task);
4155 	else if (more & IFLIB_RXEOF_EMPTY)
4156 		callout_reset_curcpu(&rxq->ifr_watchdog, 1, &_task_fn_rx_watchdog, rxq);
4157 }
4158 
4159 static void
4160 _task_fn_admin(void *context, int pending)
4161 {
4162 	if_ctx_t ctx = context;
4163 	if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
4164 	iflib_txq_t txq;
4165 	int i;
4166 	bool oactive, running, do_reset, do_watchdog, in_detach;
4167 
4168 	STATE_LOCK(ctx);
4169 	running = (if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING);
4170 	oactive = (if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_OACTIVE);
4171 	do_reset = (ctx->ifc_flags & IFC_DO_RESET);
4172 	do_watchdog = (ctx->ifc_flags & IFC_DO_WATCHDOG);
4173 	in_detach = (ctx->ifc_flags & IFC_IN_DETACH);
4174 	ctx->ifc_flags &= ~(IFC_DO_RESET | IFC_DO_WATCHDOG);
4175 	STATE_UNLOCK(ctx);
4176 
4177 	if ((!running && !oactive) && !(ctx->ifc_sctx->isc_flags & IFLIB_ADMIN_ALWAYS_RUN))
4178 		return;
4179 	if (in_detach)
4180 		return;
4181 
4182 	CTX_LOCK(ctx);
4183 	for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++) {
4184 		CALLOUT_LOCK(txq);
4185 		callout_stop(&txq->ift_timer);
4186 		CALLOUT_UNLOCK(txq);
4187 	}
4188 	if (ctx->ifc_sctx->isc_flags & IFLIB_HAS_ADMINCQ)
4189 		IFDI_ADMIN_COMPLETION_HANDLE(ctx);
4190 	if (do_watchdog) {
4191 		ctx->ifc_watchdog_events++;
4192 		IFDI_WATCHDOG_RESET(ctx);
4193 	}
4194 	IFDI_UPDATE_ADMIN_STATUS(ctx);
4195 	for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++) {
4196 		callout_reset_on(&txq->ift_timer, iflib_timer_default, iflib_timer, txq,
4197 		    txq->ift_timer.c_cpu);
4198 	}
4199 	IFDI_LINK_INTR_ENABLE(ctx);
4200 	if (do_reset)
4201 		iflib_if_init_locked(ctx);
4202 	CTX_UNLOCK(ctx);
4203 
4204 	if (LINK_ACTIVE(ctx) == 0)
4205 		return;
4206 	for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++)
4207 		iflib_txq_check_drain(txq, IFLIB_RESTART_BUDGET);
4208 }
4209 
4210 static void
4211 _task_fn_iov(void *context, int pending)
4212 {
4213 	if_ctx_t ctx = context;
4214 
4215 	if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING) &&
4216 	    !(ctx->ifc_sctx->isc_flags & IFLIB_ADMIN_ALWAYS_RUN))
4217 		return;
4218 
4219 	CTX_LOCK(ctx);
4220 	IFDI_VFLR_HANDLE(ctx);
4221 	CTX_UNLOCK(ctx);
4222 }
4223 
4224 static int
4225 iflib_sysctl_int_delay(SYSCTL_HANDLER_ARGS)
4226 {
4227 	int err;
4228 	if_int_delay_info_t info;
4229 	if_ctx_t ctx;
4230 
4231 	info = (if_int_delay_info_t)arg1;
4232 	ctx = info->iidi_ctx;
4233 	info->iidi_req = req;
4234 	info->iidi_oidp = oidp;
4235 	CTX_LOCK(ctx);
4236 	err = IFDI_SYSCTL_INT_DELAY(ctx, info);
4237 	CTX_UNLOCK(ctx);
4238 	return (err);
4239 }
4240 
4241 /*********************************************************************
4242  *
4243  *  IFNET FUNCTIONS
4244  *
4245  **********************************************************************/
4246 
4247 static void
4248 iflib_if_init_locked(if_ctx_t ctx)
4249 {
4250 	iflib_stop(ctx);
4251 	iflib_init_locked(ctx);
4252 }
4253 
4254 static void
4255 iflib_if_init(void *arg)
4256 {
4257 	if_ctx_t ctx = arg;
4258 
4259 	CTX_LOCK(ctx);
4260 	iflib_if_init_locked(ctx);
4261 	CTX_UNLOCK(ctx);
4262 }
4263 
4264 static int
4265 iflib_if_transmit(if_t ifp, struct mbuf *m)
4266 {
4267 	if_ctx_t ctx = if_getsoftc(ifp);
4268 	iflib_txq_t txq;
4269 	int err, qidx;
4270 	int abdicate;
4271 
4272 	if (__predict_false((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0 || !LINK_ACTIVE(ctx))) {
4273 		DBG_COUNTER_INC(tx_frees);
4274 		m_freem(m);
4275 		return (ENETDOWN);
4276 	}
4277 
4278 	MPASS(m->m_nextpkt == NULL);
4279 	/* ALTQ-enabled interfaces always use queue 0. */
4280 	qidx = 0;
4281 	/* Use driver-supplied queue selection method if it exists */
4282 	if (ctx->isc_txq_select_v2) {
4283 		struct if_pkt_info pi;
4284 		uint64_t early_pullups = 0;
4285 		pkt_info_zero(&pi);
4286 
4287 		err = iflib_parse_header_partial(&pi, &m, &early_pullups);
4288 		if (__predict_false(err != 0)) {
4289 			/* Assign pullups for bad pkts to default queue */
4290 			ctx->ifc_txqs[0].ift_pullups += early_pullups;
4291 			DBG_COUNTER_INC(encap_txd_encap_fail);
4292 			return (err);
4293 		}
4294 		/* Let driver make queueing decision */
4295 		qidx = ctx->isc_txq_select_v2(ctx->ifc_softc, m, &pi);
4296 		ctx->ifc_txqs[qidx].ift_pullups += early_pullups;
4297 	}
4298 	/* Backwards compatibility w/ simpler queue select */
4299 	else if (ctx->isc_txq_select)
4300 		qidx = ctx->isc_txq_select(ctx->ifc_softc, m);
4301 	/* If not, use iflib's standard method */
4302 	else if ((NTXQSETS(ctx) > 1) && M_HASHTYPE_GET(m) && !if_altq_is_enabled(ifp))
4303 		qidx = QIDX(ctx, m);
4304 
4305 	/* Set TX queue */
4306 	txq = &ctx->ifc_txqs[qidx];
4307 
4308 #ifdef DRIVER_BACKPRESSURE
4309 	if (txq->ift_closed) {
4310 		while (m != NULL) {
4311 			next = m->m_nextpkt;
4312 			m->m_nextpkt = NULL;
4313 			m_freem(m);
4314 			DBG_COUNTER_INC(tx_frees);
4315 			m = next;
4316 		}
4317 		return (ENOBUFS);
4318 	}
4319 #endif
4320 #ifdef notyet
4321 	qidx = count = 0;
4322 	mp = marr;
4323 	next = m;
4324 	do {
4325 		count++;
4326 		next = next->m_nextpkt;
4327 	} while (next != NULL);
4328 
4329 	if (count > nitems(marr))
4330 		if ((mp = malloc(count * sizeof(struct mbuf *), M_IFLIB, M_NOWAIT)) == NULL) {
4331 			/* XXX check nextpkt */
4332 			m_freem(m);
4333 			/* XXX simplify for now */
4334 			DBG_COUNTER_INC(tx_frees);
4335 			return (ENOBUFS);
4336 		}
4337 	for (next = m, i = 0; next != NULL; i++) {
4338 		mp[i] = next;
4339 		next = next->m_nextpkt;
4340 		mp[i]->m_nextpkt = NULL;
4341 	}
4342 #endif
4343 	DBG_COUNTER_INC(tx_seen);
4344 	abdicate = ctx->ifc_sysctl_tx_abdicate;
4345 
4346 	err = ifmp_ring_enqueue(txq->ift_br, (void **)&m, 1, TX_BATCH_SIZE, abdicate);
4347 
4348 	if (abdicate)
4349 		GROUPTASK_ENQUEUE(&txq->ift_task);
4350 	if (err) {
4351 		if (!abdicate)
4352 			GROUPTASK_ENQUEUE(&txq->ift_task);
4353 		/* support forthcoming later */
4354 #ifdef DRIVER_BACKPRESSURE
4355 		txq->ift_closed = TRUE;
4356 #endif
4357 		ifmp_ring_check_drainage(txq->ift_br, TX_BATCH_SIZE);
4358 		m_freem(m);
4359 		DBG_COUNTER_INC(tx_frees);
4360 	}
4361 
4362 	return (err);
4363 }
4364 
4365 #ifdef ALTQ
4366 /*
4367  * The overall approach to integrating iflib with ALTQ is to continue to use
4368  * the iflib mp_ring machinery between the ALTQ queue(s) and the hardware
4369  * ring.  Technically, when using ALTQ, queueing to an intermediate mp_ring
4370  * is redundant/unnecessary, but doing so minimizes the amount of
4371  * ALTQ-specific code required in iflib.  It is assumed that the overhead of
4372  * redundantly queueing to an intermediate mp_ring is swamped by the
4373  * performance limitations inherent in using ALTQ.
4374  *
4375  * When ALTQ support is compiled in, all iflib drivers will use a transmit
4376  * routine, iflib_altq_if_transmit(), that checks if ALTQ is enabled for the
4377  * given interface.  If ALTQ is enabled for an interface, then all
4378  * transmitted packets for that interface will be submitted to the ALTQ
4379  * subsystem via IFQ_ENQUEUE().  We don't use the legacy if_transmit()
4380  * implementation because it uses IFQ_HANDOFF(), which will duplicatively
4381  * update stats that the iflib machinery handles, and which is sensitve to
4382  * the disused IFF_DRV_OACTIVE flag.  Additionally, iflib_altq_if_start()
4383  * will be installed as the start routine for use by ALTQ facilities that
4384  * need to trigger queue drains on a scheduled basis.
4385  *
4386  */
4387 static void
4388 iflib_altq_if_start(if_t ifp)
4389 {
4390 	struct ifaltq *ifq = &ifp->if_snd; /* XXX - DRVAPI */
4391 	struct mbuf *m;
4392 
4393 	IFQ_LOCK(ifq);
4394 	IFQ_DEQUEUE_NOLOCK(ifq, m);
4395 	while (m != NULL) {
4396 		iflib_if_transmit(ifp, m);
4397 		IFQ_DEQUEUE_NOLOCK(ifq, m);
4398 	}
4399 	IFQ_UNLOCK(ifq);
4400 }
4401 
4402 static int
4403 iflib_altq_if_transmit(if_t ifp, struct mbuf *m)
4404 {
4405 	int err;
4406 
4407 	if (if_altq_is_enabled(ifp)) {
4408 		IFQ_ENQUEUE(&ifp->if_snd, m, err); /* XXX - DRVAPI */
4409 		if (err == 0)
4410 			iflib_altq_if_start(ifp);
4411 	} else
4412 		err = iflib_if_transmit(ifp, m);
4413 
4414 	return (err);
4415 }
4416 #endif /* ALTQ */
4417 
4418 static void
4419 iflib_if_qflush(if_t ifp)
4420 {
4421 	if_ctx_t ctx = if_getsoftc(ifp);
4422 	iflib_txq_t txq = ctx->ifc_txqs;
4423 	int i;
4424 
4425 	STATE_LOCK(ctx);
4426 	ctx->ifc_flags |= IFC_QFLUSH;
4427 	STATE_UNLOCK(ctx);
4428 	for (i = 0; i < NTXQSETS(ctx); i++, txq++)
4429 		while (!(ifmp_ring_is_idle(txq->ift_br) || ifmp_ring_is_stalled(txq->ift_br)))
4430 			iflib_txq_check_drain(txq, 0);
4431 	STATE_LOCK(ctx);
4432 	ctx->ifc_flags &= ~IFC_QFLUSH;
4433 	STATE_UNLOCK(ctx);
4434 
4435 	/*
4436 	 * When ALTQ is enabled, this will also take care of purging the
4437 	 * ALTQ queue(s).
4438 	 */
4439 	if_qflush(ifp);
4440 }
4441 
4442 #define IFCAP_FLAGS (IFCAP_HWCSUM_IPV6 | IFCAP_HWCSUM | IFCAP_LRO | \
4443 		    IFCAP_TSO | IFCAP_VLAN_HWTAGGING | IFCAP_HWSTATS | \
4444 		    IFCAP_VLAN_MTU | IFCAP_VLAN_HWFILTER | \
4445 		    IFCAP_VLAN_HWTSO | IFCAP_VLAN_HWCSUM | IFCAP_MEXTPG)
4446 
4447 static int
4448 iflib_if_ioctl(if_t ifp, u_long command, caddr_t data)
4449 {
4450 	if_ctx_t ctx = if_getsoftc(ifp);
4451 	struct ifreq	*ifr = (struct ifreq *)data;
4452 #if defined(INET) || defined(INET6)
4453 	struct ifaddr	*ifa = (struct ifaddr *)data;
4454 #endif
4455 	bool		avoid_reset = false;
4456 	int		err = 0, reinit = 0, bits;
4457 
4458 	switch (command) {
4459 	case SIOCSIFADDR:
4460 #ifdef INET
4461 		if (ifa->ifa_addr->sa_family == AF_INET)
4462 			avoid_reset = true;
4463 #endif
4464 #ifdef INET6
4465 		if (ifa->ifa_addr->sa_family == AF_INET6)
4466 			avoid_reset = true;
4467 #endif
4468 		/*
4469 		 * Calling init results in link renegotiation,
4470 		 * so we avoid doing it when possible.
4471 		 */
4472 		if (avoid_reset) {
4473 			if_setflagbits(ifp, IFF_UP, 0);
4474 			if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
4475 				reinit = 1;
4476 #ifdef INET
4477 			if (!(if_getflags(ifp) & IFF_NOARP))
4478 				arp_ifinit(ifp, ifa);
4479 #endif
4480 		} else
4481 			err = ether_ioctl(ifp, command, data);
4482 		break;
4483 	case SIOCSIFMTU:
4484 		CTX_LOCK(ctx);
4485 		if (ifr->ifr_mtu == if_getmtu(ifp)) {
4486 			CTX_UNLOCK(ctx);
4487 			break;
4488 		}
4489 		bits = if_getdrvflags(ifp);
4490 		/* stop the driver and free any clusters before proceeding */
4491 		iflib_stop(ctx);
4492 
4493 		if ((err = IFDI_MTU_SET(ctx, ifr->ifr_mtu)) == 0) {
4494 			STATE_LOCK(ctx);
4495 			if (ifr->ifr_mtu > ctx->ifc_max_fl_buf_size)
4496 				ctx->ifc_flags |= IFC_MULTISEG;
4497 			else
4498 				ctx->ifc_flags &= ~IFC_MULTISEG;
4499 			STATE_UNLOCK(ctx);
4500 			err = if_setmtu(ifp, ifr->ifr_mtu);
4501 		}
4502 		iflib_init_locked(ctx);
4503 		STATE_LOCK(ctx);
4504 		if_setdrvflags(ifp, bits);
4505 		STATE_UNLOCK(ctx);
4506 		CTX_UNLOCK(ctx);
4507 		break;
4508 	case SIOCSIFFLAGS:
4509 		CTX_LOCK(ctx);
4510 		if (if_getflags(ifp) & IFF_UP) {
4511 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4512 				if ((if_getflags(ifp) ^ ctx->ifc_if_flags) &
4513 				    (IFF_PROMISC | IFF_ALLMULTI)) {
4514 					CTX_UNLOCK(ctx);
4515 					err = IFDI_PROMISC_SET(ctx, if_getflags(ifp));
4516 					CTX_LOCK(ctx);
4517 				}
4518 			} else
4519 				reinit = 1;
4520 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4521 			iflib_stop(ctx);
4522 		}
4523 		ctx->ifc_if_flags = if_getflags(ifp);
4524 		CTX_UNLOCK(ctx);
4525 		break;
4526 	case SIOCADDMULTI:
4527 	case SIOCDELMULTI:
4528 		if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4529 			CTX_LOCK(ctx);
4530 			IFDI_INTR_DISABLE(ctx);
4531 			IFDI_MULTI_SET(ctx);
4532 			IFDI_INTR_ENABLE(ctx);
4533 			CTX_UNLOCK(ctx);
4534 		}
4535 		break;
4536 	case SIOCSIFMEDIA:
4537 		CTX_LOCK(ctx);
4538 		IFDI_MEDIA_SET(ctx);
4539 		CTX_UNLOCK(ctx);
4540 		/* FALLTHROUGH */
4541 	case SIOCGIFMEDIA:
4542 	case SIOCGIFXMEDIA:
4543 		err = ifmedia_ioctl(ifp, ifr, ctx->ifc_mediap, command);
4544 		break;
4545 	case SIOCGI2C:
4546 	{
4547 		struct ifi2creq i2c;
4548 
4549 		err = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
4550 		if (err != 0)
4551 			break;
4552 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
4553 			err = EINVAL;
4554 			break;
4555 		}
4556 		if (i2c.len > sizeof(i2c.data)) {
4557 			err = EINVAL;
4558 			break;
4559 		}
4560 
4561 		if ((err = IFDI_I2C_REQ(ctx, &i2c)) == 0)
4562 			err = copyout(&i2c, ifr_data_get_ptr(ifr),
4563 			    sizeof(i2c));
4564 		break;
4565 	}
4566 	case SIOCSIFCAP:
4567 	{
4568 		int mask, setmask, oldmask;
4569 
4570 		oldmask = if_getcapenable(ifp);
4571 		mask = ifr->ifr_reqcap ^ oldmask;
4572 		mask &= ctx->ifc_softc_ctx.isc_capabilities | IFCAP_MEXTPG;
4573 		setmask = 0;
4574 #ifdef TCP_OFFLOAD
4575 		setmask |= mask & (IFCAP_TOE4 | IFCAP_TOE6);
4576 #endif
4577 		setmask |= (mask & IFCAP_FLAGS);
4578 		setmask |= (mask & IFCAP_WOL);
4579 
4580 		/*
4581 		 * If any RX csum has changed, change all the ones that
4582 		 * are supported by the driver.
4583 		 */
4584 		if (setmask & (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6)) {
4585 			setmask |= ctx->ifc_softc_ctx.isc_capabilities &
4586 			    (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
4587 		}
4588 
4589 		/*
4590 		 * want to ensure that traffic has stopped before we change any of the flags
4591 		 */
4592 		if (setmask) {
4593 			CTX_LOCK(ctx);
4594 			bits = if_getdrvflags(ifp);
4595 			if (bits & IFF_DRV_RUNNING && setmask & ~IFCAP_WOL)
4596 				iflib_stop(ctx);
4597 			STATE_LOCK(ctx);
4598 			if_togglecapenable(ifp, setmask);
4599 			ctx->ifc_softc_ctx.isc_capenable ^= setmask;
4600 			STATE_UNLOCK(ctx);
4601 			if (bits & IFF_DRV_RUNNING && setmask & ~IFCAP_WOL)
4602 				iflib_init_locked(ctx);
4603 			STATE_LOCK(ctx);
4604 			if_setdrvflags(ifp, bits);
4605 			STATE_UNLOCK(ctx);
4606 			CTX_UNLOCK(ctx);
4607 		}
4608 		if_vlancap(ifp);
4609 		break;
4610 	}
4611 	case SIOCGPRIVATE_0:
4612 	case SIOCSDRVSPEC:
4613 	case SIOCGDRVSPEC:
4614 		CTX_LOCK(ctx);
4615 		err = IFDI_PRIV_IOCTL(ctx, command, data);
4616 		CTX_UNLOCK(ctx);
4617 		break;
4618 	default:
4619 		err = ether_ioctl(ifp, command, data);
4620 		break;
4621 	}
4622 	if (reinit)
4623 		iflib_if_init(ctx);
4624 	return (err);
4625 }
4626 
4627 static uint64_t
4628 iflib_if_get_counter(if_t ifp, ift_counter cnt)
4629 {
4630 	if_ctx_t ctx = if_getsoftc(ifp);
4631 
4632 	return (IFDI_GET_COUNTER(ctx, cnt));
4633 }
4634 
4635 /*********************************************************************
4636  *
4637  *  OTHER FUNCTIONS EXPORTED TO THE STACK
4638  *
4639  **********************************************************************/
4640 
4641 static void
4642 iflib_vlan_register(void *arg, if_t ifp, uint16_t vtag)
4643 {
4644 	if_ctx_t ctx = if_getsoftc(ifp);
4645 
4646 	if ((void *)ctx != arg)
4647 		return;
4648 
4649 	if ((vtag == 0) || (vtag > 4095))
4650 		return;
4651 
4652 	if (iflib_in_detach(ctx))
4653 		return;
4654 
4655 	CTX_LOCK(ctx);
4656 	/* Driver may need all untagged packets to be flushed */
4657 	if (IFDI_NEEDS_RESTART(ctx, IFLIB_RESTART_VLAN_CONFIG))
4658 		iflib_stop(ctx);
4659 	IFDI_VLAN_REGISTER(ctx, vtag);
4660 	/* Re-init to load the changes, if required */
4661 	if (IFDI_NEEDS_RESTART(ctx, IFLIB_RESTART_VLAN_CONFIG))
4662 		iflib_init_locked(ctx);
4663 	CTX_UNLOCK(ctx);
4664 }
4665 
4666 static void
4667 iflib_vlan_unregister(void *arg, if_t ifp, uint16_t vtag)
4668 {
4669 	if_ctx_t ctx = if_getsoftc(ifp);
4670 
4671 	if ((void *)ctx != arg)
4672 		return;
4673 
4674 	if ((vtag == 0) || (vtag > 4095))
4675 		return;
4676 
4677 	CTX_LOCK(ctx);
4678 	/* Driver may need all tagged packets to be flushed */
4679 	if (IFDI_NEEDS_RESTART(ctx, IFLIB_RESTART_VLAN_CONFIG))
4680 		iflib_stop(ctx);
4681 	IFDI_VLAN_UNREGISTER(ctx, vtag);
4682 	/* Re-init to load the changes, if required */
4683 	if (IFDI_NEEDS_RESTART(ctx, IFLIB_RESTART_VLAN_CONFIG))
4684 		iflib_init_locked(ctx);
4685 	CTX_UNLOCK(ctx);
4686 }
4687 
4688 static void
4689 iflib_led_func(void *arg, int onoff)
4690 {
4691 	if_ctx_t ctx = arg;
4692 
4693 	CTX_LOCK(ctx);
4694 	IFDI_LED_FUNC(ctx, onoff);
4695 	CTX_UNLOCK(ctx);
4696 }
4697 
4698 /*********************************************************************
4699  *
4700  *  BUS FUNCTION DEFINITIONS
4701  *
4702  **********************************************************************/
4703 
4704 int
4705 iflib_device_probe(device_t dev)
4706 {
4707 	const pci_vendor_info_t *ent;
4708 	if_shared_ctx_t sctx;
4709 	uint16_t pci_device_id, pci_rev_id, pci_subdevice_id, pci_subvendor_id;
4710 	uint16_t pci_vendor_id;
4711 
4712 	if ((sctx = DEVICE_REGISTER(dev)) == NULL || sctx->isc_magic != IFLIB_MAGIC)
4713 		return (ENOTSUP);
4714 
4715 	pci_vendor_id = pci_get_vendor(dev);
4716 	pci_device_id = pci_get_device(dev);
4717 	pci_subvendor_id = pci_get_subvendor(dev);
4718 	pci_subdevice_id = pci_get_subdevice(dev);
4719 	pci_rev_id = pci_get_revid(dev);
4720 	if (sctx->isc_parse_devinfo != NULL)
4721 		sctx->isc_parse_devinfo(&pci_device_id, &pci_subvendor_id, &pci_subdevice_id, &pci_rev_id);
4722 
4723 	ent = sctx->isc_vendor_info;
4724 	while (ent->pvi_vendor_id != 0) {
4725 		if (pci_vendor_id != ent->pvi_vendor_id) {
4726 			ent++;
4727 			continue;
4728 		}
4729 		if ((pci_device_id == ent->pvi_device_id) &&
4730 		    ((pci_subvendor_id == ent->pvi_subvendor_id) ||
4731 		     (ent->pvi_subvendor_id == 0)) &&
4732 		    ((pci_subdevice_id == ent->pvi_subdevice_id) ||
4733 		     (ent->pvi_subdevice_id == 0)) &&
4734 		    ((pci_rev_id == ent->pvi_rev_id) ||
4735 		     (ent->pvi_rev_id == 0))) {
4736 			device_set_desc_copy(dev, ent->pvi_name);
4737 			/* this needs to be changed to zero if the bus probing code
4738 			 * ever stops re-probing on best match because the sctx
4739 			 * may have its values over written by register calls
4740 			 * in subsequent probes
4741 			 */
4742 			return (BUS_PROBE_DEFAULT);
4743 		}
4744 		ent++;
4745 	}
4746 	return (ENXIO);
4747 }
4748 
4749 int
4750 iflib_device_probe_vendor(device_t dev)
4751 {
4752 	int probe;
4753 
4754 	probe = iflib_device_probe(dev);
4755 	if (probe == BUS_PROBE_DEFAULT)
4756 		return (BUS_PROBE_VENDOR);
4757 	else
4758 		return (probe);
4759 }
4760 
4761 static void
4762 iflib_reset_qvalues(if_ctx_t ctx)
4763 {
4764 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
4765 	if_shared_ctx_t sctx = ctx->ifc_sctx;
4766 	device_t dev = ctx->ifc_dev;
4767 	int i;
4768 
4769 	if (ctx->ifc_sysctl_ntxqs != 0)
4770 		scctx->isc_ntxqsets = ctx->ifc_sysctl_ntxqs;
4771 	if (ctx->ifc_sysctl_nrxqs != 0)
4772 		scctx->isc_nrxqsets = ctx->ifc_sysctl_nrxqs;
4773 
4774 	for (i = 0; i < sctx->isc_ntxqs; i++) {
4775 		if (ctx->ifc_sysctl_ntxds[i] != 0)
4776 			scctx->isc_ntxd[i] = ctx->ifc_sysctl_ntxds[i];
4777 		else
4778 			scctx->isc_ntxd[i] = sctx->isc_ntxd_default[i];
4779 	}
4780 
4781 	for (i = 0; i < sctx->isc_nrxqs; i++) {
4782 		if (ctx->ifc_sysctl_nrxds[i] != 0)
4783 			scctx->isc_nrxd[i] = ctx->ifc_sysctl_nrxds[i];
4784 		else
4785 			scctx->isc_nrxd[i] = sctx->isc_nrxd_default[i];
4786 	}
4787 
4788 	for (i = 0; i < sctx->isc_nrxqs; i++) {
4789 		if (scctx->isc_nrxd[i] < sctx->isc_nrxd_min[i]) {
4790 			device_printf(dev, "nrxd%d: %d less than nrxd_min %d - resetting to min\n",
4791 			    i, scctx->isc_nrxd[i], sctx->isc_nrxd_min[i]);
4792 			scctx->isc_nrxd[i] = sctx->isc_nrxd_min[i];
4793 		}
4794 		if (scctx->isc_nrxd[i] > sctx->isc_nrxd_max[i]) {
4795 			device_printf(dev, "nrxd%d: %d greater than nrxd_max %d - resetting to max\n",
4796 			    i, scctx->isc_nrxd[i], sctx->isc_nrxd_max[i]);
4797 			scctx->isc_nrxd[i] = sctx->isc_nrxd_max[i];
4798 		}
4799 		if (!powerof2(scctx->isc_nrxd[i])) {
4800 			device_printf(dev, "nrxd%d: %d is not a power of 2 - using default value of %d\n",
4801 			    i, scctx->isc_nrxd[i], sctx->isc_nrxd_default[i]);
4802 			scctx->isc_nrxd[i] = sctx->isc_nrxd_default[i];
4803 		}
4804 	}
4805 
4806 	for (i = 0; i < sctx->isc_ntxqs; i++) {
4807 		if (scctx->isc_ntxd[i] < sctx->isc_ntxd_min[i]) {
4808 			device_printf(dev, "ntxd%d: %d less than ntxd_min %d - resetting to min\n",
4809 			    i, scctx->isc_ntxd[i], sctx->isc_ntxd_min[i]);
4810 			scctx->isc_ntxd[i] = sctx->isc_ntxd_min[i];
4811 		}
4812 		if (scctx->isc_ntxd[i] > sctx->isc_ntxd_max[i]) {
4813 			device_printf(dev, "ntxd%d: %d greater than ntxd_max %d - resetting to max\n",
4814 			    i, scctx->isc_ntxd[i], sctx->isc_ntxd_max[i]);
4815 			scctx->isc_ntxd[i] = sctx->isc_ntxd_max[i];
4816 		}
4817 		if (!powerof2(scctx->isc_ntxd[i])) {
4818 			device_printf(dev, "ntxd%d: %d is not a power of 2 - using default value of %d\n",
4819 			    i, scctx->isc_ntxd[i], sctx->isc_ntxd_default[i]);
4820 			scctx->isc_ntxd[i] = sctx->isc_ntxd_default[i];
4821 		}
4822 	}
4823 }
4824 
4825 static void
4826 iflib_add_pfil(if_ctx_t ctx)
4827 {
4828 	struct pfil_head *pfil;
4829 	struct pfil_head_args pa;
4830 	iflib_rxq_t rxq;
4831 	int i;
4832 
4833 	pa.pa_version = PFIL_VERSION;
4834 	pa.pa_flags = PFIL_IN;
4835 	pa.pa_type = PFIL_TYPE_ETHERNET;
4836 	pa.pa_headname = if_name(ctx->ifc_ifp);
4837 	pfil = pfil_head_register(&pa);
4838 
4839 	for (i = 0, rxq = ctx->ifc_rxqs; i < NRXQSETS(ctx); i++, rxq++) {
4840 		rxq->pfil = pfil;
4841 	}
4842 }
4843 
4844 static void
4845 iflib_rem_pfil(if_ctx_t ctx)
4846 {
4847 	struct pfil_head *pfil;
4848 	iflib_rxq_t rxq;
4849 	int i;
4850 
4851 	rxq = ctx->ifc_rxqs;
4852 	pfil = rxq->pfil;
4853 	for (i = 0; i < NRXQSETS(ctx); i++, rxq++) {
4854 		rxq->pfil = NULL;
4855 	}
4856 	pfil_head_unregister(pfil);
4857 }
4858 
4859 
4860 /*
4861  * Advance forward by n members of the cpuset ctx->ifc_cpus starting from
4862  * cpuid and wrapping as necessary.
4863  */
4864 static unsigned int
4865 cpuid_advance(if_ctx_t ctx, unsigned int cpuid, unsigned int n)
4866 {
4867 	unsigned int first_valid;
4868 	unsigned int last_valid;
4869 
4870 	/* cpuid should always be in the valid set */
4871 	MPASS(CPU_ISSET(cpuid, &ctx->ifc_cpus));
4872 
4873 	/* valid set should never be empty */
4874 	MPASS(!CPU_EMPTY(&ctx->ifc_cpus));
4875 
4876 	first_valid = CPU_FFS(&ctx->ifc_cpus) - 1;
4877 	last_valid = CPU_FLS(&ctx->ifc_cpus) - 1;
4878 	n = n % CPU_COUNT(&ctx->ifc_cpus);
4879 	while (n > 0) {
4880 		do {
4881 			cpuid++;
4882 			if (cpuid > last_valid)
4883 				cpuid = first_valid;
4884 		} while (!CPU_ISSET(cpuid, &ctx->ifc_cpus));
4885 		n--;
4886 	}
4887 
4888 	return (cpuid);
4889 }
4890 
4891 #if defined(SMP) && defined(SCHED_ULE)
4892 extern struct cpu_group *cpu_top;	/* CPU topology */
4893 
4894 static int
4895 find_child_with_core(int cpu, struct cpu_group *grp)
4896 {
4897 	int i;
4898 
4899 	if (grp->cg_children == 0)
4900 		return (-1);
4901 
4902 	MPASS(grp->cg_child);
4903 	for (i = 0; i < grp->cg_children; i++) {
4904 		if (CPU_ISSET(cpu, &grp->cg_child[i].cg_mask))
4905 			return (i);
4906 	}
4907 
4908 	return (-1);
4909 }
4910 
4911 
4912 /*
4913  * Find an L2 neighbor of the given CPU or return -1 if none found.  This
4914  * does not distinguish among multiple L2 neighbors if the given CPU has
4915  * more than one (it will always return the same result in that case).
4916  */
4917 static int
4918 find_l2_neighbor(int cpu)
4919 {
4920 	struct cpu_group *grp;
4921 	int i;
4922 
4923 	grp = cpu_top;
4924 	if (grp == NULL)
4925 		return (-1);
4926 
4927 	/*
4928 	 * Find the smallest CPU group that contains the given core.
4929 	 */
4930 	i = 0;
4931 	while ((i = find_child_with_core(cpu, grp)) != -1) {
4932 		/*
4933 		 * If the smallest group containing the given CPU has less
4934 		 * than two members, we conclude the given CPU has no
4935 		 * L2 neighbor.
4936 		 */
4937 		if (grp->cg_child[i].cg_count <= 1)
4938 			return (-1);
4939 		grp = &grp->cg_child[i];
4940 	}
4941 
4942 	/* Must share L2. */
4943 	if (grp->cg_level > CG_SHARE_L2 || grp->cg_level == CG_SHARE_NONE)
4944 		return (-1);
4945 
4946 	/*
4947 	 * Select the first member of the set that isn't the reference
4948 	 * CPU, which at this point is guaranteed to exist.
4949 	 */
4950 	for (i = 0; i < CPU_SETSIZE; i++) {
4951 		if (CPU_ISSET(i, &grp->cg_mask) && i != cpu)
4952 			return (i);
4953 	}
4954 
4955 	/* Should never be reached */
4956 	return (-1);
4957 }
4958 
4959 #else
4960 static int
4961 find_l2_neighbor(int cpu)
4962 {
4963 
4964 	return (-1);
4965 }
4966 #endif
4967 
4968 /*
4969  * CPU mapping behaviors
4970  * ---------------------
4971  * 'separate txrx' refers to the separate_txrx sysctl
4972  * 'use logical' refers to the use_logical_cores sysctl
4973  * 'INTR CPUS' indicates whether bus_get_cpus(INTR_CPUS) succeeded
4974  *
4975  *  separate     use     INTR
4976  *    txrx     logical   CPUS   result
4977  * ---------- --------- ------ ------------------------------------------------
4978  *     -          -       X     RX and TX queues mapped to consecutive physical
4979  *                              cores with RX/TX pairs on same core and excess
4980  *                              of either following
4981  *     -          X       X     RX and TX queues mapped to consecutive cores
4982  *                              of any type with RX/TX pairs on same core and
4983  *                              excess of either following
4984  *     X          -       X     RX and TX queues mapped to consecutive physical
4985  *                              cores; all RX then all TX
4986  *     X          X       X     RX queues mapped to consecutive physical cores
4987  *                              first, then TX queues mapped to L2 neighbor of
4988  *                              the corresponding RX queue if one exists,
4989  *                              otherwise to consecutive physical cores
4990  *     -         n/a      -     RX and TX queues mapped to consecutive cores of
4991  *                              any type with RX/TX pairs on same core and excess
4992  *                              of either following
4993  *     X         n/a      -     RX and TX queues mapped to consecutive cores of
4994  *                              any type; all RX then all TX
4995  */
4996 static unsigned int
4997 get_cpuid_for_queue(if_ctx_t ctx, unsigned int base_cpuid, unsigned int qid,
4998     bool is_tx)
4999 {
5000 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
5001 	unsigned int core_index;
5002 
5003 	if (ctx->ifc_sysctl_separate_txrx) {
5004 		/*
5005 		 * When using separate CPUs for TX and RX, the assignment
5006 		 * will always be of a consecutive CPU out of the set of
5007 		 * context CPUs, except for the specific case where the
5008 		 * context CPUs are phsyical cores, the use of logical cores
5009 		 * has been enabled, the assignment is for TX, the TX qid
5010 		 * corresponds to an RX qid, and the CPU assigned to the
5011 		 * corresponding RX queue has an L2 neighbor.
5012 		 */
5013 		if (ctx->ifc_sysctl_use_logical_cores &&
5014 		    ctx->ifc_cpus_are_physical_cores &&
5015 		    is_tx && qid < scctx->isc_nrxqsets) {
5016 			int l2_neighbor;
5017 			unsigned int rx_cpuid;
5018 
5019 			rx_cpuid = cpuid_advance(ctx, base_cpuid, qid);
5020 			l2_neighbor = find_l2_neighbor(rx_cpuid);
5021 			if (l2_neighbor != -1) {
5022 				return (l2_neighbor);
5023 			}
5024 			/*
5025 			 * ... else fall through to the normal
5026 			 * consecutive-after-RX assignment scheme.
5027 			 *
5028 			 * Note that we are assuming that all RX queue CPUs
5029 			 * have an L2 neighbor, or all do not.  If a mixed
5030 			 * scenario is possible, we will have to keep track
5031 			 * separately of how many queues prior to this one
5032 			 * were not able to be assigned to an L2 neighbor.
5033 			 */
5034 		}
5035 		if (is_tx)
5036 			core_index = scctx->isc_nrxqsets + qid;
5037 		else
5038 			core_index = qid;
5039 	} else {
5040 		core_index = qid;
5041 	}
5042 
5043 	return (cpuid_advance(ctx, base_cpuid, core_index));
5044 }
5045 
5046 static uint16_t
5047 get_ctx_core_offset(if_ctx_t ctx)
5048 {
5049 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
5050 	struct cpu_offset *op;
5051 	cpuset_t assigned_cpus;
5052 	unsigned int cores_consumed;
5053 	unsigned int base_cpuid = ctx->ifc_sysctl_core_offset;
5054 	unsigned int first_valid;
5055 	unsigned int last_valid;
5056 	unsigned int i;
5057 
5058 	first_valid = CPU_FFS(&ctx->ifc_cpus) - 1;
5059 	last_valid = CPU_FLS(&ctx->ifc_cpus) - 1;
5060 
5061 	if (base_cpuid != CORE_OFFSET_UNSPECIFIED) {
5062 		/*
5063 		 * Align the user-chosen base CPU ID to the next valid CPU
5064 		 * for this device.  If the chosen base CPU ID is smaller
5065 		 * than the first valid CPU or larger than the last valid
5066 		 * CPU, we assume the user does not know what the valid
5067 		 * range is for this device and is thinking in terms of a
5068 		 * zero-based reference frame, and so we shift the given
5069 		 * value into the valid range (and wrap accordingly) so the
5070 		 * intent is translated to the proper frame of reference.
5071 		 * If the base CPU ID is within the valid first/last, but
5072 		 * does not correspond to a valid CPU, it is advanced to the
5073 		 * next valid CPU (wrapping if necessary).
5074 		 */
5075 		if (base_cpuid < first_valid || base_cpuid > last_valid) {
5076 			/* shift from zero-based to first_valid-based */
5077 			base_cpuid += first_valid;
5078 			/* wrap to range [first_valid, last_valid] */
5079 			base_cpuid = (base_cpuid - first_valid) %
5080 			    (last_valid - first_valid + 1);
5081 		}
5082 		if (!CPU_ISSET(base_cpuid, &ctx->ifc_cpus)) {
5083 			/*
5084 			 * base_cpuid is in [first_valid, last_valid], but
5085 			 * not a member of the valid set.  In this case,
5086 			 * there will always be a member of the valid set
5087 			 * with a CPU ID that is greater than base_cpuid,
5088 			 * and we simply advance to it.
5089 			 */
5090 			while (!CPU_ISSET(base_cpuid, &ctx->ifc_cpus))
5091 				base_cpuid++;
5092 		}
5093 		return (base_cpuid);
5094 	}
5095 
5096 	/*
5097 	 * Determine how many cores will be consumed by performing the CPU
5098 	 * assignments and counting how many of the assigned CPUs correspond
5099 	 * to CPUs in the set of context CPUs.  This is done using the CPU
5100 	 * ID first_valid as the base CPU ID, as the base CPU must be within
5101 	 * the set of context CPUs.
5102 	 *
5103 	 * Note not all assigned CPUs will be in the set of context CPUs
5104 	 * when separate CPUs are being allocated to TX and RX queues,
5105 	 * assignment to logical cores has been enabled, the set of context
5106 	 * CPUs contains only physical CPUs, and TX queues are mapped to L2
5107 	 * neighbors of CPUs that RX queues have been mapped to - in this
5108 	 * case we do only want to count how many CPUs in the set of context
5109 	 * CPUs have been consumed, as that determines the next CPU in that
5110 	 * set to start allocating at for the next device for which
5111 	 * core_offset is not set.
5112 	 */
5113 	CPU_ZERO(&assigned_cpus);
5114 	for (i = 0; i < scctx->isc_ntxqsets; i++)
5115 		CPU_SET(get_cpuid_for_queue(ctx, first_valid, i, true),
5116 		    &assigned_cpus);
5117 	for (i = 0; i < scctx->isc_nrxqsets; i++)
5118 		CPU_SET(get_cpuid_for_queue(ctx, first_valid, i, false),
5119 		    &assigned_cpus);
5120 	CPU_AND(&assigned_cpus, &assigned_cpus, &ctx->ifc_cpus);
5121 	cores_consumed = CPU_COUNT(&assigned_cpus);
5122 
5123 	mtx_lock(&cpu_offset_mtx);
5124 	SLIST_FOREACH(op, &cpu_offsets, entries) {
5125 		if (CPU_CMP(&ctx->ifc_cpus, &op->set) == 0) {
5126 			base_cpuid = op->next_cpuid;
5127 			op->next_cpuid = cpuid_advance(ctx, op->next_cpuid,
5128 			    cores_consumed);
5129 			MPASS(op->refcount < UINT_MAX);
5130 			op->refcount++;
5131 			break;
5132 		}
5133 	}
5134 	if (base_cpuid == CORE_OFFSET_UNSPECIFIED) {
5135 		base_cpuid = first_valid;
5136 		op = malloc(sizeof(struct cpu_offset), M_IFLIB,
5137 		    M_NOWAIT | M_ZERO);
5138 		if (op == NULL) {
5139 			device_printf(ctx->ifc_dev,
5140 			    "allocation for cpu offset failed.\n");
5141 		} else {
5142 			op->next_cpuid = cpuid_advance(ctx, base_cpuid,
5143 			    cores_consumed);
5144 			op->refcount = 1;
5145 			CPU_COPY(&ctx->ifc_cpus, &op->set);
5146 			SLIST_INSERT_HEAD(&cpu_offsets, op, entries);
5147 		}
5148 	}
5149 	mtx_unlock(&cpu_offset_mtx);
5150 
5151 	return (base_cpuid);
5152 }
5153 
5154 static void
5155 unref_ctx_core_offset(if_ctx_t ctx)
5156 {
5157 	struct cpu_offset *op, *top;
5158 
5159 	mtx_lock(&cpu_offset_mtx);
5160 	SLIST_FOREACH_SAFE(op, &cpu_offsets, entries, top) {
5161 		if (CPU_CMP(&ctx->ifc_cpus, &op->set) == 0) {
5162 			MPASS(op->refcount > 0);
5163 			op->refcount--;
5164 			if (op->refcount == 0) {
5165 				SLIST_REMOVE(&cpu_offsets, op, cpu_offset, entries);
5166 				free(op, M_IFLIB);
5167 			}
5168 			break;
5169 		}
5170 	}
5171 	mtx_unlock(&cpu_offset_mtx);
5172 }
5173 
5174 int
5175 iflib_device_register(device_t dev, void *sc, if_shared_ctx_t sctx, if_ctx_t *ctxp)
5176 {
5177 	if_ctx_t ctx;
5178 	if_t ifp;
5179 	if_softc_ctx_t scctx;
5180 	kobjop_desc_t kobj_desc;
5181 	kobj_method_t *kobj_method;
5182 	int err, msix, rid;
5183 	int num_txd, num_rxd;
5184 	char namebuf[TASKQUEUE_NAMELEN];
5185 
5186 	ctx = malloc(sizeof(*ctx), M_IFLIB, M_WAITOK | M_ZERO);
5187 
5188 	if (sc == NULL) {
5189 		sc = malloc(sctx->isc_driver->size, M_IFLIB, M_WAITOK | M_ZERO);
5190 		device_set_softc(dev, ctx);
5191 		ctx->ifc_flags |= IFC_SC_ALLOCATED;
5192 	}
5193 
5194 	ctx->ifc_sctx = sctx;
5195 	ctx->ifc_dev = dev;
5196 	ctx->ifc_softc = sc;
5197 
5198 	if ((err = iflib_register(ctx)) != 0) {
5199 		device_printf(dev, "iflib_register failed %d\n", err);
5200 		goto fail_ctx_free;
5201 	}
5202 	iflib_add_device_sysctl_pre(ctx);
5203 
5204 	scctx = &ctx->ifc_softc_ctx;
5205 	ifp = ctx->ifc_ifp;
5206 
5207 	iflib_reset_qvalues(ctx);
5208 	IFNET_WLOCK();
5209 	CTX_LOCK(ctx);
5210 	if ((err = IFDI_ATTACH_PRE(ctx)) != 0) {
5211 		device_printf(dev, "IFDI_ATTACH_PRE failed %d\n", err);
5212 		goto fail_unlock;
5213 	}
5214 	_iflib_pre_assert(scctx);
5215 	ctx->ifc_txrx = *scctx->isc_txrx;
5216 
5217 	MPASS(scctx->isc_dma_width <= flsll(BUS_SPACE_MAXADDR));
5218 
5219 	if (sctx->isc_flags & IFLIB_DRIVER_MEDIA)
5220 		ctx->ifc_mediap = scctx->isc_media;
5221 
5222 #ifdef INVARIANTS
5223 	if (scctx->isc_capabilities & IFCAP_TXCSUM)
5224 		MPASS(scctx->isc_tx_csum_flags);
5225 #endif
5226 
5227 	if_setcapabilities(ifp,
5228 	    scctx->isc_capabilities | IFCAP_HWSTATS | IFCAP_MEXTPG);
5229 	if_setcapenable(ifp,
5230 	    scctx->isc_capenable | IFCAP_HWSTATS | IFCAP_MEXTPG);
5231 
5232 	if (scctx->isc_ntxqsets == 0 || (scctx->isc_ntxqsets_max && scctx->isc_ntxqsets_max < scctx->isc_ntxqsets))
5233 		scctx->isc_ntxqsets = scctx->isc_ntxqsets_max;
5234 	if (scctx->isc_nrxqsets == 0 || (scctx->isc_nrxqsets_max && scctx->isc_nrxqsets_max < scctx->isc_nrxqsets))
5235 		scctx->isc_nrxqsets = scctx->isc_nrxqsets_max;
5236 
5237 	num_txd = iflib_num_tx_descs(ctx);
5238 	num_rxd = iflib_num_rx_descs(ctx);
5239 
5240 	/* XXX change for per-queue sizes */
5241 	device_printf(dev, "Using %d TX descriptors and %d RX descriptors\n",
5242 	    num_txd, num_rxd);
5243 
5244 	if (scctx->isc_tx_nsegments > num_txd / MAX_SINGLE_PACKET_FRACTION)
5245 		scctx->isc_tx_nsegments = max(1, num_txd /
5246 		    MAX_SINGLE_PACKET_FRACTION);
5247 	if (scctx->isc_tx_tso_segments_max > num_txd /
5248 	    MAX_SINGLE_PACKET_FRACTION)
5249 		scctx->isc_tx_tso_segments_max = max(1,
5250 		    num_txd / MAX_SINGLE_PACKET_FRACTION);
5251 
5252 	/* TSO parameters - dig these out of the data sheet - simply correspond to tag setup */
5253 	if (if_getcapabilities(ifp) & IFCAP_TSO) {
5254 		/*
5255 		 * The stack can't handle a TSO size larger than IP_MAXPACKET,
5256 		 * but some MACs do.
5257 		 */
5258 		if_sethwtsomax(ifp, min(scctx->isc_tx_tso_size_max,
5259 		    IP_MAXPACKET));
5260 		/*
5261 		 * Take maximum number of m_pullup(9)'s in iflib_parse_header()
5262 		 * into account.  In the worst case, each of these calls will
5263 		 * add another mbuf and, thus, the requirement for another DMA
5264 		 * segment.  So for best performance, it doesn't make sense to
5265 		 * advertize a maximum of TSO segments that typically will
5266 		 * require defragmentation in iflib_encap().
5267 		 */
5268 		if_sethwtsomaxsegcount(ifp, scctx->isc_tx_tso_segments_max - 3);
5269 		if_sethwtsomaxsegsize(ifp, scctx->isc_tx_tso_segsize_max);
5270 	}
5271 	if (scctx->isc_rss_table_size == 0)
5272 		scctx->isc_rss_table_size = 64;
5273 	scctx->isc_rss_table_mask = scctx->isc_rss_table_size - 1;
5274 
5275 	/* Create and start admin taskqueue */
5276 	snprintf(namebuf, TASKQUEUE_NAMELEN, "if_%s_tq", device_get_nameunit(dev));
5277 	ctx->ifc_tq = taskqueue_create_fast(namebuf, M_NOWAIT,
5278 	    taskqueue_thread_enqueue, &ctx->ifc_tq);
5279 	if (ctx->ifc_tq == NULL) {
5280 		device_printf(dev, "Unable to create admin taskqueue\n");
5281 		return (ENOMEM);
5282 	}
5283 
5284 	err = taskqueue_start_threads(&ctx->ifc_tq, 1, PI_NET, "%s", namebuf);
5285 	if (err) {
5286 		device_printf(dev,
5287 		    "Unable to start admin taskqueue threads error: %d\n",
5288 		    err);
5289 		taskqueue_free(ctx->ifc_tq);
5290 		return (err);
5291 	}
5292 
5293 	TASK_INIT(&ctx->ifc_admin_task, 0, _task_fn_admin, ctx);
5294 
5295 	/* Set up cpu set.  If it fails, use the set of all CPUs. */
5296 	if (bus_get_cpus(dev, INTR_CPUS, sizeof(ctx->ifc_cpus), &ctx->ifc_cpus) != 0) {
5297 		device_printf(dev, "Unable to fetch CPU list\n");
5298 		CPU_COPY(&all_cpus, &ctx->ifc_cpus);
5299 		ctx->ifc_cpus_are_physical_cores = false;
5300 	} else
5301 		ctx->ifc_cpus_are_physical_cores = true;
5302 	MPASS(CPU_COUNT(&ctx->ifc_cpus) > 0);
5303 
5304 	/*
5305 	 * Now set up MSI or MSI-X, should return us the number of supported
5306 	 * vectors (will be 1 for a legacy interrupt and MSI).
5307 	 */
5308 	if (sctx->isc_flags & IFLIB_SKIP_MSIX) {
5309 		msix = scctx->isc_vectors;
5310 	} else if (scctx->isc_msix_bar != 0)
5311 		/*
5312 		 * The simple fact that isc_msix_bar is not 0 does not mean we
5313 		 * we have a good value there that is known to work.
5314 		 */
5315 		msix = iflib_msix_init(ctx);
5316 	else {
5317 		scctx->isc_vectors = 1;
5318 		scctx->isc_ntxqsets = 1;
5319 		scctx->isc_nrxqsets = 1;
5320 		scctx->isc_intr = IFLIB_INTR_LEGACY;
5321 		msix = 0;
5322 	}
5323 	/* Get memory for the station queues */
5324 	if ((err = iflib_queues_alloc(ctx))) {
5325 		device_printf(dev, "Unable to allocate queue memory\n");
5326 		goto fail_intr_free;
5327 	}
5328 
5329 	if ((err = iflib_qset_structures_setup(ctx)))
5330 		goto fail_queues;
5331 
5332 	/*
5333 	 * Now that we know how many queues there are, get the core offset.
5334 	 */
5335 	ctx->ifc_sysctl_core_offset = get_ctx_core_offset(ctx);
5336 
5337 	if (msix > 1) {
5338 		/*
5339 		 * When using MSI-X, ensure that ifdi_{r,t}x_queue_intr_enable
5340 		 * aren't the default NULL implementation.
5341 		 */
5342 		kobj_desc = &ifdi_rx_queue_intr_enable_desc;
5343 		kobj_method = kobj_lookup_method(((kobj_t)ctx)->ops->cls, NULL,
5344 		    kobj_desc);
5345 		if (kobj_method == &kobj_desc->deflt) {
5346 			device_printf(dev,
5347 			    "MSI-X requires ifdi_rx_queue_intr_enable method");
5348 			err = EOPNOTSUPP;
5349 			goto fail_queues;
5350 		}
5351 		kobj_desc = &ifdi_tx_queue_intr_enable_desc;
5352 		kobj_method = kobj_lookup_method(((kobj_t)ctx)->ops->cls, NULL,
5353 		    kobj_desc);
5354 		if (kobj_method == &kobj_desc->deflt) {
5355 			device_printf(dev,
5356 			    "MSI-X requires ifdi_tx_queue_intr_enable method");
5357 			err = EOPNOTSUPP;
5358 			goto fail_queues;
5359 		}
5360 
5361 		/*
5362 		 * Assign the MSI-X vectors.
5363 		 * Note that the default NULL ifdi_msix_intr_assign method will
5364 		 * fail here, too.
5365 		 */
5366 		err = IFDI_MSIX_INTR_ASSIGN(ctx, msix);
5367 		if (err != 0) {
5368 			device_printf(dev, "IFDI_MSIX_INTR_ASSIGN failed %d\n",
5369 			    err);
5370 			goto fail_queues;
5371 		}
5372 	} else if (scctx->isc_intr != IFLIB_INTR_MSIX) {
5373 		rid = 0;
5374 		if (scctx->isc_intr == IFLIB_INTR_MSI) {
5375 			MPASS(msix == 1);
5376 			rid = 1;
5377 		}
5378 		if ((err = iflib_legacy_setup(ctx, ctx->isc_legacy_intr, ctx->ifc_softc, &rid, "irq0")) != 0) {
5379 			device_printf(dev, "iflib_legacy_setup failed %d\n", err);
5380 			goto fail_queues;
5381 		}
5382 	} else {
5383 		device_printf(dev,
5384 		    "Cannot use iflib with only 1 MSI-X interrupt!\n");
5385 		err = ENODEV;
5386 		goto fail_queues;
5387 	}
5388 
5389 	/*
5390 	 * It prevents a double-locking panic with iflib_media_status when
5391 	 * the driver loads.
5392 	 */
5393 	CTX_UNLOCK(ctx);
5394 	ether_ifattach(ctx->ifc_ifp, ctx->ifc_mac.octet);
5395 	CTX_LOCK(ctx);
5396 
5397 	if ((err = IFDI_ATTACH_POST(ctx)) != 0) {
5398 		device_printf(dev, "IFDI_ATTACH_POST failed %d\n", err);
5399 		goto fail_detach;
5400 	}
5401 
5402 	/*
5403 	 * Tell the upper layer(s) if IFCAP_VLAN_MTU is supported.
5404 	 * This must appear after the call to ether_ifattach() because
5405 	 * ether_ifattach() sets if_hdrlen to the default value.
5406 	 */
5407 	if (if_getcapabilities(ifp) & IFCAP_VLAN_MTU)
5408 		if_setifheaderlen(ifp, sizeof(struct ether_vlan_header));
5409 
5410 	if ((err = iflib_netmap_attach(ctx))) {
5411 		device_printf(ctx->ifc_dev, "netmap attach failed: %d\n", err);
5412 		goto fail_detach;
5413 	}
5414 	*ctxp = ctx;
5415 
5416 	DEBUGNET_SET(ctx->ifc_ifp, iflib);
5417 
5418 	if_setgetcounterfn(ctx->ifc_ifp, iflib_if_get_counter);
5419 	iflib_add_device_sysctl_post(ctx);
5420 	iflib_add_pfil(ctx);
5421 	ctx->ifc_flags |= IFC_INIT_DONE;
5422 	CTX_UNLOCK(ctx);
5423 	IFNET_WUNLOCK();
5424 
5425 	return (0);
5426 
5427 fail_detach:
5428 	ether_ifdetach(ctx->ifc_ifp);
5429 fail_queues:
5430 	taskqueue_free(ctx->ifc_tq);
5431 	iflib_tqg_detach(ctx);
5432 	iflib_tx_structures_free(ctx);
5433 	iflib_rx_structures_free(ctx);
5434 	IFDI_DETACH(ctx);
5435 	IFDI_QUEUES_FREE(ctx);
5436 fail_intr_free:
5437 	iflib_free_intr_mem(ctx);
5438 fail_unlock:
5439 	CTX_UNLOCK(ctx);
5440 	IFNET_WUNLOCK();
5441 	iflib_deregister(ctx);
5442 fail_ctx_free:
5443 	device_set_softc(ctx->ifc_dev, NULL);
5444 	if (ctx->ifc_flags & IFC_SC_ALLOCATED)
5445 		free(ctx->ifc_softc, M_IFLIB);
5446 	free(ctx, M_IFLIB);
5447 	return (err);
5448 }
5449 
5450 int
5451 iflib_device_attach(device_t dev)
5452 {
5453 	if_ctx_t ctx;
5454 	if_shared_ctx_t sctx;
5455 
5456 	if ((sctx = DEVICE_REGISTER(dev)) == NULL || sctx->isc_magic != IFLIB_MAGIC)
5457 		return (ENOTSUP);
5458 
5459 	pci_enable_busmaster(dev);
5460 
5461 	return (iflib_device_register(dev, NULL, sctx, &ctx));
5462 }
5463 
5464 int
5465 iflib_device_deregister(if_ctx_t ctx)
5466 {
5467 	if_t ifp = ctx->ifc_ifp;
5468 	device_t dev = ctx->ifc_dev;
5469 
5470 	/* Make sure VLANS are not using driver */
5471 	if (if_vlantrunkinuse(ifp)) {
5472 		device_printf(dev, "Vlan in use, detach first\n");
5473 		return (EBUSY);
5474 	}
5475 #ifdef PCI_IOV
5476 	if (!CTX_IS_VF(ctx) && pci_iov_detach(dev) != 0) {
5477 		device_printf(dev, "SR-IOV in use; detach first.\n");
5478 		return (EBUSY);
5479 	}
5480 #endif
5481 
5482 	STATE_LOCK(ctx);
5483 	ctx->ifc_flags |= IFC_IN_DETACH;
5484 	STATE_UNLOCK(ctx);
5485 
5486 	/* Unregister VLAN handlers before calling iflib_stop() */
5487 	iflib_unregister_vlan_handlers(ctx);
5488 
5489 	iflib_netmap_detach(ifp);
5490 	ether_ifdetach(ifp);
5491 
5492 	CTX_LOCK(ctx);
5493 	iflib_stop(ctx);
5494 	CTX_UNLOCK(ctx);
5495 
5496 	iflib_rem_pfil(ctx);
5497 	if (ctx->ifc_led_dev != NULL)
5498 		led_destroy(ctx->ifc_led_dev);
5499 
5500 	iflib_tqg_detach(ctx);
5501 	iflib_tx_structures_free(ctx);
5502 	iflib_rx_structures_free(ctx);
5503 
5504 	CTX_LOCK(ctx);
5505 	IFDI_DETACH(ctx);
5506 	IFDI_QUEUES_FREE(ctx);
5507 	CTX_UNLOCK(ctx);
5508 
5509 	taskqueue_free(ctx->ifc_tq);
5510 	ctx->ifc_tq = NULL;
5511 
5512 	/* ether_ifdetach calls if_qflush - lock must be destroy afterwards*/
5513 	iflib_free_intr_mem(ctx);
5514 
5515 	bus_generic_detach(dev);
5516 
5517 	iflib_deregister(ctx);
5518 
5519 	device_set_softc(ctx->ifc_dev, NULL);
5520 	if (ctx->ifc_flags & IFC_SC_ALLOCATED)
5521 		free(ctx->ifc_softc, M_IFLIB);
5522 	unref_ctx_core_offset(ctx);
5523 	free(ctx, M_IFLIB);
5524 	return (0);
5525 }
5526 
5527 static void
5528 iflib_tqg_detach(if_ctx_t ctx)
5529 {
5530 	iflib_txq_t txq;
5531 	iflib_rxq_t rxq;
5532 	int i;
5533 	struct taskqgroup *tqg;
5534 
5535 	/* XXX drain any dependent tasks */
5536 	tqg = qgroup_if_io_tqg;
5537 	for (txq = ctx->ifc_txqs, i = 0; i < NTXQSETS(ctx); i++, txq++) {
5538 		callout_drain(&txq->ift_timer);
5539 #ifdef DEV_NETMAP
5540 		callout_drain(&txq->ift_netmap_timer);
5541 #endif /* DEV_NETMAP */
5542 		if (txq->ift_task.gt_uniq != NULL)
5543 			taskqgroup_detach(tqg, &txq->ift_task);
5544 	}
5545 	for (i = 0, rxq = ctx->ifc_rxqs; i < NRXQSETS(ctx); i++, rxq++) {
5546 		if (rxq->ifr_task.gt_uniq != NULL)
5547 			taskqgroup_detach(tqg, &rxq->ifr_task);
5548 	}
5549 }
5550 
5551 static void
5552 iflib_free_intr_mem(if_ctx_t ctx)
5553 {
5554 
5555 	if (ctx->ifc_softc_ctx.isc_intr != IFLIB_INTR_MSIX) {
5556 		iflib_irq_free(ctx, &ctx->ifc_legacy_irq);
5557 	}
5558 	if (ctx->ifc_softc_ctx.isc_intr != IFLIB_INTR_LEGACY) {
5559 		pci_release_msi(ctx->ifc_dev);
5560 	}
5561 	if (ctx->ifc_msix_mem != NULL) {
5562 		bus_release_resource(ctx->ifc_dev, SYS_RES_MEMORY,
5563 		    rman_get_rid(ctx->ifc_msix_mem), ctx->ifc_msix_mem);
5564 		ctx->ifc_msix_mem = NULL;
5565 	}
5566 }
5567 
5568 int
5569 iflib_device_detach(device_t dev)
5570 {
5571 	if_ctx_t ctx = device_get_softc(dev);
5572 
5573 	return (iflib_device_deregister(ctx));
5574 }
5575 
5576 int
5577 iflib_device_suspend(device_t dev)
5578 {
5579 	if_ctx_t ctx = device_get_softc(dev);
5580 
5581 	CTX_LOCK(ctx);
5582 	IFDI_SUSPEND(ctx);
5583 	CTX_UNLOCK(ctx);
5584 
5585 	return (bus_generic_suspend(dev));
5586 }
5587 int
5588 iflib_device_shutdown(device_t dev)
5589 {
5590 	if_ctx_t ctx = device_get_softc(dev);
5591 
5592 	CTX_LOCK(ctx);
5593 	IFDI_SHUTDOWN(ctx);
5594 	CTX_UNLOCK(ctx);
5595 
5596 	return (bus_generic_suspend(dev));
5597 }
5598 
5599 int
5600 iflib_device_resume(device_t dev)
5601 {
5602 	if_ctx_t ctx = device_get_softc(dev);
5603 	iflib_txq_t txq = ctx->ifc_txqs;
5604 
5605 	CTX_LOCK(ctx);
5606 	IFDI_RESUME(ctx);
5607 	iflib_if_init_locked(ctx);
5608 	CTX_UNLOCK(ctx);
5609 	for (int i = 0; i < NTXQSETS(ctx); i++, txq++)
5610 		iflib_txq_check_drain(txq, IFLIB_RESTART_BUDGET);
5611 
5612 	return (bus_generic_resume(dev));
5613 }
5614 
5615 int
5616 iflib_device_iov_init(device_t dev, uint16_t num_vfs, const nvlist_t *params)
5617 {
5618 	int error;
5619 	if_ctx_t ctx = device_get_softc(dev);
5620 
5621 	CTX_LOCK(ctx);
5622 	error = IFDI_IOV_INIT(ctx, num_vfs, params);
5623 	CTX_UNLOCK(ctx);
5624 
5625 	return (error);
5626 }
5627 
5628 void
5629 iflib_device_iov_uninit(device_t dev)
5630 {
5631 	if_ctx_t ctx = device_get_softc(dev);
5632 
5633 	CTX_LOCK(ctx);
5634 	IFDI_IOV_UNINIT(ctx);
5635 	CTX_UNLOCK(ctx);
5636 }
5637 
5638 int
5639 iflib_device_iov_add_vf(device_t dev, uint16_t vfnum, const nvlist_t *params)
5640 {
5641 	int error;
5642 	if_ctx_t ctx = device_get_softc(dev);
5643 
5644 	CTX_LOCK(ctx);
5645 	error = IFDI_IOV_VF_ADD(ctx, vfnum, params);
5646 	CTX_UNLOCK(ctx);
5647 
5648 	return (error);
5649 }
5650 
5651 /*********************************************************************
5652  *
5653  *  MODULE FUNCTION DEFINITIONS
5654  *
5655  **********************************************************************/
5656 
5657 /*
5658  * - Start a fast taskqueue thread for each core
5659  * - Start a taskqueue for control operations
5660  */
5661 static int
5662 iflib_module_init(void)
5663 {
5664 	iflib_timer_default = hz / 2;
5665 	return (0);
5666 }
5667 
5668 static int
5669 iflib_module_event_handler(module_t mod, int what, void *arg)
5670 {
5671 	int err;
5672 
5673 	switch (what) {
5674 	case MOD_LOAD:
5675 		if ((err = iflib_module_init()) != 0)
5676 			return (err);
5677 		break;
5678 	case MOD_UNLOAD:
5679 		return (EBUSY);
5680 	default:
5681 		return (EOPNOTSUPP);
5682 	}
5683 
5684 	return (0);
5685 }
5686 
5687 /*********************************************************************
5688  *
5689  *  PUBLIC FUNCTION DEFINITIONS
5690  *     ordered as in iflib.h
5691  *
5692  **********************************************************************/
5693 
5694 static void
5695 _iflib_assert(if_shared_ctx_t sctx)
5696 {
5697 	int i;
5698 
5699 	MPASS(sctx->isc_tx_maxsize);
5700 	MPASS(sctx->isc_tx_maxsegsize);
5701 
5702 	MPASS(sctx->isc_rx_maxsize);
5703 	MPASS(sctx->isc_rx_nsegments);
5704 	MPASS(sctx->isc_rx_maxsegsize);
5705 
5706 	MPASS(sctx->isc_nrxqs >= 1 && sctx->isc_nrxqs <= 8);
5707 	for (i = 0; i < sctx->isc_nrxqs; i++) {
5708 		MPASS(sctx->isc_nrxd_min[i]);
5709 		MPASS(powerof2(sctx->isc_nrxd_min[i]));
5710 		MPASS(sctx->isc_nrxd_max[i]);
5711 		MPASS(powerof2(sctx->isc_nrxd_max[i]));
5712 		MPASS(sctx->isc_nrxd_default[i]);
5713 		MPASS(powerof2(sctx->isc_nrxd_default[i]));
5714 	}
5715 
5716 	MPASS(sctx->isc_ntxqs >= 1 && sctx->isc_ntxqs <= 8);
5717 	for (i = 0; i < sctx->isc_ntxqs; i++) {
5718 		MPASS(sctx->isc_ntxd_min[i]);
5719 		MPASS(powerof2(sctx->isc_ntxd_min[i]));
5720 		MPASS(sctx->isc_ntxd_max[i]);
5721 		MPASS(powerof2(sctx->isc_ntxd_max[i]));
5722 		MPASS(sctx->isc_ntxd_default[i]);
5723 		MPASS(powerof2(sctx->isc_ntxd_default[i]));
5724 	}
5725 }
5726 
5727 static void
5728 _iflib_pre_assert(if_softc_ctx_t scctx)
5729 {
5730 
5731 	MPASS(scctx->isc_txrx->ift_txd_encap);
5732 	MPASS(scctx->isc_txrx->ift_txd_flush);
5733 	MPASS(scctx->isc_txrx->ift_txd_credits_update);
5734 	MPASS(scctx->isc_txrx->ift_rxd_available);
5735 	MPASS(scctx->isc_txrx->ift_rxd_pkt_get);
5736 	MPASS(scctx->isc_txrx->ift_rxd_refill);
5737 	MPASS(scctx->isc_txrx->ift_rxd_flush);
5738 }
5739 
5740 static int
5741 iflib_register(if_ctx_t ctx)
5742 {
5743 	if_shared_ctx_t sctx = ctx->ifc_sctx;
5744 	driver_t *driver = sctx->isc_driver;
5745 	device_t dev = ctx->ifc_dev;
5746 	if_t ifp;
5747 
5748 	_iflib_assert(sctx);
5749 
5750 	CTX_LOCK_INIT(ctx);
5751 	STATE_LOCK_INIT(ctx, device_get_nameunit(ctx->ifc_dev));
5752 	ifp = ctx->ifc_ifp = if_alloc_dev(IFT_ETHER, dev);
5753 
5754 	/*
5755 	 * Initialize our context's device specific methods
5756 	 */
5757 	kobj_init((kobj_t) ctx, (kobj_class_t) driver);
5758 	kobj_class_compile((kobj_class_t) driver);
5759 
5760 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
5761 	if_setsoftc(ifp, ctx);
5762 	if_setdev(ifp, dev);
5763 	if_setinitfn(ifp, iflib_if_init);
5764 	if_setioctlfn(ifp, iflib_if_ioctl);
5765 #ifdef ALTQ
5766 	if_setstartfn(ifp, iflib_altq_if_start);
5767 	if_settransmitfn(ifp, iflib_altq_if_transmit);
5768 	if_setsendqready(ifp);
5769 #else
5770 	if_settransmitfn(ifp, iflib_if_transmit);
5771 #endif
5772 	if_setqflushfn(ifp, iflib_if_qflush);
5773 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
5774 	ctx->ifc_vlan_attach_event =
5775 	    EVENTHANDLER_REGISTER(vlan_config, iflib_vlan_register, ctx,
5776 		    EVENTHANDLER_PRI_FIRST);
5777 	ctx->ifc_vlan_detach_event =
5778 	    EVENTHANDLER_REGISTER(vlan_unconfig, iflib_vlan_unregister, ctx,
5779 		    EVENTHANDLER_PRI_FIRST);
5780 
5781 	if ((sctx->isc_flags & IFLIB_DRIVER_MEDIA) == 0) {
5782 		ctx->ifc_mediap = &ctx->ifc_media;
5783 		ifmedia_init(ctx->ifc_mediap, IFM_IMASK,
5784 		    iflib_media_change, iflib_media_status);
5785 	}
5786 	return (0);
5787 }
5788 
5789 static void
5790 iflib_unregister_vlan_handlers(if_ctx_t ctx)
5791 {
5792 	/* Unregister VLAN events */
5793 	if (ctx->ifc_vlan_attach_event != NULL) {
5794 		EVENTHANDLER_DEREGISTER(vlan_config, ctx->ifc_vlan_attach_event);
5795 		ctx->ifc_vlan_attach_event = NULL;
5796 	}
5797 	if (ctx->ifc_vlan_detach_event != NULL) {
5798 		EVENTHANDLER_DEREGISTER(vlan_unconfig, ctx->ifc_vlan_detach_event);
5799 		ctx->ifc_vlan_detach_event = NULL;
5800 	}
5801 
5802 }
5803 
5804 static void
5805 iflib_deregister(if_ctx_t ctx)
5806 {
5807 	if_t ifp = ctx->ifc_ifp;
5808 
5809 	/* Remove all media */
5810 	ifmedia_removeall(&ctx->ifc_media);
5811 
5812 	/* Ensure that VLAN event handlers are unregistered */
5813 	iflib_unregister_vlan_handlers(ctx);
5814 
5815 	/* Release kobject reference */
5816 	kobj_delete((kobj_t) ctx, NULL);
5817 
5818 	/* Free the ifnet structure */
5819 	if_free(ifp);
5820 
5821 	STATE_LOCK_DESTROY(ctx);
5822 
5823 	/* ether_ifdetach calls if_qflush - lock must be destroy afterwards*/
5824 	CTX_LOCK_DESTROY(ctx);
5825 }
5826 
5827 static int
5828 iflib_queues_alloc(if_ctx_t ctx)
5829 {
5830 	if_shared_ctx_t sctx = ctx->ifc_sctx;
5831 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
5832 	device_t dev = ctx->ifc_dev;
5833 	int nrxqsets = scctx->isc_nrxqsets;
5834 	int ntxqsets = scctx->isc_ntxqsets;
5835 	iflib_txq_t txq;
5836 	iflib_rxq_t rxq;
5837 	iflib_fl_t fl = NULL;
5838 	int i, j, cpu, err, txconf, rxconf;
5839 	iflib_dma_info_t ifdip;
5840 	uint32_t *rxqsizes = scctx->isc_rxqsizes;
5841 	uint32_t *txqsizes = scctx->isc_txqsizes;
5842 	uint8_t nrxqs = sctx->isc_nrxqs;
5843 	uint8_t ntxqs = sctx->isc_ntxqs;
5844 	int nfree_lists = sctx->isc_nfl ? sctx->isc_nfl : 1;
5845 	int fl_offset = (sctx->isc_flags & IFLIB_HAS_RXCQ ? 1 : 0);
5846 	caddr_t *vaddrs;
5847 	uint64_t *paddrs;
5848 
5849 	KASSERT(ntxqs > 0, ("number of queues per qset must be at least 1"));
5850 	KASSERT(nrxqs > 0, ("number of queues per qset must be at least 1"));
5851 	KASSERT(nrxqs >= fl_offset + nfree_lists,
5852 	    ("there must be at least a rxq for each free list"));
5853 
5854 	/* Allocate the TX ring struct memory */
5855 	if (!(ctx->ifc_txqs =
5856 	    (iflib_txq_t) malloc(sizeof(struct iflib_txq) *
5857 		    ntxqsets, M_IFLIB, M_NOWAIT | M_ZERO))) {
5858 		device_printf(dev, "Unable to allocate TX ring memory\n");
5859 		err = ENOMEM;
5860 		goto fail;
5861 	}
5862 
5863 	/* Now allocate the RX */
5864 	if (!(ctx->ifc_rxqs =
5865 	    (iflib_rxq_t) malloc(sizeof(struct iflib_rxq) *
5866 		    nrxqsets, M_IFLIB, M_NOWAIT | M_ZERO))) {
5867 		device_printf(dev, "Unable to allocate RX ring memory\n");
5868 		err = ENOMEM;
5869 		goto rx_fail;
5870 	}
5871 
5872 	txq = ctx->ifc_txqs;
5873 	rxq = ctx->ifc_rxqs;
5874 
5875 	/*
5876 	 * XXX handle allocation failure
5877 	 */
5878 	for (txconf = i = 0, cpu = CPU_FIRST(); i < ntxqsets; i++, txconf++, txq++, cpu = CPU_NEXT(cpu)) {
5879 		/* Set up some basics */
5880 
5881 		if ((ifdip = malloc(sizeof(struct iflib_dma_info) * ntxqs,
5882 		    M_IFLIB, M_NOWAIT | M_ZERO)) == NULL) {
5883 			device_printf(dev,
5884 			    "Unable to allocate TX DMA info memory\n");
5885 			err = ENOMEM;
5886 			goto err_tx_desc;
5887 		}
5888 		txq->ift_ifdi = ifdip;
5889 		for (j = 0; j < ntxqs; j++, ifdip++) {
5890 			if (iflib_dma_alloc(ctx, txqsizes[j], ifdip, 0)) {
5891 				device_printf(dev,
5892 				    "Unable to allocate TX descriptors\n");
5893 				err = ENOMEM;
5894 				goto err_tx_desc;
5895 			}
5896 			txq->ift_txd_size[j] = scctx->isc_txd_size[j];
5897 			bzero((void *)ifdip->idi_vaddr, txqsizes[j]);
5898 		}
5899 		txq->ift_ctx = ctx;
5900 		txq->ift_id = i;
5901 		if (sctx->isc_flags & IFLIB_HAS_TXCQ) {
5902 			txq->ift_br_offset = 1;
5903 		} else {
5904 			txq->ift_br_offset = 0;
5905 		}
5906 
5907 		if (iflib_txsd_alloc(txq)) {
5908 			device_printf(dev, "Critical Failure setting up TX buffers\n");
5909 			err = ENOMEM;
5910 			goto err_tx_desc;
5911 		}
5912 
5913 		/* Initialize the TX lock */
5914 		snprintf(txq->ift_mtx_name, MTX_NAME_LEN, "%s:TX(%d):callout",
5915 		    device_get_nameunit(dev), txq->ift_id);
5916 		mtx_init(&txq->ift_mtx, txq->ift_mtx_name, NULL, MTX_DEF);
5917 		callout_init_mtx(&txq->ift_timer, &txq->ift_mtx, 0);
5918 		txq->ift_timer.c_cpu = cpu;
5919 #ifdef DEV_NETMAP
5920 		callout_init_mtx(&txq->ift_netmap_timer, &txq->ift_mtx, 0);
5921 		txq->ift_netmap_timer.c_cpu = cpu;
5922 #endif /* DEV_NETMAP */
5923 
5924 		err = ifmp_ring_alloc(&txq->ift_br, 2048, txq, iflib_txq_drain,
5925 		    iflib_txq_can_drain, M_IFLIB, M_WAITOK);
5926 		if (err) {
5927 			/* XXX free any allocated rings */
5928 			device_printf(dev, "Unable to allocate buf_ring\n");
5929 			goto err_tx_desc;
5930 		}
5931 	}
5932 
5933 	for (rxconf = i = 0; i < nrxqsets; i++, rxconf++, rxq++) {
5934 		/* Set up some basics */
5935 		callout_init(&rxq->ifr_watchdog, 1);
5936 
5937 		if ((ifdip = malloc(sizeof(struct iflib_dma_info) * nrxqs,
5938 		    M_IFLIB, M_NOWAIT | M_ZERO)) == NULL) {
5939 			device_printf(dev,
5940 			    "Unable to allocate RX DMA info memory\n");
5941 			err = ENOMEM;
5942 			goto err_tx_desc;
5943 		}
5944 
5945 		rxq->ifr_ifdi = ifdip;
5946 		/* XXX this needs to be changed if #rx queues != #tx queues */
5947 		rxq->ifr_ntxqirq = 1;
5948 		rxq->ifr_txqid[0] = i;
5949 		for (j = 0; j < nrxqs; j++, ifdip++) {
5950 			if (iflib_dma_alloc(ctx, rxqsizes[j], ifdip, 0)) {
5951 				device_printf(dev,
5952 				    "Unable to allocate RX descriptors\n");
5953 				err = ENOMEM;
5954 				goto err_tx_desc;
5955 			}
5956 			bzero((void *)ifdip->idi_vaddr, rxqsizes[j]);
5957 		}
5958 		rxq->ifr_ctx = ctx;
5959 		rxq->ifr_id = i;
5960 		rxq->ifr_fl_offset = fl_offset;
5961 		rxq->ifr_nfl = nfree_lists;
5962 		if (!(fl =
5963 		    (iflib_fl_t) malloc(sizeof(struct iflib_fl) * nfree_lists, M_IFLIB, M_NOWAIT | M_ZERO))) {
5964 			device_printf(dev, "Unable to allocate free list memory\n");
5965 			err = ENOMEM;
5966 			goto err_tx_desc;
5967 		}
5968 		rxq->ifr_fl = fl;
5969 		for (j = 0; j < nfree_lists; j++) {
5970 			fl[j].ifl_rxq = rxq;
5971 			fl[j].ifl_id = j;
5972 			fl[j].ifl_ifdi = &rxq->ifr_ifdi[j + rxq->ifr_fl_offset];
5973 			fl[j].ifl_rxd_size = scctx->isc_rxd_size[j];
5974 		}
5975 		/* Allocate receive buffers for the ring */
5976 		if (iflib_rxsd_alloc(rxq)) {
5977 			device_printf(dev,
5978 			    "Critical Failure setting up receive buffers\n");
5979 			err = ENOMEM;
5980 			goto err_rx_desc;
5981 		}
5982 
5983 		for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++)
5984 			fl->ifl_rx_bitmap = bit_alloc(fl->ifl_size, M_IFLIB,
5985 			    M_WAITOK);
5986 	}
5987 
5988 	/* TXQs */
5989 	vaddrs = malloc(sizeof(caddr_t)  * ntxqsets * ntxqs, M_IFLIB, M_WAITOK);
5990 	paddrs = malloc(sizeof(uint64_t) * ntxqsets * ntxqs, M_IFLIB, M_WAITOK);
5991 	for (i = 0; i < ntxqsets; i++) {
5992 		iflib_dma_info_t di = ctx->ifc_txqs[i].ift_ifdi;
5993 
5994 		for (j = 0; j < ntxqs; j++, di++) {
5995 			vaddrs[i * ntxqs + j] = di->idi_vaddr;
5996 			paddrs[i * ntxqs + j] = di->idi_paddr;
5997 		}
5998 	}
5999 	if ((err = IFDI_TX_QUEUES_ALLOC(ctx, vaddrs, paddrs, ntxqs, ntxqsets)) != 0) {
6000 		device_printf(ctx->ifc_dev,
6001 		    "Unable to allocate device TX queue\n");
6002 		iflib_tx_structures_free(ctx);
6003 		free(vaddrs, M_IFLIB);
6004 		free(paddrs, M_IFLIB);
6005 		goto err_rx_desc;
6006 	}
6007 	free(vaddrs, M_IFLIB);
6008 	free(paddrs, M_IFLIB);
6009 
6010 	/* RXQs */
6011 	vaddrs = malloc(sizeof(caddr_t)  * nrxqsets * nrxqs, M_IFLIB, M_WAITOK);
6012 	paddrs = malloc(sizeof(uint64_t) * nrxqsets * nrxqs, M_IFLIB, M_WAITOK);
6013 	for (i = 0; i < nrxqsets; i++) {
6014 		iflib_dma_info_t di = ctx->ifc_rxqs[i].ifr_ifdi;
6015 
6016 		for (j = 0; j < nrxqs; j++, di++) {
6017 			vaddrs[i * nrxqs + j] = di->idi_vaddr;
6018 			paddrs[i * nrxqs + j] = di->idi_paddr;
6019 		}
6020 	}
6021 	if ((err = IFDI_RX_QUEUES_ALLOC(ctx, vaddrs, paddrs, nrxqs, nrxqsets)) != 0) {
6022 		device_printf(ctx->ifc_dev,
6023 		    "Unable to allocate device RX queue\n");
6024 		iflib_tx_structures_free(ctx);
6025 		free(vaddrs, M_IFLIB);
6026 		free(paddrs, M_IFLIB);
6027 		goto err_rx_desc;
6028 	}
6029 	free(vaddrs, M_IFLIB);
6030 	free(paddrs, M_IFLIB);
6031 
6032 	return (0);
6033 
6034 /* XXX handle allocation failure changes */
6035 err_rx_desc:
6036 err_tx_desc:
6037 rx_fail:
6038 	if (ctx->ifc_rxqs != NULL)
6039 		free(ctx->ifc_rxqs, M_IFLIB);
6040 	ctx->ifc_rxqs = NULL;
6041 	if (ctx->ifc_txqs != NULL)
6042 		free(ctx->ifc_txqs, M_IFLIB);
6043 	ctx->ifc_txqs = NULL;
6044 fail:
6045 	return (err);
6046 }
6047 
6048 static int
6049 iflib_tx_structures_setup(if_ctx_t ctx)
6050 {
6051 	iflib_txq_t txq = ctx->ifc_txqs;
6052 	int i;
6053 
6054 	for (i = 0; i < NTXQSETS(ctx); i++, txq++)
6055 		iflib_txq_setup(txq);
6056 
6057 	return (0);
6058 }
6059 
6060 static void
6061 iflib_tx_structures_free(if_ctx_t ctx)
6062 {
6063 	iflib_txq_t txq = ctx->ifc_txqs;
6064 	if_shared_ctx_t sctx = ctx->ifc_sctx;
6065 	int i, j;
6066 
6067 	for (i = 0; i < NTXQSETS(ctx); i++, txq++) {
6068 		for (j = 0; j < sctx->isc_ntxqs; j++)
6069 			iflib_dma_free(&txq->ift_ifdi[j]);
6070 		iflib_txq_destroy(txq);
6071 	}
6072 	free(ctx->ifc_txqs, M_IFLIB);
6073 	ctx->ifc_txqs = NULL;
6074 }
6075 
6076 /*********************************************************************
6077  *
6078  *  Initialize all receive rings.
6079  *
6080  **********************************************************************/
6081 static int
6082 iflib_rx_structures_setup(if_ctx_t ctx)
6083 {
6084 	iflib_rxq_t rxq = ctx->ifc_rxqs;
6085 	int q;
6086 #if defined(INET6) || defined(INET)
6087 	int err, i;
6088 #endif
6089 
6090 	for (q = 0; q < ctx->ifc_softc_ctx.isc_nrxqsets; q++, rxq++) {
6091 #if defined(INET6) || defined(INET)
6092 		err = tcp_lro_init_args(&rxq->ifr_lc, ctx->ifc_ifp,
6093 		    TCP_LRO_ENTRIES, min(1024,
6094 		    ctx->ifc_softc_ctx.isc_nrxd[rxq->ifr_fl_offset]));
6095 		if (err != 0) {
6096 			device_printf(ctx->ifc_dev,
6097 			    "LRO Initialization failed!\n");
6098 			goto fail;
6099 		}
6100 #endif
6101 		IFDI_RXQ_SETUP(ctx, rxq->ifr_id);
6102 	}
6103 	return (0);
6104 #if defined(INET6) || defined(INET)
6105 fail:
6106 	/*
6107 	 * Free LRO resources allocated so far, we will only handle
6108 	 * the rings that completed, the failing case will have
6109 	 * cleaned up for itself.  'q' failed, so its the terminus.
6110 	 */
6111 	rxq = ctx->ifc_rxqs;
6112 	for (i = 0; i < q; ++i, rxq++) {
6113 		tcp_lro_free(&rxq->ifr_lc);
6114 	}
6115 	return (err);
6116 #endif
6117 }
6118 
6119 /*********************************************************************
6120  *
6121  *  Free all receive rings.
6122  *
6123  **********************************************************************/
6124 static void
6125 iflib_rx_structures_free(if_ctx_t ctx)
6126 {
6127 	iflib_rxq_t rxq = ctx->ifc_rxqs;
6128 	if_shared_ctx_t sctx = ctx->ifc_sctx;
6129 	int i, j;
6130 
6131 	for (i = 0; i < ctx->ifc_softc_ctx.isc_nrxqsets; i++, rxq++) {
6132 		for (j = 0; j < sctx->isc_nrxqs; j++)
6133 			iflib_dma_free(&rxq->ifr_ifdi[j]);
6134 		iflib_rx_sds_free(rxq);
6135 #if defined(INET6) || defined(INET)
6136 		tcp_lro_free(&rxq->ifr_lc);
6137 #endif
6138 	}
6139 	free(ctx->ifc_rxqs, M_IFLIB);
6140 	ctx->ifc_rxqs = NULL;
6141 }
6142 
6143 static int
6144 iflib_qset_structures_setup(if_ctx_t ctx)
6145 {
6146 	int err;
6147 
6148 	/*
6149 	 * It is expected that the caller takes care of freeing queues if this
6150 	 * fails.
6151 	 */
6152 	if ((err = iflib_tx_structures_setup(ctx)) != 0) {
6153 		device_printf(ctx->ifc_dev, "iflib_tx_structures_setup failed: %d\n", err);
6154 		return (err);
6155 	}
6156 
6157 	if ((err = iflib_rx_structures_setup(ctx)) != 0)
6158 		device_printf(ctx->ifc_dev, "iflib_rx_structures_setup failed: %d\n", err);
6159 
6160 	return (err);
6161 }
6162 
6163 int
6164 iflib_irq_alloc(if_ctx_t ctx, if_irq_t irq, int rid,
6165 		driver_filter_t filter, void *filter_arg, driver_intr_t handler, void *arg, const char *name)
6166 {
6167 
6168 	return (_iflib_irq_alloc(ctx, irq, rid, filter, handler, arg, name));
6169 }
6170 
6171 /* Just to avoid copy/paste */
6172 static inline int
6173 iflib_irq_set_affinity(if_ctx_t ctx, if_irq_t irq, iflib_intr_type_t type,
6174     int qid, struct grouptask *gtask, struct taskqgroup *tqg, void *uniq,
6175     const char *name)
6176 {
6177 	device_t dev;
6178 	unsigned int base_cpuid, cpuid;
6179 	int err;
6180 
6181 	dev = ctx->ifc_dev;
6182 	base_cpuid = ctx->ifc_sysctl_core_offset;
6183 	cpuid = get_cpuid_for_queue(ctx, base_cpuid, qid, type == IFLIB_INTR_TX);
6184 	err = taskqgroup_attach_cpu(tqg, gtask, uniq, cpuid, dev,
6185 	    irq ? irq->ii_res : NULL, name);
6186 	if (err) {
6187 		device_printf(dev, "taskqgroup_attach_cpu failed %d\n", err);
6188 		return (err);
6189 	}
6190 #ifdef notyet
6191 	if (cpuid > ctx->ifc_cpuid_highest)
6192 		ctx->ifc_cpuid_highest = cpuid;
6193 #endif
6194 	return (0);
6195 }
6196 
6197 /*
6198  * Allocate a hardware interrupt for subctx using the parent (ctx)'s hardware
6199  * resources.
6200  *
6201  * Similar to iflib_irq_alloc_generic(), but for interrupt type IFLIB_INTR_RXTX
6202  * only.
6203  *
6204  * XXX: Could be removed if subctx's dev has its intr resource allocation
6205  * methods replaced with custom ones?
6206  */
6207 int
6208 iflib_irq_alloc_generic_subctx(if_ctx_t ctx, if_ctx_t subctx, if_irq_t irq,
6209 			       int rid, iflib_intr_type_t type,
6210 			       driver_filter_t *filter, void *filter_arg,
6211 			       int qid, const char *name)
6212 {
6213 	device_t dev, subdev;
6214 	struct grouptask *gtask;
6215 	struct taskqgroup *tqg;
6216 	iflib_filter_info_t info;
6217 	gtask_fn_t *fn;
6218 	int tqrid, err;
6219 	driver_filter_t *intr_fast;
6220 	void *q;
6221 
6222 	MPASS(ctx != NULL);
6223 	MPASS(subctx != NULL);
6224 
6225 	tqrid = rid;
6226 	dev = ctx->ifc_dev;
6227 	subdev = subctx->ifc_dev;
6228 
6229 	switch (type) {
6230 	case IFLIB_INTR_RXTX:
6231 		q = &subctx->ifc_rxqs[qid];
6232 		info = &subctx->ifc_rxqs[qid].ifr_filter_info;
6233 		gtask = &subctx->ifc_rxqs[qid].ifr_task;
6234 		tqg = qgroup_if_io_tqg;
6235 		fn = _task_fn_rx;
6236 		intr_fast = iflib_fast_intr_rxtx;
6237 		NET_GROUPTASK_INIT(gtask, 0, fn, q);
6238 		break;
6239 	default:
6240 		device_printf(dev, "%s: unknown net intr type for subctx %s (%d)\n",
6241 		    __func__, device_get_nameunit(subdev), type);
6242 		return (EINVAL);
6243 	}
6244 
6245 	info->ifi_filter = filter;
6246 	info->ifi_filter_arg = filter_arg;
6247 	info->ifi_task = gtask;
6248 	info->ifi_ctx = q;
6249 
6250 	NET_GROUPTASK_INIT(gtask, 0, fn, q);
6251 
6252 	/* Allocate interrupts from hardware using parent context */
6253 	err = _iflib_irq_alloc(ctx, irq, rid, intr_fast, NULL, info, name);
6254 	if (err != 0) {
6255 		device_printf(dev, "_iflib_irq_alloc failed for subctx %s: %d\n",
6256 		    device_get_nameunit(subdev), err);
6257 		return (err);
6258 	}
6259 
6260 	if (tqrid != -1) {
6261 		err = iflib_irq_set_affinity(ctx, irq, type, qid, gtask, tqg, q,
6262 		    name);
6263 		if (err)
6264 			return (err);
6265 	} else {
6266 		taskqgroup_attach(tqg, gtask, q, dev, irq->ii_res, name);
6267 	}
6268 
6269 	return (0);
6270 }
6271 
6272 int
6273 iflib_irq_alloc_generic(if_ctx_t ctx, if_irq_t irq, int rid,
6274 			iflib_intr_type_t type, driver_filter_t *filter,
6275 			void *filter_arg, int qid, const char *name)
6276 {
6277 	device_t dev;
6278 	struct grouptask *gtask;
6279 	struct taskqgroup *tqg;
6280 	iflib_filter_info_t info;
6281 	gtask_fn_t *fn;
6282 	int tqrid, err;
6283 	driver_filter_t *intr_fast;
6284 	void *q;
6285 
6286 	info = &ctx->ifc_filter_info;
6287 	tqrid = rid;
6288 
6289 	switch (type) {
6290 	/* XXX merge tx/rx for netmap? */
6291 	case IFLIB_INTR_TX:
6292 		q = &ctx->ifc_txqs[qid];
6293 		info = &ctx->ifc_txqs[qid].ift_filter_info;
6294 		gtask = &ctx->ifc_txqs[qid].ift_task;
6295 		tqg = qgroup_if_io_tqg;
6296 		fn = _task_fn_tx;
6297 		intr_fast = iflib_fast_intr;
6298 		GROUPTASK_INIT(gtask, 0, fn, q);
6299 		ctx->ifc_flags |= IFC_NETMAP_TX_IRQ;
6300 		break;
6301 	case IFLIB_INTR_RX:
6302 		q = &ctx->ifc_rxqs[qid];
6303 		info = &ctx->ifc_rxqs[qid].ifr_filter_info;
6304 		gtask = &ctx->ifc_rxqs[qid].ifr_task;
6305 		tqg = qgroup_if_io_tqg;
6306 		fn = _task_fn_rx;
6307 		intr_fast = iflib_fast_intr;
6308 		NET_GROUPTASK_INIT(gtask, 0, fn, q);
6309 		break;
6310 	case IFLIB_INTR_RXTX:
6311 		q = &ctx->ifc_rxqs[qid];
6312 		info = &ctx->ifc_rxqs[qid].ifr_filter_info;
6313 		gtask = &ctx->ifc_rxqs[qid].ifr_task;
6314 		tqg = qgroup_if_io_tqg;
6315 		fn = _task_fn_rx;
6316 		intr_fast = iflib_fast_intr_rxtx;
6317 		NET_GROUPTASK_INIT(gtask, 0, fn, q);
6318 		break;
6319 	case IFLIB_INTR_ADMIN:
6320 		q = ctx;
6321 		tqrid = -1;
6322 		info = &ctx->ifc_filter_info;
6323 		gtask = NULL;
6324 		intr_fast = iflib_fast_intr_ctx;
6325 		break;
6326 	default:
6327 		device_printf(ctx->ifc_dev, "%s: unknown net intr type\n",
6328 		    __func__);
6329 		return (EINVAL);
6330 	}
6331 
6332 	info->ifi_filter = filter;
6333 	info->ifi_filter_arg = filter_arg;
6334 	info->ifi_task = gtask;
6335 	info->ifi_ctx = q;
6336 
6337 	dev = ctx->ifc_dev;
6338 	err = _iflib_irq_alloc(ctx, irq, rid, intr_fast, NULL, info,  name);
6339 	if (err != 0) {
6340 		device_printf(dev, "_iflib_irq_alloc failed %d\n", err);
6341 		return (err);
6342 	}
6343 	if (type == IFLIB_INTR_ADMIN)
6344 		return (0);
6345 
6346 	if (tqrid != -1) {
6347 		err = iflib_irq_set_affinity(ctx, irq, type, qid, gtask, tqg, q,
6348 		    name);
6349 		if (err)
6350 			return (err);
6351 	} else {
6352 		taskqgroup_attach(tqg, gtask, q, dev, irq->ii_res, name);
6353 	}
6354 
6355 	return (0);
6356 }
6357 
6358 void
6359 iflib_softirq_alloc_generic(if_ctx_t ctx, if_irq_t irq, iflib_intr_type_t type,
6360 			    void *arg, int qid, const char *name)
6361 {
6362 	device_t dev;
6363 	struct grouptask *gtask;
6364 	struct taskqgroup *tqg;
6365 	gtask_fn_t *fn;
6366 	void *q;
6367 	int err;
6368 
6369 	switch (type) {
6370 	case IFLIB_INTR_TX:
6371 		q = &ctx->ifc_txqs[qid];
6372 		gtask = &ctx->ifc_txqs[qid].ift_task;
6373 		tqg = qgroup_if_io_tqg;
6374 		fn = _task_fn_tx;
6375 		GROUPTASK_INIT(gtask, 0, fn, q);
6376 		break;
6377 	case IFLIB_INTR_RX:
6378 		q = &ctx->ifc_rxqs[qid];
6379 		gtask = &ctx->ifc_rxqs[qid].ifr_task;
6380 		tqg = qgroup_if_io_tqg;
6381 		fn = _task_fn_rx;
6382 		NET_GROUPTASK_INIT(gtask, 0, fn, q);
6383 		break;
6384 	case IFLIB_INTR_IOV:
6385 		TASK_INIT(&ctx->ifc_vflr_task, 0, _task_fn_iov, ctx);
6386 		return;
6387 	default:
6388 		panic("unknown net intr type");
6389 	}
6390 	err = iflib_irq_set_affinity(ctx, irq, type, qid, gtask, tqg, q, name);
6391 	if (err) {
6392 		dev = ctx->ifc_dev;
6393 		taskqgroup_attach(tqg, gtask, q, dev, irq ? irq->ii_res : NULL,
6394 		    name);
6395 	}
6396 }
6397 
6398 void
6399 iflib_irq_free(if_ctx_t ctx, if_irq_t irq)
6400 {
6401 
6402 	if (irq->ii_tag)
6403 		bus_teardown_intr(ctx->ifc_dev, irq->ii_res, irq->ii_tag);
6404 
6405 	if (irq->ii_res)
6406 		bus_release_resource(ctx->ifc_dev, SYS_RES_IRQ,
6407 		    rman_get_rid(irq->ii_res), irq->ii_res);
6408 }
6409 
6410 static int
6411 iflib_legacy_setup(if_ctx_t ctx, driver_filter_t filter, void *filter_arg, int *rid, const char *name)
6412 {
6413 	iflib_txq_t txq = ctx->ifc_txqs;
6414 	iflib_rxq_t rxq = ctx->ifc_rxqs;
6415 	if_irq_t irq = &ctx->ifc_legacy_irq;
6416 	iflib_filter_info_t info;
6417 	device_t dev;
6418 	struct grouptask *gtask;
6419 	struct resource *res;
6420 	int err, tqrid;
6421 	bool rx_only;
6422 
6423 	info = &rxq->ifr_filter_info;
6424 	gtask = &rxq->ifr_task;
6425 	tqrid = *rid;
6426 	rx_only = (ctx->ifc_sctx->isc_flags & IFLIB_SINGLE_IRQ_RX_ONLY) != 0;
6427 
6428 	ctx->ifc_flags |= IFC_LEGACY;
6429 	info->ifi_filter = filter;
6430 	info->ifi_filter_arg = filter_arg;
6431 	info->ifi_task = gtask;
6432 	info->ifi_ctx = rxq;
6433 
6434 	dev = ctx->ifc_dev;
6435 	/* We allocate a single interrupt resource */
6436 	err = _iflib_irq_alloc(ctx, irq, tqrid, rx_only ? iflib_fast_intr :
6437 	    iflib_fast_intr_rxtx, NULL, info, name);
6438 	if (err != 0)
6439 		return (err);
6440 	NET_GROUPTASK_INIT(gtask, 0, _task_fn_rx, rxq);
6441 	res = irq->ii_res;
6442 	taskqgroup_attach(qgroup_if_io_tqg, gtask, rxq, dev, res, name);
6443 
6444 	GROUPTASK_INIT(&txq->ift_task, 0, _task_fn_tx, txq);
6445 	taskqgroup_attach(qgroup_if_io_tqg, &txq->ift_task, txq, dev, res,
6446 	    "tx");
6447 	return (0);
6448 }
6449 
6450 void
6451 iflib_led_create(if_ctx_t ctx)
6452 {
6453 
6454 	ctx->ifc_led_dev = led_create(iflib_led_func, ctx,
6455 	    device_get_nameunit(ctx->ifc_dev));
6456 }
6457 
6458 void
6459 iflib_tx_intr_deferred(if_ctx_t ctx, int txqid)
6460 {
6461 
6462 	GROUPTASK_ENQUEUE(&ctx->ifc_txqs[txqid].ift_task);
6463 }
6464 
6465 void
6466 iflib_rx_intr_deferred(if_ctx_t ctx, int rxqid)
6467 {
6468 
6469 	GROUPTASK_ENQUEUE(&ctx->ifc_rxqs[rxqid].ifr_task);
6470 }
6471 
6472 void
6473 iflib_admin_intr_deferred(if_ctx_t ctx)
6474 {
6475 
6476 	taskqueue_enqueue(ctx->ifc_tq, &ctx->ifc_admin_task);
6477 }
6478 
6479 void
6480 iflib_iov_intr_deferred(if_ctx_t ctx)
6481 {
6482 
6483 	taskqueue_enqueue(ctx->ifc_tq, &ctx->ifc_vflr_task);
6484 }
6485 
6486 void
6487 iflib_io_tqg_attach(struct grouptask *gt, void *uniq, int cpu, const char *name)
6488 {
6489 
6490 	taskqgroup_attach_cpu(qgroup_if_io_tqg, gt, uniq, cpu, NULL, NULL,
6491 	    name);
6492 }
6493 
6494 void
6495 iflib_config_task_init(if_ctx_t ctx, struct task *config_task, task_fn_t *fn)
6496 {
6497 	TASK_INIT(config_task, 0, fn, ctx);
6498 }
6499 
6500 void
6501 iflib_config_task_enqueue(if_ctx_t ctx, struct task *config_task)
6502 {
6503 	taskqueue_enqueue(ctx->ifc_tq, config_task);
6504 }
6505 
6506 void
6507 iflib_link_state_change(if_ctx_t ctx, int link_state, uint64_t baudrate)
6508 {
6509 	if_t ifp = ctx->ifc_ifp;
6510 	iflib_txq_t txq = ctx->ifc_txqs;
6511 
6512 	if_setbaudrate(ifp, baudrate);
6513 	if (baudrate >= IF_Gbps(10)) {
6514 		STATE_LOCK(ctx);
6515 		ctx->ifc_flags |= IFC_PREFETCH;
6516 		STATE_UNLOCK(ctx);
6517 	}
6518 	/* If link down, disable watchdog */
6519 	if ((ctx->ifc_link_state == LINK_STATE_UP) && (link_state == LINK_STATE_DOWN)) {
6520 		for (int i = 0; i < ctx->ifc_softc_ctx.isc_ntxqsets; i++, txq++)
6521 			txq->ift_qstatus = IFLIB_QUEUE_IDLE;
6522 	}
6523 	ctx->ifc_link_state = link_state;
6524 	if_link_state_change(ifp, link_state);
6525 }
6526 
6527 static int
6528 iflib_tx_credits_update(if_ctx_t ctx, iflib_txq_t txq)
6529 {
6530 	int credits;
6531 #ifdef INVARIANTS
6532 	int credits_pre = txq->ift_cidx_processed;
6533 #endif
6534 
6535 	bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
6536 	    BUS_DMASYNC_POSTREAD);
6537 	if ((credits = ctx->isc_txd_credits_update(ctx->ifc_softc, txq->ift_id, true)) == 0)
6538 		return (0);
6539 
6540 	txq->ift_processed += credits;
6541 	txq->ift_cidx_processed += credits;
6542 
6543 	MPASS(credits_pre + credits == txq->ift_cidx_processed);
6544 	if (txq->ift_cidx_processed >= txq->ift_size)
6545 		txq->ift_cidx_processed -= txq->ift_size;
6546 	return (credits);
6547 }
6548 
6549 static int
6550 iflib_rxd_avail(if_ctx_t ctx, iflib_rxq_t rxq, qidx_t cidx, qidx_t budget)
6551 {
6552 	iflib_fl_t fl;
6553 	u_int i;
6554 
6555 	for (i = 0, fl = &rxq->ifr_fl[0]; i < rxq->ifr_nfl; i++, fl++)
6556 		bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
6557 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
6558 	return (ctx->isc_rxd_available(ctx->ifc_softc, rxq->ifr_id, cidx,
6559 	    budget));
6560 }
6561 
6562 void
6563 iflib_add_int_delay_sysctl(if_ctx_t ctx, const char *name,
6564 	const char *description, if_int_delay_info_t info,
6565 	int offset, int value)
6566 {
6567 	info->iidi_ctx = ctx;
6568 	info->iidi_offset = offset;
6569 	info->iidi_value = value;
6570 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(ctx->ifc_dev),
6571 	    SYSCTL_CHILDREN(device_get_sysctl_tree(ctx->ifc_dev)),
6572 	    OID_AUTO, name, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
6573 	    info, 0, iflib_sysctl_int_delay, "I", description);
6574 }
6575 
6576 struct sx *
6577 iflib_ctx_lock_get(if_ctx_t ctx)
6578 {
6579 
6580 	return (&ctx->ifc_ctx_sx);
6581 }
6582 
6583 static int
6584 iflib_msix_init(if_ctx_t ctx)
6585 {
6586 	device_t dev = ctx->ifc_dev;
6587 	if_shared_ctx_t sctx = ctx->ifc_sctx;
6588 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
6589 	int admincnt, bar, err, iflib_num_rx_queues, iflib_num_tx_queues;
6590 	int msgs, queuemsgs, queues, rx_queues, tx_queues, vectors;
6591 
6592 	iflib_num_tx_queues = ctx->ifc_sysctl_ntxqs;
6593 	iflib_num_rx_queues = ctx->ifc_sysctl_nrxqs;
6594 
6595 	if (bootverbose)
6596 		device_printf(dev, "msix_init qsets capped at %d\n",
6597 		    imax(scctx->isc_ntxqsets, scctx->isc_nrxqsets));
6598 
6599 	/* Override by tuneable */
6600 	if (scctx->isc_disable_msix)
6601 		goto msi;
6602 
6603 	/* First try MSI-X */
6604 	if ((msgs = pci_msix_count(dev)) == 0) {
6605 		if (bootverbose)
6606 			device_printf(dev, "MSI-X not supported or disabled\n");
6607 		goto msi;
6608 	}
6609 
6610 	bar = ctx->ifc_softc_ctx.isc_msix_bar;
6611 	/*
6612 	 * bar == -1 => "trust me I know what I'm doing"
6613 	 * Some drivers are for hardware that is so shoddily
6614 	 * documented that no one knows which bars are which
6615 	 * so the developer has to map all bars. This hack
6616 	 * allows shoddy garbage to use MSI-X in this framework.
6617 	 */
6618 	if (bar != -1) {
6619 		ctx->ifc_msix_mem = bus_alloc_resource_any(dev,
6620 		    SYS_RES_MEMORY, &bar, RF_ACTIVE);
6621 		if (ctx->ifc_msix_mem == NULL) {
6622 			device_printf(dev, "Unable to map MSI-X table\n");
6623 			goto msi;
6624 		}
6625 	}
6626 
6627 	admincnt = sctx->isc_admin_intrcnt;
6628 #if IFLIB_DEBUG
6629 	/* use only 1 qset in debug mode */
6630 	queuemsgs = min(msgs - admincnt, 1);
6631 #else
6632 	queuemsgs = msgs - admincnt;
6633 #endif
6634 #ifdef RSS
6635 	queues = imin(queuemsgs, rss_getnumbuckets());
6636 #else
6637 	queues = queuemsgs;
6638 #endif
6639 	queues = imin(CPU_COUNT(&ctx->ifc_cpus), queues);
6640 	if (bootverbose)
6641 		device_printf(dev,
6642 		    "intr CPUs: %d queue msgs: %d admincnt: %d\n",
6643 		    CPU_COUNT(&ctx->ifc_cpus), queuemsgs, admincnt);
6644 #ifdef  RSS
6645 	/* If we're doing RSS, clamp at the number of RSS buckets */
6646 	if (queues > rss_getnumbuckets())
6647 		queues = rss_getnumbuckets();
6648 #endif
6649 	if (iflib_num_rx_queues > 0 && iflib_num_rx_queues < queuemsgs - admincnt)
6650 		rx_queues = iflib_num_rx_queues;
6651 	else
6652 		rx_queues = queues;
6653 
6654 	if (rx_queues > scctx->isc_nrxqsets)
6655 		rx_queues = scctx->isc_nrxqsets;
6656 
6657 	/*
6658 	 * We want this to be all logical CPUs by default
6659 	 */
6660 	if (iflib_num_tx_queues > 0 && iflib_num_tx_queues < queues)
6661 		tx_queues = iflib_num_tx_queues;
6662 	else
6663 		tx_queues = mp_ncpus;
6664 
6665 	if (tx_queues > scctx->isc_ntxqsets)
6666 		tx_queues = scctx->isc_ntxqsets;
6667 
6668 	if (ctx->ifc_sysctl_qs_eq_override == 0) {
6669 #ifdef INVARIANTS
6670 		if (tx_queues != rx_queues)
6671 			device_printf(dev,
6672 			    "queue equality override not set, capping rx_queues at %d and tx_queues at %d\n",
6673 			    min(rx_queues, tx_queues), min(rx_queues, tx_queues));
6674 #endif
6675 		tx_queues = min(rx_queues, tx_queues);
6676 		rx_queues = min(rx_queues, tx_queues);
6677 	}
6678 
6679 	vectors = rx_queues + admincnt;
6680 	if (msgs < vectors) {
6681 		device_printf(dev,
6682 		    "insufficient number of MSI-X vectors "
6683 		    "(supported %d, need %d)\n", msgs, vectors);
6684 		goto msi;
6685 	}
6686 
6687 	device_printf(dev, "Using %d RX queues %d TX queues\n", rx_queues,
6688 	    tx_queues);
6689 	msgs = vectors;
6690 	if ((err = pci_alloc_msix(dev, &vectors)) == 0) {
6691 		if (vectors != msgs) {
6692 			device_printf(dev,
6693 			    "Unable to allocate sufficient MSI-X vectors "
6694 			    "(got %d, need %d)\n", vectors, msgs);
6695 			pci_release_msi(dev);
6696 			if (bar != -1) {
6697 				bus_release_resource(dev, SYS_RES_MEMORY, bar,
6698 				    ctx->ifc_msix_mem);
6699 				ctx->ifc_msix_mem = NULL;
6700 			}
6701 			goto msi;
6702 		}
6703 		device_printf(dev, "Using MSI-X interrupts with %d vectors\n",
6704 		    vectors);
6705 		scctx->isc_vectors = vectors;
6706 		scctx->isc_nrxqsets = rx_queues;
6707 		scctx->isc_ntxqsets = tx_queues;
6708 		scctx->isc_intr = IFLIB_INTR_MSIX;
6709 
6710 		return (vectors);
6711 	} else {
6712 		device_printf(dev,
6713 		    "failed to allocate %d MSI-X vectors, err: %d\n", vectors,
6714 		    err);
6715 		if (bar != -1) {
6716 			bus_release_resource(dev, SYS_RES_MEMORY, bar,
6717 			    ctx->ifc_msix_mem);
6718 			ctx->ifc_msix_mem = NULL;
6719 		}
6720 	}
6721 
6722 msi:
6723 	vectors = pci_msi_count(dev);
6724 	scctx->isc_nrxqsets = 1;
6725 	scctx->isc_ntxqsets = 1;
6726 	scctx->isc_vectors = vectors;
6727 	if (vectors == 1 && pci_alloc_msi(dev, &vectors) == 0) {
6728 		device_printf(dev, "Using an MSI interrupt\n");
6729 		scctx->isc_intr = IFLIB_INTR_MSI;
6730 	} else {
6731 		scctx->isc_vectors = 1;
6732 		device_printf(dev, "Using a Legacy interrupt\n");
6733 		scctx->isc_intr = IFLIB_INTR_LEGACY;
6734 	}
6735 
6736 	return (vectors);
6737 }
6738 
6739 static const char *ring_states[] = { "IDLE", "BUSY", "STALLED", "ABDICATED" };
6740 
6741 static int
6742 mp_ring_state_handler(SYSCTL_HANDLER_ARGS)
6743 {
6744 	int rc;
6745 	uint16_t *state = ((uint16_t *)oidp->oid_arg1);
6746 	struct sbuf *sb;
6747 	const char *ring_state = "UNKNOWN";
6748 
6749 	/* XXX needed ? */
6750 	rc = sysctl_wire_old_buffer(req, 0);
6751 	MPASS(rc == 0);
6752 	if (rc != 0)
6753 		return (rc);
6754 	sb = sbuf_new_for_sysctl(NULL, NULL, 80, req);
6755 	MPASS(sb != NULL);
6756 	if (sb == NULL)
6757 		return (ENOMEM);
6758 	if (state[3] <= 3)
6759 		ring_state = ring_states[state[3]];
6760 
6761 	sbuf_printf(sb, "pidx_head: %04hd pidx_tail: %04hd cidx: %04hd state: %s",
6762 		    state[0], state[1], state[2], ring_state);
6763 	rc = sbuf_finish(sb);
6764 	sbuf_delete(sb);
6765 	return (rc);
6766 }
6767 
6768 enum iflib_ndesc_handler {
6769 	IFLIB_NTXD_HANDLER,
6770 	IFLIB_NRXD_HANDLER,
6771 };
6772 
6773 static int
6774 mp_ndesc_handler(SYSCTL_HANDLER_ARGS)
6775 {
6776 	if_ctx_t ctx = (void *)arg1;
6777 	enum iflib_ndesc_handler type = arg2;
6778 	char buf[256] = {0};
6779 	qidx_t *ndesc;
6780 	char *p, *next;
6781 	int nqs, rc, i;
6782 
6783 	nqs = 8;
6784 	switch (type) {
6785 	case IFLIB_NTXD_HANDLER:
6786 		ndesc = ctx->ifc_sysctl_ntxds;
6787 		if (ctx->ifc_sctx)
6788 			nqs = ctx->ifc_sctx->isc_ntxqs;
6789 		break;
6790 	case IFLIB_NRXD_HANDLER:
6791 		ndesc = ctx->ifc_sysctl_nrxds;
6792 		if (ctx->ifc_sctx)
6793 			nqs = ctx->ifc_sctx->isc_nrxqs;
6794 		break;
6795 	default:
6796 		printf("%s: unhandled type\n", __func__);
6797 		return (EINVAL);
6798 	}
6799 	if (nqs == 0)
6800 		nqs = 8;
6801 
6802 	for (i = 0; i < 8; i++) {
6803 		if (i >= nqs)
6804 			break;
6805 		if (i)
6806 			strcat(buf, ",");
6807 		sprintf(strchr(buf, 0), "%d", ndesc[i]);
6808 	}
6809 
6810 	rc = sysctl_handle_string(oidp, buf, sizeof(buf), req);
6811 	if (rc || req->newptr == NULL)
6812 		return (rc);
6813 
6814 	for (i = 0, next = buf, p = strsep(&next, " ,"); i < 8 && p;
6815 	    i++, p = strsep(&next, " ,")) {
6816 		ndesc[i] = strtoul(p, NULL, 10);
6817 	}
6818 
6819 	return (rc);
6820 }
6821 
6822 #define NAME_BUFLEN 32
6823 static void
6824 iflib_add_device_sysctl_pre(if_ctx_t ctx)
6825 {
6826 	device_t dev = iflib_get_dev(ctx);
6827 	struct sysctl_oid_list *child, *oid_list;
6828 	struct sysctl_ctx_list *ctx_list;
6829 	struct sysctl_oid *node;
6830 
6831 	ctx_list = device_get_sysctl_ctx(dev);
6832 	child = SYSCTL_CHILDREN(device_get_sysctl_tree(dev));
6833 	ctx->ifc_sysctl_node = node = SYSCTL_ADD_NODE(ctx_list, child,
6834 	    OID_AUTO, "iflib", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
6835 	    "IFLIB fields");
6836 	oid_list = SYSCTL_CHILDREN(node);
6837 
6838 	SYSCTL_ADD_CONST_STRING(ctx_list, oid_list, OID_AUTO, "driver_version",
6839 	    CTLFLAG_RD, ctx->ifc_sctx->isc_driver_version, "driver version");
6840 
6841 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_ntxqs",
6842 	    CTLFLAG_RWTUN, &ctx->ifc_sysctl_ntxqs, 0,
6843 	    "# of txqs to use, 0 => use default #");
6844 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_nrxqs",
6845 	    CTLFLAG_RWTUN, &ctx->ifc_sysctl_nrxqs, 0,
6846 	    "# of rxqs to use, 0 => use default #");
6847 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_qs_enable",
6848 	    CTLFLAG_RWTUN, &ctx->ifc_sysctl_qs_eq_override, 0,
6849 	    "permit #txq != #rxq");
6850 	SYSCTL_ADD_INT(ctx_list, oid_list, OID_AUTO, "disable_msix",
6851 	    CTLFLAG_RWTUN, &ctx->ifc_softc_ctx.isc_disable_msix, 0,
6852 	    "disable MSI-X (default 0)");
6853 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "rx_budget",
6854 	    CTLFLAG_RWTUN, &ctx->ifc_sysctl_rx_budget, 0, "set the RX budget");
6855 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "tx_abdicate",
6856 	    CTLFLAG_RWTUN, &ctx->ifc_sysctl_tx_abdicate, 0,
6857 	    "cause TX to abdicate instead of running to completion");
6858 	ctx->ifc_sysctl_core_offset = CORE_OFFSET_UNSPECIFIED;
6859 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "core_offset",
6860 	    CTLFLAG_RDTUN, &ctx->ifc_sysctl_core_offset, 0,
6861 	    "offset to start using cores at");
6862 	SYSCTL_ADD_U8(ctx_list, oid_list, OID_AUTO, "separate_txrx",
6863 	    CTLFLAG_RDTUN, &ctx->ifc_sysctl_separate_txrx, 0,
6864 	    "use separate cores for TX and RX");
6865 	SYSCTL_ADD_U8(ctx_list, oid_list, OID_AUTO, "use_logical_cores",
6866 	    CTLFLAG_RDTUN, &ctx->ifc_sysctl_use_logical_cores, 0,
6867 	    "try to make use of logical cores for TX and RX");
6868 	SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "use_extra_msix_vectors",
6869 	    CTLFLAG_RDTUN, &ctx->ifc_sysctl_extra_msix_vectors, 0,
6870 	    "attempt to reserve the given number of extra MSI-X vectors during driver load for the creation of additional interfaces later");
6871 	SYSCTL_ADD_INT(ctx_list, oid_list, OID_AUTO, "allocated_msix_vectors",
6872 	    CTLFLAG_RDTUN, &ctx->ifc_softc_ctx.isc_vectors, 0,
6873 	    "total # of MSI-X vectors allocated by driver");
6874 
6875 	/* XXX change for per-queue sizes */
6876 	SYSCTL_ADD_PROC(ctx_list, oid_list, OID_AUTO, "override_ntxds",
6877 	    CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT, ctx,
6878 	    IFLIB_NTXD_HANDLER, mp_ndesc_handler, "A",
6879 	    "list of # of TX descriptors to use, 0 = use default #");
6880 	SYSCTL_ADD_PROC(ctx_list, oid_list, OID_AUTO, "override_nrxds",
6881 	    CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT, ctx,
6882 	    IFLIB_NRXD_HANDLER, mp_ndesc_handler, "A",
6883 	    "list of # of RX descriptors to use, 0 = use default #");
6884 }
6885 
6886 static void
6887 iflib_add_device_sysctl_post(if_ctx_t ctx)
6888 {
6889 	if_shared_ctx_t sctx = ctx->ifc_sctx;
6890 	if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
6891 	device_t dev = iflib_get_dev(ctx);
6892 	struct sysctl_oid_list *child;
6893 	struct sysctl_ctx_list *ctx_list;
6894 	iflib_fl_t fl;
6895 	iflib_txq_t txq;
6896 	iflib_rxq_t rxq;
6897 	int i, j;
6898 	char namebuf[NAME_BUFLEN];
6899 	char *qfmt;
6900 	struct sysctl_oid *queue_node, *fl_node, *node;
6901 	struct sysctl_oid_list *queue_list, *fl_list;
6902 	ctx_list = device_get_sysctl_ctx(dev);
6903 
6904 	node = ctx->ifc_sysctl_node;
6905 	child = SYSCTL_CHILDREN(node);
6906 
6907 	if (scctx->isc_ntxqsets > 100)
6908 		qfmt = "txq%03d";
6909 	else if (scctx->isc_ntxqsets > 10)
6910 		qfmt = "txq%02d";
6911 	else
6912 		qfmt = "txq%d";
6913 	for (i = 0, txq = ctx->ifc_txqs; i < scctx->isc_ntxqsets; i++, txq++) {
6914 		snprintf(namebuf, NAME_BUFLEN, qfmt, i);
6915 		queue_node = SYSCTL_ADD_NODE(ctx_list, child, OID_AUTO, namebuf,
6916 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "Queue Name");
6917 		queue_list = SYSCTL_CHILDREN(queue_node);
6918 		SYSCTL_ADD_INT(ctx_list, queue_list, OID_AUTO, "cpu",
6919 		    CTLFLAG_RD, &txq->ift_task.gt_cpu, 0,
6920 		    "cpu this queue is bound to");
6921 #if MEMORY_LOGGING
6922 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO, "txq_dequeued",
6923 		    CTLFLAG_RD, &txq->ift_dequeued, "total mbufs freed");
6924 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO, "txq_enqueued",
6925 		    CTLFLAG_RD, &txq->ift_enqueued, "total mbufs enqueued");
6926 #endif
6927 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO, "mbuf_defrag",
6928 		    CTLFLAG_RD, &txq->ift_mbuf_defrag,
6929 		    "# of times m_defrag was called");
6930 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO, "m_pullups",
6931 		    CTLFLAG_RD, &txq->ift_pullups,
6932 		    "# of times m_pullup was called");
6933 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
6934 		    "mbuf_defrag_failed", CTLFLAG_RD,
6935 		    &txq->ift_mbuf_defrag_failed, "# of times m_defrag failed");
6936 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
6937 		    "no_desc_avail", CTLFLAG_RD, &txq->ift_no_desc_avail,
6938 		    "# of times no descriptors were available");
6939 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
6940 		    "tx_map_failed", CTLFLAG_RD, &txq->ift_map_failed,
6941 		    "# of times DMA map failed");
6942 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
6943 		    "txd_encap_efbig", CTLFLAG_RD, &txq->ift_txd_encap_efbig,
6944 		    "# of times txd_encap returned EFBIG");
6945 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
6946 		    "no_tx_dma_setup", CTLFLAG_RD, &txq->ift_no_tx_dma_setup,
6947 		    "# of times map failed for other than EFBIG");
6948 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_pidx",
6949 		    CTLFLAG_RD, &txq->ift_pidx, 1, "Producer Index");
6950 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_cidx",
6951 		    CTLFLAG_RD, &txq->ift_cidx, 1, "Consumer Index");
6952 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO,
6953 		    "txq_cidx_processed", CTLFLAG_RD, &txq->ift_cidx_processed,
6954 		    1, "Consumer Index seen by credit update");
6955 		SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_in_use",
6956 		    CTLFLAG_RD, &txq->ift_in_use, 1, "descriptors in use");
6957 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO,
6958 		    "txq_processed", CTLFLAG_RD, &txq->ift_processed,
6959 		    "descriptors procesed for clean");
6960 		SYSCTL_ADD_UQUAD(ctx_list, queue_list, OID_AUTO, "txq_cleaned",
6961 		    CTLFLAG_RD, &txq->ift_cleaned, "total cleaned");
6962 		SYSCTL_ADD_PROC(ctx_list, queue_list, OID_AUTO, "ring_state",
6963 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
6964 		    __DEVOLATILE(uint64_t *, &txq->ift_br->state), 0,
6965 		    mp_ring_state_handler, "A", "soft ring state");
6966 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
6967 		    "r_enqueues", CTLFLAG_RD, &txq->ift_br->enqueues,
6968 		    "# of enqueues to the mp_ring for this queue");
6969 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
6970 		    "r_drops", CTLFLAG_RD, &txq->ift_br->drops,
6971 		    "# of drops in the mp_ring for this queue");
6972 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
6973 		    "r_starts", CTLFLAG_RD, &txq->ift_br->starts,
6974 		    "# of normal consumer starts in mp_ring for this queue");
6975 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
6976 		    "r_stalls", CTLFLAG_RD, &txq->ift_br->stalls,
6977 		    "# of consumer stalls in the mp_ring for this queue");
6978 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
6979 		    "r_restarts", CTLFLAG_RD, &txq->ift_br->restarts,
6980 		    "# of consumer restarts in the mp_ring for this queue");
6981 		SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO,
6982 		    "r_abdications", CTLFLAG_RD, &txq->ift_br->abdications,
6983 		    "# of consumer abdications in the mp_ring for this queue");
6984 	}
6985 
6986 	if (scctx->isc_nrxqsets > 100)
6987 		qfmt = "rxq%03d";
6988 	else if (scctx->isc_nrxqsets > 10)
6989 		qfmt = "rxq%02d";
6990 	else
6991 		qfmt = "rxq%d";
6992 	for (i = 0, rxq = ctx->ifc_rxqs; i < scctx->isc_nrxqsets; i++, rxq++) {
6993 		snprintf(namebuf, NAME_BUFLEN, qfmt, i);
6994 		queue_node = SYSCTL_ADD_NODE(ctx_list, child, OID_AUTO, namebuf,
6995 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "Queue Name");
6996 		queue_list = SYSCTL_CHILDREN(queue_node);
6997 		SYSCTL_ADD_INT(ctx_list, queue_list, OID_AUTO, "cpu",
6998 		    CTLFLAG_RD, &rxq->ifr_task.gt_cpu, 0,
6999 		    "cpu this queue is bound to");
7000 		if (sctx->isc_flags & IFLIB_HAS_RXCQ) {
7001 			SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO,
7002 			    "rxq_cq_cidx", CTLFLAG_RD, &rxq->ifr_cq_cidx, 1,
7003 			    "Consumer Index");
7004 		}
7005 
7006 		for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++) {
7007 			snprintf(namebuf, NAME_BUFLEN, "rxq_fl%d", j);
7008 			fl_node = SYSCTL_ADD_NODE(ctx_list, queue_list,
7009 			    OID_AUTO, namebuf, CTLFLAG_RD | CTLFLAG_MPSAFE,
7010 			    NULL, "freelist Name");
7011 			fl_list = SYSCTL_CHILDREN(fl_node);
7012 			SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "pidx",
7013 			    CTLFLAG_RD, &fl->ifl_pidx, 1, "Producer Index");
7014 			SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "cidx",
7015 			    CTLFLAG_RD, &fl->ifl_cidx, 1, "Consumer Index");
7016 			SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "credits",
7017 			    CTLFLAG_RD, &fl->ifl_credits, 1,
7018 			    "credits available");
7019 			SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "buf_size",
7020 			    CTLFLAG_RD, &fl->ifl_buf_size, 1, "buffer size");
7021 #if MEMORY_LOGGING
7022 			SYSCTL_ADD_UQUAD(ctx_list, fl_list, OID_AUTO,
7023 			    "fl_m_enqueued", CTLFLAG_RD, &fl->ifl_m_enqueued,
7024 			    "mbufs allocated");
7025 			SYSCTL_ADD_UQUAD(ctx_list, fl_list, OID_AUTO,
7026 			    "fl_m_dequeued", CTLFLAG_RD, &fl->ifl_m_dequeued,
7027 			    "mbufs freed");
7028 			SYSCTL_ADD_UQUAD(ctx_list, fl_list, OID_AUTO,
7029 			    "fl_cl_enqueued", CTLFLAG_RD, &fl->ifl_cl_enqueued,
7030 			    "clusters allocated");
7031 			SYSCTL_ADD_UQUAD(ctx_list, fl_list, OID_AUTO,
7032 			    "fl_cl_dequeued", CTLFLAG_RD, &fl->ifl_cl_dequeued,
7033 			    "clusters freed");
7034 #endif
7035 		}
7036 	}
7037 
7038 }
7039 
7040 void
7041 iflib_request_reset(if_ctx_t ctx)
7042 {
7043 
7044 	STATE_LOCK(ctx);
7045 	ctx->ifc_flags |= IFC_DO_RESET;
7046 	STATE_UNLOCK(ctx);
7047 }
7048 
7049 #ifndef __NO_STRICT_ALIGNMENT
7050 static struct mbuf *
7051 iflib_fixup_rx(struct mbuf *m)
7052 {
7053 	struct mbuf *n;
7054 
7055 	if (m->m_len <= (MCLBYTES - ETHER_HDR_LEN)) {
7056 		bcopy(m->m_data, m->m_data + ETHER_HDR_LEN, m->m_len);
7057 		m->m_data += ETHER_HDR_LEN;
7058 		n = m;
7059 	} else {
7060 		MGETHDR(n, M_NOWAIT, MT_DATA);
7061 		if (n == NULL) {
7062 			m_freem(m);
7063 			return (NULL);
7064 		}
7065 		bcopy(m->m_data, n->m_data, ETHER_HDR_LEN);
7066 		m->m_data += ETHER_HDR_LEN;
7067 		m->m_len -= ETHER_HDR_LEN;
7068 		n->m_len = ETHER_HDR_LEN;
7069 		M_MOVE_PKTHDR(n, m);
7070 		n->m_next = m;
7071 	}
7072 	return (n);
7073 }
7074 #endif
7075 
7076 #ifdef DEBUGNET
7077 static void
7078 iflib_debugnet_init(if_t ifp, int *nrxr, int *ncl, int *clsize)
7079 {
7080 	if_ctx_t ctx;
7081 
7082 	ctx = if_getsoftc(ifp);
7083 	CTX_LOCK(ctx);
7084 	*nrxr = NRXQSETS(ctx);
7085 	*ncl = ctx->ifc_rxqs[0].ifr_fl->ifl_size;
7086 	*clsize = ctx->ifc_rxqs[0].ifr_fl->ifl_buf_size;
7087 	CTX_UNLOCK(ctx);
7088 }
7089 
7090 static void
7091 iflib_debugnet_event(if_t ifp, enum debugnet_ev event)
7092 {
7093 	if_ctx_t ctx;
7094 	if_softc_ctx_t scctx;
7095 	iflib_fl_t fl;
7096 	iflib_rxq_t rxq;
7097 	int i, j;
7098 
7099 	ctx = if_getsoftc(ifp);
7100 	scctx = &ctx->ifc_softc_ctx;
7101 
7102 	switch (event) {
7103 	case DEBUGNET_START:
7104 		for (i = 0; i < scctx->isc_nrxqsets; i++) {
7105 			rxq = &ctx->ifc_rxqs[i];
7106 			for (j = 0; j < rxq->ifr_nfl; j++) {
7107 				fl = rxq->ifr_fl;
7108 				fl->ifl_zone = m_getzone(fl->ifl_buf_size);
7109 			}
7110 		}
7111 		iflib_no_tx_batch = 1;
7112 		break;
7113 	default:
7114 		break;
7115 	}
7116 }
7117 
7118 static int
7119 iflib_debugnet_transmit(if_t ifp, struct mbuf *m)
7120 {
7121 	if_ctx_t ctx;
7122 	iflib_txq_t txq;
7123 	int error;
7124 
7125 	ctx = if_getsoftc(ifp);
7126 	if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
7127 	    IFF_DRV_RUNNING)
7128 		return (EBUSY);
7129 
7130 	txq = &ctx->ifc_txqs[0];
7131 	error = iflib_encap(txq, &m);
7132 	if (error == 0)
7133 		(void)iflib_txd_db_check(txq, true);
7134 	return (error);
7135 }
7136 
7137 static int
7138 iflib_debugnet_poll(if_t ifp, int count)
7139 {
7140 	struct epoch_tracker et;
7141 	if_ctx_t ctx;
7142 	if_softc_ctx_t scctx;
7143 	iflib_txq_t txq;
7144 	int i;
7145 
7146 	ctx = if_getsoftc(ifp);
7147 	scctx = &ctx->ifc_softc_ctx;
7148 
7149 	if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
7150 	    IFF_DRV_RUNNING)
7151 		return (EBUSY);
7152 
7153 	txq = &ctx->ifc_txqs[0];
7154 	(void)iflib_completed_tx_reclaim(txq, RECLAIM_THRESH(ctx));
7155 
7156 	NET_EPOCH_ENTER(et);
7157 	for (i = 0; i < scctx->isc_nrxqsets; i++)
7158 		(void)iflib_rxeof(&ctx->ifc_rxqs[i], 16 /* XXX */);
7159 	NET_EPOCH_EXIT(et);
7160 	return (0);
7161 }
7162 #endif /* DEBUGNET */
7163