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