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