]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/iflib.c
Copy ^/vendor/NetBSD/tests/dist/lib/libc/hash/t_hmac.c to
[FreeBSD/FreeBSD.git] / sys / net / iflib.c
1 /*-
2  * Copyright (c) 2014-2016, Matthew Macy <mmacy@nextbsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *  1. Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *
11  *  2. Neither the name of Matthew Macy nor the names of its
12  *     contributors may be used to endorse or promote products derived from
13  *     this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25  * POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_acpi.h"
34
35 #include <sys/param.h>
36 #include <sys/types.h>
37 #include <sys/bus.h>
38 #include <sys/eventhandler.h>
39 #include <sys/sockio.h>
40 #include <sys/kernel.h>
41 #include <sys/lock.h>
42 #include <sys/mutex.h>
43 #include <sys/module.h>
44 #include <sys/kobj.h>
45 #include <sys/rman.h>
46 #include <sys/sbuf.h>
47 #include <sys/smp.h>
48 #include <sys/socket.h>
49 #include <sys/sysctl.h>
50 #include <sys/syslog.h>
51 #include <sys/taskqueue.h>
52 #include <sys/limits.h>
53
54
55 #include <net/if.h>
56 #include <net/if_var.h>
57 #include <net/if_types.h>
58 #include <net/if_media.h>
59 #include <net/bpf.h>
60 #include <net/ethernet.h>
61 #include <net/mp_ring.h>
62
63 #include <netinet/in.h>
64 #include <netinet/in_pcb.h>
65 #include <netinet/tcp_lro.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/if_ether.h>
68 #include <netinet/ip.h>
69 #include <netinet/ip6.h>
70 #include <netinet/tcp.h>
71
72 #include <machine/bus.h>
73 #include <machine/in_cksum.h>
74
75 #include <vm/vm.h>
76 #include <vm/pmap.h>
77
78 #include <dev/led/led.h>
79 #include <dev/pci/pcireg.h>
80 #include <dev/pci/pcivar.h>
81 #include <dev/pci/pci_private.h>
82
83 #include <net/iflib.h>
84
85 #include "ifdi_if.h"
86
87 #if defined(__i386__) || defined(__amd64__)
88 #include <sys/memdesc.h>
89 #include <machine/bus.h>
90 #include <machine/md_var.h>
91 #include <machine/specialreg.h>
92 #include <x86/include/busdma_impl.h>
93 #include <x86/iommu/busdma_dmar.h>
94 #endif
95
96 /*
97  * enable accounting of every mbuf as it comes in to and goes out of iflib's software descriptor references
98  */
99 #define MEMORY_LOGGING 0
100 /*
101  * Enable mbuf vectors for compressing long mbuf chains
102  */
103
104 /*
105  * NB:
106  * - Prefetching in tx cleaning should perhaps be a tunable. The distance ahead
107  *   we prefetch needs to be determined by the time spent in m_free vis a vis
108  *   the cost of a prefetch. This will of course vary based on the workload:
109  *      - NFLX's m_free path is dominated by vm-based M_EXT manipulation which
110  *        is quite expensive, thus suggesting very little prefetch.
111  *      - small packet forwarding which is just returning a single mbuf to
112  *        UMA will typically be very fast vis a vis the cost of a memory
113  *        access.
114  */
115
116
117 /*
118  * File organization:
119  *  - private structures
120  *  - iflib private utility functions
121  *  - ifnet functions
122  *  - vlan registry and other exported functions
123  *  - iflib public core functions
124  *
125  *
126  */
127 static MALLOC_DEFINE(M_IFLIB, "iflib", "ifnet library");
128
129 struct iflib_txq;
130 typedef struct iflib_txq *iflib_txq_t;
131 struct iflib_rxq;
132 typedef struct iflib_rxq *iflib_rxq_t;
133 struct iflib_fl;
134 typedef struct iflib_fl *iflib_fl_t;
135
136 typedef struct iflib_filter_info {
137         driver_filter_t *ifi_filter;
138         void *ifi_filter_arg;
139         struct grouptask *ifi_task;
140 } *iflib_filter_info_t;
141
142 struct iflib_ctx {
143         KOBJ_FIELDS;
144    /*
145    * Pointer to hardware driver's softc
146    */
147         void *ifc_softc;
148         device_t ifc_dev;
149         if_t ifc_ifp;
150
151         cpuset_t ifc_cpus;
152         if_shared_ctx_t ifc_sctx;
153         struct if_softc_ctx ifc_softc_ctx;
154
155         struct mtx ifc_mtx;
156
157         uint16_t ifc_nhwtxqs;
158         uint16_t ifc_nhwrxqs;
159
160         iflib_txq_t ifc_txqs;
161         iflib_rxq_t ifc_rxqs;
162         uint32_t ifc_if_flags;
163         uint32_t ifc_flags;
164         uint32_t ifc_max_fl_buf_size;
165         int ifc_in_detach;
166
167         int ifc_link_state;
168         int ifc_link_irq;
169         int ifc_pause_frames;
170         int ifc_watchdog_events;
171         struct cdev *ifc_led_dev;
172         struct resource *ifc_msix_mem;
173
174         struct if_irq ifc_legacy_irq;
175         struct grouptask ifc_admin_task;
176         struct grouptask ifc_vflr_task;
177         struct iflib_filter_info ifc_filter_info;
178         struct ifmedia  ifc_media;
179
180         struct sysctl_oid *ifc_sysctl_node;
181         uint16_t ifc_sysctl_ntxqs;
182         uint16_t ifc_sysctl_nrxqs;
183         uint16_t ifc_sysctl_qs_eq_override;
184
185         uint16_t ifc_sysctl_ntxds[8];
186         uint16_t ifc_sysctl_nrxds[8];
187         struct if_txrx ifc_txrx;
188 #define isc_txd_encap  ifc_txrx.ift_txd_encap
189 #define isc_txd_flush  ifc_txrx.ift_txd_flush
190 #define isc_txd_credits_update  ifc_txrx.ift_txd_credits_update
191 #define isc_rxd_available ifc_txrx.ift_rxd_available
192 #define isc_rxd_pkt_get ifc_txrx.ift_rxd_pkt_get
193 #define isc_rxd_refill ifc_txrx.ift_rxd_refill
194 #define isc_rxd_flush ifc_txrx.ift_rxd_flush
195 #define isc_rxd_refill ifc_txrx.ift_rxd_refill
196 #define isc_rxd_refill ifc_txrx.ift_rxd_refill
197 #define isc_legacy_intr ifc_txrx.ift_legacy_intr
198         eventhandler_tag ifc_vlan_attach_event;
199         eventhandler_tag ifc_vlan_detach_event;
200         uint8_t ifc_mac[ETHER_ADDR_LEN];
201         char ifc_mtx_name[16];
202 };
203
204
205 void *
206 iflib_get_softc(if_ctx_t ctx)
207 {
208
209         return (ctx->ifc_softc);
210 }
211
212 device_t
213 iflib_get_dev(if_ctx_t ctx)
214 {
215
216         return (ctx->ifc_dev);
217 }
218
219 if_t
220 iflib_get_ifp(if_ctx_t ctx)
221 {
222
223         return (ctx->ifc_ifp);
224 }
225
226 struct ifmedia *
227 iflib_get_media(if_ctx_t ctx)
228 {
229
230         return (&ctx->ifc_media);
231 }
232
233 void
234 iflib_set_mac(if_ctx_t ctx, uint8_t mac[ETHER_ADDR_LEN])
235 {
236
237         bcopy(mac, ctx->ifc_mac, ETHER_ADDR_LEN);
238 }
239
240 if_softc_ctx_t
241 iflib_get_softc_ctx(if_ctx_t ctx)
242 {
243
244         return (&ctx->ifc_softc_ctx);
245 }
246
247 if_shared_ctx_t
248 iflib_get_sctx(if_ctx_t ctx)
249 {
250
251         return (ctx->ifc_sctx);
252 }
253
254 #define CACHE_PTR_INCREMENT (CACHE_LINE_SIZE/sizeof(void*))
255
256 #define LINK_ACTIVE(ctx) ((ctx)->ifc_link_state == LINK_STATE_UP)
257 #define CTX_IS_VF(ctx) ((ctx)->ifc_sctx->isc_flags & IFLIB_IS_VF)
258
259 #define RX_SW_DESC_MAP_CREATED  (1 << 0)
260 #define TX_SW_DESC_MAP_CREATED  (1 << 1)
261 #define RX_SW_DESC_INUSE        (1 << 3)
262 #define TX_SW_DESC_MAPPED       (1 << 4)
263
264 typedef struct iflib_sw_rx_desc {
265         bus_dmamap_t    ifsd_map;         /* bus_dma map for packet */
266         struct mbuf    *ifsd_m;           /* rx: uninitialized mbuf */
267         caddr_t         ifsd_cl;          /* direct cluster pointer for rx */
268         uint16_t        ifsd_flags;
269 } *iflib_rxsd_t;
270
271 typedef struct iflib_sw_tx_desc_val {
272         bus_dmamap_t    ifsd_map;         /* bus_dma map for packet */
273         struct mbuf    *ifsd_m;           /* pkthdr mbuf */
274         uint8_t         ifsd_flags;
275 } *iflib_txsd_val_t;
276
277 typedef struct iflib_sw_tx_desc_array {
278         bus_dmamap_t    *ifsd_map;         /* bus_dma maps for packet */
279         struct mbuf    **ifsd_m;           /* pkthdr mbufs */
280         uint8_t         *ifsd_flags;
281 } iflib_txsd_array_t;
282
283
284 /* magic number that should be high enough for any hardware */
285 #define IFLIB_MAX_TX_SEGS               128
286 #define IFLIB_MAX_RX_SEGS               32
287 #define IFLIB_RX_COPY_THRESH            128
288 #define IFLIB_MAX_RX_REFRESH            32
289 #define IFLIB_QUEUE_IDLE                0
290 #define IFLIB_QUEUE_HUNG                1
291 #define IFLIB_QUEUE_WORKING             2
292
293 /* this should really scale with ring size - 32 is a fairly arbitrary value for this */
294 #define TX_BATCH_SIZE                   16
295
296 #define IFLIB_RESTART_BUDGET            8
297
298 #define IFC_LEGACY              0x01
299 #define IFC_QFLUSH              0x02
300 #define IFC_MULTISEG            0x04
301 #define IFC_DMAR                0x08
302 #define IFC_SC_ALLOCATED        0x10
303
304 #define CSUM_OFFLOAD            (CSUM_IP_TSO|CSUM_IP6_TSO|CSUM_IP| \
305                                  CSUM_IP_UDP|CSUM_IP_TCP|CSUM_IP_SCTP| \
306                                  CSUM_IP6_UDP|CSUM_IP6_TCP|CSUM_IP6_SCTP)
307 struct iflib_txq {
308         uint16_t        ift_in_use;
309         uint16_t        ift_cidx;
310         uint16_t        ift_cidx_processed;
311         uint16_t        ift_pidx;
312         uint8_t         ift_gen;
313         uint8_t         ift_db_pending;
314         uint8_t         ift_db_pending_queued;
315         uint8_t         ift_npending;
316         uint8_t         ift_br_offset;
317         /* implicit pad */
318         uint64_t        ift_processed;
319         uint64_t        ift_cleaned;
320 #if MEMORY_LOGGING
321         uint64_t        ift_enqueued;
322         uint64_t        ift_dequeued;
323 #endif
324         uint64_t        ift_no_tx_dma_setup;
325         uint64_t        ift_no_desc_avail;
326         uint64_t        ift_mbuf_defrag_failed;
327         uint64_t        ift_mbuf_defrag;
328         uint64_t        ift_map_failed;
329         uint64_t        ift_txd_encap_efbig;
330         uint64_t        ift_pullups;
331
332         struct mtx      ift_mtx;
333         struct mtx      ift_db_mtx;
334
335         /* constant values */
336         if_ctx_t        ift_ctx;
337         struct ifmp_ring        **ift_br;
338         struct grouptask        ift_task;
339         uint16_t        ift_size;
340         uint16_t        ift_id;
341         struct callout  ift_timer;
342         struct callout  ift_db_check;
343
344         iflib_txsd_array_t      ift_sds;
345         uint8_t                 ift_nbr;
346         uint8_t                 ift_qstatus;
347         uint8_t                 ift_active;
348         uint8_t                 ift_closed;
349         int                     ift_watchdog_time;
350         struct iflib_filter_info ift_filter_info;
351         bus_dma_tag_t           ift_desc_tag;
352         bus_dma_tag_t           ift_tso_desc_tag;
353         iflib_dma_info_t        ift_ifdi;
354 #define MTX_NAME_LEN 16
355         char                    ift_mtx_name[MTX_NAME_LEN];
356         char                    ift_db_mtx_name[MTX_NAME_LEN];
357         bus_dma_segment_t       ift_segs[IFLIB_MAX_TX_SEGS]  __aligned(CACHE_LINE_SIZE);
358 #ifdef IFLIB_DIAGNOSTICS
359         uint64_t ift_cpu_exec_count[256];
360 #endif
361 } __aligned(CACHE_LINE_SIZE);
362
363 struct iflib_fl {
364         uint16_t        ifl_cidx;
365         uint16_t        ifl_pidx;
366         uint16_t        ifl_credits;
367         uint8_t         ifl_gen;
368 #if MEMORY_LOGGING
369         uint64_t        ifl_m_enqueued;
370         uint64_t        ifl_m_dequeued;
371         uint64_t        ifl_cl_enqueued;
372         uint64_t        ifl_cl_dequeued;
373 #endif
374         /* implicit pad */
375
376         /* constant */
377         uint16_t        ifl_size;
378         uint16_t        ifl_buf_size;
379         uint16_t        ifl_cltype;
380         uma_zone_t      ifl_zone;
381         iflib_rxsd_t    ifl_sds;
382         iflib_rxq_t     ifl_rxq;
383         uint8_t         ifl_id;
384         bus_dma_tag_t           ifl_desc_tag;
385         iflib_dma_info_t        ifl_ifdi;
386         uint64_t        ifl_bus_addrs[IFLIB_MAX_RX_REFRESH] __aligned(CACHE_LINE_SIZE);
387         caddr_t         ifl_vm_addrs[IFLIB_MAX_RX_REFRESH];
388 }  __aligned(CACHE_LINE_SIZE);
389
390 static inline int
391 get_inuse(int size, int cidx, int pidx, int gen)
392 {
393         int used;
394
395         if (pidx > cidx)
396                 used = pidx - cidx;
397         else if (pidx < cidx)
398                 used = size - cidx + pidx;
399         else if (gen == 0 && pidx == cidx)
400                 used = 0;
401         else if (gen == 1 && pidx == cidx)
402                 used = size;
403         else
404                 panic("bad state");
405
406         return (used);
407 }
408
409 #define TXQ_AVAIL(txq) (txq->ift_size - get_inuse(txq->ift_size, txq->ift_cidx, txq->ift_pidx, txq->ift_gen))
410
411 #define IDXDIFF(head, tail, wrap) \
412         ((head) >= (tail) ? (head) - (tail) : (wrap) - (tail) + (head))
413
414 struct iflib_rxq {
415         /* If there is a separate completion queue -
416          * these are the cq cidx and pidx. Otherwise
417          * these are unused.
418          */
419         uint16_t        ifr_size;
420         uint16_t        ifr_cq_cidx;
421         uint16_t        ifr_cq_pidx;
422         uint8_t         ifr_cq_gen;
423         uint8_t         ifr_fl_offset;
424
425         if_ctx_t        ifr_ctx;
426         iflib_fl_t      ifr_fl;
427         uint64_t        ifr_rx_irq;
428         uint16_t        ifr_id;
429         uint8_t         ifr_lro_enabled;
430         uint8_t         ifr_nfl;
431         struct lro_ctrl                 ifr_lc;
432         struct grouptask        ifr_task;
433         struct iflib_filter_info ifr_filter_info;
434         iflib_dma_info_t                ifr_ifdi;
435         /* dynamically allocate if any drivers need a value substantially larger than this */
436         struct if_rxd_frag      ifr_frags[IFLIB_MAX_RX_SEGS] __aligned(CACHE_LINE_SIZE);
437 #ifdef IFLIB_DIAGNOSTICS
438         uint64_t ifr_cpu_exec_count[256];
439 #endif
440 }  __aligned(CACHE_LINE_SIZE);
441
442 /*
443  * Only allow a single packet to take up most 1/nth of the tx ring
444  */
445 #define MAX_SINGLE_PACKET_FRACTION 12
446 #define IF_BAD_DMA (bus_addr_t)-1
447
448 static int enable_msix = 1;
449
450 #define CTX_ACTIVE(ctx) ((if_getdrvflags((ctx)->ifc_ifp) & IFF_DRV_RUNNING))
451
452 #define CTX_LOCK_INIT(_sc, _name)  mtx_init(&(_sc)->ifc_mtx, _name, "iflib ctx lock", MTX_DEF)
453
454 #define CTX_LOCK(ctx) mtx_lock(&(ctx)->ifc_mtx)
455 #define CTX_UNLOCK(ctx) mtx_unlock(&(ctx)->ifc_mtx)
456 #define CTX_LOCK_DESTROY(ctx) mtx_destroy(&(ctx)->ifc_mtx)
457
458
459 #define TXDB_LOCK_INIT(txq)  mtx_init(&(txq)->ift_db_mtx, (txq)->ift_db_mtx_name, NULL, MTX_DEF)
460 #define TXDB_TRYLOCK(txq) mtx_trylock(&(txq)->ift_db_mtx)
461 #define TXDB_LOCK(txq) mtx_lock(&(txq)->ift_db_mtx)
462 #define TXDB_UNLOCK(txq) mtx_unlock(&(txq)->ift_db_mtx)
463 #define TXDB_LOCK_DESTROY(txq) mtx_destroy(&(txq)->ift_db_mtx)
464
465 #define CALLOUT_LOCK(txq)       mtx_lock(&txq->ift_mtx)
466 #define CALLOUT_UNLOCK(txq)     mtx_unlock(&txq->ift_mtx)
467
468
469 /* Our boot-time initialization hook */
470 static int      iflib_module_event_handler(module_t, int, void *);
471
472 static moduledata_t iflib_moduledata = {
473         "iflib",
474         iflib_module_event_handler,
475         NULL
476 };
477
478 DECLARE_MODULE(iflib, iflib_moduledata, SI_SUB_INIT_IF, SI_ORDER_ANY);
479 MODULE_VERSION(iflib, 1);
480
481 MODULE_DEPEND(iflib, pci, 1, 1, 1);
482 MODULE_DEPEND(iflib, ether, 1, 1, 1);
483
484 TASKQGROUP_DEFINE(if_io_tqg, mp_ncpus, 1);
485 TASKQGROUP_DEFINE(if_config_tqg, 1, 1);
486
487 #ifndef IFLIB_DEBUG_COUNTERS
488 #ifdef INVARIANTS
489 #define IFLIB_DEBUG_COUNTERS 1
490 #else
491 #define IFLIB_DEBUG_COUNTERS 0
492 #endif /* !INVARIANTS */
493 #endif
494
495 static SYSCTL_NODE(_net, OID_AUTO, iflib, CTLFLAG_RD, 0,
496                    "iflib driver parameters");
497
498 /*
499  * XXX need to ensure that this can't accidentally cause the head to be moved backwards 
500  */
501 static int iflib_min_tx_latency = 0;
502
503 SYSCTL_INT(_net_iflib, OID_AUTO, min_tx_latency, CTLFLAG_RW,
504                    &iflib_min_tx_latency, 0, "minimize transmit latency at the possible expense of throughput");
505
506
507 #if IFLIB_DEBUG_COUNTERS
508
509 static int iflib_tx_seen;
510 static int iflib_tx_sent;
511 static int iflib_tx_encap;
512 static int iflib_rx_allocs;
513 static int iflib_fl_refills;
514 static int iflib_fl_refills_large;
515 static int iflib_tx_frees;
516
517 SYSCTL_INT(_net_iflib, OID_AUTO, tx_seen, CTLFLAG_RD,
518                    &iflib_tx_seen, 0, "# tx mbufs seen");
519 SYSCTL_INT(_net_iflib, OID_AUTO, tx_sent, CTLFLAG_RD,
520                    &iflib_tx_sent, 0, "# tx mbufs sent");
521 SYSCTL_INT(_net_iflib, OID_AUTO, tx_encap, CTLFLAG_RD,
522                    &iflib_tx_encap, 0, "# tx mbufs encapped");
523 SYSCTL_INT(_net_iflib, OID_AUTO, tx_frees, CTLFLAG_RD,
524                    &iflib_tx_frees, 0, "# tx frees");
525 SYSCTL_INT(_net_iflib, OID_AUTO, rx_allocs, CTLFLAG_RD,
526                    &iflib_rx_allocs, 0, "# rx allocations");
527 SYSCTL_INT(_net_iflib, OID_AUTO, fl_refills, CTLFLAG_RD,
528                    &iflib_fl_refills, 0, "# refills");
529 SYSCTL_INT(_net_iflib, OID_AUTO, fl_refills_large, CTLFLAG_RD,
530                    &iflib_fl_refills_large, 0, "# large refills");
531
532
533 static int iflib_txq_drain_flushing;
534 static int iflib_txq_drain_oactive;
535 static int iflib_txq_drain_notready;
536 static int iflib_txq_drain_encapfail;
537
538 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_flushing, CTLFLAG_RD,
539                    &iflib_txq_drain_flushing, 0, "# drain flushes");
540 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_oactive, CTLFLAG_RD,
541                    &iflib_txq_drain_oactive, 0, "# drain oactives");
542 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_notready, CTLFLAG_RD,
543                    &iflib_txq_drain_notready, 0, "# drain notready");
544 SYSCTL_INT(_net_iflib, OID_AUTO, txq_drain_encapfail, CTLFLAG_RD,
545                    &iflib_txq_drain_encapfail, 0, "# drain encap fails");
546
547
548 static int iflib_encap_load_mbuf_fail;
549 static int iflib_encap_txq_avail_fail;
550 static int iflib_encap_txd_encap_fail;
551
552 SYSCTL_INT(_net_iflib, OID_AUTO, encap_load_mbuf_fail, CTLFLAG_RD,
553                    &iflib_encap_load_mbuf_fail, 0, "# busdma load failures");
554 SYSCTL_INT(_net_iflib, OID_AUTO, encap_txq_avail_fail, CTLFLAG_RD,
555                    &iflib_encap_txq_avail_fail, 0, "# txq avail failures");
556 SYSCTL_INT(_net_iflib, OID_AUTO, encap_txd_encap_fail, CTLFLAG_RD,
557                    &iflib_encap_txd_encap_fail, 0, "# driver encap failures");
558
559 static int iflib_task_fn_rxs;
560 static int iflib_rx_intr_enables;
561 static int iflib_fast_intrs;
562 static int iflib_intr_link;
563 static int iflib_intr_msix; 
564 static int iflib_rx_unavail;
565 static int iflib_rx_ctx_inactive;
566 static int iflib_rx_zero_len;
567 static int iflib_rx_if_input;
568 static int iflib_rx_mbuf_null;
569 static int iflib_rxd_flush;
570
571 static int iflib_verbose_debug;
572
573 SYSCTL_INT(_net_iflib, OID_AUTO, intr_link, CTLFLAG_RD,
574                    &iflib_intr_link, 0, "# intr link calls");
575 SYSCTL_INT(_net_iflib, OID_AUTO, intr_msix, CTLFLAG_RD,
576                    &iflib_intr_msix, 0, "# intr msix calls");
577 SYSCTL_INT(_net_iflib, OID_AUTO, task_fn_rx, CTLFLAG_RD,
578                    &iflib_task_fn_rxs, 0, "# task_fn_rx calls");
579 SYSCTL_INT(_net_iflib, OID_AUTO, rx_intr_enables, CTLFLAG_RD,
580                    &iflib_rx_intr_enables, 0, "# rx intr enables");
581 SYSCTL_INT(_net_iflib, OID_AUTO, fast_intrs, CTLFLAG_RD,
582                    &iflib_fast_intrs, 0, "# fast_intr calls");
583 SYSCTL_INT(_net_iflib, OID_AUTO, rx_unavail, CTLFLAG_RD,
584                    &iflib_rx_unavail, 0, "# times rxeof called with no available data");
585 SYSCTL_INT(_net_iflib, OID_AUTO, rx_ctx_inactive, CTLFLAG_RD,
586                    &iflib_rx_ctx_inactive, 0, "# times rxeof called with inactive context");
587 SYSCTL_INT(_net_iflib, OID_AUTO, rx_zero_len, CTLFLAG_RD,
588                    &iflib_rx_zero_len, 0, "# times rxeof saw zero len mbuf");
589 SYSCTL_INT(_net_iflib, OID_AUTO, rx_if_input, CTLFLAG_RD,
590                    &iflib_rx_if_input, 0, "# times rxeof called if_input");
591 SYSCTL_INT(_net_iflib, OID_AUTO, rx_mbuf_null, CTLFLAG_RD,
592                    &iflib_rx_mbuf_null, 0, "# times rxeof got null mbuf");
593 SYSCTL_INT(_net_iflib, OID_AUTO, rxd_flush, CTLFLAG_RD,
594                  &iflib_rxd_flush, 0, "# times rxd_flush called");
595 SYSCTL_INT(_net_iflib, OID_AUTO, verbose_debug, CTLFLAG_RW,
596                    &iflib_verbose_debug, 0, "enable verbose debugging");
597
598 #define DBG_COUNTER_INC(name) atomic_add_int(&(iflib_ ## name), 1)
599 static void
600 iflib_debug_reset(void)
601 {
602         iflib_tx_seen = iflib_tx_sent = iflib_tx_encap = iflib_rx_allocs =
603                 iflib_fl_refills = iflib_fl_refills_large = iflib_tx_frees =
604                 iflib_txq_drain_flushing = iflib_txq_drain_oactive =
605                 iflib_txq_drain_notready = iflib_txq_drain_encapfail =
606                 iflib_encap_load_mbuf_fail = iflib_encap_txq_avail_fail =
607                 iflib_encap_txd_encap_fail = iflib_task_fn_rxs = iflib_rx_intr_enables =
608                 iflib_fast_intrs = iflib_intr_link = iflib_intr_msix = iflib_rx_unavail =
609                 iflib_rx_ctx_inactive = iflib_rx_zero_len = iflib_rx_if_input =
610                 iflib_rx_mbuf_null = iflib_rxd_flush = 0;
611 }
612
613 #else
614 #define DBG_COUNTER_INC(name)
615 static void iflib_debug_reset(void) {}
616 #endif
617
618
619
620 #define IFLIB_DEBUG 0
621
622 static void iflib_tx_structures_free(if_ctx_t ctx);
623 static void iflib_rx_structures_free(if_ctx_t ctx);
624 static int iflib_queues_alloc(if_ctx_t ctx);
625 static int iflib_tx_credits_update(if_ctx_t ctx, iflib_txq_t txq);
626 static int iflib_rxd_avail(if_ctx_t ctx, iflib_rxq_t rxq, int cidx, int budget);
627 static int iflib_qset_structures_setup(if_ctx_t ctx);
628 static int iflib_msix_init(if_ctx_t ctx);
629 static int iflib_legacy_setup(if_ctx_t ctx, driver_filter_t filter, void *filterarg, int *rid, char *str);
630 static void iflib_txq_check_drain(iflib_txq_t txq, int budget);
631 static uint32_t iflib_txq_can_drain(struct ifmp_ring *);
632 static int iflib_register(if_ctx_t);
633 static void iflib_init_locked(if_ctx_t ctx);
634 static void iflib_add_device_sysctl_pre(if_ctx_t ctx);
635 static void iflib_add_device_sysctl_post(if_ctx_t ctx);
636 static void iflib_ifmp_purge(iflib_txq_t txq);
637 static void _iflib_pre_assert(if_softc_ctx_t scctx);
638
639 #ifdef DEV_NETMAP
640 #include <sys/selinfo.h>
641 #include <net/netmap.h>
642 #include <dev/netmap/netmap_kern.h>
643
644 MODULE_DEPEND(iflib, netmap, 1, 1, 1);
645
646 /*
647  * device-specific sysctl variables:
648  *
649  * iflib_crcstrip: 0: keep CRC in rx frames (default), 1: strip it.
650  *      During regular operations the CRC is stripped, but on some
651  *      hardware reception of frames not multiple of 64 is slower,
652  *      so using crcstrip=0 helps in benchmarks.
653  *
654  * iflib_rx_miss, iflib_rx_miss_bufs:
655  *      count packets that might be missed due to lost interrupts.
656  */
657 SYSCTL_DECL(_dev_netmap);
658 /*
659  * The xl driver by default strips CRCs and we do not override it.
660  */
661
662 int iflib_crcstrip = 1;
663 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_crcstrip,
664     CTLFLAG_RW, &iflib_crcstrip, 1, "strip CRC on rx frames");
665
666 int iflib_rx_miss, iflib_rx_miss_bufs;
667 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_rx_miss,
668     CTLFLAG_RW, &iflib_rx_miss, 0, "potentially missed rx intr");
669 SYSCTL_INT(_dev_netmap, OID_AUTO, iflib_rx_miss_bufs,
670     CTLFLAG_RW, &iflib_rx_miss_bufs, 0, "potentially missed rx intr bufs");
671
672 /*
673  * Register/unregister. We are already under netmap lock.
674  * Only called on the first register or the last unregister.
675  */
676 static int
677 iflib_netmap_register(struct netmap_adapter *na, int onoff)
678 {
679         struct ifnet *ifp = na->ifp;
680         if_ctx_t ctx = ifp->if_softc;
681
682         CTX_LOCK(ctx);
683         IFDI_INTR_DISABLE(ctx);
684
685         /* Tell the stack that the interface is no longer active */
686         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
687
688         if (!CTX_IS_VF(ctx))
689                 IFDI_CRCSTRIP_SET(ctx, onoff, iflib_crcstrip);
690
691         /* enable or disable flags and callbacks in na and ifp */
692         if (onoff) {
693                 nm_set_native_flags(na);
694         } else {
695                 nm_clear_native_flags(na);
696         }
697         IFDI_INIT(ctx);
698         IFDI_CRCSTRIP_SET(ctx, onoff, iflib_crcstrip); // XXX why twice ?
699         CTX_UNLOCK(ctx);
700         return (ifp->if_drv_flags & IFF_DRV_RUNNING ? 0 : 1);
701 }
702
703 /*
704  * Reconcile kernel and user view of the transmit ring.
705  *
706  * All information is in the kring.
707  * Userspace wants to send packets up to the one before kring->rhead,
708  * kernel knows kring->nr_hwcur is the first unsent packet.
709  *
710  * Here we push packets out (as many as possible), and possibly
711  * reclaim buffers from previously completed transmission.
712  *
713  * The caller (netmap) guarantees that there is only one instance
714  * running at any time. Any interference with other driver
715  * methods should be handled by the individual drivers.
716  */
717 static int
718 iflib_netmap_txsync(struct netmap_kring *kring, int flags)
719 {
720         struct netmap_adapter *na = kring->na;
721         struct ifnet *ifp = na->ifp;
722         struct netmap_ring *ring = kring->ring;
723         u_int nm_i;     /* index into the netmap ring */
724         u_int nic_i;    /* index into the NIC ring */
725         u_int n;
726         u_int const lim = kring->nkr_num_slots - 1;
727         u_int const head = kring->rhead;
728         struct if_pkt_info pi;
729
730         /*
731          * interrupts on every tx packet are expensive so request
732          * them every half ring, or where NS_REPORT is set
733          */
734         u_int report_frequency = kring->nkr_num_slots >> 1;
735         /* device-specific */
736         if_ctx_t ctx = ifp->if_softc;
737         iflib_txq_t txq = &ctx->ifc_txqs[kring->ring_id];
738
739         pi.ipi_segs = txq->ift_segs;
740         pi.ipi_qsidx = kring->ring_id;
741         pi.ipi_ndescs = 0;
742
743         bus_dmamap_sync(txq->ift_desc_tag, txq->ift_ifdi->idi_map,
744                                         BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
745
746
747         /*
748          * First part: process new packets to send.
749          * nm_i is the current index in the netmap ring,
750          * nic_i is the corresponding index in the NIC ring.
751          *
752          * If we have packets to send (nm_i != head)
753          * iterate over the netmap ring, fetch length and update
754          * the corresponding slot in the NIC ring. Some drivers also
755          * need to update the buffer's physical address in the NIC slot
756          * even NS_BUF_CHANGED is not set (PNMB computes the addresses).
757          *
758          * The netmap_reload_map() calls is especially expensive,
759          * even when (as in this case) the tag is 0, so do only
760          * when the buffer has actually changed.
761          *
762          * If possible do not set the report/intr bit on all slots,
763          * but only a few times per ring or when NS_REPORT is set.
764          *
765          * Finally, on 10G and faster drivers, it might be useful
766          * to prefetch the next slot and txr entry.
767          */
768
769         nm_i = kring->nr_hwcur;
770         if (nm_i != head) {     /* we have new packets to send */
771                 nic_i = netmap_idx_k2n(kring, nm_i);
772
773                 __builtin_prefetch(&ring->slot[nm_i]);
774                 __builtin_prefetch(&txq->ift_sds.ifsd_m[nic_i]);
775                 __builtin_prefetch(&txq->ift_sds.ifsd_map[nic_i]);
776
777                 for (n = 0; nm_i != head; n++) {
778                         struct netmap_slot *slot = &ring->slot[nm_i];
779                         u_int len = slot->len;
780                         uint64_t paddr;
781                         void *addr = PNMB(na, slot, &paddr);
782                         int flags = (slot->flags & NS_REPORT ||
783                                 nic_i == 0 || nic_i == report_frequency) ?
784                                 IPI_TX_INTR : 0;
785
786                         /* device-specific */
787                         pi.ipi_pidx = nic_i;
788                         pi.ipi_flags = flags;
789
790                         /* Fill the slot in the NIC ring. */
791                         ctx->isc_txd_encap(ctx->ifc_softc, &pi);
792
793                         /* prefetch for next round */
794                         __builtin_prefetch(&ring->slot[nm_i + 1]);
795                         __builtin_prefetch(&txq->ift_sds.ifsd_m[nic_i + 1]);
796                         __builtin_prefetch(&txq->ift_sds.ifsd_map[nic_i + 1]);
797
798                         NM_CHECK_ADDR_LEN(na, addr, len);
799
800                         if (slot->flags & NS_BUF_CHANGED) {
801                                 /* buffer has changed, reload map */
802                                 netmap_reload_map(na, txq->ift_desc_tag, txq->ift_sds.ifsd_map[nic_i], addr);
803                         }
804                         slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED);
805
806                         /* make sure changes to the buffer are synced */
807                         bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_sds.ifsd_map[nic_i],
808                                                         BUS_DMASYNC_PREWRITE);
809
810                         nm_i = nm_next(nm_i, lim);
811                         nic_i = nm_next(nic_i, lim);
812                 }
813                 kring->nr_hwcur = head;
814
815                 /* synchronize the NIC ring */
816                 bus_dmamap_sync(txq->ift_desc_tag, txq->ift_ifdi->idi_map,
817                                                 BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
818
819                 /* (re)start the tx unit up to slot nic_i (excluded) */
820                 ctx->isc_txd_flush(ctx->ifc_softc, txq->ift_id, nic_i);
821         }
822
823         /*
824          * Second part: reclaim buffers for completed transmissions.
825          */
826         if (iflib_tx_credits_update(ctx, txq)) {
827                 /* some tx completed, increment avail */
828                 nic_i = txq->ift_cidx_processed;
829                 kring->nr_hwtail = nm_prev(netmap_idx_n2k(kring, nic_i), lim);
830         }
831         return (0);
832 }
833
834 /*
835  * Reconcile kernel and user view of the receive ring.
836  * Same as for the txsync, this routine must be efficient.
837  * The caller guarantees a single invocations, but races against
838  * the rest of the driver should be handled here.
839  *
840  * On call, kring->rhead is the first packet that userspace wants
841  * to keep, and kring->rcur is the wakeup point.
842  * The kernel has previously reported packets up to kring->rtail.
843  *
844  * If (flags & NAF_FORCE_READ) also check for incoming packets irrespective
845  * of whether or not we received an interrupt.
846  */
847 static int
848 iflib_netmap_rxsync(struct netmap_kring *kring, int flags)
849 {
850         struct netmap_adapter *na = kring->na;
851         struct ifnet *ifp = na->ifp;
852         struct netmap_ring *ring = kring->ring;
853         u_int nm_i;     /* index into the netmap ring */
854         u_int nic_i;    /* index into the NIC ring */
855         u_int i, n;
856         u_int const lim = kring->nkr_num_slots - 1;
857         u_int const head = kring->rhead;
858         int force_update = (flags & NAF_FORCE_READ) || kring->nr_kflags & NKR_PENDINTR;
859         struct if_rxd_info ri;
860         /* device-specific */
861         if_ctx_t ctx = ifp->if_softc;
862         iflib_rxq_t rxq = &ctx->ifc_rxqs[kring->ring_id];
863         iflib_fl_t fl = rxq->ifr_fl;
864         if (head > lim)
865                 return netmap_ring_reinit(kring);
866
867         bzero(&ri, sizeof(ri));
868         ri.iri_qsidx = kring->ring_id;
869         ri.iri_ifp = ctx->ifc_ifp;
870         /* XXX check sync modes */
871         for (i = 0, fl = rxq->ifr_fl; i < rxq->ifr_nfl; i++, fl++)
872                 bus_dmamap_sync(rxq->ifr_fl[i].ifl_desc_tag, fl->ifl_ifdi->idi_map,
873                                 BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
874
875         /*
876          * First part: import newly received packets.
877          *
878          * nm_i is the index of the next free slot in the netmap ring,
879          * nic_i is the index of the next received packet in the NIC ring,
880          * and they may differ in case if_init() has been called while
881          * in netmap mode. For the receive ring we have
882          *
883          *      nic_i = rxr->next_check;
884          *      nm_i = kring->nr_hwtail (previous)
885          * and
886          *      nm_i == (nic_i + kring->nkr_hwofs) % ring_size
887          *
888          * rxr->next_check is set to 0 on a ring reinit
889          */
890         if (netmap_no_pendintr || force_update) {
891                 int crclen = iflib_crcstrip ? 0 : 4;
892                 int error, avail;
893                 uint16_t slot_flags = kring->nkr_slot_flags;
894
895                 for (fl = rxq->ifr_fl, i = 0; i < rxq->ifr_nfl; i++, fl++) {
896                         nic_i = fl->ifl_cidx;
897                         nm_i = netmap_idx_n2k(kring, nic_i);
898                         avail = ctx->isc_rxd_available(ctx->ifc_softc, kring->ring_id, nic_i, INT_MAX);
899                         for (n = 0; avail > 0; n++, avail--) {
900                                 error = ctx->isc_rxd_pkt_get(ctx->ifc_softc, &ri);
901                                 if (error)
902                                         ring->slot[nm_i].len = 0;
903                                 else
904                                         ring->slot[nm_i].len = ri.iri_len - crclen;
905                                 ring->slot[nm_i].flags = slot_flags;
906                                 bus_dmamap_sync(fl->ifl_ifdi->idi_tag,
907                                                                 fl->ifl_sds[nic_i].ifsd_map, BUS_DMASYNC_POSTREAD);
908                                 nm_i = nm_next(nm_i, lim);
909                                 nic_i = nm_next(nic_i, lim);
910                         }
911                         if (n) { /* update the state variables */
912                                 if (netmap_no_pendintr && !force_update) {
913                                         /* diagnostics */
914                                         iflib_rx_miss ++;
915                                         iflib_rx_miss_bufs += n;
916                                 }
917                                 fl->ifl_cidx = nic_i;
918                                 kring->nr_hwtail = nm_i;
919                         }
920                         kring->nr_kflags &= ~NKR_PENDINTR;
921                 }
922         }
923         /*
924          * Second part: skip past packets that userspace has released.
925          * (kring->nr_hwcur to head excluded),
926          * and make the buffers available for reception.
927          * As usual nm_i is the index in the netmap ring,
928          * nic_i is the index in the NIC ring, and
929          * nm_i == (nic_i + kring->nkr_hwofs) % ring_size
930          */
931         /* XXX not sure how this will work with multiple free lists */
932         nm_i = kring->nr_hwcur;
933         if (nm_i != head) {
934                 nic_i = netmap_idx_k2n(kring, nm_i);
935                 for (n = 0; nm_i != head; n++) {
936                         struct netmap_slot *slot = &ring->slot[nm_i];
937                         uint64_t paddr;
938                         caddr_t vaddr;
939                         void *addr = PNMB(na, slot, &paddr);
940
941                         if (addr == NETMAP_BUF_BASE(na)) /* bad buf */
942                                 goto ring_reset;
943
944                         vaddr = addr;
945                         if (slot->flags & NS_BUF_CHANGED) {
946                                 /* buffer has changed, reload map */
947                                 netmap_reload_map(na, fl->ifl_ifdi->idi_tag, fl->ifl_sds[nic_i].ifsd_map, addr);
948                                 slot->flags &= ~NS_BUF_CHANGED;
949                         }
950                         /*
951                          * XXX we should be batching this operation - TODO
952                          */
953                         ctx->isc_rxd_refill(ctx->ifc_softc, rxq->ifr_id, fl->ifl_id, nic_i, &paddr, &vaddr, 1, fl->ifl_buf_size);
954                         bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_sds[nic_i].ifsd_map,
955                             BUS_DMASYNC_PREREAD);
956                         nm_i = nm_next(nm_i, lim);
957                         nic_i = nm_next(nic_i, lim);
958                 }
959                 kring->nr_hwcur = head;
960
961                 bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
962                     BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
963                 /*
964                  * IMPORTANT: we must leave one free slot in the ring,
965                  * so move nic_i back by one unit
966                  */
967                 nic_i = nm_prev(nic_i, lim);
968                 ctx->isc_rxd_flush(ctx->ifc_softc, rxq->ifr_id, fl->ifl_id, nic_i);
969         }
970
971         return 0;
972
973 ring_reset:
974         return netmap_ring_reinit(kring);
975 }
976
977 static int
978 iflib_netmap_attach(if_ctx_t ctx)
979 {
980         struct netmap_adapter na;
981         if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
982
983         bzero(&na, sizeof(na));
984
985         na.ifp = ctx->ifc_ifp;
986         na.na_flags = NAF_BDG_MAYSLEEP;
987         MPASS(ctx->ifc_softc_ctx.isc_ntxqsets);
988         MPASS(ctx->ifc_softc_ctx.isc_nrxqsets);
989
990         na.num_tx_desc = scctx->isc_ntxd[0];
991         na.num_rx_desc = scctx->isc_nrxd[0];
992         na.nm_txsync = iflib_netmap_txsync;
993         na.nm_rxsync = iflib_netmap_rxsync;
994         na.nm_register = iflib_netmap_register;
995         na.num_tx_rings = ctx->ifc_softc_ctx.isc_ntxqsets;
996         na.num_rx_rings = ctx->ifc_softc_ctx.isc_nrxqsets;
997         return (netmap_attach(&na));
998 }
999
1000 static void
1001 iflib_netmap_txq_init(if_ctx_t ctx, iflib_txq_t txq)
1002 {
1003         struct netmap_adapter *na = NA(ctx->ifc_ifp);
1004         struct netmap_slot *slot;
1005
1006         slot = netmap_reset(na, NR_TX, txq->ift_id, 0);
1007         if (slot == 0)
1008                 return;
1009
1010         for (int i = 0; i < ctx->ifc_softc_ctx.isc_ntxd[0]; i++) {
1011
1012                 /*
1013                  * In netmap mode, set the map for the packet buffer.
1014                  * NOTE: Some drivers (not this one) also need to set
1015                  * the physical buffer address in the NIC ring.
1016                  * netmap_idx_n2k() maps a nic index, i, into the corresponding
1017                  * netmap slot index, si
1018                  */
1019                 int si = netmap_idx_n2k(&na->tx_rings[txq->ift_id], i);
1020                 netmap_load_map(na, txq->ift_desc_tag, txq->ift_sds.ifsd_map[i], NMB(na, slot + si));
1021         }
1022 }
1023 static void
1024 iflib_netmap_rxq_init(if_ctx_t ctx, iflib_rxq_t rxq)
1025 {
1026         struct netmap_adapter *na = NA(ctx->ifc_ifp);
1027         struct netmap_slot *slot;
1028         iflib_rxsd_t sd;
1029         int nrxd;
1030
1031         slot = netmap_reset(na, NR_RX, rxq->ifr_id, 0);
1032         if (slot == 0)
1033                 return;
1034         sd = rxq->ifr_fl[0].ifl_sds;
1035         nrxd = ctx->ifc_softc_ctx.isc_nrxd[0];
1036         for (int i = 0; i < nrxd; i++, sd++) {
1037                         int sj = netmap_idx_n2k(&na->rx_rings[rxq->ifr_id], i);
1038                         uint64_t paddr;
1039                         void *addr;
1040                         caddr_t vaddr;
1041
1042                         vaddr = addr = PNMB(na, slot + sj, &paddr);
1043                         netmap_load_map(na, rxq->ifr_fl[0].ifl_ifdi->idi_tag, sd->ifsd_map, addr);
1044                         /* Update descriptor and the cached value */
1045                         ctx->isc_rxd_refill(ctx->ifc_softc, rxq->ifr_id, 0 /* fl_id */, i, &paddr, &vaddr, 1, rxq->ifr_fl[0].ifl_buf_size);
1046         }
1047         /* preserve queue */
1048         if (ctx->ifc_ifp->if_capenable & IFCAP_NETMAP) {
1049                 struct netmap_kring *kring = &na->rx_rings[rxq->ifr_id];
1050                 int t = na->num_rx_desc - 1 - nm_kr_rxspace(kring);
1051                 ctx->isc_rxd_flush(ctx->ifc_softc, rxq->ifr_id, 0 /* fl_id */, t);
1052         } else
1053                 ctx->isc_rxd_flush(ctx->ifc_softc, rxq->ifr_id, 0 /* fl_id */, nrxd-1);
1054 }
1055
1056 #define iflib_netmap_detach(ifp) netmap_detach(ifp)
1057
1058 #else
1059 #define iflib_netmap_txq_init(ctx, txq)
1060 #define iflib_netmap_rxq_init(ctx, rxq)
1061 #define iflib_netmap_detach(ifp)
1062
1063 #define iflib_netmap_attach(ctx) (0)
1064 #define netmap_rx_irq(ifp, qid, budget) (0)
1065
1066 #endif
1067
1068 #if defined(__i386__) || defined(__amd64__)
1069 static __inline void
1070 prefetch(void *x)
1071 {
1072         __asm volatile("prefetcht0 %0" :: "m" (*(unsigned long *)x));
1073 }
1074 #else
1075 #define prefetch(x)
1076 #endif
1077
1078 static void
1079 _iflib_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int err)
1080 {
1081         if (err)
1082                 return;
1083         *(bus_addr_t *) arg = segs[0].ds_addr;
1084 }
1085
1086 int
1087 iflib_dma_alloc(if_ctx_t ctx, int size, iflib_dma_info_t dma, int mapflags)
1088 {
1089         int err;
1090         if_shared_ctx_t sctx = ctx->ifc_sctx;
1091         device_t dev = ctx->ifc_dev;
1092
1093         KASSERT(sctx->isc_q_align != 0, ("alignment value not initialized"));
1094
1095         err = bus_dma_tag_create(bus_get_dma_tag(dev), /* parent */
1096                                 sctx->isc_q_align, 0,   /* alignment, bounds */
1097                                 BUS_SPACE_MAXADDR,      /* lowaddr */
1098                                 BUS_SPACE_MAXADDR,      /* highaddr */
1099                                 NULL, NULL,             /* filter, filterarg */
1100                                 size,                   /* maxsize */
1101                                 1,                      /* nsegments */
1102                                 size,                   /* maxsegsize */
1103                                 BUS_DMA_ALLOCNOW,       /* flags */
1104                                 NULL,                   /* lockfunc */
1105                                 NULL,                   /* lockarg */
1106                                 &dma->idi_tag);
1107         if (err) {
1108                 device_printf(dev,
1109                     "%s: bus_dma_tag_create failed: %d\n",
1110                     __func__, err);
1111                 goto fail_0;
1112         }
1113
1114         err = bus_dmamem_alloc(dma->idi_tag, (void**) &dma->idi_vaddr,
1115             BUS_DMA_NOWAIT | BUS_DMA_COHERENT | BUS_DMA_ZERO, &dma->idi_map);
1116         if (err) {
1117                 device_printf(dev,
1118                     "%s: bus_dmamem_alloc(%ju) failed: %d\n",
1119                     __func__, (uintmax_t)size, err);
1120                 goto fail_1;
1121         }
1122
1123         dma->idi_paddr = IF_BAD_DMA;
1124         err = bus_dmamap_load(dma->idi_tag, dma->idi_map, dma->idi_vaddr,
1125             size, _iflib_dmamap_cb, &dma->idi_paddr, mapflags | BUS_DMA_NOWAIT);
1126         if (err || dma->idi_paddr == IF_BAD_DMA) {
1127                 device_printf(dev,
1128                     "%s: bus_dmamap_load failed: %d\n",
1129                     __func__, err);
1130                 goto fail_2;
1131         }
1132
1133         dma->idi_size = size;
1134         return (0);
1135
1136 fail_2:
1137         bus_dmamem_free(dma->idi_tag, dma->idi_vaddr, dma->idi_map);
1138 fail_1:
1139         bus_dma_tag_destroy(dma->idi_tag);
1140 fail_0:
1141         dma->idi_tag = NULL;
1142
1143         return (err);
1144 }
1145
1146 int
1147 iflib_dma_alloc_multi(if_ctx_t ctx, int *sizes, iflib_dma_info_t *dmalist, int mapflags, int count)
1148 {
1149         int i, err;
1150         iflib_dma_info_t *dmaiter;
1151
1152         dmaiter = dmalist;
1153         for (i = 0; i < count; i++, dmaiter++) {
1154                 if ((err = iflib_dma_alloc(ctx, sizes[i], *dmaiter, mapflags)) != 0)
1155                         break;
1156         }
1157         if (err)
1158                 iflib_dma_free_multi(dmalist, i);
1159         return (err);
1160 }
1161
1162 void
1163 iflib_dma_free(iflib_dma_info_t dma)
1164 {
1165         if (dma->idi_tag == NULL)
1166                 return;
1167         if (dma->idi_paddr != IF_BAD_DMA) {
1168                 bus_dmamap_sync(dma->idi_tag, dma->idi_map,
1169                     BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1170                 bus_dmamap_unload(dma->idi_tag, dma->idi_map);
1171                 dma->idi_paddr = IF_BAD_DMA;
1172         }
1173         if (dma->idi_vaddr != NULL) {
1174                 bus_dmamem_free(dma->idi_tag, dma->idi_vaddr, dma->idi_map);
1175                 dma->idi_vaddr = NULL;
1176         }
1177         bus_dma_tag_destroy(dma->idi_tag);
1178         dma->idi_tag = NULL;
1179 }
1180
1181 void
1182 iflib_dma_free_multi(iflib_dma_info_t *dmalist, int count)
1183 {
1184         int i;
1185         iflib_dma_info_t *dmaiter = dmalist;
1186
1187         for (i = 0; i < count; i++, dmaiter++)
1188                 iflib_dma_free(*dmaiter);
1189 }
1190
1191 static int
1192 iflib_fast_intr(void *arg)
1193 {
1194         iflib_filter_info_t info = arg;
1195         struct grouptask *gtask = info->ifi_task;
1196
1197         if (!smp_started)
1198                 return (FILTER_HANDLED);
1199
1200         DBG_COUNTER_INC(fast_intrs);
1201         if (info->ifi_filter != NULL && info->ifi_filter(info->ifi_filter_arg) == FILTER_HANDLED)
1202                 return (FILTER_HANDLED);
1203
1204         GROUPTASK_ENQUEUE(gtask);
1205         return (FILTER_HANDLED);
1206 }
1207
1208 static int
1209 _iflib_irq_alloc(if_ctx_t ctx, if_irq_t irq, int rid,
1210         driver_filter_t filter, driver_intr_t handler, void *arg,
1211                                  char *name)
1212 {
1213         int rc;
1214         struct resource *res;
1215         void *tag;
1216         device_t dev = ctx->ifc_dev;
1217
1218         MPASS(rid < 512);
1219         irq->ii_rid = rid;
1220         res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &irq->ii_rid,
1221                                      RF_SHAREABLE | RF_ACTIVE);
1222         if (res == NULL) {
1223                 device_printf(dev,
1224                     "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
1225                 return (ENOMEM);
1226         }
1227         irq->ii_res = res;
1228         KASSERT(filter == NULL || handler == NULL, ("filter and handler can't both be non-NULL"));
1229         rc = bus_setup_intr(dev, res, INTR_MPSAFE | INTR_TYPE_NET,
1230                                                 filter, handler, arg, &tag);
1231         if (rc != 0) {
1232                 device_printf(dev,
1233                     "failed to setup interrupt for rid %d, name %s: %d\n",
1234                                           rid, name ? name : "unknown", rc);
1235                 return (rc);
1236         } else if (name)
1237                 bus_describe_intr(dev, res, tag, "%s", name);
1238
1239         irq->ii_tag = tag;
1240         return (0);
1241 }
1242
1243
1244 /*********************************************************************
1245  *
1246  *  Allocate memory for tx_buffer structures. The tx_buffer stores all
1247  *  the information needed to transmit a packet on the wire. This is
1248  *  called only once at attach, setup is done every reset.
1249  *
1250  **********************************************************************/
1251
1252 static int
1253 iflib_txsd_alloc(iflib_txq_t txq)
1254 {
1255         if_ctx_t ctx = txq->ift_ctx;
1256         if_shared_ctx_t sctx = ctx->ifc_sctx;
1257         if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1258         device_t dev = ctx->ifc_dev;
1259         int err, nsegments, ntsosegments;
1260
1261         nsegments = scctx->isc_tx_nsegments;
1262         ntsosegments = scctx->isc_tx_tso_segments_max;
1263         MPASS(scctx->isc_ntxd[0] > 0);
1264         MPASS(scctx->isc_ntxd[txq->ift_br_offset] > 0);
1265         MPASS(nsegments > 0);
1266         MPASS(ntsosegments > 0);
1267         /*
1268          * Setup DMA descriptor areas.
1269          */
1270         if ((err = bus_dma_tag_create(bus_get_dma_tag(dev),
1271                                1, 0,                    /* alignment, bounds */
1272                                BUS_SPACE_MAXADDR,       /* lowaddr */
1273                                BUS_SPACE_MAXADDR,       /* highaddr */
1274                                NULL, NULL,              /* filter, filterarg */
1275                                sctx->isc_tx_maxsize,            /* maxsize */
1276                                nsegments,       /* nsegments */
1277                                sctx->isc_tx_maxsegsize, /* maxsegsize */
1278                                0,                       /* flags */
1279                                NULL,                    /* lockfunc */
1280                                NULL,                    /* lockfuncarg */
1281                                &txq->ift_desc_tag))) {
1282                 device_printf(dev,"Unable to allocate TX DMA tag: %d\n", err);
1283                 device_printf(dev,"maxsize: %zd nsegments: %d maxsegsize: %zd\n",
1284                                           sctx->isc_tx_maxsize, nsegments, sctx->isc_tx_maxsegsize);
1285                 goto fail;
1286         }
1287         if ((err = bus_dma_tag_create(bus_get_dma_tag(dev),
1288                                1, 0,                    /* alignment, bounds */
1289                                BUS_SPACE_MAXADDR,       /* lowaddr */
1290                                BUS_SPACE_MAXADDR,       /* highaddr */
1291                                NULL, NULL,              /* filter, filterarg */
1292                                scctx->isc_tx_tso_size_max,              /* maxsize */
1293                                ntsosegments,    /* nsegments */
1294                                scctx->isc_tx_tso_segsize_max,   /* maxsegsize */
1295                                0,                       /* flags */
1296                                NULL,                    /* lockfunc */
1297                                NULL,                    /* lockfuncarg */
1298                                &txq->ift_tso_desc_tag))) {
1299                 device_printf(dev,"Unable to allocate TX TSO DMA tag: %d\n", err);
1300
1301                 goto fail;
1302         }
1303         if (!(txq->ift_sds.ifsd_flags =
1304             (uint8_t *) malloc(sizeof(uint8_t) *
1305             scctx->isc_ntxd[txq->ift_br_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1306                 device_printf(dev, "Unable to allocate tx_buffer memory\n");
1307                 err = ENOMEM;
1308                 goto fail;
1309         }
1310         if (!(txq->ift_sds.ifsd_m =
1311             (struct mbuf **) malloc(sizeof(struct mbuf *) *
1312             scctx->isc_ntxd[txq->ift_br_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1313                 device_printf(dev, "Unable to allocate tx_buffer memory\n");
1314                 err = ENOMEM;
1315                 goto fail;
1316         }
1317
1318         /* Create the descriptor buffer dma maps */
1319 #if defined(ACPI_DMAR) || (!(defined(__i386__) && !defined(__amd64__)))
1320         if ((ctx->ifc_flags & IFC_DMAR) == 0)
1321                 return (0);
1322
1323         if (!(txq->ift_sds.ifsd_map =
1324             (bus_dmamap_t *) malloc(sizeof(bus_dmamap_t) * scctx->isc_ntxd[txq->ift_br_offset], M_IFLIB, M_NOWAIT | M_ZERO))) {
1325                 device_printf(dev, "Unable to allocate tx_buffer map memory\n");
1326                 err = ENOMEM;
1327                 goto fail;
1328         }
1329
1330         for (int i = 0; i < scctx->isc_ntxd[txq->ift_br_offset]; i++) {
1331                 err = bus_dmamap_create(txq->ift_desc_tag, 0, &txq->ift_sds.ifsd_map[i]);
1332                 if (err != 0) {
1333                         device_printf(dev, "Unable to create TX DMA map\n");
1334                         goto fail;
1335                 }
1336         }
1337 #endif
1338         return (0);
1339 fail:
1340         /* We free all, it handles case where we are in the middle */
1341         iflib_tx_structures_free(ctx);
1342         return (err);
1343 }
1344
1345 static void
1346 iflib_txsd_destroy(if_ctx_t ctx, iflib_txq_t txq, int i)
1347 {
1348         bus_dmamap_t map;
1349
1350         map = NULL;
1351         if (txq->ift_sds.ifsd_map != NULL)
1352                 map = txq->ift_sds.ifsd_map[i];
1353         if (map != NULL) {
1354                 bus_dmamap_unload(txq->ift_desc_tag, map);
1355                 bus_dmamap_destroy(txq->ift_desc_tag, map);
1356                 txq->ift_sds.ifsd_map[i] = NULL;
1357         }
1358 }
1359
1360 static void
1361 iflib_txq_destroy(iflib_txq_t txq)
1362 {
1363         if_ctx_t ctx = txq->ift_ctx;
1364
1365         for (int i = 0; i < txq->ift_size; i++)
1366                 iflib_txsd_destroy(ctx, txq, i);
1367         if (txq->ift_sds.ifsd_map != NULL) {
1368                 free(txq->ift_sds.ifsd_map, M_IFLIB);
1369                 txq->ift_sds.ifsd_map = NULL;
1370         }
1371         if (txq->ift_sds.ifsd_m != NULL) {
1372                 free(txq->ift_sds.ifsd_m, M_IFLIB);
1373                 txq->ift_sds.ifsd_m = NULL;
1374         }
1375         if (txq->ift_sds.ifsd_flags != NULL) {
1376                 free(txq->ift_sds.ifsd_flags, M_IFLIB);
1377                 txq->ift_sds.ifsd_flags = NULL;
1378         }
1379         if (txq->ift_desc_tag != NULL) {
1380                 bus_dma_tag_destroy(txq->ift_desc_tag);
1381                 txq->ift_desc_tag = NULL;
1382         }
1383         if (txq->ift_tso_desc_tag != NULL) {
1384                 bus_dma_tag_destroy(txq->ift_tso_desc_tag);
1385                 txq->ift_tso_desc_tag = NULL;
1386         }
1387 }
1388
1389 static void
1390 iflib_txsd_free(if_ctx_t ctx, iflib_txq_t txq, int i)
1391 {
1392         struct mbuf **mp;
1393
1394         mp = &txq->ift_sds.ifsd_m[i];
1395         if (*mp == NULL)
1396                 return;
1397
1398         if (txq->ift_sds.ifsd_map != NULL) {
1399                 bus_dmamap_sync(txq->ift_desc_tag,
1400                                 txq->ift_sds.ifsd_map[i],
1401                                 BUS_DMASYNC_POSTWRITE);
1402                 bus_dmamap_unload(txq->ift_desc_tag,
1403                                   txq->ift_sds.ifsd_map[i]);
1404         }
1405         m_free(*mp);
1406         DBG_COUNTER_INC(tx_frees);
1407         *mp = NULL;
1408 }
1409
1410 static int
1411 iflib_txq_setup(iflib_txq_t txq)
1412 {
1413         if_ctx_t ctx = txq->ift_ctx;
1414         if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1415         iflib_dma_info_t di;
1416         int i;
1417
1418         /* Set number of descriptors available */
1419         txq->ift_qstatus = IFLIB_QUEUE_IDLE;
1420
1421         /* Reset indices */
1422         txq->ift_cidx_processed = txq->ift_pidx = txq->ift_cidx = txq->ift_npending = 0;
1423         txq->ift_size = scctx->isc_ntxd[txq->ift_br_offset];
1424
1425         for (i = 0, di = txq->ift_ifdi; i < ctx->ifc_nhwtxqs; i++, di++)
1426                 bzero((void *)di->idi_vaddr, di->idi_size);
1427
1428         IFDI_TXQ_SETUP(ctx, txq->ift_id);
1429         for (i = 0, di = txq->ift_ifdi; i < ctx->ifc_nhwtxqs; i++, di++)
1430                 bus_dmamap_sync(di->idi_tag, di->idi_map,
1431                                                 BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1432         return (0);
1433 }
1434
1435 /*********************************************************************
1436  *
1437  *  Allocate memory for rx_buffer structures. Since we use one
1438  *  rx_buffer per received packet, the maximum number of rx_buffer's
1439  *  that we'll need is equal to the number of receive descriptors
1440  *  that we've allocated.
1441  *
1442  **********************************************************************/
1443 static int
1444 iflib_rxsd_alloc(iflib_rxq_t rxq)
1445 {
1446         if_ctx_t ctx = rxq->ifr_ctx;
1447         if_shared_ctx_t sctx = ctx->ifc_sctx;
1448         if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1449         device_t dev = ctx->ifc_dev;
1450         iflib_fl_t fl;
1451         iflib_rxsd_t    rxsd;
1452         int                     err;
1453
1454         MPASS(scctx->isc_nrxd[0] > 0);
1455         MPASS(scctx->isc_nrxd[rxq->ifr_fl_offset] > 0);
1456
1457         fl = rxq->ifr_fl;
1458         for (int i = 0; i <  rxq->ifr_nfl; i++, fl++) {
1459                 fl->ifl_sds = malloc(sizeof(struct iflib_sw_rx_desc) *
1460                     scctx->isc_nrxd[rxq->ifr_fl_offset], M_IFLIB,
1461                     M_WAITOK | M_ZERO);
1462                 if (fl->ifl_sds == NULL) {
1463                         device_printf(dev, "Unable to allocate rx sw desc memory\n");
1464                         return (ENOMEM);
1465                 }
1466                 fl->ifl_size = scctx->isc_nrxd[rxq->ifr_fl_offset]; /* this isn't necessarily the same */
1467                 err = bus_dma_tag_create(bus_get_dma_tag(dev), /* parent */
1468                                          1, 0,                  /* alignment, bounds */
1469                                          BUS_SPACE_MAXADDR,     /* lowaddr */
1470                                          BUS_SPACE_MAXADDR,     /* highaddr */
1471                                          NULL, NULL,            /* filter, filterarg */
1472                                          sctx->isc_rx_maxsize,  /* maxsize */
1473                                          sctx->isc_rx_nsegments,        /* nsegments */
1474                                          sctx->isc_rx_maxsegsize,       /* maxsegsize */
1475                                          0,                     /* flags */
1476                                          NULL,                  /* lockfunc */
1477                                          NULL,                  /* lockarg */
1478                                          &fl->ifl_desc_tag);
1479                 if (err) {
1480                         device_printf(dev, "%s: bus_dma_tag_create failed %d\n",
1481                                 __func__, err);
1482                         goto fail;
1483                 }
1484
1485                 rxsd = fl->ifl_sds;
1486                 for (int i = 0; i < scctx->isc_nrxd[rxq->ifr_fl_offset]; i++, rxsd++) {
1487                         err = bus_dmamap_create(fl->ifl_desc_tag, 0, &rxsd->ifsd_map);
1488                         if (err) {
1489                                 device_printf(dev, "%s: bus_dmamap_create failed: %d\n",
1490                                         __func__, err);
1491                                 goto fail;
1492                         }
1493                 }
1494         }
1495         return (0);
1496
1497 fail:
1498         iflib_rx_structures_free(ctx);
1499         return (err);
1500 }
1501
1502
1503 /*
1504  * Internal service routines
1505  */
1506
1507 struct rxq_refill_cb_arg {
1508         int               error;
1509         bus_dma_segment_t seg;
1510         int               nseg;
1511 };
1512
1513 static void
1514 _rxq_refill_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1515 {
1516         struct rxq_refill_cb_arg *cb_arg = arg;
1517
1518         cb_arg->error = error;
1519         cb_arg->seg = segs[0];
1520         cb_arg->nseg = nseg;
1521 }
1522
1523
1524 #ifdef ACPI_DMAR
1525 #define IS_DMAR(ctx) (ctx->ifc_flags & IFC_DMAR)
1526 #else
1527 #define IS_DMAR(ctx) (0)
1528 #endif
1529
1530 /**
1531  *      rxq_refill - refill an rxq  free-buffer list
1532  *      @ctx: the iflib context
1533  *      @rxq: the free-list to refill
1534  *      @n: the number of new buffers to allocate
1535  *
1536  *      (Re)populate an rxq free-buffer list with up to @n new packet buffers.
1537  *      The caller must assure that @n does not exceed the queue's capacity.
1538  */
1539 static void
1540 _iflib_fl_refill(if_ctx_t ctx, iflib_fl_t fl, int count)
1541 {
1542         struct mbuf *m;
1543         int pidx = fl->ifl_pidx;
1544         iflib_rxsd_t rxsd = &fl->ifl_sds[pidx];
1545         caddr_t cl;
1546         int n, i = 0;
1547         uint64_t bus_addr;
1548         int err;
1549
1550         n  = count;
1551         MPASS(n > 0);
1552         MPASS(fl->ifl_credits + n <= fl->ifl_size);
1553
1554         if (pidx < fl->ifl_cidx)
1555                 MPASS(pidx + n <= fl->ifl_cidx);
1556         if (pidx == fl->ifl_cidx && (fl->ifl_credits < fl->ifl_size))
1557                 MPASS(fl->ifl_gen == 0);
1558         if (pidx > fl->ifl_cidx)
1559                 MPASS(n <= fl->ifl_size - pidx + fl->ifl_cidx);
1560
1561         DBG_COUNTER_INC(fl_refills);
1562         if (n > 8)
1563                 DBG_COUNTER_INC(fl_refills_large);
1564
1565         while (n--) {
1566                 /*
1567                  * We allocate an uninitialized mbuf + cluster, mbuf is
1568                  * initialized after rx.
1569                  *
1570                  * If the cluster is still set then we know a minimum sized packet was received
1571                  */
1572                 if ((cl = rxsd->ifsd_cl) == NULL) {
1573                         if ((cl = rxsd->ifsd_cl = m_cljget(NULL, M_NOWAIT, fl->ifl_buf_size)) == NULL)
1574                                 break;
1575 #if MEMORY_LOGGING
1576                         fl->ifl_cl_enqueued++;
1577 #endif
1578                 }
1579                 if ((m = m_gethdr(M_NOWAIT, MT_NOINIT)) == NULL) {
1580                         break;
1581                 }
1582 #if MEMORY_LOGGING
1583                 fl->ifl_m_enqueued++;
1584 #endif
1585
1586                 DBG_COUNTER_INC(rx_allocs);
1587 #ifdef notyet
1588                 if ((rxsd->ifsd_flags & RX_SW_DESC_MAP_CREATED) == 0) {
1589                         int err;
1590
1591                         if ((err = bus_dmamap_create(fl->ifl_ifdi->idi_tag, 0, &rxsd->ifsd_map))) {
1592                                 log(LOG_WARNING, "bus_dmamap_create failed %d\n", err);
1593                                 uma_zfree(fl->ifl_zone, cl);
1594                                 n = 0;
1595                                 goto done;
1596                         }
1597                         rxsd->ifsd_flags |= RX_SW_DESC_MAP_CREATED;
1598                 }
1599 #endif
1600 #if defined(__i386__) || defined(__amd64__)
1601                 if (!IS_DMAR(ctx)) {
1602                         bus_addr = pmap_kextract((vm_offset_t)cl);
1603                 } else
1604 #endif
1605                 {
1606                         struct rxq_refill_cb_arg cb_arg;
1607                         iflib_rxq_t q;
1608
1609                         cb_arg.error = 0;
1610                         q = fl->ifl_rxq;
1611                         err = bus_dmamap_load(fl->ifl_desc_tag, rxsd->ifsd_map,
1612                          cl, fl->ifl_buf_size, _rxq_refill_cb, &cb_arg, 0);
1613
1614                         if (err != 0 || cb_arg.error) {
1615                                 /*
1616                                  * !zone_pack ?
1617                                  */
1618                                 if (fl->ifl_zone == zone_pack)
1619                                         uma_zfree(fl->ifl_zone, cl);
1620                                 m_free(m);
1621                                 n = 0;
1622                                 goto done;
1623                         }
1624                         bus_addr = cb_arg.seg.ds_addr;
1625                 }
1626                 rxsd->ifsd_flags |= RX_SW_DESC_INUSE;
1627
1628                 MPASS(rxsd->ifsd_m == NULL);
1629                 rxsd->ifsd_cl = cl;
1630                 rxsd->ifsd_m = m;
1631                 fl->ifl_bus_addrs[i] = bus_addr;
1632                 fl->ifl_vm_addrs[i] = cl;
1633                 rxsd++;
1634                 fl->ifl_credits++;
1635                 i++;
1636                 MPASS(fl->ifl_credits <= fl->ifl_size);
1637                 if (++fl->ifl_pidx == fl->ifl_size) {
1638                         fl->ifl_pidx = 0;
1639                         fl->ifl_gen = 1;
1640                         rxsd = fl->ifl_sds;
1641                 }
1642                 if (n == 0 || i == IFLIB_MAX_RX_REFRESH) {
1643                         ctx->isc_rxd_refill(ctx->ifc_softc, fl->ifl_rxq->ifr_id, fl->ifl_id, pidx,
1644                                                                  fl->ifl_bus_addrs, fl->ifl_vm_addrs, i, fl->ifl_buf_size);
1645                         i = 0;
1646                         pidx = fl->ifl_pidx;
1647                 }
1648         }
1649 done:
1650         DBG_COUNTER_INC(rxd_flush);
1651         if (fl->ifl_pidx == 0)
1652                 pidx = fl->ifl_size - 1;
1653         else
1654                 pidx = fl->ifl_pidx - 1;
1655         ctx->isc_rxd_flush(ctx->ifc_softc, fl->ifl_rxq->ifr_id, fl->ifl_id, pidx);
1656 }
1657
1658 static __inline void
1659 __iflib_fl_refill_lt(if_ctx_t ctx, iflib_fl_t fl, int max)
1660 {
1661         /* we avoid allowing pidx to catch up with cidx as it confuses ixl */
1662         int32_t reclaimable = fl->ifl_size - fl->ifl_credits - 1;
1663 #ifdef INVARIANTS
1664         int32_t delta = fl->ifl_size - get_inuse(fl->ifl_size, fl->ifl_cidx, fl->ifl_pidx, fl->ifl_gen) - 1;
1665 #endif
1666
1667         MPASS(fl->ifl_credits <= fl->ifl_size);
1668         MPASS(reclaimable == delta);
1669
1670         if (reclaimable > 0)
1671                 _iflib_fl_refill(ctx, fl, min(max, reclaimable));
1672 }
1673
1674 static void
1675 iflib_fl_bufs_free(iflib_fl_t fl)
1676 {
1677         iflib_dma_info_t idi = fl->ifl_ifdi;
1678         uint32_t i;
1679
1680         for (i = 0; i < fl->ifl_size; i++) {
1681                 iflib_rxsd_t d = &fl->ifl_sds[i];
1682
1683                 if (d->ifsd_flags & RX_SW_DESC_INUSE) {
1684                         bus_dmamap_unload(fl->ifl_desc_tag, d->ifsd_map);
1685                         bus_dmamap_destroy(fl->ifl_desc_tag, d->ifsd_map);
1686                         if (d->ifsd_m != NULL) {
1687                                 m_init(d->ifsd_m, M_NOWAIT, MT_DATA, 0);
1688                                 uma_zfree(zone_mbuf, d->ifsd_m);
1689                         }
1690                         if (d->ifsd_cl != NULL)
1691                                 uma_zfree(fl->ifl_zone, d->ifsd_cl);
1692                         d->ifsd_flags = 0;
1693                 } else {
1694                         MPASS(d->ifsd_cl == NULL);
1695                         MPASS(d->ifsd_m == NULL);
1696                 }
1697 #if MEMORY_LOGGING
1698                 fl->ifl_m_dequeued++;
1699                 fl->ifl_cl_dequeued++;
1700 #endif
1701                 d->ifsd_cl = NULL;
1702                 d->ifsd_m = NULL;
1703         }
1704         /*
1705          * Reset free list values
1706          */
1707         fl->ifl_credits = fl->ifl_cidx = fl->ifl_pidx = fl->ifl_gen = 0;;
1708         bzero(idi->idi_vaddr, idi->idi_size);
1709 }
1710
1711 /*********************************************************************
1712  *
1713  *  Initialize a receive ring and its buffers.
1714  *
1715  **********************************************************************/
1716 static int
1717 iflib_fl_setup(iflib_fl_t fl)
1718 {
1719         iflib_rxq_t rxq = fl->ifl_rxq;
1720         if_ctx_t ctx = rxq->ifr_ctx;
1721         if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
1722
1723         /*
1724         ** Free current RX buffer structs and their mbufs
1725         */
1726         iflib_fl_bufs_free(fl);
1727         /* Now replenish the mbufs */
1728         MPASS(fl->ifl_credits == 0);
1729         /*
1730          * XXX don't set the max_frame_size to larger
1731          * than the hardware can handle
1732          */
1733         if (sctx->isc_max_frame_size <= 2048)
1734                 fl->ifl_buf_size = MCLBYTES;
1735         else if (sctx->isc_max_frame_size <= 4096)
1736                 fl->ifl_buf_size = MJUMPAGESIZE;
1737         else if (sctx->isc_max_frame_size <= 9216)
1738                 fl->ifl_buf_size = MJUM9BYTES;
1739         else
1740                 fl->ifl_buf_size = MJUM16BYTES;
1741         if (fl->ifl_buf_size > ctx->ifc_max_fl_buf_size)
1742                 ctx->ifc_max_fl_buf_size = fl->ifl_buf_size;
1743         fl->ifl_cltype = m_gettype(fl->ifl_buf_size);
1744         fl->ifl_zone = m_getzone(fl->ifl_buf_size);
1745
1746
1747         /* avoid pre-allocating zillions of clusters to an idle card
1748          * potentially speeding up attach
1749          */
1750         _iflib_fl_refill(ctx, fl, min(128, fl->ifl_size));
1751         MPASS(min(128, fl->ifl_size) == fl->ifl_credits);
1752         if (min(128, fl->ifl_size) != fl->ifl_credits)
1753                 return (ENOBUFS);
1754         /*
1755          * handle failure
1756          */
1757         MPASS(rxq != NULL);
1758         MPASS(fl->ifl_ifdi != NULL);
1759         bus_dmamap_sync(fl->ifl_ifdi->idi_tag, fl->ifl_ifdi->idi_map,
1760             BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1761         return (0);
1762 }
1763
1764 /*********************************************************************
1765  *
1766  *  Free receive ring data structures
1767  *
1768  **********************************************************************/
1769 static void
1770 iflib_rx_sds_free(iflib_rxq_t rxq)
1771 {
1772         iflib_fl_t fl;
1773         int i;
1774
1775         if (rxq->ifr_fl != NULL) {
1776                 for (i = 0; i < rxq->ifr_nfl; i++) {
1777                         fl = &rxq->ifr_fl[i];
1778                         if (fl->ifl_desc_tag != NULL) {
1779                                 bus_dma_tag_destroy(fl->ifl_desc_tag);
1780                                 fl->ifl_desc_tag = NULL;
1781                         }
1782                 }
1783                 if (rxq->ifr_fl->ifl_sds != NULL)
1784                         free(rxq->ifr_fl->ifl_sds, M_IFLIB);
1785
1786                 free(rxq->ifr_fl, M_IFLIB);
1787                 rxq->ifr_fl = NULL;
1788                 rxq->ifr_cq_gen = rxq->ifr_cq_cidx = rxq->ifr_cq_pidx = 0;
1789         }
1790 }
1791
1792 /*
1793  * MI independent logic
1794  *
1795  */
1796 static void
1797 iflib_timer(void *arg)
1798 {
1799         iflib_txq_t txq = arg;
1800         if_ctx_t ctx = txq->ift_ctx;
1801         if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1802
1803         if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING))
1804                 return;
1805         /*
1806         ** Check on the state of the TX queue(s), this
1807         ** can be done without the lock because its RO
1808         ** and the HUNG state will be static if set.
1809         */
1810         IFDI_TIMER(ctx, txq->ift_id);
1811         if ((txq->ift_qstatus == IFLIB_QUEUE_HUNG) &&
1812                 (ctx->ifc_pause_frames == 0))
1813                 goto hung;
1814
1815         if (TXQ_AVAIL(txq) <= 2*scctx->isc_tx_nsegments ||
1816             ifmp_ring_is_stalled(txq->ift_br[0]))
1817                 GROUPTASK_ENQUEUE(&txq->ift_task);
1818
1819         ctx->ifc_pause_frames = 0;
1820         if (if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING) 
1821                 callout_reset_on(&txq->ift_timer, hz/2, iflib_timer, txq, txq->ift_timer.c_cpu);
1822         return;
1823 hung:
1824         CTX_LOCK(ctx);
1825         if_setdrvflagbits(ctx->ifc_ifp, 0, IFF_DRV_RUNNING);
1826         device_printf(ctx->ifc_dev,  "TX(%d) desc avail = %d, pidx = %d\n",
1827                                   txq->ift_id, TXQ_AVAIL(txq), txq->ift_pidx);
1828
1829         IFDI_WATCHDOG_RESET(ctx);
1830         ctx->ifc_watchdog_events++;
1831         ctx->ifc_pause_frames = 0;
1832
1833         iflib_init_locked(ctx);
1834         CTX_UNLOCK(ctx);
1835 }
1836
1837 static void
1838 iflib_init_locked(if_ctx_t ctx)
1839 {
1840         if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
1841         if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1842         if_t ifp = ctx->ifc_ifp;
1843         iflib_fl_t fl;
1844         iflib_txq_t txq;
1845         iflib_rxq_t rxq;
1846         int i, j, tx_ip_csum_flags, tx_ip6_csum_flags;
1847
1848
1849         if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
1850         IFDI_INTR_DISABLE(ctx);
1851
1852         tx_ip_csum_flags = scctx->isc_tx_csum_flags & (CSUM_IP | CSUM_TCP | CSUM_UDP | CSUM_SCTP);
1853         tx_ip6_csum_flags = scctx->isc_tx_csum_flags & (CSUM_IP6_TCP | CSUM_IP6_UDP | CSUM_IP6_SCTP);
1854         /* Set hardware offload abilities */
1855         if_clearhwassist(ifp);
1856         if (if_getcapenable(ifp) & IFCAP_TXCSUM)
1857                 if_sethwassistbits(ifp, tx_ip_csum_flags, 0);
1858         if (if_getcapenable(ifp) & IFCAP_TXCSUM_IPV6)
1859                 if_sethwassistbits(ifp,  tx_ip6_csum_flags, 0);
1860         if (if_getcapenable(ifp) & IFCAP_TSO4)
1861                 if_sethwassistbits(ifp, CSUM_IP_TSO, 0);
1862         if (if_getcapenable(ifp) & IFCAP_TSO6)
1863                 if_sethwassistbits(ifp, CSUM_IP6_TSO, 0);
1864
1865         for (i = 0, txq = ctx->ifc_txqs; i < sctx->isc_ntxqsets; i++, txq++) {
1866                 CALLOUT_LOCK(txq);
1867                 callout_stop(&txq->ift_timer);
1868                 callout_stop(&txq->ift_db_check);
1869                 CALLOUT_UNLOCK(txq);
1870                 iflib_netmap_txq_init(ctx, txq);
1871         }
1872         for (i = 0, rxq = ctx->ifc_rxqs; i < sctx->isc_nrxqsets; i++, rxq++) {
1873                 iflib_netmap_rxq_init(ctx, rxq);
1874         }
1875 #ifdef INVARIANTS
1876         i = if_getdrvflags(ifp);
1877 #endif
1878         IFDI_INIT(ctx);
1879         MPASS(if_getdrvflags(ifp) == i);
1880         for (i = 0, rxq = ctx->ifc_rxqs; i < sctx->isc_nrxqsets; i++, rxq++) {
1881                 for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++) {
1882                         if (iflib_fl_setup(fl)) {
1883                                 device_printf(ctx->ifc_dev, "freelist setup failed - check cluster settings\n");
1884                                 goto done;
1885                         }
1886                 }
1887         }
1888         done:
1889         if_setdrvflagbits(ctx->ifc_ifp, IFF_DRV_RUNNING, IFF_DRV_OACTIVE);
1890         IFDI_INTR_ENABLE(ctx);
1891         txq = ctx->ifc_txqs;
1892         for (i = 0; i < sctx->isc_ntxqsets; i++, txq++)
1893                 callout_reset_on(&txq->ift_timer, hz/2, iflib_timer, txq,
1894                         txq->ift_timer.c_cpu);
1895 }
1896
1897 static int
1898 iflib_media_change(if_t ifp)
1899 {
1900         if_ctx_t ctx = if_getsoftc(ifp);
1901         int err;
1902
1903         CTX_LOCK(ctx);
1904         if ((err = IFDI_MEDIA_CHANGE(ctx)) == 0)
1905                 iflib_init_locked(ctx);
1906         CTX_UNLOCK(ctx);
1907         return (err);
1908 }
1909
1910 static void
1911 iflib_media_status(if_t ifp, struct ifmediareq *ifmr)
1912 {
1913         if_ctx_t ctx = if_getsoftc(ifp);
1914
1915         CTX_LOCK(ctx);
1916         IFDI_UPDATE_ADMIN_STATUS(ctx);
1917         IFDI_MEDIA_STATUS(ctx, ifmr);
1918         CTX_UNLOCK(ctx);
1919 }
1920
1921 static void
1922 iflib_stop(if_ctx_t ctx)
1923 {
1924         iflib_txq_t txq = ctx->ifc_txqs;
1925         iflib_rxq_t rxq = ctx->ifc_rxqs;
1926         if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
1927         iflib_dma_info_t di;
1928         iflib_fl_t fl;
1929         int i, j;
1930
1931         /* Tell the stack that the interface is no longer active */
1932         if_setdrvflagbits(ctx->ifc_ifp, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
1933
1934         IFDI_INTR_DISABLE(ctx);
1935         DELAY(100000);
1936         IFDI_STOP(ctx);
1937         DELAY(100000);
1938
1939         iflib_debug_reset();
1940         /* Wait for current tx queue users to exit to disarm watchdog timer. */
1941         for (i = 0; i < scctx->isc_ntxqsets; i++, txq++) {
1942                 /* make sure all transmitters have completed before proceeding XXX */
1943
1944                 /* clean any enqueued buffers */
1945                 iflib_ifmp_purge(txq);
1946                 /* Free any existing tx buffers. */
1947                 for (j = 0; j < txq->ift_size; j++) {
1948                         iflib_txsd_free(ctx, txq, j);
1949                 }
1950                 txq->ift_processed = txq->ift_cleaned = txq->ift_cidx_processed = 0;
1951                 txq->ift_in_use = txq->ift_gen = txq->ift_cidx = txq->ift_pidx = txq->ift_no_desc_avail = 0;
1952                 txq->ift_closed = txq->ift_mbuf_defrag = txq->ift_mbuf_defrag_failed = 0;
1953                 txq->ift_no_tx_dma_setup = txq->ift_txd_encap_efbig = txq->ift_map_failed = 0;
1954                 txq->ift_pullups = 0;
1955                 ifmp_ring_reset_stats(txq->ift_br[0]);
1956                 for (j = 0, di = txq->ift_ifdi; j < ctx->ifc_nhwtxqs; j++, di++)
1957                         bzero((void *)di->idi_vaddr, di->idi_size);
1958         }
1959         for (i = 0; i < scctx->isc_nrxqsets; i++, rxq++) {
1960                 /* make sure all transmitters have completed before proceeding XXX */
1961
1962                 for (j = 0, di = txq->ift_ifdi; j < ctx->ifc_nhwrxqs; j++, di++)
1963                         bzero((void *)di->idi_vaddr, di->idi_size);
1964                 /* also resets the free lists pidx/cidx */
1965                 for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++)
1966                         iflib_fl_bufs_free(fl);
1967         }
1968 }
1969
1970 static iflib_rxsd_t
1971 rxd_frag_to_sd(iflib_rxq_t rxq, if_rxd_frag_t irf, int *cltype, int unload)
1972 {
1973         int flid, cidx;
1974         iflib_rxsd_t sd;
1975         iflib_fl_t fl;
1976         iflib_dma_info_t di;
1977
1978         flid = irf->irf_flid;
1979         cidx = irf->irf_idx;
1980         fl = &rxq->ifr_fl[flid];
1981         fl->ifl_credits--;
1982 #if MEMORY_LOGGING
1983         fl->ifl_m_dequeued++;
1984         if (cltype)
1985                 fl->ifl_cl_dequeued++;
1986 #endif
1987         sd = &fl->ifl_sds[cidx];
1988         di = fl->ifl_ifdi;
1989         bus_dmamap_sync(di->idi_tag, di->idi_map,
1990                         BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1991
1992         /* not valid assert if bxe really does SGE from non-contiguous elements */
1993         MPASS(fl->ifl_cidx == cidx);
1994         if (unload)
1995                 bus_dmamap_unload(fl->ifl_desc_tag, sd->ifsd_map);
1996
1997         if (__predict_false(++fl->ifl_cidx == fl->ifl_size)) {
1998                 fl->ifl_cidx = 0;
1999                 fl->ifl_gen = 0;
2000         }
2001         /* YES ick */
2002         if (cltype)
2003                 *cltype = fl->ifl_cltype;
2004         return (sd);
2005 }
2006
2007 static struct mbuf *
2008 assemble_segments(iflib_rxq_t rxq, if_rxd_info_t ri)
2009 {
2010         int i, padlen , flags, cltype;
2011         struct mbuf *m, *mh, *mt;
2012         iflib_rxsd_t sd;
2013         caddr_t cl;
2014
2015         i = 0;
2016         mh = NULL;
2017         do {
2018                 sd = rxd_frag_to_sd(rxq, &ri->iri_frags[i], &cltype, TRUE);
2019
2020                 MPASS(sd->ifsd_cl != NULL);
2021                 MPASS(sd->ifsd_m != NULL);
2022
2023                 /* Don't include zero-length frags */
2024                 if (ri->iri_frags[i].irf_len == 0) {
2025                         /* XXX we can save the cluster here, but not the mbuf */
2026                         m_init(sd->ifsd_m, M_NOWAIT, MT_DATA, 0);
2027                         m_free(sd->ifsd_m);
2028                         sd->ifsd_m = NULL;
2029                         continue;
2030                 }
2031
2032                 m = sd->ifsd_m;
2033                 if (mh == NULL) {
2034                         flags = M_PKTHDR|M_EXT;
2035                         mh = mt = m;
2036                         padlen = ri->iri_pad;
2037                 } else {
2038                         flags = M_EXT;
2039                         mt->m_next = m;
2040                         mt = m;
2041                         /* assuming padding is only on the first fragment */
2042                         padlen = 0;
2043                 }
2044                 sd->ifsd_m = NULL;
2045                 cl = sd->ifsd_cl;
2046                 sd->ifsd_cl = NULL;
2047
2048                 /* Can these two be made one ? */
2049                 m_init(m, M_NOWAIT, MT_DATA, flags);
2050                 m_cljset(m, cl, cltype);
2051                 /*
2052                  * These must follow m_init and m_cljset
2053                  */
2054                 m->m_data += padlen;
2055                 ri->iri_len -= padlen;
2056                 m->m_len = ri->iri_frags[i].irf_len;
2057         } while (++i < ri->iri_nfrags);
2058
2059         return (mh);
2060 }
2061
2062 /*
2063  * Process one software descriptor
2064  */
2065 static struct mbuf *
2066 iflib_rxd_pkt_get(iflib_rxq_t rxq, if_rxd_info_t ri)
2067 {
2068         struct mbuf *m;
2069         iflib_rxsd_t sd;
2070
2071         /* should I merge this back in now that the two paths are basically duplicated? */
2072         if (ri->iri_nfrags == 1 &&
2073             ri->iri_frags[0].irf_len <= IFLIB_RX_COPY_THRESH) {
2074                 sd = rxd_frag_to_sd(rxq, &ri->iri_frags[0], NULL, FALSE);
2075                 m = sd->ifsd_m;
2076                 sd->ifsd_m = NULL;
2077                 m_init(m, M_NOWAIT, MT_DATA, M_PKTHDR);
2078                 memcpy(m->m_data, sd->ifsd_cl, ri->iri_len);
2079                 m->m_len = ri->iri_frags[0].irf_len;
2080        } else {
2081                 m = assemble_segments(rxq, ri);
2082         }
2083         m->m_pkthdr.len = ri->iri_len;
2084         m->m_pkthdr.rcvif = ri->iri_ifp;
2085         m->m_flags |= ri->iri_flags;
2086         m->m_pkthdr.ether_vtag = ri->iri_vtag;
2087         m->m_pkthdr.flowid = ri->iri_flowid;
2088         M_HASHTYPE_SET(m, ri->iri_rsstype);
2089         m->m_pkthdr.csum_flags = ri->iri_csum_flags;
2090         m->m_pkthdr.csum_data = ri->iri_csum_data;
2091         return (m);
2092 }
2093
2094 static bool
2095 iflib_rxeof(iflib_rxq_t rxq, int budget)
2096 {
2097         if_ctx_t ctx = rxq->ifr_ctx;
2098         if_shared_ctx_t sctx = ctx->ifc_sctx;
2099         if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
2100         int avail, i;
2101         uint16_t *cidxp;
2102         struct if_rxd_info ri;
2103         int err, budget_left, rx_bytes, rx_pkts;
2104         iflib_fl_t fl;
2105         struct ifnet *ifp;
2106         int lro_enabled;
2107         /*
2108          * XXX early demux data packets so that if_input processing only handles
2109          * acks in interrupt context
2110          */
2111         struct mbuf *m, *mh, *mt;
2112
2113         if (netmap_rx_irq(ctx->ifc_ifp, rxq->ifr_id, &budget)) {
2114                 return (FALSE);
2115         }
2116
2117         mh = mt = NULL;
2118         MPASS(budget > 0);
2119         rx_pkts = rx_bytes = 0;
2120         if (sctx->isc_flags & IFLIB_HAS_RXCQ)
2121                 cidxp = &rxq->ifr_cq_cidx;
2122         else
2123                 cidxp = &rxq->ifr_fl[0].ifl_cidx;
2124         if ((avail = iflib_rxd_avail(ctx, rxq, *cidxp, budget)) == 0) {
2125                 for (i = 0, fl = &rxq->ifr_fl[0]; i < sctx->isc_nfl; i++, fl++)
2126                         __iflib_fl_refill_lt(ctx, fl, budget + 8);
2127                 DBG_COUNTER_INC(rx_unavail);
2128                 return (false);
2129         }
2130
2131         for (budget_left = budget; (budget_left > 0) && (avail > 0); budget_left--, avail--) {
2132                 if (__predict_false(!CTX_ACTIVE(ctx))) {
2133                         DBG_COUNTER_INC(rx_ctx_inactive);
2134                         break;
2135                 }
2136                 /*
2137                  * Reset client set fields to their default values
2138                  */
2139                 bzero(&ri, sizeof(ri));
2140                 ri.iri_qsidx = rxq->ifr_id;
2141                 ri.iri_cidx = *cidxp;
2142                 ri.iri_ifp = ctx->ifc_ifp;
2143                 ri.iri_frags = rxq->ifr_frags;
2144                 err = ctx->isc_rxd_pkt_get(ctx->ifc_softc, &ri);
2145
2146                 /* in lieu of handling correctly - make sure it isn't being unhandled */
2147                 MPASS(err == 0);
2148                 if (sctx->isc_flags & IFLIB_HAS_RXCQ) {
2149                         *cidxp = ri.iri_cidx;
2150                         /* Update our consumer index */
2151                         while (rxq->ifr_cq_cidx >= scctx->isc_nrxd[0]) {
2152                                 rxq->ifr_cq_cidx -= scctx->isc_nrxd[0];
2153                                 rxq->ifr_cq_gen = 0;
2154                         }
2155                         /* was this only a completion queue message? */
2156                         if (__predict_false(ri.iri_nfrags == 0))
2157                                 continue;
2158                 }
2159                 MPASS(ri.iri_nfrags != 0);
2160                 MPASS(ri.iri_len != 0);
2161
2162                 /* will advance the cidx on the corresponding free lists */
2163                 m = iflib_rxd_pkt_get(rxq, &ri);
2164                 if (avail == 0 && budget_left)
2165                         avail = iflib_rxd_avail(ctx, rxq, *cidxp, budget_left);
2166
2167                 if (__predict_false(m == NULL)) {
2168                         DBG_COUNTER_INC(rx_mbuf_null);
2169                         continue;
2170                 }
2171                 /* imm_pkt: -- cxgb */
2172                 if (mh == NULL)
2173                         mh = mt = m;
2174                 else {
2175                         mt->m_nextpkt = m;
2176                         mt = m;
2177                 }
2178         }
2179         /* make sure that we can refill faster than drain */
2180         for (i = 0, fl = &rxq->ifr_fl[0]; i < sctx->isc_nfl; i++, fl++)
2181                 __iflib_fl_refill_lt(ctx, fl, budget + 8);
2182
2183         ifp = ctx->ifc_ifp;
2184         lro_enabled = (if_getcapenable(ifp) & IFCAP_LRO);
2185         while (mh != NULL) {
2186                 m = mh;
2187                 mh = mh->m_nextpkt;
2188                 m->m_nextpkt = NULL;
2189                 rx_bytes += m->m_pkthdr.len;
2190                 rx_pkts++;
2191 #if defined(INET6) || defined(INET)
2192                 if (lro_enabled && tcp_lro_rx(&rxq->ifr_lc, m, 0) == 0)
2193                         continue;
2194 #endif
2195                 DBG_COUNTER_INC(rx_if_input);
2196                 ifp->if_input(ifp, m);
2197         }
2198
2199         if_inc_counter(ifp, IFCOUNTER_IBYTES, rx_bytes);
2200         if_inc_counter(ifp, IFCOUNTER_IPACKETS, rx_pkts);
2201
2202         /*
2203          * Flush any outstanding LRO work
2204          */
2205 #if defined(INET6) || defined(INET)
2206         tcp_lro_flush_all(&rxq->ifr_lc);
2207 #endif
2208         if (avail)
2209                 return true;
2210         return (iflib_rxd_avail(ctx, rxq, *cidxp, 1));
2211 }
2212
2213 #define M_CSUM_FLAGS(m) ((m)->m_pkthdr.csum_flags)
2214 #define M_HAS_VLANTAG(m) (m->m_flags & M_VLANTAG)
2215 #define TXQ_MAX_DB_DEFERRED(size) (size >> 5)
2216 #define TXQ_MAX_DB_CONSUMED(size) (size >> 4)
2217
2218 static __inline void
2219 iflib_txd_db_check(if_ctx_t ctx, iflib_txq_t txq, int ring)
2220 {
2221         uint32_t dbval;
2222
2223         if (ring || txq->ift_db_pending >=
2224             TXQ_MAX_DB_DEFERRED(txq->ift_size)) {
2225
2226                 /* the lock will only ever be contended in the !min_latency case */
2227                 if (!TXDB_TRYLOCK(txq))
2228                         return;
2229                 dbval = txq->ift_npending ? txq->ift_npending : txq->ift_pidx;
2230                 ctx->isc_txd_flush(ctx->ifc_softc, txq->ift_id, dbval);
2231                 txq->ift_db_pending = txq->ift_npending = 0;
2232                 TXDB_UNLOCK(txq);
2233         }
2234 }
2235
2236 static void
2237 iflib_txd_deferred_db_check(void * arg)
2238 {
2239         iflib_txq_t txq = arg;
2240
2241         /* simple non-zero boolean so use bitwise OR */
2242         if ((txq->ift_db_pending | txq->ift_npending) &&
2243             txq->ift_db_pending >= txq->ift_db_pending_queued)
2244                 iflib_txd_db_check(txq->ift_ctx, txq, TRUE);
2245         txq->ift_db_pending_queued = 0;
2246         if (ifmp_ring_is_stalled(txq->ift_br[0]))
2247                 iflib_txq_check_drain(txq, 4);
2248 }
2249
2250 #ifdef PKT_DEBUG
2251 static void
2252 print_pkt(if_pkt_info_t pi)
2253 {
2254         printf("pi len:  %d qsidx: %d nsegs: %d ndescs: %d flags: %x pidx: %d\n",
2255                pi->ipi_len, pi->ipi_qsidx, pi->ipi_nsegs, pi->ipi_ndescs, pi->ipi_flags, pi->ipi_pidx);
2256         printf("pi new_pidx: %d csum_flags: %lx tso_segsz: %d mflags: %x vtag: %d\n",
2257                pi->ipi_new_pidx, pi->ipi_csum_flags, pi->ipi_tso_segsz, pi->ipi_mflags, pi->ipi_vtag);
2258         printf("pi etype: %d ehdrlen: %d ip_hlen: %d ipproto: %d\n",
2259                pi->ipi_etype, pi->ipi_ehdrlen, pi->ipi_ip_hlen, pi->ipi_ipproto);
2260 }
2261 #endif
2262
2263 #define IS_TSO4(pi) ((pi)->ipi_csum_flags & CSUM_IP_TSO)
2264 #define IS_TSO6(pi) ((pi)->ipi_csum_flags & CSUM_IP6_TSO)
2265
2266 static int
2267 iflib_parse_header(iflib_txq_t txq, if_pkt_info_t pi, struct mbuf **mp)
2268 {
2269         if_shared_ctx_t sctx = txq->ift_ctx->ifc_sctx;
2270         struct ether_vlan_header *eh;
2271         struct mbuf *m, *n;
2272
2273         n = m = *mp;
2274         if ((sctx->isc_flags & IFLIB_NEED_SCRATCH) &&
2275             M_WRITABLE(m) == 0) {
2276                 if ((m = m_dup(m, M_NOWAIT)) == NULL) {
2277                         return (ENOMEM);
2278                 } else {
2279                         m_freem(*mp);
2280                         n = *mp = m;
2281                 }
2282         }
2283
2284         /*
2285          * Determine where frame payload starts.
2286          * Jump over vlan headers if already present,
2287          * helpful for QinQ too.
2288          */
2289         if (__predict_false(m->m_len < sizeof(*eh))) {
2290                 txq->ift_pullups++;
2291                 if (__predict_false((m = m_pullup(m, sizeof(*eh))) == NULL))
2292                         return (ENOMEM);
2293         }
2294         eh = mtod(m, struct ether_vlan_header *);
2295         if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
2296                 pi->ipi_etype = ntohs(eh->evl_proto);
2297                 pi->ipi_ehdrlen = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
2298         } else {
2299                 pi->ipi_etype = ntohs(eh->evl_encap_proto);
2300                 pi->ipi_ehdrlen = ETHER_HDR_LEN;
2301         }
2302
2303         switch (pi->ipi_etype) {
2304 #ifdef INET
2305         case ETHERTYPE_IP:
2306         {
2307                 struct ip *ip = NULL;
2308                 struct tcphdr *th = NULL;
2309                 int minthlen;
2310
2311                 minthlen = min(m->m_pkthdr.len, pi->ipi_ehdrlen + sizeof(*ip) + sizeof(*th));
2312                 if (__predict_false(m->m_len < minthlen)) {
2313                         /*
2314                          * if this code bloat is causing too much of a hit
2315                          * move it to a separate function and mark it noinline
2316                          */
2317                         if (m->m_len == pi->ipi_ehdrlen) {
2318                                 n = m->m_next;
2319                                 MPASS(n);
2320                                 if (n->m_len >= sizeof(*ip))  {
2321                                         ip = (struct ip *)n->m_data;
2322                                         if (n->m_len >= (ip->ip_hl << 2) + sizeof(*th))
2323                                                 th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2324                                 } else {
2325                                         txq->ift_pullups++;
2326                                         if (__predict_false((m = m_pullup(m, minthlen)) == NULL))
2327                                                 return (ENOMEM);
2328                                         ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
2329                                 }
2330                         } else {
2331                                 txq->ift_pullups++;
2332                                 if (__predict_false((m = m_pullup(m, minthlen)) == NULL))
2333                                         return (ENOMEM);
2334                                 ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
2335                                 if (m->m_len >= (ip->ip_hl << 2) + sizeof(*th))
2336                                         th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2337                         }
2338                 } else {
2339                         ip = (struct ip *)(m->m_data + pi->ipi_ehdrlen);
2340                         if (m->m_len >= (ip->ip_hl << 2) + sizeof(*th))
2341                                 th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2342                 }
2343                 pi->ipi_ip_hlen = ip->ip_hl << 2;
2344                 pi->ipi_ipproto = ip->ip_p;
2345                 pi->ipi_flags |= IPI_TX_IPV4;
2346
2347                 if (pi->ipi_csum_flags & CSUM_IP)
2348                        ip->ip_sum = 0;
2349
2350                 if (pi->ipi_ipproto == IPPROTO_TCP) {
2351                         if (__predict_false(th == NULL)) {
2352                                 txq->ift_pullups++;
2353                                 if (__predict_false((m = m_pullup(m, (ip->ip_hl << 2) + sizeof(*th))) == NULL))
2354                                         return (ENOMEM);
2355                                 th = (struct tcphdr *)((caddr_t)ip + pi->ipi_ip_hlen);
2356                         }
2357                         pi->ipi_tcp_hflags = th->th_flags;
2358                         pi->ipi_tcp_hlen = th->th_off << 2;
2359                         pi->ipi_tcp_seq = th->th_seq;
2360                 }
2361                 if (IS_TSO4(pi)) {
2362                         if (__predict_false(ip->ip_p != IPPROTO_TCP))
2363                                 return (ENXIO);
2364                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
2365                                                ip->ip_dst.s_addr, htons(IPPROTO_TCP));
2366                         pi->ipi_tso_segsz = m->m_pkthdr.tso_segsz;
2367                         if (sctx->isc_flags & IFLIB_TSO_INIT_IP) {
2368                                 ip->ip_sum = 0;
2369                                 ip->ip_len = htons(pi->ipi_ip_hlen + pi->ipi_tcp_hlen + pi->ipi_tso_segsz);
2370                         }
2371                 }
2372                 break;
2373         }
2374 #endif
2375 #ifdef INET6
2376         case ETHERTYPE_IPV6:
2377         {
2378                 struct ip6_hdr *ip6 = (struct ip6_hdr *)(m->m_data + pi->ipi_ehdrlen);
2379                 struct tcphdr *th;
2380                 pi->ipi_ip_hlen = sizeof(struct ip6_hdr);
2381
2382                 if (__predict_false(m->m_len < pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) {
2383                         if (__predict_false((m = m_pullup(m, pi->ipi_ehdrlen + sizeof(struct ip6_hdr))) == NULL))
2384                                 return (ENOMEM);
2385                 }
2386                 th = (struct tcphdr *)((caddr_t)ip6 + pi->ipi_ip_hlen);
2387
2388                 /* XXX-BZ this will go badly in case of ext hdrs. */
2389                 pi->ipi_ipproto = ip6->ip6_nxt;
2390                 pi->ipi_flags |= IPI_TX_IPV6;
2391
2392                 if (pi->ipi_ipproto == IPPROTO_TCP) {
2393                         if (__predict_false(m->m_len < pi->ipi_ehdrlen + sizeof(struct ip6_hdr) + sizeof(struct tcphdr))) {
2394                                 if (__predict_false((m = m_pullup(m, pi->ipi_ehdrlen + sizeof(struct ip6_hdr) + sizeof(struct tcphdr))) == NULL))
2395                                         return (ENOMEM);
2396                         }
2397                         pi->ipi_tcp_hflags = th->th_flags;
2398                         pi->ipi_tcp_hlen = th->th_off << 2;
2399                 }
2400                 if (IS_TSO6(pi)) {
2401
2402                         if (__predict_false(ip6->ip6_nxt != IPPROTO_TCP))
2403                                 return (ENXIO);
2404                         /*
2405                          * The corresponding flag is set by the stack in the IPv4
2406                          * TSO case, but not in IPv6 (at least in FreeBSD 10.2).
2407                          * So, set it here because the rest of the flow requires it.
2408                          */
2409                         pi->ipi_csum_flags |= CSUM_TCP_IPV6;
2410                         th->th_sum = in6_cksum_pseudo(ip6, 0, IPPROTO_TCP, 0);
2411                         pi->ipi_tso_segsz = m->m_pkthdr.tso_segsz;
2412                 }
2413                 break;
2414         }
2415 #endif
2416         default:
2417                 pi->ipi_csum_flags &= ~CSUM_OFFLOAD;
2418                 pi->ipi_ip_hlen = 0;
2419                 break;
2420         }
2421         *mp = m;
2422
2423         return (0);
2424 }
2425
2426 static  __noinline  struct mbuf *
2427 collapse_pkthdr(struct mbuf *m0)
2428 {
2429         struct mbuf *m, *m_next, *tmp;
2430
2431         m = m0;
2432         m_next = m->m_next;
2433         while (m_next != NULL && m_next->m_len == 0) {
2434                 m = m_next;
2435                 m->m_next = NULL;
2436                 m_free(m);
2437                 m_next = m_next->m_next;
2438         }
2439         m = m0;
2440         m->m_next = m_next;
2441         if ((m_next->m_flags & M_EXT) == 0) {
2442                 m = m_defrag(m, M_NOWAIT);
2443         } else {
2444                 tmp = m_next->m_next;
2445                 memcpy(m_next, m, MPKTHSIZE);
2446                 m = m_next;
2447                 m->m_next = tmp;
2448         }
2449         return (m);
2450 }
2451
2452 /*
2453  * If dodgy hardware rejects the scatter gather chain we've handed it
2454  * we'll need to remove the mbuf chain from ifsg_m[] before we can add the
2455  * m_defrag'd mbufs
2456  */
2457 static __noinline struct mbuf *
2458 iflib_remove_mbuf(iflib_txq_t txq)
2459 {
2460         int ntxd, i, pidx;
2461         struct mbuf *m, *mh, **ifsd_m;
2462
2463         pidx = txq->ift_pidx;
2464         ifsd_m = txq->ift_sds.ifsd_m;
2465         ntxd = txq->ift_size;
2466         mh = m = ifsd_m[pidx];
2467         ifsd_m[pidx] = NULL;
2468 #if MEMORY_LOGGING
2469         txq->ift_dequeued++;
2470 #endif
2471         i = 1;
2472
2473         while (m) {
2474                 ifsd_m[(pidx + i) & (ntxd -1)] = NULL;
2475 #if MEMORY_LOGGING
2476                 txq->ift_dequeued++;
2477 #endif
2478                 m = m->m_next;
2479                 i++;
2480         }
2481         return (mh);
2482 }
2483
2484 static int
2485 iflib_busdma_load_mbuf_sg(iflib_txq_t txq, bus_dma_tag_t tag, bus_dmamap_t map,
2486                           struct mbuf **m0, bus_dma_segment_t *segs, int *nsegs,
2487                           int max_segs, int flags)
2488 {
2489         if_ctx_t ctx;
2490         if_shared_ctx_t         sctx;
2491         if_softc_ctx_t          scctx;
2492         int i, next, pidx, mask, err, maxsegsz, ntxd, count;
2493         struct mbuf *m, *tmp, **ifsd_m, **mp;
2494
2495         m = *m0;
2496
2497         /*
2498          * Please don't ever do this
2499          */
2500         if (__predict_false(m->m_len == 0))
2501                 *m0 = m = collapse_pkthdr(m);
2502
2503         ctx = txq->ift_ctx;
2504         sctx = ctx->ifc_sctx;
2505         scctx = &ctx->ifc_softc_ctx;
2506         ifsd_m = txq->ift_sds.ifsd_m;
2507         ntxd = txq->ift_size;
2508         pidx = txq->ift_pidx;
2509         if (map != NULL) {
2510                 uint8_t *ifsd_flags = txq->ift_sds.ifsd_flags;
2511
2512                 err = bus_dmamap_load_mbuf_sg(tag, map,
2513                                               *m0, segs, nsegs, BUS_DMA_NOWAIT);
2514                 if (err)
2515                         return (err);
2516                 ifsd_flags[pidx] |= TX_SW_DESC_MAPPED;
2517                 i = 0;
2518                 next = pidx;
2519                 mask = (txq->ift_size-1);
2520                 m = *m0;
2521                 do {
2522                         mp = &ifsd_m[next];
2523                         *mp = m;
2524                         m = m->m_next;
2525                         if (__predict_false((*mp)->m_len == 0)) {
2526                                 m_free(*mp);
2527                                 *mp = NULL;
2528                         } else
2529                                 next = (pidx + i) & (ntxd-1);
2530                 } while (m != NULL);
2531         } else {
2532                 int buflen, sgsize, max_sgsize;
2533                 vm_offset_t vaddr;
2534                 vm_paddr_t curaddr;
2535
2536                 count = i = 0;
2537                 maxsegsz = sctx->isc_tx_maxsize;
2538                 m = *m0;
2539                 do {
2540                         if (__predict_false(m->m_len <= 0)) {
2541                                 tmp = m;
2542                                 m = m->m_next;
2543                                 tmp->m_next = NULL;
2544                                 m_free(tmp);
2545                                 continue;
2546                         }
2547                         buflen = m->m_len;
2548                         vaddr = (vm_offset_t)m->m_data;
2549                         /*
2550                          * see if we can't be smarter about physically
2551                          * contiguous mappings
2552                          */
2553                         next = (pidx + count) & (ntxd-1);
2554                         MPASS(ifsd_m[next] == NULL);
2555 #if MEMORY_LOGGING
2556                         txq->ift_enqueued++;
2557 #endif
2558                         ifsd_m[next] = m;
2559                         while (buflen > 0) {
2560                                 max_sgsize = MIN(buflen, maxsegsz);
2561                                 curaddr = pmap_kextract(vaddr);
2562                                 sgsize = PAGE_SIZE - (curaddr & PAGE_MASK);
2563                                 sgsize = MIN(sgsize, max_sgsize);
2564                                 segs[i].ds_addr = curaddr;
2565                                 segs[i].ds_len = sgsize;
2566                                 vaddr += sgsize;
2567                                 buflen -= sgsize;
2568                                 i++;
2569                                 if (i >= max_segs)
2570                                         goto err;
2571                         }
2572                         count++;
2573                         tmp = m;
2574                         m = m->m_next;
2575                 } while (m != NULL);
2576                 *nsegs = i;
2577         }
2578         return (0);
2579 err:
2580         *m0 = iflib_remove_mbuf(txq);
2581         return (EFBIG);
2582 }
2583
2584 static int
2585 iflib_encap(iflib_txq_t txq, struct mbuf **m_headp)
2586 {
2587         if_ctx_t                ctx;
2588         if_shared_ctx_t         sctx;
2589         if_softc_ctx_t          scctx;
2590         bus_dma_segment_t       *segs;
2591         struct mbuf             *m_head;
2592         bus_dmamap_t            map;
2593         struct if_pkt_info      pi;
2594         int remap = 0;
2595         int err, nsegs, ndesc, max_segs, pidx, cidx, next, ntxd;
2596         bus_dma_tag_t desc_tag;
2597
2598         segs = txq->ift_segs;
2599         ctx = txq->ift_ctx;
2600         sctx = ctx->ifc_sctx;
2601         scctx = &ctx->ifc_softc_ctx;
2602         segs = txq->ift_segs;
2603         ntxd = txq->ift_size;
2604         m_head = *m_headp;
2605         map = NULL;
2606
2607         /*
2608          * If we're doing TSO the next descriptor to clean may be quite far ahead
2609          */
2610         cidx = txq->ift_cidx;
2611         pidx = txq->ift_pidx;
2612         next = (cidx + CACHE_PTR_INCREMENT) & (ntxd-1);
2613
2614         /* prefetch the next cache line of mbuf pointers and flags */
2615         prefetch(&txq->ift_sds.ifsd_m[next]);
2616         if (txq->ift_sds.ifsd_map != NULL) {
2617                 prefetch(&txq->ift_sds.ifsd_map[next]);
2618                 map = txq->ift_sds.ifsd_map[pidx];
2619                 next = (cidx + CACHE_LINE_SIZE) & (ntxd-1);
2620                 prefetch(&txq->ift_sds.ifsd_flags[next]);
2621         }
2622
2623
2624         if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
2625                 desc_tag = txq->ift_tso_desc_tag;
2626                 max_segs = scctx->isc_tx_tso_segments_max;
2627         } else {
2628                 desc_tag = txq->ift_desc_tag;
2629                 max_segs = scctx->isc_tx_nsegments;
2630         }
2631         m_head = *m_headp;
2632         bzero(&pi, sizeof(pi));
2633         pi.ipi_len = m_head->m_pkthdr.len;
2634         pi.ipi_mflags = (m_head->m_flags & (M_VLANTAG|M_BCAST|M_MCAST));
2635         pi.ipi_csum_flags = m_head->m_pkthdr.csum_flags;
2636         pi.ipi_vtag = (m_head->m_flags & M_VLANTAG) ? m_head->m_pkthdr.ether_vtag : 0;
2637         pi.ipi_pidx = pidx;
2638         pi.ipi_qsidx = txq->ift_id;
2639
2640         /* deliberate bitwise OR to make one condition */
2641         if (__predict_true((pi.ipi_csum_flags | pi.ipi_vtag))) {
2642                 if (__predict_false((err = iflib_parse_header(txq, &pi, m_headp)) != 0))
2643                         return (err);
2644                 m_head = *m_headp;
2645         }
2646
2647 retry:
2648         err = iflib_busdma_load_mbuf_sg(txq, desc_tag, map, m_headp, segs, &nsegs, max_segs, BUS_DMA_NOWAIT);
2649 defrag:
2650         if (__predict_false(err)) {
2651                 switch (err) {
2652                 case EFBIG:
2653                         /* try collapse once and defrag once */
2654                         if (remap == 0)
2655                                 m_head = m_collapse(*m_headp, M_NOWAIT, max_segs);
2656                         if (remap == 1)
2657                                 m_head = m_defrag(*m_headp, M_NOWAIT);
2658                         remap++;
2659                         if (__predict_false(m_head == NULL))
2660                                 goto defrag_failed;
2661                         txq->ift_mbuf_defrag++;
2662                         *m_headp = m_head;
2663                         goto retry;
2664                         break;
2665                 case ENOMEM:
2666                         txq->ift_no_tx_dma_setup++;
2667                         break;
2668                 default:
2669                         txq->ift_no_tx_dma_setup++;
2670                         m_freem(*m_headp);
2671                         DBG_COUNTER_INC(tx_frees);
2672                         *m_headp = NULL;
2673                         break;
2674                 }
2675                 txq->ift_map_failed++;
2676                 DBG_COUNTER_INC(encap_load_mbuf_fail);
2677                 return (err);
2678         }
2679
2680         /*
2681          * XXX assumes a 1 to 1 relationship between segments and
2682          *        descriptors - this does not hold true on all drivers, e.g.
2683          *        cxgb
2684          */
2685         if (__predict_false(nsegs + 2 > TXQ_AVAIL(txq))) {
2686                 txq->ift_no_desc_avail++;
2687                 if (map != NULL)
2688                         bus_dmamap_unload(desc_tag, map);
2689                 DBG_COUNTER_INC(encap_txq_avail_fail);
2690                 if ((txq->ift_task.gt_task.ta_flags & TASK_ENQUEUED) == 0)
2691                         GROUPTASK_ENQUEUE(&txq->ift_task);
2692                 return (ENOBUFS);
2693         }
2694         pi.ipi_segs = segs;
2695         pi.ipi_nsegs = nsegs;
2696
2697         MPASS(pidx >= 0 && pidx < txq->ift_size);
2698 #ifdef PKT_DEBUG
2699         print_pkt(&pi);
2700 #endif
2701         if ((err = ctx->isc_txd_encap(ctx->ifc_softc, &pi)) == 0) {
2702                 bus_dmamap_sync(txq->ift_ifdi->idi_tag, txq->ift_ifdi->idi_map,
2703                                                 BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2704
2705                 DBG_COUNTER_INC(tx_encap);
2706                 MPASS(pi.ipi_new_pidx >= 0 &&
2707                     pi.ipi_new_pidx < txq->ift_size);
2708
2709                 ndesc = pi.ipi_new_pidx - pi.ipi_pidx;
2710                 if (pi.ipi_new_pidx < pi.ipi_pidx) {
2711                         ndesc += txq->ift_size;
2712                         txq->ift_gen = 1;
2713                 }
2714                 /*
2715                  * drivers can need as many as 
2716                  * two sentinels
2717                  */
2718                 MPASS(ndesc <= pi.ipi_nsegs + 2);
2719                 MPASS(pi.ipi_new_pidx != pidx);
2720                 MPASS(ndesc > 0);
2721                 txq->ift_in_use += ndesc;
2722                 /*
2723                  * We update the last software descriptor again here because there may
2724                  * be a sentinel and/or there may be more mbufs than segments
2725                  */
2726                 txq->ift_pidx = pi.ipi_new_pidx;
2727                 txq->ift_npending += pi.ipi_ndescs;
2728         } else if (__predict_false(err == EFBIG && remap < 2)) {
2729                 *m_headp = m_head = iflib_remove_mbuf(txq);
2730                 remap = 1;
2731                 txq->ift_txd_encap_efbig++;
2732                 goto defrag;
2733         } else
2734                 DBG_COUNTER_INC(encap_txd_encap_fail);
2735         return (err);
2736
2737 defrag_failed:
2738         txq->ift_mbuf_defrag_failed++;
2739         txq->ift_map_failed++;
2740         m_freem(*m_headp);
2741         DBG_COUNTER_INC(tx_frees);
2742         *m_headp = NULL;
2743         return (ENOMEM);
2744 }
2745
2746 /* forward compatibility for cxgb */
2747 #define FIRST_QSET(ctx) 0
2748
2749 #define NTXQSETS(ctx) ((ctx)->ifc_softc_ctx.isc_ntxqsets)
2750 #define NRXQSETS(ctx) ((ctx)->ifc_softc_ctx.isc_nrxqsets)
2751 #define QIDX(ctx, m) ((((m)->m_pkthdr.flowid & ctx->ifc_softc_ctx.isc_rss_table_mask) % NTXQSETS(ctx)) + FIRST_QSET(ctx))
2752 #define DESC_RECLAIMABLE(q) ((int)((q)->ift_processed - (q)->ift_cleaned - (q)->ift_ctx->ifc_softc_ctx.isc_tx_nsegments))
2753 #define RECLAIM_THRESH(ctx) ((ctx)->ifc_sctx->isc_tx_reclaim_thresh)
2754 #define MAX_TX_DESC(ctx) ((ctx)->ifc_softc_ctx.isc_tx_tso_segments_max)
2755
2756
2757
2758 /* if there are more than TXQ_MIN_OCCUPANCY packets pending we consider deferring
2759  * doorbell writes
2760  *
2761  * ORing with 2 assures that min occupancy is never less than 2 without any conditional logic
2762  */
2763 #define TXQ_MIN_OCCUPANCY(size) ((size >> 6)| 0x2)
2764
2765 static inline int
2766 iflib_txq_min_occupancy(iflib_txq_t txq)
2767 {
2768         if_ctx_t ctx;
2769
2770         ctx = txq->ift_ctx;
2771         return (get_inuse(txq->ift_size, txq->ift_cidx, txq->ift_pidx,
2772             txq->ift_gen) < TXQ_MIN_OCCUPANCY(txq->ift_size) +
2773             MAX_TX_DESC(ctx));
2774 }
2775
2776 static void
2777 iflib_tx_desc_free(iflib_txq_t txq, int n)
2778 {
2779         int hasmap;
2780         uint32_t qsize, cidx, mask, gen;
2781         struct mbuf *m, **ifsd_m;
2782         uint8_t *ifsd_flags;
2783         bus_dmamap_t *ifsd_map;
2784
2785         cidx = txq->ift_cidx;
2786         gen = txq->ift_gen;
2787         qsize = txq->ift_size;
2788         mask = qsize-1;
2789         hasmap = txq->ift_sds.ifsd_map != NULL;
2790         ifsd_flags = txq->ift_sds.ifsd_flags;
2791         ifsd_m = txq->ift_sds.ifsd_m;
2792         ifsd_map = txq->ift_sds.ifsd_map;
2793
2794         while (n--) {
2795                 prefetch(ifsd_m[(cidx + 3) & mask]);
2796                 prefetch(ifsd_m[(cidx + 4) & mask]);
2797
2798                 if (ifsd_m[cidx] != NULL) {
2799                         prefetch(&ifsd_m[(cidx + CACHE_PTR_INCREMENT) & mask]);
2800                         prefetch(&ifsd_flags[(cidx + CACHE_PTR_INCREMENT) & mask]);
2801                         if (hasmap && (ifsd_flags[cidx] & TX_SW_DESC_MAPPED)) {
2802                                 /*
2803                                  * does it matter if it's not the TSO tag? If so we'll
2804                                  * have to add the type to flags
2805                                  */
2806                                 bus_dmamap_unload(txq->ift_desc_tag, ifsd_map[cidx]);
2807                                 ifsd_flags[cidx] &= ~TX_SW_DESC_MAPPED;
2808                         }
2809                         if ((m = ifsd_m[cidx]) != NULL) {
2810                                 /* XXX we don't support any drivers that batch packets yet */
2811                                 MPASS(m->m_nextpkt == NULL);
2812
2813                                 m_free(m);
2814                                 ifsd_m[cidx] = NULL;
2815 #if MEMORY_LOGGING
2816                                 txq->ift_dequeued++;
2817 #endif
2818                                 DBG_COUNTER_INC(tx_frees);
2819                         }
2820                 }
2821                 if (__predict_false(++cidx == qsize)) {
2822                         cidx = 0;
2823                         gen = 0;
2824                 }
2825         }
2826         txq->ift_cidx = cidx;
2827         txq->ift_gen = gen;
2828 }
2829
2830 static __inline int
2831 iflib_completed_tx_reclaim(iflib_txq_t txq, int thresh)
2832 {
2833         int reclaim;
2834         if_ctx_t ctx = txq->ift_ctx;
2835
2836         KASSERT(thresh >= 0, ("invalid threshold to reclaim"));
2837         MPASS(thresh /*+ MAX_TX_DESC(txq->ift_ctx) */ < txq->ift_size);
2838
2839         /*
2840          * Need a rate-limiting check so that this isn't called every time
2841          */
2842         iflib_tx_credits_update(ctx, txq);
2843         reclaim = DESC_RECLAIMABLE(txq);
2844
2845         if (reclaim <= thresh /* + MAX_TX_DESC(txq->ift_ctx) */) {
2846 #ifdef INVARIANTS
2847                 if (iflib_verbose_debug) {
2848                         printf("%s processed=%ju cleaned=%ju tx_nsegments=%d reclaim=%d thresh=%d\n", __FUNCTION__,
2849                                txq->ift_processed, txq->ift_cleaned, txq->ift_ctx->ifc_softc_ctx.isc_tx_nsegments,
2850                                reclaim, thresh);
2851
2852                 }
2853 #endif
2854                 return (0);
2855         }
2856         iflib_tx_desc_free(txq, reclaim);
2857         txq->ift_cleaned += reclaim;
2858         txq->ift_in_use -= reclaim;
2859
2860         if (txq->ift_active == FALSE)
2861                 txq->ift_active = TRUE;
2862
2863         return (reclaim);
2864 }
2865
2866 static struct mbuf **
2867 _ring_peek_one(struct ifmp_ring *r, int cidx, int offset)
2868 {
2869
2870         return (__DEVOLATILE(struct mbuf **, &r->items[(cidx + offset) & (r->size-1)]));
2871 }
2872
2873 static void
2874 iflib_txq_check_drain(iflib_txq_t txq, int budget)
2875 {
2876
2877         ifmp_ring_check_drainage(txq->ift_br[0], budget);
2878 }
2879
2880 static uint32_t
2881 iflib_txq_can_drain(struct ifmp_ring *r)
2882 {
2883         iflib_txq_t txq = r->cookie;
2884         if_ctx_t ctx = txq->ift_ctx;
2885
2886         return ((TXQ_AVAIL(txq) > MAX_TX_DESC(ctx) + 2) ||
2887                 ctx->isc_txd_credits_update(ctx->ifc_softc, txq->ift_id, txq->ift_cidx_processed, false));
2888 }
2889
2890 static uint32_t
2891 iflib_txq_drain(struct ifmp_ring *r, uint32_t cidx, uint32_t pidx)
2892 {
2893         iflib_txq_t txq = r->cookie;
2894         if_ctx_t ctx = txq->ift_ctx;
2895         if_t ifp = ctx->ifc_ifp;
2896         struct mbuf **mp, *m;
2897         int i, count, consumed, pkt_sent, bytes_sent, mcast_sent, avail, err, in_use_prev, desc_used;
2898
2899         if (__predict_false(!(if_getdrvflags(ifp) & IFF_DRV_RUNNING) ||
2900                             !LINK_ACTIVE(ctx))) {
2901                 DBG_COUNTER_INC(txq_drain_notready);
2902                 return (0);
2903         }
2904
2905         avail = IDXDIFF(pidx, cidx, r->size);
2906         if (__predict_false(ctx->ifc_flags & IFC_QFLUSH)) {
2907                 DBG_COUNTER_INC(txq_drain_flushing);
2908                 for (i = 0; i < avail; i++) {
2909                         m_free(r->items[(cidx + i) & (r->size-1)]);
2910                         r->items[(cidx + i) & (r->size-1)] = NULL;
2911                 }
2912                 return (avail);
2913         }
2914         iflib_completed_tx_reclaim(txq, RECLAIM_THRESH(ctx));
2915         if (__predict_false(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_OACTIVE)) {
2916                 txq->ift_qstatus = IFLIB_QUEUE_IDLE;
2917                 CALLOUT_LOCK(txq);
2918                 callout_stop(&txq->ift_timer);
2919                 callout_stop(&txq->ift_db_check);
2920                 CALLOUT_UNLOCK(txq);
2921                 DBG_COUNTER_INC(txq_drain_oactive);
2922                 return (0);
2923         }
2924         consumed = mcast_sent = bytes_sent = pkt_sent = 0;
2925         count = MIN(avail, TX_BATCH_SIZE);
2926 #ifdef INVARIANTS
2927         if (iflib_verbose_debug)
2928                 printf("%s avail=%d ifc_flags=%x txq_avail=%d ", __FUNCTION__,
2929                        avail, ctx->ifc_flags, TXQ_AVAIL(txq));
2930 #endif
2931
2932         for (desc_used = i = 0; i < count && TXQ_AVAIL(txq) > MAX_TX_DESC(ctx) + 2; i++) {
2933                 mp = _ring_peek_one(r, cidx, i);
2934                 MPASS(mp != NULL && *mp != NULL);
2935                 in_use_prev = txq->ift_in_use;
2936                 if ((err = iflib_encap(txq, mp)) == ENOBUFS) {
2937                         DBG_COUNTER_INC(txq_drain_encapfail);
2938                         /* no room - bail out */
2939                         break;
2940                 }
2941                 consumed++;
2942                 if (err) {
2943                         DBG_COUNTER_INC(txq_drain_encapfail);
2944                         /* we can't send this packet - skip it */
2945                         continue;
2946                 }
2947                 pkt_sent++;
2948                 m = *mp;
2949                 DBG_COUNTER_INC(tx_sent);
2950                 bytes_sent += m->m_pkthdr.len;
2951                 if (m->m_flags & M_MCAST)
2952                         mcast_sent++;
2953
2954                 txq->ift_db_pending += (txq->ift_in_use - in_use_prev);
2955                 desc_used += (txq->ift_in_use - in_use_prev);
2956                 iflib_txd_db_check(ctx, txq, FALSE);
2957                 ETHER_BPF_MTAP(ifp, m);
2958                 if (__predict_false(!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)))
2959                         break;
2960
2961                 if (desc_used >= TXQ_MAX_DB_CONSUMED(txq->ift_size))
2962                         break;
2963         }
2964
2965         if ((iflib_min_tx_latency || iflib_txq_min_occupancy(txq)) && txq->ift_db_pending)
2966                 iflib_txd_db_check(ctx, txq, TRUE);
2967         else if ((txq->ift_db_pending || TXQ_AVAIL(txq) <= MAX_TX_DESC(ctx) + 2) &&
2968                  (callout_pending(&txq->ift_db_check) == 0)) {
2969                 txq->ift_db_pending_queued = txq->ift_db_pending;
2970                 callout_reset_on(&txq->ift_db_check, 1, iflib_txd_deferred_db_check,
2971                                  txq, txq->ift_db_check.c_cpu);
2972         }
2973         if_inc_counter(ifp, IFCOUNTER_OBYTES, bytes_sent);
2974         if_inc_counter(ifp, IFCOUNTER_OPACKETS, pkt_sent);
2975         if (mcast_sent)
2976                 if_inc_counter(ifp, IFCOUNTER_OMCASTS, mcast_sent);
2977 #ifdef INVARIANTS
2978         if (iflib_verbose_debug)
2979                 printf("consumed=%d\n", consumed);
2980 #endif
2981         return (consumed);
2982 }
2983
2984 static uint32_t
2985 iflib_txq_drain_always(struct ifmp_ring *r)
2986 {
2987         return (1);
2988 }
2989
2990 static uint32_t
2991 iflib_txq_drain_free(struct ifmp_ring *r, uint32_t cidx, uint32_t pidx)
2992 {
2993         int i, avail;
2994         struct mbuf **mp;
2995         iflib_txq_t txq;
2996
2997         txq = r->cookie;
2998
2999         txq->ift_qstatus = IFLIB_QUEUE_IDLE;
3000         CALLOUT_LOCK(txq);
3001         callout_stop(&txq->ift_timer);
3002         callout_stop(&txq->ift_db_check);
3003         CALLOUT_UNLOCK(txq);
3004
3005         avail = IDXDIFF(pidx, cidx, r->size);
3006         for (i = 0; i < avail; i++) {
3007                 mp = _ring_peek_one(r, cidx, i);
3008                 m_freem(*mp);
3009         }
3010         MPASS(ifmp_ring_is_stalled(r) == 0);
3011         return (avail);
3012 }
3013
3014 static void
3015 iflib_ifmp_purge(iflib_txq_t txq)
3016 {
3017         struct ifmp_ring *r;
3018
3019         r = txq->ift_br[0];
3020         r->drain = iflib_txq_drain_free;
3021         r->can_drain = iflib_txq_drain_always;
3022
3023         ifmp_ring_check_drainage(r, r->size);
3024
3025         r->drain = iflib_txq_drain;
3026         r->can_drain = iflib_txq_can_drain;
3027 }
3028
3029 static void
3030 _task_fn_tx(void *context)
3031 {
3032         iflib_txq_t txq = context;
3033         if_ctx_t ctx = txq->ift_ctx;
3034
3035 #ifdef IFLIB_DIAGNOSTICS
3036         txq->ift_cpu_exec_count[curcpu]++;
3037 #endif
3038         if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING))
3039                 return;
3040         ifmp_ring_check_drainage(txq->ift_br[0], TX_BATCH_SIZE);
3041 }
3042
3043 static void
3044 _task_fn_rx(void *context)
3045 {
3046         iflib_rxq_t rxq = context;
3047         if_ctx_t ctx = rxq->ifr_ctx;
3048         bool more;
3049         int rc;
3050
3051 #ifdef IFLIB_DIAGNOSTICS
3052         rxq->ifr_cpu_exec_count[curcpu]++;
3053 #endif
3054         DBG_COUNTER_INC(task_fn_rxs);
3055         if (__predict_false(!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)))
3056                 return;
3057
3058         if ((more = iflib_rxeof(rxq, 16 /* XXX */)) == false) {
3059                 if (ctx->ifc_flags & IFC_LEGACY)
3060                         IFDI_INTR_ENABLE(ctx);
3061                 else {
3062                         DBG_COUNTER_INC(rx_intr_enables);
3063                         rc = IFDI_QUEUE_INTR_ENABLE(ctx, rxq->ifr_id);
3064                         KASSERT(rc != ENOTSUP, ("MSI-X support requires queue_intr_enable, but not implemented in driver"));
3065                 }
3066         }
3067         if (__predict_false(!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING)))
3068                 return;
3069         if (more)
3070                 GROUPTASK_ENQUEUE(&rxq->ifr_task);
3071 }
3072
3073 static void
3074 _task_fn_admin(void *context)
3075 {
3076         if_ctx_t ctx = context;
3077         if_softc_ctx_t sctx = &ctx->ifc_softc_ctx;
3078         iflib_txq_t txq;
3079         int i;
3080
3081         if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING))
3082                 return;
3083
3084         CTX_LOCK(ctx);
3085         for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++) {
3086                 CALLOUT_LOCK(txq);
3087                 callout_stop(&txq->ift_timer);
3088                 CALLOUT_UNLOCK(txq);
3089         }
3090         IFDI_UPDATE_ADMIN_STATUS(ctx);
3091         for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++)
3092                 callout_reset_on(&txq->ift_timer, hz/2, iflib_timer, txq, txq->ift_timer.c_cpu);
3093         IFDI_LINK_INTR_ENABLE(ctx);
3094         CTX_UNLOCK(ctx);
3095
3096         if (LINK_ACTIVE(ctx) == 0)
3097                 return;
3098         for (txq = ctx->ifc_txqs, i = 0; i < sctx->isc_ntxqsets; i++, txq++)
3099                 iflib_txq_check_drain(txq, IFLIB_RESTART_BUDGET);
3100 }
3101
3102
3103 static void
3104 _task_fn_iov(void *context)
3105 {
3106         if_ctx_t ctx = context;
3107
3108         if (!(if_getdrvflags(ctx->ifc_ifp) & IFF_DRV_RUNNING))
3109                 return;
3110
3111         CTX_LOCK(ctx);
3112         IFDI_VFLR_HANDLE(ctx);
3113         CTX_UNLOCK(ctx);
3114 }
3115
3116 static int
3117 iflib_sysctl_int_delay(SYSCTL_HANDLER_ARGS)
3118 {
3119         int err;
3120         if_int_delay_info_t info;
3121         if_ctx_t ctx;
3122
3123         info = (if_int_delay_info_t)arg1;
3124         ctx = info->iidi_ctx;
3125         info->iidi_req = req;
3126         info->iidi_oidp = oidp;
3127         CTX_LOCK(ctx);
3128         err = IFDI_SYSCTL_INT_DELAY(ctx, info);
3129         CTX_UNLOCK(ctx);
3130         return (err);
3131 }
3132
3133 /*********************************************************************
3134  *
3135  *  IFNET FUNCTIONS
3136  *
3137  **********************************************************************/
3138
3139 static void
3140 iflib_if_init_locked(if_ctx_t ctx)
3141 {
3142         iflib_stop(ctx);
3143         iflib_init_locked(ctx);
3144 }
3145
3146
3147 static void
3148 iflib_if_init(void *arg)
3149 {
3150         if_ctx_t ctx = arg;
3151
3152         CTX_LOCK(ctx);
3153         iflib_if_init_locked(ctx);
3154         CTX_UNLOCK(ctx);
3155 }
3156
3157 static int
3158 iflib_if_transmit(if_t ifp, struct mbuf *m)
3159 {
3160         if_ctx_t        ctx = if_getsoftc(ifp);
3161
3162         iflib_txq_t txq;
3163         int err, qidx;
3164
3165         if (__predict_false((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || !LINK_ACTIVE(ctx))) {
3166                 DBG_COUNTER_INC(tx_frees);
3167                 m_freem(m);
3168                 return (ENOBUFS);
3169         }
3170
3171         MPASS(m->m_nextpkt == NULL);
3172         qidx = 0;
3173         if ((NTXQSETS(ctx) > 1) && M_HASHTYPE_GET(m))
3174                 qidx = QIDX(ctx, m);
3175         /*
3176          * XXX calculate buf_ring based on flowid (divvy up bits?)
3177          */
3178         txq = &ctx->ifc_txqs[qidx];
3179
3180 #ifdef DRIVER_BACKPRESSURE
3181         if (txq->ift_closed) {
3182                 while (m != NULL) {
3183                         next = m->m_nextpkt;
3184                         m->m_nextpkt = NULL;
3185                         m_freem(m);
3186                         m = next;
3187                 }
3188                 return (ENOBUFS);
3189         }
3190 #endif
3191 #ifdef notyet
3192         qidx = count = 0;
3193         mp = marr;
3194         next = m;
3195         do {
3196                 count++;
3197                 next = next->m_nextpkt;
3198         } while (next != NULL);
3199
3200         if (count > nitems(marr))
3201                 if ((mp = malloc(count*sizeof(struct mbuf *), M_IFLIB, M_NOWAIT)) == NULL) {
3202                         /* XXX check nextpkt */
3203                         m_freem(m);
3204                         /* XXX simplify for now */
3205                         DBG_COUNTER_INC(tx_frees);
3206                         return (ENOBUFS);
3207                 }
3208         for (next = m, i = 0; next != NULL; i++) {
3209                 mp[i] = next;
3210                 next = next->m_nextpkt;
3211                 mp[i]->m_nextpkt = NULL;
3212         }
3213 #endif
3214         DBG_COUNTER_INC(tx_seen);
3215         err = ifmp_ring_enqueue(txq->ift_br[0], (void **)&m, 1, TX_BATCH_SIZE);
3216
3217         if (err) {
3218                 GROUPTASK_ENQUEUE(&txq->ift_task);
3219                 /* support forthcoming later */
3220 #ifdef DRIVER_BACKPRESSURE
3221                 txq->ift_closed = TRUE;
3222 #endif
3223                 ifmp_ring_check_drainage(txq->ift_br[0], TX_BATCH_SIZE);
3224                 m_freem(m);
3225         } else if (TXQ_AVAIL(txq) < (txq->ift_size >> 1)) {
3226                 GROUPTASK_ENQUEUE(&txq->ift_task);
3227         }
3228
3229         return (err);
3230 }
3231
3232 static void
3233 iflib_if_qflush(if_t ifp)
3234 {
3235         if_ctx_t ctx = if_getsoftc(ifp);
3236         iflib_txq_t txq = ctx->ifc_txqs;
3237         int i;
3238
3239         CTX_LOCK(ctx);
3240         ctx->ifc_flags |= IFC_QFLUSH;
3241         CTX_UNLOCK(ctx);
3242         for (i = 0; i < NTXQSETS(ctx); i++, txq++)
3243                 while (!(ifmp_ring_is_idle(txq->ift_br[0]) || ifmp_ring_is_stalled(txq->ift_br[0])))
3244                         iflib_txq_check_drain(txq, 0);
3245         CTX_LOCK(ctx);
3246         ctx->ifc_flags &= ~IFC_QFLUSH;
3247         CTX_UNLOCK(ctx);
3248
3249         if_qflush(ifp);
3250 }
3251
3252
3253 #define IFCAP_FLAGS (IFCAP_TXCSUM_IPV6 | IFCAP_RXCSUM_IPV6 | IFCAP_HWCSUM | IFCAP_LRO | \
3254                      IFCAP_TSO4 | IFCAP_TSO6 | IFCAP_VLAN_HWTAGGING |   \
3255                      IFCAP_VLAN_MTU | IFCAP_VLAN_HWFILTER | IFCAP_VLAN_HWTSO)
3256
3257 static int
3258 iflib_if_ioctl(if_t ifp, u_long command, caddr_t data)
3259 {
3260         if_ctx_t ctx = if_getsoftc(ifp);
3261         struct ifreq    *ifr = (struct ifreq *)data;
3262 #if defined(INET) || defined(INET6)
3263         struct ifaddr   *ifa = (struct ifaddr *)data;
3264 #endif
3265         bool            avoid_reset = FALSE;
3266         int             err = 0, reinit = 0, bits;
3267
3268         switch (command) {
3269         case SIOCSIFADDR:
3270 #ifdef INET
3271                 if (ifa->ifa_addr->sa_family == AF_INET)
3272                         avoid_reset = TRUE;
3273 #endif
3274 #ifdef INET6
3275                 if (ifa->ifa_addr->sa_family == AF_INET6)
3276                         avoid_reset = TRUE;
3277 #endif
3278                 /*
3279                 ** Calling init results in link renegotiation,
3280                 ** so we avoid doing it when possible.
3281                 */
3282                 if (avoid_reset) {
3283                         if_setflagbits(ifp, IFF_UP,0);
3284                         if (!(if_getdrvflags(ifp)& IFF_DRV_RUNNING))
3285                                 reinit = 1;
3286 #ifdef INET
3287                         if (!(if_getflags(ifp) & IFF_NOARP))
3288                                 arp_ifinit(ifp, ifa);
3289 #endif
3290                 } else
3291                         err = ether_ioctl(ifp, command, data);
3292                 break;
3293         case SIOCSIFMTU:
3294                 CTX_LOCK(ctx);
3295                 if (ifr->ifr_mtu == if_getmtu(ifp)) {
3296                         CTX_UNLOCK(ctx);
3297                         break;
3298                 }
3299                 bits = if_getdrvflags(ifp);
3300                 /* stop the driver and free any clusters before proceeding */
3301                 iflib_stop(ctx);
3302
3303                 if ((err = IFDI_MTU_SET(ctx, ifr->ifr_mtu)) == 0) {
3304                         if (ifr->ifr_mtu > ctx->ifc_max_fl_buf_size)
3305                                 ctx->ifc_flags |= IFC_MULTISEG;
3306                         else
3307                                 ctx->ifc_flags &= ~IFC_MULTISEG;
3308                         err = if_setmtu(ifp, ifr->ifr_mtu);
3309                 }
3310                 iflib_init_locked(ctx);
3311                 if_setdrvflags(ifp, bits);
3312                 CTX_UNLOCK(ctx);
3313                 break;
3314         case SIOCSIFFLAGS:
3315                 CTX_LOCK(ctx);
3316                 if (if_getflags(ifp) & IFF_UP) {
3317                         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3318                                 if ((if_getflags(ifp) ^ ctx->ifc_if_flags) &
3319                                     (IFF_PROMISC | IFF_ALLMULTI)) {
3320                                         err = IFDI_PROMISC_SET(ctx, if_getflags(ifp));
3321                                 }
3322                         } else
3323                                 reinit = 1;
3324                 } else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3325                         iflib_stop(ctx);
3326                 }
3327                 ctx->ifc_if_flags = if_getflags(ifp);
3328                 CTX_UNLOCK(ctx);
3329                 break;
3330
3331                 break;
3332         case SIOCADDMULTI:
3333         case SIOCDELMULTI:
3334                 if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3335                         CTX_LOCK(ctx);
3336                         IFDI_INTR_DISABLE(ctx);
3337                         IFDI_MULTI_SET(ctx);
3338                         IFDI_INTR_ENABLE(ctx);
3339                         CTX_UNLOCK(ctx);
3340                 }
3341                 break;
3342         case SIOCSIFMEDIA:
3343                 CTX_LOCK(ctx);
3344                 IFDI_MEDIA_SET(ctx);
3345                 CTX_UNLOCK(ctx);
3346                 /* falls thru */
3347         case SIOCGIFMEDIA:
3348                 err = ifmedia_ioctl(ifp, ifr, &ctx->ifc_media, command);
3349                 break;
3350         case SIOCGI2C:
3351         {
3352                 struct ifi2creq i2c;
3353
3354                 err = copyin(ifr->ifr_data, &i2c, sizeof(i2c));
3355                 if (err != 0)
3356                         break;
3357                 if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3358                         err = EINVAL;
3359                         break;
3360                 }
3361                 if (i2c.len > sizeof(i2c.data)) {
3362                         err = EINVAL;
3363                         break;
3364                 }
3365
3366                 if ((err = IFDI_I2C_REQ(ctx, &i2c)) == 0)
3367                         err = copyout(&i2c, ifr->ifr_data, sizeof(i2c));
3368                 break;
3369         }
3370         case SIOCSIFCAP:
3371         {
3372                 int mask, setmask;
3373
3374                 mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
3375                 setmask = 0;
3376 #ifdef TCP_OFFLOAD
3377                 setmask |= mask & (IFCAP_TOE4|IFCAP_TOE6);
3378 #endif
3379                 setmask |= (mask & IFCAP_FLAGS);
3380
3381                 if (setmask  & (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6))
3382                         setmask |= (IFCAP_RXCSUM | IFCAP_RXCSUM_IPV6);
3383                 if ((mask & IFCAP_WOL) &&
3384                     (if_getcapabilities(ifp) & IFCAP_WOL) != 0)
3385                         setmask |= (mask & (IFCAP_WOL_MCAST|IFCAP_WOL_MAGIC));
3386                 if_vlancap(ifp);
3387                 /*
3388                  * want to ensure that traffic has stopped before we change any of the flags
3389                  */
3390                 if (setmask) {
3391                         CTX_LOCK(ctx);
3392                         bits = if_getdrvflags(ifp);
3393                         if (bits & IFF_DRV_RUNNING)
3394                                 iflib_stop(ctx);
3395                         if_togglecapenable(ifp, setmask);
3396                         if (bits & IFF_DRV_RUNNING)
3397                                 iflib_init_locked(ctx);
3398                         if_setdrvflags(ifp, bits);
3399                         CTX_UNLOCK(ctx);
3400                 }
3401                 break;
3402             }
3403         case SIOCGPRIVATE_0:
3404         case SIOCSDRVSPEC:
3405         case SIOCGDRVSPEC:
3406                 CTX_LOCK(ctx);
3407                 err = IFDI_PRIV_IOCTL(ctx, command, data);
3408                 CTX_UNLOCK(ctx);
3409                 break;
3410         default:
3411                 err = ether_ioctl(ifp, command, data);
3412                 break;
3413         }
3414         if (reinit)
3415                 iflib_if_init(ctx);
3416         return (err);
3417 }
3418
3419 static uint64_t
3420 iflib_if_get_counter(if_t ifp, ift_counter cnt)
3421 {
3422         if_ctx_t ctx = if_getsoftc(ifp);
3423
3424         return (IFDI_GET_COUNTER(ctx, cnt));
3425 }
3426
3427 /*********************************************************************
3428  *
3429  *  OTHER FUNCTIONS EXPORTED TO THE STACK
3430  *
3431  **********************************************************************/
3432
3433 static void
3434 iflib_vlan_register(void *arg, if_t ifp, uint16_t vtag)
3435 {
3436         if_ctx_t ctx = if_getsoftc(ifp);
3437
3438         if ((void *)ctx != arg)
3439                 return;
3440
3441         if ((vtag == 0) || (vtag > 4095))
3442                 return;
3443
3444         CTX_LOCK(ctx);
3445         IFDI_VLAN_REGISTER(ctx, vtag);
3446         /* Re-init to load the changes */
3447         if (if_getcapenable(ifp) & IFCAP_VLAN_HWFILTER)
3448                 iflib_init_locked(ctx);
3449         CTX_UNLOCK(ctx);
3450 }
3451
3452 static void
3453 iflib_vlan_unregister(void *arg, if_t ifp, uint16_t vtag)
3454 {
3455         if_ctx_t ctx = if_getsoftc(ifp);
3456
3457         if ((void *)ctx != arg)
3458                 return;
3459
3460         if ((vtag == 0) || (vtag > 4095))
3461                 return;
3462
3463         CTX_LOCK(ctx);
3464         IFDI_VLAN_UNREGISTER(ctx, vtag);
3465         /* Re-init to load the changes */
3466         if (if_getcapenable(ifp) & IFCAP_VLAN_HWFILTER)
3467                 iflib_init_locked(ctx);
3468         CTX_UNLOCK(ctx);
3469 }
3470
3471 static void
3472 iflib_led_func(void *arg, int onoff)
3473 {
3474         if_ctx_t ctx = arg;
3475
3476         CTX_LOCK(ctx);
3477         IFDI_LED_FUNC(ctx, onoff);
3478         CTX_UNLOCK(ctx);
3479 }
3480
3481 /*********************************************************************
3482  *
3483  *  BUS FUNCTION DEFINITIONS
3484  *
3485  **********************************************************************/
3486
3487 int
3488 iflib_device_probe(device_t dev)
3489 {
3490         pci_vendor_info_t *ent;
3491
3492         uint16_t        pci_vendor_id, pci_device_id;
3493         uint16_t        pci_subvendor_id, pci_subdevice_id;
3494         uint16_t        pci_rev_id;
3495         if_shared_ctx_t sctx;
3496
3497         if ((sctx = DEVICE_REGISTER(dev)) == NULL || sctx->isc_magic != IFLIB_MAGIC)
3498                 return (ENOTSUP);
3499
3500         pci_vendor_id = pci_get_vendor(dev);
3501         pci_device_id = pci_get_device(dev);
3502         pci_subvendor_id = pci_get_subvendor(dev);
3503         pci_subdevice_id = pci_get_subdevice(dev);
3504         pci_rev_id = pci_get_revid(dev);
3505         if (sctx->isc_parse_devinfo != NULL)
3506                 sctx->isc_parse_devinfo(&pci_device_id, &pci_subvendor_id, &pci_subdevice_id, &pci_rev_id);
3507
3508         ent = sctx->isc_vendor_info;
3509         while (ent->pvi_vendor_id != 0) {
3510                 if (pci_vendor_id != ent->pvi_vendor_id) {
3511                         ent++;
3512                         continue;
3513                 }
3514                 if ((pci_device_id == ent->pvi_device_id) &&
3515                     ((pci_subvendor_id == ent->pvi_subvendor_id) ||
3516                      (ent->pvi_subvendor_id == 0)) &&
3517                     ((pci_subdevice_id == ent->pvi_subdevice_id) ||
3518                      (ent->pvi_subdevice_id == 0)) &&
3519                     ((pci_rev_id == ent->pvi_rev_id) ||
3520                      (ent->pvi_rev_id == 0))) {
3521
3522                         device_set_desc_copy(dev, ent->pvi_name);
3523                         /* this needs to be changed to zero if the bus probing code
3524                          * ever stops re-probing on best match because the sctx
3525                          * may have its values over written by register calls
3526                          * in subsequent probes
3527                          */
3528                         return (BUS_PROBE_DEFAULT);
3529                 }
3530                 ent++;
3531         }
3532         return (ENXIO);
3533 }
3534
3535 int
3536 iflib_device_register(device_t dev, void *sc, if_shared_ctx_t sctx, if_ctx_t *ctxp)
3537 {
3538         int err, rid, msix, msix_bar;
3539         if_ctx_t ctx;
3540         if_t ifp;
3541         if_softc_ctx_t scctx;
3542         int i;
3543         uint16_t main_txq;
3544         uint16_t main_rxq;
3545
3546
3547         ctx = malloc(sizeof(* ctx), M_IFLIB, M_WAITOK|M_ZERO);
3548
3549         if (sc == NULL) {
3550                 sc = malloc(sctx->isc_driver->size, M_IFLIB, M_WAITOK|M_ZERO);
3551                 device_set_softc(dev, ctx);
3552                 ctx->ifc_flags |= IFC_SC_ALLOCATED;
3553         }
3554
3555         ctx->ifc_sctx = sctx;
3556         ctx->ifc_dev = dev;
3557         ctx->ifc_softc = sc;
3558
3559         if ((err = iflib_register(ctx)) != 0) {
3560                 device_printf(dev, "iflib_register failed %d\n", err);
3561                 return (err);
3562         }
3563         iflib_add_device_sysctl_pre(ctx);
3564
3565         scctx = &ctx->ifc_softc_ctx;
3566         ifp = ctx->ifc_ifp;
3567
3568         /*
3569          * XXX sanity check that ntxd & nrxd are a power of 2
3570          */
3571         if (ctx->ifc_sysctl_ntxqs != 0)
3572                 scctx->isc_ntxqsets = ctx->ifc_sysctl_ntxqs;
3573         if (ctx->ifc_sysctl_nrxqs != 0)
3574                 scctx->isc_nrxqsets = ctx->ifc_sysctl_nrxqs;
3575
3576         for (i = 0; i < sctx->isc_ntxqs; i++) {
3577                 if (ctx->ifc_sysctl_ntxds[i] != 0)
3578                         scctx->isc_ntxd[i] = ctx->ifc_sysctl_ntxds[i];
3579                 else
3580                         scctx->isc_ntxd[i] = sctx->isc_ntxd_default[i];
3581         }
3582
3583         for (i = 0; i < sctx->isc_nrxqs; i++) {
3584                 if (ctx->ifc_sysctl_nrxds[i] != 0)
3585                         scctx->isc_nrxd[i] = ctx->ifc_sysctl_nrxds[i];
3586                 else
3587                         scctx->isc_nrxd[i] = sctx->isc_nrxd_default[i];
3588         }
3589
3590         for (i = 0; i < sctx->isc_nrxqs; i++) {
3591                 if (scctx->isc_nrxd[i] < sctx->isc_nrxd_min[i]) {
3592                         device_printf(dev, "nrxd%d: %d less than nrxd_min %d - resetting to min\n",
3593                                       i, scctx->isc_nrxd[i], sctx->isc_nrxd_min[i]);
3594                         scctx->isc_nrxd[i] = sctx->isc_nrxd_min[i];
3595                 }
3596                 if (scctx->isc_nrxd[i] > sctx->isc_nrxd_max[i]) {
3597                         device_printf(dev, "nrxd%d: %d greater than nrxd_max %d - resetting to max\n",
3598                                       i, scctx->isc_nrxd[i], sctx->isc_nrxd_max[i]);
3599                         scctx->isc_nrxd[i] = sctx->isc_nrxd_max[i];
3600                 }
3601         }
3602
3603         for (i = 0; i < sctx->isc_ntxqs; i++) {
3604                 if (scctx->isc_ntxd[i] < sctx->isc_ntxd_min[i]) {
3605                         device_printf(dev, "ntxd%d: %d less than ntxd_min %d - resetting to min\n",
3606                                       i, scctx->isc_ntxd[i], sctx->isc_ntxd_min[i]);
3607                         scctx->isc_ntxd[i] = sctx->isc_ntxd_min[i];
3608                 }
3609                 if (scctx->isc_ntxd[i] > sctx->isc_ntxd_max[i]) {
3610                         device_printf(dev, "ntxd%d: %d greater than ntxd_max %d - resetting to max\n",
3611                                       i, scctx->isc_ntxd[i], sctx->isc_ntxd_max[i]);
3612                         scctx->isc_ntxd[i] = sctx->isc_ntxd_max[i];
3613                 }
3614         }
3615
3616         if ((err = IFDI_ATTACH_PRE(ctx)) != 0) {
3617                 device_printf(dev, "IFDI_ATTACH_PRE failed %d\n", err);
3618                 return (err);
3619         }
3620         _iflib_pre_assert(scctx);
3621         ctx->ifc_txrx = *scctx->isc_txrx;
3622
3623 #ifdef INVARIANTS
3624         MPASS(scctx->isc_capenable);
3625         if (scctx->isc_capenable & IFCAP_TXCSUM)
3626                 MPASS(scctx->isc_tx_csum_flags);
3627 #endif
3628
3629         if_setcapabilities(ifp, scctx->isc_capenable);
3630         if_setcapenable(ifp, scctx->isc_capenable);
3631
3632         if (scctx->isc_ntxqsets == 0 || (scctx->isc_ntxqsets_max && scctx->isc_ntxqsets_max < scctx->isc_ntxqsets))
3633                 scctx->isc_ntxqsets = scctx->isc_ntxqsets_max;
3634         if (scctx->isc_nrxqsets == 0 || (scctx->isc_nrxqsets_max && scctx->isc_nrxqsets_max < scctx->isc_nrxqsets))
3635                 scctx->isc_nrxqsets = scctx->isc_nrxqsets_max;
3636
3637 #ifdef ACPI_DMAR
3638         if (dmar_get_dma_tag(device_get_parent(dev), dev) != NULL)
3639                 ctx->ifc_flags |= IFC_DMAR;
3640 #endif
3641
3642         msix_bar = scctx->isc_msix_bar;
3643
3644         if(sctx->isc_flags & IFLIB_HAS_TXCQ)
3645                 main_txq = 1;
3646         else
3647                 main_txq = 0;
3648
3649         if(sctx->isc_flags & IFLIB_HAS_RXCQ)
3650                 main_rxq = 1;
3651         else
3652                 main_rxq = 0;
3653
3654         /* XXX change for per-queue sizes */
3655         device_printf(dev, "using %d tx descriptors and %d rx descriptors\n",
3656                       scctx->isc_ntxd[main_txq], scctx->isc_nrxd[main_rxq]);
3657         for (i = 0; i < sctx->isc_nrxqs; i++) {
3658                 if (!powerof2(scctx->isc_nrxd[i])) {
3659                         /* round down instead? */
3660                         device_printf(dev, "# rx descriptors must be a power of 2\n");
3661                         err = EINVAL;
3662                         goto fail;
3663                 }
3664         }
3665         for (i = 0; i < sctx->isc_ntxqs; i++) {
3666                 if (!powerof2(scctx->isc_ntxd[i])) {
3667                         device_printf(dev,
3668                             "# tx descriptors must be a power of 2");
3669                         err = EINVAL;
3670                         goto fail;
3671                 }
3672         }
3673
3674         if (scctx->isc_tx_nsegments > scctx->isc_ntxd[main_txq] /
3675             MAX_SINGLE_PACKET_FRACTION)
3676                 scctx->isc_tx_nsegments = max(1, scctx->isc_ntxd[main_txq] /
3677                     MAX_SINGLE_PACKET_FRACTION);
3678         if (scctx->isc_tx_tso_segments_max > scctx->isc_ntxd[main_txq] /
3679             MAX_SINGLE_PACKET_FRACTION)
3680                 scctx->isc_tx_tso_segments_max = max(1,
3681                     scctx->isc_ntxd[main_txq] / MAX_SINGLE_PACKET_FRACTION);
3682
3683         /*
3684          * Protect the stack against modern hardware
3685          */
3686         if (scctx->isc_tx_tso_size_max > FREEBSD_TSO_SIZE_MAX)
3687                 scctx->isc_tx_tso_size_max = FREEBSD_TSO_SIZE_MAX;
3688
3689         /* TSO parameters - dig these out of the data sheet - simply correspond to tag setup */
3690         ifp->if_hw_tsomaxsegcount = scctx->isc_tx_tso_segments_max;
3691         ifp->if_hw_tsomax = scctx->isc_tx_tso_size_max;
3692         ifp->if_hw_tsomaxsegsize = scctx->isc_tx_tso_segsize_max;
3693         if (scctx->isc_rss_table_size == 0)
3694                 scctx->isc_rss_table_size = 64;
3695         scctx->isc_rss_table_mask = scctx->isc_rss_table_size-1;
3696
3697         GROUPTASK_INIT(&ctx->ifc_admin_task, 0, _task_fn_admin, ctx);
3698         /* XXX format name */
3699         taskqgroup_attach(qgroup_if_config_tqg, &ctx->ifc_admin_task, ctx, -1, "admin");
3700         /*
3701         ** Now setup MSI or MSI/X, should
3702         ** return us the number of supported
3703         ** vectors. (Will be 1 for MSI)
3704         */
3705         if (sctx->isc_flags & IFLIB_SKIP_MSIX) {
3706                 msix = scctx->isc_vectors;
3707         } else if (scctx->isc_msix_bar != 0)
3708                 msix = iflib_msix_init(ctx);
3709         else {
3710                 scctx->isc_vectors = 1;
3711                 scctx->isc_ntxqsets = 1;
3712                 scctx->isc_nrxqsets = 1;
3713                 scctx->isc_intr = IFLIB_INTR_LEGACY;
3714                 msix = 0;
3715         }
3716         /* Get memory for the station queues */
3717         if ((err = iflib_queues_alloc(ctx))) {
3718                 device_printf(dev, "Unable to allocate queue memory\n");
3719                 goto fail;
3720         }
3721
3722         if ((err = iflib_qset_structures_setup(ctx))) {
3723                 device_printf(dev, "qset structure setup failed %d\n", err);
3724                 goto fail_queues;
3725         }
3726
3727         IFDI_INTR_DISABLE(ctx);
3728         if (msix > 1 && (err = IFDI_MSIX_INTR_ASSIGN(ctx, msix)) != 0) {
3729                 device_printf(dev, "IFDI_MSIX_INTR_ASSIGN failed %d\n", err);
3730                 goto fail_intr_free;
3731         }
3732         if (msix <= 1) {
3733                 rid = 0;
3734                 if (scctx->isc_intr == IFLIB_INTR_MSI) {
3735                         MPASS(msix == 1);
3736                         rid = 1;
3737                 }
3738                 if ((err = iflib_legacy_setup(ctx, ctx->isc_legacy_intr, ctx->ifc_softc, &rid, "irq0")) != 0) {
3739                         device_printf(dev, "iflib_legacy_setup failed %d\n", err);
3740                         goto fail_intr_free;
3741                 }
3742         }
3743         ether_ifattach(ctx->ifc_ifp, ctx->ifc_mac);
3744         if ((err = IFDI_ATTACH_POST(ctx)) != 0) {
3745                 device_printf(dev, "IFDI_ATTACH_POST failed %d\n", err);
3746                 goto fail_detach;
3747         }
3748         if ((err = iflib_netmap_attach(ctx))) {
3749                 device_printf(ctx->ifc_dev, "netmap attach failed: %d\n", err);
3750                 goto fail_detach;
3751         }
3752         *ctxp = ctx;
3753
3754         if_setgetcounterfn(ctx->ifc_ifp, iflib_if_get_counter);
3755         iflib_add_device_sysctl_post(ctx);
3756         return (0);
3757 fail_detach:
3758         ether_ifdetach(ctx->ifc_ifp);
3759 fail_intr_free:
3760         if (scctx->isc_intr == IFLIB_INTR_MSIX || scctx->isc_intr == IFLIB_INTR_MSI)
3761                 pci_release_msi(ctx->ifc_dev);
3762 fail_queues:
3763         /* XXX free queues */
3764 fail:
3765         IFDI_DETACH(ctx);
3766         return (err);
3767 }
3768
3769 int
3770 iflib_device_attach(device_t dev)
3771 {
3772         if_ctx_t ctx;
3773         if_shared_ctx_t sctx;
3774
3775         if ((sctx = DEVICE_REGISTER(dev)) == NULL || sctx->isc_magic != IFLIB_MAGIC)
3776                 return (ENOTSUP);
3777
3778         pci_enable_busmaster(dev);
3779
3780         return (iflib_device_register(dev, NULL, sctx, &ctx));
3781 }
3782
3783 int
3784 iflib_device_deregister(if_ctx_t ctx)
3785 {
3786         if_t ifp = ctx->ifc_ifp;
3787         iflib_txq_t txq;
3788         iflib_rxq_t rxq;
3789         device_t dev = ctx->ifc_dev;
3790         int i;
3791         struct taskqgroup *tqg;
3792
3793         /* Make sure VLANS are not using driver */
3794         if (if_vlantrunkinuse(ifp)) {
3795                 device_printf(dev,"Vlan in use, detach first\n");
3796                 return (EBUSY);
3797         }
3798
3799         CTX_LOCK(ctx);
3800         ctx->ifc_in_detach = 1;
3801         iflib_stop(ctx);
3802         CTX_UNLOCK(ctx);
3803
3804         /* Unregister VLAN events */
3805         if (ctx->ifc_vlan_attach_event != NULL)
3806                 EVENTHANDLER_DEREGISTER(vlan_config, ctx->ifc_vlan_attach_event);
3807         if (ctx->ifc_vlan_detach_event != NULL)
3808                 EVENTHANDLER_DEREGISTER(vlan_unconfig, ctx->ifc_vlan_detach_event);
3809
3810         iflib_netmap_detach(ifp);
3811         ether_ifdetach(ifp);
3812         /* ether_ifdetach calls if_qflush - lock must be destroy afterwards*/
3813         CTX_LOCK_DESTROY(ctx);
3814         if (ctx->ifc_led_dev != NULL)
3815                 led_destroy(ctx->ifc_led_dev);
3816         /* XXX drain any dependent tasks */
3817         tqg = qgroup_if_io_tqg;
3818         for (txq = ctx->ifc_txqs, i = 0; i < NTXQSETS(ctx); i++, txq++) {
3819                 callout_drain(&txq->ift_timer);
3820                 callout_drain(&txq->ift_db_check);
3821                 if (txq->ift_task.gt_uniq != NULL)
3822                         taskqgroup_detach(tqg, &txq->ift_task);
3823         }
3824         for (i = 0, rxq = ctx->ifc_rxqs; i < NRXQSETS(ctx); i++, rxq++) {
3825                 if (rxq->ifr_task.gt_uniq != NULL)
3826                         taskqgroup_detach(tqg, &rxq->ifr_task);
3827         }
3828         tqg = qgroup_if_config_tqg;
3829         if (ctx->ifc_admin_task.gt_uniq != NULL)
3830                 taskqgroup_detach(tqg, &ctx->ifc_admin_task);
3831         if (ctx->ifc_vflr_task.gt_uniq != NULL)
3832                 taskqgroup_detach(tqg, &ctx->ifc_vflr_task);
3833
3834         IFDI_DETACH(ctx);
3835         device_set_softc(ctx->ifc_dev, NULL);
3836         if (ctx->ifc_softc_ctx.isc_intr != IFLIB_INTR_LEGACY) {
3837                 pci_release_msi(dev);
3838         }
3839         if (ctx->ifc_softc_ctx.isc_intr != IFLIB_INTR_MSIX) {
3840                 iflib_irq_free(ctx, &ctx->ifc_legacy_irq);
3841         }
3842         if (ctx->ifc_msix_mem != NULL) {
3843                 bus_release_resource(ctx->ifc_dev, SYS_RES_MEMORY,
3844                         ctx->ifc_softc_ctx.isc_msix_bar, ctx->ifc_msix_mem);
3845                 ctx->ifc_msix_mem = NULL;
3846         }
3847
3848         bus_generic_detach(dev);
3849         if_free(ifp);
3850
3851         iflib_tx_structures_free(ctx);
3852         iflib_rx_structures_free(ctx);
3853         if (ctx->ifc_flags & IFC_SC_ALLOCATED)
3854                 free(ctx->ifc_softc, M_IFLIB);
3855         free(ctx, M_IFLIB);
3856         return (0);
3857 }
3858
3859
3860 int
3861 iflib_device_detach(device_t dev)
3862 {
3863         if_ctx_t ctx = device_get_softc(dev);
3864
3865         return (iflib_device_deregister(ctx));
3866 }
3867
3868 int
3869 iflib_device_suspend(device_t dev)
3870 {
3871         if_ctx_t ctx = device_get_softc(dev);
3872
3873         CTX_LOCK(ctx);
3874         IFDI_SUSPEND(ctx);
3875         CTX_UNLOCK(ctx);
3876
3877         return bus_generic_suspend(dev);
3878 }
3879 int
3880 iflib_device_shutdown(device_t dev)
3881 {
3882         if_ctx_t ctx = device_get_softc(dev);
3883
3884         CTX_LOCK(ctx);
3885         IFDI_SHUTDOWN(ctx);
3886         CTX_UNLOCK(ctx);
3887
3888         return bus_generic_suspend(dev);
3889 }
3890
3891
3892 int
3893 iflib_device_resume(device_t dev)
3894 {
3895         if_ctx_t ctx = device_get_softc(dev);
3896         iflib_txq_t txq = ctx->ifc_txqs;
3897
3898         CTX_LOCK(ctx);
3899         IFDI_RESUME(ctx);
3900         iflib_init_locked(ctx);
3901         CTX_UNLOCK(ctx);
3902         for (int i = 0; i < NTXQSETS(ctx); i++, txq++)
3903                 iflib_txq_check_drain(txq, IFLIB_RESTART_BUDGET);
3904
3905         return (bus_generic_resume(dev));
3906 }
3907
3908 int
3909 iflib_device_iov_init(device_t dev, uint16_t num_vfs, const nvlist_t *params)
3910 {
3911         int error;
3912         if_ctx_t ctx = device_get_softc(dev);
3913
3914         CTX_LOCK(ctx);
3915         error = IFDI_IOV_INIT(ctx, num_vfs, params);
3916         CTX_UNLOCK(ctx);
3917
3918         return (error);
3919 }
3920
3921 void
3922 iflib_device_iov_uninit(device_t dev)
3923 {
3924         if_ctx_t ctx = device_get_softc(dev);
3925
3926         CTX_LOCK(ctx);
3927         IFDI_IOV_UNINIT(ctx);
3928         CTX_UNLOCK(ctx);
3929 }
3930
3931 int
3932 iflib_device_iov_add_vf(device_t dev, uint16_t vfnum, const nvlist_t *params)
3933 {
3934         int error;
3935         if_ctx_t ctx = device_get_softc(dev);
3936
3937         CTX_LOCK(ctx);
3938         error = IFDI_IOV_VF_ADD(ctx, vfnum, params);
3939         CTX_UNLOCK(ctx);
3940
3941         return (error);
3942 }
3943
3944 /*********************************************************************
3945  *
3946  *  MODULE FUNCTION DEFINITIONS
3947  *
3948  **********************************************************************/
3949
3950 /*
3951  * - Start a fast taskqueue thread for each core
3952  * - Start a taskqueue for control operations
3953  */
3954 static int
3955 iflib_module_init(void)
3956 {
3957         return (0);
3958 }
3959
3960 static int
3961 iflib_module_event_handler(module_t mod, int what, void *arg)
3962 {
3963         int err;
3964
3965         switch (what) {
3966         case MOD_LOAD:
3967                 if ((err = iflib_module_init()) != 0)
3968                         return (err);
3969                 break;
3970         case MOD_UNLOAD:
3971                 return (EBUSY);
3972         default:
3973                 return (EOPNOTSUPP);
3974         }
3975
3976         return (0);
3977 }
3978
3979 /*********************************************************************
3980  *
3981  *  PUBLIC FUNCTION DEFINITIONS
3982  *     ordered as in iflib.h
3983  *
3984  **********************************************************************/
3985
3986
3987 static void
3988 _iflib_assert(if_shared_ctx_t sctx)
3989 {
3990         MPASS(sctx->isc_tx_maxsize);
3991         MPASS(sctx->isc_tx_maxsegsize);
3992
3993         MPASS(sctx->isc_rx_maxsize);
3994         MPASS(sctx->isc_rx_nsegments);
3995         MPASS(sctx->isc_rx_maxsegsize);
3996
3997         MPASS(sctx->isc_nrxd_min[0]);
3998         MPASS(sctx->isc_nrxd_max[0]);
3999         MPASS(sctx->isc_nrxd_default[0]);
4000         MPASS(sctx->isc_ntxd_min[0]);
4001         MPASS(sctx->isc_ntxd_max[0]);
4002         MPASS(sctx->isc_ntxd_default[0]);
4003 }
4004
4005 static void
4006 _iflib_pre_assert(if_softc_ctx_t scctx)
4007 {
4008
4009         MPASS(scctx->isc_txrx->ift_txd_encap);
4010         MPASS(scctx->isc_txrx->ift_txd_flush);
4011         MPASS(scctx->isc_txrx->ift_txd_credits_update);
4012         MPASS(scctx->isc_txrx->ift_rxd_available);
4013         MPASS(scctx->isc_txrx->ift_rxd_pkt_get);
4014         MPASS(scctx->isc_txrx->ift_rxd_refill);
4015         MPASS(scctx->isc_txrx->ift_rxd_flush);
4016 }
4017
4018 static int
4019 iflib_register(if_ctx_t ctx)
4020 {
4021         if_shared_ctx_t sctx = ctx->ifc_sctx;
4022         driver_t *driver = sctx->isc_driver;
4023         device_t dev = ctx->ifc_dev;
4024         if_t ifp;
4025
4026         _iflib_assert(sctx);
4027
4028         CTX_LOCK_INIT(ctx, device_get_nameunit(ctx->ifc_dev));
4029
4030         ifp = ctx->ifc_ifp = if_gethandle(IFT_ETHER);
4031         if (ifp == NULL) {
4032                 device_printf(dev, "can not allocate ifnet structure\n");
4033                 return (ENOMEM);
4034         }
4035
4036         /*
4037          * Initialize our context's device specific methods
4038          */
4039         kobj_init((kobj_t) ctx, (kobj_class_t) driver);
4040         kobj_class_compile((kobj_class_t) driver);
4041         driver->refs++;
4042
4043         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
4044         if_setsoftc(ifp, ctx);
4045         if_setdev(ifp, dev);
4046         if_setinitfn(ifp, iflib_if_init);
4047         if_setioctlfn(ifp, iflib_if_ioctl);
4048         if_settransmitfn(ifp, iflib_if_transmit);
4049         if_setqflushfn(ifp, iflib_if_qflush);
4050         if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
4051
4052         ctx->ifc_vlan_attach_event =
4053                 EVENTHANDLER_REGISTER(vlan_config, iflib_vlan_register, ctx,
4054                                                           EVENTHANDLER_PRI_FIRST);
4055         ctx->ifc_vlan_detach_event =
4056                 EVENTHANDLER_REGISTER(vlan_unconfig, iflib_vlan_unregister, ctx,
4057                                                           EVENTHANDLER_PRI_FIRST);
4058
4059         ifmedia_init(&ctx->ifc_media, IFM_IMASK,
4060                                          iflib_media_change, iflib_media_status);
4061
4062         return (0);
4063 }
4064
4065
4066 static int
4067 iflib_queues_alloc(if_ctx_t ctx)
4068 {
4069         if_shared_ctx_t sctx = ctx->ifc_sctx;
4070         if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
4071         device_t dev = ctx->ifc_dev;
4072         int nrxqsets = scctx->isc_nrxqsets;
4073         int ntxqsets = scctx->isc_ntxqsets;
4074         iflib_txq_t txq;
4075         iflib_rxq_t rxq;
4076         iflib_fl_t fl = NULL;
4077         int i, j, cpu, err, txconf, rxconf;
4078         iflib_dma_info_t ifdip;
4079         uint32_t *rxqsizes = scctx->isc_rxqsizes;
4080         uint32_t *txqsizes = scctx->isc_txqsizes;
4081         uint8_t nrxqs = sctx->isc_nrxqs;
4082         uint8_t ntxqs = sctx->isc_ntxqs;
4083         int nfree_lists = sctx->isc_nfl ? sctx->isc_nfl : 1;
4084         caddr_t *vaddrs;
4085         uint64_t *paddrs;
4086         struct ifmp_ring **brscp;
4087         int nbuf_rings = 1; /* XXX determine dynamically */
4088
4089         KASSERT(ntxqs > 0, ("number of queues per qset must be at least 1"));
4090         KASSERT(nrxqs > 0, ("number of queues per qset must be at least 1"));
4091
4092         brscp = NULL;
4093         txq = NULL;
4094         rxq = NULL;
4095
4096 /* Allocate the TX ring struct memory */
4097         if (!(txq =
4098             (iflib_txq_t) malloc(sizeof(struct iflib_txq) *
4099             ntxqsets, M_IFLIB, M_NOWAIT | M_ZERO))) {
4100                 device_printf(dev, "Unable to allocate TX ring memory\n");
4101                 err = ENOMEM;
4102                 goto fail;
4103         }
4104
4105         /* Now allocate the RX */
4106         if (!(rxq =
4107             (iflib_rxq_t) malloc(sizeof(struct iflib_rxq) *
4108             nrxqsets, M_IFLIB, M_NOWAIT | M_ZERO))) {
4109                 device_printf(dev, "Unable to allocate RX ring memory\n");
4110                 err = ENOMEM;
4111                 goto rx_fail;
4112         }
4113         if (!(brscp = malloc(sizeof(void *) * nbuf_rings * nrxqsets, M_IFLIB, M_NOWAIT | M_ZERO))) {
4114                 device_printf(dev, "Unable to buf_ring_sc * memory\n");
4115                 err = ENOMEM;
4116                 goto rx_fail;
4117         }
4118
4119         ctx->ifc_txqs = txq;
4120         ctx->ifc_rxqs = rxq;
4121
4122         /*
4123          * XXX handle allocation failure
4124          */
4125         for (txconf = i = 0, cpu = CPU_FIRST(); i < ntxqsets; i++, txconf++, txq++, cpu = CPU_NEXT(cpu)) {
4126                 /* Set up some basics */
4127
4128                 if ((ifdip = malloc(sizeof(struct iflib_dma_info) * ntxqs, M_IFLIB, M_WAITOK|M_ZERO)) == NULL) {
4129                         device_printf(dev, "failed to allocate iflib_dma_info\n");
4130                         err = ENOMEM;
4131                         goto err_tx_desc;
4132                 }
4133                 txq->ift_ifdi = ifdip;
4134                 for (j = 0; j < ntxqs; j++, ifdip++) {
4135                         if (iflib_dma_alloc(ctx, txqsizes[j], ifdip, BUS_DMA_NOWAIT)) {
4136                                 device_printf(dev, "Unable to allocate Descriptor memory\n");
4137                                 err = ENOMEM;
4138                                 goto err_tx_desc;
4139                         }
4140                         bzero((void *)ifdip->idi_vaddr, txqsizes[j]);
4141                 }
4142                 txq->ift_ctx = ctx;
4143                 txq->ift_id = i;
4144                 if (sctx->isc_flags & IFLIB_HAS_TXCQ) {
4145                         txq->ift_br_offset = 1;
4146                 } else {
4147                         txq->ift_br_offset = 0;
4148                 }
4149                 /* XXX fix this */
4150                 txq->ift_timer.c_cpu = cpu;
4151                 txq->ift_db_check.c_cpu = cpu;
4152                 txq->ift_nbr = nbuf_rings;
4153
4154                 if (iflib_txsd_alloc(txq)) {
4155                         device_printf(dev, "Critical Failure setting up TX buffers\n");
4156                         err = ENOMEM;
4157                         goto err_tx_desc;
4158                 }
4159
4160                 /* Initialize the TX lock */
4161                 snprintf(txq->ift_mtx_name, MTX_NAME_LEN, "%s:tx(%d):callout",
4162                     device_get_nameunit(dev), txq->ift_id);
4163                 mtx_init(&txq->ift_mtx, txq->ift_mtx_name, NULL, MTX_DEF);
4164                 callout_init_mtx(&txq->ift_timer, &txq->ift_mtx, 0);
4165                 callout_init_mtx(&txq->ift_db_check, &txq->ift_mtx, 0);
4166
4167                 snprintf(txq->ift_db_mtx_name, MTX_NAME_LEN, "%s:tx(%d):db",
4168                          device_get_nameunit(dev), txq->ift_id);
4169                 TXDB_LOCK_INIT(txq);
4170
4171                 txq->ift_br = brscp + i*nbuf_rings;
4172                 for (j = 0; j < nbuf_rings; j++) {
4173                         err = ifmp_ring_alloc(&txq->ift_br[j], 2048, txq, iflib_txq_drain,
4174                                               iflib_txq_can_drain, M_IFLIB, M_WAITOK);
4175                         if (err) {
4176                                 /* XXX free any allocated rings */
4177                                 device_printf(dev, "Unable to allocate buf_ring\n");
4178                                 goto err_tx_desc;
4179                         }
4180                 }
4181         }
4182
4183         for (rxconf = i = 0; i < nrxqsets; i++, rxconf++, rxq++) {
4184                 /* Set up some basics */
4185
4186                 if ((ifdip = malloc(sizeof(struct iflib_dma_info) * nrxqs, M_IFLIB, M_WAITOK|M_ZERO)) == NULL) {
4187                         device_printf(dev, "failed to allocate iflib_dma_info\n");
4188                         err = ENOMEM;
4189                         goto err_tx_desc;
4190                 }
4191
4192                 rxq->ifr_ifdi = ifdip;
4193                 for (j = 0; j < nrxqs; j++, ifdip++) {
4194                         if (iflib_dma_alloc(ctx, rxqsizes[j], ifdip, BUS_DMA_NOWAIT)) {
4195                                 device_printf(dev, "Unable to allocate Descriptor memory\n");
4196                                 err = ENOMEM;
4197                                 goto err_tx_desc;
4198                         }
4199                         bzero((void *)ifdip->idi_vaddr, rxqsizes[j]);
4200                 }
4201                 rxq->ifr_ctx = ctx;
4202                 rxq->ifr_id = i;
4203                 if (sctx->isc_flags & IFLIB_HAS_RXCQ) {
4204                         rxq->ifr_fl_offset = 1;
4205                 } else {
4206                         rxq->ifr_fl_offset = 0;
4207                 }
4208                 rxq->ifr_nfl = nfree_lists;
4209                 if (!(fl =
4210                           (iflib_fl_t) malloc(sizeof(struct iflib_fl) * nfree_lists, M_IFLIB, M_NOWAIT | M_ZERO))) {
4211                         device_printf(dev, "Unable to allocate free list memory\n");
4212                         err = ENOMEM;
4213                         goto err_tx_desc;
4214                 }
4215                 rxq->ifr_fl = fl;
4216                 for (j = 0; j < nfree_lists; j++) {
4217                         rxq->ifr_fl[j].ifl_rxq = rxq;
4218                         rxq->ifr_fl[j].ifl_id = j;
4219                         rxq->ifr_fl[j].ifl_ifdi =
4220                             &rxq->ifr_ifdi[j + rxq->ifr_fl_offset];
4221                 }
4222         /* Allocate receive buffers for the ring*/
4223                 if (iflib_rxsd_alloc(rxq)) {
4224                         device_printf(dev,
4225                             "Critical Failure setting up receive buffers\n");
4226                         err = ENOMEM;
4227                         goto err_rx_desc;
4228                 }
4229         }
4230
4231         /* TXQs */
4232         vaddrs = malloc(sizeof(caddr_t)*ntxqsets*ntxqs, M_IFLIB, M_WAITOK);
4233         paddrs = malloc(sizeof(uint64_t)*ntxqsets*ntxqs, M_IFLIB, M_WAITOK);
4234         for (i = 0; i < ntxqsets; i++) {
4235                 iflib_dma_info_t di = ctx->ifc_txqs[i].ift_ifdi;
4236
4237                 for (j = 0; j < ntxqs; j++, di++) {
4238                         vaddrs[i*ntxqs + j] = di->idi_vaddr;
4239                         paddrs[i*ntxqs + j] = di->idi_paddr;
4240                 }
4241         }
4242         if ((err = IFDI_TX_QUEUES_ALLOC(ctx, vaddrs, paddrs, ntxqs, ntxqsets)) != 0) {
4243                 device_printf(ctx->ifc_dev, "device queue allocation failed\n");
4244                 iflib_tx_structures_free(ctx);
4245                 free(vaddrs, M_IFLIB);
4246                 free(paddrs, M_IFLIB);
4247                 goto err_rx_desc;
4248         }
4249         free(vaddrs, M_IFLIB);
4250         free(paddrs, M_IFLIB);
4251
4252         /* RXQs */
4253         vaddrs = malloc(sizeof(caddr_t)*nrxqsets*nrxqs, M_IFLIB, M_WAITOK);
4254         paddrs = malloc(sizeof(uint64_t)*nrxqsets*nrxqs, M_IFLIB, M_WAITOK);
4255         for (i = 0; i < nrxqsets; i++) {
4256                 iflib_dma_info_t di = ctx->ifc_rxqs[i].ifr_ifdi;
4257
4258                 for (j = 0; j < nrxqs; j++, di++) {
4259                         vaddrs[i*nrxqs + j] = di->idi_vaddr;
4260                         paddrs[i*nrxqs + j] = di->idi_paddr;
4261                 }
4262         }
4263         if ((err = IFDI_RX_QUEUES_ALLOC(ctx, vaddrs, paddrs, nrxqs, nrxqsets)) != 0) {
4264                 device_printf(ctx->ifc_dev, "device queue allocation failed\n");
4265                 iflib_tx_structures_free(ctx);
4266                 free(vaddrs, M_IFLIB);
4267                 free(paddrs, M_IFLIB);
4268                 goto err_rx_desc;
4269         }
4270         free(vaddrs, M_IFLIB);
4271         free(paddrs, M_IFLIB);
4272
4273         return (0);
4274
4275 /* XXX handle allocation failure changes */
4276 err_rx_desc:
4277 err_tx_desc:
4278         if (ctx->ifc_rxqs != NULL)
4279                 free(ctx->ifc_rxqs, M_IFLIB);
4280         ctx->ifc_rxqs = NULL;
4281         if (ctx->ifc_txqs != NULL)
4282                 free(ctx->ifc_txqs, M_IFLIB);
4283         ctx->ifc_txqs = NULL;
4284 rx_fail:
4285         if (brscp != NULL)
4286                 free(brscp, M_IFLIB);
4287         if (rxq != NULL)
4288                 free(rxq, M_IFLIB);
4289         if (txq != NULL)
4290                 free(txq, M_IFLIB);
4291 fail:
4292         return (err);
4293 }
4294
4295 static int
4296 iflib_tx_structures_setup(if_ctx_t ctx)
4297 {
4298         iflib_txq_t txq = ctx->ifc_txqs;
4299         int i;
4300
4301         for (i = 0; i < NTXQSETS(ctx); i++, txq++)
4302                 iflib_txq_setup(txq);
4303
4304         return (0);
4305 }
4306
4307 static void
4308 iflib_tx_structures_free(if_ctx_t ctx)
4309 {
4310         iflib_txq_t txq = ctx->ifc_txqs;
4311         int i, j;
4312
4313         for (i = 0; i < NTXQSETS(ctx); i++, txq++) {
4314                 iflib_txq_destroy(txq);
4315                 for (j = 0; j < ctx->ifc_nhwtxqs; j++)
4316                         iflib_dma_free(&txq->ift_ifdi[j]);
4317         }
4318         free(ctx->ifc_txqs, M_IFLIB);
4319         ctx->ifc_txqs = NULL;
4320         IFDI_QUEUES_FREE(ctx);
4321 }
4322
4323 /*********************************************************************
4324  *
4325  *  Initialize all receive rings.
4326  *
4327  **********************************************************************/
4328 static int
4329 iflib_rx_structures_setup(if_ctx_t ctx)
4330 {
4331         iflib_rxq_t rxq = ctx->ifc_rxqs;
4332         int q;
4333 #if defined(INET6) || defined(INET)
4334         int i, err;
4335 #endif
4336
4337         for (q = 0; q < ctx->ifc_softc_ctx.isc_nrxqsets; q++, rxq++) {
4338 #if defined(INET6) || defined(INET)
4339                 tcp_lro_free(&rxq->ifr_lc);
4340                 if ((err = tcp_lro_init_args(&rxq->ifr_lc, ctx->ifc_ifp,
4341                     TCP_LRO_ENTRIES, min(1024,
4342                     ctx->ifc_softc_ctx.isc_nrxd[rxq->ifr_fl_offset]))) != 0) {
4343                         device_printf(ctx->ifc_dev, "LRO Initialization failed!\n");
4344                         goto fail;
4345                 }
4346                 rxq->ifr_lro_enabled = TRUE;
4347 #endif
4348                 IFDI_RXQ_SETUP(ctx, rxq->ifr_id);
4349         }
4350         return (0);
4351 #if defined(INET6) || defined(INET)
4352 fail:
4353         /*
4354          * Free RX software descriptors allocated so far, we will only handle
4355          * the rings that completed, the failing case will have
4356          * cleaned up for itself. 'q' failed, so its the terminus.
4357          */
4358         rxq = ctx->ifc_rxqs;
4359         for (i = 0; i < q; ++i, rxq++) {
4360                 iflib_rx_sds_free(rxq);
4361                 rxq->ifr_cq_gen = rxq->ifr_cq_cidx = rxq->ifr_cq_pidx = 0;
4362         }
4363         return (err);
4364 #endif
4365 }
4366
4367 /*********************************************************************
4368  *
4369  *  Free all receive rings.
4370  *
4371  **********************************************************************/
4372 static void
4373 iflib_rx_structures_free(if_ctx_t ctx)
4374 {
4375         iflib_rxq_t rxq = ctx->ifc_rxqs;
4376
4377         for (int i = 0; i < ctx->ifc_softc_ctx.isc_nrxqsets; i++, rxq++) {
4378                 iflib_rx_sds_free(rxq);
4379         }
4380 }
4381
4382 static int
4383 iflib_qset_structures_setup(if_ctx_t ctx)
4384 {
4385         int err;
4386
4387         if ((err = iflib_tx_structures_setup(ctx)) != 0)
4388                 return (err);
4389
4390         if ((err = iflib_rx_structures_setup(ctx)) != 0) {
4391                 device_printf(ctx->ifc_dev, "iflib_rx_structures_setup failed: %d\n", err);
4392                 iflib_tx_structures_free(ctx);
4393                 iflib_rx_structures_free(ctx);
4394         }
4395         return (err);
4396 }
4397
4398 int
4399 iflib_irq_alloc(if_ctx_t ctx, if_irq_t irq, int rid,
4400                                 driver_filter_t filter, void *filter_arg, driver_intr_t handler, void *arg, char *name)
4401 {
4402
4403         return (_iflib_irq_alloc(ctx, irq, rid, filter, handler, arg, name));
4404 }
4405
4406 static int
4407 find_nth(if_ctx_t ctx, cpuset_t *cpus, int qid)
4408 {
4409         int i, cpuid, eqid, count;
4410
4411         CPU_COPY(&ctx->ifc_cpus, cpus);
4412         count = CPU_COUNT(&ctx->ifc_cpus);
4413         eqid = qid % count;
4414         /* clear up to the qid'th bit */
4415         for (i = 0; i < eqid; i++) {
4416                 cpuid = CPU_FFS(cpus);
4417                 MPASS(cpuid != 0);
4418                 CPU_CLR(cpuid-1, cpus);
4419         }
4420         cpuid = CPU_FFS(cpus);
4421         MPASS(cpuid != 0);
4422         return (cpuid-1);
4423 }
4424
4425 int
4426 iflib_irq_alloc_generic(if_ctx_t ctx, if_irq_t irq, int rid,
4427                                                 iflib_intr_type_t type, driver_filter_t *filter,
4428                                                 void *filter_arg, int qid, char *name)
4429 {
4430         struct grouptask *gtask;
4431         struct taskqgroup *tqg;
4432         iflib_filter_info_t info;
4433         cpuset_t cpus;
4434         gtask_fn_t *fn;
4435         int tqrid, err, cpuid;
4436         void *q;
4437
4438         info = &ctx->ifc_filter_info;
4439         tqrid = rid;
4440
4441         switch (type) {
4442         /* XXX merge tx/rx for netmap? */
4443         case IFLIB_INTR_TX:
4444                 q = &ctx->ifc_txqs[qid];
4445                 info = &ctx->ifc_txqs[qid].ift_filter_info;
4446                 gtask = &ctx->ifc_txqs[qid].ift_task;
4447                 tqg = qgroup_if_io_tqg;
4448                 fn = _task_fn_tx;
4449                 GROUPTASK_INIT(gtask, 0, fn, q);
4450                 break;
4451         case IFLIB_INTR_RX:
4452                 q = &ctx->ifc_rxqs[qid];
4453                 info = &ctx->ifc_rxqs[qid].ifr_filter_info;
4454                 gtask = &ctx->ifc_rxqs[qid].ifr_task;
4455                 tqg = qgroup_if_io_tqg;
4456                 fn = _task_fn_rx;
4457                 GROUPTASK_INIT(gtask, 0, fn, q);
4458                 break;
4459         case IFLIB_INTR_ADMIN:
4460                 q = ctx;
4461                 tqrid = -1;
4462                 info = &ctx->ifc_filter_info;
4463                 gtask = &ctx->ifc_admin_task;
4464                 tqg = qgroup_if_config_tqg;
4465                 fn = _task_fn_admin;
4466                 break;
4467         default:
4468                 panic("unknown net intr type");
4469         }
4470
4471         info->ifi_filter = filter;
4472         info->ifi_filter_arg = filter_arg;
4473         info->ifi_task = gtask;
4474
4475         err = _iflib_irq_alloc(ctx, irq, rid, iflib_fast_intr, NULL, info,  name);
4476         if (err != 0) {
4477                 device_printf(ctx->ifc_dev, "_iflib_irq_alloc failed %d\n", err);
4478                 return (err);
4479         }
4480         if (type == IFLIB_INTR_ADMIN)
4481                 return (0);
4482
4483         if (tqrid != -1) {
4484                 cpuid = find_nth(ctx, &cpus, qid);
4485                 taskqgroup_attach_cpu(tqg, gtask, q, cpuid, irq->ii_rid, name);
4486         } else {
4487                 taskqgroup_attach(tqg, gtask, q, tqrid, name);
4488         }
4489
4490         return (0);
4491 }
4492
4493 void
4494 iflib_softirq_alloc_generic(if_ctx_t ctx, int rid, iflib_intr_type_t type,  void *arg, int qid, char *name)
4495 {
4496         struct grouptask *gtask;
4497         struct taskqgroup *tqg;
4498         gtask_fn_t *fn;
4499         void *q;
4500
4501         switch (type) {
4502         case IFLIB_INTR_TX:
4503                 q = &ctx->ifc_txqs[qid];
4504                 gtask = &ctx->ifc_txqs[qid].ift_task;
4505                 tqg = qgroup_if_io_tqg;
4506                 fn = _task_fn_tx;
4507                 break;
4508         case IFLIB_INTR_RX:
4509                 q = &ctx->ifc_rxqs[qid];
4510                 gtask = &ctx->ifc_rxqs[qid].ifr_task;
4511                 tqg = qgroup_if_io_tqg;
4512                 fn = _task_fn_rx;
4513                 break;
4514         case IFLIB_INTR_IOV:
4515                 q = ctx;
4516                 gtask = &ctx->ifc_vflr_task;
4517                 tqg = qgroup_if_config_tqg;
4518                 rid = -1;
4519                 fn = _task_fn_iov;
4520                 break;
4521         default:
4522                 panic("unknown net intr type");
4523         }
4524         GROUPTASK_INIT(gtask, 0, fn, q);
4525         taskqgroup_attach(tqg, gtask, q, rid, name);
4526 }
4527
4528 void
4529 iflib_irq_free(if_ctx_t ctx, if_irq_t irq)
4530 {
4531         if (irq->ii_tag)
4532                 bus_teardown_intr(ctx->ifc_dev, irq->ii_res, irq->ii_tag);
4533
4534         if (irq->ii_res)
4535                 bus_release_resource(ctx->ifc_dev, SYS_RES_IRQ, irq->ii_rid, irq->ii_res);
4536 }
4537
4538 static int
4539 iflib_legacy_setup(if_ctx_t ctx, driver_filter_t filter, void *filter_arg, int *rid, char *name)
4540 {
4541         iflib_txq_t txq = ctx->ifc_txqs;
4542         iflib_rxq_t rxq = ctx->ifc_rxqs;
4543         if_irq_t irq = &ctx->ifc_legacy_irq;
4544         iflib_filter_info_t info;
4545         struct grouptask *gtask;
4546         struct taskqgroup *tqg;
4547         gtask_fn_t *fn;
4548         int tqrid;
4549         void *q;
4550         int err;
4551
4552         /*
4553          * group taskqueues aren't properly set up until SMP is started
4554          * so we disable interrupts until we can handle them post
4555          * SI_SUB_SMP
4556          */
4557         IFDI_INTR_DISABLE(ctx);
4558
4559         q = &ctx->ifc_rxqs[0];
4560         info = &rxq[0].ifr_filter_info;
4561         gtask = &rxq[0].ifr_task;
4562         tqg = qgroup_if_io_tqg;
4563         tqrid = irq->ii_rid = *rid;
4564         fn = _task_fn_rx;
4565
4566         ctx->ifc_flags |= IFC_LEGACY;
4567         info->ifi_filter = filter;
4568         info->ifi_filter_arg = filter_arg;
4569         info->ifi_task = gtask;
4570
4571         /* We allocate a single interrupt resource */
4572         if ((err = _iflib_irq_alloc(ctx, irq, tqrid, iflib_fast_intr, NULL, info, name)) != 0)
4573                 return (err);
4574         GROUPTASK_INIT(gtask, 0, fn, q);
4575         taskqgroup_attach(tqg, gtask, q, tqrid, name);
4576
4577         GROUPTASK_INIT(&txq->ift_task, 0, _task_fn_tx, txq);
4578         taskqgroup_attach(qgroup_if_io_tqg, &txq->ift_task, txq, tqrid, "tx");
4579         return (0);
4580 }
4581
4582 void
4583 iflib_led_create(if_ctx_t ctx)
4584 {
4585
4586         ctx->ifc_led_dev = led_create(iflib_led_func, ctx,
4587                                                                   device_get_nameunit(ctx->ifc_dev));
4588 }
4589
4590 void
4591 iflib_tx_intr_deferred(if_ctx_t ctx, int txqid)
4592 {
4593
4594         GROUPTASK_ENQUEUE(&ctx->ifc_txqs[txqid].ift_task);
4595 }
4596
4597 void
4598 iflib_rx_intr_deferred(if_ctx_t ctx, int rxqid)
4599 {
4600
4601         GROUPTASK_ENQUEUE(&ctx->ifc_rxqs[rxqid].ifr_task);
4602 }
4603
4604 void
4605 iflib_admin_intr_deferred(if_ctx_t ctx)
4606 {
4607 #ifdef INVARIANTS
4608         struct grouptask *gtask;
4609
4610         gtask = &ctx->ifc_admin_task;
4611         MPASS(gtask->gt_taskqueue != NULL);
4612 #endif
4613
4614         GROUPTASK_ENQUEUE(&ctx->ifc_admin_task);
4615 }
4616
4617 void
4618 iflib_iov_intr_deferred(if_ctx_t ctx)
4619 {
4620
4621         GROUPTASK_ENQUEUE(&ctx->ifc_vflr_task);
4622 }
4623
4624 void
4625 iflib_io_tqg_attach(struct grouptask *gt, void *uniq, int cpu, char *name)
4626 {
4627
4628         taskqgroup_attach_cpu(qgroup_if_io_tqg, gt, uniq, cpu, -1, name);
4629 }
4630
4631 void
4632 iflib_config_gtask_init(if_ctx_t ctx, struct grouptask *gtask, gtask_fn_t *fn,
4633         char *name)
4634 {
4635
4636         GROUPTASK_INIT(gtask, 0, fn, ctx);
4637         taskqgroup_attach(qgroup_if_config_tqg, gtask, gtask, -1, name);
4638 }
4639
4640 void
4641 iflib_config_gtask_deinit(struct grouptask *gtask)
4642 {
4643
4644         taskqgroup_detach(qgroup_if_config_tqg, gtask); 
4645 }
4646
4647 void
4648 iflib_link_state_change(if_ctx_t ctx, int link_state, uint64_t baudrate)
4649 {
4650         if_t ifp = ctx->ifc_ifp;
4651         iflib_txq_t txq = ctx->ifc_txqs;
4652
4653         if_setbaudrate(ifp, baudrate);
4654
4655         /* If link down, disable watchdog */
4656         if ((ctx->ifc_link_state == LINK_STATE_UP) && (link_state == LINK_STATE_DOWN)) {
4657                 for (int i = 0; i < ctx->ifc_softc_ctx.isc_ntxqsets; i++, txq++)
4658                         txq->ift_qstatus = IFLIB_QUEUE_IDLE;
4659         }
4660         ctx->ifc_link_state = link_state;
4661         if_link_state_change(ifp, link_state);
4662 }
4663
4664 static int
4665 iflib_tx_credits_update(if_ctx_t ctx, iflib_txq_t txq)
4666 {
4667         int credits;
4668 #ifdef INVARIANTS
4669         int credits_pre = txq->ift_cidx_processed;
4670 #endif  
4671
4672         if (ctx->isc_txd_credits_update == NULL)
4673                 return (0);
4674
4675         if ((credits = ctx->isc_txd_credits_update(ctx->ifc_softc, txq->ift_id, txq->ift_cidx_processed, true)) == 0)
4676                 return (0);
4677
4678         txq->ift_processed += credits;
4679         txq->ift_cidx_processed += credits;
4680
4681         MPASS(credits_pre + credits == txq->ift_cidx_processed);
4682         if (txq->ift_cidx_processed >= txq->ift_size)
4683                 txq->ift_cidx_processed -= txq->ift_size;
4684         return (credits);
4685 }
4686
4687 static int
4688 iflib_rxd_avail(if_ctx_t ctx, iflib_rxq_t rxq, int cidx, int budget)
4689 {
4690
4691         return (ctx->isc_rxd_available(ctx->ifc_softc, rxq->ifr_id, cidx,
4692             budget));
4693 }
4694
4695 void
4696 iflib_add_int_delay_sysctl(if_ctx_t ctx, const char *name,
4697         const char *description, if_int_delay_info_t info,
4698         int offset, int value)
4699 {
4700         info->iidi_ctx = ctx;
4701         info->iidi_offset = offset;
4702         info->iidi_value = value;
4703         SYSCTL_ADD_PROC(device_get_sysctl_ctx(ctx->ifc_dev),
4704             SYSCTL_CHILDREN(device_get_sysctl_tree(ctx->ifc_dev)),
4705             OID_AUTO, name, CTLTYPE_INT|CTLFLAG_RW,
4706             info, 0, iflib_sysctl_int_delay, "I", description);
4707 }
4708
4709 struct mtx *
4710 iflib_ctx_lock_get(if_ctx_t ctx)
4711 {
4712
4713         return (&ctx->ifc_mtx);
4714 }
4715
4716 static int
4717 iflib_msix_init(if_ctx_t ctx)
4718 {
4719         device_t dev = ctx->ifc_dev;
4720         if_shared_ctx_t sctx = ctx->ifc_sctx;
4721         if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
4722         int vectors, queues, rx_queues, tx_queues, queuemsgs, msgs;
4723         int iflib_num_tx_queues, iflib_num_rx_queues;
4724         int err, admincnt, bar;
4725
4726         iflib_num_tx_queues = scctx->isc_ntxqsets;
4727         iflib_num_rx_queues = scctx->isc_nrxqsets;
4728
4729         device_printf(dev, "msix_init qsets capped at %d\n", iflib_num_tx_queues);
4730         
4731         bar = ctx->ifc_softc_ctx.isc_msix_bar;
4732         admincnt = sctx->isc_admin_intrcnt;
4733         /* Override by tuneable */
4734         if (enable_msix == 0)
4735                 goto msi;
4736
4737         /*
4738         ** When used in a virtualized environment
4739         ** PCI BUSMASTER capability may not be set
4740         ** so explicity set it here and rewrite
4741         ** the ENABLE in the MSIX control register
4742         ** at this point to cause the host to
4743         ** successfully initialize us.
4744         */
4745         {
4746                 uint16_t pci_cmd_word;
4747                 int msix_ctrl, rid;
4748
4749                 rid = 0;
4750                 pci_cmd_word = pci_read_config(dev, PCIR_COMMAND, 2);
4751                 pci_cmd_word |= PCIM_CMD_BUSMASTEREN;
4752                 pci_write_config(dev, PCIR_COMMAND, pci_cmd_word, 2);
4753                 pci_find_cap(dev, PCIY_MSIX, &rid);
4754                 rid += PCIR_MSIX_CTRL;
4755                 msix_ctrl = pci_read_config(dev, rid, 2);
4756                 msix_ctrl |= PCIM_MSIXCTRL_MSIX_ENABLE;
4757                 pci_write_config(dev, rid, msix_ctrl, 2);
4758         }
4759
4760         /*
4761          * bar == -1 => "trust me I know what I'm doing"
4762          * https://www.youtube.com/watch?v=nnwWKkNau4I
4763          * Some drivers are for hardware that is so shoddily
4764          * documented that no one knows which bars are which
4765          * so the developer has to map all bars. This hack
4766          * allows shoddy garbage to use msix in this framework.
4767          */
4768         if (bar != -1) {
4769                 ctx->ifc_msix_mem = bus_alloc_resource_any(dev,
4770                     SYS_RES_MEMORY, &bar, RF_ACTIVE);
4771                 if (ctx->ifc_msix_mem == NULL) {
4772                         /* May not be enabled */
4773                         device_printf(dev, "Unable to map MSIX table \n");
4774                         goto msi;
4775                 }
4776         }
4777         /* First try MSI/X */
4778         if ((msgs = pci_msix_count(dev)) == 0) { /* system has msix disabled */
4779                 device_printf(dev, "System has MSIX disabled \n");
4780                 bus_release_resource(dev, SYS_RES_MEMORY,
4781                     bar, ctx->ifc_msix_mem);
4782                 ctx->ifc_msix_mem = NULL;
4783                 goto msi;
4784         }
4785 #if IFLIB_DEBUG
4786         /* use only 1 qset in debug mode */
4787         queuemsgs = min(msgs - admincnt, 1);
4788 #else
4789         queuemsgs = msgs - admincnt;
4790 #endif
4791         if (bus_get_cpus(dev, INTR_CPUS, sizeof(ctx->ifc_cpus), &ctx->ifc_cpus) == 0) {
4792 #ifdef RSS
4793                 queues = imin(queuemsgs, rss_getnumbuckets());
4794 #else
4795                 queues = queuemsgs;
4796 #endif
4797                 queues = imin(CPU_COUNT(&ctx->ifc_cpus), queues);
4798                 device_printf(dev, "pxm cpus: %d queue msgs: %d admincnt: %d\n",
4799                                           CPU_COUNT(&ctx->ifc_cpus), queuemsgs, admincnt);
4800         } else {
4801                 device_printf(dev, "Unable to fetch CPU list\n");
4802                 /* Figure out a reasonable auto config value */
4803                 queues = min(queuemsgs, mp_ncpus);
4804         }
4805 #ifdef  RSS
4806         /* If we're doing RSS, clamp at the number of RSS buckets */
4807         if (queues > rss_getnumbuckets())
4808                 queues = rss_getnumbuckets();
4809 #endif
4810         if (iflib_num_rx_queues > 0 && iflib_num_rx_queues < queuemsgs - admincnt)
4811                 rx_queues = iflib_num_rx_queues;
4812         else
4813                 rx_queues = queues;
4814         /*
4815          * We want this to be all logical CPUs by default
4816          */
4817         if (iflib_num_tx_queues > 0 && iflib_num_tx_queues < queues)
4818                 tx_queues = iflib_num_tx_queues;
4819         else
4820                 tx_queues = mp_ncpus;
4821
4822         if (ctx->ifc_sysctl_qs_eq_override == 0) {
4823 #ifdef INVARIANTS
4824                 if (tx_queues != rx_queues)
4825                         device_printf(dev, "queue equality override not set, capping rx_queues at %d and tx_queues at %d\n",
4826                                       min(rx_queues, tx_queues), min(rx_queues, tx_queues));
4827 #endif
4828                 tx_queues = min(rx_queues, tx_queues);
4829                 rx_queues = min(rx_queues, tx_queues);
4830         }
4831
4832         device_printf(dev, "using %d rx queues %d tx queues \n", rx_queues, tx_queues);
4833
4834         vectors = rx_queues + admincnt;
4835         if ((err = pci_alloc_msix(dev, &vectors)) == 0) {
4836                 device_printf(dev,
4837                                           "Using MSIX interrupts with %d vectors\n", vectors);
4838                 scctx->isc_vectors = vectors;
4839                 scctx->isc_nrxqsets = rx_queues;
4840                 scctx->isc_ntxqsets = tx_queues;
4841                 scctx->isc_intr = IFLIB_INTR_MSIX;
4842
4843                 return (vectors);
4844         } else {
4845                 device_printf(dev, "failed to allocate %d msix vectors, err: %d - using MSI\n", vectors, err);
4846         }
4847 msi:
4848         vectors = pci_msi_count(dev);
4849         scctx->isc_nrxqsets = 1;
4850         scctx->isc_ntxqsets = 1;
4851         scctx->isc_vectors = vectors;
4852         if (vectors == 1 && pci_alloc_msi(dev, &vectors) == 0) {
4853                 device_printf(dev,"Using an MSI interrupt\n");
4854                 scctx->isc_intr = IFLIB_INTR_MSI;
4855         } else {
4856                 device_printf(dev,"Using a Legacy interrupt\n");
4857                 scctx->isc_intr = IFLIB_INTR_LEGACY;
4858         }
4859
4860         return (vectors);
4861 }
4862
4863 char * ring_states[] = { "IDLE", "BUSY", "STALLED", "ABDICATED" };
4864
4865 static int
4866 mp_ring_state_handler(SYSCTL_HANDLER_ARGS)
4867 {
4868         int rc;
4869         uint16_t *state = ((uint16_t *)oidp->oid_arg1);
4870         struct sbuf *sb;
4871         char *ring_state = "UNKNOWN";
4872
4873         /* XXX needed ? */
4874         rc = sysctl_wire_old_buffer(req, 0);
4875         MPASS(rc == 0);
4876         if (rc != 0)
4877                 return (rc);
4878         sb = sbuf_new_for_sysctl(NULL, NULL, 80, req);
4879         MPASS(sb != NULL);
4880         if (sb == NULL)
4881                 return (ENOMEM);
4882         if (state[3] <= 3)
4883                 ring_state = ring_states[state[3]];
4884
4885         sbuf_printf(sb, "pidx_head: %04hd pidx_tail: %04hd cidx: %04hd state: %s",
4886                     state[0], state[1], state[2], ring_state);
4887         rc = sbuf_finish(sb);
4888         sbuf_delete(sb);
4889         return(rc);
4890 }
4891
4892 enum iflib_ndesc_handler {
4893         IFLIB_NTXD_HANDLER,
4894         IFLIB_NRXD_HANDLER,
4895 };
4896
4897 static int
4898 mp_ndesc_handler(SYSCTL_HANDLER_ARGS)
4899 {
4900         if_ctx_t ctx = (void *)arg1;
4901         enum iflib_ndesc_handler type = arg2;
4902         char buf[256] = {0};
4903         uint16_t *ndesc;
4904         char *p, *next;
4905         int nqs, rc, i;
4906
4907         MPASS(type == IFLIB_NTXD_HANDLER || type == IFLIB_NRXD_HANDLER);
4908
4909         nqs = 8;
4910         switch(type) {
4911         case IFLIB_NTXD_HANDLER:
4912                 ndesc = ctx->ifc_sysctl_ntxds;
4913                 if (ctx->ifc_sctx)
4914                         nqs = ctx->ifc_sctx->isc_ntxqs;
4915                 break;
4916         case IFLIB_NRXD_HANDLER:
4917                 ndesc = ctx->ifc_sysctl_nrxds;
4918                 if (ctx->ifc_sctx)
4919                         nqs = ctx->ifc_sctx->isc_nrxqs;
4920                 break;
4921         }
4922         if (nqs == 0)
4923                 nqs = 8;
4924
4925         for (i=0; i<8; i++) {
4926                 if (i >= nqs)
4927                         break;
4928                 if (i)
4929                         strcat(buf, ",");
4930                 sprintf(strchr(buf, 0), "%d", ndesc[i]);
4931         }
4932
4933         rc = sysctl_handle_string(oidp, buf, sizeof(buf), req);
4934         if (rc || req->newptr == NULL)
4935                 return rc;
4936
4937         for (i = 0, next = buf, p = strsep(&next, " ,"); i < 8 && p;
4938             i++, p = strsep(&next, " ,")) {
4939                 ndesc[i] = strtoul(p, NULL, 10);
4940         }
4941
4942         return(rc);
4943 }
4944
4945 #define NAME_BUFLEN 32
4946 static void
4947 iflib_add_device_sysctl_pre(if_ctx_t ctx)
4948 {
4949         device_t dev = iflib_get_dev(ctx);
4950         struct sysctl_oid_list *child, *oid_list;
4951         struct sysctl_ctx_list *ctx_list;
4952         struct sysctl_oid *node;
4953
4954         ctx_list = device_get_sysctl_ctx(dev);
4955         child = SYSCTL_CHILDREN(device_get_sysctl_tree(dev));
4956         ctx->ifc_sysctl_node = node = SYSCTL_ADD_NODE(ctx_list, child, OID_AUTO, "iflib",
4957                                                       CTLFLAG_RD, NULL, "IFLIB fields");
4958         oid_list = SYSCTL_CHILDREN(node);
4959
4960         SYSCTL_ADD_STRING(ctx_list, oid_list, OID_AUTO, "driver_version",
4961                        CTLFLAG_RD, ctx->ifc_sctx->isc_driver_version, 0,
4962                        "driver version");
4963
4964         SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_ntxqs",
4965                        CTLFLAG_RWTUN, &ctx->ifc_sysctl_ntxqs, 0,
4966                         "# of txqs to use, 0 => use default #");
4967         SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_nrxqs",
4968                        CTLFLAG_RWTUN, &ctx->ifc_sysctl_nrxqs, 0,
4969                         "# of rxqs to use, 0 => use default #");
4970         SYSCTL_ADD_U16(ctx_list, oid_list, OID_AUTO, "override_qs_enable",
4971                        CTLFLAG_RWTUN, &ctx->ifc_sysctl_qs_eq_override, 0,
4972                        "permit #txq != #rxq");
4973
4974         /* XXX change for per-queue sizes */
4975         SYSCTL_ADD_PROC(ctx_list, oid_list, OID_AUTO, "override_ntxds",
4976                        CTLTYPE_STRING|CTLFLAG_RWTUN, ctx, IFLIB_NTXD_HANDLER,
4977                        mp_ndesc_handler, "A",
4978                        "list of # of tx descriptors to use, 0 = use default #");
4979         SYSCTL_ADD_PROC(ctx_list, oid_list, OID_AUTO, "override_nrxds",
4980                        CTLTYPE_STRING|CTLFLAG_RWTUN, ctx, IFLIB_NRXD_HANDLER,
4981                        mp_ndesc_handler, "A",
4982                        "list of # of rx descriptors to use, 0 = use default #");
4983 }
4984
4985 static void
4986 iflib_add_device_sysctl_post(if_ctx_t ctx)
4987 {
4988         if_shared_ctx_t sctx = ctx->ifc_sctx;
4989         if_softc_ctx_t scctx = &ctx->ifc_softc_ctx;
4990         device_t dev = iflib_get_dev(ctx);
4991         struct sysctl_oid_list *child;
4992         struct sysctl_ctx_list *ctx_list;
4993         iflib_fl_t fl;
4994         iflib_txq_t txq;
4995         iflib_rxq_t rxq;
4996         int i, j;
4997         char namebuf[NAME_BUFLEN];
4998         char *qfmt;
4999         struct sysctl_oid *queue_node, *fl_node, *node;
5000         struct sysctl_oid_list *queue_list, *fl_list;
5001         ctx_list = device_get_sysctl_ctx(dev);
5002
5003         node = ctx->ifc_sysctl_node;
5004         child = SYSCTL_CHILDREN(node);
5005
5006         if (scctx->isc_ntxqsets > 100)
5007                 qfmt = "txq%03d";
5008         else if (scctx->isc_ntxqsets > 10)
5009                 qfmt = "txq%02d";
5010         else
5011                 qfmt = "txq%d";
5012         for (i = 0, txq = ctx->ifc_txqs; i < scctx->isc_ntxqsets; i++, txq++) {
5013                 snprintf(namebuf, NAME_BUFLEN, qfmt, i);
5014                 queue_node = SYSCTL_ADD_NODE(ctx_list, child, OID_AUTO, namebuf,
5015                                              CTLFLAG_RD, NULL, "Queue Name");
5016                 queue_list = SYSCTL_CHILDREN(queue_node);
5017 #if MEMORY_LOGGING
5018                 SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "txq_dequeued",
5019                                 CTLFLAG_RD,
5020                                 &txq->ift_dequeued, "total mbufs freed");
5021                 SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "txq_enqueued",
5022                                 CTLFLAG_RD,
5023                                 &txq->ift_enqueued, "total mbufs enqueued");
5024 #endif
5025                 SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "mbuf_defrag",
5026                                    CTLFLAG_RD,
5027                                    &txq->ift_mbuf_defrag, "# of times m_defrag was called");
5028                 SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "m_pullups",
5029                                    CTLFLAG_RD,
5030                                    &txq->ift_pullups, "# of times m_pullup was called");
5031                 SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "mbuf_defrag_failed",
5032                                    CTLFLAG_RD,
5033                                    &txq->ift_mbuf_defrag_failed, "# of times m_defrag failed");
5034                 SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "no_desc_avail",
5035                                    CTLFLAG_RD,
5036                                    &txq->ift_no_desc_avail, "# of times no descriptors were available");
5037                 SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "tx_map_failed",
5038                                    CTLFLAG_RD,
5039                                    &txq->ift_map_failed, "# of times dma map failed");
5040                 SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "txd_encap_efbig",
5041                                    CTLFLAG_RD,
5042                                    &txq->ift_txd_encap_efbig, "# of times txd_encap returned EFBIG");
5043                 SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "no_tx_dma_setup",
5044                                    CTLFLAG_RD,
5045                                    &txq->ift_no_tx_dma_setup, "# of times map failed for other than EFBIG");
5046                 SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_pidx",
5047                                    CTLFLAG_RD,
5048                                    &txq->ift_pidx, 1, "Producer Index");
5049                 SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_cidx",
5050                                    CTLFLAG_RD,
5051                                    &txq->ift_cidx, 1, "Consumer Index");
5052                 SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_cidx_processed",
5053                                    CTLFLAG_RD,
5054                                    &txq->ift_cidx_processed, 1, "Consumer Index seen by credit update");
5055                 SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "txq_in_use",
5056                                    CTLFLAG_RD,
5057                                    &txq->ift_in_use, 1, "descriptors in use");
5058                 SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "txq_processed",
5059                                    CTLFLAG_RD,
5060                                    &txq->ift_processed, "descriptors procesed for clean");
5061                 SYSCTL_ADD_QUAD(ctx_list, queue_list, OID_AUTO, "txq_cleaned",
5062                                    CTLFLAG_RD,
5063                                    &txq->ift_cleaned, "total cleaned");
5064                 SYSCTL_ADD_PROC(ctx_list, queue_list, OID_AUTO, "ring_state",
5065                                 CTLTYPE_STRING | CTLFLAG_RD, __DEVOLATILE(uint64_t *, &txq->ift_br[0]->state),
5066                                 0, mp_ring_state_handler, "A", "soft ring state");
5067                 SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_enqueues",
5068                                        CTLFLAG_RD, &txq->ift_br[0]->enqueues,
5069                                        "# of enqueues to the mp_ring for this queue");
5070                 SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_drops",
5071                                        CTLFLAG_RD, &txq->ift_br[0]->drops,
5072                                        "# of drops in the mp_ring for this queue");
5073                 SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_starts",
5074                                        CTLFLAG_RD, &txq->ift_br[0]->starts,
5075                                        "# of normal consumer starts in the mp_ring for this queue");
5076                 SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_stalls",
5077                                        CTLFLAG_RD, &txq->ift_br[0]->stalls,
5078                                                "# of consumer stalls in the mp_ring for this queue");
5079                 SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_restarts",
5080                                CTLFLAG_RD, &txq->ift_br[0]->restarts,
5081                                        "# of consumer restarts in the mp_ring for this queue");
5082                 SYSCTL_ADD_COUNTER_U64(ctx_list, queue_list, OID_AUTO, "r_abdications",
5083                                        CTLFLAG_RD, &txq->ift_br[0]->abdications,
5084                                        "# of consumer abdications in the mp_ring for this queue");
5085         }
5086
5087         if (scctx->isc_nrxqsets > 100)
5088                 qfmt = "rxq%03d";
5089         else if (scctx->isc_nrxqsets > 10)
5090                 qfmt = "rxq%02d";
5091         else
5092                 qfmt = "rxq%d";
5093         for (i = 0, rxq = ctx->ifc_rxqs; i < scctx->isc_nrxqsets; i++, rxq++) {
5094                 snprintf(namebuf, NAME_BUFLEN, qfmt, i);
5095                 queue_node = SYSCTL_ADD_NODE(ctx_list, child, OID_AUTO, namebuf,
5096                                              CTLFLAG_RD, NULL, "Queue Name");
5097                 queue_list = SYSCTL_CHILDREN(queue_node);
5098                 if (sctx->isc_flags & IFLIB_HAS_RXCQ) {
5099                         SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "rxq_cq_pidx",
5100                                        CTLFLAG_RD,
5101                                        &rxq->ifr_cq_pidx, 1, "Producer Index");
5102                         SYSCTL_ADD_U16(ctx_list, queue_list, OID_AUTO, "rxq_cq_cidx",
5103                                        CTLFLAG_RD,
5104                                        &rxq->ifr_cq_cidx, 1, "Consumer Index");
5105                 }
5106
5107                 for (j = 0, fl = rxq->ifr_fl; j < rxq->ifr_nfl; j++, fl++) {
5108                         snprintf(namebuf, NAME_BUFLEN, "rxq_fl%d", j);
5109                         fl_node = SYSCTL_ADD_NODE(ctx_list, queue_list, OID_AUTO, namebuf,
5110                                                      CTLFLAG_RD, NULL, "freelist Name");
5111                         fl_list = SYSCTL_CHILDREN(fl_node);
5112                         SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "pidx",
5113                                        CTLFLAG_RD,
5114                                        &fl->ifl_pidx, 1, "Producer Index");
5115                         SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "cidx",
5116                                        CTLFLAG_RD,
5117                                        &fl->ifl_cidx, 1, "Consumer Index");
5118                         SYSCTL_ADD_U16(ctx_list, fl_list, OID_AUTO, "credits",
5119                                        CTLFLAG_RD,
5120                                        &fl->ifl_credits, 1, "credits available");
5121 #if MEMORY_LOGGING
5122                         SYSCTL_ADD_QUAD(ctx_list, fl_list, OID_AUTO, "fl_m_enqueued",
5123                                         CTLFLAG_RD,
5124                                         &fl->ifl_m_enqueued, "mbufs allocated");
5125                         SYSCTL_ADD_QUAD(ctx_list, fl_list, OID_AUTO, "fl_m_dequeued",
5126                                         CTLFLAG_RD,
5127                                         &fl->ifl_m_dequeued, "mbufs freed");
5128                         SYSCTL_ADD_QUAD(ctx_list, fl_list, OID_AUTO, "fl_cl_enqueued",
5129                                         CTLFLAG_RD,
5130                                         &fl->ifl_cl_enqueued, "clusters allocated");
5131                         SYSCTL_ADD_QUAD(ctx_list, fl_list, OID_AUTO, "fl_cl_dequeued",
5132                                         CTLFLAG_RD,
5133                                         &fl->ifl_cl_dequeued, "clusters freed");
5134 #endif
5135
5136                 }
5137         }
5138
5139 }