ice: Refactor ice_set/get_rss into LUT and key specific functions
[linux-2.6-microblaze.git] / drivers / net / ethernet / intel / ice / ice_main.c
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2018, Intel Corporation. */
3
4 /* Intel(R) Ethernet Connection E800 Series Linux Driver */
5
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7
8 #include <generated/utsrelease.h>
9 #include "ice.h"
10 #include "ice_base.h"
11 #include "ice_lib.h"
12 #include "ice_fltr.h"
13 #include "ice_dcb_lib.h"
14 #include "ice_dcb_nl.h"
15 #include "ice_devlink.h"
16
17 #define DRV_SUMMARY     "Intel(R) Ethernet Connection E800 Series Linux Driver"
18 static const char ice_driver_string[] = DRV_SUMMARY;
19 static const char ice_copyright[] = "Copyright (c) 2018, Intel Corporation.";
20
21 /* DDP Package file located in firmware search paths (e.g. /lib/firmware/) */
22 #define ICE_DDP_PKG_PATH        "intel/ice/ddp/"
23 #define ICE_DDP_PKG_FILE        ICE_DDP_PKG_PATH "ice.pkg"
24
25 MODULE_AUTHOR("Intel Corporation, <linux.nics@intel.com>");
26 MODULE_DESCRIPTION(DRV_SUMMARY);
27 MODULE_LICENSE("GPL v2");
28 MODULE_FIRMWARE(ICE_DDP_PKG_FILE);
29
30 static int debug = -1;
31 module_param(debug, int, 0644);
32 #ifndef CONFIG_DYNAMIC_DEBUG
33 MODULE_PARM_DESC(debug, "netif level (0=none,...,16=all), hw debug_mask (0x8XXXXXXX)");
34 #else
35 MODULE_PARM_DESC(debug, "netif level (0=none,...,16=all)");
36 #endif /* !CONFIG_DYNAMIC_DEBUG */
37
38 static struct workqueue_struct *ice_wq;
39 static const struct net_device_ops ice_netdev_safe_mode_ops;
40 static const struct net_device_ops ice_netdev_ops;
41 static int ice_vsi_open(struct ice_vsi *vsi);
42
43 static void ice_rebuild(struct ice_pf *pf, enum ice_reset_req reset_type);
44
45 static void ice_vsi_release_all(struct ice_pf *pf);
46
47 bool netif_is_ice(struct net_device *dev)
48 {
49         return dev && (dev->netdev_ops == &ice_netdev_ops);
50 }
51
52 /**
53  * ice_get_tx_pending - returns number of Tx descriptors not processed
54  * @ring: the ring of descriptors
55  */
56 static u16 ice_get_tx_pending(struct ice_ring *ring)
57 {
58         u16 head, tail;
59
60         head = ring->next_to_clean;
61         tail = ring->next_to_use;
62
63         if (head != tail)
64                 return (head < tail) ?
65                         tail - head : (tail + ring->count - head);
66         return 0;
67 }
68
69 /**
70  * ice_check_for_hang_subtask - check for and recover hung queues
71  * @pf: pointer to PF struct
72  */
73 static void ice_check_for_hang_subtask(struct ice_pf *pf)
74 {
75         struct ice_vsi *vsi = NULL;
76         struct ice_hw *hw;
77         unsigned int i;
78         int packets;
79         u32 v;
80
81         ice_for_each_vsi(pf, v)
82                 if (pf->vsi[v] && pf->vsi[v]->type == ICE_VSI_PF) {
83                         vsi = pf->vsi[v];
84                         break;
85                 }
86
87         if (!vsi || test_bit(__ICE_DOWN, vsi->state))
88                 return;
89
90         if (!(vsi->netdev && netif_carrier_ok(vsi->netdev)))
91                 return;
92
93         hw = &vsi->back->hw;
94
95         for (i = 0; i < vsi->num_txq; i++) {
96                 struct ice_ring *tx_ring = vsi->tx_rings[i];
97
98                 if (tx_ring && tx_ring->desc) {
99                         /* If packet counter has not changed the queue is
100                          * likely stalled, so force an interrupt for this
101                          * queue.
102                          *
103                          * prev_pkt would be negative if there was no
104                          * pending work.
105                          */
106                         packets = tx_ring->stats.pkts & INT_MAX;
107                         if (tx_ring->tx_stats.prev_pkt == packets) {
108                                 /* Trigger sw interrupt to revive the queue */
109                                 ice_trigger_sw_intr(hw, tx_ring->q_vector);
110                                 continue;
111                         }
112
113                         /* Memory barrier between read of packet count and call
114                          * to ice_get_tx_pending()
115                          */
116                         smp_rmb();
117                         tx_ring->tx_stats.prev_pkt =
118                             ice_get_tx_pending(tx_ring) ? packets : -1;
119                 }
120         }
121 }
122
123 /**
124  * ice_init_mac_fltr - Set initial MAC filters
125  * @pf: board private structure
126  *
127  * Set initial set of MAC filters for PF VSI; configure filters for permanent
128  * address and broadcast address. If an error is encountered, netdevice will be
129  * unregistered.
130  */
131 static int ice_init_mac_fltr(struct ice_pf *pf)
132 {
133         enum ice_status status;
134         struct ice_vsi *vsi;
135         u8 *perm_addr;
136
137         vsi = ice_get_main_vsi(pf);
138         if (!vsi)
139                 return -EINVAL;
140
141         perm_addr = vsi->port_info->mac.perm_addr;
142         status = ice_fltr_add_mac_and_broadcast(vsi, perm_addr, ICE_FWD_TO_VSI);
143         if (status)
144                 return -EIO;
145
146         return 0;
147 }
148
149 /**
150  * ice_add_mac_to_sync_list - creates list of MAC addresses to be synced
151  * @netdev: the net device on which the sync is happening
152  * @addr: MAC address to sync
153  *
154  * This is a callback function which is called by the in kernel device sync
155  * functions (like __dev_uc_sync, __dev_mc_sync, etc). This function only
156  * populates the tmp_sync_list, which is later used by ice_add_mac to add the
157  * MAC filters from the hardware.
158  */
159 static int ice_add_mac_to_sync_list(struct net_device *netdev, const u8 *addr)
160 {
161         struct ice_netdev_priv *np = netdev_priv(netdev);
162         struct ice_vsi *vsi = np->vsi;
163
164         if (ice_fltr_add_mac_to_list(vsi, &vsi->tmp_sync_list, addr,
165                                      ICE_FWD_TO_VSI))
166                 return -EINVAL;
167
168         return 0;
169 }
170
171 /**
172  * ice_add_mac_to_unsync_list - creates list of MAC addresses to be unsynced
173  * @netdev: the net device on which the unsync is happening
174  * @addr: MAC address to unsync
175  *
176  * This is a callback function which is called by the in kernel device unsync
177  * functions (like __dev_uc_unsync, __dev_mc_unsync, etc). This function only
178  * populates the tmp_unsync_list, which is later used by ice_remove_mac to
179  * delete the MAC filters from the hardware.
180  */
181 static int ice_add_mac_to_unsync_list(struct net_device *netdev, const u8 *addr)
182 {
183         struct ice_netdev_priv *np = netdev_priv(netdev);
184         struct ice_vsi *vsi = np->vsi;
185
186         if (ice_fltr_add_mac_to_list(vsi, &vsi->tmp_unsync_list, addr,
187                                      ICE_FWD_TO_VSI))
188                 return -EINVAL;
189
190         return 0;
191 }
192
193 /**
194  * ice_vsi_fltr_changed - check if filter state changed
195  * @vsi: VSI to be checked
196  *
197  * returns true if filter state has changed, false otherwise.
198  */
199 static bool ice_vsi_fltr_changed(struct ice_vsi *vsi)
200 {
201         return test_bit(ICE_VSI_FLAG_UMAC_FLTR_CHANGED, vsi->flags) ||
202                test_bit(ICE_VSI_FLAG_MMAC_FLTR_CHANGED, vsi->flags) ||
203                test_bit(ICE_VSI_FLAG_VLAN_FLTR_CHANGED, vsi->flags);
204 }
205
206 /**
207  * ice_cfg_promisc - Enable or disable promiscuous mode for a given PF
208  * @vsi: the VSI being configured
209  * @promisc_m: mask of promiscuous config bits
210  * @set_promisc: enable or disable promisc flag request
211  *
212  */
213 static int ice_cfg_promisc(struct ice_vsi *vsi, u8 promisc_m, bool set_promisc)
214 {
215         struct ice_hw *hw = &vsi->back->hw;
216         enum ice_status status = 0;
217
218         if (vsi->type != ICE_VSI_PF)
219                 return 0;
220
221         if (vsi->num_vlan > 1) {
222                 status = ice_set_vlan_vsi_promisc(hw, vsi->idx, promisc_m,
223                                                   set_promisc);
224         } else {
225                 if (set_promisc)
226                         status = ice_set_vsi_promisc(hw, vsi->idx, promisc_m,
227                                                      0);
228                 else
229                         status = ice_clear_vsi_promisc(hw, vsi->idx, promisc_m,
230                                                        0);
231         }
232
233         if (status)
234                 return -EIO;
235
236         return 0;
237 }
238
239 /**
240  * ice_vsi_sync_fltr - Update the VSI filter list to the HW
241  * @vsi: ptr to the VSI
242  *
243  * Push any outstanding VSI filter changes through the AdminQ.
244  */
245 static int ice_vsi_sync_fltr(struct ice_vsi *vsi)
246 {
247         struct device *dev = ice_pf_to_dev(vsi->back);
248         struct net_device *netdev = vsi->netdev;
249         bool promisc_forced_on = false;
250         struct ice_pf *pf = vsi->back;
251         struct ice_hw *hw = &pf->hw;
252         enum ice_status status = 0;
253         u32 changed_flags = 0;
254         u8 promisc_m;
255         int err = 0;
256
257         if (!vsi->netdev)
258                 return -EINVAL;
259
260         while (test_and_set_bit(__ICE_CFG_BUSY, vsi->state))
261                 usleep_range(1000, 2000);
262
263         changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
264         vsi->current_netdev_flags = vsi->netdev->flags;
265
266         INIT_LIST_HEAD(&vsi->tmp_sync_list);
267         INIT_LIST_HEAD(&vsi->tmp_unsync_list);
268
269         if (ice_vsi_fltr_changed(vsi)) {
270                 clear_bit(ICE_VSI_FLAG_UMAC_FLTR_CHANGED, vsi->flags);
271                 clear_bit(ICE_VSI_FLAG_MMAC_FLTR_CHANGED, vsi->flags);
272                 clear_bit(ICE_VSI_FLAG_VLAN_FLTR_CHANGED, vsi->flags);
273
274                 /* grab the netdev's addr_list_lock */
275                 netif_addr_lock_bh(netdev);
276                 __dev_uc_sync(netdev, ice_add_mac_to_sync_list,
277                               ice_add_mac_to_unsync_list);
278                 __dev_mc_sync(netdev, ice_add_mac_to_sync_list,
279                               ice_add_mac_to_unsync_list);
280                 /* our temp lists are populated. release lock */
281                 netif_addr_unlock_bh(netdev);
282         }
283
284         /* Remove MAC addresses in the unsync list */
285         status = ice_fltr_remove_mac_list(vsi, &vsi->tmp_unsync_list);
286         ice_fltr_free_list(dev, &vsi->tmp_unsync_list);
287         if (status) {
288                 netdev_err(netdev, "Failed to delete MAC filters\n");
289                 /* if we failed because of alloc failures, just bail */
290                 if (status == ICE_ERR_NO_MEMORY) {
291                         err = -ENOMEM;
292                         goto out;
293                 }
294         }
295
296         /* Add MAC addresses in the sync list */
297         status = ice_fltr_add_mac_list(vsi, &vsi->tmp_sync_list);
298         ice_fltr_free_list(dev, &vsi->tmp_sync_list);
299         /* If filter is added successfully or already exists, do not go into
300          * 'if' condition and report it as error. Instead continue processing
301          * rest of the function.
302          */
303         if (status && status != ICE_ERR_ALREADY_EXISTS) {
304                 netdev_err(netdev, "Failed to add MAC filters\n");
305                 /* If there is no more space for new umac filters, VSI
306                  * should go into promiscuous mode. There should be some
307                  * space reserved for promiscuous filters.
308                  */
309                 if (hw->adminq.sq_last_status == ICE_AQ_RC_ENOSPC &&
310                     !test_and_set_bit(__ICE_FLTR_OVERFLOW_PROMISC,
311                                       vsi->state)) {
312                         promisc_forced_on = true;
313                         netdev_warn(netdev, "Reached MAC filter limit, forcing promisc mode on VSI %d\n",
314                                     vsi->vsi_num);
315                 } else {
316                         err = -EIO;
317                         goto out;
318                 }
319         }
320         /* check for changes in promiscuous modes */
321         if (changed_flags & IFF_ALLMULTI) {
322                 if (vsi->current_netdev_flags & IFF_ALLMULTI) {
323                         if (vsi->num_vlan > 1)
324                                 promisc_m = ICE_MCAST_VLAN_PROMISC_BITS;
325                         else
326                                 promisc_m = ICE_MCAST_PROMISC_BITS;
327
328                         err = ice_cfg_promisc(vsi, promisc_m, true);
329                         if (err) {
330                                 netdev_err(netdev, "Error setting Multicast promiscuous mode on VSI %i\n",
331                                            vsi->vsi_num);
332                                 vsi->current_netdev_flags &= ~IFF_ALLMULTI;
333                                 goto out_promisc;
334                         }
335                 } else {
336                         /* !(vsi->current_netdev_flags & IFF_ALLMULTI) */
337                         if (vsi->num_vlan > 1)
338                                 promisc_m = ICE_MCAST_VLAN_PROMISC_BITS;
339                         else
340                                 promisc_m = ICE_MCAST_PROMISC_BITS;
341
342                         err = ice_cfg_promisc(vsi, promisc_m, false);
343                         if (err) {
344                                 netdev_err(netdev, "Error clearing Multicast promiscuous mode on VSI %i\n",
345                                            vsi->vsi_num);
346                                 vsi->current_netdev_flags |= IFF_ALLMULTI;
347                                 goto out_promisc;
348                         }
349                 }
350         }
351
352         if (((changed_flags & IFF_PROMISC) || promisc_forced_on) ||
353             test_bit(ICE_VSI_FLAG_PROMISC_CHANGED, vsi->flags)) {
354                 clear_bit(ICE_VSI_FLAG_PROMISC_CHANGED, vsi->flags);
355                 if (vsi->current_netdev_flags & IFF_PROMISC) {
356                         /* Apply Rx filter rule to get traffic from wire */
357                         if (!ice_is_dflt_vsi_in_use(pf->first_sw)) {
358                                 err = ice_set_dflt_vsi(pf->first_sw, vsi);
359                                 if (err && err != -EEXIST) {
360                                         netdev_err(netdev, "Error %d setting default VSI %i Rx rule\n",
361                                                    err, vsi->vsi_num);
362                                         vsi->current_netdev_flags &=
363                                                 ~IFF_PROMISC;
364                                         goto out_promisc;
365                                 }
366                                 ice_cfg_vlan_pruning(vsi, false, false);
367                         }
368                 } else {
369                         /* Clear Rx filter to remove traffic from wire */
370                         if (ice_is_vsi_dflt_vsi(pf->first_sw, vsi)) {
371                                 err = ice_clear_dflt_vsi(pf->first_sw);
372                                 if (err) {
373                                         netdev_err(netdev, "Error %d clearing default VSI %i Rx rule\n",
374                                                    err, vsi->vsi_num);
375                                         vsi->current_netdev_flags |=
376                                                 IFF_PROMISC;
377                                         goto out_promisc;
378                                 }
379                                 if (vsi->num_vlan > 1)
380                                         ice_cfg_vlan_pruning(vsi, true, false);
381                         }
382                 }
383         }
384         goto exit;
385
386 out_promisc:
387         set_bit(ICE_VSI_FLAG_PROMISC_CHANGED, vsi->flags);
388         goto exit;
389 out:
390         /* if something went wrong then set the changed flag so we try again */
391         set_bit(ICE_VSI_FLAG_UMAC_FLTR_CHANGED, vsi->flags);
392         set_bit(ICE_VSI_FLAG_MMAC_FLTR_CHANGED, vsi->flags);
393 exit:
394         clear_bit(__ICE_CFG_BUSY, vsi->state);
395         return err;
396 }
397
398 /**
399  * ice_sync_fltr_subtask - Sync the VSI filter list with HW
400  * @pf: board private structure
401  */
402 static void ice_sync_fltr_subtask(struct ice_pf *pf)
403 {
404         int v;
405
406         if (!pf || !(test_bit(ICE_FLAG_FLTR_SYNC, pf->flags)))
407                 return;
408
409         clear_bit(ICE_FLAG_FLTR_SYNC, pf->flags);
410
411         ice_for_each_vsi(pf, v)
412                 if (pf->vsi[v] && ice_vsi_fltr_changed(pf->vsi[v]) &&
413                     ice_vsi_sync_fltr(pf->vsi[v])) {
414                         /* come back and try again later */
415                         set_bit(ICE_FLAG_FLTR_SYNC, pf->flags);
416                         break;
417                 }
418 }
419
420 /**
421  * ice_pf_dis_all_vsi - Pause all VSIs on a PF
422  * @pf: the PF
423  * @locked: is the rtnl_lock already held
424  */
425 static void ice_pf_dis_all_vsi(struct ice_pf *pf, bool locked)
426 {
427         int node;
428         int v;
429
430         ice_for_each_vsi(pf, v)
431                 if (pf->vsi[v])
432                         ice_dis_vsi(pf->vsi[v], locked);
433
434         for (node = 0; node < ICE_MAX_PF_AGG_NODES; node++)
435                 pf->pf_agg_node[node].num_vsis = 0;
436
437         for (node = 0; node < ICE_MAX_VF_AGG_NODES; node++)
438                 pf->vf_agg_node[node].num_vsis = 0;
439
440 }
441
442 /**
443  * ice_prepare_for_reset - prep for the core to reset
444  * @pf: board private structure
445  *
446  * Inform or close all dependent features in prep for reset.
447  */
448 static void
449 ice_prepare_for_reset(struct ice_pf *pf)
450 {
451         struct ice_hw *hw = &pf->hw;
452         unsigned int i;
453
454         /* already prepared for reset */
455         if (test_bit(__ICE_PREPARED_FOR_RESET, pf->state))
456                 return;
457
458         /* Notify VFs of impending reset */
459         if (ice_check_sq_alive(hw, &hw->mailboxq))
460                 ice_vc_notify_reset(pf);
461
462         /* Disable VFs until reset is completed */
463         ice_for_each_vf(pf, i)
464                 ice_set_vf_state_qs_dis(&pf->vf[i]);
465
466         /* clear SW filtering DB */
467         ice_clear_hw_tbls(hw);
468         /* disable the VSIs and their queues that are not already DOWN */
469         ice_pf_dis_all_vsi(pf, false);
470
471         if (hw->port_info)
472                 ice_sched_clear_port(hw->port_info);
473
474         ice_shutdown_all_ctrlq(hw);
475
476         set_bit(__ICE_PREPARED_FOR_RESET, pf->state);
477 }
478
479 /**
480  * ice_do_reset - Initiate one of many types of resets
481  * @pf: board private structure
482  * @reset_type: reset type requested
483  * before this function was called.
484  */
485 static void ice_do_reset(struct ice_pf *pf, enum ice_reset_req reset_type)
486 {
487         struct device *dev = ice_pf_to_dev(pf);
488         struct ice_hw *hw = &pf->hw;
489
490         dev_dbg(dev, "reset_type 0x%x requested\n", reset_type);
491
492         ice_prepare_for_reset(pf);
493
494         /* trigger the reset */
495         if (ice_reset(hw, reset_type)) {
496                 dev_err(dev, "reset %d failed\n", reset_type);
497                 set_bit(__ICE_RESET_FAILED, pf->state);
498                 clear_bit(__ICE_RESET_OICR_RECV, pf->state);
499                 clear_bit(__ICE_PREPARED_FOR_RESET, pf->state);
500                 clear_bit(__ICE_PFR_REQ, pf->state);
501                 clear_bit(__ICE_CORER_REQ, pf->state);
502                 clear_bit(__ICE_GLOBR_REQ, pf->state);
503                 return;
504         }
505
506         /* PFR is a bit of a special case because it doesn't result in an OICR
507          * interrupt. So for PFR, rebuild after the reset and clear the reset-
508          * associated state bits.
509          */
510         if (reset_type == ICE_RESET_PFR) {
511                 pf->pfr_count++;
512                 ice_rebuild(pf, reset_type);
513                 clear_bit(__ICE_PREPARED_FOR_RESET, pf->state);
514                 clear_bit(__ICE_PFR_REQ, pf->state);
515                 ice_reset_all_vfs(pf, true);
516         }
517 }
518
519 /**
520  * ice_reset_subtask - Set up for resetting the device and driver
521  * @pf: board private structure
522  */
523 static void ice_reset_subtask(struct ice_pf *pf)
524 {
525         enum ice_reset_req reset_type = ICE_RESET_INVAL;
526
527         /* When a CORER/GLOBR/EMPR is about to happen, the hardware triggers an
528          * OICR interrupt. The OICR handler (ice_misc_intr) determines what type
529          * of reset is pending and sets bits in pf->state indicating the reset
530          * type and __ICE_RESET_OICR_RECV. So, if the latter bit is set
531          * prepare for pending reset if not already (for PF software-initiated
532          * global resets the software should already be prepared for it as
533          * indicated by __ICE_PREPARED_FOR_RESET; for global resets initiated
534          * by firmware or software on other PFs, that bit is not set so prepare
535          * for the reset now), poll for reset done, rebuild and return.
536          */
537         if (test_bit(__ICE_RESET_OICR_RECV, pf->state)) {
538                 /* Perform the largest reset requested */
539                 if (test_and_clear_bit(__ICE_CORER_RECV, pf->state))
540                         reset_type = ICE_RESET_CORER;
541                 if (test_and_clear_bit(__ICE_GLOBR_RECV, pf->state))
542                         reset_type = ICE_RESET_GLOBR;
543                 if (test_and_clear_bit(__ICE_EMPR_RECV, pf->state))
544                         reset_type = ICE_RESET_EMPR;
545                 /* return if no valid reset type requested */
546                 if (reset_type == ICE_RESET_INVAL)
547                         return;
548                 ice_prepare_for_reset(pf);
549
550                 /* make sure we are ready to rebuild */
551                 if (ice_check_reset(&pf->hw)) {
552                         set_bit(__ICE_RESET_FAILED, pf->state);
553                 } else {
554                         /* done with reset. start rebuild */
555                         pf->hw.reset_ongoing = false;
556                         ice_rebuild(pf, reset_type);
557                         /* clear bit to resume normal operations, but
558                          * ICE_NEEDS_RESTART bit is set in case rebuild failed
559                          */
560                         clear_bit(__ICE_RESET_OICR_RECV, pf->state);
561                         clear_bit(__ICE_PREPARED_FOR_RESET, pf->state);
562                         clear_bit(__ICE_PFR_REQ, pf->state);
563                         clear_bit(__ICE_CORER_REQ, pf->state);
564                         clear_bit(__ICE_GLOBR_REQ, pf->state);
565                         ice_reset_all_vfs(pf, true);
566                 }
567
568                 return;
569         }
570
571         /* No pending resets to finish processing. Check for new resets */
572         if (test_bit(__ICE_PFR_REQ, pf->state))
573                 reset_type = ICE_RESET_PFR;
574         if (test_bit(__ICE_CORER_REQ, pf->state))
575                 reset_type = ICE_RESET_CORER;
576         if (test_bit(__ICE_GLOBR_REQ, pf->state))
577                 reset_type = ICE_RESET_GLOBR;
578         /* If no valid reset type requested just return */
579         if (reset_type == ICE_RESET_INVAL)
580                 return;
581
582         /* reset if not already down or busy */
583         if (!test_bit(__ICE_DOWN, pf->state) &&
584             !test_bit(__ICE_CFG_BUSY, pf->state)) {
585                 ice_do_reset(pf, reset_type);
586         }
587 }
588
589 /**
590  * ice_print_topo_conflict - print topology conflict message
591  * @vsi: the VSI whose topology status is being checked
592  */
593 static void ice_print_topo_conflict(struct ice_vsi *vsi)
594 {
595         switch (vsi->port_info->phy.link_info.topo_media_conflict) {
596         case ICE_AQ_LINK_TOPO_CONFLICT:
597         case ICE_AQ_LINK_MEDIA_CONFLICT:
598         case ICE_AQ_LINK_TOPO_UNREACH_PRT:
599         case ICE_AQ_LINK_TOPO_UNDRUTIL_PRT:
600         case ICE_AQ_LINK_TOPO_UNDRUTIL_MEDIA:
601                 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");
602                 break;
603         case ICE_AQ_LINK_TOPO_UNSUPP_MEDIA:
604                 netdev_info(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");
605                 break;
606         default:
607                 break;
608         }
609 }
610
611 /**
612  * ice_print_link_msg - print link up or down message
613  * @vsi: the VSI whose link status is being queried
614  * @isup: boolean for if the link is now up or down
615  */
616 void ice_print_link_msg(struct ice_vsi *vsi, bool isup)
617 {
618         struct ice_aqc_get_phy_caps_data *caps;
619         const char *an_advertised;
620         enum ice_status status;
621         const char *fec_req;
622         const char *speed;
623         const char *fec;
624         const char *fc;
625         const char *an;
626
627         if (!vsi)
628                 return;
629
630         if (vsi->current_isup == isup)
631                 return;
632
633         vsi->current_isup = isup;
634
635         if (!isup) {
636                 netdev_info(vsi->netdev, "NIC Link is Down\n");
637                 return;
638         }
639
640         switch (vsi->port_info->phy.link_info.link_speed) {
641         case ICE_AQ_LINK_SPEED_100GB:
642                 speed = "100 G";
643                 break;
644         case ICE_AQ_LINK_SPEED_50GB:
645                 speed = "50 G";
646                 break;
647         case ICE_AQ_LINK_SPEED_40GB:
648                 speed = "40 G";
649                 break;
650         case ICE_AQ_LINK_SPEED_25GB:
651                 speed = "25 G";
652                 break;
653         case ICE_AQ_LINK_SPEED_20GB:
654                 speed = "20 G";
655                 break;
656         case ICE_AQ_LINK_SPEED_10GB:
657                 speed = "10 G";
658                 break;
659         case ICE_AQ_LINK_SPEED_5GB:
660                 speed = "5 G";
661                 break;
662         case ICE_AQ_LINK_SPEED_2500MB:
663                 speed = "2.5 G";
664                 break;
665         case ICE_AQ_LINK_SPEED_1000MB:
666                 speed = "1 G";
667                 break;
668         case ICE_AQ_LINK_SPEED_100MB:
669                 speed = "100 M";
670                 break;
671         default:
672                 speed = "Unknown ";
673                 break;
674         }
675
676         switch (vsi->port_info->fc.current_mode) {
677         case ICE_FC_FULL:
678                 fc = "Rx/Tx";
679                 break;
680         case ICE_FC_TX_PAUSE:
681                 fc = "Tx";
682                 break;
683         case ICE_FC_RX_PAUSE:
684                 fc = "Rx";
685                 break;
686         case ICE_FC_NONE:
687                 fc = "None";
688                 break;
689         default:
690                 fc = "Unknown";
691                 break;
692         }
693
694         /* Get FEC mode based on negotiated link info */
695         switch (vsi->port_info->phy.link_info.fec_info) {
696         case ICE_AQ_LINK_25G_RS_528_FEC_EN:
697         case ICE_AQ_LINK_25G_RS_544_FEC_EN:
698                 fec = "RS-FEC";
699                 break;
700         case ICE_AQ_LINK_25G_KR_FEC_EN:
701                 fec = "FC-FEC/BASE-R";
702                 break;
703         default:
704                 fec = "NONE";
705                 break;
706         }
707
708         /* check if autoneg completed, might be false due to not supported */
709         if (vsi->port_info->phy.link_info.an_info & ICE_AQ_AN_COMPLETED)
710                 an = "True";
711         else
712                 an = "False";
713
714         /* Get FEC mode requested based on PHY caps last SW configuration */
715         caps = kzalloc(sizeof(*caps), GFP_KERNEL);
716         if (!caps) {
717                 fec_req = "Unknown";
718                 an_advertised = "Unknown";
719                 goto done;
720         }
721
722         status = ice_aq_get_phy_caps(vsi->port_info, false,
723                                      ICE_AQC_REPORT_SW_CFG, caps, NULL);
724         if (status)
725                 netdev_info(vsi->netdev, "Get phy capability failed.\n");
726
727         an_advertised = ice_is_phy_caps_an_enabled(caps) ? "On" : "Off";
728
729         if (caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_528_REQ ||
730             caps->link_fec_options & ICE_AQC_PHY_FEC_25G_RS_544_REQ)
731                 fec_req = "RS-FEC";
732         else if (caps->link_fec_options & ICE_AQC_PHY_FEC_10G_KR_40G_KR4_REQ ||
733                  caps->link_fec_options & ICE_AQC_PHY_FEC_25G_KR_REQ)
734                 fec_req = "FC-FEC/BASE-R";
735         else
736                 fec_req = "NONE";
737
738         kfree(caps);
739
740 done:
741         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",
742                     speed, fec_req, fec, an_advertised, an, fc);
743         ice_print_topo_conflict(vsi);
744 }
745
746 /**
747  * ice_vsi_link_event - update the VSI's netdev
748  * @vsi: the VSI on which the link event occurred
749  * @link_up: whether or not the VSI needs to be set up or down
750  */
751 static void ice_vsi_link_event(struct ice_vsi *vsi, bool link_up)
752 {
753         if (!vsi)
754                 return;
755
756         if (test_bit(__ICE_DOWN, vsi->state) || !vsi->netdev)
757                 return;
758
759         if (vsi->type == ICE_VSI_PF) {
760                 if (link_up == netif_carrier_ok(vsi->netdev))
761                         return;
762
763                 if (link_up) {
764                         netif_carrier_on(vsi->netdev);
765                         netif_tx_wake_all_queues(vsi->netdev);
766                 } else {
767                         netif_carrier_off(vsi->netdev);
768                         netif_tx_stop_all_queues(vsi->netdev);
769                 }
770         }
771 }
772
773 /**
774  * ice_set_dflt_mib - send a default config MIB to the FW
775  * @pf: private PF struct
776  *
777  * This function sends a default configuration MIB to the FW.
778  *
779  * If this function errors out at any point, the driver is still able to
780  * function.  The main impact is that LFC may not operate as expected.
781  * Therefore an error state in this function should be treated with a DBG
782  * message and continue on with driver rebuild/reenable.
783  */
784 static void ice_set_dflt_mib(struct ice_pf *pf)
785 {
786         struct device *dev = ice_pf_to_dev(pf);
787         u8 mib_type, *buf, *lldpmib = NULL;
788         u16 len, typelen, offset = 0;
789         struct ice_lldp_org_tlv *tlv;
790         struct ice_hw *hw = &pf->hw;
791         u32 ouisubtype;
792
793         mib_type = SET_LOCAL_MIB_TYPE_LOCAL_MIB;
794         lldpmib = kzalloc(ICE_LLDPDU_SIZE, GFP_KERNEL);
795         if (!lldpmib) {
796                 dev_dbg(dev, "%s Failed to allocate MIB memory\n",
797                         __func__);
798                 return;
799         }
800
801         /* Add ETS CFG TLV */
802         tlv = (struct ice_lldp_org_tlv *)lldpmib;
803         typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) |
804                    ICE_IEEE_ETS_TLV_LEN);
805         tlv->typelen = htons(typelen);
806         ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) |
807                       ICE_IEEE_SUBTYPE_ETS_CFG);
808         tlv->ouisubtype = htonl(ouisubtype);
809
810         buf = tlv->tlvinfo;
811         buf[0] = 0;
812
813         /* ETS CFG all UPs map to TC 0. Next 4 (1 - 4) Octets = 0.
814          * Octets 5 - 12 are BW values, set octet 5 to 100% BW.
815          * Octets 13 - 20 are TSA values - leave as zeros
816          */
817         buf[5] = 0x64;
818         len = (typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S;
819         offset += len + 2;
820         tlv = (struct ice_lldp_org_tlv *)
821                 ((char *)tlv + sizeof(tlv->typelen) + len);
822
823         /* Add ETS REC TLV */
824         buf = tlv->tlvinfo;
825         tlv->typelen = htons(typelen);
826
827         ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) |
828                       ICE_IEEE_SUBTYPE_ETS_REC);
829         tlv->ouisubtype = htonl(ouisubtype);
830
831         /* First octet of buf is reserved
832          * Octets 1 - 4 map UP to TC - all UPs map to zero
833          * Octets 5 - 12 are BW values - set TC 0 to 100%.
834          * Octets 13 - 20 are TSA value - leave as zeros
835          */
836         buf[5] = 0x64;
837         offset += len + 2;
838         tlv = (struct ice_lldp_org_tlv *)
839                 ((char *)tlv + sizeof(tlv->typelen) + len);
840
841         /* Add PFC CFG TLV */
842         typelen = ((ICE_TLV_TYPE_ORG << ICE_LLDP_TLV_TYPE_S) |
843                    ICE_IEEE_PFC_TLV_LEN);
844         tlv->typelen = htons(typelen);
845
846         ouisubtype = ((ICE_IEEE_8021QAZ_OUI << ICE_LLDP_TLV_OUI_S) |
847                       ICE_IEEE_SUBTYPE_PFC_CFG);
848         tlv->ouisubtype = htonl(ouisubtype);
849
850         /* Octet 1 left as all zeros - PFC disabled */
851         buf[0] = 0x08;
852         len = (typelen & ICE_LLDP_TLV_LEN_M) >> ICE_LLDP_TLV_LEN_S;
853         offset += len + 2;
854
855         if (ice_aq_set_lldp_mib(hw, mib_type, (void *)lldpmib, offset, NULL))
856                 dev_dbg(dev, "%s Failed to set default LLDP MIB\n", __func__);
857
858         kfree(lldpmib);
859 }
860
861 /**
862  * ice_link_event - process the link event
863  * @pf: PF that the link event is associated with
864  * @pi: port_info for the port that the link event is associated with
865  * @link_up: true if the physical link is up and false if it is down
866  * @link_speed: current link speed received from the link event
867  *
868  * Returns 0 on success and negative on failure
869  */
870 static int
871 ice_link_event(struct ice_pf *pf, struct ice_port_info *pi, bool link_up,
872                u16 link_speed)
873 {
874         struct device *dev = ice_pf_to_dev(pf);
875         struct ice_phy_info *phy_info;
876         struct ice_vsi *vsi;
877         u16 old_link_speed;
878         bool old_link;
879         int result;
880
881         phy_info = &pi->phy;
882         phy_info->link_info_old = phy_info->link_info;
883
884         old_link = !!(phy_info->link_info_old.link_info & ICE_AQ_LINK_UP);
885         old_link_speed = phy_info->link_info_old.link_speed;
886
887         /* update the link info structures and re-enable link events,
888          * don't bail on failure due to other book keeping needed
889          */
890         result = ice_update_link_info(pi);
891         if (result)
892                 dev_dbg(dev, "Failed to update link status and re-enable link events for port %d\n",
893                         pi->lport);
894
895         /* Check if the link state is up after updating link info, and treat
896          * this event as an UP event since the link is actually UP now.
897          */
898         if (phy_info->link_info.link_info & ICE_AQ_LINK_UP)
899                 link_up = true;
900
901         vsi = ice_get_main_vsi(pf);
902         if (!vsi || !vsi->port_info)
903                 return -EINVAL;
904
905         /* turn off PHY if media was removed */
906         if (!test_bit(ICE_FLAG_NO_MEDIA, pf->flags) &&
907             !(pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE)) {
908                 set_bit(ICE_FLAG_NO_MEDIA, pf->flags);
909
910                 result = ice_aq_set_link_restart_an(pi, false, NULL);
911                 if (result) {
912                         dev_dbg(dev, "Failed to set link down, VSI %d error %d\n",
913                                 vsi->vsi_num, result);
914                         return result;
915                 }
916         }
917
918         /* if the old link up/down and speed is the same as the new */
919         if (link_up == old_link && link_speed == old_link_speed)
920                 return result;
921
922         if (ice_is_dcb_active(pf)) {
923                 if (test_bit(ICE_FLAG_DCB_ENA, pf->flags))
924                         ice_dcb_rebuild(pf);
925         } else {
926                 if (link_up)
927                         ice_set_dflt_mib(pf);
928         }
929         ice_vsi_link_event(vsi, link_up);
930         ice_print_link_msg(vsi, link_up);
931
932         ice_vc_notify_link_state(pf);
933
934         return result;
935 }
936
937 /**
938  * ice_watchdog_subtask - periodic tasks not using event driven scheduling
939  * @pf: board private structure
940  */
941 static void ice_watchdog_subtask(struct ice_pf *pf)
942 {
943         int i;
944
945         /* if interface is down do nothing */
946         if (test_bit(__ICE_DOWN, pf->state) ||
947             test_bit(__ICE_CFG_BUSY, pf->state))
948                 return;
949
950         /* make sure we don't do these things too often */
951         if (time_before(jiffies,
952                         pf->serv_tmr_prev + pf->serv_tmr_period))
953                 return;
954
955         pf->serv_tmr_prev = jiffies;
956
957         /* Update the stats for active netdevs so the network stack
958          * can look at updated numbers whenever it cares to
959          */
960         ice_update_pf_stats(pf);
961         ice_for_each_vsi(pf, i)
962                 if (pf->vsi[i] && pf->vsi[i]->netdev)
963                         ice_update_vsi_stats(pf->vsi[i]);
964 }
965
966 /**
967  * ice_init_link_events - enable/initialize link events
968  * @pi: pointer to the port_info instance
969  *
970  * Returns -EIO on failure, 0 on success
971  */
972 static int ice_init_link_events(struct ice_port_info *pi)
973 {
974         u16 mask;
975
976         mask = ~((u16)(ICE_AQ_LINK_EVENT_UPDOWN | ICE_AQ_LINK_EVENT_MEDIA_NA |
977                        ICE_AQ_LINK_EVENT_MODULE_QUAL_FAIL));
978
979         if (ice_aq_set_event_mask(pi->hw, pi->lport, mask, NULL)) {
980                 dev_dbg(ice_hw_to_dev(pi->hw), "Failed to set link event mask for port %d\n",
981                         pi->lport);
982                 return -EIO;
983         }
984
985         if (ice_aq_get_link_info(pi, true, NULL, NULL)) {
986                 dev_dbg(ice_hw_to_dev(pi->hw), "Failed to enable link events for port %d\n",
987                         pi->lport);
988                 return -EIO;
989         }
990
991         return 0;
992 }
993
994 /**
995  * ice_handle_link_event - handle link event via ARQ
996  * @pf: PF that the link event is associated with
997  * @event: event structure containing link status info
998  */
999 static int
1000 ice_handle_link_event(struct ice_pf *pf, struct ice_rq_event_info *event)
1001 {
1002         struct ice_aqc_get_link_status_data *link_data;
1003         struct ice_port_info *port_info;
1004         int status;
1005
1006         link_data = (struct ice_aqc_get_link_status_data *)event->msg_buf;
1007         port_info = pf->hw.port_info;
1008         if (!port_info)
1009                 return -EINVAL;
1010
1011         status = ice_link_event(pf, port_info,
1012                                 !!(link_data->link_info & ICE_AQ_LINK_UP),
1013                                 le16_to_cpu(link_data->link_speed));
1014         if (status)
1015                 dev_dbg(ice_pf_to_dev(pf), "Could not process link event, error %d\n",
1016                         status);
1017
1018         return status;
1019 }
1020
1021 enum ice_aq_task_state {
1022         ICE_AQ_TASK_WAITING = 0,
1023         ICE_AQ_TASK_COMPLETE,
1024         ICE_AQ_TASK_CANCELED,
1025 };
1026
1027 struct ice_aq_task {
1028         struct hlist_node entry;
1029
1030         u16 opcode;
1031         struct ice_rq_event_info *event;
1032         enum ice_aq_task_state state;
1033 };
1034
1035 /**
1036  * ice_aq_wait_for_event - Wait for an AdminQ event from firmware
1037  * @pf: pointer to the PF private structure
1038  * @opcode: the opcode to wait for
1039  * @timeout: how long to wait, in jiffies
1040  * @event: storage for the event info
1041  *
1042  * Waits for a specific AdminQ completion event on the ARQ for a given PF. The
1043  * current thread will be put to sleep until the specified event occurs or
1044  * until the given timeout is reached.
1045  *
1046  * To obtain only the descriptor contents, pass an event without an allocated
1047  * msg_buf. If the complete data buffer is desired, allocate the
1048  * event->msg_buf with enough space ahead of time.
1049  *
1050  * Returns: zero on success, or a negative error code on failure.
1051  */
1052 int ice_aq_wait_for_event(struct ice_pf *pf, u16 opcode, unsigned long timeout,
1053                           struct ice_rq_event_info *event)
1054 {
1055         struct device *dev = ice_pf_to_dev(pf);
1056         struct ice_aq_task *task;
1057         unsigned long start;
1058         long ret;
1059         int err;
1060
1061         task = kzalloc(sizeof(*task), GFP_KERNEL);
1062         if (!task)
1063                 return -ENOMEM;
1064
1065         INIT_HLIST_NODE(&task->entry);
1066         task->opcode = opcode;
1067         task->event = event;
1068         task->state = ICE_AQ_TASK_WAITING;
1069
1070         spin_lock_bh(&pf->aq_wait_lock);
1071         hlist_add_head(&task->entry, &pf->aq_wait_list);
1072         spin_unlock_bh(&pf->aq_wait_lock);
1073
1074         start = jiffies;
1075
1076         ret = wait_event_interruptible_timeout(pf->aq_wait_queue, task->state,
1077                                                timeout);
1078         switch (task->state) {
1079         case ICE_AQ_TASK_WAITING:
1080                 err = ret < 0 ? ret : -ETIMEDOUT;
1081                 break;
1082         case ICE_AQ_TASK_CANCELED:
1083                 err = ret < 0 ? ret : -ECANCELED;
1084                 break;
1085         case ICE_AQ_TASK_COMPLETE:
1086                 err = ret < 0 ? ret : 0;
1087                 break;
1088         default:
1089                 WARN(1, "Unexpected AdminQ wait task state %u", task->state);
1090                 err = -EINVAL;
1091                 break;
1092         }
1093
1094         dev_dbg(dev, "Waited %u msecs (max %u msecs) for firmware response to op 0x%04x\n",
1095                 jiffies_to_msecs(jiffies - start),
1096                 jiffies_to_msecs(timeout),
1097                 opcode);
1098
1099         spin_lock_bh(&pf->aq_wait_lock);
1100         hlist_del(&task->entry);
1101         spin_unlock_bh(&pf->aq_wait_lock);
1102         kfree(task);
1103
1104         return err;
1105 }
1106
1107 /**
1108  * ice_aq_check_events - Check if any thread is waiting for an AdminQ event
1109  * @pf: pointer to the PF private structure
1110  * @opcode: the opcode of the event
1111  * @event: the event to check
1112  *
1113  * Loops over the current list of pending threads waiting for an AdminQ event.
1114  * For each matching task, copy the contents of the event into the task
1115  * structure and wake up the thread.
1116  *
1117  * If multiple threads wait for the same opcode, they will all be woken up.
1118  *
1119  * Note that event->msg_buf will only be duplicated if the event has a buffer
1120  * with enough space already allocated. Otherwise, only the descriptor and
1121  * message length will be copied.
1122  *
1123  * Returns: true if an event was found, false otherwise
1124  */
1125 static void ice_aq_check_events(struct ice_pf *pf, u16 opcode,
1126                                 struct ice_rq_event_info *event)
1127 {
1128         struct ice_aq_task *task;
1129         bool found = false;
1130
1131         spin_lock_bh(&pf->aq_wait_lock);
1132         hlist_for_each_entry(task, &pf->aq_wait_list, entry) {
1133                 if (task->state || task->opcode != opcode)
1134                         continue;
1135
1136                 memcpy(&task->event->desc, &event->desc, sizeof(event->desc));
1137                 task->event->msg_len = event->msg_len;
1138
1139                 /* Only copy the data buffer if a destination was set */
1140                 if (task->event->msg_buf &&
1141                     task->event->buf_len > event->buf_len) {
1142                         memcpy(task->event->msg_buf, event->msg_buf,
1143                                event->buf_len);
1144                         task->event->buf_len = event->buf_len;
1145                 }
1146
1147                 task->state = ICE_AQ_TASK_COMPLETE;
1148                 found = true;
1149         }
1150         spin_unlock_bh(&pf->aq_wait_lock);
1151
1152         if (found)
1153                 wake_up(&pf->aq_wait_queue);
1154 }
1155
1156 /**
1157  * ice_aq_cancel_waiting_tasks - Immediately cancel all waiting tasks
1158  * @pf: the PF private structure
1159  *
1160  * Set all waiting tasks to ICE_AQ_TASK_CANCELED, and wake up their threads.
1161  * This will then cause ice_aq_wait_for_event to exit with -ECANCELED.
1162  */
1163 static void ice_aq_cancel_waiting_tasks(struct ice_pf *pf)
1164 {
1165         struct ice_aq_task *task;
1166
1167         spin_lock_bh(&pf->aq_wait_lock);
1168         hlist_for_each_entry(task, &pf->aq_wait_list, entry)
1169                 task->state = ICE_AQ_TASK_CANCELED;
1170         spin_unlock_bh(&pf->aq_wait_lock);
1171
1172         wake_up(&pf->aq_wait_queue);
1173 }
1174
1175 /**
1176  * __ice_clean_ctrlq - helper function to clean controlq rings
1177  * @pf: ptr to struct ice_pf
1178  * @q_type: specific Control queue type
1179  */
1180 static int __ice_clean_ctrlq(struct ice_pf *pf, enum ice_ctl_q q_type)
1181 {
1182         struct device *dev = ice_pf_to_dev(pf);
1183         struct ice_rq_event_info event;
1184         struct ice_hw *hw = &pf->hw;
1185         struct ice_ctl_q_info *cq;
1186         u16 pending, i = 0;
1187         const char *qtype;
1188         u32 oldval, val;
1189
1190         /* Do not clean control queue if/when PF reset fails */
1191         if (test_bit(__ICE_RESET_FAILED, pf->state))
1192                 return 0;
1193
1194         switch (q_type) {
1195         case ICE_CTL_Q_ADMIN:
1196                 cq = &hw->adminq;
1197                 qtype = "Admin";
1198                 break;
1199         case ICE_CTL_Q_MAILBOX:
1200                 cq = &hw->mailboxq;
1201                 qtype = "Mailbox";
1202                 break;
1203         default:
1204                 dev_warn(dev, "Unknown control queue type 0x%x\n", q_type);
1205                 return 0;
1206         }
1207
1208         /* check for error indications - PF_xx_AxQLEN register layout for
1209          * FW/MBX/SB are identical so just use defines for PF_FW_AxQLEN.
1210          */
1211         val = rd32(hw, cq->rq.len);
1212         if (val & (PF_FW_ARQLEN_ARQVFE_M | PF_FW_ARQLEN_ARQOVFL_M |
1213                    PF_FW_ARQLEN_ARQCRIT_M)) {
1214                 oldval = val;
1215                 if (val & PF_FW_ARQLEN_ARQVFE_M)
1216                         dev_dbg(dev, "%s Receive Queue VF Error detected\n",
1217                                 qtype);
1218                 if (val & PF_FW_ARQLEN_ARQOVFL_M) {
1219                         dev_dbg(dev, "%s Receive Queue Overflow Error detected\n",
1220                                 qtype);
1221                 }
1222                 if (val & PF_FW_ARQLEN_ARQCRIT_M)
1223                         dev_dbg(dev, "%s Receive Queue Critical Error detected\n",
1224                                 qtype);
1225                 val &= ~(PF_FW_ARQLEN_ARQVFE_M | PF_FW_ARQLEN_ARQOVFL_M |
1226                          PF_FW_ARQLEN_ARQCRIT_M);
1227                 if (oldval != val)
1228                         wr32(hw, cq->rq.len, val);
1229         }
1230
1231         val = rd32(hw, cq->sq.len);
1232         if (val & (PF_FW_ATQLEN_ATQVFE_M | PF_FW_ATQLEN_ATQOVFL_M |
1233                    PF_FW_ATQLEN_ATQCRIT_M)) {
1234                 oldval = val;
1235                 if (val & PF_FW_ATQLEN_ATQVFE_M)
1236                         dev_dbg(dev, "%s Send Queue VF Error detected\n",
1237                                 qtype);
1238                 if (val & PF_FW_ATQLEN_ATQOVFL_M) {
1239                         dev_dbg(dev, "%s Send Queue Overflow Error detected\n",
1240                                 qtype);
1241                 }
1242                 if (val & PF_FW_ATQLEN_ATQCRIT_M)
1243                         dev_dbg(dev, "%s Send Queue Critical Error detected\n",
1244                                 qtype);
1245                 val &= ~(PF_FW_ATQLEN_ATQVFE_M | PF_FW_ATQLEN_ATQOVFL_M |
1246                          PF_FW_ATQLEN_ATQCRIT_M);
1247                 if (oldval != val)
1248                         wr32(hw, cq->sq.len, val);
1249         }
1250
1251         event.buf_len = cq->rq_buf_size;
1252         event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
1253         if (!event.msg_buf)
1254                 return 0;
1255
1256         do {
1257                 enum ice_status ret;
1258                 u16 opcode;
1259
1260                 ret = ice_clean_rq_elem(hw, cq, &event, &pending);
1261                 if (ret == ICE_ERR_AQ_NO_WORK)
1262                         break;
1263                 if (ret) {
1264                         dev_err(dev, "%s Receive Queue event error %s\n", qtype,
1265                                 ice_stat_str(ret));
1266                         break;
1267                 }
1268
1269                 opcode = le16_to_cpu(event.desc.opcode);
1270
1271                 /* Notify any thread that might be waiting for this event */
1272                 ice_aq_check_events(pf, opcode, &event);
1273
1274                 switch (opcode) {
1275                 case ice_aqc_opc_get_link_status:
1276                         if (ice_handle_link_event(pf, &event))
1277                                 dev_err(dev, "Could not handle link event\n");
1278                         break;
1279                 case ice_aqc_opc_event_lan_overflow:
1280                         ice_vf_lan_overflow_event(pf, &event);
1281                         break;
1282                 case ice_mbx_opc_send_msg_to_pf:
1283                         ice_vc_process_vf_msg(pf, &event);
1284                         break;
1285                 case ice_aqc_opc_fw_logging:
1286                         ice_output_fw_log(hw, &event.desc, event.msg_buf);
1287                         break;
1288                 case ice_aqc_opc_lldp_set_mib_change:
1289                         ice_dcb_process_lldp_set_mib_change(pf, &event);
1290                         break;
1291                 default:
1292                         dev_dbg(dev, "%s Receive Queue unknown event 0x%04x ignored\n",
1293                                 qtype, opcode);
1294                         break;
1295                 }
1296         } while (pending && (i++ < ICE_DFLT_IRQ_WORK));
1297
1298         kfree(event.msg_buf);
1299
1300         return pending && (i == ICE_DFLT_IRQ_WORK);
1301 }
1302
1303 /**
1304  * ice_ctrlq_pending - check if there is a difference between ntc and ntu
1305  * @hw: pointer to hardware info
1306  * @cq: control queue information
1307  *
1308  * returns true if there are pending messages in a queue, false if there aren't
1309  */
1310 static bool ice_ctrlq_pending(struct ice_hw *hw, struct ice_ctl_q_info *cq)
1311 {
1312         u16 ntu;
1313
1314         ntu = (u16)(rd32(hw, cq->rq.head) & cq->rq.head_mask);
1315         return cq->rq.next_to_clean != ntu;
1316 }
1317
1318 /**
1319  * ice_clean_adminq_subtask - clean the AdminQ rings
1320  * @pf: board private structure
1321  */
1322 static void ice_clean_adminq_subtask(struct ice_pf *pf)
1323 {
1324         struct ice_hw *hw = &pf->hw;
1325
1326         if (!test_bit(__ICE_ADMINQ_EVENT_PENDING, pf->state))
1327                 return;
1328
1329         if (__ice_clean_ctrlq(pf, ICE_CTL_Q_ADMIN))
1330                 return;
1331
1332         clear_bit(__ICE_ADMINQ_EVENT_PENDING, pf->state);
1333
1334         /* There might be a situation where new messages arrive to a control
1335          * queue between processing the last message and clearing the
1336          * EVENT_PENDING bit. So before exiting, check queue head again (using
1337          * ice_ctrlq_pending) and process new messages if any.
1338          */
1339         if (ice_ctrlq_pending(hw, &hw->adminq))
1340                 __ice_clean_ctrlq(pf, ICE_CTL_Q_ADMIN);
1341
1342         ice_flush(hw);
1343 }
1344
1345 /**
1346  * ice_clean_mailboxq_subtask - clean the MailboxQ rings
1347  * @pf: board private structure
1348  */
1349 static void ice_clean_mailboxq_subtask(struct ice_pf *pf)
1350 {
1351         struct ice_hw *hw = &pf->hw;
1352
1353         if (!test_bit(__ICE_MAILBOXQ_EVENT_PENDING, pf->state))
1354                 return;
1355
1356         if (__ice_clean_ctrlq(pf, ICE_CTL_Q_MAILBOX))
1357                 return;
1358
1359         clear_bit(__ICE_MAILBOXQ_EVENT_PENDING, pf->state);
1360
1361         if (ice_ctrlq_pending(hw, &hw->mailboxq))
1362                 __ice_clean_ctrlq(pf, ICE_CTL_Q_MAILBOX);
1363
1364         ice_flush(hw);
1365 }
1366
1367 /**
1368  * ice_service_task_schedule - schedule the service task to wake up
1369  * @pf: board private structure
1370  *
1371  * If not already scheduled, this puts the task into the work queue.
1372  */
1373 void ice_service_task_schedule(struct ice_pf *pf)
1374 {
1375         if (!test_bit(__ICE_SERVICE_DIS, pf->state) &&
1376             !test_and_set_bit(__ICE_SERVICE_SCHED, pf->state) &&
1377             !test_bit(__ICE_NEEDS_RESTART, pf->state))
1378                 queue_work(ice_wq, &pf->serv_task);
1379 }
1380
1381 /**
1382  * ice_service_task_complete - finish up the service task
1383  * @pf: board private structure
1384  */
1385 static void ice_service_task_complete(struct ice_pf *pf)
1386 {
1387         WARN_ON(!test_bit(__ICE_SERVICE_SCHED, pf->state));
1388
1389         /* force memory (pf->state) to sync before next service task */
1390         smp_mb__before_atomic();
1391         clear_bit(__ICE_SERVICE_SCHED, pf->state);
1392 }
1393
1394 /**
1395  * ice_service_task_stop - stop service task and cancel works
1396  * @pf: board private structure
1397  *
1398  * Return 0 if the __ICE_SERVICE_DIS bit was not already set,
1399  * 1 otherwise.
1400  */
1401 static int ice_service_task_stop(struct ice_pf *pf)
1402 {
1403         int ret;
1404
1405         ret = test_and_set_bit(__ICE_SERVICE_DIS, pf->state);
1406
1407         if (pf->serv_tmr.function)
1408                 del_timer_sync(&pf->serv_tmr);
1409         if (pf->serv_task.func)
1410                 cancel_work_sync(&pf->serv_task);
1411
1412         clear_bit(__ICE_SERVICE_SCHED, pf->state);
1413         return ret;
1414 }
1415
1416 /**
1417  * ice_service_task_restart - restart service task and schedule works
1418  * @pf: board private structure
1419  *
1420  * This function is needed for suspend and resume works (e.g WoL scenario)
1421  */
1422 static void ice_service_task_restart(struct ice_pf *pf)
1423 {
1424         clear_bit(__ICE_SERVICE_DIS, pf->state);
1425         ice_service_task_schedule(pf);
1426 }
1427
1428 /**
1429  * ice_service_timer - timer callback to schedule service task
1430  * @t: pointer to timer_list
1431  */
1432 static void ice_service_timer(struct timer_list *t)
1433 {
1434         struct ice_pf *pf = from_timer(pf, t, serv_tmr);
1435
1436         mod_timer(&pf->serv_tmr, round_jiffies(pf->serv_tmr_period + jiffies));
1437         ice_service_task_schedule(pf);
1438 }
1439
1440 /**
1441  * ice_handle_mdd_event - handle malicious driver detect event
1442  * @pf: pointer to the PF structure
1443  *
1444  * Called from service task. OICR interrupt handler indicates MDD event.
1445  * VF MDD logging is guarded by net_ratelimit. Additional PF and VF log
1446  * messages are wrapped by netif_msg_[rx|tx]_err. Since VF Rx MDD events
1447  * disable the queue, the PF can be configured to reset the VF using ethtool
1448  * private flag mdd-auto-reset-vf.
1449  */
1450 static void ice_handle_mdd_event(struct ice_pf *pf)
1451 {
1452         struct device *dev = ice_pf_to_dev(pf);
1453         struct ice_hw *hw = &pf->hw;
1454         unsigned int i;
1455         u32 reg;
1456
1457         if (!test_and_clear_bit(__ICE_MDD_EVENT_PENDING, pf->state)) {
1458                 /* Since the VF MDD event logging is rate limited, check if
1459                  * there are pending MDD events.
1460                  */
1461                 ice_print_vfs_mdd_events(pf);
1462                 return;
1463         }
1464
1465         /* find what triggered an MDD event */
1466         reg = rd32(hw, GL_MDET_TX_PQM);
1467         if (reg & GL_MDET_TX_PQM_VALID_M) {
1468                 u8 pf_num = (reg & GL_MDET_TX_PQM_PF_NUM_M) >>
1469                                 GL_MDET_TX_PQM_PF_NUM_S;
1470                 u16 vf_num = (reg & GL_MDET_TX_PQM_VF_NUM_M) >>
1471                                 GL_MDET_TX_PQM_VF_NUM_S;
1472                 u8 event = (reg & GL_MDET_TX_PQM_MAL_TYPE_M) >>
1473                                 GL_MDET_TX_PQM_MAL_TYPE_S;
1474                 u16 queue = ((reg & GL_MDET_TX_PQM_QNUM_M) >>
1475                                 GL_MDET_TX_PQM_QNUM_S);
1476
1477                 if (netif_msg_tx_err(pf))
1478                         dev_info(dev, "Malicious Driver Detection event %d on TX queue %d PF# %d VF# %d\n",
1479                                  event, queue, pf_num, vf_num);
1480                 wr32(hw, GL_MDET_TX_PQM, 0xffffffff);
1481         }
1482
1483         reg = rd32(hw, GL_MDET_TX_TCLAN);
1484         if (reg & GL_MDET_TX_TCLAN_VALID_M) {
1485                 u8 pf_num = (reg & GL_MDET_TX_TCLAN_PF_NUM_M) >>
1486                                 GL_MDET_TX_TCLAN_PF_NUM_S;
1487                 u16 vf_num = (reg & GL_MDET_TX_TCLAN_VF_NUM_M) >>
1488                                 GL_MDET_TX_TCLAN_VF_NUM_S;
1489                 u8 event = (reg & GL_MDET_TX_TCLAN_MAL_TYPE_M) >>
1490                                 GL_MDET_TX_TCLAN_MAL_TYPE_S;
1491                 u16 queue = ((reg & GL_MDET_TX_TCLAN_QNUM_M) >>
1492                                 GL_MDET_TX_TCLAN_QNUM_S);
1493
1494                 if (netif_msg_tx_err(pf))
1495                         dev_info(dev, "Malicious Driver Detection event %d on TX queue %d PF# %d VF# %d\n",
1496                                  event, queue, pf_num, vf_num);
1497                 wr32(hw, GL_MDET_TX_TCLAN, 0xffffffff);
1498         }
1499
1500         reg = rd32(hw, GL_MDET_RX);
1501         if (reg & GL_MDET_RX_VALID_M) {
1502                 u8 pf_num = (reg & GL_MDET_RX_PF_NUM_M) >>
1503                                 GL_MDET_RX_PF_NUM_S;
1504                 u16 vf_num = (reg & GL_MDET_RX_VF_NUM_M) >>
1505                                 GL_MDET_RX_VF_NUM_S;
1506                 u8 event = (reg & GL_MDET_RX_MAL_TYPE_M) >>
1507                                 GL_MDET_RX_MAL_TYPE_S;
1508                 u16 queue = ((reg & GL_MDET_RX_QNUM_M) >>
1509                                 GL_MDET_RX_QNUM_S);
1510
1511                 if (netif_msg_rx_err(pf))
1512                         dev_info(dev, "Malicious Driver Detection event %d on RX queue %d PF# %d VF# %d\n",
1513                                  event, queue, pf_num, vf_num);
1514                 wr32(hw, GL_MDET_RX, 0xffffffff);
1515         }
1516
1517         /* check to see if this PF caused an MDD event */
1518         reg = rd32(hw, PF_MDET_TX_PQM);
1519         if (reg & PF_MDET_TX_PQM_VALID_M) {
1520                 wr32(hw, PF_MDET_TX_PQM, 0xFFFF);
1521                 if (netif_msg_tx_err(pf))
1522                         dev_info(dev, "Malicious Driver Detection event TX_PQM detected on PF\n");
1523         }
1524
1525         reg = rd32(hw, PF_MDET_TX_TCLAN);
1526         if (reg & PF_MDET_TX_TCLAN_VALID_M) {
1527                 wr32(hw, PF_MDET_TX_TCLAN, 0xFFFF);
1528                 if (netif_msg_tx_err(pf))
1529                         dev_info(dev, "Malicious Driver Detection event TX_TCLAN detected on PF\n");
1530         }
1531
1532         reg = rd32(hw, PF_MDET_RX);
1533         if (reg & PF_MDET_RX_VALID_M) {
1534                 wr32(hw, PF_MDET_RX, 0xFFFF);
1535                 if (netif_msg_rx_err(pf))
1536                         dev_info(dev, "Malicious Driver Detection event RX detected on PF\n");
1537         }
1538
1539         /* Check to see if one of the VFs caused an MDD event, and then
1540          * increment counters and set print pending
1541          */
1542         ice_for_each_vf(pf, i) {
1543                 struct ice_vf *vf = &pf->vf[i];
1544
1545                 reg = rd32(hw, VP_MDET_TX_PQM(i));
1546                 if (reg & VP_MDET_TX_PQM_VALID_M) {
1547                         wr32(hw, VP_MDET_TX_PQM(i), 0xFFFF);
1548                         vf->mdd_tx_events.count++;
1549                         set_bit(__ICE_MDD_VF_PRINT_PENDING, pf->state);
1550                         if (netif_msg_tx_err(pf))
1551                                 dev_info(dev, "Malicious Driver Detection event TX_PQM detected on VF %d\n",
1552                                          i);
1553                 }
1554
1555                 reg = rd32(hw, VP_MDET_TX_TCLAN(i));
1556                 if (reg & VP_MDET_TX_TCLAN_VALID_M) {
1557                         wr32(hw, VP_MDET_TX_TCLAN(i), 0xFFFF);
1558                         vf->mdd_tx_events.count++;
1559                         set_bit(__ICE_MDD_VF_PRINT_PENDING, pf->state);
1560                         if (netif_msg_tx_err(pf))
1561                                 dev_info(dev, "Malicious Driver Detection event TX_TCLAN detected on VF %d\n",
1562                                          i);
1563                 }
1564
1565                 reg = rd32(hw, VP_MDET_TX_TDPU(i));
1566                 if (reg & VP_MDET_TX_TDPU_VALID_M) {
1567                         wr32(hw, VP_MDET_TX_TDPU(i), 0xFFFF);
1568                         vf->mdd_tx_events.count++;
1569                         set_bit(__ICE_MDD_VF_PRINT_PENDING, pf->state);
1570                         if (netif_msg_tx_err(pf))
1571                                 dev_info(dev, "Malicious Driver Detection event TX_TDPU detected on VF %d\n",
1572                                          i);
1573                 }
1574
1575                 reg = rd32(hw, VP_MDET_RX(i));
1576                 if (reg & VP_MDET_RX_VALID_M) {
1577                         wr32(hw, VP_MDET_RX(i), 0xFFFF);
1578                         vf->mdd_rx_events.count++;
1579                         set_bit(__ICE_MDD_VF_PRINT_PENDING, pf->state);
1580                         if (netif_msg_rx_err(pf))
1581                                 dev_info(dev, "Malicious Driver Detection event RX detected on VF %d\n",
1582                                          i);
1583
1584                         /* Since the queue is disabled on VF Rx MDD events, the
1585                          * PF can be configured to reset the VF through ethtool
1586                          * private flag mdd-auto-reset-vf.
1587                          */
1588                         if (test_bit(ICE_FLAG_MDD_AUTO_RESET_VF, pf->flags)) {
1589                                 /* VF MDD event counters will be cleared by
1590                                  * reset, so print the event prior to reset.
1591                                  */
1592                                 ice_print_vf_rx_mdd_event(vf);
1593                                 ice_reset_vf(&pf->vf[i], false);
1594                         }
1595                 }
1596         }
1597
1598         ice_print_vfs_mdd_events(pf);
1599 }
1600
1601 /**
1602  * ice_force_phys_link_state - Force the physical link state
1603  * @vsi: VSI to force the physical link state to up/down
1604  * @link_up: true/false indicates to set the physical link to up/down
1605  *
1606  * Force the physical link state by getting the current PHY capabilities from
1607  * hardware and setting the PHY config based on the determined capabilities. If
1608  * link changes a link event will be triggered because both the Enable Automatic
1609  * Link Update and LESM Enable bits are set when setting the PHY capabilities.
1610  *
1611  * Returns 0 on success, negative on failure
1612  */
1613 static int ice_force_phys_link_state(struct ice_vsi *vsi, bool link_up)
1614 {
1615         struct ice_aqc_get_phy_caps_data *pcaps;
1616         struct ice_aqc_set_phy_cfg_data *cfg;
1617         struct ice_port_info *pi;
1618         struct device *dev;
1619         int retcode;
1620
1621         if (!vsi || !vsi->port_info || !vsi->back)
1622                 return -EINVAL;
1623         if (vsi->type != ICE_VSI_PF)
1624                 return 0;
1625
1626         dev = ice_pf_to_dev(vsi->back);
1627
1628         pi = vsi->port_info;
1629
1630         pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL);
1631         if (!pcaps)
1632                 return -ENOMEM;
1633
1634         retcode = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_SW_CFG, pcaps,
1635                                       NULL);
1636         if (retcode) {
1637                 dev_err(dev, "Failed to get phy capabilities, VSI %d error %d\n",
1638                         vsi->vsi_num, retcode);
1639                 retcode = -EIO;
1640                 goto out;
1641         }
1642
1643         /* No change in link */
1644         if (link_up == !!(pcaps->caps & ICE_AQC_PHY_EN_LINK) &&
1645             link_up == !!(pi->phy.link_info.link_info & ICE_AQ_LINK_UP))
1646                 goto out;
1647
1648         /* Use the current user PHY configuration. The current user PHY
1649          * configuration is initialized during probe from PHY capabilities
1650          * software mode, and updated on set PHY configuration.
1651          */
1652         cfg = kmemdup(&pi->phy.curr_user_phy_cfg, sizeof(*cfg), GFP_KERNEL);
1653         if (!cfg) {
1654                 retcode = -ENOMEM;
1655                 goto out;
1656         }
1657
1658         cfg->caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT;
1659         if (link_up)
1660                 cfg->caps |= ICE_AQ_PHY_ENA_LINK;
1661         else
1662                 cfg->caps &= ~ICE_AQ_PHY_ENA_LINK;
1663
1664         retcode = ice_aq_set_phy_cfg(&vsi->back->hw, pi, cfg, NULL);
1665         if (retcode) {
1666                 dev_err(dev, "Failed to set phy config, VSI %d error %d\n",
1667                         vsi->vsi_num, retcode);
1668                 retcode = -EIO;
1669         }
1670
1671         kfree(cfg);
1672 out:
1673         kfree(pcaps);
1674         return retcode;
1675 }
1676
1677 /**
1678  * ice_init_nvm_phy_type - Initialize the NVM PHY type
1679  * @pi: port info structure
1680  *
1681  * Initialize nvm_phy_type_[low|high] for link lenient mode support
1682  */
1683 static int ice_init_nvm_phy_type(struct ice_port_info *pi)
1684 {
1685         struct ice_aqc_get_phy_caps_data *pcaps;
1686         struct ice_pf *pf = pi->hw->back;
1687         enum ice_status status;
1688         int err = 0;
1689
1690         pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL);
1691         if (!pcaps)
1692                 return -ENOMEM;
1693
1694         status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_NVM_CAP, pcaps,
1695                                      NULL);
1696
1697         if (status) {
1698                 dev_err(ice_pf_to_dev(pf), "Get PHY capability failed.\n");
1699                 err = -EIO;
1700                 goto out;
1701         }
1702
1703         pf->nvm_phy_type_hi = pcaps->phy_type_high;
1704         pf->nvm_phy_type_lo = pcaps->phy_type_low;
1705
1706 out:
1707         kfree(pcaps);
1708         return err;
1709 }
1710
1711 /**
1712  * ice_init_link_dflt_override - Initialize link default override
1713  * @pi: port info structure
1714  *
1715  * Initialize link default override and PHY total port shutdown during probe
1716  */
1717 static void ice_init_link_dflt_override(struct ice_port_info *pi)
1718 {
1719         struct ice_link_default_override_tlv *ldo;
1720         struct ice_pf *pf = pi->hw->back;
1721
1722         ldo = &pf->link_dflt_override;
1723         if (ice_get_link_default_override(ldo, pi))
1724                 return;
1725
1726         if (!(ldo->options & ICE_LINK_OVERRIDE_PORT_DIS))
1727                 return;
1728
1729         /* Enable Total Port Shutdown (override/replace link-down-on-close
1730          * ethtool private flag) for ports with Port Disable bit set.
1731          */
1732         set_bit(ICE_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags);
1733         set_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags);
1734 }
1735
1736 /**
1737  * ice_init_phy_cfg_dflt_override - Initialize PHY cfg default override settings
1738  * @pi: port info structure
1739  *
1740  * If default override is enabled, initialized the user PHY cfg speed and FEC
1741  * settings using the default override mask from the NVM.
1742  *
1743  * The PHY should only be configured with the default override settings the
1744  * first time media is available. The __ICE_LINK_DEFAULT_OVERRIDE_PENDING state
1745  * is used to indicate that the user PHY cfg default override is initialized
1746  * and the PHY has not been configured with the default override settings. The
1747  * state is set here, and cleared in ice_configure_phy the first time the PHY is
1748  * configured.
1749  */
1750 static void ice_init_phy_cfg_dflt_override(struct ice_port_info *pi)
1751 {
1752         struct ice_link_default_override_tlv *ldo;
1753         struct ice_aqc_set_phy_cfg_data *cfg;
1754         struct ice_phy_info *phy = &pi->phy;
1755         struct ice_pf *pf = pi->hw->back;
1756
1757         ldo = &pf->link_dflt_override;
1758
1759         /* If link default override is enabled, use to mask NVM PHY capabilities
1760          * for speed and FEC default configuration.
1761          */
1762         cfg = &phy->curr_user_phy_cfg;
1763
1764         if (ldo->phy_type_low || ldo->phy_type_high) {
1765                 cfg->phy_type_low = pf->nvm_phy_type_lo &
1766                                     cpu_to_le64(ldo->phy_type_low);
1767                 cfg->phy_type_high = pf->nvm_phy_type_hi &
1768                                      cpu_to_le64(ldo->phy_type_high);
1769         }
1770         cfg->link_fec_opt = ldo->fec_options;
1771         phy->curr_user_fec_req = ICE_FEC_AUTO;
1772
1773         set_bit(__ICE_LINK_DEFAULT_OVERRIDE_PENDING, pf->state);
1774 }
1775
1776 /**
1777  * ice_init_phy_user_cfg - Initialize the PHY user configuration
1778  * @pi: port info structure
1779  *
1780  * Initialize the current user PHY configuration, speed, FEC, and FC requested
1781  * mode to default. The PHY defaults are from get PHY capabilities topology
1782  * with media so call when media is first available. An error is returned if
1783  * called when media is not available. The PHY initialization completed state is
1784  * set here.
1785  *
1786  * These configurations are used when setting PHY
1787  * configuration. The user PHY configuration is updated on set PHY
1788  * configuration. Returns 0 on success, negative on failure
1789  */
1790 static int ice_init_phy_user_cfg(struct ice_port_info *pi)
1791 {
1792         struct ice_aqc_get_phy_caps_data *pcaps;
1793         struct ice_phy_info *phy = &pi->phy;
1794         struct ice_pf *pf = pi->hw->back;
1795         enum ice_status status;
1796         struct ice_vsi *vsi;
1797         int err = 0;
1798
1799         if (!(phy->link_info.link_info & ICE_AQ_MEDIA_AVAILABLE))
1800                 return -EIO;
1801
1802         vsi = ice_get_main_vsi(pf);
1803         if (!vsi)
1804                 return -EINVAL;
1805
1806         pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL);
1807         if (!pcaps)
1808                 return -ENOMEM;
1809
1810         status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_TOPO_CAP, pcaps,
1811                                      NULL);
1812         if (status) {
1813                 dev_err(ice_pf_to_dev(pf), "Get PHY capability failed.\n");
1814                 err = -EIO;
1815                 goto err_out;
1816         }
1817
1818         ice_copy_phy_caps_to_cfg(pi, pcaps, &pi->phy.curr_user_phy_cfg);
1819
1820         /* check if lenient mode is supported and enabled */
1821         if (ice_fw_supports_link_override(&vsi->back->hw) &&
1822             !(pcaps->module_compliance_enforcement &
1823               ICE_AQC_MOD_ENFORCE_STRICT_MODE)) {
1824                 set_bit(ICE_FLAG_LINK_LENIENT_MODE_ENA, pf->flags);
1825
1826                 /* if link default override is enabled, initialize user PHY
1827                  * configuration with link default override values
1828                  */
1829                 if (pf->link_dflt_override.options & ICE_LINK_OVERRIDE_EN) {
1830                         ice_init_phy_cfg_dflt_override(pi);
1831                         goto out;
1832                 }
1833         }
1834
1835         /* if link default override is not enabled, initialize PHY using
1836          * topology with media
1837          */
1838         phy->curr_user_fec_req = ice_caps_to_fec_mode(pcaps->caps,
1839                                                       pcaps->link_fec_options);
1840         phy->curr_user_fc_req = ice_caps_to_fc_mode(pcaps->caps);
1841
1842 out:
1843         phy->curr_user_speed_req = ICE_AQ_LINK_SPEED_M;
1844         set_bit(__ICE_PHY_INIT_COMPLETE, pf->state);
1845 err_out:
1846         kfree(pcaps);
1847         return err;
1848 }
1849
1850 /**
1851  * ice_configure_phy - configure PHY
1852  * @vsi: VSI of PHY
1853  *
1854  * Set the PHY configuration. If the current PHY configuration is the same as
1855  * the curr_user_phy_cfg, then do nothing to avoid link flap. Otherwise
1856  * configure the based get PHY capabilities for topology with media.
1857  */
1858 static int ice_configure_phy(struct ice_vsi *vsi)
1859 {
1860         struct device *dev = ice_pf_to_dev(vsi->back);
1861         struct ice_aqc_get_phy_caps_data *pcaps;
1862         struct ice_aqc_set_phy_cfg_data *cfg;
1863         struct ice_port_info *pi;
1864         enum ice_status status;
1865         int err = 0;
1866
1867         pi = vsi->port_info;
1868         if (!pi)
1869                 return -EINVAL;
1870
1871         /* Ensure we have media as we cannot configure a medialess port */
1872         if (!(pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE))
1873                 return -EPERM;
1874
1875         ice_print_topo_conflict(vsi);
1876
1877         if (vsi->port_info->phy.link_info.topo_media_conflict ==
1878             ICE_AQ_LINK_TOPO_UNSUPP_MEDIA)
1879                 return -EPERM;
1880
1881         if (test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags))
1882                 return ice_force_phys_link_state(vsi, true);
1883
1884         pcaps = kzalloc(sizeof(*pcaps), GFP_KERNEL);
1885         if (!pcaps)
1886                 return -ENOMEM;
1887
1888         /* Get current PHY config */
1889         status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_SW_CFG, pcaps,
1890                                      NULL);
1891         if (status) {
1892                 dev_err(dev, "Failed to get PHY configuration, VSI %d error %s\n",
1893                         vsi->vsi_num, ice_stat_str(status));
1894                 err = -EIO;
1895                 goto done;
1896         }
1897
1898         /* If PHY enable link is configured and configuration has not changed,
1899          * there's nothing to do
1900          */
1901         if (pcaps->caps & ICE_AQC_PHY_EN_LINK &&
1902             ice_phy_caps_equals_cfg(pcaps, &pi->phy.curr_user_phy_cfg))
1903                 goto done;
1904
1905         /* Use PHY topology as baseline for configuration */
1906         memset(pcaps, 0, sizeof(*pcaps));
1907         status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_TOPO_CAP, pcaps,
1908                                      NULL);
1909         if (status) {
1910                 dev_err(dev, "Failed to get PHY topology, VSI %d error %s\n",
1911                         vsi->vsi_num, ice_stat_str(status));
1912                 err = -EIO;
1913                 goto done;
1914         }
1915
1916         cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
1917         if (!cfg) {
1918                 err = -ENOMEM;
1919                 goto done;
1920         }
1921
1922         ice_copy_phy_caps_to_cfg(pi, pcaps, cfg);
1923
1924         /* Speed - If default override pending, use curr_user_phy_cfg set in
1925          * ice_init_phy_user_cfg_ldo.
1926          */
1927         if (test_and_clear_bit(__ICE_LINK_DEFAULT_OVERRIDE_PENDING,
1928                                vsi->back->state)) {
1929                 cfg->phy_type_low = pi->phy.curr_user_phy_cfg.phy_type_low;
1930                 cfg->phy_type_high = pi->phy.curr_user_phy_cfg.phy_type_high;
1931         } else {
1932                 u64 phy_low = 0, phy_high = 0;
1933
1934                 ice_update_phy_type(&phy_low, &phy_high,
1935                                     pi->phy.curr_user_speed_req);
1936                 cfg->phy_type_low = pcaps->phy_type_low & cpu_to_le64(phy_low);
1937                 cfg->phy_type_high = pcaps->phy_type_high &
1938                                      cpu_to_le64(phy_high);
1939         }
1940
1941         /* Can't provide what was requested; use PHY capabilities */
1942         if (!cfg->phy_type_low && !cfg->phy_type_high) {
1943                 cfg->phy_type_low = pcaps->phy_type_low;
1944                 cfg->phy_type_high = pcaps->phy_type_high;
1945         }
1946
1947         /* FEC */
1948         ice_cfg_phy_fec(pi, cfg, pi->phy.curr_user_fec_req);
1949
1950         /* Can't provide what was requested; use PHY capabilities */
1951         if (cfg->link_fec_opt !=
1952             (cfg->link_fec_opt & pcaps->link_fec_options)) {
1953                 cfg->caps |= pcaps->caps & ICE_AQC_PHY_EN_AUTO_FEC;
1954                 cfg->link_fec_opt = pcaps->link_fec_options;
1955         }
1956
1957         /* Flow Control - always supported; no need to check against
1958          * capabilities
1959          */
1960         ice_cfg_phy_fc(pi, cfg, pi->phy.curr_user_fc_req);
1961
1962         /* Enable link and link update */
1963         cfg->caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT | ICE_AQ_PHY_ENA_LINK;
1964
1965         status = ice_aq_set_phy_cfg(&vsi->back->hw, pi, cfg, NULL);
1966         if (status) {
1967                 dev_err(dev, "Failed to set phy config, VSI %d error %s\n",
1968                         vsi->vsi_num, ice_stat_str(status));
1969                 err = -EIO;
1970         }
1971
1972         kfree(cfg);
1973 done:
1974         kfree(pcaps);
1975         return err;
1976 }
1977
1978 /**
1979  * ice_check_media_subtask - Check for media
1980  * @pf: pointer to PF struct
1981  *
1982  * If media is available, then initialize PHY user configuration if it is not
1983  * been, and configure the PHY if the interface is up.
1984  */
1985 static void ice_check_media_subtask(struct ice_pf *pf)
1986 {
1987         struct ice_port_info *pi;
1988         struct ice_vsi *vsi;
1989         int err;
1990
1991         /* No need to check for media if it's already present */
1992         if (!test_bit(ICE_FLAG_NO_MEDIA, pf->flags))
1993                 return;
1994
1995         vsi = ice_get_main_vsi(pf);
1996         if (!vsi)
1997                 return;
1998
1999         /* Refresh link info and check if media is present */
2000         pi = vsi->port_info;
2001         err = ice_update_link_info(pi);
2002         if (err)
2003                 return;
2004
2005         if (pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE) {
2006                 if (!test_bit(__ICE_PHY_INIT_COMPLETE, pf->state))
2007                         ice_init_phy_user_cfg(pi);
2008
2009                 /* PHY settings are reset on media insertion, reconfigure
2010                  * PHY to preserve settings.
2011                  */
2012                 if (test_bit(__ICE_DOWN, vsi->state) &&
2013                     test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags))
2014                         return;
2015
2016                 err = ice_configure_phy(vsi);
2017                 if (!err)
2018                         clear_bit(ICE_FLAG_NO_MEDIA, pf->flags);
2019
2020                 /* A Link Status Event will be generated; the event handler
2021                  * will complete bringing the interface up
2022                  */
2023         }
2024 }
2025
2026 /**
2027  * ice_service_task - manage and run subtasks
2028  * @work: pointer to work_struct contained by the PF struct
2029  */
2030 static void ice_service_task(struct work_struct *work)
2031 {
2032         struct ice_pf *pf = container_of(work, struct ice_pf, serv_task);
2033         unsigned long start_time = jiffies;
2034
2035         /* subtasks */
2036
2037         /* process reset requests first */
2038         ice_reset_subtask(pf);
2039
2040         /* bail if a reset/recovery cycle is pending or rebuild failed */
2041         if (ice_is_reset_in_progress(pf->state) ||
2042             test_bit(__ICE_SUSPENDED, pf->state) ||
2043             test_bit(__ICE_NEEDS_RESTART, pf->state)) {
2044                 ice_service_task_complete(pf);
2045                 return;
2046         }
2047
2048         ice_clean_adminq_subtask(pf);
2049         ice_check_media_subtask(pf);
2050         ice_check_for_hang_subtask(pf);
2051         ice_sync_fltr_subtask(pf);
2052         ice_handle_mdd_event(pf);
2053         ice_watchdog_subtask(pf);
2054
2055         if (ice_is_safe_mode(pf)) {
2056                 ice_service_task_complete(pf);
2057                 return;
2058         }
2059
2060         ice_process_vflr_event(pf);
2061         ice_clean_mailboxq_subtask(pf);
2062         ice_sync_arfs_fltrs(pf);
2063         ice_flush_fdir_ctx(pf);
2064         /* Clear __ICE_SERVICE_SCHED flag to allow scheduling next event */
2065         ice_service_task_complete(pf);
2066
2067         /* If the tasks have taken longer than one service timer period
2068          * or there is more work to be done, reset the service timer to
2069          * schedule the service task now.
2070          */
2071         if (time_after(jiffies, (start_time + pf->serv_tmr_period)) ||
2072             test_bit(__ICE_MDD_EVENT_PENDING, pf->state) ||
2073             test_bit(__ICE_VFLR_EVENT_PENDING, pf->state) ||
2074             test_bit(__ICE_MAILBOXQ_EVENT_PENDING, pf->state) ||
2075             test_bit(__ICE_FD_VF_FLUSH_CTX, pf->state) ||
2076             test_bit(__ICE_ADMINQ_EVENT_PENDING, pf->state))
2077                 mod_timer(&pf->serv_tmr, jiffies);
2078 }
2079
2080 /**
2081  * ice_set_ctrlq_len - helper function to set controlq length
2082  * @hw: pointer to the HW instance
2083  */
2084 static void ice_set_ctrlq_len(struct ice_hw *hw)
2085 {
2086         hw->adminq.num_rq_entries = ICE_AQ_LEN;
2087         hw->adminq.num_sq_entries = ICE_AQ_LEN;
2088         hw->adminq.rq_buf_size = ICE_AQ_MAX_BUF_LEN;
2089         hw->adminq.sq_buf_size = ICE_AQ_MAX_BUF_LEN;
2090         hw->mailboxq.num_rq_entries = PF_MBX_ARQLEN_ARQLEN_M;
2091         hw->mailboxq.num_sq_entries = ICE_MBXSQ_LEN;
2092         hw->mailboxq.rq_buf_size = ICE_MBXQ_MAX_BUF_LEN;
2093         hw->mailboxq.sq_buf_size = ICE_MBXQ_MAX_BUF_LEN;
2094 }
2095
2096 /**
2097  * ice_schedule_reset - schedule a reset
2098  * @pf: board private structure
2099  * @reset: reset being requested
2100  */
2101 int ice_schedule_reset(struct ice_pf *pf, enum ice_reset_req reset)
2102 {
2103         struct device *dev = ice_pf_to_dev(pf);
2104
2105         /* bail out if earlier reset has failed */
2106         if (test_bit(__ICE_RESET_FAILED, pf->state)) {
2107                 dev_dbg(dev, "earlier reset has failed\n");
2108                 return -EIO;
2109         }
2110         /* bail if reset/recovery already in progress */
2111         if (ice_is_reset_in_progress(pf->state)) {
2112                 dev_dbg(dev, "Reset already in progress\n");
2113                 return -EBUSY;
2114         }
2115
2116         switch (reset) {
2117         case ICE_RESET_PFR:
2118                 set_bit(__ICE_PFR_REQ, pf->state);
2119                 break;
2120         case ICE_RESET_CORER:
2121                 set_bit(__ICE_CORER_REQ, pf->state);
2122                 break;
2123         case ICE_RESET_GLOBR:
2124                 set_bit(__ICE_GLOBR_REQ, pf->state);
2125                 break;
2126         default:
2127                 return -EINVAL;
2128         }
2129
2130         ice_service_task_schedule(pf);
2131         return 0;
2132 }
2133
2134 /**
2135  * ice_irq_affinity_notify - Callback for affinity changes
2136  * @notify: context as to what irq was changed
2137  * @mask: the new affinity mask
2138  *
2139  * This is a callback function used by the irq_set_affinity_notifier function
2140  * so that we may register to receive changes to the irq affinity masks.
2141  */
2142 static void
2143 ice_irq_affinity_notify(struct irq_affinity_notify *notify,
2144                         const cpumask_t *mask)
2145 {
2146         struct ice_q_vector *q_vector =
2147                 container_of(notify, struct ice_q_vector, affinity_notify);
2148
2149         cpumask_copy(&q_vector->affinity_mask, mask);
2150 }
2151
2152 /**
2153  * ice_irq_affinity_release - Callback for affinity notifier release
2154  * @ref: internal core kernel usage
2155  *
2156  * This is a callback function used by the irq_set_affinity_notifier function
2157  * to inform the current notification subscriber that they will no longer
2158  * receive notifications.
2159  */
2160 static void ice_irq_affinity_release(struct kref __always_unused *ref) {}
2161
2162 /**
2163  * ice_vsi_ena_irq - Enable IRQ for the given VSI
2164  * @vsi: the VSI being configured
2165  */
2166 static int ice_vsi_ena_irq(struct ice_vsi *vsi)
2167 {
2168         struct ice_hw *hw = &vsi->back->hw;
2169         int i;
2170
2171         ice_for_each_q_vector(vsi, i)
2172                 ice_irq_dynamic_ena(hw, vsi, vsi->q_vectors[i]);
2173
2174         ice_flush(hw);
2175         return 0;
2176 }
2177
2178 /**
2179  * ice_vsi_req_irq_msix - get MSI-X vectors from the OS for the VSI
2180  * @vsi: the VSI being configured
2181  * @basename: name for the vector
2182  */
2183 static int ice_vsi_req_irq_msix(struct ice_vsi *vsi, char *basename)
2184 {
2185         int q_vectors = vsi->num_q_vectors;
2186         struct ice_pf *pf = vsi->back;
2187         int base = vsi->base_vector;
2188         struct device *dev;
2189         int rx_int_idx = 0;
2190         int tx_int_idx = 0;
2191         int vector, err;
2192         int irq_num;
2193
2194         dev = ice_pf_to_dev(pf);
2195         for (vector = 0; vector < q_vectors; vector++) {
2196                 struct ice_q_vector *q_vector = vsi->q_vectors[vector];
2197
2198                 irq_num = pf->msix_entries[base + vector].vector;
2199
2200                 if (q_vector->tx.ring && q_vector->rx.ring) {
2201                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
2202                                  "%s-%s-%d", basename, "TxRx", rx_int_idx++);
2203                         tx_int_idx++;
2204                 } else if (q_vector->rx.ring) {
2205                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
2206                                  "%s-%s-%d", basename, "rx", rx_int_idx++);
2207                 } else if (q_vector->tx.ring) {
2208                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
2209                                  "%s-%s-%d", basename, "tx", tx_int_idx++);
2210                 } else {
2211                         /* skip this unused q_vector */
2212                         continue;
2213                 }
2214                 if (vsi->type == ICE_VSI_CTRL && vsi->vf_id != ICE_INVAL_VFID)
2215                         err = devm_request_irq(dev, irq_num, vsi->irq_handler,
2216                                                IRQF_SHARED, q_vector->name,
2217                                                q_vector);
2218                 else
2219                         err = devm_request_irq(dev, irq_num, vsi->irq_handler,
2220                                                0, q_vector->name, q_vector);
2221                 if (err) {
2222                         netdev_err(vsi->netdev, "MSIX request_irq failed, error: %d\n",
2223                                    err);
2224                         goto free_q_irqs;
2225                 }
2226
2227                 /* register for affinity change notifications */
2228                 if (!IS_ENABLED(CONFIG_RFS_ACCEL)) {
2229                         struct irq_affinity_notify *affinity_notify;
2230
2231                         affinity_notify = &q_vector->affinity_notify;
2232                         affinity_notify->notify = ice_irq_affinity_notify;
2233                         affinity_notify->release = ice_irq_affinity_release;
2234                         irq_set_affinity_notifier(irq_num, affinity_notify);
2235                 }
2236
2237                 /* assign the mask for this irq */
2238                 irq_set_affinity_hint(irq_num, &q_vector->affinity_mask);
2239         }
2240
2241         vsi->irqs_ready = true;
2242         return 0;
2243
2244 free_q_irqs:
2245         while (vector) {
2246                 vector--;
2247                 irq_num = pf->msix_entries[base + vector].vector;
2248                 if (!IS_ENABLED(CONFIG_RFS_ACCEL))
2249                         irq_set_affinity_notifier(irq_num, NULL);
2250                 irq_set_affinity_hint(irq_num, NULL);
2251                 devm_free_irq(dev, irq_num, &vsi->q_vectors[vector]);
2252         }
2253         return err;
2254 }
2255
2256 /**
2257  * ice_xdp_alloc_setup_rings - Allocate and setup Tx rings for XDP
2258  * @vsi: VSI to setup Tx rings used by XDP
2259  *
2260  * Return 0 on success and negative value on error
2261  */
2262 static int ice_xdp_alloc_setup_rings(struct ice_vsi *vsi)
2263 {
2264         struct device *dev = ice_pf_to_dev(vsi->back);
2265         int i;
2266
2267         for (i = 0; i < vsi->num_xdp_txq; i++) {
2268                 u16 xdp_q_idx = vsi->alloc_txq + i;
2269                 struct ice_ring *xdp_ring;
2270
2271                 xdp_ring = kzalloc(sizeof(*xdp_ring), GFP_KERNEL);
2272
2273                 if (!xdp_ring)
2274                         goto free_xdp_rings;
2275
2276                 xdp_ring->q_index = xdp_q_idx;
2277                 xdp_ring->reg_idx = vsi->txq_map[xdp_q_idx];
2278                 xdp_ring->ring_active = false;
2279                 xdp_ring->vsi = vsi;
2280                 xdp_ring->netdev = NULL;
2281                 xdp_ring->dev = dev;
2282                 xdp_ring->count = vsi->num_tx_desc;
2283                 WRITE_ONCE(vsi->xdp_rings[i], xdp_ring);
2284                 if (ice_setup_tx_ring(xdp_ring))
2285                         goto free_xdp_rings;
2286                 ice_set_ring_xdp(xdp_ring);
2287                 xdp_ring->xsk_pool = ice_xsk_pool(xdp_ring);
2288         }
2289
2290         return 0;
2291
2292 free_xdp_rings:
2293         for (; i >= 0; i--)
2294                 if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
2295                         ice_free_tx_ring(vsi->xdp_rings[i]);
2296         return -ENOMEM;
2297 }
2298
2299 /**
2300  * ice_vsi_assign_bpf_prog - set or clear bpf prog pointer on VSI
2301  * @vsi: VSI to set the bpf prog on
2302  * @prog: the bpf prog pointer
2303  */
2304 static void ice_vsi_assign_bpf_prog(struct ice_vsi *vsi, struct bpf_prog *prog)
2305 {
2306         struct bpf_prog *old_prog;
2307         int i;
2308
2309         old_prog = xchg(&vsi->xdp_prog, prog);
2310         if (old_prog)
2311                 bpf_prog_put(old_prog);
2312
2313         ice_for_each_rxq(vsi, i)
2314                 WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
2315 }
2316
2317 /**
2318  * ice_prepare_xdp_rings - Allocate, configure and setup Tx rings for XDP
2319  * @vsi: VSI to bring up Tx rings used by XDP
2320  * @prog: bpf program that will be assigned to VSI
2321  *
2322  * Return 0 on success and negative value on error
2323  */
2324 int ice_prepare_xdp_rings(struct ice_vsi *vsi, struct bpf_prog *prog)
2325 {
2326         u16 max_txqs[ICE_MAX_TRAFFIC_CLASS] = { 0 };
2327         int xdp_rings_rem = vsi->num_xdp_txq;
2328         struct ice_pf *pf = vsi->back;
2329         struct ice_qs_cfg xdp_qs_cfg = {
2330                 .qs_mutex = &pf->avail_q_mutex,
2331                 .pf_map = pf->avail_txqs,
2332                 .pf_map_size = pf->max_pf_txqs,
2333                 .q_count = vsi->num_xdp_txq,
2334                 .scatter_count = ICE_MAX_SCATTER_TXQS,
2335                 .vsi_map = vsi->txq_map,
2336                 .vsi_map_offset = vsi->alloc_txq,
2337                 .mapping_mode = ICE_VSI_MAP_CONTIG
2338         };
2339         enum ice_status status;
2340         struct device *dev;
2341         int i, v_idx;
2342
2343         dev = ice_pf_to_dev(pf);
2344         vsi->xdp_rings = devm_kcalloc(dev, vsi->num_xdp_txq,
2345                                       sizeof(*vsi->xdp_rings), GFP_KERNEL);
2346         if (!vsi->xdp_rings)
2347                 return -ENOMEM;
2348
2349         vsi->xdp_mapping_mode = xdp_qs_cfg.mapping_mode;
2350         if (__ice_vsi_get_qs(&xdp_qs_cfg))
2351                 goto err_map_xdp;
2352
2353         if (ice_xdp_alloc_setup_rings(vsi))
2354                 goto clear_xdp_rings;
2355
2356         /* follow the logic from ice_vsi_map_rings_to_vectors */
2357         ice_for_each_q_vector(vsi, v_idx) {
2358                 struct ice_q_vector *q_vector = vsi->q_vectors[v_idx];
2359                 int xdp_rings_per_v, q_id, q_base;
2360
2361                 xdp_rings_per_v = DIV_ROUND_UP(xdp_rings_rem,
2362                                                vsi->num_q_vectors - v_idx);
2363                 q_base = vsi->num_xdp_txq - xdp_rings_rem;
2364
2365                 for (q_id = q_base; q_id < (q_base + xdp_rings_per_v); q_id++) {
2366                         struct ice_ring *xdp_ring = vsi->xdp_rings[q_id];
2367
2368                         xdp_ring->q_vector = q_vector;
2369                         xdp_ring->next = q_vector->tx.ring;
2370                         q_vector->tx.ring = xdp_ring;
2371                 }
2372                 xdp_rings_rem -= xdp_rings_per_v;
2373         }
2374
2375         /* omit the scheduler update if in reset path; XDP queues will be
2376          * taken into account at the end of ice_vsi_rebuild, where
2377          * ice_cfg_vsi_lan is being called
2378          */
2379         if (ice_is_reset_in_progress(pf->state))
2380                 return 0;
2381
2382         /* tell the Tx scheduler that right now we have
2383          * additional queues
2384          */
2385         for (i = 0; i < vsi->tc_cfg.numtc; i++)
2386                 max_txqs[i] = vsi->num_txq + vsi->num_xdp_txq;
2387
2388         status = ice_cfg_vsi_lan(vsi->port_info, vsi->idx, vsi->tc_cfg.ena_tc,
2389                                  max_txqs);
2390         if (status) {
2391                 dev_err(dev, "Failed VSI LAN queue config for XDP, error: %s\n",
2392                         ice_stat_str(status));
2393                 goto clear_xdp_rings;
2394         }
2395         ice_vsi_assign_bpf_prog(vsi, prog);
2396
2397         return 0;
2398 clear_xdp_rings:
2399         for (i = 0; i < vsi->num_xdp_txq; i++)
2400                 if (vsi->xdp_rings[i]) {
2401                         kfree_rcu(vsi->xdp_rings[i], rcu);
2402                         vsi->xdp_rings[i] = NULL;
2403                 }
2404
2405 err_map_xdp:
2406         mutex_lock(&pf->avail_q_mutex);
2407         for (i = 0; i < vsi->num_xdp_txq; i++) {
2408                 clear_bit(vsi->txq_map[i + vsi->alloc_txq], pf->avail_txqs);
2409                 vsi->txq_map[i + vsi->alloc_txq] = ICE_INVAL_Q_INDEX;
2410         }
2411         mutex_unlock(&pf->avail_q_mutex);
2412
2413         devm_kfree(dev, vsi->xdp_rings);
2414         return -ENOMEM;
2415 }
2416
2417 /**
2418  * ice_destroy_xdp_rings - undo the configuration made by ice_prepare_xdp_rings
2419  * @vsi: VSI to remove XDP rings
2420  *
2421  * Detach XDP rings from irq vectors, clean up the PF bitmap and free
2422  * resources
2423  */
2424 int ice_destroy_xdp_rings(struct ice_vsi *vsi)
2425 {
2426         u16 max_txqs[ICE_MAX_TRAFFIC_CLASS] = { 0 };
2427         struct ice_pf *pf = vsi->back;
2428         int i, v_idx;
2429
2430         /* q_vectors are freed in reset path so there's no point in detaching
2431          * rings; in case of rebuild being triggered not from reset bits
2432          * in pf->state won't be set, so additionally check first q_vector
2433          * against NULL
2434          */
2435         if (ice_is_reset_in_progress(pf->state) || !vsi->q_vectors[0])
2436                 goto free_qmap;
2437
2438         ice_for_each_q_vector(vsi, v_idx) {
2439                 struct ice_q_vector *q_vector = vsi->q_vectors[v_idx];
2440                 struct ice_ring *ring;
2441
2442                 ice_for_each_ring(ring, q_vector->tx)
2443                         if (!ring->tx_buf || !ice_ring_is_xdp(ring))
2444                                 break;
2445
2446                 /* restore the value of last node prior to XDP setup */
2447                 q_vector->tx.ring = ring;
2448         }
2449
2450 free_qmap:
2451         mutex_lock(&pf->avail_q_mutex);
2452         for (i = 0; i < vsi->num_xdp_txq; i++) {
2453                 clear_bit(vsi->txq_map[i + vsi->alloc_txq], pf->avail_txqs);
2454                 vsi->txq_map[i + vsi->alloc_txq] = ICE_INVAL_Q_INDEX;
2455         }
2456         mutex_unlock(&pf->avail_q_mutex);
2457
2458         for (i = 0; i < vsi->num_xdp_txq; i++)
2459                 if (vsi->xdp_rings[i]) {
2460                         if (vsi->xdp_rings[i]->desc)
2461                                 ice_free_tx_ring(vsi->xdp_rings[i]);
2462                         kfree_rcu(vsi->xdp_rings[i], rcu);
2463                         vsi->xdp_rings[i] = NULL;
2464                 }
2465
2466         devm_kfree(ice_pf_to_dev(pf), vsi->xdp_rings);
2467         vsi->xdp_rings = NULL;
2468
2469         if (ice_is_reset_in_progress(pf->state) || !vsi->q_vectors[0])
2470                 return 0;
2471
2472         ice_vsi_assign_bpf_prog(vsi, NULL);
2473
2474         /* notify Tx scheduler that we destroyed XDP queues and bring
2475          * back the old number of child nodes
2476          */
2477         for (i = 0; i < vsi->tc_cfg.numtc; i++)
2478                 max_txqs[i] = vsi->num_txq;
2479
2480         /* change number of XDP Tx queues to 0 */
2481         vsi->num_xdp_txq = 0;
2482
2483         return ice_cfg_vsi_lan(vsi->port_info, vsi->idx, vsi->tc_cfg.ena_tc,
2484                                max_txqs);
2485 }
2486
2487 /**
2488  * ice_vsi_rx_napi_schedule - Schedule napi on RX queues from VSI
2489  * @vsi: VSI to schedule napi on
2490  */
2491 static void ice_vsi_rx_napi_schedule(struct ice_vsi *vsi)
2492 {
2493         int i;
2494
2495         ice_for_each_rxq(vsi, i) {
2496                 struct ice_ring *rx_ring = vsi->rx_rings[i];
2497
2498                 if (rx_ring->xsk_pool)
2499                         napi_schedule(&rx_ring->q_vector->napi);
2500         }
2501 }
2502
2503 /**
2504  * ice_xdp_setup_prog - Add or remove XDP eBPF program
2505  * @vsi: VSI to setup XDP for
2506  * @prog: XDP program
2507  * @extack: netlink extended ack
2508  */
2509 static int
2510 ice_xdp_setup_prog(struct ice_vsi *vsi, struct bpf_prog *prog,
2511                    struct netlink_ext_ack *extack)
2512 {
2513         int frame_size = vsi->netdev->mtu + ICE_ETH_PKT_HDR_PAD;
2514         bool if_running = netif_running(vsi->netdev);
2515         int ret = 0, xdp_ring_err = 0;
2516
2517         if (frame_size > vsi->rx_buf_len) {
2518                 NL_SET_ERR_MSG_MOD(extack, "MTU too large for loading XDP");
2519                 return -EOPNOTSUPP;
2520         }
2521
2522         /* need to stop netdev while setting up the program for Rx rings */
2523         if (if_running && !test_and_set_bit(__ICE_DOWN, vsi->state)) {
2524                 ret = ice_down(vsi);
2525                 if (ret) {
2526                         NL_SET_ERR_MSG_MOD(extack, "Preparing device for XDP attach failed");
2527                         return ret;
2528                 }
2529         }
2530
2531         if (!ice_is_xdp_ena_vsi(vsi) && prog) {
2532                 vsi->num_xdp_txq = vsi->alloc_rxq;
2533                 xdp_ring_err = ice_prepare_xdp_rings(vsi, prog);
2534                 if (xdp_ring_err)
2535                         NL_SET_ERR_MSG_MOD(extack, "Setting up XDP Tx resources failed");
2536         } else if (ice_is_xdp_ena_vsi(vsi) && !prog) {
2537                 xdp_ring_err = ice_destroy_xdp_rings(vsi);
2538                 if (xdp_ring_err)
2539                         NL_SET_ERR_MSG_MOD(extack, "Freeing XDP Tx resources failed");
2540         } else {
2541                 ice_vsi_assign_bpf_prog(vsi, prog);
2542         }
2543
2544         if (if_running)
2545                 ret = ice_up(vsi);
2546
2547         if (!ret && prog)
2548                 ice_vsi_rx_napi_schedule(vsi);
2549
2550         return (ret || xdp_ring_err) ? -ENOMEM : 0;
2551 }
2552
2553 /**
2554  * ice_xdp - implements XDP handler
2555  * @dev: netdevice
2556  * @xdp: XDP command
2557  */
2558 static int ice_xdp(struct net_device *dev, struct netdev_bpf *xdp)
2559 {
2560         struct ice_netdev_priv *np = netdev_priv(dev);
2561         struct ice_vsi *vsi = np->vsi;
2562
2563         if (vsi->type != ICE_VSI_PF) {
2564                 NL_SET_ERR_MSG_MOD(xdp->extack, "XDP can be loaded only on PF VSI");
2565                 return -EINVAL;
2566         }
2567
2568         switch (xdp->command) {
2569         case XDP_SETUP_PROG:
2570                 return ice_xdp_setup_prog(vsi, xdp->prog, xdp->extack);
2571         case XDP_SETUP_XSK_POOL:
2572                 return ice_xsk_pool_setup(vsi, xdp->xsk.pool,
2573                                           xdp->xsk.queue_id);
2574         default:
2575                 return -EINVAL;
2576         }
2577 }
2578
2579 /**
2580  * ice_ena_misc_vector - enable the non-queue interrupts
2581  * @pf: board private structure
2582  */
2583 static void ice_ena_misc_vector(struct ice_pf *pf)
2584 {
2585         struct ice_hw *hw = &pf->hw;
2586         u32 val;
2587
2588         /* Disable anti-spoof detection interrupt to prevent spurious event
2589          * interrupts during a function reset. Anti-spoof functionally is
2590          * still supported.
2591          */
2592         val = rd32(hw, GL_MDCK_TX_TDPU);
2593         val |= GL_MDCK_TX_TDPU_RCU_ANTISPOOF_ITR_DIS_M;
2594         wr32(hw, GL_MDCK_TX_TDPU, val);
2595
2596         /* clear things first */
2597         wr32(hw, PFINT_OICR_ENA, 0);    /* disable all */
2598         rd32(hw, PFINT_OICR);           /* read to clear */
2599
2600         val = (PFINT_OICR_ECC_ERR_M |
2601                PFINT_OICR_MAL_DETECT_M |
2602                PFINT_OICR_GRST_M |
2603                PFINT_OICR_PCI_EXCEPTION_M |
2604                PFINT_OICR_VFLR_M |
2605                PFINT_OICR_HMC_ERR_M |
2606                PFINT_OICR_PE_CRITERR_M);
2607
2608         wr32(hw, PFINT_OICR_ENA, val);
2609
2610         /* SW_ITR_IDX = 0, but don't change INTENA */
2611         wr32(hw, GLINT_DYN_CTL(pf->oicr_idx),
2612              GLINT_DYN_CTL_SW_ITR_INDX_M | GLINT_DYN_CTL_INTENA_MSK_M);
2613 }
2614
2615 /**
2616  * ice_misc_intr - misc interrupt handler
2617  * @irq: interrupt number
2618  * @data: pointer to a q_vector
2619  */
2620 static irqreturn_t ice_misc_intr(int __always_unused irq, void *data)
2621 {
2622         struct ice_pf *pf = (struct ice_pf *)data;
2623         struct ice_hw *hw = &pf->hw;
2624         irqreturn_t ret = IRQ_NONE;
2625         struct device *dev;
2626         u32 oicr, ena_mask;
2627
2628         dev = ice_pf_to_dev(pf);
2629         set_bit(__ICE_ADMINQ_EVENT_PENDING, pf->state);
2630         set_bit(__ICE_MAILBOXQ_EVENT_PENDING, pf->state);
2631
2632         oicr = rd32(hw, PFINT_OICR);
2633         ena_mask = rd32(hw, PFINT_OICR_ENA);
2634
2635         if (oicr & PFINT_OICR_SWINT_M) {
2636                 ena_mask &= ~PFINT_OICR_SWINT_M;
2637                 pf->sw_int_count++;
2638         }
2639
2640         if (oicr & PFINT_OICR_MAL_DETECT_M) {
2641                 ena_mask &= ~PFINT_OICR_MAL_DETECT_M;
2642                 set_bit(__ICE_MDD_EVENT_PENDING, pf->state);
2643         }
2644         if (oicr & PFINT_OICR_VFLR_M) {
2645                 /* disable any further VFLR event notifications */
2646                 if (test_bit(__ICE_VF_RESETS_DISABLED, pf->state)) {
2647                         u32 reg = rd32(hw, PFINT_OICR_ENA);
2648
2649                         reg &= ~PFINT_OICR_VFLR_M;
2650                         wr32(hw, PFINT_OICR_ENA, reg);
2651                 } else {
2652                         ena_mask &= ~PFINT_OICR_VFLR_M;
2653                         set_bit(__ICE_VFLR_EVENT_PENDING, pf->state);
2654                 }
2655         }
2656
2657         if (oicr & PFINT_OICR_GRST_M) {
2658                 u32 reset;
2659
2660                 /* we have a reset warning */
2661                 ena_mask &= ~PFINT_OICR_GRST_M;
2662                 reset = (rd32(hw, GLGEN_RSTAT) & GLGEN_RSTAT_RESET_TYPE_M) >>
2663                         GLGEN_RSTAT_RESET_TYPE_S;
2664
2665                 if (reset == ICE_RESET_CORER)
2666                         pf->corer_count++;
2667                 else if (reset == ICE_RESET_GLOBR)
2668                         pf->globr_count++;
2669                 else if (reset == ICE_RESET_EMPR)
2670                         pf->empr_count++;
2671                 else
2672                         dev_dbg(dev, "Invalid reset type %d\n", reset);
2673
2674                 /* If a reset cycle isn't already in progress, we set a bit in
2675                  * pf->state so that the service task can start a reset/rebuild.
2676                  * We also make note of which reset happened so that peer
2677                  * devices/drivers can be informed.
2678                  */
2679                 if (!test_and_set_bit(__ICE_RESET_OICR_RECV, pf->state)) {
2680                         if (reset == ICE_RESET_CORER)
2681                                 set_bit(__ICE_CORER_RECV, pf->state);
2682                         else if (reset == ICE_RESET_GLOBR)
2683                                 set_bit(__ICE_GLOBR_RECV, pf->state);
2684                         else
2685                                 set_bit(__ICE_EMPR_RECV, pf->state);
2686
2687                         /* There are couple of different bits at play here.
2688                          * hw->reset_ongoing indicates whether the hardware is
2689                          * in reset. This is set to true when a reset interrupt
2690                          * is received and set back to false after the driver
2691                          * has determined that the hardware is out of reset.
2692                          *
2693                          * __ICE_RESET_OICR_RECV in pf->state indicates
2694                          * that a post reset rebuild is required before the
2695                          * driver is operational again. This is set above.
2696                          *
2697                          * As this is the start of the reset/rebuild cycle, set
2698                          * both to indicate that.
2699                          */
2700                         hw->reset_ongoing = true;
2701                 }
2702         }
2703
2704         if (oicr & PFINT_OICR_HMC_ERR_M) {
2705                 ena_mask &= ~PFINT_OICR_HMC_ERR_M;
2706                 dev_dbg(dev, "HMC Error interrupt - info 0x%x, data 0x%x\n",
2707                         rd32(hw, PFHMC_ERRORINFO),
2708                         rd32(hw, PFHMC_ERRORDATA));
2709         }
2710
2711         /* Report any remaining unexpected interrupts */
2712         oicr &= ena_mask;
2713         if (oicr) {
2714                 dev_dbg(dev, "unhandled interrupt oicr=0x%08x\n", oicr);
2715                 /* If a critical error is pending there is no choice but to
2716                  * reset the device.
2717                  */
2718                 if (oicr & (PFINT_OICR_PE_CRITERR_M |
2719                             PFINT_OICR_PCI_EXCEPTION_M |
2720                             PFINT_OICR_ECC_ERR_M)) {
2721                         set_bit(__ICE_PFR_REQ, pf->state);
2722                         ice_service_task_schedule(pf);
2723                 }
2724         }
2725         ret = IRQ_HANDLED;
2726
2727         ice_service_task_schedule(pf);
2728         ice_irq_dynamic_ena(hw, NULL, NULL);
2729
2730         return ret;
2731 }
2732
2733 /**
2734  * ice_dis_ctrlq_interrupts - disable control queue interrupts
2735  * @hw: pointer to HW structure
2736  */
2737 static void ice_dis_ctrlq_interrupts(struct ice_hw *hw)
2738 {
2739         /* disable Admin queue Interrupt causes */
2740         wr32(hw, PFINT_FW_CTL,
2741              rd32(hw, PFINT_FW_CTL) & ~PFINT_FW_CTL_CAUSE_ENA_M);
2742
2743         /* disable Mailbox queue Interrupt causes */
2744         wr32(hw, PFINT_MBX_CTL,
2745              rd32(hw, PFINT_MBX_CTL) & ~PFINT_MBX_CTL_CAUSE_ENA_M);
2746
2747         /* disable Control queue Interrupt causes */
2748         wr32(hw, PFINT_OICR_CTL,
2749              rd32(hw, PFINT_OICR_CTL) & ~PFINT_OICR_CTL_CAUSE_ENA_M);
2750
2751         ice_flush(hw);
2752 }
2753
2754 /**
2755  * ice_free_irq_msix_misc - Unroll misc vector setup
2756  * @pf: board private structure
2757  */
2758 static void ice_free_irq_msix_misc(struct ice_pf *pf)
2759 {
2760         struct ice_hw *hw = &pf->hw;
2761
2762         ice_dis_ctrlq_interrupts(hw);
2763
2764         /* disable OICR interrupt */
2765         wr32(hw, PFINT_OICR_ENA, 0);
2766         ice_flush(hw);
2767
2768         if (pf->msix_entries) {
2769                 synchronize_irq(pf->msix_entries[pf->oicr_idx].vector);
2770                 devm_free_irq(ice_pf_to_dev(pf),
2771                               pf->msix_entries[pf->oicr_idx].vector, pf);
2772         }
2773
2774         pf->num_avail_sw_msix += 1;
2775         ice_free_res(pf->irq_tracker, pf->oicr_idx, ICE_RES_MISC_VEC_ID);
2776 }
2777
2778 /**
2779  * ice_ena_ctrlq_interrupts - enable control queue interrupts
2780  * @hw: pointer to HW structure
2781  * @reg_idx: HW vector index to associate the control queue interrupts with
2782  */
2783 static void ice_ena_ctrlq_interrupts(struct ice_hw *hw, u16 reg_idx)
2784 {
2785         u32 val;
2786
2787         val = ((reg_idx & PFINT_OICR_CTL_MSIX_INDX_M) |
2788                PFINT_OICR_CTL_CAUSE_ENA_M);
2789         wr32(hw, PFINT_OICR_CTL, val);
2790
2791         /* enable Admin queue Interrupt causes */
2792         val = ((reg_idx & PFINT_FW_CTL_MSIX_INDX_M) |
2793                PFINT_FW_CTL_CAUSE_ENA_M);
2794         wr32(hw, PFINT_FW_CTL, val);
2795
2796         /* enable Mailbox queue Interrupt causes */
2797         val = ((reg_idx & PFINT_MBX_CTL_MSIX_INDX_M) |
2798                PFINT_MBX_CTL_CAUSE_ENA_M);
2799         wr32(hw, PFINT_MBX_CTL, val);
2800
2801         ice_flush(hw);
2802 }
2803
2804 /**
2805  * ice_req_irq_msix_misc - Setup the misc vector to handle non queue events
2806  * @pf: board private structure
2807  *
2808  * This sets up the handler for MSIX 0, which is used to manage the
2809  * non-queue interrupts, e.g. AdminQ and errors. This is not used
2810  * when in MSI or Legacy interrupt mode.
2811  */
2812 static int ice_req_irq_msix_misc(struct ice_pf *pf)
2813 {
2814         struct device *dev = ice_pf_to_dev(pf);
2815         struct ice_hw *hw = &pf->hw;
2816         int oicr_idx, err = 0;
2817
2818         if (!pf->int_name[0])
2819                 snprintf(pf->int_name, sizeof(pf->int_name) - 1, "%s-%s:misc",
2820                          dev_driver_string(dev), dev_name(dev));
2821
2822         /* Do not request IRQ but do enable OICR interrupt since settings are
2823          * lost during reset. Note that this function is called only during
2824          * rebuild path and not while reset is in progress.
2825          */
2826         if (ice_is_reset_in_progress(pf->state))
2827                 goto skip_req_irq;
2828
2829         /* reserve one vector in irq_tracker for misc interrupts */
2830         oicr_idx = ice_get_res(pf, pf->irq_tracker, 1, ICE_RES_MISC_VEC_ID);
2831         if (oicr_idx < 0)
2832                 return oicr_idx;
2833
2834         pf->num_avail_sw_msix -= 1;
2835         pf->oicr_idx = (u16)oicr_idx;
2836
2837         err = devm_request_irq(dev, pf->msix_entries[pf->oicr_idx].vector,
2838                                ice_misc_intr, 0, pf->int_name, pf);
2839         if (err) {
2840                 dev_err(dev, "devm_request_irq for %s failed: %d\n",
2841                         pf->int_name, err);
2842                 ice_free_res(pf->irq_tracker, 1, ICE_RES_MISC_VEC_ID);
2843                 pf->num_avail_sw_msix += 1;
2844                 return err;
2845         }
2846
2847 skip_req_irq:
2848         ice_ena_misc_vector(pf);
2849
2850         ice_ena_ctrlq_interrupts(hw, pf->oicr_idx);
2851         wr32(hw, GLINT_ITR(ICE_RX_ITR, pf->oicr_idx),
2852              ITR_REG_ALIGN(ICE_ITR_8K) >> ICE_ITR_GRAN_S);
2853
2854         ice_flush(hw);
2855         ice_irq_dynamic_ena(hw, NULL, NULL);
2856
2857         return 0;
2858 }
2859
2860 /**
2861  * ice_napi_add - register NAPI handler for the VSI
2862  * @vsi: VSI for which NAPI handler is to be registered
2863  *
2864  * This function is only called in the driver's load path. Registering the NAPI
2865  * handler is done in ice_vsi_alloc_q_vector() for all other cases (i.e. resume,
2866  * reset/rebuild, etc.)
2867  */
2868 static void ice_napi_add(struct ice_vsi *vsi)
2869 {
2870         int v_idx;
2871
2872         if (!vsi->netdev)
2873                 return;
2874
2875         ice_for_each_q_vector(vsi, v_idx)
2876                 netif_napi_add(vsi->netdev, &vsi->q_vectors[v_idx]->napi,
2877                                ice_napi_poll, NAPI_POLL_WEIGHT);
2878 }
2879
2880 /**
2881  * ice_set_ops - set netdev and ethtools ops for the given netdev
2882  * @netdev: netdev instance
2883  */
2884 static void ice_set_ops(struct net_device *netdev)
2885 {
2886         struct ice_pf *pf = ice_netdev_to_pf(netdev);
2887
2888         if (ice_is_safe_mode(pf)) {
2889                 netdev->netdev_ops = &ice_netdev_safe_mode_ops;
2890                 ice_set_ethtool_safe_mode_ops(netdev);
2891                 return;
2892         }
2893
2894         netdev->netdev_ops = &ice_netdev_ops;
2895         netdev->udp_tunnel_nic_info = &pf->hw.udp_tunnel_nic;
2896         ice_set_ethtool_ops(netdev);
2897 }
2898
2899 /**
2900  * ice_set_netdev_features - set features for the given netdev
2901  * @netdev: netdev instance
2902  */
2903 static void ice_set_netdev_features(struct net_device *netdev)
2904 {
2905         struct ice_pf *pf = ice_netdev_to_pf(netdev);
2906         netdev_features_t csumo_features;
2907         netdev_features_t vlano_features;
2908         netdev_features_t dflt_features;
2909         netdev_features_t tso_features;
2910
2911         if (ice_is_safe_mode(pf)) {
2912                 /* safe mode */
2913                 netdev->features = NETIF_F_SG | NETIF_F_HIGHDMA;
2914                 netdev->hw_features = netdev->features;
2915                 return;
2916         }
2917
2918         dflt_features = NETIF_F_SG      |
2919                         NETIF_F_HIGHDMA |
2920                         NETIF_F_NTUPLE  |
2921                         NETIF_F_RXHASH;
2922
2923         csumo_features = NETIF_F_RXCSUM   |
2924                          NETIF_F_IP_CSUM  |
2925                          NETIF_F_SCTP_CRC |
2926                          NETIF_F_IPV6_CSUM;
2927
2928         vlano_features = NETIF_F_HW_VLAN_CTAG_FILTER |
2929                          NETIF_F_HW_VLAN_CTAG_TX     |
2930                          NETIF_F_HW_VLAN_CTAG_RX;
2931
2932         tso_features = NETIF_F_TSO                      |
2933                        NETIF_F_TSO_ECN                  |
2934                        NETIF_F_TSO6                     |
2935                        NETIF_F_GSO_GRE                  |
2936                        NETIF_F_GSO_UDP_TUNNEL           |
2937                        NETIF_F_GSO_GRE_CSUM             |
2938                        NETIF_F_GSO_UDP_TUNNEL_CSUM      |
2939                        NETIF_F_GSO_PARTIAL              |
2940                        NETIF_F_GSO_IPXIP4               |
2941                        NETIF_F_GSO_IPXIP6               |
2942                        NETIF_F_GSO_UDP_L4;
2943
2944         netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM |
2945                                         NETIF_F_GSO_GRE_CSUM;
2946         /* set features that user can change */
2947         netdev->hw_features = dflt_features | csumo_features |
2948                               vlano_features | tso_features;
2949
2950         /* add support for HW_CSUM on packets with MPLS header */
2951         netdev->mpls_features =  NETIF_F_HW_CSUM;
2952
2953         /* enable features */
2954         netdev->features |= netdev->hw_features;
2955         /* encap and VLAN devices inherit default, csumo and tso features */
2956         netdev->hw_enc_features |= dflt_features | csumo_features |
2957                                    tso_features;
2958         netdev->vlan_features |= dflt_features | csumo_features |
2959                                  tso_features;
2960 }
2961
2962 /**
2963  * ice_cfg_netdev - Allocate, configure and register a netdev
2964  * @vsi: the VSI associated with the new netdev
2965  *
2966  * Returns 0 on success, negative value on failure
2967  */
2968 static int ice_cfg_netdev(struct ice_vsi *vsi)
2969 {
2970         struct ice_pf *pf = vsi->back;
2971         struct ice_netdev_priv *np;
2972         struct net_device *netdev;
2973         u8 mac_addr[ETH_ALEN];
2974
2975         netdev = alloc_etherdev_mqs(sizeof(*np), vsi->alloc_txq,
2976                                     vsi->alloc_rxq);
2977         if (!netdev)
2978                 return -ENOMEM;
2979
2980         vsi->netdev = netdev;
2981         np = netdev_priv(netdev);
2982         np->vsi = vsi;
2983
2984         ice_set_netdev_features(netdev);
2985
2986         ice_set_ops(netdev);
2987
2988         if (vsi->type == ICE_VSI_PF) {
2989                 SET_NETDEV_DEV(netdev, ice_pf_to_dev(pf));
2990                 ether_addr_copy(mac_addr, vsi->port_info->mac.perm_addr);
2991                 ether_addr_copy(netdev->dev_addr, mac_addr);
2992                 ether_addr_copy(netdev->perm_addr, mac_addr);
2993         }
2994
2995         netdev->priv_flags |= IFF_UNICAST_FLT;
2996
2997         /* Setup netdev TC information */
2998         ice_vsi_cfg_netdev_tc(vsi, vsi->tc_cfg.ena_tc);
2999
3000         /* setup watchdog timeout value to be 5 second */
3001         netdev->watchdog_timeo = 5 * HZ;
3002
3003         netdev->min_mtu = ETH_MIN_MTU;
3004         netdev->max_mtu = ICE_MAX_MTU;
3005
3006         return 0;
3007 }
3008
3009 /**
3010  * ice_fill_rss_lut - Fill the RSS lookup table with default values
3011  * @lut: Lookup table
3012  * @rss_table_size: Lookup table size
3013  * @rss_size: Range of queue number for hashing
3014  */
3015 void ice_fill_rss_lut(u8 *lut, u16 rss_table_size, u16 rss_size)
3016 {
3017         u16 i;
3018
3019         for (i = 0; i < rss_table_size; i++)
3020                 lut[i] = i % rss_size;
3021 }
3022
3023 /**
3024  * ice_pf_vsi_setup - Set up a PF VSI
3025  * @pf: board private structure
3026  * @pi: pointer to the port_info instance
3027  *
3028  * Returns pointer to the successfully allocated VSI software struct
3029  * on success, otherwise returns NULL on failure.
3030  */
3031 static struct ice_vsi *
3032 ice_pf_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi)
3033 {
3034         return ice_vsi_setup(pf, pi, ICE_VSI_PF, ICE_INVAL_VFID);
3035 }
3036
3037 /**
3038  * ice_ctrl_vsi_setup - Set up a control VSI
3039  * @pf: board private structure
3040  * @pi: pointer to the port_info instance
3041  *
3042  * Returns pointer to the successfully allocated VSI software struct
3043  * on success, otherwise returns NULL on failure.
3044  */
3045 static struct ice_vsi *
3046 ice_ctrl_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi)
3047 {
3048         return ice_vsi_setup(pf, pi, ICE_VSI_CTRL, ICE_INVAL_VFID);
3049 }
3050
3051 /**
3052  * ice_lb_vsi_setup - Set up a loopback VSI
3053  * @pf: board private structure
3054  * @pi: pointer to the port_info instance
3055  *
3056  * Returns pointer to the successfully allocated VSI software struct
3057  * on success, otherwise returns NULL on failure.
3058  */
3059 struct ice_vsi *
3060 ice_lb_vsi_setup(struct ice_pf *pf, struct ice_port_info *pi)
3061 {
3062         return ice_vsi_setup(pf, pi, ICE_VSI_LB, ICE_INVAL_VFID);
3063 }
3064
3065 /**
3066  * ice_vlan_rx_add_vid - Add a VLAN ID filter to HW offload
3067  * @netdev: network interface to be adjusted
3068  * @proto: unused protocol
3069  * @vid: VLAN ID to be added
3070  *
3071  * net_device_ops implementation for adding VLAN IDs
3072  */
3073 static int
3074 ice_vlan_rx_add_vid(struct net_device *netdev, __always_unused __be16 proto,
3075                     u16 vid)
3076 {
3077         struct ice_netdev_priv *np = netdev_priv(netdev);
3078         struct ice_vsi *vsi = np->vsi;
3079         int ret;
3080
3081         if (vid >= VLAN_N_VID) {
3082                 netdev_err(netdev, "VLAN id requested %d is out of range %d\n",
3083                            vid, VLAN_N_VID);
3084                 return -EINVAL;
3085         }
3086
3087         if (vsi->info.pvid)
3088                 return -EINVAL;
3089
3090         /* VLAN 0 is added by default during load/reset */
3091         if (!vid)
3092                 return 0;
3093
3094         /* Enable VLAN pruning when a VLAN other than 0 is added */
3095         if (!ice_vsi_is_vlan_pruning_ena(vsi)) {
3096                 ret = ice_cfg_vlan_pruning(vsi, true, false);
3097                 if (ret)
3098                         return ret;
3099         }
3100
3101         /* Add a switch rule for this VLAN ID so its corresponding VLAN tagged
3102          * packets aren't pruned by the device's internal switch on Rx
3103          */
3104         ret = ice_vsi_add_vlan(vsi, vid, ICE_FWD_TO_VSI);
3105         if (!ret)
3106                 set_bit(ICE_VSI_FLAG_VLAN_FLTR_CHANGED, vsi->flags);
3107
3108         return ret;
3109 }
3110
3111 /**
3112  * ice_vlan_rx_kill_vid - Remove a VLAN ID filter from HW offload
3113  * @netdev: network interface to be adjusted
3114  * @proto: unused protocol
3115  * @vid: VLAN ID to be removed
3116  *
3117  * net_device_ops implementation for removing VLAN IDs
3118  */
3119 static int
3120 ice_vlan_rx_kill_vid(struct net_device *netdev, __always_unused __be16 proto,
3121                      u16 vid)
3122 {
3123         struct ice_netdev_priv *np = netdev_priv(netdev);
3124         struct ice_vsi *vsi = np->vsi;
3125         int ret;
3126
3127         if (vsi->info.pvid)
3128                 return -EINVAL;
3129
3130         /* don't allow removal of VLAN 0 */
3131         if (!vid)
3132                 return 0;
3133
3134         /* Make sure ice_vsi_kill_vlan is successful before updating VLAN
3135          * information
3136          */
3137         ret = ice_vsi_kill_vlan(vsi, vid);
3138         if (ret)
3139                 return ret;
3140
3141         /* Disable pruning when VLAN 0 is the only VLAN rule */
3142         if (vsi->num_vlan == 1 && ice_vsi_is_vlan_pruning_ena(vsi))
3143                 ret = ice_cfg_vlan_pruning(vsi, false, false);
3144
3145         set_bit(ICE_VSI_FLAG_VLAN_FLTR_CHANGED, vsi->flags);
3146         return ret;
3147 }
3148
3149 /**
3150  * ice_setup_pf_sw - Setup the HW switch on startup or after reset
3151  * @pf: board private structure
3152  *
3153  * Returns 0 on success, negative value on failure
3154  */
3155 static int ice_setup_pf_sw(struct ice_pf *pf)
3156 {
3157         struct ice_vsi *vsi;
3158         int status = 0;
3159
3160         if (ice_is_reset_in_progress(pf->state))
3161                 return -EBUSY;
3162
3163         vsi = ice_pf_vsi_setup(pf, pf->hw.port_info);
3164         if (!vsi)
3165                 return -ENOMEM;
3166
3167         status = ice_cfg_netdev(vsi);
3168         if (status) {
3169                 status = -ENODEV;
3170                 goto unroll_vsi_setup;
3171         }
3172         /* netdev has to be configured before setting frame size */
3173         ice_vsi_cfg_frame_size(vsi);
3174
3175         /* Setup DCB netlink interface */
3176         ice_dcbnl_setup(vsi);
3177
3178         /* registering the NAPI handler requires both the queues and
3179          * netdev to be created, which are done in ice_pf_vsi_setup()
3180          * and ice_cfg_netdev() respectively
3181          */
3182         ice_napi_add(vsi);
3183
3184         status = ice_set_cpu_rx_rmap(vsi);
3185         if (status) {
3186                 dev_err(ice_pf_to_dev(pf), "Failed to set CPU Rx map VSI %d error %d\n",
3187                         vsi->vsi_num, status);
3188                 status = -EINVAL;
3189                 goto unroll_napi_add;
3190         }
3191         status = ice_init_mac_fltr(pf);
3192         if (status)
3193                 goto free_cpu_rx_map;
3194
3195         return status;
3196
3197 free_cpu_rx_map:
3198         ice_free_cpu_rx_rmap(vsi);
3199
3200 unroll_napi_add:
3201         if (vsi) {
3202                 ice_napi_del(vsi);
3203                 if (vsi->netdev) {
3204                         free_netdev(vsi->netdev);
3205                         vsi->netdev = NULL;
3206                 }
3207         }
3208
3209 unroll_vsi_setup:
3210         ice_vsi_release(vsi);
3211         return status;
3212 }
3213
3214 /**
3215  * ice_get_avail_q_count - Get count of queues in use
3216  * @pf_qmap: bitmap to get queue use count from
3217  * @lock: pointer to a mutex that protects access to pf_qmap
3218  * @size: size of the bitmap
3219  */
3220 static u16
3221 ice_get_avail_q_count(unsigned long *pf_qmap, struct mutex *lock, u16 size)
3222 {
3223         unsigned long bit;
3224         u16 count = 0;
3225
3226         mutex_lock(lock);
3227         for_each_clear_bit(bit, pf_qmap, size)
3228                 count++;
3229         mutex_unlock(lock);
3230
3231         return count;
3232 }
3233
3234 /**
3235  * ice_get_avail_txq_count - Get count of Tx queues in use
3236  * @pf: pointer to an ice_pf instance
3237  */
3238 u16 ice_get_avail_txq_count(struct ice_pf *pf)
3239 {
3240         return ice_get_avail_q_count(pf->avail_txqs, &pf->avail_q_mutex,
3241                                      pf->max_pf_txqs);
3242 }
3243
3244 /**
3245  * ice_get_avail_rxq_count - Get count of Rx queues in use
3246  * @pf: pointer to an ice_pf instance
3247  */
3248 u16 ice_get_avail_rxq_count(struct ice_pf *pf)
3249 {
3250         return ice_get_avail_q_count(pf->avail_rxqs, &pf->avail_q_mutex,
3251                                      pf->max_pf_rxqs);
3252 }
3253
3254 /**
3255  * ice_deinit_pf - Unrolls initialziations done by ice_init_pf
3256  * @pf: board private structure to initialize
3257  */
3258 static void ice_deinit_pf(struct ice_pf *pf)
3259 {
3260         ice_service_task_stop(pf);
3261         mutex_destroy(&pf->sw_mutex);
3262         mutex_destroy(&pf->tc_mutex);
3263         mutex_destroy(&pf->avail_q_mutex);
3264
3265         if (pf->avail_txqs) {
3266                 bitmap_free(pf->avail_txqs);
3267                 pf->avail_txqs = NULL;
3268         }
3269
3270         if (pf->avail_rxqs) {
3271                 bitmap_free(pf->avail_rxqs);
3272                 pf->avail_rxqs = NULL;
3273         }
3274 }
3275
3276 /**
3277  * ice_set_pf_caps - set PFs capability flags
3278  * @pf: pointer to the PF instance
3279  */
3280 static void ice_set_pf_caps(struct ice_pf *pf)
3281 {
3282         struct ice_hw_func_caps *func_caps = &pf->hw.func_caps;
3283
3284         clear_bit(ICE_FLAG_DCB_CAPABLE, pf->flags);
3285         if (func_caps->common_cap.dcb)
3286                 set_bit(ICE_FLAG_DCB_CAPABLE, pf->flags);
3287         clear_bit(ICE_FLAG_SRIOV_CAPABLE, pf->flags);
3288         if (func_caps->common_cap.sr_iov_1_1) {
3289                 set_bit(ICE_FLAG_SRIOV_CAPABLE, pf->flags);
3290                 pf->num_vfs_supported = min_t(int, func_caps->num_allocd_vfs,
3291                                               ICE_MAX_VF_COUNT);
3292         }
3293         clear_bit(ICE_FLAG_RSS_ENA, pf->flags);
3294         if (func_caps->common_cap.rss_table_size)
3295                 set_bit(ICE_FLAG_RSS_ENA, pf->flags);
3296
3297         clear_bit(ICE_FLAG_FD_ENA, pf->flags);
3298         if (func_caps->fd_fltr_guar > 0 || func_caps->fd_fltr_best_effort > 0) {
3299                 u16 unused;
3300
3301                 /* ctrl_vsi_idx will be set to a valid value when flow director
3302                  * is setup by ice_init_fdir
3303                  */
3304                 pf->ctrl_vsi_idx = ICE_NO_VSI;
3305                 set_bit(ICE_FLAG_FD_ENA, pf->flags);
3306                 /* force guaranteed filter pool for PF */
3307                 ice_alloc_fd_guar_item(&pf->hw, &unused,
3308                                        func_caps->fd_fltr_guar);
3309                 /* force shared filter pool for PF */
3310                 ice_alloc_fd_shrd_item(&pf->hw, &unused,
3311                                        func_caps->fd_fltr_best_effort);
3312         }
3313
3314         pf->max_pf_txqs = func_caps->common_cap.num_txq;
3315         pf->max_pf_rxqs = func_caps->common_cap.num_rxq;
3316 }
3317
3318 /**
3319  * ice_init_pf - Initialize general software structures (struct ice_pf)
3320  * @pf: board private structure to initialize
3321  */
3322 static int ice_init_pf(struct ice_pf *pf)
3323 {
3324         ice_set_pf_caps(pf);
3325
3326         mutex_init(&pf->sw_mutex);
3327         mutex_init(&pf->tc_mutex);
3328
3329         INIT_HLIST_HEAD(&pf->aq_wait_list);
3330         spin_lock_init(&pf->aq_wait_lock);
3331         init_waitqueue_head(&pf->aq_wait_queue);
3332
3333         /* setup service timer and periodic service task */
3334         timer_setup(&pf->serv_tmr, ice_service_timer, 0);
3335         pf->serv_tmr_period = HZ;
3336         INIT_WORK(&pf->serv_task, ice_service_task);
3337         clear_bit(__ICE_SERVICE_SCHED, pf->state);
3338
3339         mutex_init(&pf->avail_q_mutex);
3340         pf->avail_txqs = bitmap_zalloc(pf->max_pf_txqs, GFP_KERNEL);
3341         if (!pf->avail_txqs)
3342                 return -ENOMEM;
3343
3344         pf->avail_rxqs = bitmap_zalloc(pf->max_pf_rxqs, GFP_KERNEL);
3345         if (!pf->avail_rxqs) {
3346                 devm_kfree(ice_pf_to_dev(pf), pf->avail_txqs);
3347                 pf->avail_txqs = NULL;
3348                 return -ENOMEM;
3349         }
3350
3351         return 0;
3352 }
3353
3354 /**
3355  * ice_ena_msix_range - Request a range of MSIX vectors from the OS
3356  * @pf: board private structure
3357  *
3358  * compute the number of MSIX vectors required (v_budget) and request from
3359  * the OS. Return the number of vectors reserved or negative on failure
3360  */
3361 static int ice_ena_msix_range(struct ice_pf *pf)
3362 {
3363         int v_left, v_actual, v_other, v_budget = 0;
3364         struct device *dev = ice_pf_to_dev(pf);
3365         int needed, err, i;
3366
3367         v_left = pf->hw.func_caps.common_cap.num_msix_vectors;
3368
3369         /* reserve for LAN miscellaneous handler */
3370         needed = ICE_MIN_LAN_OICR_MSIX;
3371         if (v_left < needed)
3372                 goto no_hw_vecs_left_err;
3373         v_budget += needed;
3374         v_left -= needed;
3375
3376         /* reserve for flow director */
3377         if (test_bit(ICE_FLAG_FD_ENA, pf->flags)) {
3378                 needed = ICE_FDIR_MSIX;
3379                 if (v_left < needed)
3380                         goto no_hw_vecs_left_err;
3381                 v_budget += needed;
3382                 v_left -= needed;
3383         }
3384
3385         /* total used for non-traffic vectors */
3386         v_other = v_budget;
3387
3388         /* reserve vectors for LAN traffic */
3389         needed = min_t(int, num_online_cpus(), v_left);
3390         if (v_left < needed)
3391                 goto no_hw_vecs_left_err;
3392         pf->num_lan_msix = needed;
3393         v_budget += needed;
3394         v_left -= needed;
3395
3396         pf->msix_entries = devm_kcalloc(dev, v_budget,
3397                                         sizeof(*pf->msix_entries), GFP_KERNEL);
3398         if (!pf->msix_entries) {
3399                 err = -ENOMEM;
3400                 goto exit_err;
3401         }
3402
3403         for (i = 0; i < v_budget; i++)
3404                 pf->msix_entries[i].entry = i;
3405
3406         /* actually reserve the vectors */
3407         v_actual = pci_enable_msix_range(pf->pdev, pf->msix_entries,
3408                                          ICE_MIN_MSIX, v_budget);
3409         if (v_actual < 0) {
3410                 dev_err(dev, "unable to reserve MSI-X vectors\n");
3411                 err = v_actual;
3412                 goto msix_err;
3413         }
3414
3415         if (v_actual < v_budget) {
3416                 dev_warn(dev, "not enough OS MSI-X vectors. requested = %d, obtained = %d\n",
3417                          v_budget, v_actual);
3418
3419                 if (v_actual < ICE_MIN_MSIX) {
3420                         /* error if we can't get minimum vectors */
3421                         pci_disable_msix(pf->pdev);
3422                         err = -ERANGE;
3423                         goto msix_err;
3424                 } else {
3425                         int v_traffic = v_actual - v_other;
3426
3427                         if (v_actual == ICE_MIN_MSIX ||
3428                             v_traffic < ICE_MIN_LAN_TXRX_MSIX)
3429                                 pf->num_lan_msix = ICE_MIN_LAN_TXRX_MSIX;
3430                         else
3431                                 pf->num_lan_msix = v_traffic;
3432
3433                         dev_notice(dev, "Enabled %d MSI-X vectors for LAN traffic.\n",
3434                                    pf->num_lan_msix);
3435                 }
3436         }
3437
3438         return v_actual;
3439
3440 msix_err:
3441         devm_kfree(dev, pf->msix_entries);
3442         goto exit_err;
3443
3444 no_hw_vecs_left_err:
3445         dev_err(dev, "not enough device MSI-X vectors. requested = %d, available = %d\n",
3446                 needed, v_left);
3447         err = -ERANGE;
3448 exit_err:
3449         pf->num_lan_msix = 0;
3450         return err;
3451 }
3452
3453 /**
3454  * ice_dis_msix - Disable MSI-X interrupt setup in OS
3455  * @pf: board private structure
3456  */
3457 static void ice_dis_msix(struct ice_pf *pf)
3458 {
3459         pci_disable_msix(pf->pdev);
3460         devm_kfree(ice_pf_to_dev(pf), pf->msix_entries);
3461         pf->msix_entries = NULL;
3462 }
3463
3464 /**
3465  * ice_clear_interrupt_scheme - Undo things done by ice_init_interrupt_scheme
3466  * @pf: board private structure
3467  */
3468 static void ice_clear_interrupt_scheme(struct ice_pf *pf)
3469 {
3470         ice_dis_msix(pf);
3471
3472         if (pf->irq_tracker) {
3473                 devm_kfree(ice_pf_to_dev(pf), pf->irq_tracker);
3474                 pf->irq_tracker = NULL;
3475         }
3476 }
3477
3478 /**
3479  * ice_init_interrupt_scheme - Determine proper interrupt scheme
3480  * @pf: board private structure to initialize
3481  */
3482 static int ice_init_interrupt_scheme(struct ice_pf *pf)
3483 {
3484         int vectors;
3485
3486         vectors = ice_ena_msix_range(pf);
3487
3488         if (vectors < 0)
3489                 return vectors;
3490
3491         /* set up vector assignment tracking */
3492         pf->irq_tracker = devm_kzalloc(ice_pf_to_dev(pf),
3493                                        struct_size(pf->irq_tracker, list, vectors),
3494                                        GFP_KERNEL);
3495         if (!pf->irq_tracker) {
3496                 ice_dis_msix(pf);
3497                 return -ENOMEM;
3498         }
3499
3500         /* populate SW interrupts pool with number of OS granted IRQs. */
3501         pf->num_avail_sw_msix = (u16)vectors;
3502         pf->irq_tracker->num_entries = (u16)vectors;
3503         pf->irq_tracker->end = pf->irq_tracker->num_entries;
3504
3505         return 0;
3506 }
3507
3508 /**
3509  * ice_is_wol_supported - get NVM state of WoL
3510  * @pf: board private structure
3511  *
3512  * Check if WoL is supported based on the HW configuration.
3513  * Returns true if NVM supports and enables WoL for this port, false otherwise
3514  */
3515 bool ice_is_wol_supported(struct ice_pf *pf)
3516 {
3517         struct ice_hw *hw = &pf->hw;
3518         u16 wol_ctrl;
3519
3520         /* A bit set to 1 in the NVM Software Reserved Word 2 (WoL control
3521          * word) indicates WoL is not supported on the corresponding PF ID.
3522          */
3523         if (ice_read_sr_word(hw, ICE_SR_NVM_WOL_CFG, &wol_ctrl))
3524                 return false;
3525
3526         return !(BIT(hw->pf_id) & wol_ctrl);
3527 }
3528
3529 /**
3530  * ice_vsi_recfg_qs - Change the number of queues on a VSI
3531  * @vsi: VSI being changed
3532  * @new_rx: new number of Rx queues
3533  * @new_tx: new number of Tx queues
3534  *
3535  * Only change the number of queues if new_tx, or new_rx is non-0.
3536  *
3537  * Returns 0 on success.
3538  */
3539 int ice_vsi_recfg_qs(struct ice_vsi *vsi, int new_rx, int new_tx)
3540 {
3541         struct ice_pf *pf = vsi->back;
3542         int err = 0, timeout = 50;
3543
3544         if (!new_rx && !new_tx)
3545                 return -EINVAL;
3546
3547         while (test_and_set_bit(__ICE_CFG_BUSY, pf->state)) {
3548                 timeout--;
3549                 if (!timeout)
3550                         return -EBUSY;
3551                 usleep_range(1000, 2000);
3552         }
3553
3554         if (new_tx)
3555                 vsi->req_txq = (u16)new_tx;
3556         if (new_rx)
3557                 vsi->req_rxq = (u16)new_rx;
3558
3559         /* set for the next time the netdev is started */
3560         if (!netif_running(vsi->netdev)) {
3561                 ice_vsi_rebuild(vsi, false);
3562                 dev_dbg(ice_pf_to_dev(pf), "Link is down, queue count change happens when link is brought up\n");
3563                 goto done;
3564         }
3565
3566         ice_vsi_close(vsi);
3567         ice_vsi_rebuild(vsi, false);
3568         ice_pf_dcb_recfg(pf);
3569         ice_vsi_open(vsi);
3570 done:
3571         clear_bit(__ICE_CFG_BUSY, pf->state);
3572         return err;
3573 }
3574
3575 /**
3576  * ice_set_safe_mode_vlan_cfg - configure PF VSI to allow all VLANs in safe mode
3577  * @pf: PF to configure
3578  *
3579  * No VLAN offloads/filtering are advertised in safe mode so make sure the PF
3580  * VSI can still Tx/Rx VLAN tagged packets.
3581  */
3582 static void ice_set_safe_mode_vlan_cfg(struct ice_pf *pf)
3583 {
3584         struct ice_vsi *vsi = ice_get_main_vsi(pf);
3585         struct ice_vsi_ctx *ctxt;
3586         enum ice_status status;
3587         struct ice_hw *hw;
3588
3589         if (!vsi)
3590                 return;
3591
3592         ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL);
3593         if (!ctxt)
3594                 return;
3595
3596         hw = &pf->hw;
3597         ctxt->info = vsi->info;
3598
3599         ctxt->info.valid_sections =
3600                 cpu_to_le16(ICE_AQ_VSI_PROP_VLAN_VALID |
3601                             ICE_AQ_VSI_PROP_SECURITY_VALID |
3602                             ICE_AQ_VSI_PROP_SW_VALID);
3603
3604         /* disable VLAN anti-spoof */
3605         ctxt->info.sec_flags &= ~(ICE_AQ_VSI_SEC_TX_VLAN_PRUNE_ENA <<
3606                                   ICE_AQ_VSI_SEC_TX_PRUNE_ENA_S);
3607
3608         /* disable VLAN pruning and keep all other settings */
3609         ctxt->info.sw_flags2 &= ~ICE_AQ_VSI_SW_FLAG_RX_VLAN_PRUNE_ENA;
3610
3611         /* allow all VLANs on Tx and don't strip on Rx */
3612         ctxt->info.vlan_flags = ICE_AQ_VSI_VLAN_MODE_ALL |
3613                 ICE_AQ_VSI_VLAN_EMOD_NOTHING;
3614
3615         status = ice_update_vsi(hw, vsi->idx, ctxt, NULL);
3616         if (status) {
3617                 dev_err(ice_pf_to_dev(vsi->back), "Failed to update VSI for safe mode VLANs, err %s aq_err %s\n",
3618                         ice_stat_str(status),
3619                         ice_aq_str(hw->adminq.sq_last_status));
3620         } else {
3621                 vsi->info.sec_flags = ctxt->info.sec_flags;
3622                 vsi->info.sw_flags2 = ctxt->info.sw_flags2;
3623                 vsi->info.vlan_flags = ctxt->info.vlan_flags;
3624         }
3625
3626         kfree(ctxt);
3627 }
3628
3629 /**
3630  * ice_log_pkg_init - log result of DDP package load
3631  * @hw: pointer to hardware info
3632  * @status: status of package load
3633  */
3634 static void
3635 ice_log_pkg_init(struct ice_hw *hw, enum ice_status *status)
3636 {
3637         struct ice_pf *pf = (struct ice_pf *)hw->back;
3638         struct device *dev = ice_pf_to_dev(pf);
3639
3640         switch (*status) {
3641         case ICE_SUCCESS:
3642                 /* The package download AdminQ command returned success because
3643                  * this download succeeded or ICE_ERR_AQ_NO_WORK since there is
3644                  * already a package loaded on the device.
3645                  */
3646                 if (hw->pkg_ver.major == hw->active_pkg_ver.major &&
3647                     hw->pkg_ver.minor == hw->active_pkg_ver.minor &&
3648                     hw->pkg_ver.update == hw->active_pkg_ver.update &&
3649                     hw->pkg_ver.draft == hw->active_pkg_ver.draft &&
3650                     !memcmp(hw->pkg_name, hw->active_pkg_name,
3651                             sizeof(hw->pkg_name))) {
3652                         if (hw->pkg_dwnld_status == ICE_AQ_RC_EEXIST)
3653                                 dev_info(dev, "DDP package already present on device: %s version %d.%d.%d.%d\n",
3654                                          hw->active_pkg_name,
3655                                          hw->active_pkg_ver.major,
3656                                          hw->active_pkg_ver.minor,
3657                                          hw->active_pkg_ver.update,
3658                                          hw->active_pkg_ver.draft);
3659                         else
3660                                 dev_info(dev, "The DDP package was successfully loaded: %s version %d.%d.%d.%d\n",
3661                                          hw->active_pkg_name,
3662                                          hw->active_pkg_ver.major,
3663                                          hw->active_pkg_ver.minor,
3664                                          hw->active_pkg_ver.update,
3665                                          hw->active_pkg_ver.draft);
3666                 } else if (hw->active_pkg_ver.major != ICE_PKG_SUPP_VER_MAJ ||
3667                            hw->active_pkg_ver.minor != ICE_PKG_SUPP_VER_MNR) {
3668                         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",
3669                                 hw->active_pkg_name,
3670                                 hw->active_pkg_ver.major,
3671                                 hw->active_pkg_ver.minor,
3672                                 ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
3673                         *status = ICE_ERR_NOT_SUPPORTED;
3674                 } else if (hw->active_pkg_ver.major == ICE_PKG_SUPP_VER_MAJ &&
3675                            hw->active_pkg_ver.minor == ICE_PKG_SUPP_VER_MNR) {
3676                         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",
3677                                  hw->active_pkg_name,
3678                                  hw->active_pkg_ver.major,
3679                                  hw->active_pkg_ver.minor,
3680                                  hw->active_pkg_ver.update,
3681                                  hw->active_pkg_ver.draft,
3682                                  hw->pkg_name,
3683                                  hw->pkg_ver.major,
3684                                  hw->pkg_ver.minor,
3685                                  hw->pkg_ver.update,
3686                                  hw->pkg_ver.draft);
3687                 } else {
3688                         dev_err(dev, "An unknown error occurred when loading the DDP package, please reboot the system.  If the problem persists, update the NVM.  Entering Safe Mode.\n");
3689                         *status = ICE_ERR_NOT_SUPPORTED;
3690                 }
3691                 break;
3692         case ICE_ERR_FW_DDP_MISMATCH:
3693                 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");
3694                 break;
3695         case ICE_ERR_BUF_TOO_SHORT:
3696         case ICE_ERR_CFG:
3697                 dev_err(dev, "The DDP package file is invalid. Entering Safe Mode.\n");
3698                 break;
3699         case ICE_ERR_NOT_SUPPORTED:
3700                 /* Package File version not supported */
3701                 if (hw->pkg_ver.major > ICE_PKG_SUPP_VER_MAJ ||
3702                     (hw->pkg_ver.major == ICE_PKG_SUPP_VER_MAJ &&
3703                      hw->pkg_ver.minor > ICE_PKG_SUPP_VER_MNR))
3704                         dev_err(dev, "The DDP package file version is higher than the driver supports.  Please use an updated driver.  Entering Safe Mode.\n");
3705                 else if (hw->pkg_ver.major < ICE_PKG_SUPP_VER_MAJ ||
3706                          (hw->pkg_ver.major == ICE_PKG_SUPP_VER_MAJ &&
3707                           hw->pkg_ver.minor < ICE_PKG_SUPP_VER_MNR))
3708                         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",
3709                                 ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
3710                 break;
3711         case ICE_ERR_AQ_ERROR:
3712                 switch (hw->pkg_dwnld_status) {
3713                 case ICE_AQ_RC_ENOSEC:
3714                 case ICE_AQ_RC_EBADSIG:
3715                         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");
3716                         return;
3717                 case ICE_AQ_RC_ESVN:
3718                         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");
3719                         return;
3720                 case ICE_AQ_RC_EBADMAN:
3721                 case ICE_AQ_RC_EBADBUF:
3722                         dev_err(dev, "An error occurred on the device while loading the DDP package.  The device will be reset.\n");
3723                         /* poll for reset to complete */
3724                         if (ice_check_reset(hw))
3725                                 dev_err(dev, "Error resetting device. Please reload the driver\n");
3726                         return;
3727                 default:
3728                         break;
3729                 }
3730                 fallthrough;
3731         default:
3732                 dev_err(dev, "An unknown error (%d) occurred when loading the DDP package.  Entering Safe Mode.\n",
3733                         *status);
3734                 break;
3735         }
3736 }
3737
3738 /**
3739  * ice_load_pkg - load/reload the DDP Package file
3740  * @firmware: firmware structure when firmware requested or NULL for reload
3741  * @pf: pointer to the PF instance
3742  *
3743  * Called on probe and post CORER/GLOBR rebuild to load DDP Package and
3744  * initialize HW tables.
3745  */
3746 static void
3747 ice_load_pkg(const struct firmware *firmware, struct ice_pf *pf)
3748 {
3749         enum ice_status status = ICE_ERR_PARAM;
3750         struct device *dev = ice_pf_to_dev(pf);
3751         struct ice_hw *hw = &pf->hw;
3752
3753         /* Load DDP Package */
3754         if (firmware && !hw->pkg_copy) {
3755                 status = ice_copy_and_init_pkg(hw, firmware->data,
3756                                                firmware->size);
3757                 ice_log_pkg_init(hw, &status);
3758         } else if (!firmware && hw->pkg_copy) {
3759                 /* Reload package during rebuild after CORER/GLOBR reset */
3760                 status = ice_init_pkg(hw, hw->pkg_copy, hw->pkg_size);
3761                 ice_log_pkg_init(hw, &status);
3762         } else {
3763                 dev_err(dev, "The DDP package file failed to load. Entering Safe Mode.\n");
3764         }
3765
3766         if (status) {
3767                 /* Safe Mode */
3768                 clear_bit(ICE_FLAG_ADV_FEATURES, pf->flags);
3769                 return;
3770         }
3771
3772         /* Successful download package is the precondition for advanced
3773          * features, hence setting the ICE_FLAG_ADV_FEATURES flag
3774          */
3775         set_bit(ICE_FLAG_ADV_FEATURES, pf->flags);
3776 }
3777
3778 /**
3779  * ice_verify_cacheline_size - verify driver's assumption of 64 Byte cache lines
3780  * @pf: pointer to the PF structure
3781  *
3782  * There is no error returned here because the driver should be able to handle
3783  * 128 Byte cache lines, so we only print a warning in case issues are seen,
3784  * specifically with Tx.
3785  */
3786 static void ice_verify_cacheline_size(struct ice_pf *pf)
3787 {
3788         if (rd32(&pf->hw, GLPCI_CNF2) & GLPCI_CNF2_CACHELINE_SIZE_M)
3789                 dev_warn(ice_pf_to_dev(pf), "%d Byte cache line assumption is invalid, driver may have Tx timeouts!\n",
3790                          ICE_CACHE_LINE_BYTES);
3791 }
3792
3793 /**
3794  * ice_send_version - update firmware with driver version
3795  * @pf: PF struct
3796  *
3797  * Returns ICE_SUCCESS on success, else error code
3798  */
3799 static enum ice_status ice_send_version(struct ice_pf *pf)
3800 {
3801         struct ice_driver_ver dv;
3802
3803         dv.major_ver = 0xff;
3804         dv.minor_ver = 0xff;
3805         dv.build_ver = 0xff;
3806         dv.subbuild_ver = 0;
3807         strscpy((char *)dv.driver_string, UTS_RELEASE,
3808                 sizeof(dv.driver_string));
3809         return ice_aq_send_driver_ver(&pf->hw, &dv, NULL);
3810 }
3811
3812 /**
3813  * ice_init_fdir - Initialize flow director VSI and configuration
3814  * @pf: pointer to the PF instance
3815  *
3816  * returns 0 on success, negative on error
3817  */
3818 static int ice_init_fdir(struct ice_pf *pf)
3819 {
3820         struct device *dev = ice_pf_to_dev(pf);
3821         struct ice_vsi *ctrl_vsi;
3822         int err;
3823
3824         /* Side Band Flow Director needs to have a control VSI.
3825          * Allocate it and store it in the PF.
3826          */
3827         ctrl_vsi = ice_ctrl_vsi_setup(pf, pf->hw.port_info);
3828         if (!ctrl_vsi) {
3829                 dev_dbg(dev, "could not create control VSI\n");
3830                 return -ENOMEM;
3831         }
3832
3833         err = ice_vsi_open_ctrl(ctrl_vsi);
3834         if (err) {
3835                 dev_dbg(dev, "could not open control VSI\n");
3836                 goto err_vsi_open;
3837         }
3838
3839         mutex_init(&pf->hw.fdir_fltr_lock);
3840
3841         err = ice_fdir_create_dflt_rules(pf);
3842         if (err)
3843                 goto err_fdir_rule;
3844
3845         return 0;
3846
3847 err_fdir_rule:
3848         ice_fdir_release_flows(&pf->hw);
3849         ice_vsi_close(ctrl_vsi);
3850 err_vsi_open:
3851         ice_vsi_release(ctrl_vsi);
3852         if (pf->ctrl_vsi_idx != ICE_NO_VSI) {
3853                 pf->vsi[pf->ctrl_vsi_idx] = NULL;
3854                 pf->ctrl_vsi_idx = ICE_NO_VSI;
3855         }
3856         return err;
3857 }
3858
3859 /**
3860  * ice_get_opt_fw_name - return optional firmware file name or NULL
3861  * @pf: pointer to the PF instance
3862  */
3863 static char *ice_get_opt_fw_name(struct ice_pf *pf)
3864 {
3865         /* Optional firmware name same as default with additional dash
3866          * followed by a EUI-64 identifier (PCIe Device Serial Number)
3867          */
3868         struct pci_dev *pdev = pf->pdev;
3869         char *opt_fw_filename;
3870         u64 dsn;
3871
3872         /* Determine the name of the optional file using the DSN (two
3873          * dwords following the start of the DSN Capability).
3874          */
3875         dsn = pci_get_dsn(pdev);
3876         if (!dsn)
3877                 return NULL;
3878
3879         opt_fw_filename = kzalloc(NAME_MAX, GFP_KERNEL);
3880         if (!opt_fw_filename)
3881                 return NULL;
3882
3883         snprintf(opt_fw_filename, NAME_MAX, "%sice-%016llx.pkg",
3884                  ICE_DDP_PKG_PATH, dsn);
3885
3886         return opt_fw_filename;
3887 }
3888
3889 /**
3890  * ice_request_fw - Device initialization routine
3891  * @pf: pointer to the PF instance
3892  */
3893 static void ice_request_fw(struct ice_pf *pf)
3894 {
3895         char *opt_fw_filename = ice_get_opt_fw_name(pf);
3896         const struct firmware *firmware = NULL;
3897         struct device *dev = ice_pf_to_dev(pf);
3898         int err = 0;
3899
3900         /* optional device-specific DDP (if present) overrides the default DDP
3901          * package file. kernel logs a debug message if the file doesn't exist,
3902          * and warning messages for other errors.
3903          */
3904         if (opt_fw_filename) {
3905                 err = firmware_request_nowarn(&firmware, opt_fw_filename, dev);
3906                 if (err) {
3907                         kfree(opt_fw_filename);
3908                         goto dflt_pkg_load;
3909                 }
3910
3911                 /* request for firmware was successful. Download to device */
3912                 ice_load_pkg(firmware, pf);
3913                 kfree(opt_fw_filename);
3914                 release_firmware(firmware);
3915                 return;
3916         }
3917
3918 dflt_pkg_load:
3919         err = request_firmware(&firmware, ICE_DDP_PKG_FILE, dev);
3920         if (err) {
3921                 dev_err(dev, "The DDP package file was not found or could not be read. Entering Safe Mode\n");
3922                 return;
3923         }
3924
3925         /* request for firmware was successful. Download to device */
3926         ice_load_pkg(firmware, pf);
3927         release_firmware(firmware);
3928 }
3929
3930 /**
3931  * ice_print_wake_reason - show the wake up cause in the log
3932  * @pf: pointer to the PF struct
3933  */
3934 static void ice_print_wake_reason(struct ice_pf *pf)
3935 {
3936         u32 wus = pf->wakeup_reason;
3937         const char *wake_str;
3938
3939         /* if no wake event, nothing to print */
3940         if (!wus)
3941                 return;
3942
3943         if (wus & PFPM_WUS_LNKC_M)
3944                 wake_str = "Link\n";
3945         else if (wus & PFPM_WUS_MAG_M)
3946                 wake_str = "Magic Packet\n";
3947         else if (wus & PFPM_WUS_MNG_M)
3948                 wake_str = "Management\n";
3949         else if (wus & PFPM_WUS_FW_RST_WK_M)
3950                 wake_str = "Firmware Reset\n";
3951         else
3952                 wake_str = "Unknown\n";
3953
3954         dev_info(ice_pf_to_dev(pf), "Wake reason: %s", wake_str);
3955 }
3956
3957 /**
3958  * ice_register_netdev - register netdev and devlink port
3959  * @pf: pointer to the PF struct
3960  */
3961 static int ice_register_netdev(struct ice_pf *pf)
3962 {
3963         struct ice_vsi *vsi;
3964         int err = 0;
3965
3966         vsi = ice_get_main_vsi(pf);
3967         if (!vsi || !vsi->netdev)
3968                 return -EIO;
3969
3970         err = register_netdev(vsi->netdev);
3971         if (err)
3972                 goto err_register_netdev;
3973
3974         netif_carrier_off(vsi->netdev);
3975         netif_tx_stop_all_queues(vsi->netdev);
3976         err = ice_devlink_create_port(vsi);
3977         if (err)
3978                 goto err_devlink_create;
3979
3980         devlink_port_type_eth_set(&vsi->devlink_port, vsi->netdev);
3981
3982         return 0;
3983 err_devlink_create:
3984         unregister_netdev(vsi->netdev);
3985 err_register_netdev:
3986         free_netdev(vsi->netdev);
3987         vsi->netdev = NULL;
3988         return err;
3989 }
3990
3991 /**
3992  * ice_probe - Device initialization routine
3993  * @pdev: PCI device information struct
3994  * @ent: entry in ice_pci_tbl
3995  *
3996  * Returns 0 on success, negative on failure
3997  */
3998 static int
3999 ice_probe(struct pci_dev *pdev, const struct pci_device_id __always_unused *ent)
4000 {
4001         struct device *dev = &pdev->dev;
4002         struct ice_pf *pf;
4003         struct ice_hw *hw;
4004         int i, err;
4005
4006         /* this driver uses devres, see
4007          * Documentation/driver-api/driver-model/devres.rst
4008          */
4009         err = pcim_enable_device(pdev);
4010         if (err)
4011                 return err;
4012
4013         err = pcim_iomap_regions(pdev, BIT(ICE_BAR0), pci_name(pdev));
4014         if (err) {
4015                 dev_err(dev, "BAR0 I/O map error %d\n", err);
4016                 return err;
4017         }
4018
4019         pf = ice_allocate_pf(dev);
4020         if (!pf)
4021                 return -ENOMEM;
4022
4023         /* set up for high or low DMA */
4024         err = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64));
4025         if (err)
4026                 err = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32));
4027         if (err) {
4028                 dev_err(dev, "DMA configuration failed: 0x%x\n", err);
4029                 return err;
4030         }
4031
4032         pci_enable_pcie_error_reporting(pdev);
4033         pci_set_master(pdev);
4034
4035         pf->pdev = pdev;
4036         pci_set_drvdata(pdev, pf);
4037         set_bit(__ICE_DOWN, pf->state);
4038         /* Disable service task until DOWN bit is cleared */
4039         set_bit(__ICE_SERVICE_DIS, pf->state);
4040
4041         hw = &pf->hw;
4042         hw->hw_addr = pcim_iomap_table(pdev)[ICE_BAR0];
4043         pci_save_state(pdev);
4044
4045         hw->back = pf;
4046         hw->vendor_id = pdev->vendor;
4047         hw->device_id = pdev->device;
4048         pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
4049         hw->subsystem_vendor_id = pdev->subsystem_vendor;
4050         hw->subsystem_device_id = pdev->subsystem_device;
4051         hw->bus.device = PCI_SLOT(pdev->devfn);
4052         hw->bus.func = PCI_FUNC(pdev->devfn);
4053         ice_set_ctrlq_len(hw);
4054
4055         pf->msg_enable = netif_msg_init(debug, ICE_DFLT_NETIF_M);
4056
4057         err = ice_devlink_register(pf);
4058         if (err) {
4059                 dev_err(dev, "ice_devlink_register failed: %d\n", err);
4060                 goto err_exit_unroll;
4061         }
4062
4063 #ifndef CONFIG_DYNAMIC_DEBUG
4064         if (debug < -1)
4065                 hw->debug_mask = debug;
4066 #endif
4067
4068         err = ice_init_hw(hw);
4069         if (err) {
4070                 dev_err(dev, "ice_init_hw failed: %d\n", err);
4071                 err = -EIO;
4072                 goto err_exit_unroll;
4073         }
4074
4075         ice_request_fw(pf);
4076
4077         /* if ice_request_fw fails, ICE_FLAG_ADV_FEATURES bit won't be
4078          * set in pf->state, which will cause ice_is_safe_mode to return
4079          * true
4080          */
4081         if (ice_is_safe_mode(pf)) {
4082                 dev_err(dev, "Package download failed. Advanced features disabled - Device now in Safe Mode\n");
4083                 /* we already got function/device capabilities but these don't
4084                  * reflect what the driver needs to do in safe mode. Instead of
4085                  * adding conditional logic everywhere to ignore these
4086                  * device/function capabilities, override them.
4087                  */
4088                 ice_set_safe_mode_caps(hw);
4089         }
4090
4091         err = ice_init_pf(pf);
4092         if (err) {
4093                 dev_err(dev, "ice_init_pf failed: %d\n", err);
4094                 goto err_init_pf_unroll;
4095         }
4096
4097         ice_devlink_init_regions(pf);
4098
4099         pf->hw.udp_tunnel_nic.set_port = ice_udp_tunnel_set_port;
4100         pf->hw.udp_tunnel_nic.unset_port = ice_udp_tunnel_unset_port;
4101         pf->hw.udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP;
4102         pf->hw.udp_tunnel_nic.shared = &pf->hw.udp_tunnel_shared;
4103         i = 0;
4104         if (pf->hw.tnl.valid_count[TNL_VXLAN]) {
4105                 pf->hw.udp_tunnel_nic.tables[i].n_entries =
4106                         pf->hw.tnl.valid_count[TNL_VXLAN];
4107                 pf->hw.udp_tunnel_nic.tables[i].tunnel_types =
4108                         UDP_TUNNEL_TYPE_VXLAN;
4109                 i++;
4110         }
4111         if (pf->hw.tnl.valid_count[TNL_GENEVE]) {
4112                 pf->hw.udp_tunnel_nic.tables[i].n_entries =
4113                         pf->hw.tnl.valid_count[TNL_GENEVE];
4114                 pf->hw.udp_tunnel_nic.tables[i].tunnel_types =
4115                         UDP_TUNNEL_TYPE_GENEVE;
4116                 i++;
4117         }
4118
4119         pf->num_alloc_vsi = hw->func_caps.guar_num_vsi;
4120         if (!pf->num_alloc_vsi) {
4121                 err = -EIO;
4122                 goto err_init_pf_unroll;
4123         }
4124         if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
4125                 dev_warn(&pf->pdev->dev,
4126                          "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
4127                          pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
4128                 pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
4129         }
4130
4131         pf->vsi = devm_kcalloc(dev, pf->num_alloc_vsi, sizeof(*pf->vsi),
4132                                GFP_KERNEL);
4133         if (!pf->vsi) {
4134                 err = -ENOMEM;
4135                 goto err_init_pf_unroll;
4136         }
4137
4138         err = ice_init_interrupt_scheme(pf);
4139         if (err) {
4140                 dev_err(dev, "ice_init_interrupt_scheme failed: %d\n", err);
4141                 err = -EIO;
4142                 goto err_init_vsi_unroll;
4143         }
4144
4145         /* In case of MSIX we are going to setup the misc vector right here
4146          * to handle admin queue events etc. In case of legacy and MSI
4147          * the misc functionality and queue processing is combined in
4148          * the same vector and that gets setup at open.
4149          */
4150         err = ice_req_irq_msix_misc(pf);
4151         if (err) {
4152                 dev_err(dev, "setup of misc vector failed: %d\n", err);
4153                 goto err_init_interrupt_unroll;
4154         }
4155
4156         /* create switch struct for the switch element created by FW on boot */
4157         pf->first_sw = devm_kzalloc(dev, sizeof(*pf->first_sw), GFP_KERNEL);
4158         if (!pf->first_sw) {
4159                 err = -ENOMEM;
4160                 goto err_msix_misc_unroll;
4161         }
4162
4163         if (hw->evb_veb)
4164                 pf->first_sw->bridge_mode = BRIDGE_MODE_VEB;
4165         else
4166                 pf->first_sw->bridge_mode = BRIDGE_MODE_VEPA;
4167
4168         pf->first_sw->pf = pf;
4169
4170         /* record the sw_id available for later use */
4171         pf->first_sw->sw_id = hw->port_info->sw_id;
4172
4173         err = ice_setup_pf_sw(pf);
4174         if (err) {
4175                 dev_err(dev, "probe failed due to setup PF switch: %d\n", err);
4176                 goto err_alloc_sw_unroll;
4177         }
4178
4179         clear_bit(__ICE_SERVICE_DIS, pf->state);
4180
4181         /* tell the firmware we are up */
4182         err = ice_send_version(pf);
4183         if (err) {
4184                 dev_err(dev, "probe failed sending driver version %s. error: %d\n",
4185                         UTS_RELEASE, err);
4186                 goto err_send_version_unroll;
4187         }
4188
4189         /* since everything is good, start the service timer */
4190         mod_timer(&pf->serv_tmr, round_jiffies(jiffies + pf->serv_tmr_period));
4191
4192         err = ice_init_link_events(pf->hw.port_info);
4193         if (err) {
4194                 dev_err(dev, "ice_init_link_events failed: %d\n", err);
4195                 goto err_send_version_unroll;
4196         }
4197
4198         err = ice_init_nvm_phy_type(pf->hw.port_info);
4199         if (err) {
4200                 dev_err(dev, "ice_init_nvm_phy_type failed: %d\n", err);
4201                 goto err_send_version_unroll;
4202         }
4203
4204         err = ice_update_link_info(pf->hw.port_info);
4205         if (err) {
4206                 dev_err(dev, "ice_update_link_info failed: %d\n", err);
4207                 goto err_send_version_unroll;
4208         }
4209
4210         ice_init_link_dflt_override(pf->hw.port_info);
4211
4212         /* if media available, initialize PHY settings */
4213         if (pf->hw.port_info->phy.link_info.link_info &
4214             ICE_AQ_MEDIA_AVAILABLE) {
4215                 err = ice_init_phy_user_cfg(pf->hw.port_info);
4216                 if (err) {
4217                         dev_err(dev, "ice_init_phy_user_cfg failed: %d\n", err);
4218                         goto err_send_version_unroll;
4219                 }
4220
4221                 if (!test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags)) {
4222                         struct ice_vsi *vsi = ice_get_main_vsi(pf);
4223
4224                         if (vsi)
4225                                 ice_configure_phy(vsi);
4226                 }
4227         } else {
4228                 set_bit(ICE_FLAG_NO_MEDIA, pf->flags);
4229         }
4230
4231         ice_verify_cacheline_size(pf);
4232
4233         /* Save wakeup reason register for later use */
4234         pf->wakeup_reason = rd32(hw, PFPM_WUS);
4235
4236         /* check for a power management event */
4237         ice_print_wake_reason(pf);
4238
4239         /* clear wake status, all bits */
4240         wr32(hw, PFPM_WUS, U32_MAX);
4241
4242         /* Disable WoL at init, wait for user to enable */
4243         device_set_wakeup_enable(dev, false);
4244
4245         if (ice_is_safe_mode(pf)) {
4246                 ice_set_safe_mode_vlan_cfg(pf);
4247                 goto probe_done;
4248         }
4249
4250         /* initialize DDP driven features */
4251
4252         /* Note: Flow director init failure is non-fatal to load */
4253         if (ice_init_fdir(pf))
4254                 dev_err(dev, "could not initialize flow director\n");
4255
4256         /* Note: DCB init failure is non-fatal to load */
4257         if (ice_init_pf_dcb(pf, false)) {
4258                 clear_bit(ICE_FLAG_DCB_CAPABLE, pf->flags);
4259                 clear_bit(ICE_FLAG_DCB_ENA, pf->flags);
4260         } else {
4261                 ice_cfg_lldp_mib_change(&pf->hw, true);
4262         }
4263
4264         if (ice_init_lag(pf))
4265                 dev_warn(dev, "Failed to init link aggregation support\n");
4266
4267         /* print PCI link speed and width */
4268         pcie_print_link_status(pf->pdev);
4269
4270 probe_done:
4271         err = ice_register_netdev(pf);
4272         if (err)
4273                 goto err_netdev_reg;
4274
4275         /* ready to go, so clear down state bit */
4276         clear_bit(__ICE_DOWN, pf->state);
4277
4278         return 0;
4279
4280 err_netdev_reg:
4281 err_send_version_unroll:
4282         ice_vsi_release_all(pf);
4283 err_alloc_sw_unroll:
4284         set_bit(__ICE_SERVICE_DIS, pf->state);
4285         set_bit(__ICE_DOWN, pf->state);
4286         devm_kfree(dev, pf->first_sw);
4287 err_msix_misc_unroll:
4288         ice_free_irq_msix_misc(pf);
4289 err_init_interrupt_unroll:
4290         ice_clear_interrupt_scheme(pf);
4291 err_init_vsi_unroll:
4292         devm_kfree(dev, pf->vsi);
4293 err_init_pf_unroll:
4294         ice_deinit_pf(pf);
4295         ice_devlink_destroy_regions(pf);
4296         ice_deinit_hw(hw);
4297 err_exit_unroll:
4298         ice_devlink_unregister(pf);
4299         pci_disable_pcie_error_reporting(pdev);
4300         pci_disable_device(pdev);
4301         return err;
4302 }
4303
4304 /**
4305  * ice_set_wake - enable or disable Wake on LAN
4306  * @pf: pointer to the PF struct
4307  *
4308  * Simple helper for WoL control
4309  */
4310 static void ice_set_wake(struct ice_pf *pf)
4311 {
4312         struct ice_hw *hw = &pf->hw;
4313         bool wol = pf->wol_ena;
4314
4315         /* clear wake state, otherwise new wake events won't fire */
4316         wr32(hw, PFPM_WUS, U32_MAX);
4317
4318         /* enable / disable APM wake up, no RMW needed */
4319         wr32(hw, PFPM_APM, wol ? PFPM_APM_APME_M : 0);
4320
4321         /* set magic packet filter enabled */
4322         wr32(hw, PFPM_WUFC, wol ? PFPM_WUFC_MAG_M : 0);
4323 }
4324
4325 /**
4326  * ice_setup_mc_magic_wake - setup device to wake on multicast magic packet
4327  * @pf: pointer to the PF struct
4328  *
4329  * Issue firmware command to enable multicast magic wake, making
4330  * sure that any locally administered address (LAA) is used for
4331  * wake, and that PF reset doesn't undo the LAA.
4332  */
4333 static void ice_setup_mc_magic_wake(struct ice_pf *pf)
4334 {
4335         struct device *dev = ice_pf_to_dev(pf);
4336         struct ice_hw *hw = &pf->hw;
4337         enum ice_status status;
4338         u8 mac_addr[ETH_ALEN];
4339         struct ice_vsi *vsi;
4340         u8 flags;
4341
4342         if (!pf->wol_ena)
4343                 return;
4344
4345         vsi = ice_get_main_vsi(pf);
4346         if (!vsi)
4347                 return;
4348
4349         /* Get current MAC address in case it's an LAA */
4350         if (vsi->netdev)
4351                 ether_addr_copy(mac_addr, vsi->netdev->dev_addr);
4352         else
4353                 ether_addr_copy(mac_addr, vsi->port_info->mac.perm_addr);
4354
4355         flags = ICE_AQC_MAN_MAC_WR_MC_MAG_EN |
4356                 ICE_AQC_MAN_MAC_UPDATE_LAA_WOL |
4357                 ICE_AQC_MAN_MAC_WR_WOL_LAA_PFR_KEEP;
4358
4359         status = ice_aq_manage_mac_write(hw, mac_addr, flags, NULL);
4360         if (status)
4361                 dev_err(dev, "Failed to enable Multicast Magic Packet wake, err %s aq_err %s\n",
4362                         ice_stat_str(status),
4363                         ice_aq_str(hw->adminq.sq_last_status));
4364 }
4365
4366 /**
4367  * ice_remove - Device removal routine
4368  * @pdev: PCI device information struct
4369  */
4370 static void ice_remove(struct pci_dev *pdev)
4371 {
4372         struct ice_pf *pf = pci_get_drvdata(pdev);
4373         int i;
4374
4375         if (!pf)
4376                 return;
4377
4378         for (i = 0; i < ICE_MAX_RESET_WAIT; i++) {
4379                 if (!ice_is_reset_in_progress(pf->state))
4380                         break;
4381                 msleep(100);
4382         }
4383
4384         if (test_bit(ICE_FLAG_SRIOV_ENA, pf->flags)) {
4385                 set_bit(__ICE_VF_RESETS_DISABLED, pf->state);
4386                 ice_free_vfs(pf);
4387         }
4388
4389         set_bit(__ICE_DOWN, pf->state);
4390         ice_service_task_stop(pf);
4391
4392         ice_aq_cancel_waiting_tasks(pf);
4393
4394         mutex_destroy(&(&pf->hw)->fdir_fltr_lock);
4395         ice_deinit_lag(pf);
4396         if (!ice_is_safe_mode(pf))
4397                 ice_remove_arfs(pf);
4398         ice_setup_mc_magic_wake(pf);
4399         ice_vsi_release_all(pf);
4400         ice_set_wake(pf);
4401         ice_free_irq_msix_misc(pf);
4402         ice_for_each_vsi(pf, i) {
4403                 if (!pf->vsi[i])
4404                         continue;
4405                 ice_vsi_free_q_vectors(pf->vsi[i]);
4406         }
4407         ice_deinit_pf(pf);
4408         ice_devlink_destroy_regions(pf);
4409         ice_deinit_hw(&pf->hw);
4410         ice_devlink_unregister(pf);
4411
4412         /* Issue a PFR as part of the prescribed driver unload flow.  Do not
4413          * do it via ice_schedule_reset() since there is no need to rebuild
4414          * and the service task is already stopped.
4415          */
4416         ice_reset(&pf->hw, ICE_RESET_PFR);
4417         pci_wait_for_pending_transaction(pdev);
4418         ice_clear_interrupt_scheme(pf);
4419         pci_disable_pcie_error_reporting(pdev);
4420         pci_disable_device(pdev);
4421 }
4422
4423 /**
4424  * ice_shutdown - PCI callback for shutting down device
4425  * @pdev: PCI device information struct
4426  */
4427 static void ice_shutdown(struct pci_dev *pdev)
4428 {
4429         struct ice_pf *pf = pci_get_drvdata(pdev);
4430
4431         ice_remove(pdev);
4432
4433         if (system_state == SYSTEM_POWER_OFF) {
4434                 pci_wake_from_d3(pdev, pf->wol_ena);
4435                 pci_set_power_state(pdev, PCI_D3hot);
4436         }
4437 }
4438
4439 #ifdef CONFIG_PM
4440 /**
4441  * ice_prepare_for_shutdown - prep for PCI shutdown
4442  * @pf: board private structure
4443  *
4444  * Inform or close all dependent features in prep for PCI device shutdown
4445  */
4446 static void ice_prepare_for_shutdown(struct ice_pf *pf)
4447 {
4448         struct ice_hw *hw = &pf->hw;
4449         u32 v;
4450
4451         /* Notify VFs of impending reset */
4452         if (ice_check_sq_alive(hw, &hw->mailboxq))
4453                 ice_vc_notify_reset(pf);
4454
4455         dev_dbg(ice_pf_to_dev(pf), "Tearing down internal switch for shutdown\n");
4456
4457         /* disable the VSIs and their queues that are not already DOWN */
4458         ice_pf_dis_all_vsi(pf, false);
4459
4460         ice_for_each_vsi(pf, v)
4461                 if (pf->vsi[v])
4462                         pf->vsi[v]->vsi_num = 0;
4463
4464         ice_shutdown_all_ctrlq(hw);
4465 }
4466
4467 /**
4468  * ice_reinit_interrupt_scheme - Reinitialize interrupt scheme
4469  * @pf: board private structure to reinitialize
4470  *
4471  * This routine reinitialize interrupt scheme that was cleared during
4472  * power management suspend callback.
4473  *
4474  * This should be called during resume routine to re-allocate the q_vectors
4475  * and reacquire interrupts.
4476  */
4477 static int ice_reinit_interrupt_scheme(struct ice_pf *pf)
4478 {
4479         struct device *dev = ice_pf_to_dev(pf);
4480         int ret, v;
4481
4482         /* Since we clear MSIX flag during suspend, we need to
4483          * set it back during resume...
4484          */
4485
4486         ret = ice_init_interrupt_scheme(pf);
4487         if (ret) {
4488                 dev_err(dev, "Failed to re-initialize interrupt %d\n", ret);
4489                 return ret;
4490         }
4491
4492         /* Remap vectors and rings, after successful re-init interrupts */
4493         ice_for_each_vsi(pf, v) {
4494                 if (!pf->vsi[v])
4495                         continue;
4496
4497                 ret = ice_vsi_alloc_q_vectors(pf->vsi[v]);
4498                 if (ret)
4499                         goto err_reinit;
4500                 ice_vsi_map_rings_to_vectors(pf->vsi[v]);
4501         }
4502
4503         ret = ice_req_irq_msix_misc(pf);
4504         if (ret) {
4505                 dev_err(dev, "Setting up misc vector failed after device suspend %d\n",
4506                         ret);
4507                 goto err_reinit;
4508         }
4509
4510         return 0;
4511
4512 err_reinit:
4513         while (v--)
4514                 if (pf->vsi[v])
4515                         ice_vsi_free_q_vectors(pf->vsi[v]);
4516
4517         return ret;
4518 }
4519
4520 /**
4521  * ice_suspend
4522  * @dev: generic device information structure
4523  *
4524  * Power Management callback to quiesce the device and prepare
4525  * for D3 transition.
4526  */
4527 static int __maybe_unused ice_suspend(struct device *dev)
4528 {
4529         struct pci_dev *pdev = to_pci_dev(dev);
4530         struct ice_pf *pf;
4531         int disabled, v;
4532
4533         pf = pci_get_drvdata(pdev);
4534
4535         if (!ice_pf_state_is_nominal(pf)) {
4536                 dev_err(dev, "Device is not ready, no need to suspend it\n");
4537                 return -EBUSY;
4538         }
4539
4540         /* Stop watchdog tasks until resume completion.
4541          * Even though it is most likely that the service task is
4542          * disabled if the device is suspended or down, the service task's
4543          * state is controlled by a different state bit, and we should
4544          * store and honor whatever state that bit is in at this point.
4545          */
4546         disabled = ice_service_task_stop(pf);
4547
4548         /* Already suspended?, then there is nothing to do */
4549         if (test_and_set_bit(__ICE_SUSPENDED, pf->state)) {
4550                 if (!disabled)
4551                         ice_service_task_restart(pf);
4552                 return 0;
4553         }
4554
4555         if (test_bit(__ICE_DOWN, pf->state) ||
4556             ice_is_reset_in_progress(pf->state)) {
4557                 dev_err(dev, "can't suspend device in reset or already down\n");
4558                 if (!disabled)
4559                         ice_service_task_restart(pf);
4560                 return 0;
4561         }
4562
4563         ice_setup_mc_magic_wake(pf);
4564
4565         ice_prepare_for_shutdown(pf);
4566
4567         ice_set_wake(pf);
4568
4569         /* Free vectors, clear the interrupt scheme and release IRQs
4570          * for proper hibernation, especially with large number of CPUs.
4571          * Otherwise hibernation might fail when mapping all the vectors back
4572          * to CPU0.
4573          */
4574         ice_free_irq_msix_misc(pf);
4575         ice_for_each_vsi(pf, v) {
4576                 if (!pf->vsi[v])
4577                         continue;
4578                 ice_vsi_free_q_vectors(pf->vsi[v]);
4579         }
4580         ice_clear_interrupt_scheme(pf);
4581
4582         pci_save_state(pdev);
4583         pci_wake_from_d3(pdev, pf->wol_ena);
4584         pci_set_power_state(pdev, PCI_D3hot);
4585         return 0;
4586 }
4587
4588 /**
4589  * ice_resume - PM callback for waking up from D3
4590  * @dev: generic device information structure
4591  */
4592 static int __maybe_unused ice_resume(struct device *dev)
4593 {
4594         struct pci_dev *pdev = to_pci_dev(dev);
4595         enum ice_reset_req reset_type;
4596         struct ice_pf *pf;
4597         struct ice_hw *hw;
4598         int ret;
4599
4600         pci_set_power_state(pdev, PCI_D0);
4601         pci_restore_state(pdev);
4602         pci_save_state(pdev);
4603
4604         if (!pci_device_is_present(pdev))
4605                 return -ENODEV;
4606
4607         ret = pci_enable_device_mem(pdev);
4608         if (ret) {
4609                 dev_err(dev, "Cannot enable device after suspend\n");
4610                 return ret;
4611         }
4612
4613         pf = pci_get_drvdata(pdev);
4614         hw = &pf->hw;
4615
4616         pf->wakeup_reason = rd32(hw, PFPM_WUS);
4617         ice_print_wake_reason(pf);
4618
4619         /* We cleared the interrupt scheme when we suspended, so we need to
4620          * restore it now to resume device functionality.
4621          */
4622         ret = ice_reinit_interrupt_scheme(pf);
4623         if (ret)
4624                 dev_err(dev, "Cannot restore interrupt scheme: %d\n", ret);
4625
4626         clear_bit(__ICE_DOWN, pf->state);
4627         /* Now perform PF reset and rebuild */
4628         reset_type = ICE_RESET_PFR;
4629         /* re-enable service task for reset, but allow reset to schedule it */
4630         clear_bit(__ICE_SERVICE_DIS, pf->state);
4631
4632         if (ice_schedule_reset(pf, reset_type))
4633                 dev_err(dev, "Reset during resume failed.\n");
4634
4635         clear_bit(__ICE_SUSPENDED, pf->state);
4636         ice_service_task_restart(pf);
4637
4638         /* Restart the service task */
4639         mod_timer(&pf->serv_tmr, round_jiffies(jiffies + pf->serv_tmr_period));
4640
4641         return 0;
4642 }
4643 #endif /* CONFIG_PM */
4644
4645 /**
4646  * ice_pci_err_detected - warning that PCI error has been detected
4647  * @pdev: PCI device information struct
4648  * @err: the type of PCI error
4649  *
4650  * Called to warn that something happened on the PCI bus and the error handling
4651  * is in progress.  Allows the driver to gracefully prepare/handle PCI errors.
4652  */
4653 static pci_ers_result_t
4654 ice_pci_err_detected(struct pci_dev *pdev, pci_channel_state_t err)
4655 {
4656         struct ice_pf *pf = pci_get_drvdata(pdev);
4657
4658         if (!pf) {
4659                 dev_err(&pdev->dev, "%s: unrecoverable device error %d\n",
4660                         __func__, err);
4661                 return PCI_ERS_RESULT_DISCONNECT;
4662         }
4663
4664         if (!test_bit(__ICE_SUSPENDED, pf->state)) {
4665                 ice_service_task_stop(pf);
4666
4667                 if (!test_bit(__ICE_PREPARED_FOR_RESET, pf->state)) {
4668                         set_bit(__ICE_PFR_REQ, pf->state);
4669                         ice_prepare_for_reset(pf);
4670                 }
4671         }
4672
4673         return PCI_ERS_RESULT_NEED_RESET;
4674 }
4675
4676 /**
4677  * ice_pci_err_slot_reset - a PCI slot reset has just happened
4678  * @pdev: PCI device information struct
4679  *
4680  * Called to determine if the driver can recover from the PCI slot reset by
4681  * using a register read to determine if the device is recoverable.
4682  */
4683 static pci_ers_result_t ice_pci_err_slot_reset(struct pci_dev *pdev)
4684 {
4685         struct ice_pf *pf = pci_get_drvdata(pdev);
4686         pci_ers_result_t result;
4687         int err;
4688         u32 reg;
4689
4690         err = pci_enable_device_mem(pdev);
4691         if (err) {
4692                 dev_err(&pdev->dev, "Cannot re-enable PCI device after reset, error %d\n",
4693                         err);
4694                 result = PCI_ERS_RESULT_DISCONNECT;
4695         } else {
4696                 pci_set_master(pdev);
4697                 pci_restore_state(pdev);
4698                 pci_save_state(pdev);
4699                 pci_wake_from_d3(pdev, false);
4700
4701                 /* Check for life */
4702                 reg = rd32(&pf->hw, GLGEN_RTRIG);
4703                 if (!reg)
4704                         result = PCI_ERS_RESULT_RECOVERED;
4705                 else
4706                         result = PCI_ERS_RESULT_DISCONNECT;
4707         }
4708
4709         err = pci_aer_clear_nonfatal_status(pdev);
4710         if (err)
4711                 dev_dbg(&pdev->dev, "pci_aer_clear_nonfatal_status() failed, error %d\n",
4712                         err);
4713                 /* non-fatal, continue */
4714
4715         return result;
4716 }
4717
4718 /**
4719  * ice_pci_err_resume - restart operations after PCI error recovery
4720  * @pdev: PCI device information struct
4721  *
4722  * Called to allow the driver to bring things back up after PCI error and/or
4723  * reset recovery have finished
4724  */
4725 static void ice_pci_err_resume(struct pci_dev *pdev)
4726 {
4727         struct ice_pf *pf = pci_get_drvdata(pdev);
4728
4729         if (!pf) {
4730                 dev_err(&pdev->dev, "%s failed, device is unrecoverable\n",
4731                         __func__);
4732                 return;
4733         }
4734
4735         if (test_bit(__ICE_SUSPENDED, pf->state)) {
4736                 dev_dbg(&pdev->dev, "%s failed to resume normal operations!\n",
4737                         __func__);
4738                 return;
4739         }
4740
4741         ice_restore_all_vfs_msi_state(pdev);
4742
4743         ice_do_reset(pf, ICE_RESET_PFR);
4744         ice_service_task_restart(pf);
4745         mod_timer(&pf->serv_tmr, round_jiffies(jiffies + pf->serv_tmr_period));
4746 }
4747
4748 /**
4749  * ice_pci_err_reset_prepare - prepare device driver for PCI reset
4750  * @pdev: PCI device information struct
4751  */
4752 static void ice_pci_err_reset_prepare(struct pci_dev *pdev)
4753 {
4754         struct ice_pf *pf = pci_get_drvdata(pdev);
4755
4756         if (!test_bit(__ICE_SUSPENDED, pf->state)) {
4757                 ice_service_task_stop(pf);
4758
4759                 if (!test_bit(__ICE_PREPARED_FOR_RESET, pf->state)) {
4760                         set_bit(__ICE_PFR_REQ, pf->state);
4761                         ice_prepare_for_reset(pf);
4762                 }
4763         }
4764 }
4765
4766 /**
4767  * ice_pci_err_reset_done - PCI reset done, device driver reset can begin
4768  * @pdev: PCI device information struct
4769  */
4770 static void ice_pci_err_reset_done(struct pci_dev *pdev)
4771 {
4772         ice_pci_err_resume(pdev);
4773 }
4774
4775 /* ice_pci_tbl - PCI Device ID Table
4776  *
4777  * Wildcard entries (PCI_ANY_ID) should come last
4778  * Last entry must be all 0s
4779  *
4780  * { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
4781  *   Class, Class Mask, private data (not used) }
4782  */
4783 static const struct pci_device_id ice_pci_tbl[] = {
4784         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810C_BACKPLANE), 0 },
4785         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810C_QSFP), 0 },
4786         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810C_SFP), 0 },
4787         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E810_XXV_SFP), 0 },
4788         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_BACKPLANE), 0 },
4789         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_QSFP), 0 },
4790         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_SFP), 0 },
4791         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_10G_BASE_T), 0 },
4792         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823C_SGMII), 0 },
4793         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_BACKPLANE), 0 },
4794         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_QSFP), 0 },
4795         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_SFP), 0 },
4796         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_10G_BASE_T), 0 },
4797         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822C_SGMII), 0 },
4798         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_BACKPLANE), 0 },
4799         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_SFP), 0 },
4800         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_10G_BASE_T), 0 },
4801         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E822L_SGMII), 0 },
4802         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_BACKPLANE), 0 },
4803         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_SFP), 0 },
4804         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_10G_BASE_T), 0 },
4805         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_1GBE), 0 },
4806         { PCI_VDEVICE(INTEL, ICE_DEV_ID_E823L_QSFP), 0 },
4807         /* required last entry */
4808         { 0, }
4809 };
4810 MODULE_DEVICE_TABLE(pci, ice_pci_tbl);
4811
4812 static __maybe_unused SIMPLE_DEV_PM_OPS(ice_pm_ops, ice_suspend, ice_resume);
4813
4814 static const struct pci_error_handlers ice_pci_err_handler = {
4815         .error_detected = ice_pci_err_detected,
4816         .slot_reset = ice_pci_err_slot_reset,
4817         .reset_prepare = ice_pci_err_reset_prepare,
4818         .reset_done = ice_pci_err_reset_done,
4819         .resume = ice_pci_err_resume
4820 };
4821
4822 static struct pci_driver ice_driver = {
4823         .name = KBUILD_MODNAME,
4824         .id_table = ice_pci_tbl,
4825         .probe = ice_probe,
4826         .remove = ice_remove,
4827 #ifdef CONFIG_PM
4828         .driver.pm = &ice_pm_ops,
4829 #endif /* CONFIG_PM */
4830         .shutdown = ice_shutdown,
4831         .sriov_configure = ice_sriov_configure,
4832         .err_handler = &ice_pci_err_handler
4833 };
4834
4835 /**
4836  * ice_module_init - Driver registration routine
4837  *
4838  * ice_module_init is the first routine called when the driver is
4839  * loaded. All it does is register with the PCI subsystem.
4840  */
4841 static int __init ice_module_init(void)
4842 {
4843         int status;
4844
4845         pr_info("%s\n", ice_driver_string);
4846         pr_info("%s\n", ice_copyright);
4847
4848         ice_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, KBUILD_MODNAME);
4849         if (!ice_wq) {
4850                 pr_err("Failed to create workqueue\n");
4851                 return -ENOMEM;
4852         }
4853
4854         status = pci_register_driver(&ice_driver);
4855         if (status) {
4856                 pr_err("failed to register PCI driver, err %d\n", status);
4857                 destroy_workqueue(ice_wq);
4858         }
4859
4860         return status;
4861 }
4862 module_init(ice_module_init);
4863
4864 /**
4865  * ice_module_exit - Driver exit cleanup routine
4866  *
4867  * ice_module_exit is called just before the driver is removed
4868  * from memory.
4869  */
4870 static void __exit ice_module_exit(void)
4871 {
4872         pci_unregister_driver(&ice_driver);
4873         destroy_workqueue(ice_wq);
4874         pr_info("module unloaded\n");
4875 }
4876 module_exit(ice_module_exit);
4877
4878 /**
4879  * ice_set_mac_address - NDO callback to set MAC address
4880  * @netdev: network interface device structure
4881  * @pi: pointer to an address structure
4882  *
4883  * Returns 0 on success, negative on failure
4884  */
4885 static int ice_set_mac_address(struct net_device *netdev, void *pi)
4886 {
4887         struct ice_netdev_priv *np = netdev_priv(netdev);
4888         struct ice_vsi *vsi = np->vsi;
4889         struct ice_pf *pf = vsi->back;
4890         struct ice_hw *hw = &pf->hw;
4891         struct sockaddr *addr = pi;
4892         enum ice_status status;
4893         u8 flags = 0;
4894         int err = 0;
4895         u8 *mac;
4896
4897         mac = (u8 *)addr->sa_data;
4898
4899         if (!is_valid_ether_addr(mac))
4900                 return -EADDRNOTAVAIL;
4901
4902         if (ether_addr_equal(netdev->dev_addr, mac)) {
4903                 netdev_warn(netdev, "already using mac %pM\n", mac);
4904                 return 0;
4905         }
4906
4907         if (test_bit(__ICE_DOWN, pf->state) ||
4908             ice_is_reset_in_progress(pf->state)) {
4909                 netdev_err(netdev, "can't set mac %pM. device not ready\n",
4910                            mac);
4911                 return -EBUSY;
4912         }
4913
4914         /* Clean up old MAC filter. Not an error if old filter doesn't exist */
4915         status = ice_fltr_remove_mac(vsi, netdev->dev_addr, ICE_FWD_TO_VSI);
4916         if (status && status != ICE_ERR_DOES_NOT_EXIST) {
4917                 err = -EADDRNOTAVAIL;
4918                 goto err_update_filters;
4919         }
4920
4921         /* Add filter for new MAC. If filter exists, return success */
4922         status = ice_fltr_add_mac(vsi, mac, ICE_FWD_TO_VSI);
4923         if (status == ICE_ERR_ALREADY_EXISTS) {
4924                 /* Although this MAC filter is already present in hardware it's
4925                  * possible in some cases (e.g. bonding) that dev_addr was
4926                  * modified outside of the driver and needs to be restored back
4927                  * to this value.
4928                  */
4929                 memcpy(netdev->dev_addr, mac, netdev->addr_len);
4930                 netdev_dbg(netdev, "filter for MAC %pM already exists\n", mac);
4931                 return 0;
4932         }
4933
4934         /* error if the new filter addition failed */
4935         if (status)
4936                 err = -EADDRNOTAVAIL;
4937
4938 err_update_filters:
4939         if (err) {
4940                 netdev_err(netdev, "can't set MAC %pM. filter update failed\n",
4941                            mac);
4942                 return err;
4943         }
4944
4945         /* change the netdev's MAC address */
4946         memcpy(netdev->dev_addr, mac, netdev->addr_len);
4947         netdev_dbg(vsi->netdev, "updated MAC address to %pM\n",
4948                    netdev->dev_addr);
4949
4950         /* write new MAC address to the firmware */
4951         flags = ICE_AQC_MAN_MAC_UPDATE_LAA_WOL;
4952         status = ice_aq_manage_mac_write(hw, mac, flags, NULL);
4953         if (status) {
4954                 netdev_err(netdev, "can't set MAC %pM. write to firmware failed error %s\n",
4955                            mac, ice_stat_str(status));
4956         }
4957         return 0;
4958 }
4959
4960 /**
4961  * ice_set_rx_mode - NDO callback to set the netdev filters
4962  * @netdev: network interface device structure
4963  */
4964 static void ice_set_rx_mode(struct net_device *netdev)
4965 {
4966         struct ice_netdev_priv *np = netdev_priv(netdev);
4967         struct ice_vsi *vsi = np->vsi;
4968
4969         if (!vsi)
4970                 return;
4971
4972         /* Set the flags to synchronize filters
4973          * ndo_set_rx_mode may be triggered even without a change in netdev
4974          * flags
4975          */
4976         set_bit(ICE_VSI_FLAG_UMAC_FLTR_CHANGED, vsi->flags);
4977         set_bit(ICE_VSI_FLAG_MMAC_FLTR_CHANGED, vsi->flags);
4978         set_bit(ICE_FLAG_FLTR_SYNC, vsi->back->flags);
4979
4980         /* schedule our worker thread which will take care of
4981          * applying the new filter changes
4982          */
4983         ice_service_task_schedule(vsi->back);
4984 }
4985
4986 /**
4987  * ice_set_tx_maxrate - NDO callback to set the maximum per-queue bitrate
4988  * @netdev: network interface device structure
4989  * @queue_index: Queue ID
4990  * @maxrate: maximum bandwidth in Mbps
4991  */
4992 static int
4993 ice_set_tx_maxrate(struct net_device *netdev, int queue_index, u32 maxrate)
4994 {
4995         struct ice_netdev_priv *np = netdev_priv(netdev);
4996         struct ice_vsi *vsi = np->vsi;
4997         enum ice_status status;
4998         u16 q_handle;
4999         u8 tc;
5000
5001         /* Validate maxrate requested is within permitted range */
5002         if (maxrate && (maxrate > (ICE_SCHED_MAX_BW / 1000))) {
5003                 netdev_err(netdev, "Invalid max rate %d specified for the queue %d\n",
5004                            maxrate, queue_index);
5005                 return -EINVAL;
5006         }
5007
5008         q_handle = vsi->tx_rings[queue_index]->q_handle;
5009         tc = ice_dcb_get_tc(vsi, queue_index);
5010
5011         /* Set BW back to default, when user set maxrate to 0 */
5012         if (!maxrate)
5013                 status = ice_cfg_q_bw_dflt_lmt(vsi->port_info, vsi->idx, tc,
5014                                                q_handle, ICE_MAX_BW);
5015         else
5016                 status = ice_cfg_q_bw_lmt(vsi->port_info, vsi->idx, tc,
5017                                           q_handle, ICE_MAX_BW, maxrate * 1000);
5018         if (status) {
5019                 netdev_err(netdev, "Unable to set Tx max rate, error %s\n",
5020                            ice_stat_str(status));
5021                 return -EIO;
5022         }
5023
5024         return 0;
5025 }
5026
5027 /**
5028  * ice_fdb_add - add an entry to the hardware database
5029  * @ndm: the input from the stack
5030  * @tb: pointer to array of nladdr (unused)
5031  * @dev: the net device pointer
5032  * @addr: the MAC address entry being added
5033  * @vid: VLAN ID
5034  * @flags: instructions from stack about fdb operation
5035  * @extack: netlink extended ack
5036  */
5037 static int
5038 ice_fdb_add(struct ndmsg *ndm, struct nlattr __always_unused *tb[],
5039             struct net_device *dev, const unsigned char *addr, u16 vid,
5040             u16 flags, struct netlink_ext_ack __always_unused *extack)
5041 {
5042         int err;
5043
5044         if (vid) {
5045                 netdev_err(dev, "VLANs aren't supported yet for dev_uc|mc_add()\n");
5046                 return -EINVAL;
5047         }
5048         if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
5049                 netdev_err(dev, "FDB only supports static addresses\n");
5050                 return -EINVAL;
5051         }
5052
5053         if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
5054                 err = dev_uc_add_excl(dev, addr);
5055         else if (is_multicast_ether_addr(addr))
5056                 err = dev_mc_add_excl(dev, addr);
5057         else
5058                 err = -EINVAL;
5059
5060         /* Only return duplicate errors if NLM_F_EXCL is set */
5061         if (err == -EEXIST && !(flags & NLM_F_EXCL))
5062                 err = 0;
5063
5064         return err;
5065 }
5066
5067 /**
5068  * ice_fdb_del - delete an entry from the hardware database
5069  * @ndm: the input from the stack
5070  * @tb: pointer to array of nladdr (unused)
5071  * @dev: the net device pointer
5072  * @addr: the MAC address entry being added
5073  * @vid: VLAN ID
5074  */
5075 static int
5076 ice_fdb_del(struct ndmsg *ndm, __always_unused struct nlattr *tb[],
5077             struct net_device *dev, const unsigned char *addr,
5078             __always_unused u16 vid)
5079 {
5080         int err;
5081
5082         if (ndm->ndm_state & NUD_PERMANENT) {
5083                 netdev_err(dev, "FDB only supports static addresses\n");
5084                 return -EINVAL;
5085         }
5086
5087         if (is_unicast_ether_addr(addr))
5088                 err = dev_uc_del(dev, addr);
5089         else if (is_multicast_ether_addr(addr))
5090                 err = dev_mc_del(dev, addr);
5091         else
5092                 err = -EINVAL;
5093
5094         return err;
5095 }
5096
5097 /**
5098  * ice_set_features - set the netdev feature flags
5099  * @netdev: ptr to the netdev being adjusted
5100  * @features: the feature set that the stack is suggesting
5101  */
5102 static int
5103 ice_set_features(struct net_device *netdev, netdev_features_t features)
5104 {
5105         struct ice_netdev_priv *np = netdev_priv(netdev);
5106         struct ice_vsi *vsi = np->vsi;
5107         struct ice_pf *pf = vsi->back;
5108         int ret = 0;
5109
5110         /* Don't set any netdev advanced features with device in Safe Mode */
5111         if (ice_is_safe_mode(vsi->back)) {
5112                 dev_err(ice_pf_to_dev(vsi->back), "Device is in Safe Mode - not enabling advanced netdev features\n");
5113                 return ret;
5114         }
5115
5116         /* Do not change setting during reset */
5117         if (ice_is_reset_in_progress(pf->state)) {
5118                 dev_err(ice_pf_to_dev(vsi->back), "Device is resetting, changing advanced netdev features temporarily unavailable.\n");
5119                 return -EBUSY;
5120         }
5121
5122         /* Multiple features can be changed in one call so keep features in
5123          * separate if/else statements to guarantee each feature is checked
5124          */
5125         if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
5126                 ret = ice_vsi_manage_rss_lut(vsi, true);
5127         else if (!(features & NETIF_F_RXHASH) &&
5128                  netdev->features & NETIF_F_RXHASH)
5129                 ret = ice_vsi_manage_rss_lut(vsi, false);
5130
5131         if ((features & NETIF_F_HW_VLAN_CTAG_RX) &&
5132             !(netdev->features & NETIF_F_HW_VLAN_CTAG_RX))
5133                 ret = ice_vsi_manage_vlan_stripping(vsi, true);
5134         else if (!(features & NETIF_F_HW_VLAN_CTAG_RX) &&
5135                  (netdev->features & NETIF_F_HW_VLAN_CTAG_RX))
5136                 ret = ice_vsi_manage_vlan_stripping(vsi, false);
5137
5138         if ((features & NETIF_F_HW_VLAN_CTAG_TX) &&
5139             !(netdev->features & NETIF_F_HW_VLAN_CTAG_TX))
5140                 ret = ice_vsi_manage_vlan_insertion(vsi);
5141         else if (!(features & NETIF_F_HW_VLAN_CTAG_TX) &&
5142                  (netdev->features & NETIF_F_HW_VLAN_CTAG_TX))
5143                 ret = ice_vsi_manage_vlan_insertion(vsi);
5144
5145         if ((features & NETIF_F_HW_VLAN_CTAG_FILTER) &&
5146             !(netdev->features & NETIF_F_HW_VLAN_CTAG_FILTER))
5147                 ret = ice_cfg_vlan_pruning(vsi, true, false);
5148         else if (!(features & NETIF_F_HW_VLAN_CTAG_FILTER) &&
5149                  (netdev->features & NETIF_F_HW_VLAN_CTAG_FILTER))
5150                 ret = ice_cfg_vlan_pruning(vsi, false, false);
5151
5152         if ((features & NETIF_F_NTUPLE) &&
5153             !(netdev->features & NETIF_F_NTUPLE)) {
5154                 ice_vsi_manage_fdir(vsi, true);
5155                 ice_init_arfs(vsi);
5156         } else if (!(features & NETIF_F_NTUPLE) &&
5157                  (netdev->features & NETIF_F_NTUPLE)) {
5158                 ice_vsi_manage_fdir(vsi, false);
5159                 ice_clear_arfs(vsi);
5160         }
5161
5162         return ret;
5163 }
5164
5165 /**
5166  * ice_vsi_vlan_setup - Setup VLAN offload properties on a VSI
5167  * @vsi: VSI to setup VLAN properties for
5168  */
5169 static int ice_vsi_vlan_setup(struct ice_vsi *vsi)
5170 {
5171         int ret = 0;
5172
5173         if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
5174                 ret = ice_vsi_manage_vlan_stripping(vsi, true);
5175         if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_TX)
5176                 ret = ice_vsi_manage_vlan_insertion(vsi);
5177
5178         return ret;
5179 }
5180
5181 /**
5182  * ice_vsi_cfg - Setup the VSI
5183  * @vsi: the VSI being configured
5184  *
5185  * Return 0 on success and negative value on error
5186  */
5187 int ice_vsi_cfg(struct ice_vsi *vsi)
5188 {
5189         int err;
5190
5191         if (vsi->netdev) {
5192                 ice_set_rx_mode(vsi->netdev);
5193
5194                 err = ice_vsi_vlan_setup(vsi);
5195
5196                 if (err)
5197                         return err;
5198         }
5199         ice_vsi_cfg_dcb_rings(vsi);
5200
5201         err = ice_vsi_cfg_lan_txqs(vsi);
5202         if (!err && ice_is_xdp_ena_vsi(vsi))
5203                 err = ice_vsi_cfg_xdp_txqs(vsi);
5204         if (!err)
5205                 err = ice_vsi_cfg_rxqs(vsi);
5206
5207         return err;
5208 }
5209
5210 /**
5211  * ice_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5212  * @vsi: the VSI being configured
5213  */
5214 static void ice_napi_enable_all(struct ice_vsi *vsi)
5215 {
5216         int q_idx;
5217
5218         if (!vsi->netdev)
5219                 return;
5220
5221         ice_for_each_q_vector(vsi, q_idx) {
5222                 struct ice_q_vector *q_vector = vsi->q_vectors[q_idx];
5223
5224                 if (q_vector->rx.ring || q_vector->tx.ring)
5225                         napi_enable(&q_vector->napi);
5226         }
5227 }
5228
5229 /**
5230  * ice_up_complete - Finish the last steps of bringing up a connection
5231  * @vsi: The VSI being configured
5232  *
5233  * Return 0 on success and negative value on error
5234  */
5235 static int ice_up_complete(struct ice_vsi *vsi)
5236 {
5237         struct ice_pf *pf = vsi->back;
5238         int err;
5239
5240         ice_vsi_cfg_msix(vsi);
5241
5242         /* Enable only Rx rings, Tx rings were enabled by the FW when the
5243          * Tx queue group list was configured and the context bits were
5244          * programmed using ice_vsi_cfg_txqs
5245          */
5246         err = ice_vsi_start_all_rx_rings(vsi);
5247         if (err)
5248                 return err;
5249
5250         clear_bit(__ICE_DOWN, vsi->state);
5251         ice_napi_enable_all(vsi);
5252         ice_vsi_ena_irq(vsi);
5253
5254         if (vsi->port_info &&
5255             (vsi->port_info->phy.link_info.link_info & ICE_AQ_LINK_UP) &&
5256             vsi->netdev) {
5257                 ice_print_link_msg(vsi, true);
5258                 netif_tx_start_all_queues(vsi->netdev);
5259                 netif_carrier_on(vsi->netdev);
5260         }
5261
5262         ice_service_task_schedule(pf);
5263
5264         return 0;
5265 }
5266
5267 /**
5268  * ice_up - Bring the connection back up after being down
5269  * @vsi: VSI being configured
5270  */
5271 int ice_up(struct ice_vsi *vsi)
5272 {
5273         int err;
5274
5275         err = ice_vsi_cfg(vsi);
5276         if (!err)
5277                 err = ice_up_complete(vsi);
5278
5279         return err;
5280 }
5281
5282 /**
5283  * ice_fetch_u64_stats_per_ring - get packets and bytes stats per ring
5284  * @ring: Tx or Rx ring to read stats from
5285  * @pkts: packets stats counter
5286  * @bytes: bytes stats counter
5287  *
5288  * This function fetches stats from the ring considering the atomic operations
5289  * that needs to be performed to read u64 values in 32 bit machine.
5290  */
5291 static void
5292 ice_fetch_u64_stats_per_ring(struct ice_ring *ring, u64 *pkts, u64 *bytes)
5293 {
5294         unsigned int start;
5295         *pkts = 0;
5296         *bytes = 0;
5297
5298         if (!ring)
5299                 return;
5300         do {
5301                 start = u64_stats_fetch_begin_irq(&ring->syncp);
5302                 *pkts = ring->stats.pkts;
5303                 *bytes = ring->stats.bytes;
5304         } while (u64_stats_fetch_retry_irq(&ring->syncp, start));
5305 }
5306
5307 /**
5308  * ice_update_vsi_tx_ring_stats - Update VSI Tx ring stats counters
5309  * @vsi: the VSI to be updated
5310  * @rings: rings to work on
5311  * @count: number of rings
5312  */
5313 static void
5314 ice_update_vsi_tx_ring_stats(struct ice_vsi *vsi, struct ice_ring **rings,
5315                              u16 count)
5316 {
5317         struct rtnl_link_stats64 *vsi_stats = &vsi->net_stats;
5318         u16 i;
5319
5320         for (i = 0; i < count; i++) {
5321                 struct ice_ring *ring;
5322                 u64 pkts, bytes;
5323
5324                 ring = READ_ONCE(rings[i]);
5325                 ice_fetch_u64_stats_per_ring(ring, &pkts, &bytes);
5326                 vsi_stats->tx_packets += pkts;
5327                 vsi_stats->tx_bytes += bytes;
5328                 vsi->tx_restart += ring->tx_stats.restart_q;
5329                 vsi->tx_busy += ring->tx_stats.tx_busy;
5330                 vsi->tx_linearize += ring->tx_stats.tx_linearize;
5331         }
5332 }
5333
5334 /**
5335  * ice_update_vsi_ring_stats - Update VSI stats counters
5336  * @vsi: the VSI to be updated
5337  */
5338 static void ice_update_vsi_ring_stats(struct ice_vsi *vsi)
5339 {
5340         struct rtnl_link_stats64 *vsi_stats = &vsi->net_stats;
5341         struct ice_ring *ring;
5342         u64 pkts, bytes;
5343         int i;
5344
5345         /* reset netdev stats */
5346         vsi_stats->tx_packets = 0;
5347         vsi_stats->tx_bytes = 0;
5348         vsi_stats->rx_packets = 0;
5349         vsi_stats->rx_bytes = 0;
5350
5351         /* reset non-netdev (extended) stats */
5352         vsi->tx_restart = 0;
5353         vsi->tx_busy = 0;
5354         vsi->tx_linearize = 0;
5355         vsi->rx_buf_failed = 0;
5356         vsi->rx_page_failed = 0;
5357         vsi->rx_gro_dropped = 0;
5358
5359         rcu_read_lock();
5360
5361         /* update Tx rings counters */
5362         ice_update_vsi_tx_ring_stats(vsi, vsi->tx_rings, vsi->num_txq);
5363
5364         /* update Rx rings counters */
5365         ice_for_each_rxq(vsi, i) {
5366                 ring = READ_ONCE(vsi->rx_rings[i]);
5367                 ice_fetch_u64_stats_per_ring(ring, &pkts, &bytes);
5368                 vsi_stats->rx_packets += pkts;
5369                 vsi_stats->rx_bytes += bytes;
5370                 vsi->rx_buf_failed += ring->rx_stats.alloc_buf_failed;
5371                 vsi->rx_page_failed += ring->rx_stats.alloc_page_failed;
5372                 vsi->rx_gro_dropped += ring->rx_stats.gro_dropped;
5373         }
5374
5375         /* update XDP Tx rings counters */
5376         if (ice_is_xdp_ena_vsi(vsi))
5377                 ice_update_vsi_tx_ring_stats(vsi, vsi->xdp_rings,
5378                                              vsi->num_xdp_txq);
5379
5380         rcu_read_unlock();
5381 }
5382
5383 /**
5384  * ice_update_vsi_stats - Update VSI stats counters
5385  * @vsi: the VSI to be updated
5386  */
5387 void ice_update_vsi_stats(struct ice_vsi *vsi)
5388 {
5389         struct rtnl_link_stats64 *cur_ns = &vsi->net_stats;
5390         struct ice_eth_stats *cur_es = &vsi->eth_stats;
5391         struct ice_pf *pf = vsi->back;
5392
5393         if (test_bit(__ICE_DOWN, vsi->state) ||
5394             test_bit(__ICE_CFG_BUSY, pf->state))
5395                 return;
5396
5397         /* get stats as recorded by Tx/Rx rings */
5398         ice_update_vsi_ring_stats(vsi);
5399
5400         /* get VSI stats as recorded by the hardware */
5401         ice_update_eth_stats(vsi);
5402
5403         cur_ns->tx_errors = cur_es->tx_errors;
5404         cur_ns->rx_dropped = cur_es->rx_discards + vsi->rx_gro_dropped;
5405         cur_ns->tx_dropped = cur_es->tx_discards;
5406         cur_ns->multicast = cur_es->rx_multicast;
5407
5408         /* update some more netdev stats if this is main VSI */
5409         if (vsi->type == ICE_VSI_PF) {
5410                 cur_ns->rx_crc_errors = pf->stats.crc_errors;
5411                 cur_ns->rx_errors = pf->stats.crc_errors +
5412                                     pf->stats.illegal_bytes +
5413                                     pf->stats.rx_len_errors +
5414                                     pf->stats.rx_undersize +
5415                                     pf->hw_csum_rx_error +
5416                                     pf->stats.rx_jabber +
5417                                     pf->stats.rx_fragments +
5418                                     pf->stats.rx_oversize;
5419                 cur_ns->rx_length_errors = pf->stats.rx_len_errors;
5420                 /* record drops from the port level */
5421                 cur_ns->rx_missed_errors = pf->stats.eth.rx_discards;
5422         }
5423 }
5424
5425 /**
5426  * ice_update_pf_stats - Update PF port stats counters
5427  * @pf: PF whose stats needs to be updated
5428  */
5429 void ice_update_pf_stats(struct ice_pf *pf)
5430 {
5431         struct ice_hw_port_stats *prev_ps, *cur_ps;
5432         struct ice_hw *hw = &pf->hw;
5433         u16 fd_ctr_base;
5434         u8 port;
5435
5436         port = hw->port_info->lport;
5437         prev_ps = &pf->stats_prev;
5438         cur_ps = &pf->stats;
5439
5440         ice_stat_update40(hw, GLPRT_GORCL(port), pf->stat_prev_loaded,
5441                           &prev_ps->eth.rx_bytes,
5442                           &cur_ps->eth.rx_bytes);
5443
5444         ice_stat_update40(hw, GLPRT_UPRCL(port), pf->stat_prev_loaded,
5445                           &prev_ps->eth.rx_unicast,
5446                           &cur_ps->eth.rx_unicast);
5447
5448         ice_stat_update40(hw, GLPRT_MPRCL(port), pf->stat_prev_loaded,
5449                           &prev_ps->eth.rx_multicast,
5450                           &cur_ps->eth.rx_multicast);
5451
5452         ice_stat_update40(hw, GLPRT_BPRCL(port), pf->stat_prev_loaded,
5453                           &prev_ps->eth.rx_broadcast,
5454                           &cur_ps->eth.rx_broadcast);
5455
5456         ice_stat_update32(hw, PRTRPB_RDPC, pf->stat_prev_loaded,
5457                           &prev_ps->eth.rx_discards,
5458                           &cur_ps->eth.rx_discards);
5459
5460         ice_stat_update40(hw, GLPRT_GOTCL(port), pf->stat_prev_loaded,
5461                           &prev_ps->eth.tx_bytes,
5462                           &cur_ps->eth.tx_bytes);
5463
5464         ice_stat_update40(hw, GLPRT_UPTCL(port), pf->stat_prev_loaded,
5465                           &prev_ps->eth.tx_unicast,
5466                           &cur_ps->eth.tx_unicast);
5467
5468         ice_stat_update40(hw, GLPRT_MPTCL(port), pf->stat_prev_loaded,
5469                           &prev_ps->eth.tx_multicast,
5470                           &cur_ps->eth.tx_multicast);
5471
5472         ice_stat_update40(hw, GLPRT_BPTCL(port), pf->stat_prev_loaded,
5473                           &prev_ps->eth.tx_broadcast,
5474                           &cur_ps->eth.tx_broadcast);
5475
5476         ice_stat_update32(hw, GLPRT_TDOLD(port), pf->stat_prev_loaded,
5477                           &prev_ps->tx_dropped_link_down,
5478                           &cur_ps->tx_dropped_link_down);
5479
5480         ice_stat_update40(hw, GLPRT_PRC64L(port), pf->stat_prev_loaded,
5481                           &prev_ps->rx_size_64, &cur_ps->rx_size_64);
5482
5483         ice_stat_update40(hw, GLPRT_PRC127L(port), pf->stat_prev_loaded,
5484                           &prev_ps->rx_size_127, &cur_ps->rx_size_127);
5485
5486         ice_stat_update40(hw, GLPRT_PRC255L(port), pf->stat_prev_loaded,
5487                           &prev_ps->rx_size_255, &cur_ps->rx_size_255);
5488
5489         ice_stat_update40(hw, GLPRT_PRC511L(port), pf->stat_prev_loaded,
5490                           &prev_ps->rx_size_511, &cur_ps->rx_size_511);
5491
5492         ice_stat_update40(hw, GLPRT_PRC1023L(port), pf->stat_prev_loaded,
5493                           &prev_ps->rx_size_1023, &cur_ps->rx_size_1023);
5494
5495         ice_stat_update40(hw, GLPRT_PRC1522L(port), pf->stat_prev_loaded,
5496                           &prev_ps->rx_size_1522, &cur_ps->rx_size_1522);
5497
5498         ice_stat_update40(hw, GLPRT_PRC9522L(port), pf->stat_prev_loaded,
5499                           &prev_ps->rx_size_big, &cur_ps->rx_size_big);
5500
5501         ice_stat_update40(hw, GLPRT_PTC64L(port), pf->stat_prev_loaded,
5502                           &prev_ps->tx_size_64, &cur_ps->tx_size_64);
5503
5504         ice_stat_update40(hw, GLPRT_PTC127L(port), pf->stat_prev_loaded,
5505                           &prev_ps->tx_size_127, &cur_ps->tx_size_127);
5506
5507         ice_stat_update40(hw, GLPRT_PTC255L(port), pf->stat_prev_loaded,
5508                           &prev_ps->tx_size_255, &cur_ps->tx_size_255);
5509
5510         ice_stat_update40(hw, GLPRT_PTC511L(port), pf->stat_prev_loaded,
5511                           &prev_ps->tx_size_511, &cur_ps->tx_size_511);
5512
5513         ice_stat_update40(hw, GLPRT_PTC1023L(port), pf->stat_prev_loaded,
5514                           &prev_ps->tx_size_1023, &cur_ps->tx_size_1023);
5515
5516         ice_stat_update40(hw, GLPRT_PTC1522L(port), pf->stat_prev_loaded,
5517                           &prev_ps->tx_size_1522, &cur_ps->tx_size_1522);
5518
5519         ice_stat_update40(hw, GLPRT_PTC9522L(port), pf->stat_prev_loaded,
5520                           &prev_ps->tx_size_big, &cur_ps->tx_size_big);
5521
5522         fd_ctr_base = hw->fd_ctr_base;
5523
5524         ice_stat_update40(hw,
5525                           GLSTAT_FD_CNT0L(ICE_FD_SB_STAT_IDX(fd_ctr_base)),
5526                           pf->stat_prev_loaded, &prev_ps->fd_sb_match,
5527                           &cur_ps->fd_sb_match);
5528         ice_stat_update32(hw, GLPRT_LXONRXC(port), pf->stat_prev_loaded,
5529                           &prev_ps->link_xon_rx, &cur_ps->link_xon_rx);
5530
5531         ice_stat_update32(hw, GLPRT_LXOFFRXC(port), pf->stat_prev_loaded,
5532                           &prev_ps->link_xoff_rx, &cur_ps->link_xoff_rx);
5533
5534         ice_stat_update32(hw, GLPRT_LXONTXC(port), pf->stat_prev_loaded,
5535                           &prev_ps->link_xon_tx, &cur_ps->link_xon_tx);
5536
5537         ice_stat_update32(hw, GLPRT_LXOFFTXC(port), pf->stat_prev_loaded,
5538                           &prev_ps->link_xoff_tx, &cur_ps->link_xoff_tx);
5539
5540         ice_update_dcb_stats(pf);
5541
5542         ice_stat_update32(hw, GLPRT_CRCERRS(port), pf->stat_prev_loaded,
5543                           &prev_ps->crc_errors, &cur_ps->crc_errors);
5544
5545         ice_stat_update32(hw, GLPRT_ILLERRC(port), pf->stat_prev_loaded,
5546                           &prev_ps->illegal_bytes, &cur_ps->illegal_bytes);
5547
5548         ice_stat_update32(hw, GLPRT_MLFC(port), pf->stat_prev_loaded,
5549                           &prev_ps->mac_local_faults,
5550                           &cur_ps->mac_local_faults);
5551
5552         ice_stat_update32(hw, GLPRT_MRFC(port), pf->stat_prev_loaded,
5553                           &prev_ps->mac_remote_faults,
5554                           &cur_ps->mac_remote_faults);
5555
5556         ice_stat_update32(hw, GLPRT_RLEC(port), pf->stat_prev_loaded,
5557                           &prev_ps->rx_len_errors, &cur_ps->rx_len_errors);
5558
5559         ice_stat_update32(hw, GLPRT_RUC(port), pf->stat_prev_loaded,
5560                           &prev_ps->rx_undersize, &cur_ps->rx_undersize);
5561
5562         ice_stat_update32(hw, GLPRT_RFC(port), pf->stat_prev_loaded,
5563                           &prev_ps->rx_fragments, &cur_ps->rx_fragments);
5564
5565         ice_stat_update32(hw, GLPRT_ROC(port), pf->stat_prev_loaded,
5566                           &prev_ps->rx_oversize, &cur_ps->rx_oversize);
5567
5568         ice_stat_update32(hw, GLPRT_RJC(port), pf->stat_prev_loaded,
5569                           &prev_ps->rx_jabber, &cur_ps->rx_jabber);
5570
5571         cur_ps->fd_sb_status = test_bit(ICE_FLAG_FD_ENA, pf->flags) ? 1 : 0;
5572
5573         pf->stat_prev_loaded = true;
5574 }
5575
5576 /**
5577  * ice_get_stats64 - get statistics for network device structure
5578  * @netdev: network interface device structure
5579  * @stats: main device statistics structure
5580  */
5581 static
5582 void ice_get_stats64(struct net_device *netdev, struct rtnl_link_stats64 *stats)
5583 {
5584         struct ice_netdev_priv *np = netdev_priv(netdev);
5585         struct rtnl_link_stats64 *vsi_stats;
5586         struct ice_vsi *vsi = np->vsi;
5587
5588         vsi_stats = &vsi->net_stats;
5589
5590         if (!vsi->num_txq || !vsi->num_rxq)
5591                 return;
5592
5593         /* netdev packet/byte stats come from ring counter. These are obtained
5594          * by summing up ring counters (done by ice_update_vsi_ring_stats).
5595          * But, only call the update routine and read the registers if VSI is
5596          * not down.
5597          */
5598         if (!test_bit(__ICE_DOWN, vsi->state))
5599                 ice_update_vsi_ring_stats(vsi);
5600         stats->tx_packets = vsi_stats->tx_packets;
5601         stats->tx_bytes = vsi_stats->tx_bytes;
5602         stats->rx_packets = vsi_stats->rx_packets;
5603         stats->rx_bytes = vsi_stats->rx_bytes;
5604
5605         /* The rest of the stats can be read from the hardware but instead we
5606          * just return values that the watchdog task has already obtained from
5607          * the hardware.
5608          */
5609         stats->multicast = vsi_stats->multicast;
5610         stats->tx_errors = vsi_stats->tx_errors;
5611         stats->tx_dropped = vsi_stats->tx_dropped;
5612         stats->rx_errors = vsi_stats->rx_errors;
5613         stats->rx_dropped = vsi_stats->rx_dropped;
5614         stats->rx_crc_errors = vsi_stats->rx_crc_errors;
5615         stats->rx_length_errors = vsi_stats->rx_length_errors;
5616 }
5617
5618 /**
5619  * ice_napi_disable_all - Disable NAPI for all q_vectors in the VSI
5620  * @vsi: VSI having NAPI disabled
5621  */
5622 static void ice_napi_disable_all(struct ice_vsi *vsi)
5623 {
5624         int q_idx;
5625
5626         if (!vsi->netdev)
5627                 return;
5628
5629         ice_for_each_q_vector(vsi, q_idx) {
5630                 struct ice_q_vector *q_vector = vsi->q_vectors[q_idx];
5631
5632                 if (q_vector->rx.ring || q_vector->tx.ring)
5633                         napi_disable(&q_vector->napi);
5634         }
5635 }
5636
5637 /**
5638  * ice_down - Shutdown the connection
5639  * @vsi: The VSI being stopped
5640  */
5641 int ice_down(struct ice_vsi *vsi)
5642 {
5643         int i, tx_err, rx_err, link_err = 0;
5644
5645         /* Caller of this function is expected to set the
5646          * vsi->state __ICE_DOWN bit
5647          */
5648         if (vsi->netdev) {
5649                 netif_carrier_off(vsi->netdev);
5650                 netif_tx_disable(vsi->netdev);
5651         }
5652
5653         ice_vsi_dis_irq(vsi);
5654
5655         tx_err = ice_vsi_stop_lan_tx_rings(vsi, ICE_NO_RESET, 0);
5656         if (tx_err)
5657                 netdev_err(vsi->netdev, "Failed stop Tx rings, VSI %d error %d\n",
5658                            vsi->vsi_num, tx_err);
5659         if (!tx_err && ice_is_xdp_ena_vsi(vsi)) {
5660                 tx_err = ice_vsi_stop_xdp_tx_rings(vsi);
5661                 if (tx_err)
5662                         netdev_err(vsi->netdev, "Failed stop XDP rings, VSI %d error %d\n",
5663                                    vsi->vsi_num, tx_err);
5664         }
5665
5666         rx_err = ice_vsi_stop_all_rx_rings(vsi);
5667         if (rx_err)
5668                 netdev_err(vsi->netdev, "Failed stop Rx rings, VSI %d error %d\n",
5669                            vsi->vsi_num, rx_err);
5670
5671         ice_napi_disable_all(vsi);
5672
5673         if (test_bit(ICE_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags)) {
5674                 link_err = ice_force_phys_link_state(vsi, false);
5675                 if (link_err)
5676                         netdev_err(vsi->netdev, "Failed to set physical link down, VSI %d error %d\n",
5677                                    vsi->vsi_num, link_err);
5678         }
5679
5680         ice_for_each_txq(vsi, i)
5681                 ice_clean_tx_ring(vsi->tx_rings[i]);
5682
5683         ice_for_each_rxq(vsi, i)
5684                 ice_clean_rx_ring(vsi->rx_rings[i]);
5685
5686         if (tx_err || rx_err || link_err) {
5687                 netdev_err(vsi->netdev, "Failed to close VSI 0x%04X on switch 0x%04X\n",
5688                            vsi->vsi_num, vsi->vsw->sw_id);
5689                 return -EIO;
5690         }
5691
5692         return 0;
5693 }
5694
5695 /**
5696  * ice_vsi_setup_tx_rings - Allocate VSI Tx queue resources
5697  * @vsi: VSI having resources allocated
5698  *
5699  * Return 0 on success, negative on failure
5700  */
5701 int ice_vsi_setup_tx_rings(struct ice_vsi *vsi)
5702 {
5703         int i, err = 0;
5704
5705         if (!vsi->num_txq) {
5706                 dev_err(ice_pf_to_dev(vsi->back), "VSI %d has 0 Tx queues\n",
5707                         vsi->vsi_num);
5708                 return -EINVAL;
5709         }
5710
5711         ice_for_each_txq(vsi, i) {
5712                 struct ice_ring *ring = vsi->tx_rings[i];
5713
5714                 if (!ring)
5715                         return -EINVAL;
5716
5717                 ring->netdev = vsi->netdev;
5718                 err = ice_setup_tx_ring(ring);
5719                 if (err)
5720                         break;
5721         }
5722
5723         return err;
5724 }
5725
5726 /**
5727  * ice_vsi_setup_rx_rings - Allocate VSI Rx queue resources
5728  * @vsi: VSI having resources allocated
5729  *
5730  * Return 0 on success, negative on failure
5731  */
5732 int ice_vsi_setup_rx_rings(struct ice_vsi *vsi)
5733 {
5734         int i, err = 0;
5735
5736         if (!vsi->num_rxq) {
5737                 dev_err(ice_pf_to_dev(vsi->back), "VSI %d has 0 Rx queues\n",
5738                         vsi->vsi_num);
5739                 return -EINVAL;
5740         }
5741
5742         ice_for_each_rxq(vsi, i) {
5743                 struct ice_ring *ring = vsi->rx_rings[i];
5744
5745                 if (!ring)
5746                         return -EINVAL;
5747
5748                 ring->netdev = vsi->netdev;
5749                 err = ice_setup_rx_ring(ring);
5750                 if (err)
5751                         break;
5752         }
5753
5754         return err;
5755 }
5756
5757 /**
5758  * ice_vsi_open_ctrl - open control VSI for use
5759  * @vsi: the VSI to open
5760  *
5761  * Initialization of the Control VSI
5762  *
5763  * Returns 0 on success, negative value on error
5764  */
5765 int ice_vsi_open_ctrl(struct ice_vsi *vsi)
5766 {
5767         char int_name[ICE_INT_NAME_STR_LEN];
5768         struct ice_pf *pf = vsi->back;
5769         struct device *dev;
5770         int err;
5771
5772         dev = ice_pf_to_dev(pf);
5773         /* allocate descriptors */
5774         err = ice_vsi_setup_tx_rings(vsi);
5775         if (err)
5776                 goto err_setup_tx;
5777
5778         err = ice_vsi_setup_rx_rings(vsi);
5779         if (err)
5780                 goto err_setup_rx;
5781
5782         err = ice_vsi_cfg(vsi);
5783         if (err)
5784                 goto err_setup_rx;
5785
5786         snprintf(int_name, sizeof(int_name) - 1, "%s-%s:ctrl",
5787                  dev_driver_string(dev), dev_name(dev));
5788         err = ice_vsi_req_irq_msix(vsi, int_name);
5789         if (err)
5790                 goto err_setup_rx;
5791
5792         ice_vsi_cfg_msix(vsi);
5793
5794         err = ice_vsi_start_all_rx_rings(vsi);
5795         if (err)
5796                 goto err_up_complete;
5797
5798         clear_bit(__ICE_DOWN, vsi->state);
5799         ice_vsi_ena_irq(vsi);
5800
5801         return 0;
5802
5803 err_up_complete:
5804         ice_down(vsi);
5805 err_setup_rx:
5806         ice_vsi_free_rx_rings(vsi);
5807 err_setup_tx:
5808         ice_vsi_free_tx_rings(vsi);
5809
5810         return err;
5811 }
5812
5813 /**
5814  * ice_vsi_open - Called when a network interface is made active
5815  * @vsi: the VSI to open
5816  *
5817  * Initialization of the VSI
5818  *
5819  * Returns 0 on success, negative value on error
5820  */
5821 static int ice_vsi_open(struct ice_vsi *vsi)
5822 {
5823         char int_name[ICE_INT_NAME_STR_LEN];
5824         struct ice_pf *pf = vsi->back;
5825         int err;
5826
5827         /* allocate descriptors */
5828         err = ice_vsi_setup_tx_rings(vsi);
5829         if (err)
5830                 goto err_setup_tx;
5831
5832         err = ice_vsi_setup_rx_rings(vsi);
5833         if (err)
5834                 goto err_setup_rx;
5835
5836         err = ice_vsi_cfg(vsi);
5837         if (err)
5838                 goto err_setup_rx;
5839
5840         snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
5841                  dev_driver_string(ice_pf_to_dev(pf)), vsi->netdev->name);
5842         err = ice_vsi_req_irq_msix(vsi, int_name);
5843         if (err)
5844                 goto err_setup_rx;
5845
5846         /* Notify the stack of the actual queue counts. */
5847         err = netif_set_real_num_tx_queues(vsi->netdev, vsi->num_txq);
5848         if (err)
5849                 goto err_set_qs;
5850
5851         err = netif_set_real_num_rx_queues(vsi->netdev, vsi->num_rxq);
5852         if (err)
5853                 goto err_set_qs;
5854
5855         err = ice_up_complete(vsi);
5856         if (err)
5857                 goto err_up_complete;
5858
5859         return 0;
5860
5861 err_up_complete:
5862         ice_down(vsi);
5863 err_set_qs:
5864         ice_vsi_free_irq(vsi);
5865 err_setup_rx:
5866         ice_vsi_free_rx_rings(vsi);
5867 err_setup_tx:
5868         ice_vsi_free_tx_rings(vsi);
5869
5870         return err;
5871 }
5872
5873 /**
5874  * ice_vsi_release_all - Delete all VSIs
5875  * @pf: PF from which all VSIs are being removed
5876  */
5877 static void ice_vsi_release_all(struct ice_pf *pf)
5878 {
5879         int err, i;
5880
5881         if (!pf->vsi)
5882                 return;
5883
5884         ice_for_each_vsi(pf, i) {
5885                 if (!pf->vsi[i])
5886                         continue;
5887
5888                 err = ice_vsi_release(pf->vsi[i]);
5889                 if (err)
5890                         dev_dbg(ice_pf_to_dev(pf), "Failed to release pf->vsi[%d], err %d, vsi_num = %d\n",
5891                                 i, err, pf->vsi[i]->vsi_num);
5892         }
5893 }
5894
5895 /**
5896  * ice_vsi_rebuild_by_type - Rebuild VSI of a given type
5897  * @pf: pointer to the PF instance
5898  * @type: VSI type to rebuild
5899  *
5900  * Iterates through the pf->vsi array and rebuilds VSIs of the requested type
5901  */
5902 static int ice_vsi_rebuild_by_type(struct ice_pf *pf, enum ice_vsi_type type)
5903 {
5904         struct device *dev = ice_pf_to_dev(pf);
5905         enum ice_status status;
5906         int i, err;
5907
5908         ice_for_each_vsi(pf, i) {
5909                 struct ice_vsi *vsi = pf->vsi[i];
5910
5911                 if (!vsi || vsi->type != type)
5912                         continue;
5913
5914                 /* rebuild the VSI */
5915                 err = ice_vsi_rebuild(vsi, true);
5916                 if (err) {
5917                         dev_err(dev, "rebuild VSI failed, err %d, VSI index %d, type %s\n",
5918                                 err, vsi->idx, ice_vsi_type_str(type));
5919                         return err;
5920                 }
5921
5922                 /* replay filters for the VSI */
5923                 status = ice_replay_vsi(&pf->hw, vsi->idx);
5924                 if (status) {
5925                         dev_err(dev, "replay VSI failed, status %s, VSI index %d, type %s\n",
5926                                 ice_stat_str(status), vsi->idx,
5927                                 ice_vsi_type_str(type));
5928                         return -EIO;
5929                 }
5930
5931                 /* Re-map HW VSI number, using VSI handle that has been
5932                  * previously validated in ice_replay_vsi() call above
5933                  */
5934                 vsi->vsi_num = ice_get_hw_vsi_num(&pf->hw, vsi->idx);
5935
5936                 /* enable the VSI */
5937                 err = ice_ena_vsi(vsi, false);
5938                 if (err) {
5939                         dev_err(dev, "enable VSI failed, err %d, VSI index %d, type %s\n",
5940                                 err, vsi->idx, ice_vsi_type_str(type));
5941                         return err;
5942                 }
5943
5944                 dev_info(dev, "VSI rebuilt. VSI index %d, type %s\n", vsi->idx,
5945                          ice_vsi_type_str(type));
5946         }
5947
5948         return 0;
5949 }
5950
5951 /**
5952  * ice_update_pf_netdev_link - Update PF netdev link status
5953  * @pf: pointer to the PF instance
5954  */
5955 static void ice_update_pf_netdev_link(struct ice_pf *pf)
5956 {
5957         bool link_up;
5958         int i;
5959
5960         ice_for_each_vsi(pf, i) {
5961                 struct ice_vsi *vsi = pf->vsi[i];
5962
5963                 if (!vsi || vsi->type != ICE_VSI_PF)
5964                         return;
5965
5966                 ice_get_link_status(pf->vsi[i]->port_info, &link_up);
5967                 if (link_up) {
5968                         netif_carrier_on(pf->vsi[i]->netdev);
5969                         netif_tx_wake_all_queues(pf->vsi[i]->netdev);
5970                 } else {
5971                         netif_carrier_off(pf->vsi[i]->netdev);
5972                         netif_tx_stop_all_queues(pf->vsi[i]->netdev);
5973                 }
5974         }
5975 }
5976
5977 /**
5978  * ice_rebuild - rebuild after reset
5979  * @pf: PF to rebuild
5980  * @reset_type: type of reset
5981  *
5982  * Do not rebuild VF VSI in this flow because that is already handled via
5983  * ice_reset_all_vfs(). This is because requirements for resetting a VF after a
5984  * PFR/CORER/GLOBER/etc. are different than the normal flow. Also, we don't want
5985  * to reset/rebuild all the VF VSI twice.
5986  */
5987 static void ice_rebuild(struct ice_pf *pf, enum ice_reset_req reset_type)
5988 {
5989         struct device *dev = ice_pf_to_dev(pf);
5990         struct ice_hw *hw = &pf->hw;
5991         enum ice_status ret;
5992         int err;
5993
5994         if (test_bit(__ICE_DOWN, pf->state))
5995                 goto clear_recovery;
5996
5997         dev_dbg(dev, "rebuilding PF after reset_type=%d\n", reset_type);
5998
5999         ret = ice_init_all_ctrlq(hw);
6000         if (ret) {
6001                 dev_err(dev, "control queues init failed %s\n",
6002                         ice_stat_str(ret));
6003                 goto err_init_ctrlq;
6004         }
6005
6006         /* if DDP was previously loaded successfully */
6007         if (!ice_is_safe_mode(pf)) {
6008                 /* reload the SW DB of filter tables */
6009                 if (reset_type == ICE_RESET_PFR)
6010                         ice_fill_blk_tbls(hw);
6011                 else
6012                         /* Reload DDP Package after CORER/GLOBR reset */
6013                         ice_load_pkg(NULL, pf);
6014         }
6015
6016         ret = ice_clear_pf_cfg(hw);
6017         if (ret) {
6018                 dev_err(dev, "clear PF configuration failed %s\n",
6019                         ice_stat_str(ret));
6020                 goto err_init_ctrlq;
6021         }
6022
6023         if (pf->first_sw->dflt_vsi_ena)
6024                 dev_info(dev, "Clearing default VSI, re-enable after reset completes\n");
6025         /* clear the default VSI configuration if it exists */
6026         pf->first_sw->dflt_vsi = NULL;
6027         pf->first_sw->dflt_vsi_ena = false;
6028
6029         ice_clear_pxe_mode(hw);
6030
6031         ret = ice_get_caps(hw);
6032         if (ret) {
6033                 dev_err(dev, "ice_get_caps failed %s\n", ice_stat_str(ret));
6034                 goto err_init_ctrlq;
6035         }
6036
6037         ret = ice_aq_set_mac_cfg(hw, ICE_AQ_SET_MAC_FRAME_SIZE_MAX, NULL);
6038         if (ret) {
6039                 dev_err(dev, "set_mac_cfg failed %s\n", ice_stat_str(ret));
6040                 goto err_init_ctrlq;
6041         }
6042
6043         err = ice_sched_init_port(hw->port_info);
6044         if (err)
6045                 goto err_sched_init_port;
6046
6047         /* start misc vector */
6048         err = ice_req_irq_msix_misc(pf);
6049         if (err) {
6050                 dev_err(dev, "misc vector setup failed: %d\n", err);
6051                 goto err_sched_init_port;
6052         }
6053
6054         if (test_bit(ICE_FLAG_FD_ENA, pf->flags)) {
6055                 wr32(hw, PFQF_FD_ENA, PFQF_FD_ENA_FD_ENA_M);
6056                 if (!rd32(hw, PFQF_FD_SIZE)) {
6057                         u16 unused, guar, b_effort;
6058
6059                         guar = hw->func_caps.fd_fltr_guar;
6060                         b_effort = hw->func_caps.fd_fltr_best_effort;
6061
6062                         /* force guaranteed filter pool for PF */
6063                         ice_alloc_fd_guar_item(hw, &unused, guar);
6064                         /* force shared filter pool for PF */
6065                         ice_alloc_fd_shrd_item(hw, &unused, b_effort);
6066                 }
6067         }
6068
6069         if (test_bit(ICE_FLAG_DCB_ENA, pf->flags))
6070                 ice_dcb_rebuild(pf);
6071
6072         /* rebuild PF VSI */
6073         err = ice_vsi_rebuild_by_type(pf, ICE_VSI_PF);
6074         if (err) {
6075                 dev_err(dev, "PF VSI rebuild failed: %d\n", err);
6076                 goto err_vsi_rebuild;
6077         }
6078
6079         /* If Flow Director is active */
6080         if (test_bit(ICE_FLAG_FD_ENA, pf->flags)) {
6081                 err = ice_vsi_rebuild_by_type(pf, ICE_VSI_CTRL);
6082                 if (err) {
6083                         dev_err(dev, "control VSI rebuild failed: %d\n", err);
6084                         goto err_vsi_rebuild;
6085                 }
6086
6087                 /* replay HW Flow Director recipes */
6088                 if (hw->fdir_prof)
6089                         ice_fdir_replay_flows(hw);
6090
6091                 /* replay Flow Director filters */
6092                 ice_fdir_replay_fltrs(pf);
6093
6094                 ice_rebuild_arfs(pf);
6095         }
6096
6097         ice_update_pf_netdev_link(pf);
6098
6099         /* tell the firmware we are up */
6100         ret = ice_send_version(pf);
6101         if (ret) {
6102                 dev_err(dev, "Rebuild failed due to error sending driver version: %s\n",
6103                         ice_stat_str(ret));
6104                 goto err_vsi_rebuild;
6105         }
6106
6107         ice_replay_post(hw);
6108
6109         /* if we get here, reset flow is successful */
6110         clear_bit(__ICE_RESET_FAILED, pf->state);
6111         return;
6112
6113 err_vsi_rebuild:
6114 err_sched_init_port:
6115         ice_sched_cleanup_all(hw);
6116 err_init_ctrlq:
6117         ice_shutdown_all_ctrlq(hw);
6118         set_bit(__ICE_RESET_FAILED, pf->state);
6119 clear_recovery:
6120         /* set this bit in PF state to control service task scheduling */
6121         set_bit(__ICE_NEEDS_RESTART, pf->state);
6122         dev_err(dev, "Rebuild failed, unload and reload driver\n");
6123 }
6124
6125 /**
6126  * ice_max_xdp_frame_size - returns the maximum allowed frame size for XDP
6127  * @vsi: Pointer to VSI structure
6128  */
6129 static int ice_max_xdp_frame_size(struct ice_vsi *vsi)
6130 {
6131         if (PAGE_SIZE >= 8192 || test_bit(ICE_FLAG_LEGACY_RX, vsi->back->flags))
6132                 return ICE_RXBUF_2048 - XDP_PACKET_HEADROOM;
6133         else
6134                 return ICE_RXBUF_3072;
6135 }
6136
6137 /**
6138  * ice_change_mtu - NDO callback to change the MTU
6139  * @netdev: network interface device structure
6140  * @new_mtu: new value for maximum frame size
6141  *
6142  * Returns 0 on success, negative on failure
6143  */
6144 static int ice_change_mtu(struct net_device *netdev, int new_mtu)
6145 {
6146         struct ice_netdev_priv *np = netdev_priv(netdev);
6147         struct ice_vsi *vsi = np->vsi;
6148         struct ice_pf *pf = vsi->back;
6149         u8 count = 0;
6150
6151         if (new_mtu == (int)netdev->mtu) {
6152                 netdev_warn(netdev, "MTU is already %u\n", netdev->mtu);
6153                 return 0;
6154         }
6155
6156         if (ice_is_xdp_ena_vsi(vsi)) {
6157                 int frame_size = ice_max_xdp_frame_size(vsi);
6158
6159                 if (new_mtu + ICE_ETH_PKT_HDR_PAD > frame_size) {
6160                         netdev_err(netdev, "max MTU for XDP usage is %d\n",
6161                                    frame_size - ICE_ETH_PKT_HDR_PAD);
6162                         return -EINVAL;
6163                 }
6164         }
6165
6166         /* if a reset is in progress, wait for some time for it to complete */
6167         do {
6168                 if (ice_is_reset_in_progress(pf->state)) {
6169                         count++;
6170                         usleep_range(1000, 2000);
6171                 } else {
6172                         break;
6173                 }
6174
6175         } while (count < 100);
6176
6177         if (count == 100) {
6178                 netdev_err(netdev, "can't change MTU. Device is busy\n");
6179                 return -EBUSY;
6180         }
6181
6182         netdev->mtu = (unsigned int)new_mtu;
6183
6184         /* if VSI is up, bring it down and then back up */
6185         if (!test_and_set_bit(__ICE_DOWN, vsi->state)) {
6186                 int err;
6187
6188                 err = ice_down(vsi);
6189                 if (err) {
6190                         netdev_err(netdev, "change MTU if_down err %d\n", err);
6191                         return err;
6192                 }
6193
6194                 err = ice_up(vsi);
6195                 if (err) {
6196                         netdev_err(netdev, "change MTU if_up err %d\n", err);
6197                         return err;
6198                 }
6199         }
6200
6201         netdev_dbg(netdev, "changed MTU to %d\n", new_mtu);
6202         return 0;
6203 }
6204
6205 /**
6206  * ice_aq_str - convert AQ err code to a string
6207  * @aq_err: the AQ error code to convert
6208  */
6209 const char *ice_aq_str(enum ice_aq_err aq_err)
6210 {
6211         switch (aq_err) {
6212         case ICE_AQ_RC_OK:
6213                 return "OK";
6214         case ICE_AQ_RC_EPERM:
6215                 return "ICE_AQ_RC_EPERM";
6216         case ICE_AQ_RC_ENOENT:
6217                 return "ICE_AQ_RC_ENOENT";
6218         case ICE_AQ_RC_ENOMEM:
6219                 return "ICE_AQ_RC_ENOMEM";
6220         case ICE_AQ_RC_EBUSY:
6221                 return "ICE_AQ_RC_EBUSY";
6222         case ICE_AQ_RC_EEXIST:
6223                 return "ICE_AQ_RC_EEXIST";
6224         case ICE_AQ_RC_EINVAL:
6225                 return "ICE_AQ_RC_EINVAL";
6226         case ICE_AQ_RC_ENOSPC:
6227                 return "ICE_AQ_RC_ENOSPC";
6228         case ICE_AQ_RC_ENOSYS:
6229                 return "ICE_AQ_RC_ENOSYS";
6230         case ICE_AQ_RC_EMODE:
6231                 return "ICE_AQ_RC_EMODE";
6232         case ICE_AQ_RC_ENOSEC:
6233                 return "ICE_AQ_RC_ENOSEC";
6234         case ICE_AQ_RC_EBADSIG:
6235                 return "ICE_AQ_RC_EBADSIG";
6236         case ICE_AQ_RC_ESVN:
6237                 return "ICE_AQ_RC_ESVN";
6238         case ICE_AQ_RC_EBADMAN:
6239                 return "ICE_AQ_RC_EBADMAN";
6240         case ICE_AQ_RC_EBADBUF:
6241                 return "ICE_AQ_RC_EBADBUF";
6242         }
6243
6244         return "ICE_AQ_RC_UNKNOWN";
6245 }
6246
6247 /**
6248  * ice_stat_str - convert status err code to a string
6249  * @stat_err: the status error code to convert
6250  */
6251 const char *ice_stat_str(enum ice_status stat_err)
6252 {
6253         switch (stat_err) {
6254         case ICE_SUCCESS:
6255                 return "OK";
6256         case ICE_ERR_PARAM:
6257                 return "ICE_ERR_PARAM";
6258         case ICE_ERR_NOT_IMPL:
6259                 return "ICE_ERR_NOT_IMPL";
6260         case ICE_ERR_NOT_READY:
6261                 return "ICE_ERR_NOT_READY";
6262         case ICE_ERR_NOT_SUPPORTED:
6263                 return "ICE_ERR_NOT_SUPPORTED";
6264         case ICE_ERR_BAD_PTR:
6265                 return "ICE_ERR_BAD_PTR";
6266         case ICE_ERR_INVAL_SIZE:
6267                 return "ICE_ERR_INVAL_SIZE";
6268         case ICE_ERR_DEVICE_NOT_SUPPORTED:
6269                 return "ICE_ERR_DEVICE_NOT_SUPPORTED";
6270         case ICE_ERR_RESET_FAILED:
6271                 return "ICE_ERR_RESET_FAILED";
6272         case ICE_ERR_FW_API_VER:
6273                 return "ICE_ERR_FW_API_VER";
6274         case ICE_ERR_NO_MEMORY:
6275                 return "ICE_ERR_NO_MEMORY";
6276         case ICE_ERR_CFG:
6277                 return "ICE_ERR_CFG";
6278         case ICE_ERR_OUT_OF_RANGE:
6279                 return "ICE_ERR_OUT_OF_RANGE";
6280         case ICE_ERR_ALREADY_EXISTS:
6281                 return "ICE_ERR_ALREADY_EXISTS";
6282         case ICE_ERR_NVM:
6283                 return "ICE_ERR_NVM";
6284         case ICE_ERR_NVM_CHECKSUM:
6285                 return "ICE_ERR_NVM_CHECKSUM";
6286         case ICE_ERR_BUF_TOO_SHORT:
6287                 return "ICE_ERR_BUF_TOO_SHORT";
6288         case ICE_ERR_NVM_BLANK_MODE:
6289                 return "ICE_ERR_NVM_BLANK_MODE";
6290         case ICE_ERR_IN_USE:
6291                 return "ICE_ERR_IN_USE";
6292         case ICE_ERR_MAX_LIMIT:
6293                 return "ICE_ERR_MAX_LIMIT";
6294         case ICE_ERR_RESET_ONGOING:
6295                 return "ICE_ERR_RESET_ONGOING";
6296         case ICE_ERR_HW_TABLE:
6297                 return "ICE_ERR_HW_TABLE";
6298         case ICE_ERR_DOES_NOT_EXIST:
6299                 return "ICE_ERR_DOES_NOT_EXIST";
6300         case ICE_ERR_FW_DDP_MISMATCH:
6301                 return "ICE_ERR_FW_DDP_MISMATCH";
6302         case ICE_ERR_AQ_ERROR:
6303                 return "ICE_ERR_AQ_ERROR";
6304         case ICE_ERR_AQ_TIMEOUT:
6305                 return "ICE_ERR_AQ_TIMEOUT";
6306         case ICE_ERR_AQ_FULL:
6307                 return "ICE_ERR_AQ_FULL";
6308         case ICE_ERR_AQ_NO_WORK:
6309                 return "ICE_ERR_AQ_NO_WORK";
6310         case ICE_ERR_AQ_EMPTY:
6311                 return "ICE_ERR_AQ_EMPTY";
6312         case ICE_ERR_AQ_FW_CRITICAL:
6313                 return "ICE_ERR_AQ_FW_CRITICAL";
6314         }
6315
6316         return "ICE_ERR_UNKNOWN";
6317 }
6318
6319 /**
6320  * ice_set_rss_lut - Set RSS LUT
6321  * @vsi: Pointer to VSI structure
6322  * @lut: Lookup table
6323  * @lut_size: Lookup table size
6324  *
6325  * Returns 0 on success, negative on failure
6326  */
6327 int ice_set_rss_lut(struct ice_vsi *vsi, u8 *lut, u16 lut_size)
6328 {
6329         struct ice_aq_get_set_rss_lut_params params = {};
6330         struct ice_hw *hw = &vsi->back->hw;
6331         enum ice_status status;
6332
6333         if (!lut)
6334                 return -EINVAL;
6335
6336         params.vsi_handle = vsi->idx;
6337         params.lut_size = lut_size;
6338         params.lut_type = vsi->rss_lut_type;
6339         params.lut = lut;
6340
6341         status = ice_aq_set_rss_lut(hw, &params);
6342         if (status) {
6343                 dev_err(ice_pf_to_dev(vsi->back), "Cannot set RSS lut, err %s aq_err %s\n",
6344                         ice_stat_str(status),
6345                         ice_aq_str(hw->adminq.sq_last_status));
6346                 return -EIO;
6347         }
6348
6349         return 0;
6350 }
6351
6352 /**
6353  * ice_set_rss_key - Set RSS key
6354  * @vsi: Pointer to the VSI structure
6355  * @seed: RSS hash seed
6356  *
6357  * Returns 0 on success, negative on failure
6358  */
6359 int ice_set_rss_key(struct ice_vsi *vsi, u8 *seed)
6360 {
6361         struct ice_hw *hw = &vsi->back->hw;
6362         enum ice_status status;
6363
6364         if (!seed)
6365                 return -EINVAL;
6366
6367         status = ice_aq_set_rss_key(hw, vsi->idx, (struct ice_aqc_get_set_rss_keys *)seed);
6368         if (status) {
6369                 dev_err(ice_pf_to_dev(vsi->back), "Cannot set RSS key, err %s aq_err %s\n",
6370                         ice_stat_str(status),
6371                         ice_aq_str(hw->adminq.sq_last_status));
6372                 return -EIO;
6373         }
6374
6375         return 0;
6376 }
6377
6378 /**
6379  * ice_get_rss_lut - Get RSS LUT
6380  * @vsi: Pointer to VSI structure
6381  * @lut: Buffer to store the lookup table entries
6382  * @lut_size: Size of buffer to store the lookup table entries
6383  *
6384  * Returns 0 on success, negative on failure
6385  */
6386 int ice_get_rss_lut(struct ice_vsi *vsi, u8 *lut, u16 lut_size)
6387 {
6388         struct ice_aq_get_set_rss_lut_params params = {};
6389         struct ice_hw *hw = &vsi->back->hw;
6390         enum ice_status status;
6391
6392         if (!lut)
6393                 return -EINVAL;
6394
6395         params.vsi_handle = vsi->idx;
6396         params.lut_size = lut_size;
6397         params.lut_type = vsi->rss_lut_type;
6398         params.lut = lut;
6399
6400         status = ice_aq_get_rss_lut(hw, &params);
6401         if (status) {
6402                 dev_err(ice_pf_to_dev(vsi->back), "Cannot get RSS lut, err %s aq_err %s\n",
6403                         ice_stat_str(status),
6404                         ice_aq_str(hw->adminq.sq_last_status));
6405                 return -EIO;
6406         }
6407
6408         return 0;
6409 }
6410
6411 /**
6412  * ice_get_rss_key - Get RSS key
6413  * @vsi: Pointer to VSI structure
6414  * @seed: Buffer to store the key in
6415  *
6416  * Returns 0 on success, negative on failure
6417  */
6418 int ice_get_rss_key(struct ice_vsi *vsi, u8 *seed)
6419 {
6420         struct ice_hw *hw = &vsi->back->hw;
6421         enum ice_status status;
6422
6423         if (!seed)
6424                 return -EINVAL;
6425
6426         status = ice_aq_get_rss_key(hw, vsi->idx, (struct ice_aqc_get_set_rss_keys *)seed);
6427         if (status) {
6428                 dev_err(ice_pf_to_dev(vsi->back), "Cannot get RSS key, err %s aq_err %s\n",
6429                         ice_stat_str(status),
6430                         ice_aq_str(hw->adminq.sq_last_status));
6431                 return -EIO;
6432         }
6433
6434         return 0;
6435 }
6436
6437 /**
6438  * ice_bridge_getlink - Get the hardware bridge mode
6439  * @skb: skb buff
6440  * @pid: process ID
6441  * @seq: RTNL message seq
6442  * @dev: the netdev being configured
6443  * @filter_mask: filter mask passed in
6444  * @nlflags: netlink flags passed in
6445  *
6446  * Return the bridge mode (VEB/VEPA)
6447  */
6448 static int
6449 ice_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
6450                    struct net_device *dev, u32 filter_mask, int nlflags)
6451 {
6452         struct ice_netdev_priv *np = netdev_priv(dev);
6453         struct ice_vsi *vsi = np->vsi;
6454         struct ice_pf *pf = vsi->back;
6455         u16 bmode;
6456
6457         bmode = pf->first_sw->bridge_mode;
6458
6459         return ndo_dflt_bridge_getlink(skb, pid, seq, dev, bmode, 0, 0, nlflags,
6460                                        filter_mask, NULL);
6461 }
6462
6463 /**
6464  * ice_vsi_update_bridge_mode - Update VSI for switching bridge mode (VEB/VEPA)
6465  * @vsi: Pointer to VSI structure
6466  * @bmode: Hardware bridge mode (VEB/VEPA)
6467  *
6468  * Returns 0 on success, negative on failure
6469  */
6470 static int ice_vsi_update_bridge_mode(struct ice_vsi *vsi, u16 bmode)
6471 {
6472         struct ice_aqc_vsi_props *vsi_props;
6473         struct ice_hw *hw = &vsi->back->hw;
6474         struct ice_vsi_ctx *ctxt;
6475         enum ice_status status;
6476         int ret = 0;
6477
6478         vsi_props = &vsi->info;
6479
6480         ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL);
6481         if (!ctxt)
6482                 return -ENOMEM;
6483
6484         ctxt->info = vsi->info;
6485
6486         if (bmode == BRIDGE_MODE_VEB)
6487                 /* change from VEPA to VEB mode */
6488                 ctxt->info.sw_flags |= ICE_AQ_VSI_SW_FLAG_ALLOW_LB;
6489         else
6490                 /* change from VEB to VEPA mode */
6491                 ctxt->info.sw_flags &= ~ICE_AQ_VSI_SW_FLAG_ALLOW_LB;
6492         ctxt->info.valid_sections = cpu_to_le16(ICE_AQ_VSI_PROP_SW_VALID);
6493
6494         status = ice_update_vsi(hw, vsi->idx, ctxt, NULL);
6495         if (status) {
6496                 dev_err(ice_pf_to_dev(vsi->back), "update VSI for bridge mode failed, bmode = %d err %s aq_err %s\n",
6497                         bmode, ice_stat_str(status),
6498                         ice_aq_str(hw->adminq.sq_last_status));
6499                 ret = -EIO;
6500                 goto out;
6501         }
6502         /* Update sw flags for book keeping */
6503         vsi_props->sw_flags = ctxt->info.sw_flags;
6504
6505 out:
6506         kfree(ctxt);
6507         return ret;
6508 }
6509
6510 /**
6511  * ice_bridge_setlink - Set the hardware bridge mode
6512  * @dev: the netdev being configured
6513  * @nlh: RTNL message
6514  * @flags: bridge setlink flags
6515  * @extack: netlink extended ack
6516  *
6517  * Sets the bridge mode (VEB/VEPA) of the switch to which the netdev (VSI) is
6518  * hooked up to. Iterates through the PF VSI list and sets the loopback mode (if
6519  * not already set for all VSIs connected to this switch. And also update the
6520  * unicast switch filter rules for the corresponding switch of the netdev.
6521  */
6522 static int
6523 ice_bridge_setlink(struct net_device *dev, struct nlmsghdr *nlh,
6524                    u16 __always_unused flags,
6525                    struct netlink_ext_ack __always_unused *extack)
6526 {
6527         struct ice_netdev_priv *np = netdev_priv(dev);
6528         struct ice_pf *pf = np->vsi->back;
6529         struct nlattr *attr, *br_spec;
6530         struct ice_hw *hw = &pf->hw;
6531         enum ice_status status;
6532         struct ice_sw *pf_sw;
6533         int rem, v, err = 0;
6534
6535         pf_sw = pf->first_sw;
6536         /* find the attribute in the netlink message */
6537         br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
6538
6539         nla_for_each_nested(attr, br_spec, rem) {
6540                 __u16 mode;
6541
6542                 if (nla_type(attr) != IFLA_BRIDGE_MODE)
6543                         continue;
6544                 mode = nla_get_u16(attr);
6545                 if (mode != BRIDGE_MODE_VEPA && mode != BRIDGE_MODE_VEB)
6546                         return -EINVAL;
6547                 /* Continue  if bridge mode is not being flipped */
6548                 if (mode == pf_sw->bridge_mode)
6549                         continue;
6550                 /* Iterates through the PF VSI list and update the loopback
6551                  * mode of the VSI
6552                  */
6553                 ice_for_each_vsi(pf, v) {
6554                         if (!pf->vsi[v])
6555                                 continue;
6556                         err = ice_vsi_update_bridge_mode(pf->vsi[v], mode);
6557                         if (err)
6558                                 return err;
6559                 }
6560
6561                 hw->evb_veb = (mode == BRIDGE_MODE_VEB);
6562                 /* Update the unicast switch filter rules for the corresponding
6563                  * switch of the netdev
6564                  */
6565                 status = ice_update_sw_rule_bridge_mode(hw);
6566                 if (status) {
6567                         netdev_err(dev, "switch rule update failed, mode = %d err %s aq_err %s\n",
6568                                    mode, ice_stat_str(status),
6569                                    ice_aq_str(hw->adminq.sq_last_status));
6570                         /* revert hw->evb_veb */
6571                         hw->evb_veb = (pf_sw->bridge_mode == BRIDGE_MODE_VEB);
6572                         return -EIO;
6573                 }
6574
6575                 pf_sw->bridge_mode = mode;
6576         }
6577
6578         return 0;
6579 }
6580
6581 /**
6582  * ice_tx_timeout - Respond to a Tx Hang
6583  * @netdev: network interface device structure
6584  * @txqueue: Tx queue
6585  */
6586 static void ice_tx_timeout(struct net_device *netdev, unsigned int txqueue)
6587 {
6588         struct ice_netdev_priv *np = netdev_priv(netdev);
6589         struct ice_ring *tx_ring = NULL;
6590         struct ice_vsi *vsi = np->vsi;
6591         struct ice_pf *pf = vsi->back;
6592         u32 i;
6593
6594         pf->tx_timeout_count++;
6595
6596         /* Check if PFC is enabled for the TC to which the queue belongs
6597          * to. If yes then Tx timeout is not caused by a hung queue, no
6598          * need to reset and rebuild
6599          */
6600         if (ice_is_pfc_causing_hung_q(pf, txqueue)) {
6601                 dev_info(ice_pf_to_dev(pf), "Fake Tx hang detected on queue %u, timeout caused by PFC storm\n",
6602                          txqueue);
6603                 return;
6604         }
6605
6606         /* now that we have an index, find the tx_ring struct */
6607         for (i = 0; i < vsi->num_txq; i++)
6608                 if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
6609                         if (txqueue == vsi->tx_rings[i]->q_index) {
6610                                 tx_ring = vsi->tx_rings[i];
6611                                 break;
6612                         }
6613
6614         /* Reset recovery level if enough time has elapsed after last timeout.
6615          * Also ensure no new reset action happens before next timeout period.
6616          */
6617         if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ * 20)))
6618                 pf->tx_timeout_recovery_level = 1;
6619         else if (time_before(jiffies, (pf->tx_timeout_last_recovery +
6620                                        netdev->watchdog_timeo)))
6621                 return;
6622
6623         if (tx_ring) {
6624                 struct ice_hw *hw = &pf->hw;
6625                 u32 head, val = 0;
6626
6627                 head = (rd32(hw, QTX_COMM_HEAD(vsi->txq_map[txqueue])) &
6628                         QTX_COMM_HEAD_HEAD_M) >> QTX_COMM_HEAD_HEAD_S;
6629                 /* Read interrupt register */
6630                 val = rd32(hw, GLINT_DYN_CTL(tx_ring->q_vector->reg_idx));
6631
6632                 netdev_info(netdev, "tx_timeout: VSI_num: %d, Q %u, NTC: 0x%x, HW_HEAD: 0x%x, NTU: 0x%x, INT: 0x%x\n",
6633                             vsi->vsi_num, txqueue, tx_ring->next_to_clean,
6634                             head, tx_ring->next_to_use, val);
6635         }
6636
6637         pf->tx_timeout_last_recovery = jiffies;
6638         netdev_info(netdev, "tx_timeout recovery level %d, txqueue %u\n",
6639                     pf->tx_timeout_recovery_level, txqueue);
6640
6641         switch (pf->tx_timeout_recovery_level) {
6642         case 1:
6643                 set_bit(__ICE_PFR_REQ, pf->state);
6644                 break;
6645         case 2:
6646                 set_bit(__ICE_CORER_REQ, pf->state);
6647                 break;
6648         case 3:
6649                 set_bit(__ICE_GLOBR_REQ, pf->state);
6650                 break;
6651         default:
6652                 netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in unrecoverable state.\n");
6653                 set_bit(__ICE_DOWN, pf->state);
6654                 set_bit(__ICE_NEEDS_RESTART, vsi->state);
6655                 set_bit(__ICE_SERVICE_DIS, pf->state);
6656                 break;
6657         }
6658
6659         ice_service_task_schedule(pf);
6660         pf->tx_timeout_recovery_level++;
6661 }
6662
6663 /**
6664  * ice_open - Called when a network interface becomes active
6665  * @netdev: network interface device structure
6666  *
6667  * The open entry point is called when a network interface is made
6668  * active by the system (IFF_UP). At this point all resources needed
6669  * for transmit and receive operations are allocated, the interrupt
6670  * handler is registered with the OS, the netdev watchdog is enabled,
6671  * and the stack is notified that the interface is ready.
6672  *
6673  * Returns 0 on success, negative value on failure
6674  */
6675 int ice_open(struct net_device *netdev)
6676 {
6677         struct ice_netdev_priv *np = netdev_priv(netdev);
6678         struct ice_vsi *vsi = np->vsi;
6679         struct ice_pf *pf = vsi->back;
6680         struct ice_port_info *pi;
6681         int err;
6682
6683         if (test_bit(__ICE_NEEDS_RESTART, pf->state)) {
6684                 netdev_err(netdev, "driver needs to be unloaded and reloaded\n");
6685                 return -EIO;
6686         }
6687
6688         netif_carrier_off(netdev);
6689
6690         pi = vsi->port_info;
6691         err = ice_update_link_info(pi);
6692         if (err) {
6693                 netdev_err(netdev, "Failed to get link info, error %d\n",
6694                            err);
6695                 return err;
6696         }
6697
6698         /* Set PHY if there is media, otherwise, turn off PHY */
6699         if (pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE) {
6700                 clear_bit(ICE_FLAG_NO_MEDIA, pf->flags);
6701                 if (!test_bit(__ICE_PHY_INIT_COMPLETE, pf->state)) {
6702                         err = ice_init_phy_user_cfg(pi);
6703                         if (err) {
6704                                 netdev_err(netdev, "Failed to initialize PHY settings, error %d\n",
6705                                            err);
6706                                 return err;
6707                         }
6708                 }
6709
6710                 err = ice_configure_phy(vsi);
6711                 if (err) {
6712                         netdev_err(netdev, "Failed to set physical link up, error %d\n",
6713                                    err);
6714                         return err;
6715                 }
6716         } else {
6717                 set_bit(ICE_FLAG_NO_MEDIA, pf->flags);
6718                 err = ice_aq_set_link_restart_an(pi, false, NULL);
6719                 if (err) {
6720                         netdev_err(netdev, "Failed to set PHY state, VSI %d error %d\n",
6721                                    vsi->vsi_num, err);
6722                         return err;
6723                 }
6724         }
6725
6726         err = ice_vsi_open(vsi);
6727         if (err)
6728                 netdev_err(netdev, "Failed to open VSI 0x%04X on switch 0x%04X\n",
6729                            vsi->vsi_num, vsi->vsw->sw_id);
6730
6731         /* Update existing tunnels information */
6732         udp_tunnel_get_rx_info(netdev);
6733
6734         return err;
6735 }
6736
6737 /**
6738  * ice_stop - Disables a network interface
6739  * @netdev: network interface device structure
6740  *
6741  * The stop entry point is called when an interface is de-activated by the OS,
6742  * and the netdevice enters the DOWN state. The hardware is still under the
6743  * driver's control, but the netdev interface is disabled.
6744  *
6745  * Returns success only - not allowed to fail
6746  */
6747 int ice_stop(struct net_device *netdev)
6748 {
6749         struct ice_netdev_priv *np = netdev_priv(netdev);
6750         struct ice_vsi *vsi = np->vsi;
6751
6752         ice_vsi_close(vsi);
6753
6754         return 0;
6755 }
6756
6757 /**
6758  * ice_features_check - Validate encapsulated packet conforms to limits
6759  * @skb: skb buffer
6760  * @netdev: This port's netdev
6761  * @features: Offload features that the stack believes apply
6762  */
6763 static netdev_features_t
6764 ice_features_check(struct sk_buff *skb,
6765                    struct net_device __always_unused *netdev,
6766                    netdev_features_t features)
6767 {
6768         size_t len;
6769
6770         /* No point in doing any of this if neither checksum nor GSO are
6771          * being requested for this frame. We can rule out both by just
6772          * checking for CHECKSUM_PARTIAL
6773          */
6774         if (skb->ip_summed != CHECKSUM_PARTIAL)
6775                 return features;
6776
6777         /* We cannot support GSO if the MSS is going to be less than
6778          * 64 bytes. If it is then we need to drop support for GSO.
6779          */
6780         if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
6781                 features &= ~NETIF_F_GSO_MASK;
6782
6783         len = skb_network_header(skb) - skb->data;
6784         if (len > ICE_TXD_MACLEN_MAX || len & 0x1)
6785                 goto out_rm_features;
6786
6787         len = skb_transport_header(skb) - skb_network_header(skb);
6788         if (len > ICE_TXD_IPLEN_MAX || len & 0x1)
6789                 goto out_rm_features;
6790
6791         if (skb->encapsulation) {
6792                 len = skb_inner_network_header(skb) - skb_transport_header(skb);
6793                 if (len > ICE_TXD_L4LEN_MAX || len & 0x1)
6794                         goto out_rm_features;
6795
6796                 len = skb_inner_transport_header(skb) -
6797                       skb_inner_network_header(skb);
6798                 if (len > ICE_TXD_IPLEN_MAX || len & 0x1)
6799                         goto out_rm_features;
6800         }
6801
6802         return features;
6803 out_rm_features:
6804         return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
6805 }
6806
6807 static const struct net_device_ops ice_netdev_safe_mode_ops = {
6808         .ndo_open = ice_open,
6809         .ndo_stop = ice_stop,
6810         .ndo_start_xmit = ice_start_xmit,
6811         .ndo_set_mac_address = ice_set_mac_address,
6812         .ndo_validate_addr = eth_validate_addr,
6813         .ndo_change_mtu = ice_change_mtu,
6814         .ndo_get_stats64 = ice_get_stats64,
6815         .ndo_tx_timeout = ice_tx_timeout,
6816 };
6817
6818 static const struct net_device_ops ice_netdev_ops = {
6819         .ndo_open = ice_open,
6820         .ndo_stop = ice_stop,
6821         .ndo_start_xmit = ice_start_xmit,
6822         .ndo_features_check = ice_features_check,
6823         .ndo_set_rx_mode = ice_set_rx_mode,
6824         .ndo_set_mac_address = ice_set_mac_address,
6825         .ndo_validate_addr = eth_validate_addr,
6826         .ndo_change_mtu = ice_change_mtu,
6827         .ndo_get_stats64 = ice_get_stats64,
6828         .ndo_set_tx_maxrate = ice_set_tx_maxrate,
6829         .ndo_set_vf_spoofchk = ice_set_vf_spoofchk,
6830         .ndo_set_vf_mac = ice_set_vf_mac,
6831         .ndo_get_vf_config = ice_get_vf_cfg,
6832         .ndo_set_vf_trust = ice_set_vf_trust,
6833         .ndo_set_vf_vlan = ice_set_vf_port_vlan,
6834         .ndo_set_vf_link_state = ice_set_vf_link_state,
6835         .ndo_get_vf_stats = ice_get_vf_stats,
6836         .ndo_vlan_rx_add_vid = ice_vlan_rx_add_vid,
6837         .ndo_vlan_rx_kill_vid = ice_vlan_rx_kill_vid,
6838         .ndo_set_features = ice_set_features,
6839         .ndo_bridge_getlink = ice_bridge_getlink,
6840         .ndo_bridge_setlink = ice_bridge_setlink,
6841         .ndo_fdb_add = ice_fdb_add,
6842         .ndo_fdb_del = ice_fdb_del,
6843 #ifdef CONFIG_RFS_ACCEL
6844         .ndo_rx_flow_steer = ice_rx_flow_steer,
6845 #endif
6846         .ndo_tx_timeout = ice_tx_timeout,
6847         .ndo_bpf = ice_xdp,
6848         .ndo_xdp_xmit = ice_xdp_xmit,
6849         .ndo_xsk_wakeup = ice_xsk_wakeup,
6850 };