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