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