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