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