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