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