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