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