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