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