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