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