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