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