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