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