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