xref: /linux/drivers/net/ethernet/intel/i40e/i40e_main.c (revision 0ce92d548b44649a8de706f9bb9e74a4ed2f18a7)
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), 0},
67 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QEMU), 0},
68 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_B), 0},
69 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_C), 0},
70 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_A), 0},
71 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_B), 0},
72 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_C), 0},
73 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_BC), 0},
74 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T), 0},
75 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T4), 0},
76 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_BC), 0},
77 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_SFP), 0},
78 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_B), 0},
79 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_X722), 0},
80 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_X722), 0},
81 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722), 0},
82 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_X722), 0},
83 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_X722), 0},
84 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_I_X722), 0},
85 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722_A), 0},
86 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2), 0},
87 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A), 0},
88 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_X710_N3000), 0},
89 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_XXV710_N3000), 0},
90 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B), 0},
91 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28), 0},
92 	/* required last entry */
93 	{0, }
94 };
95 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
96 
97 #define I40E_MAX_VF_COUNT 128
98 static int debug = -1;
99 module_param(debug, uint, 0);
100 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
101 
102 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
103 MODULE_IMPORT_NS("LIBIE");
104 MODULE_LICENSE("GPL v2");
105 
106 static struct workqueue_struct *i40e_wq;
107 
108 static void netdev_hw_addr_refcnt(struct i40e_mac_filter *f,
109 				  struct net_device *netdev, int delta)
110 {
111 	struct netdev_hw_addr_list *ha_list;
112 	struct netdev_hw_addr *ha;
113 
114 	if (!f || !netdev)
115 		return;
116 
117 	if (is_unicast_ether_addr(f->macaddr) || is_link_local_ether_addr(f->macaddr))
118 		ha_list = &netdev->uc;
119 	else
120 		ha_list = &netdev->mc;
121 
122 	netdev_hw_addr_list_for_each(ha, ha_list) {
123 		if (ether_addr_equal(ha->addr, f->macaddr)) {
124 			ha->refcount += delta;
125 			if (ha->refcount <= 0)
126 				ha->refcount = 1;
127 			break;
128 		}
129 	}
130 }
131 
132 /**
133  * i40e_hw_to_dev - get device pointer from the hardware structure
134  * @hw: pointer to the device HW structure
135  **/
136 struct device *i40e_hw_to_dev(struct i40e_hw *hw)
137 {
138 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
139 
140 	return &pf->pdev->dev;
141 }
142 
143 /**
144  * i40e_allocate_dma_mem - OS specific memory alloc for shared code
145  * @hw:   pointer to the HW structure
146  * @mem:  ptr to mem struct to fill out
147  * @size: size of memory requested
148  * @alignment: what to align the allocation to
149  **/
150 int i40e_allocate_dma_mem(struct i40e_hw *hw, struct i40e_dma_mem *mem,
151 			  u64 size, u32 alignment)
152 {
153 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
154 
155 	mem->size = ALIGN(size, alignment);
156 	mem->va = dma_alloc_coherent(&pf->pdev->dev, mem->size, &mem->pa,
157 				     GFP_KERNEL);
158 	if (!mem->va)
159 		return -ENOMEM;
160 
161 	return 0;
162 }
163 
164 /**
165  * i40e_free_dma_mem - OS specific memory free for shared code
166  * @hw:   pointer to the HW structure
167  * @mem:  ptr to mem struct to free
168  **/
169 int i40e_free_dma_mem(struct i40e_hw *hw, struct i40e_dma_mem *mem)
170 {
171 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
172 
173 	dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
174 	mem->va = NULL;
175 	mem->pa = 0;
176 	mem->size = 0;
177 
178 	return 0;
179 }
180 
181 /**
182  * i40e_allocate_virt_mem - OS specific memory alloc for shared code
183  * @hw:   pointer to the HW structure
184  * @mem:  ptr to mem struct to fill out
185  * @size: size of memory requested
186  **/
187 int i40e_allocate_virt_mem(struct i40e_hw *hw, struct i40e_virt_mem *mem,
188 			   u32 size)
189 {
190 	mem->size = size;
191 	mem->va = kzalloc(size, GFP_KERNEL);
192 
193 	if (!mem->va)
194 		return -ENOMEM;
195 
196 	return 0;
197 }
198 
199 /**
200  * i40e_free_virt_mem - OS specific memory free for shared code
201  * @hw:   pointer to the HW structure
202  * @mem:  ptr to mem struct to free
203  **/
204 int i40e_free_virt_mem(struct i40e_hw *hw, struct i40e_virt_mem *mem)
205 {
206 	/* it's ok to kfree a NULL pointer */
207 	kfree(mem->va);
208 	mem->va = NULL;
209 	mem->size = 0;
210 
211 	return 0;
212 }
213 
214 /**
215  * i40e_get_lump - find a lump of free generic resource
216  * @pf: board private structure
217  * @pile: the pile of resource to search
218  * @needed: the number of items needed
219  * @id: an owner id to stick on the items assigned
220  *
221  * Returns the base item index of the lump, or negative for error
222  **/
223 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
224 			 u16 needed, u16 id)
225 {
226 	int ret = -ENOMEM;
227 	int i, j;
228 
229 	if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
230 		dev_info(&pf->pdev->dev,
231 			 "param err: pile=%s needed=%d id=0x%04x\n",
232 			 pile ? "<valid>" : "<null>", needed, id);
233 		return -EINVAL;
234 	}
235 
236 	/* Allocate last queue in the pile for FDIR VSI queue
237 	 * so it doesn't fragment the qp_pile
238 	 */
239 	if (pile == pf->qp_pile && pf->vsi[id]->type == I40E_VSI_FDIR) {
240 		if (pile->list[pile->num_entries - 1] & I40E_PILE_VALID_BIT) {
241 			dev_err(&pf->pdev->dev,
242 				"Cannot allocate queue %d for I40E_VSI_FDIR\n",
243 				pile->num_entries - 1);
244 			return -ENOMEM;
245 		}
246 		pile->list[pile->num_entries - 1] = id | I40E_PILE_VALID_BIT;
247 		return pile->num_entries - 1;
248 	}
249 
250 	i = 0;
251 	while (i < pile->num_entries) {
252 		/* skip already allocated entries */
253 		if (pile->list[i] & I40E_PILE_VALID_BIT) {
254 			i++;
255 			continue;
256 		}
257 
258 		/* do we have enough in this lump? */
259 		for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
260 			if (pile->list[i+j] & I40E_PILE_VALID_BIT)
261 				break;
262 		}
263 
264 		if (j == needed) {
265 			/* there was enough, so assign it to the requestor */
266 			for (j = 0; j < needed; j++)
267 				pile->list[i+j] = id | I40E_PILE_VALID_BIT;
268 			ret = i;
269 			break;
270 		}
271 
272 		/* not enough, so skip over it and continue looking */
273 		i += j;
274 	}
275 
276 	return ret;
277 }
278 
279 /**
280  * i40e_put_lump - return a lump of generic resource
281  * @pile: the pile of resource to search
282  * @index: the base item index
283  * @id: the owner id of the items assigned
284  *
285  * Returns the count of items in the lump
286  **/
287 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
288 {
289 	int valid_id = (id | I40E_PILE_VALID_BIT);
290 	int count = 0;
291 	u16 i;
292 
293 	if (!pile || index >= pile->num_entries)
294 		return -EINVAL;
295 
296 	for (i = index;
297 	     i < pile->num_entries && pile->list[i] == valid_id;
298 	     i++) {
299 		pile->list[i] = 0;
300 		count++;
301 	}
302 
303 
304 	return count;
305 }
306 
307 /**
308  * i40e_find_vsi_from_id - searches for the vsi with the given id
309  * @pf: the pf structure to search for the vsi
310  * @id: id of the vsi it is searching for
311  **/
312 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
313 {
314 	struct i40e_vsi *vsi;
315 	int i;
316 
317 	i40e_pf_for_each_vsi(pf, i, vsi)
318 		if (vsi->id == id)
319 			return vsi;
320 
321 	return NULL;
322 }
323 
324 /**
325  * i40e_service_event_schedule - Schedule the service task to wake up
326  * @pf: board private structure
327  *
328  * If not already scheduled, this puts the task into the work queue
329  **/
330 void i40e_service_event_schedule(struct i40e_pf *pf)
331 {
332 	if ((!test_bit(__I40E_DOWN, pf->state) &&
333 	     !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) ||
334 	      test_bit(__I40E_RECOVERY_MODE, pf->state))
335 		queue_work(i40e_wq, &pf->service_task);
336 }
337 
338 /**
339  * i40e_tx_timeout - Respond to a Tx Hang
340  * @netdev: network interface device structure
341  * @txqueue: queue number timing out
342  *
343  * If any port has noticed a Tx timeout, it is likely that the whole
344  * device is munged, not just the one netdev port, so go for the full
345  * reset.
346  **/
347 static void i40e_tx_timeout(struct net_device *netdev, unsigned int txqueue)
348 {
349 	struct i40e_netdev_priv *np = netdev_priv(netdev);
350 	struct i40e_vsi *vsi = np->vsi;
351 	struct i40e_pf *pf = vsi->back;
352 	struct i40e_ring *tx_ring = NULL;
353 	unsigned int i;
354 	u32 head, val;
355 
356 	pf->tx_timeout_count++;
357 
358 	/* with txqueue index, find the tx_ring struct */
359 	for (i = 0; i < vsi->num_queue_pairs; i++) {
360 		if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
361 			if (txqueue ==
362 			    vsi->tx_rings[i]->queue_index) {
363 				tx_ring = vsi->tx_rings[i];
364 				break;
365 			}
366 		}
367 	}
368 
369 	if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
370 		pf->tx_timeout_recovery_level = 1;  /* reset after some time */
371 	else if (time_before(jiffies,
372 		      (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
373 		return;   /* don't do any new action before the next timeout */
374 
375 	/* don't kick off another recovery if one is already pending */
376 	if (test_and_set_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state))
377 		return;
378 
379 	if (tx_ring) {
380 		head = i40e_get_head(tx_ring);
381 		/* Read interrupt register */
382 		if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
383 			val = rd32(&pf->hw,
384 			     I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
385 						tx_ring->vsi->base_vector - 1));
386 		else
387 			val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
388 
389 		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",
390 			    vsi->seid, txqueue, tx_ring->next_to_clean,
391 			    head, tx_ring->next_to_use,
392 			    readl(tx_ring->tail), val);
393 	}
394 
395 	pf->tx_timeout_last_recovery = jiffies;
396 	netdev_info(netdev, "tx_timeout recovery level %d, txqueue %d\n",
397 		    pf->tx_timeout_recovery_level, txqueue);
398 
399 	switch (pf->tx_timeout_recovery_level) {
400 	case 1:
401 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
402 		break;
403 	case 2:
404 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
405 		break;
406 	case 3:
407 		set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
408 		break;
409 	default:
410 		netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in non-recoverable state.\n");
411 		set_bit(__I40E_DOWN_REQUESTED, pf->state);
412 		set_bit(__I40E_VSI_DOWN_REQUESTED, vsi->state);
413 		break;
414 	}
415 
416 	i40e_service_event_schedule(pf);
417 	pf->tx_timeout_recovery_level++;
418 }
419 
420 /**
421  * i40e_get_vsi_stats_struct - Get System Network Statistics
422  * @vsi: the VSI we care about
423  *
424  * Returns the address of the device statistics structure.
425  * The statistics are actually updated from the service task.
426  **/
427 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
428 {
429 	return &vsi->net_stats;
430 }
431 
432 /**
433  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
434  * @ring: Tx ring to get statistics from
435  * @stats: statistics entry to be updated
436  **/
437 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
438 					    struct rtnl_link_stats64 *stats)
439 {
440 	u64 bytes, packets;
441 	unsigned int start;
442 
443 	do {
444 		start = u64_stats_fetch_begin(&ring->syncp);
445 		packets = ring->stats.packets;
446 		bytes   = ring->stats.bytes;
447 	} while (u64_stats_fetch_retry(&ring->syncp, start));
448 
449 	stats->tx_packets += packets;
450 	stats->tx_bytes   += bytes;
451 }
452 
453 /**
454  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
455  * @netdev: network interface device structure
456  * @stats: data structure to store statistics
457  *
458  * Returns the address of the device statistics structure.
459  * The statistics are actually updated from the service task.
460  **/
461 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
462 				  struct rtnl_link_stats64 *stats)
463 {
464 	struct i40e_netdev_priv *np = netdev_priv(netdev);
465 	struct i40e_vsi *vsi = np->vsi;
466 	struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
467 	struct i40e_ring *ring;
468 	int i;
469 
470 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
471 		return;
472 
473 	if (!vsi->tx_rings)
474 		return;
475 
476 	rcu_read_lock();
477 	for (i = 0; i < vsi->num_queue_pairs; i++) {
478 		u64 bytes, packets;
479 		unsigned int start;
480 
481 		ring = READ_ONCE(vsi->tx_rings[i]);
482 		if (!ring)
483 			continue;
484 		i40e_get_netdev_stats_struct_tx(ring, stats);
485 
486 		if (i40e_enabled_xdp_vsi(vsi)) {
487 			ring = READ_ONCE(vsi->xdp_rings[i]);
488 			if (!ring)
489 				continue;
490 			i40e_get_netdev_stats_struct_tx(ring, stats);
491 		}
492 
493 		ring = READ_ONCE(vsi->rx_rings[i]);
494 		if (!ring)
495 			continue;
496 		do {
497 			start   = u64_stats_fetch_begin(&ring->syncp);
498 			packets = ring->stats.packets;
499 			bytes   = ring->stats.bytes;
500 		} while (u64_stats_fetch_retry(&ring->syncp, start));
501 
502 		stats->rx_packets += packets;
503 		stats->rx_bytes   += bytes;
504 
505 	}
506 	rcu_read_unlock();
507 
508 	/* following stats updated by i40e_watchdog_subtask() */
509 	stats->multicast	= vsi_stats->multicast;
510 	stats->tx_errors	= vsi_stats->tx_errors;
511 	stats->tx_dropped	= vsi_stats->tx_dropped;
512 	stats->rx_errors	= vsi_stats->rx_errors;
513 	stats->rx_dropped	= vsi_stats->rx_dropped;
514 	stats->rx_missed_errors	= vsi_stats->rx_missed_errors;
515 	stats->rx_crc_errors	= vsi_stats->rx_crc_errors;
516 	stats->rx_length_errors	= vsi_stats->rx_length_errors;
517 }
518 
519 /**
520  * i40e_vsi_reset_stats - Resets all stats of the given vsi
521  * @vsi: the VSI to have its stats reset
522  **/
523 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
524 {
525 	struct rtnl_link_stats64 *ns;
526 	int i;
527 
528 	if (!vsi)
529 		return;
530 
531 	ns = i40e_get_vsi_stats_struct(vsi);
532 	memset(ns, 0, sizeof(*ns));
533 	memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
534 	memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
535 	memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
536 	if (vsi->rx_rings && vsi->rx_rings[0]) {
537 		for (i = 0; i < vsi->num_queue_pairs; i++) {
538 			memset(&vsi->rx_rings[i]->stats, 0,
539 			       sizeof(vsi->rx_rings[i]->stats));
540 			memset(&vsi->rx_rings[i]->rx_stats, 0,
541 			       sizeof(vsi->rx_rings[i]->rx_stats));
542 			memset(&vsi->tx_rings[i]->stats, 0,
543 			       sizeof(vsi->tx_rings[i]->stats));
544 			memset(&vsi->tx_rings[i]->tx_stats, 0,
545 			       sizeof(vsi->tx_rings[i]->tx_stats));
546 		}
547 	}
548 	vsi->stat_offsets_loaded = false;
549 }
550 
551 /**
552  * i40e_pf_reset_stats - Reset all of the stats for the given PF
553  * @pf: the PF to be reset
554  **/
555 void i40e_pf_reset_stats(struct i40e_pf *pf)
556 {
557 	struct i40e_veb *veb;
558 	int i;
559 
560 	memset(&pf->stats, 0, sizeof(pf->stats));
561 	memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
562 	pf->stat_offsets_loaded = false;
563 
564 	i40e_pf_for_each_veb(pf, i, veb) {
565 		memset(&veb->stats, 0, sizeof(veb->stats));
566 		memset(&veb->stats_offsets, 0, sizeof(veb->stats_offsets));
567 		memset(&veb->tc_stats, 0, sizeof(veb->tc_stats));
568 		memset(&veb->tc_stats_offsets, 0, sizeof(veb->tc_stats_offsets));
569 		veb->stat_offsets_loaded = false;
570 	}
571 	pf->hw_csum_rx_error = 0;
572 }
573 
574 /**
575  * i40e_compute_pci_to_hw_id - compute index form PCI function.
576  * @vsi: ptr to the VSI to read from.
577  * @hw: ptr to the hardware info.
578  **/
579 static u32 i40e_compute_pci_to_hw_id(struct i40e_vsi *vsi, struct i40e_hw *hw)
580 {
581 	int pf_count = i40e_get_pf_count(hw);
582 
583 	if (vsi->type == I40E_VSI_SRIOV)
584 		return (hw->port * BIT(7)) / pf_count + vsi->vf_id;
585 
586 	return hw->port + BIT(7);
587 }
588 
589 /**
590  * i40e_stat_update64 - read and update a 64 bit stat from the chip.
591  * @hw: ptr to the hardware info.
592  * @hireg: the high 32 bit reg to read.
593  * @loreg: the low 32 bit reg to read.
594  * @offset_loaded: has the initial offset been loaded yet.
595  * @offset: ptr to current offset value.
596  * @stat: ptr to the stat.
597  *
598  * Since the device stats are not reset at PFReset, they will not
599  * be zeroed when the driver starts.  We'll save the first values read
600  * and use them as offsets to be subtracted from the raw values in order
601  * to report stats that count from zero.
602  **/
603 static void i40e_stat_update64(struct i40e_hw *hw, u32 hireg, u32 loreg,
604 			       bool offset_loaded, u64 *offset, u64 *stat)
605 {
606 	u64 new_data;
607 
608 	new_data = rd64(hw, loreg);
609 
610 	if (!offset_loaded || new_data < *offset)
611 		*offset = new_data;
612 	*stat = new_data - *offset;
613 }
614 
615 /**
616  * i40e_stat_update48 - read and update a 48 bit stat from the chip
617  * @hw: ptr to the hardware info
618  * @hireg: the high 32 bit reg to read
619  * @loreg: the low 32 bit reg to read
620  * @offset_loaded: has the initial offset been loaded yet
621  * @offset: ptr to current offset value
622  * @stat: ptr to the stat
623  *
624  * Since the device stats are not reset at PFReset, they likely will not
625  * be zeroed when the driver starts.  We'll save the first values read
626  * and use them as offsets to be subtracted from the raw values in order
627  * to report stats that count from zero.  In the process, we also manage
628  * the potential roll-over.
629  **/
630 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
631 			       bool offset_loaded, u64 *offset, u64 *stat)
632 {
633 	u64 new_data;
634 
635 	if (hw->device_id == I40E_DEV_ID_QEMU) {
636 		new_data = rd32(hw, loreg);
637 		new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
638 	} else {
639 		new_data = rd64(hw, loreg);
640 	}
641 	if (!offset_loaded)
642 		*offset = new_data;
643 	if (likely(new_data >= *offset))
644 		*stat = new_data - *offset;
645 	else
646 		*stat = (new_data + BIT_ULL(48)) - *offset;
647 	*stat &= 0xFFFFFFFFFFFFULL;
648 }
649 
650 /**
651  * i40e_stat_update32 - read and update a 32 bit stat from the chip
652  * @hw: ptr to the hardware info
653  * @reg: the hw reg to read
654  * @offset_loaded: has the initial offset been loaded yet
655  * @offset: ptr to current offset value
656  * @stat: ptr to the stat
657  **/
658 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
659 			       bool offset_loaded, u64 *offset, u64 *stat)
660 {
661 	u32 new_data;
662 
663 	new_data = rd32(hw, reg);
664 	if (!offset_loaded)
665 		*offset = new_data;
666 	if (likely(new_data >= *offset))
667 		*stat = (u32)(new_data - *offset);
668 	else
669 		*stat = (u32)((new_data + BIT_ULL(32)) - *offset);
670 }
671 
672 /**
673  * i40e_stat_update_and_clear32 - read and clear hw reg, update a 32 bit stat
674  * @hw: ptr to the hardware info
675  * @reg: the hw reg to read and clear
676  * @stat: ptr to the stat
677  **/
678 static void i40e_stat_update_and_clear32(struct i40e_hw *hw, u32 reg, u64 *stat)
679 {
680 	u32 new_data = rd32(hw, reg);
681 
682 	wr32(hw, reg, 1); /* must write a nonzero value to clear register */
683 	*stat += new_data;
684 }
685 
686 /**
687  * i40e_stats_update_rx_discards - update rx_discards.
688  * @vsi: ptr to the VSI to be updated.
689  * @hw: ptr to the hardware info.
690  * @stat_idx: VSI's stat_counter_idx.
691  * @offset_loaded: ptr to the VSI's stat_offsets_loaded.
692  * @stat_offset: ptr to stat_offset to store first read of specific register.
693  * @stat: ptr to VSI's stat to be updated.
694  **/
695 static void
696 i40e_stats_update_rx_discards(struct i40e_vsi *vsi, struct i40e_hw *hw,
697 			      int stat_idx, bool offset_loaded,
698 			      struct i40e_eth_stats *stat_offset,
699 			      struct i40e_eth_stats *stat)
700 {
701 	i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx), offset_loaded,
702 			   &stat_offset->rx_discards, &stat->rx_discards);
703 	i40e_stat_update64(hw,
704 			   I40E_GL_RXERR1H(i40e_compute_pci_to_hw_id(vsi, hw)),
705 			   I40E_GL_RXERR1L(i40e_compute_pci_to_hw_id(vsi, hw)),
706 			   offset_loaded, &stat_offset->rx_discards_other,
707 			   &stat->rx_discards_other);
708 }
709 
710 /**
711  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
712  * @vsi: the VSI to be updated
713  **/
714 void i40e_update_eth_stats(struct i40e_vsi *vsi)
715 {
716 	int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
717 	struct i40e_pf *pf = vsi->back;
718 	struct i40e_hw *hw = &pf->hw;
719 	struct i40e_eth_stats *oes;
720 	struct i40e_eth_stats *es;     /* device's eth stats */
721 
722 	es = &vsi->eth_stats;
723 	oes = &vsi->eth_stats_offsets;
724 
725 	/* Gather up the stats that the hw collects */
726 	i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
727 			   vsi->stat_offsets_loaded,
728 			   &oes->tx_errors, &es->tx_errors);
729 	i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
730 			   vsi->stat_offsets_loaded,
731 			   &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
732 
733 	i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
734 			   I40E_GLV_GORCL(stat_idx),
735 			   vsi->stat_offsets_loaded,
736 			   &oes->rx_bytes, &es->rx_bytes);
737 	i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
738 			   I40E_GLV_UPRCL(stat_idx),
739 			   vsi->stat_offsets_loaded,
740 			   &oes->rx_unicast, &es->rx_unicast);
741 	i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
742 			   I40E_GLV_MPRCL(stat_idx),
743 			   vsi->stat_offsets_loaded,
744 			   &oes->rx_multicast, &es->rx_multicast);
745 	i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
746 			   I40E_GLV_BPRCL(stat_idx),
747 			   vsi->stat_offsets_loaded,
748 			   &oes->rx_broadcast, &es->rx_broadcast);
749 
750 	i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
751 			   I40E_GLV_GOTCL(stat_idx),
752 			   vsi->stat_offsets_loaded,
753 			   &oes->tx_bytes, &es->tx_bytes);
754 	i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
755 			   I40E_GLV_UPTCL(stat_idx),
756 			   vsi->stat_offsets_loaded,
757 			   &oes->tx_unicast, &es->tx_unicast);
758 	i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
759 			   I40E_GLV_MPTCL(stat_idx),
760 			   vsi->stat_offsets_loaded,
761 			   &oes->tx_multicast, &es->tx_multicast);
762 	i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
763 			   I40E_GLV_BPTCL(stat_idx),
764 			   vsi->stat_offsets_loaded,
765 			   &oes->tx_broadcast, &es->tx_broadcast);
766 
767 	i40e_stats_update_rx_discards(vsi, hw, stat_idx,
768 				      vsi->stat_offsets_loaded, oes, es);
769 
770 	vsi->stat_offsets_loaded = true;
771 }
772 
773 /**
774  * i40e_update_veb_stats - Update Switch component statistics
775  * @veb: the VEB being updated
776  **/
777 void i40e_update_veb_stats(struct i40e_veb *veb)
778 {
779 	struct i40e_pf *pf = veb->pf;
780 	struct i40e_hw *hw = &pf->hw;
781 	struct i40e_eth_stats *oes;
782 	struct i40e_eth_stats *es;     /* device's eth stats */
783 	struct i40e_veb_tc_stats *veb_oes;
784 	struct i40e_veb_tc_stats *veb_es;
785 	int i, idx = 0;
786 
787 	idx = veb->stats_idx;
788 	es = &veb->stats;
789 	oes = &veb->stats_offsets;
790 	veb_es = &veb->tc_stats;
791 	veb_oes = &veb->tc_stats_offsets;
792 
793 	/* Gather up the stats that the hw collects */
794 	i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
795 			   veb->stat_offsets_loaded,
796 			   &oes->tx_discards, &es->tx_discards);
797 	if (hw->revision_id > 0)
798 		i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
799 				   veb->stat_offsets_loaded,
800 				   &oes->rx_unknown_protocol,
801 				   &es->rx_unknown_protocol);
802 	i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
803 			   veb->stat_offsets_loaded,
804 			   &oes->rx_bytes, &es->rx_bytes);
805 	i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
806 			   veb->stat_offsets_loaded,
807 			   &oes->rx_unicast, &es->rx_unicast);
808 	i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
809 			   veb->stat_offsets_loaded,
810 			   &oes->rx_multicast, &es->rx_multicast);
811 	i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
812 			   veb->stat_offsets_loaded,
813 			   &oes->rx_broadcast, &es->rx_broadcast);
814 
815 	i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
816 			   veb->stat_offsets_loaded,
817 			   &oes->tx_bytes, &es->tx_bytes);
818 	i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
819 			   veb->stat_offsets_loaded,
820 			   &oes->tx_unicast, &es->tx_unicast);
821 	i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
822 			   veb->stat_offsets_loaded,
823 			   &oes->tx_multicast, &es->tx_multicast);
824 	i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
825 			   veb->stat_offsets_loaded,
826 			   &oes->tx_broadcast, &es->tx_broadcast);
827 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
828 		i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
829 				   I40E_GLVEBTC_RPCL(i, idx),
830 				   veb->stat_offsets_loaded,
831 				   &veb_oes->tc_rx_packets[i],
832 				   &veb_es->tc_rx_packets[i]);
833 		i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
834 				   I40E_GLVEBTC_RBCL(i, idx),
835 				   veb->stat_offsets_loaded,
836 				   &veb_oes->tc_rx_bytes[i],
837 				   &veb_es->tc_rx_bytes[i]);
838 		i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
839 				   I40E_GLVEBTC_TPCL(i, idx),
840 				   veb->stat_offsets_loaded,
841 				   &veb_oes->tc_tx_packets[i],
842 				   &veb_es->tc_tx_packets[i]);
843 		i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
844 				   I40E_GLVEBTC_TBCL(i, idx),
845 				   veb->stat_offsets_loaded,
846 				   &veb_oes->tc_tx_bytes[i],
847 				   &veb_es->tc_tx_bytes[i]);
848 	}
849 	veb->stat_offsets_loaded = true;
850 }
851 
852 /**
853  * i40e_update_vsi_stats - Update the vsi statistics counters.
854  * @vsi: the VSI to be updated
855  *
856  * There are a few instances where we store the same stat in a
857  * couple of different structs.  This is partly because we have
858  * the netdev stats that need to be filled out, which is slightly
859  * different from the "eth_stats" defined by the chip and used in
860  * VF communications.  We sort it out here.
861  **/
862 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
863 {
864 	u64 rx_page, rx_buf, rx_reuse, rx_alloc, rx_waive, rx_busy;
865 	struct i40e_pf *pf = vsi->back;
866 	struct rtnl_link_stats64 *ons;
867 	struct rtnl_link_stats64 *ns;   /* netdev stats */
868 	struct i40e_eth_stats *oes;
869 	struct i40e_eth_stats *es;     /* device's eth stats */
870 	u64 tx_restart, tx_busy;
871 	struct i40e_ring *p;
872 	u64 bytes, packets;
873 	unsigned int start;
874 	u64 tx_linearize;
875 	u64 tx_force_wb;
876 	u64 tx_stopped;
877 	u64 rx_p, rx_b;
878 	u64 tx_p, tx_b;
879 	u16 q;
880 
881 	if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
882 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
883 		return;
884 
885 	ns = i40e_get_vsi_stats_struct(vsi);
886 	ons = &vsi->net_stats_offsets;
887 	es = &vsi->eth_stats;
888 	oes = &vsi->eth_stats_offsets;
889 
890 	/* Gather up the netdev and vsi stats that the driver collects
891 	 * on the fly during packet processing
892 	 */
893 	rx_b = rx_p = 0;
894 	tx_b = tx_p = 0;
895 	tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
896 	tx_stopped = 0;
897 	rx_page = 0;
898 	rx_buf = 0;
899 	rx_reuse = 0;
900 	rx_alloc = 0;
901 	rx_waive = 0;
902 	rx_busy = 0;
903 	rcu_read_lock();
904 	for (q = 0; q < vsi->num_queue_pairs; q++) {
905 		/* locate Tx ring */
906 		p = READ_ONCE(vsi->tx_rings[q]);
907 		if (!p)
908 			continue;
909 
910 		do {
911 			start = u64_stats_fetch_begin(&p->syncp);
912 			packets = p->stats.packets;
913 			bytes = p->stats.bytes;
914 		} while (u64_stats_fetch_retry(&p->syncp, start));
915 		tx_b += bytes;
916 		tx_p += packets;
917 		tx_restart += p->tx_stats.restart_queue;
918 		tx_busy += p->tx_stats.tx_busy;
919 		tx_linearize += p->tx_stats.tx_linearize;
920 		tx_force_wb += p->tx_stats.tx_force_wb;
921 		tx_stopped += p->tx_stats.tx_stopped;
922 
923 		/* locate Rx ring */
924 		p = READ_ONCE(vsi->rx_rings[q]);
925 		if (!p)
926 			continue;
927 
928 		do {
929 			start = u64_stats_fetch_begin(&p->syncp);
930 			packets = p->stats.packets;
931 			bytes = p->stats.bytes;
932 		} while (u64_stats_fetch_retry(&p->syncp, start));
933 		rx_b += bytes;
934 		rx_p += packets;
935 		rx_buf += p->rx_stats.alloc_buff_failed;
936 		rx_page += p->rx_stats.alloc_page_failed;
937 		rx_reuse += p->rx_stats.page_reuse_count;
938 		rx_alloc += p->rx_stats.page_alloc_count;
939 		rx_waive += p->rx_stats.page_waive_count;
940 		rx_busy += p->rx_stats.page_busy_count;
941 
942 		if (i40e_enabled_xdp_vsi(vsi)) {
943 			/* locate XDP ring */
944 			p = READ_ONCE(vsi->xdp_rings[q]);
945 			if (!p)
946 				continue;
947 
948 			do {
949 				start = u64_stats_fetch_begin(&p->syncp);
950 				packets = p->stats.packets;
951 				bytes = p->stats.bytes;
952 			} while (u64_stats_fetch_retry(&p->syncp, start));
953 			tx_b += bytes;
954 			tx_p += packets;
955 			tx_restart += p->tx_stats.restart_queue;
956 			tx_busy += p->tx_stats.tx_busy;
957 			tx_linearize += p->tx_stats.tx_linearize;
958 			tx_force_wb += p->tx_stats.tx_force_wb;
959 		}
960 	}
961 	rcu_read_unlock();
962 	vsi->tx_restart = tx_restart;
963 	vsi->tx_busy = tx_busy;
964 	vsi->tx_linearize = tx_linearize;
965 	vsi->tx_force_wb = tx_force_wb;
966 	vsi->tx_stopped = tx_stopped;
967 	vsi->rx_page_failed = rx_page;
968 	vsi->rx_buf_failed = rx_buf;
969 	vsi->rx_page_reuse = rx_reuse;
970 	vsi->rx_page_alloc = rx_alloc;
971 	vsi->rx_page_waive = rx_waive;
972 	vsi->rx_page_busy = rx_busy;
973 
974 	ns->rx_packets = rx_p;
975 	ns->rx_bytes = rx_b;
976 	ns->tx_packets = tx_p;
977 	ns->tx_bytes = tx_b;
978 
979 	/* update netdev stats from eth stats */
980 	i40e_update_eth_stats(vsi);
981 	ons->tx_errors = oes->tx_errors;
982 	ns->tx_errors = es->tx_errors;
983 	ons->multicast = oes->rx_multicast;
984 	ns->multicast = es->rx_multicast;
985 	ons->rx_dropped = oes->rx_discards_other;
986 	ns->rx_dropped = es->rx_discards_other;
987 	ons->rx_missed_errors = oes->rx_discards;
988 	ns->rx_missed_errors = es->rx_discards;
989 	ons->tx_dropped = oes->tx_discards;
990 	ns->tx_dropped = es->tx_discards;
991 
992 	/* pull in a couple PF stats if this is the main vsi */
993 	if (vsi->type == I40E_VSI_MAIN) {
994 		ns->rx_crc_errors = pf->stats.crc_errors;
995 		ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
996 		ns->rx_length_errors = pf->stats.rx_length_errors;
997 	}
998 }
999 
1000 /**
1001  * i40e_update_pf_stats - Update the PF statistics counters.
1002  * @pf: the PF to be updated
1003  **/
1004 static void i40e_update_pf_stats(struct i40e_pf *pf)
1005 {
1006 	struct i40e_hw_port_stats *osd = &pf->stats_offsets;
1007 	struct i40e_hw_port_stats *nsd = &pf->stats;
1008 	struct i40e_hw *hw = &pf->hw;
1009 	u32 val;
1010 	int i;
1011 
1012 	i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
1013 			   I40E_GLPRT_GORCL(hw->port),
1014 			   pf->stat_offsets_loaded,
1015 			   &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
1016 	i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
1017 			   I40E_GLPRT_GOTCL(hw->port),
1018 			   pf->stat_offsets_loaded,
1019 			   &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
1020 	i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
1021 			   pf->stat_offsets_loaded,
1022 			   &osd->eth.rx_discards,
1023 			   &nsd->eth.rx_discards);
1024 	i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
1025 			   I40E_GLPRT_UPRCL(hw->port),
1026 			   pf->stat_offsets_loaded,
1027 			   &osd->eth.rx_unicast,
1028 			   &nsd->eth.rx_unicast);
1029 	i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
1030 			   I40E_GLPRT_MPRCL(hw->port),
1031 			   pf->stat_offsets_loaded,
1032 			   &osd->eth.rx_multicast,
1033 			   &nsd->eth.rx_multicast);
1034 	i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
1035 			   I40E_GLPRT_BPRCL(hw->port),
1036 			   pf->stat_offsets_loaded,
1037 			   &osd->eth.rx_broadcast,
1038 			   &nsd->eth.rx_broadcast);
1039 	i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
1040 			   I40E_GLPRT_UPTCL(hw->port),
1041 			   pf->stat_offsets_loaded,
1042 			   &osd->eth.tx_unicast,
1043 			   &nsd->eth.tx_unicast);
1044 	i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
1045 			   I40E_GLPRT_MPTCL(hw->port),
1046 			   pf->stat_offsets_loaded,
1047 			   &osd->eth.tx_multicast,
1048 			   &nsd->eth.tx_multicast);
1049 	i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
1050 			   I40E_GLPRT_BPTCL(hw->port),
1051 			   pf->stat_offsets_loaded,
1052 			   &osd->eth.tx_broadcast,
1053 			   &nsd->eth.tx_broadcast);
1054 
1055 	i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
1056 			   pf->stat_offsets_loaded,
1057 			   &osd->tx_dropped_link_down,
1058 			   &nsd->tx_dropped_link_down);
1059 
1060 	i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
1061 			   pf->stat_offsets_loaded,
1062 			   &osd->crc_errors, &nsd->crc_errors);
1063 
1064 	i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
1065 			   pf->stat_offsets_loaded,
1066 			   &osd->illegal_bytes, &nsd->illegal_bytes);
1067 
1068 	i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
1069 			   pf->stat_offsets_loaded,
1070 			   &osd->mac_local_faults,
1071 			   &nsd->mac_local_faults);
1072 	i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
1073 			   pf->stat_offsets_loaded,
1074 			   &osd->mac_remote_faults,
1075 			   &nsd->mac_remote_faults);
1076 
1077 	i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
1078 			   pf->stat_offsets_loaded,
1079 			   &osd->rx_length_errors,
1080 			   &nsd->rx_length_errors);
1081 
1082 	i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
1083 			   pf->stat_offsets_loaded,
1084 			   &osd->link_xon_rx, &nsd->link_xon_rx);
1085 	i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
1086 			   pf->stat_offsets_loaded,
1087 			   &osd->link_xon_tx, &nsd->link_xon_tx);
1088 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
1089 			   pf->stat_offsets_loaded,
1090 			   &osd->link_xoff_rx, &nsd->link_xoff_rx);
1091 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
1092 			   pf->stat_offsets_loaded,
1093 			   &osd->link_xoff_tx, &nsd->link_xoff_tx);
1094 
1095 	for (i = 0; i < 8; i++) {
1096 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
1097 				   pf->stat_offsets_loaded,
1098 				   &osd->priority_xoff_rx[i],
1099 				   &nsd->priority_xoff_rx[i]);
1100 		i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
1101 				   pf->stat_offsets_loaded,
1102 				   &osd->priority_xon_rx[i],
1103 				   &nsd->priority_xon_rx[i]);
1104 		i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
1105 				   pf->stat_offsets_loaded,
1106 				   &osd->priority_xon_tx[i],
1107 				   &nsd->priority_xon_tx[i]);
1108 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
1109 				   pf->stat_offsets_loaded,
1110 				   &osd->priority_xoff_tx[i],
1111 				   &nsd->priority_xoff_tx[i]);
1112 		i40e_stat_update32(hw,
1113 				   I40E_GLPRT_RXON2OFFCNT(hw->port, i),
1114 				   pf->stat_offsets_loaded,
1115 				   &osd->priority_xon_2_xoff[i],
1116 				   &nsd->priority_xon_2_xoff[i]);
1117 	}
1118 
1119 	i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
1120 			   I40E_GLPRT_PRC64L(hw->port),
1121 			   pf->stat_offsets_loaded,
1122 			   &osd->rx_size_64, &nsd->rx_size_64);
1123 	i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
1124 			   I40E_GLPRT_PRC127L(hw->port),
1125 			   pf->stat_offsets_loaded,
1126 			   &osd->rx_size_127, &nsd->rx_size_127);
1127 	i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
1128 			   I40E_GLPRT_PRC255L(hw->port),
1129 			   pf->stat_offsets_loaded,
1130 			   &osd->rx_size_255, &nsd->rx_size_255);
1131 	i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
1132 			   I40E_GLPRT_PRC511L(hw->port),
1133 			   pf->stat_offsets_loaded,
1134 			   &osd->rx_size_511, &nsd->rx_size_511);
1135 	i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
1136 			   I40E_GLPRT_PRC1023L(hw->port),
1137 			   pf->stat_offsets_loaded,
1138 			   &osd->rx_size_1023, &nsd->rx_size_1023);
1139 	i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
1140 			   I40E_GLPRT_PRC1522L(hw->port),
1141 			   pf->stat_offsets_loaded,
1142 			   &osd->rx_size_1522, &nsd->rx_size_1522);
1143 	i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
1144 			   I40E_GLPRT_PRC9522L(hw->port),
1145 			   pf->stat_offsets_loaded,
1146 			   &osd->rx_size_big, &nsd->rx_size_big);
1147 
1148 	i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1149 			   I40E_GLPRT_PTC64L(hw->port),
1150 			   pf->stat_offsets_loaded,
1151 			   &osd->tx_size_64, &nsd->tx_size_64);
1152 	i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1153 			   I40E_GLPRT_PTC127L(hw->port),
1154 			   pf->stat_offsets_loaded,
1155 			   &osd->tx_size_127, &nsd->tx_size_127);
1156 	i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1157 			   I40E_GLPRT_PTC255L(hw->port),
1158 			   pf->stat_offsets_loaded,
1159 			   &osd->tx_size_255, &nsd->tx_size_255);
1160 	i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1161 			   I40E_GLPRT_PTC511L(hw->port),
1162 			   pf->stat_offsets_loaded,
1163 			   &osd->tx_size_511, &nsd->tx_size_511);
1164 	i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1165 			   I40E_GLPRT_PTC1023L(hw->port),
1166 			   pf->stat_offsets_loaded,
1167 			   &osd->tx_size_1023, &nsd->tx_size_1023);
1168 	i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1169 			   I40E_GLPRT_PTC1522L(hw->port),
1170 			   pf->stat_offsets_loaded,
1171 			   &osd->tx_size_1522, &nsd->tx_size_1522);
1172 	i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1173 			   I40E_GLPRT_PTC9522L(hw->port),
1174 			   pf->stat_offsets_loaded,
1175 			   &osd->tx_size_big, &nsd->tx_size_big);
1176 
1177 	i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1178 			   pf->stat_offsets_loaded,
1179 			   &osd->rx_undersize, &nsd->rx_undersize);
1180 	i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1181 			   pf->stat_offsets_loaded,
1182 			   &osd->rx_fragments, &nsd->rx_fragments);
1183 	i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1184 			   pf->stat_offsets_loaded,
1185 			   &osd->rx_oversize, &nsd->rx_oversize);
1186 	i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1187 			   pf->stat_offsets_loaded,
1188 			   &osd->rx_jabber, &nsd->rx_jabber);
1189 
1190 	/* FDIR stats */
1191 	i40e_stat_update_and_clear32(hw,
1192 			I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(hw->pf_id)),
1193 			&nsd->fd_atr_match);
1194 	i40e_stat_update_and_clear32(hw,
1195 			I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(hw->pf_id)),
1196 			&nsd->fd_sb_match);
1197 	i40e_stat_update_and_clear32(hw,
1198 			I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(hw->pf_id)),
1199 			&nsd->fd_atr_tunnel_match);
1200 
1201 	val = rd32(hw, I40E_PRTPM_EEE_STAT);
1202 	nsd->tx_lpi_status =
1203 		       FIELD_GET(I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK, val);
1204 	nsd->rx_lpi_status =
1205 		       FIELD_GET(I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK, val);
1206 	i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1207 			   pf->stat_offsets_loaded,
1208 			   &osd->tx_lpi_count, &nsd->tx_lpi_count);
1209 	i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1210 			   pf->stat_offsets_loaded,
1211 			   &osd->rx_lpi_count, &nsd->rx_lpi_count);
1212 
1213 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
1214 	    !test_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
1215 		nsd->fd_sb_status = true;
1216 	else
1217 		nsd->fd_sb_status = false;
1218 
1219 	if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
1220 	    !test_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
1221 		nsd->fd_atr_status = true;
1222 	else
1223 		nsd->fd_atr_status = false;
1224 
1225 	pf->stat_offsets_loaded = true;
1226 }
1227 
1228 /**
1229  * i40e_update_stats - Update the various statistics counters.
1230  * @vsi: the VSI to be updated
1231  *
1232  * Update the various stats for this VSI and its related entities.
1233  **/
1234 void i40e_update_stats(struct i40e_vsi *vsi)
1235 {
1236 	struct i40e_pf *pf = vsi->back;
1237 
1238 	if (vsi->type == I40E_VSI_MAIN)
1239 		i40e_update_pf_stats(pf);
1240 
1241 	i40e_update_vsi_stats(vsi);
1242 }
1243 
1244 /**
1245  * i40e_count_filters - counts VSI mac filters
1246  * @vsi: the VSI to be searched
1247  *
1248  * Returns count of mac filters
1249  **/
1250 int i40e_count_filters(struct i40e_vsi *vsi)
1251 {
1252 	struct i40e_mac_filter *f;
1253 	struct hlist_node *h;
1254 	int bkt;
1255 	int cnt = 0;
1256 
1257 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1258 		if (f->state == I40E_FILTER_NEW ||
1259 		    f->state == I40E_FILTER_NEW_SYNC ||
1260 		    f->state == I40E_FILTER_ACTIVE)
1261 			++cnt;
1262 	}
1263 
1264 	return cnt;
1265 }
1266 
1267 /**
1268  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1269  * @vsi: the VSI to be searched
1270  * @macaddr: the MAC address
1271  * @vlan: the vlan
1272  *
1273  * Returns ptr to the filter object or NULL
1274  **/
1275 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1276 						const u8 *macaddr, s16 vlan)
1277 {
1278 	struct i40e_mac_filter *f;
1279 	u64 key;
1280 
1281 	if (!vsi || !macaddr)
1282 		return NULL;
1283 
1284 	key = i40e_addr_to_hkey(macaddr);
1285 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1286 		if ((ether_addr_equal(macaddr, f->macaddr)) &&
1287 		    (vlan == f->vlan))
1288 			return f;
1289 	}
1290 	return NULL;
1291 }
1292 
1293 /**
1294  * i40e_find_mac - Find a mac addr in the macvlan filters list
1295  * @vsi: the VSI to be searched
1296  * @macaddr: the MAC address we are searching for
1297  *
1298  * Returns the first filter with the provided MAC address or NULL if
1299  * MAC address was not found
1300  **/
1301 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1302 {
1303 	struct i40e_mac_filter *f;
1304 	u64 key;
1305 
1306 	if (!vsi || !macaddr)
1307 		return NULL;
1308 
1309 	key = i40e_addr_to_hkey(macaddr);
1310 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1311 		if ((ether_addr_equal(macaddr, f->macaddr)))
1312 			return f;
1313 	}
1314 	return NULL;
1315 }
1316 
1317 /**
1318  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1319  * @vsi: the VSI to be searched
1320  *
1321  * Returns true if VSI is in vlan mode or false otherwise
1322  **/
1323 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1324 {
1325 	/* If we have a PVID, always operate in VLAN mode */
1326 	if (vsi->info.pvid)
1327 		return true;
1328 
1329 	/* We need to operate in VLAN mode whenever we have any filters with
1330 	 * a VLAN other than I40E_VLAN_ALL. We could check the table each
1331 	 * time, incurring search cost repeatedly. However, we can notice two
1332 	 * things:
1333 	 *
1334 	 * 1) the only place where we can gain a VLAN filter is in
1335 	 *    i40e_add_filter.
1336 	 *
1337 	 * 2) the only place where filters are actually removed is in
1338 	 *    i40e_sync_filters_subtask.
1339 	 *
1340 	 * Thus, we can simply use a boolean value, has_vlan_filters which we
1341 	 * will set to true when we add a VLAN filter in i40e_add_filter. Then
1342 	 * we have to perform the full search after deleting filters in
1343 	 * i40e_sync_filters_subtask, but we already have to search
1344 	 * filters here and can perform the check at the same time. This
1345 	 * results in avoiding embedding a loop for VLAN mode inside another
1346 	 * loop over all the filters, and should maintain correctness as noted
1347 	 * above.
1348 	 */
1349 	return vsi->has_vlan_filter;
1350 }
1351 
1352 /**
1353  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1354  * @vsi: the VSI to configure
1355  * @tmp_add_list: list of filters ready to be added
1356  * @tmp_del_list: list of filters ready to be deleted
1357  * @vlan_filters: the number of active VLAN filters
1358  *
1359  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1360  * behave as expected. If we have any active VLAN filters remaining or about
1361  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1362  * so that they only match against untagged traffic. If we no longer have any
1363  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1364  * so that they match against both tagged and untagged traffic. In this way,
1365  * we ensure that we correctly receive the desired traffic. This ensures that
1366  * when we have an active VLAN we will receive only untagged traffic and
1367  * traffic matching active VLANs. If we have no active VLANs then we will
1368  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1369  *
1370  * Finally, in a similar fashion, this function also corrects filters when
1371  * there is an active PVID assigned to this VSI.
1372  *
1373  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1374  *
1375  * This function is only expected to be called from within
1376  * i40e_sync_vsi_filters.
1377  *
1378  * NOTE: This function expects to be called while under the
1379  * mac_filter_hash_lock
1380  */
1381 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1382 					 struct hlist_head *tmp_add_list,
1383 					 struct hlist_head *tmp_del_list,
1384 					 int vlan_filters)
1385 {
1386 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1387 	struct i40e_mac_filter *f, *add_head;
1388 	struct i40e_new_mac_filter *new;
1389 	struct hlist_node *h;
1390 	int bkt, new_vlan;
1391 
1392 	/* To determine if a particular filter needs to be replaced we
1393 	 * have the three following conditions:
1394 	 *
1395 	 * a) if we have a PVID assigned, then all filters which are
1396 	 *    not marked as VLAN=PVID must be replaced with filters that
1397 	 *    are.
1398 	 * b) otherwise, if we have any active VLANS, all filters
1399 	 *    which are marked as VLAN=-1 must be replaced with
1400 	 *    filters marked as VLAN=0
1401 	 * c) finally, if we do not have any active VLANS, all filters
1402 	 *    which are marked as VLAN=0 must be replaced with filters
1403 	 *    marked as VLAN=-1
1404 	 */
1405 
1406 	/* Update the filters about to be added in place */
1407 	hlist_for_each_entry(new, tmp_add_list, hlist) {
1408 		if (pvid && new->f->vlan != pvid)
1409 			new->f->vlan = pvid;
1410 		else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1411 			new->f->vlan = 0;
1412 		else if (!vlan_filters && new->f->vlan == 0)
1413 			new->f->vlan = I40E_VLAN_ANY;
1414 	}
1415 
1416 	/* Update the remaining active filters */
1417 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1418 		/* Combine the checks for whether a filter needs to be changed
1419 		 * and then determine the new VLAN inside the if block, in
1420 		 * order to avoid duplicating code for adding the new filter
1421 		 * then deleting the old filter.
1422 		 */
1423 		if ((pvid && f->vlan != pvid) ||
1424 		    (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1425 		    (!vlan_filters && f->vlan == 0)) {
1426 			/* Determine the new vlan we will be adding */
1427 			if (pvid)
1428 				new_vlan = pvid;
1429 			else if (vlan_filters)
1430 				new_vlan = 0;
1431 			else
1432 				new_vlan = I40E_VLAN_ANY;
1433 
1434 			/* Create the new filter */
1435 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1436 			if (!add_head)
1437 				return -ENOMEM;
1438 
1439 			/* Create a temporary i40e_new_mac_filter */
1440 			new = kzalloc(sizeof(*new), GFP_ATOMIC);
1441 			if (!new)
1442 				return -ENOMEM;
1443 
1444 			new->f = add_head;
1445 			new->state = add_head->state;
1446 			if (add_head->state == I40E_FILTER_NEW)
1447 				add_head->state = I40E_FILTER_NEW_SYNC;
1448 
1449 			/* Add the new filter to the tmp list */
1450 			hlist_add_head(&new->hlist, tmp_add_list);
1451 
1452 			/* Put the original filter into the delete list */
1453 			f->state = I40E_FILTER_REMOVE;
1454 			hash_del(&f->hlist);
1455 			hlist_add_head(&f->hlist, tmp_del_list);
1456 		}
1457 	}
1458 
1459 	vsi->has_vlan_filter = !!vlan_filters;
1460 
1461 	return 0;
1462 }
1463 
1464 /**
1465  * i40e_get_vf_new_vlan - Get new vlan id on a vf
1466  * @vsi: the vsi to configure
1467  * @new_mac: new mac filter to be added
1468  * @f: existing mac filter, replaced with new_mac->f if new_mac is not NULL
1469  * @vlan_filters: the number of active VLAN filters
1470  * @trusted: flag if the VF is trusted
1471  *
1472  * Get new VLAN id based on current VLAN filters, trust, PVID
1473  * and vf-vlan-prune-disable flag.
1474  *
1475  * Returns the value of the new vlan filter or
1476  * the old value if no new filter is needed.
1477  */
1478 static s16 i40e_get_vf_new_vlan(struct i40e_vsi *vsi,
1479 				struct i40e_new_mac_filter *new_mac,
1480 				struct i40e_mac_filter *f,
1481 				int vlan_filters,
1482 				bool trusted)
1483 {
1484 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1485 	struct i40e_pf *pf = vsi->back;
1486 	bool is_any;
1487 
1488 	if (new_mac)
1489 		f = new_mac->f;
1490 
1491 	if (pvid && f->vlan != pvid)
1492 		return pvid;
1493 
1494 	is_any = (trusted ||
1495 		  !test_bit(I40E_FLAG_VF_VLAN_PRUNING_ENA, pf->flags));
1496 
1497 	if ((vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1498 	    (!is_any && !vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1499 	    (is_any && !vlan_filters && f->vlan == 0)) {
1500 		if (is_any)
1501 			return I40E_VLAN_ANY;
1502 		else
1503 			return 0;
1504 	}
1505 
1506 	return f->vlan;
1507 }
1508 
1509 /**
1510  * i40e_correct_vf_mac_vlan_filters - Correct non-VLAN VF filters if necessary
1511  * @vsi: the vsi to configure
1512  * @tmp_add_list: list of filters ready to be added
1513  * @tmp_del_list: list of filters ready to be deleted
1514  * @vlan_filters: the number of active VLAN filters
1515  * @trusted: flag if the VF is trusted
1516  *
1517  * Correct VF VLAN filters based on current VLAN filters, trust, PVID
1518  * and vf-vlan-prune-disable flag.
1519  *
1520  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1521  *
1522  * This function is only expected to be called from within
1523  * i40e_sync_vsi_filters.
1524  *
1525  * NOTE: This function expects to be called while under the
1526  * mac_filter_hash_lock
1527  */
1528 static int i40e_correct_vf_mac_vlan_filters(struct i40e_vsi *vsi,
1529 					    struct hlist_head *tmp_add_list,
1530 					    struct hlist_head *tmp_del_list,
1531 					    int vlan_filters,
1532 					    bool trusted)
1533 {
1534 	struct i40e_mac_filter *f, *add_head;
1535 	struct i40e_new_mac_filter *new_mac;
1536 	struct hlist_node *h;
1537 	int bkt, new_vlan;
1538 
1539 	hlist_for_each_entry(new_mac, tmp_add_list, hlist) {
1540 		new_mac->f->vlan = i40e_get_vf_new_vlan(vsi, new_mac, NULL,
1541 							vlan_filters, trusted);
1542 	}
1543 
1544 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1545 		new_vlan = i40e_get_vf_new_vlan(vsi, NULL, f, vlan_filters,
1546 						trusted);
1547 		if (new_vlan != f->vlan) {
1548 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1549 			if (!add_head)
1550 				return -ENOMEM;
1551 			/* Create a temporary i40e_new_mac_filter */
1552 			new_mac = kzalloc(sizeof(*new_mac), GFP_ATOMIC);
1553 			if (!new_mac)
1554 				return -ENOMEM;
1555 			new_mac->f = add_head;
1556 			new_mac->state = add_head->state;
1557 			if (add_head->state == I40E_FILTER_NEW)
1558 				add_head->state = I40E_FILTER_NEW_SYNC;
1559 
1560 			/* Add the new filter to the tmp list */
1561 			hlist_add_head(&new_mac->hlist, tmp_add_list);
1562 
1563 			/* Put the original filter into the delete list */
1564 			f->state = I40E_FILTER_REMOVE;
1565 			hash_del(&f->hlist);
1566 			hlist_add_head(&f->hlist, tmp_del_list);
1567 		}
1568 	}
1569 
1570 	vsi->has_vlan_filter = !!vlan_filters;
1571 	return 0;
1572 }
1573 
1574 /**
1575  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1576  * @vsi: the PF Main VSI - inappropriate for any other VSI
1577  * @macaddr: the MAC address
1578  *
1579  * Remove whatever filter the firmware set up so the driver can manage
1580  * its own filtering intelligently.
1581  **/
1582 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1583 {
1584 	struct i40e_aqc_remove_macvlan_element_data element;
1585 	struct i40e_pf *pf = vsi->back;
1586 
1587 	/* Only appropriate for the PF main VSI */
1588 	if (vsi->type != I40E_VSI_MAIN)
1589 		return;
1590 
1591 	memset(&element, 0, sizeof(element));
1592 	ether_addr_copy(element.mac_addr, macaddr);
1593 	element.vlan_tag = 0;
1594 	/* Ignore error returns, some firmware does it this way... */
1595 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1596 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1597 
1598 	memset(&element, 0, sizeof(element));
1599 	ether_addr_copy(element.mac_addr, macaddr);
1600 	element.vlan_tag = 0;
1601 	/* ...and some firmware does it this way. */
1602 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1603 			I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1604 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1605 }
1606 
1607 /**
1608  * i40e_add_filter - Add a mac/vlan filter to the VSI
1609  * @vsi: the VSI to be searched
1610  * @macaddr: the MAC address
1611  * @vlan: the vlan
1612  *
1613  * Returns ptr to the filter object or NULL when no memory available.
1614  *
1615  * NOTE: This function is expected to be called with mac_filter_hash_lock
1616  * being held.
1617  **/
1618 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1619 					const u8 *macaddr, s16 vlan)
1620 {
1621 	struct i40e_mac_filter *f;
1622 	u64 key;
1623 
1624 	if (!vsi || !macaddr)
1625 		return NULL;
1626 
1627 	f = i40e_find_filter(vsi, macaddr, vlan);
1628 	if (!f) {
1629 		f = kzalloc(sizeof(*f), GFP_ATOMIC);
1630 		if (!f)
1631 			return NULL;
1632 
1633 		/* Update the boolean indicating if we need to function in
1634 		 * VLAN mode.
1635 		 */
1636 		if (vlan >= 0)
1637 			vsi->has_vlan_filter = true;
1638 
1639 		ether_addr_copy(f->macaddr, macaddr);
1640 		f->vlan = vlan;
1641 		f->state = I40E_FILTER_NEW;
1642 		INIT_HLIST_NODE(&f->hlist);
1643 
1644 		key = i40e_addr_to_hkey(macaddr);
1645 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
1646 
1647 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1648 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1649 	}
1650 
1651 	/* If we're asked to add a filter that has been marked for removal, it
1652 	 * is safe to simply restore it to active state. __i40e_del_filter
1653 	 * will have simply deleted any filters which were previously marked
1654 	 * NEW or FAILED, so if it is currently marked REMOVE it must have
1655 	 * previously been ACTIVE. Since we haven't yet run the sync filters
1656 	 * task, just restore this filter to the ACTIVE state so that the
1657 	 * sync task leaves it in place
1658 	 */
1659 	if (f->state == I40E_FILTER_REMOVE)
1660 		f->state = I40E_FILTER_ACTIVE;
1661 
1662 	return f;
1663 }
1664 
1665 /**
1666  * __i40e_del_filter - Remove a specific filter from the VSI
1667  * @vsi: VSI to remove from
1668  * @f: the filter to remove from the list
1669  *
1670  * This function requires you've found * the exact filter you will remove
1671  * already, such as via i40e_find_filter or i40e_find_mac.
1672  *
1673  * NOTE: This function is expected to be called with mac_filter_hash_lock
1674  * being held.
1675  * ANOTHER NOTE: This function MUST be called from within the context of
1676  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1677  * instead of list_for_each_entry().
1678  **/
1679 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1680 {
1681 	if (!f)
1682 		return;
1683 
1684 	/* If the filter was never added to firmware then we can just delete it
1685 	 * directly and we don't want to set the status to remove or else an
1686 	 * admin queue command will unnecessarily fire.
1687 	 */
1688 	if ((f->state == I40E_FILTER_FAILED) ||
1689 	    (f->state == I40E_FILTER_NEW)) {
1690 		hash_del(&f->hlist);
1691 		kfree(f);
1692 	} else {
1693 		f->state = I40E_FILTER_REMOVE;
1694 	}
1695 
1696 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1697 	set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1698 }
1699 
1700 /**
1701  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1702  * @vsi: the VSI to be searched
1703  * @macaddr: the mac address to be filtered
1704  *
1705  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1706  * go through all the macvlan filters and add a macvlan filter for each
1707  * unique vlan that already exists. If a PVID has been assigned, instead only
1708  * add the macaddr to that VLAN.
1709  *
1710  * Returns last filter added on success, else NULL
1711  **/
1712 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1713 					    const u8 *macaddr)
1714 {
1715 	struct i40e_mac_filter *f, *add = NULL;
1716 	struct hlist_node *h;
1717 	int bkt;
1718 
1719 	lockdep_assert_held(&vsi->mac_filter_hash_lock);
1720 	if (vsi->info.pvid)
1721 		return i40e_add_filter(vsi, macaddr,
1722 				       le16_to_cpu(vsi->info.pvid));
1723 
1724 	if (!i40e_is_vsi_in_vlan(vsi))
1725 		return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1726 
1727 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1728 		if (f->state == I40E_FILTER_REMOVE)
1729 			continue;
1730 		add = i40e_add_filter(vsi, macaddr, f->vlan);
1731 		if (!add)
1732 			return NULL;
1733 	}
1734 
1735 	return add;
1736 }
1737 
1738 /**
1739  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1740  * @vsi: the VSI to be searched
1741  * @macaddr: the mac address to be removed
1742  *
1743  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1744  * associated with.
1745  *
1746  * Returns 0 for success, or error
1747  **/
1748 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1749 {
1750 	struct i40e_mac_filter *f;
1751 	struct hlist_node *h;
1752 	bool found = false;
1753 	int bkt;
1754 
1755 	lockdep_assert_held(&vsi->mac_filter_hash_lock);
1756 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1757 		if (ether_addr_equal(macaddr, f->macaddr)) {
1758 			__i40e_del_filter(vsi, f);
1759 			found = true;
1760 		}
1761 	}
1762 
1763 	if (found)
1764 		return 0;
1765 	else
1766 		return -ENOENT;
1767 }
1768 
1769 /**
1770  * i40e_set_mac - NDO callback to set mac address
1771  * @netdev: network interface device structure
1772  * @p: pointer to an address structure
1773  *
1774  * Returns 0 on success, negative on failure
1775  **/
1776 static int i40e_set_mac(struct net_device *netdev, void *p)
1777 {
1778 	struct i40e_netdev_priv *np = netdev_priv(netdev);
1779 	struct i40e_vsi *vsi = np->vsi;
1780 	struct i40e_pf *pf = vsi->back;
1781 	struct i40e_hw *hw = &pf->hw;
1782 	struct sockaddr *addr = p;
1783 
1784 	if (!is_valid_ether_addr(addr->sa_data))
1785 		return -EADDRNOTAVAIL;
1786 
1787 	if (test_bit(__I40E_DOWN, pf->state) ||
1788 	    test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1789 		return -EADDRNOTAVAIL;
1790 
1791 	if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1792 		netdev_info(netdev, "returning to hw mac address %pM\n",
1793 			    hw->mac.addr);
1794 	else
1795 		netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1796 
1797 	/* Copy the address first, so that we avoid a possible race with
1798 	 * .set_rx_mode().
1799 	 * - Remove old address from MAC filter
1800 	 * - Copy new address
1801 	 * - Add new address to MAC filter
1802 	 */
1803 	spin_lock_bh(&vsi->mac_filter_hash_lock);
1804 	i40e_del_mac_filter(vsi, netdev->dev_addr);
1805 	eth_hw_addr_set(netdev, addr->sa_data);
1806 	i40e_add_mac_filter(vsi, netdev->dev_addr);
1807 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
1808 
1809 	if (vsi->type == I40E_VSI_MAIN) {
1810 		int ret;
1811 
1812 		ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1813 						addr->sa_data, NULL);
1814 		if (ret)
1815 			netdev_info(netdev, "Ignoring error from firmware on LAA update, status %pe, AQ ret %s\n",
1816 				    ERR_PTR(ret),
1817 				    i40e_aq_str(hw, hw->aq.asq_last_status));
1818 	}
1819 
1820 	/* schedule our worker thread which will take care of
1821 	 * applying the new filter changes
1822 	 */
1823 	i40e_service_event_schedule(pf);
1824 	return 0;
1825 }
1826 
1827 /**
1828  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1829  * @vsi: vsi structure
1830  * @seed: RSS hash seed
1831  * @lut: pointer to lookup table of lut_size
1832  * @lut_size: size of the lookup table
1833  **/
1834 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1835 			      u8 *lut, u16 lut_size)
1836 {
1837 	struct i40e_pf *pf = vsi->back;
1838 	struct i40e_hw *hw = &pf->hw;
1839 	int ret = 0;
1840 
1841 	if (seed) {
1842 		struct i40e_aqc_get_set_rss_key_data *seed_dw =
1843 			(struct i40e_aqc_get_set_rss_key_data *)seed;
1844 		ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1845 		if (ret) {
1846 			dev_info(&pf->pdev->dev,
1847 				 "Cannot set RSS key, err %pe aq_err %s\n",
1848 				 ERR_PTR(ret),
1849 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1850 			return ret;
1851 		}
1852 	}
1853 	if (lut) {
1854 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
1855 
1856 		ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1857 		if (ret) {
1858 			dev_info(&pf->pdev->dev,
1859 				 "Cannot set RSS lut, err %pe aq_err %s\n",
1860 				 ERR_PTR(ret),
1861 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1862 			return ret;
1863 		}
1864 	}
1865 	return ret;
1866 }
1867 
1868 /**
1869  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1870  * @vsi: VSI structure
1871  **/
1872 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1873 {
1874 	struct i40e_pf *pf = vsi->back;
1875 	u8 seed[I40E_HKEY_ARRAY_SIZE];
1876 	u8 *lut;
1877 	int ret;
1878 
1879 	if (!test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
1880 		return 0;
1881 	if (!vsi->rss_size)
1882 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
1883 				      vsi->num_queue_pairs);
1884 	if (!vsi->rss_size)
1885 		return -EINVAL;
1886 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1887 	if (!lut)
1888 		return -ENOMEM;
1889 
1890 	/* Use the user configured hash keys and lookup table if there is one,
1891 	 * otherwise use default
1892 	 */
1893 	if (vsi->rss_lut_user)
1894 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1895 	else
1896 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1897 	if (vsi->rss_hkey_user)
1898 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1899 	else
1900 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1901 	ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1902 	kfree(lut);
1903 	return ret;
1904 }
1905 
1906 /**
1907  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1908  * @vsi: the VSI being configured,
1909  * @ctxt: VSI context structure
1910  * @enabled_tc: number of traffic classes to enable
1911  *
1912  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1913  **/
1914 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1915 					   struct i40e_vsi_context *ctxt,
1916 					   u8 enabled_tc)
1917 {
1918 	u16 qcount = 0, max_qcount, qmap, sections = 0;
1919 	int i, override_q, pow, num_qps, ret;
1920 	u8 netdev_tc = 0, offset = 0;
1921 
1922 	if (vsi->type != I40E_VSI_MAIN)
1923 		return -EINVAL;
1924 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1925 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1926 	vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1927 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1928 	num_qps = vsi->mqprio_qopt.qopt.count[0];
1929 
1930 	/* find the next higher power-of-2 of num queue pairs */
1931 	pow = ilog2(num_qps);
1932 	if (!is_power_of_2(num_qps))
1933 		pow++;
1934 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1935 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1936 
1937 	/* Setup queue offset/count for all TCs for given VSI */
1938 	max_qcount = vsi->mqprio_qopt.qopt.count[0];
1939 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1940 		/* See if the given TC is enabled for the given VSI */
1941 		if (vsi->tc_config.enabled_tc & BIT(i)) {
1942 			offset = vsi->mqprio_qopt.qopt.offset[i];
1943 			qcount = vsi->mqprio_qopt.qopt.count[i];
1944 			if (qcount > max_qcount)
1945 				max_qcount = qcount;
1946 			vsi->tc_config.tc_info[i].qoffset = offset;
1947 			vsi->tc_config.tc_info[i].qcount = qcount;
1948 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1949 		} else {
1950 			/* TC is not enabled so set the offset to
1951 			 * default queue and allocate one queue
1952 			 * for the given TC.
1953 			 */
1954 			vsi->tc_config.tc_info[i].qoffset = 0;
1955 			vsi->tc_config.tc_info[i].qcount = 1;
1956 			vsi->tc_config.tc_info[i].netdev_tc = 0;
1957 		}
1958 	}
1959 
1960 	/* Set actual Tx/Rx queue pairs */
1961 	vsi->num_queue_pairs = offset + qcount;
1962 
1963 	/* Setup queue TC[0].qmap for given VSI context */
1964 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1965 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1966 	ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1967 	ctxt->info.valid_sections |= cpu_to_le16(sections);
1968 
1969 	/* Reconfigure RSS for main VSI with max queue count */
1970 	vsi->rss_size = max_qcount;
1971 	ret = i40e_vsi_config_rss(vsi);
1972 	if (ret) {
1973 		dev_info(&vsi->back->pdev->dev,
1974 			 "Failed to reconfig rss for num_queues (%u)\n",
1975 			 max_qcount);
1976 		return ret;
1977 	}
1978 	vsi->reconfig_rss = true;
1979 	dev_dbg(&vsi->back->pdev->dev,
1980 		"Reconfigured rss with num_queues (%u)\n", max_qcount);
1981 
1982 	/* Find queue count available for channel VSIs and starting offset
1983 	 * for channel VSIs
1984 	 */
1985 	override_q = vsi->mqprio_qopt.qopt.count[0];
1986 	if (override_q && override_q < vsi->num_queue_pairs) {
1987 		vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
1988 		vsi->next_base_queue = override_q;
1989 	}
1990 	return 0;
1991 }
1992 
1993 /**
1994  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
1995  * @vsi: the VSI being setup
1996  * @ctxt: VSI context structure
1997  * @enabled_tc: Enabled TCs bitmap
1998  * @is_add: True if called before Add VSI
1999  *
2000  * Setup VSI queue mapping for enabled traffic classes.
2001  **/
2002 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
2003 				     struct i40e_vsi_context *ctxt,
2004 				     u8 enabled_tc,
2005 				     bool is_add)
2006 {
2007 	struct i40e_pf *pf = vsi->back;
2008 	u16 num_tc_qps = 0;
2009 	u16 sections = 0;
2010 	u8 netdev_tc = 0;
2011 	u16 numtc = 1;
2012 	u16 qcount;
2013 	u8 offset;
2014 	u16 qmap;
2015 	int i;
2016 
2017 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
2018 	offset = 0;
2019 	/* zero out queue mapping, it will get updated on the end of the function */
2020 	memset(ctxt->info.queue_mapping, 0, sizeof(ctxt->info.queue_mapping));
2021 
2022 	if (vsi->type == I40E_VSI_MAIN) {
2023 		/* This code helps add more queue to the VSI if we have
2024 		 * more cores than RSS can support, the higher cores will
2025 		 * be served by ATR or other filters. Furthermore, the
2026 		 * non-zero req_queue_pairs says that user requested a new
2027 		 * queue count via ethtool's set_channels, so use this
2028 		 * value for queues distribution across traffic classes
2029 		 * We need at least one queue pair for the interface
2030 		 * to be usable as we see in else statement.
2031 		 */
2032 		if (vsi->req_queue_pairs > 0)
2033 			vsi->num_queue_pairs = vsi->req_queue_pairs;
2034 		else if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
2035 			vsi->num_queue_pairs = pf->num_lan_msix;
2036 		else
2037 			vsi->num_queue_pairs = 1;
2038 	}
2039 
2040 	/* Number of queues per enabled TC */
2041 	if (vsi->type == I40E_VSI_MAIN ||
2042 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs != 0))
2043 		num_tc_qps = vsi->num_queue_pairs;
2044 	else
2045 		num_tc_qps = vsi->alloc_queue_pairs;
2046 
2047 	if (enabled_tc && test_bit(I40E_FLAG_DCB_ENA, vsi->back->flags)) {
2048 		/* Find numtc from enabled TC bitmap */
2049 		for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2050 			if (enabled_tc & BIT(i)) /* TC is enabled */
2051 				numtc++;
2052 		}
2053 		if (!numtc) {
2054 			dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
2055 			numtc = 1;
2056 		}
2057 		num_tc_qps = num_tc_qps / numtc;
2058 		num_tc_qps = min_t(int, num_tc_qps,
2059 				   i40e_pf_get_max_q_per_tc(pf));
2060 	}
2061 
2062 	vsi->tc_config.numtc = numtc;
2063 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
2064 
2065 	/* Do not allow use more TC queue pairs than MSI-X vectors exist */
2066 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
2067 		num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
2068 
2069 	/* Setup queue offset/count for all TCs for given VSI */
2070 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2071 		/* See if the given TC is enabled for the given VSI */
2072 		if (vsi->tc_config.enabled_tc & BIT(i)) {
2073 			/* TC is enabled */
2074 			int pow, num_qps;
2075 
2076 			switch (vsi->type) {
2077 			case I40E_VSI_MAIN:
2078 				if ((!test_bit(I40E_FLAG_FD_SB_ENA,
2079 					       pf->flags) &&
2080 				     !test_bit(I40E_FLAG_FD_ATR_ENA,
2081 					       pf->flags)) ||
2082 				    vsi->tc_config.enabled_tc != 1) {
2083 					qcount = min_t(int, pf->alloc_rss_size,
2084 						       num_tc_qps);
2085 					break;
2086 				}
2087 				fallthrough;
2088 			case I40E_VSI_FDIR:
2089 			case I40E_VSI_SRIOV:
2090 			case I40E_VSI_VMDQ2:
2091 			default:
2092 				qcount = num_tc_qps;
2093 				WARN_ON(i != 0);
2094 				break;
2095 			}
2096 			vsi->tc_config.tc_info[i].qoffset = offset;
2097 			vsi->tc_config.tc_info[i].qcount = qcount;
2098 
2099 			/* find the next higher power-of-2 of num queue pairs */
2100 			num_qps = qcount;
2101 			pow = 0;
2102 			while (num_qps && (BIT_ULL(pow) < qcount)) {
2103 				pow++;
2104 				num_qps >>= 1;
2105 			}
2106 
2107 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
2108 			qmap =
2109 			    (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
2110 			    (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
2111 
2112 			offset += qcount;
2113 		} else {
2114 			/* TC is not enabled so set the offset to
2115 			 * default queue and allocate one queue
2116 			 * for the given TC.
2117 			 */
2118 			vsi->tc_config.tc_info[i].qoffset = 0;
2119 			vsi->tc_config.tc_info[i].qcount = 1;
2120 			vsi->tc_config.tc_info[i].netdev_tc = 0;
2121 
2122 			qmap = 0;
2123 		}
2124 		ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
2125 	}
2126 	/* Do not change previously set num_queue_pairs for PFs and VFs*/
2127 	if ((vsi->type == I40E_VSI_MAIN && numtc != 1) ||
2128 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs == 0) ||
2129 	    (vsi->type != I40E_VSI_MAIN && vsi->type != I40E_VSI_SRIOV))
2130 		vsi->num_queue_pairs = offset;
2131 
2132 	/* Scheduler section valid can only be set for ADD VSI */
2133 	if (is_add) {
2134 		sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
2135 
2136 		ctxt->info.up_enable_bits = enabled_tc;
2137 	}
2138 	if (vsi->type == I40E_VSI_SRIOV) {
2139 		ctxt->info.mapping_flags |=
2140 				     cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
2141 		for (i = 0; i < vsi->num_queue_pairs; i++)
2142 			ctxt->info.queue_mapping[i] =
2143 					       cpu_to_le16(vsi->base_queue + i);
2144 	} else {
2145 		ctxt->info.mapping_flags |=
2146 					cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
2147 		ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
2148 	}
2149 	ctxt->info.valid_sections |= cpu_to_le16(sections);
2150 }
2151 
2152 /**
2153  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
2154  * @netdev: the netdevice
2155  * @addr: address to add
2156  *
2157  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
2158  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2159  */
2160 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
2161 {
2162 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2163 	struct i40e_vsi *vsi = np->vsi;
2164 
2165 	if (i40e_add_mac_filter(vsi, addr))
2166 		return 0;
2167 	else
2168 		return -ENOMEM;
2169 }
2170 
2171 /**
2172  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
2173  * @netdev: the netdevice
2174  * @addr: address to add
2175  *
2176  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
2177  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2178  */
2179 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
2180 {
2181 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2182 	struct i40e_vsi *vsi = np->vsi;
2183 
2184 	/* Under some circumstances, we might receive a request to delete
2185 	 * our own device address from our uc list. Because we store the
2186 	 * device address in the VSI's MAC/VLAN filter list, we need to ignore
2187 	 * such requests and not delete our device address from this list.
2188 	 */
2189 	if (ether_addr_equal(addr, netdev->dev_addr))
2190 		return 0;
2191 
2192 	i40e_del_mac_filter(vsi, addr);
2193 
2194 	return 0;
2195 }
2196 
2197 /**
2198  * i40e_set_rx_mode - NDO callback to set the netdev filters
2199  * @netdev: network interface device structure
2200  **/
2201 static void i40e_set_rx_mode(struct net_device *netdev)
2202 {
2203 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2204 	struct i40e_vsi *vsi = np->vsi;
2205 
2206 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2207 
2208 	__dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2209 	__dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2210 
2211 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2212 
2213 	/* check for other flag changes */
2214 	if (vsi->current_netdev_flags != vsi->netdev->flags) {
2215 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2216 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
2217 	}
2218 }
2219 
2220 /**
2221  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
2222  * @vsi: Pointer to VSI struct
2223  * @from: Pointer to list which contains MAC filter entries - changes to
2224  *        those entries needs to be undone.
2225  *
2226  * MAC filter entries from this list were slated for deletion.
2227  **/
2228 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
2229 					 struct hlist_head *from)
2230 {
2231 	struct i40e_mac_filter *f;
2232 	struct hlist_node *h;
2233 
2234 	hlist_for_each_entry_safe(f, h, from, hlist) {
2235 		u64 key = i40e_addr_to_hkey(f->macaddr);
2236 
2237 		/* Move the element back into MAC filter list*/
2238 		hlist_del(&f->hlist);
2239 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
2240 	}
2241 }
2242 
2243 /**
2244  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
2245  * @vsi: Pointer to vsi struct
2246  * @from: Pointer to list which contains MAC filter entries - changes to
2247  *        those entries needs to be undone.
2248  *
2249  * MAC filter entries from this list were slated for addition.
2250  **/
2251 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
2252 					 struct hlist_head *from)
2253 {
2254 	struct i40e_new_mac_filter *new;
2255 	struct hlist_node *h;
2256 
2257 	hlist_for_each_entry_safe(new, h, from, hlist) {
2258 		/* We can simply free the wrapper structure */
2259 		hlist_del(&new->hlist);
2260 		netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2261 		kfree(new);
2262 	}
2263 }
2264 
2265 /**
2266  * i40e_next_filter - Get the next non-broadcast filter from a list
2267  * @next: pointer to filter in list
2268  *
2269  * Returns the next non-broadcast filter in the list. Required so that we
2270  * ignore broadcast filters within the list, since these are not handled via
2271  * the normal firmware update path.
2272  */
2273 static
2274 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2275 {
2276 	hlist_for_each_entry_continue(next, hlist) {
2277 		if (!is_broadcast_ether_addr(next->f->macaddr))
2278 			return next;
2279 	}
2280 
2281 	return NULL;
2282 }
2283 
2284 /**
2285  * i40e_update_filter_state - Update filter state based on return data
2286  * from firmware
2287  * @count: Number of filters added
2288  * @add_list: return data from fw
2289  * @add_head: pointer to first filter in current batch
2290  *
2291  * MAC filter entries from list were slated to be added to device. Returns
2292  * number of successful filters. Note that 0 does NOT mean success!
2293  **/
2294 static int
2295 i40e_update_filter_state(int count,
2296 			 struct i40e_aqc_add_macvlan_element_data *add_list,
2297 			 struct i40e_new_mac_filter *add_head)
2298 {
2299 	int retval = 0;
2300 	int i;
2301 
2302 	for (i = 0; i < count; i++) {
2303 		/* Always check status of each filter. We don't need to check
2304 		 * the firmware return status because we pre-set the filter
2305 		 * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2306 		 * request to the adminq. Thus, if it no longer matches then
2307 		 * we know the filter is active.
2308 		 */
2309 		if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2310 			add_head->state = I40E_FILTER_FAILED;
2311 		} else {
2312 			add_head->state = I40E_FILTER_ACTIVE;
2313 			retval++;
2314 		}
2315 
2316 		add_head = i40e_next_filter(add_head);
2317 		if (!add_head)
2318 			break;
2319 	}
2320 
2321 	return retval;
2322 }
2323 
2324 /**
2325  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2326  * @vsi: ptr to the VSI
2327  * @vsi_name: name to display in messages
2328  * @list: the list of filters to send to firmware
2329  * @num_del: the number of filters to delete
2330  * @retval: Set to -EIO on failure to delete
2331  *
2332  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2333  * *retval instead of a return value so that success does not force ret_val to
2334  * be set to 0. This ensures that a sequence of calls to this function
2335  * preserve the previous value of *retval on successful delete.
2336  */
2337 static
2338 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2339 			  struct i40e_aqc_remove_macvlan_element_data *list,
2340 			  int num_del, int *retval)
2341 {
2342 	struct i40e_hw *hw = &vsi->back->hw;
2343 	enum i40e_admin_queue_err aq_status;
2344 	int aq_ret;
2345 
2346 	aq_ret = i40e_aq_remove_macvlan_v2(hw, vsi->seid, list, num_del, NULL,
2347 					   &aq_status);
2348 
2349 	/* Explicitly ignore and do not report when firmware returns ENOENT */
2350 	if (aq_ret && !(aq_status == I40E_AQ_RC_ENOENT)) {
2351 		*retval = -EIO;
2352 		dev_info(&vsi->back->pdev->dev,
2353 			 "ignoring delete macvlan error on %s, err %pe, aq_err %s\n",
2354 			 vsi_name, ERR_PTR(aq_ret),
2355 			 i40e_aq_str(hw, aq_status));
2356 	}
2357 }
2358 
2359 /**
2360  * i40e_aqc_add_filters - Request firmware to add a set of filters
2361  * @vsi: ptr to the VSI
2362  * @vsi_name: name to display in messages
2363  * @list: the list of filters to send to firmware
2364  * @add_head: Position in the add hlist
2365  * @num_add: the number of filters to add
2366  *
2367  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2368  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2369  * space for more filters.
2370  */
2371 static
2372 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2373 			  struct i40e_aqc_add_macvlan_element_data *list,
2374 			  struct i40e_new_mac_filter *add_head,
2375 			  int num_add)
2376 {
2377 	struct i40e_hw *hw = &vsi->back->hw;
2378 	enum i40e_admin_queue_err aq_status;
2379 	int fcnt;
2380 
2381 	i40e_aq_add_macvlan_v2(hw, vsi->seid, list, num_add, NULL, &aq_status);
2382 	fcnt = i40e_update_filter_state(num_add, list, add_head);
2383 
2384 	if (fcnt != num_add) {
2385 		if (vsi->type == I40E_VSI_MAIN) {
2386 			set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2387 			dev_warn(&vsi->back->pdev->dev,
2388 				 "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2389 				 i40e_aq_str(hw, aq_status), vsi_name);
2390 		} else if (vsi->type == I40E_VSI_SRIOV ||
2391 			   vsi->type == I40E_VSI_VMDQ1 ||
2392 			   vsi->type == I40E_VSI_VMDQ2) {
2393 			dev_warn(&vsi->back->pdev->dev,
2394 				 "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2395 				 i40e_aq_str(hw, aq_status), vsi_name,
2396 					     vsi_name);
2397 		} else {
2398 			dev_warn(&vsi->back->pdev->dev,
2399 				 "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2400 				 i40e_aq_str(hw, aq_status), vsi_name,
2401 					     vsi->type);
2402 		}
2403 	}
2404 }
2405 
2406 /**
2407  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2408  * @vsi: pointer to the VSI
2409  * @vsi_name: the VSI name
2410  * @f: filter data
2411  *
2412  * This function sets or clears the promiscuous broadcast flags for VLAN
2413  * filters in order to properly receive broadcast frames. Assumes that only
2414  * broadcast filters are passed.
2415  *
2416  * Returns status indicating success or failure;
2417  **/
2418 static int
2419 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2420 			  struct i40e_mac_filter *f)
2421 {
2422 	bool enable = f->state == I40E_FILTER_NEW ||
2423 		      f->state == I40E_FILTER_NEW_SYNC;
2424 	struct i40e_hw *hw = &vsi->back->hw;
2425 	int aq_ret;
2426 
2427 	if (f->vlan == I40E_VLAN_ANY) {
2428 		aq_ret = i40e_aq_set_vsi_broadcast(hw,
2429 						   vsi->seid,
2430 						   enable,
2431 						   NULL);
2432 	} else {
2433 		aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2434 							    vsi->seid,
2435 							    enable,
2436 							    f->vlan,
2437 							    NULL);
2438 	}
2439 
2440 	if (aq_ret) {
2441 		set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2442 		dev_warn(&vsi->back->pdev->dev,
2443 			 "Error %s, forcing overflow promiscuous on %s\n",
2444 			 i40e_aq_str(hw, hw->aq.asq_last_status),
2445 			 vsi_name);
2446 	}
2447 
2448 	return aq_ret;
2449 }
2450 
2451 /**
2452  * i40e_set_promiscuous - set promiscuous mode
2453  * @pf: board private structure
2454  * @promisc: promisc on or off
2455  *
2456  * There are different ways of setting promiscuous mode on a PF depending on
2457  * what state/environment we're in.  This identifies and sets it appropriately.
2458  * Returns 0 on success.
2459  **/
2460 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2461 {
2462 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
2463 	struct i40e_hw *hw = &pf->hw;
2464 	int aq_ret;
2465 
2466 	if (vsi->type == I40E_VSI_MAIN &&
2467 	    i40e_pf_get_main_veb(pf) &&
2468 	    !test_bit(I40E_FLAG_MFP_ENA, pf->flags)) {
2469 		/* set defport ON for Main VSI instead of true promisc
2470 		 * this way we will get all unicast/multicast and VLAN
2471 		 * promisc behavior but will not get VF or VMDq traffic
2472 		 * replicated on the Main VSI.
2473 		 */
2474 		if (promisc)
2475 			aq_ret = i40e_aq_set_default_vsi(hw,
2476 							 vsi->seid,
2477 							 NULL);
2478 		else
2479 			aq_ret = i40e_aq_clear_default_vsi(hw,
2480 							   vsi->seid,
2481 							   NULL);
2482 		if (aq_ret) {
2483 			dev_info(&pf->pdev->dev,
2484 				 "Set default VSI failed, err %pe, aq_err %s\n",
2485 				 ERR_PTR(aq_ret),
2486 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2487 		}
2488 	} else {
2489 		aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2490 						  hw,
2491 						  vsi->seid,
2492 						  promisc, NULL,
2493 						  true);
2494 		if (aq_ret) {
2495 			dev_info(&pf->pdev->dev,
2496 				 "set unicast promisc failed, err %pe, aq_err %s\n",
2497 				 ERR_PTR(aq_ret),
2498 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2499 		}
2500 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2501 						  hw,
2502 						  vsi->seid,
2503 						  promisc, NULL);
2504 		if (aq_ret) {
2505 			dev_info(&pf->pdev->dev,
2506 				 "set multicast promisc failed, err %pe, aq_err %s\n",
2507 				 ERR_PTR(aq_ret),
2508 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2509 		}
2510 	}
2511 
2512 	if (!aq_ret)
2513 		pf->cur_promisc = promisc;
2514 
2515 	return aq_ret;
2516 }
2517 
2518 /**
2519  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2520  * @vsi: ptr to the VSI
2521  *
2522  * Push any outstanding VSI filter changes through the AdminQ.
2523  *
2524  * Returns 0 or error value
2525  **/
2526 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2527 {
2528 	struct hlist_head tmp_add_list, tmp_del_list;
2529 	struct i40e_mac_filter *f;
2530 	struct i40e_new_mac_filter *new, *add_head = NULL;
2531 	struct i40e_hw *hw = &vsi->back->hw;
2532 	bool old_overflow, new_overflow;
2533 	unsigned int failed_filters = 0;
2534 	unsigned int vlan_filters = 0;
2535 	char vsi_name[16] = "PF";
2536 	int filter_list_len = 0;
2537 	u32 changed_flags = 0;
2538 	struct hlist_node *h;
2539 	struct i40e_pf *pf;
2540 	int num_add = 0;
2541 	int num_del = 0;
2542 	int aq_ret = 0;
2543 	int retval = 0;
2544 	u16 cmd_flags;
2545 	int list_size;
2546 	int bkt;
2547 
2548 	/* empty array typed pointers, kcalloc later */
2549 	struct i40e_aqc_add_macvlan_element_data *add_list;
2550 	struct i40e_aqc_remove_macvlan_element_data *del_list;
2551 
2552 	while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2553 		usleep_range(1000, 2000);
2554 	pf = vsi->back;
2555 
2556 	old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2557 
2558 	if (vsi->netdev) {
2559 		changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2560 		vsi->current_netdev_flags = vsi->netdev->flags;
2561 	}
2562 
2563 	INIT_HLIST_HEAD(&tmp_add_list);
2564 	INIT_HLIST_HEAD(&tmp_del_list);
2565 
2566 	if (vsi->type == I40E_VSI_SRIOV)
2567 		snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2568 	else if (vsi->type != I40E_VSI_MAIN)
2569 		snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2570 
2571 	if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2572 		vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2573 
2574 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2575 		/* Create a list of filters to delete. */
2576 		hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2577 			if (f->state == I40E_FILTER_REMOVE) {
2578 				/* Move the element into temporary del_list */
2579 				hash_del(&f->hlist);
2580 				hlist_add_head(&f->hlist, &tmp_del_list);
2581 
2582 				/* Avoid counting removed filters */
2583 				continue;
2584 			}
2585 			if (f->state == I40E_FILTER_NEW) {
2586 				/* Create a temporary i40e_new_mac_filter */
2587 				new = kzalloc(sizeof(*new), GFP_ATOMIC);
2588 				if (!new)
2589 					goto err_no_memory_locked;
2590 
2591 				/* Store pointer to the real filter */
2592 				new->f = f;
2593 				new->state = f->state;
2594 
2595 				/* Add it to the hash list */
2596 				hlist_add_head(&new->hlist, &tmp_add_list);
2597 				f->state = I40E_FILTER_NEW_SYNC;
2598 			}
2599 
2600 			/* Count the number of active (current and new) VLAN
2601 			 * filters we have now. Does not count filters which
2602 			 * are marked for deletion.
2603 			 */
2604 			if (f->vlan > 0)
2605 				vlan_filters++;
2606 		}
2607 
2608 		if (vsi->type != I40E_VSI_SRIOV)
2609 			retval = i40e_correct_mac_vlan_filters
2610 				(vsi, &tmp_add_list, &tmp_del_list,
2611 				 vlan_filters);
2612 		else if (pf->vf)
2613 			retval = i40e_correct_vf_mac_vlan_filters
2614 				(vsi, &tmp_add_list, &tmp_del_list,
2615 				 vlan_filters, pf->vf[vsi->vf_id].trusted);
2616 
2617 		hlist_for_each_entry(new, &tmp_add_list, hlist)
2618 			netdev_hw_addr_refcnt(new->f, vsi->netdev, 1);
2619 
2620 		if (retval)
2621 			goto err_no_memory_locked;
2622 
2623 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2624 	}
2625 
2626 	/* Now process 'del_list' outside the lock */
2627 	if (!hlist_empty(&tmp_del_list)) {
2628 		filter_list_len = hw->aq.asq_buf_size /
2629 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2630 		list_size = filter_list_len *
2631 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2632 		del_list = kzalloc(list_size, GFP_ATOMIC);
2633 		if (!del_list)
2634 			goto err_no_memory;
2635 
2636 		hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2637 			cmd_flags = 0;
2638 
2639 			/* handle broadcast filters by updating the broadcast
2640 			 * promiscuous flag and release filter list.
2641 			 */
2642 			if (is_broadcast_ether_addr(f->macaddr)) {
2643 				i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2644 
2645 				hlist_del(&f->hlist);
2646 				kfree(f);
2647 				continue;
2648 			}
2649 
2650 			/* add to delete list */
2651 			ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2652 			if (f->vlan == I40E_VLAN_ANY) {
2653 				del_list[num_del].vlan_tag = 0;
2654 				cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2655 			} else {
2656 				del_list[num_del].vlan_tag =
2657 					cpu_to_le16((u16)(f->vlan));
2658 			}
2659 
2660 			cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2661 			del_list[num_del].flags = cmd_flags;
2662 			num_del++;
2663 
2664 			/* flush a full buffer */
2665 			if (num_del == filter_list_len) {
2666 				i40e_aqc_del_filters(vsi, vsi_name, del_list,
2667 						     num_del, &retval);
2668 				memset(del_list, 0, list_size);
2669 				num_del = 0;
2670 			}
2671 			/* Release memory for MAC filter entries which were
2672 			 * synced up with HW.
2673 			 */
2674 			hlist_del(&f->hlist);
2675 			kfree(f);
2676 		}
2677 
2678 		if (num_del) {
2679 			i40e_aqc_del_filters(vsi, vsi_name, del_list,
2680 					     num_del, &retval);
2681 		}
2682 
2683 		kfree(del_list);
2684 		del_list = NULL;
2685 	}
2686 
2687 	if (!hlist_empty(&tmp_add_list)) {
2688 		/* Do all the adds now. */
2689 		filter_list_len = hw->aq.asq_buf_size /
2690 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2691 		list_size = filter_list_len *
2692 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2693 		add_list = kzalloc(list_size, GFP_ATOMIC);
2694 		if (!add_list)
2695 			goto err_no_memory;
2696 
2697 		num_add = 0;
2698 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2699 			/* handle broadcast filters by updating the broadcast
2700 			 * promiscuous flag instead of adding a MAC filter.
2701 			 */
2702 			if (is_broadcast_ether_addr(new->f->macaddr)) {
2703 				if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2704 							      new->f))
2705 					new->state = I40E_FILTER_FAILED;
2706 				else
2707 					new->state = I40E_FILTER_ACTIVE;
2708 				continue;
2709 			}
2710 
2711 			/* add to add array */
2712 			if (num_add == 0)
2713 				add_head = new;
2714 			cmd_flags = 0;
2715 			ether_addr_copy(add_list[num_add].mac_addr,
2716 					new->f->macaddr);
2717 			if (new->f->vlan == I40E_VLAN_ANY) {
2718 				add_list[num_add].vlan_tag = 0;
2719 				cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2720 			} else {
2721 				add_list[num_add].vlan_tag =
2722 					cpu_to_le16((u16)(new->f->vlan));
2723 			}
2724 			add_list[num_add].queue_number = 0;
2725 			/* set invalid match method for later detection */
2726 			add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2727 			cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2728 			add_list[num_add].flags = cpu_to_le16(cmd_flags);
2729 			num_add++;
2730 
2731 			/* flush a full buffer */
2732 			if (num_add == filter_list_len) {
2733 				i40e_aqc_add_filters(vsi, vsi_name, add_list,
2734 						     add_head, num_add);
2735 				memset(add_list, 0, list_size);
2736 				num_add = 0;
2737 			}
2738 		}
2739 		if (num_add) {
2740 			i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2741 					     num_add);
2742 		}
2743 		/* Now move all of the filters from the temp add list back to
2744 		 * the VSI's list.
2745 		 */
2746 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2747 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2748 			/* Only update the state if we're still NEW */
2749 			if (new->f->state == I40E_FILTER_NEW ||
2750 			    new->f->state == I40E_FILTER_NEW_SYNC)
2751 				new->f->state = new->state;
2752 			hlist_del(&new->hlist);
2753 			netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2754 			kfree(new);
2755 		}
2756 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2757 		kfree(add_list);
2758 		add_list = NULL;
2759 	}
2760 
2761 	/* Determine the number of active and failed filters. */
2762 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2763 	vsi->active_filters = 0;
2764 	hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2765 		if (f->state == I40E_FILTER_ACTIVE)
2766 			vsi->active_filters++;
2767 		else if (f->state == I40E_FILTER_FAILED)
2768 			failed_filters++;
2769 	}
2770 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2771 
2772 	/* Check if we are able to exit overflow promiscuous mode. We can
2773 	 * safely exit if we didn't just enter, we no longer have any failed
2774 	 * filters, and we have reduced filters below the threshold value.
2775 	 */
2776 	if (old_overflow && !failed_filters &&
2777 	    vsi->active_filters < vsi->promisc_threshold) {
2778 		dev_info(&pf->pdev->dev,
2779 			 "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2780 			 vsi_name);
2781 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2782 		vsi->promisc_threshold = 0;
2783 	}
2784 
2785 	/* if the VF is not trusted do not do promisc */
2786 	if (vsi->type == I40E_VSI_SRIOV && pf->vf &&
2787 	    !pf->vf[vsi->vf_id].trusted) {
2788 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2789 		goto out;
2790 	}
2791 
2792 	new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2793 
2794 	/* If we are entering overflow promiscuous, we need to calculate a new
2795 	 * threshold for when we are safe to exit
2796 	 */
2797 	if (!old_overflow && new_overflow)
2798 		vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2799 
2800 	/* check for changes in promiscuous modes */
2801 	if (changed_flags & IFF_ALLMULTI) {
2802 		bool cur_multipromisc;
2803 
2804 		cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2805 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2806 							       vsi->seid,
2807 							       cur_multipromisc,
2808 							       NULL);
2809 		if (aq_ret) {
2810 			retval = i40e_aq_rc_to_posix(aq_ret,
2811 						     hw->aq.asq_last_status);
2812 			dev_info(&pf->pdev->dev,
2813 				 "set multi promisc failed on %s, err %pe aq_err %s\n",
2814 				 vsi_name,
2815 				 ERR_PTR(aq_ret),
2816 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2817 		} else {
2818 			dev_info(&pf->pdev->dev, "%s allmulti mode.\n",
2819 				 cur_multipromisc ? "entering" : "leaving");
2820 		}
2821 	}
2822 
2823 	if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2824 		bool cur_promisc;
2825 
2826 		cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2827 			       new_overflow);
2828 		aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2829 		if (aq_ret) {
2830 			retval = i40e_aq_rc_to_posix(aq_ret,
2831 						     hw->aq.asq_last_status);
2832 			dev_info(&pf->pdev->dev,
2833 				 "Setting promiscuous %s failed on %s, err %pe aq_err %s\n",
2834 				 cur_promisc ? "on" : "off",
2835 				 vsi_name,
2836 				 ERR_PTR(aq_ret),
2837 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2838 		}
2839 	}
2840 out:
2841 	/* if something went wrong then set the changed flag so we try again */
2842 	if (retval)
2843 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2844 
2845 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2846 	return retval;
2847 
2848 err_no_memory:
2849 	/* Restore elements on the temporary add and delete lists */
2850 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2851 err_no_memory_locked:
2852 	i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2853 	i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2854 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2855 
2856 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2857 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2858 	return -ENOMEM;
2859 }
2860 
2861 /**
2862  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2863  * @pf: board private structure
2864  **/
2865 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2866 {
2867 	struct i40e_vsi *vsi;
2868 	int v;
2869 
2870 	if (!pf)
2871 		return;
2872 	if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2873 		return;
2874 	if (test_bit(__I40E_VF_DISABLE, pf->state)) {
2875 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
2876 		return;
2877 	}
2878 
2879 	i40e_pf_for_each_vsi(pf, v, vsi) {
2880 		if ((vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) &&
2881 		    !test_bit(__I40E_VSI_RELEASING, vsi->state)) {
2882 			int ret = i40e_sync_vsi_filters(vsi);
2883 
2884 			if (ret) {
2885 				/* come back and try again later */
2886 				set_bit(__I40E_MACVLAN_SYNC_PENDING,
2887 					pf->state);
2888 				break;
2889 			}
2890 		}
2891 	}
2892 }
2893 
2894 /**
2895  * i40e_calculate_vsi_rx_buf_len - Calculates buffer length
2896  *
2897  * @vsi: VSI to calculate rx_buf_len from
2898  */
2899 static u16 i40e_calculate_vsi_rx_buf_len(struct i40e_vsi *vsi)
2900 {
2901 	if (!vsi->netdev || test_bit(I40E_FLAG_LEGACY_RX_ENA, vsi->back->flags))
2902 		return SKB_WITH_OVERHEAD(I40E_RXBUFFER_2048);
2903 
2904 	return PAGE_SIZE < 8192 ? I40E_RXBUFFER_3072 : I40E_RXBUFFER_2048;
2905 }
2906 
2907 /**
2908  * i40e_max_vsi_frame_size - returns the maximum allowed frame size for VSI
2909  * @vsi: the vsi
2910  * @xdp_prog: XDP program
2911  **/
2912 static int i40e_max_vsi_frame_size(struct i40e_vsi *vsi,
2913 				   struct bpf_prog *xdp_prog)
2914 {
2915 	u16 rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
2916 	u16 chain_len;
2917 
2918 	if (xdp_prog && !xdp_prog->aux->xdp_has_frags)
2919 		chain_len = 1;
2920 	else
2921 		chain_len = I40E_MAX_CHAINED_RX_BUFFERS;
2922 
2923 	return min_t(u16, rx_buf_len * chain_len, I40E_MAX_RXBUFFER);
2924 }
2925 
2926 /**
2927  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2928  * @netdev: network interface device structure
2929  * @new_mtu: new value for maximum frame size
2930  *
2931  * Returns 0 on success, negative on failure
2932  **/
2933 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2934 {
2935 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2936 	struct i40e_vsi *vsi = np->vsi;
2937 	struct i40e_pf *pf = vsi->back;
2938 	int frame_size;
2939 
2940 	frame_size = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
2941 	if (new_mtu > frame_size - I40E_PACKET_HDR_PAD) {
2942 		netdev_err(netdev, "Error changing mtu to %d, Max is %d\n",
2943 			   new_mtu, frame_size - I40E_PACKET_HDR_PAD);
2944 		return -EINVAL;
2945 	}
2946 
2947 	netdev_dbg(netdev, "changing MTU from %d to %d\n",
2948 		   netdev->mtu, new_mtu);
2949 	WRITE_ONCE(netdev->mtu, new_mtu);
2950 	if (netif_running(netdev))
2951 		i40e_vsi_reinit_locked(vsi);
2952 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2953 	set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2954 	return 0;
2955 }
2956 
2957 /**
2958  * i40e_ioctl - Access the hwtstamp interface
2959  * @netdev: network interface device structure
2960  * @ifr: interface request data
2961  * @cmd: ioctl command
2962  **/
2963 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2964 {
2965 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2966 	struct i40e_pf *pf = np->vsi->back;
2967 
2968 	switch (cmd) {
2969 	case SIOCGHWTSTAMP:
2970 		return i40e_ptp_get_ts_config(pf, ifr);
2971 	case SIOCSHWTSTAMP:
2972 		return i40e_ptp_set_ts_config(pf, ifr);
2973 	default:
2974 		return -EOPNOTSUPP;
2975 	}
2976 }
2977 
2978 /**
2979  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2980  * @vsi: the vsi being adjusted
2981  **/
2982 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2983 {
2984 	struct i40e_vsi_context ctxt;
2985 	int ret;
2986 
2987 	/* Don't modify stripping options if a port VLAN is active */
2988 	if (vsi->info.pvid)
2989 		return;
2990 
2991 	if ((vsi->info.valid_sections &
2992 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2993 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2994 		return;  /* already enabled */
2995 
2996 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2997 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2998 				    I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
2999 
3000 	ctxt.seid = vsi->seid;
3001 	ctxt.info = vsi->info;
3002 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3003 	if (ret) {
3004 		dev_info(&vsi->back->pdev->dev,
3005 			 "update vlan stripping failed, err %pe aq_err %s\n",
3006 			 ERR_PTR(ret),
3007 			 i40e_aq_str(&vsi->back->hw,
3008 				     vsi->back->hw.aq.asq_last_status));
3009 	}
3010 }
3011 
3012 /**
3013  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
3014  * @vsi: the vsi being adjusted
3015  **/
3016 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
3017 {
3018 	struct i40e_vsi_context ctxt;
3019 	int ret;
3020 
3021 	/* Don't modify stripping options if a port VLAN is active */
3022 	if (vsi->info.pvid)
3023 		return;
3024 
3025 	if ((vsi->info.valid_sections &
3026 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
3027 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
3028 	     I40E_AQ_VSI_PVLAN_EMOD_MASK))
3029 		return;  /* already disabled */
3030 
3031 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3032 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3033 				    I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
3034 
3035 	ctxt.seid = vsi->seid;
3036 	ctxt.info = vsi->info;
3037 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3038 	if (ret) {
3039 		dev_info(&vsi->back->pdev->dev,
3040 			 "update vlan stripping failed, err %pe aq_err %s\n",
3041 			 ERR_PTR(ret),
3042 			 i40e_aq_str(&vsi->back->hw,
3043 				     vsi->back->hw.aq.asq_last_status));
3044 	}
3045 }
3046 
3047 /**
3048  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
3049  * @vsi: the vsi being configured
3050  * @vid: vlan id to be added (0 = untagged only , -1 = any)
3051  *
3052  * This is a helper function for adding a new MAC/VLAN filter with the
3053  * specified VLAN for each existing MAC address already in the hash table.
3054  * This function does *not* perform any accounting to update filters based on
3055  * VLAN mode.
3056  *
3057  * NOTE: this function expects to be called while under the
3058  * mac_filter_hash_lock
3059  **/
3060 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3061 {
3062 	struct i40e_mac_filter *f, *add_f;
3063 	struct hlist_node *h;
3064 	int bkt;
3065 
3066 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3067 		/* If we're asked to add a filter that has been marked for
3068 		 * removal, it is safe to simply restore it to active state.
3069 		 * __i40e_del_filter will have simply deleted any filters which
3070 		 * were previously marked NEW or FAILED, so if it is currently
3071 		 * marked REMOVE it must have previously been ACTIVE. Since we
3072 		 * haven't yet run the sync filters task, just restore this
3073 		 * filter to the ACTIVE state so that the sync task leaves it
3074 		 * in place.
3075 		 */
3076 		if (f->state == I40E_FILTER_REMOVE && f->vlan == vid) {
3077 			f->state = I40E_FILTER_ACTIVE;
3078 			continue;
3079 		} else if (f->state == I40E_FILTER_REMOVE) {
3080 			continue;
3081 		}
3082 		add_f = i40e_add_filter(vsi, f->macaddr, vid);
3083 		if (!add_f) {
3084 			dev_info(&vsi->back->pdev->dev,
3085 				 "Could not add vlan filter %d for %pM\n",
3086 				 vid, f->macaddr);
3087 			return -ENOMEM;
3088 		}
3089 	}
3090 
3091 	return 0;
3092 }
3093 
3094 /**
3095  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
3096  * @vsi: the VSI being configured
3097  * @vid: VLAN id to be added
3098  **/
3099 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
3100 {
3101 	int err;
3102 
3103 	if (vsi->info.pvid)
3104 		return -EINVAL;
3105 
3106 	/* The network stack will attempt to add VID=0, with the intention to
3107 	 * receive priority tagged packets with a VLAN of 0. Our HW receives
3108 	 * these packets by default when configured to receive untagged
3109 	 * packets, so we don't need to add a filter for this case.
3110 	 * Additionally, HW interprets adding a VID=0 filter as meaning to
3111 	 * receive *only* tagged traffic and stops receiving untagged traffic.
3112 	 * Thus, we do not want to actually add a filter for VID=0
3113 	 */
3114 	if (!vid)
3115 		return 0;
3116 
3117 	/* Locked once because all functions invoked below iterates list*/
3118 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3119 	err = i40e_add_vlan_all_mac(vsi, vid);
3120 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3121 	if (err)
3122 		return err;
3123 
3124 	/* schedule our worker thread which will take care of
3125 	 * applying the new filter changes
3126 	 */
3127 	i40e_service_event_schedule(vsi->back);
3128 	return 0;
3129 }
3130 
3131 /**
3132  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
3133  * @vsi: the vsi being configured
3134  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
3135  *
3136  * This function should be used to remove all VLAN filters which match the
3137  * given VID. It does not schedule the service event and does not take the
3138  * mac_filter_hash_lock so it may be combined with other operations under
3139  * a single invocation of the mac_filter_hash_lock.
3140  *
3141  * NOTE: this function expects to be called while under the
3142  * mac_filter_hash_lock
3143  */
3144 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3145 {
3146 	struct i40e_mac_filter *f;
3147 	struct hlist_node *h;
3148 	int bkt;
3149 
3150 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3151 		if (f->vlan == vid)
3152 			__i40e_del_filter(vsi, f);
3153 	}
3154 }
3155 
3156 /**
3157  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
3158  * @vsi: the VSI being configured
3159  * @vid: VLAN id to be removed
3160  **/
3161 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
3162 {
3163 	if (!vid || vsi->info.pvid)
3164 		return;
3165 
3166 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3167 	i40e_rm_vlan_all_mac(vsi, vid);
3168 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3169 
3170 	/* schedule our worker thread which will take care of
3171 	 * applying the new filter changes
3172 	 */
3173 	i40e_service_event_schedule(vsi->back);
3174 }
3175 
3176 /**
3177  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
3178  * @netdev: network interface to be adjusted
3179  * @proto: unused protocol value
3180  * @vid: vlan id to be added
3181  *
3182  * net_device_ops implementation for adding vlan ids
3183  **/
3184 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
3185 				__always_unused __be16 proto, u16 vid)
3186 {
3187 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3188 	struct i40e_vsi *vsi = np->vsi;
3189 	int ret = 0;
3190 
3191 	if (vid >= VLAN_N_VID)
3192 		return -EINVAL;
3193 
3194 	ret = i40e_vsi_add_vlan(vsi, vid);
3195 	if (!ret)
3196 		set_bit(vid, vsi->active_vlans);
3197 
3198 	return ret;
3199 }
3200 
3201 /**
3202  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
3203  * @netdev: network interface to be adjusted
3204  * @proto: unused protocol value
3205  * @vid: vlan id to be added
3206  **/
3207 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
3208 				    __always_unused __be16 proto, u16 vid)
3209 {
3210 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3211 	struct i40e_vsi *vsi = np->vsi;
3212 
3213 	if (vid >= VLAN_N_VID)
3214 		return;
3215 	set_bit(vid, vsi->active_vlans);
3216 }
3217 
3218 /**
3219  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
3220  * @netdev: network interface to be adjusted
3221  * @proto: unused protocol value
3222  * @vid: vlan id to be removed
3223  *
3224  * net_device_ops implementation for removing vlan ids
3225  **/
3226 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
3227 				 __always_unused __be16 proto, u16 vid)
3228 {
3229 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3230 	struct i40e_vsi *vsi = np->vsi;
3231 
3232 	/* return code is ignored as there is nothing a user
3233 	 * can do about failure to remove and a log message was
3234 	 * already printed from the other function
3235 	 */
3236 	i40e_vsi_kill_vlan(vsi, vid);
3237 
3238 	clear_bit(vid, vsi->active_vlans);
3239 
3240 	return 0;
3241 }
3242 
3243 /**
3244  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
3245  * @vsi: the vsi being brought back up
3246  **/
3247 static void i40e_restore_vlan(struct i40e_vsi *vsi)
3248 {
3249 	u16 vid;
3250 
3251 	if (!vsi->netdev)
3252 		return;
3253 
3254 	if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
3255 		i40e_vlan_stripping_enable(vsi);
3256 	else
3257 		i40e_vlan_stripping_disable(vsi);
3258 
3259 	for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
3260 		i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
3261 					vid);
3262 }
3263 
3264 /**
3265  * i40e_vsi_add_pvid - Add pvid for the VSI
3266  * @vsi: the vsi being adjusted
3267  * @vid: the vlan id to set as a PVID
3268  **/
3269 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
3270 {
3271 	struct i40e_vsi_context ctxt;
3272 	int ret;
3273 
3274 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3275 	vsi->info.pvid = cpu_to_le16(vid);
3276 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
3277 				    I40E_AQ_VSI_PVLAN_INSERT_PVID |
3278 				    I40E_AQ_VSI_PVLAN_EMOD_STR;
3279 
3280 	ctxt.seid = vsi->seid;
3281 	ctxt.info = vsi->info;
3282 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3283 	if (ret) {
3284 		dev_info(&vsi->back->pdev->dev,
3285 			 "add pvid failed, err %pe aq_err %s\n",
3286 			 ERR_PTR(ret),
3287 			 i40e_aq_str(&vsi->back->hw,
3288 				     vsi->back->hw.aq.asq_last_status));
3289 		return -ENOENT;
3290 	}
3291 
3292 	return 0;
3293 }
3294 
3295 /**
3296  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
3297  * @vsi: the vsi being adjusted
3298  *
3299  * Just use the vlan_rx_register() service to put it back to normal
3300  **/
3301 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
3302 {
3303 	vsi->info.pvid = 0;
3304 
3305 	i40e_vlan_stripping_disable(vsi);
3306 }
3307 
3308 /**
3309  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
3310  * @vsi: ptr to the VSI
3311  *
3312  * If this function returns with an error, then it's possible one or
3313  * more of the rings is populated (while the rest are not).  It is the
3314  * callers duty to clean those orphaned rings.
3315  *
3316  * Return 0 on success, negative on failure
3317  **/
3318 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3319 {
3320 	int i, err = 0;
3321 
3322 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3323 		err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3324 
3325 	if (!i40e_enabled_xdp_vsi(vsi))
3326 		return err;
3327 
3328 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3329 		err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3330 
3331 	return err;
3332 }
3333 
3334 /**
3335  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3336  * @vsi: ptr to the VSI
3337  *
3338  * Free VSI's transmit software resources
3339  **/
3340 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3341 {
3342 	int i;
3343 
3344 	if (vsi->tx_rings) {
3345 		for (i = 0; i < vsi->num_queue_pairs; i++)
3346 			if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3347 				i40e_free_tx_resources(vsi->tx_rings[i]);
3348 	}
3349 
3350 	if (vsi->xdp_rings) {
3351 		for (i = 0; i < vsi->num_queue_pairs; i++)
3352 			if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3353 				i40e_free_tx_resources(vsi->xdp_rings[i]);
3354 	}
3355 }
3356 
3357 /**
3358  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3359  * @vsi: ptr to the VSI
3360  *
3361  * If this function returns with an error, then it's possible one or
3362  * more of the rings is populated (while the rest are not).  It is the
3363  * callers duty to clean those orphaned rings.
3364  *
3365  * Return 0 on success, negative on failure
3366  **/
3367 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3368 {
3369 	int i, err = 0;
3370 
3371 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3372 		err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3373 	return err;
3374 }
3375 
3376 /**
3377  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3378  * @vsi: ptr to the VSI
3379  *
3380  * Free all receive software resources
3381  **/
3382 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3383 {
3384 	int i;
3385 
3386 	if (!vsi->rx_rings)
3387 		return;
3388 
3389 	for (i = 0; i < vsi->num_queue_pairs; i++)
3390 		if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3391 			i40e_free_rx_resources(vsi->rx_rings[i]);
3392 }
3393 
3394 /**
3395  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3396  * @ring: The Tx ring to configure
3397  *
3398  * This enables/disables XPS for a given Tx descriptor ring
3399  * based on the TCs enabled for the VSI that ring belongs to.
3400  **/
3401 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3402 {
3403 	int cpu;
3404 
3405 	if (!ring->q_vector || !ring->netdev || ring->ch)
3406 		return;
3407 
3408 	/* We only initialize XPS once, so as not to overwrite user settings */
3409 	if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3410 		return;
3411 
3412 	cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3413 	netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3414 			    ring->queue_index);
3415 }
3416 
3417 /**
3418  * i40e_xsk_pool - Retrieve the AF_XDP buffer pool if XDP and ZC is enabled
3419  * @ring: The Tx or Rx ring
3420  *
3421  * Returns the AF_XDP buffer pool or NULL.
3422  **/
3423 static struct xsk_buff_pool *i40e_xsk_pool(struct i40e_ring *ring)
3424 {
3425 	bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3426 	int qid = ring->queue_index;
3427 
3428 	if (ring_is_xdp(ring))
3429 		qid -= ring->vsi->alloc_queue_pairs;
3430 
3431 	if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3432 		return NULL;
3433 
3434 	return xsk_get_pool_from_qid(ring->vsi->netdev, qid);
3435 }
3436 
3437 /**
3438  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3439  * @ring: The Tx ring to configure
3440  *
3441  * Configure the Tx descriptor ring in the HMC context.
3442  **/
3443 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3444 {
3445 	struct i40e_vsi *vsi = ring->vsi;
3446 	u16 pf_q = vsi->base_queue + ring->queue_index;
3447 	struct i40e_hw *hw = &vsi->back->hw;
3448 	struct i40e_hmc_obj_txq tx_ctx;
3449 	u32 qtx_ctl = 0;
3450 	int err = 0;
3451 
3452 	if (ring_is_xdp(ring))
3453 		ring->xsk_pool = i40e_xsk_pool(ring);
3454 
3455 	/* some ATR related tx ring init */
3456 	if (test_bit(I40E_FLAG_FD_ATR_ENA, vsi->back->flags)) {
3457 		ring->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
3458 		ring->atr_count = 0;
3459 	} else {
3460 		ring->atr_sample_rate = 0;
3461 	}
3462 
3463 	/* configure XPS */
3464 	i40e_config_xps_tx_ring(ring);
3465 
3466 	/* clear the context structure first */
3467 	memset(&tx_ctx, 0, sizeof(tx_ctx));
3468 
3469 	tx_ctx.new_context = 1;
3470 	tx_ctx.base = (ring->dma / 128);
3471 	tx_ctx.qlen = ring->count;
3472 	if (test_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags) ||
3473 	    test_bit(I40E_FLAG_FD_ATR_ENA, vsi->back->flags))
3474 		tx_ctx.fd_ena = 1;
3475 	if (test_bit(I40E_FLAG_PTP_ENA, vsi->back->flags))
3476 		tx_ctx.timesync_ena = 1;
3477 	/* FDIR VSI tx ring can still use RS bit and writebacks */
3478 	if (vsi->type != I40E_VSI_FDIR)
3479 		tx_ctx.head_wb_ena = 1;
3480 	tx_ctx.head_wb_addr = ring->dma +
3481 			      (ring->count * sizeof(struct i40e_tx_desc));
3482 
3483 	/* As part of VSI creation/update, FW allocates certain
3484 	 * Tx arbitration queue sets for each TC enabled for
3485 	 * the VSI. The FW returns the handles to these queue
3486 	 * sets as part of the response buffer to Add VSI,
3487 	 * Update VSI, etc. AQ commands. It is expected that
3488 	 * these queue set handles be associated with the Tx
3489 	 * queues by the driver as part of the TX queue context
3490 	 * initialization. This has to be done regardless of
3491 	 * DCB as by default everything is mapped to TC0.
3492 	 */
3493 
3494 	if (ring->ch)
3495 		tx_ctx.rdylist =
3496 			le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3497 
3498 	else
3499 		tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3500 
3501 	tx_ctx.rdylist_act = 0;
3502 
3503 	/* clear the context in the HMC */
3504 	err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3505 	if (err) {
3506 		dev_info(&vsi->back->pdev->dev,
3507 			 "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3508 			 ring->queue_index, pf_q, err);
3509 		return -ENOMEM;
3510 	}
3511 
3512 	/* set the context in the HMC */
3513 	err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3514 	if (err) {
3515 		dev_info(&vsi->back->pdev->dev,
3516 			 "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3517 			 ring->queue_index, pf_q, err);
3518 		return -ENOMEM;
3519 	}
3520 
3521 	/* Now associate this queue with this PCI function */
3522 	if (ring->ch) {
3523 		if (ring->ch->type == I40E_VSI_VMDQ2)
3524 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3525 		else
3526 			return -EINVAL;
3527 
3528 		qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_VFVM_INDX_MASK,
3529 				      ring->ch->vsi_number);
3530 	} else {
3531 		if (vsi->type == I40E_VSI_VMDQ2) {
3532 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3533 			qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_VFVM_INDX_MASK,
3534 					      vsi->id);
3535 		} else {
3536 			qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3537 		}
3538 	}
3539 
3540 	qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_PF_INDX_MASK, hw->pf_id);
3541 	wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3542 	i40e_flush(hw);
3543 
3544 	/* cache tail off for easier writes later */
3545 	ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3546 
3547 	return 0;
3548 }
3549 
3550 /**
3551  * i40e_rx_offset - Return expected offset into page to access data
3552  * @rx_ring: Ring we are requesting offset of
3553  *
3554  * Returns the offset value for ring into the data buffer.
3555  */
3556 static unsigned int i40e_rx_offset(struct i40e_ring *rx_ring)
3557 {
3558 	return ring_uses_build_skb(rx_ring) ? I40E_SKB_PAD : 0;
3559 }
3560 
3561 /**
3562  * i40e_configure_rx_ring - Configure a receive ring context
3563  * @ring: The Rx ring to configure
3564  *
3565  * Configure the Rx descriptor ring in the HMC context.
3566  **/
3567 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3568 {
3569 	struct i40e_vsi *vsi = ring->vsi;
3570 	u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3571 	u16 pf_q = vsi->base_queue + ring->queue_index;
3572 	struct i40e_hw *hw = &vsi->back->hw;
3573 	struct i40e_hmc_obj_rxq rx_ctx;
3574 	int err = 0;
3575 	bool ok;
3576 
3577 	bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3578 
3579 	/* clear the context structure first */
3580 	memset(&rx_ctx, 0, sizeof(rx_ctx));
3581 
3582 	ring->rx_buf_len = vsi->rx_buf_len;
3583 
3584 	/* XDP RX-queue info only needed for RX rings exposed to XDP */
3585 	if (ring->vsi->type != I40E_VSI_MAIN)
3586 		goto skip;
3587 
3588 	if (!xdp_rxq_info_is_reg(&ring->xdp_rxq)) {
3589 		err = __xdp_rxq_info_reg(&ring->xdp_rxq, ring->netdev,
3590 					 ring->queue_index,
3591 					 ring->q_vector->napi.napi_id,
3592 					 ring->rx_buf_len);
3593 		if (err)
3594 			return err;
3595 	}
3596 
3597 	ring->xsk_pool = i40e_xsk_pool(ring);
3598 	if (ring->xsk_pool) {
3599 		xdp_rxq_info_unreg(&ring->xdp_rxq);
3600 		ring->rx_buf_len = xsk_pool_get_rx_frame_size(ring->xsk_pool);
3601 		err = __xdp_rxq_info_reg(&ring->xdp_rxq, ring->netdev,
3602 					 ring->queue_index,
3603 					 ring->q_vector->napi.napi_id,
3604 					 ring->rx_buf_len);
3605 		if (err)
3606 			return err;
3607 		err = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3608 						 MEM_TYPE_XSK_BUFF_POOL,
3609 						 NULL);
3610 		if (err)
3611 			return err;
3612 		dev_info(&vsi->back->pdev->dev,
3613 			 "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n",
3614 			 ring->queue_index);
3615 
3616 	} else {
3617 		err = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3618 						 MEM_TYPE_PAGE_SHARED,
3619 						 NULL);
3620 		if (err)
3621 			return err;
3622 	}
3623 
3624 skip:
3625 	xdp_init_buff(&ring->xdp, i40e_rx_pg_size(ring) / 2, &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 		return -ENOMEM;
3660 	}
3661 
3662 	/* set the context in the HMC */
3663 	err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3664 	if (err) {
3665 		dev_info(&vsi->back->pdev->dev,
3666 			 "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3667 			 ring->queue_index, pf_q, err);
3668 		return -ENOMEM;
3669 	}
3670 
3671 	/* configure Rx buffer alignment */
3672 	if (!vsi->netdev || test_bit(I40E_FLAG_LEGACY_RX_ENA, vsi->back->flags)) {
3673 		if (I40E_2K_TOO_SMALL_WITH_PADDING) {
3674 			dev_info(&vsi->back->pdev->dev,
3675 				 "2k Rx buffer is too small to fit standard MTU and skb_shared_info\n");
3676 			return -EOPNOTSUPP;
3677 		}
3678 		clear_ring_build_skb_enabled(ring);
3679 	} else {
3680 		set_ring_build_skb_enabled(ring);
3681 	}
3682 
3683 	ring->rx_offset = i40e_rx_offset(ring);
3684 
3685 	/* cache tail for quicker writes, and clear the reg before use */
3686 	ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3687 	writel(0, ring->tail);
3688 
3689 	if (ring->xsk_pool) {
3690 		xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
3691 		ok = i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring));
3692 	} else {
3693 		ok = !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3694 	}
3695 	if (!ok) {
3696 		/* Log this in case the user has forgotten to give the kernel
3697 		 * any buffers, even later in the application.
3698 		 */
3699 		dev_info(&vsi->back->pdev->dev,
3700 			 "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3701 			 ring->xsk_pool ? "AF_XDP ZC enabled " : "",
3702 			 ring->queue_index, pf_q);
3703 	}
3704 
3705 	return 0;
3706 }
3707 
3708 /**
3709  * i40e_vsi_configure_tx - Configure the VSI for Tx
3710  * @vsi: VSI structure describing this set of rings and resources
3711  *
3712  * Configure the Tx VSI for operation.
3713  **/
3714 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3715 {
3716 	int err = 0;
3717 	u16 i;
3718 
3719 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3720 		err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3721 
3722 	if (err || !i40e_enabled_xdp_vsi(vsi))
3723 		return err;
3724 
3725 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3726 		err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3727 
3728 	return err;
3729 }
3730 
3731 /**
3732  * i40e_vsi_configure_rx - Configure the VSI for Rx
3733  * @vsi: the VSI being configured
3734  *
3735  * Configure the Rx VSI for operation.
3736  **/
3737 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3738 {
3739 	int err = 0;
3740 	u16 i;
3741 
3742 	vsi->max_frame = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
3743 	vsi->rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
3744 
3745 #if (PAGE_SIZE < 8192)
3746 	if (vsi->netdev && !I40E_2K_TOO_SMALL_WITH_PADDING &&
3747 	    vsi->netdev->mtu <= ETH_DATA_LEN) {
3748 		vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3749 		vsi->max_frame = vsi->rx_buf_len;
3750 	}
3751 #endif
3752 
3753 	/* set up individual rings */
3754 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3755 		err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3756 
3757 	return err;
3758 }
3759 
3760 /**
3761  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3762  * @vsi: ptr to the VSI
3763  **/
3764 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3765 {
3766 	struct i40e_ring *tx_ring, *rx_ring;
3767 	u16 qoffset, qcount;
3768 	int i, n;
3769 
3770 	if (!test_bit(I40E_FLAG_DCB_ENA, vsi->back->flags)) {
3771 		/* Reset the TC information */
3772 		for (i = 0; i < vsi->num_queue_pairs; i++) {
3773 			rx_ring = vsi->rx_rings[i];
3774 			tx_ring = vsi->tx_rings[i];
3775 			rx_ring->dcb_tc = 0;
3776 			tx_ring->dcb_tc = 0;
3777 		}
3778 		return;
3779 	}
3780 
3781 	for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3782 		if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3783 			continue;
3784 
3785 		qoffset = vsi->tc_config.tc_info[n].qoffset;
3786 		qcount = vsi->tc_config.tc_info[n].qcount;
3787 		for (i = qoffset; i < (qoffset + qcount); i++) {
3788 			rx_ring = vsi->rx_rings[i];
3789 			tx_ring = vsi->tx_rings[i];
3790 			rx_ring->dcb_tc = n;
3791 			tx_ring->dcb_tc = n;
3792 		}
3793 	}
3794 }
3795 
3796 /**
3797  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3798  * @vsi: ptr to the VSI
3799  **/
3800 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3801 {
3802 	if (vsi->netdev)
3803 		i40e_set_rx_mode(vsi->netdev);
3804 }
3805 
3806 /**
3807  * i40e_reset_fdir_filter_cnt - Reset flow director filter counters
3808  * @pf: Pointer to the targeted PF
3809  *
3810  * Set all flow director counters to 0.
3811  */
3812 static void i40e_reset_fdir_filter_cnt(struct i40e_pf *pf)
3813 {
3814 	pf->fd_tcp4_filter_cnt = 0;
3815 	pf->fd_udp4_filter_cnt = 0;
3816 	pf->fd_sctp4_filter_cnt = 0;
3817 	pf->fd_ip4_filter_cnt = 0;
3818 	pf->fd_tcp6_filter_cnt = 0;
3819 	pf->fd_udp6_filter_cnt = 0;
3820 	pf->fd_sctp6_filter_cnt = 0;
3821 	pf->fd_ip6_filter_cnt = 0;
3822 }
3823 
3824 /**
3825  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3826  * @vsi: Pointer to the targeted VSI
3827  *
3828  * This function replays the hlist on the hw where all the SB Flow Director
3829  * filters were saved.
3830  **/
3831 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3832 {
3833 	struct i40e_fdir_filter *filter;
3834 	struct i40e_pf *pf = vsi->back;
3835 	struct hlist_node *node;
3836 
3837 	if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
3838 		return;
3839 
3840 	/* Reset FDir counters as we're replaying all existing filters */
3841 	i40e_reset_fdir_filter_cnt(pf);
3842 
3843 	hlist_for_each_entry_safe(filter, node,
3844 				  &pf->fdir_filter_list, fdir_node) {
3845 		i40e_add_del_fdir(vsi, filter, true);
3846 	}
3847 }
3848 
3849 /**
3850  * i40e_vsi_configure - Set up the VSI for action
3851  * @vsi: the VSI being configured
3852  **/
3853 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3854 {
3855 	int err;
3856 
3857 	i40e_set_vsi_rx_mode(vsi);
3858 	i40e_restore_vlan(vsi);
3859 	i40e_vsi_config_dcb_rings(vsi);
3860 	err = i40e_vsi_configure_tx(vsi);
3861 	if (!err)
3862 		err = i40e_vsi_configure_rx(vsi);
3863 
3864 	return err;
3865 }
3866 
3867 /**
3868  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3869  * @vsi: the VSI being configured
3870  **/
3871 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3872 {
3873 	bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3874 	struct i40e_pf *pf = vsi->back;
3875 	struct i40e_hw *hw = &pf->hw;
3876 	u16 vector;
3877 	int i, q;
3878 	u32 qp;
3879 
3880 	/* The interrupt indexing is offset by 1 in the PFINT_ITRn
3881 	 * and PFINT_LNKLSTn registers, e.g.:
3882 	 *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3883 	 */
3884 	qp = vsi->base_queue;
3885 	vector = vsi->base_vector;
3886 	for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3887 		struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3888 
3889 		q_vector->rx.next_update = jiffies + 1;
3890 		q_vector->rx.target_itr =
3891 			ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3892 		wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3893 		     q_vector->rx.target_itr >> 1);
3894 		q_vector->rx.current_itr = q_vector->rx.target_itr;
3895 
3896 		q_vector->tx.next_update = jiffies + 1;
3897 		q_vector->tx.target_itr =
3898 			ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3899 		wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3900 		     q_vector->tx.target_itr >> 1);
3901 		q_vector->tx.current_itr = q_vector->tx.target_itr;
3902 
3903 		/* Set ITR for software interrupts triggered after exiting
3904 		 * busy-loop polling.
3905 		 */
3906 		wr32(hw, I40E_PFINT_ITRN(I40E_SW_ITR, vector - 1),
3907 		     I40E_ITR_20K);
3908 
3909 		wr32(hw, I40E_PFINT_RATEN(vector - 1),
3910 		     i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3911 
3912 		/* begin of linked list for RX queue assigned to this vector */
3913 		wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3914 		for (q = 0; q < q_vector->num_ringpairs; q++) {
3915 			u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3916 			u32 val;
3917 
3918 			val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3919 			      (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3920 			      (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3921 			      (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3922 			      (I40E_QUEUE_TYPE_TX <<
3923 			       I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3924 
3925 			wr32(hw, I40E_QINT_RQCTL(qp), val);
3926 
3927 			if (has_xdp) {
3928 				/* TX queue with next queue set to TX */
3929 				val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3930 				      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3931 				      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3932 				      (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3933 				      (I40E_QUEUE_TYPE_TX <<
3934 				       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3935 
3936 				wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3937 			}
3938 			/* TX queue with next RX or end of linked list */
3939 			val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3940 			      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3941 			      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3942 			      ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3943 			      (I40E_QUEUE_TYPE_RX <<
3944 			       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3945 
3946 			/* Terminate the linked list */
3947 			if (q == (q_vector->num_ringpairs - 1))
3948 				val |= (I40E_QUEUE_END_OF_LIST <<
3949 					I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3950 
3951 			wr32(hw, I40E_QINT_TQCTL(qp), val);
3952 			qp++;
3953 		}
3954 	}
3955 
3956 	i40e_flush(hw);
3957 }
3958 
3959 /**
3960  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3961  * @pf: pointer to private device data structure
3962  **/
3963 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3964 {
3965 	struct i40e_hw *hw = &pf->hw;
3966 	u32 val;
3967 
3968 	/* clear things first */
3969 	wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3970 	rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3971 
3972 	val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3973 	      I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3974 	      I40E_PFINT_ICR0_ENA_GRST_MASK          |
3975 	      I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3976 	      I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3977 	      I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3978 	      I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3979 	      I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3980 
3981 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags))
3982 		val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3983 
3984 	if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
3985 		val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3986 
3987 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
3988 
3989 	/* SW_ITR_IDX = 0, but don't change INTENA */
3990 	wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3991 					I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
3992 
3993 	/* OTHER_ITR_IDX = 0 */
3994 	wr32(hw, I40E_PFINT_STAT_CTL0, 0);
3995 }
3996 
3997 /**
3998  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
3999  * @vsi: the VSI being configured
4000  **/
4001 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
4002 {
4003 	u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
4004 	struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4005 	struct i40e_pf *pf = vsi->back;
4006 	struct i40e_hw *hw = &pf->hw;
4007 
4008 	/* set the ITR configuration */
4009 	q_vector->rx.next_update = jiffies + 1;
4010 	q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
4011 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr >> 1);
4012 	q_vector->rx.current_itr = q_vector->rx.target_itr;
4013 	q_vector->tx.next_update = jiffies + 1;
4014 	q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
4015 	wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr >> 1);
4016 	q_vector->tx.current_itr = q_vector->tx.target_itr;
4017 
4018 	i40e_enable_misc_int_causes(pf);
4019 
4020 	/* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
4021 	wr32(hw, I40E_PFINT_LNKLST0, 0);
4022 
4023 	/* Associate the queue pair to the vector and enable the queue
4024 	 * interrupt RX queue in linked list with next queue set to TX
4025 	 */
4026 	wr32(hw, I40E_QINT_RQCTL(0), I40E_QINT_RQCTL_VAL(nextqp, 0, TX));
4027 
4028 	if (i40e_enabled_xdp_vsi(vsi)) {
4029 		/* TX queue in linked list with next queue set to TX */
4030 		wr32(hw, I40E_QINT_TQCTL(nextqp),
4031 		     I40E_QINT_TQCTL_VAL(nextqp, 0, TX));
4032 	}
4033 
4034 	/* last TX queue so the next RX queue doesn't matter */
4035 	wr32(hw, I40E_QINT_TQCTL(0),
4036 	     I40E_QINT_TQCTL_VAL(I40E_QUEUE_END_OF_LIST, 0, RX));
4037 	i40e_flush(hw);
4038 }
4039 
4040 /**
4041  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
4042  * @pf: board private structure
4043  **/
4044 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
4045 {
4046 	struct i40e_hw *hw = &pf->hw;
4047 
4048 	wr32(hw, I40E_PFINT_DYN_CTL0,
4049 	     I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
4050 	i40e_flush(hw);
4051 }
4052 
4053 /**
4054  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
4055  * @pf: board private structure
4056  **/
4057 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
4058 {
4059 	struct i40e_hw *hw = &pf->hw;
4060 	u32 val;
4061 
4062 	val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
4063 	      I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
4064 	      (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
4065 
4066 	wr32(hw, I40E_PFINT_DYN_CTL0, val);
4067 	i40e_flush(hw);
4068 }
4069 
4070 /**
4071  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
4072  * @irq: interrupt number
4073  * @data: pointer to a q_vector
4074  **/
4075 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
4076 {
4077 	struct i40e_q_vector *q_vector = data;
4078 
4079 	if (!q_vector->tx.ring && !q_vector->rx.ring)
4080 		return IRQ_HANDLED;
4081 
4082 	napi_schedule_irqoff(&q_vector->napi);
4083 
4084 	return IRQ_HANDLED;
4085 }
4086 
4087 /**
4088  * i40e_irq_affinity_notify - Callback for affinity changes
4089  * @notify: context as to what irq was changed
4090  * @mask: the new affinity mask
4091  *
4092  * This is a callback function used by the irq_set_affinity_notifier function
4093  * so that we may register to receive changes to the irq affinity masks.
4094  **/
4095 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
4096 				     const cpumask_t *mask)
4097 {
4098 	struct i40e_q_vector *q_vector =
4099 		container_of(notify, struct i40e_q_vector, affinity_notify);
4100 
4101 	cpumask_copy(&q_vector->affinity_mask, mask);
4102 }
4103 
4104 /**
4105  * i40e_irq_affinity_release - Callback for affinity notifier release
4106  * @ref: internal core kernel usage
4107  *
4108  * This is a callback function used by the irq_set_affinity_notifier function
4109  * to inform the current notification subscriber that they will no longer
4110  * receive notifications.
4111  **/
4112 static void i40e_irq_affinity_release(struct kref *ref) {}
4113 
4114 /**
4115  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
4116  * @vsi: the VSI being configured
4117  * @basename: name for the vector
4118  *
4119  * Allocates MSI-X vectors and requests interrupts from the kernel.
4120  **/
4121 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
4122 {
4123 	int q_vectors = vsi->num_q_vectors;
4124 	struct i40e_pf *pf = vsi->back;
4125 	int base = vsi->base_vector;
4126 	int rx_int_idx = 0;
4127 	int tx_int_idx = 0;
4128 	int vector, err;
4129 	int irq_num;
4130 	int cpu;
4131 
4132 	for (vector = 0; vector < q_vectors; vector++) {
4133 		struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
4134 
4135 		irq_num = pf->msix_entries[base + vector].vector;
4136 
4137 		if (q_vector->tx.ring && q_vector->rx.ring) {
4138 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4139 				 "%s-%s-%d", basename, "TxRx", rx_int_idx++);
4140 			tx_int_idx++;
4141 		} else if (q_vector->rx.ring) {
4142 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4143 				 "%s-%s-%d", basename, "rx", rx_int_idx++);
4144 		} else if (q_vector->tx.ring) {
4145 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4146 				 "%s-%s-%d", basename, "tx", tx_int_idx++);
4147 		} else {
4148 			/* skip this unused q_vector */
4149 			continue;
4150 		}
4151 		err = request_irq(irq_num,
4152 				  vsi->irq_handler,
4153 				  0,
4154 				  q_vector->name,
4155 				  q_vector);
4156 		if (err) {
4157 			dev_info(&pf->pdev->dev,
4158 				 "MSIX request_irq failed, error: %d\n", err);
4159 			goto free_queue_irqs;
4160 		}
4161 
4162 		/* register for affinity change notifications */
4163 		q_vector->irq_num = irq_num;
4164 		q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
4165 		q_vector->affinity_notify.release = i40e_irq_affinity_release;
4166 		irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
4167 		/* Spread affinity hints out across online CPUs.
4168 		 *
4169 		 * get_cpu_mask returns a static constant mask with
4170 		 * a permanent lifetime so it's ok to pass to
4171 		 * irq_update_affinity_hint without making a copy.
4172 		 */
4173 		cpu = cpumask_local_spread(q_vector->v_idx, -1);
4174 		irq_update_affinity_hint(irq_num, get_cpu_mask(cpu));
4175 	}
4176 
4177 	vsi->irqs_ready = true;
4178 	return 0;
4179 
4180 free_queue_irqs:
4181 	while (vector) {
4182 		vector--;
4183 		irq_num = pf->msix_entries[base + vector].vector;
4184 		irq_set_affinity_notifier(irq_num, NULL);
4185 		irq_update_affinity_hint(irq_num, NULL);
4186 		free_irq(irq_num, &vsi->q_vectors[vector]);
4187 	}
4188 	return err;
4189 }
4190 
4191 /**
4192  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
4193  * @vsi: the VSI being un-configured
4194  **/
4195 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
4196 {
4197 	struct i40e_pf *pf = vsi->back;
4198 	struct i40e_hw *hw = &pf->hw;
4199 	int base = vsi->base_vector;
4200 	int i;
4201 
4202 	/* disable interrupt causation from each queue */
4203 	for (i = 0; i < vsi->num_queue_pairs; i++) {
4204 		u32 val;
4205 
4206 		val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
4207 		val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
4208 		wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
4209 
4210 		val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
4211 		val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
4212 		wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
4213 
4214 		if (!i40e_enabled_xdp_vsi(vsi))
4215 			continue;
4216 		wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
4217 	}
4218 
4219 	/* disable each interrupt */
4220 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4221 		for (i = vsi->base_vector;
4222 		     i < (vsi->num_q_vectors + vsi->base_vector); i++)
4223 			wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
4224 
4225 		i40e_flush(hw);
4226 		for (i = 0; i < vsi->num_q_vectors; i++)
4227 			synchronize_irq(pf->msix_entries[i + base].vector);
4228 	} else {
4229 		/* Legacy and MSI mode - this stops all interrupt handling */
4230 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
4231 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
4232 		i40e_flush(hw);
4233 		synchronize_irq(pf->pdev->irq);
4234 	}
4235 }
4236 
4237 /**
4238  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
4239  * @vsi: the VSI being configured
4240  **/
4241 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
4242 {
4243 	struct i40e_pf *pf = vsi->back;
4244 	int i;
4245 
4246 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4247 		for (i = 0; i < vsi->num_q_vectors; i++)
4248 			i40e_irq_dynamic_enable(vsi, i);
4249 	} else {
4250 		i40e_irq_dynamic_enable_icr0(pf);
4251 	}
4252 
4253 	i40e_flush(&pf->hw);
4254 	return 0;
4255 }
4256 
4257 /**
4258  * i40e_free_misc_vector - Free the vector that handles non-queue events
4259  * @pf: board private structure
4260  **/
4261 static void i40e_free_misc_vector(struct i40e_pf *pf)
4262 {
4263 	/* Disable ICR 0 */
4264 	wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
4265 	i40e_flush(&pf->hw);
4266 
4267 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags) && pf->msix_entries) {
4268 		free_irq(pf->msix_entries[0].vector, pf);
4269 		clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
4270 	}
4271 }
4272 
4273 /**
4274  * i40e_intr - MSI/Legacy and non-queue interrupt handler
4275  * @irq: interrupt number
4276  * @data: pointer to a q_vector
4277  *
4278  * This is the handler used for all MSI/Legacy interrupts, and deals
4279  * with both queue and non-queue interrupts.  This is also used in
4280  * MSIX mode to handle the non-queue interrupts.
4281  **/
4282 static irqreturn_t i40e_intr(int irq, void *data)
4283 {
4284 	struct i40e_pf *pf = (struct i40e_pf *)data;
4285 	struct i40e_hw *hw = &pf->hw;
4286 	irqreturn_t ret = IRQ_NONE;
4287 	u32 icr0, icr0_remaining;
4288 	u32 val, ena_mask;
4289 
4290 	icr0 = rd32(hw, I40E_PFINT_ICR0);
4291 	ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
4292 
4293 	/* if sharing a legacy IRQ, we might get called w/o an intr pending */
4294 	if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
4295 		goto enable_intr;
4296 
4297 	/* if interrupt but no bits showing, must be SWINT */
4298 	if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
4299 	    (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
4300 		pf->sw_int_count++;
4301 
4302 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags) &&
4303 	    (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
4304 		ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4305 		dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
4306 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
4307 	}
4308 
4309 	/* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
4310 	if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
4311 		struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
4312 		struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4313 
4314 		/* We do not have a way to disarm Queue causes while leaving
4315 		 * interrupt enabled for all other causes, ideally
4316 		 * interrupt should be disabled while we are in NAPI but
4317 		 * this is not a performance path and napi_schedule()
4318 		 * can deal with rescheduling.
4319 		 */
4320 		if (!test_bit(__I40E_DOWN, pf->state))
4321 			napi_schedule_irqoff(&q_vector->napi);
4322 	}
4323 
4324 	if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
4325 		ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
4326 		set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
4327 		i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
4328 	}
4329 
4330 	if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
4331 		ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
4332 		set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
4333 	}
4334 
4335 	if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
4336 		/* disable any further VFLR event notifications */
4337 		if (test_bit(__I40E_VF_RESETS_DISABLED, pf->state)) {
4338 			u32 reg = rd32(hw, I40E_PFINT_ICR0_ENA);
4339 
4340 			reg &= ~I40E_PFINT_ICR0_VFLR_MASK;
4341 			wr32(hw, I40E_PFINT_ICR0_ENA, reg);
4342 		} else {
4343 			ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
4344 			set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
4345 		}
4346 	}
4347 
4348 	if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
4349 		if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4350 			set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
4351 		ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
4352 		val = rd32(hw, I40E_GLGEN_RSTAT);
4353 		val = FIELD_GET(I40E_GLGEN_RSTAT_RESET_TYPE_MASK, val);
4354 		if (val == I40E_RESET_CORER) {
4355 			pf->corer_count++;
4356 		} else if (val == I40E_RESET_GLOBR) {
4357 			pf->globr_count++;
4358 		} else if (val == I40E_RESET_EMPR) {
4359 			pf->empr_count++;
4360 			set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
4361 		}
4362 	}
4363 
4364 	if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
4365 		icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
4366 		dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4367 		dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4368 			 rd32(hw, I40E_PFHMC_ERRORINFO),
4369 			 rd32(hw, I40E_PFHMC_ERRORDATA));
4370 	}
4371 
4372 	if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4373 		u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4374 
4375 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_EVENT0_MASK)
4376 			schedule_work(&pf->ptp_extts0_work);
4377 
4378 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK)
4379 			i40e_ptp_tx_hwtstamp(pf);
4380 
4381 		icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4382 	}
4383 
4384 	/* If a critical error is pending we have no choice but to reset the
4385 	 * device.
4386 	 * Report and mask out any remaining unexpected interrupts.
4387 	 */
4388 	icr0_remaining = icr0 & ena_mask;
4389 	if (icr0_remaining) {
4390 		dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4391 			 icr0_remaining);
4392 		if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4393 		    (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4394 		    (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4395 			dev_info(&pf->pdev->dev, "device will be reset\n");
4396 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4397 			i40e_service_event_schedule(pf);
4398 		}
4399 		ena_mask &= ~icr0_remaining;
4400 	}
4401 	ret = IRQ_HANDLED;
4402 
4403 enable_intr:
4404 	/* re-enable interrupt causes */
4405 	wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4406 	if (!test_bit(__I40E_DOWN, pf->state) ||
4407 	    test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4408 		i40e_service_event_schedule(pf);
4409 		i40e_irq_dynamic_enable_icr0(pf);
4410 	}
4411 
4412 	return ret;
4413 }
4414 
4415 /**
4416  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4417  * @tx_ring:  tx ring to clean
4418  * @budget:   how many cleans we're allowed
4419  *
4420  * Returns true if there's any budget left (e.g. the clean is finished)
4421  **/
4422 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4423 {
4424 	struct i40e_vsi *vsi = tx_ring->vsi;
4425 	u16 i = tx_ring->next_to_clean;
4426 	struct i40e_tx_buffer *tx_buf;
4427 	struct i40e_tx_desc *tx_desc;
4428 
4429 	tx_buf = &tx_ring->tx_bi[i];
4430 	tx_desc = I40E_TX_DESC(tx_ring, i);
4431 	i -= tx_ring->count;
4432 
4433 	do {
4434 		struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4435 
4436 		/* if next_to_watch is not set then there is no work pending */
4437 		if (!eop_desc)
4438 			break;
4439 
4440 		/* prevent any other reads prior to eop_desc */
4441 		smp_rmb();
4442 
4443 		/* if the descriptor isn't done, no work yet to do */
4444 		if (!(eop_desc->cmd_type_offset_bsz &
4445 		      cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4446 			break;
4447 
4448 		/* clear next_to_watch to prevent false hangs */
4449 		tx_buf->next_to_watch = NULL;
4450 
4451 		tx_desc->buffer_addr = 0;
4452 		tx_desc->cmd_type_offset_bsz = 0;
4453 		/* move past filter desc */
4454 		tx_buf++;
4455 		tx_desc++;
4456 		i++;
4457 		if (unlikely(!i)) {
4458 			i -= tx_ring->count;
4459 			tx_buf = tx_ring->tx_bi;
4460 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4461 		}
4462 		/* unmap skb header data */
4463 		dma_unmap_single(tx_ring->dev,
4464 				 dma_unmap_addr(tx_buf, dma),
4465 				 dma_unmap_len(tx_buf, len),
4466 				 DMA_TO_DEVICE);
4467 		if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4468 			kfree(tx_buf->raw_buf);
4469 
4470 		tx_buf->raw_buf = NULL;
4471 		tx_buf->tx_flags = 0;
4472 		tx_buf->next_to_watch = NULL;
4473 		dma_unmap_len_set(tx_buf, len, 0);
4474 		tx_desc->buffer_addr = 0;
4475 		tx_desc->cmd_type_offset_bsz = 0;
4476 
4477 		/* move us past the eop_desc for start of next FD desc */
4478 		tx_buf++;
4479 		tx_desc++;
4480 		i++;
4481 		if (unlikely(!i)) {
4482 			i -= tx_ring->count;
4483 			tx_buf = tx_ring->tx_bi;
4484 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4485 		}
4486 
4487 		/* update budget accounting */
4488 		budget--;
4489 	} while (likely(budget));
4490 
4491 	i += tx_ring->count;
4492 	tx_ring->next_to_clean = i;
4493 
4494 	if (test_bit(I40E_FLAG_MSIX_ENA, vsi->back->flags))
4495 		i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4496 
4497 	return budget > 0;
4498 }
4499 
4500 /**
4501  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4502  * @irq: interrupt number
4503  * @data: pointer to a q_vector
4504  **/
4505 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4506 {
4507 	struct i40e_q_vector *q_vector = data;
4508 	struct i40e_vsi *vsi;
4509 
4510 	if (!q_vector->tx.ring)
4511 		return IRQ_HANDLED;
4512 
4513 	vsi = q_vector->tx.ring->vsi;
4514 	i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4515 
4516 	return IRQ_HANDLED;
4517 }
4518 
4519 /**
4520  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4521  * @vsi: the VSI being configured
4522  * @v_idx: vector index
4523  * @qp_idx: queue pair index
4524  **/
4525 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4526 {
4527 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4528 	struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4529 	struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4530 
4531 	tx_ring->q_vector = q_vector;
4532 	tx_ring->next = q_vector->tx.ring;
4533 	q_vector->tx.ring = tx_ring;
4534 	q_vector->tx.count++;
4535 
4536 	/* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4537 	if (i40e_enabled_xdp_vsi(vsi)) {
4538 		struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4539 
4540 		xdp_ring->q_vector = q_vector;
4541 		xdp_ring->next = q_vector->tx.ring;
4542 		q_vector->tx.ring = xdp_ring;
4543 		q_vector->tx.count++;
4544 	}
4545 
4546 	rx_ring->q_vector = q_vector;
4547 	rx_ring->next = q_vector->rx.ring;
4548 	q_vector->rx.ring = rx_ring;
4549 	q_vector->rx.count++;
4550 }
4551 
4552 /**
4553  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4554  * @vsi: the VSI being configured
4555  *
4556  * This function maps descriptor rings to the queue-specific vectors
4557  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4558  * one vector per queue pair, but on a constrained vector budget, we
4559  * group the queue pairs as "efficiently" as possible.
4560  **/
4561 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4562 {
4563 	int qp_remaining = vsi->num_queue_pairs;
4564 	int q_vectors = vsi->num_q_vectors;
4565 	int num_ringpairs;
4566 	int v_start = 0;
4567 	int qp_idx = 0;
4568 
4569 	/* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4570 	 * group them so there are multiple queues per vector.
4571 	 * It is also important to go through all the vectors available to be
4572 	 * sure that if we don't use all the vectors, that the remaining vectors
4573 	 * are cleared. This is especially important when decreasing the
4574 	 * number of queues in use.
4575 	 */
4576 	for (; v_start < q_vectors; v_start++) {
4577 		struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4578 
4579 		num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4580 
4581 		q_vector->num_ringpairs = num_ringpairs;
4582 		q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4583 
4584 		q_vector->rx.count = 0;
4585 		q_vector->tx.count = 0;
4586 		q_vector->rx.ring = NULL;
4587 		q_vector->tx.ring = NULL;
4588 
4589 		while (num_ringpairs--) {
4590 			i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4591 			qp_idx++;
4592 			qp_remaining--;
4593 		}
4594 	}
4595 }
4596 
4597 /**
4598  * i40e_vsi_request_irq - Request IRQ from the OS
4599  * @vsi: the VSI being configured
4600  * @basename: name for the vector
4601  **/
4602 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4603 {
4604 	struct i40e_pf *pf = vsi->back;
4605 	int err;
4606 
4607 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
4608 		err = i40e_vsi_request_irq_msix(vsi, basename);
4609 	else if (test_bit(I40E_FLAG_MSI_ENA, pf->flags))
4610 		err = request_irq(pf->pdev->irq, i40e_intr, 0,
4611 				  pf->int_name, pf);
4612 	else
4613 		err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4614 				  pf->int_name, pf);
4615 
4616 	if (err)
4617 		dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4618 
4619 	return err;
4620 }
4621 
4622 #ifdef CONFIG_NET_POLL_CONTROLLER
4623 /**
4624  * i40e_netpoll - A Polling 'interrupt' handler
4625  * @netdev: network interface device structure
4626  *
4627  * This is used by netconsole to send skbs without having to re-enable
4628  * interrupts.  It's not called while the normal interrupt routine is executing.
4629  **/
4630 static void i40e_netpoll(struct net_device *netdev)
4631 {
4632 	struct i40e_netdev_priv *np = netdev_priv(netdev);
4633 	struct i40e_vsi *vsi = np->vsi;
4634 	struct i40e_pf *pf = vsi->back;
4635 	int i;
4636 
4637 	/* if interface is down do nothing */
4638 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
4639 		return;
4640 
4641 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4642 		for (i = 0; i < vsi->num_q_vectors; i++)
4643 			i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4644 	} else {
4645 		i40e_intr(pf->pdev->irq, netdev);
4646 	}
4647 }
4648 #endif
4649 
4650 #define I40E_QTX_ENA_WAIT_COUNT 50
4651 
4652 /**
4653  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4654  * @pf: the PF being configured
4655  * @pf_q: the PF queue
4656  * @enable: enable or disable state of the queue
4657  *
4658  * This routine will wait for the given Tx queue of the PF to reach the
4659  * enabled or disabled state.
4660  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4661  * multiple retries; else will return 0 in case of success.
4662  **/
4663 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4664 {
4665 	int i;
4666 	u32 tx_reg;
4667 
4668 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4669 		tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4670 		if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4671 			break;
4672 
4673 		usleep_range(10, 20);
4674 	}
4675 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4676 		return -ETIMEDOUT;
4677 
4678 	return 0;
4679 }
4680 
4681 /**
4682  * i40e_control_tx_q - Start or stop a particular Tx queue
4683  * @pf: the PF structure
4684  * @pf_q: the PF queue to configure
4685  * @enable: start or stop the queue
4686  *
4687  * This function enables or disables a single queue. Note that any delay
4688  * required after the operation is expected to be handled by the caller of
4689  * this function.
4690  **/
4691 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4692 {
4693 	struct i40e_hw *hw = &pf->hw;
4694 	u32 tx_reg;
4695 	int i;
4696 
4697 	/* warn the TX unit of coming changes */
4698 	i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4699 	if (!enable)
4700 		usleep_range(10, 20);
4701 
4702 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4703 		tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4704 		if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4705 		    ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4706 			break;
4707 		usleep_range(1000, 2000);
4708 	}
4709 
4710 	/* Skip if the queue is already in the requested state */
4711 	if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4712 		return;
4713 
4714 	/* turn on/off the queue */
4715 	if (enable) {
4716 		wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4717 		tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4718 	} else {
4719 		tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4720 	}
4721 
4722 	wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4723 }
4724 
4725 /**
4726  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4727  * @seid: VSI SEID
4728  * @pf: the PF structure
4729  * @pf_q: the PF queue to configure
4730  * @is_xdp: true if the queue is used for XDP
4731  * @enable: start or stop the queue
4732  **/
4733 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4734 			   bool is_xdp, bool enable)
4735 {
4736 	int ret;
4737 
4738 	i40e_control_tx_q(pf, pf_q, enable);
4739 
4740 	/* wait for the change to finish */
4741 	ret = i40e_pf_txq_wait(pf, pf_q, enable);
4742 	if (ret) {
4743 		dev_info(&pf->pdev->dev,
4744 			 "VSI seid %d %sTx ring %d %sable timeout\n",
4745 			 seid, (is_xdp ? "XDP " : ""), pf_q,
4746 			 (enable ? "en" : "dis"));
4747 	}
4748 
4749 	return ret;
4750 }
4751 
4752 /**
4753  * i40e_vsi_enable_tx - Start a VSI's rings
4754  * @vsi: the VSI being configured
4755  **/
4756 static int i40e_vsi_enable_tx(struct i40e_vsi *vsi)
4757 {
4758 	struct i40e_pf *pf = vsi->back;
4759 	int i, pf_q, ret = 0;
4760 
4761 	pf_q = vsi->base_queue;
4762 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4763 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4764 					     pf_q,
4765 					     false /*is xdp*/, true);
4766 		if (ret)
4767 			break;
4768 
4769 		if (!i40e_enabled_xdp_vsi(vsi))
4770 			continue;
4771 
4772 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4773 					     pf_q + vsi->alloc_queue_pairs,
4774 					     true /*is xdp*/, true);
4775 		if (ret)
4776 			break;
4777 	}
4778 	return ret;
4779 }
4780 
4781 /**
4782  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4783  * @pf: the PF being configured
4784  * @pf_q: the PF queue
4785  * @enable: enable or disable state of the queue
4786  *
4787  * This routine will wait for the given Rx queue of the PF to reach the
4788  * enabled or disabled state.
4789  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4790  * multiple retries; else will return 0 in case of success.
4791  **/
4792 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4793 {
4794 	int i;
4795 	u32 rx_reg;
4796 
4797 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4798 		rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4799 		if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4800 			break;
4801 
4802 		usleep_range(10, 20);
4803 	}
4804 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4805 		return -ETIMEDOUT;
4806 
4807 	return 0;
4808 }
4809 
4810 /**
4811  * i40e_control_rx_q - Start or stop a particular Rx queue
4812  * @pf: the PF structure
4813  * @pf_q: the PF queue to configure
4814  * @enable: start or stop the queue
4815  *
4816  * This function enables or disables a single queue. Note that
4817  * any delay required after the operation is expected to be
4818  * handled by the caller of this function.
4819  **/
4820 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4821 {
4822 	struct i40e_hw *hw = &pf->hw;
4823 	u32 rx_reg;
4824 	int i;
4825 
4826 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4827 		rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4828 		if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4829 		    ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4830 			break;
4831 		usleep_range(1000, 2000);
4832 	}
4833 
4834 	/* Skip if the queue is already in the requested state */
4835 	if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4836 		return;
4837 
4838 	/* turn on/off the queue */
4839 	if (enable)
4840 		rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4841 	else
4842 		rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4843 
4844 	wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4845 }
4846 
4847 /**
4848  * i40e_control_wait_rx_q
4849  * @pf: the PF structure
4850  * @pf_q: queue being configured
4851  * @enable: start or stop the rings
4852  *
4853  * This function enables or disables a single queue along with waiting
4854  * for the change to finish. The caller of this function should handle
4855  * the delays needed in the case of disabling queues.
4856  **/
4857 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4858 {
4859 	int ret = 0;
4860 
4861 	i40e_control_rx_q(pf, pf_q, enable);
4862 
4863 	/* wait for the change to finish */
4864 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4865 	if (ret)
4866 		return ret;
4867 
4868 	return ret;
4869 }
4870 
4871 /**
4872  * i40e_vsi_enable_rx - Start a VSI's rings
4873  * @vsi: the VSI being configured
4874  **/
4875 static int i40e_vsi_enable_rx(struct i40e_vsi *vsi)
4876 {
4877 	struct i40e_pf *pf = vsi->back;
4878 	int i, pf_q, ret = 0;
4879 
4880 	pf_q = vsi->base_queue;
4881 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4882 		ret = i40e_control_wait_rx_q(pf, pf_q, true);
4883 		if (ret) {
4884 			dev_info(&pf->pdev->dev,
4885 				 "VSI seid %d Rx ring %d enable timeout\n",
4886 				 vsi->seid, pf_q);
4887 			break;
4888 		}
4889 	}
4890 
4891 	return ret;
4892 }
4893 
4894 /**
4895  * i40e_vsi_start_rings - Start a VSI's rings
4896  * @vsi: the VSI being configured
4897  **/
4898 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4899 {
4900 	int ret = 0;
4901 
4902 	/* do rx first for enable and last for disable */
4903 	ret = i40e_vsi_enable_rx(vsi);
4904 	if (ret)
4905 		return ret;
4906 	ret = i40e_vsi_enable_tx(vsi);
4907 
4908 	return ret;
4909 }
4910 
4911 #define I40E_DISABLE_TX_GAP_MSEC	50
4912 
4913 /**
4914  * i40e_vsi_stop_rings - Stop a VSI's rings
4915  * @vsi: the VSI being configured
4916  **/
4917 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4918 {
4919 	struct i40e_pf *pf = vsi->back;
4920 	u32 pf_q, tx_q_end, rx_q_end;
4921 
4922 	/* When port TX is suspended, don't wait */
4923 	if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4924 		return i40e_vsi_stop_rings_no_wait(vsi);
4925 
4926 	tx_q_end = vsi->base_queue +
4927 		vsi->alloc_queue_pairs * (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
4928 	for (pf_q = vsi->base_queue; pf_q < tx_q_end; pf_q++)
4929 		i40e_pre_tx_queue_cfg(&pf->hw, pf_q, false);
4930 
4931 	rx_q_end = vsi->base_queue + vsi->num_queue_pairs;
4932 	for (pf_q = vsi->base_queue; pf_q < rx_q_end; pf_q++)
4933 		i40e_control_rx_q(pf, pf_q, false);
4934 
4935 	msleep(I40E_DISABLE_TX_GAP_MSEC);
4936 	for (pf_q = vsi->base_queue; pf_q < tx_q_end; pf_q++)
4937 		wr32(&pf->hw, I40E_QTX_ENA(pf_q), 0);
4938 
4939 	i40e_vsi_wait_queues_disabled(vsi);
4940 }
4941 
4942 /**
4943  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4944  * @vsi: the VSI being shutdown
4945  *
4946  * This function stops all the rings for a VSI but does not delay to verify
4947  * that rings have been disabled. It is expected that the caller is shutting
4948  * down multiple VSIs at once and will delay together for all the VSIs after
4949  * initiating the shutdown. This is particularly useful for shutting down lots
4950  * of VFs together. Otherwise, a large delay can be incurred while configuring
4951  * each VSI in serial.
4952  **/
4953 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4954 {
4955 	struct i40e_pf *pf = vsi->back;
4956 	int i, pf_q;
4957 
4958 	pf_q = vsi->base_queue;
4959 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4960 		i40e_control_tx_q(pf, pf_q, false);
4961 		i40e_control_rx_q(pf, pf_q, false);
4962 	}
4963 }
4964 
4965 /**
4966  * i40e_vsi_free_irq - Free the irq association with the OS
4967  * @vsi: the VSI being configured
4968  **/
4969 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4970 {
4971 	struct i40e_pf *pf = vsi->back;
4972 	struct i40e_hw *hw = &pf->hw;
4973 	int base = vsi->base_vector;
4974 	u32 val, qp;
4975 	int i;
4976 
4977 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4978 		if (!vsi->q_vectors)
4979 			return;
4980 
4981 		if (!vsi->irqs_ready)
4982 			return;
4983 
4984 		vsi->irqs_ready = false;
4985 		for (i = 0; i < vsi->num_q_vectors; i++) {
4986 			int irq_num;
4987 			u16 vector;
4988 
4989 			vector = i + base;
4990 			irq_num = pf->msix_entries[vector].vector;
4991 
4992 			/* free only the irqs that were actually requested */
4993 			if (!vsi->q_vectors[i] ||
4994 			    !vsi->q_vectors[i]->num_ringpairs)
4995 				continue;
4996 
4997 			/* clear the affinity notifier in the IRQ descriptor */
4998 			irq_set_affinity_notifier(irq_num, NULL);
4999 			/* remove our suggested affinity mask for this IRQ */
5000 			irq_update_affinity_hint(irq_num, NULL);
5001 			free_irq(irq_num, vsi->q_vectors[i]);
5002 
5003 			/* Tear down the interrupt queue link list
5004 			 *
5005 			 * We know that they come in pairs and always
5006 			 * the Rx first, then the Tx.  To clear the
5007 			 * link list, stick the EOL value into the
5008 			 * next_q field of the registers.
5009 			 */
5010 			val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
5011 			qp = FIELD_GET(I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK,
5012 				       val);
5013 			val |= I40E_QUEUE_END_OF_LIST
5014 				<< I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
5015 			wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
5016 
5017 			while (qp != I40E_QUEUE_END_OF_LIST) {
5018 				u32 next;
5019 
5020 				val = rd32(hw, I40E_QINT_RQCTL(qp));
5021 
5022 				val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5023 					 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5024 					 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5025 					 I40E_QINT_RQCTL_INTEVENT_MASK);
5026 
5027 				val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5028 					 I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5029 
5030 				wr32(hw, I40E_QINT_RQCTL(qp), val);
5031 
5032 				val = rd32(hw, I40E_QINT_TQCTL(qp));
5033 
5034 				next = FIELD_GET(I40E_QINT_TQCTL_NEXTQ_INDX_MASK,
5035 						 val);
5036 
5037 				val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5038 					 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5039 					 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5040 					 I40E_QINT_TQCTL_INTEVENT_MASK);
5041 
5042 				val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5043 					 I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5044 
5045 				wr32(hw, I40E_QINT_TQCTL(qp), val);
5046 				qp = next;
5047 			}
5048 		}
5049 	} else {
5050 		free_irq(pf->pdev->irq, pf);
5051 
5052 		val = rd32(hw, I40E_PFINT_LNKLST0);
5053 		qp = FIELD_GET(I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK, val);
5054 		val |= I40E_QUEUE_END_OF_LIST
5055 			<< I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
5056 		wr32(hw, I40E_PFINT_LNKLST0, val);
5057 
5058 		val = rd32(hw, I40E_QINT_RQCTL(qp));
5059 		val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5060 			 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5061 			 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5062 			 I40E_QINT_RQCTL_INTEVENT_MASK);
5063 
5064 		val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5065 			I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5066 
5067 		wr32(hw, I40E_QINT_RQCTL(qp), val);
5068 
5069 		val = rd32(hw, I40E_QINT_TQCTL(qp));
5070 
5071 		val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5072 			 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5073 			 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5074 			 I40E_QINT_TQCTL_INTEVENT_MASK);
5075 
5076 		val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5077 			I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5078 
5079 		wr32(hw, I40E_QINT_TQCTL(qp), val);
5080 	}
5081 }
5082 
5083 /**
5084  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
5085  * @vsi: the VSI being configured
5086  * @v_idx: Index of vector to be freed
5087  *
5088  * This function frees the memory allocated to the q_vector.  In addition if
5089  * NAPI is enabled it will delete any references to the NAPI struct prior
5090  * to freeing the q_vector.
5091  **/
5092 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
5093 {
5094 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
5095 	struct i40e_ring *ring;
5096 
5097 	if (!q_vector)
5098 		return;
5099 
5100 	/* disassociate q_vector from rings */
5101 	i40e_for_each_ring(ring, q_vector->tx)
5102 		ring->q_vector = NULL;
5103 
5104 	i40e_for_each_ring(ring, q_vector->rx)
5105 		ring->q_vector = NULL;
5106 
5107 	/* only VSI w/ an associated netdev is set up w/ NAPI */
5108 	if (vsi->netdev)
5109 		netif_napi_del(&q_vector->napi);
5110 
5111 	vsi->q_vectors[v_idx] = NULL;
5112 
5113 	kfree_rcu(q_vector, rcu);
5114 }
5115 
5116 /**
5117  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
5118  * @vsi: the VSI being un-configured
5119  *
5120  * This frees the memory allocated to the q_vectors and
5121  * deletes references to the NAPI struct.
5122  **/
5123 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
5124 {
5125 	int v_idx;
5126 
5127 	for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
5128 		i40e_free_q_vector(vsi, v_idx);
5129 }
5130 
5131 /**
5132  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
5133  * @pf: board private structure
5134  **/
5135 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
5136 {
5137 	/* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
5138 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
5139 		pci_disable_msix(pf->pdev);
5140 		kfree(pf->msix_entries);
5141 		pf->msix_entries = NULL;
5142 		kfree(pf->irq_pile);
5143 		pf->irq_pile = NULL;
5144 	} else if (test_bit(I40E_FLAG_MSI_ENA, pf->flags)) {
5145 		pci_disable_msi(pf->pdev);
5146 	}
5147 	clear_bit(I40E_FLAG_MSI_ENA, pf->flags);
5148 	clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
5149 }
5150 
5151 /**
5152  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
5153  * @pf: board private structure
5154  *
5155  * We go through and clear interrupt specific resources and reset the structure
5156  * to pre-load conditions
5157  **/
5158 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
5159 {
5160 	struct i40e_vsi *vsi;
5161 	int i;
5162 
5163 	if (test_bit(__I40E_MISC_IRQ_REQUESTED, pf->state))
5164 		i40e_free_misc_vector(pf);
5165 
5166 	i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
5167 		      I40E_IWARP_IRQ_PILE_ID);
5168 
5169 	i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
5170 
5171 	i40e_pf_for_each_vsi(pf, i, vsi)
5172 		i40e_vsi_free_q_vectors(vsi);
5173 
5174 	i40e_reset_interrupt_capability(pf);
5175 }
5176 
5177 /**
5178  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5179  * @vsi: the VSI being configured
5180  **/
5181 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
5182 {
5183 	int q_idx;
5184 
5185 	if (!vsi->netdev)
5186 		return;
5187 
5188 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5189 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5190 
5191 		if (q_vector->rx.ring || q_vector->tx.ring)
5192 			napi_enable(&q_vector->napi);
5193 	}
5194 }
5195 
5196 /**
5197  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
5198  * @vsi: the VSI being configured
5199  **/
5200 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
5201 {
5202 	int q_idx;
5203 
5204 	if (!vsi->netdev)
5205 		return;
5206 
5207 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5208 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5209 
5210 		if (q_vector->rx.ring || q_vector->tx.ring)
5211 			napi_disable(&q_vector->napi);
5212 	}
5213 }
5214 
5215 /**
5216  * i40e_vsi_close - Shut down a VSI
5217  * @vsi: the vsi to be quelled
5218  **/
5219 static void i40e_vsi_close(struct i40e_vsi *vsi)
5220 {
5221 	struct i40e_pf *pf = vsi->back;
5222 	if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
5223 		i40e_down(vsi);
5224 	i40e_vsi_free_irq(vsi);
5225 	i40e_vsi_free_tx_resources(vsi);
5226 	i40e_vsi_free_rx_resources(vsi);
5227 	vsi->current_netdev_flags = 0;
5228 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
5229 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
5230 		set_bit(__I40E_CLIENT_RESET, pf->state);
5231 }
5232 
5233 /**
5234  * i40e_quiesce_vsi - Pause a given VSI
5235  * @vsi: the VSI being paused
5236  **/
5237 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
5238 {
5239 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
5240 		return;
5241 
5242 	set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
5243 	if (vsi->netdev && netif_running(vsi->netdev))
5244 		vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
5245 	else
5246 		i40e_vsi_close(vsi);
5247 }
5248 
5249 /**
5250  * i40e_unquiesce_vsi - Resume a given VSI
5251  * @vsi: the VSI being resumed
5252  **/
5253 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
5254 {
5255 	if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
5256 		return;
5257 
5258 	if (vsi->netdev && netif_running(vsi->netdev))
5259 		vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
5260 	else
5261 		i40e_vsi_open(vsi);   /* this clears the DOWN bit */
5262 }
5263 
5264 /**
5265  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
5266  * @pf: the PF
5267  **/
5268 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
5269 {
5270 	struct i40e_vsi *vsi;
5271 	int v;
5272 
5273 	i40e_pf_for_each_vsi(pf, v, vsi)
5274 		i40e_quiesce_vsi(vsi);
5275 }
5276 
5277 /**
5278  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
5279  * @pf: the PF
5280  **/
5281 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
5282 {
5283 	struct i40e_vsi *vsi;
5284 	int v;
5285 
5286 	i40e_pf_for_each_vsi(pf, v, vsi)
5287 		i40e_unquiesce_vsi(vsi);
5288 }
5289 
5290 /**
5291  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
5292  * @vsi: the VSI being configured
5293  *
5294  * Wait until all queues on a given VSI have been disabled.
5295  **/
5296 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
5297 {
5298 	struct i40e_pf *pf = vsi->back;
5299 	int i, pf_q, ret;
5300 
5301 	pf_q = vsi->base_queue;
5302 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
5303 		/* Check and wait for the Tx queue */
5304 		ret = i40e_pf_txq_wait(pf, pf_q, false);
5305 		if (ret) {
5306 			dev_info(&pf->pdev->dev,
5307 				 "VSI seid %d Tx ring %d disable timeout\n",
5308 				 vsi->seid, pf_q);
5309 			return ret;
5310 		}
5311 
5312 		if (!i40e_enabled_xdp_vsi(vsi))
5313 			goto wait_rx;
5314 
5315 		/* Check and wait for the XDP Tx queue */
5316 		ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
5317 				       false);
5318 		if (ret) {
5319 			dev_info(&pf->pdev->dev,
5320 				 "VSI seid %d XDP Tx ring %d disable timeout\n",
5321 				 vsi->seid, pf_q);
5322 			return ret;
5323 		}
5324 wait_rx:
5325 		/* Check and wait for the Rx queue */
5326 		ret = i40e_pf_rxq_wait(pf, pf_q, false);
5327 		if (ret) {
5328 			dev_info(&pf->pdev->dev,
5329 				 "VSI seid %d Rx ring %d disable timeout\n",
5330 				 vsi->seid, pf_q);
5331 			return ret;
5332 		}
5333 	}
5334 
5335 	return 0;
5336 }
5337 
5338 #ifdef CONFIG_I40E_DCB
5339 /**
5340  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
5341  * @pf: the PF
5342  *
5343  * This function waits for the queues to be in disabled state for all the
5344  * VSIs that are managed by this PF.
5345  **/
5346 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
5347 {
5348 	struct i40e_vsi *vsi;
5349 	int v, ret = 0;
5350 
5351 	i40e_pf_for_each_vsi(pf, v, vsi) {
5352 		ret = i40e_vsi_wait_queues_disabled(vsi);
5353 		if (ret)
5354 			break;
5355 	}
5356 
5357 	return ret;
5358 }
5359 
5360 #endif
5361 
5362 /**
5363  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
5364  * @pf: pointer to PF
5365  *
5366  * Get TC map for ISCSI PF type that will include iSCSI TC
5367  * and LAN TC.
5368  **/
5369 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
5370 {
5371 	struct i40e_dcb_app_priority_table app;
5372 	struct i40e_hw *hw = &pf->hw;
5373 	u8 enabled_tc = 1; /* TC0 is always enabled */
5374 	u8 tc, i;
5375 	/* Get the iSCSI APP TLV */
5376 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5377 
5378 	for (i = 0; i < dcbcfg->numapps; i++) {
5379 		app = dcbcfg->app[i];
5380 		if (app.selector == I40E_APP_SEL_TCPIP &&
5381 		    app.protocolid == I40E_APP_PROTOID_ISCSI) {
5382 			tc = dcbcfg->etscfg.prioritytable[app.priority];
5383 			enabled_tc |= BIT(tc);
5384 			break;
5385 		}
5386 	}
5387 
5388 	return enabled_tc;
5389 }
5390 
5391 /**
5392  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5393  * @dcbcfg: the corresponding DCBx configuration structure
5394  *
5395  * Return the number of TCs from given DCBx configuration
5396  **/
5397 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5398 {
5399 	int i, tc_unused = 0;
5400 	u8 num_tc = 0;
5401 	u8 ret = 0;
5402 
5403 	/* Scan the ETS Config Priority Table to find
5404 	 * traffic class enabled for a given priority
5405 	 * and create a bitmask of enabled TCs
5406 	 */
5407 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5408 		num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5409 
5410 	/* Now scan the bitmask to check for
5411 	 * contiguous TCs starting with TC0
5412 	 */
5413 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5414 		if (num_tc & BIT(i)) {
5415 			if (!tc_unused) {
5416 				ret++;
5417 			} else {
5418 				pr_err("Non-contiguous TC - Disabling DCB\n");
5419 				return 1;
5420 			}
5421 		} else {
5422 			tc_unused = 1;
5423 		}
5424 	}
5425 
5426 	/* There is always at least TC0 */
5427 	if (!ret)
5428 		ret = 1;
5429 
5430 	return ret;
5431 }
5432 
5433 /**
5434  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5435  * @dcbcfg: the corresponding DCBx configuration structure
5436  *
5437  * Query the current DCB configuration and return the number of
5438  * traffic classes enabled from the given DCBX config
5439  **/
5440 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5441 {
5442 	u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5443 	u8 enabled_tc = 1;
5444 	u8 i;
5445 
5446 	for (i = 0; i < num_tc; i++)
5447 		enabled_tc |= BIT(i);
5448 
5449 	return enabled_tc;
5450 }
5451 
5452 /**
5453  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5454  * @pf: PF being queried
5455  *
5456  * Query the current MQPRIO configuration and return the number of
5457  * traffic classes enabled.
5458  **/
5459 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5460 {
5461 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
5462 	u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5463 	u8 enabled_tc = 1, i;
5464 
5465 	for (i = 1; i < num_tc; i++)
5466 		enabled_tc |= BIT(i);
5467 	return enabled_tc;
5468 }
5469 
5470 /**
5471  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5472  * @pf: PF being queried
5473  *
5474  * Return number of traffic classes enabled for the given PF
5475  **/
5476 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5477 {
5478 	u8 i, enabled_tc = 1;
5479 	u8 num_tc = 0;
5480 
5481 	if (i40e_is_tc_mqprio_enabled(pf)) {
5482 		struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
5483 
5484 		return vsi->mqprio_qopt.qopt.num_tc;
5485 	}
5486 
5487 	/* If neither MQPRIO nor DCB is enabled, then always use single TC */
5488 	if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags))
5489 		return 1;
5490 
5491 	/* SFP mode will be enabled for all TCs on port */
5492 	if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
5493 		return i40e_dcb_get_num_tc(&pf->hw.local_dcbx_config);
5494 
5495 	/* MFP mode return count of enabled TCs for this PF */
5496 	if (pf->hw.func_caps.iscsi)
5497 		enabled_tc =  i40e_get_iscsi_tc_map(pf);
5498 	else
5499 		return 1; /* Only TC0 */
5500 
5501 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5502 		if (enabled_tc & BIT(i))
5503 			num_tc++;
5504 	}
5505 	return num_tc;
5506 }
5507 
5508 /**
5509  * i40e_pf_get_tc_map - Get bitmap for enabled traffic classes
5510  * @pf: PF being queried
5511  *
5512  * Return a bitmap for enabled traffic classes for this PF.
5513  **/
5514 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5515 {
5516 	if (i40e_is_tc_mqprio_enabled(pf))
5517 		return i40e_mqprio_get_enabled_tc(pf);
5518 
5519 	/* If neither MQPRIO nor DCB is enabled for this PF then just return
5520 	 * default TC
5521 	 */
5522 	if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags))
5523 		return I40E_DEFAULT_TRAFFIC_CLASS;
5524 
5525 	/* SFP mode we want PF to be enabled for all TCs */
5526 	if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
5527 		return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5528 
5529 	/* MFP enabled and iSCSI PF type */
5530 	if (pf->hw.func_caps.iscsi)
5531 		return i40e_get_iscsi_tc_map(pf);
5532 	else
5533 		return I40E_DEFAULT_TRAFFIC_CLASS;
5534 }
5535 
5536 /**
5537  * i40e_vsi_get_bw_info - Query VSI BW Information
5538  * @vsi: the VSI being queried
5539  *
5540  * Returns 0 on success, negative value on failure
5541  **/
5542 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5543 {
5544 	struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5545 	struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5546 	struct i40e_pf *pf = vsi->back;
5547 	struct i40e_hw *hw = &pf->hw;
5548 	u32 tc_bw_max;
5549 	int ret;
5550 	int i;
5551 
5552 	/* Get the VSI level BW configuration */
5553 	ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5554 	if (ret) {
5555 		dev_info(&pf->pdev->dev,
5556 			 "couldn't get PF vsi bw config, err %pe aq_err %s\n",
5557 			 ERR_PTR(ret),
5558 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5559 		return -EINVAL;
5560 	}
5561 
5562 	/* Get the VSI level BW configuration per TC */
5563 	ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5564 					       NULL);
5565 	if (ret) {
5566 		dev_info(&pf->pdev->dev,
5567 			 "couldn't get PF vsi ets bw config, err %pe aq_err %s\n",
5568 			 ERR_PTR(ret),
5569 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5570 		return -EINVAL;
5571 	}
5572 
5573 	if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5574 		dev_info(&pf->pdev->dev,
5575 			 "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5576 			 bw_config.tc_valid_bits,
5577 			 bw_ets_config.tc_valid_bits);
5578 		/* Still continuing */
5579 	}
5580 
5581 	vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5582 	vsi->bw_max_quanta = bw_config.max_bw;
5583 	tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5584 		    (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5585 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5586 		vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5587 		vsi->bw_ets_limit_credits[i] =
5588 					le16_to_cpu(bw_ets_config.credits[i]);
5589 		/* 3 bits out of 4 for each TC */
5590 		vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5591 	}
5592 
5593 	return 0;
5594 }
5595 
5596 /**
5597  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5598  * @vsi: the VSI being configured
5599  * @enabled_tc: TC bitmap
5600  * @bw_share: BW shared credits per TC
5601  *
5602  * Returns 0 on success, negative value on failure
5603  **/
5604 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5605 				       u8 *bw_share)
5606 {
5607 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5608 	struct i40e_pf *pf = vsi->back;
5609 	int ret;
5610 	int i;
5611 
5612 	/* There is no need to reset BW when mqprio mode is on.  */
5613 	if (i40e_is_tc_mqprio_enabled(pf))
5614 		return 0;
5615 	if (!vsi->mqprio_qopt.qopt.hw && !test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
5616 		ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5617 		if (ret)
5618 			dev_info(&pf->pdev->dev,
5619 				 "Failed to reset tx rate for vsi->seid %u\n",
5620 				 vsi->seid);
5621 		return ret;
5622 	}
5623 	memset(&bw_data, 0, sizeof(bw_data));
5624 	bw_data.tc_valid_bits = enabled_tc;
5625 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5626 		bw_data.tc_bw_credits[i] = bw_share[i];
5627 
5628 	ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5629 	if (ret) {
5630 		dev_info(&pf->pdev->dev,
5631 			 "AQ command Config VSI BW allocation per TC failed = %d\n",
5632 			 pf->hw.aq.asq_last_status);
5633 		return -EINVAL;
5634 	}
5635 
5636 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5637 		vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5638 
5639 	return 0;
5640 }
5641 
5642 /**
5643  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5644  * @vsi: the VSI being configured
5645  * @enabled_tc: TC map to be enabled
5646  *
5647  **/
5648 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5649 {
5650 	struct net_device *netdev = vsi->netdev;
5651 	struct i40e_pf *pf = vsi->back;
5652 	struct i40e_hw *hw = &pf->hw;
5653 	u8 netdev_tc = 0;
5654 	int i;
5655 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5656 
5657 	if (!netdev)
5658 		return;
5659 
5660 	if (!enabled_tc) {
5661 		netdev_reset_tc(netdev);
5662 		return;
5663 	}
5664 
5665 	/* Set up actual enabled TCs on the VSI */
5666 	if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5667 		return;
5668 
5669 	/* set per TC queues for the VSI */
5670 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5671 		/* Only set TC queues for enabled tcs
5672 		 *
5673 		 * e.g. For a VSI that has TC0 and TC3 enabled the
5674 		 * enabled_tc bitmap would be 0x00001001; the driver
5675 		 * will set the numtc for netdev as 2 that will be
5676 		 * referenced by the netdev layer as TC 0 and 1.
5677 		 */
5678 		if (vsi->tc_config.enabled_tc & BIT(i))
5679 			netdev_set_tc_queue(netdev,
5680 					vsi->tc_config.tc_info[i].netdev_tc,
5681 					vsi->tc_config.tc_info[i].qcount,
5682 					vsi->tc_config.tc_info[i].qoffset);
5683 	}
5684 
5685 	if (i40e_is_tc_mqprio_enabled(pf))
5686 		return;
5687 
5688 	/* Assign UP2TC map for the VSI */
5689 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5690 		/* Get the actual TC# for the UP */
5691 		u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5692 		/* Get the mapped netdev TC# for the UP */
5693 		netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5694 		netdev_set_prio_tc_map(netdev, i, netdev_tc);
5695 	}
5696 }
5697 
5698 /**
5699  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5700  * @vsi: the VSI being configured
5701  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5702  **/
5703 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5704 				      struct i40e_vsi_context *ctxt)
5705 {
5706 	/* copy just the sections touched not the entire info
5707 	 * since not all sections are valid as returned by
5708 	 * update vsi params
5709 	 */
5710 	vsi->info.mapping_flags = ctxt->info.mapping_flags;
5711 	memcpy(&vsi->info.queue_mapping,
5712 	       &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5713 	memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5714 	       sizeof(vsi->info.tc_mapping));
5715 }
5716 
5717 /**
5718  * i40e_update_adq_vsi_queues - update queue mapping for ADq VSI
5719  * @vsi: the VSI being reconfigured
5720  * @vsi_offset: offset from main VF VSI
5721  */
5722 int i40e_update_adq_vsi_queues(struct i40e_vsi *vsi, int vsi_offset)
5723 {
5724 	struct i40e_vsi_context ctxt = {};
5725 	struct i40e_pf *pf;
5726 	struct i40e_hw *hw;
5727 	int ret;
5728 
5729 	if (!vsi)
5730 		return -EINVAL;
5731 	pf = vsi->back;
5732 	hw = &pf->hw;
5733 
5734 	ctxt.seid = vsi->seid;
5735 	ctxt.pf_num = hw->pf_id;
5736 	ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id + vsi_offset;
5737 	ctxt.uplink_seid = vsi->uplink_seid;
5738 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5739 	ctxt.flags = I40E_AQ_VSI_TYPE_VF;
5740 	ctxt.info = vsi->info;
5741 
5742 	i40e_vsi_setup_queue_map(vsi, &ctxt, vsi->tc_config.enabled_tc,
5743 				 false);
5744 	if (vsi->reconfig_rss) {
5745 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
5746 				      vsi->num_queue_pairs);
5747 		ret = i40e_vsi_config_rss(vsi);
5748 		if (ret) {
5749 			dev_info(&pf->pdev->dev, "Failed to reconfig rss for num_queues\n");
5750 			return ret;
5751 		}
5752 		vsi->reconfig_rss = false;
5753 	}
5754 
5755 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5756 	if (ret) {
5757 		dev_info(&pf->pdev->dev, "Update vsi config failed, err %pe aq_err %s\n",
5758 			 ERR_PTR(ret),
5759 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5760 		return ret;
5761 	}
5762 	/* update the local VSI info with updated queue map */
5763 	i40e_vsi_update_queue_map(vsi, &ctxt);
5764 	vsi->info.valid_sections = 0;
5765 
5766 	return ret;
5767 }
5768 
5769 /**
5770  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5771  * @vsi: VSI to be configured
5772  * @enabled_tc: TC bitmap
5773  *
5774  * This configures a particular VSI for TCs that are mapped to the
5775  * given TC bitmap. It uses default bandwidth share for TCs across
5776  * VSIs to configure TC for a particular VSI.
5777  *
5778  * NOTE:
5779  * It is expected that the VSI queues have been quisced before calling
5780  * this function.
5781  **/
5782 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5783 {
5784 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5785 	struct i40e_pf *pf = vsi->back;
5786 	struct i40e_hw *hw = &pf->hw;
5787 	struct i40e_vsi_context ctxt;
5788 	int ret = 0;
5789 	int i;
5790 
5791 	/* Check if enabled_tc is same as existing or new TCs */
5792 	if (vsi->tc_config.enabled_tc == enabled_tc &&
5793 	    vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5794 		return ret;
5795 
5796 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
5797 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5798 		if (enabled_tc & BIT(i))
5799 			bw_share[i] = 1;
5800 	}
5801 
5802 	ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5803 	if (ret) {
5804 		struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5805 
5806 		dev_info(&pf->pdev->dev,
5807 			 "Failed configuring TC map %d for VSI %d\n",
5808 			 enabled_tc, vsi->seid);
5809 		ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5810 						  &bw_config, NULL);
5811 		if (ret) {
5812 			dev_info(&pf->pdev->dev,
5813 				 "Failed querying vsi bw info, err %pe aq_err %s\n",
5814 				 ERR_PTR(ret),
5815 				 i40e_aq_str(hw, hw->aq.asq_last_status));
5816 			goto out;
5817 		}
5818 		if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5819 			u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5820 
5821 			if (!valid_tc)
5822 				valid_tc = bw_config.tc_valid_bits;
5823 			/* Always enable TC0, no matter what */
5824 			valid_tc |= 1;
5825 			dev_info(&pf->pdev->dev,
5826 				 "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5827 				 enabled_tc, bw_config.tc_valid_bits, valid_tc);
5828 			enabled_tc = valid_tc;
5829 		}
5830 
5831 		ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5832 		if (ret) {
5833 			dev_err(&pf->pdev->dev,
5834 				"Unable to  configure TC map %d for VSI %d\n",
5835 				enabled_tc, vsi->seid);
5836 			goto out;
5837 		}
5838 	}
5839 
5840 	/* Update Queue Pairs Mapping for currently enabled UPs */
5841 	ctxt.seid = vsi->seid;
5842 	ctxt.pf_num = vsi->back->hw.pf_id;
5843 	ctxt.vf_num = 0;
5844 	ctxt.uplink_seid = vsi->uplink_seid;
5845 	ctxt.info = vsi->info;
5846 	if (i40e_is_tc_mqprio_enabled(pf)) {
5847 		ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5848 		if (ret)
5849 			goto out;
5850 	} else {
5851 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5852 	}
5853 
5854 	/* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5855 	 * queues changed.
5856 	 */
5857 	if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5858 		vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5859 				      vsi->num_queue_pairs);
5860 		ret = i40e_vsi_config_rss(vsi);
5861 		if (ret) {
5862 			dev_info(&vsi->back->pdev->dev,
5863 				 "Failed to reconfig rss for num_queues\n");
5864 			return ret;
5865 		}
5866 		vsi->reconfig_rss = false;
5867 	}
5868 	if (test_bit(I40E_FLAG_IWARP_ENA, vsi->back->flags)) {
5869 		ctxt.info.valid_sections |=
5870 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5871 		ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5872 	}
5873 
5874 	/* Update the VSI after updating the VSI queue-mapping
5875 	 * information
5876 	 */
5877 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5878 	if (ret) {
5879 		dev_info(&pf->pdev->dev,
5880 			 "Update vsi tc config failed, err %pe aq_err %s\n",
5881 			 ERR_PTR(ret),
5882 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5883 		goto out;
5884 	}
5885 	/* update the local VSI info with updated queue map */
5886 	i40e_vsi_update_queue_map(vsi, &ctxt);
5887 	vsi->info.valid_sections = 0;
5888 
5889 	/* Update current VSI BW information */
5890 	ret = i40e_vsi_get_bw_info(vsi);
5891 	if (ret) {
5892 		dev_info(&pf->pdev->dev,
5893 			 "Failed updating vsi bw info, err %pe aq_err %s\n",
5894 			 ERR_PTR(ret),
5895 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5896 		goto out;
5897 	}
5898 
5899 	/* Update the netdev TC setup */
5900 	i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5901 out:
5902 	return ret;
5903 }
5904 
5905 /**
5906  * i40e_vsi_reconfig_tc - Reconfigure VSI Tx Scheduler for stored TC map
5907  * @vsi: VSI to be reconfigured
5908  *
5909  * This reconfigures a particular VSI for TCs that are mapped to the
5910  * TC bitmap stored previously for the VSI.
5911  *
5912  * Context: It is expected that the VSI queues have been quisced before
5913  *          calling this function.
5914  *
5915  * Return: 0 on success, negative value on failure
5916  **/
5917 static int i40e_vsi_reconfig_tc(struct i40e_vsi *vsi)
5918 {
5919 	u8 enabled_tc;
5920 
5921 	enabled_tc = vsi->tc_config.enabled_tc;
5922 	vsi->tc_config.enabled_tc = 0;
5923 
5924 	return i40e_vsi_config_tc(vsi, enabled_tc);
5925 }
5926 
5927 /**
5928  * i40e_get_link_speed - Returns link speed for the interface
5929  * @vsi: VSI to be configured
5930  *
5931  **/
5932 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5933 {
5934 	struct i40e_pf *pf = vsi->back;
5935 
5936 	switch (pf->hw.phy.link_info.link_speed) {
5937 	case I40E_LINK_SPEED_40GB:
5938 		return 40000;
5939 	case I40E_LINK_SPEED_25GB:
5940 		return 25000;
5941 	case I40E_LINK_SPEED_20GB:
5942 		return 20000;
5943 	case I40E_LINK_SPEED_10GB:
5944 		return 10000;
5945 	case I40E_LINK_SPEED_1GB:
5946 		return 1000;
5947 	default:
5948 		return -EINVAL;
5949 	}
5950 }
5951 
5952 /**
5953  * i40e_bw_bytes_to_mbits - Convert max_tx_rate from bytes to mbits
5954  * @vsi: Pointer to vsi structure
5955  * @max_tx_rate: max TX rate in bytes to be converted into Mbits
5956  *
5957  * Helper function to convert units before send to set BW limit
5958  **/
5959 static u64 i40e_bw_bytes_to_mbits(struct i40e_vsi *vsi, u64 max_tx_rate)
5960 {
5961 	if (max_tx_rate < I40E_BW_MBPS_DIVISOR) {
5962 		dev_warn(&vsi->back->pdev->dev,
5963 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
5964 		max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5965 	} else {
5966 		do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
5967 	}
5968 
5969 	return max_tx_rate;
5970 }
5971 
5972 /**
5973  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5974  * @vsi: VSI to be configured
5975  * @seid: seid of the channel/VSI
5976  * @max_tx_rate: max TX rate to be configured as BW limit
5977  *
5978  * Helper function to set BW limit for a given VSI
5979  **/
5980 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5981 {
5982 	struct i40e_pf *pf = vsi->back;
5983 	u64 credits = 0;
5984 	int speed = 0;
5985 	int ret = 0;
5986 
5987 	speed = i40e_get_link_speed(vsi);
5988 	if (max_tx_rate > speed) {
5989 		dev_err(&pf->pdev->dev,
5990 			"Invalid max tx rate %llu specified for VSI seid %d.",
5991 			max_tx_rate, seid);
5992 		return -EINVAL;
5993 	}
5994 	if (max_tx_rate && max_tx_rate < I40E_BW_CREDIT_DIVISOR) {
5995 		dev_warn(&pf->pdev->dev,
5996 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
5997 		max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5998 	}
5999 
6000 	/* Tx rate credits are in values of 50Mbps, 0 is disabled */
6001 	credits = max_tx_rate;
6002 	do_div(credits, I40E_BW_CREDIT_DIVISOR);
6003 	ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
6004 					  I40E_MAX_BW_INACTIVE_ACCUM, NULL);
6005 	if (ret)
6006 		dev_err(&pf->pdev->dev,
6007 			"Failed set tx rate (%llu Mbps) for vsi->seid %u, err %pe aq_err %s\n",
6008 			max_tx_rate, seid, ERR_PTR(ret),
6009 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6010 	return ret;
6011 }
6012 
6013 /**
6014  * i40e_remove_queue_channels - Remove queue channels for the TCs
6015  * @vsi: VSI to be configured
6016  *
6017  * Remove queue channels for the TCs
6018  **/
6019 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
6020 {
6021 	enum i40e_admin_queue_err last_aq_status;
6022 	struct i40e_cloud_filter *cfilter;
6023 	struct i40e_channel *ch, *ch_tmp;
6024 	struct i40e_pf *pf = vsi->back;
6025 	struct hlist_node *node;
6026 	int ret, i;
6027 
6028 	/* Reset rss size that was stored when reconfiguring rss for
6029 	 * channel VSIs with non-power-of-2 queue count.
6030 	 */
6031 	vsi->current_rss_size = 0;
6032 
6033 	/* perform cleanup for channels if they exist */
6034 	if (list_empty(&vsi->ch_list))
6035 		return;
6036 
6037 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6038 		struct i40e_vsi *p_vsi;
6039 
6040 		list_del(&ch->list);
6041 		p_vsi = ch->parent_vsi;
6042 		if (!p_vsi || !ch->initialized) {
6043 			kfree(ch);
6044 			continue;
6045 		}
6046 		/* Reset queue contexts */
6047 		for (i = 0; i < ch->num_queue_pairs; i++) {
6048 			struct i40e_ring *tx_ring, *rx_ring;
6049 			u16 pf_q;
6050 
6051 			pf_q = ch->base_queue + i;
6052 			tx_ring = vsi->tx_rings[pf_q];
6053 			tx_ring->ch = NULL;
6054 
6055 			rx_ring = vsi->rx_rings[pf_q];
6056 			rx_ring->ch = NULL;
6057 		}
6058 
6059 		/* Reset BW configured for this VSI via mqprio */
6060 		ret = i40e_set_bw_limit(vsi, ch->seid, 0);
6061 		if (ret)
6062 			dev_info(&vsi->back->pdev->dev,
6063 				 "Failed to reset tx rate for ch->seid %u\n",
6064 				 ch->seid);
6065 
6066 		/* delete cloud filters associated with this channel */
6067 		hlist_for_each_entry_safe(cfilter, node,
6068 					  &pf->cloud_filter_list, cloud_node) {
6069 			if (cfilter->seid != ch->seid)
6070 				continue;
6071 
6072 			hash_del(&cfilter->cloud_node);
6073 			if (cfilter->dst_port)
6074 				ret = i40e_add_del_cloud_filter_big_buf(vsi,
6075 									cfilter,
6076 									false);
6077 			else
6078 				ret = i40e_add_del_cloud_filter(vsi, cfilter,
6079 								false);
6080 			last_aq_status = pf->hw.aq.asq_last_status;
6081 			if (ret)
6082 				dev_info(&pf->pdev->dev,
6083 					 "Failed to delete cloud filter, err %pe aq_err %s\n",
6084 					 ERR_PTR(ret),
6085 					 i40e_aq_str(&pf->hw, last_aq_status));
6086 			kfree(cfilter);
6087 		}
6088 
6089 		/* delete VSI from FW */
6090 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
6091 					     NULL);
6092 		if (ret)
6093 			dev_err(&vsi->back->pdev->dev,
6094 				"unable to remove channel (%d) for parent VSI(%d)\n",
6095 				ch->seid, p_vsi->seid);
6096 		kfree(ch);
6097 	}
6098 	INIT_LIST_HEAD(&vsi->ch_list);
6099 }
6100 
6101 /**
6102  * i40e_get_max_queues_for_channel
6103  * @vsi: ptr to VSI to which channels are associated with
6104  *
6105  * Helper function which returns max value among the queue counts set on the
6106  * channels/TCs created.
6107  **/
6108 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
6109 {
6110 	struct i40e_channel *ch, *ch_tmp;
6111 	int max = 0;
6112 
6113 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6114 		if (!ch->initialized)
6115 			continue;
6116 		if (ch->num_queue_pairs > max)
6117 			max = ch->num_queue_pairs;
6118 	}
6119 
6120 	return max;
6121 }
6122 
6123 /**
6124  * i40e_validate_num_queues - validate num_queues w.r.t channel
6125  * @pf: ptr to PF device
6126  * @num_queues: number of queues
6127  * @vsi: the parent VSI
6128  * @reconfig_rss: indicates should the RSS be reconfigured or not
6129  *
6130  * This function validates number of queues in the context of new channel
6131  * which is being established and determines if RSS should be reconfigured
6132  * or not for parent VSI.
6133  **/
6134 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
6135 				    struct i40e_vsi *vsi, bool *reconfig_rss)
6136 {
6137 	int max_ch_queues;
6138 
6139 	if (!reconfig_rss)
6140 		return -EINVAL;
6141 
6142 	*reconfig_rss = false;
6143 	if (vsi->current_rss_size) {
6144 		if (num_queues > vsi->current_rss_size) {
6145 			dev_dbg(&pf->pdev->dev,
6146 				"Error: num_queues (%d) > vsi's current_size(%d)\n",
6147 				num_queues, vsi->current_rss_size);
6148 			return -EINVAL;
6149 		} else if ((num_queues < vsi->current_rss_size) &&
6150 			   (!is_power_of_2(num_queues))) {
6151 			dev_dbg(&pf->pdev->dev,
6152 				"Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
6153 				num_queues, vsi->current_rss_size);
6154 			return -EINVAL;
6155 		}
6156 	}
6157 
6158 	if (!is_power_of_2(num_queues)) {
6159 		/* Find the max num_queues configured for channel if channel
6160 		 * exist.
6161 		 * if channel exist, then enforce 'num_queues' to be more than
6162 		 * max ever queues configured for channel.
6163 		 */
6164 		max_ch_queues = i40e_get_max_queues_for_channel(vsi);
6165 		if (num_queues < max_ch_queues) {
6166 			dev_dbg(&pf->pdev->dev,
6167 				"Error: num_queues (%d) < max queues configured for channel(%d)\n",
6168 				num_queues, max_ch_queues);
6169 			return -EINVAL;
6170 		}
6171 		*reconfig_rss = true;
6172 	}
6173 
6174 	return 0;
6175 }
6176 
6177 /**
6178  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
6179  * @vsi: the VSI being setup
6180  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
6181  *
6182  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
6183  **/
6184 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
6185 {
6186 	struct i40e_pf *pf = vsi->back;
6187 	u8 seed[I40E_HKEY_ARRAY_SIZE];
6188 	struct i40e_hw *hw = &pf->hw;
6189 	int local_rss_size;
6190 	u8 *lut;
6191 	int ret;
6192 
6193 	if (!vsi->rss_size)
6194 		return -EINVAL;
6195 
6196 	if (rss_size > vsi->rss_size)
6197 		return -EINVAL;
6198 
6199 	local_rss_size = min_t(int, vsi->rss_size, rss_size);
6200 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
6201 	if (!lut)
6202 		return -ENOMEM;
6203 
6204 	/* Ignoring user configured lut if there is one */
6205 	i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
6206 
6207 	/* Use user configured hash key if there is one, otherwise
6208 	 * use default.
6209 	 */
6210 	if (vsi->rss_hkey_user)
6211 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
6212 	else
6213 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
6214 
6215 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
6216 	if (ret) {
6217 		dev_info(&pf->pdev->dev,
6218 			 "Cannot set RSS lut, err %pe aq_err %s\n",
6219 			 ERR_PTR(ret),
6220 			 i40e_aq_str(hw, hw->aq.asq_last_status));
6221 		kfree(lut);
6222 		return ret;
6223 	}
6224 	kfree(lut);
6225 
6226 	/* Do the update w.r.t. storing rss_size */
6227 	if (!vsi->orig_rss_size)
6228 		vsi->orig_rss_size = vsi->rss_size;
6229 	vsi->current_rss_size = local_rss_size;
6230 
6231 	return ret;
6232 }
6233 
6234 /**
6235  * i40e_channel_setup_queue_map - Setup a channel queue map
6236  * @pf: ptr to PF device
6237  * @ctxt: VSI context structure
6238  * @ch: ptr to channel structure
6239  *
6240  * Setup queue map for a specific channel
6241  **/
6242 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
6243 					 struct i40e_vsi_context *ctxt,
6244 					 struct i40e_channel *ch)
6245 {
6246 	u16 qcount, qmap, sections = 0;
6247 	u8 offset = 0;
6248 	int pow;
6249 
6250 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
6251 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
6252 
6253 	qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
6254 	ch->num_queue_pairs = qcount;
6255 
6256 	/* find the next higher power-of-2 of num queue pairs */
6257 	pow = ilog2(qcount);
6258 	if (!is_power_of_2(qcount))
6259 		pow++;
6260 
6261 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
6262 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
6263 
6264 	/* Setup queue TC[0].qmap for given VSI context */
6265 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
6266 
6267 	ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
6268 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
6269 	ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
6270 	ctxt->info.valid_sections |= cpu_to_le16(sections);
6271 }
6272 
6273 /**
6274  * i40e_add_channel - add a channel by adding VSI
6275  * @pf: ptr to PF device
6276  * @uplink_seid: underlying HW switching element (VEB) ID
6277  * @ch: ptr to channel structure
6278  *
6279  * Add a channel (VSI) using add_vsi and queue_map
6280  **/
6281 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
6282 			    struct i40e_channel *ch)
6283 {
6284 	struct i40e_hw *hw = &pf->hw;
6285 	struct i40e_vsi_context ctxt;
6286 	u8 enabled_tc = 0x1; /* TC0 enabled */
6287 	int ret;
6288 
6289 	if (ch->type != I40E_VSI_VMDQ2) {
6290 		dev_info(&pf->pdev->dev,
6291 			 "add new vsi failed, ch->type %d\n", ch->type);
6292 		return -EINVAL;
6293 	}
6294 
6295 	memset(&ctxt, 0, sizeof(ctxt));
6296 	ctxt.pf_num = hw->pf_id;
6297 	ctxt.vf_num = 0;
6298 	ctxt.uplink_seid = uplink_seid;
6299 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
6300 	if (ch->type == I40E_VSI_VMDQ2)
6301 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
6302 
6303 	if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
6304 		ctxt.info.valid_sections |=
6305 		     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6306 		ctxt.info.switch_id =
6307 		   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6308 	}
6309 
6310 	/* Set queue map for a given VSI context */
6311 	i40e_channel_setup_queue_map(pf, &ctxt, ch);
6312 
6313 	/* Now time to create VSI */
6314 	ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
6315 	if (ret) {
6316 		dev_info(&pf->pdev->dev,
6317 			 "add new vsi failed, err %pe aq_err %s\n",
6318 			 ERR_PTR(ret),
6319 			 i40e_aq_str(&pf->hw,
6320 				     pf->hw.aq.asq_last_status));
6321 		return -ENOENT;
6322 	}
6323 
6324 	/* Success, update channel, set enabled_tc only if the channel
6325 	 * is not a macvlan
6326 	 */
6327 	ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
6328 	ch->seid = ctxt.seid;
6329 	ch->vsi_number = ctxt.vsi_number;
6330 	ch->stat_counter_idx = le16_to_cpu(ctxt.info.stat_counter_idx);
6331 
6332 	/* copy just the sections touched not the entire info
6333 	 * since not all sections are valid as returned by
6334 	 * update vsi params
6335 	 */
6336 	ch->info.mapping_flags = ctxt.info.mapping_flags;
6337 	memcpy(&ch->info.queue_mapping,
6338 	       &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
6339 	memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
6340 	       sizeof(ctxt.info.tc_mapping));
6341 
6342 	return 0;
6343 }
6344 
6345 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
6346 				  u8 *bw_share)
6347 {
6348 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
6349 	int ret;
6350 	int i;
6351 
6352 	memset(&bw_data, 0, sizeof(bw_data));
6353 	bw_data.tc_valid_bits = ch->enabled_tc;
6354 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6355 		bw_data.tc_bw_credits[i] = bw_share[i];
6356 
6357 	ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
6358 				       &bw_data, NULL);
6359 	if (ret) {
6360 		dev_info(&vsi->back->pdev->dev,
6361 			 "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
6362 			 vsi->back->hw.aq.asq_last_status, ch->seid);
6363 		return -EINVAL;
6364 	}
6365 
6366 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6367 		ch->info.qs_handle[i] = bw_data.qs_handles[i];
6368 
6369 	return 0;
6370 }
6371 
6372 /**
6373  * i40e_channel_config_tx_ring - config TX ring associated with new channel
6374  * @pf: ptr to PF device
6375  * @vsi: the VSI being setup
6376  * @ch: ptr to channel structure
6377  *
6378  * Configure TX rings associated with channel (VSI) since queues are being
6379  * from parent VSI.
6380  **/
6381 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
6382 				       struct i40e_vsi *vsi,
6383 				       struct i40e_channel *ch)
6384 {
6385 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
6386 	int ret;
6387 	int i;
6388 
6389 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
6390 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6391 		if (ch->enabled_tc & BIT(i))
6392 			bw_share[i] = 1;
6393 	}
6394 
6395 	/* configure BW for new VSI */
6396 	ret = i40e_channel_config_bw(vsi, ch, bw_share);
6397 	if (ret) {
6398 		dev_info(&vsi->back->pdev->dev,
6399 			 "Failed configuring TC map %d for channel (seid %u)\n",
6400 			 ch->enabled_tc, ch->seid);
6401 		return ret;
6402 	}
6403 
6404 	for (i = 0; i < ch->num_queue_pairs; i++) {
6405 		struct i40e_ring *tx_ring, *rx_ring;
6406 		u16 pf_q;
6407 
6408 		pf_q = ch->base_queue + i;
6409 
6410 		/* Get to TX ring ptr of main VSI, for re-setup TX queue
6411 		 * context
6412 		 */
6413 		tx_ring = vsi->tx_rings[pf_q];
6414 		tx_ring->ch = ch;
6415 
6416 		/* Get the RX ring ptr */
6417 		rx_ring = vsi->rx_rings[pf_q];
6418 		rx_ring->ch = ch;
6419 	}
6420 
6421 	return 0;
6422 }
6423 
6424 /**
6425  * i40e_setup_hw_channel - setup new channel
6426  * @pf: ptr to PF device
6427  * @vsi: the VSI being setup
6428  * @ch: ptr to channel structure
6429  * @uplink_seid: underlying HW switching element (VEB) ID
6430  * @type: type of channel to be created (VMDq2/VF)
6431  *
6432  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6433  * and configures TX rings accordingly
6434  **/
6435 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
6436 					struct i40e_vsi *vsi,
6437 					struct i40e_channel *ch,
6438 					u16 uplink_seid, u8 type)
6439 {
6440 	int ret;
6441 
6442 	ch->initialized = false;
6443 	ch->base_queue = vsi->next_base_queue;
6444 	ch->type = type;
6445 
6446 	/* Proceed with creation of channel (VMDq2) VSI */
6447 	ret = i40e_add_channel(pf, uplink_seid, ch);
6448 	if (ret) {
6449 		dev_info(&pf->pdev->dev,
6450 			 "failed to add_channel using uplink_seid %u\n",
6451 			 uplink_seid);
6452 		return ret;
6453 	}
6454 
6455 	/* Mark the successful creation of channel */
6456 	ch->initialized = true;
6457 
6458 	/* Reconfigure TX queues using QTX_CTL register */
6459 	ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6460 	if (ret) {
6461 		dev_info(&pf->pdev->dev,
6462 			 "failed to configure TX rings for channel %u\n",
6463 			 ch->seid);
6464 		return ret;
6465 	}
6466 
6467 	/* update 'next_base_queue' */
6468 	vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6469 	dev_dbg(&pf->pdev->dev,
6470 		"Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6471 		ch->seid, ch->vsi_number, ch->stat_counter_idx,
6472 		ch->num_queue_pairs,
6473 		vsi->next_base_queue);
6474 	return ret;
6475 }
6476 
6477 /**
6478  * i40e_setup_channel - setup new channel using uplink element
6479  * @pf: ptr to PF device
6480  * @vsi: pointer to the VSI to set up the channel within
6481  * @ch: ptr to channel structure
6482  *
6483  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6484  * and uplink switching element (uplink_seid)
6485  **/
6486 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6487 			       struct i40e_channel *ch)
6488 {
6489 	struct i40e_vsi *main_vsi;
6490 	u8 vsi_type;
6491 	u16 seid;
6492 	int ret;
6493 
6494 	if (vsi->type == I40E_VSI_MAIN) {
6495 		vsi_type = I40E_VSI_VMDQ2;
6496 	} else {
6497 		dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6498 			vsi->type);
6499 		return false;
6500 	}
6501 
6502 	/* underlying switching element */
6503 	main_vsi = i40e_pf_get_main_vsi(pf);
6504 	seid = main_vsi->uplink_seid;
6505 
6506 	/* create channel (VSI), configure TX rings */
6507 	ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6508 	if (ret) {
6509 		dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6510 		return false;
6511 	}
6512 
6513 	return ch->initialized ? true : false;
6514 }
6515 
6516 /**
6517  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6518  * @vsi: ptr to VSI which has PF backing
6519  *
6520  * Sets up switch mode correctly if it needs to be changed and perform
6521  * what are allowed modes.
6522  **/
6523 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6524 {
6525 	u8 mode;
6526 	struct i40e_pf *pf = vsi->back;
6527 	struct i40e_hw *hw = &pf->hw;
6528 	int ret;
6529 
6530 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6531 	if (ret)
6532 		return -EINVAL;
6533 
6534 	if (hw->dev_caps.switch_mode) {
6535 		/* if switch mode is set, support mode2 (non-tunneled for
6536 		 * cloud filter) for now
6537 		 */
6538 		u32 switch_mode = hw->dev_caps.switch_mode &
6539 				  I40E_SWITCH_MODE_MASK;
6540 		if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6541 			if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6542 				return 0;
6543 			dev_err(&pf->pdev->dev,
6544 				"Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6545 				hw->dev_caps.switch_mode);
6546 			return -EINVAL;
6547 		}
6548 	}
6549 
6550 	/* Set Bit 7 to be valid */
6551 	mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6552 
6553 	/* Set L4type for TCP support */
6554 	mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6555 
6556 	/* Set cloud filter mode */
6557 	mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6558 
6559 	/* Prep mode field for set_switch_config */
6560 	ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6561 					pf->last_sw_conf_valid_flags,
6562 					mode, NULL);
6563 	if (ret && hw->aq.asq_last_status != I40E_AQ_RC_ESRCH)
6564 		dev_err(&pf->pdev->dev,
6565 			"couldn't set switch config bits, err %pe aq_err %s\n",
6566 			ERR_PTR(ret),
6567 			i40e_aq_str(hw,
6568 				    hw->aq.asq_last_status));
6569 
6570 	return ret;
6571 }
6572 
6573 /**
6574  * i40e_create_queue_channel - function to create channel
6575  * @vsi: VSI to be configured
6576  * @ch: ptr to channel (it contains channel specific params)
6577  *
6578  * This function creates channel (VSI) using num_queues specified by user,
6579  * reconfigs RSS if needed.
6580  **/
6581 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6582 			      struct i40e_channel *ch)
6583 {
6584 	struct i40e_pf *pf = vsi->back;
6585 	bool reconfig_rss;
6586 	int err;
6587 
6588 	if (!ch)
6589 		return -EINVAL;
6590 
6591 	if (!ch->num_queue_pairs) {
6592 		dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6593 			ch->num_queue_pairs);
6594 		return -EINVAL;
6595 	}
6596 
6597 	/* validate user requested num_queues for channel */
6598 	err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6599 				       &reconfig_rss);
6600 	if (err) {
6601 		dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6602 			 ch->num_queue_pairs);
6603 		return -EINVAL;
6604 	}
6605 
6606 	/* By default we are in VEPA mode, if this is the first VF/VMDq
6607 	 * VSI to be added switch to VEB mode.
6608 	 */
6609 
6610 	if (!test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
6611 		set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
6612 
6613 		if (vsi->type == I40E_VSI_MAIN) {
6614 			if (i40e_is_tc_mqprio_enabled(pf))
6615 				i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
6616 			else
6617 				i40e_do_reset_safe(pf, I40E_PF_RESET_FLAG);
6618 		}
6619 		/* now onwards for main VSI, number of queues will be value
6620 		 * of TC0's queue count
6621 		 */
6622 	}
6623 
6624 	/* By this time, vsi->cnt_q_avail shall be set to non-zero and
6625 	 * it should be more than num_queues
6626 	 */
6627 	if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6628 		dev_dbg(&pf->pdev->dev,
6629 			"Error: cnt_q_avail (%u) less than num_queues %d\n",
6630 			vsi->cnt_q_avail, ch->num_queue_pairs);
6631 		return -EINVAL;
6632 	}
6633 
6634 	/* reconfig_rss only if vsi type is MAIN_VSI */
6635 	if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6636 		err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6637 		if (err) {
6638 			dev_info(&pf->pdev->dev,
6639 				 "Error: unable to reconfig rss for num_queues (%u)\n",
6640 				 ch->num_queue_pairs);
6641 			return -EINVAL;
6642 		}
6643 	}
6644 
6645 	if (!i40e_setup_channel(pf, vsi, ch)) {
6646 		dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6647 		return -EINVAL;
6648 	}
6649 
6650 	dev_info(&pf->pdev->dev,
6651 		 "Setup channel (id:%u) utilizing num_queues %d\n",
6652 		 ch->seid, ch->num_queue_pairs);
6653 
6654 	/* configure VSI for BW limit */
6655 	if (ch->max_tx_rate) {
6656 		u64 credits = ch->max_tx_rate;
6657 
6658 		if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6659 			return -EINVAL;
6660 
6661 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
6662 		dev_dbg(&pf->pdev->dev,
6663 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6664 			ch->max_tx_rate,
6665 			credits,
6666 			ch->seid);
6667 	}
6668 
6669 	/* in case of VF, this will be main SRIOV VSI */
6670 	ch->parent_vsi = vsi;
6671 
6672 	/* and update main_vsi's count for queue_available to use */
6673 	vsi->cnt_q_avail -= ch->num_queue_pairs;
6674 
6675 	return 0;
6676 }
6677 
6678 /**
6679  * i40e_configure_queue_channels - Add queue channel for the given TCs
6680  * @vsi: VSI to be configured
6681  *
6682  * Configures queue channel mapping to the given TCs
6683  **/
6684 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6685 {
6686 	struct i40e_channel *ch;
6687 	u64 max_rate = 0;
6688 	int ret = 0, i;
6689 
6690 	/* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6691 	vsi->tc_seid_map[0] = vsi->seid;
6692 	for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6693 		if (vsi->tc_config.enabled_tc & BIT(i)) {
6694 			ch = kzalloc(sizeof(*ch), GFP_KERNEL);
6695 			if (!ch) {
6696 				ret = -ENOMEM;
6697 				goto err_free;
6698 			}
6699 
6700 			INIT_LIST_HEAD(&ch->list);
6701 			ch->num_queue_pairs =
6702 				vsi->tc_config.tc_info[i].qcount;
6703 			ch->base_queue =
6704 				vsi->tc_config.tc_info[i].qoffset;
6705 
6706 			/* Bandwidth limit through tc interface is in bytes/s,
6707 			 * change to Mbit/s
6708 			 */
6709 			max_rate = vsi->mqprio_qopt.max_rate[i];
6710 			do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6711 			ch->max_tx_rate = max_rate;
6712 
6713 			list_add_tail(&ch->list, &vsi->ch_list);
6714 
6715 			ret = i40e_create_queue_channel(vsi, ch);
6716 			if (ret) {
6717 				dev_err(&vsi->back->pdev->dev,
6718 					"Failed creating queue channel with TC%d: queues %d\n",
6719 					i, ch->num_queue_pairs);
6720 				goto err_free;
6721 			}
6722 			vsi->tc_seid_map[i] = ch->seid;
6723 		}
6724 	}
6725 
6726 	/* reset to reconfigure TX queue contexts */
6727 	i40e_do_reset(vsi->back, I40E_PF_RESET_FLAG, true);
6728 	return ret;
6729 
6730 err_free:
6731 	i40e_remove_queue_channels(vsi);
6732 	return ret;
6733 }
6734 
6735 /**
6736  * i40e_veb_config_tc - Configure TCs for given VEB
6737  * @veb: given VEB
6738  * @enabled_tc: TC bitmap
6739  *
6740  * Configures given TC bitmap for VEB (switching) element
6741  **/
6742 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6743 {
6744 	struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6745 	struct i40e_pf *pf = veb->pf;
6746 	int ret = 0;
6747 	int i;
6748 
6749 	/* No TCs or already enabled TCs just return */
6750 	if (!enabled_tc || veb->enabled_tc == enabled_tc)
6751 		return ret;
6752 
6753 	bw_data.tc_valid_bits = enabled_tc;
6754 	/* bw_data.absolute_credits is not set (relative) */
6755 
6756 	/* Enable ETS TCs with equal BW Share for now */
6757 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6758 		if (enabled_tc & BIT(i))
6759 			bw_data.tc_bw_share_credits[i] = 1;
6760 	}
6761 
6762 	ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6763 						   &bw_data, NULL);
6764 	if (ret) {
6765 		dev_info(&pf->pdev->dev,
6766 			 "VEB bw config failed, err %pe aq_err %s\n",
6767 			 ERR_PTR(ret),
6768 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6769 		goto out;
6770 	}
6771 
6772 	/* Update the BW information */
6773 	ret = i40e_veb_get_bw_info(veb);
6774 	if (ret) {
6775 		dev_info(&pf->pdev->dev,
6776 			 "Failed getting veb bw config, err %pe aq_err %s\n",
6777 			 ERR_PTR(ret),
6778 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6779 	}
6780 
6781 out:
6782 	return ret;
6783 }
6784 
6785 #ifdef CONFIG_I40E_DCB
6786 /**
6787  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6788  * @pf: PF struct
6789  *
6790  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6791  * the caller would've quiesce all the VSIs before calling
6792  * this function
6793  **/
6794 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6795 {
6796 	struct i40e_vsi *vsi;
6797 	struct i40e_veb *veb;
6798 	u8 tc_map = 0;
6799 	int ret;
6800 	int v;
6801 
6802 	/* Enable the TCs available on PF to all VEBs */
6803 	tc_map = i40e_pf_get_tc_map(pf);
6804 	if (tc_map == I40E_DEFAULT_TRAFFIC_CLASS)
6805 		return;
6806 
6807 	i40e_pf_for_each_veb(pf, v, veb) {
6808 		ret = i40e_veb_config_tc(veb, tc_map);
6809 		if (ret) {
6810 			dev_info(&pf->pdev->dev,
6811 				 "Failed configuring TC for VEB seid=%d\n",
6812 				 veb->seid);
6813 			/* Will try to configure as many components */
6814 		}
6815 	}
6816 
6817 	/* Update each VSI */
6818 	i40e_pf_for_each_vsi(pf, v, vsi) {
6819 		/* - Enable all TCs for the LAN VSI
6820 		 * - For all others keep them at TC0 for now
6821 		 */
6822 		if (vsi->type == I40E_VSI_MAIN)
6823 			tc_map = i40e_pf_get_tc_map(pf);
6824 		else
6825 			tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6826 
6827 		ret = i40e_vsi_config_tc(vsi, tc_map);
6828 		if (ret) {
6829 			dev_info(&pf->pdev->dev,
6830 				 "Failed configuring TC for VSI seid=%d\n",
6831 				 vsi->seid);
6832 			/* Will try to configure as many components */
6833 		} else {
6834 			/* Re-configure VSI vectors based on updated TC map */
6835 			i40e_vsi_map_rings_to_vectors(vsi);
6836 			if (vsi->netdev)
6837 				i40e_dcbnl_set_all(vsi);
6838 		}
6839 	}
6840 }
6841 
6842 /**
6843  * i40e_resume_port_tx - Resume port Tx
6844  * @pf: PF struct
6845  *
6846  * Resume a port's Tx and issue a PF reset in case of failure to
6847  * resume.
6848  **/
6849 static int i40e_resume_port_tx(struct i40e_pf *pf)
6850 {
6851 	struct i40e_hw *hw = &pf->hw;
6852 	int ret;
6853 
6854 	ret = i40e_aq_resume_port_tx(hw, NULL);
6855 	if (ret) {
6856 		dev_info(&pf->pdev->dev,
6857 			 "Resume Port Tx failed, err %pe aq_err %s\n",
6858 			  ERR_PTR(ret),
6859 			  i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6860 		/* Schedule PF reset to recover */
6861 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6862 		i40e_service_event_schedule(pf);
6863 	}
6864 
6865 	return ret;
6866 }
6867 
6868 /**
6869  * i40e_suspend_port_tx - Suspend port Tx
6870  * @pf: PF struct
6871  *
6872  * Suspend a port's Tx and issue a PF reset in case of failure.
6873  **/
6874 static int i40e_suspend_port_tx(struct i40e_pf *pf)
6875 {
6876 	struct i40e_hw *hw = &pf->hw;
6877 	int ret;
6878 
6879 	ret = i40e_aq_suspend_port_tx(hw, pf->mac_seid, NULL);
6880 	if (ret) {
6881 		dev_info(&pf->pdev->dev,
6882 			 "Suspend Port Tx failed, err %pe aq_err %s\n",
6883 			 ERR_PTR(ret),
6884 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6885 		/* Schedule PF reset to recover */
6886 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6887 		i40e_service_event_schedule(pf);
6888 	}
6889 
6890 	return ret;
6891 }
6892 
6893 /**
6894  * i40e_hw_set_dcb_config - Program new DCBX settings into HW
6895  * @pf: PF being configured
6896  * @new_cfg: New DCBX configuration
6897  *
6898  * Program DCB settings into HW and reconfigure VEB/VSIs on
6899  * given PF. Uses "Set LLDP MIB" AQC to program the hardware.
6900  **/
6901 static int i40e_hw_set_dcb_config(struct i40e_pf *pf,
6902 				  struct i40e_dcbx_config *new_cfg)
6903 {
6904 	struct i40e_dcbx_config *old_cfg = &pf->hw.local_dcbx_config;
6905 	int ret;
6906 
6907 	/* Check if need reconfiguration */
6908 	if (!memcmp(&new_cfg, &old_cfg, sizeof(new_cfg))) {
6909 		dev_dbg(&pf->pdev->dev, "No Change in DCB Config required.\n");
6910 		return 0;
6911 	}
6912 
6913 	/* Config change disable all VSIs */
6914 	i40e_pf_quiesce_all_vsi(pf);
6915 
6916 	/* Copy the new config to the current config */
6917 	*old_cfg = *new_cfg;
6918 	old_cfg->etsrec = old_cfg->etscfg;
6919 	ret = i40e_set_dcb_config(&pf->hw);
6920 	if (ret) {
6921 		dev_info(&pf->pdev->dev,
6922 			 "Set DCB Config failed, err %pe aq_err %s\n",
6923 			 ERR_PTR(ret),
6924 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6925 		goto out;
6926 	}
6927 
6928 	/* Changes in configuration update VEB/VSI */
6929 	i40e_dcb_reconfigure(pf);
6930 out:
6931 	/* In case of reset do not try to resume anything */
6932 	if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
6933 		/* Re-start the VSIs if disabled */
6934 		ret = i40e_resume_port_tx(pf);
6935 		/* In case of error no point in resuming VSIs */
6936 		if (ret)
6937 			goto err;
6938 		i40e_pf_unquiesce_all_vsi(pf);
6939 	}
6940 err:
6941 	return ret;
6942 }
6943 
6944 /**
6945  * i40e_hw_dcb_config - Program new DCBX settings into HW
6946  * @pf: PF being configured
6947  * @new_cfg: New DCBX configuration
6948  *
6949  * Program DCB settings into HW and reconfigure VEB/VSIs on
6950  * given PF
6951  **/
6952 int i40e_hw_dcb_config(struct i40e_pf *pf, struct i40e_dcbx_config *new_cfg)
6953 {
6954 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6955 	u8 prio_type[I40E_MAX_TRAFFIC_CLASS] = {0};
6956 	u32 mfs_tc[I40E_MAX_TRAFFIC_CLASS];
6957 	struct i40e_dcbx_config *old_cfg;
6958 	u8 mode[I40E_MAX_TRAFFIC_CLASS];
6959 	struct i40e_rx_pb_config pb_cfg;
6960 	struct i40e_hw *hw = &pf->hw;
6961 	u8 num_ports = hw->num_ports;
6962 	bool need_reconfig;
6963 	int ret = -EINVAL;
6964 	u8 lltc_map = 0;
6965 	u8 tc_map = 0;
6966 	u8 new_numtc;
6967 	u8 i;
6968 
6969 	dev_dbg(&pf->pdev->dev, "Configuring DCB registers directly\n");
6970 	/* Un-pack information to Program ETS HW via shared API
6971 	 * numtc, tcmap
6972 	 * LLTC map
6973 	 * ETS/NON-ETS arbiter mode
6974 	 * max exponent (credit refills)
6975 	 * Total number of ports
6976 	 * PFC priority bit-map
6977 	 * Priority Table
6978 	 * BW % per TC
6979 	 * Arbiter mode between UPs sharing same TC
6980 	 * TSA table (ETS or non-ETS)
6981 	 * EEE enabled or not
6982 	 * MFS TC table
6983 	 */
6984 
6985 	new_numtc = i40e_dcb_get_num_tc(new_cfg);
6986 
6987 	memset(&ets_data, 0, sizeof(ets_data));
6988 	for (i = 0; i < new_numtc; i++) {
6989 		tc_map |= BIT(i);
6990 		switch (new_cfg->etscfg.tsatable[i]) {
6991 		case I40E_IEEE_TSA_ETS:
6992 			prio_type[i] = I40E_DCB_PRIO_TYPE_ETS;
6993 			ets_data.tc_bw_share_credits[i] =
6994 					new_cfg->etscfg.tcbwtable[i];
6995 			break;
6996 		case I40E_IEEE_TSA_STRICT:
6997 			prio_type[i] = I40E_DCB_PRIO_TYPE_STRICT;
6998 			lltc_map |= BIT(i);
6999 			ets_data.tc_bw_share_credits[i] =
7000 					I40E_DCB_STRICT_PRIO_CREDITS;
7001 			break;
7002 		default:
7003 			/* Invalid TSA type */
7004 			need_reconfig = false;
7005 			goto out;
7006 		}
7007 	}
7008 
7009 	old_cfg = &hw->local_dcbx_config;
7010 	/* Check if need reconfiguration */
7011 	need_reconfig = i40e_dcb_need_reconfig(pf, old_cfg, new_cfg);
7012 
7013 	/* If needed, enable/disable frame tagging, disable all VSIs
7014 	 * and suspend port tx
7015 	 */
7016 	if (need_reconfig) {
7017 		/* Enable DCB tagging only when more than one TC */
7018 		if (new_numtc > 1)
7019 			set_bit(I40E_FLAG_DCB_ENA, pf->flags);
7020 		else
7021 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7022 
7023 		set_bit(__I40E_PORT_SUSPENDED, pf->state);
7024 		/* Reconfiguration needed quiesce all VSIs */
7025 		i40e_pf_quiesce_all_vsi(pf);
7026 		ret = i40e_suspend_port_tx(pf);
7027 		if (ret)
7028 			goto err;
7029 	}
7030 
7031 	/* Configure Port ETS Tx Scheduler */
7032 	ets_data.tc_valid_bits = tc_map;
7033 	ets_data.tc_strict_priority_flags = lltc_map;
7034 	ret = i40e_aq_config_switch_comp_ets
7035 		(hw, pf->mac_seid, &ets_data,
7036 		 i40e_aqc_opc_modify_switching_comp_ets, NULL);
7037 	if (ret) {
7038 		dev_info(&pf->pdev->dev,
7039 			 "Modify Port ETS failed, err %pe aq_err %s\n",
7040 			 ERR_PTR(ret),
7041 			 i40e_aq_str(&pf->hw, 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),
7081 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7082 		goto out;
7083 	}
7084 
7085 	/* Update the port DCBx configuration */
7086 	*old_cfg = *new_cfg;
7087 
7088 	/* Changes in configuration update VEB/VSI */
7089 	i40e_dcb_reconfigure(pf);
7090 out:
7091 	/* Re-start the VSIs if disabled */
7092 	if (need_reconfig) {
7093 		ret = i40e_resume_port_tx(pf);
7094 
7095 		clear_bit(__I40E_PORT_SUSPENDED, pf->state);
7096 		/* In case of error no point in resuming VSIs */
7097 		if (ret)
7098 			goto err;
7099 
7100 		/* Wait for the PF's queues to be disabled */
7101 		ret = i40e_pf_wait_queues_disabled(pf);
7102 		if (ret) {
7103 			/* Schedule PF reset to recover */
7104 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
7105 			i40e_service_event_schedule(pf);
7106 			goto err;
7107 		} else {
7108 			i40e_pf_unquiesce_all_vsi(pf);
7109 			set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7110 			set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
7111 		}
7112 		/* registers are set, lets apply */
7113 		if (test_bit(I40E_HW_CAP_USE_SET_LLDP_MIB, pf->hw.caps))
7114 			ret = i40e_hw_set_dcb_config(pf, new_cfg);
7115 	}
7116 
7117 err:
7118 	return ret;
7119 }
7120 
7121 /**
7122  * i40e_dcb_sw_default_config - Set default DCB configuration when DCB in SW
7123  * @pf: PF being queried
7124  *
7125  * Set default DCB configuration in case DCB is to be done in SW.
7126  **/
7127 int i40e_dcb_sw_default_config(struct i40e_pf *pf)
7128 {
7129 	struct i40e_dcbx_config *dcb_cfg = &pf->hw.local_dcbx_config;
7130 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
7131 	struct i40e_hw *hw = &pf->hw;
7132 	int err;
7133 
7134 	if (test_bit(I40E_HW_CAP_USE_SET_LLDP_MIB, pf->hw.caps)) {
7135 		/* Update the local cached instance with TC0 ETS */
7136 		memset(&pf->tmp_cfg, 0, sizeof(struct i40e_dcbx_config));
7137 		pf->tmp_cfg.etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7138 		pf->tmp_cfg.etscfg.maxtcs = 0;
7139 		pf->tmp_cfg.etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7140 		pf->tmp_cfg.etscfg.tsatable[0] = I40E_IEEE_TSA_ETS;
7141 		pf->tmp_cfg.pfc.willing = I40E_IEEE_DEFAULT_PFC_WILLING;
7142 		pf->tmp_cfg.pfc.pfccap = I40E_MAX_TRAFFIC_CLASS;
7143 		/* FW needs one App to configure HW */
7144 		pf->tmp_cfg.numapps = I40E_IEEE_DEFAULT_NUM_APPS;
7145 		pf->tmp_cfg.app[0].selector = I40E_APP_SEL_ETHTYPE;
7146 		pf->tmp_cfg.app[0].priority = I40E_IEEE_DEFAULT_APP_PRIO;
7147 		pf->tmp_cfg.app[0].protocolid = I40E_APP_PROTOID_FCOE;
7148 
7149 		return i40e_hw_set_dcb_config(pf, &pf->tmp_cfg);
7150 	}
7151 
7152 	memset(&ets_data, 0, sizeof(ets_data));
7153 	ets_data.tc_valid_bits = I40E_DEFAULT_TRAFFIC_CLASS; /* TC0 only */
7154 	ets_data.tc_strict_priority_flags = 0; /* ETS */
7155 	ets_data.tc_bw_share_credits[0] = I40E_IEEE_DEFAULT_ETS_TCBW; /* 100% to TC0 */
7156 
7157 	/* Enable ETS on the Physical port */
7158 	err = i40e_aq_config_switch_comp_ets
7159 		(hw, pf->mac_seid, &ets_data,
7160 		 i40e_aqc_opc_enable_switching_comp_ets, NULL);
7161 	if (err) {
7162 		dev_info(&pf->pdev->dev,
7163 			 "Enable Port ETS failed, err %pe aq_err %s\n",
7164 			 ERR_PTR(err),
7165 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7166 		err = -ENOENT;
7167 		goto out;
7168 	}
7169 
7170 	/* Update the local cached instance with TC0 ETS */
7171 	dcb_cfg->etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7172 	dcb_cfg->etscfg.cbs = 0;
7173 	dcb_cfg->etscfg.maxtcs = I40E_MAX_TRAFFIC_CLASS;
7174 	dcb_cfg->etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7175 
7176 out:
7177 	return err;
7178 }
7179 
7180 /**
7181  * i40e_init_pf_dcb - Initialize DCB configuration
7182  * @pf: PF being configured
7183  *
7184  * Query the current DCB configuration and cache it
7185  * in the hardware structure
7186  **/
7187 static int i40e_init_pf_dcb(struct i40e_pf *pf)
7188 {
7189 	struct i40e_hw *hw = &pf->hw;
7190 	int err;
7191 
7192 	/* Do not enable DCB for SW1 and SW2 images even if the FW is capable
7193 	 * Also do not enable DCBx if FW LLDP agent is disabled
7194 	 */
7195 	if (test_bit(I40E_HW_CAP_NO_DCB_SUPPORT, pf->hw.caps)) {
7196 		dev_info(&pf->pdev->dev, "DCB is not supported.\n");
7197 		err = -EOPNOTSUPP;
7198 		goto out;
7199 	}
7200 	if (test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags)) {
7201 		dev_info(&pf->pdev->dev, "FW LLDP is disabled, attempting SW DCB\n");
7202 		err = i40e_dcb_sw_default_config(pf);
7203 		if (err) {
7204 			dev_info(&pf->pdev->dev, "Could not initialize SW DCB\n");
7205 			goto out;
7206 		}
7207 		dev_info(&pf->pdev->dev, "SW DCB initialization succeeded.\n");
7208 		pf->dcbx_cap = DCB_CAP_DCBX_HOST |
7209 			       DCB_CAP_DCBX_VER_IEEE;
7210 		/* at init capable but disabled */
7211 		set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
7212 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7213 		goto out;
7214 	}
7215 	err = i40e_init_dcb(hw, true);
7216 	if (!err) {
7217 		/* Device/Function is not DCBX capable */
7218 		if ((!hw->func_caps.dcb) ||
7219 		    (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
7220 			dev_info(&pf->pdev->dev,
7221 				 "DCBX offload is not supported or is disabled for this PF.\n");
7222 		} else {
7223 			/* When status is not DISABLED then DCBX in FW */
7224 			pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
7225 				       DCB_CAP_DCBX_VER_IEEE;
7226 
7227 			set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
7228 			/* Enable DCB tagging only when more than one TC
7229 			 * or explicitly disable if only one TC
7230 			 */
7231 			if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
7232 				set_bit(I40E_FLAG_DCB_ENA, pf->flags);
7233 			else
7234 				clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7235 			dev_dbg(&pf->pdev->dev,
7236 				"DCBX offload is supported for this PF.\n");
7237 		}
7238 	} else if (pf->hw.aq.asq_last_status == I40E_AQ_RC_EPERM) {
7239 		dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
7240 		set_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags);
7241 	} else {
7242 		dev_info(&pf->pdev->dev,
7243 			 "Query for DCB configuration failed, err %pe aq_err %s\n",
7244 			 ERR_PTR(err),
7245 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7246 	}
7247 
7248 out:
7249 	return err;
7250 }
7251 #endif /* CONFIG_I40E_DCB */
7252 
7253 static void i40e_print_link_message_eee(struct i40e_vsi *vsi,
7254 					const char *speed, const char *fc)
7255 {
7256 	struct ethtool_keee kedata;
7257 
7258 	memzero_explicit(&kedata, sizeof(kedata));
7259 	if (vsi->netdev->ethtool_ops->get_eee)
7260 		vsi->netdev->ethtool_ops->get_eee(vsi->netdev, &kedata);
7261 
7262 	if (!linkmode_empty(kedata.supported))
7263 		netdev_info(vsi->netdev,
7264 			    "NIC Link is Up, %sbps Full Duplex, Flow Control: %s, EEE: %s\n",
7265 			    speed, fc,
7266 			    kedata.eee_enabled ? "Enabled" : "Disabled");
7267 	else
7268 		netdev_info(vsi->netdev,
7269 			    "NIC Link is Up, %sbps Full Duplex, Flow Control: %s\n",
7270 			    speed, fc);
7271 }
7272 
7273 /**
7274  * i40e_print_link_message - print link up or down
7275  * @vsi: the VSI for which link needs a message
7276  * @isup: true of link is up, false otherwise
7277  */
7278 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
7279 {
7280 	enum i40e_aq_link_speed new_speed;
7281 	struct i40e_pf *pf = vsi->back;
7282 	char *speed = "Unknown";
7283 	char *fc = "Unknown";
7284 	char *fec = "";
7285 	char *req_fec = "";
7286 	char *an = "";
7287 
7288 	if (isup)
7289 		new_speed = pf->hw.phy.link_info.link_speed;
7290 	else
7291 		new_speed = I40E_LINK_SPEED_UNKNOWN;
7292 
7293 	if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
7294 		return;
7295 	vsi->current_isup = isup;
7296 	vsi->current_speed = new_speed;
7297 	if (!isup) {
7298 		netdev_info(vsi->netdev, "NIC Link is Down\n");
7299 		return;
7300 	}
7301 
7302 	/* Warn user if link speed on NPAR enabled partition is not at
7303 	 * least 10GB
7304 	 */
7305 	if (pf->hw.func_caps.npar_enable &&
7306 	    (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
7307 	     pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
7308 		netdev_warn(vsi->netdev,
7309 			    "The partition detected link speed that is less than 10Gbps\n");
7310 
7311 	switch (pf->hw.phy.link_info.link_speed) {
7312 	case I40E_LINK_SPEED_40GB:
7313 		speed = "40 G";
7314 		break;
7315 	case I40E_LINK_SPEED_20GB:
7316 		speed = "20 G";
7317 		break;
7318 	case I40E_LINK_SPEED_25GB:
7319 		speed = "25 G";
7320 		break;
7321 	case I40E_LINK_SPEED_10GB:
7322 		speed = "10 G";
7323 		break;
7324 	case I40E_LINK_SPEED_5GB:
7325 		speed = "5 G";
7326 		break;
7327 	case I40E_LINK_SPEED_2_5GB:
7328 		speed = "2.5 G";
7329 		break;
7330 	case I40E_LINK_SPEED_1GB:
7331 		speed = "1000 M";
7332 		break;
7333 	case I40E_LINK_SPEED_100MB:
7334 		speed = "100 M";
7335 		break;
7336 	default:
7337 		break;
7338 	}
7339 
7340 	switch (pf->hw.fc.current_mode) {
7341 	case I40E_FC_FULL:
7342 		fc = "RX/TX";
7343 		break;
7344 	case I40E_FC_TX_PAUSE:
7345 		fc = "TX";
7346 		break;
7347 	case I40E_FC_RX_PAUSE:
7348 		fc = "RX";
7349 		break;
7350 	default:
7351 		fc = "None";
7352 		break;
7353 	}
7354 
7355 	if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
7356 		req_fec = "None";
7357 		fec = "None";
7358 		an = "False";
7359 
7360 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7361 			an = "True";
7362 
7363 		if (pf->hw.phy.link_info.fec_info &
7364 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7365 			fec = "CL74 FC-FEC/BASE-R";
7366 		else if (pf->hw.phy.link_info.fec_info &
7367 			 I40E_AQ_CONFIG_FEC_RS_ENA)
7368 			fec = "CL108 RS-FEC";
7369 
7370 		/* 'CL108 RS-FEC' should be displayed when RS is requested, or
7371 		 * both RS and FC are requested
7372 		 */
7373 		if (vsi->back->hw.phy.link_info.req_fec_info &
7374 		    (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
7375 			if (vsi->back->hw.phy.link_info.req_fec_info &
7376 			    I40E_AQ_REQUEST_FEC_RS)
7377 				req_fec = "CL108 RS-FEC";
7378 			else
7379 				req_fec = "CL74 FC-FEC/BASE-R";
7380 		}
7381 		netdev_info(vsi->netdev,
7382 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7383 			    speed, req_fec, fec, an, fc);
7384 	} else if (pf->hw.device_id == I40E_DEV_ID_KX_X722) {
7385 		req_fec = "None";
7386 		fec = "None";
7387 		an = "False";
7388 
7389 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7390 			an = "True";
7391 
7392 		if (pf->hw.phy.link_info.fec_info &
7393 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7394 			fec = "CL74 FC-FEC/BASE-R";
7395 
7396 		if (pf->hw.phy.link_info.req_fec_info &
7397 		    I40E_AQ_REQUEST_FEC_KR)
7398 			req_fec = "CL74 FC-FEC/BASE-R";
7399 
7400 		netdev_info(vsi->netdev,
7401 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7402 			    speed, req_fec, fec, an, fc);
7403 	} else {
7404 		i40e_print_link_message_eee(vsi, speed, fc);
7405 	}
7406 
7407 }
7408 
7409 /**
7410  * i40e_up_complete - Finish the last steps of bringing up a connection
7411  * @vsi: the VSI being configured
7412  **/
7413 static int i40e_up_complete(struct i40e_vsi *vsi)
7414 {
7415 	struct i40e_pf *pf = vsi->back;
7416 	int err;
7417 
7418 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
7419 		i40e_vsi_configure_msix(vsi);
7420 	else
7421 		i40e_configure_msi_and_legacy(vsi);
7422 
7423 	/* start rings */
7424 	err = i40e_vsi_start_rings(vsi);
7425 	if (err)
7426 		return err;
7427 
7428 	clear_bit(__I40E_VSI_DOWN, vsi->state);
7429 	i40e_napi_enable_all(vsi);
7430 	i40e_vsi_enable_irq(vsi);
7431 
7432 	if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
7433 	    (vsi->netdev)) {
7434 		i40e_print_link_message(vsi, true);
7435 		netif_tx_start_all_queues(vsi->netdev);
7436 		netif_carrier_on(vsi->netdev);
7437 	}
7438 
7439 	/* replay FDIR SB filters */
7440 	if (vsi->type == I40E_VSI_FDIR) {
7441 		/* reset fd counters */
7442 		pf->fd_add_err = 0;
7443 		pf->fd_atr_cnt = 0;
7444 		i40e_fdir_filter_restore(vsi);
7445 	}
7446 
7447 	/* On the next run of the service_task, notify any clients of the new
7448 	 * opened netdev
7449 	 */
7450 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7451 	i40e_service_event_schedule(pf);
7452 
7453 	return 0;
7454 }
7455 
7456 /**
7457  * i40e_vsi_reinit_locked - Reset the VSI
7458  * @vsi: the VSI being configured
7459  *
7460  * Rebuild the ring structs after some configuration
7461  * has changed, e.g. MTU size.
7462  **/
7463 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
7464 {
7465 	struct i40e_pf *pf = vsi->back;
7466 
7467 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
7468 		usleep_range(1000, 2000);
7469 	i40e_down(vsi);
7470 
7471 	i40e_up(vsi);
7472 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
7473 }
7474 
7475 /**
7476  * i40e_force_link_state - Force the link status
7477  * @pf: board private structure
7478  * @is_up: whether the link state should be forced up or down
7479  **/
7480 static int i40e_force_link_state(struct i40e_pf *pf, bool is_up)
7481 {
7482 	struct i40e_aq_get_phy_abilities_resp abilities;
7483 	struct i40e_aq_set_phy_config config = {0};
7484 	bool non_zero_phy_type = is_up;
7485 	struct i40e_hw *hw = &pf->hw;
7486 	u64 mask;
7487 	u8 speed;
7488 	int err;
7489 
7490 	/* Card might've been put in an unstable state by other drivers
7491 	 * and applications, which causes incorrect speed values being
7492 	 * set on startup. In order to clear speed registers, we call
7493 	 * get_phy_capabilities twice, once to get initial state of
7494 	 * available speeds, and once to get current PHY config.
7495 	 */
7496 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
7497 					   NULL);
7498 	if (err) {
7499 		dev_err(&pf->pdev->dev,
7500 			"failed to get phy cap., ret =  %pe last_status =  %s\n",
7501 			ERR_PTR(err),
7502 			i40e_aq_str(hw, hw->aq.asq_last_status));
7503 		return err;
7504 	}
7505 	speed = abilities.link_speed;
7506 
7507 	/* Get the current phy config */
7508 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
7509 					   NULL);
7510 	if (err) {
7511 		dev_err(&pf->pdev->dev,
7512 			"failed to get phy cap., ret =  %pe last_status =  %s\n",
7513 			ERR_PTR(err),
7514 			i40e_aq_str(hw, hw->aq.asq_last_status));
7515 		return err;
7516 	}
7517 
7518 	/* If link needs to go up, but was not forced to go down,
7519 	 * and its speed values are OK, no need for a flap
7520 	 * if non_zero_phy_type was set, still need to force up
7521 	 */
7522 	if (test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags))
7523 		non_zero_phy_type = true;
7524 	else if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
7525 		return 0;
7526 
7527 	/* To force link we need to set bits for all supported PHY types,
7528 	 * but there are now more than 32, so we need to split the bitmap
7529 	 * across two fields.
7530 	 */
7531 	mask = I40E_PHY_TYPES_BITMASK;
7532 	config.phy_type =
7533 		non_zero_phy_type ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
7534 	config.phy_type_ext =
7535 		non_zero_phy_type ? (u8)((mask >> 32) & 0xff) : 0;
7536 	/* Copy the old settings, except of phy_type */
7537 	config.abilities = abilities.abilities;
7538 	if (test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags)) {
7539 		if (is_up)
7540 			config.abilities |= I40E_AQ_PHY_ENABLE_LINK;
7541 		else
7542 			config.abilities &= ~(I40E_AQ_PHY_ENABLE_LINK);
7543 	}
7544 	if (abilities.link_speed != 0)
7545 		config.link_speed = abilities.link_speed;
7546 	else
7547 		config.link_speed = speed;
7548 	config.eee_capability = abilities.eee_capability;
7549 	config.eeer = abilities.eeer_val;
7550 	config.low_power_ctrl = abilities.d3_lpan;
7551 	config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
7552 			    I40E_AQ_PHY_FEC_CONFIG_MASK;
7553 	err = i40e_aq_set_phy_config(hw, &config, NULL);
7554 
7555 	if (err) {
7556 		dev_err(&pf->pdev->dev,
7557 			"set phy config ret =  %pe last_status =  %s\n",
7558 			ERR_PTR(err),
7559 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7560 		return err;
7561 	}
7562 
7563 	/* Update the link info */
7564 	err = i40e_update_link_info(hw);
7565 	if (err) {
7566 		/* Wait a little bit (on 40G cards it sometimes takes a really
7567 		 * long time for link to come back from the atomic reset)
7568 		 * and try once more
7569 		 */
7570 		msleep(1000);
7571 		i40e_update_link_info(hw);
7572 	}
7573 
7574 	i40e_aq_set_link_restart_an(hw, is_up, NULL);
7575 
7576 	return 0;
7577 }
7578 
7579 /**
7580  * i40e_up - Bring the connection back up after being down
7581  * @vsi: the VSI being configured
7582  **/
7583 int i40e_up(struct i40e_vsi *vsi)
7584 {
7585 	int err;
7586 
7587 	if (vsi->type == I40E_VSI_MAIN &&
7588 	    (test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags) ||
7589 	     test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, vsi->back->flags)))
7590 		i40e_force_link_state(vsi->back, true);
7591 
7592 	err = i40e_vsi_configure(vsi);
7593 	if (!err)
7594 		err = i40e_up_complete(vsi);
7595 
7596 	return err;
7597 }
7598 
7599 /**
7600  * i40e_down - Shutdown the connection processing
7601  * @vsi: the VSI being stopped
7602  **/
7603 void i40e_down(struct i40e_vsi *vsi)
7604 {
7605 	int i;
7606 
7607 	/* It is assumed that the caller of this function
7608 	 * sets the vsi->state __I40E_VSI_DOWN bit.
7609 	 */
7610 	if (vsi->netdev) {
7611 		netif_carrier_off(vsi->netdev);
7612 		netif_tx_disable(vsi->netdev);
7613 	}
7614 	i40e_vsi_disable_irq(vsi);
7615 	i40e_vsi_stop_rings(vsi);
7616 	if (vsi->type == I40E_VSI_MAIN &&
7617 	   (test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags) ||
7618 	    test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, vsi->back->flags)))
7619 		i40e_force_link_state(vsi->back, false);
7620 	i40e_napi_disable_all(vsi);
7621 
7622 	for (i = 0; i < vsi->num_queue_pairs; i++) {
7623 		i40e_clean_tx_ring(vsi->tx_rings[i]);
7624 		if (i40e_enabled_xdp_vsi(vsi)) {
7625 			/* Make sure that in-progress ndo_xdp_xmit and
7626 			 * ndo_xsk_wakeup calls are completed.
7627 			 */
7628 			synchronize_rcu();
7629 			i40e_clean_tx_ring(vsi->xdp_rings[i]);
7630 		}
7631 		i40e_clean_rx_ring(vsi->rx_rings[i]);
7632 	}
7633 
7634 }
7635 
7636 /**
7637  * i40e_validate_mqprio_qopt- validate queue mapping info
7638  * @vsi: the VSI being configured
7639  * @mqprio_qopt: queue parametrs
7640  **/
7641 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
7642 				     struct tc_mqprio_qopt_offload *mqprio_qopt)
7643 {
7644 	u64 sum_max_rate = 0;
7645 	u64 max_rate = 0;
7646 	int i;
7647 
7648 	if (mqprio_qopt->qopt.offset[0] != 0 ||
7649 	    mqprio_qopt->qopt.num_tc < 1 ||
7650 	    mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
7651 		return -EINVAL;
7652 	for (i = 0; ; i++) {
7653 		if (!mqprio_qopt->qopt.count[i])
7654 			return -EINVAL;
7655 		if (mqprio_qopt->min_rate[i]) {
7656 			dev_err(&vsi->back->pdev->dev,
7657 				"Invalid min tx rate (greater than 0) specified\n");
7658 			return -EINVAL;
7659 		}
7660 		max_rate = mqprio_qopt->max_rate[i];
7661 		do_div(max_rate, I40E_BW_MBPS_DIVISOR);
7662 		sum_max_rate += max_rate;
7663 
7664 		if (i >= mqprio_qopt->qopt.num_tc - 1)
7665 			break;
7666 		if (mqprio_qopt->qopt.offset[i + 1] !=
7667 		    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7668 			return -EINVAL;
7669 	}
7670 	if (vsi->num_queue_pairs <
7671 	    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
7672 		dev_err(&vsi->back->pdev->dev,
7673 			"Failed to create traffic channel, insufficient number of queues.\n");
7674 		return -EINVAL;
7675 	}
7676 	if (sum_max_rate > i40e_get_link_speed(vsi)) {
7677 		dev_err(&vsi->back->pdev->dev,
7678 			"Invalid max tx rate specified\n");
7679 		return -EINVAL;
7680 	}
7681 	return 0;
7682 }
7683 
7684 /**
7685  * i40e_vsi_set_default_tc_config - set default values for tc configuration
7686  * @vsi: the VSI being configured
7687  **/
7688 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
7689 {
7690 	u16 qcount;
7691 	int i;
7692 
7693 	/* Only TC0 is enabled */
7694 	vsi->tc_config.numtc = 1;
7695 	vsi->tc_config.enabled_tc = 1;
7696 	qcount = min_t(int, vsi->alloc_queue_pairs,
7697 		       i40e_pf_get_max_q_per_tc(vsi->back));
7698 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7699 		/* For the TC that is not enabled set the offset to default
7700 		 * queue and allocate one queue for the given TC.
7701 		 */
7702 		vsi->tc_config.tc_info[i].qoffset = 0;
7703 		if (i == 0)
7704 			vsi->tc_config.tc_info[i].qcount = qcount;
7705 		else
7706 			vsi->tc_config.tc_info[i].qcount = 1;
7707 		vsi->tc_config.tc_info[i].netdev_tc = 0;
7708 	}
7709 }
7710 
7711 /**
7712  * i40e_del_macvlan_filter
7713  * @hw: pointer to the HW structure
7714  * @seid: seid of the channel VSI
7715  * @macaddr: the mac address to apply as a filter
7716  * @aq_err: store the admin Q error
7717  *
7718  * This function deletes a mac filter on the channel VSI which serves as the
7719  * macvlan. Returns 0 on success.
7720  **/
7721 static int i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
7722 				   const u8 *macaddr, int *aq_err)
7723 {
7724 	struct i40e_aqc_remove_macvlan_element_data element;
7725 	int status;
7726 
7727 	memset(&element, 0, sizeof(element));
7728 	ether_addr_copy(element.mac_addr, macaddr);
7729 	element.vlan_tag = 0;
7730 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
7731 	status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
7732 	*aq_err = hw->aq.asq_last_status;
7733 
7734 	return status;
7735 }
7736 
7737 /**
7738  * i40e_add_macvlan_filter
7739  * @hw: pointer to the HW structure
7740  * @seid: seid of the channel VSI
7741  * @macaddr: the mac address to apply as a filter
7742  * @aq_err: store the admin Q error
7743  *
7744  * This function adds a mac filter on the channel VSI which serves as the
7745  * macvlan. Returns 0 on success.
7746  **/
7747 static int i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
7748 				   const u8 *macaddr, int *aq_err)
7749 {
7750 	struct i40e_aqc_add_macvlan_element_data element;
7751 	u16 cmd_flags = 0;
7752 	int status;
7753 
7754 	ether_addr_copy(element.mac_addr, macaddr);
7755 	element.vlan_tag = 0;
7756 	element.queue_number = 0;
7757 	element.match_method = I40E_AQC_MM_ERR_NO_RES;
7758 	cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
7759 	element.flags = cpu_to_le16(cmd_flags);
7760 	status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
7761 	*aq_err = hw->aq.asq_last_status;
7762 
7763 	return status;
7764 }
7765 
7766 /**
7767  * i40e_reset_ch_rings - Reset the queue contexts in a channel
7768  * @vsi: the VSI we want to access
7769  * @ch: the channel we want to access
7770  */
7771 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
7772 {
7773 	struct i40e_ring *tx_ring, *rx_ring;
7774 	u16 pf_q;
7775 	int i;
7776 
7777 	for (i = 0; i < ch->num_queue_pairs; i++) {
7778 		pf_q = ch->base_queue + i;
7779 		tx_ring = vsi->tx_rings[pf_q];
7780 		tx_ring->ch = NULL;
7781 		rx_ring = vsi->rx_rings[pf_q];
7782 		rx_ring->ch = NULL;
7783 	}
7784 }
7785 
7786 /**
7787  * i40e_free_macvlan_channels
7788  * @vsi: the VSI we want to access
7789  *
7790  * This function frees the Qs of the channel VSI from
7791  * the stack and also deletes the channel VSIs which
7792  * serve as macvlans.
7793  */
7794 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
7795 {
7796 	struct i40e_channel *ch, *ch_tmp;
7797 	int ret;
7798 
7799 	if (list_empty(&vsi->macvlan_list))
7800 		return;
7801 
7802 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7803 		struct i40e_vsi *parent_vsi;
7804 
7805 		if (i40e_is_channel_macvlan(ch)) {
7806 			i40e_reset_ch_rings(vsi, ch);
7807 			clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7808 			netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
7809 			netdev_set_sb_channel(ch->fwd->netdev, 0);
7810 			kfree(ch->fwd);
7811 			ch->fwd = NULL;
7812 		}
7813 
7814 		list_del(&ch->list);
7815 		parent_vsi = ch->parent_vsi;
7816 		if (!parent_vsi || !ch->initialized) {
7817 			kfree(ch);
7818 			continue;
7819 		}
7820 
7821 		/* remove the VSI */
7822 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
7823 					     NULL);
7824 		if (ret)
7825 			dev_err(&vsi->back->pdev->dev,
7826 				"unable to remove channel (%d) for parent VSI(%d)\n",
7827 				ch->seid, parent_vsi->seid);
7828 		kfree(ch);
7829 	}
7830 	vsi->macvlan_cnt = 0;
7831 }
7832 
7833 /**
7834  * i40e_fwd_ring_up - bring the macvlan device up
7835  * @vsi: the VSI we want to access
7836  * @vdev: macvlan netdevice
7837  * @fwd: the private fwd structure
7838  */
7839 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7840 			    struct i40e_fwd_adapter *fwd)
7841 {
7842 	struct i40e_channel *ch = NULL, *ch_tmp, *iter;
7843 	int ret = 0, num_tc = 1,  i, aq_err;
7844 	struct i40e_pf *pf = vsi->back;
7845 	struct i40e_hw *hw = &pf->hw;
7846 
7847 	/* Go through the list and find an available channel */
7848 	list_for_each_entry_safe(iter, ch_tmp, &vsi->macvlan_list, list) {
7849 		if (!i40e_is_channel_macvlan(iter)) {
7850 			iter->fwd = fwd;
7851 			/* record configuration for macvlan interface in vdev */
7852 			for (i = 0; i < num_tc; i++)
7853 				netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7854 							     i,
7855 							     iter->num_queue_pairs,
7856 							     iter->base_queue);
7857 			for (i = 0; i < iter->num_queue_pairs; i++) {
7858 				struct i40e_ring *tx_ring, *rx_ring;
7859 				u16 pf_q;
7860 
7861 				pf_q = iter->base_queue + i;
7862 
7863 				/* Get to TX ring ptr */
7864 				tx_ring = vsi->tx_rings[pf_q];
7865 				tx_ring->ch = iter;
7866 
7867 				/* Get the RX ring ptr */
7868 				rx_ring = vsi->rx_rings[pf_q];
7869 				rx_ring->ch = iter;
7870 			}
7871 			ch = iter;
7872 			break;
7873 		}
7874 	}
7875 
7876 	if (!ch)
7877 		return -EINVAL;
7878 
7879 	/* Guarantee all rings are updated before we update the
7880 	 * MAC address filter.
7881 	 */
7882 	wmb();
7883 
7884 	/* Add a mac filter */
7885 	ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7886 	if (ret) {
7887 		/* if we cannot add the MAC rule then disable the offload */
7888 		macvlan_release_l2fw_offload(vdev);
7889 		for (i = 0; i < ch->num_queue_pairs; i++) {
7890 			struct i40e_ring *rx_ring;
7891 			u16 pf_q;
7892 
7893 			pf_q = ch->base_queue + i;
7894 			rx_ring = vsi->rx_rings[pf_q];
7895 			rx_ring->netdev = NULL;
7896 		}
7897 		dev_info(&pf->pdev->dev,
7898 			 "Error adding mac filter on macvlan err %pe, aq_err %s\n",
7899 			  ERR_PTR(ret),
7900 			  i40e_aq_str(hw, aq_err));
7901 		netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7902 	}
7903 
7904 	return ret;
7905 }
7906 
7907 /**
7908  * i40e_setup_macvlans - create the channels which will be macvlans
7909  * @vsi: the VSI we want to access
7910  * @macvlan_cnt: no. of macvlans to be setup
7911  * @qcnt: no. of Qs per macvlan
7912  * @vdev: macvlan netdevice
7913  */
7914 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7915 			       struct net_device *vdev)
7916 {
7917 	struct i40e_pf *pf = vsi->back;
7918 	struct i40e_hw *hw = &pf->hw;
7919 	struct i40e_vsi_context ctxt;
7920 	u16 sections, qmap, num_qps;
7921 	struct i40e_channel *ch;
7922 	int i, pow, ret = 0;
7923 	u8 offset = 0;
7924 
7925 	if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7926 		return -EINVAL;
7927 
7928 	num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7929 
7930 	/* find the next higher power-of-2 of num queue pairs */
7931 	pow = fls(roundup_pow_of_two(num_qps) - 1);
7932 
7933 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7934 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7935 
7936 	/* Setup context bits for the main VSI */
7937 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7938 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7939 	memset(&ctxt, 0, sizeof(ctxt));
7940 	ctxt.seid = vsi->seid;
7941 	ctxt.pf_num = vsi->back->hw.pf_id;
7942 	ctxt.vf_num = 0;
7943 	ctxt.uplink_seid = vsi->uplink_seid;
7944 	ctxt.info = vsi->info;
7945 	ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7946 	ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7947 	ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7948 	ctxt.info.valid_sections |= cpu_to_le16(sections);
7949 
7950 	/* Reconfigure RSS for main VSI with new max queue count */
7951 	vsi->rss_size = max_t(u16, num_qps, qcnt);
7952 	ret = i40e_vsi_config_rss(vsi);
7953 	if (ret) {
7954 		dev_info(&pf->pdev->dev,
7955 			 "Failed to reconfig RSS for num_queues (%u)\n",
7956 			 vsi->rss_size);
7957 		return ret;
7958 	}
7959 	vsi->reconfig_rss = true;
7960 	dev_dbg(&vsi->back->pdev->dev,
7961 		"Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7962 	vsi->next_base_queue = num_qps;
7963 	vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7964 
7965 	/* Update the VSI after updating the VSI queue-mapping
7966 	 * information
7967 	 */
7968 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7969 	if (ret) {
7970 		dev_info(&pf->pdev->dev,
7971 			 "Update vsi tc config failed, err %pe aq_err %s\n",
7972 			 ERR_PTR(ret),
7973 			 i40e_aq_str(hw, hw->aq.asq_last_status));
7974 		return ret;
7975 	}
7976 	/* update the local VSI info with updated queue map */
7977 	i40e_vsi_update_queue_map(vsi, &ctxt);
7978 	vsi->info.valid_sections = 0;
7979 
7980 	/* Create channels for macvlans */
7981 	INIT_LIST_HEAD(&vsi->macvlan_list);
7982 	for (i = 0; i < macvlan_cnt; i++) {
7983 		ch = kzalloc(sizeof(*ch), GFP_KERNEL);
7984 		if (!ch) {
7985 			ret = -ENOMEM;
7986 			goto err_free;
7987 		}
7988 		INIT_LIST_HEAD(&ch->list);
7989 		ch->num_queue_pairs = qcnt;
7990 		if (!i40e_setup_channel(pf, vsi, ch)) {
7991 			ret = -EINVAL;
7992 			kfree(ch);
7993 			goto err_free;
7994 		}
7995 		ch->parent_vsi = vsi;
7996 		vsi->cnt_q_avail -= ch->num_queue_pairs;
7997 		vsi->macvlan_cnt++;
7998 		list_add_tail(&ch->list, &vsi->macvlan_list);
7999 	}
8000 
8001 	return ret;
8002 
8003 err_free:
8004 	dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
8005 	i40e_free_macvlan_channels(vsi);
8006 
8007 	return ret;
8008 }
8009 
8010 /**
8011  * i40e_fwd_add - configure macvlans
8012  * @netdev: net device to configure
8013  * @vdev: macvlan netdevice
8014  **/
8015 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
8016 {
8017 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8018 	u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
8019 	struct i40e_vsi *vsi = np->vsi;
8020 	struct i40e_pf *pf = vsi->back;
8021 	struct i40e_fwd_adapter *fwd;
8022 	int avail_macvlan, ret;
8023 
8024 	if (test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8025 		netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
8026 		return ERR_PTR(-EINVAL);
8027 	}
8028 	if (i40e_is_tc_mqprio_enabled(pf)) {
8029 		netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
8030 		return ERR_PTR(-EINVAL);
8031 	}
8032 	if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
8033 		netdev_info(netdev, "Not enough vectors available to support macvlans\n");
8034 		return ERR_PTR(-EINVAL);
8035 	}
8036 
8037 	/* The macvlan device has to be a single Q device so that the
8038 	 * tc_to_txq field can be reused to pick the tx queue.
8039 	 */
8040 	if (netif_is_multiqueue(vdev))
8041 		return ERR_PTR(-ERANGE);
8042 
8043 	if (!vsi->macvlan_cnt) {
8044 		/* reserve bit 0 for the pf device */
8045 		set_bit(0, vsi->fwd_bitmask);
8046 
8047 		/* Try to reserve as many queues as possible for macvlans. First
8048 		 * reserve 3/4th of max vectors, then half, then quarter and
8049 		 * calculate Qs per macvlan as you go
8050 		 */
8051 		vectors = pf->num_lan_msix;
8052 		if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
8053 			/* allocate 4 Qs per macvlan and 32 Qs to the PF*/
8054 			q_per_macvlan = 4;
8055 			macvlan_cnt = (vectors - 32) / 4;
8056 		} else if (vectors <= 64 && vectors > 32) {
8057 			/* allocate 2 Qs per macvlan and 16 Qs to the PF*/
8058 			q_per_macvlan = 2;
8059 			macvlan_cnt = (vectors - 16) / 2;
8060 		} else if (vectors <= 32 && vectors > 16) {
8061 			/* allocate 1 Q per macvlan and 16 Qs to the PF*/
8062 			q_per_macvlan = 1;
8063 			macvlan_cnt = vectors - 16;
8064 		} else if (vectors <= 16 && vectors > 8) {
8065 			/* allocate 1 Q per macvlan and 8 Qs to the PF */
8066 			q_per_macvlan = 1;
8067 			macvlan_cnt = vectors - 8;
8068 		} else {
8069 			/* allocate 1 Q per macvlan and 1 Q to the PF */
8070 			q_per_macvlan = 1;
8071 			macvlan_cnt = vectors - 1;
8072 		}
8073 
8074 		if (macvlan_cnt == 0)
8075 			return ERR_PTR(-EBUSY);
8076 
8077 		/* Quiesce VSI queues */
8078 		i40e_quiesce_vsi(vsi);
8079 
8080 		/* sets up the macvlans but does not "enable" them */
8081 		ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
8082 					  vdev);
8083 		if (ret)
8084 			return ERR_PTR(ret);
8085 
8086 		/* Unquiesce VSI */
8087 		i40e_unquiesce_vsi(vsi);
8088 	}
8089 	avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
8090 					    vsi->macvlan_cnt);
8091 	if (avail_macvlan >= I40E_MAX_MACVLANS)
8092 		return ERR_PTR(-EBUSY);
8093 
8094 	/* create the fwd struct */
8095 	fwd = kzalloc(sizeof(*fwd), GFP_KERNEL);
8096 	if (!fwd)
8097 		return ERR_PTR(-ENOMEM);
8098 
8099 	set_bit(avail_macvlan, vsi->fwd_bitmask);
8100 	fwd->bit_no = avail_macvlan;
8101 	netdev_set_sb_channel(vdev, avail_macvlan);
8102 	fwd->netdev = vdev;
8103 
8104 	if (!netif_running(netdev))
8105 		return fwd;
8106 
8107 	/* Set fwd ring up */
8108 	ret = i40e_fwd_ring_up(vsi, vdev, fwd);
8109 	if (ret) {
8110 		/* unbind the queues and drop the subordinate channel config */
8111 		netdev_unbind_sb_channel(netdev, vdev);
8112 		netdev_set_sb_channel(vdev, 0);
8113 
8114 		kfree(fwd);
8115 		return ERR_PTR(-EINVAL);
8116 	}
8117 
8118 	return fwd;
8119 }
8120 
8121 /**
8122  * i40e_del_all_macvlans - Delete all the mac filters on the channels
8123  * @vsi: the VSI we want to access
8124  */
8125 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
8126 {
8127 	struct i40e_channel *ch, *ch_tmp;
8128 	struct i40e_pf *pf = vsi->back;
8129 	struct i40e_hw *hw = &pf->hw;
8130 	int aq_err, ret = 0;
8131 
8132 	if (list_empty(&vsi->macvlan_list))
8133 		return;
8134 
8135 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8136 		if (i40e_is_channel_macvlan(ch)) {
8137 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8138 						      i40e_channel_mac(ch),
8139 						      &aq_err);
8140 			if (!ret) {
8141 				/* Reset queue contexts */
8142 				i40e_reset_ch_rings(vsi, ch);
8143 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8144 				netdev_unbind_sb_channel(vsi->netdev,
8145 							 ch->fwd->netdev);
8146 				netdev_set_sb_channel(ch->fwd->netdev, 0);
8147 				kfree(ch->fwd);
8148 				ch->fwd = NULL;
8149 			}
8150 		}
8151 	}
8152 }
8153 
8154 /**
8155  * i40e_fwd_del - delete macvlan interfaces
8156  * @netdev: net device to configure
8157  * @vdev: macvlan netdevice
8158  */
8159 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
8160 {
8161 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8162 	struct i40e_fwd_adapter *fwd = vdev;
8163 	struct i40e_channel *ch, *ch_tmp;
8164 	struct i40e_vsi *vsi = np->vsi;
8165 	struct i40e_pf *pf = vsi->back;
8166 	struct i40e_hw *hw = &pf->hw;
8167 	int aq_err, ret = 0;
8168 
8169 	/* Find the channel associated with the macvlan and del mac filter */
8170 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8171 		if (i40e_is_channel_macvlan(ch) &&
8172 		    ether_addr_equal(i40e_channel_mac(ch),
8173 				     fwd->netdev->dev_addr)) {
8174 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8175 						      i40e_channel_mac(ch),
8176 						      &aq_err);
8177 			if (!ret) {
8178 				/* Reset queue contexts */
8179 				i40e_reset_ch_rings(vsi, ch);
8180 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8181 				netdev_unbind_sb_channel(netdev, fwd->netdev);
8182 				netdev_set_sb_channel(fwd->netdev, 0);
8183 				kfree(ch->fwd);
8184 				ch->fwd = NULL;
8185 			} else {
8186 				dev_info(&pf->pdev->dev,
8187 					 "Error deleting mac filter on macvlan err %pe, aq_err %s\n",
8188 					  ERR_PTR(ret),
8189 					  i40e_aq_str(hw, aq_err));
8190 			}
8191 			break;
8192 		}
8193 	}
8194 }
8195 
8196 /**
8197  * i40e_setup_tc - configure multiple traffic classes
8198  * @netdev: net device to configure
8199  * @type_data: tc offload data
8200  **/
8201 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
8202 {
8203 	struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
8204 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8205 	struct i40e_vsi *vsi = np->vsi;
8206 	struct i40e_pf *pf = vsi->back;
8207 	u8 enabled_tc = 0, num_tc, hw;
8208 	bool need_reset = false;
8209 	int old_queue_pairs;
8210 	int ret = -EINVAL;
8211 	u16 mode;
8212 	int i;
8213 
8214 	old_queue_pairs = vsi->num_queue_pairs;
8215 	num_tc = mqprio_qopt->qopt.num_tc;
8216 	hw = mqprio_qopt->qopt.hw;
8217 	mode = mqprio_qopt->mode;
8218 	if (!hw) {
8219 		clear_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8220 		memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8221 		goto config_tc;
8222 	}
8223 
8224 	/* Check if MFP enabled */
8225 	if (test_bit(I40E_FLAG_MFP_ENA, pf->flags)) {
8226 		netdev_info(netdev,
8227 			    "Configuring TC not supported in MFP mode\n");
8228 		return ret;
8229 	}
8230 	switch (mode) {
8231 	case TC_MQPRIO_MODE_DCB:
8232 		clear_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8233 
8234 		/* Check if DCB enabled to continue */
8235 		if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8236 			netdev_info(netdev,
8237 				    "DCB is not enabled for adapter\n");
8238 			return ret;
8239 		}
8240 
8241 		/* Check whether tc count is within enabled limit */
8242 		if (num_tc > i40e_pf_get_num_tc(pf)) {
8243 			netdev_info(netdev,
8244 				    "TC count greater than enabled on link for adapter\n");
8245 			return ret;
8246 		}
8247 		break;
8248 	case TC_MQPRIO_MODE_CHANNEL:
8249 		if (test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8250 			netdev_info(netdev,
8251 				    "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
8252 			return ret;
8253 		}
8254 		if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
8255 			return ret;
8256 		ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
8257 		if (ret)
8258 			return ret;
8259 		memcpy(&vsi->mqprio_qopt, mqprio_qopt,
8260 		       sizeof(*mqprio_qopt));
8261 		set_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8262 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
8263 		break;
8264 	default:
8265 		return -EINVAL;
8266 	}
8267 
8268 config_tc:
8269 	/* Generate TC map for number of tc requested */
8270 	for (i = 0; i < num_tc; i++)
8271 		enabled_tc |= BIT(i);
8272 
8273 	/* Requesting same TC configuration as already enabled */
8274 	if (enabled_tc == vsi->tc_config.enabled_tc &&
8275 	    mode != TC_MQPRIO_MODE_CHANNEL)
8276 		return 0;
8277 
8278 	/* Quiesce VSI queues */
8279 	i40e_quiesce_vsi(vsi);
8280 
8281 	if (!hw && !i40e_is_tc_mqprio_enabled(pf))
8282 		i40e_remove_queue_channels(vsi);
8283 
8284 	/* Configure VSI for enabled TCs */
8285 	ret = i40e_vsi_config_tc(vsi, enabled_tc);
8286 	if (ret) {
8287 		netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
8288 			    vsi->seid);
8289 		need_reset = true;
8290 		goto exit;
8291 	} else if (enabled_tc &&
8292 		   (!is_power_of_2(vsi->tc_config.tc_info[0].qcount))) {
8293 		netdev_info(netdev,
8294 			    "Failed to create channel. Override queues (%u) not power of 2\n",
8295 			    vsi->tc_config.tc_info[0].qcount);
8296 		ret = -EINVAL;
8297 		need_reset = true;
8298 		goto exit;
8299 	}
8300 
8301 	dev_info(&vsi->back->pdev->dev,
8302 		 "Setup channel (id:%u) utilizing num_queues %d\n",
8303 		 vsi->seid, vsi->tc_config.tc_info[0].qcount);
8304 
8305 	if (i40e_is_tc_mqprio_enabled(pf)) {
8306 		if (vsi->mqprio_qopt.max_rate[0]) {
8307 			u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
8308 						  vsi->mqprio_qopt.max_rate[0]);
8309 
8310 			ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
8311 			if (!ret) {
8312 				u64 credits = max_tx_rate;
8313 
8314 				do_div(credits, I40E_BW_CREDIT_DIVISOR);
8315 				dev_dbg(&vsi->back->pdev->dev,
8316 					"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
8317 					max_tx_rate,
8318 					credits,
8319 					vsi->seid);
8320 			} else {
8321 				need_reset = true;
8322 				goto exit;
8323 			}
8324 		}
8325 		ret = i40e_configure_queue_channels(vsi);
8326 		if (ret) {
8327 			vsi->num_queue_pairs = old_queue_pairs;
8328 			netdev_info(netdev,
8329 				    "Failed configuring queue channels\n");
8330 			need_reset = true;
8331 			goto exit;
8332 		}
8333 	}
8334 
8335 exit:
8336 	/* Reset the configuration data to defaults, only TC0 is enabled */
8337 	if (need_reset) {
8338 		i40e_vsi_set_default_tc_config(vsi);
8339 		need_reset = false;
8340 	}
8341 
8342 	/* Unquiesce VSI */
8343 	i40e_unquiesce_vsi(vsi);
8344 	return ret;
8345 }
8346 
8347 /**
8348  * i40e_set_cld_element - sets cloud filter element data
8349  * @filter: cloud filter rule
8350  * @cld: ptr to cloud filter element data
8351  *
8352  * This is helper function to copy data into cloud filter element
8353  **/
8354 static inline void
8355 i40e_set_cld_element(struct i40e_cloud_filter *filter,
8356 		     struct i40e_aqc_cloud_filters_element_data *cld)
8357 {
8358 	u32 ipa;
8359 	int i;
8360 
8361 	memset(cld, 0, sizeof(*cld));
8362 	ether_addr_copy(cld->outer_mac, filter->dst_mac);
8363 	ether_addr_copy(cld->inner_mac, filter->src_mac);
8364 
8365 	if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
8366 		return;
8367 
8368 	if (filter->n_proto == ETH_P_IPV6) {
8369 #define IPV6_MAX_INDEX	(ARRAY_SIZE(filter->dst_ipv6) - 1)
8370 		for (i = 0; i < ARRAY_SIZE(filter->dst_ipv6); i++) {
8371 			ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
8372 
8373 			*(__le32 *)&cld->ipaddr.raw_v6.data[i * 2] = cpu_to_le32(ipa);
8374 		}
8375 	} else {
8376 		ipa = be32_to_cpu(filter->dst_ipv4);
8377 
8378 		memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
8379 	}
8380 
8381 	cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
8382 
8383 	/* tenant_id is not supported by FW now, once the support is enabled
8384 	 * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
8385 	 */
8386 	if (filter->tenant_id)
8387 		return;
8388 }
8389 
8390 /**
8391  * i40e_add_del_cloud_filter - Add/del cloud filter
8392  * @vsi: pointer to VSI
8393  * @filter: cloud filter rule
8394  * @add: if true, add, if false, delete
8395  *
8396  * Add or delete a cloud filter for a specific flow spec.
8397  * Returns 0 if the filter were successfully added.
8398  **/
8399 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
8400 			      struct i40e_cloud_filter *filter, bool add)
8401 {
8402 	struct i40e_aqc_cloud_filters_element_data cld_filter;
8403 	struct i40e_pf *pf = vsi->back;
8404 	int ret;
8405 	static const u16 flag_table[128] = {
8406 		[I40E_CLOUD_FILTER_FLAGS_OMAC]  =
8407 			I40E_AQC_ADD_CLOUD_FILTER_OMAC,
8408 		[I40E_CLOUD_FILTER_FLAGS_IMAC]  =
8409 			I40E_AQC_ADD_CLOUD_FILTER_IMAC,
8410 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
8411 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
8412 		[I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
8413 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
8414 		[I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
8415 			I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
8416 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
8417 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
8418 		[I40E_CLOUD_FILTER_FLAGS_IIP] =
8419 			I40E_AQC_ADD_CLOUD_FILTER_IIP,
8420 	};
8421 
8422 	if (filter->flags >= ARRAY_SIZE(flag_table))
8423 		return -EIO;
8424 
8425 	memset(&cld_filter, 0, sizeof(cld_filter));
8426 
8427 	/* copy element needed to add cloud filter from filter */
8428 	i40e_set_cld_element(filter, &cld_filter);
8429 
8430 	if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
8431 		cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
8432 					     I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
8433 
8434 	if (filter->n_proto == ETH_P_IPV6)
8435 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8436 						I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8437 	else
8438 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8439 						I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8440 
8441 	if (add)
8442 		ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
8443 						&cld_filter, 1);
8444 	else
8445 		ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
8446 						&cld_filter, 1);
8447 	if (ret)
8448 		dev_dbg(&pf->pdev->dev,
8449 			"Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
8450 			add ? "add" : "delete", filter->dst_port, ret,
8451 			pf->hw.aq.asq_last_status);
8452 	else
8453 		dev_info(&pf->pdev->dev,
8454 			 "%s cloud filter for VSI: %d\n",
8455 			 add ? "Added" : "Deleted", filter->seid);
8456 	return ret;
8457 }
8458 
8459 /**
8460  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
8461  * @vsi: pointer to VSI
8462  * @filter: cloud filter rule
8463  * @add: if true, add, if false, delete
8464  *
8465  * Add or delete a cloud filter for a specific flow spec using big buffer.
8466  * Returns 0 if the filter were successfully added.
8467  **/
8468 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
8469 				      struct i40e_cloud_filter *filter,
8470 				      bool add)
8471 {
8472 	struct i40e_aqc_cloud_filters_element_bb cld_filter;
8473 	struct i40e_pf *pf = vsi->back;
8474 	int ret;
8475 
8476 	/* Both (src/dst) valid mac_addr are not supported */
8477 	if ((is_valid_ether_addr(filter->dst_mac) &&
8478 	     is_valid_ether_addr(filter->src_mac)) ||
8479 	    (is_multicast_ether_addr(filter->dst_mac) &&
8480 	     is_multicast_ether_addr(filter->src_mac)))
8481 		return -EOPNOTSUPP;
8482 
8483 	/* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
8484 	 * ports are not supported via big buffer now.
8485 	 */
8486 	if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
8487 		return -EOPNOTSUPP;
8488 
8489 	/* adding filter using src_port/src_ip is not supported at this stage */
8490 	if (filter->src_port ||
8491 	    (filter->src_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8492 	    !ipv6_addr_any(&filter->ip.v6.src_ip6))
8493 		return -EOPNOTSUPP;
8494 
8495 	memset(&cld_filter, 0, sizeof(cld_filter));
8496 
8497 	/* copy element needed to add cloud filter from filter */
8498 	i40e_set_cld_element(filter, &cld_filter.element);
8499 
8500 	if (is_valid_ether_addr(filter->dst_mac) ||
8501 	    is_valid_ether_addr(filter->src_mac) ||
8502 	    is_multicast_ether_addr(filter->dst_mac) ||
8503 	    is_multicast_ether_addr(filter->src_mac)) {
8504 		/* MAC + IP : unsupported mode */
8505 		if (filter->dst_ipv4)
8506 			return -EOPNOTSUPP;
8507 
8508 		/* since we validated that L4 port must be valid before
8509 		 * we get here, start with respective "flags" value
8510 		 * and update if vlan is present or not
8511 		 */
8512 		cld_filter.element.flags =
8513 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
8514 
8515 		if (filter->vlan_id) {
8516 			cld_filter.element.flags =
8517 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
8518 		}
8519 
8520 	} else if ((filter->dst_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8521 		   !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
8522 		cld_filter.element.flags =
8523 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
8524 		if (filter->n_proto == ETH_P_IPV6)
8525 			cld_filter.element.flags |=
8526 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8527 		else
8528 			cld_filter.element.flags |=
8529 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8530 	} else {
8531 		dev_err(&pf->pdev->dev,
8532 			"either mac or ip has to be valid for cloud filter\n");
8533 		return -EINVAL;
8534 	}
8535 
8536 	/* Now copy L4 port in Byte 6..7 in general fields */
8537 	cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
8538 						be16_to_cpu(filter->dst_port);
8539 
8540 	if (add) {
8541 		/* Validate current device switch mode, change if necessary */
8542 		ret = i40e_validate_and_set_switch_mode(vsi);
8543 		if (ret) {
8544 			dev_err(&pf->pdev->dev,
8545 				"failed to set switch mode, ret %d\n",
8546 				ret);
8547 			return ret;
8548 		}
8549 
8550 		ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
8551 						   &cld_filter, 1);
8552 	} else {
8553 		ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
8554 						   &cld_filter, 1);
8555 	}
8556 
8557 	if (ret)
8558 		dev_dbg(&pf->pdev->dev,
8559 			"Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
8560 			add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
8561 	else
8562 		dev_info(&pf->pdev->dev,
8563 			 "%s cloud filter for VSI: %d, L4 port: %d\n",
8564 			 add ? "add" : "delete", filter->seid,
8565 			 ntohs(filter->dst_port));
8566 	return ret;
8567 }
8568 
8569 /**
8570  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
8571  * @vsi: Pointer to VSI
8572  * @f: Pointer to struct flow_cls_offload
8573  * @filter: Pointer to cloud filter structure
8574  *
8575  **/
8576 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
8577 				 struct flow_cls_offload *f,
8578 				 struct i40e_cloud_filter *filter)
8579 {
8580 	struct flow_rule *rule = flow_cls_offload_flow_rule(f);
8581 	struct flow_dissector *dissector = rule->match.dissector;
8582 	u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
8583 	struct i40e_pf *pf = vsi->back;
8584 	u8 field_flags = 0;
8585 
8586 	if (dissector->used_keys &
8587 	    ~(BIT_ULL(FLOW_DISSECTOR_KEY_CONTROL) |
8588 	      BIT_ULL(FLOW_DISSECTOR_KEY_BASIC) |
8589 	      BIT_ULL(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
8590 	      BIT_ULL(FLOW_DISSECTOR_KEY_VLAN) |
8591 	      BIT_ULL(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
8592 	      BIT_ULL(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
8593 	      BIT_ULL(FLOW_DISSECTOR_KEY_PORTS) |
8594 	      BIT_ULL(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
8595 		dev_err(&pf->pdev->dev, "Unsupported key used: 0x%llx\n",
8596 			dissector->used_keys);
8597 		return -EOPNOTSUPP;
8598 	}
8599 
8600 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
8601 		struct flow_match_enc_keyid match;
8602 
8603 		flow_rule_match_enc_keyid(rule, &match);
8604 		if (match.mask->keyid != 0)
8605 			field_flags |= I40E_CLOUD_FIELD_TEN_ID;
8606 
8607 		filter->tenant_id = be32_to_cpu(match.key->keyid);
8608 	}
8609 
8610 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
8611 		struct flow_match_basic match;
8612 
8613 		flow_rule_match_basic(rule, &match);
8614 		n_proto_key = ntohs(match.key->n_proto);
8615 		n_proto_mask = ntohs(match.mask->n_proto);
8616 
8617 		if (n_proto_key == ETH_P_ALL) {
8618 			n_proto_key = 0;
8619 			n_proto_mask = 0;
8620 		}
8621 		filter->n_proto = n_proto_key & n_proto_mask;
8622 		filter->ip_proto = match.key->ip_proto;
8623 	}
8624 
8625 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
8626 		struct flow_match_eth_addrs match;
8627 
8628 		flow_rule_match_eth_addrs(rule, &match);
8629 
8630 		/* use is_broadcast and is_zero to check for all 0xf or 0 */
8631 		if (!is_zero_ether_addr(match.mask->dst)) {
8632 			if (is_broadcast_ether_addr(match.mask->dst)) {
8633 				field_flags |= I40E_CLOUD_FIELD_OMAC;
8634 			} else {
8635 				dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
8636 					match.mask->dst);
8637 				return -EIO;
8638 			}
8639 		}
8640 
8641 		if (!is_zero_ether_addr(match.mask->src)) {
8642 			if (is_broadcast_ether_addr(match.mask->src)) {
8643 				field_flags |= I40E_CLOUD_FIELD_IMAC;
8644 			} else {
8645 				dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
8646 					match.mask->src);
8647 				return -EIO;
8648 			}
8649 		}
8650 		ether_addr_copy(filter->dst_mac, match.key->dst);
8651 		ether_addr_copy(filter->src_mac, match.key->src);
8652 	}
8653 
8654 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
8655 		struct flow_match_vlan match;
8656 
8657 		flow_rule_match_vlan(rule, &match);
8658 		if (match.mask->vlan_id) {
8659 			if (match.mask->vlan_id == VLAN_VID_MASK) {
8660 				field_flags |= I40E_CLOUD_FIELD_IVLAN;
8661 
8662 			} else {
8663 				dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
8664 					match.mask->vlan_id);
8665 				return -EIO;
8666 			}
8667 		}
8668 
8669 		filter->vlan_id = cpu_to_be16(match.key->vlan_id);
8670 	}
8671 
8672 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
8673 		struct flow_match_control match;
8674 
8675 		flow_rule_match_control(rule, &match);
8676 		addr_type = match.key->addr_type;
8677 
8678 		if (flow_rule_has_control_flags(match.mask->flags,
8679 						f->common.extack))
8680 			return -EOPNOTSUPP;
8681 	}
8682 
8683 	if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
8684 		struct flow_match_ipv4_addrs match;
8685 
8686 		flow_rule_match_ipv4_addrs(rule, &match);
8687 		if (match.mask->dst) {
8688 			if (match.mask->dst == cpu_to_be32(0xffffffff)) {
8689 				field_flags |= I40E_CLOUD_FIELD_IIP;
8690 			} else {
8691 				dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
8692 					&match.mask->dst);
8693 				return -EIO;
8694 			}
8695 		}
8696 
8697 		if (match.mask->src) {
8698 			if (match.mask->src == cpu_to_be32(0xffffffff)) {
8699 				field_flags |= I40E_CLOUD_FIELD_IIP;
8700 			} else {
8701 				dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
8702 					&match.mask->src);
8703 				return -EIO;
8704 			}
8705 		}
8706 
8707 		if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
8708 			dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
8709 			return -EIO;
8710 		}
8711 		filter->dst_ipv4 = match.key->dst;
8712 		filter->src_ipv4 = match.key->src;
8713 	}
8714 
8715 	if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
8716 		struct flow_match_ipv6_addrs match;
8717 
8718 		flow_rule_match_ipv6_addrs(rule, &match);
8719 
8720 		/* src and dest IPV6 address should not be LOOPBACK
8721 		 * (0:0:0:0:0:0:0:1), which can be represented as ::1
8722 		 */
8723 		if (ipv6_addr_loopback(&match.key->dst) ||
8724 		    ipv6_addr_loopback(&match.key->src)) {
8725 			dev_err(&pf->pdev->dev,
8726 				"Bad ipv6, addr is LOOPBACK\n");
8727 			return -EIO;
8728 		}
8729 		if (!ipv6_addr_any(&match.mask->dst) ||
8730 		    !ipv6_addr_any(&match.mask->src))
8731 			field_flags |= I40E_CLOUD_FIELD_IIP;
8732 
8733 		memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
8734 		       sizeof(filter->src_ipv6));
8735 		memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
8736 		       sizeof(filter->dst_ipv6));
8737 	}
8738 
8739 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
8740 		struct flow_match_ports match;
8741 
8742 		flow_rule_match_ports(rule, &match);
8743 		if (match.mask->src) {
8744 			if (match.mask->src == cpu_to_be16(0xffff)) {
8745 				field_flags |= I40E_CLOUD_FIELD_IIP;
8746 			} else {
8747 				dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
8748 					be16_to_cpu(match.mask->src));
8749 				return -EIO;
8750 			}
8751 		}
8752 
8753 		if (match.mask->dst) {
8754 			if (match.mask->dst == cpu_to_be16(0xffff)) {
8755 				field_flags |= I40E_CLOUD_FIELD_IIP;
8756 			} else {
8757 				dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
8758 					be16_to_cpu(match.mask->dst));
8759 				return -EIO;
8760 			}
8761 		}
8762 
8763 		filter->dst_port = match.key->dst;
8764 		filter->src_port = match.key->src;
8765 
8766 		switch (filter->ip_proto) {
8767 		case IPPROTO_TCP:
8768 		case IPPROTO_UDP:
8769 			break;
8770 		default:
8771 			dev_err(&pf->pdev->dev,
8772 				"Only UDP and TCP transport are supported\n");
8773 			return -EINVAL;
8774 		}
8775 	}
8776 	filter->flags = field_flags;
8777 	return 0;
8778 }
8779 
8780 /**
8781  * i40e_handle_tclass: Forward to a traffic class on the device
8782  * @vsi: Pointer to VSI
8783  * @tc: traffic class index on the device
8784  * @filter: Pointer to cloud filter structure
8785  *
8786  **/
8787 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
8788 			      struct i40e_cloud_filter *filter)
8789 {
8790 	struct i40e_channel *ch, *ch_tmp;
8791 
8792 	/* direct to a traffic class on the same device */
8793 	if (tc == 0) {
8794 		filter->seid = vsi->seid;
8795 		return 0;
8796 	} else if (vsi->tc_config.enabled_tc & BIT(tc)) {
8797 		if (!filter->dst_port) {
8798 			dev_err(&vsi->back->pdev->dev,
8799 				"Specify destination port to direct to traffic class that is not default\n");
8800 			return -EINVAL;
8801 		}
8802 		if (list_empty(&vsi->ch_list))
8803 			return -EINVAL;
8804 		list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
8805 					 list) {
8806 			if (ch->seid == vsi->tc_seid_map[tc])
8807 				filter->seid = ch->seid;
8808 		}
8809 		return 0;
8810 	}
8811 	dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
8812 	return -EINVAL;
8813 }
8814 
8815 /**
8816  * i40e_configure_clsflower - Configure tc flower filters
8817  * @vsi: Pointer to VSI
8818  * @cls_flower: Pointer to struct flow_cls_offload
8819  *
8820  **/
8821 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
8822 				    struct flow_cls_offload *cls_flower)
8823 {
8824 	int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
8825 	struct i40e_cloud_filter *filter = NULL;
8826 	struct i40e_pf *pf = vsi->back;
8827 	int err = 0;
8828 
8829 	if (tc < 0) {
8830 		dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
8831 		return -EOPNOTSUPP;
8832 	}
8833 
8834 	if (!tc) {
8835 		dev_err(&pf->pdev->dev, "Unable to add filter because of invalid destination");
8836 		return -EINVAL;
8837 	}
8838 
8839 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
8840 	    test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
8841 		return -EBUSY;
8842 
8843 	if (pf->fdir_pf_active_filters ||
8844 	    (!hlist_empty(&pf->fdir_filter_list))) {
8845 		dev_err(&vsi->back->pdev->dev,
8846 			"Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
8847 		return -EINVAL;
8848 	}
8849 
8850 	if (test_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags)) {
8851 		dev_err(&vsi->back->pdev->dev,
8852 			"Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
8853 		clear_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags);
8854 		clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, vsi->back->flags);
8855 	}
8856 
8857 	filter = kzalloc(sizeof(*filter), GFP_KERNEL);
8858 	if (!filter)
8859 		return -ENOMEM;
8860 
8861 	filter->cookie = cls_flower->cookie;
8862 
8863 	err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8864 	if (err < 0)
8865 		goto err;
8866 
8867 	err = i40e_handle_tclass(vsi, tc, filter);
8868 	if (err < 0)
8869 		goto err;
8870 
8871 	/* Add cloud filter */
8872 	if (filter->dst_port)
8873 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8874 	else
8875 		err = i40e_add_del_cloud_filter(vsi, filter, true);
8876 
8877 	if (err) {
8878 		dev_err(&pf->pdev->dev, "Failed to add cloud filter, err %d\n",
8879 			err);
8880 		goto err;
8881 	}
8882 
8883 	/* add filter to the ordered list */
8884 	INIT_HLIST_NODE(&filter->cloud_node);
8885 
8886 	hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8887 
8888 	pf->num_cloud_filters++;
8889 
8890 	return err;
8891 err:
8892 	kfree(filter);
8893 	return err;
8894 }
8895 
8896 /**
8897  * i40e_find_cloud_filter - Find the could filter in the list
8898  * @vsi: Pointer to VSI
8899  * @cookie: filter specific cookie
8900  *
8901  **/
8902 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8903 							unsigned long *cookie)
8904 {
8905 	struct i40e_cloud_filter *filter = NULL;
8906 	struct hlist_node *node2;
8907 
8908 	hlist_for_each_entry_safe(filter, node2,
8909 				  &vsi->back->cloud_filter_list, cloud_node)
8910 		if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8911 			return filter;
8912 	return NULL;
8913 }
8914 
8915 /**
8916  * i40e_delete_clsflower - Remove tc flower filters
8917  * @vsi: Pointer to VSI
8918  * @cls_flower: Pointer to struct flow_cls_offload
8919  *
8920  **/
8921 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8922 				 struct flow_cls_offload *cls_flower)
8923 {
8924 	struct i40e_cloud_filter *filter = NULL;
8925 	struct i40e_pf *pf = vsi->back;
8926 	int err = 0;
8927 
8928 	filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8929 
8930 	if (!filter)
8931 		return -EINVAL;
8932 
8933 	hash_del(&filter->cloud_node);
8934 
8935 	if (filter->dst_port)
8936 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8937 	else
8938 		err = i40e_add_del_cloud_filter(vsi, filter, false);
8939 
8940 	kfree(filter);
8941 	if (err) {
8942 		dev_err(&pf->pdev->dev,
8943 			"Failed to delete cloud filter, err %pe\n",
8944 			ERR_PTR(err));
8945 		return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8946 	}
8947 
8948 	pf->num_cloud_filters--;
8949 	if (!pf->num_cloud_filters)
8950 		if (test_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags) &&
8951 		    !test_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags)) {
8952 			set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
8953 			clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags);
8954 			clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
8955 		}
8956 	return 0;
8957 }
8958 
8959 /**
8960  * i40e_setup_tc_cls_flower - flower classifier offloads
8961  * @np: net device to configure
8962  * @cls_flower: offload data
8963  **/
8964 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8965 				    struct flow_cls_offload *cls_flower)
8966 {
8967 	struct i40e_vsi *vsi = np->vsi;
8968 
8969 	switch (cls_flower->command) {
8970 	case FLOW_CLS_REPLACE:
8971 		return i40e_configure_clsflower(vsi, cls_flower);
8972 	case FLOW_CLS_DESTROY:
8973 		return i40e_delete_clsflower(vsi, cls_flower);
8974 	case FLOW_CLS_STATS:
8975 		return -EOPNOTSUPP;
8976 	default:
8977 		return -EOPNOTSUPP;
8978 	}
8979 }
8980 
8981 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8982 				  void *cb_priv)
8983 {
8984 	struct i40e_netdev_priv *np = cb_priv;
8985 
8986 	if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8987 		return -EOPNOTSUPP;
8988 
8989 	switch (type) {
8990 	case TC_SETUP_CLSFLOWER:
8991 		return i40e_setup_tc_cls_flower(np, type_data);
8992 
8993 	default:
8994 		return -EOPNOTSUPP;
8995 	}
8996 }
8997 
8998 static LIST_HEAD(i40e_block_cb_list);
8999 
9000 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
9001 			   void *type_data)
9002 {
9003 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9004 
9005 	switch (type) {
9006 	case TC_SETUP_QDISC_MQPRIO:
9007 		return i40e_setup_tc(netdev, type_data);
9008 	case TC_SETUP_BLOCK:
9009 		return flow_block_cb_setup_simple(type_data,
9010 						  &i40e_block_cb_list,
9011 						  i40e_setup_tc_block_cb,
9012 						  np, np, true);
9013 	default:
9014 		return -EOPNOTSUPP;
9015 	}
9016 }
9017 
9018 /**
9019  * i40e_open - Called when a network interface is made active
9020  * @netdev: network interface device structure
9021  *
9022  * The open entry point is called when a network interface is made
9023  * active by the system (IFF_UP).  At this point all resources needed
9024  * for transmit and receive operations are allocated, the interrupt
9025  * handler is registered with the OS, the netdev watchdog subtask is
9026  * enabled, and the stack is notified that the interface is ready.
9027  *
9028  * Returns 0 on success, negative value on failure
9029  **/
9030 int i40e_open(struct net_device *netdev)
9031 {
9032 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9033 	struct i40e_vsi *vsi = np->vsi;
9034 	struct i40e_pf *pf = vsi->back;
9035 	int err;
9036 
9037 	/* disallow open during test or if eeprom is broken */
9038 	if (test_bit(__I40E_TESTING, pf->state) ||
9039 	    test_bit(__I40E_BAD_EEPROM, pf->state))
9040 		return -EBUSY;
9041 
9042 	netif_carrier_off(netdev);
9043 
9044 	if (i40e_force_link_state(pf, true))
9045 		return -EAGAIN;
9046 
9047 	err = i40e_vsi_open(vsi);
9048 	if (err)
9049 		return err;
9050 
9051 	/* configure global TSO hardware offload settings */
9052 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
9053 						       TCP_FLAG_FIN) >> 16);
9054 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
9055 						       TCP_FLAG_FIN |
9056 						       TCP_FLAG_CWR) >> 16);
9057 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
9058 	udp_tunnel_get_rx_info(netdev);
9059 
9060 	return 0;
9061 }
9062 
9063 /**
9064  * i40e_netif_set_realnum_tx_rx_queues - Update number of tx/rx queues
9065  * @vsi: vsi structure
9066  *
9067  * This updates netdev's number of tx/rx queues
9068  *
9069  * Returns status of setting tx/rx queues
9070  **/
9071 static int i40e_netif_set_realnum_tx_rx_queues(struct i40e_vsi *vsi)
9072 {
9073 	int ret;
9074 
9075 	ret = netif_set_real_num_rx_queues(vsi->netdev,
9076 					   vsi->num_queue_pairs);
9077 	if (ret)
9078 		return ret;
9079 
9080 	return netif_set_real_num_tx_queues(vsi->netdev,
9081 					    vsi->num_queue_pairs);
9082 }
9083 
9084 /**
9085  * i40e_vsi_open -
9086  * @vsi: the VSI to open
9087  *
9088  * Finish initialization of the VSI.
9089  *
9090  * Returns 0 on success, negative value on failure
9091  *
9092  * Note: expects to be called while under rtnl_lock()
9093  **/
9094 int i40e_vsi_open(struct i40e_vsi *vsi)
9095 {
9096 	struct i40e_pf *pf = vsi->back;
9097 	char int_name[I40E_INT_NAME_STR_LEN];
9098 	int err;
9099 
9100 	/* allocate descriptors */
9101 	err = i40e_vsi_setup_tx_resources(vsi);
9102 	if (err)
9103 		goto err_setup_tx;
9104 	err = i40e_vsi_setup_rx_resources(vsi);
9105 	if (err)
9106 		goto err_setup_rx;
9107 
9108 	err = i40e_vsi_configure(vsi);
9109 	if (err)
9110 		goto err_setup_rx;
9111 
9112 	if (vsi->netdev) {
9113 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
9114 			 dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
9115 		err = i40e_vsi_request_irq(vsi, int_name);
9116 		if (err)
9117 			goto err_setup_rx;
9118 
9119 		/* Notify the stack of the actual queue counts. */
9120 		err = i40e_netif_set_realnum_tx_rx_queues(vsi);
9121 		if (err)
9122 			goto err_set_queues;
9123 
9124 	} else if (vsi->type == I40E_VSI_FDIR) {
9125 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
9126 			 dev_driver_string(&pf->pdev->dev),
9127 			 dev_name(&pf->pdev->dev));
9128 		err = i40e_vsi_request_irq(vsi, int_name);
9129 		if (err)
9130 			goto err_setup_rx;
9131 
9132 	} else {
9133 		err = -EINVAL;
9134 		goto err_setup_rx;
9135 	}
9136 
9137 	err = i40e_up_complete(vsi);
9138 	if (err)
9139 		goto err_up_complete;
9140 
9141 	return 0;
9142 
9143 err_up_complete:
9144 	i40e_down(vsi);
9145 err_set_queues:
9146 	i40e_vsi_free_irq(vsi);
9147 err_setup_rx:
9148 	i40e_vsi_free_rx_resources(vsi);
9149 err_setup_tx:
9150 	i40e_vsi_free_tx_resources(vsi);
9151 	if (vsi->type == I40E_VSI_MAIN)
9152 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
9153 
9154 	return err;
9155 }
9156 
9157 /**
9158  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
9159  * @pf: Pointer to PF
9160  *
9161  * This function destroys the hlist where all the Flow Director
9162  * filters were saved.
9163  **/
9164 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
9165 {
9166 	struct i40e_fdir_filter *filter;
9167 	struct i40e_flex_pit *pit_entry, *tmp;
9168 	struct hlist_node *node2;
9169 
9170 	hlist_for_each_entry_safe(filter, node2,
9171 				  &pf->fdir_filter_list, fdir_node) {
9172 		hlist_del(&filter->fdir_node);
9173 		kfree(filter);
9174 	}
9175 
9176 	list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
9177 		list_del(&pit_entry->list);
9178 		kfree(pit_entry);
9179 	}
9180 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
9181 
9182 	list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
9183 		list_del(&pit_entry->list);
9184 		kfree(pit_entry);
9185 	}
9186 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
9187 
9188 	pf->fdir_pf_active_filters = 0;
9189 	i40e_reset_fdir_filter_cnt(pf);
9190 
9191 	/* Reprogram the default input set for TCP/IPv4 */
9192 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV4_TCP,
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 TCP/IPv6 */
9197 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV6_TCP,
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 UDP/IPv4 */
9202 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV4_UDP,
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 UDP/IPv6 */
9207 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV6_UDP,
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 SCTP/IPv4 */
9212 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV4_SCTP,
9213 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9214 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9215 
9216 	/* Reprogram the default input set for SCTP/IPv6 */
9217 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV6_SCTP,
9218 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9219 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9220 
9221 	/* Reprogram the default input set for Other/IPv4 */
9222 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV4_OTHER,
9223 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9224 
9225 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_FRAG_IPV4,
9226 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9227 
9228 	/* Reprogram the default input set for Other/IPv6 */
9229 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV6_OTHER,
9230 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9231 
9232 	i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_FRAG_IPV6,
9233 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9234 }
9235 
9236 /**
9237  * i40e_cloud_filter_exit - Cleans up the cloud filters
9238  * @pf: Pointer to PF
9239  *
9240  * This function destroys the hlist where all the cloud filters
9241  * were saved.
9242  **/
9243 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
9244 {
9245 	struct i40e_cloud_filter *cfilter;
9246 	struct hlist_node *node;
9247 
9248 	hlist_for_each_entry_safe(cfilter, node,
9249 				  &pf->cloud_filter_list, cloud_node) {
9250 		hlist_del(&cfilter->cloud_node);
9251 		kfree(cfilter);
9252 	}
9253 	pf->num_cloud_filters = 0;
9254 
9255 	if (test_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags) &&
9256 	    !test_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags)) {
9257 		set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
9258 		clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags);
9259 		clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
9260 	}
9261 }
9262 
9263 /**
9264  * i40e_close - Disables a network interface
9265  * @netdev: network interface device structure
9266  *
9267  * The close entry point is called when an interface is de-activated
9268  * by the OS.  The hardware is still under the driver's control, but
9269  * this netdev interface is disabled.
9270  *
9271  * Returns 0, this is not allowed to fail
9272  **/
9273 int i40e_close(struct net_device *netdev)
9274 {
9275 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9276 	struct i40e_vsi *vsi = np->vsi;
9277 
9278 	i40e_vsi_close(vsi);
9279 
9280 	return 0;
9281 }
9282 
9283 /**
9284  * i40e_do_reset - Start a PF or Core Reset sequence
9285  * @pf: board private structure
9286  * @reset_flags: which reset is requested
9287  * @lock_acquired: indicates whether or not the lock has been acquired
9288  * before this function was called.
9289  *
9290  * The essential difference in resets is that the PF Reset
9291  * doesn't clear the packet buffers, doesn't reset the PE
9292  * firmware, and doesn't bother the other PFs on the chip.
9293  **/
9294 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
9295 {
9296 	struct i40e_vsi *vsi;
9297 	u32 val;
9298 	int i;
9299 
9300 	/* do the biggest reset indicated */
9301 	if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
9302 
9303 		/* Request a Global Reset
9304 		 *
9305 		 * This will start the chip's countdown to the actual full
9306 		 * chip reset event, and a warning interrupt to be sent
9307 		 * to all PFs, including the requestor.  Our handler
9308 		 * for the warning interrupt will deal with the shutdown
9309 		 * and recovery of the switch setup.
9310 		 */
9311 		dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
9312 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9313 		val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
9314 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9315 
9316 	} else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
9317 
9318 		/* Request a Core Reset
9319 		 *
9320 		 * Same as Global Reset, except does *not* include the MAC/PHY
9321 		 */
9322 		dev_dbg(&pf->pdev->dev, "CoreR requested\n");
9323 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9324 		val |= I40E_GLGEN_RTRIG_CORER_MASK;
9325 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9326 		i40e_flush(&pf->hw);
9327 
9328 	} else if (reset_flags & I40E_PF_RESET_FLAG) {
9329 
9330 		/* Request a PF Reset
9331 		 *
9332 		 * Resets only the PF-specific registers
9333 		 *
9334 		 * This goes directly to the tear-down and rebuild of
9335 		 * the switch, since we need to do all the recovery as
9336 		 * for the Core Reset.
9337 		 */
9338 		dev_dbg(&pf->pdev->dev, "PFR requested\n");
9339 		i40e_handle_reset_warning(pf, lock_acquired);
9340 
9341 	} else if (reset_flags & I40E_PF_RESET_AND_REBUILD_FLAG) {
9342 		/* Request a PF Reset
9343 		 *
9344 		 * Resets PF and reinitializes PFs VSI.
9345 		 */
9346 		i40e_prep_for_reset(pf);
9347 		i40e_reset_and_rebuild(pf, true, lock_acquired);
9348 		dev_info(&pf->pdev->dev,
9349 			 test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags) ?
9350 			 "FW LLDP is disabled\n" :
9351 			 "FW LLDP is enabled\n");
9352 
9353 	} else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
9354 		/* Find the VSI(s) that requested a re-init */
9355 		dev_info(&pf->pdev->dev, "VSI reinit requested\n");
9356 
9357 		i40e_pf_for_each_vsi(pf, i, vsi) {
9358 			if (test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
9359 					       vsi->state))
9360 				i40e_vsi_reinit_locked(vsi);
9361 		}
9362 	} else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
9363 		/* Find the VSI(s) that needs to be brought down */
9364 		dev_info(&pf->pdev->dev, "VSI down requested\n");
9365 
9366 		i40e_pf_for_each_vsi(pf, i, vsi) {
9367 			if (test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
9368 					       vsi->state)) {
9369 				set_bit(__I40E_VSI_DOWN, vsi->state);
9370 				i40e_down(vsi);
9371 			}
9372 		}
9373 	} else {
9374 		dev_info(&pf->pdev->dev,
9375 			 "bad reset request 0x%08x\n", reset_flags);
9376 	}
9377 }
9378 
9379 #ifdef CONFIG_I40E_DCB
9380 /**
9381  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
9382  * @pf: board private structure
9383  * @old_cfg: current DCB config
9384  * @new_cfg: new DCB config
9385  **/
9386 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
9387 			    struct i40e_dcbx_config *old_cfg,
9388 			    struct i40e_dcbx_config *new_cfg)
9389 {
9390 	bool need_reconfig = false;
9391 
9392 	/* Check if ETS configuration has changed */
9393 	if (memcmp(&new_cfg->etscfg,
9394 		   &old_cfg->etscfg,
9395 		   sizeof(new_cfg->etscfg))) {
9396 		/* If Priority Table has changed reconfig is needed */
9397 		if (memcmp(&new_cfg->etscfg.prioritytable,
9398 			   &old_cfg->etscfg.prioritytable,
9399 			   sizeof(new_cfg->etscfg.prioritytable))) {
9400 			need_reconfig = true;
9401 			dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
9402 		}
9403 
9404 		if (memcmp(&new_cfg->etscfg.tcbwtable,
9405 			   &old_cfg->etscfg.tcbwtable,
9406 			   sizeof(new_cfg->etscfg.tcbwtable)))
9407 			dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
9408 
9409 		if (memcmp(&new_cfg->etscfg.tsatable,
9410 			   &old_cfg->etscfg.tsatable,
9411 			   sizeof(new_cfg->etscfg.tsatable)))
9412 			dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
9413 	}
9414 
9415 	/* Check if PFC configuration has changed */
9416 	if (memcmp(&new_cfg->pfc,
9417 		   &old_cfg->pfc,
9418 		   sizeof(new_cfg->pfc))) {
9419 		need_reconfig = true;
9420 		dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
9421 	}
9422 
9423 	/* Check if APP Table has changed */
9424 	if (memcmp(&new_cfg->app,
9425 		   &old_cfg->app,
9426 		   sizeof(new_cfg->app))) {
9427 		need_reconfig = true;
9428 		dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
9429 	}
9430 
9431 	dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
9432 	return need_reconfig;
9433 }
9434 
9435 /**
9436  * i40e_handle_lldp_event - Handle LLDP Change MIB event
9437  * @pf: board private structure
9438  * @e: event info posted on ARQ
9439  **/
9440 static int i40e_handle_lldp_event(struct i40e_pf *pf,
9441 				  struct i40e_arq_event_info *e)
9442 {
9443 	struct i40e_aqc_lldp_get_mib *mib =
9444 		(struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
9445 	struct i40e_hw *hw = &pf->hw;
9446 	struct i40e_dcbx_config tmp_dcbx_cfg;
9447 	bool need_reconfig = false;
9448 	int ret = 0;
9449 	u8 type;
9450 
9451 	/* X710-T*L 2.5G and 5G speeds don't support DCB */
9452 	if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9453 	    (hw->phy.link_info.link_speed &
9454 	     ~(I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB)) &&
9455 	     !test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
9456 		/* let firmware decide if the DCB should be disabled */
9457 		set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9458 
9459 	/* Not DCB capable or capability disabled */
9460 	if (!test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
9461 		return ret;
9462 
9463 	/* Ignore if event is not for Nearest Bridge */
9464 	type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
9465 		& I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
9466 	dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
9467 	if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
9468 		return ret;
9469 
9470 	/* Check MIB Type and return if event for Remote MIB update */
9471 	type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
9472 	dev_dbg(&pf->pdev->dev,
9473 		"LLDP event mib type %s\n", type ? "remote" : "local");
9474 	if (type == I40E_AQ_LLDP_MIB_REMOTE) {
9475 		/* Update the remote cached instance and return */
9476 		ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
9477 				I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
9478 				&hw->remote_dcbx_config);
9479 		goto exit;
9480 	}
9481 
9482 	/* Store the old configuration */
9483 	tmp_dcbx_cfg = hw->local_dcbx_config;
9484 
9485 	/* Reset the old DCBx configuration data */
9486 	memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
9487 	/* Get updated DCBX data from firmware */
9488 	ret = i40e_get_dcb_config(&pf->hw);
9489 	if (ret) {
9490 		/* X710-T*L 2.5G and 5G speeds don't support DCB */
9491 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9492 		    (hw->phy.link_info.link_speed &
9493 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
9494 			dev_warn(&pf->pdev->dev,
9495 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
9496 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9497 		} else {
9498 			dev_info(&pf->pdev->dev,
9499 				 "Failed querying DCB configuration data from firmware, err %pe aq_err %s\n",
9500 				 ERR_PTR(ret),
9501 				 i40e_aq_str(&pf->hw,
9502 					     pf->hw.aq.asq_last_status));
9503 		}
9504 		goto exit;
9505 	}
9506 
9507 	/* No change detected in DCBX configs */
9508 	if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
9509 		    sizeof(tmp_dcbx_cfg))) {
9510 		dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
9511 		goto exit;
9512 	}
9513 
9514 	need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
9515 					       &hw->local_dcbx_config);
9516 
9517 	i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
9518 
9519 	if (!need_reconfig)
9520 		goto exit;
9521 
9522 	/* Enable DCB tagging only when more than one TC */
9523 	if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
9524 		set_bit(I40E_FLAG_DCB_ENA, pf->flags);
9525 	else
9526 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
9527 
9528 	set_bit(__I40E_PORT_SUSPENDED, pf->state);
9529 	/* Reconfiguration needed quiesce all VSIs */
9530 	i40e_pf_quiesce_all_vsi(pf);
9531 
9532 	/* Changes in configuration update VEB/VSI */
9533 	i40e_dcb_reconfigure(pf);
9534 
9535 	ret = i40e_resume_port_tx(pf);
9536 
9537 	clear_bit(__I40E_PORT_SUSPENDED, pf->state);
9538 	/* In case of error no point in resuming VSIs */
9539 	if (ret)
9540 		goto exit;
9541 
9542 	/* Wait for the PF's queues to be disabled */
9543 	ret = i40e_pf_wait_queues_disabled(pf);
9544 	if (ret) {
9545 		/* Schedule PF reset to recover */
9546 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9547 		i40e_service_event_schedule(pf);
9548 	} else {
9549 		i40e_pf_unquiesce_all_vsi(pf);
9550 		set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
9551 		set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
9552 	}
9553 
9554 exit:
9555 	return ret;
9556 }
9557 #endif /* CONFIG_I40E_DCB */
9558 
9559 /**
9560  * i40e_do_reset_safe - Protected reset path for userland calls.
9561  * @pf: board private structure
9562  * @reset_flags: which reset is requested
9563  *
9564  **/
9565 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
9566 {
9567 	rtnl_lock();
9568 	i40e_do_reset(pf, reset_flags, true);
9569 	rtnl_unlock();
9570 }
9571 
9572 /**
9573  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
9574  * @pf: board private structure
9575  * @e: event info posted on ARQ
9576  *
9577  * Handler for LAN Queue Overflow Event generated by the firmware for PF
9578  * and VF queues
9579  **/
9580 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
9581 					   struct i40e_arq_event_info *e)
9582 {
9583 	struct i40e_aqc_lan_overflow *data =
9584 		(struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
9585 	u32 queue = le32_to_cpu(data->prtdcb_rupto);
9586 	u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
9587 	struct i40e_hw *hw = &pf->hw;
9588 	struct i40e_vf *vf;
9589 	u16 vf_id;
9590 
9591 	dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
9592 		queue, qtx_ctl);
9593 
9594 	if (FIELD_GET(I40E_QTX_CTL_PFVF_Q_MASK, qtx_ctl) !=
9595 	    I40E_QTX_CTL_VF_QUEUE)
9596 		return;
9597 
9598 	/* Queue belongs to VF, find the VF and issue VF reset */
9599 	vf_id = FIELD_GET(I40E_QTX_CTL_VFVM_INDX_MASK, qtx_ctl);
9600 	vf_id -= hw->func_caps.vf_base_id;
9601 	vf = &pf->vf[vf_id];
9602 	i40e_vc_notify_vf_reset(vf);
9603 	/* Allow VF to process pending reset notification */
9604 	msleep(20);
9605 	i40e_reset_vf(vf, false);
9606 }
9607 
9608 /**
9609  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
9610  * @pf: board private structure
9611  **/
9612 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
9613 {
9614 	u32 val, fcnt_prog;
9615 
9616 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9617 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
9618 		    FIELD_GET(I40E_PFQF_FDSTAT_BEST_CNT_MASK, val);
9619 	return fcnt_prog;
9620 }
9621 
9622 /**
9623  * i40e_get_global_fd_count - Get total FD filters programmed on device
9624  * @pf: board private structure
9625  **/
9626 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
9627 {
9628 	u32 val, fcnt_prog;
9629 
9630 	val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
9631 	fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
9632 		    FIELD_GET(I40E_GLQF_FDCNT_0_BESTCNT_MASK, val);
9633 	return fcnt_prog;
9634 }
9635 
9636 /**
9637  * i40e_reenable_fdir_sb - Restore FDir SB capability
9638  * @pf: board private structure
9639  **/
9640 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
9641 {
9642 	if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
9643 		if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
9644 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9645 			dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
9646 }
9647 
9648 /**
9649  * i40e_reenable_fdir_atr - Restore FDir ATR capability
9650  * @pf: board private structure
9651  **/
9652 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
9653 {
9654 	if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
9655 		/* ATR uses the same filtering logic as SB rules. It only
9656 		 * functions properly if the input set mask is at the default
9657 		 * settings. It is safe to restore the default input set
9658 		 * because there are no active TCPv4 filter rules.
9659 		 */
9660 		i40e_write_fd_input_set(pf, LIBIE_FILTER_PCTYPE_NONF_IPV4_TCP,
9661 					I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9662 					I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9663 
9664 		if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
9665 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9666 			dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
9667 	}
9668 }
9669 
9670 /**
9671  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
9672  * @pf: board private structure
9673  * @filter: FDir filter to remove
9674  */
9675 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
9676 				       struct i40e_fdir_filter *filter)
9677 {
9678 	/* Update counters */
9679 	pf->fdir_pf_active_filters--;
9680 	pf->fd_inv = 0;
9681 
9682 	switch (filter->flow_type) {
9683 	case TCP_V4_FLOW:
9684 		pf->fd_tcp4_filter_cnt--;
9685 		break;
9686 	case UDP_V4_FLOW:
9687 		pf->fd_udp4_filter_cnt--;
9688 		break;
9689 	case SCTP_V4_FLOW:
9690 		pf->fd_sctp4_filter_cnt--;
9691 		break;
9692 	case TCP_V6_FLOW:
9693 		pf->fd_tcp6_filter_cnt--;
9694 		break;
9695 	case UDP_V6_FLOW:
9696 		pf->fd_udp6_filter_cnt--;
9697 		break;
9698 	case SCTP_V6_FLOW:
9699 		pf->fd_udp6_filter_cnt--;
9700 		break;
9701 	case IP_USER_FLOW:
9702 		switch (filter->ipl4_proto) {
9703 		case IPPROTO_TCP:
9704 			pf->fd_tcp4_filter_cnt--;
9705 			break;
9706 		case IPPROTO_UDP:
9707 			pf->fd_udp4_filter_cnt--;
9708 			break;
9709 		case IPPROTO_SCTP:
9710 			pf->fd_sctp4_filter_cnt--;
9711 			break;
9712 		case IPPROTO_IP:
9713 			pf->fd_ip4_filter_cnt--;
9714 			break;
9715 		}
9716 		break;
9717 	case IPV6_USER_FLOW:
9718 		switch (filter->ipl4_proto) {
9719 		case IPPROTO_TCP:
9720 			pf->fd_tcp6_filter_cnt--;
9721 			break;
9722 		case IPPROTO_UDP:
9723 			pf->fd_udp6_filter_cnt--;
9724 			break;
9725 		case IPPROTO_SCTP:
9726 			pf->fd_sctp6_filter_cnt--;
9727 			break;
9728 		case IPPROTO_IP:
9729 			pf->fd_ip6_filter_cnt--;
9730 			break;
9731 		}
9732 		break;
9733 	}
9734 
9735 	/* Remove the filter from the list and free memory */
9736 	hlist_del(&filter->fdir_node);
9737 	kfree(filter);
9738 }
9739 
9740 /**
9741  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
9742  * @pf: board private structure
9743  **/
9744 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
9745 {
9746 	struct i40e_fdir_filter *filter;
9747 	u32 fcnt_prog, fcnt_avail;
9748 	struct hlist_node *node;
9749 
9750 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9751 		return;
9752 
9753 	/* Check if we have enough room to re-enable FDir SB capability. */
9754 	fcnt_prog = i40e_get_global_fd_count(pf);
9755 	fcnt_avail = pf->fdir_pf_filter_count;
9756 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
9757 	    (pf->fd_add_err == 0) ||
9758 	    (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
9759 		i40e_reenable_fdir_sb(pf);
9760 
9761 	/* We should wait for even more space before re-enabling ATR.
9762 	 * Additionally, we cannot enable ATR as long as we still have TCP SB
9763 	 * rules active.
9764 	 */
9765 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
9766 	    pf->fd_tcp4_filter_cnt == 0 && pf->fd_tcp6_filter_cnt == 0)
9767 		i40e_reenable_fdir_atr(pf);
9768 
9769 	/* if hw had a problem adding a filter, delete it */
9770 	if (pf->fd_inv > 0) {
9771 		hlist_for_each_entry_safe(filter, node,
9772 					  &pf->fdir_filter_list, fdir_node)
9773 			if (filter->fd_id == pf->fd_inv)
9774 				i40e_delete_invalid_filter(pf, filter);
9775 	}
9776 }
9777 
9778 #define I40E_MIN_FD_FLUSH_INTERVAL 10
9779 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
9780 /**
9781  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
9782  * @pf: board private structure
9783  **/
9784 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
9785 {
9786 	unsigned long min_flush_time;
9787 	int flush_wait_retry = 50;
9788 	bool disable_atr = false;
9789 	int fd_room;
9790 	int reg;
9791 
9792 	if (!time_after(jiffies, pf->fd_flush_timestamp +
9793 				 (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
9794 		return;
9795 
9796 	/* If the flush is happening too quick and we have mostly SB rules we
9797 	 * should not re-enable ATR for some time.
9798 	 */
9799 	min_flush_time = pf->fd_flush_timestamp +
9800 			 (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
9801 	fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
9802 
9803 	if (!(time_after(jiffies, min_flush_time)) &&
9804 	    (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
9805 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9806 			dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
9807 		disable_atr = true;
9808 	}
9809 
9810 	pf->fd_flush_timestamp = jiffies;
9811 	set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9812 	/* flush all filters */
9813 	wr32(&pf->hw, I40E_PFQF_CTL_1,
9814 	     I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
9815 	i40e_flush(&pf->hw);
9816 	pf->fd_flush_cnt++;
9817 	pf->fd_add_err = 0;
9818 	do {
9819 		/* Check FD flush status every 5-6msec */
9820 		usleep_range(5000, 6000);
9821 		reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
9822 		if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
9823 			break;
9824 	} while (flush_wait_retry--);
9825 	if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
9826 		dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
9827 	} else {
9828 		/* replay sideband filters */
9829 		i40e_fdir_filter_restore(i40e_pf_get_main_vsi(pf));
9830 		if (!disable_atr && !pf->fd_tcp4_filter_cnt)
9831 			clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9832 		clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
9833 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9834 			dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
9835 	}
9836 }
9837 
9838 /**
9839  * i40e_get_current_atr_cnt - Get the count of total FD ATR filters programmed
9840  * @pf: board private structure
9841  **/
9842 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
9843 {
9844 	return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
9845 }
9846 
9847 /**
9848  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
9849  * @pf: board private structure
9850  **/
9851 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
9852 {
9853 
9854 	/* if interface is down do nothing */
9855 	if (test_bit(__I40E_DOWN, pf->state))
9856 		return;
9857 
9858 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9859 		i40e_fdir_flush_and_replay(pf);
9860 
9861 	i40e_fdir_check_and_reenable(pf);
9862 
9863 }
9864 
9865 /**
9866  * i40e_vsi_link_event - notify VSI of a link event
9867  * @vsi: vsi to be notified
9868  * @link_up: link up or down
9869  **/
9870 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
9871 {
9872 	if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
9873 		return;
9874 
9875 	switch (vsi->type) {
9876 	case I40E_VSI_MAIN:
9877 		if (!vsi->netdev || !vsi->netdev_registered)
9878 			break;
9879 
9880 		if (link_up) {
9881 			netif_carrier_on(vsi->netdev);
9882 			netif_tx_wake_all_queues(vsi->netdev);
9883 		} else {
9884 			netif_carrier_off(vsi->netdev);
9885 			netif_tx_stop_all_queues(vsi->netdev);
9886 		}
9887 		break;
9888 
9889 	case I40E_VSI_SRIOV:
9890 	case I40E_VSI_VMDQ2:
9891 	case I40E_VSI_CTRL:
9892 	case I40E_VSI_IWARP:
9893 	case I40E_VSI_MIRROR:
9894 	default:
9895 		/* there is no notification for other VSIs */
9896 		break;
9897 	}
9898 }
9899 
9900 /**
9901  * i40e_veb_link_event - notify elements on the veb of a link event
9902  * @veb: veb to be notified
9903  * @link_up: link up or down
9904  **/
9905 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
9906 {
9907 	struct i40e_vsi *vsi;
9908 	struct i40e_pf *pf;
9909 	int i;
9910 
9911 	if (!veb || !veb->pf)
9912 		return;
9913 	pf = veb->pf;
9914 
9915 	/* Send link event to contained VSIs */
9916 	i40e_pf_for_each_vsi(pf, i, vsi)
9917 		if (vsi->uplink_seid == veb->seid)
9918 			i40e_vsi_link_event(vsi, link_up);
9919 }
9920 
9921 /**
9922  * i40e_link_event - Update netif_carrier status
9923  * @pf: board private structure
9924  **/
9925 static void i40e_link_event(struct i40e_pf *pf)
9926 {
9927 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
9928 	struct i40e_veb *veb = i40e_pf_get_main_veb(pf);
9929 	u8 new_link_speed, old_link_speed;
9930 	bool new_link, old_link;
9931 	int status;
9932 #ifdef CONFIG_I40E_DCB
9933 	int err;
9934 #endif /* CONFIG_I40E_DCB */
9935 
9936 	/* set this to force the get_link_status call to refresh state */
9937 	pf->hw.phy.get_link_info = true;
9938 	old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9939 	status = i40e_get_link_status(&pf->hw, &new_link);
9940 
9941 	/* On success, disable temp link polling */
9942 	if (status == 0) {
9943 		clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9944 	} else {
9945 		/* Enable link polling temporarily until i40e_get_link_status
9946 		 * returns 0
9947 		 */
9948 		set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9949 		dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9950 			status);
9951 		return;
9952 	}
9953 
9954 	old_link_speed = pf->hw.phy.link_info_old.link_speed;
9955 	new_link_speed = pf->hw.phy.link_info.link_speed;
9956 
9957 	if (new_link == old_link &&
9958 	    new_link_speed == old_link_speed &&
9959 	    (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9960 	     new_link == netif_carrier_ok(vsi->netdev)))
9961 		return;
9962 
9963 	if (!new_link && old_link)
9964 		pf->link_down_events++;
9965 
9966 	i40e_print_link_message(vsi, new_link);
9967 
9968 	/* Notify the base of the switch tree connected to
9969 	 * the link.  Floating VEBs are not notified.
9970 	 */
9971 	if (veb)
9972 		i40e_veb_link_event(veb, new_link);
9973 	else
9974 		i40e_vsi_link_event(vsi, new_link);
9975 
9976 	if (pf->vf)
9977 		i40e_vc_notify_link_state(pf);
9978 
9979 	if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
9980 		i40e_ptp_set_increment(pf);
9981 #ifdef CONFIG_I40E_DCB
9982 	if (new_link == old_link)
9983 		return;
9984 	/* Not SW DCB so firmware will take care of default settings */
9985 	if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED)
9986 		return;
9987 
9988 	/* We cover here only link down, as after link up in case of SW DCB
9989 	 * SW LLDP agent will take care of setting it up
9990 	 */
9991 	if (!new_link) {
9992 		dev_dbg(&pf->pdev->dev, "Reconfig DCB to single TC as result of Link Down\n");
9993 		memset(&pf->tmp_cfg, 0, sizeof(pf->tmp_cfg));
9994 		err = i40e_dcb_sw_default_config(pf);
9995 		if (err) {
9996 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9997 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
9998 		} else {
9999 			pf->dcbx_cap = DCB_CAP_DCBX_HOST |
10000 				       DCB_CAP_DCBX_VER_IEEE;
10001 			set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
10002 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
10003 		}
10004 	}
10005 #endif /* CONFIG_I40E_DCB */
10006 }
10007 
10008 /**
10009  * i40e_watchdog_subtask - periodic checks not using event driven response
10010  * @pf: board private structure
10011  **/
10012 static void i40e_watchdog_subtask(struct i40e_pf *pf)
10013 {
10014 	struct i40e_vsi *vsi;
10015 	struct i40e_veb *veb;
10016 	int i;
10017 
10018 	/* if interface is down do nothing */
10019 	if (test_bit(__I40E_DOWN, pf->state) ||
10020 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
10021 		return;
10022 
10023 	/* make sure we don't do these things too often */
10024 	if (time_before(jiffies, (pf->service_timer_previous +
10025 				  pf->service_timer_period)))
10026 		return;
10027 	pf->service_timer_previous = jiffies;
10028 
10029 	if (test_bit(I40E_FLAG_LINK_POLLING_ENA, pf->flags) ||
10030 	    test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
10031 		i40e_link_event(pf);
10032 
10033 	/* Update the stats for active netdevs so the network stack
10034 	 * can look at updated numbers whenever it cares to
10035 	 */
10036 	i40e_pf_for_each_vsi(pf, i, vsi)
10037 		if (vsi->netdev)
10038 			i40e_update_stats(vsi);
10039 
10040 	if (test_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags)) {
10041 		/* Update the stats for the active switching components */
10042 		i40e_pf_for_each_veb(pf, i, veb)
10043 			i40e_update_veb_stats(veb);
10044 	}
10045 
10046 	i40e_ptp_rx_hang(pf);
10047 	i40e_ptp_tx_hang(pf);
10048 }
10049 
10050 /**
10051  * i40e_reset_subtask - Set up for resetting the device and driver
10052  * @pf: board private structure
10053  **/
10054 static void i40e_reset_subtask(struct i40e_pf *pf)
10055 {
10056 	u32 reset_flags = 0;
10057 
10058 	if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
10059 		reset_flags |= BIT(__I40E_REINIT_REQUESTED);
10060 		clear_bit(__I40E_REINIT_REQUESTED, pf->state);
10061 	}
10062 	if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
10063 		reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
10064 		clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
10065 	}
10066 	if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
10067 		reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
10068 		clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
10069 	}
10070 	if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
10071 		reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
10072 		clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
10073 	}
10074 	if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
10075 		reset_flags |= BIT(__I40E_DOWN_REQUESTED);
10076 		clear_bit(__I40E_DOWN_REQUESTED, pf->state);
10077 	}
10078 
10079 	/* If there's a recovery already waiting, it takes
10080 	 * precedence before starting a new reset sequence.
10081 	 */
10082 	if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
10083 		i40e_prep_for_reset(pf);
10084 		i40e_reset(pf);
10085 		i40e_rebuild(pf, false, false);
10086 	}
10087 
10088 	/* If we're already down or resetting, just bail */
10089 	if (reset_flags &&
10090 	    !test_bit(__I40E_DOWN, pf->state) &&
10091 	    !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
10092 		i40e_do_reset(pf, reset_flags, false);
10093 	}
10094 }
10095 
10096 /**
10097  * i40e_handle_link_event - Handle link event
10098  * @pf: board private structure
10099  * @e: event info posted on ARQ
10100  **/
10101 static void i40e_handle_link_event(struct i40e_pf *pf,
10102 				   struct i40e_arq_event_info *e)
10103 {
10104 	struct i40e_aqc_get_link_status *status =
10105 		(struct i40e_aqc_get_link_status *)&e->desc.params.raw;
10106 
10107 	/* Do a new status request to re-enable LSE reporting
10108 	 * and load new status information into the hw struct
10109 	 * This completely ignores any state information
10110 	 * in the ARQ event info, instead choosing to always
10111 	 * issue the AQ update link status command.
10112 	 */
10113 	i40e_link_event(pf);
10114 
10115 	/* Check if module meets thermal requirements */
10116 	if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
10117 		dev_err(&pf->pdev->dev,
10118 			"Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
10119 		dev_err(&pf->pdev->dev,
10120 			"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10121 	} else {
10122 		/* check for unqualified module, if link is down, suppress
10123 		 * the message if link was forced to be down.
10124 		 */
10125 		if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
10126 		    (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
10127 		    (!(status->link_info & I40E_AQ_LINK_UP)) &&
10128 		    (!test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags))) {
10129 			dev_err(&pf->pdev->dev,
10130 				"Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
10131 			dev_err(&pf->pdev->dev,
10132 				"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10133 		}
10134 	}
10135 }
10136 
10137 /**
10138  * i40e_clean_adminq_subtask - Clean the AdminQ rings
10139  * @pf: board private structure
10140  **/
10141 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
10142 {
10143 	struct i40e_arq_event_info event;
10144 	struct i40e_hw *hw = &pf->hw;
10145 	u16 pending, i = 0;
10146 	u16 opcode;
10147 	u32 oldval;
10148 	int ret;
10149 	u32 val;
10150 
10151 	/* Do not run clean AQ when PF reset fails */
10152 	if (test_bit(__I40E_RESET_FAILED, pf->state))
10153 		return;
10154 
10155 	/* check for error indications */
10156 	val = rd32(&pf->hw, I40E_PF_ARQLEN);
10157 	oldval = val;
10158 	if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
10159 		if (hw->debug_mask & I40E_DEBUG_AQ)
10160 			dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
10161 		val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
10162 	}
10163 	if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
10164 		if (hw->debug_mask & I40E_DEBUG_AQ)
10165 			dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
10166 		val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
10167 		pf->arq_overflows++;
10168 	}
10169 	if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
10170 		if (hw->debug_mask & I40E_DEBUG_AQ)
10171 			dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
10172 		val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
10173 	}
10174 	if (oldval != val)
10175 		wr32(&pf->hw, I40E_PF_ARQLEN, val);
10176 
10177 	val = rd32(&pf->hw, I40E_PF_ATQLEN);
10178 	oldval = val;
10179 	if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
10180 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10181 			dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
10182 		val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
10183 	}
10184 	if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
10185 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10186 			dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
10187 		val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
10188 	}
10189 	if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
10190 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10191 			dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
10192 		val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
10193 	}
10194 	if (oldval != val)
10195 		wr32(&pf->hw, I40E_PF_ATQLEN, val);
10196 
10197 	event.buf_len = I40E_MAX_AQ_BUF_SIZE;
10198 	event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
10199 	if (!event.msg_buf)
10200 		return;
10201 
10202 	do {
10203 		ret = i40e_clean_arq_element(hw, &event, &pending);
10204 		if (ret == -EALREADY)
10205 			break;
10206 		else if (ret) {
10207 			dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
10208 			break;
10209 		}
10210 
10211 		opcode = le16_to_cpu(event.desc.opcode);
10212 		switch (opcode) {
10213 
10214 		case i40e_aqc_opc_get_link_status:
10215 			rtnl_lock();
10216 			i40e_handle_link_event(pf, &event);
10217 			rtnl_unlock();
10218 			break;
10219 		case i40e_aqc_opc_send_msg_to_pf:
10220 			ret = i40e_vc_process_vf_msg(pf,
10221 					le16_to_cpu(event.desc.retval),
10222 					le32_to_cpu(event.desc.cookie_high),
10223 					le32_to_cpu(event.desc.cookie_low),
10224 					event.msg_buf,
10225 					event.msg_len);
10226 			break;
10227 		case i40e_aqc_opc_lldp_update_mib:
10228 			dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
10229 #ifdef CONFIG_I40E_DCB
10230 			rtnl_lock();
10231 			i40e_handle_lldp_event(pf, &event);
10232 			rtnl_unlock();
10233 #endif /* CONFIG_I40E_DCB */
10234 			break;
10235 		case i40e_aqc_opc_event_lan_overflow:
10236 			dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
10237 			i40e_handle_lan_overflow_event(pf, &event);
10238 			break;
10239 		case i40e_aqc_opc_send_msg_to_peer:
10240 			dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
10241 			break;
10242 		case i40e_aqc_opc_nvm_erase:
10243 		case i40e_aqc_opc_nvm_update:
10244 		case i40e_aqc_opc_oem_post_update:
10245 			i40e_debug(&pf->hw, I40E_DEBUG_NVM,
10246 				   "ARQ NVM operation 0x%04x completed\n",
10247 				   opcode);
10248 			break;
10249 		default:
10250 			dev_info(&pf->pdev->dev,
10251 				 "ARQ: Unknown event 0x%04x ignored\n",
10252 				 opcode);
10253 			break;
10254 		}
10255 	} while (i++ < I40E_AQ_WORK_LIMIT);
10256 
10257 	if (i < I40E_AQ_WORK_LIMIT)
10258 		clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
10259 
10260 	/* re-enable Admin queue interrupt cause */
10261 	val = rd32(hw, I40E_PFINT_ICR0_ENA);
10262 	val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
10263 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
10264 	i40e_flush(hw);
10265 
10266 	kfree(event.msg_buf);
10267 }
10268 
10269 /**
10270  * i40e_verify_eeprom - make sure eeprom is good to use
10271  * @pf: board private structure
10272  **/
10273 static void i40e_verify_eeprom(struct i40e_pf *pf)
10274 {
10275 	int err;
10276 
10277 	err = i40e_diag_eeprom_test(&pf->hw);
10278 	if (err) {
10279 		/* retry in case of garbage read */
10280 		err = i40e_diag_eeprom_test(&pf->hw);
10281 		if (err) {
10282 			dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
10283 				 err);
10284 			set_bit(__I40E_BAD_EEPROM, pf->state);
10285 		}
10286 	}
10287 
10288 	if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
10289 		dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
10290 		clear_bit(__I40E_BAD_EEPROM, pf->state);
10291 	}
10292 }
10293 
10294 /**
10295  * i40e_enable_pf_switch_lb
10296  * @pf: pointer to the PF structure
10297  *
10298  * enable switch loop back or die - no point in a return value
10299  **/
10300 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
10301 {
10302 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
10303 	struct i40e_vsi_context ctxt;
10304 	int ret;
10305 
10306 	ctxt.seid = pf->main_vsi_seid;
10307 	ctxt.pf_num = pf->hw.pf_id;
10308 	ctxt.vf_num = 0;
10309 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10310 	if (ret) {
10311 		dev_info(&pf->pdev->dev,
10312 			 "couldn't get PF vsi config, err %pe aq_err %s\n",
10313 			 ERR_PTR(ret),
10314 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10315 		return;
10316 	}
10317 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10318 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10319 	ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10320 
10321 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10322 	if (ret) {
10323 		dev_info(&pf->pdev->dev,
10324 			 "update vsi switch failed, err %pe aq_err %s\n",
10325 			 ERR_PTR(ret),
10326 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10327 	}
10328 }
10329 
10330 /**
10331  * i40e_disable_pf_switch_lb
10332  * @pf: pointer to the PF structure
10333  *
10334  * disable switch loop back or die - no point in a return value
10335  **/
10336 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
10337 {
10338 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
10339 	struct i40e_vsi_context ctxt;
10340 	int ret;
10341 
10342 	ctxt.seid = pf->main_vsi_seid;
10343 	ctxt.pf_num = pf->hw.pf_id;
10344 	ctxt.vf_num = 0;
10345 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10346 	if (ret) {
10347 		dev_info(&pf->pdev->dev,
10348 			 "couldn't get PF vsi config, err %pe aq_err %s\n",
10349 			 ERR_PTR(ret),
10350 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10351 		return;
10352 	}
10353 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10354 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10355 	ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10356 
10357 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10358 	if (ret) {
10359 		dev_info(&pf->pdev->dev,
10360 			 "update vsi switch failed, err %pe aq_err %s\n",
10361 			 ERR_PTR(ret),
10362 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10363 	}
10364 }
10365 
10366 /**
10367  * i40e_config_bridge_mode - Configure the HW bridge mode
10368  * @veb: pointer to the bridge instance
10369  *
10370  * Configure the loop back mode for the LAN VSI that is downlink to the
10371  * specified HW bridge instance. It is expected this function is called
10372  * when a new HW bridge is instantiated.
10373  **/
10374 static void i40e_config_bridge_mode(struct i40e_veb *veb)
10375 {
10376 	struct i40e_pf *pf = veb->pf;
10377 
10378 	if (pf->hw.debug_mask & I40E_DEBUG_LAN)
10379 		dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
10380 			 veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
10381 	if (veb->bridge_mode & BRIDGE_MODE_VEPA)
10382 		i40e_disable_pf_switch_lb(pf);
10383 	else
10384 		i40e_enable_pf_switch_lb(pf);
10385 }
10386 
10387 /**
10388  * i40e_reconstitute_veb - rebuild the VEB and VSIs connected to it
10389  * @veb: pointer to the VEB instance
10390  *
10391  * This is a function that builds the attached VSIs. We track the connections
10392  * through our own index numbers because the seid's from the HW could change
10393  * across the reset.
10394  **/
10395 static int i40e_reconstitute_veb(struct i40e_veb *veb)
10396 {
10397 	struct i40e_vsi *ctl_vsi = NULL;
10398 	struct i40e_pf *pf = veb->pf;
10399 	struct i40e_vsi *vsi;
10400 	int v, ret;
10401 
10402 	/* As we do not maintain PV (port virtualizer) switch element then
10403 	 * there can be only one non-floating VEB that have uplink to MAC SEID
10404 	 * and its control VSI is the main one.
10405 	 */
10406 	if (WARN_ON(veb->uplink_seid && veb->uplink_seid != pf->mac_seid)) {
10407 		dev_err(&pf->pdev->dev,
10408 			"Invalid uplink SEID for VEB %d\n", veb->idx);
10409 		return -ENOENT;
10410 	}
10411 
10412 	if (veb->uplink_seid == pf->mac_seid) {
10413 		/* Check that the LAN VSI has VEB owning flag set */
10414 		ctl_vsi = i40e_pf_get_main_vsi(pf);
10415 
10416 		if (WARN_ON(ctl_vsi->veb_idx != veb->idx ||
10417 			    !(ctl_vsi->flags & I40E_VSI_FLAG_VEB_OWNER))) {
10418 			dev_err(&pf->pdev->dev,
10419 				"Invalid control VSI for VEB %d\n", veb->idx);
10420 			return -ENOENT;
10421 		}
10422 
10423 		/* Add the control VSI to switch */
10424 		ret = i40e_add_vsi(ctl_vsi);
10425 		if (ret) {
10426 			dev_err(&pf->pdev->dev,
10427 				"Rebuild of owner VSI for VEB %d failed: %d\n",
10428 				veb->idx, ret);
10429 			return ret;
10430 		}
10431 
10432 		i40e_vsi_reset_stats(ctl_vsi);
10433 	}
10434 
10435 	/* create the VEB in the switch and move the VSI onto the VEB */
10436 	ret = i40e_add_veb(veb, ctl_vsi);
10437 	if (ret)
10438 		return ret;
10439 
10440 	if (veb->uplink_seid) {
10441 		if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags))
10442 			veb->bridge_mode = BRIDGE_MODE_VEB;
10443 		else
10444 			veb->bridge_mode = BRIDGE_MODE_VEPA;
10445 		i40e_config_bridge_mode(veb);
10446 	}
10447 
10448 	/* create the remaining VSIs attached to this VEB */
10449 	i40e_pf_for_each_vsi(pf, v, vsi) {
10450 		if (vsi == ctl_vsi)
10451 			continue;
10452 
10453 		if (vsi->veb_idx == veb->idx) {
10454 			vsi->uplink_seid = veb->seid;
10455 			ret = i40e_add_vsi(vsi);
10456 			if (ret) {
10457 				dev_info(&pf->pdev->dev,
10458 					 "rebuild of vsi_idx %d failed: %d\n",
10459 					 v, ret);
10460 				return ret;
10461 			}
10462 			i40e_vsi_reset_stats(vsi);
10463 		}
10464 	}
10465 
10466 	return ret;
10467 }
10468 
10469 /**
10470  * i40e_get_capabilities - get info about the HW
10471  * @pf: the PF struct
10472  * @list_type: AQ capability to be queried
10473  **/
10474 static int i40e_get_capabilities(struct i40e_pf *pf,
10475 				 enum i40e_admin_queue_opc list_type)
10476 {
10477 	struct i40e_aqc_list_capabilities_element_resp *cap_buf;
10478 	u16 data_size;
10479 	int buf_len;
10480 	int err;
10481 
10482 	buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
10483 	do {
10484 		cap_buf = kzalloc(buf_len, GFP_KERNEL);
10485 		if (!cap_buf)
10486 			return -ENOMEM;
10487 
10488 		/* this loads the data into the hw struct for us */
10489 		err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
10490 						    &data_size, list_type,
10491 						    NULL);
10492 		/* data loaded, buffer no longer needed */
10493 		kfree(cap_buf);
10494 
10495 		if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
10496 			/* retry with a larger buffer */
10497 			buf_len = data_size;
10498 		} else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK || err) {
10499 			dev_info(&pf->pdev->dev,
10500 				 "capability discovery failed, err %pe aq_err %s\n",
10501 				 ERR_PTR(err),
10502 				 i40e_aq_str(&pf->hw,
10503 					     pf->hw.aq.asq_last_status));
10504 			return -ENODEV;
10505 		}
10506 	} while (err);
10507 
10508 	if (pf->hw.debug_mask & I40E_DEBUG_USER) {
10509 		if (list_type == i40e_aqc_opc_list_func_capabilities) {
10510 			dev_info(&pf->pdev->dev,
10511 				 "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",
10512 				 pf->hw.pf_id, pf->hw.func_caps.num_vfs,
10513 				 pf->hw.func_caps.num_msix_vectors,
10514 				 pf->hw.func_caps.num_msix_vectors_vf,
10515 				 pf->hw.func_caps.fd_filters_guaranteed,
10516 				 pf->hw.func_caps.fd_filters_best_effort,
10517 				 pf->hw.func_caps.num_tx_qp,
10518 				 pf->hw.func_caps.num_vsis);
10519 		} else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
10520 			dev_info(&pf->pdev->dev,
10521 				 "switch_mode=0x%04x, function_valid=0x%08x\n",
10522 				 pf->hw.dev_caps.switch_mode,
10523 				 pf->hw.dev_caps.valid_functions);
10524 			dev_info(&pf->pdev->dev,
10525 				 "SR-IOV=%d, num_vfs for all function=%u\n",
10526 				 pf->hw.dev_caps.sr_iov_1_1,
10527 				 pf->hw.dev_caps.num_vfs);
10528 			dev_info(&pf->pdev->dev,
10529 				 "num_vsis=%u, num_rx:%u, num_tx=%u\n",
10530 				 pf->hw.dev_caps.num_vsis,
10531 				 pf->hw.dev_caps.num_rx_qp,
10532 				 pf->hw.dev_caps.num_tx_qp);
10533 		}
10534 	}
10535 	if (list_type == i40e_aqc_opc_list_func_capabilities) {
10536 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
10537 		       + pf->hw.func_caps.num_vfs)
10538 		if (pf->hw.revision_id == 0 &&
10539 		    pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
10540 			dev_info(&pf->pdev->dev,
10541 				 "got num_vsis %d, setting num_vsis to %d\n",
10542 				 pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
10543 			pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
10544 		}
10545 	}
10546 	return 0;
10547 }
10548 
10549 static int i40e_vsi_clear(struct i40e_vsi *vsi);
10550 
10551 /**
10552  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
10553  * @pf: board private structure
10554  **/
10555 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
10556 {
10557 	struct i40e_vsi *main_vsi, *vsi;
10558 
10559 	/* quick workaround for an NVM issue that leaves a critical register
10560 	 * uninitialized
10561 	 */
10562 	if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
10563 		static const u32 hkey[] = {
10564 			0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
10565 			0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
10566 			0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
10567 			0x95b3a76d};
10568 		int i;
10569 
10570 		for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
10571 			wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
10572 	}
10573 
10574 	if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
10575 		return;
10576 
10577 	/* find existing VSI and see if it needs configuring */
10578 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10579 
10580 	/* create a new VSI if none exists */
10581 	if (!vsi) {
10582 		main_vsi = i40e_pf_get_main_vsi(pf);
10583 		vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR, main_vsi->seid, 0);
10584 		if (!vsi) {
10585 			dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
10586 			clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
10587 			set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
10588 			return;
10589 		}
10590 	}
10591 
10592 	i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
10593 }
10594 
10595 /**
10596  * i40e_fdir_teardown - release the Flow Director resources
10597  * @pf: board private structure
10598  **/
10599 static void i40e_fdir_teardown(struct i40e_pf *pf)
10600 {
10601 	struct i40e_vsi *vsi;
10602 
10603 	i40e_fdir_filter_exit(pf);
10604 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10605 	if (vsi)
10606 		i40e_vsi_release(vsi);
10607 }
10608 
10609 /**
10610  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
10611  * @vsi: PF main vsi
10612  * @seid: seid of main or channel VSIs
10613  *
10614  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
10615  * existed before reset
10616  **/
10617 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
10618 {
10619 	struct i40e_cloud_filter *cfilter;
10620 	struct i40e_pf *pf = vsi->back;
10621 	struct hlist_node *node;
10622 	int ret;
10623 
10624 	/* Add cloud filters back if they exist */
10625 	hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
10626 				  cloud_node) {
10627 		if (cfilter->seid != seid)
10628 			continue;
10629 
10630 		if (cfilter->dst_port)
10631 			ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
10632 								true);
10633 		else
10634 			ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
10635 
10636 		if (ret) {
10637 			dev_dbg(&pf->pdev->dev,
10638 				"Failed to rebuild cloud filter, err %pe aq_err %s\n",
10639 				ERR_PTR(ret),
10640 				i40e_aq_str(&pf->hw,
10641 					    pf->hw.aq.asq_last_status));
10642 			return ret;
10643 		}
10644 	}
10645 	return 0;
10646 }
10647 
10648 /**
10649  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
10650  * @vsi: PF main vsi
10651  *
10652  * Rebuilds channel VSIs if they existed before reset
10653  **/
10654 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
10655 {
10656 	struct i40e_channel *ch, *ch_tmp;
10657 	int ret;
10658 
10659 	if (list_empty(&vsi->ch_list))
10660 		return 0;
10661 
10662 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
10663 		if (!ch->initialized)
10664 			break;
10665 		/* Proceed with creation of channel (VMDq2) VSI */
10666 		ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
10667 		if (ret) {
10668 			dev_info(&vsi->back->pdev->dev,
10669 				 "failed to rebuild channels using uplink_seid %u\n",
10670 				 vsi->uplink_seid);
10671 			return ret;
10672 		}
10673 		/* Reconfigure TX queues using QTX_CTL register */
10674 		ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
10675 		if (ret) {
10676 			dev_info(&vsi->back->pdev->dev,
10677 				 "failed to configure TX rings for channel %u\n",
10678 				 ch->seid);
10679 			return ret;
10680 		}
10681 		/* update 'next_base_queue' */
10682 		vsi->next_base_queue = vsi->next_base_queue +
10683 							ch->num_queue_pairs;
10684 		if (ch->max_tx_rate) {
10685 			u64 credits = ch->max_tx_rate;
10686 
10687 			if (i40e_set_bw_limit(vsi, ch->seid,
10688 					      ch->max_tx_rate))
10689 				return -EINVAL;
10690 
10691 			do_div(credits, I40E_BW_CREDIT_DIVISOR);
10692 			dev_dbg(&vsi->back->pdev->dev,
10693 				"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10694 				ch->max_tx_rate,
10695 				credits,
10696 				ch->seid);
10697 		}
10698 		ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
10699 		if (ret) {
10700 			dev_dbg(&vsi->back->pdev->dev,
10701 				"Failed to rebuild cloud filters for channel VSI %u\n",
10702 				ch->seid);
10703 			return ret;
10704 		}
10705 	}
10706 	return 0;
10707 }
10708 
10709 /**
10710  * i40e_clean_xps_state - clean xps state for every tx_ring
10711  * @vsi: ptr to the VSI
10712  **/
10713 static void i40e_clean_xps_state(struct i40e_vsi *vsi)
10714 {
10715 	int i;
10716 
10717 	if (vsi->tx_rings)
10718 		for (i = 0; i < vsi->num_queue_pairs; i++)
10719 			if (vsi->tx_rings[i])
10720 				clear_bit(__I40E_TX_XPS_INIT_DONE,
10721 					  vsi->tx_rings[i]->state);
10722 }
10723 
10724 /**
10725  * i40e_prep_for_reset - prep for the core to reset
10726  * @pf: board private structure
10727  *
10728  * Close up the VFs and other things in prep for PF Reset.
10729   **/
10730 static void i40e_prep_for_reset(struct i40e_pf *pf)
10731 {
10732 	struct i40e_hw *hw = &pf->hw;
10733 	struct i40e_vsi *vsi;
10734 	int ret = 0;
10735 	u32 v;
10736 
10737 	clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
10738 	if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
10739 		return;
10740 	if (i40e_check_asq_alive(&pf->hw))
10741 		i40e_vc_notify_reset(pf);
10742 
10743 	dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
10744 
10745 	/* quiesce the VSIs and their queues that are not already DOWN */
10746 	i40e_pf_quiesce_all_vsi(pf);
10747 
10748 	i40e_pf_for_each_vsi(pf, v, vsi) {
10749 		i40e_clean_xps_state(vsi);
10750 		vsi->seid = 0;
10751 	}
10752 
10753 	i40e_shutdown_adminq(&pf->hw);
10754 
10755 	/* call shutdown HMC */
10756 	if (hw->hmc.hmc_obj) {
10757 		ret = i40e_shutdown_lan_hmc(hw);
10758 		if (ret)
10759 			dev_warn(&pf->pdev->dev,
10760 				 "shutdown_lan_hmc failed: %d\n", ret);
10761 	}
10762 
10763 	/* Save the current PTP time so that we can restore the time after the
10764 	 * reset completes.
10765 	 */
10766 	i40e_ptp_save_hw_time(pf);
10767 }
10768 
10769 /**
10770  * i40e_send_version - update firmware with driver version
10771  * @pf: PF struct
10772  */
10773 static void i40e_send_version(struct i40e_pf *pf)
10774 {
10775 	struct i40e_driver_version dv;
10776 
10777 	dv.major_version = 0xff;
10778 	dv.minor_version = 0xff;
10779 	dv.build_version = 0xff;
10780 	dv.subbuild_version = 0;
10781 	strscpy(dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string));
10782 	i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
10783 }
10784 
10785 /**
10786  * i40e_get_oem_version - get OEM specific version information
10787  * @hw: pointer to the hardware structure
10788  **/
10789 static void i40e_get_oem_version(struct i40e_hw *hw)
10790 {
10791 	u16 block_offset = 0xffff;
10792 	u16 block_length = 0;
10793 	u16 capabilities = 0;
10794 	u16 gen_snap = 0;
10795 	u16 release = 0;
10796 
10797 #define I40E_SR_NVM_OEM_VERSION_PTR		0x1B
10798 #define I40E_NVM_OEM_LENGTH_OFFSET		0x00
10799 #define I40E_NVM_OEM_CAPABILITIES_OFFSET	0x01
10800 #define I40E_NVM_OEM_GEN_OFFSET			0x02
10801 #define I40E_NVM_OEM_RELEASE_OFFSET		0x03
10802 #define I40E_NVM_OEM_CAPABILITIES_MASK		0x000F
10803 #define I40E_NVM_OEM_LENGTH			3
10804 
10805 	/* Check if pointer to OEM version block is valid. */
10806 	i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
10807 	if (block_offset == 0xffff)
10808 		return;
10809 
10810 	/* Check if OEM version block has correct length. */
10811 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
10812 			   &block_length);
10813 	if (block_length < I40E_NVM_OEM_LENGTH)
10814 		return;
10815 
10816 	/* Check if OEM version format is as expected. */
10817 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
10818 			   &capabilities);
10819 	if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
10820 		return;
10821 
10822 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
10823 			   &gen_snap);
10824 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
10825 			   &release);
10826 	hw->nvm.oem_ver =
10827 		FIELD_PREP(I40E_OEM_GEN_MASK | I40E_OEM_SNAP_MASK, gen_snap) |
10828 		FIELD_PREP(I40E_OEM_RELEASE_MASK, release);
10829 	hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
10830 }
10831 
10832 /**
10833  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
10834  * @pf: board private structure
10835  **/
10836 static int i40e_reset(struct i40e_pf *pf)
10837 {
10838 	struct i40e_hw *hw = &pf->hw;
10839 	int ret;
10840 
10841 	ret = i40e_pf_reset(hw);
10842 	if (ret) {
10843 		dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
10844 		set_bit(__I40E_RESET_FAILED, pf->state);
10845 		clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10846 	} else {
10847 		pf->pfr_count++;
10848 	}
10849 	return ret;
10850 }
10851 
10852 /**
10853  * i40e_rebuild - rebuild using a saved config
10854  * @pf: board private structure
10855  * @reinit: if the Main VSI needs to re-initialized.
10856  * @lock_acquired: indicates whether or not the lock has been acquired
10857  * before this function was called.
10858  **/
10859 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
10860 {
10861 	const bool is_recovery_mode_reported = i40e_check_recovery_mode(pf);
10862 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
10863 	struct i40e_hw *hw = &pf->hw;
10864 	struct i40e_veb *veb;
10865 	int ret;
10866 	u32 val;
10867 	int v;
10868 
10869 	if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10870 	    is_recovery_mode_reported)
10871 		i40e_set_ethtool_ops(vsi->netdev);
10872 
10873 	if (test_bit(__I40E_DOWN, pf->state) &&
10874 	    !test_bit(__I40E_RECOVERY_MODE, pf->state))
10875 		goto clear_recovery;
10876 	dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
10877 
10878 	/* rebuild the basics for the AdminQ, HMC, and initial HW switch */
10879 	ret = i40e_init_adminq(&pf->hw);
10880 	if (ret) {
10881 		dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %pe aq_err %s\n",
10882 			 ERR_PTR(ret),
10883 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10884 		goto clear_recovery;
10885 	}
10886 	i40e_get_oem_version(&pf->hw);
10887 
10888 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state)) {
10889 		/* The following delay is necessary for firmware update. */
10890 		mdelay(1000);
10891 	}
10892 
10893 	/* re-verify the eeprom if we just had an EMP reset */
10894 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
10895 		i40e_verify_eeprom(pf);
10896 
10897 	/* if we are going out of or into recovery mode we have to act
10898 	 * accordingly with regard to resources initialization
10899 	 * and deinitialization
10900 	 */
10901 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10902 		if (i40e_get_capabilities(pf,
10903 					  i40e_aqc_opc_list_func_capabilities))
10904 			goto end_unlock;
10905 
10906 		if (is_recovery_mode_reported) {
10907 			/* we're staying in recovery mode so we'll reinitialize
10908 			 * misc vector here
10909 			 */
10910 			if (i40e_setup_misc_vector_for_recovery_mode(pf))
10911 				goto end_unlock;
10912 		} else {
10913 			if (!lock_acquired)
10914 				rtnl_lock();
10915 			/* we're going out of recovery mode so we'll free
10916 			 * the IRQ allocated specifically for recovery mode
10917 			 * and restore the interrupt scheme
10918 			 */
10919 			free_irq(pf->pdev->irq, pf);
10920 			i40e_clear_interrupt_scheme(pf);
10921 			if (i40e_restore_interrupt_scheme(pf))
10922 				goto end_unlock;
10923 		}
10924 
10925 		/* tell the firmware that we're starting */
10926 		i40e_send_version(pf);
10927 
10928 		/* bail out in case recovery mode was detected, as there is
10929 		 * no need for further configuration.
10930 		 */
10931 		goto end_unlock;
10932 	}
10933 
10934 	i40e_clear_pxe_mode(hw);
10935 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10936 	if (ret)
10937 		goto end_core_reset;
10938 
10939 	ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10940 				hw->func_caps.num_rx_qp, 0, 0);
10941 	if (ret) {
10942 		dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10943 		goto end_core_reset;
10944 	}
10945 	ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10946 	if (ret) {
10947 		dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10948 		goto end_core_reset;
10949 	}
10950 
10951 #ifdef CONFIG_I40E_DCB
10952 	/* Enable FW to write a default DCB config on link-up
10953 	 * unless I40E_FLAG_TC_MQPRIO was enabled or DCB
10954 	 * is not supported with new link speed
10955 	 */
10956 	if (i40e_is_tc_mqprio_enabled(pf)) {
10957 		i40e_aq_set_dcb_parameters(hw, false, NULL);
10958 	} else {
10959 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
10960 		    (hw->phy.link_info.link_speed &
10961 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
10962 			i40e_aq_set_dcb_parameters(hw, false, NULL);
10963 			dev_warn(&pf->pdev->dev,
10964 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
10965 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
10966 		} else {
10967 			i40e_aq_set_dcb_parameters(hw, true, NULL);
10968 			ret = i40e_init_pf_dcb(pf);
10969 			if (ret) {
10970 				dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n",
10971 					 ret);
10972 				clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
10973 				/* Continue without DCB enabled */
10974 			}
10975 		}
10976 	}
10977 
10978 #endif /* CONFIG_I40E_DCB */
10979 	if (!lock_acquired)
10980 		rtnl_lock();
10981 	ret = i40e_setup_pf_switch(pf, reinit, true);
10982 	if (ret)
10983 		goto end_unlock;
10984 
10985 	/* The driver only wants link up/down and module qualification
10986 	 * reports from firmware.  Note the negative logic.
10987 	 */
10988 	ret = i40e_aq_set_phy_int_mask(&pf->hw,
10989 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
10990 					 I40E_AQ_EVENT_MEDIA_NA |
10991 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10992 	if (ret)
10993 		dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
10994 			 ERR_PTR(ret),
10995 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10996 
10997 	/* Rebuild the VSIs and VEBs that existed before reset.
10998 	 * They are still in our local switch element arrays, so only
10999 	 * need to rebuild the switch model in the HW.
11000 	 *
11001 	 * If there were VEBs but the reconstitution failed, we'll try
11002 	 * to recover minimal use by getting the basic PF VSI working.
11003 	 */
11004 	if (vsi->uplink_seid != pf->mac_seid) {
11005 		dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
11006 
11007 		/* Rebuild VEBs */
11008 		i40e_pf_for_each_veb(pf, v, veb) {
11009 			ret = i40e_reconstitute_veb(veb);
11010 			if (!ret)
11011 				continue;
11012 
11013 			/* If Main VEB failed, we're in deep doodoo,
11014 			 * so give up rebuilding the switch and set up
11015 			 * for minimal rebuild of PF VSI.
11016 			 * If orphan failed, we'll report the error
11017 			 * but try to keep going.
11018 			 */
11019 			if (veb->uplink_seid == pf->mac_seid) {
11020 				dev_info(&pf->pdev->dev,
11021 					 "rebuild of switch failed: %d, will try to set up simple PF connection\n",
11022 					 ret);
11023 				vsi->uplink_seid = pf->mac_seid;
11024 				break;
11025 			} else if (veb->uplink_seid == 0) {
11026 				dev_info(&pf->pdev->dev,
11027 					 "rebuild of orphan VEB failed: %d\n",
11028 					 ret);
11029 			}
11030 		}
11031 	}
11032 
11033 	if (vsi->uplink_seid == pf->mac_seid) {
11034 		dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
11035 		/* no VEB, so rebuild only the Main VSI */
11036 		ret = i40e_add_vsi(vsi);
11037 		if (ret) {
11038 			dev_info(&pf->pdev->dev,
11039 				 "rebuild of Main VSI failed: %d\n", ret);
11040 			goto end_unlock;
11041 		}
11042 	}
11043 
11044 	if (vsi->mqprio_qopt.max_rate[0]) {
11045 		u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
11046 						  vsi->mqprio_qopt.max_rate[0]);
11047 		u64 credits = 0;
11048 
11049 		ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
11050 		if (ret)
11051 			goto end_unlock;
11052 
11053 		credits = max_tx_rate;
11054 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
11055 		dev_dbg(&vsi->back->pdev->dev,
11056 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
11057 			max_tx_rate,
11058 			credits,
11059 			vsi->seid);
11060 	}
11061 
11062 	ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
11063 	if (ret)
11064 		goto end_unlock;
11065 
11066 	/* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
11067 	 * for this main VSI if they exist
11068 	 */
11069 	ret = i40e_rebuild_channels(vsi);
11070 	if (ret)
11071 		goto end_unlock;
11072 
11073 	/* Reconfigure hardware for allowing smaller MSS in the case
11074 	 * of TSO, so that we avoid the MDD being fired and causing
11075 	 * a reset in the case of small MSS+TSO.
11076 	 */
11077 #define I40E_REG_MSS          0x000E64DC
11078 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
11079 #define I40E_64BYTE_MSS       0x400000
11080 	val = rd32(hw, I40E_REG_MSS);
11081 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
11082 		val &= ~I40E_REG_MSS_MIN_MASK;
11083 		val |= I40E_64BYTE_MSS;
11084 		wr32(hw, I40E_REG_MSS, val);
11085 	}
11086 
11087 	if (test_bit(I40E_HW_CAP_RESTART_AUTONEG, pf->hw.caps)) {
11088 		msleep(75);
11089 		ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
11090 		if (ret)
11091 			dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
11092 				 ERR_PTR(ret),
11093 				 i40e_aq_str(&pf->hw,
11094 					     pf->hw.aq.asq_last_status));
11095 	}
11096 	/* reinit the misc interrupt */
11097 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
11098 		ret = i40e_setup_misc_vector(pf);
11099 		if (ret)
11100 			goto end_unlock;
11101 	}
11102 
11103 	/* Add a filter to drop all Flow control frames from any VSI from being
11104 	 * transmitted. By doing so we stop a malicious VF from sending out
11105 	 * PAUSE or PFC frames and potentially controlling traffic for other
11106 	 * PF/VF VSIs.
11107 	 * The FW can still send Flow control frames if enabled.
11108 	 */
11109 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
11110 						       pf->main_vsi_seid);
11111 
11112 	/* restart the VSIs that were rebuilt and running before the reset */
11113 	i40e_pf_unquiesce_all_vsi(pf);
11114 
11115 	/* Release the RTNL lock before we start resetting VFs */
11116 	if (!lock_acquired)
11117 		rtnl_unlock();
11118 
11119 	/* Restore promiscuous settings */
11120 	ret = i40e_set_promiscuous(pf, pf->cur_promisc);
11121 	if (ret)
11122 		dev_warn(&pf->pdev->dev,
11123 			 "Failed to restore promiscuous setting: %s, err %pe aq_err %s\n",
11124 			 pf->cur_promisc ? "on" : "off",
11125 			 ERR_PTR(ret),
11126 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11127 
11128 	i40e_reset_all_vfs(pf, true);
11129 
11130 	/* tell the firmware that we're starting */
11131 	i40e_send_version(pf);
11132 
11133 	/* We've already released the lock, so don't do it again */
11134 	goto end_core_reset;
11135 
11136 end_unlock:
11137 	if (!lock_acquired)
11138 		rtnl_unlock();
11139 end_core_reset:
11140 	clear_bit(__I40E_RESET_FAILED, pf->state);
11141 clear_recovery:
11142 	clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
11143 	clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
11144 }
11145 
11146 /**
11147  * i40e_reset_and_rebuild - reset and rebuild using a saved config
11148  * @pf: board private structure
11149  * @reinit: if the Main VSI needs to re-initialized.
11150  * @lock_acquired: indicates whether or not the lock has been acquired
11151  * before this function was called.
11152  **/
11153 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
11154 				   bool lock_acquired)
11155 {
11156 	int ret;
11157 
11158 	if (test_bit(__I40E_IN_REMOVE, pf->state))
11159 		return;
11160 	/* Now we wait for GRST to settle out.
11161 	 * We don't have to delete the VEBs or VSIs from the hw switch
11162 	 * because the reset will make them disappear.
11163 	 */
11164 	ret = i40e_reset(pf);
11165 	if (!ret)
11166 		i40e_rebuild(pf, reinit, lock_acquired);
11167 	else
11168 		dev_err(&pf->pdev->dev, "%s: i40e_reset() FAILED", __func__);
11169 }
11170 
11171 /**
11172  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
11173  * @pf: board private structure
11174  *
11175  * Close up the VFs and other things in prep for a Core Reset,
11176  * then get ready to rebuild the world.
11177  * @lock_acquired: indicates whether or not the lock has been acquired
11178  * before this function was called.
11179  **/
11180 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
11181 {
11182 	i40e_prep_for_reset(pf);
11183 	i40e_reset_and_rebuild(pf, false, lock_acquired);
11184 }
11185 
11186 /**
11187  * i40e_print_vf_mdd_event - print VF Tx/Rx malicious driver detect event
11188  * @pf: board private structure
11189  * @vf: pointer to the VF structure
11190  * @is_tx: true - for Tx event, false - for  Rx
11191  */
11192 static void i40e_print_vf_mdd_event(struct i40e_pf *pf, struct i40e_vf *vf,
11193 				    bool is_tx)
11194 {
11195 	dev_err(&pf->pdev->dev, is_tx ?
11196 		"%lld Tx Malicious Driver Detection events detected on PF %d VF %d MAC %pm. mdd-auto-reset-vfs=%s\n" :
11197 		"%lld Rx Malicious Driver Detection events detected on PF %d VF %d MAC %pm. mdd-auto-reset-vfs=%s\n",
11198 		is_tx ? vf->mdd_tx_events.count : vf->mdd_rx_events.count,
11199 		pf->hw.pf_id,
11200 		vf->vf_id,
11201 		vf->default_lan_addr.addr,
11202 		str_on_off(test_bit(I40E_FLAG_MDD_AUTO_RESET_VF, pf->flags)));
11203 }
11204 
11205 /**
11206  * i40e_print_vfs_mdd_events - print VFs malicious driver detect event
11207  * @pf: pointer to the PF structure
11208  *
11209  * Called from i40e_handle_mdd_event to rate limit and print VFs MDD events.
11210  */
11211 static void i40e_print_vfs_mdd_events(struct i40e_pf *pf)
11212 {
11213 	unsigned int i;
11214 
11215 	/* check that there are pending MDD events to print */
11216 	if (!test_and_clear_bit(__I40E_MDD_VF_PRINT_PENDING, pf->state))
11217 		return;
11218 
11219 	if (!__ratelimit(&pf->mdd_message_rate_limit))
11220 		return;
11221 
11222 	for (i = 0; i < pf->num_alloc_vfs; i++) {
11223 		struct i40e_vf *vf = &pf->vf[i];
11224 		bool is_printed = false;
11225 
11226 		/* only print Rx MDD event message if there are new events */
11227 		if (vf->mdd_rx_events.count != vf->mdd_rx_events.last_printed) {
11228 			vf->mdd_rx_events.last_printed = vf->mdd_rx_events.count;
11229 			i40e_print_vf_mdd_event(pf, vf, false);
11230 			is_printed = true;
11231 		}
11232 
11233 		/* only print Tx MDD event message if there are new events */
11234 		if (vf->mdd_tx_events.count != vf->mdd_tx_events.last_printed) {
11235 			vf->mdd_tx_events.last_printed = vf->mdd_tx_events.count;
11236 			i40e_print_vf_mdd_event(pf, vf, true);
11237 			is_printed = true;
11238 		}
11239 
11240 		if (is_printed && !test_bit(I40E_FLAG_MDD_AUTO_RESET_VF, pf->flags))
11241 			dev_info(&pf->pdev->dev,
11242 				 "Use PF Control I/F to re-enable the VF #%d\n",
11243 				 i);
11244 	}
11245 }
11246 
11247 /**
11248  * i40e_handle_mdd_event
11249  * @pf: pointer to the PF structure
11250  *
11251  * Called from the MDD irq handler to identify possibly malicious vfs
11252  **/
11253 static void i40e_handle_mdd_event(struct i40e_pf *pf)
11254 {
11255 	struct i40e_hw *hw = &pf->hw;
11256 	bool mdd_detected = false;
11257 	struct i40e_vf *vf;
11258 	u32 reg;
11259 	int i;
11260 
11261 	if (!test_and_clear_bit(__I40E_MDD_EVENT_PENDING, pf->state)) {
11262 		/* Since the VF MDD event logging is rate limited, check if
11263 		 * there are pending MDD events.
11264 		 */
11265 		i40e_print_vfs_mdd_events(pf);
11266 		return;
11267 	}
11268 
11269 	/* find what triggered the MDD event */
11270 	reg = rd32(hw, I40E_GL_MDET_TX);
11271 	if (reg & I40E_GL_MDET_TX_VALID_MASK) {
11272 		u8 pf_num = FIELD_GET(I40E_GL_MDET_TX_PF_NUM_MASK, reg);
11273 		u16 vf_num = FIELD_GET(I40E_GL_MDET_TX_VF_NUM_MASK, reg);
11274 		u8 event = FIELD_GET(I40E_GL_MDET_TX_EVENT_MASK, reg);
11275 		u16 queue = FIELD_GET(I40E_GL_MDET_TX_QUEUE_MASK, reg) -
11276 				pf->hw.func_caps.base_queue;
11277 		if (netif_msg_tx_err(pf))
11278 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
11279 				 event, queue, pf_num, vf_num);
11280 		wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
11281 		mdd_detected = true;
11282 	}
11283 	reg = rd32(hw, I40E_GL_MDET_RX);
11284 	if (reg & I40E_GL_MDET_RX_VALID_MASK) {
11285 		u8 func = FIELD_GET(I40E_GL_MDET_RX_FUNCTION_MASK, reg);
11286 		u8 event = FIELD_GET(I40E_GL_MDET_RX_EVENT_MASK, reg);
11287 		u16 queue = FIELD_GET(I40E_GL_MDET_RX_QUEUE_MASK, reg) -
11288 				pf->hw.func_caps.base_queue;
11289 		if (netif_msg_rx_err(pf))
11290 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
11291 				 event, queue, func);
11292 		wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
11293 		mdd_detected = true;
11294 	}
11295 
11296 	if (mdd_detected) {
11297 		reg = rd32(hw, I40E_PF_MDET_TX);
11298 		if (reg & I40E_PF_MDET_TX_VALID_MASK) {
11299 			wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
11300 			dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
11301 		}
11302 		reg = rd32(hw, I40E_PF_MDET_RX);
11303 		if (reg & I40E_PF_MDET_RX_VALID_MASK) {
11304 			wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
11305 			dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
11306 		}
11307 	}
11308 
11309 	/* see if one of the VFs needs its hand slapped */
11310 	for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
11311 		bool is_mdd_on_tx = false;
11312 		bool is_mdd_on_rx = false;
11313 
11314 		vf = &(pf->vf[i]);
11315 		reg = rd32(hw, I40E_VP_MDET_TX(i));
11316 		if (reg & I40E_VP_MDET_TX_VALID_MASK) {
11317 			set_bit(__I40E_MDD_VF_PRINT_PENDING, pf->state);
11318 			wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
11319 			vf->mdd_tx_events.count++;
11320 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11321 			is_mdd_on_tx = true;
11322 		}
11323 
11324 		reg = rd32(hw, I40E_VP_MDET_RX(i));
11325 		if (reg & I40E_VP_MDET_RX_VALID_MASK) {
11326 			set_bit(__I40E_MDD_VF_PRINT_PENDING, pf->state);
11327 			wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
11328 			vf->mdd_rx_events.count++;
11329 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11330 			is_mdd_on_rx = true;
11331 		}
11332 
11333 		if ((is_mdd_on_tx || is_mdd_on_rx) &&
11334 		    test_bit(I40E_FLAG_MDD_AUTO_RESET_VF, pf->flags)) {
11335 			/* VF MDD event counters will be cleared by
11336 			 * reset, so print the event prior to reset.
11337 			 */
11338 			if (is_mdd_on_rx)
11339 				i40e_print_vf_mdd_event(pf, vf, false);
11340 			if (is_mdd_on_tx)
11341 				i40e_print_vf_mdd_event(pf, vf, true);
11342 
11343 			i40e_vc_reset_vf(vf, true);
11344 		}
11345 	}
11346 
11347 	reg = rd32(hw, I40E_PFINT_ICR0_ENA);
11348 	reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
11349 	wr32(hw, I40E_PFINT_ICR0_ENA, reg);
11350 	i40e_flush(hw);
11351 
11352 	i40e_print_vfs_mdd_events(pf);
11353 }
11354 
11355 /**
11356  * i40e_service_task - Run the driver's async subtasks
11357  * @work: pointer to work_struct containing our data
11358  **/
11359 static void i40e_service_task(struct work_struct *work)
11360 {
11361 	struct i40e_pf *pf = container_of(work,
11362 					  struct i40e_pf,
11363 					  service_task);
11364 	unsigned long start_time = jiffies;
11365 
11366 	/* don't bother with service tasks if a reset is in progress */
11367 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
11368 	    test_bit(__I40E_SUSPENDED, pf->state))
11369 		return;
11370 
11371 	if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
11372 		return;
11373 
11374 	if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
11375 		i40e_detect_recover_hung(pf);
11376 		i40e_sync_filters_subtask(pf);
11377 		i40e_reset_subtask(pf);
11378 		i40e_handle_mdd_event(pf);
11379 		i40e_vc_process_vflr_event(pf);
11380 		i40e_watchdog_subtask(pf);
11381 		i40e_fdir_reinit_subtask(pf);
11382 		if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
11383 			/* Client subtask will reopen next time through. */
11384 			i40e_notify_client_of_netdev_close(pf, true);
11385 		} else {
11386 			i40e_client_subtask(pf);
11387 			if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
11388 					       pf->state))
11389 				i40e_notify_client_of_l2_param_changes(pf);
11390 		}
11391 		i40e_sync_filters_subtask(pf);
11392 	} else {
11393 		i40e_reset_subtask(pf);
11394 	}
11395 
11396 	i40e_clean_adminq_subtask(pf);
11397 
11398 	/* flush memory to make sure state is correct before next watchdog */
11399 	smp_mb__before_atomic();
11400 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
11401 
11402 	/* If the tasks have taken longer than one timer cycle or there
11403 	 * is more work to be done, reschedule the service task now
11404 	 * rather than wait for the timer to tick again.
11405 	 */
11406 	if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
11407 	    test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)		 ||
11408 	    test_bit(__I40E_MDD_EVENT_PENDING, pf->state)		 ||
11409 	    test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
11410 		i40e_service_event_schedule(pf);
11411 }
11412 
11413 /**
11414  * i40e_service_timer - timer callback
11415  * @t: timer list pointer
11416  **/
11417 static void i40e_service_timer(struct timer_list *t)
11418 {
11419 	struct i40e_pf *pf = timer_container_of(pf, t, service_timer);
11420 
11421 	mod_timer(&pf->service_timer,
11422 		  round_jiffies(jiffies + pf->service_timer_period));
11423 	i40e_service_event_schedule(pf);
11424 }
11425 
11426 /**
11427  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
11428  * @vsi: the VSI being configured
11429  **/
11430 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
11431 {
11432 	struct i40e_pf *pf = vsi->back;
11433 
11434 	switch (vsi->type) {
11435 	case I40E_VSI_MAIN:
11436 		vsi->alloc_queue_pairs = pf->num_lan_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 		if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
11444 			vsi->num_q_vectors = pf->num_lan_msix;
11445 		else
11446 			vsi->num_q_vectors = 1;
11447 
11448 		break;
11449 
11450 	case I40E_VSI_FDIR:
11451 		vsi->alloc_queue_pairs = 1;
11452 		vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11453 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11454 		vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11455 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11456 		vsi->num_q_vectors = pf->num_fdsb_msix;
11457 		break;
11458 
11459 	case I40E_VSI_VMDQ2:
11460 		vsi->alloc_queue_pairs = pf->num_vmdq_qps;
11461 		if (!vsi->num_tx_desc)
11462 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11463 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11464 		if (!vsi->num_rx_desc)
11465 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11466 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11467 		vsi->num_q_vectors = pf->num_vmdq_msix;
11468 		break;
11469 
11470 	case I40E_VSI_SRIOV:
11471 		vsi->alloc_queue_pairs = pf->num_vf_qps;
11472 		if (!vsi->num_tx_desc)
11473 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11474 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11475 		if (!vsi->num_rx_desc)
11476 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11477 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11478 		break;
11479 
11480 	default:
11481 		WARN_ON(1);
11482 		return -ENODATA;
11483 	}
11484 
11485 	if (is_kdump_kernel()) {
11486 		vsi->num_tx_desc = I40E_MIN_NUM_DESCRIPTORS;
11487 		vsi->num_rx_desc = I40E_MIN_NUM_DESCRIPTORS;
11488 	}
11489 
11490 	return 0;
11491 }
11492 
11493 /**
11494  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
11495  * @vsi: VSI pointer
11496  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
11497  *
11498  * On error: returns error code (negative)
11499  * On success: returns 0
11500  **/
11501 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
11502 {
11503 	struct i40e_ring **next_rings;
11504 	int size;
11505 	int ret = 0;
11506 
11507 	/* allocate memory for both Tx, XDP Tx and Rx ring pointers */
11508 	size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
11509 	       (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
11510 	vsi->tx_rings = kzalloc(size, GFP_KERNEL);
11511 	if (!vsi->tx_rings)
11512 		return -ENOMEM;
11513 	next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
11514 	if (i40e_enabled_xdp_vsi(vsi)) {
11515 		vsi->xdp_rings = next_rings;
11516 		next_rings += vsi->alloc_queue_pairs;
11517 	}
11518 	vsi->rx_rings = next_rings;
11519 
11520 	if (alloc_qvectors) {
11521 		/* allocate memory for q_vector pointers */
11522 		size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
11523 		vsi->q_vectors = kzalloc(size, GFP_KERNEL);
11524 		if (!vsi->q_vectors) {
11525 			ret = -ENOMEM;
11526 			goto err_vectors;
11527 		}
11528 	}
11529 	return ret;
11530 
11531 err_vectors:
11532 	kfree(vsi->tx_rings);
11533 	return ret;
11534 }
11535 
11536 /**
11537  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
11538  * @pf: board private structure
11539  * @type: type of VSI
11540  *
11541  * On error: returns error code (negative)
11542  * On success: returns vsi index in PF (positive)
11543  **/
11544 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
11545 {
11546 	int ret = -ENODEV;
11547 	struct i40e_vsi *vsi;
11548 	int vsi_idx;
11549 	int i;
11550 
11551 	/* Need to protect the allocation of the VSIs at the PF level */
11552 	mutex_lock(&pf->switch_mutex);
11553 
11554 	/* VSI list may be fragmented if VSI creation/destruction has
11555 	 * been happening.  We can afford to do a quick scan to look
11556 	 * for any free VSIs in the list.
11557 	 *
11558 	 * find next empty vsi slot, looping back around if necessary
11559 	 */
11560 	i = pf->next_vsi;
11561 	while (i < pf->num_alloc_vsi && pf->vsi[i])
11562 		i++;
11563 	if (i >= pf->num_alloc_vsi) {
11564 		i = 0;
11565 		while (i < pf->next_vsi && pf->vsi[i])
11566 			i++;
11567 	}
11568 
11569 	if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
11570 		vsi_idx = i;             /* Found one! */
11571 	} else {
11572 		ret = -ENODEV;
11573 		goto unlock_pf;  /* out of VSI slots! */
11574 	}
11575 	pf->next_vsi = ++i;
11576 
11577 	vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
11578 	if (!vsi) {
11579 		ret = -ENOMEM;
11580 		goto unlock_pf;
11581 	}
11582 	vsi->type = type;
11583 	vsi->back = pf;
11584 	set_bit(__I40E_VSI_DOWN, vsi->state);
11585 	vsi->flags = 0;
11586 	vsi->idx = vsi_idx;
11587 	vsi->int_rate_limit = 0;
11588 	vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
11589 				pf->rss_table_size : 64;
11590 	vsi->netdev_registered = false;
11591 	vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
11592 	hash_init(vsi->mac_filter_hash);
11593 	vsi->irqs_ready = false;
11594 
11595 	if (type == I40E_VSI_MAIN) {
11596 		vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
11597 		if (!vsi->af_xdp_zc_qps)
11598 			goto err_rings;
11599 	}
11600 
11601 	ret = i40e_set_num_rings_in_vsi(vsi);
11602 	if (ret)
11603 		goto err_rings;
11604 
11605 	ret = i40e_vsi_alloc_arrays(vsi, true);
11606 	if (ret)
11607 		goto err_rings;
11608 
11609 	/* Setup default MSIX irq handler for VSI */
11610 	i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
11611 
11612 	/* Initialize VSI lock */
11613 	spin_lock_init(&vsi->mac_filter_hash_lock);
11614 	pf->vsi[vsi_idx] = vsi;
11615 	ret = vsi_idx;
11616 	goto unlock_pf;
11617 
11618 err_rings:
11619 	bitmap_free(vsi->af_xdp_zc_qps);
11620 	pf->next_vsi = i - 1;
11621 	kfree(vsi);
11622 unlock_pf:
11623 	mutex_unlock(&pf->switch_mutex);
11624 	return ret;
11625 }
11626 
11627 /**
11628  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
11629  * @vsi: VSI pointer
11630  * @free_qvectors: a bool to specify if q_vectors need to be freed.
11631  *
11632  * On error: returns error code (negative)
11633  * On success: returns 0
11634  **/
11635 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
11636 {
11637 	/* free the ring and vector containers */
11638 	if (free_qvectors) {
11639 		kfree(vsi->q_vectors);
11640 		vsi->q_vectors = NULL;
11641 	}
11642 	kfree(vsi->tx_rings);
11643 	vsi->tx_rings = NULL;
11644 	vsi->rx_rings = NULL;
11645 	vsi->xdp_rings = NULL;
11646 }
11647 
11648 /**
11649  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
11650  * and lookup table
11651  * @vsi: Pointer to VSI structure
11652  */
11653 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
11654 {
11655 	if (!vsi)
11656 		return;
11657 
11658 	kfree(vsi->rss_hkey_user);
11659 	vsi->rss_hkey_user = NULL;
11660 
11661 	kfree(vsi->rss_lut_user);
11662 	vsi->rss_lut_user = NULL;
11663 }
11664 
11665 /**
11666  * i40e_vsi_clear - Deallocate the VSI provided
11667  * @vsi: the VSI being un-configured
11668  **/
11669 static int i40e_vsi_clear(struct i40e_vsi *vsi)
11670 {
11671 	struct i40e_pf *pf;
11672 
11673 	if (!vsi)
11674 		return 0;
11675 
11676 	if (!vsi->back)
11677 		goto free_vsi;
11678 	pf = vsi->back;
11679 
11680 	mutex_lock(&pf->switch_mutex);
11681 	if (!pf->vsi[vsi->idx]) {
11682 		dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
11683 			vsi->idx, vsi->idx, vsi->type);
11684 		goto unlock_vsi;
11685 	}
11686 
11687 	if (pf->vsi[vsi->idx] != vsi) {
11688 		dev_err(&pf->pdev->dev,
11689 			"pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
11690 			pf->vsi[vsi->idx]->idx,
11691 			pf->vsi[vsi->idx]->type,
11692 			vsi->idx, vsi->type);
11693 		goto unlock_vsi;
11694 	}
11695 
11696 	/* updates the PF for this cleared vsi */
11697 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
11698 	i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
11699 
11700 	bitmap_free(vsi->af_xdp_zc_qps);
11701 	i40e_vsi_free_arrays(vsi, true);
11702 	i40e_clear_rss_config_user(vsi);
11703 
11704 	pf->vsi[vsi->idx] = NULL;
11705 	if (vsi->idx < pf->next_vsi)
11706 		pf->next_vsi = vsi->idx;
11707 
11708 unlock_vsi:
11709 	mutex_unlock(&pf->switch_mutex);
11710 free_vsi:
11711 	kfree(vsi);
11712 
11713 	return 0;
11714 }
11715 
11716 /**
11717  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
11718  * @vsi: the VSI being cleaned
11719  **/
11720 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
11721 {
11722 	int i;
11723 
11724 	if (vsi->tx_rings && vsi->tx_rings[0]) {
11725 		for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11726 			kfree_rcu(vsi->tx_rings[i], rcu);
11727 			WRITE_ONCE(vsi->tx_rings[i], NULL);
11728 			WRITE_ONCE(vsi->rx_rings[i], NULL);
11729 			if (vsi->xdp_rings)
11730 				WRITE_ONCE(vsi->xdp_rings[i], NULL);
11731 		}
11732 	}
11733 }
11734 
11735 /**
11736  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
11737  * @vsi: the VSI being configured
11738  **/
11739 static int i40e_alloc_rings(struct i40e_vsi *vsi)
11740 {
11741 	int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
11742 	struct i40e_pf *pf = vsi->back;
11743 	struct i40e_ring *ring;
11744 
11745 	/* Set basic values in the rings to be used later during open() */
11746 	for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11747 		/* allocate space for both Tx and Rx in one shot */
11748 		ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
11749 		if (!ring)
11750 			goto err_out;
11751 
11752 		ring->queue_index = i;
11753 		ring->reg_idx = vsi->base_queue + i;
11754 		ring->ring_active = false;
11755 		ring->vsi = vsi;
11756 		ring->netdev = vsi->netdev;
11757 		ring->dev = &pf->pdev->dev;
11758 		ring->count = vsi->num_tx_desc;
11759 		ring->size = 0;
11760 		ring->dcb_tc = 0;
11761 		if (test_bit(I40E_HW_CAP_WB_ON_ITR, vsi->back->hw.caps))
11762 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11763 		ring->itr_setting = pf->tx_itr_default;
11764 		WRITE_ONCE(vsi->tx_rings[i], ring++);
11765 
11766 		if (!i40e_enabled_xdp_vsi(vsi))
11767 			goto setup_rx;
11768 
11769 		ring->queue_index = vsi->alloc_queue_pairs + i;
11770 		ring->reg_idx = vsi->base_queue + ring->queue_index;
11771 		ring->ring_active = false;
11772 		ring->vsi = vsi;
11773 		ring->netdev = NULL;
11774 		ring->dev = &pf->pdev->dev;
11775 		ring->count = vsi->num_tx_desc;
11776 		ring->size = 0;
11777 		ring->dcb_tc = 0;
11778 		if (test_bit(I40E_HW_CAP_WB_ON_ITR, vsi->back->hw.caps))
11779 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11780 		set_ring_xdp(ring);
11781 		ring->itr_setting = pf->tx_itr_default;
11782 		WRITE_ONCE(vsi->xdp_rings[i], ring++);
11783 
11784 setup_rx:
11785 		ring->queue_index = i;
11786 		ring->reg_idx = vsi->base_queue + i;
11787 		ring->ring_active = false;
11788 		ring->vsi = vsi;
11789 		ring->netdev = vsi->netdev;
11790 		ring->dev = &pf->pdev->dev;
11791 		ring->count = vsi->num_rx_desc;
11792 		ring->size = 0;
11793 		ring->dcb_tc = 0;
11794 		ring->itr_setting = pf->rx_itr_default;
11795 		WRITE_ONCE(vsi->rx_rings[i], ring);
11796 	}
11797 
11798 	return 0;
11799 
11800 err_out:
11801 	i40e_vsi_clear_rings(vsi);
11802 	return -ENOMEM;
11803 }
11804 
11805 /**
11806  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
11807  * @pf: board private structure
11808  * @vectors: the number of MSI-X vectors to request
11809  *
11810  * Returns the number of vectors reserved, or error
11811  **/
11812 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
11813 {
11814 	vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
11815 					I40E_MIN_MSIX, vectors);
11816 	if (vectors < 0) {
11817 		dev_info(&pf->pdev->dev,
11818 			 "MSI-X vector reservation failed: %d\n", vectors);
11819 		vectors = 0;
11820 	}
11821 
11822 	return vectors;
11823 }
11824 
11825 /**
11826  * i40e_init_msix - Setup the MSIX capability
11827  * @pf: board private structure
11828  *
11829  * Work with the OS to set up the MSIX vectors needed.
11830  *
11831  * Returns the number of vectors reserved or negative on failure
11832  **/
11833 static int i40e_init_msix(struct i40e_pf *pf)
11834 {
11835 	struct i40e_hw *hw = &pf->hw;
11836 	int cpus, extra_vectors;
11837 	int vectors_left;
11838 	int v_budget, i;
11839 	int v_actual;
11840 	int iwarp_requested = 0;
11841 
11842 	if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
11843 		return -ENODEV;
11844 
11845 	/* The number of vectors we'll request will be comprised of:
11846 	 *   - Add 1 for "other" cause for Admin Queue events, etc.
11847 	 *   - The number of LAN queue pairs
11848 	 *	- Queues being used for RSS.
11849 	 *		We don't need as many as max_rss_size vectors.
11850 	 *		use rss_size instead in the calculation since that
11851 	 *		is governed by number of cpus in the system.
11852 	 *	- assumes symmetric Tx/Rx pairing
11853 	 *   - The number of VMDq pairs
11854 	 *   - The CPU count within the NUMA node if iWARP is enabled
11855 	 * Once we count this up, try the request.
11856 	 *
11857 	 * If we can't get what we want, we'll simplify to nearly nothing
11858 	 * and try again.  If that still fails, we punt.
11859 	 */
11860 	vectors_left = hw->func_caps.num_msix_vectors;
11861 	v_budget = 0;
11862 
11863 	/* reserve one vector for miscellaneous handler */
11864 	if (vectors_left) {
11865 		v_budget++;
11866 		vectors_left--;
11867 	}
11868 
11869 	/* reserve some vectors for the main PF traffic queues. Initially we
11870 	 * only reserve at most 50% of the available vectors, in the case that
11871 	 * the number of online CPUs is large. This ensures that we can enable
11872 	 * extra features as well. Once we've enabled the other features, we
11873 	 * will use any remaining vectors to reach as close as we can to the
11874 	 * number of online CPUs.
11875 	 */
11876 	cpus = num_online_cpus();
11877 	pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
11878 	vectors_left -= pf->num_lan_msix;
11879 
11880 	/* reserve one vector for sideband flow director */
11881 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
11882 		if (vectors_left) {
11883 			pf->num_fdsb_msix = 1;
11884 			v_budget++;
11885 			vectors_left--;
11886 		} else {
11887 			pf->num_fdsb_msix = 0;
11888 		}
11889 	}
11890 
11891 	/* can we reserve enough for iWARP? */
11892 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
11893 		iwarp_requested = pf->num_iwarp_msix;
11894 
11895 		if (!vectors_left)
11896 			pf->num_iwarp_msix = 0;
11897 		else if (vectors_left < pf->num_iwarp_msix)
11898 			pf->num_iwarp_msix = 1;
11899 		v_budget += pf->num_iwarp_msix;
11900 		vectors_left -= pf->num_iwarp_msix;
11901 	}
11902 
11903 	/* any vectors left over go for VMDq support */
11904 	if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags)) {
11905 		if (!vectors_left) {
11906 			pf->num_vmdq_msix = 0;
11907 			pf->num_vmdq_qps = 0;
11908 		} else {
11909 			int vmdq_vecs_wanted =
11910 				pf->num_vmdq_vsis * pf->num_vmdq_qps;
11911 			int vmdq_vecs =
11912 				min_t(int, vectors_left, vmdq_vecs_wanted);
11913 
11914 			/* if we're short on vectors for what's desired, we limit
11915 			 * the queues per vmdq.  If this is still more than are
11916 			 * available, the user will need to change the number of
11917 			 * queues/vectors used by the PF later with the ethtool
11918 			 * channels command
11919 			 */
11920 			if (vectors_left < vmdq_vecs_wanted) {
11921 				pf->num_vmdq_qps = 1;
11922 				vmdq_vecs_wanted = pf->num_vmdq_vsis;
11923 				vmdq_vecs = min_t(int,
11924 						  vectors_left,
11925 						  vmdq_vecs_wanted);
11926 			}
11927 			pf->num_vmdq_msix = pf->num_vmdq_qps;
11928 
11929 			v_budget += vmdq_vecs;
11930 			vectors_left -= vmdq_vecs;
11931 		}
11932 	}
11933 
11934 	/* On systems with a large number of SMP cores, we previously limited
11935 	 * the number of vectors for num_lan_msix to be at most 50% of the
11936 	 * available vectors, to allow for other features. Now, we add back
11937 	 * the remaining vectors. However, we ensure that the total
11938 	 * num_lan_msix will not exceed num_online_cpus(). To do this, we
11939 	 * calculate the number of vectors we can add without going over the
11940 	 * cap of CPUs. For systems with a small number of CPUs this will be
11941 	 * zero.
11942 	 */
11943 	extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11944 	pf->num_lan_msix += extra_vectors;
11945 	vectors_left -= extra_vectors;
11946 
11947 	WARN(vectors_left < 0,
11948 	     "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11949 
11950 	v_budget += pf->num_lan_msix;
11951 	pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
11952 				   GFP_KERNEL);
11953 	if (!pf->msix_entries)
11954 		return -ENOMEM;
11955 
11956 	for (i = 0; i < v_budget; i++)
11957 		pf->msix_entries[i].entry = i;
11958 	v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11959 
11960 	if (v_actual < I40E_MIN_MSIX) {
11961 		clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
11962 		kfree(pf->msix_entries);
11963 		pf->msix_entries = NULL;
11964 		pci_disable_msix(pf->pdev);
11965 		return -ENODEV;
11966 
11967 	} else if (v_actual == I40E_MIN_MSIX) {
11968 		/* Adjust for minimal MSIX use */
11969 		pf->num_vmdq_vsis = 0;
11970 		pf->num_vmdq_qps = 0;
11971 		pf->num_lan_qps = 1;
11972 		pf->num_lan_msix = 1;
11973 
11974 	} else if (v_actual != v_budget) {
11975 		/* If we have limited resources, we will start with no vectors
11976 		 * for the special features and then allocate vectors to some
11977 		 * of these features based on the policy and at the end disable
11978 		 * the features that did not get any vectors.
11979 		 */
11980 		int vec;
11981 
11982 		dev_info(&pf->pdev->dev,
11983 			 "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11984 			 v_actual, v_budget);
11985 		/* reserve the misc vector */
11986 		vec = v_actual - 1;
11987 
11988 		/* Scale vector usage down */
11989 		pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11990 		pf->num_vmdq_vsis = 1;
11991 		pf->num_vmdq_qps = 1;
11992 
11993 		/* partition out the remaining vectors */
11994 		switch (vec) {
11995 		case 2:
11996 			pf->num_lan_msix = 1;
11997 			break;
11998 		case 3:
11999 			if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
12000 				pf->num_lan_msix = 1;
12001 				pf->num_iwarp_msix = 1;
12002 			} else {
12003 				pf->num_lan_msix = 2;
12004 			}
12005 			break;
12006 		default:
12007 			if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
12008 				pf->num_iwarp_msix = min_t(int, (vec / 3),
12009 						 iwarp_requested);
12010 				pf->num_vmdq_vsis = min_t(int, (vec / 3),
12011 						  I40E_DEFAULT_NUM_VMDQ_VSI);
12012 			} else {
12013 				pf->num_vmdq_vsis = min_t(int, (vec / 2),
12014 						  I40E_DEFAULT_NUM_VMDQ_VSI);
12015 			}
12016 			if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
12017 				pf->num_fdsb_msix = 1;
12018 				vec--;
12019 			}
12020 			pf->num_lan_msix = min_t(int,
12021 			       (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
12022 							      pf->num_lan_msix);
12023 			pf->num_lan_qps = pf->num_lan_msix;
12024 			break;
12025 		}
12026 	}
12027 
12028 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) && pf->num_fdsb_msix == 0) {
12029 		dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
12030 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12031 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12032 	}
12033 	if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags) && pf->num_vmdq_msix == 0) {
12034 		dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
12035 		clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
12036 	}
12037 
12038 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags) &&
12039 	    pf->num_iwarp_msix == 0) {
12040 		dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
12041 		clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
12042 	}
12043 	i40e_debug(&pf->hw, I40E_DEBUG_INIT,
12044 		   "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
12045 		   pf->num_lan_msix,
12046 		   pf->num_vmdq_msix * pf->num_vmdq_vsis,
12047 		   pf->num_fdsb_msix,
12048 		   pf->num_iwarp_msix);
12049 
12050 	return v_actual;
12051 }
12052 
12053 /**
12054  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
12055  * @vsi: the VSI being configured
12056  * @v_idx: index of the vector in the vsi struct
12057  *
12058  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
12059  **/
12060 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx)
12061 {
12062 	struct i40e_q_vector *q_vector;
12063 
12064 	/* allocate q_vector */
12065 	q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
12066 	if (!q_vector)
12067 		return -ENOMEM;
12068 
12069 	q_vector->vsi = vsi;
12070 	q_vector->v_idx = v_idx;
12071 	cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
12072 
12073 	if (vsi->netdev)
12074 		netif_napi_add(vsi->netdev, &q_vector->napi, i40e_napi_poll);
12075 
12076 	/* tie q_vector and vsi together */
12077 	vsi->q_vectors[v_idx] = q_vector;
12078 
12079 	return 0;
12080 }
12081 
12082 /**
12083  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
12084  * @vsi: the VSI being configured
12085  *
12086  * We allocate one q_vector per queue interrupt.  If allocation fails we
12087  * return -ENOMEM.
12088  **/
12089 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
12090 {
12091 	struct i40e_pf *pf = vsi->back;
12092 	int err, v_idx, num_q_vectors;
12093 
12094 	/* if not MSIX, give the one vector only to the LAN VSI */
12095 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
12096 		num_q_vectors = vsi->num_q_vectors;
12097 	else if (vsi->type == I40E_VSI_MAIN)
12098 		num_q_vectors = 1;
12099 	else
12100 		return -EINVAL;
12101 
12102 	for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
12103 		err = i40e_vsi_alloc_q_vector(vsi, v_idx);
12104 		if (err)
12105 			goto err_out;
12106 	}
12107 
12108 	return 0;
12109 
12110 err_out:
12111 	while (v_idx--)
12112 		i40e_free_q_vector(vsi, v_idx);
12113 
12114 	return err;
12115 }
12116 
12117 /**
12118  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
12119  * @pf: board private structure to initialize
12120  **/
12121 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
12122 {
12123 	int vectors = 0;
12124 	ssize_t size;
12125 
12126 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
12127 		vectors = i40e_init_msix(pf);
12128 		if (vectors < 0) {
12129 			clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12130 			clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
12131 			clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
12132 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
12133 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
12134 			clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
12135 			clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12136 			clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
12137 			clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
12138 			set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12139 
12140 			/* rework the queue expectations without MSIX */
12141 			i40e_determine_queue_usage(pf);
12142 		}
12143 	}
12144 
12145 	if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
12146 	    test_bit(I40E_FLAG_MSI_ENA, pf->flags)) {
12147 		dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
12148 		vectors = pci_enable_msi(pf->pdev);
12149 		if (vectors < 0) {
12150 			dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
12151 				 vectors);
12152 			clear_bit(I40E_FLAG_MSI_ENA, pf->flags);
12153 		}
12154 		vectors = 1;  /* one MSI or Legacy vector */
12155 	}
12156 
12157 	if (!test_bit(I40E_FLAG_MSI_ENA, pf->flags) &&
12158 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
12159 		dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
12160 
12161 	/* set up vector assignment tracking */
12162 	size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
12163 	pf->irq_pile = kzalloc(size, GFP_KERNEL);
12164 	if (!pf->irq_pile)
12165 		return -ENOMEM;
12166 
12167 	pf->irq_pile->num_entries = vectors;
12168 
12169 	/* track first vector for misc interrupts, ignore return */
12170 	(void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
12171 
12172 	return 0;
12173 }
12174 
12175 /**
12176  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
12177  * @pf: private board data structure
12178  *
12179  * Restore the interrupt scheme that was cleared when we suspended the
12180  * device. This should be called during resume to re-allocate the q_vectors
12181  * and reacquire IRQs.
12182  */
12183 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
12184 {
12185 	struct i40e_vsi *vsi;
12186 	int err, i;
12187 
12188 	/* We cleared the MSI and MSI-X flags when disabling the old interrupt
12189 	 * scheme. We need to re-enabled them here in order to attempt to
12190 	 * re-acquire the MSI or MSI-X vectors
12191 	 */
12192 	set_bit(I40E_FLAG_MSI_ENA, pf->flags);
12193 	set_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12194 
12195 	err = i40e_init_interrupt_scheme(pf);
12196 	if (err)
12197 		return err;
12198 
12199 	/* Now that we've re-acquired IRQs, we need to remap the vectors and
12200 	 * rings together again.
12201 	 */
12202 	i40e_pf_for_each_vsi(pf, i, vsi) {
12203 		err = i40e_vsi_alloc_q_vectors(vsi);
12204 		if (err)
12205 			goto err_unwind;
12206 
12207 		i40e_vsi_map_rings_to_vectors(vsi);
12208 	}
12209 
12210 	err = i40e_setup_misc_vector(pf);
12211 	if (err)
12212 		goto err_unwind;
12213 
12214 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags))
12215 		i40e_client_update_msix_info(pf);
12216 
12217 	return 0;
12218 
12219 err_unwind:
12220 	while (i--) {
12221 		if (pf->vsi[i])
12222 			i40e_vsi_free_q_vectors(pf->vsi[i]);
12223 	}
12224 
12225 	return err;
12226 }
12227 
12228 /**
12229  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
12230  * non queue events in recovery mode
12231  * @pf: board private structure
12232  *
12233  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
12234  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
12235  * This is handled differently than in recovery mode since no Tx/Rx resources
12236  * are being allocated.
12237  **/
12238 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
12239 {
12240 	int err;
12241 
12242 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
12243 		err = i40e_setup_misc_vector(pf);
12244 
12245 		if (err) {
12246 			dev_info(&pf->pdev->dev,
12247 				 "MSI-X misc vector request failed, error %d\n",
12248 				 err);
12249 			return err;
12250 		}
12251 	} else {
12252 		u32 flags = test_bit(I40E_FLAG_MSI_ENA, pf->flags) ? 0 : IRQF_SHARED;
12253 
12254 		err = request_irq(pf->pdev->irq, i40e_intr, flags,
12255 				  pf->int_name, pf);
12256 
12257 		if (err) {
12258 			dev_info(&pf->pdev->dev,
12259 				 "MSI/legacy misc vector request failed, error %d\n",
12260 				 err);
12261 			return err;
12262 		}
12263 		i40e_enable_misc_int_causes(pf);
12264 		i40e_irq_dynamic_enable_icr0(pf);
12265 	}
12266 
12267 	return 0;
12268 }
12269 
12270 /**
12271  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
12272  * @pf: board private structure
12273  *
12274  * This sets up the handler for MSIX 0, which is used to manage the
12275  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
12276  * when in MSI or Legacy interrupt mode.
12277  **/
12278 static int i40e_setup_misc_vector(struct i40e_pf *pf)
12279 {
12280 	struct i40e_hw *hw = &pf->hw;
12281 	int err = 0;
12282 
12283 	/* Only request the IRQ once, the first time through. */
12284 	if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
12285 		err = request_irq(pf->msix_entries[0].vector,
12286 				  i40e_intr, 0, pf->int_name, pf);
12287 		if (err) {
12288 			clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
12289 			dev_info(&pf->pdev->dev,
12290 				 "request_irq for %s failed: %d\n",
12291 				 pf->int_name, err);
12292 			return -EFAULT;
12293 		}
12294 	}
12295 
12296 	i40e_enable_misc_int_causes(pf);
12297 
12298 	/* associate no queues to the misc vector */
12299 	wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
12300 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K >> 1);
12301 
12302 	i40e_flush(hw);
12303 
12304 	i40e_irq_dynamic_enable_icr0(pf);
12305 
12306 	return err;
12307 }
12308 
12309 /**
12310  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
12311  * @vsi: Pointer to vsi structure
12312  * @seed: Buffter to store the hash keys
12313  * @lut: Buffer to store the lookup table entries
12314  * @lut_size: Size of buffer to store the lookup table entries
12315  *
12316  * Return 0 on success, negative on failure
12317  */
12318 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
12319 			   u8 *lut, u16 lut_size)
12320 {
12321 	struct i40e_pf *pf = vsi->back;
12322 	struct i40e_hw *hw = &pf->hw;
12323 	int ret = 0;
12324 
12325 	if (seed) {
12326 		ret = i40e_aq_get_rss_key(hw, vsi->id,
12327 			(struct i40e_aqc_get_set_rss_key_data *)seed);
12328 		if (ret) {
12329 			dev_info(&pf->pdev->dev,
12330 				 "Cannot get RSS key, err %pe aq_err %s\n",
12331 				 ERR_PTR(ret),
12332 				 i40e_aq_str(&pf->hw,
12333 					     pf->hw.aq.asq_last_status));
12334 			return ret;
12335 		}
12336 	}
12337 
12338 	if (lut) {
12339 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
12340 
12341 		ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
12342 		if (ret) {
12343 			dev_info(&pf->pdev->dev,
12344 				 "Cannot get RSS lut, err %pe aq_err %s\n",
12345 				 ERR_PTR(ret),
12346 				 i40e_aq_str(&pf->hw,
12347 					     pf->hw.aq.asq_last_status));
12348 			return ret;
12349 		}
12350 	}
12351 
12352 	return ret;
12353 }
12354 
12355 /**
12356  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
12357  * @vsi: Pointer to vsi structure
12358  * @seed: RSS hash seed
12359  * @lut: Lookup table
12360  * @lut_size: Lookup table size
12361  *
12362  * Returns 0 on success, negative on failure
12363  **/
12364 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
12365 			       const u8 *lut, u16 lut_size)
12366 {
12367 	struct i40e_pf *pf = vsi->back;
12368 	struct i40e_hw *hw = &pf->hw;
12369 	u16 vf_id = vsi->vf_id;
12370 	u8 i;
12371 
12372 	/* Fill out hash function seed */
12373 	if (seed) {
12374 		u32 *seed_dw = (u32 *)seed;
12375 
12376 		if (vsi->type == I40E_VSI_MAIN) {
12377 			for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12378 				wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
12379 		} else if (vsi->type == I40E_VSI_SRIOV) {
12380 			for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
12381 				wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
12382 		} else {
12383 			dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
12384 		}
12385 	}
12386 
12387 	if (lut) {
12388 		u32 *lut_dw = (u32 *)lut;
12389 
12390 		if (vsi->type == I40E_VSI_MAIN) {
12391 			if (lut_size != I40E_HLUT_ARRAY_SIZE)
12392 				return -EINVAL;
12393 			for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12394 				wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
12395 		} else if (vsi->type == I40E_VSI_SRIOV) {
12396 			if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
12397 				return -EINVAL;
12398 			for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12399 				wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
12400 		} else {
12401 			dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12402 		}
12403 	}
12404 	i40e_flush(hw);
12405 
12406 	return 0;
12407 }
12408 
12409 /**
12410  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
12411  * @vsi: Pointer to VSI structure
12412  * @seed: Buffer to store the keys
12413  * @lut: Buffer to store the lookup table entries
12414  * @lut_size: Size of buffer to store the lookup table entries
12415  *
12416  * Returns 0 on success, negative on failure
12417  */
12418 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
12419 			    u8 *lut, u16 lut_size)
12420 {
12421 	struct i40e_pf *pf = vsi->back;
12422 	struct i40e_hw *hw = &pf->hw;
12423 	u16 i;
12424 
12425 	if (seed) {
12426 		u32 *seed_dw = (u32 *)seed;
12427 
12428 		for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12429 			seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
12430 	}
12431 	if (lut) {
12432 		u32 *lut_dw = (u32 *)lut;
12433 
12434 		if (lut_size != I40E_HLUT_ARRAY_SIZE)
12435 			return -EINVAL;
12436 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12437 			lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
12438 	}
12439 
12440 	return 0;
12441 }
12442 
12443 /**
12444  * i40e_config_rss - Configure RSS keys and lut
12445  * @vsi: Pointer to VSI structure
12446  * @seed: RSS hash seed
12447  * @lut: Lookup table
12448  * @lut_size: Lookup table size
12449  *
12450  * Returns 0 on success, negative on failure
12451  */
12452 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12453 {
12454 	struct i40e_pf *pf = vsi->back;
12455 
12456 	if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
12457 		return i40e_config_rss_aq(vsi, seed, lut, lut_size);
12458 	else
12459 		return i40e_config_rss_reg(vsi, seed, lut, lut_size);
12460 }
12461 
12462 /**
12463  * i40e_get_rss - Get RSS keys and lut
12464  * @vsi: Pointer to VSI structure
12465  * @seed: Buffer to store the keys
12466  * @lut: Buffer to store the lookup table entries
12467  * @lut_size: Size of buffer to store the lookup table entries
12468  *
12469  * Returns 0 on success, negative on failure
12470  */
12471 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12472 {
12473 	struct i40e_pf *pf = vsi->back;
12474 
12475 	if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
12476 		return i40e_get_rss_aq(vsi, seed, lut, lut_size);
12477 	else
12478 		return i40e_get_rss_reg(vsi, seed, lut, lut_size);
12479 }
12480 
12481 /**
12482  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
12483  * @pf: Pointer to board private structure
12484  * @lut: Lookup table
12485  * @rss_table_size: Lookup table size
12486  * @rss_size: Range of queue number for hashing
12487  */
12488 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
12489 		       u16 rss_table_size, u16 rss_size)
12490 {
12491 	u16 i;
12492 
12493 	for (i = 0; i < rss_table_size; i++)
12494 		lut[i] = i % rss_size;
12495 }
12496 
12497 /**
12498  * i40e_pf_config_rss - Prepare for RSS if used
12499  * @pf: board private structure
12500  **/
12501 static int i40e_pf_config_rss(struct i40e_pf *pf)
12502 {
12503 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
12504 	u8 seed[I40E_HKEY_ARRAY_SIZE];
12505 	u8 *lut;
12506 	struct i40e_hw *hw = &pf->hw;
12507 	u32 reg_val;
12508 	u64 hena;
12509 	int ret;
12510 
12511 	/* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
12512 	hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
12513 		((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
12514 	hena |= i40e_pf_get_default_rss_hashcfg(pf);
12515 
12516 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
12517 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
12518 
12519 	/* Determine the RSS table size based on the hardware capabilities */
12520 	reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
12521 	reg_val = (pf->rss_table_size == 512) ?
12522 			(reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
12523 			(reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
12524 	i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
12525 
12526 	/* Determine the RSS size of the VSI */
12527 	if (!vsi->rss_size) {
12528 		u16 qcount;
12529 		/* If the firmware does something weird during VSI init, we
12530 		 * could end up with zero TCs. Check for that to avoid
12531 		 * divide-by-zero. It probably won't pass traffic, but it also
12532 		 * won't panic.
12533 		 */
12534 		qcount = vsi->num_queue_pairs /
12535 			 (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
12536 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12537 	}
12538 	if (!vsi->rss_size)
12539 		return -EINVAL;
12540 
12541 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
12542 	if (!lut)
12543 		return -ENOMEM;
12544 
12545 	/* Use user configured lut if there is one, otherwise use default */
12546 	if (vsi->rss_lut_user)
12547 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
12548 	else
12549 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
12550 
12551 	/* Use user configured hash key if there is one, otherwise
12552 	 * use default.
12553 	 */
12554 	if (vsi->rss_hkey_user)
12555 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
12556 	else
12557 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
12558 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
12559 	kfree(lut);
12560 
12561 	return ret;
12562 }
12563 
12564 /**
12565  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
12566  * @pf: board private structure
12567  * @queue_count: the requested queue count for rss.
12568  *
12569  * returns 0 if rss is not enabled, if enabled returns the final rss queue
12570  * count which may be different from the requested queue count.
12571  * Note: expects to be called while under rtnl_lock()
12572  **/
12573 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
12574 {
12575 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
12576 	int new_rss_size;
12577 
12578 	if (!test_bit(I40E_FLAG_RSS_ENA, pf->flags))
12579 		return 0;
12580 
12581 	queue_count = min_t(int, queue_count, num_online_cpus());
12582 	new_rss_size = min_t(int, queue_count, pf->rss_size_max);
12583 
12584 	if (queue_count != vsi->num_queue_pairs) {
12585 		u16 qcount;
12586 
12587 		vsi->req_queue_pairs = queue_count;
12588 		i40e_prep_for_reset(pf);
12589 		if (test_bit(__I40E_IN_REMOVE, pf->state))
12590 			return pf->alloc_rss_size;
12591 
12592 		pf->alloc_rss_size = new_rss_size;
12593 
12594 		i40e_reset_and_rebuild(pf, true, true);
12595 
12596 		/* Discard the user configured hash keys and lut, if less
12597 		 * queues are enabled.
12598 		 */
12599 		if (queue_count < vsi->rss_size) {
12600 			i40e_clear_rss_config_user(vsi);
12601 			dev_dbg(&pf->pdev->dev,
12602 				"discard user configured hash keys and lut\n");
12603 		}
12604 
12605 		/* Reset vsi->rss_size, as number of enabled queues changed */
12606 		qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
12607 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12608 
12609 		i40e_pf_config_rss(pf);
12610 	}
12611 	dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
12612 		 vsi->req_queue_pairs, pf->rss_size_max);
12613 	return pf->alloc_rss_size;
12614 }
12615 
12616 /**
12617  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
12618  * @pf: board private structure
12619  **/
12620 int i40e_get_partition_bw_setting(struct i40e_pf *pf)
12621 {
12622 	bool min_valid, max_valid;
12623 	u32 max_bw, min_bw;
12624 	int status;
12625 
12626 	status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
12627 					   &min_valid, &max_valid);
12628 
12629 	if (!status) {
12630 		if (min_valid)
12631 			pf->min_bw = min_bw;
12632 		if (max_valid)
12633 			pf->max_bw = max_bw;
12634 	}
12635 
12636 	return status;
12637 }
12638 
12639 /**
12640  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
12641  * @pf: board private structure
12642  **/
12643 int i40e_set_partition_bw_setting(struct i40e_pf *pf)
12644 {
12645 	struct i40e_aqc_configure_partition_bw_data bw_data;
12646 	int status;
12647 
12648 	memset(&bw_data, 0, sizeof(bw_data));
12649 
12650 	/* Set the valid bit for this PF */
12651 	bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
12652 	bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
12653 	bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
12654 
12655 	/* Set the new bandwidths */
12656 	status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
12657 
12658 	return status;
12659 }
12660 
12661 /**
12662  * i40e_is_total_port_shutdown_enabled - read NVM and return value
12663  * if total port shutdown feature is enabled for this PF
12664  * @pf: board private structure
12665  **/
12666 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf)
12667 {
12668 #define I40E_TOTAL_PORT_SHUTDOWN_ENABLED	BIT(4)
12669 #define I40E_FEATURES_ENABLE_PTR		0x2A
12670 #define I40E_CURRENT_SETTING_PTR		0x2B
12671 #define I40E_LINK_BEHAVIOR_WORD_OFFSET		0x2D
12672 #define I40E_LINK_BEHAVIOR_WORD_LENGTH		0x1
12673 #define I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED	BIT(0)
12674 #define I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH	4
12675 	u16 sr_emp_sr_settings_ptr = 0;
12676 	u16 features_enable = 0;
12677 	u16 link_behavior = 0;
12678 	int read_status = 0;
12679 	bool ret = false;
12680 
12681 	read_status = i40e_read_nvm_word(&pf->hw,
12682 					 I40E_SR_EMP_SR_SETTINGS_PTR,
12683 					 &sr_emp_sr_settings_ptr);
12684 	if (read_status)
12685 		goto err_nvm;
12686 	read_status = i40e_read_nvm_word(&pf->hw,
12687 					 sr_emp_sr_settings_ptr +
12688 					 I40E_FEATURES_ENABLE_PTR,
12689 					 &features_enable);
12690 	if (read_status)
12691 		goto err_nvm;
12692 	if (I40E_TOTAL_PORT_SHUTDOWN_ENABLED & features_enable) {
12693 		read_status = i40e_read_nvm_module_data(&pf->hw,
12694 							I40E_SR_EMP_SR_SETTINGS_PTR,
12695 							I40E_CURRENT_SETTING_PTR,
12696 							I40E_LINK_BEHAVIOR_WORD_OFFSET,
12697 							I40E_LINK_BEHAVIOR_WORD_LENGTH,
12698 							&link_behavior);
12699 		if (read_status)
12700 			goto err_nvm;
12701 		link_behavior >>= (pf->hw.port * I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH);
12702 		ret = I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED & link_behavior;
12703 	}
12704 	return ret;
12705 
12706 err_nvm:
12707 	dev_warn(&pf->pdev->dev,
12708 		 "total-port-shutdown feature is off due to read nvm error: %pe\n",
12709 		 ERR_PTR(read_status));
12710 	return ret;
12711 }
12712 
12713 /**
12714  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
12715  * @pf: board private structure to initialize
12716  *
12717  * i40e_sw_init initializes the Adapter private data structure.
12718  * Fields are initialized based on PCI device information and
12719  * OS network device settings (MTU size).
12720  **/
12721 static int i40e_sw_init(struct i40e_pf *pf)
12722 {
12723 	int err = 0;
12724 	int size;
12725 	u16 pow;
12726 
12727 	/* Set default capability flags */
12728 	bitmap_zero(pf->flags, I40E_PF_FLAGS_NBITS);
12729 	set_bit(I40E_FLAG_MSI_ENA, pf->flags);
12730 	set_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12731 
12732 	/* Set default ITR */
12733 	pf->rx_itr_default = I40E_ITR_RX_DEF;
12734 	pf->tx_itr_default = I40E_ITR_TX_DEF;
12735 
12736 	/* Depending on PF configurations, it is possible that the RSS
12737 	 * maximum might end up larger than the available queues
12738 	 */
12739 	pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
12740 	pf->alloc_rss_size = 1;
12741 	pf->rss_table_size = pf->hw.func_caps.rss_table_size;
12742 	pf->rss_size_max = min_t(int, pf->rss_size_max,
12743 				 pf->hw.func_caps.num_tx_qp);
12744 
12745 	/* find the next higher power-of-2 of num cpus */
12746 	pow = roundup_pow_of_two(num_online_cpus());
12747 	pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
12748 
12749 	if (pf->hw.func_caps.rss) {
12750 		set_bit(I40E_FLAG_RSS_ENA, pf->flags);
12751 		pf->alloc_rss_size = min_t(int, pf->rss_size_max,
12752 					   num_online_cpus());
12753 	}
12754 
12755 	/* MFP mode enabled */
12756 	if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
12757 		set_bit(I40E_FLAG_MFP_ENA, pf->flags);
12758 		dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
12759 		if (i40e_get_partition_bw_setting(pf)) {
12760 			dev_warn(&pf->pdev->dev,
12761 				 "Could not get partition bw settings\n");
12762 		} else {
12763 			dev_info(&pf->pdev->dev,
12764 				 "Partition BW Min = %8.8x, Max = %8.8x\n",
12765 				 pf->min_bw, pf->max_bw);
12766 
12767 			/* nudge the Tx scheduler */
12768 			i40e_set_partition_bw_setting(pf);
12769 		}
12770 	}
12771 
12772 	if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
12773 	    (pf->hw.func_caps.fd_filters_best_effort > 0)) {
12774 		set_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
12775 		if (test_bit(I40E_FLAG_MFP_ENA, pf->flags) &&
12776 		    pf->hw.num_partitions > 1)
12777 			dev_info(&pf->pdev->dev,
12778 				 "Flow Director Sideband mode Disabled in MFP mode\n");
12779 		else
12780 			set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12781 		pf->fdir_pf_filter_count =
12782 				 pf->hw.func_caps.fd_filters_guaranteed;
12783 		pf->hw.fdir_shared_filter_count =
12784 				 pf->hw.func_caps.fd_filters_best_effort;
12785 	}
12786 
12787 	/* Enable HW ATR eviction if possible */
12788 	if (test_bit(I40E_HW_CAP_ATR_EVICT, pf->hw.caps))
12789 		set_bit(I40E_FLAG_HW_ATR_EVICT_ENA, pf->flags);
12790 
12791 	if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
12792 		pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
12793 		set_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
12794 		pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
12795 	}
12796 
12797 	if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
12798 		set_bit(I40E_FLAG_IWARP_ENA, pf->flags);
12799 		/* IWARP needs one extra vector for CQP just like MISC.*/
12800 		pf->num_iwarp_msix = (int)num_online_cpus() + 1;
12801 	}
12802 	/* Stopping FW LLDP engine is supported on XL710 and X722
12803 	 * starting from FW versions determined in i40e_init_adminq.
12804 	 * Stopping the FW LLDP engine is not supported on XL710
12805 	 * if NPAR is functioning so unset this hw flag in this case.
12806 	 */
12807 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
12808 	    pf->hw.func_caps.npar_enable)
12809 		clear_bit(I40E_HW_CAP_FW_LLDP_STOPPABLE, pf->hw.caps);
12810 
12811 #ifdef CONFIG_PCI_IOV
12812 	if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
12813 		pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
12814 		set_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
12815 		pf->num_req_vfs = min_t(int,
12816 					pf->hw.func_caps.num_vfs,
12817 					I40E_MAX_VF_COUNT);
12818 	}
12819 #endif /* CONFIG_PCI_IOV */
12820 	pf->lan_veb = I40E_NO_VEB;
12821 	pf->lan_vsi = I40E_NO_VSI;
12822 
12823 	/* By default FW has this off for performance reasons */
12824 	clear_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags);
12825 
12826 	/* set up queue assignment tracking */
12827 	size = sizeof(struct i40e_lump_tracking)
12828 		+ (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
12829 	pf->qp_pile = kzalloc(size, GFP_KERNEL);
12830 	if (!pf->qp_pile) {
12831 		err = -ENOMEM;
12832 		goto sw_init_done;
12833 	}
12834 	pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
12835 
12836 	pf->tx_timeout_recovery_level = 1;
12837 
12838 	if (pf->hw.mac.type != I40E_MAC_X722 &&
12839 	    i40e_is_total_port_shutdown_enabled(pf)) {
12840 		/* Link down on close must be on when total port shutdown
12841 		 * is enabled for a given port
12842 		 */
12843 		set_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags);
12844 		set_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags);
12845 		dev_info(&pf->pdev->dev,
12846 			 "total-port-shutdown was enabled, link-down-on-close is forced on\n");
12847 	}
12848 	mutex_init(&pf->switch_mutex);
12849 
12850 sw_init_done:
12851 	return err;
12852 }
12853 
12854 /**
12855  * i40e_set_ntuple - set the ntuple feature flag and take action
12856  * @pf: board private structure to initialize
12857  * @features: the feature set that the stack is suggesting
12858  *
12859  * returns a bool to indicate if reset needs to happen
12860  **/
12861 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12862 {
12863 	bool need_reset = false;
12864 
12865 	/* Check if Flow Director n-tuple support was enabled or disabled.  If
12866 	 * the state changed, we need to reset.
12867 	 */
12868 	if (features & NETIF_F_NTUPLE) {
12869 		/* Enable filters and mark for reset */
12870 		if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
12871 			need_reset = true;
12872 		/* enable FD_SB only if there is MSI-X vector and no cloud
12873 		 * filters exist
12874 		 */
12875 		if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12876 			set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12877 			clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12878 		}
12879 	} else {
12880 		/* turn off filters, mark for reset and clear SW filter list */
12881 		if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
12882 			need_reset = true;
12883 			i40e_fdir_filter_exit(pf);
12884 		}
12885 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12886 		clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12887 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12888 
12889 		/* reset fd counters */
12890 		pf->fd_add_err = 0;
12891 		pf->fd_atr_cnt = 0;
12892 		/* if ATR was auto disabled it can be re-enabled. */
12893 		if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12894 			if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
12895 			    (I40E_DEBUG_FD & pf->hw.debug_mask))
12896 				dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12897 	}
12898 	return need_reset;
12899 }
12900 
12901 /**
12902  * i40e_clear_rss_lut - clear the rx hash lookup table
12903  * @vsi: the VSI being configured
12904  **/
12905 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12906 {
12907 	struct i40e_pf *pf = vsi->back;
12908 	struct i40e_hw *hw = &pf->hw;
12909 	u16 vf_id = vsi->vf_id;
12910 	u8 i;
12911 
12912 	if (vsi->type == I40E_VSI_MAIN) {
12913 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12914 			wr32(hw, I40E_PFQF_HLUT(i), 0);
12915 	} else if (vsi->type == I40E_VSI_SRIOV) {
12916 		for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12917 			i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12918 	} else {
12919 		dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12920 	}
12921 }
12922 
12923 /**
12924  * i40e_set_loopback - turn on/off loopback mode on underlying PF
12925  * @vsi: ptr to VSI
12926  * @ena: flag to indicate the on/off setting
12927  */
12928 static int i40e_set_loopback(struct i40e_vsi *vsi, bool ena)
12929 {
12930 	bool if_running = netif_running(vsi->netdev) &&
12931 			  !test_and_set_bit(__I40E_VSI_DOWN, vsi->state);
12932 	int ret;
12933 
12934 	if (if_running)
12935 		i40e_down(vsi);
12936 
12937 	ret = i40e_aq_set_mac_loopback(&vsi->back->hw, ena, NULL);
12938 	if (ret)
12939 		netdev_err(vsi->netdev, "Failed to toggle loopback state\n");
12940 	if (if_running)
12941 		i40e_up(vsi);
12942 
12943 	return ret;
12944 }
12945 
12946 /**
12947  * i40e_set_features - set the netdev feature flags
12948  * @netdev: ptr to the netdev being adjusted
12949  * @features: the feature set that the stack is suggesting
12950  * Note: expects to be called while under rtnl_lock()
12951  **/
12952 static int i40e_set_features(struct net_device *netdev,
12953 			     netdev_features_t features)
12954 {
12955 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12956 	struct i40e_vsi *vsi = np->vsi;
12957 	struct i40e_pf *pf = vsi->back;
12958 	bool need_reset;
12959 
12960 	if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
12961 		i40e_pf_config_rss(pf);
12962 	else if (!(features & NETIF_F_RXHASH) &&
12963 		 netdev->features & NETIF_F_RXHASH)
12964 		i40e_clear_rss_lut(vsi);
12965 
12966 	if (features & NETIF_F_HW_VLAN_CTAG_RX)
12967 		i40e_vlan_stripping_enable(vsi);
12968 	else
12969 		i40e_vlan_stripping_disable(vsi);
12970 
12971 	if (!(features & NETIF_F_HW_TC) &&
12972 	    (netdev->features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
12973 		dev_err(&pf->pdev->dev,
12974 			"Offloaded tc filters active, can't turn hw_tc_offload off");
12975 		return -EINVAL;
12976 	}
12977 
12978 	if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
12979 		i40e_del_all_macvlans(vsi);
12980 
12981 	need_reset = i40e_set_ntuple(pf, features);
12982 
12983 	if (need_reset)
12984 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12985 
12986 	if ((features ^ netdev->features) & NETIF_F_LOOPBACK)
12987 		return i40e_set_loopback(vsi, !!(features & NETIF_F_LOOPBACK));
12988 
12989 	return 0;
12990 }
12991 
12992 static int i40e_udp_tunnel_set_port(struct net_device *netdev,
12993 				    unsigned int table, unsigned int idx,
12994 				    struct udp_tunnel_info *ti)
12995 {
12996 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12997 	struct i40e_hw *hw = &np->vsi->back->hw;
12998 	u8 type, filter_index;
12999 	int ret;
13000 
13001 	type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? I40E_AQC_TUNNEL_TYPE_VXLAN :
13002 						   I40E_AQC_TUNNEL_TYPE_NGE;
13003 
13004 	ret = i40e_aq_add_udp_tunnel(hw, ntohs(ti->port), type, &filter_index,
13005 				     NULL);
13006 	if (ret) {
13007 		netdev_info(netdev, "add UDP port failed, err %pe aq_err %s\n",
13008 			    ERR_PTR(ret),
13009 			    i40e_aq_str(hw, hw->aq.asq_last_status));
13010 		return -EIO;
13011 	}
13012 
13013 	udp_tunnel_nic_set_port_priv(netdev, table, idx, filter_index);
13014 	return 0;
13015 }
13016 
13017 static int i40e_udp_tunnel_unset_port(struct net_device *netdev,
13018 				      unsigned int table, unsigned int idx,
13019 				      struct udp_tunnel_info *ti)
13020 {
13021 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13022 	struct i40e_hw *hw = &np->vsi->back->hw;
13023 	int ret;
13024 
13025 	ret = i40e_aq_del_udp_tunnel(hw, ti->hw_priv, NULL);
13026 	if (ret) {
13027 		netdev_info(netdev, "delete UDP port failed, err %pe aq_err %s\n",
13028 			    ERR_PTR(ret),
13029 			    i40e_aq_str(hw, hw->aq.asq_last_status));
13030 		return -EIO;
13031 	}
13032 
13033 	return 0;
13034 }
13035 
13036 static int i40e_get_phys_port_id(struct net_device *netdev,
13037 				 struct netdev_phys_item_id *ppid)
13038 {
13039 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13040 	struct i40e_pf *pf = np->vsi->back;
13041 	struct i40e_hw *hw = &pf->hw;
13042 
13043 	if (!test_bit(I40E_HW_CAP_PORT_ID_VALID, pf->hw.caps))
13044 		return -EOPNOTSUPP;
13045 
13046 	ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
13047 	memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
13048 
13049 	return 0;
13050 }
13051 
13052 /**
13053  * i40e_ndo_fdb_add - add an entry to the hardware database
13054  * @ndm: the input from the stack
13055  * @tb: pointer to array of nladdr (unused)
13056  * @dev: the net device pointer
13057  * @addr: the MAC address entry being added
13058  * @vid: VLAN ID
13059  * @flags: instructions from stack about fdb operation
13060  * @notified: whether notification was emitted
13061  * @extack: netlink extended ack, unused currently
13062  */
13063 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
13064 			    struct net_device *dev,
13065 			    const unsigned char *addr, u16 vid,
13066 			    u16 flags, bool *notified,
13067 			    struct netlink_ext_ack *extack)
13068 {
13069 	struct i40e_netdev_priv *np = netdev_priv(dev);
13070 	struct i40e_pf *pf = np->vsi->back;
13071 	int err = 0;
13072 
13073 	if (!test_bit(I40E_FLAG_SRIOV_ENA, pf->flags))
13074 		return -EOPNOTSUPP;
13075 
13076 	if (vid) {
13077 		pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
13078 		return -EINVAL;
13079 	}
13080 
13081 	/* Hardware does not support aging addresses so if a
13082 	 * ndm_state is given only allow permanent addresses
13083 	 */
13084 	if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
13085 		netdev_info(dev, "FDB only supports static addresses\n");
13086 		return -EINVAL;
13087 	}
13088 
13089 	if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
13090 		err = dev_uc_add_excl(dev, addr);
13091 	else if (is_multicast_ether_addr(addr))
13092 		err = dev_mc_add_excl(dev, addr);
13093 	else
13094 		err = -EINVAL;
13095 
13096 	/* Only return duplicate errors if NLM_F_EXCL is set */
13097 	if (err == -EEXIST && !(flags & NLM_F_EXCL))
13098 		err = 0;
13099 
13100 	return err;
13101 }
13102 
13103 /**
13104  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
13105  * @dev: the netdev being configured
13106  * @nlh: RTNL message
13107  * @flags: bridge flags
13108  * @extack: netlink extended ack
13109  *
13110  * Inserts a new hardware bridge if not already created and
13111  * enables the bridging mode requested (VEB or VEPA). If the
13112  * hardware bridge has already been inserted and the request
13113  * is to change the mode then that requires a PF reset to
13114  * allow rebuild of the components with required hardware
13115  * bridge mode enabled.
13116  *
13117  * Note: expects to be called while under rtnl_lock()
13118  **/
13119 static int i40e_ndo_bridge_setlink(struct net_device *dev,
13120 				   struct nlmsghdr *nlh,
13121 				   u16 flags,
13122 				   struct netlink_ext_ack *extack)
13123 {
13124 	struct i40e_netdev_priv *np = netdev_priv(dev);
13125 	struct i40e_vsi *vsi = np->vsi;
13126 	struct i40e_pf *pf = vsi->back;
13127 	struct nlattr *attr, *br_spec;
13128 	struct i40e_veb *veb;
13129 	int rem;
13130 
13131 	/* Only for PF VSI for now */
13132 	if (vsi->type != I40E_VSI_MAIN)
13133 		return -EOPNOTSUPP;
13134 
13135 	/* Find the HW bridge for PF VSI */
13136 	veb = i40e_pf_get_veb_by_seid(pf, vsi->uplink_seid);
13137 
13138 	br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
13139 	if (!br_spec)
13140 		return -EINVAL;
13141 
13142 	nla_for_each_nested_type(attr, IFLA_BRIDGE_MODE, br_spec, rem) {
13143 		__u16 mode = nla_get_u16(attr);
13144 
13145 		if ((mode != BRIDGE_MODE_VEPA) &&
13146 		    (mode != BRIDGE_MODE_VEB))
13147 			return -EINVAL;
13148 
13149 		/* Insert a new HW bridge */
13150 		if (!veb) {
13151 			veb = i40e_veb_setup(pf, vsi->uplink_seid, vsi->seid,
13152 					     vsi->tc_config.enabled_tc);
13153 			if (veb) {
13154 				veb->bridge_mode = mode;
13155 				i40e_config_bridge_mode(veb);
13156 			} else {
13157 				/* No Bridge HW offload available */
13158 				return -ENOENT;
13159 			}
13160 			break;
13161 		} else if (mode != veb->bridge_mode) {
13162 			/* Existing HW bridge but different mode needs reset */
13163 			veb->bridge_mode = mode;
13164 			/* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
13165 			if (mode == BRIDGE_MODE_VEB)
13166 				set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
13167 			else
13168 				clear_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
13169 			i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13170 			break;
13171 		}
13172 	}
13173 
13174 	return 0;
13175 }
13176 
13177 /**
13178  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
13179  * @skb: skb buff
13180  * @pid: process id
13181  * @seq: RTNL message seq #
13182  * @dev: the netdev being configured
13183  * @filter_mask: unused
13184  * @nlflags: netlink flags passed in
13185  *
13186  * Return the mode in which the hardware bridge is operating in
13187  * i.e VEB or VEPA.
13188  **/
13189 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
13190 				   struct net_device *dev,
13191 				   u32 __always_unused filter_mask,
13192 				   int nlflags)
13193 {
13194 	struct i40e_netdev_priv *np = netdev_priv(dev);
13195 	struct i40e_vsi *vsi = np->vsi;
13196 	struct i40e_pf *pf = vsi->back;
13197 	struct i40e_veb *veb;
13198 
13199 	/* Only for PF VSI for now */
13200 	if (vsi->type != I40E_VSI_MAIN)
13201 		return -EOPNOTSUPP;
13202 
13203 	/* Find the HW bridge for the PF VSI */
13204 	veb = i40e_pf_get_veb_by_seid(pf, vsi->uplink_seid);
13205 	if (!veb)
13206 		return 0;
13207 
13208 	return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
13209 				       0, 0, nlflags, filter_mask, NULL);
13210 }
13211 
13212 /**
13213  * i40e_features_check - Validate encapsulated packet conforms to limits
13214  * @skb: skb buff
13215  * @dev: This physical port's netdev
13216  * @features: Offload features that the stack believes apply
13217  **/
13218 static netdev_features_t i40e_features_check(struct sk_buff *skb,
13219 					     struct net_device *dev,
13220 					     netdev_features_t features)
13221 {
13222 	size_t len;
13223 
13224 	/* No point in doing any of this if neither checksum nor GSO are
13225 	 * being requested for this frame.  We can rule out both by just
13226 	 * checking for CHECKSUM_PARTIAL
13227 	 */
13228 	if (skb->ip_summed != CHECKSUM_PARTIAL)
13229 		return features;
13230 
13231 	/* We cannot support GSO if the MSS is going to be less than
13232 	 * 64 bytes.  If it is then we need to drop support for GSO.
13233 	 */
13234 	if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
13235 		features &= ~NETIF_F_GSO_MASK;
13236 
13237 	/* MACLEN can support at most 63 words */
13238 	len = skb_network_offset(skb);
13239 	if (len & ~(63 * 2))
13240 		goto out_err;
13241 
13242 	/* IPLEN and EIPLEN can support at most 127 dwords */
13243 	len = skb_network_header_len(skb);
13244 	if (len & ~(127 * 4))
13245 		goto out_err;
13246 
13247 	if (skb->encapsulation) {
13248 		/* L4TUNLEN can support 127 words */
13249 		len = skb_inner_network_header(skb) - skb_transport_header(skb);
13250 		if (len & ~(127 * 2))
13251 			goto out_err;
13252 
13253 		/* IPLEN can support at most 127 dwords */
13254 		len = skb_inner_transport_header(skb) -
13255 		      skb_inner_network_header(skb);
13256 		if (len & ~(127 * 4))
13257 			goto out_err;
13258 	}
13259 
13260 	/* No need to validate L4LEN as TCP is the only protocol with a
13261 	 * flexible value and we support all possible values supported
13262 	 * by TCP, which is at most 15 dwords
13263 	 */
13264 
13265 	return features;
13266 out_err:
13267 	return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
13268 }
13269 
13270 /**
13271  * i40e_xdp_setup - add/remove an XDP program
13272  * @vsi: VSI to changed
13273  * @prog: XDP program
13274  * @extack: netlink extended ack
13275  **/
13276 static int i40e_xdp_setup(struct i40e_vsi *vsi, struct bpf_prog *prog,
13277 			  struct netlink_ext_ack *extack)
13278 {
13279 	int frame_size = i40e_max_vsi_frame_size(vsi, prog);
13280 	struct i40e_pf *pf = vsi->back;
13281 	struct bpf_prog *old_prog;
13282 	bool need_reset;
13283 	int i;
13284 
13285 	/* VSI shall be deleted in a moment, block loading new programs */
13286 	if (prog && test_bit(__I40E_IN_REMOVE, pf->state))
13287 		return -EINVAL;
13288 
13289 	/* Don't allow frames that span over multiple buffers */
13290 	if (vsi->netdev->mtu > frame_size - I40E_PACKET_HDR_PAD) {
13291 		NL_SET_ERR_MSG_MOD(extack, "MTU too large for linear frames and XDP prog does not support frags");
13292 		return -EINVAL;
13293 	}
13294 
13295 	/* When turning XDP on->off/off->on we reset and rebuild the rings. */
13296 	need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
13297 	if (need_reset)
13298 		i40e_prep_for_reset(pf);
13299 
13300 	old_prog = xchg(&vsi->xdp_prog, prog);
13301 
13302 	if (need_reset) {
13303 		if (!prog) {
13304 			xdp_features_clear_redirect_target(vsi->netdev);
13305 			/* Wait until ndo_xsk_wakeup completes. */
13306 			synchronize_rcu();
13307 		}
13308 		i40e_reset_and_rebuild(pf, true, true);
13309 	}
13310 
13311 	if (!i40e_enabled_xdp_vsi(vsi) && prog) {
13312 		if (i40e_realloc_rx_bi_zc(vsi, true))
13313 			return -ENOMEM;
13314 	} else if (i40e_enabled_xdp_vsi(vsi) && !prog) {
13315 		if (i40e_realloc_rx_bi_zc(vsi, false))
13316 			return -ENOMEM;
13317 	}
13318 
13319 	for (i = 0; i < vsi->num_queue_pairs; i++)
13320 		WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
13321 
13322 	if (old_prog)
13323 		bpf_prog_put(old_prog);
13324 
13325 	/* Kick start the NAPI context if there is an AF_XDP socket open
13326 	 * on that queue id. This so that receiving will start.
13327 	 */
13328 	if (need_reset && prog) {
13329 		for (i = 0; i < vsi->num_queue_pairs; i++)
13330 			if (vsi->xdp_rings[i]->xsk_pool)
13331 				(void)i40e_xsk_wakeup(vsi->netdev, i,
13332 						      XDP_WAKEUP_RX);
13333 		xdp_features_set_redirect_target(vsi->netdev, true);
13334 	}
13335 
13336 	return 0;
13337 }
13338 
13339 /**
13340  * i40e_enter_busy_conf - Enters busy config state
13341  * @vsi: vsi
13342  *
13343  * Returns 0 on success, <0 for failure.
13344  **/
13345 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
13346 {
13347 	struct i40e_pf *pf = vsi->back;
13348 	int timeout = 50;
13349 
13350 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
13351 		timeout--;
13352 		if (!timeout)
13353 			return -EBUSY;
13354 		usleep_range(1000, 2000);
13355 	}
13356 
13357 	return 0;
13358 }
13359 
13360 /**
13361  * i40e_exit_busy_conf - Exits busy config state
13362  * @vsi: vsi
13363  **/
13364 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
13365 {
13366 	struct i40e_pf *pf = vsi->back;
13367 
13368 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
13369 }
13370 
13371 /**
13372  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
13373  * @vsi: vsi
13374  * @queue_pair: queue pair
13375  **/
13376 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
13377 {
13378 	memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
13379 	       sizeof(vsi->rx_rings[queue_pair]->rx_stats));
13380 	memset(&vsi->tx_rings[queue_pair]->stats, 0,
13381 	       sizeof(vsi->tx_rings[queue_pair]->stats));
13382 	if (i40e_enabled_xdp_vsi(vsi)) {
13383 		memset(&vsi->xdp_rings[queue_pair]->stats, 0,
13384 		       sizeof(vsi->xdp_rings[queue_pair]->stats));
13385 	}
13386 }
13387 
13388 /**
13389  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
13390  * @vsi: vsi
13391  * @queue_pair: queue pair
13392  **/
13393 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
13394 {
13395 	i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
13396 	if (i40e_enabled_xdp_vsi(vsi)) {
13397 		/* Make sure that in-progress ndo_xdp_xmit calls are
13398 		 * completed.
13399 		 */
13400 		synchronize_rcu();
13401 		i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
13402 	}
13403 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13404 }
13405 
13406 /**
13407  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
13408  * @vsi: vsi
13409  * @queue_pair: queue pair
13410  * @enable: true for enable, false for disable
13411  **/
13412 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
13413 					bool enable)
13414 {
13415 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13416 	struct i40e_q_vector *q_vector = rxr->q_vector;
13417 
13418 	if (!vsi->netdev)
13419 		return;
13420 
13421 	/* All rings in a qp belong to the same qvector. */
13422 	if (q_vector->rx.ring || q_vector->tx.ring) {
13423 		if (enable)
13424 			napi_enable(&q_vector->napi);
13425 		else
13426 			napi_disable(&q_vector->napi);
13427 	}
13428 }
13429 
13430 /**
13431  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
13432  * @vsi: vsi
13433  * @queue_pair: queue pair
13434  * @enable: true for enable, false for disable
13435  *
13436  * Returns 0 on success, <0 on failure.
13437  **/
13438 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
13439 					bool enable)
13440 {
13441 	struct i40e_pf *pf = vsi->back;
13442 	int pf_q, ret = 0;
13443 
13444 	pf_q = vsi->base_queue + queue_pair;
13445 	ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
13446 				     false /*is xdp*/, enable);
13447 	if (ret) {
13448 		dev_info(&pf->pdev->dev,
13449 			 "VSI seid %d Tx ring %d %sable timeout\n",
13450 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13451 		return ret;
13452 	}
13453 
13454 	i40e_control_rx_q(pf, pf_q, enable);
13455 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
13456 	if (ret) {
13457 		dev_info(&pf->pdev->dev,
13458 			 "VSI seid %d Rx ring %d %sable timeout\n",
13459 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13460 		return ret;
13461 	}
13462 
13463 	/* Due to HW errata, on Rx disable only, the register can
13464 	 * indicate done before it really is. Needs 50ms to be sure
13465 	 */
13466 	if (!enable)
13467 		mdelay(50);
13468 
13469 	if (!i40e_enabled_xdp_vsi(vsi))
13470 		return ret;
13471 
13472 	ret = i40e_control_wait_tx_q(vsi->seid, pf,
13473 				     pf_q + vsi->alloc_queue_pairs,
13474 				     true /*is xdp*/, enable);
13475 	if (ret) {
13476 		dev_info(&pf->pdev->dev,
13477 			 "VSI seid %d XDP Tx ring %d %sable timeout\n",
13478 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13479 	}
13480 
13481 	return ret;
13482 }
13483 
13484 /**
13485  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
13486  * @vsi: vsi
13487  * @queue_pair: queue_pair
13488  **/
13489 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
13490 {
13491 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13492 	struct i40e_pf *pf = vsi->back;
13493 	struct i40e_hw *hw = &pf->hw;
13494 
13495 	/* All rings in a qp belong to the same qvector. */
13496 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
13497 		i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
13498 	else
13499 		i40e_irq_dynamic_enable_icr0(pf);
13500 
13501 	i40e_flush(hw);
13502 }
13503 
13504 /**
13505  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
13506  * @vsi: vsi
13507  * @queue_pair: queue_pair
13508  **/
13509 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
13510 {
13511 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13512 	struct i40e_pf *pf = vsi->back;
13513 	struct i40e_hw *hw = &pf->hw;
13514 
13515 	/* For simplicity, instead of removing the qp interrupt causes
13516 	 * from the interrupt linked list, we simply disable the interrupt, and
13517 	 * leave the list intact.
13518 	 *
13519 	 * All rings in a qp belong to the same qvector.
13520 	 */
13521 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
13522 		u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
13523 
13524 		wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
13525 		i40e_flush(hw);
13526 		synchronize_irq(pf->msix_entries[intpf].vector);
13527 	} else {
13528 		/* Legacy and MSI mode - this stops all interrupt handling */
13529 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
13530 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
13531 		i40e_flush(hw);
13532 		synchronize_irq(pf->pdev->irq);
13533 	}
13534 }
13535 
13536 /**
13537  * i40e_queue_pair_disable - Disables a queue pair
13538  * @vsi: vsi
13539  * @queue_pair: queue pair
13540  *
13541  * Returns 0 on success, <0 on failure.
13542  **/
13543 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
13544 {
13545 	int err;
13546 
13547 	err = i40e_enter_busy_conf(vsi);
13548 	if (err)
13549 		return err;
13550 
13551 	i40e_queue_pair_disable_irq(vsi, queue_pair);
13552 	i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
13553 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
13554 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13555 	i40e_queue_pair_clean_rings(vsi, queue_pair);
13556 	i40e_queue_pair_reset_stats(vsi, queue_pair);
13557 
13558 	return err;
13559 }
13560 
13561 /**
13562  * i40e_queue_pair_enable - Enables a queue pair
13563  * @vsi: vsi
13564  * @queue_pair: queue pair
13565  *
13566  * Returns 0 on success, <0 on failure.
13567  **/
13568 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
13569 {
13570 	int err;
13571 
13572 	err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
13573 	if (err)
13574 		return err;
13575 
13576 	if (i40e_enabled_xdp_vsi(vsi)) {
13577 		err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
13578 		if (err)
13579 			return err;
13580 	}
13581 
13582 	err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
13583 	if (err)
13584 		return err;
13585 
13586 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
13587 	i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
13588 	i40e_queue_pair_enable_irq(vsi, queue_pair);
13589 
13590 	i40e_exit_busy_conf(vsi);
13591 
13592 	return err;
13593 }
13594 
13595 /**
13596  * i40e_xdp - implements ndo_bpf for i40e
13597  * @dev: netdevice
13598  * @xdp: XDP command
13599  **/
13600 static int i40e_xdp(struct net_device *dev,
13601 		    struct netdev_bpf *xdp)
13602 {
13603 	struct i40e_netdev_priv *np = netdev_priv(dev);
13604 	struct i40e_vsi *vsi = np->vsi;
13605 
13606 	if (vsi->type != I40E_VSI_MAIN)
13607 		return -EINVAL;
13608 
13609 	switch (xdp->command) {
13610 	case XDP_SETUP_PROG:
13611 		return i40e_xdp_setup(vsi, xdp->prog, xdp->extack);
13612 	case XDP_SETUP_XSK_POOL:
13613 		return i40e_xsk_pool_setup(vsi, xdp->xsk.pool,
13614 					   xdp->xsk.queue_id);
13615 	default:
13616 		return -EINVAL;
13617 	}
13618 }
13619 
13620 static const struct net_device_ops i40e_netdev_ops = {
13621 	.ndo_open		= i40e_open,
13622 	.ndo_stop		= i40e_close,
13623 	.ndo_start_xmit		= i40e_lan_xmit_frame,
13624 	.ndo_get_stats64	= i40e_get_netdev_stats_struct,
13625 	.ndo_set_rx_mode	= i40e_set_rx_mode,
13626 	.ndo_validate_addr	= eth_validate_addr,
13627 	.ndo_set_mac_address	= i40e_set_mac,
13628 	.ndo_change_mtu		= i40e_change_mtu,
13629 	.ndo_eth_ioctl		= i40e_ioctl,
13630 	.ndo_tx_timeout		= i40e_tx_timeout,
13631 	.ndo_vlan_rx_add_vid	= i40e_vlan_rx_add_vid,
13632 	.ndo_vlan_rx_kill_vid	= i40e_vlan_rx_kill_vid,
13633 #ifdef CONFIG_NET_POLL_CONTROLLER
13634 	.ndo_poll_controller	= i40e_netpoll,
13635 #endif
13636 	.ndo_setup_tc		= __i40e_setup_tc,
13637 	.ndo_select_queue	= i40e_lan_select_queue,
13638 	.ndo_set_features	= i40e_set_features,
13639 	.ndo_set_vf_mac		= i40e_ndo_set_vf_mac,
13640 	.ndo_set_vf_vlan	= i40e_ndo_set_vf_port_vlan,
13641 	.ndo_get_vf_stats	= i40e_get_vf_stats,
13642 	.ndo_set_vf_rate	= i40e_ndo_set_vf_bw,
13643 	.ndo_get_vf_config	= i40e_ndo_get_vf_config,
13644 	.ndo_set_vf_link_state	= i40e_ndo_set_vf_link_state,
13645 	.ndo_set_vf_spoofchk	= i40e_ndo_set_vf_spoofchk,
13646 	.ndo_set_vf_trust	= i40e_ndo_set_vf_trust,
13647 	.ndo_get_phys_port_id	= i40e_get_phys_port_id,
13648 	.ndo_fdb_add		= i40e_ndo_fdb_add,
13649 	.ndo_features_check	= i40e_features_check,
13650 	.ndo_bridge_getlink	= i40e_ndo_bridge_getlink,
13651 	.ndo_bridge_setlink	= i40e_ndo_bridge_setlink,
13652 	.ndo_bpf		= i40e_xdp,
13653 	.ndo_xdp_xmit		= i40e_xdp_xmit,
13654 	.ndo_xsk_wakeup	        = i40e_xsk_wakeup,
13655 	.ndo_dfwd_add_station	= i40e_fwd_add,
13656 	.ndo_dfwd_del_station	= i40e_fwd_del,
13657 };
13658 
13659 /**
13660  * i40e_config_netdev - Setup the netdev flags
13661  * @vsi: the VSI being configured
13662  *
13663  * Returns 0 on success, negative value on failure
13664  **/
13665 static int i40e_config_netdev(struct i40e_vsi *vsi)
13666 {
13667 	struct i40e_pf *pf = vsi->back;
13668 	struct i40e_hw *hw = &pf->hw;
13669 	struct i40e_netdev_priv *np;
13670 	struct net_device *netdev;
13671 	u8 broadcast[ETH_ALEN];
13672 	u8 mac_addr[ETH_ALEN];
13673 	int etherdev_size;
13674 	netdev_features_t hw_enc_features;
13675 	netdev_features_t hw_features;
13676 
13677 	etherdev_size = sizeof(struct i40e_netdev_priv);
13678 	netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
13679 	if (!netdev)
13680 		return -ENOMEM;
13681 
13682 	vsi->netdev = netdev;
13683 	np = netdev_priv(netdev);
13684 	np->vsi = vsi;
13685 
13686 	hw_enc_features = NETIF_F_SG			|
13687 			  NETIF_F_HW_CSUM		|
13688 			  NETIF_F_HIGHDMA		|
13689 			  NETIF_F_SOFT_FEATURES		|
13690 			  NETIF_F_TSO			|
13691 			  NETIF_F_TSO_ECN		|
13692 			  NETIF_F_TSO6			|
13693 			  NETIF_F_GSO_GRE		|
13694 			  NETIF_F_GSO_GRE_CSUM		|
13695 			  NETIF_F_GSO_PARTIAL		|
13696 			  NETIF_F_GSO_IPXIP4		|
13697 			  NETIF_F_GSO_IPXIP6		|
13698 			  NETIF_F_GSO_UDP_TUNNEL	|
13699 			  NETIF_F_GSO_UDP_TUNNEL_CSUM	|
13700 			  NETIF_F_GSO_UDP_L4		|
13701 			  NETIF_F_SCTP_CRC		|
13702 			  NETIF_F_RXHASH		|
13703 			  NETIF_F_RXCSUM		|
13704 			  0;
13705 
13706 	if (!test_bit(I40E_HW_CAP_OUTER_UDP_CSUM, pf->hw.caps))
13707 		netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
13708 
13709 	netdev->udp_tunnel_nic_info = &pf->udp_tunnel_nic;
13710 
13711 	netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
13712 
13713 	netdev->hw_enc_features |= hw_enc_features;
13714 
13715 	/* record features VLANs can make use of */
13716 	netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
13717 
13718 #define I40E_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE |		\
13719 				   NETIF_F_GSO_GRE_CSUM |	\
13720 				   NETIF_F_GSO_IPXIP4 |		\
13721 				   NETIF_F_GSO_IPXIP6 |		\
13722 				   NETIF_F_GSO_UDP_TUNNEL |	\
13723 				   NETIF_F_GSO_UDP_TUNNEL_CSUM)
13724 
13725 	netdev->gso_partial_features = I40E_GSO_PARTIAL_FEATURES;
13726 	netdev->features |= NETIF_F_GSO_PARTIAL |
13727 			    I40E_GSO_PARTIAL_FEATURES;
13728 
13729 	netdev->mpls_features |= NETIF_F_SG;
13730 	netdev->mpls_features |= NETIF_F_HW_CSUM;
13731 	netdev->mpls_features |= NETIF_F_TSO;
13732 	netdev->mpls_features |= NETIF_F_TSO6;
13733 	netdev->mpls_features |= I40E_GSO_PARTIAL_FEATURES;
13734 
13735 	/* enable macvlan offloads */
13736 	netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
13737 
13738 	hw_features = hw_enc_features		|
13739 		      NETIF_F_HW_VLAN_CTAG_TX	|
13740 		      NETIF_F_HW_VLAN_CTAG_RX;
13741 
13742 	if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
13743 		hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
13744 
13745 	netdev->hw_features |= hw_features | NETIF_F_LOOPBACK;
13746 
13747 	netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
13748 	netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
13749 
13750 	netdev->features &= ~NETIF_F_HW_TC;
13751 
13752 	if (vsi->type == I40E_VSI_MAIN) {
13753 		SET_NETDEV_DEV(netdev, &pf->pdev->dev);
13754 		ether_addr_copy(mac_addr, hw->mac.perm_addr);
13755 		/* The following steps are necessary for two reasons. First,
13756 		 * some older NVM configurations load a default MAC-VLAN
13757 		 * filter that will accept any tagged packet, and we want to
13758 		 * replace this with a normal filter. Additionally, it is
13759 		 * possible our MAC address was provided by the platform using
13760 		 * Open Firmware or similar.
13761 		 *
13762 		 * Thus, we need to remove the default filter and install one
13763 		 * specific to the MAC address.
13764 		 */
13765 		i40e_rm_default_mac_filter(vsi, mac_addr);
13766 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13767 		i40e_add_mac_filter(vsi, mac_addr);
13768 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13769 
13770 		netdev->xdp_features = NETDEV_XDP_ACT_BASIC |
13771 				       NETDEV_XDP_ACT_REDIRECT |
13772 				       NETDEV_XDP_ACT_XSK_ZEROCOPY |
13773 				       NETDEV_XDP_ACT_RX_SG;
13774 		netdev->xdp_zc_max_segs = I40E_MAX_BUFFER_TXD;
13775 	} else {
13776 		/* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
13777 		 * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
13778 		 * the end, which is 4 bytes long, so force truncation of the
13779 		 * original name by IFNAMSIZ - 4
13780 		 */
13781 		struct i40e_vsi *main_vsi = i40e_pf_get_main_vsi(pf);
13782 
13783 		snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d", IFNAMSIZ - 4,
13784 			 main_vsi->netdev->name);
13785 		eth_random_addr(mac_addr);
13786 
13787 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13788 		i40e_add_mac_filter(vsi, mac_addr);
13789 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13790 	}
13791 
13792 	/* Add the broadcast filter so that we initially will receive
13793 	 * broadcast packets. Note that when a new VLAN is first added the
13794 	 * driver will convert all filters marked I40E_VLAN_ANY into VLAN
13795 	 * specific filters as part of transitioning into "vlan" operation.
13796 	 * When more VLANs are added, the driver will copy each existing MAC
13797 	 * filter and add it for the new VLAN.
13798 	 *
13799 	 * Broadcast filters are handled specially by
13800 	 * i40e_sync_filters_subtask, as the driver must to set the broadcast
13801 	 * promiscuous bit instead of adding this directly as a MAC/VLAN
13802 	 * filter. The subtask will update the correct broadcast promiscuous
13803 	 * bits as VLANs become active or inactive.
13804 	 */
13805 	eth_broadcast_addr(broadcast);
13806 	spin_lock_bh(&vsi->mac_filter_hash_lock);
13807 	i40e_add_mac_filter(vsi, broadcast);
13808 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
13809 
13810 	eth_hw_addr_set(netdev, mac_addr);
13811 	ether_addr_copy(netdev->perm_addr, mac_addr);
13812 
13813 	/* i40iw_net_event() reads 16 bytes from neigh->primary_key */
13814 	netdev->neigh_priv_len = sizeof(u32) * 4;
13815 
13816 	netdev->priv_flags |= IFF_UNICAST_FLT;
13817 	netdev->priv_flags |= IFF_SUPP_NOFCS;
13818 	/* Setup netdev TC information */
13819 	i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
13820 
13821 	netdev->netdev_ops = &i40e_netdev_ops;
13822 	netdev->watchdog_timeo = 5 * HZ;
13823 	i40e_set_ethtool_ops(netdev);
13824 
13825 	/* MTU range: 68 - 9706 */
13826 	netdev->min_mtu = ETH_MIN_MTU;
13827 	netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13828 
13829 	return 0;
13830 }
13831 
13832 /**
13833  * i40e_vsi_delete - Delete a VSI from the switch
13834  * @vsi: the VSI being removed
13835  *
13836  * Returns 0 on success, negative value on failure
13837  **/
13838 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13839 {
13840 	/* remove default VSI is not allowed */
13841 	if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13842 		return;
13843 
13844 	i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13845 }
13846 
13847 /**
13848  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13849  * @vsi: the VSI being queried
13850  *
13851  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13852  **/
13853 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13854 {
13855 	struct i40e_veb *veb;
13856 	struct i40e_pf *pf = vsi->back;
13857 
13858 	/* Uplink is not a bridge so default to VEB */
13859 	if (vsi->veb_idx >= I40E_MAX_VEB)
13860 		return 1;
13861 
13862 	veb = pf->veb[vsi->veb_idx];
13863 	if (!veb) {
13864 		dev_info(&pf->pdev->dev,
13865 			 "There is no veb associated with the bridge\n");
13866 		return -ENOENT;
13867 	}
13868 
13869 	/* Uplink is a bridge in VEPA mode */
13870 	if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13871 		return 0;
13872 	} else {
13873 		/* Uplink is a bridge in VEB mode */
13874 		return 1;
13875 	}
13876 
13877 	/* VEPA is now default bridge, so return 0 */
13878 	return 0;
13879 }
13880 
13881 /**
13882  * i40e_add_vsi - Add a VSI to the switch
13883  * @vsi: the VSI being configured
13884  *
13885  * This initializes a VSI context depending on the VSI type to be added and
13886  * passes it down to the add_vsi aq command.
13887  **/
13888 static int i40e_add_vsi(struct i40e_vsi *vsi)
13889 {
13890 	int ret = -ENODEV;
13891 	struct i40e_pf *pf = vsi->back;
13892 	struct i40e_hw *hw = &pf->hw;
13893 	struct i40e_vsi_context ctxt;
13894 	struct i40e_mac_filter *f;
13895 	struct hlist_node *h;
13896 	int bkt;
13897 
13898 	u8 enabled_tc = 0x1; /* TC0 enabled */
13899 	int f_count = 0;
13900 
13901 	memset(&ctxt, 0, sizeof(ctxt));
13902 	switch (vsi->type) {
13903 	case I40E_VSI_MAIN:
13904 		/* The PF's main VSI is already setup as part of the
13905 		 * device initialization, so we'll not bother with
13906 		 * the add_vsi call, but we will retrieve the current
13907 		 * VSI context.
13908 		 */
13909 		ctxt.seid = pf->main_vsi_seid;
13910 		ctxt.pf_num = pf->hw.pf_id;
13911 		ctxt.vf_num = 0;
13912 		ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13913 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13914 		if (ret) {
13915 			dev_info(&pf->pdev->dev,
13916 				 "couldn't get PF vsi config, err %pe aq_err %s\n",
13917 				 ERR_PTR(ret),
13918 				 i40e_aq_str(&pf->hw,
13919 					     pf->hw.aq.asq_last_status));
13920 			return -ENOENT;
13921 		}
13922 		vsi->info = ctxt.info;
13923 		vsi->info.valid_sections = 0;
13924 
13925 		vsi->seid = ctxt.seid;
13926 		vsi->id = ctxt.vsi_number;
13927 
13928 		enabled_tc = i40e_pf_get_tc_map(pf);
13929 
13930 		/* Source pruning is enabled by default, so the flag is
13931 		 * negative logic - if it's set, we need to fiddle with
13932 		 * the VSI to disable source pruning.
13933 		 */
13934 		if (test_bit(I40E_FLAG_SOURCE_PRUNING_DIS, pf->flags)) {
13935 			memset(&ctxt, 0, sizeof(ctxt));
13936 			ctxt.seid = pf->main_vsi_seid;
13937 			ctxt.pf_num = pf->hw.pf_id;
13938 			ctxt.vf_num = 0;
13939 			ctxt.info.valid_sections |=
13940 				     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13941 			ctxt.info.switch_id =
13942 				   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13943 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13944 			if (ret) {
13945 				dev_info(&pf->pdev->dev,
13946 					 "update vsi failed, err %d aq_err %s\n",
13947 					 ret,
13948 					 i40e_aq_str(&pf->hw,
13949 						     pf->hw.aq.asq_last_status));
13950 				ret = -ENOENT;
13951 				goto err;
13952 			}
13953 		}
13954 
13955 		/* MFP mode setup queue map and update VSI */
13956 		if (test_bit(I40E_FLAG_MFP_ENA, pf->flags) &&
13957 		    !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
13958 			memset(&ctxt, 0, sizeof(ctxt));
13959 			ctxt.seid = pf->main_vsi_seid;
13960 			ctxt.pf_num = pf->hw.pf_id;
13961 			ctxt.vf_num = 0;
13962 			i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
13963 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13964 			if (ret) {
13965 				dev_info(&pf->pdev->dev,
13966 					 "update vsi failed, err %pe aq_err %s\n",
13967 					 ERR_PTR(ret),
13968 					 i40e_aq_str(&pf->hw,
13969 						    pf->hw.aq.asq_last_status));
13970 				ret = -ENOENT;
13971 				goto err;
13972 			}
13973 			/* update the local VSI info queue map */
13974 			i40e_vsi_update_queue_map(vsi, &ctxt);
13975 			vsi->info.valid_sections = 0;
13976 		} else {
13977 			/* Default/Main VSI is only enabled for TC0
13978 			 * reconfigure it to enable all TCs that are
13979 			 * available on the port in SFP mode.
13980 			 * For MFP case the iSCSI PF would use this
13981 			 * flow to enable LAN+iSCSI TC.
13982 			 */
13983 			ret = i40e_vsi_config_tc(vsi, enabled_tc);
13984 			if (ret) {
13985 				/* Single TC condition is not fatal,
13986 				 * message and continue
13987 				 */
13988 				dev_info(&pf->pdev->dev,
13989 					 "failed to configure TCs for main VSI tc_map 0x%08x, err %pe aq_err %s\n",
13990 					 enabled_tc,
13991 					 ERR_PTR(ret),
13992 					 i40e_aq_str(&pf->hw,
13993 						    pf->hw.aq.asq_last_status));
13994 			}
13995 		}
13996 		break;
13997 
13998 	case I40E_VSI_FDIR:
13999 		ctxt.pf_num = hw->pf_id;
14000 		ctxt.vf_num = 0;
14001 		ctxt.uplink_seid = vsi->uplink_seid;
14002 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14003 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
14004 		if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags) &&
14005 		    (i40e_is_vsi_uplink_mode_veb(vsi))) {
14006 			ctxt.info.valid_sections |=
14007 			     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14008 			ctxt.info.switch_id =
14009 			   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14010 		}
14011 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14012 		break;
14013 
14014 	case I40E_VSI_VMDQ2:
14015 		ctxt.pf_num = hw->pf_id;
14016 		ctxt.vf_num = 0;
14017 		ctxt.uplink_seid = vsi->uplink_seid;
14018 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14019 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
14020 
14021 		/* This VSI is connected to VEB so the switch_id
14022 		 * should be set to zero by default.
14023 		 */
14024 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14025 			ctxt.info.valid_sections |=
14026 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14027 			ctxt.info.switch_id =
14028 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14029 		}
14030 
14031 		/* Setup the VSI tx/rx queue map for TC0 only for now */
14032 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14033 		break;
14034 
14035 	case I40E_VSI_SRIOV:
14036 		ctxt.pf_num = hw->pf_id;
14037 		ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
14038 		ctxt.uplink_seid = vsi->uplink_seid;
14039 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14040 		ctxt.flags = I40E_AQ_VSI_TYPE_VF;
14041 
14042 		/* This VSI is connected to VEB so the switch_id
14043 		 * should be set to zero by default.
14044 		 */
14045 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14046 			ctxt.info.valid_sections |=
14047 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14048 			ctxt.info.switch_id =
14049 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14050 		}
14051 
14052 		if (test_bit(I40E_FLAG_IWARP_ENA, vsi->back->flags)) {
14053 			ctxt.info.valid_sections |=
14054 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
14055 			ctxt.info.queueing_opt_flags |=
14056 				(I40E_AQ_VSI_QUE_OPT_TCP_ENA |
14057 				 I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
14058 		}
14059 
14060 		ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
14061 		ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
14062 		if (pf->vf[vsi->vf_id].spoofchk) {
14063 			ctxt.info.valid_sections |=
14064 				cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
14065 			ctxt.info.sec_flags |=
14066 				(I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
14067 				 I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
14068 		}
14069 		/* Setup the VSI tx/rx queue map for TC0 only for now */
14070 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14071 		break;
14072 
14073 	case I40E_VSI_IWARP:
14074 		/* send down message to iWARP */
14075 		break;
14076 
14077 	default:
14078 		return -ENODEV;
14079 	}
14080 
14081 	if (vsi->type != I40E_VSI_MAIN) {
14082 		ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
14083 		if (ret) {
14084 			dev_info(&vsi->back->pdev->dev,
14085 				 "add vsi failed, err %pe aq_err %s\n",
14086 				 ERR_PTR(ret),
14087 				 i40e_aq_str(&pf->hw,
14088 					     pf->hw.aq.asq_last_status));
14089 			ret = -ENOENT;
14090 			goto err;
14091 		}
14092 		vsi->info = ctxt.info;
14093 		vsi->info.valid_sections = 0;
14094 		vsi->seid = ctxt.seid;
14095 		vsi->id = ctxt.vsi_number;
14096 	}
14097 
14098 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14099 	vsi->active_filters = 0;
14100 	/* If macvlan filters already exist, force them to get loaded */
14101 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
14102 		f->state = I40E_FILTER_NEW;
14103 		f_count++;
14104 	}
14105 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14106 	clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
14107 
14108 	if (f_count) {
14109 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
14110 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
14111 	}
14112 
14113 	/* Update VSI BW information */
14114 	ret = i40e_vsi_get_bw_info(vsi);
14115 	if (ret) {
14116 		dev_info(&pf->pdev->dev,
14117 			 "couldn't get vsi bw info, err %pe aq_err %s\n",
14118 			 ERR_PTR(ret),
14119 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14120 		/* VSI is already added so not tearing that up */
14121 		ret = 0;
14122 	}
14123 
14124 err:
14125 	return ret;
14126 }
14127 
14128 /**
14129  * i40e_vsi_release - Delete a VSI and free its resources
14130  * @vsi: the VSI being removed
14131  *
14132  * Returns 0 on success or < 0 on error
14133  **/
14134 int i40e_vsi_release(struct i40e_vsi *vsi)
14135 {
14136 	struct i40e_mac_filter *f;
14137 	struct hlist_node *h;
14138 	struct i40e_veb *veb;
14139 	struct i40e_pf *pf;
14140 	u16 uplink_seid;
14141 	int i, n, bkt;
14142 
14143 	pf = vsi->back;
14144 
14145 	/* release of a VEB-owner or last VSI is not allowed */
14146 	if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
14147 		dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
14148 			 vsi->seid, vsi->uplink_seid);
14149 		return -ENODEV;
14150 	}
14151 	if (vsi->type == I40E_VSI_MAIN && !test_bit(__I40E_DOWN, pf->state)) {
14152 		dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
14153 		return -ENODEV;
14154 	}
14155 	set_bit(__I40E_VSI_RELEASING, vsi->state);
14156 	uplink_seid = vsi->uplink_seid;
14157 
14158 	if (vsi->type != I40E_VSI_SRIOV) {
14159 		if (vsi->netdev_registered) {
14160 			vsi->netdev_registered = false;
14161 			if (vsi->netdev) {
14162 				/* results in a call to i40e_close() */
14163 				unregister_netdev(vsi->netdev);
14164 			}
14165 		} else {
14166 			i40e_vsi_close(vsi);
14167 		}
14168 		i40e_vsi_disable_irq(vsi);
14169 	}
14170 
14171 	if (vsi->type == I40E_VSI_MAIN)
14172 		i40e_devlink_destroy_port(pf);
14173 
14174 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14175 
14176 	/* clear the sync flag on all filters */
14177 	if (vsi->netdev) {
14178 		__dev_uc_unsync(vsi->netdev, NULL);
14179 		__dev_mc_unsync(vsi->netdev, NULL);
14180 	}
14181 
14182 	/* make sure any remaining filters are marked for deletion */
14183 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
14184 		__i40e_del_filter(vsi, f);
14185 
14186 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14187 
14188 	i40e_sync_vsi_filters(vsi);
14189 
14190 	i40e_vsi_delete(vsi);
14191 	i40e_vsi_free_q_vectors(vsi);
14192 	if (vsi->netdev) {
14193 		free_netdev(vsi->netdev);
14194 		vsi->netdev = NULL;
14195 	}
14196 	i40e_vsi_clear_rings(vsi);
14197 	i40e_vsi_clear(vsi);
14198 
14199 	/* If this was the last thing on the VEB, except for the
14200 	 * controlling VSI, remove the VEB, which puts the controlling
14201 	 * VSI onto the uplink port.
14202 	 *
14203 	 * Well, okay, there's one more exception here: don't remove
14204 	 * the floating VEBs yet.  We'll wait for an explicit remove request
14205 	 * from up the network stack.
14206 	 */
14207 	veb = i40e_pf_get_veb_by_seid(pf, uplink_seid);
14208 	if (veb && veb->uplink_seid) {
14209 		n = 0;
14210 
14211 		/* Count non-controlling VSIs present on  the VEB */
14212 		i40e_pf_for_each_vsi(pf, i, vsi)
14213 			if (vsi->uplink_seid == uplink_seid &&
14214 			    (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14215 				n++;
14216 
14217 		/* If there is no VSI except the control one then release
14218 		 * the VEB and put the control VSI onto VEB uplink.
14219 		 */
14220 		if (!n)
14221 			i40e_veb_release(veb);
14222 	}
14223 
14224 	return 0;
14225 }
14226 
14227 /**
14228  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
14229  * @vsi: ptr to the VSI
14230  *
14231  * This should only be called after i40e_vsi_mem_alloc() which allocates the
14232  * corresponding SW VSI structure and initializes num_queue_pairs for the
14233  * newly allocated VSI.
14234  *
14235  * Returns 0 on success or negative on failure
14236  **/
14237 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
14238 {
14239 	int ret = -ENOENT;
14240 	struct i40e_pf *pf = vsi->back;
14241 
14242 	if (vsi->q_vectors[0]) {
14243 		dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
14244 			 vsi->seid);
14245 		return -EEXIST;
14246 	}
14247 
14248 	if (vsi->base_vector) {
14249 		dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
14250 			 vsi->seid, vsi->base_vector);
14251 		return -EEXIST;
14252 	}
14253 
14254 	ret = i40e_vsi_alloc_q_vectors(vsi);
14255 	if (ret) {
14256 		dev_info(&pf->pdev->dev,
14257 			 "failed to allocate %d q_vector for VSI %d, ret=%d\n",
14258 			 vsi->num_q_vectors, vsi->seid, ret);
14259 		vsi->num_q_vectors = 0;
14260 		goto vector_setup_out;
14261 	}
14262 
14263 	/* In Legacy mode, we do not have to get any other vector since we
14264 	 * piggyback on the misc/ICR0 for queue interrupts.
14265 	*/
14266 	if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
14267 		return ret;
14268 	if (vsi->num_q_vectors)
14269 		vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
14270 						 vsi->num_q_vectors, vsi->idx);
14271 	if (vsi->base_vector < 0) {
14272 		dev_info(&pf->pdev->dev,
14273 			 "failed to get tracking for %d vectors for VSI %d, err=%d\n",
14274 			 vsi->num_q_vectors, vsi->seid, vsi->base_vector);
14275 		i40e_vsi_free_q_vectors(vsi);
14276 		ret = -ENOENT;
14277 		goto vector_setup_out;
14278 	}
14279 
14280 vector_setup_out:
14281 	return ret;
14282 }
14283 
14284 /**
14285  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
14286  * @vsi: pointer to the vsi.
14287  *
14288  * This re-allocates a vsi's queue resources.
14289  *
14290  * Returns pointer to the successfully allocated and configured VSI sw struct
14291  * on success, otherwise returns NULL on failure.
14292  **/
14293 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
14294 {
14295 	struct i40e_vsi *main_vsi;
14296 	u16 alloc_queue_pairs;
14297 	struct i40e_pf *pf;
14298 	int ret;
14299 
14300 	if (!vsi)
14301 		return NULL;
14302 
14303 	pf = vsi->back;
14304 
14305 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
14306 	i40e_vsi_clear_rings(vsi);
14307 
14308 	i40e_vsi_free_arrays(vsi, false);
14309 	i40e_set_num_rings_in_vsi(vsi);
14310 	ret = i40e_vsi_alloc_arrays(vsi, false);
14311 	if (ret)
14312 		goto err_vsi;
14313 
14314 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14315 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14316 
14317 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14318 	if (ret < 0) {
14319 		dev_info(&pf->pdev->dev,
14320 			 "failed to get tracking for %d queues for VSI %d err %d\n",
14321 			 alloc_queue_pairs, vsi->seid, ret);
14322 		goto err_vsi;
14323 	}
14324 	vsi->base_queue = ret;
14325 
14326 	/* Update the FW view of the VSI. Force a reset of TC and queue
14327 	 * layout configurations.
14328 	 */
14329 	main_vsi = i40e_pf_get_main_vsi(pf);
14330 	main_vsi->seid = pf->main_vsi_seid;
14331 	i40e_vsi_reconfig_tc(main_vsi);
14332 
14333 	if (vsi->type == I40E_VSI_MAIN)
14334 		i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
14335 
14336 	/* assign it some queues */
14337 	ret = i40e_alloc_rings(vsi);
14338 	if (ret)
14339 		goto err_rings;
14340 
14341 	/* map all of the rings to the q_vectors */
14342 	i40e_vsi_map_rings_to_vectors(vsi);
14343 	return vsi;
14344 
14345 err_rings:
14346 	i40e_vsi_free_q_vectors(vsi);
14347 	if (vsi->netdev_registered) {
14348 		vsi->netdev_registered = false;
14349 		unregister_netdev(vsi->netdev);
14350 		free_netdev(vsi->netdev);
14351 		vsi->netdev = NULL;
14352 	}
14353 	if (vsi->type == I40E_VSI_MAIN)
14354 		i40e_devlink_destroy_port(pf);
14355 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14356 err_vsi:
14357 	i40e_vsi_clear(vsi);
14358 	return NULL;
14359 }
14360 
14361 /**
14362  * i40e_vsi_setup - Set up a VSI by a given type
14363  * @pf: board private structure
14364  * @type: VSI type
14365  * @uplink_seid: the switch element to link to
14366  * @param1: usage depends upon VSI type. For VF types, indicates VF id
14367  *
14368  * This allocates the sw VSI structure and its queue resources, then add a VSI
14369  * to the identified VEB.
14370  *
14371  * Returns pointer to the successfully allocated and configure VSI sw struct on
14372  * success, otherwise returns NULL on failure.
14373  **/
14374 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
14375 				u16 uplink_seid, u32 param1)
14376 {
14377 	struct i40e_vsi *vsi = NULL;
14378 	struct i40e_veb *veb = NULL;
14379 	u16 alloc_queue_pairs;
14380 	int v_idx;
14381 	int ret;
14382 
14383 	/* The requested uplink_seid must be either
14384 	 *     - the PF's port seid
14385 	 *              no VEB is needed because this is the PF
14386 	 *              or this is a Flow Director special case VSI
14387 	 *     - seid of an existing VEB
14388 	 *     - seid of a VSI that owns an existing VEB
14389 	 *     - seid of a VSI that doesn't own a VEB
14390 	 *              a new VEB is created and the VSI becomes the owner
14391 	 *     - seid of the PF VSI, which is what creates the first VEB
14392 	 *              this is a special case of the previous
14393 	 *
14394 	 * Find which uplink_seid we were given and create a new VEB if needed
14395 	 */
14396 	veb = i40e_pf_get_veb_by_seid(pf, uplink_seid);
14397 	if (!veb && uplink_seid != pf->mac_seid) {
14398 		vsi = i40e_pf_get_vsi_by_seid(pf, uplink_seid);
14399 		if (!vsi) {
14400 			dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
14401 				 uplink_seid);
14402 			return NULL;
14403 		}
14404 
14405 		if (vsi->uplink_seid == pf->mac_seid)
14406 			veb = i40e_veb_setup(pf, pf->mac_seid, vsi->seid,
14407 					     vsi->tc_config.enabled_tc);
14408 		else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14409 			veb = i40e_veb_setup(pf, vsi->uplink_seid, vsi->seid,
14410 					     vsi->tc_config.enabled_tc);
14411 		if (veb) {
14412 			if (vsi->type != I40E_VSI_MAIN) {
14413 				dev_info(&vsi->back->pdev->dev,
14414 					 "New VSI creation error, uplink seid of LAN VSI expected.\n");
14415 				return NULL;
14416 			}
14417 			/* We come up by default in VEPA mode if SRIOV is not
14418 			 * already enabled, in which case we can't force VEPA
14419 			 * mode.
14420 			 */
14421 			if (!test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
14422 				veb->bridge_mode = BRIDGE_MODE_VEPA;
14423 				clear_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
14424 			}
14425 			i40e_config_bridge_mode(veb);
14426 		}
14427 		veb = i40e_pf_get_veb_by_seid(pf, vsi->uplink_seid);
14428 		if (!veb) {
14429 			dev_info(&pf->pdev->dev, "couldn't add VEB\n");
14430 			return NULL;
14431 		}
14432 
14433 		vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14434 		uplink_seid = veb->seid;
14435 	}
14436 
14437 	/* get vsi sw struct */
14438 	v_idx = i40e_vsi_mem_alloc(pf, type);
14439 	if (v_idx < 0)
14440 		goto err_alloc;
14441 	vsi = pf->vsi[v_idx];
14442 	if (!vsi)
14443 		goto err_alloc;
14444 	vsi->type = type;
14445 	vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
14446 
14447 	if (type == I40E_VSI_MAIN)
14448 		pf->lan_vsi = v_idx;
14449 	else if (type == I40E_VSI_SRIOV)
14450 		vsi->vf_id = param1;
14451 	/* assign it some queues */
14452 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14453 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14454 
14455 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14456 	if (ret < 0) {
14457 		dev_info(&pf->pdev->dev,
14458 			 "failed to get tracking for %d queues for VSI %d err=%d\n",
14459 			 alloc_queue_pairs, vsi->seid, ret);
14460 		goto err_vsi;
14461 	}
14462 	vsi->base_queue = ret;
14463 
14464 	/* get a VSI from the hardware */
14465 	vsi->uplink_seid = uplink_seid;
14466 	ret = i40e_add_vsi(vsi);
14467 	if (ret)
14468 		goto err_vsi;
14469 
14470 	switch (vsi->type) {
14471 	/* setup the netdev if needed */
14472 	case I40E_VSI_MAIN:
14473 	case I40E_VSI_VMDQ2:
14474 		ret = i40e_config_netdev(vsi);
14475 		if (ret)
14476 			goto err_netdev;
14477 		ret = i40e_netif_set_realnum_tx_rx_queues(vsi);
14478 		if (ret)
14479 			goto err_netdev;
14480 		if (vsi->type == I40E_VSI_MAIN) {
14481 			ret = i40e_devlink_create_port(pf);
14482 			if (ret)
14483 				goto err_netdev;
14484 			SET_NETDEV_DEVLINK_PORT(vsi->netdev, &pf->devlink_port);
14485 		}
14486 		ret = register_netdev(vsi->netdev);
14487 		if (ret)
14488 			goto err_dl_port;
14489 		vsi->netdev_registered = true;
14490 		netif_carrier_off(vsi->netdev);
14491 #ifdef CONFIG_I40E_DCB
14492 		/* Setup DCB netlink interface */
14493 		i40e_dcbnl_setup(vsi);
14494 #endif /* CONFIG_I40E_DCB */
14495 		fallthrough;
14496 	case I40E_VSI_FDIR:
14497 		/* set up vectors and rings if needed */
14498 		ret = i40e_vsi_setup_vectors(vsi);
14499 		if (ret)
14500 			goto err_msix;
14501 
14502 		ret = i40e_alloc_rings(vsi);
14503 		if (ret)
14504 			goto err_rings;
14505 
14506 		/* map all of the rings to the q_vectors */
14507 		i40e_vsi_map_rings_to_vectors(vsi);
14508 
14509 		i40e_vsi_reset_stats(vsi);
14510 		break;
14511 	default:
14512 		/* no netdev or rings for the other VSI types */
14513 		break;
14514 	}
14515 
14516 	if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps) &&
14517 	    vsi->type == I40E_VSI_VMDQ2) {
14518 		ret = i40e_vsi_config_rss(vsi);
14519 		if (ret)
14520 			goto err_config;
14521 	}
14522 	return vsi;
14523 
14524 err_config:
14525 	i40e_vsi_clear_rings(vsi);
14526 err_rings:
14527 	i40e_vsi_free_q_vectors(vsi);
14528 err_msix:
14529 	if (vsi->netdev_registered) {
14530 		vsi->netdev_registered = false;
14531 		unregister_netdev(vsi->netdev);
14532 		free_netdev(vsi->netdev);
14533 		vsi->netdev = NULL;
14534 	}
14535 err_dl_port:
14536 	if (vsi->type == I40E_VSI_MAIN)
14537 		i40e_devlink_destroy_port(pf);
14538 err_netdev:
14539 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14540 err_vsi:
14541 	i40e_vsi_clear(vsi);
14542 err_alloc:
14543 	return NULL;
14544 }
14545 
14546 /**
14547  * i40e_veb_get_bw_info - Query VEB BW information
14548  * @veb: the veb to query
14549  *
14550  * Query the Tx scheduler BW configuration data for given VEB
14551  **/
14552 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
14553 {
14554 	struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
14555 	struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
14556 	struct i40e_pf *pf = veb->pf;
14557 	struct i40e_hw *hw = &pf->hw;
14558 	u32 tc_bw_max;
14559 	int ret = 0;
14560 	int i;
14561 
14562 	ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
14563 						  &bw_data, NULL);
14564 	if (ret) {
14565 		dev_info(&pf->pdev->dev,
14566 			 "query veb bw config failed, err %pe aq_err %s\n",
14567 			 ERR_PTR(ret),
14568 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14569 		goto out;
14570 	}
14571 
14572 	ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
14573 						   &ets_data, NULL);
14574 	if (ret) {
14575 		dev_info(&pf->pdev->dev,
14576 			 "query veb bw ets config failed, err %pe aq_err %s\n",
14577 			 ERR_PTR(ret),
14578 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14579 		goto out;
14580 	}
14581 
14582 	veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
14583 	veb->bw_max_quanta = ets_data.tc_bw_max;
14584 	veb->is_abs_credits = bw_data.absolute_credits_enable;
14585 	veb->enabled_tc = ets_data.tc_valid_bits;
14586 	tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
14587 		    (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
14588 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
14589 		veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
14590 		veb->bw_tc_limit_credits[i] =
14591 					le16_to_cpu(bw_data.tc_bw_limits[i]);
14592 		veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
14593 	}
14594 
14595 out:
14596 	return ret;
14597 }
14598 
14599 /**
14600  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
14601  * @pf: board private structure
14602  *
14603  * On error: returns error code (negative)
14604  * On success: returns vsi index in PF (positive)
14605  **/
14606 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
14607 {
14608 	int ret = -ENOENT;
14609 	struct i40e_veb *veb;
14610 	int i;
14611 
14612 	/* Need to protect the allocation of switch elements at the PF level */
14613 	mutex_lock(&pf->switch_mutex);
14614 
14615 	/* VEB list may be fragmented if VEB creation/destruction has
14616 	 * been happening.  We can afford to do a quick scan to look
14617 	 * for any free slots in the list.
14618 	 *
14619 	 * find next empty veb slot, looping back around if necessary
14620 	 */
14621 	i = 0;
14622 	while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
14623 		i++;
14624 	if (i >= I40E_MAX_VEB) {
14625 		ret = -ENOMEM;
14626 		goto err_alloc_veb;  /* out of VEB slots! */
14627 	}
14628 
14629 	veb = kzalloc(sizeof(*veb), GFP_KERNEL);
14630 	if (!veb) {
14631 		ret = -ENOMEM;
14632 		goto err_alloc_veb;
14633 	}
14634 	veb->pf = pf;
14635 	veb->idx = i;
14636 	veb->enabled_tc = 1;
14637 
14638 	pf->veb[i] = veb;
14639 	ret = i;
14640 err_alloc_veb:
14641 	mutex_unlock(&pf->switch_mutex);
14642 	return ret;
14643 }
14644 
14645 /**
14646  * i40e_switch_branch_release - Delete a branch of the switch tree
14647  * @branch: where to start deleting
14648  *
14649  * This uses recursion to find the tips of the branch to be
14650  * removed, deleting until we get back to and can delete this VEB.
14651  **/
14652 static void i40e_switch_branch_release(struct i40e_veb *branch)
14653 {
14654 	struct i40e_pf *pf = branch->pf;
14655 	u16 branch_seid = branch->seid;
14656 	u16 veb_idx = branch->idx;
14657 	struct i40e_vsi *vsi;
14658 	struct i40e_veb *veb;
14659 	int i;
14660 
14661 	/* release any VEBs on this VEB - RECURSION */
14662 	i40e_pf_for_each_veb(pf, i, veb)
14663 		if (veb->uplink_seid == branch->seid)
14664 			i40e_switch_branch_release(veb);
14665 
14666 	/* Release the VSIs on this VEB, but not the owner VSI.
14667 	 *
14668 	 * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
14669 	 *       the VEB itself, so don't use (*branch) after this loop.
14670 	 */
14671 	i40e_pf_for_each_vsi(pf, i, vsi)
14672 		if (vsi->uplink_seid == branch_seid &&
14673 		    (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14674 			i40e_vsi_release(vsi);
14675 
14676 	/* There's one corner case where the VEB might not have been
14677 	 * removed, so double check it here and remove it if needed.
14678 	 * This case happens if the veb was created from the debugfs
14679 	 * commands and no VSIs were added to it.
14680 	 */
14681 	if (pf->veb[veb_idx])
14682 		i40e_veb_release(pf->veb[veb_idx]);
14683 }
14684 
14685 /**
14686  * i40e_veb_clear - remove veb struct
14687  * @veb: the veb to remove
14688  **/
14689 static void i40e_veb_clear(struct i40e_veb *veb)
14690 {
14691 	if (!veb)
14692 		return;
14693 
14694 	if (veb->pf) {
14695 		struct i40e_pf *pf = veb->pf;
14696 
14697 		mutex_lock(&pf->switch_mutex);
14698 		if (pf->veb[veb->idx] == veb)
14699 			pf->veb[veb->idx] = NULL;
14700 		mutex_unlock(&pf->switch_mutex);
14701 	}
14702 
14703 	kfree(veb);
14704 }
14705 
14706 /**
14707  * i40e_veb_release - Delete a VEB and free its resources
14708  * @veb: the VEB being removed
14709  **/
14710 void i40e_veb_release(struct i40e_veb *veb)
14711 {
14712 	struct i40e_vsi *vsi, *vsi_it;
14713 	struct i40e_pf *pf;
14714 	int i, n = 0;
14715 
14716 	pf = veb->pf;
14717 
14718 	/* find the remaining VSI and check for extras */
14719 	i40e_pf_for_each_vsi(pf, i, vsi_it)
14720 		if (vsi_it->uplink_seid == veb->seid) {
14721 			if (vsi_it->flags & I40E_VSI_FLAG_VEB_OWNER)
14722 				vsi = vsi_it;
14723 			n++;
14724 		}
14725 
14726 	/* Floating VEB has to be empty and regular one must have
14727 	 * single owner VSI.
14728 	 */
14729 	if ((veb->uplink_seid && n != 1) || (!veb->uplink_seid && n != 0)) {
14730 		dev_info(&pf->pdev->dev,
14731 			 "can't remove VEB %d with %d VSIs left\n",
14732 			 veb->seid, n);
14733 		return;
14734 	}
14735 
14736 	/* For regular VEB move the owner VSI to uplink port */
14737 	if (veb->uplink_seid) {
14738 		vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
14739 		vsi->uplink_seid = veb->uplink_seid;
14740 		vsi->veb_idx = I40E_NO_VEB;
14741 	}
14742 
14743 	i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14744 	i40e_veb_clear(veb);
14745 }
14746 
14747 /**
14748  * i40e_add_veb - create the VEB in the switch
14749  * @veb: the VEB to be instantiated
14750  * @vsi: the controlling VSI
14751  **/
14752 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
14753 {
14754 	struct i40e_pf *pf = veb->pf;
14755 	bool enable_stats = !!test_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags);
14756 	int ret;
14757 
14758 	ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi ? vsi->seid : 0,
14759 			      veb->enabled_tc, vsi ? false : true,
14760 			      &veb->seid, enable_stats, NULL);
14761 
14762 	/* get a VEB from the hardware */
14763 	if (ret) {
14764 		dev_info(&pf->pdev->dev,
14765 			 "couldn't add VEB, err %pe aq_err %s\n",
14766 			 ERR_PTR(ret),
14767 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14768 		return -EPERM;
14769 	}
14770 
14771 	/* get statistics counter */
14772 	ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
14773 					 &veb->stats_idx, NULL, NULL, NULL);
14774 	if (ret) {
14775 		dev_info(&pf->pdev->dev,
14776 			 "couldn't get VEB statistics idx, err %pe aq_err %s\n",
14777 			 ERR_PTR(ret),
14778 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14779 		return -EPERM;
14780 	}
14781 	ret = i40e_veb_get_bw_info(veb);
14782 	if (ret) {
14783 		dev_info(&pf->pdev->dev,
14784 			 "couldn't get VEB bw info, err %pe aq_err %s\n",
14785 			 ERR_PTR(ret),
14786 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14787 		i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14788 		return -ENOENT;
14789 	}
14790 
14791 	if (vsi) {
14792 		vsi->uplink_seid = veb->seid;
14793 		vsi->veb_idx = veb->idx;
14794 		vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14795 	}
14796 
14797 	return 0;
14798 }
14799 
14800 /**
14801  * i40e_veb_setup - Set up a VEB
14802  * @pf: board private structure
14803  * @uplink_seid: the switch element to link to
14804  * @vsi_seid: the initial VSI seid
14805  * @enabled_tc: Enabled TC bit-map
14806  *
14807  * This allocates the sw VEB structure and links it into the switch
14808  * It is possible and legal for this to be a duplicate of an already
14809  * existing VEB.  It is also possible for both uplink and vsi seids
14810  * to be zero, in order to create a floating VEB.
14811  *
14812  * Returns pointer to the successfully allocated VEB sw struct on
14813  * success, otherwise returns NULL on failure.
14814  **/
14815 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 uplink_seid,
14816 				u16 vsi_seid, u8 enabled_tc)
14817 {
14818 	struct i40e_vsi *vsi = NULL;
14819 	struct i40e_veb *veb;
14820 	int veb_idx;
14821 	int ret;
14822 
14823 	/* if one seid is 0, the other must be 0 to create a floating relay */
14824 	if ((uplink_seid == 0 || vsi_seid == 0) &&
14825 	    (uplink_seid + vsi_seid != 0)) {
14826 		dev_info(&pf->pdev->dev,
14827 			 "one, not both seid's are 0: uplink=%d vsi=%d\n",
14828 			 uplink_seid, vsi_seid);
14829 		return NULL;
14830 	}
14831 
14832 	/* make sure there is such a vsi and uplink */
14833 	if (vsi_seid) {
14834 		vsi = i40e_pf_get_vsi_by_seid(pf, vsi_seid);
14835 		if (!vsi) {
14836 			dev_err(&pf->pdev->dev, "vsi seid %d not found\n",
14837 				vsi_seid);
14838 			return NULL;
14839 		}
14840 	}
14841 
14842 	/* get veb sw struct */
14843 	veb_idx = i40e_veb_mem_alloc(pf);
14844 	if (veb_idx < 0)
14845 		goto err_alloc;
14846 	veb = pf->veb[veb_idx];
14847 	veb->uplink_seid = uplink_seid;
14848 	veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14849 
14850 	/* create the VEB in the switch */
14851 	ret = i40e_add_veb(veb, vsi);
14852 	if (ret)
14853 		goto err_veb;
14854 
14855 	if (vsi && vsi->idx == pf->lan_vsi)
14856 		pf->lan_veb = veb->idx;
14857 
14858 	return veb;
14859 
14860 err_veb:
14861 	i40e_veb_clear(veb);
14862 err_alloc:
14863 	return NULL;
14864 }
14865 
14866 /**
14867  * i40e_setup_pf_switch_element - set PF vars based on switch type
14868  * @pf: board private structure
14869  * @ele: element we are building info from
14870  * @num_reported: total number of elements
14871  * @printconfig: should we print the contents
14872  *
14873  * helper function to assist in extracting a few useful SEID values.
14874  **/
14875 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14876 				struct i40e_aqc_switch_config_element_resp *ele,
14877 				u16 num_reported, bool printconfig)
14878 {
14879 	u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14880 	u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14881 	u8 element_type = ele->element_type;
14882 	u16 seid = le16_to_cpu(ele->seid);
14883 	struct i40e_veb *veb;
14884 
14885 	if (printconfig)
14886 		dev_info(&pf->pdev->dev,
14887 			 "type=%d seid=%d uplink=%d downlink=%d\n",
14888 			 element_type, seid, uplink_seid, downlink_seid);
14889 
14890 	switch (element_type) {
14891 	case I40E_SWITCH_ELEMENT_TYPE_MAC:
14892 		pf->mac_seid = seid;
14893 		break;
14894 	case I40E_SWITCH_ELEMENT_TYPE_VEB:
14895 		/* Main VEB? */
14896 		if (uplink_seid != pf->mac_seid)
14897 			break;
14898 		veb = i40e_pf_get_main_veb(pf);
14899 		if (!veb) {
14900 			int v;
14901 
14902 			/* find existing or else empty VEB */
14903 			veb = i40e_pf_get_veb_by_seid(pf, seid);
14904 			if (veb) {
14905 				pf->lan_veb = veb->idx;
14906 			} else {
14907 				v = i40e_veb_mem_alloc(pf);
14908 				if (v < 0)
14909 					break;
14910 				pf->lan_veb = v;
14911 			}
14912 		}
14913 
14914 		/* Try to get again main VEB as pf->lan_veb may have changed */
14915 		veb = i40e_pf_get_main_veb(pf);
14916 		if (!veb)
14917 			break;
14918 
14919 		veb->seid = seid;
14920 		veb->uplink_seid = pf->mac_seid;
14921 		veb->pf = pf;
14922 		break;
14923 	case I40E_SWITCH_ELEMENT_TYPE_VSI:
14924 		if (num_reported != 1)
14925 			break;
14926 		/* This is immediately after a reset so we can assume this is
14927 		 * the PF's VSI
14928 		 */
14929 		pf->mac_seid = uplink_seid;
14930 		pf->main_vsi_seid = seid;
14931 		if (printconfig)
14932 			dev_info(&pf->pdev->dev,
14933 				 "pf_seid=%d main_vsi_seid=%d\n",
14934 				 downlink_seid, pf->main_vsi_seid);
14935 		break;
14936 	case I40E_SWITCH_ELEMENT_TYPE_PF:
14937 	case I40E_SWITCH_ELEMENT_TYPE_VF:
14938 	case I40E_SWITCH_ELEMENT_TYPE_EMP:
14939 	case I40E_SWITCH_ELEMENT_TYPE_BMC:
14940 	case I40E_SWITCH_ELEMENT_TYPE_PE:
14941 	case I40E_SWITCH_ELEMENT_TYPE_PA:
14942 		/* ignore these for now */
14943 		break;
14944 	default:
14945 		dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
14946 			 element_type, seid);
14947 		break;
14948 	}
14949 }
14950 
14951 /**
14952  * i40e_fetch_switch_configuration - Get switch config from firmware
14953  * @pf: board private structure
14954  * @printconfig: should we print the contents
14955  *
14956  * Get the current switch configuration from the device and
14957  * extract a few useful SEID values.
14958  **/
14959 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
14960 {
14961 	struct i40e_aqc_get_switch_config_resp *sw_config;
14962 	u16 next_seid = 0;
14963 	int ret = 0;
14964 	u8 *aq_buf;
14965 	int i;
14966 
14967 	aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
14968 	if (!aq_buf)
14969 		return -ENOMEM;
14970 
14971 	sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
14972 	do {
14973 		u16 num_reported, num_total;
14974 
14975 		ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
14976 						I40E_AQ_LARGE_BUF,
14977 						&next_seid, NULL);
14978 		if (ret) {
14979 			dev_info(&pf->pdev->dev,
14980 				 "get switch config failed err %d aq_err %s\n",
14981 				 ret,
14982 				 i40e_aq_str(&pf->hw,
14983 					     pf->hw.aq.asq_last_status));
14984 			kfree(aq_buf);
14985 			return -ENOENT;
14986 		}
14987 
14988 		num_reported = le16_to_cpu(sw_config->header.num_reported);
14989 		num_total = le16_to_cpu(sw_config->header.num_total);
14990 
14991 		if (printconfig)
14992 			dev_info(&pf->pdev->dev,
14993 				 "header: %d reported %d total\n",
14994 				 num_reported, num_total);
14995 
14996 		for (i = 0; i < num_reported; i++) {
14997 			struct i40e_aqc_switch_config_element_resp *ele =
14998 				&sw_config->element[i];
14999 
15000 			i40e_setup_pf_switch_element(pf, ele, num_reported,
15001 						     printconfig);
15002 		}
15003 	} while (next_seid != 0);
15004 
15005 	kfree(aq_buf);
15006 	return ret;
15007 }
15008 
15009 /**
15010  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
15011  * @pf: board private structure
15012  * @reinit: if the Main VSI needs to re-initialized.
15013  * @lock_acquired: indicates whether or not the lock has been acquired
15014  *
15015  * Returns 0 on success, negative value on failure
15016  **/
15017 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired)
15018 {
15019 	struct i40e_vsi *main_vsi;
15020 	u16 flags = 0;
15021 	int ret;
15022 
15023 	/* find out what's out there already */
15024 	ret = i40e_fetch_switch_configuration(pf, false);
15025 	if (ret) {
15026 		dev_info(&pf->pdev->dev,
15027 			 "couldn't fetch switch config, err %pe aq_err %s\n",
15028 			 ERR_PTR(ret),
15029 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15030 		return ret;
15031 	}
15032 	i40e_pf_reset_stats(pf);
15033 
15034 	/* set the switch config bit for the whole device to
15035 	 * support limited promisc or true promisc
15036 	 * when user requests promisc. The default is limited
15037 	 * promisc.
15038 	*/
15039 
15040 	if ((pf->hw.pf_id == 0) &&
15041 	    !test_bit(I40E_FLAG_TRUE_PROMISC_ENA, pf->flags)) {
15042 		flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15043 		pf->last_sw_conf_flags = flags;
15044 	}
15045 
15046 	if (pf->hw.pf_id == 0) {
15047 		u16 valid_flags;
15048 
15049 		valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15050 		ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
15051 						NULL);
15052 		if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
15053 			dev_info(&pf->pdev->dev,
15054 				 "couldn't set switch config bits, err %pe aq_err %s\n",
15055 				 ERR_PTR(ret),
15056 				 i40e_aq_str(&pf->hw,
15057 					     pf->hw.aq.asq_last_status));
15058 			/* not a fatal problem, just keep going */
15059 		}
15060 		pf->last_sw_conf_valid_flags = valid_flags;
15061 	}
15062 
15063 	/* first time setup */
15064 	main_vsi = i40e_pf_get_main_vsi(pf);
15065 	if (!main_vsi || reinit) {
15066 		struct i40e_veb *veb;
15067 		u16 uplink_seid;
15068 
15069 		/* Set up the PF VSI associated with the PF's main VSI
15070 		 * that is already in the HW switch
15071 		 */
15072 		veb = i40e_pf_get_main_veb(pf);
15073 		if (veb)
15074 			uplink_seid = veb->seid;
15075 		else
15076 			uplink_seid = pf->mac_seid;
15077 		if (!main_vsi)
15078 			main_vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN,
15079 						  uplink_seid, 0);
15080 		else if (reinit)
15081 			main_vsi = i40e_vsi_reinit_setup(main_vsi);
15082 		if (!main_vsi) {
15083 			dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
15084 			i40e_cloud_filter_exit(pf);
15085 			i40e_fdir_teardown(pf);
15086 			return -EAGAIN;
15087 		}
15088 	} else {
15089 		/* force a reset of TC and queue layout configurations */
15090 		main_vsi->seid = pf->main_vsi_seid;
15091 		i40e_vsi_reconfig_tc(main_vsi);
15092 	}
15093 	i40e_vlan_stripping_disable(main_vsi);
15094 
15095 	i40e_fdir_sb_setup(pf);
15096 
15097 	/* Setup static PF queue filter control settings */
15098 	ret = i40e_setup_pf_filter_control(pf);
15099 	if (ret) {
15100 		dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
15101 			 ret);
15102 		/* Failure here should not stop continuing other steps */
15103 	}
15104 
15105 	/* enable RSS in the HW, even for only one queue, as the stack can use
15106 	 * the hash
15107 	 */
15108 	if (test_bit(I40E_FLAG_RSS_ENA, pf->flags))
15109 		i40e_pf_config_rss(pf);
15110 
15111 	/* fill in link information and enable LSE reporting */
15112 	i40e_link_event(pf);
15113 
15114 	i40e_ptp_init(pf);
15115 
15116 	if (!lock_acquired)
15117 		rtnl_lock();
15118 
15119 	/* repopulate tunnel port filters */
15120 	udp_tunnel_nic_reset_ntf(main_vsi->netdev);
15121 
15122 	if (!lock_acquired)
15123 		rtnl_unlock();
15124 
15125 	return ret;
15126 }
15127 
15128 /**
15129  * i40e_determine_queue_usage - Work out queue distribution
15130  * @pf: board private structure
15131  **/
15132 static void i40e_determine_queue_usage(struct i40e_pf *pf)
15133 {
15134 	int queues_left;
15135 	int q_max;
15136 
15137 	pf->num_lan_qps = 0;
15138 
15139 	/* Find the max queues to be put into basic use.  We'll always be
15140 	 * using TC0, whether or not DCB is running, and TC0 will get the
15141 	 * big RSS set.
15142 	 */
15143 	queues_left = pf->hw.func_caps.num_tx_qp;
15144 
15145 	if ((queues_left == 1) ||
15146 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
15147 		/* one qp for PF, no queues for anything else */
15148 		queues_left = 0;
15149 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15150 
15151 		/* make sure all the fancies are disabled */
15152 		clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
15153 		clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
15154 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15155 		clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
15156 		clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15157 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15158 		clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
15159 		clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
15160 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15161 	} else if (!test_bit(I40E_FLAG_RSS_ENA, pf->flags) &&
15162 		   !test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
15163 		   !test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
15164 		   !test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags)) {
15165 		/* one qp for PF */
15166 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15167 		queues_left -= pf->num_lan_qps;
15168 
15169 		clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
15170 		clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
15171 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15172 		clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
15173 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15174 		clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
15175 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15176 	} else {
15177 		/* Not enough queues for all TCs */
15178 		if (test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags) &&
15179 		    queues_left < I40E_MAX_TRAFFIC_CLASS) {
15180 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15181 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15182 			dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
15183 		}
15184 
15185 		/* limit lan qps to the smaller of qps, cpus or msix */
15186 		q_max = max_t(int, pf->rss_size_max, num_online_cpus());
15187 		q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
15188 		q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
15189 		pf->num_lan_qps = q_max;
15190 
15191 		queues_left -= pf->num_lan_qps;
15192 	}
15193 
15194 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
15195 		if (queues_left > 1) {
15196 			queues_left -= 1; /* save 1 queue for FD */
15197 		} else {
15198 			clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15199 			set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15200 			dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
15201 		}
15202 	}
15203 
15204 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
15205 	    pf->num_vf_qps && pf->num_req_vfs && queues_left) {
15206 		pf->num_req_vfs = min_t(int, pf->num_req_vfs,
15207 					(queues_left / pf->num_vf_qps));
15208 		queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
15209 	}
15210 
15211 	if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags) &&
15212 	    pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
15213 		pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
15214 					  (queues_left / pf->num_vmdq_qps));
15215 		queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
15216 	}
15217 
15218 	pf->queues_left = queues_left;
15219 	dev_dbg(&pf->pdev->dev,
15220 		"qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
15221 		pf->hw.func_caps.num_tx_qp,
15222 		!!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags),
15223 		pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
15224 		pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
15225 		queues_left);
15226 }
15227 
15228 /**
15229  * i40e_setup_pf_filter_control - Setup PF static filter control
15230  * @pf: PF to be setup
15231  *
15232  * i40e_setup_pf_filter_control sets up a PF's initial filter control
15233  * settings. If PE/FCoE are enabled then it will also set the per PF
15234  * based filter sizes required for them. It also enables Flow director,
15235  * ethertype and macvlan type filter settings for the pf.
15236  *
15237  * Returns 0 on success, negative on failure
15238  **/
15239 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
15240 {
15241 	struct i40e_filter_control_settings *settings = &pf->filter_settings;
15242 
15243 	settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
15244 
15245 	/* Flow Director is enabled */
15246 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) ||
15247 	    test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags))
15248 		settings->enable_fdir = true;
15249 
15250 	/* Ethtype and MACVLAN filters enabled for PF */
15251 	settings->enable_ethtype = true;
15252 	settings->enable_macvlan = true;
15253 
15254 	if (i40e_set_filter_control(&pf->hw, settings))
15255 		return -ENOENT;
15256 
15257 	return 0;
15258 }
15259 
15260 #define INFO_STRING_LEN 255
15261 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
15262 static void i40e_print_features(struct i40e_pf *pf)
15263 {
15264 	struct i40e_vsi *main_vsi = i40e_pf_get_main_vsi(pf);
15265 	struct i40e_hw *hw = &pf->hw;
15266 	char *buf;
15267 	int i;
15268 
15269 	buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
15270 	if (!buf)
15271 		return;
15272 
15273 	i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
15274 #ifdef CONFIG_PCI_IOV
15275 	i += scnprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
15276 #endif
15277 	i += scnprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
15278 		       pf->hw.func_caps.num_vsis, main_vsi->num_queue_pairs);
15279 	if (test_bit(I40E_FLAG_RSS_ENA, pf->flags))
15280 		i += scnprintf(&buf[i], REMAIN(i), " RSS");
15281 	if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags))
15282 		i += scnprintf(&buf[i], REMAIN(i), " FD_ATR");
15283 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
15284 		i += scnprintf(&buf[i], REMAIN(i), " FD_SB");
15285 		i += scnprintf(&buf[i], REMAIN(i), " NTUPLE");
15286 	}
15287 	if (test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
15288 		i += scnprintf(&buf[i], REMAIN(i), " DCB");
15289 	i += scnprintf(&buf[i], REMAIN(i), " VxLAN");
15290 	i += scnprintf(&buf[i], REMAIN(i), " Geneve");
15291 	if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
15292 		i += scnprintf(&buf[i], REMAIN(i), " PTP");
15293 	if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags))
15294 		i += scnprintf(&buf[i], REMAIN(i), " VEB");
15295 	else
15296 		i += scnprintf(&buf[i], REMAIN(i), " VEPA");
15297 
15298 	dev_info(&pf->pdev->dev, "%s\n", buf);
15299 	kfree(buf);
15300 	WARN_ON(i > INFO_STRING_LEN);
15301 }
15302 
15303 /**
15304  * i40e_get_platform_mac_addr - get platform-specific MAC address
15305  * @pdev: PCI device information struct
15306  * @pf: board private structure
15307  *
15308  * Look up the MAC address for the device. First we'll try
15309  * eth_platform_get_mac_address, which will check Open Firmware, or arch
15310  * specific fallback. Otherwise, we'll default to the stored value in
15311  * firmware.
15312  **/
15313 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
15314 {
15315 	if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
15316 		i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
15317 }
15318 
15319 /**
15320  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
15321  * @fec_cfg: FEC option to set in flags
15322  * @flags: ptr to flags in which we set FEC option
15323  **/
15324 void i40e_set_fec_in_flags(u8 fec_cfg, unsigned long *flags)
15325 {
15326 	if (fec_cfg & I40E_AQ_SET_FEC_AUTO) {
15327 		set_bit(I40E_FLAG_RS_FEC, flags);
15328 		set_bit(I40E_FLAG_BASE_R_FEC, flags);
15329 	}
15330 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
15331 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
15332 		set_bit(I40E_FLAG_RS_FEC, flags);
15333 		clear_bit(I40E_FLAG_BASE_R_FEC, flags);
15334 	}
15335 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
15336 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
15337 		set_bit(I40E_FLAG_BASE_R_FEC, flags);
15338 		clear_bit(I40E_FLAG_RS_FEC, flags);
15339 	}
15340 	if (fec_cfg == 0) {
15341 		clear_bit(I40E_FLAG_RS_FEC, flags);
15342 		clear_bit(I40E_FLAG_BASE_R_FEC, flags);
15343 	}
15344 }
15345 
15346 /**
15347  * i40e_check_recovery_mode - check if we are running transition firmware
15348  * @pf: board private structure
15349  *
15350  * Check registers indicating the firmware runs in recovery mode. Sets the
15351  * appropriate driver state.
15352  *
15353  * Returns true if the recovery mode was detected, false otherwise
15354  **/
15355 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
15356 {
15357 	u32 val = rd32(&pf->hw, I40E_GL_FWSTS);
15358 
15359 	if (val & I40E_GL_FWSTS_FWS1B_MASK) {
15360 		dev_crit(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
15361 		dev_crit(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
15362 		set_bit(__I40E_RECOVERY_MODE, pf->state);
15363 
15364 		return true;
15365 	}
15366 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15367 		dev_info(&pf->pdev->dev, "Please do Power-On Reset to initialize adapter in normal mode with full functionality.\n");
15368 
15369 	return false;
15370 }
15371 
15372 /**
15373  * i40e_pf_loop_reset - perform reset in a loop.
15374  * @pf: board private structure
15375  *
15376  * This function is useful when a NIC is about to enter recovery mode.
15377  * When a NIC's internal data structures are corrupted the NIC's
15378  * firmware is going to enter recovery mode.
15379  * Right after a POR it takes about 7 minutes for firmware to enter
15380  * recovery mode. Until that time a NIC is in some kind of intermediate
15381  * state. After that time period the NIC almost surely enters
15382  * recovery mode. The only way for a driver to detect intermediate
15383  * state is to issue a series of pf-resets and check a return value.
15384  * If a PF reset returns success then the firmware could be in recovery
15385  * mode so the caller of this code needs to check for recovery mode
15386  * if this function returns success. There is a little chance that
15387  * firmware will hang in intermediate state forever.
15388  * Since waiting 7 minutes is quite a lot of time this function waits
15389  * 10 seconds and then gives up by returning an error.
15390  *
15391  * Return 0 on success, negative on failure.
15392  **/
15393 static int i40e_pf_loop_reset(struct i40e_pf *pf)
15394 {
15395 	/* wait max 10 seconds for PF reset to succeed */
15396 	const unsigned long time_end = jiffies + 10 * HZ;
15397 	struct i40e_hw *hw = &pf->hw;
15398 	int ret;
15399 
15400 	ret = i40e_pf_reset(hw);
15401 	while (ret != 0 && time_before(jiffies, time_end)) {
15402 		usleep_range(10000, 20000);
15403 		ret = i40e_pf_reset(hw);
15404 	}
15405 
15406 	if (ret == 0)
15407 		pf->pfr_count++;
15408 	else
15409 		dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
15410 
15411 	return ret;
15412 }
15413 
15414 /**
15415  * i40e_check_fw_empr - check if FW issued unexpected EMP Reset
15416  * @pf: board private structure
15417  *
15418  * Check FW registers to determine if FW issued unexpected EMP Reset.
15419  * Every time when unexpected EMP Reset occurs the FW increments
15420  * a counter of unexpected EMP Resets. When the counter reaches 10
15421  * the FW should enter the Recovery mode
15422  *
15423  * Returns true if FW issued unexpected EMP Reset
15424  **/
15425 static bool i40e_check_fw_empr(struct i40e_pf *pf)
15426 {
15427 	const u32 fw_sts = rd32(&pf->hw, I40E_GL_FWSTS) &
15428 			   I40E_GL_FWSTS_FWS1B_MASK;
15429 	return (fw_sts > I40E_GL_FWSTS_FWS1B_EMPR_0) &&
15430 	       (fw_sts <= I40E_GL_FWSTS_FWS1B_EMPR_10);
15431 }
15432 
15433 /**
15434  * i40e_handle_resets - handle EMP resets and PF resets
15435  * @pf: board private structure
15436  *
15437  * Handle both EMP resets and PF resets and conclude whether there are
15438  * any issues regarding these resets. If there are any issues then
15439  * generate log entry.
15440  *
15441  * Return 0 if NIC is healthy or negative value when there are issues
15442  * with resets
15443  **/
15444 static int i40e_handle_resets(struct i40e_pf *pf)
15445 {
15446 	const int pfr = i40e_pf_loop_reset(pf);
15447 	const bool is_empr = i40e_check_fw_empr(pf);
15448 
15449 	if (is_empr || pfr != 0)
15450 		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");
15451 
15452 	return is_empr ? -EIO : pfr;
15453 }
15454 
15455 /**
15456  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
15457  * @pf: board private structure
15458  * @hw: ptr to the hardware info
15459  *
15460  * This function does a minimal setup of all subsystems needed for running
15461  * recovery mode.
15462  *
15463  * Returns 0 on success, negative on failure
15464  **/
15465 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
15466 {
15467 	struct i40e_vsi *vsi;
15468 	int err;
15469 	int v_idx;
15470 
15471 	pci_set_drvdata(pf->pdev, pf);
15472 	pci_save_state(pf->pdev);
15473 
15474 	/* set up periodic task facility */
15475 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15476 	pf->service_timer_period = HZ;
15477 
15478 	INIT_WORK(&pf->service_task, i40e_service_task);
15479 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15480 
15481 	err = i40e_init_interrupt_scheme(pf);
15482 	if (err)
15483 		goto err_switch_setup;
15484 
15485 	/* The number of VSIs reported by the FW is the minimum guaranteed
15486 	 * to us; HW supports far more and we share the remaining pool with
15487 	 * the other PFs. We allocate space for more than the guarantee with
15488 	 * the understanding that we might not get them all later.
15489 	 */
15490 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15491 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15492 	else
15493 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15494 
15495 	/* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
15496 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15497 			  GFP_KERNEL);
15498 	if (!pf->vsi) {
15499 		err = -ENOMEM;
15500 		goto err_switch_setup;
15501 	}
15502 
15503 	/* We allocate one VSI which is needed as absolute minimum
15504 	 * in order to register the netdev
15505 	 */
15506 	v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
15507 	if (v_idx < 0) {
15508 		err = v_idx;
15509 		goto err_switch_setup;
15510 	}
15511 	pf->lan_vsi = v_idx;
15512 	vsi = pf->vsi[v_idx];
15513 	if (!vsi) {
15514 		err = -EFAULT;
15515 		goto err_switch_setup;
15516 	}
15517 	vsi->alloc_queue_pairs = 1;
15518 	err = i40e_config_netdev(vsi);
15519 	if (err)
15520 		goto err_switch_setup;
15521 	err = register_netdev(vsi->netdev);
15522 	if (err)
15523 		goto err_switch_setup;
15524 	vsi->netdev_registered = true;
15525 	i40e_dbg_pf_init(pf);
15526 
15527 	err = i40e_setup_misc_vector_for_recovery_mode(pf);
15528 	if (err)
15529 		goto err_switch_setup;
15530 
15531 	/* tell the firmware that we're starting */
15532 	i40e_send_version(pf);
15533 
15534 	/* since everything's happy, start the service_task timer */
15535 	mod_timer(&pf->service_timer,
15536 		  round_jiffies(jiffies + pf->service_timer_period));
15537 
15538 	return 0;
15539 
15540 err_switch_setup:
15541 	i40e_reset_interrupt_capability(pf);
15542 	timer_shutdown_sync(&pf->service_timer);
15543 	i40e_shutdown_adminq(hw);
15544 	iounmap(hw->hw_addr);
15545 	pci_release_mem_regions(pf->pdev);
15546 	pci_disable_device(pf->pdev);
15547 	i40e_free_pf(pf);
15548 
15549 	return err;
15550 }
15551 
15552 /**
15553  * i40e_set_subsystem_device_id - set subsystem device id
15554  * @hw: pointer to the hardware info
15555  *
15556  * Set PCI subsystem device id either from a pci_dev structure or
15557  * a specific FW register.
15558  **/
15559 static inline void i40e_set_subsystem_device_id(struct i40e_hw *hw)
15560 {
15561 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
15562 
15563 	hw->subsystem_device_id = pf->pdev->subsystem_device ?
15564 		pf->pdev->subsystem_device :
15565 		(ushort)(rd32(hw, I40E_PFPCI_SUBSYSID) & USHRT_MAX);
15566 }
15567 
15568 /**
15569  * i40e_probe - Device initialization routine
15570  * @pdev: PCI device information struct
15571  * @ent: entry in i40e_pci_tbl
15572  *
15573  * i40e_probe initializes a PF identified by a pci_dev structure.
15574  * The OS initialization, configuring of the PF private structure,
15575  * and a hardware reset occur.
15576  *
15577  * Returns 0 on success, negative on failure
15578  **/
15579 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
15580 {
15581 	struct i40e_aq_get_phy_abilities_resp abilities;
15582 #ifdef CONFIG_I40E_DCB
15583 	enum i40e_get_fw_lldp_status_resp lldp_status;
15584 #endif /* CONFIG_I40E_DCB */
15585 	struct i40e_vsi *vsi;
15586 	struct i40e_pf *pf;
15587 	struct i40e_hw *hw;
15588 	u16 wol_nvm_bits;
15589 	char nvm_ver[32];
15590 	u16 link_status;
15591 #ifdef CONFIG_I40E_DCB
15592 	int status;
15593 #endif /* CONFIG_I40E_DCB */
15594 	int err;
15595 	u32 val;
15596 
15597 	err = pci_enable_device_mem(pdev);
15598 	if (err)
15599 		return err;
15600 
15601 	/* set up for high or low dma */
15602 	err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
15603 	if (err) {
15604 		dev_err(&pdev->dev,
15605 			"DMA configuration failed: 0x%x\n", err);
15606 		goto err_dma;
15607 	}
15608 
15609 	/* set up pci connections */
15610 	err = pci_request_mem_regions(pdev, i40e_driver_name);
15611 	if (err) {
15612 		dev_info(&pdev->dev,
15613 			 "pci_request_selected_regions failed %d\n", err);
15614 		goto err_pci_reg;
15615 	}
15616 
15617 	pci_set_master(pdev);
15618 
15619 	/* Now that we have a PCI connection, we need to do the
15620 	 * low level device setup.  This is primarily setting up
15621 	 * the Admin Queue structures and then querying for the
15622 	 * device's current profile information.
15623 	 */
15624 	pf = i40e_alloc_pf(&pdev->dev);
15625 	if (!pf) {
15626 		err = -ENOMEM;
15627 		goto err_pf_alloc;
15628 	}
15629 	pf->next_vsi = 0;
15630 	pf->pdev = pdev;
15631 	set_bit(__I40E_DOWN, pf->state);
15632 
15633 	hw = &pf->hw;
15634 
15635 	pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
15636 				I40E_MAX_CSR_SPACE);
15637 	/* We believe that the highest register to read is
15638 	 * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
15639 	 * is not less than that before mapping to prevent a
15640 	 * kernel panic.
15641 	 */
15642 	if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
15643 		dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
15644 			pf->ioremap_len);
15645 		err = -ENOMEM;
15646 		goto err_ioremap;
15647 	}
15648 	hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
15649 	if (!hw->hw_addr) {
15650 		err = -EIO;
15651 		dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
15652 			 (unsigned int)pci_resource_start(pdev, 0),
15653 			 pf->ioremap_len, err);
15654 		goto err_ioremap;
15655 	}
15656 	hw->vendor_id = pdev->vendor;
15657 	hw->device_id = pdev->device;
15658 	pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
15659 	hw->subsystem_vendor_id = pdev->subsystem_vendor;
15660 	i40e_set_subsystem_device_id(hw);
15661 	hw->bus.device = PCI_SLOT(pdev->devfn);
15662 	hw->bus.func = PCI_FUNC(pdev->devfn);
15663 	hw->bus.bus_id = pdev->bus->number;
15664 
15665 	/* Select something other than the 802.1ad ethertype for the
15666 	 * switch to use internally and drop on ingress.
15667 	 */
15668 	hw->switch_tag = 0xffff;
15669 	hw->first_tag = ETH_P_8021AD;
15670 	hw->second_tag = ETH_P_8021Q;
15671 
15672 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
15673 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
15674 	INIT_LIST_HEAD(&pf->ddp_old_prof);
15675 
15676 	/* set up the locks for the AQ, do this only once in probe
15677 	 * and destroy them only once in remove
15678 	 */
15679 	mutex_init(&hw->aq.asq_mutex);
15680 	mutex_init(&hw->aq.arq_mutex);
15681 
15682 	pf->msg_enable = netif_msg_init(debug,
15683 					NETIF_MSG_DRV |
15684 					NETIF_MSG_PROBE |
15685 					NETIF_MSG_LINK);
15686 	if (debug < -1)
15687 		pf->hw.debug_mask = debug;
15688 
15689 	/* do a special CORER for clearing PXE mode once at init */
15690 	if (hw->revision_id == 0 &&
15691 	    (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
15692 		wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
15693 		i40e_flush(hw);
15694 		msleep(200);
15695 		pf->corer_count++;
15696 
15697 		i40e_clear_pxe_mode(hw);
15698 	}
15699 
15700 	/* Reset here to make sure all is clean and to define PF 'n' */
15701 	i40e_clear_hw(hw);
15702 
15703 	err = i40e_set_mac_type(hw);
15704 	if (err) {
15705 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15706 			 err);
15707 		goto err_pf_reset;
15708 	}
15709 
15710 	err = i40e_handle_resets(pf);
15711 	if (err)
15712 		goto err_pf_reset;
15713 
15714 	i40e_check_recovery_mode(pf);
15715 
15716 	if (is_kdump_kernel()) {
15717 		hw->aq.num_arq_entries = I40E_MIN_ARQ_LEN;
15718 		hw->aq.num_asq_entries = I40E_MIN_ASQ_LEN;
15719 	} else {
15720 		hw->aq.num_arq_entries = I40E_AQ_LEN;
15721 		hw->aq.num_asq_entries = I40E_AQ_LEN;
15722 	}
15723 	hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15724 	hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15725 
15726 	snprintf(pf->int_name, sizeof(pf->int_name) - 1,
15727 		 "%s-%s:misc",
15728 		 dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
15729 
15730 	err = i40e_init_shared_code(hw);
15731 	if (err) {
15732 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15733 			 err);
15734 		goto err_pf_reset;
15735 	}
15736 
15737 	/* set up a default setting for link flow control */
15738 	pf->hw.fc.requested_mode = I40E_FC_NONE;
15739 
15740 	err = i40e_init_adminq(hw);
15741 	if (err) {
15742 		if (err == -EIO)
15743 			dev_info(&pdev->dev,
15744 				 "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",
15745 				 hw->aq.api_maj_ver,
15746 				 hw->aq.api_min_ver,
15747 				 I40E_FW_API_VERSION_MAJOR,
15748 				 I40E_FW_MINOR_VERSION(hw));
15749 		else
15750 			dev_info(&pdev->dev,
15751 				 "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
15752 
15753 		goto err_pf_reset;
15754 	}
15755 	i40e_get_oem_version(hw);
15756 	i40e_get_pba_string(hw);
15757 
15758 	/* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
15759 	i40e_nvm_version_str(hw, nvm_ver, sizeof(nvm_ver));
15760 	dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
15761 		 hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
15762 		 hw->aq.api_maj_ver, hw->aq.api_min_ver, nvm_ver,
15763 		 hw->vendor_id, hw->device_id, hw->subsystem_vendor_id,
15764 		 hw->subsystem_device_id);
15765 
15766 	if (i40e_is_aq_api_ver_ge(hw, I40E_FW_API_VERSION_MAJOR,
15767 				  I40E_FW_MINOR_VERSION(hw) + 1))
15768 		dev_dbg(&pdev->dev,
15769 			"The driver for the device detected a newer version of the NVM image v%u.%u than v%u.%u.\n",
15770 			 hw->aq.api_maj_ver,
15771 			 hw->aq.api_min_ver,
15772 			 I40E_FW_API_VERSION_MAJOR,
15773 			 I40E_FW_MINOR_VERSION(hw));
15774 	else if (i40e_is_aq_api_ver_lt(hw, 1, 4))
15775 		dev_info(&pdev->dev,
15776 			 "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",
15777 			 hw->aq.api_maj_ver,
15778 			 hw->aq.api_min_ver,
15779 			 I40E_FW_API_VERSION_MAJOR,
15780 			 I40E_FW_MINOR_VERSION(hw));
15781 
15782 	i40e_verify_eeprom(pf);
15783 
15784 	/* Rev 0 hardware was never productized */
15785 	if (hw->revision_id < 1)
15786 		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");
15787 
15788 	i40e_clear_pxe_mode(hw);
15789 
15790 	err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
15791 	if (err)
15792 		goto err_adminq_setup;
15793 
15794 	err = i40e_sw_init(pf);
15795 	if (err) {
15796 		dev_info(&pdev->dev, "sw_init failed: %d\n", err);
15797 		goto err_sw_init;
15798 	}
15799 
15800 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15801 		return i40e_init_recovery_mode(pf, hw);
15802 
15803 	err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
15804 				hw->func_caps.num_rx_qp, 0, 0);
15805 	if (err) {
15806 		dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
15807 		goto err_init_lan_hmc;
15808 	}
15809 
15810 	err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
15811 	if (err) {
15812 		dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
15813 		err = -ENOENT;
15814 		goto err_configure_lan_hmc;
15815 	}
15816 
15817 	/* Disable LLDP for NICs that have firmware versions lower than v4.3.
15818 	 * Ignore error return codes because if it was already disabled via
15819 	 * hardware settings this will fail
15820 	 */
15821 	if (test_bit(I40E_HW_CAP_STOP_FW_LLDP, pf->hw.caps)) {
15822 		dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
15823 		i40e_aq_stop_lldp(hw, true, false, NULL);
15824 	}
15825 
15826 	/* allow a platform config to override the HW addr */
15827 	i40e_get_platform_mac_addr(pdev, pf);
15828 
15829 	if (!is_valid_ether_addr(hw->mac.addr)) {
15830 		dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
15831 		err = -EIO;
15832 		goto err_mac_addr;
15833 	}
15834 	dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
15835 	ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
15836 	i40e_get_port_mac_addr(hw, hw->mac.port_addr);
15837 	if (is_valid_ether_addr(hw->mac.port_addr))
15838 		set_bit(I40E_HW_CAP_PORT_ID_VALID, pf->hw.caps);
15839 
15840 	i40e_ptp_alloc_pins(pf);
15841 	pci_set_drvdata(pdev, pf);
15842 	pci_save_state(pdev);
15843 
15844 #ifdef CONFIG_I40E_DCB
15845 	status = i40e_get_fw_lldp_status(&pf->hw, &lldp_status);
15846 	(!status &&
15847 	 lldp_status == I40E_GET_FW_LLDP_STATUS_ENABLED) ?
15848 		(clear_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags)) :
15849 		(set_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags));
15850 	dev_info(&pdev->dev,
15851 		 test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags) ?
15852 			"FW LLDP is disabled\n" :
15853 			"FW LLDP is enabled\n");
15854 
15855 	/* Enable FW to write default DCB config on link-up */
15856 	i40e_aq_set_dcb_parameters(hw, true, NULL);
15857 
15858 	err = i40e_init_pf_dcb(pf);
15859 	if (err) {
15860 		dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
15861 		clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15862 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15863 		/* Continue without DCB enabled */
15864 	}
15865 #endif /* CONFIG_I40E_DCB */
15866 
15867 	/* set up periodic task facility */
15868 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15869 	pf->service_timer_period = HZ;
15870 
15871 	INIT_WORK(&pf->service_task, i40e_service_task);
15872 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15873 
15874 	/* NVM bit on means WoL disabled for the port */
15875 	i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15876 	if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15877 		pf->wol_en = false;
15878 	else
15879 		pf->wol_en = true;
15880 	device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15881 
15882 	/* set up the main switch operations */
15883 	i40e_determine_queue_usage(pf);
15884 	err = i40e_init_interrupt_scheme(pf);
15885 	if (err)
15886 		goto err_switch_setup;
15887 
15888 	/* Reduce Tx and Rx pairs for kdump
15889 	 * When MSI-X is enabled, it's not allowed to use more TC queue
15890 	 * pairs than MSI-X vectors (pf->num_lan_msix) exist. Thus
15891 	 * vsi->num_queue_pairs will be equal to pf->num_lan_msix, i.e., 1.
15892 	 */
15893 	if (is_kdump_kernel())
15894 		pf->num_lan_msix = 1;
15895 
15896 	pf->udp_tunnel_nic.set_port = i40e_udp_tunnel_set_port;
15897 	pf->udp_tunnel_nic.unset_port = i40e_udp_tunnel_unset_port;
15898 	pf->udp_tunnel_nic.shared = &pf->udp_tunnel_shared;
15899 	pf->udp_tunnel_nic.tables[0].n_entries = I40E_MAX_PF_UDP_OFFLOAD_PORTS;
15900 	pf->udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
15901 						    UDP_TUNNEL_TYPE_GENEVE;
15902 
15903 	/* The number of VSIs reported by the FW is the minimum guaranteed
15904 	 * to us; HW supports far more and we share the remaining pool with
15905 	 * the other PFs. We allocate space for more than the guarantee with
15906 	 * the understanding that we might not get them all later.
15907 	 */
15908 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15909 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15910 	else
15911 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15912 	if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
15913 		dev_warn(&pf->pdev->dev,
15914 			 "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
15915 			 pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
15916 		pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
15917 	}
15918 
15919 	/* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15920 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15921 			  GFP_KERNEL);
15922 	if (!pf->vsi) {
15923 		err = -ENOMEM;
15924 		goto err_switch_setup;
15925 	}
15926 
15927 #ifdef CONFIG_PCI_IOV
15928 	/* prep for VF support */
15929 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
15930 	    test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
15931 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15932 		if (pci_num_vf(pdev))
15933 			set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
15934 	}
15935 #endif
15936 	err = i40e_setup_pf_switch(pf, false, false);
15937 	if (err) {
15938 		dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
15939 		goto err_vsis;
15940 	}
15941 
15942 	vsi = i40e_pf_get_main_vsi(pf);
15943 	INIT_LIST_HEAD(&vsi->ch_list);
15944 
15945 	/* if FDIR VSI was set up, start it now */
15946 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
15947 	if (vsi)
15948 		i40e_vsi_open(vsi);
15949 
15950 	/* The driver only wants link up/down and module qualification
15951 	 * reports from firmware.  Note the negative logic.
15952 	 */
15953 	err = i40e_aq_set_phy_int_mask(&pf->hw,
15954 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
15955 					 I40E_AQ_EVENT_MEDIA_NA |
15956 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
15957 	if (err)
15958 		dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
15959 			 ERR_PTR(err),
15960 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15961 
15962 	/* VF MDD event logs are rate limited to one second intervals */
15963 	ratelimit_state_init(&pf->mdd_message_rate_limit, 1 * HZ, 1);
15964 
15965 	/* Reconfigure hardware for allowing smaller MSS in the case
15966 	 * of TSO, so that we avoid the MDD being fired and causing
15967 	 * a reset in the case of small MSS+TSO.
15968 	 */
15969 	val = rd32(hw, I40E_REG_MSS);
15970 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
15971 		val &= ~I40E_REG_MSS_MIN_MASK;
15972 		val |= I40E_64BYTE_MSS;
15973 		wr32(hw, I40E_REG_MSS, val);
15974 	}
15975 
15976 	if (test_bit(I40E_HW_CAP_RESTART_AUTONEG, pf->hw.caps)) {
15977 		msleep(75);
15978 		err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
15979 		if (err)
15980 			dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
15981 				 ERR_PTR(err),
15982 				 i40e_aq_str(&pf->hw,
15983 					     pf->hw.aq.asq_last_status));
15984 	}
15985 	/* The main driver is (mostly) up and happy. We need to set this state
15986 	 * before setting up the misc vector or we get a race and the vector
15987 	 * ends up disabled forever.
15988 	 */
15989 	clear_bit(__I40E_DOWN, pf->state);
15990 
15991 	/* In case of MSIX we are going to setup the misc vector right here
15992 	 * to handle admin queue events etc. In case of legacy and MSI
15993 	 * the misc functionality and queue processing is combined in
15994 	 * the same vector and that gets setup at open.
15995 	 */
15996 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
15997 		err = i40e_setup_misc_vector(pf);
15998 		if (err) {
15999 			dev_info(&pdev->dev,
16000 				 "setup of misc vector failed: %d\n", err);
16001 			i40e_cloud_filter_exit(pf);
16002 			i40e_fdir_teardown(pf);
16003 			goto err_vsis;
16004 		}
16005 	}
16006 
16007 #ifdef CONFIG_PCI_IOV
16008 	/* prep for VF support */
16009 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
16010 	    test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
16011 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
16012 		/* disable link interrupts for VFs */
16013 		val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
16014 		val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
16015 		wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
16016 		i40e_flush(hw);
16017 
16018 		if (pci_num_vf(pdev)) {
16019 			dev_info(&pdev->dev,
16020 				 "Active VFs found, allocating resources.\n");
16021 			err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
16022 			if (err)
16023 				dev_info(&pdev->dev,
16024 					 "Error %d allocating resources for existing VFs\n",
16025 					 err);
16026 		}
16027 	}
16028 #endif /* CONFIG_PCI_IOV */
16029 
16030 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
16031 		pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
16032 						      pf->num_iwarp_msix,
16033 						      I40E_IWARP_IRQ_PILE_ID);
16034 		if (pf->iwarp_base_vector < 0) {
16035 			dev_info(&pdev->dev,
16036 				 "failed to get tracking for %d vectors for IWARP err=%d\n",
16037 				 pf->num_iwarp_msix, pf->iwarp_base_vector);
16038 			clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
16039 		}
16040 	}
16041 
16042 	i40e_dbg_pf_init(pf);
16043 
16044 	/* tell the firmware that we're starting */
16045 	i40e_send_version(pf);
16046 
16047 	/* since everything's happy, start the service_task timer */
16048 	mod_timer(&pf->service_timer,
16049 		  round_jiffies(jiffies + pf->service_timer_period));
16050 
16051 	/* add this PF to client device list and launch a client service task */
16052 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
16053 		err = i40e_lan_add_device(pf);
16054 		if (err)
16055 			dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
16056 				 err);
16057 	}
16058 
16059 #define PCI_SPEED_SIZE 8
16060 #define PCI_WIDTH_SIZE 8
16061 	/* Devices on the IOSF bus do not have this information
16062 	 * and will report PCI Gen 1 x 1 by default so don't bother
16063 	 * checking them.
16064 	 */
16065 	if (!test_bit(I40E_HW_CAP_NO_PCI_LINK_CHECK, pf->hw.caps)) {
16066 		char speed[PCI_SPEED_SIZE] = "Unknown";
16067 		char width[PCI_WIDTH_SIZE] = "Unknown";
16068 
16069 		/* Get the negotiated link width and speed from PCI config
16070 		 * space
16071 		 */
16072 		pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
16073 					  &link_status);
16074 
16075 		i40e_set_pci_config_data(hw, link_status);
16076 
16077 		switch (hw->bus.speed) {
16078 		case i40e_bus_speed_8000:
16079 			strscpy(speed, "8.0", PCI_SPEED_SIZE); break;
16080 		case i40e_bus_speed_5000:
16081 			strscpy(speed, "5.0", PCI_SPEED_SIZE); break;
16082 		case i40e_bus_speed_2500:
16083 			strscpy(speed, "2.5", PCI_SPEED_SIZE); break;
16084 		default:
16085 			break;
16086 		}
16087 		switch (hw->bus.width) {
16088 		case i40e_bus_width_pcie_x8:
16089 			strscpy(width, "8", PCI_WIDTH_SIZE); break;
16090 		case i40e_bus_width_pcie_x4:
16091 			strscpy(width, "4", PCI_WIDTH_SIZE); break;
16092 		case i40e_bus_width_pcie_x2:
16093 			strscpy(width, "2", PCI_WIDTH_SIZE); break;
16094 		case i40e_bus_width_pcie_x1:
16095 			strscpy(width, "1", PCI_WIDTH_SIZE); break;
16096 		default:
16097 			break;
16098 		}
16099 
16100 		dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
16101 			 speed, width);
16102 
16103 		if (hw->bus.width < i40e_bus_width_pcie_x8 ||
16104 		    hw->bus.speed < i40e_bus_speed_8000) {
16105 			dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
16106 			dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
16107 		}
16108 	}
16109 
16110 	/* get the requested speeds from the fw */
16111 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
16112 	if (err)
16113 		dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %pe last_status =  %s\n",
16114 			ERR_PTR(err),
16115 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16116 	pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
16117 
16118 	/* set the FEC config due to the board capabilities */
16119 	i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, pf->flags);
16120 
16121 	/* get the supported phy types from the fw */
16122 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
16123 	if (err)
16124 		dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %pe last_status =  %s\n",
16125 			ERR_PTR(err),
16126 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16127 
16128 	/* make sure the MFS hasn't been set lower than the default */
16129 #define MAX_FRAME_SIZE_DEFAULT 0x2600
16130 	val = FIELD_GET(I40E_PRTGL_SAH_MFS_MASK,
16131 			rd32(&pf->hw, I40E_PRTGL_SAH));
16132 	if (val < MAX_FRAME_SIZE_DEFAULT)
16133 		dev_warn(&pdev->dev, "MFS for port %x (%d) has been set below the default (%d)\n",
16134 			 pf->hw.port, val, MAX_FRAME_SIZE_DEFAULT);
16135 
16136 	/* Add a filter to drop all Flow control frames from any VSI from being
16137 	 * transmitted. By doing so we stop a malicious VF from sending out
16138 	 * PAUSE or PFC frames and potentially controlling traffic for other
16139 	 * PF/VF VSIs.
16140 	 * The FW can still send Flow control frames if enabled.
16141 	 */
16142 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
16143 						       pf->main_vsi_seid);
16144 
16145 	if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
16146 	    (pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
16147 		set_bit(I40E_HW_CAP_PHY_CONTROLS_LEDS, pf->hw.caps);
16148 	if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
16149 		set_bit(I40E_HW_CAP_CRT_RETIMER, pf->hw.caps);
16150 	/* print a string summarizing features */
16151 	i40e_print_features(pf);
16152 
16153 	i40e_devlink_register(pf);
16154 
16155 	return 0;
16156 
16157 	/* Unwind what we've done if something failed in the setup */
16158 err_vsis:
16159 	set_bit(__I40E_DOWN, pf->state);
16160 	i40e_clear_interrupt_scheme(pf);
16161 	kfree(pf->vsi);
16162 err_switch_setup:
16163 	i40e_reset_interrupt_capability(pf);
16164 	timer_shutdown_sync(&pf->service_timer);
16165 err_mac_addr:
16166 err_configure_lan_hmc:
16167 	(void)i40e_shutdown_lan_hmc(hw);
16168 err_init_lan_hmc:
16169 	kfree(pf->qp_pile);
16170 err_sw_init:
16171 err_adminq_setup:
16172 err_pf_reset:
16173 	iounmap(hw->hw_addr);
16174 err_ioremap:
16175 	i40e_free_pf(pf);
16176 err_pf_alloc:
16177 	pci_release_mem_regions(pdev);
16178 err_pci_reg:
16179 err_dma:
16180 	pci_disable_device(pdev);
16181 	return err;
16182 }
16183 
16184 /**
16185  * i40e_remove - Device removal routine
16186  * @pdev: PCI device information struct
16187  *
16188  * i40e_remove is called by the PCI subsystem to alert the driver
16189  * that is should release a PCI device.  This could be caused by a
16190  * Hot-Plug event, or because the driver is going to be removed from
16191  * memory.
16192  **/
16193 static void i40e_remove(struct pci_dev *pdev)
16194 {
16195 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16196 	struct i40e_hw *hw = &pf->hw;
16197 	struct i40e_vsi *vsi;
16198 	struct i40e_veb *veb;
16199 	int ret_code;
16200 	int i;
16201 
16202 	i40e_devlink_unregister(pf);
16203 
16204 	i40e_dbg_pf_exit(pf);
16205 
16206 	i40e_ptp_stop(pf);
16207 
16208 	/* Disable RSS in hw */
16209 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
16210 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
16211 
16212 	/* Grab __I40E_RESET_RECOVERY_PENDING and set __I40E_IN_REMOVE
16213 	 * flags, once they are set, i40e_rebuild should not be called as
16214 	 * i40e_prep_for_reset always returns early.
16215 	 */
16216 	while (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
16217 		usleep_range(1000, 2000);
16218 	set_bit(__I40E_IN_REMOVE, pf->state);
16219 
16220 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags)) {
16221 		set_bit(__I40E_VF_RESETS_DISABLED, pf->state);
16222 		i40e_free_vfs(pf);
16223 		clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
16224 	}
16225 	/* no more scheduling of any task */
16226 	set_bit(__I40E_SUSPENDED, pf->state);
16227 	set_bit(__I40E_DOWN, pf->state);
16228 	if (pf->service_timer.function)
16229 		timer_shutdown_sync(&pf->service_timer);
16230 	if (pf->service_task.func)
16231 		cancel_work_sync(&pf->service_task);
16232 
16233 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
16234 		struct i40e_vsi *vsi = pf->vsi[0];
16235 
16236 		/* We know that we have allocated only one vsi for this PF,
16237 		 * it was just for registering netdevice, so the interface
16238 		 * could be visible in the 'ifconfig' output
16239 		 */
16240 		unregister_netdev(vsi->netdev);
16241 		free_netdev(vsi->netdev);
16242 
16243 		goto unmap;
16244 	}
16245 
16246 	/* Client close must be called explicitly here because the timer
16247 	 * has been stopped.
16248 	 */
16249 	i40e_notify_client_of_netdev_close(pf, false);
16250 
16251 	i40e_fdir_teardown(pf);
16252 
16253 	/* If there is a switch structure or any orphans, remove them.
16254 	 * This will leave only the PF's VSI remaining.
16255 	 */
16256 	i40e_pf_for_each_veb(pf, i, veb)
16257 		if (veb->uplink_seid == pf->mac_seid ||
16258 		    veb->uplink_seid == 0)
16259 			i40e_switch_branch_release(veb);
16260 
16261 	/* Now we can shutdown the PF's VSIs, just before we kill
16262 	 * adminq and hmc.
16263 	 */
16264 	i40e_pf_for_each_vsi(pf, i, vsi) {
16265 		i40e_vsi_close(vsi);
16266 		i40e_vsi_release(vsi);
16267 		pf->vsi[i] = NULL;
16268 	}
16269 
16270 	i40e_cloud_filter_exit(pf);
16271 
16272 	/* remove attached clients */
16273 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
16274 		ret_code = i40e_lan_del_device(pf);
16275 		if (ret_code)
16276 			dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
16277 				 ret_code);
16278 	}
16279 
16280 	/* shutdown and destroy the HMC */
16281 	if (hw->hmc.hmc_obj) {
16282 		ret_code = i40e_shutdown_lan_hmc(hw);
16283 		if (ret_code)
16284 			dev_warn(&pdev->dev,
16285 				 "Failed to destroy the HMC resources: %d\n",
16286 				 ret_code);
16287 	}
16288 
16289 unmap:
16290 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16291 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16292 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
16293 		free_irq(pf->pdev->irq, pf);
16294 
16295 	/* shutdown the adminq */
16296 	i40e_shutdown_adminq(hw);
16297 
16298 	/* destroy the locks only once, here */
16299 	mutex_destroy(&hw->aq.arq_mutex);
16300 	mutex_destroy(&hw->aq.asq_mutex);
16301 
16302 	/* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
16303 	rtnl_lock();
16304 	i40e_clear_interrupt_scheme(pf);
16305 	i40e_pf_for_each_vsi(pf, i, vsi) {
16306 		if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
16307 			i40e_vsi_clear_rings(vsi);
16308 
16309 		i40e_vsi_clear(vsi);
16310 		pf->vsi[i] = NULL;
16311 	}
16312 	rtnl_unlock();
16313 
16314 	i40e_pf_for_each_veb(pf, i, veb) {
16315 		kfree(veb);
16316 		pf->veb[i] = NULL;
16317 	}
16318 
16319 	kfree(pf->qp_pile);
16320 	kfree(pf->vsi);
16321 
16322 	iounmap(hw->hw_addr);
16323 	i40e_free_pf(pf);
16324 	pci_release_mem_regions(pdev);
16325 
16326 	pci_disable_device(pdev);
16327 }
16328 
16329 /**
16330  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
16331  * using the mac_address_write admin q function
16332  * @pf: pointer to i40e_pf struct
16333  **/
16334 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
16335 {
16336 	struct i40e_vsi *main_vsi = i40e_pf_get_main_vsi(pf);
16337 	struct i40e_hw *hw = &pf->hw;
16338 	u8 mac_addr[6];
16339 	u16 flags = 0;
16340 	int ret;
16341 
16342 	/* Get current MAC address in case it's an LAA */
16343 	if (main_vsi && main_vsi->netdev) {
16344 		ether_addr_copy(mac_addr, main_vsi->netdev->dev_addr);
16345 	} else {
16346 		dev_err(&pf->pdev->dev,
16347 			"Failed to retrieve MAC address; using default\n");
16348 		ether_addr_copy(mac_addr, hw->mac.addr);
16349 	}
16350 
16351 	/* The FW expects the mac address write cmd to first be called with
16352 	 * one of these flags before calling it again with the multicast
16353 	 * enable flags.
16354 	 */
16355 	flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
16356 
16357 	if (hw->func_caps.flex10_enable && hw->partition_id != 1)
16358 		flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
16359 
16360 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16361 	if (ret) {
16362 		dev_err(&pf->pdev->dev,
16363 			"Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
16364 		return;
16365 	}
16366 
16367 	flags = I40E_AQC_MC_MAG_EN
16368 			| I40E_AQC_WOL_PRESERVE_ON_PFR
16369 			| I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
16370 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16371 	if (ret)
16372 		dev_err(&pf->pdev->dev,
16373 			"Failed to enable Multicast Magic Packet wake up\n");
16374 }
16375 
16376 /**
16377  * i40e_io_suspend - suspend all IO operations
16378  * @pf: pointer to i40e_pf struct
16379  *
16380  **/
16381 static int i40e_io_suspend(struct i40e_pf *pf)
16382 {
16383 	struct i40e_hw *hw = &pf->hw;
16384 
16385 	set_bit(__I40E_DOWN, pf->state);
16386 
16387 	/* Ensure service task will not be running */
16388 	timer_delete_sync(&pf->service_timer);
16389 	cancel_work_sync(&pf->service_task);
16390 
16391 	/* Client close must be called explicitly here because the timer
16392 	 * has been stopped.
16393 	 */
16394 	i40e_notify_client_of_netdev_close(pf, false);
16395 
16396 	if (test_bit(I40E_HW_CAP_WOL_MC_MAGIC_PKT_WAKE, pf->hw.caps) &&
16397 	    pf->wol_en)
16398 		i40e_enable_mc_magic_wake(pf);
16399 
16400 	/* Since we're going to destroy queues during the
16401 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16402 	 * whole section
16403 	 */
16404 	rtnl_lock();
16405 
16406 	i40e_prep_for_reset(pf);
16407 
16408 	wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16409 	wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16410 
16411 	/* Clear the interrupt scheme and release our IRQs so that the system
16412 	 * can safely hibernate even when there are a large number of CPUs.
16413 	 * Otherwise hibernation might fail when mapping all the vectors back
16414 	 * to CPU0.
16415 	 */
16416 	i40e_clear_interrupt_scheme(pf);
16417 
16418 	rtnl_unlock();
16419 
16420 	return 0;
16421 }
16422 
16423 /**
16424  * i40e_io_resume - resume IO operations
16425  * @pf: pointer to i40e_pf struct
16426  *
16427  **/
16428 static int i40e_io_resume(struct i40e_pf *pf)
16429 {
16430 	struct device *dev = &pf->pdev->dev;
16431 	int err;
16432 
16433 	/* We need to hold the RTNL lock prior to restoring interrupt schemes,
16434 	 * since we're going to be restoring queues
16435 	 */
16436 	rtnl_lock();
16437 
16438 	/* We cleared the interrupt scheme when we suspended, so we need to
16439 	 * restore it now to resume device functionality.
16440 	 */
16441 	err = i40e_restore_interrupt_scheme(pf);
16442 	if (err) {
16443 		dev_err(dev, "Cannot restore interrupt scheme: %d\n",
16444 			err);
16445 	}
16446 
16447 	clear_bit(__I40E_DOWN, pf->state);
16448 	i40e_reset_and_rebuild(pf, false, true);
16449 
16450 	rtnl_unlock();
16451 
16452 	/* Clear suspended state last after everything is recovered */
16453 	clear_bit(__I40E_SUSPENDED, pf->state);
16454 
16455 	/* Restart the service task */
16456 	mod_timer(&pf->service_timer,
16457 		  round_jiffies(jiffies + pf->service_timer_period));
16458 
16459 	return 0;
16460 }
16461 
16462 /**
16463  * i40e_pci_error_detected - warning that something funky happened in PCI land
16464  * @pdev: PCI device information struct
16465  * @error: the type of PCI error
16466  *
16467  * Called to warn that something happened and the error handling steps
16468  * are in progress.  Allows the driver to quiesce things, be ready for
16469  * remediation.
16470  **/
16471 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
16472 						pci_channel_state_t error)
16473 {
16474 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16475 
16476 	dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
16477 
16478 	if (!pf) {
16479 		dev_info(&pdev->dev,
16480 			 "Cannot recover - error happened during device probe\n");
16481 		return PCI_ERS_RESULT_DISCONNECT;
16482 	}
16483 
16484 	/* shutdown all operations */
16485 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16486 		i40e_io_suspend(pf);
16487 
16488 	/* Request a slot reset */
16489 	return PCI_ERS_RESULT_NEED_RESET;
16490 }
16491 
16492 /**
16493  * i40e_pci_error_slot_reset - a PCI slot reset just happened
16494  * @pdev: PCI device information struct
16495  *
16496  * Called to find if the driver can work with the device now that
16497  * the pci slot has been reset.  If a basic connection seems good
16498  * (registers are readable and have sane content) then return a
16499  * happy little PCI_ERS_RESULT_xxx.
16500  **/
16501 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
16502 {
16503 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16504 	pci_ers_result_t result;
16505 	u32 reg;
16506 
16507 	dev_dbg(&pdev->dev, "%s\n", __func__);
16508 	/* enable I/O and memory of the device  */
16509 	if (pci_enable_device(pdev)) {
16510 		dev_info(&pdev->dev,
16511 			 "Cannot re-enable PCI device after reset.\n");
16512 		result = PCI_ERS_RESULT_DISCONNECT;
16513 	} else {
16514 		pci_set_master(pdev);
16515 		pci_restore_state(pdev);
16516 		pci_save_state(pdev);
16517 		pci_wake_from_d3(pdev, false);
16518 
16519 		reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
16520 		if (reg == 0)
16521 			result = PCI_ERS_RESULT_RECOVERED;
16522 		else
16523 			result = PCI_ERS_RESULT_DISCONNECT;
16524 	}
16525 
16526 	return result;
16527 }
16528 
16529 /**
16530  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
16531  * @pdev: PCI device information struct
16532  */
16533 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
16534 {
16535 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16536 
16537 	i40e_prep_for_reset(pf);
16538 }
16539 
16540 /**
16541  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
16542  * @pdev: PCI device information struct
16543  */
16544 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
16545 {
16546 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16547 
16548 	if (test_bit(__I40E_IN_REMOVE, pf->state))
16549 		return;
16550 
16551 	i40e_reset_and_rebuild(pf, false, false);
16552 #ifdef CONFIG_PCI_IOV
16553 	i40e_restore_all_vfs_msi_state(pdev);
16554 #endif /* CONFIG_PCI_IOV */
16555 }
16556 
16557 /**
16558  * i40e_pci_error_resume - restart operations after PCI error recovery
16559  * @pdev: PCI device information struct
16560  *
16561  * Called to allow the driver to bring things back up after PCI error
16562  * and/or reset recovery has finished.
16563  **/
16564 static void i40e_pci_error_resume(struct pci_dev *pdev)
16565 {
16566 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16567 
16568 	dev_dbg(&pdev->dev, "%s\n", __func__);
16569 	if (test_bit(__I40E_SUSPENDED, pf->state))
16570 		return;
16571 
16572 	i40e_io_resume(pf);
16573 }
16574 
16575 /**
16576  * i40e_shutdown - PCI callback for shutting down
16577  * @pdev: PCI device information struct
16578  **/
16579 static void i40e_shutdown(struct pci_dev *pdev)
16580 {
16581 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16582 	struct i40e_hw *hw = &pf->hw;
16583 
16584 	set_bit(__I40E_SUSPENDED, pf->state);
16585 	set_bit(__I40E_DOWN, pf->state);
16586 
16587 	timer_delete_sync(&pf->service_timer);
16588 	cancel_work_sync(&pf->service_task);
16589 	i40e_cloud_filter_exit(pf);
16590 	i40e_fdir_teardown(pf);
16591 
16592 	/* Client close must be called explicitly here because the timer
16593 	 * has been stopped.
16594 	 */
16595 	i40e_notify_client_of_netdev_close(pf, false);
16596 
16597 	if (test_bit(I40E_HW_CAP_WOL_MC_MAGIC_PKT_WAKE, pf->hw.caps) &&
16598 	    pf->wol_en)
16599 		i40e_enable_mc_magic_wake(pf);
16600 
16601 	i40e_prep_for_reset(pf);
16602 
16603 	wr32(hw, I40E_PFPM_APM,
16604 	     (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16605 	wr32(hw, I40E_PFPM_WUFC,
16606 	     (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16607 
16608 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16609 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16610 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
16611 		free_irq(pf->pdev->irq, pf);
16612 
16613 	/* Since we're going to destroy queues during the
16614 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16615 	 * whole section
16616 	 */
16617 	rtnl_lock();
16618 	i40e_clear_interrupt_scheme(pf);
16619 	rtnl_unlock();
16620 
16621 	if (system_state == SYSTEM_POWER_OFF) {
16622 		pci_wake_from_d3(pdev, pf->wol_en);
16623 		pci_set_power_state(pdev, PCI_D3hot);
16624 	}
16625 }
16626 
16627 /**
16628  * i40e_suspend - PM callback for moving to D3
16629  * @dev: generic device information structure
16630  **/
16631 static int i40e_suspend(struct device *dev)
16632 {
16633 	struct i40e_pf *pf = dev_get_drvdata(dev);
16634 
16635 	/* If we're already suspended, then there is nothing to do */
16636 	if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
16637 		return 0;
16638 	return i40e_io_suspend(pf);
16639 }
16640 
16641 /**
16642  * i40e_resume - PM callback for waking up from D3
16643  * @dev: generic device information structure
16644  **/
16645 static int i40e_resume(struct device *dev)
16646 {
16647 	struct i40e_pf *pf = dev_get_drvdata(dev);
16648 
16649 	/* If we're not suspended, then there is nothing to do */
16650 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16651 		return 0;
16652 	return i40e_io_resume(pf);
16653 }
16654 
16655 static const struct pci_error_handlers i40e_err_handler = {
16656 	.error_detected = i40e_pci_error_detected,
16657 	.slot_reset = i40e_pci_error_slot_reset,
16658 	.reset_prepare = i40e_pci_error_reset_prepare,
16659 	.reset_done = i40e_pci_error_reset_done,
16660 	.resume = i40e_pci_error_resume,
16661 };
16662 
16663 static DEFINE_SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
16664 
16665 static struct pci_driver i40e_driver = {
16666 	.name     = i40e_driver_name,
16667 	.id_table = i40e_pci_tbl,
16668 	.probe    = i40e_probe,
16669 	.remove   = i40e_remove,
16670 	.driver.pm = pm_sleep_ptr(&i40e_pm_ops),
16671 	.shutdown = i40e_shutdown,
16672 	.err_handler = &i40e_err_handler,
16673 	.sriov_configure = i40e_pci_sriov_configure,
16674 };
16675 
16676 /**
16677  * i40e_init_module - Driver registration routine
16678  *
16679  * i40e_init_module is the first routine called when the driver is
16680  * loaded. All it does is register with the PCI subsystem.
16681  **/
16682 static int __init i40e_init_module(void)
16683 {
16684 	int err;
16685 
16686 	pr_info("%s: %s\n", i40e_driver_name, i40e_driver_string);
16687 	pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
16688 
16689 	/* There is no need to throttle the number of active tasks because
16690 	 * each device limits its own task using a state bit for scheduling
16691 	 * the service task, and the device tasks do not interfere with each
16692 	 * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
16693 	 * since we need to be able to guarantee forward progress even under
16694 	 * memory pressure.
16695 	 */
16696 	i40e_wq = alloc_workqueue("%s", 0, 0, i40e_driver_name);
16697 	if (!i40e_wq) {
16698 		pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
16699 		return -ENOMEM;
16700 	}
16701 
16702 	i40e_dbg_init();
16703 	err = pci_register_driver(&i40e_driver);
16704 	if (err) {
16705 		destroy_workqueue(i40e_wq);
16706 		i40e_dbg_exit();
16707 		return err;
16708 	}
16709 
16710 	return 0;
16711 }
16712 module_init(i40e_init_module);
16713 
16714 /**
16715  * i40e_exit_module - Driver exit cleanup routine
16716  *
16717  * i40e_exit_module is called just before the driver is removed
16718  * from memory.
16719  **/
16720 static void __exit i40e_exit_module(void)
16721 {
16722 	pci_unregister_driver(&i40e_driver);
16723 	destroy_workqueue(i40e_wq);
16724 	ida_destroy(&i40e_client_ida);
16725 	i40e_dbg_exit();
16726 }
16727 module_exit(i40e_exit_module);
16728