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