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