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