]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/ena/ena.c
Fix calculating io queues number in ENA driver
[FreeBSD/FreeBSD.git] / sys / dev / ena / ena.c
1 /*-
2  * BSD LICENSE
3  *
4  * Copyright (c) 2015-2017 Amazon.com, Inc. or its affiliates.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/bus.h>
36 #include <sys/endian.h>
37 #include <sys/kernel.h>
38 #include <sys/kthread.h>
39 #include <sys/malloc.h>
40 #include <sys/mbuf.h>
41 #include <sys/module.h>
42 #include <sys/rman.h>
43 #include <sys/smp.h>
44 #include <sys/socket.h>
45 #include <sys/sockio.h>
46 #include <sys/sysctl.h>
47 #include <sys/taskqueue.h>
48 #include <sys/time.h>
49 #include <sys/eventhandler.h>
50
51 #include <machine/bus.h>
52 #include <machine/resource.h>
53 #include <machine/in_cksum.h>
54
55 #include <net/bpf.h>
56 #include <net/ethernet.h>
57 #include <net/if.h>
58 #include <net/if_var.h>
59 #include <net/if_arp.h>
60 #include <net/if_dl.h>
61 #include <net/if_media.h>
62 #include <net/rss_config.h>
63 #include <net/if_types.h>
64 #include <net/if_vlan_var.h>
65
66 #include <netinet/in_rss.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/in.h>
69 #include <netinet/if_ether.h>
70 #include <netinet/ip.h>
71 #include <netinet/ip6.h>
72 #include <netinet/tcp.h>
73 #include <netinet/udp.h>
74
75 #include <dev/pci/pcivar.h>
76 #include <dev/pci/pcireg.h>
77
78 #include "ena.h"
79 #include "ena_sysctl.h"
80
81 /*********************************************************
82  *  Function prototypes
83  *********************************************************/
84 static int      ena_probe(device_t);
85 static void     ena_intr_msix_mgmnt(void *);
86 static int      ena_allocate_pci_resources(struct ena_adapter*);
87 static void     ena_free_pci_resources(struct ena_adapter *);
88 static int      ena_change_mtu(if_t, int);
89 static inline void ena_alloc_counters(counter_u64_t *, int);
90 static inline void ena_free_counters(counter_u64_t *, int);
91 static inline void ena_reset_counters(counter_u64_t *, int);
92 static void     ena_init_io_rings_common(struct ena_adapter *,
93     struct ena_ring *, uint16_t);
94 static void     ena_init_io_rings(struct ena_adapter *);
95 static void     ena_free_io_ring_resources(struct ena_adapter *, unsigned int);
96 static void     ena_free_all_io_rings_resources(struct ena_adapter *);
97 static int      ena_setup_tx_dma_tag(struct ena_adapter *);
98 static int      ena_free_tx_dma_tag(struct ena_adapter *);
99 static int      ena_setup_rx_dma_tag(struct ena_adapter *);
100 static int      ena_free_rx_dma_tag(struct ena_adapter *);
101 static int      ena_setup_tx_resources(struct ena_adapter *, int);
102 static void     ena_free_tx_resources(struct ena_adapter *, int);
103 static int      ena_setup_all_tx_resources(struct ena_adapter *);
104 static void     ena_free_all_tx_resources(struct ena_adapter *);
105 static inline int validate_rx_req_id(struct ena_ring *, uint16_t);
106 static int      ena_setup_rx_resources(struct ena_adapter *, unsigned int);
107 static void     ena_free_rx_resources(struct ena_adapter *, unsigned int);
108 static int      ena_setup_all_rx_resources(struct ena_adapter *);
109 static void     ena_free_all_rx_resources(struct ena_adapter *);
110 static inline int ena_alloc_rx_mbuf(struct ena_adapter *, struct ena_ring *,
111     struct ena_rx_buffer *);
112 static void     ena_free_rx_mbuf(struct ena_adapter *, struct ena_ring *,
113     struct ena_rx_buffer *);
114 static int      ena_refill_rx_bufs(struct ena_ring *, uint32_t);
115 static void     ena_free_rx_bufs(struct ena_adapter *, unsigned int);
116 static void     ena_refill_all_rx_bufs(struct ena_adapter *);
117 static void     ena_free_all_rx_bufs(struct ena_adapter *);
118 static void     ena_free_tx_bufs(struct ena_adapter *, unsigned int);
119 static void     ena_free_all_tx_bufs(struct ena_adapter *);
120 static void     ena_destroy_all_tx_queues(struct ena_adapter *);
121 static void     ena_destroy_all_rx_queues(struct ena_adapter *);
122 static void     ena_destroy_all_io_queues(struct ena_adapter *);
123 static int      ena_create_io_queues(struct ena_adapter *);
124 static int      ena_tx_cleanup(struct ena_ring *);
125 static void     ena_deferred_rx_cleanup(void *, int);
126 static int      ena_rx_cleanup(struct ena_ring *);
127 static inline int validate_tx_req_id(struct ena_ring *, uint16_t);
128 static void     ena_rx_hash_mbuf(struct ena_ring *, struct ena_com_rx_ctx *,
129     struct mbuf *);
130 static struct mbuf* ena_rx_mbuf(struct ena_ring *, struct ena_com_rx_buf_info *,
131     struct ena_com_rx_ctx *, uint16_t *);
132 static inline void ena_rx_checksum(struct ena_ring *, struct ena_com_rx_ctx *,
133     struct mbuf *);
134 static void     ena_handle_msix(void *);
135 static int      ena_enable_msix(struct ena_adapter *);
136 static void     ena_setup_mgmnt_intr(struct ena_adapter *);
137 static void     ena_setup_io_intr(struct ena_adapter *);
138 static int      ena_request_mgmnt_irq(struct ena_adapter *);
139 static int      ena_request_io_irq(struct ena_adapter *);
140 static void     ena_free_mgmnt_irq(struct ena_adapter *);
141 static void     ena_free_io_irq(struct ena_adapter *);
142 static void     ena_free_irqs(struct ena_adapter*);
143 static void     ena_disable_msix(struct ena_adapter *);
144 static void     ena_unmask_all_io_irqs(struct ena_adapter *);
145 static int      ena_rss_configure(struct ena_adapter *);
146 static int      ena_up_complete(struct ena_adapter *);
147 static int      ena_up(struct ena_adapter *);
148 static void     ena_down(struct ena_adapter *);
149 static uint64_t ena_get_counter(if_t, ift_counter);
150 static int      ena_media_change(if_t);
151 static void     ena_media_status(if_t, struct ifmediareq *);
152 static void     ena_init(void *);
153 static int      ena_ioctl(if_t, u_long, caddr_t);
154 static int      ena_get_dev_offloads(struct ena_com_dev_get_features_ctx *);
155 static void     ena_update_host_info(struct ena_admin_host_info *, if_t);
156 static void     ena_update_hwassist(struct ena_adapter *);
157 static int      ena_setup_ifnet(device_t, struct ena_adapter *,
158     struct ena_com_dev_get_features_ctx *);
159 static void     ena_tx_csum(struct ena_com_tx_ctx *, struct mbuf *);
160 static int      ena_check_and_collapse_mbuf(struct ena_ring *tx_ring,
161     struct mbuf **mbuf);
162 static int      ena_xmit_mbuf(struct ena_ring *, struct mbuf **);
163 static void     ena_start_xmit(struct ena_ring *);
164 static int      ena_mq_start(if_t, struct mbuf *);
165 static void     ena_deferred_mq_start(void *, int);
166 static void     ena_qflush(if_t);
167 static int      ena_calc_io_queue_num(struct ena_adapter *,
168     struct ena_com_dev_get_features_ctx *);
169 static int      ena_calc_queue_size(struct ena_adapter *, uint16_t *,
170     uint16_t *, struct ena_com_dev_get_features_ctx *);
171 static int      ena_rss_init_default(struct ena_adapter *);
172 static void     ena_rss_init_default_deferred(void *);
173 static void     ena_config_host_info(struct ena_com_dev *);
174 static int      ena_attach(device_t);
175 static int      ena_detach(device_t);
176 static int      ena_device_init(struct ena_adapter *, device_t,
177     struct ena_com_dev_get_features_ctx *, int *);
178 static int      ena_enable_msix_and_set_admin_interrupts(struct ena_adapter *,
179     int);
180 static void ena_update_on_link_change(void *, struct ena_admin_aenq_entry *);
181 static void     unimplemented_aenq_handler(void *,
182     struct ena_admin_aenq_entry *);
183 static void     ena_timer_service(void *);
184
185 static char ena_version[] = DEVICE_NAME DRV_MODULE_NAME " v" DRV_MODULE_VERSION;
186
187 static SYSCTL_NODE(_hw, OID_AUTO, ena, CTLFLAG_RD, 0, "ENA driver parameters");
188
189 /*
190  * Tuneable number of buffers in the buf-ring (drbr)
191  */
192 static int ena_buf_ring_size = 4096;
193 SYSCTL_INT(_hw_ena, OID_AUTO, buf_ring_size, CTLFLAG_RWTUN,
194     &ena_buf_ring_size, 0, "Size of the bufring");
195
196 /*
197  * Logging level for changing verbosity of the output
198  */
199 int ena_log_level = ENA_ALERT | ENA_WARNING;
200 SYSCTL_INT(_hw_ena, OID_AUTO, log_level, CTLFLAG_RWTUN,
201     &ena_log_level, 0, "Logging level indicating verbosity of the logs");
202
203 static ena_vendor_info_t ena_vendor_info_array[] = {
204     { PCI_VENDOR_ID_AMAZON, PCI_DEV_ID_ENA_PF, 0},
205     { PCI_VENDOR_ID_AMAZON, PCI_DEV_ID_ENA_LLQ_PF, 0},
206     { PCI_VENDOR_ID_AMAZON, PCI_DEV_ID_ENA_VF, 0},
207     { PCI_VENDOR_ID_AMAZON, PCI_DEV_ID_ENA_LLQ_VF, 0},
208     /* Last entry */
209     { 0, 0, 0 }
210 };
211
212 /*
213  * Contains pointers to event handlers, e.g. link state chage.
214  */
215 static struct ena_aenq_handlers aenq_handlers;
216
217 void
218 ena_dmamap_callback(void *arg, bus_dma_segment_t *segs, int nseg, int error)
219 {
220         if (error != 0)
221                 return;
222         *(bus_addr_t *) arg = segs[0].ds_addr;
223 }
224
225 int
226 ena_dma_alloc(device_t dmadev, bus_size_t size,
227     ena_mem_handle_t *dma , int mapflags)
228 {
229         struct ena_adapter* adapter = device_get_softc(dmadev);
230         uint32_t maxsize;
231         uint64_t dma_space_addr;
232         int error;
233
234         maxsize = ((size - 1) / PAGE_SIZE + 1) * PAGE_SIZE;
235
236         dma_space_addr = ENA_DMA_BIT_MASK(adapter->dma_width);
237         if (unlikely(dma_space_addr == 0))
238                 dma_space_addr = BUS_SPACE_MAXADDR;
239
240         error = bus_dma_tag_create(bus_get_dma_tag(dmadev), /* parent */
241             8, 0,             /* alignment, bounds              */
242             dma_space_addr,   /* lowaddr of exclusion window    */
243             BUS_SPACE_MAXADDR,/* highaddr of exclusion window   */
244             NULL, NULL,       /* filter, filterarg              */
245             maxsize,          /* maxsize                        */
246             1,                /* nsegments                      */
247             maxsize,          /* maxsegsize                     */
248             BUS_DMA_ALLOCNOW, /* flags                          */
249             NULL,             /* lockfunc                       */
250             NULL,             /* lockarg                        */
251             &dma->tag);
252         if (unlikely(error != 0)) {
253                 ena_trace(ENA_ALERT, "bus_dma_tag_create failed: %d\n", error);
254                 goto fail_tag;
255         }
256
257         error = bus_dmamem_alloc(dma->tag, (void**) &dma->vaddr,
258             BUS_DMA_COHERENT | BUS_DMA_ZERO, &dma->map);
259         if (unlikely(error != 0)) {
260                 ena_trace(ENA_ALERT, "bus_dmamem_alloc(%ju) failed: %d\n",
261                     (uintmax_t)size, error);
262                 goto fail_map_create;
263         }
264
265         dma->paddr = 0;
266         error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr,
267             size, ena_dmamap_callback, &dma->paddr, mapflags);
268         if (unlikely((error != 0) || (dma->paddr == 0))) {
269                 ena_trace(ENA_ALERT, ": bus_dmamap_load failed: %d\n", error);
270                 goto fail_map_load;
271         }
272
273         return (0);
274
275 fail_map_load:
276         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
277 fail_map_create:
278         bus_dma_tag_destroy(dma->tag);
279 fail_tag:
280         dma->tag = NULL;
281
282         return (error);
283 }
284
285 static int
286 ena_allocate_pci_resources(struct ena_adapter* adapter)
287 {
288         device_t pdev = adapter->pdev;
289         int rid;
290
291         rid = PCIR_BAR(ENA_REG_BAR);
292         adapter->memory = NULL;
293         adapter->registers = bus_alloc_resource_any(pdev, SYS_RES_MEMORY,
294             &rid, RF_ACTIVE);
295         if (unlikely(adapter->registers == NULL)) {
296                 device_printf(pdev, "Unable to allocate bus resource: "
297                     "registers\n");
298                 return (ENXIO);
299         }
300
301         return (0);
302 }
303
304 static void
305 ena_free_pci_resources(struct ena_adapter *adapter)
306 {
307         device_t pdev = adapter->pdev;
308
309         if (adapter->memory != NULL) {
310                 bus_release_resource(pdev, SYS_RES_MEMORY,
311                     PCIR_BAR(ENA_MEM_BAR), adapter->memory);
312         }
313
314         if (adapter->registers != NULL) {
315                 bus_release_resource(pdev, SYS_RES_MEMORY,
316                     PCIR_BAR(ENA_REG_BAR), adapter->registers);
317         }
318 }
319
320 static int
321 ena_probe(device_t dev)
322 {
323         ena_vendor_info_t *ent;
324         char            adapter_name[60];
325         uint16_t        pci_vendor_id = 0;
326         uint16_t        pci_device_id = 0;
327
328         pci_vendor_id = pci_get_vendor(dev);
329         pci_device_id = pci_get_device(dev);
330
331         ent = ena_vendor_info_array;
332         while (ent->vendor_id != 0) {
333                 if ((pci_vendor_id == ent->vendor_id) &&
334                     (pci_device_id == ent->device_id)) {
335                         ena_trace(ENA_DBG, "vendor=%x device=%x ",
336                             pci_vendor_id, pci_device_id);
337
338                         sprintf(adapter_name, DEVICE_DESC);
339                         device_set_desc_copy(dev, adapter_name);
340                         return (BUS_PROBE_DEFAULT);
341                 }
342
343                 ent++;
344
345         }
346
347         return (ENXIO);
348 }
349
350 static int
351 ena_change_mtu(if_t ifp, int new_mtu)
352 {
353         struct ena_adapter *adapter = if_getsoftc(ifp);
354         struct ena_com_dev_get_features_ctx get_feat_ctx;
355         int rc, old_mtu, max_frame;
356
357         rc = ena_com_get_dev_attr_feat(adapter->ena_dev, &get_feat_ctx);
358         if (unlikely(rc != 0)) {
359                 device_printf(adapter->pdev,
360                     "Cannot get attribute for ena device\n");
361                 return (ENXIO);
362         }
363
364         /* Save old MTU in case of fail */
365         old_mtu = if_getmtu(ifp);
366
367         /* Change MTU and calculate max frame */
368         if_setmtu(ifp, new_mtu);
369         max_frame = ETHER_MAX_FRAME(ifp, ETHERTYPE_VLAN, 1);
370
371         if (unlikely((new_mtu < ENA_MIN_FRAME_LEN) ||
372             (new_mtu > get_feat_ctx.dev_attr.max_mtu) ||
373             (max_frame > ENA_MAX_FRAME_LEN))) {
374                 device_printf(adapter->pdev, "Invalid MTU setting. "
375                     "new_mtu: %d\n", new_mtu);
376                 goto error;
377         }
378
379         rc = ena_com_set_dev_mtu(adapter->ena_dev, new_mtu);
380         if (rc != 0)
381                 goto error;
382
383         return (0);
384 error:
385         if_setmtu(ifp, old_mtu);
386         return (EINVAL);
387 }
388
389 static inline void
390 ena_alloc_counters(counter_u64_t *begin, int size)
391 {
392         counter_u64_t *end = (counter_u64_t *)((char *)begin + size);
393
394         for (; begin < end; ++begin)
395                 *begin = counter_u64_alloc(M_WAITOK);
396 }
397
398 static inline void
399 ena_free_counters(counter_u64_t *begin, int size)
400 {
401         counter_u64_t *end = (counter_u64_t *)((char *)begin + size);
402
403         for (; begin < end; ++begin)
404                 counter_u64_free(*begin);
405 }
406
407 static inline void
408 ena_reset_counters(counter_u64_t *begin, int size)
409 {
410         counter_u64_t *end = (counter_u64_t *)((char *)begin + size);
411
412         for (; begin < end; ++begin)
413                 counter_u64_zero(*begin);
414 }
415
416 static void
417 ena_init_io_rings_common(struct ena_adapter *adapter, struct ena_ring *ring,
418     uint16_t qid)
419 {
420
421         ring->qid = qid;
422         ring->adapter = adapter;
423         ring->ena_dev = adapter->ena_dev;
424 }
425
426 static void
427 ena_init_io_rings(struct ena_adapter *adapter)
428 {
429         struct ena_com_dev *ena_dev;
430         struct ena_ring *txr, *rxr;
431         struct ena_que *que;
432         int i;
433
434         ena_dev = adapter->ena_dev;
435
436         for (i = 0; i < adapter->num_queues; i++) {
437                 txr = &adapter->tx_ring[i];
438                 rxr = &adapter->rx_ring[i];
439
440                 /* TX/RX common ring state */
441                 ena_init_io_rings_common(adapter, txr, i);
442                 ena_init_io_rings_common(adapter, rxr, i);
443
444                 /* TX specific ring state */
445                 txr->ring_size = adapter->tx_ring_size;
446                 txr->tx_max_header_size = ena_dev->tx_max_header_size;
447                 txr->tx_mem_queue_type = ena_dev->tx_mem_queue_type;
448                 txr->smoothed_interval =
449                     ena_com_get_nonadaptive_moderation_interval_tx(ena_dev);
450
451                 /* Allocate a buf ring */
452                 txr->br = buf_ring_alloc(ena_buf_ring_size, M_DEVBUF,
453                     M_WAITOK, &txr->ring_mtx);
454
455                 /* Alloc TX statistics. */
456                 ena_alloc_counters((counter_u64_t *)&txr->tx_stats,
457                     sizeof(txr->tx_stats));
458
459                 /* RX specific ring state */
460                 rxr->ring_size = adapter->rx_ring_size;
461                 rxr->smoothed_interval =
462                     ena_com_get_nonadaptive_moderation_interval_rx(ena_dev);
463
464                 /* Alloc RX statistics. */
465                 ena_alloc_counters((counter_u64_t *)&rxr->rx_stats,
466                     sizeof(rxr->rx_stats));
467
468                 /* Initialize locks */
469                 snprintf(txr->mtx_name, nitems(txr->mtx_name), "%s:tx(%d)",
470                     device_get_nameunit(adapter->pdev), i);
471                 snprintf(rxr->mtx_name, nitems(rxr->mtx_name), "%s:rx(%d)",
472                     device_get_nameunit(adapter->pdev), i);
473
474                 mtx_init(&txr->ring_mtx, txr->mtx_name, NULL, MTX_DEF);
475                 mtx_init(&rxr->ring_mtx, rxr->mtx_name, NULL, MTX_DEF);
476
477                 que = &adapter->que[i];
478                 que->adapter = adapter;
479                 que->id = i;
480                 que->tx_ring = txr;
481                 que->rx_ring = rxr;
482
483                 txr->que = que;
484                 rxr->que = que;
485
486                 rxr->empty_rx_queue = 0;
487         }
488 }
489
490 static void
491 ena_free_io_ring_resources(struct ena_adapter *adapter, unsigned int qid)
492 {
493         struct ena_ring *txr = &adapter->tx_ring[qid];
494         struct ena_ring *rxr = &adapter->rx_ring[qid];
495
496         ena_free_counters((counter_u64_t *)&txr->tx_stats,
497             sizeof(txr->tx_stats));
498         ena_free_counters((counter_u64_t *)&rxr->rx_stats,
499             sizeof(rxr->rx_stats));
500
501         ENA_RING_MTX_LOCK(txr);
502         drbr_free(txr->br, M_DEVBUF);
503         ENA_RING_MTX_UNLOCK(txr);
504
505         mtx_destroy(&txr->ring_mtx);
506         mtx_destroy(&rxr->ring_mtx);
507 }
508
509 static void
510 ena_free_all_io_rings_resources(struct ena_adapter *adapter)
511 {
512         int i;
513
514         for (i = 0; i < adapter->num_queues; i++)
515                 ena_free_io_ring_resources(adapter, i);
516
517 }
518
519 static int
520 ena_setup_tx_dma_tag(struct ena_adapter *adapter)
521 {
522         int ret;
523
524         /* Create DMA tag for Tx buffers */
525         ret = bus_dma_tag_create(bus_get_dma_tag(adapter->pdev),
526             1, 0,                                 /* alignment, bounds       */
527             ENA_DMA_BIT_MASK(adapter->dma_width), /* lowaddr of excl window  */
528             BUS_SPACE_MAXADDR,                    /* highaddr of excl window */
529             NULL, NULL,                           /* filter, filterarg       */
530             ENA_TSO_MAXSIZE,                      /* maxsize                 */
531             adapter->max_tx_sgl_size - 1,         /* nsegments               */
532             ENA_TSO_MAXSIZE,                      /* maxsegsize              */
533             0,                                    /* flags                   */
534             NULL,                                 /* lockfunc                */
535             NULL,                                 /* lockfuncarg             */
536             &adapter->tx_buf_tag);
537
538         return (ret);
539 }
540
541 static int
542 ena_free_tx_dma_tag(struct ena_adapter *adapter)
543 {
544         int ret;
545
546         ret = bus_dma_tag_destroy(adapter->tx_buf_tag);
547
548         if (likely(ret == 0))
549                 adapter->tx_buf_tag = NULL;
550
551         return (ret);
552 }
553
554 static int
555 ena_setup_rx_dma_tag(struct ena_adapter *adapter)
556 {
557         int ret;
558
559         /* Create DMA tag for Rx buffers*/
560         ret = bus_dma_tag_create(bus_get_dma_tag(adapter->pdev), /* parent   */
561             1, 0,                                 /* alignment, bounds       */
562             ENA_DMA_BIT_MASK(adapter->dma_width), /* lowaddr of excl window  */
563             BUS_SPACE_MAXADDR,                    /* highaddr of excl window */
564             NULL, NULL,                           /* filter, filterarg       */
565             MJUM16BYTES,                          /* maxsize                 */
566             1,                                    /* nsegments               */
567             MJUM16BYTES,                          /* maxsegsize              */
568             0,                                    /* flags                   */
569             NULL,                                 /* lockfunc                */
570             NULL,                                 /* lockarg                 */
571             &adapter->rx_buf_tag);
572
573         return (ret);
574 }
575
576 static int
577 ena_free_rx_dma_tag(struct ena_adapter *adapter)
578 {
579         int ret;
580
581         ret = bus_dma_tag_destroy(adapter->rx_buf_tag);
582
583         if (likely(ret == 0))
584                 adapter->rx_buf_tag = NULL;
585
586         return (ret);
587 }
588
589 /**
590  * ena_setup_tx_resources - allocate Tx resources (Descriptors)
591  * @adapter: network interface device structure
592  * @qid: queue index
593  *
594  * Returns 0 on success, otherwise on failure.
595  **/
596 static int
597 ena_setup_tx_resources(struct ena_adapter *adapter, int qid)
598 {
599         struct ena_que *que = &adapter->que[qid];
600         struct ena_ring *tx_ring = que->tx_ring;
601         int size, i, err;
602 #ifdef  RSS
603         cpuset_t cpu_mask;
604 #endif
605
606         size = sizeof(struct ena_tx_buffer) * tx_ring->ring_size;
607
608         tx_ring->tx_buffer_info = malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
609         if (unlikely(tx_ring->tx_buffer_info == NULL))
610                 return (ENOMEM);
611
612         size = sizeof(uint16_t) * tx_ring->ring_size;
613         tx_ring->free_tx_ids = malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
614         if (unlikely(tx_ring->free_tx_ids == NULL))
615                 goto err_buf_info_free;
616
617         /* Req id stack for TX OOO completions */
618         for (i = 0; i < tx_ring->ring_size; i++)
619                 tx_ring->free_tx_ids[i] = i;
620
621         /* Reset TX statistics. */
622         ena_reset_counters((counter_u64_t *)&tx_ring->tx_stats,
623             sizeof(tx_ring->tx_stats));
624
625         tx_ring->next_to_use = 0;
626         tx_ring->next_to_clean = 0;
627
628         /* Make sure that drbr is empty */
629         ENA_RING_MTX_LOCK(tx_ring);
630         drbr_flush(adapter->ifp, tx_ring->br);
631         ENA_RING_MTX_UNLOCK(tx_ring);
632
633         /* ... and create the buffer DMA maps */
634         for (i = 0; i < tx_ring->ring_size; i++) {
635                 err = bus_dmamap_create(adapter->tx_buf_tag, 0,
636                     &tx_ring->tx_buffer_info[i].map);
637                 if (unlikely(err != 0)) {
638                         ena_trace(ENA_ALERT,
639                              "Unable to create Tx DMA map for buffer %d\n", i);
640                         goto err_buf_info_unmap;
641                 }
642         }
643
644         /* Allocate taskqueues */
645         TASK_INIT(&tx_ring->enqueue_task, 0, ena_deferred_mq_start, tx_ring);
646         tx_ring->enqueue_tq = taskqueue_create_fast("ena_tx_enque", M_NOWAIT,
647             taskqueue_thread_enqueue, &tx_ring->enqueue_tq);
648         if (unlikely(tx_ring->enqueue_tq == NULL)) {
649                 ena_trace(ENA_ALERT,
650                     "Unable to create taskqueue for enqueue task\n");
651                 i = tx_ring->ring_size;
652                 goto err_buf_info_unmap;
653         }
654
655         /* RSS set cpu for thread */
656 #ifdef RSS
657         CPU_SETOF(que->cpu, &cpu_mask);
658         taskqueue_start_threads_cpuset(&tx_ring->enqueue_tq, 1, PI_NET,
659             &cpu_mask, "%s tx_ring enq (bucket %d)",
660             device_get_nameunit(adapter->pdev), que->cpu);
661 #else /* RSS */
662         taskqueue_start_threads(&tx_ring->enqueue_tq, 1, PI_NET,
663             "%s txeq %d", device_get_nameunit(adapter->pdev), que->cpu);
664 #endif /* RSS */
665
666         return (0);
667
668 err_buf_info_unmap:
669         while (i--) {
670                 bus_dmamap_destroy(adapter->tx_buf_tag,
671                     tx_ring->tx_buffer_info[i].map);
672         }
673         free(tx_ring->free_tx_ids, M_DEVBUF);
674         tx_ring->free_tx_ids = NULL;
675 err_buf_info_free:
676         free(tx_ring->tx_buffer_info, M_DEVBUF);
677         tx_ring->tx_buffer_info = NULL;
678
679         return (ENOMEM);
680 }
681
682 /**
683  * ena_free_tx_resources - Free Tx Resources per Queue
684  * @adapter: network interface device structure
685  * @qid: queue index
686  *
687  * Free all transmit software resources
688  **/
689 static void
690 ena_free_tx_resources(struct ena_adapter *adapter, int qid)
691 {
692         struct ena_ring *tx_ring = &adapter->tx_ring[qid];
693
694         while (taskqueue_cancel(tx_ring->enqueue_tq, &tx_ring->enqueue_task,
695             NULL))
696                 taskqueue_drain(tx_ring->enqueue_tq, &tx_ring->enqueue_task);
697
698         taskqueue_free(tx_ring->enqueue_tq);
699
700         ENA_RING_MTX_LOCK(tx_ring);
701         /* Flush buffer ring, */
702         drbr_flush(adapter->ifp, tx_ring->br);
703
704         /* Free buffer DMA maps, */
705         for (int i = 0; i < tx_ring->ring_size; i++) {
706                 m_freem(tx_ring->tx_buffer_info[i].mbuf);
707                 tx_ring->tx_buffer_info[i].mbuf = NULL;
708                 bus_dmamap_unload(adapter->tx_buf_tag,
709                     tx_ring->tx_buffer_info[i].map);
710                 bus_dmamap_destroy(adapter->tx_buf_tag,
711                     tx_ring->tx_buffer_info[i].map);
712         }
713         ENA_RING_MTX_UNLOCK(tx_ring);
714
715         /* And free allocated memory. */
716         free(tx_ring->tx_buffer_info, M_DEVBUF);
717         tx_ring->tx_buffer_info = NULL;
718
719         free(tx_ring->free_tx_ids, M_DEVBUF);
720         tx_ring->free_tx_ids = NULL;
721 }
722
723 /**
724  * ena_setup_all_tx_resources - allocate all queues Tx resources
725  * @adapter: network interface device structure
726  *
727  * Returns 0 on success, otherwise on failure.
728  **/
729 static int
730 ena_setup_all_tx_resources(struct ena_adapter *adapter)
731 {
732         int i, rc;
733
734         for (i = 0; i < adapter->num_queues; i++) {
735                 rc = ena_setup_tx_resources(adapter, i);
736                 if (rc != 0) {
737                         device_printf(adapter->pdev,
738                             "Allocation for Tx Queue %u failed\n", i);
739                         goto err_setup_tx;
740                 }
741         }
742
743         return (0);
744
745 err_setup_tx:
746         /* Rewind the index freeing the rings as we go */
747         while (i--)
748                 ena_free_tx_resources(adapter, i);
749         return (rc);
750 }
751
752 /**
753  * ena_free_all_tx_resources - Free Tx Resources for All Queues
754  * @adapter: network interface device structure
755  *
756  * Free all transmit software resources
757  **/
758 static void
759 ena_free_all_tx_resources(struct ena_adapter *adapter)
760 {
761         int i;
762
763         for (i = 0; i < adapter->num_queues; i++)
764                 ena_free_tx_resources(adapter, i);
765 }
766
767 static inline int
768 validate_rx_req_id(struct ena_ring *rx_ring, uint16_t req_id)
769 {
770         if (likely(req_id < rx_ring->ring_size))
771                 return (0);
772
773         device_printf(rx_ring->adapter->pdev, "Invalid rx req_id: %hu\n",
774             req_id);
775         counter_u64_add(rx_ring->rx_stats.bad_req_id, 1);
776
777         /* Trigger device reset */
778         rx_ring->adapter->reset_reason = ENA_REGS_RESET_INV_RX_REQ_ID;
779         rx_ring->adapter->trigger_reset = true;
780
781         return (EFAULT);
782 }
783
784 /**
785  * ena_setup_rx_resources - allocate Rx resources (Descriptors)
786  * @adapter: network interface device structure
787  * @qid: queue index
788  *
789  * Returns 0 on success, otherwise on failure.
790  **/
791 static int
792 ena_setup_rx_resources(struct ena_adapter *adapter, unsigned int qid)
793 {
794         struct ena_que *que = &adapter->que[qid];
795         struct ena_ring *rx_ring = que->rx_ring;
796         int size, err, i;
797 #ifdef  RSS
798         cpuset_t cpu_mask;
799 #endif
800
801         size = sizeof(struct ena_rx_buffer) * rx_ring->ring_size;
802
803         /*
804          * Alloc extra element so in rx path
805          * we can always prefetch rx_info + 1
806          */
807         size += sizeof(struct ena_rx_buffer);
808
809         rx_ring->rx_buffer_info = malloc(size, M_DEVBUF, M_WAITOK | M_ZERO);
810
811         size = sizeof(uint16_t) * rx_ring->ring_size;
812         rx_ring->free_rx_ids = malloc(size, M_DEVBUF, M_WAITOK);
813
814         for (i = 0; i < rx_ring->ring_size; i++)
815                 rx_ring->free_rx_ids[i] = i;
816
817         /* Reset RX statistics. */
818         ena_reset_counters((counter_u64_t *)&rx_ring->rx_stats,
819             sizeof(rx_ring->rx_stats));
820
821         rx_ring->next_to_clean = 0;
822         rx_ring->next_to_use = 0;
823
824         /* ... and create the buffer DMA maps */
825         for (i = 0; i < rx_ring->ring_size; i++) {
826                 err = bus_dmamap_create(adapter->rx_buf_tag, 0,
827                     &(rx_ring->rx_buffer_info[i].map));
828                 if (err != 0) {
829                         ena_trace(ENA_ALERT,
830                             "Unable to create Rx DMA map for buffer %d\n", i);
831                         goto err_buf_info_unmap;
832                 }
833         }
834
835         /* Create LRO for the ring */
836         if ((adapter->ifp->if_capenable & IFCAP_LRO) != 0) {
837                 int err = tcp_lro_init(&rx_ring->lro);
838                 if (err != 0) {
839                         device_printf(adapter->pdev,
840                             "LRO[%d] Initialization failed!\n", qid);
841                 } else {
842                         ena_trace(ENA_INFO,
843                             "RX Soft LRO[%d] Initialized\n", qid);
844                         rx_ring->lro.ifp = adapter->ifp;
845                 }
846         }
847
848         /* Allocate taskqueues */
849         TASK_INIT(&rx_ring->cmpl_task, 0, ena_deferred_rx_cleanup, rx_ring);
850         rx_ring->cmpl_tq = taskqueue_create_fast("ena RX completion", M_WAITOK,
851             taskqueue_thread_enqueue, &rx_ring->cmpl_tq);
852
853         /* RSS set cpu for thread */
854 #ifdef RSS
855         CPU_SETOF(que->cpu, &cpu_mask);
856         taskqueue_start_threads_cpuset(&rx_ring->cmpl_tq, 1, PI_NET, &cpu_mask,
857             "%s rx_ring cmpl (bucket %d)",
858             device_get_nameunit(adapter->pdev), que->cpu);
859 #else
860         taskqueue_start_threads(&rx_ring->cmpl_tq, 1, PI_NET,
861             "%s rx_ring cmpl %d", device_get_nameunit(adapter->pdev), que->cpu);
862 #endif
863
864         return (0);
865
866 err_buf_info_unmap:
867         while (i--) {
868                 bus_dmamap_destroy(adapter->rx_buf_tag,
869                     rx_ring->rx_buffer_info[i].map);
870         }
871
872         free(rx_ring->free_rx_ids, M_DEVBUF);
873         rx_ring->free_rx_ids = NULL;
874         free(rx_ring->rx_buffer_info, M_DEVBUF);
875         rx_ring->rx_buffer_info = NULL;
876         return (ENOMEM);
877 }
878
879 /**
880  * ena_free_rx_resources - Free Rx Resources
881  * @adapter: network interface device structure
882  * @qid: queue index
883  *
884  * Free all receive software resources
885  **/
886 static void
887 ena_free_rx_resources(struct ena_adapter *adapter, unsigned int qid)
888 {
889         struct ena_ring *rx_ring = &adapter->rx_ring[qid];
890
891         while (taskqueue_cancel(rx_ring->cmpl_tq, &rx_ring->cmpl_task, NULL) != 0)
892                 taskqueue_drain(rx_ring->cmpl_tq, &rx_ring->cmpl_task);
893
894         taskqueue_free(rx_ring->cmpl_tq);
895
896         /* Free buffer DMA maps, */
897         for (int i = 0; i < rx_ring->ring_size; i++) {
898                 m_freem(rx_ring->rx_buffer_info[i].mbuf);
899                 rx_ring->rx_buffer_info[i].mbuf = NULL;
900                 bus_dmamap_unload(adapter->rx_buf_tag,
901                     rx_ring->rx_buffer_info[i].map);
902                 bus_dmamap_destroy(adapter->rx_buf_tag,
903                     rx_ring->rx_buffer_info[i].map);
904         }
905
906         /* free LRO resources, */
907         tcp_lro_free(&rx_ring->lro);
908
909         /* free allocated memory */
910         free(rx_ring->rx_buffer_info, M_DEVBUF);
911         rx_ring->rx_buffer_info = NULL;
912
913         free(rx_ring->free_rx_ids, M_DEVBUF);
914         rx_ring->free_rx_ids = NULL;
915 }
916
917 /**
918  * ena_setup_all_rx_resources - allocate all queues Rx resources
919  * @adapter: network interface device structure
920  *
921  * Returns 0 on success, otherwise on failure.
922  **/
923 static int
924 ena_setup_all_rx_resources(struct ena_adapter *adapter)
925 {
926         int i, rc = 0;
927
928         for (i = 0; i < adapter->num_queues; i++) {
929                 rc = ena_setup_rx_resources(adapter, i);
930                 if (rc != 0) {
931                         device_printf(adapter->pdev,
932                             "Allocation for Rx Queue %u failed\n", i);
933                         goto err_setup_rx;
934                 }
935         }
936         return (0);
937
938 err_setup_rx:
939         /* rewind the index freeing the rings as we go */
940         while (i--)
941                 ena_free_rx_resources(adapter, i);
942         return (rc);
943 }
944
945 /**
946  * ena_free_all_rx_resources - Free Rx resources for all queues
947  * @adapter: network interface device structure
948  *
949  * Free all receive software resources
950  **/
951 static void
952 ena_free_all_rx_resources(struct ena_adapter *adapter)
953 {
954         int i;
955
956         for (i = 0; i < adapter->num_queues; i++)
957                 ena_free_rx_resources(adapter, i);
958 }
959
960 static inline int
961 ena_alloc_rx_mbuf(struct ena_adapter *adapter,
962     struct ena_ring *rx_ring, struct ena_rx_buffer *rx_info)
963 {
964         struct ena_com_buf *ena_buf;
965         bus_dma_segment_t segs[1];
966         int nsegs, error;
967
968         /* if previous allocated frag is not used */
969         if (unlikely(rx_info->mbuf != NULL))
970                 return (0);
971
972         /* Get mbuf using UMA allocator */
973         rx_info->mbuf = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUM16BYTES);
974
975         if (unlikely(rx_info->mbuf == NULL)) {
976                 counter_u64_add(rx_ring->rx_stats.mbuf_alloc_fail, 1);
977                 return (ENOMEM);
978         }
979         /* Set mbuf length*/
980         rx_info->mbuf->m_pkthdr.len = rx_info->mbuf->m_len = MJUM16BYTES;
981
982         /* Map packets for DMA */
983         ena_trace(ENA_DBG | ENA_RSC | ENA_RXPTH,
984             "Using tag %p for buffers' DMA mapping, mbuf %p len: %d",
985             adapter->rx_buf_tag,rx_info->mbuf, rx_info->mbuf->m_len);
986         error = bus_dmamap_load_mbuf_sg(adapter->rx_buf_tag, rx_info->map,
987             rx_info->mbuf, segs, &nsegs, BUS_DMA_NOWAIT);
988         if (unlikely((error != 0) || (nsegs != 1))) {
989                 ena_trace(ENA_WARNING, "failed to map mbuf, error: %d, "
990                     "nsegs: %d\n", error, nsegs);
991                 counter_u64_add(rx_ring->rx_stats.dma_mapping_err, 1);
992                 goto exit;
993
994         }
995
996         bus_dmamap_sync(adapter->rx_buf_tag, rx_info->map, BUS_DMASYNC_PREREAD);
997
998         ena_buf = &rx_info->ena_buf;
999         ena_buf->paddr = segs[0].ds_addr;
1000         ena_buf->len = MJUM16BYTES;
1001
1002         ena_trace(ENA_DBG | ENA_RSC | ENA_RXPTH,
1003             "ALLOC RX BUF: mbuf %p, rx_info %p, len %d, paddr %#jx\n",
1004             rx_info->mbuf, rx_info,ena_buf->len, (uintmax_t)ena_buf->paddr);
1005
1006         return (0);
1007
1008 exit:
1009         m_freem(rx_info->mbuf);
1010         rx_info->mbuf = NULL;
1011         return (EFAULT);
1012 }
1013
1014 static void
1015 ena_free_rx_mbuf(struct ena_adapter *adapter, struct ena_ring *rx_ring,
1016     struct ena_rx_buffer *rx_info)
1017 {
1018
1019         if (rx_info->mbuf == NULL) {
1020                 ena_trace(ENA_WARNING, "Trying to free unallocated buffer\n");
1021                 return;
1022         }
1023
1024         bus_dmamap_unload(adapter->rx_buf_tag, rx_info->map);
1025         m_freem(rx_info->mbuf);
1026         rx_info->mbuf = NULL;
1027 }
1028
1029 /**
1030  * ena_refill_rx_bufs - Refills ring with descriptors
1031  * @rx_ring: the ring which we want to feed with free descriptors
1032  * @num: number of descriptors to refill
1033  * Refills the ring with newly allocated DMA-mapped mbufs for receiving
1034  **/
1035 static int
1036 ena_refill_rx_bufs(struct ena_ring *rx_ring, uint32_t num)
1037 {
1038         struct ena_adapter *adapter = rx_ring->adapter;
1039         uint16_t next_to_use, req_id;
1040         uint32_t i;
1041         int rc;
1042
1043         ena_trace(ENA_DBG | ENA_RXPTH | ENA_RSC, "refill qid: %d",
1044             rx_ring->qid);
1045
1046         next_to_use = rx_ring->next_to_use;
1047
1048         for (i = 0; i < num; i++) {
1049                 struct ena_rx_buffer *rx_info;
1050
1051                 ena_trace(ENA_DBG | ENA_RXPTH | ENA_RSC,
1052                     "RX buffer - next to use: %d", next_to_use);
1053
1054                 req_id = rx_ring->free_rx_ids[next_to_use];
1055                 rc = validate_rx_req_id(rx_ring, req_id);
1056                 if (unlikely(rc != 0))
1057                         break;
1058
1059                 rx_info = &rx_ring->rx_buffer_info[req_id];
1060
1061                 rc = ena_alloc_rx_mbuf(adapter, rx_ring, rx_info);
1062                 if (unlikely(rc != 0)) {
1063                         ena_trace(ENA_WARNING,
1064                             "failed to alloc buffer for rx queue %d\n",
1065                             rx_ring->qid);
1066                         break;
1067                 }
1068                 rc = ena_com_add_single_rx_desc(rx_ring->ena_com_io_sq,
1069                     &rx_info->ena_buf, req_id);
1070                 if (unlikely(rc != 0)) {
1071                         ena_trace(ENA_WARNING,
1072                             "failed to add buffer for rx queue %d\n",
1073                             rx_ring->qid);
1074                         break;
1075                 }
1076                 next_to_use = ENA_RX_RING_IDX_NEXT(next_to_use,
1077                     rx_ring->ring_size);
1078         }
1079
1080         if (unlikely(i < num)) {
1081                 counter_u64_add(rx_ring->rx_stats.refil_partial, 1);
1082                 ena_trace(ENA_WARNING,
1083                      "refilled rx qid %d with only %d mbufs (from %d)\n",
1084                      rx_ring->qid, i, num);
1085         }
1086
1087         if (likely(i != 0)) {
1088                 wmb();
1089                 ena_com_write_sq_doorbell(rx_ring->ena_com_io_sq);
1090         }
1091         rx_ring->next_to_use = next_to_use;
1092         return (i);
1093 }
1094
1095 static void
1096 ena_free_rx_bufs(struct ena_adapter *adapter, unsigned int qid)
1097 {
1098         struct ena_ring *rx_ring = &adapter->rx_ring[qid];
1099         unsigned int i;
1100
1101         for (i = 0; i < rx_ring->ring_size; i++) {
1102                 struct ena_rx_buffer *rx_info = &rx_ring->rx_buffer_info[i];
1103
1104                 if (rx_info->mbuf != NULL)
1105                         ena_free_rx_mbuf(adapter, rx_ring, rx_info);
1106         }
1107 }
1108
1109 /**
1110  * ena_refill_all_rx_bufs - allocate all queues Rx buffers
1111  * @adapter: network interface device structure
1112  *
1113  */
1114 static void
1115 ena_refill_all_rx_bufs(struct ena_adapter *adapter)
1116 {
1117         struct ena_ring *rx_ring;
1118         int i, rc, bufs_num;
1119
1120         for (i = 0; i < adapter->num_queues; i++) {
1121                 rx_ring = &adapter->rx_ring[i];
1122                 bufs_num = rx_ring->ring_size - 1;
1123                 rc = ena_refill_rx_bufs(rx_ring, bufs_num);
1124
1125                 if (unlikely(rc != bufs_num))
1126                         ena_trace(ENA_WARNING, "refilling Queue %d failed. "
1127                             "Allocated %d buffers from: %d\n", i, rc, bufs_num);
1128         }
1129 }
1130
1131 static void
1132 ena_free_all_rx_bufs(struct ena_adapter *adapter)
1133 {
1134         int i;
1135
1136         for (i = 0; i < adapter->num_queues; i++)
1137                 ena_free_rx_bufs(adapter, i);
1138 }
1139
1140 /**
1141  * ena_free_tx_bufs - Free Tx Buffers per Queue
1142  * @adapter: network interface device structure
1143  * @qid: queue index
1144  **/
1145 static void
1146 ena_free_tx_bufs(struct ena_adapter *adapter, unsigned int qid)
1147 {
1148         bool print_once = true;
1149         struct ena_ring *tx_ring = &adapter->tx_ring[qid];
1150
1151         ENA_RING_MTX_LOCK(tx_ring);
1152         for (int i = 0; i < tx_ring->ring_size; i++) {
1153                 struct ena_tx_buffer *tx_info = &tx_ring->tx_buffer_info[i];
1154
1155                 if (tx_info->mbuf == NULL)
1156                         continue;
1157
1158                 if (print_once) {
1159                         device_printf(adapter->pdev,
1160                             "free uncompleted tx mbuf qid %d idx 0x%x",
1161                             qid, i);
1162                         print_once = false;
1163                 } else {
1164                         ena_trace(ENA_DBG,
1165                             "free uncompleted tx mbuf qid %d idx 0x%x",
1166                              qid, i);
1167                 }
1168
1169                 bus_dmamap_unload(adapter->tx_buf_tag, tx_info->map);
1170                 m_free(tx_info->mbuf);
1171                 tx_info->mbuf = NULL;
1172         }
1173         ENA_RING_MTX_UNLOCK(tx_ring);
1174 }
1175
1176 static void
1177 ena_free_all_tx_bufs(struct ena_adapter *adapter)
1178 {
1179
1180         for (int i = 0; i < adapter->num_queues; i++)
1181                 ena_free_tx_bufs(adapter, i);
1182 }
1183
1184 static void
1185 ena_destroy_all_tx_queues(struct ena_adapter *adapter)
1186 {
1187         uint16_t ena_qid;
1188         int i;
1189
1190         for (i = 0; i < adapter->num_queues; i++) {
1191                 ena_qid = ENA_IO_TXQ_IDX(i);
1192                 ena_com_destroy_io_queue(adapter->ena_dev, ena_qid);
1193         }
1194 }
1195
1196 static void
1197 ena_destroy_all_rx_queues(struct ena_adapter *adapter)
1198 {
1199         uint16_t ena_qid;
1200         int i;
1201
1202         for (i = 0; i < adapter->num_queues; i++) {
1203                 ena_qid = ENA_IO_RXQ_IDX(i);
1204                 ena_com_destroy_io_queue(adapter->ena_dev, ena_qid);
1205         }
1206 }
1207
1208 static void
1209 ena_destroy_all_io_queues(struct ena_adapter *adapter)
1210 {
1211         ena_destroy_all_tx_queues(adapter);
1212         ena_destroy_all_rx_queues(adapter);
1213 }
1214
1215 static inline int
1216 validate_tx_req_id(struct ena_ring *tx_ring, uint16_t req_id)
1217 {
1218         struct ena_adapter *adapter = tx_ring->adapter;
1219         struct ena_tx_buffer *tx_info = NULL;
1220
1221         if (likely(req_id < tx_ring->ring_size)) {
1222                 tx_info = &tx_ring->tx_buffer_info[req_id];
1223                 if (tx_info->mbuf != NULL)
1224                         return (0);
1225         }
1226
1227         if (tx_info->mbuf == NULL)
1228                 device_printf(adapter->pdev,
1229                     "tx_info doesn't have valid mbuf\n");
1230         else
1231                 device_printf(adapter->pdev, "Invalid req_id: %hu\n", req_id);
1232
1233         counter_u64_add(tx_ring->tx_stats.bad_req_id, 1);
1234
1235         return (EFAULT);
1236 }
1237
1238 static int
1239 ena_create_io_queues(struct ena_adapter *adapter)
1240 {
1241         struct ena_com_dev *ena_dev = adapter->ena_dev;
1242         struct ena_com_create_io_ctx ctx;
1243         struct ena_ring *ring;
1244         uint16_t ena_qid;
1245         uint32_t msix_vector;
1246         int rc, i;
1247
1248         /* Create TX queues */
1249         for (i = 0; i < adapter->num_queues; i++) {
1250                 msix_vector = ENA_IO_IRQ_IDX(i);
1251                 ena_qid = ENA_IO_TXQ_IDX(i);
1252                 ctx.mem_queue_type = ena_dev->tx_mem_queue_type;
1253                 ctx.direction = ENA_COM_IO_QUEUE_DIRECTION_TX;
1254                 ctx.queue_size = adapter->tx_ring_size;
1255                 ctx.msix_vector = msix_vector;
1256                 ctx.qid = ena_qid;
1257                 rc = ena_com_create_io_queue(ena_dev, &ctx);
1258                 if (rc != 0) {
1259                         device_printf(adapter->pdev,
1260                             "Failed to create io TX queue #%d rc: %d\n", i, rc);
1261                         goto err_tx;
1262                 }
1263                 ring = &adapter->tx_ring[i];
1264                 rc = ena_com_get_io_handlers(ena_dev, ena_qid,
1265                     &ring->ena_com_io_sq,
1266                     &ring->ena_com_io_cq);
1267                 if (rc != 0) {
1268                         device_printf(adapter->pdev,
1269                             "Failed to get TX queue handlers. TX queue num"
1270                             " %d rc: %d\n", i, rc);
1271                         ena_com_destroy_io_queue(ena_dev, ena_qid);
1272                         goto err_tx;
1273                 }
1274         }
1275
1276         /* Create RX queues */
1277         for (i = 0; i < adapter->num_queues; i++) {
1278                 msix_vector = ENA_IO_IRQ_IDX(i);
1279                 ena_qid = ENA_IO_RXQ_IDX(i);
1280                 ctx.mem_queue_type = ENA_ADMIN_PLACEMENT_POLICY_HOST;
1281                 ctx.direction = ENA_COM_IO_QUEUE_DIRECTION_RX;
1282                 ctx.queue_size = adapter->rx_ring_size;
1283                 ctx.msix_vector = msix_vector;
1284                 ctx.qid = ena_qid;
1285                 rc = ena_com_create_io_queue(ena_dev, &ctx);
1286                 if (unlikely(rc != 0)) {
1287                         device_printf(adapter->pdev,
1288                             "Failed to create io RX queue[%d] rc: %d\n", i, rc);
1289                         goto err_rx;
1290                 }
1291
1292                 ring = &adapter->rx_ring[i];
1293                 rc = ena_com_get_io_handlers(ena_dev, ena_qid,
1294                     &ring->ena_com_io_sq,
1295                     &ring->ena_com_io_cq);
1296                 if (unlikely(rc != 0)) {
1297                         device_printf(adapter->pdev,
1298                             "Failed to get RX queue handlers. RX queue num"
1299                             " %d rc: %d\n", i, rc);
1300                         ena_com_destroy_io_queue(ena_dev, ena_qid);
1301                         goto err_rx;
1302                 }
1303         }
1304
1305         return (0);
1306
1307 err_rx:
1308         while (i--)
1309                 ena_com_destroy_io_queue(ena_dev, ENA_IO_RXQ_IDX(i));
1310         i = adapter->num_queues;
1311 err_tx:
1312         while (i--)
1313                 ena_com_destroy_io_queue(ena_dev, ENA_IO_TXQ_IDX(i));
1314
1315         return (ENXIO);
1316 }
1317
1318 /**
1319  * ena_tx_cleanup - clear sent packets and corresponding descriptors
1320  * @tx_ring: ring for which we want to clean packets
1321  *
1322  * Once packets are sent, we ask the device in a loop for no longer used
1323  * descriptors. We find the related mbuf chain in a map (index in an array)
1324  * and free it, then update ring state.
1325  * This is performed in "endless" loop, updating ring pointers every
1326  * TX_COMMIT. The first check of free descriptor is performed before the actual
1327  * loop, then repeated at the loop end.
1328  **/
1329 static int
1330 ena_tx_cleanup(struct ena_ring *tx_ring)
1331 {
1332         struct ena_adapter *adapter;
1333         struct ena_com_io_cq* io_cq;
1334         uint16_t next_to_clean;
1335         uint16_t req_id;
1336         uint16_t ena_qid;
1337         unsigned int total_done = 0;
1338         int rc;
1339         int commit = TX_COMMIT;
1340         int budget = TX_BUDGET;
1341         int work_done;
1342
1343         adapter = tx_ring->que->adapter;
1344         ena_qid = ENA_IO_TXQ_IDX(tx_ring->que->id);
1345         io_cq = &adapter->ena_dev->io_cq_queues[ena_qid];
1346         next_to_clean = tx_ring->next_to_clean;
1347
1348         do {
1349                 struct ena_tx_buffer *tx_info;
1350                 struct mbuf *mbuf;
1351
1352                 rc = ena_com_tx_comp_req_id_get(io_cq, &req_id);
1353                 if (unlikely(rc != 0))
1354                         break;
1355
1356                 rc = validate_tx_req_id(tx_ring, req_id);
1357                 if (unlikely(rc != 0))
1358                         break;
1359
1360                 tx_info = &tx_ring->tx_buffer_info[req_id];
1361
1362                 mbuf = tx_info->mbuf;
1363
1364                 tx_info->mbuf = NULL;
1365                 bintime_clear(&tx_info->timestamp);
1366
1367                 if (likely(tx_info->num_of_bufs != 0)) {
1368                         /* Map is no longer required */
1369                         bus_dmamap_unload(adapter->tx_buf_tag, tx_info->map);
1370                 }
1371
1372                 ena_trace(ENA_DBG | ENA_TXPTH, "tx: q %d mbuf %p completed",
1373                     tx_ring->qid, mbuf);
1374
1375                 m_freem(mbuf);
1376
1377                 total_done += tx_info->tx_descs;
1378
1379                 tx_ring->free_tx_ids[next_to_clean] = req_id;
1380                 next_to_clean = ENA_TX_RING_IDX_NEXT(next_to_clean,
1381                     tx_ring->ring_size);
1382
1383                 if (unlikely(--commit == 0)) {
1384                         commit = TX_COMMIT;
1385                         /* update ring state every TX_COMMIT descriptor */
1386                         tx_ring->next_to_clean = next_to_clean;
1387                         ena_com_comp_ack(
1388                             &adapter->ena_dev->io_sq_queues[ena_qid],
1389                             total_done);
1390                         ena_com_update_dev_comp_head(io_cq);
1391                         total_done = 0;
1392                 }
1393         } while (likely(--budget));
1394
1395         work_done = TX_BUDGET - budget;
1396
1397         ena_trace(ENA_DBG | ENA_TXPTH, "tx: q %d done. total pkts: %d",
1398         tx_ring->qid, work_done);
1399
1400         /* If there is still something to commit update ring state */
1401         if (likely(commit != TX_COMMIT)) {
1402                 tx_ring->next_to_clean = next_to_clean;
1403                 ena_com_comp_ack(&adapter->ena_dev->io_sq_queues[ena_qid],
1404                     total_done);
1405                 ena_com_update_dev_comp_head(io_cq);
1406         }
1407
1408         taskqueue_enqueue(tx_ring->enqueue_tq, &tx_ring->enqueue_task);
1409
1410         return (work_done);
1411 }
1412
1413 static void
1414 ena_rx_hash_mbuf(struct ena_ring *rx_ring, struct ena_com_rx_ctx *ena_rx_ctx,
1415     struct mbuf *mbuf)
1416 {
1417         struct ena_adapter *adapter = rx_ring->adapter;
1418
1419         if (likely(adapter->rss_support)) {
1420                 mbuf->m_pkthdr.flowid = ena_rx_ctx->hash;
1421
1422                 if (ena_rx_ctx->frag &&
1423                     (ena_rx_ctx->l3_proto != ENA_ETH_IO_L3_PROTO_UNKNOWN)) {
1424                         M_HASHTYPE_SET(mbuf, M_HASHTYPE_OPAQUE_HASH);
1425                         return;
1426                 }
1427
1428                 switch (ena_rx_ctx->l3_proto) {
1429                 case ENA_ETH_IO_L3_PROTO_IPV4:
1430                         switch (ena_rx_ctx->l4_proto) {
1431                         case ENA_ETH_IO_L4_PROTO_TCP:
1432                                 M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_TCP_IPV4);
1433                                 break;
1434                         case ENA_ETH_IO_L4_PROTO_UDP:
1435                                 M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_UDP_IPV4);
1436                                 break;
1437                         default:
1438                                 M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_IPV4);
1439                         }
1440                         break;
1441                 case ENA_ETH_IO_L3_PROTO_IPV6:
1442                         switch (ena_rx_ctx->l4_proto) {
1443                         case ENA_ETH_IO_L4_PROTO_TCP:
1444                                 M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_TCP_IPV6);
1445                                 break;
1446                         case ENA_ETH_IO_L4_PROTO_UDP:
1447                                 M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_UDP_IPV6);
1448                                 break;
1449                         default:
1450                                 M_HASHTYPE_SET(mbuf, M_HASHTYPE_RSS_IPV6);
1451                         }
1452                         break;
1453                 case ENA_ETH_IO_L3_PROTO_UNKNOWN:
1454                         M_HASHTYPE_SET(mbuf, M_HASHTYPE_NONE);
1455                         break;
1456                 default:
1457                         M_HASHTYPE_SET(mbuf, M_HASHTYPE_OPAQUE_HASH);
1458                 }
1459         } else {
1460                 mbuf->m_pkthdr.flowid = rx_ring->qid;
1461                 M_HASHTYPE_SET(mbuf, M_HASHTYPE_NONE);
1462         }
1463 }
1464
1465 /**
1466  * ena_rx_mbuf - assemble mbuf from descriptors
1467  * @rx_ring: ring for which we want to clean packets
1468  * @ena_bufs: buffer info
1469  * @ena_rx_ctx: metadata for this packet(s)
1470  * @next_to_clean: ring pointer, will be updated only upon success
1471  *
1472  **/
1473 static struct mbuf*
1474 ena_rx_mbuf(struct ena_ring *rx_ring, struct ena_com_rx_buf_info *ena_bufs,
1475     struct ena_com_rx_ctx *ena_rx_ctx, uint16_t *next_to_clean)
1476 {
1477         struct mbuf *mbuf;
1478         struct ena_rx_buffer *rx_info;
1479         struct ena_adapter *adapter;
1480         unsigned int descs = ena_rx_ctx->descs;
1481         uint16_t ntc, len, req_id, buf = 0;
1482
1483         ntc = *next_to_clean;
1484         adapter = rx_ring->adapter;
1485         rx_info = &rx_ring->rx_buffer_info[ntc];
1486
1487         if (unlikely(rx_info->mbuf == NULL)) {
1488                 device_printf(adapter->pdev, "NULL mbuf in rx_info");
1489                 return (NULL);
1490         }
1491
1492         len = ena_bufs[buf].len;
1493         req_id = ena_bufs[buf].req_id;
1494         rx_info = &rx_ring->rx_buffer_info[req_id];
1495
1496         ena_trace(ENA_DBG | ENA_RXPTH, "rx_info %p, mbuf %p, paddr %jx",
1497             rx_info, rx_info->mbuf, (uintmax_t)rx_info->ena_buf.paddr);
1498
1499         mbuf = rx_info->mbuf;
1500         mbuf->m_flags |= M_PKTHDR;
1501         mbuf->m_pkthdr.len = len;
1502         mbuf->m_len = len;
1503         mbuf->m_pkthdr.rcvif = rx_ring->que->adapter->ifp;
1504
1505         /* Fill mbuf with hash key and it's interpretation for optimization */
1506         ena_rx_hash_mbuf(rx_ring, ena_rx_ctx, mbuf);
1507
1508         ena_trace(ENA_DBG | ENA_RXPTH, "rx mbuf 0x%p, flags=0x%x, len: %d",
1509             mbuf, mbuf->m_flags, mbuf->m_pkthdr.len);
1510
1511         /* DMA address is not needed anymore, unmap it */
1512         bus_dmamap_unload(rx_ring->adapter->rx_buf_tag, rx_info->map);
1513
1514         rx_info->mbuf = NULL;
1515         rx_ring->free_rx_ids[ntc] = req_id;
1516         ntc = ENA_RX_RING_IDX_NEXT(ntc, rx_ring->ring_size);
1517
1518         /*
1519          * While we have more than 1 descriptors for one rcvd packet, append
1520          * other mbufs to the main one
1521          */
1522         while (--descs) {
1523                 ++buf;
1524                 len = ena_bufs[buf].len;
1525                 req_id = ena_bufs[buf].req_id;
1526                 rx_info = &rx_ring->rx_buffer_info[req_id];
1527
1528                 if (unlikely(rx_info->mbuf == NULL)) {
1529                         device_printf(adapter->pdev, "NULL mbuf in rx_info");
1530                         /*
1531                          * If one of the required mbufs was not allocated yet,
1532                          * we can break there.
1533                          * All earlier used descriptors will be reallocated
1534                          * later and not used mbufs can be reused.
1535                          * The next_to_clean pointer will not be updated in case
1536                          * of an error, so caller should advance it manually
1537                          * in error handling routine to keep it up to date
1538                          * with hw ring.
1539                          */
1540                         m_freem(mbuf);
1541                         return (NULL);
1542                 }
1543
1544                 if (unlikely(m_append(mbuf, len, rx_info->mbuf->m_data) == 0)) {
1545                         counter_u64_add(rx_ring->rx_stats.mbuf_alloc_fail, 1);
1546                         ena_trace(ENA_WARNING, "Failed to append Rx mbuf %p",
1547                             mbuf);
1548                 }
1549
1550                 ena_trace(ENA_DBG | ENA_RXPTH,
1551                     "rx mbuf updated. len %d", mbuf->m_pkthdr.len);
1552
1553                 /* Free already appended mbuf, it won't be useful anymore */
1554                 bus_dmamap_unload(rx_ring->adapter->rx_buf_tag, rx_info->map);
1555                 m_freem(rx_info->mbuf);
1556                 rx_info->mbuf = NULL;
1557
1558                 rx_ring->free_rx_ids[ntc] = req_id;
1559                 ntc = ENA_RX_RING_IDX_NEXT(ntc, rx_ring->ring_size);
1560         }
1561
1562         *next_to_clean = ntc;
1563
1564         return (mbuf);
1565 }
1566
1567 /**
1568  * ena_rx_checksum - indicate in mbuf if hw indicated a good cksum
1569  **/
1570 static inline void
1571 ena_rx_checksum(struct ena_ring *rx_ring, struct ena_com_rx_ctx *ena_rx_ctx,
1572     struct mbuf *mbuf)
1573 {
1574
1575         /* if IP and error */
1576         if (unlikely((ena_rx_ctx->l3_proto == ENA_ETH_IO_L3_PROTO_IPV4) &&
1577             ena_rx_ctx->l3_csum_err)) {
1578                 /* ipv4 checksum error */
1579                 mbuf->m_pkthdr.csum_flags = 0;
1580                 counter_u64_add(rx_ring->rx_stats.bad_csum, 1);
1581                 ena_trace(ENA_DBG, "RX IPv4 header checksum error");
1582                 return;
1583         }
1584
1585         /* if TCP/UDP */
1586         if ((ena_rx_ctx->l4_proto == ENA_ETH_IO_L4_PROTO_TCP) ||
1587             (ena_rx_ctx->l4_proto == ENA_ETH_IO_L4_PROTO_UDP)) {
1588                 if (ena_rx_ctx->l4_csum_err) {
1589                         /* TCP/UDP checksum error */
1590                         mbuf->m_pkthdr.csum_flags = 0;
1591                         counter_u64_add(rx_ring->rx_stats.bad_csum, 1);
1592                         ena_trace(ENA_DBG, "RX L4 checksum error");
1593                 } else {
1594                         mbuf->m_pkthdr.csum_flags = CSUM_IP_CHECKED;
1595                         mbuf->m_pkthdr.csum_flags |= CSUM_IP_VALID;
1596                 }
1597         }
1598 }
1599
1600 static void
1601 ena_deferred_rx_cleanup(void *arg, int pending)
1602 {
1603         struct ena_ring *rx_ring = arg;
1604         int budget = CLEAN_BUDGET;
1605
1606         ENA_RING_MTX_LOCK(rx_ring);
1607         /*
1608          * If deferred task was executed, perform cleanup of all awaiting
1609          * descs (or until given budget is depleted to avoid infinite loop).
1610          */
1611         while (likely(budget--)) {
1612                 if (ena_rx_cleanup(rx_ring) == 0)
1613                         break;
1614         }
1615         ENA_RING_MTX_UNLOCK(rx_ring);
1616 }
1617
1618 /**
1619  * ena_rx_cleanup - handle rx irq
1620  * @arg: ring for which irq is being handled
1621  **/
1622 static int
1623 ena_rx_cleanup(struct ena_ring *rx_ring)
1624 {
1625         struct ena_adapter *adapter;
1626         struct mbuf *mbuf;
1627         struct ena_com_rx_ctx ena_rx_ctx;
1628         struct ena_com_io_cq* io_cq;
1629         struct ena_com_io_sq* io_sq;
1630         if_t ifp;
1631         uint16_t ena_qid;
1632         uint16_t next_to_clean;
1633         uint32_t refill_required;
1634         uint32_t refill_threshold;
1635         uint32_t do_if_input = 0;
1636         unsigned int qid;
1637         int rc, i;
1638         int budget = RX_BUDGET;
1639
1640         adapter = rx_ring->que->adapter;
1641         ifp = adapter->ifp;
1642         qid = rx_ring->que->id;
1643         ena_qid = ENA_IO_RXQ_IDX(qid);
1644         io_cq = &adapter->ena_dev->io_cq_queues[ena_qid];
1645         io_sq = &adapter->ena_dev->io_sq_queues[ena_qid];
1646         next_to_clean = rx_ring->next_to_clean;
1647
1648         ena_trace(ENA_DBG, "rx: qid %d", qid);
1649
1650         do {
1651                 ena_rx_ctx.ena_bufs = rx_ring->ena_bufs;
1652                 ena_rx_ctx.max_bufs = adapter->max_rx_sgl_size;
1653                 ena_rx_ctx.descs = 0;
1654                 rc = ena_com_rx_pkt(io_cq, io_sq, &ena_rx_ctx);
1655
1656                 if (unlikely(rc != 0))
1657                         goto error;
1658
1659                 if (unlikely(ena_rx_ctx.descs == 0))
1660                         break;
1661
1662                 ena_trace(ENA_DBG | ENA_RXPTH, "rx: q %d got packet from ena. "
1663                     "descs #: %d l3 proto %d l4 proto %d hash: %x",
1664                     rx_ring->qid, ena_rx_ctx.descs, ena_rx_ctx.l3_proto,
1665                     ena_rx_ctx.l4_proto, ena_rx_ctx.hash);
1666
1667                 /* Receive mbuf from the ring */
1668                 mbuf = ena_rx_mbuf(rx_ring, rx_ring->ena_bufs,
1669                     &ena_rx_ctx, &next_to_clean);
1670
1671                 /* Exit if we failed to retrieve a buffer */
1672                 if (unlikely(mbuf == NULL)) {
1673                         for (i = 0; i < ena_rx_ctx.descs; ++i) {
1674                                 rx_ring->free_rx_ids[next_to_clean] =
1675                                     rx_ring->ena_bufs[i].req_id;
1676                                 next_to_clean =
1677                                     ENA_RX_RING_IDX_NEXT(next_to_clean,
1678                                     rx_ring->ring_size);
1679
1680                         }
1681                         break;
1682                 }
1683
1684                 if (((ifp->if_capenable & IFCAP_RXCSUM) != 0) ||
1685                     ((ifp->if_capenable & IFCAP_RXCSUM_IPV6) != 0)) {
1686                         ena_rx_checksum(rx_ring, &ena_rx_ctx, mbuf);
1687                 }
1688
1689                 counter_enter();
1690                 counter_u64_add_protected(rx_ring->rx_stats.bytes,
1691                     mbuf->m_pkthdr.len);
1692                 counter_u64_add_protected(adapter->hw_stats.rx_bytes,
1693                     mbuf->m_pkthdr.len);
1694                 counter_exit();
1695                 /*
1696                  * LRO is only for IP/TCP packets and TCP checksum of the packet
1697                  * should be computed by hardware.
1698                  */
1699                 do_if_input = 1;
1700                 if (((ifp->if_capenable & IFCAP_LRO) != 0)  &&
1701                     ((mbuf->m_pkthdr.csum_flags & CSUM_IP_VALID) != 0) &&
1702                     (ena_rx_ctx.l4_proto == ENA_ETH_IO_L4_PROTO_TCP)) {
1703                         /*
1704                          * Send to the stack if:
1705                          *  - LRO not enabled, or
1706                          *  - no LRO resources, or
1707                          *  - lro enqueue fails
1708                          */
1709                         if ((rx_ring->lro.lro_cnt != 0) &&
1710                             (tcp_lro_rx(&rx_ring->lro, mbuf, 0) == 0))
1711                                         do_if_input = 0;
1712                 }
1713                 if (do_if_input != 0) {
1714                         ena_trace(ENA_DBG | ENA_RXPTH,
1715                             "calling if_input() with mbuf %p", mbuf);
1716                         (*ifp->if_input)(ifp, mbuf);
1717                 }
1718
1719                 counter_enter();
1720                 counter_u64_add_protected(rx_ring->rx_stats.cnt, 1);
1721                 counter_u64_add_protected(adapter->hw_stats.rx_packets, 1);
1722                 counter_exit();
1723         } while (--budget);
1724
1725         rx_ring->next_to_clean = next_to_clean;
1726
1727         refill_required = ena_com_free_desc(io_sq);
1728         refill_threshold = rx_ring->ring_size / ENA_RX_REFILL_THRESH_DIVIDER;
1729
1730         if (refill_required > refill_threshold) {
1731                 ena_com_update_dev_comp_head(rx_ring->ena_com_io_cq);
1732                 ena_refill_rx_bufs(rx_ring, refill_required);
1733         }
1734
1735         tcp_lro_flush_all(&rx_ring->lro);
1736
1737         return (RX_BUDGET - budget);
1738
1739 error:
1740         counter_u64_add(rx_ring->rx_stats.bad_desc_num, 1);
1741         return (RX_BUDGET - budget);
1742 }
1743
1744 /*********************************************************************
1745  *
1746  *  MSIX & Interrupt Service routine
1747  *
1748  **********************************************************************/
1749
1750 /**
1751  * ena_handle_msix - MSIX Interrupt Handler for admin/async queue
1752  * @arg: interrupt number
1753  **/
1754 static void
1755 ena_intr_msix_mgmnt(void *arg)
1756 {
1757         struct ena_adapter *adapter = (struct ena_adapter *)arg;
1758
1759         ena_com_admin_q_comp_intr_handler(adapter->ena_dev);
1760         if (likely(adapter->running))
1761                 ena_com_aenq_intr_handler(adapter->ena_dev, arg);
1762 }
1763
1764 /**
1765  * ena_handle_msix - MSIX Interrupt Handler for Tx/Rx
1766  * @arg: interrupt number
1767  **/
1768 static void
1769 ena_handle_msix(void *arg)
1770 {
1771         struct ena_que  *que = arg;
1772         struct ena_adapter *adapter = que->adapter;
1773         if_t ifp = adapter->ifp;
1774         struct ena_ring *tx_ring;
1775         struct ena_ring *rx_ring;
1776         struct ena_com_io_cq* io_cq;
1777         struct ena_eth_io_intr_reg intr_reg;
1778         int qid, ena_qid;
1779         int txc, rxc, i;
1780
1781         if (unlikely((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0))
1782                 return;
1783
1784         ena_trace(ENA_DBG, "MSI-X TX/RX routine");
1785
1786         tx_ring = que->tx_ring;
1787         rx_ring = que->rx_ring;
1788         qid = que->id;
1789         ena_qid = ENA_IO_TXQ_IDX(qid);
1790         io_cq = &adapter->ena_dev->io_cq_queues[ena_qid];
1791
1792         for (i = 0; i < CLEAN_BUDGET; ++i) {
1793                 /*
1794                  * If lock cannot be acquired, then deferred cleanup task was
1795                  * being executed and rx ring is being cleaned up in
1796                  * another thread.
1797                  */
1798                 if (likely(ENA_RING_MTX_TRYLOCK(rx_ring) != 0)) {
1799                         rxc = ena_rx_cleanup(rx_ring);
1800                         ENA_RING_MTX_UNLOCK(rx_ring);
1801                 } else {
1802                         rxc = 0;
1803                 }
1804
1805                 /* Protection from calling ena_tx_cleanup from ena_start_xmit */
1806                 ENA_RING_MTX_LOCK(tx_ring);
1807                 txc = ena_tx_cleanup(tx_ring);
1808                 ENA_RING_MTX_UNLOCK(tx_ring);
1809
1810                 if (unlikely((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0))
1811                         return;
1812
1813                 if ((txc != TX_BUDGET) && (rxc != RX_BUDGET))
1814                        break;
1815         }
1816
1817         /* Signal that work is done and unmask interrupt */
1818         ena_com_update_intr_reg(&intr_reg,
1819             RX_IRQ_INTERVAL,
1820             TX_IRQ_INTERVAL,
1821             true);
1822         ena_com_unmask_intr(io_cq, &intr_reg);
1823 }
1824
1825 static int
1826 ena_enable_msix(struct ena_adapter *adapter)
1827 {
1828         device_t dev = adapter->pdev;
1829         int msix_vecs, msix_req;
1830         int i, rc = 0;
1831
1832         /* Reserved the max msix vectors we might need */
1833         msix_vecs = ENA_MAX_MSIX_VEC(adapter->num_queues);
1834
1835         adapter->msix_entries = malloc(msix_vecs * sizeof(struct msix_entry),
1836             M_DEVBUF, M_WAITOK | M_ZERO);
1837
1838         ena_trace(ENA_DBG, "trying to enable MSI-X, vectors: %d", msix_vecs);
1839
1840         for (i = 0; i < msix_vecs; i++) {
1841                 adapter->msix_entries[i].entry = i;
1842                 /* Vectors must start from 1 */
1843                 adapter->msix_entries[i].vector = i + 1;
1844         }
1845
1846         msix_req = msix_vecs;
1847         rc = pci_alloc_msix(dev, &msix_vecs);
1848         if (unlikely(rc != 0)) {
1849                 device_printf(dev,
1850                     "Failed to enable MSIX, vectors %d rc %d\n", msix_vecs, rc);
1851
1852                 rc = ENOSPC;
1853                 goto err_msix_free;
1854         }
1855
1856         if (msix_vecs != msix_req) {
1857                 device_printf(dev, "Enable only %d MSI-x (out of %d), reduce "
1858                     "the number of queues\n", msix_vecs, msix_req);
1859                 adapter->num_queues = msix_vecs - ENA_ADMIN_MSIX_VEC;
1860         }
1861
1862         adapter->msix_vecs = msix_vecs;
1863         adapter->msix_enabled = true;
1864
1865         return (0);
1866
1867 err_msix_free:
1868         free(adapter->msix_entries, M_DEVBUF);
1869         adapter->msix_entries = NULL;
1870
1871         return (rc);
1872 }
1873
1874 static void
1875 ena_setup_mgmnt_intr(struct ena_adapter *adapter)
1876 {
1877
1878         snprintf(adapter->irq_tbl[ENA_MGMNT_IRQ_IDX].name,
1879             ENA_IRQNAME_SIZE, "ena-mgmnt@pci:%s",
1880             device_get_nameunit(adapter->pdev));
1881         /*
1882          * Handler is NULL on purpose, it will be set
1883          * when mgmnt interrupt is acquired
1884          */
1885         adapter->irq_tbl[ENA_MGMNT_IRQ_IDX].handler = NULL;
1886         adapter->irq_tbl[ENA_MGMNT_IRQ_IDX].data = adapter;
1887         adapter->irq_tbl[ENA_MGMNT_IRQ_IDX].vector =
1888             adapter->msix_entries[ENA_MGMNT_IRQ_IDX].vector;
1889 }
1890
1891 static void
1892 ena_setup_io_intr(struct ena_adapter *adapter)
1893 {
1894         static int last_bind_cpu = -1;
1895         int irq_idx;
1896
1897         for (int i = 0; i < adapter->num_queues; i++) {
1898                 irq_idx = ENA_IO_IRQ_IDX(i);
1899
1900                 snprintf(adapter->irq_tbl[irq_idx].name, ENA_IRQNAME_SIZE,
1901                     "%s-TxRx-%d", device_get_nameunit(adapter->pdev), i);
1902                 adapter->irq_tbl[irq_idx].handler = ena_handle_msix;
1903                 adapter->irq_tbl[irq_idx].data = &adapter->que[i];
1904                 adapter->irq_tbl[irq_idx].vector =
1905                     adapter->msix_entries[irq_idx].vector;
1906                 ena_trace(ENA_INFO | ENA_IOQ, "ena_setup_io_intr vector: %d\n",
1907                     adapter->msix_entries[irq_idx].vector);
1908 #ifdef  RSS
1909                 adapter->que[i].cpu = adapter->irq_tbl[irq_idx].cpu =
1910                     rss_getcpu(i % rss_getnumbuckets());
1911 #else
1912                 /*
1913                  * We still want to bind rings to the corresponding cpu
1914                  * using something similar to the RSS round-robin technique.
1915                  */
1916                 if (unlikely(last_bind_cpu < 0))
1917                         last_bind_cpu = CPU_FIRST();
1918                 adapter->que[i].cpu = adapter->irq_tbl[irq_idx].cpu =
1919                     last_bind_cpu;
1920                 last_bind_cpu = CPU_NEXT(last_bind_cpu);
1921 #endif
1922         }
1923 }
1924
1925 static int
1926 ena_request_mgmnt_irq(struct ena_adapter *adapter)
1927 {
1928         struct ena_irq *irq;
1929         unsigned long flags;
1930         int rc, rcc;
1931
1932         flags = RF_ACTIVE | RF_SHAREABLE;
1933
1934         irq = &adapter->irq_tbl[ENA_MGMNT_IRQ_IDX];
1935         irq->res = bus_alloc_resource_any(adapter->pdev, SYS_RES_IRQ,
1936             &irq->vector, flags);
1937
1938         if (unlikely(irq->res == NULL)) {
1939                 device_printf(adapter->pdev, "could not allocate "
1940                     "irq vector: %d\n", irq->vector);
1941                 return (ENXIO);
1942         }
1943
1944         rc = bus_activate_resource(adapter->pdev, SYS_RES_IRQ,
1945             irq->vector, irq->res);
1946         if (unlikely(rc != 0)) {
1947                 device_printf(adapter->pdev, "could not activate "
1948                     "irq vector: %d\n", irq->vector);
1949                 goto err_res_free;
1950         }
1951
1952         rc = bus_setup_intr(adapter->pdev, irq->res,
1953             INTR_TYPE_NET | INTR_MPSAFE, NULL, ena_intr_msix_mgmnt,
1954             irq->data, &irq->cookie);
1955         if (unlikely(rc != 0)) {
1956                 device_printf(adapter->pdev, "failed to register "
1957                     "interrupt handler for irq %ju: %d\n",
1958                     rman_get_start(irq->res), rc);
1959                 goto err_res_free;
1960         }
1961         irq->requested = true;
1962
1963         return (rc);
1964
1965 err_res_free:
1966         ena_trace(ENA_INFO | ENA_ADMQ, "releasing resource for irq %d\n",
1967             irq->vector);
1968         rcc = bus_release_resource(adapter->pdev, SYS_RES_IRQ,
1969             irq->vector, irq->res);
1970         if (unlikely(rcc != 0))
1971                 device_printf(adapter->pdev, "dev has no parent while "
1972                     "releasing res for irq: %d\n", irq->vector);
1973         irq->res = NULL;
1974
1975         return (rc);
1976 }
1977
1978 static int
1979 ena_request_io_irq(struct ena_adapter *adapter)
1980 {
1981         struct ena_irq *irq;
1982         unsigned long flags = 0;
1983         int rc = 0, i, rcc;
1984
1985         if (unlikely(adapter->msix_enabled == 0)) {
1986                 device_printf(adapter->pdev,
1987                     "failed to request I/O IRQ: MSI-X is not enabled\n");
1988                 return (EINVAL);
1989         } else {
1990                 flags = RF_ACTIVE | RF_SHAREABLE;
1991         }
1992
1993         for (i = ENA_IO_IRQ_FIRST_IDX; i < adapter->msix_vecs; i++) {
1994                 irq = &adapter->irq_tbl[i];
1995
1996                 if (unlikely(irq->requested))
1997                         continue;
1998
1999                 irq->res = bus_alloc_resource_any(adapter->pdev, SYS_RES_IRQ,
2000                     &irq->vector, flags);
2001                 if (unlikely(irq->res == NULL)) {
2002                         device_printf(adapter->pdev, "could not allocate "
2003                             "irq vector: %d\n", irq->vector);
2004                         goto err;
2005                 }
2006
2007                 rc = bus_setup_intr(adapter->pdev, irq->res,
2008                     INTR_TYPE_NET | INTR_MPSAFE, NULL,
2009                     irq->handler, irq->data, &irq->cookie);
2010                  if (unlikely(rc != 0)) {
2011                         device_printf(adapter->pdev, "failed to register "
2012                             "interrupt handler for irq %ju: %d\n",
2013                             rman_get_start(irq->res), rc);
2014                         goto err;
2015                 }
2016                 irq->requested = true;
2017
2018 #ifdef  RSS
2019                 ena_trace(ENA_INFO, "queue %d - RSS bucket %d\n",
2020                     i - ENA_IO_IRQ_FIRST_IDX, irq->cpu);
2021 #else
2022                 ena_trace(ENA_INFO, "queue %d - cpu %d\n",
2023                     i - ENA_IO_IRQ_FIRST_IDX, irq->cpu);
2024 #endif
2025         }
2026
2027         return (rc);
2028
2029 err:
2030
2031         for (; i >= ENA_IO_IRQ_FIRST_IDX; i--) {
2032                 irq = &adapter->irq_tbl[i];
2033                 rcc = 0;
2034
2035                 /* Once we entered err: section and irq->requested is true we
2036                    free both intr and resources */
2037                 if (irq->requested)
2038                         rcc = bus_teardown_intr(adapter->pdev, irq->res, irq->cookie);
2039                 if (unlikely(rcc != 0))
2040                         device_printf(adapter->pdev, "could not release"
2041                             " irq: %d, error: %d\n", irq->vector, rcc);
2042
2043                 /* If we entred err: section without irq->requested set we know
2044                    it was bus_alloc_resource_any() that needs cleanup, provided
2045                    res is not NULL. In case res is NULL no work in needed in
2046                    this iteration */
2047                 rcc = 0;
2048                 if (irq->res != NULL) {
2049                         rcc = bus_release_resource(adapter->pdev, SYS_RES_IRQ,
2050                             irq->vector, irq->res);
2051                 }
2052                 if (unlikely(rcc != 0))
2053                         device_printf(adapter->pdev, "dev has no parent while "
2054                             "releasing res for irq: %d\n", irq->vector);
2055                 irq->requested = false;
2056                 irq->res = NULL;
2057         }
2058
2059         return (rc);
2060 }
2061
2062 static void
2063 ena_free_mgmnt_irq(struct ena_adapter *adapter)
2064 {
2065         struct ena_irq *irq;
2066         int rc;
2067
2068         irq = &adapter->irq_tbl[ENA_MGMNT_IRQ_IDX];
2069         if (irq->requested) {
2070                 ena_trace(ENA_INFO | ENA_ADMQ, "tear down irq: %d\n",
2071                     irq->vector);
2072                 rc = bus_teardown_intr(adapter->pdev, irq->res, irq->cookie);
2073                 if (unlikely(rc != 0))
2074                         device_printf(adapter->pdev, "failed to tear "
2075                             "down irq: %d\n", irq->vector);
2076                 irq->requested = 0;
2077         }
2078
2079         if (irq->res != NULL) {
2080                 ena_trace(ENA_INFO | ENA_ADMQ, "release resource irq: %d\n",
2081                     irq->vector);
2082                 rc = bus_release_resource(adapter->pdev, SYS_RES_IRQ,
2083                     irq->vector, irq->res);
2084                 irq->res = NULL;
2085                 if (unlikely(rc != 0))
2086                         device_printf(adapter->pdev, "dev has no parent while "
2087                             "releasing res for irq: %d\n", irq->vector);
2088         }
2089 }
2090
2091 static void
2092 ena_free_io_irq(struct ena_adapter *adapter)
2093 {
2094         struct ena_irq *irq;
2095         int rc;
2096
2097         for (int i = ENA_IO_IRQ_FIRST_IDX; i < adapter->msix_vecs; i++) {
2098                 irq = &adapter->irq_tbl[i];
2099                 if (irq->requested) {
2100                         ena_trace(ENA_INFO | ENA_IOQ, "tear down irq: %d\n",
2101                             irq->vector);
2102                         rc = bus_teardown_intr(adapter->pdev, irq->res,
2103                             irq->cookie);
2104                         if (unlikely(rc != 0)) {
2105                                 device_printf(adapter->pdev, "failed to tear "
2106                                     "down irq: %d\n", irq->vector);
2107                         }
2108                         irq->requested = 0;
2109                 }
2110
2111                 if (irq->res != NULL) {
2112                         ena_trace(ENA_INFO | ENA_IOQ, "release resource irq: %d\n",
2113                             irq->vector);
2114                         rc = bus_release_resource(adapter->pdev, SYS_RES_IRQ,
2115                             irq->vector, irq->res);
2116                         irq->res = NULL;
2117                         if (unlikely(rc != 0)) {
2118                                 device_printf(adapter->pdev, "dev has no parent"
2119                                     " while releasing res for irq: %d\n",
2120                                     irq->vector);
2121                         }
2122                 }
2123         }
2124 }
2125
2126 static void
2127 ena_free_irqs(struct ena_adapter* adapter)
2128 {
2129
2130         ena_free_io_irq(adapter);
2131         ena_free_mgmnt_irq(adapter);
2132         ena_disable_msix(adapter);
2133 }
2134
2135 static void
2136 ena_disable_msix(struct ena_adapter *adapter)
2137 {
2138
2139         pci_release_msi(adapter->pdev);
2140
2141         adapter->msix_vecs = 0;
2142         free(adapter->msix_entries, M_DEVBUF);
2143         adapter->msix_entries = NULL;
2144 }
2145
2146 static void
2147 ena_unmask_all_io_irqs(struct ena_adapter *adapter)
2148 {
2149         struct ena_com_io_cq* io_cq;
2150         struct ena_eth_io_intr_reg intr_reg;
2151         uint16_t ena_qid;
2152         int i;
2153
2154         /* Unmask interrupts for all queues */
2155         for (i = 0; i < adapter->num_queues; i++) {
2156                 ena_qid = ENA_IO_TXQ_IDX(i);
2157                 io_cq = &adapter->ena_dev->io_cq_queues[ena_qid];
2158                 ena_com_update_intr_reg(&intr_reg, 0, 0, true);
2159                 ena_com_unmask_intr(io_cq, &intr_reg);
2160         }
2161 }
2162
2163 /* Configure the Rx forwarding */
2164 static int
2165 ena_rss_configure(struct ena_adapter *adapter)
2166 {
2167         struct ena_com_dev *ena_dev = adapter->ena_dev;
2168         int rc;
2169
2170         /* Set indirect table */
2171         rc = ena_com_indirect_table_set(ena_dev);
2172         if (unlikely((rc != 0) && (rc != EOPNOTSUPP)))
2173                 return (rc);
2174
2175         /* Configure hash function (if supported) */
2176         rc = ena_com_set_hash_function(ena_dev);
2177         if (unlikely((rc != 0) && (rc != EOPNOTSUPP)))
2178                 return (rc);
2179
2180         /* Configure hash inputs (if supported) */
2181         rc = ena_com_set_hash_ctrl(ena_dev);
2182         if (unlikely((rc != 0) && (rc != EOPNOTSUPP)))
2183                 return (rc);
2184
2185         return (0);
2186 }
2187
2188 static int
2189 ena_up_complete(struct ena_adapter *adapter)
2190 {
2191         int rc;
2192
2193         if (likely(adapter->rss_support)) {
2194                 rc = ena_rss_configure(adapter);
2195                 if (rc != 0)
2196                         return (rc);
2197         }
2198
2199         rc = ena_change_mtu(adapter->ifp, adapter->ifp->if_mtu);
2200         if (unlikely(rc != 0))
2201                 return (rc);
2202
2203         ena_refill_all_rx_bufs(adapter);
2204         ena_reset_counters((counter_u64_t *)&adapter->hw_stats,
2205             sizeof(adapter->hw_stats));
2206
2207         return (0);
2208 }
2209
2210 static int
2211 ena_up(struct ena_adapter *adapter)
2212 {
2213         int rc = 0;
2214
2215         if (unlikely(device_is_attached(adapter->pdev) == 0)) {
2216                 device_printf(adapter->pdev, "device is not attached!\n");
2217                 return (ENXIO);
2218         }
2219
2220         if (unlikely(!adapter->running)) {
2221                 device_printf(adapter->pdev, "device is not running!\n");
2222                 return (ENXIO);
2223         }
2224
2225         if (!adapter->up) {
2226                 device_printf(adapter->pdev, "device is going UP\n");
2227
2228                 /* setup interrupts for IO queues */
2229                 ena_setup_io_intr(adapter);
2230                 rc = ena_request_io_irq(adapter);
2231                 if (unlikely(rc != 0)) {
2232                         ena_trace(ENA_ALERT, "err_req_irq");
2233                         goto err_req_irq;
2234                 }
2235
2236                 /* allocate transmit descriptors */
2237                 rc = ena_setup_all_tx_resources(adapter);
2238                 if (unlikely(rc != 0)) {
2239                         ena_trace(ENA_ALERT, "err_setup_tx");
2240                         goto err_setup_tx;
2241                 }
2242
2243                 /* allocate receive descriptors */
2244                 rc = ena_setup_all_rx_resources(adapter);
2245                 if (unlikely(rc != 0)) {
2246                         ena_trace(ENA_ALERT, "err_setup_rx");
2247                         goto err_setup_rx;
2248                 }
2249
2250                 /* create IO queues for Rx & Tx */
2251                 rc = ena_create_io_queues(adapter);
2252                 if (unlikely(rc != 0)) {
2253                         ena_trace(ENA_ALERT,
2254                             "create IO queues failed");
2255                         goto err_io_que;
2256                 }
2257
2258                 if (unlikely(adapter->link_status))
2259                         if_link_state_change(adapter->ifp, LINK_STATE_UP);
2260
2261                 rc = ena_up_complete(adapter);
2262                 if (unlikely(rc != 0))
2263                         goto err_up_complete;
2264
2265                 counter_u64_add(adapter->dev_stats.interface_up, 1);
2266
2267                 ena_update_hwassist(adapter);
2268
2269                 if_setdrvflagbits(adapter->ifp, IFF_DRV_RUNNING,
2270                     IFF_DRV_OACTIVE);
2271
2272                 callout_reset_sbt(&adapter->timer_service, SBT_1S, SBT_1S,
2273                     ena_timer_service, (void *)adapter, 0);
2274
2275                 adapter->up = true;
2276
2277                 ena_unmask_all_io_irqs(adapter);
2278         }
2279
2280         return (0);
2281
2282 err_up_complete:
2283         ena_destroy_all_io_queues(adapter);
2284 err_io_que:
2285         ena_free_all_rx_resources(adapter);
2286 err_setup_rx:
2287         ena_free_all_tx_resources(adapter);
2288 err_setup_tx:
2289         ena_free_io_irq(adapter);
2290 err_req_irq:
2291         return (rc);
2292 }
2293
2294 static uint64_t
2295 ena_get_counter(if_t ifp, ift_counter cnt)
2296 {
2297         struct ena_adapter *adapter;
2298         struct ena_hw_stats *stats;
2299
2300         adapter = if_getsoftc(ifp);
2301         stats = &adapter->hw_stats;
2302
2303         switch (cnt) {
2304         case IFCOUNTER_IPACKETS:
2305                 return (counter_u64_fetch(stats->rx_packets));
2306         case IFCOUNTER_OPACKETS:
2307                 return (counter_u64_fetch(stats->tx_packets));
2308         case IFCOUNTER_IBYTES:
2309                 return (counter_u64_fetch(stats->rx_bytes));
2310         case IFCOUNTER_OBYTES:
2311                 return (counter_u64_fetch(stats->tx_bytes));
2312         case IFCOUNTER_IQDROPS:
2313                 return (counter_u64_fetch(stats->rx_drops));
2314         default:
2315                 return (if_get_counter_default(ifp, cnt));
2316         }
2317 }
2318
2319 static int
2320 ena_media_change(if_t ifp)
2321 {
2322         /* Media Change is not supported by firmware */
2323         return (0);
2324 }
2325
2326 static void
2327 ena_media_status(if_t ifp, struct ifmediareq *ifmr)
2328 {
2329         struct ena_adapter *adapter = if_getsoftc(ifp);
2330         ena_trace(ENA_DBG, "enter");
2331
2332         mtx_lock(&adapter->global_mtx);
2333
2334         ifmr->ifm_status = IFM_AVALID;
2335         ifmr->ifm_active = IFM_ETHER;
2336
2337         if (!adapter->link_status) {
2338                 mtx_unlock(&adapter->global_mtx);
2339                 ena_trace(ENA_INFO, "link_status = false");
2340                 return;
2341         }
2342
2343         ifmr->ifm_status |= IFM_ACTIVE;
2344         ifmr->ifm_active |= IFM_10G_T | IFM_FDX;
2345
2346         mtx_unlock(&adapter->global_mtx);
2347 }
2348
2349 static void
2350 ena_init(void *arg)
2351 {
2352         struct ena_adapter *adapter = (struct ena_adapter *)arg;
2353
2354         if (!adapter->up) {
2355                 sx_xlock(&adapter->ioctl_sx);
2356                 ena_up(adapter);
2357                 sx_unlock(&adapter->ioctl_sx);
2358         }
2359 }
2360
2361 static int
2362 ena_ioctl(if_t ifp, u_long command, caddr_t data)
2363 {
2364         struct ena_adapter *adapter;
2365         struct ifreq *ifr;
2366         int rc;
2367
2368         adapter = ifp->if_softc;
2369         ifr = (struct ifreq *)data;
2370
2371         /*
2372          * Acquiring lock to prevent from running up and down routines parallel.
2373          */
2374         rc = 0;
2375         switch (command) {
2376         case SIOCSIFMTU:
2377                 sx_xlock(&adapter->ioctl_sx);
2378                 ena_down(adapter);
2379
2380                 ena_change_mtu(ifp, ifr->ifr_mtu);
2381
2382                 rc = ena_up(adapter);
2383                 sx_unlock(&adapter->ioctl_sx);
2384                 break;
2385
2386         case SIOCSIFFLAGS:
2387                 if ((ifp->if_flags & IFF_UP) != 0) {
2388                         if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) != 0) {
2389                                 if ((ifp->if_flags & (IFF_PROMISC |
2390                                     IFF_ALLMULTI)) != 0) {
2391                                         device_printf(adapter->pdev,
2392                                             "ioctl promisc/allmulti\n");
2393                                 }
2394                         } else {
2395                                 sx_xlock(&adapter->ioctl_sx);
2396                                 rc = ena_up(adapter);
2397                                 sx_unlock(&adapter->ioctl_sx);
2398                         }
2399                 } else {
2400                         if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) != 0) {
2401                                 sx_xlock(&adapter->ioctl_sx);
2402                                 ena_down(adapter);
2403                                 sx_unlock(&adapter->ioctl_sx);
2404                         }
2405                 }
2406                 break;
2407
2408         case SIOCADDMULTI:
2409         case SIOCDELMULTI:
2410                 break;
2411
2412         case SIOCSIFMEDIA:
2413         case SIOCGIFMEDIA:
2414                 rc = ifmedia_ioctl(ifp, ifr, &adapter->media, command);
2415                 break;
2416
2417         case SIOCSIFCAP:
2418                 {
2419                         int reinit = 0;
2420
2421                         if (ifr->ifr_reqcap != ifp->if_capenable) {
2422                                 ifp->if_capenable = ifr->ifr_reqcap;
2423                                 reinit = 1;
2424                         }
2425
2426                         if ((reinit != 0) &&
2427                             ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) != 0)) {
2428                                 sx_xlock(&adapter->ioctl_sx);
2429                                 ena_down(adapter);
2430                                 rc = ena_up(adapter);
2431                                 sx_unlock(&adapter->ioctl_sx);
2432                         }
2433                 }
2434
2435                 break;
2436         default:
2437                 rc = ether_ioctl(ifp, command, data);
2438                 break;
2439         }
2440
2441         return (rc);
2442 }
2443
2444 static int
2445 ena_get_dev_offloads(struct ena_com_dev_get_features_ctx *feat)
2446 {
2447         int caps = 0;
2448
2449         if ((feat->offload.tx &
2450             (ENA_ADMIN_FEATURE_OFFLOAD_DESC_TX_L4_IPV4_CSUM_FULL_MASK |
2451             ENA_ADMIN_FEATURE_OFFLOAD_DESC_TX_L4_IPV4_CSUM_PART_MASK |
2452                 ENA_ADMIN_FEATURE_OFFLOAD_DESC_TX_L3_CSUM_IPV4_MASK)) != 0)
2453                 caps |= IFCAP_TXCSUM;
2454
2455         if ((feat->offload.tx &
2456             (ENA_ADMIN_FEATURE_OFFLOAD_DESC_TX_L4_IPV6_CSUM_FULL_MASK |
2457             ENA_ADMIN_FEATURE_OFFLOAD_DESC_TX_L4_IPV6_CSUM_PART_MASK)) != 0)
2458                 caps |= IFCAP_TXCSUM_IPV6;
2459
2460         if ((feat->offload.tx &
2461             ENA_ADMIN_FEATURE_OFFLOAD_DESC_TSO_IPV4_MASK) != 0)
2462                 caps |= IFCAP_TSO4;
2463
2464         if ((feat->offload.tx &
2465             ENA_ADMIN_FEATURE_OFFLOAD_DESC_TSO_IPV6_MASK) != 0)
2466                 caps |= IFCAP_TSO6;
2467
2468         if ((feat->offload.rx_supported &
2469             (ENA_ADMIN_FEATURE_OFFLOAD_DESC_RX_L4_IPV4_CSUM_MASK |
2470             ENA_ADMIN_FEATURE_OFFLOAD_DESC_RX_L3_CSUM_IPV4_MASK)) != 0)
2471                 caps |= IFCAP_RXCSUM;
2472
2473         if ((feat->offload.rx_supported &
2474             ENA_ADMIN_FEATURE_OFFLOAD_DESC_RX_L4_IPV6_CSUM_MASK) != 0)
2475                 caps |= IFCAP_RXCSUM_IPV6;
2476
2477         caps |= IFCAP_LRO | IFCAP_JUMBO_MTU;
2478
2479         return (caps);
2480 }
2481
2482 static void
2483 ena_update_host_info(struct ena_admin_host_info *host_info, if_t ifp)
2484 {
2485
2486         host_info->supported_network_features[0] =
2487             (uint32_t)if_getcapabilities(ifp);
2488 }
2489
2490 static void
2491 ena_update_hwassist(struct ena_adapter *adapter)
2492 {
2493         if_t ifp = adapter->ifp;
2494         uint32_t feat = adapter->tx_offload_cap;
2495         int cap = if_getcapenable(ifp);
2496         int flags = 0;
2497
2498         if_clearhwassist(ifp);
2499
2500         if ((cap & IFCAP_TXCSUM) != 0) {
2501                 if ((feat &
2502                     ENA_ADMIN_FEATURE_OFFLOAD_DESC_TX_L3_CSUM_IPV4_MASK) != 0)
2503                         flags |= CSUM_IP;
2504                 if ((feat &
2505                     (ENA_ADMIN_FEATURE_OFFLOAD_DESC_TX_L4_IPV4_CSUM_FULL_MASK |
2506                     ENA_ADMIN_FEATURE_OFFLOAD_DESC_TX_L4_IPV4_CSUM_PART_MASK)) != 0)
2507                         flags |= CSUM_IP_UDP | CSUM_IP_TCP;
2508         }
2509
2510         if ((cap & IFCAP_TXCSUM_IPV6) != 0)
2511                 flags |= CSUM_IP6_UDP | CSUM_IP6_TCP;
2512
2513         if ((cap & IFCAP_TSO4) != 0)
2514                 flags |= CSUM_IP_TSO;
2515
2516         if ((cap & IFCAP_TSO6) != 0)
2517                 flags |= CSUM_IP6_TSO;
2518
2519         if_sethwassistbits(ifp, flags, 0);
2520 }
2521
2522 static int
2523 ena_setup_ifnet(device_t pdev, struct ena_adapter *adapter,
2524     struct ena_com_dev_get_features_ctx *feat)
2525 {
2526         if_t ifp;
2527         int caps = 0;
2528
2529         ifp = adapter->ifp = if_gethandle(IFT_ETHER);
2530         if (unlikely(ifp == NULL)) {
2531                 ena_trace(ENA_ALERT, "can not allocate ifnet structure\n");
2532                 return (ENXIO);
2533         }
2534         if_initname(ifp, device_get_name(pdev), device_get_unit(pdev));
2535         if_setdev(ifp, pdev);
2536         if_setsoftc(ifp, adapter);
2537
2538         if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2539         if_setinitfn(ifp, ena_init);
2540         if_settransmitfn(ifp, ena_mq_start);
2541         if_setqflushfn(ifp, ena_qflush);
2542         if_setioctlfn(ifp, ena_ioctl);
2543         if_setgetcounterfn(ifp, ena_get_counter);
2544
2545         if_setsendqlen(ifp, adapter->tx_ring_size);
2546         if_setsendqready(ifp);
2547         if_setmtu(ifp, ETHERMTU);
2548         if_setbaudrate(ifp, 0);
2549         /* Zeroize capabilities... */
2550         if_setcapabilities(ifp, 0);
2551         if_setcapenable(ifp, 0);
2552         /* check hardware support */
2553         caps = ena_get_dev_offloads(feat);
2554         /* ... and set them */
2555         if_setcapabilitiesbit(ifp, caps, 0);
2556
2557         /* TSO parameters */
2558         ifp->if_hw_tsomax = ENA_TSO_MAXSIZE -
2559             (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
2560         ifp->if_hw_tsomaxsegcount = adapter->max_tx_sgl_size - 1;
2561         ifp->if_hw_tsomaxsegsize = ENA_TSO_MAXSIZE;
2562
2563         if_setifheaderlen(ifp, sizeof(struct ether_vlan_header));
2564         if_setcapenable(ifp, if_getcapabilities(ifp));
2565
2566         /*
2567          * Specify the media types supported by this adapter and register
2568          * callbacks to update media and link information
2569          */
2570         ifmedia_init(&adapter->media, IFM_IMASK,
2571             ena_media_change, ena_media_status);
2572         ifmedia_add(&adapter->media, IFM_ETHER | IFM_AUTO, 0, NULL);
2573         ifmedia_set(&adapter->media, IFM_ETHER | IFM_AUTO);
2574
2575         ether_ifattach(ifp, adapter->mac_addr);
2576
2577         return (0);
2578 }
2579
2580 static void
2581 ena_down(struct ena_adapter *adapter)
2582 {
2583         int rc;
2584
2585         if (adapter->up) {
2586                 device_printf(adapter->pdev, "device is going DOWN\n");
2587
2588                 callout_drain(&adapter->timer_service);
2589
2590                 adapter->up = false;
2591                 if_setdrvflagbits(adapter->ifp, IFF_DRV_OACTIVE,
2592                     IFF_DRV_RUNNING);
2593
2594                 ena_free_io_irq(adapter);
2595
2596                 if (adapter->trigger_reset) {
2597                         rc = ena_com_dev_reset(adapter->ena_dev,
2598                             adapter->reset_reason);
2599                         if (unlikely(rc != 0))
2600                                 device_printf(adapter->pdev,
2601                                     "Device reset failed\n");
2602                 }
2603
2604                 ena_destroy_all_io_queues(adapter);
2605
2606                 ena_free_all_tx_bufs(adapter);
2607                 ena_free_all_rx_bufs(adapter);
2608                 ena_free_all_tx_resources(adapter);
2609                 ena_free_all_rx_resources(adapter);
2610
2611                 counter_u64_add(adapter->dev_stats.interface_down, 1);
2612         }
2613 }
2614
2615 static void
2616 ena_tx_csum(struct ena_com_tx_ctx *ena_tx_ctx, struct mbuf *mbuf)
2617 {
2618         struct ena_com_tx_meta *ena_meta;
2619         struct ether_vlan_header *eh;
2620         u32 mss;
2621         bool offload;
2622         uint16_t etype;
2623         int ehdrlen;
2624         struct ip *ip;
2625         int iphlen;
2626         struct tcphdr *th;
2627
2628         offload = false;
2629         ena_meta = &ena_tx_ctx->ena_meta;
2630         mss = mbuf->m_pkthdr.tso_segsz;
2631
2632         if (mss != 0)
2633                 offload = true;
2634
2635         if ((mbuf->m_pkthdr.csum_flags & CSUM_TSO) != 0)
2636                 offload = true;
2637
2638         if ((mbuf->m_pkthdr.csum_flags & CSUM_OFFLOAD) != 0)
2639                 offload = true;
2640
2641         if (!offload) {
2642                 ena_tx_ctx->meta_valid = 0;
2643                 return;
2644         }
2645
2646         /* Determine where frame payload starts. */
2647         eh = mtod(mbuf, struct ether_vlan_header *);
2648         if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
2649                 etype = ntohs(eh->evl_proto);
2650                 ehdrlen = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
2651         } else {
2652                 etype = ntohs(eh->evl_encap_proto);
2653                 ehdrlen = ETHER_HDR_LEN;
2654         }
2655
2656         ip = (struct ip *)(mbuf->m_data + ehdrlen);
2657         iphlen = ip->ip_hl << 2;
2658         th = (struct tcphdr *)((caddr_t)ip + iphlen);
2659
2660         if ((mbuf->m_pkthdr.csum_flags & CSUM_IP) != 0) {
2661                 ena_tx_ctx->l3_csum_enable = 1;
2662         }
2663         if ((mbuf->m_pkthdr.csum_flags & CSUM_TSO) != 0) {
2664                 ena_tx_ctx->tso_enable = 1;
2665                 ena_meta->l4_hdr_len = (th->th_off);
2666         }
2667
2668         switch (etype) {
2669         case ETHERTYPE_IP:
2670                 ena_tx_ctx->l3_proto = ENA_ETH_IO_L3_PROTO_IPV4;
2671                 if ((ip->ip_off & htons(IP_DF)) != 0)
2672                         ena_tx_ctx->df = 1;
2673                 break;
2674         case ETHERTYPE_IPV6:
2675                 ena_tx_ctx->l3_proto = ENA_ETH_IO_L3_PROTO_IPV6;
2676
2677         default:
2678                 break;
2679         }
2680
2681         if (ip->ip_p == IPPROTO_TCP) {
2682                 ena_tx_ctx->l4_proto = ENA_ETH_IO_L4_PROTO_TCP;
2683                 if ((mbuf->m_pkthdr.csum_flags &
2684                     (CSUM_IP_TCP | CSUM_IP6_TCP)) != 0)
2685                         ena_tx_ctx->l4_csum_enable = 1;
2686                 else
2687                         ena_tx_ctx->l4_csum_enable = 0;
2688         } else if (ip->ip_p == IPPROTO_UDP) {
2689                 ena_tx_ctx->l4_proto = ENA_ETH_IO_L4_PROTO_UDP;
2690                 if ((mbuf->m_pkthdr.csum_flags &
2691                     (CSUM_IP_UDP | CSUM_IP6_UDP)) != 0)
2692                         ena_tx_ctx->l4_csum_enable = 1;
2693                 else
2694                         ena_tx_ctx->l4_csum_enable = 0;
2695         } else {
2696                 ena_tx_ctx->l4_proto = ENA_ETH_IO_L4_PROTO_UNKNOWN;
2697                 ena_tx_ctx->l4_csum_enable = 0;
2698         }
2699
2700         ena_meta->mss = mss;
2701         ena_meta->l3_hdr_len = iphlen;
2702         ena_meta->l3_hdr_offset = ehdrlen;
2703         ena_tx_ctx->meta_valid = 1;
2704 }
2705
2706 static int
2707 ena_check_and_collapse_mbuf(struct ena_ring *tx_ring, struct mbuf **mbuf)
2708 {
2709         struct ena_adapter *adapter;
2710         struct mbuf *collapsed_mbuf;
2711         int num_frags;
2712
2713         adapter = tx_ring->adapter;
2714         num_frags = ena_mbuf_count(*mbuf);
2715
2716         /* One segment must be reserved for configuration descriptor. */
2717         if (num_frags < adapter->max_tx_sgl_size)
2718                 return (0);
2719         counter_u64_add(tx_ring->tx_stats.collapse, 1);
2720
2721         collapsed_mbuf = m_collapse(*mbuf, M_NOWAIT,
2722             adapter->max_tx_sgl_size - 1);
2723         if (unlikely(collapsed_mbuf == NULL)) {
2724                 counter_u64_add(tx_ring->tx_stats.collapse_err, 1);
2725                 return (ENOMEM);
2726         }
2727
2728         /* If mbuf was collapsed succesfully, original mbuf is released. */
2729         *mbuf = collapsed_mbuf;
2730
2731         return (0);
2732 }
2733
2734 static int
2735 ena_xmit_mbuf(struct ena_ring *tx_ring, struct mbuf **mbuf)
2736 {
2737         struct ena_adapter *adapter;
2738         struct ena_tx_buffer *tx_info;
2739         struct ena_com_tx_ctx ena_tx_ctx;
2740         struct ena_com_dev *ena_dev;
2741         struct ena_com_buf *ena_buf;
2742         struct ena_com_io_sq* io_sq;
2743         bus_dma_segment_t segs[ENA_BUS_DMA_SEGS];
2744         void *push_hdr;
2745         uint16_t next_to_use;
2746         uint16_t req_id;
2747         uint16_t push_len;
2748         uint16_t ena_qid;
2749         uint32_t len, nsegs, header_len;
2750         int i, rc;
2751         int nb_hw_desc;
2752
2753         ena_qid = ENA_IO_TXQ_IDX(tx_ring->que->id);
2754         adapter = tx_ring->que->adapter;
2755         ena_dev = adapter->ena_dev;
2756         io_sq = &ena_dev->io_sq_queues[ena_qid];
2757
2758         rc = ena_check_and_collapse_mbuf(tx_ring, mbuf);
2759         if (unlikely(rc != 0)) {
2760                 ena_trace(ENA_WARNING,
2761                     "Failed to collapse mbuf! err: %d", rc);
2762                 return (rc);
2763         }
2764
2765         next_to_use = tx_ring->next_to_use;
2766         req_id = tx_ring->free_tx_ids[next_to_use];
2767         tx_info = &tx_ring->tx_buffer_info[req_id];
2768
2769         tx_info->mbuf = *mbuf;
2770         tx_info->num_of_bufs = 0;
2771
2772         ena_buf = tx_info->bufs;
2773         len = (*mbuf)->m_len;
2774
2775         ena_trace(ENA_DBG | ENA_TXPTH, "Tx: %d bytes", (*mbuf)->m_pkthdr.len);
2776
2777         push_len = 0;
2778         header_len = min_t(uint32_t, len, tx_ring->tx_max_header_size);
2779         push_hdr = NULL;
2780
2781         rc = bus_dmamap_load_mbuf_sg(adapter->tx_buf_tag, tx_info->map,
2782             *mbuf, segs, &nsegs, BUS_DMA_NOWAIT);
2783
2784         if (unlikely((rc != 0) || (nsegs == 0))) {
2785                 ena_trace(ENA_WARNING,
2786                     "dmamap load failed! err: %d nsegs: %d", rc, nsegs);
2787                 counter_u64_add(tx_ring->tx_stats.dma_mapping_err, 1);
2788                 tx_info->mbuf = NULL;
2789                 if (rc == ENOMEM)
2790                         return (ENA_COM_NO_MEM);
2791                 else
2792                         return (ENA_COM_INVAL);
2793         }
2794
2795         for (i = 0; i < nsegs; i++) {
2796                 ena_buf->len = segs[i].ds_len;
2797                 ena_buf->paddr = segs[i].ds_addr;
2798                 ena_buf++;
2799         }
2800         tx_info->num_of_bufs = nsegs;
2801
2802         memset(&ena_tx_ctx, 0x0, sizeof(struct ena_com_tx_ctx));
2803         ena_tx_ctx.ena_bufs = tx_info->bufs;
2804         ena_tx_ctx.push_header = push_hdr;
2805         ena_tx_ctx.num_bufs = tx_info->num_of_bufs;
2806         ena_tx_ctx.req_id = req_id;
2807         ena_tx_ctx.header_len = header_len;
2808
2809         /* Set flags and meta data */
2810         ena_tx_csum(&ena_tx_ctx, *mbuf);
2811         /* Prepare the packet's descriptors and send them to device */
2812         rc = ena_com_prepare_tx(io_sq, &ena_tx_ctx, &nb_hw_desc);
2813         if (unlikely(rc != 0)) {
2814                 device_printf(adapter->pdev, "failed to prepare tx bufs\n");
2815                 counter_u64_add(tx_ring->tx_stats.prepare_ctx_err, 1);
2816                 goto dma_error;
2817         }
2818
2819         counter_enter();
2820         counter_u64_add_protected(tx_ring->tx_stats.cnt, 1);
2821         counter_u64_add_protected(tx_ring->tx_stats.bytes,
2822             (*mbuf)->m_pkthdr.len);
2823
2824         counter_u64_add_protected(adapter->hw_stats.tx_packets, 1);
2825         counter_u64_add_protected(adapter->hw_stats.tx_bytes,
2826             (*mbuf)->m_pkthdr.len);
2827         counter_exit();
2828
2829         tx_info->tx_descs = nb_hw_desc;
2830         getbinuptime(&tx_info->timestamp);
2831         tx_info->print_once = true;
2832
2833         tx_ring->next_to_use = ENA_TX_RING_IDX_NEXT(next_to_use,
2834             tx_ring->ring_size);
2835
2836         bus_dmamap_sync(adapter->tx_buf_tag, tx_info->map,
2837             BUS_DMASYNC_PREWRITE);
2838
2839         return (0);
2840
2841 dma_error:
2842         tx_info->mbuf = NULL;
2843         bus_dmamap_unload(adapter->tx_buf_tag, tx_info->map);
2844
2845         return (rc);
2846 }
2847
2848 static void
2849 ena_start_xmit(struct ena_ring *tx_ring)
2850 {
2851         struct mbuf *mbuf;
2852         struct ena_adapter *adapter = tx_ring->adapter;
2853         struct ena_com_io_sq* io_sq;
2854         int ena_qid;
2855         int acum_pkts = 0;
2856         int ret = 0;
2857
2858         if (unlikely((if_getdrvflags(adapter->ifp) & IFF_DRV_RUNNING) == 0))
2859                 return;
2860
2861         if (unlikely(!adapter->link_status))
2862                 return;
2863
2864         ena_qid = ENA_IO_TXQ_IDX(tx_ring->que->id);
2865         io_sq = &adapter->ena_dev->io_sq_queues[ena_qid];
2866
2867         while ((mbuf = drbr_peek(adapter->ifp, tx_ring->br)) != NULL) {
2868                 ena_trace(ENA_DBG | ENA_TXPTH, "\ndequeued mbuf %p with flags %#x and"
2869                     " header csum flags %#jx",
2870                     mbuf, mbuf->m_flags, (uint64_t)mbuf->m_pkthdr.csum_flags);
2871
2872                 if (unlikely(!ena_com_sq_have_enough_space(io_sq,
2873                     ENA_TX_CLEANUP_THRESHOLD)))
2874                         ena_tx_cleanup(tx_ring);
2875
2876                 if (unlikely((ret = ena_xmit_mbuf(tx_ring, &mbuf)) != 0)) {
2877                         if (ret == ENA_COM_NO_MEM) {
2878                                 drbr_putback(adapter->ifp, tx_ring->br, mbuf);
2879                         } else if (ret == ENA_COM_NO_SPACE) {
2880                                 drbr_putback(adapter->ifp, tx_ring->br, mbuf);
2881                         } else {
2882                                 m_freem(mbuf);
2883                                 drbr_advance(adapter->ifp, tx_ring->br);
2884                         }
2885
2886                         break;
2887                 }
2888
2889                 drbr_advance(adapter->ifp, tx_ring->br);
2890
2891                 if (unlikely((if_getdrvflags(adapter->ifp) &
2892                     IFF_DRV_RUNNING) == 0))
2893                         return;
2894
2895                 acum_pkts++;
2896
2897                 BPF_MTAP(adapter->ifp, mbuf);
2898
2899                 if (unlikely(acum_pkts == DB_THRESHOLD)) {
2900                         acum_pkts = 0;
2901                         wmb();
2902                         /* Trigger the dma engine */
2903                         ena_com_write_sq_doorbell(io_sq);
2904                         counter_u64_add(tx_ring->tx_stats.doorbells, 1);
2905                 }
2906
2907         }
2908
2909         if (likely(acum_pkts != 0)) {
2910                 wmb();
2911                 /* Trigger the dma engine */
2912                 ena_com_write_sq_doorbell(io_sq);
2913                 counter_u64_add(tx_ring->tx_stats.doorbells, 1);
2914         }
2915
2916         if (!ena_com_sq_have_enough_space(io_sq, ENA_TX_CLEANUP_THRESHOLD))
2917                 ena_tx_cleanup(tx_ring);
2918 }
2919
2920 static void
2921 ena_deferred_mq_start(void *arg, int pending)
2922 {
2923         struct ena_ring *tx_ring = (struct ena_ring *)arg;
2924         struct ifnet *ifp = tx_ring->adapter->ifp;
2925
2926         while (!drbr_empty(ifp, tx_ring->br) &&
2927             (if_getdrvflags(ifp) & IFF_DRV_RUNNING) != 0) {
2928                 ENA_RING_MTX_LOCK(tx_ring);
2929                 ena_start_xmit(tx_ring);
2930                 ENA_RING_MTX_UNLOCK(tx_ring);
2931         }
2932 }
2933
2934 static int
2935 ena_mq_start(if_t ifp, struct mbuf *m)
2936 {
2937         struct ena_adapter *adapter = ifp->if_softc;
2938         struct ena_ring *tx_ring;
2939         int ret, is_drbr_empty;
2940         uint32_t i;
2941
2942         if (unlikely((if_getdrvflags(adapter->ifp) & IFF_DRV_RUNNING) == 0))
2943                 return (ENODEV);
2944
2945         /* Which queue to use */
2946         /*
2947          * If everything is setup correctly, it should be the
2948          * same bucket that the current CPU we're on is.
2949          * It should improve performance.
2950          */
2951         if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) {
2952 #ifdef  RSS
2953                 if (rss_hash2bucket(m->m_pkthdr.flowid,
2954                     M_HASHTYPE_GET(m), &i) == 0) {
2955                         i = i % adapter->num_queues;
2956
2957                 } else
2958 #endif
2959                 {
2960                         i = m->m_pkthdr.flowid % adapter->num_queues;
2961                 }
2962         } else {
2963                 i = curcpu % adapter->num_queues;
2964         }
2965         tx_ring = &adapter->tx_ring[i];
2966
2967         /* Check if drbr is empty before putting packet */
2968         is_drbr_empty = drbr_empty(ifp, tx_ring->br);
2969         ret = drbr_enqueue(ifp, tx_ring->br, m);
2970         if (unlikely(ret != 0)) {
2971                 taskqueue_enqueue(tx_ring->enqueue_tq, &tx_ring->enqueue_task);
2972                 return (ret);
2973         }
2974
2975         if ((is_drbr_empty != 0) && (ENA_RING_MTX_TRYLOCK(tx_ring) != 0)) {
2976                 ena_start_xmit(tx_ring);
2977                 ENA_RING_MTX_UNLOCK(tx_ring);
2978         } else {
2979                 taskqueue_enqueue(tx_ring->enqueue_tq, &tx_ring->enqueue_task);
2980         }
2981
2982         return (0);
2983 }
2984
2985 static void
2986 ena_qflush(if_t ifp)
2987 {
2988         struct ena_adapter *adapter = ifp->if_softc;
2989         struct ena_ring *tx_ring = adapter->tx_ring;
2990         int i;
2991
2992         for(i = 0; i < adapter->num_queues; ++i, ++tx_ring)
2993                 if (!drbr_empty(ifp, tx_ring->br)) {
2994                         ENA_RING_MTX_LOCK(tx_ring);
2995                         drbr_flush(ifp, tx_ring->br);
2996                         ENA_RING_MTX_UNLOCK(tx_ring);
2997                 }
2998
2999         if_qflush(ifp);
3000 }
3001
3002 static int
3003 ena_calc_io_queue_num(struct ena_adapter *adapter,
3004     struct ena_com_dev_get_features_ctx *get_feat_ctx)
3005 {
3006         int io_sq_num, io_cq_num, io_queue_num;
3007
3008         io_sq_num = get_feat_ctx->max_queues.max_sq_num;
3009         io_cq_num = get_feat_ctx->max_queues.max_cq_num;
3010
3011         io_queue_num = min_t(int, mp_ncpus, ENA_MAX_NUM_IO_QUEUES);
3012         io_queue_num = min_t(int, io_queue_num, io_sq_num);
3013         io_queue_num = min_t(int, io_queue_num, io_cq_num);
3014         /* 1 IRQ for for mgmnt and 1 IRQ for each TX/RX pair */
3015         io_queue_num = min_t(int, io_queue_num,
3016             pci_msix_count(adapter->pdev) - 1);
3017 #ifdef  RSS
3018         io_queue_num = min_t(int, io_queue_num, rss_getnumbuckets());
3019 #endif
3020
3021         return (io_queue_num);
3022 }
3023
3024 static int
3025 ena_calc_queue_size(struct ena_adapter *adapter, uint16_t *max_tx_sgl_size,
3026     uint16_t *max_rx_sgl_size, struct ena_com_dev_get_features_ctx *feat)
3027 {
3028         uint32_t queue_size = ENA_DEFAULT_RING_SIZE;
3029         uint32_t v;
3030         uint32_t q;
3031
3032         queue_size = min_t(uint32_t, queue_size,
3033             feat->max_queues.max_cq_depth);
3034         queue_size = min_t(uint32_t, queue_size,
3035             feat->max_queues.max_sq_depth);
3036
3037         /* round down to the nearest power of 2 */
3038         v = queue_size;
3039         while (v != 0) {
3040                 if (powerof2(queue_size) != 0)
3041                         break;
3042                 v /= 2;
3043                 q = rounddown2(queue_size, v);
3044                 if (q != 0) {
3045                         queue_size = q;
3046                         break;
3047                 }
3048         }
3049
3050         if (unlikely(queue_size == 0)) {
3051                 device_printf(adapter->pdev, "Invalid queue size\n");
3052                 return (ENA_COM_FAULT);
3053         }
3054
3055         *max_tx_sgl_size = min_t(uint16_t, ENA_PKT_MAX_BUFS,
3056             feat->max_queues.max_packet_tx_descs);
3057         *max_rx_sgl_size = min_t(uint16_t, ENA_PKT_MAX_BUFS,
3058             feat->max_queues.max_packet_rx_descs);
3059
3060         return (queue_size);
3061 }
3062
3063 static int
3064 ena_rss_init_default(struct ena_adapter *adapter)
3065 {
3066         struct ena_com_dev *ena_dev = adapter->ena_dev;
3067         device_t dev = adapter->pdev;
3068         int qid, rc, i;
3069
3070         rc = ena_com_rss_init(ena_dev, ENA_RX_RSS_TABLE_LOG_SIZE);
3071         if (unlikely(rc != 0)) {
3072                 device_printf(dev, "Cannot init indirect table\n");
3073                 return (rc);
3074         }
3075
3076         for (i = 0; i < ENA_RX_RSS_TABLE_SIZE; i++) {
3077 #ifdef  RSS
3078                 qid = rss_get_indirection_to_bucket(i);
3079                 qid = qid % adapter->num_queues;
3080 #else
3081                 qid = i % adapter->num_queues;
3082 #endif
3083                 rc = ena_com_indirect_table_fill_entry(ena_dev, i,
3084                     ENA_IO_RXQ_IDX(qid));
3085                 if (unlikely((rc != 0) && (rc != EOPNOTSUPP))) {
3086                         device_printf(dev, "Cannot fill indirect table\n");
3087                         goto err_rss_destroy;
3088                 }
3089         }
3090
3091         rc = ena_com_fill_hash_function(ena_dev, ENA_ADMIN_CRC32, NULL,
3092             ENA_HASH_KEY_SIZE, 0xFFFFFFFF);
3093         if (unlikely((rc != 0) && (rc != EOPNOTSUPP))) {
3094                 device_printf(dev, "Cannot fill hash function\n");
3095                 goto err_rss_destroy;
3096         }
3097
3098         rc = ena_com_set_default_hash_ctrl(ena_dev);
3099         if (unlikely((rc != 0) && (rc != EOPNOTSUPP))) {
3100                 device_printf(dev, "Cannot fill hash control\n");
3101                 goto err_rss_destroy;
3102         }
3103
3104         return (0);
3105
3106 err_rss_destroy:
3107         ena_com_rss_destroy(ena_dev);
3108         return (rc);
3109 }
3110
3111 static void
3112 ena_rss_init_default_deferred(void *arg)
3113 {
3114         struct ena_adapter *adapter;
3115         devclass_t dc;
3116         int max;
3117         int rc;
3118
3119         dc = devclass_find("ena");
3120         if (unlikely(dc == NULL)) {
3121                 ena_trace(ENA_ALERT, "No devclass ena\n");
3122                 return;
3123         }
3124
3125         max = devclass_get_maxunit(dc);
3126         while (max-- >= 0) {
3127                 adapter = devclass_get_softc(dc, max);
3128                 if (adapter != NULL) {
3129                         rc = ena_rss_init_default(adapter);
3130                         adapter->rss_support = true;
3131                         if (unlikely(rc != 0)) {
3132                                 device_printf(adapter->pdev,
3133                                     "WARNING: RSS was not properly initialized,"
3134                                     " it will affect bandwidth\n");
3135                                 adapter->rss_support = false;
3136                         }
3137                 }
3138         }
3139 }
3140 SYSINIT(ena_rss_init, SI_SUB_KICK_SCHEDULER, SI_ORDER_SECOND, ena_rss_init_default_deferred, NULL);
3141
3142 static void
3143 ena_config_host_info(struct ena_com_dev *ena_dev)
3144 {
3145         struct ena_admin_host_info *host_info;
3146         int rc;
3147
3148         /* Allocate only the host info */
3149         rc = ena_com_allocate_host_info(ena_dev);
3150         if (unlikely(rc != 0)) {
3151                 ena_trace(ENA_ALERT, "Cannot allocate host info\n");
3152                 return;
3153         }
3154
3155         host_info = ena_dev->host_attr.host_info;
3156
3157         host_info->os_type = ENA_ADMIN_OS_FREEBSD;
3158         host_info->kernel_ver = osreldate;
3159
3160         sprintf(host_info->kernel_ver_str, "%d", osreldate);
3161         host_info->os_dist = 0;
3162         strncpy(host_info->os_dist_str, osrelease,
3163             sizeof(host_info->os_dist_str) - 1);
3164
3165         host_info->driver_version =
3166                 (DRV_MODULE_VER_MAJOR) |
3167                 (DRV_MODULE_VER_MINOR << ENA_ADMIN_HOST_INFO_MINOR_SHIFT) |
3168                 (DRV_MODULE_VER_SUBMINOR << ENA_ADMIN_HOST_INFO_SUB_MINOR_SHIFT);
3169
3170         rc = ena_com_set_host_attributes(ena_dev);
3171         if (unlikely(rc != 0)) {
3172                 if (rc == EOPNOTSUPP)
3173                         ena_trace(ENA_WARNING, "Cannot set host attributes\n");
3174                 else
3175                         ena_trace(ENA_ALERT, "Cannot set host attributes\n");
3176
3177                 goto err;
3178         }
3179
3180         return;
3181
3182 err:
3183         ena_com_delete_host_info(ena_dev);
3184 }
3185
3186 static int
3187 ena_device_init(struct ena_adapter *adapter, device_t pdev,
3188     struct ena_com_dev_get_features_ctx *get_feat_ctx, int *wd_active)
3189 {
3190         struct ena_com_dev* ena_dev = adapter->ena_dev;
3191         bool readless_supported;
3192         uint32_t aenq_groups;
3193         int dma_width;
3194         int rc;
3195
3196         rc = ena_com_mmio_reg_read_request_init(ena_dev);
3197         if (unlikely(rc != 0)) {
3198                 device_printf(pdev, "failed to init mmio read less\n");
3199                 return (rc);
3200         }
3201
3202         /*
3203          * The PCIe configuration space revision id indicate if mmio reg
3204          * read is disabled
3205          */
3206         readless_supported = !(pci_get_revid(pdev) & ENA_MMIO_DISABLE_REG_READ);
3207         ena_com_set_mmio_read_mode(ena_dev, readless_supported);
3208
3209         rc = ena_com_dev_reset(ena_dev, ENA_REGS_RESET_NORMAL);
3210         if (unlikely(rc != 0)) {
3211                 device_printf(pdev, "Can not reset device\n");
3212                 goto err_mmio_read_less;
3213         }
3214
3215         rc = ena_com_validate_version(ena_dev);
3216         if (unlikely(rc != 0)) {
3217                 device_printf(pdev, "device version is too low\n");
3218                 goto err_mmio_read_less;
3219         }
3220
3221         dma_width = ena_com_get_dma_width(ena_dev);
3222         if (unlikely(dma_width < 0)) {
3223                 device_printf(pdev, "Invalid dma width value %d", dma_width);
3224                 rc = dma_width;
3225                 goto err_mmio_read_less;
3226         }
3227         adapter->dma_width = dma_width;
3228
3229         /* ENA admin level init */
3230         rc = ena_com_admin_init(ena_dev, &aenq_handlers, true);
3231         if (unlikely(rc != 0)) {
3232                 device_printf(pdev,
3233                     "Can not initialize ena admin queue with device\n");
3234                 goto err_mmio_read_less;
3235         }
3236
3237         /*
3238          * To enable the msix interrupts the driver needs to know the number
3239          * of queues. So the driver uses polling mode to retrieve this
3240          * information
3241          */
3242         ena_com_set_admin_polling_mode(ena_dev, true);
3243
3244         ena_config_host_info(ena_dev);
3245
3246         /* Get Device Attributes */
3247         rc = ena_com_get_dev_attr_feat(ena_dev, get_feat_ctx);
3248         if (unlikely(rc != 0)) {
3249                 device_printf(pdev,
3250                     "Cannot get attribute for ena device rc: %d\n", rc);
3251                 goto err_admin_init;
3252         }
3253
3254         aenq_groups = BIT(ENA_ADMIN_LINK_CHANGE) |
3255             BIT(ENA_ADMIN_FATAL_ERROR) |
3256             BIT(ENA_ADMIN_WARNING) |
3257             BIT(ENA_ADMIN_NOTIFICATION) |
3258             BIT(ENA_ADMIN_KEEP_ALIVE);
3259
3260         aenq_groups &= get_feat_ctx->aenq.supported_groups;
3261         rc = ena_com_set_aenq_config(ena_dev, aenq_groups);
3262         if (unlikely(rc != 0)) {
3263                 device_printf(pdev, "Cannot configure aenq groups rc: %d\n", rc);
3264                 goto err_admin_init;
3265         }
3266
3267         *wd_active = !!(aenq_groups & BIT(ENA_ADMIN_KEEP_ALIVE));
3268
3269         return (0);
3270
3271 err_admin_init:
3272         ena_com_delete_host_info(ena_dev);
3273         ena_com_admin_destroy(ena_dev);
3274 err_mmio_read_less:
3275         ena_com_mmio_reg_read_request_destroy(ena_dev);
3276
3277         return (rc);
3278 }
3279
3280 static int ena_enable_msix_and_set_admin_interrupts(struct ena_adapter *adapter,
3281     int io_vectors)
3282 {
3283         struct ena_com_dev *ena_dev = adapter->ena_dev;
3284         int rc;
3285
3286         rc = ena_enable_msix(adapter);
3287         if (unlikely(rc != 0)) {
3288                 device_printf(adapter->pdev, "Error with MSI-X enablement\n");
3289                 return (rc);
3290         }
3291
3292         ena_setup_mgmnt_intr(adapter);
3293
3294         rc = ena_request_mgmnt_irq(adapter);
3295         if (unlikely(rc != 0)) {
3296                 device_printf(adapter->pdev, "Cannot setup mgmnt queue intr\n");
3297                 goto err_disable_msix;
3298         }
3299
3300         ena_com_set_admin_polling_mode(ena_dev, false);
3301
3302         ena_com_admin_aenq_enable(ena_dev);
3303
3304         return (0);
3305
3306 err_disable_msix:
3307         ena_disable_msix(adapter);
3308
3309         return (rc);
3310 }
3311
3312 /* Function called on ENA_ADMIN_KEEP_ALIVE event */
3313 static void ena_keep_alive_wd(void *adapter_data,
3314     struct ena_admin_aenq_entry *aenq_e)
3315 {
3316         struct ena_adapter *adapter = (struct ena_adapter *)adapter_data;
3317         struct ena_admin_aenq_keep_alive_desc *desc;
3318         sbintime_t stime;
3319         uint64_t rx_drops;
3320
3321         desc = (struct ena_admin_aenq_keep_alive_desc *)aenq_e;
3322
3323         rx_drops = ((uint64_t)desc->rx_drops_high << 32) | desc->rx_drops_low;
3324         counter_u64_zero(adapter->hw_stats.rx_drops);
3325         counter_u64_add(adapter->hw_stats.rx_drops, rx_drops);
3326
3327         stime = getsbinuptime();
3328         atomic_store_rel_64(&adapter->keep_alive_timestamp, stime);
3329 }
3330
3331 /* Check for keep alive expiration */
3332 static void check_for_missing_keep_alive(struct ena_adapter *adapter)
3333 {
3334         sbintime_t timestamp, time;
3335
3336         if (adapter->wd_active == 0)
3337                 return;
3338
3339         if (likely(adapter->keep_alive_timeout == 0))
3340                 return;
3341
3342         timestamp = atomic_load_acq_64(&adapter->keep_alive_timestamp);
3343         time = getsbinuptime() - timestamp;
3344         if (unlikely(time > adapter->keep_alive_timeout)) {
3345                 device_printf(adapter->pdev,
3346                     "Keep alive watchdog timeout.\n");
3347                 counter_u64_add(adapter->dev_stats.wd_expired, 1);
3348                 adapter->reset_reason = ENA_REGS_RESET_KEEP_ALIVE_TO;
3349                 adapter->trigger_reset = true;
3350         }
3351 }
3352
3353 /* Check if admin queue is enabled */
3354 static void check_for_admin_com_state(struct ena_adapter *adapter)
3355 {
3356         if (unlikely(ena_com_get_admin_running_state(adapter->ena_dev) ==
3357             false)) {
3358                 device_printf(adapter->pdev,
3359                     "ENA admin queue is not in running state!\n");
3360                 counter_u64_add(adapter->dev_stats.admin_q_pause, 1);
3361                 adapter->reset_reason = ENA_REGS_RESET_ADMIN_TO;
3362                 adapter->trigger_reset = true;
3363         }
3364 }
3365
3366 static int
3367 check_missing_comp_in_queue(struct ena_adapter *adapter,
3368     struct ena_ring *tx_ring)
3369 {
3370         struct bintime curtime, time;
3371         struct ena_tx_buffer *tx_buf;
3372         uint32_t missed_tx = 0;
3373         int i;
3374
3375         getbinuptime(&curtime);
3376
3377         for (i = 0; i < tx_ring->ring_size; i++) {
3378                 tx_buf = &tx_ring->tx_buffer_info[i];
3379
3380                 if (bintime_isset(&tx_buf->timestamp) == 0)
3381                         continue;
3382
3383                 time = curtime;
3384                 bintime_sub(&time, &tx_buf->timestamp);
3385
3386                 /* Check again if packet is still waiting */
3387                 if (unlikely(bttosbt(time) > adapter->missing_tx_timeout)) {
3388
3389                         if (!tx_buf->print_once)
3390                                 ena_trace(ENA_WARNING, "Found a Tx that wasn't "
3391                                     "completed on time, qid %d, index %d.\n",
3392                                     tx_ring->qid, i);
3393
3394                         tx_buf->print_once = true;
3395                         missed_tx++;
3396                         counter_u64_add(tx_ring->tx_stats.missing_tx_comp, 1);
3397
3398                         if (unlikely(missed_tx >
3399                             adapter->missing_tx_threshold)) {
3400                                 device_printf(adapter->pdev,
3401                                     "The number of lost tx completion "
3402                                     "is above the threshold (%d > %d). "
3403                                     "Reset the device\n",
3404                                     missed_tx, adapter->missing_tx_threshold);
3405                                 adapter->reset_reason =
3406                                     ENA_REGS_RESET_MISS_TX_CMPL;
3407                                 adapter->trigger_reset = true;
3408                                 return (EIO);
3409                         }
3410                 }
3411         }
3412
3413         return (0);
3414 }
3415
3416 /*
3417  * Check for TX which were not completed on time.
3418  * Timeout is defined by "missing_tx_timeout".
3419  * Reset will be performed if number of incompleted
3420  * transactions exceeds "missing_tx_threshold".
3421  */
3422 static void
3423 check_for_missing_tx_completions(struct ena_adapter *adapter)
3424 {
3425         struct ena_ring *tx_ring;
3426         int i, budget, rc;
3427
3428         /* Make sure the driver doesn't turn the device in other process */
3429         rmb();
3430
3431         if (!adapter->up)
3432                 return;
3433
3434         if (adapter->trigger_reset)
3435                 return;
3436
3437         if (adapter->missing_tx_timeout == 0)
3438                 return;
3439
3440         budget = adapter->missing_tx_max_queues;
3441
3442         for (i = adapter->next_monitored_tx_qid; i < adapter->num_queues; i++) {
3443                 tx_ring = &adapter->tx_ring[i];
3444
3445                 rc = check_missing_comp_in_queue(adapter, tx_ring);
3446                 if (unlikely(rc != 0))
3447                         return;
3448
3449                 budget--;
3450                 if (budget == 0) {
3451                         i++;
3452                         break;
3453                 }
3454         }
3455
3456         adapter->next_monitored_tx_qid = i % adapter->num_queues;
3457 }
3458
3459 /* trigger deferred rx cleanup after 2 consecutive detections */
3460 #define EMPTY_RX_REFILL 2
3461 /* For the rare case where the device runs out of Rx descriptors and the
3462  * msix handler failed to refill new Rx descriptors (due to a lack of memory
3463  * for example).
3464  * This case will lead to a deadlock:
3465  * The device won't send interrupts since all the new Rx packets will be dropped
3466  * The msix handler won't allocate new Rx descriptors so the device won't be
3467  * able to send new packets.
3468  *
3469  * When such a situation is detected - execute rx cleanup task in another thread
3470  */
3471 static void
3472 check_for_empty_rx_ring(struct ena_adapter *adapter)
3473 {
3474         struct ena_ring *rx_ring;
3475         int i, refill_required;
3476
3477         if (!adapter->up)
3478                 return;
3479
3480         if (adapter->trigger_reset)
3481                 return;
3482
3483         for (i = 0; i < adapter->num_queues; i++) {
3484                 rx_ring = &adapter->rx_ring[i];
3485
3486                 refill_required = ena_com_free_desc(rx_ring->ena_com_io_sq);
3487                 if (unlikely(refill_required == (rx_ring->ring_size - 1))) {
3488                         rx_ring->empty_rx_queue++;
3489
3490                         if (rx_ring->empty_rx_queue >= EMPTY_RX_REFILL) {
3491                                 counter_u64_add(rx_ring->rx_stats.empty_rx_ring,
3492                                     1);
3493
3494                                 device_printf(adapter->pdev,
3495                                     "trigger refill for ring %d\n", i);
3496
3497                                 taskqueue_enqueue(rx_ring->cmpl_tq,
3498                                     &rx_ring->cmpl_task);
3499                                 rx_ring->empty_rx_queue = 0;
3500                         }
3501                 } else {
3502                         rx_ring->empty_rx_queue = 0;
3503                 }
3504         }
3505 }
3506
3507 static void
3508 ena_timer_service(void *data)
3509 {
3510         struct ena_adapter *adapter = (struct ena_adapter *)data;
3511         struct ena_admin_host_info *host_info =
3512             adapter->ena_dev->host_attr.host_info;
3513
3514         check_for_missing_keep_alive(adapter);
3515
3516         check_for_admin_com_state(adapter);
3517
3518         check_for_missing_tx_completions(adapter);
3519
3520         check_for_empty_rx_ring(adapter);
3521
3522         if (host_info != NULL)
3523                 ena_update_host_info(host_info, adapter->ifp);
3524
3525         if (unlikely(adapter->trigger_reset)) {
3526                 device_printf(adapter->pdev, "Trigger reset is on\n");
3527                 taskqueue_enqueue(adapter->reset_tq, &adapter->reset_task);
3528                 return;
3529         }
3530
3531         /*
3532          * Schedule another timeout one second from now.
3533          */
3534         callout_schedule_sbt(&adapter->timer_service, SBT_1S, SBT_1S, 0);
3535 }
3536
3537 static void
3538 ena_reset_task(void *arg, int pending)
3539 {
3540         struct ena_com_dev_get_features_ctx get_feat_ctx;
3541         struct ena_adapter *adapter = (struct ena_adapter *)arg;
3542         struct ena_com_dev *ena_dev = adapter->ena_dev;
3543         bool dev_up;
3544         int rc;
3545
3546         if (unlikely(!adapter->trigger_reset)) {
3547                 device_printf(adapter->pdev,
3548                     "device reset scheduled but trigger_reset is off\n");
3549                 return;
3550         }
3551
3552         sx_xlock(&adapter->ioctl_sx);
3553
3554         callout_drain(&adapter->timer_service);
3555
3556         dev_up = adapter->up;
3557
3558         ena_com_set_admin_running_state(ena_dev, false);
3559         ena_down(adapter);
3560         ena_free_mgmnt_irq(adapter);
3561         ena_disable_msix(adapter);
3562         ena_com_abort_admin_commands(ena_dev);
3563         ena_com_wait_for_abort_completion(ena_dev);
3564         ena_com_admin_destroy(ena_dev);
3565         ena_com_mmio_reg_read_request_destroy(ena_dev);
3566
3567         adapter->reset_reason = ENA_REGS_RESET_NORMAL;
3568         adapter->trigger_reset = false;
3569
3570         /* Finished destroy part. Restart the device */
3571         rc = ena_device_init(adapter, adapter->pdev, &get_feat_ctx,
3572             &adapter->wd_active);
3573         if (unlikely(rc != 0)) {
3574                 device_printf(adapter->pdev,
3575                     "ENA device init failed! (err: %d)\n", rc);
3576                 goto err_dev_free;
3577         }
3578
3579         rc = ena_enable_msix_and_set_admin_interrupts(adapter,
3580             adapter->num_queues);
3581         if (unlikely(rc != 0)) {
3582                 device_printf(adapter->pdev, "Enable MSI-X failed\n");
3583                 goto err_com_free;
3584         }
3585
3586         /* If the interface was up before the reset bring it up */
3587         if (dev_up) {
3588                 rc = ena_up(adapter);
3589                 if (unlikely(rc != 0)) {
3590                         device_printf(adapter->pdev,
3591                             "Failed to create I/O queues\n");
3592                         goto err_msix_free;
3593                 }
3594         }
3595
3596         callout_reset_sbt(&adapter->timer_service, SBT_1S, SBT_1S,
3597             ena_timer_service, (void *)adapter, 0);
3598
3599         sx_unlock(&adapter->ioctl_sx);
3600
3601         return;
3602
3603 err_msix_free:
3604         ena_free_mgmnt_irq(adapter);
3605         ena_disable_msix(adapter);
3606 err_com_free:
3607         ena_com_admin_destroy(ena_dev);
3608 err_dev_free:
3609         device_printf(adapter->pdev, "ENA reset failed!\n");
3610         adapter->running = false;
3611         sx_unlock(&adapter->ioctl_sx);
3612 }
3613
3614 /**
3615  * ena_attach - Device Initialization Routine
3616  * @pdev: device information struct
3617  *
3618  * Returns 0 on success, otherwise on failure.
3619  *
3620  * ena_attach initializes an adapter identified by a device structure.
3621  * The OS initialization, configuring of the adapter private structure,
3622  * and a hardware reset occur.
3623  **/
3624 static int
3625 ena_attach(device_t pdev)
3626 {
3627         struct ena_com_dev_get_features_ctx get_feat_ctx;
3628         static int version_printed;
3629         struct ena_adapter *adapter;
3630         struct ena_com_dev *ena_dev = NULL;
3631         uint16_t tx_sgl_size = 0;
3632         uint16_t rx_sgl_size = 0;
3633         int io_queue_num;
3634         int queue_size;
3635         int rc;
3636         adapter = device_get_softc(pdev);
3637         adapter->pdev = pdev;
3638
3639         mtx_init(&adapter->global_mtx, "ENA global mtx", NULL, MTX_DEF);
3640         sx_init(&adapter->ioctl_sx, "ENA ioctl sx");
3641
3642         /* Set up the timer service */
3643         callout_init_mtx(&adapter->timer_service, &adapter->global_mtx, 0);
3644         adapter->keep_alive_timeout = DEFAULT_KEEP_ALIVE_TO;
3645         adapter->missing_tx_timeout = DEFAULT_TX_CMP_TO;
3646         adapter->missing_tx_max_queues = DEFAULT_TX_MONITORED_QUEUES;
3647         adapter->missing_tx_threshold = DEFAULT_TX_CMP_THRESHOLD;
3648
3649         if (version_printed++ == 0)
3650                 device_printf(pdev, "%s\n", ena_version);
3651
3652         rc = ena_allocate_pci_resources(adapter);
3653         if (unlikely(rc != 0)) {
3654                 device_printf(pdev, "PCI resource allocation failed!\n");
3655                 ena_free_pci_resources(adapter);
3656                 return (rc);
3657         }
3658
3659         /* Allocate memory for ena_dev structure */
3660         ena_dev = malloc(sizeof(struct ena_com_dev), M_DEVBUF,
3661             M_WAITOK | M_ZERO);
3662
3663         adapter->ena_dev = ena_dev;
3664         ena_dev->dmadev = pdev;
3665         ena_dev->bus = malloc(sizeof(struct ena_bus), M_DEVBUF,
3666             M_WAITOK | M_ZERO);
3667
3668         /* Store register resources */
3669         ((struct ena_bus*)(ena_dev->bus))->reg_bar_t =
3670             rman_get_bustag(adapter->registers);
3671         ((struct ena_bus*)(ena_dev->bus))->reg_bar_h =
3672             rman_get_bushandle(adapter->registers);
3673
3674         if (unlikely(((struct ena_bus*)(ena_dev->bus))->reg_bar_h == 0)) {
3675                 device_printf(pdev, "failed to pmap registers bar\n");
3676                 rc = ENXIO;
3677                 goto err_bus_free;
3678         }
3679
3680         ena_dev->tx_mem_queue_type = ENA_ADMIN_PLACEMENT_POLICY_HOST;
3681
3682         /* Device initialization */
3683         rc = ena_device_init(adapter, pdev, &get_feat_ctx, &adapter->wd_active);
3684         if (unlikely(rc != 0)) {
3685                 device_printf(pdev, "ENA device init failed! (err: %d)\n", rc);
3686                 rc = ENXIO;
3687                 goto err_bus_free;
3688         }
3689
3690         adapter->keep_alive_timestamp = getsbinuptime();
3691
3692         adapter->tx_offload_cap = get_feat_ctx.offload.tx;
3693
3694         /* Set for sure that interface is not up */
3695         adapter->up = false;
3696
3697         memcpy(adapter->mac_addr, get_feat_ctx.dev_attr.mac_addr,
3698             ETHER_ADDR_LEN);
3699
3700         /* calculate IO queue number to create */
3701         io_queue_num = ena_calc_io_queue_num(adapter, &get_feat_ctx);
3702
3703         ENA_ASSERT(io_queue_num > 0, "Invalid queue number: %d\n",
3704             io_queue_num);
3705         adapter->num_queues = io_queue_num;
3706
3707         /* calculatre ring sizes */
3708         queue_size = ena_calc_queue_size(adapter,&tx_sgl_size,
3709             &rx_sgl_size, &get_feat_ctx);
3710         if (unlikely((queue_size <= 0) || (io_queue_num <= 0))) {
3711                 rc = ENA_COM_FAULT;
3712                 goto err_com_free;
3713         }
3714
3715         adapter->reset_reason = ENA_REGS_RESET_NORMAL;
3716
3717         adapter->tx_ring_size = queue_size;
3718         adapter->rx_ring_size = queue_size;
3719
3720         adapter->max_tx_sgl_size = tx_sgl_size;
3721         adapter->max_rx_sgl_size = rx_sgl_size;
3722
3723         /* set up dma tags for rx and tx buffers */
3724         rc = ena_setup_tx_dma_tag(adapter);
3725         if (unlikely(rc != 0)) {
3726                 device_printf(pdev, "Failed to create TX DMA tag\n");
3727                 goto err_com_free;
3728         }
3729
3730         rc = ena_setup_rx_dma_tag(adapter);
3731         if (unlikely(rc != 0)) {
3732                 device_printf(pdev, "Failed to create RX DMA tag\n");
3733                 goto err_tx_tag_free;
3734         }
3735
3736         /* initialize rings basic information */
3737         device_printf(pdev, "initalize %d io queues\n", io_queue_num);
3738         ena_init_io_rings(adapter);
3739
3740         /* setup network interface */
3741         rc = ena_setup_ifnet(pdev, adapter, &get_feat_ctx);
3742         if (unlikely(rc != 0)) {
3743                 device_printf(pdev, "Error with network interface setup\n");
3744                 goto err_io_free;
3745         }
3746
3747         rc = ena_enable_msix_and_set_admin_interrupts(adapter, io_queue_num);
3748         if (unlikely(rc != 0)) {
3749                 device_printf(pdev,
3750                     "Failed to enable and set the admin interrupts\n");
3751                 goto err_ifp_free;
3752         }
3753
3754         /* Initialize reset task queue */
3755         TASK_INIT(&adapter->reset_task, 0, ena_reset_task, adapter);
3756         adapter->reset_tq = taskqueue_create("ena_reset_enqueue",
3757             M_WAITOK | M_ZERO, taskqueue_thread_enqueue, &adapter->reset_tq);
3758         taskqueue_start_threads(&adapter->reset_tq, 1, PI_NET,
3759             "%s rstq", device_get_nameunit(adapter->pdev));
3760
3761         /* Initialize statistics */
3762         ena_alloc_counters((counter_u64_t *)&adapter->dev_stats,
3763             sizeof(struct ena_stats_dev));
3764         ena_alloc_counters((counter_u64_t *)&adapter->hw_stats,
3765             sizeof(struct ena_hw_stats));
3766         ena_sysctl_add_nodes(adapter);
3767
3768         /* Tell the stack that the interface is not active */
3769         if_setdrvflagbits(adapter->ifp, IFF_DRV_OACTIVE, IFF_DRV_RUNNING);
3770
3771         adapter->running = true;
3772         return (0);
3773
3774 err_ifp_free:
3775         if_detach(adapter->ifp);
3776         if_free(adapter->ifp);
3777 err_io_free:
3778         ena_free_all_io_rings_resources(adapter);
3779         ena_free_rx_dma_tag(adapter);
3780 err_tx_tag_free:
3781         ena_free_tx_dma_tag(adapter);
3782 err_com_free:
3783         ena_com_admin_destroy(ena_dev);
3784         ena_com_delete_host_info(ena_dev);
3785         ena_com_mmio_reg_read_request_destroy(ena_dev);
3786 err_bus_free:
3787         free(ena_dev->bus, M_DEVBUF);
3788         free(ena_dev, M_DEVBUF);
3789         ena_free_pci_resources(adapter);
3790
3791         return (rc);
3792 }
3793
3794 /**
3795  * ena_detach - Device Removal Routine
3796  * @pdev: device information struct
3797  *
3798  * ena_detach is called by the device subsystem to alert the driver
3799  * that it should release a PCI device.
3800  **/
3801 static int
3802 ena_detach(device_t pdev)
3803 {
3804         struct ena_adapter *adapter = device_get_softc(pdev);
3805         struct ena_com_dev *ena_dev = adapter->ena_dev;
3806         int rc;
3807
3808         /* Make sure VLANS are not using driver */
3809         if (adapter->ifp->if_vlantrunk != NULL) {
3810                 device_printf(adapter->pdev ,"VLAN is in use, detach first\n");
3811                 return (EBUSY);
3812         }
3813
3814         /* Free reset task and callout */
3815         callout_drain(&adapter->timer_service);
3816         while (taskqueue_cancel(adapter->reset_tq, &adapter->reset_task, NULL))
3817                 taskqueue_drain(adapter->reset_tq, &adapter->reset_task);
3818         taskqueue_free(adapter->reset_tq);
3819
3820         sx_xlock(&adapter->ioctl_sx);
3821         ena_down(adapter);
3822         sx_unlock(&adapter->ioctl_sx);
3823
3824         if (adapter->ifp != NULL) {
3825                 ether_ifdetach(adapter->ifp);
3826                 if_free(adapter->ifp);
3827         }
3828
3829         ena_free_all_io_rings_resources(adapter);
3830
3831         ena_free_counters((counter_u64_t *)&adapter->hw_stats,
3832             sizeof(struct ena_hw_stats));
3833         ena_free_counters((counter_u64_t *)&adapter->dev_stats,
3834             sizeof(struct ena_stats_dev));
3835
3836         if (likely(adapter->rss_support))
3837                 ena_com_rss_destroy(ena_dev);
3838
3839         rc = ena_free_rx_dma_tag(adapter);
3840         if (unlikely(rc != 0))
3841                 device_printf(adapter->pdev,
3842                     "Unmapped RX DMA tag associations\n");
3843
3844         rc = ena_free_tx_dma_tag(adapter);
3845         if (unlikely(rc != 0))
3846                 device_printf(adapter->pdev,
3847                     "Unmapped TX DMA tag associations\n");
3848
3849         /* Reset the device only if the device is running. */
3850         if (adapter->running)
3851                 ena_com_dev_reset(ena_dev, adapter->reset_reason);
3852
3853         ena_com_delete_host_info(ena_dev);
3854
3855         ena_free_irqs(adapter);
3856
3857         ena_com_abort_admin_commands(ena_dev);
3858
3859         ena_com_wait_for_abort_completion(ena_dev);
3860
3861         ena_com_admin_destroy(ena_dev);
3862
3863         ena_com_mmio_reg_read_request_destroy(ena_dev);
3864
3865         ena_free_pci_resources(adapter);
3866
3867         mtx_destroy(&adapter->global_mtx);
3868         sx_destroy(&adapter->ioctl_sx);
3869
3870         if (ena_dev->bus != NULL)
3871                 free(ena_dev->bus, M_DEVBUF);
3872
3873         if (ena_dev != NULL)
3874                 free(ena_dev, M_DEVBUF);
3875
3876         return (bus_generic_detach(pdev));
3877 }
3878
3879 /******************************************************************************
3880  ******************************** AENQ Handlers *******************************
3881  *****************************************************************************/
3882 /**
3883  * ena_update_on_link_change:
3884  * Notify the network interface about the change in link status
3885  **/
3886 static void
3887 ena_update_on_link_change(void *adapter_data,
3888     struct ena_admin_aenq_entry *aenq_e)
3889 {
3890         struct ena_adapter *adapter = (struct ena_adapter *)adapter_data;
3891         struct ena_admin_aenq_link_change_desc *aenq_desc;
3892         int status;
3893         if_t ifp;
3894
3895         aenq_desc = (struct ena_admin_aenq_link_change_desc *)aenq_e;
3896         ifp = adapter->ifp;
3897         status = aenq_desc->flags &
3898             ENA_ADMIN_AENQ_LINK_CHANGE_DESC_LINK_STATUS_MASK;
3899
3900         if (status != 0) {
3901                 device_printf(adapter->pdev, "link is UP\n");
3902                 if_link_state_change(ifp, LINK_STATE_UP);
3903         } else if (status == 0) {
3904                 device_printf(adapter->pdev, "link is DOWN\n");
3905                 if_link_state_change(ifp, LINK_STATE_DOWN);
3906         } else {
3907                 device_printf(adapter->pdev, "invalid value recvd\n");
3908                 BUG();
3909         }
3910
3911         adapter->link_status = status;
3912 }
3913
3914 /**
3915  * This handler will called for unknown event group or unimplemented handlers
3916  **/
3917 static void
3918 unimplemented_aenq_handler(void *data,
3919     struct ena_admin_aenq_entry *aenq_e)
3920 {
3921         return;
3922 }
3923
3924 static struct ena_aenq_handlers aenq_handlers = {
3925     .handlers = {
3926             [ENA_ADMIN_LINK_CHANGE] = ena_update_on_link_change,
3927             [ENA_ADMIN_KEEP_ALIVE] = ena_keep_alive_wd,
3928     },
3929     .unimplemented_handler = unimplemented_aenq_handler
3930 };
3931
3932 /*********************************************************************
3933  *  FreeBSD Device Interface Entry Points
3934  *********************************************************************/
3935
3936 static device_method_t ena_methods[] = {
3937     /* Device interface */
3938     DEVMETHOD(device_probe, ena_probe),
3939     DEVMETHOD(device_attach, ena_attach),
3940     DEVMETHOD(device_detach, ena_detach),
3941     DEVMETHOD_END
3942 };
3943
3944 static driver_t ena_driver = {
3945     "ena", ena_methods, sizeof(struct ena_adapter),
3946 };
3947
3948 devclass_t ena_devclass;
3949 DRIVER_MODULE(ena, pci, ena_driver, ena_devclass, 0, 0);
3950 MODULE_DEPEND(ena, pci, 1, 1, 1);
3951 MODULE_DEPEND(ena, ether, 1, 1, 1);
3952
3953 /*********************************************************************/