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