xref: /linux/drivers/net/ethernet/amazon/ena/ena_netdev.c (revision 1cc3462159babb69c84c39cb1b4e262aef3ea325)
1 // SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB
2 /*
3  * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All rights reserved.
4  */
5 
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 
8 #include <linux/ethtool.h>
9 #include <linux/kernel.h>
10 #include <linux/module.h>
11 #include <linux/numa.h>
12 #include <linux/pci.h>
13 #include <linux/utsname.h>
14 #include <linux/version.h>
15 #include <linux/vmalloc.h>
16 #include <net/ip.h>
17 
18 #include "ena_netdev.h"
19 #include "ena_pci_id_tbl.h"
20 #include "ena_xdp.h"
21 
22 MODULE_AUTHOR("Amazon.com, Inc. or its affiliates");
23 MODULE_DESCRIPTION(DEVICE_NAME);
24 MODULE_LICENSE("GPL");
25 
26 /* Time in jiffies before concluding the transmitter is hung. */
27 #define TX_TIMEOUT  (5 * HZ)
28 
29 #define ENA_MAX_RINGS min_t(unsigned int, ENA_MAX_NUM_IO_QUEUES, num_possible_cpus())
30 
31 #define DEFAULT_MSG_ENABLE (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_IFUP | \
32 		NETIF_MSG_IFDOWN | NETIF_MSG_TX_ERR | NETIF_MSG_RX_ERR)
33 
34 static struct ena_aenq_handlers aenq_handlers;
35 
36 static struct workqueue_struct *ena_wq;
37 
38 MODULE_DEVICE_TABLE(pci, ena_pci_tbl);
39 
40 static int ena_rss_init_default(struct ena_adapter *adapter);
41 static void check_for_admin_com_state(struct ena_adapter *adapter);
42 static int ena_destroy_device(struct ena_adapter *adapter, bool graceful);
43 static int ena_restore_device(struct ena_adapter *adapter);
44 
45 static void ena_tx_timeout(struct net_device *dev, unsigned int txqueue)
46 {
47 	enum ena_regs_reset_reason_types reset_reason = ENA_REGS_RESET_OS_NETDEV_WD;
48 	struct ena_adapter *adapter = netdev_priv(dev);
49 	unsigned int time_since_last_napi, threshold;
50 	struct ena_ring *tx_ring;
51 	int napi_scheduled;
52 
53 	if (txqueue >= adapter->num_io_queues) {
54 		netdev_err(dev, "TX timeout on invalid queue %u\n", txqueue);
55 		goto schedule_reset;
56 	}
57 
58 	threshold = jiffies_to_usecs(dev->watchdog_timeo);
59 	tx_ring = &adapter->tx_ring[txqueue];
60 
61 	time_since_last_napi = jiffies_to_usecs(jiffies - tx_ring->tx_stats.last_napi_jiffies);
62 	napi_scheduled = !!(tx_ring->napi->state & NAPIF_STATE_SCHED);
63 
64 	netdev_err(dev,
65 		   "TX q %d is paused for too long (threshold %u). Time since last napi %u usec. napi scheduled: %d\n",
66 		   txqueue,
67 		   threshold,
68 		   time_since_last_napi,
69 		   napi_scheduled);
70 
71 	if (threshold < time_since_last_napi && napi_scheduled) {
72 		netdev_err(dev,
73 			   "napi handler hasn't been called for a long time but is scheduled\n");
74 		reset_reason = ENA_REGS_RESET_SUSPECTED_POLL_STARVATION;
75 	}
76 schedule_reset:
77 	/* Change the state of the device to trigger reset
78 	 * Check that we are not in the middle or a trigger already
79 	 */
80 	if (test_and_set_bit(ENA_FLAG_TRIGGER_RESET, &adapter->flags))
81 		return;
82 
83 	ena_reset_device(adapter, reset_reason);
84 	ena_increase_stat(&adapter->dev_stats.tx_timeout, 1, &adapter->syncp);
85 }
86 
87 static void update_rx_ring_mtu(struct ena_adapter *adapter, int mtu)
88 {
89 	int i;
90 
91 	for (i = 0; i < adapter->num_io_queues; i++)
92 		adapter->rx_ring[i].mtu = mtu;
93 }
94 
95 static int ena_change_mtu(struct net_device *dev, int new_mtu)
96 {
97 	struct ena_adapter *adapter = netdev_priv(dev);
98 	int ret;
99 
100 	ret = ena_com_set_dev_mtu(adapter->ena_dev, new_mtu);
101 	if (!ret) {
102 		netif_dbg(adapter, drv, dev, "Set MTU to %d\n", new_mtu);
103 		update_rx_ring_mtu(adapter, new_mtu);
104 		WRITE_ONCE(dev->mtu, new_mtu);
105 	} else {
106 		netif_err(adapter, drv, dev, "Failed to set MTU to %d\n",
107 			  new_mtu);
108 	}
109 
110 	return ret;
111 }
112 
113 int ena_xmit_common(struct ena_adapter *adapter,
114 		    struct ena_ring *ring,
115 		    struct ena_tx_buffer *tx_info,
116 		    struct ena_com_tx_ctx *ena_tx_ctx,
117 		    u16 next_to_use,
118 		    u32 bytes)
119 {
120 	int rc, nb_hw_desc;
121 
122 	if (unlikely(ena_com_is_doorbell_needed(ring->ena_com_io_sq,
123 						ena_tx_ctx))) {
124 		netif_dbg(adapter, tx_queued, adapter->netdev,
125 			  "llq tx max burst size of queue %d achieved, writing doorbell to send burst\n",
126 			  ring->qid);
127 		ena_ring_tx_doorbell(ring);
128 	}
129 
130 	/* prepare the packet's descriptors to dma engine */
131 	rc = ena_com_prepare_tx(ring->ena_com_io_sq, ena_tx_ctx,
132 				&nb_hw_desc);
133 
134 	/* In case there isn't enough space in the queue for the packet,
135 	 * we simply drop it. All other failure reasons of
136 	 * ena_com_prepare_tx() are fatal and therefore require a device reset.
137 	 */
138 	if (unlikely(rc)) {
139 		netif_err(adapter, tx_queued, adapter->netdev,
140 			  "Failed to prepare tx bufs\n");
141 		ena_increase_stat(&ring->tx_stats.prepare_ctx_err, 1, &ring->syncp);
142 		if (rc != -ENOMEM)
143 			ena_reset_device(adapter, ENA_REGS_RESET_DRIVER_INVALID_STATE);
144 		return rc;
145 	}
146 
147 	u64_stats_update_begin(&ring->syncp);
148 	ring->tx_stats.cnt++;
149 	ring->tx_stats.bytes += bytes;
150 	u64_stats_update_end(&ring->syncp);
151 
152 	tx_info->tx_descs = nb_hw_desc;
153 	tx_info->total_tx_size = bytes;
154 	tx_info->last_jiffies = jiffies;
155 	tx_info->print_once = 0;
156 
157 	ring->next_to_use = ENA_TX_RING_IDX_NEXT(next_to_use,
158 						 ring->ring_size);
159 	return 0;
160 }
161 
162 static void ena_init_io_rings_common(struct ena_adapter *adapter,
163 				     struct ena_ring *ring, u16 qid)
164 {
165 	ring->qid = qid;
166 	ring->pdev = adapter->pdev;
167 	ring->dev = &adapter->pdev->dev;
168 	ring->netdev = adapter->netdev;
169 	ring->napi = &adapter->ena_napi[qid].napi;
170 	ring->adapter = adapter;
171 	ring->ena_dev = adapter->ena_dev;
172 	ring->per_napi_packets = 0;
173 	ring->cpu = 0;
174 	ring->numa_node = 0;
175 	ring->no_interrupt_event_cnt = 0;
176 	u64_stats_init(&ring->syncp);
177 }
178 
179 void ena_init_io_rings(struct ena_adapter *adapter,
180 		       int first_index, int count)
181 {
182 	struct ena_com_dev *ena_dev;
183 	struct ena_ring *txr, *rxr;
184 	int i;
185 
186 	ena_dev = adapter->ena_dev;
187 
188 	for (i = first_index; i < first_index + count; i++) {
189 		txr = &adapter->tx_ring[i];
190 		rxr = &adapter->rx_ring[i];
191 
192 		/* TX common ring state */
193 		ena_init_io_rings_common(adapter, txr, i);
194 
195 		/* TX specific ring state */
196 		txr->ring_size = adapter->requested_tx_ring_size;
197 		txr->tx_max_header_size = ena_dev->tx_max_header_size;
198 		txr->tx_mem_queue_type = ena_dev->tx_mem_queue_type;
199 		txr->sgl_size = adapter->max_tx_sgl_size;
200 		txr->smoothed_interval =
201 			ena_com_get_nonadaptive_moderation_interval_tx(ena_dev);
202 		txr->disable_meta_caching = adapter->disable_meta_caching;
203 		spin_lock_init(&txr->xdp_tx_lock);
204 
205 		/* Don't init RX queues for xdp queues */
206 		if (!ENA_IS_XDP_INDEX(adapter, i)) {
207 			/* RX common ring state */
208 			ena_init_io_rings_common(adapter, rxr, i);
209 
210 			/* RX specific ring state */
211 			rxr->ring_size = adapter->requested_rx_ring_size;
212 			rxr->rx_copybreak = adapter->rx_copybreak;
213 			rxr->sgl_size = adapter->max_rx_sgl_size;
214 			rxr->smoothed_interval =
215 				ena_com_get_nonadaptive_moderation_interval_rx(ena_dev);
216 			rxr->empty_rx_queue = 0;
217 			rxr->rx_headroom = NET_SKB_PAD;
218 			adapter->ena_napi[i].dim.mode = DIM_CQ_PERIOD_MODE_START_FROM_EQE;
219 			rxr->xdp_ring = &adapter->tx_ring[i + adapter->num_io_queues];
220 		}
221 	}
222 }
223 
224 /* ena_setup_tx_resources - allocate I/O Tx resources (Descriptors)
225  * @adapter: network interface device structure
226  * @qid: queue index
227  *
228  * Return 0 on success, negative on failure
229  */
230 static int ena_setup_tx_resources(struct ena_adapter *adapter, int qid)
231 {
232 	struct ena_ring *tx_ring = &adapter->tx_ring[qid];
233 	struct ena_irq *ena_irq = &adapter->irq_tbl[ENA_IO_IRQ_IDX(qid)];
234 	int size, i, node;
235 
236 	if (tx_ring->tx_buffer_info) {
237 		netif_err(adapter, ifup,
238 			  adapter->netdev, "tx_buffer_info info is not NULL");
239 		return -EEXIST;
240 	}
241 
242 	size = sizeof(struct ena_tx_buffer) * tx_ring->ring_size;
243 	node = cpu_to_node(ena_irq->cpu);
244 
245 	tx_ring->tx_buffer_info = vzalloc_node(size, node);
246 	if (!tx_ring->tx_buffer_info) {
247 		tx_ring->tx_buffer_info = vzalloc(size);
248 		if (!tx_ring->tx_buffer_info)
249 			goto err_tx_buffer_info;
250 	}
251 
252 	size = sizeof(u16) * tx_ring->ring_size;
253 	tx_ring->free_ids = vzalloc_node(size, node);
254 	if (!tx_ring->free_ids) {
255 		tx_ring->free_ids = vzalloc(size);
256 		if (!tx_ring->free_ids)
257 			goto err_tx_free_ids;
258 	}
259 
260 	size = tx_ring->tx_max_header_size;
261 	tx_ring->push_buf_intermediate_buf = vzalloc_node(size, node);
262 	if (!tx_ring->push_buf_intermediate_buf) {
263 		tx_ring->push_buf_intermediate_buf = vzalloc(size);
264 		if (!tx_ring->push_buf_intermediate_buf)
265 			goto err_push_buf_intermediate_buf;
266 	}
267 
268 	/* Req id ring for TX out of order completions */
269 	for (i = 0; i < tx_ring->ring_size; i++)
270 		tx_ring->free_ids[i] = i;
271 
272 	/* Reset tx statistics */
273 	memset(&tx_ring->tx_stats, 0x0, sizeof(tx_ring->tx_stats));
274 
275 	tx_ring->next_to_use = 0;
276 	tx_ring->next_to_clean = 0;
277 	tx_ring->cpu = ena_irq->cpu;
278 	tx_ring->numa_node = node;
279 	return 0;
280 
281 err_push_buf_intermediate_buf:
282 	vfree(tx_ring->free_ids);
283 	tx_ring->free_ids = NULL;
284 err_tx_free_ids:
285 	vfree(tx_ring->tx_buffer_info);
286 	tx_ring->tx_buffer_info = NULL;
287 err_tx_buffer_info:
288 	return -ENOMEM;
289 }
290 
291 /* ena_free_tx_resources - Free I/O Tx Resources per Queue
292  * @adapter: network interface device structure
293  * @qid: queue index
294  *
295  * Free all transmit software resources
296  */
297 static void ena_free_tx_resources(struct ena_adapter *adapter, int qid)
298 {
299 	struct ena_ring *tx_ring = &adapter->tx_ring[qid];
300 
301 	vfree(tx_ring->tx_buffer_info);
302 	tx_ring->tx_buffer_info = NULL;
303 
304 	vfree(tx_ring->free_ids);
305 	tx_ring->free_ids = NULL;
306 
307 	vfree(tx_ring->push_buf_intermediate_buf);
308 	tx_ring->push_buf_intermediate_buf = NULL;
309 }
310 
311 int ena_setup_tx_resources_in_range(struct ena_adapter *adapter,
312 				    int first_index, int count)
313 {
314 	int i, rc = 0;
315 
316 	for (i = first_index; i < first_index + count; i++) {
317 		rc = ena_setup_tx_resources(adapter, i);
318 		if (rc)
319 			goto err_setup_tx;
320 	}
321 
322 	return 0;
323 
324 err_setup_tx:
325 
326 	netif_err(adapter, ifup, adapter->netdev,
327 		  "Tx queue %d: allocation failed\n", i);
328 
329 	/* rewind the index freeing the rings as we go */
330 	while (first_index < i--)
331 		ena_free_tx_resources(adapter, i);
332 	return rc;
333 }
334 
335 void ena_free_all_io_tx_resources_in_range(struct ena_adapter *adapter,
336 					   int first_index, int count)
337 {
338 	int i;
339 
340 	for (i = first_index; i < first_index + count; i++)
341 		ena_free_tx_resources(adapter, i);
342 }
343 
344 /* ena_free_all_io_tx_resources - Free I/O Tx Resources for All Queues
345  * @adapter: board private structure
346  *
347  * Free all transmit software resources
348  */
349 void ena_free_all_io_tx_resources(struct ena_adapter *adapter)
350 {
351 	ena_free_all_io_tx_resources_in_range(adapter,
352 					      0,
353 					      adapter->xdp_num_queues +
354 					      adapter->num_io_queues);
355 }
356 
357 /* ena_setup_rx_resources - allocate I/O Rx resources (Descriptors)
358  * @adapter: network interface device structure
359  * @qid: queue index
360  *
361  * Returns 0 on success, negative on failure
362  */
363 static int ena_setup_rx_resources(struct ena_adapter *adapter,
364 				  u32 qid)
365 {
366 	struct ena_ring *rx_ring = &adapter->rx_ring[qid];
367 	struct ena_irq *ena_irq = &adapter->irq_tbl[ENA_IO_IRQ_IDX(qid)];
368 	int size, node, i;
369 
370 	if (rx_ring->rx_buffer_info) {
371 		netif_err(adapter, ifup, adapter->netdev,
372 			  "rx_buffer_info is not NULL");
373 		return -EEXIST;
374 	}
375 
376 	/* alloc extra element so in rx path
377 	 * we can always prefetch rx_info + 1
378 	 */
379 	size = sizeof(struct ena_rx_buffer) * (rx_ring->ring_size + 1);
380 	node = cpu_to_node(ena_irq->cpu);
381 
382 	rx_ring->rx_buffer_info = vzalloc_node(size, node);
383 	if (!rx_ring->rx_buffer_info) {
384 		rx_ring->rx_buffer_info = vzalloc(size);
385 		if (!rx_ring->rx_buffer_info)
386 			return -ENOMEM;
387 	}
388 
389 	size = sizeof(u16) * rx_ring->ring_size;
390 	rx_ring->free_ids = vzalloc_node(size, node);
391 	if (!rx_ring->free_ids) {
392 		rx_ring->free_ids = vzalloc(size);
393 		if (!rx_ring->free_ids) {
394 			vfree(rx_ring->rx_buffer_info);
395 			rx_ring->rx_buffer_info = NULL;
396 			return -ENOMEM;
397 		}
398 	}
399 
400 	/* Req id ring for receiving RX pkts out of order */
401 	for (i = 0; i < rx_ring->ring_size; i++)
402 		rx_ring->free_ids[i] = i;
403 
404 	/* Reset rx statistics */
405 	memset(&rx_ring->rx_stats, 0x0, sizeof(rx_ring->rx_stats));
406 
407 	rx_ring->next_to_clean = 0;
408 	rx_ring->next_to_use = 0;
409 	rx_ring->cpu = ena_irq->cpu;
410 	rx_ring->numa_node = node;
411 
412 	return 0;
413 }
414 
415 /* ena_free_rx_resources - Free I/O Rx Resources
416  * @adapter: network interface device structure
417  * @qid: queue index
418  *
419  * Free all receive software resources
420  */
421 static void ena_free_rx_resources(struct ena_adapter *adapter,
422 				  u32 qid)
423 {
424 	struct ena_ring *rx_ring = &adapter->rx_ring[qid];
425 
426 	vfree(rx_ring->rx_buffer_info);
427 	rx_ring->rx_buffer_info = NULL;
428 
429 	vfree(rx_ring->free_ids);
430 	rx_ring->free_ids = NULL;
431 }
432 
433 /* ena_setup_all_rx_resources - allocate I/O Rx queues resources for all queues
434  * @adapter: board private structure
435  *
436  * Return 0 on success, negative on failure
437  */
438 static int ena_setup_all_rx_resources(struct ena_adapter *adapter)
439 {
440 	int i, rc = 0;
441 
442 	for (i = 0; i < adapter->num_io_queues; i++) {
443 		rc = ena_setup_rx_resources(adapter, i);
444 		if (rc)
445 			goto err_setup_rx;
446 	}
447 
448 	return 0;
449 
450 err_setup_rx:
451 
452 	netif_err(adapter, ifup, adapter->netdev,
453 		  "Rx queue %d: allocation failed\n", i);
454 
455 	/* rewind the index freeing the rings as we go */
456 	while (i--)
457 		ena_free_rx_resources(adapter, i);
458 	return rc;
459 }
460 
461 /* ena_free_all_io_rx_resources - Free I/O Rx Resources for All Queues
462  * @adapter: board private structure
463  *
464  * Free all receive software resources
465  */
466 static void ena_free_all_io_rx_resources(struct ena_adapter *adapter)
467 {
468 	int i;
469 
470 	for (i = 0; i < adapter->num_io_queues; i++)
471 		ena_free_rx_resources(adapter, i);
472 }
473 
474 static struct page *ena_alloc_map_page(struct ena_ring *rx_ring,
475 				       dma_addr_t *dma)
476 {
477 	struct page *page;
478 
479 	/* This would allocate the page on the same NUMA node the executing code
480 	 * is running on.
481 	 */
482 	page = dev_alloc_page();
483 	if (!page) {
484 		ena_increase_stat(&rx_ring->rx_stats.page_alloc_fail, 1, &rx_ring->syncp);
485 		return ERR_PTR(-ENOSPC);
486 	}
487 
488 	/* To enable NIC-side port-mirroring, AKA SPAN port,
489 	 * we make the buffer readable from the nic as well
490 	 */
491 	*dma = dma_map_page(rx_ring->dev, page, 0, ENA_PAGE_SIZE,
492 			    DMA_BIDIRECTIONAL);
493 	if (unlikely(dma_mapping_error(rx_ring->dev, *dma))) {
494 		ena_increase_stat(&rx_ring->rx_stats.dma_mapping_err, 1,
495 				  &rx_ring->syncp);
496 		__free_page(page);
497 		return ERR_PTR(-EIO);
498 	}
499 
500 	return page;
501 }
502 
503 static int ena_alloc_rx_buffer(struct ena_ring *rx_ring,
504 			       struct ena_rx_buffer *rx_info)
505 {
506 	int headroom = rx_ring->rx_headroom;
507 	struct ena_com_buf *ena_buf;
508 	struct page *page;
509 	dma_addr_t dma;
510 	int tailroom;
511 
512 	/* restore page offset value in case it has been changed by device */
513 	rx_info->buf_offset = headroom;
514 
515 	/* if previous allocated page is not used */
516 	if (unlikely(rx_info->page))
517 		return 0;
518 
519 	/* We handle DMA here */
520 	page = ena_alloc_map_page(rx_ring, &dma);
521 	if (IS_ERR(page))
522 		return PTR_ERR(page);
523 
524 	netif_dbg(rx_ring->adapter, rx_status, rx_ring->netdev,
525 		  "Allocate page %p, rx_info %p\n", page, rx_info);
526 
527 	tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
528 
529 	rx_info->page = page;
530 	rx_info->dma_addr = dma;
531 	rx_info->page_offset = 0;
532 	ena_buf = &rx_info->ena_buf;
533 	ena_buf->paddr = dma + headroom;
534 	ena_buf->len = ENA_PAGE_SIZE - headroom - tailroom;
535 
536 	return 0;
537 }
538 
539 static void ena_unmap_rx_buff_attrs(struct ena_ring *rx_ring,
540 				    struct ena_rx_buffer *rx_info,
541 				    unsigned long attrs)
542 {
543 	dma_unmap_page_attrs(rx_ring->dev, rx_info->dma_addr, ENA_PAGE_SIZE, DMA_BIDIRECTIONAL,
544 			     attrs);
545 }
546 
547 static void ena_free_rx_page(struct ena_ring *rx_ring,
548 			     struct ena_rx_buffer *rx_info)
549 {
550 	struct page *page = rx_info->page;
551 
552 	if (unlikely(!page)) {
553 		netif_warn(rx_ring->adapter, rx_err, rx_ring->netdev,
554 			   "Trying to free unallocated buffer\n");
555 		return;
556 	}
557 
558 	ena_unmap_rx_buff_attrs(rx_ring, rx_info, 0);
559 
560 	__free_page(page);
561 	rx_info->page = NULL;
562 }
563 
564 static int ena_refill_rx_bufs(struct ena_ring *rx_ring, u32 num)
565 {
566 	u16 next_to_use, req_id;
567 	u32 i;
568 	int rc;
569 
570 	next_to_use = rx_ring->next_to_use;
571 
572 	for (i = 0; i < num; i++) {
573 		struct ena_rx_buffer *rx_info;
574 
575 		req_id = rx_ring->free_ids[next_to_use];
576 
577 		rx_info = &rx_ring->rx_buffer_info[req_id];
578 
579 		rc = ena_alloc_rx_buffer(rx_ring, rx_info);
580 		if (unlikely(rc < 0)) {
581 			netif_warn(rx_ring->adapter, rx_err, rx_ring->netdev,
582 				   "Failed to allocate buffer for rx queue %d\n",
583 				   rx_ring->qid);
584 			break;
585 		}
586 		rc = ena_com_add_single_rx_desc(rx_ring->ena_com_io_sq,
587 						&rx_info->ena_buf,
588 						req_id);
589 		if (unlikely(rc)) {
590 			netif_warn(rx_ring->adapter, rx_status, rx_ring->netdev,
591 				   "Failed to add buffer for rx queue %d\n",
592 				   rx_ring->qid);
593 			break;
594 		}
595 		next_to_use = ENA_RX_RING_IDX_NEXT(next_to_use,
596 						   rx_ring->ring_size);
597 	}
598 
599 	if (unlikely(i < num)) {
600 		ena_increase_stat(&rx_ring->rx_stats.refil_partial, 1,
601 				  &rx_ring->syncp);
602 		netif_warn(rx_ring->adapter, rx_err, rx_ring->netdev,
603 			   "Refilled rx qid %d with only %d buffers (from %d)\n",
604 			   rx_ring->qid, i, num);
605 	}
606 
607 	/* ena_com_write_sq_doorbell issues a wmb() */
608 	if (likely(i))
609 		ena_com_write_sq_doorbell(rx_ring->ena_com_io_sq);
610 
611 	rx_ring->next_to_use = next_to_use;
612 
613 	return i;
614 }
615 
616 static void ena_free_rx_bufs(struct ena_adapter *adapter,
617 			     u32 qid)
618 {
619 	struct ena_ring *rx_ring = &adapter->rx_ring[qid];
620 	u32 i;
621 
622 	for (i = 0; i < rx_ring->ring_size; i++) {
623 		struct ena_rx_buffer *rx_info = &rx_ring->rx_buffer_info[i];
624 
625 		if (rx_info->page)
626 			ena_free_rx_page(rx_ring, rx_info);
627 	}
628 }
629 
630 /* ena_refill_all_rx_bufs - allocate all queues Rx buffers
631  * @adapter: board private structure
632  */
633 static void ena_refill_all_rx_bufs(struct ena_adapter *adapter)
634 {
635 	struct ena_ring *rx_ring;
636 	int i, rc, bufs_num;
637 
638 	for (i = 0; i < adapter->num_io_queues; i++) {
639 		rx_ring = &adapter->rx_ring[i];
640 		bufs_num = rx_ring->ring_size - 1;
641 		rc = ena_refill_rx_bufs(rx_ring, bufs_num);
642 
643 		if (unlikely(rc != bufs_num))
644 			netif_warn(rx_ring->adapter, rx_status, rx_ring->netdev,
645 				   "Refilling Queue %d failed. allocated %d buffers from: %d\n",
646 				   i, rc, bufs_num);
647 	}
648 }
649 
650 static void ena_free_all_rx_bufs(struct ena_adapter *adapter)
651 {
652 	int i;
653 
654 	for (i = 0; i < adapter->num_io_queues; i++)
655 		ena_free_rx_bufs(adapter, i);
656 }
657 
658 void ena_unmap_tx_buff(struct ena_ring *tx_ring,
659 		       struct ena_tx_buffer *tx_info)
660 {
661 	struct ena_com_buf *ena_buf;
662 	u32 cnt;
663 	int i;
664 
665 	ena_buf = tx_info->bufs;
666 	cnt = tx_info->num_of_bufs;
667 
668 	if (unlikely(!cnt))
669 		return;
670 
671 	if (tx_info->map_linear_data) {
672 		dma_unmap_single(tx_ring->dev,
673 				 dma_unmap_addr(ena_buf, paddr),
674 				 dma_unmap_len(ena_buf, len),
675 				 DMA_TO_DEVICE);
676 		ena_buf++;
677 		cnt--;
678 	}
679 
680 	/* unmap remaining mapped pages */
681 	for (i = 0; i < cnt; i++) {
682 		dma_unmap_page(tx_ring->dev, dma_unmap_addr(ena_buf, paddr),
683 			       dma_unmap_len(ena_buf, len), DMA_TO_DEVICE);
684 		ena_buf++;
685 	}
686 }
687 
688 /* ena_free_tx_bufs - Free Tx Buffers per Queue
689  * @tx_ring: TX ring for which buffers be freed
690  */
691 static void ena_free_tx_bufs(struct ena_ring *tx_ring)
692 {
693 	bool print_once = true;
694 	bool is_xdp_ring;
695 	u32 i;
696 
697 	is_xdp_ring = ENA_IS_XDP_INDEX(tx_ring->adapter, tx_ring->qid);
698 
699 	for (i = 0; i < tx_ring->ring_size; i++) {
700 		struct ena_tx_buffer *tx_info = &tx_ring->tx_buffer_info[i];
701 
702 		if (!tx_info->skb)
703 			continue;
704 
705 		if (print_once) {
706 			netif_notice(tx_ring->adapter, ifdown, tx_ring->netdev,
707 				     "Free uncompleted tx skb qid %d idx 0x%x\n",
708 				     tx_ring->qid, i);
709 			print_once = false;
710 		} else {
711 			netif_dbg(tx_ring->adapter, ifdown, tx_ring->netdev,
712 				  "Free uncompleted tx skb qid %d idx 0x%x\n",
713 				  tx_ring->qid, i);
714 		}
715 
716 		ena_unmap_tx_buff(tx_ring, tx_info);
717 
718 		if (is_xdp_ring)
719 			xdp_return_frame(tx_info->xdpf);
720 		else
721 			dev_kfree_skb_any(tx_info->skb);
722 	}
723 
724 	if (!is_xdp_ring)
725 		netdev_tx_reset_queue(netdev_get_tx_queue(tx_ring->netdev,
726 							  tx_ring->qid));
727 }
728 
729 static void ena_free_all_tx_bufs(struct ena_adapter *adapter)
730 {
731 	struct ena_ring *tx_ring;
732 	int i;
733 
734 	for (i = 0; i < adapter->num_io_queues + adapter->xdp_num_queues; i++) {
735 		tx_ring = &adapter->tx_ring[i];
736 		ena_free_tx_bufs(tx_ring);
737 	}
738 }
739 
740 static void ena_destroy_all_tx_queues(struct ena_adapter *adapter)
741 {
742 	u16 ena_qid;
743 	int i;
744 
745 	for (i = 0; i < adapter->num_io_queues + adapter->xdp_num_queues; i++) {
746 		ena_qid = ENA_IO_TXQ_IDX(i);
747 		ena_com_destroy_io_queue(adapter->ena_dev, ena_qid);
748 	}
749 }
750 
751 static void ena_destroy_all_rx_queues(struct ena_adapter *adapter)
752 {
753 	u16 ena_qid;
754 	int i;
755 
756 	for (i = 0; i < adapter->num_io_queues; i++) {
757 		ena_qid = ENA_IO_RXQ_IDX(i);
758 		cancel_work_sync(&adapter->ena_napi[i].dim.work);
759 		ena_xdp_unregister_rxq_info(&adapter->rx_ring[i]);
760 		ena_com_destroy_io_queue(adapter->ena_dev, ena_qid);
761 	}
762 }
763 
764 static void ena_destroy_all_io_queues(struct ena_adapter *adapter)
765 {
766 	ena_destroy_all_tx_queues(adapter);
767 	ena_destroy_all_rx_queues(adapter);
768 }
769 
770 int handle_invalid_req_id(struct ena_ring *ring, u16 req_id,
771 			  struct ena_tx_buffer *tx_info, bool is_xdp)
772 {
773 	if (tx_info)
774 		netif_err(ring->adapter,
775 			  tx_done,
776 			  ring->netdev,
777 			  "tx_info doesn't have valid %s. qid %u req_id %u",
778 			   is_xdp ? "xdp frame" : "skb", ring->qid, req_id);
779 	else
780 		netif_err(ring->adapter,
781 			  tx_done,
782 			  ring->netdev,
783 			  "Invalid req_id %u in qid %u\n",
784 			  req_id, ring->qid);
785 
786 	ena_increase_stat(&ring->tx_stats.bad_req_id, 1, &ring->syncp);
787 	ena_reset_device(ring->adapter, ENA_REGS_RESET_INV_TX_REQ_ID);
788 
789 	return -EFAULT;
790 }
791 
792 static int validate_tx_req_id(struct ena_ring *tx_ring, u16 req_id)
793 {
794 	struct ena_tx_buffer *tx_info;
795 
796 	tx_info = &tx_ring->tx_buffer_info[req_id];
797 	if (likely(tx_info->skb))
798 		return 0;
799 
800 	return handle_invalid_req_id(tx_ring, req_id, tx_info, false);
801 }
802 
803 static int ena_clean_tx_irq(struct ena_ring *tx_ring, u32 budget)
804 {
805 	struct netdev_queue *txq;
806 	bool above_thresh;
807 	u32 tx_bytes = 0;
808 	u32 total_done = 0;
809 	u16 next_to_clean;
810 	u16 req_id;
811 	int tx_pkts = 0;
812 	int rc;
813 
814 	next_to_clean = tx_ring->next_to_clean;
815 	txq = netdev_get_tx_queue(tx_ring->netdev, tx_ring->qid);
816 
817 	while (tx_pkts < budget) {
818 		struct ena_tx_buffer *tx_info;
819 		struct sk_buff *skb;
820 
821 		rc = ena_com_tx_comp_req_id_get(tx_ring->ena_com_io_cq,
822 						&req_id);
823 		if (rc) {
824 			if (unlikely(rc == -EINVAL))
825 				handle_invalid_req_id(tx_ring, req_id, NULL, false);
826 			break;
827 		}
828 
829 		/* validate that the request id points to a valid skb */
830 		rc = validate_tx_req_id(tx_ring, req_id);
831 		if (rc)
832 			break;
833 
834 		tx_info = &tx_ring->tx_buffer_info[req_id];
835 		skb = tx_info->skb;
836 
837 		/* prefetch skb_end_pointer() to speedup skb_shinfo(skb) */
838 		prefetch(&skb->end);
839 
840 		tx_info->skb = NULL;
841 		tx_info->last_jiffies = 0;
842 
843 		ena_unmap_tx_buff(tx_ring, tx_info);
844 
845 		netif_dbg(tx_ring->adapter, tx_done, tx_ring->netdev,
846 			  "tx_poll: q %d skb %p completed\n", tx_ring->qid,
847 			  skb);
848 
849 		tx_bytes += tx_info->total_tx_size;
850 		dev_kfree_skb(skb);
851 		tx_pkts++;
852 		total_done += tx_info->tx_descs;
853 
854 		tx_ring->free_ids[next_to_clean] = req_id;
855 		next_to_clean = ENA_TX_RING_IDX_NEXT(next_to_clean,
856 						     tx_ring->ring_size);
857 	}
858 
859 	tx_ring->next_to_clean = next_to_clean;
860 	ena_com_comp_ack(tx_ring->ena_com_io_sq, total_done);
861 
862 	netdev_tx_completed_queue(txq, tx_pkts, tx_bytes);
863 
864 	netif_dbg(tx_ring->adapter, tx_done, tx_ring->netdev,
865 		  "tx_poll: q %d done. total pkts: %d\n",
866 		  tx_ring->qid, tx_pkts);
867 
868 	/* need to make the rings circular update visible to
869 	 * ena_start_xmit() before checking for netif_queue_stopped().
870 	 */
871 	smp_mb();
872 
873 	above_thresh = ena_com_sq_have_enough_space(tx_ring->ena_com_io_sq,
874 						    ENA_TX_WAKEUP_THRESH);
875 	if (unlikely(netif_tx_queue_stopped(txq) && above_thresh)) {
876 		__netif_tx_lock(txq, smp_processor_id());
877 		above_thresh =
878 			ena_com_sq_have_enough_space(tx_ring->ena_com_io_sq,
879 						     ENA_TX_WAKEUP_THRESH);
880 		if (netif_tx_queue_stopped(txq) && above_thresh &&
881 		    test_bit(ENA_FLAG_DEV_UP, &tx_ring->adapter->flags)) {
882 			netif_tx_wake_queue(txq);
883 			ena_increase_stat(&tx_ring->tx_stats.queue_wakeup, 1,
884 					  &tx_ring->syncp);
885 		}
886 		__netif_tx_unlock(txq);
887 	}
888 
889 	return tx_pkts;
890 }
891 
892 static struct sk_buff *ena_alloc_skb(struct ena_ring *rx_ring, void *first_frag, u16 len)
893 {
894 	struct sk_buff *skb;
895 
896 	if (!first_frag)
897 		skb = napi_alloc_skb(rx_ring->napi, len);
898 	else
899 		skb = napi_build_skb(first_frag, len);
900 
901 	if (unlikely(!skb)) {
902 		ena_increase_stat(&rx_ring->rx_stats.skb_alloc_fail, 1,
903 				  &rx_ring->syncp);
904 
905 		netif_dbg(rx_ring->adapter, rx_err, rx_ring->netdev,
906 			  "Failed to allocate skb. first_frag %s\n",
907 			  first_frag ? "provided" : "not provided");
908 	}
909 
910 	return skb;
911 }
912 
913 static bool ena_try_rx_buf_page_reuse(struct ena_rx_buffer *rx_info, u16 buf_len,
914 				      u16 len, int pkt_offset)
915 {
916 	struct ena_com_buf *ena_buf = &rx_info->ena_buf;
917 
918 	/* More than ENA_MIN_RX_BUF_SIZE left in the reused buffer
919 	 * for data + headroom + tailroom.
920 	 */
921 	if (SKB_DATA_ALIGN(len + pkt_offset) + ENA_MIN_RX_BUF_SIZE <= ena_buf->len) {
922 		page_ref_inc(rx_info->page);
923 		rx_info->page_offset += buf_len;
924 		ena_buf->paddr += buf_len;
925 		ena_buf->len -= buf_len;
926 		return true;
927 	}
928 
929 	return false;
930 }
931 
932 static struct sk_buff *ena_rx_skb(struct ena_ring *rx_ring,
933 				  struct ena_com_rx_buf_info *ena_bufs,
934 				  u32 descs,
935 				  u16 *next_to_clean)
936 {
937 	int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
938 	bool is_xdp_loaded = ena_xdp_present_ring(rx_ring);
939 	struct ena_rx_buffer *rx_info;
940 	struct ena_adapter *adapter;
941 	int page_offset, pkt_offset;
942 	dma_addr_t pre_reuse_paddr;
943 	u16 len, req_id, buf = 0;
944 	bool reuse_rx_buf_page;
945 	struct sk_buff *skb;
946 	void *buf_addr;
947 	int buf_offset;
948 	u16 buf_len;
949 
950 	len = ena_bufs[buf].len;
951 	req_id = ena_bufs[buf].req_id;
952 
953 	rx_info = &rx_ring->rx_buffer_info[req_id];
954 
955 	if (unlikely(!rx_info->page)) {
956 		adapter = rx_ring->adapter;
957 		netif_err(adapter, rx_err, rx_ring->netdev,
958 			  "Page is NULL. qid %u req_id %u\n", rx_ring->qid, req_id);
959 		ena_increase_stat(&rx_ring->rx_stats.bad_req_id, 1, &rx_ring->syncp);
960 		ena_reset_device(adapter, ENA_REGS_RESET_INV_RX_REQ_ID);
961 		return NULL;
962 	}
963 
964 	netif_dbg(rx_ring->adapter, rx_status, rx_ring->netdev,
965 		  "rx_info %p page %p\n",
966 		  rx_info, rx_info->page);
967 
968 	buf_offset = rx_info->buf_offset;
969 	pkt_offset = buf_offset - rx_ring->rx_headroom;
970 	page_offset = rx_info->page_offset;
971 	buf_addr = page_address(rx_info->page) + page_offset;
972 
973 	if (len <= rx_ring->rx_copybreak) {
974 		skb = ena_alloc_skb(rx_ring, NULL, len);
975 		if (unlikely(!skb))
976 			return NULL;
977 
978 		skb_copy_to_linear_data(skb, buf_addr + buf_offset, len);
979 		dma_sync_single_for_device(rx_ring->dev,
980 					   dma_unmap_addr(&rx_info->ena_buf, paddr) + pkt_offset,
981 					   len,
982 					   DMA_FROM_DEVICE);
983 
984 		skb_put(skb, len);
985 		netif_dbg(rx_ring->adapter, rx_status, rx_ring->netdev,
986 			  "RX allocated small packet. len %d.\n", skb->len);
987 		skb->protocol = eth_type_trans(skb, rx_ring->netdev);
988 		rx_ring->free_ids[*next_to_clean] = req_id;
989 		*next_to_clean = ENA_RX_RING_IDX_ADD(*next_to_clean, descs,
990 						     rx_ring->ring_size);
991 		return skb;
992 	}
993 
994 	buf_len = SKB_DATA_ALIGN(len + buf_offset + tailroom);
995 
996 	/* If XDP isn't loaded try to reuse part of the RX buffer */
997 	reuse_rx_buf_page = !is_xdp_loaded &&
998 			    ena_try_rx_buf_page_reuse(rx_info, buf_len, len, pkt_offset);
999 
1000 	if (!reuse_rx_buf_page)
1001 		ena_unmap_rx_buff_attrs(rx_ring, rx_info, DMA_ATTR_SKIP_CPU_SYNC);
1002 
1003 	skb = ena_alloc_skb(rx_ring, buf_addr, buf_len);
1004 	if (unlikely(!skb))
1005 		return NULL;
1006 
1007 	/* Populate skb's linear part */
1008 	skb_reserve(skb, buf_offset);
1009 	skb_put(skb, len);
1010 	skb->protocol = eth_type_trans(skb, rx_ring->netdev);
1011 
1012 	do {
1013 		netif_dbg(rx_ring->adapter, rx_status, rx_ring->netdev,
1014 			  "RX skb updated. len %d. data_len %d\n",
1015 			  skb->len, skb->data_len);
1016 
1017 		if (!reuse_rx_buf_page)
1018 			rx_info->page = NULL;
1019 
1020 		rx_ring->free_ids[*next_to_clean] = req_id;
1021 		*next_to_clean =
1022 			ENA_RX_RING_IDX_NEXT(*next_to_clean,
1023 					     rx_ring->ring_size);
1024 		if (likely(--descs == 0))
1025 			break;
1026 
1027 		buf++;
1028 		len = ena_bufs[buf].len;
1029 		req_id = ena_bufs[buf].req_id;
1030 
1031 		rx_info = &rx_ring->rx_buffer_info[req_id];
1032 
1033 		/* rx_info->buf_offset includes rx_ring->rx_headroom */
1034 		buf_offset = rx_info->buf_offset;
1035 		pkt_offset = buf_offset - rx_ring->rx_headroom;
1036 		buf_len = SKB_DATA_ALIGN(len + buf_offset + tailroom);
1037 		page_offset = rx_info->page_offset;
1038 
1039 		pre_reuse_paddr = dma_unmap_addr(&rx_info->ena_buf, paddr);
1040 
1041 		reuse_rx_buf_page = !is_xdp_loaded &&
1042 				    ena_try_rx_buf_page_reuse(rx_info, buf_len, len, pkt_offset);
1043 
1044 		dma_sync_single_for_cpu(rx_ring->dev,
1045 					pre_reuse_paddr + pkt_offset,
1046 					len,
1047 					DMA_FROM_DEVICE);
1048 
1049 		if (!reuse_rx_buf_page)
1050 			ena_unmap_rx_buff_attrs(rx_ring, rx_info, DMA_ATTR_SKIP_CPU_SYNC);
1051 
1052 		skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, rx_info->page,
1053 				page_offset + buf_offset, len, buf_len);
1054 
1055 	} while (1);
1056 
1057 	return skb;
1058 }
1059 
1060 /* ena_rx_checksum - indicate in skb if hw indicated a good cksum
1061  * @adapter: structure containing adapter specific data
1062  * @ena_rx_ctx: received packet context/metadata
1063  * @skb: skb currently being received and modified
1064  */
1065 static void ena_rx_checksum(struct ena_ring *rx_ring,
1066 				   struct ena_com_rx_ctx *ena_rx_ctx,
1067 				   struct sk_buff *skb)
1068 {
1069 	/* Rx csum disabled */
1070 	if (unlikely(!(rx_ring->netdev->features & NETIF_F_RXCSUM))) {
1071 		skb->ip_summed = CHECKSUM_NONE;
1072 		return;
1073 	}
1074 
1075 	/* For fragmented packets the checksum isn't valid */
1076 	if (ena_rx_ctx->frag) {
1077 		skb->ip_summed = CHECKSUM_NONE;
1078 		return;
1079 	}
1080 
1081 	/* if IP and error */
1082 	if (unlikely((ena_rx_ctx->l3_proto == ENA_ETH_IO_L3_PROTO_IPV4) &&
1083 		     (ena_rx_ctx->l3_csum_err))) {
1084 		/* ipv4 checksum error */
1085 		skb->ip_summed = CHECKSUM_NONE;
1086 		ena_increase_stat(&rx_ring->rx_stats.csum_bad, 1,
1087 				  &rx_ring->syncp);
1088 		netif_dbg(rx_ring->adapter, rx_err, rx_ring->netdev,
1089 			  "RX IPv4 header checksum error\n");
1090 		return;
1091 	}
1092 
1093 	/* if TCP/UDP */
1094 	if (likely((ena_rx_ctx->l4_proto == ENA_ETH_IO_L4_PROTO_TCP) ||
1095 		   (ena_rx_ctx->l4_proto == ENA_ETH_IO_L4_PROTO_UDP))) {
1096 		if (unlikely(ena_rx_ctx->l4_csum_err)) {
1097 			/* TCP/UDP checksum error */
1098 			ena_increase_stat(&rx_ring->rx_stats.csum_bad, 1,
1099 					  &rx_ring->syncp);
1100 			netif_dbg(rx_ring->adapter, rx_err, rx_ring->netdev,
1101 				  "RX L4 checksum error\n");
1102 			skb->ip_summed = CHECKSUM_NONE;
1103 			return;
1104 		}
1105 
1106 		if (likely(ena_rx_ctx->l4_csum_checked)) {
1107 			skb->ip_summed = CHECKSUM_UNNECESSARY;
1108 			ena_increase_stat(&rx_ring->rx_stats.csum_good, 1,
1109 					  &rx_ring->syncp);
1110 		} else {
1111 			ena_increase_stat(&rx_ring->rx_stats.csum_unchecked, 1,
1112 					  &rx_ring->syncp);
1113 			skb->ip_summed = CHECKSUM_NONE;
1114 		}
1115 	} else {
1116 		skb->ip_summed = CHECKSUM_NONE;
1117 		return;
1118 	}
1119 
1120 }
1121 
1122 static void ena_set_rx_hash(struct ena_ring *rx_ring,
1123 			    struct ena_com_rx_ctx *ena_rx_ctx,
1124 			    struct sk_buff *skb)
1125 {
1126 	enum pkt_hash_types hash_type;
1127 
1128 	if (likely(rx_ring->netdev->features & NETIF_F_RXHASH)) {
1129 		if (likely((ena_rx_ctx->l4_proto == ENA_ETH_IO_L4_PROTO_TCP) ||
1130 			   (ena_rx_ctx->l4_proto == ENA_ETH_IO_L4_PROTO_UDP)))
1131 
1132 			hash_type = PKT_HASH_TYPE_L4;
1133 		else
1134 			hash_type = PKT_HASH_TYPE_NONE;
1135 
1136 		/* Override hash type if the packet is fragmented */
1137 		if (ena_rx_ctx->frag)
1138 			hash_type = PKT_HASH_TYPE_NONE;
1139 
1140 		skb_set_hash(skb, ena_rx_ctx->hash, hash_type);
1141 	}
1142 }
1143 
1144 static int ena_xdp_handle_buff(struct ena_ring *rx_ring, struct xdp_buff *xdp, u16 num_descs)
1145 {
1146 	struct ena_rx_buffer *rx_info;
1147 	int ret;
1148 
1149 	/* XDP multi-buffer packets not supported */
1150 	if (unlikely(num_descs > 1)) {
1151 		netdev_err_once(rx_ring->adapter->netdev,
1152 				"xdp: dropped unsupported multi-buffer packets\n");
1153 		ena_increase_stat(&rx_ring->rx_stats.xdp_drop, 1, &rx_ring->syncp);
1154 		return ENA_XDP_DROP;
1155 	}
1156 
1157 	rx_info = &rx_ring->rx_buffer_info[rx_ring->ena_bufs[0].req_id];
1158 	xdp_prepare_buff(xdp, page_address(rx_info->page),
1159 			 rx_info->buf_offset,
1160 			 rx_ring->ena_bufs[0].len, false);
1161 
1162 	ret = ena_xdp_execute(rx_ring, xdp);
1163 
1164 	/* The xdp program might expand the headers */
1165 	if (ret == ENA_XDP_PASS) {
1166 		rx_info->buf_offset = xdp->data - xdp->data_hard_start;
1167 		rx_ring->ena_bufs[0].len = xdp->data_end - xdp->data;
1168 	}
1169 
1170 	return ret;
1171 }
1172 
1173 /* ena_clean_rx_irq - Cleanup RX irq
1174  * @rx_ring: RX ring to clean
1175  * @napi: napi handler
1176  * @budget: how many packets driver is allowed to clean
1177  *
1178  * Returns the number of cleaned buffers.
1179  */
1180 static int ena_clean_rx_irq(struct ena_ring *rx_ring, struct napi_struct *napi,
1181 			    u32 budget)
1182 {
1183 	u16 next_to_clean = rx_ring->next_to_clean;
1184 	struct ena_com_rx_ctx ena_rx_ctx;
1185 	struct ena_rx_buffer *rx_info;
1186 	struct ena_adapter *adapter;
1187 	u32 res_budget, work_done;
1188 	int rx_copybreak_pkt = 0;
1189 	int refill_threshold;
1190 	struct sk_buff *skb;
1191 	int refill_required;
1192 	struct xdp_buff xdp;
1193 	int xdp_flags = 0;
1194 	int total_len = 0;
1195 	int xdp_verdict;
1196 	u8 pkt_offset;
1197 	int rc = 0;
1198 	int i;
1199 
1200 	netif_dbg(rx_ring->adapter, rx_status, rx_ring->netdev,
1201 		  "%s qid %d\n", __func__, rx_ring->qid);
1202 	res_budget = budget;
1203 	xdp_init_buff(&xdp, ENA_PAGE_SIZE, &rx_ring->xdp_rxq);
1204 
1205 	do {
1206 		xdp_verdict = ENA_XDP_PASS;
1207 		skb = NULL;
1208 		ena_rx_ctx.ena_bufs = rx_ring->ena_bufs;
1209 		ena_rx_ctx.max_bufs = rx_ring->sgl_size;
1210 		ena_rx_ctx.descs = 0;
1211 		ena_rx_ctx.pkt_offset = 0;
1212 		rc = ena_com_rx_pkt(rx_ring->ena_com_io_cq,
1213 				    rx_ring->ena_com_io_sq,
1214 				    &ena_rx_ctx);
1215 		if (unlikely(rc))
1216 			goto error;
1217 
1218 		if (unlikely(ena_rx_ctx.descs == 0))
1219 			break;
1220 
1221 		/* First descriptor might have an offset set by the device */
1222 		rx_info = &rx_ring->rx_buffer_info[rx_ring->ena_bufs[0].req_id];
1223 		pkt_offset = ena_rx_ctx.pkt_offset;
1224 		rx_info->buf_offset += pkt_offset;
1225 
1226 		netif_dbg(rx_ring->adapter, rx_status, rx_ring->netdev,
1227 			  "rx_poll: q %d got packet from ena. descs #: %d l3 proto %d l4 proto %d hash: %x\n",
1228 			  rx_ring->qid, ena_rx_ctx.descs, ena_rx_ctx.l3_proto,
1229 			  ena_rx_ctx.l4_proto, ena_rx_ctx.hash);
1230 
1231 		dma_sync_single_for_cpu(rx_ring->dev,
1232 					dma_unmap_addr(&rx_info->ena_buf, paddr) + pkt_offset,
1233 					rx_ring->ena_bufs[0].len,
1234 					DMA_FROM_DEVICE);
1235 
1236 		if (ena_xdp_present_ring(rx_ring))
1237 			xdp_verdict = ena_xdp_handle_buff(rx_ring, &xdp, ena_rx_ctx.descs);
1238 
1239 		/* allocate skb and fill it */
1240 		if (xdp_verdict == ENA_XDP_PASS)
1241 			skb = ena_rx_skb(rx_ring,
1242 					 rx_ring->ena_bufs,
1243 					 ena_rx_ctx.descs,
1244 					 &next_to_clean);
1245 
1246 		if (unlikely(!skb)) {
1247 			for (i = 0; i < ena_rx_ctx.descs; i++) {
1248 				int req_id = rx_ring->ena_bufs[i].req_id;
1249 
1250 				rx_ring->free_ids[next_to_clean] = req_id;
1251 				next_to_clean =
1252 					ENA_RX_RING_IDX_NEXT(next_to_clean,
1253 							     rx_ring->ring_size);
1254 
1255 				/* Packets was passed for transmission, unmap it
1256 				 * from RX side.
1257 				 */
1258 				if (xdp_verdict & ENA_XDP_FORWARDED) {
1259 					ena_unmap_rx_buff_attrs(rx_ring,
1260 								&rx_ring->rx_buffer_info[req_id],
1261 								DMA_ATTR_SKIP_CPU_SYNC);
1262 					rx_ring->rx_buffer_info[req_id].page = NULL;
1263 				}
1264 			}
1265 			if (xdp_verdict != ENA_XDP_PASS) {
1266 				xdp_flags |= xdp_verdict;
1267 				total_len += ena_rx_ctx.ena_bufs[0].len;
1268 				res_budget--;
1269 				continue;
1270 			}
1271 			break;
1272 		}
1273 
1274 		ena_rx_checksum(rx_ring, &ena_rx_ctx, skb);
1275 
1276 		ena_set_rx_hash(rx_ring, &ena_rx_ctx, skb);
1277 
1278 		skb_record_rx_queue(skb, rx_ring->qid);
1279 
1280 		if (rx_ring->ena_bufs[0].len <= rx_ring->rx_copybreak)
1281 			rx_copybreak_pkt++;
1282 
1283 		total_len += skb->len;
1284 
1285 		napi_gro_receive(napi, skb);
1286 
1287 		res_budget--;
1288 	} while (likely(res_budget));
1289 
1290 	work_done = budget - res_budget;
1291 	rx_ring->per_napi_packets += work_done;
1292 	u64_stats_update_begin(&rx_ring->syncp);
1293 	rx_ring->rx_stats.bytes += total_len;
1294 	rx_ring->rx_stats.cnt += work_done;
1295 	rx_ring->rx_stats.rx_copybreak_pkt += rx_copybreak_pkt;
1296 	u64_stats_update_end(&rx_ring->syncp);
1297 
1298 	rx_ring->next_to_clean = next_to_clean;
1299 
1300 	refill_required = ena_com_free_q_entries(rx_ring->ena_com_io_sq);
1301 	refill_threshold =
1302 		min_t(int, rx_ring->ring_size / ENA_RX_REFILL_THRESH_DIVIDER,
1303 		      ENA_RX_REFILL_THRESH_PACKET);
1304 
1305 	/* Optimization, try to batch new rx buffers */
1306 	if (refill_required > refill_threshold)
1307 		ena_refill_rx_bufs(rx_ring, refill_required);
1308 
1309 	if (xdp_flags & ENA_XDP_REDIRECT)
1310 		xdp_do_flush();
1311 
1312 	return work_done;
1313 
1314 error:
1315 	if (xdp_flags & ENA_XDP_REDIRECT)
1316 		xdp_do_flush();
1317 
1318 	adapter = netdev_priv(rx_ring->netdev);
1319 
1320 	if (rc == -ENOSPC) {
1321 		ena_increase_stat(&rx_ring->rx_stats.bad_desc_num, 1, &rx_ring->syncp);
1322 		ena_reset_device(adapter, ENA_REGS_RESET_TOO_MANY_RX_DESCS);
1323 	} else if (rc == -EFAULT) {
1324 		ena_reset_device(adapter, ENA_REGS_RESET_RX_DESCRIPTOR_MALFORMED);
1325 	} else {
1326 		ena_increase_stat(&rx_ring->rx_stats.bad_req_id, 1,
1327 				  &rx_ring->syncp);
1328 		ena_reset_device(adapter, ENA_REGS_RESET_INV_RX_REQ_ID);
1329 	}
1330 	return 0;
1331 }
1332 
1333 static void ena_dim_work(struct work_struct *w)
1334 {
1335 	struct dim *dim = container_of(w, struct dim, work);
1336 	struct dim_cq_moder cur_moder =
1337 		net_dim_get_rx_moderation(dim->mode, dim->profile_ix);
1338 	struct ena_napi *ena_napi = container_of(dim, struct ena_napi, dim);
1339 
1340 	ena_napi->rx_ring->smoothed_interval = cur_moder.usec;
1341 	dim->state = DIM_START_MEASURE;
1342 }
1343 
1344 static void ena_adjust_adaptive_rx_intr_moderation(struct ena_napi *ena_napi)
1345 {
1346 	struct dim_sample dim_sample;
1347 	struct ena_ring *rx_ring = ena_napi->rx_ring;
1348 
1349 	if (!rx_ring->per_napi_packets)
1350 		return;
1351 
1352 	rx_ring->non_empty_napi_events++;
1353 
1354 	dim_update_sample(rx_ring->non_empty_napi_events,
1355 			  rx_ring->rx_stats.cnt,
1356 			  rx_ring->rx_stats.bytes,
1357 			  &dim_sample);
1358 
1359 	net_dim(&ena_napi->dim, &dim_sample);
1360 
1361 	rx_ring->per_napi_packets = 0;
1362 }
1363 
1364 void ena_unmask_interrupt(struct ena_ring *tx_ring,
1365 			  struct ena_ring *rx_ring)
1366 {
1367 	u32 rx_interval = tx_ring->smoothed_interval;
1368 	struct ena_eth_io_intr_reg intr_reg;
1369 
1370 	/* Rx ring can be NULL when for XDP tx queues which don't have an
1371 	 * accompanying rx_ring pair.
1372 	 */
1373 	if (rx_ring)
1374 		rx_interval = ena_com_get_adaptive_moderation_enabled(rx_ring->ena_dev) ?
1375 			rx_ring->smoothed_interval :
1376 			ena_com_get_nonadaptive_moderation_interval_rx(rx_ring->ena_dev);
1377 
1378 	/* Update intr register: rx intr delay,
1379 	 * tx intr delay and interrupt unmask
1380 	 */
1381 	ena_com_update_intr_reg(&intr_reg,
1382 				rx_interval,
1383 				tx_ring->smoothed_interval,
1384 				true);
1385 
1386 	ena_increase_stat(&tx_ring->tx_stats.unmask_interrupt, 1,
1387 			  &tx_ring->syncp);
1388 
1389 	/* It is a shared MSI-X.
1390 	 * Tx and Rx CQ have pointer to it.
1391 	 * So we use one of them to reach the intr reg
1392 	 * The Tx ring is used because the rx_ring is NULL for XDP queues
1393 	 */
1394 	ena_com_unmask_intr(tx_ring->ena_com_io_cq, &intr_reg);
1395 }
1396 
1397 void ena_update_ring_numa_node(struct ena_ring *tx_ring,
1398 			       struct ena_ring *rx_ring)
1399 {
1400 	int cpu = get_cpu();
1401 	int numa_node;
1402 
1403 	/* Check only one ring since the 2 rings are running on the same cpu */
1404 	if (likely(tx_ring->cpu == cpu))
1405 		goto out;
1406 
1407 	tx_ring->cpu = cpu;
1408 	if (rx_ring)
1409 		rx_ring->cpu = cpu;
1410 
1411 	numa_node = cpu_to_node(cpu);
1412 
1413 	if (likely(tx_ring->numa_node == numa_node))
1414 		goto out;
1415 
1416 	put_cpu();
1417 
1418 	if (numa_node != NUMA_NO_NODE) {
1419 		ena_com_update_numa_node(tx_ring->ena_com_io_cq, numa_node);
1420 		tx_ring->numa_node = numa_node;
1421 		if (rx_ring) {
1422 			rx_ring->numa_node = numa_node;
1423 			ena_com_update_numa_node(rx_ring->ena_com_io_cq,
1424 						 numa_node);
1425 		}
1426 	}
1427 
1428 	return;
1429 out:
1430 	put_cpu();
1431 }
1432 
1433 static int ena_io_poll(struct napi_struct *napi, int budget)
1434 {
1435 	struct ena_napi *ena_napi = container_of(napi, struct ena_napi, napi);
1436 	struct ena_ring *tx_ring, *rx_ring;
1437 	int tx_work_done;
1438 	int rx_work_done = 0;
1439 	int tx_budget;
1440 	int napi_comp_call = 0;
1441 	int ret;
1442 
1443 	tx_ring = ena_napi->tx_ring;
1444 	rx_ring = ena_napi->rx_ring;
1445 
1446 	tx_budget = tx_ring->ring_size / ENA_TX_POLL_BUDGET_DIVIDER;
1447 
1448 	if (!test_bit(ENA_FLAG_DEV_UP, &tx_ring->adapter->flags) ||
1449 	    test_bit(ENA_FLAG_TRIGGER_RESET, &tx_ring->adapter->flags)) {
1450 		napi_complete_done(napi, 0);
1451 		return 0;
1452 	}
1453 
1454 	tx_work_done = ena_clean_tx_irq(tx_ring, tx_budget);
1455 	/* On netpoll the budget is zero and the handler should only clean the
1456 	 * tx completions.
1457 	 */
1458 	if (likely(budget))
1459 		rx_work_done = ena_clean_rx_irq(rx_ring, napi, budget);
1460 
1461 	/* If the device is about to reset or down, avoid unmask
1462 	 * the interrupt and return 0 so NAPI won't reschedule
1463 	 */
1464 	if (unlikely(!test_bit(ENA_FLAG_DEV_UP, &tx_ring->adapter->flags) ||
1465 		     test_bit(ENA_FLAG_TRIGGER_RESET, &tx_ring->adapter->flags))) {
1466 		napi_complete_done(napi, 0);
1467 		ret = 0;
1468 
1469 	} else if ((budget > rx_work_done) && (tx_budget > tx_work_done)) {
1470 		napi_comp_call = 1;
1471 
1472 		/* Update numa and unmask the interrupt only when schedule
1473 		 * from the interrupt context (vs from sk_busy_loop)
1474 		 */
1475 		if (napi_complete_done(napi, rx_work_done) &&
1476 		    READ_ONCE(ena_napi->interrupts_masked)) {
1477 			smp_rmb(); /* make sure interrupts_masked is read */
1478 			WRITE_ONCE(ena_napi->interrupts_masked, false);
1479 			/* We apply adaptive moderation on Rx path only.
1480 			 * Tx uses static interrupt moderation.
1481 			 */
1482 			if (ena_com_get_adaptive_moderation_enabled(rx_ring->ena_dev))
1483 				ena_adjust_adaptive_rx_intr_moderation(ena_napi);
1484 
1485 			ena_update_ring_numa_node(tx_ring, rx_ring);
1486 			ena_unmask_interrupt(tx_ring, rx_ring);
1487 		}
1488 
1489 		ret = rx_work_done;
1490 	} else {
1491 		ret = budget;
1492 	}
1493 
1494 	u64_stats_update_begin(&tx_ring->syncp);
1495 	tx_ring->tx_stats.napi_comp += napi_comp_call;
1496 	tx_ring->tx_stats.tx_poll++;
1497 	u64_stats_update_end(&tx_ring->syncp);
1498 
1499 	tx_ring->tx_stats.last_napi_jiffies = jiffies;
1500 
1501 	return ret;
1502 }
1503 
1504 static irqreturn_t ena_intr_msix_mgmnt(int irq, void *data)
1505 {
1506 	struct ena_adapter *adapter = (struct ena_adapter *)data;
1507 
1508 	ena_com_admin_q_comp_intr_handler(adapter->ena_dev);
1509 
1510 	/* Don't call the aenq handler before probe is done */
1511 	if (likely(test_bit(ENA_FLAG_DEVICE_RUNNING, &adapter->flags)))
1512 		ena_com_aenq_intr_handler(adapter->ena_dev, data);
1513 
1514 	return IRQ_HANDLED;
1515 }
1516 
1517 /* ena_intr_msix_io - MSI-X Interrupt Handler for Tx/Rx
1518  * @irq: interrupt number
1519  * @data: pointer to a network interface private napi device structure
1520  */
1521 static irqreturn_t ena_intr_msix_io(int irq, void *data)
1522 {
1523 	struct ena_napi *ena_napi = data;
1524 
1525 	/* Used to check HW health */
1526 	WRITE_ONCE(ena_napi->first_interrupt, true);
1527 
1528 	WRITE_ONCE(ena_napi->interrupts_masked, true);
1529 	smp_wmb(); /* write interrupts_masked before calling napi */
1530 
1531 	napi_schedule_irqoff(&ena_napi->napi);
1532 
1533 	return IRQ_HANDLED;
1534 }
1535 
1536 /* Reserve a single MSI-X vector for management (admin + aenq).
1537  * plus reserve one vector for each potential io queue.
1538  * the number of potential io queues is the minimum of what the device
1539  * supports and the number of vCPUs.
1540  */
1541 static int ena_enable_msix(struct ena_adapter *adapter)
1542 {
1543 	int msix_vecs, irq_cnt;
1544 
1545 	if (test_bit(ENA_FLAG_MSIX_ENABLED, &adapter->flags)) {
1546 		netif_err(adapter, probe, adapter->netdev,
1547 			  "Error, MSI-X is already enabled\n");
1548 		return -EPERM;
1549 	}
1550 
1551 	/* Reserved the max msix vectors we might need */
1552 	msix_vecs = ENA_MAX_MSIX_VEC(adapter->max_num_io_queues);
1553 	netif_dbg(adapter, probe, adapter->netdev,
1554 		  "Trying to enable MSI-X, vectors %d\n", msix_vecs);
1555 
1556 	irq_cnt = pci_alloc_irq_vectors(adapter->pdev, ENA_MIN_MSIX_VEC,
1557 					msix_vecs, PCI_IRQ_MSIX);
1558 
1559 	if (irq_cnt < 0) {
1560 		netif_err(adapter, probe, adapter->netdev,
1561 			  "Failed to enable MSI-X. irq_cnt %d\n", irq_cnt);
1562 		return -ENOSPC;
1563 	}
1564 
1565 	if (irq_cnt != msix_vecs) {
1566 		netif_notice(adapter, probe, adapter->netdev,
1567 			     "Enable only %d MSI-X (out of %d), reduce the number of queues\n",
1568 			     irq_cnt, msix_vecs);
1569 		adapter->num_io_queues = irq_cnt - ENA_ADMIN_MSIX_VEC;
1570 	}
1571 
1572 	if (netif_enable_cpu_rmap(adapter->netdev, adapter->num_io_queues))
1573 		netif_warn(adapter, probe, adapter->netdev,
1574 			   "Failed to map IRQs to CPUs\n");
1575 
1576 	adapter->msix_vecs = irq_cnt;
1577 	set_bit(ENA_FLAG_MSIX_ENABLED, &adapter->flags);
1578 
1579 	return 0;
1580 }
1581 
1582 static void ena_setup_mgmnt_intr(struct ena_adapter *adapter)
1583 {
1584 	u32 cpu;
1585 
1586 	snprintf(adapter->irq_tbl[ENA_MGMNT_IRQ_IDX].name,
1587 		 ENA_IRQNAME_SIZE, "ena-mgmnt@pci:%s",
1588 		 pci_name(adapter->pdev));
1589 	adapter->irq_tbl[ENA_MGMNT_IRQ_IDX].handler =
1590 		ena_intr_msix_mgmnt;
1591 	adapter->irq_tbl[ENA_MGMNT_IRQ_IDX].data = adapter;
1592 	adapter->irq_tbl[ENA_MGMNT_IRQ_IDX].vector =
1593 		pci_irq_vector(adapter->pdev, ENA_MGMNT_IRQ_IDX);
1594 	cpu = cpumask_first(cpu_online_mask);
1595 	adapter->irq_tbl[ENA_MGMNT_IRQ_IDX].cpu = cpu;
1596 	cpumask_set_cpu(cpu,
1597 			&adapter->irq_tbl[ENA_MGMNT_IRQ_IDX].affinity_hint_mask);
1598 }
1599 
1600 static void ena_setup_io_intr(struct ena_adapter *adapter)
1601 {
1602 	struct net_device *netdev;
1603 	int irq_idx, i, cpu;
1604 	int io_queue_count;
1605 
1606 	netdev = adapter->netdev;
1607 	io_queue_count = adapter->num_io_queues + adapter->xdp_num_queues;
1608 
1609 	for (i = 0; i < io_queue_count; i++) {
1610 		irq_idx = ENA_IO_IRQ_IDX(i);
1611 		cpu = i % num_online_cpus();
1612 
1613 		snprintf(adapter->irq_tbl[irq_idx].name, ENA_IRQNAME_SIZE,
1614 			 "%s-Tx-Rx-%d", netdev->name, i);
1615 		adapter->irq_tbl[irq_idx].handler = ena_intr_msix_io;
1616 		adapter->irq_tbl[irq_idx].data = &adapter->ena_napi[i];
1617 		adapter->irq_tbl[irq_idx].vector =
1618 			pci_irq_vector(adapter->pdev, irq_idx);
1619 		adapter->irq_tbl[irq_idx].cpu = cpu;
1620 
1621 		cpumask_set_cpu(cpu,
1622 				&adapter->irq_tbl[irq_idx].affinity_hint_mask);
1623 	}
1624 }
1625 
1626 static int ena_request_mgmnt_irq(struct ena_adapter *adapter)
1627 {
1628 	unsigned long flags = 0;
1629 	struct ena_irq *irq;
1630 	int rc;
1631 
1632 	irq = &adapter->irq_tbl[ENA_MGMNT_IRQ_IDX];
1633 	rc = request_irq(irq->vector, irq->handler, flags, irq->name,
1634 			 irq->data);
1635 	if (rc) {
1636 		netif_err(adapter, probe, adapter->netdev,
1637 			  "Failed to request admin irq\n");
1638 		return rc;
1639 	}
1640 
1641 	netif_dbg(adapter, probe, adapter->netdev,
1642 		  "Set affinity hint of mgmnt irq.to 0x%lx (irq vector: %d)\n",
1643 		  irq->affinity_hint_mask.bits[0], irq->vector);
1644 
1645 	irq_set_affinity_hint(irq->vector, &irq->affinity_hint_mask);
1646 
1647 	return rc;
1648 }
1649 
1650 static int ena_request_io_irq(struct ena_adapter *adapter)
1651 {
1652 	u32 io_queue_count = adapter->num_io_queues + adapter->xdp_num_queues;
1653 	int rc = 0, i, k, irq_idx;
1654 	unsigned long flags = 0;
1655 	struct ena_irq *irq;
1656 
1657 	if (!test_bit(ENA_FLAG_MSIX_ENABLED, &adapter->flags)) {
1658 		netif_err(adapter, ifup, adapter->netdev,
1659 			  "Failed to request I/O IRQ: MSI-X is not enabled\n");
1660 		return -EINVAL;
1661 	}
1662 
1663 	for (i = ENA_IO_IRQ_FIRST_IDX; i < ENA_MAX_MSIX_VEC(io_queue_count); i++) {
1664 		irq = &adapter->irq_tbl[i];
1665 		rc = request_irq(irq->vector, irq->handler, flags, irq->name,
1666 				 irq->data);
1667 		if (rc) {
1668 			netif_err(adapter, ifup, adapter->netdev,
1669 				  "Failed to request I/O IRQ. index %d rc %d\n",
1670 				   i, rc);
1671 			goto err;
1672 		}
1673 
1674 		netif_dbg(adapter, ifup, adapter->netdev,
1675 			  "Set affinity hint of irq. index %d to 0x%lx (irq vector: %d)\n",
1676 			  i, irq->affinity_hint_mask.bits[0], irq->vector);
1677 
1678 		irq_set_affinity_hint(irq->vector, &irq->affinity_hint_mask);
1679 	}
1680 
1681 	/* Now that IO IRQs have been successfully allocated map them to the
1682 	 * corresponding IO NAPI instance. Note that the mgmnt IRQ does not
1683 	 * have a NAPI, so care must be taken to correctly map IRQs to NAPIs.
1684 	 */
1685 	for (i = 0; i < io_queue_count; i++) {
1686 		irq_idx = ENA_IO_IRQ_IDX(i);
1687 		irq = &adapter->irq_tbl[irq_idx];
1688 		netif_napi_set_irq(&adapter->ena_napi[i].napi, irq->vector);
1689 	}
1690 
1691 	return rc;
1692 
1693 err:
1694 	for (k = ENA_IO_IRQ_FIRST_IDX; k < i; k++) {
1695 		irq = &adapter->irq_tbl[k];
1696 		free_irq(irq->vector, irq->data);
1697 	}
1698 
1699 	return rc;
1700 }
1701 
1702 static void ena_free_mgmnt_irq(struct ena_adapter *adapter)
1703 {
1704 	struct ena_irq *irq;
1705 
1706 	irq = &adapter->irq_tbl[ENA_MGMNT_IRQ_IDX];
1707 	synchronize_irq(irq->vector);
1708 	irq_set_affinity_hint(irq->vector, NULL);
1709 	free_irq(irq->vector, irq->data);
1710 }
1711 
1712 static void ena_free_io_irq(struct ena_adapter *adapter)
1713 {
1714 	u32 io_queue_count = adapter->num_io_queues + adapter->xdp_num_queues;
1715 	struct ena_irq *irq;
1716 	int i;
1717 
1718 	for (i = ENA_IO_IRQ_FIRST_IDX; i < ENA_MAX_MSIX_VEC(io_queue_count); i++) {
1719 		irq = &adapter->irq_tbl[i];
1720 		irq_set_affinity_hint(irq->vector, NULL);
1721 		free_irq(irq->vector, irq->data);
1722 	}
1723 }
1724 
1725 static void ena_disable_msix(struct ena_adapter *adapter)
1726 {
1727 	if (test_and_clear_bit(ENA_FLAG_MSIX_ENABLED, &adapter->flags))
1728 		pci_free_irq_vectors(adapter->pdev);
1729 }
1730 
1731 static void ena_disable_io_intr_sync(struct ena_adapter *adapter)
1732 {
1733 	u32 io_queue_count = adapter->num_io_queues + adapter->xdp_num_queues;
1734 	int i;
1735 
1736 	if (!netif_running(adapter->netdev))
1737 		return;
1738 
1739 	for (i = ENA_IO_IRQ_FIRST_IDX; i < ENA_MAX_MSIX_VEC(io_queue_count); i++)
1740 		synchronize_irq(adapter->irq_tbl[i].vector);
1741 }
1742 
1743 static void ena_del_napi_in_range(struct ena_adapter *adapter,
1744 				  int first_index,
1745 				  int count)
1746 {
1747 	int i;
1748 
1749 	for (i = first_index; i < first_index + count; i++) {
1750 		netif_napi_del(&adapter->ena_napi[i].napi);
1751 
1752 		WARN_ON(ENA_IS_XDP_INDEX(adapter, i) &&
1753 			adapter->ena_napi[i].rx_ring);
1754 	}
1755 }
1756 
1757 static void ena_init_napi_in_range(struct ena_adapter *adapter,
1758 				   int first_index, int count)
1759 {
1760 	int (*napi_handler)(struct napi_struct *napi, int budget);
1761 	int i;
1762 
1763 	for (i = first_index; i < first_index + count; i++) {
1764 		struct ena_napi *napi = &adapter->ena_napi[i];
1765 		struct ena_ring *rx_ring, *tx_ring;
1766 
1767 		memset(napi, 0, sizeof(*napi));
1768 
1769 		rx_ring = &adapter->rx_ring[i];
1770 		tx_ring = &adapter->tx_ring[i];
1771 
1772 		napi_handler = ena_io_poll;
1773 		if (ENA_IS_XDP_INDEX(adapter, i))
1774 			napi_handler = ena_xdp_io_poll;
1775 
1776 		netif_napi_add(adapter->netdev, &napi->napi, napi_handler);
1777 
1778 		if (!ENA_IS_XDP_INDEX(adapter, i))
1779 			napi->rx_ring = rx_ring;
1780 
1781 		napi->tx_ring = tx_ring;
1782 		napi->qid = i;
1783 	}
1784 }
1785 
1786 static void ena_napi_disable_in_range(struct ena_adapter *adapter,
1787 				      int first_index,
1788 				      int count)
1789 {
1790 	struct napi_struct *napi;
1791 	int i;
1792 
1793 	for (i = first_index; i < first_index + count; i++) {
1794 		napi = &adapter->ena_napi[i].napi;
1795 		if (!ENA_IS_XDP_INDEX(adapter, i)) {
1796 			/* This API is supported for non-XDP queues only */
1797 			netif_queue_set_napi(adapter->netdev, i,
1798 					     NETDEV_QUEUE_TYPE_TX, NULL);
1799 			netif_queue_set_napi(adapter->netdev, i,
1800 					     NETDEV_QUEUE_TYPE_RX, NULL);
1801 		}
1802 		napi_disable(napi);
1803 	}
1804 }
1805 
1806 static void ena_napi_enable_in_range(struct ena_adapter *adapter,
1807 				     int first_index,
1808 				     int count)
1809 {
1810 	struct napi_struct *napi;
1811 	int i;
1812 
1813 	for (i = first_index; i < first_index + count; i++) {
1814 		napi = &adapter->ena_napi[i].napi;
1815 		napi_enable(napi);
1816 		if (!ENA_IS_XDP_INDEX(adapter, i)) {
1817 			/* This API is supported for non-XDP queues only */
1818 			netif_queue_set_napi(adapter->netdev, i,
1819 					     NETDEV_QUEUE_TYPE_RX, napi);
1820 			netif_queue_set_napi(adapter->netdev, i,
1821 					     NETDEV_QUEUE_TYPE_TX, napi);
1822 		}
1823 	}
1824 }
1825 
1826 /* Configure the Rx forwarding */
1827 static int ena_rss_configure(struct ena_adapter *adapter)
1828 {
1829 	struct ena_com_dev *ena_dev = adapter->ena_dev;
1830 	int rc;
1831 
1832 	/* In case the RSS table wasn't initialized by probe */
1833 	if (!ena_dev->rss.tbl_log_size) {
1834 		rc = ena_rss_init_default(adapter);
1835 		if (rc && (rc != -EOPNOTSUPP)) {
1836 			netif_err(adapter, ifup, adapter->netdev, "Failed to init RSS rc: %d\n", rc);
1837 			return rc;
1838 		}
1839 	}
1840 
1841 	/* Set indirect table */
1842 	rc = ena_com_indirect_table_set(ena_dev);
1843 	if (unlikely(rc && rc != -EOPNOTSUPP))
1844 		return rc;
1845 
1846 	/* Configure hash function (if supported) */
1847 	rc = ena_com_set_hash_function(ena_dev);
1848 	if (unlikely(rc && (rc != -EOPNOTSUPP)))
1849 		return rc;
1850 
1851 	/* Configure hash inputs (if supported) */
1852 	rc = ena_com_set_hash_ctrl(ena_dev);
1853 	if (unlikely(rc && (rc != -EOPNOTSUPP)))
1854 		return rc;
1855 
1856 	return 0;
1857 }
1858 
1859 static int ena_up_complete(struct ena_adapter *adapter)
1860 {
1861 	int rc;
1862 
1863 	rc = ena_rss_configure(adapter);
1864 	if (rc)
1865 		return rc;
1866 
1867 	ena_change_mtu(adapter->netdev, adapter->netdev->mtu);
1868 
1869 	ena_refill_all_rx_bufs(adapter);
1870 
1871 	/* enable transmits */
1872 	netif_tx_start_all_queues(adapter->netdev);
1873 
1874 	ena_napi_enable_in_range(adapter,
1875 				 0,
1876 				 adapter->xdp_num_queues + adapter->num_io_queues);
1877 
1878 	return 0;
1879 }
1880 
1881 static int ena_create_io_tx_queue(struct ena_adapter *adapter, int qid)
1882 {
1883 	struct ena_com_create_io_ctx ctx;
1884 	struct ena_com_dev *ena_dev;
1885 	struct ena_ring *tx_ring;
1886 	u32 msix_vector;
1887 	u16 ena_qid;
1888 	int rc;
1889 
1890 	ena_dev = adapter->ena_dev;
1891 
1892 	tx_ring = &adapter->tx_ring[qid];
1893 	msix_vector = ENA_IO_IRQ_IDX(qid);
1894 	ena_qid = ENA_IO_TXQ_IDX(qid);
1895 
1896 	memset(&ctx, 0x0, sizeof(ctx));
1897 
1898 	ctx.direction = ENA_COM_IO_QUEUE_DIRECTION_TX;
1899 	ctx.qid = ena_qid;
1900 	ctx.mem_queue_type = ena_dev->tx_mem_queue_type;
1901 	ctx.msix_vector = msix_vector;
1902 	ctx.queue_size = tx_ring->ring_size;
1903 	ctx.numa_node = tx_ring->numa_node;
1904 
1905 	rc = ena_com_create_io_queue(ena_dev, &ctx);
1906 	if (rc) {
1907 		netif_err(adapter, ifup, adapter->netdev,
1908 			  "Failed to create I/O TX queue num %d rc: %d\n",
1909 			  qid, rc);
1910 		return rc;
1911 	}
1912 
1913 	rc = ena_com_get_io_handlers(ena_dev, ena_qid,
1914 				     &tx_ring->ena_com_io_sq,
1915 				     &tx_ring->ena_com_io_cq);
1916 	if (rc) {
1917 		netif_err(adapter, ifup, adapter->netdev,
1918 			  "Failed to get TX queue handlers. TX queue num %d rc: %d\n",
1919 			  qid, rc);
1920 		ena_com_destroy_io_queue(ena_dev, ena_qid);
1921 		return rc;
1922 	}
1923 
1924 	ena_com_update_numa_node(tx_ring->ena_com_io_cq, ctx.numa_node);
1925 	return rc;
1926 }
1927 
1928 int ena_create_io_tx_queues_in_range(struct ena_adapter *adapter,
1929 				     int first_index, int count)
1930 {
1931 	struct ena_com_dev *ena_dev = adapter->ena_dev;
1932 	int rc, i;
1933 
1934 	for (i = first_index; i < first_index + count; i++) {
1935 		rc = ena_create_io_tx_queue(adapter, i);
1936 		if (rc)
1937 			goto create_err;
1938 	}
1939 
1940 	return 0;
1941 
1942 create_err:
1943 	while (i-- > first_index)
1944 		ena_com_destroy_io_queue(ena_dev, ENA_IO_TXQ_IDX(i));
1945 
1946 	return rc;
1947 }
1948 
1949 static int ena_create_io_rx_queue(struct ena_adapter *adapter, int qid)
1950 {
1951 	struct ena_com_dev *ena_dev;
1952 	struct ena_com_create_io_ctx ctx;
1953 	struct ena_ring *rx_ring;
1954 	u32 msix_vector;
1955 	u16 ena_qid;
1956 	int rc;
1957 
1958 	ena_dev = adapter->ena_dev;
1959 
1960 	rx_ring = &adapter->rx_ring[qid];
1961 	msix_vector = ENA_IO_IRQ_IDX(qid);
1962 	ena_qid = ENA_IO_RXQ_IDX(qid);
1963 
1964 	memset(&ctx, 0x0, sizeof(ctx));
1965 
1966 	ctx.qid = ena_qid;
1967 	ctx.direction = ENA_COM_IO_QUEUE_DIRECTION_RX;
1968 	ctx.mem_queue_type = ENA_ADMIN_PLACEMENT_POLICY_HOST;
1969 	ctx.msix_vector = msix_vector;
1970 	ctx.queue_size = rx_ring->ring_size;
1971 	ctx.numa_node = rx_ring->numa_node;
1972 
1973 	rc = ena_com_create_io_queue(ena_dev, &ctx);
1974 	if (rc) {
1975 		netif_err(adapter, ifup, adapter->netdev,
1976 			  "Failed to create I/O RX queue num %d rc: %d\n",
1977 			  qid, rc);
1978 		return rc;
1979 	}
1980 
1981 	rc = ena_com_get_io_handlers(ena_dev, ena_qid,
1982 				     &rx_ring->ena_com_io_sq,
1983 				     &rx_ring->ena_com_io_cq);
1984 	if (rc) {
1985 		netif_err(adapter, ifup, adapter->netdev,
1986 			  "Failed to get RX queue handlers. RX queue num %d rc: %d\n",
1987 			  qid, rc);
1988 		goto err;
1989 	}
1990 
1991 	ena_com_update_numa_node(rx_ring->ena_com_io_cq, ctx.numa_node);
1992 
1993 	return rc;
1994 err:
1995 	ena_com_destroy_io_queue(ena_dev, ena_qid);
1996 	return rc;
1997 }
1998 
1999 static int ena_create_all_io_rx_queues(struct ena_adapter *adapter)
2000 {
2001 	struct ena_com_dev *ena_dev = adapter->ena_dev;
2002 	int rc, i;
2003 
2004 	for (i = 0; i < adapter->num_io_queues; i++) {
2005 		rc = ena_create_io_rx_queue(adapter, i);
2006 		if (rc)
2007 			goto create_err;
2008 		INIT_WORK(&adapter->ena_napi[i].dim.work, ena_dim_work);
2009 
2010 		ena_xdp_register_rxq_info(&adapter->rx_ring[i]);
2011 	}
2012 
2013 	return 0;
2014 
2015 create_err:
2016 	while (i--) {
2017 		ena_xdp_unregister_rxq_info(&adapter->rx_ring[i]);
2018 		cancel_work_sync(&adapter->ena_napi[i].dim.work);
2019 		ena_com_destroy_io_queue(ena_dev, ENA_IO_RXQ_IDX(i));
2020 	}
2021 
2022 	return rc;
2023 }
2024 
2025 static void set_io_rings_size(struct ena_adapter *adapter,
2026 			      int new_tx_size,
2027 			      int new_rx_size)
2028 {
2029 	int i;
2030 
2031 	for (i = 0; i < adapter->num_io_queues; i++) {
2032 		adapter->tx_ring[i].ring_size = new_tx_size;
2033 		adapter->rx_ring[i].ring_size = new_rx_size;
2034 	}
2035 }
2036 
2037 /* This function allows queue allocation to backoff when the system is
2038  * low on memory. If there is not enough memory to allocate io queues
2039  * the driver will try to allocate smaller queues.
2040  *
2041  * The backoff algorithm is as follows:
2042  *  1. Try to allocate TX and RX and if successful.
2043  *  1.1. return success
2044  *
2045  *  2. Divide by 2 the size of the larger of RX and TX queues (or both if their size is the same).
2046  *
2047  *  3. If TX or RX is smaller than 256
2048  *  3.1. return failure.
2049  *  4. else
2050  *  4.1. go back to 1.
2051  */
2052 static int create_queues_with_size_backoff(struct ena_adapter *adapter)
2053 {
2054 	int rc, cur_rx_ring_size, cur_tx_ring_size;
2055 	int new_rx_ring_size, new_tx_ring_size;
2056 
2057 	/* current queue sizes might be set to smaller than the requested
2058 	 * ones due to past queue allocation failures.
2059 	 */
2060 	set_io_rings_size(adapter, adapter->requested_tx_ring_size,
2061 			  adapter->requested_rx_ring_size);
2062 
2063 	while (1) {
2064 		if (ena_xdp_present(adapter)) {
2065 			rc = ena_setup_and_create_all_xdp_queues(adapter);
2066 
2067 			if (rc)
2068 				goto err_setup_tx;
2069 		}
2070 		rc = ena_setup_tx_resources_in_range(adapter,
2071 						     0,
2072 						     adapter->num_io_queues);
2073 		if (rc)
2074 			goto err_setup_tx;
2075 
2076 		rc = ena_create_io_tx_queues_in_range(adapter,
2077 						      0,
2078 						      adapter->num_io_queues);
2079 		if (rc)
2080 			goto err_create_tx_queues;
2081 
2082 		rc = ena_setup_all_rx_resources(adapter);
2083 		if (rc)
2084 			goto err_setup_rx;
2085 
2086 		rc = ena_create_all_io_rx_queues(adapter);
2087 		if (rc)
2088 			goto err_create_rx_queues;
2089 
2090 		return 0;
2091 
2092 err_create_rx_queues:
2093 		ena_free_all_io_rx_resources(adapter);
2094 err_setup_rx:
2095 		ena_destroy_all_tx_queues(adapter);
2096 err_create_tx_queues:
2097 		ena_free_all_io_tx_resources(adapter);
2098 err_setup_tx:
2099 		if (rc != -ENOMEM) {
2100 			netif_err(adapter, ifup, adapter->netdev,
2101 				  "Queue creation failed with error code %d\n",
2102 				  rc);
2103 			return rc;
2104 		}
2105 
2106 		cur_tx_ring_size = adapter->tx_ring[0].ring_size;
2107 		cur_rx_ring_size = adapter->rx_ring[0].ring_size;
2108 
2109 		netif_err(adapter, ifup, adapter->netdev,
2110 			  "Not enough memory to create queues with sizes TX=%d, RX=%d\n",
2111 			  cur_tx_ring_size, cur_rx_ring_size);
2112 
2113 		new_tx_ring_size = cur_tx_ring_size;
2114 		new_rx_ring_size = cur_rx_ring_size;
2115 
2116 		/* Decrease the size of the larger queue, or
2117 		 * decrease both if they are the same size.
2118 		 */
2119 		if (cur_rx_ring_size <= cur_tx_ring_size)
2120 			new_tx_ring_size = cur_tx_ring_size / 2;
2121 		if (cur_rx_ring_size >= cur_tx_ring_size)
2122 			new_rx_ring_size = cur_rx_ring_size / 2;
2123 
2124 		if (new_tx_ring_size < ENA_MIN_RING_SIZE ||
2125 		    new_rx_ring_size < ENA_MIN_RING_SIZE) {
2126 			netif_err(adapter, ifup, adapter->netdev,
2127 				  "Queue creation failed with the smallest possible queue size of %d for both queues. Not retrying with smaller queues\n",
2128 				  ENA_MIN_RING_SIZE);
2129 			return rc;
2130 		}
2131 
2132 		netif_err(adapter, ifup, adapter->netdev,
2133 			  "Retrying queue creation with sizes TX=%d, RX=%d\n",
2134 			  new_tx_ring_size,
2135 			  new_rx_ring_size);
2136 
2137 		set_io_rings_size(adapter, new_tx_ring_size,
2138 				  new_rx_ring_size);
2139 	}
2140 }
2141 
2142 int ena_up(struct ena_adapter *adapter)
2143 {
2144 	int io_queue_count, rc, i;
2145 
2146 	netif_dbg(adapter, ifup, adapter->netdev, "%s\n", __func__);
2147 
2148 	io_queue_count = adapter->num_io_queues + adapter->xdp_num_queues;
2149 	ena_setup_io_intr(adapter);
2150 
2151 	/* napi poll functions should be initialized before running
2152 	 * request_irq(), to handle a rare condition where there is a pending
2153 	 * interrupt, causing the ISR to fire immediately while the poll
2154 	 * function wasn't set yet, causing a null dereference
2155 	 */
2156 	ena_init_napi_in_range(adapter, 0, io_queue_count);
2157 
2158 	/* Enabling DIM needs to happen before enabling IRQs since DIM
2159 	 * is run from napi routine
2160 	 */
2161 	if (ena_com_interrupt_moderation_supported(adapter->ena_dev))
2162 		ena_com_enable_adaptive_moderation(adapter->ena_dev);
2163 
2164 	rc = ena_request_io_irq(adapter);
2165 	if (rc)
2166 		goto err_req_irq;
2167 
2168 	rc = create_queues_with_size_backoff(adapter);
2169 	if (rc)
2170 		goto err_create_queues_with_backoff;
2171 
2172 	rc = ena_up_complete(adapter);
2173 	if (rc)
2174 		goto err_up;
2175 
2176 	if (test_bit(ENA_FLAG_LINK_UP, &adapter->flags))
2177 		netif_carrier_on(adapter->netdev);
2178 
2179 	ena_increase_stat(&adapter->dev_stats.interface_up, 1,
2180 			  &adapter->syncp);
2181 
2182 	set_bit(ENA_FLAG_DEV_UP, &adapter->flags);
2183 
2184 	/* Enable completion queues interrupt */
2185 	for (i = 0; i < adapter->num_io_queues; i++)
2186 		ena_unmask_interrupt(&adapter->tx_ring[i],
2187 				     &adapter->rx_ring[i]);
2188 
2189 	/* schedule napi in case we had pending packets
2190 	 * from the last time we disable napi
2191 	 */
2192 	for (i = 0; i < io_queue_count; i++)
2193 		napi_schedule(&adapter->ena_napi[i].napi);
2194 
2195 	return rc;
2196 
2197 err_up:
2198 	ena_destroy_all_tx_queues(adapter);
2199 	ena_free_all_io_tx_resources(adapter);
2200 	ena_destroy_all_rx_queues(adapter);
2201 	ena_free_all_io_rx_resources(adapter);
2202 err_create_queues_with_backoff:
2203 	ena_free_io_irq(adapter);
2204 err_req_irq:
2205 	ena_del_napi_in_range(adapter, 0, io_queue_count);
2206 
2207 	return rc;
2208 }
2209 
2210 void ena_down(struct ena_adapter *adapter)
2211 {
2212 	int io_queue_count = adapter->num_io_queues + adapter->xdp_num_queues;
2213 
2214 	netif_dbg(adapter, ifdown, adapter->netdev, "%s\n", __func__);
2215 
2216 	clear_bit(ENA_FLAG_DEV_UP, &adapter->flags);
2217 
2218 	ena_increase_stat(&adapter->dev_stats.interface_down, 1,
2219 			  &adapter->syncp);
2220 
2221 	netif_carrier_off(adapter->netdev);
2222 	netif_tx_disable(adapter->netdev);
2223 
2224 	/* After this point the napi handler won't enable the tx queue */
2225 	ena_napi_disable_in_range(adapter, 0, io_queue_count);
2226 
2227 	if (test_bit(ENA_FLAG_TRIGGER_RESET, &adapter->flags)) {
2228 		int rc;
2229 
2230 		rc = ena_com_dev_reset(adapter->ena_dev, adapter->reset_reason);
2231 		if (rc)
2232 			netif_err(adapter, ifdown, adapter->netdev,
2233 				  "Device reset failed\n");
2234 		/* stop submitting admin commands on a device that was reset */
2235 		ena_com_set_admin_running_state(adapter->ena_dev, false);
2236 	}
2237 
2238 	ena_destroy_all_io_queues(adapter);
2239 
2240 	ena_disable_io_intr_sync(adapter);
2241 	ena_free_io_irq(adapter);
2242 	ena_del_napi_in_range(adapter, 0, io_queue_count);
2243 
2244 	ena_free_all_tx_bufs(adapter);
2245 	ena_free_all_rx_bufs(adapter);
2246 	ena_free_all_io_tx_resources(adapter);
2247 	ena_free_all_io_rx_resources(adapter);
2248 }
2249 
2250 /* ena_open - Called when a network interface is made active
2251  * @netdev: network interface device structure
2252  *
2253  * Returns 0 on success, negative value on failure
2254  *
2255  * The open entry point is called when a network interface is made
2256  * active by the system (IFF_UP).  At this point all resources needed
2257  * for transmit and receive operations are allocated, the interrupt
2258  * handler is registered with the OS, the watchdog timer is started,
2259  * and the stack is notified that the interface is ready.
2260  */
2261 static int ena_open(struct net_device *netdev)
2262 {
2263 	struct ena_adapter *adapter = netdev_priv(netdev);
2264 	int rc;
2265 
2266 	/* Notify the stack of the actual queue counts. */
2267 	rc = netif_set_real_num_tx_queues(netdev, adapter->num_io_queues);
2268 	if (rc) {
2269 		netif_err(adapter, ifup, netdev, "Can't set num tx queues\n");
2270 		return rc;
2271 	}
2272 
2273 	rc = netif_set_real_num_rx_queues(netdev, adapter->num_io_queues);
2274 	if (rc) {
2275 		netif_err(adapter, ifup, netdev, "Can't set num rx queues\n");
2276 		return rc;
2277 	}
2278 
2279 	rc = ena_up(adapter);
2280 	if (rc)
2281 		return rc;
2282 
2283 	return rc;
2284 }
2285 
2286 /* ena_close - Disables a network interface
2287  * @netdev: network interface device structure
2288  *
2289  * Returns 0, this is not allowed to fail
2290  *
2291  * The close entry point is called when an interface is de-activated
2292  * by the OS.  The hardware is still under the drivers control, but
2293  * needs to be disabled.  A global MAC reset is issued to stop the
2294  * hardware, and all transmit and receive resources are freed.
2295  */
2296 static int ena_close(struct net_device *netdev)
2297 {
2298 	struct ena_adapter *adapter = netdev_priv(netdev);
2299 
2300 	netif_dbg(adapter, ifdown, netdev, "%s\n", __func__);
2301 
2302 	if (!test_bit(ENA_FLAG_DEVICE_RUNNING, &adapter->flags))
2303 		return 0;
2304 
2305 	if (test_bit(ENA_FLAG_DEV_UP, &adapter->flags))
2306 		ena_down(adapter);
2307 
2308 	/* Check for device status and issue reset if needed*/
2309 	check_for_admin_com_state(adapter);
2310 	if (unlikely(test_bit(ENA_FLAG_TRIGGER_RESET, &adapter->flags))) {
2311 		netif_err(adapter, ifdown, adapter->netdev,
2312 			  "Destroy failure, restarting device\n");
2313 		ena_dump_stats_to_dmesg(adapter);
2314 		/* rtnl lock already obtained in dev_ioctl() layer */
2315 		ena_destroy_device(adapter, false);
2316 		ena_restore_device(adapter);
2317 	}
2318 
2319 	return 0;
2320 }
2321 
2322 int ena_update_queue_params(struct ena_adapter *adapter,
2323 			    u32 new_tx_size,
2324 			    u32 new_rx_size,
2325 			    u32 new_llq_header_len)
2326 {
2327 	bool dev_was_up, large_llq_changed = false;
2328 	int rc = 0;
2329 
2330 	dev_was_up = test_bit(ENA_FLAG_DEV_UP, &adapter->flags);
2331 	ena_close(adapter->netdev);
2332 	adapter->requested_tx_ring_size = new_tx_size;
2333 	adapter->requested_rx_ring_size = new_rx_size;
2334 	ena_init_io_rings(adapter,
2335 			  0,
2336 			  adapter->xdp_num_queues +
2337 			  adapter->num_io_queues);
2338 
2339 	large_llq_changed = adapter->ena_dev->tx_mem_queue_type ==
2340 			    ENA_ADMIN_PLACEMENT_POLICY_DEV;
2341 	large_llq_changed &=
2342 		new_llq_header_len != adapter->ena_dev->tx_max_header_size;
2343 
2344 	/* a check that the configuration is valid is done by caller */
2345 	if (large_llq_changed) {
2346 		adapter->large_llq_header_enabled = !adapter->large_llq_header_enabled;
2347 
2348 		ena_destroy_device(adapter, false);
2349 		rc = ena_restore_device(adapter);
2350 	}
2351 
2352 	return dev_was_up && !rc ? ena_up(adapter) : rc;
2353 }
2354 
2355 int ena_set_rx_copybreak(struct ena_adapter *adapter, u32 rx_copybreak)
2356 {
2357 	struct ena_ring *rx_ring;
2358 	int i;
2359 
2360 	if (rx_copybreak > min_t(u16, adapter->netdev->mtu, ENA_PAGE_SIZE))
2361 		return -EINVAL;
2362 
2363 	adapter->rx_copybreak = rx_copybreak;
2364 
2365 	for (i = 0; i < adapter->num_io_queues; i++) {
2366 		rx_ring = &adapter->rx_ring[i];
2367 		rx_ring->rx_copybreak = rx_copybreak;
2368 	}
2369 
2370 	return 0;
2371 }
2372 
2373 int ena_update_queue_count(struct ena_adapter *adapter, u32 new_channel_count)
2374 {
2375 	struct ena_com_dev *ena_dev = adapter->ena_dev;
2376 	int prev_channel_count;
2377 	bool dev_was_up;
2378 
2379 	dev_was_up = test_bit(ENA_FLAG_DEV_UP, &adapter->flags);
2380 	ena_close(adapter->netdev);
2381 	prev_channel_count = adapter->num_io_queues;
2382 	adapter->num_io_queues = new_channel_count;
2383 	if (ena_xdp_present(adapter) &&
2384 	    ena_xdp_allowed(adapter) == ENA_XDP_ALLOWED) {
2385 		adapter->xdp_first_ring = new_channel_count;
2386 		adapter->xdp_num_queues = new_channel_count;
2387 		if (prev_channel_count > new_channel_count)
2388 			ena_xdp_exchange_program_rx_in_range(adapter,
2389 							     NULL,
2390 							     new_channel_count,
2391 							     prev_channel_count);
2392 		else
2393 			ena_xdp_exchange_program_rx_in_range(adapter,
2394 							     adapter->xdp_bpf_prog,
2395 							     prev_channel_count,
2396 							     new_channel_count);
2397 	}
2398 
2399 	/* We need to destroy the rss table so that the indirection
2400 	 * table will be reinitialized by ena_up()
2401 	 */
2402 	ena_com_rss_destroy(ena_dev);
2403 	ena_init_io_rings(adapter,
2404 			  0,
2405 			  adapter->xdp_num_queues +
2406 			  adapter->num_io_queues);
2407 	return dev_was_up ? ena_open(adapter->netdev) : 0;
2408 }
2409 
2410 static void ena_tx_csum(struct ena_com_tx_ctx *ena_tx_ctx,
2411 			struct sk_buff *skb,
2412 			bool disable_meta_caching)
2413 {
2414 	u32 mss = skb_shinfo(skb)->gso_size;
2415 	struct ena_com_tx_meta *ena_meta = &ena_tx_ctx->ena_meta;
2416 	u8 l4_protocol = 0;
2417 
2418 	if ((skb->ip_summed == CHECKSUM_PARTIAL) || mss) {
2419 		ena_tx_ctx->l4_csum_enable = 1;
2420 		if (mss) {
2421 			ena_tx_ctx->tso_enable = 1;
2422 			ena_meta->l4_hdr_len = tcp_hdr(skb)->doff;
2423 			ena_tx_ctx->l4_csum_partial = 0;
2424 		} else {
2425 			ena_tx_ctx->tso_enable = 0;
2426 			ena_meta->l4_hdr_len = 0;
2427 			ena_tx_ctx->l4_csum_partial = 1;
2428 		}
2429 
2430 		switch (ip_hdr(skb)->version) {
2431 		case IPVERSION:
2432 			ena_tx_ctx->l3_proto = ENA_ETH_IO_L3_PROTO_IPV4;
2433 			if (ip_hdr(skb)->frag_off & htons(IP_DF))
2434 				ena_tx_ctx->df = 1;
2435 			if (mss)
2436 				ena_tx_ctx->l3_csum_enable = 1;
2437 			l4_protocol = ip_hdr(skb)->protocol;
2438 			break;
2439 		case 6:
2440 			ena_tx_ctx->l3_proto = ENA_ETH_IO_L3_PROTO_IPV6;
2441 			l4_protocol = ipv6_hdr(skb)->nexthdr;
2442 			break;
2443 		default:
2444 			break;
2445 		}
2446 
2447 		if (l4_protocol == IPPROTO_TCP)
2448 			ena_tx_ctx->l4_proto = ENA_ETH_IO_L4_PROTO_TCP;
2449 		else
2450 			ena_tx_ctx->l4_proto = ENA_ETH_IO_L4_PROTO_UDP;
2451 
2452 		ena_meta->mss = mss;
2453 		ena_meta->l3_hdr_len = skb_network_header_len(skb);
2454 		ena_meta->l3_hdr_offset = skb_network_offset(skb);
2455 		ena_tx_ctx->meta_valid = 1;
2456 	} else if (disable_meta_caching) {
2457 		memset(ena_meta, 0, sizeof(*ena_meta));
2458 		ena_tx_ctx->meta_valid = 1;
2459 	} else {
2460 		ena_tx_ctx->meta_valid = 0;
2461 	}
2462 }
2463 
2464 static int ena_check_and_linearize_skb(struct ena_ring *tx_ring,
2465 				       struct sk_buff *skb)
2466 {
2467 	int num_frags, header_len, rc;
2468 
2469 	num_frags = skb_shinfo(skb)->nr_frags;
2470 	header_len = skb_headlen(skb);
2471 
2472 	if (num_frags < tx_ring->sgl_size)
2473 		return 0;
2474 
2475 	if ((num_frags == tx_ring->sgl_size) &&
2476 	    (header_len < tx_ring->tx_max_header_size))
2477 		return 0;
2478 
2479 	ena_increase_stat(&tx_ring->tx_stats.linearize, 1, &tx_ring->syncp);
2480 
2481 	rc = skb_linearize(skb);
2482 	if (unlikely(rc)) {
2483 		ena_increase_stat(&tx_ring->tx_stats.linearize_failed, 1,
2484 				  &tx_ring->syncp);
2485 	}
2486 
2487 	return rc;
2488 }
2489 
2490 static int ena_tx_map_skb(struct ena_ring *tx_ring,
2491 			  struct ena_tx_buffer *tx_info,
2492 			  struct sk_buff *skb,
2493 			  void **push_hdr,
2494 			  u16 *header_len)
2495 {
2496 	struct ena_adapter *adapter = tx_ring->adapter;
2497 	struct ena_com_buf *ena_buf;
2498 	dma_addr_t dma;
2499 	u32 skb_head_len, frag_len, last_frag;
2500 	u16 push_len = 0;
2501 	u16 delta = 0;
2502 	int i = 0;
2503 
2504 	skb_head_len = skb_headlen(skb);
2505 	tx_info->skb = skb;
2506 	ena_buf = tx_info->bufs;
2507 
2508 	if (tx_ring->tx_mem_queue_type == ENA_ADMIN_PLACEMENT_POLICY_DEV) {
2509 		/* When the device is LLQ mode, the driver will copy
2510 		 * the header into the device memory space.
2511 		 * the ena_com layer assume the header is in a linear
2512 		 * memory space.
2513 		 * This assumption might be wrong since part of the header
2514 		 * can be in the fragmented buffers.
2515 		 * Use skb_header_pointer to make sure the header is in a
2516 		 * linear memory space.
2517 		 */
2518 
2519 		push_len = min_t(u32, skb->len, tx_ring->tx_max_header_size);
2520 		*push_hdr = skb_header_pointer(skb, 0, push_len,
2521 					       tx_ring->push_buf_intermediate_buf);
2522 		*header_len = push_len;
2523 		if (unlikely(skb->data != *push_hdr)) {
2524 			ena_increase_stat(&tx_ring->tx_stats.llq_buffer_copy, 1,
2525 					  &tx_ring->syncp);
2526 
2527 			delta = push_len - skb_head_len;
2528 		}
2529 	} else {
2530 		*push_hdr = NULL;
2531 		*header_len = min_t(u32, skb_head_len,
2532 				    tx_ring->tx_max_header_size);
2533 	}
2534 
2535 	netif_dbg(adapter, tx_queued, adapter->netdev,
2536 		  "skb: %p header_buf->vaddr: %p push_len: %d\n", skb,
2537 		  *push_hdr, push_len);
2538 
2539 	if (skb_head_len > push_len) {
2540 		dma = dma_map_single(tx_ring->dev, skb->data + push_len,
2541 				     skb_head_len - push_len, DMA_TO_DEVICE);
2542 		if (unlikely(dma_mapping_error(tx_ring->dev, dma)))
2543 			goto error_report_dma_error;
2544 
2545 		ena_buf->paddr = dma;
2546 		ena_buf->len = skb_head_len - push_len;
2547 
2548 		ena_buf++;
2549 		tx_info->num_of_bufs++;
2550 		tx_info->map_linear_data = 1;
2551 	} else {
2552 		tx_info->map_linear_data = 0;
2553 	}
2554 
2555 	last_frag = skb_shinfo(skb)->nr_frags;
2556 
2557 	for (i = 0; i < last_frag; i++) {
2558 		const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2559 
2560 		frag_len = skb_frag_size(frag);
2561 
2562 		if (unlikely(delta >= frag_len)) {
2563 			delta -= frag_len;
2564 			continue;
2565 		}
2566 
2567 		dma = skb_frag_dma_map(tx_ring->dev, frag, delta,
2568 				       frag_len - delta, DMA_TO_DEVICE);
2569 		if (unlikely(dma_mapping_error(tx_ring->dev, dma)))
2570 			goto error_report_dma_error;
2571 
2572 		ena_buf->paddr = dma;
2573 		ena_buf->len = frag_len - delta;
2574 		ena_buf++;
2575 		tx_info->num_of_bufs++;
2576 		delta = 0;
2577 	}
2578 
2579 	return 0;
2580 
2581 error_report_dma_error:
2582 	ena_increase_stat(&tx_ring->tx_stats.dma_mapping_err, 1,
2583 			  &tx_ring->syncp);
2584 	netif_warn(adapter, tx_queued, adapter->netdev, "Failed to map skb\n");
2585 
2586 	tx_info->skb = NULL;
2587 
2588 	tx_info->num_of_bufs += i;
2589 	ena_unmap_tx_buff(tx_ring, tx_info);
2590 
2591 	return -EINVAL;
2592 }
2593 
2594 /* Called with netif_tx_lock. */
2595 static netdev_tx_t ena_start_xmit(struct sk_buff *skb, struct net_device *dev)
2596 {
2597 	struct ena_adapter *adapter = netdev_priv(dev);
2598 	struct ena_tx_buffer *tx_info;
2599 	struct ena_com_tx_ctx ena_tx_ctx;
2600 	struct ena_ring *tx_ring;
2601 	struct netdev_queue *txq;
2602 	void *push_hdr;
2603 	u16 next_to_use, req_id, header_len;
2604 	int qid, rc;
2605 
2606 	netif_dbg(adapter, tx_queued, dev, "%s skb %p\n", __func__, skb);
2607 	/*  Determine which tx ring we will be placed on */
2608 	qid = skb_get_queue_mapping(skb);
2609 	tx_ring = &adapter->tx_ring[qid];
2610 	txq = netdev_get_tx_queue(dev, qid);
2611 
2612 	rc = ena_check_and_linearize_skb(tx_ring, skb);
2613 	if (unlikely(rc))
2614 		goto error_drop_packet;
2615 
2616 	next_to_use = tx_ring->next_to_use;
2617 	req_id = tx_ring->free_ids[next_to_use];
2618 	tx_info = &tx_ring->tx_buffer_info[req_id];
2619 	tx_info->num_of_bufs = 0;
2620 
2621 	WARN(tx_info->skb, "SKB isn't NULL req_id %d\n", req_id);
2622 
2623 	rc = ena_tx_map_skb(tx_ring, tx_info, skb, &push_hdr, &header_len);
2624 	if (unlikely(rc))
2625 		goto error_drop_packet;
2626 
2627 	memset(&ena_tx_ctx, 0x0, sizeof(struct ena_com_tx_ctx));
2628 	ena_tx_ctx.ena_bufs = tx_info->bufs;
2629 	ena_tx_ctx.push_header = push_hdr;
2630 	ena_tx_ctx.num_bufs = tx_info->num_of_bufs;
2631 	ena_tx_ctx.req_id = req_id;
2632 	ena_tx_ctx.header_len = header_len;
2633 
2634 	/* set flags and meta data */
2635 	ena_tx_csum(&ena_tx_ctx, skb, tx_ring->disable_meta_caching);
2636 
2637 	rc = ena_xmit_common(adapter,
2638 			     tx_ring,
2639 			     tx_info,
2640 			     &ena_tx_ctx,
2641 			     next_to_use,
2642 			     skb->len);
2643 	if (rc)
2644 		goto error_unmap_dma;
2645 
2646 	netdev_tx_sent_queue(txq, skb->len);
2647 
2648 	/* stop the queue when no more space available, the packet can have up
2649 	 * to sgl_size + 2. one for the meta descriptor and one for header
2650 	 * (if the header is larger than tx_max_header_size).
2651 	 */
2652 	if (unlikely(!ena_com_sq_have_enough_space(tx_ring->ena_com_io_sq,
2653 						   tx_ring->sgl_size + 2))) {
2654 		netif_dbg(adapter, tx_queued, dev, "%s stop queue %d\n",
2655 			  __func__, qid);
2656 
2657 		netif_tx_stop_queue(txq);
2658 		ena_increase_stat(&tx_ring->tx_stats.queue_stop, 1,
2659 				  &tx_ring->syncp);
2660 
2661 		/* There is a rare condition where this function decide to
2662 		 * stop the queue but meanwhile clean_tx_irq updates
2663 		 * next_to_completion and terminates.
2664 		 * The queue will remain stopped forever.
2665 		 * To solve this issue add a mb() to make sure that
2666 		 * netif_tx_stop_queue() write is vissible before checking if
2667 		 * there is additional space in the queue.
2668 		 */
2669 		smp_mb();
2670 
2671 		if (ena_com_sq_have_enough_space(tx_ring->ena_com_io_sq,
2672 						 ENA_TX_WAKEUP_THRESH)) {
2673 			netif_tx_wake_queue(txq);
2674 			ena_increase_stat(&tx_ring->tx_stats.queue_wakeup, 1,
2675 					  &tx_ring->syncp);
2676 		}
2677 	}
2678 
2679 	skb_tx_timestamp(skb);
2680 
2681 	if (netif_xmit_stopped(txq) || !netdev_xmit_more())
2682 		/* trigger the dma engine. ena_ring_tx_doorbell()
2683 		 * calls a memory barrier inside it.
2684 		 */
2685 		ena_ring_tx_doorbell(tx_ring);
2686 
2687 	return NETDEV_TX_OK;
2688 
2689 error_unmap_dma:
2690 	ena_unmap_tx_buff(tx_ring, tx_info);
2691 	tx_info->skb = NULL;
2692 
2693 error_drop_packet:
2694 	dev_kfree_skb(skb);
2695 	return NETDEV_TX_OK;
2696 }
2697 
2698 static void ena_config_host_info(struct ena_com_dev *ena_dev, struct pci_dev *pdev)
2699 {
2700 	struct device *dev = &pdev->dev;
2701 	struct ena_admin_host_info *host_info;
2702 	ssize_t ret;
2703 	int rc;
2704 
2705 	/* Allocate only the host info */
2706 	rc = ena_com_allocate_host_info(ena_dev);
2707 	if (rc) {
2708 		dev_err(dev, "Cannot allocate host info\n");
2709 		return;
2710 	}
2711 
2712 	host_info = ena_dev->host_attr.host_info;
2713 
2714 	host_info->bdf = pci_dev_id(pdev);
2715 	host_info->os_type = ENA_ADMIN_OS_LINUX;
2716 	host_info->kernel_ver = LINUX_VERSION_CODE;
2717 	ret = strscpy(host_info->kernel_ver_str, utsname()->version,
2718 		      sizeof(host_info->kernel_ver_str));
2719 	if (ret < 0)
2720 		dev_dbg(dev,
2721 			"kernel version string will be truncated, status = %zd\n", ret);
2722 
2723 	host_info->os_dist = 0;
2724 	ret = strscpy(host_info->os_dist_str, utsname()->release,
2725 		      sizeof(host_info->os_dist_str));
2726 	if (ret < 0)
2727 		dev_dbg(dev,
2728 			"OS distribution string will be truncated, status = %zd\n", ret);
2729 
2730 	host_info->driver_version =
2731 		(DRV_MODULE_GEN_MAJOR) |
2732 		(DRV_MODULE_GEN_MINOR << ENA_ADMIN_HOST_INFO_MINOR_SHIFT) |
2733 		(DRV_MODULE_GEN_SUBMINOR << ENA_ADMIN_HOST_INFO_SUB_MINOR_SHIFT) |
2734 		("K"[0] << ENA_ADMIN_HOST_INFO_MODULE_TYPE_SHIFT);
2735 	host_info->num_cpus = num_online_cpus();
2736 
2737 	host_info->driver_supported_features =
2738 		ENA_ADMIN_HOST_INFO_RX_OFFSET_MASK |
2739 		ENA_ADMIN_HOST_INFO_INTERRUPT_MODERATION_MASK |
2740 		ENA_ADMIN_HOST_INFO_RX_BUF_MIRRORING_MASK |
2741 		ENA_ADMIN_HOST_INFO_RSS_CONFIGURABLE_FUNCTION_KEY_MASK |
2742 		ENA_ADMIN_HOST_INFO_RX_PAGE_REUSE_MASK;
2743 
2744 	rc = ena_com_set_host_attributes(ena_dev);
2745 	if (rc) {
2746 		if (rc == -EOPNOTSUPP)
2747 			dev_warn(dev, "Cannot set host attributes\n");
2748 		else
2749 			dev_err(dev, "Cannot set host attributes\n");
2750 
2751 		goto err;
2752 	}
2753 
2754 	return;
2755 
2756 err:
2757 	ena_com_delete_host_info(ena_dev);
2758 }
2759 
2760 static void ena_config_debug_area(struct ena_adapter *adapter)
2761 {
2762 	u32 debug_area_size;
2763 	int rc, ss_count;
2764 
2765 	ss_count = ena_get_sset_count(adapter->netdev, ETH_SS_STATS);
2766 	if (ss_count <= 0) {
2767 		netif_err(adapter, drv, adapter->netdev,
2768 			  "SS count is negative\n");
2769 		return;
2770 	}
2771 
2772 	/* allocate 32 bytes for each string and 64bit for the value */
2773 	debug_area_size = ss_count * ETH_GSTRING_LEN + sizeof(u64) * ss_count;
2774 
2775 	rc = ena_com_allocate_debug_area(adapter->ena_dev, debug_area_size);
2776 	if (rc) {
2777 		netif_err(adapter, drv, adapter->netdev,
2778 			  "Cannot allocate debug area\n");
2779 		return;
2780 	}
2781 
2782 	rc = ena_com_set_host_attributes(adapter->ena_dev);
2783 	if (rc) {
2784 		if (rc == -EOPNOTSUPP)
2785 			netif_warn(adapter, drv, adapter->netdev, "Cannot set host attributes\n");
2786 		else
2787 			netif_err(adapter, drv, adapter->netdev,
2788 				  "Cannot set host attributes\n");
2789 		goto err;
2790 	}
2791 
2792 	return;
2793 err:
2794 	ena_com_delete_debug_area(adapter->ena_dev);
2795 }
2796 
2797 static void ena_get_stats64(struct net_device *netdev,
2798 			    struct rtnl_link_stats64 *stats)
2799 {
2800 	struct ena_adapter *adapter = netdev_priv(netdev);
2801 	struct ena_ring *rx_ring, *tx_ring;
2802 	u64 total_xdp_rx_drops = 0;
2803 	unsigned int start;
2804 	u64 rx_drops;
2805 	u64 tx_drops;
2806 	int i;
2807 
2808 	if (!test_bit(ENA_FLAG_DEV_UP, &adapter->flags))
2809 		return;
2810 
2811 	for (i = 0; i < adapter->num_io_queues + adapter->xdp_num_queues; i++) {
2812 		u64 bytes, packets, xdp_rx_drops;
2813 
2814 		tx_ring = &adapter->tx_ring[i];
2815 
2816 		do {
2817 			start = u64_stats_fetch_begin(&tx_ring->syncp);
2818 			packets = tx_ring->tx_stats.cnt;
2819 			bytes = tx_ring->tx_stats.bytes;
2820 		} while (u64_stats_fetch_retry(&tx_ring->syncp, start));
2821 
2822 		stats->tx_packets += packets;
2823 		stats->tx_bytes += bytes;
2824 
2825 		/* In XDP there isn't an RX queue counterpart */
2826 		if (ENA_IS_XDP_INDEX(adapter, i))
2827 			continue;
2828 
2829 		rx_ring = &adapter->rx_ring[i];
2830 
2831 		do {
2832 			start = u64_stats_fetch_begin(&rx_ring->syncp);
2833 			packets = rx_ring->rx_stats.cnt;
2834 			bytes = rx_ring->rx_stats.bytes;
2835 			xdp_rx_drops = rx_ring->rx_stats.xdp_drop;
2836 		} while (u64_stats_fetch_retry(&rx_ring->syncp, start));
2837 
2838 		stats->rx_packets += packets;
2839 		stats->rx_bytes += bytes;
2840 		total_xdp_rx_drops += xdp_rx_drops;
2841 	}
2842 
2843 	do {
2844 		start = u64_stats_fetch_begin(&adapter->syncp);
2845 		rx_drops = adapter->dev_stats.rx_drops;
2846 		tx_drops = adapter->dev_stats.tx_drops;
2847 	} while (u64_stats_fetch_retry(&adapter->syncp, start));
2848 
2849 	stats->rx_dropped = rx_drops + total_xdp_rx_drops;
2850 	stats->tx_dropped = tx_drops;
2851 
2852 	stats->multicast = 0;
2853 	stats->collisions = 0;
2854 
2855 	stats->rx_length_errors = 0;
2856 	stats->rx_crc_errors = 0;
2857 	stats->rx_frame_errors = 0;
2858 	stats->rx_fifo_errors = 0;
2859 	stats->rx_missed_errors = 0;
2860 	stats->tx_window_errors = 0;
2861 
2862 	stats->rx_errors = 0;
2863 	stats->tx_errors = 0;
2864 }
2865 
2866 static const struct net_device_ops ena_netdev_ops = {
2867 	.ndo_open		= ena_open,
2868 	.ndo_stop		= ena_close,
2869 	.ndo_start_xmit		= ena_start_xmit,
2870 	.ndo_get_stats64	= ena_get_stats64,
2871 	.ndo_tx_timeout		= ena_tx_timeout,
2872 	.ndo_change_mtu		= ena_change_mtu,
2873 	.ndo_validate_addr	= eth_validate_addr,
2874 	.ndo_bpf		= ena_xdp,
2875 	.ndo_xdp_xmit		= ena_xdp_xmit,
2876 };
2877 
2878 static int ena_calc_io_queue_size(struct ena_adapter *adapter,
2879 				  struct ena_com_dev_get_features_ctx *get_feat_ctx)
2880 {
2881 	struct ena_admin_feature_llq_desc *llq = &get_feat_ctx->llq;
2882 	struct ena_com_dev *ena_dev = adapter->ena_dev;
2883 	u32 tx_queue_size = ENA_DEFAULT_RING_SIZE;
2884 	u32 rx_queue_size = ENA_DEFAULT_RING_SIZE;
2885 	u32 max_tx_queue_size;
2886 	u32 max_rx_queue_size;
2887 
2888 	/* If this function is called after driver load, the ring sizes have already
2889 	 * been configured. Take it into account when recalculating ring size.
2890 	 */
2891 	if (adapter->tx_ring->ring_size)
2892 		tx_queue_size = adapter->tx_ring->ring_size;
2893 
2894 	if (adapter->rx_ring->ring_size)
2895 		rx_queue_size = adapter->rx_ring->ring_size;
2896 
2897 	if (ena_dev->supported_features & BIT(ENA_ADMIN_MAX_QUEUES_EXT)) {
2898 		struct ena_admin_queue_ext_feature_fields *max_queue_ext =
2899 			&get_feat_ctx->max_queue_ext.max_queue_ext;
2900 		max_rx_queue_size = min_t(u32, max_queue_ext->max_rx_cq_depth,
2901 					  max_queue_ext->max_rx_sq_depth);
2902 		max_tx_queue_size = max_queue_ext->max_tx_cq_depth;
2903 
2904 		if (ena_dev->tx_mem_queue_type == ENA_ADMIN_PLACEMENT_POLICY_DEV)
2905 			max_tx_queue_size = min_t(u32, max_tx_queue_size,
2906 						  llq->max_llq_depth);
2907 		else
2908 			max_tx_queue_size = min_t(u32, max_tx_queue_size,
2909 						  max_queue_ext->max_tx_sq_depth);
2910 
2911 		adapter->max_tx_sgl_size = min_t(u16, ENA_PKT_MAX_BUFS,
2912 						 max_queue_ext->max_per_packet_tx_descs);
2913 		adapter->max_rx_sgl_size = min_t(u16, ENA_PKT_MAX_BUFS,
2914 						 max_queue_ext->max_per_packet_rx_descs);
2915 	} else {
2916 		struct ena_admin_queue_feature_desc *max_queues =
2917 			&get_feat_ctx->max_queues;
2918 		max_rx_queue_size = min_t(u32, max_queues->max_cq_depth,
2919 					  max_queues->max_sq_depth);
2920 		max_tx_queue_size = max_queues->max_cq_depth;
2921 
2922 		if (ena_dev->tx_mem_queue_type == ENA_ADMIN_PLACEMENT_POLICY_DEV)
2923 			max_tx_queue_size = min_t(u32, max_tx_queue_size,
2924 						  llq->max_llq_depth);
2925 		else
2926 			max_tx_queue_size = min_t(u32, max_tx_queue_size,
2927 						  max_queues->max_sq_depth);
2928 
2929 		adapter->max_tx_sgl_size = min_t(u16, ENA_PKT_MAX_BUFS,
2930 						 max_queues->max_packet_tx_descs);
2931 		adapter->max_rx_sgl_size = min_t(u16, ENA_PKT_MAX_BUFS,
2932 						 max_queues->max_packet_rx_descs);
2933 	}
2934 
2935 	max_tx_queue_size = rounddown_pow_of_two(max_tx_queue_size);
2936 	max_rx_queue_size = rounddown_pow_of_two(max_rx_queue_size);
2937 
2938 	if (max_tx_queue_size < ENA_MIN_RING_SIZE) {
2939 		netdev_err(adapter->netdev, "Device max TX queue size: %d < minimum: %d\n",
2940 			   max_tx_queue_size, ENA_MIN_RING_SIZE);
2941 		return -EINVAL;
2942 	}
2943 
2944 	if (max_rx_queue_size < ENA_MIN_RING_SIZE) {
2945 		netdev_err(adapter->netdev, "Device max RX queue size: %d < minimum: %d\n",
2946 			   max_rx_queue_size, ENA_MIN_RING_SIZE);
2947 		return -EINVAL;
2948 	}
2949 
2950 	/* When forcing large headers, we multiply the entry size by 2, and therefore divide
2951 	 * the queue size by 2, leaving the amount of memory used by the queues unchanged.
2952 	 */
2953 	if (adapter->large_llq_header_enabled) {
2954 		if ((llq->entry_size_ctrl_supported & ENA_ADMIN_LIST_ENTRY_SIZE_256B) &&
2955 		    ena_dev->tx_mem_queue_type == ENA_ADMIN_PLACEMENT_POLICY_DEV) {
2956 			max_tx_queue_size /= 2;
2957 			dev_info(&adapter->pdev->dev,
2958 				 "Forcing large headers and decreasing maximum TX queue size to %d\n",
2959 				 max_tx_queue_size);
2960 		} else {
2961 			dev_err(&adapter->pdev->dev,
2962 				"Forcing large headers failed: LLQ is disabled or device does not support large headers\n");
2963 
2964 			adapter->large_llq_header_enabled = false;
2965 		}
2966 	}
2967 
2968 	tx_queue_size = clamp_val(tx_queue_size, ENA_MIN_RING_SIZE,
2969 				  max_tx_queue_size);
2970 	rx_queue_size = clamp_val(rx_queue_size, ENA_MIN_RING_SIZE,
2971 				  max_rx_queue_size);
2972 
2973 	tx_queue_size = rounddown_pow_of_two(tx_queue_size);
2974 	rx_queue_size = rounddown_pow_of_two(rx_queue_size);
2975 
2976 	adapter->max_tx_ring_size  = max_tx_queue_size;
2977 	adapter->max_rx_ring_size = max_rx_queue_size;
2978 	adapter->requested_tx_ring_size = tx_queue_size;
2979 	adapter->requested_rx_ring_size = rx_queue_size;
2980 
2981 	return 0;
2982 }
2983 
2984 static int ena_device_validate_params(struct ena_adapter *adapter,
2985 				      struct ena_com_dev_get_features_ctx *get_feat_ctx)
2986 {
2987 	struct net_device *netdev = adapter->netdev;
2988 	int rc;
2989 
2990 	rc = ether_addr_equal(get_feat_ctx->dev_attr.mac_addr,
2991 			      adapter->mac_addr);
2992 	if (!rc) {
2993 		netif_err(adapter, drv, netdev,
2994 			  "Error, mac address are different\n");
2995 		return -EINVAL;
2996 	}
2997 
2998 	if (get_feat_ctx->dev_attr.max_mtu < netdev->mtu) {
2999 		netif_err(adapter, drv, netdev,
3000 			  "Error, device max mtu is smaller than netdev MTU\n");
3001 		return -EINVAL;
3002 	}
3003 
3004 	return 0;
3005 }
3006 
3007 static void set_default_llq_configurations(struct ena_adapter *adapter,
3008 					   struct ena_llq_configurations *llq_config,
3009 					   struct ena_admin_feature_llq_desc *llq)
3010 {
3011 	struct ena_com_dev *ena_dev = adapter->ena_dev;
3012 
3013 	llq_config->llq_header_location = ENA_ADMIN_INLINE_HEADER;
3014 	llq_config->llq_stride_ctrl = ENA_ADMIN_MULTIPLE_DESCS_PER_ENTRY;
3015 	llq_config->llq_num_decs_before_header = ENA_ADMIN_LLQ_NUM_DESCS_BEFORE_HEADER_2;
3016 
3017 	adapter->large_llq_header_supported =
3018 		!!(ena_dev->supported_features & BIT(ENA_ADMIN_LLQ));
3019 	adapter->large_llq_header_supported &=
3020 		!!(llq->entry_size_ctrl_supported &
3021 			ENA_ADMIN_LIST_ENTRY_SIZE_256B);
3022 
3023 	if ((llq->entry_size_ctrl_supported & ENA_ADMIN_LIST_ENTRY_SIZE_256B) &&
3024 	    adapter->large_llq_header_enabled) {
3025 		llq_config->llq_ring_entry_size = ENA_ADMIN_LIST_ENTRY_SIZE_256B;
3026 		llq_config->llq_ring_entry_size_value = 256;
3027 	} else {
3028 		llq_config->llq_ring_entry_size = ENA_ADMIN_LIST_ENTRY_SIZE_128B;
3029 		llq_config->llq_ring_entry_size_value = 128;
3030 	}
3031 }
3032 
3033 static int ena_set_queues_placement_policy(struct pci_dev *pdev,
3034 					   struct ena_com_dev *ena_dev,
3035 					   struct ena_admin_feature_llq_desc *llq,
3036 					   struct ena_llq_configurations *llq_default_configurations)
3037 {
3038 	int rc;
3039 	u32 llq_feature_mask;
3040 
3041 	llq_feature_mask = 1 << ENA_ADMIN_LLQ;
3042 	if (!(ena_dev->supported_features & llq_feature_mask)) {
3043 		dev_warn(&pdev->dev,
3044 			"LLQ is not supported Fallback to host mode policy.\n");
3045 		ena_dev->tx_mem_queue_type = ENA_ADMIN_PLACEMENT_POLICY_HOST;
3046 		return 0;
3047 	}
3048 
3049 	if (!ena_dev->mem_bar) {
3050 		netdev_err(ena_dev->net_device,
3051 			   "LLQ is advertised as supported but device doesn't expose mem bar\n");
3052 		ena_dev->tx_mem_queue_type = ENA_ADMIN_PLACEMENT_POLICY_HOST;
3053 		return 0;
3054 	}
3055 
3056 	rc = ena_com_config_dev_mode(ena_dev, llq, llq_default_configurations);
3057 	if (unlikely(rc)) {
3058 		dev_err(&pdev->dev,
3059 			"Failed to configure the device mode.  Fallback to host mode policy.\n");
3060 		ena_dev->tx_mem_queue_type = ENA_ADMIN_PLACEMENT_POLICY_HOST;
3061 	}
3062 
3063 	return 0;
3064 }
3065 
3066 static int ena_map_llq_mem_bar(struct pci_dev *pdev, struct ena_com_dev *ena_dev,
3067 			       int bars)
3068 {
3069 	bool has_mem_bar = !!(bars & BIT(ENA_MEM_BAR));
3070 
3071 	if (!has_mem_bar)
3072 		return 0;
3073 
3074 	ena_dev->mem_bar = devm_ioremap_wc(&pdev->dev,
3075 					   pci_resource_start(pdev, ENA_MEM_BAR),
3076 					   pci_resource_len(pdev, ENA_MEM_BAR));
3077 
3078 	if (!ena_dev->mem_bar)
3079 		return -EFAULT;
3080 
3081 	return 0;
3082 }
3083 
3084 static int ena_device_init(struct ena_adapter *adapter, struct pci_dev *pdev,
3085 			   struct ena_com_dev_get_features_ctx *get_feat_ctx,
3086 			   bool *wd_state)
3087 {
3088 	struct ena_com_dev *ena_dev = adapter->ena_dev;
3089 	struct net_device *netdev = adapter->netdev;
3090 	struct ena_llq_configurations llq_config;
3091 	struct device *dev = &pdev->dev;
3092 	bool readless_supported;
3093 	u32 aenq_groups;
3094 	int dma_width;
3095 	int rc;
3096 
3097 	rc = ena_com_mmio_reg_read_request_init(ena_dev);
3098 	if (rc) {
3099 		dev_err(dev, "Failed to init mmio read less\n");
3100 		return rc;
3101 	}
3102 
3103 	/* The PCIe configuration space revision id indicate if mmio reg
3104 	 * read is disabled
3105 	 */
3106 	readless_supported = !(pdev->revision & ENA_MMIO_DISABLE_REG_READ);
3107 	ena_com_set_mmio_read_mode(ena_dev, readless_supported);
3108 
3109 	rc = ena_com_dev_reset(ena_dev, ENA_REGS_RESET_NORMAL);
3110 	if (rc) {
3111 		dev_err(dev, "Can not reset device\n");
3112 		goto err_mmio_read_less;
3113 	}
3114 
3115 	rc = ena_com_validate_version(ena_dev);
3116 	if (rc) {
3117 		dev_err(dev, "Device version is too low\n");
3118 		goto err_mmio_read_less;
3119 	}
3120 
3121 	dma_width = ena_com_get_dma_width(ena_dev);
3122 	if (dma_width < 0) {
3123 		dev_err(dev, "Invalid dma width value %d", dma_width);
3124 		rc = dma_width;
3125 		goto err_mmio_read_less;
3126 	}
3127 
3128 	rc = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(dma_width));
3129 	if (rc) {
3130 		dev_err(dev, "dma_set_mask_and_coherent failed %d\n", rc);
3131 		goto err_mmio_read_less;
3132 	}
3133 
3134 	/* ENA admin level init */
3135 	rc = ena_com_admin_init(ena_dev, &aenq_handlers);
3136 	if (rc) {
3137 		dev_err(dev,
3138 			"Can not initialize ena admin queue with device\n");
3139 		goto err_mmio_read_less;
3140 	}
3141 
3142 	/* To enable the msix interrupts the driver needs to know the number
3143 	 * of queues. So the driver uses polling mode to retrieve this
3144 	 * information
3145 	 */
3146 	ena_com_set_admin_polling_mode(ena_dev, true);
3147 
3148 	ena_config_host_info(ena_dev, pdev);
3149 
3150 	/* Get Device Attributes*/
3151 	rc = ena_com_get_dev_attr_feat(ena_dev, get_feat_ctx);
3152 	if (rc) {
3153 		dev_err(dev, "Cannot get attribute for ena device rc=%d\n", rc);
3154 		goto err_admin_init;
3155 	}
3156 
3157 	/* Try to turn all the available aenq groups */
3158 	aenq_groups = BIT(ENA_ADMIN_LINK_CHANGE) |
3159 		BIT(ENA_ADMIN_FATAL_ERROR) |
3160 		BIT(ENA_ADMIN_WARNING) |
3161 		BIT(ENA_ADMIN_NOTIFICATION) |
3162 		BIT(ENA_ADMIN_KEEP_ALIVE);
3163 
3164 	aenq_groups &= get_feat_ctx->aenq.supported_groups;
3165 
3166 	rc = ena_com_set_aenq_config(ena_dev, aenq_groups);
3167 	if (rc) {
3168 		dev_err(dev, "Cannot configure aenq groups rc= %d\n", rc);
3169 		goto err_admin_init;
3170 	}
3171 
3172 	*wd_state = !!(aenq_groups & BIT(ENA_ADMIN_KEEP_ALIVE));
3173 
3174 	set_default_llq_configurations(adapter, &llq_config, &get_feat_ctx->llq);
3175 
3176 	rc = ena_set_queues_placement_policy(pdev, ena_dev, &get_feat_ctx->llq,
3177 					     &llq_config);
3178 	if (rc) {
3179 		netdev_err(netdev, "Cannot set queues placement policy rc= %d\n", rc);
3180 		goto err_admin_init;
3181 	}
3182 
3183 	rc = ena_calc_io_queue_size(adapter, get_feat_ctx);
3184 	if (unlikely(rc))
3185 		goto err_admin_init;
3186 
3187 	return 0;
3188 
3189 err_admin_init:
3190 	ena_com_abort_admin_commands(ena_dev);
3191 	ena_com_wait_for_abort_completion(ena_dev);
3192 	ena_com_delete_host_info(ena_dev);
3193 	ena_com_admin_destroy(ena_dev);
3194 err_mmio_read_less:
3195 	ena_com_mmio_reg_read_request_destroy(ena_dev);
3196 
3197 	return rc;
3198 }
3199 
3200 static int ena_enable_msix_and_set_admin_interrupts(struct ena_adapter *adapter)
3201 {
3202 	struct ena_com_dev *ena_dev = adapter->ena_dev;
3203 	struct device *dev = &adapter->pdev->dev;
3204 	int rc;
3205 
3206 	rc = ena_enable_msix(adapter);
3207 	if (rc) {
3208 		dev_err(dev, "Can not reserve msix vectors\n");
3209 		return rc;
3210 	}
3211 
3212 	ena_setup_mgmnt_intr(adapter);
3213 
3214 	rc = ena_request_mgmnt_irq(adapter);
3215 	if (rc) {
3216 		dev_err(dev, "Can not setup management interrupts\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 
3226 err_disable_msix:
3227 	ena_disable_msix(adapter);
3228 
3229 	return rc;
3230 }
3231 
3232 static int ena_destroy_device(struct ena_adapter *adapter, bool graceful)
3233 {
3234 	struct net_device *netdev = adapter->netdev;
3235 	struct ena_com_dev *ena_dev = adapter->ena_dev;
3236 	bool dev_up;
3237 	int rc = 0;
3238 
3239 	if (!test_bit(ENA_FLAG_DEVICE_RUNNING, &adapter->flags))
3240 		return 0;
3241 
3242 	netif_carrier_off(netdev);
3243 
3244 	del_timer_sync(&adapter->timer_service);
3245 
3246 	dev_up = test_bit(ENA_FLAG_DEV_UP, &adapter->flags);
3247 	adapter->dev_up_before_reset = dev_up;
3248 	if (!graceful)
3249 		ena_com_set_admin_running_state(ena_dev, false);
3250 
3251 	if (dev_up)
3252 		ena_down(adapter);
3253 
3254 	/* Stop the device from sending AENQ events (in case reset flag is set
3255 	 *  and device is up, ena_down() already reset the device.
3256 	 */
3257 	if (!(test_bit(ENA_FLAG_TRIGGER_RESET, &adapter->flags) && dev_up))
3258 		rc = ena_com_dev_reset(adapter->ena_dev, adapter->reset_reason);
3259 
3260 	ena_free_mgmnt_irq(adapter);
3261 
3262 	ena_disable_msix(adapter);
3263 
3264 	ena_com_abort_admin_commands(ena_dev);
3265 
3266 	ena_com_wait_for_abort_completion(ena_dev);
3267 
3268 	ena_com_admin_destroy(ena_dev);
3269 
3270 	ena_com_mmio_reg_read_request_destroy(ena_dev);
3271 
3272 	/* return reset reason to default value */
3273 	adapter->reset_reason = ENA_REGS_RESET_NORMAL;
3274 
3275 	clear_bit(ENA_FLAG_TRIGGER_RESET, &adapter->flags);
3276 	clear_bit(ENA_FLAG_DEVICE_RUNNING, &adapter->flags);
3277 
3278 	return rc;
3279 }
3280 
3281 static int ena_restore_device(struct ena_adapter *adapter)
3282 {
3283 	struct ena_com_dev_get_features_ctx get_feat_ctx;
3284 	struct ena_com_dev *ena_dev = adapter->ena_dev;
3285 	struct pci_dev *pdev = adapter->pdev;
3286 	struct ena_ring *txr;
3287 	int rc, count, i;
3288 	bool wd_state;
3289 
3290 	set_bit(ENA_FLAG_ONGOING_RESET, &adapter->flags);
3291 	rc = ena_device_init(adapter, adapter->pdev, &get_feat_ctx, &wd_state);
3292 	if (rc) {
3293 		dev_err(&pdev->dev, "Can not initialize device\n");
3294 		goto err;
3295 	}
3296 	adapter->wd_state = wd_state;
3297 
3298 	count =  adapter->xdp_num_queues + adapter->num_io_queues;
3299 	for (i = 0 ; i < count; i++) {
3300 		txr = &adapter->tx_ring[i];
3301 		txr->tx_mem_queue_type = ena_dev->tx_mem_queue_type;
3302 		txr->tx_max_header_size = ena_dev->tx_max_header_size;
3303 	}
3304 
3305 	rc = ena_device_validate_params(adapter, &get_feat_ctx);
3306 	if (rc) {
3307 		dev_err(&pdev->dev, "Validation of device parameters failed\n");
3308 		goto err_device_destroy;
3309 	}
3310 
3311 	rc = ena_enable_msix_and_set_admin_interrupts(adapter);
3312 	if (rc) {
3313 		dev_err(&pdev->dev, "Enable MSI-X failed\n");
3314 		goto err_device_destroy;
3315 	}
3316 	/* If the interface was up before the reset bring it up */
3317 	if (adapter->dev_up_before_reset) {
3318 		rc = ena_up(adapter);
3319 		if (rc) {
3320 			dev_err(&pdev->dev, "Failed to create I/O queues\n");
3321 			goto err_disable_msix;
3322 		}
3323 	}
3324 
3325 	set_bit(ENA_FLAG_DEVICE_RUNNING, &adapter->flags);
3326 
3327 	clear_bit(ENA_FLAG_ONGOING_RESET, &adapter->flags);
3328 	if (test_bit(ENA_FLAG_LINK_UP, &adapter->flags))
3329 		netif_carrier_on(adapter->netdev);
3330 
3331 	mod_timer(&adapter->timer_service, round_jiffies(jiffies + HZ));
3332 	adapter->last_keep_alive_jiffies = jiffies;
3333 
3334 	return rc;
3335 err_disable_msix:
3336 	ena_free_mgmnt_irq(adapter);
3337 	ena_disable_msix(adapter);
3338 err_device_destroy:
3339 	ena_com_abort_admin_commands(ena_dev);
3340 	ena_com_wait_for_abort_completion(ena_dev);
3341 	ena_com_admin_destroy(ena_dev);
3342 	ena_com_dev_reset(ena_dev, ENA_REGS_RESET_DRIVER_INVALID_STATE);
3343 	ena_com_mmio_reg_read_request_destroy(ena_dev);
3344 err:
3345 	clear_bit(ENA_FLAG_DEVICE_RUNNING, &adapter->flags);
3346 	clear_bit(ENA_FLAG_ONGOING_RESET, &adapter->flags);
3347 	dev_err(&pdev->dev,
3348 		"Reset attempt failed. Can not reset the device\n");
3349 
3350 	return rc;
3351 }
3352 
3353 static void ena_fw_reset_device(struct work_struct *work)
3354 {
3355 	int rc = 0;
3356 
3357 	struct ena_adapter *adapter =
3358 		container_of(work, struct ena_adapter, reset_task);
3359 
3360 	rtnl_lock();
3361 
3362 	if (likely(test_bit(ENA_FLAG_TRIGGER_RESET, &adapter->flags))) {
3363 		rc |= ena_destroy_device(adapter, false);
3364 		rc |= ena_restore_device(adapter);
3365 		adapter->dev_stats.reset_fail += !!rc;
3366 
3367 		dev_err(&adapter->pdev->dev, "Device reset completed successfully\n");
3368 	}
3369 
3370 	rtnl_unlock();
3371 }
3372 
3373 static int check_for_rx_interrupt_queue(struct ena_adapter *adapter,
3374 					struct ena_ring *rx_ring)
3375 {
3376 	struct ena_napi *ena_napi = container_of(rx_ring->napi, struct ena_napi, napi);
3377 
3378 	if (likely(READ_ONCE(ena_napi->first_interrupt)))
3379 		return 0;
3380 
3381 	if (ena_com_cq_empty(rx_ring->ena_com_io_cq))
3382 		return 0;
3383 
3384 	rx_ring->no_interrupt_event_cnt++;
3385 
3386 	if (rx_ring->no_interrupt_event_cnt == ENA_MAX_NO_INTERRUPT_ITERATIONS) {
3387 		netif_err(adapter, rx_err, adapter->netdev,
3388 			  "Potential MSIX issue on Rx side Queue = %d. Reset the device\n",
3389 			  rx_ring->qid);
3390 
3391 		ena_reset_device(adapter, ENA_REGS_RESET_MISS_INTERRUPT);
3392 		return -EIO;
3393 	}
3394 
3395 	return 0;
3396 }
3397 
3398 static int check_missing_comp_in_tx_queue(struct ena_adapter *adapter,
3399 					  struct ena_ring *tx_ring)
3400 {
3401 	struct ena_napi *ena_napi = container_of(tx_ring->napi, struct ena_napi, napi);
3402 	enum ena_regs_reset_reason_types reset_reason = ENA_REGS_RESET_MISS_TX_CMPL;
3403 	unsigned int time_since_last_napi;
3404 	unsigned int missing_tx_comp_to;
3405 	bool is_tx_comp_time_expired;
3406 	struct ena_tx_buffer *tx_buf;
3407 	unsigned long last_jiffies;
3408 	int napi_scheduled;
3409 	u32 missed_tx = 0;
3410 	int i, rc = 0;
3411 
3412 	missing_tx_comp_to = jiffies_to_msecs(adapter->missing_tx_completion_to);
3413 
3414 	for (i = 0; i < tx_ring->ring_size; i++) {
3415 		tx_buf = &tx_ring->tx_buffer_info[i];
3416 		last_jiffies = tx_buf->last_jiffies;
3417 
3418 		if (last_jiffies == 0)
3419 			/* no pending Tx at this location */
3420 			continue;
3421 
3422 		is_tx_comp_time_expired = time_is_before_jiffies(last_jiffies +
3423 			 2 * adapter->missing_tx_completion_to);
3424 
3425 		if (unlikely(!READ_ONCE(ena_napi->first_interrupt) && is_tx_comp_time_expired)) {
3426 			/* If after graceful period interrupt is still not
3427 			 * received, we schedule a reset
3428 			 */
3429 			netif_err(adapter, tx_err, adapter->netdev,
3430 				  "Potential MSIX issue on Tx side Queue = %d. Reset the device\n",
3431 				  tx_ring->qid);
3432 			ena_reset_device(adapter, ENA_REGS_RESET_MISS_INTERRUPT);
3433 			return -EIO;
3434 		}
3435 
3436 		is_tx_comp_time_expired = time_is_before_jiffies(last_jiffies +
3437 			adapter->missing_tx_completion_to);
3438 
3439 		if (unlikely(is_tx_comp_time_expired)) {
3440 			time_since_last_napi =
3441 				jiffies_to_usecs(jiffies - tx_ring->tx_stats.last_napi_jiffies);
3442 			napi_scheduled = !!(ena_napi->napi.state & NAPIF_STATE_SCHED);
3443 
3444 			if (missing_tx_comp_to < time_since_last_napi && napi_scheduled) {
3445 				/* We suspect napi isn't called because the
3446 				 * bottom half is not run. Require a bigger
3447 				 * timeout for these cases
3448 				 */
3449 				if (!time_is_before_jiffies(last_jiffies +
3450 					2 * adapter->missing_tx_completion_to))
3451 					continue;
3452 
3453 				reset_reason = ENA_REGS_RESET_SUSPECTED_POLL_STARVATION;
3454 			}
3455 
3456 			missed_tx++;
3457 
3458 			if (tx_buf->print_once)
3459 				continue;
3460 
3461 			netif_notice(adapter, tx_err, adapter->netdev,
3462 				     "TX hasn't completed, qid %d, index %d. %u usecs from last napi execution, napi scheduled: %d\n",
3463 				     tx_ring->qid, i, time_since_last_napi, napi_scheduled);
3464 
3465 			tx_buf->print_once = 1;
3466 		}
3467 	}
3468 
3469 	if (unlikely(missed_tx > adapter->missing_tx_completion_threshold)) {
3470 		netif_err(adapter, tx_err, adapter->netdev,
3471 			  "Lost TX completions are above the threshold (%d > %d). Completion transmission timeout: %u.\n",
3472 			  missed_tx,
3473 			  adapter->missing_tx_completion_threshold,
3474 			  missing_tx_comp_to);
3475 		netif_err(adapter, tx_err, adapter->netdev,
3476 			  "Resetting the device\n");
3477 
3478 		ena_reset_device(adapter, reset_reason);
3479 		rc = -EIO;
3480 	}
3481 
3482 	ena_increase_stat(&tx_ring->tx_stats.missed_tx, missed_tx,
3483 			  &tx_ring->syncp);
3484 
3485 	return rc;
3486 }
3487 
3488 static void check_for_missing_completions(struct ena_adapter *adapter)
3489 {
3490 	struct ena_ring *tx_ring;
3491 	struct ena_ring *rx_ring;
3492 	int qid, budget, rc;
3493 	int io_queue_count;
3494 
3495 	io_queue_count = adapter->xdp_num_queues + adapter->num_io_queues;
3496 
3497 	/* Make sure the driver doesn't turn the device in other process */
3498 	smp_rmb();
3499 
3500 	if (!test_bit(ENA_FLAG_DEV_UP, &adapter->flags))
3501 		return;
3502 
3503 	if (test_bit(ENA_FLAG_TRIGGER_RESET, &adapter->flags))
3504 		return;
3505 
3506 	if (adapter->missing_tx_completion_to == ENA_HW_HINTS_NO_TIMEOUT)
3507 		return;
3508 
3509 	budget = min_t(u32, io_queue_count, ENA_MONITORED_TX_QUEUES);
3510 
3511 	qid = adapter->last_monitored_tx_qid;
3512 
3513 	while (budget) {
3514 		qid = (qid + 1) % io_queue_count;
3515 
3516 		tx_ring = &adapter->tx_ring[qid];
3517 		rx_ring = &adapter->rx_ring[qid];
3518 
3519 		rc = check_missing_comp_in_tx_queue(adapter, tx_ring);
3520 		if (unlikely(rc))
3521 			return;
3522 
3523 		rc =  !ENA_IS_XDP_INDEX(adapter, qid) ?
3524 			check_for_rx_interrupt_queue(adapter, rx_ring) : 0;
3525 		if (unlikely(rc))
3526 			return;
3527 
3528 		budget--;
3529 	}
3530 
3531 	adapter->last_monitored_tx_qid = qid;
3532 }
3533 
3534 /* trigger napi schedule after 2 consecutive detections */
3535 #define EMPTY_RX_REFILL 2
3536 /* For the rare case where the device runs out of Rx descriptors and the
3537  * napi handler failed to refill new Rx descriptors (due to a lack of memory
3538  * for example).
3539  * This case will lead to a deadlock:
3540  * The device won't send interrupts since all the new Rx packets will be dropped
3541  * The napi handler won't allocate new Rx descriptors so the device will be
3542  * able to send new packets.
3543  *
3544  * This scenario can happen when the kernel's vm.min_free_kbytes is too small.
3545  * It is recommended to have at least 512MB, with a minimum of 128MB for
3546  * constrained environment).
3547  *
3548  * When such a situation is detected - Reschedule napi
3549  */
3550 static void check_for_empty_rx_ring(struct ena_adapter *adapter)
3551 {
3552 	struct ena_ring *rx_ring;
3553 	int i, refill_required;
3554 
3555 	if (!test_bit(ENA_FLAG_DEV_UP, &adapter->flags))
3556 		return;
3557 
3558 	if (test_bit(ENA_FLAG_TRIGGER_RESET, &adapter->flags))
3559 		return;
3560 
3561 	for (i = 0; i < adapter->num_io_queues; i++) {
3562 		rx_ring = &adapter->rx_ring[i];
3563 
3564 		refill_required = ena_com_free_q_entries(rx_ring->ena_com_io_sq);
3565 		if (unlikely(refill_required == (rx_ring->ring_size - 1))) {
3566 			rx_ring->empty_rx_queue++;
3567 
3568 			if (rx_ring->empty_rx_queue >= EMPTY_RX_REFILL) {
3569 				ena_increase_stat(&rx_ring->rx_stats.empty_rx_ring, 1,
3570 						  &rx_ring->syncp);
3571 
3572 				netif_err(adapter, drv, adapter->netdev,
3573 					  "Trigger refill for ring %d\n", i);
3574 
3575 				napi_schedule(rx_ring->napi);
3576 				rx_ring->empty_rx_queue = 0;
3577 			}
3578 		} else {
3579 			rx_ring->empty_rx_queue = 0;
3580 		}
3581 	}
3582 }
3583 
3584 /* Check for keep alive expiration */
3585 static void check_for_missing_keep_alive(struct ena_adapter *adapter)
3586 {
3587 	unsigned long keep_alive_expired;
3588 
3589 	if (!adapter->wd_state)
3590 		return;
3591 
3592 	if (adapter->keep_alive_timeout == ENA_HW_HINTS_NO_TIMEOUT)
3593 		return;
3594 
3595 	keep_alive_expired = adapter->last_keep_alive_jiffies +
3596 			     adapter->keep_alive_timeout;
3597 	if (unlikely(time_is_before_jiffies(keep_alive_expired))) {
3598 		netif_err(adapter, drv, adapter->netdev,
3599 			  "Keep alive watchdog timeout.\n");
3600 		ena_increase_stat(&adapter->dev_stats.wd_expired, 1,
3601 				  &adapter->syncp);
3602 		ena_reset_device(adapter, ENA_REGS_RESET_KEEP_ALIVE_TO);
3603 	}
3604 }
3605 
3606 static void check_for_admin_com_state(struct ena_adapter *adapter)
3607 {
3608 	if (unlikely(!ena_com_get_admin_running_state(adapter->ena_dev))) {
3609 		netif_err(adapter, drv, adapter->netdev,
3610 			  "ENA admin queue is not in running state!\n");
3611 		ena_increase_stat(&adapter->dev_stats.admin_q_pause, 1,
3612 				  &adapter->syncp);
3613 		ena_reset_device(adapter, ENA_REGS_RESET_ADMIN_TO);
3614 	}
3615 }
3616 
3617 static void ena_update_hints(struct ena_adapter *adapter,
3618 			     struct ena_admin_ena_hw_hints *hints)
3619 {
3620 	struct net_device *netdev = adapter->netdev;
3621 
3622 	if (hints->admin_completion_tx_timeout)
3623 		adapter->ena_dev->admin_queue.completion_timeout =
3624 			hints->admin_completion_tx_timeout * 1000;
3625 
3626 	if (hints->mmio_read_timeout)
3627 		/* convert to usec */
3628 		adapter->ena_dev->mmio_read.reg_read_to =
3629 			hints->mmio_read_timeout * 1000;
3630 
3631 	if (hints->missed_tx_completion_count_threshold_to_reset)
3632 		adapter->missing_tx_completion_threshold =
3633 			hints->missed_tx_completion_count_threshold_to_reset;
3634 
3635 	if (hints->missing_tx_completion_timeout) {
3636 		if (hints->missing_tx_completion_timeout == ENA_HW_HINTS_NO_TIMEOUT)
3637 			adapter->missing_tx_completion_to = ENA_HW_HINTS_NO_TIMEOUT;
3638 		else
3639 			adapter->missing_tx_completion_to =
3640 				msecs_to_jiffies(hints->missing_tx_completion_timeout);
3641 	}
3642 
3643 	if (hints->netdev_wd_timeout)
3644 		netdev->watchdog_timeo = msecs_to_jiffies(hints->netdev_wd_timeout);
3645 
3646 	if (hints->driver_watchdog_timeout) {
3647 		if (hints->driver_watchdog_timeout == ENA_HW_HINTS_NO_TIMEOUT)
3648 			adapter->keep_alive_timeout = ENA_HW_HINTS_NO_TIMEOUT;
3649 		else
3650 			adapter->keep_alive_timeout =
3651 				msecs_to_jiffies(hints->driver_watchdog_timeout);
3652 	}
3653 }
3654 
3655 static void ena_update_host_info(struct ena_admin_host_info *host_info,
3656 				 struct net_device *netdev)
3657 {
3658 	host_info->supported_network_features[0] =
3659 		netdev->features & GENMASK_ULL(31, 0);
3660 	host_info->supported_network_features[1] =
3661 		(netdev->features & GENMASK_ULL(63, 32)) >> 32;
3662 }
3663 
3664 static void ena_timer_service(struct timer_list *t)
3665 {
3666 	struct ena_adapter *adapter = from_timer(adapter, t, timer_service);
3667 	u8 *debug_area = adapter->ena_dev->host_attr.debug_area_virt_addr;
3668 	struct ena_admin_host_info *host_info =
3669 		adapter->ena_dev->host_attr.host_info;
3670 
3671 	check_for_missing_keep_alive(adapter);
3672 
3673 	check_for_admin_com_state(adapter);
3674 
3675 	check_for_missing_completions(adapter);
3676 
3677 	check_for_empty_rx_ring(adapter);
3678 
3679 	if (debug_area)
3680 		ena_dump_stats_to_buf(adapter, debug_area);
3681 
3682 	if (host_info)
3683 		ena_update_host_info(host_info, adapter->netdev);
3684 
3685 	if (unlikely(test_bit(ENA_FLAG_TRIGGER_RESET, &adapter->flags))) {
3686 		netif_err(adapter, drv, adapter->netdev,
3687 			  "Trigger reset is on\n");
3688 		ena_dump_stats_to_dmesg(adapter);
3689 		queue_work(ena_wq, &adapter->reset_task);
3690 		return;
3691 	}
3692 
3693 	/* Reset the timer */
3694 	mod_timer(&adapter->timer_service, round_jiffies(jiffies + HZ));
3695 }
3696 
3697 static u32 ena_calc_max_io_queue_num(struct pci_dev *pdev,
3698 				     struct ena_com_dev *ena_dev,
3699 				     struct ena_com_dev_get_features_ctx *get_feat_ctx)
3700 {
3701 	u32 io_tx_sq_num, io_tx_cq_num, io_rx_num, max_num_io_queues;
3702 
3703 	if (ena_dev->supported_features & BIT(ENA_ADMIN_MAX_QUEUES_EXT)) {
3704 		struct ena_admin_queue_ext_feature_fields *max_queue_ext =
3705 			&get_feat_ctx->max_queue_ext.max_queue_ext;
3706 		io_rx_num = min_t(u32, max_queue_ext->max_rx_sq_num,
3707 				  max_queue_ext->max_rx_cq_num);
3708 
3709 		io_tx_sq_num = max_queue_ext->max_tx_sq_num;
3710 		io_tx_cq_num = max_queue_ext->max_tx_cq_num;
3711 	} else {
3712 		struct ena_admin_queue_feature_desc *max_queues =
3713 			&get_feat_ctx->max_queues;
3714 		io_tx_sq_num = max_queues->max_sq_num;
3715 		io_tx_cq_num = max_queues->max_cq_num;
3716 		io_rx_num = min_t(u32, io_tx_sq_num, io_tx_cq_num);
3717 	}
3718 
3719 	/* In case of LLQ use the llq fields for the tx SQ/CQ */
3720 	if (ena_dev->tx_mem_queue_type == ENA_ADMIN_PLACEMENT_POLICY_DEV)
3721 		io_tx_sq_num = get_feat_ctx->llq.max_llq_num;
3722 
3723 	max_num_io_queues = min_t(u32, num_online_cpus(), ENA_MAX_NUM_IO_QUEUES);
3724 	max_num_io_queues = min_t(u32, max_num_io_queues, io_rx_num);
3725 	max_num_io_queues = min_t(u32, max_num_io_queues, io_tx_sq_num);
3726 	max_num_io_queues = min_t(u32, max_num_io_queues, io_tx_cq_num);
3727 	/* 1 IRQ for mgmnt and 1 IRQs for each IO direction */
3728 	max_num_io_queues = min_t(u32, max_num_io_queues, pci_msix_vec_count(pdev) - 1);
3729 
3730 	return max_num_io_queues;
3731 }
3732 
3733 static void ena_set_dev_offloads(struct ena_com_dev_get_features_ctx *feat,
3734 				 struct net_device *netdev)
3735 {
3736 	netdev_features_t dev_features = 0;
3737 
3738 	/* Set offload features */
3739 	if (feat->offload.tx &
3740 		ENA_ADMIN_FEATURE_OFFLOAD_DESC_TX_L4_IPV4_CSUM_PART_MASK)
3741 		dev_features |= NETIF_F_IP_CSUM;
3742 
3743 	if (feat->offload.tx &
3744 		ENA_ADMIN_FEATURE_OFFLOAD_DESC_TX_L4_IPV6_CSUM_PART_MASK)
3745 		dev_features |= NETIF_F_IPV6_CSUM;
3746 
3747 	if (feat->offload.tx & ENA_ADMIN_FEATURE_OFFLOAD_DESC_TSO_IPV4_MASK)
3748 		dev_features |= NETIF_F_TSO;
3749 
3750 	if (feat->offload.tx & ENA_ADMIN_FEATURE_OFFLOAD_DESC_TSO_IPV6_MASK)
3751 		dev_features |= NETIF_F_TSO6;
3752 
3753 	if (feat->offload.tx & ENA_ADMIN_FEATURE_OFFLOAD_DESC_TSO_ECN_MASK)
3754 		dev_features |= NETIF_F_TSO_ECN;
3755 
3756 	if (feat->offload.rx_supported &
3757 		ENA_ADMIN_FEATURE_OFFLOAD_DESC_RX_L4_IPV4_CSUM_MASK)
3758 		dev_features |= NETIF_F_RXCSUM;
3759 
3760 	if (feat->offload.rx_supported &
3761 		ENA_ADMIN_FEATURE_OFFLOAD_DESC_RX_L4_IPV6_CSUM_MASK)
3762 		dev_features |= NETIF_F_RXCSUM;
3763 
3764 	netdev->features =
3765 		dev_features |
3766 		NETIF_F_SG |
3767 		NETIF_F_RXHASH |
3768 		NETIF_F_HIGHDMA;
3769 
3770 	netdev->hw_features |= netdev->features;
3771 	netdev->vlan_features |= netdev->features;
3772 }
3773 
3774 static void ena_set_conf_feat_params(struct ena_adapter *adapter,
3775 				     struct ena_com_dev_get_features_ctx *feat)
3776 {
3777 	struct net_device *netdev = adapter->netdev;
3778 
3779 	/* Copy mac address */
3780 	if (!is_valid_ether_addr(feat->dev_attr.mac_addr)) {
3781 		eth_hw_addr_random(netdev);
3782 		ether_addr_copy(adapter->mac_addr, netdev->dev_addr);
3783 	} else {
3784 		ether_addr_copy(adapter->mac_addr, feat->dev_attr.mac_addr);
3785 		eth_hw_addr_set(netdev, adapter->mac_addr);
3786 	}
3787 
3788 	/* Set offload features */
3789 	ena_set_dev_offloads(feat, netdev);
3790 
3791 	adapter->max_mtu = feat->dev_attr.max_mtu;
3792 	netdev->max_mtu = adapter->max_mtu;
3793 	netdev->min_mtu = ENA_MIN_MTU;
3794 }
3795 
3796 static int ena_rss_init_default(struct ena_adapter *adapter)
3797 {
3798 	struct ena_com_dev *ena_dev = adapter->ena_dev;
3799 	struct device *dev = &adapter->pdev->dev;
3800 	int rc, i;
3801 	u32 val;
3802 
3803 	rc = ena_com_rss_init(ena_dev, ENA_RX_RSS_TABLE_LOG_SIZE);
3804 	if (unlikely(rc)) {
3805 		dev_err(dev, "Cannot init indirect table\n");
3806 		goto err_rss_init;
3807 	}
3808 
3809 	for (i = 0; i < ENA_RX_RSS_TABLE_SIZE; i++) {
3810 		val = ethtool_rxfh_indir_default(i, adapter->num_io_queues);
3811 		rc = ena_com_indirect_table_fill_entry(ena_dev, i,
3812 						       ENA_IO_RXQ_IDX(val));
3813 		if (unlikely(rc)) {
3814 			dev_err(dev, "Cannot fill indirect table\n");
3815 			goto err_fill_indir;
3816 		}
3817 	}
3818 
3819 	rc = ena_com_fill_hash_function(ena_dev, ENA_ADMIN_TOEPLITZ, NULL, ENA_HASH_KEY_SIZE,
3820 					0xFFFFFFFF);
3821 	if (unlikely(rc && (rc != -EOPNOTSUPP))) {
3822 		dev_err(dev, "Cannot fill hash function\n");
3823 		goto err_fill_indir;
3824 	}
3825 
3826 	rc = ena_com_set_default_hash_ctrl(ena_dev);
3827 	if (unlikely(rc && (rc != -EOPNOTSUPP))) {
3828 		dev_err(dev, "Cannot fill hash control\n");
3829 		goto err_fill_indir;
3830 	}
3831 
3832 	return 0;
3833 
3834 err_fill_indir:
3835 	ena_com_rss_destroy(ena_dev);
3836 err_rss_init:
3837 
3838 	return rc;
3839 }
3840 
3841 static void ena_release_bars(struct ena_com_dev *ena_dev, struct pci_dev *pdev)
3842 {
3843 	int release_bars = pci_select_bars(pdev, IORESOURCE_MEM) & ENA_BAR_MASK;
3844 
3845 	pci_release_selected_regions(pdev, release_bars);
3846 }
3847 
3848 /* ena_probe - Device Initialization Routine
3849  * @pdev: PCI device information struct
3850  * @ent: entry in ena_pci_tbl
3851  *
3852  * Returns 0 on success, negative on failure
3853  *
3854  * ena_probe initializes an adapter identified by a pci_dev structure.
3855  * The OS initialization, configuring of the adapter private structure,
3856  * and a hardware reset occur.
3857  */
3858 static int ena_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
3859 {
3860 	struct ena_com_dev_get_features_ctx get_feat_ctx;
3861 	struct ena_com_dev *ena_dev = NULL;
3862 	struct ena_adapter *adapter;
3863 	struct net_device *netdev;
3864 	static int adapters_found;
3865 	u32 max_num_io_queues;
3866 	bool wd_state;
3867 	int bars, rc;
3868 
3869 	dev_dbg(&pdev->dev, "%s\n", __func__);
3870 
3871 	rc = pci_enable_device_mem(pdev);
3872 	if (rc) {
3873 		dev_err(&pdev->dev, "pci_enable_device_mem() failed!\n");
3874 		return rc;
3875 	}
3876 
3877 	rc = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(ENA_MAX_PHYS_ADDR_SIZE_BITS));
3878 	if (rc) {
3879 		dev_err(&pdev->dev, "dma_set_mask_and_coherent failed %d\n", rc);
3880 		goto err_disable_device;
3881 	}
3882 
3883 	pci_set_master(pdev);
3884 
3885 	ena_dev = vzalloc(sizeof(*ena_dev));
3886 	if (!ena_dev) {
3887 		rc = -ENOMEM;
3888 		goto err_disable_device;
3889 	}
3890 
3891 	bars = pci_select_bars(pdev, IORESOURCE_MEM) & ENA_BAR_MASK;
3892 	rc = pci_request_selected_regions(pdev, bars, DRV_MODULE_NAME);
3893 	if (rc) {
3894 		dev_err(&pdev->dev, "pci_request_selected_regions failed %d\n",
3895 			rc);
3896 		goto err_free_ena_dev;
3897 	}
3898 
3899 	ena_dev->reg_bar = devm_ioremap(&pdev->dev,
3900 					pci_resource_start(pdev, ENA_REG_BAR),
3901 					pci_resource_len(pdev, ENA_REG_BAR));
3902 	if (!ena_dev->reg_bar) {
3903 		dev_err(&pdev->dev, "Failed to remap regs bar\n");
3904 		rc = -EFAULT;
3905 		goto err_free_region;
3906 	}
3907 
3908 	ena_dev->ena_min_poll_delay_us = ENA_ADMIN_POLL_DELAY_US;
3909 
3910 	ena_dev->dmadev = &pdev->dev;
3911 
3912 	netdev = alloc_etherdev_mq(sizeof(struct ena_adapter), ENA_MAX_RINGS);
3913 	if (!netdev) {
3914 		dev_err(&pdev->dev, "alloc_etherdev_mq failed\n");
3915 		rc = -ENOMEM;
3916 		goto err_free_region;
3917 	}
3918 
3919 	SET_NETDEV_DEV(netdev, &pdev->dev);
3920 	adapter = netdev_priv(netdev);
3921 	adapter->ena_dev = ena_dev;
3922 	adapter->netdev = netdev;
3923 	adapter->pdev = pdev;
3924 	adapter->msg_enable = DEFAULT_MSG_ENABLE;
3925 
3926 	ena_dev->net_device = netdev;
3927 
3928 	pci_set_drvdata(pdev, adapter);
3929 
3930 	rc = ena_com_allocate_customer_metrics_buffer(ena_dev);
3931 	if (rc) {
3932 		netdev_err(netdev, "ena_com_allocate_customer_metrics_buffer failed\n");
3933 		goto err_netdev_destroy;
3934 	}
3935 
3936 	rc = ena_map_llq_mem_bar(pdev, ena_dev, bars);
3937 	if (rc) {
3938 		dev_err(&pdev->dev, "ENA LLQ bar mapping failed\n");
3939 		goto err_metrics_destroy;
3940 	}
3941 
3942 	rc = ena_device_init(adapter, pdev, &get_feat_ctx, &wd_state);
3943 	if (rc) {
3944 		dev_err(&pdev->dev, "ENA device init failed\n");
3945 		if (rc == -ETIME)
3946 			rc = -EPROBE_DEFER;
3947 		goto err_metrics_destroy;
3948 	}
3949 
3950 	/* Initial TX and RX interrupt delay. Assumes 1 usec granularity.
3951 	 * Updated during device initialization with the real granularity
3952 	 */
3953 	ena_dev->intr_moder_tx_interval = ENA_INTR_INITIAL_TX_INTERVAL_USECS;
3954 	ena_dev->intr_moder_rx_interval = ENA_INTR_INITIAL_RX_INTERVAL_USECS;
3955 	ena_dev->intr_delay_resolution = ENA_DEFAULT_INTR_DELAY_RESOLUTION;
3956 	max_num_io_queues = ena_calc_max_io_queue_num(pdev, ena_dev, &get_feat_ctx);
3957 	if (unlikely(!max_num_io_queues)) {
3958 		rc = -EFAULT;
3959 		goto err_device_destroy;
3960 	}
3961 
3962 	ena_set_conf_feat_params(adapter, &get_feat_ctx);
3963 
3964 	adapter->reset_reason = ENA_REGS_RESET_NORMAL;
3965 
3966 	adapter->num_io_queues = max_num_io_queues;
3967 	adapter->max_num_io_queues = max_num_io_queues;
3968 	adapter->last_monitored_tx_qid = 0;
3969 
3970 	adapter->xdp_first_ring = 0;
3971 	adapter->xdp_num_queues = 0;
3972 
3973 	adapter->rx_copybreak = ENA_DEFAULT_RX_COPYBREAK;
3974 	if (ena_dev->tx_mem_queue_type == ENA_ADMIN_PLACEMENT_POLICY_DEV)
3975 		adapter->disable_meta_caching =
3976 			!!(get_feat_ctx.llq.accel_mode.u.get.supported_flags &
3977 			   BIT(ENA_ADMIN_DISABLE_META_CACHING));
3978 
3979 	adapter->wd_state = wd_state;
3980 
3981 	snprintf(adapter->name, ENA_NAME_MAX_LEN, "ena_%d", adapters_found);
3982 
3983 	rc = ena_com_init_interrupt_moderation(adapter->ena_dev);
3984 	if (rc) {
3985 		dev_err(&pdev->dev,
3986 			"Failed to query interrupt moderation feature\n");
3987 		goto err_device_destroy;
3988 	}
3989 
3990 	ena_init_io_rings(adapter,
3991 			  0,
3992 			  adapter->xdp_num_queues +
3993 			  adapter->num_io_queues);
3994 
3995 	netdev->netdev_ops = &ena_netdev_ops;
3996 	netdev->watchdog_timeo = TX_TIMEOUT;
3997 	ena_set_ethtool_ops(netdev);
3998 
3999 	netdev->priv_flags |= IFF_UNICAST_FLT;
4000 
4001 	u64_stats_init(&adapter->syncp);
4002 
4003 	rc = ena_enable_msix_and_set_admin_interrupts(adapter);
4004 	if (rc) {
4005 		dev_err(&pdev->dev,
4006 			"Failed to enable and set the admin interrupts\n");
4007 		goto err_worker_destroy;
4008 	}
4009 	rc = ena_rss_init_default(adapter);
4010 	if (rc && (rc != -EOPNOTSUPP)) {
4011 		dev_err(&pdev->dev, "Cannot init RSS rc: %d\n", rc);
4012 		goto err_free_msix;
4013 	}
4014 
4015 	ena_config_debug_area(adapter);
4016 
4017 	if (ena_xdp_legal_queue_count(adapter, adapter->num_io_queues))
4018 		netdev->xdp_features = NETDEV_XDP_ACT_BASIC |
4019 				       NETDEV_XDP_ACT_REDIRECT;
4020 
4021 	memcpy(adapter->netdev->perm_addr, adapter->mac_addr, netdev->addr_len);
4022 
4023 	netif_carrier_off(netdev);
4024 
4025 	rc = register_netdev(netdev);
4026 	if (rc) {
4027 		dev_err(&pdev->dev, "Cannot register net device\n");
4028 		goto err_rss;
4029 	}
4030 
4031 	INIT_WORK(&adapter->reset_task, ena_fw_reset_device);
4032 
4033 	adapter->last_keep_alive_jiffies = jiffies;
4034 	adapter->keep_alive_timeout = ENA_DEVICE_KALIVE_TIMEOUT;
4035 	adapter->missing_tx_completion_to = TX_TIMEOUT;
4036 	adapter->missing_tx_completion_threshold = MAX_NUM_OF_TIMEOUTED_PACKETS;
4037 
4038 	ena_update_hints(adapter, &get_feat_ctx.hw_hints);
4039 
4040 	timer_setup(&adapter->timer_service, ena_timer_service, 0);
4041 	mod_timer(&adapter->timer_service, round_jiffies(jiffies + HZ));
4042 
4043 	dev_info(&pdev->dev,
4044 		 "%s found at mem %lx, mac addr %pM\n",
4045 		 DEVICE_NAME, (long)pci_resource_start(pdev, 0),
4046 		 netdev->dev_addr);
4047 
4048 	set_bit(ENA_FLAG_DEVICE_RUNNING, &adapter->flags);
4049 
4050 	adapters_found++;
4051 
4052 	return 0;
4053 
4054 err_rss:
4055 	ena_com_delete_debug_area(ena_dev);
4056 	ena_com_rss_destroy(ena_dev);
4057 err_free_msix:
4058 	ena_com_dev_reset(ena_dev, ENA_REGS_RESET_INIT_ERR);
4059 	/* stop submitting admin commands on a device that was reset */
4060 	ena_com_set_admin_running_state(ena_dev, false);
4061 	ena_free_mgmnt_irq(adapter);
4062 	ena_disable_msix(adapter);
4063 err_worker_destroy:
4064 	del_timer(&adapter->timer_service);
4065 err_device_destroy:
4066 	ena_com_delete_host_info(ena_dev);
4067 	ena_com_admin_destroy(ena_dev);
4068 err_metrics_destroy:
4069 	ena_com_delete_customer_metrics_buffer(ena_dev);
4070 err_netdev_destroy:
4071 	free_netdev(netdev);
4072 err_free_region:
4073 	ena_release_bars(ena_dev, pdev);
4074 err_free_ena_dev:
4075 	vfree(ena_dev);
4076 err_disable_device:
4077 	pci_disable_device(pdev);
4078 	return rc;
4079 }
4080 
4081 /*****************************************************************************/
4082 
4083 /* __ena_shutoff - Helper used in both PCI remove/shutdown routines
4084  * @pdev: PCI device information struct
4085  * @shutdown: Is it a shutdown operation? If false, means it is a removal
4086  *
4087  * __ena_shutoff is a helper routine that does the real work on shutdown and
4088  * removal paths; the difference between those paths is with regards to whether
4089  * dettach or unregister the netdevice.
4090  */
4091 static void __ena_shutoff(struct pci_dev *pdev, bool shutdown)
4092 {
4093 	struct ena_adapter *adapter = pci_get_drvdata(pdev);
4094 	struct ena_com_dev *ena_dev;
4095 	struct net_device *netdev;
4096 
4097 	ena_dev = adapter->ena_dev;
4098 	netdev = adapter->netdev;
4099 
4100 	/* Make sure timer and reset routine won't be called after
4101 	 * freeing device resources.
4102 	 */
4103 	del_timer_sync(&adapter->timer_service);
4104 	cancel_work_sync(&adapter->reset_task);
4105 
4106 	rtnl_lock(); /* lock released inside the below if-else block */
4107 	adapter->reset_reason = ENA_REGS_RESET_SHUTDOWN;
4108 	ena_destroy_device(adapter, true);
4109 
4110 	if (shutdown) {
4111 		netif_device_detach(netdev);
4112 		dev_close(netdev);
4113 		rtnl_unlock();
4114 	} else {
4115 		rtnl_unlock();
4116 		unregister_netdev(netdev);
4117 		free_netdev(netdev);
4118 	}
4119 
4120 	ena_com_rss_destroy(ena_dev);
4121 
4122 	ena_com_delete_debug_area(ena_dev);
4123 
4124 	ena_com_delete_host_info(ena_dev);
4125 
4126 	ena_com_delete_customer_metrics_buffer(ena_dev);
4127 
4128 	ena_release_bars(ena_dev, pdev);
4129 
4130 	pci_disable_device(pdev);
4131 
4132 	vfree(ena_dev);
4133 }
4134 
4135 /* ena_remove - Device Removal Routine
4136  * @pdev: PCI device information struct
4137  *
4138  * ena_remove is called by the PCI subsystem to alert the driver
4139  * that it should release a PCI device.
4140  */
4141 
4142 static void ena_remove(struct pci_dev *pdev)
4143 {
4144 	__ena_shutoff(pdev, false);
4145 }
4146 
4147 /* ena_shutdown - Device Shutdown Routine
4148  * @pdev: PCI device information struct
4149  *
4150  * ena_shutdown is called by the PCI subsystem to alert the driver that
4151  * a shutdown/reboot (or kexec) is happening and device must be disabled.
4152  */
4153 
4154 static void ena_shutdown(struct pci_dev *pdev)
4155 {
4156 	__ena_shutoff(pdev, true);
4157 }
4158 
4159 /* ena_suspend - PM suspend callback
4160  * @dev_d: Device information struct
4161  */
4162 static int __maybe_unused ena_suspend(struct device *dev_d)
4163 {
4164 	struct pci_dev *pdev = to_pci_dev(dev_d);
4165 	struct ena_adapter *adapter = pci_get_drvdata(pdev);
4166 
4167 	ena_increase_stat(&adapter->dev_stats.suspend, 1, &adapter->syncp);
4168 
4169 	rtnl_lock();
4170 	if (unlikely(test_bit(ENA_FLAG_TRIGGER_RESET, &adapter->flags))) {
4171 		dev_err(&pdev->dev,
4172 			"Ignoring device reset request as the device is being suspended\n");
4173 		clear_bit(ENA_FLAG_TRIGGER_RESET, &adapter->flags);
4174 	}
4175 	ena_destroy_device(adapter, true);
4176 	rtnl_unlock();
4177 	return 0;
4178 }
4179 
4180 /* ena_resume - PM resume callback
4181  * @dev_d: Device information struct
4182  */
4183 static int __maybe_unused ena_resume(struct device *dev_d)
4184 {
4185 	struct ena_adapter *adapter = dev_get_drvdata(dev_d);
4186 	int rc;
4187 
4188 	ena_increase_stat(&adapter->dev_stats.resume, 1, &adapter->syncp);
4189 
4190 	rtnl_lock();
4191 	rc = ena_restore_device(adapter);
4192 	rtnl_unlock();
4193 	return rc;
4194 }
4195 
4196 static SIMPLE_DEV_PM_OPS(ena_pm_ops, ena_suspend, ena_resume);
4197 
4198 static struct pci_driver ena_pci_driver = {
4199 	.name		= DRV_MODULE_NAME,
4200 	.id_table	= ena_pci_tbl,
4201 	.probe		= ena_probe,
4202 	.remove		= ena_remove,
4203 	.shutdown	= ena_shutdown,
4204 	.driver.pm	= &ena_pm_ops,
4205 	.sriov_configure = pci_sriov_configure_simple,
4206 };
4207 
4208 static int __init ena_init(void)
4209 {
4210 	int ret;
4211 
4212 	ena_wq = create_singlethread_workqueue(DRV_MODULE_NAME);
4213 	if (!ena_wq) {
4214 		pr_err("Failed to create workqueue\n");
4215 		return -ENOMEM;
4216 	}
4217 
4218 	ret = pci_register_driver(&ena_pci_driver);
4219 	if (ret)
4220 		destroy_workqueue(ena_wq);
4221 
4222 	return ret;
4223 }
4224 
4225 static void __exit ena_cleanup(void)
4226 {
4227 	pci_unregister_driver(&ena_pci_driver);
4228 
4229 	if (ena_wq) {
4230 		destroy_workqueue(ena_wq);
4231 		ena_wq = NULL;
4232 	}
4233 }
4234 
4235 /******************************************************************************
4236  ******************************** AENQ Handlers *******************************
4237  *****************************************************************************/
4238 /* ena_update_on_link_change:
4239  * Notify the network interface about the change in link status
4240  */
4241 static void ena_update_on_link_change(void *adapter_data,
4242 				      struct ena_admin_aenq_entry *aenq_e)
4243 {
4244 	struct ena_adapter *adapter = (struct ena_adapter *)adapter_data;
4245 	struct ena_admin_aenq_link_change_desc *aenq_desc =
4246 		(struct ena_admin_aenq_link_change_desc *)aenq_e;
4247 	int status = aenq_desc->flags &
4248 		ENA_ADMIN_AENQ_LINK_CHANGE_DESC_LINK_STATUS_MASK;
4249 
4250 	if (status) {
4251 		netif_dbg(adapter, ifup, adapter->netdev, "%s\n", __func__);
4252 		set_bit(ENA_FLAG_LINK_UP, &adapter->flags);
4253 		if (!test_bit(ENA_FLAG_ONGOING_RESET, &adapter->flags))
4254 			netif_carrier_on(adapter->netdev);
4255 	} else {
4256 		clear_bit(ENA_FLAG_LINK_UP, &adapter->flags);
4257 		netif_carrier_off(adapter->netdev);
4258 	}
4259 }
4260 
4261 static void ena_keep_alive_wd(void *adapter_data,
4262 			      struct ena_admin_aenq_entry *aenq_e)
4263 {
4264 	struct ena_adapter *adapter = (struct ena_adapter *)adapter_data;
4265 	struct ena_admin_aenq_keep_alive_desc *desc;
4266 	u64 rx_drops;
4267 	u64 tx_drops;
4268 
4269 	desc = (struct ena_admin_aenq_keep_alive_desc *)aenq_e;
4270 	adapter->last_keep_alive_jiffies = jiffies;
4271 
4272 	rx_drops = ((u64)desc->rx_drops_high << 32) | desc->rx_drops_low;
4273 	tx_drops = ((u64)desc->tx_drops_high << 32) | desc->tx_drops_low;
4274 
4275 	u64_stats_update_begin(&adapter->syncp);
4276 	/* These stats are accumulated by the device, so the counters indicate
4277 	 * all drops since last reset.
4278 	 */
4279 	adapter->dev_stats.rx_drops = rx_drops;
4280 	adapter->dev_stats.tx_drops = tx_drops;
4281 	u64_stats_update_end(&adapter->syncp);
4282 }
4283 
4284 static void ena_notification(void *adapter_data,
4285 			     struct ena_admin_aenq_entry *aenq_e)
4286 {
4287 	struct ena_adapter *adapter = (struct ena_adapter *)adapter_data;
4288 	struct ena_admin_ena_hw_hints *hints;
4289 
4290 	WARN(aenq_e->aenq_common_desc.group != ENA_ADMIN_NOTIFICATION,
4291 	     "Invalid group(%x) expected %x\n",
4292 	     aenq_e->aenq_common_desc.group,
4293 	     ENA_ADMIN_NOTIFICATION);
4294 
4295 	switch (aenq_e->aenq_common_desc.syndrome) {
4296 	case ENA_ADMIN_UPDATE_HINTS:
4297 		hints = (struct ena_admin_ena_hw_hints *)
4298 			(&aenq_e->inline_data_w4);
4299 		ena_update_hints(adapter, hints);
4300 		break;
4301 	default:
4302 		netif_err(adapter, drv, adapter->netdev,
4303 			  "Invalid aenq notification link state %d\n",
4304 			  aenq_e->aenq_common_desc.syndrome);
4305 	}
4306 }
4307 
4308 /* This handler will called for unknown event group or unimplemented handlers*/
4309 static void unimplemented_aenq_handler(void *data,
4310 				       struct ena_admin_aenq_entry *aenq_e)
4311 {
4312 	struct ena_adapter *adapter = (struct ena_adapter *)data;
4313 
4314 	netif_err(adapter, drv, adapter->netdev,
4315 		  "Unknown event was received or event with unimplemented handler\n");
4316 }
4317 
4318 static struct ena_aenq_handlers aenq_handlers = {
4319 	.handlers = {
4320 		[ENA_ADMIN_LINK_CHANGE] = ena_update_on_link_change,
4321 		[ENA_ADMIN_NOTIFICATION] = ena_notification,
4322 		[ENA_ADMIN_KEEP_ALIVE] = ena_keep_alive_wd,
4323 	},
4324 	.unimplemented_handler = unimplemented_aenq_handler
4325 };
4326 
4327 module_init(ena_init);
4328 module_exit(ena_cleanup);
4329