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