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