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