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