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