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