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