ice: Refactor promiscuous functions
[platform/kernel/linux-starfive.git] / drivers / net / ethernet / intel / ice / ice_main.c
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2018, Intel Corporation. */
3
4 /* Intel(R) Ethernet Connection E800 Series Linux Driver */
5
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7
8 #include <generated/utsrelease.h>
9 #include "ice.h"
10 #include "ice_base.h"
11 #include "ice_lib.h"
12 #include "ice_fltr.h"
13 #include "ice_dcb_lib.h"
14 #include "ice_dcb_nl.h"
15 #include "ice_devlink.h"
16 /* Including ice_trace.h with CREATE_TRACE_POINTS defined will generate the
17  * ice tracepoint functions. This must be done exactly once across the
18  * ice driver.
19  */
20 #define CREATE_TRACE_POINTS
21 #include "ice_trace.h"
22 #include "ice_eswitch.h"
23 #include "ice_tc_lib.h"
24
25 #define DRV_SUMMARY     "Intel(R) Ethernet Connection E800 Series Linux Driver"
26 static const char ice_driver_string[] = DRV_SUMMARY;
27 static const char ice_copyright[] = "Copyright (c) 2018, Intel Corporation.";
28
29 /* DDP Package file located in firmware search paths (e.g. /lib/firmware/) */
30 #define ICE_DDP_PKG_PATH        "intel/ice/ddp/"
31 #define ICE_DDP_PKG_FILE        ICE_DDP_PKG_PATH "ice.pkg"
32
33 MODULE_AUTHOR("Intel Corporation, <linux.nics@intel.com>");
34 MODULE_DESCRIPTION(DRV_SUMMARY);
35 MODULE_LICENSE("GPL v2");
36 MODULE_FIRMWARE(ICE_DDP_PKG_FILE);
37
38 static int debug = -1;
39 module_param(debug, int, 0644);
40 #ifndef CONFIG_DYNAMIC_DEBUG
41 MODULE_PARM_DESC(debug, "netif level (0=none,...,16=all), hw debug_mask (0x8XXXXXXX)");
42 #else
43 MODULE_PARM_DESC(debug, "netif level (0=none,...,16=all)");
44 #endif /* !CONFIG_DYNAMIC_DEBUG */
45
46 static DEFINE_IDA(ice_aux_ida);
47 DEFINE_STATIC_KEY_FALSE(ice_xdp_locking_key);
48 EXPORT_SYMBOL(ice_xdp_locking_key);
49
50 static struct workqueue_struct *ice_wq;
51 static const struct net_device_ops ice_netdev_safe_mode_ops;
52 static const struct net_device_ops ice_netdev_ops;
53
54 static void ice_rebuild(struct ice_pf *pf, enum ice_reset_req reset_type);
55
56 static void ice_vsi_release_all(struct ice_pf *pf);
57
58 static int ice_rebuild_channels(struct ice_pf *pf);
59 static void ice_remove_q_channels(struct ice_vsi *vsi, bool rem_adv_fltr);
60
61 static int
62 ice_indr_setup_tc_cb(struct net_device *netdev, struct Qdisc *sch,
63                      void *cb_priv, enum tc_setup_type type, void *type_data,
64                      void *data,
65                      void (*cleanup)(struct flow_block_cb *block_cb));
66
67 bool netif_is_ice(struct net_device *dev)
68 {
69         return dev && (dev->netdev_ops == &ice_netdev_ops);
70 }
71
72 /**
73  * ice_get_tx_pending - returns number of Tx descriptors not processed
74  * @ring: the ring of descriptors
75  */
76 static u16 ice_get_tx_pending(struct ice_tx_ring *ring)
77 {
78         u16 head, tail;
79
80         head = ring->next_to_clean;
81         tail = ring->next_to_use;
82
83         if (head != tail)
84                 return (head < tail) ?
85                         tail - head : (tail + ring->count - head);
86         return 0;
87 }
88
89 /**
90  * ice_check_for_hang_subtask - check for and recover hung queues
91  * @pf: pointer to PF struct
92  */
93 static void ice_check_for_hang_subtask(struct ice_pf *pf)
94 {
95         struct ice_vsi *vsi = NULL;
96         struct ice_hw *hw;
97         unsigned int i;
98         int packets;
99         u32 v;
100
101         ice_for_each_vsi(pf, v)
102                 if (pf->vsi[v] && pf->vsi[v]->type == ICE_VSI_PF) {
103                         vsi = pf->vsi[v];
104                         break;
105                 }
106
107         if (!vsi || test_bit(ICE_VSI_DOWN, vsi->state))
108                 return;
109
110         if (!(vsi->netdev && netif_carrier_ok(vsi->netdev)))
111                 return;
112
113         hw = &vsi->back->hw;
114
115         ice_for_each_txq(vsi, i) {
116                 struct ice_tx_ring *tx_ring = vsi->tx_rings[i];
117
118                 if (!tx_ring)
119                         continue;
120                 if (ice_ring_ch_enabled(tx_ring))
121                         continue;
122
123                 if (tx_ring->desc) {
124                         /* If packet counter has not changed the queue is
125                          * likely stalled, so force an interrupt for this
126                          * queue.
127                          *
128                          * prev_pkt would be negative if there was no
129                          * pending work.
130                          */
131                         packets = tx_ring->stats.pkts & INT_MAX;
132                         if (tx_ring->tx_stats.prev_pkt == packets) {
133                                 /* Trigger sw interrupt to revive the queue */
134                                 ice_trigger_sw_intr(hw, tx_ring->q_vector);
135                                 continue;
136                         }
137
138                         /* Memory barrier between read of packet count and call
139                          * to ice_get_tx_pending()
140                          */
141                         smp_rmb();
142                         tx_ring->tx_stats.prev_pkt =
143                             ice_get_tx_pending(tx_ring) ? packets : -1;
144                 }
145         }
146 }
147
148 /**
149  * ice_init_mac_fltr - Set initial MAC filters
150  * @pf: board private structure
151  *
152  * Set initial set of MAC filters for PF VSI; configure filters for permanent
153  * address and broadcast address. If an error is encountered, netdevice will be
154  * unregistered.
155  */
156 static int ice_init_mac_fltr(struct ice_pf *pf)
157 {
158         enum ice_status status;
159         struct ice_vsi *vsi;
160         u8 *perm_addr;
161
162         vsi = ice_get_main_vsi(pf);
163         if (!vsi)
164                 return -EINVAL;
165
166         perm_addr = vsi->port_info->mac.perm_addr;
167         status = ice_fltr_add_mac_and_broadcast(vsi, perm_addr, ICE_FWD_TO_VSI);
168         if (status)
169                 return -EIO;
170
171         return 0;
172 }
173
174 /**
175  * ice_add_mac_to_sync_list - creates list of MAC addresses to be synced
176  * @netdev: the net device on which the sync is happening
177  * @addr: MAC address to sync
178  *
179  * This is a callback function which is called by the in kernel device sync
180  * functions (like __dev_uc_sync, __dev_mc_sync, etc). This function only
181  * populates the tmp_sync_list, which is later used by ice_add_mac to add the
182  * MAC filters from the hardware.
183  */
184 static int ice_add_mac_to_sync_list(struct net_device *netdev, const u8 *addr)
185 {
186         struct ice_netdev_priv *np = netdev_priv(netdev);
187         struct ice_vsi *vsi = np->vsi;
188
189         if (ice_fltr_add_mac_to_list(vsi, &vsi->tmp_sync_list, addr,
190                                      ICE_FWD_TO_VSI))
191                 return -EINVAL;
192
193         return 0;
194 }
195
196 /**
197  * ice_add_mac_to_unsync_list - creates list of MAC addresses to be unsynced
198  * @netdev: the net device on which the unsync is happening
199  * @addr: MAC address to unsync
200  *
201  * This is a callback function which is called by the in kernel device unsync
202  * functions (like __dev_uc_unsync, __dev_mc_unsync, etc). This function only
203  * populates the tmp_unsync_list, which is later used by ice_remove_mac to
204  * delete the MAC filters from the hardware.
205  */
206 static int ice_add_mac_to_unsync_list(struct net_device *netdev, const u8 *addr)
207 {
208         struct ice_netdev_priv *np = netdev_priv(netdev);
209         struct ice_vsi *vsi = np->vsi;
210
211         /* Under some circumstances, we might receive a request to delete our
212          * own device address from our uc list. Because we store the device
213          * address in the VSI's MAC filter list, we need to ignore such
214          * requests and not delete our device address from this list.
215          */
216         if (ether_addr_equal(addr, netdev->dev_addr))
217                 return 0;
218
219         if (ice_fltr_add_mac_to_list(vsi, &vsi->tmp_unsync_list, addr,
220                                      ICE_FWD_TO_VSI))
221                 return -EINVAL;
222
223         return 0;
224 }
225
226 /**
227  * ice_vsi_fltr_changed - check if filter state changed
228  * @vsi: VSI to be checked
229  *
230  * returns true if filter state has changed, false otherwise.
231  */
232 static bool ice_vsi_fltr_changed(struct ice_vsi *vsi)
233 {
234         return test_bit(ICE_VSI_UMAC_FLTR_CHANGED, vsi->state) ||
235                test_bit(ICE_VSI_MMAC_FLTR_CHANGED, vsi->state) ||
236                test_bit(ICE_VSI_VLAN_FLTR_CHANGED, vsi->state);
237 }
238
239 /**
240  * ice_set_promisc - Enable promiscuous mode for a given PF
241  * @vsi: the VSI being configured
242  * @promisc_m: mask of promiscuous config bits
243  *
244  */
245 static int ice_set_promisc(struct ice_vsi *vsi, u8 promisc_m)
246 {
247         enum ice_status status;
248
249         if (vsi->type != ICE_VSI_PF)
250                 return 0;
251
252         if (vsi->num_vlan > 1)
253                 status = ice_fltr_set_vlan_vsi_promisc(&vsi->back->hw, vsi, promisc_m);
254         else
255                 status = ice_fltr_set_vsi_promisc(&vsi->back->hw, vsi->idx, promisc_m, 0);
256         if (status)
257                 return -EIO;
258
259         return 0;
260 }
261
262 /**
263  * ice_clear_promisc - Disable promiscuous mode for a given PF
264  * @vsi: the VSI being configured
265  * @promisc_m: mask of promiscuous config bits
266  *
267  */
268 static int ice_clear_promisc(struct ice_vsi *vsi, u8 promisc_m)
269 {
270         enum ice_status status;
271
272         if (vsi->type != ICE_VSI_PF)
273                 return 0;
274
275         if (vsi->num_vlan > 1)
276                 status = ice_fltr_clear_vlan_vsi_promisc(&vsi->back->hw, vsi, promisc_m);
277         else
278                 status = ice_fltr_clear_vsi_promisc(&vsi->back->hw, vsi->idx, promisc_m, 0);
279         if (status)
280                 return -EIO;
281
282         return 0;
283 }
284
285 /**
286  * ice_vsi_sync_fltr - Update the VSI filter list to the HW
287  * @vsi: ptr to the VSI
288  *
289  * Push any outstanding VSI filter changes through the AdminQ.
290  */
291 static int ice_vsi_sync_fltr(struct ice_vsi *vsi)
292 {
293         struct device *dev = ice_pf_to_dev(vsi->back);
294         struct net_device *netdev = vsi->netdev;
295         bool promisc_forced_on = false;
296         struct ice_pf *pf = vsi->back;
297         struct ice_hw *hw = &pf->hw;
298         enum ice_status status = 0;
299         u32 changed_flags = 0;
300         u8 promisc_m;
301         int err = 0;
302
303         if (!vsi->netdev)
304                 return -EINVAL;
305
306         while (test_and_set_bit(ICE_CFG_BUSY, vsi->state))
307                 usleep_range(1000, 2000);
308
309         changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
310         vsi->current_netdev_flags = vsi->netdev->flags;
311
312         INIT_LIST_HEAD(&vsi->tmp_sync_list);
313         INIT_LIST_HEAD(&vsi->tmp_unsync_list);
314
315         if (ice_vsi_fltr_changed(vsi)) {
316                 clear_bit(ICE_VSI_UMAC_FLTR_CHANGED, vsi->state);
317                 clear_bit(ICE_VSI_MMAC_FLTR_CHANGED, vsi->state);
318                 clear_bit(ICE_VSI_VLAN_FLTR_CHANGED, vsi->state);
319
320                 /* grab the netdev's addr_list_lock */
321                 netif_addr_lock_bh(netdev);
322                 __dev_uc_sync(netdev, ice_add_mac_to_sync_list,
323                               ice_add_mac_to_unsync_list);
324                 __dev_mc_sync(netdev, ice_add_mac_to_sync_list,
325                               ice_add_mac_to_unsync_list);
326                 /* our temp lists are populated. release lock */
327                 netif_addr_unlock_bh(netdev);
328         }
329
330         /* Remove MAC addresses in the unsync list */
331         status = ice_fltr_remove_mac_list(vsi, &vsi->tmp_unsync_list);
332         ice_fltr_free_list(dev, &vsi->tmp_unsync_list);
333         if (status) {
334                 netdev_err(netdev, "Failed to delete MAC filters\n");
335                 /* if we failed because of alloc failures, just bail */
336                 if (status == ICE_ERR_NO_MEMORY) {
337                         err = -ENOMEM;
338                         goto out;
339                 }
340         }
341
342         /* Add MAC addresses in the sync list */
343         status = ice_fltr_add_mac_list(vsi, &vsi->tmp_sync_list);
344         ice_fltr_free_list(dev, &vsi->tmp_sync_list);
345         /* If filter is added successfully or already exists, do not go into
346          * 'if' condition and report it as error. Instead continue processing
347          * rest of the function.
348          */
349         if (status && status != ICE_ERR_ALREADY_EXISTS) {
350                 netdev_err(netdev, "Failed to add MAC filters\n");
351                 /* If there is no more space for new umac filters, VSI
352                  * should go into promiscuous mode. There should be some
353                  * space reserved for promiscuous filters.
354                  */
355                 if (hw->adminq.sq_last_status == ICE_AQ_RC_ENOSPC &&
356                     !test_and_set_bit(ICE_FLTR_OVERFLOW_PROMISC,
357                                       vsi->state)) {
358                         promisc_forced_on = true;
359                         netdev_warn(netdev, "Reached MAC filter limit, forcing promisc mode on VSI %d\n",
360                                     vsi->vsi_num);
361                 } else {
362                         err = -EIO;
363                         goto out;
364                 }
365         }
366         /* check for changes in promiscuous modes */
367         if (changed_flags & IFF_ALLMULTI) {
368                 if (vsi->current_netdev_flags & IFF_ALLMULTI) {
369                         if (vsi->num_vlan > 1)
370                                 promisc_m = ICE_MCAST_VLAN_PROMISC_BITS;
371                         else
372                                 promisc_m = ICE_MCAST_PROMISC_BITS;
373
374                         err = ice_set_promisc(vsi, promisc_m);
375                         if (err) {
376                                 netdev_err(netdev, "Error setting Multicast promiscuous mode on VSI %i\n",
377                                            vsi->vsi_num);
378                                 vsi->current_netdev_flags &= ~IFF_ALLMULTI;
379                                 goto out_promisc;
380                         }
381                 } else {
382                         /* !(vsi->current_netdev_flags & IFF_ALLMULTI) */
383                         if (vsi->num_vlan > 1)
384                                 promisc_m = ICE_MCAST_VLAN_PROMISC_BITS;
385                         else
386                                 promisc_m = ICE_MCAST_PROMISC_BITS;
387
388                         err = ice_clear_promisc(vsi, promisc_m);
389                         if (err) {
390                                 netdev_err(netdev, "Error clearing Multicast promiscuous mode on VSI %i\n",
391                                            vsi->vsi_num);
392                                 vsi->current_netdev_flags |= IFF_ALLMULTI;
393                                 goto out_promisc;
394                         }
395                 }
396         }
397
398         if (((changed_flags & IFF_PROMISC) || promisc_forced_on) ||
399             test_bit(ICE_VSI_PROMISC_CHANGED, vsi->state)) {
400                 clear_bit(ICE_VSI_PROMISC_CHANGED, vsi->state);
401                 if (vsi->current_netdev_flags & IFF_PROMISC) {
402                         /* Apply Rx filter rule to get traffic from wire */
403                         if (!ice_is_dflt_vsi_in_use(pf->first_sw)) {
404                                 err = ice_set_dflt_vsi(pf->first_sw, vsi);
405                                 if (err && err != -EEXIST) {
406                                         netdev_err(netdev, "Error %d setting default VSI %i Rx rule\n",
407                                                    err, vsi->vsi_num);
408                                         vsi->current_netdev_flags &=
409                                                 ~IFF_PROMISC;
410                                         goto out_promisc;
411                                 }
412                                 ice_cfg_vlan_pruning(vsi, false);
413                         }
414                 } else {
415                         /* Clear Rx filter to remove traffic from wire */
416                         if (ice_is_vsi_dflt_vsi(pf->first_sw, vsi)) {
417                                 err = ice_clear_dflt_vsi(pf->first_sw);
418                                 if (err) {
419                                         netdev_err(netdev, "Error %d clearing default VSI %i Rx rule\n",
420                                                    err, vsi->vsi_num);
421                                         vsi->current_netdev_flags |=
422                                                 IFF_PROMISC;
423                                         goto out_promisc;
424                                 }
425                                 if (vsi->num_vlan > 1)
426                                         ice_cfg_vlan_pruning(vsi, true);
427                         }
428                 }
429         }
430         goto exit;
431
432 out_promisc:
433         set_bit(ICE_VSI_PROMISC_CHANGED, vsi->state);
434         goto exit;
435 out:
436         /* if something went wrong then set the changed flag so we try again */
437         set_bit(ICE_VSI_UMAC_FLTR_CHANGED, vsi->state);
438         set_bit(ICE_VSI_MMAC_FLTR_CHANGED, vsi->state);
439 exit:
440         clear_bit(ICE_CFG_BUSY, vsi->state);
441         return err;
442 }
443
444 /**
445  * ice_sync_fltr_subtask - Sync the VSI filter list with HW
446  * @pf: board private structure
447  */
448 static void ice_sync_fltr_subtask(struct ice_pf *pf)
449 {
450         int v;
451
452         if (!pf || !(test_bit(ICE_FLAG_FLTR_SYNC, pf->flags)))
453                 return;
454
455         clear_bit(ICE_FLAG_FLTR_SYNC, pf->flags);
456
457         ice_for_each_vsi(pf, v)
458                 if (pf->vsi[v] && ice_vsi_fltr_changed(pf->vsi[v]) &&
459                     ice_vsi_sync_fltr(pf->vsi[v])) {
460                         /* come back and try again later */
461                         set_bit(ICE_FLAG_FLTR_SYNC, pf->flags);
462                         break;
463                 }
464 }
465
466 /**
467  * ice_pf_dis_all_vsi - Pause all VSIs on a PF
468  * @pf: the PF
469  * @locked: is the rtnl_lock already held
470  */
471 static void ice_pf_dis_all_vsi(struct ice_pf *pf, bool locked)
472 {
473         int node;
474         int v;
475
476         ice_for_each_vsi(pf, v)
477                 if (pf->vsi[v])
478                         ice_dis_vsi(pf->vsi[v], locked);
479
480         for (node = 0; node < ICE_MAX_PF_AGG_NODES; node++)
481                 pf->pf_agg_node[node].num_vsis = 0;
482
483         for (node = 0; node < ICE_MAX_VF_AGG_NODES; node++)
484                 pf->vf_agg_node[node].num_vsis = 0;
485 }
486
487 /**
488  * ice_prepare_for_reset - prep for reset
489  * @pf: board private structure
490  * @reset_type: reset type requested
491  *
492  * Inform or close all dependent features in prep for reset.
493  */
494 static void
495 ice_prepare_for_reset(struct ice_pf *pf, enum ice_reset_req reset_type)
496 {
497         struct ice_hw *hw = &pf->hw;
498         struct ice_vsi *vsi;
499         unsigned int i;
500
501         dev_dbg(ice_pf_to_dev(pf), "reset_type=%d\n", reset_type);
502
503         /* already prepared for reset */
504         if (test_bit(ICE_PREPARED_FOR_RESET, pf->state))
505                 return;
506
507         ice_unplug_aux_dev(pf);
508
509         /* Notify VFs of impending reset */
510         if (ice_check_sq_alive(hw, &hw->mailboxq))
511                 ice_vc_notify_reset(pf);
512
513         /* Disable VFs until reset is completed */
514         ice_for_each_vf(pf, i)
515                 ice_set_vf_state_qs_dis(&pf->vf[i]);
516
517         /* release ADQ specific HW and SW resources */
518         vsi = ice_get_main_vsi(pf);
519         if (!vsi)
520                 goto skip;
521
522         /* to be on safe side, reset orig_rss_size so that normal flow
523          * of deciding rss_size can take precedence
524          */
525         vsi->orig_rss_size = 0;
526
527         if (test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) {
528                 if (reset_type == ICE_RESET_PFR) {
529                         vsi->old_ena_tc = vsi->all_enatc;
530                         vsi->old_numtc = vsi->all_numtc;
531                 } else {
532                         ice_remove_q_channels(vsi, true);
533
534                         /* for other reset type, do not support channel rebuild
535                          * hence reset needed info
536                          */
537                         vsi->old_ena_tc = 0;
538                         vsi->all_enatc = 0;
539                         vsi->old_numtc = 0;
540                         vsi->all_numtc = 0;
541                         vsi->req_txq = 0;
542                         vsi->req_rxq = 0;
543                         clear_bit(ICE_FLAG_TC_MQPRIO, pf->flags);
544                         memset(&vsi->mqprio_qopt, 0, sizeof(vsi->mqprio_qopt));
545                 }
546         }
547 skip:
548
549         /* clear SW filtering DB */
550         ice_clear_hw_tbls(hw);
551         /* disable the VSIs and their queues that are not already DOWN */
552         ice_pf_dis_all_vsi(pf, false);
553
554         if (test_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags))
555                 ice_ptp_release(pf);
556
557         if (hw->port_info)
558                 ice_sched_clear_port(hw->port_info);
559
560         ice_shutdown_all_ctrlq(hw);
561
562         set_bit(ICE_PREPARED_FOR_RESET, pf->state);
563 }
564
565 /**
566  * ice_do_reset - Initiate one of many types of resets
567  * @pf: board private structure
568  * @reset_type: reset type requested before this function was called.
569  */
570 static void ice_do_reset(struct ice_pf *pf, enum ice_reset_req reset_type)
571 {
572         struct device *dev = ice_pf_to_dev(pf);
573         struct ice_hw *hw = &pf->hw;
574
575         dev_dbg(dev, "reset_type 0x%x requested\n", reset_type);
576
577         ice_prepare_for_reset(pf, reset_type);
578
579         /* trigger the reset */
580         if (ice_reset(hw, reset_type)) {
581                 dev_err(dev, "reset %d failed\n", reset_type);
582                 set_bit(ICE_RESET_FAILED, pf->state);
583                 clear_bit(ICE_RESET_OICR_RECV, pf->state);
584                 clear_bit(ICE_PREPARED_FOR_RESET, pf->state);
585                 clear_bit(ICE_PFR_REQ, pf->state);
586                 clear_bit(ICE_CORER_REQ, pf->state);
587                 clear_bit(ICE_GLOBR_REQ, pf->state);
588                 wake_up(&pf->reset_wait_queue);
589                 return;
590         }
591
592         /* PFR is a bit of a special case because it doesn't result in an OICR
593          * interrupt. So for PFR, rebuild after the reset and clear the reset-
594          * associated state bits.
595          */
596         if (reset_type == ICE_RESET_PFR) {
597                 pf->pfr_count++;
598                 ice_rebuild(pf, reset_type);
599                 clear_bit(ICE_PREPARED_FOR_RESET, pf->state);
600                 clear_bit(ICE_PFR_REQ, pf->state);
601                 wake_up(&pf->reset_wait_queue);
602                 ice_reset_all_vfs(pf, true);
603         }
604 }
605
606 /**
607  * ice_reset_subtask - Set up for resetting the device and driver
608  * @pf: board private structure
609  */
610 static void ice_reset_subtask(struct ice_pf *pf)
611 {
612         enum ice_reset_req reset_type = ICE_RESET_INVAL;
613
614         /* When a CORER/GLOBR/EMPR is about to happen, the hardware triggers an
615          * OICR interrupt. The OICR handler (ice_misc_intr) determines what type
616          * of reset is pending and sets bits in pf->state indicating the reset
617          * type and ICE_RESET_OICR_RECV. So, if the latter bit is set
618          * prepare for pending reset if not already (for PF software-initiated
619          * global resets the software should already be prepared for it as
620          * indicated by ICE_PREPARED_FOR_RESET; for global resets initiated
621          * by firmware or software on other PFs, that bit is not set so prepare
622          * for the reset now), poll for reset done, rebuild and return.
623          */
624         if (test_bit(ICE_RESET_OICR_RECV, pf->state)) {
625                 /* Perform the largest reset requested */
626                 if (test_and_clear_bit(ICE_CORER_RECV, pf->state))
627                         reset_type = ICE_RESET_CORER;
628                 if (test_and_clear_bit(ICE_GLOBR_RECV, pf->state))
629                         reset_type = ICE_RESET_GLOBR;
630                 if (test_and_clear_bit(ICE_EMPR_RECV, pf->state))
631                         reset_type = ICE_RESET_EMPR;
632                 /* return if no valid reset type requested */
633                 if (reset_type == ICE_RESET_INVAL)
634                         return;
635                 ice_prepare_for_reset(pf, reset_type);
636
637                 /* make sure we are ready to rebuild */
638                 if (ice_check_reset(&pf->hw)) {
639                         set_bit(ICE_RESET_FAILED, pf->state);
640                 } else {
641                         /* done with reset. start rebuild */
642                         pf->hw.reset_ongoing = false;
643                         ice_rebuild(pf, reset_type);
644                         /* clear bit to resume normal operations, but
645                          * ICE_NEEDS_RESTART bit is set in case rebuild failed
646                          */
647                         clear_bit(ICE_RESET_OICR_RECV, pf->state);
648                         clear_bit(ICE_PREPARED_FOR_RESET, pf->state);
649                         clear_bit(ICE_PFR_REQ, pf->state);
650                         clear_bit(ICE_CORER_REQ, pf->state);
651                         clear_bit(ICE_GLOBR_REQ, pf->state);
652                         wake_up(&pf->reset_wait_queue);
653                         ice_reset_all_vfs(pf, true);
654                 }
655
656                 return;
657         }
658
659         /* No pending resets to finish processing. Check for new resets */
660         if (test_bit(ICE_PFR_REQ, pf->state))
661                 reset_type = ICE_RESET_PFR;
662         if (test_bit(ICE_CORER_REQ, pf->state))
663                 reset_type = ICE_RESET_CORER;
664         if (test_bit(ICE_GLOBR_REQ, pf->state))
665                 reset_type = ICE_RESET_GLOBR;
666         /* If no valid reset type requested just return */
667         if (reset_type == ICE_RESET_INVAL)
668                 return;
669
670         /* reset if not already down or busy */
671         if (!test_bit(ICE_DOWN, pf->state) &&
672             !test_bit(ICE_CFG_BUSY, pf->state)) {
673                 ice_do_reset(pf, reset_type);
674         }
675 }
676
677 /**
678  * ice_print_topo_conflict - print topology conflict message
679  * @vsi: the VSI whose topology status is being checked
680  */
681 static void ice_print_topo_conflict(struct ice_vsi *vsi)
682 {
683         switch (vsi->port_info->phy.link_info.topo_media_conflict) {
684         case ICE_AQ_LINK_TOPO_CONFLICT:
685         case ICE_AQ_LINK_MEDIA_CONFLICT:
686         case ICE_AQ_LINK_TOPO_UNREACH_PRT:
687         case ICE_AQ_LINK_TOPO_UNDRUTIL_PRT:
688         case ICE_AQ_LINK_TOPO_UNDRUTIL_MEDIA:
689                 netdev_info(vsi->netdev, "Potential misconfiguration of the Ethernet port detected. If it was not intended, please use the Intel (R) Ethernet Port Configuration Tool to address the issue.\n");
690                 break;
691         case ICE_AQ_LINK_TOPO_UNSUPP_MEDIA:
692                 if (test_bit(ICE_FLAG_LINK_LENIENT_MODE_ENA, vsi->back->flags))
693                         netdev_warn(vsi->netdev, "An unsupported module type was detected. Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules\n");
694                 else
695                         netdev_err(vsi->netdev, "Rx/Tx is disabled on this device because an unsupported module type was detected. Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
696                 break;
697         default:
698                 break;
699         }
700 }
701
702 /**
703  * ice_print_link_msg - print link up or down message
704  * @vsi: the VSI whose link status is being queried
705  * @isup: boolean for if the link is now up or down
706  */
707 void ice_print_link_msg(struct ice_vsi *vsi, bool isup)
708 {
709         struct ice_aqc_get_phy_caps_data *caps;
710         const char *an_advertised;
711         enum ice_status status;
712         const char *fec_req;
713         const char *speed;
714         const char *fec;
715         const char *fc;
716         const char *an;
717
718         if (!vsi)
719                 return;
720
721         if (vsi->current_isup == isup)
722                 return;
723
724         vsi->current_isup = isup;
725
726         if (!isup) {
727                 netdev_info(vsi->netdev, "NIC Link is Down\n");
728                 return;
729         }
730
731         switch (vsi->port_info->phy.link_info.link_speed) {
732         case ICE_AQ_LINK_SPEED_100GB:
733                 speed = "100 G";
734                 break;
735         case ICE_AQ_LINK_SPEED_50GB:
736                 speed = "50 G";
737                 break;
738         case ICE_AQ_LINK_SPEED_40GB:
739                 speed = "40 G";
740                 break;
741         case ICE_AQ_LINK_SPEED_25GB:
742                 speed = "25 G";
743                 break;
744         case ICE_AQ_LINK_SPEED_20GB:
745                 speed = "20 G";
746                 break;
747         case ICE_AQ_LINK_SPEED_10GB:
748                 speed = "10 G";
749                 break;
750         case ICE_AQ_LINK_SPEED_5GB:
751                 speed = "5 G";
752                 break;
753         case ICE_AQ_LINK_SPEED_2500MB:
754                 speed = "2.5 G";
755                 break;
756         case ICE_AQ_LINK_SPEED_1000MB:
757                 speed = "1 G";
758                 break;
759         case ICE_AQ_LINK_SPEED_100MB:
760                 speed = "100 M";
761                 break;
762         default:
763                 speed = "Unknown ";
764                 break;
765         }
766
767         switch (vsi->port_info->fc.current_mode) {
768         case ICE_FC_FULL:
769                 fc = "Rx/Tx";
770                 break;
771         case ICE_FC_TX_PAUSE:
772                 fc = "Tx";
773                 break;
774         case ICE_FC_RX_PAUSE:
775                 fc = "Rx";
776                 break;
777         case ICE_FC_NONE:
778                 fc = "None";
779                 break;
780         default:
781                 fc = "Unknown";
782                 break;
783         }
784
785         /* Get FEC mode based on negotiated link info */
786         switch (vsi->port_info->phy.link_info.fec_info) {
787         case ICE_AQ_LINK_25G_RS_528_FEC_EN:
788         case ICE_AQ_LINK_25G_RS_544_FEC_EN:
789                 fec = "RS-FEC";
790                 break;
791         case ICE_AQ_LINK_25G_KR_FEC_EN:
792                 fec = "FC-FEC/BASE-R";
793                 break;
794         default:
795                 fec = "NONE";
796                 break;
797         }
798
799         /* check if autoneg completed, might be false due to not supported */
800         if (vsi->port_info->phy.link_info.an_info & ICE_AQ_AN_COMPLETED)
801                 an = "True";
802         else
803                 an = "False";
804
805         /* Get FEC mode requested based on PHY caps last SW configuration */
806         caps = kzalloc(sizeof(*caps), GFP_KERNEL);
807         if (!caps) {
808                 fec_req = "Unknown";
809                 an_advertised = "Unknown";
810                 goto done;
811         }
812
813         status = ice_aq_get_phy_caps(vsi->port_info, false,
814                                      ICE_AQC_REPORT_ACTIVE_CFG, caps, NULL);
815         if (status)
816                 netdev_info(vsi->netdev, "Get phy capability failed.\n");
817
818         an_advertised = ice_is_phy_caps_an_enabled(caps) ? "On" : "Off";
819
820         if (caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_528_REQ ||
821             caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_544_REQ)
822                 fec_req = "RS-FEC";
823         else if (caps->link_fec_options & ICE_AQC_PHY_FEC_10G_KR_40G_KR4_REQ ||
824                  caps->link_fec_options & ICE_AQC_PHY_FEC_25G_KR_REQ)
825                 fec_req = "FC-FEC/BASE-R";
826         else
827                 fec_req = "NONE";
828
829         kfree(caps);
830
831 done:
832         netdev_info(vsi->netdev, "NIC Link is up %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg Advertised: %s, Autoneg Negotiated: %s, Flow Control: %s\n",
833                     speed, fec_req, fec, an_advertised, an, fc);
834         ice_print_topo_conflict(vsi);
835 }
836
837 /**
838  * ice_vsi_link_event - update the VSI's netdev
839  * @vsi: the VSI on which the link event occurred
840  * @link_up: whether or not the VSI needs to be set up or down
841  */
842 static void ice_vsi_link_event(struct ice_vsi *vsi, bool link_up)
843 {
844         if (!vsi)
845                 return;
846
847         if (test_bit(ICE_VSI_DOWN, vsi->state) || !vsi->netdev)
848                 return;
849
850         if (vsi->type == ICE_VSI_PF) {
851                 if (link_up == netif_carrier_ok(vsi->netdev))
852                         return;
853
854                 if (link_up) {
855                         netif_carrier_on(vsi->netdev);
856                         netif_tx_wake_all_queues(vsi->netdev);
857                 } else {
858                         netif_carrier_off(vsi->netdev);
859                         netif_tx_stop_all_queues(vsi->netdev);
860                 }
861         }
862 }
863
864 /**
865  * ice_set_dflt_mib - send a default config MIB to the FW
866  * @pf: private PF struct
867  *
868  * This function sends a default configuration MIB to the FW.
869  *
870  * If this function errors out at any point, the driver is still able to
871  * function.  The main impact is that LFC may not operate as expected.
872  * Therefore an error state in this function should be treated with a DBG
873  * message and continue on with driver rebuild/reenable.
874  */
875 static void ice_set_dflt_mib(struct ice_pf *pf)
876 {
877         struct device *dev = ice_pf_to_dev(pf);
878         u8 mib_type, *buf, *lldpmib = NULL;
879         u16 len, typelen, offset = 0;
880         struct ice_lldp_org_tlv *tlv;
881         struct ice_hw *hw = &pf->hw;
882         u32 ouisubtype;
883
884         mib_type = SET_LOCAL_MIB_TYPE_LOCAL_MIB;
885         lldpmib = kzalloc(ICE_LLDPDU_SIZE, GFP_KERNEL);
886         if (!lldpmib) {
887                 dev_dbg(dev, "%s Failed to allocate MIB memory\n",
888                         __func__);
889                 return;
890         }
891
892         /* Add ETS CFG TLV */
893         tlv = (struct ice_lldp_org_tlv *)lldpmib;
894         typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) |
895                    ICE_IEEE_ETS_TLV_LEN);
896         tlv->typelen = htons(typelen);
897         ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) |
898                       ICE_IEEE_SUBTYPE_ETS_CFG);
899         tlv->ouisubtype = htonl(ouisubtype);
900
901         buf = tlv->tlvinfo;
902         buf[0] = 0;
903
904         /* ETS CFG all UPs map to TC 0. Next 4 (1 - 4) Octets = 0.
905          * Octets 5 - 12 are BW values, set octet 5 to 100% BW.
906          * Octets 13 - 20 are TSA values - leave as zeros
907          */
908         buf[5] = 0x64;
909         len = (typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S;
910         offset += len + 2;
911         tlv = (struct ice_lldp_org_tlv *)
912                 ((char *)tlv + sizeof(tlv->typelen) + len);
913
914         /* Add ETS REC TLV */
915         buf = tlv->tlvinfo;
916         tlv->typelen = htons(typelen);
917
918         ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) |
919                       ICE_IEEE_SUBTYPE_ETS_REC);
920         tlv->ouisubtype = htonl(ouisubtype);
921
922         /* First octet of buf is reserved
923          * Octets 1 - 4 map UP to TC - all UPs map to zero
924          * Octets 5 - 12 are BW values - set TC 0 to 100%.
925          * Octets 13 - 20 are TSA value - leave as zeros
926          */
927         buf[5] = 0x64;
928         offset += len + 2;
929         tlv = (struct ice_lldp_org_tlv *)
930                 ((char *)tlv + sizeof(tlv->typelen) + len);
931
932         /* Add PFC CFG TLV */
933         typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) |
934                    ICE_IEEE_PFC_TLV_LEN);
935         tlv->typelen = htons(typelen);
936
937         ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) |
938                       ICE_IEEE_SUBTYPE_PFC_CFG);
939         tlv->ouisubtype = htonl(ouisubtype);
940
941         /* Octet 1 left as all zeros - PFC disabled */
942         buf[0] = 0x08;
943         len = (typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S;
944         offset += len + 2;
945
946         if (ice_aq_set_lldp_mib(hw, mib_type, (void *)lldpmib, offset, NULL))
947                 dev_dbg(dev, "%s Failed to set default LLDP MIB\n", __func__);
948
949         kfree(lldpmib);
950 }
951
952 /**
953  * ice_check_phy_fw_load - check if PHY FW load failed
954  * @pf: pointer to PF struct
955  * @link_cfg_err: bitmap from the link info structure
956  *
957  * check if external PHY FW load failed and print an error message if it did
958  */
959 static void ice_check_phy_fw_load(struct ice_pf *pf, u8 link_cfg_err)
960 {
961         if (!(link_cfg_err & ICE_AQ_LINK_EXTERNAL_PHY_LOAD_FAILURE)) {
962                 clear_bit(ICE_FLAG_PHY_FW_LOAD_FAILED, pf->flags);
963                 return;
964         }
965
966         if (test_bit(ICE_FLAG_PHY_FW_LOAD_FAILED, pf->flags))
967                 return;
968
969         if (link_cfg_err & ICE_AQ_LINK_EXTERNAL_PHY_LOAD_FAILURE) {
970                 dev_err(ice_pf_to_dev(pf), "Device failed to load the FW for the external PHY. Please download and install the latest NVM for your device and try again\n");
971                 set_bit(ICE_FLAG_PHY_FW_LOAD_FAILED, pf->flags);
972         }
973 }
974
975 /**
976  * ice_check_module_power
977  * @pf: pointer to PF struct
978  * @link_cfg_err: bitmap from the link info structure
979  *
980  * check module power level returned by a previous call to aq_get_link_info
981  * and print error messages if module power level is not supported
982  */
983 static void ice_check_module_power(struct ice_pf *pf, u8 link_cfg_err)
984 {
985         /* if module power level is supported, clear the flag */
986         if (!(link_cfg_err & (ICE_AQ_LINK_INVAL_MAX_POWER_LIMIT |
987                               ICE_AQ_LINK_MODULE_POWER_UNSUPPORTED))) {
988                 clear_bit(ICE_FLAG_MOD_POWER_UNSUPPORTED, pf->flags);
989                 return;
990         }
991
992         /* if ICE_FLAG_MOD_POWER_UNSUPPORTED was previously set and the
993          * above block didn't clear this bit, there's nothing to do
994          */
995         if (test_bit(ICE_FLAG_MOD_POWER_UNSUPPORTED, pf->flags))
996                 return;
997
998         if (link_cfg_err & ICE_AQ_LINK_INVAL_MAX_POWER_LIMIT) {
999                 dev_err(ice_pf_to_dev(pf), "The installed module is incompatible with the device's NVM image. Cannot start link\n");
1000                 set_bit(ICE_FLAG_MOD_POWER_UNSUPPORTED, pf->flags);
1001         } else if (link_cfg_err & ICE_AQ_LINK_MODULE_POWER_UNSUPPORTED) {
1002                 dev_err(ice_pf_to_dev(pf), "The module's power requirements exceed the device's power supply. Cannot start link\n");
1003                 set_bit(ICE_FLAG_MOD_POWER_UNSUPPORTED, pf->flags);
1004         }
1005 }
1006
1007 /**
1008  * ice_check_link_cfg_err - check if link configuration failed
1009  * @pf: pointer to the PF struct
1010  * @link_cfg_err: bitmap from the link info structure
1011  *
1012  * print if any link configuration failure happens due to the value in the
1013  * link_cfg_err parameter in the link info structure
1014  */
1015 static void ice_check_link_cfg_err(struct ice_pf *pf, u8 link_cfg_err)
1016 {
1017         ice_check_module_power(pf, link_cfg_err);
1018         ice_check_phy_fw_load(pf, link_cfg_err);
1019 }
1020
1021 /**
1022  * ice_link_event - process the link event
1023  * @pf: PF that the link event is associated with
1024  * @pi: port_info for the port that the link event is associated with
1025  * @link_up: true if the physical link is up and false if it is down
1026  * @link_speed: current link speed received from the link event
1027  *
1028  * Returns 0 on success and negative on failure
1029  */
1030 static int
1031 ice_link_event(struct ice_pf *pf, struct ice_port_info *pi, bool link_up,
1032                u16 link_speed)
1033 {
1034         struct device *dev = ice_pf_to_dev(pf);
1035         struct ice_phy_info *phy_info;
1036         enum ice_status status;
1037         struct ice_vsi *vsi;
1038         u16 old_link_speed;
1039         bool old_link;
1040
1041         phy_info = &pi->phy;
1042         phy_info->link_info_old = phy_info->link_info;
1043
1044         old_link = !!(phy_info->link_info_old.link_info & ICE_AQ_LINK_UP);
1045         old_link_speed = phy_info->link_info_old.link_speed;
1046
1047         /* update the link info structures and re-enable link events,
1048          * don't bail on failure due to other book keeping needed
1049          */
1050         status = ice_update_link_info(pi);
1051         if (status)
1052                 dev_dbg(dev, "Failed to update link status on port %d, err %s aq_err %s\n",
1053                         pi->lport, ice_stat_str(status),
1054                         ice_aq_str(pi->hw->adminq.sq_last_status));
1055
1056         ice_check_link_cfg_err(pf, pi->phy.link_info.link_cfg_err);
1057
1058         /* Check if the link state is up after updating link info, and treat
1059          * this event as an UP event since the link is actually UP now.
1060          */
1061         if (phy_info->link_info.link_info & ICE_AQ_LINK_UP)
1062                 link_up = true;
1063
1064         vsi = ice_get_main_vsi(pf);
1065         if (!vsi || !vsi->port_info)
1066                 return -EINVAL;
1067
1068         /* turn off PHY if media was removed */
1069         if (!test_bit(ICE_FLAG_NO_MEDIA, pf->flags) &&
1070             !(pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE)) {
1071                 set_bit(ICE_FLAG_NO_MEDIA, pf->flags);
1072                 ice_set_link(vsi, false);
1073         }
1074
1075         /* if the old link up/down and speed is the same as the new */
1076         if (link_up == old_link && link_speed == old_link_speed)
1077                 return 0;
1078
1079         if (ice_is_dcb_active(pf)) {
1080                 if (test_bit(ICE_FLAG_DCB_ENA, pf->flags))
1081                         ice_dcb_rebuild(pf);
1082         } else {
1083                 if (link_up)
1084                         ice_set_dflt_mib(pf);
1085         }
1086         ice_vsi_link_event(vsi, link_up);
1087         ice_print_link_msg(vsi, link_up);
1088
1089         ice_vc_notify_link_state(pf);
1090
1091         return 0;
1092 }
1093
1094 /**
1095  * ice_watchdog_subtask - periodic tasks not using event driven scheduling
1096  * @pf: board private structure
1097  */
1098 static void ice_watchdog_subtask(struct ice_pf *pf)
1099 {
1100         int i;
1101
1102         /* if interface is down do nothing */
1103         if (test_bit(ICE_DOWN, pf->state) ||
1104             test_bit(ICE_CFG_BUSY, pf->state))
1105                 return;
1106
1107         /* make sure we don't do these things too often */
1108         if (time_before(jiffies,
1109                         pf->serv_tmr_prev + pf->serv_tmr_period))
1110                 return;
1111
1112         pf->serv_tmr_prev = jiffies;
1113
1114         /* Update the stats for active netdevs so the network stack
1115          * can look at updated numbers whenever it cares to
1116          */
1117         ice_update_pf_stats(pf);
1118         ice_for_each_vsi(pf, i)
1119                 if (pf->vsi[i] && pf->vsi[i]->netdev)
1120                         ice_update_vsi_stats(pf->vsi[i]);
1121 }
1122
1123 /**
1124  * ice_init_link_events - enable/initialize link events
1125  * @pi: pointer to the port_info instance
1126  *
1127  * Returns -EIO on failure, 0 on success
1128  */
1129 static int ice_init_link_events(struct ice_port_info *pi)
1130 {
1131         u16 mask;
1132
1133         mask = ~((u16)(ICE_AQ_LINK_EVENT_UPDOWN | ICE_AQ_LINK_EVENT_MEDIA_NA |
1134                        ICE_AQ_LINK_EVENT_MODULE_QUAL_FAIL |
1135                        ICE_AQ_LINK_EVENT_PHY_FW_LOAD_FAIL));
1136
1137         if (ice_aq_set_event_mask(pi->hw, pi->lport, mask, NULL)) {
1138                 dev_dbg(ice_hw_to_dev(pi->hw), "Failed to set link event mask for port %d\n",
1139                         pi->lport);
1140                 return -EIO;
1141         }
1142
1143         if (ice_aq_get_link_info(pi, true, NULL, NULL)) {
1144                 dev_dbg(ice_hw_to_dev(pi->hw), "Failed to enable link events for port %d\n",
1145                         pi->lport);
1146                 return -EIO;
1147         }
1148
1149         return 0;
1150 }
1151
1152 /**
1153  * ice_handle_link_event - handle link event via ARQ
1154  * @pf: PF that the link event is associated with
1155  * @event: event structure containing link status info
1156  */
1157 static int
1158 ice_handle_link_event(struct ice_pf *pf, struct ice_rq_event_info *event)
1159 {
1160         struct ice_aqc_get_link_status_data *link_data;
1161         struct ice_port_info *port_info;
1162         int status;
1163
1164         link_data = (struct ice_aqc_get_link_status_data *)event->msg_buf;
1165         port_info = pf->hw.port_info;
1166         if (!port_info)
1167                 return -EINVAL;
1168
1169         status = ice_link_event(pf, port_info,
1170                                 !!(link_data->link_info & ICE_AQ_LINK_UP),
1171                                 le16_to_cpu(link_data->link_speed));
1172         if (status)
1173                 dev_dbg(ice_pf_to_dev(pf), "Could not process link event, error %d\n",
1174                         status);
1175
1176         return status;
1177 }
1178
1179 enum ice_aq_task_state {
1180         ICE_AQ_TASK_WAITING = 0,
1181         ICE_AQ_TASK_COMPLETE,
1182         ICE_AQ_TASK_CANCELED,
1183 };
1184
1185 struct ice_aq_task {
1186         struct hlist_node entry;
1187
1188         u16 opcode;
1189         struct ice_rq_event_info *event;
1190         enum ice_aq_task_state state;
1191 };
1192
1193 /**
1194  * ice_aq_wait_for_event - Wait for an AdminQ event from firmware
1195  * @pf: pointer to the PF private structure
1196  * @opcode: the opcode to wait for
1197  * @timeout: how long to wait, in jiffies
1198  * @event: storage for the event info
1199  *
1200  * Waits for a specific AdminQ completion event on the ARQ for a given PF. The
1201  * current thread will be put to sleep until the specified event occurs or
1202  * until the given timeout is reached.
1203  *
1204  * To obtain only the descriptor contents, pass an event without an allocated
1205  * msg_buf. If the complete data buffer is desired, allocate the
1206  * event->msg_buf with enough space ahead of time.
1207  *
1208  * Returns: zero on success, or a negative error code on failure.
1209  */
1210 int ice_aq_wait_for_event(struct ice_pf *pf, u16 opcode, unsigned long timeout,
1211                           struct ice_rq_event_info *event)
1212 {
1213         struct device *dev = ice_pf_to_dev(pf);
1214         struct ice_aq_task *task;
1215         unsigned long start;
1216         long ret;
1217         int err;
1218
1219         task = kzalloc(sizeof(*task), GFP_KERNEL);
1220         if (!task)
1221                 return -ENOMEM;
1222
1223         INIT_HLIST_NODE(&task->entry);
1224         task->opcode = opcode;
1225         task->event = event;
1226         task->state = ICE_AQ_TASK_WAITING;
1227
1228         spin_lock_bh(&pf->aq_wait_lock);
1229         hlist_add_head(&task->entry, &pf->aq_wait_list);
1230         spin_unlock_bh(&pf->aq_wait_lock);
1231
1232         start = jiffies;
1233
1234         ret = wait_event_interruptible_timeout(pf->aq_wait_queue, task->state,
1235                                                timeout);
1236         switch (task->state) {
1237         case ICE_AQ_TASK_WAITING:
1238                 err = ret < 0 ? ret : -ETIMEDOUT;
1239                 break;
1240         case ICE_AQ_TASK_CANCELED:
1241                 err = ret < 0 ? ret : -ECANCELED;
1242                 break;
1243         case ICE_AQ_TASK_COMPLETE:
1244                 err = ret < 0 ? ret : 0;
1245                 break;
1246         default:
1247                 WARN(1, "Unexpected AdminQ wait task state %u", task->state);
1248                 err = -EINVAL;
1249                 break;
1250         }
1251
1252         dev_dbg(dev, "Waited %u msecs (max %u msecs) for firmware response to op 0x%04x\n",
1253                 jiffies_to_msecs(jiffies - start),
1254                 jiffies_to_msecs(timeout),
1255                 opcode);
1256
1257         spin_lock_bh(&pf->aq_wait_lock);
1258         hlist_del(&task->entry);
1259         spin_unlock_bh(&pf->aq_wait_lock);
1260         kfree(task);
1261
1262         return err;
1263 }
1264
1265 /**
1266  * ice_aq_check_events - Check if any thread is waiting for an AdminQ event
1267  * @pf: pointer to the PF private structure
1268  * @opcode: the opcode of the event
1269  * @event: the event to check
1270  *
1271  * Loops over the current list of pending threads waiting for an AdminQ event.
1272  * For each matching task, copy the contents of the event into the task
1273  * structure and wake up the thread.
1274  *
1275  * If multiple threads wait for the same opcode, they will all be woken up.
1276  *
1277  * Note that event->msg_buf will only be duplicated if the event has a buffer
1278  * with enough space already allocated. Otherwise, only the descriptor and
1279  * message length will be copied.
1280  *
1281  * Returns: true if an event was found, false otherwise
1282  */
1283 static void ice_aq_check_events(struct ice_pf *pf, u16 opcode,
1284                                 struct ice_rq_event_info *event)
1285 {
1286         struct ice_aq_task *task;
1287         bool found = false;
1288
1289         spin_lock_bh(&pf->aq_wait_lock);
1290         hlist_for_each_entry(task, &pf->aq_wait_list, entry) {
1291                 if (task->state || task->opcode != opcode)
1292                         continue;
1293
1294                 memcpy(&task->event->desc, &event->desc, sizeof(event->desc));
1295                 task->event->msg_len = event->msg_len;
1296
1297                 /* Only copy the data buffer if a destination was set */
1298                 if (task->event->msg_buf &&
1299                     task->event->buf_len > event->buf_len) {
1300                         memcpy(task->event->msg_buf, event->msg_buf,
1301                                event->buf_len);
1302                         task->event->buf_len = event->buf_len;
1303                 }
1304
1305                 task->state = ICE_AQ_TASK_COMPLETE;
1306                 found = true;
1307         }
1308         spin_unlock_bh(&pf->aq_wait_lock);
1309
1310         if (found)
1311                 wake_up(&pf->aq_wait_queue);
1312 }
1313
1314 /**
1315  * ice_aq_cancel_waiting_tasks - Immediately cancel all waiting tasks
1316  * @pf: the PF private structure
1317  *
1318  * Set all waiting tasks to ICE_AQ_TASK_CANCELED, and wake up their threads.
1319  * This will then cause ice_aq_wait_for_event to exit with -ECANCELED.
1320  */
1321 static void ice_aq_cancel_waiting_tasks(struct ice_pf *pf)
1322 {
1323         struct ice_aq_task *task;
1324
1325         spin_lock_bh(&pf->aq_wait_lock);
1326         hlist_for_each_entry(task, &pf->aq_wait_list, entry)
1327                 task->state = ICE_AQ_TASK_CANCELED;
1328         spin_unlock_bh(&pf->aq_wait_lock);
1329
1330         wake_up(&pf->aq_wait_queue);
1331 }
1332
1333 /**
1334  * __ice_clean_ctrlq - helper function to clean controlq rings
1335  * @pf: ptr to struct ice_pf
1336  * @q_type: specific Control queue type
1337  */
1338 static int __ice_clean_ctrlq(struct ice_pf *pf, enum ice_ctl_q q_type)
1339 {
1340         struct device *dev = ice_pf_to_dev(pf);
1341         struct ice_rq_event_info event;
1342         struct ice_hw *hw = &pf->hw;
1343         struct ice_ctl_q_info *cq;
1344         u16 pending, i = 0;
1345         const char *qtype;
1346         u32 oldval, val;
1347
1348         /* Do not clean control queue if/when PF reset fails */
1349         if (test_bit(ICE_RESET_FAILED, pf->state))
1350                 return 0;
1351
1352         switch (q_type) {
1353         case ICE_CTL_Q_ADMIN:
1354                 cq = &hw->adminq;
1355                 qtype = "Admin";
1356                 break;
1357         case ICE_CTL_Q_SB:
1358                 cq = &hw->sbq;
1359                 qtype = "Sideband";
1360                 break;
1361         case ICE_CTL_Q_MAILBOX:
1362                 cq = &hw->mailboxq;
1363                 qtype = "Mailbox";
1364                 /* we are going to try to detect a malicious VF, so set the
1365                  * state to begin detection
1366                  */
1367                 hw->mbx_snapshot.mbx_buf.state = ICE_MAL_VF_DETECT_STATE_NEW_SNAPSHOT;
1368                 break;
1369         default:
1370                 dev_warn(dev, "Unknown control queue type 0x%x\n", q_type);
1371                 return 0;
1372         }
1373
1374         /* check for error indications - PF_xx_AxQLEN register layout for
1375          * FW/MBX/SB are identical so just use defines for PF_FW_AxQLEN.
1376          */
1377         val = rd32(hw, cq->rq.len);
1378         if (val & (PF_FW_ARQLEN_ARQVFE_M | PF_FW_ARQLEN_ARQOVFL_M |
1379                    PF_FW_ARQLEN_ARQCRIT_M)) {
1380                 oldval = val;
1381                 if (val & PF_FW_ARQLEN_ARQVFE_M)
1382                         dev_dbg(dev, "%s Receive Queue VF Error detected\n",
1383                                 qtype);
1384                 if (val & PF_FW_ARQLEN_ARQOVFL_M) {
1385                         dev_dbg(dev, "%s Receive Queue Overflow Error detected\n",
1386                                 qtype);
1387                 }
1388                 if (val & PF_FW_ARQLEN_ARQCRIT_M)
1389                         dev_dbg(dev, "%s Receive Queue Critical Error detected\n",
1390                                 qtype);
1391                 val &= ~(PF_FW_ARQLEN_ARQVFE_M | PF_FW_ARQLEN_ARQOVFL_M |
1392                          PF_FW_ARQLEN_ARQCRIT_M);
1393                 if (oldval != val)
1394                         wr32(hw, cq->rq.len, val);
1395         }
1396
1397         val = rd32(hw, cq->sq.len);
1398         if (val & (PF_FW_ATQLEN_ATQVFE_M | PF_FW_ATQLEN_ATQOVFL_M |
1399                    PF_FW_ATQLEN_ATQCRIT_M)) {
1400                 oldval = val;
1401                 if (val & PF_FW_ATQLEN_ATQVFE_M)
1402                         dev_dbg(dev, "%s Send Queue VF Error detected\n",
1403                                 qtype);
1404                 if (val & PF_FW_ATQLEN_ATQOVFL_M) {
1405                         dev_dbg(dev, "%s Send Queue Overflow Error detected\n",
1406                                 qtype);
1407                 }
1408                 if (val & PF_FW_ATQLEN_ATQCRIT_M)
1409                         dev_dbg(dev, "%s Send Queue Critical Error detected\n",
1410                                 qtype);
1411                 val &= ~(PF_FW_ATQLEN_ATQVFE_M | PF_FW_ATQLEN_ATQOVFL_M |
1412                          PF_FW_ATQLEN_ATQCRIT_M);
1413                 if (oldval != val)
1414                         wr32(hw, cq->sq.len, val);
1415         }
1416
1417         event.buf_len = cq->rq_buf_size;
1418         event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
1419         if (!event.msg_buf)
1420                 return 0;
1421
1422         do {
1423                 enum ice_status ret;
1424                 u16 opcode;
1425
1426                 ret = ice_clean_rq_elem(hw, cq, &event, &pending);
1427                 if (ret == ICE_ERR_AQ_NO_WORK)
1428                         break;
1429                 if (ret) {
1430                         dev_err(dev, "%s Receive Queue event error %s\n", qtype,
1431                                 ice_stat_str(ret));
1432                         break;
1433                 }
1434
1435                 opcode = le16_to_cpu(event.desc.opcode);
1436
1437                 /* Notify any thread that might be waiting for this event */
1438                 ice_aq_check_events(pf, opcode, &event);
1439
1440                 switch (opcode) {
1441                 case ice_aqc_opc_get_link_status:
1442                         if (ice_handle_link_event(pf, &event))
1443                                 dev_err(dev, "Could not handle link event\n");
1444                         break;
1445                 case ice_aqc_opc_event_lan_overflow:
1446                         ice_vf_lan_overflow_event(pf, &event);
1447                         break;
1448                 case ice_mbx_opc_send_msg_to_pf:
1449                         if (!ice_is_malicious_vf(pf, &event, i, pending))
1450                                 ice_vc_process_vf_msg(pf, &event);
1451                         break;
1452                 case ice_aqc_opc_fw_logging:
1453                         ice_output_fw_log(hw, &event.desc, event.msg_buf);
1454                         break;
1455                 case ice_aqc_opc_lldp_set_mib_change:
1456                         ice_dcb_process_lldp_set_mib_change(pf, &event);
1457                         break;
1458                 default:
1459                         dev_dbg(dev, "%s Receive Queue unknown event 0x%04x ignored\n",
1460                                 qtype, opcode);
1461                         break;
1462                 }
1463         } while (pending && (i++ < ICE_DFLT_IRQ_WORK));
1464
1465         kfree(event.msg_buf);
1466
1467         return pending && (i == ICE_DFLT_IRQ_WORK);
1468 }
1469
1470 /**
1471  * ice_ctrlq_pending - check if there is a difference between ntc and ntu
1472  * @hw: pointer to hardware info
1473  * @cq: control queue information
1474  *
1475  * returns true if there are pending messages in a queue, false if there aren't
1476  */
1477 static bool ice_ctrlq_pending(struct ice_hw *hw, struct ice_ctl_q_info *cq)
1478 {
1479         u16 ntu;
1480
1481         ntu = (u16)(rd32(hw, cq->rq.head) & cq->rq.head_mask);
1482         return cq->rq.next_to_clean != ntu;
1483 }
1484
1485 /**
1486  * ice_clean_adminq_subtask - clean the AdminQ rings
1487  * @pf: board private structure
1488  */
1489 static void ice_clean_adminq_subtask(struct ice_pf *pf)
1490 {
1491         struct ice_hw *hw = &pf->hw;
1492
1493         if (!test_bit(ICE_ADMINQ_EVENT_PENDING, pf->state))
1494                 return;
1495
1496         if (__ice_clean_ctrlq(pf, ICE_CTL_Q_ADMIN))
1497                 return;
1498
1499         clear_bit(ICE_ADMINQ_EVENT_PENDING, pf->state);
1500
1501         /* There might be a situation where new messages arrive to a control
1502          * queue between processing the last message and clearing the
1503          * EVENT_PENDING bit. So before exiting, check queue head again (using
1504          * ice_ctrlq_pending) and process new messages if any.
1505          */
1506         if (ice_ctrlq_pending(hw, &hw->adminq))
1507                 __ice_clean_ctrlq(pf, ICE_CTL_Q_ADMIN);
1508
1509         ice_flush(hw);
1510 }
1511
1512 /**
1513  * ice_clean_mailboxq_subtask - clean the MailboxQ rings
1514  * @pf: board private structure
1515  */
1516 static void ice_clean_mailboxq_subtask(struct ice_pf *pf)
1517 {
1518         struct ice_hw *hw = &pf->hw;
1519
1520         if (!test_bit(ICE_MAILBOXQ_EVENT_PENDING, pf->state))
1521                 return;
1522
1523         if (__ice_clean_ctrlq(pf, ICE_CTL_Q_MAILBOX))
1524                 return;
1525
1526         clear_bit(ICE_MAILBOXQ_EVENT_PENDING, pf->state);
1527
1528         if (ice_ctrlq_pending(hw, &hw->mailboxq))
1529                 __ice_clean_ctrlq(pf, ICE_CTL_Q_MAILBOX);
1530
1531         ice_flush(hw);
1532 }
1533
1534 /**
1535  * ice_clean_sbq_subtask - clean the Sideband Queue rings
1536  * @pf: board private structure
1537  */
1538 static void ice_clean_sbq_subtask(struct ice_pf *pf)
1539 {
1540         struct ice_hw *hw = &pf->hw;
1541
1542         /* Nothing to do here if sideband queue is not supported */
1543         if (!ice_is_sbq_supported(hw)) {
1544                 clear_bit(ICE_SIDEBANDQ_EVENT_PENDING, pf->state);
1545                 return;
1546         }
1547
1548         if (!test_bit(ICE_SIDEBANDQ_EVENT_PENDING, pf->state))
1549                 return;
1550
1551         if (__ice_clean_ctrlq(pf, ICE_CTL_Q_SB))
1552                 return;
1553
1554         clear_bit(ICE_SIDEBANDQ_EVENT_PENDING, pf->state);
1555
1556         if (ice_ctrlq_pending(hw, &hw->sbq))
1557                 __ice_clean_ctrlq(pf, ICE_CTL_Q_SB);
1558
1559         ice_flush(hw);
1560 }
1561
1562 /**
1563  * ice_service_task_schedule - schedule the service task to wake up
1564  * @pf: board private structure
1565  *
1566  * If not already scheduled, this puts the task into the work queue.
1567  */
1568 void ice_service_task_schedule(struct ice_pf *pf)
1569 {
1570         if (!test_bit(ICE_SERVICE_DIS, pf->state) &&
1571             !test_and_set_bit(ICE_SERVICE_SCHED, pf->state) &&
1572             !test_bit(ICE_NEEDS_RESTART, pf->state))
1573                 queue_work(ice_wq, &pf->serv_task);
1574 }
1575
1576 /**
1577  * ice_service_task_complete - finish up the service task
1578  * @pf: board private structure
1579  */
1580 static void ice_service_task_complete(struct ice_pf *pf)
1581 {
1582         WARN_ON(!test_bit(ICE_SERVICE_SCHED, pf->state));
1583
1584         /* force memory (pf->state) to sync before next service task */
1585         smp_mb__before_atomic();
1586         clear_bit(ICE_SERVICE_SCHED, pf->state);
1587 }
1588
1589 /**
1590  * ice_service_task_stop - stop service task and cancel works
1591  * @pf: board private structure
1592  *
1593  * Return 0 if the ICE_SERVICE_DIS bit was not already set,
1594  * 1 otherwise.
1595  */
1596 static int ice_service_task_stop(struct ice_pf *pf)
1597 {
1598         int ret;
1599
1600         ret = test_and_set_bit(ICE_SERVICE_DIS, pf->state);
1601
1602         if (pf->serv_tmr.function)
1603                 del_timer_sync(&pf->serv_tmr);
1604         if (pf->serv_task.func)
1605                 cancel_work_sync(&pf->serv_task);
1606
1607         clear_bit(ICE_SERVICE_SCHED, pf->state);
1608         return ret;
1609 }
1610
1611 /**
1612  * ice_service_task_restart - restart service task and schedule works
1613  * @pf: board private structure
1614  *
1615  * This function is needed for suspend and resume works (e.g WoL scenario)
1616  */
1617 static void ice_service_task_restart(struct ice_pf *pf)
1618 {
1619         clear_bit(ICE_SERVICE_DIS, pf->state);
1620         ice_service_task_schedule(pf);
1621 }
1622
1623 /**
1624  * ice_service_timer - timer callback to schedule service task
1625  * @t: pointer to timer_list
1626  */
1627 static void ice_service_timer(struct timer_list *t)
1628 {
1629         struct ice_pf *pf = from_timer(pf, t, serv_tmr);
1630
1631         mod_timer(&pf->serv_tmr, round_jiffies(pf->serv_tmr_period + jiffies));
1632         ice_service_task_schedule(pf);
1633 }
1634
1635 /**
1636  * ice_handle_mdd_event - handle malicious driver detect event
1637  * @pf: pointer to the PF structure
1638  *
1639  * Called from service task. OICR interrupt handler indicates MDD event.
1640  * VF MDD logging is guarded by net_ratelimit. Additional PF and VF log
1641  * messages are wrapped by netif_msg_[rx|tx]_err. Since VF Rx MDD events
1642  * disable the queue, the PF can be configured to reset the VF using ethtool
1643  * private flag mdd-auto-reset-vf.
1644  */
1645 static void ice_handle_mdd_event(struct ice_pf *pf)
1646 {
1647         struct device *dev = ice_pf_to_dev(pf);
1648         struct ice_hw *hw = &pf->hw;
1649         unsigned int i;
1650         u32 reg;
1651
1652         if (!test_and_clear_bit(ICE_MDD_EVENT_PENDING, pf->state)) {
1653                 /* Since the VF MDD event logging is rate limited, check if
1654                  * there are pending MDD events.
1655                  */
1656                 ice_print_vfs_mdd_events(pf);
1657                 return;
1658         }
1659
1660         /* find what triggered an MDD event */
1661         reg = rd32(hw, GL_MDET_TX_PQM);
1662         if (reg & GL_MDET_TX_PQM_VALID_M) {
1663                 u8 pf_num = (reg & GL_MDET_TX_PQM_PF_NUM_M) >>
1664                                 GL_MDET_TX_PQM_PF_NUM_S;
1665                 u16 vf_num = (reg & GL_MDET_TX_PQM_VF_NUM_M) >>
1666                                 GL_MDET_TX_PQM_VF_NUM_S;
1667                 u8 event = (reg & GL_MDET_TX_PQM_MAL_TYPE_M) >>
1668                                 GL_MDET_TX_PQM_MAL_TYPE_S;
1669                 u16 queue = ((reg & GL_MDET_TX_PQM_QNUM_M) >>
1670                                 GL_MDET_TX_PQM_QNUM_S);
1671
1672                 if (netif_msg_tx_err(pf))
1673                         dev_info(dev, "Malicious Driver Detection event %d on TX queue %d PF# %d VF# %d\n",
1674                                  event, queue, pf_num, vf_num);
1675                 wr32(hw, GL_MDET_TX_PQM, 0xffffffff);
1676         }
1677
1678         reg = rd32(hw, GL_MDET_TX_TCLAN);
1679         if (reg & GL_MDET_TX_TCLAN_VALID_M) {
1680                 u8 pf_num = (reg & GL_MDET_TX_TCLAN_PF_NUM_M) >>
1681                                 GL_MDET_TX_TCLAN_PF_NUM_S;
1682                 u16 vf_num = (reg & GL_MDET_TX_TCLAN_VF_NUM_M) >>
1683                                 GL_MDET_TX_TCLAN_VF_NUM_S;
1684                 u8 event = (reg & GL_MDET_TX_TCLAN_MAL_TYPE_M) >>
1685                                 GL_MDET_TX_TCLAN_MAL_TYPE_S;
1686                 u16 queue = ((reg & GL_MDET_TX_TCLAN_QNUM_M) >>
1687                                 GL_MDET_TX_TCLAN_QNUM_S);
1688
1689                 if (netif_msg_tx_err(pf))
1690                         dev_info(dev, "Malicious Driver Detection event %d on TX queue %d PF# %d VF# %d\n",
1691                                  event, queue, pf_num, vf_num);
1692                 wr32(hw, GL_MDET_TX_TCLAN, 0xffffffff);
1693         }
1694
1695         reg = rd32(hw, GL_MDET_RX);
1696         if (reg & GL_MDET_RX_VALID_M) {
1697                 u8 pf_num = (reg & GL_MDET_RX_PF_NUM_M) >>
1698                                 GL_MDET_RX_PF_NUM_S;
1699                 u16 vf_num = (reg & GL_MDET_RX_VF_NUM_M) >>
1700                                 GL_MDET_RX_VF_NUM_S;
1701                 u8 event = (reg & GL_MDET_RX_MAL_TYPE_M) >>
1702                                 GL_MDET_RX_MAL_TYPE_S;
1703                 u16 queue = ((reg & GL_MDET_RX_QNUM_M) >>
1704                                 GL_MDET_RX_QNUM_S);
1705
1706                 if (netif_msg_rx_err(pf))
1707                         dev_info(dev, "Malicious Driver Detection event %d on RX queue %d PF# %d VF# %d\n",
1708                                  event, queue, pf_num, vf_num);
1709                 wr32(hw, GL_MDET_RX, 0xffffffff);
1710         }
1711
1712         /* check to see if this PF caused an MDD event */
1713         reg = rd32(hw, PF_MDET_TX_PQM);
1714         if (reg & PF_MDET_TX_PQM_VALID_M) {
1715                 wr32(hw, PF_MDET_TX_PQM, 0xFFFF);
1716                 if (netif_msg_tx_err(pf))
1717                         dev_info(dev, "Malicious Driver Detection event TX_PQM detected on PF\n");
1718         }
1719
1720         reg = rd32(hw, PF_MDET_TX_TCLAN);
1721         if (reg & PF_MDET_TX_TCLAN_VALID_M) {
1722                 wr32(hw, PF_MDET_TX_TCLAN, 0xFFFF);
1723                 if (netif_msg_tx_err(pf))
1724                         dev_info(dev, "Malicious Driver Detection event TX_TCLAN detected on PF\n");
1725         }
1726
1727         reg = rd32(hw, PF_MDET_RX);
1728         if (reg & PF_MDET_RX_VALID_M) {
1729                 wr32(hw, PF_MDET_RX, 0xFFFF);
1730                 if (netif_msg_rx_err(pf))
1731                         dev_info(dev, "Malicious Driver Detection event RX detected on PF\n");
1732         }
1733
1734         /* Check to see if one of the VFs caused an MDD event, and then
1735          * increment counters and set print pending
1736          */
1737         ice_for_each_vf(pf, i) {
1738                 struct ice_vf *vf = &pf->vf[i];
1739
1740                 reg = rd32(hw, VP_MDET_TX_PQM(i));
1741                 if (reg & VP_MDET_TX_PQM_VALID_M) {
1742                         wr32(hw, VP_MDET_TX_PQM(i), 0xFFFF);
1743                         vf->mdd_tx_events.count++;
1744                         set_bit(ICE_MDD_VF_PRINT_PENDING, pf->state);
1745                         if (netif_msg_tx_err(pf))
1746                                 dev_info(dev, "Malicious Driver Detection event TX_PQM detected on VF %d\n",
1747                                          i);
1748                 }
1749
1750                 reg = rd32(hw, VP_MDET_TX_TCLAN(i));
1751                 if (reg & VP_MDET_TX_TCLAN_VALID_M) {
1752                         wr32(hw, VP_MDET_TX_TCLAN(i), 0xFFFF);
1753                         vf->mdd_tx_events.count++;
1754                         set_bit(ICE_MDD_VF_PRINT_PENDING, pf->state);
1755                         if (netif_msg_tx_err(pf))
1756                                 dev_info(dev, "Malicious Driver Detection event TX_TCLAN detected on VF %d\n",
1757                                          i);
1758                 }
1759
1760                 reg = rd32(hw, VP_MDET_TX_TDPU(i));
1761                 if (reg & VP_MDET_TX_TDPU_VALID_M) {
1762                         wr32(hw, VP_MDET_TX_TDPU(i), 0xFFFF);
1763                         vf->mdd_tx_events.count++;
1764                         set_bit(ICE_MDD_VF_PRINT_PENDING, pf->state);
1765                         if (netif_msg_tx_err(pf))
1766                                 dev_info(dev, "Malicious Driver Detection event TX_TDPU detected on VF %d\n",
1767                                          i);
1768                 }
1769
1770                 reg = rd32(hw, VP_MDET_RX(i));
1771                 if (reg & VP_MDET_RX_VALID_M) {
1772                         wr32(hw, VP_MDET_RX(i), 0xFFFF);
1773                         vf->mdd_rx_events.count++;
1774                         set_bit(ICE_MDD_VF_PRINT_PENDING, pf->state);
1775                         if (netif_msg_rx_err(pf))
1776                                 dev_info(dev, "Malicious Driver Detection event RX detected on VF %d\n",
1777                                          i);
1778
1779                         /* Since the queue is disabled on VF Rx MDD events, the
1780                          * PF can be configured to reset the VF through ethtool
1781                          * private flag mdd-auto-reset-vf.
1782                          */
1783                         if (test_bit(ICE_FLAG_MDD_AUTO_RESET_VF, pf->flags)) {
1784                                 /* VF MDD event counters will be cleared by
1785                                  * reset, so print the event prior to reset.
1786                                  */
1787                                 ice_print_vf_rx_mdd_event(vf);
1788                                 ice_reset_vf(&pf->vf[i], false);
1789                         }
1790                 }
1791         }
1792
1793         ice_print_vfs_mdd_events(pf);
1794 }
1795
1796 /**
1797  * ice_force_phys_link_state - Force the physical link state
1798  * @vsi: VSI to force the physical link state to up/down
1799  * @link_up: true/false indicates to set the physical link to up/down
1800  *
1801  * Force the physical link state by getting the current PHY capabilities from
1802  * hardware and setting the PHY config based on the determined capabilities. If
1803  * link changes a link event will be triggered because both the Enable Automatic
1804  * Link Update and LESM Enable bits are set when setting the PHY capabilities.
1805  *
1806  * Returns 0 on success, negative on failure
1807  */
1808 static int ice_force_phys_link_state(struct ice_vsi *vsi, bool link_up)
1809 {
1810         struct ice_aqc_get_phy_caps_data *pcaps;
1811         struct ice_aqc_set_phy_cfg_data *cfg;
1812         struct ice_port_info *pi;
1813         struct device *dev;
1814         int retcode;
1815
1816         if (!vsi || !vsi->port_info || !vsi->back)
1817                 return -EINVAL;
1818         if (vsi->type != ICE_VSI_PF)
1819                 return 0;
1820
1821         dev = ice_pf_to_dev(vsi->back);
1822
1823         pi = vsi->port_info;
1824
1825         pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL);
1826         if (!pcaps)
1827                 return -ENOMEM;
1828
1829         retcode = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_ACTIVE_CFG, pcaps,
1830                                       NULL);
1831         if (retcode) {
1832                 dev_err(dev, "Failed to get phy capabilities, VSI %d error %d\n",
1833                         vsi->vsi_num, retcode);
1834                 retcode = -EIO;
1835                 goto out;
1836         }
1837
1838         /* No change in link */
1839         if (link_up == !!(pcaps->caps & ICE_AQC_PHY_EN_LINK) &&
1840             link_up == !!(pi->phy.link_info.link_info & ICE_AQ_LINK_UP))
1841                 goto out;
1842
1843         /* Use the current user PHY configuration. The current user PHY
1844          * configuration is initialized during probe from PHY capabilities
1845          * software mode, and updated on set PHY configuration.
1846          */
1847         cfg = kmemdup(&pi->phy.curr_user_phy_cfg, sizeof(*cfg), GFP_KERNEL);
1848         if (!cfg) {
1849                 retcode = -ENOMEM;
1850                 goto out;
1851         }
1852
1853         cfg->caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT;
1854         if (link_up)
1855                 cfg->caps |= ICE_AQ_PHY_ENA_LINK;
1856         else
1857                 cfg->caps &= ~ICE_AQ_PHY_ENA_LINK;
1858
1859         retcode = ice_aq_set_phy_cfg(&vsi->back->hw, pi, cfg, NULL);
1860         if (retcode) {
1861                 dev_err(dev, "Failed to set phy config, VSI %d error %d\n",
1862                         vsi->vsi_num, retcode);
1863                 retcode = -EIO;
1864         }
1865
1866         kfree(cfg);
1867 out:
1868         kfree(pcaps);
1869         return retcode;
1870 }
1871
1872 /**
1873  * ice_init_nvm_phy_type - Initialize the NVM PHY type
1874  * @pi: port info structure
1875  *
1876  * Initialize nvm_phy_type_[low|high] for link lenient mode support
1877  */
1878 static int ice_init_nvm_phy_type(struct ice_port_info *pi)
1879 {
1880         struct ice_aqc_get_phy_caps_data *pcaps;
1881         struct ice_pf *pf = pi->hw->back;
1882         enum ice_status status;
1883         int err = 0;
1884
1885         pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL);
1886         if (!pcaps)
1887                 return -ENOMEM;
1888
1889         status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_TOPO_CAP_NO_MEDIA, pcaps,
1890                                      NULL);
1891
1892         if (status) {
1893                 dev_err(ice_pf_to_dev(pf), "Get PHY capability failed.\n");
1894                 err = -EIO;
1895                 goto out;
1896         }
1897
1898         pf->nvm_phy_type_hi = pcaps->phy_type_high;
1899         pf->nvm_phy_type_lo = pcaps->phy_type_low;
1900
1901 out:
1902         kfree(pcaps);
1903         return err;
1904 }
1905
1906 /**
1907  * ice_init_link_dflt_override - Initialize link default override
1908  * @pi: port info structure
1909  *
1910  * Initialize link default override and PHY total port shutdown during probe
1911  */
1912 static void ice_init_link_dflt_override(struct ice_port_info *pi)
1913 {
1914         struct ice_link_default_override_tlv *ldo;
1915         struct ice_pf *pf = pi->hw->back;
1916
1917         ldo = &pf->link_dflt_override;
1918         if (ice_get_link_default_override(ldo, pi))
1919                 return;
1920
1921         if (!(ldo->options & ICE_LINK_OVERRIDE_PORT_DIS))
1922                 return;
1923
1924         /* Enable Total Port Shutdown (override/replace link-down-on-close
1925          * ethtool private flag) for ports with Port Disable bit set.
1926          */
1927         set_bit(ICE_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags);
1928         set_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags);
1929 }
1930
1931 /**
1932  * ice_init_phy_cfg_dflt_override - Initialize PHY cfg default override settings
1933  * @pi: port info structure
1934  *
1935  * If default override is enabled, initialize the user PHY cfg speed and FEC
1936  * settings using the default override mask from the NVM.
1937  *
1938  * The PHY should only be configured with the default override settings the
1939  * first time media is available. The ICE_LINK_DEFAULT_OVERRIDE_PENDING state
1940  * is used to indicate that the user PHY cfg default override is initialized
1941  * and the PHY has not been configured with the default override settings. The
1942  * state is set here, and cleared in ice_configure_phy the first time the PHY is
1943  * configured.
1944  *
1945  * This function should be called only if the FW doesn't support default
1946  * configuration mode, as reported by ice_fw_supports_report_dflt_cfg.
1947  */
1948 static void ice_init_phy_cfg_dflt_override(struct ice_port_info *pi)
1949 {
1950         struct ice_link_default_override_tlv *ldo;
1951         struct ice_aqc_set_phy_cfg_data *cfg;
1952         struct ice_phy_info *phy = &pi->phy;
1953         struct ice_pf *pf = pi->hw->back;
1954
1955         ldo = &pf->link_dflt_override;
1956
1957         /* If link default override is enabled, use to mask NVM PHY capabilities
1958          * for speed and FEC default configuration.
1959          */
1960         cfg = &phy->curr_user_phy_cfg;
1961
1962         if (ldo->phy_type_low || ldo->phy_type_high) {
1963                 cfg->phy_type_low = pf->nvm_phy_type_lo &
1964                                     cpu_to_le64(ldo->phy_type_low);
1965                 cfg->phy_type_high = pf->nvm_phy_type_hi &
1966                                      cpu_to_le64(ldo->phy_type_high);
1967         }
1968         cfg->link_fec_opt = ldo->fec_options;
1969         phy->curr_user_fec_req = ICE_FEC_AUTO;
1970
1971         set_bit(ICE_LINK_DEFAULT_OVERRIDE_PENDING, pf->state);
1972 }
1973
1974 /**
1975  * ice_init_phy_user_cfg - Initialize the PHY user configuration
1976  * @pi: port info structure
1977  *
1978  * Initialize the current user PHY configuration, speed, FEC, and FC requested
1979  * mode to default. The PHY defaults are from get PHY capabilities topology
1980  * with media so call when media is first available. An error is returned if
1981  * called when media is not available. The PHY initialization completed state is
1982  * set here.
1983  *
1984  * These configurations are used when setting PHY
1985  * configuration. The user PHY configuration is updated on set PHY
1986  * configuration. Returns 0 on success, negative on failure
1987  */
1988 static int ice_init_phy_user_cfg(struct ice_port_info *pi)
1989 {
1990         struct ice_aqc_get_phy_caps_data *pcaps;
1991         struct ice_phy_info *phy = &pi->phy;
1992         struct ice_pf *pf = pi->hw->back;
1993         enum ice_status status;
1994         int err = 0;
1995
1996         if (!(phy->link_info.link_info & ICE_AQ_MEDIA_AVAILABLE))
1997                 return -EIO;
1998
1999         pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL);
2000         if (!pcaps)
2001                 return -ENOMEM;
2002
2003         if (ice_fw_supports_report_dflt_cfg(pi->hw))
2004                 status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_DFLT_CFG,
2005                                              pcaps, NULL);
2006         else
2007                 status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_TOPO_CAP_MEDIA,
2008                                              pcaps, NULL);
2009         if (status) {
2010                 dev_err(ice_pf_to_dev(pf), "Get PHY capability failed.\n");
2011                 err = -EIO;
2012                 goto err_out;
2013         }
2014
2015         ice_copy_phy_caps_to_cfg(pi, pcaps, &pi->phy.curr_user_phy_cfg);
2016
2017         /* check if lenient mode is supported and enabled */
2018         if (ice_fw_supports_link_override(pi->hw) &&
2019             !(pcaps->module_compliance_enforcement &
2020               ICE_AQC_MOD_ENFORCE_STRICT_MODE)) {
2021                 set_bit(ICE_FLAG_LINK_LENIENT_MODE_ENA, pf->flags);
2022
2023                 /* if the FW supports default PHY configuration mode, then the driver
2024                  * does not have to apply link override settings. If not,
2025                  * initialize user PHY configuration with link override values
2026                  */
2027                 if (!ice_fw_supports_report_dflt_cfg(pi->hw) &&
2028                     (pf->link_dflt_override.options & ICE_LINK_OVERRIDE_EN)) {
2029                         ice_init_phy_cfg_dflt_override(pi);
2030                         goto out;
2031                 }
2032         }
2033
2034         /* if link default override is not enabled, set user flow control and
2035          * FEC settings based on what get_phy_caps returned
2036          */
2037         phy->curr_user_fec_req = ice_caps_to_fec_mode(pcaps->caps,
2038                                                       pcaps->link_fec_options);
2039         phy->curr_user_fc_req = ice_caps_to_fc_mode(pcaps->caps);
2040
2041 out:
2042         phy->curr_user_speed_req = ICE_AQ_LINK_SPEED_M;
2043         set_bit(ICE_PHY_INIT_COMPLETE, pf->state);
2044 err_out:
2045         kfree(pcaps);
2046         return err;
2047 }
2048
2049 /**
2050  * ice_configure_phy - configure PHY
2051  * @vsi: VSI of PHY
2052  *
2053  * Set the PHY configuration. If the current PHY configuration is the same as
2054  * the curr_user_phy_cfg, then do nothing to avoid link flap. Otherwise
2055  * configure the based get PHY capabilities for topology with media.
2056  */
2057 static int ice_configure_phy(struct ice_vsi *vsi)
2058 {
2059         struct device *dev = ice_pf_to_dev(vsi->back);
2060         struct ice_port_info *pi = vsi->port_info;
2061         struct ice_aqc_get_phy_caps_data *pcaps;
2062         struct ice_aqc_set_phy_cfg_data *cfg;
2063         struct ice_phy_info *phy = &pi->phy;
2064         struct ice_pf *pf = vsi->back;
2065         enum ice_status status;
2066         int err = 0;
2067
2068         /* Ensure we have media as we cannot configure a medialess port */
2069         if (!(phy->link_info.link_info & ICE_AQ_MEDIA_AVAILABLE))
2070                 return -EPERM;
2071
2072         ice_print_topo_conflict(vsi);
2073
2074         if (!test_bit(ICE_FLAG_LINK_LENIENT_MODE_ENA, pf->flags) &&
2075             phy->link_info.topo_media_conflict == ICE_AQ_LINK_TOPO_UNSUPP_MEDIA)
2076                 return -EPERM;
2077
2078         if (test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags))
2079                 return ice_force_phys_link_state(vsi, true);
2080
2081         pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL);
2082         if (!pcaps)
2083                 return -ENOMEM;
2084
2085         /* Get current PHY config */
2086         status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_ACTIVE_CFG, pcaps,
2087                                      NULL);
2088         if (status) {
2089                 dev_err(dev, "Failed to get PHY configuration, VSI %d error %s\n",
2090                         vsi->vsi_num, ice_stat_str(status));
2091                 err = -EIO;
2092                 goto done;
2093         }
2094
2095         /* If PHY enable link is configured and configuration has not changed,
2096          * there's nothing to do
2097          */
2098         if (pcaps->caps & ICE_AQC_PHY_EN_LINK &&
2099             ice_phy_caps_equals_cfg(pcaps, &phy->curr_user_phy_cfg))
2100                 goto done;
2101
2102         /* Use PHY topology as baseline for configuration */
2103         memset(pcaps, 0, sizeof(*pcaps));
2104         if (ice_fw_supports_report_dflt_cfg(pi->hw))
2105                 status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_DFLT_CFG,
2106                                              pcaps, NULL);
2107         else
2108                 status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_TOPO_CAP_MEDIA,
2109                                              pcaps, NULL);
2110         if (status) {
2111                 dev_err(dev, "Failed to get PHY caps, VSI %d error %s\n",
2112                         vsi->vsi_num, ice_stat_str(status));
2113                 err = -EIO;
2114                 goto done;
2115         }
2116
2117         cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
2118         if (!cfg) {
2119                 err = -ENOMEM;
2120                 goto done;
2121         }
2122
2123         ice_copy_phy_caps_to_cfg(pi, pcaps, cfg);
2124
2125         /* Speed - If default override pending, use curr_user_phy_cfg set in
2126          * ice_init_phy_user_cfg_ldo.
2127          */
2128         if (test_and_clear_bit(ICE_LINK_DEFAULT_OVERRIDE_PENDING,
2129                                vsi->back->state)) {
2130                 cfg->phy_type_low = phy->curr_user_phy_cfg.phy_type_low;
2131                 cfg->phy_type_high = phy->curr_user_phy_cfg.phy_type_high;
2132         } else {
2133                 u64 phy_low = 0, phy_high = 0;
2134
2135                 ice_update_phy_type(&phy_low, &phy_high,
2136                                     pi->phy.curr_user_speed_req);
2137                 cfg->phy_type_low = pcaps->phy_type_low & cpu_to_le64(phy_low);
2138                 cfg->phy_type_high = pcaps->phy_type_high &
2139                                      cpu_to_le64(phy_high);
2140         }
2141
2142         /* Can't provide what was requested; use PHY capabilities */
2143         if (!cfg->phy_type_low && !cfg->phy_type_high) {
2144                 cfg->phy_type_low = pcaps->phy_type_low;
2145                 cfg->phy_type_high = pcaps->phy_type_high;
2146         }
2147
2148         /* FEC */
2149         ice_cfg_phy_fec(pi, cfg, phy->curr_user_fec_req);
2150
2151         /* Can't provide what was requested; use PHY capabilities */
2152         if (cfg->link_fec_opt !=
2153             (cfg->link_fec_opt & pcaps->link_fec_options)) {
2154                 cfg->caps |= pcaps->caps & ICE_AQC_PHY_EN_AUTO_FEC;
2155                 cfg->link_fec_opt = pcaps->link_fec_options;
2156         }
2157
2158         /* Flow Control - always supported; no need to check against
2159          * capabilities
2160          */
2161         ice_cfg_phy_fc(pi, cfg, phy->curr_user_fc_req);
2162
2163         /* Enable link and link update */
2164         cfg->caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT | ICE_AQ_PHY_ENA_LINK;
2165
2166         status = ice_aq_set_phy_cfg(&pf->hw, pi, cfg, NULL);
2167         if (status) {
2168                 dev_err(dev, "Failed to set phy config, VSI %d error %s\n",
2169                         vsi->vsi_num, ice_stat_str(status));
2170                 err = -EIO;
2171         }
2172
2173         kfree(cfg);
2174 done:
2175         kfree(pcaps);
2176         return err;
2177 }
2178
2179 /**
2180  * ice_check_media_subtask - Check for media
2181  * @pf: pointer to PF struct
2182  *
2183  * If media is available, then initialize PHY user configuration if it is not
2184  * been, and configure the PHY if the interface is up.
2185  */
2186 static void ice_check_media_subtask(struct ice_pf *pf)
2187 {
2188         struct ice_port_info *pi;
2189         struct ice_vsi *vsi;
2190         int err;
2191
2192         /* No need to check for media if it's already present */
2193         if (!test_bit(ICE_FLAG_NO_MEDIA, pf->flags))
2194                 return;
2195
2196         vsi = ice_get_main_vsi(pf);
2197         if (!vsi)
2198                 return;
2199
2200         /* Refresh link info and check if media is present */
2201         pi = vsi->port_info;
2202         err = ice_update_link_info(pi);
2203         if (err)
2204                 return;
2205
2206         ice_check_link_cfg_err(pf, pi->phy.link_info.link_cfg_err);
2207
2208         if (pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE) {
2209                 if (!test_bit(ICE_PHY_INIT_COMPLETE, pf->state))
2210                         ice_init_phy_user_cfg(pi);
2211
2212                 /* PHY settings are reset on media insertion, reconfigure
2213                  * PHY to preserve settings.
2214                  */
2215                 if (test_bit(ICE_VSI_DOWN, vsi->state) &&
2216                     test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags))
2217                         return;
2218
2219                 err = ice_configure_phy(vsi);
2220                 if (!err)
2221                         clear_bit(ICE_FLAG_NO_MEDIA, pf->flags);
2222
2223                 /* A Link Status Event will be generated; the event handler
2224                  * will complete bringing the interface up
2225                  */
2226         }
2227 }
2228
2229 /**
2230  * ice_service_task - manage and run subtasks
2231  * @work: pointer to work_struct contained by the PF struct
2232  */
2233 static void ice_service_task(struct work_struct *work)
2234 {
2235         struct ice_pf *pf = container_of(work, struct ice_pf, serv_task);
2236         unsigned long start_time = jiffies;
2237
2238         /* subtasks */
2239
2240         /* process reset requests first */
2241         ice_reset_subtask(pf);
2242
2243         /* bail if a reset/recovery cycle is pending or rebuild failed */
2244         if (ice_is_reset_in_progress(pf->state) ||
2245             test_bit(ICE_SUSPENDED, pf->state) ||
2246             test_bit(ICE_NEEDS_RESTART, pf->state)) {
2247                 ice_service_task_complete(pf);
2248                 return;
2249         }
2250
2251         ice_clean_adminq_subtask(pf);
2252         ice_check_media_subtask(pf);
2253         ice_check_for_hang_subtask(pf);
2254         ice_sync_fltr_subtask(pf);
2255         ice_handle_mdd_event(pf);
2256         ice_watchdog_subtask(pf);
2257
2258         if (ice_is_safe_mode(pf)) {
2259                 ice_service_task_complete(pf);
2260                 return;
2261         }
2262
2263         ice_process_vflr_event(pf);
2264         ice_clean_mailboxq_subtask(pf);
2265         ice_clean_sbq_subtask(pf);
2266         ice_sync_arfs_fltrs(pf);
2267         ice_flush_fdir_ctx(pf);
2268
2269         /* Clear ICE_SERVICE_SCHED flag to allow scheduling next event */
2270         ice_service_task_complete(pf);
2271
2272         /* If the tasks have taken longer than one service timer period
2273          * or there is more work to be done, reset the service timer to
2274          * schedule the service task now.
2275          */
2276         if (time_after(jiffies, (start_time + pf->serv_tmr_period)) ||
2277             test_bit(ICE_MDD_EVENT_PENDING, pf->state) ||
2278             test_bit(ICE_VFLR_EVENT_PENDING, pf->state) ||
2279             test_bit(ICE_MAILBOXQ_EVENT_PENDING, pf->state) ||
2280             test_bit(ICE_FD_VF_FLUSH_CTX, pf->state) ||
2281             test_bit(ICE_SIDEBANDQ_EVENT_PENDING, pf->state) ||
2282             test_bit(ICE_ADMINQ_EVENT_PENDING, pf->state))
2283                 mod_timer(&pf->serv_tmr, jiffies);
2284 }
2285
2286 /**
2287  * ice_set_ctrlq_len - helper function to set controlq length
2288  * @hw: pointer to the HW instance
2289  */
2290 static void ice_set_ctrlq_len(struct ice_hw *hw)
2291 {
2292         hw->adminq.num_rq_entries = ICE_AQ_LEN;
2293         hw->adminq.num_sq_entries = ICE_AQ_LEN;
2294         hw->adminq.rq_buf_size = ICE_AQ_MAX_BUF_LEN;
2295         hw->adminq.sq_buf_size = ICE_AQ_MAX_BUF_LEN;
2296         hw->mailboxq.num_rq_entries = PF_MBX_ARQLEN_ARQLEN_M;
2297         hw->mailboxq.num_sq_entries = ICE_MBXSQ_LEN;
2298         hw->mailboxq.rq_buf_size = ICE_MBXQ_MAX_BUF_LEN;
2299         hw->mailboxq.sq_buf_size = ICE_MBXQ_MAX_BUF_LEN;
2300         hw->sbq.num_rq_entries = ICE_SBQ_LEN;
2301         hw->sbq.num_sq_entries = ICE_SBQ_LEN;
2302         hw->sbq.rq_buf_size = ICE_SBQ_MAX_BUF_LEN;
2303         hw->sbq.sq_buf_size = ICE_SBQ_MAX_BUF_LEN;
2304 }
2305
2306 /**
2307  * ice_schedule_reset - schedule a reset
2308  * @pf: board private structure
2309  * @reset: reset being requested
2310  */
2311 int ice_schedule_reset(struct ice_pf *pf, enum ice_reset_req reset)
2312 {
2313         struct device *dev = ice_pf_to_dev(pf);
2314
2315         /* bail out if earlier reset has failed */
2316         if (test_bit(ICE_RESET_FAILED, pf->state)) {
2317                 dev_dbg(dev, "earlier reset has failed\n");
2318                 return -EIO;
2319         }
2320         /* bail if reset/recovery already in progress */
2321         if (ice_is_reset_in_progress(pf->state)) {
2322                 dev_dbg(dev, "Reset already in progress\n");
2323                 return -EBUSY;
2324         }
2325
2326         ice_unplug_aux_dev(pf);
2327
2328         switch (reset) {
2329         case ICE_RESET_PFR:
2330                 set_bit(ICE_PFR_REQ, pf->state);
2331                 break;
2332         case ICE_RESET_CORER:
2333                 set_bit(ICE_CORER_REQ, pf->state);
2334                 break;
2335         case ICE_RESET_GLOBR:
2336                 set_bit(ICE_GLOBR_REQ, pf->state);
2337                 break;
2338         default:
2339                 return -EINVAL;
2340         }
2341
2342         ice_service_task_schedule(pf);
2343         return 0;
2344 }
2345
2346 /**
2347  * ice_irq_affinity_notify - Callback for affinity changes
2348  * @notify: context as to what irq was changed
2349  * @mask: the new affinity mask
2350  *
2351  * This is a callback function used by the irq_set_affinity_notifier function
2352  * so that we may register to receive changes to the irq affinity masks.
2353  */
2354 static void
2355 ice_irq_affinity_notify(struct irq_affinity_notify *notify,
2356                         const cpumask_t *mask)
2357 {
2358         struct ice_q_vector *q_vector =
2359                 container_of(notify, struct ice_q_vector, affinity_notify);
2360
2361         cpumask_copy(&q_vector->affinity_mask, mask);
2362 }
2363
2364 /**
2365  * ice_irq_affinity_release - Callback for affinity notifier release
2366  * @ref: internal core kernel usage
2367  *
2368  * This is a callback function used by the irq_set_affinity_notifier function
2369  * to inform the current notification subscriber that they will no longer
2370  * receive notifications.
2371  */
2372 static void ice_irq_affinity_release(struct kref __always_unused *ref) {}
2373
2374 /**
2375  * ice_vsi_ena_irq - Enable IRQ for the given VSI
2376  * @vsi: the VSI being configured
2377  */
2378 static int ice_vsi_ena_irq(struct ice_vsi *vsi)
2379 {
2380         struct ice_hw *hw = &vsi->back->hw;
2381         int i;
2382
2383         ice_for_each_q_vector(vsi, i)
2384                 ice_irq_dynamic_ena(hw, vsi, vsi->q_vectors[i]);
2385
2386         ice_flush(hw);
2387         return 0;
2388 }
2389
2390 /**
2391  * ice_vsi_req_irq_msix - get MSI-X vectors from the OS for the VSI
2392  * @vsi: the VSI being configured
2393  * @basename: name for the vector
2394  */
2395 static int ice_vsi_req_irq_msix(struct ice_vsi *vsi, char *basename)
2396 {
2397         int q_vectors = vsi->num_q_vectors;
2398         struct ice_pf *pf = vsi->back;
2399         int base = vsi->base_vector;
2400         struct device *dev;
2401         int rx_int_idx = 0;
2402         int tx_int_idx = 0;
2403         int vector, err;
2404         int irq_num;
2405
2406         dev = ice_pf_to_dev(pf);
2407         for (vector = 0; vector < q_vectors; vector++) {
2408                 struct ice_q_vector *q_vector = vsi->q_vectors[vector];
2409
2410                 irq_num = pf->msix_entries[base + vector].vector;
2411
2412                 if (q_vector->tx.tx_ring && q_vector->rx.rx_ring) {
2413                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
2414                                  "%s-%s-%d", basename, "TxRx", rx_int_idx++);
2415                         tx_int_idx++;
2416                 } else if (q_vector->rx.rx_ring) {
2417                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
2418                                  "%s-%s-%d", basename, "rx", rx_int_idx++);
2419                 } else if (q_vector->tx.tx_ring) {
2420                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
2421                                  "%s-%s-%d", basename, "tx", tx_int_idx++);
2422                 } else {
2423                         /* skip this unused q_vector */
2424                         continue;
2425                 }
2426                 if (vsi->type == ICE_VSI_CTRL && vsi->vf_id != ICE_INVAL_VFID)
2427                         err = devm_request_irq(dev, irq_num, vsi->irq_handler,
2428                                                IRQF_SHARED, q_vector->name,
2429                                                q_vector);
2430                 else
2431                         err = devm_request_irq(dev, irq_num, vsi->irq_handler,
2432                                                0, q_vector->name, q_vector);
2433                 if (err) {
2434                         netdev_err(vsi->netdev, "MSIX request_irq failed, error: %d\n",
2435                                    err);
2436                         goto free_q_irqs;
2437                 }
2438
2439                 /* register for affinity change notifications */
2440                 if (!IS_ENABLED(CONFIG_RFS_ACCEL)) {
2441                         struct irq_affinity_notify *affinity_notify;
2442
2443                         affinity_notify = &q_vector->affinity_notify;
2444                         affinity_notify->notify = ice_irq_affinity_notify;
2445                         affinity_notify->release = ice_irq_affinity_release;
2446                         irq_set_affinity_notifier(irq_num, affinity_notify);
2447                 }
2448
2449                 /* assign the mask for this irq */
2450                 irq_set_affinity_hint(irq_num, &q_vector->affinity_mask);
2451         }
2452
2453         vsi->irqs_ready = true;
2454         return 0;
2455
2456 free_q_irqs:
2457         while (vector) {
2458                 vector--;
2459                 irq_num = pf->msix_entries[base + vector].vector;
2460                 if (!IS_ENABLED(CONFIG_RFS_ACCEL))
2461                         irq_set_affinity_notifier(irq_num, NULL);
2462                 irq_set_affinity_hint(irq_num, NULL);
2463                 devm_free_irq(dev, irq_num, &vsi->q_vectors[vector]);
2464         }
2465         return err;
2466 }
2467
2468 /**
2469  * ice_xdp_alloc_setup_rings - Allocate and setup Tx rings for XDP
2470  * @vsi: VSI to setup Tx rings used by XDP
2471  *
2472  * Return 0 on success and negative value on error
2473  */
2474 static int ice_xdp_alloc_setup_rings(struct ice_vsi *vsi)
2475 {
2476         struct device *dev = ice_pf_to_dev(vsi->back);
2477         struct ice_tx_desc *tx_desc;
2478         int i, j;
2479
2480         ice_for_each_xdp_txq(vsi, i) {
2481                 u16 xdp_q_idx = vsi->alloc_txq + i;
2482                 struct ice_tx_ring *xdp_ring;
2483
2484                 xdp_ring = kzalloc(sizeof(*xdp_ring), GFP_KERNEL);
2485
2486                 if (!xdp_ring)
2487                         goto free_xdp_rings;
2488
2489                 xdp_ring->q_index = xdp_q_idx;
2490                 xdp_ring->reg_idx = vsi->txq_map[xdp_q_idx];
2491                 xdp_ring->vsi = vsi;
2492                 xdp_ring->netdev = NULL;
2493                 xdp_ring->next_dd = ICE_TX_THRESH - 1;
2494                 xdp_ring->next_rs = ICE_TX_THRESH - 1;
2495                 xdp_ring->dev = dev;
2496                 xdp_ring->count = vsi->num_tx_desc;
2497                 WRITE_ONCE(vsi->xdp_rings[i], xdp_ring);
2498                 if (ice_setup_tx_ring(xdp_ring))
2499                         goto free_xdp_rings;
2500                 ice_set_ring_xdp(xdp_ring);
2501                 xdp_ring->xsk_pool = ice_tx_xsk_pool(xdp_ring);
2502                 spin_lock_init(&xdp_ring->tx_lock);
2503                 for (j = 0; j < xdp_ring->count; j++) {
2504                         tx_desc = ICE_TX_DESC(xdp_ring, j);
2505                         tx_desc->cmd_type_offset_bsz = cpu_to_le64(ICE_TX_DESC_DTYPE_DESC_DONE);
2506                 }
2507         }
2508
2509         ice_for_each_rxq(vsi, i) {
2510                 if (static_key_enabled(&ice_xdp_locking_key))
2511                         vsi->rx_rings[i]->xdp_ring = vsi->xdp_rings[i % vsi->num_xdp_txq];
2512                 else
2513                         vsi->rx_rings[i]->xdp_ring = vsi->xdp_rings[i];
2514         }
2515
2516         return 0;
2517
2518 free_xdp_rings:
2519         for (; i >= 0; i--)
2520                 if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
2521                         ice_free_tx_ring(vsi->xdp_rings[i]);
2522         return -ENOMEM;
2523 }
2524
2525 /**
2526  * ice_vsi_assign_bpf_prog - set or clear bpf prog pointer on VSI
2527  * @vsi: VSI to set the bpf prog on
2528  * @prog: the bpf prog pointer
2529  */
2530 static void ice_vsi_assign_bpf_prog(struct ice_vsi *vsi, struct bpf_prog *prog)
2531 {
2532         struct bpf_prog *old_prog;
2533         int i;
2534
2535         old_prog = xchg(&vsi->xdp_prog, prog);
2536         if (old_prog)
2537                 bpf_prog_put(old_prog);
2538
2539         ice_for_each_rxq(vsi, i)
2540                 WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
2541 }
2542
2543 /**
2544  * ice_prepare_xdp_rings - Allocate, configure and setup Tx rings for XDP
2545  * @vsi: VSI to bring up Tx rings used by XDP
2546  * @prog: bpf program that will be assigned to VSI
2547  *
2548  * Return 0 on success and negative value on error
2549  */
2550 int ice_prepare_xdp_rings(struct ice_vsi *vsi, struct bpf_prog *prog)
2551 {
2552         u16 max_txqs[ICE_MAX_TRAFFIC_CLASS] = { 0 };
2553         int xdp_rings_rem = vsi->num_xdp_txq;
2554         struct ice_pf *pf = vsi->back;
2555         struct ice_qs_cfg xdp_qs_cfg = {
2556                 .qs_mutex = &pf->avail_q_mutex,
2557                 .pf_map = pf->avail_txqs,
2558                 .pf_map_size = pf->max_pf_txqs,
2559                 .q_count = vsi->num_xdp_txq,
2560                 .scatter_count = ICE_MAX_SCATTER_TXQS,
2561                 .vsi_map = vsi->txq_map,
2562                 .vsi_map_offset = vsi->alloc_txq,
2563                 .mapping_mode = ICE_VSI_MAP_CONTIG
2564         };
2565         enum ice_status status;
2566         struct device *dev;
2567         int i, v_idx;
2568
2569         dev = ice_pf_to_dev(pf);
2570         vsi->xdp_rings = devm_kcalloc(dev, vsi->num_xdp_txq,
2571                                       sizeof(*vsi->xdp_rings), GFP_KERNEL);
2572         if (!vsi->xdp_rings)
2573                 return -ENOMEM;
2574
2575         vsi->xdp_mapping_mode = xdp_qs_cfg.mapping_mode;
2576         if (__ice_vsi_get_qs(&xdp_qs_cfg))
2577                 goto err_map_xdp;
2578
2579         if (static_key_enabled(&ice_xdp_locking_key))
2580                 netdev_warn(vsi->netdev,
2581                             "Could not allocate one XDP Tx ring per CPU, XDP_TX/XDP_REDIRECT actions will be slower\n");
2582
2583         if (ice_xdp_alloc_setup_rings(vsi))
2584                 goto clear_xdp_rings;
2585
2586         /* follow the logic from ice_vsi_map_rings_to_vectors */
2587         ice_for_each_q_vector(vsi, v_idx) {
2588                 struct ice_q_vector *q_vector = vsi->q_vectors[v_idx];
2589                 int xdp_rings_per_v, q_id, q_base;
2590
2591                 xdp_rings_per_v = DIV_ROUND_UP(xdp_rings_rem,
2592                                                vsi->num_q_vectors - v_idx);
2593                 q_base = vsi->num_xdp_txq - xdp_rings_rem;
2594
2595                 for (q_id = q_base; q_id < (q_base + xdp_rings_per_v); q_id++) {
2596                         struct ice_tx_ring *xdp_ring = vsi->xdp_rings[q_id];
2597
2598                         xdp_ring->q_vector = q_vector;
2599                         xdp_ring->next = q_vector->tx.tx_ring;
2600                         q_vector->tx.tx_ring = xdp_ring;
2601                 }
2602                 xdp_rings_rem -= xdp_rings_per_v;
2603         }
2604
2605         /* omit the scheduler update if in reset path; XDP queues will be
2606          * taken into account at the end of ice_vsi_rebuild, where
2607          * ice_cfg_vsi_lan is being called
2608          */
2609         if (ice_is_reset_in_progress(pf->state))
2610                 return 0;
2611
2612         /* tell the Tx scheduler that right now we have
2613          * additional queues
2614          */
2615         for (i = 0; i < vsi->tc_cfg.numtc; i++)
2616                 max_txqs[i] = vsi->num_txq + vsi->num_xdp_txq;
2617
2618         status = ice_cfg_vsi_lan(vsi->port_info, vsi->idx, vsi->tc_cfg.ena_tc,
2619                                  max_txqs);
2620         if (status) {
2621                 dev_err(dev, "Failed VSI LAN queue config for XDP, error: %s\n",
2622                         ice_stat_str(status));
2623                 goto clear_xdp_rings;
2624         }
2625
2626         /* assign the prog only when it's not already present on VSI;
2627          * this flow is a subject of both ethtool -L and ndo_bpf flows;
2628          * VSI rebuild that happens under ethtool -L can expose us to
2629          * the bpf_prog refcount issues as we would be swapping same
2630          * bpf_prog pointers from vsi->xdp_prog and calling bpf_prog_put
2631          * on it as it would be treated as an 'old_prog'; for ndo_bpf
2632          * this is not harmful as dev_xdp_install bumps the refcount
2633          * before calling the op exposed by the driver;
2634          */
2635         if (!ice_is_xdp_ena_vsi(vsi))
2636                 ice_vsi_assign_bpf_prog(vsi, prog);
2637
2638         return 0;
2639 clear_xdp_rings:
2640         ice_for_each_xdp_txq(vsi, i)
2641                 if (vsi->xdp_rings[i]) {
2642                         kfree_rcu(vsi->xdp_rings[i], rcu);
2643                         vsi->xdp_rings[i] = NULL;
2644                 }
2645
2646 err_map_xdp:
2647         mutex_lock(&pf->avail_q_mutex);
2648         ice_for_each_xdp_txq(vsi, i) {
2649                 clear_bit(vsi->txq_map[i + vsi->alloc_txq], pf->avail_txqs);
2650                 vsi->txq_map[i + vsi->alloc_txq] = ICE_INVAL_Q_INDEX;
2651         }
2652         mutex_unlock(&pf->avail_q_mutex);
2653
2654         devm_kfree(dev, vsi->xdp_rings);
2655         return -ENOMEM;
2656 }
2657
2658 /**
2659  * ice_destroy_xdp_rings - undo the configuration made by ice_prepare_xdp_rings
2660  * @vsi: VSI to remove XDP rings
2661  *
2662  * Detach XDP rings from irq vectors, clean up the PF bitmap and free
2663  * resources
2664  */
2665 int ice_destroy_xdp_rings(struct ice_vsi *vsi)
2666 {
2667         u16 max_txqs[ICE_MAX_TRAFFIC_CLASS] = { 0 };
2668         struct ice_pf *pf = vsi->back;
2669         int i, v_idx;
2670
2671         /* q_vectors are freed in reset path so there's no point in detaching
2672          * rings; in case of rebuild being triggered not from reset bits
2673          * in pf->state won't be set, so additionally check first q_vector
2674          * against NULL
2675          */
2676         if (ice_is_reset_in_progress(pf->state) || !vsi->q_vectors[0])
2677                 goto free_qmap;
2678
2679         ice_for_each_q_vector(vsi, v_idx) {
2680                 struct ice_q_vector *q_vector = vsi->q_vectors[v_idx];
2681                 struct ice_tx_ring *ring;
2682
2683                 ice_for_each_tx_ring(ring, q_vector->tx)
2684                         if (!ring->tx_buf || !ice_ring_is_xdp(ring))
2685                                 break;
2686
2687                 /* restore the value of last node prior to XDP setup */
2688                 q_vector->tx.tx_ring = ring;
2689         }
2690
2691 free_qmap:
2692         mutex_lock(&pf->avail_q_mutex);
2693         ice_for_each_xdp_txq(vsi, i) {
2694                 clear_bit(vsi->txq_map[i + vsi->alloc_txq], pf->avail_txqs);
2695                 vsi->txq_map[i + vsi->alloc_txq] = ICE_INVAL_Q_INDEX;
2696         }
2697         mutex_unlock(&pf->avail_q_mutex);
2698
2699         ice_for_each_xdp_txq(vsi, i)
2700                 if (vsi->xdp_rings[i]) {
2701                         if (vsi->xdp_rings[i]->desc)
2702                                 ice_free_tx_ring(vsi->xdp_rings[i]);
2703                         kfree_rcu(vsi->xdp_rings[i], rcu);
2704                         vsi->xdp_rings[i] = NULL;
2705                 }
2706
2707         devm_kfree(ice_pf_to_dev(pf), vsi->xdp_rings);
2708         vsi->xdp_rings = NULL;
2709
2710         if (static_key_enabled(&ice_xdp_locking_key))
2711                 static_branch_dec(&ice_xdp_locking_key);
2712
2713         if (ice_is_reset_in_progress(pf->state) || !vsi->q_vectors[0])
2714                 return 0;
2715
2716         ice_vsi_assign_bpf_prog(vsi, NULL);
2717
2718         /* notify Tx scheduler that we destroyed XDP queues and bring
2719          * back the old number of child nodes
2720          */
2721         for (i = 0; i < vsi->tc_cfg.numtc; i++)
2722                 max_txqs[i] = vsi->num_txq;
2723
2724         /* change number of XDP Tx queues to 0 */
2725         vsi->num_xdp_txq = 0;
2726
2727         return ice_cfg_vsi_lan(vsi->port_info, vsi->idx, vsi->tc_cfg.ena_tc,
2728                                max_txqs);
2729 }
2730
2731 /**
2732  * ice_vsi_rx_napi_schedule - Schedule napi on RX queues from VSI
2733  * @vsi: VSI to schedule napi on
2734  */
2735 static void ice_vsi_rx_napi_schedule(struct ice_vsi *vsi)
2736 {
2737         int i;
2738
2739         ice_for_each_rxq(vsi, i) {
2740                 struct ice_rx_ring *rx_ring = vsi->rx_rings[i];
2741
2742                 if (rx_ring->xsk_pool)
2743                         napi_schedule(&rx_ring->q_vector->napi);
2744         }
2745 }
2746
2747 /**
2748  * ice_vsi_determine_xdp_res - figure out how many Tx qs can XDP have
2749  * @vsi: VSI to determine the count of XDP Tx qs
2750  *
2751  * returns 0 if Tx qs count is higher than at least half of CPU count,
2752  * -ENOMEM otherwise
2753  */
2754 int ice_vsi_determine_xdp_res(struct ice_vsi *vsi)
2755 {
2756         u16 avail = ice_get_avail_txq_count(vsi->back);
2757         u16 cpus = num_possible_cpus();
2758
2759         if (avail < cpus / 2)
2760                 return -ENOMEM;
2761
2762         vsi->num_xdp_txq = min_t(u16, avail, cpus);
2763
2764         if (vsi->num_xdp_txq < cpus)
2765                 static_branch_inc(&ice_xdp_locking_key);
2766
2767         return 0;
2768 }
2769
2770 /**
2771  * ice_xdp_setup_prog - Add or remove XDP eBPF program
2772  * @vsi: VSI to setup XDP for
2773  * @prog: XDP program
2774  * @extack: netlink extended ack
2775  */
2776 static int
2777 ice_xdp_setup_prog(struct ice_vsi *vsi, struct bpf_prog *prog,
2778                    struct netlink_ext_ack *extack)
2779 {
2780         int frame_size = vsi->netdev->mtu + ICE_ETH_PKT_HDR_PAD;
2781         bool if_running = netif_running(vsi->netdev);
2782         int ret = 0, xdp_ring_err = 0;
2783
2784         if (frame_size > vsi->rx_buf_len) {
2785                 NL_SET_ERR_MSG_MOD(extack, "MTU too large for loading XDP");
2786                 return -EOPNOTSUPP;
2787         }
2788
2789         /* need to stop netdev while setting up the program for Rx rings */
2790         if (if_running && !test_and_set_bit(ICE_VSI_DOWN, vsi->state)) {
2791                 ret = ice_down(vsi);
2792                 if (ret) {
2793                         NL_SET_ERR_MSG_MOD(extack, "Preparing device for XDP attach failed");
2794                         return ret;
2795                 }
2796         }
2797
2798         if (!ice_is_xdp_ena_vsi(vsi) && prog) {
2799                 xdp_ring_err = ice_vsi_determine_xdp_res(vsi);
2800                 if (xdp_ring_err) {
2801                         NL_SET_ERR_MSG_MOD(extack, "Not enough Tx resources for XDP");
2802                 } else {
2803                         xdp_ring_err = ice_prepare_xdp_rings(vsi, prog);
2804                         if (xdp_ring_err)
2805                                 NL_SET_ERR_MSG_MOD(extack, "Setting up XDP Tx resources failed");
2806                 }
2807         } else if (ice_is_xdp_ena_vsi(vsi) && !prog) {
2808                 xdp_ring_err = ice_destroy_xdp_rings(vsi);
2809                 if (xdp_ring_err)
2810                         NL_SET_ERR_MSG_MOD(extack, "Freeing XDP Tx resources failed");
2811         } else {
2812                 /* safe to call even when prog == vsi->xdp_prog as
2813                  * dev_xdp_install in net/core/dev.c incremented prog's
2814                  * refcount so corresponding bpf_prog_put won't cause
2815                  * underflow
2816                  */
2817                 ice_vsi_assign_bpf_prog(vsi, prog);
2818         }
2819
2820         if (if_running)
2821                 ret = ice_up(vsi);
2822
2823         if (!ret && prog)
2824                 ice_vsi_rx_napi_schedule(vsi);
2825
2826         return (ret || xdp_ring_err) ? -ENOMEM : 0;
2827 }
2828
2829 /**
2830  * ice_xdp_safe_mode - XDP handler for safe mode
2831  * @dev: netdevice
2832  * @xdp: XDP command
2833  */
2834 static int ice_xdp_safe_mode(struct net_device __always_unused *dev,
2835                              struct netdev_bpf *xdp)
2836 {
2837         NL_SET_ERR_MSG_MOD(xdp->extack,
2838                            "Please provide working DDP firmware package in order to use XDP\n"
2839                            "Refer to Documentation/networking/device_drivers/ethernet/intel/ice.rst");
2840         return -EOPNOTSUPP;
2841 }
2842
2843 /**
2844  * ice_xdp - implements XDP handler
2845  * @dev: netdevice
2846  * @xdp: XDP command
2847  */
2848 static int ice_xdp(struct net_device *dev, struct netdev_bpf *xdp)
2849 {
2850         struct ice_netdev_priv *np = netdev_priv(dev);
2851         struct ice_vsi *vsi = np->vsi;
2852
2853         if (vsi->type != ICE_VSI_PF) {
2854                 NL_SET_ERR_MSG_MOD(xdp->extack, "XDP can be loaded only on PF VSI");
2855                 return -EINVAL;
2856         }
2857
2858         switch (xdp->command) {
2859         case XDP_SETUP_PROG:
2860                 return ice_xdp_setup_prog(vsi, xdp->prog, xdp->extack);
2861         case XDP_SETUP_XSK_POOL:
2862                 return ice_xsk_pool_setup(vsi, xdp->xsk.pool,
2863                                           xdp->xsk.queue_id);
2864         default:
2865                 return -EINVAL;
2866         }
2867 }
2868
2869 /**
2870  * ice_ena_misc_vector - enable the non-queue interrupts
2871  * @pf: board private structure
2872  */
2873 static void ice_ena_misc_vector(struct ice_pf *pf)
2874 {
2875         struct ice_hw *hw = &pf->hw;
2876         u32 val;
2877
2878         /* Disable anti-spoof detection interrupt to prevent spurious event
2879          * interrupts during a function reset. Anti-spoof functionally is
2880          * still supported.
2881          */
2882         val = rd32(hw, GL_MDCK_TX_TDPU);
2883         val |= GL_MDCK_TX_TDPU_RCU_ANTISPOOF_ITR_DIS_M;
2884         wr32(hw, GL_MDCK_TX_TDPU, val);
2885
2886         /* clear things first */
2887         wr32(hw, PFINT_OICR_ENA, 0);    /* disable all */
2888         rd32(hw, PFINT_OICR);           /* read to clear */
2889
2890         val = (PFINT_OICR_ECC_ERR_M |
2891                PFINT_OICR_MAL_DETECT_M |
2892                PFINT_OICR_GRST_M |
2893                PFINT_OICR_PCI_EXCEPTION_M |
2894                PFINT_OICR_VFLR_M |
2895                PFINT_OICR_HMC_ERR_M |
2896                PFINT_OICR_PE_PUSH_M |
2897                PFINT_OICR_PE_CRITERR_M);
2898
2899         wr32(hw, PFINT_OICR_ENA, val);
2900
2901         /* SW_ITR_IDX = 0, but don't change INTENA */
2902         wr32(hw, GLINT_DYN_CTL(pf->oicr_idx),
2903              GLINT_DYN_CTL_SW_ITR_INDX_M | GLINT_DYN_CTL_INTENA_MSK_M);
2904 }
2905
2906 /**
2907  * ice_misc_intr - misc interrupt handler
2908  * @irq: interrupt number
2909  * @data: pointer to a q_vector
2910  */
2911 static irqreturn_t ice_misc_intr(int __always_unused irq, void *data)
2912 {
2913         struct ice_pf *pf = (struct ice_pf *)data;
2914         struct ice_hw *hw = &pf->hw;
2915         irqreturn_t ret = IRQ_NONE;
2916         struct device *dev;
2917         u32 oicr, ena_mask;
2918
2919         dev = ice_pf_to_dev(pf);
2920         set_bit(ICE_ADMINQ_EVENT_PENDING, pf->state);
2921         set_bit(ICE_MAILBOXQ_EVENT_PENDING, pf->state);
2922         set_bit(ICE_SIDEBANDQ_EVENT_PENDING, pf->state);
2923
2924         oicr = rd32(hw, PFINT_OICR);
2925         ena_mask = rd32(hw, PFINT_OICR_ENA);
2926
2927         if (oicr & PFINT_OICR_SWINT_M) {
2928                 ena_mask &= ~PFINT_OICR_SWINT_M;
2929                 pf->sw_int_count++;
2930         }
2931
2932         if (oicr & PFINT_OICR_MAL_DETECT_M) {
2933                 ena_mask &= ~PFINT_OICR_MAL_DETECT_M;
2934                 set_bit(ICE_MDD_EVENT_PENDING, pf->state);
2935         }
2936         if (oicr & PFINT_OICR_VFLR_M) {
2937                 /* disable any further VFLR event notifications */
2938                 if (test_bit(ICE_VF_RESETS_DISABLED, pf->state)) {
2939                         u32 reg = rd32(hw, PFINT_OICR_ENA);
2940
2941                         reg &= ~PFINT_OICR_VFLR_M;
2942                         wr32(hw, PFINT_OICR_ENA, reg);
2943                 } else {
2944                         ena_mask &= ~PFINT_OICR_VFLR_M;
2945                         set_bit(ICE_VFLR_EVENT_PENDING, pf->state);
2946                 }
2947         }
2948
2949         if (oicr & PFINT_OICR_GRST_M) {
2950                 u32 reset;
2951
2952                 /* we have a reset warning */
2953                 ena_mask &= ~PFINT_OICR_GRST_M;
2954                 reset = (rd32(hw, GLGEN_RSTAT) & GLGEN_RSTAT_RESET_TYPE_M) >>
2955                         GLGEN_RSTAT_RESET_TYPE_S;
2956
2957                 if (reset == ICE_RESET_CORER)
2958                         pf->corer_count++;
2959                 else if (reset == ICE_RESET_GLOBR)
2960                         pf->globr_count++;
2961                 else if (reset == ICE_RESET_EMPR)
2962                         pf->empr_count++;
2963                 else
2964                         dev_dbg(dev, "Invalid reset type %d\n", reset);
2965
2966                 /* If a reset cycle isn't already in progress, we set a bit in
2967                  * pf->state so that the service task can start a reset/rebuild.
2968                  */
2969                 if (!test_and_set_bit(ICE_RESET_OICR_RECV, pf->state)) {
2970                         if (reset == ICE_RESET_CORER)
2971                                 set_bit(ICE_CORER_RECV, pf->state);
2972                         else if (reset == ICE_RESET_GLOBR)
2973                                 set_bit(ICE_GLOBR_RECV, pf->state);
2974                         else
2975                                 set_bit(ICE_EMPR_RECV, pf->state);
2976
2977                         /* There are couple of different bits at play here.
2978                          * hw->reset_ongoing indicates whether the hardware is
2979                          * in reset. This is set to true when a reset interrupt
2980                          * is received and set back to false after the driver
2981                          * has determined that the hardware is out of reset.
2982                          *
2983                          * ICE_RESET_OICR_RECV in pf->state indicates
2984                          * that a post reset rebuild is required before the
2985                          * driver is operational again. This is set above.
2986                          *
2987                          * As this is the start of the reset/rebuild cycle, set
2988                          * both to indicate that.
2989                          */
2990                         hw->reset_ongoing = true;
2991                 }
2992         }
2993
2994         if (oicr & PFINT_OICR_TSYN_TX_M) {
2995                 ena_mask &= ~PFINT_OICR_TSYN_TX_M;
2996                 ice_ptp_process_ts(pf);
2997         }
2998
2999         if (oicr & PFINT_OICR_TSYN_EVNT_M) {
3000                 u8 tmr_idx = hw->func_caps.ts_func_info.tmr_index_owned;
3001                 u32 gltsyn_stat = rd32(hw, GLTSYN_STAT(tmr_idx));
3002
3003                 /* Save EVENTs from GTSYN register */
3004                 pf->ptp.ext_ts_irq |= gltsyn_stat & (GLTSYN_STAT_EVENT0_M |
3005                                                      GLTSYN_STAT_EVENT1_M |
3006                                                      GLTSYN_STAT_EVENT2_M);
3007                 ena_mask &= ~PFINT_OICR_TSYN_EVNT_M;
3008                 kthread_queue_work(pf->ptp.kworker, &pf->ptp.extts_work);
3009         }
3010
3011 #define ICE_AUX_CRIT_ERR (PFINT_OICR_PE_CRITERR_M | PFINT_OICR_HMC_ERR_M | PFINT_OICR_PE_PUSH_M)
3012         if (oicr & ICE_AUX_CRIT_ERR) {
3013                 struct iidc_event *event;
3014
3015                 ena_mask &= ~ICE_AUX_CRIT_ERR;
3016                 event = kzalloc(sizeof(*event), GFP_KERNEL);
3017                 if (event) {
3018                         set_bit(IIDC_EVENT_CRIT_ERR, event->type);
3019                         /* report the entire OICR value to AUX driver */
3020                         event->reg = oicr;
3021                         ice_send_event_to_aux(pf, event);
3022                         kfree(event);
3023                 }
3024         }
3025
3026         /* Report any remaining unexpected interrupts */
3027         oicr &= ena_mask;
3028         if (oicr) {
3029                 dev_dbg(dev, "unhandled interrupt oicr=0x%08x\n", oicr);
3030                 /* If a critical error is pending there is no choice but to
3031                  * reset the device.
3032                  */
3033                 if (oicr & (PFINT_OICR_PCI_EXCEPTION_M |
3034                             PFINT_OICR_ECC_ERR_M)) {
3035                         set_bit(ICE_PFR_REQ, pf->state);
3036                         ice_service_task_schedule(pf);
3037                 }
3038         }
3039         ret = IRQ_HANDLED;
3040
3041         ice_service_task_schedule(pf);
3042         ice_irq_dynamic_ena(hw, NULL, NULL);
3043
3044         return ret;
3045 }
3046
3047 /**
3048  * ice_dis_ctrlq_interrupts - disable control queue interrupts
3049  * @hw: pointer to HW structure
3050  */
3051 static void ice_dis_ctrlq_interrupts(struct ice_hw *hw)
3052 {
3053         /* disable Admin queue Interrupt causes */
3054         wr32(hw, PFINT_FW_CTL,
3055              rd32(hw, PFINT_FW_CTL) & ~PFINT_FW_CTL_CAUSE_ENA_M);
3056
3057         /* disable Mailbox queue Interrupt causes */
3058         wr32(hw, PFINT_MBX_CTL,
3059              rd32(hw, PFINT_MBX_CTL) & ~PFINT_MBX_CTL_CAUSE_ENA_M);
3060
3061         wr32(hw, PFINT_SB_CTL,
3062              rd32(hw, PFINT_SB_CTL) & ~PFINT_SB_CTL_CAUSE_ENA_M);
3063
3064         /* disable Control queue Interrupt causes */
3065         wr32(hw, PFINT_OICR_CTL,
3066              rd32(hw, PFINT_OICR_CTL) & ~PFINT_OICR_CTL_CAUSE_ENA_M);
3067
3068         ice_flush(hw);
3069 }
3070
3071 /**
3072  * ice_free_irq_msix_misc - Unroll misc vector setup
3073  * @pf: board private structure
3074  */
3075 static void ice_free_irq_msix_misc(struct ice_pf *pf)
3076 {
3077         struct ice_hw *hw = &pf->hw;
3078
3079         ice_dis_ctrlq_interrupts(hw);
3080
3081         /* disable OICR interrupt */
3082         wr32(hw, PFINT_OICR_ENA, 0);
3083         ice_flush(hw);
3084
3085         if (pf->msix_entries) {
3086                 synchronize_irq(pf->msix_entries[pf->oicr_idx].vector);
3087                 devm_free_irq(ice_pf_to_dev(pf),
3088                               pf->msix_entries[pf->oicr_idx].vector, pf);
3089         }
3090
3091         pf->num_avail_sw_msix += 1;
3092         ice_free_res(pf->irq_tracker, pf->oicr_idx, ICE_RES_MISC_VEC_ID);
3093 }
3094
3095 /**
3096  * ice_ena_ctrlq_interrupts - enable control queue interrupts
3097  * @hw: pointer to HW structure
3098  * @reg_idx: HW vector index to associate the control queue interrupts with
3099  */
3100 static void ice_ena_ctrlq_interrupts(struct ice_hw *hw, u16 reg_idx)
3101 {
3102         u32 val;
3103
3104         val = ((reg_idx & PFINT_OICR_CTL_MSIX_INDX_M) |
3105                PFINT_OICR_CTL_CAUSE_ENA_M);
3106         wr32(hw, PFINT_OICR_CTL, val);
3107
3108         /* enable Admin queue Interrupt causes */
3109         val = ((reg_idx & PFINT_FW_CTL_MSIX_INDX_M) |
3110                PFINT_FW_CTL_CAUSE_ENA_M);
3111         wr32(hw, PFINT_FW_CTL, val);
3112
3113         /* enable Mailbox queue Interrupt causes */
3114         val = ((reg_idx & PFINT_MBX_CTL_MSIX_INDX_M) |
3115                PFINT_MBX_CTL_CAUSE_ENA_M);
3116         wr32(hw, PFINT_MBX_CTL, val);
3117
3118         /* This enables Sideband queue Interrupt causes */
3119         val = ((reg_idx & PFINT_SB_CTL_MSIX_INDX_M) |
3120                PFINT_SB_CTL_CAUSE_ENA_M);
3121         wr32(hw, PFINT_SB_CTL, val);
3122
3123         ice_flush(hw);
3124 }
3125
3126 /**
3127  * ice_req_irq_msix_misc - Setup the misc vector to handle non queue events
3128  * @pf: board private structure
3129  *
3130  * This sets up the handler for MSIX 0, which is used to manage the
3131  * non-queue interrupts, e.g. AdminQ and errors. This is not used
3132  * when in MSI or Legacy interrupt mode.
3133  */
3134 static int ice_req_irq_msix_misc(struct ice_pf *pf)
3135 {
3136         struct device *dev = ice_pf_to_dev(pf);
3137         struct ice_hw *hw = &pf->hw;
3138         int oicr_idx, err = 0;
3139
3140         if (!pf->int_name[0])
3141                 snprintf(pf->int_name, sizeof(pf->int_name) - 1, "%s-%s:misc",
3142                          dev_driver_string(dev), dev_name(dev));
3143
3144         /* Do not request IRQ but do enable OICR interrupt since settings are
3145          * lost during reset. Note that this function is called only during
3146          * rebuild path and not while reset is in progress.
3147          */
3148         if (ice_is_reset_in_progress(pf->state))
3149                 goto skip_req_irq;
3150
3151         /* reserve one vector in irq_tracker for misc interrupts */
3152         oicr_idx = ice_get_res(pf, pf->irq_tracker, 1, ICE_RES_MISC_VEC_ID);
3153         if (oicr_idx < 0)
3154                 return oicr_idx;
3155
3156         pf->num_avail_sw_msix -= 1;
3157         pf->oicr_idx = (u16)oicr_idx;
3158
3159         err = devm_request_irq(dev, pf->msix_entries[pf->oicr_idx].vector,
3160                                ice_misc_intr, 0, pf->int_name, pf);
3161         if (err) {
3162                 dev_err(dev, "devm_request_irq for %s failed: %d\n",
3163                         pf->int_name, err);
3164                 ice_free_res(pf->irq_tracker, 1, ICE_RES_MISC_VEC_ID);
3165                 pf->num_avail_sw_msix += 1;
3166                 return err;
3167         }
3168
3169 skip_req_irq:
3170         ice_ena_misc_vector(pf);
3171
3172         ice_ena_ctrlq_interrupts(hw, pf->oicr_idx);
3173         wr32(hw, GLINT_ITR(ICE_RX_ITR, pf->oicr_idx),
3174              ITR_REG_ALIGN(ICE_ITR_8K) >> ICE_ITR_GRAN_S);
3175
3176         ice_flush(hw);
3177         ice_irq_dynamic_ena(hw, NULL, NULL);
3178
3179         return 0;
3180 }
3181
3182 /**
3183  * ice_napi_add - register NAPI handler for the VSI
3184  * @vsi: VSI for which NAPI handler is to be registered
3185  *
3186  * This function is only called in the driver's load path. Registering the NAPI
3187  * handler is done in ice_vsi_alloc_q_vector() for all other cases (i.e. resume,
3188  * reset/rebuild, etc.)
3189  */
3190 static void ice_napi_add(struct ice_vsi *vsi)
3191 {
3192         int v_idx;
3193
3194         if (!vsi->netdev)
3195                 return;
3196
3197         ice_for_each_q_vector(vsi, v_idx)
3198                 netif_napi_add(vsi->netdev, &vsi->q_vectors[v_idx]->napi,
3199                                ice_napi_poll, NAPI_POLL_WEIGHT);
3200 }
3201
3202 /**
3203  * ice_set_ops - set netdev and ethtools ops for the given netdev
3204  * @netdev: netdev instance
3205  */
3206 static void ice_set_ops(struct net_device *netdev)
3207 {
3208         struct ice_pf *pf = ice_netdev_to_pf(netdev);
3209
3210         if (ice_is_safe_mode(pf)) {
3211                 netdev->netdev_ops = &ice_netdev_safe_mode_ops;
3212                 ice_set_ethtool_safe_mode_ops(netdev);
3213                 return;
3214         }
3215
3216         netdev->netdev_ops = &ice_netdev_ops;
3217         netdev->udp_tunnel_nic_info = &pf->hw.udp_tunnel_nic;
3218         ice_set_ethtool_ops(netdev);
3219 }
3220
3221 /**
3222  * ice_set_netdev_features - set features for the given netdev
3223  * @netdev: netdev instance
3224  */
3225 static void ice_set_netdev_features(struct net_device *netdev)
3226 {
3227         struct ice_pf *pf = ice_netdev_to_pf(netdev);
3228         netdev_features_t csumo_features;
3229         netdev_features_t vlano_features;
3230         netdev_features_t dflt_features;
3231         netdev_features_t tso_features;
3232
3233         if (ice_is_safe_mode(pf)) {
3234                 /* safe mode */
3235                 netdev->features = NETIF_F_SG | NETIF_F_HIGHDMA;
3236                 netdev->hw_features = netdev->features;
3237                 return;
3238         }
3239
3240         dflt_features = NETIF_F_SG      |
3241                         NETIF_F_HIGHDMA |
3242                         NETIF_F_NTUPLE  |
3243                         NETIF_F_RXHASH;
3244
3245         csumo_features = NETIF_F_RXCSUM   |
3246                          NETIF_F_IP_CSUM  |
3247                          NETIF_F_SCTP_CRC |
3248                          NETIF_F_IPV6_CSUM;
3249
3250         vlano_features = NETIF_F_HW_VLAN_CTAG_FILTER |
3251                          NETIF_F_HW_VLAN_CTAG_TX     |
3252                          NETIF_F_HW_VLAN_CTAG_RX;
3253
3254         tso_features = NETIF_F_TSO                      |
3255                        NETIF_F_TSO_ECN                  |
3256                        NETIF_F_TSO6                     |
3257                        NETIF_F_GSO_GRE                  |
3258                        NETIF_F_GSO_UDP_TUNNEL           |
3259                        NETIF_F_GSO_GRE_CSUM             |
3260                        NETIF_F_GSO_UDP_TUNNEL_CSUM      |
3261                        NETIF_F_GSO_PARTIAL              |
3262                        NETIF_F_GSO_IPXIP4               |
3263                        NETIF_F_GSO_IPXIP6               |
3264                        NETIF_F_GSO_UDP_L4;
3265
3266         netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM |
3267                                         NETIF_F_GSO_GRE_CSUM;
3268         /* set features that user can change */
3269         netdev->hw_features = dflt_features | csumo_features |
3270                               vlano_features | tso_features;
3271
3272         /* add support for HW_CSUM on packets with MPLS header */
3273         netdev->mpls_features =  NETIF_F_HW_CSUM;
3274
3275         /* enable features */
3276         netdev->features |= netdev->hw_features;
3277
3278         netdev->hw_features |= NETIF_F_HW_TC;
3279
3280         /* encap and VLAN devices inherit default, csumo and tso features */
3281         netdev->hw_enc_features |= dflt_features | csumo_features |
3282                                    tso_features;
3283         netdev->vlan_features |= dflt_features | csumo_features |
3284                                  tso_features;
3285 }
3286
3287 /**
3288  * ice_cfg_netdev - Allocate, configure and register a netdev
3289  * @vsi: the VSI associated with the new netdev
3290  *
3291  * Returns 0 on success, negative value on failure
3292  */
3293 static int ice_cfg_netdev(struct ice_vsi *vsi)
3294 {
3295         struct ice_netdev_priv *np;
3296         struct net_device *netdev;
3297         u8 mac_addr[ETH_ALEN];
3298
3299         netdev = alloc_etherdev_mqs(sizeof(*np), vsi->alloc_txq,
3300                                     vsi->alloc_rxq);
3301         if (!netdev)
3302                 return -ENOMEM;
3303
3304         set_bit(ICE_VSI_NETDEV_ALLOCD, vsi->state);
3305         vsi->netdev = netdev;
3306         np = netdev_priv(netdev);
3307         np->vsi = vsi;
3308
3309         ice_set_netdev_features(netdev);
3310
3311         ice_set_ops(netdev);
3312
3313         if (vsi->type == ICE_VSI_PF) {
3314                 SET_NETDEV_DEV(netdev, ice_pf_to_dev(vsi->back));
3315                 ether_addr_copy(mac_addr, vsi->port_info->mac.perm_addr);
3316                 eth_hw_addr_set(netdev, mac_addr);
3317                 ether_addr_copy(netdev->perm_addr, mac_addr);
3318         }
3319
3320         netdev->priv_flags |= IFF_UNICAST_FLT;
3321
3322         /* Setup netdev TC information */
3323         ice_vsi_cfg_netdev_tc(vsi, vsi->tc_cfg.ena_tc);
3324
3325         /* setup watchdog timeout value to be 5 second */
3326         netdev->watchdog_timeo = 5 * HZ;
3327
3328         netdev->min_mtu = ETH_MIN_MTU;
3329         netdev->max_mtu = ICE_MAX_MTU;
3330
3331         return 0;
3332 }
3333
3334 /**
3335  * ice_fill_rss_lut - Fill the RSS lookup table with default values
3336  * @lut: Lookup table
3337  * @rss_table_size: Lookup table size
3338  * @rss_size: Range of queue number for hashing
3339  */
3340 void ice_fill_rss_lut(u8 *lut, u16 rss_table_size, u16 rss_size)
3341 {
3342         u16 i;
3343
3344         for (i = 0; i < rss_table_size; i++)
3345                 lut[i] = i % rss_size;
3346 }
3347
3348 /**
3349  * ice_pf_vsi_setup - Set up a PF VSI
3350  * @pf: board private structure
3351  * @pi: pointer to the port_info instance
3352  *
3353  * Returns pointer to the successfully allocated VSI software struct
3354  * on success, otherwise returns NULL on failure.
3355  */
3356 static struct ice_vsi *
3357 ice_pf_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi)
3358 {
3359         return ice_vsi_setup(pf, pi, ICE_VSI_PF, ICE_INVAL_VFID, NULL);
3360 }
3361
3362 static struct ice_vsi *
3363 ice_chnl_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi,
3364                    struct ice_channel *ch)
3365 {
3366         return ice_vsi_setup(pf, pi, ICE_VSI_CHNL, ICE_INVAL_VFID, ch);
3367 }
3368
3369 /**
3370  * ice_ctrl_vsi_setup - Set up a control VSI
3371  * @pf: board private structure
3372  * @pi: pointer to the port_info instance
3373  *
3374  * Returns pointer to the successfully allocated VSI software struct
3375  * on success, otherwise returns NULL on failure.
3376  */
3377 static struct ice_vsi *
3378 ice_ctrl_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi)
3379 {
3380         return ice_vsi_setup(pf, pi, ICE_VSI_CTRL, ICE_INVAL_VFID, NULL);
3381 }
3382
3383 /**
3384  * ice_lb_vsi_setup - Set up a loopback VSI
3385  * @pf: board private structure
3386  * @pi: pointer to the port_info instance
3387  *
3388  * Returns pointer to the successfully allocated VSI software struct
3389  * on success, otherwise returns NULL on failure.
3390  */
3391 struct ice_vsi *
3392 ice_lb_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi)
3393 {
3394         return ice_vsi_setup(pf, pi, ICE_VSI_LB, ICE_INVAL_VFID, NULL);
3395 }
3396
3397 /**
3398  * ice_vlan_rx_add_vid - Add a VLAN ID filter to HW offload
3399  * @netdev: network interface to be adjusted
3400  * @proto: unused protocol
3401  * @vid: VLAN ID to be added
3402  *
3403  * net_device_ops implementation for adding VLAN IDs
3404  */
3405 static int
3406 ice_vlan_rx_add_vid(struct net_device *netdev, __always_unused __be16 proto,
3407                     u16 vid)
3408 {
3409         struct ice_netdev_priv *np = netdev_priv(netdev);
3410         struct ice_vsi *vsi = np->vsi;
3411         int ret;
3412
3413         /* VLAN 0 is added by default during load/reset */
3414         if (!vid)
3415                 return 0;
3416
3417         /* Enable VLAN pruning when a VLAN other than 0 is added */
3418         if (!ice_vsi_is_vlan_pruning_ena(vsi)) {
3419                 ret = ice_cfg_vlan_pruning(vsi, true);
3420                 if (ret)
3421                         return ret;
3422         }
3423
3424         /* Add a switch rule for this VLAN ID so its corresponding VLAN tagged
3425          * packets aren't pruned by the device's internal switch on Rx
3426          */
3427         ret = ice_vsi_add_vlan(vsi, vid, ICE_FWD_TO_VSI);
3428         if (!ret)
3429                 set_bit(ICE_VSI_VLAN_FLTR_CHANGED, vsi->state);
3430
3431         return ret;
3432 }
3433
3434 /**
3435  * ice_vlan_rx_kill_vid - Remove a VLAN ID filter from HW offload
3436  * @netdev: network interface to be adjusted
3437  * @proto: unused protocol
3438  * @vid: VLAN ID to be removed
3439  *
3440  * net_device_ops implementation for removing VLAN IDs
3441  */
3442 static int
3443 ice_vlan_rx_kill_vid(struct net_device *netdev, __always_unused __be16 proto,
3444                      u16 vid)
3445 {
3446         struct ice_netdev_priv *np = netdev_priv(netdev);
3447         struct ice_vsi *vsi = np->vsi;
3448         int ret;
3449
3450         /* don't allow removal of VLAN 0 */
3451         if (!vid)
3452                 return 0;
3453
3454         /* Make sure ice_vsi_kill_vlan is successful before updating VLAN
3455          * information
3456          */
3457         ret = ice_vsi_kill_vlan(vsi, vid);
3458         if (ret)
3459                 return ret;
3460
3461         /* Disable pruning when VLAN 0 is the only VLAN rule */
3462         if (vsi->num_vlan == 1 && ice_vsi_is_vlan_pruning_ena(vsi))
3463                 ret = ice_cfg_vlan_pruning(vsi, false);
3464
3465         set_bit(ICE_VSI_VLAN_FLTR_CHANGED, vsi->state);
3466         return ret;
3467 }
3468
3469 /**
3470  * ice_rep_indr_tc_block_unbind
3471  * @cb_priv: indirection block private data
3472  */
3473 static void ice_rep_indr_tc_block_unbind(void *cb_priv)
3474 {
3475         struct ice_indr_block_priv *indr_priv = cb_priv;
3476
3477         list_del(&indr_priv->list);
3478         kfree(indr_priv);
3479 }
3480
3481 /**
3482  * ice_tc_indir_block_unregister - Unregister TC indirect block notifications
3483  * @vsi: VSI struct which has the netdev
3484  */
3485 static void ice_tc_indir_block_unregister(struct ice_vsi *vsi)
3486 {
3487         struct ice_netdev_priv *np = netdev_priv(vsi->netdev);
3488
3489         flow_indr_dev_unregister(ice_indr_setup_tc_cb, np,
3490                                  ice_rep_indr_tc_block_unbind);
3491 }
3492
3493 /**
3494  * ice_tc_indir_block_remove - clean indirect TC block notifications
3495  * @pf: PF structure
3496  */
3497 static void ice_tc_indir_block_remove(struct ice_pf *pf)
3498 {
3499         struct ice_vsi *pf_vsi = ice_get_main_vsi(pf);
3500
3501         if (!pf_vsi)
3502                 return;
3503
3504         ice_tc_indir_block_unregister(pf_vsi);
3505 }
3506
3507 /**
3508  * ice_tc_indir_block_register - Register TC indirect block notifications
3509  * @vsi: VSI struct which has the netdev
3510  *
3511  * Returns 0 on success, negative value on failure
3512  */
3513 static int ice_tc_indir_block_register(struct ice_vsi *vsi)
3514 {
3515         struct ice_netdev_priv *np;
3516
3517         if (!vsi || !vsi->netdev)
3518                 return -EINVAL;
3519
3520         np = netdev_priv(vsi->netdev);
3521
3522         INIT_LIST_HEAD(&np->tc_indr_block_priv_list);
3523         return flow_indr_dev_register(ice_indr_setup_tc_cb, np);
3524 }
3525
3526 /**
3527  * ice_setup_pf_sw - Setup the HW switch on startup or after reset
3528  * @pf: board private structure
3529  *
3530  * Returns 0 on success, negative value on failure
3531  */
3532 static int ice_setup_pf_sw(struct ice_pf *pf)
3533 {
3534         struct device *dev = ice_pf_to_dev(pf);
3535         struct ice_vsi *vsi;
3536         int status = 0;
3537
3538         if (ice_is_reset_in_progress(pf->state))
3539                 return -EBUSY;
3540
3541         vsi = ice_pf_vsi_setup(pf, pf->hw.port_info);
3542         if (!vsi)
3543                 return -ENOMEM;
3544
3545         /* init channel list */
3546         INIT_LIST_HEAD(&vsi->ch_list);
3547
3548         status = ice_cfg_netdev(vsi);
3549         if (status) {
3550                 status = -ENODEV;
3551                 goto unroll_vsi_setup;
3552         }
3553         /* netdev has to be configured before setting frame size */
3554         ice_vsi_cfg_frame_size(vsi);
3555
3556         /* init indirect block notifications */
3557         status = ice_tc_indir_block_register(vsi);
3558         if (status) {
3559                 dev_err(dev, "Failed to register netdev notifier\n");
3560                 goto unroll_cfg_netdev;
3561         }
3562
3563         /* Setup DCB netlink interface */
3564         ice_dcbnl_setup(vsi);
3565
3566         /* registering the NAPI handler requires both the queues and
3567          * netdev to be created, which are done in ice_pf_vsi_setup()
3568          * and ice_cfg_netdev() respectively
3569          */
3570         ice_napi_add(vsi);
3571
3572         status = ice_set_cpu_rx_rmap(vsi);
3573         if (status) {
3574                 dev_err(dev, "Failed to set CPU Rx map VSI %d error %d\n",
3575                         vsi->vsi_num, status);
3576                 status = -EINVAL;
3577                 goto unroll_napi_add;
3578         }
3579         status = ice_init_mac_fltr(pf);
3580         if (status)
3581                 goto free_cpu_rx_map;
3582
3583         return status;
3584
3585 free_cpu_rx_map:
3586         ice_free_cpu_rx_rmap(vsi);
3587 unroll_napi_add:
3588         ice_tc_indir_block_unregister(vsi);
3589 unroll_cfg_netdev:
3590         if (vsi) {
3591                 ice_napi_del(vsi);
3592                 if (vsi->netdev) {
3593                         clear_bit(ICE_VSI_NETDEV_ALLOCD, vsi->state);
3594                         free_netdev(vsi->netdev);
3595                         vsi->netdev = NULL;
3596                 }
3597         }
3598
3599 unroll_vsi_setup:
3600         ice_vsi_release(vsi);
3601         return status;
3602 }
3603
3604 /**
3605  * ice_get_avail_q_count - Get count of queues in use
3606  * @pf_qmap: bitmap to get queue use count from
3607  * @lock: pointer to a mutex that protects access to pf_qmap
3608  * @size: size of the bitmap
3609  */
3610 static u16
3611 ice_get_avail_q_count(unsigned long *pf_qmap, struct mutex *lock, u16 size)
3612 {
3613         unsigned long bit;
3614         u16 count = 0;
3615
3616         mutex_lock(lock);
3617         for_each_clear_bit(bit, pf_qmap, size)
3618                 count++;
3619         mutex_unlock(lock);
3620
3621         return count;
3622 }
3623
3624 /**
3625  * ice_get_avail_txq_count - Get count of Tx queues in use
3626  * @pf: pointer to an ice_pf instance
3627  */
3628 u16 ice_get_avail_txq_count(struct ice_pf *pf)
3629 {
3630         return ice_get_avail_q_count(pf->avail_txqs, &pf->avail_q_mutex,
3631                                      pf->max_pf_txqs);
3632 }
3633
3634 /**
3635  * ice_get_avail_rxq_count - Get count of Rx queues in use
3636  * @pf: pointer to an ice_pf instance
3637  */
3638 u16 ice_get_avail_rxq_count(struct ice_pf *pf)
3639 {
3640         return ice_get_avail_q_count(pf->avail_rxqs, &pf->avail_q_mutex,
3641                                      pf->max_pf_rxqs);
3642 }
3643
3644 /**
3645  * ice_deinit_pf - Unrolls initialziations done by ice_init_pf
3646  * @pf: board private structure to initialize
3647  */
3648 static void ice_deinit_pf(struct ice_pf *pf)
3649 {
3650         ice_service_task_stop(pf);
3651         mutex_destroy(&pf->sw_mutex);
3652         mutex_destroy(&pf->tc_mutex);
3653         mutex_destroy(&pf->avail_q_mutex);
3654
3655         if (pf->avail_txqs) {
3656                 bitmap_free(pf->avail_txqs);
3657                 pf->avail_txqs = NULL;
3658         }
3659
3660         if (pf->avail_rxqs) {
3661                 bitmap_free(pf->avail_rxqs);
3662                 pf->avail_rxqs = NULL;
3663         }
3664
3665         if (pf->ptp.clock)
3666                 ptp_clock_unregister(pf->ptp.clock);
3667 }
3668
3669 /**
3670  * ice_set_pf_caps - set PFs capability flags
3671  * @pf: pointer to the PF instance
3672  */
3673 static void ice_set_pf_caps(struct ice_pf *pf)
3674 {
3675         struct ice_hw_func_caps *func_caps = &pf->hw.func_caps;
3676
3677         clear_bit(ICE_FLAG_RDMA_ENA, pf->flags);
3678         clear_bit(ICE_FLAG_AUX_ENA, pf->flags);
3679         if (func_caps->common_cap.rdma) {
3680                 set_bit(ICE_FLAG_RDMA_ENA, pf->flags);
3681                 set_bit(ICE_FLAG_AUX_ENA, pf->flags);
3682         }
3683         clear_bit(ICE_FLAG_DCB_CAPABLE, pf->flags);
3684         if (func_caps->common_cap.dcb)
3685                 set_bit(ICE_FLAG_DCB_CAPABLE, pf->flags);
3686         clear_bit(ICE_FLAG_SRIOV_CAPABLE, pf->flags);
3687         if (func_caps->common_cap.sr_iov_1_1) {
3688                 set_bit(ICE_FLAG_SRIOV_CAPABLE, pf->flags);
3689                 pf->num_vfs_supported = min_t(int, func_caps->num_allocd_vfs,
3690                                               ICE_MAX_VF_COUNT);
3691         }
3692         clear_bit(ICE_FLAG_RSS_ENA, pf->flags);
3693         if (func_caps->common_cap.rss_table_size)
3694                 set_bit(ICE_FLAG_RSS_ENA, pf->flags);
3695
3696         clear_bit(ICE_FLAG_FD_ENA, pf->flags);
3697         if (func_caps->fd_fltr_guar > 0 || func_caps->fd_fltr_best_effort > 0) {
3698                 u16 unused;
3699
3700                 /* ctrl_vsi_idx will be set to a valid value when flow director
3701                  * is setup by ice_init_fdir
3702                  */
3703                 pf->ctrl_vsi_idx = ICE_NO_VSI;
3704                 set_bit(ICE_FLAG_FD_ENA, pf->flags);
3705                 /* force guaranteed filter pool for PF */
3706                 ice_alloc_fd_guar_item(&pf->hw, &unused,
3707                                        func_caps->fd_fltr_guar);
3708                 /* force shared filter pool for PF */
3709                 ice_alloc_fd_shrd_item(&pf->hw, &unused,
3710                                        func_caps->fd_fltr_best_effort);
3711         }
3712
3713         clear_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags);
3714         if (func_caps->common_cap.ieee_1588)
3715                 set_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags);
3716
3717         pf->max_pf_txqs = func_caps->common_cap.num_txq;
3718         pf->max_pf_rxqs = func_caps->common_cap.num_rxq;
3719 }
3720
3721 /**
3722  * ice_init_pf - Initialize general software structures (struct ice_pf)
3723  * @pf: board private structure to initialize
3724  */
3725 static int ice_init_pf(struct ice_pf *pf)
3726 {
3727         ice_set_pf_caps(pf);
3728
3729         mutex_init(&pf->sw_mutex);
3730         mutex_init(&pf->tc_mutex);
3731
3732         INIT_HLIST_HEAD(&pf->aq_wait_list);
3733         spin_lock_init(&pf->aq_wait_lock);
3734         init_waitqueue_head(&pf->aq_wait_queue);
3735
3736         init_waitqueue_head(&pf->reset_wait_queue);
3737
3738         /* setup service timer and periodic service task */
3739         timer_setup(&pf->serv_tmr, ice_service_timer, 0);
3740         pf->serv_tmr_period = HZ;
3741         INIT_WORK(&pf->serv_task, ice_service_task);
3742         clear_bit(ICE_SERVICE_SCHED, pf->state);
3743
3744         mutex_init(&pf->avail_q_mutex);
3745         pf->avail_txqs = bitmap_zalloc(pf->max_pf_txqs, GFP_KERNEL);
3746         if (!pf->avail_txqs)
3747                 return -ENOMEM;
3748
3749         pf->avail_rxqs = bitmap_zalloc(pf->max_pf_rxqs, GFP_KERNEL);
3750         if (!pf->avail_rxqs) {
3751                 devm_kfree(ice_pf_to_dev(pf), pf->avail_txqs);
3752                 pf->avail_txqs = NULL;
3753                 return -ENOMEM;
3754         }
3755
3756         return 0;
3757 }
3758
3759 /**
3760  * ice_ena_msix_range - Request a range of MSIX vectors from the OS
3761  * @pf: board private structure
3762  *
3763  * compute the number of MSIX vectors required (v_budget) and request from
3764  * the OS. Return the number of vectors reserved or negative on failure
3765  */
3766 static int ice_ena_msix_range(struct ice_pf *pf)
3767 {
3768         int num_cpus, v_left, v_actual, v_other, v_budget = 0;
3769         struct device *dev = ice_pf_to_dev(pf);
3770         int needed, err, i;
3771
3772         v_left = pf->hw.func_caps.common_cap.num_msix_vectors;
3773         num_cpus = num_online_cpus();
3774
3775         /* reserve for LAN miscellaneous handler */
3776         needed = ICE_MIN_LAN_OICR_MSIX;
3777         if (v_left < needed)
3778                 goto no_hw_vecs_left_err;
3779         v_budget += needed;
3780         v_left -= needed;
3781
3782         /* reserve for flow director */
3783         if (test_bit(ICE_FLAG_FD_ENA, pf->flags)) {
3784                 needed = ICE_FDIR_MSIX;
3785                 if (v_left < needed)
3786                         goto no_hw_vecs_left_err;
3787                 v_budget += needed;
3788                 v_left -= needed;
3789         }
3790
3791         /* reserve for switchdev */
3792         needed = ICE_ESWITCH_MSIX;
3793         if (v_left < needed)
3794                 goto no_hw_vecs_left_err;
3795         v_budget += needed;
3796         v_left -= needed;
3797
3798         /* total used for non-traffic vectors */
3799         v_other = v_budget;
3800
3801         /* reserve vectors for LAN traffic */
3802         needed = num_cpus;
3803         if (v_left < needed)
3804                 goto no_hw_vecs_left_err;
3805         pf->num_lan_msix = needed;
3806         v_budget += needed;
3807         v_left -= needed;
3808
3809         /* reserve vectors for RDMA auxiliary driver */
3810         if (test_bit(ICE_FLAG_RDMA_ENA, pf->flags)) {
3811                 needed = num_cpus + ICE_RDMA_NUM_AEQ_MSIX;
3812                 if (v_left < needed)
3813                         goto no_hw_vecs_left_err;
3814                 pf->num_rdma_msix = needed;
3815                 v_budget += needed;
3816                 v_left -= needed;
3817         }
3818
3819         pf->msix_entries = devm_kcalloc(dev, v_budget,
3820                                         sizeof(*pf->msix_entries), GFP_KERNEL);
3821         if (!pf->msix_entries) {
3822                 err = -ENOMEM;
3823                 goto exit_err;
3824         }
3825
3826         for (i = 0; i < v_budget; i++)
3827                 pf->msix_entries[i].entry = i;
3828
3829         /* actually reserve the vectors */
3830         v_actual = pci_enable_msix_range(pf->pdev, pf->msix_entries,
3831                                          ICE_MIN_MSIX, v_budget);
3832         if (v_actual < 0) {
3833                 dev_err(dev, "unable to reserve MSI-X vectors\n");
3834                 err = v_actual;
3835                 goto msix_err;
3836         }
3837
3838         if (v_actual < v_budget) {
3839                 dev_warn(dev, "not enough OS MSI-X vectors. requested = %d, obtained = %d\n",
3840                          v_budget, v_actual);
3841
3842                 if (v_actual < ICE_MIN_MSIX) {
3843                         /* error if we can't get minimum vectors */
3844                         pci_disable_msix(pf->pdev);
3845                         err = -ERANGE;
3846                         goto msix_err;
3847                 } else {
3848                         int v_remain = v_actual - v_other;
3849                         int v_rdma = 0, v_min_rdma = 0;
3850
3851                         if (test_bit(ICE_FLAG_RDMA_ENA, pf->flags)) {
3852                                 /* Need at least 1 interrupt in addition to
3853                                  * AEQ MSIX
3854                                  */
3855                                 v_rdma = ICE_RDMA_NUM_AEQ_MSIX + 1;
3856                                 v_min_rdma = ICE_MIN_RDMA_MSIX;
3857                         }
3858
3859                         if (v_actual == ICE_MIN_MSIX ||
3860                             v_remain < ICE_MIN_LAN_TXRX_MSIX + v_min_rdma) {
3861                                 dev_warn(dev, "Not enough MSI-X vectors to support RDMA.\n");
3862                                 clear_bit(ICE_FLAG_RDMA_ENA, pf->flags);
3863
3864                                 pf->num_rdma_msix = 0;
3865                                 pf->num_lan_msix = ICE_MIN_LAN_TXRX_MSIX;
3866                         } else if ((v_remain < ICE_MIN_LAN_TXRX_MSIX + v_rdma) ||
3867                                    (v_remain - v_rdma < v_rdma)) {
3868                                 /* Support minimum RDMA and give remaining
3869                                  * vectors to LAN MSIX
3870                                  */
3871                                 pf->num_rdma_msix = v_min_rdma;
3872                                 pf->num_lan_msix = v_remain - v_min_rdma;
3873                         } else {
3874                                 /* Split remaining MSIX with RDMA after
3875                                  * accounting for AEQ MSIX
3876                                  */
3877                                 pf->num_rdma_msix = (v_remain - ICE_RDMA_NUM_AEQ_MSIX) / 2 +
3878                                                     ICE_RDMA_NUM_AEQ_MSIX;
3879                                 pf->num_lan_msix = v_remain - pf->num_rdma_msix;
3880                         }
3881
3882                         dev_notice(dev, "Enabled %d MSI-X vectors for LAN traffic.\n",
3883                                    pf->num_lan_msix);
3884
3885                         if (test_bit(ICE_FLAG_RDMA_ENA, pf->flags))
3886                                 dev_notice(dev, "Enabled %d MSI-X vectors for RDMA.\n",
3887                                            pf->num_rdma_msix);
3888                 }
3889         }
3890
3891         return v_actual;
3892
3893 msix_err:
3894         devm_kfree(dev, pf->msix_entries);
3895         goto exit_err;
3896
3897 no_hw_vecs_left_err:
3898         dev_err(dev, "not enough device MSI-X vectors. requested = %d, available = %d\n",
3899                 needed, v_left);
3900         err = -ERANGE;
3901 exit_err:
3902         pf->num_rdma_msix = 0;
3903         pf->num_lan_msix = 0;
3904         return err;
3905 }
3906
3907 /**
3908  * ice_dis_msix - Disable MSI-X interrupt setup in OS
3909  * @pf: board private structure
3910  */
3911 static void ice_dis_msix(struct ice_pf *pf)
3912 {
3913         pci_disable_msix(pf->pdev);
3914         devm_kfree(ice_pf_to_dev(pf), pf->msix_entries);
3915         pf->msix_entries = NULL;
3916 }
3917
3918 /**
3919  * ice_clear_interrupt_scheme - Undo things done by ice_init_interrupt_scheme
3920  * @pf: board private structure
3921  */
3922 static void ice_clear_interrupt_scheme(struct ice_pf *pf)
3923 {
3924         ice_dis_msix(pf);
3925
3926         if (pf->irq_tracker) {
3927                 devm_kfree(ice_pf_to_dev(pf), pf->irq_tracker);
3928                 pf->irq_tracker = NULL;
3929         }
3930 }
3931
3932 /**
3933  * ice_init_interrupt_scheme - Determine proper interrupt scheme
3934  * @pf: board private structure to initialize
3935  */
3936 static int ice_init_interrupt_scheme(struct ice_pf *pf)
3937 {
3938         int vectors;
3939
3940         vectors = ice_ena_msix_range(pf);
3941
3942         if (vectors < 0)
3943                 return vectors;
3944
3945         /* set up vector assignment tracking */
3946         pf->irq_tracker = devm_kzalloc(ice_pf_to_dev(pf),
3947                                        struct_size(pf->irq_tracker, list, vectors),
3948                                        GFP_KERNEL);
3949         if (!pf->irq_tracker) {
3950                 ice_dis_msix(pf);
3951                 return -ENOMEM;
3952         }
3953
3954         /* populate SW interrupts pool with number of OS granted IRQs. */
3955         pf->num_avail_sw_msix = (u16)vectors;
3956         pf->irq_tracker->num_entries = (u16)vectors;
3957         pf->irq_tracker->end = pf->irq_tracker->num_entries;
3958
3959         return 0;
3960 }
3961
3962 /**
3963  * ice_is_wol_supported - check if WoL is supported
3964  * @hw: pointer to hardware info
3965  *
3966  * Check if WoL is supported based on the HW configuration.
3967  * Returns true if NVM supports and enables WoL for this port, false otherwise
3968  */
3969 bool ice_is_wol_supported(struct ice_hw *hw)
3970 {
3971         u16 wol_ctrl;
3972
3973         /* A bit set to 1 in the NVM Software Reserved Word 2 (WoL control
3974          * word) indicates WoL is not supported on the corresponding PF ID.
3975          */
3976         if (ice_read_sr_word(hw, ICE_SR_NVM_WOL_CFG, &wol_ctrl))
3977                 return false;
3978
3979         return !(BIT(hw->port_info->lport) & wol_ctrl);
3980 }
3981
3982 /**
3983  * ice_vsi_recfg_qs - Change the number of queues on a VSI
3984  * @vsi: VSI being changed
3985  * @new_rx: new number of Rx queues
3986  * @new_tx: new number of Tx queues
3987  *
3988  * Only change the number of queues if new_tx, or new_rx is non-0.
3989  *
3990  * Returns 0 on success.
3991  */
3992 int ice_vsi_recfg_qs(struct ice_vsi *vsi, int new_rx, int new_tx)
3993 {
3994         struct ice_pf *pf = vsi->back;
3995         int err = 0, timeout = 50;
3996
3997         if (!new_rx && !new_tx)
3998                 return -EINVAL;
3999
4000         while (test_and_set_bit(ICE_CFG_BUSY, pf->state)) {
4001                 timeout--;
4002                 if (!timeout)
4003                         return -EBUSY;
4004                 usleep_range(1000, 2000);
4005         }
4006
4007         if (new_tx)
4008                 vsi->req_txq = (u16)new_tx;
4009         if (new_rx)
4010                 vsi->req_rxq = (u16)new_rx;
4011
4012         /* set for the next time the netdev is started */
4013         if (!netif_running(vsi->netdev)) {
4014                 ice_vsi_rebuild(vsi, false);
4015                 dev_dbg(ice_pf_to_dev(pf), "Link is down, queue count change happens when link is brought up\n");
4016                 goto done;
4017         }
4018
4019         ice_vsi_close(vsi);
4020         ice_vsi_rebuild(vsi, false);
4021         ice_pf_dcb_recfg(pf);
4022         ice_vsi_open(vsi);
4023 done:
4024         clear_bit(ICE_CFG_BUSY, pf->state);
4025         return err;
4026 }
4027
4028 /**
4029  * ice_set_safe_mode_vlan_cfg - configure PF VSI to allow all VLANs in safe mode
4030  * @pf: PF to configure
4031  *
4032  * No VLAN offloads/filtering are advertised in safe mode so make sure the PF
4033  * VSI can still Tx/Rx VLAN tagged packets.
4034  */
4035 static void ice_set_safe_mode_vlan_cfg(struct ice_pf *pf)
4036 {
4037         struct ice_vsi *vsi = ice_get_main_vsi(pf);
4038         struct ice_vsi_ctx *ctxt;
4039         enum ice_status status;
4040         struct ice_hw *hw;
4041
4042         if (!vsi)
4043                 return;
4044
4045         ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL);
4046         if (!ctxt)
4047                 return;
4048
4049         hw = &pf->hw;
4050         ctxt->info = vsi->info;
4051
4052         ctxt->info.valid_sections =
4053                 cpu_to_le16(ICE_AQ_VSI_PROP_VLAN_VALID |
4054                             ICE_AQ_VSI_PROP_SECURITY_VALID |
4055                             ICE_AQ_VSI_PROP_SW_VALID);
4056
4057         /* disable VLAN anti-spoof */
4058         ctxt->info.sec_flags &= ~(ICE_AQ_VSI_SEC_TX_VLAN_PRUNE_ENA <<
4059                                   ICE_AQ_VSI_SEC_TX_PRUNE_ENA_S);
4060
4061         /* disable VLAN pruning and keep all other settings */
4062         ctxt->info.sw_flags2 &= ~ICE_AQ_VSI_SW_FLAG_RX_VLAN_PRUNE_ENA;
4063
4064         /* allow all VLANs on Tx and don't strip on Rx */
4065         ctxt->info.vlan_flags = ICE_AQ_VSI_VLAN_MODE_ALL |
4066                 ICE_AQ_VSI_VLAN_EMOD_NOTHING;
4067
4068         status = ice_update_vsi(hw, vsi->idx, ctxt, NULL);
4069         if (status) {
4070                 dev_err(ice_pf_to_dev(vsi->back), "Failed to update VSI for safe mode VLANs, err %s aq_err %s\n",
4071                         ice_stat_str(status),
4072                         ice_aq_str(hw->adminq.sq_last_status));
4073         } else {
4074                 vsi->info.sec_flags = ctxt->info.sec_flags;
4075                 vsi->info.sw_flags2 = ctxt->info.sw_flags2;
4076                 vsi->info.vlan_flags = ctxt->info.vlan_flags;
4077         }
4078
4079         kfree(ctxt);
4080 }
4081
4082 /**
4083  * ice_log_pkg_init - log result of DDP package load
4084  * @hw: pointer to hardware info
4085  * @status: status of package load
4086  */
4087 static void
4088 ice_log_pkg_init(struct ice_hw *hw, enum ice_status *status)
4089 {
4090         struct ice_pf *pf = (struct ice_pf *)hw->back;
4091         struct device *dev = ice_pf_to_dev(pf);
4092
4093         switch (*status) {
4094         case ICE_SUCCESS:
4095                 /* The package download AdminQ command returned success because
4096                  * this download succeeded or ICE_ERR_AQ_NO_WORK since there is
4097                  * already a package loaded on the device.
4098                  */
4099                 if (hw->pkg_ver.major == hw->active_pkg_ver.major &&
4100                     hw->pkg_ver.minor == hw->active_pkg_ver.minor &&
4101                     hw->pkg_ver.update == hw->active_pkg_ver.update &&
4102                     hw->pkg_ver.draft == hw->active_pkg_ver.draft &&
4103                     !memcmp(hw->pkg_name, hw->active_pkg_name,
4104                             sizeof(hw->pkg_name))) {
4105                         if (hw->pkg_dwnld_status == ICE_AQ_RC_EEXIST)
4106                                 dev_info(dev, "DDP package already present on device: %s version %d.%d.%d.%d\n",
4107                                          hw->active_pkg_name,
4108                                          hw->active_pkg_ver.major,
4109                                          hw->active_pkg_ver.minor,
4110                                          hw->active_pkg_ver.update,
4111                                          hw->active_pkg_ver.draft);
4112                         else
4113                                 dev_info(dev, "The DDP package was successfully loaded: %s version %d.%d.%d.%d\n",
4114                                          hw->active_pkg_name,
4115                                          hw->active_pkg_ver.major,
4116                                          hw->active_pkg_ver.minor,
4117                                          hw->active_pkg_ver.update,
4118                                          hw->active_pkg_ver.draft);
4119                 } else if (hw->active_pkg_ver.major != ICE_PKG_SUPP_VER_MAJ ||
4120                            hw->active_pkg_ver.minor != ICE_PKG_SUPP_VER_MNR) {
4121                         dev_err(dev, "The device has a DDP package that is not supported by the driver.  The device has package '%s' version %d.%d.x.x.  The driver requires version %d.%d.x.x.  Entering Safe Mode.\n",
4122                                 hw->active_pkg_name,
4123                                 hw->active_pkg_ver.major,
4124                                 hw->active_pkg_ver.minor,
4125                                 ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
4126                         *status = ICE_ERR_NOT_SUPPORTED;
4127                 } else if (hw->active_pkg_ver.major == ICE_PKG_SUPP_VER_MAJ &&
4128                            hw->active_pkg_ver.minor == ICE_PKG_SUPP_VER_MNR) {
4129                         dev_info(dev, "The driver could not load the DDP package file because a compatible DDP package is already present on the device.  The device has package '%s' version %d.%d.%d.%d.  The package file found by the driver: '%s' version %d.%d.%d.%d.\n",
4130                                  hw->active_pkg_name,
4131                                  hw->active_pkg_ver.major,
4132                                  hw->active_pkg_ver.minor,
4133                                  hw->active_pkg_ver.update,
4134                                  hw->active_pkg_ver.draft,
4135                                  hw->pkg_name,
4136                                  hw->pkg_ver.major,
4137                                  hw->pkg_ver.minor,
4138                                  hw->pkg_ver.update,
4139                                  hw->pkg_ver.draft);
4140                 } else {
4141                         dev_err(dev, "An unknown error occurred when loading the DDP package, please reboot the system.  If the problem persists, update the NVM.  Entering Safe Mode.\n");
4142                         *status = ICE_ERR_NOT_SUPPORTED;
4143                 }
4144                 break;
4145         case ICE_ERR_FW_DDP_MISMATCH:
4146                 dev_err(dev, "The firmware loaded on the device is not compatible with the DDP package.  Please update the device's NVM.  Entering safe mode.\n");
4147                 break;
4148         case ICE_ERR_BUF_TOO_SHORT:
4149         case ICE_ERR_CFG:
4150                 dev_err(dev, "The DDP package file is invalid. Entering Safe Mode.\n");
4151                 break;
4152         case ICE_ERR_NOT_SUPPORTED:
4153                 /* Package File version not supported */
4154                 if (hw->pkg_ver.major > ICE_PKG_SUPP_VER_MAJ ||
4155                     (hw->pkg_ver.major == ICE_PKG_SUPP_VER_MAJ &&
4156                      hw->pkg_ver.minor > ICE_PKG_SUPP_VER_MNR))
4157                         dev_err(dev, "The DDP package file version is higher than the driver supports.  Please use an updated driver.  Entering Safe Mode.\n");
4158                 else if (hw->pkg_ver.major < ICE_PKG_SUPP_VER_MAJ ||
4159                          (hw->pkg_ver.major == ICE_PKG_SUPP_VER_MAJ &&
4160                           hw->pkg_ver.minor < ICE_PKG_SUPP_VER_MNR))
4161                         dev_err(dev, "The DDP package file version is lower than the driver supports.  The driver requires version %d.%d.x.x.  Please use an updated DDP Package file.  Entering Safe Mode.\n",
4162                                 ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
4163                 break;
4164         case ICE_ERR_AQ_ERROR:
4165                 switch (hw->pkg_dwnld_status) {
4166                 case ICE_AQ_RC_ENOSEC:
4167                 case ICE_AQ_RC_EBADSIG:
4168                         dev_err(dev, "The DDP package could not be loaded because its signature is not valid.  Please use a valid DDP Package.  Entering Safe Mode.\n");
4169                         return;
4170                 case ICE_AQ_RC_ESVN:
4171                         dev_err(dev, "The DDP Package could not be loaded because its security revision is too low.  Please use an updated DDP Package.  Entering Safe Mode.\n");
4172                         return;
4173                 case ICE_AQ_RC_EBADMAN:
4174                 case ICE_AQ_RC_EBADBUF:
4175                         dev_err(dev, "An error occurred on the device while loading the DDP package.  The device will be reset.\n");
4176                         /* poll for reset to complete */
4177                         if (ice_check_reset(hw))
4178                                 dev_err(dev, "Error resetting device. Please reload the driver\n");
4179                         return;
4180                 default:
4181                         break;
4182                 }
4183                 fallthrough;
4184         default:
4185                 dev_err(dev, "An unknown error (%d) occurred when loading the DDP package.  Entering Safe Mode.\n",
4186                         *status);
4187                 break;
4188         }
4189 }
4190
4191 /**
4192  * ice_load_pkg - load/reload the DDP Package file
4193  * @firmware: firmware structure when firmware requested or NULL for reload
4194  * @pf: pointer to the PF instance
4195  *
4196  * Called on probe and post CORER/GLOBR rebuild to load DDP Package and
4197  * initialize HW tables.
4198  */
4199 static void
4200 ice_load_pkg(const struct firmware *firmware, struct ice_pf *pf)
4201 {
4202         enum ice_status status = ICE_ERR_PARAM;
4203         struct device *dev = ice_pf_to_dev(pf);
4204         struct ice_hw *hw = &pf->hw;
4205
4206         /* Load DDP Package */
4207         if (firmware && !hw->pkg_copy) {
4208                 status = ice_copy_and_init_pkg(hw, firmware->data,
4209                                                firmware->size);
4210                 ice_log_pkg_init(hw, &status);
4211         } else if (!firmware && hw->pkg_copy) {
4212                 /* Reload package during rebuild after CORER/GLOBR reset */
4213                 status = ice_init_pkg(hw, hw->pkg_copy, hw->pkg_size);
4214                 ice_log_pkg_init(hw, &status);
4215         } else {
4216                 dev_err(dev, "The DDP package file failed to load. Entering Safe Mode.\n");
4217         }
4218
4219         if (status) {
4220                 /* Safe Mode */
4221                 clear_bit(ICE_FLAG_ADV_FEATURES, pf->flags);
4222                 return;
4223         }
4224
4225         /* Successful download package is the precondition for advanced
4226          * features, hence setting the ICE_FLAG_ADV_FEATURES flag
4227          */
4228         set_bit(ICE_FLAG_ADV_FEATURES, pf->flags);
4229 }
4230
4231 /**
4232  * ice_verify_cacheline_size - verify driver's assumption of 64 Byte cache lines
4233  * @pf: pointer to the PF structure
4234  *
4235  * There is no error returned here because the driver should be able to handle
4236  * 128 Byte cache lines, so we only print a warning in case issues are seen,
4237  * specifically with Tx.
4238  */
4239 static void ice_verify_cacheline_size(struct ice_pf *pf)
4240 {
4241         if (rd32(&pf->hw, GLPCI_CNF2) & GLPCI_CNF2_CACHELINE_SIZE_M)
4242                 dev_warn(ice_pf_to_dev(pf), "%d Byte cache line assumption is invalid, driver may have Tx timeouts!\n",
4243                          ICE_CACHE_LINE_BYTES);
4244 }
4245
4246 /**
4247  * ice_send_version - update firmware with driver version
4248  * @pf: PF struct
4249  *
4250  * Returns ICE_SUCCESS on success, else error code
4251  */
4252 static enum ice_status ice_send_version(struct ice_pf *pf)
4253 {
4254         struct ice_driver_ver dv;
4255
4256         dv.major_ver = 0xff;
4257         dv.minor_ver = 0xff;
4258         dv.build_ver = 0xff;
4259         dv.subbuild_ver = 0;
4260         strscpy((char *)dv.driver_string, UTS_RELEASE,
4261                 sizeof(dv.driver_string));
4262         return ice_aq_send_driver_ver(&pf->hw, &dv, NULL);
4263 }
4264
4265 /**
4266  * ice_init_fdir - Initialize flow director VSI and configuration
4267  * @pf: pointer to the PF instance
4268  *
4269  * returns 0 on success, negative on error
4270  */
4271 static int ice_init_fdir(struct ice_pf *pf)
4272 {
4273         struct device *dev = ice_pf_to_dev(pf);
4274         struct ice_vsi *ctrl_vsi;
4275         int err;
4276
4277         /* Side Band Flow Director needs to have a control VSI.
4278          * Allocate it and store it in the PF.
4279          */
4280         ctrl_vsi = ice_ctrl_vsi_setup(pf, pf->hw.port_info);
4281         if (!ctrl_vsi) {
4282                 dev_dbg(dev, "could not create control VSI\n");
4283                 return -ENOMEM;
4284         }
4285
4286         err = ice_vsi_open_ctrl(ctrl_vsi);
4287         if (err) {
4288                 dev_dbg(dev, "could not open control VSI\n");
4289                 goto err_vsi_open;
4290         }
4291
4292         mutex_init(&pf->hw.fdir_fltr_lock);
4293
4294         err = ice_fdir_create_dflt_rules(pf);
4295         if (err)
4296                 goto err_fdir_rule;
4297
4298         return 0;
4299
4300 err_fdir_rule:
4301         ice_fdir_release_flows(&pf->hw);
4302         ice_vsi_close(ctrl_vsi);
4303 err_vsi_open:
4304         ice_vsi_release(ctrl_vsi);
4305         if (pf->ctrl_vsi_idx != ICE_NO_VSI) {
4306                 pf->vsi[pf->ctrl_vsi_idx] = NULL;
4307                 pf->ctrl_vsi_idx = ICE_NO_VSI;
4308         }
4309         return err;
4310 }
4311
4312 /**
4313  * ice_get_opt_fw_name - return optional firmware file name or NULL
4314  * @pf: pointer to the PF instance
4315  */
4316 static char *ice_get_opt_fw_name(struct ice_pf *pf)
4317 {
4318         /* Optional firmware name same as default with additional dash
4319          * followed by a EUI-64 identifier (PCIe Device Serial Number)
4320          */
4321         struct pci_dev *pdev = pf->pdev;
4322         char *opt_fw_filename;
4323         u64 dsn;
4324
4325         /* Determine the name of the optional file using the DSN (two
4326          * dwords following the start of the DSN Capability).
4327          */
4328         dsn = pci_get_dsn(pdev);
4329         if (!dsn)
4330                 return NULL;
4331
4332         opt_fw_filename = kzalloc(NAME_MAX, GFP_KERNEL);
4333         if (!opt_fw_filename)
4334                 return NULL;
4335
4336         snprintf(opt_fw_filename, NAME_MAX, "%sice-%016llx.pkg",
4337                  ICE_DDP_PKG_PATH, dsn);
4338
4339         return opt_fw_filename;
4340 }
4341
4342 /**
4343  * ice_request_fw - Device initialization routine
4344  * @pf: pointer to the PF instance
4345  */
4346 static void ice_request_fw(struct ice_pf *pf)
4347 {
4348         char *opt_fw_filename = ice_get_opt_fw_name(pf);
4349         const struct firmware *firmware = NULL;
4350         struct device *dev = ice_pf_to_dev(pf);
4351         int err = 0;
4352
4353         /* optional device-specific DDP (if present) overrides the default DDP
4354          * package file. kernel logs a debug message if the file doesn't exist,
4355          * and warning messages for other errors.
4356          */
4357         if (opt_fw_filename) {
4358                 err = firmware_request_nowarn(&firmware, opt_fw_filename, dev);
4359                 if (err) {
4360                         kfree(opt_fw_filename);
4361                         goto dflt_pkg_load;
4362                 }
4363
4364                 /* request for firmware was successful. Download to device */
4365                 ice_load_pkg(firmware, pf);
4366                 kfree(opt_fw_filename);
4367                 release_firmware(firmware);
4368                 return;
4369         }
4370
4371 dflt_pkg_load:
4372         err = request_firmware(&firmware, ICE_DDP_PKG_FILE, dev);
4373         if (err) {
4374                 dev_err(dev, "The DDP package file was not found or could not be read. Entering Safe Mode\n");
4375                 return;
4376         }
4377
4378         /* request for firmware was successful. Download to device */
4379         ice_load_pkg(firmware, pf);
4380         release_firmware(firmware);
4381 }
4382
4383 /**
4384  * ice_print_wake_reason - show the wake up cause in the log
4385  * @pf: pointer to the PF struct
4386  */
4387 static void ice_print_wake_reason(struct ice_pf *pf)
4388 {
4389         u32 wus = pf->wakeup_reason;
4390         const char *wake_str;
4391
4392         /* if no wake event, nothing to print */
4393         if (!wus)
4394                 return;
4395
4396         if (wus & PFPM_WUS_LNKC_M)
4397                 wake_str = "Link\n";
4398         else if (wus & PFPM_WUS_MAG_M)
4399                 wake_str = "Magic Packet\n";
4400         else if (wus & PFPM_WUS_MNG_M)
4401                 wake_str = "Management\n";
4402         else if (wus & PFPM_WUS_FW_RST_WK_M)
4403                 wake_str = "Firmware Reset\n";
4404         else
4405                 wake_str = "Unknown\n";
4406
4407         dev_info(ice_pf_to_dev(pf), "Wake reason: %s", wake_str);
4408 }
4409
4410 /**
4411  * ice_register_netdev - register netdev and devlink port
4412  * @pf: pointer to the PF struct
4413  */
4414 static int ice_register_netdev(struct ice_pf *pf)
4415 {
4416         struct ice_vsi *vsi;
4417         int err = 0;
4418
4419         vsi = ice_get_main_vsi(pf);
4420         if (!vsi || !vsi->netdev)
4421                 return -EIO;
4422
4423         err = register_netdev(vsi->netdev);
4424         if (err)
4425                 goto err_register_netdev;
4426
4427         set_bit(ICE_VSI_NETDEV_REGISTERED, vsi->state);
4428         netif_carrier_off(vsi->netdev);
4429         netif_tx_stop_all_queues(vsi->netdev);
4430         err = ice_devlink_create_pf_port(pf);
4431         if (err)
4432                 goto err_devlink_create;
4433
4434         devlink_port_type_eth_set(&pf->devlink_port, vsi->netdev);
4435
4436         return 0;
4437 err_devlink_create:
4438         unregister_netdev(vsi->netdev);
4439         clear_bit(ICE_VSI_NETDEV_REGISTERED, vsi->state);
4440 err_register_netdev:
4441         free_netdev(vsi->netdev);
4442         vsi->netdev = NULL;
4443         clear_bit(ICE_VSI_NETDEV_ALLOCD, vsi->state);
4444         return err;
4445 }
4446
4447 /**
4448  * ice_probe - Device initialization routine
4449  * @pdev: PCI device information struct
4450  * @ent: entry in ice_pci_tbl
4451  *
4452  * Returns 0 on success, negative on failure
4453  */
4454 static int
4455 ice_probe(struct pci_dev *pdev, const struct pci_device_id __always_unused *ent)
4456 {
4457         struct device *dev = &pdev->dev;
4458         struct ice_pf *pf;
4459         struct ice_hw *hw;
4460         int i, err;
4461
4462         if (pdev->is_virtfn) {
4463                 dev_err(dev, "can't probe a virtual function\n");
4464                 return -EINVAL;
4465         }
4466
4467         /* this driver uses devres, see
4468          * Documentation/driver-api/driver-model/devres.rst
4469          */
4470         err = pcim_enable_device(pdev);
4471         if (err)
4472                 return err;
4473
4474         err = pcim_iomap_regions(pdev, BIT(ICE_BAR0), dev_driver_string(dev));
4475         if (err) {
4476                 dev_err(dev, "BAR0 I/O map error %d\n", err);
4477                 return err;
4478         }
4479
4480         pf = ice_allocate_pf(dev);
4481         if (!pf)
4482                 return -ENOMEM;
4483
4484         /* initialize Auxiliary index to invalid value */
4485         pf->aux_idx = -1;
4486
4487         /* set up for high or low DMA */
4488         err = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64));
4489         if (err)
4490                 err = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32));
4491         if (err) {
4492                 dev_err(dev, "DMA configuration failed: 0x%x\n", err);
4493                 return err;
4494         }
4495
4496         pci_enable_pcie_error_reporting(pdev);
4497         pci_set_master(pdev);
4498
4499         pf->pdev = pdev;
4500         pci_set_drvdata(pdev, pf);
4501         set_bit(ICE_DOWN, pf->state);
4502         /* Disable service task until DOWN bit is cleared */
4503         set_bit(ICE_SERVICE_DIS, pf->state);
4504
4505         hw = &pf->hw;
4506         hw->hw_addr = pcim_iomap_table(pdev)[ICE_BAR0];
4507         pci_save_state(pdev);
4508
4509         hw->back = pf;
4510         hw->vendor_id = pdev->vendor;
4511         hw->device_id = pdev->device;
4512         pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
4513         hw->subsystem_vendor_id = pdev->subsystem_vendor;
4514         hw->subsystem_device_id = pdev->subsystem_device;
4515         hw->bus.device = PCI_SLOT(pdev->devfn);
4516         hw->bus.func = PCI_FUNC(pdev->devfn);
4517         ice_set_ctrlq_len(hw);
4518
4519         pf->msg_enable = netif_msg_init(debug, ICE_DFLT_NETIF_M);
4520
4521 #ifndef CONFIG_DYNAMIC_DEBUG
4522         if (debug < -1)
4523                 hw->debug_mask = debug;
4524 #endif
4525
4526         err = ice_init_hw(hw);
4527         if (err) {
4528                 dev_err(dev, "ice_init_hw failed: %d\n", err);
4529                 err = -EIO;
4530                 goto err_exit_unroll;
4531         }
4532
4533         ice_init_feature_support(pf);
4534
4535         ice_request_fw(pf);
4536
4537         /* if ice_request_fw fails, ICE_FLAG_ADV_FEATURES bit won't be
4538          * set in pf->state, which will cause ice_is_safe_mode to return
4539          * true
4540          */
4541         if (ice_is_safe_mode(pf)) {
4542                 dev_err(dev, "Package download failed. Advanced features disabled - Device now in Safe Mode\n");
4543                 /* we already got function/device capabilities but these don't
4544                  * reflect what the driver needs to do in safe mode. Instead of
4545                  * adding conditional logic everywhere to ignore these
4546                  * device/function capabilities, override them.
4547                  */
4548                 ice_set_safe_mode_caps(hw);
4549         }
4550
4551         err = ice_init_pf(pf);
4552         if (err) {
4553                 dev_err(dev, "ice_init_pf failed: %d\n", err);
4554                 goto err_init_pf_unroll;
4555         }
4556
4557         ice_devlink_init_regions(pf);
4558
4559         pf->hw.udp_tunnel_nic.set_port = ice_udp_tunnel_set_port;
4560         pf->hw.udp_tunnel_nic.unset_port = ice_udp_tunnel_unset_port;
4561         pf->hw.udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP;
4562         pf->hw.udp_tunnel_nic.shared = &pf->hw.udp_tunnel_shared;
4563         i = 0;
4564         if (pf->hw.tnl.valid_count[TNL_VXLAN]) {
4565                 pf->hw.udp_tunnel_nic.tables[i].n_entries =
4566                         pf->hw.tnl.valid_count[TNL_VXLAN];
4567                 pf->hw.udp_tunnel_nic.tables[i].tunnel_types =
4568                         UDP_TUNNEL_TYPE_VXLAN;
4569                 i++;
4570         }
4571         if (pf->hw.tnl.valid_count[TNL_GENEVE]) {
4572                 pf->hw.udp_tunnel_nic.tables[i].n_entries =
4573                         pf->hw.tnl.valid_count[TNL_GENEVE];
4574                 pf->hw.udp_tunnel_nic.tables[i].tunnel_types =
4575                         UDP_TUNNEL_TYPE_GENEVE;
4576                 i++;
4577         }
4578
4579         pf->num_alloc_vsi = hw->func_caps.guar_num_vsi;
4580         if (!pf->num_alloc_vsi) {
4581                 err = -EIO;
4582                 goto err_init_pf_unroll;
4583         }
4584         if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
4585                 dev_warn(&pf->pdev->dev,
4586                          "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
4587                          pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
4588                 pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
4589         }
4590
4591         pf->vsi = devm_kcalloc(dev, pf->num_alloc_vsi, sizeof(*pf->vsi),
4592                                GFP_KERNEL);
4593         if (!pf->vsi) {
4594                 err = -ENOMEM;
4595                 goto err_init_pf_unroll;
4596         }
4597
4598         err = ice_init_interrupt_scheme(pf);
4599         if (err) {
4600                 dev_err(dev, "ice_init_interrupt_scheme failed: %d\n", err);
4601                 err = -EIO;
4602                 goto err_init_vsi_unroll;
4603         }
4604
4605         /* In case of MSIX we are going to setup the misc vector right here
4606          * to handle admin queue events etc. In case of legacy and MSI
4607          * the misc functionality and queue processing is combined in
4608          * the same vector and that gets setup at open.
4609          */
4610         err = ice_req_irq_msix_misc(pf);
4611         if (err) {
4612                 dev_err(dev, "setup of misc vector failed: %d\n", err);
4613                 goto err_init_interrupt_unroll;
4614         }
4615
4616         /* create switch struct for the switch element created by FW on boot */
4617         pf->first_sw = devm_kzalloc(dev, sizeof(*pf->first_sw), GFP_KERNEL);
4618         if (!pf->first_sw) {
4619                 err = -ENOMEM;
4620                 goto err_msix_misc_unroll;
4621         }
4622
4623         if (hw->evb_veb)
4624                 pf->first_sw->bridge_mode = BRIDGE_MODE_VEB;
4625         else
4626                 pf->first_sw->bridge_mode = BRIDGE_MODE_VEPA;
4627
4628         pf->first_sw->pf = pf;
4629
4630         /* record the sw_id available for later use */
4631         pf->first_sw->sw_id = hw->port_info->sw_id;
4632
4633         err = ice_setup_pf_sw(pf);
4634         if (err) {
4635                 dev_err(dev, "probe failed due to setup PF switch: %d\n", err);
4636                 goto err_alloc_sw_unroll;
4637         }
4638
4639         clear_bit(ICE_SERVICE_DIS, pf->state);
4640
4641         /* tell the firmware we are up */
4642         err = ice_send_version(pf);
4643         if (err) {
4644                 dev_err(dev, "probe failed sending driver version %s. error: %d\n",
4645                         UTS_RELEASE, err);
4646                 goto err_send_version_unroll;
4647         }
4648
4649         /* since everything is good, start the service timer */
4650         mod_timer(&pf->serv_tmr, round_jiffies(jiffies + pf->serv_tmr_period));
4651
4652         err = ice_init_link_events(pf->hw.port_info);
4653         if (err) {
4654                 dev_err(dev, "ice_init_link_events failed: %d\n", err);
4655                 goto err_send_version_unroll;
4656         }
4657
4658         /* not a fatal error if this fails */
4659         err = ice_init_nvm_phy_type(pf->hw.port_info);
4660         if (err)
4661                 dev_err(dev, "ice_init_nvm_phy_type failed: %d\n", err);
4662
4663         /* not a fatal error if this fails */
4664         err = ice_update_link_info(pf->hw.port_info);
4665         if (err)
4666                 dev_err(dev, "ice_update_link_info failed: %d\n", err);
4667
4668         ice_init_link_dflt_override(pf->hw.port_info);
4669
4670         ice_check_link_cfg_err(pf,
4671                                pf->hw.port_info->phy.link_info.link_cfg_err);
4672
4673         /* if media available, initialize PHY settings */
4674         if (pf->hw.port_info->phy.link_info.link_info &
4675             ICE_AQ_MEDIA_AVAILABLE) {
4676                 /* not a fatal error if this fails */
4677                 err = ice_init_phy_user_cfg(pf->hw.port_info);
4678                 if (err)
4679                         dev_err(dev, "ice_init_phy_user_cfg failed: %d\n", err);
4680
4681                 if (!test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags)) {
4682                         struct ice_vsi *vsi = ice_get_main_vsi(pf);
4683
4684                         if (vsi)
4685                                 ice_configure_phy(vsi);
4686                 }
4687         } else {
4688                 set_bit(ICE_FLAG_NO_MEDIA, pf->flags);
4689         }
4690
4691         ice_verify_cacheline_size(pf);
4692
4693         /* Save wakeup reason register for later use */
4694         pf->wakeup_reason = rd32(hw, PFPM_WUS);
4695
4696         /* check for a power management event */
4697         ice_print_wake_reason(pf);
4698
4699         /* clear wake status, all bits */
4700         wr32(hw, PFPM_WUS, U32_MAX);
4701
4702         /* Disable WoL at init, wait for user to enable */
4703         device_set_wakeup_enable(dev, false);
4704
4705         if (ice_is_safe_mode(pf)) {
4706                 ice_set_safe_mode_vlan_cfg(pf);
4707                 goto probe_done;
4708         }
4709
4710         /* initialize DDP driven features */
4711         if (test_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags))
4712                 ice_ptp_init(pf);
4713
4714         /* Note: Flow director init failure is non-fatal to load */
4715         if (ice_init_fdir(pf))
4716                 dev_err(dev, "could not initialize flow director\n");
4717
4718         /* Note: DCB init failure is non-fatal to load */
4719         if (ice_init_pf_dcb(pf, false)) {
4720                 clear_bit(ICE_FLAG_DCB_CAPABLE, pf->flags);
4721                 clear_bit(ICE_FLAG_DCB_ENA, pf->flags);
4722         } else {
4723                 ice_cfg_lldp_mib_change(&pf->hw, true);
4724         }
4725
4726         if (ice_init_lag(pf))
4727                 dev_warn(dev, "Failed to init link aggregation support\n");
4728
4729         /* print PCI link speed and width */
4730         pcie_print_link_status(pf->pdev);
4731
4732 probe_done:
4733         err = ice_register_netdev(pf);
4734         if (err)
4735                 goto err_netdev_reg;
4736
4737         err = ice_devlink_register_params(pf);
4738         if (err)
4739                 goto err_netdev_reg;
4740
4741         /* ready to go, so clear down state bit */
4742         clear_bit(ICE_DOWN, pf->state);
4743         if (ice_is_aux_ena(pf)) {
4744                 pf->aux_idx = ida_alloc(&ice_aux_ida, GFP_KERNEL);
4745                 if (pf->aux_idx < 0) {
4746                         dev_err(dev, "Failed to allocate device ID for AUX driver\n");
4747                         err = -ENOMEM;
4748                         goto err_devlink_reg_param;
4749                 }
4750
4751                 err = ice_init_rdma(pf);
4752                 if (err) {
4753                         dev_err(dev, "Failed to initialize RDMA: %d\n", err);
4754                         err = -EIO;
4755                         goto err_init_aux_unroll;
4756                 }
4757         } else {
4758                 dev_warn(dev, "RDMA is not supported on this device\n");
4759         }
4760
4761         ice_devlink_register(pf);
4762         return 0;
4763
4764 err_init_aux_unroll:
4765         pf->adev = NULL;
4766         ida_free(&ice_aux_ida, pf->aux_idx);
4767 err_devlink_reg_param:
4768         ice_devlink_unregister_params(pf);
4769 err_netdev_reg:
4770 err_send_version_unroll:
4771         ice_vsi_release_all(pf);
4772 err_alloc_sw_unroll:
4773         set_bit(ICE_SERVICE_DIS, pf->state);
4774         set_bit(ICE_DOWN, pf->state);
4775         devm_kfree(dev, pf->first_sw);
4776 err_msix_misc_unroll:
4777         ice_free_irq_msix_misc(pf);
4778 err_init_interrupt_unroll:
4779         ice_clear_interrupt_scheme(pf);
4780 err_init_vsi_unroll:
4781         devm_kfree(dev, pf->vsi);
4782 err_init_pf_unroll:
4783         ice_deinit_pf(pf);
4784         ice_devlink_destroy_regions(pf);
4785         ice_deinit_hw(hw);
4786 err_exit_unroll:
4787         pci_disable_pcie_error_reporting(pdev);
4788         pci_disable_device(pdev);
4789         return err;
4790 }
4791
4792 /**
4793  * ice_set_wake - enable or disable Wake on LAN
4794  * @pf: pointer to the PF struct
4795  *
4796  * Simple helper for WoL control
4797  */
4798 static void ice_set_wake(struct ice_pf *pf)
4799 {
4800         struct ice_hw *hw = &pf->hw;
4801         bool wol = pf->wol_ena;
4802
4803         /* clear wake state, otherwise new wake events won't fire */
4804         wr32(hw, PFPM_WUS, U32_MAX);
4805
4806         /* enable / disable APM wake up, no RMW needed */
4807         wr32(hw, PFPM_APM, wol ? PFPM_APM_APME_M : 0);
4808
4809         /* set magic packet filter enabled */
4810         wr32(hw, PFPM_WUFC, wol ? PFPM_WUFC_MAG_M : 0);
4811 }
4812
4813 /**
4814  * ice_setup_mc_magic_wake - setup device to wake on multicast magic packet
4815  * @pf: pointer to the PF struct
4816  *
4817  * Issue firmware command to enable multicast magic wake, making
4818  * sure that any locally administered address (LAA) is used for
4819  * wake, and that PF reset doesn't undo the LAA.
4820  */
4821 static void ice_setup_mc_magic_wake(struct ice_pf *pf)
4822 {
4823         struct device *dev = ice_pf_to_dev(pf);
4824         struct ice_hw *hw = &pf->hw;
4825         enum ice_status status;
4826         u8 mac_addr[ETH_ALEN];
4827         struct ice_vsi *vsi;
4828         u8 flags;
4829
4830         if (!pf->wol_ena)
4831                 return;
4832
4833         vsi = ice_get_main_vsi(pf);
4834         if (!vsi)
4835                 return;
4836
4837         /* Get current MAC address in case it's an LAA */
4838         if (vsi->netdev)
4839                 ether_addr_copy(mac_addr, vsi->netdev->dev_addr);
4840         else
4841                 ether_addr_copy(mac_addr, vsi->port_info->mac.perm_addr);
4842
4843         flags = ICE_AQC_MAN_MAC_WR_MC_MAG_EN |
4844                 ICE_AQC_MAN_MAC_UPDATE_LAA_WOL |
4845                 ICE_AQC_MAN_MAC_WR_WOL_LAA_PFR_KEEP;
4846
4847         status = ice_aq_manage_mac_write(hw, mac_addr, flags, NULL);
4848         if (status)
4849                 dev_err(dev, "Failed to enable Multicast Magic Packet wake, err %s aq_err %s\n",
4850                         ice_stat_str(status),
4851                         ice_aq_str(hw->adminq.sq_last_status));
4852 }
4853
4854 /**
4855  * ice_remove - Device removal routine
4856  * @pdev: PCI device information struct
4857  */
4858 static void ice_remove(struct pci_dev *pdev)
4859 {
4860         struct ice_pf *pf = pci_get_drvdata(pdev);
4861         int i;
4862
4863         ice_devlink_unregister(pf);
4864         for (i = 0; i < ICE_MAX_RESET_WAIT; i++) {
4865                 if (!ice_is_reset_in_progress(pf->state))
4866                         break;
4867                 msleep(100);
4868         }
4869
4870         ice_tc_indir_block_remove(pf);
4871
4872         if (test_bit(ICE_FLAG_SRIOV_ENA, pf->flags)) {
4873                 set_bit(ICE_VF_RESETS_DISABLED, pf->state);
4874                 ice_free_vfs(pf);
4875         }
4876
4877         ice_service_task_stop(pf);
4878
4879         ice_aq_cancel_waiting_tasks(pf);
4880         ice_unplug_aux_dev(pf);
4881         if (pf->aux_idx >= 0)
4882                 ida_free(&ice_aux_ida, pf->aux_idx);
4883         ice_devlink_unregister_params(pf);
4884         set_bit(ICE_DOWN, pf->state);
4885
4886         mutex_destroy(&(&pf->hw)->fdir_fltr_lock);
4887         ice_deinit_lag(pf);
4888         if (test_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags))
4889                 ice_ptp_release(pf);
4890         if (!ice_is_safe_mode(pf))
4891                 ice_remove_arfs(pf);
4892         ice_setup_mc_magic_wake(pf);
4893         ice_vsi_release_all(pf);
4894         ice_set_wake(pf);
4895         ice_free_irq_msix_misc(pf);
4896         ice_for_each_vsi(pf, i) {
4897                 if (!pf->vsi[i])
4898                         continue;
4899                 ice_vsi_free_q_vectors(pf->vsi[i]);
4900         }
4901         ice_deinit_pf(pf);
4902         ice_devlink_destroy_regions(pf);
4903         ice_deinit_hw(&pf->hw);
4904
4905         /* Issue a PFR as part of the prescribed driver unload flow.  Do not
4906          * do it via ice_schedule_reset() since there is no need to rebuild
4907          * and the service task is already stopped.
4908          */
4909         ice_reset(&pf->hw, ICE_RESET_PFR);
4910         pci_wait_for_pending_transaction(pdev);
4911         ice_clear_interrupt_scheme(pf);
4912         pci_disable_pcie_error_reporting(pdev);
4913         pci_disable_device(pdev);
4914 }
4915
4916 /**
4917  * ice_shutdown - PCI callback for shutting down device
4918  * @pdev: PCI device information struct
4919  */
4920 static void ice_shutdown(struct pci_dev *pdev)
4921 {
4922         struct ice_pf *pf = pci_get_drvdata(pdev);
4923
4924         ice_remove(pdev);
4925
4926         if (system_state == SYSTEM_POWER_OFF) {
4927                 pci_wake_from_d3(pdev, pf->wol_ena);
4928                 pci_set_power_state(pdev, PCI_D3hot);
4929         }
4930 }
4931
4932 #ifdef CONFIG_PM
4933 /**
4934  * ice_prepare_for_shutdown - prep for PCI shutdown
4935  * @pf: board private structure
4936  *
4937  * Inform or close all dependent features in prep for PCI device shutdown
4938  */
4939 static void ice_prepare_for_shutdown(struct ice_pf *pf)
4940 {
4941         struct ice_hw *hw = &pf->hw;
4942         u32 v;
4943
4944         /* Notify VFs of impending reset */
4945         if (ice_check_sq_alive(hw, &hw->mailboxq))
4946                 ice_vc_notify_reset(pf);
4947
4948         dev_dbg(ice_pf_to_dev(pf), "Tearing down internal switch for shutdown\n");
4949
4950         /* disable the VSIs and their queues that are not already DOWN */
4951         ice_pf_dis_all_vsi(pf, false);
4952
4953         ice_for_each_vsi(pf, v)
4954                 if (pf->vsi[v])
4955                         pf->vsi[v]->vsi_num = 0;
4956
4957         ice_shutdown_all_ctrlq(hw);
4958 }
4959
4960 /**
4961  * ice_reinit_interrupt_scheme - Reinitialize interrupt scheme
4962  * @pf: board private structure to reinitialize
4963  *
4964  * This routine reinitialize interrupt scheme that was cleared during
4965  * power management suspend callback.
4966  *
4967  * This should be called during resume routine to re-allocate the q_vectors
4968  * and reacquire interrupts.
4969  */
4970 static int ice_reinit_interrupt_scheme(struct ice_pf *pf)
4971 {
4972         struct device *dev = ice_pf_to_dev(pf);
4973         int ret, v;
4974
4975         /* Since we clear MSIX flag during suspend, we need to
4976          * set it back during resume...
4977          */
4978
4979         ret = ice_init_interrupt_scheme(pf);
4980         if (ret) {
4981                 dev_err(dev, "Failed to re-initialize interrupt %d\n", ret);
4982                 return ret;
4983         }
4984
4985         /* Remap vectors and rings, after successful re-init interrupts */
4986         ice_for_each_vsi(pf, v) {
4987                 if (!pf->vsi[v])
4988                         continue;
4989
4990                 ret = ice_vsi_alloc_q_vectors(pf->vsi[v]);
4991                 if (ret)
4992                         goto err_reinit;
4993                 ice_vsi_map_rings_to_vectors(pf->vsi[v]);
4994         }
4995
4996         ret = ice_req_irq_msix_misc(pf);
4997         if (ret) {
4998                 dev_err(dev, "Setting up misc vector failed after device suspend %d\n",
4999                         ret);
5000                 goto err_reinit;
5001         }
5002
5003         return 0;
5004
5005 err_reinit:
5006         while (v--)
5007                 if (pf->vsi[v])
5008                         ice_vsi_free_q_vectors(pf->vsi[v]);
5009
5010         return ret;
5011 }
5012
5013 /**
5014  * ice_suspend
5015  * @dev: generic device information structure
5016  *
5017  * Power Management callback to quiesce the device and prepare
5018  * for D3 transition.
5019  */
5020 static int __maybe_unused ice_suspend(struct device *dev)
5021 {
5022         struct pci_dev *pdev = to_pci_dev(dev);
5023         struct ice_pf *pf;
5024         int disabled, v;
5025
5026         pf = pci_get_drvdata(pdev);
5027
5028         if (!ice_pf_state_is_nominal(pf)) {
5029                 dev_err(dev, "Device is not ready, no need to suspend it\n");
5030                 return -EBUSY;
5031         }
5032
5033         /* Stop watchdog tasks until resume completion.
5034          * Even though it is most likely that the service task is
5035          * disabled if the device is suspended or down, the service task's
5036          * state is controlled by a different state bit, and we should
5037          * store and honor whatever state that bit is in at this point.
5038          */
5039         disabled = ice_service_task_stop(pf);
5040
5041         ice_unplug_aux_dev(pf);
5042
5043         /* Already suspended?, then there is nothing to do */
5044         if (test_and_set_bit(ICE_SUSPENDED, pf->state)) {
5045                 if (!disabled)
5046                         ice_service_task_restart(pf);
5047                 return 0;
5048         }
5049
5050         if (test_bit(ICE_DOWN, pf->state) ||
5051             ice_is_reset_in_progress(pf->state)) {
5052                 dev_err(dev, "can't suspend device in reset or already down\n");
5053                 if (!disabled)
5054                         ice_service_task_restart(pf);
5055                 return 0;
5056         }
5057
5058         ice_setup_mc_magic_wake(pf);
5059
5060         ice_prepare_for_shutdown(pf);
5061
5062         ice_set_wake(pf);
5063
5064         /* Free vectors, clear the interrupt scheme and release IRQs
5065          * for proper hibernation, especially with large number of CPUs.
5066          * Otherwise hibernation might fail when mapping all the vectors back
5067          * to CPU0.
5068          */
5069         ice_free_irq_msix_misc(pf);
5070         ice_for_each_vsi(pf, v) {
5071                 if (!pf->vsi[v])
5072                         continue;
5073                 ice_vsi_free_q_vectors(pf->vsi[v]);
5074         }
5075         ice_free_cpu_rx_rmap(ice_get_main_vsi(pf));
5076         ice_clear_interrupt_scheme(pf);
5077
5078         pci_save_state(pdev);
5079         pci_wake_from_d3(pdev, pf->wol_ena);
5080         pci_set_power_state(pdev, PCI_D3hot);
5081         return 0;
5082 }
5083
5084 /**
5085  * ice_resume - PM callback for waking up from D3
5086  * @dev: generic device information structure
5087  */
5088 static int __maybe_unused ice_resume(struct device *dev)
5089 {
5090         struct pci_dev *pdev = to_pci_dev(dev);
5091         enum ice_reset_req reset_type;
5092         struct ice_pf *pf;
5093         struct ice_hw *hw;
5094         int ret;
5095
5096         pci_set_power_state(pdev, PCI_D0);
5097         pci_restore_state(pdev);
5098         pci_save_state(pdev);
5099
5100         if (!pci_device_is_present(pdev))
5101                 return -ENODEV;
5102
5103         ret = pci_enable_device_mem(pdev);
5104         if (ret) {
5105                 dev_err(dev, "Cannot enable device after suspend\n");
5106                 return ret;
5107         }
5108
5109         pf = pci_get_drvdata(pdev);
5110         hw = &pf->hw;
5111
5112         pf->wakeup_reason = rd32(hw, PFPM_WUS);
5113         ice_print_wake_reason(pf);
5114
5115         /* We cleared the interrupt scheme when we suspended, so we need to
5116          * restore it now to resume device functionality.
5117          */
5118         ret = ice_reinit_interrupt_scheme(pf);
5119         if (ret)
5120                 dev_err(dev, "Cannot restore interrupt scheme: %d\n", ret);
5121
5122         clear_bit(ICE_DOWN, pf->state);
5123         /* Now perform PF reset and rebuild */
5124         reset_type = ICE_RESET_PFR;
5125         /* re-enable service task for reset, but allow reset to schedule it */
5126         clear_bit(ICE_SERVICE_DIS, pf->state);
5127
5128         if (ice_schedule_reset(pf, reset_type))
5129                 dev_err(dev, "Reset during resume failed.\n");
5130
5131         clear_bit(ICE_SUSPENDED, pf->state);
5132         ice_service_task_restart(pf);
5133
5134         /* Restart the service task */
5135         mod_timer(&pf->serv_tmr, round_jiffies(jiffies + pf->serv_tmr_period));
5136
5137         return 0;
5138 }
5139 #endif /* CONFIG_PM */
5140
5141 /**
5142  * ice_pci_err_detected - warning that PCI error has been detected
5143  * @pdev: PCI device information struct
5144  * @err: the type of PCI error
5145  *
5146  * Called to warn that something happened on the PCI bus and the error handling
5147  * is in progress.  Allows the driver to gracefully prepare/handle PCI errors.
5148  */
5149 static pci_ers_result_t
5150 ice_pci_err_detected(struct pci_dev *pdev, pci_channel_state_t err)
5151 {
5152         struct ice_pf *pf = pci_get_drvdata(pdev);
5153
5154         if (!pf) {
5155                 dev_err(&pdev->dev, "%s: unrecoverable device error %d\n",
5156                         __func__, err);
5157                 return PCI_ERS_RESULT_DISCONNECT;
5158         }
5159
5160         if (!test_bit(ICE_SUSPENDED, pf->state)) {
5161                 ice_service_task_stop(pf);
5162
5163                 if (!test_bit(ICE_PREPARED_FOR_RESET, pf->state)) {
5164                         set_bit(ICE_PFR_REQ, pf->state);
5165                         ice_prepare_for_reset(pf, ICE_RESET_PFR);
5166                 }
5167         }
5168
5169         return PCI_ERS_RESULT_NEED_RESET;
5170 }
5171
5172 /**
5173  * ice_pci_err_slot_reset - a PCI slot reset has just happened
5174  * @pdev: PCI device information struct
5175  *
5176  * Called to determine if the driver can recover from the PCI slot reset by
5177  * using a register read to determine if the device is recoverable.
5178  */
5179 static pci_ers_result_t ice_pci_err_slot_reset(struct pci_dev *pdev)
5180 {
5181         struct ice_pf *pf = pci_get_drvdata(pdev);
5182         pci_ers_result_t result;
5183         int err;
5184         u32 reg;
5185
5186         err = pci_enable_device_mem(pdev);
5187         if (err) {
5188                 dev_err(&pdev->dev, "Cannot re-enable PCI device after reset, error %d\n",
5189                         err);
5190                 result = PCI_ERS_RESULT_DISCONNECT;
5191         } else {
5192                 pci_set_master(pdev);
5193                 pci_restore_state(pdev);
5194                 pci_save_state(pdev);
5195                 pci_wake_from_d3(pdev, false);
5196
5197                 /* Check for life */
5198                 reg = rd32(&pf->hw, GLGEN_RTRIG);
5199                 if (!reg)
5200                         result = PCI_ERS_RESULT_RECOVERED;
5201                 else
5202                         result = PCI_ERS_RESULT_DISCONNECT;
5203         }
5204
5205         err = pci_aer_clear_nonfatal_status(pdev);
5206         if (err)
5207                 dev_dbg(&pdev->dev, "pci_aer_clear_nonfatal_status() failed, error %d\n",
5208                         err);
5209                 /* non-fatal, continue */
5210
5211         return result;
5212 }
5213
5214 /**
5215  * ice_pci_err_resume - restart operations after PCI error recovery
5216  * @pdev: PCI device information struct
5217  *
5218  * Called to allow the driver to bring things back up after PCI error and/or
5219  * reset recovery have finished
5220  */
5221 static void ice_pci_err_resume(struct pci_dev *pdev)
5222 {
5223         struct ice_pf *pf = pci_get_drvdata(pdev);
5224
5225         if (!pf) {
5226                 dev_err(&pdev->dev, "%s failed, device is unrecoverable\n",
5227                         __func__);
5228                 return;
5229         }
5230
5231         if (test_bit(ICE_SUSPENDED, pf->state)) {
5232                 dev_dbg(&pdev->dev, "%s failed to resume normal operations!\n",
5233                         __func__);
5234                 return;
5235         }
5236
5237         ice_restore_all_vfs_msi_state(pdev);
5238
5239         ice_do_reset(pf, ICE_RESET_PFR);
5240         ice_service_task_restart(pf);
5241         mod_timer(&pf->serv_tmr, round_jiffies(jiffies + pf->serv_tmr_period));
5242 }
5243
5244 /**
5245  * ice_pci_err_reset_prepare - prepare device driver for PCI reset
5246  * @pdev: PCI device information struct
5247  */
5248 static void ice_pci_err_reset_prepare(struct pci_dev *pdev)
5249 {
5250         struct ice_pf *pf = pci_get_drvdata(pdev);
5251
5252         if (!test_bit(ICE_SUSPENDED, pf->state)) {
5253                 ice_service_task_stop(pf);
5254
5255                 if (!test_bit(ICE_PREPARED_FOR_RESET, pf->state)) {
5256                         set_bit(ICE_PFR_REQ, pf->state);
5257                         ice_prepare_for_reset(pf, ICE_RESET_PFR);
5258                 }
5259         }
5260 }
5261
5262 /**
5263  * ice_pci_err_reset_done - PCI reset done, device driver reset can begin
5264  * @pdev: PCI device information struct
5265  */
5266 static void ice_pci_err_reset_done(struct pci_dev *pdev)
5267 {
5268         ice_pci_err_resume(pdev);
5269 }
5270
5271 /* ice_pci_tbl - PCI Device ID Table
5272  *
5273  * Wildcard entries (PCI_ANY_ID) should come last
5274  * Last entry must be all 0s
5275  *
5276  * { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
5277  *   Class, Class Mask, private data (not used) }
5278  */
5279 static const struct pci_device_id ice_pci_tbl[] = {
5280         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810C_BACKPLANE), 0 },
5281         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810C_QSFP), 0 },
5282         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810C_SFP), 0 },
5283         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810_XXV_BACKPLANE), 0 },
5284         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810_XXV_QSFP), 0 },
5285         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810_XXV_SFP), 0 },
5286         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_BACKPLANE), 0 },
5287         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_QSFP), 0 },
5288         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_SFP), 0 },
5289         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_10G_BASE_T), 0 },
5290         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_SGMII), 0 },
5291         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_BACKPLANE), 0 },
5292         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_QSFP), 0 },
5293         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_SFP), 0 },
5294         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_10G_BASE_T), 0 },
5295         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_SGMII), 0 },
5296         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_BACKPLANE), 0 },
5297         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_SFP), 0 },
5298         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_10G_BASE_T), 0 },
5299         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_SGMII), 0 },
5300         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_BACKPLANE), 0 },
5301         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_SFP), 0 },
5302         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_10G_BASE_T), 0 },
5303         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_1GBE), 0 },
5304         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_QSFP), 0 },
5305         /* required last entry */
5306         { 0, }
5307 };
5308 MODULE_DEVICE_TABLE(pci, ice_pci_tbl);
5309
5310 static __maybe_unused SIMPLE_DEV_PM_OPS(ice_pm_ops, ice_suspend, ice_resume);
5311
5312 static const struct pci_error_handlers ice_pci_err_handler = {
5313         .error_detected = ice_pci_err_detected,
5314         .slot_reset = ice_pci_err_slot_reset,
5315         .reset_prepare = ice_pci_err_reset_prepare,
5316         .reset_done = ice_pci_err_reset_done,
5317         .resume = ice_pci_err_resume
5318 };
5319
5320 static struct pci_driver ice_driver = {
5321         .name = KBUILD_MODNAME,
5322         .id_table = ice_pci_tbl,
5323         .probe = ice_probe,
5324         .remove = ice_remove,
5325 #ifdef CONFIG_PM
5326         .driver.pm = &ice_pm_ops,
5327 #endif /* CONFIG_PM */
5328         .shutdown = ice_shutdown,
5329         .sriov_configure = ice_sriov_configure,
5330         .err_handler = &ice_pci_err_handler
5331 };
5332
5333 /**
5334  * ice_module_init - Driver registration routine
5335  *
5336  * ice_module_init is the first routine called when the driver is
5337  * loaded. All it does is register with the PCI subsystem.
5338  */
5339 static int __init ice_module_init(void)
5340 {
5341         int status;
5342
5343         pr_info("%s\n", ice_driver_string);
5344         pr_info("%s\n", ice_copyright);
5345
5346         ice_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, KBUILD_MODNAME);
5347         if (!ice_wq) {
5348                 pr_err("Failed to create workqueue\n");
5349                 return -ENOMEM;
5350         }
5351
5352         status = pci_register_driver(&ice_driver);
5353         if (status) {
5354                 pr_err("failed to register PCI driver, err %d\n", status);
5355                 destroy_workqueue(ice_wq);
5356         }
5357
5358         return status;
5359 }
5360 module_init(ice_module_init);
5361
5362 /**
5363  * ice_module_exit - Driver exit cleanup routine
5364  *
5365  * ice_module_exit is called just before the driver is removed
5366  * from memory.
5367  */
5368 static void __exit ice_module_exit(void)
5369 {
5370         pci_unregister_driver(&ice_driver);
5371         destroy_workqueue(ice_wq);
5372         pr_info("module unloaded\n");
5373 }
5374 module_exit(ice_module_exit);
5375
5376 /**
5377  * ice_set_mac_address - NDO callback to set MAC address
5378  * @netdev: network interface device structure
5379  * @pi: pointer to an address structure
5380  *
5381  * Returns 0 on success, negative on failure
5382  */
5383 static int ice_set_mac_address(struct net_device *netdev, void *pi)
5384 {
5385         struct ice_netdev_priv *np = netdev_priv(netdev);
5386         struct ice_vsi *vsi = np->vsi;
5387         struct ice_pf *pf = vsi->back;
5388         struct ice_hw *hw = &pf->hw;
5389         struct sockaddr *addr = pi;
5390         enum ice_status status;
5391         u8 old_mac[ETH_ALEN];
5392         u8 flags = 0;
5393         int err = 0;
5394         u8 *mac;
5395
5396         mac = (u8 *)addr->sa_data;
5397
5398         if (!is_valid_ether_addr(mac))
5399                 return -EADDRNOTAVAIL;
5400
5401         if (ether_addr_equal(netdev->dev_addr, mac)) {
5402                 netdev_dbg(netdev, "already using mac %pM\n", mac);
5403                 return 0;
5404         }
5405
5406         if (test_bit(ICE_DOWN, pf->state) ||
5407             ice_is_reset_in_progress(pf->state)) {
5408                 netdev_err(netdev, "can't set mac %pM. device not ready\n",
5409                            mac);
5410                 return -EBUSY;
5411         }
5412
5413         if (ice_chnl_dmac_fltr_cnt(pf)) {
5414                 netdev_err(netdev, "can't set mac %pM. Device has tc-flower filters, delete all of them and try again\n",
5415                            mac);
5416                 return -EAGAIN;
5417         }
5418
5419         netif_addr_lock_bh(netdev);
5420         ether_addr_copy(old_mac, netdev->dev_addr);
5421         /* change the netdev's MAC address */
5422         eth_hw_addr_set(netdev, mac);
5423         netif_addr_unlock_bh(netdev);
5424
5425         /* Clean up old MAC filter. Not an error if old filter doesn't exist */
5426         status = ice_fltr_remove_mac(vsi, old_mac, ICE_FWD_TO_VSI);
5427         if (status && status != ICE_ERR_DOES_NOT_EXIST) {
5428                 err = -EADDRNOTAVAIL;
5429                 goto err_update_filters;
5430         }
5431
5432         /* Add filter for new MAC. If filter exists, return success */
5433         status = ice_fltr_add_mac(vsi, mac, ICE_FWD_TO_VSI);
5434         if (status == ICE_ERR_ALREADY_EXISTS)
5435                 /* Although this MAC filter is already present in hardware it's
5436                  * possible in some cases (e.g. bonding) that dev_addr was
5437                  * modified outside of the driver and needs to be restored back
5438                  * to this value.
5439                  */
5440                 netdev_dbg(netdev, "filter for MAC %pM already exists\n", mac);
5441         else if (status)
5442                 /* error if the new filter addition failed */
5443                 err = -EADDRNOTAVAIL;
5444
5445 err_update_filters:
5446         if (err) {
5447                 netdev_err(netdev, "can't set MAC %pM. filter update failed\n",
5448                            mac);
5449                 netif_addr_lock_bh(netdev);
5450                 eth_hw_addr_set(netdev, old_mac);
5451                 netif_addr_unlock_bh(netdev);
5452                 return err;
5453         }
5454
5455         netdev_dbg(vsi->netdev, "updated MAC address to %pM\n",
5456                    netdev->dev_addr);
5457
5458         /* write new MAC address to the firmware */
5459         flags = ICE_AQC_MAN_MAC_UPDATE_LAA_WOL;
5460         status = ice_aq_manage_mac_write(hw, mac, flags, NULL);
5461         if (status) {
5462                 netdev_err(netdev, "can't set MAC %pM. write to firmware failed error %s\n",
5463                            mac, ice_stat_str(status));
5464         }
5465         return 0;
5466 }
5467
5468 /**
5469  * ice_set_rx_mode - NDO callback to set the netdev filters
5470  * @netdev: network interface device structure
5471  */
5472 static void ice_set_rx_mode(struct net_device *netdev)
5473 {
5474         struct ice_netdev_priv *np = netdev_priv(netdev);
5475         struct ice_vsi *vsi = np->vsi;
5476
5477         if (!vsi)
5478                 return;
5479
5480         /* Set the flags to synchronize filters
5481          * ndo_set_rx_mode may be triggered even without a change in netdev
5482          * flags
5483          */
5484         set_bit(ICE_VSI_UMAC_FLTR_CHANGED, vsi->state);
5485         set_bit(ICE_VSI_MMAC_FLTR_CHANGED, vsi->state);
5486         set_bit(ICE_FLAG_FLTR_SYNC, vsi->back->flags);
5487
5488         /* schedule our worker thread which will take care of
5489          * applying the new filter changes
5490          */
5491         ice_service_task_schedule(vsi->back);
5492 }
5493
5494 /**
5495  * ice_set_tx_maxrate - NDO callback to set the maximum per-queue bitrate
5496  * @netdev: network interface device structure
5497  * @queue_index: Queue ID
5498  * @maxrate: maximum bandwidth in Mbps
5499  */
5500 static int
5501 ice_set_tx_maxrate(struct net_device *netdev, int queue_index, u32 maxrate)
5502 {
5503         struct ice_netdev_priv *np = netdev_priv(netdev);
5504         struct ice_vsi *vsi = np->vsi;
5505         enum ice_status status;
5506         u16 q_handle;
5507         u8 tc;
5508
5509         /* Validate maxrate requested is within permitted range */
5510         if (maxrate && (maxrate > (ICE_SCHED_MAX_BW / 1000))) {
5511                 netdev_err(netdev, "Invalid max rate %d specified for the queue %d\n",
5512                            maxrate, queue_index);
5513                 return -EINVAL;
5514         }
5515
5516         q_handle = vsi->tx_rings[queue_index]->q_handle;
5517         tc = ice_dcb_get_tc(vsi, queue_index);
5518
5519         /* Set BW back to default, when user set maxrate to 0 */
5520         if (!maxrate)
5521                 status = ice_cfg_q_bw_dflt_lmt(vsi->port_info, vsi->idx, tc,
5522                                                q_handle, ICE_MAX_BW);
5523         else
5524                 status = ice_cfg_q_bw_lmt(vsi->port_info, vsi->idx, tc,
5525                                           q_handle, ICE_MAX_BW, maxrate * 1000);
5526         if (status) {
5527                 netdev_err(netdev, "Unable to set Tx max rate, error %s\n",
5528                            ice_stat_str(status));
5529                 return -EIO;
5530         }
5531
5532         return 0;
5533 }
5534
5535 /**
5536  * ice_fdb_add - add an entry to the hardware database
5537  * @ndm: the input from the stack
5538  * @tb: pointer to array of nladdr (unused)
5539  * @dev: the net device pointer
5540  * @addr: the MAC address entry being added
5541  * @vid: VLAN ID
5542  * @flags: instructions from stack about fdb operation
5543  * @extack: netlink extended ack
5544  */
5545 static int
5546 ice_fdb_add(struct ndmsg *ndm, struct nlattr __always_unused *tb[],
5547             struct net_device *dev, const unsigned char *addr, u16 vid,
5548             u16 flags, struct netlink_ext_ack __always_unused *extack)
5549 {
5550         int err;
5551
5552         if (vid) {
5553                 netdev_err(dev, "VLANs aren't supported yet for dev_uc|mc_add()\n");
5554                 return -EINVAL;
5555         }
5556         if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
5557                 netdev_err(dev, "FDB only supports static addresses\n");
5558                 return -EINVAL;
5559         }
5560
5561         if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
5562                 err = dev_uc_add_excl(dev, addr);
5563         else if (is_multicast_ether_addr(addr))
5564                 err = dev_mc_add_excl(dev, addr);
5565         else
5566                 err = -EINVAL;
5567
5568         /* Only return duplicate errors if NLM_F_EXCL is set */
5569         if (err == -EEXIST && !(flags & NLM_F_EXCL))
5570                 err = 0;
5571
5572         return err;
5573 }
5574
5575 /**
5576  * ice_fdb_del - delete an entry from the hardware database
5577  * @ndm: the input from the stack
5578  * @tb: pointer to array of nladdr (unused)
5579  * @dev: the net device pointer
5580  * @addr: the MAC address entry being added
5581  * @vid: VLAN ID
5582  */
5583 static int
5584 ice_fdb_del(struct ndmsg *ndm, __always_unused struct nlattr *tb[],
5585             struct net_device *dev, const unsigned char *addr,
5586             __always_unused u16 vid)
5587 {
5588         int err;
5589
5590         if (ndm->ndm_state & NUD_PERMANENT) {
5591                 netdev_err(dev, "FDB only supports static addresses\n");
5592                 return -EINVAL;
5593         }
5594
5595         if (is_unicast_ether_addr(addr))
5596                 err = dev_uc_del(dev, addr);
5597         else if (is_multicast_ether_addr(addr))
5598                 err = dev_mc_del(dev, addr);
5599         else
5600                 err = -EINVAL;
5601
5602         return err;
5603 }
5604
5605 /**
5606  * ice_set_features - set the netdev feature flags
5607  * @netdev: ptr to the netdev being adjusted
5608  * @features: the feature set that the stack is suggesting
5609  */
5610 static int
5611 ice_set_features(struct net_device *netdev, netdev_features_t features)
5612 {
5613         struct ice_netdev_priv *np = netdev_priv(netdev);
5614         struct ice_vsi *vsi = np->vsi;
5615         struct ice_pf *pf = vsi->back;
5616         int ret = 0;
5617
5618         /* Don't set any netdev advanced features with device in Safe Mode */
5619         if (ice_is_safe_mode(vsi->back)) {
5620                 dev_err(ice_pf_to_dev(vsi->back), "Device is in Safe Mode - not enabling advanced netdev features\n");
5621                 return ret;
5622         }
5623
5624         /* Do not change setting during reset */
5625         if (ice_is_reset_in_progress(pf->state)) {
5626                 dev_err(ice_pf_to_dev(vsi->back), "Device is resetting, changing advanced netdev features temporarily unavailable.\n");
5627                 return -EBUSY;
5628         }
5629
5630         /* Multiple features can be changed in one call so keep features in
5631          * separate if/else statements to guarantee each feature is checked
5632          */
5633         if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
5634                 ice_vsi_manage_rss_lut(vsi, true);
5635         else if (!(features & NETIF_F_RXHASH) &&
5636                  netdev->features & NETIF_F_RXHASH)
5637                 ice_vsi_manage_rss_lut(vsi, false);
5638
5639         if ((features & NETIF_F_HW_VLAN_CTAG_RX) &&
5640             !(netdev->features & NETIF_F_HW_VLAN_CTAG_RX))
5641                 ret = ice_vsi_manage_vlan_stripping(vsi, true);
5642         else if (!(features & NETIF_F_HW_VLAN_CTAG_RX) &&
5643                  (netdev->features & NETIF_F_HW_VLAN_CTAG_RX))
5644                 ret = ice_vsi_manage_vlan_stripping(vsi, false);
5645
5646         if ((features & NETIF_F_HW_VLAN_CTAG_TX) &&
5647             !(netdev->features & NETIF_F_HW_VLAN_CTAG_TX))
5648                 ret = ice_vsi_manage_vlan_insertion(vsi);
5649         else if (!(features & NETIF_F_HW_VLAN_CTAG_TX) &&
5650                  (netdev->features & NETIF_F_HW_VLAN_CTAG_TX))
5651                 ret = ice_vsi_manage_vlan_insertion(vsi);
5652
5653         if ((features & NETIF_F_HW_VLAN_CTAG_FILTER) &&
5654             !(netdev->features & NETIF_F_HW_VLAN_CTAG_FILTER))
5655                 ret = ice_cfg_vlan_pruning(vsi, true);
5656         else if (!(features & NETIF_F_HW_VLAN_CTAG_FILTER) &&
5657                  (netdev->features & NETIF_F_HW_VLAN_CTAG_FILTER))
5658                 ret = ice_cfg_vlan_pruning(vsi, false);
5659
5660         if ((features & NETIF_F_NTUPLE) &&
5661             !(netdev->features & NETIF_F_NTUPLE)) {
5662                 ice_vsi_manage_fdir(vsi, true);
5663                 ice_init_arfs(vsi);
5664         } else if (!(features & NETIF_F_NTUPLE) &&
5665                  (netdev->features & NETIF_F_NTUPLE)) {
5666                 ice_vsi_manage_fdir(vsi, false);
5667                 ice_clear_arfs(vsi);
5668         }
5669
5670         /* don't turn off hw_tc_offload when ADQ is already enabled */
5671         if (!(features & NETIF_F_HW_TC) && ice_is_adq_active(pf)) {
5672                 dev_err(ice_pf_to_dev(pf), "ADQ is active, can't turn hw_tc_offload off\n");
5673                 return -EACCES;
5674         }
5675
5676         if ((features & NETIF_F_HW_TC) &&
5677             !(netdev->features & NETIF_F_HW_TC))
5678                 set_bit(ICE_FLAG_CLS_FLOWER, pf->flags);
5679         else
5680                 clear_bit(ICE_FLAG_CLS_FLOWER, pf->flags);
5681
5682         return ret;
5683 }
5684
5685 /**
5686  * ice_vsi_vlan_setup - Setup VLAN offload properties on a VSI
5687  * @vsi: VSI to setup VLAN properties for
5688  */
5689 static int ice_vsi_vlan_setup(struct ice_vsi *vsi)
5690 {
5691         int ret = 0;
5692
5693         if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
5694                 ret = ice_vsi_manage_vlan_stripping(vsi, true);
5695         if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_TX)
5696                 ret = ice_vsi_manage_vlan_insertion(vsi);
5697
5698         return ret;
5699 }
5700
5701 /**
5702  * ice_vsi_cfg - Setup the VSI
5703  * @vsi: the VSI being configured
5704  *
5705  * Return 0 on success and negative value on error
5706  */
5707 int ice_vsi_cfg(struct ice_vsi *vsi)
5708 {
5709         int err;
5710
5711         if (vsi->netdev) {
5712                 ice_set_rx_mode(vsi->netdev);
5713
5714                 err = ice_vsi_vlan_setup(vsi);
5715
5716                 if (err)
5717                         return err;
5718         }
5719         ice_vsi_cfg_dcb_rings(vsi);
5720
5721         err = ice_vsi_cfg_lan_txqs(vsi);
5722         if (!err && ice_is_xdp_ena_vsi(vsi))
5723                 err = ice_vsi_cfg_xdp_txqs(vsi);
5724         if (!err)
5725                 err = ice_vsi_cfg_rxqs(vsi);
5726
5727         return err;
5728 }
5729
5730 /* THEORY OF MODERATION:
5731  * The ice driver hardware works differently than the hardware that DIMLIB was
5732  * originally made for. ice hardware doesn't have packet count limits that
5733  * can trigger an interrupt, but it *does* have interrupt rate limit support,
5734  * which is hard-coded to a limit of 250,000 ints/second.
5735  * If not using dynamic moderation, the INTRL value can be modified
5736  * by ethtool rx-usecs-high.
5737  */
5738 struct ice_dim {
5739         /* the throttle rate for interrupts, basically worst case delay before
5740          * an initial interrupt fires, value is stored in microseconds.
5741          */
5742         u16 itr;
5743 };
5744
5745 /* Make a different profile for Rx that doesn't allow quite so aggressive
5746  * moderation at the high end (it maxes out at 126us or about 8k interrupts a
5747  * second.
5748  */
5749 static const struct ice_dim rx_profile[] = {
5750         {2},    /* 500,000 ints/s, capped at 250K by INTRL */
5751         {8},    /* 125,000 ints/s */
5752         {16},   /*  62,500 ints/s */
5753         {62},   /*  16,129 ints/s */
5754         {126}   /*   7,936 ints/s */
5755 };
5756
5757 /* The transmit profile, which has the same sorts of values
5758  * as the previous struct
5759  */
5760 static const struct ice_dim tx_profile[] = {
5761         {2},    /* 500,000 ints/s, capped at 250K by INTRL */
5762         {8},    /* 125,000 ints/s */
5763         {40},   /*  16,125 ints/s */
5764         {128},  /*   7,812 ints/s */
5765         {256}   /*   3,906 ints/s */
5766 };
5767
5768 static void ice_tx_dim_work(struct work_struct *work)
5769 {
5770         struct ice_ring_container *rc;
5771         struct dim *dim;
5772         u16 itr;
5773
5774         dim = container_of(work, struct dim, work);
5775         rc = (struct ice_ring_container *)dim->priv;
5776
5777         WARN_ON(dim->profile_ix >= ARRAY_SIZE(tx_profile));
5778
5779         /* look up the values in our local table */
5780         itr = tx_profile[dim->profile_ix].itr;
5781
5782         ice_trace(tx_dim_work, container_of(rc, struct ice_q_vector, tx), dim);
5783         ice_write_itr(rc, itr);
5784
5785         dim->state = DIM_START_MEASURE;
5786 }
5787
5788 static void ice_rx_dim_work(struct work_struct *work)
5789 {
5790         struct ice_ring_container *rc;
5791         struct dim *dim;
5792         u16 itr;
5793
5794         dim = container_of(work, struct dim, work);
5795         rc = (struct ice_ring_container *)dim->priv;
5796
5797         WARN_ON(dim->profile_ix >= ARRAY_SIZE(rx_profile));
5798
5799         /* look up the values in our local table */
5800         itr = rx_profile[dim->profile_ix].itr;
5801
5802         ice_trace(rx_dim_work, container_of(rc, struct ice_q_vector, rx), dim);
5803         ice_write_itr(rc, itr);
5804
5805         dim->state = DIM_START_MEASURE;
5806 }
5807
5808 #define ICE_DIM_DEFAULT_PROFILE_IX 1
5809
5810 /**
5811  * ice_init_moderation - set up interrupt moderation
5812  * @q_vector: the vector containing rings to be configured
5813  *
5814  * Set up interrupt moderation registers, with the intent to do the right thing
5815  * when called from reset or from probe, and whether or not dynamic moderation
5816  * is enabled or not. Take special care to write all the registers in both
5817  * dynamic moderation mode or not in order to make sure hardware is in a known
5818  * state.
5819  */
5820 static void ice_init_moderation(struct ice_q_vector *q_vector)
5821 {
5822         struct ice_ring_container *rc;
5823         bool tx_dynamic, rx_dynamic;
5824
5825         rc = &q_vector->tx;
5826         INIT_WORK(&rc->dim.work, ice_tx_dim_work);
5827         rc->dim.mode = DIM_CQ_PERIOD_MODE_START_FROM_EQE;
5828         rc->dim.profile_ix = ICE_DIM_DEFAULT_PROFILE_IX;
5829         rc->dim.priv = rc;
5830         tx_dynamic = ITR_IS_DYNAMIC(rc);
5831
5832         /* set the initial TX ITR to match the above */
5833         ice_write_itr(rc, tx_dynamic ?
5834                       tx_profile[rc->dim.profile_ix].itr : rc->itr_setting);
5835
5836         rc = &q_vector->rx;
5837         INIT_WORK(&rc->dim.work, ice_rx_dim_work);
5838         rc->dim.mode = DIM_CQ_PERIOD_MODE_START_FROM_EQE;
5839         rc->dim.profile_ix = ICE_DIM_DEFAULT_PROFILE_IX;
5840         rc->dim.priv = rc;
5841         rx_dynamic = ITR_IS_DYNAMIC(rc);
5842
5843         /* set the initial RX ITR to match the above */
5844         ice_write_itr(rc, rx_dynamic ? rx_profile[rc->dim.profile_ix].itr :
5845                                        rc->itr_setting);
5846
5847         ice_set_q_vector_intrl(q_vector);
5848 }
5849
5850 /**
5851  * ice_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5852  * @vsi: the VSI being configured
5853  */
5854 static void ice_napi_enable_all(struct ice_vsi *vsi)
5855 {
5856         int q_idx;
5857
5858         if (!vsi->netdev)
5859                 return;
5860
5861         ice_for_each_q_vector(vsi, q_idx) {
5862                 struct ice_q_vector *q_vector = vsi->q_vectors[q_idx];
5863
5864                 ice_init_moderation(q_vector);
5865
5866                 if (q_vector->rx.rx_ring || q_vector->tx.tx_ring)
5867                         napi_enable(&q_vector->napi);
5868         }
5869 }
5870
5871 /**
5872  * ice_up_complete - Finish the last steps of bringing up a connection
5873  * @vsi: The VSI being configured
5874  *
5875  * Return 0 on success and negative value on error
5876  */
5877 static int ice_up_complete(struct ice_vsi *vsi)
5878 {
5879         struct ice_pf *pf = vsi->back;
5880         int err;
5881
5882         ice_vsi_cfg_msix(vsi);
5883
5884         /* Enable only Rx rings, Tx rings were enabled by the FW when the
5885          * Tx queue group list was configured and the context bits were
5886          * programmed using ice_vsi_cfg_txqs
5887          */
5888         err = ice_vsi_start_all_rx_rings(vsi);
5889         if (err)
5890                 return err;
5891
5892         clear_bit(ICE_VSI_DOWN, vsi->state);
5893         ice_napi_enable_all(vsi);
5894         ice_vsi_ena_irq(vsi);
5895
5896         if (vsi->port_info &&
5897             (vsi->port_info->phy.link_info.link_info & ICE_AQ_LINK_UP) &&
5898             vsi->netdev) {
5899                 ice_print_link_msg(vsi, true);
5900                 netif_tx_start_all_queues(vsi->netdev);
5901                 netif_carrier_on(vsi->netdev);
5902         }
5903
5904         /* clear this now, and the first stats read will be used as baseline */
5905         vsi->stat_offsets_loaded = false;
5906
5907         ice_service_task_schedule(pf);
5908
5909         return 0;
5910 }
5911
5912 /**
5913  * ice_up - Bring the connection back up after being down
5914  * @vsi: VSI being configured
5915  */
5916 int ice_up(struct ice_vsi *vsi)
5917 {
5918         int err;
5919
5920         err = ice_vsi_cfg(vsi);
5921         if (!err)
5922                 err = ice_up_complete(vsi);
5923
5924         return err;
5925 }
5926
5927 /**
5928  * ice_fetch_u64_stats_per_ring - get packets and bytes stats per ring
5929  * @syncp: pointer to u64_stats_sync
5930  * @stats: stats that pkts and bytes count will be taken from
5931  * @pkts: packets stats counter
5932  * @bytes: bytes stats counter
5933  *
5934  * This function fetches stats from the ring considering the atomic operations
5935  * that needs to be performed to read u64 values in 32 bit machine.
5936  */
5937 static void
5938 ice_fetch_u64_stats_per_ring(struct u64_stats_sync *syncp, struct ice_q_stats stats,
5939                              u64 *pkts, u64 *bytes)
5940 {
5941         unsigned int start;
5942
5943         do {
5944                 start = u64_stats_fetch_begin_irq(syncp);
5945                 *pkts = stats.pkts;
5946                 *bytes = stats.bytes;
5947         } while (u64_stats_fetch_retry_irq(syncp, start));
5948 }
5949
5950 /**
5951  * ice_update_vsi_tx_ring_stats - Update VSI Tx ring stats counters
5952  * @vsi: the VSI to be updated
5953  * @vsi_stats: the stats struct to be updated
5954  * @rings: rings to work on
5955  * @count: number of rings
5956  */
5957 static void
5958 ice_update_vsi_tx_ring_stats(struct ice_vsi *vsi,
5959                              struct rtnl_link_stats64 *vsi_stats,
5960                              struct ice_tx_ring **rings, u16 count)
5961 {
5962         u16 i;
5963
5964         for (i = 0; i < count; i++) {
5965                 struct ice_tx_ring *ring;
5966                 u64 pkts = 0, bytes = 0;
5967
5968                 ring = READ_ONCE(rings[i]);
5969                 if (ring)
5970                         ice_fetch_u64_stats_per_ring(&ring->syncp, ring->stats, &pkts, &bytes);
5971                 vsi_stats->tx_packets += pkts;
5972                 vsi_stats->tx_bytes += bytes;
5973                 vsi->tx_restart += ring->tx_stats.restart_q;
5974                 vsi->tx_busy += ring->tx_stats.tx_busy;
5975                 vsi->tx_linearize += ring->tx_stats.tx_linearize;
5976         }
5977 }
5978
5979 /**
5980  * ice_update_vsi_ring_stats - Update VSI stats counters
5981  * @vsi: the VSI to be updated
5982  */
5983 static void ice_update_vsi_ring_stats(struct ice_vsi *vsi)
5984 {
5985         struct rtnl_link_stats64 *vsi_stats;
5986         u64 pkts, bytes;
5987         int i;
5988
5989         vsi_stats = kzalloc(sizeof(*vsi_stats), GFP_ATOMIC);
5990         if (!vsi_stats)
5991                 return;
5992
5993         /* reset non-netdev (extended) stats */
5994         vsi->tx_restart = 0;
5995         vsi->tx_busy = 0;
5996         vsi->tx_linearize = 0;
5997         vsi->rx_buf_failed = 0;
5998         vsi->rx_page_failed = 0;
5999
6000         rcu_read_lock();
6001
6002         /* update Tx rings counters */
6003         ice_update_vsi_tx_ring_stats(vsi, vsi_stats, vsi->tx_rings,
6004                                      vsi->num_txq);
6005
6006         /* update Rx rings counters */
6007         ice_for_each_rxq(vsi, i) {
6008                 struct ice_rx_ring *ring = READ_ONCE(vsi->rx_rings[i]);
6009
6010                 ice_fetch_u64_stats_per_ring(&ring->syncp, ring->stats, &pkts, &bytes);
6011                 vsi_stats->rx_packets += pkts;
6012                 vsi_stats->rx_bytes += bytes;
6013                 vsi->rx_buf_failed += ring->rx_stats.alloc_buf_failed;
6014                 vsi->rx_page_failed += ring->rx_stats.alloc_page_failed;
6015         }
6016
6017         /* update XDP Tx rings counters */
6018         if (ice_is_xdp_ena_vsi(vsi))
6019                 ice_update_vsi_tx_ring_stats(vsi, vsi_stats, vsi->xdp_rings,
6020                                              vsi->num_xdp_txq);
6021
6022         rcu_read_unlock();
6023
6024         vsi->net_stats.tx_packets = vsi_stats->tx_packets;
6025         vsi->net_stats.tx_bytes = vsi_stats->tx_bytes;
6026         vsi->net_stats.rx_packets = vsi_stats->rx_packets;
6027         vsi->net_stats.rx_bytes = vsi_stats->rx_bytes;
6028
6029         kfree(vsi_stats);
6030 }
6031
6032 /**
6033  * ice_update_vsi_stats - Update VSI stats counters
6034  * @vsi: the VSI to be updated
6035  */
6036 void ice_update_vsi_stats(struct ice_vsi *vsi)
6037 {
6038         struct rtnl_link_stats64 *cur_ns = &vsi->net_stats;
6039         struct ice_eth_stats *cur_es = &vsi->eth_stats;
6040         struct ice_pf *pf = vsi->back;
6041
6042         if (test_bit(ICE_VSI_DOWN, vsi->state) ||
6043             test_bit(ICE_CFG_BUSY, pf->state))
6044                 return;
6045
6046         /* get stats as recorded by Tx/Rx rings */
6047         ice_update_vsi_ring_stats(vsi);
6048
6049         /* get VSI stats as recorded by the hardware */
6050         ice_update_eth_stats(vsi);
6051
6052         cur_ns->tx_errors = cur_es->tx_errors;
6053         cur_ns->rx_dropped = cur_es->rx_discards;
6054         cur_ns->tx_dropped = cur_es->tx_discards;
6055         cur_ns->multicast = cur_es->rx_multicast;
6056
6057         /* update some more netdev stats if this is main VSI */
6058         if (vsi->type == ICE_VSI_PF) {
6059                 cur_ns->rx_crc_errors = pf->stats.crc_errors;
6060                 cur_ns->rx_errors = pf->stats.crc_errors +
6061                                     pf->stats.illegal_bytes +
6062                                     pf->stats.rx_len_errors +
6063                                     pf->stats.rx_undersize +
6064                                     pf->hw_csum_rx_error +
6065                                     pf->stats.rx_jabber +
6066                                     pf->stats.rx_fragments +
6067                                     pf->stats.rx_oversize;
6068                 cur_ns->rx_length_errors = pf->stats.rx_len_errors;
6069                 /* record drops from the port level */
6070                 cur_ns->rx_missed_errors = pf->stats.eth.rx_discards;
6071         }
6072 }
6073
6074 /**
6075  * ice_update_pf_stats - Update PF port stats counters
6076  * @pf: PF whose stats needs to be updated
6077  */
6078 void ice_update_pf_stats(struct ice_pf *pf)
6079 {
6080         struct ice_hw_port_stats *prev_ps, *cur_ps;
6081         struct ice_hw *hw = &pf->hw;
6082         u16 fd_ctr_base;
6083         u8 port;
6084
6085         port = hw->port_info->lport;
6086         prev_ps = &pf->stats_prev;
6087         cur_ps = &pf->stats;
6088
6089         ice_stat_update40(hw, GLPRT_GORCL(port), pf->stat_prev_loaded,
6090                           &prev_ps->eth.rx_bytes,
6091                           &cur_ps->eth.rx_bytes);
6092
6093         ice_stat_update40(hw, GLPRT_UPRCL(port), pf->stat_prev_loaded,
6094                           &prev_ps->eth.rx_unicast,
6095                           &cur_ps->eth.rx_unicast);
6096
6097         ice_stat_update40(hw, GLPRT_MPRCL(port), pf->stat_prev_loaded,
6098                           &prev_ps->eth.rx_multicast,
6099                           &cur_ps->eth.rx_multicast);
6100
6101         ice_stat_update40(hw, GLPRT_BPRCL(port), pf->stat_prev_loaded,
6102                           &prev_ps->eth.rx_broadcast,
6103                           &cur_ps->eth.rx_broadcast);
6104
6105         ice_stat_update32(hw, PRTRPB_RDPC, pf->stat_prev_loaded,
6106                           &prev_ps->eth.rx_discards,
6107                           &cur_ps->eth.rx_discards);
6108
6109         ice_stat_update40(hw, GLPRT_GOTCL(port), pf->stat_prev_loaded,
6110                           &prev_ps->eth.tx_bytes,
6111                           &cur_ps->eth.tx_bytes);
6112
6113         ice_stat_update40(hw, GLPRT_UPTCL(port), pf->stat_prev_loaded,
6114                           &prev_ps->eth.tx_unicast,
6115                           &cur_ps->eth.tx_unicast);
6116
6117         ice_stat_update40(hw, GLPRT_MPTCL(port), pf->stat_prev_loaded,
6118                           &prev_ps->eth.tx_multicast,
6119                           &cur_ps->eth.tx_multicast);
6120
6121         ice_stat_update40(hw, GLPRT_BPTCL(port), pf->stat_prev_loaded,
6122                           &prev_ps->eth.tx_broadcast,
6123                           &cur_ps->eth.tx_broadcast);
6124
6125         ice_stat_update32(hw, GLPRT_TDOLD(port), pf->stat_prev_loaded,
6126                           &prev_ps->tx_dropped_link_down,
6127                           &cur_ps->tx_dropped_link_down);
6128
6129         ice_stat_update40(hw, GLPRT_PRC64L(port), pf->stat_prev_loaded,
6130                           &prev_ps->rx_size_64, &cur_ps->rx_size_64);
6131
6132         ice_stat_update40(hw, GLPRT_PRC127L(port), pf->stat_prev_loaded,
6133                           &prev_ps->rx_size_127, &cur_ps->rx_size_127);
6134
6135         ice_stat_update40(hw, GLPRT_PRC255L(port), pf->stat_prev_loaded,
6136                           &prev_ps->rx_size_255, &cur_ps->rx_size_255);
6137
6138         ice_stat_update40(hw, GLPRT_PRC511L(port), pf->stat_prev_loaded,
6139                           &prev_ps->rx_size_511, &cur_ps->rx_size_511);
6140
6141         ice_stat_update40(hw, GLPRT_PRC1023L(port), pf->stat_prev_loaded,
6142                           &prev_ps->rx_size_1023, &cur_ps->rx_size_1023);
6143
6144         ice_stat_update40(hw, GLPRT_PRC1522L(port), pf->stat_prev_loaded,
6145                           &prev_ps->rx_size_1522, &cur_ps->rx_size_1522);
6146
6147         ice_stat_update40(hw, GLPRT_PRC9522L(port), pf->stat_prev_loaded,
6148                           &prev_ps->rx_size_big, &cur_ps->rx_size_big);
6149
6150         ice_stat_update40(hw, GLPRT_PTC64L(port), pf->stat_prev_loaded,
6151                           &prev_ps->tx_size_64, &cur_ps->tx_size_64);
6152
6153         ice_stat_update40(hw, GLPRT_PTC127L(port), pf->stat_prev_loaded,
6154                           &prev_ps->tx_size_127, &cur_ps->tx_size_127);
6155
6156         ice_stat_update40(hw, GLPRT_PTC255L(port), pf->stat_prev_loaded,
6157                           &prev_ps->tx_size_255, &cur_ps->tx_size_255);
6158
6159         ice_stat_update40(hw, GLPRT_PTC511L(port), pf->stat_prev_loaded,
6160                           &prev_ps->tx_size_511, &cur_ps->tx_size_511);
6161
6162         ice_stat_update40(hw, GLPRT_PTC1023L(port), pf->stat_prev_loaded,
6163                           &prev_ps->tx_size_1023, &cur_ps->tx_size_1023);
6164
6165         ice_stat_update40(hw, GLPRT_PTC1522L(port), pf->stat_prev_loaded,
6166                           &prev_ps->tx_size_1522, &cur_ps->tx_size_1522);
6167
6168         ice_stat_update40(hw, GLPRT_PTC9522L(port), pf->stat_prev_loaded,
6169                           &prev_ps->tx_size_big, &cur_ps->tx_size_big);
6170
6171         fd_ctr_base = hw->fd_ctr_base;
6172
6173         ice_stat_update40(hw,
6174                           GLSTAT_FD_CNT0L(ICE_FD_SB_STAT_IDX(fd_ctr_base)),
6175                           pf->stat_prev_loaded, &prev_ps->fd_sb_match,
6176                           &cur_ps->fd_sb_match);
6177         ice_stat_update32(hw, GLPRT_LXONRXC(port), pf->stat_prev_loaded,
6178                           &prev_ps->link_xon_rx, &cur_ps->link_xon_rx);
6179
6180         ice_stat_update32(hw, GLPRT_LXOFFRXC(port), pf->stat_prev_loaded,
6181                           &prev_ps->link_xoff_rx, &cur_ps->link_xoff_rx);
6182
6183         ice_stat_update32(hw, GLPRT_LXONTXC(port), pf->stat_prev_loaded,
6184                           &prev_ps->link_xon_tx, &cur_ps->link_xon_tx);
6185
6186         ice_stat_update32(hw, GLPRT_LXOFFTXC(port), pf->stat_prev_loaded,
6187                           &prev_ps->link_xoff_tx, &cur_ps->link_xoff_tx);
6188
6189         ice_update_dcb_stats(pf);
6190
6191         ice_stat_update32(hw, GLPRT_CRCERRS(port), pf->stat_prev_loaded,
6192                           &prev_ps->crc_errors, &cur_ps->crc_errors);
6193
6194         ice_stat_update32(hw, GLPRT_ILLERRC(port), pf->stat_prev_loaded,
6195                           &prev_ps->illegal_bytes, &cur_ps->illegal_bytes);
6196
6197         ice_stat_update32(hw, GLPRT_MLFC(port), pf->stat_prev_loaded,
6198                           &prev_ps->mac_local_faults,
6199                           &cur_ps->mac_local_faults);
6200
6201         ice_stat_update32(hw, GLPRT_MRFC(port), pf->stat_prev_loaded,
6202                           &prev_ps->mac_remote_faults,
6203                           &cur_ps->mac_remote_faults);
6204
6205         ice_stat_update32(hw, GLPRT_RLEC(port), pf->stat_prev_loaded,
6206                           &prev_ps->rx_len_errors, &cur_ps->rx_len_errors);
6207
6208         ice_stat_update32(hw, GLPRT_RUC(port), pf->stat_prev_loaded,
6209                           &prev_ps->rx_undersize, &cur_ps->rx_undersize);
6210
6211         ice_stat_update32(hw, GLPRT_RFC(port), pf->stat_prev_loaded,
6212                           &prev_ps->rx_fragments, &cur_ps->rx_fragments);
6213
6214         ice_stat_update32(hw, GLPRT_ROC(port), pf->stat_prev_loaded,
6215                           &prev_ps->rx_oversize, &cur_ps->rx_oversize);
6216
6217         ice_stat_update32(hw, GLPRT_RJC(port), pf->stat_prev_loaded,
6218                           &prev_ps->rx_jabber, &cur_ps->rx_jabber);
6219
6220         cur_ps->fd_sb_status = test_bit(ICE_FLAG_FD_ENA, pf->flags) ? 1 : 0;
6221
6222         pf->stat_prev_loaded = true;
6223 }
6224
6225 /**
6226  * ice_get_stats64 - get statistics for network device structure
6227  * @netdev: network interface device structure
6228  * @stats: main device statistics structure
6229  */
6230 static
6231 void ice_get_stats64(struct net_device *netdev, struct rtnl_link_stats64 *stats)
6232 {
6233         struct ice_netdev_priv *np = netdev_priv(netdev);
6234         struct rtnl_link_stats64 *vsi_stats;
6235         struct ice_vsi *vsi = np->vsi;
6236
6237         vsi_stats = &vsi->net_stats;
6238
6239         if (!vsi->num_txq || !vsi->num_rxq)
6240                 return;
6241
6242         /* netdev packet/byte stats come from ring counter. These are obtained
6243          * by summing up ring counters (done by ice_update_vsi_ring_stats).
6244          * But, only call the update routine and read the registers if VSI is
6245          * not down.
6246          */
6247         if (!test_bit(ICE_VSI_DOWN, vsi->state))
6248                 ice_update_vsi_ring_stats(vsi);
6249         stats->tx_packets = vsi_stats->tx_packets;
6250         stats->tx_bytes = vsi_stats->tx_bytes;
6251         stats->rx_packets = vsi_stats->rx_packets;
6252         stats->rx_bytes = vsi_stats->rx_bytes;
6253
6254         /* The rest of the stats can be read from the hardware but instead we
6255          * just return values that the watchdog task has already obtained from
6256          * the hardware.
6257          */
6258         stats->multicast = vsi_stats->multicast;
6259         stats->tx_errors = vsi_stats->tx_errors;
6260         stats->tx_dropped = vsi_stats->tx_dropped;
6261         stats->rx_errors = vsi_stats->rx_errors;
6262         stats->rx_dropped = vsi_stats->rx_dropped;
6263         stats->rx_crc_errors = vsi_stats->rx_crc_errors;
6264         stats->rx_length_errors = vsi_stats->rx_length_errors;
6265 }
6266
6267 /**
6268  * ice_napi_disable_all - Disable NAPI for all q_vectors in the VSI
6269  * @vsi: VSI having NAPI disabled
6270  */
6271 static void ice_napi_disable_all(struct ice_vsi *vsi)
6272 {
6273         int q_idx;
6274
6275         if (!vsi->netdev)
6276                 return;
6277
6278         ice_for_each_q_vector(vsi, q_idx) {
6279                 struct ice_q_vector *q_vector = vsi->q_vectors[q_idx];
6280
6281                 if (q_vector->rx.rx_ring || q_vector->tx.tx_ring)
6282                         napi_disable(&q_vector->napi);
6283
6284                 cancel_work_sync(&q_vector->tx.dim.work);
6285                 cancel_work_sync(&q_vector->rx.dim.work);
6286         }
6287 }
6288
6289 /**
6290  * ice_down - Shutdown the connection
6291  * @vsi: The VSI being stopped
6292  */
6293 int ice_down(struct ice_vsi *vsi)
6294 {
6295         int i, tx_err, rx_err, link_err = 0;
6296
6297         /* Caller of this function is expected to set the
6298          * vsi->state ICE_DOWN bit
6299          */
6300         if (vsi->netdev && vsi->type == ICE_VSI_PF) {
6301                 netif_carrier_off(vsi->netdev);
6302                 netif_tx_disable(vsi->netdev);
6303         } else if (vsi->type == ICE_VSI_SWITCHDEV_CTRL) {
6304                 ice_eswitch_stop_all_tx_queues(vsi->back);
6305         }
6306
6307         ice_vsi_dis_irq(vsi);
6308
6309         tx_err = ice_vsi_stop_lan_tx_rings(vsi, ICE_NO_RESET, 0);
6310         if (tx_err)
6311                 netdev_err(vsi->netdev, "Failed stop Tx rings, VSI %d error %d\n",
6312                            vsi->vsi_num, tx_err);
6313         if (!tx_err && ice_is_xdp_ena_vsi(vsi)) {
6314                 tx_err = ice_vsi_stop_xdp_tx_rings(vsi);
6315                 if (tx_err)
6316                         netdev_err(vsi->netdev, "Failed stop XDP rings, VSI %d error %d\n",
6317                                    vsi->vsi_num, tx_err);
6318         }
6319
6320         rx_err = ice_vsi_stop_all_rx_rings(vsi);
6321         if (rx_err)
6322                 netdev_err(vsi->netdev, "Failed stop Rx rings, VSI %d error %d\n",
6323                            vsi->vsi_num, rx_err);
6324
6325         ice_napi_disable_all(vsi);
6326
6327         if (test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags)) {
6328                 link_err = ice_force_phys_link_state(vsi, false);
6329                 if (link_err)
6330                         netdev_err(vsi->netdev, "Failed to set physical link down, VSI %d error %d\n",
6331                                    vsi->vsi_num, link_err);
6332         }
6333
6334         ice_for_each_txq(vsi, i)
6335                 ice_clean_tx_ring(vsi->tx_rings[i]);
6336
6337         ice_for_each_rxq(vsi, i)
6338                 ice_clean_rx_ring(vsi->rx_rings[i]);
6339
6340         if (tx_err || rx_err || link_err) {
6341                 netdev_err(vsi->netdev, "Failed to close VSI 0x%04X on switch 0x%04X\n",
6342                            vsi->vsi_num, vsi->vsw->sw_id);
6343                 return -EIO;
6344         }
6345
6346         return 0;
6347 }
6348
6349 /**
6350  * ice_vsi_setup_tx_rings - Allocate VSI Tx queue resources
6351  * @vsi: VSI having resources allocated
6352  *
6353  * Return 0 on success, negative on failure
6354  */
6355 int ice_vsi_setup_tx_rings(struct ice_vsi *vsi)
6356 {
6357         int i, err = 0;
6358
6359         if (!vsi->num_txq) {
6360                 dev_err(ice_pf_to_dev(vsi->back), "VSI %d has 0 Tx queues\n",
6361                         vsi->vsi_num);
6362                 return -EINVAL;
6363         }
6364
6365         ice_for_each_txq(vsi, i) {
6366                 struct ice_tx_ring *ring = vsi->tx_rings[i];
6367
6368                 if (!ring)
6369                         return -EINVAL;
6370
6371                 if (vsi->netdev)
6372                         ring->netdev = vsi->netdev;
6373                 err = ice_setup_tx_ring(ring);
6374                 if (err)
6375                         break;
6376         }
6377
6378         return err;
6379 }
6380
6381 /**
6382  * ice_vsi_setup_rx_rings - Allocate VSI Rx queue resources
6383  * @vsi: VSI having resources allocated
6384  *
6385  * Return 0 on success, negative on failure
6386  */
6387 int ice_vsi_setup_rx_rings(struct ice_vsi *vsi)
6388 {
6389         int i, err = 0;
6390
6391         if (!vsi->num_rxq) {
6392                 dev_err(ice_pf_to_dev(vsi->back), "VSI %d has 0 Rx queues\n",
6393                         vsi->vsi_num);
6394                 return -EINVAL;
6395         }
6396
6397         ice_for_each_rxq(vsi, i) {
6398                 struct ice_rx_ring *ring = vsi->rx_rings[i];
6399
6400                 if (!ring)
6401                         return -EINVAL;
6402
6403                 if (vsi->netdev)
6404                         ring->netdev = vsi->netdev;
6405                 err = ice_setup_rx_ring(ring);
6406                 if (err)
6407                         break;
6408         }
6409
6410         return err;
6411 }
6412
6413 /**
6414  * ice_vsi_open_ctrl - open control VSI for use
6415  * @vsi: the VSI to open
6416  *
6417  * Initialization of the Control VSI
6418  *
6419  * Returns 0 on success, negative value on error
6420  */
6421 int ice_vsi_open_ctrl(struct ice_vsi *vsi)
6422 {
6423         char int_name[ICE_INT_NAME_STR_LEN];
6424         struct ice_pf *pf = vsi->back;
6425         struct device *dev;
6426         int err;
6427
6428         dev = ice_pf_to_dev(pf);
6429         /* allocate descriptors */
6430         err = ice_vsi_setup_tx_rings(vsi);
6431         if (err)
6432                 goto err_setup_tx;
6433
6434         err = ice_vsi_setup_rx_rings(vsi);
6435         if (err)
6436                 goto err_setup_rx;
6437
6438         err = ice_vsi_cfg(vsi);
6439         if (err)
6440                 goto err_setup_rx;
6441
6442         snprintf(int_name, sizeof(int_name) - 1, "%s-%s:ctrl",
6443                  dev_driver_string(dev), dev_name(dev));
6444         err = ice_vsi_req_irq_msix(vsi, int_name);
6445         if (err)
6446                 goto err_setup_rx;
6447
6448         ice_vsi_cfg_msix(vsi);
6449
6450         err = ice_vsi_start_all_rx_rings(vsi);
6451         if (err)
6452                 goto err_up_complete;
6453
6454         clear_bit(ICE_VSI_DOWN, vsi->state);
6455         ice_vsi_ena_irq(vsi);
6456
6457         return 0;
6458
6459 err_up_complete:
6460         ice_down(vsi);
6461 err_setup_rx:
6462         ice_vsi_free_rx_rings(vsi);
6463 err_setup_tx:
6464         ice_vsi_free_tx_rings(vsi);
6465
6466         return err;
6467 }
6468
6469 /**
6470  * ice_vsi_open - Called when a network interface is made active
6471  * @vsi: the VSI to open
6472  *
6473  * Initialization of the VSI
6474  *
6475  * Returns 0 on success, negative value on error
6476  */
6477 int ice_vsi_open(struct ice_vsi *vsi)
6478 {
6479         char int_name[ICE_INT_NAME_STR_LEN];
6480         struct ice_pf *pf = vsi->back;
6481         int err;
6482
6483         /* allocate descriptors */
6484         err = ice_vsi_setup_tx_rings(vsi);
6485         if (err)
6486                 goto err_setup_tx;
6487
6488         err = ice_vsi_setup_rx_rings(vsi);
6489         if (err)
6490                 goto err_setup_rx;
6491
6492         err = ice_vsi_cfg(vsi);
6493         if (err)
6494                 goto err_setup_rx;
6495
6496         snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
6497                  dev_driver_string(ice_pf_to_dev(pf)), vsi->netdev->name);
6498         err = ice_vsi_req_irq_msix(vsi, int_name);
6499         if (err)
6500                 goto err_setup_rx;
6501
6502         if (vsi->type == ICE_VSI_PF) {
6503                 /* Notify the stack of the actual queue counts. */
6504                 err = netif_set_real_num_tx_queues(vsi->netdev, vsi->num_txq);
6505                 if (err)
6506                         goto err_set_qs;
6507
6508                 err = netif_set_real_num_rx_queues(vsi->netdev, vsi->num_rxq);
6509                 if (err)
6510                         goto err_set_qs;
6511         }
6512
6513         err = ice_up_complete(vsi);
6514         if (err)
6515                 goto err_up_complete;
6516
6517         return 0;
6518
6519 err_up_complete:
6520         ice_down(vsi);
6521 err_set_qs:
6522         ice_vsi_free_irq(vsi);
6523 err_setup_rx:
6524         ice_vsi_free_rx_rings(vsi);
6525 err_setup_tx:
6526         ice_vsi_free_tx_rings(vsi);
6527
6528         return err;
6529 }
6530
6531 /**
6532  * ice_vsi_release_all - Delete all VSIs
6533  * @pf: PF from which all VSIs are being removed
6534  */
6535 static void ice_vsi_release_all(struct ice_pf *pf)
6536 {
6537         int err, i;
6538
6539         if (!pf->vsi)
6540                 return;
6541
6542         ice_for_each_vsi(pf, i) {
6543                 if (!pf->vsi[i])
6544                         continue;
6545
6546                 if (pf->vsi[i]->type == ICE_VSI_CHNL)
6547                         continue;
6548
6549                 err = ice_vsi_release(pf->vsi[i]);
6550                 if (err)
6551                         dev_dbg(ice_pf_to_dev(pf), "Failed to release pf->vsi[%d], err %d, vsi_num = %d\n",
6552                                 i, err, pf->vsi[i]->vsi_num);
6553         }
6554 }
6555
6556 /**
6557  * ice_vsi_rebuild_by_type - Rebuild VSI of a given type
6558  * @pf: pointer to the PF instance
6559  * @type: VSI type to rebuild
6560  *
6561  * Iterates through the pf->vsi array and rebuilds VSIs of the requested type
6562  */
6563 static int ice_vsi_rebuild_by_type(struct ice_pf *pf, enum ice_vsi_type type)
6564 {
6565         struct device *dev = ice_pf_to_dev(pf);
6566         enum ice_status status;
6567         int i, err;
6568
6569         ice_for_each_vsi(pf, i) {
6570                 struct ice_vsi *vsi = pf->vsi[i];
6571
6572                 if (!vsi || vsi->type != type)
6573                         continue;
6574
6575                 /* rebuild the VSI */
6576                 err = ice_vsi_rebuild(vsi, true);
6577                 if (err) {
6578                         dev_err(dev, "rebuild VSI failed, err %d, VSI index %d, type %s\n",
6579                                 err, vsi->idx, ice_vsi_type_str(type));
6580                         return err;
6581                 }
6582
6583                 /* replay filters for the VSI */
6584                 status = ice_replay_vsi(&pf->hw, vsi->idx);
6585                 if (status) {
6586                         dev_err(dev, "replay VSI failed, status %s, VSI index %d, type %s\n",
6587                                 ice_stat_str(status), vsi->idx,
6588                                 ice_vsi_type_str(type));
6589                         return -EIO;
6590                 }
6591
6592                 /* Re-map HW VSI number, using VSI handle that has been
6593                  * previously validated in ice_replay_vsi() call above
6594                  */
6595                 vsi->vsi_num = ice_get_hw_vsi_num(&pf->hw, vsi->idx);
6596
6597                 /* enable the VSI */
6598                 err = ice_ena_vsi(vsi, false);
6599                 if (err) {
6600                         dev_err(dev, "enable VSI failed, err %d, VSI index %d, type %s\n",
6601                                 err, vsi->idx, ice_vsi_type_str(type));
6602                         return err;
6603                 }
6604
6605                 dev_info(dev, "VSI rebuilt. VSI index %d, type %s\n", vsi->idx,
6606                          ice_vsi_type_str(type));
6607         }
6608
6609         return 0;
6610 }
6611
6612 /**
6613  * ice_update_pf_netdev_link - Update PF netdev link status
6614  * @pf: pointer to the PF instance
6615  */
6616 static void ice_update_pf_netdev_link(struct ice_pf *pf)
6617 {
6618         bool link_up;
6619         int i;
6620
6621         ice_for_each_vsi(pf, i) {
6622                 struct ice_vsi *vsi = pf->vsi[i];
6623
6624                 if (!vsi || vsi->type != ICE_VSI_PF)
6625                         return;
6626
6627                 ice_get_link_status(pf->vsi[i]->port_info, &link_up);
6628                 if (link_up) {
6629                         netif_carrier_on(pf->vsi[i]->netdev);
6630                         netif_tx_wake_all_queues(pf->vsi[i]->netdev);
6631                 } else {
6632                         netif_carrier_off(pf->vsi[i]->netdev);
6633                         netif_tx_stop_all_queues(pf->vsi[i]->netdev);
6634                 }
6635         }
6636 }
6637
6638 /**
6639  * ice_rebuild - rebuild after reset
6640  * @pf: PF to rebuild
6641  * @reset_type: type of reset
6642  *
6643  * Do not rebuild VF VSI in this flow because that is already handled via
6644  * ice_reset_all_vfs(). This is because requirements for resetting a VF after a
6645  * PFR/CORER/GLOBER/etc. are different than the normal flow. Also, we don't want
6646  * to reset/rebuild all the VF VSI twice.
6647  */
6648 static void ice_rebuild(struct ice_pf *pf, enum ice_reset_req reset_type)
6649 {
6650         struct device *dev = ice_pf_to_dev(pf);
6651         struct ice_hw *hw = &pf->hw;
6652         enum ice_status ret;
6653         int err;
6654
6655         if (test_bit(ICE_DOWN, pf->state))
6656                 goto clear_recovery;
6657
6658         dev_dbg(dev, "rebuilding PF after reset_type=%d\n", reset_type);
6659
6660         ret = ice_init_all_ctrlq(hw);
6661         if (ret) {
6662                 dev_err(dev, "control queues init failed %s\n",
6663                         ice_stat_str(ret));
6664                 goto err_init_ctrlq;
6665         }
6666
6667         /* if DDP was previously loaded successfully */
6668         if (!ice_is_safe_mode(pf)) {
6669                 /* reload the SW DB of filter tables */
6670                 if (reset_type == ICE_RESET_PFR)
6671                         ice_fill_blk_tbls(hw);
6672                 else
6673                         /* Reload DDP Package after CORER/GLOBR reset */
6674                         ice_load_pkg(NULL, pf);
6675         }
6676
6677         ret = ice_clear_pf_cfg(hw);
6678         if (ret) {
6679                 dev_err(dev, "clear PF configuration failed %s\n",
6680                         ice_stat_str(ret));
6681                 goto err_init_ctrlq;
6682         }
6683
6684         if (pf->first_sw->dflt_vsi_ena)
6685                 dev_info(dev, "Clearing default VSI, re-enable after reset completes\n");
6686         /* clear the default VSI configuration if it exists */
6687         pf->first_sw->dflt_vsi = NULL;
6688         pf->first_sw->dflt_vsi_ena = false;
6689
6690         ice_clear_pxe_mode(hw);
6691
6692         ret = ice_init_nvm(hw);
6693         if (ret) {
6694                 dev_err(dev, "ice_init_nvm failed %s\n", ice_stat_str(ret));
6695                 goto err_init_ctrlq;
6696         }
6697
6698         ret = ice_get_caps(hw);
6699         if (ret) {
6700                 dev_err(dev, "ice_get_caps failed %s\n", ice_stat_str(ret));
6701                 goto err_init_ctrlq;
6702         }
6703
6704         ret = ice_aq_set_mac_cfg(hw, ICE_AQ_SET_MAC_FRAME_SIZE_MAX, NULL);
6705         if (ret) {
6706                 dev_err(dev, "set_mac_cfg failed %s\n", ice_stat_str(ret));
6707                 goto err_init_ctrlq;
6708         }
6709
6710         err = ice_sched_init_port(hw->port_info);
6711         if (err)
6712                 goto err_sched_init_port;
6713
6714         /* start misc vector */
6715         err = ice_req_irq_msix_misc(pf);
6716         if (err) {
6717                 dev_err(dev, "misc vector setup failed: %d\n", err);
6718                 goto err_sched_init_port;
6719         }
6720
6721         if (test_bit(ICE_FLAG_FD_ENA, pf->flags)) {
6722                 wr32(hw, PFQF_FD_ENA, PFQF_FD_ENA_FD_ENA_M);
6723                 if (!rd32(hw, PFQF_FD_SIZE)) {
6724                         u16 unused, guar, b_effort;
6725
6726                         guar = hw->func_caps.fd_fltr_guar;
6727                         b_effort = hw->func_caps.fd_fltr_best_effort;
6728
6729                         /* force guaranteed filter pool for PF */
6730                         ice_alloc_fd_guar_item(hw, &unused, guar);
6731                         /* force shared filter pool for PF */
6732                         ice_alloc_fd_shrd_item(hw, &unused, b_effort);
6733                 }
6734         }
6735
6736         if (test_bit(ICE_FLAG_DCB_ENA, pf->flags))
6737                 ice_dcb_rebuild(pf);
6738
6739         /* If the PF previously had enabled PTP, PTP init needs to happen before
6740          * the VSI rebuild. If not, this causes the PTP link status events to
6741          * fail.
6742          */
6743         if (test_bit(ICE_FLAG_PTP_SUPPORTED, pf->flags))
6744                 ice_ptp_init(pf);
6745
6746         /* rebuild PF VSI */
6747         err = ice_vsi_rebuild_by_type(pf, ICE_VSI_PF);
6748         if (err) {
6749                 dev_err(dev, "PF VSI rebuild failed: %d\n", err);
6750                 goto err_vsi_rebuild;
6751         }
6752
6753         err = ice_vsi_rebuild_by_type(pf, ICE_VSI_SWITCHDEV_CTRL);
6754         if (err) {
6755                 dev_err(dev, "Switchdev CTRL VSI rebuild failed: %d\n", err);
6756                 goto err_vsi_rebuild;
6757         }
6758
6759         if (reset_type == ICE_RESET_PFR) {
6760                 err = ice_rebuild_channels(pf);
6761                 if (err) {
6762                         dev_err(dev, "failed to rebuild and replay ADQ VSIs, err %d\n",
6763                                 err);
6764                         goto err_vsi_rebuild;
6765                 }
6766         }
6767
6768         /* If Flow Director is active */
6769         if (test_bit(ICE_FLAG_FD_ENA, pf->flags)) {
6770                 err = ice_vsi_rebuild_by_type(pf, ICE_VSI_CTRL);
6771                 if (err) {
6772                         dev_err(dev, "control VSI rebuild failed: %d\n", err);
6773                         goto err_vsi_rebuild;
6774                 }
6775
6776                 /* replay HW Flow Director recipes */
6777                 if (hw->fdir_prof)
6778                         ice_fdir_replay_flows(hw);
6779
6780                 /* replay Flow Director filters */
6781                 ice_fdir_replay_fltrs(pf);
6782
6783                 ice_rebuild_arfs(pf);
6784         }
6785
6786         ice_update_pf_netdev_link(pf);
6787
6788         /* tell the firmware we are up */
6789         ret = ice_send_version(pf);
6790         if (ret) {
6791                 dev_err(dev, "Rebuild failed due to error sending driver version: %s\n",
6792                         ice_stat_str(ret));
6793                 goto err_vsi_rebuild;
6794         }
6795
6796         ice_replay_post(hw);
6797
6798         /* if we get here, reset flow is successful */
6799         clear_bit(ICE_RESET_FAILED, pf->state);
6800
6801         ice_plug_aux_dev(pf);
6802         return;
6803
6804 err_vsi_rebuild:
6805 err_sched_init_port:
6806         ice_sched_cleanup_all(hw);
6807 err_init_ctrlq:
6808         ice_shutdown_all_ctrlq(hw);
6809         set_bit(ICE_RESET_FAILED, pf->state);
6810 clear_recovery:
6811         /* set this bit in PF state to control service task scheduling */
6812         set_bit(ICE_NEEDS_RESTART, pf->state);
6813         dev_err(dev, "Rebuild failed, unload and reload driver\n");
6814 }
6815
6816 /**
6817  * ice_max_xdp_frame_size - returns the maximum allowed frame size for XDP
6818  * @vsi: Pointer to VSI structure
6819  */
6820 static int ice_max_xdp_frame_size(struct ice_vsi *vsi)
6821 {
6822         if (PAGE_SIZE >= 8192 || test_bit(ICE_FLAG_LEGACY_RX, vsi->back->flags))
6823                 return ICE_RXBUF_2048 - XDP_PACKET_HEADROOM;
6824         else
6825                 return ICE_RXBUF_3072;
6826 }
6827
6828 /**
6829  * ice_change_mtu - NDO callback to change the MTU
6830  * @netdev: network interface device structure
6831  * @new_mtu: new value for maximum frame size
6832  *
6833  * Returns 0 on success, negative on failure
6834  */
6835 static int ice_change_mtu(struct net_device *netdev, int new_mtu)
6836 {
6837         struct ice_netdev_priv *np = netdev_priv(netdev);
6838         struct ice_vsi *vsi = np->vsi;
6839         struct ice_pf *pf = vsi->back;
6840         struct iidc_event *event;
6841         u8 count = 0;
6842         int err = 0;
6843
6844         if (new_mtu == (int)netdev->mtu) {
6845                 netdev_warn(netdev, "MTU is already %u\n", netdev->mtu);
6846                 return 0;
6847         }
6848
6849         if (ice_is_xdp_ena_vsi(vsi)) {
6850                 int frame_size = ice_max_xdp_frame_size(vsi);
6851
6852                 if (new_mtu + ICE_ETH_PKT_HDR_PAD > frame_size) {
6853                         netdev_err(netdev, "max MTU for XDP usage is %d\n",
6854                                    frame_size - ICE_ETH_PKT_HDR_PAD);
6855                         return -EINVAL;
6856                 }
6857         }
6858
6859         /* if a reset is in progress, wait for some time for it to complete */
6860         do {
6861                 if (ice_is_reset_in_progress(pf->state)) {
6862                         count++;
6863                         usleep_range(1000, 2000);
6864                 } else {
6865                         break;
6866                 }
6867
6868         } while (count < 100);
6869
6870         if (count == 100) {
6871                 netdev_err(netdev, "can't change MTU. Device is busy\n");
6872                 return -EBUSY;
6873         }
6874
6875         event = kzalloc(sizeof(*event), GFP_KERNEL);
6876         if (!event)
6877                 return -ENOMEM;
6878
6879         set_bit(IIDC_EVENT_BEFORE_MTU_CHANGE, event->type);
6880         ice_send_event_to_aux(pf, event);
6881         clear_bit(IIDC_EVENT_BEFORE_MTU_CHANGE, event->type);
6882
6883         netdev->mtu = (unsigned int)new_mtu;
6884
6885         /* if VSI is up, bring it down and then back up */
6886         if (!test_and_set_bit(ICE_VSI_DOWN, vsi->state)) {
6887                 err = ice_down(vsi);
6888                 if (err) {
6889                         netdev_err(netdev, "change MTU if_down err %d\n", err);
6890                         goto event_after;
6891                 }
6892
6893                 err = ice_up(vsi);
6894                 if (err) {
6895                         netdev_err(netdev, "change MTU if_up err %d\n", err);
6896                         goto event_after;
6897                 }
6898         }
6899
6900         netdev_dbg(netdev, "changed MTU to %d\n", new_mtu);
6901 event_after:
6902         set_bit(IIDC_EVENT_AFTER_MTU_CHANGE, event->type);
6903         ice_send_event_to_aux(pf, event);
6904         kfree(event);
6905
6906         return err;
6907 }
6908
6909 /**
6910  * ice_eth_ioctl - Access the hwtstamp interface
6911  * @netdev: network interface device structure
6912  * @ifr: interface request data
6913  * @cmd: ioctl command
6914  */
6915 static int ice_eth_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
6916 {
6917         struct ice_netdev_priv *np = netdev_priv(netdev);
6918         struct ice_pf *pf = np->vsi->back;
6919
6920         switch (cmd) {
6921         case SIOCGHWTSTAMP:
6922                 return ice_ptp_get_ts_config(pf, ifr);
6923         case SIOCSHWTSTAMP:
6924                 return ice_ptp_set_ts_config(pf, ifr);
6925         default:
6926                 return -EOPNOTSUPP;
6927         }
6928 }
6929
6930 /**
6931  * ice_aq_str - convert AQ err code to a string
6932  * @aq_err: the AQ error code to convert
6933  */
6934 const char *ice_aq_str(enum ice_aq_err aq_err)
6935 {
6936         switch (aq_err) {
6937         case ICE_AQ_RC_OK:
6938                 return "OK";
6939         case ICE_AQ_RC_EPERM:
6940                 return "ICE_AQ_RC_EPERM";
6941         case ICE_AQ_RC_ENOENT:
6942                 return "ICE_AQ_RC_ENOENT";
6943         case ICE_AQ_RC_ENOMEM:
6944                 return "ICE_AQ_RC_ENOMEM";
6945         case ICE_AQ_RC_EBUSY:
6946                 return "ICE_AQ_RC_EBUSY";
6947         case ICE_AQ_RC_EEXIST:
6948                 return "ICE_AQ_RC_EEXIST";
6949         case ICE_AQ_RC_EINVAL:
6950                 return "ICE_AQ_RC_EINVAL";
6951         case ICE_AQ_RC_ENOSPC:
6952                 return "ICE_AQ_RC_ENOSPC";
6953         case ICE_AQ_RC_ENOSYS:
6954                 return "ICE_AQ_RC_ENOSYS";
6955         case ICE_AQ_RC_EMODE:
6956                 return "ICE_AQ_RC_EMODE";
6957         case ICE_AQ_RC_ENOSEC:
6958                 return "ICE_AQ_RC_ENOSEC";
6959         case ICE_AQ_RC_EBADSIG:
6960                 return "ICE_AQ_RC_EBADSIG";
6961         case ICE_AQ_RC_ESVN:
6962                 return "ICE_AQ_RC_ESVN";
6963         case ICE_AQ_RC_EBADMAN:
6964                 return "ICE_AQ_RC_EBADMAN";
6965         case ICE_AQ_RC_EBADBUF:
6966                 return "ICE_AQ_RC_EBADBUF";
6967         }
6968
6969         return "ICE_AQ_RC_UNKNOWN";
6970 }
6971
6972 /**
6973  * ice_stat_str - convert status err code to a string
6974  * @stat_err: the status error code to convert
6975  */
6976 const char *ice_stat_str(enum ice_status stat_err)
6977 {
6978         switch (stat_err) {
6979         case ICE_SUCCESS:
6980                 return "OK";
6981         case ICE_ERR_PARAM:
6982                 return "ICE_ERR_PARAM";
6983         case ICE_ERR_NOT_IMPL:
6984                 return "ICE_ERR_NOT_IMPL";
6985         case ICE_ERR_NOT_READY:
6986                 return "ICE_ERR_NOT_READY";
6987         case ICE_ERR_NOT_SUPPORTED:
6988                 return "ICE_ERR_NOT_SUPPORTED";
6989         case ICE_ERR_BAD_PTR:
6990                 return "ICE_ERR_BAD_PTR";
6991         case ICE_ERR_INVAL_SIZE:
6992                 return "ICE_ERR_INVAL_SIZE";
6993         case ICE_ERR_DEVICE_NOT_SUPPORTED:
6994                 return "ICE_ERR_DEVICE_NOT_SUPPORTED";
6995         case ICE_ERR_RESET_FAILED:
6996                 return "ICE_ERR_RESET_FAILED";
6997         case ICE_ERR_FW_API_VER:
6998                 return "ICE_ERR_FW_API_VER";
6999         case ICE_ERR_NO_MEMORY:
7000                 return "ICE_ERR_NO_MEMORY";
7001         case ICE_ERR_CFG:
7002                 return "ICE_ERR_CFG";
7003         case ICE_ERR_OUT_OF_RANGE:
7004                 return "ICE_ERR_OUT_OF_RANGE";
7005         case ICE_ERR_ALREADY_EXISTS:
7006                 return "ICE_ERR_ALREADY_EXISTS";
7007         case ICE_ERR_NVM:
7008                 return "ICE_ERR_NVM";
7009         case ICE_ERR_NVM_CHECKSUM:
7010                 return "ICE_ERR_NVM_CHECKSUM";
7011         case ICE_ERR_BUF_TOO_SHORT:
7012                 return "ICE_ERR_BUF_TOO_SHORT";
7013         case ICE_ERR_NVM_BLANK_MODE:
7014                 return "ICE_ERR_NVM_BLANK_MODE";
7015         case ICE_ERR_IN_USE:
7016                 return "ICE_ERR_IN_USE";
7017         case ICE_ERR_MAX_LIMIT:
7018                 return "ICE_ERR_MAX_LIMIT";
7019         case ICE_ERR_RESET_ONGOING:
7020                 return "ICE_ERR_RESET_ONGOING";
7021         case ICE_ERR_HW_TABLE:
7022                 return "ICE_ERR_HW_TABLE";
7023         case ICE_ERR_DOES_NOT_EXIST:
7024                 return "ICE_ERR_DOES_NOT_EXIST";
7025         case ICE_ERR_FW_DDP_MISMATCH:
7026                 return "ICE_ERR_FW_DDP_MISMATCH";
7027         case ICE_ERR_AQ_ERROR:
7028                 return "ICE_ERR_AQ_ERROR";
7029         case ICE_ERR_AQ_TIMEOUT:
7030                 return "ICE_ERR_AQ_TIMEOUT";
7031         case ICE_ERR_AQ_FULL:
7032                 return "ICE_ERR_AQ_FULL";
7033         case ICE_ERR_AQ_NO_WORK:
7034                 return "ICE_ERR_AQ_NO_WORK";
7035         case ICE_ERR_AQ_EMPTY:
7036                 return "ICE_ERR_AQ_EMPTY";
7037         case ICE_ERR_AQ_FW_CRITICAL:
7038                 return "ICE_ERR_AQ_FW_CRITICAL";
7039         }
7040
7041         return "ICE_ERR_UNKNOWN";
7042 }
7043
7044 /**
7045  * ice_set_rss_lut - Set RSS LUT
7046  * @vsi: Pointer to VSI structure
7047  * @lut: Lookup table
7048  * @lut_size: Lookup table size
7049  *
7050  * Returns 0 on success, negative on failure
7051  */
7052 int ice_set_rss_lut(struct ice_vsi *vsi, u8 *lut, u16 lut_size)
7053 {
7054         struct ice_aq_get_set_rss_lut_params params = {};
7055         struct ice_hw *hw = &vsi->back->hw;
7056         enum ice_status status;
7057
7058         if (!lut)
7059                 return -EINVAL;
7060
7061         params.vsi_handle = vsi->idx;
7062         params.lut_size = lut_size;
7063         params.lut_type = vsi->rss_lut_type;
7064         params.lut = lut;
7065
7066         status = ice_aq_set_rss_lut(hw, &params);
7067         if (status) {
7068                 dev_err(ice_pf_to_dev(vsi->back), "Cannot set RSS lut, err %s aq_err %s\n",
7069                         ice_stat_str(status),
7070                         ice_aq_str(hw->adminq.sq_last_status));
7071                 return -EIO;
7072         }
7073
7074         return 0;
7075 }
7076
7077 /**
7078  * ice_set_rss_key - Set RSS key
7079  * @vsi: Pointer to the VSI structure
7080  * @seed: RSS hash seed
7081  *
7082  * Returns 0 on success, negative on failure
7083  */
7084 int ice_set_rss_key(struct ice_vsi *vsi, u8 *seed)
7085 {
7086         struct ice_hw *hw = &vsi->back->hw;
7087         enum ice_status status;
7088
7089         if (!seed)
7090                 return -EINVAL;
7091
7092         status = ice_aq_set_rss_key(hw, vsi->idx, (struct ice_aqc_get_set_rss_keys *)seed);
7093         if (status) {
7094                 dev_err(ice_pf_to_dev(vsi->back), "Cannot set RSS key, err %s aq_err %s\n",
7095                         ice_stat_str(status),
7096                         ice_aq_str(hw->adminq.sq_last_status));
7097                 return -EIO;
7098         }
7099
7100         return 0;
7101 }
7102
7103 /**
7104  * ice_get_rss_lut - Get RSS LUT
7105  * @vsi: Pointer to VSI structure
7106  * @lut: Buffer to store the lookup table entries
7107  * @lut_size: Size of buffer to store the lookup table entries
7108  *
7109  * Returns 0 on success, negative on failure
7110  */
7111 int ice_get_rss_lut(struct ice_vsi *vsi, u8 *lut, u16 lut_size)
7112 {
7113         struct ice_aq_get_set_rss_lut_params params = {};
7114         struct ice_hw *hw = &vsi->back->hw;
7115         enum ice_status status;
7116
7117         if (!lut)
7118                 return -EINVAL;
7119
7120         params.vsi_handle = vsi->idx;
7121         params.lut_size = lut_size;
7122         params.lut_type = vsi->rss_lut_type;
7123         params.lut = lut;
7124
7125         status = ice_aq_get_rss_lut(hw, &params);
7126         if (status) {
7127                 dev_err(ice_pf_to_dev(vsi->back), "Cannot get RSS lut, err %s aq_err %s\n",
7128                         ice_stat_str(status),
7129                         ice_aq_str(hw->adminq.sq_last_status));
7130                 return -EIO;
7131         }
7132
7133         return 0;
7134 }
7135
7136 /**
7137  * ice_get_rss_key - Get RSS key
7138  * @vsi: Pointer to VSI structure
7139  * @seed: Buffer to store the key in
7140  *
7141  * Returns 0 on success, negative on failure
7142  */
7143 int ice_get_rss_key(struct ice_vsi *vsi, u8 *seed)
7144 {
7145         struct ice_hw *hw = &vsi->back->hw;
7146         enum ice_status status;
7147
7148         if (!seed)
7149                 return -EINVAL;
7150
7151         status = ice_aq_get_rss_key(hw, vsi->idx, (struct ice_aqc_get_set_rss_keys *)seed);
7152         if (status) {
7153                 dev_err(ice_pf_to_dev(vsi->back), "Cannot get RSS key, err %s aq_err %s\n",
7154                         ice_stat_str(status),
7155                         ice_aq_str(hw->adminq.sq_last_status));
7156                 return -EIO;
7157         }
7158
7159         return 0;
7160 }
7161
7162 /**
7163  * ice_bridge_getlink - Get the hardware bridge mode
7164  * @skb: skb buff
7165  * @pid: process ID
7166  * @seq: RTNL message seq
7167  * @dev: the netdev being configured
7168  * @filter_mask: filter mask passed in
7169  * @nlflags: netlink flags passed in
7170  *
7171  * Return the bridge mode (VEB/VEPA)
7172  */
7173 static int
7174 ice_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
7175                    struct net_device *dev, u32 filter_mask, int nlflags)
7176 {
7177         struct ice_netdev_priv *np = netdev_priv(dev);
7178         struct ice_vsi *vsi = np->vsi;
7179         struct ice_pf *pf = vsi->back;
7180         u16 bmode;
7181
7182         bmode = pf->first_sw->bridge_mode;
7183
7184         return ndo_dflt_bridge_getlink(skb, pid, seq, dev, bmode, 0, 0, nlflags,
7185                                        filter_mask, NULL);
7186 }
7187
7188 /**
7189  * ice_vsi_update_bridge_mode - Update VSI for switching bridge mode (VEB/VEPA)
7190  * @vsi: Pointer to VSI structure
7191  * @bmode: Hardware bridge mode (VEB/VEPA)
7192  *
7193  * Returns 0 on success, negative on failure
7194  */
7195 static int ice_vsi_update_bridge_mode(struct ice_vsi *vsi, u16 bmode)
7196 {
7197         struct ice_aqc_vsi_props *vsi_props;
7198         struct ice_hw *hw = &vsi->back->hw;
7199         struct ice_vsi_ctx *ctxt;
7200         enum ice_status status;
7201         int ret = 0;
7202
7203         vsi_props = &vsi->info;
7204
7205         ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL);
7206         if (!ctxt)
7207                 return -ENOMEM;
7208
7209         ctxt->info = vsi->info;
7210
7211         if (bmode == BRIDGE_MODE_VEB)
7212                 /* change from VEPA to VEB mode */
7213                 ctxt->info.sw_flags |= ICE_AQ_VSI_SW_FLAG_ALLOW_LB;
7214         else
7215                 /* change from VEB to VEPA mode */
7216                 ctxt->info.sw_flags &= ~ICE_AQ_VSI_SW_FLAG_ALLOW_LB;
7217         ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_SW_VALID);
7218
7219         status = ice_update_vsi(hw, vsi->idx, ctxt, NULL);
7220         if (status) {
7221                 dev_err(ice_pf_to_dev(vsi->back), "update VSI for bridge mode failed, bmode = %d err %s aq_err %s\n",
7222                         bmode, ice_stat_str(status),
7223                         ice_aq_str(hw->adminq.sq_last_status));
7224                 ret = -EIO;
7225                 goto out;
7226         }
7227         /* Update sw flags for book keeping */
7228         vsi_props->sw_flags = ctxt->info.sw_flags;
7229
7230 out:
7231         kfree(ctxt);
7232         return ret;
7233 }
7234
7235 /**
7236  * ice_bridge_setlink - Set the hardware bridge mode
7237  * @dev: the netdev being configured
7238  * @nlh: RTNL message
7239  * @flags: bridge setlink flags
7240  * @extack: netlink extended ack
7241  *
7242  * Sets the bridge mode (VEB/VEPA) of the switch to which the netdev (VSI) is
7243  * hooked up to. Iterates through the PF VSI list and sets the loopback mode (if
7244  * not already set for all VSIs connected to this switch. And also update the
7245  * unicast switch filter rules for the corresponding switch of the netdev.
7246  */
7247 static int
7248 ice_bridge_setlink(struct net_device *dev, struct nlmsghdr *nlh,
7249                    u16 __always_unused flags,
7250                    struct netlink_ext_ack __always_unused *extack)
7251 {
7252         struct ice_netdev_priv *np = netdev_priv(dev);
7253         struct ice_pf *pf = np->vsi->back;
7254         struct nlattr *attr, *br_spec;
7255         struct ice_hw *hw = &pf->hw;
7256         enum ice_status status;
7257         struct ice_sw *pf_sw;
7258         int rem, v, err = 0;
7259
7260         pf_sw = pf->first_sw;
7261         /* find the attribute in the netlink message */
7262         br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
7263
7264         nla_for_each_nested(attr, br_spec, rem) {
7265                 __u16 mode;
7266
7267                 if (nla_type(attr) != IFLA_BRIDGE_MODE)
7268                         continue;
7269                 mode = nla_get_u16(attr);
7270                 if (mode != BRIDGE_MODE_VEPA && mode != BRIDGE_MODE_VEB)
7271                         return -EINVAL;
7272                 /* Continue  if bridge mode is not being flipped */
7273                 if (mode == pf_sw->bridge_mode)
7274                         continue;
7275                 /* Iterates through the PF VSI list and update the loopback
7276                  * mode of the VSI
7277                  */
7278                 ice_for_each_vsi(pf, v) {
7279                         if (!pf->vsi[v])
7280                                 continue;
7281                         err = ice_vsi_update_bridge_mode(pf->vsi[v], mode);
7282                         if (err)
7283                                 return err;
7284                 }
7285
7286                 hw->evb_veb = (mode == BRIDGE_MODE_VEB);
7287                 /* Update the unicast switch filter rules for the corresponding
7288                  * switch of the netdev
7289                  */
7290                 status = ice_update_sw_rule_bridge_mode(hw);
7291                 if (status) {
7292                         netdev_err(dev, "switch rule update failed, mode = %d err %s aq_err %s\n",
7293                                    mode, ice_stat_str(status),
7294                                    ice_aq_str(hw->adminq.sq_last_status));
7295                         /* revert hw->evb_veb */
7296                         hw->evb_veb = (pf_sw->bridge_mode == BRIDGE_MODE_VEB);
7297                         return -EIO;
7298                 }
7299
7300                 pf_sw->bridge_mode = mode;
7301         }
7302
7303         return 0;
7304 }
7305
7306 /**
7307  * ice_tx_timeout - Respond to a Tx Hang
7308  * @netdev: network interface device structure
7309  * @txqueue: Tx queue
7310  */
7311 static void ice_tx_timeout(struct net_device *netdev, unsigned int txqueue)
7312 {
7313         struct ice_netdev_priv *np = netdev_priv(netdev);
7314         struct ice_tx_ring *tx_ring = NULL;
7315         struct ice_vsi *vsi = np->vsi;
7316         struct ice_pf *pf = vsi->back;
7317         u32 i;
7318
7319         pf->tx_timeout_count++;
7320
7321         /* Check if PFC is enabled for the TC to which the queue belongs
7322          * to. If yes then Tx timeout is not caused by a hung queue, no
7323          * need to reset and rebuild
7324          */
7325         if (ice_is_pfc_causing_hung_q(pf, txqueue)) {
7326                 dev_info(ice_pf_to_dev(pf), "Fake Tx hang detected on queue %u, timeout caused by PFC storm\n",
7327                          txqueue);
7328                 return;
7329         }
7330
7331         /* now that we have an index, find the tx_ring struct */
7332         ice_for_each_txq(vsi, i)
7333                 if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
7334                         if (txqueue == vsi->tx_rings[i]->q_index) {
7335                                 tx_ring = vsi->tx_rings[i];
7336                                 break;
7337                         }
7338
7339         /* Reset recovery level if enough time has elapsed after last timeout.
7340          * Also ensure no new reset action happens before next timeout period.
7341          */
7342         if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ * 20)))
7343                 pf->tx_timeout_recovery_level = 1;
7344         else if (time_before(jiffies, (pf->tx_timeout_last_recovery +
7345                                        netdev->watchdog_timeo)))
7346                 return;
7347
7348         if (tx_ring) {
7349                 struct ice_hw *hw = &pf->hw;
7350                 u32 head, val = 0;
7351
7352                 head = (rd32(hw, QTX_COMM_HEAD(vsi->txq_map[txqueue])) &
7353                         QTX_COMM_HEAD_HEAD_M) >> QTX_COMM_HEAD_HEAD_S;
7354                 /* Read interrupt register */
7355                 val = rd32(hw, GLINT_DYN_CTL(tx_ring->q_vector->reg_idx));
7356
7357                 netdev_info(netdev, "tx_timeout: VSI_num: %d, Q %u, NTC: 0x%x, HW_HEAD: 0x%x, NTU: 0x%x, INT: 0x%x\n",
7358                             vsi->vsi_num, txqueue, tx_ring->next_to_clean,
7359                             head, tx_ring->next_to_use, val);
7360         }
7361
7362         pf->tx_timeout_last_recovery = jiffies;
7363         netdev_info(netdev, "tx_timeout recovery level %d, txqueue %u\n",
7364                     pf->tx_timeout_recovery_level, txqueue);
7365
7366         switch (pf->tx_timeout_recovery_level) {
7367         case 1:
7368                 set_bit(ICE_PFR_REQ, pf->state);
7369                 break;
7370         case 2:
7371                 set_bit(ICE_CORER_REQ, pf->state);
7372                 break;
7373         case 3:
7374                 set_bit(ICE_GLOBR_REQ, pf->state);
7375                 break;
7376         default:
7377                 netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in unrecoverable state.\n");
7378                 set_bit(ICE_DOWN, pf->state);
7379                 set_bit(ICE_VSI_NEEDS_RESTART, vsi->state);
7380                 set_bit(ICE_SERVICE_DIS, pf->state);
7381                 break;
7382         }
7383
7384         ice_service_task_schedule(pf);
7385         pf->tx_timeout_recovery_level++;
7386 }
7387
7388 /**
7389  * ice_setup_tc_cls_flower - flower classifier offloads
7390  * @np: net device to configure
7391  * @filter_dev: device on which filter is added
7392  * @cls_flower: offload data
7393  */
7394 static int
7395 ice_setup_tc_cls_flower(struct ice_netdev_priv *np,
7396                         struct net_device *filter_dev,
7397                         struct flow_cls_offload *cls_flower)
7398 {
7399         struct ice_vsi *vsi = np->vsi;
7400
7401         if (cls_flower->common.chain_index)
7402                 return -EOPNOTSUPP;
7403
7404         switch (cls_flower->command) {
7405         case FLOW_CLS_REPLACE:
7406                 return ice_add_cls_flower(filter_dev, vsi, cls_flower);
7407         case FLOW_CLS_DESTROY:
7408                 return ice_del_cls_flower(vsi, cls_flower);
7409         default:
7410                 return -EINVAL;
7411         }
7412 }
7413
7414 /**
7415  * ice_setup_tc_block_cb - callback handler registered for TC block
7416  * @type: TC SETUP type
7417  * @type_data: TC flower offload data that contains user input
7418  * @cb_priv: netdev private data
7419  */
7420 static int
7421 ice_setup_tc_block_cb(enum tc_setup_type type, void *type_data, void *cb_priv)
7422 {
7423         struct ice_netdev_priv *np = cb_priv;
7424
7425         switch (type) {
7426         case TC_SETUP_CLSFLOWER:
7427                 return ice_setup_tc_cls_flower(np, np->vsi->netdev,
7428                                                type_data);
7429         default:
7430                 return -EOPNOTSUPP;
7431         }
7432 }
7433
7434 /**
7435  * ice_validate_mqprio_qopt - Validate TCF input parameters
7436  * @vsi: Pointer to VSI
7437  * @mqprio_qopt: input parameters for mqprio queue configuration
7438  *
7439  * This function validates MQPRIO params, such as qcount (power of 2 wherever
7440  * needed), and make sure user doesn't specify qcount and BW rate limit
7441  * for TCs, which are more than "num_tc"
7442  */
7443 static int
7444 ice_validate_mqprio_qopt(struct ice_vsi *vsi,
7445                          struct tc_mqprio_qopt_offload *mqprio_qopt)
7446 {
7447         u64 sum_max_rate = 0, sum_min_rate = 0;
7448         int non_power_of_2_qcount = 0;
7449         struct ice_pf *pf = vsi->back;
7450         int max_rss_q_cnt = 0;
7451         struct device *dev;
7452         int i, speed;
7453         u8 num_tc;
7454
7455         if (vsi->type != ICE_VSI_PF)
7456                 return -EINVAL;
7457
7458         if (mqprio_qopt->qopt.offset[0] != 0 ||
7459             mqprio_qopt->qopt.num_tc < 1 ||
7460             mqprio_qopt->qopt.num_tc > ICE_CHNL_MAX_TC)
7461                 return -EINVAL;
7462
7463         dev = ice_pf_to_dev(pf);
7464         vsi->ch_rss_size = 0;
7465         num_tc = mqprio_qopt->qopt.num_tc;
7466
7467         for (i = 0; num_tc; i++) {
7468                 int qcount = mqprio_qopt->qopt.count[i];
7469                 u64 max_rate, min_rate, rem;
7470
7471                 if (!qcount)
7472                         return -EINVAL;
7473
7474                 if (is_power_of_2(qcount)) {
7475                         if (non_power_of_2_qcount &&
7476                             qcount > non_power_of_2_qcount) {
7477                                 dev_err(dev, "qcount[%d] cannot be greater than non power of 2 qcount[%d]\n",
7478                                         qcount, non_power_of_2_qcount);
7479                                 return -EINVAL;
7480                         }
7481                         if (qcount > max_rss_q_cnt)
7482                                 max_rss_q_cnt = qcount;
7483                 } else {
7484                         if (non_power_of_2_qcount &&
7485                             qcount != non_power_of_2_qcount) {
7486                                 dev_err(dev, "Only one non power of 2 qcount allowed[%d,%d]\n",
7487                                         qcount, non_power_of_2_qcount);
7488                                 return -EINVAL;
7489                         }
7490                         if (qcount < max_rss_q_cnt) {
7491                                 dev_err(dev, "non power of 2 qcount[%d] cannot be less than other qcount[%d]\n",
7492                                         qcount, max_rss_q_cnt);
7493                                 return -EINVAL;
7494                         }
7495                         max_rss_q_cnt = qcount;
7496                         non_power_of_2_qcount = qcount;
7497                 }
7498
7499                 /* TC command takes input in K/N/Gbps or K/M/Gbit etc but
7500                  * converts the bandwidth rate limit into Bytes/s when
7501                  * passing it down to the driver. So convert input bandwidth
7502                  * from Bytes/s to Kbps
7503                  */
7504                 max_rate = mqprio_qopt->max_rate[i];
7505                 max_rate = div_u64(max_rate, ICE_BW_KBPS_DIVISOR);
7506                 sum_max_rate += max_rate;
7507
7508                 /* min_rate is minimum guaranteed rate and it can't be zero */
7509                 min_rate = mqprio_qopt->min_rate[i];
7510                 min_rate = div_u64(min_rate, ICE_BW_KBPS_DIVISOR);
7511                 sum_min_rate += min_rate;
7512
7513                 if (min_rate && min_rate < ICE_MIN_BW_LIMIT) {
7514                         dev_err(dev, "TC%d: min_rate(%llu Kbps) < %u Kbps\n", i,
7515                                 min_rate, ICE_MIN_BW_LIMIT);
7516                         return -EINVAL;
7517                 }
7518
7519                 iter_div_u64_rem(min_rate, ICE_MIN_BW_LIMIT, &rem);
7520                 if (rem) {
7521                         dev_err(dev, "TC%d: Min Rate not multiple of %u Kbps",
7522                                 i, ICE_MIN_BW_LIMIT);
7523                         return -EINVAL;
7524                 }
7525
7526                 iter_div_u64_rem(max_rate, ICE_MIN_BW_LIMIT, &rem);
7527                 if (rem) {
7528                         dev_err(dev, "TC%d: Max Rate not multiple of %u Kbps",
7529                                 i, ICE_MIN_BW_LIMIT);
7530                         return -EINVAL;
7531                 }
7532
7533                 /* min_rate can't be more than max_rate, except when max_rate
7534                  * is zero (implies max_rate sought is max line rate). In such
7535                  * a case min_rate can be more than max.
7536                  */
7537                 if (max_rate && min_rate > max_rate) {
7538                         dev_err(dev, "min_rate %llu Kbps can't be more than max_rate %llu Kbps\n",
7539                                 min_rate, max_rate);
7540                         return -EINVAL;
7541                 }
7542
7543                 if (i >= mqprio_qopt->qopt.num_tc - 1)
7544                         break;
7545                 if (mqprio_qopt->qopt.offset[i + 1] !=
7546                     (mqprio_qopt->qopt.offset[i] + qcount))
7547                         return -EINVAL;
7548         }
7549         if (vsi->num_rxq <
7550             (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7551                 return -EINVAL;
7552         if (vsi->num_txq <
7553             (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7554                 return -EINVAL;
7555
7556         speed = ice_get_link_speed_kbps(vsi);
7557         if (sum_max_rate && sum_max_rate > (u64)speed) {
7558                 dev_err(dev, "Invalid max Tx rate(%llu) Kbps > speed(%u) Kbps specified\n",
7559                         sum_max_rate, speed);
7560                 return -EINVAL;
7561         }
7562         if (sum_min_rate && sum_min_rate > (u64)speed) {
7563                 dev_err(dev, "Invalid min Tx rate(%llu) Kbps > speed (%u) Kbps specified\n",
7564                         sum_min_rate, speed);
7565                 return -EINVAL;
7566         }
7567
7568         /* make sure vsi->ch_rss_size is set correctly based on TC's qcount */
7569         vsi->ch_rss_size = max_rss_q_cnt;
7570
7571         return 0;
7572 }
7573
7574 /**
7575  * ice_add_channel - add a channel by adding VSI
7576  * @pf: ptr to PF device
7577  * @sw_id: underlying HW switching element ID
7578  * @ch: ptr to channel structure
7579  *
7580  * Add a channel (VSI) using add_vsi and queue_map
7581  */
7582 static int ice_add_channel(struct ice_pf *pf, u16 sw_id, struct ice_channel *ch)
7583 {
7584         struct device *dev = ice_pf_to_dev(pf);
7585         struct ice_vsi *vsi;
7586
7587         if (ch->type != ICE_VSI_CHNL) {
7588                 dev_err(dev, "add new VSI failed, ch->type %d\n", ch->type);
7589                 return -EINVAL;
7590         }
7591
7592         vsi = ice_chnl_vsi_setup(pf, pf->hw.port_info, ch);
7593         if (!vsi || vsi->type != ICE_VSI_CHNL) {
7594                 dev_err(dev, "create chnl VSI failure\n");
7595                 return -EINVAL;
7596         }
7597
7598         ch->sw_id = sw_id;
7599         ch->vsi_num = vsi->vsi_num;
7600         ch->info.mapping_flags = vsi->info.mapping_flags;
7601         ch->ch_vsi = vsi;
7602         /* set the back pointer of channel for newly created VSI */
7603         vsi->ch = ch;
7604
7605         memcpy(&ch->info.q_mapping, &vsi->info.q_mapping,
7606                sizeof(vsi->info.q_mapping));
7607         memcpy(&ch->info.tc_mapping, vsi->info.tc_mapping,
7608                sizeof(vsi->info.tc_mapping));
7609
7610         return 0;
7611 }
7612
7613 /**
7614  * ice_chnl_cfg_res
7615  * @vsi: the VSI being setup
7616  * @ch: ptr to channel structure
7617  *
7618  * Configure channel specific resources such as rings, vector.
7619  */
7620 static void ice_chnl_cfg_res(struct ice_vsi *vsi, struct ice_channel *ch)
7621 {
7622         int i;
7623
7624         for (i = 0; i < ch->num_txq; i++) {
7625                 struct ice_q_vector *tx_q_vector, *rx_q_vector;
7626                 struct ice_ring_container *rc;
7627                 struct ice_tx_ring *tx_ring;
7628                 struct ice_rx_ring *rx_ring;
7629
7630                 tx_ring = vsi->tx_rings[ch->base_q + i];
7631                 rx_ring = vsi->rx_rings[ch->base_q + i];
7632                 if (!tx_ring || !rx_ring)
7633                         continue;
7634
7635                 /* setup ring being channel enabled */
7636                 tx_ring->ch = ch;
7637                 rx_ring->ch = ch;
7638
7639                 /* following code block sets up vector specific attributes */
7640                 tx_q_vector = tx_ring->q_vector;
7641                 rx_q_vector = rx_ring->q_vector;
7642                 if (!tx_q_vector && !rx_q_vector)
7643                         continue;
7644
7645                 if (tx_q_vector) {
7646                         tx_q_vector->ch = ch;
7647                         /* setup Tx and Rx ITR setting if DIM is off */
7648                         rc = &tx_q_vector->tx;
7649                         if (!ITR_IS_DYNAMIC(rc))
7650                                 ice_write_itr(rc, rc->itr_setting);
7651                 }
7652                 if (rx_q_vector) {
7653                         rx_q_vector->ch = ch;
7654                         /* setup Tx and Rx ITR setting if DIM is off */
7655                         rc = &rx_q_vector->rx;
7656                         if (!ITR_IS_DYNAMIC(rc))
7657                                 ice_write_itr(rc, rc->itr_setting);
7658                 }
7659         }
7660
7661         /* it is safe to assume that, if channel has non-zero num_t[r]xq, then
7662          * GLINT_ITR register would have written to perform in-context
7663          * update, hence perform flush
7664          */
7665         if (ch->num_txq || ch->num_rxq)
7666                 ice_flush(&vsi->back->hw);
7667 }
7668
7669 /**
7670  * ice_cfg_chnl_all_res - configure channel resources
7671  * @vsi: pte to main_vsi
7672  * @ch: ptr to channel structure
7673  *
7674  * This function configures channel specific resources such as flow-director
7675  * counter index, and other resources such as queues, vectors, ITR settings
7676  */
7677 static void
7678 ice_cfg_chnl_all_res(struct ice_vsi *vsi, struct ice_channel *ch)
7679 {
7680         /* configure channel (aka ADQ) resources such as queues, vectors,
7681          * ITR settings for channel specific vectors and anything else
7682          */
7683         ice_chnl_cfg_res(vsi, ch);
7684 }
7685
7686 /**
7687  * ice_setup_hw_channel - setup new channel
7688  * @pf: ptr to PF device
7689  * @vsi: the VSI being setup
7690  * @ch: ptr to channel structure
7691  * @sw_id: underlying HW switching element ID
7692  * @type: type of channel to be created (VMDq2/VF)
7693  *
7694  * Setup new channel (VSI) based on specified type (VMDq2/VF)
7695  * and configures Tx rings accordingly
7696  */
7697 static int
7698 ice_setup_hw_channel(struct ice_pf *pf, struct ice_vsi *vsi,
7699                      struct ice_channel *ch, u16 sw_id, u8 type)
7700 {
7701         struct device *dev = ice_pf_to_dev(pf);
7702         int ret;
7703
7704         ch->base_q = vsi->next_base_q;
7705         ch->type = type;
7706
7707         ret = ice_add_channel(pf, sw_id, ch);
7708         if (ret) {
7709                 dev_err(dev, "failed to add_channel using sw_id %u\n", sw_id);
7710                 return ret;
7711         }
7712
7713         /* configure/setup ADQ specific resources */
7714         ice_cfg_chnl_all_res(vsi, ch);
7715
7716         /* make sure to update the next_base_q so that subsequent channel's
7717          * (aka ADQ) VSI queue map is correct
7718          */
7719         vsi->next_base_q = vsi->next_base_q + ch->num_rxq;
7720         dev_dbg(dev, "added channel: vsi_num %u, num_rxq %u\n", ch->vsi_num,
7721                 ch->num_rxq);
7722
7723         return 0;
7724 }
7725
7726 /**
7727  * ice_setup_channel - setup new channel using uplink element
7728  * @pf: ptr to PF device
7729  * @vsi: the VSI being setup
7730  * @ch: ptr to channel structure
7731  *
7732  * Setup new channel (VSI) based on specified type (VMDq2/VF)
7733  * and uplink switching element
7734  */
7735 static bool
7736 ice_setup_channel(struct ice_pf *pf, struct ice_vsi *vsi,
7737                   struct ice_channel *ch)
7738 {
7739         struct device *dev = ice_pf_to_dev(pf);
7740         u16 sw_id;
7741         int ret;
7742
7743         if (vsi->type != ICE_VSI_PF) {
7744                 dev_err(dev, "unsupported parent VSI type(%d)\n", vsi->type);
7745                 return false;
7746         }
7747
7748         sw_id = pf->first_sw->sw_id;
7749
7750         /* create channel (VSI) */
7751         ret = ice_setup_hw_channel(pf, vsi, ch, sw_id, ICE_VSI_CHNL);
7752         if (ret) {
7753                 dev_err(dev, "failed to setup hw_channel\n");
7754                 return false;
7755         }
7756         dev_dbg(dev, "successfully created channel()\n");
7757
7758         return ch->ch_vsi ? true : false;
7759 }
7760
7761 /**
7762  * ice_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
7763  * @vsi: VSI to be configured
7764  * @max_tx_rate: max Tx rate in Kbps to be configured as maximum BW limit
7765  * @min_tx_rate: min Tx rate in Kbps to be configured as minimum BW limit
7766  */
7767 static int
7768 ice_set_bw_limit(struct ice_vsi *vsi, u64 max_tx_rate, u64 min_tx_rate)
7769 {
7770         int err;
7771
7772         err = ice_set_min_bw_limit(vsi, min_tx_rate);
7773         if (err)
7774                 return err;
7775
7776         return ice_set_max_bw_limit(vsi, max_tx_rate);
7777 }
7778
7779 /**
7780  * ice_create_q_channel - function to create channel
7781  * @vsi: VSI to be configured
7782  * @ch: ptr to channel (it contains channel specific params)
7783  *
7784  * This function creates channel (VSI) using num_queues specified by user,
7785  * reconfigs RSS if needed.
7786  */
7787 static int ice_create_q_channel(struct ice_vsi *vsi, struct ice_channel *ch)
7788 {
7789         struct ice_pf *pf = vsi->back;
7790         struct device *dev;
7791
7792         if (!ch)
7793                 return -EINVAL;
7794
7795         dev = ice_pf_to_dev(pf);
7796         if (!ch->num_txq || !ch->num_rxq) {
7797                 dev_err(dev, "Invalid num_queues requested: %d\n", ch->num_rxq);
7798                 return -EINVAL;
7799         }
7800
7801         if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_txq) {
7802                 dev_err(dev, "cnt_q_avail (%u) less than num_queues %d\n",
7803                         vsi->cnt_q_avail, ch->num_txq);
7804                 return -EINVAL;
7805         }
7806
7807         if (!ice_setup_channel(pf, vsi, ch)) {
7808                 dev_info(dev, "Failed to setup channel\n");
7809                 return -EINVAL;
7810         }
7811         /* configure BW rate limit */
7812         if (ch->ch_vsi && (ch->max_tx_rate || ch->min_tx_rate)) {
7813                 int ret;
7814
7815                 ret = ice_set_bw_limit(ch->ch_vsi, ch->max_tx_rate,
7816                                        ch->min_tx_rate);
7817                 if (ret)
7818                         dev_err(dev, "failed to set Tx rate of %llu Kbps for VSI(%u)\n",
7819                                 ch->max_tx_rate, ch->ch_vsi->vsi_num);
7820                 else
7821                         dev_dbg(dev, "set Tx rate of %llu Kbps for VSI(%u)\n",
7822                                 ch->max_tx_rate, ch->ch_vsi->vsi_num);
7823         }
7824
7825         vsi->cnt_q_avail -= ch->num_txq;
7826
7827         return 0;
7828 }
7829
7830 /**
7831  * ice_rem_all_chnl_fltrs - removes all channel filters
7832  * @pf: ptr to PF, TC-flower based filter are tracked at PF level
7833  *
7834  * Remove all advanced switch filters only if they are channel specific
7835  * tc-flower based filter
7836  */
7837 static void ice_rem_all_chnl_fltrs(struct ice_pf *pf)
7838 {
7839         struct ice_tc_flower_fltr *fltr;
7840         struct hlist_node *node;
7841
7842         /* to remove all channel filters, iterate an ordered list of filters */
7843         hlist_for_each_entry_safe(fltr, node,
7844                                   &pf->tc_flower_fltr_list,
7845                                   tc_flower_node) {
7846                 struct ice_rule_query_data rule;
7847                 int status;
7848
7849                 /* for now process only channel specific filters */
7850                 if (!ice_is_chnl_fltr(fltr))
7851                         continue;
7852
7853                 rule.rid = fltr->rid;
7854                 rule.rule_id = fltr->rule_id;
7855                 rule.vsi_handle = fltr->dest_id;
7856                 status = ice_rem_adv_rule_by_id(&pf->hw, &rule);
7857                 if (status) {
7858                         if (status == -ENOENT)
7859                                 dev_dbg(ice_pf_to_dev(pf), "TC flower filter (rule_id %u) does not exist\n",
7860                                         rule.rule_id);
7861                         else
7862                                 dev_err(ice_pf_to_dev(pf), "failed to delete TC flower filter, status %d\n",
7863                                         status);
7864                 } else if (fltr->dest_vsi) {
7865                         /* update advanced switch filter count */
7866                         if (fltr->dest_vsi->type == ICE_VSI_CHNL) {
7867                                 u32 flags = fltr->flags;
7868
7869                                 fltr->dest_vsi->num_chnl_fltr--;
7870                                 if (flags & (ICE_TC_FLWR_FIELD_DST_MAC |
7871                                              ICE_TC_FLWR_FIELD_ENC_DST_MAC))
7872                                         pf->num_dmac_chnl_fltrs--;
7873                         }
7874                 }
7875
7876                 hlist_del(&fltr->tc_flower_node);
7877                 kfree(fltr);
7878         }
7879 }
7880
7881 /**
7882  * ice_remove_q_channels - Remove queue channels for the TCs
7883  * @vsi: VSI to be configured
7884  * @rem_fltr: delete advanced switch filter or not
7885  *
7886  * Remove queue channels for the TCs
7887  */
7888 static void ice_remove_q_channels(struct ice_vsi *vsi, bool rem_fltr)
7889 {
7890         struct ice_channel *ch, *ch_tmp;
7891         struct ice_pf *pf = vsi->back;
7892         int i;
7893
7894         /* remove all tc-flower based filter if they are channel filters only */
7895         if (rem_fltr)
7896                 ice_rem_all_chnl_fltrs(pf);
7897
7898         /* perform cleanup for channels if they exist */
7899         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
7900                 struct ice_vsi *ch_vsi;
7901
7902                 list_del(&ch->list);
7903                 ch_vsi = ch->ch_vsi;
7904                 if (!ch_vsi) {
7905                         kfree(ch);
7906                         continue;
7907                 }
7908
7909                 /* Reset queue contexts */
7910                 for (i = 0; i < ch->num_rxq; i++) {
7911                         struct ice_tx_ring *tx_ring;
7912                         struct ice_rx_ring *rx_ring;
7913
7914                         tx_ring = vsi->tx_rings[ch->base_q + i];
7915                         rx_ring = vsi->rx_rings[ch->base_q + i];
7916                         if (tx_ring) {
7917                                 tx_ring->ch = NULL;
7918                                 if (tx_ring->q_vector)
7919                                         tx_ring->q_vector->ch = NULL;
7920                         }
7921                         if (rx_ring) {
7922                                 rx_ring->ch = NULL;
7923                                 if (rx_ring->q_vector)
7924                                         rx_ring->q_vector->ch = NULL;
7925                         }
7926                 }
7927
7928                 /* clear the VSI from scheduler tree */
7929                 ice_rm_vsi_lan_cfg(ch->ch_vsi->port_info, ch->ch_vsi->idx);
7930
7931                 /* Delete VSI from FW */
7932                 ice_vsi_delete(ch->ch_vsi);
7933
7934                 /* Delete VSI from PF and HW VSI arrays */
7935                 ice_vsi_clear(ch->ch_vsi);
7936
7937                 /* free the channel */
7938                 kfree(ch);
7939         }
7940
7941         /* clear the channel VSI map which is stored in main VSI */
7942         ice_for_each_chnl_tc(i)
7943                 vsi->tc_map_vsi[i] = NULL;
7944
7945         /* reset main VSI's all TC information */
7946         vsi->all_enatc = 0;
7947         vsi->all_numtc = 0;
7948 }
7949
7950 /**
7951  * ice_rebuild_channels - rebuild channel
7952  * @pf: ptr to PF
7953  *
7954  * Recreate channel VSIs and replay filters
7955  */
7956 static int ice_rebuild_channels(struct ice_pf *pf)
7957 {
7958         struct device *dev = ice_pf_to_dev(pf);
7959         struct ice_vsi *main_vsi;
7960         bool rem_adv_fltr = true;
7961         struct ice_channel *ch;
7962         struct ice_vsi *vsi;
7963         int tc_idx = 1;
7964         int i, err;
7965
7966         main_vsi = ice_get_main_vsi(pf);
7967         if (!main_vsi)
7968                 return 0;
7969
7970         if (!test_bit(ICE_FLAG_TC_MQPRIO, pf->flags) ||
7971             main_vsi->old_numtc == 1)
7972                 return 0; /* nothing to be done */
7973
7974         /* reconfigure main VSI based on old value of TC and cached values
7975          * for MQPRIO opts
7976          */
7977         err = ice_vsi_cfg_tc(main_vsi, main_vsi->old_ena_tc);
7978         if (err) {
7979                 dev_err(dev, "failed configuring TC(ena_tc:0x%02x) for HW VSI=%u\n",
7980                         main_vsi->old_ena_tc, main_vsi->vsi_num);
7981                 return err;
7982         }
7983
7984         /* rebuild ADQ VSIs */
7985         ice_for_each_vsi(pf, i) {
7986                 enum ice_vsi_type type;
7987
7988                 vsi = pf->vsi[i];
7989                 if (!vsi || vsi->type != ICE_VSI_CHNL)
7990                         continue;
7991
7992                 type = vsi->type;
7993
7994                 /* rebuild ADQ VSI */
7995                 err = ice_vsi_rebuild(vsi, true);
7996                 if (err) {
7997                         dev_err(dev, "VSI (type:%s) at index %d rebuild failed, err %d\n",
7998                                 ice_vsi_type_str(type), vsi->idx, err);
7999                         goto cleanup;
8000                 }
8001
8002                 /* Re-map HW VSI number, using VSI handle that has been
8003                  * previously validated in ice_replay_vsi() call above
8004                  */
8005                 vsi->vsi_num = ice_get_hw_vsi_num(&pf->hw, vsi->idx);
8006
8007                 /* replay filters for the VSI */
8008                 err = ice_replay_vsi(&pf->hw, vsi->idx);
8009                 if (err) {
8010                         dev_err(dev, "VSI (type:%s) replay failed, err %d, VSI index %d\n",
8011                                 ice_vsi_type_str(type), err, vsi->idx);
8012                         rem_adv_fltr = false;
8013                         goto cleanup;
8014                 }
8015                 dev_info(dev, "VSI (type:%s) at index %d rebuilt successfully\n",
8016                          ice_vsi_type_str(type), vsi->idx);
8017
8018                 /* store ADQ VSI at correct TC index in main VSI's
8019                  * map of TC to VSI
8020                  */
8021                 main_vsi->tc_map_vsi[tc_idx++] = vsi;
8022         }
8023
8024         /* ADQ VSI(s) has been rebuilt successfully, so setup
8025          * channel for main VSI's Tx and Rx rings
8026          */
8027         list_for_each_entry(ch, &main_vsi->ch_list, list) {
8028                 struct ice_vsi *ch_vsi;
8029
8030                 ch_vsi = ch->ch_vsi;
8031                 if (!ch_vsi)
8032                         continue;
8033
8034                 /* reconfig channel resources */
8035                 ice_cfg_chnl_all_res(main_vsi, ch);
8036
8037                 /* replay BW rate limit if it is non-zero */
8038                 if (!ch->max_tx_rate && !ch->min_tx_rate)
8039                         continue;
8040
8041                 err = ice_set_bw_limit(ch_vsi, ch->max_tx_rate,
8042                                        ch->min_tx_rate);
8043                 if (err)
8044                         dev_err(dev, "failed (err:%d) to rebuild BW rate limit, max_tx_rate: %llu Kbps, min_tx_rate: %llu Kbps for VSI(%u)\n",
8045                                 err, ch->max_tx_rate, ch->min_tx_rate,
8046                                 ch_vsi->vsi_num);
8047                 else
8048                         dev_dbg(dev, "successfully rebuild BW rate limit, max_tx_rate: %llu Kbps, min_tx_rate: %llu Kbps for VSI(%u)\n",
8049                                 ch->max_tx_rate, ch->min_tx_rate,
8050                                 ch_vsi->vsi_num);
8051         }
8052
8053         /* reconfig RSS for main VSI */
8054         if (main_vsi->ch_rss_size)
8055                 ice_vsi_cfg_rss_lut_key(main_vsi);
8056
8057         return 0;
8058
8059 cleanup:
8060         ice_remove_q_channels(main_vsi, rem_adv_fltr);
8061         return err;
8062 }
8063
8064 /**
8065  * ice_create_q_channels - Add queue channel for the given TCs
8066  * @vsi: VSI to be configured
8067  *
8068  * Configures queue channel mapping to the given TCs
8069  */
8070 static int ice_create_q_channels(struct ice_vsi *vsi)
8071 {
8072         struct ice_pf *pf = vsi->back;
8073         struct ice_channel *ch;
8074         int ret = 0, i;
8075
8076         ice_for_each_chnl_tc(i) {
8077                 if (!(vsi->all_enatc & BIT(i)))
8078                         continue;
8079
8080                 ch = kzalloc(sizeof(*ch), GFP_KERNEL);
8081                 if (!ch) {
8082                         ret = -ENOMEM;
8083                         goto err_free;
8084                 }
8085                 INIT_LIST_HEAD(&ch->list);
8086                 ch->num_rxq = vsi->mqprio_qopt.qopt.count[i];
8087                 ch->num_txq = vsi->mqprio_qopt.qopt.count[i];
8088                 ch->base_q = vsi->mqprio_qopt.qopt.offset[i];
8089                 ch->max_tx_rate = vsi->mqprio_qopt.max_rate[i];
8090                 ch->min_tx_rate = vsi->mqprio_qopt.min_rate[i];
8091
8092                 /* convert to Kbits/s */
8093                 if (ch->max_tx_rate)
8094                         ch->max_tx_rate = div_u64(ch->max_tx_rate,
8095                                                   ICE_BW_KBPS_DIVISOR);
8096                 if (ch->min_tx_rate)
8097                         ch->min_tx_rate = div_u64(ch->min_tx_rate,
8098                                                   ICE_BW_KBPS_DIVISOR);
8099
8100                 ret = ice_create_q_channel(vsi, ch);
8101                 if (ret) {
8102                         dev_err(ice_pf_to_dev(pf),
8103                                 "failed creating channel TC:%d\n", i);
8104                         kfree(ch);
8105                         goto err_free;
8106                 }
8107                 list_add_tail(&ch->list, &vsi->ch_list);
8108                 vsi->tc_map_vsi[i] = ch->ch_vsi;
8109                 dev_dbg(ice_pf_to_dev(pf),
8110                         "successfully created channel: VSI %pK\n", ch->ch_vsi);
8111         }
8112         return 0;
8113
8114 err_free:
8115         ice_remove_q_channels(vsi, false);
8116
8117         return ret;
8118 }
8119
8120 /**
8121  * ice_setup_tc_mqprio_qdisc - configure multiple traffic classes
8122  * @netdev: net device to configure
8123  * @type_data: TC offload data
8124  */
8125 static int ice_setup_tc_mqprio_qdisc(struct net_device *netdev, void *type_data)
8126 {
8127         struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
8128         struct ice_netdev_priv *np = netdev_priv(netdev);
8129         struct ice_vsi *vsi = np->vsi;
8130         struct ice_pf *pf = vsi->back;
8131         u16 mode, ena_tc_qdisc = 0;
8132         int cur_txq, cur_rxq;
8133         u8 hw = 0, num_tcf;
8134         struct device *dev;
8135         int ret, i;
8136
8137         dev = ice_pf_to_dev(pf);
8138         num_tcf = mqprio_qopt->qopt.num_tc;
8139         hw = mqprio_qopt->qopt.hw;
8140         mode = mqprio_qopt->mode;
8141         if (!hw) {
8142                 clear_bit(ICE_FLAG_TC_MQPRIO, pf->flags);
8143                 vsi->ch_rss_size = 0;
8144                 memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8145                 goto config_tcf;
8146         }
8147
8148         /* Generate queue region map for number of TCF requested */
8149         for (i = 0; i < num_tcf; i++)
8150                 ena_tc_qdisc |= BIT(i);
8151
8152         switch (mode) {
8153         case TC_MQPRIO_MODE_CHANNEL:
8154
8155                 ret = ice_validate_mqprio_qopt(vsi, mqprio_qopt);
8156                 if (ret) {
8157                         netdev_err(netdev, "failed to validate_mqprio_qopt(), ret %d\n",
8158                                    ret);
8159                         return ret;
8160                 }
8161                 memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8162                 set_bit(ICE_FLAG_TC_MQPRIO, pf->flags);
8163                 /* don't assume state of hw_tc_offload during driver load
8164                  * and set the flag for TC flower filter if hw_tc_offload
8165                  * already ON
8166                  */
8167                 if (vsi->netdev->features & NETIF_F_HW_TC)
8168                         set_bit(ICE_FLAG_CLS_FLOWER, pf->flags);
8169                 break;
8170         default:
8171                 return -EINVAL;
8172         }
8173
8174 config_tcf:
8175
8176         /* Requesting same TCF configuration as already enabled */
8177         if (ena_tc_qdisc == vsi->tc_cfg.ena_tc &&
8178             mode != TC_MQPRIO_MODE_CHANNEL)
8179                 return 0;
8180
8181         /* Pause VSI queues */
8182         ice_dis_vsi(vsi, true);
8183
8184         if (!hw && !test_bit(ICE_FLAG_TC_MQPRIO, pf->flags))
8185                 ice_remove_q_channels(vsi, true);
8186
8187         if (!hw && !test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) {
8188                 vsi->req_txq = min_t(int, ice_get_avail_txq_count(pf),
8189                                      num_online_cpus());
8190                 vsi->req_rxq = min_t(int, ice_get_avail_rxq_count(pf),
8191                                      num_online_cpus());
8192         } else {
8193                 /* logic to rebuild VSI, same like ethtool -L */
8194                 u16 offset = 0, qcount_tx = 0, qcount_rx = 0;
8195
8196                 for (i = 0; i < num_tcf; i++) {
8197                         if (!(ena_tc_qdisc & BIT(i)))
8198                                 continue;
8199
8200                         offset = vsi->mqprio_qopt.qopt.offset[i];
8201                         qcount_rx = vsi->mqprio_qopt.qopt.count[i];
8202                         qcount_tx = vsi->mqprio_qopt.qopt.count[i];
8203                 }
8204                 vsi->req_txq = offset + qcount_tx;
8205                 vsi->req_rxq = offset + qcount_rx;
8206
8207                 /* store away original rss_size info, so that it gets reused
8208                  * form ice_vsi_rebuild during tc-qdisc delete stage - to
8209                  * determine, what should be the rss_sizefor main VSI
8210                  */
8211                 vsi->orig_rss_size = vsi->rss_size;
8212         }
8213
8214         /* save current values of Tx and Rx queues before calling VSI rebuild
8215          * for fallback option
8216          */
8217         cur_txq = vsi->num_txq;
8218         cur_rxq = vsi->num_rxq;
8219
8220         /* proceed with rebuild main VSI using correct number of queues */
8221         ret = ice_vsi_rebuild(vsi, false);
8222         if (ret) {
8223                 /* fallback to current number of queues */
8224                 dev_info(dev, "Rebuild failed with new queues, try with current number of queues\n");
8225                 vsi->req_txq = cur_txq;
8226                 vsi->req_rxq = cur_rxq;
8227                 clear_bit(ICE_RESET_FAILED, pf->state);
8228                 if (ice_vsi_rebuild(vsi, false)) {
8229                         dev_err(dev, "Rebuild of main VSI failed again\n");
8230                         return ret;
8231                 }
8232         }
8233
8234         vsi->all_numtc = num_tcf;
8235         vsi->all_enatc = ena_tc_qdisc;
8236         ret = ice_vsi_cfg_tc(vsi, ena_tc_qdisc);
8237         if (ret) {
8238                 netdev_err(netdev, "failed configuring TC for VSI id=%d\n",
8239                            vsi->vsi_num);
8240                 goto exit;
8241         }
8242
8243         if (test_bit(ICE_FLAG_TC_MQPRIO, pf->flags)) {
8244                 u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0];
8245                 u64 min_tx_rate = vsi->mqprio_qopt.min_rate[0];
8246
8247                 /* set TC0 rate limit if specified */
8248                 if (max_tx_rate || min_tx_rate) {
8249                         /* convert to Kbits/s */
8250                         if (max_tx_rate)
8251                                 max_tx_rate = div_u64(max_tx_rate, ICE_BW_KBPS_DIVISOR);
8252                         if (min_tx_rate)
8253                                 min_tx_rate = div_u64(min_tx_rate, ICE_BW_KBPS_DIVISOR);
8254
8255                         ret = ice_set_bw_limit(vsi, max_tx_rate, min_tx_rate);
8256                         if (!ret) {
8257                                 dev_dbg(dev, "set Tx rate max %llu min %llu for VSI(%u)\n",
8258                                         max_tx_rate, min_tx_rate, vsi->vsi_num);
8259                         } else {
8260                                 dev_err(dev, "failed to set Tx rate max %llu min %llu for VSI(%u)\n",
8261                                         max_tx_rate, min_tx_rate, vsi->vsi_num);
8262                                 goto exit;
8263                         }
8264                 }
8265                 ret = ice_create_q_channels(vsi);
8266                 if (ret) {
8267                         netdev_err(netdev, "failed configuring queue channels\n");
8268                         goto exit;
8269                 } else {
8270                         netdev_dbg(netdev, "successfully configured channels\n");
8271                 }
8272         }
8273
8274         if (vsi->ch_rss_size)
8275                 ice_vsi_cfg_rss_lut_key(vsi);
8276
8277 exit:
8278         /* if error, reset the all_numtc and all_enatc */
8279         if (ret) {
8280                 vsi->all_numtc = 0;
8281                 vsi->all_enatc = 0;
8282         }
8283         /* resume VSI */
8284         ice_ena_vsi(vsi, true);
8285
8286         return ret;
8287 }
8288
8289 static LIST_HEAD(ice_block_cb_list);
8290
8291 static int
8292 ice_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8293              void *type_data)
8294 {
8295         struct ice_netdev_priv *np = netdev_priv(netdev);
8296         struct ice_pf *pf = np->vsi->back;
8297         int err;
8298
8299         switch (type) {
8300         case TC_SETUP_BLOCK:
8301                 return flow_block_cb_setup_simple(type_data,
8302                                                   &ice_block_cb_list,
8303                                                   ice_setup_tc_block_cb,
8304                                                   np, np, true);
8305         case TC_SETUP_QDISC_MQPRIO:
8306                 /* setup traffic classifier for receive side */
8307                 mutex_lock(&pf->tc_mutex);
8308                 err = ice_setup_tc_mqprio_qdisc(netdev, type_data);
8309                 mutex_unlock(&pf->tc_mutex);
8310                 return err;
8311         default:
8312                 return -EOPNOTSUPP;
8313         }
8314         return -EOPNOTSUPP;
8315 }
8316
8317 static struct ice_indr_block_priv *
8318 ice_indr_block_priv_lookup(struct ice_netdev_priv *np,
8319                            struct net_device *netdev)
8320 {
8321         struct ice_indr_block_priv *cb_priv;
8322
8323         list_for_each_entry(cb_priv, &np->tc_indr_block_priv_list, list) {
8324                 if (!cb_priv->netdev)
8325                         return NULL;
8326                 if (cb_priv->netdev == netdev)
8327                         return cb_priv;
8328         }
8329         return NULL;
8330 }
8331
8332 static int
8333 ice_indr_setup_block_cb(enum tc_setup_type type, void *type_data,
8334                         void *indr_priv)
8335 {
8336         struct ice_indr_block_priv *priv = indr_priv;
8337         struct ice_netdev_priv *np = priv->np;
8338
8339         switch (type) {
8340         case TC_SETUP_CLSFLOWER:
8341                 return ice_setup_tc_cls_flower(np, priv->netdev,
8342                                                (struct flow_cls_offload *)
8343                                                type_data);
8344         default:
8345                 return -EOPNOTSUPP;
8346         }
8347 }
8348
8349 static int
8350 ice_indr_setup_tc_block(struct net_device *netdev, struct Qdisc *sch,
8351                         struct ice_netdev_priv *np,
8352                         struct flow_block_offload *f, void *data,
8353                         void (*cleanup)(struct flow_block_cb *block_cb))
8354 {
8355         struct ice_indr_block_priv *indr_priv;
8356         struct flow_block_cb *block_cb;
8357
8358         if (!ice_is_tunnel_supported(netdev) &&
8359             !(is_vlan_dev(netdev) &&
8360               vlan_dev_real_dev(netdev) == np->vsi->netdev))
8361                 return -EOPNOTSUPP;
8362
8363         if (f->binder_type != FLOW_BLOCK_BINDER_TYPE_CLSACT_INGRESS)
8364                 return -EOPNOTSUPP;
8365
8366         switch (f->command) {
8367         case FLOW_BLOCK_BIND:
8368                 indr_priv = ice_indr_block_priv_lookup(np, netdev);
8369                 if (indr_priv)
8370                         return -EEXIST;
8371
8372                 indr_priv = kzalloc(sizeof(*indr_priv), GFP_KERNEL);
8373                 if (!indr_priv)
8374                         return -ENOMEM;
8375
8376                 indr_priv->netdev = netdev;
8377                 indr_priv->np = np;
8378                 list_add(&indr_priv->list, &np->tc_indr_block_priv_list);
8379
8380                 block_cb =
8381                         flow_indr_block_cb_alloc(ice_indr_setup_block_cb,
8382                                                  indr_priv, indr_priv,
8383                                                  ice_rep_indr_tc_block_unbind,
8384                                                  f, netdev, sch, data, np,
8385                                                  cleanup);
8386
8387                 if (IS_ERR(block_cb)) {
8388                         list_del(&indr_priv->list);
8389                         kfree(indr_priv);
8390                         return PTR_ERR(block_cb);
8391                 }
8392                 flow_block_cb_add(block_cb, f);
8393                 list_add_tail(&block_cb->driver_list, &ice_block_cb_list);
8394                 break;
8395         case FLOW_BLOCK_UNBIND:
8396                 indr_priv = ice_indr_block_priv_lookup(np, netdev);
8397                 if (!indr_priv)
8398                         return -ENOENT;
8399
8400                 block_cb = flow_block_cb_lookup(f->block,
8401                                                 ice_indr_setup_block_cb,
8402                                                 indr_priv);
8403                 if (!block_cb)
8404                         return -ENOENT;
8405
8406                 flow_indr_block_cb_remove(block_cb, f);
8407
8408                 list_del(&block_cb->driver_list);
8409                 break;
8410         default:
8411                 return -EOPNOTSUPP;
8412         }
8413         return 0;
8414 }
8415
8416 static int
8417 ice_indr_setup_tc_cb(struct net_device *netdev, struct Qdisc *sch,
8418                      void *cb_priv, enum tc_setup_type type, void *type_data,
8419                      void *data,
8420                      void (*cleanup)(struct flow_block_cb *block_cb))
8421 {
8422         switch (type) {
8423         case TC_SETUP_BLOCK:
8424                 return ice_indr_setup_tc_block(netdev, sch, cb_priv, type_data,
8425                                                data, cleanup);
8426
8427         default:
8428                 return -EOPNOTSUPP;
8429         }
8430 }
8431
8432 /**
8433  * ice_open - Called when a network interface becomes active
8434  * @netdev: network interface device structure
8435  *
8436  * The open entry point is called when a network interface is made
8437  * active by the system (IFF_UP). At this point all resources needed
8438  * for transmit and receive operations are allocated, the interrupt
8439  * handler is registered with the OS, the netdev watchdog is enabled,
8440  * and the stack is notified that the interface is ready.
8441  *
8442  * Returns 0 on success, negative value on failure
8443  */
8444 int ice_open(struct net_device *netdev)
8445 {
8446         struct ice_netdev_priv *np = netdev_priv(netdev);
8447         struct ice_pf *pf = np->vsi->back;
8448
8449         if (ice_is_reset_in_progress(pf->state)) {
8450                 netdev_err(netdev, "can't open net device while reset is in progress");
8451                 return -EBUSY;
8452         }
8453
8454         return ice_open_internal(netdev);
8455 }
8456
8457 /**
8458  * ice_open_internal - Called when a network interface becomes active
8459  * @netdev: network interface device structure
8460  *
8461  * Internal ice_open implementation. Should not be used directly except for ice_open and reset
8462  * handling routine
8463  *
8464  * Returns 0 on success, negative value on failure
8465  */
8466 int ice_open_internal(struct net_device *netdev)
8467 {
8468         struct ice_netdev_priv *np = netdev_priv(netdev);
8469         struct ice_vsi *vsi = np->vsi;
8470         struct ice_pf *pf = vsi->back;
8471         struct ice_port_info *pi;
8472         enum ice_status status;
8473         int err;
8474
8475         if (test_bit(ICE_NEEDS_RESTART, pf->state)) {
8476                 netdev_err(netdev, "driver needs to be unloaded and reloaded\n");
8477                 return -EIO;
8478         }
8479
8480         netif_carrier_off(netdev);
8481
8482         pi = vsi->port_info;
8483         status = ice_update_link_info(pi);
8484         if (status) {
8485                 netdev_err(netdev, "Failed to get link info, error %s\n",
8486                            ice_stat_str(status));
8487                 return -EIO;
8488         }
8489
8490         ice_check_link_cfg_err(pf, pi->phy.link_info.link_cfg_err);
8491
8492         /* Set PHY if there is media, otherwise, turn off PHY */
8493         if (pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE) {
8494                 clear_bit(ICE_FLAG_NO_MEDIA, pf->flags);
8495                 if (!test_bit(ICE_PHY_INIT_COMPLETE, pf->state)) {
8496                         err = ice_init_phy_user_cfg(pi);
8497                         if (err) {
8498                                 netdev_err(netdev, "Failed to initialize PHY settings, error %d\n",
8499                                            err);
8500                                 return err;
8501                         }
8502                 }
8503
8504                 err = ice_configure_phy(vsi);
8505                 if (err) {
8506                         netdev_err(netdev, "Failed to set physical link up, error %d\n",
8507                                    err);
8508                         return err;
8509                 }
8510         } else {
8511                 set_bit(ICE_FLAG_NO_MEDIA, pf->flags);
8512                 ice_set_link(vsi, false);
8513         }
8514
8515         err = ice_vsi_open(vsi);
8516         if (err)
8517                 netdev_err(netdev, "Failed to open VSI 0x%04X on switch 0x%04X\n",
8518                            vsi->vsi_num, vsi->vsw->sw_id);
8519
8520         /* Update existing tunnels information */
8521         udp_tunnel_get_rx_info(netdev);
8522
8523         return err;
8524 }
8525
8526 /**
8527  * ice_stop - Disables a network interface
8528  * @netdev: network interface device structure
8529  *
8530  * The stop entry point is called when an interface is de-activated by the OS,
8531  * and the netdevice enters the DOWN state. The hardware is still under the
8532  * driver's control, but the netdev interface is disabled.
8533  *
8534  * Returns success only - not allowed to fail
8535  */
8536 int ice_stop(struct net_device *netdev)
8537 {
8538         struct ice_netdev_priv *np = netdev_priv(netdev);
8539         struct ice_vsi *vsi = np->vsi;
8540         struct ice_pf *pf = vsi->back;
8541
8542         if (ice_is_reset_in_progress(pf->state)) {
8543                 netdev_err(netdev, "can't stop net device while reset is in progress");
8544                 return -EBUSY;
8545         }
8546
8547         ice_vsi_close(vsi);
8548
8549         return 0;
8550 }
8551
8552 /**
8553  * ice_features_check - Validate encapsulated packet conforms to limits
8554  * @skb: skb buffer
8555  * @netdev: This port's netdev
8556  * @features: Offload features that the stack believes apply
8557  */
8558 static netdev_features_t
8559 ice_features_check(struct sk_buff *skb,
8560                    struct net_device __always_unused *netdev,
8561                    netdev_features_t features)
8562 {
8563         size_t len;
8564
8565         /* No point in doing any of this if neither checksum nor GSO are
8566          * being requested for this frame. We can rule out both by just
8567          * checking for CHECKSUM_PARTIAL
8568          */
8569         if (skb->ip_summed != CHECKSUM_PARTIAL)
8570                 return features;
8571
8572         /* We cannot support GSO if the MSS is going to be less than
8573          * 64 bytes. If it is then we need to drop support for GSO.
8574          */
8575         if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
8576                 features &= ~NETIF_F_GSO_MASK;
8577
8578         len = skb_network_header(skb) - skb->data;
8579         if (len > ICE_TXD_MACLEN_MAX || len & 0x1)
8580                 goto out_rm_features;
8581
8582         len = skb_transport_header(skb) - skb_network_header(skb);
8583         if (len > ICE_TXD_IPLEN_MAX || len & 0x1)
8584                 goto out_rm_features;
8585
8586         if (skb->encapsulation) {
8587                 len = skb_inner_network_header(skb) - skb_transport_header(skb);
8588                 if (len > ICE_TXD_L4LEN_MAX || len & 0x1)
8589                         goto out_rm_features;
8590
8591                 len = skb_inner_transport_header(skb) -
8592                       skb_inner_network_header(skb);
8593                 if (len > ICE_TXD_IPLEN_MAX || len & 0x1)
8594                         goto out_rm_features;
8595         }
8596
8597         return features;
8598 out_rm_features:
8599         return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
8600 }
8601
8602 static const struct net_device_ops ice_netdev_safe_mode_ops = {
8603         .ndo_open = ice_open,
8604         .ndo_stop = ice_stop,
8605         .ndo_start_xmit = ice_start_xmit,
8606         .ndo_set_mac_address = ice_set_mac_address,
8607         .ndo_validate_addr = eth_validate_addr,
8608         .ndo_change_mtu = ice_change_mtu,
8609         .ndo_get_stats64 = ice_get_stats64,
8610         .ndo_tx_timeout = ice_tx_timeout,
8611         .ndo_bpf = ice_xdp_safe_mode,
8612 };
8613
8614 static const struct net_device_ops ice_netdev_ops = {
8615         .ndo_open = ice_open,
8616         .ndo_stop = ice_stop,
8617         .ndo_start_xmit = ice_start_xmit,
8618         .ndo_select_queue = ice_select_queue,
8619         .ndo_features_check = ice_features_check,
8620         .ndo_set_rx_mode = ice_set_rx_mode,
8621         .ndo_set_mac_address = ice_set_mac_address,
8622         .ndo_validate_addr = eth_validate_addr,
8623         .ndo_change_mtu = ice_change_mtu,
8624         .ndo_get_stats64 = ice_get_stats64,
8625         .ndo_set_tx_maxrate = ice_set_tx_maxrate,
8626         .ndo_eth_ioctl = ice_eth_ioctl,
8627         .ndo_set_vf_spoofchk = ice_set_vf_spoofchk,
8628         .ndo_set_vf_mac = ice_set_vf_mac,
8629         .ndo_get_vf_config = ice_get_vf_cfg,
8630         .ndo_set_vf_trust = ice_set_vf_trust,
8631         .ndo_set_vf_vlan = ice_set_vf_port_vlan,
8632         .ndo_set_vf_link_state = ice_set_vf_link_state,
8633         .ndo_get_vf_stats = ice_get_vf_stats,
8634         .ndo_set_vf_rate = ice_set_vf_bw,
8635         .ndo_vlan_rx_add_vid = ice_vlan_rx_add_vid,
8636         .ndo_vlan_rx_kill_vid = ice_vlan_rx_kill_vid,
8637         .ndo_setup_tc = ice_setup_tc,
8638         .ndo_set_features = ice_set_features,
8639         .ndo_bridge_getlink = ice_bridge_getlink,
8640         .ndo_bridge_setlink = ice_bridge_setlink,
8641         .ndo_fdb_add = ice_fdb_add,
8642         .ndo_fdb_del = ice_fdb_del,
8643 #ifdef CONFIG_RFS_ACCEL
8644         .ndo_rx_flow_steer = ice_rx_flow_steer,
8645 #endif
8646         .ndo_tx_timeout = ice_tx_timeout,
8647         .ndo_bpf = ice_xdp,
8648         .ndo_xdp_xmit = ice_xdp_xmit,
8649         .ndo_xsk_wakeup = ice_xsk_wakeup,
8650 };