xref: /linux/drivers/net/ethernet/intel/i40e/i40e_main.c (revision 878492af7d503f4b093ea903173500be00e9cbe7)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2013 - 2021 Intel Corporation. */
3 
4 #include <generated/utsrelease.h>
5 #include <linux/crash_dump.h>
6 #include <linux/net/intel/libie/pctype.h>
7 #include <linux/if_bridge.h>
8 #include <linux/if_macvlan.h>
9 #include <linux/module.h>
10 #include <net/pkt_cls.h>
11 #include <net/xdp_sock_drv.h>
12 
13 /* Local includes */
14 #include "i40e.h"
15 #include "i40e_devids.h"
16 #include "i40e_diag.h"
17 #include "i40e_lan_hmc.h"
18 #include "i40e_virtchnl_pf.h"
19 #include "i40e_xsk.h"
20 
21 /* All i40e tracepoints are defined by the include below, which
22  * must be included exactly once across the whole kernel with
23  * CREATE_TRACE_POINTS defined
24  */
25 #define CREATE_TRACE_POINTS
26 #include "i40e_trace.h"
27 
28 const char i40e_driver_name[] = "i40e";
29 static const char i40e_driver_string[] =
30 			"Intel(R) Ethernet Connection XL710 Network Driver";
31 
32 static const char i40e_copyright[] = "Copyright (c) 2013 - 2019 Intel Corporation.";
33 
34 /* a bit of forward declarations */
35 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi);
36 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired);
37 static int i40e_add_vsi(struct i40e_vsi *vsi);
38 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi);
39 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired);
40 static int i40e_setup_misc_vector(struct i40e_pf *pf);
41 static void i40e_determine_queue_usage(struct i40e_pf *pf);
42 static int i40e_setup_pf_filter_control(struct i40e_pf *pf);
43 static void i40e_prep_for_reset(struct i40e_pf *pf);
44 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
45 				   bool lock_acquired);
46 static int i40e_reset(struct i40e_pf *pf);
47 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired);
48 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf);
49 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf);
50 static bool i40e_check_recovery_mode(struct i40e_pf *pf);
51 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw);
52 static void i40e_fdir_sb_setup(struct i40e_pf *pf);
53 static int i40e_veb_get_bw_info(struct i40e_veb *veb);
54 static int i40e_get_capabilities(struct i40e_pf *pf,
55 				 enum i40e_admin_queue_opc list_type);
56 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf);
57 
58 /* i40e_pci_tbl - PCI Device ID Table
59  *
60  * Last entry must be all 0s
61  *
62  * { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
63  *   Class, Class Mask, private data (not used) }
64  */
65 static const struct pci_device_id i40e_pci_tbl[] = {
66 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_XL710) },
67 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_QEMU) },
68 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_B) },
69 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_C) },
70 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_A) },
71 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_B) },
72 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_C) },
73 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_BC) },
74 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T) },
75 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T4) },
76 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_BC) },
77 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_SFP) },
78 	/*
79 	 * This ID conflicts with ipw2200, but the devices can be differentiated
80 	 * because i40e devices use PCI_CLASS_NETWORK_ETHERNET and ipw2200
81 	 * devices use PCI_CLASS_NETWORK_OTHER.
82 	 */
83 	{
84 		PCI_DEVICE(PCI_VENDOR_ID_INTEL, I40E_DEV_ID_10G_B),
85 		.class = PCI_CLASS_NETWORK_ETHERNET << 8,
86 		.class_mask = 0xffff00,
87 	},
88 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_X722) },
89 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_X722) },
90 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722) },
91 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_X722) },
92 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_X722) },
93 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_I_X722) },
94 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722_A) },
95 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2) },
96 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A) },
97 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_X710_N3000) },
98 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_XXV710_N3000) },
99 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B) },
100 	{ PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28) },
101 	/* required last entry */
102 	{ }
103 };
104 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
105 
106 #define I40E_MAX_VF_COUNT 128
107 static int debug = -1;
108 module_param(debug, uint, 0);
109 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
110 
111 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
112 MODULE_IMPORT_NS("LIBIE");
113 MODULE_IMPORT_NS("LIBIE_ADMINQ");
114 MODULE_LICENSE("GPL v2");
115 
116 static struct workqueue_struct *i40e_wq;
117 
118 static void netdev_hw_addr_refcnt(struct i40e_mac_filter *f,
119 				  struct net_device *netdev, int delta)
120 {
121 	struct netdev_hw_addr_list *ha_list;
122 	struct netdev_hw_addr *ha;
123 
124 	if (!f || !netdev)
125 		return;
126 
127 	if (is_unicast_ether_addr(f->macaddr) || is_link_local_ether_addr(f->macaddr))
128 		ha_list = &netdev->uc;
129 	else
130 		ha_list = &netdev->mc;
131 
132 	netdev_hw_addr_list_for_each(ha, ha_list) {
133 		if (ether_addr_equal(ha->addr, f->macaddr)) {
134 			ha->refcount += delta;
135 			if (ha->refcount <= 0)
136 				ha->refcount = 1;
137 			break;
138 		}
139 	}
140 }
141 
142 /**
143  * i40e_hw_to_dev - get device pointer from the hardware structure
144  * @hw: pointer to the device HW structure
145  **/
146 struct device *i40e_hw_to_dev(struct i40e_hw *hw)
147 {
148 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
149 
150 	return &pf->pdev->dev;
151 }
152 
153 /**
154  * i40e_allocate_dma_mem - OS specific memory alloc for shared code
155  * @hw:   pointer to the HW structure
156  * @mem:  ptr to mem struct to fill out
157  * @size: size of memory requested
158  * @alignment: what to align the allocation to
159  **/
160 int i40e_allocate_dma_mem(struct i40e_hw *hw, struct i40e_dma_mem *mem,
161 			  u64 size, u32 alignment)
162 {
163 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
164 
165 	mem->size = ALIGN(size, alignment);
166 	mem->va = dma_alloc_coherent(&pf->pdev->dev, mem->size, &mem->pa,
167 				     GFP_KERNEL);
168 	if (!mem->va)
169 		return -ENOMEM;
170 
171 	return 0;
172 }
173 
174 /**
175  * i40e_free_dma_mem - OS specific memory free for shared code
176  * @hw:   pointer to the HW structure
177  * @mem:  ptr to mem struct to free
178  **/
179 int i40e_free_dma_mem(struct i40e_hw *hw, struct i40e_dma_mem *mem)
180 {
181 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
182 
183 	dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
184 	mem->va = NULL;
185 	mem->pa = 0;
186 	mem->size = 0;
187 
188 	return 0;
189 }
190 
191 /**
192  * i40e_allocate_virt_mem - OS specific memory alloc for shared code
193  * @hw:   pointer to the HW structure
194  * @mem:  ptr to mem struct to fill out
195  * @size: size of memory requested
196  **/
197 int i40e_allocate_virt_mem(struct i40e_hw *hw, struct i40e_virt_mem *mem,
198 			   u32 size)
199 {
200 	mem->size = size;
201 	mem->va = kzalloc(size, GFP_KERNEL);
202 
203 	if (!mem->va)
204 		return -ENOMEM;
205 
206 	return 0;
207 }
208 
209 /**
210  * i40e_free_virt_mem - OS specific memory free for shared code
211  * @hw:   pointer to the HW structure
212  * @mem:  ptr to mem struct to free
213  **/
214 int i40e_free_virt_mem(struct i40e_hw *hw, struct i40e_virt_mem *mem)
215 {
216 	/* it's ok to kfree a NULL pointer */
217 	kfree(mem->va);
218 	mem->va = NULL;
219 	mem->size = 0;
220 
221 	return 0;
222 }
223 
224 /**
225  * i40e_get_lump - find a lump of free generic resource
226  * @pf: board private structure
227  * @pile: the pile of resource to search
228  * @needed: the number of items needed
229  * @id: an owner id to stick on the items assigned
230  *
231  * Returns the base item index of the lump, or negative for error
232  **/
233 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
234 			 u16 needed, u16 id)
235 {
236 	int ret = -ENOMEM;
237 	int i, j;
238 
239 	if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
240 		dev_info(&pf->pdev->dev,
241 			 "param err: pile=%s needed=%d id=0x%04x\n",
242 			 pile ? "<valid>" : "<null>", needed, id);
243 		return -EINVAL;
244 	}
245 
246 	/* Allocate last queue in the pile for FDIR VSI queue
247 	 * so it doesn't fragment the qp_pile
248 	 */
249 	if (pile == pf->qp_pile && pf->vsi[id]->type == I40E_VSI_FDIR) {
250 		if (pile->list[pile->num_entries - 1] & I40E_PILE_VALID_BIT) {
251 			dev_err(&pf->pdev->dev,
252 				"Cannot allocate queue %d for I40E_VSI_FDIR\n",
253 				pile->num_entries - 1);
254 			return -ENOMEM;
255 		}
256 		pile->list[pile->num_entries - 1] = id | I40E_PILE_VALID_BIT;
257 		return pile->num_entries - 1;
258 	}
259 
260 	i = 0;
261 	while (i < pile->num_entries) {
262 		/* skip already allocated entries */
263 		if (pile->list[i] & I40E_PILE_VALID_BIT) {
264 			i++;
265 			continue;
266 		}
267 
268 		/* do we have enough in this lump? */
269 		for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
270 			if (pile->list[i+j] & I40E_PILE_VALID_BIT)
271 				break;
272 		}
273 
274 		if (j == needed) {
275 			/* there was enough, so assign it to the requestor */
276 			for (j = 0; j < needed; j++)
277 				pile->list[i+j] = id | I40E_PILE_VALID_BIT;
278 			ret = i;
279 			break;
280 		}
281 
282 		/* not enough, so skip over it and continue looking */
283 		i += j;
284 	}
285 
286 	return ret;
287 }
288 
289 /**
290  * i40e_put_lump - return a lump of generic resource
291  * @pile: the pile of resource to search
292  * @index: the base item index
293  * @id: the owner id of the items assigned
294  *
295  * Returns the count of items in the lump
296  **/
297 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
298 {
299 	int valid_id = (id | I40E_PILE_VALID_BIT);
300 	int count = 0;
301 	u16 i;
302 
303 	if (!pile || index >= pile->num_entries)
304 		return -EINVAL;
305 
306 	for (i = index;
307 	     i < pile->num_entries && pile->list[i] == valid_id;
308 	     i++) {
309 		pile->list[i] = 0;
310 		count++;
311 	}
312 
313 
314 	return count;
315 }
316 
317 /**
318  * i40e_find_vsi_from_id - searches for the vsi with the given id
319  * @pf: the pf structure to search for the vsi
320  * @id: id of the vsi it is searching for
321  **/
322 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
323 {
324 	struct i40e_vsi *vsi;
325 	int i;
326 
327 	i40e_pf_for_each_vsi(pf, i, vsi)
328 		if (vsi->id == id)
329 			return vsi;
330 
331 	return NULL;
332 }
333 
334 /**
335  * i40e_service_event_schedule - Schedule the service task to wake up
336  * @pf: board private structure
337  *
338  * If not already scheduled, this puts the task into the work queue
339  **/
340 void i40e_service_event_schedule(struct i40e_pf *pf)
341 {
342 	if ((!test_bit(__I40E_DOWN, pf->state) &&
343 	     !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) ||
344 	      test_bit(__I40E_RECOVERY_MODE, pf->state))
345 		queue_work(i40e_wq, &pf->service_task);
346 }
347 
348 /**
349  * i40e_tx_timeout - Respond to a Tx Hang
350  * @netdev: network interface device structure
351  * @txqueue: queue number timing out
352  *
353  * If any port has noticed a Tx timeout, it is likely that the whole
354  * device is munged, not just the one netdev port, so go for the full
355  * reset.
356  **/
357 static void i40e_tx_timeout(struct net_device *netdev, unsigned int txqueue)
358 {
359 	struct i40e_netdev_priv *np = netdev_priv(netdev);
360 	struct i40e_vsi *vsi = np->vsi;
361 	struct i40e_pf *pf = vsi->back;
362 	struct i40e_ring *tx_ring = NULL;
363 	unsigned int i;
364 	u32 head, val;
365 
366 	pf->tx_timeout_count++;
367 
368 	/* with txqueue index, find the tx_ring struct */
369 	for (i = 0; i < vsi->num_queue_pairs; i++) {
370 		if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
371 			if (txqueue ==
372 			    vsi->tx_rings[i]->queue_index) {
373 				tx_ring = vsi->tx_rings[i];
374 				break;
375 			}
376 		}
377 	}
378 
379 	if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
380 		pf->tx_timeout_recovery_level = 1;  /* reset after some time */
381 	else if (time_before(jiffies,
382 		      (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
383 		return;   /* don't do any new action before the next timeout */
384 
385 	/* don't kick off another recovery if one is already pending */
386 	if (test_and_set_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state))
387 		return;
388 
389 	if (tx_ring) {
390 		head = i40e_get_head(tx_ring);
391 		/* Read interrupt register */
392 		if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
393 			val = rd32(&pf->hw,
394 			     I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
395 						tx_ring->vsi->base_vector - 1));
396 		else
397 			val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
398 
399 		netdev_info(netdev, "tx_timeout: VSI_seid: %d, Q %d, NTC: 0x%x, HWB: 0x%x, NTU: 0x%x, TAIL: 0x%x, INT: 0x%x\n",
400 			    vsi->seid, txqueue, tx_ring->next_to_clean,
401 			    head, tx_ring->next_to_use,
402 			    readl(tx_ring->tail), val);
403 	}
404 
405 	pf->tx_timeout_last_recovery = jiffies;
406 	netdev_info(netdev, "tx_timeout recovery level %d, txqueue %d\n",
407 		    pf->tx_timeout_recovery_level, txqueue);
408 
409 	switch (pf->tx_timeout_recovery_level) {
410 	case 1:
411 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
412 		break;
413 	case 2:
414 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
415 		break;
416 	case 3:
417 		set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
418 		break;
419 	default:
420 		netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in non-recoverable state.\n");
421 		set_bit(__I40E_DOWN_REQUESTED, pf->state);
422 		set_bit(__I40E_VSI_DOWN_REQUESTED, vsi->state);
423 		break;
424 	}
425 
426 	i40e_service_event_schedule(pf);
427 	pf->tx_timeout_recovery_level++;
428 }
429 
430 /**
431  * i40e_get_vsi_stats_struct - Get System Network Statistics
432  * @vsi: the VSI we care about
433  *
434  * Returns the address of the device statistics structure.
435  * The statistics are actually updated from the service task.
436  **/
437 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
438 {
439 	return &vsi->net_stats;
440 }
441 
442 /**
443  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
444  * @ring: Tx ring to get statistics from
445  * @stats: statistics entry to be updated
446  **/
447 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
448 					    struct rtnl_link_stats64 *stats)
449 {
450 	u64 bytes, packets;
451 	unsigned int start;
452 
453 	do {
454 		start = u64_stats_fetch_begin(&ring->syncp);
455 		packets = ring->stats.packets;
456 		bytes   = ring->stats.bytes;
457 	} while (u64_stats_fetch_retry(&ring->syncp, start));
458 
459 	stats->tx_packets += packets;
460 	stats->tx_bytes   += bytes;
461 }
462 
463 /**
464  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
465  * @netdev: network interface device structure
466  * @stats: data structure to store statistics
467  *
468  * Returns the address of the device statistics structure.
469  * The statistics are actually updated from the service task.
470  **/
471 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
472 				  struct rtnl_link_stats64 *stats)
473 {
474 	struct i40e_netdev_priv *np = netdev_priv(netdev);
475 	struct i40e_vsi *vsi = np->vsi;
476 	struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
477 	struct i40e_ring *ring;
478 	int i;
479 
480 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
481 		return;
482 
483 	if (!vsi->tx_rings)
484 		return;
485 
486 	rcu_read_lock();
487 	for (i = 0; i < vsi->num_queue_pairs; i++) {
488 		u64 bytes, packets;
489 		unsigned int start;
490 
491 		ring = READ_ONCE(vsi->tx_rings[i]);
492 		if (!ring)
493 			continue;
494 		i40e_get_netdev_stats_struct_tx(ring, stats);
495 
496 		if (i40e_enabled_xdp_vsi(vsi)) {
497 			ring = READ_ONCE(vsi->xdp_rings[i]);
498 			if (!ring)
499 				continue;
500 			i40e_get_netdev_stats_struct_tx(ring, stats);
501 		}
502 
503 		ring = READ_ONCE(vsi->rx_rings[i]);
504 		if (!ring)
505 			continue;
506 		do {
507 			start   = u64_stats_fetch_begin(&ring->syncp);
508 			packets = ring->stats.packets;
509 			bytes   = ring->stats.bytes;
510 		} while (u64_stats_fetch_retry(&ring->syncp, start));
511 
512 		stats->rx_packets += packets;
513 		stats->rx_bytes   += bytes;
514 
515 	}
516 	rcu_read_unlock();
517 
518 	/* following stats updated by i40e_watchdog_subtask() */
519 	stats->multicast	= vsi_stats->multicast;
520 	stats->tx_errors	= vsi_stats->tx_errors;
521 	stats->tx_dropped	= vsi_stats->tx_dropped;
522 	stats->rx_errors	= vsi_stats->rx_errors;
523 	stats->rx_dropped	= vsi_stats->rx_dropped;
524 	stats->rx_missed_errors	= vsi_stats->rx_missed_errors;
525 	stats->rx_crc_errors	= vsi_stats->rx_crc_errors;
526 	stats->rx_length_errors	= vsi_stats->rx_length_errors;
527 }
528 
529 /**
530  * i40e_vsi_reset_stats - Resets all stats of the given vsi
531  * @vsi: the VSI to have its stats reset
532  **/
533 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
534 {
535 	struct rtnl_link_stats64 *ns;
536 	int i;
537 
538 	if (!vsi)
539 		return;
540 
541 	ns = i40e_get_vsi_stats_struct(vsi);
542 	memset(ns, 0, sizeof(*ns));
543 	memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
544 	memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
545 	memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
546 	if (vsi->rx_rings && vsi->rx_rings[0]) {
547 		for (i = 0; i < vsi->num_queue_pairs; i++) {
548 			memset(&vsi->rx_rings[i]->stats, 0,
549 			       sizeof(vsi->rx_rings[i]->stats));
550 			memset(&vsi->rx_rings[i]->rx_stats, 0,
551 			       sizeof(vsi->rx_rings[i]->rx_stats));
552 			memset(&vsi->tx_rings[i]->stats, 0,
553 			       sizeof(vsi->tx_rings[i]->stats));
554 			memset(&vsi->tx_rings[i]->tx_stats, 0,
555 			       sizeof(vsi->tx_rings[i]->tx_stats));
556 		}
557 	}
558 	vsi->stat_offsets_loaded = false;
559 }
560 
561 /**
562  * i40e_pf_reset_stats - Reset all of the stats for the given PF
563  * @pf: the PF to be reset
564  **/
565 void i40e_pf_reset_stats(struct i40e_pf *pf)
566 {
567 	struct i40e_veb *veb;
568 	int i;
569 
570 	memset(&pf->stats, 0, sizeof(pf->stats));
571 	memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
572 	pf->stat_offsets_loaded = false;
573 
574 	i40e_pf_for_each_veb(pf, i, veb) {
575 		memset(&veb->stats, 0, sizeof(veb->stats));
576 		memset(&veb->stats_offsets, 0, sizeof(veb->stats_offsets));
577 		memset(&veb->tc_stats, 0, sizeof(veb->tc_stats));
578 		memset(&veb->tc_stats_offsets, 0, sizeof(veb->tc_stats_offsets));
579 		veb->stat_offsets_loaded = false;
580 	}
581 	pf->hw_csum_rx_error = 0;
582 }
583 
584 /**
585  * i40e_compute_pci_to_hw_id - compute index form PCI function.
586  * @vsi: ptr to the VSI to read from.
587  * @hw: ptr to the hardware info.
588  **/
589 static u32 i40e_compute_pci_to_hw_id(struct i40e_vsi *vsi, struct i40e_hw *hw)
590 {
591 	int pf_count = i40e_get_pf_count(hw);
592 
593 	if (vsi->type == I40E_VSI_SRIOV)
594 		return (hw->port * BIT(7)) / pf_count + vsi->vf_id;
595 
596 	return hw->port + BIT(7);
597 }
598 
599 /**
600  * i40e_stat_update64 - read and update a 64 bit stat from the chip.
601  * @hw: ptr to the hardware info.
602  * @hireg: the high 32 bit reg to read.
603  * @loreg: the low 32 bit reg to read.
604  * @offset_loaded: has the initial offset been loaded yet.
605  * @offset: ptr to current offset value.
606  * @stat: ptr to the stat.
607  *
608  * Since the device stats are not reset at PFReset, they will not
609  * be zeroed when the driver starts.  We'll save the first values read
610  * and use them as offsets to be subtracted from the raw values in order
611  * to report stats that count from zero.
612  **/
613 static void i40e_stat_update64(struct i40e_hw *hw, u32 hireg, u32 loreg,
614 			       bool offset_loaded, u64 *offset, u64 *stat)
615 {
616 	u64 new_data;
617 
618 	new_data = rd64(hw, loreg);
619 
620 	if (!offset_loaded || new_data < *offset)
621 		*offset = new_data;
622 	*stat = new_data - *offset;
623 }
624 
625 /**
626  * i40e_stat_update48 - read and update a 48 bit stat from the chip
627  * @hw: ptr to the hardware info
628  * @hireg: the high 32 bit reg to read
629  * @loreg: the low 32 bit reg to read
630  * @offset_loaded: has the initial offset been loaded yet
631  * @offset: ptr to current offset value
632  * @stat: ptr to the stat
633  *
634  * Since the device stats are not reset at PFReset, they likely will not
635  * be zeroed when the driver starts.  We'll save the first values read
636  * and use them as offsets to be subtracted from the raw values in order
637  * to report stats that count from zero.  In the process, we also manage
638  * the potential roll-over.
639  **/
640 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
641 			       bool offset_loaded, u64 *offset, u64 *stat)
642 {
643 	u64 new_data;
644 
645 	if (hw->device_id == I40E_DEV_ID_QEMU) {
646 		new_data = rd32(hw, loreg);
647 		new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
648 	} else {
649 		new_data = rd64(hw, loreg);
650 	}
651 	if (!offset_loaded)
652 		*offset = new_data;
653 	if (likely(new_data >= *offset))
654 		*stat = new_data - *offset;
655 	else
656 		*stat = (new_data + BIT_ULL(48)) - *offset;
657 	*stat &= 0xFFFFFFFFFFFFULL;
658 }
659 
660 /**
661  * i40e_stat_update32 - read and update a 32 bit stat from the chip
662  * @hw: ptr to the hardware info
663  * @reg: the hw reg to read
664  * @offset_loaded: has the initial offset been loaded yet
665  * @offset: ptr to current offset value
666  * @stat: ptr to the stat
667  **/
668 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
669 			       bool offset_loaded, u64 *offset, u64 *stat)
670 {
671 	u32 new_data;
672 
673 	new_data = rd32(hw, reg);
674 	if (!offset_loaded)
675 		*offset = new_data;
676 	if (likely(new_data >= *offset))
677 		*stat = (u32)(new_data - *offset);
678 	else
679 		*stat = (u32)((new_data + BIT_ULL(32)) - *offset);
680 }
681 
682 /**
683  * i40e_stat_update_and_clear32 - read and clear hw reg, update a 32 bit stat
684  * @hw: ptr to the hardware info
685  * @reg: the hw reg to read and clear
686  * @stat: ptr to the stat
687  **/
688 static void i40e_stat_update_and_clear32(struct i40e_hw *hw, u32 reg, u64 *stat)
689 {
690 	u32 new_data = rd32(hw, reg);
691 
692 	wr32(hw, reg, 1); /* must write a nonzero value to clear register */
693 	*stat += new_data;
694 }
695 
696 /**
697  * i40e_stats_update_rx_discards - update rx_discards.
698  * @vsi: ptr to the VSI to be updated.
699  * @hw: ptr to the hardware info.
700  * @stat_idx: VSI's stat_counter_idx.
701  * @offset_loaded: ptr to the VSI's stat_offsets_loaded.
702  * @stat_offset: ptr to stat_offset to store first read of specific register.
703  * @stat: ptr to VSI's stat to be updated.
704  **/
705 static void
706 i40e_stats_update_rx_discards(struct i40e_vsi *vsi, struct i40e_hw *hw,
707 			      int stat_idx, bool offset_loaded,
708 			      struct i40e_eth_stats *stat_offset,
709 			      struct i40e_eth_stats *stat)
710 {
711 	i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx), offset_loaded,
712 			   &stat_offset->rx_discards, &stat->rx_discards);
713 	i40e_stat_update64(hw,
714 			   I40E_GL_RXERR1H(i40e_compute_pci_to_hw_id(vsi, hw)),
715 			   I40E_GL_RXERR1L(i40e_compute_pci_to_hw_id(vsi, hw)),
716 			   offset_loaded, &stat_offset->rx_discards_other,
717 			   &stat->rx_discards_other);
718 }
719 
720 /**
721  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
722  * @vsi: the VSI to be updated
723  **/
724 void i40e_update_eth_stats(struct i40e_vsi *vsi)
725 {
726 	int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
727 	struct i40e_pf *pf = vsi->back;
728 	struct i40e_hw *hw = &pf->hw;
729 	struct i40e_eth_stats *oes;
730 	struct i40e_eth_stats *es;     /* device's eth stats */
731 
732 	es = &vsi->eth_stats;
733 	oes = &vsi->eth_stats_offsets;
734 
735 	/* Gather up the stats that the hw collects */
736 	i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
737 			   vsi->stat_offsets_loaded,
738 			   &oes->tx_errors, &es->tx_errors);
739 	i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
740 			   vsi->stat_offsets_loaded,
741 			   &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
742 
743 	i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
744 			   I40E_GLV_GORCL(stat_idx),
745 			   vsi->stat_offsets_loaded,
746 			   &oes->rx_bytes, &es->rx_bytes);
747 	i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
748 			   I40E_GLV_UPRCL(stat_idx),
749 			   vsi->stat_offsets_loaded,
750 			   &oes->rx_unicast, &es->rx_unicast);
751 	i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
752 			   I40E_GLV_MPRCL(stat_idx),
753 			   vsi->stat_offsets_loaded,
754 			   &oes->rx_multicast, &es->rx_multicast);
755 	i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
756 			   I40E_GLV_BPRCL(stat_idx),
757 			   vsi->stat_offsets_loaded,
758 			   &oes->rx_broadcast, &es->rx_broadcast);
759 
760 	i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
761 			   I40E_GLV_GOTCL(stat_idx),
762 			   vsi->stat_offsets_loaded,
763 			   &oes->tx_bytes, &es->tx_bytes);
764 	i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
765 			   I40E_GLV_UPTCL(stat_idx),
766 			   vsi->stat_offsets_loaded,
767 			   &oes->tx_unicast, &es->tx_unicast);
768 	i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
769 			   I40E_GLV_MPTCL(stat_idx),
770 			   vsi->stat_offsets_loaded,
771 			   &oes->tx_multicast, &es->tx_multicast);
772 	i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
773 			   I40E_GLV_BPTCL(stat_idx),
774 			   vsi->stat_offsets_loaded,
775 			   &oes->tx_broadcast, &es->tx_broadcast);
776 
777 	i40e_stats_update_rx_discards(vsi, hw, stat_idx,
778 				      vsi->stat_offsets_loaded, oes, es);
779 
780 	vsi->stat_offsets_loaded = true;
781 }
782 
783 /**
784  * i40e_update_veb_stats - Update Switch component statistics
785  * @veb: the VEB being updated
786  **/
787 void i40e_update_veb_stats(struct i40e_veb *veb)
788 {
789 	struct i40e_pf *pf = veb->pf;
790 	struct i40e_hw *hw = &pf->hw;
791 	struct i40e_eth_stats *oes;
792 	struct i40e_eth_stats *es;     /* device's eth stats */
793 	struct i40e_veb_tc_stats *veb_oes;
794 	struct i40e_veb_tc_stats *veb_es;
795 	int i, idx = 0;
796 
797 	idx = veb->stats_idx;
798 	es = &veb->stats;
799 	oes = &veb->stats_offsets;
800 	veb_es = &veb->tc_stats;
801 	veb_oes = &veb->tc_stats_offsets;
802 
803 	/* Gather up the stats that the hw collects */
804 	i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
805 			   veb->stat_offsets_loaded,
806 			   &oes->tx_discards, &es->tx_discards);
807 	if (hw->revision_id > 0)
808 		i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
809 				   veb->stat_offsets_loaded,
810 				   &oes->rx_unknown_protocol,
811 				   &es->rx_unknown_protocol);
812 	i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
813 			   veb->stat_offsets_loaded,
814 			   &oes->rx_bytes, &es->rx_bytes);
815 	i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
816 			   veb->stat_offsets_loaded,
817 			   &oes->rx_unicast, &es->rx_unicast);
818 	i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
819 			   veb->stat_offsets_loaded,
820 			   &oes->rx_multicast, &es->rx_multicast);
821 	i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
822 			   veb->stat_offsets_loaded,
823 			   &oes->rx_broadcast, &es->rx_broadcast);
824 
825 	i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
826 			   veb->stat_offsets_loaded,
827 			   &oes->tx_bytes, &es->tx_bytes);
828 	i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
829 			   veb->stat_offsets_loaded,
830 			   &oes->tx_unicast, &es->tx_unicast);
831 	i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
832 			   veb->stat_offsets_loaded,
833 			   &oes->tx_multicast, &es->tx_multicast);
834 	i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
835 			   veb->stat_offsets_loaded,
836 			   &oes->tx_broadcast, &es->tx_broadcast);
837 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
838 		i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
839 				   I40E_GLVEBTC_RPCL(i, idx),
840 				   veb->stat_offsets_loaded,
841 				   &veb_oes->tc_rx_packets[i],
842 				   &veb_es->tc_rx_packets[i]);
843 		i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
844 				   I40E_GLVEBTC_RBCL(i, idx),
845 				   veb->stat_offsets_loaded,
846 				   &veb_oes->tc_rx_bytes[i],
847 				   &veb_es->tc_rx_bytes[i]);
848 		i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
849 				   I40E_GLVEBTC_TPCL(i, idx),
850 				   veb->stat_offsets_loaded,
851 				   &veb_oes->tc_tx_packets[i],
852 				   &veb_es->tc_tx_packets[i]);
853 		i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
854 				   I40E_GLVEBTC_TBCL(i, idx),
855 				   veb->stat_offsets_loaded,
856 				   &veb_oes->tc_tx_bytes[i],
857 				   &veb_es->tc_tx_bytes[i]);
858 	}
859 	veb->stat_offsets_loaded = true;
860 }
861 
862 /**
863  * i40e_update_vsi_stats - Update the vsi statistics counters.
864  * @vsi: the VSI to be updated
865  *
866  * There are a few instances where we store the same stat in a
867  * couple of different structs.  This is partly because we have
868  * the netdev stats that need to be filled out, which is slightly
869  * different from the "eth_stats" defined by the chip and used in
870  * VF communications.  We sort it out here.
871  **/
872 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
873 {
874 	u64 rx_page, rx_buf, rx_reuse, rx_alloc, rx_waive, rx_busy;
875 	struct i40e_pf *pf = vsi->back;
876 	struct rtnl_link_stats64 *ons;
877 	struct rtnl_link_stats64 *ns;   /* netdev stats */
878 	struct i40e_eth_stats *oes;
879 	struct i40e_eth_stats *es;     /* device's eth stats */
880 	u64 tx_restart, tx_busy;
881 	struct i40e_ring *p;
882 	u64 bytes, packets;
883 	unsigned int start;
884 	u64 tx_linearize;
885 	u64 tx_force_wb;
886 	u64 tx_stopped;
887 	u64 rx_p, rx_b;
888 	u64 tx_p, tx_b;
889 	u16 q;
890 
891 	if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
892 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
893 		return;
894 
895 	ns = i40e_get_vsi_stats_struct(vsi);
896 	ons = &vsi->net_stats_offsets;
897 	es = &vsi->eth_stats;
898 	oes = &vsi->eth_stats_offsets;
899 
900 	/* Gather up the netdev and vsi stats that the driver collects
901 	 * on the fly during packet processing
902 	 */
903 	rx_b = rx_p = 0;
904 	tx_b = tx_p = 0;
905 	tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
906 	tx_stopped = 0;
907 	rx_page = 0;
908 	rx_buf = 0;
909 	rx_reuse = 0;
910 	rx_alloc = 0;
911 	rx_waive = 0;
912 	rx_busy = 0;
913 	rcu_read_lock();
914 	for (q = 0; q < vsi->num_queue_pairs; q++) {
915 		/* locate Tx ring */
916 		p = READ_ONCE(vsi->tx_rings[q]);
917 		if (!p)
918 			continue;
919 
920 		do {
921 			start = u64_stats_fetch_begin(&p->syncp);
922 			packets = p->stats.packets;
923 			bytes = p->stats.bytes;
924 		} while (u64_stats_fetch_retry(&p->syncp, start));
925 		tx_b += bytes;
926 		tx_p += packets;
927 		tx_restart += p->tx_stats.restart_queue;
928 		tx_busy += p->tx_stats.tx_busy;
929 		tx_linearize += p->tx_stats.tx_linearize;
930 		tx_force_wb += p->tx_stats.tx_force_wb;
931 		tx_stopped += p->tx_stats.tx_stopped;
932 
933 		/* locate Rx ring */
934 		p = READ_ONCE(vsi->rx_rings[q]);
935 		if (!p)
936 			continue;
937 
938 		do {
939 			start = u64_stats_fetch_begin(&p->syncp);
940 			packets = p->stats.packets;
941 			bytes = p->stats.bytes;
942 		} while (u64_stats_fetch_retry(&p->syncp, start));
943 		rx_b += bytes;
944 		rx_p += packets;
945 		rx_buf += p->rx_stats.alloc_buff_failed;
946 		rx_page += p->rx_stats.alloc_page_failed;
947 		rx_reuse += p->rx_stats.page_reuse_count;
948 		rx_alloc += p->rx_stats.page_alloc_count;
949 		rx_waive += p->rx_stats.page_waive_count;
950 		rx_busy += p->rx_stats.page_busy_count;
951 
952 		if (i40e_enabled_xdp_vsi(vsi)) {
953 			/* locate XDP ring */
954 			p = READ_ONCE(vsi->xdp_rings[q]);
955 			if (!p)
956 				continue;
957 
958 			do {
959 				start = u64_stats_fetch_begin(&p->syncp);
960 				packets = p->stats.packets;
961 				bytes = p->stats.bytes;
962 			} while (u64_stats_fetch_retry(&p->syncp, start));
963 			tx_b += bytes;
964 			tx_p += packets;
965 			tx_restart += p->tx_stats.restart_queue;
966 			tx_busy += p->tx_stats.tx_busy;
967 			tx_linearize += p->tx_stats.tx_linearize;
968 			tx_force_wb += p->tx_stats.tx_force_wb;
969 		}
970 	}
971 	rcu_read_unlock();
972 	vsi->tx_restart = tx_restart;
973 	vsi->tx_busy = tx_busy;
974 	vsi->tx_linearize = tx_linearize;
975 	vsi->tx_force_wb = tx_force_wb;
976 	vsi->tx_stopped = tx_stopped;
977 	vsi->rx_page_failed = rx_page;
978 	vsi->rx_buf_failed = rx_buf;
979 	vsi->rx_page_reuse = rx_reuse;
980 	vsi->rx_page_alloc = rx_alloc;
981 	vsi->rx_page_waive = rx_waive;
982 	vsi->rx_page_busy = rx_busy;
983 
984 	ns->rx_packets = rx_p;
985 	ns->rx_bytes = rx_b;
986 	ns->tx_packets = tx_p;
987 	ns->tx_bytes = tx_b;
988 
989 	/* update netdev stats from eth stats */
990 	i40e_update_eth_stats(vsi);
991 	ons->tx_errors = oes->tx_errors;
992 	ns->tx_errors = es->tx_errors;
993 	ons->multicast = oes->rx_multicast;
994 	ns->multicast = es->rx_multicast;
995 	ons->rx_dropped = oes->rx_discards_other;
996 	ns->rx_dropped = es->rx_discards_other;
997 	ons->rx_missed_errors = oes->rx_discards;
998 	ns->rx_missed_errors = es->rx_discards;
999 	ons->tx_dropped = oes->tx_discards;
1000 	ns->tx_dropped = es->tx_discards;
1001 
1002 	/* pull in a couple PF stats if this is the main vsi */
1003 	if (vsi->type == I40E_VSI_MAIN) {
1004 		ns->rx_crc_errors = pf->stats.crc_errors;
1005 		ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
1006 		ns->rx_length_errors = pf->stats.rx_length_errors;
1007 	}
1008 }
1009 
1010 /**
1011  * i40e_update_pf_stats - Update the PF statistics counters.
1012  * @pf: the PF to be updated
1013  **/
1014 static void i40e_update_pf_stats(struct i40e_pf *pf)
1015 {
1016 	struct i40e_hw_port_stats *osd = &pf->stats_offsets;
1017 	struct i40e_hw_port_stats *nsd = &pf->stats;
1018 	struct i40e_hw *hw = &pf->hw;
1019 	u32 val;
1020 	int i;
1021 
1022 	i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
1023 			   I40E_GLPRT_GORCL(hw->port),
1024 			   pf->stat_offsets_loaded,
1025 			   &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
1026 	i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
1027 			   I40E_GLPRT_GOTCL(hw->port),
1028 			   pf->stat_offsets_loaded,
1029 			   &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
1030 	i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
1031 			   pf->stat_offsets_loaded,
1032 			   &osd->eth.rx_discards,
1033 			   &nsd->eth.rx_discards);
1034 	i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
1035 			   I40E_GLPRT_UPRCL(hw->port),
1036 			   pf->stat_offsets_loaded,
1037 			   &osd->eth.rx_unicast,
1038 			   &nsd->eth.rx_unicast);
1039 	i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
1040 			   I40E_GLPRT_MPRCL(hw->port),
1041 			   pf->stat_offsets_loaded,
1042 			   &osd->eth.rx_multicast,
1043 			   &nsd->eth.rx_multicast);
1044 	i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
1045 			   I40E_GLPRT_BPRCL(hw->port),
1046 			   pf->stat_offsets_loaded,
1047 			   &osd->eth.rx_broadcast,
1048 			   &nsd->eth.rx_broadcast);
1049 	i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
1050 			   I40E_GLPRT_UPTCL(hw->port),
1051 			   pf->stat_offsets_loaded,
1052 			   &osd->eth.tx_unicast,
1053 			   &nsd->eth.tx_unicast);
1054 	i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
1055 			   I40E_GLPRT_MPTCL(hw->port),
1056 			   pf->stat_offsets_loaded,
1057 			   &osd->eth.tx_multicast,
1058 			   &nsd->eth.tx_multicast);
1059 	i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
1060 			   I40E_GLPRT_BPTCL(hw->port),
1061 			   pf->stat_offsets_loaded,
1062 			   &osd->eth.tx_broadcast,
1063 			   &nsd->eth.tx_broadcast);
1064 
1065 	i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
1066 			   pf->stat_offsets_loaded,
1067 			   &osd->tx_dropped_link_down,
1068 			   &nsd->tx_dropped_link_down);
1069 
1070 	i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
1071 			   pf->stat_offsets_loaded,
1072 			   &osd->crc_errors, &nsd->crc_errors);
1073 
1074 	i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
1075 			   pf->stat_offsets_loaded,
1076 			   &osd->illegal_bytes, &nsd->illegal_bytes);
1077 
1078 	i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
1079 			   pf->stat_offsets_loaded,
1080 			   &osd->mac_local_faults,
1081 			   &nsd->mac_local_faults);
1082 	i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
1083 			   pf->stat_offsets_loaded,
1084 			   &osd->mac_remote_faults,
1085 			   &nsd->mac_remote_faults);
1086 
1087 	i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
1088 			   pf->stat_offsets_loaded,
1089 			   &osd->rx_length_errors,
1090 			   &nsd->rx_length_errors);
1091 
1092 	i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
1093 			   pf->stat_offsets_loaded,
1094 			   &osd->link_xon_rx, &nsd->link_xon_rx);
1095 	i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
1096 			   pf->stat_offsets_loaded,
1097 			   &osd->link_xon_tx, &nsd->link_xon_tx);
1098 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
1099 			   pf->stat_offsets_loaded,
1100 			   &osd->link_xoff_rx, &nsd->link_xoff_rx);
1101 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
1102 			   pf->stat_offsets_loaded,
1103 			   &osd->link_xoff_tx, &nsd->link_xoff_tx);
1104 
1105 	for (i = 0; i < 8; i++) {
1106 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
1107 				   pf->stat_offsets_loaded,
1108 				   &osd->priority_xoff_rx[i],
1109 				   &nsd->priority_xoff_rx[i]);
1110 		i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
1111 				   pf->stat_offsets_loaded,
1112 				   &osd->priority_xon_rx[i],
1113 				   &nsd->priority_xon_rx[i]);
1114 		i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
1115 				   pf->stat_offsets_loaded,
1116 				   &osd->priority_xon_tx[i],
1117 				   &nsd->priority_xon_tx[i]);
1118 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
1119 				   pf->stat_offsets_loaded,
1120 				   &osd->priority_xoff_tx[i],
1121 				   &nsd->priority_xoff_tx[i]);
1122 		i40e_stat_update32(hw,
1123 				   I40E_GLPRT_RXON2OFFCNT(hw->port, i),
1124 				   pf->stat_offsets_loaded,
1125 				   &osd->priority_xon_2_xoff[i],
1126 				   &nsd->priority_xon_2_xoff[i]);
1127 	}
1128 
1129 	i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
1130 			   I40E_GLPRT_PRC64L(hw->port),
1131 			   pf->stat_offsets_loaded,
1132 			   &osd->rx_size_64, &nsd->rx_size_64);
1133 	i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
1134 			   I40E_GLPRT_PRC127L(hw->port),
1135 			   pf->stat_offsets_loaded,
1136 			   &osd->rx_size_127, &nsd->rx_size_127);
1137 	i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
1138 			   I40E_GLPRT_PRC255L(hw->port),
1139 			   pf->stat_offsets_loaded,
1140 			   &osd->rx_size_255, &nsd->rx_size_255);
1141 	i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
1142 			   I40E_GLPRT_PRC511L(hw->port),
1143 			   pf->stat_offsets_loaded,
1144 			   &osd->rx_size_511, &nsd->rx_size_511);
1145 	i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
1146 			   I40E_GLPRT_PRC1023L(hw->port),
1147 			   pf->stat_offsets_loaded,
1148 			   &osd->rx_size_1023, &nsd->rx_size_1023);
1149 	i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
1150 			   I40E_GLPRT_PRC1522L(hw->port),
1151 			   pf->stat_offsets_loaded,
1152 			   &osd->rx_size_1522, &nsd->rx_size_1522);
1153 	i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
1154 			   I40E_GLPRT_PRC9522L(hw->port),
1155 			   pf->stat_offsets_loaded,
1156 			   &osd->rx_size_big, &nsd->rx_size_big);
1157 
1158 	i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1159 			   I40E_GLPRT_PTC64L(hw->port),
1160 			   pf->stat_offsets_loaded,
1161 			   &osd->tx_size_64, &nsd->tx_size_64);
1162 	i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1163 			   I40E_GLPRT_PTC127L(hw->port),
1164 			   pf->stat_offsets_loaded,
1165 			   &osd->tx_size_127, &nsd->tx_size_127);
1166 	i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1167 			   I40E_GLPRT_PTC255L(hw->port),
1168 			   pf->stat_offsets_loaded,
1169 			   &osd->tx_size_255, &nsd->tx_size_255);
1170 	i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1171 			   I40E_GLPRT_PTC511L(hw->port),
1172 			   pf->stat_offsets_loaded,
1173 			   &osd->tx_size_511, &nsd->tx_size_511);
1174 	i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1175 			   I40E_GLPRT_PTC1023L(hw->port),
1176 			   pf->stat_offsets_loaded,
1177 			   &osd->tx_size_1023, &nsd->tx_size_1023);
1178 	i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1179 			   I40E_GLPRT_PTC1522L(hw->port),
1180 			   pf->stat_offsets_loaded,
1181 			   &osd->tx_size_1522, &nsd->tx_size_1522);
1182 	i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1183 			   I40E_GLPRT_PTC9522L(hw->port),
1184 			   pf->stat_offsets_loaded,
1185 			   &osd->tx_size_big, &nsd->tx_size_big);
1186 
1187 	i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1188 			   pf->stat_offsets_loaded,
1189 			   &osd->rx_undersize, &nsd->rx_undersize);
1190 	i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1191 			   pf->stat_offsets_loaded,
1192 			   &osd->rx_fragments, &nsd->rx_fragments);
1193 	i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1194 			   pf->stat_offsets_loaded,
1195 			   &osd->rx_oversize, &nsd->rx_oversize);
1196 	i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1197 			   pf->stat_offsets_loaded,
1198 			   &osd->rx_jabber, &nsd->rx_jabber);
1199 
1200 	/* FDIR stats */
1201 	i40e_stat_update_and_clear32(hw,
1202 			I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(hw->pf_id)),
1203 			&nsd->fd_atr_match);
1204 	i40e_stat_update_and_clear32(hw,
1205 			I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(hw->pf_id)),
1206 			&nsd->fd_sb_match);
1207 	i40e_stat_update_and_clear32(hw,
1208 			I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(hw->pf_id)),
1209 			&nsd->fd_atr_tunnel_match);
1210 
1211 	val = rd32(hw, I40E_PRTPM_EEE_STAT);
1212 	nsd->tx_lpi_status =
1213 		       FIELD_GET(I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK, val);
1214 	nsd->rx_lpi_status =
1215 		       FIELD_GET(I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK, val);
1216 	i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1217 			   pf->stat_offsets_loaded,
1218 			   &osd->tx_lpi_count, &nsd->tx_lpi_count);
1219 	i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1220 			   pf->stat_offsets_loaded,
1221 			   &osd->rx_lpi_count, &nsd->rx_lpi_count);
1222 
1223 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
1224 	    !test_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
1225 		nsd->fd_sb_status = true;
1226 	else
1227 		nsd->fd_sb_status = false;
1228 
1229 	if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
1230 	    !test_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
1231 		nsd->fd_atr_status = true;
1232 	else
1233 		nsd->fd_atr_status = false;
1234 
1235 	pf->stat_offsets_loaded = true;
1236 }
1237 
1238 /**
1239  * i40e_update_stats - Update the various statistics counters.
1240  * @vsi: the VSI to be updated
1241  *
1242  * Update the various stats for this VSI and its related entities.
1243  **/
1244 void i40e_update_stats(struct i40e_vsi *vsi)
1245 {
1246 	struct i40e_pf *pf = vsi->back;
1247 
1248 	if (vsi->type == I40E_VSI_MAIN)
1249 		i40e_update_pf_stats(pf);
1250 
1251 	i40e_update_vsi_stats(vsi);
1252 }
1253 
1254 /**
1255  * i40e_count_all_filters - counts VSI MAC filters
1256  * @vsi: the VSI to be searched
1257  *
1258  * Return: count of MAC filters in any state.
1259  */
1260 int i40e_count_all_filters(struct i40e_vsi *vsi)
1261 {
1262 	struct i40e_mac_filter *f;
1263 	struct hlist_node *h;
1264 	int bkt, cnt = 0;
1265 
1266 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
1267 		cnt++;
1268 
1269 	return cnt;
1270 }
1271 
1272 /**
1273  * i40e_count_active_filters - counts VSI MAC filters
1274  * @vsi: the VSI to be searched
1275  *
1276  * Return: count of active MAC filters.
1277  */
1278 int i40e_count_active_filters(struct i40e_vsi *vsi)
1279 {
1280 	struct i40e_mac_filter *f;
1281 	struct hlist_node *h;
1282 	int bkt;
1283 	int cnt = 0;
1284 
1285 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1286 		if (f->state == I40E_FILTER_NEW ||
1287 		    f->state == I40E_FILTER_NEW_SYNC ||
1288 		    f->state == I40E_FILTER_ACTIVE)
1289 			++cnt;
1290 	}
1291 
1292 	return cnt;
1293 }
1294 
1295 /**
1296  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1297  * @vsi: the VSI to be searched
1298  * @macaddr: the MAC address
1299  * @vlan: the vlan
1300  *
1301  * Returns ptr to the filter object or NULL
1302  **/
1303 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1304 						const u8 *macaddr, s16 vlan)
1305 {
1306 	struct i40e_mac_filter *f;
1307 	u64 key;
1308 
1309 	if (!vsi || !macaddr)
1310 		return NULL;
1311 
1312 	key = i40e_addr_to_hkey(macaddr);
1313 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1314 		if ((ether_addr_equal(macaddr, f->macaddr)) &&
1315 		    (vlan == f->vlan))
1316 			return f;
1317 	}
1318 	return NULL;
1319 }
1320 
1321 /**
1322  * i40e_find_mac - Find a mac addr in the macvlan filters list
1323  * @vsi: the VSI to be searched
1324  * @macaddr: the MAC address we are searching for
1325  *
1326  * Returns the first filter with the provided MAC address or NULL if
1327  * MAC address was not found
1328  **/
1329 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1330 {
1331 	struct i40e_mac_filter *f;
1332 	u64 key;
1333 
1334 	if (!vsi || !macaddr)
1335 		return NULL;
1336 
1337 	key = i40e_addr_to_hkey(macaddr);
1338 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1339 		if ((ether_addr_equal(macaddr, f->macaddr)))
1340 			return f;
1341 	}
1342 	return NULL;
1343 }
1344 
1345 /**
1346  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1347  * @vsi: the VSI to be searched
1348  *
1349  * Returns true if VSI is in vlan mode or false otherwise
1350  **/
1351 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1352 {
1353 	/* If we have a PVID, always operate in VLAN mode */
1354 	if (vsi->info.pvid)
1355 		return true;
1356 
1357 	/* We need to operate in VLAN mode whenever we have any filters with
1358 	 * a VLAN other than I40E_VLAN_ALL. We could check the table each
1359 	 * time, incurring search cost repeatedly. However, we can notice two
1360 	 * things:
1361 	 *
1362 	 * 1) the only place where we can gain a VLAN filter is in
1363 	 *    i40e_add_filter.
1364 	 *
1365 	 * 2) the only place where filters are actually removed is in
1366 	 *    i40e_sync_filters_subtask.
1367 	 *
1368 	 * Thus, we can simply use a boolean value, has_vlan_filters which we
1369 	 * will set to true when we add a VLAN filter in i40e_add_filter. Then
1370 	 * we have to perform the full search after deleting filters in
1371 	 * i40e_sync_filters_subtask, but we already have to search
1372 	 * filters here and can perform the check at the same time. This
1373 	 * results in avoiding embedding a loop for VLAN mode inside another
1374 	 * loop over all the filters, and should maintain correctness as noted
1375 	 * above.
1376 	 */
1377 	return vsi->has_vlan_filter;
1378 }
1379 
1380 /**
1381  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1382  * @vsi: the VSI to configure
1383  * @tmp_add_list: list of filters ready to be added
1384  * @tmp_del_list: list of filters ready to be deleted
1385  * @vlan_filters: the number of active VLAN filters
1386  *
1387  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1388  * behave as expected. If we have any active VLAN filters remaining or about
1389  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1390  * so that they only match against untagged traffic. If we no longer have any
1391  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1392  * so that they match against both tagged and untagged traffic. In this way,
1393  * we ensure that we correctly receive the desired traffic. This ensures that
1394  * when we have an active VLAN we will receive only untagged traffic and
1395  * traffic matching active VLANs. If we have no active VLANs then we will
1396  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1397  *
1398  * Finally, in a similar fashion, this function also corrects filters when
1399  * there is an active PVID assigned to this VSI.
1400  *
1401  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1402  *
1403  * This function is only expected to be called from within
1404  * i40e_sync_vsi_filters.
1405  *
1406  * NOTE: This function expects to be called while under the
1407  * mac_filter_hash_lock
1408  */
1409 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1410 					 struct hlist_head *tmp_add_list,
1411 					 struct hlist_head *tmp_del_list,
1412 					 int vlan_filters)
1413 {
1414 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1415 	struct i40e_mac_filter *f, *add_head;
1416 	struct i40e_new_mac_filter *new;
1417 	struct hlist_node *h;
1418 	int bkt, new_vlan;
1419 
1420 	/* To determine if a particular filter needs to be replaced we
1421 	 * have the three following conditions:
1422 	 *
1423 	 * a) if we have a PVID assigned, then all filters which are
1424 	 *    not marked as VLAN=PVID must be replaced with filters that
1425 	 *    are.
1426 	 * b) otherwise, if we have any active VLANS, all filters
1427 	 *    which are marked as VLAN=-1 must be replaced with
1428 	 *    filters marked as VLAN=0
1429 	 * c) finally, if we do not have any active VLANS, all filters
1430 	 *    which are marked as VLAN=0 must be replaced with filters
1431 	 *    marked as VLAN=-1
1432 	 */
1433 
1434 	/* Update the filters about to be added in place */
1435 	hlist_for_each_entry(new, tmp_add_list, hlist) {
1436 		if (pvid && new->f->vlan != pvid)
1437 			new->f->vlan = pvid;
1438 		else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1439 			new->f->vlan = 0;
1440 		else if (!vlan_filters && new->f->vlan == 0)
1441 			new->f->vlan = I40E_VLAN_ANY;
1442 	}
1443 
1444 	/* Update the remaining active filters */
1445 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1446 		/* Combine the checks for whether a filter needs to be changed
1447 		 * and then determine the new VLAN inside the if block, in
1448 		 * order to avoid duplicating code for adding the new filter
1449 		 * then deleting the old filter.
1450 		 */
1451 		if ((pvid && f->vlan != pvid) ||
1452 		    (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1453 		    (!vlan_filters && f->vlan == 0)) {
1454 			/* Determine the new vlan we will be adding */
1455 			if (pvid)
1456 				new_vlan = pvid;
1457 			else if (vlan_filters)
1458 				new_vlan = 0;
1459 			else
1460 				new_vlan = I40E_VLAN_ANY;
1461 
1462 			/* Create the new filter */
1463 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1464 			if (!add_head)
1465 				return -ENOMEM;
1466 
1467 			/* Create a temporary i40e_new_mac_filter */
1468 			new = kzalloc_obj(*new, GFP_ATOMIC);
1469 			if (!new)
1470 				return -ENOMEM;
1471 
1472 			new->f = add_head;
1473 			new->state = add_head->state;
1474 			if (add_head->state == I40E_FILTER_NEW)
1475 				add_head->state = I40E_FILTER_NEW_SYNC;
1476 
1477 			/* Add the new filter to the tmp list */
1478 			hlist_add_head(&new->hlist, tmp_add_list);
1479 
1480 			/* Put the original filter into the delete list */
1481 			f->state = I40E_FILTER_REMOVE;
1482 			hash_del(&f->hlist);
1483 			hlist_add_head(&f->hlist, tmp_del_list);
1484 		}
1485 	}
1486 
1487 	vsi->has_vlan_filter = !!vlan_filters;
1488 
1489 	return 0;
1490 }
1491 
1492 /**
1493  * i40e_get_vf_new_vlan - Get new vlan id on a vf
1494  * @vsi: the vsi to configure
1495  * @new_mac: new mac filter to be added
1496  * @f: existing mac filter, replaced with new_mac->f if new_mac is not NULL
1497  * @vlan_filters: the number of active VLAN filters
1498  * @trusted: flag if the VF is trusted
1499  *
1500  * Get new VLAN id based on current VLAN filters, trust, PVID
1501  * and vf-vlan-prune-disable flag.
1502  *
1503  * Returns the value of the new vlan filter or
1504  * the old value if no new filter is needed.
1505  */
1506 static s16 i40e_get_vf_new_vlan(struct i40e_vsi *vsi,
1507 				struct i40e_new_mac_filter *new_mac,
1508 				struct i40e_mac_filter *f,
1509 				int vlan_filters,
1510 				bool trusted)
1511 {
1512 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1513 	struct i40e_pf *pf = vsi->back;
1514 	bool is_any;
1515 
1516 	if (new_mac)
1517 		f = new_mac->f;
1518 
1519 	if (pvid && f->vlan != pvid)
1520 		return pvid;
1521 
1522 	is_any = (trusted ||
1523 		  !test_bit(I40E_FLAG_VF_VLAN_PRUNING_ENA, pf->flags));
1524 
1525 	if ((vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1526 	    (!is_any && !vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1527 	    (is_any && !vlan_filters && f->vlan == 0)) {
1528 		if (is_any)
1529 			return I40E_VLAN_ANY;
1530 		else
1531 			return 0;
1532 	}
1533 
1534 	return f->vlan;
1535 }
1536 
1537 /**
1538  * i40e_correct_vf_mac_vlan_filters - Correct non-VLAN VF filters if necessary
1539  * @vsi: the vsi to configure
1540  * @tmp_add_list: list of filters ready to be added
1541  * @tmp_del_list: list of filters ready to be deleted
1542  * @vlan_filters: the number of active VLAN filters
1543  * @trusted: flag if the VF is trusted
1544  *
1545  * Correct VF VLAN filters based on current VLAN filters, trust, PVID
1546  * and vf-vlan-prune-disable flag.
1547  *
1548  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1549  *
1550  * This function is only expected to be called from within
1551  * i40e_sync_vsi_filters.
1552  *
1553  * NOTE: This function expects to be called while under the
1554  * mac_filter_hash_lock
1555  */
1556 static int i40e_correct_vf_mac_vlan_filters(struct i40e_vsi *vsi,
1557 					    struct hlist_head *tmp_add_list,
1558 					    struct hlist_head *tmp_del_list,
1559 					    int vlan_filters,
1560 					    bool trusted)
1561 {
1562 	struct i40e_mac_filter *f, *add_head;
1563 	struct i40e_new_mac_filter *new_mac;
1564 	struct hlist_node *h;
1565 	int bkt, new_vlan;
1566 
1567 	hlist_for_each_entry(new_mac, tmp_add_list, hlist) {
1568 		new_mac->f->vlan = i40e_get_vf_new_vlan(vsi, new_mac, NULL,
1569 							vlan_filters, trusted);
1570 	}
1571 
1572 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1573 		new_vlan = i40e_get_vf_new_vlan(vsi, NULL, f, vlan_filters,
1574 						trusted);
1575 		if (new_vlan != f->vlan) {
1576 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1577 			if (!add_head)
1578 				return -ENOMEM;
1579 			/* Create a temporary i40e_new_mac_filter */
1580 			new_mac = kzalloc_obj(*new_mac, GFP_ATOMIC);
1581 			if (!new_mac)
1582 				return -ENOMEM;
1583 			new_mac->f = add_head;
1584 			new_mac->state = add_head->state;
1585 			if (add_head->state == I40E_FILTER_NEW)
1586 				add_head->state = I40E_FILTER_NEW_SYNC;
1587 
1588 			/* Add the new filter to the tmp list */
1589 			hlist_add_head(&new_mac->hlist, tmp_add_list);
1590 
1591 			/* Put the original filter into the delete list */
1592 			f->state = I40E_FILTER_REMOVE;
1593 			hash_del(&f->hlist);
1594 			hlist_add_head(&f->hlist, tmp_del_list);
1595 		}
1596 	}
1597 
1598 	vsi->has_vlan_filter = !!vlan_filters;
1599 	return 0;
1600 }
1601 
1602 /**
1603  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1604  * @vsi: the PF Main VSI - inappropriate for any other VSI
1605  * @macaddr: the MAC address
1606  *
1607  * Remove whatever filter the firmware set up so the driver can manage
1608  * its own filtering intelligently.
1609  **/
1610 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1611 {
1612 	struct i40e_aqc_remove_macvlan_element_data element;
1613 	struct i40e_pf *pf = vsi->back;
1614 
1615 	/* Only appropriate for the PF main VSI */
1616 	if (vsi->type != I40E_VSI_MAIN)
1617 		return;
1618 
1619 	memset(&element, 0, sizeof(element));
1620 	ether_addr_copy(element.mac_addr, macaddr);
1621 	element.vlan_tag = 0;
1622 	/* Ignore error returns, some firmware does it this way... */
1623 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1624 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1625 
1626 	memset(&element, 0, sizeof(element));
1627 	ether_addr_copy(element.mac_addr, macaddr);
1628 	element.vlan_tag = 0;
1629 	/* ...and some firmware does it this way. */
1630 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1631 			I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1632 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1633 }
1634 
1635 /**
1636  * i40e_add_filter - Add a mac/vlan filter to the VSI
1637  * @vsi: the VSI to be searched
1638  * @macaddr: the MAC address
1639  * @vlan: the vlan
1640  *
1641  * Returns ptr to the filter object or NULL when no memory available.
1642  *
1643  * NOTE: This function is expected to be called with mac_filter_hash_lock
1644  * being held.
1645  **/
1646 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1647 					const u8 *macaddr, s16 vlan)
1648 {
1649 	struct i40e_mac_filter *f;
1650 	u64 key;
1651 
1652 	if (!vsi || !macaddr)
1653 		return NULL;
1654 
1655 	f = i40e_find_filter(vsi, macaddr, vlan);
1656 	if (!f) {
1657 		f = kzalloc_obj(*f, GFP_ATOMIC);
1658 		if (!f)
1659 			return NULL;
1660 
1661 		/* Update the boolean indicating if we need to function in
1662 		 * VLAN mode.
1663 		 */
1664 		if (vlan >= 0)
1665 			vsi->has_vlan_filter = true;
1666 
1667 		ether_addr_copy(f->macaddr, macaddr);
1668 		f->vlan = vlan;
1669 		f->state = I40E_FILTER_NEW;
1670 		INIT_HLIST_NODE(&f->hlist);
1671 
1672 		key = i40e_addr_to_hkey(macaddr);
1673 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
1674 
1675 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1676 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1677 	}
1678 
1679 	/* If we're asked to add a filter that has been marked for removal, it
1680 	 * is safe to simply restore it to active state. __i40e_del_filter
1681 	 * will have simply deleted any filters which were previously marked
1682 	 * NEW or FAILED, so if it is currently marked REMOVE it must have
1683 	 * previously been ACTIVE. Since we haven't yet run the sync filters
1684 	 * task, just restore this filter to the ACTIVE state so that the
1685 	 * sync task leaves it in place
1686 	 */
1687 	if (f->state == I40E_FILTER_REMOVE)
1688 		f->state = I40E_FILTER_ACTIVE;
1689 
1690 	return f;
1691 }
1692 
1693 /**
1694  * __i40e_del_filter - Remove a specific filter from the VSI
1695  * @vsi: VSI to remove from
1696  * @f: the filter to remove from the list
1697  *
1698  * This function requires you've found * the exact filter you will remove
1699  * already, such as via i40e_find_filter or i40e_find_mac.
1700  *
1701  * NOTE: This function is expected to be called with mac_filter_hash_lock
1702  * being held.
1703  * ANOTHER NOTE: This function MUST be called from within the context of
1704  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1705  * instead of list_for_each_entry().
1706  **/
1707 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1708 {
1709 	if (!f)
1710 		return;
1711 
1712 	/* If the filter was never added to firmware then we can just delete it
1713 	 * directly and we don't want to set the status to remove or else an
1714 	 * admin queue command will unnecessarily fire.
1715 	 */
1716 	if ((f->state == I40E_FILTER_FAILED) ||
1717 	    (f->state == I40E_FILTER_NEW)) {
1718 		hash_del(&f->hlist);
1719 		kfree(f);
1720 	} else {
1721 		f->state = I40E_FILTER_REMOVE;
1722 	}
1723 
1724 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1725 	set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1726 }
1727 
1728 /**
1729  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1730  * @vsi: the VSI to be searched
1731  * @macaddr: the mac address to be filtered
1732  *
1733  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1734  * go through all the macvlan filters and add a macvlan filter for each
1735  * unique vlan that already exists. If a PVID has been assigned, instead only
1736  * add the macaddr to that VLAN.
1737  *
1738  * Returns last filter added on success, else NULL
1739  **/
1740 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1741 					    const u8 *macaddr)
1742 {
1743 	struct i40e_mac_filter *f, *add = NULL;
1744 	struct hlist_node *h;
1745 	int bkt;
1746 
1747 	lockdep_assert_held(&vsi->mac_filter_hash_lock);
1748 	if (vsi->info.pvid)
1749 		return i40e_add_filter(vsi, macaddr,
1750 				       le16_to_cpu(vsi->info.pvid));
1751 
1752 	if (!i40e_is_vsi_in_vlan(vsi))
1753 		return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1754 
1755 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1756 		if (f->state == I40E_FILTER_REMOVE)
1757 			continue;
1758 		add = i40e_add_filter(vsi, macaddr, f->vlan);
1759 		if (!add)
1760 			return NULL;
1761 	}
1762 
1763 	return add;
1764 }
1765 
1766 /**
1767  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1768  * @vsi: the VSI to be searched
1769  * @macaddr: the mac address to be removed
1770  *
1771  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1772  * associated with.
1773  *
1774  * Returns 0 for success, or error
1775  **/
1776 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1777 {
1778 	struct i40e_mac_filter *f;
1779 	struct hlist_node *h;
1780 	bool found = false;
1781 	int bkt;
1782 
1783 	lockdep_assert_held(&vsi->mac_filter_hash_lock);
1784 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1785 		if (ether_addr_equal(macaddr, f->macaddr)) {
1786 			__i40e_del_filter(vsi, f);
1787 			found = true;
1788 		}
1789 	}
1790 
1791 	if (found)
1792 		return 0;
1793 	else
1794 		return -ENOENT;
1795 }
1796 
1797 /**
1798  * i40e_set_mac - NDO callback to set mac address
1799  * @netdev: network interface device structure
1800  * @p: pointer to an address structure
1801  *
1802  * Returns 0 on success, negative on failure
1803  **/
1804 static int i40e_set_mac(struct net_device *netdev, void *p)
1805 {
1806 	struct i40e_netdev_priv *np = netdev_priv(netdev);
1807 	struct i40e_vsi *vsi = np->vsi;
1808 	struct i40e_pf *pf = vsi->back;
1809 	struct i40e_hw *hw = &pf->hw;
1810 	struct sockaddr *addr = p;
1811 
1812 	if (!is_valid_ether_addr(addr->sa_data))
1813 		return -EADDRNOTAVAIL;
1814 
1815 	if (test_bit(__I40E_DOWN, pf->state) ||
1816 	    test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1817 		return -EADDRNOTAVAIL;
1818 
1819 	if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1820 		netdev_info(netdev, "returning to hw mac address %pM\n",
1821 			    hw->mac.addr);
1822 	else
1823 		netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1824 
1825 	/* Copy the address first, so that we avoid a possible race with
1826 	 * .set_rx_mode().
1827 	 * - Remove old address from MAC filter
1828 	 * - Copy new address
1829 	 * - Add new address to MAC filter
1830 	 */
1831 	spin_lock_bh(&vsi->mac_filter_hash_lock);
1832 	i40e_del_mac_filter(vsi, netdev->dev_addr);
1833 	eth_hw_addr_set(netdev, addr->sa_data);
1834 	i40e_add_mac_filter(vsi, netdev->dev_addr);
1835 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
1836 
1837 	if (vsi->type == I40E_VSI_MAIN) {
1838 		int ret;
1839 
1840 		ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1841 						addr->sa_data, NULL);
1842 		if (ret)
1843 			netdev_info(netdev, "Ignoring error from firmware on LAA update, status %pe, AQ ret %s\n",
1844 				    ERR_PTR(ret),
1845 				    libie_aq_str(hw->aq.asq_last_status));
1846 	}
1847 
1848 	/* schedule our worker thread which will take care of
1849 	 * applying the new filter changes
1850 	 */
1851 	i40e_service_event_schedule(pf);
1852 	return 0;
1853 }
1854 
1855 /**
1856  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1857  * @vsi: vsi structure
1858  * @seed: RSS hash seed
1859  * @lut: pointer to lookup table of lut_size
1860  * @lut_size: size of the lookup table
1861  **/
1862 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1863 			      u8 *lut, u16 lut_size)
1864 {
1865 	struct i40e_pf *pf = vsi->back;
1866 	struct i40e_hw *hw = &pf->hw;
1867 	int ret = 0;
1868 
1869 	if (seed) {
1870 		struct i40e_aqc_get_set_rss_key_data *seed_dw =
1871 			(struct i40e_aqc_get_set_rss_key_data *)seed;
1872 		ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1873 		if (ret) {
1874 			dev_info(&pf->pdev->dev,
1875 				 "Cannot set RSS key, err %pe aq_err %s\n",
1876 				 ERR_PTR(ret),
1877 				 libie_aq_str(hw->aq.asq_last_status));
1878 			return ret;
1879 		}
1880 	}
1881 	if (lut) {
1882 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
1883 
1884 		ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1885 		if (ret) {
1886 			dev_info(&pf->pdev->dev,
1887 				 "Cannot set RSS lut, err %pe aq_err %s\n",
1888 				 ERR_PTR(ret),
1889 				 libie_aq_str(hw->aq.asq_last_status));
1890 			return ret;
1891 		}
1892 	}
1893 	return ret;
1894 }
1895 
1896 /**
1897  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1898  * @vsi: VSI structure
1899  **/
1900 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1901 {
1902 	struct i40e_pf *pf = vsi->back;
1903 	u8 seed[I40E_HKEY_ARRAY_SIZE];
1904 	u8 *lut;
1905 	int ret;
1906 
1907 	if (!test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
1908 		return 0;
1909 	if (!vsi->rss_size)
1910 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
1911 				      vsi->num_queue_pairs);
1912 	if (!vsi->rss_size)
1913 		return -EINVAL;
1914 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1915 	if (!lut)
1916 		return -ENOMEM;
1917 
1918 	/* Use the user configured hash keys and lookup table if there is one,
1919 	 * otherwise use default
1920 	 */
1921 	if (vsi->rss_lut_user)
1922 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1923 	else
1924 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1925 	if (vsi->rss_hkey_user)
1926 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1927 	else
1928 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1929 	ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1930 	kfree(lut);
1931 	return ret;
1932 }
1933 
1934 /**
1935  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1936  * @vsi: the VSI being configured,
1937  * @ctxt: VSI context structure
1938  * @enabled_tc: number of traffic classes to enable
1939  *
1940  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1941  **/
1942 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1943 					   struct i40e_vsi_context *ctxt,
1944 					   u8 enabled_tc)
1945 {
1946 	u16 qcount = 0, max_qcount, qmap, sections = 0;
1947 	int i, override_q, pow, num_qps, ret;
1948 	u8 netdev_tc = 0, offset = 0;
1949 
1950 	if (vsi->type != I40E_VSI_MAIN)
1951 		return -EINVAL;
1952 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1953 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1954 	vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1955 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1956 	num_qps = vsi->mqprio_qopt.qopt.count[0];
1957 
1958 	/* find the next higher power-of-2 of num queue pairs */
1959 	pow = ilog2(num_qps);
1960 	if (!is_power_of_2(num_qps))
1961 		pow++;
1962 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1963 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1964 
1965 	/* Setup queue offset/count for all TCs for given VSI */
1966 	max_qcount = vsi->mqprio_qopt.qopt.count[0];
1967 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1968 		/* See if the given TC is enabled for the given VSI */
1969 		if (vsi->tc_config.enabled_tc & BIT(i)) {
1970 			offset = vsi->mqprio_qopt.qopt.offset[i];
1971 			qcount = vsi->mqprio_qopt.qopt.count[i];
1972 			if (qcount > max_qcount)
1973 				max_qcount = qcount;
1974 			vsi->tc_config.tc_info[i].qoffset = offset;
1975 			vsi->tc_config.tc_info[i].qcount = qcount;
1976 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1977 		} else {
1978 			/* TC is not enabled so set the offset to
1979 			 * default queue and allocate one queue
1980 			 * for the given TC.
1981 			 */
1982 			vsi->tc_config.tc_info[i].qoffset = 0;
1983 			vsi->tc_config.tc_info[i].qcount = 1;
1984 			vsi->tc_config.tc_info[i].netdev_tc = 0;
1985 		}
1986 	}
1987 
1988 	/* Set actual Tx/Rx queue pairs */
1989 	vsi->num_queue_pairs = offset + qcount;
1990 
1991 	/* Setup queue TC[0].qmap for given VSI context */
1992 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1993 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1994 	ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1995 	ctxt->info.valid_sections |= cpu_to_le16(sections);
1996 
1997 	/* Reconfigure RSS for main VSI with max queue count */
1998 	vsi->rss_size = max_qcount;
1999 	ret = i40e_vsi_config_rss(vsi);
2000 	if (ret) {
2001 		dev_info(&vsi->back->pdev->dev,
2002 			 "Failed to reconfig rss for num_queues (%u)\n",
2003 			 max_qcount);
2004 		return ret;
2005 	}
2006 	vsi->reconfig_rss = true;
2007 	dev_dbg(&vsi->back->pdev->dev,
2008 		"Reconfigured rss with num_queues (%u)\n", max_qcount);
2009 
2010 	/* Find queue count available for channel VSIs and starting offset
2011 	 * for channel VSIs
2012 	 */
2013 	override_q = vsi->mqprio_qopt.qopt.count[0];
2014 	if (override_q && override_q < vsi->num_queue_pairs) {
2015 		vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
2016 		vsi->next_base_queue = override_q;
2017 	}
2018 	return 0;
2019 }
2020 
2021 /**
2022  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
2023  * @vsi: the VSI being setup
2024  * @ctxt: VSI context structure
2025  * @enabled_tc: Enabled TCs bitmap
2026  * @is_add: True if called before Add VSI
2027  *
2028  * Setup VSI queue mapping for enabled traffic classes.
2029  **/
2030 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
2031 				     struct i40e_vsi_context *ctxt,
2032 				     u8 enabled_tc,
2033 				     bool is_add)
2034 {
2035 	struct i40e_pf *pf = vsi->back;
2036 	u16 num_tc_qps = 0;
2037 	u16 sections = 0;
2038 	u8 netdev_tc = 0;
2039 	u16 numtc = 1;
2040 	u16 qcount;
2041 	u8 offset;
2042 	u16 qmap;
2043 	int i;
2044 
2045 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
2046 	offset = 0;
2047 	/* zero out queue mapping, it will get updated on the end of the function */
2048 	memset(ctxt->info.queue_mapping, 0, sizeof(ctxt->info.queue_mapping));
2049 
2050 	if (vsi->type == I40E_VSI_MAIN) {
2051 		/* This code helps add more queue to the VSI if we have
2052 		 * more cores than RSS can support, the higher cores will
2053 		 * be served by ATR or other filters. Furthermore, the
2054 		 * non-zero req_queue_pairs says that user requested a new
2055 		 * queue count via ethtool's set_channels, so use this
2056 		 * value for queues distribution across traffic classes
2057 		 * We need at least one queue pair for the interface
2058 		 * to be usable as we see in else statement.
2059 		 */
2060 		if (vsi->req_queue_pairs > 0)
2061 			vsi->num_queue_pairs = vsi->req_queue_pairs;
2062 		else if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
2063 			vsi->num_queue_pairs = pf->num_lan_msix;
2064 		else
2065 			vsi->num_queue_pairs = 1;
2066 	}
2067 
2068 	/* Number of queues per enabled TC */
2069 	if (vsi->type == I40E_VSI_MAIN ||
2070 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs != 0))
2071 		num_tc_qps = vsi->num_queue_pairs;
2072 	else
2073 		num_tc_qps = vsi->alloc_queue_pairs;
2074 
2075 	if (enabled_tc && test_bit(I40E_FLAG_DCB_ENA, vsi->back->flags)) {
2076 		/* Find numtc from enabled TC bitmap */
2077 		for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2078 			if (enabled_tc & BIT(i)) /* TC is enabled */
2079 				numtc++;
2080 		}
2081 		if (!numtc) {
2082 			dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
2083 			numtc = 1;
2084 		}
2085 		num_tc_qps = num_tc_qps / numtc;
2086 		num_tc_qps = min_t(int, num_tc_qps,
2087 				   i40e_pf_get_max_q_per_tc(pf));
2088 	}
2089 
2090 	vsi->tc_config.numtc = numtc;
2091 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
2092 
2093 	/* Do not allow use more TC queue pairs than MSI-X vectors exist */
2094 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
2095 		num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
2096 
2097 	/* Setup queue offset/count for all TCs for given VSI */
2098 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2099 		/* See if the given TC is enabled for the given VSI */
2100 		if (vsi->tc_config.enabled_tc & BIT(i)) {
2101 			/* TC is enabled */
2102 			int pow, num_qps;
2103 
2104 			switch (vsi->type) {
2105 			case I40E_VSI_MAIN:
2106 				if ((!test_bit(I40E_FLAG_FD_SB_ENA,
2107 					       pf->flags) &&
2108 				     !test_bit(I40E_FLAG_FD_ATR_ENA,
2109 					       pf->flags)) ||
2110 				    vsi->tc_config.enabled_tc != 1) {
2111 					qcount = min_t(int, pf->alloc_rss_size,
2112 						       num_tc_qps);
2113 					break;
2114 				}
2115 				fallthrough;
2116 			case I40E_VSI_FDIR:
2117 			case I40E_VSI_SRIOV:
2118 			case I40E_VSI_VMDQ2:
2119 			default:
2120 				qcount = num_tc_qps;
2121 				WARN_ON(i != 0);
2122 				break;
2123 			}
2124 			vsi->tc_config.tc_info[i].qoffset = offset;
2125 			vsi->tc_config.tc_info[i].qcount = qcount;
2126 
2127 			/* find the next higher power-of-2 of num queue pairs */
2128 			num_qps = qcount;
2129 			pow = 0;
2130 			while (num_qps && (BIT_ULL(pow) < qcount)) {
2131 				pow++;
2132 				num_qps >>= 1;
2133 			}
2134 
2135 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
2136 			qmap =
2137 			    (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
2138 			    (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
2139 
2140 			offset += qcount;
2141 		} else {
2142 			/* TC is not enabled so set the offset to
2143 			 * default queue and allocate one queue
2144 			 * for the given TC.
2145 			 */
2146 			vsi->tc_config.tc_info[i].qoffset = 0;
2147 			vsi->tc_config.tc_info[i].qcount = 1;
2148 			vsi->tc_config.tc_info[i].netdev_tc = 0;
2149 
2150 			qmap = 0;
2151 		}
2152 		ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
2153 	}
2154 	/* Do not change previously set num_queue_pairs for PFs and VFs*/
2155 	if ((vsi->type == I40E_VSI_MAIN && numtc != 1) ||
2156 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs == 0) ||
2157 	    (vsi->type != I40E_VSI_MAIN && vsi->type != I40E_VSI_SRIOV))
2158 		vsi->num_queue_pairs = offset;
2159 
2160 	/* Scheduler section valid can only be set for ADD VSI */
2161 	if (is_add) {
2162 		sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
2163 
2164 		ctxt->info.up_enable_bits = enabled_tc;
2165 	}
2166 	if (vsi->type == I40E_VSI_SRIOV) {
2167 		ctxt->info.mapping_flags |=
2168 				     cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
2169 		for (i = 0; i < vsi->num_queue_pairs; i++)
2170 			ctxt->info.queue_mapping[i] =
2171 					       cpu_to_le16(vsi->base_queue + i);
2172 	} else {
2173 		ctxt->info.mapping_flags |=
2174 					cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
2175 		ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
2176 	}
2177 	ctxt->info.valid_sections |= cpu_to_le16(sections);
2178 }
2179 
2180 /**
2181  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
2182  * @netdev: the netdevice
2183  * @addr: address to add
2184  *
2185  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
2186  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2187  */
2188 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
2189 {
2190 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2191 	struct i40e_vsi *vsi = np->vsi;
2192 
2193 	if (i40e_add_mac_filter(vsi, addr))
2194 		return 0;
2195 	else
2196 		return -ENOMEM;
2197 }
2198 
2199 /**
2200  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
2201  * @netdev: the netdevice
2202  * @addr: address to add
2203  *
2204  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
2205  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2206  */
2207 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
2208 {
2209 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2210 	struct i40e_vsi *vsi = np->vsi;
2211 
2212 	/* Under some circumstances, we might receive a request to delete
2213 	 * our own device address from our uc list. Because we store the
2214 	 * device address in the VSI's MAC/VLAN filter list, we need to ignore
2215 	 * such requests and not delete our device address from this list.
2216 	 */
2217 	if (ether_addr_equal(addr, netdev->dev_addr))
2218 		return 0;
2219 
2220 	i40e_del_mac_filter(vsi, addr);
2221 
2222 	return 0;
2223 }
2224 
2225 /**
2226  * i40e_set_rx_mode - NDO callback to set the netdev filters
2227  * @netdev: network interface device structure
2228  **/
2229 static void i40e_set_rx_mode(struct net_device *netdev)
2230 {
2231 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2232 	struct i40e_vsi *vsi = np->vsi;
2233 
2234 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2235 
2236 	__dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2237 	__dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2238 
2239 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2240 
2241 	/* check for other flag changes */
2242 	if (vsi->current_netdev_flags != vsi->netdev->flags) {
2243 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2244 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
2245 	}
2246 	i40e_service_event_schedule(vsi->back);
2247 }
2248 
2249 /**
2250  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
2251  * @vsi: Pointer to VSI struct
2252  * @from: Pointer to list which contains MAC filter entries - changes to
2253  *        those entries needs to be undone.
2254  *
2255  * MAC filter entries from this list were slated for deletion.
2256  **/
2257 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
2258 					 struct hlist_head *from)
2259 {
2260 	struct i40e_mac_filter *f;
2261 	struct hlist_node *h;
2262 
2263 	hlist_for_each_entry_safe(f, h, from, hlist) {
2264 		u64 key = i40e_addr_to_hkey(f->macaddr);
2265 
2266 		/* Move the element back into MAC filter list*/
2267 		hlist_del(&f->hlist);
2268 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
2269 	}
2270 }
2271 
2272 /**
2273  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
2274  * @vsi: Pointer to vsi struct
2275  * @from: Pointer to list which contains MAC filter entries - changes to
2276  *        those entries needs to be undone.
2277  *
2278  * MAC filter entries from this list were slated for addition.
2279  **/
2280 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
2281 					 struct hlist_head *from)
2282 {
2283 	struct i40e_new_mac_filter *new;
2284 	struct hlist_node *h;
2285 
2286 	hlist_for_each_entry_safe(new, h, from, hlist) {
2287 		/* We can simply free the wrapper structure */
2288 		hlist_del(&new->hlist);
2289 		netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2290 		kfree(new);
2291 	}
2292 }
2293 
2294 /**
2295  * i40e_next_filter - Get the next non-broadcast filter from a list
2296  * @next: pointer to filter in list
2297  *
2298  * Returns the next non-broadcast filter in the list. Required so that we
2299  * ignore broadcast filters within the list, since these are not handled via
2300  * the normal firmware update path.
2301  */
2302 static
2303 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2304 {
2305 	hlist_for_each_entry_continue(next, hlist) {
2306 		if (!is_broadcast_ether_addr(next->f->macaddr))
2307 			return next;
2308 	}
2309 
2310 	return NULL;
2311 }
2312 
2313 /**
2314  * i40e_update_filter_state - Update filter state based on return data
2315  * from firmware
2316  * @count: Number of filters added
2317  * @add_list: return data from fw
2318  * @add_head: pointer to first filter in current batch
2319  *
2320  * MAC filter entries from list were slated to be added to device. Returns
2321  * number of successful filters. Note that 0 does NOT mean success!
2322  **/
2323 static int
2324 i40e_update_filter_state(int count,
2325 			 struct i40e_aqc_add_macvlan_element_data *add_list,
2326 			 struct i40e_new_mac_filter *add_head)
2327 {
2328 	int retval = 0;
2329 	int i;
2330 
2331 	for (i = 0; i < count; i++) {
2332 		/* Always check status of each filter. We don't need to check
2333 		 * the firmware return status because we pre-set the filter
2334 		 * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2335 		 * request to the adminq. Thus, if it no longer matches then
2336 		 * we know the filter is active.
2337 		 */
2338 		if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2339 			add_head->state = I40E_FILTER_FAILED;
2340 		} else {
2341 			add_head->state = I40E_FILTER_ACTIVE;
2342 			retval++;
2343 		}
2344 
2345 		add_head = i40e_next_filter(add_head);
2346 		if (!add_head)
2347 			break;
2348 	}
2349 
2350 	return retval;
2351 }
2352 
2353 /**
2354  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2355  * @vsi: ptr to the VSI
2356  * @vsi_name: name to display in messages
2357  * @list: the list of filters to send to firmware
2358  * @num_del: the number of filters to delete
2359  * @retval: Set to -EIO on failure to delete
2360  *
2361  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2362  * *retval instead of a return value so that success does not force ret_val to
2363  * be set to 0. This ensures that a sequence of calls to this function
2364  * preserve the previous value of *retval on successful delete.
2365  */
2366 static
2367 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2368 			  struct i40e_aqc_remove_macvlan_element_data *list,
2369 			  int num_del, int *retval)
2370 {
2371 	struct i40e_hw *hw = &vsi->back->hw;
2372 	enum libie_aq_err aq_status;
2373 	int aq_ret;
2374 
2375 	aq_ret = i40e_aq_remove_macvlan_v2(hw, vsi->seid, list, num_del, NULL,
2376 					   &aq_status);
2377 
2378 	/* Explicitly ignore and do not report when firmware returns ENOENT */
2379 	if (aq_ret && !(aq_status == LIBIE_AQ_RC_ENOENT)) {
2380 		*retval = -EIO;
2381 		dev_info(&vsi->back->pdev->dev,
2382 			 "ignoring delete macvlan error on %s, err %pe, aq_err %s\n",
2383 			 vsi_name, ERR_PTR(aq_ret), libie_aq_str(aq_status));
2384 	}
2385 }
2386 
2387 /**
2388  * i40e_aqc_add_filters - Request firmware to add a set of filters
2389  * @vsi: ptr to the VSI
2390  * @vsi_name: name to display in messages
2391  * @list: the list of filters to send to firmware
2392  * @add_head: Position in the add hlist
2393  * @num_add: the number of filters to add
2394  *
2395  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2396  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2397  * space for more filters.
2398  */
2399 static
2400 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2401 			  struct i40e_aqc_add_macvlan_element_data *list,
2402 			  struct i40e_new_mac_filter *add_head,
2403 			  int num_add)
2404 {
2405 	struct i40e_hw *hw = &vsi->back->hw;
2406 	enum libie_aq_err aq_status;
2407 	int fcnt;
2408 
2409 	i40e_aq_add_macvlan_v2(hw, vsi->seid, list, num_add, NULL, &aq_status);
2410 	fcnt = i40e_update_filter_state(num_add, list, add_head);
2411 
2412 	if (fcnt != num_add) {
2413 		if (vsi->type == I40E_VSI_MAIN) {
2414 			set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2415 			dev_warn(&vsi->back->pdev->dev,
2416 				 "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2417 				 libie_aq_str(aq_status), vsi_name);
2418 		} else if (vsi->type == I40E_VSI_SRIOV ||
2419 			   vsi->type == I40E_VSI_VMDQ1 ||
2420 			   vsi->type == I40E_VSI_VMDQ2) {
2421 			dev_warn(&vsi->back->pdev->dev,
2422 				 "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2423 				 libie_aq_str(aq_status), vsi_name, vsi_name);
2424 		} else {
2425 			dev_warn(&vsi->back->pdev->dev,
2426 				 "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2427 				 libie_aq_str(aq_status), vsi_name, vsi->type);
2428 		}
2429 	}
2430 }
2431 
2432 /**
2433  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2434  * @vsi: pointer to the VSI
2435  * @vsi_name: the VSI name
2436  * @f: filter data
2437  *
2438  * This function sets or clears the promiscuous broadcast flags for VLAN
2439  * filters in order to properly receive broadcast frames. Assumes that only
2440  * broadcast filters are passed.
2441  *
2442  * Returns status indicating success or failure;
2443  **/
2444 static int
2445 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2446 			  struct i40e_mac_filter *f)
2447 {
2448 	bool enable = f->state == I40E_FILTER_NEW ||
2449 		      f->state == I40E_FILTER_NEW_SYNC;
2450 	struct i40e_hw *hw = &vsi->back->hw;
2451 	int aq_ret;
2452 
2453 	if (f->vlan == I40E_VLAN_ANY) {
2454 		aq_ret = i40e_aq_set_vsi_broadcast(hw,
2455 						   vsi->seid,
2456 						   enable,
2457 						   NULL);
2458 	} else {
2459 		aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2460 							    vsi->seid,
2461 							    enable,
2462 							    f->vlan,
2463 							    NULL);
2464 	}
2465 
2466 	if (aq_ret) {
2467 		set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2468 		dev_warn(&vsi->back->pdev->dev,
2469 			 "Error %s, forcing overflow promiscuous on %s\n",
2470 			 libie_aq_str(hw->aq.asq_last_status), vsi_name);
2471 	}
2472 
2473 	return aq_ret;
2474 }
2475 
2476 /**
2477  * i40e_set_promiscuous - set promiscuous mode
2478  * @pf: board private structure
2479  * @promisc: promisc on or off
2480  *
2481  * There are different ways of setting promiscuous mode on a PF depending on
2482  * what state/environment we're in.  This identifies and sets it appropriately.
2483  * Returns 0 on success.
2484  **/
2485 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2486 {
2487 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
2488 	struct i40e_hw *hw = &pf->hw;
2489 	int aq_ret;
2490 
2491 	if (vsi->type == I40E_VSI_MAIN &&
2492 	    i40e_pf_get_main_veb(pf) &&
2493 	    !test_bit(I40E_FLAG_MFP_ENA, pf->flags)) {
2494 		/* set defport ON for Main VSI instead of true promisc
2495 		 * this way we will get all unicast/multicast and VLAN
2496 		 * promisc behavior but will not get VF or VMDq traffic
2497 		 * replicated on the Main VSI.
2498 		 */
2499 		if (promisc)
2500 			aq_ret = i40e_aq_set_default_vsi(hw,
2501 							 vsi->seid,
2502 							 NULL);
2503 		else
2504 			aq_ret = i40e_aq_clear_default_vsi(hw,
2505 							   vsi->seid,
2506 							   NULL);
2507 		if (aq_ret) {
2508 			dev_info(&pf->pdev->dev,
2509 				 "Set default VSI failed, err %pe, aq_err %s\n",
2510 				 ERR_PTR(aq_ret),
2511 				 libie_aq_str(hw->aq.asq_last_status));
2512 		}
2513 	} else {
2514 		aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2515 						  hw,
2516 						  vsi->seid,
2517 						  promisc, NULL,
2518 						  true);
2519 		if (aq_ret) {
2520 			dev_info(&pf->pdev->dev,
2521 				 "set unicast promisc failed, err %pe, aq_err %s\n",
2522 				 ERR_PTR(aq_ret),
2523 				 libie_aq_str(hw->aq.asq_last_status));
2524 		}
2525 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2526 						  hw,
2527 						  vsi->seid,
2528 						  promisc, NULL);
2529 		if (aq_ret) {
2530 			dev_info(&pf->pdev->dev,
2531 				 "set multicast promisc failed, err %pe, aq_err %s\n",
2532 				 ERR_PTR(aq_ret),
2533 				 libie_aq_str(hw->aq.asq_last_status));
2534 		}
2535 	}
2536 
2537 	if (!aq_ret)
2538 		pf->cur_promisc = promisc;
2539 
2540 	return aq_ret;
2541 }
2542 
2543 /**
2544  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2545  * @vsi: ptr to the VSI
2546  *
2547  * Push any outstanding VSI filter changes through the AdminQ.
2548  *
2549  * Returns 0 or error value
2550  **/
2551 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2552 {
2553 	struct hlist_head tmp_add_list, tmp_del_list;
2554 	struct i40e_mac_filter *f;
2555 	struct i40e_new_mac_filter *new, *add_head = NULL;
2556 	struct i40e_hw *hw = &vsi->back->hw;
2557 	bool old_overflow, new_overflow;
2558 	unsigned int failed_filters = 0;
2559 	unsigned int vlan_filters = 0;
2560 	char vsi_name[16] = "PF";
2561 	int filter_list_len = 0;
2562 	u32 changed_flags = 0;
2563 	struct hlist_node *h;
2564 	struct i40e_pf *pf;
2565 	int num_add = 0;
2566 	int num_del = 0;
2567 	int aq_ret = 0;
2568 	int retval = 0;
2569 	u16 cmd_flags;
2570 	int list_size;
2571 	int bkt;
2572 
2573 	/* empty array typed pointers, kcalloc later */
2574 	struct i40e_aqc_add_macvlan_element_data *add_list;
2575 	struct i40e_aqc_remove_macvlan_element_data *del_list;
2576 
2577 	while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2578 		usleep_range(1000, 2000);
2579 	pf = vsi->back;
2580 
2581 	old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2582 
2583 	if (vsi->netdev) {
2584 		changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2585 		vsi->current_netdev_flags = vsi->netdev->flags;
2586 	}
2587 
2588 	INIT_HLIST_HEAD(&tmp_add_list);
2589 	INIT_HLIST_HEAD(&tmp_del_list);
2590 
2591 	if (vsi->type == I40E_VSI_SRIOV)
2592 		snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2593 	else if (vsi->type != I40E_VSI_MAIN)
2594 		snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2595 
2596 	if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2597 		vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2598 
2599 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2600 		/* Create a list of filters to delete. */
2601 		hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2602 			if (f->state == I40E_FILTER_REMOVE) {
2603 				/* Move the element into temporary del_list */
2604 				hash_del(&f->hlist);
2605 				hlist_add_head(&f->hlist, &tmp_del_list);
2606 
2607 				/* Avoid counting removed filters */
2608 				continue;
2609 			}
2610 			if (f->state == I40E_FILTER_NEW) {
2611 				/* Create a temporary i40e_new_mac_filter */
2612 				new = kzalloc_obj(*new, GFP_ATOMIC);
2613 				if (!new)
2614 					goto err_no_memory_locked;
2615 
2616 				/* Store pointer to the real filter */
2617 				new->f = f;
2618 				new->state = f->state;
2619 
2620 				/* Add it to the hash list */
2621 				hlist_add_head(&new->hlist, &tmp_add_list);
2622 				f->state = I40E_FILTER_NEW_SYNC;
2623 			}
2624 
2625 			/* Count the number of active (current and new) VLAN
2626 			 * filters we have now. Does not count filters which
2627 			 * are marked for deletion.
2628 			 */
2629 			if (f->vlan > 0)
2630 				vlan_filters++;
2631 		}
2632 
2633 		if (vsi->type != I40E_VSI_SRIOV)
2634 			retval = i40e_correct_mac_vlan_filters
2635 				(vsi, &tmp_add_list, &tmp_del_list,
2636 				 vlan_filters);
2637 		else if (pf->vf)
2638 			retval = i40e_correct_vf_mac_vlan_filters
2639 				(vsi, &tmp_add_list, &tmp_del_list,
2640 				 vlan_filters, pf->vf[vsi->vf_id].trusted);
2641 
2642 		hlist_for_each_entry(new, &tmp_add_list, hlist)
2643 			netdev_hw_addr_refcnt(new->f, vsi->netdev, 1);
2644 
2645 		if (retval)
2646 			goto err_no_memory_locked;
2647 
2648 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2649 	}
2650 
2651 	/* Now process 'del_list' outside the lock */
2652 	if (!hlist_empty(&tmp_del_list)) {
2653 		filter_list_len = hw->aq.asq_buf_size /
2654 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2655 		list_size = filter_list_len *
2656 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2657 		del_list = kzalloc(list_size, GFP_ATOMIC);
2658 		if (!del_list)
2659 			goto err_no_memory;
2660 
2661 		hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2662 			cmd_flags = 0;
2663 
2664 			/* handle broadcast filters by updating the broadcast
2665 			 * promiscuous flag and release filter list.
2666 			 */
2667 			if (is_broadcast_ether_addr(f->macaddr)) {
2668 				i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2669 
2670 				hlist_del(&f->hlist);
2671 				kfree(f);
2672 				continue;
2673 			}
2674 
2675 			/* add to delete list */
2676 			ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2677 			if (f->vlan == I40E_VLAN_ANY) {
2678 				del_list[num_del].vlan_tag = 0;
2679 				cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2680 			} else {
2681 				del_list[num_del].vlan_tag =
2682 					cpu_to_le16((u16)(f->vlan));
2683 			}
2684 
2685 			cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2686 			del_list[num_del].flags = cmd_flags;
2687 			num_del++;
2688 
2689 			/* flush a full buffer */
2690 			if (num_del == filter_list_len) {
2691 				i40e_aqc_del_filters(vsi, vsi_name, del_list,
2692 						     num_del, &retval);
2693 				memset(del_list, 0, list_size);
2694 				num_del = 0;
2695 			}
2696 			/* Release memory for MAC filter entries which were
2697 			 * synced up with HW.
2698 			 */
2699 			hlist_del(&f->hlist);
2700 			kfree(f);
2701 		}
2702 
2703 		if (num_del) {
2704 			i40e_aqc_del_filters(vsi, vsi_name, del_list,
2705 					     num_del, &retval);
2706 		}
2707 
2708 		kfree(del_list);
2709 		del_list = NULL;
2710 	}
2711 
2712 	if (!hlist_empty(&tmp_add_list)) {
2713 		/* Do all the adds now. */
2714 		filter_list_len = hw->aq.asq_buf_size /
2715 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2716 		list_size = filter_list_len *
2717 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2718 		add_list = kzalloc(list_size, GFP_ATOMIC);
2719 		if (!add_list)
2720 			goto err_no_memory;
2721 
2722 		num_add = 0;
2723 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2724 			/* handle broadcast filters by updating the broadcast
2725 			 * promiscuous flag instead of adding a MAC filter.
2726 			 */
2727 			if (is_broadcast_ether_addr(new->f->macaddr)) {
2728 				if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2729 							      new->f))
2730 					new->state = I40E_FILTER_FAILED;
2731 				else
2732 					new->state = I40E_FILTER_ACTIVE;
2733 				continue;
2734 			}
2735 
2736 			/* add to add array */
2737 			if (num_add == 0)
2738 				add_head = new;
2739 			cmd_flags = 0;
2740 			ether_addr_copy(add_list[num_add].mac_addr,
2741 					new->f->macaddr);
2742 			if (new->f->vlan == I40E_VLAN_ANY) {
2743 				add_list[num_add].vlan_tag = 0;
2744 				cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2745 			} else {
2746 				add_list[num_add].vlan_tag =
2747 					cpu_to_le16((u16)(new->f->vlan));
2748 			}
2749 			add_list[num_add].queue_number = 0;
2750 			/* set invalid match method for later detection */
2751 			add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2752 			cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2753 			add_list[num_add].flags = cpu_to_le16(cmd_flags);
2754 			num_add++;
2755 
2756 			/* flush a full buffer */
2757 			if (num_add == filter_list_len) {
2758 				i40e_aqc_add_filters(vsi, vsi_name, add_list,
2759 						     add_head, num_add);
2760 				memset(add_list, 0, list_size);
2761 				num_add = 0;
2762 			}
2763 		}
2764 		if (num_add) {
2765 			i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2766 					     num_add);
2767 		}
2768 		/* Now move all of the filters from the temp add list back to
2769 		 * the VSI's list.
2770 		 */
2771 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2772 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2773 			/* Only update the state if we're still NEW */
2774 			if (new->f->state == I40E_FILTER_NEW ||
2775 			    new->f->state == I40E_FILTER_NEW_SYNC)
2776 				new->f->state = new->state;
2777 			hlist_del(&new->hlist);
2778 			netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2779 			kfree(new);
2780 		}
2781 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2782 		kfree(add_list);
2783 		add_list = NULL;
2784 	}
2785 
2786 	/* Determine the number of active and failed filters. */
2787 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2788 	vsi->active_filters = 0;
2789 	hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2790 		if (f->state == I40E_FILTER_ACTIVE)
2791 			vsi->active_filters++;
2792 		else if (f->state == I40E_FILTER_FAILED)
2793 			failed_filters++;
2794 	}
2795 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2796 
2797 	/* Check if we are able to exit overflow promiscuous mode. We can
2798 	 * safely exit if we didn't just enter, we no longer have any failed
2799 	 * filters, and we have reduced filters below the threshold value.
2800 	 */
2801 	if (old_overflow && !failed_filters &&
2802 	    vsi->active_filters < vsi->promisc_threshold) {
2803 		dev_info(&pf->pdev->dev,
2804 			 "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2805 			 vsi_name);
2806 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2807 		vsi->promisc_threshold = 0;
2808 	}
2809 
2810 	/* if the VF is not trusted do not do promisc */
2811 	if (vsi->type == I40E_VSI_SRIOV && pf->vf &&
2812 	    !pf->vf[vsi->vf_id].trusted) {
2813 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2814 		goto out;
2815 	}
2816 
2817 	new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2818 
2819 	/* If we are entering overflow promiscuous, we need to calculate a new
2820 	 * threshold for when we are safe to exit
2821 	 */
2822 	if (!old_overflow && new_overflow)
2823 		vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2824 
2825 	/* check for changes in promiscuous modes */
2826 	if (changed_flags & IFF_ALLMULTI) {
2827 		bool cur_multipromisc;
2828 
2829 		cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2830 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2831 							       vsi->seid,
2832 							       cur_multipromisc,
2833 							       NULL);
2834 		if (aq_ret) {
2835 			retval = i40e_aq_rc_to_posix(aq_ret,
2836 						     hw->aq.asq_last_status);
2837 			dev_info(&pf->pdev->dev,
2838 				 "set multi promisc failed on %s, err %pe aq_err %s\n",
2839 				 vsi_name,
2840 				 ERR_PTR(aq_ret),
2841 				 libie_aq_str(hw->aq.asq_last_status));
2842 		} else {
2843 			dev_info(&pf->pdev->dev, "%s allmulti mode.\n",
2844 				 cur_multipromisc ? "entering" : "leaving");
2845 		}
2846 	}
2847 
2848 	if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2849 		bool cur_promisc;
2850 
2851 		cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2852 			       new_overflow);
2853 		aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2854 		if (aq_ret) {
2855 			retval = i40e_aq_rc_to_posix(aq_ret,
2856 						     hw->aq.asq_last_status);
2857 			dev_info(&pf->pdev->dev,
2858 				 "Setting promiscuous %s failed on %s, err %pe aq_err %s\n",
2859 				 cur_promisc ? "on" : "off",
2860 				 vsi_name,
2861 				 ERR_PTR(aq_ret),
2862 				 libie_aq_str(hw->aq.asq_last_status));
2863 		}
2864 	}
2865 out:
2866 	/* if something went wrong then set the changed flag so we try again */
2867 	if (retval)
2868 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2869 
2870 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2871 	return retval;
2872 
2873 err_no_memory:
2874 	/* Restore elements on the temporary add and delete lists */
2875 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2876 err_no_memory_locked:
2877 	i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2878 	i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2879 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2880 
2881 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2882 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2883 	return -ENOMEM;
2884 }
2885 
2886 /**
2887  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2888  * @pf: board private structure
2889  **/
2890 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2891 {
2892 	struct i40e_vsi *vsi;
2893 	int v;
2894 
2895 	if (!pf)
2896 		return;
2897 	if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2898 		return;
2899 	if (test_bit(__I40E_VF_DISABLE, pf->state)) {
2900 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
2901 		return;
2902 	}
2903 
2904 	i40e_pf_for_each_vsi(pf, v, vsi) {
2905 		if ((vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) &&
2906 		    !test_bit(__I40E_VSI_RELEASING, vsi->state)) {
2907 			int ret = i40e_sync_vsi_filters(vsi);
2908 
2909 			if (ret) {
2910 				/* come back and try again later */
2911 				set_bit(__I40E_MACVLAN_SYNC_PENDING,
2912 					pf->state);
2913 				break;
2914 			}
2915 		}
2916 	}
2917 }
2918 
2919 /**
2920  * i40e_calculate_vsi_rx_buf_len - Calculates buffer length
2921  *
2922  * @vsi: VSI to calculate rx_buf_len from
2923  */
2924 static u16 i40e_calculate_vsi_rx_buf_len(struct i40e_vsi *vsi)
2925 {
2926 	if (!vsi->netdev || test_bit(I40E_FLAG_LEGACY_RX_ENA, vsi->back->flags))
2927 		return SKB_WITH_OVERHEAD(I40E_RXBUFFER_2048);
2928 
2929 	return PAGE_SIZE < 8192 ? I40E_RXBUFFER_3072 : I40E_RXBUFFER_2048;
2930 }
2931 
2932 /**
2933  * i40e_max_vsi_frame_size - returns the maximum allowed frame size for VSI
2934  * @vsi: the vsi
2935  * @xdp_prog: XDP program
2936  **/
2937 static int i40e_max_vsi_frame_size(struct i40e_vsi *vsi,
2938 				   struct bpf_prog *xdp_prog)
2939 {
2940 	u16 rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
2941 	u16 chain_len;
2942 
2943 	if (xdp_prog && !xdp_prog->aux->xdp_has_frags)
2944 		chain_len = 1;
2945 	else
2946 		chain_len = I40E_MAX_CHAINED_RX_BUFFERS;
2947 
2948 	return min_t(u16, rx_buf_len * chain_len, I40E_MAX_RXBUFFER);
2949 }
2950 
2951 /**
2952  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2953  * @netdev: network interface device structure
2954  * @new_mtu: new value for maximum frame size
2955  *
2956  * Returns 0 on success, negative on failure
2957  **/
2958 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2959 {
2960 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2961 	struct i40e_vsi *vsi = np->vsi;
2962 	struct i40e_pf *pf = vsi->back;
2963 	int frame_size;
2964 
2965 	frame_size = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
2966 	if (new_mtu > frame_size - I40E_PACKET_HDR_PAD) {
2967 		netdev_err(netdev, "Error changing mtu to %d, Max is %d\n",
2968 			   new_mtu, frame_size - I40E_PACKET_HDR_PAD);
2969 		return -EINVAL;
2970 	}
2971 
2972 	netdev_dbg(netdev, "changing MTU from %d to %d\n",
2973 		   netdev->mtu, new_mtu);
2974 	WRITE_ONCE(netdev->mtu, new_mtu);
2975 	if (netif_running(netdev))
2976 		i40e_vsi_reinit_locked(vsi);
2977 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2978 	set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2979 	return 0;
2980 }
2981 
2982 /**
2983  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2984  * @vsi: the vsi being adjusted
2985  **/
2986 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2987 {
2988 	struct i40e_vsi_context ctxt;
2989 	int ret;
2990 
2991 	/* Don't modify stripping options if a port VLAN is active */
2992 	if (vsi->info.pvid)
2993 		return;
2994 
2995 	if ((vsi->info.valid_sections &
2996 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2997 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2998 		return;  /* already enabled */
2999 
3000 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3001 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3002 				    I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
3003 
3004 	ctxt.seid = vsi->seid;
3005 	ctxt.info = vsi->info;
3006 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3007 	if (ret) {
3008 		dev_info(&vsi->back->pdev->dev,
3009 			 "update vlan stripping failed, err %pe aq_err %s\n",
3010 			 ERR_PTR(ret),
3011 			 libie_aq_str(vsi->back->hw.aq.asq_last_status));
3012 	}
3013 }
3014 
3015 /**
3016  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
3017  * @vsi: the vsi being adjusted
3018  **/
3019 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
3020 {
3021 	struct i40e_vsi_context ctxt;
3022 	int ret;
3023 
3024 	/* Don't modify stripping options if a port VLAN is active */
3025 	if (vsi->info.pvid)
3026 		return;
3027 
3028 	if ((vsi->info.valid_sections &
3029 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
3030 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
3031 	     I40E_AQ_VSI_PVLAN_EMOD_MASK))
3032 		return;  /* already disabled */
3033 
3034 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3035 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3036 				    I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
3037 
3038 	ctxt.seid = vsi->seid;
3039 	ctxt.info = vsi->info;
3040 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3041 	if (ret) {
3042 		dev_info(&vsi->back->pdev->dev,
3043 			 "update vlan stripping failed, err %pe aq_err %s\n",
3044 			 ERR_PTR(ret),
3045 			 libie_aq_str(vsi->back->hw.aq.asq_last_status));
3046 	}
3047 }
3048 
3049 /**
3050  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
3051  * @vsi: the vsi being configured
3052  * @vid: vlan id to be added (0 = untagged only , -1 = any)
3053  *
3054  * This is a helper function for adding a new MAC/VLAN filter with the
3055  * specified VLAN for each existing MAC address already in the hash table.
3056  * This function does *not* perform any accounting to update filters based on
3057  * VLAN mode.
3058  *
3059  * NOTE: this function expects to be called while under the
3060  * mac_filter_hash_lock
3061  **/
3062 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3063 {
3064 	struct i40e_mac_filter *f, *add_f;
3065 	struct hlist_node *h;
3066 	int bkt;
3067 
3068 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3069 		/* If we're asked to add a filter that has been marked for
3070 		 * removal, it is safe to simply restore it to active state.
3071 		 * __i40e_del_filter will have simply deleted any filters which
3072 		 * were previously marked NEW or FAILED, so if it is currently
3073 		 * marked REMOVE it must have previously been ACTIVE. Since we
3074 		 * haven't yet run the sync filters task, just restore this
3075 		 * filter to the ACTIVE state so that the sync task leaves it
3076 		 * in place.
3077 		 */
3078 		if (f->state == I40E_FILTER_REMOVE && f->vlan == vid) {
3079 			f->state = I40E_FILTER_ACTIVE;
3080 			continue;
3081 		} else if (f->state == I40E_FILTER_REMOVE) {
3082 			continue;
3083 		}
3084 		add_f = i40e_add_filter(vsi, f->macaddr, vid);
3085 		if (!add_f) {
3086 			dev_info(&vsi->back->pdev->dev,
3087 				 "Could not add vlan filter %d for %pM\n",
3088 				 vid, f->macaddr);
3089 			return -ENOMEM;
3090 		}
3091 	}
3092 
3093 	return 0;
3094 }
3095 
3096 /**
3097  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
3098  * @vsi: the VSI being configured
3099  * @vid: VLAN id to be added
3100  **/
3101 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
3102 {
3103 	int err;
3104 
3105 	if (vsi->info.pvid)
3106 		return -EINVAL;
3107 
3108 	/* The network stack will attempt to add VID=0, with the intention to
3109 	 * receive priority tagged packets with a VLAN of 0. Our HW receives
3110 	 * these packets by default when configured to receive untagged
3111 	 * packets, so we don't need to add a filter for this case.
3112 	 * Additionally, HW interprets adding a VID=0 filter as meaning to
3113 	 * receive *only* tagged traffic and stops receiving untagged traffic.
3114 	 * Thus, we do not want to actually add a filter for VID=0
3115 	 */
3116 	if (!vid)
3117 		return 0;
3118 
3119 	/* Locked once because all functions invoked below iterates list*/
3120 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3121 	err = i40e_add_vlan_all_mac(vsi, vid);
3122 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3123 	if (err)
3124 		return err;
3125 
3126 	/* schedule our worker thread which will take care of
3127 	 * applying the new filter changes
3128 	 */
3129 	i40e_service_event_schedule(vsi->back);
3130 	return 0;
3131 }
3132 
3133 /**
3134  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
3135  * @vsi: the vsi being configured
3136  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
3137  *
3138  * This function should be used to remove all VLAN filters which match the
3139  * given VID. It does not schedule the service event and does not take the
3140  * mac_filter_hash_lock so it may be combined with other operations under
3141  * a single invocation of the mac_filter_hash_lock.
3142  *
3143  * NOTE: this function expects to be called while under the
3144  * mac_filter_hash_lock
3145  */
3146 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3147 {
3148 	struct i40e_mac_filter *f;
3149 	struct hlist_node *h;
3150 	int bkt;
3151 
3152 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3153 		if (f->vlan == vid)
3154 			__i40e_del_filter(vsi, f);
3155 	}
3156 }
3157 
3158 /**
3159  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
3160  * @vsi: the VSI being configured
3161  * @vid: VLAN id to be removed
3162  **/
3163 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
3164 {
3165 	if (!vid || vsi->info.pvid)
3166 		return;
3167 
3168 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3169 	i40e_rm_vlan_all_mac(vsi, vid);
3170 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3171 
3172 	/* schedule our worker thread which will take care of
3173 	 * applying the new filter changes
3174 	 */
3175 	i40e_service_event_schedule(vsi->back);
3176 }
3177 
3178 /**
3179  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
3180  * @netdev: network interface to be adjusted
3181  * @proto: unused protocol value
3182  * @vid: vlan id to be added
3183  *
3184  * net_device_ops implementation for adding vlan ids
3185  **/
3186 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
3187 				__always_unused __be16 proto, u16 vid)
3188 {
3189 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3190 	struct i40e_vsi *vsi = np->vsi;
3191 	int ret = 0;
3192 
3193 	if (vid >= VLAN_N_VID)
3194 		return -EINVAL;
3195 
3196 	ret = i40e_vsi_add_vlan(vsi, vid);
3197 	if (!ret)
3198 		set_bit(vid, vsi->active_vlans);
3199 
3200 	return ret;
3201 }
3202 
3203 /**
3204  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
3205  * @netdev: network interface to be adjusted
3206  * @proto: unused protocol value
3207  * @vid: vlan id to be added
3208  **/
3209 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
3210 				    __always_unused __be16 proto, u16 vid)
3211 {
3212 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3213 	struct i40e_vsi *vsi = np->vsi;
3214 
3215 	if (vid >= VLAN_N_VID)
3216 		return;
3217 	set_bit(vid, vsi->active_vlans);
3218 }
3219 
3220 /**
3221  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
3222  * @netdev: network interface to be adjusted
3223  * @proto: unused protocol value
3224  * @vid: vlan id to be removed
3225  *
3226  * net_device_ops implementation for removing vlan ids
3227  **/
3228 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
3229 				 __always_unused __be16 proto, u16 vid)
3230 {
3231 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3232 	struct i40e_vsi *vsi = np->vsi;
3233 
3234 	/* return code is ignored as there is nothing a user
3235 	 * can do about failure to remove and a log message was
3236 	 * already printed from the other function
3237 	 */
3238 	i40e_vsi_kill_vlan(vsi, vid);
3239 
3240 	clear_bit(vid, vsi->active_vlans);
3241 
3242 	return 0;
3243 }
3244 
3245 /**
3246  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
3247  * @vsi: the vsi being brought back up
3248  **/
3249 static void i40e_restore_vlan(struct i40e_vsi *vsi)
3250 {
3251 	u16 vid;
3252 
3253 	if (!vsi->netdev)
3254 		return;
3255 
3256 	if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
3257 		i40e_vlan_stripping_enable(vsi);
3258 	else
3259 		i40e_vlan_stripping_disable(vsi);
3260 
3261 	for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
3262 		i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
3263 					vid);
3264 }
3265 
3266 /**
3267  * i40e_vsi_add_pvid - Add pvid for the VSI
3268  * @vsi: the vsi being adjusted
3269  * @vid: the vlan id to set as a PVID
3270  **/
3271 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
3272 {
3273 	struct i40e_vsi_context ctxt;
3274 	int ret;
3275 
3276 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3277 	vsi->info.pvid = cpu_to_le16(vid);
3278 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
3279 				    I40E_AQ_VSI_PVLAN_INSERT_PVID |
3280 				    I40E_AQ_VSI_PVLAN_EMOD_STR;
3281 
3282 	ctxt.seid = vsi->seid;
3283 	ctxt.info = vsi->info;
3284 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3285 	if (ret) {
3286 		dev_info(&vsi->back->pdev->dev,
3287 			 "add pvid failed, err %pe aq_err %s\n",
3288 			 ERR_PTR(ret),
3289 			 libie_aq_str(vsi->back->hw.aq.asq_last_status));
3290 		return -ENOENT;
3291 	}
3292 
3293 	return 0;
3294 }
3295 
3296 /**
3297  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
3298  * @vsi: the vsi being adjusted
3299  *
3300  * Just use the vlan_rx_register() service to put it back to normal
3301  **/
3302 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
3303 {
3304 	vsi->info.pvid = 0;
3305 
3306 	i40e_vlan_stripping_disable(vsi);
3307 }
3308 
3309 /**
3310  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
3311  * @vsi: ptr to the VSI
3312  *
3313  * If this function returns with an error, then it's possible one or
3314  * more of the rings is populated (while the rest are not).  It is the
3315  * callers duty to clean those orphaned rings.
3316  *
3317  * Return 0 on success, negative on failure
3318  **/
3319 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3320 {
3321 	int i, err = 0;
3322 
3323 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3324 		err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3325 
3326 	if (!i40e_enabled_xdp_vsi(vsi))
3327 		return err;
3328 
3329 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3330 		err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3331 
3332 	return err;
3333 }
3334 
3335 /**
3336  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3337  * @vsi: ptr to the VSI
3338  *
3339  * Free VSI's transmit software resources
3340  **/
3341 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3342 {
3343 	int i;
3344 
3345 	if (vsi->tx_rings) {
3346 		for (i = 0; i < vsi->num_queue_pairs; i++)
3347 			if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3348 				i40e_free_tx_resources(vsi->tx_rings[i]);
3349 	}
3350 
3351 	if (vsi->xdp_rings) {
3352 		for (i = 0; i < vsi->num_queue_pairs; i++)
3353 			if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3354 				i40e_free_tx_resources(vsi->xdp_rings[i]);
3355 	}
3356 }
3357 
3358 /**
3359  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3360  * @vsi: ptr to the VSI
3361  *
3362  * If this function returns with an error, then it's possible one or
3363  * more of the rings is populated (while the rest are not).  It is the
3364  * callers duty to clean those orphaned rings.
3365  *
3366  * Return 0 on success, negative on failure
3367  **/
3368 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3369 {
3370 	int i, err = 0;
3371 
3372 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3373 		err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3374 	return err;
3375 }
3376 
3377 /**
3378  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3379  * @vsi: ptr to the VSI
3380  *
3381  * Free all receive software resources
3382  **/
3383 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3384 {
3385 	int i;
3386 
3387 	if (!vsi->rx_rings)
3388 		return;
3389 
3390 	for (i = 0; i < vsi->num_queue_pairs; i++)
3391 		if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3392 			i40e_free_rx_resources(vsi->rx_rings[i]);
3393 }
3394 
3395 /**
3396  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3397  * @ring: The Tx ring to configure
3398  *
3399  * This enables/disables XPS for a given Tx descriptor ring
3400  * based on the TCs enabled for the VSI that ring belongs to.
3401  **/
3402 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3403 {
3404 	int cpu;
3405 
3406 	if (!ring->q_vector || !ring->netdev || ring->ch)
3407 		return;
3408 
3409 	/* We only initialize XPS once, so as not to overwrite user settings */
3410 	if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3411 		return;
3412 
3413 	cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3414 	netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3415 			    ring->queue_index);
3416 }
3417 
3418 /**
3419  * i40e_xsk_pool - Retrieve the AF_XDP buffer pool if XDP and ZC is enabled
3420  * @ring: The Tx or Rx ring
3421  *
3422  * Returns the AF_XDP buffer pool or NULL.
3423  **/
3424 static struct xsk_buff_pool *i40e_xsk_pool(struct i40e_ring *ring)
3425 {
3426 	bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3427 	int qid = ring->queue_index;
3428 
3429 	if (ring_is_xdp(ring))
3430 		qid -= ring->vsi->alloc_queue_pairs;
3431 
3432 	if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3433 		return NULL;
3434 
3435 	return xsk_get_pool_from_qid(ring->vsi->netdev, qid);
3436 }
3437 
3438 /**
3439  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3440  * @ring: The Tx ring to configure
3441  *
3442  * Configure the Tx descriptor ring in the HMC context.
3443  **/
3444 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3445 {
3446 	struct i40e_vsi *vsi = ring->vsi;
3447 	u16 pf_q = vsi->base_queue + ring->queue_index;
3448 	struct i40e_hw *hw = &vsi->back->hw;
3449 	struct i40e_hmc_obj_txq tx_ctx;
3450 	u32 qtx_ctl = 0;
3451 	int err = 0;
3452 
3453 	if (ring_is_xdp(ring))
3454 		ring->xsk_pool = i40e_xsk_pool(ring);
3455 
3456 	/* some ATR related tx ring init */
3457 	if (test_bit(I40E_FLAG_FD_ATR_ENA, vsi->back->flags)) {
3458 		ring->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
3459 		ring->atr_count = 0;
3460 	} else {
3461 		ring->atr_sample_rate = 0;
3462 	}
3463 
3464 	/* configure XPS */
3465 	i40e_config_xps_tx_ring(ring);
3466 
3467 	/* clear the context structure first */
3468 	memset(&tx_ctx, 0, sizeof(tx_ctx));
3469 
3470 	tx_ctx.new_context = 1;
3471 	tx_ctx.base = (ring->dma / 128);
3472 	tx_ctx.qlen = ring->count;
3473 	if (test_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags) ||
3474 	    test_bit(I40E_FLAG_FD_ATR_ENA, vsi->back->flags))
3475 		tx_ctx.fd_ena = 1;
3476 	if (test_bit(I40E_FLAG_PTP_ENA, vsi->back->flags))
3477 		tx_ctx.timesync_ena = 1;
3478 	/* FDIR VSI tx ring can still use RS bit and writebacks */
3479 	if (vsi->type != I40E_VSI_FDIR)
3480 		tx_ctx.head_wb_ena = 1;
3481 	tx_ctx.head_wb_addr = ring->dma +
3482 			      (ring->count * sizeof(struct i40e_tx_desc));
3483 
3484 	/* As part of VSI creation/update, FW allocates certain
3485 	 * Tx arbitration queue sets for each TC enabled for
3486 	 * the VSI. The FW returns the handles to these queue
3487 	 * sets as part of the response buffer to Add VSI,
3488 	 * Update VSI, etc. AQ commands. It is expected that
3489 	 * these queue set handles be associated with the Tx
3490 	 * queues by the driver as part of the TX queue context
3491 	 * initialization. This has to be done regardless of
3492 	 * DCB as by default everything is mapped to TC0.
3493 	 */
3494 
3495 	if (ring->ch)
3496 		tx_ctx.rdylist =
3497 			le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3498 
3499 	else
3500 		tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3501 
3502 	tx_ctx.rdylist_act = 0;
3503 
3504 	/* clear the context in the HMC */
3505 	err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3506 	if (err) {
3507 		dev_info(&vsi->back->pdev->dev,
3508 			 "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3509 			 ring->queue_index, pf_q, err);
3510 		return -ENOMEM;
3511 	}
3512 
3513 	/* set the context in the HMC */
3514 	err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3515 	if (err) {
3516 		dev_info(&vsi->back->pdev->dev,
3517 			 "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3518 			 ring->queue_index, pf_q, err);
3519 		return -ENOMEM;
3520 	}
3521 
3522 	/* Now associate this queue with this PCI function */
3523 	if (ring->ch) {
3524 		if (ring->ch->type == I40E_VSI_VMDQ2)
3525 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3526 		else
3527 			return -EINVAL;
3528 
3529 		qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_VFVM_INDX_MASK,
3530 				      ring->ch->vsi_number);
3531 	} else {
3532 		if (vsi->type == I40E_VSI_VMDQ2) {
3533 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3534 			qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_VFVM_INDX_MASK,
3535 					      vsi->id);
3536 		} else {
3537 			qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3538 		}
3539 	}
3540 
3541 	qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_PF_INDX_MASK, hw->pf_id);
3542 	wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3543 	i40e_flush(hw);
3544 
3545 	/* cache tail off for easier writes later */
3546 	ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3547 
3548 	return 0;
3549 }
3550 
3551 /**
3552  * i40e_rx_offset - Return expected offset into page to access data
3553  * @rx_ring: Ring we are requesting offset of
3554  *
3555  * Returns the offset value for ring into the data buffer.
3556  */
3557 static unsigned int i40e_rx_offset(struct i40e_ring *rx_ring)
3558 {
3559 	return ring_uses_build_skb(rx_ring) ? I40E_SKB_PAD : 0;
3560 }
3561 
3562 /**
3563  * i40e_configure_rx_ring - Configure a receive ring context
3564  * @ring: The Rx ring to configure
3565  *
3566  * Configure the Rx descriptor ring in the HMC context.
3567  **/
3568 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3569 {
3570 	struct i40e_vsi *vsi = ring->vsi;
3571 	u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3572 	u16 pf_q = vsi->base_queue + ring->queue_index;
3573 	struct i40e_hw *hw = &vsi->back->hw;
3574 	struct i40e_hmc_obj_rxq rx_ctx;
3575 	u32 xdp_frame_sz;
3576 	int err = 0;
3577 	bool ok;
3578 
3579 	bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3580 
3581 	/* clear the context structure first */
3582 	memset(&rx_ctx, 0, sizeof(rx_ctx));
3583 
3584 	ring->rx_buf_len = vsi->rx_buf_len;
3585 	xdp_frame_sz = i40e_rx_pg_size(ring) / 2;
3586 
3587 	/* XDP RX-queue info only needed for RX rings exposed to XDP */
3588 	if (ring->vsi->type != I40E_VSI_MAIN)
3589 		goto skip;
3590 
3591 	ring->xsk_pool = i40e_xsk_pool(ring);
3592 	if (ring->xsk_pool) {
3593 		xdp_frame_sz = xsk_pool_get_rx_frag_step(ring->xsk_pool);
3594 		ring->rx_buf_len = xsk_pool_get_rx_frame_size(ring->xsk_pool);
3595 		err = __xdp_rxq_info_reg(&ring->xdp_rxq, ring->netdev,
3596 					 ring->queue_index,
3597 					 ring->q_vector->napi.napi_id,
3598 					 xdp_frame_sz);
3599 		if (err)
3600 			return err;
3601 		err = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3602 						 MEM_TYPE_XSK_BUFF_POOL,
3603 						 NULL);
3604 		if (err)
3605 			goto unreg_xdp;
3606 		dev_info(&vsi->back->pdev->dev,
3607 			 "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n",
3608 			 ring->queue_index);
3609 
3610 	} else {
3611 		err = __xdp_rxq_info_reg(&ring->xdp_rxq, ring->netdev,
3612 					 ring->queue_index,
3613 					 ring->q_vector->napi.napi_id,
3614 					 xdp_frame_sz);
3615 		if (err)
3616 			return err;
3617 		err = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3618 						 MEM_TYPE_PAGE_SHARED,
3619 						 NULL);
3620 		if (err)
3621 			goto unreg_xdp;
3622 	}
3623 
3624 skip:
3625 	xdp_init_buff(&ring->xdp, xdp_frame_sz, &ring->xdp_rxq);
3626 
3627 	rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3628 				    BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3629 
3630 	rx_ctx.base = (ring->dma / 128);
3631 	rx_ctx.qlen = ring->count;
3632 
3633 	/* use 16 byte descriptors */
3634 	rx_ctx.dsize = 0;
3635 
3636 	/* descriptor type is always zero
3637 	 * rx_ctx.dtype = 0;
3638 	 */
3639 	rx_ctx.hsplit_0 = 0;
3640 
3641 	rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3642 	if (hw->revision_id == 0)
3643 		rx_ctx.lrxqthresh = 0;
3644 	else
3645 		rx_ctx.lrxqthresh = 1;
3646 	rx_ctx.crcstrip = 1;
3647 	rx_ctx.l2tsel = 1;
3648 	/* this controls whether VLAN is stripped from inner headers */
3649 	rx_ctx.showiv = 0;
3650 	/* set the prefena field to 1 because the manual says to */
3651 	rx_ctx.prefena = 1;
3652 
3653 	/* clear the context in the HMC */
3654 	err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3655 	if (err) {
3656 		dev_info(&vsi->back->pdev->dev,
3657 			 "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3658 			 ring->queue_index, pf_q, err);
3659 		err = -ENOMEM;
3660 		goto unreg_xdp;
3661 	}
3662 
3663 	/* set the context in the HMC */
3664 	err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3665 	if (err) {
3666 		dev_info(&vsi->back->pdev->dev,
3667 			 "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3668 			 ring->queue_index, pf_q, err);
3669 		err = -ENOMEM;
3670 		goto unreg_xdp;
3671 	}
3672 
3673 	/* configure Rx buffer alignment */
3674 	if (!vsi->netdev || test_bit(I40E_FLAG_LEGACY_RX_ENA, vsi->back->flags)) {
3675 		if (I40E_2K_TOO_SMALL_WITH_PADDING) {
3676 			dev_info(&vsi->back->pdev->dev,
3677 				 "2k Rx buffer is too small to fit standard MTU and skb_shared_info\n");
3678 			err = -EOPNOTSUPP;
3679 			goto unreg_xdp;
3680 		}
3681 		clear_ring_build_skb_enabled(ring);
3682 	} else {
3683 		set_ring_build_skb_enabled(ring);
3684 	}
3685 
3686 	ring->rx_offset = i40e_rx_offset(ring);
3687 
3688 	/* cache tail for quicker writes, and clear the reg before use */
3689 	ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3690 	writel(0, ring->tail);
3691 
3692 	if (ring->xsk_pool) {
3693 		xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
3694 		ok = i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring));
3695 	} else {
3696 		ok = !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3697 	}
3698 	if (!ok) {
3699 		/* Log this in case the user has forgotten to give the kernel
3700 		 * any buffers, even later in the application.
3701 		 */
3702 		dev_info(&vsi->back->pdev->dev,
3703 			 "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3704 			 ring->xsk_pool ? "AF_XDP ZC enabled " : "",
3705 			 ring->queue_index, pf_q);
3706 	}
3707 
3708 	return 0;
3709 unreg_xdp:
3710 	if (ring->vsi->type == I40E_VSI_MAIN)
3711 		xdp_rxq_info_unreg(&ring->xdp_rxq);
3712 
3713 	return err;
3714 }
3715 
3716 /**
3717  * i40e_vsi_configure_tx - Configure the VSI for Tx
3718  * @vsi: VSI structure describing this set of rings and resources
3719  *
3720  * Configure the Tx VSI for operation.
3721  **/
3722 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3723 {
3724 	int err = 0;
3725 	u16 i;
3726 
3727 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3728 		err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3729 
3730 	if (err || !i40e_enabled_xdp_vsi(vsi))
3731 		return err;
3732 
3733 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3734 		err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3735 
3736 	return err;
3737 }
3738 
3739 /**
3740  * i40e_vsi_configure_rx - Configure the VSI for Rx
3741  * @vsi: the VSI being configured
3742  *
3743  * Configure the Rx VSI for operation.
3744  **/
3745 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3746 {
3747 	int err = 0;
3748 	u16 i;
3749 
3750 	vsi->max_frame = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
3751 	vsi->rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
3752 
3753 #if (PAGE_SIZE < 8192)
3754 	if (vsi->netdev && !I40E_2K_TOO_SMALL_WITH_PADDING &&
3755 	    vsi->netdev->mtu <= ETH_DATA_LEN) {
3756 		vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3757 		vsi->max_frame = vsi->rx_buf_len;
3758 	}
3759 #endif
3760 
3761 	/* set up individual rings */
3762 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3763 		err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3764 
3765 	return err;
3766 }
3767 
3768 /**
3769  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3770  * @vsi: ptr to the VSI
3771  **/
3772 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3773 {
3774 	struct i40e_ring *tx_ring, *rx_ring;
3775 	u16 qoffset, qcount;
3776 	int i, n;
3777 
3778 	if (!test_bit(I40E_FLAG_DCB_ENA, vsi->back->flags)) {
3779 		/* Reset the TC information */
3780 		for (i = 0; i < vsi->num_queue_pairs; i++) {
3781 			rx_ring = vsi->rx_rings[i];
3782 			tx_ring = vsi->tx_rings[i];
3783 			rx_ring->dcb_tc = 0;
3784 			tx_ring->dcb_tc = 0;
3785 		}
3786 		return;
3787 	}
3788 
3789 	for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3790 		if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3791 			continue;
3792 
3793 		qoffset = vsi->tc_config.tc_info[n].qoffset;
3794 		qcount = vsi->tc_config.tc_info[n].qcount;
3795 		for (i = qoffset; i < (qoffset + qcount); i++) {
3796 			rx_ring = vsi->rx_rings[i];
3797 			tx_ring = vsi->tx_rings[i];
3798 			rx_ring->dcb_tc = n;
3799 			tx_ring->dcb_tc = n;
3800 		}
3801 	}
3802 }
3803 
3804 /**
3805  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3806  * @vsi: ptr to the VSI
3807  **/
3808 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3809 {
3810 	if (vsi->netdev)
3811 		i40e_set_rx_mode(vsi->netdev);
3812 }
3813 
3814 /**
3815  * i40e_reset_fdir_filter_cnt - Reset flow director filter counters
3816  * @pf: Pointer to the targeted PF
3817  *
3818  * Set all flow director counters to 0.
3819  */
3820 static void i40e_reset_fdir_filter_cnt(struct i40e_pf *pf)
3821 {
3822 	pf->fd_tcp4_filter_cnt = 0;
3823 	pf->fd_udp4_filter_cnt = 0;
3824 	pf->fd_sctp4_filter_cnt = 0;
3825 	pf->fd_ip4_filter_cnt = 0;
3826 	pf->fd_tcp6_filter_cnt = 0;
3827 	pf->fd_udp6_filter_cnt = 0;
3828 	pf->fd_sctp6_filter_cnt = 0;
3829 	pf->fd_ip6_filter_cnt = 0;
3830 }
3831 
3832 /**
3833  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3834  * @vsi: Pointer to the targeted VSI
3835  *
3836  * This function replays the hlist on the hw where all the SB Flow Director
3837  * filters were saved.
3838  **/
3839 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3840 {
3841 	struct i40e_fdir_filter *filter;
3842 	struct i40e_pf *pf = vsi->back;
3843 	struct hlist_node *node;
3844 
3845 	if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
3846 		return;
3847 
3848 	/* Reset FDir counters as we're replaying all existing filters */
3849 	i40e_reset_fdir_filter_cnt(pf);
3850 
3851 	hlist_for_each_entry_safe(filter, node,
3852 				  &pf->fdir_filter_list, fdir_node) {
3853 		i40e_add_del_fdir(vsi, filter, true);
3854 	}
3855 }
3856 
3857 /**
3858  * i40e_vsi_configure - Set up the VSI for action
3859  * @vsi: the VSI being configured
3860  **/
3861 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3862 {
3863 	int err;
3864 
3865 	i40e_set_vsi_rx_mode(vsi);
3866 	i40e_restore_vlan(vsi);
3867 	i40e_vsi_config_dcb_rings(vsi);
3868 	err = i40e_vsi_configure_tx(vsi);
3869 	if (!err)
3870 		err = i40e_vsi_configure_rx(vsi);
3871 
3872 	return err;
3873 }
3874 
3875 /**
3876  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3877  * @vsi: the VSI being configured
3878  **/
3879 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3880 {
3881 	bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3882 	struct i40e_pf *pf = vsi->back;
3883 	struct i40e_hw *hw = &pf->hw;
3884 	u16 vector;
3885 	int i, q;
3886 	u32 qp;
3887 
3888 	/* The interrupt indexing is offset by 1 in the PFINT_ITRn
3889 	 * and PFINT_LNKLSTn registers, e.g.:
3890 	 *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3891 	 */
3892 	qp = vsi->base_queue;
3893 	vector = vsi->base_vector;
3894 	for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3895 		struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3896 
3897 		q_vector->rx.next_update = jiffies + 1;
3898 		q_vector->rx.target_itr =
3899 			ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3900 		wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3901 		     q_vector->rx.target_itr >> 1);
3902 		q_vector->rx.current_itr = q_vector->rx.target_itr;
3903 
3904 		q_vector->tx.next_update = jiffies + 1;
3905 		q_vector->tx.target_itr =
3906 			ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3907 		wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3908 		     q_vector->tx.target_itr >> 1);
3909 		q_vector->tx.current_itr = q_vector->tx.target_itr;
3910 
3911 		/* Set ITR for software interrupts triggered after exiting
3912 		 * busy-loop polling.
3913 		 */
3914 		wr32(hw, I40E_PFINT_ITRN(I40E_SW_ITR, vector - 1),
3915 		     I40E_ITR_20K);
3916 
3917 		wr32(hw, I40E_PFINT_RATEN(vector - 1),
3918 		     i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3919 
3920 		/* begin of linked list for RX queue assigned to this vector */
3921 		wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3922 		for (q = 0; q < q_vector->num_ringpairs; q++) {
3923 			u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3924 			u32 val;
3925 
3926 			val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3927 			      (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3928 			      (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3929 			      (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3930 			      (I40E_QUEUE_TYPE_TX <<
3931 			       I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3932 
3933 			wr32(hw, I40E_QINT_RQCTL(qp), val);
3934 
3935 			if (has_xdp) {
3936 				/* TX queue with next queue set to TX */
3937 				val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3938 				      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3939 				      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3940 				      (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3941 				      (I40E_QUEUE_TYPE_TX <<
3942 				       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3943 
3944 				wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3945 			}
3946 			/* TX queue with next RX or end of linked list */
3947 			val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3948 			      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3949 			      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3950 			      ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3951 			      (I40E_QUEUE_TYPE_RX <<
3952 			       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3953 
3954 			/* Terminate the linked list */
3955 			if (q == (q_vector->num_ringpairs - 1))
3956 				val |= (I40E_QUEUE_END_OF_LIST <<
3957 					I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3958 
3959 			wr32(hw, I40E_QINT_TQCTL(qp), val);
3960 			qp++;
3961 		}
3962 	}
3963 
3964 	i40e_flush(hw);
3965 }
3966 
3967 /**
3968  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3969  * @pf: pointer to private device data structure
3970  **/
3971 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3972 {
3973 	struct i40e_hw *hw = &pf->hw;
3974 	u32 val;
3975 
3976 	/* clear things first */
3977 	wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3978 	rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3979 
3980 	val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3981 	      I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3982 	      I40E_PFINT_ICR0_ENA_GRST_MASK          |
3983 	      I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3984 	      I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3985 	      I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3986 	      I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3987 	      I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3988 
3989 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags))
3990 		val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3991 
3992 	if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
3993 		val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3994 
3995 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
3996 
3997 	/* SW_ITR_IDX = 0, but don't change INTENA */
3998 	wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3999 					I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
4000 
4001 	/* OTHER_ITR_IDX = 0 */
4002 	wr32(hw, I40E_PFINT_STAT_CTL0, 0);
4003 }
4004 
4005 /**
4006  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
4007  * @vsi: the VSI being configured
4008  **/
4009 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
4010 {
4011 	u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
4012 	struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4013 	struct i40e_pf *pf = vsi->back;
4014 	struct i40e_hw *hw = &pf->hw;
4015 
4016 	/* set the ITR configuration */
4017 	q_vector->rx.next_update = jiffies + 1;
4018 	q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
4019 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr >> 1);
4020 	q_vector->rx.current_itr = q_vector->rx.target_itr;
4021 	q_vector->tx.next_update = jiffies + 1;
4022 	q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
4023 	wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr >> 1);
4024 	q_vector->tx.current_itr = q_vector->tx.target_itr;
4025 
4026 	i40e_enable_misc_int_causes(pf);
4027 
4028 	/* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
4029 	wr32(hw, I40E_PFINT_LNKLST0, 0);
4030 
4031 	/* Associate the queue pair to the vector and enable the queue
4032 	 * interrupt RX queue in linked list with next queue set to TX
4033 	 */
4034 	wr32(hw, I40E_QINT_RQCTL(0), I40E_QINT_RQCTL_VAL(nextqp, 0, TX));
4035 
4036 	if (i40e_enabled_xdp_vsi(vsi)) {
4037 		/* TX queue in linked list with next queue set to TX */
4038 		wr32(hw, I40E_QINT_TQCTL(nextqp),
4039 		     I40E_QINT_TQCTL_VAL(nextqp, 0, TX));
4040 	}
4041 
4042 	/* last TX queue so the next RX queue doesn't matter */
4043 	wr32(hw, I40E_QINT_TQCTL(0),
4044 	     I40E_QINT_TQCTL_VAL(I40E_QUEUE_END_OF_LIST, 0, RX));
4045 	i40e_flush(hw);
4046 }
4047 
4048 /**
4049  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
4050  * @pf: board private structure
4051  **/
4052 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
4053 {
4054 	struct i40e_hw *hw = &pf->hw;
4055 
4056 	wr32(hw, I40E_PFINT_DYN_CTL0,
4057 	     I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
4058 	i40e_flush(hw);
4059 }
4060 
4061 /**
4062  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
4063  * @pf: board private structure
4064  **/
4065 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
4066 {
4067 	struct i40e_hw *hw = &pf->hw;
4068 	u32 val;
4069 
4070 	val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
4071 	      I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
4072 	      (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
4073 
4074 	wr32(hw, I40E_PFINT_DYN_CTL0, val);
4075 	i40e_flush(hw);
4076 }
4077 
4078 /**
4079  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
4080  * @irq: interrupt number
4081  * @data: pointer to a q_vector
4082  **/
4083 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
4084 {
4085 	struct i40e_q_vector *q_vector = data;
4086 
4087 	if (!q_vector->tx.ring && !q_vector->rx.ring)
4088 		return IRQ_HANDLED;
4089 
4090 	napi_schedule_irqoff(&q_vector->napi);
4091 
4092 	return IRQ_HANDLED;
4093 }
4094 
4095 /**
4096  * i40e_irq_affinity_notify - Callback for affinity changes
4097  * @notify: context as to what irq was changed
4098  * @mask: the new affinity mask
4099  *
4100  * This is a callback function used by the irq_set_affinity_notifier function
4101  * so that we may register to receive changes to the irq affinity masks.
4102  **/
4103 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
4104 				     const cpumask_t *mask)
4105 {
4106 	struct i40e_q_vector *q_vector =
4107 		container_of(notify, struct i40e_q_vector, affinity_notify);
4108 
4109 	cpumask_copy(&q_vector->affinity_mask, mask);
4110 }
4111 
4112 /**
4113  * i40e_irq_affinity_release - Callback for affinity notifier release
4114  * @ref: internal core kernel usage
4115  *
4116  * This is a callback function used by the irq_set_affinity_notifier function
4117  * to inform the current notification subscriber that they will no longer
4118  * receive notifications.
4119  **/
4120 static void i40e_irq_affinity_release(struct kref *ref) {}
4121 
4122 /**
4123  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
4124  * @vsi: the VSI being configured
4125  * @basename: name for the vector
4126  *
4127  * Allocates MSI-X vectors and requests interrupts from the kernel.
4128  **/
4129 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
4130 {
4131 	int q_vectors = vsi->num_q_vectors;
4132 	struct i40e_pf *pf = vsi->back;
4133 	int base = vsi->base_vector;
4134 	int rx_int_idx = 0;
4135 	int tx_int_idx = 0;
4136 	int vector, err;
4137 	int irq_num;
4138 	int cpu;
4139 
4140 	for (vector = 0; vector < q_vectors; vector++) {
4141 		struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
4142 
4143 		irq_num = pf->msix_entries[base + vector].vector;
4144 
4145 		if (q_vector->tx.ring && q_vector->rx.ring) {
4146 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4147 				 "%s-%s-%d", basename, "TxRx", rx_int_idx++);
4148 			tx_int_idx++;
4149 		} else if (q_vector->rx.ring) {
4150 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4151 				 "%s-%s-%d", basename, "rx", rx_int_idx++);
4152 		} else if (q_vector->tx.ring) {
4153 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4154 				 "%s-%s-%d", basename, "tx", tx_int_idx++);
4155 		} else {
4156 			/* skip this unused q_vector */
4157 			continue;
4158 		}
4159 		err = request_irq(irq_num,
4160 				  vsi->irq_handler,
4161 				  0,
4162 				  q_vector->name,
4163 				  q_vector);
4164 		if (err) {
4165 			dev_info(&pf->pdev->dev,
4166 				 "MSIX request_irq failed, error: %d\n", err);
4167 			goto free_queue_irqs;
4168 		}
4169 
4170 		/* register for affinity change notifications */
4171 		q_vector->irq_num = irq_num;
4172 		q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
4173 		q_vector->affinity_notify.release = i40e_irq_affinity_release;
4174 		irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
4175 		/* Spread affinity hints out across online CPUs.
4176 		 *
4177 		 * get_cpu_mask returns a static constant mask with
4178 		 * a permanent lifetime so it's ok to pass to
4179 		 * irq_update_affinity_hint without making a copy.
4180 		 */
4181 		cpu = cpumask_local_spread(q_vector->v_idx, -1);
4182 		irq_update_affinity_hint(irq_num, get_cpu_mask(cpu));
4183 	}
4184 
4185 	vsi->irqs_ready = true;
4186 	return 0;
4187 
4188 free_queue_irqs:
4189 	while (vector) {
4190 		vector--;
4191 		irq_num = pf->msix_entries[base + vector].vector;
4192 		irq_set_affinity_notifier(irq_num, NULL);
4193 		irq_update_affinity_hint(irq_num, NULL);
4194 		free_irq(irq_num, vsi->q_vectors[vector]);
4195 	}
4196 	return err;
4197 }
4198 
4199 /**
4200  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
4201  * @vsi: the VSI being un-configured
4202  **/
4203 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
4204 {
4205 	struct i40e_pf *pf = vsi->back;
4206 	struct i40e_hw *hw = &pf->hw;
4207 	int base = vsi->base_vector;
4208 	int i;
4209 
4210 	/* disable interrupt causation from each queue */
4211 	for (i = 0; i < vsi->num_queue_pairs; i++) {
4212 		u32 val;
4213 
4214 		val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
4215 		val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
4216 		wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
4217 
4218 		val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
4219 		val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
4220 		wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
4221 
4222 		if (!i40e_enabled_xdp_vsi(vsi))
4223 			continue;
4224 		wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
4225 	}
4226 
4227 	/* disable each interrupt */
4228 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4229 		for (i = vsi->base_vector;
4230 		     i < (vsi->num_q_vectors + vsi->base_vector); i++)
4231 			wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
4232 
4233 		i40e_flush(hw);
4234 		for (i = 0; i < vsi->num_q_vectors; i++)
4235 			synchronize_irq(pf->msix_entries[i + base].vector);
4236 	} else {
4237 		/* Legacy and MSI mode - this stops all interrupt handling */
4238 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
4239 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
4240 		i40e_flush(hw);
4241 		synchronize_irq(pf->pdev->irq);
4242 	}
4243 }
4244 
4245 /**
4246  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
4247  * @vsi: the VSI being configured
4248  **/
4249 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
4250 {
4251 	struct i40e_pf *pf = vsi->back;
4252 	int i;
4253 
4254 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4255 		for (i = 0; i < vsi->num_q_vectors; i++)
4256 			i40e_irq_dynamic_enable(vsi, i);
4257 	} else {
4258 		i40e_irq_dynamic_enable_icr0(pf);
4259 	}
4260 
4261 	i40e_flush(&pf->hw);
4262 	return 0;
4263 }
4264 
4265 /**
4266  * i40e_free_misc_vector - Free the vector that handles non-queue events
4267  * @pf: board private structure
4268  **/
4269 static void i40e_free_misc_vector(struct i40e_pf *pf)
4270 {
4271 	/* Disable ICR 0 */
4272 	wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
4273 	i40e_flush(&pf->hw);
4274 
4275 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags) && pf->msix_entries) {
4276 		free_irq(pf->msix_entries[0].vector, pf);
4277 		clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
4278 	}
4279 }
4280 
4281 /**
4282  * i40e_intr - MSI/Legacy and non-queue interrupt handler
4283  * @irq: interrupt number
4284  * @data: pointer to a q_vector
4285  *
4286  * This is the handler used for all MSI/Legacy interrupts, and deals
4287  * with both queue and non-queue interrupts.  This is also used in
4288  * MSIX mode to handle the non-queue interrupts.
4289  **/
4290 static irqreturn_t i40e_intr(int irq, void *data)
4291 {
4292 	struct i40e_pf *pf = (struct i40e_pf *)data;
4293 	struct i40e_hw *hw = &pf->hw;
4294 	irqreturn_t ret = IRQ_NONE;
4295 	u32 icr0, icr0_remaining;
4296 	u32 val, ena_mask;
4297 
4298 	icr0 = rd32(hw, I40E_PFINT_ICR0);
4299 	ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
4300 
4301 	/* if sharing a legacy IRQ, we might get called w/o an intr pending */
4302 	if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
4303 		goto enable_intr;
4304 
4305 	/* if interrupt but no bits showing, must be SWINT */
4306 	if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
4307 	    (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
4308 		pf->sw_int_count++;
4309 
4310 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags) &&
4311 	    (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
4312 		ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4313 		dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
4314 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
4315 	}
4316 
4317 	/* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
4318 	if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
4319 		struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
4320 		struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4321 
4322 		/* We do not have a way to disarm Queue causes while leaving
4323 		 * interrupt enabled for all other causes, ideally
4324 		 * interrupt should be disabled while we are in NAPI but
4325 		 * this is not a performance path and napi_schedule()
4326 		 * can deal with rescheduling.
4327 		 */
4328 		if (!test_bit(__I40E_DOWN, pf->state))
4329 			napi_schedule_irqoff(&q_vector->napi);
4330 	}
4331 
4332 	if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
4333 		ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
4334 		set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
4335 		i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
4336 	}
4337 
4338 	if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
4339 		ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
4340 		set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
4341 	}
4342 
4343 	if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
4344 		/* disable any further VFLR event notifications */
4345 		if (test_bit(__I40E_VF_RESETS_DISABLED, pf->state)) {
4346 			u32 reg = rd32(hw, I40E_PFINT_ICR0_ENA);
4347 
4348 			reg &= ~I40E_PFINT_ICR0_VFLR_MASK;
4349 			wr32(hw, I40E_PFINT_ICR0_ENA, reg);
4350 		} else {
4351 			ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
4352 			set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
4353 		}
4354 	}
4355 
4356 	if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
4357 		if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4358 			set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
4359 		ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
4360 		val = rd32(hw, I40E_GLGEN_RSTAT);
4361 		val = FIELD_GET(I40E_GLGEN_RSTAT_RESET_TYPE_MASK, val);
4362 		if (val == I40E_RESET_CORER) {
4363 			pf->corer_count++;
4364 		} else if (val == I40E_RESET_GLOBR) {
4365 			pf->globr_count++;
4366 		} else if (val == I40E_RESET_EMPR) {
4367 			pf->empr_count++;
4368 			set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
4369 		}
4370 	}
4371 
4372 	if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
4373 		icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
4374 		dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4375 		dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4376 			 rd32(hw, I40E_PFHMC_ERRORINFO),
4377 			 rd32(hw, I40E_PFHMC_ERRORDATA));
4378 	}
4379 
4380 	if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4381 		u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4382 
4383 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_EVENT0_MASK)
4384 			schedule_work(&pf->ptp_extts0_work);
4385 
4386 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK)
4387 			i40e_ptp_tx_hwtstamp(pf);
4388 
4389 		icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4390 	}
4391 
4392 	/* If a critical error is pending we have no choice but to reset the
4393 	 * device.
4394 	 * Report and mask out any remaining unexpected interrupts.
4395 	 */
4396 	icr0_remaining = icr0 & ena_mask;
4397 	if (icr0_remaining) {
4398 		dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4399 			 icr0_remaining);
4400 		if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4401 		    (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4402 		    (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4403 			dev_info(&pf->pdev->dev, "device will be reset\n");
4404 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4405 			i40e_service_event_schedule(pf);
4406 		}
4407 		ena_mask &= ~icr0_remaining;
4408 	}
4409 	ret = IRQ_HANDLED;
4410 
4411 enable_intr:
4412 	/* re-enable interrupt causes */
4413 	wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4414 	if (!test_bit(__I40E_DOWN, pf->state) ||
4415 	    test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4416 		i40e_service_event_schedule(pf);
4417 		i40e_irq_dynamic_enable_icr0(pf);
4418 	}
4419 
4420 	return ret;
4421 }
4422 
4423 /**
4424  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4425  * @tx_ring:  tx ring to clean
4426  * @budget:   how many cleans we're allowed
4427  *
4428  * Returns true if there's any budget left (e.g. the clean is finished)
4429  **/
4430 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4431 {
4432 	struct i40e_vsi *vsi = tx_ring->vsi;
4433 	u16 i = tx_ring->next_to_clean;
4434 	struct i40e_tx_buffer *tx_buf;
4435 	struct i40e_tx_desc *tx_desc;
4436 
4437 	tx_buf = &tx_ring->tx_bi[i];
4438 	tx_desc = I40E_TX_DESC(tx_ring, i);
4439 	i -= tx_ring->count;
4440 
4441 	do {
4442 		struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4443 
4444 		/* if next_to_watch is not set then there is no work pending */
4445 		if (!eop_desc)
4446 			break;
4447 
4448 		/* prevent any other reads prior to eop_desc */
4449 		smp_rmb();
4450 
4451 		/* if the descriptor isn't done, no work yet to do */
4452 		if (!(eop_desc->cmd_type_offset_bsz &
4453 		      cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4454 			break;
4455 
4456 		/* clear next_to_watch to prevent false hangs */
4457 		tx_buf->next_to_watch = NULL;
4458 
4459 		tx_desc->buffer_addr = 0;
4460 		tx_desc->cmd_type_offset_bsz = 0;
4461 		/* move past filter desc */
4462 		tx_buf++;
4463 		tx_desc++;
4464 		i++;
4465 		if (unlikely(!i)) {
4466 			i -= tx_ring->count;
4467 			tx_buf = tx_ring->tx_bi;
4468 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4469 		}
4470 		/* unmap skb header data */
4471 		dma_unmap_single(tx_ring->dev,
4472 				 dma_unmap_addr(tx_buf, dma),
4473 				 dma_unmap_len(tx_buf, len),
4474 				 DMA_TO_DEVICE);
4475 		if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4476 			kfree(tx_buf->raw_buf);
4477 
4478 		tx_buf->raw_buf = NULL;
4479 		tx_buf->tx_flags = 0;
4480 		tx_buf->next_to_watch = NULL;
4481 		dma_unmap_len_set(tx_buf, len, 0);
4482 		tx_desc->buffer_addr = 0;
4483 		tx_desc->cmd_type_offset_bsz = 0;
4484 
4485 		/* move us past the eop_desc for start of next FD desc */
4486 		tx_buf++;
4487 		tx_desc++;
4488 		i++;
4489 		if (unlikely(!i)) {
4490 			i -= tx_ring->count;
4491 			tx_buf = tx_ring->tx_bi;
4492 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4493 		}
4494 
4495 		/* update budget accounting */
4496 		budget--;
4497 	} while (likely(budget));
4498 
4499 	i += tx_ring->count;
4500 	tx_ring->next_to_clean = i;
4501 
4502 	if (test_bit(I40E_FLAG_MSIX_ENA, vsi->back->flags))
4503 		i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4504 
4505 	return budget > 0;
4506 }
4507 
4508 /**
4509  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4510  * @irq: interrupt number
4511  * @data: pointer to a q_vector
4512  **/
4513 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4514 {
4515 	struct i40e_q_vector *q_vector = data;
4516 	struct i40e_vsi *vsi;
4517 
4518 	if (!q_vector->tx.ring)
4519 		return IRQ_HANDLED;
4520 
4521 	vsi = q_vector->tx.ring->vsi;
4522 	i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4523 
4524 	return IRQ_HANDLED;
4525 }
4526 
4527 /**
4528  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4529  * @vsi: the VSI being configured
4530  * @v_idx: vector index
4531  * @qp_idx: queue pair index
4532  **/
4533 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4534 {
4535 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4536 	struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4537 	struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4538 
4539 	tx_ring->q_vector = q_vector;
4540 	tx_ring->next = q_vector->tx.ring;
4541 	q_vector->tx.ring = tx_ring;
4542 	q_vector->tx.count++;
4543 
4544 	/* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4545 	if (i40e_enabled_xdp_vsi(vsi)) {
4546 		struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4547 
4548 		xdp_ring->q_vector = q_vector;
4549 		xdp_ring->next = q_vector->tx.ring;
4550 		q_vector->tx.ring = xdp_ring;
4551 		q_vector->tx.count++;
4552 	}
4553 
4554 	rx_ring->q_vector = q_vector;
4555 	rx_ring->next = q_vector->rx.ring;
4556 	q_vector->rx.ring = rx_ring;
4557 	q_vector->rx.count++;
4558 }
4559 
4560 /**
4561  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4562  * @vsi: the VSI being configured
4563  *
4564  * This function maps descriptor rings to the queue-specific vectors
4565  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4566  * one vector per queue pair, but on a constrained vector budget, we
4567  * group the queue pairs as "efficiently" as possible.
4568  **/
4569 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4570 {
4571 	int qp_remaining = vsi->num_queue_pairs;
4572 	int q_vectors = vsi->num_q_vectors;
4573 	int num_ringpairs;
4574 	int v_start = 0;
4575 	int qp_idx = 0;
4576 
4577 	/* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4578 	 * group them so there are multiple queues per vector.
4579 	 * It is also important to go through all the vectors available to be
4580 	 * sure that if we don't use all the vectors, that the remaining vectors
4581 	 * are cleared. This is especially important when decreasing the
4582 	 * number of queues in use.
4583 	 */
4584 	for (; v_start < q_vectors; v_start++) {
4585 		struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4586 
4587 		num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4588 
4589 		q_vector->num_ringpairs = num_ringpairs;
4590 		q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4591 
4592 		q_vector->rx.count = 0;
4593 		q_vector->tx.count = 0;
4594 		q_vector->rx.ring = NULL;
4595 		q_vector->tx.ring = NULL;
4596 
4597 		while (num_ringpairs--) {
4598 			i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4599 			qp_idx++;
4600 			qp_remaining--;
4601 		}
4602 	}
4603 }
4604 
4605 /**
4606  * i40e_vsi_request_irq - Request IRQ from the OS
4607  * @vsi: the VSI being configured
4608  * @basename: name for the vector
4609  **/
4610 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4611 {
4612 	struct i40e_pf *pf = vsi->back;
4613 	int err;
4614 
4615 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
4616 		err = i40e_vsi_request_irq_msix(vsi, basename);
4617 	else if (test_bit(I40E_FLAG_MSI_ENA, pf->flags))
4618 		err = request_irq(pf->pdev->irq, i40e_intr, 0,
4619 				  pf->int_name, pf);
4620 	else
4621 		err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4622 				  pf->int_name, pf);
4623 
4624 	if (err)
4625 		dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4626 
4627 	return err;
4628 }
4629 
4630 #ifdef CONFIG_NET_POLL_CONTROLLER
4631 /**
4632  * i40e_netpoll - A Polling 'interrupt' handler
4633  * @netdev: network interface device structure
4634  *
4635  * This is used by netconsole to send skbs without having to re-enable
4636  * interrupts.  It's not called while the normal interrupt routine is executing.
4637  **/
4638 static void i40e_netpoll(struct net_device *netdev)
4639 {
4640 	struct i40e_netdev_priv *np = netdev_priv(netdev);
4641 	struct i40e_vsi *vsi = np->vsi;
4642 	struct i40e_pf *pf = vsi->back;
4643 	int i;
4644 
4645 	/* if interface is down do nothing */
4646 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
4647 		return;
4648 
4649 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4650 		for (i = 0; i < vsi->num_q_vectors; i++)
4651 			i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4652 	} else {
4653 		i40e_intr(pf->pdev->irq, netdev);
4654 	}
4655 }
4656 #endif
4657 
4658 #define I40E_QTX_ENA_WAIT_COUNT 50
4659 
4660 /**
4661  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4662  * @pf: the PF being configured
4663  * @pf_q: the PF queue
4664  * @enable: enable or disable state of the queue
4665  *
4666  * This routine will wait for the given Tx queue of the PF to reach the
4667  * enabled or disabled state.
4668  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4669  * multiple retries; else will return 0 in case of success.
4670  **/
4671 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4672 {
4673 	int i;
4674 	u32 tx_reg;
4675 
4676 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4677 		tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4678 		if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4679 			break;
4680 
4681 		usleep_range(10, 20);
4682 	}
4683 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4684 		return -ETIMEDOUT;
4685 
4686 	return 0;
4687 }
4688 
4689 /**
4690  * i40e_control_tx_q - Start or stop a particular Tx queue
4691  * @pf: the PF structure
4692  * @pf_q: the PF queue to configure
4693  * @enable: start or stop the queue
4694  *
4695  * This function enables or disables a single queue. Note that any delay
4696  * required after the operation is expected to be handled by the caller of
4697  * this function.
4698  **/
4699 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4700 {
4701 	struct i40e_hw *hw = &pf->hw;
4702 	u32 tx_reg;
4703 	int i;
4704 
4705 	/* warn the TX unit of coming changes */
4706 	i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4707 	if (!enable)
4708 		usleep_range(10, 20);
4709 
4710 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4711 		tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4712 		if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4713 		    ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4714 			break;
4715 		usleep_range(1000, 2000);
4716 	}
4717 
4718 	/* Skip if the queue is already in the requested state */
4719 	if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4720 		return;
4721 
4722 	/* turn on/off the queue */
4723 	if (enable) {
4724 		wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4725 		tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4726 	} else {
4727 		tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4728 	}
4729 
4730 	wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4731 }
4732 
4733 /**
4734  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4735  * @seid: VSI SEID
4736  * @pf: the PF structure
4737  * @pf_q: the PF queue to configure
4738  * @is_xdp: true if the queue is used for XDP
4739  * @enable: start or stop the queue
4740  **/
4741 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4742 			   bool is_xdp, bool enable)
4743 {
4744 	int ret;
4745 
4746 	i40e_control_tx_q(pf, pf_q, enable);
4747 
4748 	/* wait for the change to finish */
4749 	ret = i40e_pf_txq_wait(pf, pf_q, enable);
4750 	if (ret) {
4751 		dev_info(&pf->pdev->dev,
4752 			 "VSI seid %d %sTx ring %d %sable timeout\n",
4753 			 seid, (is_xdp ? "XDP " : ""), pf_q,
4754 			 (enable ? "en" : "dis"));
4755 	}
4756 
4757 	return ret;
4758 }
4759 
4760 /**
4761  * i40e_vsi_enable_tx - Start a VSI's rings
4762  * @vsi: the VSI being configured
4763  **/
4764 static int i40e_vsi_enable_tx(struct i40e_vsi *vsi)
4765 {
4766 	struct i40e_pf *pf = vsi->back;
4767 	int i, pf_q, ret = 0;
4768 
4769 	pf_q = vsi->base_queue;
4770 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4771 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4772 					     pf_q,
4773 					     false /*is xdp*/, true);
4774 		if (ret)
4775 			break;
4776 
4777 		if (!i40e_enabled_xdp_vsi(vsi))
4778 			continue;
4779 
4780 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4781 					     pf_q + vsi->alloc_queue_pairs,
4782 					     true /*is xdp*/, true);
4783 		if (ret)
4784 			break;
4785 	}
4786 	return ret;
4787 }
4788 
4789 /**
4790  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4791  * @pf: the PF being configured
4792  * @pf_q: the PF queue
4793  * @enable: enable or disable state of the queue
4794  *
4795  * This routine will wait for the given Rx queue of the PF to reach the
4796  * enabled or disabled state.
4797  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4798  * multiple retries; else will return 0 in case of success.
4799  **/
4800 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4801 {
4802 	int i;
4803 	u32 rx_reg;
4804 
4805 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4806 		rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4807 		if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4808 			break;
4809 
4810 		usleep_range(10, 20);
4811 	}
4812 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4813 		return -ETIMEDOUT;
4814 
4815 	return 0;
4816 }
4817 
4818 /**
4819  * i40e_control_rx_q - Start or stop a particular Rx queue
4820  * @pf: the PF structure
4821  * @pf_q: the PF queue to configure
4822  * @enable: start or stop the queue
4823  *
4824  * This function enables or disables a single queue. Note that
4825  * any delay required after the operation is expected to be
4826  * handled by the caller of this function.
4827  **/
4828 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4829 {
4830 	struct i40e_hw *hw = &pf->hw;
4831 	u32 rx_reg;
4832 	int i;
4833 
4834 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4835 		rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4836 		if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4837 		    ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4838 			break;
4839 		usleep_range(1000, 2000);
4840 	}
4841 
4842 	/* Skip if the queue is already in the requested state */
4843 	if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4844 		return;
4845 
4846 	/* turn on/off the queue */
4847 	if (enable)
4848 		rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4849 	else
4850 		rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4851 
4852 	wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4853 }
4854 
4855 /**
4856  * i40e_control_wait_rx_q
4857  * @pf: the PF structure
4858  * @pf_q: queue being configured
4859  * @enable: start or stop the rings
4860  *
4861  * This function enables or disables a single queue along with waiting
4862  * for the change to finish. The caller of this function should handle
4863  * the delays needed in the case of disabling queues.
4864  **/
4865 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4866 {
4867 	int ret = 0;
4868 
4869 	i40e_control_rx_q(pf, pf_q, enable);
4870 
4871 	/* wait for the change to finish */
4872 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4873 	if (ret)
4874 		return ret;
4875 
4876 	return ret;
4877 }
4878 
4879 /**
4880  * i40e_vsi_enable_rx - Start a VSI's rings
4881  * @vsi: the VSI being configured
4882  **/
4883 static int i40e_vsi_enable_rx(struct i40e_vsi *vsi)
4884 {
4885 	struct i40e_pf *pf = vsi->back;
4886 	int i, pf_q, ret = 0;
4887 
4888 	pf_q = vsi->base_queue;
4889 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4890 		ret = i40e_control_wait_rx_q(pf, pf_q, true);
4891 		if (ret) {
4892 			dev_info(&pf->pdev->dev,
4893 				 "VSI seid %d Rx ring %d enable timeout\n",
4894 				 vsi->seid, pf_q);
4895 			break;
4896 		}
4897 	}
4898 
4899 	return ret;
4900 }
4901 
4902 /**
4903  * i40e_vsi_start_rings - Start a VSI's rings
4904  * @vsi: the VSI being configured
4905  **/
4906 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4907 {
4908 	int ret = 0;
4909 
4910 	/* do rx first for enable and last for disable */
4911 	ret = i40e_vsi_enable_rx(vsi);
4912 	if (ret)
4913 		return ret;
4914 	ret = i40e_vsi_enable_tx(vsi);
4915 
4916 	return ret;
4917 }
4918 
4919 #define I40E_DISABLE_TX_GAP_MSEC	50
4920 
4921 /**
4922  * i40e_vsi_stop_rings - Stop a VSI's rings
4923  * @vsi: the VSI being configured
4924  **/
4925 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4926 {
4927 	struct i40e_pf *pf = vsi->back;
4928 	u32 pf_q, tx_q_end, rx_q_end;
4929 
4930 	/* When port TX is suspended, don't wait */
4931 	if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4932 		return i40e_vsi_stop_rings_no_wait(vsi);
4933 
4934 	tx_q_end = vsi->base_queue +
4935 		vsi->alloc_queue_pairs * (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
4936 	for (pf_q = vsi->base_queue; pf_q < tx_q_end; pf_q++)
4937 		i40e_pre_tx_queue_cfg(&pf->hw, pf_q, false);
4938 
4939 	rx_q_end = vsi->base_queue + vsi->num_queue_pairs;
4940 	for (pf_q = vsi->base_queue; pf_q < rx_q_end; pf_q++)
4941 		i40e_control_rx_q(pf, pf_q, false);
4942 
4943 	msleep(I40E_DISABLE_TX_GAP_MSEC);
4944 	for (pf_q = vsi->base_queue; pf_q < tx_q_end; pf_q++)
4945 		wr32(&pf->hw, I40E_QTX_ENA(pf_q), 0);
4946 
4947 	i40e_vsi_wait_queues_disabled(vsi);
4948 }
4949 
4950 /**
4951  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4952  * @vsi: the VSI being shutdown
4953  *
4954  * This function stops all the rings for a VSI but does not delay to verify
4955  * that rings have been disabled. It is expected that the caller is shutting
4956  * down multiple VSIs at once and will delay together for all the VSIs after
4957  * initiating the shutdown. This is particularly useful for shutting down lots
4958  * of VFs together. Otherwise, a large delay can be incurred while configuring
4959  * each VSI in serial.
4960  **/
4961 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4962 {
4963 	struct i40e_pf *pf = vsi->back;
4964 	int i, pf_q;
4965 
4966 	pf_q = vsi->base_queue;
4967 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4968 		i40e_control_tx_q(pf, pf_q, false);
4969 		i40e_control_rx_q(pf, pf_q, false);
4970 	}
4971 }
4972 
4973 /**
4974  * i40e_vsi_free_irq - Free the irq association with the OS
4975  * @vsi: the VSI being configured
4976  **/
4977 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4978 {
4979 	struct i40e_pf *pf = vsi->back;
4980 	struct i40e_hw *hw = &pf->hw;
4981 	int base = vsi->base_vector;
4982 	u32 val, qp;
4983 	int i;
4984 
4985 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4986 		if (!vsi->q_vectors)
4987 			return;
4988 
4989 		if (!vsi->irqs_ready)
4990 			return;
4991 
4992 		vsi->irqs_ready = false;
4993 		for (i = 0; i < vsi->num_q_vectors; i++) {
4994 			int irq_num;
4995 			u16 vector;
4996 
4997 			vector = i + base;
4998 			irq_num = pf->msix_entries[vector].vector;
4999 
5000 			/* free only the irqs that were actually requested */
5001 			if (!vsi->q_vectors[i] ||
5002 			    !vsi->q_vectors[i]->num_ringpairs)
5003 				continue;
5004 
5005 			/* clear the affinity notifier in the IRQ descriptor */
5006 			irq_set_affinity_notifier(irq_num, NULL);
5007 			/* remove our suggested affinity mask for this IRQ */
5008 			irq_update_affinity_hint(irq_num, NULL);
5009 			free_irq(irq_num, vsi->q_vectors[i]);
5010 
5011 			/* Tear down the interrupt queue link list
5012 			 *
5013 			 * We know that they come in pairs and always
5014 			 * the Rx first, then the Tx.  To clear the
5015 			 * link list, stick the EOL value into the
5016 			 * next_q field of the registers.
5017 			 */
5018 			val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
5019 			qp = FIELD_GET(I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK,
5020 				       val);
5021 			val |= I40E_QUEUE_END_OF_LIST
5022 				<< I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
5023 			wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
5024 
5025 			while (qp != I40E_QUEUE_END_OF_LIST) {
5026 				u32 next;
5027 
5028 				val = rd32(hw, I40E_QINT_RQCTL(qp));
5029 
5030 				val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5031 					 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5032 					 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5033 					 I40E_QINT_RQCTL_INTEVENT_MASK);
5034 
5035 				val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5036 					 I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5037 
5038 				wr32(hw, I40E_QINT_RQCTL(qp), val);
5039 
5040 				val = rd32(hw, I40E_QINT_TQCTL(qp));
5041 
5042 				next = FIELD_GET(I40E_QINT_TQCTL_NEXTQ_INDX_MASK,
5043 						 val);
5044 
5045 				val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5046 					 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5047 					 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5048 					 I40E_QINT_TQCTL_INTEVENT_MASK);
5049 
5050 				val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5051 					 I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5052 
5053 				wr32(hw, I40E_QINT_TQCTL(qp), val);
5054 				qp = next;
5055 			}
5056 		}
5057 	} else {
5058 		free_irq(pf->pdev->irq, pf);
5059 
5060 		val = rd32(hw, I40E_PFINT_LNKLST0);
5061 		qp = FIELD_GET(I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK, val);
5062 		val |= I40E_QUEUE_END_OF_LIST
5063 			<< I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
5064 		wr32(hw, I40E_PFINT_LNKLST0, val);
5065 
5066 		val = rd32(hw, I40E_QINT_RQCTL(qp));
5067 		val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5068 			 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5069 			 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5070 			 I40E_QINT_RQCTL_INTEVENT_MASK);
5071 
5072 		val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5073 			I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5074 
5075 		wr32(hw, I40E_QINT_RQCTL(qp), val);
5076 
5077 		val = rd32(hw, I40E_QINT_TQCTL(qp));
5078 
5079 		val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5080 			 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5081 			 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5082 			 I40E_QINT_TQCTL_INTEVENT_MASK);
5083 
5084 		val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5085 			I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5086 
5087 		wr32(hw, I40E_QINT_TQCTL(qp), val);
5088 	}
5089 }
5090 
5091 /**
5092  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
5093  * @vsi: the VSI being configured
5094  * @v_idx: Index of vector to be freed
5095  *
5096  * This function frees the memory allocated to the q_vector.  In addition if
5097  * NAPI is enabled it will delete any references to the NAPI struct prior
5098  * to freeing the q_vector.
5099  **/
5100 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
5101 {
5102 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
5103 	struct i40e_ring *ring;
5104 
5105 	if (!q_vector)
5106 		return;
5107 
5108 	/* disassociate q_vector from rings */
5109 	i40e_for_each_ring(ring, q_vector->tx)
5110 		ring->q_vector = NULL;
5111 
5112 	i40e_for_each_ring(ring, q_vector->rx)
5113 		ring->q_vector = NULL;
5114 
5115 	/* only VSI w/ an associated netdev is set up w/ NAPI */
5116 	if (vsi->netdev)
5117 		netif_napi_del(&q_vector->napi);
5118 
5119 	vsi->q_vectors[v_idx] = NULL;
5120 
5121 	kfree_rcu(q_vector, rcu);
5122 }
5123 
5124 /**
5125  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
5126  * @vsi: the VSI being un-configured
5127  *
5128  * This frees the memory allocated to the q_vectors and
5129  * deletes references to the NAPI struct.
5130  **/
5131 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
5132 {
5133 	int v_idx;
5134 
5135 	for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
5136 		i40e_free_q_vector(vsi, v_idx);
5137 }
5138 
5139 /**
5140  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
5141  * @pf: board private structure
5142  **/
5143 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
5144 {
5145 	/* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
5146 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
5147 		pci_disable_msix(pf->pdev);
5148 		kfree(pf->msix_entries);
5149 		pf->msix_entries = NULL;
5150 		kfree(pf->irq_pile);
5151 		pf->irq_pile = NULL;
5152 	} else if (test_bit(I40E_FLAG_MSI_ENA, pf->flags)) {
5153 		pci_disable_msi(pf->pdev);
5154 	}
5155 	clear_bit(I40E_FLAG_MSI_ENA, pf->flags);
5156 	clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
5157 }
5158 
5159 /**
5160  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
5161  * @pf: board private structure
5162  *
5163  * We go through and clear interrupt specific resources and reset the structure
5164  * to pre-load conditions
5165  **/
5166 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
5167 {
5168 	struct i40e_vsi *vsi;
5169 	int i;
5170 
5171 	if (test_bit(__I40E_MISC_IRQ_REQUESTED, pf->state))
5172 		i40e_free_misc_vector(pf);
5173 
5174 	i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
5175 		      I40E_IWARP_IRQ_PILE_ID);
5176 
5177 	i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
5178 
5179 	i40e_pf_for_each_vsi(pf, i, vsi)
5180 		i40e_vsi_free_q_vectors(vsi);
5181 
5182 	i40e_reset_interrupt_capability(pf);
5183 }
5184 
5185 /**
5186  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5187  * @vsi: the VSI being configured
5188  **/
5189 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
5190 {
5191 	int q_idx;
5192 
5193 	if (!vsi->netdev)
5194 		return;
5195 
5196 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5197 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5198 
5199 		if (q_vector->rx.ring || q_vector->tx.ring)
5200 			napi_enable(&q_vector->napi);
5201 	}
5202 }
5203 
5204 /**
5205  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
5206  * @vsi: the VSI being configured
5207  **/
5208 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
5209 {
5210 	int q_idx;
5211 
5212 	if (!vsi->netdev)
5213 		return;
5214 
5215 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5216 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5217 
5218 		if (q_vector->rx.ring || q_vector->tx.ring)
5219 			napi_disable(&q_vector->napi);
5220 	}
5221 }
5222 
5223 /**
5224  * i40e_vsi_close - Shut down a VSI
5225  * @vsi: the vsi to be quelled
5226  **/
5227 static void i40e_vsi_close(struct i40e_vsi *vsi)
5228 {
5229 	struct i40e_pf *pf = vsi->back;
5230 	if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
5231 		i40e_down(vsi);
5232 	i40e_vsi_free_irq(vsi);
5233 	i40e_vsi_free_tx_resources(vsi);
5234 	i40e_vsi_free_rx_resources(vsi);
5235 	vsi->current_netdev_flags = 0;
5236 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
5237 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
5238 		set_bit(__I40E_CLIENT_RESET, pf->state);
5239 }
5240 
5241 /**
5242  * i40e_quiesce_vsi - Pause a given VSI
5243  * @vsi: the VSI being paused
5244  **/
5245 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
5246 {
5247 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
5248 		return;
5249 
5250 	set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
5251 	if (vsi->netdev && netif_running(vsi->netdev))
5252 		vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
5253 	else
5254 		i40e_vsi_close(vsi);
5255 }
5256 
5257 /**
5258  * i40e_unquiesce_vsi - Resume a given VSI
5259  * @vsi: the VSI being resumed
5260  **/
5261 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
5262 {
5263 	if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
5264 		return;
5265 
5266 	if (vsi->netdev && netif_running(vsi->netdev))
5267 		vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
5268 	else
5269 		i40e_vsi_open(vsi);   /* this clears the DOWN bit */
5270 }
5271 
5272 /**
5273  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
5274  * @pf: the PF
5275  **/
5276 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
5277 {
5278 	struct i40e_vsi *vsi;
5279 	int v;
5280 
5281 	i40e_pf_for_each_vsi(pf, v, vsi)
5282 		i40e_quiesce_vsi(vsi);
5283 }
5284 
5285 /**
5286  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
5287  * @pf: the PF
5288  **/
5289 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
5290 {
5291 	struct i40e_vsi *vsi;
5292 	int v;
5293 
5294 	i40e_pf_for_each_vsi(pf, v, vsi)
5295 		i40e_unquiesce_vsi(vsi);
5296 }
5297 
5298 /**
5299  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
5300  * @vsi: the VSI being configured
5301  *
5302  * Wait until all queues on a given VSI have been disabled.
5303  **/
5304 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
5305 {
5306 	struct i40e_pf *pf = vsi->back;
5307 	int i, pf_q, ret;
5308 
5309 	pf_q = vsi->base_queue;
5310 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
5311 		/* Check and wait for the Tx queue */
5312 		ret = i40e_pf_txq_wait(pf, pf_q, false);
5313 		if (ret) {
5314 			dev_info(&pf->pdev->dev,
5315 				 "VSI seid %d Tx ring %d disable timeout\n",
5316 				 vsi->seid, pf_q);
5317 			return ret;
5318 		}
5319 
5320 		if (!i40e_enabled_xdp_vsi(vsi))
5321 			goto wait_rx;
5322 
5323 		/* Check and wait for the XDP Tx queue */
5324 		ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
5325 				       false);
5326 		if (ret) {
5327 			dev_info(&pf->pdev->dev,
5328 				 "VSI seid %d XDP Tx ring %d disable timeout\n",
5329 				 vsi->seid, pf_q);
5330 			return ret;
5331 		}
5332 wait_rx:
5333 		/* Check and wait for the Rx queue */
5334 		ret = i40e_pf_rxq_wait(pf, pf_q, false);
5335 		if (ret) {
5336 			dev_info(&pf->pdev->dev,
5337 				 "VSI seid %d Rx ring %d disable timeout\n",
5338 				 vsi->seid, pf_q);
5339 			return ret;
5340 		}
5341 	}
5342 
5343 	return 0;
5344 }
5345 
5346 #ifdef CONFIG_I40E_DCB
5347 /**
5348  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
5349  * @pf: the PF
5350  *
5351  * This function waits for the queues to be in disabled state for all the
5352  * VSIs that are managed by this PF.
5353  **/
5354 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
5355 {
5356 	struct i40e_vsi *vsi;
5357 	int v, ret = 0;
5358 
5359 	i40e_pf_for_each_vsi(pf, v, vsi) {
5360 		ret = i40e_vsi_wait_queues_disabled(vsi);
5361 		if (ret)
5362 			break;
5363 	}
5364 
5365 	return ret;
5366 }
5367 
5368 #endif
5369 
5370 /**
5371  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
5372  * @pf: pointer to PF
5373  *
5374  * Get TC map for ISCSI PF type that will include iSCSI TC
5375  * and LAN TC.
5376  **/
5377 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
5378 {
5379 	struct i40e_dcb_app_priority_table app;
5380 	struct i40e_hw *hw = &pf->hw;
5381 	u8 enabled_tc = 1; /* TC0 is always enabled */
5382 	u8 tc, i;
5383 	/* Get the iSCSI APP TLV */
5384 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5385 
5386 	for (i = 0; i < dcbcfg->numapps; i++) {
5387 		app = dcbcfg->app[i];
5388 		if (app.selector == I40E_APP_SEL_TCPIP &&
5389 		    app.protocolid == I40E_APP_PROTOID_ISCSI) {
5390 			tc = dcbcfg->etscfg.prioritytable[app.priority];
5391 			enabled_tc |= BIT(tc);
5392 			break;
5393 		}
5394 	}
5395 
5396 	return enabled_tc;
5397 }
5398 
5399 /**
5400  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5401  * @dcbcfg: the corresponding DCBx configuration structure
5402  *
5403  * Return the number of TCs from given DCBx configuration
5404  **/
5405 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5406 {
5407 	int i, tc_unused = 0;
5408 	u8 num_tc = 0;
5409 	u8 ret = 0;
5410 
5411 	/* Scan the ETS Config Priority Table to find
5412 	 * traffic class enabled for a given priority
5413 	 * and create a bitmask of enabled TCs
5414 	 */
5415 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5416 		num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5417 
5418 	/* Now scan the bitmask to check for
5419 	 * contiguous TCs starting with TC0
5420 	 */
5421 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5422 		if (num_tc & BIT(i)) {
5423 			if (!tc_unused) {
5424 				ret++;
5425 			} else {
5426 				pr_err("Non-contiguous TC - Disabling DCB\n");
5427 				return 1;
5428 			}
5429 		} else {
5430 			tc_unused = 1;
5431 		}
5432 	}
5433 
5434 	/* There is always at least TC0 */
5435 	if (!ret)
5436 		ret = 1;
5437 
5438 	return ret;
5439 }
5440 
5441 /**
5442  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5443  * @dcbcfg: the corresponding DCBx configuration structure
5444  *
5445  * Query the current DCB configuration and return the number of
5446  * traffic classes enabled from the given DCBX config
5447  **/
5448 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5449 {
5450 	u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5451 	u8 enabled_tc = 1;
5452 	u8 i;
5453 
5454 	for (i = 0; i < num_tc; i++)
5455 		enabled_tc |= BIT(i);
5456 
5457 	return enabled_tc;
5458 }
5459 
5460 /**
5461  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5462  * @pf: PF being queried
5463  *
5464  * Query the current MQPRIO configuration and return the number of
5465  * traffic classes enabled.
5466  **/
5467 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5468 {
5469 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
5470 	u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5471 	u8 enabled_tc = 1, i;
5472 
5473 	for (i = 1; i < num_tc; i++)
5474 		enabled_tc |= BIT(i);
5475 	return enabled_tc;
5476 }
5477 
5478 /**
5479  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5480  * @pf: PF being queried
5481  *
5482  * Return number of traffic classes enabled for the given PF
5483  **/
5484 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5485 {
5486 	u8 i, enabled_tc = 1;
5487 	u8 num_tc = 0;
5488 
5489 	if (i40e_is_tc_mqprio_enabled(pf)) {
5490 		struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
5491 
5492 		return vsi->mqprio_qopt.qopt.num_tc;
5493 	}
5494 
5495 	/* If neither MQPRIO nor DCB is enabled, then always use single TC */
5496 	if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags))
5497 		return 1;
5498 
5499 	/* SFP mode will be enabled for all TCs on port */
5500 	if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
5501 		return i40e_dcb_get_num_tc(&pf->hw.local_dcbx_config);
5502 
5503 	/* MFP mode return count of enabled TCs for this PF */
5504 	if (pf->hw.func_caps.iscsi)
5505 		enabled_tc =  i40e_get_iscsi_tc_map(pf);
5506 	else
5507 		return 1; /* Only TC0 */
5508 
5509 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5510 		if (enabled_tc & BIT(i))
5511 			num_tc++;
5512 	}
5513 	return num_tc;
5514 }
5515 
5516 /**
5517  * i40e_pf_get_tc_map - Get bitmap for enabled traffic classes
5518  * @pf: PF being queried
5519  *
5520  * Return a bitmap for enabled traffic classes for this PF.
5521  **/
5522 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5523 {
5524 	if (i40e_is_tc_mqprio_enabled(pf))
5525 		return i40e_mqprio_get_enabled_tc(pf);
5526 
5527 	/* If neither MQPRIO nor DCB is enabled for this PF then just return
5528 	 * default TC
5529 	 */
5530 	if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags))
5531 		return I40E_DEFAULT_TRAFFIC_CLASS;
5532 
5533 	/* SFP mode we want PF to be enabled for all TCs */
5534 	if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
5535 		return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5536 
5537 	/* MFP enabled and iSCSI PF type */
5538 	if (pf->hw.func_caps.iscsi)
5539 		return i40e_get_iscsi_tc_map(pf);
5540 	else
5541 		return I40E_DEFAULT_TRAFFIC_CLASS;
5542 }
5543 
5544 /**
5545  * i40e_vsi_get_bw_info - Query VSI BW Information
5546  * @vsi: the VSI being queried
5547  *
5548  * Returns 0 on success, negative value on failure
5549  **/
5550 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5551 {
5552 	struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5553 	struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5554 	struct i40e_pf *pf = vsi->back;
5555 	struct i40e_hw *hw = &pf->hw;
5556 	u32 tc_bw_max;
5557 	int ret;
5558 	int i;
5559 
5560 	/* Get the VSI level BW configuration */
5561 	ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5562 	if (ret) {
5563 		dev_info(&pf->pdev->dev,
5564 			 "couldn't get PF vsi bw config, err %pe aq_err %s\n",
5565 			 ERR_PTR(ret),
5566 			 libie_aq_str(pf->hw.aq.asq_last_status));
5567 		return -EINVAL;
5568 	}
5569 
5570 	/* Get the VSI level BW configuration per TC */
5571 	ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5572 					       NULL);
5573 	if (ret) {
5574 		dev_info(&pf->pdev->dev,
5575 			 "couldn't get PF vsi ets bw config, err %pe aq_err %s\n",
5576 			 ERR_PTR(ret),
5577 			 libie_aq_str(pf->hw.aq.asq_last_status));
5578 		return -EINVAL;
5579 	}
5580 
5581 	if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5582 		dev_info(&pf->pdev->dev,
5583 			 "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5584 			 bw_config.tc_valid_bits,
5585 			 bw_ets_config.tc_valid_bits);
5586 		/* Still continuing */
5587 	}
5588 
5589 	vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5590 	vsi->bw_max_quanta = bw_config.max_bw;
5591 	tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5592 		    (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5593 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5594 		vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5595 		vsi->bw_ets_limit_credits[i] =
5596 					le16_to_cpu(bw_ets_config.credits[i]);
5597 		/* 3 bits out of 4 for each TC */
5598 		vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5599 	}
5600 
5601 	return 0;
5602 }
5603 
5604 /**
5605  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5606  * @vsi: the VSI being configured
5607  * @enabled_tc: TC bitmap
5608  * @bw_share: BW shared credits per TC
5609  *
5610  * Returns 0 on success, negative value on failure
5611  **/
5612 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5613 				       u8 *bw_share)
5614 {
5615 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5616 	struct i40e_pf *pf = vsi->back;
5617 	int ret;
5618 	int i;
5619 
5620 	/* There is no need to reset BW when mqprio mode is on.  */
5621 	if (i40e_is_tc_mqprio_enabled(pf))
5622 		return 0;
5623 	if (!vsi->mqprio_qopt.qopt.hw && !test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
5624 		ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5625 		if (ret)
5626 			dev_info(&pf->pdev->dev,
5627 				 "Failed to reset tx rate for vsi->seid %u\n",
5628 				 vsi->seid);
5629 		return ret;
5630 	}
5631 	memset(&bw_data, 0, sizeof(bw_data));
5632 	bw_data.tc_valid_bits = enabled_tc;
5633 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5634 		bw_data.tc_bw_credits[i] = bw_share[i];
5635 
5636 	ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5637 	if (ret) {
5638 		dev_info(&pf->pdev->dev,
5639 			 "AQ command Config VSI BW allocation per TC failed = %d\n",
5640 			 pf->hw.aq.asq_last_status);
5641 		return -EINVAL;
5642 	}
5643 
5644 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5645 		vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5646 
5647 	return 0;
5648 }
5649 
5650 /**
5651  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5652  * @vsi: the VSI being configured
5653  * @enabled_tc: TC map to be enabled
5654  *
5655  **/
5656 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5657 {
5658 	struct net_device *netdev = vsi->netdev;
5659 	struct i40e_pf *pf = vsi->back;
5660 	struct i40e_hw *hw = &pf->hw;
5661 	u8 netdev_tc = 0;
5662 	int i;
5663 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5664 
5665 	if (!netdev)
5666 		return;
5667 
5668 	if (!enabled_tc) {
5669 		netdev_reset_tc(netdev);
5670 		return;
5671 	}
5672 
5673 	/* Set up actual enabled TCs on the VSI */
5674 	if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5675 		return;
5676 
5677 	/* set per TC queues for the VSI */
5678 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5679 		/* Only set TC queues for enabled tcs
5680 		 *
5681 		 * e.g. For a VSI that has TC0 and TC3 enabled the
5682 		 * enabled_tc bitmap would be 0x00001001; the driver
5683 		 * will set the numtc for netdev as 2 that will be
5684 		 * referenced by the netdev layer as TC 0 and 1.
5685 		 */
5686 		if (vsi->tc_config.enabled_tc & BIT(i))
5687 			netdev_set_tc_queue(netdev,
5688 					vsi->tc_config.tc_info[i].netdev_tc,
5689 					vsi->tc_config.tc_info[i].qcount,
5690 					vsi->tc_config.tc_info[i].qoffset);
5691 	}
5692 
5693 	if (i40e_is_tc_mqprio_enabled(pf))
5694 		return;
5695 
5696 	/* Assign UP2TC map for the VSI */
5697 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5698 		/* Get the actual TC# for the UP */
5699 		u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5700 		/* Get the mapped netdev TC# for the UP */
5701 		netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5702 		netdev_set_prio_tc_map(netdev, i, netdev_tc);
5703 	}
5704 }
5705 
5706 /**
5707  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5708  * @vsi: the VSI being configured
5709  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5710  **/
5711 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5712 				      struct i40e_vsi_context *ctxt)
5713 {
5714 	/* copy just the sections touched not the entire info
5715 	 * since not all sections are valid as returned by
5716 	 * update vsi params
5717 	 */
5718 	vsi->info.mapping_flags = ctxt->info.mapping_flags;
5719 	memcpy(&vsi->info.queue_mapping,
5720 	       &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5721 	memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5722 	       sizeof(vsi->info.tc_mapping));
5723 }
5724 
5725 /**
5726  * i40e_update_adq_vsi_queues - update queue mapping for ADq VSI
5727  * @vsi: the VSI being reconfigured
5728  * @vsi_offset: offset from main VF VSI
5729  */
5730 int i40e_update_adq_vsi_queues(struct i40e_vsi *vsi, int vsi_offset)
5731 {
5732 	struct i40e_vsi_context ctxt = {};
5733 	struct i40e_pf *pf;
5734 	struct i40e_hw *hw;
5735 	int ret;
5736 
5737 	if (!vsi)
5738 		return -EINVAL;
5739 	pf = vsi->back;
5740 	hw = &pf->hw;
5741 
5742 	ctxt.seid = vsi->seid;
5743 	ctxt.pf_num = hw->pf_id;
5744 	ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id + vsi_offset;
5745 	ctxt.uplink_seid = vsi->uplink_seid;
5746 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5747 	ctxt.flags = I40E_AQ_VSI_TYPE_VF;
5748 	ctxt.info = vsi->info;
5749 
5750 	i40e_vsi_setup_queue_map(vsi, &ctxt, vsi->tc_config.enabled_tc,
5751 				 false);
5752 	if (vsi->reconfig_rss) {
5753 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
5754 				      vsi->num_queue_pairs);
5755 		ret = i40e_vsi_config_rss(vsi);
5756 		if (ret) {
5757 			dev_info(&pf->pdev->dev, "Failed to reconfig rss for num_queues\n");
5758 			return ret;
5759 		}
5760 		vsi->reconfig_rss = false;
5761 	}
5762 
5763 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5764 	if (ret) {
5765 		dev_info(&pf->pdev->dev, "Update vsi config failed, err %pe aq_err %s\n",
5766 			 ERR_PTR(ret),
5767 			 libie_aq_str(hw->aq.asq_last_status));
5768 		return ret;
5769 	}
5770 	/* update the local VSI info with updated queue map */
5771 	i40e_vsi_update_queue_map(vsi, &ctxt);
5772 	vsi->info.valid_sections = 0;
5773 
5774 	return ret;
5775 }
5776 
5777 /**
5778  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5779  * @vsi: VSI to be configured
5780  * @enabled_tc: TC bitmap
5781  *
5782  * This configures a particular VSI for TCs that are mapped to the
5783  * given TC bitmap. It uses default bandwidth share for TCs across
5784  * VSIs to configure TC for a particular VSI.
5785  *
5786  * NOTE:
5787  * It is expected that the VSI queues have been quisced before calling
5788  * this function.
5789  **/
5790 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5791 {
5792 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5793 	struct i40e_pf *pf = vsi->back;
5794 	struct i40e_hw *hw = &pf->hw;
5795 	struct i40e_vsi_context ctxt;
5796 	int ret = 0;
5797 	int i;
5798 
5799 	/* Check if enabled_tc is same as existing or new TCs */
5800 	if (vsi->tc_config.enabled_tc == enabled_tc &&
5801 	    vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5802 		return ret;
5803 
5804 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
5805 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5806 		if (enabled_tc & BIT(i))
5807 			bw_share[i] = 1;
5808 	}
5809 
5810 	ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5811 	if (ret) {
5812 		struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5813 
5814 		dev_info(&pf->pdev->dev,
5815 			 "Failed configuring TC map %d for VSI %d\n",
5816 			 enabled_tc, vsi->seid);
5817 		ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5818 						  &bw_config, NULL);
5819 		if (ret) {
5820 			dev_info(&pf->pdev->dev,
5821 				 "Failed querying vsi bw info, err %pe aq_err %s\n",
5822 				 ERR_PTR(ret),
5823 				 libie_aq_str(hw->aq.asq_last_status));
5824 			goto out;
5825 		}
5826 		if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5827 			u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5828 
5829 			if (!valid_tc)
5830 				valid_tc = bw_config.tc_valid_bits;
5831 			/* Always enable TC0, no matter what */
5832 			valid_tc |= 1;
5833 			dev_info(&pf->pdev->dev,
5834 				 "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5835 				 enabled_tc, bw_config.tc_valid_bits, valid_tc);
5836 			enabled_tc = valid_tc;
5837 		}
5838 
5839 		ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5840 		if (ret) {
5841 			dev_err(&pf->pdev->dev,
5842 				"Unable to  configure TC map %d for VSI %d\n",
5843 				enabled_tc, vsi->seid);
5844 			goto out;
5845 		}
5846 	}
5847 
5848 	/* Update Queue Pairs Mapping for currently enabled UPs */
5849 	ctxt.seid = vsi->seid;
5850 	ctxt.pf_num = vsi->back->hw.pf_id;
5851 	ctxt.vf_num = 0;
5852 	ctxt.uplink_seid = vsi->uplink_seid;
5853 	ctxt.info = vsi->info;
5854 	if (i40e_is_tc_mqprio_enabled(pf)) {
5855 		ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5856 		if (ret)
5857 			goto out;
5858 	} else {
5859 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5860 	}
5861 
5862 	/* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5863 	 * queues changed.
5864 	 */
5865 	if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5866 		vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5867 				      vsi->num_queue_pairs);
5868 		ret = i40e_vsi_config_rss(vsi);
5869 		if (ret) {
5870 			dev_info(&vsi->back->pdev->dev,
5871 				 "Failed to reconfig rss for num_queues\n");
5872 			return ret;
5873 		}
5874 		vsi->reconfig_rss = false;
5875 	}
5876 	if (test_bit(I40E_FLAG_IWARP_ENA, vsi->back->flags)) {
5877 		ctxt.info.valid_sections |=
5878 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5879 		ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5880 	}
5881 
5882 	/* Update the VSI after updating the VSI queue-mapping
5883 	 * information
5884 	 */
5885 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5886 	if (ret) {
5887 		dev_info(&pf->pdev->dev,
5888 			 "Update vsi tc config failed, err %pe aq_err %s\n",
5889 			 ERR_PTR(ret),
5890 			 libie_aq_str(hw->aq.asq_last_status));
5891 		goto out;
5892 	}
5893 	/* update the local VSI info with updated queue map */
5894 	i40e_vsi_update_queue_map(vsi, &ctxt);
5895 	vsi->info.valid_sections = 0;
5896 
5897 	/* Update current VSI BW information */
5898 	ret = i40e_vsi_get_bw_info(vsi);
5899 	if (ret) {
5900 		dev_info(&pf->pdev->dev,
5901 			 "Failed updating vsi bw info, err %pe aq_err %s\n",
5902 			 ERR_PTR(ret),
5903 			 libie_aq_str(hw->aq.asq_last_status));
5904 		goto out;
5905 	}
5906 
5907 	/* Update the netdev TC setup */
5908 	i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5909 out:
5910 	return ret;
5911 }
5912 
5913 /**
5914  * i40e_vsi_reconfig_tc - Reconfigure VSI Tx Scheduler for stored TC map
5915  * @vsi: VSI to be reconfigured
5916  *
5917  * This reconfigures a particular VSI for TCs that are mapped to the
5918  * TC bitmap stored previously for the VSI.
5919  *
5920  * Context: It is expected that the VSI queues have been quisced before
5921  *          calling this function.
5922  *
5923  * Return: 0 on success, negative value on failure
5924  **/
5925 static int i40e_vsi_reconfig_tc(struct i40e_vsi *vsi)
5926 {
5927 	u8 enabled_tc;
5928 
5929 	enabled_tc = vsi->tc_config.enabled_tc;
5930 	vsi->tc_config.enabled_tc = 0;
5931 
5932 	return i40e_vsi_config_tc(vsi, enabled_tc);
5933 }
5934 
5935 /**
5936  * i40e_get_link_speed - Returns link speed for the interface
5937  * @vsi: VSI to be configured
5938  *
5939  **/
5940 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5941 {
5942 	struct i40e_pf *pf = vsi->back;
5943 
5944 	switch (pf->hw.phy.link_info.link_speed) {
5945 	case I40E_LINK_SPEED_40GB:
5946 		return 40000;
5947 	case I40E_LINK_SPEED_25GB:
5948 		return 25000;
5949 	case I40E_LINK_SPEED_20GB:
5950 		return 20000;
5951 	case I40E_LINK_SPEED_10GB:
5952 		return 10000;
5953 	case I40E_LINK_SPEED_1GB:
5954 		return 1000;
5955 	default:
5956 		return -EINVAL;
5957 	}
5958 }
5959 
5960 /**
5961  * i40e_bw_bytes_to_mbits - Convert max_tx_rate from bytes to mbits
5962  * @vsi: Pointer to vsi structure
5963  * @max_tx_rate: max TX rate in bytes to be converted into Mbits
5964  *
5965  * Helper function to convert units before send to set BW limit
5966  **/
5967 static u64 i40e_bw_bytes_to_mbits(struct i40e_vsi *vsi, u64 max_tx_rate)
5968 {
5969 	if (max_tx_rate < I40E_BW_MBPS_DIVISOR) {
5970 		dev_warn(&vsi->back->pdev->dev,
5971 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
5972 		max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5973 	} else {
5974 		do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
5975 	}
5976 
5977 	return max_tx_rate;
5978 }
5979 
5980 /**
5981  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5982  * @vsi: VSI to be configured
5983  * @seid: seid of the channel/VSI
5984  * @max_tx_rate: max TX rate to be configured as BW limit
5985  *
5986  * Helper function to set BW limit for a given VSI
5987  **/
5988 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5989 {
5990 	struct i40e_pf *pf = vsi->back;
5991 	u64 credits = 0;
5992 	int speed = 0;
5993 	int ret = 0;
5994 
5995 	speed = i40e_get_link_speed(vsi);
5996 	if (max_tx_rate > speed) {
5997 		dev_err(&pf->pdev->dev,
5998 			"Invalid max tx rate %llu specified for VSI seid %d.",
5999 			max_tx_rate, seid);
6000 		return -EINVAL;
6001 	}
6002 	if (max_tx_rate && max_tx_rate < I40E_BW_CREDIT_DIVISOR) {
6003 		dev_warn(&pf->pdev->dev,
6004 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
6005 		max_tx_rate = I40E_BW_CREDIT_DIVISOR;
6006 	}
6007 
6008 	/* Tx rate credits are in values of 50Mbps, 0 is disabled */
6009 	credits = max_tx_rate;
6010 	do_div(credits, I40E_BW_CREDIT_DIVISOR);
6011 	ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
6012 					  I40E_MAX_BW_INACTIVE_ACCUM, NULL);
6013 	if (ret)
6014 		dev_err(&pf->pdev->dev,
6015 			"Failed set tx rate (%llu Mbps) for vsi->seid %u, err %pe aq_err %s\n",
6016 			max_tx_rate, seid, ERR_PTR(ret),
6017 			libie_aq_str(pf->hw.aq.asq_last_status));
6018 	return ret;
6019 }
6020 
6021 /**
6022  * i40e_remove_queue_channels - Remove queue channels for the TCs
6023  * @vsi: VSI to be configured
6024  *
6025  * Remove queue channels for the TCs
6026  **/
6027 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
6028 {
6029 	struct i40e_cloud_filter *cfilter;
6030 	enum libie_aq_err last_aq_status;
6031 	struct i40e_channel *ch, *ch_tmp;
6032 	struct i40e_pf *pf = vsi->back;
6033 	struct hlist_node *node;
6034 	int ret, i;
6035 
6036 	/* Reset rss size that was stored when reconfiguring rss for
6037 	 * channel VSIs with non-power-of-2 queue count.
6038 	 */
6039 	vsi->current_rss_size = 0;
6040 
6041 	/* perform cleanup for channels if they exist */
6042 	if (list_empty(&vsi->ch_list))
6043 		return;
6044 
6045 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6046 		struct i40e_vsi *p_vsi;
6047 
6048 		list_del(&ch->list);
6049 		p_vsi = ch->parent_vsi;
6050 		if (!p_vsi || !ch->initialized) {
6051 			kfree(ch);
6052 			continue;
6053 		}
6054 		/* Reset queue contexts */
6055 		for (i = 0; i < ch->num_queue_pairs; i++) {
6056 			struct i40e_ring *tx_ring, *rx_ring;
6057 			u16 pf_q;
6058 
6059 			pf_q = ch->base_queue + i;
6060 			tx_ring = vsi->tx_rings[pf_q];
6061 			tx_ring->ch = NULL;
6062 
6063 			rx_ring = vsi->rx_rings[pf_q];
6064 			rx_ring->ch = NULL;
6065 		}
6066 
6067 		/* Reset BW configured for this VSI via mqprio */
6068 		ret = i40e_set_bw_limit(vsi, ch->seid, 0);
6069 		if (ret)
6070 			dev_info(&vsi->back->pdev->dev,
6071 				 "Failed to reset tx rate for ch->seid %u\n",
6072 				 ch->seid);
6073 
6074 		/* delete cloud filters associated with this channel */
6075 		hlist_for_each_entry_safe(cfilter, node,
6076 					  &pf->cloud_filter_list, cloud_node) {
6077 			if (cfilter->seid != ch->seid)
6078 				continue;
6079 
6080 			hash_del(&cfilter->cloud_node);
6081 			if (cfilter->dst_port)
6082 				ret = i40e_add_del_cloud_filter_big_buf(vsi,
6083 									cfilter,
6084 									false);
6085 			else
6086 				ret = i40e_add_del_cloud_filter(vsi, cfilter,
6087 								false);
6088 			last_aq_status = pf->hw.aq.asq_last_status;
6089 			if (ret)
6090 				dev_info(&pf->pdev->dev,
6091 					 "Failed to delete cloud filter, err %pe aq_err %s\n",
6092 					 ERR_PTR(ret),
6093 					 libie_aq_str(last_aq_status));
6094 			kfree(cfilter);
6095 		}
6096 
6097 		/* delete VSI from FW */
6098 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
6099 					     NULL);
6100 		if (ret)
6101 			dev_err(&vsi->back->pdev->dev,
6102 				"unable to remove channel (%d) for parent VSI(%d)\n",
6103 				ch->seid, p_vsi->seid);
6104 		kfree(ch);
6105 	}
6106 	INIT_LIST_HEAD(&vsi->ch_list);
6107 }
6108 
6109 /**
6110  * i40e_get_max_queues_for_channel
6111  * @vsi: ptr to VSI to which channels are associated with
6112  *
6113  * Helper function which returns max value among the queue counts set on the
6114  * channels/TCs created.
6115  **/
6116 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
6117 {
6118 	struct i40e_channel *ch, *ch_tmp;
6119 	int max = 0;
6120 
6121 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6122 		if (!ch->initialized)
6123 			continue;
6124 		if (ch->num_queue_pairs > max)
6125 			max = ch->num_queue_pairs;
6126 	}
6127 
6128 	return max;
6129 }
6130 
6131 /**
6132  * i40e_validate_num_queues - validate num_queues w.r.t channel
6133  * @pf: ptr to PF device
6134  * @num_queues: number of queues
6135  * @vsi: the parent VSI
6136  * @reconfig_rss: indicates should the RSS be reconfigured or not
6137  *
6138  * This function validates number of queues in the context of new channel
6139  * which is being established and determines if RSS should be reconfigured
6140  * or not for parent VSI.
6141  **/
6142 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
6143 				    struct i40e_vsi *vsi, bool *reconfig_rss)
6144 {
6145 	int max_ch_queues;
6146 
6147 	if (!reconfig_rss)
6148 		return -EINVAL;
6149 
6150 	*reconfig_rss = false;
6151 	if (vsi->current_rss_size) {
6152 		if (num_queues > vsi->current_rss_size) {
6153 			dev_dbg(&pf->pdev->dev,
6154 				"Error: num_queues (%d) > vsi's current_size(%d)\n",
6155 				num_queues, vsi->current_rss_size);
6156 			return -EINVAL;
6157 		} else if ((num_queues < vsi->current_rss_size) &&
6158 			   (!is_power_of_2(num_queues))) {
6159 			dev_dbg(&pf->pdev->dev,
6160 				"Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
6161 				num_queues, vsi->current_rss_size);
6162 			return -EINVAL;
6163 		}
6164 	}
6165 
6166 	if (!is_power_of_2(num_queues)) {
6167 		/* Find the max num_queues configured for channel if channel
6168 		 * exist.
6169 		 * if channel exist, then enforce 'num_queues' to be more than
6170 		 * max ever queues configured for channel.
6171 		 */
6172 		max_ch_queues = i40e_get_max_queues_for_channel(vsi);
6173 		if (num_queues < max_ch_queues) {
6174 			dev_dbg(&pf->pdev->dev,
6175 				"Error: num_queues (%d) < max queues configured for channel(%d)\n",
6176 				num_queues, max_ch_queues);
6177 			return -EINVAL;
6178 		}
6179 		*reconfig_rss = true;
6180 	}
6181 
6182 	return 0;
6183 }
6184 
6185 /**
6186  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
6187  * @vsi: the VSI being setup
6188  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
6189  *
6190  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
6191  **/
6192 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
6193 {
6194 	struct i40e_pf *pf = vsi->back;
6195 	u8 seed[I40E_HKEY_ARRAY_SIZE];
6196 	struct i40e_hw *hw = &pf->hw;
6197 	int local_rss_size;
6198 	u8 *lut;
6199 	int ret;
6200 
6201 	if (!vsi->rss_size)
6202 		return -EINVAL;
6203 
6204 	if (rss_size > vsi->rss_size)
6205 		return -EINVAL;
6206 
6207 	local_rss_size = min_t(int, vsi->rss_size, rss_size);
6208 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
6209 	if (!lut)
6210 		return -ENOMEM;
6211 
6212 	/* Ignoring user configured lut if there is one */
6213 	i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
6214 
6215 	/* Use user configured hash key if there is one, otherwise
6216 	 * use default.
6217 	 */
6218 	if (vsi->rss_hkey_user)
6219 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
6220 	else
6221 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
6222 
6223 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
6224 	if (ret) {
6225 		dev_info(&pf->pdev->dev,
6226 			 "Cannot set RSS lut, err %pe aq_err %s\n",
6227 			 ERR_PTR(ret),
6228 			 libie_aq_str(hw->aq.asq_last_status));
6229 		kfree(lut);
6230 		return ret;
6231 	}
6232 	kfree(lut);
6233 
6234 	/* Do the update w.r.t. storing rss_size */
6235 	if (!vsi->orig_rss_size)
6236 		vsi->orig_rss_size = vsi->rss_size;
6237 	vsi->current_rss_size = local_rss_size;
6238 
6239 	return ret;
6240 }
6241 
6242 /**
6243  * i40e_channel_setup_queue_map - Setup a channel queue map
6244  * @pf: ptr to PF device
6245  * @ctxt: VSI context structure
6246  * @ch: ptr to channel structure
6247  *
6248  * Setup queue map for a specific channel
6249  **/
6250 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
6251 					 struct i40e_vsi_context *ctxt,
6252 					 struct i40e_channel *ch)
6253 {
6254 	u16 qcount, qmap, sections = 0;
6255 	u8 offset = 0;
6256 	int pow;
6257 
6258 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
6259 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
6260 
6261 	qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
6262 	ch->num_queue_pairs = qcount;
6263 
6264 	/* find the next higher power-of-2 of num queue pairs */
6265 	pow = ilog2(qcount);
6266 	if (!is_power_of_2(qcount))
6267 		pow++;
6268 
6269 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
6270 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
6271 
6272 	/* Setup queue TC[0].qmap for given VSI context */
6273 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
6274 
6275 	ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
6276 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
6277 	ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
6278 	ctxt->info.valid_sections |= cpu_to_le16(sections);
6279 }
6280 
6281 /**
6282  * i40e_add_channel - add a channel by adding VSI
6283  * @pf: ptr to PF device
6284  * @uplink_seid: underlying HW switching element (VEB) ID
6285  * @ch: ptr to channel structure
6286  *
6287  * Add a channel (VSI) using add_vsi and queue_map
6288  **/
6289 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
6290 			    struct i40e_channel *ch)
6291 {
6292 	struct i40e_hw *hw = &pf->hw;
6293 	struct i40e_vsi_context ctxt;
6294 	u8 enabled_tc = 0x1; /* TC0 enabled */
6295 	int ret;
6296 
6297 	if (ch->type != I40E_VSI_VMDQ2) {
6298 		dev_info(&pf->pdev->dev,
6299 			 "add new vsi failed, ch->type %d\n", ch->type);
6300 		return -EINVAL;
6301 	}
6302 
6303 	memset(&ctxt, 0, sizeof(ctxt));
6304 	ctxt.pf_num = hw->pf_id;
6305 	ctxt.vf_num = 0;
6306 	ctxt.uplink_seid = uplink_seid;
6307 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
6308 	if (ch->type == I40E_VSI_VMDQ2)
6309 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
6310 
6311 	if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
6312 		ctxt.info.valid_sections |=
6313 		     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6314 		ctxt.info.switch_id =
6315 		   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6316 	}
6317 
6318 	/* Set queue map for a given VSI context */
6319 	i40e_channel_setup_queue_map(pf, &ctxt, ch);
6320 
6321 	/* Now time to create VSI */
6322 	ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
6323 	if (ret) {
6324 		dev_info(&pf->pdev->dev,
6325 			 "add new vsi failed, err %pe aq_err %s\n",
6326 			 ERR_PTR(ret),
6327 			 libie_aq_str(pf->hw.aq.asq_last_status));
6328 		return -ENOENT;
6329 	}
6330 
6331 	/* Success, update channel, set enabled_tc only if the channel
6332 	 * is not a macvlan
6333 	 */
6334 	ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
6335 	ch->seid = ctxt.seid;
6336 	ch->vsi_number = ctxt.vsi_number;
6337 	ch->stat_counter_idx = le16_to_cpu(ctxt.info.stat_counter_idx);
6338 
6339 	/* copy just the sections touched not the entire info
6340 	 * since not all sections are valid as returned by
6341 	 * update vsi params
6342 	 */
6343 	ch->info.mapping_flags = ctxt.info.mapping_flags;
6344 	memcpy(&ch->info.queue_mapping,
6345 	       &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
6346 	memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
6347 	       sizeof(ctxt.info.tc_mapping));
6348 
6349 	return 0;
6350 }
6351 
6352 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
6353 				  u8 *bw_share)
6354 {
6355 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
6356 	int ret;
6357 	int i;
6358 
6359 	memset(&bw_data, 0, sizeof(bw_data));
6360 	bw_data.tc_valid_bits = ch->enabled_tc;
6361 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6362 		bw_data.tc_bw_credits[i] = bw_share[i];
6363 
6364 	ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
6365 				       &bw_data, NULL);
6366 	if (ret) {
6367 		dev_info(&vsi->back->pdev->dev,
6368 			 "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
6369 			 vsi->back->hw.aq.asq_last_status, ch->seid);
6370 		return -EINVAL;
6371 	}
6372 
6373 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6374 		ch->info.qs_handle[i] = bw_data.qs_handles[i];
6375 
6376 	return 0;
6377 }
6378 
6379 /**
6380  * i40e_channel_config_tx_ring - config TX ring associated with new channel
6381  * @pf: ptr to PF device
6382  * @vsi: the VSI being setup
6383  * @ch: ptr to channel structure
6384  *
6385  * Configure TX rings associated with channel (VSI) since queues are being
6386  * from parent VSI.
6387  **/
6388 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
6389 				       struct i40e_vsi *vsi,
6390 				       struct i40e_channel *ch)
6391 {
6392 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
6393 	int ret;
6394 	int i;
6395 
6396 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
6397 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6398 		if (ch->enabled_tc & BIT(i))
6399 			bw_share[i] = 1;
6400 	}
6401 
6402 	/* configure BW for new VSI */
6403 	ret = i40e_channel_config_bw(vsi, ch, bw_share);
6404 	if (ret) {
6405 		dev_info(&vsi->back->pdev->dev,
6406 			 "Failed configuring TC map %d for channel (seid %u)\n",
6407 			 ch->enabled_tc, ch->seid);
6408 		return ret;
6409 	}
6410 
6411 	for (i = 0; i < ch->num_queue_pairs; i++) {
6412 		struct i40e_ring *tx_ring, *rx_ring;
6413 		u16 pf_q;
6414 
6415 		pf_q = ch->base_queue + i;
6416 
6417 		/* Get to TX ring ptr of main VSI, for re-setup TX queue
6418 		 * context
6419 		 */
6420 		tx_ring = vsi->tx_rings[pf_q];
6421 		tx_ring->ch = ch;
6422 
6423 		/* Get the RX ring ptr */
6424 		rx_ring = vsi->rx_rings[pf_q];
6425 		rx_ring->ch = ch;
6426 	}
6427 
6428 	return 0;
6429 }
6430 
6431 /**
6432  * i40e_setup_hw_channel - setup new channel
6433  * @pf: ptr to PF device
6434  * @vsi: the VSI being setup
6435  * @ch: ptr to channel structure
6436  * @uplink_seid: underlying HW switching element (VEB) ID
6437  * @type: type of channel to be created (VMDq2/VF)
6438  *
6439  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6440  * and configures TX rings accordingly
6441  **/
6442 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
6443 					struct i40e_vsi *vsi,
6444 					struct i40e_channel *ch,
6445 					u16 uplink_seid, u8 type)
6446 {
6447 	int ret;
6448 
6449 	ch->initialized = false;
6450 	ch->base_queue = vsi->next_base_queue;
6451 	ch->type = type;
6452 
6453 	/* Proceed with creation of channel (VMDq2) VSI */
6454 	ret = i40e_add_channel(pf, uplink_seid, ch);
6455 	if (ret) {
6456 		dev_info(&pf->pdev->dev,
6457 			 "failed to add_channel using uplink_seid %u\n",
6458 			 uplink_seid);
6459 		return ret;
6460 	}
6461 
6462 	/* Mark the successful creation of channel */
6463 	ch->initialized = true;
6464 
6465 	/* Reconfigure TX queues using QTX_CTL register */
6466 	ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6467 	if (ret) {
6468 		dev_info(&pf->pdev->dev,
6469 			 "failed to configure TX rings for channel %u\n",
6470 			 ch->seid);
6471 		return ret;
6472 	}
6473 
6474 	/* update 'next_base_queue' */
6475 	vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6476 	dev_dbg(&pf->pdev->dev,
6477 		"Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6478 		ch->seid, ch->vsi_number, ch->stat_counter_idx,
6479 		ch->num_queue_pairs,
6480 		vsi->next_base_queue);
6481 	return ret;
6482 }
6483 
6484 /**
6485  * i40e_setup_channel - setup new channel using uplink element
6486  * @pf: ptr to PF device
6487  * @vsi: pointer to the VSI to set up the channel within
6488  * @ch: ptr to channel structure
6489  *
6490  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6491  * and uplink switching element (uplink_seid)
6492  **/
6493 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6494 			       struct i40e_channel *ch)
6495 {
6496 	struct i40e_vsi *main_vsi;
6497 	u8 vsi_type;
6498 	u16 seid;
6499 	int ret;
6500 
6501 	if (vsi->type == I40E_VSI_MAIN) {
6502 		vsi_type = I40E_VSI_VMDQ2;
6503 	} else {
6504 		dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6505 			vsi->type);
6506 		return false;
6507 	}
6508 
6509 	/* underlying switching element */
6510 	main_vsi = i40e_pf_get_main_vsi(pf);
6511 	seid = main_vsi->uplink_seid;
6512 
6513 	/* create channel (VSI), configure TX rings */
6514 	ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6515 	if (ret) {
6516 		dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6517 		return false;
6518 	}
6519 
6520 	return ch->initialized ? true : false;
6521 }
6522 
6523 /**
6524  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6525  * @vsi: ptr to VSI which has PF backing
6526  *
6527  * Sets up switch mode correctly if it needs to be changed and perform
6528  * what are allowed modes.
6529  **/
6530 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6531 {
6532 	u8 mode;
6533 	struct i40e_pf *pf = vsi->back;
6534 	struct i40e_hw *hw = &pf->hw;
6535 	int ret;
6536 
6537 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6538 	if (ret)
6539 		return -EINVAL;
6540 
6541 	if (hw->dev_caps.switch_mode) {
6542 		/* if switch mode is set, support mode2 (non-tunneled for
6543 		 * cloud filter) for now
6544 		 */
6545 		u32 switch_mode = hw->dev_caps.switch_mode &
6546 				  I40E_SWITCH_MODE_MASK;
6547 		if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6548 			if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6549 				return 0;
6550 			dev_err(&pf->pdev->dev,
6551 				"Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6552 				hw->dev_caps.switch_mode);
6553 			return -EINVAL;
6554 		}
6555 	}
6556 
6557 	/* Set Bit 7 to be valid */
6558 	mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6559 
6560 	/* Set L4type for TCP support */
6561 	mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6562 
6563 	/* Set cloud filter mode */
6564 	mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6565 
6566 	/* Prep mode field for set_switch_config */
6567 	ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6568 					pf->last_sw_conf_valid_flags,
6569 					mode, NULL);
6570 	if (ret && hw->aq.asq_last_status != LIBIE_AQ_RC_ESRCH)
6571 		dev_err(&pf->pdev->dev,
6572 			"couldn't set switch config bits, err %pe aq_err %s\n",
6573 			ERR_PTR(ret), libie_aq_str(hw->aq.asq_last_status));
6574 
6575 	return ret;
6576 }
6577 
6578 /**
6579  * i40e_create_queue_channel - function to create channel
6580  * @vsi: VSI to be configured
6581  * @ch: ptr to channel (it contains channel specific params)
6582  *
6583  * This function creates channel (VSI) using num_queues specified by user,
6584  * reconfigs RSS if needed.
6585  **/
6586 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6587 			      struct i40e_channel *ch)
6588 {
6589 	struct i40e_pf *pf = vsi->back;
6590 	bool reconfig_rss;
6591 	int err;
6592 
6593 	if (!ch)
6594 		return -EINVAL;
6595 
6596 	if (!ch->num_queue_pairs) {
6597 		dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6598 			ch->num_queue_pairs);
6599 		return -EINVAL;
6600 	}
6601 
6602 	/* validate user requested num_queues for channel */
6603 	err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6604 				       &reconfig_rss);
6605 	if (err) {
6606 		dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6607 			 ch->num_queue_pairs);
6608 		return -EINVAL;
6609 	}
6610 
6611 	/* By default we are in VEPA mode, if this is the first VF/VMDq
6612 	 * VSI to be added switch to VEB mode.
6613 	 */
6614 
6615 	if (!test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
6616 		set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
6617 
6618 		if (vsi->type == I40E_VSI_MAIN) {
6619 			if (i40e_is_tc_mqprio_enabled(pf))
6620 				i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
6621 			else
6622 				i40e_do_reset_safe(pf, I40E_PF_RESET_FLAG);
6623 		}
6624 		/* now onwards for main VSI, number of queues will be value
6625 		 * of TC0's queue count
6626 		 */
6627 	}
6628 
6629 	/* By this time, vsi->cnt_q_avail shall be set to non-zero and
6630 	 * it should be more than num_queues
6631 	 */
6632 	if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6633 		dev_dbg(&pf->pdev->dev,
6634 			"Error: cnt_q_avail (%u) less than num_queues %d\n",
6635 			vsi->cnt_q_avail, ch->num_queue_pairs);
6636 		return -EINVAL;
6637 	}
6638 
6639 	/* reconfig_rss only if vsi type is MAIN_VSI */
6640 	if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6641 		err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6642 		if (err) {
6643 			dev_info(&pf->pdev->dev,
6644 				 "Error: unable to reconfig rss for num_queues (%u)\n",
6645 				 ch->num_queue_pairs);
6646 			return -EINVAL;
6647 		}
6648 	}
6649 
6650 	if (!i40e_setup_channel(pf, vsi, ch)) {
6651 		dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6652 		return -EINVAL;
6653 	}
6654 
6655 	dev_info(&pf->pdev->dev,
6656 		 "Setup channel (id:%u) utilizing num_queues %d\n",
6657 		 ch->seid, ch->num_queue_pairs);
6658 
6659 	/* configure VSI for BW limit */
6660 	if (ch->max_tx_rate) {
6661 		u64 credits = ch->max_tx_rate;
6662 
6663 		if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6664 			return -EINVAL;
6665 
6666 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
6667 		dev_dbg(&pf->pdev->dev,
6668 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6669 			ch->max_tx_rate,
6670 			credits,
6671 			ch->seid);
6672 	}
6673 
6674 	/* in case of VF, this will be main SRIOV VSI */
6675 	ch->parent_vsi = vsi;
6676 
6677 	/* and update main_vsi's count for queue_available to use */
6678 	vsi->cnt_q_avail -= ch->num_queue_pairs;
6679 
6680 	return 0;
6681 }
6682 
6683 /**
6684  * i40e_configure_queue_channels - Add queue channel for the given TCs
6685  * @vsi: VSI to be configured
6686  *
6687  * Configures queue channel mapping to the given TCs
6688  **/
6689 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6690 {
6691 	struct i40e_channel *ch;
6692 	u64 max_rate = 0;
6693 	int ret = 0, i;
6694 
6695 	/* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6696 	vsi->tc_seid_map[0] = vsi->seid;
6697 	for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6698 		if (vsi->tc_config.enabled_tc & BIT(i)) {
6699 			ch = kzalloc_obj(*ch);
6700 			if (!ch) {
6701 				ret = -ENOMEM;
6702 				goto err_free;
6703 			}
6704 
6705 			INIT_LIST_HEAD(&ch->list);
6706 			ch->num_queue_pairs =
6707 				vsi->tc_config.tc_info[i].qcount;
6708 			ch->base_queue =
6709 				vsi->tc_config.tc_info[i].qoffset;
6710 
6711 			/* Bandwidth limit through tc interface is in bytes/s,
6712 			 * change to Mbit/s
6713 			 */
6714 			max_rate = vsi->mqprio_qopt.max_rate[i];
6715 			do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6716 			ch->max_tx_rate = max_rate;
6717 
6718 			list_add_tail(&ch->list, &vsi->ch_list);
6719 
6720 			ret = i40e_create_queue_channel(vsi, ch);
6721 			if (ret) {
6722 				dev_err(&vsi->back->pdev->dev,
6723 					"Failed creating queue channel with TC%d: queues %d\n",
6724 					i, ch->num_queue_pairs);
6725 				goto err_free;
6726 			}
6727 			vsi->tc_seid_map[i] = ch->seid;
6728 		}
6729 	}
6730 
6731 	/* reset to reconfigure TX queue contexts */
6732 	i40e_do_reset(vsi->back, I40E_PF_RESET_FLAG, true);
6733 	return ret;
6734 
6735 err_free:
6736 	i40e_remove_queue_channels(vsi);
6737 	return ret;
6738 }
6739 
6740 /**
6741  * i40e_veb_config_tc - Configure TCs for given VEB
6742  * @veb: given VEB
6743  * @enabled_tc: TC bitmap
6744  *
6745  * Configures given TC bitmap for VEB (switching) element
6746  **/
6747 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6748 {
6749 	struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6750 	struct i40e_pf *pf = veb->pf;
6751 	int ret = 0;
6752 	int i;
6753 
6754 	/* No TCs or already enabled TCs just return */
6755 	if (!enabled_tc || veb->enabled_tc == enabled_tc)
6756 		return ret;
6757 
6758 	bw_data.tc_valid_bits = enabled_tc;
6759 	/* bw_data.absolute_credits is not set (relative) */
6760 
6761 	/* Enable ETS TCs with equal BW Share for now */
6762 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6763 		if (enabled_tc & BIT(i))
6764 			bw_data.tc_bw_share_credits[i] = 1;
6765 	}
6766 
6767 	ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6768 						   &bw_data, NULL);
6769 	if (ret) {
6770 		dev_info(&pf->pdev->dev,
6771 			 "VEB bw config failed, err %pe aq_err %s\n",
6772 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
6773 		goto out;
6774 	}
6775 
6776 	/* Update the BW information */
6777 	ret = i40e_veb_get_bw_info(veb);
6778 	if (ret) {
6779 		dev_info(&pf->pdev->dev,
6780 			 "Failed getting veb bw config, err %pe aq_err %s\n",
6781 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
6782 	}
6783 
6784 out:
6785 	return ret;
6786 }
6787 
6788 #ifdef CONFIG_I40E_DCB
6789 /**
6790  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6791  * @pf: PF struct
6792  *
6793  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6794  * the caller would've quiesce all the VSIs before calling
6795  * this function
6796  **/
6797 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6798 {
6799 	struct i40e_vsi *vsi;
6800 	struct i40e_veb *veb;
6801 	u8 tc_map = 0;
6802 	int ret;
6803 	int v;
6804 
6805 	/* Enable the TCs available on PF to all VEBs */
6806 	tc_map = i40e_pf_get_tc_map(pf);
6807 	if (tc_map == I40E_DEFAULT_TRAFFIC_CLASS)
6808 		return;
6809 
6810 	i40e_pf_for_each_veb(pf, v, veb) {
6811 		ret = i40e_veb_config_tc(veb, tc_map);
6812 		if (ret) {
6813 			dev_info(&pf->pdev->dev,
6814 				 "Failed configuring TC for VEB seid=%d\n",
6815 				 veb->seid);
6816 			/* Will try to configure as many components */
6817 		}
6818 	}
6819 
6820 	/* Update each VSI */
6821 	i40e_pf_for_each_vsi(pf, v, vsi) {
6822 		/* - Enable all TCs for the LAN VSI
6823 		 * - For all others keep them at TC0 for now
6824 		 */
6825 		if (vsi->type == I40E_VSI_MAIN)
6826 			tc_map = i40e_pf_get_tc_map(pf);
6827 		else
6828 			tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6829 
6830 		ret = i40e_vsi_config_tc(vsi, tc_map);
6831 		if (ret) {
6832 			dev_info(&pf->pdev->dev,
6833 				 "Failed configuring TC for VSI seid=%d\n",
6834 				 vsi->seid);
6835 			/* Will try to configure as many components */
6836 		} else {
6837 			/* Re-configure VSI vectors based on updated TC map */
6838 			i40e_vsi_map_rings_to_vectors(vsi);
6839 			if (vsi->netdev)
6840 				i40e_dcbnl_set_all(vsi);
6841 		}
6842 	}
6843 }
6844 
6845 /**
6846  * i40e_resume_port_tx - Resume port Tx
6847  * @pf: PF struct
6848  *
6849  * Resume a port's Tx and issue a PF reset in case of failure to
6850  * resume.
6851  **/
6852 static int i40e_resume_port_tx(struct i40e_pf *pf)
6853 {
6854 	struct i40e_hw *hw = &pf->hw;
6855 	int ret;
6856 
6857 	ret = i40e_aq_resume_port_tx(hw, NULL);
6858 	if (ret) {
6859 		dev_info(&pf->pdev->dev,
6860 			 "Resume Port Tx failed, err %pe aq_err %s\n",
6861 			  ERR_PTR(ret),
6862 			  libie_aq_str(pf->hw.aq.asq_last_status));
6863 		/* Schedule PF reset to recover */
6864 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6865 		i40e_service_event_schedule(pf);
6866 	}
6867 
6868 	return ret;
6869 }
6870 
6871 /**
6872  * i40e_suspend_port_tx - Suspend port Tx
6873  * @pf: PF struct
6874  *
6875  * Suspend a port's Tx and issue a PF reset in case of failure.
6876  **/
6877 static int i40e_suspend_port_tx(struct i40e_pf *pf)
6878 {
6879 	struct i40e_hw *hw = &pf->hw;
6880 	int ret;
6881 
6882 	ret = i40e_aq_suspend_port_tx(hw, pf->mac_seid, NULL);
6883 	if (ret) {
6884 		dev_info(&pf->pdev->dev,
6885 			 "Suspend Port Tx failed, err %pe aq_err %s\n",
6886 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
6887 		/* Schedule PF reset to recover */
6888 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6889 		i40e_service_event_schedule(pf);
6890 	}
6891 
6892 	return ret;
6893 }
6894 
6895 /**
6896  * i40e_hw_set_dcb_config - Program new DCBX settings into HW
6897  * @pf: PF being configured
6898  * @new_cfg: New DCBX configuration
6899  *
6900  * Program DCB settings into HW and reconfigure VEB/VSIs on
6901  * given PF. Uses "Set LLDP MIB" AQC to program the hardware.
6902  **/
6903 static int i40e_hw_set_dcb_config(struct i40e_pf *pf,
6904 				  struct i40e_dcbx_config *new_cfg)
6905 {
6906 	struct i40e_dcbx_config *old_cfg = &pf->hw.local_dcbx_config;
6907 	int ret;
6908 
6909 	/* Check if need reconfiguration */
6910 	if (!memcmp(&new_cfg, &old_cfg, sizeof(new_cfg))) {
6911 		dev_dbg(&pf->pdev->dev, "No Change in DCB Config required.\n");
6912 		return 0;
6913 	}
6914 
6915 	/* Config change disable all VSIs */
6916 	i40e_pf_quiesce_all_vsi(pf);
6917 
6918 	/* Copy the new config to the current config */
6919 	*old_cfg = *new_cfg;
6920 	old_cfg->etsrec = old_cfg->etscfg;
6921 	ret = i40e_set_dcb_config(&pf->hw);
6922 	if (ret) {
6923 		dev_info(&pf->pdev->dev,
6924 			 "Set DCB Config failed, err %pe aq_err %s\n",
6925 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
6926 		goto out;
6927 	}
6928 
6929 	/* Changes in configuration update VEB/VSI */
6930 	i40e_dcb_reconfigure(pf);
6931 out:
6932 	/* In case of reset do not try to resume anything */
6933 	if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
6934 		/* Re-start the VSIs if disabled */
6935 		ret = i40e_resume_port_tx(pf);
6936 		/* In case of error no point in resuming VSIs */
6937 		if (ret)
6938 			goto err;
6939 		i40e_pf_unquiesce_all_vsi(pf);
6940 	}
6941 err:
6942 	return ret;
6943 }
6944 
6945 /**
6946  * i40e_hw_dcb_config - Program new DCBX settings into HW
6947  * @pf: PF being configured
6948  * @new_cfg: New DCBX configuration
6949  *
6950  * Program DCB settings into HW and reconfigure VEB/VSIs on
6951  * given PF
6952  **/
6953 int i40e_hw_dcb_config(struct i40e_pf *pf, struct i40e_dcbx_config *new_cfg)
6954 {
6955 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6956 	u8 prio_type[I40E_MAX_TRAFFIC_CLASS] = {0};
6957 	u32 mfs_tc[I40E_MAX_TRAFFIC_CLASS];
6958 	struct i40e_dcbx_config *old_cfg;
6959 	u8 mode[I40E_MAX_TRAFFIC_CLASS];
6960 	struct i40e_rx_pb_config pb_cfg;
6961 	struct i40e_hw *hw = &pf->hw;
6962 	u8 num_ports = hw->num_ports;
6963 	bool need_reconfig;
6964 	int ret = -EINVAL;
6965 	u8 lltc_map = 0;
6966 	u8 tc_map = 0;
6967 	u8 new_numtc;
6968 	u8 i;
6969 
6970 	dev_dbg(&pf->pdev->dev, "Configuring DCB registers directly\n");
6971 	/* Un-pack information to Program ETS HW via shared API
6972 	 * numtc, tcmap
6973 	 * LLTC map
6974 	 * ETS/NON-ETS arbiter mode
6975 	 * max exponent (credit refills)
6976 	 * Total number of ports
6977 	 * PFC priority bit-map
6978 	 * Priority Table
6979 	 * BW % per TC
6980 	 * Arbiter mode between UPs sharing same TC
6981 	 * TSA table (ETS or non-ETS)
6982 	 * EEE enabled or not
6983 	 * MFS TC table
6984 	 */
6985 
6986 	new_numtc = i40e_dcb_get_num_tc(new_cfg);
6987 
6988 	memset(&ets_data, 0, sizeof(ets_data));
6989 	for (i = 0; i < new_numtc; i++) {
6990 		tc_map |= BIT(i);
6991 		switch (new_cfg->etscfg.tsatable[i]) {
6992 		case I40E_IEEE_TSA_ETS:
6993 			prio_type[i] = I40E_DCB_PRIO_TYPE_ETS;
6994 			ets_data.tc_bw_share_credits[i] =
6995 					new_cfg->etscfg.tcbwtable[i];
6996 			break;
6997 		case I40E_IEEE_TSA_STRICT:
6998 			prio_type[i] = I40E_DCB_PRIO_TYPE_STRICT;
6999 			lltc_map |= BIT(i);
7000 			ets_data.tc_bw_share_credits[i] =
7001 					I40E_DCB_STRICT_PRIO_CREDITS;
7002 			break;
7003 		default:
7004 			/* Invalid TSA type */
7005 			need_reconfig = false;
7006 			goto out;
7007 		}
7008 	}
7009 
7010 	old_cfg = &hw->local_dcbx_config;
7011 	/* Check if need reconfiguration */
7012 	need_reconfig = i40e_dcb_need_reconfig(pf, old_cfg, new_cfg);
7013 
7014 	/* If needed, enable/disable frame tagging, disable all VSIs
7015 	 * and suspend port tx
7016 	 */
7017 	if (need_reconfig) {
7018 		/* Enable DCB tagging only when more than one TC */
7019 		if (new_numtc > 1)
7020 			set_bit(I40E_FLAG_DCB_ENA, pf->flags);
7021 		else
7022 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7023 
7024 		set_bit(__I40E_PORT_SUSPENDED, pf->state);
7025 		/* Reconfiguration needed quiesce all VSIs */
7026 		i40e_pf_quiesce_all_vsi(pf);
7027 		ret = i40e_suspend_port_tx(pf);
7028 		if (ret)
7029 			goto err;
7030 	}
7031 
7032 	/* Configure Port ETS Tx Scheduler */
7033 	ets_data.tc_valid_bits = tc_map;
7034 	ets_data.tc_strict_priority_flags = lltc_map;
7035 	ret = i40e_aq_config_switch_comp_ets
7036 		(hw, pf->mac_seid, &ets_data,
7037 		 i40e_aqc_opc_modify_switching_comp_ets, NULL);
7038 	if (ret) {
7039 		dev_info(&pf->pdev->dev,
7040 			 "Modify Port ETS failed, err %pe aq_err %s\n",
7041 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
7042 		goto out;
7043 	}
7044 
7045 	/* Configure Rx ETS HW */
7046 	memset(&mode, I40E_DCB_ARB_MODE_ROUND_ROBIN, sizeof(mode));
7047 	i40e_dcb_hw_set_num_tc(hw, new_numtc);
7048 	i40e_dcb_hw_rx_fifo_config(hw, I40E_DCB_ARB_MODE_ROUND_ROBIN,
7049 				   I40E_DCB_ARB_MODE_STRICT_PRIORITY,
7050 				   I40E_DCB_DEFAULT_MAX_EXPONENT,
7051 				   lltc_map);
7052 	i40e_dcb_hw_rx_cmd_monitor_config(hw, new_numtc, num_ports);
7053 	i40e_dcb_hw_rx_ets_bw_config(hw, new_cfg->etscfg.tcbwtable, mode,
7054 				     prio_type);
7055 	i40e_dcb_hw_pfc_config(hw, new_cfg->pfc.pfcenable,
7056 			       new_cfg->etscfg.prioritytable);
7057 	i40e_dcb_hw_rx_up2tc_config(hw, new_cfg->etscfg.prioritytable);
7058 
7059 	/* Configure Rx Packet Buffers in HW */
7060 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7061 		struct i40e_vsi *main_vsi = i40e_pf_get_main_vsi(pf);
7062 
7063 		mfs_tc[i] = main_vsi->netdev->mtu;
7064 		mfs_tc[i] += I40E_PACKET_HDR_PAD;
7065 	}
7066 
7067 	i40e_dcb_hw_calculate_pool_sizes(hw, num_ports,
7068 					 false, new_cfg->pfc.pfcenable,
7069 					 mfs_tc, &pb_cfg);
7070 	i40e_dcb_hw_rx_pb_config(hw, &pf->pb_cfg, &pb_cfg);
7071 
7072 	/* Update the local Rx Packet buffer config */
7073 	pf->pb_cfg = pb_cfg;
7074 
7075 	/* Inform the FW about changes to DCB configuration */
7076 	ret = i40e_aq_dcb_updated(&pf->hw, NULL);
7077 	if (ret) {
7078 		dev_info(&pf->pdev->dev,
7079 			 "DCB Updated failed, err %pe aq_err %s\n",
7080 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
7081 		goto out;
7082 	}
7083 
7084 	/* Update the port DCBx configuration */
7085 	*old_cfg = *new_cfg;
7086 
7087 	/* Changes in configuration update VEB/VSI */
7088 	i40e_dcb_reconfigure(pf);
7089 out:
7090 	/* Re-start the VSIs if disabled */
7091 	if (need_reconfig) {
7092 		ret = i40e_resume_port_tx(pf);
7093 
7094 		clear_bit(__I40E_PORT_SUSPENDED, pf->state);
7095 		/* In case of error no point in resuming VSIs */
7096 		if (ret)
7097 			goto err;
7098 
7099 		/* Wait for the PF's queues to be disabled */
7100 		ret = i40e_pf_wait_queues_disabled(pf);
7101 		if (ret) {
7102 			/* Schedule PF reset to recover */
7103 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
7104 			i40e_service_event_schedule(pf);
7105 			goto err;
7106 		} else {
7107 			i40e_pf_unquiesce_all_vsi(pf);
7108 			set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7109 			set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
7110 		}
7111 		/* registers are set, lets apply */
7112 		if (test_bit(I40E_HW_CAP_USE_SET_LLDP_MIB, pf->hw.caps))
7113 			ret = i40e_hw_set_dcb_config(pf, new_cfg);
7114 	}
7115 
7116 err:
7117 	return ret;
7118 }
7119 
7120 /**
7121  * i40e_dcb_sw_default_config - Set default DCB configuration when DCB in SW
7122  * @pf: PF being queried
7123  *
7124  * Set default DCB configuration in case DCB is to be done in SW.
7125  **/
7126 int i40e_dcb_sw_default_config(struct i40e_pf *pf)
7127 {
7128 	struct i40e_dcbx_config *dcb_cfg = &pf->hw.local_dcbx_config;
7129 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
7130 	struct i40e_hw *hw = &pf->hw;
7131 	int err;
7132 
7133 	if (test_bit(I40E_HW_CAP_USE_SET_LLDP_MIB, pf->hw.caps)) {
7134 		/* Update the local cached instance with TC0 ETS */
7135 		memset(&pf->tmp_cfg, 0, sizeof(struct i40e_dcbx_config));
7136 		pf->tmp_cfg.etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7137 		pf->tmp_cfg.etscfg.maxtcs = 0;
7138 		pf->tmp_cfg.etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7139 		pf->tmp_cfg.etscfg.tsatable[0] = I40E_IEEE_TSA_ETS;
7140 		pf->tmp_cfg.pfc.willing = I40E_IEEE_DEFAULT_PFC_WILLING;
7141 		pf->tmp_cfg.pfc.pfccap = I40E_MAX_TRAFFIC_CLASS;
7142 		/* FW needs one App to configure HW */
7143 		pf->tmp_cfg.numapps = I40E_IEEE_DEFAULT_NUM_APPS;
7144 		pf->tmp_cfg.app[0].selector = I40E_APP_SEL_ETHTYPE;
7145 		pf->tmp_cfg.app[0].priority = I40E_IEEE_DEFAULT_APP_PRIO;
7146 		pf->tmp_cfg.app[0].protocolid = I40E_APP_PROTOID_FCOE;
7147 
7148 		return i40e_hw_set_dcb_config(pf, &pf->tmp_cfg);
7149 	}
7150 
7151 	memset(&ets_data, 0, sizeof(ets_data));
7152 	ets_data.tc_valid_bits = I40E_DEFAULT_TRAFFIC_CLASS; /* TC0 only */
7153 	ets_data.tc_strict_priority_flags = 0; /* ETS */
7154 	ets_data.tc_bw_share_credits[0] = I40E_IEEE_DEFAULT_ETS_TCBW; /* 100% to TC0 */
7155 
7156 	/* Enable ETS on the Physical port */
7157 	err = i40e_aq_config_switch_comp_ets
7158 		(hw, pf->mac_seid, &ets_data,
7159 		 i40e_aqc_opc_enable_switching_comp_ets, NULL);
7160 	if (err) {
7161 		dev_info(&pf->pdev->dev,
7162 			 "Enable Port ETS failed, err %pe aq_err %s\n",
7163 			 ERR_PTR(err), libie_aq_str(pf->hw.aq.asq_last_status));
7164 		err = -ENOENT;
7165 		goto out;
7166 	}
7167 
7168 	/* Update the local cached instance with TC0 ETS */
7169 	dcb_cfg->etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7170 	dcb_cfg->etscfg.cbs = 0;
7171 	dcb_cfg->etscfg.maxtcs = I40E_MAX_TRAFFIC_CLASS;
7172 	dcb_cfg->etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7173 
7174 out:
7175 	return err;
7176 }
7177 
7178 /**
7179  * i40e_init_pf_dcb - Initialize DCB configuration
7180  * @pf: PF being configured
7181  *
7182  * Query the current DCB configuration and cache it
7183  * in the hardware structure
7184  **/
7185 static int i40e_init_pf_dcb(struct i40e_pf *pf)
7186 {
7187 	struct i40e_hw *hw = &pf->hw;
7188 	int err;
7189 
7190 	/* Do not enable DCB for SW1 and SW2 images even if the FW is capable
7191 	 * Also do not enable DCBx if FW LLDP agent is disabled
7192 	 */
7193 	if (test_bit(I40E_HW_CAP_NO_DCB_SUPPORT, pf->hw.caps)) {
7194 		dev_info(&pf->pdev->dev, "DCB is not supported.\n");
7195 		err = -EOPNOTSUPP;
7196 		goto out;
7197 	}
7198 	if (test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags)) {
7199 		dev_info(&pf->pdev->dev, "FW LLDP is disabled, attempting SW DCB\n");
7200 		err = i40e_dcb_sw_default_config(pf);
7201 		if (err) {
7202 			dev_info(&pf->pdev->dev, "Could not initialize SW DCB\n");
7203 			goto out;
7204 		}
7205 		dev_info(&pf->pdev->dev, "SW DCB initialization succeeded.\n");
7206 		pf->dcbx_cap = DCB_CAP_DCBX_HOST |
7207 			       DCB_CAP_DCBX_VER_IEEE;
7208 		/* at init capable but disabled */
7209 		set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
7210 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7211 		goto out;
7212 	}
7213 	err = i40e_init_dcb(hw, true);
7214 	if (!err) {
7215 		/* Device/Function is not DCBX capable */
7216 		if ((!hw->func_caps.dcb) ||
7217 		    (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
7218 			dev_info(&pf->pdev->dev,
7219 				 "DCBX offload is not supported or is disabled for this PF.\n");
7220 		} else {
7221 			/* When status is not DISABLED then DCBX in FW */
7222 			pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
7223 				       DCB_CAP_DCBX_VER_IEEE;
7224 
7225 			set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
7226 			/* Enable DCB tagging only when more than one TC
7227 			 * or explicitly disable if only one TC
7228 			 */
7229 			if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
7230 				set_bit(I40E_FLAG_DCB_ENA, pf->flags);
7231 			else
7232 				clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7233 			dev_dbg(&pf->pdev->dev,
7234 				"DCBX offload is supported for this PF.\n");
7235 		}
7236 	} else if (pf->hw.aq.asq_last_status == LIBIE_AQ_RC_EPERM) {
7237 		dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
7238 		set_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags);
7239 	} else {
7240 		dev_info(&pf->pdev->dev,
7241 			 "Query for DCB configuration failed, err %pe aq_err %s\n",
7242 			 ERR_PTR(err), libie_aq_str(pf->hw.aq.asq_last_status));
7243 	}
7244 
7245 out:
7246 	return err;
7247 }
7248 #endif /* CONFIG_I40E_DCB */
7249 
7250 static void i40e_print_link_message_eee(struct i40e_vsi *vsi,
7251 					const char *speed, const char *fc)
7252 {
7253 	struct ethtool_keee kedata;
7254 
7255 	memzero_explicit(&kedata, sizeof(kedata));
7256 	if (vsi->netdev->ethtool_ops->get_eee)
7257 		vsi->netdev->ethtool_ops->get_eee(vsi->netdev, &kedata);
7258 
7259 	if (!linkmode_empty(kedata.supported))
7260 		netdev_info(vsi->netdev,
7261 			    "NIC Link is Up, %sbps Full Duplex, Flow Control: %s, EEE: %s\n",
7262 			    speed, fc,
7263 			    kedata.eee_enabled ? "Enabled" : "Disabled");
7264 	else
7265 		netdev_info(vsi->netdev,
7266 			    "NIC Link is Up, %sbps Full Duplex, Flow Control: %s\n",
7267 			    speed, fc);
7268 }
7269 
7270 /**
7271  * i40e_print_link_message - print link up or down
7272  * @vsi: the VSI for which link needs a message
7273  * @isup: true of link is up, false otherwise
7274  */
7275 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
7276 {
7277 	enum i40e_aq_link_speed new_speed;
7278 	struct i40e_pf *pf = vsi->back;
7279 	char *speed = "Unknown";
7280 	char *fc = "Unknown";
7281 	char *fec = "";
7282 	char *req_fec = "";
7283 	char *an = "";
7284 
7285 	if (isup)
7286 		new_speed = pf->hw.phy.link_info.link_speed;
7287 	else
7288 		new_speed = I40E_LINK_SPEED_UNKNOWN;
7289 
7290 	if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
7291 		return;
7292 	vsi->current_isup = isup;
7293 	vsi->current_speed = new_speed;
7294 	if (!isup) {
7295 		netdev_info(vsi->netdev, "NIC Link is Down\n");
7296 		return;
7297 	}
7298 
7299 	/* Warn user if link speed on NPAR enabled partition is not at
7300 	 * least 10GB
7301 	 */
7302 	if (pf->hw.func_caps.npar_enable &&
7303 	    (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
7304 	     pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
7305 		netdev_warn(vsi->netdev,
7306 			    "The partition detected link speed that is less than 10Gbps\n");
7307 
7308 	switch (pf->hw.phy.link_info.link_speed) {
7309 	case I40E_LINK_SPEED_40GB:
7310 		speed = "40 G";
7311 		break;
7312 	case I40E_LINK_SPEED_20GB:
7313 		speed = "20 G";
7314 		break;
7315 	case I40E_LINK_SPEED_25GB:
7316 		speed = "25 G";
7317 		break;
7318 	case I40E_LINK_SPEED_10GB:
7319 		speed = "10 G";
7320 		break;
7321 	case I40E_LINK_SPEED_5GB:
7322 		speed = "5 G";
7323 		break;
7324 	case I40E_LINK_SPEED_2_5GB:
7325 		speed = "2.5 G";
7326 		break;
7327 	case I40E_LINK_SPEED_1GB:
7328 		speed = "1000 M";
7329 		break;
7330 	case I40E_LINK_SPEED_100MB:
7331 		speed = "100 M";
7332 		break;
7333 	default:
7334 		break;
7335 	}
7336 
7337 	switch (pf->hw.fc.current_mode) {
7338 	case I40E_FC_FULL:
7339 		fc = "RX/TX";
7340 		break;
7341 	case I40E_FC_TX_PAUSE:
7342 		fc = "TX";
7343 		break;
7344 	case I40E_FC_RX_PAUSE:
7345 		fc = "RX";
7346 		break;
7347 	default:
7348 		fc = "None";
7349 		break;
7350 	}
7351 
7352 	if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
7353 		req_fec = "None";
7354 		fec = "None";
7355 		an = "False";
7356 
7357 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7358 			an = "True";
7359 
7360 		if (pf->hw.phy.link_info.fec_info &
7361 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7362 			fec = "CL74 FC-FEC/BASE-R";
7363 		else if (pf->hw.phy.link_info.fec_info &
7364 			 I40E_AQ_CONFIG_FEC_RS_ENA)
7365 			fec = "CL108 RS-FEC";
7366 
7367 		/* 'CL108 RS-FEC' should be displayed when RS is requested, or
7368 		 * both RS and FC are requested
7369 		 */
7370 		if (vsi->back->hw.phy.link_info.req_fec_info &
7371 		    (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
7372 			if (vsi->back->hw.phy.link_info.req_fec_info &
7373 			    I40E_AQ_REQUEST_FEC_RS)
7374 				req_fec = "CL108 RS-FEC";
7375 			else
7376 				req_fec = "CL74 FC-FEC/BASE-R";
7377 		}
7378 		netdev_info(vsi->netdev,
7379 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7380 			    speed, req_fec, fec, an, fc);
7381 	} else if (pf->hw.device_id == I40E_DEV_ID_KX_X722) {
7382 		req_fec = "None";
7383 		fec = "None";
7384 		an = "False";
7385 
7386 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7387 			an = "True";
7388 
7389 		if (pf->hw.phy.link_info.fec_info &
7390 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7391 			fec = "CL74 FC-FEC/BASE-R";
7392 
7393 		if (pf->hw.phy.link_info.req_fec_info &
7394 		    I40E_AQ_REQUEST_FEC_KR)
7395 			req_fec = "CL74 FC-FEC/BASE-R";
7396 
7397 		netdev_info(vsi->netdev,
7398 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7399 			    speed, req_fec, fec, an, fc);
7400 	} else {
7401 		i40e_print_link_message_eee(vsi, speed, fc);
7402 	}
7403 
7404 }
7405 
7406 /**
7407  * i40e_up_complete - Finish the last steps of bringing up a connection
7408  * @vsi: the VSI being configured
7409  **/
7410 static int i40e_up_complete(struct i40e_vsi *vsi)
7411 {
7412 	struct i40e_pf *pf = vsi->back;
7413 	int err;
7414 
7415 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
7416 		i40e_vsi_configure_msix(vsi);
7417 	else
7418 		i40e_configure_msi_and_legacy(vsi);
7419 
7420 	/* start rings */
7421 	err = i40e_vsi_start_rings(vsi);
7422 	if (err)
7423 		return err;
7424 
7425 	clear_bit(__I40E_VSI_DOWN, vsi->state);
7426 	i40e_napi_enable_all(vsi);
7427 	i40e_vsi_enable_irq(vsi);
7428 
7429 	if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
7430 	    (vsi->netdev)) {
7431 		i40e_print_link_message(vsi, true);
7432 		netif_tx_start_all_queues(vsi->netdev);
7433 		netif_carrier_on(vsi->netdev);
7434 	}
7435 
7436 	/* replay FDIR SB filters */
7437 	if (vsi->type == I40E_VSI_FDIR) {
7438 		/* reset fd counters */
7439 		pf->fd_add_err = 0;
7440 		pf->fd_atr_cnt = 0;
7441 		i40e_fdir_filter_restore(vsi);
7442 	}
7443 
7444 	/* On the next run of the service_task, notify any clients of the new
7445 	 * opened netdev
7446 	 */
7447 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7448 	i40e_service_event_schedule(pf);
7449 
7450 	return 0;
7451 }
7452 
7453 /**
7454  * i40e_vsi_reinit_locked - Reset the VSI
7455  * @vsi: the VSI being configured
7456  *
7457  * Rebuild the ring structs after some configuration
7458  * has changed, e.g. MTU size.
7459  **/
7460 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
7461 {
7462 	struct i40e_pf *pf = vsi->back;
7463 
7464 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
7465 		usleep_range(1000, 2000);
7466 	i40e_down(vsi);
7467 
7468 	i40e_up(vsi);
7469 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
7470 }
7471 
7472 /**
7473  * i40e_force_link_state - Force the link status
7474  * @pf: board private structure
7475  * @is_up: whether the link state should be forced up or down
7476  **/
7477 static int i40e_force_link_state(struct i40e_pf *pf, bool is_up)
7478 {
7479 	struct i40e_aq_get_phy_abilities_resp abilities;
7480 	struct i40e_aq_set_phy_config config = {0};
7481 	bool non_zero_phy_type = is_up;
7482 	struct i40e_hw *hw = &pf->hw;
7483 	u64 mask;
7484 	u8 speed;
7485 	int err;
7486 
7487 	/* Card might've been put in an unstable state by other drivers
7488 	 * and applications, which causes incorrect speed values being
7489 	 * set on startup. In order to clear speed registers, we call
7490 	 * get_phy_capabilities twice, once to get initial state of
7491 	 * available speeds, and once to get current PHY config.
7492 	 */
7493 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
7494 					   NULL);
7495 	if (err) {
7496 		dev_err(&pf->pdev->dev,
7497 			"failed to get phy cap., ret =  %pe last_status =  %s\n",
7498 			ERR_PTR(err), libie_aq_str(hw->aq.asq_last_status));
7499 		return err;
7500 	}
7501 	speed = abilities.link_speed;
7502 
7503 	/* Get the current phy config */
7504 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
7505 					   NULL);
7506 	if (err) {
7507 		dev_err(&pf->pdev->dev,
7508 			"failed to get phy cap., ret =  %pe last_status =  %s\n",
7509 			ERR_PTR(err), libie_aq_str(hw->aq.asq_last_status));
7510 		return err;
7511 	}
7512 
7513 	/* If link needs to go up, but was not forced to go down,
7514 	 * and its speed values are OK, no need for a flap
7515 	 * if non_zero_phy_type was set, still need to force up
7516 	 */
7517 	if (test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags))
7518 		non_zero_phy_type = true;
7519 	else if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
7520 		return 0;
7521 
7522 	/* To force link we need to set bits for all supported PHY types,
7523 	 * but there are now more than 32, so we need to split the bitmap
7524 	 * across two fields.
7525 	 */
7526 	mask = I40E_PHY_TYPES_BITMASK;
7527 	config.phy_type =
7528 		non_zero_phy_type ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
7529 	config.phy_type_ext =
7530 		non_zero_phy_type ? (u8)((mask >> 32) & 0xff) : 0;
7531 	/* Copy the old settings, except of phy_type */
7532 	config.abilities = abilities.abilities;
7533 	if (test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags)) {
7534 		if (is_up)
7535 			config.abilities |= I40E_AQ_PHY_ENABLE_LINK;
7536 		else
7537 			config.abilities &= ~(I40E_AQ_PHY_ENABLE_LINK);
7538 	}
7539 	if (abilities.link_speed != 0)
7540 		config.link_speed = abilities.link_speed;
7541 	else
7542 		config.link_speed = speed;
7543 	config.eee_capability = abilities.eee_capability;
7544 	config.eeer = abilities.eeer_val;
7545 	config.low_power_ctrl = abilities.d3_lpan;
7546 	config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
7547 			    I40E_AQ_PHY_FEC_CONFIG_MASK;
7548 	err = i40e_aq_set_phy_config(hw, &config, NULL);
7549 
7550 	if (err) {
7551 		dev_err(&pf->pdev->dev,
7552 			"set phy config ret =  %pe last_status =  %s\n",
7553 			ERR_PTR(err), libie_aq_str(pf->hw.aq.asq_last_status));
7554 		return err;
7555 	}
7556 
7557 	/* Update the link info */
7558 	err = i40e_update_link_info(hw);
7559 	if (err) {
7560 		/* Wait a little bit (on 40G cards it sometimes takes a really
7561 		 * long time for link to come back from the atomic reset)
7562 		 * and try once more
7563 		 */
7564 		msleep(1000);
7565 		i40e_update_link_info(hw);
7566 	}
7567 
7568 	i40e_aq_set_link_restart_an(hw, is_up, NULL);
7569 
7570 	return 0;
7571 }
7572 
7573 /**
7574  * i40e_up - Bring the connection back up after being down
7575  * @vsi: the VSI being configured
7576  **/
7577 int i40e_up(struct i40e_vsi *vsi)
7578 {
7579 	int err;
7580 
7581 	if (vsi->type == I40E_VSI_MAIN &&
7582 	    (test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags) ||
7583 	     test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, vsi->back->flags)))
7584 		i40e_force_link_state(vsi->back, true);
7585 
7586 	err = i40e_vsi_configure(vsi);
7587 	if (!err)
7588 		err = i40e_up_complete(vsi);
7589 
7590 	return err;
7591 }
7592 
7593 /**
7594  * i40e_down - Shutdown the connection processing
7595  * @vsi: the VSI being stopped
7596  **/
7597 void i40e_down(struct i40e_vsi *vsi)
7598 {
7599 	int i;
7600 
7601 	/* It is assumed that the caller of this function
7602 	 * sets the vsi->state __I40E_VSI_DOWN bit.
7603 	 */
7604 	if (vsi->netdev) {
7605 		netif_carrier_off(vsi->netdev);
7606 		netif_tx_disable(vsi->netdev);
7607 	}
7608 	i40e_vsi_disable_irq(vsi);
7609 	i40e_vsi_stop_rings(vsi);
7610 	if (vsi->type == I40E_VSI_MAIN &&
7611 	   (test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags) ||
7612 	    test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, vsi->back->flags)))
7613 		i40e_force_link_state(vsi->back, false);
7614 	i40e_napi_disable_all(vsi);
7615 
7616 	for (i = 0; i < vsi->num_queue_pairs; i++) {
7617 		i40e_clean_tx_ring(vsi->tx_rings[i]);
7618 		if (i40e_enabled_xdp_vsi(vsi)) {
7619 			/* Make sure that in-progress ndo_xdp_xmit and
7620 			 * ndo_xsk_wakeup calls are completed.
7621 			 */
7622 			synchronize_rcu();
7623 			i40e_clean_tx_ring(vsi->xdp_rings[i]);
7624 		}
7625 		i40e_clean_rx_ring(vsi->rx_rings[i]);
7626 	}
7627 
7628 }
7629 
7630 /**
7631  * i40e_validate_mqprio_qopt- validate queue mapping info
7632  * @vsi: the VSI being configured
7633  * @mqprio_qopt: queue parametrs
7634  **/
7635 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
7636 				     struct tc_mqprio_qopt_offload *mqprio_qopt)
7637 {
7638 	u64 sum_max_rate = 0;
7639 	u64 max_rate = 0;
7640 	int i;
7641 
7642 	if (mqprio_qopt->qopt.offset[0] != 0 ||
7643 	    mqprio_qopt->qopt.num_tc < 1 ||
7644 	    mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
7645 		return -EINVAL;
7646 	for (i = 0; ; i++) {
7647 		if (!mqprio_qopt->qopt.count[i])
7648 			return -EINVAL;
7649 		if (mqprio_qopt->min_rate[i]) {
7650 			dev_err(&vsi->back->pdev->dev,
7651 				"Invalid min tx rate (greater than 0) specified\n");
7652 			return -EINVAL;
7653 		}
7654 		max_rate = mqprio_qopt->max_rate[i];
7655 		do_div(max_rate, I40E_BW_MBPS_DIVISOR);
7656 		sum_max_rate += max_rate;
7657 
7658 		if (i >= mqprio_qopt->qopt.num_tc - 1)
7659 			break;
7660 		if (mqprio_qopt->qopt.offset[i + 1] !=
7661 		    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7662 			return -EINVAL;
7663 	}
7664 	if (vsi->num_queue_pairs <
7665 	    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
7666 		dev_err(&vsi->back->pdev->dev,
7667 			"Failed to create traffic channel, insufficient number of queues.\n");
7668 		return -EINVAL;
7669 	}
7670 	if (sum_max_rate > i40e_get_link_speed(vsi)) {
7671 		dev_err(&vsi->back->pdev->dev,
7672 			"Invalid max tx rate specified\n");
7673 		return -EINVAL;
7674 	}
7675 	return 0;
7676 }
7677 
7678 /**
7679  * i40e_vsi_set_default_tc_config - set default values for tc configuration
7680  * @vsi: the VSI being configured
7681  **/
7682 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
7683 {
7684 	u16 qcount;
7685 	int i;
7686 
7687 	/* Only TC0 is enabled */
7688 	vsi->tc_config.numtc = 1;
7689 	vsi->tc_config.enabled_tc = 1;
7690 	qcount = min_t(int, vsi->alloc_queue_pairs,
7691 		       i40e_pf_get_max_q_per_tc(vsi->back));
7692 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7693 		/* For the TC that is not enabled set the offset to default
7694 		 * queue and allocate one queue for the given TC.
7695 		 */
7696 		vsi->tc_config.tc_info[i].qoffset = 0;
7697 		if (i == 0)
7698 			vsi->tc_config.tc_info[i].qcount = qcount;
7699 		else
7700 			vsi->tc_config.tc_info[i].qcount = 1;
7701 		vsi->tc_config.tc_info[i].netdev_tc = 0;
7702 	}
7703 }
7704 
7705 /**
7706  * i40e_del_macvlan_filter
7707  * @hw: pointer to the HW structure
7708  * @seid: seid of the channel VSI
7709  * @macaddr: the mac address to apply as a filter
7710  * @aq_err: store the admin Q error
7711  *
7712  * This function deletes a mac filter on the channel VSI which serves as the
7713  * macvlan. Returns 0 on success.
7714  **/
7715 static int i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
7716 				   const u8 *macaddr, int *aq_err)
7717 {
7718 	struct i40e_aqc_remove_macvlan_element_data element;
7719 	int status;
7720 
7721 	memset(&element, 0, sizeof(element));
7722 	ether_addr_copy(element.mac_addr, macaddr);
7723 	element.vlan_tag = 0;
7724 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
7725 	status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
7726 	*aq_err = hw->aq.asq_last_status;
7727 
7728 	return status;
7729 }
7730 
7731 /**
7732  * i40e_add_macvlan_filter
7733  * @hw: pointer to the HW structure
7734  * @seid: seid of the channel VSI
7735  * @macaddr: the mac address to apply as a filter
7736  * @aq_err: store the admin Q error
7737  *
7738  * This function adds a mac filter on the channel VSI which serves as the
7739  * macvlan. Returns 0 on success.
7740  **/
7741 static int i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
7742 				   const u8 *macaddr, int *aq_err)
7743 {
7744 	struct i40e_aqc_add_macvlan_element_data element;
7745 	u16 cmd_flags = 0;
7746 	int status;
7747 
7748 	ether_addr_copy(element.mac_addr, macaddr);
7749 	element.vlan_tag = 0;
7750 	element.queue_number = 0;
7751 	element.match_method = I40E_AQC_MM_ERR_NO_RES;
7752 	cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
7753 	element.flags = cpu_to_le16(cmd_flags);
7754 	status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
7755 	*aq_err = hw->aq.asq_last_status;
7756 
7757 	return status;
7758 }
7759 
7760 /**
7761  * i40e_reset_ch_rings - Reset the queue contexts in a channel
7762  * @vsi: the VSI we want to access
7763  * @ch: the channel we want to access
7764  */
7765 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
7766 {
7767 	struct i40e_ring *tx_ring, *rx_ring;
7768 	u16 pf_q;
7769 	int i;
7770 
7771 	for (i = 0; i < ch->num_queue_pairs; i++) {
7772 		pf_q = ch->base_queue + i;
7773 		tx_ring = vsi->tx_rings[pf_q];
7774 		tx_ring->ch = NULL;
7775 		rx_ring = vsi->rx_rings[pf_q];
7776 		rx_ring->ch = NULL;
7777 	}
7778 }
7779 
7780 /**
7781  * i40e_free_macvlan_channels
7782  * @vsi: the VSI we want to access
7783  *
7784  * This function frees the Qs of the channel VSI from
7785  * the stack and also deletes the channel VSIs which
7786  * serve as macvlans.
7787  */
7788 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
7789 {
7790 	struct i40e_channel *ch, *ch_tmp;
7791 	int ret;
7792 
7793 	if (list_empty(&vsi->macvlan_list))
7794 		return;
7795 
7796 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7797 		struct i40e_vsi *parent_vsi;
7798 
7799 		if (i40e_is_channel_macvlan(ch)) {
7800 			i40e_reset_ch_rings(vsi, ch);
7801 			clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7802 			netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
7803 			netdev_set_sb_channel(ch->fwd->netdev, 0);
7804 			kfree(ch->fwd);
7805 			ch->fwd = NULL;
7806 		}
7807 
7808 		list_del(&ch->list);
7809 		parent_vsi = ch->parent_vsi;
7810 		if (!parent_vsi || !ch->initialized) {
7811 			kfree(ch);
7812 			continue;
7813 		}
7814 
7815 		/* remove the VSI */
7816 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
7817 					     NULL);
7818 		if (ret)
7819 			dev_err(&vsi->back->pdev->dev,
7820 				"unable to remove channel (%d) for parent VSI(%d)\n",
7821 				ch->seid, parent_vsi->seid);
7822 		kfree(ch);
7823 	}
7824 	vsi->macvlan_cnt = 0;
7825 }
7826 
7827 /**
7828  * i40e_fwd_ring_up - bring the macvlan device up
7829  * @vsi: the VSI we want to access
7830  * @vdev: macvlan netdevice
7831  * @fwd: the private fwd structure
7832  */
7833 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7834 			    struct i40e_fwd_adapter *fwd)
7835 {
7836 	struct i40e_channel *ch = NULL, *ch_tmp, *iter;
7837 	int ret = 0, num_tc = 1,  i, aq_err;
7838 	struct i40e_pf *pf = vsi->back;
7839 	struct i40e_hw *hw = &pf->hw;
7840 
7841 	/* Go through the list and find an available channel */
7842 	list_for_each_entry_safe(iter, ch_tmp, &vsi->macvlan_list, list) {
7843 		if (!i40e_is_channel_macvlan(iter)) {
7844 			iter->fwd = fwd;
7845 			/* record configuration for macvlan interface in vdev */
7846 			for (i = 0; i < num_tc; i++)
7847 				netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7848 							     i,
7849 							     iter->num_queue_pairs,
7850 							     iter->base_queue);
7851 			for (i = 0; i < iter->num_queue_pairs; i++) {
7852 				struct i40e_ring *tx_ring, *rx_ring;
7853 				u16 pf_q;
7854 
7855 				pf_q = iter->base_queue + i;
7856 
7857 				/* Get to TX ring ptr */
7858 				tx_ring = vsi->tx_rings[pf_q];
7859 				tx_ring->ch = iter;
7860 
7861 				/* Get the RX ring ptr */
7862 				rx_ring = vsi->rx_rings[pf_q];
7863 				rx_ring->ch = iter;
7864 			}
7865 			ch = iter;
7866 			break;
7867 		}
7868 	}
7869 
7870 	if (!ch)
7871 		return -EINVAL;
7872 
7873 	/* Guarantee all rings are updated before we update the
7874 	 * MAC address filter.
7875 	 */
7876 	wmb();
7877 
7878 	/* Add a mac filter */
7879 	ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7880 	if (ret) {
7881 		/* if we cannot add the MAC rule then disable the offload */
7882 		macvlan_release_l2fw_offload(vdev);
7883 		for (i = 0; i < ch->num_queue_pairs; i++) {
7884 			struct i40e_ring *rx_ring;
7885 			u16 pf_q;
7886 
7887 			pf_q = ch->base_queue + i;
7888 			rx_ring = vsi->rx_rings[pf_q];
7889 			rx_ring->netdev = NULL;
7890 		}
7891 		dev_info(&pf->pdev->dev,
7892 			 "Error adding mac filter on macvlan err %pe, aq_err %s\n",
7893 			  ERR_PTR(ret), libie_aq_str(aq_err));
7894 		netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7895 	}
7896 
7897 	return ret;
7898 }
7899 
7900 /**
7901  * i40e_setup_macvlans - create the channels which will be macvlans
7902  * @vsi: the VSI we want to access
7903  * @macvlan_cnt: no. of macvlans to be setup
7904  * @qcnt: no. of Qs per macvlan
7905  * @vdev: macvlan netdevice
7906  */
7907 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7908 			       struct net_device *vdev)
7909 {
7910 	struct i40e_pf *pf = vsi->back;
7911 	struct i40e_hw *hw = &pf->hw;
7912 	struct i40e_vsi_context ctxt;
7913 	u16 sections, qmap, num_qps;
7914 	struct i40e_channel *ch;
7915 	int i, pow, ret = 0;
7916 	u8 offset = 0;
7917 
7918 	if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7919 		return -EINVAL;
7920 
7921 	num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7922 
7923 	/* find the next higher power-of-2 of num queue pairs */
7924 	pow = fls(roundup_pow_of_two(num_qps) - 1);
7925 
7926 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7927 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7928 
7929 	/* Setup context bits for the main VSI */
7930 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7931 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7932 	memset(&ctxt, 0, sizeof(ctxt));
7933 	ctxt.seid = vsi->seid;
7934 	ctxt.pf_num = vsi->back->hw.pf_id;
7935 	ctxt.vf_num = 0;
7936 	ctxt.uplink_seid = vsi->uplink_seid;
7937 	ctxt.info = vsi->info;
7938 	ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7939 	ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7940 	ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7941 	ctxt.info.valid_sections |= cpu_to_le16(sections);
7942 
7943 	/* Reconfigure RSS for main VSI with new max queue count */
7944 	vsi->rss_size = max_t(u16, num_qps, qcnt);
7945 	ret = i40e_vsi_config_rss(vsi);
7946 	if (ret) {
7947 		dev_info(&pf->pdev->dev,
7948 			 "Failed to reconfig RSS for num_queues (%u)\n",
7949 			 vsi->rss_size);
7950 		return ret;
7951 	}
7952 	vsi->reconfig_rss = true;
7953 	dev_dbg(&vsi->back->pdev->dev,
7954 		"Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7955 	vsi->next_base_queue = num_qps;
7956 	vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7957 
7958 	/* Update the VSI after updating the VSI queue-mapping
7959 	 * information
7960 	 */
7961 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7962 	if (ret) {
7963 		dev_info(&pf->pdev->dev,
7964 			 "Update vsi tc config failed, err %pe aq_err %s\n",
7965 			 ERR_PTR(ret), libie_aq_str(hw->aq.asq_last_status));
7966 		return ret;
7967 	}
7968 	/* update the local VSI info with updated queue map */
7969 	i40e_vsi_update_queue_map(vsi, &ctxt);
7970 	vsi->info.valid_sections = 0;
7971 
7972 	/* Create channels for macvlans */
7973 	INIT_LIST_HEAD(&vsi->macvlan_list);
7974 	for (i = 0; i < macvlan_cnt; i++) {
7975 		ch = kzalloc_obj(*ch);
7976 		if (!ch) {
7977 			ret = -ENOMEM;
7978 			goto err_free;
7979 		}
7980 		INIT_LIST_HEAD(&ch->list);
7981 		ch->num_queue_pairs = qcnt;
7982 		if (!i40e_setup_channel(pf, vsi, ch)) {
7983 			ret = -EINVAL;
7984 			kfree(ch);
7985 			goto err_free;
7986 		}
7987 		ch->parent_vsi = vsi;
7988 		vsi->cnt_q_avail -= ch->num_queue_pairs;
7989 		vsi->macvlan_cnt++;
7990 		list_add_tail(&ch->list, &vsi->macvlan_list);
7991 	}
7992 
7993 	return ret;
7994 
7995 err_free:
7996 	dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
7997 	i40e_free_macvlan_channels(vsi);
7998 
7999 	return ret;
8000 }
8001 
8002 /**
8003  * i40e_fwd_add - configure macvlans
8004  * @netdev: net device to configure
8005  * @vdev: macvlan netdevice
8006  **/
8007 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
8008 {
8009 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8010 	u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
8011 	struct i40e_vsi *vsi = np->vsi;
8012 	struct i40e_pf *pf = vsi->back;
8013 	struct i40e_fwd_adapter *fwd;
8014 	int avail_macvlan, ret;
8015 
8016 	if (test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8017 		netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
8018 		return ERR_PTR(-EINVAL);
8019 	}
8020 	if (i40e_is_tc_mqprio_enabled(pf)) {
8021 		netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
8022 		return ERR_PTR(-EINVAL);
8023 	}
8024 	if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
8025 		netdev_info(netdev, "Not enough vectors available to support macvlans\n");
8026 		return ERR_PTR(-EINVAL);
8027 	}
8028 
8029 	/* The macvlan device has to be a single Q device so that the
8030 	 * tc_to_txq field can be reused to pick the tx queue.
8031 	 */
8032 	if (netif_is_multiqueue(vdev))
8033 		return ERR_PTR(-ERANGE);
8034 
8035 	if (!vsi->macvlan_cnt) {
8036 		/* reserve bit 0 for the pf device */
8037 		set_bit(0, vsi->fwd_bitmask);
8038 
8039 		/* Try to reserve as many queues as possible for macvlans. First
8040 		 * reserve 3/4th of max vectors, then half, then quarter and
8041 		 * calculate Qs per macvlan as you go
8042 		 */
8043 		vectors = pf->num_lan_msix;
8044 		if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
8045 			/* allocate 4 Qs per macvlan and 32 Qs to the PF*/
8046 			q_per_macvlan = 4;
8047 			macvlan_cnt = (vectors - 32) / 4;
8048 		} else if (vectors <= 64 && vectors > 32) {
8049 			/* allocate 2 Qs per macvlan and 16 Qs to the PF*/
8050 			q_per_macvlan = 2;
8051 			macvlan_cnt = (vectors - 16) / 2;
8052 		} else if (vectors <= 32 && vectors > 16) {
8053 			/* allocate 1 Q per macvlan and 16 Qs to the PF*/
8054 			q_per_macvlan = 1;
8055 			macvlan_cnt = vectors - 16;
8056 		} else if (vectors <= 16 && vectors > 8) {
8057 			/* allocate 1 Q per macvlan and 8 Qs to the PF */
8058 			q_per_macvlan = 1;
8059 			macvlan_cnt = vectors - 8;
8060 		} else {
8061 			/* allocate 1 Q per macvlan and 1 Q to the PF */
8062 			q_per_macvlan = 1;
8063 			macvlan_cnt = vectors - 1;
8064 		}
8065 
8066 		if (macvlan_cnt == 0)
8067 			return ERR_PTR(-EBUSY);
8068 
8069 		/* Quiesce VSI queues */
8070 		i40e_quiesce_vsi(vsi);
8071 
8072 		/* sets up the macvlans but does not "enable" them */
8073 		ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
8074 					  vdev);
8075 		if (ret)
8076 			return ERR_PTR(ret);
8077 
8078 		/* Unquiesce VSI */
8079 		i40e_unquiesce_vsi(vsi);
8080 	}
8081 	avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
8082 					    vsi->macvlan_cnt);
8083 	if (avail_macvlan >= I40E_MAX_MACVLANS)
8084 		return ERR_PTR(-EBUSY);
8085 
8086 	/* create the fwd struct */
8087 	fwd = kzalloc_obj(*fwd);
8088 	if (!fwd)
8089 		return ERR_PTR(-ENOMEM);
8090 
8091 	set_bit(avail_macvlan, vsi->fwd_bitmask);
8092 	fwd->bit_no = avail_macvlan;
8093 	netdev_set_sb_channel(vdev, avail_macvlan);
8094 	fwd->netdev = vdev;
8095 
8096 	if (!netif_running(netdev))
8097 		return fwd;
8098 
8099 	/* Set fwd ring up */
8100 	ret = i40e_fwd_ring_up(vsi, vdev, fwd);
8101 	if (ret) {
8102 		/* unbind the queues and drop the subordinate channel config */
8103 		netdev_unbind_sb_channel(netdev, vdev);
8104 		netdev_set_sb_channel(vdev, 0);
8105 
8106 		kfree(fwd);
8107 		return ERR_PTR(-EINVAL);
8108 	}
8109 
8110 	return fwd;
8111 }
8112 
8113 /**
8114  * i40e_del_all_macvlans - Delete all the mac filters on the channels
8115  * @vsi: the VSI we want to access
8116  */
8117 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
8118 {
8119 	struct i40e_channel *ch, *ch_tmp;
8120 	struct i40e_pf *pf = vsi->back;
8121 	struct i40e_hw *hw = &pf->hw;
8122 	int aq_err, ret = 0;
8123 
8124 	if (list_empty(&vsi->macvlan_list))
8125 		return;
8126 
8127 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8128 		if (i40e_is_channel_macvlan(ch)) {
8129 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8130 						      i40e_channel_mac(ch),
8131 						      &aq_err);
8132 			if (!ret) {
8133 				/* Reset queue contexts */
8134 				i40e_reset_ch_rings(vsi, ch);
8135 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8136 				netdev_unbind_sb_channel(vsi->netdev,
8137 							 ch->fwd->netdev);
8138 				netdev_set_sb_channel(ch->fwd->netdev, 0);
8139 				kfree(ch->fwd);
8140 				ch->fwd = NULL;
8141 			}
8142 		}
8143 	}
8144 }
8145 
8146 /**
8147  * i40e_fwd_del - delete macvlan interfaces
8148  * @netdev: net device to configure
8149  * @vdev: macvlan netdevice
8150  */
8151 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
8152 {
8153 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8154 	struct i40e_fwd_adapter *fwd = vdev;
8155 	struct i40e_channel *ch, *ch_tmp;
8156 	struct i40e_vsi *vsi = np->vsi;
8157 	struct i40e_pf *pf = vsi->back;
8158 	struct i40e_hw *hw = &pf->hw;
8159 	int aq_err, ret = 0;
8160 
8161 	/* Find the channel associated with the macvlan and del mac filter */
8162 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8163 		if (i40e_is_channel_macvlan(ch) &&
8164 		    ether_addr_equal(i40e_channel_mac(ch),
8165 				     fwd->netdev->dev_addr)) {
8166 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8167 						      i40e_channel_mac(ch),
8168 						      &aq_err);
8169 			if (!ret) {
8170 				/* Reset queue contexts */
8171 				i40e_reset_ch_rings(vsi, ch);
8172 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8173 				netdev_unbind_sb_channel(netdev, fwd->netdev);
8174 				netdev_set_sb_channel(fwd->netdev, 0);
8175 				kfree(ch->fwd);
8176 				ch->fwd = NULL;
8177 			} else {
8178 				dev_info(&pf->pdev->dev,
8179 					 "Error deleting mac filter on macvlan err %pe, aq_err %s\n",
8180 					  ERR_PTR(ret), libie_aq_str(aq_err));
8181 			}
8182 			break;
8183 		}
8184 	}
8185 }
8186 
8187 /**
8188  * i40e_setup_tc - configure multiple traffic classes
8189  * @netdev: net device to configure
8190  * @type_data: tc offload data
8191  **/
8192 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
8193 {
8194 	struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
8195 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8196 	struct i40e_vsi *vsi = np->vsi;
8197 	struct i40e_pf *pf = vsi->back;
8198 	u8 enabled_tc = 0, num_tc, hw;
8199 	bool need_reset = false;
8200 	int old_queue_pairs;
8201 	int ret = -EINVAL;
8202 	u16 mode;
8203 	int i;
8204 
8205 	old_queue_pairs = vsi->num_queue_pairs;
8206 	num_tc = mqprio_qopt->qopt.num_tc;
8207 	hw = mqprio_qopt->qopt.hw;
8208 	mode = mqprio_qopt->mode;
8209 	if (!hw) {
8210 		clear_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8211 		memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8212 		goto config_tc;
8213 	}
8214 
8215 	/* Check if MFP enabled */
8216 	if (test_bit(I40E_FLAG_MFP_ENA, pf->flags)) {
8217 		netdev_info(netdev,
8218 			    "Configuring TC not supported in MFP mode\n");
8219 		return ret;
8220 	}
8221 	switch (mode) {
8222 	case TC_MQPRIO_MODE_DCB:
8223 		clear_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8224 
8225 		/* Check if DCB enabled to continue */
8226 		if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8227 			netdev_info(netdev,
8228 				    "DCB is not enabled for adapter\n");
8229 			return ret;
8230 		}
8231 
8232 		/* Check whether tc count is within enabled limit */
8233 		if (num_tc > i40e_pf_get_num_tc(pf)) {
8234 			netdev_info(netdev,
8235 				    "TC count greater than enabled on link for adapter\n");
8236 			return ret;
8237 		}
8238 		break;
8239 	case TC_MQPRIO_MODE_CHANNEL:
8240 		if (test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8241 			netdev_info(netdev,
8242 				    "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
8243 			return ret;
8244 		}
8245 		if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
8246 			return ret;
8247 		ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
8248 		if (ret)
8249 			return ret;
8250 		memcpy(&vsi->mqprio_qopt, mqprio_qopt,
8251 		       sizeof(*mqprio_qopt));
8252 		set_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8253 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
8254 		break;
8255 	default:
8256 		return -EINVAL;
8257 	}
8258 
8259 config_tc:
8260 	/* Generate TC map for number of tc requested */
8261 	for (i = 0; i < num_tc; i++)
8262 		enabled_tc |= BIT(i);
8263 
8264 	/* Requesting same TC configuration as already enabled */
8265 	if (enabled_tc == vsi->tc_config.enabled_tc &&
8266 	    mode != TC_MQPRIO_MODE_CHANNEL)
8267 		return 0;
8268 
8269 	/* Quiesce VSI queues */
8270 	i40e_quiesce_vsi(vsi);
8271 
8272 	if (!hw && !i40e_is_tc_mqprio_enabled(pf))
8273 		i40e_remove_queue_channels(vsi);
8274 
8275 	/* Configure VSI for enabled TCs */
8276 	ret = i40e_vsi_config_tc(vsi, enabled_tc);
8277 	if (ret) {
8278 		netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
8279 			    vsi->seid);
8280 		need_reset = true;
8281 		goto exit;
8282 	} else if (enabled_tc &&
8283 		   (!is_power_of_2(vsi->tc_config.tc_info[0].qcount))) {
8284 		netdev_info(netdev,
8285 			    "Failed to create channel. Override queues (%u) not power of 2\n",
8286 			    vsi->tc_config.tc_info[0].qcount);
8287 		ret = -EINVAL;
8288 		need_reset = true;
8289 		goto exit;
8290 	}
8291 
8292 	dev_info(&vsi->back->pdev->dev,
8293 		 "Setup channel (id:%u) utilizing num_queues %d\n",
8294 		 vsi->seid, vsi->tc_config.tc_info[0].qcount);
8295 
8296 	if (i40e_is_tc_mqprio_enabled(pf)) {
8297 		if (vsi->mqprio_qopt.max_rate[0]) {
8298 			u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
8299 						  vsi->mqprio_qopt.max_rate[0]);
8300 
8301 			ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
8302 			if (!ret) {
8303 				u64 credits = max_tx_rate;
8304 
8305 				do_div(credits, I40E_BW_CREDIT_DIVISOR);
8306 				dev_dbg(&vsi->back->pdev->dev,
8307 					"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
8308 					max_tx_rate,
8309 					credits,
8310 					vsi->seid);
8311 			} else {
8312 				need_reset = true;
8313 				goto exit;
8314 			}
8315 		}
8316 		ret = i40e_configure_queue_channels(vsi);
8317 		if (ret) {
8318 			vsi->num_queue_pairs = old_queue_pairs;
8319 			netdev_info(netdev,
8320 				    "Failed configuring queue channels\n");
8321 			need_reset = true;
8322 			goto exit;
8323 		}
8324 	}
8325 
8326 exit:
8327 	/* Reset the configuration data to defaults, only TC0 is enabled */
8328 	if (need_reset) {
8329 		i40e_vsi_set_default_tc_config(vsi);
8330 		need_reset = false;
8331 	}
8332 
8333 	/* Unquiesce VSI */
8334 	i40e_unquiesce_vsi(vsi);
8335 	return ret;
8336 }
8337 
8338 /**
8339  * i40e_set_cld_element - sets cloud filter element data
8340  * @filter: cloud filter rule
8341  * @cld: ptr to cloud filter element data
8342  *
8343  * This is helper function to copy data into cloud filter element
8344  **/
8345 static inline void
8346 i40e_set_cld_element(struct i40e_cloud_filter *filter,
8347 		     struct i40e_aqc_cloud_filters_element_data *cld)
8348 {
8349 	u32 ipa;
8350 	int i;
8351 
8352 	memset(cld, 0, sizeof(*cld));
8353 	ether_addr_copy(cld->outer_mac, filter->dst_mac);
8354 	ether_addr_copy(cld->inner_mac, filter->src_mac);
8355 
8356 	if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
8357 		return;
8358 
8359 	if (filter->n_proto == ETH_P_IPV6) {
8360 #define IPV6_MAX_INDEX	(ARRAY_SIZE(filter->dst_ipv6) - 1)
8361 		for (i = 0; i < ARRAY_SIZE(filter->dst_ipv6); i++) {
8362 			ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
8363 
8364 			*(__le32 *)&cld->ipaddr.raw_v6.data[i * 2] = cpu_to_le32(ipa);
8365 		}
8366 	} else {
8367 		ipa = be32_to_cpu(filter->dst_ipv4);
8368 
8369 		memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
8370 	}
8371 
8372 	cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
8373 
8374 	/* tenant_id is not supported by FW now, once the support is enabled
8375 	 * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
8376 	 */
8377 	if (filter->tenant_id)
8378 		return;
8379 }
8380 
8381 /**
8382  * i40e_add_del_cloud_filter - Add/del cloud filter
8383  * @vsi: pointer to VSI
8384  * @filter: cloud filter rule
8385  * @add: if true, add, if false, delete
8386  *
8387  * Add or delete a cloud filter for a specific flow spec.
8388  * Returns 0 if the filter were successfully added.
8389  **/
8390 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
8391 			      struct i40e_cloud_filter *filter, bool add)
8392 {
8393 	struct i40e_aqc_cloud_filters_element_data cld_filter;
8394 	struct i40e_pf *pf = vsi->back;
8395 	int ret;
8396 	static const u16 flag_table[128] = {
8397 		[I40E_CLOUD_FILTER_FLAGS_OMAC]  =
8398 			I40E_AQC_ADD_CLOUD_FILTER_OMAC,
8399 		[I40E_CLOUD_FILTER_FLAGS_IMAC]  =
8400 			I40E_AQC_ADD_CLOUD_FILTER_IMAC,
8401 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
8402 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
8403 		[I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
8404 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
8405 		[I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
8406 			I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
8407 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
8408 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
8409 		[I40E_CLOUD_FILTER_FLAGS_IIP] =
8410 			I40E_AQC_ADD_CLOUD_FILTER_IIP,
8411 	};
8412 
8413 	if (filter->flags >= ARRAY_SIZE(flag_table))
8414 		return -EIO;
8415 
8416 	memset(&cld_filter, 0, sizeof(cld_filter));
8417 
8418 	/* copy element needed to add cloud filter from filter */
8419 	i40e_set_cld_element(filter, &cld_filter);
8420 
8421 	if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
8422 		cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
8423 					     I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
8424 
8425 	if (filter->n_proto == ETH_P_IPV6)
8426 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8427 						I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8428 	else
8429 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8430 						I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8431 
8432 	if (add)
8433 		ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
8434 						&cld_filter, 1);
8435 	else
8436 		ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
8437 						&cld_filter, 1);
8438 	if (ret)
8439 		dev_dbg(&pf->pdev->dev,
8440 			"Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
8441 			add ? "add" : "delete", filter->dst_port, ret,
8442 			pf->hw.aq.asq_last_status);
8443 	else
8444 		dev_info(&pf->pdev->dev,
8445 			 "%s cloud filter for VSI: %d\n",
8446 			 add ? "Added" : "Deleted", filter->seid);
8447 	return ret;
8448 }
8449 
8450 /**
8451  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
8452  * @vsi: pointer to VSI
8453  * @filter: cloud filter rule
8454  * @add: if true, add, if false, delete
8455  *
8456  * Add or delete a cloud filter for a specific flow spec using big buffer.
8457  * Returns 0 if the filter were successfully added.
8458  **/
8459 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
8460 				      struct i40e_cloud_filter *filter,
8461 				      bool add)
8462 {
8463 	struct i40e_aqc_cloud_filters_element_bb cld_filter;
8464 	struct i40e_pf *pf = vsi->back;
8465 	int ret;
8466 
8467 	/* Both (src/dst) valid mac_addr are not supported */
8468 	if ((is_valid_ether_addr(filter->dst_mac) &&
8469 	     is_valid_ether_addr(filter->src_mac)) ||
8470 	    (is_multicast_ether_addr(filter->dst_mac) &&
8471 	     is_multicast_ether_addr(filter->src_mac)))
8472 		return -EOPNOTSUPP;
8473 
8474 	/* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
8475 	 * ports are not supported via big buffer now.
8476 	 */
8477 	if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
8478 		return -EOPNOTSUPP;
8479 
8480 	/* adding filter using src_port/src_ip is not supported at this stage */
8481 	if (filter->src_port ||
8482 	    (filter->src_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8483 	    !ipv6_addr_any(&filter->ip.v6.src_ip6))
8484 		return -EOPNOTSUPP;
8485 
8486 	memset(&cld_filter, 0, sizeof(cld_filter));
8487 
8488 	/* copy element needed to add cloud filter from filter */
8489 	i40e_set_cld_element(filter, &cld_filter.element);
8490 
8491 	if (is_valid_ether_addr(filter->dst_mac) ||
8492 	    is_valid_ether_addr(filter->src_mac) ||
8493 	    is_multicast_ether_addr(filter->dst_mac) ||
8494 	    is_multicast_ether_addr(filter->src_mac)) {
8495 		/* MAC + IP : unsupported mode */
8496 		if (filter->dst_ipv4)
8497 			return -EOPNOTSUPP;
8498 
8499 		/* since we validated that L4 port must be valid before
8500 		 * we get here, start with respective "flags" value
8501 		 * and update if vlan is present or not
8502 		 */
8503 		cld_filter.element.flags =
8504 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
8505 
8506 		if (filter->vlan_id) {
8507 			cld_filter.element.flags =
8508 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
8509 		}
8510 
8511 	} else if ((filter->dst_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8512 		   !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
8513 		cld_filter.element.flags =
8514 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
8515 		if (filter->n_proto == ETH_P_IPV6)
8516 			cld_filter.element.flags |=
8517 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8518 		else
8519 			cld_filter.element.flags |=
8520 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8521 	} else {
8522 		dev_err(&pf->pdev->dev,
8523 			"either mac or ip has to be valid for cloud filter\n");
8524 		return -EINVAL;
8525 	}
8526 
8527 	/* Now copy L4 port in Byte 6..7 in general fields */
8528 	cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
8529 						be16_to_cpu(filter->dst_port);
8530 
8531 	if (add) {
8532 		/* Validate current device switch mode, change if necessary */
8533 		ret = i40e_validate_and_set_switch_mode(vsi);
8534 		if (ret) {
8535 			dev_err(&pf->pdev->dev,
8536 				"failed to set switch mode, ret %d\n",
8537 				ret);
8538 			return ret;
8539 		}
8540 
8541 		ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
8542 						   &cld_filter, 1);
8543 	} else {
8544 		ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
8545 						   &cld_filter, 1);
8546 	}
8547 
8548 	if (ret)
8549 		dev_dbg(&pf->pdev->dev,
8550 			"Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
8551 			add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
8552 	else
8553 		dev_info(&pf->pdev->dev,
8554 			 "%s cloud filter for VSI: %d, L4 port: %d\n",
8555 			 add ? "add" : "delete", filter->seid,
8556 			 ntohs(filter->dst_port));
8557 	return ret;
8558 }
8559 
8560 /**
8561  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
8562  * @vsi: Pointer to VSI
8563  * @f: Pointer to struct flow_cls_offload
8564  * @filter: Pointer to cloud filter structure
8565  *
8566  **/
8567 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
8568 				 struct flow_cls_offload *f,
8569 				 struct i40e_cloud_filter *filter)
8570 {
8571 	struct flow_rule *rule = flow_cls_offload_flow_rule(f);
8572 	struct flow_dissector *dissector = rule->match.dissector;
8573 	u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
8574 	struct i40e_pf *pf = vsi->back;
8575 	u8 field_flags = 0;
8576 
8577 	if (dissector->used_keys &
8578 	    ~(BIT_ULL(FLOW_DISSECTOR_KEY_CONTROL) |
8579 	      BIT_ULL(FLOW_DISSECTOR_KEY_BASIC) |
8580 	      BIT_ULL(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
8581 	      BIT_ULL(FLOW_DISSECTOR_KEY_VLAN) |
8582 	      BIT_ULL(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
8583 	      BIT_ULL(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
8584 	      BIT_ULL(FLOW_DISSECTOR_KEY_PORTS) |
8585 	      BIT_ULL(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
8586 		dev_err(&pf->pdev->dev, "Unsupported key used: 0x%llx\n",
8587 			dissector->used_keys);
8588 		return -EOPNOTSUPP;
8589 	}
8590 
8591 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
8592 		struct flow_match_enc_keyid match;
8593 
8594 		flow_rule_match_enc_keyid(rule, &match);
8595 		if (match.mask->keyid != 0)
8596 			field_flags |= I40E_CLOUD_FIELD_TEN_ID;
8597 
8598 		filter->tenant_id = be32_to_cpu(match.key->keyid);
8599 	}
8600 
8601 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
8602 		struct flow_match_basic match;
8603 
8604 		flow_rule_match_basic(rule, &match);
8605 		n_proto_key = ntohs(match.key->n_proto);
8606 		n_proto_mask = ntohs(match.mask->n_proto);
8607 
8608 		if (n_proto_key == ETH_P_ALL) {
8609 			n_proto_key = 0;
8610 			n_proto_mask = 0;
8611 		}
8612 		filter->n_proto = n_proto_key & n_proto_mask;
8613 		filter->ip_proto = match.key->ip_proto;
8614 	}
8615 
8616 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
8617 		struct flow_match_eth_addrs match;
8618 
8619 		flow_rule_match_eth_addrs(rule, &match);
8620 
8621 		/* use is_broadcast and is_zero to check for all 0xf or 0 */
8622 		if (!is_zero_ether_addr(match.mask->dst)) {
8623 			if (is_broadcast_ether_addr(match.mask->dst)) {
8624 				field_flags |= I40E_CLOUD_FIELD_OMAC;
8625 			} else {
8626 				dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
8627 					match.mask->dst);
8628 				return -EIO;
8629 			}
8630 		}
8631 
8632 		if (!is_zero_ether_addr(match.mask->src)) {
8633 			if (is_broadcast_ether_addr(match.mask->src)) {
8634 				field_flags |= I40E_CLOUD_FIELD_IMAC;
8635 			} else {
8636 				dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
8637 					match.mask->src);
8638 				return -EIO;
8639 			}
8640 		}
8641 		ether_addr_copy(filter->dst_mac, match.key->dst);
8642 		ether_addr_copy(filter->src_mac, match.key->src);
8643 	}
8644 
8645 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
8646 		struct flow_match_vlan match;
8647 
8648 		flow_rule_match_vlan(rule, &match);
8649 		if (match.mask->vlan_id) {
8650 			if (match.mask->vlan_id == VLAN_VID_MASK) {
8651 				field_flags |= I40E_CLOUD_FIELD_IVLAN;
8652 
8653 			} else {
8654 				dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
8655 					match.mask->vlan_id);
8656 				return -EIO;
8657 			}
8658 		}
8659 
8660 		filter->vlan_id = cpu_to_be16(match.key->vlan_id);
8661 	}
8662 
8663 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
8664 		struct flow_match_control match;
8665 
8666 		flow_rule_match_control(rule, &match);
8667 		addr_type = match.key->addr_type;
8668 
8669 		if (flow_rule_has_control_flags(match.mask->flags,
8670 						f->common.extack))
8671 			return -EOPNOTSUPP;
8672 	}
8673 
8674 	if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
8675 		struct flow_match_ipv4_addrs match;
8676 
8677 		flow_rule_match_ipv4_addrs(rule, &match);
8678 		if (match.mask->dst) {
8679 			if (match.mask->dst == cpu_to_be32(0xffffffff)) {
8680 				field_flags |= I40E_CLOUD_FIELD_IIP;
8681 			} else {
8682 				dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
8683 					&match.mask->dst);
8684 				return -EIO;
8685 			}
8686 		}
8687 
8688 		if (match.mask->src) {
8689 			if (match.mask->src == cpu_to_be32(0xffffffff)) {
8690 				field_flags |= I40E_CLOUD_FIELD_IIP;
8691 			} else {
8692 				dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
8693 					&match.mask->src);
8694 				return -EIO;
8695 			}
8696 		}
8697 
8698 		if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
8699 			dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
8700 			return -EIO;
8701 		}
8702 		filter->dst_ipv4 = match.key->dst;
8703 		filter->src_ipv4 = match.key->src;
8704 	}
8705 
8706 	if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
8707 		struct flow_match_ipv6_addrs match;
8708 
8709 		flow_rule_match_ipv6_addrs(rule, &match);
8710 
8711 		/* src and dest IPV6 address should not be LOOPBACK
8712 		 * (0:0:0:0:0:0:0:1), which can be represented as ::1
8713 		 */
8714 		if (ipv6_addr_loopback(&match.key->dst) ||
8715 		    ipv6_addr_loopback(&match.key->src)) {
8716 			dev_err(&pf->pdev->dev,
8717 				"Bad ipv6, addr is LOOPBACK\n");
8718 			return -EIO;
8719 		}
8720 		if (!ipv6_addr_any(&match.mask->dst) ||
8721 		    !ipv6_addr_any(&match.mask->src))
8722 			field_flags |= I40E_CLOUD_FIELD_IIP;
8723 
8724 		memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
8725 		       sizeof(filter->src_ipv6));
8726 		memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
8727 		       sizeof(filter->dst_ipv6));
8728 	}
8729 
8730 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
8731 		struct flow_match_ports match;
8732 
8733 		flow_rule_match_ports(rule, &match);
8734 		if (match.mask->src) {
8735 			if (match.mask->src == cpu_to_be16(0xffff)) {
8736 				field_flags |= I40E_CLOUD_FIELD_IIP;
8737 			} else {
8738 				dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
8739 					be16_to_cpu(match.mask->src));
8740 				return -EIO;
8741 			}
8742 		}
8743 
8744 		if (match.mask->dst) {
8745 			if (match.mask->dst == cpu_to_be16(0xffff)) {
8746 				field_flags |= I40E_CLOUD_FIELD_IIP;
8747 			} else {
8748 				dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
8749 					be16_to_cpu(match.mask->dst));
8750 				return -EIO;
8751 			}
8752 		}
8753 
8754 		filter->dst_port = match.key->dst;
8755 		filter->src_port = match.key->src;
8756 
8757 		switch (filter->ip_proto) {
8758 		case IPPROTO_TCP:
8759 		case IPPROTO_UDP:
8760 			break;
8761 		default:
8762 			dev_err(&pf->pdev->dev,
8763 				"Only UDP and TCP transport are supported\n");
8764 			return -EINVAL;
8765 		}
8766 	}
8767 	filter->flags = field_flags;
8768 	return 0;
8769 }
8770 
8771 /**
8772  * i40e_handle_tclass: Forward to a traffic class on the device
8773  * @vsi: Pointer to VSI
8774  * @tc: traffic class index on the device
8775  * @filter: Pointer to cloud filter structure
8776  *
8777  **/
8778 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
8779 			      struct i40e_cloud_filter *filter)
8780 {
8781 	struct i40e_channel *ch, *ch_tmp;
8782 
8783 	/* direct to a traffic class on the same device */
8784 	if (tc == 0) {
8785 		filter->seid = vsi->seid;
8786 		return 0;
8787 	} else if (vsi->tc_config.enabled_tc & BIT(tc)) {
8788 		if (!filter->dst_port) {
8789 			dev_err(&vsi->back->pdev->dev,
8790 				"Specify destination port to direct to traffic class that is not default\n");
8791 			return -EINVAL;
8792 		}
8793 		if (list_empty(&vsi->ch_list))
8794 			return -EINVAL;
8795 		list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
8796 					 list) {
8797 			if (ch->seid == vsi->tc_seid_map[tc])
8798 				filter->seid = ch->seid;
8799 		}
8800 		return 0;
8801 	}
8802 	dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
8803 	return -EINVAL;
8804 }
8805 
8806 /**
8807  * i40e_configure_clsflower - Configure tc flower filters
8808  * @vsi: Pointer to VSI
8809  * @cls_flower: Pointer to struct flow_cls_offload
8810  *
8811  **/
8812 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
8813 				    struct flow_cls_offload *cls_flower)
8814 {
8815 	int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
8816 	struct i40e_cloud_filter *filter = NULL;
8817 	struct i40e_pf *pf = vsi->back;
8818 	int err = 0;
8819 
8820 	if (tc < 0) {
8821 		dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
8822 		return -EOPNOTSUPP;
8823 	}
8824 
8825 	if (!tc) {
8826 		dev_err(&pf->pdev->dev, "Unable to add filter because of invalid destination");
8827 		return -EINVAL;
8828 	}
8829 
8830 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
8831 	    test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
8832 		return -EBUSY;
8833 
8834 	if (pf->fdir_pf_active_filters ||
8835 	    (!hlist_empty(&pf->fdir_filter_list))) {
8836 		dev_err(&vsi->back->pdev->dev,
8837 			"Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
8838 		return -EINVAL;
8839 	}
8840 
8841 	if (test_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags)) {
8842 		dev_err(&vsi->back->pdev->dev,
8843 			"Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
8844 		clear_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags);
8845 		clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, vsi->back->flags);
8846 	}
8847 
8848 	filter = kzalloc_obj(*filter);
8849 	if (!filter)
8850 		return -ENOMEM;
8851 
8852 	filter->cookie = cls_flower->cookie;
8853 
8854 	err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8855 	if (err < 0)
8856 		goto err;
8857 
8858 	err = i40e_handle_tclass(vsi, tc, filter);
8859 	if (err < 0)
8860 		goto err;
8861 
8862 	/* Add cloud filter */
8863 	if (filter->dst_port)
8864 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8865 	else
8866 		err = i40e_add_del_cloud_filter(vsi, filter, true);
8867 
8868 	if (err) {
8869 		dev_err(&pf->pdev->dev, "Failed to add cloud filter, err %d\n",
8870 			err);
8871 		goto err;
8872 	}
8873 
8874 	/* add filter to the ordered list */
8875 	INIT_HLIST_NODE(&filter->cloud_node);
8876 
8877 	hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8878 
8879 	pf->num_cloud_filters++;
8880 
8881 	return err;
8882 err:
8883 	kfree(filter);
8884 	return err;
8885 }
8886 
8887 /**
8888  * i40e_find_cloud_filter - Find the could filter in the list
8889  * @vsi: Pointer to VSI
8890  * @cookie: filter specific cookie
8891  *
8892  **/
8893 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8894 							unsigned long *cookie)
8895 {
8896 	struct i40e_cloud_filter *filter = NULL;
8897 	struct hlist_node *node2;
8898 
8899 	hlist_for_each_entry_safe(filter, node2,
8900 				  &vsi->back->cloud_filter_list, cloud_node)
8901 		if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8902 			return filter;
8903 	return NULL;
8904 }
8905 
8906 /**
8907  * i40e_delete_clsflower - Remove tc flower filters
8908  * @vsi: Pointer to VSI
8909  * @cls_flower: Pointer to struct flow_cls_offload
8910  *
8911  **/
8912 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8913 				 struct flow_cls_offload *cls_flower)
8914 {
8915 	struct i40e_cloud_filter *filter = NULL;
8916 	struct i40e_pf *pf = vsi->back;
8917 	int err = 0;
8918 
8919 	filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8920 
8921 	if (!filter)
8922 		return -EINVAL;
8923 
8924 	hash_del(&filter->cloud_node);
8925 
8926 	if (filter->dst_port)
8927 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8928 	else
8929 		err = i40e_add_del_cloud_filter(vsi, filter, false);
8930 
8931 	kfree(filter);
8932 	if (err) {
8933 		dev_err(&pf->pdev->dev,
8934 			"Failed to delete cloud filter, err %pe\n",
8935 			ERR_PTR(err));
8936 		return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8937 	}
8938 
8939 	pf->num_cloud_filters--;
8940 	if (!pf->num_cloud_filters)
8941 		if (test_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags) &&
8942 		    !test_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags)) {
8943 			set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
8944 			clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags);
8945 			clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
8946 		}
8947 	return 0;
8948 }
8949 
8950 /**
8951  * i40e_setup_tc_cls_flower - flower classifier offloads
8952  * @np: net device to configure
8953  * @cls_flower: offload data
8954  **/
8955 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8956 				    struct flow_cls_offload *cls_flower)
8957 {
8958 	struct i40e_vsi *vsi = np->vsi;
8959 
8960 	switch (cls_flower->command) {
8961 	case FLOW_CLS_REPLACE:
8962 		return i40e_configure_clsflower(vsi, cls_flower);
8963 	case FLOW_CLS_DESTROY:
8964 		return i40e_delete_clsflower(vsi, cls_flower);
8965 	case FLOW_CLS_STATS:
8966 		return -EOPNOTSUPP;
8967 	default:
8968 		return -EOPNOTSUPP;
8969 	}
8970 }
8971 
8972 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8973 				  void *cb_priv)
8974 {
8975 	struct i40e_netdev_priv *np = cb_priv;
8976 
8977 	if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8978 		return -EOPNOTSUPP;
8979 
8980 	switch (type) {
8981 	case TC_SETUP_CLSFLOWER:
8982 		return i40e_setup_tc_cls_flower(np, type_data);
8983 
8984 	default:
8985 		return -EOPNOTSUPP;
8986 	}
8987 }
8988 
8989 static LIST_HEAD(i40e_block_cb_list);
8990 
8991 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8992 			   void *type_data)
8993 {
8994 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8995 
8996 	switch (type) {
8997 	case TC_SETUP_QDISC_MQPRIO:
8998 		return i40e_setup_tc(netdev, type_data);
8999 	case TC_SETUP_BLOCK:
9000 		return flow_block_cb_setup_simple(type_data,
9001 						  &i40e_block_cb_list,
9002 						  i40e_setup_tc_block_cb,
9003 						  np, np, true);
9004 	default:
9005 		return -EOPNOTSUPP;
9006 	}
9007 }
9008 
9009 /**
9010  * i40e_open - Called when a network interface is made active
9011  * @netdev: network interface device structure
9012  *
9013  * The open entry point is called when a network interface is made
9014  * active by the system (IFF_UP).  At this point all resources needed
9015  * for transmit and receive operations are allocated, the interrupt
9016  * handler is registered with the OS, the netdev watchdog subtask is
9017  * enabled, and the stack is notified that the interface is ready.
9018  *
9019  * Returns 0 on success, negative value on failure
9020  **/
9021 int i40e_open(struct net_device *netdev)
9022 {
9023 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9024 	struct i40e_vsi *vsi = np->vsi;
9025 	struct i40e_pf *pf = vsi->back;
9026 	int err;
9027 
9028 	/* disallow open during test or if eeprom is broken */
9029 	if (test_bit(__I40E_TESTING, pf->state) ||
9030 	    test_bit(__I40E_BAD_EEPROM, pf->state))
9031 		return -EBUSY;
9032 
9033 	netif_carrier_off(netdev);
9034 
9035 	if (i40e_force_link_state(pf, true))
9036 		return -EAGAIN;
9037 
9038 	err = i40e_vsi_open(vsi);
9039 	if (err)
9040 		return err;
9041 
9042 	/* configure global TSO hardware offload settings */
9043 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
9044 						       TCP_FLAG_FIN) >> 16);
9045 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
9046 						       TCP_FLAG_FIN |
9047 						       TCP_FLAG_CWR) >> 16);
9048 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
9049 
9050 	return 0;
9051 }
9052 
9053 /**
9054  * i40e_netif_set_realnum_tx_rx_queues - Update number of tx/rx queues
9055  * @vsi: vsi structure
9056  *
9057  * This updates netdev's number of tx/rx queues
9058  *
9059  * Returns status of setting tx/rx queues
9060  **/
9061 static int i40e_netif_set_realnum_tx_rx_queues(struct i40e_vsi *vsi)
9062 {
9063 	int ret;
9064 
9065 	ret = netif_set_real_num_rx_queues(vsi->netdev,
9066 					   vsi->num_queue_pairs);
9067 	if (ret)
9068 		return ret;
9069 
9070 	return netif_set_real_num_tx_queues(vsi->netdev,
9071 					    vsi->num_queue_pairs);
9072 }
9073 
9074 /**
9075  * i40e_vsi_open -
9076  * @vsi: the VSI to open
9077  *
9078  * Finish initialization of the VSI.
9079  *
9080  * Returns 0 on success, negative value on failure
9081  *
9082  * Note: expects to be called while under rtnl_lock()
9083  **/
9084 int i40e_vsi_open(struct i40e_vsi *vsi)
9085 {
9086 	struct i40e_pf *pf = vsi->back;
9087 	char int_name[I40E_INT_NAME_STR_LEN];
9088 	int err;
9089 
9090 	/* allocate descriptors */
9091 	err = i40e_vsi_setup_tx_resources(vsi);
9092 	if (err)
9093 		goto err_setup_tx;
9094 	err = i40e_vsi_setup_rx_resources(vsi);
9095 	if (err)
9096 		goto err_setup_rx;
9097 
9098 	err = i40e_vsi_configure(vsi);
9099 	if (err)
9100 		goto err_setup_rx;
9101 
9102 	if (vsi->netdev) {
9103 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
9104 			 dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
9105 		err = i40e_vsi_request_irq(vsi, int_name);
9106 		if (err)
9107 			goto err_setup_rx;
9108 
9109 		/* Notify the stack of the actual queue counts. */
9110 		err = i40e_netif_set_realnum_tx_rx_queues(vsi);
9111 		if (err)
9112 			goto err_set_queues;
9113 
9114 	} else if (vsi->type == I40E_VSI_FDIR) {
9115 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
9116 			 dev_driver_string(&pf->pdev->dev),
9117 			 dev_name(&pf->pdev->dev));
9118 		err = i40e_vsi_request_irq(vsi, int_name);
9119 		if (err)
9120 			goto err_setup_rx;
9121 
9122 	} else {
9123 		err = -EINVAL;
9124 		goto err_setup_rx;
9125 	}
9126 
9127 	err = i40e_up_complete(vsi);
9128 	if (err)
9129 		goto err_up_complete;
9130 
9131 	return 0;
9132 
9133 err_up_complete:
9134 	i40e_down(vsi);
9135 err_set_queues:
9136 	i40e_vsi_free_irq(vsi);
9137 err_setup_rx:
9138 	i40e_vsi_free_rx_resources(vsi);
9139 err_setup_tx:
9140 	i40e_vsi_free_tx_resources(vsi);
9141 	if (vsi->type == I40E_VSI_MAIN)
9142 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
9143 
9144 	return err;
9145 }
9146 
9147 /**
9148  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
9149  * @pf: Pointer to PF
9150  *
9151  * This function destroys the hlist where all the Flow Director
9152  * filters were saved.
9153  **/
9154 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
9155 {
9156 	struct i40e_fdir_filter *filter;
9157 	struct i40e_flex_pit *pit_entry, *tmp;
9158 	struct hlist_node *node2;
9159 
9160 	hlist_for_each_entry_safe(filter, node2,
9161 				  &pf->fdir_filter_list, fdir_node) {
9162 		hlist_del(&filter->fdir_node);
9163 		kfree(filter);
9164 	}
9165 
9166 	list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
9167 		list_del(&pit_entry->list);
9168 		kfree(pit_entry);
9169 	}
9170 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
9171 
9172 	list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
9173 		list_del(&pit_entry->list);
9174 		kfree(pit_entry);
9175 	}
9176 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
9177 
9178 	pf->fdir_pf_active_filters = 0;
9179 	i40e_reset_fdir_filter_cnt(pf);
9180 
9181 	/* Reprogram the default input set for TCP/IPv4 */
9182 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV4_TCP,
9183 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9184 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9185 
9186 	/* Reprogram the default input set for TCP/IPv6 */
9187 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV6_TCP,
9188 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9189 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9190 
9191 	/* Reprogram the default input set for UDP/IPv4 */
9192 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV4_UDP,
9193 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9194 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9195 
9196 	/* Reprogram the default input set for UDP/IPv6 */
9197 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV6_UDP,
9198 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9199 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9200 
9201 	/* Reprogram the default input set for SCTP/IPv4 */
9202 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV4_SCTP,
9203 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9204 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9205 
9206 	/* Reprogram the default input set for SCTP/IPv6 */
9207 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV6_SCTP,
9208 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9209 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9210 
9211 	/* Reprogram the default input set for Other/IPv4 */
9212 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV4_OTHER,
9213 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9214 
9215 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_FRAG_IPV4,
9216 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9217 
9218 	/* Reprogram the default input set for Other/IPv6 */
9219 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV6_OTHER,
9220 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9221 
9222 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_FRAG_IPV6,
9223 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9224 }
9225 
9226 /**
9227  * i40e_cloud_filter_exit - Cleans up the cloud filters
9228  * @pf: Pointer to PF
9229  *
9230  * This function destroys the hlist where all the cloud filters
9231  * were saved.
9232  **/
9233 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
9234 {
9235 	struct i40e_cloud_filter *cfilter;
9236 	struct hlist_node *node;
9237 
9238 	hlist_for_each_entry_safe(cfilter, node,
9239 				  &pf->cloud_filter_list, cloud_node) {
9240 		hlist_del(&cfilter->cloud_node);
9241 		kfree(cfilter);
9242 	}
9243 	pf->num_cloud_filters = 0;
9244 
9245 	if (test_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags) &&
9246 	    !test_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags)) {
9247 		set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
9248 		clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags);
9249 		clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
9250 	}
9251 }
9252 
9253 /**
9254  * i40e_close - Disables a network interface
9255  * @netdev: network interface device structure
9256  *
9257  * The close entry point is called when an interface is de-activated
9258  * by the OS.  The hardware is still under the driver's control, but
9259  * this netdev interface is disabled.
9260  *
9261  * Returns 0, this is not allowed to fail
9262  **/
9263 int i40e_close(struct net_device *netdev)
9264 {
9265 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9266 	struct i40e_vsi *vsi = np->vsi;
9267 
9268 	i40e_vsi_close(vsi);
9269 
9270 	return 0;
9271 }
9272 
9273 /**
9274  * i40e_do_reset - Start a PF or Core Reset sequence
9275  * @pf: board private structure
9276  * @reset_flags: which reset is requested
9277  * @lock_acquired: indicates whether or not the lock has been acquired
9278  * before this function was called.
9279  *
9280  * The essential difference in resets is that the PF Reset
9281  * doesn't clear the packet buffers, doesn't reset the PE
9282  * firmware, and doesn't bother the other PFs on the chip.
9283  **/
9284 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
9285 {
9286 	struct i40e_vsi *vsi;
9287 	u32 val;
9288 	int i;
9289 
9290 	/* do the biggest reset indicated */
9291 	if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
9292 
9293 		/* Request a Global Reset
9294 		 *
9295 		 * This will start the chip's countdown to the actual full
9296 		 * chip reset event, and a warning interrupt to be sent
9297 		 * to all PFs, including the requestor.  Our handler
9298 		 * for the warning interrupt will deal with the shutdown
9299 		 * and recovery of the switch setup.
9300 		 */
9301 		dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
9302 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9303 		val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
9304 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9305 
9306 	} else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
9307 
9308 		/* Request a Core Reset
9309 		 *
9310 		 * Same as Global Reset, except does *not* include the MAC/PHY
9311 		 */
9312 		dev_dbg(&pf->pdev->dev, "CoreR requested\n");
9313 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9314 		val |= I40E_GLGEN_RTRIG_CORER_MASK;
9315 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9316 		i40e_flush(&pf->hw);
9317 
9318 	} else if (reset_flags & I40E_PF_RESET_FLAG) {
9319 
9320 		/* Request a PF Reset
9321 		 *
9322 		 * Resets only the PF-specific registers
9323 		 *
9324 		 * This goes directly to the tear-down and rebuild of
9325 		 * the switch, since we need to do all the recovery as
9326 		 * for the Core Reset.
9327 		 */
9328 		dev_dbg(&pf->pdev->dev, "PFR requested\n");
9329 		i40e_handle_reset_warning(pf, lock_acquired);
9330 
9331 	} else if (reset_flags & I40E_PF_RESET_AND_REBUILD_FLAG) {
9332 		/* Request a PF Reset
9333 		 *
9334 		 * Resets PF and reinitializes PFs VSI.
9335 		 */
9336 		i40e_prep_for_reset(pf);
9337 		i40e_reset_and_rebuild(pf, true, lock_acquired);
9338 		dev_info(&pf->pdev->dev,
9339 			 test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags) ?
9340 			 "FW LLDP is disabled\n" :
9341 			 "FW LLDP is enabled\n");
9342 
9343 	} else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
9344 		/* Find the VSI(s) that requested a re-init */
9345 		dev_info(&pf->pdev->dev, "VSI reinit requested\n");
9346 
9347 		i40e_pf_for_each_vsi(pf, i, vsi) {
9348 			if (test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
9349 					       vsi->state))
9350 				i40e_vsi_reinit_locked(vsi);
9351 		}
9352 	} else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
9353 		/* Find the VSI(s) that needs to be brought down */
9354 		dev_info(&pf->pdev->dev, "VSI down requested\n");
9355 
9356 		i40e_pf_for_each_vsi(pf, i, vsi) {
9357 			if (test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
9358 					       vsi->state)) {
9359 				set_bit(__I40E_VSI_DOWN, vsi->state);
9360 				i40e_down(vsi);
9361 			}
9362 		}
9363 	} else {
9364 		dev_info(&pf->pdev->dev,
9365 			 "bad reset request 0x%08x\n", reset_flags);
9366 	}
9367 }
9368 
9369 #ifdef CONFIG_I40E_DCB
9370 /**
9371  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
9372  * @pf: board private structure
9373  * @old_cfg: current DCB config
9374  * @new_cfg: new DCB config
9375  **/
9376 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
9377 			    struct i40e_dcbx_config *old_cfg,
9378 			    struct i40e_dcbx_config *new_cfg)
9379 {
9380 	bool need_reconfig = false;
9381 
9382 	/* Check if ETS configuration has changed */
9383 	if (memcmp(&new_cfg->etscfg,
9384 		   &old_cfg->etscfg,
9385 		   sizeof(new_cfg->etscfg))) {
9386 		/* If Priority Table has changed reconfig is needed */
9387 		if (memcmp(&new_cfg->etscfg.prioritytable,
9388 			   &old_cfg->etscfg.prioritytable,
9389 			   sizeof(new_cfg->etscfg.prioritytable))) {
9390 			need_reconfig = true;
9391 			dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
9392 		}
9393 
9394 		if (memcmp(&new_cfg->etscfg.tcbwtable,
9395 			   &old_cfg->etscfg.tcbwtable,
9396 			   sizeof(new_cfg->etscfg.tcbwtable)))
9397 			dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
9398 
9399 		if (memcmp(&new_cfg->etscfg.tsatable,
9400 			   &old_cfg->etscfg.tsatable,
9401 			   sizeof(new_cfg->etscfg.tsatable)))
9402 			dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
9403 	}
9404 
9405 	/* Check if PFC configuration has changed */
9406 	if (memcmp(&new_cfg->pfc,
9407 		   &old_cfg->pfc,
9408 		   sizeof(new_cfg->pfc))) {
9409 		need_reconfig = true;
9410 		dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
9411 	}
9412 
9413 	/* Check if APP Table has changed */
9414 	if (memcmp(&new_cfg->app,
9415 		   &old_cfg->app,
9416 		   sizeof(new_cfg->app))) {
9417 		need_reconfig = true;
9418 		dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
9419 	}
9420 
9421 	dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
9422 	return need_reconfig;
9423 }
9424 
9425 /**
9426  * i40e_handle_lldp_event - Handle LLDP Change MIB event
9427  * @pf: board private structure
9428  * @e: event info posted on ARQ
9429  **/
9430 static int i40e_handle_lldp_event(struct i40e_pf *pf,
9431 				  struct i40e_arq_event_info *e)
9432 {
9433 	struct i40e_aqc_lldp_get_mib *mib = libie_aq_raw(&e->desc);
9434 	struct i40e_hw *hw = &pf->hw;
9435 	struct i40e_dcbx_config tmp_dcbx_cfg;
9436 	bool need_reconfig = false;
9437 	int ret = 0;
9438 	u8 type;
9439 
9440 	/* X710-T*L 2.5G and 5G speeds don't support DCB */
9441 	if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9442 	    (hw->phy.link_info.link_speed &
9443 	     ~(I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB)) &&
9444 	     !test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
9445 		/* let firmware decide if the DCB should be disabled */
9446 		set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9447 
9448 	/* Not DCB capable or capability disabled */
9449 	if (!test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
9450 		return ret;
9451 
9452 	/* Ignore if event is not for Nearest Bridge */
9453 	type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
9454 		& I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
9455 	dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
9456 	if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
9457 		return ret;
9458 
9459 	/* Check MIB Type and return if event for Remote MIB update */
9460 	type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
9461 	dev_dbg(&pf->pdev->dev,
9462 		"LLDP event mib type %s\n", type ? "remote" : "local");
9463 	if (type == I40E_AQ_LLDP_MIB_REMOTE) {
9464 		/* Update the remote cached instance and return */
9465 		ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
9466 				I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
9467 				&hw->remote_dcbx_config);
9468 		goto exit;
9469 	}
9470 
9471 	/* Store the old configuration */
9472 	tmp_dcbx_cfg = hw->local_dcbx_config;
9473 
9474 	/* Reset the old DCBx configuration data */
9475 	memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
9476 	/* Get updated DCBX data from firmware */
9477 	ret = i40e_get_dcb_config(&pf->hw);
9478 	if (ret) {
9479 		/* X710-T*L 2.5G and 5G speeds don't support DCB */
9480 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9481 		    (hw->phy.link_info.link_speed &
9482 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
9483 			dev_warn(&pf->pdev->dev,
9484 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
9485 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9486 		} else {
9487 			dev_info(&pf->pdev->dev,
9488 				 "Failed querying DCB configuration data from firmware, err %pe aq_err %s\n",
9489 				 ERR_PTR(ret),
9490 				 libie_aq_str(pf->hw.aq.asq_last_status));
9491 		}
9492 		goto exit;
9493 	}
9494 
9495 	/* No change detected in DCBX configs */
9496 	if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
9497 		    sizeof(tmp_dcbx_cfg))) {
9498 		dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
9499 		goto exit;
9500 	}
9501 
9502 	need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
9503 					       &hw->local_dcbx_config);
9504 
9505 	i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
9506 
9507 	if (!need_reconfig)
9508 		goto exit;
9509 
9510 	/* Enable DCB tagging only when more than one TC */
9511 	if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
9512 		set_bit(I40E_FLAG_DCB_ENA, pf->flags);
9513 	else
9514 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
9515 
9516 	set_bit(__I40E_PORT_SUSPENDED, pf->state);
9517 	/* Reconfiguration needed quiesce all VSIs */
9518 	i40e_pf_quiesce_all_vsi(pf);
9519 
9520 	/* Changes in configuration update VEB/VSI */
9521 	i40e_dcb_reconfigure(pf);
9522 
9523 	ret = i40e_resume_port_tx(pf);
9524 
9525 	clear_bit(__I40E_PORT_SUSPENDED, pf->state);
9526 	/* In case of error no point in resuming VSIs */
9527 	if (ret)
9528 		goto exit;
9529 
9530 	/* Wait for the PF's queues to be disabled */
9531 	ret = i40e_pf_wait_queues_disabled(pf);
9532 	if (ret) {
9533 		/* Schedule PF reset to recover */
9534 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9535 		i40e_service_event_schedule(pf);
9536 	} else {
9537 		i40e_pf_unquiesce_all_vsi(pf);
9538 		set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
9539 		set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
9540 	}
9541 
9542 exit:
9543 	return ret;
9544 }
9545 #endif /* CONFIG_I40E_DCB */
9546 
9547 /**
9548  * i40e_do_reset_safe - Protected reset path for userland calls.
9549  * @pf: board private structure
9550  * @reset_flags: which reset is requested
9551  *
9552  **/
9553 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
9554 {
9555 	rtnl_lock();
9556 	i40e_do_reset(pf, reset_flags, true);
9557 	rtnl_unlock();
9558 }
9559 
9560 /**
9561  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
9562  * @pf: board private structure
9563  * @e: event info posted on ARQ
9564  *
9565  * Handler for LAN Queue Overflow Event generated by the firmware for PF
9566  * and VF queues
9567  **/
9568 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
9569 					   struct i40e_arq_event_info *e)
9570 {
9571 	struct i40e_aqc_lan_overflow *data = libie_aq_raw(&e->desc);
9572 	u32 queue = le32_to_cpu(data->prtdcb_rupto);
9573 	u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
9574 	struct i40e_hw *hw = &pf->hw;
9575 	struct i40e_vf *vf;
9576 	u16 vf_id;
9577 
9578 	dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
9579 		queue, qtx_ctl);
9580 
9581 	if (FIELD_GET(I40E_QTX_CTL_PFVF_Q_MASK, qtx_ctl) !=
9582 	    I40E_QTX_CTL_VF_QUEUE)
9583 		return;
9584 
9585 	/* Queue belongs to VF, find the VF and issue VF reset */
9586 	vf_id = FIELD_GET(I40E_QTX_CTL_VFVM_INDX_MASK, qtx_ctl);
9587 	vf_id -= hw->func_caps.vf_base_id;
9588 	vf = &pf->vf[vf_id];
9589 	i40e_vc_notify_vf_reset(vf);
9590 	/* Allow VF to process pending reset notification */
9591 	msleep(20);
9592 	i40e_reset_vf(vf, false);
9593 }
9594 
9595 /**
9596  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
9597  * @pf: board private structure
9598  **/
9599 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
9600 {
9601 	u32 val, fcnt_prog;
9602 
9603 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9604 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
9605 		    FIELD_GET(I40E_PFQF_FDSTAT_BEST_CNT_MASK, val);
9606 	return fcnt_prog;
9607 }
9608 
9609 /**
9610  * i40e_get_global_fd_count - Get total FD filters programmed on device
9611  * @pf: board private structure
9612  **/
9613 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
9614 {
9615 	u32 val, fcnt_prog;
9616 
9617 	val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
9618 	fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
9619 		    FIELD_GET(I40E_GLQF_FDCNT_0_BESTCNT_MASK, val);
9620 	return fcnt_prog;
9621 }
9622 
9623 /**
9624  * i40e_reenable_fdir_sb - Restore FDir SB capability
9625  * @pf: board private structure
9626  **/
9627 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
9628 {
9629 	if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
9630 		if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
9631 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9632 			dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
9633 }
9634 
9635 /**
9636  * i40e_reenable_fdir_atr - Restore FDir ATR capability
9637  * @pf: board private structure
9638  **/
9639 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
9640 {
9641 	if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
9642 		/* ATR uses the same filtering logic as SB rules. It only
9643 		 * functions properly if the input set mask is at the default
9644 		 * settings. It is safe to restore the default input set
9645 		 * because there are no active TCPv4 filter rules.
9646 		 */
9647 		i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV4_TCP,
9648 					I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9649 					I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9650 
9651 		if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
9652 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9653 			dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
9654 	}
9655 }
9656 
9657 /**
9658  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
9659  * @pf: board private structure
9660  * @filter: FDir filter to remove
9661  */
9662 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
9663 				       struct i40e_fdir_filter *filter)
9664 {
9665 	/* Update counters */
9666 	pf->fdir_pf_active_filters--;
9667 	pf->fd_inv = 0;
9668 
9669 	switch (filter->flow_type) {
9670 	case TCP_V4_FLOW:
9671 		pf->fd_tcp4_filter_cnt--;
9672 		break;
9673 	case UDP_V4_FLOW:
9674 		pf->fd_udp4_filter_cnt--;
9675 		break;
9676 	case SCTP_V4_FLOW:
9677 		pf->fd_sctp4_filter_cnt--;
9678 		break;
9679 	case TCP_V6_FLOW:
9680 		pf->fd_tcp6_filter_cnt--;
9681 		break;
9682 	case UDP_V6_FLOW:
9683 		pf->fd_udp6_filter_cnt--;
9684 		break;
9685 	case SCTP_V6_FLOW:
9686 		pf->fd_udp6_filter_cnt--;
9687 		break;
9688 	case IP_USER_FLOW:
9689 		switch (filter->ipl4_proto) {
9690 		case IPPROTO_TCP:
9691 			pf->fd_tcp4_filter_cnt--;
9692 			break;
9693 		case IPPROTO_UDP:
9694 			pf->fd_udp4_filter_cnt--;
9695 			break;
9696 		case IPPROTO_SCTP:
9697 			pf->fd_sctp4_filter_cnt--;
9698 			break;
9699 		case IPPROTO_IP:
9700 			pf->fd_ip4_filter_cnt--;
9701 			break;
9702 		}
9703 		break;
9704 	case IPV6_USER_FLOW:
9705 		switch (filter->ipl4_proto) {
9706 		case IPPROTO_TCP:
9707 			pf->fd_tcp6_filter_cnt--;
9708 			break;
9709 		case IPPROTO_UDP:
9710 			pf->fd_udp6_filter_cnt--;
9711 			break;
9712 		case IPPROTO_SCTP:
9713 			pf->fd_sctp6_filter_cnt--;
9714 			break;
9715 		case IPPROTO_IP:
9716 			pf->fd_ip6_filter_cnt--;
9717 			break;
9718 		}
9719 		break;
9720 	}
9721 
9722 	/* Remove the filter from the list and free memory */
9723 	hlist_del(&filter->fdir_node);
9724 	kfree(filter);
9725 }
9726 
9727 /**
9728  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
9729  * @pf: board private structure
9730  **/
9731 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
9732 {
9733 	struct i40e_fdir_filter *filter;
9734 	u32 fcnt_prog, fcnt_avail;
9735 	struct hlist_node *node;
9736 
9737 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9738 		return;
9739 
9740 	/* Check if we have enough room to re-enable FDir SB capability. */
9741 	fcnt_prog = i40e_get_global_fd_count(pf);
9742 	fcnt_avail = pf->fdir_pf_filter_count;
9743 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
9744 	    (pf->fd_add_err == 0) ||
9745 	    (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
9746 		i40e_reenable_fdir_sb(pf);
9747 
9748 	/* We should wait for even more space before re-enabling ATR.
9749 	 * Additionally, we cannot enable ATR as long as we still have TCP SB
9750 	 * rules active.
9751 	 */
9752 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
9753 	    pf->fd_tcp4_filter_cnt == 0 && pf->fd_tcp6_filter_cnt == 0)
9754 		i40e_reenable_fdir_atr(pf);
9755 
9756 	/* if hw had a problem adding a filter, delete it */
9757 	if (pf->fd_inv > 0) {
9758 		hlist_for_each_entry_safe(filter, node,
9759 					  &pf->fdir_filter_list, fdir_node)
9760 			if (filter->fd_id == pf->fd_inv)
9761 				i40e_delete_invalid_filter(pf, filter);
9762 	}
9763 }
9764 
9765 #define I40E_MIN_FD_FLUSH_INTERVAL 10
9766 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
9767 /**
9768  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
9769  * @pf: board private structure
9770  **/
9771 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
9772 {
9773 	unsigned long min_flush_time;
9774 	int flush_wait_retry = 50;
9775 	bool disable_atr = false;
9776 	int fd_room;
9777 	int reg;
9778 
9779 	if (!time_after(jiffies, pf->fd_flush_timestamp +
9780 				 (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
9781 		return;
9782 
9783 	/* If the flush is happening too quick and we have mostly SB rules we
9784 	 * should not re-enable ATR for some time.
9785 	 */
9786 	min_flush_time = pf->fd_flush_timestamp +
9787 			 (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
9788 	fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
9789 
9790 	if (!(time_after(jiffies, min_flush_time)) &&
9791 	    (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
9792 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9793 			dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
9794 		disable_atr = true;
9795 	}
9796 
9797 	pf->fd_flush_timestamp = jiffies;
9798 	set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9799 	/* flush all filters */
9800 	wr32(&pf->hw, I40E_PFQF_CTL_1,
9801 	     I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
9802 	i40e_flush(&pf->hw);
9803 	pf->fd_flush_cnt++;
9804 	pf->fd_add_err = 0;
9805 	do {
9806 		/* Check FD flush status every 5-6msec */
9807 		usleep_range(5000, 6000);
9808 		reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
9809 		if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
9810 			break;
9811 	} while (flush_wait_retry--);
9812 	if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
9813 		dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
9814 	} else {
9815 		/* replay sideband filters */
9816 		i40e_fdir_filter_restore(i40e_pf_get_main_vsi(pf));
9817 		if (!disable_atr && !pf->fd_tcp4_filter_cnt)
9818 			clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9819 		clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
9820 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9821 			dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
9822 	}
9823 }
9824 
9825 /**
9826  * i40e_get_current_atr_cnt - Get the count of total FD ATR filters programmed
9827  * @pf: board private structure
9828  **/
9829 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
9830 {
9831 	return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
9832 }
9833 
9834 /**
9835  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
9836  * @pf: board private structure
9837  **/
9838 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
9839 {
9840 
9841 	/* if interface is down do nothing */
9842 	if (test_bit(__I40E_DOWN, pf->state))
9843 		return;
9844 
9845 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9846 		i40e_fdir_flush_and_replay(pf);
9847 
9848 	i40e_fdir_check_and_reenable(pf);
9849 
9850 }
9851 
9852 /**
9853  * i40e_vsi_link_event - notify VSI of a link event
9854  * @vsi: vsi to be notified
9855  * @link_up: link up or down
9856  **/
9857 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
9858 {
9859 	if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
9860 		return;
9861 
9862 	switch (vsi->type) {
9863 	case I40E_VSI_MAIN:
9864 		if (!vsi->netdev || !vsi->netdev_registered)
9865 			break;
9866 
9867 		if (link_up) {
9868 			netif_carrier_on(vsi->netdev);
9869 			netif_tx_wake_all_queues(vsi->netdev);
9870 		} else {
9871 			netif_carrier_off(vsi->netdev);
9872 			netif_tx_stop_all_queues(vsi->netdev);
9873 		}
9874 		break;
9875 
9876 	case I40E_VSI_SRIOV:
9877 	case I40E_VSI_VMDQ2:
9878 	case I40E_VSI_CTRL:
9879 	case I40E_VSI_IWARP:
9880 	case I40E_VSI_MIRROR:
9881 	default:
9882 		/* there is no notification for other VSIs */
9883 		break;
9884 	}
9885 }
9886 
9887 /**
9888  * i40e_veb_link_event - notify elements on the veb of a link event
9889  * @veb: veb to be notified
9890  * @link_up: link up or down
9891  **/
9892 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
9893 {
9894 	struct i40e_vsi *vsi;
9895 	struct i40e_pf *pf;
9896 	int i;
9897 
9898 	if (!veb || !veb->pf)
9899 		return;
9900 	pf = veb->pf;
9901 
9902 	/* Send link event to contained VSIs */
9903 	i40e_pf_for_each_vsi(pf, i, vsi)
9904 		if (vsi->uplink_seid == veb->seid)
9905 			i40e_vsi_link_event(vsi, link_up);
9906 }
9907 
9908 /**
9909  * i40e_link_event - Update netif_carrier status
9910  * @pf: board private structure
9911  **/
9912 static void i40e_link_event(struct i40e_pf *pf)
9913 {
9914 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
9915 	struct i40e_veb *veb = i40e_pf_get_main_veb(pf);
9916 	u8 new_link_speed, old_link_speed;
9917 	bool new_link, old_link;
9918 	int status;
9919 #ifdef CONFIG_I40E_DCB
9920 	int err;
9921 #endif /* CONFIG_I40E_DCB */
9922 
9923 	/* set this to force the get_link_status call to refresh state */
9924 	pf->hw.phy.get_link_info = true;
9925 	old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9926 	status = i40e_get_link_status(&pf->hw, &new_link);
9927 
9928 	/* On success, disable temp link polling */
9929 	if (status == 0) {
9930 		clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9931 	} else {
9932 		/* Enable link polling temporarily until i40e_get_link_status
9933 		 * returns 0
9934 		 */
9935 		set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9936 		dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9937 			status);
9938 		return;
9939 	}
9940 
9941 	old_link_speed = pf->hw.phy.link_info_old.link_speed;
9942 	new_link_speed = pf->hw.phy.link_info.link_speed;
9943 
9944 	if (new_link == old_link &&
9945 	    new_link_speed == old_link_speed &&
9946 	    (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9947 	     new_link == netif_carrier_ok(vsi->netdev)))
9948 		return;
9949 
9950 	if (!new_link && old_link)
9951 		pf->link_down_events++;
9952 
9953 	i40e_print_link_message(vsi, new_link);
9954 
9955 	/* Notify the base of the switch tree connected to
9956 	 * the link.  Floating VEBs are not notified.
9957 	 */
9958 	if (veb)
9959 		i40e_veb_link_event(veb, new_link);
9960 	else
9961 		i40e_vsi_link_event(vsi, new_link);
9962 
9963 	if (pf->vf)
9964 		i40e_vc_notify_link_state(pf);
9965 
9966 	if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
9967 		i40e_ptp_set_increment(pf);
9968 #ifdef CONFIG_I40E_DCB
9969 	if (new_link == old_link)
9970 		return;
9971 	/* Not SW DCB so firmware will take care of default settings */
9972 	if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED)
9973 		return;
9974 
9975 	/* We cover here only link down, as after link up in case of SW DCB
9976 	 * SW LLDP agent will take care of setting it up
9977 	 */
9978 	if (!new_link) {
9979 		dev_dbg(&pf->pdev->dev, "Reconfig DCB to single TC as result of Link Down\n");
9980 		memset(&pf->tmp_cfg, 0, sizeof(pf->tmp_cfg));
9981 		err = i40e_dcb_sw_default_config(pf);
9982 		if (err) {
9983 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9984 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
9985 		} else {
9986 			pf->dcbx_cap = DCB_CAP_DCBX_HOST |
9987 				       DCB_CAP_DCBX_VER_IEEE;
9988 			set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9989 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
9990 		}
9991 	}
9992 #endif /* CONFIG_I40E_DCB */
9993 }
9994 
9995 /**
9996  * i40e_watchdog_subtask - periodic checks not using event driven response
9997  * @pf: board private structure
9998  **/
9999 static void i40e_watchdog_subtask(struct i40e_pf *pf)
10000 {
10001 	struct i40e_vsi *vsi;
10002 	struct i40e_veb *veb;
10003 	int i;
10004 
10005 	/* if interface is down do nothing */
10006 	if (test_bit(__I40E_DOWN, pf->state) ||
10007 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
10008 		return;
10009 
10010 	/* make sure we don't do these things too often */
10011 	if (time_before(jiffies, (pf->service_timer_previous +
10012 				  pf->service_timer_period)))
10013 		return;
10014 	pf->service_timer_previous = jiffies;
10015 
10016 	if (test_bit(I40E_FLAG_LINK_POLLING_ENA, pf->flags) ||
10017 	    test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
10018 		i40e_link_event(pf);
10019 
10020 	/* Update the stats for active netdevs so the network stack
10021 	 * can look at updated numbers whenever it cares to
10022 	 */
10023 	i40e_pf_for_each_vsi(pf, i, vsi)
10024 		if (vsi->netdev)
10025 			i40e_update_stats(vsi);
10026 
10027 	if (test_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags)) {
10028 		/* Update the stats for the active switching components */
10029 		i40e_pf_for_each_veb(pf, i, veb)
10030 			i40e_update_veb_stats(veb);
10031 	}
10032 
10033 	i40e_ptp_rx_hang(pf);
10034 	i40e_ptp_tx_hang(pf);
10035 }
10036 
10037 /**
10038  * i40e_reset_subtask - Set up for resetting the device and driver
10039  * @pf: board private structure
10040  **/
10041 static void i40e_reset_subtask(struct i40e_pf *pf)
10042 {
10043 	u32 reset_flags = 0;
10044 
10045 	if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
10046 		reset_flags |= BIT(__I40E_REINIT_REQUESTED);
10047 		clear_bit(__I40E_REINIT_REQUESTED, pf->state);
10048 	}
10049 	if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
10050 		reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
10051 		clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
10052 	}
10053 	if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
10054 		reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
10055 		clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
10056 	}
10057 	if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
10058 		reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
10059 		clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
10060 	}
10061 	if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
10062 		reset_flags |= BIT(__I40E_DOWN_REQUESTED);
10063 		clear_bit(__I40E_DOWN_REQUESTED, pf->state);
10064 	}
10065 
10066 	/* If there's a recovery already waiting, it takes
10067 	 * precedence before starting a new reset sequence.
10068 	 */
10069 	if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
10070 		i40e_prep_for_reset(pf);
10071 		i40e_reset(pf);
10072 		i40e_rebuild(pf, false, false);
10073 	}
10074 
10075 	/* If we're already down or resetting, just bail */
10076 	if (reset_flags &&
10077 	    !test_bit(__I40E_DOWN, pf->state) &&
10078 	    !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
10079 		i40e_do_reset(pf, reset_flags, false);
10080 	}
10081 }
10082 
10083 /**
10084  * i40e_handle_link_event - Handle link event
10085  * @pf: board private structure
10086  * @e: event info posted on ARQ
10087  **/
10088 static void i40e_handle_link_event(struct i40e_pf *pf,
10089 				   struct i40e_arq_event_info *e)
10090 {
10091 	struct i40e_aqc_get_link_status *status = libie_aq_raw(&e->desc);
10092 
10093 	/* Do a new status request to re-enable LSE reporting
10094 	 * and load new status information into the hw struct
10095 	 * This completely ignores any state information
10096 	 * in the ARQ event info, instead choosing to always
10097 	 * issue the AQ update link status command.
10098 	 */
10099 	i40e_link_event(pf);
10100 
10101 	/* Check if module meets thermal requirements */
10102 	if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
10103 		dev_err(&pf->pdev->dev,
10104 			"Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
10105 		dev_err(&pf->pdev->dev,
10106 			"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10107 	} else {
10108 		/* check for unqualified module, if link is down, suppress
10109 		 * the message if link was forced to be down.
10110 		 */
10111 		if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
10112 		    (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
10113 		    (!(status->link_info & I40E_AQ_LINK_UP)) &&
10114 		    (!test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags))) {
10115 			dev_err(&pf->pdev->dev,
10116 				"Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
10117 			dev_err(&pf->pdev->dev,
10118 				"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10119 		}
10120 	}
10121 }
10122 
10123 /**
10124  * i40e_clean_adminq_subtask - Clean the AdminQ rings
10125  * @pf: board private structure
10126  **/
10127 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
10128 {
10129 	struct i40e_arq_event_info event;
10130 	struct i40e_hw *hw = &pf->hw;
10131 	u16 pending, i = 0;
10132 	u16 opcode;
10133 	u32 oldval;
10134 	int ret;
10135 	u32 val;
10136 
10137 	/* Do not run clean AQ when PF reset fails */
10138 	if (test_bit(__I40E_RESET_FAILED, pf->state))
10139 		return;
10140 
10141 	/* check for error indications */
10142 	val = rd32(&pf->hw, I40E_PF_ARQLEN);
10143 	oldval = val;
10144 	if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
10145 		if (hw->debug_mask & I40E_DEBUG_AQ)
10146 			dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
10147 		val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
10148 	}
10149 	if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
10150 		if (hw->debug_mask & I40E_DEBUG_AQ)
10151 			dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
10152 		val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
10153 		pf->arq_overflows++;
10154 	}
10155 	if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
10156 		if (hw->debug_mask & I40E_DEBUG_AQ)
10157 			dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
10158 		val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
10159 	}
10160 	if (oldval != val)
10161 		wr32(&pf->hw, I40E_PF_ARQLEN, val);
10162 
10163 	val = rd32(&pf->hw, I40E_PF_ATQLEN);
10164 	oldval = val;
10165 	if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
10166 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10167 			dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
10168 		val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
10169 	}
10170 	if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
10171 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10172 			dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
10173 		val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
10174 	}
10175 	if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
10176 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10177 			dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
10178 		val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
10179 	}
10180 	if (oldval != val)
10181 		wr32(&pf->hw, I40E_PF_ATQLEN, val);
10182 
10183 	event.buf_len = I40E_MAX_AQ_BUF_SIZE;
10184 	event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
10185 	if (!event.msg_buf)
10186 		return;
10187 
10188 	do {
10189 		ret = i40e_clean_arq_element(hw, &event, &pending);
10190 		if (ret == -EALREADY)
10191 			break;
10192 		else if (ret) {
10193 			dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
10194 			break;
10195 		}
10196 
10197 		opcode = le16_to_cpu(event.desc.opcode);
10198 		switch (opcode) {
10199 
10200 		case i40e_aqc_opc_get_link_status:
10201 			rtnl_lock();
10202 			i40e_handle_link_event(pf, &event);
10203 			rtnl_unlock();
10204 			break;
10205 		case i40e_aqc_opc_send_msg_to_pf:
10206 			ret = i40e_vc_process_vf_msg(pf,
10207 					le16_to_cpu(event.desc.retval),
10208 					le32_to_cpu(event.desc.cookie_high),
10209 					le32_to_cpu(event.desc.cookie_low),
10210 					event.msg_buf,
10211 					event.msg_len);
10212 			break;
10213 		case i40e_aqc_opc_lldp_update_mib:
10214 			dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
10215 #ifdef CONFIG_I40E_DCB
10216 			rtnl_lock();
10217 			i40e_handle_lldp_event(pf, &event);
10218 			rtnl_unlock();
10219 #endif /* CONFIG_I40E_DCB */
10220 			break;
10221 		case i40e_aqc_opc_event_lan_overflow:
10222 			dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
10223 			i40e_handle_lan_overflow_event(pf, &event);
10224 			break;
10225 		case i40e_aqc_opc_send_msg_to_peer:
10226 			dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
10227 			break;
10228 		case i40e_aqc_opc_nvm_erase:
10229 		case i40e_aqc_opc_nvm_update:
10230 		case i40e_aqc_opc_oem_post_update:
10231 			i40e_debug(&pf->hw, I40E_DEBUG_NVM,
10232 				   "ARQ NVM operation 0x%04x completed\n",
10233 				   opcode);
10234 			break;
10235 		default:
10236 			dev_info(&pf->pdev->dev,
10237 				 "ARQ: Unknown event 0x%04x ignored\n",
10238 				 opcode);
10239 			break;
10240 		}
10241 	} while (i++ < I40E_AQ_WORK_LIMIT);
10242 
10243 	if (i < I40E_AQ_WORK_LIMIT)
10244 		clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
10245 
10246 	/* re-enable Admin queue interrupt cause */
10247 	val = rd32(hw, I40E_PFINT_ICR0_ENA);
10248 	val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
10249 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
10250 	i40e_flush(hw);
10251 
10252 	kfree(event.msg_buf);
10253 }
10254 
10255 /**
10256  * i40e_verify_eeprom - make sure eeprom is good to use
10257  * @pf: board private structure
10258  **/
10259 static void i40e_verify_eeprom(struct i40e_pf *pf)
10260 {
10261 	int err;
10262 
10263 	err = i40e_diag_eeprom_test(&pf->hw);
10264 	if (err) {
10265 		/* retry in case of garbage read */
10266 		err = i40e_diag_eeprom_test(&pf->hw);
10267 		if (err) {
10268 			dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
10269 				 err);
10270 			set_bit(__I40E_BAD_EEPROM, pf->state);
10271 		}
10272 	}
10273 
10274 	if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
10275 		dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
10276 		clear_bit(__I40E_BAD_EEPROM, pf->state);
10277 	}
10278 }
10279 
10280 /**
10281  * i40e_enable_pf_switch_lb
10282  * @pf: pointer to the PF structure
10283  *
10284  * enable switch loop back or die - no point in a return value
10285  **/
10286 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
10287 {
10288 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
10289 	struct i40e_vsi_context ctxt;
10290 	int ret;
10291 
10292 	ctxt.seid = pf->main_vsi_seid;
10293 	ctxt.pf_num = pf->hw.pf_id;
10294 	ctxt.vf_num = 0;
10295 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10296 	if (ret) {
10297 		dev_info(&pf->pdev->dev,
10298 			 "couldn't get PF vsi config, err %pe aq_err %s\n",
10299 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
10300 		return;
10301 	}
10302 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10303 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10304 	ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10305 
10306 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10307 	if (ret) {
10308 		dev_info(&pf->pdev->dev,
10309 			 "update vsi switch failed, err %pe aq_err %s\n",
10310 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
10311 	}
10312 }
10313 
10314 /**
10315  * i40e_disable_pf_switch_lb
10316  * @pf: pointer to the PF structure
10317  *
10318  * disable switch loop back or die - no point in a return value
10319  **/
10320 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
10321 {
10322 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
10323 	struct i40e_vsi_context ctxt;
10324 	int ret;
10325 
10326 	ctxt.seid = pf->main_vsi_seid;
10327 	ctxt.pf_num = pf->hw.pf_id;
10328 	ctxt.vf_num = 0;
10329 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10330 	if (ret) {
10331 		dev_info(&pf->pdev->dev,
10332 			 "couldn't get PF vsi config, err %pe aq_err %s\n",
10333 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
10334 		return;
10335 	}
10336 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10337 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10338 	ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10339 
10340 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10341 	if (ret) {
10342 		dev_info(&pf->pdev->dev,
10343 			 "update vsi switch failed, err %pe aq_err %s\n",
10344 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
10345 	}
10346 }
10347 
10348 /**
10349  * i40e_config_bridge_mode - Configure the HW bridge mode
10350  * @veb: pointer to the bridge instance
10351  *
10352  * Configure the loop back mode for the LAN VSI that is downlink to the
10353  * specified HW bridge instance. It is expected this function is called
10354  * when a new HW bridge is instantiated.
10355  **/
10356 static void i40e_config_bridge_mode(struct i40e_veb *veb)
10357 {
10358 	struct i40e_pf *pf = veb->pf;
10359 
10360 	if (pf->hw.debug_mask & I40E_DEBUG_LAN)
10361 		dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
10362 			 veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
10363 	if (veb->bridge_mode & BRIDGE_MODE_VEPA)
10364 		i40e_disable_pf_switch_lb(pf);
10365 	else
10366 		i40e_enable_pf_switch_lb(pf);
10367 }
10368 
10369 /**
10370  * i40e_reconstitute_veb - rebuild the VEB and VSIs connected to it
10371  * @veb: pointer to the VEB instance
10372  *
10373  * This is a function that builds the attached VSIs. We track the connections
10374  * through our own index numbers because the seid's from the HW could change
10375  * across the reset.
10376  **/
10377 static int i40e_reconstitute_veb(struct i40e_veb *veb)
10378 {
10379 	struct i40e_vsi *ctl_vsi = NULL;
10380 	struct i40e_pf *pf = veb->pf;
10381 	struct i40e_vsi *vsi;
10382 	int v, ret;
10383 
10384 	/* As we do not maintain PV (port virtualizer) switch element then
10385 	 * there can be only one non-floating VEB that have uplink to MAC SEID
10386 	 * and its control VSI is the main one.
10387 	 */
10388 	if (WARN_ON(veb->uplink_seid && veb->uplink_seid != pf->mac_seid)) {
10389 		dev_err(&pf->pdev->dev,
10390 			"Invalid uplink SEID for VEB %d\n", veb->idx);
10391 		return -ENOENT;
10392 	}
10393 
10394 	if (veb->uplink_seid == pf->mac_seid) {
10395 		/* Check that the LAN VSI has VEB owning flag set */
10396 		ctl_vsi = i40e_pf_get_main_vsi(pf);
10397 
10398 		if (WARN_ON(ctl_vsi->veb_idx != veb->idx ||
10399 			    !(ctl_vsi->flags & I40E_VSI_FLAG_VEB_OWNER))) {
10400 			dev_err(&pf->pdev->dev,
10401 				"Invalid control VSI for VEB %d\n", veb->idx);
10402 			return -ENOENT;
10403 		}
10404 
10405 		/* Add the control VSI to switch */
10406 		ret = i40e_add_vsi(ctl_vsi);
10407 		if (ret) {
10408 			dev_err(&pf->pdev->dev,
10409 				"Rebuild of owner VSI for VEB %d failed: %d\n",
10410 				veb->idx, ret);
10411 			return ret;
10412 		}
10413 
10414 		i40e_vsi_reset_stats(ctl_vsi);
10415 	}
10416 
10417 	/* create the VEB in the switch and move the VSI onto the VEB */
10418 	ret = i40e_add_veb(veb, ctl_vsi);
10419 	if (ret)
10420 		return ret;
10421 
10422 	if (veb->uplink_seid) {
10423 		if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags))
10424 			veb->bridge_mode = BRIDGE_MODE_VEB;
10425 		else
10426 			veb->bridge_mode = BRIDGE_MODE_VEPA;
10427 		i40e_config_bridge_mode(veb);
10428 	}
10429 
10430 	/* create the remaining VSIs attached to this VEB */
10431 	i40e_pf_for_each_vsi(pf, v, vsi) {
10432 		if (vsi == ctl_vsi)
10433 			continue;
10434 
10435 		if (vsi->veb_idx == veb->idx) {
10436 			vsi->uplink_seid = veb->seid;
10437 			ret = i40e_add_vsi(vsi);
10438 			if (ret) {
10439 				dev_info(&pf->pdev->dev,
10440 					 "rebuild of vsi_idx %d failed: %d\n",
10441 					 v, ret);
10442 				return ret;
10443 			}
10444 			i40e_vsi_reset_stats(vsi);
10445 		}
10446 	}
10447 
10448 	return ret;
10449 }
10450 
10451 /**
10452  * i40e_get_capabilities - get info about the HW
10453  * @pf: the PF struct
10454  * @list_type: AQ capability to be queried
10455  **/
10456 static int i40e_get_capabilities(struct i40e_pf *pf,
10457 				 enum i40e_admin_queue_opc list_type)
10458 {
10459 	struct libie_aqc_list_caps_elem *cap_buf;
10460 	u16 data_size;
10461 	int buf_len;
10462 	int err;
10463 
10464 	buf_len = 40 * sizeof(struct libie_aqc_list_caps_elem);
10465 	do {
10466 		cap_buf = kzalloc(buf_len, GFP_KERNEL);
10467 		if (!cap_buf)
10468 			return -ENOMEM;
10469 
10470 		/* this loads the data into the hw struct for us */
10471 		err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
10472 						    &data_size, list_type,
10473 						    NULL);
10474 		/* data loaded, buffer no longer needed */
10475 		kfree(cap_buf);
10476 
10477 		if (pf->hw.aq.asq_last_status == LIBIE_AQ_RC_ENOMEM) {
10478 			/* retry with a larger buffer */
10479 			buf_len = data_size;
10480 		} else if (pf->hw.aq.asq_last_status != LIBIE_AQ_RC_OK || err) {
10481 			dev_info(&pf->pdev->dev,
10482 				 "capability discovery failed, err %pe aq_err %s\n",
10483 				 ERR_PTR(err),
10484 				 libie_aq_str(pf->hw.aq.asq_last_status));
10485 			return -ENODEV;
10486 		}
10487 	} while (err);
10488 
10489 	if (pf->hw.debug_mask & I40E_DEBUG_USER) {
10490 		if (list_type == i40e_aqc_opc_list_func_capabilities) {
10491 			dev_info(&pf->pdev->dev,
10492 				 "pf=%d, num_vfs=%d, msix_pf=%d, msix_vf=%d, fd_g=%d, fd_b=%d, pf_max_q=%d num_vsi=%d\n",
10493 				 pf->hw.pf_id, pf->hw.func_caps.num_vfs,
10494 				 pf->hw.func_caps.num_msix_vectors,
10495 				 pf->hw.func_caps.num_msix_vectors_vf,
10496 				 pf->hw.func_caps.fd_filters_guaranteed,
10497 				 pf->hw.func_caps.fd_filters_best_effort,
10498 				 pf->hw.func_caps.num_tx_qp,
10499 				 pf->hw.func_caps.num_vsis);
10500 		} else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
10501 			dev_info(&pf->pdev->dev,
10502 				 "switch_mode=0x%04x, function_valid=0x%08x\n",
10503 				 pf->hw.dev_caps.switch_mode,
10504 				 pf->hw.dev_caps.valid_functions);
10505 			dev_info(&pf->pdev->dev,
10506 				 "SR-IOV=%d, num_vfs for all function=%u\n",
10507 				 pf->hw.dev_caps.sr_iov_1_1,
10508 				 pf->hw.dev_caps.num_vfs);
10509 			dev_info(&pf->pdev->dev,
10510 				 "num_vsis=%u, num_rx:%u, num_tx=%u\n",
10511 				 pf->hw.dev_caps.num_vsis,
10512 				 pf->hw.dev_caps.num_rx_qp,
10513 				 pf->hw.dev_caps.num_tx_qp);
10514 		}
10515 	}
10516 	if (list_type == i40e_aqc_opc_list_func_capabilities) {
10517 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
10518 		       + pf->hw.func_caps.num_vfs)
10519 		if (pf->hw.revision_id == 0 &&
10520 		    pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
10521 			dev_info(&pf->pdev->dev,
10522 				 "got num_vsis %d, setting num_vsis to %d\n",
10523 				 pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
10524 			pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
10525 		}
10526 	}
10527 	return 0;
10528 }
10529 
10530 static int i40e_vsi_clear(struct i40e_vsi *vsi);
10531 
10532 /**
10533  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
10534  * @pf: board private structure
10535  **/
10536 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
10537 {
10538 	struct i40e_vsi *main_vsi, *vsi;
10539 
10540 	/* quick workaround for an NVM issue that leaves a critical register
10541 	 * uninitialized
10542 	 */
10543 	if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
10544 		static const u32 hkey[] = {
10545 			0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
10546 			0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
10547 			0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
10548 			0x95b3a76d};
10549 		int i;
10550 
10551 		for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
10552 			wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
10553 	}
10554 
10555 	if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
10556 		return;
10557 
10558 	/* find existing VSI and see if it needs configuring */
10559 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10560 
10561 	/* create a new VSI if none exists */
10562 	if (!vsi) {
10563 		main_vsi = i40e_pf_get_main_vsi(pf);
10564 		vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR, main_vsi->seid, 0);
10565 		if (!vsi) {
10566 			dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
10567 			clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
10568 			set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
10569 			return;
10570 		}
10571 	}
10572 
10573 	i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
10574 }
10575 
10576 /**
10577  * i40e_fdir_teardown - release the Flow Director resources
10578  * @pf: board private structure
10579  **/
10580 static void i40e_fdir_teardown(struct i40e_pf *pf)
10581 {
10582 	struct i40e_vsi *vsi;
10583 
10584 	i40e_fdir_filter_exit(pf);
10585 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10586 	if (vsi)
10587 		i40e_vsi_release(vsi);
10588 }
10589 
10590 /**
10591  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
10592  * @vsi: PF main vsi
10593  * @seid: seid of main or channel VSIs
10594  *
10595  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
10596  * existed before reset
10597  **/
10598 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
10599 {
10600 	struct i40e_cloud_filter *cfilter;
10601 	struct i40e_pf *pf = vsi->back;
10602 	struct hlist_node *node;
10603 	int ret;
10604 
10605 	/* Add cloud filters back if they exist */
10606 	hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
10607 				  cloud_node) {
10608 		if (cfilter->seid != seid)
10609 			continue;
10610 
10611 		if (cfilter->dst_port)
10612 			ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
10613 								true);
10614 		else
10615 			ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
10616 
10617 		if (ret) {
10618 			dev_dbg(&pf->pdev->dev,
10619 				"Failed to rebuild cloud filter, err %pe aq_err %s\n",
10620 				ERR_PTR(ret),
10621 				libie_aq_str(pf->hw.aq.asq_last_status));
10622 			return ret;
10623 		}
10624 	}
10625 	return 0;
10626 }
10627 
10628 /**
10629  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
10630  * @vsi: PF main vsi
10631  *
10632  * Rebuilds channel VSIs if they existed before reset
10633  **/
10634 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
10635 {
10636 	struct i40e_channel *ch, *ch_tmp;
10637 	int ret;
10638 
10639 	if (list_empty(&vsi->ch_list))
10640 		return 0;
10641 
10642 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
10643 		if (!ch->initialized)
10644 			break;
10645 		/* Proceed with creation of channel (VMDq2) VSI */
10646 		ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
10647 		if (ret) {
10648 			dev_info(&vsi->back->pdev->dev,
10649 				 "failed to rebuild channels using uplink_seid %u\n",
10650 				 vsi->uplink_seid);
10651 			return ret;
10652 		}
10653 		/* Reconfigure TX queues using QTX_CTL register */
10654 		ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
10655 		if (ret) {
10656 			dev_info(&vsi->back->pdev->dev,
10657 				 "failed to configure TX rings for channel %u\n",
10658 				 ch->seid);
10659 			return ret;
10660 		}
10661 		/* update 'next_base_queue' */
10662 		vsi->next_base_queue = vsi->next_base_queue +
10663 							ch->num_queue_pairs;
10664 		if (ch->max_tx_rate) {
10665 			u64 credits = ch->max_tx_rate;
10666 
10667 			if (i40e_set_bw_limit(vsi, ch->seid,
10668 					      ch->max_tx_rate))
10669 				return -EINVAL;
10670 
10671 			do_div(credits, I40E_BW_CREDIT_DIVISOR);
10672 			dev_dbg(&vsi->back->pdev->dev,
10673 				"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10674 				ch->max_tx_rate,
10675 				credits,
10676 				ch->seid);
10677 		}
10678 		ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
10679 		if (ret) {
10680 			dev_dbg(&vsi->back->pdev->dev,
10681 				"Failed to rebuild cloud filters for channel VSI %u\n",
10682 				ch->seid);
10683 			return ret;
10684 		}
10685 	}
10686 	return 0;
10687 }
10688 
10689 /**
10690  * i40e_clean_xps_state - clean xps state for every tx_ring
10691  * @vsi: ptr to the VSI
10692  **/
10693 static void i40e_clean_xps_state(struct i40e_vsi *vsi)
10694 {
10695 	int i;
10696 
10697 	if (vsi->tx_rings)
10698 		for (i = 0; i < vsi->num_queue_pairs; i++)
10699 			if (vsi->tx_rings[i])
10700 				clear_bit(__I40E_TX_XPS_INIT_DONE,
10701 					  vsi->tx_rings[i]->state);
10702 }
10703 
10704 /**
10705  * i40e_prep_for_reset - prep for the core to reset
10706  * @pf: board private structure
10707  *
10708  * Close up the VFs and other things in prep for PF Reset.
10709   **/
10710 static void i40e_prep_for_reset(struct i40e_pf *pf)
10711 {
10712 	struct i40e_hw *hw = &pf->hw;
10713 	struct i40e_vsi *vsi;
10714 	int ret = 0;
10715 	u32 v;
10716 
10717 	clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
10718 	if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
10719 		return;
10720 	if (i40e_check_asq_alive(&pf->hw))
10721 		i40e_vc_notify_reset(pf);
10722 
10723 	dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
10724 
10725 	/* quiesce the VSIs and their queues that are not already DOWN */
10726 	i40e_pf_quiesce_all_vsi(pf);
10727 
10728 	i40e_pf_for_each_vsi(pf, v, vsi) {
10729 		i40e_clean_xps_state(vsi);
10730 		vsi->seid = 0;
10731 	}
10732 
10733 	i40e_shutdown_adminq(&pf->hw);
10734 
10735 	/* call shutdown HMC */
10736 	if (hw->hmc.hmc_obj) {
10737 		ret = i40e_shutdown_lan_hmc(hw);
10738 		if (ret)
10739 			dev_warn(&pf->pdev->dev,
10740 				 "shutdown_lan_hmc failed: %d\n", ret);
10741 	}
10742 
10743 	/* Save the current PTP time so that we can restore the time after the
10744 	 * reset completes.
10745 	 */
10746 	i40e_ptp_save_hw_time(pf);
10747 }
10748 
10749 /**
10750  * i40e_send_version - update firmware with driver version
10751  * @pf: PF struct
10752  */
10753 static void i40e_send_version(struct i40e_pf *pf)
10754 {
10755 	struct i40e_driver_version dv;
10756 
10757 	dv.major_version = 0xff;
10758 	dv.minor_version = 0xff;
10759 	dv.build_version = 0xff;
10760 	dv.subbuild_version = 0;
10761 	strscpy(dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string));
10762 	i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
10763 }
10764 
10765 /**
10766  * i40e_get_oem_version - get OEM specific version information
10767  * @hw: pointer to the hardware structure
10768  **/
10769 static void i40e_get_oem_version(struct i40e_hw *hw)
10770 {
10771 	u16 block_offset = 0xffff;
10772 	u16 block_length = 0;
10773 	u16 capabilities = 0;
10774 	u16 gen_snap = 0;
10775 	u16 release = 0;
10776 
10777 #define I40E_SR_NVM_OEM_VERSION_PTR		0x1B
10778 #define I40E_NVM_OEM_LENGTH_OFFSET		0x00
10779 #define I40E_NVM_OEM_CAPABILITIES_OFFSET	0x01
10780 #define I40E_NVM_OEM_GEN_OFFSET			0x02
10781 #define I40E_NVM_OEM_RELEASE_OFFSET		0x03
10782 #define I40E_NVM_OEM_CAPABILITIES_MASK		0x000F
10783 #define I40E_NVM_OEM_LENGTH			3
10784 
10785 	/* Check if pointer to OEM version block is valid. */
10786 	i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
10787 	if (block_offset == 0xffff)
10788 		return;
10789 
10790 	/* Check if OEM version block has correct length. */
10791 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
10792 			   &block_length);
10793 	if (block_length < I40E_NVM_OEM_LENGTH)
10794 		return;
10795 
10796 	/* Check if OEM version format is as expected. */
10797 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
10798 			   &capabilities);
10799 	if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
10800 		return;
10801 
10802 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
10803 			   &gen_snap);
10804 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
10805 			   &release);
10806 	hw->nvm.oem_ver =
10807 		FIELD_PREP(I40E_OEM_GEN_MASK | I40E_OEM_SNAP_MASK, gen_snap) |
10808 		FIELD_PREP(I40E_OEM_RELEASE_MASK, release);
10809 	hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
10810 }
10811 
10812 /**
10813  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
10814  * @pf: board private structure
10815  **/
10816 static int i40e_reset(struct i40e_pf *pf)
10817 {
10818 	struct i40e_hw *hw = &pf->hw;
10819 	int ret;
10820 
10821 	ret = i40e_pf_reset(hw);
10822 	if (ret) {
10823 		dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
10824 		set_bit(__I40E_RESET_FAILED, pf->state);
10825 		clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10826 	} else {
10827 		pf->pfr_count++;
10828 	}
10829 	return ret;
10830 }
10831 
10832 /**
10833  * i40e_rebuild - rebuild using a saved config
10834  * @pf: board private structure
10835  * @reinit: if the Main VSI needs to re-initialized.
10836  * @lock_acquired: indicates whether or not the lock has been acquired
10837  * before this function was called.
10838  **/
10839 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
10840 {
10841 	const bool is_recovery_mode_reported = i40e_check_recovery_mode(pf);
10842 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
10843 	struct i40e_hw *hw = &pf->hw;
10844 	struct i40e_veb *veb;
10845 	int ret;
10846 	u32 val;
10847 	int v;
10848 
10849 	if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10850 	    is_recovery_mode_reported)
10851 		i40e_set_ethtool_ops(vsi->netdev);
10852 
10853 	if (test_bit(__I40E_DOWN, pf->state) &&
10854 	    !test_bit(__I40E_RECOVERY_MODE, pf->state))
10855 		goto clear_recovery;
10856 	dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
10857 
10858 	/* rebuild the basics for the AdminQ, HMC, and initial HW switch */
10859 	ret = i40e_init_adminq(&pf->hw);
10860 	if (ret) {
10861 		dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %pe aq_err %s\n",
10862 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
10863 		goto clear_recovery;
10864 	}
10865 	i40e_get_oem_version(&pf->hw);
10866 
10867 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state)) {
10868 		/* The following delay is necessary for firmware update. */
10869 		mdelay(1000);
10870 	}
10871 
10872 	/* re-verify the eeprom if we just had an EMP reset */
10873 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
10874 		i40e_verify_eeprom(pf);
10875 
10876 	/* if we are going out of or into recovery mode we have to act
10877 	 * accordingly with regard to resources initialization
10878 	 * and deinitialization
10879 	 */
10880 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10881 		if (i40e_get_capabilities(pf,
10882 					  i40e_aqc_opc_list_func_capabilities))
10883 			goto end_unlock;
10884 
10885 		if (is_recovery_mode_reported) {
10886 			/* we're staying in recovery mode so we'll reinitialize
10887 			 * misc vector here
10888 			 */
10889 			if (i40e_setup_misc_vector_for_recovery_mode(pf))
10890 				goto end_unlock;
10891 		} else {
10892 			if (!lock_acquired)
10893 				rtnl_lock();
10894 			/* we're going out of recovery mode so we'll free
10895 			 * the IRQ allocated specifically for recovery mode
10896 			 * and restore the interrupt scheme
10897 			 */
10898 			free_irq(pf->pdev->irq, pf);
10899 			i40e_clear_interrupt_scheme(pf);
10900 			if (i40e_restore_interrupt_scheme(pf))
10901 				goto end_unlock;
10902 		}
10903 
10904 		/* tell the firmware that we're starting */
10905 		i40e_send_version(pf);
10906 
10907 		/* bail out in case recovery mode was detected, as there is
10908 		 * no need for further configuration.
10909 		 */
10910 		goto end_unlock;
10911 	}
10912 
10913 	i40e_clear_pxe_mode(hw);
10914 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10915 	if (ret)
10916 		goto end_core_reset;
10917 
10918 	ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10919 				hw->func_caps.num_rx_qp, 0, 0);
10920 	if (ret) {
10921 		dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10922 		goto end_core_reset;
10923 	}
10924 	ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10925 	if (ret) {
10926 		dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10927 		goto end_core_reset;
10928 	}
10929 
10930 #ifdef CONFIG_I40E_DCB
10931 	/* Enable FW to write a default DCB config on link-up
10932 	 * unless I40E_FLAG_TC_MQPRIO was enabled or DCB
10933 	 * is not supported with new link speed
10934 	 */
10935 	if (i40e_is_tc_mqprio_enabled(pf)) {
10936 		i40e_aq_set_dcb_parameters(hw, false, NULL);
10937 	} else {
10938 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
10939 		    (hw->phy.link_info.link_speed &
10940 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
10941 			i40e_aq_set_dcb_parameters(hw, false, NULL);
10942 			dev_warn(&pf->pdev->dev,
10943 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
10944 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
10945 		} else {
10946 			i40e_aq_set_dcb_parameters(hw, true, NULL);
10947 			ret = i40e_init_pf_dcb(pf);
10948 			if (ret) {
10949 				dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n",
10950 					 ret);
10951 				clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
10952 				/* Continue without DCB enabled */
10953 			}
10954 		}
10955 	}
10956 
10957 #endif /* CONFIG_I40E_DCB */
10958 	if (!lock_acquired)
10959 		rtnl_lock();
10960 	ret = i40e_setup_pf_switch(pf, reinit, true);
10961 	if (ret)
10962 		goto end_unlock;
10963 
10964 	/* The driver only wants link up/down and module qualification
10965 	 * reports from firmware.  Note the negative logic.
10966 	 */
10967 	ret = i40e_aq_set_phy_int_mask(&pf->hw,
10968 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
10969 					 I40E_AQ_EVENT_MEDIA_NA |
10970 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10971 	if (ret)
10972 		dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
10973 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
10974 
10975 	/* Rebuild the VSIs and VEBs that existed before reset.
10976 	 * They are still in our local switch element arrays, so only
10977 	 * need to rebuild the switch model in the HW.
10978 	 *
10979 	 * If there were VEBs but the reconstitution failed, we'll try
10980 	 * to recover minimal use by getting the basic PF VSI working.
10981 	 */
10982 	if (vsi->uplink_seid != pf->mac_seid) {
10983 		dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
10984 
10985 		/* Rebuild VEBs */
10986 		i40e_pf_for_each_veb(pf, v, veb) {
10987 			ret = i40e_reconstitute_veb(veb);
10988 			if (!ret)
10989 				continue;
10990 
10991 			/* If Main VEB failed, we're in deep doodoo,
10992 			 * so give up rebuilding the switch and set up
10993 			 * for minimal rebuild of PF VSI.
10994 			 * If orphan failed, we'll report the error
10995 			 * but try to keep going.
10996 			 */
10997 			if (veb->uplink_seid == pf->mac_seid) {
10998 				dev_info(&pf->pdev->dev,
10999 					 "rebuild of switch failed: %d, will try to set up simple PF connection\n",
11000 					 ret);
11001 				vsi->uplink_seid = pf->mac_seid;
11002 				break;
11003 			} else if (veb->uplink_seid == 0) {
11004 				dev_info(&pf->pdev->dev,
11005 					 "rebuild of orphan VEB failed: %d\n",
11006 					 ret);
11007 			}
11008 		}
11009 	}
11010 
11011 	if (vsi->uplink_seid == pf->mac_seid) {
11012 		dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
11013 		/* no VEB, so rebuild only the Main VSI */
11014 		ret = i40e_add_vsi(vsi);
11015 		if (ret) {
11016 			dev_info(&pf->pdev->dev,
11017 				 "rebuild of Main VSI failed: %d\n", ret);
11018 			goto end_unlock;
11019 		}
11020 	}
11021 
11022 	if (vsi->mqprio_qopt.max_rate[0]) {
11023 		u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
11024 						  vsi->mqprio_qopt.max_rate[0]);
11025 		u64 credits = 0;
11026 
11027 		ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
11028 		if (ret)
11029 			goto end_unlock;
11030 
11031 		credits = max_tx_rate;
11032 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
11033 		dev_dbg(&vsi->back->pdev->dev,
11034 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
11035 			max_tx_rate,
11036 			credits,
11037 			vsi->seid);
11038 	}
11039 
11040 	ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
11041 	if (ret)
11042 		goto end_unlock;
11043 
11044 	/* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
11045 	 * for this main VSI if they exist
11046 	 */
11047 	ret = i40e_rebuild_channels(vsi);
11048 	if (ret)
11049 		goto end_unlock;
11050 
11051 	/* Reconfigure hardware for allowing smaller MSS in the case
11052 	 * of TSO, so that we avoid the MDD being fired and causing
11053 	 * a reset in the case of small MSS+TSO.
11054 	 */
11055 #define I40E_REG_MSS          0x000E64DC
11056 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
11057 #define I40E_64BYTE_MSS       0x400000
11058 	val = rd32(hw, I40E_REG_MSS);
11059 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
11060 		val &= ~I40E_REG_MSS_MIN_MASK;
11061 		val |= I40E_64BYTE_MSS;
11062 		wr32(hw, I40E_REG_MSS, val);
11063 	}
11064 
11065 	if (test_bit(I40E_HW_CAP_RESTART_AUTONEG, pf->hw.caps)) {
11066 		msleep(75);
11067 		ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
11068 		if (ret)
11069 			dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
11070 				 ERR_PTR(ret),
11071 				 libie_aq_str(pf->hw.aq.asq_last_status));
11072 	}
11073 	/* reinit the misc interrupt */
11074 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
11075 		ret = i40e_setup_misc_vector(pf);
11076 		if (ret)
11077 			goto end_unlock;
11078 	}
11079 
11080 	/* Add a filter to drop all Flow control frames from any VSI from being
11081 	 * transmitted. By doing so we stop a malicious VF from sending out
11082 	 * PAUSE or PFC frames and potentially controlling traffic for other
11083 	 * PF/VF VSIs.
11084 	 * The FW can still send Flow control frames if enabled.
11085 	 */
11086 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
11087 						       pf->main_vsi_seid);
11088 
11089 	/* restart the VSIs that were rebuilt and running before the reset */
11090 	i40e_pf_unquiesce_all_vsi(pf);
11091 
11092 	/* Release the RTNL lock before we start resetting VFs */
11093 	if (!lock_acquired)
11094 		rtnl_unlock();
11095 
11096 	/* Restore promiscuous settings */
11097 	ret = i40e_set_promiscuous(pf, pf->cur_promisc);
11098 	if (ret)
11099 		dev_warn(&pf->pdev->dev,
11100 			 "Failed to restore promiscuous setting: %s, err %pe aq_err %s\n",
11101 			 pf->cur_promisc ? "on" : "off",
11102 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
11103 
11104 	i40e_reset_all_vfs(pf, true);
11105 
11106 	/* tell the firmware that we're starting */
11107 	i40e_send_version(pf);
11108 
11109 	/* We've already released the lock, so don't do it again */
11110 	goto end_core_reset;
11111 
11112 end_unlock:
11113 	if (!lock_acquired)
11114 		rtnl_unlock();
11115 end_core_reset:
11116 	clear_bit(__I40E_RESET_FAILED, pf->state);
11117 clear_recovery:
11118 	clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
11119 	clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
11120 }
11121 
11122 /**
11123  * i40e_reset_and_rebuild - reset and rebuild using a saved config
11124  * @pf: board private structure
11125  * @reinit: if the Main VSI needs to re-initialized.
11126  * @lock_acquired: indicates whether or not the lock has been acquired
11127  * before this function was called.
11128  **/
11129 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
11130 				   bool lock_acquired)
11131 {
11132 	int ret;
11133 
11134 	if (test_bit(__I40E_IN_REMOVE, pf->state))
11135 		return;
11136 	/* Now we wait for GRST to settle out.
11137 	 * We don't have to delete the VEBs or VSIs from the hw switch
11138 	 * because the reset will make them disappear.
11139 	 */
11140 	ret = i40e_reset(pf);
11141 	if (!ret)
11142 		i40e_rebuild(pf, reinit, lock_acquired);
11143 	else
11144 		dev_err(&pf->pdev->dev, "%s: i40e_reset() FAILED", __func__);
11145 }
11146 
11147 /**
11148  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
11149  * @pf: board private structure
11150  *
11151  * Close up the VFs and other things in prep for a Core Reset,
11152  * then get ready to rebuild the world.
11153  * @lock_acquired: indicates whether or not the lock has been acquired
11154  * before this function was called.
11155  **/
11156 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
11157 {
11158 	i40e_prep_for_reset(pf);
11159 	i40e_reset_and_rebuild(pf, false, lock_acquired);
11160 }
11161 
11162 /**
11163  * i40e_print_vf_mdd_event - print VF Tx/Rx malicious driver detect event
11164  * @pf: board private structure
11165  * @vf: pointer to the VF structure
11166  * @is_tx: true - for Tx event, false - for  Rx
11167  */
11168 static void i40e_print_vf_mdd_event(struct i40e_pf *pf, struct i40e_vf *vf,
11169 				    bool is_tx)
11170 {
11171 	dev_err(&pf->pdev->dev, is_tx ?
11172 		"%lld Tx Malicious Driver Detection events detected on PF %d VF %d MAC %pm. mdd-auto-reset-vfs=%s\n" :
11173 		"%lld Rx Malicious Driver Detection events detected on PF %d VF %d MAC %pm. mdd-auto-reset-vfs=%s\n",
11174 		is_tx ? vf->mdd_tx_events.count : vf->mdd_rx_events.count,
11175 		pf->hw.pf_id,
11176 		vf->vf_id,
11177 		vf->default_lan_addr.addr,
11178 		str_on_off(test_bit(I40E_FLAG_MDD_AUTO_RESET_VF, pf->flags)));
11179 }
11180 
11181 /**
11182  * i40e_print_vfs_mdd_events - print VFs malicious driver detect event
11183  * @pf: pointer to the PF structure
11184  *
11185  * Called from i40e_handle_mdd_event to rate limit and print VFs MDD events.
11186  */
11187 static void i40e_print_vfs_mdd_events(struct i40e_pf *pf)
11188 {
11189 	unsigned int i;
11190 
11191 	/* check that there are pending MDD events to print */
11192 	if (!test_and_clear_bit(__I40E_MDD_VF_PRINT_PENDING, pf->state))
11193 		return;
11194 
11195 	if (!__ratelimit(&pf->mdd_message_rate_limit))
11196 		return;
11197 
11198 	for (i = 0; i < pf->num_alloc_vfs; i++) {
11199 		struct i40e_vf *vf = &pf->vf[i];
11200 		bool is_printed = false;
11201 
11202 		/* only print Rx MDD event message if there are new events */
11203 		if (vf->mdd_rx_events.count != vf->mdd_rx_events.last_printed) {
11204 			vf->mdd_rx_events.last_printed = vf->mdd_rx_events.count;
11205 			i40e_print_vf_mdd_event(pf, vf, false);
11206 			is_printed = true;
11207 		}
11208 
11209 		/* only print Tx MDD event message if there are new events */
11210 		if (vf->mdd_tx_events.count != vf->mdd_tx_events.last_printed) {
11211 			vf->mdd_tx_events.last_printed = vf->mdd_tx_events.count;
11212 			i40e_print_vf_mdd_event(pf, vf, true);
11213 			is_printed = true;
11214 		}
11215 
11216 		if (is_printed && !test_bit(I40E_FLAG_MDD_AUTO_RESET_VF, pf->flags))
11217 			dev_info(&pf->pdev->dev,
11218 				 "Use PF Control I/F to re-enable the VF #%d\n",
11219 				 i);
11220 	}
11221 }
11222 
11223 /**
11224  * i40e_handle_mdd_event
11225  * @pf: pointer to the PF structure
11226  *
11227  * Called from the MDD irq handler to identify possibly malicious vfs
11228  **/
11229 static void i40e_handle_mdd_event(struct i40e_pf *pf)
11230 {
11231 	struct i40e_hw *hw = &pf->hw;
11232 	bool mdd_detected = false;
11233 	struct i40e_vf *vf;
11234 	u32 reg;
11235 	int i;
11236 
11237 	if (!test_and_clear_bit(__I40E_MDD_EVENT_PENDING, pf->state)) {
11238 		/* Since the VF MDD event logging is rate limited, check if
11239 		 * there are pending MDD events.
11240 		 */
11241 		i40e_print_vfs_mdd_events(pf);
11242 		return;
11243 	}
11244 
11245 	/* find what triggered the MDD event */
11246 	reg = rd32(hw, I40E_GL_MDET_TX);
11247 	if (reg & I40E_GL_MDET_TX_VALID_MASK) {
11248 		u8 pf_num = FIELD_GET(I40E_GL_MDET_TX_PF_NUM_MASK, reg);
11249 		u16 vf_num = FIELD_GET(I40E_GL_MDET_TX_VF_NUM_MASK, reg);
11250 		u8 event = FIELD_GET(I40E_GL_MDET_TX_EVENT_MASK, reg);
11251 		u16 queue = FIELD_GET(I40E_GL_MDET_TX_QUEUE_MASK, reg) -
11252 				pf->hw.func_caps.base_queue;
11253 		if (netif_msg_tx_err(pf))
11254 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
11255 				 event, queue, pf_num, vf_num);
11256 		wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
11257 		mdd_detected = true;
11258 	}
11259 	reg = rd32(hw, I40E_GL_MDET_RX);
11260 	if (reg & I40E_GL_MDET_RX_VALID_MASK) {
11261 		u8 func = FIELD_GET(I40E_GL_MDET_RX_FUNCTION_MASK, reg);
11262 		u8 event = FIELD_GET(I40E_GL_MDET_RX_EVENT_MASK, reg);
11263 		u16 queue = FIELD_GET(I40E_GL_MDET_RX_QUEUE_MASK, reg) -
11264 				pf->hw.func_caps.base_queue;
11265 		if (netif_msg_rx_err(pf))
11266 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
11267 				 event, queue, func);
11268 		wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
11269 		mdd_detected = true;
11270 	}
11271 
11272 	if (mdd_detected) {
11273 		reg = rd32(hw, I40E_PF_MDET_TX);
11274 		if (reg & I40E_PF_MDET_TX_VALID_MASK) {
11275 			wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
11276 			dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
11277 		}
11278 		reg = rd32(hw, I40E_PF_MDET_RX);
11279 		if (reg & I40E_PF_MDET_RX_VALID_MASK) {
11280 			wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
11281 			dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
11282 		}
11283 	}
11284 
11285 	/* see if one of the VFs needs its hand slapped */
11286 	for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
11287 		bool is_mdd_on_tx = false;
11288 		bool is_mdd_on_rx = false;
11289 
11290 		vf = &(pf->vf[i]);
11291 		reg = rd32(hw, I40E_VP_MDET_TX(i));
11292 		if (reg & I40E_VP_MDET_TX_VALID_MASK) {
11293 			set_bit(__I40E_MDD_VF_PRINT_PENDING, pf->state);
11294 			wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
11295 			vf->mdd_tx_events.count++;
11296 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11297 			is_mdd_on_tx = true;
11298 		}
11299 
11300 		reg = rd32(hw, I40E_VP_MDET_RX(i));
11301 		if (reg & I40E_VP_MDET_RX_VALID_MASK) {
11302 			set_bit(__I40E_MDD_VF_PRINT_PENDING, pf->state);
11303 			wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
11304 			vf->mdd_rx_events.count++;
11305 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11306 			is_mdd_on_rx = true;
11307 		}
11308 
11309 		if ((is_mdd_on_tx || is_mdd_on_rx) &&
11310 		    test_bit(I40E_FLAG_MDD_AUTO_RESET_VF, pf->flags)) {
11311 			/* VF MDD event counters will be cleared by
11312 			 * reset, so print the event prior to reset.
11313 			 */
11314 			if (is_mdd_on_rx)
11315 				i40e_print_vf_mdd_event(pf, vf, false);
11316 			if (is_mdd_on_tx)
11317 				i40e_print_vf_mdd_event(pf, vf, true);
11318 
11319 			i40e_vc_reset_vf(vf, true);
11320 		}
11321 	}
11322 
11323 	reg = rd32(hw, I40E_PFINT_ICR0_ENA);
11324 	reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
11325 	wr32(hw, I40E_PFINT_ICR0_ENA, reg);
11326 	i40e_flush(hw);
11327 
11328 	i40e_print_vfs_mdd_events(pf);
11329 }
11330 
11331 /**
11332  * i40e_service_task - Run the driver's async subtasks
11333  * @work: pointer to work_struct containing our data
11334  **/
11335 static void i40e_service_task(struct work_struct *work)
11336 {
11337 	struct i40e_pf *pf = container_of(work,
11338 					  struct i40e_pf,
11339 					  service_task);
11340 	unsigned long start_time = jiffies;
11341 
11342 	/* don't bother with service tasks if a reset is in progress */
11343 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
11344 	    test_bit(__I40E_SUSPENDED, pf->state))
11345 		return;
11346 
11347 	if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
11348 		return;
11349 
11350 	if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
11351 		i40e_detect_recover_hung(pf);
11352 		i40e_sync_filters_subtask(pf);
11353 		i40e_reset_subtask(pf);
11354 		i40e_handle_mdd_event(pf);
11355 		i40e_vc_process_vflr_event(pf);
11356 		i40e_watchdog_subtask(pf);
11357 		i40e_fdir_reinit_subtask(pf);
11358 		if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
11359 			/* Client subtask will reopen next time through. */
11360 			i40e_notify_client_of_netdev_close(pf, true);
11361 		} else {
11362 			i40e_client_subtask(pf);
11363 			if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
11364 					       pf->state))
11365 				i40e_notify_client_of_l2_param_changes(pf);
11366 		}
11367 		i40e_sync_filters_subtask(pf);
11368 	} else {
11369 		i40e_reset_subtask(pf);
11370 	}
11371 
11372 	i40e_clean_adminq_subtask(pf);
11373 
11374 	/* flush memory to make sure state is correct before next watchdog */
11375 	smp_mb__before_atomic();
11376 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
11377 
11378 	/* If the tasks have taken longer than one timer cycle or there
11379 	 * is more work to be done, reschedule the service task now
11380 	 * rather than wait for the timer to tick again.
11381 	 */
11382 	if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
11383 	    test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)		 ||
11384 	    test_bit(__I40E_MDD_EVENT_PENDING, pf->state)		 ||
11385 	    test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
11386 		i40e_service_event_schedule(pf);
11387 }
11388 
11389 /**
11390  * i40e_service_timer - timer callback
11391  * @t: timer list pointer
11392  **/
11393 static void i40e_service_timer(struct timer_list *t)
11394 {
11395 	struct i40e_pf *pf = timer_container_of(pf, t, service_timer);
11396 
11397 	mod_timer(&pf->service_timer,
11398 		  round_jiffies(jiffies + pf->service_timer_period));
11399 	i40e_service_event_schedule(pf);
11400 }
11401 
11402 /**
11403  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
11404  * @vsi: the VSI being configured
11405  **/
11406 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
11407 {
11408 	struct i40e_pf *pf = vsi->back;
11409 
11410 	switch (vsi->type) {
11411 	case I40E_VSI_MAIN:
11412 		vsi->alloc_queue_pairs = pf->num_lan_qps;
11413 		if (!vsi->num_tx_desc)
11414 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11415 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11416 		if (!vsi->num_rx_desc)
11417 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11418 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11419 		if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
11420 			vsi->num_q_vectors = pf->num_lan_msix;
11421 		else
11422 			vsi->num_q_vectors = 1;
11423 
11424 		break;
11425 
11426 	case I40E_VSI_FDIR:
11427 		vsi->alloc_queue_pairs = 1;
11428 		vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11429 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11430 		vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11431 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11432 		vsi->num_q_vectors = pf->num_fdsb_msix;
11433 		break;
11434 
11435 	case I40E_VSI_VMDQ2:
11436 		vsi->alloc_queue_pairs = pf->num_vmdq_qps;
11437 		if (!vsi->num_tx_desc)
11438 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11439 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11440 		if (!vsi->num_rx_desc)
11441 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11442 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11443 		vsi->num_q_vectors = pf->num_vmdq_msix;
11444 		break;
11445 
11446 	case I40E_VSI_SRIOV:
11447 		vsi->alloc_queue_pairs = pf->num_vf_qps;
11448 		if (!vsi->num_tx_desc)
11449 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11450 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11451 		if (!vsi->num_rx_desc)
11452 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11453 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11454 		break;
11455 
11456 	default:
11457 		WARN_ON(1);
11458 		return -ENODATA;
11459 	}
11460 
11461 	if (is_kdump_kernel()) {
11462 		vsi->num_tx_desc = I40E_MIN_NUM_DESCRIPTORS;
11463 		vsi->num_rx_desc = I40E_MIN_NUM_DESCRIPTORS;
11464 	}
11465 
11466 	return 0;
11467 }
11468 
11469 /**
11470  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
11471  * @vsi: VSI pointer
11472  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
11473  *
11474  * On error: returns error code (negative)
11475  * On success: returns 0
11476  **/
11477 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
11478 {
11479 	struct i40e_ring **next_rings;
11480 	int size;
11481 	int ret = 0;
11482 
11483 	/* allocate memory for both Tx, XDP Tx and Rx ring pointers */
11484 	size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
11485 	       (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
11486 	vsi->tx_rings = kzalloc(size, GFP_KERNEL);
11487 	if (!vsi->tx_rings)
11488 		return -ENOMEM;
11489 	next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
11490 	if (i40e_enabled_xdp_vsi(vsi)) {
11491 		vsi->xdp_rings = next_rings;
11492 		next_rings += vsi->alloc_queue_pairs;
11493 	}
11494 	vsi->rx_rings = next_rings;
11495 
11496 	if (alloc_qvectors) {
11497 		/* allocate memory for q_vector pointers */
11498 		size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
11499 		vsi->q_vectors = kzalloc(size, GFP_KERNEL);
11500 		if (!vsi->q_vectors) {
11501 			ret = -ENOMEM;
11502 			goto err_vectors;
11503 		}
11504 	}
11505 	return ret;
11506 
11507 err_vectors:
11508 	kfree(vsi->tx_rings);
11509 	return ret;
11510 }
11511 
11512 /**
11513  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
11514  * @pf: board private structure
11515  * @type: type of VSI
11516  *
11517  * On error: returns error code (negative)
11518  * On success: returns vsi index in PF (positive)
11519  **/
11520 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
11521 {
11522 	int ret = -ENODEV;
11523 	struct i40e_vsi *vsi;
11524 	int vsi_idx;
11525 	int i;
11526 
11527 	/* Need to protect the allocation of the VSIs at the PF level */
11528 	mutex_lock(&pf->switch_mutex);
11529 
11530 	/* VSI list may be fragmented if VSI creation/destruction has
11531 	 * been happening.  We can afford to do a quick scan to look
11532 	 * for any free VSIs in the list.
11533 	 *
11534 	 * find next empty vsi slot, looping back around if necessary
11535 	 */
11536 	i = pf->next_vsi;
11537 	while (i < pf->num_alloc_vsi && pf->vsi[i])
11538 		i++;
11539 	if (i >= pf->num_alloc_vsi) {
11540 		i = 0;
11541 		while (i < pf->next_vsi && pf->vsi[i])
11542 			i++;
11543 	}
11544 
11545 	if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
11546 		vsi_idx = i;             /* Found one! */
11547 	} else {
11548 		ret = -ENODEV;
11549 		goto unlock_pf;  /* out of VSI slots! */
11550 	}
11551 	pf->next_vsi = ++i;
11552 
11553 	vsi = kzalloc_obj(*vsi);
11554 	if (!vsi) {
11555 		ret = -ENOMEM;
11556 		goto unlock_pf;
11557 	}
11558 	vsi->type = type;
11559 	vsi->back = pf;
11560 	set_bit(__I40E_VSI_DOWN, vsi->state);
11561 	vsi->flags = 0;
11562 	vsi->idx = vsi_idx;
11563 	vsi->int_rate_limit = 0;
11564 	vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
11565 				pf->rss_table_size : 64;
11566 	vsi->netdev_registered = false;
11567 	vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
11568 	hash_init(vsi->mac_filter_hash);
11569 	vsi->irqs_ready = false;
11570 
11571 	if (type == I40E_VSI_MAIN) {
11572 		vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
11573 		if (!vsi->af_xdp_zc_qps)
11574 			goto err_rings;
11575 	}
11576 
11577 	ret = i40e_set_num_rings_in_vsi(vsi);
11578 	if (ret)
11579 		goto err_rings;
11580 
11581 	ret = i40e_vsi_alloc_arrays(vsi, true);
11582 	if (ret)
11583 		goto err_rings;
11584 
11585 	/* Setup default MSIX irq handler for VSI */
11586 	i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
11587 
11588 	/* Initialize VSI lock */
11589 	spin_lock_init(&vsi->mac_filter_hash_lock);
11590 	pf->vsi[vsi_idx] = vsi;
11591 	ret = vsi_idx;
11592 	goto unlock_pf;
11593 
11594 err_rings:
11595 	bitmap_free(vsi->af_xdp_zc_qps);
11596 	pf->next_vsi = i - 1;
11597 	kfree(vsi);
11598 unlock_pf:
11599 	mutex_unlock(&pf->switch_mutex);
11600 	return ret;
11601 }
11602 
11603 /**
11604  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
11605  * @vsi: VSI pointer
11606  * @free_qvectors: a bool to specify if q_vectors need to be freed.
11607  *
11608  * On error: returns error code (negative)
11609  * On success: returns 0
11610  **/
11611 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
11612 {
11613 	/* free the ring and vector containers */
11614 	if (free_qvectors) {
11615 		kfree(vsi->q_vectors);
11616 		vsi->q_vectors = NULL;
11617 	}
11618 	kfree(vsi->tx_rings);
11619 	vsi->tx_rings = NULL;
11620 	vsi->rx_rings = NULL;
11621 	vsi->xdp_rings = NULL;
11622 }
11623 
11624 /**
11625  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
11626  * and lookup table
11627  * @vsi: Pointer to VSI structure
11628  */
11629 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
11630 {
11631 	if (!vsi)
11632 		return;
11633 
11634 	kfree(vsi->rss_hkey_user);
11635 	vsi->rss_hkey_user = NULL;
11636 
11637 	kfree(vsi->rss_lut_user);
11638 	vsi->rss_lut_user = NULL;
11639 }
11640 
11641 /**
11642  * i40e_vsi_clear - Deallocate the VSI provided
11643  * @vsi: the VSI being un-configured
11644  **/
11645 static int i40e_vsi_clear(struct i40e_vsi *vsi)
11646 {
11647 	struct i40e_pf *pf;
11648 
11649 	if (!vsi)
11650 		return 0;
11651 
11652 	if (!vsi->back)
11653 		goto free_vsi;
11654 	pf = vsi->back;
11655 
11656 	mutex_lock(&pf->switch_mutex);
11657 	if (!pf->vsi[vsi->idx]) {
11658 		dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
11659 			vsi->idx, vsi->idx, vsi->type);
11660 		goto unlock_vsi;
11661 	}
11662 
11663 	if (pf->vsi[vsi->idx] != vsi) {
11664 		dev_err(&pf->pdev->dev,
11665 			"pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
11666 			pf->vsi[vsi->idx]->idx,
11667 			pf->vsi[vsi->idx]->type,
11668 			vsi->idx, vsi->type);
11669 		goto unlock_vsi;
11670 	}
11671 
11672 	/* updates the PF for this cleared vsi */
11673 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
11674 	i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
11675 
11676 	bitmap_free(vsi->af_xdp_zc_qps);
11677 	i40e_vsi_free_arrays(vsi, true);
11678 	i40e_clear_rss_config_user(vsi);
11679 
11680 	pf->vsi[vsi->idx] = NULL;
11681 	if (vsi->idx < pf->next_vsi)
11682 		pf->next_vsi = vsi->idx;
11683 
11684 unlock_vsi:
11685 	mutex_unlock(&pf->switch_mutex);
11686 free_vsi:
11687 	kfree(vsi);
11688 
11689 	return 0;
11690 }
11691 
11692 /**
11693  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
11694  * @vsi: the VSI being cleaned
11695  **/
11696 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
11697 {
11698 	int i;
11699 
11700 	if (vsi->tx_rings && vsi->tx_rings[0]) {
11701 		for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11702 			kfree_rcu(vsi->tx_rings[i], rcu);
11703 			WRITE_ONCE(vsi->tx_rings[i], NULL);
11704 			WRITE_ONCE(vsi->rx_rings[i], NULL);
11705 			if (vsi->xdp_rings)
11706 				WRITE_ONCE(vsi->xdp_rings[i], NULL);
11707 		}
11708 	}
11709 }
11710 
11711 /**
11712  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
11713  * @vsi: the VSI being configured
11714  **/
11715 static int i40e_alloc_rings(struct i40e_vsi *vsi)
11716 {
11717 	int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
11718 	struct i40e_pf *pf = vsi->back;
11719 	struct i40e_ring *ring;
11720 
11721 	/* Set basic values in the rings to be used later during open() */
11722 	for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11723 		/* allocate space for both Tx and Rx in one shot */
11724 		ring = kzalloc_objs(struct i40e_ring, qpv);
11725 		if (!ring)
11726 			goto err_out;
11727 
11728 		ring->queue_index = i;
11729 		ring->reg_idx = vsi->base_queue + i;
11730 		ring->ring_active = false;
11731 		ring->vsi = vsi;
11732 		ring->netdev = vsi->netdev;
11733 		ring->dev = &pf->pdev->dev;
11734 		ring->count = vsi->num_tx_desc;
11735 		ring->size = 0;
11736 		ring->dcb_tc = 0;
11737 		if (test_bit(I40E_HW_CAP_WB_ON_ITR, vsi->back->hw.caps))
11738 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11739 		ring->itr_setting = pf->tx_itr_default;
11740 		WRITE_ONCE(vsi->tx_rings[i], ring++);
11741 
11742 		if (!i40e_enabled_xdp_vsi(vsi))
11743 			goto setup_rx;
11744 
11745 		ring->queue_index = vsi->alloc_queue_pairs + i;
11746 		ring->reg_idx = vsi->base_queue + ring->queue_index;
11747 		ring->ring_active = false;
11748 		ring->vsi = vsi;
11749 		ring->netdev = NULL;
11750 		ring->dev = &pf->pdev->dev;
11751 		ring->count = vsi->num_tx_desc;
11752 		ring->size = 0;
11753 		ring->dcb_tc = 0;
11754 		if (test_bit(I40E_HW_CAP_WB_ON_ITR, vsi->back->hw.caps))
11755 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11756 		set_ring_xdp(ring);
11757 		ring->itr_setting = pf->tx_itr_default;
11758 		WRITE_ONCE(vsi->xdp_rings[i], ring++);
11759 
11760 setup_rx:
11761 		ring->queue_index = i;
11762 		ring->reg_idx = vsi->base_queue + i;
11763 		ring->ring_active = false;
11764 		ring->vsi = vsi;
11765 		ring->netdev = vsi->netdev;
11766 		ring->dev = &pf->pdev->dev;
11767 		ring->count = vsi->num_rx_desc;
11768 		ring->size = 0;
11769 		ring->dcb_tc = 0;
11770 		ring->itr_setting = pf->rx_itr_default;
11771 		WRITE_ONCE(vsi->rx_rings[i], ring);
11772 	}
11773 
11774 	return 0;
11775 
11776 err_out:
11777 	i40e_vsi_clear_rings(vsi);
11778 	return -ENOMEM;
11779 }
11780 
11781 /**
11782  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
11783  * @pf: board private structure
11784  * @vectors: the number of MSI-X vectors to request
11785  *
11786  * Returns the number of vectors reserved, or error
11787  **/
11788 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
11789 {
11790 	vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
11791 					I40E_MIN_MSIX, vectors);
11792 	if (vectors < 0) {
11793 		dev_info(&pf->pdev->dev,
11794 			 "MSI-X vector reservation failed: %d\n", vectors);
11795 		vectors = 0;
11796 	}
11797 
11798 	return vectors;
11799 }
11800 
11801 /**
11802  * i40e_init_msix - Setup the MSIX capability
11803  * @pf: board private structure
11804  *
11805  * Work with the OS to set up the MSIX vectors needed.
11806  *
11807  * Returns the number of vectors reserved or negative on failure
11808  **/
11809 static int i40e_init_msix(struct i40e_pf *pf)
11810 {
11811 	struct i40e_hw *hw = &pf->hw;
11812 	int cpus, extra_vectors;
11813 	int vectors_left;
11814 	int v_budget, i;
11815 	int v_actual;
11816 	int iwarp_requested = 0;
11817 
11818 	if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
11819 		return -ENODEV;
11820 
11821 	/* The number of vectors we'll request will be comprised of:
11822 	 *   - Add 1 for "other" cause for Admin Queue events, etc.
11823 	 *   - The number of LAN queue pairs
11824 	 *	- Queues being used for RSS.
11825 	 *		We don't need as many as max_rss_size vectors.
11826 	 *		use rss_size instead in the calculation since that
11827 	 *		is governed by number of cpus in the system.
11828 	 *	- assumes symmetric Tx/Rx pairing
11829 	 *   - The number of VMDq pairs
11830 	 *   - The CPU count within the NUMA node if iWARP is enabled
11831 	 * Once we count this up, try the request.
11832 	 *
11833 	 * If we can't get what we want, we'll simplify to nearly nothing
11834 	 * and try again.  If that still fails, we punt.
11835 	 */
11836 	vectors_left = hw->func_caps.num_msix_vectors;
11837 	v_budget = 0;
11838 
11839 	/* reserve one vector for miscellaneous handler */
11840 	if (vectors_left) {
11841 		v_budget++;
11842 		vectors_left--;
11843 	}
11844 
11845 	/* reserve some vectors for the main PF traffic queues. Initially we
11846 	 * only reserve at most 50% of the available vectors, in the case that
11847 	 * the number of online CPUs is large. This ensures that we can enable
11848 	 * extra features as well. Once we've enabled the other features, we
11849 	 * will use any remaining vectors to reach as close as we can to the
11850 	 * number of online CPUs.
11851 	 */
11852 	cpus = num_online_cpus();
11853 	pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
11854 	vectors_left -= pf->num_lan_msix;
11855 
11856 	/* reserve one vector for sideband flow director */
11857 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
11858 		if (vectors_left) {
11859 			pf->num_fdsb_msix = 1;
11860 			v_budget++;
11861 			vectors_left--;
11862 		} else {
11863 			pf->num_fdsb_msix = 0;
11864 		}
11865 	}
11866 
11867 	/* can we reserve enough for iWARP? */
11868 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
11869 		iwarp_requested = pf->num_iwarp_msix;
11870 
11871 		if (!vectors_left)
11872 			pf->num_iwarp_msix = 0;
11873 		else if (vectors_left < pf->num_iwarp_msix)
11874 			pf->num_iwarp_msix = 1;
11875 		v_budget += pf->num_iwarp_msix;
11876 		vectors_left -= pf->num_iwarp_msix;
11877 	}
11878 
11879 	/* any vectors left over go for VMDq support */
11880 	if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags)) {
11881 		if (!vectors_left) {
11882 			pf->num_vmdq_msix = 0;
11883 			pf->num_vmdq_qps = 0;
11884 		} else {
11885 			int vmdq_vecs_wanted =
11886 				pf->num_vmdq_vsis * pf->num_vmdq_qps;
11887 			int vmdq_vecs =
11888 				min_t(int, vectors_left, vmdq_vecs_wanted);
11889 
11890 			/* if we're short on vectors for what's desired, we limit
11891 			 * the queues per vmdq.  If this is still more than are
11892 			 * available, the user will need to change the number of
11893 			 * queues/vectors used by the PF later with the ethtool
11894 			 * channels command
11895 			 */
11896 			if (vectors_left < vmdq_vecs_wanted) {
11897 				pf->num_vmdq_qps = 1;
11898 				vmdq_vecs_wanted = pf->num_vmdq_vsis;
11899 				vmdq_vecs = min_t(int,
11900 						  vectors_left,
11901 						  vmdq_vecs_wanted);
11902 			}
11903 			pf->num_vmdq_msix = pf->num_vmdq_qps;
11904 
11905 			v_budget += vmdq_vecs;
11906 			vectors_left -= vmdq_vecs;
11907 		}
11908 	}
11909 
11910 	/* On systems with a large number of SMP cores, we previously limited
11911 	 * the number of vectors for num_lan_msix to be at most 50% of the
11912 	 * available vectors, to allow for other features. Now, we add back
11913 	 * the remaining vectors. However, we ensure that the total
11914 	 * num_lan_msix will not exceed num_online_cpus(). To do this, we
11915 	 * calculate the number of vectors we can add without going over the
11916 	 * cap of CPUs. For systems with a small number of CPUs this will be
11917 	 * zero.
11918 	 */
11919 	extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11920 	pf->num_lan_msix += extra_vectors;
11921 	vectors_left -= extra_vectors;
11922 
11923 	WARN(vectors_left < 0,
11924 	     "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11925 
11926 	v_budget += pf->num_lan_msix;
11927 	pf->msix_entries = kzalloc_objs(struct msix_entry, v_budget);
11928 	if (!pf->msix_entries)
11929 		return -ENOMEM;
11930 
11931 	for (i = 0; i < v_budget; i++)
11932 		pf->msix_entries[i].entry = i;
11933 	v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11934 
11935 	if (v_actual < I40E_MIN_MSIX) {
11936 		clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
11937 		kfree(pf->msix_entries);
11938 		pf->msix_entries = NULL;
11939 		pci_disable_msix(pf->pdev);
11940 		return -ENODEV;
11941 
11942 	} else if (v_actual == I40E_MIN_MSIX) {
11943 		/* Adjust for minimal MSIX use */
11944 		pf->num_vmdq_vsis = 0;
11945 		pf->num_vmdq_qps = 0;
11946 		pf->num_lan_qps = 1;
11947 		pf->num_lan_msix = 1;
11948 
11949 	} else if (v_actual != v_budget) {
11950 		/* If we have limited resources, we will start with no vectors
11951 		 * for the special features and then allocate vectors to some
11952 		 * of these features based on the policy and at the end disable
11953 		 * the features that did not get any vectors.
11954 		 */
11955 		int vec;
11956 
11957 		dev_info(&pf->pdev->dev,
11958 			 "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11959 			 v_actual, v_budget);
11960 		/* reserve the misc vector */
11961 		vec = v_actual - 1;
11962 
11963 		/* Scale vector usage down */
11964 		pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11965 		pf->num_vmdq_vsis = 1;
11966 		pf->num_vmdq_qps = 1;
11967 
11968 		/* partition out the remaining vectors */
11969 		switch (vec) {
11970 		case 2:
11971 			pf->num_lan_msix = 1;
11972 			break;
11973 		case 3:
11974 			if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
11975 				pf->num_lan_msix = 1;
11976 				pf->num_iwarp_msix = 1;
11977 			} else {
11978 				pf->num_lan_msix = 2;
11979 			}
11980 			break;
11981 		default:
11982 			if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
11983 				pf->num_iwarp_msix = min_t(int, (vec / 3),
11984 						 iwarp_requested);
11985 				pf->num_vmdq_vsis = min_t(int, (vec / 3),
11986 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11987 			} else {
11988 				pf->num_vmdq_vsis = min_t(int, (vec / 2),
11989 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11990 			}
11991 			if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
11992 				pf->num_fdsb_msix = 1;
11993 				vec--;
11994 			}
11995 			pf->num_lan_msix = min_t(int,
11996 			       (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
11997 							      pf->num_lan_msix);
11998 			pf->num_lan_qps = pf->num_lan_msix;
11999 			break;
12000 		}
12001 	}
12002 
12003 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) && pf->num_fdsb_msix == 0) {
12004 		dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
12005 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12006 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12007 	}
12008 	if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags) && pf->num_vmdq_msix == 0) {
12009 		dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
12010 		clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
12011 	}
12012 
12013 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags) &&
12014 	    pf->num_iwarp_msix == 0) {
12015 		dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
12016 		clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
12017 	}
12018 	i40e_debug(&pf->hw, I40E_DEBUG_INIT,
12019 		   "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
12020 		   pf->num_lan_msix,
12021 		   pf->num_vmdq_msix * pf->num_vmdq_vsis,
12022 		   pf->num_fdsb_msix,
12023 		   pf->num_iwarp_msix);
12024 
12025 	return v_actual;
12026 }
12027 
12028 /**
12029  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
12030  * @vsi: the VSI being configured
12031  * @v_idx: index of the vector in the vsi struct
12032  *
12033  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
12034  **/
12035 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx)
12036 {
12037 	struct i40e_q_vector *q_vector;
12038 
12039 	/* allocate q_vector */
12040 	q_vector = kzalloc_obj(struct i40e_q_vector);
12041 	if (!q_vector)
12042 		return -ENOMEM;
12043 
12044 	q_vector->vsi = vsi;
12045 	q_vector->v_idx = v_idx;
12046 	cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
12047 
12048 	if (vsi->netdev)
12049 		netif_napi_add(vsi->netdev, &q_vector->napi, i40e_napi_poll);
12050 
12051 	/* tie q_vector and vsi together */
12052 	vsi->q_vectors[v_idx] = q_vector;
12053 
12054 	return 0;
12055 }
12056 
12057 /**
12058  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
12059  * @vsi: the VSI being configured
12060  *
12061  * We allocate one q_vector per queue interrupt.  If allocation fails we
12062  * return -ENOMEM.
12063  **/
12064 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
12065 {
12066 	struct i40e_pf *pf = vsi->back;
12067 	int err, v_idx, num_q_vectors;
12068 
12069 	/* if not MSIX, give the one vector only to the LAN VSI */
12070 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
12071 		num_q_vectors = vsi->num_q_vectors;
12072 	else if (vsi->type == I40E_VSI_MAIN)
12073 		num_q_vectors = 1;
12074 	else
12075 		return -EINVAL;
12076 
12077 	for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
12078 		err = i40e_vsi_alloc_q_vector(vsi, v_idx);
12079 		if (err)
12080 			goto err_out;
12081 	}
12082 
12083 	return 0;
12084 
12085 err_out:
12086 	while (v_idx--)
12087 		i40e_free_q_vector(vsi, v_idx);
12088 
12089 	return err;
12090 }
12091 
12092 /**
12093  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
12094  * @pf: board private structure to initialize
12095  **/
12096 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
12097 {
12098 	int vectors = 0;
12099 	ssize_t size;
12100 
12101 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
12102 		vectors = i40e_init_msix(pf);
12103 		if (vectors < 0) {
12104 			clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12105 			clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
12106 			clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
12107 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
12108 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
12109 			clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
12110 			clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12111 			clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
12112 			clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
12113 			set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12114 
12115 			/* rework the queue expectations without MSIX */
12116 			i40e_determine_queue_usage(pf);
12117 		}
12118 	}
12119 
12120 	if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
12121 	    test_bit(I40E_FLAG_MSI_ENA, pf->flags)) {
12122 		dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
12123 		vectors = pci_enable_msi(pf->pdev);
12124 		if (vectors < 0) {
12125 			dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
12126 				 vectors);
12127 			clear_bit(I40E_FLAG_MSI_ENA, pf->flags);
12128 		}
12129 		vectors = 1;  /* one MSI or Legacy vector */
12130 	}
12131 
12132 	if (!test_bit(I40E_FLAG_MSI_ENA, pf->flags) &&
12133 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
12134 		dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
12135 
12136 	/* set up vector assignment tracking */
12137 	size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
12138 	pf->irq_pile = kzalloc(size, GFP_KERNEL);
12139 	if (!pf->irq_pile)
12140 		return -ENOMEM;
12141 
12142 	pf->irq_pile->num_entries = vectors;
12143 
12144 	/* track first vector for misc interrupts, ignore return */
12145 	(void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
12146 
12147 	return 0;
12148 }
12149 
12150 /**
12151  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
12152  * @pf: private board data structure
12153  *
12154  * Restore the interrupt scheme that was cleared when we suspended the
12155  * device. This should be called during resume to re-allocate the q_vectors
12156  * and reacquire IRQs.
12157  */
12158 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
12159 {
12160 	struct i40e_vsi *vsi;
12161 	int err, i;
12162 
12163 	/* We cleared the MSI and MSI-X flags when disabling the old interrupt
12164 	 * scheme. We need to re-enabled them here in order to attempt to
12165 	 * re-acquire the MSI or MSI-X vectors
12166 	 */
12167 	set_bit(I40E_FLAG_MSI_ENA, pf->flags);
12168 	set_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12169 
12170 	err = i40e_init_interrupt_scheme(pf);
12171 	if (err)
12172 		return err;
12173 
12174 	/* Now that we've re-acquired IRQs, we need to remap the vectors and
12175 	 * rings together again.
12176 	 */
12177 	i40e_pf_for_each_vsi(pf, i, vsi) {
12178 		err = i40e_vsi_alloc_q_vectors(vsi);
12179 		if (err)
12180 			goto err_unwind;
12181 
12182 		i40e_vsi_map_rings_to_vectors(vsi);
12183 	}
12184 
12185 	err = i40e_setup_misc_vector(pf);
12186 	if (err)
12187 		goto err_unwind;
12188 
12189 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags))
12190 		i40e_client_update_msix_info(pf);
12191 
12192 	return 0;
12193 
12194 err_unwind:
12195 	while (i--) {
12196 		if (pf->vsi[i])
12197 			i40e_vsi_free_q_vectors(pf->vsi[i]);
12198 	}
12199 
12200 	return err;
12201 }
12202 
12203 /**
12204  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
12205  * non queue events in recovery mode
12206  * @pf: board private structure
12207  *
12208  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
12209  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
12210  * This is handled differently than in recovery mode since no Tx/Rx resources
12211  * are being allocated.
12212  **/
12213 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
12214 {
12215 	int err;
12216 
12217 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
12218 		err = i40e_setup_misc_vector(pf);
12219 
12220 		if (err) {
12221 			dev_info(&pf->pdev->dev,
12222 				 "MSI-X misc vector request failed, error %d\n",
12223 				 err);
12224 			return err;
12225 		}
12226 	} else {
12227 		u32 flags = test_bit(I40E_FLAG_MSI_ENA, pf->flags) ? 0 : IRQF_SHARED;
12228 
12229 		err = request_irq(pf->pdev->irq, i40e_intr, flags,
12230 				  pf->int_name, pf);
12231 
12232 		if (err) {
12233 			dev_info(&pf->pdev->dev,
12234 				 "MSI/legacy misc vector request failed, error %d\n",
12235 				 err);
12236 			return err;
12237 		}
12238 		i40e_enable_misc_int_causes(pf);
12239 		i40e_irq_dynamic_enable_icr0(pf);
12240 	}
12241 
12242 	return 0;
12243 }
12244 
12245 /**
12246  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
12247  * @pf: board private structure
12248  *
12249  * This sets up the handler for MSIX 0, which is used to manage the
12250  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
12251  * when in MSI or Legacy interrupt mode.
12252  **/
12253 static int i40e_setup_misc_vector(struct i40e_pf *pf)
12254 {
12255 	struct i40e_hw *hw = &pf->hw;
12256 	int err = 0;
12257 
12258 	/* Only request the IRQ once, the first time through. */
12259 	if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
12260 		err = request_irq(pf->msix_entries[0].vector,
12261 				  i40e_intr, 0, pf->int_name, pf);
12262 		if (err) {
12263 			clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
12264 			dev_info(&pf->pdev->dev,
12265 				 "request_irq for %s failed: %d\n",
12266 				 pf->int_name, err);
12267 			return -EFAULT;
12268 		}
12269 	}
12270 
12271 	i40e_enable_misc_int_causes(pf);
12272 
12273 	/* associate no queues to the misc vector */
12274 	wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
12275 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K >> 1);
12276 
12277 	i40e_flush(hw);
12278 
12279 	i40e_irq_dynamic_enable_icr0(pf);
12280 
12281 	return err;
12282 }
12283 
12284 /**
12285  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
12286  * @vsi: Pointer to vsi structure
12287  * @seed: Buffter to store the hash keys
12288  * @lut: Buffer to store the lookup table entries
12289  * @lut_size: Size of buffer to store the lookup table entries
12290  *
12291  * Return 0 on success, negative on failure
12292  */
12293 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
12294 			   u8 *lut, u16 lut_size)
12295 {
12296 	struct i40e_pf *pf = vsi->back;
12297 	struct i40e_hw *hw = &pf->hw;
12298 	int ret = 0;
12299 
12300 	if (seed) {
12301 		ret = i40e_aq_get_rss_key(hw, vsi->id,
12302 			(struct i40e_aqc_get_set_rss_key_data *)seed);
12303 		if (ret) {
12304 			dev_info(&pf->pdev->dev,
12305 				 "Cannot get RSS key, err %pe aq_err %s\n",
12306 				 ERR_PTR(ret),
12307 				 libie_aq_str(pf->hw.aq.asq_last_status));
12308 			return ret;
12309 		}
12310 	}
12311 
12312 	if (lut) {
12313 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
12314 
12315 		ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
12316 		if (ret) {
12317 			dev_info(&pf->pdev->dev,
12318 				 "Cannot get RSS lut, err %pe aq_err %s\n",
12319 				 ERR_PTR(ret),
12320 				 libie_aq_str(pf->hw.aq.asq_last_status));
12321 			return ret;
12322 		}
12323 	}
12324 
12325 	return ret;
12326 }
12327 
12328 /**
12329  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
12330  * @vsi: Pointer to vsi structure
12331  * @seed: RSS hash seed
12332  * @lut: Lookup table
12333  * @lut_size: Lookup table size
12334  *
12335  * Returns 0 on success, negative on failure
12336  **/
12337 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
12338 			       const u8 *lut, u16 lut_size)
12339 {
12340 	struct i40e_pf *pf = vsi->back;
12341 	struct i40e_hw *hw = &pf->hw;
12342 	u16 vf_id = vsi->vf_id;
12343 	u8 i;
12344 
12345 	/* Fill out hash function seed */
12346 	if (seed) {
12347 		u32 *seed_dw = (u32 *)seed;
12348 
12349 		if (vsi->type == I40E_VSI_MAIN) {
12350 			for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12351 				wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
12352 		} else if (vsi->type == I40E_VSI_SRIOV) {
12353 			for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
12354 				wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
12355 		} else {
12356 			dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
12357 		}
12358 	}
12359 
12360 	if (lut) {
12361 		u32 *lut_dw = (u32 *)lut;
12362 
12363 		if (vsi->type == I40E_VSI_MAIN) {
12364 			if (lut_size != I40E_HLUT_ARRAY_SIZE)
12365 				return -EINVAL;
12366 			for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12367 				wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
12368 		} else if (vsi->type == I40E_VSI_SRIOV) {
12369 			if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
12370 				return -EINVAL;
12371 			for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12372 				wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
12373 		} else {
12374 			dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12375 		}
12376 	}
12377 	i40e_flush(hw);
12378 
12379 	return 0;
12380 }
12381 
12382 /**
12383  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
12384  * @vsi: Pointer to VSI structure
12385  * @seed: Buffer to store the keys
12386  * @lut: Buffer to store the lookup table entries
12387  * @lut_size: Size of buffer to store the lookup table entries
12388  *
12389  * Returns 0 on success, negative on failure
12390  */
12391 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
12392 			    u8 *lut, u16 lut_size)
12393 {
12394 	struct i40e_pf *pf = vsi->back;
12395 	struct i40e_hw *hw = &pf->hw;
12396 	u16 i;
12397 
12398 	if (seed) {
12399 		u32 *seed_dw = (u32 *)seed;
12400 
12401 		for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12402 			seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
12403 	}
12404 	if (lut) {
12405 		u32 *lut_dw = (u32 *)lut;
12406 
12407 		if (lut_size != I40E_HLUT_ARRAY_SIZE)
12408 			return -EINVAL;
12409 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12410 			lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
12411 	}
12412 
12413 	return 0;
12414 }
12415 
12416 /**
12417  * i40e_config_rss - Configure RSS keys and lut
12418  * @vsi: Pointer to VSI structure
12419  * @seed: RSS hash seed
12420  * @lut: Lookup table
12421  * @lut_size: Lookup table size
12422  *
12423  * Returns 0 on success, negative on failure
12424  */
12425 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12426 {
12427 	struct i40e_pf *pf = vsi->back;
12428 
12429 	if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
12430 		return i40e_config_rss_aq(vsi, seed, lut, lut_size);
12431 	else
12432 		return i40e_config_rss_reg(vsi, seed, lut, lut_size);
12433 }
12434 
12435 /**
12436  * i40e_get_rss - Get RSS keys and lut
12437  * @vsi: Pointer to VSI structure
12438  * @seed: Buffer to store the keys
12439  * @lut: Buffer to store the lookup table entries
12440  * @lut_size: Size of buffer to store the lookup table entries
12441  *
12442  * Returns 0 on success, negative on failure
12443  */
12444 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12445 {
12446 	struct i40e_pf *pf = vsi->back;
12447 
12448 	if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
12449 		return i40e_get_rss_aq(vsi, seed, lut, lut_size);
12450 	else
12451 		return i40e_get_rss_reg(vsi, seed, lut, lut_size);
12452 }
12453 
12454 /**
12455  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
12456  * @pf: Pointer to board private structure
12457  * @lut: Lookup table
12458  * @rss_table_size: Lookup table size
12459  * @rss_size: Range of queue number for hashing
12460  */
12461 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
12462 		       u16 rss_table_size, u16 rss_size)
12463 {
12464 	u16 i;
12465 
12466 	for (i = 0; i < rss_table_size; i++)
12467 		lut[i] = i % rss_size;
12468 }
12469 
12470 /**
12471  * i40e_pf_config_rss - Prepare for RSS if used
12472  * @pf: board private structure
12473  **/
12474 static int i40e_pf_config_rss(struct i40e_pf *pf)
12475 {
12476 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
12477 	u8 seed[I40E_HKEY_ARRAY_SIZE];
12478 	u8 *lut;
12479 	struct i40e_hw *hw = &pf->hw;
12480 	u32 reg_val;
12481 	u64 hena;
12482 	int ret;
12483 
12484 	/* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
12485 	hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
12486 		((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
12487 	hena |= i40e_pf_get_default_rss_hashcfg(pf);
12488 
12489 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
12490 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
12491 
12492 	/* Determine the RSS table size based on the hardware capabilities */
12493 	reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
12494 	reg_val = (pf->rss_table_size == 512) ?
12495 			(reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
12496 			(reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
12497 	i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
12498 
12499 	/* Determine the RSS size of the VSI */
12500 	if (!vsi->rss_size) {
12501 		u16 qcount;
12502 		/* If the firmware does something weird during VSI init, we
12503 		 * could end up with zero TCs. Check for that to avoid
12504 		 * divide-by-zero. It probably won't pass traffic, but it also
12505 		 * won't panic.
12506 		 */
12507 		qcount = vsi->num_queue_pairs /
12508 			 (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
12509 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12510 	}
12511 	if (!vsi->rss_size)
12512 		return -EINVAL;
12513 
12514 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
12515 	if (!lut)
12516 		return -ENOMEM;
12517 
12518 	/* Use user configured lut if there is one, otherwise use default */
12519 	if (vsi->rss_lut_user)
12520 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
12521 	else
12522 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
12523 
12524 	/* Use user configured hash key if there is one, otherwise
12525 	 * use default.
12526 	 */
12527 	if (vsi->rss_hkey_user)
12528 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
12529 	else
12530 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
12531 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
12532 	kfree(lut);
12533 
12534 	return ret;
12535 }
12536 
12537 /**
12538  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
12539  * @pf: board private structure
12540  * @queue_count: the requested queue count for rss.
12541  *
12542  * returns 0 if rss is not enabled, if enabled returns the final rss queue
12543  * count which may be different from the requested queue count.
12544  * Note: expects to be called while under rtnl_lock()
12545  **/
12546 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
12547 {
12548 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
12549 	int new_rss_size;
12550 
12551 	if (!test_bit(I40E_FLAG_RSS_ENA, pf->flags))
12552 		return 0;
12553 
12554 	queue_count = min_t(int, queue_count, num_online_cpus());
12555 	new_rss_size = min_t(int, queue_count, pf->rss_size_max);
12556 
12557 	if (queue_count != vsi->num_queue_pairs) {
12558 		u16 qcount;
12559 
12560 		vsi->req_queue_pairs = queue_count;
12561 		i40e_prep_for_reset(pf);
12562 		if (test_bit(__I40E_IN_REMOVE, pf->state))
12563 			return pf->alloc_rss_size;
12564 
12565 		pf->alloc_rss_size = new_rss_size;
12566 
12567 		i40e_reset_and_rebuild(pf, true, true);
12568 
12569 		/* Discard the user configured hash keys and lut, if less
12570 		 * queues are enabled.
12571 		 */
12572 		if (queue_count < vsi->rss_size) {
12573 			i40e_clear_rss_config_user(vsi);
12574 			dev_dbg(&pf->pdev->dev,
12575 				"discard user configured hash keys and lut\n");
12576 		}
12577 
12578 		/* Reset vsi->rss_size, as number of enabled queues changed */
12579 		qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
12580 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12581 
12582 		i40e_pf_config_rss(pf);
12583 	}
12584 	dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
12585 		 vsi->req_queue_pairs, pf->rss_size_max);
12586 	return pf->alloc_rss_size;
12587 }
12588 
12589 /**
12590  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
12591  * @pf: board private structure
12592  **/
12593 int i40e_get_partition_bw_setting(struct i40e_pf *pf)
12594 {
12595 	bool min_valid, max_valid;
12596 	u32 max_bw, min_bw;
12597 	int status;
12598 
12599 	status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
12600 					   &min_valid, &max_valid);
12601 
12602 	if (!status) {
12603 		if (min_valid)
12604 			pf->min_bw = min_bw;
12605 		if (max_valid)
12606 			pf->max_bw = max_bw;
12607 	}
12608 
12609 	return status;
12610 }
12611 
12612 /**
12613  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
12614  * @pf: board private structure
12615  **/
12616 int i40e_set_partition_bw_setting(struct i40e_pf *pf)
12617 {
12618 	struct i40e_aqc_configure_partition_bw_data bw_data;
12619 	int status;
12620 
12621 	memset(&bw_data, 0, sizeof(bw_data));
12622 
12623 	/* Set the valid bit for this PF */
12624 	bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
12625 	bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
12626 	bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
12627 
12628 	/* Set the new bandwidths */
12629 	status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
12630 
12631 	return status;
12632 }
12633 
12634 /**
12635  * i40e_is_total_port_shutdown_enabled - read NVM and return value
12636  * if total port shutdown feature is enabled for this PF
12637  * @pf: board private structure
12638  **/
12639 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf)
12640 {
12641 #define I40E_TOTAL_PORT_SHUTDOWN_ENABLED	BIT(4)
12642 #define I40E_FEATURES_ENABLE_PTR		0x2A
12643 #define I40E_CURRENT_SETTING_PTR		0x2B
12644 #define I40E_LINK_BEHAVIOR_WORD_OFFSET		0x2D
12645 #define I40E_LINK_BEHAVIOR_WORD_LENGTH		0x1
12646 #define I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED	BIT(0)
12647 #define I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH	4
12648 	u16 sr_emp_sr_settings_ptr = 0;
12649 	u16 features_enable = 0;
12650 	u16 link_behavior = 0;
12651 	int read_status = 0;
12652 	bool ret = false;
12653 
12654 	read_status = i40e_read_nvm_word(&pf->hw,
12655 					 I40E_SR_EMP_SR_SETTINGS_PTR,
12656 					 &sr_emp_sr_settings_ptr);
12657 	if (read_status)
12658 		goto err_nvm;
12659 	read_status = i40e_read_nvm_word(&pf->hw,
12660 					 sr_emp_sr_settings_ptr +
12661 					 I40E_FEATURES_ENABLE_PTR,
12662 					 &features_enable);
12663 	if (read_status)
12664 		goto err_nvm;
12665 	if (I40E_TOTAL_PORT_SHUTDOWN_ENABLED & features_enable) {
12666 		read_status = i40e_read_nvm_module_data(&pf->hw,
12667 							I40E_SR_EMP_SR_SETTINGS_PTR,
12668 							I40E_CURRENT_SETTING_PTR,
12669 							I40E_LINK_BEHAVIOR_WORD_OFFSET,
12670 							I40E_LINK_BEHAVIOR_WORD_LENGTH,
12671 							&link_behavior);
12672 		if (read_status)
12673 			goto err_nvm;
12674 		link_behavior >>= (pf->hw.port * I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH);
12675 		ret = I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED & link_behavior;
12676 	}
12677 	return ret;
12678 
12679 err_nvm:
12680 	dev_warn(&pf->pdev->dev,
12681 		 "total-port-shutdown feature is off due to read nvm error: %pe\n",
12682 		 ERR_PTR(read_status));
12683 	return ret;
12684 }
12685 
12686 /**
12687  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
12688  * @pf: board private structure to initialize
12689  *
12690  * i40e_sw_init initializes the Adapter private data structure.
12691  * Fields are initialized based on PCI device information and
12692  * OS network device settings (MTU size).
12693  **/
12694 static int i40e_sw_init(struct i40e_pf *pf)
12695 {
12696 	int err = 0;
12697 	int size;
12698 	u16 pow;
12699 
12700 	/* Set default capability flags */
12701 	bitmap_zero(pf->flags, I40E_PF_FLAGS_NBITS);
12702 	set_bit(I40E_FLAG_MSI_ENA, pf->flags);
12703 	set_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12704 
12705 	/* Set default ITR */
12706 	pf->rx_itr_default = I40E_ITR_RX_DEF;
12707 	pf->tx_itr_default = I40E_ITR_TX_DEF;
12708 
12709 	/* Depending on PF configurations, it is possible that the RSS
12710 	 * maximum might end up larger than the available queues
12711 	 */
12712 	pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
12713 	pf->alloc_rss_size = 1;
12714 	pf->rss_table_size = pf->hw.func_caps.rss_table_size;
12715 	pf->rss_size_max = min_t(int, pf->rss_size_max,
12716 				 pf->hw.func_caps.num_tx_qp);
12717 
12718 	/* find the next higher power-of-2 of num cpus */
12719 	pow = roundup_pow_of_two(num_online_cpus());
12720 	pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
12721 
12722 	if (pf->hw.func_caps.rss) {
12723 		set_bit(I40E_FLAG_RSS_ENA, pf->flags);
12724 		pf->alloc_rss_size = min_t(int, pf->rss_size_max,
12725 					   num_online_cpus());
12726 	}
12727 
12728 	/* MFP mode enabled */
12729 	if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
12730 		set_bit(I40E_FLAG_MFP_ENA, pf->flags);
12731 		dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
12732 		if (i40e_get_partition_bw_setting(pf)) {
12733 			dev_warn(&pf->pdev->dev,
12734 				 "Could not get partition bw settings\n");
12735 		} else {
12736 			dev_info(&pf->pdev->dev,
12737 				 "Partition BW Min = %8.8x, Max = %8.8x\n",
12738 				 pf->min_bw, pf->max_bw);
12739 
12740 			/* nudge the Tx scheduler */
12741 			i40e_set_partition_bw_setting(pf);
12742 		}
12743 	}
12744 
12745 	if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
12746 	    (pf->hw.func_caps.fd_filters_best_effort > 0)) {
12747 		set_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
12748 		if (test_bit(I40E_FLAG_MFP_ENA, pf->flags) &&
12749 		    pf->hw.num_partitions > 1)
12750 			dev_info(&pf->pdev->dev,
12751 				 "Flow Director Sideband mode Disabled in MFP mode\n");
12752 		else
12753 			set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12754 		pf->fdir_pf_filter_count =
12755 				 pf->hw.func_caps.fd_filters_guaranteed;
12756 		pf->hw.fdir_shared_filter_count =
12757 				 pf->hw.func_caps.fd_filters_best_effort;
12758 	}
12759 
12760 	/* Enable HW ATR eviction if possible */
12761 	if (test_bit(I40E_HW_CAP_ATR_EVICT, pf->hw.caps))
12762 		set_bit(I40E_FLAG_HW_ATR_EVICT_ENA, pf->flags);
12763 
12764 	if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
12765 		pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
12766 		set_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
12767 		pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
12768 	}
12769 
12770 	if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
12771 		set_bit(I40E_FLAG_IWARP_ENA, pf->flags);
12772 		/* IWARP needs one extra vector for CQP just like MISC.*/
12773 		pf->num_iwarp_msix = (int)num_online_cpus() + 1;
12774 	}
12775 	/* Stopping FW LLDP engine is supported on XL710 and X722
12776 	 * starting from FW versions determined in i40e_init_adminq.
12777 	 * Stopping the FW LLDP engine is not supported on XL710
12778 	 * if NPAR is functioning so unset this hw flag in this case.
12779 	 */
12780 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
12781 	    pf->hw.func_caps.npar_enable)
12782 		clear_bit(I40E_HW_CAP_FW_LLDP_STOPPABLE, pf->hw.caps);
12783 
12784 #ifdef CONFIG_PCI_IOV
12785 	if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
12786 		pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
12787 		set_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
12788 		pf->num_req_vfs = min_t(int,
12789 					pf->hw.func_caps.num_vfs,
12790 					I40E_MAX_VF_COUNT);
12791 	}
12792 #endif /* CONFIG_PCI_IOV */
12793 	pf->lan_veb = I40E_NO_VEB;
12794 	pf->lan_vsi = I40E_NO_VSI;
12795 
12796 	/* By default FW has this off for performance reasons */
12797 	clear_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags);
12798 
12799 	/* set up queue assignment tracking */
12800 	size = sizeof(struct i40e_lump_tracking)
12801 		+ (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
12802 	pf->qp_pile = kzalloc(size, GFP_KERNEL);
12803 	if (!pf->qp_pile) {
12804 		err = -ENOMEM;
12805 		goto sw_init_done;
12806 	}
12807 	pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
12808 
12809 	pf->tx_timeout_recovery_level = 1;
12810 
12811 	if (pf->hw.mac.type != I40E_MAC_X722 &&
12812 	    i40e_is_total_port_shutdown_enabled(pf)) {
12813 		/* Link down on close must be on when total port shutdown
12814 		 * is enabled for a given port
12815 		 */
12816 		set_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags);
12817 		set_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags);
12818 		dev_info(&pf->pdev->dev,
12819 			 "total-port-shutdown was enabled, link-down-on-close is forced on\n");
12820 	}
12821 	mutex_init(&pf->switch_mutex);
12822 
12823 sw_init_done:
12824 	return err;
12825 }
12826 
12827 /**
12828  * i40e_set_ntuple - set the ntuple feature flag and take action
12829  * @pf: board private structure to initialize
12830  * @features: the feature set that the stack is suggesting
12831  *
12832  * returns a bool to indicate if reset needs to happen
12833  **/
12834 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12835 {
12836 	bool need_reset = false;
12837 
12838 	/* Check if Flow Director n-tuple support was enabled or disabled.  If
12839 	 * the state changed, we need to reset.
12840 	 */
12841 	if (features & NETIF_F_NTUPLE) {
12842 		/* Enable filters and mark for reset */
12843 		if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
12844 			need_reset = true;
12845 		/* enable FD_SB only if there is MSI-X vector and no cloud
12846 		 * filters exist
12847 		 */
12848 		if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12849 			set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12850 			clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12851 		}
12852 	} else {
12853 		/* turn off filters, mark for reset and clear SW filter list */
12854 		if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
12855 			need_reset = true;
12856 			i40e_fdir_filter_exit(pf);
12857 		}
12858 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12859 		clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12860 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12861 
12862 		/* reset fd counters */
12863 		pf->fd_add_err = 0;
12864 		pf->fd_atr_cnt = 0;
12865 		/* if ATR was auto disabled it can be re-enabled. */
12866 		if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12867 			if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
12868 			    (I40E_DEBUG_FD & pf->hw.debug_mask))
12869 				dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12870 	}
12871 	return need_reset;
12872 }
12873 
12874 /**
12875  * i40e_clear_rss_lut - clear the rx hash lookup table
12876  * @vsi: the VSI being configured
12877  **/
12878 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12879 {
12880 	struct i40e_pf *pf = vsi->back;
12881 	struct i40e_hw *hw = &pf->hw;
12882 	u16 vf_id = vsi->vf_id;
12883 	u8 i;
12884 
12885 	if (vsi->type == I40E_VSI_MAIN) {
12886 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12887 			wr32(hw, I40E_PFQF_HLUT(i), 0);
12888 	} else if (vsi->type == I40E_VSI_SRIOV) {
12889 		for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12890 			i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12891 	} else {
12892 		dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12893 	}
12894 }
12895 
12896 /**
12897  * i40e_set_loopback - turn on/off loopback mode on underlying PF
12898  * @vsi: ptr to VSI
12899  * @ena: flag to indicate the on/off setting
12900  */
12901 static int i40e_set_loopback(struct i40e_vsi *vsi, bool ena)
12902 {
12903 	bool if_running = netif_running(vsi->netdev) &&
12904 			  !test_and_set_bit(__I40E_VSI_DOWN, vsi->state);
12905 	int ret;
12906 
12907 	if (if_running)
12908 		i40e_down(vsi);
12909 
12910 	ret = i40e_aq_set_mac_loopback(&vsi->back->hw, ena, NULL);
12911 	if (ret)
12912 		netdev_err(vsi->netdev, "Failed to toggle loopback state\n");
12913 	if (if_running)
12914 		i40e_up(vsi);
12915 
12916 	return ret;
12917 }
12918 
12919 /**
12920  * i40e_set_features - set the netdev feature flags
12921  * @netdev: ptr to the netdev being adjusted
12922  * @features: the feature set that the stack is suggesting
12923  * Note: expects to be called while under rtnl_lock()
12924  **/
12925 static int i40e_set_features(struct net_device *netdev,
12926 			     netdev_features_t features)
12927 {
12928 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12929 	struct i40e_vsi *vsi = np->vsi;
12930 	struct i40e_pf *pf = vsi->back;
12931 	bool need_reset;
12932 
12933 	if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
12934 		i40e_pf_config_rss(pf);
12935 	else if (!(features & NETIF_F_RXHASH) &&
12936 		 netdev->features & NETIF_F_RXHASH)
12937 		i40e_clear_rss_lut(vsi);
12938 
12939 	if (features & NETIF_F_HW_VLAN_CTAG_RX)
12940 		i40e_vlan_stripping_enable(vsi);
12941 	else
12942 		i40e_vlan_stripping_disable(vsi);
12943 
12944 	if (!(features & NETIF_F_HW_TC) &&
12945 	    (netdev->features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
12946 		dev_err(&pf->pdev->dev,
12947 			"Offloaded tc filters active, can't turn hw_tc_offload off");
12948 		return -EINVAL;
12949 	}
12950 
12951 	if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
12952 		i40e_del_all_macvlans(vsi);
12953 
12954 	need_reset = i40e_set_ntuple(pf, features);
12955 
12956 	if (need_reset)
12957 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12958 
12959 	if ((features ^ netdev->features) & NETIF_F_LOOPBACK)
12960 		return i40e_set_loopback(vsi, !!(features & NETIF_F_LOOPBACK));
12961 
12962 	return 0;
12963 }
12964 
12965 static int i40e_udp_tunnel_set_port(struct net_device *netdev,
12966 				    unsigned int table, unsigned int idx,
12967 				    struct udp_tunnel_info *ti)
12968 {
12969 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12970 	struct i40e_hw *hw = &np->vsi->back->hw;
12971 	u8 type, filter_index;
12972 	int ret;
12973 
12974 	type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? I40E_AQC_TUNNEL_TYPE_VXLAN :
12975 						   I40E_AQC_TUNNEL_TYPE_NGE;
12976 
12977 	ret = i40e_aq_add_udp_tunnel(hw, ntohs(ti->port), type, &filter_index,
12978 				     NULL);
12979 	if (ret) {
12980 		netdev_info(netdev, "add UDP port failed, err %pe aq_err %s\n",
12981 			    ERR_PTR(ret), libie_aq_str(hw->aq.asq_last_status));
12982 		return -EIO;
12983 	}
12984 
12985 	udp_tunnel_nic_set_port_priv(netdev, table, idx, filter_index);
12986 	return 0;
12987 }
12988 
12989 static int i40e_udp_tunnel_unset_port(struct net_device *netdev,
12990 				      unsigned int table, unsigned int idx,
12991 				      struct udp_tunnel_info *ti)
12992 {
12993 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12994 	struct i40e_hw *hw = &np->vsi->back->hw;
12995 	int ret;
12996 
12997 	ret = i40e_aq_del_udp_tunnel(hw, ti->hw_priv, NULL);
12998 	if (ret) {
12999 		netdev_info(netdev, "delete UDP port failed, err %pe aq_err %s\n",
13000 			    ERR_PTR(ret), libie_aq_str(hw->aq.asq_last_status));
13001 		return -EIO;
13002 	}
13003 
13004 	return 0;
13005 }
13006 
13007 static int i40e_get_phys_port_id(struct net_device *netdev,
13008 				 struct netdev_phys_item_id *ppid)
13009 {
13010 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13011 	struct i40e_pf *pf = np->vsi->back;
13012 	struct i40e_hw *hw = &pf->hw;
13013 
13014 	if (!test_bit(I40E_HW_CAP_PORT_ID_VALID, pf->hw.caps))
13015 		return -EOPNOTSUPP;
13016 
13017 	ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
13018 	memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
13019 
13020 	return 0;
13021 }
13022 
13023 /**
13024  * i40e_ndo_fdb_add - add an entry to the hardware database
13025  * @ndm: the input from the stack
13026  * @tb: pointer to array of nladdr (unused)
13027  * @dev: the net device pointer
13028  * @addr: the MAC address entry being added
13029  * @vid: VLAN ID
13030  * @flags: instructions from stack about fdb operation
13031  * @notified: whether notification was emitted
13032  * @extack: netlink extended ack, unused currently
13033  */
13034 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
13035 			    struct net_device *dev,
13036 			    const unsigned char *addr, u16 vid,
13037 			    u16 flags, bool *notified,
13038 			    struct netlink_ext_ack *extack)
13039 {
13040 	struct i40e_netdev_priv *np = netdev_priv(dev);
13041 	struct i40e_pf *pf = np->vsi->back;
13042 	int err = 0;
13043 
13044 	if (!test_bit(I40E_FLAG_SRIOV_ENA, pf->flags))
13045 		return -EOPNOTSUPP;
13046 
13047 	if (vid) {
13048 		pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
13049 		return -EINVAL;
13050 	}
13051 
13052 	/* Hardware does not support aging addresses so if a
13053 	 * ndm_state is given only allow permanent addresses
13054 	 */
13055 	if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
13056 		netdev_info(dev, "FDB only supports static addresses\n");
13057 		return -EINVAL;
13058 	}
13059 
13060 	if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
13061 		err = dev_uc_add_excl(dev, addr);
13062 	else if (is_multicast_ether_addr(addr))
13063 		err = dev_mc_add_excl(dev, addr);
13064 	else
13065 		err = -EINVAL;
13066 
13067 	/* Only return duplicate errors if NLM_F_EXCL is set */
13068 	if (err == -EEXIST && !(flags & NLM_F_EXCL))
13069 		err = 0;
13070 
13071 	return err;
13072 }
13073 
13074 /**
13075  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
13076  * @dev: the netdev being configured
13077  * @nlh: RTNL message
13078  * @flags: bridge flags
13079  * @extack: netlink extended ack
13080  *
13081  * Inserts a new hardware bridge if not already created and
13082  * enables the bridging mode requested (VEB or VEPA). If the
13083  * hardware bridge has already been inserted and the request
13084  * is to change the mode then that requires a PF reset to
13085  * allow rebuild of the components with required hardware
13086  * bridge mode enabled.
13087  *
13088  * Note: expects to be called while under rtnl_lock()
13089  **/
13090 static int i40e_ndo_bridge_setlink(struct net_device *dev,
13091 				   struct nlmsghdr *nlh,
13092 				   u16 flags,
13093 				   struct netlink_ext_ack *extack)
13094 {
13095 	struct i40e_netdev_priv *np = netdev_priv(dev);
13096 	struct i40e_vsi *vsi = np->vsi;
13097 	struct i40e_pf *pf = vsi->back;
13098 	struct nlattr *attr, *br_spec;
13099 	struct i40e_veb *veb;
13100 	int rem;
13101 
13102 	/* Only for PF VSI for now */
13103 	if (vsi->type != I40E_VSI_MAIN)
13104 		return -EOPNOTSUPP;
13105 
13106 	/* Find the HW bridge for PF VSI */
13107 	veb = i40e_pf_get_veb_by_seid(pf, vsi->uplink_seid);
13108 
13109 	br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
13110 	if (!br_spec)
13111 		return -EINVAL;
13112 
13113 	nla_for_each_nested_type(attr, IFLA_BRIDGE_MODE, br_spec, rem) {
13114 		__u16 mode = nla_get_u16(attr);
13115 
13116 		if ((mode != BRIDGE_MODE_VEPA) &&
13117 		    (mode != BRIDGE_MODE_VEB))
13118 			return -EINVAL;
13119 
13120 		/* Insert a new HW bridge */
13121 		if (!veb) {
13122 			veb = i40e_veb_setup(pf, vsi->uplink_seid, vsi->seid,
13123 					     vsi->tc_config.enabled_tc);
13124 			if (veb) {
13125 				veb->bridge_mode = mode;
13126 				i40e_config_bridge_mode(veb);
13127 			} else {
13128 				/* No Bridge HW offload available */
13129 				return -ENOENT;
13130 			}
13131 			break;
13132 		} else if (mode != veb->bridge_mode) {
13133 			/* Existing HW bridge but different mode needs reset */
13134 			veb->bridge_mode = mode;
13135 			/* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
13136 			if (mode == BRIDGE_MODE_VEB)
13137 				set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
13138 			else
13139 				clear_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
13140 			i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13141 			break;
13142 		}
13143 	}
13144 
13145 	return 0;
13146 }
13147 
13148 /**
13149  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
13150  * @skb: skb buff
13151  * @pid: process id
13152  * @seq: RTNL message seq #
13153  * @dev: the netdev being configured
13154  * @filter_mask: unused
13155  * @nlflags: netlink flags passed in
13156  *
13157  * Return the mode in which the hardware bridge is operating in
13158  * i.e VEB or VEPA.
13159  **/
13160 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
13161 				   struct net_device *dev,
13162 				   u32 __always_unused filter_mask,
13163 				   int nlflags)
13164 {
13165 	struct i40e_netdev_priv *np = netdev_priv(dev);
13166 	struct i40e_vsi *vsi = np->vsi;
13167 	struct i40e_pf *pf = vsi->back;
13168 	struct i40e_veb *veb;
13169 
13170 	/* Only for PF VSI for now */
13171 	if (vsi->type != I40E_VSI_MAIN)
13172 		return -EOPNOTSUPP;
13173 
13174 	/* Find the HW bridge for the PF VSI */
13175 	veb = i40e_pf_get_veb_by_seid(pf, vsi->uplink_seid);
13176 	if (!veb)
13177 		return 0;
13178 
13179 	return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
13180 				       0, 0, nlflags, filter_mask, NULL);
13181 }
13182 
13183 /**
13184  * i40e_features_check - Validate encapsulated packet conforms to limits
13185  * @skb: skb buff
13186  * @dev: This physical port's netdev
13187  * @features: Offload features that the stack believes apply
13188  **/
13189 static netdev_features_t i40e_features_check(struct sk_buff *skb,
13190 					     struct net_device *dev,
13191 					     netdev_features_t features)
13192 {
13193 	size_t len;
13194 
13195 	/* No point in doing any of this if neither checksum nor GSO are
13196 	 * being requested for this frame.  We can rule out both by just
13197 	 * checking for CHECKSUM_PARTIAL
13198 	 */
13199 	if (skb->ip_summed != CHECKSUM_PARTIAL)
13200 		return features;
13201 
13202 	/* We cannot support GSO if the MSS is going to be less than
13203 	 * 64 bytes.  If it is then we need to drop support for GSO.
13204 	 */
13205 	if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
13206 		features &= ~NETIF_F_GSO_MASK;
13207 
13208 	/* MACLEN can support at most 63 words */
13209 	len = skb_network_offset(skb);
13210 	if (len & ~(63 * 2))
13211 		goto out_err;
13212 
13213 	/* IPLEN and EIPLEN can support at most 127 dwords */
13214 	len = skb_network_header_len(skb);
13215 	if (len & ~(127 * 4))
13216 		goto out_err;
13217 
13218 	if (skb->encapsulation) {
13219 		/* L4TUNLEN can support 127 words */
13220 		len = skb_inner_network_header(skb) - skb_transport_header(skb);
13221 		if (len & ~(127 * 2))
13222 			goto out_err;
13223 
13224 		/* IPLEN can support at most 127 dwords */
13225 		len = skb_inner_transport_header(skb) -
13226 		      skb_inner_network_header(skb);
13227 		if (len & ~(127 * 4))
13228 			goto out_err;
13229 	}
13230 
13231 	/* No need to validate L4LEN as TCP is the only protocol with a
13232 	 * flexible value and we support all possible values supported
13233 	 * by TCP, which is at most 15 dwords
13234 	 */
13235 
13236 	return features;
13237 out_err:
13238 	return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
13239 }
13240 
13241 /**
13242  * i40e_xdp_setup - add/remove an XDP program
13243  * @vsi: VSI to changed
13244  * @prog: XDP program
13245  * @extack: netlink extended ack
13246  **/
13247 static int i40e_xdp_setup(struct i40e_vsi *vsi, struct bpf_prog *prog,
13248 			  struct netlink_ext_ack *extack)
13249 {
13250 	int frame_size = i40e_max_vsi_frame_size(vsi, prog);
13251 	struct i40e_pf *pf = vsi->back;
13252 	struct bpf_prog *old_prog;
13253 	bool need_reset;
13254 	int i;
13255 
13256 	/* VSI shall be deleted in a moment, block loading new programs */
13257 	if (prog && test_bit(__I40E_IN_REMOVE, pf->state))
13258 		return -EINVAL;
13259 
13260 	/* Don't allow frames that span over multiple buffers */
13261 	if (vsi->netdev->mtu > frame_size - I40E_PACKET_HDR_PAD) {
13262 		NL_SET_ERR_MSG_MOD(extack, "MTU too large for linear frames and XDP prog does not support frags");
13263 		return -EINVAL;
13264 	}
13265 
13266 	/* When turning XDP on->off/off->on we reset and rebuild the rings. */
13267 	need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
13268 	if (need_reset)
13269 		i40e_prep_for_reset(pf);
13270 
13271 	old_prog = xchg(&vsi->xdp_prog, prog);
13272 
13273 	if (need_reset) {
13274 		if (!prog) {
13275 			xdp_features_clear_redirect_target(vsi->netdev);
13276 			/* Wait until ndo_xsk_wakeup completes. */
13277 			synchronize_rcu();
13278 		}
13279 		i40e_reset_and_rebuild(pf, true, true);
13280 	}
13281 
13282 	if (!i40e_enabled_xdp_vsi(vsi) && prog) {
13283 		if (i40e_realloc_rx_bi_zc(vsi, true))
13284 			return -ENOMEM;
13285 	} else if (i40e_enabled_xdp_vsi(vsi) && !prog) {
13286 		if (i40e_realloc_rx_bi_zc(vsi, false))
13287 			return -ENOMEM;
13288 	}
13289 
13290 	for (i = 0; i < vsi->num_queue_pairs; i++)
13291 		WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
13292 
13293 	if (old_prog)
13294 		bpf_prog_put(old_prog);
13295 
13296 	/* Kick start the NAPI context if there is an AF_XDP socket open
13297 	 * on that queue id. This so that receiving will start.
13298 	 */
13299 	if (need_reset && prog) {
13300 		for (i = 0; i < vsi->num_queue_pairs; i++)
13301 			if (vsi->xdp_rings[i]->xsk_pool)
13302 				(void)i40e_xsk_wakeup(vsi->netdev, i,
13303 						      XDP_WAKEUP_RX);
13304 		xdp_features_set_redirect_target(vsi->netdev, true);
13305 	}
13306 
13307 	return 0;
13308 }
13309 
13310 /**
13311  * i40e_enter_busy_conf - Enters busy config state
13312  * @vsi: vsi
13313  *
13314  * Returns 0 on success, <0 for failure.
13315  **/
13316 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
13317 {
13318 	struct i40e_pf *pf = vsi->back;
13319 	int timeout = 50;
13320 
13321 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
13322 		timeout--;
13323 		if (!timeout)
13324 			return -EBUSY;
13325 		usleep_range(1000, 2000);
13326 	}
13327 
13328 	return 0;
13329 }
13330 
13331 /**
13332  * i40e_exit_busy_conf - Exits busy config state
13333  * @vsi: vsi
13334  **/
13335 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
13336 {
13337 	struct i40e_pf *pf = vsi->back;
13338 
13339 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
13340 }
13341 
13342 /**
13343  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
13344  * @vsi: vsi
13345  * @queue_pair: queue pair
13346  **/
13347 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
13348 {
13349 	memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
13350 	       sizeof(vsi->rx_rings[queue_pair]->rx_stats));
13351 	memset(&vsi->tx_rings[queue_pair]->stats, 0,
13352 	       sizeof(vsi->tx_rings[queue_pair]->stats));
13353 	if (i40e_enabled_xdp_vsi(vsi)) {
13354 		memset(&vsi->xdp_rings[queue_pair]->stats, 0,
13355 		       sizeof(vsi->xdp_rings[queue_pair]->stats));
13356 	}
13357 }
13358 
13359 /**
13360  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
13361  * @vsi: vsi
13362  * @queue_pair: queue pair
13363  **/
13364 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
13365 {
13366 	i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
13367 	if (i40e_enabled_xdp_vsi(vsi)) {
13368 		/* Make sure that in-progress ndo_xdp_xmit calls are
13369 		 * completed.
13370 		 */
13371 		synchronize_rcu();
13372 		i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
13373 	}
13374 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13375 }
13376 
13377 /**
13378  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
13379  * @vsi: vsi
13380  * @queue_pair: queue pair
13381  * @enable: true for enable, false for disable
13382  **/
13383 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
13384 					bool enable)
13385 {
13386 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13387 	struct i40e_q_vector *q_vector = rxr->q_vector;
13388 
13389 	if (!vsi->netdev)
13390 		return;
13391 
13392 	/* All rings in a qp belong to the same qvector. */
13393 	if (q_vector->rx.ring || q_vector->tx.ring) {
13394 		if (enable)
13395 			napi_enable(&q_vector->napi);
13396 		else
13397 			napi_disable(&q_vector->napi);
13398 	}
13399 }
13400 
13401 /**
13402  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
13403  * @vsi: vsi
13404  * @queue_pair: queue pair
13405  * @enable: true for enable, false for disable
13406  *
13407  * Returns 0 on success, <0 on failure.
13408  **/
13409 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
13410 					bool enable)
13411 {
13412 	struct i40e_pf *pf = vsi->back;
13413 	int pf_q, ret = 0;
13414 
13415 	pf_q = vsi->base_queue + queue_pair;
13416 	ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
13417 				     false /*is xdp*/, enable);
13418 	if (ret) {
13419 		dev_info(&pf->pdev->dev,
13420 			 "VSI seid %d Tx ring %d %sable timeout\n",
13421 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13422 		return ret;
13423 	}
13424 
13425 	i40e_control_rx_q(pf, pf_q, enable);
13426 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
13427 	if (ret) {
13428 		dev_info(&pf->pdev->dev,
13429 			 "VSI seid %d Rx ring %d %sable timeout\n",
13430 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13431 		return ret;
13432 	}
13433 
13434 	/* Due to HW errata, on Rx disable only, the register can
13435 	 * indicate done before it really is. Needs 50ms to be sure
13436 	 */
13437 	if (!enable)
13438 		mdelay(50);
13439 
13440 	if (!i40e_enabled_xdp_vsi(vsi))
13441 		return ret;
13442 
13443 	ret = i40e_control_wait_tx_q(vsi->seid, pf,
13444 				     pf_q + vsi->alloc_queue_pairs,
13445 				     true /*is xdp*/, enable);
13446 	if (ret) {
13447 		dev_info(&pf->pdev->dev,
13448 			 "VSI seid %d XDP Tx ring %d %sable timeout\n",
13449 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13450 	}
13451 
13452 	return ret;
13453 }
13454 
13455 /**
13456  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
13457  * @vsi: vsi
13458  * @queue_pair: queue_pair
13459  **/
13460 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
13461 {
13462 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13463 	struct i40e_pf *pf = vsi->back;
13464 	struct i40e_hw *hw = &pf->hw;
13465 
13466 	/* All rings in a qp belong to the same qvector. */
13467 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
13468 		i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
13469 	else
13470 		i40e_irq_dynamic_enable_icr0(pf);
13471 
13472 	i40e_flush(hw);
13473 }
13474 
13475 /**
13476  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
13477  * @vsi: vsi
13478  * @queue_pair: queue_pair
13479  **/
13480 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
13481 {
13482 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13483 	struct i40e_pf *pf = vsi->back;
13484 	struct i40e_hw *hw = &pf->hw;
13485 
13486 	/* For simplicity, instead of removing the qp interrupt causes
13487 	 * from the interrupt linked list, we simply disable the interrupt, and
13488 	 * leave the list intact.
13489 	 *
13490 	 * All rings in a qp belong to the same qvector.
13491 	 */
13492 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
13493 		u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
13494 
13495 		wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
13496 		i40e_flush(hw);
13497 		synchronize_irq(pf->msix_entries[intpf].vector);
13498 	} else {
13499 		/* Legacy and MSI mode - this stops all interrupt handling */
13500 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
13501 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
13502 		i40e_flush(hw);
13503 		synchronize_irq(pf->pdev->irq);
13504 	}
13505 }
13506 
13507 /**
13508  * i40e_queue_pair_disable - Disables a queue pair
13509  * @vsi: vsi
13510  * @queue_pair: queue pair
13511  *
13512  * Returns 0 on success, <0 on failure.
13513  **/
13514 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
13515 {
13516 	int err;
13517 
13518 	err = i40e_enter_busy_conf(vsi);
13519 	if (err)
13520 		return err;
13521 
13522 	i40e_queue_pair_disable_irq(vsi, queue_pair);
13523 	i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
13524 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
13525 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13526 	i40e_queue_pair_clean_rings(vsi, queue_pair);
13527 	i40e_queue_pair_reset_stats(vsi, queue_pair);
13528 
13529 	return err;
13530 }
13531 
13532 /**
13533  * i40e_queue_pair_enable - Enables a queue pair
13534  * @vsi: vsi
13535  * @queue_pair: queue pair
13536  *
13537  * Returns 0 on success, <0 on failure.
13538  **/
13539 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
13540 {
13541 	int err;
13542 
13543 	err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
13544 	if (err)
13545 		return err;
13546 
13547 	if (i40e_enabled_xdp_vsi(vsi)) {
13548 		err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
13549 		if (err)
13550 			return err;
13551 	}
13552 
13553 	err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
13554 	if (err)
13555 		return err;
13556 
13557 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
13558 	i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
13559 	i40e_queue_pair_enable_irq(vsi, queue_pair);
13560 
13561 	i40e_exit_busy_conf(vsi);
13562 
13563 	return err;
13564 }
13565 
13566 /**
13567  * i40e_xdp - implements ndo_bpf for i40e
13568  * @dev: netdevice
13569  * @xdp: XDP command
13570  **/
13571 static int i40e_xdp(struct net_device *dev,
13572 		    struct netdev_bpf *xdp)
13573 {
13574 	struct i40e_netdev_priv *np = netdev_priv(dev);
13575 	struct i40e_vsi *vsi = np->vsi;
13576 
13577 	if (vsi->type != I40E_VSI_MAIN)
13578 		return -EINVAL;
13579 
13580 	switch (xdp->command) {
13581 	case XDP_SETUP_PROG:
13582 		return i40e_xdp_setup(vsi, xdp->prog, xdp->extack);
13583 	case XDP_SETUP_XSK_POOL:
13584 		return i40e_xsk_pool_setup(vsi, xdp->xsk.pool,
13585 					   xdp->xsk.queue_id);
13586 	default:
13587 		return -EINVAL;
13588 	}
13589 }
13590 
13591 static const struct net_device_ops i40e_netdev_ops = {
13592 	.ndo_open		= i40e_open,
13593 	.ndo_stop		= i40e_close,
13594 	.ndo_start_xmit		= i40e_lan_xmit_frame,
13595 	.ndo_get_stats64	= i40e_get_netdev_stats_struct,
13596 	.ndo_set_rx_mode	= i40e_set_rx_mode,
13597 	.ndo_validate_addr	= eth_validate_addr,
13598 	.ndo_set_mac_address	= i40e_set_mac,
13599 	.ndo_change_mtu		= i40e_change_mtu,
13600 	.ndo_tx_timeout		= i40e_tx_timeout,
13601 	.ndo_vlan_rx_add_vid	= i40e_vlan_rx_add_vid,
13602 	.ndo_vlan_rx_kill_vid	= i40e_vlan_rx_kill_vid,
13603 #ifdef CONFIG_NET_POLL_CONTROLLER
13604 	.ndo_poll_controller	= i40e_netpoll,
13605 #endif
13606 	.ndo_setup_tc		= __i40e_setup_tc,
13607 	.ndo_select_queue	= i40e_lan_select_queue,
13608 	.ndo_set_features	= i40e_set_features,
13609 	.ndo_set_vf_mac		= i40e_ndo_set_vf_mac,
13610 	.ndo_set_vf_vlan	= i40e_ndo_set_vf_port_vlan,
13611 	.ndo_get_vf_stats	= i40e_get_vf_stats,
13612 	.ndo_set_vf_rate	= i40e_ndo_set_vf_bw,
13613 	.ndo_get_vf_config	= i40e_ndo_get_vf_config,
13614 	.ndo_set_vf_link_state	= i40e_ndo_set_vf_link_state,
13615 	.ndo_set_vf_spoofchk	= i40e_ndo_set_vf_spoofchk,
13616 	.ndo_set_vf_trust	= i40e_ndo_set_vf_trust,
13617 	.ndo_get_phys_port_id	= i40e_get_phys_port_id,
13618 	.ndo_fdb_add		= i40e_ndo_fdb_add,
13619 	.ndo_features_check	= i40e_features_check,
13620 	.ndo_bridge_getlink	= i40e_ndo_bridge_getlink,
13621 	.ndo_bridge_setlink	= i40e_ndo_bridge_setlink,
13622 	.ndo_bpf		= i40e_xdp,
13623 	.ndo_xdp_xmit		= i40e_xdp_xmit,
13624 	.ndo_xsk_wakeup	        = i40e_xsk_wakeup,
13625 	.ndo_dfwd_add_station	= i40e_fwd_add,
13626 	.ndo_dfwd_del_station	= i40e_fwd_del,
13627 	.ndo_hwtstamp_get	= i40e_ptp_hwtstamp_get,
13628 	.ndo_hwtstamp_set	= i40e_ptp_hwtstamp_set,
13629 };
13630 
13631 /**
13632  * i40e_config_netdev - Setup the netdev flags
13633  * @vsi: the VSI being configured
13634  *
13635  * Returns 0 on success, negative value on failure
13636  **/
13637 static int i40e_config_netdev(struct i40e_vsi *vsi)
13638 {
13639 	struct i40e_pf *pf = vsi->back;
13640 	struct i40e_hw *hw = &pf->hw;
13641 	struct i40e_netdev_priv *np;
13642 	struct net_device *netdev;
13643 	u8 broadcast[ETH_ALEN];
13644 	u8 mac_addr[ETH_ALEN];
13645 	int etherdev_size;
13646 	netdev_features_t hw_enc_features;
13647 	netdev_features_t hw_features;
13648 
13649 	etherdev_size = sizeof(struct i40e_netdev_priv);
13650 	netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
13651 	if (!netdev)
13652 		return -ENOMEM;
13653 
13654 	vsi->netdev = netdev;
13655 	np = netdev_priv(netdev);
13656 	np->vsi = vsi;
13657 
13658 	hw_enc_features = NETIF_F_SG			|
13659 			  NETIF_F_HW_CSUM		|
13660 			  NETIF_F_HIGHDMA		|
13661 			  NETIF_F_SOFT_FEATURES		|
13662 			  NETIF_F_TSO			|
13663 			  NETIF_F_TSO_ECN		|
13664 			  NETIF_F_TSO6			|
13665 			  NETIF_F_GSO_GRE		|
13666 			  NETIF_F_GSO_GRE_CSUM		|
13667 			  NETIF_F_GSO_PARTIAL		|
13668 			  NETIF_F_GSO_IPXIP4		|
13669 			  NETIF_F_GSO_IPXIP6		|
13670 			  NETIF_F_GSO_UDP_TUNNEL	|
13671 			  NETIF_F_GSO_UDP_TUNNEL_CSUM	|
13672 			  NETIF_F_GSO_UDP_L4		|
13673 			  NETIF_F_SCTP_CRC		|
13674 			  NETIF_F_RXHASH		|
13675 			  NETIF_F_RXCSUM		|
13676 			  0;
13677 
13678 	if (!test_bit(I40E_HW_CAP_OUTER_UDP_CSUM, pf->hw.caps))
13679 		netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
13680 
13681 	netdev->udp_tunnel_nic_info = &pf->udp_tunnel_nic;
13682 
13683 	netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
13684 
13685 	netdev->hw_enc_features |= hw_enc_features;
13686 
13687 	/* record features VLANs can make use of */
13688 	netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
13689 
13690 #define I40E_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE |		\
13691 				   NETIF_F_GSO_GRE_CSUM |	\
13692 				   NETIF_F_GSO_IPXIP4 |		\
13693 				   NETIF_F_GSO_IPXIP6 |		\
13694 				   NETIF_F_GSO_UDP_TUNNEL |	\
13695 				   NETIF_F_GSO_UDP_TUNNEL_CSUM)
13696 
13697 	netdev->gso_partial_features = I40E_GSO_PARTIAL_FEATURES;
13698 	netdev->features |= NETIF_F_GSO_PARTIAL |
13699 			    I40E_GSO_PARTIAL_FEATURES;
13700 
13701 	netdev->mpls_features |= NETIF_F_SG;
13702 	netdev->mpls_features |= NETIF_F_HW_CSUM;
13703 	netdev->mpls_features |= NETIF_F_TSO;
13704 	netdev->mpls_features |= NETIF_F_TSO6;
13705 	netdev->mpls_features |= I40E_GSO_PARTIAL_FEATURES;
13706 
13707 	/* enable macvlan offloads */
13708 	netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
13709 
13710 	hw_features = hw_enc_features		|
13711 		      NETIF_F_HW_VLAN_CTAG_TX	|
13712 		      NETIF_F_HW_VLAN_CTAG_RX;
13713 
13714 	if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
13715 		hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
13716 
13717 	netdev->hw_features |= hw_features | NETIF_F_LOOPBACK;
13718 
13719 	netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
13720 	netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
13721 
13722 	netdev->features &= ~NETIF_F_HW_TC;
13723 
13724 	if (vsi->type == I40E_VSI_MAIN) {
13725 		SET_NETDEV_DEV(netdev, &pf->pdev->dev);
13726 		ether_addr_copy(mac_addr, hw->mac.perm_addr);
13727 		/* The following steps are necessary for two reasons. First,
13728 		 * some older NVM configurations load a default MAC-VLAN
13729 		 * filter that will accept any tagged packet, and we want to
13730 		 * replace this with a normal filter. Additionally, it is
13731 		 * possible our MAC address was provided by the platform using
13732 		 * Open Firmware or similar.
13733 		 *
13734 		 * Thus, we need to remove the default filter and install one
13735 		 * specific to the MAC address.
13736 		 */
13737 		i40e_rm_default_mac_filter(vsi, mac_addr);
13738 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13739 		i40e_add_mac_filter(vsi, mac_addr);
13740 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13741 
13742 		netdev->xdp_features = NETDEV_XDP_ACT_BASIC |
13743 				       NETDEV_XDP_ACT_REDIRECT |
13744 				       NETDEV_XDP_ACT_XSK_ZEROCOPY |
13745 				       NETDEV_XDP_ACT_RX_SG;
13746 		netdev->xdp_zc_max_segs = I40E_MAX_BUFFER_TXD;
13747 	} else {
13748 		/* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
13749 		 * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
13750 		 * the end, which is 4 bytes long, so force truncation of the
13751 		 * original name by IFNAMSIZ - 4
13752 		 */
13753 		struct i40e_vsi *main_vsi = i40e_pf_get_main_vsi(pf);
13754 
13755 		snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d", IFNAMSIZ - 4,
13756 			 main_vsi->netdev->name);
13757 		eth_random_addr(mac_addr);
13758 
13759 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13760 		i40e_add_mac_filter(vsi, mac_addr);
13761 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13762 	}
13763 
13764 	/* Add the broadcast filter so that we initially will receive
13765 	 * broadcast packets. Note that when a new VLAN is first added the
13766 	 * driver will convert all filters marked I40E_VLAN_ANY into VLAN
13767 	 * specific filters as part of transitioning into "vlan" operation.
13768 	 * When more VLANs are added, the driver will copy each existing MAC
13769 	 * filter and add it for the new VLAN.
13770 	 *
13771 	 * Broadcast filters are handled specially by
13772 	 * i40e_sync_filters_subtask, as the driver must to set the broadcast
13773 	 * promiscuous bit instead of adding this directly as a MAC/VLAN
13774 	 * filter. The subtask will update the correct broadcast promiscuous
13775 	 * bits as VLANs become active or inactive.
13776 	 */
13777 	eth_broadcast_addr(broadcast);
13778 	spin_lock_bh(&vsi->mac_filter_hash_lock);
13779 	i40e_add_mac_filter(vsi, broadcast);
13780 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
13781 
13782 	eth_hw_addr_set(netdev, mac_addr);
13783 	ether_addr_copy(netdev->perm_addr, mac_addr);
13784 
13785 	/* i40iw_net_event() reads 16 bytes from neigh->primary_key */
13786 	netdev->neigh_priv_len = sizeof(u32) * 4;
13787 
13788 	netdev->priv_flags |= IFF_UNICAST_FLT;
13789 	/* Setup netdev TC information */
13790 	i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
13791 
13792 	netdev->netdev_ops = &i40e_netdev_ops;
13793 	netdev->watchdog_timeo = 5 * HZ;
13794 	i40e_set_ethtool_ops(netdev);
13795 
13796 	/* MTU range: 68 - 9706 */
13797 	netdev->min_mtu = ETH_MIN_MTU;
13798 	netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13799 
13800 	return 0;
13801 }
13802 
13803 /**
13804  * i40e_vsi_delete - Delete a VSI from the switch
13805  * @vsi: the VSI being removed
13806  *
13807  * Returns 0 on success, negative value on failure
13808  **/
13809 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13810 {
13811 	/* remove default VSI is not allowed */
13812 	if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13813 		return;
13814 
13815 	i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13816 }
13817 
13818 /**
13819  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13820  * @vsi: the VSI being queried
13821  *
13822  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13823  **/
13824 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13825 {
13826 	struct i40e_veb *veb;
13827 	struct i40e_pf *pf = vsi->back;
13828 
13829 	/* Uplink is not a bridge so default to VEB */
13830 	if (vsi->veb_idx >= I40E_MAX_VEB)
13831 		return 1;
13832 
13833 	veb = pf->veb[vsi->veb_idx];
13834 	if (!veb) {
13835 		dev_info(&pf->pdev->dev,
13836 			 "There is no veb associated with the bridge\n");
13837 		return -ENOENT;
13838 	}
13839 
13840 	/* Uplink is a bridge in VEPA mode */
13841 	if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13842 		return 0;
13843 	} else {
13844 		/* Uplink is a bridge in VEB mode */
13845 		return 1;
13846 	}
13847 
13848 	/* VEPA is now default bridge, so return 0 */
13849 	return 0;
13850 }
13851 
13852 /**
13853  * i40e_add_vsi - Add a VSI to the switch
13854  * @vsi: the VSI being configured
13855  *
13856  * This initializes a VSI context depending on the VSI type to be added and
13857  * passes it down to the add_vsi aq command.
13858  **/
13859 static int i40e_add_vsi(struct i40e_vsi *vsi)
13860 {
13861 	int ret = -ENODEV;
13862 	struct i40e_pf *pf = vsi->back;
13863 	struct i40e_hw *hw = &pf->hw;
13864 	struct i40e_vsi_context ctxt;
13865 	struct i40e_mac_filter *f;
13866 	struct hlist_node *h;
13867 	int bkt;
13868 
13869 	u8 enabled_tc = 0x1; /* TC0 enabled */
13870 	int f_count = 0;
13871 
13872 	memset(&ctxt, 0, sizeof(ctxt));
13873 	switch (vsi->type) {
13874 	case I40E_VSI_MAIN:
13875 		/* The PF's main VSI is already setup as part of the
13876 		 * device initialization, so we'll not bother with
13877 		 * the add_vsi call, but we will retrieve the current
13878 		 * VSI context.
13879 		 */
13880 		ctxt.seid = pf->main_vsi_seid;
13881 		ctxt.pf_num = pf->hw.pf_id;
13882 		ctxt.vf_num = 0;
13883 		ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13884 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13885 		if (ret) {
13886 			dev_info(&pf->pdev->dev,
13887 				 "couldn't get PF vsi config, err %pe aq_err %s\n",
13888 				 ERR_PTR(ret),
13889 				 libie_aq_str(pf->hw.aq.asq_last_status));
13890 			return -ENOENT;
13891 		}
13892 		vsi->info = ctxt.info;
13893 		vsi->info.valid_sections = 0;
13894 
13895 		vsi->seid = ctxt.seid;
13896 		vsi->id = ctxt.vsi_number;
13897 
13898 		enabled_tc = i40e_pf_get_tc_map(pf);
13899 
13900 		/* Source pruning is enabled by default, so the flag is
13901 		 * negative logic - if it's set, we need to fiddle with
13902 		 * the VSI to disable source pruning.
13903 		 */
13904 		if (test_bit(I40E_FLAG_SOURCE_PRUNING_DIS, pf->flags)) {
13905 			memset(&ctxt, 0, sizeof(ctxt));
13906 			ctxt.seid = pf->main_vsi_seid;
13907 			ctxt.pf_num = pf->hw.pf_id;
13908 			ctxt.vf_num = 0;
13909 			ctxt.info.valid_sections |=
13910 				     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13911 			ctxt.info.switch_id =
13912 				   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13913 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13914 			if (ret) {
13915 				dev_info(&pf->pdev->dev,
13916 					 "update vsi failed, err %d aq_err %s\n",
13917 					 ret,
13918 					 libie_aq_str(pf->hw.aq.asq_last_status));
13919 				ret = -ENOENT;
13920 				goto err;
13921 			}
13922 		}
13923 
13924 		/* MFP mode setup queue map and update VSI */
13925 		if (test_bit(I40E_FLAG_MFP_ENA, pf->flags) &&
13926 		    !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
13927 			memset(&ctxt, 0, sizeof(ctxt));
13928 			ctxt.seid = pf->main_vsi_seid;
13929 			ctxt.pf_num = pf->hw.pf_id;
13930 			ctxt.vf_num = 0;
13931 			i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
13932 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13933 			if (ret) {
13934 				dev_info(&pf->pdev->dev,
13935 					 "update vsi failed, err %pe aq_err %s\n",
13936 					 ERR_PTR(ret),
13937 					 libie_aq_str(pf->hw.aq.asq_last_status));
13938 				ret = -ENOENT;
13939 				goto err;
13940 			}
13941 			/* update the local VSI info queue map */
13942 			i40e_vsi_update_queue_map(vsi, &ctxt);
13943 			vsi->info.valid_sections = 0;
13944 		} else {
13945 			/* Default/Main VSI is only enabled for TC0
13946 			 * reconfigure it to enable all TCs that are
13947 			 * available on the port in SFP mode.
13948 			 * For MFP case the iSCSI PF would use this
13949 			 * flow to enable LAN+iSCSI TC.
13950 			 */
13951 			ret = i40e_vsi_config_tc(vsi, enabled_tc);
13952 			if (ret) {
13953 				/* Single TC condition is not fatal,
13954 				 * message and continue
13955 				 */
13956 				dev_info(&pf->pdev->dev,
13957 					 "failed to configure TCs for main VSI tc_map 0x%08x, err %pe aq_err %s\n",
13958 					 enabled_tc,
13959 					 ERR_PTR(ret),
13960 					 libie_aq_str(pf->hw.aq.asq_last_status));
13961 			}
13962 		}
13963 		break;
13964 
13965 	case I40E_VSI_FDIR:
13966 		ctxt.pf_num = hw->pf_id;
13967 		ctxt.vf_num = 0;
13968 		ctxt.uplink_seid = vsi->uplink_seid;
13969 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13970 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13971 		if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags) &&
13972 		    (i40e_is_vsi_uplink_mode_veb(vsi))) {
13973 			ctxt.info.valid_sections |=
13974 			     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13975 			ctxt.info.switch_id =
13976 			   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13977 		}
13978 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13979 		break;
13980 
13981 	case I40E_VSI_VMDQ2:
13982 		ctxt.pf_num = hw->pf_id;
13983 		ctxt.vf_num = 0;
13984 		ctxt.uplink_seid = vsi->uplink_seid;
13985 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13986 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
13987 
13988 		/* This VSI is connected to VEB so the switch_id
13989 		 * should be set to zero by default.
13990 		 */
13991 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13992 			ctxt.info.valid_sections |=
13993 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13994 			ctxt.info.switch_id =
13995 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13996 		}
13997 
13998 		/* Setup the VSI tx/rx queue map for TC0 only for now */
13999 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14000 		break;
14001 
14002 	case I40E_VSI_SRIOV:
14003 		ctxt.pf_num = hw->pf_id;
14004 		ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
14005 		ctxt.uplink_seid = vsi->uplink_seid;
14006 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14007 		ctxt.flags = I40E_AQ_VSI_TYPE_VF;
14008 
14009 		/* This VSI is connected to VEB so the switch_id
14010 		 * should be set to zero by default.
14011 		 */
14012 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14013 			ctxt.info.valid_sections |=
14014 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14015 			ctxt.info.switch_id =
14016 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14017 		}
14018 
14019 		if (test_bit(I40E_FLAG_IWARP_ENA, vsi->back->flags)) {
14020 			ctxt.info.valid_sections |=
14021 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
14022 			ctxt.info.queueing_opt_flags |=
14023 				(I40E_AQ_VSI_QUE_OPT_TCP_ENA |
14024 				 I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
14025 		}
14026 
14027 		ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
14028 		ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
14029 		if (pf->vf[vsi->vf_id].spoofchk) {
14030 			ctxt.info.valid_sections |=
14031 				cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
14032 			ctxt.info.sec_flags |=
14033 				(I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
14034 				 I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
14035 		}
14036 		/* Setup the VSI tx/rx queue map for TC0 only for now */
14037 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14038 		break;
14039 
14040 	case I40E_VSI_IWARP:
14041 		/* send down message to iWARP */
14042 		break;
14043 
14044 	default:
14045 		return -ENODEV;
14046 	}
14047 
14048 	if (vsi->type != I40E_VSI_MAIN) {
14049 		ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
14050 		if (ret) {
14051 			dev_info(&vsi->back->pdev->dev,
14052 				 "add vsi failed, err %pe aq_err %s\n",
14053 				 ERR_PTR(ret),
14054 				 libie_aq_str(pf->hw.aq.asq_last_status));
14055 			ret = -ENOENT;
14056 			goto err;
14057 		}
14058 		vsi->info = ctxt.info;
14059 		vsi->info.valid_sections = 0;
14060 		vsi->seid = ctxt.seid;
14061 		vsi->id = ctxt.vsi_number;
14062 	}
14063 
14064 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14065 	vsi->active_filters = 0;
14066 	/* If macvlan filters already exist, force them to get loaded */
14067 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
14068 		f->state = I40E_FILTER_NEW;
14069 		f_count++;
14070 	}
14071 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14072 	clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
14073 
14074 	if (f_count) {
14075 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
14076 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
14077 	}
14078 
14079 	/* Update VSI BW information */
14080 	ret = i40e_vsi_get_bw_info(vsi);
14081 	if (ret) {
14082 		dev_info(&pf->pdev->dev,
14083 			 "couldn't get vsi bw info, err %pe aq_err %s\n",
14084 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
14085 		/* VSI is already added so not tearing that up */
14086 		ret = 0;
14087 	}
14088 
14089 err:
14090 	return ret;
14091 }
14092 
14093 /**
14094  * i40e_vsi_release - Delete a VSI and free its resources
14095  * @vsi: the VSI being removed
14096  *
14097  * Returns 0 on success or < 0 on error
14098  **/
14099 int i40e_vsi_release(struct i40e_vsi *vsi)
14100 {
14101 	struct i40e_mac_filter *f;
14102 	struct hlist_node *h;
14103 	struct i40e_veb *veb;
14104 	struct i40e_pf *pf;
14105 	u16 uplink_seid;
14106 	int i, n, bkt;
14107 
14108 	pf = vsi->back;
14109 
14110 	/* release of a VEB-owner or last VSI is not allowed */
14111 	if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
14112 		dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
14113 			 vsi->seid, vsi->uplink_seid);
14114 		return -ENODEV;
14115 	}
14116 	if (vsi->type == I40E_VSI_MAIN && !test_bit(__I40E_DOWN, pf->state)) {
14117 		dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
14118 		return -ENODEV;
14119 	}
14120 	set_bit(__I40E_VSI_RELEASING, vsi->state);
14121 	uplink_seid = vsi->uplink_seid;
14122 
14123 	if (vsi->type != I40E_VSI_SRIOV) {
14124 		if (vsi->netdev_registered) {
14125 			vsi->netdev_registered = false;
14126 			if (vsi->netdev) {
14127 				/* results in a call to i40e_close() */
14128 				unregister_netdev(vsi->netdev);
14129 			}
14130 		} else {
14131 			i40e_vsi_close(vsi);
14132 		}
14133 		i40e_vsi_disable_irq(vsi);
14134 	}
14135 
14136 	if (vsi->type == I40E_VSI_MAIN)
14137 		i40e_devlink_destroy_port(pf);
14138 
14139 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14140 
14141 	/* clear the sync flag on all filters */
14142 	if (vsi->netdev) {
14143 		__dev_uc_unsync(vsi->netdev, NULL);
14144 		__dev_mc_unsync(vsi->netdev, NULL);
14145 	}
14146 
14147 	/* make sure any remaining filters are marked for deletion */
14148 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
14149 		__i40e_del_filter(vsi, f);
14150 
14151 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14152 
14153 	i40e_sync_vsi_filters(vsi);
14154 
14155 	i40e_vsi_delete(vsi);
14156 	i40e_vsi_free_q_vectors(vsi);
14157 	if (vsi->netdev) {
14158 		free_netdev(vsi->netdev);
14159 		vsi->netdev = NULL;
14160 	}
14161 	i40e_vsi_clear_rings(vsi);
14162 	i40e_vsi_clear(vsi);
14163 
14164 	/* If this was the last thing on the VEB, except for the
14165 	 * controlling VSI, remove the VEB, which puts the controlling
14166 	 * VSI onto the uplink port.
14167 	 *
14168 	 * Well, okay, there's one more exception here: don't remove
14169 	 * the floating VEBs yet.  We'll wait for an explicit remove request
14170 	 * from up the network stack.
14171 	 */
14172 	veb = i40e_pf_get_veb_by_seid(pf, uplink_seid);
14173 	if (veb && veb->uplink_seid) {
14174 		n = 0;
14175 
14176 		/* Count non-controlling VSIs present on  the VEB */
14177 		i40e_pf_for_each_vsi(pf, i, vsi)
14178 			if (vsi->uplink_seid == uplink_seid &&
14179 			    (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14180 				n++;
14181 
14182 		/* If there is no VSI except the control one then release
14183 		 * the VEB and put the control VSI onto VEB uplink.
14184 		 */
14185 		if (!n)
14186 			i40e_veb_release(veb);
14187 	}
14188 
14189 	return 0;
14190 }
14191 
14192 /**
14193  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
14194  * @vsi: ptr to the VSI
14195  *
14196  * This should only be called after i40e_vsi_mem_alloc() which allocates the
14197  * corresponding SW VSI structure and initializes num_queue_pairs for the
14198  * newly allocated VSI.
14199  *
14200  * Returns 0 on success or negative on failure
14201  **/
14202 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
14203 {
14204 	int ret = -ENOENT;
14205 	struct i40e_pf *pf = vsi->back;
14206 
14207 	if (vsi->q_vectors[0]) {
14208 		dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
14209 			 vsi->seid);
14210 		return -EEXIST;
14211 	}
14212 
14213 	if (vsi->base_vector) {
14214 		dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
14215 			 vsi->seid, vsi->base_vector);
14216 		return -EEXIST;
14217 	}
14218 
14219 	ret = i40e_vsi_alloc_q_vectors(vsi);
14220 	if (ret) {
14221 		dev_info(&pf->pdev->dev,
14222 			 "failed to allocate %d q_vector for VSI %d, ret=%d\n",
14223 			 vsi->num_q_vectors, vsi->seid, ret);
14224 		vsi->num_q_vectors = 0;
14225 		goto vector_setup_out;
14226 	}
14227 
14228 	/* In Legacy mode, we do not have to get any other vector since we
14229 	 * piggyback on the misc/ICR0 for queue interrupts.
14230 	*/
14231 	if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
14232 		return ret;
14233 	if (vsi->num_q_vectors)
14234 		vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
14235 						 vsi->num_q_vectors, vsi->idx);
14236 	if (vsi->base_vector < 0) {
14237 		dev_info(&pf->pdev->dev,
14238 			 "failed to get tracking for %d vectors for VSI %d, err=%d\n",
14239 			 vsi->num_q_vectors, vsi->seid, vsi->base_vector);
14240 		i40e_vsi_free_q_vectors(vsi);
14241 		ret = -ENOENT;
14242 		goto vector_setup_out;
14243 	}
14244 
14245 vector_setup_out:
14246 	return ret;
14247 }
14248 
14249 /**
14250  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
14251  * @vsi: pointer to the vsi.
14252  *
14253  * This re-allocates a vsi's queue resources.
14254  *
14255  * Returns pointer to the successfully allocated and configured VSI sw struct
14256  * on success, otherwise returns NULL on failure.
14257  **/
14258 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
14259 {
14260 	struct i40e_vsi *main_vsi;
14261 	u16 alloc_queue_pairs;
14262 	struct i40e_pf *pf;
14263 	int ret;
14264 
14265 	if (!vsi)
14266 		return NULL;
14267 
14268 	pf = vsi->back;
14269 
14270 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
14271 	i40e_vsi_clear_rings(vsi);
14272 
14273 	i40e_vsi_free_arrays(vsi, false);
14274 	i40e_set_num_rings_in_vsi(vsi);
14275 	ret = i40e_vsi_alloc_arrays(vsi, false);
14276 	if (ret)
14277 		goto err_vsi;
14278 
14279 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14280 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14281 
14282 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14283 	if (ret < 0) {
14284 		dev_info(&pf->pdev->dev,
14285 			 "failed to get tracking for %d queues for VSI %d err %d\n",
14286 			 alloc_queue_pairs, vsi->seid, ret);
14287 		goto err_vsi;
14288 	}
14289 	vsi->base_queue = ret;
14290 
14291 	/* Update the FW view of the VSI. Force a reset of TC and queue
14292 	 * layout configurations.
14293 	 */
14294 	main_vsi = i40e_pf_get_main_vsi(pf);
14295 	main_vsi->seid = pf->main_vsi_seid;
14296 	i40e_vsi_reconfig_tc(main_vsi);
14297 
14298 	if (vsi->type == I40E_VSI_MAIN)
14299 		i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
14300 
14301 	/* assign it some queues */
14302 	ret = i40e_alloc_rings(vsi);
14303 	if (ret)
14304 		goto err_rings;
14305 
14306 	/* map all of the rings to the q_vectors */
14307 	i40e_vsi_map_rings_to_vectors(vsi);
14308 	return vsi;
14309 
14310 err_rings:
14311 	i40e_vsi_free_q_vectors(vsi);
14312 	if (vsi->netdev_registered) {
14313 		vsi->netdev_registered = false;
14314 		unregister_netdev(vsi->netdev);
14315 		free_netdev(vsi->netdev);
14316 		vsi->netdev = NULL;
14317 	}
14318 	if (vsi->type == I40E_VSI_MAIN)
14319 		i40e_devlink_destroy_port(pf);
14320 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14321 err_vsi:
14322 	i40e_vsi_clear(vsi);
14323 	return NULL;
14324 }
14325 
14326 /**
14327  * i40e_vsi_setup - Set up a VSI by a given type
14328  * @pf: board private structure
14329  * @type: VSI type
14330  * @uplink_seid: the switch element to link to
14331  * @param1: usage depends upon VSI type. For VF types, indicates VF id
14332  *
14333  * This allocates the sw VSI structure and its queue resources, then add a VSI
14334  * to the identified VEB.
14335  *
14336  * Returns pointer to the successfully allocated and configure VSI sw struct on
14337  * success, otherwise returns NULL on failure.
14338  **/
14339 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
14340 				u16 uplink_seid, u32 param1)
14341 {
14342 	struct i40e_vsi *vsi = NULL;
14343 	struct i40e_veb *veb = NULL;
14344 	u16 alloc_queue_pairs;
14345 	int v_idx;
14346 	int ret;
14347 
14348 	/* The requested uplink_seid must be either
14349 	 *     - the PF's port seid
14350 	 *              no VEB is needed because this is the PF
14351 	 *              or this is a Flow Director special case VSI
14352 	 *     - seid of an existing VEB
14353 	 *     - seid of a VSI that owns an existing VEB
14354 	 *     - seid of a VSI that doesn't own a VEB
14355 	 *              a new VEB is created and the VSI becomes the owner
14356 	 *     - seid of the PF VSI, which is what creates the first VEB
14357 	 *              this is a special case of the previous
14358 	 *
14359 	 * Find which uplink_seid we were given and create a new VEB if needed
14360 	 */
14361 	veb = i40e_pf_get_veb_by_seid(pf, uplink_seid);
14362 	if (!veb && uplink_seid != pf->mac_seid) {
14363 		vsi = i40e_pf_get_vsi_by_seid(pf, uplink_seid);
14364 		if (!vsi) {
14365 			dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
14366 				 uplink_seid);
14367 			return NULL;
14368 		}
14369 
14370 		if (vsi->uplink_seid == pf->mac_seid)
14371 			veb = i40e_veb_setup(pf, pf->mac_seid, vsi->seid,
14372 					     vsi->tc_config.enabled_tc);
14373 		else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14374 			veb = i40e_veb_setup(pf, vsi->uplink_seid, vsi->seid,
14375 					     vsi->tc_config.enabled_tc);
14376 		if (veb) {
14377 			if (vsi->type != I40E_VSI_MAIN) {
14378 				dev_info(&vsi->back->pdev->dev,
14379 					 "New VSI creation error, uplink seid of LAN VSI expected.\n");
14380 				return NULL;
14381 			}
14382 			/* We come up by default in VEPA mode if SRIOV is not
14383 			 * already enabled, in which case we can't force VEPA
14384 			 * mode.
14385 			 */
14386 			if (!test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
14387 				veb->bridge_mode = BRIDGE_MODE_VEPA;
14388 				clear_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
14389 			}
14390 			i40e_config_bridge_mode(veb);
14391 		}
14392 		veb = i40e_pf_get_veb_by_seid(pf, vsi->uplink_seid);
14393 		if (!veb) {
14394 			dev_info(&pf->pdev->dev, "couldn't add VEB\n");
14395 			return NULL;
14396 		}
14397 
14398 		vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14399 		uplink_seid = veb->seid;
14400 	}
14401 
14402 	/* get vsi sw struct */
14403 	v_idx = i40e_vsi_mem_alloc(pf, type);
14404 	if (v_idx < 0)
14405 		goto err_alloc;
14406 	vsi = pf->vsi[v_idx];
14407 	if (!vsi)
14408 		goto err_alloc;
14409 	vsi->type = type;
14410 	vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
14411 
14412 	if (type == I40E_VSI_MAIN)
14413 		pf->lan_vsi = v_idx;
14414 	else if (type == I40E_VSI_SRIOV)
14415 		vsi->vf_id = param1;
14416 	/* assign it some queues */
14417 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14418 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14419 
14420 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14421 	if (ret < 0) {
14422 		dev_info(&pf->pdev->dev,
14423 			 "failed to get tracking for %d queues for VSI %d err=%d\n",
14424 			 alloc_queue_pairs, vsi->seid, ret);
14425 		goto err_vsi;
14426 	}
14427 	vsi->base_queue = ret;
14428 
14429 	/* get a VSI from the hardware */
14430 	vsi->uplink_seid = uplink_seid;
14431 	ret = i40e_add_vsi(vsi);
14432 	if (ret)
14433 		goto err_vsi;
14434 
14435 	switch (vsi->type) {
14436 	/* setup the netdev if needed */
14437 	case I40E_VSI_MAIN:
14438 	case I40E_VSI_VMDQ2:
14439 		ret = i40e_config_netdev(vsi);
14440 		if (ret)
14441 			goto err_netdev;
14442 		ret = i40e_netif_set_realnum_tx_rx_queues(vsi);
14443 		if (ret)
14444 			goto err_netdev;
14445 		if (vsi->type == I40E_VSI_MAIN) {
14446 			ret = i40e_devlink_create_port(pf);
14447 			if (ret)
14448 				goto err_netdev;
14449 			SET_NETDEV_DEVLINK_PORT(vsi->netdev, &pf->devlink_port);
14450 		}
14451 		ret = register_netdev(vsi->netdev);
14452 		if (ret)
14453 			goto err_dl_port;
14454 		vsi->netdev_registered = true;
14455 		netif_carrier_off(vsi->netdev);
14456 #ifdef CONFIG_I40E_DCB
14457 		/* Setup DCB netlink interface */
14458 		i40e_dcbnl_setup(vsi);
14459 #endif /* CONFIG_I40E_DCB */
14460 		fallthrough;
14461 	case I40E_VSI_FDIR:
14462 		/* set up vectors and rings if needed */
14463 		ret = i40e_vsi_setup_vectors(vsi);
14464 		if (ret)
14465 			goto err_msix;
14466 
14467 		ret = i40e_alloc_rings(vsi);
14468 		if (ret)
14469 			goto err_rings;
14470 
14471 		/* map all of the rings to the q_vectors */
14472 		i40e_vsi_map_rings_to_vectors(vsi);
14473 
14474 		i40e_vsi_reset_stats(vsi);
14475 		break;
14476 	default:
14477 		/* no netdev or rings for the other VSI types */
14478 		break;
14479 	}
14480 
14481 	if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps) &&
14482 	    vsi->type == I40E_VSI_VMDQ2) {
14483 		ret = i40e_vsi_config_rss(vsi);
14484 		if (ret)
14485 			goto err_config;
14486 	}
14487 	return vsi;
14488 
14489 err_config:
14490 	i40e_vsi_clear_rings(vsi);
14491 err_rings:
14492 	i40e_vsi_free_q_vectors(vsi);
14493 err_msix:
14494 	if (vsi->netdev_registered) {
14495 		vsi->netdev_registered = false;
14496 		unregister_netdev(vsi->netdev);
14497 		free_netdev(vsi->netdev);
14498 		vsi->netdev = NULL;
14499 	}
14500 err_dl_port:
14501 	if (vsi->type == I40E_VSI_MAIN)
14502 		i40e_devlink_destroy_port(pf);
14503 err_netdev:
14504 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14505 err_vsi:
14506 	i40e_vsi_clear(vsi);
14507 err_alloc:
14508 	return NULL;
14509 }
14510 
14511 /**
14512  * i40e_veb_get_bw_info - Query VEB BW information
14513  * @veb: the veb to query
14514  *
14515  * Query the Tx scheduler BW configuration data for given VEB
14516  **/
14517 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
14518 {
14519 	struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
14520 	struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
14521 	struct i40e_pf *pf = veb->pf;
14522 	struct i40e_hw *hw = &pf->hw;
14523 	u32 tc_bw_max;
14524 	int ret = 0;
14525 	int i;
14526 
14527 	ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
14528 						  &bw_data, NULL);
14529 	if (ret) {
14530 		dev_info(&pf->pdev->dev,
14531 			 "query veb bw config failed, err %pe aq_err %s\n",
14532 			 ERR_PTR(ret), libie_aq_str(hw->aq.asq_last_status));
14533 		goto out;
14534 	}
14535 
14536 	ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
14537 						   &ets_data, NULL);
14538 	if (ret) {
14539 		dev_info(&pf->pdev->dev,
14540 			 "query veb bw ets config failed, err %pe aq_err %s\n",
14541 			 ERR_PTR(ret), libie_aq_str(hw->aq.asq_last_status));
14542 		goto out;
14543 	}
14544 
14545 	veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
14546 	veb->bw_max_quanta = ets_data.tc_bw_max;
14547 	veb->is_abs_credits = bw_data.absolute_credits_enable;
14548 	veb->enabled_tc = ets_data.tc_valid_bits;
14549 	tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
14550 		    (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
14551 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
14552 		veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
14553 		veb->bw_tc_limit_credits[i] =
14554 					le16_to_cpu(bw_data.tc_bw_limits[i]);
14555 		veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
14556 	}
14557 
14558 out:
14559 	return ret;
14560 }
14561 
14562 /**
14563  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
14564  * @pf: board private structure
14565  *
14566  * On error: returns error code (negative)
14567  * On success: returns vsi index in PF (positive)
14568  **/
14569 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
14570 {
14571 	int ret = -ENOENT;
14572 	struct i40e_veb *veb;
14573 	int i;
14574 
14575 	/* Need to protect the allocation of switch elements at the PF level */
14576 	mutex_lock(&pf->switch_mutex);
14577 
14578 	/* VEB list may be fragmented if VEB creation/destruction has
14579 	 * been happening.  We can afford to do a quick scan to look
14580 	 * for any free slots in the list.
14581 	 *
14582 	 * find next empty veb slot, looping back around if necessary
14583 	 */
14584 	i = 0;
14585 	while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
14586 		i++;
14587 	if (i >= I40E_MAX_VEB) {
14588 		ret = -ENOMEM;
14589 		goto err_alloc_veb;  /* out of VEB slots! */
14590 	}
14591 
14592 	veb = kzalloc_obj(*veb);
14593 	if (!veb) {
14594 		ret = -ENOMEM;
14595 		goto err_alloc_veb;
14596 	}
14597 	veb->pf = pf;
14598 	veb->idx = i;
14599 	veb->enabled_tc = 1;
14600 
14601 	pf->veb[i] = veb;
14602 	ret = i;
14603 err_alloc_veb:
14604 	mutex_unlock(&pf->switch_mutex);
14605 	return ret;
14606 }
14607 
14608 /**
14609  * i40e_switch_branch_release - Delete a branch of the switch tree
14610  * @branch: where to start deleting
14611  *
14612  * This uses recursion to find the tips of the branch to be
14613  * removed, deleting until we get back to and can delete this VEB.
14614  **/
14615 static void i40e_switch_branch_release(struct i40e_veb *branch)
14616 {
14617 	struct i40e_pf *pf = branch->pf;
14618 	u16 branch_seid = branch->seid;
14619 	u16 veb_idx = branch->idx;
14620 	struct i40e_vsi *vsi;
14621 	struct i40e_veb *veb;
14622 	int i;
14623 
14624 	/* release any VEBs on this VEB - RECURSION */
14625 	i40e_pf_for_each_veb(pf, i, veb)
14626 		if (veb->uplink_seid == branch->seid)
14627 			i40e_switch_branch_release(veb);
14628 
14629 	/* Release the VSIs on this VEB, but not the owner VSI.
14630 	 *
14631 	 * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
14632 	 *       the VEB itself, so don't use (*branch) after this loop.
14633 	 */
14634 	i40e_pf_for_each_vsi(pf, i, vsi)
14635 		if (vsi->uplink_seid == branch_seid &&
14636 		    (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14637 			i40e_vsi_release(vsi);
14638 
14639 	/* There's one corner case where the VEB might not have been
14640 	 * removed, so double check it here and remove it if needed.
14641 	 * This case happens if the veb was created from the debugfs
14642 	 * commands and no VSIs were added to it.
14643 	 */
14644 	if (pf->veb[veb_idx])
14645 		i40e_veb_release(pf->veb[veb_idx]);
14646 }
14647 
14648 /**
14649  * i40e_veb_clear - remove veb struct
14650  * @veb: the veb to remove
14651  **/
14652 static void i40e_veb_clear(struct i40e_veb *veb)
14653 {
14654 	if (!veb)
14655 		return;
14656 
14657 	if (veb->pf) {
14658 		struct i40e_pf *pf = veb->pf;
14659 
14660 		mutex_lock(&pf->switch_mutex);
14661 		if (pf->veb[veb->idx] == veb)
14662 			pf->veb[veb->idx] = NULL;
14663 		mutex_unlock(&pf->switch_mutex);
14664 	}
14665 
14666 	kfree(veb);
14667 }
14668 
14669 /**
14670  * i40e_veb_release - Delete a VEB and free its resources
14671  * @veb: the VEB being removed
14672  **/
14673 void i40e_veb_release(struct i40e_veb *veb)
14674 {
14675 	struct i40e_vsi *vsi, *vsi_it;
14676 	struct i40e_pf *pf;
14677 	int i, n = 0;
14678 
14679 	pf = veb->pf;
14680 
14681 	/* find the remaining VSI and check for extras */
14682 	i40e_pf_for_each_vsi(pf, i, vsi_it)
14683 		if (vsi_it->uplink_seid == veb->seid) {
14684 			if (vsi_it->flags & I40E_VSI_FLAG_VEB_OWNER)
14685 				vsi = vsi_it;
14686 			n++;
14687 		}
14688 
14689 	/* Floating VEB has to be empty and regular one must have
14690 	 * single owner VSI.
14691 	 */
14692 	if ((veb->uplink_seid && n != 1) || (!veb->uplink_seid && n != 0)) {
14693 		dev_info(&pf->pdev->dev,
14694 			 "can't remove VEB %d with %d VSIs left\n",
14695 			 veb->seid, n);
14696 		return;
14697 	}
14698 
14699 	/* For regular VEB move the owner VSI to uplink port */
14700 	if (veb->uplink_seid) {
14701 		vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
14702 		vsi->uplink_seid = veb->uplink_seid;
14703 		vsi->veb_idx = I40E_NO_VEB;
14704 	}
14705 
14706 	i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14707 	i40e_veb_clear(veb);
14708 }
14709 
14710 /**
14711  * i40e_add_veb - create the VEB in the switch
14712  * @veb: the VEB to be instantiated
14713  * @vsi: the controlling VSI
14714  **/
14715 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
14716 {
14717 	struct i40e_pf *pf = veb->pf;
14718 	bool enable_stats = !!test_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags);
14719 	int ret;
14720 
14721 	ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi ? vsi->seid : 0,
14722 			      veb->enabled_tc, vsi ? false : true,
14723 			      &veb->seid, enable_stats, NULL);
14724 
14725 	/* get a VEB from the hardware */
14726 	if (ret) {
14727 		dev_info(&pf->pdev->dev,
14728 			 "couldn't add VEB, err %pe aq_err %s\n",
14729 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
14730 		return -EPERM;
14731 	}
14732 
14733 	/* get statistics counter */
14734 	ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
14735 					 &veb->stats_idx, NULL, NULL, NULL);
14736 	if (ret) {
14737 		dev_info(&pf->pdev->dev,
14738 			 "couldn't get VEB statistics idx, err %pe aq_err %s\n",
14739 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
14740 		return -EPERM;
14741 	}
14742 	ret = i40e_veb_get_bw_info(veb);
14743 	if (ret) {
14744 		dev_info(&pf->pdev->dev,
14745 			 "couldn't get VEB bw info, err %pe aq_err %s\n",
14746 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
14747 		i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14748 		return -ENOENT;
14749 	}
14750 
14751 	if (vsi) {
14752 		vsi->uplink_seid = veb->seid;
14753 		vsi->veb_idx = veb->idx;
14754 		vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14755 	}
14756 
14757 	return 0;
14758 }
14759 
14760 /**
14761  * i40e_veb_setup - Set up a VEB
14762  * @pf: board private structure
14763  * @uplink_seid: the switch element to link to
14764  * @vsi_seid: the initial VSI seid
14765  * @enabled_tc: Enabled TC bit-map
14766  *
14767  * This allocates the sw VEB structure and links it into the switch
14768  * It is possible and legal for this to be a duplicate of an already
14769  * existing VEB.  It is also possible for both uplink and vsi seids
14770  * to be zero, in order to create a floating VEB.
14771  *
14772  * Returns pointer to the successfully allocated VEB sw struct on
14773  * success, otherwise returns NULL on failure.
14774  **/
14775 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 uplink_seid,
14776 				u16 vsi_seid, u8 enabled_tc)
14777 {
14778 	struct i40e_vsi *vsi = NULL;
14779 	struct i40e_veb *veb;
14780 	int veb_idx;
14781 	int ret;
14782 
14783 	/* if one seid is 0, the other must be 0 to create a floating relay */
14784 	if ((uplink_seid == 0 || vsi_seid == 0) &&
14785 	    (uplink_seid + vsi_seid != 0)) {
14786 		dev_info(&pf->pdev->dev,
14787 			 "one, not both seid's are 0: uplink=%d vsi=%d\n",
14788 			 uplink_seid, vsi_seid);
14789 		return NULL;
14790 	}
14791 
14792 	/* make sure there is such a vsi and uplink */
14793 	if (vsi_seid) {
14794 		vsi = i40e_pf_get_vsi_by_seid(pf, vsi_seid);
14795 		if (!vsi) {
14796 			dev_err(&pf->pdev->dev, "vsi seid %d not found\n",
14797 				vsi_seid);
14798 			return NULL;
14799 		}
14800 	}
14801 
14802 	/* get veb sw struct */
14803 	veb_idx = i40e_veb_mem_alloc(pf);
14804 	if (veb_idx < 0)
14805 		goto err_alloc;
14806 	veb = pf->veb[veb_idx];
14807 	veb->uplink_seid = uplink_seid;
14808 	veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14809 
14810 	/* create the VEB in the switch */
14811 	ret = i40e_add_veb(veb, vsi);
14812 	if (ret)
14813 		goto err_veb;
14814 
14815 	if (vsi && vsi->idx == pf->lan_vsi)
14816 		pf->lan_veb = veb->idx;
14817 
14818 	return veb;
14819 
14820 err_veb:
14821 	i40e_veb_clear(veb);
14822 err_alloc:
14823 	return NULL;
14824 }
14825 
14826 /**
14827  * i40e_setup_pf_switch_element - set PF vars based on switch type
14828  * @pf: board private structure
14829  * @ele: element we are building info from
14830  * @num_reported: total number of elements
14831  * @printconfig: should we print the contents
14832  *
14833  * helper function to assist in extracting a few useful SEID values.
14834  **/
14835 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14836 				struct i40e_aqc_switch_config_element_resp *ele,
14837 				u16 num_reported, bool printconfig)
14838 {
14839 	u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14840 	u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14841 	u8 element_type = ele->element_type;
14842 	u16 seid = le16_to_cpu(ele->seid);
14843 	struct i40e_veb *veb;
14844 
14845 	if (printconfig)
14846 		dev_info(&pf->pdev->dev,
14847 			 "type=%d seid=%d uplink=%d downlink=%d\n",
14848 			 element_type, seid, uplink_seid, downlink_seid);
14849 
14850 	switch (element_type) {
14851 	case I40E_SWITCH_ELEMENT_TYPE_MAC:
14852 		pf->mac_seid = seid;
14853 		break;
14854 	case I40E_SWITCH_ELEMENT_TYPE_VEB:
14855 		/* Main VEB? */
14856 		if (uplink_seid != pf->mac_seid)
14857 			break;
14858 		veb = i40e_pf_get_main_veb(pf);
14859 		if (!veb) {
14860 			int v;
14861 
14862 			/* find existing or else empty VEB */
14863 			veb = i40e_pf_get_veb_by_seid(pf, seid);
14864 			if (veb) {
14865 				pf->lan_veb = veb->idx;
14866 			} else {
14867 				v = i40e_veb_mem_alloc(pf);
14868 				if (v < 0)
14869 					break;
14870 				pf->lan_veb = v;
14871 			}
14872 		}
14873 
14874 		/* Try to get again main VEB as pf->lan_veb may have changed */
14875 		veb = i40e_pf_get_main_veb(pf);
14876 		if (!veb)
14877 			break;
14878 
14879 		veb->seid = seid;
14880 		veb->uplink_seid = pf->mac_seid;
14881 		veb->pf = pf;
14882 		break;
14883 	case I40E_SWITCH_ELEMENT_TYPE_VSI:
14884 		if (num_reported != 1)
14885 			break;
14886 		/* This is immediately after a reset so we can assume this is
14887 		 * the PF's VSI
14888 		 */
14889 		pf->mac_seid = uplink_seid;
14890 		pf->main_vsi_seid = seid;
14891 		if (printconfig)
14892 			dev_info(&pf->pdev->dev,
14893 				 "pf_seid=%d main_vsi_seid=%d\n",
14894 				 downlink_seid, pf->main_vsi_seid);
14895 		break;
14896 	case I40E_SWITCH_ELEMENT_TYPE_PF:
14897 	case I40E_SWITCH_ELEMENT_TYPE_VF:
14898 	case I40E_SWITCH_ELEMENT_TYPE_EMP:
14899 	case I40E_SWITCH_ELEMENT_TYPE_BMC:
14900 	case I40E_SWITCH_ELEMENT_TYPE_PE:
14901 	case I40E_SWITCH_ELEMENT_TYPE_PA:
14902 		/* ignore these for now */
14903 		break;
14904 	default:
14905 		dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
14906 			 element_type, seid);
14907 		break;
14908 	}
14909 }
14910 
14911 /**
14912  * i40e_fetch_switch_configuration - Get switch config from firmware
14913  * @pf: board private structure
14914  * @printconfig: should we print the contents
14915  *
14916  * Get the current switch configuration from the device and
14917  * extract a few useful SEID values.
14918  **/
14919 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
14920 {
14921 	struct i40e_aqc_get_switch_config_resp *sw_config;
14922 	u16 next_seid = 0;
14923 	int ret = 0;
14924 	u8 *aq_buf;
14925 	int i;
14926 
14927 	aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
14928 	if (!aq_buf)
14929 		return -ENOMEM;
14930 
14931 	sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
14932 	do {
14933 		u16 num_reported, num_total;
14934 
14935 		ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
14936 						I40E_AQ_LARGE_BUF,
14937 						&next_seid, NULL);
14938 		if (ret) {
14939 			dev_info(&pf->pdev->dev,
14940 				 "get switch config failed err %d aq_err %s\n",
14941 				 ret, libie_aq_str(pf->hw.aq.asq_last_status));
14942 			kfree(aq_buf);
14943 			return -ENOENT;
14944 		}
14945 
14946 		num_reported = le16_to_cpu(sw_config->header.num_reported);
14947 		num_total = le16_to_cpu(sw_config->header.num_total);
14948 
14949 		if (printconfig)
14950 			dev_info(&pf->pdev->dev,
14951 				 "header: %d reported %d total\n",
14952 				 num_reported, num_total);
14953 
14954 		for (i = 0; i < num_reported; i++) {
14955 			struct i40e_aqc_switch_config_element_resp *ele =
14956 				&sw_config->element[i];
14957 
14958 			i40e_setup_pf_switch_element(pf, ele, num_reported,
14959 						     printconfig);
14960 		}
14961 	} while (next_seid != 0);
14962 
14963 	kfree(aq_buf);
14964 	return ret;
14965 }
14966 
14967 /**
14968  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
14969  * @pf: board private structure
14970  * @reinit: if the Main VSI needs to re-initialized.
14971  * @lock_acquired: indicates whether or not the lock has been acquired
14972  *
14973  * Returns 0 on success, negative value on failure
14974  **/
14975 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired)
14976 {
14977 	struct i40e_vsi *main_vsi;
14978 	u16 flags = 0;
14979 	int ret;
14980 
14981 	/* find out what's out there already */
14982 	ret = i40e_fetch_switch_configuration(pf, false);
14983 	if (ret) {
14984 		dev_info(&pf->pdev->dev,
14985 			 "couldn't fetch switch config, err %pe aq_err %s\n",
14986 			 ERR_PTR(ret), libie_aq_str(pf->hw.aq.asq_last_status));
14987 		return ret;
14988 	}
14989 	i40e_pf_reset_stats(pf);
14990 
14991 	/* set the switch config bit for the whole device to
14992 	 * support limited promisc or true promisc
14993 	 * when user requests promisc. The default is limited
14994 	 * promisc.
14995 	*/
14996 
14997 	if ((pf->hw.pf_id == 0) &&
14998 	    !test_bit(I40E_FLAG_TRUE_PROMISC_ENA, pf->flags)) {
14999 		flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15000 		pf->last_sw_conf_flags = flags;
15001 	}
15002 
15003 	if (pf->hw.pf_id == 0) {
15004 		u16 valid_flags;
15005 
15006 		valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15007 		ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
15008 						NULL);
15009 		if (ret && pf->hw.aq.asq_last_status != LIBIE_AQ_RC_ESRCH) {
15010 			dev_info(&pf->pdev->dev,
15011 				 "couldn't set switch config bits, err %pe aq_err %s\n",
15012 				 ERR_PTR(ret),
15013 				 libie_aq_str(pf->hw.aq.asq_last_status));
15014 			/* not a fatal problem, just keep going */
15015 		}
15016 		pf->last_sw_conf_valid_flags = valid_flags;
15017 	}
15018 
15019 	/* first time setup */
15020 	main_vsi = i40e_pf_get_main_vsi(pf);
15021 	if (!main_vsi || reinit) {
15022 		struct i40e_veb *veb;
15023 		u16 uplink_seid;
15024 
15025 		/* Set up the PF VSI associated with the PF's main VSI
15026 		 * that is already in the HW switch
15027 		 */
15028 		veb = i40e_pf_get_main_veb(pf);
15029 		if (veb)
15030 			uplink_seid = veb->seid;
15031 		else
15032 			uplink_seid = pf->mac_seid;
15033 		if (!main_vsi)
15034 			main_vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN,
15035 						  uplink_seid, 0);
15036 		else if (reinit)
15037 			main_vsi = i40e_vsi_reinit_setup(main_vsi);
15038 		if (!main_vsi) {
15039 			dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
15040 			i40e_cloud_filter_exit(pf);
15041 			i40e_fdir_teardown(pf);
15042 			return -EAGAIN;
15043 		}
15044 	} else {
15045 		/* force a reset of TC and queue layout configurations */
15046 		main_vsi->seid = pf->main_vsi_seid;
15047 		i40e_vsi_reconfig_tc(main_vsi);
15048 	}
15049 	i40e_vlan_stripping_disable(main_vsi);
15050 
15051 	i40e_fdir_sb_setup(pf);
15052 
15053 	/* Setup static PF queue filter control settings */
15054 	ret = i40e_setup_pf_filter_control(pf);
15055 	if (ret) {
15056 		dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
15057 			 ret);
15058 		/* Failure here should not stop continuing other steps */
15059 	}
15060 
15061 	/* enable RSS in the HW, even for only one queue, as the stack can use
15062 	 * the hash
15063 	 */
15064 	if (test_bit(I40E_FLAG_RSS_ENA, pf->flags))
15065 		i40e_pf_config_rss(pf);
15066 
15067 	/* fill in link information and enable LSE reporting */
15068 	i40e_link_event(pf);
15069 
15070 	i40e_ptp_init(pf);
15071 
15072 	if (!lock_acquired)
15073 		rtnl_lock();
15074 
15075 	/* repopulate tunnel port filters */
15076 	udp_tunnel_nic_reset_ntf(main_vsi->netdev);
15077 
15078 	if (!lock_acquired)
15079 		rtnl_unlock();
15080 
15081 	return ret;
15082 }
15083 
15084 /**
15085  * i40e_determine_queue_usage - Work out queue distribution
15086  * @pf: board private structure
15087  **/
15088 static void i40e_determine_queue_usage(struct i40e_pf *pf)
15089 {
15090 	int queues_left;
15091 	int q_max;
15092 
15093 	pf->num_lan_qps = 0;
15094 
15095 	/* Find the max queues to be put into basic use.  We'll always be
15096 	 * using TC0, whether or not DCB is running, and TC0 will get the
15097 	 * big RSS set.
15098 	 */
15099 	queues_left = pf->hw.func_caps.num_tx_qp;
15100 
15101 	if ((queues_left == 1) ||
15102 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
15103 		/* one qp for PF, no queues for anything else */
15104 		queues_left = 0;
15105 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15106 
15107 		/* make sure all the fancies are disabled */
15108 		clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
15109 		clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
15110 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15111 		clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
15112 		clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15113 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15114 		clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
15115 		clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
15116 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15117 	} else if (!test_bit(I40E_FLAG_RSS_ENA, pf->flags) &&
15118 		   !test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
15119 		   !test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
15120 		   !test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags)) {
15121 		/* one qp for PF */
15122 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15123 		queues_left -= pf->num_lan_qps;
15124 
15125 		clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
15126 		clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
15127 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15128 		clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
15129 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15130 		clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
15131 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15132 	} else {
15133 		/* Not enough queues for all TCs */
15134 		if (test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags) &&
15135 		    queues_left < I40E_MAX_TRAFFIC_CLASS) {
15136 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15137 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15138 			dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
15139 		}
15140 
15141 		/* limit lan qps to the smaller of qps, cpus or msix */
15142 		q_max = max_t(int, pf->rss_size_max, num_online_cpus());
15143 		q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
15144 		q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
15145 		pf->num_lan_qps = q_max;
15146 
15147 		queues_left -= pf->num_lan_qps;
15148 	}
15149 
15150 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
15151 		if (queues_left > 1) {
15152 			queues_left -= 1; /* save 1 queue for FD */
15153 		} else {
15154 			clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15155 			set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15156 			dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
15157 		}
15158 	}
15159 
15160 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
15161 	    pf->num_vf_qps && pf->num_req_vfs && queues_left) {
15162 		pf->num_req_vfs = min_t(int, pf->num_req_vfs,
15163 					(queues_left / pf->num_vf_qps));
15164 		queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
15165 	}
15166 
15167 	if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags) &&
15168 	    pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
15169 		pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
15170 					  (queues_left / pf->num_vmdq_qps));
15171 		queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
15172 	}
15173 
15174 	pf->queues_left = queues_left;
15175 	dev_dbg(&pf->pdev->dev,
15176 		"qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
15177 		pf->hw.func_caps.num_tx_qp,
15178 		!!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags),
15179 		pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
15180 		pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
15181 		queues_left);
15182 }
15183 
15184 /**
15185  * i40e_setup_pf_filter_control - Setup PF static filter control
15186  * @pf: PF to be setup
15187  *
15188  * i40e_setup_pf_filter_control sets up a PF's initial filter control
15189  * settings. If PE/FCoE are enabled then it will also set the per PF
15190  * based filter sizes required for them. It also enables Flow director,
15191  * ethertype and macvlan type filter settings for the pf.
15192  *
15193  * Returns 0 on success, negative on failure
15194  **/
15195 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
15196 {
15197 	struct i40e_filter_control_settings *settings = &pf->filter_settings;
15198 
15199 	settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
15200 
15201 	/* Flow Director is enabled */
15202 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) ||
15203 	    test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags))
15204 		settings->enable_fdir = true;
15205 
15206 	/* Ethtype and MACVLAN filters enabled for PF */
15207 	settings->enable_ethtype = true;
15208 	settings->enable_macvlan = true;
15209 
15210 	if (i40e_set_filter_control(&pf->hw, settings))
15211 		return -ENOENT;
15212 
15213 	return 0;
15214 }
15215 
15216 #define INFO_STRING_LEN 255
15217 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
15218 static void i40e_print_features(struct i40e_pf *pf)
15219 {
15220 	struct i40e_vsi *main_vsi = i40e_pf_get_main_vsi(pf);
15221 	struct i40e_hw *hw = &pf->hw;
15222 	char *buf;
15223 	int i;
15224 
15225 	buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
15226 	if (!buf)
15227 		return;
15228 
15229 	i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
15230 #ifdef CONFIG_PCI_IOV
15231 	i += scnprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
15232 #endif
15233 	i += scnprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
15234 		       pf->hw.func_caps.num_vsis, main_vsi->num_queue_pairs);
15235 	if (test_bit(I40E_FLAG_RSS_ENA, pf->flags))
15236 		i += scnprintf(&buf[i], REMAIN(i), " RSS");
15237 	if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags))
15238 		i += scnprintf(&buf[i], REMAIN(i), " FD_ATR");
15239 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
15240 		i += scnprintf(&buf[i], REMAIN(i), " FD_SB");
15241 		i += scnprintf(&buf[i], REMAIN(i), " NTUPLE");
15242 	}
15243 	if (test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
15244 		i += scnprintf(&buf[i], REMAIN(i), " DCB");
15245 	i += scnprintf(&buf[i], REMAIN(i), " VxLAN");
15246 	i += scnprintf(&buf[i], REMAIN(i), " Geneve");
15247 	if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
15248 		i += scnprintf(&buf[i], REMAIN(i), " PTP");
15249 	if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags))
15250 		i += scnprintf(&buf[i], REMAIN(i), " VEB");
15251 	else
15252 		i += scnprintf(&buf[i], REMAIN(i), " VEPA");
15253 
15254 	dev_info(&pf->pdev->dev, "%s\n", buf);
15255 	kfree(buf);
15256 	WARN_ON(i > INFO_STRING_LEN);
15257 }
15258 
15259 /**
15260  * i40e_get_platform_mac_addr - get platform-specific MAC address
15261  * @pdev: PCI device information struct
15262  * @pf: board private structure
15263  *
15264  * Look up the MAC address for the device. First we'll try
15265  * eth_platform_get_mac_address, which will check Open Firmware, or arch
15266  * specific fallback. Otherwise, we'll default to the stored value in
15267  * firmware.
15268  **/
15269 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
15270 {
15271 	if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
15272 		i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
15273 }
15274 
15275 /**
15276  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
15277  * @fec_cfg: FEC option to set in flags
15278  * @flags: ptr to flags in which we set FEC option
15279  **/
15280 void i40e_set_fec_in_flags(u8 fec_cfg, unsigned long *flags)
15281 {
15282 	if (fec_cfg & I40E_AQ_SET_FEC_AUTO) {
15283 		set_bit(I40E_FLAG_RS_FEC, flags);
15284 		set_bit(I40E_FLAG_BASE_R_FEC, flags);
15285 	}
15286 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
15287 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
15288 		set_bit(I40E_FLAG_RS_FEC, flags);
15289 		clear_bit(I40E_FLAG_BASE_R_FEC, flags);
15290 	}
15291 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
15292 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
15293 		set_bit(I40E_FLAG_BASE_R_FEC, flags);
15294 		clear_bit(I40E_FLAG_RS_FEC, flags);
15295 	}
15296 	if (fec_cfg == 0) {
15297 		clear_bit(I40E_FLAG_RS_FEC, flags);
15298 		clear_bit(I40E_FLAG_BASE_R_FEC, flags);
15299 	}
15300 }
15301 
15302 /**
15303  * i40e_check_recovery_mode - check if we are running transition firmware
15304  * @pf: board private structure
15305  *
15306  * Check registers indicating the firmware runs in recovery mode. Sets the
15307  * appropriate driver state.
15308  *
15309  * Returns true if the recovery mode was detected, false otherwise
15310  **/
15311 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
15312 {
15313 	u32 val = rd32(&pf->hw, I40E_GL_FWSTS);
15314 
15315 	if (val & I40E_GL_FWSTS_FWS1B_MASK) {
15316 		dev_crit(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
15317 		dev_crit(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
15318 		set_bit(__I40E_RECOVERY_MODE, pf->state);
15319 
15320 		return true;
15321 	}
15322 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15323 		dev_info(&pf->pdev->dev, "Please do Power-On Reset to initialize adapter in normal mode with full functionality.\n");
15324 
15325 	return false;
15326 }
15327 
15328 /**
15329  * i40e_pf_loop_reset - perform reset in a loop.
15330  * @pf: board private structure
15331  *
15332  * This function is useful when a NIC is about to enter recovery mode.
15333  * When a NIC's internal data structures are corrupted the NIC's
15334  * firmware is going to enter recovery mode.
15335  * Right after a POR it takes about 7 minutes for firmware to enter
15336  * recovery mode. Until that time a NIC is in some kind of intermediate
15337  * state. After that time period the NIC almost surely enters
15338  * recovery mode. The only way for a driver to detect intermediate
15339  * state is to issue a series of pf-resets and check a return value.
15340  * If a PF reset returns success then the firmware could be in recovery
15341  * mode so the caller of this code needs to check for recovery mode
15342  * if this function returns success. There is a little chance that
15343  * firmware will hang in intermediate state forever.
15344  * Since waiting 7 minutes is quite a lot of time this function waits
15345  * 10 seconds and then gives up by returning an error.
15346  *
15347  * Return 0 on success, negative on failure.
15348  **/
15349 static int i40e_pf_loop_reset(struct i40e_pf *pf)
15350 {
15351 	/* wait max 10 seconds for PF reset to succeed */
15352 	const unsigned long time_end = jiffies + 10 * HZ;
15353 	struct i40e_hw *hw = &pf->hw;
15354 	int ret;
15355 
15356 	ret = i40e_pf_reset(hw);
15357 	while (ret != 0 && time_before(jiffies, time_end)) {
15358 		usleep_range(10000, 20000);
15359 		ret = i40e_pf_reset(hw);
15360 	}
15361 
15362 	if (ret == 0)
15363 		pf->pfr_count++;
15364 	else
15365 		dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
15366 
15367 	return ret;
15368 }
15369 
15370 /**
15371  * i40e_check_fw_empr - check if FW issued unexpected EMP Reset
15372  * @pf: board private structure
15373  *
15374  * Check FW registers to determine if FW issued unexpected EMP Reset.
15375  * Every time when unexpected EMP Reset occurs the FW increments
15376  * a counter of unexpected EMP Resets. When the counter reaches 10
15377  * the FW should enter the Recovery mode
15378  *
15379  * Returns true if FW issued unexpected EMP Reset
15380  **/
15381 static bool i40e_check_fw_empr(struct i40e_pf *pf)
15382 {
15383 	const u32 fw_sts = rd32(&pf->hw, I40E_GL_FWSTS) &
15384 			   I40E_GL_FWSTS_FWS1B_MASK;
15385 	return (fw_sts > I40E_GL_FWSTS_FWS1B_EMPR_0) &&
15386 	       (fw_sts <= I40E_GL_FWSTS_FWS1B_EMPR_10);
15387 }
15388 
15389 /**
15390  * i40e_handle_resets - handle EMP resets and PF resets
15391  * @pf: board private structure
15392  *
15393  * Handle both EMP resets and PF resets and conclude whether there are
15394  * any issues regarding these resets. If there are any issues then
15395  * generate log entry.
15396  *
15397  * Return 0 if NIC is healthy or negative value when there are issues
15398  * with resets
15399  **/
15400 static int i40e_handle_resets(struct i40e_pf *pf)
15401 {
15402 	const int pfr = i40e_pf_loop_reset(pf);
15403 	const bool is_empr = i40e_check_fw_empr(pf);
15404 
15405 	if (is_empr || pfr != 0)
15406 		dev_crit(&pf->pdev->dev, "Entering recovery mode due to repeated FW resets. This may take several minutes. Refer to the Intel(R) Ethernet Adapters and Devices User Guide.\n");
15407 
15408 	return is_empr ? -EIO : pfr;
15409 }
15410 
15411 /**
15412  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
15413  * @pf: board private structure
15414  * @hw: ptr to the hardware info
15415  *
15416  * This function does a minimal setup of all subsystems needed for running
15417  * recovery mode.
15418  *
15419  * Returns 0 on success, negative on failure
15420  **/
15421 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
15422 {
15423 	struct i40e_vsi *vsi;
15424 	int err;
15425 	int v_idx;
15426 
15427 	pci_set_drvdata(pf->pdev, pf);
15428 	pci_save_state(pf->pdev);
15429 
15430 	/* set up periodic task facility */
15431 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15432 	pf->service_timer_period = HZ;
15433 
15434 	INIT_WORK(&pf->service_task, i40e_service_task);
15435 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15436 
15437 	err = i40e_init_interrupt_scheme(pf);
15438 	if (err)
15439 		goto err_switch_setup;
15440 
15441 	/* The number of VSIs reported by the FW is the minimum guaranteed
15442 	 * to us; HW supports far more and we share the remaining pool with
15443 	 * the other PFs. We allocate space for more than the guarantee with
15444 	 * the understanding that we might not get them all later.
15445 	 */
15446 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15447 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15448 	else
15449 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15450 
15451 	/* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
15452 	pf->vsi = kzalloc_objs(struct i40e_vsi *, pf->num_alloc_vsi);
15453 	if (!pf->vsi) {
15454 		err = -ENOMEM;
15455 		goto err_switch_setup;
15456 	}
15457 
15458 	/* We allocate one VSI which is needed as absolute minimum
15459 	 * in order to register the netdev
15460 	 */
15461 	v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
15462 	if (v_idx < 0) {
15463 		err = v_idx;
15464 		goto err_switch_setup;
15465 	}
15466 	pf->lan_vsi = v_idx;
15467 	vsi = pf->vsi[v_idx];
15468 	if (!vsi) {
15469 		err = -EFAULT;
15470 		goto err_switch_setup;
15471 	}
15472 	vsi->alloc_queue_pairs = 1;
15473 	err = i40e_config_netdev(vsi);
15474 	if (err)
15475 		goto err_switch_setup;
15476 	err = register_netdev(vsi->netdev);
15477 	if (err)
15478 		goto err_switch_setup;
15479 	vsi->netdev_registered = true;
15480 	i40e_dbg_pf_init(pf);
15481 
15482 	err = i40e_setup_misc_vector_for_recovery_mode(pf);
15483 	if (err)
15484 		goto err_switch_setup;
15485 
15486 	/* tell the firmware that we're starting */
15487 	i40e_send_version(pf);
15488 
15489 	/* since everything's happy, start the service_task timer */
15490 	mod_timer(&pf->service_timer,
15491 		  round_jiffies(jiffies + pf->service_timer_period));
15492 
15493 	return 0;
15494 
15495 err_switch_setup:
15496 	i40e_reset_interrupt_capability(pf);
15497 	timer_shutdown_sync(&pf->service_timer);
15498 	i40e_shutdown_adminq(hw);
15499 	iounmap(hw->hw_addr);
15500 	pci_release_mem_regions(pf->pdev);
15501 	pci_disable_device(pf->pdev);
15502 	i40e_free_pf(pf);
15503 
15504 	return err;
15505 }
15506 
15507 /**
15508  * i40e_set_subsystem_device_id - set subsystem device id
15509  * @hw: pointer to the hardware info
15510  *
15511  * Set PCI subsystem device id either from a pci_dev structure or
15512  * a specific FW register.
15513  **/
15514 static inline void i40e_set_subsystem_device_id(struct i40e_hw *hw)
15515 {
15516 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
15517 
15518 	hw->subsystem_device_id = pf->pdev->subsystem_device ?
15519 		pf->pdev->subsystem_device :
15520 		(ushort)(rd32(hw, I40E_PFPCI_SUBSYSID) & USHRT_MAX);
15521 }
15522 
15523 /**
15524  * i40e_probe - Device initialization routine
15525  * @pdev: PCI device information struct
15526  * @ent: entry in i40e_pci_tbl
15527  *
15528  * i40e_probe initializes a PF identified by a pci_dev structure.
15529  * The OS initialization, configuring of the PF private structure,
15530  * and a hardware reset occur.
15531  *
15532  * Returns 0 on success, negative on failure
15533  **/
15534 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
15535 {
15536 	struct i40e_aq_get_phy_abilities_resp abilities;
15537 #ifdef CONFIG_I40E_DCB
15538 	enum i40e_get_fw_lldp_status_resp lldp_status;
15539 #endif /* CONFIG_I40E_DCB */
15540 	struct i40e_vsi *vsi;
15541 	struct i40e_pf *pf;
15542 	struct i40e_hw *hw;
15543 	u16 wol_nvm_bits;
15544 	char nvm_ver[32];
15545 	u16 link_status;
15546 #ifdef CONFIG_I40E_DCB
15547 	int status;
15548 #endif /* CONFIG_I40E_DCB */
15549 	int err;
15550 	u32 val;
15551 
15552 	err = pci_enable_device_mem(pdev);
15553 	if (err)
15554 		return err;
15555 
15556 	/* set up for high or low dma */
15557 	err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
15558 	if (err) {
15559 		dev_err(&pdev->dev,
15560 			"DMA configuration failed: 0x%x\n", err);
15561 		goto err_dma;
15562 	}
15563 
15564 	/* set up pci connections */
15565 	err = pci_request_mem_regions(pdev, i40e_driver_name);
15566 	if (err) {
15567 		dev_info(&pdev->dev,
15568 			 "pci_request_selected_regions failed %d\n", err);
15569 		goto err_pci_reg;
15570 	}
15571 
15572 	pci_set_master(pdev);
15573 
15574 	/* Now that we have a PCI connection, we need to do the
15575 	 * low level device setup.  This is primarily setting up
15576 	 * the Admin Queue structures and then querying for the
15577 	 * device's current profile information.
15578 	 */
15579 	pf = i40e_alloc_pf(&pdev->dev);
15580 	if (!pf) {
15581 		err = -ENOMEM;
15582 		goto err_pf_alloc;
15583 	}
15584 	pf->next_vsi = 0;
15585 	pf->pdev = pdev;
15586 	set_bit(__I40E_DOWN, pf->state);
15587 
15588 	hw = &pf->hw;
15589 
15590 	pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
15591 				I40E_MAX_CSR_SPACE);
15592 	/* We believe that the highest register to read is
15593 	 * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
15594 	 * is not less than that before mapping to prevent a
15595 	 * kernel panic.
15596 	 */
15597 	if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
15598 		dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
15599 			pf->ioremap_len);
15600 		err = -ENOMEM;
15601 		goto err_ioremap;
15602 	}
15603 	hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
15604 	if (!hw->hw_addr) {
15605 		err = -EIO;
15606 		dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
15607 			 (unsigned int)pci_resource_start(pdev, 0),
15608 			 pf->ioremap_len, err);
15609 		goto err_ioremap;
15610 	}
15611 	hw->vendor_id = pdev->vendor;
15612 	hw->device_id = pdev->device;
15613 	pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
15614 	hw->subsystem_vendor_id = pdev->subsystem_vendor;
15615 	i40e_set_subsystem_device_id(hw);
15616 	hw->bus.device = PCI_SLOT(pdev->devfn);
15617 	hw->bus.func = PCI_FUNC(pdev->devfn);
15618 	hw->bus.bus_id = pdev->bus->number;
15619 
15620 	/* Select something other than the 802.1ad ethertype for the
15621 	 * switch to use internally and drop on ingress.
15622 	 */
15623 	hw->switch_tag = 0xffff;
15624 	hw->first_tag = ETH_P_8021AD;
15625 	hw->second_tag = ETH_P_8021Q;
15626 
15627 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
15628 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
15629 	INIT_LIST_HEAD(&pf->ddp_old_prof);
15630 
15631 	/* set up the locks for the AQ, do this only once in probe
15632 	 * and destroy them only once in remove
15633 	 */
15634 	mutex_init(&hw->aq.asq_mutex);
15635 	mutex_init(&hw->aq.arq_mutex);
15636 
15637 	pf->msg_enable = netif_msg_init(debug,
15638 					NETIF_MSG_DRV |
15639 					NETIF_MSG_PROBE |
15640 					NETIF_MSG_LINK);
15641 	if (debug < -1)
15642 		pf->hw.debug_mask = debug;
15643 
15644 	/* do a special CORER for clearing PXE mode once at init */
15645 	if (hw->revision_id == 0 &&
15646 	    (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
15647 		wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
15648 		i40e_flush(hw);
15649 		msleep(200);
15650 		pf->corer_count++;
15651 
15652 		i40e_clear_pxe_mode(hw);
15653 	}
15654 
15655 	/* Reset here to make sure all is clean and to define PF 'n' */
15656 	i40e_clear_hw(hw);
15657 
15658 	err = i40e_set_mac_type(hw);
15659 	if (err) {
15660 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15661 			 err);
15662 		goto err_pf_reset;
15663 	}
15664 
15665 	err = i40e_handle_resets(pf);
15666 	if (err)
15667 		goto err_pf_reset;
15668 
15669 	i40e_check_recovery_mode(pf);
15670 
15671 	if (is_kdump_kernel()) {
15672 		hw->aq.num_arq_entries = I40E_MIN_ARQ_LEN;
15673 		hw->aq.num_asq_entries = I40E_MIN_ASQ_LEN;
15674 	} else {
15675 		hw->aq.num_arq_entries = I40E_AQ_LEN;
15676 		hw->aq.num_asq_entries = I40E_AQ_LEN;
15677 	}
15678 	hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15679 	hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15680 
15681 	snprintf(pf->int_name, sizeof(pf->int_name) - 1,
15682 		 "%s-%s:misc",
15683 		 dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
15684 
15685 	err = i40e_init_shared_code(hw);
15686 	if (err) {
15687 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15688 			 err);
15689 		goto err_pf_reset;
15690 	}
15691 
15692 	/* set up a default setting for link flow control */
15693 	pf->hw.fc.requested_mode = I40E_FC_NONE;
15694 
15695 	err = i40e_init_adminq(hw);
15696 	if (err) {
15697 		if (err == -EIO)
15698 			dev_info(&pdev->dev,
15699 				 "The driver for the device stopped because the NVM image v%u.%u is newer than expected v%u.%u. You must install the most recent version of the network driver.\n",
15700 				 hw->aq.api_maj_ver,
15701 				 hw->aq.api_min_ver,
15702 				 I40E_FW_API_VERSION_MAJOR,
15703 				 I40E_FW_MINOR_VERSION(hw));
15704 		else
15705 			dev_info(&pdev->dev,
15706 				 "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
15707 
15708 		goto err_pf_reset;
15709 	}
15710 	i40e_get_oem_version(hw);
15711 	i40e_get_pba_string(hw);
15712 
15713 	/* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
15714 	i40e_nvm_version_str(hw, nvm_ver, sizeof(nvm_ver));
15715 	dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
15716 		 hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
15717 		 hw->aq.api_maj_ver, hw->aq.api_min_ver, nvm_ver,
15718 		 hw->vendor_id, hw->device_id, hw->subsystem_vendor_id,
15719 		 hw->subsystem_device_id);
15720 
15721 	if (i40e_is_aq_api_ver_ge(hw, I40E_FW_API_VERSION_MAJOR,
15722 				  I40E_FW_MINOR_VERSION(hw) + 1))
15723 		dev_dbg(&pdev->dev,
15724 			"The driver for the device detected a newer version of the NVM image v%u.%u than v%u.%u.\n",
15725 			 hw->aq.api_maj_ver,
15726 			 hw->aq.api_min_ver,
15727 			 I40E_FW_API_VERSION_MAJOR,
15728 			 I40E_FW_MINOR_VERSION(hw));
15729 	else if (i40e_is_aq_api_ver_lt(hw, 1, 4))
15730 		dev_info(&pdev->dev,
15731 			 "The driver for the device detected an older version of the NVM image v%u.%u than expected v%u.%u. Please update the NVM image.\n",
15732 			 hw->aq.api_maj_ver,
15733 			 hw->aq.api_min_ver,
15734 			 I40E_FW_API_VERSION_MAJOR,
15735 			 I40E_FW_MINOR_VERSION(hw));
15736 
15737 	i40e_verify_eeprom(pf);
15738 
15739 	/* Rev 0 hardware was never productized */
15740 	if (hw->revision_id < 1)
15741 		dev_warn(&pdev->dev, "This device is a pre-production adapter/LOM. Please be aware there may be issues with your hardware. If you are experiencing problems please contact your Intel or hardware representative who provided you with this hardware.\n");
15742 
15743 	i40e_clear_pxe_mode(hw);
15744 
15745 	err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
15746 	if (err)
15747 		goto err_adminq_setup;
15748 
15749 	err = i40e_sw_init(pf);
15750 	if (err) {
15751 		dev_info(&pdev->dev, "sw_init failed: %d\n", err);
15752 		goto err_sw_init;
15753 	}
15754 
15755 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15756 		return i40e_init_recovery_mode(pf, hw);
15757 
15758 	err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
15759 				hw->func_caps.num_rx_qp, 0, 0);
15760 	if (err) {
15761 		dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
15762 		goto err_init_lan_hmc;
15763 	}
15764 
15765 	err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
15766 	if (err) {
15767 		dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
15768 		err = -ENOENT;
15769 		goto err_configure_lan_hmc;
15770 	}
15771 
15772 	/* Disable LLDP for NICs that have firmware versions lower than v4.3.
15773 	 * Ignore error return codes because if it was already disabled via
15774 	 * hardware settings this will fail
15775 	 */
15776 	if (test_bit(I40E_HW_CAP_STOP_FW_LLDP, pf->hw.caps)) {
15777 		dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
15778 		i40e_aq_stop_lldp(hw, true, false, NULL);
15779 	}
15780 
15781 	/* allow a platform config to override the HW addr */
15782 	i40e_get_platform_mac_addr(pdev, pf);
15783 
15784 	if (!is_valid_ether_addr(hw->mac.addr)) {
15785 		dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
15786 		err = -EIO;
15787 		goto err_mac_addr;
15788 	}
15789 	dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
15790 	ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
15791 	i40e_get_port_mac_addr(hw, hw->mac.port_addr);
15792 	if (is_valid_ether_addr(hw->mac.port_addr))
15793 		set_bit(I40E_HW_CAP_PORT_ID_VALID, pf->hw.caps);
15794 
15795 	i40e_ptp_alloc_pins(pf);
15796 	pci_set_drvdata(pdev, pf);
15797 	pci_save_state(pdev);
15798 
15799 #ifdef CONFIG_I40E_DCB
15800 	status = i40e_get_fw_lldp_status(&pf->hw, &lldp_status);
15801 	(!status &&
15802 	 lldp_status == I40E_GET_FW_LLDP_STATUS_ENABLED) ?
15803 		(clear_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags)) :
15804 		(set_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags));
15805 	dev_info(&pdev->dev,
15806 		 test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags) ?
15807 			"FW LLDP is disabled\n" :
15808 			"FW LLDP is enabled\n");
15809 
15810 	/* Enable FW to write default DCB config on link-up */
15811 	i40e_aq_set_dcb_parameters(hw, true, NULL);
15812 
15813 	err = i40e_init_pf_dcb(pf);
15814 	if (err) {
15815 		dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
15816 		clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15817 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15818 		/* Continue without DCB enabled */
15819 	}
15820 #endif /* CONFIG_I40E_DCB */
15821 
15822 	/* set up periodic task facility */
15823 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15824 	pf->service_timer_period = HZ;
15825 
15826 	INIT_WORK(&pf->service_task, i40e_service_task);
15827 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15828 
15829 	/* NVM bit on means WoL disabled for the port */
15830 	i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15831 	if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15832 		pf->wol_en = false;
15833 	else
15834 		pf->wol_en = true;
15835 	device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15836 
15837 	/* set up the main switch operations */
15838 	i40e_determine_queue_usage(pf);
15839 	err = i40e_init_interrupt_scheme(pf);
15840 	if (err)
15841 		goto err_switch_setup;
15842 
15843 	/* Reduce Tx and Rx pairs for kdump
15844 	 * When MSI-X is enabled, it's not allowed to use more TC queue
15845 	 * pairs than MSI-X vectors (pf->num_lan_msix) exist. Thus
15846 	 * vsi->num_queue_pairs will be equal to pf->num_lan_msix, i.e., 1.
15847 	 */
15848 	if (is_kdump_kernel())
15849 		pf->num_lan_msix = 1;
15850 
15851 	pf->udp_tunnel_nic.set_port = i40e_udp_tunnel_set_port;
15852 	pf->udp_tunnel_nic.unset_port = i40e_udp_tunnel_unset_port;
15853 	pf->udp_tunnel_nic.shared = &pf->udp_tunnel_shared;
15854 	pf->udp_tunnel_nic.tables[0].n_entries = I40E_MAX_PF_UDP_OFFLOAD_PORTS;
15855 	pf->udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
15856 						    UDP_TUNNEL_TYPE_GENEVE;
15857 
15858 	/* The number of VSIs reported by the FW is the minimum guaranteed
15859 	 * to us; HW supports far more and we share the remaining pool with
15860 	 * the other PFs. We allocate space for more than the guarantee with
15861 	 * the understanding that we might not get them all later.
15862 	 */
15863 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15864 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15865 	else
15866 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15867 	if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
15868 		dev_warn(&pf->pdev->dev,
15869 			 "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
15870 			 pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
15871 		pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
15872 	}
15873 
15874 	/* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15875 	pf->vsi = kzalloc_objs(struct i40e_vsi *, pf->num_alloc_vsi);
15876 	if (!pf->vsi) {
15877 		err = -ENOMEM;
15878 		goto err_switch_setup;
15879 	}
15880 
15881 #ifdef CONFIG_PCI_IOV
15882 	/* prep for VF support */
15883 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
15884 	    test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
15885 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15886 		if (pci_num_vf(pdev))
15887 			set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
15888 	}
15889 #endif
15890 	err = i40e_setup_pf_switch(pf, false, false);
15891 	if (err) {
15892 		dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
15893 		goto err_vsis;
15894 	}
15895 
15896 	vsi = i40e_pf_get_main_vsi(pf);
15897 	INIT_LIST_HEAD(&vsi->ch_list);
15898 
15899 	/* if FDIR VSI was set up, start it now */
15900 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
15901 	if (vsi)
15902 		i40e_vsi_open(vsi);
15903 
15904 	/* The driver only wants link up/down and module qualification
15905 	 * reports from firmware.  Note the negative logic.
15906 	 */
15907 	err = i40e_aq_set_phy_int_mask(&pf->hw,
15908 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
15909 					 I40E_AQ_EVENT_MEDIA_NA |
15910 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
15911 	if (err)
15912 		dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
15913 			 ERR_PTR(err), libie_aq_str(pf->hw.aq.asq_last_status));
15914 
15915 	/* VF MDD event logs are rate limited to one second intervals */
15916 	ratelimit_state_init(&pf->mdd_message_rate_limit, 1 * HZ, 1);
15917 
15918 	/* Reconfigure hardware for allowing smaller MSS in the case
15919 	 * of TSO, so that we avoid the MDD being fired and causing
15920 	 * a reset in the case of small MSS+TSO.
15921 	 */
15922 	val = rd32(hw, I40E_REG_MSS);
15923 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
15924 		val &= ~I40E_REG_MSS_MIN_MASK;
15925 		val |= I40E_64BYTE_MSS;
15926 		wr32(hw, I40E_REG_MSS, val);
15927 	}
15928 
15929 	if (test_bit(I40E_HW_CAP_RESTART_AUTONEG, pf->hw.caps)) {
15930 		msleep(75);
15931 		err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
15932 		if (err)
15933 			dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
15934 				 ERR_PTR(err),
15935 				 libie_aq_str(pf->hw.aq.asq_last_status));
15936 	}
15937 	/* The main driver is (mostly) up and happy. We need to set this state
15938 	 * before setting up the misc vector or we get a race and the vector
15939 	 * ends up disabled forever.
15940 	 */
15941 	clear_bit(__I40E_DOWN, pf->state);
15942 
15943 	/* In case of MSIX we are going to setup the misc vector right here
15944 	 * to handle admin queue events etc. In case of legacy and MSI
15945 	 * the misc functionality and queue processing is combined in
15946 	 * the same vector and that gets setup at open.
15947 	 */
15948 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
15949 		err = i40e_setup_misc_vector(pf);
15950 		if (err) {
15951 			dev_info(&pdev->dev,
15952 				 "setup of misc vector failed: %d\n", err);
15953 			i40e_cloud_filter_exit(pf);
15954 			i40e_fdir_teardown(pf);
15955 			goto err_vsis;
15956 		}
15957 	}
15958 
15959 #ifdef CONFIG_PCI_IOV
15960 	/* prep for VF support */
15961 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
15962 	    test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
15963 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15964 		/* disable link interrupts for VFs */
15965 		val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
15966 		val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
15967 		wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
15968 		i40e_flush(hw);
15969 
15970 		if (pci_num_vf(pdev)) {
15971 			dev_info(&pdev->dev,
15972 				 "Active VFs found, allocating resources.\n");
15973 			err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
15974 			if (err)
15975 				dev_info(&pdev->dev,
15976 					 "Error %d allocating resources for existing VFs\n",
15977 					 err);
15978 		}
15979 	}
15980 #endif /* CONFIG_PCI_IOV */
15981 
15982 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
15983 		pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
15984 						      pf->num_iwarp_msix,
15985 						      I40E_IWARP_IRQ_PILE_ID);
15986 		if (pf->iwarp_base_vector < 0) {
15987 			dev_info(&pdev->dev,
15988 				 "failed to get tracking for %d vectors for IWARP err=%d\n",
15989 				 pf->num_iwarp_msix, pf->iwarp_base_vector);
15990 			clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
15991 		}
15992 	}
15993 
15994 	i40e_dbg_pf_init(pf);
15995 
15996 	/* tell the firmware that we're starting */
15997 	i40e_send_version(pf);
15998 
15999 	/* since everything's happy, start the service_task timer */
16000 	mod_timer(&pf->service_timer,
16001 		  round_jiffies(jiffies + pf->service_timer_period));
16002 
16003 	/* add this PF to client device list and launch a client service task */
16004 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
16005 		err = i40e_lan_add_device(pf);
16006 		if (err)
16007 			dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
16008 				 err);
16009 	}
16010 
16011 #define PCI_SPEED_SIZE 8
16012 #define PCI_WIDTH_SIZE 8
16013 	/* Devices on the IOSF bus do not have this information
16014 	 * and will report PCI Gen 1 x 1 by default so don't bother
16015 	 * checking them.
16016 	 */
16017 	if (!test_bit(I40E_HW_CAP_NO_PCI_LINK_CHECK, pf->hw.caps)) {
16018 		char speed[PCI_SPEED_SIZE] = "Unknown";
16019 		char width[PCI_WIDTH_SIZE] = "Unknown";
16020 
16021 		/* Get the negotiated link width and speed from PCI config
16022 		 * space
16023 		 */
16024 		pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
16025 					  &link_status);
16026 
16027 		i40e_set_pci_config_data(hw, link_status);
16028 
16029 		switch (hw->bus.speed) {
16030 		case i40e_bus_speed_8000:
16031 			strscpy(speed, "8.0", PCI_SPEED_SIZE); break;
16032 		case i40e_bus_speed_5000:
16033 			strscpy(speed, "5.0", PCI_SPEED_SIZE); break;
16034 		case i40e_bus_speed_2500:
16035 			strscpy(speed, "2.5", PCI_SPEED_SIZE); break;
16036 		default:
16037 			break;
16038 		}
16039 		switch (hw->bus.width) {
16040 		case i40e_bus_width_pcie_x8:
16041 			strscpy(width, "8", PCI_WIDTH_SIZE); break;
16042 		case i40e_bus_width_pcie_x4:
16043 			strscpy(width, "4", PCI_WIDTH_SIZE); break;
16044 		case i40e_bus_width_pcie_x2:
16045 			strscpy(width, "2", PCI_WIDTH_SIZE); break;
16046 		case i40e_bus_width_pcie_x1:
16047 			strscpy(width, "1", PCI_WIDTH_SIZE); break;
16048 		default:
16049 			break;
16050 		}
16051 
16052 		dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
16053 			 speed, width);
16054 
16055 		if (hw->bus.width < i40e_bus_width_pcie_x8 ||
16056 		    hw->bus.speed < i40e_bus_speed_8000) {
16057 			dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
16058 			dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
16059 		}
16060 	}
16061 
16062 	/* get the requested speeds from the fw */
16063 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
16064 	if (err)
16065 		dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %pe last_status =  %s\n",
16066 			ERR_PTR(err), libie_aq_str(pf->hw.aq.asq_last_status));
16067 	pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
16068 
16069 	/* set the FEC config due to the board capabilities */
16070 	i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, pf->flags);
16071 
16072 	/* get the supported phy types from the fw */
16073 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
16074 	if (err)
16075 		dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %pe last_status =  %s\n",
16076 			ERR_PTR(err), libie_aq_str(pf->hw.aq.asq_last_status));
16077 
16078 #define MAX_FRAME_SIZE_DEFAULT 0x2600
16079 
16080 	err = i40e_aq_set_mac_config(hw, MAX_FRAME_SIZE_DEFAULT, NULL);
16081 	if (err)
16082 		dev_warn(&pdev->dev, "set mac config ret = %pe last_status = %s\n",
16083 			 ERR_PTR(err), libie_aq_str(pf->hw.aq.asq_last_status));
16084 
16085 	/* Make sure the MFS is set to the expected value */
16086 	val = rd32(hw, I40E_PRTGL_SAH);
16087 	FIELD_MODIFY(I40E_PRTGL_SAH_MFS_MASK, &val, MAX_FRAME_SIZE_DEFAULT);
16088 	wr32(hw, I40E_PRTGL_SAH, val);
16089 
16090 	/* Add a filter to drop all Flow control frames from any VSI from being
16091 	 * transmitted. By doing so we stop a malicious VF from sending out
16092 	 * PAUSE or PFC frames and potentially controlling traffic for other
16093 	 * PF/VF VSIs.
16094 	 * The FW can still send Flow control frames if enabled.
16095 	 */
16096 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
16097 						       pf->main_vsi_seid);
16098 
16099 	if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
16100 	    (pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
16101 		set_bit(I40E_HW_CAP_PHY_CONTROLS_LEDS, pf->hw.caps);
16102 	if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
16103 		set_bit(I40E_HW_CAP_CRT_RETIMER, pf->hw.caps);
16104 	/* print a string summarizing features */
16105 	i40e_print_features(pf);
16106 
16107 	i40e_devlink_register(pf);
16108 
16109 	return 0;
16110 
16111 	/* Unwind what we've done if something failed in the setup */
16112 err_vsis:
16113 	set_bit(__I40E_DOWN, pf->state);
16114 	i40e_ptp_stop(pf);
16115 	i40e_clear_interrupt_scheme(pf);
16116 	kfree(pf->vsi);
16117 err_switch_setup:
16118 	i40e_ptp_free_pins(pf);
16119 	i40e_reset_interrupt_capability(pf);
16120 	timer_shutdown_sync(&pf->service_timer);
16121 err_mac_addr:
16122 err_configure_lan_hmc:
16123 	(void)i40e_shutdown_lan_hmc(hw);
16124 err_init_lan_hmc:
16125 	kfree(pf->qp_pile);
16126 err_sw_init:
16127 err_adminq_setup:
16128 err_pf_reset:
16129 	iounmap(hw->hw_addr);
16130 err_ioremap:
16131 	i40e_free_pf(pf);
16132 err_pf_alloc:
16133 	pci_release_mem_regions(pdev);
16134 err_pci_reg:
16135 err_dma:
16136 	pci_disable_device(pdev);
16137 	return err;
16138 }
16139 
16140 /**
16141  * i40e_remove - Device removal routine
16142  * @pdev: PCI device information struct
16143  *
16144  * i40e_remove is called by the PCI subsystem to alert the driver
16145  * that is should release a PCI device.  This could be caused by a
16146  * Hot-Plug event, or because the driver is going to be removed from
16147  * memory.
16148  **/
16149 static void i40e_remove(struct pci_dev *pdev)
16150 {
16151 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16152 	struct i40e_hw *hw = &pf->hw;
16153 	struct i40e_vsi *vsi;
16154 	struct i40e_veb *veb;
16155 	int ret_code;
16156 	int i;
16157 
16158 	i40e_devlink_unregister(pf);
16159 
16160 	i40e_dbg_pf_exit(pf);
16161 
16162 	i40e_ptp_stop(pf);
16163 
16164 	/* Disable RSS in hw */
16165 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
16166 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
16167 
16168 	/* Grab __I40E_RESET_RECOVERY_PENDING and set __I40E_IN_REMOVE
16169 	 * flags, once they are set, i40e_rebuild should not be called as
16170 	 * i40e_prep_for_reset always returns early.
16171 	 */
16172 	while (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
16173 		usleep_range(1000, 2000);
16174 	set_bit(__I40E_IN_REMOVE, pf->state);
16175 
16176 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags)) {
16177 		set_bit(__I40E_VF_RESETS_DISABLED, pf->state);
16178 		i40e_free_vfs(pf);
16179 		clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
16180 	}
16181 	/* no more scheduling of any task */
16182 	set_bit(__I40E_SUSPENDED, pf->state);
16183 	set_bit(__I40E_DOWN, pf->state);
16184 	if (pf->service_timer.function)
16185 		timer_shutdown_sync(&pf->service_timer);
16186 	if (pf->service_task.func)
16187 		cancel_work_sync(&pf->service_task);
16188 
16189 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
16190 		struct i40e_vsi *vsi = pf->vsi[0];
16191 
16192 		/* We know that we have allocated only one vsi for this PF,
16193 		 * it was just for registering netdevice, so the interface
16194 		 * could be visible in the 'ifconfig' output
16195 		 */
16196 		unregister_netdev(vsi->netdev);
16197 		free_netdev(vsi->netdev);
16198 
16199 		goto unmap;
16200 	}
16201 
16202 	/* Client close must be called explicitly here because the timer
16203 	 * has been stopped.
16204 	 */
16205 	i40e_notify_client_of_netdev_close(pf, false);
16206 
16207 	i40e_fdir_teardown(pf);
16208 
16209 	/* If there is a switch structure or any orphans, remove them.
16210 	 * This will leave only the PF's VSI remaining.
16211 	 */
16212 	i40e_pf_for_each_veb(pf, i, veb)
16213 		if (veb->uplink_seid == pf->mac_seid ||
16214 		    veb->uplink_seid == 0)
16215 			i40e_switch_branch_release(veb);
16216 
16217 	/* Now we can shutdown the PF's VSIs, just before we kill
16218 	 * adminq and hmc.
16219 	 */
16220 	i40e_pf_for_each_vsi(pf, i, vsi) {
16221 		i40e_vsi_close(vsi);
16222 		i40e_vsi_release(vsi);
16223 		pf->vsi[i] = NULL;
16224 	}
16225 
16226 	i40e_cloud_filter_exit(pf);
16227 
16228 	/* remove attached clients */
16229 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
16230 		ret_code = i40e_lan_del_device(pf);
16231 		if (ret_code)
16232 			dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
16233 				 ret_code);
16234 	}
16235 
16236 	/* shutdown and destroy the HMC */
16237 	if (hw->hmc.hmc_obj) {
16238 		ret_code = i40e_shutdown_lan_hmc(hw);
16239 		if (ret_code)
16240 			dev_warn(&pdev->dev,
16241 				 "Failed to destroy the HMC resources: %d\n",
16242 				 ret_code);
16243 	}
16244 
16245 unmap:
16246 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16247 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16248 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
16249 		free_irq(pf->pdev->irq, pf);
16250 
16251 	/* shutdown the adminq */
16252 	i40e_shutdown_adminq(hw);
16253 
16254 	/* destroy the locks only once, here */
16255 	mutex_destroy(&hw->aq.arq_mutex);
16256 	mutex_destroy(&hw->aq.asq_mutex);
16257 
16258 	/* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
16259 	rtnl_lock();
16260 	i40e_clear_interrupt_scheme(pf);
16261 	i40e_pf_for_each_vsi(pf, i, vsi) {
16262 		if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
16263 			i40e_vsi_clear_rings(vsi);
16264 
16265 		i40e_vsi_clear(vsi);
16266 		pf->vsi[i] = NULL;
16267 	}
16268 	rtnl_unlock();
16269 
16270 	i40e_pf_for_each_veb(pf, i, veb) {
16271 		kfree(veb);
16272 		pf->veb[i] = NULL;
16273 	}
16274 
16275 	kfree(pf->qp_pile);
16276 	kfree(pf->vsi);
16277 
16278 	iounmap(hw->hw_addr);
16279 	i40e_free_pf(pf);
16280 	pci_release_mem_regions(pdev);
16281 
16282 	pci_disable_device(pdev);
16283 }
16284 
16285 /**
16286  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
16287  * using the mac_address_write admin q function
16288  * @pf: pointer to i40e_pf struct
16289  **/
16290 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
16291 {
16292 	struct i40e_vsi *main_vsi = i40e_pf_get_main_vsi(pf);
16293 	struct i40e_hw *hw = &pf->hw;
16294 	u8 mac_addr[6];
16295 	u16 flags = 0;
16296 	int ret;
16297 
16298 	/* Get current MAC address in case it's an LAA */
16299 	if (main_vsi && main_vsi->netdev) {
16300 		ether_addr_copy(mac_addr, main_vsi->netdev->dev_addr);
16301 	} else {
16302 		dev_err(&pf->pdev->dev,
16303 			"Failed to retrieve MAC address; using default\n");
16304 		ether_addr_copy(mac_addr, hw->mac.addr);
16305 	}
16306 
16307 	/* The FW expects the mac address write cmd to first be called with
16308 	 * one of these flags before calling it again with the multicast
16309 	 * enable flags.
16310 	 */
16311 	flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
16312 
16313 	if (hw->func_caps.flex10_enable && hw->partition_id != 1)
16314 		flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
16315 
16316 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16317 	if (ret) {
16318 		dev_err(&pf->pdev->dev,
16319 			"Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
16320 		return;
16321 	}
16322 
16323 	flags = I40E_AQC_MC_MAG_EN
16324 			| I40E_AQC_WOL_PRESERVE_ON_PFR
16325 			| I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
16326 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16327 	if (ret)
16328 		dev_err(&pf->pdev->dev,
16329 			"Failed to enable Multicast Magic Packet wake up\n");
16330 }
16331 
16332 /**
16333  * i40e_io_suspend - suspend all IO operations
16334  * @pf: pointer to i40e_pf struct
16335  *
16336  **/
16337 static int i40e_io_suspend(struct i40e_pf *pf)
16338 {
16339 	struct i40e_hw *hw = &pf->hw;
16340 
16341 	set_bit(__I40E_DOWN, pf->state);
16342 
16343 	/* Ensure service task will not be running */
16344 	timer_delete_sync(&pf->service_timer);
16345 	cancel_work_sync(&pf->service_task);
16346 
16347 	/* Client close must be called explicitly here because the timer
16348 	 * has been stopped.
16349 	 */
16350 	i40e_notify_client_of_netdev_close(pf, false);
16351 
16352 	if (test_bit(I40E_HW_CAP_WOL_MC_MAGIC_PKT_WAKE, pf->hw.caps) &&
16353 	    pf->wol_en)
16354 		i40e_enable_mc_magic_wake(pf);
16355 
16356 	/* Since we're going to destroy queues during the
16357 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16358 	 * whole section
16359 	 */
16360 	rtnl_lock();
16361 
16362 	i40e_prep_for_reset(pf);
16363 
16364 	wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16365 	wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16366 
16367 	/* Clear the interrupt scheme and release our IRQs so that the system
16368 	 * can safely hibernate even when there are a large number of CPUs.
16369 	 * Otherwise hibernation might fail when mapping all the vectors back
16370 	 * to CPU0.
16371 	 */
16372 	i40e_clear_interrupt_scheme(pf);
16373 
16374 	rtnl_unlock();
16375 
16376 	return 0;
16377 }
16378 
16379 /**
16380  * i40e_io_resume - resume IO operations
16381  * @pf: pointer to i40e_pf struct
16382  *
16383  **/
16384 static int i40e_io_resume(struct i40e_pf *pf)
16385 {
16386 	struct device *dev = &pf->pdev->dev;
16387 	int err;
16388 
16389 	/* We need to hold the RTNL lock prior to restoring interrupt schemes,
16390 	 * since we're going to be restoring queues
16391 	 */
16392 	rtnl_lock();
16393 
16394 	/* We cleared the interrupt scheme when we suspended, so we need to
16395 	 * restore it now to resume device functionality.
16396 	 */
16397 	err = i40e_restore_interrupt_scheme(pf);
16398 	if (err) {
16399 		dev_err(dev, "Cannot restore interrupt scheme: %d\n",
16400 			err);
16401 	}
16402 
16403 	clear_bit(__I40E_DOWN, pf->state);
16404 	i40e_reset_and_rebuild(pf, false, true);
16405 
16406 	rtnl_unlock();
16407 
16408 	/* Clear suspended state last after everything is recovered */
16409 	clear_bit(__I40E_SUSPENDED, pf->state);
16410 
16411 	/* Restart the service task */
16412 	mod_timer(&pf->service_timer,
16413 		  round_jiffies(jiffies + pf->service_timer_period));
16414 
16415 	return 0;
16416 }
16417 
16418 /**
16419  * i40e_pci_error_detected - warning that something funky happened in PCI land
16420  * @pdev: PCI device information struct
16421  * @error: the type of PCI error
16422  *
16423  * Called to warn that something happened and the error handling steps
16424  * are in progress.  Allows the driver to quiesce things, be ready for
16425  * remediation.
16426  **/
16427 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
16428 						pci_channel_state_t error)
16429 {
16430 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16431 
16432 	dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
16433 
16434 	if (!pf) {
16435 		dev_info(&pdev->dev,
16436 			 "Cannot recover - error happened during device probe\n");
16437 		return PCI_ERS_RESULT_DISCONNECT;
16438 	}
16439 
16440 	/* shutdown all operations */
16441 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16442 		i40e_io_suspend(pf);
16443 
16444 	/* Request a slot reset */
16445 	return PCI_ERS_RESULT_NEED_RESET;
16446 }
16447 
16448 /**
16449  * i40e_pci_error_slot_reset - a PCI slot reset just happened
16450  * @pdev: PCI device information struct
16451  *
16452  * Called to find if the driver can work with the device now that
16453  * the pci slot has been reset.  If a basic connection seems good
16454  * (registers are readable and have sane content) then return a
16455  * happy little PCI_ERS_RESULT_xxx.
16456  **/
16457 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
16458 {
16459 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16460 	pci_ers_result_t result;
16461 	u32 reg;
16462 
16463 	dev_dbg(&pdev->dev, "%s\n", __func__);
16464 	/* enable I/O and memory of the device  */
16465 	if (pci_enable_device(pdev)) {
16466 		dev_info(&pdev->dev,
16467 			 "Cannot re-enable PCI device after reset.\n");
16468 		result = PCI_ERS_RESULT_DISCONNECT;
16469 	} else {
16470 		pci_set_master(pdev);
16471 		pci_restore_state(pdev);
16472 		pci_wake_from_d3(pdev, false);
16473 
16474 		reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
16475 		if (reg == 0)
16476 			result = PCI_ERS_RESULT_RECOVERED;
16477 		else
16478 			result = PCI_ERS_RESULT_DISCONNECT;
16479 	}
16480 
16481 	return result;
16482 }
16483 
16484 /**
16485  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
16486  * @pdev: PCI device information struct
16487  */
16488 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
16489 {
16490 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16491 
16492 	i40e_prep_for_reset(pf);
16493 }
16494 
16495 /**
16496  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
16497  * @pdev: PCI device information struct
16498  */
16499 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
16500 {
16501 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16502 
16503 	if (test_bit(__I40E_IN_REMOVE, pf->state))
16504 		return;
16505 
16506 	i40e_reset_and_rebuild(pf, false, false);
16507 #ifdef CONFIG_PCI_IOV
16508 	i40e_restore_all_vfs_msi_state(pdev);
16509 #endif /* CONFIG_PCI_IOV */
16510 }
16511 
16512 /**
16513  * i40e_pci_error_resume - restart operations after PCI error recovery
16514  * @pdev: PCI device information struct
16515  *
16516  * Called to allow the driver to bring things back up after PCI error
16517  * and/or reset recovery has finished.
16518  **/
16519 static void i40e_pci_error_resume(struct pci_dev *pdev)
16520 {
16521 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16522 
16523 	dev_dbg(&pdev->dev, "%s\n", __func__);
16524 	if (test_bit(__I40E_SUSPENDED, pf->state))
16525 		return;
16526 
16527 	i40e_io_resume(pf);
16528 }
16529 
16530 /**
16531  * i40e_shutdown - PCI callback for shutting down
16532  * @pdev: PCI device information struct
16533  **/
16534 static void i40e_shutdown(struct pci_dev *pdev)
16535 {
16536 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16537 	struct i40e_hw *hw = &pf->hw;
16538 
16539 	set_bit(__I40E_SUSPENDED, pf->state);
16540 	set_bit(__I40E_DOWN, pf->state);
16541 
16542 	timer_delete_sync(&pf->service_timer);
16543 	cancel_work_sync(&pf->service_task);
16544 	i40e_cloud_filter_exit(pf);
16545 	i40e_fdir_teardown(pf);
16546 
16547 	/* Client close must be called explicitly here because the timer
16548 	 * has been stopped.
16549 	 */
16550 	i40e_notify_client_of_netdev_close(pf, false);
16551 
16552 	if (test_bit(I40E_HW_CAP_WOL_MC_MAGIC_PKT_WAKE, pf->hw.caps) &&
16553 	    pf->wol_en)
16554 		i40e_enable_mc_magic_wake(pf);
16555 
16556 	i40e_prep_for_reset(pf);
16557 
16558 	wr32(hw, I40E_PFPM_APM,
16559 	     (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16560 	wr32(hw, I40E_PFPM_WUFC,
16561 	     (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16562 
16563 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16564 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16565 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
16566 		free_irq(pf->pdev->irq, pf);
16567 
16568 	/* Since we're going to destroy queues during the
16569 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16570 	 * whole section
16571 	 */
16572 	rtnl_lock();
16573 	i40e_clear_interrupt_scheme(pf);
16574 	rtnl_unlock();
16575 
16576 	if (system_state == SYSTEM_POWER_OFF) {
16577 		pci_wake_from_d3(pdev, pf->wol_en);
16578 		pci_set_power_state(pdev, PCI_D3hot);
16579 	}
16580 }
16581 
16582 /**
16583  * i40e_suspend - PM callback for moving to D3
16584  * @dev: generic device information structure
16585  **/
16586 static int i40e_suspend(struct device *dev)
16587 {
16588 	struct i40e_pf *pf = dev_get_drvdata(dev);
16589 
16590 	/* If we're already suspended, then there is nothing to do */
16591 	if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
16592 		return 0;
16593 	return i40e_io_suspend(pf);
16594 }
16595 
16596 /**
16597  * i40e_resume - PM callback for waking up from D3
16598  * @dev: generic device information structure
16599  **/
16600 static int i40e_resume(struct device *dev)
16601 {
16602 	struct i40e_pf *pf = dev_get_drvdata(dev);
16603 
16604 	/* If we're not suspended, then there is nothing to do */
16605 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16606 		return 0;
16607 	return i40e_io_resume(pf);
16608 }
16609 
16610 static const struct pci_error_handlers i40e_err_handler = {
16611 	.error_detected = i40e_pci_error_detected,
16612 	.slot_reset = i40e_pci_error_slot_reset,
16613 	.reset_prepare = i40e_pci_error_reset_prepare,
16614 	.reset_done = i40e_pci_error_reset_done,
16615 	.resume = i40e_pci_error_resume,
16616 };
16617 
16618 static DEFINE_SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
16619 
16620 static struct pci_driver i40e_driver = {
16621 	.name     = i40e_driver_name,
16622 	.id_table = i40e_pci_tbl,
16623 	.probe    = i40e_probe,
16624 	.remove   = i40e_remove,
16625 	.driver.pm = pm_sleep_ptr(&i40e_pm_ops),
16626 	.shutdown = i40e_shutdown,
16627 	.err_handler = &i40e_err_handler,
16628 	.sriov_configure = i40e_pci_sriov_configure,
16629 };
16630 
16631 /**
16632  * i40e_init_module - Driver registration routine
16633  *
16634  * i40e_init_module is the first routine called when the driver is
16635  * loaded. All it does is register with the PCI subsystem.
16636  **/
16637 static int __init i40e_init_module(void)
16638 {
16639 	int err;
16640 
16641 	pr_info("%s: %s\n", i40e_driver_name, i40e_driver_string);
16642 	pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
16643 
16644 	/* There is no need to throttle the number of active tasks because
16645 	 * each device limits its own task using a state bit for scheduling
16646 	 * the service task, and the device tasks do not interfere with each
16647 	 * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
16648 	 * since we need to be able to guarantee forward progress even under
16649 	 * memory pressure.
16650 	 */
16651 	i40e_wq = alloc_workqueue("%s", WQ_PERCPU, 0, i40e_driver_name);
16652 	if (!i40e_wq) {
16653 		pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
16654 		return -ENOMEM;
16655 	}
16656 
16657 	i40e_dbg_init();
16658 	err = pci_register_driver(&i40e_driver);
16659 	if (err) {
16660 		destroy_workqueue(i40e_wq);
16661 		i40e_dbg_exit();
16662 		return err;
16663 	}
16664 
16665 	return 0;
16666 }
16667 module_init(i40e_init_module);
16668 
16669 /**
16670  * i40e_exit_module - Driver exit cleanup routine
16671  *
16672  * i40e_exit_module is called just before the driver is removed
16673  * from memory.
16674  **/
16675 static void __exit i40e_exit_module(void)
16676 {
16677 	pci_unregister_driver(&i40e_driver);
16678 	destroy_workqueue(i40e_wq);
16679 	ida_destroy(&i40e_client_ida);
16680 	i40e_dbg_exit();
16681 }
16682 module_exit(i40e_exit_module);
16683