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