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