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