xref: /linux/drivers/net/ethernet/intel/i40e/i40e_main.c (revision d53b8e36925256097a08d7cb749198d85cbf9b2b)
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/if_bridge.h>
7 #include <linux/if_macvlan.h>
8 #include <linux/module.h>
9 #include <net/pkt_cls.h>
10 #include <net/xdp_sock_drv.h>
11 
12 /* Local includes */
13 #include "i40e.h"
14 #include "i40e_devids.h"
15 #include "i40e_diag.h"
16 #include "i40e_lan_hmc.h"
17 #include "i40e_virtchnl_pf.h"
18 #include "i40e_xsk.h"
19 
20 /* All i40e tracepoints are defined by the include below, which
21  * must be included exactly once across the whole kernel with
22  * CREATE_TRACE_POINTS defined
23  */
24 #define CREATE_TRACE_POINTS
25 #include "i40e_trace.h"
26 
27 const char i40e_driver_name[] = "i40e";
28 static const char i40e_driver_string[] =
29 			"Intel(R) Ethernet Connection XL710 Network Driver";
30 
31 static const char i40e_copyright[] = "Copyright (c) 2013 - 2019 Intel Corporation.";
32 
33 /* a bit of forward declarations */
34 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi);
35 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired);
36 static int i40e_add_vsi(struct i40e_vsi *vsi);
37 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi);
38 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired);
39 static int i40e_setup_misc_vector(struct i40e_pf *pf);
40 static void i40e_determine_queue_usage(struct i40e_pf *pf);
41 static int i40e_setup_pf_filter_control(struct i40e_pf *pf);
42 static void i40e_prep_for_reset(struct i40e_pf *pf);
43 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
44 				   bool lock_acquired);
45 static int i40e_reset(struct i40e_pf *pf);
46 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired);
47 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf);
48 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf);
49 static bool i40e_check_recovery_mode(struct i40e_pf *pf);
50 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw);
51 static void i40e_fdir_sb_setup(struct i40e_pf *pf);
52 static int i40e_veb_get_bw_info(struct i40e_veb *veb);
53 static int i40e_get_capabilities(struct i40e_pf *pf,
54 				 enum i40e_admin_queue_opc list_type);
55 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf);
56 
57 /* i40e_pci_tbl - PCI Device ID Table
58  *
59  * Last entry must be all 0s
60  *
61  * { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
62  *   Class, Class Mask, private data (not used) }
63  */
64 static const struct pci_device_id i40e_pci_tbl[] = {
65 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_XL710), 0},
66 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QEMU), 0},
67 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_B), 0},
68 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_C), 0},
69 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_A), 0},
70 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_B), 0},
71 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_C), 0},
72 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_BC), 0},
73 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T), 0},
74 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T4), 0},
75 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_BC), 0},
76 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_SFP), 0},
77 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_B), 0},
78 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_X722), 0},
79 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_X722), 0},
80 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722), 0},
81 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_X722), 0},
82 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_X722), 0},
83 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_I_X722), 0},
84 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722_A), 0},
85 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2), 0},
86 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A), 0},
87 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_X710_N3000), 0},
88 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_XXV710_N3000), 0},
89 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B), 0},
90 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28), 0},
91 	/* required last entry */
92 	{0, }
93 };
94 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
95 
96 #define I40E_MAX_VF_COUNT 128
97 static int debug = -1;
98 module_param(debug, uint, 0);
99 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
100 
101 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
102 MODULE_IMPORT_NS(LIBIE);
103 MODULE_LICENSE("GPL v2");
104 
105 static struct workqueue_struct *i40e_wq;
106 
107 static void netdev_hw_addr_refcnt(struct i40e_mac_filter *f,
108 				  struct net_device *netdev, int delta)
109 {
110 	struct netdev_hw_addr_list *ha_list;
111 	struct netdev_hw_addr *ha;
112 
113 	if (!f || !netdev)
114 		return;
115 
116 	if (is_unicast_ether_addr(f->macaddr) || is_link_local_ether_addr(f->macaddr))
117 		ha_list = &netdev->uc;
118 	else
119 		ha_list = &netdev->mc;
120 
121 	netdev_hw_addr_list_for_each(ha, ha_list) {
122 		if (ether_addr_equal(ha->addr, f->macaddr)) {
123 			ha->refcount += delta;
124 			if (ha->refcount <= 0)
125 				ha->refcount = 1;
126 			break;
127 		}
128 	}
129 }
130 
131 /**
132  * i40e_hw_to_dev - get device pointer from the hardware structure
133  * @hw: pointer to the device HW structure
134  **/
135 struct device *i40e_hw_to_dev(struct i40e_hw *hw)
136 {
137 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
138 
139 	return &pf->pdev->dev;
140 }
141 
142 /**
143  * i40e_allocate_dma_mem - OS specific memory alloc for shared code
144  * @hw:   pointer to the HW structure
145  * @mem:  ptr to mem struct to fill out
146  * @size: size of memory requested
147  * @alignment: what to align the allocation to
148  **/
149 int i40e_allocate_dma_mem(struct i40e_hw *hw, struct i40e_dma_mem *mem,
150 			  u64 size, u32 alignment)
151 {
152 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
153 
154 	mem->size = ALIGN(size, alignment);
155 	mem->va = dma_alloc_coherent(&pf->pdev->dev, mem->size, &mem->pa,
156 				     GFP_KERNEL);
157 	if (!mem->va)
158 		return -ENOMEM;
159 
160 	return 0;
161 }
162 
163 /**
164  * i40e_free_dma_mem - OS specific memory free for shared code
165  * @hw:   pointer to the HW structure
166  * @mem:  ptr to mem struct to free
167  **/
168 int i40e_free_dma_mem(struct i40e_hw *hw, struct i40e_dma_mem *mem)
169 {
170 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
171 
172 	dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
173 	mem->va = NULL;
174 	mem->pa = 0;
175 	mem->size = 0;
176 
177 	return 0;
178 }
179 
180 /**
181  * i40e_allocate_virt_mem - OS specific memory alloc for shared code
182  * @hw:   pointer to the HW structure
183  * @mem:  ptr to mem struct to fill out
184  * @size: size of memory requested
185  **/
186 int i40e_allocate_virt_mem(struct i40e_hw *hw, struct i40e_virt_mem *mem,
187 			   u32 size)
188 {
189 	mem->size = size;
190 	mem->va = kzalloc(size, GFP_KERNEL);
191 
192 	if (!mem->va)
193 		return -ENOMEM;
194 
195 	return 0;
196 }
197 
198 /**
199  * i40e_free_virt_mem - OS specific memory free for shared code
200  * @hw:   pointer to the HW structure
201  * @mem:  ptr to mem struct to free
202  **/
203 int i40e_free_virt_mem(struct i40e_hw *hw, struct i40e_virt_mem *mem)
204 {
205 	/* it's ok to kfree a NULL pointer */
206 	kfree(mem->va);
207 	mem->va = NULL;
208 	mem->size = 0;
209 
210 	return 0;
211 }
212 
213 /**
214  * i40e_get_lump - find a lump of free generic resource
215  * @pf: board private structure
216  * @pile: the pile of resource to search
217  * @needed: the number of items needed
218  * @id: an owner id to stick on the items assigned
219  *
220  * Returns the base item index of the lump, or negative for error
221  **/
222 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
223 			 u16 needed, u16 id)
224 {
225 	int ret = -ENOMEM;
226 	int i, j;
227 
228 	if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
229 		dev_info(&pf->pdev->dev,
230 			 "param err: pile=%s needed=%d id=0x%04x\n",
231 			 pile ? "<valid>" : "<null>", needed, id);
232 		return -EINVAL;
233 	}
234 
235 	/* Allocate last queue in the pile for FDIR VSI queue
236 	 * so it doesn't fragment the qp_pile
237 	 */
238 	if (pile == pf->qp_pile && pf->vsi[id]->type == I40E_VSI_FDIR) {
239 		if (pile->list[pile->num_entries - 1] & I40E_PILE_VALID_BIT) {
240 			dev_err(&pf->pdev->dev,
241 				"Cannot allocate queue %d for I40E_VSI_FDIR\n",
242 				pile->num_entries - 1);
243 			return -ENOMEM;
244 		}
245 		pile->list[pile->num_entries - 1] = id | I40E_PILE_VALID_BIT;
246 		return pile->num_entries - 1;
247 	}
248 
249 	i = 0;
250 	while (i < pile->num_entries) {
251 		/* skip already allocated entries */
252 		if (pile->list[i] & I40E_PILE_VALID_BIT) {
253 			i++;
254 			continue;
255 		}
256 
257 		/* do we have enough in this lump? */
258 		for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
259 			if (pile->list[i+j] & I40E_PILE_VALID_BIT)
260 				break;
261 		}
262 
263 		if (j == needed) {
264 			/* there was enough, so assign it to the requestor */
265 			for (j = 0; j < needed; j++)
266 				pile->list[i+j] = id | I40E_PILE_VALID_BIT;
267 			ret = i;
268 			break;
269 		}
270 
271 		/* not enough, so skip over it and continue looking */
272 		i += j;
273 	}
274 
275 	return ret;
276 }
277 
278 /**
279  * i40e_put_lump - return a lump of generic resource
280  * @pile: the pile of resource to search
281  * @index: the base item index
282  * @id: the owner id of the items assigned
283  *
284  * Returns the count of items in the lump
285  **/
286 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
287 {
288 	int valid_id = (id | I40E_PILE_VALID_BIT);
289 	int count = 0;
290 	u16 i;
291 
292 	if (!pile || index >= pile->num_entries)
293 		return -EINVAL;
294 
295 	for (i = index;
296 	     i < pile->num_entries && pile->list[i] == valid_id;
297 	     i++) {
298 		pile->list[i] = 0;
299 		count++;
300 	}
301 
302 
303 	return count;
304 }
305 
306 /**
307  * i40e_find_vsi_from_id - searches for the vsi with the given id
308  * @pf: the pf structure to search for the vsi
309  * @id: id of the vsi it is searching for
310  **/
311 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
312 {
313 	struct i40e_vsi *vsi;
314 	int i;
315 
316 	i40e_pf_for_each_vsi(pf, i, vsi)
317 		if (vsi->id == id)
318 			return vsi;
319 
320 	return NULL;
321 }
322 
323 /**
324  * i40e_service_event_schedule - Schedule the service task to wake up
325  * @pf: board private structure
326  *
327  * If not already scheduled, this puts the task into the work queue
328  **/
329 void i40e_service_event_schedule(struct i40e_pf *pf)
330 {
331 	if ((!test_bit(__I40E_DOWN, pf->state) &&
332 	     !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) ||
333 	      test_bit(__I40E_RECOVERY_MODE, pf->state))
334 		queue_work(i40e_wq, &pf->service_task);
335 }
336 
337 /**
338  * i40e_tx_timeout - Respond to a Tx Hang
339  * @netdev: network interface device structure
340  * @txqueue: queue number timing out
341  *
342  * If any port has noticed a Tx timeout, it is likely that the whole
343  * device is munged, not just the one netdev port, so go for the full
344  * reset.
345  **/
346 static void i40e_tx_timeout(struct net_device *netdev, unsigned int txqueue)
347 {
348 	struct i40e_netdev_priv *np = netdev_priv(netdev);
349 	struct i40e_vsi *vsi = np->vsi;
350 	struct i40e_pf *pf = vsi->back;
351 	struct i40e_ring *tx_ring = NULL;
352 	unsigned int i;
353 	u32 head, val;
354 
355 	pf->tx_timeout_count++;
356 
357 	/* with txqueue index, find the tx_ring struct */
358 	for (i = 0; i < vsi->num_queue_pairs; i++) {
359 		if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
360 			if (txqueue ==
361 			    vsi->tx_rings[i]->queue_index) {
362 				tx_ring = vsi->tx_rings[i];
363 				break;
364 			}
365 		}
366 	}
367 
368 	if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
369 		pf->tx_timeout_recovery_level = 1;  /* reset after some time */
370 	else if (time_before(jiffies,
371 		      (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
372 		return;   /* don't do any new action before the next timeout */
373 
374 	/* don't kick off another recovery if one is already pending */
375 	if (test_and_set_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state))
376 		return;
377 
378 	if (tx_ring) {
379 		head = i40e_get_head(tx_ring);
380 		/* Read interrupt register */
381 		if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
382 			val = rd32(&pf->hw,
383 			     I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
384 						tx_ring->vsi->base_vector - 1));
385 		else
386 			val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
387 
388 		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",
389 			    vsi->seid, txqueue, tx_ring->next_to_clean,
390 			    head, tx_ring->next_to_use,
391 			    readl(tx_ring->tail), val);
392 	}
393 
394 	pf->tx_timeout_last_recovery = jiffies;
395 	netdev_info(netdev, "tx_timeout recovery level %d, txqueue %d\n",
396 		    pf->tx_timeout_recovery_level, txqueue);
397 
398 	switch (pf->tx_timeout_recovery_level) {
399 	case 1:
400 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
401 		break;
402 	case 2:
403 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
404 		break;
405 	case 3:
406 		set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
407 		break;
408 	default:
409 		netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in non-recoverable state.\n");
410 		set_bit(__I40E_DOWN_REQUESTED, pf->state);
411 		set_bit(__I40E_VSI_DOWN_REQUESTED, vsi->state);
412 		break;
413 	}
414 
415 	i40e_service_event_schedule(pf);
416 	pf->tx_timeout_recovery_level++;
417 }
418 
419 /**
420  * i40e_get_vsi_stats_struct - Get System Network Statistics
421  * @vsi: the VSI we care about
422  *
423  * Returns the address of the device statistics structure.
424  * The statistics are actually updated from the service task.
425  **/
426 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
427 {
428 	return &vsi->net_stats;
429 }
430 
431 /**
432  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
433  * @ring: Tx ring to get statistics from
434  * @stats: statistics entry to be updated
435  **/
436 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
437 					    struct rtnl_link_stats64 *stats)
438 {
439 	u64 bytes, packets;
440 	unsigned int start;
441 
442 	do {
443 		start = u64_stats_fetch_begin(&ring->syncp);
444 		packets = ring->stats.packets;
445 		bytes   = ring->stats.bytes;
446 	} while (u64_stats_fetch_retry(&ring->syncp, start));
447 
448 	stats->tx_packets += packets;
449 	stats->tx_bytes   += bytes;
450 }
451 
452 /**
453  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
454  * @netdev: network interface device structure
455  * @stats: data structure to store statistics
456  *
457  * Returns the address of the device statistics structure.
458  * The statistics are actually updated from the service task.
459  **/
460 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
461 				  struct rtnl_link_stats64 *stats)
462 {
463 	struct i40e_netdev_priv *np = netdev_priv(netdev);
464 	struct i40e_vsi *vsi = np->vsi;
465 	struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
466 	struct i40e_ring *ring;
467 	int i;
468 
469 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
470 		return;
471 
472 	if (!vsi->tx_rings)
473 		return;
474 
475 	rcu_read_lock();
476 	for (i = 0; i < vsi->num_queue_pairs; i++) {
477 		u64 bytes, packets;
478 		unsigned int start;
479 
480 		ring = READ_ONCE(vsi->tx_rings[i]);
481 		if (!ring)
482 			continue;
483 		i40e_get_netdev_stats_struct_tx(ring, stats);
484 
485 		if (i40e_enabled_xdp_vsi(vsi)) {
486 			ring = READ_ONCE(vsi->xdp_rings[i]);
487 			if (!ring)
488 				continue;
489 			i40e_get_netdev_stats_struct_tx(ring, stats);
490 		}
491 
492 		ring = READ_ONCE(vsi->rx_rings[i]);
493 		if (!ring)
494 			continue;
495 		do {
496 			start   = u64_stats_fetch_begin(&ring->syncp);
497 			packets = ring->stats.packets;
498 			bytes   = ring->stats.bytes;
499 		} while (u64_stats_fetch_retry(&ring->syncp, start));
500 
501 		stats->rx_packets += packets;
502 		stats->rx_bytes   += bytes;
503 
504 	}
505 	rcu_read_unlock();
506 
507 	/* following stats updated by i40e_watchdog_subtask() */
508 	stats->multicast	= vsi_stats->multicast;
509 	stats->tx_errors	= vsi_stats->tx_errors;
510 	stats->tx_dropped	= vsi_stats->tx_dropped;
511 	stats->rx_errors	= vsi_stats->rx_errors;
512 	stats->rx_dropped	= vsi_stats->rx_dropped;
513 	stats->rx_missed_errors	= vsi_stats->rx_missed_errors;
514 	stats->rx_crc_errors	= vsi_stats->rx_crc_errors;
515 	stats->rx_length_errors	= vsi_stats->rx_length_errors;
516 }
517 
518 /**
519  * i40e_vsi_reset_stats - Resets all stats of the given vsi
520  * @vsi: the VSI to have its stats reset
521  **/
522 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
523 {
524 	struct rtnl_link_stats64 *ns;
525 	int i;
526 
527 	if (!vsi)
528 		return;
529 
530 	ns = i40e_get_vsi_stats_struct(vsi);
531 	memset(ns, 0, sizeof(*ns));
532 	memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
533 	memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
534 	memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
535 	if (vsi->rx_rings && vsi->rx_rings[0]) {
536 		for (i = 0; i < vsi->num_queue_pairs; i++) {
537 			memset(&vsi->rx_rings[i]->stats, 0,
538 			       sizeof(vsi->rx_rings[i]->stats));
539 			memset(&vsi->rx_rings[i]->rx_stats, 0,
540 			       sizeof(vsi->rx_rings[i]->rx_stats));
541 			memset(&vsi->tx_rings[i]->stats, 0,
542 			       sizeof(vsi->tx_rings[i]->stats));
543 			memset(&vsi->tx_rings[i]->tx_stats, 0,
544 			       sizeof(vsi->tx_rings[i]->tx_stats));
545 		}
546 	}
547 	vsi->stat_offsets_loaded = false;
548 }
549 
550 /**
551  * i40e_pf_reset_stats - Reset all of the stats for the given PF
552  * @pf: the PF to be reset
553  **/
554 void i40e_pf_reset_stats(struct i40e_pf *pf)
555 {
556 	struct i40e_veb *veb;
557 	int i;
558 
559 	memset(&pf->stats, 0, sizeof(pf->stats));
560 	memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
561 	pf->stat_offsets_loaded = false;
562 
563 	i40e_pf_for_each_veb(pf, i, veb) {
564 		memset(&veb->stats, 0, sizeof(veb->stats));
565 		memset(&veb->stats_offsets, 0, sizeof(veb->stats_offsets));
566 		memset(&veb->tc_stats, 0, sizeof(veb->tc_stats));
567 		memset(&veb->tc_stats_offsets, 0, sizeof(veb->tc_stats_offsets));
568 		veb->stat_offsets_loaded = false;
569 	}
570 	pf->hw_csum_rx_error = 0;
571 }
572 
573 /**
574  * i40e_compute_pci_to_hw_id - compute index form PCI function.
575  * @vsi: ptr to the VSI to read from.
576  * @hw: ptr to the hardware info.
577  **/
578 static u32 i40e_compute_pci_to_hw_id(struct i40e_vsi *vsi, struct i40e_hw *hw)
579 {
580 	int pf_count = i40e_get_pf_count(hw);
581 
582 	if (vsi->type == I40E_VSI_SRIOV)
583 		return (hw->port * BIT(7)) / pf_count + vsi->vf_id;
584 
585 	return hw->port + BIT(7);
586 }
587 
588 /**
589  * i40e_stat_update64 - read and update a 64 bit stat from the chip.
590  * @hw: ptr to the hardware info.
591  * @hireg: the high 32 bit reg to read.
592  * @loreg: the low 32 bit reg to read.
593  * @offset_loaded: has the initial offset been loaded yet.
594  * @offset: ptr to current offset value.
595  * @stat: ptr to the stat.
596  *
597  * Since the device stats are not reset at PFReset, they will not
598  * be zeroed when the driver starts.  We'll save the first values read
599  * and use them as offsets to be subtracted from the raw values in order
600  * to report stats that count from zero.
601  **/
602 static void i40e_stat_update64(struct i40e_hw *hw, u32 hireg, u32 loreg,
603 			       bool offset_loaded, u64 *offset, u64 *stat)
604 {
605 	u64 new_data;
606 
607 	new_data = rd64(hw, loreg);
608 
609 	if (!offset_loaded || new_data < *offset)
610 		*offset = new_data;
611 	*stat = new_data - *offset;
612 }
613 
614 /**
615  * i40e_stat_update48 - read and update a 48 bit stat from the chip
616  * @hw: ptr to the hardware info
617  * @hireg: the high 32 bit reg to read
618  * @loreg: the low 32 bit reg to read
619  * @offset_loaded: has the initial offset been loaded yet
620  * @offset: ptr to current offset value
621  * @stat: ptr to the stat
622  *
623  * Since the device stats are not reset at PFReset, they likely will not
624  * be zeroed when the driver starts.  We'll save the first values read
625  * and use them as offsets to be subtracted from the raw values in order
626  * to report stats that count from zero.  In the process, we also manage
627  * the potential roll-over.
628  **/
629 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
630 			       bool offset_loaded, u64 *offset, u64 *stat)
631 {
632 	u64 new_data;
633 
634 	if (hw->device_id == I40E_DEV_ID_QEMU) {
635 		new_data = rd32(hw, loreg);
636 		new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
637 	} else {
638 		new_data = rd64(hw, loreg);
639 	}
640 	if (!offset_loaded)
641 		*offset = new_data;
642 	if (likely(new_data >= *offset))
643 		*stat = new_data - *offset;
644 	else
645 		*stat = (new_data + BIT_ULL(48)) - *offset;
646 	*stat &= 0xFFFFFFFFFFFFULL;
647 }
648 
649 /**
650  * i40e_stat_update32 - read and update a 32 bit stat from the chip
651  * @hw: ptr to the hardware info
652  * @reg: the hw reg to read
653  * @offset_loaded: has the initial offset been loaded yet
654  * @offset: ptr to current offset value
655  * @stat: ptr to the stat
656  **/
657 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
658 			       bool offset_loaded, u64 *offset, u64 *stat)
659 {
660 	u32 new_data;
661 
662 	new_data = rd32(hw, reg);
663 	if (!offset_loaded)
664 		*offset = new_data;
665 	if (likely(new_data >= *offset))
666 		*stat = (u32)(new_data - *offset);
667 	else
668 		*stat = (u32)((new_data + BIT_ULL(32)) - *offset);
669 }
670 
671 /**
672  * i40e_stat_update_and_clear32 - read and clear hw reg, update a 32 bit stat
673  * @hw: ptr to the hardware info
674  * @reg: the hw reg to read and clear
675  * @stat: ptr to the stat
676  **/
677 static void i40e_stat_update_and_clear32(struct i40e_hw *hw, u32 reg, u64 *stat)
678 {
679 	u32 new_data = rd32(hw, reg);
680 
681 	wr32(hw, reg, 1); /* must write a nonzero value to clear register */
682 	*stat += new_data;
683 }
684 
685 /**
686  * i40e_stats_update_rx_discards - update rx_discards.
687  * @vsi: ptr to the VSI to be updated.
688  * @hw: ptr to the hardware info.
689  * @stat_idx: VSI's stat_counter_idx.
690  * @offset_loaded: ptr to the VSI's stat_offsets_loaded.
691  * @stat_offset: ptr to stat_offset to store first read of specific register.
692  * @stat: ptr to VSI's stat to be updated.
693  **/
694 static void
695 i40e_stats_update_rx_discards(struct i40e_vsi *vsi, struct i40e_hw *hw,
696 			      int stat_idx, bool offset_loaded,
697 			      struct i40e_eth_stats *stat_offset,
698 			      struct i40e_eth_stats *stat)
699 {
700 	i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx), offset_loaded,
701 			   &stat_offset->rx_discards, &stat->rx_discards);
702 	i40e_stat_update64(hw,
703 			   I40E_GL_RXERR1H(i40e_compute_pci_to_hw_id(vsi, hw)),
704 			   I40E_GL_RXERR1L(i40e_compute_pci_to_hw_id(vsi, hw)),
705 			   offset_loaded, &stat_offset->rx_discards_other,
706 			   &stat->rx_discards_other);
707 }
708 
709 /**
710  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
711  * @vsi: the VSI to be updated
712  **/
713 void i40e_update_eth_stats(struct i40e_vsi *vsi)
714 {
715 	int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
716 	struct i40e_pf *pf = vsi->back;
717 	struct i40e_hw *hw = &pf->hw;
718 	struct i40e_eth_stats *oes;
719 	struct i40e_eth_stats *es;     /* device's eth stats */
720 
721 	es = &vsi->eth_stats;
722 	oes = &vsi->eth_stats_offsets;
723 
724 	/* Gather up the stats that the hw collects */
725 	i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
726 			   vsi->stat_offsets_loaded,
727 			   &oes->tx_errors, &es->tx_errors);
728 	i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
729 			   vsi->stat_offsets_loaded,
730 			   &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
731 
732 	i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
733 			   I40E_GLV_GORCL(stat_idx),
734 			   vsi->stat_offsets_loaded,
735 			   &oes->rx_bytes, &es->rx_bytes);
736 	i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
737 			   I40E_GLV_UPRCL(stat_idx),
738 			   vsi->stat_offsets_loaded,
739 			   &oes->rx_unicast, &es->rx_unicast);
740 	i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
741 			   I40E_GLV_MPRCL(stat_idx),
742 			   vsi->stat_offsets_loaded,
743 			   &oes->rx_multicast, &es->rx_multicast);
744 	i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
745 			   I40E_GLV_BPRCL(stat_idx),
746 			   vsi->stat_offsets_loaded,
747 			   &oes->rx_broadcast, &es->rx_broadcast);
748 
749 	i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
750 			   I40E_GLV_GOTCL(stat_idx),
751 			   vsi->stat_offsets_loaded,
752 			   &oes->tx_bytes, &es->tx_bytes);
753 	i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
754 			   I40E_GLV_UPTCL(stat_idx),
755 			   vsi->stat_offsets_loaded,
756 			   &oes->tx_unicast, &es->tx_unicast);
757 	i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
758 			   I40E_GLV_MPTCL(stat_idx),
759 			   vsi->stat_offsets_loaded,
760 			   &oes->tx_multicast, &es->tx_multicast);
761 	i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
762 			   I40E_GLV_BPTCL(stat_idx),
763 			   vsi->stat_offsets_loaded,
764 			   &oes->tx_broadcast, &es->tx_broadcast);
765 
766 	i40e_stats_update_rx_discards(vsi, hw, stat_idx,
767 				      vsi->stat_offsets_loaded, oes, es);
768 
769 	vsi->stat_offsets_loaded = true;
770 }
771 
772 /**
773  * i40e_update_veb_stats - Update Switch component statistics
774  * @veb: the VEB being updated
775  **/
776 void i40e_update_veb_stats(struct i40e_veb *veb)
777 {
778 	struct i40e_pf *pf = veb->pf;
779 	struct i40e_hw *hw = &pf->hw;
780 	struct i40e_eth_stats *oes;
781 	struct i40e_eth_stats *es;     /* device's eth stats */
782 	struct i40e_veb_tc_stats *veb_oes;
783 	struct i40e_veb_tc_stats *veb_es;
784 	int i, idx = 0;
785 
786 	idx = veb->stats_idx;
787 	es = &veb->stats;
788 	oes = &veb->stats_offsets;
789 	veb_es = &veb->tc_stats;
790 	veb_oes = &veb->tc_stats_offsets;
791 
792 	/* Gather up the stats that the hw collects */
793 	i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
794 			   veb->stat_offsets_loaded,
795 			   &oes->tx_discards, &es->tx_discards);
796 	if (hw->revision_id > 0)
797 		i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
798 				   veb->stat_offsets_loaded,
799 				   &oes->rx_unknown_protocol,
800 				   &es->rx_unknown_protocol);
801 	i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
802 			   veb->stat_offsets_loaded,
803 			   &oes->rx_bytes, &es->rx_bytes);
804 	i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
805 			   veb->stat_offsets_loaded,
806 			   &oes->rx_unicast, &es->rx_unicast);
807 	i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
808 			   veb->stat_offsets_loaded,
809 			   &oes->rx_multicast, &es->rx_multicast);
810 	i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
811 			   veb->stat_offsets_loaded,
812 			   &oes->rx_broadcast, &es->rx_broadcast);
813 
814 	i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
815 			   veb->stat_offsets_loaded,
816 			   &oes->tx_bytes, &es->tx_bytes);
817 	i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
818 			   veb->stat_offsets_loaded,
819 			   &oes->tx_unicast, &es->tx_unicast);
820 	i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
821 			   veb->stat_offsets_loaded,
822 			   &oes->tx_multicast, &es->tx_multicast);
823 	i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
824 			   veb->stat_offsets_loaded,
825 			   &oes->tx_broadcast, &es->tx_broadcast);
826 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
827 		i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
828 				   I40E_GLVEBTC_RPCL(i, idx),
829 				   veb->stat_offsets_loaded,
830 				   &veb_oes->tc_rx_packets[i],
831 				   &veb_es->tc_rx_packets[i]);
832 		i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
833 				   I40E_GLVEBTC_RBCL(i, idx),
834 				   veb->stat_offsets_loaded,
835 				   &veb_oes->tc_rx_bytes[i],
836 				   &veb_es->tc_rx_bytes[i]);
837 		i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
838 				   I40E_GLVEBTC_TPCL(i, idx),
839 				   veb->stat_offsets_loaded,
840 				   &veb_oes->tc_tx_packets[i],
841 				   &veb_es->tc_tx_packets[i]);
842 		i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
843 				   I40E_GLVEBTC_TBCL(i, idx),
844 				   veb->stat_offsets_loaded,
845 				   &veb_oes->tc_tx_bytes[i],
846 				   &veb_es->tc_tx_bytes[i]);
847 	}
848 	veb->stat_offsets_loaded = true;
849 }
850 
851 /**
852  * i40e_update_vsi_stats - Update the vsi statistics counters.
853  * @vsi: the VSI to be updated
854  *
855  * There are a few instances where we store the same stat in a
856  * couple of different structs.  This is partly because we have
857  * the netdev stats that need to be filled out, which is slightly
858  * different from the "eth_stats" defined by the chip and used in
859  * VF communications.  We sort it out here.
860  **/
861 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
862 {
863 	u64 rx_page, rx_buf, rx_reuse, rx_alloc, rx_waive, rx_busy;
864 	struct i40e_pf *pf = vsi->back;
865 	struct rtnl_link_stats64 *ons;
866 	struct rtnl_link_stats64 *ns;   /* netdev stats */
867 	struct i40e_eth_stats *oes;
868 	struct i40e_eth_stats *es;     /* device's eth stats */
869 	u64 tx_restart, tx_busy;
870 	struct i40e_ring *p;
871 	u64 bytes, packets;
872 	unsigned int start;
873 	u64 tx_linearize;
874 	u64 tx_force_wb;
875 	u64 tx_stopped;
876 	u64 rx_p, rx_b;
877 	u64 tx_p, tx_b;
878 	u16 q;
879 
880 	if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
881 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
882 		return;
883 
884 	ns = i40e_get_vsi_stats_struct(vsi);
885 	ons = &vsi->net_stats_offsets;
886 	es = &vsi->eth_stats;
887 	oes = &vsi->eth_stats_offsets;
888 
889 	/* Gather up the netdev and vsi stats that the driver collects
890 	 * on the fly during packet processing
891 	 */
892 	rx_b = rx_p = 0;
893 	tx_b = tx_p = 0;
894 	tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
895 	tx_stopped = 0;
896 	rx_page = 0;
897 	rx_buf = 0;
898 	rx_reuse = 0;
899 	rx_alloc = 0;
900 	rx_waive = 0;
901 	rx_busy = 0;
902 	rcu_read_lock();
903 	for (q = 0; q < vsi->num_queue_pairs; q++) {
904 		/* locate Tx ring */
905 		p = READ_ONCE(vsi->tx_rings[q]);
906 		if (!p)
907 			continue;
908 
909 		do {
910 			start = u64_stats_fetch_begin(&p->syncp);
911 			packets = p->stats.packets;
912 			bytes = p->stats.bytes;
913 		} while (u64_stats_fetch_retry(&p->syncp, start));
914 		tx_b += bytes;
915 		tx_p += packets;
916 		tx_restart += p->tx_stats.restart_queue;
917 		tx_busy += p->tx_stats.tx_busy;
918 		tx_linearize += p->tx_stats.tx_linearize;
919 		tx_force_wb += p->tx_stats.tx_force_wb;
920 		tx_stopped += p->tx_stats.tx_stopped;
921 
922 		/* locate Rx ring */
923 		p = READ_ONCE(vsi->rx_rings[q]);
924 		if (!p)
925 			continue;
926 
927 		do {
928 			start = u64_stats_fetch_begin(&p->syncp);
929 			packets = p->stats.packets;
930 			bytes = p->stats.bytes;
931 		} while (u64_stats_fetch_retry(&p->syncp, start));
932 		rx_b += bytes;
933 		rx_p += packets;
934 		rx_buf += p->rx_stats.alloc_buff_failed;
935 		rx_page += p->rx_stats.alloc_page_failed;
936 		rx_reuse += p->rx_stats.page_reuse_count;
937 		rx_alloc += p->rx_stats.page_alloc_count;
938 		rx_waive += p->rx_stats.page_waive_count;
939 		rx_busy += p->rx_stats.page_busy_count;
940 
941 		if (i40e_enabled_xdp_vsi(vsi)) {
942 			/* locate XDP ring */
943 			p = READ_ONCE(vsi->xdp_rings[q]);
944 			if (!p)
945 				continue;
946 
947 			do {
948 				start = u64_stats_fetch_begin(&p->syncp);
949 				packets = p->stats.packets;
950 				bytes = p->stats.bytes;
951 			} while (u64_stats_fetch_retry(&p->syncp, start));
952 			tx_b += bytes;
953 			tx_p += packets;
954 			tx_restart += p->tx_stats.restart_queue;
955 			tx_busy += p->tx_stats.tx_busy;
956 			tx_linearize += p->tx_stats.tx_linearize;
957 			tx_force_wb += p->tx_stats.tx_force_wb;
958 		}
959 	}
960 	rcu_read_unlock();
961 	vsi->tx_restart = tx_restart;
962 	vsi->tx_busy = tx_busy;
963 	vsi->tx_linearize = tx_linearize;
964 	vsi->tx_force_wb = tx_force_wb;
965 	vsi->tx_stopped = tx_stopped;
966 	vsi->rx_page_failed = rx_page;
967 	vsi->rx_buf_failed = rx_buf;
968 	vsi->rx_page_reuse = rx_reuse;
969 	vsi->rx_page_alloc = rx_alloc;
970 	vsi->rx_page_waive = rx_waive;
971 	vsi->rx_page_busy = rx_busy;
972 
973 	ns->rx_packets = rx_p;
974 	ns->rx_bytes = rx_b;
975 	ns->tx_packets = tx_p;
976 	ns->tx_bytes = tx_b;
977 
978 	/* update netdev stats from eth stats */
979 	i40e_update_eth_stats(vsi);
980 	ons->tx_errors = oes->tx_errors;
981 	ns->tx_errors = es->tx_errors;
982 	ons->multicast = oes->rx_multicast;
983 	ns->multicast = es->rx_multicast;
984 	ons->rx_dropped = oes->rx_discards_other;
985 	ns->rx_dropped = es->rx_discards_other;
986 	ons->rx_missed_errors = oes->rx_discards;
987 	ns->rx_missed_errors = es->rx_discards;
988 	ons->tx_dropped = oes->tx_discards;
989 	ns->tx_dropped = es->tx_discards;
990 
991 	/* pull in a couple PF stats if this is the main vsi */
992 	if (vsi->type == I40E_VSI_MAIN) {
993 		ns->rx_crc_errors = pf->stats.crc_errors;
994 		ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
995 		ns->rx_length_errors = pf->stats.rx_length_errors;
996 	}
997 }
998 
999 /**
1000  * i40e_update_pf_stats - Update the PF statistics counters.
1001  * @pf: the PF to be updated
1002  **/
1003 static void i40e_update_pf_stats(struct i40e_pf *pf)
1004 {
1005 	struct i40e_hw_port_stats *osd = &pf->stats_offsets;
1006 	struct i40e_hw_port_stats *nsd = &pf->stats;
1007 	struct i40e_hw *hw = &pf->hw;
1008 	u32 val;
1009 	int i;
1010 
1011 	i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
1012 			   I40E_GLPRT_GORCL(hw->port),
1013 			   pf->stat_offsets_loaded,
1014 			   &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
1015 	i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
1016 			   I40E_GLPRT_GOTCL(hw->port),
1017 			   pf->stat_offsets_loaded,
1018 			   &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
1019 	i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
1020 			   pf->stat_offsets_loaded,
1021 			   &osd->eth.rx_discards,
1022 			   &nsd->eth.rx_discards);
1023 	i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
1024 			   I40E_GLPRT_UPRCL(hw->port),
1025 			   pf->stat_offsets_loaded,
1026 			   &osd->eth.rx_unicast,
1027 			   &nsd->eth.rx_unicast);
1028 	i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
1029 			   I40E_GLPRT_MPRCL(hw->port),
1030 			   pf->stat_offsets_loaded,
1031 			   &osd->eth.rx_multicast,
1032 			   &nsd->eth.rx_multicast);
1033 	i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
1034 			   I40E_GLPRT_BPRCL(hw->port),
1035 			   pf->stat_offsets_loaded,
1036 			   &osd->eth.rx_broadcast,
1037 			   &nsd->eth.rx_broadcast);
1038 	i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
1039 			   I40E_GLPRT_UPTCL(hw->port),
1040 			   pf->stat_offsets_loaded,
1041 			   &osd->eth.tx_unicast,
1042 			   &nsd->eth.tx_unicast);
1043 	i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
1044 			   I40E_GLPRT_MPTCL(hw->port),
1045 			   pf->stat_offsets_loaded,
1046 			   &osd->eth.tx_multicast,
1047 			   &nsd->eth.tx_multicast);
1048 	i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
1049 			   I40E_GLPRT_BPTCL(hw->port),
1050 			   pf->stat_offsets_loaded,
1051 			   &osd->eth.tx_broadcast,
1052 			   &nsd->eth.tx_broadcast);
1053 
1054 	i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
1055 			   pf->stat_offsets_loaded,
1056 			   &osd->tx_dropped_link_down,
1057 			   &nsd->tx_dropped_link_down);
1058 
1059 	i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
1060 			   pf->stat_offsets_loaded,
1061 			   &osd->crc_errors, &nsd->crc_errors);
1062 
1063 	i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
1064 			   pf->stat_offsets_loaded,
1065 			   &osd->illegal_bytes, &nsd->illegal_bytes);
1066 
1067 	i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
1068 			   pf->stat_offsets_loaded,
1069 			   &osd->mac_local_faults,
1070 			   &nsd->mac_local_faults);
1071 	i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
1072 			   pf->stat_offsets_loaded,
1073 			   &osd->mac_remote_faults,
1074 			   &nsd->mac_remote_faults);
1075 
1076 	i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
1077 			   pf->stat_offsets_loaded,
1078 			   &osd->rx_length_errors,
1079 			   &nsd->rx_length_errors);
1080 
1081 	i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
1082 			   pf->stat_offsets_loaded,
1083 			   &osd->link_xon_rx, &nsd->link_xon_rx);
1084 	i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
1085 			   pf->stat_offsets_loaded,
1086 			   &osd->link_xon_tx, &nsd->link_xon_tx);
1087 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
1088 			   pf->stat_offsets_loaded,
1089 			   &osd->link_xoff_rx, &nsd->link_xoff_rx);
1090 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
1091 			   pf->stat_offsets_loaded,
1092 			   &osd->link_xoff_tx, &nsd->link_xoff_tx);
1093 
1094 	for (i = 0; i < 8; i++) {
1095 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
1096 				   pf->stat_offsets_loaded,
1097 				   &osd->priority_xoff_rx[i],
1098 				   &nsd->priority_xoff_rx[i]);
1099 		i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
1100 				   pf->stat_offsets_loaded,
1101 				   &osd->priority_xon_rx[i],
1102 				   &nsd->priority_xon_rx[i]);
1103 		i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
1104 				   pf->stat_offsets_loaded,
1105 				   &osd->priority_xon_tx[i],
1106 				   &nsd->priority_xon_tx[i]);
1107 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
1108 				   pf->stat_offsets_loaded,
1109 				   &osd->priority_xoff_tx[i],
1110 				   &nsd->priority_xoff_tx[i]);
1111 		i40e_stat_update32(hw,
1112 				   I40E_GLPRT_RXON2OFFCNT(hw->port, i),
1113 				   pf->stat_offsets_loaded,
1114 				   &osd->priority_xon_2_xoff[i],
1115 				   &nsd->priority_xon_2_xoff[i]);
1116 	}
1117 
1118 	i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
1119 			   I40E_GLPRT_PRC64L(hw->port),
1120 			   pf->stat_offsets_loaded,
1121 			   &osd->rx_size_64, &nsd->rx_size_64);
1122 	i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
1123 			   I40E_GLPRT_PRC127L(hw->port),
1124 			   pf->stat_offsets_loaded,
1125 			   &osd->rx_size_127, &nsd->rx_size_127);
1126 	i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
1127 			   I40E_GLPRT_PRC255L(hw->port),
1128 			   pf->stat_offsets_loaded,
1129 			   &osd->rx_size_255, &nsd->rx_size_255);
1130 	i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
1131 			   I40E_GLPRT_PRC511L(hw->port),
1132 			   pf->stat_offsets_loaded,
1133 			   &osd->rx_size_511, &nsd->rx_size_511);
1134 	i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
1135 			   I40E_GLPRT_PRC1023L(hw->port),
1136 			   pf->stat_offsets_loaded,
1137 			   &osd->rx_size_1023, &nsd->rx_size_1023);
1138 	i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
1139 			   I40E_GLPRT_PRC1522L(hw->port),
1140 			   pf->stat_offsets_loaded,
1141 			   &osd->rx_size_1522, &nsd->rx_size_1522);
1142 	i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
1143 			   I40E_GLPRT_PRC9522L(hw->port),
1144 			   pf->stat_offsets_loaded,
1145 			   &osd->rx_size_big, &nsd->rx_size_big);
1146 
1147 	i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1148 			   I40E_GLPRT_PTC64L(hw->port),
1149 			   pf->stat_offsets_loaded,
1150 			   &osd->tx_size_64, &nsd->tx_size_64);
1151 	i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1152 			   I40E_GLPRT_PTC127L(hw->port),
1153 			   pf->stat_offsets_loaded,
1154 			   &osd->tx_size_127, &nsd->tx_size_127);
1155 	i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1156 			   I40E_GLPRT_PTC255L(hw->port),
1157 			   pf->stat_offsets_loaded,
1158 			   &osd->tx_size_255, &nsd->tx_size_255);
1159 	i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1160 			   I40E_GLPRT_PTC511L(hw->port),
1161 			   pf->stat_offsets_loaded,
1162 			   &osd->tx_size_511, &nsd->tx_size_511);
1163 	i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1164 			   I40E_GLPRT_PTC1023L(hw->port),
1165 			   pf->stat_offsets_loaded,
1166 			   &osd->tx_size_1023, &nsd->tx_size_1023);
1167 	i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1168 			   I40E_GLPRT_PTC1522L(hw->port),
1169 			   pf->stat_offsets_loaded,
1170 			   &osd->tx_size_1522, &nsd->tx_size_1522);
1171 	i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1172 			   I40E_GLPRT_PTC9522L(hw->port),
1173 			   pf->stat_offsets_loaded,
1174 			   &osd->tx_size_big, &nsd->tx_size_big);
1175 
1176 	i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1177 			   pf->stat_offsets_loaded,
1178 			   &osd->rx_undersize, &nsd->rx_undersize);
1179 	i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1180 			   pf->stat_offsets_loaded,
1181 			   &osd->rx_fragments, &nsd->rx_fragments);
1182 	i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1183 			   pf->stat_offsets_loaded,
1184 			   &osd->rx_oversize, &nsd->rx_oversize);
1185 	i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1186 			   pf->stat_offsets_loaded,
1187 			   &osd->rx_jabber, &nsd->rx_jabber);
1188 
1189 	/* FDIR stats */
1190 	i40e_stat_update_and_clear32(hw,
1191 			I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(hw->pf_id)),
1192 			&nsd->fd_atr_match);
1193 	i40e_stat_update_and_clear32(hw,
1194 			I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(hw->pf_id)),
1195 			&nsd->fd_sb_match);
1196 	i40e_stat_update_and_clear32(hw,
1197 			I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(hw->pf_id)),
1198 			&nsd->fd_atr_tunnel_match);
1199 
1200 	val = rd32(hw, I40E_PRTPM_EEE_STAT);
1201 	nsd->tx_lpi_status =
1202 		       FIELD_GET(I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK, val);
1203 	nsd->rx_lpi_status =
1204 		       FIELD_GET(I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK, val);
1205 	i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1206 			   pf->stat_offsets_loaded,
1207 			   &osd->tx_lpi_count, &nsd->tx_lpi_count);
1208 	i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1209 			   pf->stat_offsets_loaded,
1210 			   &osd->rx_lpi_count, &nsd->rx_lpi_count);
1211 
1212 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
1213 	    !test_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
1214 		nsd->fd_sb_status = true;
1215 	else
1216 		nsd->fd_sb_status = false;
1217 
1218 	if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
1219 	    !test_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
1220 		nsd->fd_atr_status = true;
1221 	else
1222 		nsd->fd_atr_status = false;
1223 
1224 	pf->stat_offsets_loaded = true;
1225 }
1226 
1227 /**
1228  * i40e_update_stats - Update the various statistics counters.
1229  * @vsi: the VSI to be updated
1230  *
1231  * Update the various stats for this VSI and its related entities.
1232  **/
1233 void i40e_update_stats(struct i40e_vsi *vsi)
1234 {
1235 	struct i40e_pf *pf = vsi->back;
1236 
1237 	if (vsi->type == I40E_VSI_MAIN)
1238 		i40e_update_pf_stats(pf);
1239 
1240 	i40e_update_vsi_stats(vsi);
1241 }
1242 
1243 /**
1244  * i40e_count_filters - counts VSI mac filters
1245  * @vsi: the VSI to be searched
1246  *
1247  * Returns count of mac filters
1248  **/
1249 int i40e_count_filters(struct i40e_vsi *vsi)
1250 {
1251 	struct i40e_mac_filter *f;
1252 	struct hlist_node *h;
1253 	int bkt;
1254 	int cnt = 0;
1255 
1256 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1257 		if (f->state == I40E_FILTER_NEW ||
1258 		    f->state == I40E_FILTER_ACTIVE)
1259 			++cnt;
1260 	}
1261 
1262 	return cnt;
1263 }
1264 
1265 /**
1266  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1267  * @vsi: the VSI to be searched
1268  * @macaddr: the MAC address
1269  * @vlan: the vlan
1270  *
1271  * Returns ptr to the filter object or NULL
1272  **/
1273 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1274 						const u8 *macaddr, s16 vlan)
1275 {
1276 	struct i40e_mac_filter *f;
1277 	u64 key;
1278 
1279 	if (!vsi || !macaddr)
1280 		return NULL;
1281 
1282 	key = i40e_addr_to_hkey(macaddr);
1283 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1284 		if ((ether_addr_equal(macaddr, f->macaddr)) &&
1285 		    (vlan == f->vlan))
1286 			return f;
1287 	}
1288 	return NULL;
1289 }
1290 
1291 /**
1292  * i40e_find_mac - Find a mac addr in the macvlan filters list
1293  * @vsi: the VSI to be searched
1294  * @macaddr: the MAC address we are searching for
1295  *
1296  * Returns the first filter with the provided MAC address or NULL if
1297  * MAC address was not found
1298  **/
1299 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1300 {
1301 	struct i40e_mac_filter *f;
1302 	u64 key;
1303 
1304 	if (!vsi || !macaddr)
1305 		return NULL;
1306 
1307 	key = i40e_addr_to_hkey(macaddr);
1308 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1309 		if ((ether_addr_equal(macaddr, f->macaddr)))
1310 			return f;
1311 	}
1312 	return NULL;
1313 }
1314 
1315 /**
1316  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1317  * @vsi: the VSI to be searched
1318  *
1319  * Returns true if VSI is in vlan mode or false otherwise
1320  **/
1321 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1322 {
1323 	/* If we have a PVID, always operate in VLAN mode */
1324 	if (vsi->info.pvid)
1325 		return true;
1326 
1327 	/* We need to operate in VLAN mode whenever we have any filters with
1328 	 * a VLAN other than I40E_VLAN_ALL. We could check the table each
1329 	 * time, incurring search cost repeatedly. However, we can notice two
1330 	 * things:
1331 	 *
1332 	 * 1) the only place where we can gain a VLAN filter is in
1333 	 *    i40e_add_filter.
1334 	 *
1335 	 * 2) the only place where filters are actually removed is in
1336 	 *    i40e_sync_filters_subtask.
1337 	 *
1338 	 * Thus, we can simply use a boolean value, has_vlan_filters which we
1339 	 * will set to true when we add a VLAN filter in i40e_add_filter. Then
1340 	 * we have to perform the full search after deleting filters in
1341 	 * i40e_sync_filters_subtask, but we already have to search
1342 	 * filters here and can perform the check at the same time. This
1343 	 * results in avoiding embedding a loop for VLAN mode inside another
1344 	 * loop over all the filters, and should maintain correctness as noted
1345 	 * above.
1346 	 */
1347 	return vsi->has_vlan_filter;
1348 }
1349 
1350 /**
1351  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1352  * @vsi: the VSI to configure
1353  * @tmp_add_list: list of filters ready to be added
1354  * @tmp_del_list: list of filters ready to be deleted
1355  * @vlan_filters: the number of active VLAN filters
1356  *
1357  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1358  * behave as expected. If we have any active VLAN filters remaining or about
1359  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1360  * so that they only match against untagged traffic. If we no longer have any
1361  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1362  * so that they match against both tagged and untagged traffic. In this way,
1363  * we ensure that we correctly receive the desired traffic. This ensures that
1364  * when we have an active VLAN we will receive only untagged traffic and
1365  * traffic matching active VLANs. If we have no active VLANs then we will
1366  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1367  *
1368  * Finally, in a similar fashion, this function also corrects filters when
1369  * there is an active PVID assigned to this VSI.
1370  *
1371  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1372  *
1373  * This function is only expected to be called from within
1374  * i40e_sync_vsi_filters.
1375  *
1376  * NOTE: This function expects to be called while under the
1377  * mac_filter_hash_lock
1378  */
1379 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1380 					 struct hlist_head *tmp_add_list,
1381 					 struct hlist_head *tmp_del_list,
1382 					 int vlan_filters)
1383 {
1384 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1385 	struct i40e_mac_filter *f, *add_head;
1386 	struct i40e_new_mac_filter *new;
1387 	struct hlist_node *h;
1388 	int bkt, new_vlan;
1389 
1390 	/* To determine if a particular filter needs to be replaced we
1391 	 * have the three following conditions:
1392 	 *
1393 	 * a) if we have a PVID assigned, then all filters which are
1394 	 *    not marked as VLAN=PVID must be replaced with filters that
1395 	 *    are.
1396 	 * b) otherwise, if we have any active VLANS, all filters
1397 	 *    which are marked as VLAN=-1 must be replaced with
1398 	 *    filters marked as VLAN=0
1399 	 * c) finally, if we do not have any active VLANS, all filters
1400 	 *    which are marked as VLAN=0 must be replaced with filters
1401 	 *    marked as VLAN=-1
1402 	 */
1403 
1404 	/* Update the filters about to be added in place */
1405 	hlist_for_each_entry(new, tmp_add_list, hlist) {
1406 		if (pvid && new->f->vlan != pvid)
1407 			new->f->vlan = pvid;
1408 		else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1409 			new->f->vlan = 0;
1410 		else if (!vlan_filters && new->f->vlan == 0)
1411 			new->f->vlan = I40E_VLAN_ANY;
1412 	}
1413 
1414 	/* Update the remaining active filters */
1415 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1416 		/* Combine the checks for whether a filter needs to be changed
1417 		 * and then determine the new VLAN inside the if block, in
1418 		 * order to avoid duplicating code for adding the new filter
1419 		 * then deleting the old filter.
1420 		 */
1421 		if ((pvid && f->vlan != pvid) ||
1422 		    (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1423 		    (!vlan_filters && f->vlan == 0)) {
1424 			/* Determine the new vlan we will be adding */
1425 			if (pvid)
1426 				new_vlan = pvid;
1427 			else if (vlan_filters)
1428 				new_vlan = 0;
1429 			else
1430 				new_vlan = I40E_VLAN_ANY;
1431 
1432 			/* Create the new filter */
1433 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1434 			if (!add_head)
1435 				return -ENOMEM;
1436 
1437 			/* Create a temporary i40e_new_mac_filter */
1438 			new = kzalloc(sizeof(*new), GFP_ATOMIC);
1439 			if (!new)
1440 				return -ENOMEM;
1441 
1442 			new->f = add_head;
1443 			new->state = add_head->state;
1444 
1445 			/* Add the new filter to the tmp list */
1446 			hlist_add_head(&new->hlist, tmp_add_list);
1447 
1448 			/* Put the original filter into the delete list */
1449 			f->state = I40E_FILTER_REMOVE;
1450 			hash_del(&f->hlist);
1451 			hlist_add_head(&f->hlist, tmp_del_list);
1452 		}
1453 	}
1454 
1455 	vsi->has_vlan_filter = !!vlan_filters;
1456 
1457 	return 0;
1458 }
1459 
1460 /**
1461  * i40e_get_vf_new_vlan - Get new vlan id on a vf
1462  * @vsi: the vsi to configure
1463  * @new_mac: new mac filter to be added
1464  * @f: existing mac filter, replaced with new_mac->f if new_mac is not NULL
1465  * @vlan_filters: the number of active VLAN filters
1466  * @trusted: flag if the VF is trusted
1467  *
1468  * Get new VLAN id based on current VLAN filters, trust, PVID
1469  * and vf-vlan-prune-disable flag.
1470  *
1471  * Returns the value of the new vlan filter or
1472  * the old value if no new filter is needed.
1473  */
1474 static s16 i40e_get_vf_new_vlan(struct i40e_vsi *vsi,
1475 				struct i40e_new_mac_filter *new_mac,
1476 				struct i40e_mac_filter *f,
1477 				int vlan_filters,
1478 				bool trusted)
1479 {
1480 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1481 	struct i40e_pf *pf = vsi->back;
1482 	bool is_any;
1483 
1484 	if (new_mac)
1485 		f = new_mac->f;
1486 
1487 	if (pvid && f->vlan != pvid)
1488 		return pvid;
1489 
1490 	is_any = (trusted ||
1491 		  !test_bit(I40E_FLAG_VF_VLAN_PRUNING_ENA, pf->flags));
1492 
1493 	if ((vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1494 	    (!is_any && !vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1495 	    (is_any && !vlan_filters && f->vlan == 0)) {
1496 		if (is_any)
1497 			return I40E_VLAN_ANY;
1498 		else
1499 			return 0;
1500 	}
1501 
1502 	return f->vlan;
1503 }
1504 
1505 /**
1506  * i40e_correct_vf_mac_vlan_filters - Correct non-VLAN VF filters if necessary
1507  * @vsi: the vsi to configure
1508  * @tmp_add_list: list of filters ready to be added
1509  * @tmp_del_list: list of filters ready to be deleted
1510  * @vlan_filters: the number of active VLAN filters
1511  * @trusted: flag if the VF is trusted
1512  *
1513  * Correct VF VLAN filters based on current VLAN filters, trust, PVID
1514  * and vf-vlan-prune-disable flag.
1515  *
1516  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1517  *
1518  * This function is only expected to be called from within
1519  * i40e_sync_vsi_filters.
1520  *
1521  * NOTE: This function expects to be called while under the
1522  * mac_filter_hash_lock
1523  */
1524 static int i40e_correct_vf_mac_vlan_filters(struct i40e_vsi *vsi,
1525 					    struct hlist_head *tmp_add_list,
1526 					    struct hlist_head *tmp_del_list,
1527 					    int vlan_filters,
1528 					    bool trusted)
1529 {
1530 	struct i40e_mac_filter *f, *add_head;
1531 	struct i40e_new_mac_filter *new_mac;
1532 	struct hlist_node *h;
1533 	int bkt, new_vlan;
1534 
1535 	hlist_for_each_entry(new_mac, tmp_add_list, hlist) {
1536 		new_mac->f->vlan = i40e_get_vf_new_vlan(vsi, new_mac, NULL,
1537 							vlan_filters, trusted);
1538 	}
1539 
1540 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1541 		new_vlan = i40e_get_vf_new_vlan(vsi, NULL, f, vlan_filters,
1542 						trusted);
1543 		if (new_vlan != f->vlan) {
1544 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1545 			if (!add_head)
1546 				return -ENOMEM;
1547 			/* Create a temporary i40e_new_mac_filter */
1548 			new_mac = kzalloc(sizeof(*new_mac), GFP_ATOMIC);
1549 			if (!new_mac)
1550 				return -ENOMEM;
1551 			new_mac->f = add_head;
1552 			new_mac->state = add_head->state;
1553 
1554 			/* Add the new filter to the tmp list */
1555 			hlist_add_head(&new_mac->hlist, tmp_add_list);
1556 
1557 			/* Put the original filter into the delete list */
1558 			f->state = I40E_FILTER_REMOVE;
1559 			hash_del(&f->hlist);
1560 			hlist_add_head(&f->hlist, tmp_del_list);
1561 		}
1562 	}
1563 
1564 	vsi->has_vlan_filter = !!vlan_filters;
1565 	return 0;
1566 }
1567 
1568 /**
1569  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1570  * @vsi: the PF Main VSI - inappropriate for any other VSI
1571  * @macaddr: the MAC address
1572  *
1573  * Remove whatever filter the firmware set up so the driver can manage
1574  * its own filtering intelligently.
1575  **/
1576 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1577 {
1578 	struct i40e_aqc_remove_macvlan_element_data element;
1579 	struct i40e_pf *pf = vsi->back;
1580 
1581 	/* Only appropriate for the PF main VSI */
1582 	if (vsi->type != I40E_VSI_MAIN)
1583 		return;
1584 
1585 	memset(&element, 0, sizeof(element));
1586 	ether_addr_copy(element.mac_addr, macaddr);
1587 	element.vlan_tag = 0;
1588 	/* Ignore error returns, some firmware does it this way... */
1589 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1590 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1591 
1592 	memset(&element, 0, sizeof(element));
1593 	ether_addr_copy(element.mac_addr, macaddr);
1594 	element.vlan_tag = 0;
1595 	/* ...and some firmware does it this way. */
1596 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1597 			I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1598 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1599 }
1600 
1601 /**
1602  * i40e_add_filter - Add a mac/vlan filter to the VSI
1603  * @vsi: the VSI to be searched
1604  * @macaddr: the MAC address
1605  * @vlan: the vlan
1606  *
1607  * Returns ptr to the filter object or NULL when no memory available.
1608  *
1609  * NOTE: This function is expected to be called with mac_filter_hash_lock
1610  * being held.
1611  **/
1612 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1613 					const u8 *macaddr, s16 vlan)
1614 {
1615 	struct i40e_mac_filter *f;
1616 	u64 key;
1617 
1618 	if (!vsi || !macaddr)
1619 		return NULL;
1620 
1621 	f = i40e_find_filter(vsi, macaddr, vlan);
1622 	if (!f) {
1623 		f = kzalloc(sizeof(*f), GFP_ATOMIC);
1624 		if (!f)
1625 			return NULL;
1626 
1627 		/* Update the boolean indicating if we need to function in
1628 		 * VLAN mode.
1629 		 */
1630 		if (vlan >= 0)
1631 			vsi->has_vlan_filter = true;
1632 
1633 		ether_addr_copy(f->macaddr, macaddr);
1634 		f->vlan = vlan;
1635 		f->state = I40E_FILTER_NEW;
1636 		INIT_HLIST_NODE(&f->hlist);
1637 
1638 		key = i40e_addr_to_hkey(macaddr);
1639 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
1640 
1641 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1642 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1643 	}
1644 
1645 	/* If we're asked to add a filter that has been marked for removal, it
1646 	 * is safe to simply restore it to active state. __i40e_del_filter
1647 	 * will have simply deleted any filters which were previously marked
1648 	 * NEW or FAILED, so if it is currently marked REMOVE it must have
1649 	 * previously been ACTIVE. Since we haven't yet run the sync filters
1650 	 * task, just restore this filter to the ACTIVE state so that the
1651 	 * sync task leaves it in place
1652 	 */
1653 	if (f->state == I40E_FILTER_REMOVE)
1654 		f->state = I40E_FILTER_ACTIVE;
1655 
1656 	return f;
1657 }
1658 
1659 /**
1660  * __i40e_del_filter - Remove a specific filter from the VSI
1661  * @vsi: VSI to remove from
1662  * @f: the filter to remove from the list
1663  *
1664  * This function should be called instead of i40e_del_filter only if you know
1665  * the exact filter you will remove already, such as via i40e_find_filter or
1666  * i40e_find_mac.
1667  *
1668  * NOTE: This function is expected to be called with mac_filter_hash_lock
1669  * being held.
1670  * ANOTHER NOTE: This function MUST be called from within the context of
1671  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1672  * instead of list_for_each_entry().
1673  **/
1674 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1675 {
1676 	if (!f)
1677 		return;
1678 
1679 	/* If the filter was never added to firmware then we can just delete it
1680 	 * directly and we don't want to set the status to remove or else an
1681 	 * admin queue command will unnecessarily fire.
1682 	 */
1683 	if ((f->state == I40E_FILTER_FAILED) ||
1684 	    (f->state == I40E_FILTER_NEW)) {
1685 		hash_del(&f->hlist);
1686 		kfree(f);
1687 	} else {
1688 		f->state = I40E_FILTER_REMOVE;
1689 	}
1690 
1691 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1692 	set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1693 }
1694 
1695 /**
1696  * i40e_del_filter - Remove a MAC/VLAN filter from the VSI
1697  * @vsi: the VSI to be searched
1698  * @macaddr: the MAC address
1699  * @vlan: the VLAN
1700  *
1701  * NOTE: This function is expected to be called with mac_filter_hash_lock
1702  * being held.
1703  * ANOTHER NOTE: This function MUST be called from within the context of
1704  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1705  * instead of list_for_each_entry().
1706  **/
1707 void i40e_del_filter(struct i40e_vsi *vsi, const u8 *macaddr, s16 vlan)
1708 {
1709 	struct i40e_mac_filter *f;
1710 
1711 	if (!vsi || !macaddr)
1712 		return;
1713 
1714 	f = i40e_find_filter(vsi, macaddr, vlan);
1715 	__i40e_del_filter(vsi, f);
1716 }
1717 
1718 /**
1719  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1720  * @vsi: the VSI to be searched
1721  * @macaddr: the mac address to be filtered
1722  *
1723  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1724  * go through all the macvlan filters and add a macvlan filter for each
1725  * unique vlan that already exists. If a PVID has been assigned, instead only
1726  * add the macaddr to that VLAN.
1727  *
1728  * Returns last filter added on success, else NULL
1729  **/
1730 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1731 					    const u8 *macaddr)
1732 {
1733 	struct i40e_mac_filter *f, *add = NULL;
1734 	struct hlist_node *h;
1735 	int bkt;
1736 
1737 	if (vsi->info.pvid)
1738 		return i40e_add_filter(vsi, macaddr,
1739 				       le16_to_cpu(vsi->info.pvid));
1740 
1741 	if (!i40e_is_vsi_in_vlan(vsi))
1742 		return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1743 
1744 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1745 		if (f->state == I40E_FILTER_REMOVE)
1746 			continue;
1747 		add = i40e_add_filter(vsi, macaddr, f->vlan);
1748 		if (!add)
1749 			return NULL;
1750 	}
1751 
1752 	return add;
1753 }
1754 
1755 /**
1756  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1757  * @vsi: the VSI to be searched
1758  * @macaddr: the mac address to be removed
1759  *
1760  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1761  * associated with.
1762  *
1763  * Returns 0 for success, or error
1764  **/
1765 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1766 {
1767 	struct i40e_mac_filter *f;
1768 	struct hlist_node *h;
1769 	bool found = false;
1770 	int bkt;
1771 
1772 	lockdep_assert_held(&vsi->mac_filter_hash_lock);
1773 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1774 		if (ether_addr_equal(macaddr, f->macaddr)) {
1775 			__i40e_del_filter(vsi, f);
1776 			found = true;
1777 		}
1778 	}
1779 
1780 	if (found)
1781 		return 0;
1782 	else
1783 		return -ENOENT;
1784 }
1785 
1786 /**
1787  * i40e_set_mac - NDO callback to set mac address
1788  * @netdev: network interface device structure
1789  * @p: pointer to an address structure
1790  *
1791  * Returns 0 on success, negative on failure
1792  **/
1793 static int i40e_set_mac(struct net_device *netdev, void *p)
1794 {
1795 	struct i40e_netdev_priv *np = netdev_priv(netdev);
1796 	struct i40e_vsi *vsi = np->vsi;
1797 	struct i40e_pf *pf = vsi->back;
1798 	struct i40e_hw *hw = &pf->hw;
1799 	struct sockaddr *addr = p;
1800 
1801 	if (!is_valid_ether_addr(addr->sa_data))
1802 		return -EADDRNOTAVAIL;
1803 
1804 	if (test_bit(__I40E_DOWN, pf->state) ||
1805 	    test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1806 		return -EADDRNOTAVAIL;
1807 
1808 	if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1809 		netdev_info(netdev, "returning to hw mac address %pM\n",
1810 			    hw->mac.addr);
1811 	else
1812 		netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1813 
1814 	/* Copy the address first, so that we avoid a possible race with
1815 	 * .set_rx_mode().
1816 	 * - Remove old address from MAC filter
1817 	 * - Copy new address
1818 	 * - Add new address to MAC filter
1819 	 */
1820 	spin_lock_bh(&vsi->mac_filter_hash_lock);
1821 	i40e_del_mac_filter(vsi, netdev->dev_addr);
1822 	eth_hw_addr_set(netdev, addr->sa_data);
1823 	i40e_add_mac_filter(vsi, netdev->dev_addr);
1824 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
1825 
1826 	if (vsi->type == I40E_VSI_MAIN) {
1827 		int ret;
1828 
1829 		ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1830 						addr->sa_data, NULL);
1831 		if (ret)
1832 			netdev_info(netdev, "Ignoring error from firmware on LAA update, status %pe, AQ ret %s\n",
1833 				    ERR_PTR(ret),
1834 				    i40e_aq_str(hw, hw->aq.asq_last_status));
1835 	}
1836 
1837 	/* schedule our worker thread which will take care of
1838 	 * applying the new filter changes
1839 	 */
1840 	i40e_service_event_schedule(pf);
1841 	return 0;
1842 }
1843 
1844 /**
1845  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1846  * @vsi: vsi structure
1847  * @seed: RSS hash seed
1848  * @lut: pointer to lookup table of lut_size
1849  * @lut_size: size of the lookup table
1850  **/
1851 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1852 			      u8 *lut, u16 lut_size)
1853 {
1854 	struct i40e_pf *pf = vsi->back;
1855 	struct i40e_hw *hw = &pf->hw;
1856 	int ret = 0;
1857 
1858 	if (seed) {
1859 		struct i40e_aqc_get_set_rss_key_data *seed_dw =
1860 			(struct i40e_aqc_get_set_rss_key_data *)seed;
1861 		ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1862 		if (ret) {
1863 			dev_info(&pf->pdev->dev,
1864 				 "Cannot set RSS key, err %pe aq_err %s\n",
1865 				 ERR_PTR(ret),
1866 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1867 			return ret;
1868 		}
1869 	}
1870 	if (lut) {
1871 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
1872 
1873 		ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1874 		if (ret) {
1875 			dev_info(&pf->pdev->dev,
1876 				 "Cannot set RSS lut, err %pe aq_err %s\n",
1877 				 ERR_PTR(ret),
1878 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1879 			return ret;
1880 		}
1881 	}
1882 	return ret;
1883 }
1884 
1885 /**
1886  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1887  * @vsi: VSI structure
1888  **/
1889 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1890 {
1891 	struct i40e_pf *pf = vsi->back;
1892 	u8 seed[I40E_HKEY_ARRAY_SIZE];
1893 	u8 *lut;
1894 	int ret;
1895 
1896 	if (!test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
1897 		return 0;
1898 	if (!vsi->rss_size)
1899 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
1900 				      vsi->num_queue_pairs);
1901 	if (!vsi->rss_size)
1902 		return -EINVAL;
1903 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1904 	if (!lut)
1905 		return -ENOMEM;
1906 
1907 	/* Use the user configured hash keys and lookup table if there is one,
1908 	 * otherwise use default
1909 	 */
1910 	if (vsi->rss_lut_user)
1911 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1912 	else
1913 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1914 	if (vsi->rss_hkey_user)
1915 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1916 	else
1917 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1918 	ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1919 	kfree(lut);
1920 	return ret;
1921 }
1922 
1923 /**
1924  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1925  * @vsi: the VSI being configured,
1926  * @ctxt: VSI context structure
1927  * @enabled_tc: number of traffic classes to enable
1928  *
1929  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1930  **/
1931 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1932 					   struct i40e_vsi_context *ctxt,
1933 					   u8 enabled_tc)
1934 {
1935 	u16 qcount = 0, max_qcount, qmap, sections = 0;
1936 	int i, override_q, pow, num_qps, ret;
1937 	u8 netdev_tc = 0, offset = 0;
1938 
1939 	if (vsi->type != I40E_VSI_MAIN)
1940 		return -EINVAL;
1941 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1942 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1943 	vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1944 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1945 	num_qps = vsi->mqprio_qopt.qopt.count[0];
1946 
1947 	/* find the next higher power-of-2 of num queue pairs */
1948 	pow = ilog2(num_qps);
1949 	if (!is_power_of_2(num_qps))
1950 		pow++;
1951 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1952 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1953 
1954 	/* Setup queue offset/count for all TCs for given VSI */
1955 	max_qcount = vsi->mqprio_qopt.qopt.count[0];
1956 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1957 		/* See if the given TC is enabled for the given VSI */
1958 		if (vsi->tc_config.enabled_tc & BIT(i)) {
1959 			offset = vsi->mqprio_qopt.qopt.offset[i];
1960 			qcount = vsi->mqprio_qopt.qopt.count[i];
1961 			if (qcount > max_qcount)
1962 				max_qcount = qcount;
1963 			vsi->tc_config.tc_info[i].qoffset = offset;
1964 			vsi->tc_config.tc_info[i].qcount = qcount;
1965 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1966 		} else {
1967 			/* TC is not enabled so set the offset to
1968 			 * default queue and allocate one queue
1969 			 * for the given TC.
1970 			 */
1971 			vsi->tc_config.tc_info[i].qoffset = 0;
1972 			vsi->tc_config.tc_info[i].qcount = 1;
1973 			vsi->tc_config.tc_info[i].netdev_tc = 0;
1974 		}
1975 	}
1976 
1977 	/* Set actual Tx/Rx queue pairs */
1978 	vsi->num_queue_pairs = offset + qcount;
1979 
1980 	/* Setup queue TC[0].qmap for given VSI context */
1981 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1982 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1983 	ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1984 	ctxt->info.valid_sections |= cpu_to_le16(sections);
1985 
1986 	/* Reconfigure RSS for main VSI with max queue count */
1987 	vsi->rss_size = max_qcount;
1988 	ret = i40e_vsi_config_rss(vsi);
1989 	if (ret) {
1990 		dev_info(&vsi->back->pdev->dev,
1991 			 "Failed to reconfig rss for num_queues (%u)\n",
1992 			 max_qcount);
1993 		return ret;
1994 	}
1995 	vsi->reconfig_rss = true;
1996 	dev_dbg(&vsi->back->pdev->dev,
1997 		"Reconfigured rss with num_queues (%u)\n", max_qcount);
1998 
1999 	/* Find queue count available for channel VSIs and starting offset
2000 	 * for channel VSIs
2001 	 */
2002 	override_q = vsi->mqprio_qopt.qopt.count[0];
2003 	if (override_q && override_q < vsi->num_queue_pairs) {
2004 		vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
2005 		vsi->next_base_queue = override_q;
2006 	}
2007 	return 0;
2008 }
2009 
2010 /**
2011  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
2012  * @vsi: the VSI being setup
2013  * @ctxt: VSI context structure
2014  * @enabled_tc: Enabled TCs bitmap
2015  * @is_add: True if called before Add VSI
2016  *
2017  * Setup VSI queue mapping for enabled traffic classes.
2018  **/
2019 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
2020 				     struct i40e_vsi_context *ctxt,
2021 				     u8 enabled_tc,
2022 				     bool is_add)
2023 {
2024 	struct i40e_pf *pf = vsi->back;
2025 	u16 num_tc_qps = 0;
2026 	u16 sections = 0;
2027 	u8 netdev_tc = 0;
2028 	u16 numtc = 1;
2029 	u16 qcount;
2030 	u8 offset;
2031 	u16 qmap;
2032 	int i;
2033 
2034 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
2035 	offset = 0;
2036 	/* zero out queue mapping, it will get updated on the end of the function */
2037 	memset(ctxt->info.queue_mapping, 0, sizeof(ctxt->info.queue_mapping));
2038 
2039 	if (vsi->type == I40E_VSI_MAIN) {
2040 		/* This code helps add more queue to the VSI if we have
2041 		 * more cores than RSS can support, the higher cores will
2042 		 * be served by ATR or other filters. Furthermore, the
2043 		 * non-zero req_queue_pairs says that user requested a new
2044 		 * queue count via ethtool's set_channels, so use this
2045 		 * value for queues distribution across traffic classes
2046 		 * We need at least one queue pair for the interface
2047 		 * to be usable as we see in else statement.
2048 		 */
2049 		if (vsi->req_queue_pairs > 0)
2050 			vsi->num_queue_pairs = vsi->req_queue_pairs;
2051 		else if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
2052 			vsi->num_queue_pairs = pf->num_lan_msix;
2053 		else
2054 			vsi->num_queue_pairs = 1;
2055 	}
2056 
2057 	/* Number of queues per enabled TC */
2058 	if (vsi->type == I40E_VSI_MAIN ||
2059 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs != 0))
2060 		num_tc_qps = vsi->num_queue_pairs;
2061 	else
2062 		num_tc_qps = vsi->alloc_queue_pairs;
2063 
2064 	if (enabled_tc && test_bit(I40E_FLAG_DCB_ENA, vsi->back->flags)) {
2065 		/* Find numtc from enabled TC bitmap */
2066 		for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2067 			if (enabled_tc & BIT(i)) /* TC is enabled */
2068 				numtc++;
2069 		}
2070 		if (!numtc) {
2071 			dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
2072 			numtc = 1;
2073 		}
2074 		num_tc_qps = num_tc_qps / numtc;
2075 		num_tc_qps = min_t(int, num_tc_qps,
2076 				   i40e_pf_get_max_q_per_tc(pf));
2077 	}
2078 
2079 	vsi->tc_config.numtc = numtc;
2080 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
2081 
2082 	/* Do not allow use more TC queue pairs than MSI-X vectors exist */
2083 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
2084 		num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
2085 
2086 	/* Setup queue offset/count for all TCs for given VSI */
2087 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2088 		/* See if the given TC is enabled for the given VSI */
2089 		if (vsi->tc_config.enabled_tc & BIT(i)) {
2090 			/* TC is enabled */
2091 			int pow, num_qps;
2092 
2093 			switch (vsi->type) {
2094 			case I40E_VSI_MAIN:
2095 				if ((!test_bit(I40E_FLAG_FD_SB_ENA,
2096 					       pf->flags) &&
2097 				     !test_bit(I40E_FLAG_FD_ATR_ENA,
2098 					       pf->flags)) ||
2099 				    vsi->tc_config.enabled_tc != 1) {
2100 					qcount = min_t(int, pf->alloc_rss_size,
2101 						       num_tc_qps);
2102 					break;
2103 				}
2104 				fallthrough;
2105 			case I40E_VSI_FDIR:
2106 			case I40E_VSI_SRIOV:
2107 			case I40E_VSI_VMDQ2:
2108 			default:
2109 				qcount = num_tc_qps;
2110 				WARN_ON(i != 0);
2111 				break;
2112 			}
2113 			vsi->tc_config.tc_info[i].qoffset = offset;
2114 			vsi->tc_config.tc_info[i].qcount = qcount;
2115 
2116 			/* find the next higher power-of-2 of num queue pairs */
2117 			num_qps = qcount;
2118 			pow = 0;
2119 			while (num_qps && (BIT_ULL(pow) < qcount)) {
2120 				pow++;
2121 				num_qps >>= 1;
2122 			}
2123 
2124 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
2125 			qmap =
2126 			    (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
2127 			    (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
2128 
2129 			offset += qcount;
2130 		} else {
2131 			/* TC is not enabled so set the offset to
2132 			 * default queue and allocate one queue
2133 			 * for the given TC.
2134 			 */
2135 			vsi->tc_config.tc_info[i].qoffset = 0;
2136 			vsi->tc_config.tc_info[i].qcount = 1;
2137 			vsi->tc_config.tc_info[i].netdev_tc = 0;
2138 
2139 			qmap = 0;
2140 		}
2141 		ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
2142 	}
2143 	/* Do not change previously set num_queue_pairs for PFs and VFs*/
2144 	if ((vsi->type == I40E_VSI_MAIN && numtc != 1) ||
2145 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs == 0) ||
2146 	    (vsi->type != I40E_VSI_MAIN && vsi->type != I40E_VSI_SRIOV))
2147 		vsi->num_queue_pairs = offset;
2148 
2149 	/* Scheduler section valid can only be set for ADD VSI */
2150 	if (is_add) {
2151 		sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
2152 
2153 		ctxt->info.up_enable_bits = enabled_tc;
2154 	}
2155 	if (vsi->type == I40E_VSI_SRIOV) {
2156 		ctxt->info.mapping_flags |=
2157 				     cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
2158 		for (i = 0; i < vsi->num_queue_pairs; i++)
2159 			ctxt->info.queue_mapping[i] =
2160 					       cpu_to_le16(vsi->base_queue + i);
2161 	} else {
2162 		ctxt->info.mapping_flags |=
2163 					cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
2164 		ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
2165 	}
2166 	ctxt->info.valid_sections |= cpu_to_le16(sections);
2167 }
2168 
2169 /**
2170  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
2171  * @netdev: the netdevice
2172  * @addr: address to add
2173  *
2174  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
2175  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2176  */
2177 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
2178 {
2179 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2180 	struct i40e_vsi *vsi = np->vsi;
2181 
2182 	if (i40e_add_mac_filter(vsi, addr))
2183 		return 0;
2184 	else
2185 		return -ENOMEM;
2186 }
2187 
2188 /**
2189  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
2190  * @netdev: the netdevice
2191  * @addr: address to add
2192  *
2193  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
2194  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2195  */
2196 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
2197 {
2198 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2199 	struct i40e_vsi *vsi = np->vsi;
2200 
2201 	/* Under some circumstances, we might receive a request to delete
2202 	 * our own device address from our uc list. Because we store the
2203 	 * device address in the VSI's MAC/VLAN filter list, we need to ignore
2204 	 * such requests and not delete our device address from this list.
2205 	 */
2206 	if (ether_addr_equal(addr, netdev->dev_addr))
2207 		return 0;
2208 
2209 	i40e_del_mac_filter(vsi, addr);
2210 
2211 	return 0;
2212 }
2213 
2214 /**
2215  * i40e_set_rx_mode - NDO callback to set the netdev filters
2216  * @netdev: network interface device structure
2217  **/
2218 static void i40e_set_rx_mode(struct net_device *netdev)
2219 {
2220 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2221 	struct i40e_vsi *vsi = np->vsi;
2222 
2223 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2224 
2225 	__dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2226 	__dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2227 
2228 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2229 
2230 	/* check for other flag changes */
2231 	if (vsi->current_netdev_flags != vsi->netdev->flags) {
2232 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2233 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
2234 	}
2235 }
2236 
2237 /**
2238  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
2239  * @vsi: Pointer to VSI struct
2240  * @from: Pointer to list which contains MAC filter entries - changes to
2241  *        those entries needs to be undone.
2242  *
2243  * MAC filter entries from this list were slated for deletion.
2244  **/
2245 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
2246 					 struct hlist_head *from)
2247 {
2248 	struct i40e_mac_filter *f;
2249 	struct hlist_node *h;
2250 
2251 	hlist_for_each_entry_safe(f, h, from, hlist) {
2252 		u64 key = i40e_addr_to_hkey(f->macaddr);
2253 
2254 		/* Move the element back into MAC filter list*/
2255 		hlist_del(&f->hlist);
2256 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
2257 	}
2258 }
2259 
2260 /**
2261  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
2262  * @vsi: Pointer to vsi struct
2263  * @from: Pointer to list which contains MAC filter entries - changes to
2264  *        those entries needs to be undone.
2265  *
2266  * MAC filter entries from this list were slated for addition.
2267  **/
2268 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
2269 					 struct hlist_head *from)
2270 {
2271 	struct i40e_new_mac_filter *new;
2272 	struct hlist_node *h;
2273 
2274 	hlist_for_each_entry_safe(new, h, from, hlist) {
2275 		/* We can simply free the wrapper structure */
2276 		hlist_del(&new->hlist);
2277 		netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2278 		kfree(new);
2279 	}
2280 }
2281 
2282 /**
2283  * i40e_next_filter - Get the next non-broadcast filter from a list
2284  * @next: pointer to filter in list
2285  *
2286  * Returns the next non-broadcast filter in the list. Required so that we
2287  * ignore broadcast filters within the list, since these are not handled via
2288  * the normal firmware update path.
2289  */
2290 static
2291 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2292 {
2293 	hlist_for_each_entry_continue(next, hlist) {
2294 		if (!is_broadcast_ether_addr(next->f->macaddr))
2295 			return next;
2296 	}
2297 
2298 	return NULL;
2299 }
2300 
2301 /**
2302  * i40e_update_filter_state - Update filter state based on return data
2303  * from firmware
2304  * @count: Number of filters added
2305  * @add_list: return data from fw
2306  * @add_head: pointer to first filter in current batch
2307  *
2308  * MAC filter entries from list were slated to be added to device. Returns
2309  * number of successful filters. Note that 0 does NOT mean success!
2310  **/
2311 static int
2312 i40e_update_filter_state(int count,
2313 			 struct i40e_aqc_add_macvlan_element_data *add_list,
2314 			 struct i40e_new_mac_filter *add_head)
2315 {
2316 	int retval = 0;
2317 	int i;
2318 
2319 	for (i = 0; i < count; i++) {
2320 		/* Always check status of each filter. We don't need to check
2321 		 * the firmware return status because we pre-set the filter
2322 		 * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2323 		 * request to the adminq. Thus, if it no longer matches then
2324 		 * we know the filter is active.
2325 		 */
2326 		if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2327 			add_head->state = I40E_FILTER_FAILED;
2328 		} else {
2329 			add_head->state = I40E_FILTER_ACTIVE;
2330 			retval++;
2331 		}
2332 
2333 		add_head = i40e_next_filter(add_head);
2334 		if (!add_head)
2335 			break;
2336 	}
2337 
2338 	return retval;
2339 }
2340 
2341 /**
2342  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2343  * @vsi: ptr to the VSI
2344  * @vsi_name: name to display in messages
2345  * @list: the list of filters to send to firmware
2346  * @num_del: the number of filters to delete
2347  * @retval: Set to -EIO on failure to delete
2348  *
2349  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2350  * *retval instead of a return value so that success does not force ret_val to
2351  * be set to 0. This ensures that a sequence of calls to this function
2352  * preserve the previous value of *retval on successful delete.
2353  */
2354 static
2355 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2356 			  struct i40e_aqc_remove_macvlan_element_data *list,
2357 			  int num_del, int *retval)
2358 {
2359 	struct i40e_hw *hw = &vsi->back->hw;
2360 	enum i40e_admin_queue_err aq_status;
2361 	int aq_ret;
2362 
2363 	aq_ret = i40e_aq_remove_macvlan_v2(hw, vsi->seid, list, num_del, NULL,
2364 					   &aq_status);
2365 
2366 	/* Explicitly ignore and do not report when firmware returns ENOENT */
2367 	if (aq_ret && !(aq_status == I40E_AQ_RC_ENOENT)) {
2368 		*retval = -EIO;
2369 		dev_info(&vsi->back->pdev->dev,
2370 			 "ignoring delete macvlan error on %s, err %pe, aq_err %s\n",
2371 			 vsi_name, ERR_PTR(aq_ret),
2372 			 i40e_aq_str(hw, aq_status));
2373 	}
2374 }
2375 
2376 /**
2377  * i40e_aqc_add_filters - Request firmware to add a set of filters
2378  * @vsi: ptr to the VSI
2379  * @vsi_name: name to display in messages
2380  * @list: the list of filters to send to firmware
2381  * @add_head: Position in the add hlist
2382  * @num_add: the number of filters to add
2383  *
2384  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2385  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2386  * space for more filters.
2387  */
2388 static
2389 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2390 			  struct i40e_aqc_add_macvlan_element_data *list,
2391 			  struct i40e_new_mac_filter *add_head,
2392 			  int num_add)
2393 {
2394 	struct i40e_hw *hw = &vsi->back->hw;
2395 	enum i40e_admin_queue_err aq_status;
2396 	int fcnt;
2397 
2398 	i40e_aq_add_macvlan_v2(hw, vsi->seid, list, num_add, NULL, &aq_status);
2399 	fcnt = i40e_update_filter_state(num_add, list, add_head);
2400 
2401 	if (fcnt != num_add) {
2402 		if (vsi->type == I40E_VSI_MAIN) {
2403 			set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2404 			dev_warn(&vsi->back->pdev->dev,
2405 				 "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2406 				 i40e_aq_str(hw, aq_status), vsi_name);
2407 		} else if (vsi->type == I40E_VSI_SRIOV ||
2408 			   vsi->type == I40E_VSI_VMDQ1 ||
2409 			   vsi->type == I40E_VSI_VMDQ2) {
2410 			dev_warn(&vsi->back->pdev->dev,
2411 				 "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2412 				 i40e_aq_str(hw, aq_status), vsi_name,
2413 					     vsi_name);
2414 		} else {
2415 			dev_warn(&vsi->back->pdev->dev,
2416 				 "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2417 				 i40e_aq_str(hw, aq_status), vsi_name,
2418 					     vsi->type);
2419 		}
2420 	}
2421 }
2422 
2423 /**
2424  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2425  * @vsi: pointer to the VSI
2426  * @vsi_name: the VSI name
2427  * @f: filter data
2428  *
2429  * This function sets or clears the promiscuous broadcast flags for VLAN
2430  * filters in order to properly receive broadcast frames. Assumes that only
2431  * broadcast filters are passed.
2432  *
2433  * Returns status indicating success or failure;
2434  **/
2435 static int
2436 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2437 			  struct i40e_mac_filter *f)
2438 {
2439 	bool enable = f->state == I40E_FILTER_NEW;
2440 	struct i40e_hw *hw = &vsi->back->hw;
2441 	int aq_ret;
2442 
2443 	if (f->vlan == I40E_VLAN_ANY) {
2444 		aq_ret = i40e_aq_set_vsi_broadcast(hw,
2445 						   vsi->seid,
2446 						   enable,
2447 						   NULL);
2448 	} else {
2449 		aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2450 							    vsi->seid,
2451 							    enable,
2452 							    f->vlan,
2453 							    NULL);
2454 	}
2455 
2456 	if (aq_ret) {
2457 		set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2458 		dev_warn(&vsi->back->pdev->dev,
2459 			 "Error %s, forcing overflow promiscuous on %s\n",
2460 			 i40e_aq_str(hw, hw->aq.asq_last_status),
2461 			 vsi_name);
2462 	}
2463 
2464 	return aq_ret;
2465 }
2466 
2467 /**
2468  * i40e_set_promiscuous - set promiscuous mode
2469  * @pf: board private structure
2470  * @promisc: promisc on or off
2471  *
2472  * There are different ways of setting promiscuous mode on a PF depending on
2473  * what state/environment we're in.  This identifies and sets it appropriately.
2474  * Returns 0 on success.
2475  **/
2476 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2477 {
2478 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
2479 	struct i40e_hw *hw = &pf->hw;
2480 	int aq_ret;
2481 
2482 	if (vsi->type == I40E_VSI_MAIN &&
2483 	    i40e_pf_get_main_veb(pf) &&
2484 	    !test_bit(I40E_FLAG_MFP_ENA, pf->flags)) {
2485 		/* set defport ON for Main VSI instead of true promisc
2486 		 * this way we will get all unicast/multicast and VLAN
2487 		 * promisc behavior but will not get VF or VMDq traffic
2488 		 * replicated on the Main VSI.
2489 		 */
2490 		if (promisc)
2491 			aq_ret = i40e_aq_set_default_vsi(hw,
2492 							 vsi->seid,
2493 							 NULL);
2494 		else
2495 			aq_ret = i40e_aq_clear_default_vsi(hw,
2496 							   vsi->seid,
2497 							   NULL);
2498 		if (aq_ret) {
2499 			dev_info(&pf->pdev->dev,
2500 				 "Set default VSI failed, err %pe, aq_err %s\n",
2501 				 ERR_PTR(aq_ret),
2502 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2503 		}
2504 	} else {
2505 		aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2506 						  hw,
2507 						  vsi->seid,
2508 						  promisc, NULL,
2509 						  true);
2510 		if (aq_ret) {
2511 			dev_info(&pf->pdev->dev,
2512 				 "set unicast promisc failed, err %pe, aq_err %s\n",
2513 				 ERR_PTR(aq_ret),
2514 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2515 		}
2516 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2517 						  hw,
2518 						  vsi->seid,
2519 						  promisc, NULL);
2520 		if (aq_ret) {
2521 			dev_info(&pf->pdev->dev,
2522 				 "set multicast promisc failed, err %pe, aq_err %s\n",
2523 				 ERR_PTR(aq_ret),
2524 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2525 		}
2526 	}
2527 
2528 	if (!aq_ret)
2529 		pf->cur_promisc = promisc;
2530 
2531 	return aq_ret;
2532 }
2533 
2534 /**
2535  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2536  * @vsi: ptr to the VSI
2537  *
2538  * Push any outstanding VSI filter changes through the AdminQ.
2539  *
2540  * Returns 0 or error value
2541  **/
2542 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2543 {
2544 	struct hlist_head tmp_add_list, tmp_del_list;
2545 	struct i40e_mac_filter *f;
2546 	struct i40e_new_mac_filter *new, *add_head = NULL;
2547 	struct i40e_hw *hw = &vsi->back->hw;
2548 	bool old_overflow, new_overflow;
2549 	unsigned int failed_filters = 0;
2550 	unsigned int vlan_filters = 0;
2551 	char vsi_name[16] = "PF";
2552 	int filter_list_len = 0;
2553 	u32 changed_flags = 0;
2554 	struct hlist_node *h;
2555 	struct i40e_pf *pf;
2556 	int num_add = 0;
2557 	int num_del = 0;
2558 	int aq_ret = 0;
2559 	int retval = 0;
2560 	u16 cmd_flags;
2561 	int list_size;
2562 	int bkt;
2563 
2564 	/* empty array typed pointers, kcalloc later */
2565 	struct i40e_aqc_add_macvlan_element_data *add_list;
2566 	struct i40e_aqc_remove_macvlan_element_data *del_list;
2567 
2568 	while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2569 		usleep_range(1000, 2000);
2570 	pf = vsi->back;
2571 
2572 	old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2573 
2574 	if (vsi->netdev) {
2575 		changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2576 		vsi->current_netdev_flags = vsi->netdev->flags;
2577 	}
2578 
2579 	INIT_HLIST_HEAD(&tmp_add_list);
2580 	INIT_HLIST_HEAD(&tmp_del_list);
2581 
2582 	if (vsi->type == I40E_VSI_SRIOV)
2583 		snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2584 	else if (vsi->type != I40E_VSI_MAIN)
2585 		snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2586 
2587 	if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2588 		vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2589 
2590 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2591 		/* Create a list of filters to delete. */
2592 		hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2593 			if (f->state == I40E_FILTER_REMOVE) {
2594 				/* Move the element into temporary del_list */
2595 				hash_del(&f->hlist);
2596 				hlist_add_head(&f->hlist, &tmp_del_list);
2597 
2598 				/* Avoid counting removed filters */
2599 				continue;
2600 			}
2601 			if (f->state == I40E_FILTER_NEW) {
2602 				/* Create a temporary i40e_new_mac_filter */
2603 				new = kzalloc(sizeof(*new), GFP_ATOMIC);
2604 				if (!new)
2605 					goto err_no_memory_locked;
2606 
2607 				/* Store pointer to the real filter */
2608 				new->f = f;
2609 				new->state = f->state;
2610 
2611 				/* Add it to the hash list */
2612 				hlist_add_head(&new->hlist, &tmp_add_list);
2613 			}
2614 
2615 			/* Count the number of active (current and new) VLAN
2616 			 * filters we have now. Does not count filters which
2617 			 * are marked for deletion.
2618 			 */
2619 			if (f->vlan > 0)
2620 				vlan_filters++;
2621 		}
2622 
2623 		if (vsi->type != I40E_VSI_SRIOV)
2624 			retval = i40e_correct_mac_vlan_filters
2625 				(vsi, &tmp_add_list, &tmp_del_list,
2626 				 vlan_filters);
2627 		else if (pf->vf)
2628 			retval = i40e_correct_vf_mac_vlan_filters
2629 				(vsi, &tmp_add_list, &tmp_del_list,
2630 				 vlan_filters, pf->vf[vsi->vf_id].trusted);
2631 
2632 		hlist_for_each_entry(new, &tmp_add_list, hlist)
2633 			netdev_hw_addr_refcnt(new->f, vsi->netdev, 1);
2634 
2635 		if (retval)
2636 			goto err_no_memory_locked;
2637 
2638 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2639 	}
2640 
2641 	/* Now process 'del_list' outside the lock */
2642 	if (!hlist_empty(&tmp_del_list)) {
2643 		filter_list_len = hw->aq.asq_buf_size /
2644 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2645 		list_size = filter_list_len *
2646 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2647 		del_list = kzalloc(list_size, GFP_ATOMIC);
2648 		if (!del_list)
2649 			goto err_no_memory;
2650 
2651 		hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2652 			cmd_flags = 0;
2653 
2654 			/* handle broadcast filters by updating the broadcast
2655 			 * promiscuous flag and release filter list.
2656 			 */
2657 			if (is_broadcast_ether_addr(f->macaddr)) {
2658 				i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2659 
2660 				hlist_del(&f->hlist);
2661 				kfree(f);
2662 				continue;
2663 			}
2664 
2665 			/* add to delete list */
2666 			ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2667 			if (f->vlan == I40E_VLAN_ANY) {
2668 				del_list[num_del].vlan_tag = 0;
2669 				cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2670 			} else {
2671 				del_list[num_del].vlan_tag =
2672 					cpu_to_le16((u16)(f->vlan));
2673 			}
2674 
2675 			cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2676 			del_list[num_del].flags = cmd_flags;
2677 			num_del++;
2678 
2679 			/* flush a full buffer */
2680 			if (num_del == filter_list_len) {
2681 				i40e_aqc_del_filters(vsi, vsi_name, del_list,
2682 						     num_del, &retval);
2683 				memset(del_list, 0, list_size);
2684 				num_del = 0;
2685 			}
2686 			/* Release memory for MAC filter entries which were
2687 			 * synced up with HW.
2688 			 */
2689 			hlist_del(&f->hlist);
2690 			kfree(f);
2691 		}
2692 
2693 		if (num_del) {
2694 			i40e_aqc_del_filters(vsi, vsi_name, del_list,
2695 					     num_del, &retval);
2696 		}
2697 
2698 		kfree(del_list);
2699 		del_list = NULL;
2700 	}
2701 
2702 	if (!hlist_empty(&tmp_add_list)) {
2703 		/* Do all the adds now. */
2704 		filter_list_len = hw->aq.asq_buf_size /
2705 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2706 		list_size = filter_list_len *
2707 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2708 		add_list = kzalloc(list_size, GFP_ATOMIC);
2709 		if (!add_list)
2710 			goto err_no_memory;
2711 
2712 		num_add = 0;
2713 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2714 			/* handle broadcast filters by updating the broadcast
2715 			 * promiscuous flag instead of adding a MAC filter.
2716 			 */
2717 			if (is_broadcast_ether_addr(new->f->macaddr)) {
2718 				if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2719 							      new->f))
2720 					new->state = I40E_FILTER_FAILED;
2721 				else
2722 					new->state = I40E_FILTER_ACTIVE;
2723 				continue;
2724 			}
2725 
2726 			/* add to add array */
2727 			if (num_add == 0)
2728 				add_head = new;
2729 			cmd_flags = 0;
2730 			ether_addr_copy(add_list[num_add].mac_addr,
2731 					new->f->macaddr);
2732 			if (new->f->vlan == I40E_VLAN_ANY) {
2733 				add_list[num_add].vlan_tag = 0;
2734 				cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2735 			} else {
2736 				add_list[num_add].vlan_tag =
2737 					cpu_to_le16((u16)(new->f->vlan));
2738 			}
2739 			add_list[num_add].queue_number = 0;
2740 			/* set invalid match method for later detection */
2741 			add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2742 			cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2743 			add_list[num_add].flags = cpu_to_le16(cmd_flags);
2744 			num_add++;
2745 
2746 			/* flush a full buffer */
2747 			if (num_add == filter_list_len) {
2748 				i40e_aqc_add_filters(vsi, vsi_name, add_list,
2749 						     add_head, num_add);
2750 				memset(add_list, 0, list_size);
2751 				num_add = 0;
2752 			}
2753 		}
2754 		if (num_add) {
2755 			i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2756 					     num_add);
2757 		}
2758 		/* Now move all of the filters from the temp add list back to
2759 		 * the VSI's list.
2760 		 */
2761 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2762 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2763 			/* Only update the state if we're still NEW */
2764 			if (new->f->state == I40E_FILTER_NEW)
2765 				new->f->state = new->state;
2766 			hlist_del(&new->hlist);
2767 			netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2768 			kfree(new);
2769 		}
2770 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2771 		kfree(add_list);
2772 		add_list = NULL;
2773 	}
2774 
2775 	/* Determine the number of active and failed filters. */
2776 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2777 	vsi->active_filters = 0;
2778 	hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2779 		if (f->state == I40E_FILTER_ACTIVE)
2780 			vsi->active_filters++;
2781 		else if (f->state == I40E_FILTER_FAILED)
2782 			failed_filters++;
2783 	}
2784 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2785 
2786 	/* Check if we are able to exit overflow promiscuous mode. We can
2787 	 * safely exit if we didn't just enter, we no longer have any failed
2788 	 * filters, and we have reduced filters below the threshold value.
2789 	 */
2790 	if (old_overflow && !failed_filters &&
2791 	    vsi->active_filters < vsi->promisc_threshold) {
2792 		dev_info(&pf->pdev->dev,
2793 			 "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2794 			 vsi_name);
2795 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2796 		vsi->promisc_threshold = 0;
2797 	}
2798 
2799 	/* if the VF is not trusted do not do promisc */
2800 	if (vsi->type == I40E_VSI_SRIOV && pf->vf &&
2801 	    !pf->vf[vsi->vf_id].trusted) {
2802 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2803 		goto out;
2804 	}
2805 
2806 	new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2807 
2808 	/* If we are entering overflow promiscuous, we need to calculate a new
2809 	 * threshold for when we are safe to exit
2810 	 */
2811 	if (!old_overflow && new_overflow)
2812 		vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2813 
2814 	/* check for changes in promiscuous modes */
2815 	if (changed_flags & IFF_ALLMULTI) {
2816 		bool cur_multipromisc;
2817 
2818 		cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2819 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2820 							       vsi->seid,
2821 							       cur_multipromisc,
2822 							       NULL);
2823 		if (aq_ret) {
2824 			retval = i40e_aq_rc_to_posix(aq_ret,
2825 						     hw->aq.asq_last_status);
2826 			dev_info(&pf->pdev->dev,
2827 				 "set multi promisc failed on %s, err %pe aq_err %s\n",
2828 				 vsi_name,
2829 				 ERR_PTR(aq_ret),
2830 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2831 		} else {
2832 			dev_info(&pf->pdev->dev, "%s allmulti mode.\n",
2833 				 cur_multipromisc ? "entering" : "leaving");
2834 		}
2835 	}
2836 
2837 	if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2838 		bool cur_promisc;
2839 
2840 		cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2841 			       new_overflow);
2842 		aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2843 		if (aq_ret) {
2844 			retval = i40e_aq_rc_to_posix(aq_ret,
2845 						     hw->aq.asq_last_status);
2846 			dev_info(&pf->pdev->dev,
2847 				 "Setting promiscuous %s failed on %s, err %pe aq_err %s\n",
2848 				 cur_promisc ? "on" : "off",
2849 				 vsi_name,
2850 				 ERR_PTR(aq_ret),
2851 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2852 		}
2853 	}
2854 out:
2855 	/* if something went wrong then set the changed flag so we try again */
2856 	if (retval)
2857 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2858 
2859 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2860 	return retval;
2861 
2862 err_no_memory:
2863 	/* Restore elements on the temporary add and delete lists */
2864 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2865 err_no_memory_locked:
2866 	i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2867 	i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2868 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2869 
2870 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2871 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2872 	return -ENOMEM;
2873 }
2874 
2875 /**
2876  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2877  * @pf: board private structure
2878  **/
2879 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2880 {
2881 	struct i40e_vsi *vsi;
2882 	int v;
2883 
2884 	if (!pf)
2885 		return;
2886 	if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2887 		return;
2888 	if (test_bit(__I40E_VF_DISABLE, pf->state)) {
2889 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
2890 		return;
2891 	}
2892 
2893 	i40e_pf_for_each_vsi(pf, v, vsi) {
2894 		if ((vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) &&
2895 		    !test_bit(__I40E_VSI_RELEASING, vsi->state)) {
2896 			int ret = i40e_sync_vsi_filters(vsi);
2897 
2898 			if (ret) {
2899 				/* come back and try again later */
2900 				set_bit(__I40E_MACVLAN_SYNC_PENDING,
2901 					pf->state);
2902 				break;
2903 			}
2904 		}
2905 	}
2906 }
2907 
2908 /**
2909  * i40e_calculate_vsi_rx_buf_len - Calculates buffer length
2910  *
2911  * @vsi: VSI to calculate rx_buf_len from
2912  */
2913 static u16 i40e_calculate_vsi_rx_buf_len(struct i40e_vsi *vsi)
2914 {
2915 	if (!vsi->netdev || test_bit(I40E_FLAG_LEGACY_RX_ENA, vsi->back->flags))
2916 		return SKB_WITH_OVERHEAD(I40E_RXBUFFER_2048);
2917 
2918 	return PAGE_SIZE < 8192 ? I40E_RXBUFFER_3072 : I40E_RXBUFFER_2048;
2919 }
2920 
2921 /**
2922  * i40e_max_vsi_frame_size - returns the maximum allowed frame size for VSI
2923  * @vsi: the vsi
2924  * @xdp_prog: XDP program
2925  **/
2926 static int i40e_max_vsi_frame_size(struct i40e_vsi *vsi,
2927 				   struct bpf_prog *xdp_prog)
2928 {
2929 	u16 rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
2930 	u16 chain_len;
2931 
2932 	if (xdp_prog && !xdp_prog->aux->xdp_has_frags)
2933 		chain_len = 1;
2934 	else
2935 		chain_len = I40E_MAX_CHAINED_RX_BUFFERS;
2936 
2937 	return min_t(u16, rx_buf_len * chain_len, I40E_MAX_RXBUFFER);
2938 }
2939 
2940 /**
2941  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2942  * @netdev: network interface device structure
2943  * @new_mtu: new value for maximum frame size
2944  *
2945  * Returns 0 on success, negative on failure
2946  **/
2947 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2948 {
2949 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2950 	struct i40e_vsi *vsi = np->vsi;
2951 	struct i40e_pf *pf = vsi->back;
2952 	int frame_size;
2953 
2954 	frame_size = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
2955 	if (new_mtu > frame_size - I40E_PACKET_HDR_PAD) {
2956 		netdev_err(netdev, "Error changing mtu to %d, Max is %d\n",
2957 			   new_mtu, frame_size - I40E_PACKET_HDR_PAD);
2958 		return -EINVAL;
2959 	}
2960 
2961 	netdev_dbg(netdev, "changing MTU from %d to %d\n",
2962 		   netdev->mtu, new_mtu);
2963 	WRITE_ONCE(netdev->mtu, new_mtu);
2964 	if (netif_running(netdev))
2965 		i40e_vsi_reinit_locked(vsi);
2966 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2967 	set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2968 	return 0;
2969 }
2970 
2971 /**
2972  * i40e_ioctl - Access the hwtstamp interface
2973  * @netdev: network interface device structure
2974  * @ifr: interface request data
2975  * @cmd: ioctl command
2976  **/
2977 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2978 {
2979 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2980 	struct i40e_pf *pf = np->vsi->back;
2981 
2982 	switch (cmd) {
2983 	case SIOCGHWTSTAMP:
2984 		return i40e_ptp_get_ts_config(pf, ifr);
2985 	case SIOCSHWTSTAMP:
2986 		return i40e_ptp_set_ts_config(pf, ifr);
2987 	default:
2988 		return -EOPNOTSUPP;
2989 	}
2990 }
2991 
2992 /**
2993  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2994  * @vsi: the vsi being adjusted
2995  **/
2996 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2997 {
2998 	struct i40e_vsi_context ctxt;
2999 	int ret;
3000 
3001 	/* Don't modify stripping options if a port VLAN is active */
3002 	if (vsi->info.pvid)
3003 		return;
3004 
3005 	if ((vsi->info.valid_sections &
3006 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
3007 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
3008 		return;  /* already enabled */
3009 
3010 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3011 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3012 				    I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
3013 
3014 	ctxt.seid = vsi->seid;
3015 	ctxt.info = vsi->info;
3016 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3017 	if (ret) {
3018 		dev_info(&vsi->back->pdev->dev,
3019 			 "update vlan stripping failed, err %pe aq_err %s\n",
3020 			 ERR_PTR(ret),
3021 			 i40e_aq_str(&vsi->back->hw,
3022 				     vsi->back->hw.aq.asq_last_status));
3023 	}
3024 }
3025 
3026 /**
3027  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
3028  * @vsi: the vsi being adjusted
3029  **/
3030 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
3031 {
3032 	struct i40e_vsi_context ctxt;
3033 	int ret;
3034 
3035 	/* Don't modify stripping options if a port VLAN is active */
3036 	if (vsi->info.pvid)
3037 		return;
3038 
3039 	if ((vsi->info.valid_sections &
3040 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
3041 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
3042 	     I40E_AQ_VSI_PVLAN_EMOD_MASK))
3043 		return;  /* already disabled */
3044 
3045 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3046 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3047 				    I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
3048 
3049 	ctxt.seid = vsi->seid;
3050 	ctxt.info = vsi->info;
3051 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3052 	if (ret) {
3053 		dev_info(&vsi->back->pdev->dev,
3054 			 "update vlan stripping failed, err %pe aq_err %s\n",
3055 			 ERR_PTR(ret),
3056 			 i40e_aq_str(&vsi->back->hw,
3057 				     vsi->back->hw.aq.asq_last_status));
3058 	}
3059 }
3060 
3061 /**
3062  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
3063  * @vsi: the vsi being configured
3064  * @vid: vlan id to be added (0 = untagged only , -1 = any)
3065  *
3066  * This is a helper function for adding a new MAC/VLAN filter with the
3067  * specified VLAN for each existing MAC address already in the hash table.
3068  * This function does *not* perform any accounting to update filters based on
3069  * VLAN mode.
3070  *
3071  * NOTE: this function expects to be called while under the
3072  * mac_filter_hash_lock
3073  **/
3074 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3075 {
3076 	struct i40e_mac_filter *f, *add_f;
3077 	struct hlist_node *h;
3078 	int bkt;
3079 
3080 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3081 		/* If we're asked to add a filter that has been marked for
3082 		 * removal, it is safe to simply restore it to active state.
3083 		 * __i40e_del_filter will have simply deleted any filters which
3084 		 * were previously marked NEW or FAILED, so if it is currently
3085 		 * marked REMOVE it must have previously been ACTIVE. Since we
3086 		 * haven't yet run the sync filters task, just restore this
3087 		 * filter to the ACTIVE state so that the sync task leaves it
3088 		 * in place.
3089 		 */
3090 		if (f->state == I40E_FILTER_REMOVE && f->vlan == vid) {
3091 			f->state = I40E_FILTER_ACTIVE;
3092 			continue;
3093 		} else if (f->state == I40E_FILTER_REMOVE) {
3094 			continue;
3095 		}
3096 		add_f = i40e_add_filter(vsi, f->macaddr, vid);
3097 		if (!add_f) {
3098 			dev_info(&vsi->back->pdev->dev,
3099 				 "Could not add vlan filter %d for %pM\n",
3100 				 vid, f->macaddr);
3101 			return -ENOMEM;
3102 		}
3103 	}
3104 
3105 	return 0;
3106 }
3107 
3108 /**
3109  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
3110  * @vsi: the VSI being configured
3111  * @vid: VLAN id to be added
3112  **/
3113 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
3114 {
3115 	int err;
3116 
3117 	if (vsi->info.pvid)
3118 		return -EINVAL;
3119 
3120 	/* The network stack will attempt to add VID=0, with the intention to
3121 	 * receive priority tagged packets with a VLAN of 0. Our HW receives
3122 	 * these packets by default when configured to receive untagged
3123 	 * packets, so we don't need to add a filter for this case.
3124 	 * Additionally, HW interprets adding a VID=0 filter as meaning to
3125 	 * receive *only* tagged traffic and stops receiving untagged traffic.
3126 	 * Thus, we do not want to actually add a filter for VID=0
3127 	 */
3128 	if (!vid)
3129 		return 0;
3130 
3131 	/* Locked once because all functions invoked below iterates list*/
3132 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3133 	err = i40e_add_vlan_all_mac(vsi, vid);
3134 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3135 	if (err)
3136 		return err;
3137 
3138 	/* schedule our worker thread which will take care of
3139 	 * applying the new filter changes
3140 	 */
3141 	i40e_service_event_schedule(vsi->back);
3142 	return 0;
3143 }
3144 
3145 /**
3146  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
3147  * @vsi: the vsi being configured
3148  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
3149  *
3150  * This function should be used to remove all VLAN filters which match the
3151  * given VID. It does not schedule the service event and does not take the
3152  * mac_filter_hash_lock so it may be combined with other operations under
3153  * a single invocation of the mac_filter_hash_lock.
3154  *
3155  * NOTE: this function expects to be called while under the
3156  * mac_filter_hash_lock
3157  */
3158 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3159 {
3160 	struct i40e_mac_filter *f;
3161 	struct hlist_node *h;
3162 	int bkt;
3163 
3164 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3165 		if (f->vlan == vid)
3166 			__i40e_del_filter(vsi, f);
3167 	}
3168 }
3169 
3170 /**
3171  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
3172  * @vsi: the VSI being configured
3173  * @vid: VLAN id to be removed
3174  **/
3175 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
3176 {
3177 	if (!vid || vsi->info.pvid)
3178 		return;
3179 
3180 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3181 	i40e_rm_vlan_all_mac(vsi, vid);
3182 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3183 
3184 	/* schedule our worker thread which will take care of
3185 	 * applying the new filter changes
3186 	 */
3187 	i40e_service_event_schedule(vsi->back);
3188 }
3189 
3190 /**
3191  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
3192  * @netdev: network interface to be adjusted
3193  * @proto: unused protocol value
3194  * @vid: vlan id to be added
3195  *
3196  * net_device_ops implementation for adding vlan ids
3197  **/
3198 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
3199 				__always_unused __be16 proto, u16 vid)
3200 {
3201 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3202 	struct i40e_vsi *vsi = np->vsi;
3203 	int ret = 0;
3204 
3205 	if (vid >= VLAN_N_VID)
3206 		return -EINVAL;
3207 
3208 	ret = i40e_vsi_add_vlan(vsi, vid);
3209 	if (!ret)
3210 		set_bit(vid, vsi->active_vlans);
3211 
3212 	return ret;
3213 }
3214 
3215 /**
3216  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
3217  * @netdev: network interface to be adjusted
3218  * @proto: unused protocol value
3219  * @vid: vlan id to be added
3220  **/
3221 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
3222 				    __always_unused __be16 proto, u16 vid)
3223 {
3224 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3225 	struct i40e_vsi *vsi = np->vsi;
3226 
3227 	if (vid >= VLAN_N_VID)
3228 		return;
3229 	set_bit(vid, vsi->active_vlans);
3230 }
3231 
3232 /**
3233  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
3234  * @netdev: network interface to be adjusted
3235  * @proto: unused protocol value
3236  * @vid: vlan id to be removed
3237  *
3238  * net_device_ops implementation for removing vlan ids
3239  **/
3240 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
3241 				 __always_unused __be16 proto, u16 vid)
3242 {
3243 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3244 	struct i40e_vsi *vsi = np->vsi;
3245 
3246 	/* return code is ignored as there is nothing a user
3247 	 * can do about failure to remove and a log message was
3248 	 * already printed from the other function
3249 	 */
3250 	i40e_vsi_kill_vlan(vsi, vid);
3251 
3252 	clear_bit(vid, vsi->active_vlans);
3253 
3254 	return 0;
3255 }
3256 
3257 /**
3258  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
3259  * @vsi: the vsi being brought back up
3260  **/
3261 static void i40e_restore_vlan(struct i40e_vsi *vsi)
3262 {
3263 	u16 vid;
3264 
3265 	if (!vsi->netdev)
3266 		return;
3267 
3268 	if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
3269 		i40e_vlan_stripping_enable(vsi);
3270 	else
3271 		i40e_vlan_stripping_disable(vsi);
3272 
3273 	for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
3274 		i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
3275 					vid);
3276 }
3277 
3278 /**
3279  * i40e_vsi_add_pvid - Add pvid for the VSI
3280  * @vsi: the vsi being adjusted
3281  * @vid: the vlan id to set as a PVID
3282  **/
3283 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
3284 {
3285 	struct i40e_vsi_context ctxt;
3286 	int ret;
3287 
3288 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3289 	vsi->info.pvid = cpu_to_le16(vid);
3290 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
3291 				    I40E_AQ_VSI_PVLAN_INSERT_PVID |
3292 				    I40E_AQ_VSI_PVLAN_EMOD_STR;
3293 
3294 	ctxt.seid = vsi->seid;
3295 	ctxt.info = vsi->info;
3296 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3297 	if (ret) {
3298 		dev_info(&vsi->back->pdev->dev,
3299 			 "add pvid failed, err %pe aq_err %s\n",
3300 			 ERR_PTR(ret),
3301 			 i40e_aq_str(&vsi->back->hw,
3302 				     vsi->back->hw.aq.asq_last_status));
3303 		return -ENOENT;
3304 	}
3305 
3306 	return 0;
3307 }
3308 
3309 /**
3310  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
3311  * @vsi: the vsi being adjusted
3312  *
3313  * Just use the vlan_rx_register() service to put it back to normal
3314  **/
3315 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
3316 {
3317 	vsi->info.pvid = 0;
3318 
3319 	i40e_vlan_stripping_disable(vsi);
3320 }
3321 
3322 /**
3323  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
3324  * @vsi: ptr to the VSI
3325  *
3326  * If this function returns with an error, then it's possible one or
3327  * more of the rings is populated (while the rest are not).  It is the
3328  * callers duty to clean those orphaned rings.
3329  *
3330  * Return 0 on success, negative on failure
3331  **/
3332 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3333 {
3334 	int i, err = 0;
3335 
3336 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3337 		err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3338 
3339 	if (!i40e_enabled_xdp_vsi(vsi))
3340 		return err;
3341 
3342 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3343 		err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3344 
3345 	return err;
3346 }
3347 
3348 /**
3349  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3350  * @vsi: ptr to the VSI
3351  *
3352  * Free VSI's transmit software resources
3353  **/
3354 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3355 {
3356 	int i;
3357 
3358 	if (vsi->tx_rings) {
3359 		for (i = 0; i < vsi->num_queue_pairs; i++)
3360 			if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3361 				i40e_free_tx_resources(vsi->tx_rings[i]);
3362 	}
3363 
3364 	if (vsi->xdp_rings) {
3365 		for (i = 0; i < vsi->num_queue_pairs; i++)
3366 			if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3367 				i40e_free_tx_resources(vsi->xdp_rings[i]);
3368 	}
3369 }
3370 
3371 /**
3372  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3373  * @vsi: ptr to the VSI
3374  *
3375  * If this function returns with an error, then it's possible one or
3376  * more of the rings is populated (while the rest are not).  It is the
3377  * callers duty to clean those orphaned rings.
3378  *
3379  * Return 0 on success, negative on failure
3380  **/
3381 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3382 {
3383 	int i, err = 0;
3384 
3385 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3386 		err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3387 	return err;
3388 }
3389 
3390 /**
3391  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3392  * @vsi: ptr to the VSI
3393  *
3394  * Free all receive software resources
3395  **/
3396 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3397 {
3398 	int i;
3399 
3400 	if (!vsi->rx_rings)
3401 		return;
3402 
3403 	for (i = 0; i < vsi->num_queue_pairs; i++)
3404 		if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3405 			i40e_free_rx_resources(vsi->rx_rings[i]);
3406 }
3407 
3408 /**
3409  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3410  * @ring: The Tx ring to configure
3411  *
3412  * This enables/disables XPS for a given Tx descriptor ring
3413  * based on the TCs enabled for the VSI that ring belongs to.
3414  **/
3415 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3416 {
3417 	int cpu;
3418 
3419 	if (!ring->q_vector || !ring->netdev || ring->ch)
3420 		return;
3421 
3422 	/* We only initialize XPS once, so as not to overwrite user settings */
3423 	if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3424 		return;
3425 
3426 	cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3427 	netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3428 			    ring->queue_index);
3429 }
3430 
3431 /**
3432  * i40e_xsk_pool - Retrieve the AF_XDP buffer pool if XDP and ZC is enabled
3433  * @ring: The Tx or Rx ring
3434  *
3435  * Returns the AF_XDP buffer pool or NULL.
3436  **/
3437 static struct xsk_buff_pool *i40e_xsk_pool(struct i40e_ring *ring)
3438 {
3439 	bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3440 	int qid = ring->queue_index;
3441 
3442 	if (ring_is_xdp(ring))
3443 		qid -= ring->vsi->alloc_queue_pairs;
3444 
3445 	if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3446 		return NULL;
3447 
3448 	return xsk_get_pool_from_qid(ring->vsi->netdev, qid);
3449 }
3450 
3451 /**
3452  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3453  * @ring: The Tx ring to configure
3454  *
3455  * Configure the Tx descriptor ring in the HMC context.
3456  **/
3457 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3458 {
3459 	struct i40e_vsi *vsi = ring->vsi;
3460 	u16 pf_q = vsi->base_queue + ring->queue_index;
3461 	struct i40e_hw *hw = &vsi->back->hw;
3462 	struct i40e_hmc_obj_txq tx_ctx;
3463 	u32 qtx_ctl = 0;
3464 	int err = 0;
3465 
3466 	if (ring_is_xdp(ring))
3467 		ring->xsk_pool = i40e_xsk_pool(ring);
3468 
3469 	/* some ATR related tx ring init */
3470 	if (test_bit(I40E_FLAG_FD_ATR_ENA, vsi->back->flags)) {
3471 		ring->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
3472 		ring->atr_count = 0;
3473 	} else {
3474 		ring->atr_sample_rate = 0;
3475 	}
3476 
3477 	/* configure XPS */
3478 	i40e_config_xps_tx_ring(ring);
3479 
3480 	/* clear the context structure first */
3481 	memset(&tx_ctx, 0, sizeof(tx_ctx));
3482 
3483 	tx_ctx.new_context = 1;
3484 	tx_ctx.base = (ring->dma / 128);
3485 	tx_ctx.qlen = ring->count;
3486 	if (test_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags) ||
3487 	    test_bit(I40E_FLAG_FD_ATR_ENA, vsi->back->flags))
3488 		tx_ctx.fd_ena = 1;
3489 	if (test_bit(I40E_FLAG_PTP_ENA, vsi->back->flags))
3490 		tx_ctx.timesync_ena = 1;
3491 	/* FDIR VSI tx ring can still use RS bit and writebacks */
3492 	if (vsi->type != I40E_VSI_FDIR)
3493 		tx_ctx.head_wb_ena = 1;
3494 	tx_ctx.head_wb_addr = ring->dma +
3495 			      (ring->count * sizeof(struct i40e_tx_desc));
3496 
3497 	/* As part of VSI creation/update, FW allocates certain
3498 	 * Tx arbitration queue sets for each TC enabled for
3499 	 * the VSI. The FW returns the handles to these queue
3500 	 * sets as part of the response buffer to Add VSI,
3501 	 * Update VSI, etc. AQ commands. It is expected that
3502 	 * these queue set handles be associated with the Tx
3503 	 * queues by the driver as part of the TX queue context
3504 	 * initialization. This has to be done regardless of
3505 	 * DCB as by default everything is mapped to TC0.
3506 	 */
3507 
3508 	if (ring->ch)
3509 		tx_ctx.rdylist =
3510 			le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3511 
3512 	else
3513 		tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3514 
3515 	tx_ctx.rdylist_act = 0;
3516 
3517 	/* clear the context in the HMC */
3518 	err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3519 	if (err) {
3520 		dev_info(&vsi->back->pdev->dev,
3521 			 "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3522 			 ring->queue_index, pf_q, err);
3523 		return -ENOMEM;
3524 	}
3525 
3526 	/* set the context in the HMC */
3527 	err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3528 	if (err) {
3529 		dev_info(&vsi->back->pdev->dev,
3530 			 "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3531 			 ring->queue_index, pf_q, err);
3532 		return -ENOMEM;
3533 	}
3534 
3535 	/* Now associate this queue with this PCI function */
3536 	if (ring->ch) {
3537 		if (ring->ch->type == I40E_VSI_VMDQ2)
3538 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3539 		else
3540 			return -EINVAL;
3541 
3542 		qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_VFVM_INDX_MASK,
3543 				      ring->ch->vsi_number);
3544 	} else {
3545 		if (vsi->type == I40E_VSI_VMDQ2) {
3546 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3547 			qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_VFVM_INDX_MASK,
3548 					      vsi->id);
3549 		} else {
3550 			qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3551 		}
3552 	}
3553 
3554 	qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_PF_INDX_MASK, hw->pf_id);
3555 	wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3556 	i40e_flush(hw);
3557 
3558 	/* cache tail off for easier writes later */
3559 	ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3560 
3561 	return 0;
3562 }
3563 
3564 /**
3565  * i40e_rx_offset - Return expected offset into page to access data
3566  * @rx_ring: Ring we are requesting offset of
3567  *
3568  * Returns the offset value for ring into the data buffer.
3569  */
3570 static unsigned int i40e_rx_offset(struct i40e_ring *rx_ring)
3571 {
3572 	return ring_uses_build_skb(rx_ring) ? I40E_SKB_PAD : 0;
3573 }
3574 
3575 /**
3576  * i40e_configure_rx_ring - Configure a receive ring context
3577  * @ring: The Rx ring to configure
3578  *
3579  * Configure the Rx descriptor ring in the HMC context.
3580  **/
3581 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3582 {
3583 	struct i40e_vsi *vsi = ring->vsi;
3584 	u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3585 	u16 pf_q = vsi->base_queue + ring->queue_index;
3586 	struct i40e_hw *hw = &vsi->back->hw;
3587 	struct i40e_hmc_obj_rxq rx_ctx;
3588 	int err = 0;
3589 	bool ok;
3590 
3591 	bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3592 
3593 	/* clear the context structure first */
3594 	memset(&rx_ctx, 0, sizeof(rx_ctx));
3595 
3596 	ring->rx_buf_len = vsi->rx_buf_len;
3597 
3598 	/* XDP RX-queue info only needed for RX rings exposed to XDP */
3599 	if (ring->vsi->type != I40E_VSI_MAIN)
3600 		goto skip;
3601 
3602 	if (!xdp_rxq_info_is_reg(&ring->xdp_rxq)) {
3603 		err = __xdp_rxq_info_reg(&ring->xdp_rxq, ring->netdev,
3604 					 ring->queue_index,
3605 					 ring->q_vector->napi.napi_id,
3606 					 ring->rx_buf_len);
3607 		if (err)
3608 			return err;
3609 	}
3610 
3611 	ring->xsk_pool = i40e_xsk_pool(ring);
3612 	if (ring->xsk_pool) {
3613 		xdp_rxq_info_unreg(&ring->xdp_rxq);
3614 		ring->rx_buf_len = xsk_pool_get_rx_frame_size(ring->xsk_pool);
3615 		err = __xdp_rxq_info_reg(&ring->xdp_rxq, ring->netdev,
3616 					 ring->queue_index,
3617 					 ring->q_vector->napi.napi_id,
3618 					 ring->rx_buf_len);
3619 		if (err)
3620 			return err;
3621 		err = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3622 						 MEM_TYPE_XSK_BUFF_POOL,
3623 						 NULL);
3624 		if (err)
3625 			return err;
3626 		dev_info(&vsi->back->pdev->dev,
3627 			 "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n",
3628 			 ring->queue_index);
3629 
3630 	} else {
3631 		err = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3632 						 MEM_TYPE_PAGE_SHARED,
3633 						 NULL);
3634 		if (err)
3635 			return err;
3636 	}
3637 
3638 skip:
3639 	xdp_init_buff(&ring->xdp, i40e_rx_pg_size(ring) / 2, &ring->xdp_rxq);
3640 
3641 	rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3642 				    BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3643 
3644 	rx_ctx.base = (ring->dma / 128);
3645 	rx_ctx.qlen = ring->count;
3646 
3647 	/* use 16 byte descriptors */
3648 	rx_ctx.dsize = 0;
3649 
3650 	/* descriptor type is always zero
3651 	 * rx_ctx.dtype = 0;
3652 	 */
3653 	rx_ctx.hsplit_0 = 0;
3654 
3655 	rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3656 	if (hw->revision_id == 0)
3657 		rx_ctx.lrxqthresh = 0;
3658 	else
3659 		rx_ctx.lrxqthresh = 1;
3660 	rx_ctx.crcstrip = 1;
3661 	rx_ctx.l2tsel = 1;
3662 	/* this controls whether VLAN is stripped from inner headers */
3663 	rx_ctx.showiv = 0;
3664 	/* set the prefena field to 1 because the manual says to */
3665 	rx_ctx.prefena = 1;
3666 
3667 	/* clear the context in the HMC */
3668 	err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3669 	if (err) {
3670 		dev_info(&vsi->back->pdev->dev,
3671 			 "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3672 			 ring->queue_index, pf_q, err);
3673 		return -ENOMEM;
3674 	}
3675 
3676 	/* set the context in the HMC */
3677 	err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3678 	if (err) {
3679 		dev_info(&vsi->back->pdev->dev,
3680 			 "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3681 			 ring->queue_index, pf_q, err);
3682 		return -ENOMEM;
3683 	}
3684 
3685 	/* configure Rx buffer alignment */
3686 	if (!vsi->netdev || test_bit(I40E_FLAG_LEGACY_RX_ENA, vsi->back->flags)) {
3687 		if (I40E_2K_TOO_SMALL_WITH_PADDING) {
3688 			dev_info(&vsi->back->pdev->dev,
3689 				 "2k Rx buffer is too small to fit standard MTU and skb_shared_info\n");
3690 			return -EOPNOTSUPP;
3691 		}
3692 		clear_ring_build_skb_enabled(ring);
3693 	} else {
3694 		set_ring_build_skb_enabled(ring);
3695 	}
3696 
3697 	ring->rx_offset = i40e_rx_offset(ring);
3698 
3699 	/* cache tail for quicker writes, and clear the reg before use */
3700 	ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3701 	writel(0, ring->tail);
3702 
3703 	if (ring->xsk_pool) {
3704 		xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
3705 		ok = i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring));
3706 	} else {
3707 		ok = !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3708 	}
3709 	if (!ok) {
3710 		/* Log this in case the user has forgotten to give the kernel
3711 		 * any buffers, even later in the application.
3712 		 */
3713 		dev_info(&vsi->back->pdev->dev,
3714 			 "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3715 			 ring->xsk_pool ? "AF_XDP ZC enabled " : "",
3716 			 ring->queue_index, pf_q);
3717 	}
3718 
3719 	return 0;
3720 }
3721 
3722 /**
3723  * i40e_vsi_configure_tx - Configure the VSI for Tx
3724  * @vsi: VSI structure describing this set of rings and resources
3725  *
3726  * Configure the Tx VSI for operation.
3727  **/
3728 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3729 {
3730 	int err = 0;
3731 	u16 i;
3732 
3733 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3734 		err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3735 
3736 	if (err || !i40e_enabled_xdp_vsi(vsi))
3737 		return err;
3738 
3739 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3740 		err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3741 
3742 	return err;
3743 }
3744 
3745 /**
3746  * i40e_vsi_configure_rx - Configure the VSI for Rx
3747  * @vsi: the VSI being configured
3748  *
3749  * Configure the Rx VSI for operation.
3750  **/
3751 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3752 {
3753 	int err = 0;
3754 	u16 i;
3755 
3756 	vsi->max_frame = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
3757 	vsi->rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
3758 
3759 #if (PAGE_SIZE < 8192)
3760 	if (vsi->netdev && !I40E_2K_TOO_SMALL_WITH_PADDING &&
3761 	    vsi->netdev->mtu <= ETH_DATA_LEN) {
3762 		vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3763 		vsi->max_frame = vsi->rx_buf_len;
3764 	}
3765 #endif
3766 
3767 	/* set up individual rings */
3768 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3769 		err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3770 
3771 	return err;
3772 }
3773 
3774 /**
3775  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3776  * @vsi: ptr to the VSI
3777  **/
3778 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3779 {
3780 	struct i40e_ring *tx_ring, *rx_ring;
3781 	u16 qoffset, qcount;
3782 	int i, n;
3783 
3784 	if (!test_bit(I40E_FLAG_DCB_ENA, vsi->back->flags)) {
3785 		/* Reset the TC information */
3786 		for (i = 0; i < vsi->num_queue_pairs; i++) {
3787 			rx_ring = vsi->rx_rings[i];
3788 			tx_ring = vsi->tx_rings[i];
3789 			rx_ring->dcb_tc = 0;
3790 			tx_ring->dcb_tc = 0;
3791 		}
3792 		return;
3793 	}
3794 
3795 	for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3796 		if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3797 			continue;
3798 
3799 		qoffset = vsi->tc_config.tc_info[n].qoffset;
3800 		qcount = vsi->tc_config.tc_info[n].qcount;
3801 		for (i = qoffset; i < (qoffset + qcount); i++) {
3802 			rx_ring = vsi->rx_rings[i];
3803 			tx_ring = vsi->tx_rings[i];
3804 			rx_ring->dcb_tc = n;
3805 			tx_ring->dcb_tc = n;
3806 		}
3807 	}
3808 }
3809 
3810 /**
3811  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3812  * @vsi: ptr to the VSI
3813  **/
3814 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3815 {
3816 	if (vsi->netdev)
3817 		i40e_set_rx_mode(vsi->netdev);
3818 }
3819 
3820 /**
3821  * i40e_reset_fdir_filter_cnt - Reset flow director filter counters
3822  * @pf: Pointer to the targeted PF
3823  *
3824  * Set all flow director counters to 0.
3825  */
3826 static void i40e_reset_fdir_filter_cnt(struct i40e_pf *pf)
3827 {
3828 	pf->fd_tcp4_filter_cnt = 0;
3829 	pf->fd_udp4_filter_cnt = 0;
3830 	pf->fd_sctp4_filter_cnt = 0;
3831 	pf->fd_ip4_filter_cnt = 0;
3832 	pf->fd_tcp6_filter_cnt = 0;
3833 	pf->fd_udp6_filter_cnt = 0;
3834 	pf->fd_sctp6_filter_cnt = 0;
3835 	pf->fd_ip6_filter_cnt = 0;
3836 }
3837 
3838 /**
3839  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3840  * @vsi: Pointer to the targeted VSI
3841  *
3842  * This function replays the hlist on the hw where all the SB Flow Director
3843  * filters were saved.
3844  **/
3845 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3846 {
3847 	struct i40e_fdir_filter *filter;
3848 	struct i40e_pf *pf = vsi->back;
3849 	struct hlist_node *node;
3850 
3851 	if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
3852 		return;
3853 
3854 	/* Reset FDir counters as we're replaying all existing filters */
3855 	i40e_reset_fdir_filter_cnt(pf);
3856 
3857 	hlist_for_each_entry_safe(filter, node,
3858 				  &pf->fdir_filter_list, fdir_node) {
3859 		i40e_add_del_fdir(vsi, filter, true);
3860 	}
3861 }
3862 
3863 /**
3864  * i40e_vsi_configure - Set up the VSI for action
3865  * @vsi: the VSI being configured
3866  **/
3867 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3868 {
3869 	int err;
3870 
3871 	i40e_set_vsi_rx_mode(vsi);
3872 	i40e_restore_vlan(vsi);
3873 	i40e_vsi_config_dcb_rings(vsi);
3874 	err = i40e_vsi_configure_tx(vsi);
3875 	if (!err)
3876 		err = i40e_vsi_configure_rx(vsi);
3877 
3878 	return err;
3879 }
3880 
3881 /**
3882  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3883  * @vsi: the VSI being configured
3884  **/
3885 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3886 {
3887 	bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3888 	struct i40e_pf *pf = vsi->back;
3889 	struct i40e_hw *hw = &pf->hw;
3890 	u16 vector;
3891 	int i, q;
3892 	u32 qp;
3893 
3894 	/* The interrupt indexing is offset by 1 in the PFINT_ITRn
3895 	 * and PFINT_LNKLSTn registers, e.g.:
3896 	 *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3897 	 */
3898 	qp = vsi->base_queue;
3899 	vector = vsi->base_vector;
3900 	for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3901 		struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3902 
3903 		q_vector->rx.next_update = jiffies + 1;
3904 		q_vector->rx.target_itr =
3905 			ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3906 		wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3907 		     q_vector->rx.target_itr >> 1);
3908 		q_vector->rx.current_itr = q_vector->rx.target_itr;
3909 
3910 		q_vector->tx.next_update = jiffies + 1;
3911 		q_vector->tx.target_itr =
3912 			ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3913 		wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3914 		     q_vector->tx.target_itr >> 1);
3915 		q_vector->tx.current_itr = q_vector->tx.target_itr;
3916 
3917 		/* Set ITR for software interrupts triggered after exiting
3918 		 * busy-loop polling.
3919 		 */
3920 		wr32(hw, I40E_PFINT_ITRN(I40E_SW_ITR, vector - 1),
3921 		     I40E_ITR_20K);
3922 
3923 		wr32(hw, I40E_PFINT_RATEN(vector - 1),
3924 		     i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3925 
3926 		/* begin of linked list for RX queue assigned to this vector */
3927 		wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3928 		for (q = 0; q < q_vector->num_ringpairs; q++) {
3929 			u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3930 			u32 val;
3931 
3932 			val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3933 			      (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3934 			      (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3935 			      (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3936 			      (I40E_QUEUE_TYPE_TX <<
3937 			       I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3938 
3939 			wr32(hw, I40E_QINT_RQCTL(qp), val);
3940 
3941 			if (has_xdp) {
3942 				/* TX queue with next queue set to TX */
3943 				val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3944 				      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3945 				      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3946 				      (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3947 				      (I40E_QUEUE_TYPE_TX <<
3948 				       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3949 
3950 				wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3951 			}
3952 			/* TX queue with next RX or end of linked list */
3953 			val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3954 			      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3955 			      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3956 			      ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3957 			      (I40E_QUEUE_TYPE_RX <<
3958 			       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3959 
3960 			/* Terminate the linked list */
3961 			if (q == (q_vector->num_ringpairs - 1))
3962 				val |= (I40E_QUEUE_END_OF_LIST <<
3963 					I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3964 
3965 			wr32(hw, I40E_QINT_TQCTL(qp), val);
3966 			qp++;
3967 		}
3968 	}
3969 
3970 	i40e_flush(hw);
3971 }
3972 
3973 /**
3974  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3975  * @pf: pointer to private device data structure
3976  **/
3977 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3978 {
3979 	struct i40e_hw *hw = &pf->hw;
3980 	u32 val;
3981 
3982 	/* clear things first */
3983 	wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3984 	rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3985 
3986 	val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3987 	      I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3988 	      I40E_PFINT_ICR0_ENA_GRST_MASK          |
3989 	      I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3990 	      I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3991 	      I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3992 	      I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3993 	      I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3994 
3995 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags))
3996 		val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3997 
3998 	if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
3999 		val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4000 
4001 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
4002 
4003 	/* SW_ITR_IDX = 0, but don't change INTENA */
4004 	wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
4005 					I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
4006 
4007 	/* OTHER_ITR_IDX = 0 */
4008 	wr32(hw, I40E_PFINT_STAT_CTL0, 0);
4009 }
4010 
4011 /**
4012  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
4013  * @vsi: the VSI being configured
4014  **/
4015 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
4016 {
4017 	u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
4018 	struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4019 	struct i40e_pf *pf = vsi->back;
4020 	struct i40e_hw *hw = &pf->hw;
4021 
4022 	/* set the ITR configuration */
4023 	q_vector->rx.next_update = jiffies + 1;
4024 	q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
4025 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr >> 1);
4026 	q_vector->rx.current_itr = q_vector->rx.target_itr;
4027 	q_vector->tx.next_update = jiffies + 1;
4028 	q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
4029 	wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr >> 1);
4030 	q_vector->tx.current_itr = q_vector->tx.target_itr;
4031 
4032 	i40e_enable_misc_int_causes(pf);
4033 
4034 	/* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
4035 	wr32(hw, I40E_PFINT_LNKLST0, 0);
4036 
4037 	/* Associate the queue pair to the vector and enable the queue
4038 	 * interrupt RX queue in linked list with next queue set to TX
4039 	 */
4040 	wr32(hw, I40E_QINT_RQCTL(0), I40E_QINT_RQCTL_VAL(nextqp, 0, TX));
4041 
4042 	if (i40e_enabled_xdp_vsi(vsi)) {
4043 		/* TX queue in linked list with next queue set to TX */
4044 		wr32(hw, I40E_QINT_TQCTL(nextqp),
4045 		     I40E_QINT_TQCTL_VAL(nextqp, 0, TX));
4046 	}
4047 
4048 	/* last TX queue so the next RX queue doesn't matter */
4049 	wr32(hw, I40E_QINT_TQCTL(0),
4050 	     I40E_QINT_TQCTL_VAL(I40E_QUEUE_END_OF_LIST, 0, RX));
4051 	i40e_flush(hw);
4052 }
4053 
4054 /**
4055  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
4056  * @pf: board private structure
4057  **/
4058 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
4059 {
4060 	struct i40e_hw *hw = &pf->hw;
4061 
4062 	wr32(hw, I40E_PFINT_DYN_CTL0,
4063 	     I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
4064 	i40e_flush(hw);
4065 }
4066 
4067 /**
4068  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
4069  * @pf: board private structure
4070  **/
4071 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
4072 {
4073 	struct i40e_hw *hw = &pf->hw;
4074 	u32 val;
4075 
4076 	val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
4077 	      I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
4078 	      (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
4079 
4080 	wr32(hw, I40E_PFINT_DYN_CTL0, val);
4081 	i40e_flush(hw);
4082 }
4083 
4084 /**
4085  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
4086  * @irq: interrupt number
4087  * @data: pointer to a q_vector
4088  **/
4089 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
4090 {
4091 	struct i40e_q_vector *q_vector = data;
4092 
4093 	if (!q_vector->tx.ring && !q_vector->rx.ring)
4094 		return IRQ_HANDLED;
4095 
4096 	napi_schedule_irqoff(&q_vector->napi);
4097 
4098 	return IRQ_HANDLED;
4099 }
4100 
4101 /**
4102  * i40e_irq_affinity_notify - Callback for affinity changes
4103  * @notify: context as to what irq was changed
4104  * @mask: the new affinity mask
4105  *
4106  * This is a callback function used by the irq_set_affinity_notifier function
4107  * so that we may register to receive changes to the irq affinity masks.
4108  **/
4109 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
4110 				     const cpumask_t *mask)
4111 {
4112 	struct i40e_q_vector *q_vector =
4113 		container_of(notify, struct i40e_q_vector, affinity_notify);
4114 
4115 	cpumask_copy(&q_vector->affinity_mask, mask);
4116 }
4117 
4118 /**
4119  * i40e_irq_affinity_release - Callback for affinity notifier release
4120  * @ref: internal core kernel usage
4121  *
4122  * This is a callback function used by the irq_set_affinity_notifier function
4123  * to inform the current notification subscriber that they will no longer
4124  * receive notifications.
4125  **/
4126 static void i40e_irq_affinity_release(struct kref *ref) {}
4127 
4128 /**
4129  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
4130  * @vsi: the VSI being configured
4131  * @basename: name for the vector
4132  *
4133  * Allocates MSI-X vectors and requests interrupts from the kernel.
4134  **/
4135 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
4136 {
4137 	int q_vectors = vsi->num_q_vectors;
4138 	struct i40e_pf *pf = vsi->back;
4139 	int base = vsi->base_vector;
4140 	int rx_int_idx = 0;
4141 	int tx_int_idx = 0;
4142 	int vector, err;
4143 	int irq_num;
4144 	int cpu;
4145 
4146 	for (vector = 0; vector < q_vectors; vector++) {
4147 		struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
4148 
4149 		irq_num = pf->msix_entries[base + vector].vector;
4150 
4151 		if (q_vector->tx.ring && q_vector->rx.ring) {
4152 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4153 				 "%s-%s-%d", basename, "TxRx", rx_int_idx++);
4154 			tx_int_idx++;
4155 		} else if (q_vector->rx.ring) {
4156 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4157 				 "%s-%s-%d", basename, "rx", rx_int_idx++);
4158 		} else if (q_vector->tx.ring) {
4159 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4160 				 "%s-%s-%d", basename, "tx", tx_int_idx++);
4161 		} else {
4162 			/* skip this unused q_vector */
4163 			continue;
4164 		}
4165 		err = request_irq(irq_num,
4166 				  vsi->irq_handler,
4167 				  0,
4168 				  q_vector->name,
4169 				  q_vector);
4170 		if (err) {
4171 			dev_info(&pf->pdev->dev,
4172 				 "MSIX request_irq failed, error: %d\n", err);
4173 			goto free_queue_irqs;
4174 		}
4175 
4176 		/* register for affinity change notifications */
4177 		q_vector->irq_num = irq_num;
4178 		q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
4179 		q_vector->affinity_notify.release = i40e_irq_affinity_release;
4180 		irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
4181 		/* Spread affinity hints out across online CPUs.
4182 		 *
4183 		 * get_cpu_mask returns a static constant mask with
4184 		 * a permanent lifetime so it's ok to pass to
4185 		 * irq_update_affinity_hint without making a copy.
4186 		 */
4187 		cpu = cpumask_local_spread(q_vector->v_idx, -1);
4188 		irq_update_affinity_hint(irq_num, get_cpu_mask(cpu));
4189 	}
4190 
4191 	vsi->irqs_ready = true;
4192 	return 0;
4193 
4194 free_queue_irqs:
4195 	while (vector) {
4196 		vector--;
4197 		irq_num = pf->msix_entries[base + vector].vector;
4198 		irq_set_affinity_notifier(irq_num, NULL);
4199 		irq_update_affinity_hint(irq_num, NULL);
4200 		free_irq(irq_num, &vsi->q_vectors[vector]);
4201 	}
4202 	return err;
4203 }
4204 
4205 /**
4206  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
4207  * @vsi: the VSI being un-configured
4208  **/
4209 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
4210 {
4211 	struct i40e_pf *pf = vsi->back;
4212 	struct i40e_hw *hw = &pf->hw;
4213 	int base = vsi->base_vector;
4214 	int i;
4215 
4216 	/* disable interrupt causation from each queue */
4217 	for (i = 0; i < vsi->num_queue_pairs; i++) {
4218 		u32 val;
4219 
4220 		val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
4221 		val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
4222 		wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
4223 
4224 		val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
4225 		val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
4226 		wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
4227 
4228 		if (!i40e_enabled_xdp_vsi(vsi))
4229 			continue;
4230 		wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
4231 	}
4232 
4233 	/* disable each interrupt */
4234 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4235 		for (i = vsi->base_vector;
4236 		     i < (vsi->num_q_vectors + vsi->base_vector); i++)
4237 			wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
4238 
4239 		i40e_flush(hw);
4240 		for (i = 0; i < vsi->num_q_vectors; i++)
4241 			synchronize_irq(pf->msix_entries[i + base].vector);
4242 	} else {
4243 		/* Legacy and MSI mode - this stops all interrupt handling */
4244 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
4245 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
4246 		i40e_flush(hw);
4247 		synchronize_irq(pf->pdev->irq);
4248 	}
4249 }
4250 
4251 /**
4252  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
4253  * @vsi: the VSI being configured
4254  **/
4255 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
4256 {
4257 	struct i40e_pf *pf = vsi->back;
4258 	int i;
4259 
4260 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4261 		for (i = 0; i < vsi->num_q_vectors; i++)
4262 			i40e_irq_dynamic_enable(vsi, i);
4263 	} else {
4264 		i40e_irq_dynamic_enable_icr0(pf);
4265 	}
4266 
4267 	i40e_flush(&pf->hw);
4268 	return 0;
4269 }
4270 
4271 /**
4272  * i40e_free_misc_vector - Free the vector that handles non-queue events
4273  * @pf: board private structure
4274  **/
4275 static void i40e_free_misc_vector(struct i40e_pf *pf)
4276 {
4277 	/* Disable ICR 0 */
4278 	wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
4279 	i40e_flush(&pf->hw);
4280 
4281 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags) && pf->msix_entries) {
4282 		free_irq(pf->msix_entries[0].vector, pf);
4283 		clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
4284 	}
4285 }
4286 
4287 /**
4288  * i40e_intr - MSI/Legacy and non-queue interrupt handler
4289  * @irq: interrupt number
4290  * @data: pointer to a q_vector
4291  *
4292  * This is the handler used for all MSI/Legacy interrupts, and deals
4293  * with both queue and non-queue interrupts.  This is also used in
4294  * MSIX mode to handle the non-queue interrupts.
4295  **/
4296 static irqreturn_t i40e_intr(int irq, void *data)
4297 {
4298 	struct i40e_pf *pf = (struct i40e_pf *)data;
4299 	struct i40e_hw *hw = &pf->hw;
4300 	irqreturn_t ret = IRQ_NONE;
4301 	u32 icr0, icr0_remaining;
4302 	u32 val, ena_mask;
4303 
4304 	icr0 = rd32(hw, I40E_PFINT_ICR0);
4305 	ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
4306 
4307 	/* if sharing a legacy IRQ, we might get called w/o an intr pending */
4308 	if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
4309 		goto enable_intr;
4310 
4311 	/* if interrupt but no bits showing, must be SWINT */
4312 	if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
4313 	    (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
4314 		pf->sw_int_count++;
4315 
4316 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags) &&
4317 	    (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
4318 		ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4319 		dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
4320 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
4321 	}
4322 
4323 	/* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
4324 	if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
4325 		struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
4326 		struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4327 
4328 		/* We do not have a way to disarm Queue causes while leaving
4329 		 * interrupt enabled for all other causes, ideally
4330 		 * interrupt should be disabled while we are in NAPI but
4331 		 * this is not a performance path and napi_schedule()
4332 		 * can deal with rescheduling.
4333 		 */
4334 		if (!test_bit(__I40E_DOWN, pf->state))
4335 			napi_schedule_irqoff(&q_vector->napi);
4336 	}
4337 
4338 	if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
4339 		ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
4340 		set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
4341 		i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
4342 	}
4343 
4344 	if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
4345 		ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
4346 		set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
4347 	}
4348 
4349 	if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
4350 		/* disable any further VFLR event notifications */
4351 		if (test_bit(__I40E_VF_RESETS_DISABLED, pf->state)) {
4352 			u32 reg = rd32(hw, I40E_PFINT_ICR0_ENA);
4353 
4354 			reg &= ~I40E_PFINT_ICR0_VFLR_MASK;
4355 			wr32(hw, I40E_PFINT_ICR0_ENA, reg);
4356 		} else {
4357 			ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
4358 			set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
4359 		}
4360 	}
4361 
4362 	if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
4363 		if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4364 			set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
4365 		ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
4366 		val = rd32(hw, I40E_GLGEN_RSTAT);
4367 		val = FIELD_GET(I40E_GLGEN_RSTAT_RESET_TYPE_MASK, val);
4368 		if (val == I40E_RESET_CORER) {
4369 			pf->corer_count++;
4370 		} else if (val == I40E_RESET_GLOBR) {
4371 			pf->globr_count++;
4372 		} else if (val == I40E_RESET_EMPR) {
4373 			pf->empr_count++;
4374 			set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
4375 		}
4376 	}
4377 
4378 	if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
4379 		icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
4380 		dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4381 		dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4382 			 rd32(hw, I40E_PFHMC_ERRORINFO),
4383 			 rd32(hw, I40E_PFHMC_ERRORDATA));
4384 	}
4385 
4386 	if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4387 		u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4388 
4389 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_EVENT0_MASK)
4390 			schedule_work(&pf->ptp_extts0_work);
4391 
4392 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK)
4393 			i40e_ptp_tx_hwtstamp(pf);
4394 
4395 		icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4396 	}
4397 
4398 	/* If a critical error is pending we have no choice but to reset the
4399 	 * device.
4400 	 * Report and mask out any remaining unexpected interrupts.
4401 	 */
4402 	icr0_remaining = icr0 & ena_mask;
4403 	if (icr0_remaining) {
4404 		dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4405 			 icr0_remaining);
4406 		if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4407 		    (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4408 		    (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4409 			dev_info(&pf->pdev->dev, "device will be reset\n");
4410 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4411 			i40e_service_event_schedule(pf);
4412 		}
4413 		ena_mask &= ~icr0_remaining;
4414 	}
4415 	ret = IRQ_HANDLED;
4416 
4417 enable_intr:
4418 	/* re-enable interrupt causes */
4419 	wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4420 	if (!test_bit(__I40E_DOWN, pf->state) ||
4421 	    test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4422 		i40e_service_event_schedule(pf);
4423 		i40e_irq_dynamic_enable_icr0(pf);
4424 	}
4425 
4426 	return ret;
4427 }
4428 
4429 /**
4430  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4431  * @tx_ring:  tx ring to clean
4432  * @budget:   how many cleans we're allowed
4433  *
4434  * Returns true if there's any budget left (e.g. the clean is finished)
4435  **/
4436 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4437 {
4438 	struct i40e_vsi *vsi = tx_ring->vsi;
4439 	u16 i = tx_ring->next_to_clean;
4440 	struct i40e_tx_buffer *tx_buf;
4441 	struct i40e_tx_desc *tx_desc;
4442 
4443 	tx_buf = &tx_ring->tx_bi[i];
4444 	tx_desc = I40E_TX_DESC(tx_ring, i);
4445 	i -= tx_ring->count;
4446 
4447 	do {
4448 		struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4449 
4450 		/* if next_to_watch is not set then there is no work pending */
4451 		if (!eop_desc)
4452 			break;
4453 
4454 		/* prevent any other reads prior to eop_desc */
4455 		smp_rmb();
4456 
4457 		/* if the descriptor isn't done, no work yet to do */
4458 		if (!(eop_desc->cmd_type_offset_bsz &
4459 		      cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4460 			break;
4461 
4462 		/* clear next_to_watch to prevent false hangs */
4463 		tx_buf->next_to_watch = NULL;
4464 
4465 		tx_desc->buffer_addr = 0;
4466 		tx_desc->cmd_type_offset_bsz = 0;
4467 		/* move past filter desc */
4468 		tx_buf++;
4469 		tx_desc++;
4470 		i++;
4471 		if (unlikely(!i)) {
4472 			i -= tx_ring->count;
4473 			tx_buf = tx_ring->tx_bi;
4474 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4475 		}
4476 		/* unmap skb header data */
4477 		dma_unmap_single(tx_ring->dev,
4478 				 dma_unmap_addr(tx_buf, dma),
4479 				 dma_unmap_len(tx_buf, len),
4480 				 DMA_TO_DEVICE);
4481 		if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4482 			kfree(tx_buf->raw_buf);
4483 
4484 		tx_buf->raw_buf = NULL;
4485 		tx_buf->tx_flags = 0;
4486 		tx_buf->next_to_watch = NULL;
4487 		dma_unmap_len_set(tx_buf, len, 0);
4488 		tx_desc->buffer_addr = 0;
4489 		tx_desc->cmd_type_offset_bsz = 0;
4490 
4491 		/* move us past the eop_desc for start of next FD desc */
4492 		tx_buf++;
4493 		tx_desc++;
4494 		i++;
4495 		if (unlikely(!i)) {
4496 			i -= tx_ring->count;
4497 			tx_buf = tx_ring->tx_bi;
4498 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4499 		}
4500 
4501 		/* update budget accounting */
4502 		budget--;
4503 	} while (likely(budget));
4504 
4505 	i += tx_ring->count;
4506 	tx_ring->next_to_clean = i;
4507 
4508 	if (test_bit(I40E_FLAG_MSIX_ENA, vsi->back->flags))
4509 		i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4510 
4511 	return budget > 0;
4512 }
4513 
4514 /**
4515  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4516  * @irq: interrupt number
4517  * @data: pointer to a q_vector
4518  **/
4519 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4520 {
4521 	struct i40e_q_vector *q_vector = data;
4522 	struct i40e_vsi *vsi;
4523 
4524 	if (!q_vector->tx.ring)
4525 		return IRQ_HANDLED;
4526 
4527 	vsi = q_vector->tx.ring->vsi;
4528 	i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4529 
4530 	return IRQ_HANDLED;
4531 }
4532 
4533 /**
4534  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4535  * @vsi: the VSI being configured
4536  * @v_idx: vector index
4537  * @qp_idx: queue pair index
4538  **/
4539 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4540 {
4541 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4542 	struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4543 	struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4544 
4545 	tx_ring->q_vector = q_vector;
4546 	tx_ring->next = q_vector->tx.ring;
4547 	q_vector->tx.ring = tx_ring;
4548 	q_vector->tx.count++;
4549 
4550 	/* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4551 	if (i40e_enabled_xdp_vsi(vsi)) {
4552 		struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4553 
4554 		xdp_ring->q_vector = q_vector;
4555 		xdp_ring->next = q_vector->tx.ring;
4556 		q_vector->tx.ring = xdp_ring;
4557 		q_vector->tx.count++;
4558 	}
4559 
4560 	rx_ring->q_vector = q_vector;
4561 	rx_ring->next = q_vector->rx.ring;
4562 	q_vector->rx.ring = rx_ring;
4563 	q_vector->rx.count++;
4564 }
4565 
4566 /**
4567  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4568  * @vsi: the VSI being configured
4569  *
4570  * This function maps descriptor rings to the queue-specific vectors
4571  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4572  * one vector per queue pair, but on a constrained vector budget, we
4573  * group the queue pairs as "efficiently" as possible.
4574  **/
4575 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4576 {
4577 	int qp_remaining = vsi->num_queue_pairs;
4578 	int q_vectors = vsi->num_q_vectors;
4579 	int num_ringpairs;
4580 	int v_start = 0;
4581 	int qp_idx = 0;
4582 
4583 	/* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4584 	 * group them so there are multiple queues per vector.
4585 	 * It is also important to go through all the vectors available to be
4586 	 * sure that if we don't use all the vectors, that the remaining vectors
4587 	 * are cleared. This is especially important when decreasing the
4588 	 * number of queues in use.
4589 	 */
4590 	for (; v_start < q_vectors; v_start++) {
4591 		struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4592 
4593 		num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4594 
4595 		q_vector->num_ringpairs = num_ringpairs;
4596 		q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4597 
4598 		q_vector->rx.count = 0;
4599 		q_vector->tx.count = 0;
4600 		q_vector->rx.ring = NULL;
4601 		q_vector->tx.ring = NULL;
4602 
4603 		while (num_ringpairs--) {
4604 			i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4605 			qp_idx++;
4606 			qp_remaining--;
4607 		}
4608 	}
4609 }
4610 
4611 /**
4612  * i40e_vsi_request_irq - Request IRQ from the OS
4613  * @vsi: the VSI being configured
4614  * @basename: name for the vector
4615  **/
4616 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4617 {
4618 	struct i40e_pf *pf = vsi->back;
4619 	int err;
4620 
4621 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
4622 		err = i40e_vsi_request_irq_msix(vsi, basename);
4623 	else if (test_bit(I40E_FLAG_MSI_ENA, pf->flags))
4624 		err = request_irq(pf->pdev->irq, i40e_intr, 0,
4625 				  pf->int_name, pf);
4626 	else
4627 		err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4628 				  pf->int_name, pf);
4629 
4630 	if (err)
4631 		dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4632 
4633 	return err;
4634 }
4635 
4636 #ifdef CONFIG_NET_POLL_CONTROLLER
4637 /**
4638  * i40e_netpoll - A Polling 'interrupt' handler
4639  * @netdev: network interface device structure
4640  *
4641  * This is used by netconsole to send skbs without having to re-enable
4642  * interrupts.  It's not called while the normal interrupt routine is executing.
4643  **/
4644 static void i40e_netpoll(struct net_device *netdev)
4645 {
4646 	struct i40e_netdev_priv *np = netdev_priv(netdev);
4647 	struct i40e_vsi *vsi = np->vsi;
4648 	struct i40e_pf *pf = vsi->back;
4649 	int i;
4650 
4651 	/* if interface is down do nothing */
4652 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
4653 		return;
4654 
4655 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4656 		for (i = 0; i < vsi->num_q_vectors; i++)
4657 			i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4658 	} else {
4659 		i40e_intr(pf->pdev->irq, netdev);
4660 	}
4661 }
4662 #endif
4663 
4664 #define I40E_QTX_ENA_WAIT_COUNT 50
4665 
4666 /**
4667  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4668  * @pf: the PF being configured
4669  * @pf_q: the PF queue
4670  * @enable: enable or disable state of the queue
4671  *
4672  * This routine will wait for the given Tx queue of the PF to reach the
4673  * enabled or disabled state.
4674  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4675  * multiple retries; else will return 0 in case of success.
4676  **/
4677 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4678 {
4679 	int i;
4680 	u32 tx_reg;
4681 
4682 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4683 		tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4684 		if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4685 			break;
4686 
4687 		usleep_range(10, 20);
4688 	}
4689 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4690 		return -ETIMEDOUT;
4691 
4692 	return 0;
4693 }
4694 
4695 /**
4696  * i40e_control_tx_q - Start or stop a particular Tx queue
4697  * @pf: the PF structure
4698  * @pf_q: the PF queue to configure
4699  * @enable: start or stop the queue
4700  *
4701  * This function enables or disables a single queue. Note that any delay
4702  * required after the operation is expected to be handled by the caller of
4703  * this function.
4704  **/
4705 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4706 {
4707 	struct i40e_hw *hw = &pf->hw;
4708 	u32 tx_reg;
4709 	int i;
4710 
4711 	/* warn the TX unit of coming changes */
4712 	i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4713 	if (!enable)
4714 		usleep_range(10, 20);
4715 
4716 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4717 		tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4718 		if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4719 		    ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4720 			break;
4721 		usleep_range(1000, 2000);
4722 	}
4723 
4724 	/* Skip if the queue is already in the requested state */
4725 	if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4726 		return;
4727 
4728 	/* turn on/off the queue */
4729 	if (enable) {
4730 		wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4731 		tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4732 	} else {
4733 		tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4734 	}
4735 
4736 	wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4737 }
4738 
4739 /**
4740  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4741  * @seid: VSI SEID
4742  * @pf: the PF structure
4743  * @pf_q: the PF queue to configure
4744  * @is_xdp: true if the queue is used for XDP
4745  * @enable: start or stop the queue
4746  **/
4747 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4748 			   bool is_xdp, bool enable)
4749 {
4750 	int ret;
4751 
4752 	i40e_control_tx_q(pf, pf_q, enable);
4753 
4754 	/* wait for the change to finish */
4755 	ret = i40e_pf_txq_wait(pf, pf_q, enable);
4756 	if (ret) {
4757 		dev_info(&pf->pdev->dev,
4758 			 "VSI seid %d %sTx ring %d %sable timeout\n",
4759 			 seid, (is_xdp ? "XDP " : ""), pf_q,
4760 			 (enable ? "en" : "dis"));
4761 	}
4762 
4763 	return ret;
4764 }
4765 
4766 /**
4767  * i40e_vsi_enable_tx - Start a VSI's rings
4768  * @vsi: the VSI being configured
4769  **/
4770 static int i40e_vsi_enable_tx(struct i40e_vsi *vsi)
4771 {
4772 	struct i40e_pf *pf = vsi->back;
4773 	int i, pf_q, ret = 0;
4774 
4775 	pf_q = vsi->base_queue;
4776 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4777 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4778 					     pf_q,
4779 					     false /*is xdp*/, true);
4780 		if (ret)
4781 			break;
4782 
4783 		if (!i40e_enabled_xdp_vsi(vsi))
4784 			continue;
4785 
4786 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4787 					     pf_q + vsi->alloc_queue_pairs,
4788 					     true /*is xdp*/, true);
4789 		if (ret)
4790 			break;
4791 	}
4792 	return ret;
4793 }
4794 
4795 /**
4796  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4797  * @pf: the PF being configured
4798  * @pf_q: the PF queue
4799  * @enable: enable or disable state of the queue
4800  *
4801  * This routine will wait for the given Rx queue of the PF to reach the
4802  * enabled or disabled state.
4803  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4804  * multiple retries; else will return 0 in case of success.
4805  **/
4806 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4807 {
4808 	int i;
4809 	u32 rx_reg;
4810 
4811 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4812 		rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4813 		if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4814 			break;
4815 
4816 		usleep_range(10, 20);
4817 	}
4818 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4819 		return -ETIMEDOUT;
4820 
4821 	return 0;
4822 }
4823 
4824 /**
4825  * i40e_control_rx_q - Start or stop a particular Rx queue
4826  * @pf: the PF structure
4827  * @pf_q: the PF queue to configure
4828  * @enable: start or stop the queue
4829  *
4830  * This function enables or disables a single queue. Note that
4831  * any delay required after the operation is expected to be
4832  * handled by the caller of this function.
4833  **/
4834 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4835 {
4836 	struct i40e_hw *hw = &pf->hw;
4837 	u32 rx_reg;
4838 	int i;
4839 
4840 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4841 		rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4842 		if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4843 		    ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4844 			break;
4845 		usleep_range(1000, 2000);
4846 	}
4847 
4848 	/* Skip if the queue is already in the requested state */
4849 	if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4850 		return;
4851 
4852 	/* turn on/off the queue */
4853 	if (enable)
4854 		rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4855 	else
4856 		rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4857 
4858 	wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4859 }
4860 
4861 /**
4862  * i40e_control_wait_rx_q
4863  * @pf: the PF structure
4864  * @pf_q: queue being configured
4865  * @enable: start or stop the rings
4866  *
4867  * This function enables or disables a single queue along with waiting
4868  * for the change to finish. The caller of this function should handle
4869  * the delays needed in the case of disabling queues.
4870  **/
4871 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4872 {
4873 	int ret = 0;
4874 
4875 	i40e_control_rx_q(pf, pf_q, enable);
4876 
4877 	/* wait for the change to finish */
4878 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4879 	if (ret)
4880 		return ret;
4881 
4882 	return ret;
4883 }
4884 
4885 /**
4886  * i40e_vsi_enable_rx - Start a VSI's rings
4887  * @vsi: the VSI being configured
4888  **/
4889 static int i40e_vsi_enable_rx(struct i40e_vsi *vsi)
4890 {
4891 	struct i40e_pf *pf = vsi->back;
4892 	int i, pf_q, ret = 0;
4893 
4894 	pf_q = vsi->base_queue;
4895 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4896 		ret = i40e_control_wait_rx_q(pf, pf_q, true);
4897 		if (ret) {
4898 			dev_info(&pf->pdev->dev,
4899 				 "VSI seid %d Rx ring %d enable timeout\n",
4900 				 vsi->seid, pf_q);
4901 			break;
4902 		}
4903 	}
4904 
4905 	return ret;
4906 }
4907 
4908 /**
4909  * i40e_vsi_start_rings - Start a VSI's rings
4910  * @vsi: the VSI being configured
4911  **/
4912 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4913 {
4914 	int ret = 0;
4915 
4916 	/* do rx first for enable and last for disable */
4917 	ret = i40e_vsi_enable_rx(vsi);
4918 	if (ret)
4919 		return ret;
4920 	ret = i40e_vsi_enable_tx(vsi);
4921 
4922 	return ret;
4923 }
4924 
4925 #define I40E_DISABLE_TX_GAP_MSEC	50
4926 
4927 /**
4928  * i40e_vsi_stop_rings - Stop a VSI's rings
4929  * @vsi: the VSI being configured
4930  **/
4931 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4932 {
4933 	struct i40e_pf *pf = vsi->back;
4934 	u32 pf_q, tx_q_end, rx_q_end;
4935 
4936 	/* When port TX is suspended, don't wait */
4937 	if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4938 		return i40e_vsi_stop_rings_no_wait(vsi);
4939 
4940 	tx_q_end = vsi->base_queue +
4941 		vsi->alloc_queue_pairs * (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
4942 	for (pf_q = vsi->base_queue; pf_q < tx_q_end; pf_q++)
4943 		i40e_pre_tx_queue_cfg(&pf->hw, pf_q, false);
4944 
4945 	rx_q_end = vsi->base_queue + vsi->num_queue_pairs;
4946 	for (pf_q = vsi->base_queue; pf_q < rx_q_end; pf_q++)
4947 		i40e_control_rx_q(pf, pf_q, false);
4948 
4949 	msleep(I40E_DISABLE_TX_GAP_MSEC);
4950 	for (pf_q = vsi->base_queue; pf_q < tx_q_end; pf_q++)
4951 		wr32(&pf->hw, I40E_QTX_ENA(pf_q), 0);
4952 
4953 	i40e_vsi_wait_queues_disabled(vsi);
4954 }
4955 
4956 /**
4957  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4958  * @vsi: the VSI being shutdown
4959  *
4960  * This function stops all the rings for a VSI but does not delay to verify
4961  * that rings have been disabled. It is expected that the caller is shutting
4962  * down multiple VSIs at once and will delay together for all the VSIs after
4963  * initiating the shutdown. This is particularly useful for shutting down lots
4964  * of VFs together. Otherwise, a large delay can be incurred while configuring
4965  * each VSI in serial.
4966  **/
4967 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4968 {
4969 	struct i40e_pf *pf = vsi->back;
4970 	int i, pf_q;
4971 
4972 	pf_q = vsi->base_queue;
4973 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4974 		i40e_control_tx_q(pf, pf_q, false);
4975 		i40e_control_rx_q(pf, pf_q, false);
4976 	}
4977 }
4978 
4979 /**
4980  * i40e_vsi_free_irq - Free the irq association with the OS
4981  * @vsi: the VSI being configured
4982  **/
4983 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4984 {
4985 	struct i40e_pf *pf = vsi->back;
4986 	struct i40e_hw *hw = &pf->hw;
4987 	int base = vsi->base_vector;
4988 	u32 val, qp;
4989 	int i;
4990 
4991 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4992 		if (!vsi->q_vectors)
4993 			return;
4994 
4995 		if (!vsi->irqs_ready)
4996 			return;
4997 
4998 		vsi->irqs_ready = false;
4999 		for (i = 0; i < vsi->num_q_vectors; i++) {
5000 			int irq_num;
5001 			u16 vector;
5002 
5003 			vector = i + base;
5004 			irq_num = pf->msix_entries[vector].vector;
5005 
5006 			/* free only the irqs that were actually requested */
5007 			if (!vsi->q_vectors[i] ||
5008 			    !vsi->q_vectors[i]->num_ringpairs)
5009 				continue;
5010 
5011 			/* clear the affinity notifier in the IRQ descriptor */
5012 			irq_set_affinity_notifier(irq_num, NULL);
5013 			/* remove our suggested affinity mask for this IRQ */
5014 			irq_update_affinity_hint(irq_num, NULL);
5015 			free_irq(irq_num, vsi->q_vectors[i]);
5016 
5017 			/* Tear down the interrupt queue link list
5018 			 *
5019 			 * We know that they come in pairs and always
5020 			 * the Rx first, then the Tx.  To clear the
5021 			 * link list, stick the EOL value into the
5022 			 * next_q field of the registers.
5023 			 */
5024 			val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
5025 			qp = FIELD_GET(I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK,
5026 				       val);
5027 			val |= I40E_QUEUE_END_OF_LIST
5028 				<< I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
5029 			wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
5030 
5031 			while (qp != I40E_QUEUE_END_OF_LIST) {
5032 				u32 next;
5033 
5034 				val = rd32(hw, I40E_QINT_RQCTL(qp));
5035 
5036 				val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5037 					 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5038 					 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5039 					 I40E_QINT_RQCTL_INTEVENT_MASK);
5040 
5041 				val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5042 					 I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5043 
5044 				wr32(hw, I40E_QINT_RQCTL(qp), val);
5045 
5046 				val = rd32(hw, I40E_QINT_TQCTL(qp));
5047 
5048 				next = FIELD_GET(I40E_QINT_TQCTL_NEXTQ_INDX_MASK,
5049 						 val);
5050 
5051 				val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5052 					 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5053 					 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5054 					 I40E_QINT_TQCTL_INTEVENT_MASK);
5055 
5056 				val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5057 					 I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5058 
5059 				wr32(hw, I40E_QINT_TQCTL(qp), val);
5060 				qp = next;
5061 			}
5062 		}
5063 	} else {
5064 		free_irq(pf->pdev->irq, pf);
5065 
5066 		val = rd32(hw, I40E_PFINT_LNKLST0);
5067 		qp = FIELD_GET(I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK, val);
5068 		val |= I40E_QUEUE_END_OF_LIST
5069 			<< I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
5070 		wr32(hw, I40E_PFINT_LNKLST0, val);
5071 
5072 		val = rd32(hw, I40E_QINT_RQCTL(qp));
5073 		val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5074 			 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5075 			 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5076 			 I40E_QINT_RQCTL_INTEVENT_MASK);
5077 
5078 		val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5079 			I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5080 
5081 		wr32(hw, I40E_QINT_RQCTL(qp), val);
5082 
5083 		val = rd32(hw, I40E_QINT_TQCTL(qp));
5084 
5085 		val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5086 			 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5087 			 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5088 			 I40E_QINT_TQCTL_INTEVENT_MASK);
5089 
5090 		val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5091 			I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5092 
5093 		wr32(hw, I40E_QINT_TQCTL(qp), val);
5094 	}
5095 }
5096 
5097 /**
5098  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
5099  * @vsi: the VSI being configured
5100  * @v_idx: Index of vector to be freed
5101  *
5102  * This function frees the memory allocated to the q_vector.  In addition if
5103  * NAPI is enabled it will delete any references to the NAPI struct prior
5104  * to freeing the q_vector.
5105  **/
5106 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
5107 {
5108 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
5109 	struct i40e_ring *ring;
5110 
5111 	if (!q_vector)
5112 		return;
5113 
5114 	/* disassociate q_vector from rings */
5115 	i40e_for_each_ring(ring, q_vector->tx)
5116 		ring->q_vector = NULL;
5117 
5118 	i40e_for_each_ring(ring, q_vector->rx)
5119 		ring->q_vector = NULL;
5120 
5121 	/* only VSI w/ an associated netdev is set up w/ NAPI */
5122 	if (vsi->netdev)
5123 		netif_napi_del(&q_vector->napi);
5124 
5125 	vsi->q_vectors[v_idx] = NULL;
5126 
5127 	kfree_rcu(q_vector, rcu);
5128 }
5129 
5130 /**
5131  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
5132  * @vsi: the VSI being un-configured
5133  *
5134  * This frees the memory allocated to the q_vectors and
5135  * deletes references to the NAPI struct.
5136  **/
5137 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
5138 {
5139 	int v_idx;
5140 
5141 	for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
5142 		i40e_free_q_vector(vsi, v_idx);
5143 }
5144 
5145 /**
5146  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
5147  * @pf: board private structure
5148  **/
5149 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
5150 {
5151 	/* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
5152 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
5153 		pci_disable_msix(pf->pdev);
5154 		kfree(pf->msix_entries);
5155 		pf->msix_entries = NULL;
5156 		kfree(pf->irq_pile);
5157 		pf->irq_pile = NULL;
5158 	} else if (test_bit(I40E_FLAG_MSI_ENA, pf->flags)) {
5159 		pci_disable_msi(pf->pdev);
5160 	}
5161 	clear_bit(I40E_FLAG_MSI_ENA, pf->flags);
5162 	clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
5163 }
5164 
5165 /**
5166  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
5167  * @pf: board private structure
5168  *
5169  * We go through and clear interrupt specific resources and reset the structure
5170  * to pre-load conditions
5171  **/
5172 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
5173 {
5174 	struct i40e_vsi *vsi;
5175 	int i;
5176 
5177 	if (test_bit(__I40E_MISC_IRQ_REQUESTED, pf->state))
5178 		i40e_free_misc_vector(pf);
5179 
5180 	i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
5181 		      I40E_IWARP_IRQ_PILE_ID);
5182 
5183 	i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
5184 
5185 	i40e_pf_for_each_vsi(pf, i, vsi)
5186 		i40e_vsi_free_q_vectors(vsi);
5187 
5188 	i40e_reset_interrupt_capability(pf);
5189 }
5190 
5191 /**
5192  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5193  * @vsi: the VSI being configured
5194  **/
5195 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
5196 {
5197 	int q_idx;
5198 
5199 	if (!vsi->netdev)
5200 		return;
5201 
5202 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5203 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5204 
5205 		if (q_vector->rx.ring || q_vector->tx.ring)
5206 			napi_enable(&q_vector->napi);
5207 	}
5208 }
5209 
5210 /**
5211  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
5212  * @vsi: the VSI being configured
5213  **/
5214 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
5215 {
5216 	int q_idx;
5217 
5218 	if (!vsi->netdev)
5219 		return;
5220 
5221 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5222 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5223 
5224 		if (q_vector->rx.ring || q_vector->tx.ring)
5225 			napi_disable(&q_vector->napi);
5226 	}
5227 }
5228 
5229 /**
5230  * i40e_vsi_close - Shut down a VSI
5231  * @vsi: the vsi to be quelled
5232  **/
5233 static void i40e_vsi_close(struct i40e_vsi *vsi)
5234 {
5235 	struct i40e_pf *pf = vsi->back;
5236 	if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
5237 		i40e_down(vsi);
5238 	i40e_vsi_free_irq(vsi);
5239 	i40e_vsi_free_tx_resources(vsi);
5240 	i40e_vsi_free_rx_resources(vsi);
5241 	vsi->current_netdev_flags = 0;
5242 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
5243 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
5244 		set_bit(__I40E_CLIENT_RESET, pf->state);
5245 }
5246 
5247 /**
5248  * i40e_quiesce_vsi - Pause a given VSI
5249  * @vsi: the VSI being paused
5250  **/
5251 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
5252 {
5253 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
5254 		return;
5255 
5256 	set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
5257 	if (vsi->netdev && netif_running(vsi->netdev))
5258 		vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
5259 	else
5260 		i40e_vsi_close(vsi);
5261 }
5262 
5263 /**
5264  * i40e_unquiesce_vsi - Resume a given VSI
5265  * @vsi: the VSI being resumed
5266  **/
5267 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
5268 {
5269 	if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
5270 		return;
5271 
5272 	if (vsi->netdev && netif_running(vsi->netdev))
5273 		vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
5274 	else
5275 		i40e_vsi_open(vsi);   /* this clears the DOWN bit */
5276 }
5277 
5278 /**
5279  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
5280  * @pf: the PF
5281  **/
5282 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
5283 {
5284 	struct i40e_vsi *vsi;
5285 	int v;
5286 
5287 	i40e_pf_for_each_vsi(pf, v, vsi)
5288 		i40e_quiesce_vsi(vsi);
5289 }
5290 
5291 /**
5292  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
5293  * @pf: the PF
5294  **/
5295 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
5296 {
5297 	struct i40e_vsi *vsi;
5298 	int v;
5299 
5300 	i40e_pf_for_each_vsi(pf, v, vsi)
5301 		i40e_unquiesce_vsi(vsi);
5302 }
5303 
5304 /**
5305  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
5306  * @vsi: the VSI being configured
5307  *
5308  * Wait until all queues on a given VSI have been disabled.
5309  **/
5310 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
5311 {
5312 	struct i40e_pf *pf = vsi->back;
5313 	int i, pf_q, ret;
5314 
5315 	pf_q = vsi->base_queue;
5316 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
5317 		/* Check and wait for the Tx queue */
5318 		ret = i40e_pf_txq_wait(pf, pf_q, false);
5319 		if (ret) {
5320 			dev_info(&pf->pdev->dev,
5321 				 "VSI seid %d Tx ring %d disable timeout\n",
5322 				 vsi->seid, pf_q);
5323 			return ret;
5324 		}
5325 
5326 		if (!i40e_enabled_xdp_vsi(vsi))
5327 			goto wait_rx;
5328 
5329 		/* Check and wait for the XDP Tx queue */
5330 		ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
5331 				       false);
5332 		if (ret) {
5333 			dev_info(&pf->pdev->dev,
5334 				 "VSI seid %d XDP Tx ring %d disable timeout\n",
5335 				 vsi->seid, pf_q);
5336 			return ret;
5337 		}
5338 wait_rx:
5339 		/* Check and wait for the Rx queue */
5340 		ret = i40e_pf_rxq_wait(pf, pf_q, false);
5341 		if (ret) {
5342 			dev_info(&pf->pdev->dev,
5343 				 "VSI seid %d Rx ring %d disable timeout\n",
5344 				 vsi->seid, pf_q);
5345 			return ret;
5346 		}
5347 	}
5348 
5349 	return 0;
5350 }
5351 
5352 #ifdef CONFIG_I40E_DCB
5353 /**
5354  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
5355  * @pf: the PF
5356  *
5357  * This function waits for the queues to be in disabled state for all the
5358  * VSIs that are managed by this PF.
5359  **/
5360 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
5361 {
5362 	struct i40e_vsi *vsi;
5363 	int v, ret = 0;
5364 
5365 	i40e_pf_for_each_vsi(pf, v, vsi) {
5366 		ret = i40e_vsi_wait_queues_disabled(vsi);
5367 		if (ret)
5368 			break;
5369 	}
5370 
5371 	return ret;
5372 }
5373 
5374 #endif
5375 
5376 /**
5377  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
5378  * @pf: pointer to PF
5379  *
5380  * Get TC map for ISCSI PF type that will include iSCSI TC
5381  * and LAN TC.
5382  **/
5383 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
5384 {
5385 	struct i40e_dcb_app_priority_table app;
5386 	struct i40e_hw *hw = &pf->hw;
5387 	u8 enabled_tc = 1; /* TC0 is always enabled */
5388 	u8 tc, i;
5389 	/* Get the iSCSI APP TLV */
5390 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5391 
5392 	for (i = 0; i < dcbcfg->numapps; i++) {
5393 		app = dcbcfg->app[i];
5394 		if (app.selector == I40E_APP_SEL_TCPIP &&
5395 		    app.protocolid == I40E_APP_PROTOID_ISCSI) {
5396 			tc = dcbcfg->etscfg.prioritytable[app.priority];
5397 			enabled_tc |= BIT(tc);
5398 			break;
5399 		}
5400 	}
5401 
5402 	return enabled_tc;
5403 }
5404 
5405 /**
5406  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5407  * @dcbcfg: the corresponding DCBx configuration structure
5408  *
5409  * Return the number of TCs from given DCBx configuration
5410  **/
5411 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5412 {
5413 	int i, tc_unused = 0;
5414 	u8 num_tc = 0;
5415 	u8 ret = 0;
5416 
5417 	/* Scan the ETS Config Priority Table to find
5418 	 * traffic class enabled for a given priority
5419 	 * and create a bitmask of enabled TCs
5420 	 */
5421 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5422 		num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5423 
5424 	/* Now scan the bitmask to check for
5425 	 * contiguous TCs starting with TC0
5426 	 */
5427 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5428 		if (num_tc & BIT(i)) {
5429 			if (!tc_unused) {
5430 				ret++;
5431 			} else {
5432 				pr_err("Non-contiguous TC - Disabling DCB\n");
5433 				return 1;
5434 			}
5435 		} else {
5436 			tc_unused = 1;
5437 		}
5438 	}
5439 
5440 	/* There is always at least TC0 */
5441 	if (!ret)
5442 		ret = 1;
5443 
5444 	return ret;
5445 }
5446 
5447 /**
5448  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5449  * @dcbcfg: the corresponding DCBx configuration structure
5450  *
5451  * Query the current DCB configuration and return the number of
5452  * traffic classes enabled from the given DCBX config
5453  **/
5454 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5455 {
5456 	u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5457 	u8 enabled_tc = 1;
5458 	u8 i;
5459 
5460 	for (i = 0; i < num_tc; i++)
5461 		enabled_tc |= BIT(i);
5462 
5463 	return enabled_tc;
5464 }
5465 
5466 /**
5467  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5468  * @pf: PF being queried
5469  *
5470  * Query the current MQPRIO configuration and return the number of
5471  * traffic classes enabled.
5472  **/
5473 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5474 {
5475 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
5476 	u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5477 	u8 enabled_tc = 1, i;
5478 
5479 	for (i = 1; i < num_tc; i++)
5480 		enabled_tc |= BIT(i);
5481 	return enabled_tc;
5482 }
5483 
5484 /**
5485  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5486  * @pf: PF being queried
5487  *
5488  * Return number of traffic classes enabled for the given PF
5489  **/
5490 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5491 {
5492 	u8 i, enabled_tc = 1;
5493 	u8 num_tc = 0;
5494 
5495 	if (i40e_is_tc_mqprio_enabled(pf)) {
5496 		struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
5497 
5498 		return vsi->mqprio_qopt.qopt.num_tc;
5499 	}
5500 
5501 	/* If neither MQPRIO nor DCB is enabled, then always use single TC */
5502 	if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags))
5503 		return 1;
5504 
5505 	/* SFP mode will be enabled for all TCs on port */
5506 	if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
5507 		return i40e_dcb_get_num_tc(&pf->hw.local_dcbx_config);
5508 
5509 	/* MFP mode return count of enabled TCs for this PF */
5510 	if (pf->hw.func_caps.iscsi)
5511 		enabled_tc =  i40e_get_iscsi_tc_map(pf);
5512 	else
5513 		return 1; /* Only TC0 */
5514 
5515 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5516 		if (enabled_tc & BIT(i))
5517 			num_tc++;
5518 	}
5519 	return num_tc;
5520 }
5521 
5522 /**
5523  * i40e_pf_get_tc_map - Get bitmap for enabled traffic classes
5524  * @pf: PF being queried
5525  *
5526  * Return a bitmap for enabled traffic classes for this PF.
5527  **/
5528 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5529 {
5530 	if (i40e_is_tc_mqprio_enabled(pf))
5531 		return i40e_mqprio_get_enabled_tc(pf);
5532 
5533 	/* If neither MQPRIO nor DCB is enabled for this PF then just return
5534 	 * default TC
5535 	 */
5536 	if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags))
5537 		return I40E_DEFAULT_TRAFFIC_CLASS;
5538 
5539 	/* SFP mode we want PF to be enabled for all TCs */
5540 	if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
5541 		return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5542 
5543 	/* MFP enabled and iSCSI PF type */
5544 	if (pf->hw.func_caps.iscsi)
5545 		return i40e_get_iscsi_tc_map(pf);
5546 	else
5547 		return I40E_DEFAULT_TRAFFIC_CLASS;
5548 }
5549 
5550 /**
5551  * i40e_vsi_get_bw_info - Query VSI BW Information
5552  * @vsi: the VSI being queried
5553  *
5554  * Returns 0 on success, negative value on failure
5555  **/
5556 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5557 {
5558 	struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5559 	struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5560 	struct i40e_pf *pf = vsi->back;
5561 	struct i40e_hw *hw = &pf->hw;
5562 	u32 tc_bw_max;
5563 	int ret;
5564 	int i;
5565 
5566 	/* Get the VSI level BW configuration */
5567 	ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5568 	if (ret) {
5569 		dev_info(&pf->pdev->dev,
5570 			 "couldn't get PF vsi bw config, err %pe aq_err %s\n",
5571 			 ERR_PTR(ret),
5572 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5573 		return -EINVAL;
5574 	}
5575 
5576 	/* Get the VSI level BW configuration per TC */
5577 	ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5578 					       NULL);
5579 	if (ret) {
5580 		dev_info(&pf->pdev->dev,
5581 			 "couldn't get PF vsi ets bw config, err %pe aq_err %s\n",
5582 			 ERR_PTR(ret),
5583 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5584 		return -EINVAL;
5585 	}
5586 
5587 	if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5588 		dev_info(&pf->pdev->dev,
5589 			 "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5590 			 bw_config.tc_valid_bits,
5591 			 bw_ets_config.tc_valid_bits);
5592 		/* Still continuing */
5593 	}
5594 
5595 	vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5596 	vsi->bw_max_quanta = bw_config.max_bw;
5597 	tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5598 		    (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5599 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5600 		vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5601 		vsi->bw_ets_limit_credits[i] =
5602 					le16_to_cpu(bw_ets_config.credits[i]);
5603 		/* 3 bits out of 4 for each TC */
5604 		vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5605 	}
5606 
5607 	return 0;
5608 }
5609 
5610 /**
5611  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5612  * @vsi: the VSI being configured
5613  * @enabled_tc: TC bitmap
5614  * @bw_share: BW shared credits per TC
5615  *
5616  * Returns 0 on success, negative value on failure
5617  **/
5618 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5619 				       u8 *bw_share)
5620 {
5621 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5622 	struct i40e_pf *pf = vsi->back;
5623 	int ret;
5624 	int i;
5625 
5626 	/* There is no need to reset BW when mqprio mode is on.  */
5627 	if (i40e_is_tc_mqprio_enabled(pf))
5628 		return 0;
5629 	if (!vsi->mqprio_qopt.qopt.hw && !test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
5630 		ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5631 		if (ret)
5632 			dev_info(&pf->pdev->dev,
5633 				 "Failed to reset tx rate for vsi->seid %u\n",
5634 				 vsi->seid);
5635 		return ret;
5636 	}
5637 	memset(&bw_data, 0, sizeof(bw_data));
5638 	bw_data.tc_valid_bits = enabled_tc;
5639 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5640 		bw_data.tc_bw_credits[i] = bw_share[i];
5641 
5642 	ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5643 	if (ret) {
5644 		dev_info(&pf->pdev->dev,
5645 			 "AQ command Config VSI BW allocation per TC failed = %d\n",
5646 			 pf->hw.aq.asq_last_status);
5647 		return -EINVAL;
5648 	}
5649 
5650 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5651 		vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5652 
5653 	return 0;
5654 }
5655 
5656 /**
5657  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5658  * @vsi: the VSI being configured
5659  * @enabled_tc: TC map to be enabled
5660  *
5661  **/
5662 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5663 {
5664 	struct net_device *netdev = vsi->netdev;
5665 	struct i40e_pf *pf = vsi->back;
5666 	struct i40e_hw *hw = &pf->hw;
5667 	u8 netdev_tc = 0;
5668 	int i;
5669 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5670 
5671 	if (!netdev)
5672 		return;
5673 
5674 	if (!enabled_tc) {
5675 		netdev_reset_tc(netdev);
5676 		return;
5677 	}
5678 
5679 	/* Set up actual enabled TCs on the VSI */
5680 	if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5681 		return;
5682 
5683 	/* set per TC queues for the VSI */
5684 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5685 		/* Only set TC queues for enabled tcs
5686 		 *
5687 		 * e.g. For a VSI that has TC0 and TC3 enabled the
5688 		 * enabled_tc bitmap would be 0x00001001; the driver
5689 		 * will set the numtc for netdev as 2 that will be
5690 		 * referenced by the netdev layer as TC 0 and 1.
5691 		 */
5692 		if (vsi->tc_config.enabled_tc & BIT(i))
5693 			netdev_set_tc_queue(netdev,
5694 					vsi->tc_config.tc_info[i].netdev_tc,
5695 					vsi->tc_config.tc_info[i].qcount,
5696 					vsi->tc_config.tc_info[i].qoffset);
5697 	}
5698 
5699 	if (i40e_is_tc_mqprio_enabled(pf))
5700 		return;
5701 
5702 	/* Assign UP2TC map for the VSI */
5703 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5704 		/* Get the actual TC# for the UP */
5705 		u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5706 		/* Get the mapped netdev TC# for the UP */
5707 		netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5708 		netdev_set_prio_tc_map(netdev, i, netdev_tc);
5709 	}
5710 }
5711 
5712 /**
5713  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5714  * @vsi: the VSI being configured
5715  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5716  **/
5717 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5718 				      struct i40e_vsi_context *ctxt)
5719 {
5720 	/* copy just the sections touched not the entire info
5721 	 * since not all sections are valid as returned by
5722 	 * update vsi params
5723 	 */
5724 	vsi->info.mapping_flags = ctxt->info.mapping_flags;
5725 	memcpy(&vsi->info.queue_mapping,
5726 	       &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5727 	memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5728 	       sizeof(vsi->info.tc_mapping));
5729 }
5730 
5731 /**
5732  * i40e_update_adq_vsi_queues - update queue mapping for ADq VSI
5733  * @vsi: the VSI being reconfigured
5734  * @vsi_offset: offset from main VF VSI
5735  */
5736 int i40e_update_adq_vsi_queues(struct i40e_vsi *vsi, int vsi_offset)
5737 {
5738 	struct i40e_vsi_context ctxt = {};
5739 	struct i40e_pf *pf;
5740 	struct i40e_hw *hw;
5741 	int ret;
5742 
5743 	if (!vsi)
5744 		return -EINVAL;
5745 	pf = vsi->back;
5746 	hw = &pf->hw;
5747 
5748 	ctxt.seid = vsi->seid;
5749 	ctxt.pf_num = hw->pf_id;
5750 	ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id + vsi_offset;
5751 	ctxt.uplink_seid = vsi->uplink_seid;
5752 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5753 	ctxt.flags = I40E_AQ_VSI_TYPE_VF;
5754 	ctxt.info = vsi->info;
5755 
5756 	i40e_vsi_setup_queue_map(vsi, &ctxt, vsi->tc_config.enabled_tc,
5757 				 false);
5758 	if (vsi->reconfig_rss) {
5759 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
5760 				      vsi->num_queue_pairs);
5761 		ret = i40e_vsi_config_rss(vsi);
5762 		if (ret) {
5763 			dev_info(&pf->pdev->dev, "Failed to reconfig rss for num_queues\n");
5764 			return ret;
5765 		}
5766 		vsi->reconfig_rss = false;
5767 	}
5768 
5769 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5770 	if (ret) {
5771 		dev_info(&pf->pdev->dev, "Update vsi config failed, err %pe aq_err %s\n",
5772 			 ERR_PTR(ret),
5773 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5774 		return ret;
5775 	}
5776 	/* update the local VSI info with updated queue map */
5777 	i40e_vsi_update_queue_map(vsi, &ctxt);
5778 	vsi->info.valid_sections = 0;
5779 
5780 	return ret;
5781 }
5782 
5783 /**
5784  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5785  * @vsi: VSI to be configured
5786  * @enabled_tc: TC bitmap
5787  *
5788  * This configures a particular VSI for TCs that are mapped to the
5789  * given TC bitmap. It uses default bandwidth share for TCs across
5790  * VSIs to configure TC for a particular VSI.
5791  *
5792  * NOTE:
5793  * It is expected that the VSI queues have been quisced before calling
5794  * this function.
5795  **/
5796 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5797 {
5798 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5799 	struct i40e_pf *pf = vsi->back;
5800 	struct i40e_hw *hw = &pf->hw;
5801 	struct i40e_vsi_context ctxt;
5802 	int ret = 0;
5803 	int i;
5804 
5805 	/* Check if enabled_tc is same as existing or new TCs */
5806 	if (vsi->tc_config.enabled_tc == enabled_tc &&
5807 	    vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5808 		return ret;
5809 
5810 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
5811 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5812 		if (enabled_tc & BIT(i))
5813 			bw_share[i] = 1;
5814 	}
5815 
5816 	ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5817 	if (ret) {
5818 		struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5819 
5820 		dev_info(&pf->pdev->dev,
5821 			 "Failed configuring TC map %d for VSI %d\n",
5822 			 enabled_tc, vsi->seid);
5823 		ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5824 						  &bw_config, NULL);
5825 		if (ret) {
5826 			dev_info(&pf->pdev->dev,
5827 				 "Failed querying vsi bw info, err %pe aq_err %s\n",
5828 				 ERR_PTR(ret),
5829 				 i40e_aq_str(hw, hw->aq.asq_last_status));
5830 			goto out;
5831 		}
5832 		if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5833 			u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5834 
5835 			if (!valid_tc)
5836 				valid_tc = bw_config.tc_valid_bits;
5837 			/* Always enable TC0, no matter what */
5838 			valid_tc |= 1;
5839 			dev_info(&pf->pdev->dev,
5840 				 "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5841 				 enabled_tc, bw_config.tc_valid_bits, valid_tc);
5842 			enabled_tc = valid_tc;
5843 		}
5844 
5845 		ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5846 		if (ret) {
5847 			dev_err(&pf->pdev->dev,
5848 				"Unable to  configure TC map %d for VSI %d\n",
5849 				enabled_tc, vsi->seid);
5850 			goto out;
5851 		}
5852 	}
5853 
5854 	/* Update Queue Pairs Mapping for currently enabled UPs */
5855 	ctxt.seid = vsi->seid;
5856 	ctxt.pf_num = vsi->back->hw.pf_id;
5857 	ctxt.vf_num = 0;
5858 	ctxt.uplink_seid = vsi->uplink_seid;
5859 	ctxt.info = vsi->info;
5860 	if (i40e_is_tc_mqprio_enabled(pf)) {
5861 		ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5862 		if (ret)
5863 			goto out;
5864 	} else {
5865 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5866 	}
5867 
5868 	/* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5869 	 * queues changed.
5870 	 */
5871 	if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5872 		vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5873 				      vsi->num_queue_pairs);
5874 		ret = i40e_vsi_config_rss(vsi);
5875 		if (ret) {
5876 			dev_info(&vsi->back->pdev->dev,
5877 				 "Failed to reconfig rss for num_queues\n");
5878 			return ret;
5879 		}
5880 		vsi->reconfig_rss = false;
5881 	}
5882 	if (test_bit(I40E_FLAG_IWARP_ENA, vsi->back->flags)) {
5883 		ctxt.info.valid_sections |=
5884 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5885 		ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5886 	}
5887 
5888 	/* Update the VSI after updating the VSI queue-mapping
5889 	 * information
5890 	 */
5891 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5892 	if (ret) {
5893 		dev_info(&pf->pdev->dev,
5894 			 "Update vsi tc config failed, err %pe aq_err %s\n",
5895 			 ERR_PTR(ret),
5896 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5897 		goto out;
5898 	}
5899 	/* update the local VSI info with updated queue map */
5900 	i40e_vsi_update_queue_map(vsi, &ctxt);
5901 	vsi->info.valid_sections = 0;
5902 
5903 	/* Update current VSI BW information */
5904 	ret = i40e_vsi_get_bw_info(vsi);
5905 	if (ret) {
5906 		dev_info(&pf->pdev->dev,
5907 			 "Failed updating vsi bw info, err %pe aq_err %s\n",
5908 			 ERR_PTR(ret),
5909 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5910 		goto out;
5911 	}
5912 
5913 	/* Update the netdev TC setup */
5914 	i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5915 out:
5916 	return ret;
5917 }
5918 
5919 /**
5920  * i40e_vsi_reconfig_tc - Reconfigure VSI Tx Scheduler for stored TC map
5921  * @vsi: VSI to be reconfigured
5922  *
5923  * This reconfigures a particular VSI for TCs that are mapped to the
5924  * TC bitmap stored previously for the VSI.
5925  *
5926  * Context: It is expected that the VSI queues have been quisced before
5927  *          calling this function.
5928  *
5929  * Return: 0 on success, negative value on failure
5930  **/
5931 static int i40e_vsi_reconfig_tc(struct i40e_vsi *vsi)
5932 {
5933 	u8 enabled_tc;
5934 
5935 	enabled_tc = vsi->tc_config.enabled_tc;
5936 	vsi->tc_config.enabled_tc = 0;
5937 
5938 	return i40e_vsi_config_tc(vsi, enabled_tc);
5939 }
5940 
5941 /**
5942  * i40e_get_link_speed - Returns link speed for the interface
5943  * @vsi: VSI to be configured
5944  *
5945  **/
5946 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5947 {
5948 	struct i40e_pf *pf = vsi->back;
5949 
5950 	switch (pf->hw.phy.link_info.link_speed) {
5951 	case I40E_LINK_SPEED_40GB:
5952 		return 40000;
5953 	case I40E_LINK_SPEED_25GB:
5954 		return 25000;
5955 	case I40E_LINK_SPEED_20GB:
5956 		return 20000;
5957 	case I40E_LINK_SPEED_10GB:
5958 		return 10000;
5959 	case I40E_LINK_SPEED_1GB:
5960 		return 1000;
5961 	default:
5962 		return -EINVAL;
5963 	}
5964 }
5965 
5966 /**
5967  * i40e_bw_bytes_to_mbits - Convert max_tx_rate from bytes to mbits
5968  * @vsi: Pointer to vsi structure
5969  * @max_tx_rate: max TX rate in bytes to be converted into Mbits
5970  *
5971  * Helper function to convert units before send to set BW limit
5972  **/
5973 static u64 i40e_bw_bytes_to_mbits(struct i40e_vsi *vsi, u64 max_tx_rate)
5974 {
5975 	if (max_tx_rate < I40E_BW_MBPS_DIVISOR) {
5976 		dev_warn(&vsi->back->pdev->dev,
5977 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
5978 		max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5979 	} else {
5980 		do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
5981 	}
5982 
5983 	return max_tx_rate;
5984 }
5985 
5986 /**
5987  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5988  * @vsi: VSI to be configured
5989  * @seid: seid of the channel/VSI
5990  * @max_tx_rate: max TX rate to be configured as BW limit
5991  *
5992  * Helper function to set BW limit for a given VSI
5993  **/
5994 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5995 {
5996 	struct i40e_pf *pf = vsi->back;
5997 	u64 credits = 0;
5998 	int speed = 0;
5999 	int ret = 0;
6000 
6001 	speed = i40e_get_link_speed(vsi);
6002 	if (max_tx_rate > speed) {
6003 		dev_err(&pf->pdev->dev,
6004 			"Invalid max tx rate %llu specified for VSI seid %d.",
6005 			max_tx_rate, seid);
6006 		return -EINVAL;
6007 	}
6008 	if (max_tx_rate && max_tx_rate < I40E_BW_CREDIT_DIVISOR) {
6009 		dev_warn(&pf->pdev->dev,
6010 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
6011 		max_tx_rate = I40E_BW_CREDIT_DIVISOR;
6012 	}
6013 
6014 	/* Tx rate credits are in values of 50Mbps, 0 is disabled */
6015 	credits = max_tx_rate;
6016 	do_div(credits, I40E_BW_CREDIT_DIVISOR);
6017 	ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
6018 					  I40E_MAX_BW_INACTIVE_ACCUM, NULL);
6019 	if (ret)
6020 		dev_err(&pf->pdev->dev,
6021 			"Failed set tx rate (%llu Mbps) for vsi->seid %u, err %pe aq_err %s\n",
6022 			max_tx_rate, seid, ERR_PTR(ret),
6023 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6024 	return ret;
6025 }
6026 
6027 /**
6028  * i40e_remove_queue_channels - Remove queue channels for the TCs
6029  * @vsi: VSI to be configured
6030  *
6031  * Remove queue channels for the TCs
6032  **/
6033 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
6034 {
6035 	enum i40e_admin_queue_err last_aq_status;
6036 	struct i40e_cloud_filter *cfilter;
6037 	struct i40e_channel *ch, *ch_tmp;
6038 	struct i40e_pf *pf = vsi->back;
6039 	struct hlist_node *node;
6040 	int ret, i;
6041 
6042 	/* Reset rss size that was stored when reconfiguring rss for
6043 	 * channel VSIs with non-power-of-2 queue count.
6044 	 */
6045 	vsi->current_rss_size = 0;
6046 
6047 	/* perform cleanup for channels if they exist */
6048 	if (list_empty(&vsi->ch_list))
6049 		return;
6050 
6051 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6052 		struct i40e_vsi *p_vsi;
6053 
6054 		list_del(&ch->list);
6055 		p_vsi = ch->parent_vsi;
6056 		if (!p_vsi || !ch->initialized) {
6057 			kfree(ch);
6058 			continue;
6059 		}
6060 		/* Reset queue contexts */
6061 		for (i = 0; i < ch->num_queue_pairs; i++) {
6062 			struct i40e_ring *tx_ring, *rx_ring;
6063 			u16 pf_q;
6064 
6065 			pf_q = ch->base_queue + i;
6066 			tx_ring = vsi->tx_rings[pf_q];
6067 			tx_ring->ch = NULL;
6068 
6069 			rx_ring = vsi->rx_rings[pf_q];
6070 			rx_ring->ch = NULL;
6071 		}
6072 
6073 		/* Reset BW configured for this VSI via mqprio */
6074 		ret = i40e_set_bw_limit(vsi, ch->seid, 0);
6075 		if (ret)
6076 			dev_info(&vsi->back->pdev->dev,
6077 				 "Failed to reset tx rate for ch->seid %u\n",
6078 				 ch->seid);
6079 
6080 		/* delete cloud filters associated with this channel */
6081 		hlist_for_each_entry_safe(cfilter, node,
6082 					  &pf->cloud_filter_list, cloud_node) {
6083 			if (cfilter->seid != ch->seid)
6084 				continue;
6085 
6086 			hash_del(&cfilter->cloud_node);
6087 			if (cfilter->dst_port)
6088 				ret = i40e_add_del_cloud_filter_big_buf(vsi,
6089 									cfilter,
6090 									false);
6091 			else
6092 				ret = i40e_add_del_cloud_filter(vsi, cfilter,
6093 								false);
6094 			last_aq_status = pf->hw.aq.asq_last_status;
6095 			if (ret)
6096 				dev_info(&pf->pdev->dev,
6097 					 "Failed to delete cloud filter, err %pe aq_err %s\n",
6098 					 ERR_PTR(ret),
6099 					 i40e_aq_str(&pf->hw, last_aq_status));
6100 			kfree(cfilter);
6101 		}
6102 
6103 		/* delete VSI from FW */
6104 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
6105 					     NULL);
6106 		if (ret)
6107 			dev_err(&vsi->back->pdev->dev,
6108 				"unable to remove channel (%d) for parent VSI(%d)\n",
6109 				ch->seid, p_vsi->seid);
6110 		kfree(ch);
6111 	}
6112 	INIT_LIST_HEAD(&vsi->ch_list);
6113 }
6114 
6115 /**
6116  * i40e_get_max_queues_for_channel
6117  * @vsi: ptr to VSI to which channels are associated with
6118  *
6119  * Helper function which returns max value among the queue counts set on the
6120  * channels/TCs created.
6121  **/
6122 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
6123 {
6124 	struct i40e_channel *ch, *ch_tmp;
6125 	int max = 0;
6126 
6127 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6128 		if (!ch->initialized)
6129 			continue;
6130 		if (ch->num_queue_pairs > max)
6131 			max = ch->num_queue_pairs;
6132 	}
6133 
6134 	return max;
6135 }
6136 
6137 /**
6138  * i40e_validate_num_queues - validate num_queues w.r.t channel
6139  * @pf: ptr to PF device
6140  * @num_queues: number of queues
6141  * @vsi: the parent VSI
6142  * @reconfig_rss: indicates should the RSS be reconfigured or not
6143  *
6144  * This function validates number of queues in the context of new channel
6145  * which is being established and determines if RSS should be reconfigured
6146  * or not for parent VSI.
6147  **/
6148 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
6149 				    struct i40e_vsi *vsi, bool *reconfig_rss)
6150 {
6151 	int max_ch_queues;
6152 
6153 	if (!reconfig_rss)
6154 		return -EINVAL;
6155 
6156 	*reconfig_rss = false;
6157 	if (vsi->current_rss_size) {
6158 		if (num_queues > vsi->current_rss_size) {
6159 			dev_dbg(&pf->pdev->dev,
6160 				"Error: num_queues (%d) > vsi's current_size(%d)\n",
6161 				num_queues, vsi->current_rss_size);
6162 			return -EINVAL;
6163 		} else if ((num_queues < vsi->current_rss_size) &&
6164 			   (!is_power_of_2(num_queues))) {
6165 			dev_dbg(&pf->pdev->dev,
6166 				"Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
6167 				num_queues, vsi->current_rss_size);
6168 			return -EINVAL;
6169 		}
6170 	}
6171 
6172 	if (!is_power_of_2(num_queues)) {
6173 		/* Find the max num_queues configured for channel if channel
6174 		 * exist.
6175 		 * if channel exist, then enforce 'num_queues' to be more than
6176 		 * max ever queues configured for channel.
6177 		 */
6178 		max_ch_queues = i40e_get_max_queues_for_channel(vsi);
6179 		if (num_queues < max_ch_queues) {
6180 			dev_dbg(&pf->pdev->dev,
6181 				"Error: num_queues (%d) < max queues configured for channel(%d)\n",
6182 				num_queues, max_ch_queues);
6183 			return -EINVAL;
6184 		}
6185 		*reconfig_rss = true;
6186 	}
6187 
6188 	return 0;
6189 }
6190 
6191 /**
6192  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
6193  * @vsi: the VSI being setup
6194  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
6195  *
6196  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
6197  **/
6198 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
6199 {
6200 	struct i40e_pf *pf = vsi->back;
6201 	u8 seed[I40E_HKEY_ARRAY_SIZE];
6202 	struct i40e_hw *hw = &pf->hw;
6203 	int local_rss_size;
6204 	u8 *lut;
6205 	int ret;
6206 
6207 	if (!vsi->rss_size)
6208 		return -EINVAL;
6209 
6210 	if (rss_size > vsi->rss_size)
6211 		return -EINVAL;
6212 
6213 	local_rss_size = min_t(int, vsi->rss_size, rss_size);
6214 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
6215 	if (!lut)
6216 		return -ENOMEM;
6217 
6218 	/* Ignoring user configured lut if there is one */
6219 	i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
6220 
6221 	/* Use user configured hash key if there is one, otherwise
6222 	 * use default.
6223 	 */
6224 	if (vsi->rss_hkey_user)
6225 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
6226 	else
6227 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
6228 
6229 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
6230 	if (ret) {
6231 		dev_info(&pf->pdev->dev,
6232 			 "Cannot set RSS lut, err %pe aq_err %s\n",
6233 			 ERR_PTR(ret),
6234 			 i40e_aq_str(hw, hw->aq.asq_last_status));
6235 		kfree(lut);
6236 		return ret;
6237 	}
6238 	kfree(lut);
6239 
6240 	/* Do the update w.r.t. storing rss_size */
6241 	if (!vsi->orig_rss_size)
6242 		vsi->orig_rss_size = vsi->rss_size;
6243 	vsi->current_rss_size = local_rss_size;
6244 
6245 	return ret;
6246 }
6247 
6248 /**
6249  * i40e_channel_setup_queue_map - Setup a channel queue map
6250  * @pf: ptr to PF device
6251  * @ctxt: VSI context structure
6252  * @ch: ptr to channel structure
6253  *
6254  * Setup queue map for a specific channel
6255  **/
6256 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
6257 					 struct i40e_vsi_context *ctxt,
6258 					 struct i40e_channel *ch)
6259 {
6260 	u16 qcount, qmap, sections = 0;
6261 	u8 offset = 0;
6262 	int pow;
6263 
6264 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
6265 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
6266 
6267 	qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
6268 	ch->num_queue_pairs = qcount;
6269 
6270 	/* find the next higher power-of-2 of num queue pairs */
6271 	pow = ilog2(qcount);
6272 	if (!is_power_of_2(qcount))
6273 		pow++;
6274 
6275 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
6276 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
6277 
6278 	/* Setup queue TC[0].qmap for given VSI context */
6279 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
6280 
6281 	ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
6282 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
6283 	ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
6284 	ctxt->info.valid_sections |= cpu_to_le16(sections);
6285 }
6286 
6287 /**
6288  * i40e_add_channel - add a channel by adding VSI
6289  * @pf: ptr to PF device
6290  * @uplink_seid: underlying HW switching element (VEB) ID
6291  * @ch: ptr to channel structure
6292  *
6293  * Add a channel (VSI) using add_vsi and queue_map
6294  **/
6295 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
6296 			    struct i40e_channel *ch)
6297 {
6298 	struct i40e_hw *hw = &pf->hw;
6299 	struct i40e_vsi_context ctxt;
6300 	u8 enabled_tc = 0x1; /* TC0 enabled */
6301 	int ret;
6302 
6303 	if (ch->type != I40E_VSI_VMDQ2) {
6304 		dev_info(&pf->pdev->dev,
6305 			 "add new vsi failed, ch->type %d\n", ch->type);
6306 		return -EINVAL;
6307 	}
6308 
6309 	memset(&ctxt, 0, sizeof(ctxt));
6310 	ctxt.pf_num = hw->pf_id;
6311 	ctxt.vf_num = 0;
6312 	ctxt.uplink_seid = uplink_seid;
6313 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
6314 	if (ch->type == I40E_VSI_VMDQ2)
6315 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
6316 
6317 	if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
6318 		ctxt.info.valid_sections |=
6319 		     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6320 		ctxt.info.switch_id =
6321 		   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6322 	}
6323 
6324 	/* Set queue map for a given VSI context */
6325 	i40e_channel_setup_queue_map(pf, &ctxt, ch);
6326 
6327 	/* Now time to create VSI */
6328 	ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
6329 	if (ret) {
6330 		dev_info(&pf->pdev->dev,
6331 			 "add new vsi failed, err %pe aq_err %s\n",
6332 			 ERR_PTR(ret),
6333 			 i40e_aq_str(&pf->hw,
6334 				     pf->hw.aq.asq_last_status));
6335 		return -ENOENT;
6336 	}
6337 
6338 	/* Success, update channel, set enabled_tc only if the channel
6339 	 * is not a macvlan
6340 	 */
6341 	ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
6342 	ch->seid = ctxt.seid;
6343 	ch->vsi_number = ctxt.vsi_number;
6344 	ch->stat_counter_idx = le16_to_cpu(ctxt.info.stat_counter_idx);
6345 
6346 	/* copy just the sections touched not the entire info
6347 	 * since not all sections are valid as returned by
6348 	 * update vsi params
6349 	 */
6350 	ch->info.mapping_flags = ctxt.info.mapping_flags;
6351 	memcpy(&ch->info.queue_mapping,
6352 	       &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
6353 	memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
6354 	       sizeof(ctxt.info.tc_mapping));
6355 
6356 	return 0;
6357 }
6358 
6359 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
6360 				  u8 *bw_share)
6361 {
6362 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
6363 	int ret;
6364 	int i;
6365 
6366 	memset(&bw_data, 0, sizeof(bw_data));
6367 	bw_data.tc_valid_bits = ch->enabled_tc;
6368 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6369 		bw_data.tc_bw_credits[i] = bw_share[i];
6370 
6371 	ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
6372 				       &bw_data, NULL);
6373 	if (ret) {
6374 		dev_info(&vsi->back->pdev->dev,
6375 			 "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
6376 			 vsi->back->hw.aq.asq_last_status, ch->seid);
6377 		return -EINVAL;
6378 	}
6379 
6380 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6381 		ch->info.qs_handle[i] = bw_data.qs_handles[i];
6382 
6383 	return 0;
6384 }
6385 
6386 /**
6387  * i40e_channel_config_tx_ring - config TX ring associated with new channel
6388  * @pf: ptr to PF device
6389  * @vsi: the VSI being setup
6390  * @ch: ptr to channel structure
6391  *
6392  * Configure TX rings associated with channel (VSI) since queues are being
6393  * from parent VSI.
6394  **/
6395 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
6396 				       struct i40e_vsi *vsi,
6397 				       struct i40e_channel *ch)
6398 {
6399 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
6400 	int ret;
6401 	int i;
6402 
6403 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
6404 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6405 		if (ch->enabled_tc & BIT(i))
6406 			bw_share[i] = 1;
6407 	}
6408 
6409 	/* configure BW for new VSI */
6410 	ret = i40e_channel_config_bw(vsi, ch, bw_share);
6411 	if (ret) {
6412 		dev_info(&vsi->back->pdev->dev,
6413 			 "Failed configuring TC map %d for channel (seid %u)\n",
6414 			 ch->enabled_tc, ch->seid);
6415 		return ret;
6416 	}
6417 
6418 	for (i = 0; i < ch->num_queue_pairs; i++) {
6419 		struct i40e_ring *tx_ring, *rx_ring;
6420 		u16 pf_q;
6421 
6422 		pf_q = ch->base_queue + i;
6423 
6424 		/* Get to TX ring ptr of main VSI, for re-setup TX queue
6425 		 * context
6426 		 */
6427 		tx_ring = vsi->tx_rings[pf_q];
6428 		tx_ring->ch = ch;
6429 
6430 		/* Get the RX ring ptr */
6431 		rx_ring = vsi->rx_rings[pf_q];
6432 		rx_ring->ch = ch;
6433 	}
6434 
6435 	return 0;
6436 }
6437 
6438 /**
6439  * i40e_setup_hw_channel - setup new channel
6440  * @pf: ptr to PF device
6441  * @vsi: the VSI being setup
6442  * @ch: ptr to channel structure
6443  * @uplink_seid: underlying HW switching element (VEB) ID
6444  * @type: type of channel to be created (VMDq2/VF)
6445  *
6446  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6447  * and configures TX rings accordingly
6448  **/
6449 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
6450 					struct i40e_vsi *vsi,
6451 					struct i40e_channel *ch,
6452 					u16 uplink_seid, u8 type)
6453 {
6454 	int ret;
6455 
6456 	ch->initialized = false;
6457 	ch->base_queue = vsi->next_base_queue;
6458 	ch->type = type;
6459 
6460 	/* Proceed with creation of channel (VMDq2) VSI */
6461 	ret = i40e_add_channel(pf, uplink_seid, ch);
6462 	if (ret) {
6463 		dev_info(&pf->pdev->dev,
6464 			 "failed to add_channel using uplink_seid %u\n",
6465 			 uplink_seid);
6466 		return ret;
6467 	}
6468 
6469 	/* Mark the successful creation of channel */
6470 	ch->initialized = true;
6471 
6472 	/* Reconfigure TX queues using QTX_CTL register */
6473 	ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6474 	if (ret) {
6475 		dev_info(&pf->pdev->dev,
6476 			 "failed to configure TX rings for channel %u\n",
6477 			 ch->seid);
6478 		return ret;
6479 	}
6480 
6481 	/* update 'next_base_queue' */
6482 	vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6483 	dev_dbg(&pf->pdev->dev,
6484 		"Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6485 		ch->seid, ch->vsi_number, ch->stat_counter_idx,
6486 		ch->num_queue_pairs,
6487 		vsi->next_base_queue);
6488 	return ret;
6489 }
6490 
6491 /**
6492  * i40e_setup_channel - setup new channel using uplink element
6493  * @pf: ptr to PF device
6494  * @vsi: pointer to the VSI to set up the channel within
6495  * @ch: ptr to channel structure
6496  *
6497  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6498  * and uplink switching element (uplink_seid)
6499  **/
6500 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6501 			       struct i40e_channel *ch)
6502 {
6503 	struct i40e_vsi *main_vsi;
6504 	u8 vsi_type;
6505 	u16 seid;
6506 	int ret;
6507 
6508 	if (vsi->type == I40E_VSI_MAIN) {
6509 		vsi_type = I40E_VSI_VMDQ2;
6510 	} else {
6511 		dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6512 			vsi->type);
6513 		return false;
6514 	}
6515 
6516 	/* underlying switching element */
6517 	main_vsi = i40e_pf_get_main_vsi(pf);
6518 	seid = main_vsi->uplink_seid;
6519 
6520 	/* create channel (VSI), configure TX rings */
6521 	ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6522 	if (ret) {
6523 		dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6524 		return false;
6525 	}
6526 
6527 	return ch->initialized ? true : false;
6528 }
6529 
6530 /**
6531  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6532  * @vsi: ptr to VSI which has PF backing
6533  *
6534  * Sets up switch mode correctly if it needs to be changed and perform
6535  * what are allowed modes.
6536  **/
6537 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6538 {
6539 	u8 mode;
6540 	struct i40e_pf *pf = vsi->back;
6541 	struct i40e_hw *hw = &pf->hw;
6542 	int ret;
6543 
6544 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6545 	if (ret)
6546 		return -EINVAL;
6547 
6548 	if (hw->dev_caps.switch_mode) {
6549 		/* if switch mode is set, support mode2 (non-tunneled for
6550 		 * cloud filter) for now
6551 		 */
6552 		u32 switch_mode = hw->dev_caps.switch_mode &
6553 				  I40E_SWITCH_MODE_MASK;
6554 		if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6555 			if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6556 				return 0;
6557 			dev_err(&pf->pdev->dev,
6558 				"Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6559 				hw->dev_caps.switch_mode);
6560 			return -EINVAL;
6561 		}
6562 	}
6563 
6564 	/* Set Bit 7 to be valid */
6565 	mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6566 
6567 	/* Set L4type for TCP support */
6568 	mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6569 
6570 	/* Set cloud filter mode */
6571 	mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6572 
6573 	/* Prep mode field for set_switch_config */
6574 	ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6575 					pf->last_sw_conf_valid_flags,
6576 					mode, NULL);
6577 	if (ret && hw->aq.asq_last_status != I40E_AQ_RC_ESRCH)
6578 		dev_err(&pf->pdev->dev,
6579 			"couldn't set switch config bits, err %pe aq_err %s\n",
6580 			ERR_PTR(ret),
6581 			i40e_aq_str(hw,
6582 				    hw->aq.asq_last_status));
6583 
6584 	return ret;
6585 }
6586 
6587 /**
6588  * i40e_create_queue_channel - function to create channel
6589  * @vsi: VSI to be configured
6590  * @ch: ptr to channel (it contains channel specific params)
6591  *
6592  * This function creates channel (VSI) using num_queues specified by user,
6593  * reconfigs RSS if needed.
6594  **/
6595 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6596 			      struct i40e_channel *ch)
6597 {
6598 	struct i40e_pf *pf = vsi->back;
6599 	bool reconfig_rss;
6600 	int err;
6601 
6602 	if (!ch)
6603 		return -EINVAL;
6604 
6605 	if (!ch->num_queue_pairs) {
6606 		dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6607 			ch->num_queue_pairs);
6608 		return -EINVAL;
6609 	}
6610 
6611 	/* validate user requested num_queues for channel */
6612 	err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6613 				       &reconfig_rss);
6614 	if (err) {
6615 		dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6616 			 ch->num_queue_pairs);
6617 		return -EINVAL;
6618 	}
6619 
6620 	/* By default we are in VEPA mode, if this is the first VF/VMDq
6621 	 * VSI to be added switch to VEB mode.
6622 	 */
6623 
6624 	if (!test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
6625 		set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
6626 
6627 		if (vsi->type == I40E_VSI_MAIN) {
6628 			if (i40e_is_tc_mqprio_enabled(pf))
6629 				i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
6630 			else
6631 				i40e_do_reset_safe(pf, I40E_PF_RESET_FLAG);
6632 		}
6633 		/* now onwards for main VSI, number of queues will be value
6634 		 * of TC0's queue count
6635 		 */
6636 	}
6637 
6638 	/* By this time, vsi->cnt_q_avail shall be set to non-zero and
6639 	 * it should be more than num_queues
6640 	 */
6641 	if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6642 		dev_dbg(&pf->pdev->dev,
6643 			"Error: cnt_q_avail (%u) less than num_queues %d\n",
6644 			vsi->cnt_q_avail, ch->num_queue_pairs);
6645 		return -EINVAL;
6646 	}
6647 
6648 	/* reconfig_rss only if vsi type is MAIN_VSI */
6649 	if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6650 		err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6651 		if (err) {
6652 			dev_info(&pf->pdev->dev,
6653 				 "Error: unable to reconfig rss for num_queues (%u)\n",
6654 				 ch->num_queue_pairs);
6655 			return -EINVAL;
6656 		}
6657 	}
6658 
6659 	if (!i40e_setup_channel(pf, vsi, ch)) {
6660 		dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6661 		return -EINVAL;
6662 	}
6663 
6664 	dev_info(&pf->pdev->dev,
6665 		 "Setup channel (id:%u) utilizing num_queues %d\n",
6666 		 ch->seid, ch->num_queue_pairs);
6667 
6668 	/* configure VSI for BW limit */
6669 	if (ch->max_tx_rate) {
6670 		u64 credits = ch->max_tx_rate;
6671 
6672 		if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6673 			return -EINVAL;
6674 
6675 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
6676 		dev_dbg(&pf->pdev->dev,
6677 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6678 			ch->max_tx_rate,
6679 			credits,
6680 			ch->seid);
6681 	}
6682 
6683 	/* in case of VF, this will be main SRIOV VSI */
6684 	ch->parent_vsi = vsi;
6685 
6686 	/* and update main_vsi's count for queue_available to use */
6687 	vsi->cnt_q_avail -= ch->num_queue_pairs;
6688 
6689 	return 0;
6690 }
6691 
6692 /**
6693  * i40e_configure_queue_channels - Add queue channel for the given TCs
6694  * @vsi: VSI to be configured
6695  *
6696  * Configures queue channel mapping to the given TCs
6697  **/
6698 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6699 {
6700 	struct i40e_channel *ch;
6701 	u64 max_rate = 0;
6702 	int ret = 0, i;
6703 
6704 	/* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6705 	vsi->tc_seid_map[0] = vsi->seid;
6706 	for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6707 		if (vsi->tc_config.enabled_tc & BIT(i)) {
6708 			ch = kzalloc(sizeof(*ch), GFP_KERNEL);
6709 			if (!ch) {
6710 				ret = -ENOMEM;
6711 				goto err_free;
6712 			}
6713 
6714 			INIT_LIST_HEAD(&ch->list);
6715 			ch->num_queue_pairs =
6716 				vsi->tc_config.tc_info[i].qcount;
6717 			ch->base_queue =
6718 				vsi->tc_config.tc_info[i].qoffset;
6719 
6720 			/* Bandwidth limit through tc interface is in bytes/s,
6721 			 * change to Mbit/s
6722 			 */
6723 			max_rate = vsi->mqprio_qopt.max_rate[i];
6724 			do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6725 			ch->max_tx_rate = max_rate;
6726 
6727 			list_add_tail(&ch->list, &vsi->ch_list);
6728 
6729 			ret = i40e_create_queue_channel(vsi, ch);
6730 			if (ret) {
6731 				dev_err(&vsi->back->pdev->dev,
6732 					"Failed creating queue channel with TC%d: queues %d\n",
6733 					i, ch->num_queue_pairs);
6734 				goto err_free;
6735 			}
6736 			vsi->tc_seid_map[i] = ch->seid;
6737 		}
6738 	}
6739 
6740 	/* reset to reconfigure TX queue contexts */
6741 	i40e_do_reset(vsi->back, I40E_PF_RESET_FLAG, true);
6742 	return ret;
6743 
6744 err_free:
6745 	i40e_remove_queue_channels(vsi);
6746 	return ret;
6747 }
6748 
6749 /**
6750  * i40e_veb_config_tc - Configure TCs for given VEB
6751  * @veb: given VEB
6752  * @enabled_tc: TC bitmap
6753  *
6754  * Configures given TC bitmap for VEB (switching) element
6755  **/
6756 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6757 {
6758 	struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6759 	struct i40e_pf *pf = veb->pf;
6760 	int ret = 0;
6761 	int i;
6762 
6763 	/* No TCs or already enabled TCs just return */
6764 	if (!enabled_tc || veb->enabled_tc == enabled_tc)
6765 		return ret;
6766 
6767 	bw_data.tc_valid_bits = enabled_tc;
6768 	/* bw_data.absolute_credits is not set (relative) */
6769 
6770 	/* Enable ETS TCs with equal BW Share for now */
6771 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6772 		if (enabled_tc & BIT(i))
6773 			bw_data.tc_bw_share_credits[i] = 1;
6774 	}
6775 
6776 	ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6777 						   &bw_data, NULL);
6778 	if (ret) {
6779 		dev_info(&pf->pdev->dev,
6780 			 "VEB bw config failed, err %pe aq_err %s\n",
6781 			 ERR_PTR(ret),
6782 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6783 		goto out;
6784 	}
6785 
6786 	/* Update the BW information */
6787 	ret = i40e_veb_get_bw_info(veb);
6788 	if (ret) {
6789 		dev_info(&pf->pdev->dev,
6790 			 "Failed getting veb bw config, err %pe aq_err %s\n",
6791 			 ERR_PTR(ret),
6792 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6793 	}
6794 
6795 out:
6796 	return ret;
6797 }
6798 
6799 #ifdef CONFIG_I40E_DCB
6800 /**
6801  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6802  * @pf: PF struct
6803  *
6804  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6805  * the caller would've quiesce all the VSIs before calling
6806  * this function
6807  **/
6808 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6809 {
6810 	struct i40e_vsi *vsi;
6811 	struct i40e_veb *veb;
6812 	u8 tc_map = 0;
6813 	int ret;
6814 	int v;
6815 
6816 	/* Enable the TCs available on PF to all VEBs */
6817 	tc_map = i40e_pf_get_tc_map(pf);
6818 	if (tc_map == I40E_DEFAULT_TRAFFIC_CLASS)
6819 		return;
6820 
6821 	i40e_pf_for_each_veb(pf, v, veb) {
6822 		ret = i40e_veb_config_tc(veb, tc_map);
6823 		if (ret) {
6824 			dev_info(&pf->pdev->dev,
6825 				 "Failed configuring TC for VEB seid=%d\n",
6826 				 veb->seid);
6827 			/* Will try to configure as many components */
6828 		}
6829 	}
6830 
6831 	/* Update each VSI */
6832 	i40e_pf_for_each_vsi(pf, v, vsi) {
6833 		/* - Enable all TCs for the LAN VSI
6834 		 * - For all others keep them at TC0 for now
6835 		 */
6836 		if (vsi->type == I40E_VSI_MAIN)
6837 			tc_map = i40e_pf_get_tc_map(pf);
6838 		else
6839 			tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6840 
6841 		ret = i40e_vsi_config_tc(vsi, tc_map);
6842 		if (ret) {
6843 			dev_info(&pf->pdev->dev,
6844 				 "Failed configuring TC for VSI seid=%d\n",
6845 				 vsi->seid);
6846 			/* Will try to configure as many components */
6847 		} else {
6848 			/* Re-configure VSI vectors based on updated TC map */
6849 			i40e_vsi_map_rings_to_vectors(vsi);
6850 			if (vsi->netdev)
6851 				i40e_dcbnl_set_all(vsi);
6852 		}
6853 	}
6854 }
6855 
6856 /**
6857  * i40e_resume_port_tx - Resume port Tx
6858  * @pf: PF struct
6859  *
6860  * Resume a port's Tx and issue a PF reset in case of failure to
6861  * resume.
6862  **/
6863 static int i40e_resume_port_tx(struct i40e_pf *pf)
6864 {
6865 	struct i40e_hw *hw = &pf->hw;
6866 	int ret;
6867 
6868 	ret = i40e_aq_resume_port_tx(hw, NULL);
6869 	if (ret) {
6870 		dev_info(&pf->pdev->dev,
6871 			 "Resume Port Tx failed, err %pe aq_err %s\n",
6872 			  ERR_PTR(ret),
6873 			  i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6874 		/* Schedule PF reset to recover */
6875 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6876 		i40e_service_event_schedule(pf);
6877 	}
6878 
6879 	return ret;
6880 }
6881 
6882 /**
6883  * i40e_suspend_port_tx - Suspend port Tx
6884  * @pf: PF struct
6885  *
6886  * Suspend a port's Tx and issue a PF reset in case of failure.
6887  **/
6888 static int i40e_suspend_port_tx(struct i40e_pf *pf)
6889 {
6890 	struct i40e_hw *hw = &pf->hw;
6891 	int ret;
6892 
6893 	ret = i40e_aq_suspend_port_tx(hw, pf->mac_seid, NULL);
6894 	if (ret) {
6895 		dev_info(&pf->pdev->dev,
6896 			 "Suspend Port Tx failed, err %pe aq_err %s\n",
6897 			 ERR_PTR(ret),
6898 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6899 		/* Schedule PF reset to recover */
6900 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6901 		i40e_service_event_schedule(pf);
6902 	}
6903 
6904 	return ret;
6905 }
6906 
6907 /**
6908  * i40e_hw_set_dcb_config - Program new DCBX settings into HW
6909  * @pf: PF being configured
6910  * @new_cfg: New DCBX configuration
6911  *
6912  * Program DCB settings into HW and reconfigure VEB/VSIs on
6913  * given PF. Uses "Set LLDP MIB" AQC to program the hardware.
6914  **/
6915 static int i40e_hw_set_dcb_config(struct i40e_pf *pf,
6916 				  struct i40e_dcbx_config *new_cfg)
6917 {
6918 	struct i40e_dcbx_config *old_cfg = &pf->hw.local_dcbx_config;
6919 	int ret;
6920 
6921 	/* Check if need reconfiguration */
6922 	if (!memcmp(&new_cfg, &old_cfg, sizeof(new_cfg))) {
6923 		dev_dbg(&pf->pdev->dev, "No Change in DCB Config required.\n");
6924 		return 0;
6925 	}
6926 
6927 	/* Config change disable all VSIs */
6928 	i40e_pf_quiesce_all_vsi(pf);
6929 
6930 	/* Copy the new config to the current config */
6931 	*old_cfg = *new_cfg;
6932 	old_cfg->etsrec = old_cfg->etscfg;
6933 	ret = i40e_set_dcb_config(&pf->hw);
6934 	if (ret) {
6935 		dev_info(&pf->pdev->dev,
6936 			 "Set DCB Config failed, err %pe aq_err %s\n",
6937 			 ERR_PTR(ret),
6938 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6939 		goto out;
6940 	}
6941 
6942 	/* Changes in configuration update VEB/VSI */
6943 	i40e_dcb_reconfigure(pf);
6944 out:
6945 	/* In case of reset do not try to resume anything */
6946 	if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
6947 		/* Re-start the VSIs if disabled */
6948 		ret = i40e_resume_port_tx(pf);
6949 		/* In case of error no point in resuming VSIs */
6950 		if (ret)
6951 			goto err;
6952 		i40e_pf_unquiesce_all_vsi(pf);
6953 	}
6954 err:
6955 	return ret;
6956 }
6957 
6958 /**
6959  * i40e_hw_dcb_config - Program new DCBX settings into HW
6960  * @pf: PF being configured
6961  * @new_cfg: New DCBX configuration
6962  *
6963  * Program DCB settings into HW and reconfigure VEB/VSIs on
6964  * given PF
6965  **/
6966 int i40e_hw_dcb_config(struct i40e_pf *pf, struct i40e_dcbx_config *new_cfg)
6967 {
6968 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6969 	u8 prio_type[I40E_MAX_TRAFFIC_CLASS] = {0};
6970 	u32 mfs_tc[I40E_MAX_TRAFFIC_CLASS];
6971 	struct i40e_dcbx_config *old_cfg;
6972 	u8 mode[I40E_MAX_TRAFFIC_CLASS];
6973 	struct i40e_rx_pb_config pb_cfg;
6974 	struct i40e_hw *hw = &pf->hw;
6975 	u8 num_ports = hw->num_ports;
6976 	bool need_reconfig;
6977 	int ret = -EINVAL;
6978 	u8 lltc_map = 0;
6979 	u8 tc_map = 0;
6980 	u8 new_numtc;
6981 	u8 i;
6982 
6983 	dev_dbg(&pf->pdev->dev, "Configuring DCB registers directly\n");
6984 	/* Un-pack information to Program ETS HW via shared API
6985 	 * numtc, tcmap
6986 	 * LLTC map
6987 	 * ETS/NON-ETS arbiter mode
6988 	 * max exponent (credit refills)
6989 	 * Total number of ports
6990 	 * PFC priority bit-map
6991 	 * Priority Table
6992 	 * BW % per TC
6993 	 * Arbiter mode between UPs sharing same TC
6994 	 * TSA table (ETS or non-ETS)
6995 	 * EEE enabled or not
6996 	 * MFS TC table
6997 	 */
6998 
6999 	new_numtc = i40e_dcb_get_num_tc(new_cfg);
7000 
7001 	memset(&ets_data, 0, sizeof(ets_data));
7002 	for (i = 0; i < new_numtc; i++) {
7003 		tc_map |= BIT(i);
7004 		switch (new_cfg->etscfg.tsatable[i]) {
7005 		case I40E_IEEE_TSA_ETS:
7006 			prio_type[i] = I40E_DCB_PRIO_TYPE_ETS;
7007 			ets_data.tc_bw_share_credits[i] =
7008 					new_cfg->etscfg.tcbwtable[i];
7009 			break;
7010 		case I40E_IEEE_TSA_STRICT:
7011 			prio_type[i] = I40E_DCB_PRIO_TYPE_STRICT;
7012 			lltc_map |= BIT(i);
7013 			ets_data.tc_bw_share_credits[i] =
7014 					I40E_DCB_STRICT_PRIO_CREDITS;
7015 			break;
7016 		default:
7017 			/* Invalid TSA type */
7018 			need_reconfig = false;
7019 			goto out;
7020 		}
7021 	}
7022 
7023 	old_cfg = &hw->local_dcbx_config;
7024 	/* Check if need reconfiguration */
7025 	need_reconfig = i40e_dcb_need_reconfig(pf, old_cfg, new_cfg);
7026 
7027 	/* If needed, enable/disable frame tagging, disable all VSIs
7028 	 * and suspend port tx
7029 	 */
7030 	if (need_reconfig) {
7031 		/* Enable DCB tagging only when more than one TC */
7032 		if (new_numtc > 1)
7033 			set_bit(I40E_FLAG_DCB_ENA, pf->flags);
7034 		else
7035 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7036 
7037 		set_bit(__I40E_PORT_SUSPENDED, pf->state);
7038 		/* Reconfiguration needed quiesce all VSIs */
7039 		i40e_pf_quiesce_all_vsi(pf);
7040 		ret = i40e_suspend_port_tx(pf);
7041 		if (ret)
7042 			goto err;
7043 	}
7044 
7045 	/* Configure Port ETS Tx Scheduler */
7046 	ets_data.tc_valid_bits = tc_map;
7047 	ets_data.tc_strict_priority_flags = lltc_map;
7048 	ret = i40e_aq_config_switch_comp_ets
7049 		(hw, pf->mac_seid, &ets_data,
7050 		 i40e_aqc_opc_modify_switching_comp_ets, NULL);
7051 	if (ret) {
7052 		dev_info(&pf->pdev->dev,
7053 			 "Modify Port ETS failed, err %pe aq_err %s\n",
7054 			 ERR_PTR(ret),
7055 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7056 		goto out;
7057 	}
7058 
7059 	/* Configure Rx ETS HW */
7060 	memset(&mode, I40E_DCB_ARB_MODE_ROUND_ROBIN, sizeof(mode));
7061 	i40e_dcb_hw_set_num_tc(hw, new_numtc);
7062 	i40e_dcb_hw_rx_fifo_config(hw, I40E_DCB_ARB_MODE_ROUND_ROBIN,
7063 				   I40E_DCB_ARB_MODE_STRICT_PRIORITY,
7064 				   I40E_DCB_DEFAULT_MAX_EXPONENT,
7065 				   lltc_map);
7066 	i40e_dcb_hw_rx_cmd_monitor_config(hw, new_numtc, num_ports);
7067 	i40e_dcb_hw_rx_ets_bw_config(hw, new_cfg->etscfg.tcbwtable, mode,
7068 				     prio_type);
7069 	i40e_dcb_hw_pfc_config(hw, new_cfg->pfc.pfcenable,
7070 			       new_cfg->etscfg.prioritytable);
7071 	i40e_dcb_hw_rx_up2tc_config(hw, new_cfg->etscfg.prioritytable);
7072 
7073 	/* Configure Rx Packet Buffers in HW */
7074 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7075 		struct i40e_vsi *main_vsi = i40e_pf_get_main_vsi(pf);
7076 
7077 		mfs_tc[i] = main_vsi->netdev->mtu;
7078 		mfs_tc[i] += I40E_PACKET_HDR_PAD;
7079 	}
7080 
7081 	i40e_dcb_hw_calculate_pool_sizes(hw, num_ports,
7082 					 false, new_cfg->pfc.pfcenable,
7083 					 mfs_tc, &pb_cfg);
7084 	i40e_dcb_hw_rx_pb_config(hw, &pf->pb_cfg, &pb_cfg);
7085 
7086 	/* Update the local Rx Packet buffer config */
7087 	pf->pb_cfg = pb_cfg;
7088 
7089 	/* Inform the FW about changes to DCB configuration */
7090 	ret = i40e_aq_dcb_updated(&pf->hw, NULL);
7091 	if (ret) {
7092 		dev_info(&pf->pdev->dev,
7093 			 "DCB Updated failed, err %pe aq_err %s\n",
7094 			 ERR_PTR(ret),
7095 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7096 		goto out;
7097 	}
7098 
7099 	/* Update the port DCBx configuration */
7100 	*old_cfg = *new_cfg;
7101 
7102 	/* Changes in configuration update VEB/VSI */
7103 	i40e_dcb_reconfigure(pf);
7104 out:
7105 	/* Re-start the VSIs if disabled */
7106 	if (need_reconfig) {
7107 		ret = i40e_resume_port_tx(pf);
7108 
7109 		clear_bit(__I40E_PORT_SUSPENDED, pf->state);
7110 		/* In case of error no point in resuming VSIs */
7111 		if (ret)
7112 			goto err;
7113 
7114 		/* Wait for the PF's queues to be disabled */
7115 		ret = i40e_pf_wait_queues_disabled(pf);
7116 		if (ret) {
7117 			/* Schedule PF reset to recover */
7118 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
7119 			i40e_service_event_schedule(pf);
7120 			goto err;
7121 		} else {
7122 			i40e_pf_unquiesce_all_vsi(pf);
7123 			set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7124 			set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
7125 		}
7126 		/* registers are set, lets apply */
7127 		if (test_bit(I40E_HW_CAP_USE_SET_LLDP_MIB, pf->hw.caps))
7128 			ret = i40e_hw_set_dcb_config(pf, new_cfg);
7129 	}
7130 
7131 err:
7132 	return ret;
7133 }
7134 
7135 /**
7136  * i40e_dcb_sw_default_config - Set default DCB configuration when DCB in SW
7137  * @pf: PF being queried
7138  *
7139  * Set default DCB configuration in case DCB is to be done in SW.
7140  **/
7141 int i40e_dcb_sw_default_config(struct i40e_pf *pf)
7142 {
7143 	struct i40e_dcbx_config *dcb_cfg = &pf->hw.local_dcbx_config;
7144 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
7145 	struct i40e_hw *hw = &pf->hw;
7146 	int err;
7147 
7148 	if (test_bit(I40E_HW_CAP_USE_SET_LLDP_MIB, pf->hw.caps)) {
7149 		/* Update the local cached instance with TC0 ETS */
7150 		memset(&pf->tmp_cfg, 0, sizeof(struct i40e_dcbx_config));
7151 		pf->tmp_cfg.etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7152 		pf->tmp_cfg.etscfg.maxtcs = 0;
7153 		pf->tmp_cfg.etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7154 		pf->tmp_cfg.etscfg.tsatable[0] = I40E_IEEE_TSA_ETS;
7155 		pf->tmp_cfg.pfc.willing = I40E_IEEE_DEFAULT_PFC_WILLING;
7156 		pf->tmp_cfg.pfc.pfccap = I40E_MAX_TRAFFIC_CLASS;
7157 		/* FW needs one App to configure HW */
7158 		pf->tmp_cfg.numapps = I40E_IEEE_DEFAULT_NUM_APPS;
7159 		pf->tmp_cfg.app[0].selector = I40E_APP_SEL_ETHTYPE;
7160 		pf->tmp_cfg.app[0].priority = I40E_IEEE_DEFAULT_APP_PRIO;
7161 		pf->tmp_cfg.app[0].protocolid = I40E_APP_PROTOID_FCOE;
7162 
7163 		return i40e_hw_set_dcb_config(pf, &pf->tmp_cfg);
7164 	}
7165 
7166 	memset(&ets_data, 0, sizeof(ets_data));
7167 	ets_data.tc_valid_bits = I40E_DEFAULT_TRAFFIC_CLASS; /* TC0 only */
7168 	ets_data.tc_strict_priority_flags = 0; /* ETS */
7169 	ets_data.tc_bw_share_credits[0] = I40E_IEEE_DEFAULT_ETS_TCBW; /* 100% to TC0 */
7170 
7171 	/* Enable ETS on the Physical port */
7172 	err = i40e_aq_config_switch_comp_ets
7173 		(hw, pf->mac_seid, &ets_data,
7174 		 i40e_aqc_opc_enable_switching_comp_ets, NULL);
7175 	if (err) {
7176 		dev_info(&pf->pdev->dev,
7177 			 "Enable Port ETS failed, err %pe aq_err %s\n",
7178 			 ERR_PTR(err),
7179 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7180 		err = -ENOENT;
7181 		goto out;
7182 	}
7183 
7184 	/* Update the local cached instance with TC0 ETS */
7185 	dcb_cfg->etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7186 	dcb_cfg->etscfg.cbs = 0;
7187 	dcb_cfg->etscfg.maxtcs = I40E_MAX_TRAFFIC_CLASS;
7188 	dcb_cfg->etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7189 
7190 out:
7191 	return err;
7192 }
7193 
7194 /**
7195  * i40e_init_pf_dcb - Initialize DCB configuration
7196  * @pf: PF being configured
7197  *
7198  * Query the current DCB configuration and cache it
7199  * in the hardware structure
7200  **/
7201 static int i40e_init_pf_dcb(struct i40e_pf *pf)
7202 {
7203 	struct i40e_hw *hw = &pf->hw;
7204 	int err;
7205 
7206 	/* Do not enable DCB for SW1 and SW2 images even if the FW is capable
7207 	 * Also do not enable DCBx if FW LLDP agent is disabled
7208 	 */
7209 	if (test_bit(I40E_HW_CAP_NO_DCB_SUPPORT, pf->hw.caps)) {
7210 		dev_info(&pf->pdev->dev, "DCB is not supported.\n");
7211 		err = -EOPNOTSUPP;
7212 		goto out;
7213 	}
7214 	if (test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags)) {
7215 		dev_info(&pf->pdev->dev, "FW LLDP is disabled, attempting SW DCB\n");
7216 		err = i40e_dcb_sw_default_config(pf);
7217 		if (err) {
7218 			dev_info(&pf->pdev->dev, "Could not initialize SW DCB\n");
7219 			goto out;
7220 		}
7221 		dev_info(&pf->pdev->dev, "SW DCB initialization succeeded.\n");
7222 		pf->dcbx_cap = DCB_CAP_DCBX_HOST |
7223 			       DCB_CAP_DCBX_VER_IEEE;
7224 		/* at init capable but disabled */
7225 		set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
7226 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7227 		goto out;
7228 	}
7229 	err = i40e_init_dcb(hw, true);
7230 	if (!err) {
7231 		/* Device/Function is not DCBX capable */
7232 		if ((!hw->func_caps.dcb) ||
7233 		    (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
7234 			dev_info(&pf->pdev->dev,
7235 				 "DCBX offload is not supported or is disabled for this PF.\n");
7236 		} else {
7237 			/* When status is not DISABLED then DCBX in FW */
7238 			pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
7239 				       DCB_CAP_DCBX_VER_IEEE;
7240 
7241 			set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
7242 			/* Enable DCB tagging only when more than one TC
7243 			 * or explicitly disable if only one TC
7244 			 */
7245 			if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
7246 				set_bit(I40E_FLAG_DCB_ENA, pf->flags);
7247 			else
7248 				clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7249 			dev_dbg(&pf->pdev->dev,
7250 				"DCBX offload is supported for this PF.\n");
7251 		}
7252 	} else if (pf->hw.aq.asq_last_status == I40E_AQ_RC_EPERM) {
7253 		dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
7254 		set_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags);
7255 	} else {
7256 		dev_info(&pf->pdev->dev,
7257 			 "Query for DCB configuration failed, err %pe aq_err %s\n",
7258 			 ERR_PTR(err),
7259 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7260 	}
7261 
7262 out:
7263 	return err;
7264 }
7265 #endif /* CONFIG_I40E_DCB */
7266 
7267 /**
7268  * i40e_print_link_message - print link up or down
7269  * @vsi: the VSI for which link needs a message
7270  * @isup: true of link is up, false otherwise
7271  */
7272 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
7273 {
7274 	enum i40e_aq_link_speed new_speed;
7275 	struct i40e_pf *pf = vsi->back;
7276 	char *speed = "Unknown";
7277 	char *fc = "Unknown";
7278 	char *fec = "";
7279 	char *req_fec = "";
7280 	char *an = "";
7281 
7282 	if (isup)
7283 		new_speed = pf->hw.phy.link_info.link_speed;
7284 	else
7285 		new_speed = I40E_LINK_SPEED_UNKNOWN;
7286 
7287 	if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
7288 		return;
7289 	vsi->current_isup = isup;
7290 	vsi->current_speed = new_speed;
7291 	if (!isup) {
7292 		netdev_info(vsi->netdev, "NIC Link is Down\n");
7293 		return;
7294 	}
7295 
7296 	/* Warn user if link speed on NPAR enabled partition is not at
7297 	 * least 10GB
7298 	 */
7299 	if (pf->hw.func_caps.npar_enable &&
7300 	    (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
7301 	     pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
7302 		netdev_warn(vsi->netdev,
7303 			    "The partition detected link speed that is less than 10Gbps\n");
7304 
7305 	switch (pf->hw.phy.link_info.link_speed) {
7306 	case I40E_LINK_SPEED_40GB:
7307 		speed = "40 G";
7308 		break;
7309 	case I40E_LINK_SPEED_20GB:
7310 		speed = "20 G";
7311 		break;
7312 	case I40E_LINK_SPEED_25GB:
7313 		speed = "25 G";
7314 		break;
7315 	case I40E_LINK_SPEED_10GB:
7316 		speed = "10 G";
7317 		break;
7318 	case I40E_LINK_SPEED_5GB:
7319 		speed = "5 G";
7320 		break;
7321 	case I40E_LINK_SPEED_2_5GB:
7322 		speed = "2.5 G";
7323 		break;
7324 	case I40E_LINK_SPEED_1GB:
7325 		speed = "1000 M";
7326 		break;
7327 	case I40E_LINK_SPEED_100MB:
7328 		speed = "100 M";
7329 		break;
7330 	default:
7331 		break;
7332 	}
7333 
7334 	switch (pf->hw.fc.current_mode) {
7335 	case I40E_FC_FULL:
7336 		fc = "RX/TX";
7337 		break;
7338 	case I40E_FC_TX_PAUSE:
7339 		fc = "TX";
7340 		break;
7341 	case I40E_FC_RX_PAUSE:
7342 		fc = "RX";
7343 		break;
7344 	default:
7345 		fc = "None";
7346 		break;
7347 	}
7348 
7349 	if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
7350 		req_fec = "None";
7351 		fec = "None";
7352 		an = "False";
7353 
7354 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7355 			an = "True";
7356 
7357 		if (pf->hw.phy.link_info.fec_info &
7358 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7359 			fec = "CL74 FC-FEC/BASE-R";
7360 		else if (pf->hw.phy.link_info.fec_info &
7361 			 I40E_AQ_CONFIG_FEC_RS_ENA)
7362 			fec = "CL108 RS-FEC";
7363 
7364 		/* 'CL108 RS-FEC' should be displayed when RS is requested, or
7365 		 * both RS and FC are requested
7366 		 */
7367 		if (vsi->back->hw.phy.link_info.req_fec_info &
7368 		    (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
7369 			if (vsi->back->hw.phy.link_info.req_fec_info &
7370 			    I40E_AQ_REQUEST_FEC_RS)
7371 				req_fec = "CL108 RS-FEC";
7372 			else
7373 				req_fec = "CL74 FC-FEC/BASE-R";
7374 		}
7375 		netdev_info(vsi->netdev,
7376 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7377 			    speed, req_fec, fec, an, fc);
7378 	} else if (pf->hw.device_id == I40E_DEV_ID_KX_X722) {
7379 		req_fec = "None";
7380 		fec = "None";
7381 		an = "False";
7382 
7383 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7384 			an = "True";
7385 
7386 		if (pf->hw.phy.link_info.fec_info &
7387 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7388 			fec = "CL74 FC-FEC/BASE-R";
7389 
7390 		if (pf->hw.phy.link_info.req_fec_info &
7391 		    I40E_AQ_REQUEST_FEC_KR)
7392 			req_fec = "CL74 FC-FEC/BASE-R";
7393 
7394 		netdev_info(vsi->netdev,
7395 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7396 			    speed, req_fec, fec, an, fc);
7397 	} else {
7398 		netdev_info(vsi->netdev,
7399 			    "NIC Link is Up, %sbps Full Duplex, Flow Control: %s\n",
7400 			    speed, fc);
7401 	}
7402 
7403 }
7404 
7405 /**
7406  * i40e_up_complete - Finish the last steps of bringing up a connection
7407  * @vsi: the VSI being configured
7408  **/
7409 static int i40e_up_complete(struct i40e_vsi *vsi)
7410 {
7411 	struct i40e_pf *pf = vsi->back;
7412 	int err;
7413 
7414 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
7415 		i40e_vsi_configure_msix(vsi);
7416 	else
7417 		i40e_configure_msi_and_legacy(vsi);
7418 
7419 	/* start rings */
7420 	err = i40e_vsi_start_rings(vsi);
7421 	if (err)
7422 		return err;
7423 
7424 	clear_bit(__I40E_VSI_DOWN, vsi->state);
7425 	i40e_napi_enable_all(vsi);
7426 	i40e_vsi_enable_irq(vsi);
7427 
7428 	if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
7429 	    (vsi->netdev)) {
7430 		i40e_print_link_message(vsi, true);
7431 		netif_tx_start_all_queues(vsi->netdev);
7432 		netif_carrier_on(vsi->netdev);
7433 	}
7434 
7435 	/* replay FDIR SB filters */
7436 	if (vsi->type == I40E_VSI_FDIR) {
7437 		/* reset fd counters */
7438 		pf->fd_add_err = 0;
7439 		pf->fd_atr_cnt = 0;
7440 		i40e_fdir_filter_restore(vsi);
7441 	}
7442 
7443 	/* On the next run of the service_task, notify any clients of the new
7444 	 * opened netdev
7445 	 */
7446 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7447 	i40e_service_event_schedule(pf);
7448 
7449 	return 0;
7450 }
7451 
7452 /**
7453  * i40e_vsi_reinit_locked - Reset the VSI
7454  * @vsi: the VSI being configured
7455  *
7456  * Rebuild the ring structs after some configuration
7457  * has changed, e.g. MTU size.
7458  **/
7459 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
7460 {
7461 	struct i40e_pf *pf = vsi->back;
7462 
7463 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
7464 		usleep_range(1000, 2000);
7465 	i40e_down(vsi);
7466 
7467 	i40e_up(vsi);
7468 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
7469 }
7470 
7471 /**
7472  * i40e_force_link_state - Force the link status
7473  * @pf: board private structure
7474  * @is_up: whether the link state should be forced up or down
7475  **/
7476 static int i40e_force_link_state(struct i40e_pf *pf, bool is_up)
7477 {
7478 	struct i40e_aq_get_phy_abilities_resp abilities;
7479 	struct i40e_aq_set_phy_config config = {0};
7480 	bool non_zero_phy_type = is_up;
7481 	struct i40e_hw *hw = &pf->hw;
7482 	u64 mask;
7483 	u8 speed;
7484 	int err;
7485 
7486 	/* Card might've been put in an unstable state by other drivers
7487 	 * and applications, which causes incorrect speed values being
7488 	 * set on startup. In order to clear speed registers, we call
7489 	 * get_phy_capabilities twice, once to get initial state of
7490 	 * available speeds, and once to get current PHY config.
7491 	 */
7492 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
7493 					   NULL);
7494 	if (err) {
7495 		dev_err(&pf->pdev->dev,
7496 			"failed to get phy cap., ret =  %pe last_status =  %s\n",
7497 			ERR_PTR(err),
7498 			i40e_aq_str(hw, hw->aq.asq_last_status));
7499 		return err;
7500 	}
7501 	speed = abilities.link_speed;
7502 
7503 	/* Get the current phy config */
7504 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
7505 					   NULL);
7506 	if (err) {
7507 		dev_err(&pf->pdev->dev,
7508 			"failed to get phy cap., ret =  %pe last_status =  %s\n",
7509 			ERR_PTR(err),
7510 			i40e_aq_str(hw, hw->aq.asq_last_status));
7511 		return err;
7512 	}
7513 
7514 	/* If link needs to go up, but was not forced to go down,
7515 	 * and its speed values are OK, no need for a flap
7516 	 * if non_zero_phy_type was set, still need to force up
7517 	 */
7518 	if (test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags))
7519 		non_zero_phy_type = true;
7520 	else if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
7521 		return 0;
7522 
7523 	/* To force link we need to set bits for all supported PHY types,
7524 	 * but there are now more than 32, so we need to split the bitmap
7525 	 * across two fields.
7526 	 */
7527 	mask = I40E_PHY_TYPES_BITMASK;
7528 	config.phy_type =
7529 		non_zero_phy_type ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
7530 	config.phy_type_ext =
7531 		non_zero_phy_type ? (u8)((mask >> 32) & 0xff) : 0;
7532 	/* Copy the old settings, except of phy_type */
7533 	config.abilities = abilities.abilities;
7534 	if (test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags)) {
7535 		if (is_up)
7536 			config.abilities |= I40E_AQ_PHY_ENABLE_LINK;
7537 		else
7538 			config.abilities &= ~(I40E_AQ_PHY_ENABLE_LINK);
7539 	}
7540 	if (abilities.link_speed != 0)
7541 		config.link_speed = abilities.link_speed;
7542 	else
7543 		config.link_speed = speed;
7544 	config.eee_capability = abilities.eee_capability;
7545 	config.eeer = abilities.eeer_val;
7546 	config.low_power_ctrl = abilities.d3_lpan;
7547 	config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
7548 			    I40E_AQ_PHY_FEC_CONFIG_MASK;
7549 	err = i40e_aq_set_phy_config(hw, &config, NULL);
7550 
7551 	if (err) {
7552 		dev_err(&pf->pdev->dev,
7553 			"set phy config ret =  %pe last_status =  %s\n",
7554 			ERR_PTR(err),
7555 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7556 		return err;
7557 	}
7558 
7559 	/* Update the link info */
7560 	err = i40e_update_link_info(hw);
7561 	if (err) {
7562 		/* Wait a little bit (on 40G cards it sometimes takes a really
7563 		 * long time for link to come back from the atomic reset)
7564 		 * and try once more
7565 		 */
7566 		msleep(1000);
7567 		i40e_update_link_info(hw);
7568 	}
7569 
7570 	i40e_aq_set_link_restart_an(hw, is_up, NULL);
7571 
7572 	return 0;
7573 }
7574 
7575 /**
7576  * i40e_up - Bring the connection back up after being down
7577  * @vsi: the VSI being configured
7578  **/
7579 int i40e_up(struct i40e_vsi *vsi)
7580 {
7581 	int err;
7582 
7583 	if (vsi->type == I40E_VSI_MAIN &&
7584 	    (test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags) ||
7585 	     test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, vsi->back->flags)))
7586 		i40e_force_link_state(vsi->back, true);
7587 
7588 	err = i40e_vsi_configure(vsi);
7589 	if (!err)
7590 		err = i40e_up_complete(vsi);
7591 
7592 	return err;
7593 }
7594 
7595 /**
7596  * i40e_down - Shutdown the connection processing
7597  * @vsi: the VSI being stopped
7598  **/
7599 void i40e_down(struct i40e_vsi *vsi)
7600 {
7601 	int i;
7602 
7603 	/* It is assumed that the caller of this function
7604 	 * sets the vsi->state __I40E_VSI_DOWN bit.
7605 	 */
7606 	if (vsi->netdev) {
7607 		netif_carrier_off(vsi->netdev);
7608 		netif_tx_disable(vsi->netdev);
7609 	}
7610 	i40e_vsi_disable_irq(vsi);
7611 	i40e_vsi_stop_rings(vsi);
7612 	if (vsi->type == I40E_VSI_MAIN &&
7613 	   (test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags) ||
7614 	    test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, vsi->back->flags)))
7615 		i40e_force_link_state(vsi->back, false);
7616 	i40e_napi_disable_all(vsi);
7617 
7618 	for (i = 0; i < vsi->num_queue_pairs; i++) {
7619 		i40e_clean_tx_ring(vsi->tx_rings[i]);
7620 		if (i40e_enabled_xdp_vsi(vsi)) {
7621 			/* Make sure that in-progress ndo_xdp_xmit and
7622 			 * ndo_xsk_wakeup calls are completed.
7623 			 */
7624 			synchronize_rcu();
7625 			i40e_clean_tx_ring(vsi->xdp_rings[i]);
7626 		}
7627 		i40e_clean_rx_ring(vsi->rx_rings[i]);
7628 	}
7629 
7630 }
7631 
7632 /**
7633  * i40e_validate_mqprio_qopt- validate queue mapping info
7634  * @vsi: the VSI being configured
7635  * @mqprio_qopt: queue parametrs
7636  **/
7637 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
7638 				     struct tc_mqprio_qopt_offload *mqprio_qopt)
7639 {
7640 	u64 sum_max_rate = 0;
7641 	u64 max_rate = 0;
7642 	int i;
7643 
7644 	if (mqprio_qopt->qopt.offset[0] != 0 ||
7645 	    mqprio_qopt->qopt.num_tc < 1 ||
7646 	    mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
7647 		return -EINVAL;
7648 	for (i = 0; ; i++) {
7649 		if (!mqprio_qopt->qopt.count[i])
7650 			return -EINVAL;
7651 		if (mqprio_qopt->min_rate[i]) {
7652 			dev_err(&vsi->back->pdev->dev,
7653 				"Invalid min tx rate (greater than 0) specified\n");
7654 			return -EINVAL;
7655 		}
7656 		max_rate = mqprio_qopt->max_rate[i];
7657 		do_div(max_rate, I40E_BW_MBPS_DIVISOR);
7658 		sum_max_rate += max_rate;
7659 
7660 		if (i >= mqprio_qopt->qopt.num_tc - 1)
7661 			break;
7662 		if (mqprio_qopt->qopt.offset[i + 1] !=
7663 		    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7664 			return -EINVAL;
7665 	}
7666 	if (vsi->num_queue_pairs <
7667 	    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
7668 		dev_err(&vsi->back->pdev->dev,
7669 			"Failed to create traffic channel, insufficient number of queues.\n");
7670 		return -EINVAL;
7671 	}
7672 	if (sum_max_rate > i40e_get_link_speed(vsi)) {
7673 		dev_err(&vsi->back->pdev->dev,
7674 			"Invalid max tx rate specified\n");
7675 		return -EINVAL;
7676 	}
7677 	return 0;
7678 }
7679 
7680 /**
7681  * i40e_vsi_set_default_tc_config - set default values for tc configuration
7682  * @vsi: the VSI being configured
7683  **/
7684 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
7685 {
7686 	u16 qcount;
7687 	int i;
7688 
7689 	/* Only TC0 is enabled */
7690 	vsi->tc_config.numtc = 1;
7691 	vsi->tc_config.enabled_tc = 1;
7692 	qcount = min_t(int, vsi->alloc_queue_pairs,
7693 		       i40e_pf_get_max_q_per_tc(vsi->back));
7694 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7695 		/* For the TC that is not enabled set the offset to default
7696 		 * queue and allocate one queue for the given TC.
7697 		 */
7698 		vsi->tc_config.tc_info[i].qoffset = 0;
7699 		if (i == 0)
7700 			vsi->tc_config.tc_info[i].qcount = qcount;
7701 		else
7702 			vsi->tc_config.tc_info[i].qcount = 1;
7703 		vsi->tc_config.tc_info[i].netdev_tc = 0;
7704 	}
7705 }
7706 
7707 /**
7708  * i40e_del_macvlan_filter
7709  * @hw: pointer to the HW structure
7710  * @seid: seid of the channel VSI
7711  * @macaddr: the mac address to apply as a filter
7712  * @aq_err: store the admin Q error
7713  *
7714  * This function deletes a mac filter on the channel VSI which serves as the
7715  * macvlan. Returns 0 on success.
7716  **/
7717 static int i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
7718 				   const u8 *macaddr, int *aq_err)
7719 {
7720 	struct i40e_aqc_remove_macvlan_element_data element;
7721 	int status;
7722 
7723 	memset(&element, 0, sizeof(element));
7724 	ether_addr_copy(element.mac_addr, macaddr);
7725 	element.vlan_tag = 0;
7726 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
7727 	status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
7728 	*aq_err = hw->aq.asq_last_status;
7729 
7730 	return status;
7731 }
7732 
7733 /**
7734  * i40e_add_macvlan_filter
7735  * @hw: pointer to the HW structure
7736  * @seid: seid of the channel VSI
7737  * @macaddr: the mac address to apply as a filter
7738  * @aq_err: store the admin Q error
7739  *
7740  * This function adds a mac filter on the channel VSI which serves as the
7741  * macvlan. Returns 0 on success.
7742  **/
7743 static int i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
7744 				   const u8 *macaddr, int *aq_err)
7745 {
7746 	struct i40e_aqc_add_macvlan_element_data element;
7747 	u16 cmd_flags = 0;
7748 	int status;
7749 
7750 	ether_addr_copy(element.mac_addr, macaddr);
7751 	element.vlan_tag = 0;
7752 	element.queue_number = 0;
7753 	element.match_method = I40E_AQC_MM_ERR_NO_RES;
7754 	cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
7755 	element.flags = cpu_to_le16(cmd_flags);
7756 	status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
7757 	*aq_err = hw->aq.asq_last_status;
7758 
7759 	return status;
7760 }
7761 
7762 /**
7763  * i40e_reset_ch_rings - Reset the queue contexts in a channel
7764  * @vsi: the VSI we want to access
7765  * @ch: the channel we want to access
7766  */
7767 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
7768 {
7769 	struct i40e_ring *tx_ring, *rx_ring;
7770 	u16 pf_q;
7771 	int i;
7772 
7773 	for (i = 0; i < ch->num_queue_pairs; i++) {
7774 		pf_q = ch->base_queue + i;
7775 		tx_ring = vsi->tx_rings[pf_q];
7776 		tx_ring->ch = NULL;
7777 		rx_ring = vsi->rx_rings[pf_q];
7778 		rx_ring->ch = NULL;
7779 	}
7780 }
7781 
7782 /**
7783  * i40e_free_macvlan_channels
7784  * @vsi: the VSI we want to access
7785  *
7786  * This function frees the Qs of the channel VSI from
7787  * the stack and also deletes the channel VSIs which
7788  * serve as macvlans.
7789  */
7790 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
7791 {
7792 	struct i40e_channel *ch, *ch_tmp;
7793 	int ret;
7794 
7795 	if (list_empty(&vsi->macvlan_list))
7796 		return;
7797 
7798 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7799 		struct i40e_vsi *parent_vsi;
7800 
7801 		if (i40e_is_channel_macvlan(ch)) {
7802 			i40e_reset_ch_rings(vsi, ch);
7803 			clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7804 			netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
7805 			netdev_set_sb_channel(ch->fwd->netdev, 0);
7806 			kfree(ch->fwd);
7807 			ch->fwd = NULL;
7808 		}
7809 
7810 		list_del(&ch->list);
7811 		parent_vsi = ch->parent_vsi;
7812 		if (!parent_vsi || !ch->initialized) {
7813 			kfree(ch);
7814 			continue;
7815 		}
7816 
7817 		/* remove the VSI */
7818 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
7819 					     NULL);
7820 		if (ret)
7821 			dev_err(&vsi->back->pdev->dev,
7822 				"unable to remove channel (%d) for parent VSI(%d)\n",
7823 				ch->seid, parent_vsi->seid);
7824 		kfree(ch);
7825 	}
7826 	vsi->macvlan_cnt = 0;
7827 }
7828 
7829 /**
7830  * i40e_fwd_ring_up - bring the macvlan device up
7831  * @vsi: the VSI we want to access
7832  * @vdev: macvlan netdevice
7833  * @fwd: the private fwd structure
7834  */
7835 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7836 			    struct i40e_fwd_adapter *fwd)
7837 {
7838 	struct i40e_channel *ch = NULL, *ch_tmp, *iter;
7839 	int ret = 0, num_tc = 1,  i, aq_err;
7840 	struct i40e_pf *pf = vsi->back;
7841 	struct i40e_hw *hw = &pf->hw;
7842 
7843 	/* Go through the list and find an available channel */
7844 	list_for_each_entry_safe(iter, ch_tmp, &vsi->macvlan_list, list) {
7845 		if (!i40e_is_channel_macvlan(iter)) {
7846 			iter->fwd = fwd;
7847 			/* record configuration for macvlan interface in vdev */
7848 			for (i = 0; i < num_tc; i++)
7849 				netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7850 							     i,
7851 							     iter->num_queue_pairs,
7852 							     iter->base_queue);
7853 			for (i = 0; i < iter->num_queue_pairs; i++) {
7854 				struct i40e_ring *tx_ring, *rx_ring;
7855 				u16 pf_q;
7856 
7857 				pf_q = iter->base_queue + i;
7858 
7859 				/* Get to TX ring ptr */
7860 				tx_ring = vsi->tx_rings[pf_q];
7861 				tx_ring->ch = iter;
7862 
7863 				/* Get the RX ring ptr */
7864 				rx_ring = vsi->rx_rings[pf_q];
7865 				rx_ring->ch = iter;
7866 			}
7867 			ch = iter;
7868 			break;
7869 		}
7870 	}
7871 
7872 	if (!ch)
7873 		return -EINVAL;
7874 
7875 	/* Guarantee all rings are updated before we update the
7876 	 * MAC address filter.
7877 	 */
7878 	wmb();
7879 
7880 	/* Add a mac filter */
7881 	ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7882 	if (ret) {
7883 		/* if we cannot add the MAC rule then disable the offload */
7884 		macvlan_release_l2fw_offload(vdev);
7885 		for (i = 0; i < ch->num_queue_pairs; i++) {
7886 			struct i40e_ring *rx_ring;
7887 			u16 pf_q;
7888 
7889 			pf_q = ch->base_queue + i;
7890 			rx_ring = vsi->rx_rings[pf_q];
7891 			rx_ring->netdev = NULL;
7892 		}
7893 		dev_info(&pf->pdev->dev,
7894 			 "Error adding mac filter on macvlan err %pe, aq_err %s\n",
7895 			  ERR_PTR(ret),
7896 			  i40e_aq_str(hw, aq_err));
7897 		netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7898 	}
7899 
7900 	return ret;
7901 }
7902 
7903 /**
7904  * i40e_setup_macvlans - create the channels which will be macvlans
7905  * @vsi: the VSI we want to access
7906  * @macvlan_cnt: no. of macvlans to be setup
7907  * @qcnt: no. of Qs per macvlan
7908  * @vdev: macvlan netdevice
7909  */
7910 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7911 			       struct net_device *vdev)
7912 {
7913 	struct i40e_pf *pf = vsi->back;
7914 	struct i40e_hw *hw = &pf->hw;
7915 	struct i40e_vsi_context ctxt;
7916 	u16 sections, qmap, num_qps;
7917 	struct i40e_channel *ch;
7918 	int i, pow, ret = 0;
7919 	u8 offset = 0;
7920 
7921 	if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7922 		return -EINVAL;
7923 
7924 	num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7925 
7926 	/* find the next higher power-of-2 of num queue pairs */
7927 	pow = fls(roundup_pow_of_two(num_qps) - 1);
7928 
7929 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7930 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7931 
7932 	/* Setup context bits for the main VSI */
7933 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7934 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7935 	memset(&ctxt, 0, sizeof(ctxt));
7936 	ctxt.seid = vsi->seid;
7937 	ctxt.pf_num = vsi->back->hw.pf_id;
7938 	ctxt.vf_num = 0;
7939 	ctxt.uplink_seid = vsi->uplink_seid;
7940 	ctxt.info = vsi->info;
7941 	ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7942 	ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7943 	ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7944 	ctxt.info.valid_sections |= cpu_to_le16(sections);
7945 
7946 	/* Reconfigure RSS for main VSI with new max queue count */
7947 	vsi->rss_size = max_t(u16, num_qps, qcnt);
7948 	ret = i40e_vsi_config_rss(vsi);
7949 	if (ret) {
7950 		dev_info(&pf->pdev->dev,
7951 			 "Failed to reconfig RSS for num_queues (%u)\n",
7952 			 vsi->rss_size);
7953 		return ret;
7954 	}
7955 	vsi->reconfig_rss = true;
7956 	dev_dbg(&vsi->back->pdev->dev,
7957 		"Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7958 	vsi->next_base_queue = num_qps;
7959 	vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7960 
7961 	/* Update the VSI after updating the VSI queue-mapping
7962 	 * information
7963 	 */
7964 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7965 	if (ret) {
7966 		dev_info(&pf->pdev->dev,
7967 			 "Update vsi tc config failed, err %pe aq_err %s\n",
7968 			 ERR_PTR(ret),
7969 			 i40e_aq_str(hw, hw->aq.asq_last_status));
7970 		return ret;
7971 	}
7972 	/* update the local VSI info with updated queue map */
7973 	i40e_vsi_update_queue_map(vsi, &ctxt);
7974 	vsi->info.valid_sections = 0;
7975 
7976 	/* Create channels for macvlans */
7977 	INIT_LIST_HEAD(&vsi->macvlan_list);
7978 	for (i = 0; i < macvlan_cnt; i++) {
7979 		ch = kzalloc(sizeof(*ch), GFP_KERNEL);
7980 		if (!ch) {
7981 			ret = -ENOMEM;
7982 			goto err_free;
7983 		}
7984 		INIT_LIST_HEAD(&ch->list);
7985 		ch->num_queue_pairs = qcnt;
7986 		if (!i40e_setup_channel(pf, vsi, ch)) {
7987 			ret = -EINVAL;
7988 			kfree(ch);
7989 			goto err_free;
7990 		}
7991 		ch->parent_vsi = vsi;
7992 		vsi->cnt_q_avail -= ch->num_queue_pairs;
7993 		vsi->macvlan_cnt++;
7994 		list_add_tail(&ch->list, &vsi->macvlan_list);
7995 	}
7996 
7997 	return ret;
7998 
7999 err_free:
8000 	dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
8001 	i40e_free_macvlan_channels(vsi);
8002 
8003 	return ret;
8004 }
8005 
8006 /**
8007  * i40e_fwd_add - configure macvlans
8008  * @netdev: net device to configure
8009  * @vdev: macvlan netdevice
8010  **/
8011 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
8012 {
8013 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8014 	u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
8015 	struct i40e_vsi *vsi = np->vsi;
8016 	struct i40e_pf *pf = vsi->back;
8017 	struct i40e_fwd_adapter *fwd;
8018 	int avail_macvlan, ret;
8019 
8020 	if (test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8021 		netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
8022 		return ERR_PTR(-EINVAL);
8023 	}
8024 	if (i40e_is_tc_mqprio_enabled(pf)) {
8025 		netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
8026 		return ERR_PTR(-EINVAL);
8027 	}
8028 	if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
8029 		netdev_info(netdev, "Not enough vectors available to support macvlans\n");
8030 		return ERR_PTR(-EINVAL);
8031 	}
8032 
8033 	/* The macvlan device has to be a single Q device so that the
8034 	 * tc_to_txq field can be reused to pick the tx queue.
8035 	 */
8036 	if (netif_is_multiqueue(vdev))
8037 		return ERR_PTR(-ERANGE);
8038 
8039 	if (!vsi->macvlan_cnt) {
8040 		/* reserve bit 0 for the pf device */
8041 		set_bit(0, vsi->fwd_bitmask);
8042 
8043 		/* Try to reserve as many queues as possible for macvlans. First
8044 		 * reserve 3/4th of max vectors, then half, then quarter and
8045 		 * calculate Qs per macvlan as you go
8046 		 */
8047 		vectors = pf->num_lan_msix;
8048 		if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
8049 			/* allocate 4 Qs per macvlan and 32 Qs to the PF*/
8050 			q_per_macvlan = 4;
8051 			macvlan_cnt = (vectors - 32) / 4;
8052 		} else if (vectors <= 64 && vectors > 32) {
8053 			/* allocate 2 Qs per macvlan and 16 Qs to the PF*/
8054 			q_per_macvlan = 2;
8055 			macvlan_cnt = (vectors - 16) / 2;
8056 		} else if (vectors <= 32 && vectors > 16) {
8057 			/* allocate 1 Q per macvlan and 16 Qs to the PF*/
8058 			q_per_macvlan = 1;
8059 			macvlan_cnt = vectors - 16;
8060 		} else if (vectors <= 16 && vectors > 8) {
8061 			/* allocate 1 Q per macvlan and 8 Qs to the PF */
8062 			q_per_macvlan = 1;
8063 			macvlan_cnt = vectors - 8;
8064 		} else {
8065 			/* allocate 1 Q per macvlan and 1 Q to the PF */
8066 			q_per_macvlan = 1;
8067 			macvlan_cnt = vectors - 1;
8068 		}
8069 
8070 		if (macvlan_cnt == 0)
8071 			return ERR_PTR(-EBUSY);
8072 
8073 		/* Quiesce VSI queues */
8074 		i40e_quiesce_vsi(vsi);
8075 
8076 		/* sets up the macvlans but does not "enable" them */
8077 		ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
8078 					  vdev);
8079 		if (ret)
8080 			return ERR_PTR(ret);
8081 
8082 		/* Unquiesce VSI */
8083 		i40e_unquiesce_vsi(vsi);
8084 	}
8085 	avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
8086 					    vsi->macvlan_cnt);
8087 	if (avail_macvlan >= I40E_MAX_MACVLANS)
8088 		return ERR_PTR(-EBUSY);
8089 
8090 	/* create the fwd struct */
8091 	fwd = kzalloc(sizeof(*fwd), GFP_KERNEL);
8092 	if (!fwd)
8093 		return ERR_PTR(-ENOMEM);
8094 
8095 	set_bit(avail_macvlan, vsi->fwd_bitmask);
8096 	fwd->bit_no = avail_macvlan;
8097 	netdev_set_sb_channel(vdev, avail_macvlan);
8098 	fwd->netdev = vdev;
8099 
8100 	if (!netif_running(netdev))
8101 		return fwd;
8102 
8103 	/* Set fwd ring up */
8104 	ret = i40e_fwd_ring_up(vsi, vdev, fwd);
8105 	if (ret) {
8106 		/* unbind the queues and drop the subordinate channel config */
8107 		netdev_unbind_sb_channel(netdev, vdev);
8108 		netdev_set_sb_channel(vdev, 0);
8109 
8110 		kfree(fwd);
8111 		return ERR_PTR(-EINVAL);
8112 	}
8113 
8114 	return fwd;
8115 }
8116 
8117 /**
8118  * i40e_del_all_macvlans - Delete all the mac filters on the channels
8119  * @vsi: the VSI we want to access
8120  */
8121 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
8122 {
8123 	struct i40e_channel *ch, *ch_tmp;
8124 	struct i40e_pf *pf = vsi->back;
8125 	struct i40e_hw *hw = &pf->hw;
8126 	int aq_err, ret = 0;
8127 
8128 	if (list_empty(&vsi->macvlan_list))
8129 		return;
8130 
8131 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8132 		if (i40e_is_channel_macvlan(ch)) {
8133 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8134 						      i40e_channel_mac(ch),
8135 						      &aq_err);
8136 			if (!ret) {
8137 				/* Reset queue contexts */
8138 				i40e_reset_ch_rings(vsi, ch);
8139 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8140 				netdev_unbind_sb_channel(vsi->netdev,
8141 							 ch->fwd->netdev);
8142 				netdev_set_sb_channel(ch->fwd->netdev, 0);
8143 				kfree(ch->fwd);
8144 				ch->fwd = NULL;
8145 			}
8146 		}
8147 	}
8148 }
8149 
8150 /**
8151  * i40e_fwd_del - delete macvlan interfaces
8152  * @netdev: net device to configure
8153  * @vdev: macvlan netdevice
8154  */
8155 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
8156 {
8157 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8158 	struct i40e_fwd_adapter *fwd = vdev;
8159 	struct i40e_channel *ch, *ch_tmp;
8160 	struct i40e_vsi *vsi = np->vsi;
8161 	struct i40e_pf *pf = vsi->back;
8162 	struct i40e_hw *hw = &pf->hw;
8163 	int aq_err, ret = 0;
8164 
8165 	/* Find the channel associated with the macvlan and del mac filter */
8166 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8167 		if (i40e_is_channel_macvlan(ch) &&
8168 		    ether_addr_equal(i40e_channel_mac(ch),
8169 				     fwd->netdev->dev_addr)) {
8170 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8171 						      i40e_channel_mac(ch),
8172 						      &aq_err);
8173 			if (!ret) {
8174 				/* Reset queue contexts */
8175 				i40e_reset_ch_rings(vsi, ch);
8176 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8177 				netdev_unbind_sb_channel(netdev, fwd->netdev);
8178 				netdev_set_sb_channel(fwd->netdev, 0);
8179 				kfree(ch->fwd);
8180 				ch->fwd = NULL;
8181 			} else {
8182 				dev_info(&pf->pdev->dev,
8183 					 "Error deleting mac filter on macvlan err %pe, aq_err %s\n",
8184 					  ERR_PTR(ret),
8185 					  i40e_aq_str(hw, aq_err));
8186 			}
8187 			break;
8188 		}
8189 	}
8190 }
8191 
8192 /**
8193  * i40e_setup_tc - configure multiple traffic classes
8194  * @netdev: net device to configure
8195  * @type_data: tc offload data
8196  **/
8197 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
8198 {
8199 	struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
8200 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8201 	struct i40e_vsi *vsi = np->vsi;
8202 	struct i40e_pf *pf = vsi->back;
8203 	u8 enabled_tc = 0, num_tc, hw;
8204 	bool need_reset = false;
8205 	int old_queue_pairs;
8206 	int ret = -EINVAL;
8207 	u16 mode;
8208 	int i;
8209 
8210 	old_queue_pairs = vsi->num_queue_pairs;
8211 	num_tc = mqprio_qopt->qopt.num_tc;
8212 	hw = mqprio_qopt->qopt.hw;
8213 	mode = mqprio_qopt->mode;
8214 	if (!hw) {
8215 		clear_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8216 		memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8217 		goto config_tc;
8218 	}
8219 
8220 	/* Check if MFP enabled */
8221 	if (test_bit(I40E_FLAG_MFP_ENA, pf->flags)) {
8222 		netdev_info(netdev,
8223 			    "Configuring TC not supported in MFP mode\n");
8224 		return ret;
8225 	}
8226 	switch (mode) {
8227 	case TC_MQPRIO_MODE_DCB:
8228 		clear_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8229 
8230 		/* Check if DCB enabled to continue */
8231 		if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8232 			netdev_info(netdev,
8233 				    "DCB is not enabled for adapter\n");
8234 			return ret;
8235 		}
8236 
8237 		/* Check whether tc count is within enabled limit */
8238 		if (num_tc > i40e_pf_get_num_tc(pf)) {
8239 			netdev_info(netdev,
8240 				    "TC count greater than enabled on link for adapter\n");
8241 			return ret;
8242 		}
8243 		break;
8244 	case TC_MQPRIO_MODE_CHANNEL:
8245 		if (test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8246 			netdev_info(netdev,
8247 				    "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
8248 			return ret;
8249 		}
8250 		if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
8251 			return ret;
8252 		ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
8253 		if (ret)
8254 			return ret;
8255 		memcpy(&vsi->mqprio_qopt, mqprio_qopt,
8256 		       sizeof(*mqprio_qopt));
8257 		set_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8258 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
8259 		break;
8260 	default:
8261 		return -EINVAL;
8262 	}
8263 
8264 config_tc:
8265 	/* Generate TC map for number of tc requested */
8266 	for (i = 0; i < num_tc; i++)
8267 		enabled_tc |= BIT(i);
8268 
8269 	/* Requesting same TC configuration as already enabled */
8270 	if (enabled_tc == vsi->tc_config.enabled_tc &&
8271 	    mode != TC_MQPRIO_MODE_CHANNEL)
8272 		return 0;
8273 
8274 	/* Quiesce VSI queues */
8275 	i40e_quiesce_vsi(vsi);
8276 
8277 	if (!hw && !i40e_is_tc_mqprio_enabled(pf))
8278 		i40e_remove_queue_channels(vsi);
8279 
8280 	/* Configure VSI for enabled TCs */
8281 	ret = i40e_vsi_config_tc(vsi, enabled_tc);
8282 	if (ret) {
8283 		netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
8284 			    vsi->seid);
8285 		need_reset = true;
8286 		goto exit;
8287 	} else if (enabled_tc &&
8288 		   (!is_power_of_2(vsi->tc_config.tc_info[0].qcount))) {
8289 		netdev_info(netdev,
8290 			    "Failed to create channel. Override queues (%u) not power of 2\n",
8291 			    vsi->tc_config.tc_info[0].qcount);
8292 		ret = -EINVAL;
8293 		need_reset = true;
8294 		goto exit;
8295 	}
8296 
8297 	dev_info(&vsi->back->pdev->dev,
8298 		 "Setup channel (id:%u) utilizing num_queues %d\n",
8299 		 vsi->seid, vsi->tc_config.tc_info[0].qcount);
8300 
8301 	if (i40e_is_tc_mqprio_enabled(pf)) {
8302 		if (vsi->mqprio_qopt.max_rate[0]) {
8303 			u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
8304 						  vsi->mqprio_qopt.max_rate[0]);
8305 
8306 			ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
8307 			if (!ret) {
8308 				u64 credits = max_tx_rate;
8309 
8310 				do_div(credits, I40E_BW_CREDIT_DIVISOR);
8311 				dev_dbg(&vsi->back->pdev->dev,
8312 					"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
8313 					max_tx_rate,
8314 					credits,
8315 					vsi->seid);
8316 			} else {
8317 				need_reset = true;
8318 				goto exit;
8319 			}
8320 		}
8321 		ret = i40e_configure_queue_channels(vsi);
8322 		if (ret) {
8323 			vsi->num_queue_pairs = old_queue_pairs;
8324 			netdev_info(netdev,
8325 				    "Failed configuring queue channels\n");
8326 			need_reset = true;
8327 			goto exit;
8328 		}
8329 	}
8330 
8331 exit:
8332 	/* Reset the configuration data to defaults, only TC0 is enabled */
8333 	if (need_reset) {
8334 		i40e_vsi_set_default_tc_config(vsi);
8335 		need_reset = false;
8336 	}
8337 
8338 	/* Unquiesce VSI */
8339 	i40e_unquiesce_vsi(vsi);
8340 	return ret;
8341 }
8342 
8343 /**
8344  * i40e_set_cld_element - sets cloud filter element data
8345  * @filter: cloud filter rule
8346  * @cld: ptr to cloud filter element data
8347  *
8348  * This is helper function to copy data into cloud filter element
8349  **/
8350 static inline void
8351 i40e_set_cld_element(struct i40e_cloud_filter *filter,
8352 		     struct i40e_aqc_cloud_filters_element_data *cld)
8353 {
8354 	u32 ipa;
8355 	int i;
8356 
8357 	memset(cld, 0, sizeof(*cld));
8358 	ether_addr_copy(cld->outer_mac, filter->dst_mac);
8359 	ether_addr_copy(cld->inner_mac, filter->src_mac);
8360 
8361 	if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
8362 		return;
8363 
8364 	if (filter->n_proto == ETH_P_IPV6) {
8365 #define IPV6_MAX_INDEX	(ARRAY_SIZE(filter->dst_ipv6) - 1)
8366 		for (i = 0; i < ARRAY_SIZE(filter->dst_ipv6); i++) {
8367 			ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
8368 
8369 			*(__le32 *)&cld->ipaddr.raw_v6.data[i * 2] = cpu_to_le32(ipa);
8370 		}
8371 	} else {
8372 		ipa = be32_to_cpu(filter->dst_ipv4);
8373 
8374 		memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
8375 	}
8376 
8377 	cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
8378 
8379 	/* tenant_id is not supported by FW now, once the support is enabled
8380 	 * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
8381 	 */
8382 	if (filter->tenant_id)
8383 		return;
8384 }
8385 
8386 /**
8387  * i40e_add_del_cloud_filter - Add/del cloud filter
8388  * @vsi: pointer to VSI
8389  * @filter: cloud filter rule
8390  * @add: if true, add, if false, delete
8391  *
8392  * Add or delete a cloud filter for a specific flow spec.
8393  * Returns 0 if the filter were successfully added.
8394  **/
8395 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
8396 			      struct i40e_cloud_filter *filter, bool add)
8397 {
8398 	struct i40e_aqc_cloud_filters_element_data cld_filter;
8399 	struct i40e_pf *pf = vsi->back;
8400 	int ret;
8401 	static const u16 flag_table[128] = {
8402 		[I40E_CLOUD_FILTER_FLAGS_OMAC]  =
8403 			I40E_AQC_ADD_CLOUD_FILTER_OMAC,
8404 		[I40E_CLOUD_FILTER_FLAGS_IMAC]  =
8405 			I40E_AQC_ADD_CLOUD_FILTER_IMAC,
8406 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
8407 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
8408 		[I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
8409 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
8410 		[I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
8411 			I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
8412 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
8413 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
8414 		[I40E_CLOUD_FILTER_FLAGS_IIP] =
8415 			I40E_AQC_ADD_CLOUD_FILTER_IIP,
8416 	};
8417 
8418 	if (filter->flags >= ARRAY_SIZE(flag_table))
8419 		return -EIO;
8420 
8421 	memset(&cld_filter, 0, sizeof(cld_filter));
8422 
8423 	/* copy element needed to add cloud filter from filter */
8424 	i40e_set_cld_element(filter, &cld_filter);
8425 
8426 	if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
8427 		cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
8428 					     I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
8429 
8430 	if (filter->n_proto == ETH_P_IPV6)
8431 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8432 						I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8433 	else
8434 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8435 						I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8436 
8437 	if (add)
8438 		ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
8439 						&cld_filter, 1);
8440 	else
8441 		ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
8442 						&cld_filter, 1);
8443 	if (ret)
8444 		dev_dbg(&pf->pdev->dev,
8445 			"Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
8446 			add ? "add" : "delete", filter->dst_port, ret,
8447 			pf->hw.aq.asq_last_status);
8448 	else
8449 		dev_info(&pf->pdev->dev,
8450 			 "%s cloud filter for VSI: %d\n",
8451 			 add ? "Added" : "Deleted", filter->seid);
8452 	return ret;
8453 }
8454 
8455 /**
8456  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
8457  * @vsi: pointer to VSI
8458  * @filter: cloud filter rule
8459  * @add: if true, add, if false, delete
8460  *
8461  * Add or delete a cloud filter for a specific flow spec using big buffer.
8462  * Returns 0 if the filter were successfully added.
8463  **/
8464 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
8465 				      struct i40e_cloud_filter *filter,
8466 				      bool add)
8467 {
8468 	struct i40e_aqc_cloud_filters_element_bb cld_filter;
8469 	struct i40e_pf *pf = vsi->back;
8470 	int ret;
8471 
8472 	/* Both (src/dst) valid mac_addr are not supported */
8473 	if ((is_valid_ether_addr(filter->dst_mac) &&
8474 	     is_valid_ether_addr(filter->src_mac)) ||
8475 	    (is_multicast_ether_addr(filter->dst_mac) &&
8476 	     is_multicast_ether_addr(filter->src_mac)))
8477 		return -EOPNOTSUPP;
8478 
8479 	/* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
8480 	 * ports are not supported via big buffer now.
8481 	 */
8482 	if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
8483 		return -EOPNOTSUPP;
8484 
8485 	/* adding filter using src_port/src_ip is not supported at this stage */
8486 	if (filter->src_port ||
8487 	    (filter->src_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8488 	    !ipv6_addr_any(&filter->ip.v6.src_ip6))
8489 		return -EOPNOTSUPP;
8490 
8491 	memset(&cld_filter, 0, sizeof(cld_filter));
8492 
8493 	/* copy element needed to add cloud filter from filter */
8494 	i40e_set_cld_element(filter, &cld_filter.element);
8495 
8496 	if (is_valid_ether_addr(filter->dst_mac) ||
8497 	    is_valid_ether_addr(filter->src_mac) ||
8498 	    is_multicast_ether_addr(filter->dst_mac) ||
8499 	    is_multicast_ether_addr(filter->src_mac)) {
8500 		/* MAC + IP : unsupported mode */
8501 		if (filter->dst_ipv4)
8502 			return -EOPNOTSUPP;
8503 
8504 		/* since we validated that L4 port must be valid before
8505 		 * we get here, start with respective "flags" value
8506 		 * and update if vlan is present or not
8507 		 */
8508 		cld_filter.element.flags =
8509 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
8510 
8511 		if (filter->vlan_id) {
8512 			cld_filter.element.flags =
8513 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
8514 		}
8515 
8516 	} else if ((filter->dst_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8517 		   !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
8518 		cld_filter.element.flags =
8519 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
8520 		if (filter->n_proto == ETH_P_IPV6)
8521 			cld_filter.element.flags |=
8522 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8523 		else
8524 			cld_filter.element.flags |=
8525 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8526 	} else {
8527 		dev_err(&pf->pdev->dev,
8528 			"either mac or ip has to be valid for cloud filter\n");
8529 		return -EINVAL;
8530 	}
8531 
8532 	/* Now copy L4 port in Byte 6..7 in general fields */
8533 	cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
8534 						be16_to_cpu(filter->dst_port);
8535 
8536 	if (add) {
8537 		/* Validate current device switch mode, change if necessary */
8538 		ret = i40e_validate_and_set_switch_mode(vsi);
8539 		if (ret) {
8540 			dev_err(&pf->pdev->dev,
8541 				"failed to set switch mode, ret %d\n",
8542 				ret);
8543 			return ret;
8544 		}
8545 
8546 		ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
8547 						   &cld_filter, 1);
8548 	} else {
8549 		ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
8550 						   &cld_filter, 1);
8551 	}
8552 
8553 	if (ret)
8554 		dev_dbg(&pf->pdev->dev,
8555 			"Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
8556 			add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
8557 	else
8558 		dev_info(&pf->pdev->dev,
8559 			 "%s cloud filter for VSI: %d, L4 port: %d\n",
8560 			 add ? "add" : "delete", filter->seid,
8561 			 ntohs(filter->dst_port));
8562 	return ret;
8563 }
8564 
8565 /**
8566  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
8567  * @vsi: Pointer to VSI
8568  * @f: Pointer to struct flow_cls_offload
8569  * @filter: Pointer to cloud filter structure
8570  *
8571  **/
8572 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
8573 				 struct flow_cls_offload *f,
8574 				 struct i40e_cloud_filter *filter)
8575 {
8576 	struct flow_rule *rule = flow_cls_offload_flow_rule(f);
8577 	struct flow_dissector *dissector = rule->match.dissector;
8578 	u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
8579 	struct i40e_pf *pf = vsi->back;
8580 	u8 field_flags = 0;
8581 
8582 	if (dissector->used_keys &
8583 	    ~(BIT_ULL(FLOW_DISSECTOR_KEY_CONTROL) |
8584 	      BIT_ULL(FLOW_DISSECTOR_KEY_BASIC) |
8585 	      BIT_ULL(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
8586 	      BIT_ULL(FLOW_DISSECTOR_KEY_VLAN) |
8587 	      BIT_ULL(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
8588 	      BIT_ULL(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
8589 	      BIT_ULL(FLOW_DISSECTOR_KEY_PORTS) |
8590 	      BIT_ULL(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
8591 		dev_err(&pf->pdev->dev, "Unsupported key used: 0x%llx\n",
8592 			dissector->used_keys);
8593 		return -EOPNOTSUPP;
8594 	}
8595 
8596 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
8597 		struct flow_match_enc_keyid match;
8598 
8599 		flow_rule_match_enc_keyid(rule, &match);
8600 		if (match.mask->keyid != 0)
8601 			field_flags |= I40E_CLOUD_FIELD_TEN_ID;
8602 
8603 		filter->tenant_id = be32_to_cpu(match.key->keyid);
8604 	}
8605 
8606 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
8607 		struct flow_match_basic match;
8608 
8609 		flow_rule_match_basic(rule, &match);
8610 		n_proto_key = ntohs(match.key->n_proto);
8611 		n_proto_mask = ntohs(match.mask->n_proto);
8612 
8613 		if (n_proto_key == ETH_P_ALL) {
8614 			n_proto_key = 0;
8615 			n_proto_mask = 0;
8616 		}
8617 		filter->n_proto = n_proto_key & n_proto_mask;
8618 		filter->ip_proto = match.key->ip_proto;
8619 	}
8620 
8621 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
8622 		struct flow_match_eth_addrs match;
8623 
8624 		flow_rule_match_eth_addrs(rule, &match);
8625 
8626 		/* use is_broadcast and is_zero to check for all 0xf or 0 */
8627 		if (!is_zero_ether_addr(match.mask->dst)) {
8628 			if (is_broadcast_ether_addr(match.mask->dst)) {
8629 				field_flags |= I40E_CLOUD_FIELD_OMAC;
8630 			} else {
8631 				dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
8632 					match.mask->dst);
8633 				return -EIO;
8634 			}
8635 		}
8636 
8637 		if (!is_zero_ether_addr(match.mask->src)) {
8638 			if (is_broadcast_ether_addr(match.mask->src)) {
8639 				field_flags |= I40E_CLOUD_FIELD_IMAC;
8640 			} else {
8641 				dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
8642 					match.mask->src);
8643 				return -EIO;
8644 			}
8645 		}
8646 		ether_addr_copy(filter->dst_mac, match.key->dst);
8647 		ether_addr_copy(filter->src_mac, match.key->src);
8648 	}
8649 
8650 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
8651 		struct flow_match_vlan match;
8652 
8653 		flow_rule_match_vlan(rule, &match);
8654 		if (match.mask->vlan_id) {
8655 			if (match.mask->vlan_id == VLAN_VID_MASK) {
8656 				field_flags |= I40E_CLOUD_FIELD_IVLAN;
8657 
8658 			} else {
8659 				dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
8660 					match.mask->vlan_id);
8661 				return -EIO;
8662 			}
8663 		}
8664 
8665 		filter->vlan_id = cpu_to_be16(match.key->vlan_id);
8666 	}
8667 
8668 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
8669 		struct flow_match_control match;
8670 
8671 		flow_rule_match_control(rule, &match);
8672 		addr_type = match.key->addr_type;
8673 
8674 		if (flow_rule_has_control_flags(match.mask->flags,
8675 						f->common.extack))
8676 			return -EOPNOTSUPP;
8677 	}
8678 
8679 	if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
8680 		struct flow_match_ipv4_addrs match;
8681 
8682 		flow_rule_match_ipv4_addrs(rule, &match);
8683 		if (match.mask->dst) {
8684 			if (match.mask->dst == cpu_to_be32(0xffffffff)) {
8685 				field_flags |= I40E_CLOUD_FIELD_IIP;
8686 			} else {
8687 				dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
8688 					&match.mask->dst);
8689 				return -EIO;
8690 			}
8691 		}
8692 
8693 		if (match.mask->src) {
8694 			if (match.mask->src == cpu_to_be32(0xffffffff)) {
8695 				field_flags |= I40E_CLOUD_FIELD_IIP;
8696 			} else {
8697 				dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
8698 					&match.mask->src);
8699 				return -EIO;
8700 			}
8701 		}
8702 
8703 		if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
8704 			dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
8705 			return -EIO;
8706 		}
8707 		filter->dst_ipv4 = match.key->dst;
8708 		filter->src_ipv4 = match.key->src;
8709 	}
8710 
8711 	if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
8712 		struct flow_match_ipv6_addrs match;
8713 
8714 		flow_rule_match_ipv6_addrs(rule, &match);
8715 
8716 		/* src and dest IPV6 address should not be LOOPBACK
8717 		 * (0:0:0:0:0:0:0:1), which can be represented as ::1
8718 		 */
8719 		if (ipv6_addr_loopback(&match.key->dst) ||
8720 		    ipv6_addr_loopback(&match.key->src)) {
8721 			dev_err(&pf->pdev->dev,
8722 				"Bad ipv6, addr is LOOPBACK\n");
8723 			return -EIO;
8724 		}
8725 		if (!ipv6_addr_any(&match.mask->dst) ||
8726 		    !ipv6_addr_any(&match.mask->src))
8727 			field_flags |= I40E_CLOUD_FIELD_IIP;
8728 
8729 		memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
8730 		       sizeof(filter->src_ipv6));
8731 		memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
8732 		       sizeof(filter->dst_ipv6));
8733 	}
8734 
8735 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
8736 		struct flow_match_ports match;
8737 
8738 		flow_rule_match_ports(rule, &match);
8739 		if (match.mask->src) {
8740 			if (match.mask->src == cpu_to_be16(0xffff)) {
8741 				field_flags |= I40E_CLOUD_FIELD_IIP;
8742 			} else {
8743 				dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
8744 					be16_to_cpu(match.mask->src));
8745 				return -EIO;
8746 			}
8747 		}
8748 
8749 		if (match.mask->dst) {
8750 			if (match.mask->dst == cpu_to_be16(0xffff)) {
8751 				field_flags |= I40E_CLOUD_FIELD_IIP;
8752 			} else {
8753 				dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
8754 					be16_to_cpu(match.mask->dst));
8755 				return -EIO;
8756 			}
8757 		}
8758 
8759 		filter->dst_port = match.key->dst;
8760 		filter->src_port = match.key->src;
8761 
8762 		switch (filter->ip_proto) {
8763 		case IPPROTO_TCP:
8764 		case IPPROTO_UDP:
8765 			break;
8766 		default:
8767 			dev_err(&pf->pdev->dev,
8768 				"Only UDP and TCP transport are supported\n");
8769 			return -EINVAL;
8770 		}
8771 	}
8772 	filter->flags = field_flags;
8773 	return 0;
8774 }
8775 
8776 /**
8777  * i40e_handle_tclass: Forward to a traffic class on the device
8778  * @vsi: Pointer to VSI
8779  * @tc: traffic class index on the device
8780  * @filter: Pointer to cloud filter structure
8781  *
8782  **/
8783 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
8784 			      struct i40e_cloud_filter *filter)
8785 {
8786 	struct i40e_channel *ch, *ch_tmp;
8787 
8788 	/* direct to a traffic class on the same device */
8789 	if (tc == 0) {
8790 		filter->seid = vsi->seid;
8791 		return 0;
8792 	} else if (vsi->tc_config.enabled_tc & BIT(tc)) {
8793 		if (!filter->dst_port) {
8794 			dev_err(&vsi->back->pdev->dev,
8795 				"Specify destination port to direct to traffic class that is not default\n");
8796 			return -EINVAL;
8797 		}
8798 		if (list_empty(&vsi->ch_list))
8799 			return -EINVAL;
8800 		list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
8801 					 list) {
8802 			if (ch->seid == vsi->tc_seid_map[tc])
8803 				filter->seid = ch->seid;
8804 		}
8805 		return 0;
8806 	}
8807 	dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
8808 	return -EINVAL;
8809 }
8810 
8811 /**
8812  * i40e_configure_clsflower - Configure tc flower filters
8813  * @vsi: Pointer to VSI
8814  * @cls_flower: Pointer to struct flow_cls_offload
8815  *
8816  **/
8817 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
8818 				    struct flow_cls_offload *cls_flower)
8819 {
8820 	int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
8821 	struct i40e_cloud_filter *filter = NULL;
8822 	struct i40e_pf *pf = vsi->back;
8823 	int err = 0;
8824 
8825 	if (tc < 0) {
8826 		dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
8827 		return -EOPNOTSUPP;
8828 	}
8829 
8830 	if (!tc) {
8831 		dev_err(&pf->pdev->dev, "Unable to add filter because of invalid destination");
8832 		return -EINVAL;
8833 	}
8834 
8835 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
8836 	    test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
8837 		return -EBUSY;
8838 
8839 	if (pf->fdir_pf_active_filters ||
8840 	    (!hlist_empty(&pf->fdir_filter_list))) {
8841 		dev_err(&vsi->back->pdev->dev,
8842 			"Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
8843 		return -EINVAL;
8844 	}
8845 
8846 	if (test_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags)) {
8847 		dev_err(&vsi->back->pdev->dev,
8848 			"Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
8849 		clear_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags);
8850 		clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, vsi->back->flags);
8851 	}
8852 
8853 	filter = kzalloc(sizeof(*filter), GFP_KERNEL);
8854 	if (!filter)
8855 		return -ENOMEM;
8856 
8857 	filter->cookie = cls_flower->cookie;
8858 
8859 	err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8860 	if (err < 0)
8861 		goto err;
8862 
8863 	err = i40e_handle_tclass(vsi, tc, filter);
8864 	if (err < 0)
8865 		goto err;
8866 
8867 	/* Add cloud filter */
8868 	if (filter->dst_port)
8869 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8870 	else
8871 		err = i40e_add_del_cloud_filter(vsi, filter, true);
8872 
8873 	if (err) {
8874 		dev_err(&pf->pdev->dev, "Failed to add cloud filter, err %d\n",
8875 			err);
8876 		goto err;
8877 	}
8878 
8879 	/* add filter to the ordered list */
8880 	INIT_HLIST_NODE(&filter->cloud_node);
8881 
8882 	hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8883 
8884 	pf->num_cloud_filters++;
8885 
8886 	return err;
8887 err:
8888 	kfree(filter);
8889 	return err;
8890 }
8891 
8892 /**
8893  * i40e_find_cloud_filter - Find the could filter in the list
8894  * @vsi: Pointer to VSI
8895  * @cookie: filter specific cookie
8896  *
8897  **/
8898 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8899 							unsigned long *cookie)
8900 {
8901 	struct i40e_cloud_filter *filter = NULL;
8902 	struct hlist_node *node2;
8903 
8904 	hlist_for_each_entry_safe(filter, node2,
8905 				  &vsi->back->cloud_filter_list, cloud_node)
8906 		if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8907 			return filter;
8908 	return NULL;
8909 }
8910 
8911 /**
8912  * i40e_delete_clsflower - Remove tc flower filters
8913  * @vsi: Pointer to VSI
8914  * @cls_flower: Pointer to struct flow_cls_offload
8915  *
8916  **/
8917 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8918 				 struct flow_cls_offload *cls_flower)
8919 {
8920 	struct i40e_cloud_filter *filter = NULL;
8921 	struct i40e_pf *pf = vsi->back;
8922 	int err = 0;
8923 
8924 	filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8925 
8926 	if (!filter)
8927 		return -EINVAL;
8928 
8929 	hash_del(&filter->cloud_node);
8930 
8931 	if (filter->dst_port)
8932 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8933 	else
8934 		err = i40e_add_del_cloud_filter(vsi, filter, false);
8935 
8936 	kfree(filter);
8937 	if (err) {
8938 		dev_err(&pf->pdev->dev,
8939 			"Failed to delete cloud filter, err %pe\n",
8940 			ERR_PTR(err));
8941 		return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8942 	}
8943 
8944 	pf->num_cloud_filters--;
8945 	if (!pf->num_cloud_filters)
8946 		if (test_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags) &&
8947 		    !test_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags)) {
8948 			set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
8949 			clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags);
8950 			clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
8951 		}
8952 	return 0;
8953 }
8954 
8955 /**
8956  * i40e_setup_tc_cls_flower - flower classifier offloads
8957  * @np: net device to configure
8958  * @cls_flower: offload data
8959  **/
8960 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8961 				    struct flow_cls_offload *cls_flower)
8962 {
8963 	struct i40e_vsi *vsi = np->vsi;
8964 
8965 	switch (cls_flower->command) {
8966 	case FLOW_CLS_REPLACE:
8967 		return i40e_configure_clsflower(vsi, cls_flower);
8968 	case FLOW_CLS_DESTROY:
8969 		return i40e_delete_clsflower(vsi, cls_flower);
8970 	case FLOW_CLS_STATS:
8971 		return -EOPNOTSUPP;
8972 	default:
8973 		return -EOPNOTSUPP;
8974 	}
8975 }
8976 
8977 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8978 				  void *cb_priv)
8979 {
8980 	struct i40e_netdev_priv *np = cb_priv;
8981 
8982 	if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8983 		return -EOPNOTSUPP;
8984 
8985 	switch (type) {
8986 	case TC_SETUP_CLSFLOWER:
8987 		return i40e_setup_tc_cls_flower(np, type_data);
8988 
8989 	default:
8990 		return -EOPNOTSUPP;
8991 	}
8992 }
8993 
8994 static LIST_HEAD(i40e_block_cb_list);
8995 
8996 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8997 			   void *type_data)
8998 {
8999 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9000 
9001 	switch (type) {
9002 	case TC_SETUP_QDISC_MQPRIO:
9003 		return i40e_setup_tc(netdev, type_data);
9004 	case TC_SETUP_BLOCK:
9005 		return flow_block_cb_setup_simple(type_data,
9006 						  &i40e_block_cb_list,
9007 						  i40e_setup_tc_block_cb,
9008 						  np, np, true);
9009 	default:
9010 		return -EOPNOTSUPP;
9011 	}
9012 }
9013 
9014 /**
9015  * i40e_open - Called when a network interface is made active
9016  * @netdev: network interface device structure
9017  *
9018  * The open entry point is called when a network interface is made
9019  * active by the system (IFF_UP).  At this point all resources needed
9020  * for transmit and receive operations are allocated, the interrupt
9021  * handler is registered with the OS, the netdev watchdog subtask is
9022  * enabled, and the stack is notified that the interface is ready.
9023  *
9024  * Returns 0 on success, negative value on failure
9025  **/
9026 int i40e_open(struct net_device *netdev)
9027 {
9028 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9029 	struct i40e_vsi *vsi = np->vsi;
9030 	struct i40e_pf *pf = vsi->back;
9031 	int err;
9032 
9033 	/* disallow open during test or if eeprom is broken */
9034 	if (test_bit(__I40E_TESTING, pf->state) ||
9035 	    test_bit(__I40E_BAD_EEPROM, pf->state))
9036 		return -EBUSY;
9037 
9038 	netif_carrier_off(netdev);
9039 
9040 	if (i40e_force_link_state(pf, true))
9041 		return -EAGAIN;
9042 
9043 	err = i40e_vsi_open(vsi);
9044 	if (err)
9045 		return err;
9046 
9047 	/* configure global TSO hardware offload settings */
9048 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
9049 						       TCP_FLAG_FIN) >> 16);
9050 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
9051 						       TCP_FLAG_FIN |
9052 						       TCP_FLAG_CWR) >> 16);
9053 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
9054 	udp_tunnel_get_rx_info(netdev);
9055 
9056 	return 0;
9057 }
9058 
9059 /**
9060  * i40e_netif_set_realnum_tx_rx_queues - Update number of tx/rx queues
9061  * @vsi: vsi structure
9062  *
9063  * This updates netdev's number of tx/rx queues
9064  *
9065  * Returns status of setting tx/rx queues
9066  **/
9067 static int i40e_netif_set_realnum_tx_rx_queues(struct i40e_vsi *vsi)
9068 {
9069 	int ret;
9070 
9071 	ret = netif_set_real_num_rx_queues(vsi->netdev,
9072 					   vsi->num_queue_pairs);
9073 	if (ret)
9074 		return ret;
9075 
9076 	return netif_set_real_num_tx_queues(vsi->netdev,
9077 					    vsi->num_queue_pairs);
9078 }
9079 
9080 /**
9081  * i40e_vsi_open -
9082  * @vsi: the VSI to open
9083  *
9084  * Finish initialization of the VSI.
9085  *
9086  * Returns 0 on success, negative value on failure
9087  *
9088  * Note: expects to be called while under rtnl_lock()
9089  **/
9090 int i40e_vsi_open(struct i40e_vsi *vsi)
9091 {
9092 	struct i40e_pf *pf = vsi->back;
9093 	char int_name[I40E_INT_NAME_STR_LEN];
9094 	int err;
9095 
9096 	/* allocate descriptors */
9097 	err = i40e_vsi_setup_tx_resources(vsi);
9098 	if (err)
9099 		goto err_setup_tx;
9100 	err = i40e_vsi_setup_rx_resources(vsi);
9101 	if (err)
9102 		goto err_setup_rx;
9103 
9104 	err = i40e_vsi_configure(vsi);
9105 	if (err)
9106 		goto err_setup_rx;
9107 
9108 	if (vsi->netdev) {
9109 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
9110 			 dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
9111 		err = i40e_vsi_request_irq(vsi, int_name);
9112 		if (err)
9113 			goto err_setup_rx;
9114 
9115 		/* Notify the stack of the actual queue counts. */
9116 		err = i40e_netif_set_realnum_tx_rx_queues(vsi);
9117 		if (err)
9118 			goto err_set_queues;
9119 
9120 	} else if (vsi->type == I40E_VSI_FDIR) {
9121 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
9122 			 dev_driver_string(&pf->pdev->dev),
9123 			 dev_name(&pf->pdev->dev));
9124 		err = i40e_vsi_request_irq(vsi, int_name);
9125 		if (err)
9126 			goto err_setup_rx;
9127 
9128 	} else {
9129 		err = -EINVAL;
9130 		goto err_setup_rx;
9131 	}
9132 
9133 	err = i40e_up_complete(vsi);
9134 	if (err)
9135 		goto err_up_complete;
9136 
9137 	return 0;
9138 
9139 err_up_complete:
9140 	i40e_down(vsi);
9141 err_set_queues:
9142 	i40e_vsi_free_irq(vsi);
9143 err_setup_rx:
9144 	i40e_vsi_free_rx_resources(vsi);
9145 err_setup_tx:
9146 	i40e_vsi_free_tx_resources(vsi);
9147 	if (vsi->type == I40E_VSI_MAIN)
9148 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
9149 
9150 	return err;
9151 }
9152 
9153 /**
9154  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
9155  * @pf: Pointer to PF
9156  *
9157  * This function destroys the hlist where all the Flow Director
9158  * filters were saved.
9159  **/
9160 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
9161 {
9162 	struct i40e_fdir_filter *filter;
9163 	struct i40e_flex_pit *pit_entry, *tmp;
9164 	struct hlist_node *node2;
9165 
9166 	hlist_for_each_entry_safe(filter, node2,
9167 				  &pf->fdir_filter_list, fdir_node) {
9168 		hlist_del(&filter->fdir_node);
9169 		kfree(filter);
9170 	}
9171 
9172 	list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
9173 		list_del(&pit_entry->list);
9174 		kfree(pit_entry);
9175 	}
9176 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
9177 
9178 	list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
9179 		list_del(&pit_entry->list);
9180 		kfree(pit_entry);
9181 	}
9182 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
9183 
9184 	pf->fdir_pf_active_filters = 0;
9185 	i40e_reset_fdir_filter_cnt(pf);
9186 
9187 	/* Reprogram the default input set for TCP/IPv4 */
9188 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9189 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9190 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9191 
9192 	/* Reprogram the default input set for TCP/IPv6 */
9193 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_TCP,
9194 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9195 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9196 
9197 	/* Reprogram the default input set for UDP/IPv4 */
9198 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
9199 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9200 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9201 
9202 	/* Reprogram the default input set for UDP/IPv6 */
9203 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_UDP,
9204 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9205 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9206 
9207 	/* Reprogram the default input set for SCTP/IPv4 */
9208 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
9209 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9210 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9211 
9212 	/* Reprogram the default input set for SCTP/IPv6 */
9213 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_SCTP,
9214 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9215 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9216 
9217 	/* Reprogram the default input set for Other/IPv4 */
9218 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
9219 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9220 
9221 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
9222 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9223 
9224 	/* Reprogram the default input set for Other/IPv6 */
9225 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_OTHER,
9226 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9227 
9228 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV6,
9229 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9230 }
9231 
9232 /**
9233  * i40e_cloud_filter_exit - Cleans up the cloud filters
9234  * @pf: Pointer to PF
9235  *
9236  * This function destroys the hlist where all the cloud filters
9237  * were saved.
9238  **/
9239 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
9240 {
9241 	struct i40e_cloud_filter *cfilter;
9242 	struct hlist_node *node;
9243 
9244 	hlist_for_each_entry_safe(cfilter, node,
9245 				  &pf->cloud_filter_list, cloud_node) {
9246 		hlist_del(&cfilter->cloud_node);
9247 		kfree(cfilter);
9248 	}
9249 	pf->num_cloud_filters = 0;
9250 
9251 	if (test_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags) &&
9252 	    !test_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags)) {
9253 		set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
9254 		clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags);
9255 		clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
9256 	}
9257 }
9258 
9259 /**
9260  * i40e_close - Disables a network interface
9261  * @netdev: network interface device structure
9262  *
9263  * The close entry point is called when an interface is de-activated
9264  * by the OS.  The hardware is still under the driver's control, but
9265  * this netdev interface is disabled.
9266  *
9267  * Returns 0, this is not allowed to fail
9268  **/
9269 int i40e_close(struct net_device *netdev)
9270 {
9271 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9272 	struct i40e_vsi *vsi = np->vsi;
9273 
9274 	i40e_vsi_close(vsi);
9275 
9276 	return 0;
9277 }
9278 
9279 /**
9280  * i40e_do_reset - Start a PF or Core Reset sequence
9281  * @pf: board private structure
9282  * @reset_flags: which reset is requested
9283  * @lock_acquired: indicates whether or not the lock has been acquired
9284  * before this function was called.
9285  *
9286  * The essential difference in resets is that the PF Reset
9287  * doesn't clear the packet buffers, doesn't reset the PE
9288  * firmware, and doesn't bother the other PFs on the chip.
9289  **/
9290 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
9291 {
9292 	struct i40e_vsi *vsi;
9293 	u32 val;
9294 	int i;
9295 
9296 	/* do the biggest reset indicated */
9297 	if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
9298 
9299 		/* Request a Global Reset
9300 		 *
9301 		 * This will start the chip's countdown to the actual full
9302 		 * chip reset event, and a warning interrupt to be sent
9303 		 * to all PFs, including the requestor.  Our handler
9304 		 * for the warning interrupt will deal with the shutdown
9305 		 * and recovery of the switch setup.
9306 		 */
9307 		dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
9308 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9309 		val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
9310 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9311 
9312 	} else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
9313 
9314 		/* Request a Core Reset
9315 		 *
9316 		 * Same as Global Reset, except does *not* include the MAC/PHY
9317 		 */
9318 		dev_dbg(&pf->pdev->dev, "CoreR requested\n");
9319 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9320 		val |= I40E_GLGEN_RTRIG_CORER_MASK;
9321 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9322 		i40e_flush(&pf->hw);
9323 
9324 	} else if (reset_flags & I40E_PF_RESET_FLAG) {
9325 
9326 		/* Request a PF Reset
9327 		 *
9328 		 * Resets only the PF-specific registers
9329 		 *
9330 		 * This goes directly to the tear-down and rebuild of
9331 		 * the switch, since we need to do all the recovery as
9332 		 * for the Core Reset.
9333 		 */
9334 		dev_dbg(&pf->pdev->dev, "PFR requested\n");
9335 		i40e_handle_reset_warning(pf, lock_acquired);
9336 
9337 	} else if (reset_flags & I40E_PF_RESET_AND_REBUILD_FLAG) {
9338 		/* Request a PF Reset
9339 		 *
9340 		 * Resets PF and reinitializes PFs VSI.
9341 		 */
9342 		i40e_prep_for_reset(pf);
9343 		i40e_reset_and_rebuild(pf, true, lock_acquired);
9344 		dev_info(&pf->pdev->dev,
9345 			 test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags) ?
9346 			 "FW LLDP is disabled\n" :
9347 			 "FW LLDP is enabled\n");
9348 
9349 	} else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
9350 		/* Find the VSI(s) that requested a re-init */
9351 		dev_info(&pf->pdev->dev, "VSI reinit requested\n");
9352 
9353 		i40e_pf_for_each_vsi(pf, i, vsi) {
9354 			if (test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
9355 					       vsi->state))
9356 				i40e_vsi_reinit_locked(vsi);
9357 		}
9358 	} else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
9359 		/* Find the VSI(s) that needs to be brought down */
9360 		dev_info(&pf->pdev->dev, "VSI down requested\n");
9361 
9362 		i40e_pf_for_each_vsi(pf, i, vsi) {
9363 			if (test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
9364 					       vsi->state)) {
9365 				set_bit(__I40E_VSI_DOWN, vsi->state);
9366 				i40e_down(vsi);
9367 			}
9368 		}
9369 	} else {
9370 		dev_info(&pf->pdev->dev,
9371 			 "bad reset request 0x%08x\n", reset_flags);
9372 	}
9373 }
9374 
9375 #ifdef CONFIG_I40E_DCB
9376 /**
9377  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
9378  * @pf: board private structure
9379  * @old_cfg: current DCB config
9380  * @new_cfg: new DCB config
9381  **/
9382 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
9383 			    struct i40e_dcbx_config *old_cfg,
9384 			    struct i40e_dcbx_config *new_cfg)
9385 {
9386 	bool need_reconfig = false;
9387 
9388 	/* Check if ETS configuration has changed */
9389 	if (memcmp(&new_cfg->etscfg,
9390 		   &old_cfg->etscfg,
9391 		   sizeof(new_cfg->etscfg))) {
9392 		/* If Priority Table has changed reconfig is needed */
9393 		if (memcmp(&new_cfg->etscfg.prioritytable,
9394 			   &old_cfg->etscfg.prioritytable,
9395 			   sizeof(new_cfg->etscfg.prioritytable))) {
9396 			need_reconfig = true;
9397 			dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
9398 		}
9399 
9400 		if (memcmp(&new_cfg->etscfg.tcbwtable,
9401 			   &old_cfg->etscfg.tcbwtable,
9402 			   sizeof(new_cfg->etscfg.tcbwtable)))
9403 			dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
9404 
9405 		if (memcmp(&new_cfg->etscfg.tsatable,
9406 			   &old_cfg->etscfg.tsatable,
9407 			   sizeof(new_cfg->etscfg.tsatable)))
9408 			dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
9409 	}
9410 
9411 	/* Check if PFC configuration has changed */
9412 	if (memcmp(&new_cfg->pfc,
9413 		   &old_cfg->pfc,
9414 		   sizeof(new_cfg->pfc))) {
9415 		need_reconfig = true;
9416 		dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
9417 	}
9418 
9419 	/* Check if APP Table has changed */
9420 	if (memcmp(&new_cfg->app,
9421 		   &old_cfg->app,
9422 		   sizeof(new_cfg->app))) {
9423 		need_reconfig = true;
9424 		dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
9425 	}
9426 
9427 	dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
9428 	return need_reconfig;
9429 }
9430 
9431 /**
9432  * i40e_handle_lldp_event - Handle LLDP Change MIB event
9433  * @pf: board private structure
9434  * @e: event info posted on ARQ
9435  **/
9436 static int i40e_handle_lldp_event(struct i40e_pf *pf,
9437 				  struct i40e_arq_event_info *e)
9438 {
9439 	struct i40e_aqc_lldp_get_mib *mib =
9440 		(struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
9441 	struct i40e_hw *hw = &pf->hw;
9442 	struct i40e_dcbx_config tmp_dcbx_cfg;
9443 	bool need_reconfig = false;
9444 	int ret = 0;
9445 	u8 type;
9446 
9447 	/* X710-T*L 2.5G and 5G speeds don't support DCB */
9448 	if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9449 	    (hw->phy.link_info.link_speed &
9450 	     ~(I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB)) &&
9451 	     !test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
9452 		/* let firmware decide if the DCB should be disabled */
9453 		set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9454 
9455 	/* Not DCB capable or capability disabled */
9456 	if (!test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
9457 		return ret;
9458 
9459 	/* Ignore if event is not for Nearest Bridge */
9460 	type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
9461 		& I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
9462 	dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
9463 	if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
9464 		return ret;
9465 
9466 	/* Check MIB Type and return if event for Remote MIB update */
9467 	type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
9468 	dev_dbg(&pf->pdev->dev,
9469 		"LLDP event mib type %s\n", type ? "remote" : "local");
9470 	if (type == I40E_AQ_LLDP_MIB_REMOTE) {
9471 		/* Update the remote cached instance and return */
9472 		ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
9473 				I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
9474 				&hw->remote_dcbx_config);
9475 		goto exit;
9476 	}
9477 
9478 	/* Store the old configuration */
9479 	tmp_dcbx_cfg = hw->local_dcbx_config;
9480 
9481 	/* Reset the old DCBx configuration data */
9482 	memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
9483 	/* Get updated DCBX data from firmware */
9484 	ret = i40e_get_dcb_config(&pf->hw);
9485 	if (ret) {
9486 		/* X710-T*L 2.5G and 5G speeds don't support DCB */
9487 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9488 		    (hw->phy.link_info.link_speed &
9489 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
9490 			dev_warn(&pf->pdev->dev,
9491 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
9492 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9493 		} else {
9494 			dev_info(&pf->pdev->dev,
9495 				 "Failed querying DCB configuration data from firmware, err %pe aq_err %s\n",
9496 				 ERR_PTR(ret),
9497 				 i40e_aq_str(&pf->hw,
9498 					     pf->hw.aq.asq_last_status));
9499 		}
9500 		goto exit;
9501 	}
9502 
9503 	/* No change detected in DCBX configs */
9504 	if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
9505 		    sizeof(tmp_dcbx_cfg))) {
9506 		dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
9507 		goto exit;
9508 	}
9509 
9510 	need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
9511 					       &hw->local_dcbx_config);
9512 
9513 	i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
9514 
9515 	if (!need_reconfig)
9516 		goto exit;
9517 
9518 	/* Enable DCB tagging only when more than one TC */
9519 	if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
9520 		set_bit(I40E_FLAG_DCB_ENA, pf->flags);
9521 	else
9522 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
9523 
9524 	set_bit(__I40E_PORT_SUSPENDED, pf->state);
9525 	/* Reconfiguration needed quiesce all VSIs */
9526 	i40e_pf_quiesce_all_vsi(pf);
9527 
9528 	/* Changes in configuration update VEB/VSI */
9529 	i40e_dcb_reconfigure(pf);
9530 
9531 	ret = i40e_resume_port_tx(pf);
9532 
9533 	clear_bit(__I40E_PORT_SUSPENDED, pf->state);
9534 	/* In case of error no point in resuming VSIs */
9535 	if (ret)
9536 		goto exit;
9537 
9538 	/* Wait for the PF's queues to be disabled */
9539 	ret = i40e_pf_wait_queues_disabled(pf);
9540 	if (ret) {
9541 		/* Schedule PF reset to recover */
9542 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9543 		i40e_service_event_schedule(pf);
9544 	} else {
9545 		i40e_pf_unquiesce_all_vsi(pf);
9546 		set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
9547 		set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
9548 	}
9549 
9550 exit:
9551 	return ret;
9552 }
9553 #endif /* CONFIG_I40E_DCB */
9554 
9555 /**
9556  * i40e_do_reset_safe - Protected reset path for userland calls.
9557  * @pf: board private structure
9558  * @reset_flags: which reset is requested
9559  *
9560  **/
9561 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
9562 {
9563 	rtnl_lock();
9564 	i40e_do_reset(pf, reset_flags, true);
9565 	rtnl_unlock();
9566 }
9567 
9568 /**
9569  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
9570  * @pf: board private structure
9571  * @e: event info posted on ARQ
9572  *
9573  * Handler for LAN Queue Overflow Event generated by the firmware for PF
9574  * and VF queues
9575  **/
9576 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
9577 					   struct i40e_arq_event_info *e)
9578 {
9579 	struct i40e_aqc_lan_overflow *data =
9580 		(struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
9581 	u32 queue = le32_to_cpu(data->prtdcb_rupto);
9582 	u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
9583 	struct i40e_hw *hw = &pf->hw;
9584 	struct i40e_vf *vf;
9585 	u16 vf_id;
9586 
9587 	dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
9588 		queue, qtx_ctl);
9589 
9590 	if (FIELD_GET(I40E_QTX_CTL_PFVF_Q_MASK, qtx_ctl) !=
9591 	    I40E_QTX_CTL_VF_QUEUE)
9592 		return;
9593 
9594 	/* Queue belongs to VF, find the VF and issue VF reset */
9595 	vf_id = FIELD_GET(I40E_QTX_CTL_VFVM_INDX_MASK, qtx_ctl);
9596 	vf_id -= hw->func_caps.vf_base_id;
9597 	vf = &pf->vf[vf_id];
9598 	i40e_vc_notify_vf_reset(vf);
9599 	/* Allow VF to process pending reset notification */
9600 	msleep(20);
9601 	i40e_reset_vf(vf, false);
9602 }
9603 
9604 /**
9605  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
9606  * @pf: board private structure
9607  **/
9608 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
9609 {
9610 	u32 val, fcnt_prog;
9611 
9612 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9613 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
9614 	return fcnt_prog;
9615 }
9616 
9617 /**
9618  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
9619  * @pf: board private structure
9620  **/
9621 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
9622 {
9623 	u32 val, fcnt_prog;
9624 
9625 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9626 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
9627 		    FIELD_GET(I40E_PFQF_FDSTAT_BEST_CNT_MASK, val);
9628 	return fcnt_prog;
9629 }
9630 
9631 /**
9632  * i40e_get_global_fd_count - Get total FD filters programmed on device
9633  * @pf: board private structure
9634  **/
9635 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
9636 {
9637 	u32 val, fcnt_prog;
9638 
9639 	val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
9640 	fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
9641 		    FIELD_GET(I40E_GLQF_FDCNT_0_BESTCNT_MASK, val);
9642 	return fcnt_prog;
9643 }
9644 
9645 /**
9646  * i40e_reenable_fdir_sb - Restore FDir SB capability
9647  * @pf: board private structure
9648  **/
9649 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
9650 {
9651 	if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
9652 		if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
9653 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9654 			dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
9655 }
9656 
9657 /**
9658  * i40e_reenable_fdir_atr - Restore FDir ATR capability
9659  * @pf: board private structure
9660  **/
9661 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
9662 {
9663 	if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
9664 		/* ATR uses the same filtering logic as SB rules. It only
9665 		 * functions properly if the input set mask is at the default
9666 		 * settings. It is safe to restore the default input set
9667 		 * because there are no active TCPv4 filter rules.
9668 		 */
9669 		i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9670 					I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9671 					I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9672 
9673 		if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
9674 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9675 			dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
9676 	}
9677 }
9678 
9679 /**
9680  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
9681  * @pf: board private structure
9682  * @filter: FDir filter to remove
9683  */
9684 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
9685 				       struct i40e_fdir_filter *filter)
9686 {
9687 	/* Update counters */
9688 	pf->fdir_pf_active_filters--;
9689 	pf->fd_inv = 0;
9690 
9691 	switch (filter->flow_type) {
9692 	case TCP_V4_FLOW:
9693 		pf->fd_tcp4_filter_cnt--;
9694 		break;
9695 	case UDP_V4_FLOW:
9696 		pf->fd_udp4_filter_cnt--;
9697 		break;
9698 	case SCTP_V4_FLOW:
9699 		pf->fd_sctp4_filter_cnt--;
9700 		break;
9701 	case TCP_V6_FLOW:
9702 		pf->fd_tcp6_filter_cnt--;
9703 		break;
9704 	case UDP_V6_FLOW:
9705 		pf->fd_udp6_filter_cnt--;
9706 		break;
9707 	case SCTP_V6_FLOW:
9708 		pf->fd_udp6_filter_cnt--;
9709 		break;
9710 	case IP_USER_FLOW:
9711 		switch (filter->ipl4_proto) {
9712 		case IPPROTO_TCP:
9713 			pf->fd_tcp4_filter_cnt--;
9714 			break;
9715 		case IPPROTO_UDP:
9716 			pf->fd_udp4_filter_cnt--;
9717 			break;
9718 		case IPPROTO_SCTP:
9719 			pf->fd_sctp4_filter_cnt--;
9720 			break;
9721 		case IPPROTO_IP:
9722 			pf->fd_ip4_filter_cnt--;
9723 			break;
9724 		}
9725 		break;
9726 	case IPV6_USER_FLOW:
9727 		switch (filter->ipl4_proto) {
9728 		case IPPROTO_TCP:
9729 			pf->fd_tcp6_filter_cnt--;
9730 			break;
9731 		case IPPROTO_UDP:
9732 			pf->fd_udp6_filter_cnt--;
9733 			break;
9734 		case IPPROTO_SCTP:
9735 			pf->fd_sctp6_filter_cnt--;
9736 			break;
9737 		case IPPROTO_IP:
9738 			pf->fd_ip6_filter_cnt--;
9739 			break;
9740 		}
9741 		break;
9742 	}
9743 
9744 	/* Remove the filter from the list and free memory */
9745 	hlist_del(&filter->fdir_node);
9746 	kfree(filter);
9747 }
9748 
9749 /**
9750  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
9751  * @pf: board private structure
9752  **/
9753 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
9754 {
9755 	struct i40e_fdir_filter *filter;
9756 	u32 fcnt_prog, fcnt_avail;
9757 	struct hlist_node *node;
9758 
9759 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9760 		return;
9761 
9762 	/* Check if we have enough room to re-enable FDir SB capability. */
9763 	fcnt_prog = i40e_get_global_fd_count(pf);
9764 	fcnt_avail = pf->fdir_pf_filter_count;
9765 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
9766 	    (pf->fd_add_err == 0) ||
9767 	    (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
9768 		i40e_reenable_fdir_sb(pf);
9769 
9770 	/* We should wait for even more space before re-enabling ATR.
9771 	 * Additionally, we cannot enable ATR as long as we still have TCP SB
9772 	 * rules active.
9773 	 */
9774 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
9775 	    pf->fd_tcp4_filter_cnt == 0 && pf->fd_tcp6_filter_cnt == 0)
9776 		i40e_reenable_fdir_atr(pf);
9777 
9778 	/* if hw had a problem adding a filter, delete it */
9779 	if (pf->fd_inv > 0) {
9780 		hlist_for_each_entry_safe(filter, node,
9781 					  &pf->fdir_filter_list, fdir_node)
9782 			if (filter->fd_id == pf->fd_inv)
9783 				i40e_delete_invalid_filter(pf, filter);
9784 	}
9785 }
9786 
9787 #define I40E_MIN_FD_FLUSH_INTERVAL 10
9788 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
9789 /**
9790  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
9791  * @pf: board private structure
9792  **/
9793 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
9794 {
9795 	unsigned long min_flush_time;
9796 	int flush_wait_retry = 50;
9797 	bool disable_atr = false;
9798 	int fd_room;
9799 	int reg;
9800 
9801 	if (!time_after(jiffies, pf->fd_flush_timestamp +
9802 				 (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
9803 		return;
9804 
9805 	/* If the flush is happening too quick and we have mostly SB rules we
9806 	 * should not re-enable ATR for some time.
9807 	 */
9808 	min_flush_time = pf->fd_flush_timestamp +
9809 			 (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
9810 	fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
9811 
9812 	if (!(time_after(jiffies, min_flush_time)) &&
9813 	    (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
9814 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9815 			dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
9816 		disable_atr = true;
9817 	}
9818 
9819 	pf->fd_flush_timestamp = jiffies;
9820 	set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9821 	/* flush all filters */
9822 	wr32(&pf->hw, I40E_PFQF_CTL_1,
9823 	     I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
9824 	i40e_flush(&pf->hw);
9825 	pf->fd_flush_cnt++;
9826 	pf->fd_add_err = 0;
9827 	do {
9828 		/* Check FD flush status every 5-6msec */
9829 		usleep_range(5000, 6000);
9830 		reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
9831 		if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
9832 			break;
9833 	} while (flush_wait_retry--);
9834 	if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
9835 		dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
9836 	} else {
9837 		/* replay sideband filters */
9838 		i40e_fdir_filter_restore(i40e_pf_get_main_vsi(pf));
9839 		if (!disable_atr && !pf->fd_tcp4_filter_cnt)
9840 			clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9841 		clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
9842 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9843 			dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
9844 	}
9845 }
9846 
9847 /**
9848  * i40e_get_current_atr_cnt - Get the count of total FD ATR filters programmed
9849  * @pf: board private structure
9850  **/
9851 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
9852 {
9853 	return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
9854 }
9855 
9856 /**
9857  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
9858  * @pf: board private structure
9859  **/
9860 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
9861 {
9862 
9863 	/* if interface is down do nothing */
9864 	if (test_bit(__I40E_DOWN, pf->state))
9865 		return;
9866 
9867 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9868 		i40e_fdir_flush_and_replay(pf);
9869 
9870 	i40e_fdir_check_and_reenable(pf);
9871 
9872 }
9873 
9874 /**
9875  * i40e_vsi_link_event - notify VSI of a link event
9876  * @vsi: vsi to be notified
9877  * @link_up: link up or down
9878  **/
9879 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
9880 {
9881 	if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
9882 		return;
9883 
9884 	switch (vsi->type) {
9885 	case I40E_VSI_MAIN:
9886 		if (!vsi->netdev || !vsi->netdev_registered)
9887 			break;
9888 
9889 		if (link_up) {
9890 			netif_carrier_on(vsi->netdev);
9891 			netif_tx_wake_all_queues(vsi->netdev);
9892 		} else {
9893 			netif_carrier_off(vsi->netdev);
9894 			netif_tx_stop_all_queues(vsi->netdev);
9895 		}
9896 		break;
9897 
9898 	case I40E_VSI_SRIOV:
9899 	case I40E_VSI_VMDQ2:
9900 	case I40E_VSI_CTRL:
9901 	case I40E_VSI_IWARP:
9902 	case I40E_VSI_MIRROR:
9903 	default:
9904 		/* there is no notification for other VSIs */
9905 		break;
9906 	}
9907 }
9908 
9909 /**
9910  * i40e_veb_link_event - notify elements on the veb of a link event
9911  * @veb: veb to be notified
9912  * @link_up: link up or down
9913  **/
9914 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
9915 {
9916 	struct i40e_vsi *vsi;
9917 	struct i40e_pf *pf;
9918 	int i;
9919 
9920 	if (!veb || !veb->pf)
9921 		return;
9922 	pf = veb->pf;
9923 
9924 	/* Send link event to contained VSIs */
9925 	i40e_pf_for_each_vsi(pf, i, vsi)
9926 		if (vsi->uplink_seid == veb->seid)
9927 			i40e_vsi_link_event(vsi, link_up);
9928 }
9929 
9930 /**
9931  * i40e_link_event - Update netif_carrier status
9932  * @pf: board private structure
9933  **/
9934 static void i40e_link_event(struct i40e_pf *pf)
9935 {
9936 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
9937 	struct i40e_veb *veb = i40e_pf_get_main_veb(pf);
9938 	u8 new_link_speed, old_link_speed;
9939 	bool new_link, old_link;
9940 	int status;
9941 #ifdef CONFIG_I40E_DCB
9942 	int err;
9943 #endif /* CONFIG_I40E_DCB */
9944 
9945 	/* set this to force the get_link_status call to refresh state */
9946 	pf->hw.phy.get_link_info = true;
9947 	old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9948 	status = i40e_get_link_status(&pf->hw, &new_link);
9949 
9950 	/* On success, disable temp link polling */
9951 	if (status == 0) {
9952 		clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9953 	} else {
9954 		/* Enable link polling temporarily until i40e_get_link_status
9955 		 * returns 0
9956 		 */
9957 		set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9958 		dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9959 			status);
9960 		return;
9961 	}
9962 
9963 	old_link_speed = pf->hw.phy.link_info_old.link_speed;
9964 	new_link_speed = pf->hw.phy.link_info.link_speed;
9965 
9966 	if (new_link == old_link &&
9967 	    new_link_speed == old_link_speed &&
9968 	    (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9969 	     new_link == netif_carrier_ok(vsi->netdev)))
9970 		return;
9971 
9972 	i40e_print_link_message(vsi, new_link);
9973 
9974 	/* Notify the base of the switch tree connected to
9975 	 * the link.  Floating VEBs are not notified.
9976 	 */
9977 	if (veb)
9978 		i40e_veb_link_event(veb, new_link);
9979 	else
9980 		i40e_vsi_link_event(vsi, new_link);
9981 
9982 	if (pf->vf)
9983 		i40e_vc_notify_link_state(pf);
9984 
9985 	if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
9986 		i40e_ptp_set_increment(pf);
9987 #ifdef CONFIG_I40E_DCB
9988 	if (new_link == old_link)
9989 		return;
9990 	/* Not SW DCB so firmware will take care of default settings */
9991 	if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED)
9992 		return;
9993 
9994 	/* We cover here only link down, as after link up in case of SW DCB
9995 	 * SW LLDP agent will take care of setting it up
9996 	 */
9997 	if (!new_link) {
9998 		dev_dbg(&pf->pdev->dev, "Reconfig DCB to single TC as result of Link Down\n");
9999 		memset(&pf->tmp_cfg, 0, sizeof(pf->tmp_cfg));
10000 		err = i40e_dcb_sw_default_config(pf);
10001 		if (err) {
10002 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
10003 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
10004 		} else {
10005 			pf->dcbx_cap = DCB_CAP_DCBX_HOST |
10006 				       DCB_CAP_DCBX_VER_IEEE;
10007 			set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
10008 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
10009 		}
10010 	}
10011 #endif /* CONFIG_I40E_DCB */
10012 }
10013 
10014 /**
10015  * i40e_watchdog_subtask - periodic checks not using event driven response
10016  * @pf: board private structure
10017  **/
10018 static void i40e_watchdog_subtask(struct i40e_pf *pf)
10019 {
10020 	struct i40e_vsi *vsi;
10021 	struct i40e_veb *veb;
10022 	int i;
10023 
10024 	/* if interface is down do nothing */
10025 	if (test_bit(__I40E_DOWN, pf->state) ||
10026 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
10027 		return;
10028 
10029 	/* make sure we don't do these things too often */
10030 	if (time_before(jiffies, (pf->service_timer_previous +
10031 				  pf->service_timer_period)))
10032 		return;
10033 	pf->service_timer_previous = jiffies;
10034 
10035 	if (test_bit(I40E_FLAG_LINK_POLLING_ENA, pf->flags) ||
10036 	    test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
10037 		i40e_link_event(pf);
10038 
10039 	/* Update the stats for active netdevs so the network stack
10040 	 * can look at updated numbers whenever it cares to
10041 	 */
10042 	i40e_pf_for_each_vsi(pf, i, vsi)
10043 		if (vsi->netdev)
10044 			i40e_update_stats(vsi);
10045 
10046 	if (test_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags)) {
10047 		/* Update the stats for the active switching components */
10048 		i40e_pf_for_each_veb(pf, i, veb)
10049 			i40e_update_veb_stats(veb);
10050 	}
10051 
10052 	i40e_ptp_rx_hang(pf);
10053 	i40e_ptp_tx_hang(pf);
10054 }
10055 
10056 /**
10057  * i40e_reset_subtask - Set up for resetting the device and driver
10058  * @pf: board private structure
10059  **/
10060 static void i40e_reset_subtask(struct i40e_pf *pf)
10061 {
10062 	u32 reset_flags = 0;
10063 
10064 	if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
10065 		reset_flags |= BIT(__I40E_REINIT_REQUESTED);
10066 		clear_bit(__I40E_REINIT_REQUESTED, pf->state);
10067 	}
10068 	if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
10069 		reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
10070 		clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
10071 	}
10072 	if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
10073 		reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
10074 		clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
10075 	}
10076 	if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
10077 		reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
10078 		clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
10079 	}
10080 	if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
10081 		reset_flags |= BIT(__I40E_DOWN_REQUESTED);
10082 		clear_bit(__I40E_DOWN_REQUESTED, pf->state);
10083 	}
10084 
10085 	/* If there's a recovery already waiting, it takes
10086 	 * precedence before starting a new reset sequence.
10087 	 */
10088 	if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
10089 		i40e_prep_for_reset(pf);
10090 		i40e_reset(pf);
10091 		i40e_rebuild(pf, false, false);
10092 	}
10093 
10094 	/* If we're already down or resetting, just bail */
10095 	if (reset_flags &&
10096 	    !test_bit(__I40E_DOWN, pf->state) &&
10097 	    !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
10098 		i40e_do_reset(pf, reset_flags, false);
10099 	}
10100 }
10101 
10102 /**
10103  * i40e_handle_link_event - Handle link event
10104  * @pf: board private structure
10105  * @e: event info posted on ARQ
10106  **/
10107 static void i40e_handle_link_event(struct i40e_pf *pf,
10108 				   struct i40e_arq_event_info *e)
10109 {
10110 	struct i40e_aqc_get_link_status *status =
10111 		(struct i40e_aqc_get_link_status *)&e->desc.params.raw;
10112 
10113 	/* Do a new status request to re-enable LSE reporting
10114 	 * and load new status information into the hw struct
10115 	 * This completely ignores any state information
10116 	 * in the ARQ event info, instead choosing to always
10117 	 * issue the AQ update link status command.
10118 	 */
10119 	i40e_link_event(pf);
10120 
10121 	/* Check if module meets thermal requirements */
10122 	if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
10123 		dev_err(&pf->pdev->dev,
10124 			"Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
10125 		dev_err(&pf->pdev->dev,
10126 			"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10127 	} else {
10128 		/* check for unqualified module, if link is down, suppress
10129 		 * the message if link was forced to be down.
10130 		 */
10131 		if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
10132 		    (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
10133 		    (!(status->link_info & I40E_AQ_LINK_UP)) &&
10134 		    (!test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags))) {
10135 			dev_err(&pf->pdev->dev,
10136 				"Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
10137 			dev_err(&pf->pdev->dev,
10138 				"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10139 		}
10140 	}
10141 }
10142 
10143 /**
10144  * i40e_clean_adminq_subtask - Clean the AdminQ rings
10145  * @pf: board private structure
10146  **/
10147 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
10148 {
10149 	struct i40e_arq_event_info event;
10150 	struct i40e_hw *hw = &pf->hw;
10151 	u16 pending, i = 0;
10152 	u16 opcode;
10153 	u32 oldval;
10154 	int ret;
10155 	u32 val;
10156 
10157 	/* Do not run clean AQ when PF reset fails */
10158 	if (test_bit(__I40E_RESET_FAILED, pf->state))
10159 		return;
10160 
10161 	/* check for error indications */
10162 	val = rd32(&pf->hw, I40E_PF_ARQLEN);
10163 	oldval = val;
10164 	if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
10165 		if (hw->debug_mask & I40E_DEBUG_AQ)
10166 			dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
10167 		val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
10168 	}
10169 	if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
10170 		if (hw->debug_mask & I40E_DEBUG_AQ)
10171 			dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
10172 		val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
10173 		pf->arq_overflows++;
10174 	}
10175 	if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
10176 		if (hw->debug_mask & I40E_DEBUG_AQ)
10177 			dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
10178 		val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
10179 	}
10180 	if (oldval != val)
10181 		wr32(&pf->hw, I40E_PF_ARQLEN, val);
10182 
10183 	val = rd32(&pf->hw, I40E_PF_ATQLEN);
10184 	oldval = val;
10185 	if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
10186 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10187 			dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
10188 		val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
10189 	}
10190 	if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
10191 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10192 			dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
10193 		val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
10194 	}
10195 	if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
10196 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10197 			dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
10198 		val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
10199 	}
10200 	if (oldval != val)
10201 		wr32(&pf->hw, I40E_PF_ATQLEN, val);
10202 
10203 	event.buf_len = I40E_MAX_AQ_BUF_SIZE;
10204 	event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
10205 	if (!event.msg_buf)
10206 		return;
10207 
10208 	do {
10209 		ret = i40e_clean_arq_element(hw, &event, &pending);
10210 		if (ret == -EALREADY)
10211 			break;
10212 		else if (ret) {
10213 			dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
10214 			break;
10215 		}
10216 
10217 		opcode = le16_to_cpu(event.desc.opcode);
10218 		switch (opcode) {
10219 
10220 		case i40e_aqc_opc_get_link_status:
10221 			rtnl_lock();
10222 			i40e_handle_link_event(pf, &event);
10223 			rtnl_unlock();
10224 			break;
10225 		case i40e_aqc_opc_send_msg_to_pf:
10226 			ret = i40e_vc_process_vf_msg(pf,
10227 					le16_to_cpu(event.desc.retval),
10228 					le32_to_cpu(event.desc.cookie_high),
10229 					le32_to_cpu(event.desc.cookie_low),
10230 					event.msg_buf,
10231 					event.msg_len);
10232 			break;
10233 		case i40e_aqc_opc_lldp_update_mib:
10234 			dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
10235 #ifdef CONFIG_I40E_DCB
10236 			rtnl_lock();
10237 			i40e_handle_lldp_event(pf, &event);
10238 			rtnl_unlock();
10239 #endif /* CONFIG_I40E_DCB */
10240 			break;
10241 		case i40e_aqc_opc_event_lan_overflow:
10242 			dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
10243 			i40e_handle_lan_overflow_event(pf, &event);
10244 			break;
10245 		case i40e_aqc_opc_send_msg_to_peer:
10246 			dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
10247 			break;
10248 		case i40e_aqc_opc_nvm_erase:
10249 		case i40e_aqc_opc_nvm_update:
10250 		case i40e_aqc_opc_oem_post_update:
10251 			i40e_debug(&pf->hw, I40E_DEBUG_NVM,
10252 				   "ARQ NVM operation 0x%04x completed\n",
10253 				   opcode);
10254 			break;
10255 		default:
10256 			dev_info(&pf->pdev->dev,
10257 				 "ARQ: Unknown event 0x%04x ignored\n",
10258 				 opcode);
10259 			break;
10260 		}
10261 	} while (i++ < I40E_AQ_WORK_LIMIT);
10262 
10263 	if (i < I40E_AQ_WORK_LIMIT)
10264 		clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
10265 
10266 	/* re-enable Admin queue interrupt cause */
10267 	val = rd32(hw, I40E_PFINT_ICR0_ENA);
10268 	val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
10269 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
10270 	i40e_flush(hw);
10271 
10272 	kfree(event.msg_buf);
10273 }
10274 
10275 /**
10276  * i40e_verify_eeprom - make sure eeprom is good to use
10277  * @pf: board private structure
10278  **/
10279 static void i40e_verify_eeprom(struct i40e_pf *pf)
10280 {
10281 	int err;
10282 
10283 	err = i40e_diag_eeprom_test(&pf->hw);
10284 	if (err) {
10285 		/* retry in case of garbage read */
10286 		err = i40e_diag_eeprom_test(&pf->hw);
10287 		if (err) {
10288 			dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
10289 				 err);
10290 			set_bit(__I40E_BAD_EEPROM, pf->state);
10291 		}
10292 	}
10293 
10294 	if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
10295 		dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
10296 		clear_bit(__I40E_BAD_EEPROM, pf->state);
10297 	}
10298 }
10299 
10300 /**
10301  * i40e_enable_pf_switch_lb
10302  * @pf: pointer to the PF structure
10303  *
10304  * enable switch loop back or die - no point in a return value
10305  **/
10306 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
10307 {
10308 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
10309 	struct i40e_vsi_context ctxt;
10310 	int ret;
10311 
10312 	ctxt.seid = pf->main_vsi_seid;
10313 	ctxt.pf_num = pf->hw.pf_id;
10314 	ctxt.vf_num = 0;
10315 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10316 	if (ret) {
10317 		dev_info(&pf->pdev->dev,
10318 			 "couldn't get PF vsi config, err %pe aq_err %s\n",
10319 			 ERR_PTR(ret),
10320 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10321 		return;
10322 	}
10323 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10324 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10325 	ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10326 
10327 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10328 	if (ret) {
10329 		dev_info(&pf->pdev->dev,
10330 			 "update vsi switch failed, err %pe aq_err %s\n",
10331 			 ERR_PTR(ret),
10332 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10333 	}
10334 }
10335 
10336 /**
10337  * i40e_disable_pf_switch_lb
10338  * @pf: pointer to the PF structure
10339  *
10340  * disable switch loop back or die - no point in a return value
10341  **/
10342 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
10343 {
10344 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
10345 	struct i40e_vsi_context ctxt;
10346 	int ret;
10347 
10348 	ctxt.seid = pf->main_vsi_seid;
10349 	ctxt.pf_num = pf->hw.pf_id;
10350 	ctxt.vf_num = 0;
10351 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10352 	if (ret) {
10353 		dev_info(&pf->pdev->dev,
10354 			 "couldn't get PF vsi config, err %pe aq_err %s\n",
10355 			 ERR_PTR(ret),
10356 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10357 		return;
10358 	}
10359 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10360 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10361 	ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10362 
10363 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10364 	if (ret) {
10365 		dev_info(&pf->pdev->dev,
10366 			 "update vsi switch failed, err %pe aq_err %s\n",
10367 			 ERR_PTR(ret),
10368 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10369 	}
10370 }
10371 
10372 /**
10373  * i40e_config_bridge_mode - Configure the HW bridge mode
10374  * @veb: pointer to the bridge instance
10375  *
10376  * Configure the loop back mode for the LAN VSI that is downlink to the
10377  * specified HW bridge instance. It is expected this function is called
10378  * when a new HW bridge is instantiated.
10379  **/
10380 static void i40e_config_bridge_mode(struct i40e_veb *veb)
10381 {
10382 	struct i40e_pf *pf = veb->pf;
10383 
10384 	if (pf->hw.debug_mask & I40E_DEBUG_LAN)
10385 		dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
10386 			 veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
10387 	if (veb->bridge_mode & BRIDGE_MODE_VEPA)
10388 		i40e_disable_pf_switch_lb(pf);
10389 	else
10390 		i40e_enable_pf_switch_lb(pf);
10391 }
10392 
10393 /**
10394  * i40e_reconstitute_veb - rebuild the VEB and VSIs connected to it
10395  * @veb: pointer to the VEB instance
10396  *
10397  * This is a function that builds the attached VSIs. We track the connections
10398  * through our own index numbers because the seid's from the HW could change
10399  * across the reset.
10400  **/
10401 static int i40e_reconstitute_veb(struct i40e_veb *veb)
10402 {
10403 	struct i40e_vsi *ctl_vsi = NULL;
10404 	struct i40e_pf *pf = veb->pf;
10405 	struct i40e_vsi *vsi;
10406 	int v, ret;
10407 
10408 	/* As we do not maintain PV (port virtualizer) switch element then
10409 	 * there can be only one non-floating VEB that have uplink to MAC SEID
10410 	 * and its control VSI is the main one.
10411 	 */
10412 	if (WARN_ON(veb->uplink_seid && veb->uplink_seid != pf->mac_seid)) {
10413 		dev_err(&pf->pdev->dev,
10414 			"Invalid uplink SEID for VEB %d\n", veb->idx);
10415 		return -ENOENT;
10416 	}
10417 
10418 	if (veb->uplink_seid == pf->mac_seid) {
10419 		/* Check that the LAN VSI has VEB owning flag set */
10420 		ctl_vsi = i40e_pf_get_main_vsi(pf);
10421 
10422 		if (WARN_ON(ctl_vsi->veb_idx != veb->idx ||
10423 			    !(ctl_vsi->flags & I40E_VSI_FLAG_VEB_OWNER))) {
10424 			dev_err(&pf->pdev->dev,
10425 				"Invalid control VSI for VEB %d\n", veb->idx);
10426 			return -ENOENT;
10427 		}
10428 
10429 		/* Add the control VSI to switch */
10430 		ret = i40e_add_vsi(ctl_vsi);
10431 		if (ret) {
10432 			dev_err(&pf->pdev->dev,
10433 				"Rebuild of owner VSI for VEB %d failed: %d\n",
10434 				veb->idx, ret);
10435 			return ret;
10436 		}
10437 
10438 		i40e_vsi_reset_stats(ctl_vsi);
10439 	}
10440 
10441 	/* create the VEB in the switch and move the VSI onto the VEB */
10442 	ret = i40e_add_veb(veb, ctl_vsi);
10443 	if (ret)
10444 		return ret;
10445 
10446 	if (veb->uplink_seid) {
10447 		if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags))
10448 			veb->bridge_mode = BRIDGE_MODE_VEB;
10449 		else
10450 			veb->bridge_mode = BRIDGE_MODE_VEPA;
10451 		i40e_config_bridge_mode(veb);
10452 	}
10453 
10454 	/* create the remaining VSIs attached to this VEB */
10455 	i40e_pf_for_each_vsi(pf, v, vsi) {
10456 		if (vsi == ctl_vsi)
10457 			continue;
10458 
10459 		if (vsi->veb_idx == veb->idx) {
10460 			vsi->uplink_seid = veb->seid;
10461 			ret = i40e_add_vsi(vsi);
10462 			if (ret) {
10463 				dev_info(&pf->pdev->dev,
10464 					 "rebuild of vsi_idx %d failed: %d\n",
10465 					 v, ret);
10466 				return ret;
10467 			}
10468 			i40e_vsi_reset_stats(vsi);
10469 		}
10470 	}
10471 
10472 	return ret;
10473 }
10474 
10475 /**
10476  * i40e_get_capabilities - get info about the HW
10477  * @pf: the PF struct
10478  * @list_type: AQ capability to be queried
10479  **/
10480 static int i40e_get_capabilities(struct i40e_pf *pf,
10481 				 enum i40e_admin_queue_opc list_type)
10482 {
10483 	struct i40e_aqc_list_capabilities_element_resp *cap_buf;
10484 	u16 data_size;
10485 	int buf_len;
10486 	int err;
10487 
10488 	buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
10489 	do {
10490 		cap_buf = kzalloc(buf_len, GFP_KERNEL);
10491 		if (!cap_buf)
10492 			return -ENOMEM;
10493 
10494 		/* this loads the data into the hw struct for us */
10495 		err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
10496 						    &data_size, list_type,
10497 						    NULL);
10498 		/* data loaded, buffer no longer needed */
10499 		kfree(cap_buf);
10500 
10501 		if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
10502 			/* retry with a larger buffer */
10503 			buf_len = data_size;
10504 		} else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK || err) {
10505 			dev_info(&pf->pdev->dev,
10506 				 "capability discovery failed, err %pe aq_err %s\n",
10507 				 ERR_PTR(err),
10508 				 i40e_aq_str(&pf->hw,
10509 					     pf->hw.aq.asq_last_status));
10510 			return -ENODEV;
10511 		}
10512 	} while (err);
10513 
10514 	if (pf->hw.debug_mask & I40E_DEBUG_USER) {
10515 		if (list_type == i40e_aqc_opc_list_func_capabilities) {
10516 			dev_info(&pf->pdev->dev,
10517 				 "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",
10518 				 pf->hw.pf_id, pf->hw.func_caps.num_vfs,
10519 				 pf->hw.func_caps.num_msix_vectors,
10520 				 pf->hw.func_caps.num_msix_vectors_vf,
10521 				 pf->hw.func_caps.fd_filters_guaranteed,
10522 				 pf->hw.func_caps.fd_filters_best_effort,
10523 				 pf->hw.func_caps.num_tx_qp,
10524 				 pf->hw.func_caps.num_vsis);
10525 		} else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
10526 			dev_info(&pf->pdev->dev,
10527 				 "switch_mode=0x%04x, function_valid=0x%08x\n",
10528 				 pf->hw.dev_caps.switch_mode,
10529 				 pf->hw.dev_caps.valid_functions);
10530 			dev_info(&pf->pdev->dev,
10531 				 "SR-IOV=%d, num_vfs for all function=%u\n",
10532 				 pf->hw.dev_caps.sr_iov_1_1,
10533 				 pf->hw.dev_caps.num_vfs);
10534 			dev_info(&pf->pdev->dev,
10535 				 "num_vsis=%u, num_rx:%u, num_tx=%u\n",
10536 				 pf->hw.dev_caps.num_vsis,
10537 				 pf->hw.dev_caps.num_rx_qp,
10538 				 pf->hw.dev_caps.num_tx_qp);
10539 		}
10540 	}
10541 	if (list_type == i40e_aqc_opc_list_func_capabilities) {
10542 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
10543 		       + pf->hw.func_caps.num_vfs)
10544 		if (pf->hw.revision_id == 0 &&
10545 		    pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
10546 			dev_info(&pf->pdev->dev,
10547 				 "got num_vsis %d, setting num_vsis to %d\n",
10548 				 pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
10549 			pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
10550 		}
10551 	}
10552 	return 0;
10553 }
10554 
10555 static int i40e_vsi_clear(struct i40e_vsi *vsi);
10556 
10557 /**
10558  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
10559  * @pf: board private structure
10560  **/
10561 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
10562 {
10563 	struct i40e_vsi *main_vsi, *vsi;
10564 
10565 	/* quick workaround for an NVM issue that leaves a critical register
10566 	 * uninitialized
10567 	 */
10568 	if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
10569 		static const u32 hkey[] = {
10570 			0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
10571 			0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
10572 			0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
10573 			0x95b3a76d};
10574 		int i;
10575 
10576 		for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
10577 			wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
10578 	}
10579 
10580 	if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
10581 		return;
10582 
10583 	/* find existing VSI and see if it needs configuring */
10584 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10585 
10586 	/* create a new VSI if none exists */
10587 	if (!vsi) {
10588 		main_vsi = i40e_pf_get_main_vsi(pf);
10589 		vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR, main_vsi->seid, 0);
10590 		if (!vsi) {
10591 			dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
10592 			clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
10593 			set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
10594 			return;
10595 		}
10596 	}
10597 
10598 	i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
10599 }
10600 
10601 /**
10602  * i40e_fdir_teardown - release the Flow Director resources
10603  * @pf: board private structure
10604  **/
10605 static void i40e_fdir_teardown(struct i40e_pf *pf)
10606 {
10607 	struct i40e_vsi *vsi;
10608 
10609 	i40e_fdir_filter_exit(pf);
10610 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10611 	if (vsi)
10612 		i40e_vsi_release(vsi);
10613 }
10614 
10615 /**
10616  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
10617  * @vsi: PF main vsi
10618  * @seid: seid of main or channel VSIs
10619  *
10620  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
10621  * existed before reset
10622  **/
10623 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
10624 {
10625 	struct i40e_cloud_filter *cfilter;
10626 	struct i40e_pf *pf = vsi->back;
10627 	struct hlist_node *node;
10628 	int ret;
10629 
10630 	/* Add cloud filters back if they exist */
10631 	hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
10632 				  cloud_node) {
10633 		if (cfilter->seid != seid)
10634 			continue;
10635 
10636 		if (cfilter->dst_port)
10637 			ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
10638 								true);
10639 		else
10640 			ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
10641 
10642 		if (ret) {
10643 			dev_dbg(&pf->pdev->dev,
10644 				"Failed to rebuild cloud filter, err %pe aq_err %s\n",
10645 				ERR_PTR(ret),
10646 				i40e_aq_str(&pf->hw,
10647 					    pf->hw.aq.asq_last_status));
10648 			return ret;
10649 		}
10650 	}
10651 	return 0;
10652 }
10653 
10654 /**
10655  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
10656  * @vsi: PF main vsi
10657  *
10658  * Rebuilds channel VSIs if they existed before reset
10659  **/
10660 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
10661 {
10662 	struct i40e_channel *ch, *ch_tmp;
10663 	int ret;
10664 
10665 	if (list_empty(&vsi->ch_list))
10666 		return 0;
10667 
10668 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
10669 		if (!ch->initialized)
10670 			break;
10671 		/* Proceed with creation of channel (VMDq2) VSI */
10672 		ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
10673 		if (ret) {
10674 			dev_info(&vsi->back->pdev->dev,
10675 				 "failed to rebuild channels using uplink_seid %u\n",
10676 				 vsi->uplink_seid);
10677 			return ret;
10678 		}
10679 		/* Reconfigure TX queues using QTX_CTL register */
10680 		ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
10681 		if (ret) {
10682 			dev_info(&vsi->back->pdev->dev,
10683 				 "failed to configure TX rings for channel %u\n",
10684 				 ch->seid);
10685 			return ret;
10686 		}
10687 		/* update 'next_base_queue' */
10688 		vsi->next_base_queue = vsi->next_base_queue +
10689 							ch->num_queue_pairs;
10690 		if (ch->max_tx_rate) {
10691 			u64 credits = ch->max_tx_rate;
10692 
10693 			if (i40e_set_bw_limit(vsi, ch->seid,
10694 					      ch->max_tx_rate))
10695 				return -EINVAL;
10696 
10697 			do_div(credits, I40E_BW_CREDIT_DIVISOR);
10698 			dev_dbg(&vsi->back->pdev->dev,
10699 				"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10700 				ch->max_tx_rate,
10701 				credits,
10702 				ch->seid);
10703 		}
10704 		ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
10705 		if (ret) {
10706 			dev_dbg(&vsi->back->pdev->dev,
10707 				"Failed to rebuild cloud filters for channel VSI %u\n",
10708 				ch->seid);
10709 			return ret;
10710 		}
10711 	}
10712 	return 0;
10713 }
10714 
10715 /**
10716  * i40e_clean_xps_state - clean xps state for every tx_ring
10717  * @vsi: ptr to the VSI
10718  **/
10719 static void i40e_clean_xps_state(struct i40e_vsi *vsi)
10720 {
10721 	int i;
10722 
10723 	if (vsi->tx_rings)
10724 		for (i = 0; i < vsi->num_queue_pairs; i++)
10725 			if (vsi->tx_rings[i])
10726 				clear_bit(__I40E_TX_XPS_INIT_DONE,
10727 					  vsi->tx_rings[i]->state);
10728 }
10729 
10730 /**
10731  * i40e_prep_for_reset - prep for the core to reset
10732  * @pf: board private structure
10733  *
10734  * Close up the VFs and other things in prep for PF Reset.
10735   **/
10736 static void i40e_prep_for_reset(struct i40e_pf *pf)
10737 {
10738 	struct i40e_hw *hw = &pf->hw;
10739 	struct i40e_vsi *vsi;
10740 	int ret = 0;
10741 	u32 v;
10742 
10743 	clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
10744 	if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
10745 		return;
10746 	if (i40e_check_asq_alive(&pf->hw))
10747 		i40e_vc_notify_reset(pf);
10748 
10749 	dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
10750 
10751 	/* quiesce the VSIs and their queues that are not already DOWN */
10752 	i40e_pf_quiesce_all_vsi(pf);
10753 
10754 	i40e_pf_for_each_vsi(pf, v, vsi) {
10755 		i40e_clean_xps_state(vsi);
10756 		vsi->seid = 0;
10757 	}
10758 
10759 	i40e_shutdown_adminq(&pf->hw);
10760 
10761 	/* call shutdown HMC */
10762 	if (hw->hmc.hmc_obj) {
10763 		ret = i40e_shutdown_lan_hmc(hw);
10764 		if (ret)
10765 			dev_warn(&pf->pdev->dev,
10766 				 "shutdown_lan_hmc failed: %d\n", ret);
10767 	}
10768 
10769 	/* Save the current PTP time so that we can restore the time after the
10770 	 * reset completes.
10771 	 */
10772 	i40e_ptp_save_hw_time(pf);
10773 }
10774 
10775 /**
10776  * i40e_send_version - update firmware with driver version
10777  * @pf: PF struct
10778  */
10779 static void i40e_send_version(struct i40e_pf *pf)
10780 {
10781 	struct i40e_driver_version dv;
10782 
10783 	dv.major_version = 0xff;
10784 	dv.minor_version = 0xff;
10785 	dv.build_version = 0xff;
10786 	dv.subbuild_version = 0;
10787 	strscpy(dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string));
10788 	i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
10789 }
10790 
10791 /**
10792  * i40e_get_oem_version - get OEM specific version information
10793  * @hw: pointer to the hardware structure
10794  **/
10795 static void i40e_get_oem_version(struct i40e_hw *hw)
10796 {
10797 	u16 block_offset = 0xffff;
10798 	u16 block_length = 0;
10799 	u16 capabilities = 0;
10800 	u16 gen_snap = 0;
10801 	u16 release = 0;
10802 
10803 #define I40E_SR_NVM_OEM_VERSION_PTR		0x1B
10804 #define I40E_NVM_OEM_LENGTH_OFFSET		0x00
10805 #define I40E_NVM_OEM_CAPABILITIES_OFFSET	0x01
10806 #define I40E_NVM_OEM_GEN_OFFSET			0x02
10807 #define I40E_NVM_OEM_RELEASE_OFFSET		0x03
10808 #define I40E_NVM_OEM_CAPABILITIES_MASK		0x000F
10809 #define I40E_NVM_OEM_LENGTH			3
10810 
10811 	/* Check if pointer to OEM version block is valid. */
10812 	i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
10813 	if (block_offset == 0xffff)
10814 		return;
10815 
10816 	/* Check if OEM version block has correct length. */
10817 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
10818 			   &block_length);
10819 	if (block_length < I40E_NVM_OEM_LENGTH)
10820 		return;
10821 
10822 	/* Check if OEM version format is as expected. */
10823 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
10824 			   &capabilities);
10825 	if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
10826 		return;
10827 
10828 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
10829 			   &gen_snap);
10830 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
10831 			   &release);
10832 	hw->nvm.oem_ver =
10833 		FIELD_PREP(I40E_OEM_GEN_MASK | I40E_OEM_SNAP_MASK, gen_snap) |
10834 		FIELD_PREP(I40E_OEM_RELEASE_MASK, release);
10835 	hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
10836 }
10837 
10838 /**
10839  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
10840  * @pf: board private structure
10841  **/
10842 static int i40e_reset(struct i40e_pf *pf)
10843 {
10844 	struct i40e_hw *hw = &pf->hw;
10845 	int ret;
10846 
10847 	ret = i40e_pf_reset(hw);
10848 	if (ret) {
10849 		dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
10850 		set_bit(__I40E_RESET_FAILED, pf->state);
10851 		clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10852 	} else {
10853 		pf->pfr_count++;
10854 	}
10855 	return ret;
10856 }
10857 
10858 /**
10859  * i40e_rebuild - rebuild using a saved config
10860  * @pf: board private structure
10861  * @reinit: if the Main VSI needs to re-initialized.
10862  * @lock_acquired: indicates whether or not the lock has been acquired
10863  * before this function was called.
10864  **/
10865 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
10866 {
10867 	const bool is_recovery_mode_reported = i40e_check_recovery_mode(pf);
10868 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
10869 	struct i40e_hw *hw = &pf->hw;
10870 	struct i40e_veb *veb;
10871 	int ret;
10872 	u32 val;
10873 	int v;
10874 
10875 	if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10876 	    is_recovery_mode_reported)
10877 		i40e_set_ethtool_ops(vsi->netdev);
10878 
10879 	if (test_bit(__I40E_DOWN, pf->state) &&
10880 	    !test_bit(__I40E_RECOVERY_MODE, pf->state))
10881 		goto clear_recovery;
10882 	dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
10883 
10884 	/* rebuild the basics for the AdminQ, HMC, and initial HW switch */
10885 	ret = i40e_init_adminq(&pf->hw);
10886 	if (ret) {
10887 		dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %pe aq_err %s\n",
10888 			 ERR_PTR(ret),
10889 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10890 		goto clear_recovery;
10891 	}
10892 	i40e_get_oem_version(&pf->hw);
10893 
10894 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state)) {
10895 		/* The following delay is necessary for firmware update. */
10896 		mdelay(1000);
10897 	}
10898 
10899 	/* re-verify the eeprom if we just had an EMP reset */
10900 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
10901 		i40e_verify_eeprom(pf);
10902 
10903 	/* if we are going out of or into recovery mode we have to act
10904 	 * accordingly with regard to resources initialization
10905 	 * and deinitialization
10906 	 */
10907 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10908 		if (i40e_get_capabilities(pf,
10909 					  i40e_aqc_opc_list_func_capabilities))
10910 			goto end_unlock;
10911 
10912 		if (is_recovery_mode_reported) {
10913 			/* we're staying in recovery mode so we'll reinitialize
10914 			 * misc vector here
10915 			 */
10916 			if (i40e_setup_misc_vector_for_recovery_mode(pf))
10917 				goto end_unlock;
10918 		} else {
10919 			if (!lock_acquired)
10920 				rtnl_lock();
10921 			/* we're going out of recovery mode so we'll free
10922 			 * the IRQ allocated specifically for recovery mode
10923 			 * and restore the interrupt scheme
10924 			 */
10925 			free_irq(pf->pdev->irq, pf);
10926 			i40e_clear_interrupt_scheme(pf);
10927 			if (i40e_restore_interrupt_scheme(pf))
10928 				goto end_unlock;
10929 		}
10930 
10931 		/* tell the firmware that we're starting */
10932 		i40e_send_version(pf);
10933 
10934 		/* bail out in case recovery mode was detected, as there is
10935 		 * no need for further configuration.
10936 		 */
10937 		goto end_unlock;
10938 	}
10939 
10940 	i40e_clear_pxe_mode(hw);
10941 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10942 	if (ret)
10943 		goto end_core_reset;
10944 
10945 	ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10946 				hw->func_caps.num_rx_qp, 0, 0);
10947 	if (ret) {
10948 		dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10949 		goto end_core_reset;
10950 	}
10951 	ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10952 	if (ret) {
10953 		dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10954 		goto end_core_reset;
10955 	}
10956 
10957 #ifdef CONFIG_I40E_DCB
10958 	/* Enable FW to write a default DCB config on link-up
10959 	 * unless I40E_FLAG_TC_MQPRIO was enabled or DCB
10960 	 * is not supported with new link speed
10961 	 */
10962 	if (i40e_is_tc_mqprio_enabled(pf)) {
10963 		i40e_aq_set_dcb_parameters(hw, false, NULL);
10964 	} else {
10965 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
10966 		    (hw->phy.link_info.link_speed &
10967 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
10968 			i40e_aq_set_dcb_parameters(hw, false, NULL);
10969 			dev_warn(&pf->pdev->dev,
10970 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
10971 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
10972 		} else {
10973 			i40e_aq_set_dcb_parameters(hw, true, NULL);
10974 			ret = i40e_init_pf_dcb(pf);
10975 			if (ret) {
10976 				dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n",
10977 					 ret);
10978 				clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
10979 				/* Continue without DCB enabled */
10980 			}
10981 		}
10982 	}
10983 
10984 #endif /* CONFIG_I40E_DCB */
10985 	if (!lock_acquired)
10986 		rtnl_lock();
10987 	ret = i40e_setup_pf_switch(pf, reinit, true);
10988 	if (ret)
10989 		goto end_unlock;
10990 
10991 	/* The driver only wants link up/down and module qualification
10992 	 * reports from firmware.  Note the negative logic.
10993 	 */
10994 	ret = i40e_aq_set_phy_int_mask(&pf->hw,
10995 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
10996 					 I40E_AQ_EVENT_MEDIA_NA |
10997 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10998 	if (ret)
10999 		dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
11000 			 ERR_PTR(ret),
11001 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11002 
11003 	/* Rebuild the VSIs and VEBs that existed before reset.
11004 	 * They are still in our local switch element arrays, so only
11005 	 * need to rebuild the switch model in the HW.
11006 	 *
11007 	 * If there were VEBs but the reconstitution failed, we'll try
11008 	 * to recover minimal use by getting the basic PF VSI working.
11009 	 */
11010 	if (vsi->uplink_seid != pf->mac_seid) {
11011 		dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
11012 
11013 		/* Rebuild VEBs */
11014 		i40e_pf_for_each_veb(pf, v, veb) {
11015 			ret = i40e_reconstitute_veb(veb);
11016 			if (!ret)
11017 				continue;
11018 
11019 			/* If Main VEB failed, we're in deep doodoo,
11020 			 * so give up rebuilding the switch and set up
11021 			 * for minimal rebuild of PF VSI.
11022 			 * If orphan failed, we'll report the error
11023 			 * but try to keep going.
11024 			 */
11025 			if (veb->uplink_seid == pf->mac_seid) {
11026 				dev_info(&pf->pdev->dev,
11027 					 "rebuild of switch failed: %d, will try to set up simple PF connection\n",
11028 					 ret);
11029 				vsi->uplink_seid = pf->mac_seid;
11030 				break;
11031 			} else if (veb->uplink_seid == 0) {
11032 				dev_info(&pf->pdev->dev,
11033 					 "rebuild of orphan VEB failed: %d\n",
11034 					 ret);
11035 			}
11036 		}
11037 	}
11038 
11039 	if (vsi->uplink_seid == pf->mac_seid) {
11040 		dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
11041 		/* no VEB, so rebuild only the Main VSI */
11042 		ret = i40e_add_vsi(vsi);
11043 		if (ret) {
11044 			dev_info(&pf->pdev->dev,
11045 				 "rebuild of Main VSI failed: %d\n", ret);
11046 			goto end_unlock;
11047 		}
11048 	}
11049 
11050 	if (vsi->mqprio_qopt.max_rate[0]) {
11051 		u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
11052 						  vsi->mqprio_qopt.max_rate[0]);
11053 		u64 credits = 0;
11054 
11055 		ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
11056 		if (ret)
11057 			goto end_unlock;
11058 
11059 		credits = max_tx_rate;
11060 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
11061 		dev_dbg(&vsi->back->pdev->dev,
11062 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
11063 			max_tx_rate,
11064 			credits,
11065 			vsi->seid);
11066 	}
11067 
11068 	ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
11069 	if (ret)
11070 		goto end_unlock;
11071 
11072 	/* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
11073 	 * for this main VSI if they exist
11074 	 */
11075 	ret = i40e_rebuild_channels(vsi);
11076 	if (ret)
11077 		goto end_unlock;
11078 
11079 	/* Reconfigure hardware for allowing smaller MSS in the case
11080 	 * of TSO, so that we avoid the MDD being fired and causing
11081 	 * a reset in the case of small MSS+TSO.
11082 	 */
11083 #define I40E_REG_MSS          0x000E64DC
11084 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
11085 #define I40E_64BYTE_MSS       0x400000
11086 	val = rd32(hw, I40E_REG_MSS);
11087 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
11088 		val &= ~I40E_REG_MSS_MIN_MASK;
11089 		val |= I40E_64BYTE_MSS;
11090 		wr32(hw, I40E_REG_MSS, val);
11091 	}
11092 
11093 	if (test_bit(I40E_HW_CAP_RESTART_AUTONEG, pf->hw.caps)) {
11094 		msleep(75);
11095 		ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
11096 		if (ret)
11097 			dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
11098 				 ERR_PTR(ret),
11099 				 i40e_aq_str(&pf->hw,
11100 					     pf->hw.aq.asq_last_status));
11101 	}
11102 	/* reinit the misc interrupt */
11103 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
11104 		ret = i40e_setup_misc_vector(pf);
11105 		if (ret)
11106 			goto end_unlock;
11107 	}
11108 
11109 	/* Add a filter to drop all Flow control frames from any VSI from being
11110 	 * transmitted. By doing so we stop a malicious VF from sending out
11111 	 * PAUSE or PFC frames and potentially controlling traffic for other
11112 	 * PF/VF VSIs.
11113 	 * The FW can still send Flow control frames if enabled.
11114 	 */
11115 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
11116 						       pf->main_vsi_seid);
11117 
11118 	/* restart the VSIs that were rebuilt and running before the reset */
11119 	i40e_pf_unquiesce_all_vsi(pf);
11120 
11121 	/* Release the RTNL lock before we start resetting VFs */
11122 	if (!lock_acquired)
11123 		rtnl_unlock();
11124 
11125 	/* Restore promiscuous settings */
11126 	ret = i40e_set_promiscuous(pf, pf->cur_promisc);
11127 	if (ret)
11128 		dev_warn(&pf->pdev->dev,
11129 			 "Failed to restore promiscuous setting: %s, err %pe aq_err %s\n",
11130 			 pf->cur_promisc ? "on" : "off",
11131 			 ERR_PTR(ret),
11132 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11133 
11134 	i40e_reset_all_vfs(pf, true);
11135 
11136 	/* tell the firmware that we're starting */
11137 	i40e_send_version(pf);
11138 
11139 	/* We've already released the lock, so don't do it again */
11140 	goto end_core_reset;
11141 
11142 end_unlock:
11143 	if (!lock_acquired)
11144 		rtnl_unlock();
11145 end_core_reset:
11146 	clear_bit(__I40E_RESET_FAILED, pf->state);
11147 clear_recovery:
11148 	clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
11149 	clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
11150 }
11151 
11152 /**
11153  * i40e_reset_and_rebuild - reset and rebuild using a saved config
11154  * @pf: board private structure
11155  * @reinit: if the Main VSI needs to re-initialized.
11156  * @lock_acquired: indicates whether or not the lock has been acquired
11157  * before this function was called.
11158  **/
11159 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
11160 				   bool lock_acquired)
11161 {
11162 	int ret;
11163 
11164 	if (test_bit(__I40E_IN_REMOVE, pf->state))
11165 		return;
11166 	/* Now we wait for GRST to settle out.
11167 	 * We don't have to delete the VEBs or VSIs from the hw switch
11168 	 * because the reset will make them disappear.
11169 	 */
11170 	ret = i40e_reset(pf);
11171 	if (!ret)
11172 		i40e_rebuild(pf, reinit, lock_acquired);
11173 	else
11174 		dev_err(&pf->pdev->dev, "%s: i40e_reset() FAILED", __func__);
11175 }
11176 
11177 /**
11178  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
11179  * @pf: board private structure
11180  *
11181  * Close up the VFs and other things in prep for a Core Reset,
11182  * then get ready to rebuild the world.
11183  * @lock_acquired: indicates whether or not the lock has been acquired
11184  * before this function was called.
11185  **/
11186 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
11187 {
11188 	i40e_prep_for_reset(pf);
11189 	i40e_reset_and_rebuild(pf, false, lock_acquired);
11190 }
11191 
11192 /**
11193  * i40e_handle_mdd_event
11194  * @pf: pointer to the PF structure
11195  *
11196  * Called from the MDD irq handler to identify possibly malicious vfs
11197  **/
11198 static void i40e_handle_mdd_event(struct i40e_pf *pf)
11199 {
11200 	struct i40e_hw *hw = &pf->hw;
11201 	bool mdd_detected = false;
11202 	struct i40e_vf *vf;
11203 	u32 reg;
11204 	int i;
11205 
11206 	if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
11207 		return;
11208 
11209 	/* find what triggered the MDD event */
11210 	reg = rd32(hw, I40E_GL_MDET_TX);
11211 	if (reg & I40E_GL_MDET_TX_VALID_MASK) {
11212 		u8 pf_num = FIELD_GET(I40E_GL_MDET_TX_PF_NUM_MASK, reg);
11213 		u16 vf_num = FIELD_GET(I40E_GL_MDET_TX_VF_NUM_MASK, reg);
11214 		u8 event = FIELD_GET(I40E_GL_MDET_TX_EVENT_MASK, reg);
11215 		u16 queue = FIELD_GET(I40E_GL_MDET_TX_QUEUE_MASK, reg) -
11216 				pf->hw.func_caps.base_queue;
11217 		if (netif_msg_tx_err(pf))
11218 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
11219 				 event, queue, pf_num, vf_num);
11220 		wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
11221 		mdd_detected = true;
11222 	}
11223 	reg = rd32(hw, I40E_GL_MDET_RX);
11224 	if (reg & I40E_GL_MDET_RX_VALID_MASK) {
11225 		u8 func = FIELD_GET(I40E_GL_MDET_RX_FUNCTION_MASK, reg);
11226 		u8 event = FIELD_GET(I40E_GL_MDET_RX_EVENT_MASK, reg);
11227 		u16 queue = FIELD_GET(I40E_GL_MDET_RX_QUEUE_MASK, reg) -
11228 				pf->hw.func_caps.base_queue;
11229 		if (netif_msg_rx_err(pf))
11230 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
11231 				 event, queue, func);
11232 		wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
11233 		mdd_detected = true;
11234 	}
11235 
11236 	if (mdd_detected) {
11237 		reg = rd32(hw, I40E_PF_MDET_TX);
11238 		if (reg & I40E_PF_MDET_TX_VALID_MASK) {
11239 			wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
11240 			dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
11241 		}
11242 		reg = rd32(hw, I40E_PF_MDET_RX);
11243 		if (reg & I40E_PF_MDET_RX_VALID_MASK) {
11244 			wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
11245 			dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
11246 		}
11247 	}
11248 
11249 	/* see if one of the VFs needs its hand slapped */
11250 	for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
11251 		vf = &(pf->vf[i]);
11252 		reg = rd32(hw, I40E_VP_MDET_TX(i));
11253 		if (reg & I40E_VP_MDET_TX_VALID_MASK) {
11254 			wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
11255 			vf->num_mdd_events++;
11256 			dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
11257 				 i);
11258 			dev_info(&pf->pdev->dev,
11259 				 "Use PF Control I/F to re-enable the VF\n");
11260 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11261 		}
11262 
11263 		reg = rd32(hw, I40E_VP_MDET_RX(i));
11264 		if (reg & I40E_VP_MDET_RX_VALID_MASK) {
11265 			wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
11266 			vf->num_mdd_events++;
11267 			dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
11268 				 i);
11269 			dev_info(&pf->pdev->dev,
11270 				 "Use PF Control I/F to re-enable the VF\n");
11271 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11272 		}
11273 	}
11274 
11275 	/* re-enable mdd interrupt cause */
11276 	clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
11277 	reg = rd32(hw, I40E_PFINT_ICR0_ENA);
11278 	reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
11279 	wr32(hw, I40E_PFINT_ICR0_ENA, reg);
11280 	i40e_flush(hw);
11281 }
11282 
11283 /**
11284  * i40e_service_task - Run the driver's async subtasks
11285  * @work: pointer to work_struct containing our data
11286  **/
11287 static void i40e_service_task(struct work_struct *work)
11288 {
11289 	struct i40e_pf *pf = container_of(work,
11290 					  struct i40e_pf,
11291 					  service_task);
11292 	unsigned long start_time = jiffies;
11293 
11294 	/* don't bother with service tasks if a reset is in progress */
11295 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
11296 	    test_bit(__I40E_SUSPENDED, pf->state))
11297 		return;
11298 
11299 	if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
11300 		return;
11301 
11302 	if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
11303 		i40e_detect_recover_hung(pf);
11304 		i40e_sync_filters_subtask(pf);
11305 		i40e_reset_subtask(pf);
11306 		i40e_handle_mdd_event(pf);
11307 		i40e_vc_process_vflr_event(pf);
11308 		i40e_watchdog_subtask(pf);
11309 		i40e_fdir_reinit_subtask(pf);
11310 		if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
11311 			/* Client subtask will reopen next time through. */
11312 			i40e_notify_client_of_netdev_close(pf, true);
11313 		} else {
11314 			i40e_client_subtask(pf);
11315 			if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
11316 					       pf->state))
11317 				i40e_notify_client_of_l2_param_changes(pf);
11318 		}
11319 		i40e_sync_filters_subtask(pf);
11320 	} else {
11321 		i40e_reset_subtask(pf);
11322 	}
11323 
11324 	i40e_clean_adminq_subtask(pf);
11325 
11326 	/* flush memory to make sure state is correct before next watchdog */
11327 	smp_mb__before_atomic();
11328 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
11329 
11330 	/* If the tasks have taken longer than one timer cycle or there
11331 	 * is more work to be done, reschedule the service task now
11332 	 * rather than wait for the timer to tick again.
11333 	 */
11334 	if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
11335 	    test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)		 ||
11336 	    test_bit(__I40E_MDD_EVENT_PENDING, pf->state)		 ||
11337 	    test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
11338 		i40e_service_event_schedule(pf);
11339 }
11340 
11341 /**
11342  * i40e_service_timer - timer callback
11343  * @t: timer list pointer
11344  **/
11345 static void i40e_service_timer(struct timer_list *t)
11346 {
11347 	struct i40e_pf *pf = from_timer(pf, t, service_timer);
11348 
11349 	mod_timer(&pf->service_timer,
11350 		  round_jiffies(jiffies + pf->service_timer_period));
11351 	i40e_service_event_schedule(pf);
11352 }
11353 
11354 /**
11355  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
11356  * @vsi: the VSI being configured
11357  **/
11358 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
11359 {
11360 	struct i40e_pf *pf = vsi->back;
11361 
11362 	switch (vsi->type) {
11363 	case I40E_VSI_MAIN:
11364 		vsi->alloc_queue_pairs = pf->num_lan_qps;
11365 		if (!vsi->num_tx_desc)
11366 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11367 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11368 		if (!vsi->num_rx_desc)
11369 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11370 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11371 		if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
11372 			vsi->num_q_vectors = pf->num_lan_msix;
11373 		else
11374 			vsi->num_q_vectors = 1;
11375 
11376 		break;
11377 
11378 	case I40E_VSI_FDIR:
11379 		vsi->alloc_queue_pairs = 1;
11380 		vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11381 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11382 		vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11383 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11384 		vsi->num_q_vectors = pf->num_fdsb_msix;
11385 		break;
11386 
11387 	case I40E_VSI_VMDQ2:
11388 		vsi->alloc_queue_pairs = pf->num_vmdq_qps;
11389 		if (!vsi->num_tx_desc)
11390 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11391 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11392 		if (!vsi->num_rx_desc)
11393 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11394 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11395 		vsi->num_q_vectors = pf->num_vmdq_msix;
11396 		break;
11397 
11398 	case I40E_VSI_SRIOV:
11399 		vsi->alloc_queue_pairs = pf->num_vf_qps;
11400 		if (!vsi->num_tx_desc)
11401 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11402 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11403 		if (!vsi->num_rx_desc)
11404 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11405 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11406 		break;
11407 
11408 	default:
11409 		WARN_ON(1);
11410 		return -ENODATA;
11411 	}
11412 
11413 	if (is_kdump_kernel()) {
11414 		vsi->num_tx_desc = I40E_MIN_NUM_DESCRIPTORS;
11415 		vsi->num_rx_desc = I40E_MIN_NUM_DESCRIPTORS;
11416 	}
11417 
11418 	return 0;
11419 }
11420 
11421 /**
11422  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
11423  * @vsi: VSI pointer
11424  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
11425  *
11426  * On error: returns error code (negative)
11427  * On success: returns 0
11428  **/
11429 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
11430 {
11431 	struct i40e_ring **next_rings;
11432 	int size;
11433 	int ret = 0;
11434 
11435 	/* allocate memory for both Tx, XDP Tx and Rx ring pointers */
11436 	size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
11437 	       (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
11438 	vsi->tx_rings = kzalloc(size, GFP_KERNEL);
11439 	if (!vsi->tx_rings)
11440 		return -ENOMEM;
11441 	next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
11442 	if (i40e_enabled_xdp_vsi(vsi)) {
11443 		vsi->xdp_rings = next_rings;
11444 		next_rings += vsi->alloc_queue_pairs;
11445 	}
11446 	vsi->rx_rings = next_rings;
11447 
11448 	if (alloc_qvectors) {
11449 		/* allocate memory for q_vector pointers */
11450 		size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
11451 		vsi->q_vectors = kzalloc(size, GFP_KERNEL);
11452 		if (!vsi->q_vectors) {
11453 			ret = -ENOMEM;
11454 			goto err_vectors;
11455 		}
11456 	}
11457 	return ret;
11458 
11459 err_vectors:
11460 	kfree(vsi->tx_rings);
11461 	return ret;
11462 }
11463 
11464 /**
11465  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
11466  * @pf: board private structure
11467  * @type: type of VSI
11468  *
11469  * On error: returns error code (negative)
11470  * On success: returns vsi index in PF (positive)
11471  **/
11472 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
11473 {
11474 	int ret = -ENODEV;
11475 	struct i40e_vsi *vsi;
11476 	int vsi_idx;
11477 	int i;
11478 
11479 	/* Need to protect the allocation of the VSIs at the PF level */
11480 	mutex_lock(&pf->switch_mutex);
11481 
11482 	/* VSI list may be fragmented if VSI creation/destruction has
11483 	 * been happening.  We can afford to do a quick scan to look
11484 	 * for any free VSIs in the list.
11485 	 *
11486 	 * find next empty vsi slot, looping back around if necessary
11487 	 */
11488 	i = pf->next_vsi;
11489 	while (i < pf->num_alloc_vsi && pf->vsi[i])
11490 		i++;
11491 	if (i >= pf->num_alloc_vsi) {
11492 		i = 0;
11493 		while (i < pf->next_vsi && pf->vsi[i])
11494 			i++;
11495 	}
11496 
11497 	if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
11498 		vsi_idx = i;             /* Found one! */
11499 	} else {
11500 		ret = -ENODEV;
11501 		goto unlock_pf;  /* out of VSI slots! */
11502 	}
11503 	pf->next_vsi = ++i;
11504 
11505 	vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
11506 	if (!vsi) {
11507 		ret = -ENOMEM;
11508 		goto unlock_pf;
11509 	}
11510 	vsi->type = type;
11511 	vsi->back = pf;
11512 	set_bit(__I40E_VSI_DOWN, vsi->state);
11513 	vsi->flags = 0;
11514 	vsi->idx = vsi_idx;
11515 	vsi->int_rate_limit = 0;
11516 	vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
11517 				pf->rss_table_size : 64;
11518 	vsi->netdev_registered = false;
11519 	vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
11520 	hash_init(vsi->mac_filter_hash);
11521 	vsi->irqs_ready = false;
11522 
11523 	if (type == I40E_VSI_MAIN) {
11524 		vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
11525 		if (!vsi->af_xdp_zc_qps)
11526 			goto err_rings;
11527 	}
11528 
11529 	ret = i40e_set_num_rings_in_vsi(vsi);
11530 	if (ret)
11531 		goto err_rings;
11532 
11533 	ret = i40e_vsi_alloc_arrays(vsi, true);
11534 	if (ret)
11535 		goto err_rings;
11536 
11537 	/* Setup default MSIX irq handler for VSI */
11538 	i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
11539 
11540 	/* Initialize VSI lock */
11541 	spin_lock_init(&vsi->mac_filter_hash_lock);
11542 	pf->vsi[vsi_idx] = vsi;
11543 	ret = vsi_idx;
11544 	goto unlock_pf;
11545 
11546 err_rings:
11547 	bitmap_free(vsi->af_xdp_zc_qps);
11548 	pf->next_vsi = i - 1;
11549 	kfree(vsi);
11550 unlock_pf:
11551 	mutex_unlock(&pf->switch_mutex);
11552 	return ret;
11553 }
11554 
11555 /**
11556  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
11557  * @vsi: VSI pointer
11558  * @free_qvectors: a bool to specify if q_vectors need to be freed.
11559  *
11560  * On error: returns error code (negative)
11561  * On success: returns 0
11562  **/
11563 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
11564 {
11565 	/* free the ring and vector containers */
11566 	if (free_qvectors) {
11567 		kfree(vsi->q_vectors);
11568 		vsi->q_vectors = NULL;
11569 	}
11570 	kfree(vsi->tx_rings);
11571 	vsi->tx_rings = NULL;
11572 	vsi->rx_rings = NULL;
11573 	vsi->xdp_rings = NULL;
11574 }
11575 
11576 /**
11577  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
11578  * and lookup table
11579  * @vsi: Pointer to VSI structure
11580  */
11581 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
11582 {
11583 	if (!vsi)
11584 		return;
11585 
11586 	kfree(vsi->rss_hkey_user);
11587 	vsi->rss_hkey_user = NULL;
11588 
11589 	kfree(vsi->rss_lut_user);
11590 	vsi->rss_lut_user = NULL;
11591 }
11592 
11593 /**
11594  * i40e_vsi_clear - Deallocate the VSI provided
11595  * @vsi: the VSI being un-configured
11596  **/
11597 static int i40e_vsi_clear(struct i40e_vsi *vsi)
11598 {
11599 	struct i40e_pf *pf;
11600 
11601 	if (!vsi)
11602 		return 0;
11603 
11604 	if (!vsi->back)
11605 		goto free_vsi;
11606 	pf = vsi->back;
11607 
11608 	mutex_lock(&pf->switch_mutex);
11609 	if (!pf->vsi[vsi->idx]) {
11610 		dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
11611 			vsi->idx, vsi->idx, vsi->type);
11612 		goto unlock_vsi;
11613 	}
11614 
11615 	if (pf->vsi[vsi->idx] != vsi) {
11616 		dev_err(&pf->pdev->dev,
11617 			"pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
11618 			pf->vsi[vsi->idx]->idx,
11619 			pf->vsi[vsi->idx]->type,
11620 			vsi->idx, vsi->type);
11621 		goto unlock_vsi;
11622 	}
11623 
11624 	/* updates the PF for this cleared vsi */
11625 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
11626 	i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
11627 
11628 	bitmap_free(vsi->af_xdp_zc_qps);
11629 	i40e_vsi_free_arrays(vsi, true);
11630 	i40e_clear_rss_config_user(vsi);
11631 
11632 	pf->vsi[vsi->idx] = NULL;
11633 	if (vsi->idx < pf->next_vsi)
11634 		pf->next_vsi = vsi->idx;
11635 
11636 unlock_vsi:
11637 	mutex_unlock(&pf->switch_mutex);
11638 free_vsi:
11639 	kfree(vsi);
11640 
11641 	return 0;
11642 }
11643 
11644 /**
11645  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
11646  * @vsi: the VSI being cleaned
11647  **/
11648 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
11649 {
11650 	int i;
11651 
11652 	if (vsi->tx_rings && vsi->tx_rings[0]) {
11653 		for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11654 			kfree_rcu(vsi->tx_rings[i], rcu);
11655 			WRITE_ONCE(vsi->tx_rings[i], NULL);
11656 			WRITE_ONCE(vsi->rx_rings[i], NULL);
11657 			if (vsi->xdp_rings)
11658 				WRITE_ONCE(vsi->xdp_rings[i], NULL);
11659 		}
11660 	}
11661 }
11662 
11663 /**
11664  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
11665  * @vsi: the VSI being configured
11666  **/
11667 static int i40e_alloc_rings(struct i40e_vsi *vsi)
11668 {
11669 	int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
11670 	struct i40e_pf *pf = vsi->back;
11671 	struct i40e_ring *ring;
11672 
11673 	/* Set basic values in the rings to be used later during open() */
11674 	for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11675 		/* allocate space for both Tx and Rx in one shot */
11676 		ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
11677 		if (!ring)
11678 			goto err_out;
11679 
11680 		ring->queue_index = i;
11681 		ring->reg_idx = vsi->base_queue + i;
11682 		ring->ring_active = false;
11683 		ring->vsi = vsi;
11684 		ring->netdev = vsi->netdev;
11685 		ring->dev = &pf->pdev->dev;
11686 		ring->count = vsi->num_tx_desc;
11687 		ring->size = 0;
11688 		ring->dcb_tc = 0;
11689 		if (test_bit(I40E_HW_CAP_WB_ON_ITR, vsi->back->hw.caps))
11690 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11691 		ring->itr_setting = pf->tx_itr_default;
11692 		WRITE_ONCE(vsi->tx_rings[i], ring++);
11693 
11694 		if (!i40e_enabled_xdp_vsi(vsi))
11695 			goto setup_rx;
11696 
11697 		ring->queue_index = vsi->alloc_queue_pairs + i;
11698 		ring->reg_idx = vsi->base_queue + ring->queue_index;
11699 		ring->ring_active = false;
11700 		ring->vsi = vsi;
11701 		ring->netdev = NULL;
11702 		ring->dev = &pf->pdev->dev;
11703 		ring->count = vsi->num_tx_desc;
11704 		ring->size = 0;
11705 		ring->dcb_tc = 0;
11706 		if (test_bit(I40E_HW_CAP_WB_ON_ITR, vsi->back->hw.caps))
11707 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11708 		set_ring_xdp(ring);
11709 		ring->itr_setting = pf->tx_itr_default;
11710 		WRITE_ONCE(vsi->xdp_rings[i], ring++);
11711 
11712 setup_rx:
11713 		ring->queue_index = i;
11714 		ring->reg_idx = vsi->base_queue + i;
11715 		ring->ring_active = false;
11716 		ring->vsi = vsi;
11717 		ring->netdev = vsi->netdev;
11718 		ring->dev = &pf->pdev->dev;
11719 		ring->count = vsi->num_rx_desc;
11720 		ring->size = 0;
11721 		ring->dcb_tc = 0;
11722 		ring->itr_setting = pf->rx_itr_default;
11723 		WRITE_ONCE(vsi->rx_rings[i], ring);
11724 	}
11725 
11726 	return 0;
11727 
11728 err_out:
11729 	i40e_vsi_clear_rings(vsi);
11730 	return -ENOMEM;
11731 }
11732 
11733 /**
11734  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
11735  * @pf: board private structure
11736  * @vectors: the number of MSI-X vectors to request
11737  *
11738  * Returns the number of vectors reserved, or error
11739  **/
11740 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
11741 {
11742 	vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
11743 					I40E_MIN_MSIX, vectors);
11744 	if (vectors < 0) {
11745 		dev_info(&pf->pdev->dev,
11746 			 "MSI-X vector reservation failed: %d\n", vectors);
11747 		vectors = 0;
11748 	}
11749 
11750 	return vectors;
11751 }
11752 
11753 /**
11754  * i40e_init_msix - Setup the MSIX capability
11755  * @pf: board private structure
11756  *
11757  * Work with the OS to set up the MSIX vectors needed.
11758  *
11759  * Returns the number of vectors reserved or negative on failure
11760  **/
11761 static int i40e_init_msix(struct i40e_pf *pf)
11762 {
11763 	struct i40e_hw *hw = &pf->hw;
11764 	int cpus, extra_vectors;
11765 	int vectors_left;
11766 	int v_budget, i;
11767 	int v_actual;
11768 	int iwarp_requested = 0;
11769 
11770 	if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
11771 		return -ENODEV;
11772 
11773 	/* The number of vectors we'll request will be comprised of:
11774 	 *   - Add 1 for "other" cause for Admin Queue events, etc.
11775 	 *   - The number of LAN queue pairs
11776 	 *	- Queues being used for RSS.
11777 	 *		We don't need as many as max_rss_size vectors.
11778 	 *		use rss_size instead in the calculation since that
11779 	 *		is governed by number of cpus in the system.
11780 	 *	- assumes symmetric Tx/Rx pairing
11781 	 *   - The number of VMDq pairs
11782 	 *   - The CPU count within the NUMA node if iWARP is enabled
11783 	 * Once we count this up, try the request.
11784 	 *
11785 	 * If we can't get what we want, we'll simplify to nearly nothing
11786 	 * and try again.  If that still fails, we punt.
11787 	 */
11788 	vectors_left = hw->func_caps.num_msix_vectors;
11789 	v_budget = 0;
11790 
11791 	/* reserve one vector for miscellaneous handler */
11792 	if (vectors_left) {
11793 		v_budget++;
11794 		vectors_left--;
11795 	}
11796 
11797 	/* reserve some vectors for the main PF traffic queues. Initially we
11798 	 * only reserve at most 50% of the available vectors, in the case that
11799 	 * the number of online CPUs is large. This ensures that we can enable
11800 	 * extra features as well. Once we've enabled the other features, we
11801 	 * will use any remaining vectors to reach as close as we can to the
11802 	 * number of online CPUs.
11803 	 */
11804 	cpus = num_online_cpus();
11805 	pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
11806 	vectors_left -= pf->num_lan_msix;
11807 
11808 	/* reserve one vector for sideband flow director */
11809 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
11810 		if (vectors_left) {
11811 			pf->num_fdsb_msix = 1;
11812 			v_budget++;
11813 			vectors_left--;
11814 		} else {
11815 			pf->num_fdsb_msix = 0;
11816 		}
11817 	}
11818 
11819 	/* can we reserve enough for iWARP? */
11820 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
11821 		iwarp_requested = pf->num_iwarp_msix;
11822 
11823 		if (!vectors_left)
11824 			pf->num_iwarp_msix = 0;
11825 		else if (vectors_left < pf->num_iwarp_msix)
11826 			pf->num_iwarp_msix = 1;
11827 		v_budget += pf->num_iwarp_msix;
11828 		vectors_left -= pf->num_iwarp_msix;
11829 	}
11830 
11831 	/* any vectors left over go for VMDq support */
11832 	if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags)) {
11833 		if (!vectors_left) {
11834 			pf->num_vmdq_msix = 0;
11835 			pf->num_vmdq_qps = 0;
11836 		} else {
11837 			int vmdq_vecs_wanted =
11838 				pf->num_vmdq_vsis * pf->num_vmdq_qps;
11839 			int vmdq_vecs =
11840 				min_t(int, vectors_left, vmdq_vecs_wanted);
11841 
11842 			/* if we're short on vectors for what's desired, we limit
11843 			 * the queues per vmdq.  If this is still more than are
11844 			 * available, the user will need to change the number of
11845 			 * queues/vectors used by the PF later with the ethtool
11846 			 * channels command
11847 			 */
11848 			if (vectors_left < vmdq_vecs_wanted) {
11849 				pf->num_vmdq_qps = 1;
11850 				vmdq_vecs_wanted = pf->num_vmdq_vsis;
11851 				vmdq_vecs = min_t(int,
11852 						  vectors_left,
11853 						  vmdq_vecs_wanted);
11854 			}
11855 			pf->num_vmdq_msix = pf->num_vmdq_qps;
11856 
11857 			v_budget += vmdq_vecs;
11858 			vectors_left -= vmdq_vecs;
11859 		}
11860 	}
11861 
11862 	/* On systems with a large number of SMP cores, we previously limited
11863 	 * the number of vectors for num_lan_msix to be at most 50% of the
11864 	 * available vectors, to allow for other features. Now, we add back
11865 	 * the remaining vectors. However, we ensure that the total
11866 	 * num_lan_msix will not exceed num_online_cpus(). To do this, we
11867 	 * calculate the number of vectors we can add without going over the
11868 	 * cap of CPUs. For systems with a small number of CPUs this will be
11869 	 * zero.
11870 	 */
11871 	extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11872 	pf->num_lan_msix += extra_vectors;
11873 	vectors_left -= extra_vectors;
11874 
11875 	WARN(vectors_left < 0,
11876 	     "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11877 
11878 	v_budget += pf->num_lan_msix;
11879 	pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
11880 				   GFP_KERNEL);
11881 	if (!pf->msix_entries)
11882 		return -ENOMEM;
11883 
11884 	for (i = 0; i < v_budget; i++)
11885 		pf->msix_entries[i].entry = i;
11886 	v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11887 
11888 	if (v_actual < I40E_MIN_MSIX) {
11889 		clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
11890 		kfree(pf->msix_entries);
11891 		pf->msix_entries = NULL;
11892 		pci_disable_msix(pf->pdev);
11893 		return -ENODEV;
11894 
11895 	} else if (v_actual == I40E_MIN_MSIX) {
11896 		/* Adjust for minimal MSIX use */
11897 		pf->num_vmdq_vsis = 0;
11898 		pf->num_vmdq_qps = 0;
11899 		pf->num_lan_qps = 1;
11900 		pf->num_lan_msix = 1;
11901 
11902 	} else if (v_actual != v_budget) {
11903 		/* If we have limited resources, we will start with no vectors
11904 		 * for the special features and then allocate vectors to some
11905 		 * of these features based on the policy and at the end disable
11906 		 * the features that did not get any vectors.
11907 		 */
11908 		int vec;
11909 
11910 		dev_info(&pf->pdev->dev,
11911 			 "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11912 			 v_actual, v_budget);
11913 		/* reserve the misc vector */
11914 		vec = v_actual - 1;
11915 
11916 		/* Scale vector usage down */
11917 		pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11918 		pf->num_vmdq_vsis = 1;
11919 		pf->num_vmdq_qps = 1;
11920 
11921 		/* partition out the remaining vectors */
11922 		switch (vec) {
11923 		case 2:
11924 			pf->num_lan_msix = 1;
11925 			break;
11926 		case 3:
11927 			if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
11928 				pf->num_lan_msix = 1;
11929 				pf->num_iwarp_msix = 1;
11930 			} else {
11931 				pf->num_lan_msix = 2;
11932 			}
11933 			break;
11934 		default:
11935 			if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
11936 				pf->num_iwarp_msix = min_t(int, (vec / 3),
11937 						 iwarp_requested);
11938 				pf->num_vmdq_vsis = min_t(int, (vec / 3),
11939 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11940 			} else {
11941 				pf->num_vmdq_vsis = min_t(int, (vec / 2),
11942 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11943 			}
11944 			if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
11945 				pf->num_fdsb_msix = 1;
11946 				vec--;
11947 			}
11948 			pf->num_lan_msix = min_t(int,
11949 			       (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
11950 							      pf->num_lan_msix);
11951 			pf->num_lan_qps = pf->num_lan_msix;
11952 			break;
11953 		}
11954 	}
11955 
11956 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) && pf->num_fdsb_msix == 0) {
11957 		dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
11958 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
11959 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
11960 	}
11961 	if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags) && pf->num_vmdq_msix == 0) {
11962 		dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
11963 		clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
11964 	}
11965 
11966 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags) &&
11967 	    pf->num_iwarp_msix == 0) {
11968 		dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
11969 		clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
11970 	}
11971 	i40e_debug(&pf->hw, I40E_DEBUG_INIT,
11972 		   "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
11973 		   pf->num_lan_msix,
11974 		   pf->num_vmdq_msix * pf->num_vmdq_vsis,
11975 		   pf->num_fdsb_msix,
11976 		   pf->num_iwarp_msix);
11977 
11978 	return v_actual;
11979 }
11980 
11981 /**
11982  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
11983  * @vsi: the VSI being configured
11984  * @v_idx: index of the vector in the vsi struct
11985  *
11986  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
11987  **/
11988 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx)
11989 {
11990 	struct i40e_q_vector *q_vector;
11991 
11992 	/* allocate q_vector */
11993 	q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
11994 	if (!q_vector)
11995 		return -ENOMEM;
11996 
11997 	q_vector->vsi = vsi;
11998 	q_vector->v_idx = v_idx;
11999 	cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
12000 
12001 	if (vsi->netdev)
12002 		netif_napi_add(vsi->netdev, &q_vector->napi, i40e_napi_poll);
12003 
12004 	/* tie q_vector and vsi together */
12005 	vsi->q_vectors[v_idx] = q_vector;
12006 
12007 	return 0;
12008 }
12009 
12010 /**
12011  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
12012  * @vsi: the VSI being configured
12013  *
12014  * We allocate one q_vector per queue interrupt.  If allocation fails we
12015  * return -ENOMEM.
12016  **/
12017 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
12018 {
12019 	struct i40e_pf *pf = vsi->back;
12020 	int err, v_idx, num_q_vectors;
12021 
12022 	/* if not MSIX, give the one vector only to the LAN VSI */
12023 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
12024 		num_q_vectors = vsi->num_q_vectors;
12025 	else if (vsi->type == I40E_VSI_MAIN)
12026 		num_q_vectors = 1;
12027 	else
12028 		return -EINVAL;
12029 
12030 	for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
12031 		err = i40e_vsi_alloc_q_vector(vsi, v_idx);
12032 		if (err)
12033 			goto err_out;
12034 	}
12035 
12036 	return 0;
12037 
12038 err_out:
12039 	while (v_idx--)
12040 		i40e_free_q_vector(vsi, v_idx);
12041 
12042 	return err;
12043 }
12044 
12045 /**
12046  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
12047  * @pf: board private structure to initialize
12048  **/
12049 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
12050 {
12051 	int vectors = 0;
12052 	ssize_t size;
12053 
12054 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
12055 		vectors = i40e_init_msix(pf);
12056 		if (vectors < 0) {
12057 			clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12058 			clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
12059 			clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
12060 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
12061 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
12062 			clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
12063 			clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12064 			clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
12065 			clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
12066 			set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12067 
12068 			/* rework the queue expectations without MSIX */
12069 			i40e_determine_queue_usage(pf);
12070 		}
12071 	}
12072 
12073 	if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
12074 	    test_bit(I40E_FLAG_MSI_ENA, pf->flags)) {
12075 		dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
12076 		vectors = pci_enable_msi(pf->pdev);
12077 		if (vectors < 0) {
12078 			dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
12079 				 vectors);
12080 			clear_bit(I40E_FLAG_MSI_ENA, pf->flags);
12081 		}
12082 		vectors = 1;  /* one MSI or Legacy vector */
12083 	}
12084 
12085 	if (!test_bit(I40E_FLAG_MSI_ENA, pf->flags) &&
12086 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
12087 		dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
12088 
12089 	/* set up vector assignment tracking */
12090 	size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
12091 	pf->irq_pile = kzalloc(size, GFP_KERNEL);
12092 	if (!pf->irq_pile)
12093 		return -ENOMEM;
12094 
12095 	pf->irq_pile->num_entries = vectors;
12096 
12097 	/* track first vector for misc interrupts, ignore return */
12098 	(void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
12099 
12100 	return 0;
12101 }
12102 
12103 /**
12104  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
12105  * @pf: private board data structure
12106  *
12107  * Restore the interrupt scheme that was cleared when we suspended the
12108  * device. This should be called during resume to re-allocate the q_vectors
12109  * and reacquire IRQs.
12110  */
12111 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
12112 {
12113 	struct i40e_vsi *vsi;
12114 	int err, i;
12115 
12116 	/* We cleared the MSI and MSI-X flags when disabling the old interrupt
12117 	 * scheme. We need to re-enabled them here in order to attempt to
12118 	 * re-acquire the MSI or MSI-X vectors
12119 	 */
12120 	set_bit(I40E_FLAG_MSI_ENA, pf->flags);
12121 	set_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12122 
12123 	err = i40e_init_interrupt_scheme(pf);
12124 	if (err)
12125 		return err;
12126 
12127 	/* Now that we've re-acquired IRQs, we need to remap the vectors and
12128 	 * rings together again.
12129 	 */
12130 	i40e_pf_for_each_vsi(pf, i, vsi) {
12131 		err = i40e_vsi_alloc_q_vectors(vsi);
12132 		if (err)
12133 			goto err_unwind;
12134 
12135 		i40e_vsi_map_rings_to_vectors(vsi);
12136 	}
12137 
12138 	err = i40e_setup_misc_vector(pf);
12139 	if (err)
12140 		goto err_unwind;
12141 
12142 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags))
12143 		i40e_client_update_msix_info(pf);
12144 
12145 	return 0;
12146 
12147 err_unwind:
12148 	while (i--) {
12149 		if (pf->vsi[i])
12150 			i40e_vsi_free_q_vectors(pf->vsi[i]);
12151 	}
12152 
12153 	return err;
12154 }
12155 
12156 /**
12157  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
12158  * non queue events in recovery mode
12159  * @pf: board private structure
12160  *
12161  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
12162  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
12163  * This is handled differently than in recovery mode since no Tx/Rx resources
12164  * are being allocated.
12165  **/
12166 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
12167 {
12168 	int err;
12169 
12170 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
12171 		err = i40e_setup_misc_vector(pf);
12172 
12173 		if (err) {
12174 			dev_info(&pf->pdev->dev,
12175 				 "MSI-X misc vector request failed, error %d\n",
12176 				 err);
12177 			return err;
12178 		}
12179 	} else {
12180 		u32 flags = test_bit(I40E_FLAG_MSI_ENA, pf->flags) ? 0 : IRQF_SHARED;
12181 
12182 		err = request_irq(pf->pdev->irq, i40e_intr, flags,
12183 				  pf->int_name, pf);
12184 
12185 		if (err) {
12186 			dev_info(&pf->pdev->dev,
12187 				 "MSI/legacy misc vector request failed, error %d\n",
12188 				 err);
12189 			return err;
12190 		}
12191 		i40e_enable_misc_int_causes(pf);
12192 		i40e_irq_dynamic_enable_icr0(pf);
12193 	}
12194 
12195 	return 0;
12196 }
12197 
12198 /**
12199  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
12200  * @pf: board private structure
12201  *
12202  * This sets up the handler for MSIX 0, which is used to manage the
12203  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
12204  * when in MSI or Legacy interrupt mode.
12205  **/
12206 static int i40e_setup_misc_vector(struct i40e_pf *pf)
12207 {
12208 	struct i40e_hw *hw = &pf->hw;
12209 	int err = 0;
12210 
12211 	/* Only request the IRQ once, the first time through. */
12212 	if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
12213 		err = request_irq(pf->msix_entries[0].vector,
12214 				  i40e_intr, 0, pf->int_name, pf);
12215 		if (err) {
12216 			clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
12217 			dev_info(&pf->pdev->dev,
12218 				 "request_irq for %s failed: %d\n",
12219 				 pf->int_name, err);
12220 			return -EFAULT;
12221 		}
12222 	}
12223 
12224 	i40e_enable_misc_int_causes(pf);
12225 
12226 	/* associate no queues to the misc vector */
12227 	wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
12228 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K >> 1);
12229 
12230 	i40e_flush(hw);
12231 
12232 	i40e_irq_dynamic_enable_icr0(pf);
12233 
12234 	return err;
12235 }
12236 
12237 /**
12238  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
12239  * @vsi: Pointer to vsi structure
12240  * @seed: Buffter to store the hash keys
12241  * @lut: Buffer to store the lookup table entries
12242  * @lut_size: Size of buffer to store the lookup table entries
12243  *
12244  * Return 0 on success, negative on failure
12245  */
12246 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
12247 			   u8 *lut, u16 lut_size)
12248 {
12249 	struct i40e_pf *pf = vsi->back;
12250 	struct i40e_hw *hw = &pf->hw;
12251 	int ret = 0;
12252 
12253 	if (seed) {
12254 		ret = i40e_aq_get_rss_key(hw, vsi->id,
12255 			(struct i40e_aqc_get_set_rss_key_data *)seed);
12256 		if (ret) {
12257 			dev_info(&pf->pdev->dev,
12258 				 "Cannot get RSS key, err %pe aq_err %s\n",
12259 				 ERR_PTR(ret),
12260 				 i40e_aq_str(&pf->hw,
12261 					     pf->hw.aq.asq_last_status));
12262 			return ret;
12263 		}
12264 	}
12265 
12266 	if (lut) {
12267 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
12268 
12269 		ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
12270 		if (ret) {
12271 			dev_info(&pf->pdev->dev,
12272 				 "Cannot get RSS lut, err %pe aq_err %s\n",
12273 				 ERR_PTR(ret),
12274 				 i40e_aq_str(&pf->hw,
12275 					     pf->hw.aq.asq_last_status));
12276 			return ret;
12277 		}
12278 	}
12279 
12280 	return ret;
12281 }
12282 
12283 /**
12284  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
12285  * @vsi: Pointer to vsi structure
12286  * @seed: RSS hash seed
12287  * @lut: Lookup table
12288  * @lut_size: Lookup table size
12289  *
12290  * Returns 0 on success, negative on failure
12291  **/
12292 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
12293 			       const u8 *lut, u16 lut_size)
12294 {
12295 	struct i40e_pf *pf = vsi->back;
12296 	struct i40e_hw *hw = &pf->hw;
12297 	u16 vf_id = vsi->vf_id;
12298 	u8 i;
12299 
12300 	/* Fill out hash function seed */
12301 	if (seed) {
12302 		u32 *seed_dw = (u32 *)seed;
12303 
12304 		if (vsi->type == I40E_VSI_MAIN) {
12305 			for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12306 				wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
12307 		} else if (vsi->type == I40E_VSI_SRIOV) {
12308 			for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
12309 				wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
12310 		} else {
12311 			dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
12312 		}
12313 	}
12314 
12315 	if (lut) {
12316 		u32 *lut_dw = (u32 *)lut;
12317 
12318 		if (vsi->type == I40E_VSI_MAIN) {
12319 			if (lut_size != I40E_HLUT_ARRAY_SIZE)
12320 				return -EINVAL;
12321 			for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12322 				wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
12323 		} else if (vsi->type == I40E_VSI_SRIOV) {
12324 			if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
12325 				return -EINVAL;
12326 			for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12327 				wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
12328 		} else {
12329 			dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12330 		}
12331 	}
12332 	i40e_flush(hw);
12333 
12334 	return 0;
12335 }
12336 
12337 /**
12338  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
12339  * @vsi: Pointer to VSI structure
12340  * @seed: Buffer to store the keys
12341  * @lut: Buffer to store the lookup table entries
12342  * @lut_size: Size of buffer to store the lookup table entries
12343  *
12344  * Returns 0 on success, negative on failure
12345  */
12346 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
12347 			    u8 *lut, u16 lut_size)
12348 {
12349 	struct i40e_pf *pf = vsi->back;
12350 	struct i40e_hw *hw = &pf->hw;
12351 	u16 i;
12352 
12353 	if (seed) {
12354 		u32 *seed_dw = (u32 *)seed;
12355 
12356 		for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12357 			seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
12358 	}
12359 	if (lut) {
12360 		u32 *lut_dw = (u32 *)lut;
12361 
12362 		if (lut_size != I40E_HLUT_ARRAY_SIZE)
12363 			return -EINVAL;
12364 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12365 			lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
12366 	}
12367 
12368 	return 0;
12369 }
12370 
12371 /**
12372  * i40e_config_rss - Configure RSS keys and lut
12373  * @vsi: Pointer to VSI structure
12374  * @seed: RSS hash seed
12375  * @lut: Lookup table
12376  * @lut_size: Lookup table size
12377  *
12378  * Returns 0 on success, negative on failure
12379  */
12380 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12381 {
12382 	struct i40e_pf *pf = vsi->back;
12383 
12384 	if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
12385 		return i40e_config_rss_aq(vsi, seed, lut, lut_size);
12386 	else
12387 		return i40e_config_rss_reg(vsi, seed, lut, lut_size);
12388 }
12389 
12390 /**
12391  * i40e_get_rss - Get RSS keys and lut
12392  * @vsi: Pointer to VSI structure
12393  * @seed: Buffer to store the keys
12394  * @lut: Buffer to store the lookup table entries
12395  * @lut_size: Size of buffer to store the lookup table entries
12396  *
12397  * Returns 0 on success, negative on failure
12398  */
12399 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12400 {
12401 	struct i40e_pf *pf = vsi->back;
12402 
12403 	if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
12404 		return i40e_get_rss_aq(vsi, seed, lut, lut_size);
12405 	else
12406 		return i40e_get_rss_reg(vsi, seed, lut, lut_size);
12407 }
12408 
12409 /**
12410  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
12411  * @pf: Pointer to board private structure
12412  * @lut: Lookup table
12413  * @rss_table_size: Lookup table size
12414  * @rss_size: Range of queue number for hashing
12415  */
12416 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
12417 		       u16 rss_table_size, u16 rss_size)
12418 {
12419 	u16 i;
12420 
12421 	for (i = 0; i < rss_table_size; i++)
12422 		lut[i] = i % rss_size;
12423 }
12424 
12425 /**
12426  * i40e_pf_config_rss - Prepare for RSS if used
12427  * @pf: board private structure
12428  **/
12429 static int i40e_pf_config_rss(struct i40e_pf *pf)
12430 {
12431 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
12432 	u8 seed[I40E_HKEY_ARRAY_SIZE];
12433 	u8 *lut;
12434 	struct i40e_hw *hw = &pf->hw;
12435 	u32 reg_val;
12436 	u64 hena;
12437 	int ret;
12438 
12439 	/* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
12440 	hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
12441 		((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
12442 	hena |= i40e_pf_get_default_rss_hena(pf);
12443 
12444 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
12445 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
12446 
12447 	/* Determine the RSS table size based on the hardware capabilities */
12448 	reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
12449 	reg_val = (pf->rss_table_size == 512) ?
12450 			(reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
12451 			(reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
12452 	i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
12453 
12454 	/* Determine the RSS size of the VSI */
12455 	if (!vsi->rss_size) {
12456 		u16 qcount;
12457 		/* If the firmware does something weird during VSI init, we
12458 		 * could end up with zero TCs. Check for that to avoid
12459 		 * divide-by-zero. It probably won't pass traffic, but it also
12460 		 * won't panic.
12461 		 */
12462 		qcount = vsi->num_queue_pairs /
12463 			 (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
12464 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12465 	}
12466 	if (!vsi->rss_size)
12467 		return -EINVAL;
12468 
12469 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
12470 	if (!lut)
12471 		return -ENOMEM;
12472 
12473 	/* Use user configured lut if there is one, otherwise use default */
12474 	if (vsi->rss_lut_user)
12475 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
12476 	else
12477 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
12478 
12479 	/* Use user configured hash key if there is one, otherwise
12480 	 * use default.
12481 	 */
12482 	if (vsi->rss_hkey_user)
12483 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
12484 	else
12485 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
12486 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
12487 	kfree(lut);
12488 
12489 	return ret;
12490 }
12491 
12492 /**
12493  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
12494  * @pf: board private structure
12495  * @queue_count: the requested queue count for rss.
12496  *
12497  * returns 0 if rss is not enabled, if enabled returns the final rss queue
12498  * count which may be different from the requested queue count.
12499  * Note: expects to be called while under rtnl_lock()
12500  **/
12501 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
12502 {
12503 	struct i40e_vsi *vsi = i40e_pf_get_main_vsi(pf);
12504 	int new_rss_size;
12505 
12506 	if (!test_bit(I40E_FLAG_RSS_ENA, pf->flags))
12507 		return 0;
12508 
12509 	queue_count = min_t(int, queue_count, num_online_cpus());
12510 	new_rss_size = min_t(int, queue_count, pf->rss_size_max);
12511 
12512 	if (queue_count != vsi->num_queue_pairs) {
12513 		u16 qcount;
12514 
12515 		vsi->req_queue_pairs = queue_count;
12516 		i40e_prep_for_reset(pf);
12517 		if (test_bit(__I40E_IN_REMOVE, pf->state))
12518 			return pf->alloc_rss_size;
12519 
12520 		pf->alloc_rss_size = new_rss_size;
12521 
12522 		i40e_reset_and_rebuild(pf, true, true);
12523 
12524 		/* Discard the user configured hash keys and lut, if less
12525 		 * queues are enabled.
12526 		 */
12527 		if (queue_count < vsi->rss_size) {
12528 			i40e_clear_rss_config_user(vsi);
12529 			dev_dbg(&pf->pdev->dev,
12530 				"discard user configured hash keys and lut\n");
12531 		}
12532 
12533 		/* Reset vsi->rss_size, as number of enabled queues changed */
12534 		qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
12535 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12536 
12537 		i40e_pf_config_rss(pf);
12538 	}
12539 	dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
12540 		 vsi->req_queue_pairs, pf->rss_size_max);
12541 	return pf->alloc_rss_size;
12542 }
12543 
12544 /**
12545  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
12546  * @pf: board private structure
12547  **/
12548 int i40e_get_partition_bw_setting(struct i40e_pf *pf)
12549 {
12550 	bool min_valid, max_valid;
12551 	u32 max_bw, min_bw;
12552 	int status;
12553 
12554 	status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
12555 					   &min_valid, &max_valid);
12556 
12557 	if (!status) {
12558 		if (min_valid)
12559 			pf->min_bw = min_bw;
12560 		if (max_valid)
12561 			pf->max_bw = max_bw;
12562 	}
12563 
12564 	return status;
12565 }
12566 
12567 /**
12568  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
12569  * @pf: board private structure
12570  **/
12571 int i40e_set_partition_bw_setting(struct i40e_pf *pf)
12572 {
12573 	struct i40e_aqc_configure_partition_bw_data bw_data;
12574 	int status;
12575 
12576 	memset(&bw_data, 0, sizeof(bw_data));
12577 
12578 	/* Set the valid bit for this PF */
12579 	bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
12580 	bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
12581 	bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
12582 
12583 	/* Set the new bandwidths */
12584 	status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
12585 
12586 	return status;
12587 }
12588 
12589 /**
12590  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
12591  * @pf: board private structure
12592  **/
12593 int i40e_commit_partition_bw_setting(struct i40e_pf *pf)
12594 {
12595 	/* Commit temporary BW setting to permanent NVM image */
12596 	enum i40e_admin_queue_err last_aq_status;
12597 	u16 nvm_word;
12598 	int ret;
12599 
12600 	if (pf->hw.partition_id != 1) {
12601 		dev_info(&pf->pdev->dev,
12602 			 "Commit BW only works on partition 1! This is partition %d",
12603 			 pf->hw.partition_id);
12604 		ret = -EOPNOTSUPP;
12605 		goto bw_commit_out;
12606 	}
12607 
12608 	/* Acquire NVM for read access */
12609 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
12610 	last_aq_status = pf->hw.aq.asq_last_status;
12611 	if (ret) {
12612 		dev_info(&pf->pdev->dev,
12613 			 "Cannot acquire NVM for read access, err %pe aq_err %s\n",
12614 			 ERR_PTR(ret),
12615 			 i40e_aq_str(&pf->hw, last_aq_status));
12616 		goto bw_commit_out;
12617 	}
12618 
12619 	/* Read word 0x10 of NVM - SW compatibility word 1 */
12620 	ret = i40e_aq_read_nvm(&pf->hw,
12621 			       I40E_SR_NVM_CONTROL_WORD,
12622 			       0x10, sizeof(nvm_word), &nvm_word,
12623 			       false, NULL);
12624 	/* Save off last admin queue command status before releasing
12625 	 * the NVM
12626 	 */
12627 	last_aq_status = pf->hw.aq.asq_last_status;
12628 	i40e_release_nvm(&pf->hw);
12629 	if (ret) {
12630 		dev_info(&pf->pdev->dev, "NVM read error, err %pe aq_err %s\n",
12631 			 ERR_PTR(ret),
12632 			 i40e_aq_str(&pf->hw, last_aq_status));
12633 		goto bw_commit_out;
12634 	}
12635 
12636 	/* Wait a bit for NVM release to complete */
12637 	msleep(50);
12638 
12639 	/* Acquire NVM for write access */
12640 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
12641 	last_aq_status = pf->hw.aq.asq_last_status;
12642 	if (ret) {
12643 		dev_info(&pf->pdev->dev,
12644 			 "Cannot acquire NVM for write access, err %pe aq_err %s\n",
12645 			 ERR_PTR(ret),
12646 			 i40e_aq_str(&pf->hw, last_aq_status));
12647 		goto bw_commit_out;
12648 	}
12649 	/* Write it back out unchanged to initiate update NVM,
12650 	 * which will force a write of the shadow (alt) RAM to
12651 	 * the NVM - thus storing the bandwidth values permanently.
12652 	 */
12653 	ret = i40e_aq_update_nvm(&pf->hw,
12654 				 I40E_SR_NVM_CONTROL_WORD,
12655 				 0x10, sizeof(nvm_word),
12656 				 &nvm_word, true, 0, NULL);
12657 	/* Save off last admin queue command status before releasing
12658 	 * the NVM
12659 	 */
12660 	last_aq_status = pf->hw.aq.asq_last_status;
12661 	i40e_release_nvm(&pf->hw);
12662 	if (ret)
12663 		dev_info(&pf->pdev->dev,
12664 			 "BW settings NOT SAVED, err %pe aq_err %s\n",
12665 			 ERR_PTR(ret),
12666 			 i40e_aq_str(&pf->hw, last_aq_status));
12667 bw_commit_out:
12668 
12669 	return ret;
12670 }
12671 
12672 /**
12673  * i40e_is_total_port_shutdown_enabled - read NVM and return value
12674  * if total port shutdown feature is enabled for this PF
12675  * @pf: board private structure
12676  **/
12677 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf)
12678 {
12679 #define I40E_TOTAL_PORT_SHUTDOWN_ENABLED	BIT(4)
12680 #define I40E_FEATURES_ENABLE_PTR		0x2A
12681 #define I40E_CURRENT_SETTING_PTR		0x2B
12682 #define I40E_LINK_BEHAVIOR_WORD_OFFSET		0x2D
12683 #define I40E_LINK_BEHAVIOR_WORD_LENGTH		0x1
12684 #define I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED	BIT(0)
12685 #define I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH	4
12686 	u16 sr_emp_sr_settings_ptr = 0;
12687 	u16 features_enable = 0;
12688 	u16 link_behavior = 0;
12689 	int read_status = 0;
12690 	bool ret = false;
12691 
12692 	read_status = i40e_read_nvm_word(&pf->hw,
12693 					 I40E_SR_EMP_SR_SETTINGS_PTR,
12694 					 &sr_emp_sr_settings_ptr);
12695 	if (read_status)
12696 		goto err_nvm;
12697 	read_status = i40e_read_nvm_word(&pf->hw,
12698 					 sr_emp_sr_settings_ptr +
12699 					 I40E_FEATURES_ENABLE_PTR,
12700 					 &features_enable);
12701 	if (read_status)
12702 		goto err_nvm;
12703 	if (I40E_TOTAL_PORT_SHUTDOWN_ENABLED & features_enable) {
12704 		read_status = i40e_read_nvm_module_data(&pf->hw,
12705 							I40E_SR_EMP_SR_SETTINGS_PTR,
12706 							I40E_CURRENT_SETTING_PTR,
12707 							I40E_LINK_BEHAVIOR_WORD_OFFSET,
12708 							I40E_LINK_BEHAVIOR_WORD_LENGTH,
12709 							&link_behavior);
12710 		if (read_status)
12711 			goto err_nvm;
12712 		link_behavior >>= (pf->hw.port * I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH);
12713 		ret = I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED & link_behavior;
12714 	}
12715 	return ret;
12716 
12717 err_nvm:
12718 	dev_warn(&pf->pdev->dev,
12719 		 "total-port-shutdown feature is off due to read nvm error: %pe\n",
12720 		 ERR_PTR(read_status));
12721 	return ret;
12722 }
12723 
12724 /**
12725  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
12726  * @pf: board private structure to initialize
12727  *
12728  * i40e_sw_init initializes the Adapter private data structure.
12729  * Fields are initialized based on PCI device information and
12730  * OS network device settings (MTU size).
12731  **/
12732 static int i40e_sw_init(struct i40e_pf *pf)
12733 {
12734 	int err = 0;
12735 	int size;
12736 	u16 pow;
12737 
12738 	/* Set default capability flags */
12739 	bitmap_zero(pf->flags, I40E_PF_FLAGS_NBITS);
12740 	set_bit(I40E_FLAG_MSI_ENA, pf->flags);
12741 	set_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12742 
12743 	/* Set default ITR */
12744 	pf->rx_itr_default = I40E_ITR_RX_DEF;
12745 	pf->tx_itr_default = I40E_ITR_TX_DEF;
12746 
12747 	/* Depending on PF configurations, it is possible that the RSS
12748 	 * maximum might end up larger than the available queues
12749 	 */
12750 	pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
12751 	pf->alloc_rss_size = 1;
12752 	pf->rss_table_size = pf->hw.func_caps.rss_table_size;
12753 	pf->rss_size_max = min_t(int, pf->rss_size_max,
12754 				 pf->hw.func_caps.num_tx_qp);
12755 
12756 	/* find the next higher power-of-2 of num cpus */
12757 	pow = roundup_pow_of_two(num_online_cpus());
12758 	pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
12759 
12760 	if (pf->hw.func_caps.rss) {
12761 		set_bit(I40E_FLAG_RSS_ENA, pf->flags);
12762 		pf->alloc_rss_size = min_t(int, pf->rss_size_max,
12763 					   num_online_cpus());
12764 	}
12765 
12766 	/* MFP mode enabled */
12767 	if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
12768 		set_bit(I40E_FLAG_MFP_ENA, pf->flags);
12769 		dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
12770 		if (i40e_get_partition_bw_setting(pf)) {
12771 			dev_warn(&pf->pdev->dev,
12772 				 "Could not get partition bw settings\n");
12773 		} else {
12774 			dev_info(&pf->pdev->dev,
12775 				 "Partition BW Min = %8.8x, Max = %8.8x\n",
12776 				 pf->min_bw, pf->max_bw);
12777 
12778 			/* nudge the Tx scheduler */
12779 			i40e_set_partition_bw_setting(pf);
12780 		}
12781 	}
12782 
12783 	if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
12784 	    (pf->hw.func_caps.fd_filters_best_effort > 0)) {
12785 		set_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
12786 		if (test_bit(I40E_FLAG_MFP_ENA, pf->flags) &&
12787 		    pf->hw.num_partitions > 1)
12788 			dev_info(&pf->pdev->dev,
12789 				 "Flow Director Sideband mode Disabled in MFP mode\n");
12790 		else
12791 			set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12792 		pf->fdir_pf_filter_count =
12793 				 pf->hw.func_caps.fd_filters_guaranteed;
12794 		pf->hw.fdir_shared_filter_count =
12795 				 pf->hw.func_caps.fd_filters_best_effort;
12796 	}
12797 
12798 	/* Enable HW ATR eviction if possible */
12799 	if (test_bit(I40E_HW_CAP_ATR_EVICT, pf->hw.caps))
12800 		set_bit(I40E_FLAG_HW_ATR_EVICT_ENA, pf->flags);
12801 
12802 	if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
12803 		pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
12804 		set_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
12805 		pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
12806 	}
12807 
12808 	if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
12809 		set_bit(I40E_FLAG_IWARP_ENA, pf->flags);
12810 		/* IWARP needs one extra vector for CQP just like MISC.*/
12811 		pf->num_iwarp_msix = (int)num_online_cpus() + 1;
12812 	}
12813 	/* Stopping FW LLDP engine is supported on XL710 and X722
12814 	 * starting from FW versions determined in i40e_init_adminq.
12815 	 * Stopping the FW LLDP engine is not supported on XL710
12816 	 * if NPAR is functioning so unset this hw flag in this case.
12817 	 */
12818 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
12819 	    pf->hw.func_caps.npar_enable)
12820 		clear_bit(I40E_HW_CAP_FW_LLDP_STOPPABLE, pf->hw.caps);
12821 
12822 #ifdef CONFIG_PCI_IOV
12823 	if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
12824 		pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
12825 		set_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
12826 		pf->num_req_vfs = min_t(int,
12827 					pf->hw.func_caps.num_vfs,
12828 					I40E_MAX_VF_COUNT);
12829 	}
12830 #endif /* CONFIG_PCI_IOV */
12831 	pf->lan_veb = I40E_NO_VEB;
12832 	pf->lan_vsi = I40E_NO_VSI;
12833 
12834 	/* By default FW has this off for performance reasons */
12835 	clear_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags);
12836 
12837 	/* set up queue assignment tracking */
12838 	size = sizeof(struct i40e_lump_tracking)
12839 		+ (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
12840 	pf->qp_pile = kzalloc(size, GFP_KERNEL);
12841 	if (!pf->qp_pile) {
12842 		err = -ENOMEM;
12843 		goto sw_init_done;
12844 	}
12845 	pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
12846 
12847 	pf->tx_timeout_recovery_level = 1;
12848 
12849 	if (pf->hw.mac.type != I40E_MAC_X722 &&
12850 	    i40e_is_total_port_shutdown_enabled(pf)) {
12851 		/* Link down on close must be on when total port shutdown
12852 		 * is enabled for a given port
12853 		 */
12854 		set_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags);
12855 		set_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags);
12856 		dev_info(&pf->pdev->dev,
12857 			 "total-port-shutdown was enabled, link-down-on-close is forced on\n");
12858 	}
12859 	mutex_init(&pf->switch_mutex);
12860 
12861 sw_init_done:
12862 	return err;
12863 }
12864 
12865 /**
12866  * i40e_set_ntuple - set the ntuple feature flag and take action
12867  * @pf: board private structure to initialize
12868  * @features: the feature set that the stack is suggesting
12869  *
12870  * returns a bool to indicate if reset needs to happen
12871  **/
12872 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12873 {
12874 	bool need_reset = false;
12875 
12876 	/* Check if Flow Director n-tuple support was enabled or disabled.  If
12877 	 * the state changed, we need to reset.
12878 	 */
12879 	if (features & NETIF_F_NTUPLE) {
12880 		/* Enable filters and mark for reset */
12881 		if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
12882 			need_reset = true;
12883 		/* enable FD_SB only if there is MSI-X vector and no cloud
12884 		 * filters exist
12885 		 */
12886 		if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12887 			set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12888 			clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12889 		}
12890 	} else {
12891 		/* turn off filters, mark for reset and clear SW filter list */
12892 		if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
12893 			need_reset = true;
12894 			i40e_fdir_filter_exit(pf);
12895 		}
12896 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12897 		clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12898 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12899 
12900 		/* reset fd counters */
12901 		pf->fd_add_err = 0;
12902 		pf->fd_atr_cnt = 0;
12903 		/* if ATR was auto disabled it can be re-enabled. */
12904 		if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12905 			if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
12906 			    (I40E_DEBUG_FD & pf->hw.debug_mask))
12907 				dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12908 	}
12909 	return need_reset;
12910 }
12911 
12912 /**
12913  * i40e_clear_rss_lut - clear the rx hash lookup table
12914  * @vsi: the VSI being configured
12915  **/
12916 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12917 {
12918 	struct i40e_pf *pf = vsi->back;
12919 	struct i40e_hw *hw = &pf->hw;
12920 	u16 vf_id = vsi->vf_id;
12921 	u8 i;
12922 
12923 	if (vsi->type == I40E_VSI_MAIN) {
12924 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12925 			wr32(hw, I40E_PFQF_HLUT(i), 0);
12926 	} else if (vsi->type == I40E_VSI_SRIOV) {
12927 		for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12928 			i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12929 	} else {
12930 		dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12931 	}
12932 }
12933 
12934 /**
12935  * i40e_set_loopback - turn on/off loopback mode on underlying PF
12936  * @vsi: ptr to VSI
12937  * @ena: flag to indicate the on/off setting
12938  */
12939 static int i40e_set_loopback(struct i40e_vsi *vsi, bool ena)
12940 {
12941 	bool if_running = netif_running(vsi->netdev) &&
12942 			  !test_and_set_bit(__I40E_VSI_DOWN, vsi->state);
12943 	int ret;
12944 
12945 	if (if_running)
12946 		i40e_down(vsi);
12947 
12948 	ret = i40e_aq_set_mac_loopback(&vsi->back->hw, ena, NULL);
12949 	if (ret)
12950 		netdev_err(vsi->netdev, "Failed to toggle loopback state\n");
12951 	if (if_running)
12952 		i40e_up(vsi);
12953 
12954 	return ret;
12955 }
12956 
12957 /**
12958  * i40e_set_features - set the netdev feature flags
12959  * @netdev: ptr to the netdev being adjusted
12960  * @features: the feature set that the stack is suggesting
12961  * Note: expects to be called while under rtnl_lock()
12962  **/
12963 static int i40e_set_features(struct net_device *netdev,
12964 			     netdev_features_t features)
12965 {
12966 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12967 	struct i40e_vsi *vsi = np->vsi;
12968 	struct i40e_pf *pf = vsi->back;
12969 	bool need_reset;
12970 
12971 	if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
12972 		i40e_pf_config_rss(pf);
12973 	else if (!(features & NETIF_F_RXHASH) &&
12974 		 netdev->features & NETIF_F_RXHASH)
12975 		i40e_clear_rss_lut(vsi);
12976 
12977 	if (features & NETIF_F_HW_VLAN_CTAG_RX)
12978 		i40e_vlan_stripping_enable(vsi);
12979 	else
12980 		i40e_vlan_stripping_disable(vsi);
12981 
12982 	if (!(features & NETIF_F_HW_TC) &&
12983 	    (netdev->features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
12984 		dev_err(&pf->pdev->dev,
12985 			"Offloaded tc filters active, can't turn hw_tc_offload off");
12986 		return -EINVAL;
12987 	}
12988 
12989 	if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
12990 		i40e_del_all_macvlans(vsi);
12991 
12992 	need_reset = i40e_set_ntuple(pf, features);
12993 
12994 	if (need_reset)
12995 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12996 
12997 	if ((features ^ netdev->features) & NETIF_F_LOOPBACK)
12998 		return i40e_set_loopback(vsi, !!(features & NETIF_F_LOOPBACK));
12999 
13000 	return 0;
13001 }
13002 
13003 static int i40e_udp_tunnel_set_port(struct net_device *netdev,
13004 				    unsigned int table, unsigned int idx,
13005 				    struct udp_tunnel_info *ti)
13006 {
13007 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13008 	struct i40e_hw *hw = &np->vsi->back->hw;
13009 	u8 type, filter_index;
13010 	int ret;
13011 
13012 	type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? I40E_AQC_TUNNEL_TYPE_VXLAN :
13013 						   I40E_AQC_TUNNEL_TYPE_NGE;
13014 
13015 	ret = i40e_aq_add_udp_tunnel(hw, ntohs(ti->port), type, &filter_index,
13016 				     NULL);
13017 	if (ret) {
13018 		netdev_info(netdev, "add UDP port failed, err %pe aq_err %s\n",
13019 			    ERR_PTR(ret),
13020 			    i40e_aq_str(hw, hw->aq.asq_last_status));
13021 		return -EIO;
13022 	}
13023 
13024 	udp_tunnel_nic_set_port_priv(netdev, table, idx, filter_index);
13025 	return 0;
13026 }
13027 
13028 static int i40e_udp_tunnel_unset_port(struct net_device *netdev,
13029 				      unsigned int table, unsigned int idx,
13030 				      struct udp_tunnel_info *ti)
13031 {
13032 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13033 	struct i40e_hw *hw = &np->vsi->back->hw;
13034 	int ret;
13035 
13036 	ret = i40e_aq_del_udp_tunnel(hw, ti->hw_priv, NULL);
13037 	if (ret) {
13038 		netdev_info(netdev, "delete UDP port failed, err %pe aq_err %s\n",
13039 			    ERR_PTR(ret),
13040 			    i40e_aq_str(hw, hw->aq.asq_last_status));
13041 		return -EIO;
13042 	}
13043 
13044 	return 0;
13045 }
13046 
13047 static int i40e_get_phys_port_id(struct net_device *netdev,
13048 				 struct netdev_phys_item_id *ppid)
13049 {
13050 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13051 	struct i40e_pf *pf = np->vsi->back;
13052 	struct i40e_hw *hw = &pf->hw;
13053 
13054 	if (!test_bit(I40E_HW_CAP_PORT_ID_VALID, pf->hw.caps))
13055 		return -EOPNOTSUPP;
13056 
13057 	ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
13058 	memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
13059 
13060 	return 0;
13061 }
13062 
13063 /**
13064  * i40e_ndo_fdb_add - add an entry to the hardware database
13065  * @ndm: the input from the stack
13066  * @tb: pointer to array of nladdr (unused)
13067  * @dev: the net device pointer
13068  * @addr: the MAC address entry being added
13069  * @vid: VLAN ID
13070  * @flags: instructions from stack about fdb operation
13071  * @extack: netlink extended ack, unused currently
13072  */
13073 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
13074 			    struct net_device *dev,
13075 			    const unsigned char *addr, u16 vid,
13076 			    u16 flags,
13077 			    struct netlink_ext_ack *extack)
13078 {
13079 	struct i40e_netdev_priv *np = netdev_priv(dev);
13080 	struct i40e_pf *pf = np->vsi->back;
13081 	int err = 0;
13082 
13083 	if (!test_bit(I40E_FLAG_SRIOV_ENA, pf->flags))
13084 		return -EOPNOTSUPP;
13085 
13086 	if (vid) {
13087 		pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
13088 		return -EINVAL;
13089 	}
13090 
13091 	/* Hardware does not support aging addresses so if a
13092 	 * ndm_state is given only allow permanent addresses
13093 	 */
13094 	if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
13095 		netdev_info(dev, "FDB only supports static addresses\n");
13096 		return -EINVAL;
13097 	}
13098 
13099 	if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
13100 		err = dev_uc_add_excl(dev, addr);
13101 	else if (is_multicast_ether_addr(addr))
13102 		err = dev_mc_add_excl(dev, addr);
13103 	else
13104 		err = -EINVAL;
13105 
13106 	/* Only return duplicate errors if NLM_F_EXCL is set */
13107 	if (err == -EEXIST && !(flags & NLM_F_EXCL))
13108 		err = 0;
13109 
13110 	return err;
13111 }
13112 
13113 /**
13114  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
13115  * @dev: the netdev being configured
13116  * @nlh: RTNL message
13117  * @flags: bridge flags
13118  * @extack: netlink extended ack
13119  *
13120  * Inserts a new hardware bridge if not already created and
13121  * enables the bridging mode requested (VEB or VEPA). If the
13122  * hardware bridge has already been inserted and the request
13123  * is to change the mode then that requires a PF reset to
13124  * allow rebuild of the components with required hardware
13125  * bridge mode enabled.
13126  *
13127  * Note: expects to be called while under rtnl_lock()
13128  **/
13129 static int i40e_ndo_bridge_setlink(struct net_device *dev,
13130 				   struct nlmsghdr *nlh,
13131 				   u16 flags,
13132 				   struct netlink_ext_ack *extack)
13133 {
13134 	struct i40e_netdev_priv *np = netdev_priv(dev);
13135 	struct i40e_vsi *vsi = np->vsi;
13136 	struct i40e_pf *pf = vsi->back;
13137 	struct nlattr *attr, *br_spec;
13138 	struct i40e_veb *veb;
13139 	int rem;
13140 
13141 	/* Only for PF VSI for now */
13142 	if (vsi->type != I40E_VSI_MAIN)
13143 		return -EOPNOTSUPP;
13144 
13145 	/* Find the HW bridge for PF VSI */
13146 	veb = i40e_pf_get_veb_by_seid(pf, vsi->uplink_seid);
13147 
13148 	br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
13149 	if (!br_spec)
13150 		return -EINVAL;
13151 
13152 	nla_for_each_nested_type(attr, IFLA_BRIDGE_MODE, br_spec, rem) {
13153 		__u16 mode = nla_get_u16(attr);
13154 
13155 		if ((mode != BRIDGE_MODE_VEPA) &&
13156 		    (mode != BRIDGE_MODE_VEB))
13157 			return -EINVAL;
13158 
13159 		/* Insert a new HW bridge */
13160 		if (!veb) {
13161 			veb = i40e_veb_setup(pf, vsi->uplink_seid, vsi->seid,
13162 					     vsi->tc_config.enabled_tc);
13163 			if (veb) {
13164 				veb->bridge_mode = mode;
13165 				i40e_config_bridge_mode(veb);
13166 			} else {
13167 				/* No Bridge HW offload available */
13168 				return -ENOENT;
13169 			}
13170 			break;
13171 		} else if (mode != veb->bridge_mode) {
13172 			/* Existing HW bridge but different mode needs reset */
13173 			veb->bridge_mode = mode;
13174 			/* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
13175 			if (mode == BRIDGE_MODE_VEB)
13176 				set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
13177 			else
13178 				clear_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
13179 			i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13180 			break;
13181 		}
13182 	}
13183 
13184 	return 0;
13185 }
13186 
13187 /**
13188  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
13189  * @skb: skb buff
13190  * @pid: process id
13191  * @seq: RTNL message seq #
13192  * @dev: the netdev being configured
13193  * @filter_mask: unused
13194  * @nlflags: netlink flags passed in
13195  *
13196  * Return the mode in which the hardware bridge is operating in
13197  * i.e VEB or VEPA.
13198  **/
13199 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
13200 				   struct net_device *dev,
13201 				   u32 __always_unused filter_mask,
13202 				   int nlflags)
13203 {
13204 	struct i40e_netdev_priv *np = netdev_priv(dev);
13205 	struct i40e_vsi *vsi = np->vsi;
13206 	struct i40e_pf *pf = vsi->back;
13207 	struct i40e_veb *veb;
13208 
13209 	/* Only for PF VSI for now */
13210 	if (vsi->type != I40E_VSI_MAIN)
13211 		return -EOPNOTSUPP;
13212 
13213 	/* Find the HW bridge for the PF VSI */
13214 	veb = i40e_pf_get_veb_by_seid(pf, vsi->uplink_seid);
13215 	if (!veb)
13216 		return 0;
13217 
13218 	return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
13219 				       0, 0, nlflags, filter_mask, NULL);
13220 }
13221 
13222 /**
13223  * i40e_features_check - Validate encapsulated packet conforms to limits
13224  * @skb: skb buff
13225  * @dev: This physical port's netdev
13226  * @features: Offload features that the stack believes apply
13227  **/
13228 static netdev_features_t i40e_features_check(struct sk_buff *skb,
13229 					     struct net_device *dev,
13230 					     netdev_features_t features)
13231 {
13232 	size_t len;
13233 
13234 	/* No point in doing any of this if neither checksum nor GSO are
13235 	 * being requested for this frame.  We can rule out both by just
13236 	 * checking for CHECKSUM_PARTIAL
13237 	 */
13238 	if (skb->ip_summed != CHECKSUM_PARTIAL)
13239 		return features;
13240 
13241 	/* We cannot support GSO if the MSS is going to be less than
13242 	 * 64 bytes.  If it is then we need to drop support for GSO.
13243 	 */
13244 	if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
13245 		features &= ~NETIF_F_GSO_MASK;
13246 
13247 	/* MACLEN can support at most 63 words */
13248 	len = skb_network_offset(skb);
13249 	if (len & ~(63 * 2))
13250 		goto out_err;
13251 
13252 	/* IPLEN and EIPLEN can support at most 127 dwords */
13253 	len = skb_network_header_len(skb);
13254 	if (len & ~(127 * 4))
13255 		goto out_err;
13256 
13257 	if (skb->encapsulation) {
13258 		/* L4TUNLEN can support 127 words */
13259 		len = skb_inner_network_header(skb) - skb_transport_header(skb);
13260 		if (len & ~(127 * 2))
13261 			goto out_err;
13262 
13263 		/* IPLEN can support at most 127 dwords */
13264 		len = skb_inner_transport_header(skb) -
13265 		      skb_inner_network_header(skb);
13266 		if (len & ~(127 * 4))
13267 			goto out_err;
13268 	}
13269 
13270 	/* No need to validate L4LEN as TCP is the only protocol with a
13271 	 * flexible value and we support all possible values supported
13272 	 * by TCP, which is at most 15 dwords
13273 	 */
13274 
13275 	return features;
13276 out_err:
13277 	return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
13278 }
13279 
13280 /**
13281  * i40e_xdp_setup - add/remove an XDP program
13282  * @vsi: VSI to changed
13283  * @prog: XDP program
13284  * @extack: netlink extended ack
13285  **/
13286 static int i40e_xdp_setup(struct i40e_vsi *vsi, struct bpf_prog *prog,
13287 			  struct netlink_ext_ack *extack)
13288 {
13289 	int frame_size = i40e_max_vsi_frame_size(vsi, prog);
13290 	struct i40e_pf *pf = vsi->back;
13291 	struct bpf_prog *old_prog;
13292 	bool need_reset;
13293 	int i;
13294 
13295 	/* VSI shall be deleted in a moment, block loading new programs */
13296 	if (prog && test_bit(__I40E_IN_REMOVE, pf->state))
13297 		return -EINVAL;
13298 
13299 	/* Don't allow frames that span over multiple buffers */
13300 	if (vsi->netdev->mtu > frame_size - I40E_PACKET_HDR_PAD) {
13301 		NL_SET_ERR_MSG_MOD(extack, "MTU too large for linear frames and XDP prog does not support frags");
13302 		return -EINVAL;
13303 	}
13304 
13305 	/* When turning XDP on->off/off->on we reset and rebuild the rings. */
13306 	need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
13307 	if (need_reset)
13308 		i40e_prep_for_reset(pf);
13309 
13310 	old_prog = xchg(&vsi->xdp_prog, prog);
13311 
13312 	if (need_reset) {
13313 		if (!prog) {
13314 			xdp_features_clear_redirect_target(vsi->netdev);
13315 			/* Wait until ndo_xsk_wakeup completes. */
13316 			synchronize_rcu();
13317 		}
13318 		i40e_reset_and_rebuild(pf, true, true);
13319 	}
13320 
13321 	if (!i40e_enabled_xdp_vsi(vsi) && prog) {
13322 		if (i40e_realloc_rx_bi_zc(vsi, true))
13323 			return -ENOMEM;
13324 	} else if (i40e_enabled_xdp_vsi(vsi) && !prog) {
13325 		if (i40e_realloc_rx_bi_zc(vsi, false))
13326 			return -ENOMEM;
13327 	}
13328 
13329 	for (i = 0; i < vsi->num_queue_pairs; i++)
13330 		WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
13331 
13332 	if (old_prog)
13333 		bpf_prog_put(old_prog);
13334 
13335 	/* Kick start the NAPI context if there is an AF_XDP socket open
13336 	 * on that queue id. This so that receiving will start.
13337 	 */
13338 	if (need_reset && prog) {
13339 		for (i = 0; i < vsi->num_queue_pairs; i++)
13340 			if (vsi->xdp_rings[i]->xsk_pool)
13341 				(void)i40e_xsk_wakeup(vsi->netdev, i,
13342 						      XDP_WAKEUP_RX);
13343 		xdp_features_set_redirect_target(vsi->netdev, true);
13344 	}
13345 
13346 	return 0;
13347 }
13348 
13349 /**
13350  * i40e_enter_busy_conf - Enters busy config state
13351  * @vsi: vsi
13352  *
13353  * Returns 0 on success, <0 for failure.
13354  **/
13355 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
13356 {
13357 	struct i40e_pf *pf = vsi->back;
13358 	int timeout = 50;
13359 
13360 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
13361 		timeout--;
13362 		if (!timeout)
13363 			return -EBUSY;
13364 		usleep_range(1000, 2000);
13365 	}
13366 
13367 	return 0;
13368 }
13369 
13370 /**
13371  * i40e_exit_busy_conf - Exits busy config state
13372  * @vsi: vsi
13373  **/
13374 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
13375 {
13376 	struct i40e_pf *pf = vsi->back;
13377 
13378 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
13379 }
13380 
13381 /**
13382  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
13383  * @vsi: vsi
13384  * @queue_pair: queue pair
13385  **/
13386 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
13387 {
13388 	memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
13389 	       sizeof(vsi->rx_rings[queue_pair]->rx_stats));
13390 	memset(&vsi->tx_rings[queue_pair]->stats, 0,
13391 	       sizeof(vsi->tx_rings[queue_pair]->stats));
13392 	if (i40e_enabled_xdp_vsi(vsi)) {
13393 		memset(&vsi->xdp_rings[queue_pair]->stats, 0,
13394 		       sizeof(vsi->xdp_rings[queue_pair]->stats));
13395 	}
13396 }
13397 
13398 /**
13399  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
13400  * @vsi: vsi
13401  * @queue_pair: queue pair
13402  **/
13403 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
13404 {
13405 	i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
13406 	if (i40e_enabled_xdp_vsi(vsi)) {
13407 		/* Make sure that in-progress ndo_xdp_xmit calls are
13408 		 * completed.
13409 		 */
13410 		synchronize_rcu();
13411 		i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
13412 	}
13413 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13414 }
13415 
13416 /**
13417  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
13418  * @vsi: vsi
13419  * @queue_pair: queue pair
13420  * @enable: true for enable, false for disable
13421  **/
13422 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
13423 					bool enable)
13424 {
13425 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13426 	struct i40e_q_vector *q_vector = rxr->q_vector;
13427 
13428 	if (!vsi->netdev)
13429 		return;
13430 
13431 	/* All rings in a qp belong to the same qvector. */
13432 	if (q_vector->rx.ring || q_vector->tx.ring) {
13433 		if (enable)
13434 			napi_enable(&q_vector->napi);
13435 		else
13436 			napi_disable(&q_vector->napi);
13437 	}
13438 }
13439 
13440 /**
13441  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
13442  * @vsi: vsi
13443  * @queue_pair: queue pair
13444  * @enable: true for enable, false for disable
13445  *
13446  * Returns 0 on success, <0 on failure.
13447  **/
13448 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
13449 					bool enable)
13450 {
13451 	struct i40e_pf *pf = vsi->back;
13452 	int pf_q, ret = 0;
13453 
13454 	pf_q = vsi->base_queue + queue_pair;
13455 	ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
13456 				     false /*is xdp*/, enable);
13457 	if (ret) {
13458 		dev_info(&pf->pdev->dev,
13459 			 "VSI seid %d Tx ring %d %sable timeout\n",
13460 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13461 		return ret;
13462 	}
13463 
13464 	i40e_control_rx_q(pf, pf_q, enable);
13465 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
13466 	if (ret) {
13467 		dev_info(&pf->pdev->dev,
13468 			 "VSI seid %d Rx ring %d %sable timeout\n",
13469 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13470 		return ret;
13471 	}
13472 
13473 	/* Due to HW errata, on Rx disable only, the register can
13474 	 * indicate done before it really is. Needs 50ms to be sure
13475 	 */
13476 	if (!enable)
13477 		mdelay(50);
13478 
13479 	if (!i40e_enabled_xdp_vsi(vsi))
13480 		return ret;
13481 
13482 	ret = i40e_control_wait_tx_q(vsi->seid, pf,
13483 				     pf_q + vsi->alloc_queue_pairs,
13484 				     true /*is xdp*/, enable);
13485 	if (ret) {
13486 		dev_info(&pf->pdev->dev,
13487 			 "VSI seid %d XDP Tx ring %d %sable timeout\n",
13488 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13489 	}
13490 
13491 	return ret;
13492 }
13493 
13494 /**
13495  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
13496  * @vsi: vsi
13497  * @queue_pair: queue_pair
13498  **/
13499 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
13500 {
13501 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13502 	struct i40e_pf *pf = vsi->back;
13503 	struct i40e_hw *hw = &pf->hw;
13504 
13505 	/* All rings in a qp belong to the same qvector. */
13506 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
13507 		i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
13508 	else
13509 		i40e_irq_dynamic_enable_icr0(pf);
13510 
13511 	i40e_flush(hw);
13512 }
13513 
13514 /**
13515  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
13516  * @vsi: vsi
13517  * @queue_pair: queue_pair
13518  **/
13519 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
13520 {
13521 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13522 	struct i40e_pf *pf = vsi->back;
13523 	struct i40e_hw *hw = &pf->hw;
13524 
13525 	/* For simplicity, instead of removing the qp interrupt causes
13526 	 * from the interrupt linked list, we simply disable the interrupt, and
13527 	 * leave the list intact.
13528 	 *
13529 	 * All rings in a qp belong to the same qvector.
13530 	 */
13531 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
13532 		u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
13533 
13534 		wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
13535 		i40e_flush(hw);
13536 		synchronize_irq(pf->msix_entries[intpf].vector);
13537 	} else {
13538 		/* Legacy and MSI mode - this stops all interrupt handling */
13539 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
13540 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
13541 		i40e_flush(hw);
13542 		synchronize_irq(pf->pdev->irq);
13543 	}
13544 }
13545 
13546 /**
13547  * i40e_queue_pair_disable - Disables a queue pair
13548  * @vsi: vsi
13549  * @queue_pair: queue pair
13550  *
13551  * Returns 0 on success, <0 on failure.
13552  **/
13553 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
13554 {
13555 	int err;
13556 
13557 	err = i40e_enter_busy_conf(vsi);
13558 	if (err)
13559 		return err;
13560 
13561 	i40e_queue_pair_disable_irq(vsi, queue_pair);
13562 	i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
13563 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
13564 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13565 	i40e_queue_pair_clean_rings(vsi, queue_pair);
13566 	i40e_queue_pair_reset_stats(vsi, queue_pair);
13567 
13568 	return err;
13569 }
13570 
13571 /**
13572  * i40e_queue_pair_enable - Enables a queue pair
13573  * @vsi: vsi
13574  * @queue_pair: queue pair
13575  *
13576  * Returns 0 on success, <0 on failure.
13577  **/
13578 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
13579 {
13580 	int err;
13581 
13582 	err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
13583 	if (err)
13584 		return err;
13585 
13586 	if (i40e_enabled_xdp_vsi(vsi)) {
13587 		err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
13588 		if (err)
13589 			return err;
13590 	}
13591 
13592 	err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
13593 	if (err)
13594 		return err;
13595 
13596 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
13597 	i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
13598 	i40e_queue_pair_enable_irq(vsi, queue_pair);
13599 
13600 	i40e_exit_busy_conf(vsi);
13601 
13602 	return err;
13603 }
13604 
13605 /**
13606  * i40e_xdp - implements ndo_bpf for i40e
13607  * @dev: netdevice
13608  * @xdp: XDP command
13609  **/
13610 static int i40e_xdp(struct net_device *dev,
13611 		    struct netdev_bpf *xdp)
13612 {
13613 	struct i40e_netdev_priv *np = netdev_priv(dev);
13614 	struct i40e_vsi *vsi = np->vsi;
13615 
13616 	if (vsi->type != I40E_VSI_MAIN)
13617 		return -EINVAL;
13618 
13619 	switch (xdp->command) {
13620 	case XDP_SETUP_PROG:
13621 		return i40e_xdp_setup(vsi, xdp->prog, xdp->extack);
13622 	case XDP_SETUP_XSK_POOL:
13623 		return i40e_xsk_pool_setup(vsi, xdp->xsk.pool,
13624 					   xdp->xsk.queue_id);
13625 	default:
13626 		return -EINVAL;
13627 	}
13628 }
13629 
13630 static const struct net_device_ops i40e_netdev_ops = {
13631 	.ndo_open		= i40e_open,
13632 	.ndo_stop		= i40e_close,
13633 	.ndo_start_xmit		= i40e_lan_xmit_frame,
13634 	.ndo_get_stats64	= i40e_get_netdev_stats_struct,
13635 	.ndo_set_rx_mode	= i40e_set_rx_mode,
13636 	.ndo_validate_addr	= eth_validate_addr,
13637 	.ndo_set_mac_address	= i40e_set_mac,
13638 	.ndo_change_mtu		= i40e_change_mtu,
13639 	.ndo_eth_ioctl		= i40e_ioctl,
13640 	.ndo_tx_timeout		= i40e_tx_timeout,
13641 	.ndo_vlan_rx_add_vid	= i40e_vlan_rx_add_vid,
13642 	.ndo_vlan_rx_kill_vid	= i40e_vlan_rx_kill_vid,
13643 #ifdef CONFIG_NET_POLL_CONTROLLER
13644 	.ndo_poll_controller	= i40e_netpoll,
13645 #endif
13646 	.ndo_setup_tc		= __i40e_setup_tc,
13647 	.ndo_select_queue	= i40e_lan_select_queue,
13648 	.ndo_set_features	= i40e_set_features,
13649 	.ndo_set_vf_mac		= i40e_ndo_set_vf_mac,
13650 	.ndo_set_vf_vlan	= i40e_ndo_set_vf_port_vlan,
13651 	.ndo_get_vf_stats	= i40e_get_vf_stats,
13652 	.ndo_set_vf_rate	= i40e_ndo_set_vf_bw,
13653 	.ndo_get_vf_config	= i40e_ndo_get_vf_config,
13654 	.ndo_set_vf_link_state	= i40e_ndo_set_vf_link_state,
13655 	.ndo_set_vf_spoofchk	= i40e_ndo_set_vf_spoofchk,
13656 	.ndo_set_vf_trust	= i40e_ndo_set_vf_trust,
13657 	.ndo_get_phys_port_id	= i40e_get_phys_port_id,
13658 	.ndo_fdb_add		= i40e_ndo_fdb_add,
13659 	.ndo_features_check	= i40e_features_check,
13660 	.ndo_bridge_getlink	= i40e_ndo_bridge_getlink,
13661 	.ndo_bridge_setlink	= i40e_ndo_bridge_setlink,
13662 	.ndo_bpf		= i40e_xdp,
13663 	.ndo_xdp_xmit		= i40e_xdp_xmit,
13664 	.ndo_xsk_wakeup	        = i40e_xsk_wakeup,
13665 	.ndo_dfwd_add_station	= i40e_fwd_add,
13666 	.ndo_dfwd_del_station	= i40e_fwd_del,
13667 };
13668 
13669 /**
13670  * i40e_config_netdev - Setup the netdev flags
13671  * @vsi: the VSI being configured
13672  *
13673  * Returns 0 on success, negative value on failure
13674  **/
13675 static int i40e_config_netdev(struct i40e_vsi *vsi)
13676 {
13677 	struct i40e_pf *pf = vsi->back;
13678 	struct i40e_hw *hw = &pf->hw;
13679 	struct i40e_netdev_priv *np;
13680 	struct net_device *netdev;
13681 	u8 broadcast[ETH_ALEN];
13682 	u8 mac_addr[ETH_ALEN];
13683 	int etherdev_size;
13684 	netdev_features_t hw_enc_features;
13685 	netdev_features_t hw_features;
13686 
13687 	etherdev_size = sizeof(struct i40e_netdev_priv);
13688 	netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
13689 	if (!netdev)
13690 		return -ENOMEM;
13691 
13692 	vsi->netdev = netdev;
13693 	np = netdev_priv(netdev);
13694 	np->vsi = vsi;
13695 
13696 	hw_enc_features = NETIF_F_SG			|
13697 			  NETIF_F_HW_CSUM		|
13698 			  NETIF_F_HIGHDMA		|
13699 			  NETIF_F_SOFT_FEATURES		|
13700 			  NETIF_F_TSO			|
13701 			  NETIF_F_TSO_ECN		|
13702 			  NETIF_F_TSO6			|
13703 			  NETIF_F_GSO_GRE		|
13704 			  NETIF_F_GSO_GRE_CSUM		|
13705 			  NETIF_F_GSO_PARTIAL		|
13706 			  NETIF_F_GSO_IPXIP4		|
13707 			  NETIF_F_GSO_IPXIP6		|
13708 			  NETIF_F_GSO_UDP_TUNNEL	|
13709 			  NETIF_F_GSO_UDP_TUNNEL_CSUM	|
13710 			  NETIF_F_GSO_UDP_L4		|
13711 			  NETIF_F_SCTP_CRC		|
13712 			  NETIF_F_RXHASH		|
13713 			  NETIF_F_RXCSUM		|
13714 			  0;
13715 
13716 	if (!test_bit(I40E_HW_CAP_OUTER_UDP_CSUM, pf->hw.caps))
13717 		netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
13718 
13719 	netdev->udp_tunnel_nic_info = &pf->udp_tunnel_nic;
13720 
13721 	netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
13722 
13723 	netdev->hw_enc_features |= hw_enc_features;
13724 
13725 	/* record features VLANs can make use of */
13726 	netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
13727 
13728 #define I40E_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE |		\
13729 				   NETIF_F_GSO_GRE_CSUM |	\
13730 				   NETIF_F_GSO_IPXIP4 |		\
13731 				   NETIF_F_GSO_IPXIP6 |		\
13732 				   NETIF_F_GSO_UDP_TUNNEL |	\
13733 				   NETIF_F_GSO_UDP_TUNNEL_CSUM)
13734 
13735 	netdev->gso_partial_features = I40E_GSO_PARTIAL_FEATURES;
13736 	netdev->features |= NETIF_F_GSO_PARTIAL |
13737 			    I40E_GSO_PARTIAL_FEATURES;
13738 
13739 	netdev->mpls_features |= NETIF_F_SG;
13740 	netdev->mpls_features |= NETIF_F_HW_CSUM;
13741 	netdev->mpls_features |= NETIF_F_TSO;
13742 	netdev->mpls_features |= NETIF_F_TSO6;
13743 	netdev->mpls_features |= I40E_GSO_PARTIAL_FEATURES;
13744 
13745 	/* enable macvlan offloads */
13746 	netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
13747 
13748 	hw_features = hw_enc_features		|
13749 		      NETIF_F_HW_VLAN_CTAG_TX	|
13750 		      NETIF_F_HW_VLAN_CTAG_RX;
13751 
13752 	if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
13753 		hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
13754 
13755 	netdev->hw_features |= hw_features | NETIF_F_LOOPBACK;
13756 
13757 	netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
13758 	netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
13759 
13760 	netdev->features &= ~NETIF_F_HW_TC;
13761 
13762 	if (vsi->type == I40E_VSI_MAIN) {
13763 		SET_NETDEV_DEV(netdev, &pf->pdev->dev);
13764 		ether_addr_copy(mac_addr, hw->mac.perm_addr);
13765 		/* The following steps are necessary for two reasons. First,
13766 		 * some older NVM configurations load a default MAC-VLAN
13767 		 * filter that will accept any tagged packet, and we want to
13768 		 * replace this with a normal filter. Additionally, it is
13769 		 * possible our MAC address was provided by the platform using
13770 		 * Open Firmware or similar.
13771 		 *
13772 		 * Thus, we need to remove the default filter and install one
13773 		 * specific to the MAC address.
13774 		 */
13775 		i40e_rm_default_mac_filter(vsi, mac_addr);
13776 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13777 		i40e_add_mac_filter(vsi, mac_addr);
13778 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13779 
13780 		netdev->xdp_features = NETDEV_XDP_ACT_BASIC |
13781 				       NETDEV_XDP_ACT_REDIRECT |
13782 				       NETDEV_XDP_ACT_XSK_ZEROCOPY |
13783 				       NETDEV_XDP_ACT_RX_SG;
13784 		netdev->xdp_zc_max_segs = I40E_MAX_BUFFER_TXD;
13785 	} else {
13786 		/* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
13787 		 * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
13788 		 * the end, which is 4 bytes long, so force truncation of the
13789 		 * original name by IFNAMSIZ - 4
13790 		 */
13791 		struct i40e_vsi *main_vsi = i40e_pf_get_main_vsi(pf);
13792 
13793 		snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d", IFNAMSIZ - 4,
13794 			 main_vsi->netdev->name);
13795 		eth_random_addr(mac_addr);
13796 
13797 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13798 		i40e_add_mac_filter(vsi, mac_addr);
13799 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13800 	}
13801 
13802 	/* Add the broadcast filter so that we initially will receive
13803 	 * broadcast packets. Note that when a new VLAN is first added the
13804 	 * driver will convert all filters marked I40E_VLAN_ANY into VLAN
13805 	 * specific filters as part of transitioning into "vlan" operation.
13806 	 * When more VLANs are added, the driver will copy each existing MAC
13807 	 * filter and add it for the new VLAN.
13808 	 *
13809 	 * Broadcast filters are handled specially by
13810 	 * i40e_sync_filters_subtask, as the driver must to set the broadcast
13811 	 * promiscuous bit instead of adding this directly as a MAC/VLAN
13812 	 * filter. The subtask will update the correct broadcast promiscuous
13813 	 * bits as VLANs become active or inactive.
13814 	 */
13815 	eth_broadcast_addr(broadcast);
13816 	spin_lock_bh(&vsi->mac_filter_hash_lock);
13817 	i40e_add_mac_filter(vsi, broadcast);
13818 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
13819 
13820 	eth_hw_addr_set(netdev, mac_addr);
13821 	ether_addr_copy(netdev->perm_addr, mac_addr);
13822 
13823 	/* i40iw_net_event() reads 16 bytes from neigh->primary_key */
13824 	netdev->neigh_priv_len = sizeof(u32) * 4;
13825 
13826 	netdev->priv_flags |= IFF_UNICAST_FLT;
13827 	netdev->priv_flags |= IFF_SUPP_NOFCS;
13828 	/* Setup netdev TC information */
13829 	i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
13830 
13831 	netdev->netdev_ops = &i40e_netdev_ops;
13832 	netdev->watchdog_timeo = 5 * HZ;
13833 	i40e_set_ethtool_ops(netdev);
13834 
13835 	/* MTU range: 68 - 9706 */
13836 	netdev->min_mtu = ETH_MIN_MTU;
13837 	netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13838 
13839 	return 0;
13840 }
13841 
13842 /**
13843  * i40e_vsi_delete - Delete a VSI from the switch
13844  * @vsi: the VSI being removed
13845  *
13846  * Returns 0 on success, negative value on failure
13847  **/
13848 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13849 {
13850 	/* remove default VSI is not allowed */
13851 	if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13852 		return;
13853 
13854 	i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13855 }
13856 
13857 /**
13858  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13859  * @vsi: the VSI being queried
13860  *
13861  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13862  **/
13863 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13864 {
13865 	struct i40e_veb *veb;
13866 	struct i40e_pf *pf = vsi->back;
13867 
13868 	/* Uplink is not a bridge so default to VEB */
13869 	if (vsi->veb_idx >= I40E_MAX_VEB)
13870 		return 1;
13871 
13872 	veb = pf->veb[vsi->veb_idx];
13873 	if (!veb) {
13874 		dev_info(&pf->pdev->dev,
13875 			 "There is no veb associated with the bridge\n");
13876 		return -ENOENT;
13877 	}
13878 
13879 	/* Uplink is a bridge in VEPA mode */
13880 	if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13881 		return 0;
13882 	} else {
13883 		/* Uplink is a bridge in VEB mode */
13884 		return 1;
13885 	}
13886 
13887 	/* VEPA is now default bridge, so return 0 */
13888 	return 0;
13889 }
13890 
13891 /**
13892  * i40e_add_vsi - Add a VSI to the switch
13893  * @vsi: the VSI being configured
13894  *
13895  * This initializes a VSI context depending on the VSI type to be added and
13896  * passes it down to the add_vsi aq command.
13897  **/
13898 static int i40e_add_vsi(struct i40e_vsi *vsi)
13899 {
13900 	int ret = -ENODEV;
13901 	struct i40e_pf *pf = vsi->back;
13902 	struct i40e_hw *hw = &pf->hw;
13903 	struct i40e_vsi_context ctxt;
13904 	struct i40e_mac_filter *f;
13905 	struct hlist_node *h;
13906 	int bkt;
13907 
13908 	u8 enabled_tc = 0x1; /* TC0 enabled */
13909 	int f_count = 0;
13910 
13911 	memset(&ctxt, 0, sizeof(ctxt));
13912 	switch (vsi->type) {
13913 	case I40E_VSI_MAIN:
13914 		/* The PF's main VSI is already setup as part of the
13915 		 * device initialization, so we'll not bother with
13916 		 * the add_vsi call, but we will retrieve the current
13917 		 * VSI context.
13918 		 */
13919 		ctxt.seid = pf->main_vsi_seid;
13920 		ctxt.pf_num = pf->hw.pf_id;
13921 		ctxt.vf_num = 0;
13922 		ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13923 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13924 		if (ret) {
13925 			dev_info(&pf->pdev->dev,
13926 				 "couldn't get PF vsi config, err %pe aq_err %s\n",
13927 				 ERR_PTR(ret),
13928 				 i40e_aq_str(&pf->hw,
13929 					     pf->hw.aq.asq_last_status));
13930 			return -ENOENT;
13931 		}
13932 		vsi->info = ctxt.info;
13933 		vsi->info.valid_sections = 0;
13934 
13935 		vsi->seid = ctxt.seid;
13936 		vsi->id = ctxt.vsi_number;
13937 
13938 		enabled_tc = i40e_pf_get_tc_map(pf);
13939 
13940 		/* Source pruning is enabled by default, so the flag is
13941 		 * negative logic - if it's set, we need to fiddle with
13942 		 * the VSI to disable source pruning.
13943 		 */
13944 		if (test_bit(I40E_FLAG_SOURCE_PRUNING_DIS, pf->flags)) {
13945 			memset(&ctxt, 0, sizeof(ctxt));
13946 			ctxt.seid = pf->main_vsi_seid;
13947 			ctxt.pf_num = pf->hw.pf_id;
13948 			ctxt.vf_num = 0;
13949 			ctxt.info.valid_sections |=
13950 				     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13951 			ctxt.info.switch_id =
13952 				   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13953 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13954 			if (ret) {
13955 				dev_info(&pf->pdev->dev,
13956 					 "update vsi failed, err %d aq_err %s\n",
13957 					 ret,
13958 					 i40e_aq_str(&pf->hw,
13959 						     pf->hw.aq.asq_last_status));
13960 				ret = -ENOENT;
13961 				goto err;
13962 			}
13963 		}
13964 
13965 		/* MFP mode setup queue map and update VSI */
13966 		if (test_bit(I40E_FLAG_MFP_ENA, pf->flags) &&
13967 		    !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
13968 			memset(&ctxt, 0, sizeof(ctxt));
13969 			ctxt.seid = pf->main_vsi_seid;
13970 			ctxt.pf_num = pf->hw.pf_id;
13971 			ctxt.vf_num = 0;
13972 			i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
13973 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13974 			if (ret) {
13975 				dev_info(&pf->pdev->dev,
13976 					 "update vsi failed, err %pe aq_err %s\n",
13977 					 ERR_PTR(ret),
13978 					 i40e_aq_str(&pf->hw,
13979 						    pf->hw.aq.asq_last_status));
13980 				ret = -ENOENT;
13981 				goto err;
13982 			}
13983 			/* update the local VSI info queue map */
13984 			i40e_vsi_update_queue_map(vsi, &ctxt);
13985 			vsi->info.valid_sections = 0;
13986 		} else {
13987 			/* Default/Main VSI is only enabled for TC0
13988 			 * reconfigure it to enable all TCs that are
13989 			 * available on the port in SFP mode.
13990 			 * For MFP case the iSCSI PF would use this
13991 			 * flow to enable LAN+iSCSI TC.
13992 			 */
13993 			ret = i40e_vsi_config_tc(vsi, enabled_tc);
13994 			if (ret) {
13995 				/* Single TC condition is not fatal,
13996 				 * message and continue
13997 				 */
13998 				dev_info(&pf->pdev->dev,
13999 					 "failed to configure TCs for main VSI tc_map 0x%08x, err %pe aq_err %s\n",
14000 					 enabled_tc,
14001 					 ERR_PTR(ret),
14002 					 i40e_aq_str(&pf->hw,
14003 						    pf->hw.aq.asq_last_status));
14004 			}
14005 		}
14006 		break;
14007 
14008 	case I40E_VSI_FDIR:
14009 		ctxt.pf_num = hw->pf_id;
14010 		ctxt.vf_num = 0;
14011 		ctxt.uplink_seid = vsi->uplink_seid;
14012 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14013 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
14014 		if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags) &&
14015 		    (i40e_is_vsi_uplink_mode_veb(vsi))) {
14016 			ctxt.info.valid_sections |=
14017 			     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14018 			ctxt.info.switch_id =
14019 			   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14020 		}
14021 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14022 		break;
14023 
14024 	case I40E_VSI_VMDQ2:
14025 		ctxt.pf_num = hw->pf_id;
14026 		ctxt.vf_num = 0;
14027 		ctxt.uplink_seid = vsi->uplink_seid;
14028 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14029 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
14030 
14031 		/* This VSI is connected to VEB so the switch_id
14032 		 * should be set to zero by default.
14033 		 */
14034 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14035 			ctxt.info.valid_sections |=
14036 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14037 			ctxt.info.switch_id =
14038 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14039 		}
14040 
14041 		/* Setup the VSI tx/rx queue map for TC0 only for now */
14042 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14043 		break;
14044 
14045 	case I40E_VSI_SRIOV:
14046 		ctxt.pf_num = hw->pf_id;
14047 		ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
14048 		ctxt.uplink_seid = vsi->uplink_seid;
14049 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14050 		ctxt.flags = I40E_AQ_VSI_TYPE_VF;
14051 
14052 		/* This VSI is connected to VEB so the switch_id
14053 		 * should be set to zero by default.
14054 		 */
14055 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14056 			ctxt.info.valid_sections |=
14057 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14058 			ctxt.info.switch_id =
14059 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14060 		}
14061 
14062 		if (test_bit(I40E_FLAG_IWARP_ENA, vsi->back->flags)) {
14063 			ctxt.info.valid_sections |=
14064 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
14065 			ctxt.info.queueing_opt_flags |=
14066 				(I40E_AQ_VSI_QUE_OPT_TCP_ENA |
14067 				 I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
14068 		}
14069 
14070 		ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
14071 		ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
14072 		if (pf->vf[vsi->vf_id].spoofchk) {
14073 			ctxt.info.valid_sections |=
14074 				cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
14075 			ctxt.info.sec_flags |=
14076 				(I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
14077 				 I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
14078 		}
14079 		/* Setup the VSI tx/rx queue map for TC0 only for now */
14080 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14081 		break;
14082 
14083 	case I40E_VSI_IWARP:
14084 		/* send down message to iWARP */
14085 		break;
14086 
14087 	default:
14088 		return -ENODEV;
14089 	}
14090 
14091 	if (vsi->type != I40E_VSI_MAIN) {
14092 		ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
14093 		if (ret) {
14094 			dev_info(&vsi->back->pdev->dev,
14095 				 "add vsi failed, err %pe aq_err %s\n",
14096 				 ERR_PTR(ret),
14097 				 i40e_aq_str(&pf->hw,
14098 					     pf->hw.aq.asq_last_status));
14099 			ret = -ENOENT;
14100 			goto err;
14101 		}
14102 		vsi->info = ctxt.info;
14103 		vsi->info.valid_sections = 0;
14104 		vsi->seid = ctxt.seid;
14105 		vsi->id = ctxt.vsi_number;
14106 	}
14107 
14108 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14109 	vsi->active_filters = 0;
14110 	/* If macvlan filters already exist, force them to get loaded */
14111 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
14112 		f->state = I40E_FILTER_NEW;
14113 		f_count++;
14114 	}
14115 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14116 	clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
14117 
14118 	if (f_count) {
14119 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
14120 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
14121 	}
14122 
14123 	/* Update VSI BW information */
14124 	ret = i40e_vsi_get_bw_info(vsi);
14125 	if (ret) {
14126 		dev_info(&pf->pdev->dev,
14127 			 "couldn't get vsi bw info, err %pe aq_err %s\n",
14128 			 ERR_PTR(ret),
14129 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14130 		/* VSI is already added so not tearing that up */
14131 		ret = 0;
14132 	}
14133 
14134 err:
14135 	return ret;
14136 }
14137 
14138 /**
14139  * i40e_vsi_release - Delete a VSI and free its resources
14140  * @vsi: the VSI being removed
14141  *
14142  * Returns 0 on success or < 0 on error
14143  **/
14144 int i40e_vsi_release(struct i40e_vsi *vsi)
14145 {
14146 	struct i40e_mac_filter *f;
14147 	struct hlist_node *h;
14148 	struct i40e_veb *veb;
14149 	struct i40e_pf *pf;
14150 	u16 uplink_seid;
14151 	int i, n, bkt;
14152 
14153 	pf = vsi->back;
14154 
14155 	/* release of a VEB-owner or last VSI is not allowed */
14156 	if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
14157 		dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
14158 			 vsi->seid, vsi->uplink_seid);
14159 		return -ENODEV;
14160 	}
14161 	if (vsi->type == I40E_VSI_MAIN && !test_bit(__I40E_DOWN, pf->state)) {
14162 		dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
14163 		return -ENODEV;
14164 	}
14165 	set_bit(__I40E_VSI_RELEASING, vsi->state);
14166 	uplink_seid = vsi->uplink_seid;
14167 
14168 	if (vsi->type != I40E_VSI_SRIOV) {
14169 		if (vsi->netdev_registered) {
14170 			vsi->netdev_registered = false;
14171 			if (vsi->netdev) {
14172 				/* results in a call to i40e_close() */
14173 				unregister_netdev(vsi->netdev);
14174 			}
14175 		} else {
14176 			i40e_vsi_close(vsi);
14177 		}
14178 		i40e_vsi_disable_irq(vsi);
14179 	}
14180 
14181 	if (vsi->type == I40E_VSI_MAIN)
14182 		i40e_devlink_destroy_port(pf);
14183 
14184 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14185 
14186 	/* clear the sync flag on all filters */
14187 	if (vsi->netdev) {
14188 		__dev_uc_unsync(vsi->netdev, NULL);
14189 		__dev_mc_unsync(vsi->netdev, NULL);
14190 	}
14191 
14192 	/* make sure any remaining filters are marked for deletion */
14193 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
14194 		__i40e_del_filter(vsi, f);
14195 
14196 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14197 
14198 	i40e_sync_vsi_filters(vsi);
14199 
14200 	i40e_vsi_delete(vsi);
14201 	i40e_vsi_free_q_vectors(vsi);
14202 	if (vsi->netdev) {
14203 		free_netdev(vsi->netdev);
14204 		vsi->netdev = NULL;
14205 	}
14206 	i40e_vsi_clear_rings(vsi);
14207 	i40e_vsi_clear(vsi);
14208 
14209 	/* If this was the last thing on the VEB, except for the
14210 	 * controlling VSI, remove the VEB, which puts the controlling
14211 	 * VSI onto the uplink port.
14212 	 *
14213 	 * Well, okay, there's one more exception here: don't remove
14214 	 * the floating VEBs yet.  We'll wait for an explicit remove request
14215 	 * from up the network stack.
14216 	 */
14217 	veb = i40e_pf_get_veb_by_seid(pf, uplink_seid);
14218 	if (veb && veb->uplink_seid) {
14219 		n = 0;
14220 
14221 		/* Count non-controlling VSIs present on  the VEB */
14222 		i40e_pf_for_each_vsi(pf, i, vsi)
14223 			if (vsi->uplink_seid == uplink_seid &&
14224 			    (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14225 				n++;
14226 
14227 		/* If there is no VSI except the control one then release
14228 		 * the VEB and put the control VSI onto VEB uplink.
14229 		 */
14230 		if (!n)
14231 			i40e_veb_release(veb);
14232 	}
14233 
14234 	return 0;
14235 }
14236 
14237 /**
14238  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
14239  * @vsi: ptr to the VSI
14240  *
14241  * This should only be called after i40e_vsi_mem_alloc() which allocates the
14242  * corresponding SW VSI structure and initializes num_queue_pairs for the
14243  * newly allocated VSI.
14244  *
14245  * Returns 0 on success or negative on failure
14246  **/
14247 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
14248 {
14249 	int ret = -ENOENT;
14250 	struct i40e_pf *pf = vsi->back;
14251 
14252 	if (vsi->q_vectors[0]) {
14253 		dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
14254 			 vsi->seid);
14255 		return -EEXIST;
14256 	}
14257 
14258 	if (vsi->base_vector) {
14259 		dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
14260 			 vsi->seid, vsi->base_vector);
14261 		return -EEXIST;
14262 	}
14263 
14264 	ret = i40e_vsi_alloc_q_vectors(vsi);
14265 	if (ret) {
14266 		dev_info(&pf->pdev->dev,
14267 			 "failed to allocate %d q_vector for VSI %d, ret=%d\n",
14268 			 vsi->num_q_vectors, vsi->seid, ret);
14269 		vsi->num_q_vectors = 0;
14270 		goto vector_setup_out;
14271 	}
14272 
14273 	/* In Legacy mode, we do not have to get any other vector since we
14274 	 * piggyback on the misc/ICR0 for queue interrupts.
14275 	*/
14276 	if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
14277 		return ret;
14278 	if (vsi->num_q_vectors)
14279 		vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
14280 						 vsi->num_q_vectors, vsi->idx);
14281 	if (vsi->base_vector < 0) {
14282 		dev_info(&pf->pdev->dev,
14283 			 "failed to get tracking for %d vectors for VSI %d, err=%d\n",
14284 			 vsi->num_q_vectors, vsi->seid, vsi->base_vector);
14285 		i40e_vsi_free_q_vectors(vsi);
14286 		ret = -ENOENT;
14287 		goto vector_setup_out;
14288 	}
14289 
14290 vector_setup_out:
14291 	return ret;
14292 }
14293 
14294 /**
14295  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
14296  * @vsi: pointer to the vsi.
14297  *
14298  * This re-allocates a vsi's queue resources.
14299  *
14300  * Returns pointer to the successfully allocated and configured VSI sw struct
14301  * on success, otherwise returns NULL on failure.
14302  **/
14303 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
14304 {
14305 	struct i40e_vsi *main_vsi;
14306 	u16 alloc_queue_pairs;
14307 	struct i40e_pf *pf;
14308 	int ret;
14309 
14310 	if (!vsi)
14311 		return NULL;
14312 
14313 	pf = vsi->back;
14314 
14315 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
14316 	i40e_vsi_clear_rings(vsi);
14317 
14318 	i40e_vsi_free_arrays(vsi, false);
14319 	i40e_set_num_rings_in_vsi(vsi);
14320 	ret = i40e_vsi_alloc_arrays(vsi, false);
14321 	if (ret)
14322 		goto err_vsi;
14323 
14324 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14325 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14326 
14327 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14328 	if (ret < 0) {
14329 		dev_info(&pf->pdev->dev,
14330 			 "failed to get tracking for %d queues for VSI %d err %d\n",
14331 			 alloc_queue_pairs, vsi->seid, ret);
14332 		goto err_vsi;
14333 	}
14334 	vsi->base_queue = ret;
14335 
14336 	/* Update the FW view of the VSI. Force a reset of TC and queue
14337 	 * layout configurations.
14338 	 */
14339 	main_vsi = i40e_pf_get_main_vsi(pf);
14340 	main_vsi->seid = pf->main_vsi_seid;
14341 	i40e_vsi_reconfig_tc(main_vsi);
14342 
14343 	if (vsi->type == I40E_VSI_MAIN)
14344 		i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
14345 
14346 	/* assign it some queues */
14347 	ret = i40e_alloc_rings(vsi);
14348 	if (ret)
14349 		goto err_rings;
14350 
14351 	/* map all of the rings to the q_vectors */
14352 	i40e_vsi_map_rings_to_vectors(vsi);
14353 	return vsi;
14354 
14355 err_rings:
14356 	i40e_vsi_free_q_vectors(vsi);
14357 	if (vsi->netdev_registered) {
14358 		vsi->netdev_registered = false;
14359 		unregister_netdev(vsi->netdev);
14360 		free_netdev(vsi->netdev);
14361 		vsi->netdev = NULL;
14362 	}
14363 	if (vsi->type == I40E_VSI_MAIN)
14364 		i40e_devlink_destroy_port(pf);
14365 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14366 err_vsi:
14367 	i40e_vsi_clear(vsi);
14368 	return NULL;
14369 }
14370 
14371 /**
14372  * i40e_vsi_setup - Set up a VSI by a given type
14373  * @pf: board private structure
14374  * @type: VSI type
14375  * @uplink_seid: the switch element to link to
14376  * @param1: usage depends upon VSI type. For VF types, indicates VF id
14377  *
14378  * This allocates the sw VSI structure and its queue resources, then add a VSI
14379  * to the identified VEB.
14380  *
14381  * Returns pointer to the successfully allocated and configure VSI sw struct on
14382  * success, otherwise returns NULL on failure.
14383  **/
14384 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
14385 				u16 uplink_seid, u32 param1)
14386 {
14387 	struct i40e_vsi *vsi = NULL;
14388 	struct i40e_veb *veb = NULL;
14389 	u16 alloc_queue_pairs;
14390 	int v_idx;
14391 	int ret;
14392 
14393 	/* The requested uplink_seid must be either
14394 	 *     - the PF's port seid
14395 	 *              no VEB is needed because this is the PF
14396 	 *              or this is a Flow Director special case VSI
14397 	 *     - seid of an existing VEB
14398 	 *     - seid of a VSI that owns an existing VEB
14399 	 *     - seid of a VSI that doesn't own a VEB
14400 	 *              a new VEB is created and the VSI becomes the owner
14401 	 *     - seid of the PF VSI, which is what creates the first VEB
14402 	 *              this is a special case of the previous
14403 	 *
14404 	 * Find which uplink_seid we were given and create a new VEB if needed
14405 	 */
14406 	veb = i40e_pf_get_veb_by_seid(pf, uplink_seid);
14407 	if (!veb && uplink_seid != pf->mac_seid) {
14408 		vsi = i40e_pf_get_vsi_by_seid(pf, uplink_seid);
14409 		if (!vsi) {
14410 			dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
14411 				 uplink_seid);
14412 			return NULL;
14413 		}
14414 
14415 		if (vsi->uplink_seid == pf->mac_seid)
14416 			veb = i40e_veb_setup(pf, pf->mac_seid, vsi->seid,
14417 					     vsi->tc_config.enabled_tc);
14418 		else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14419 			veb = i40e_veb_setup(pf, vsi->uplink_seid, vsi->seid,
14420 					     vsi->tc_config.enabled_tc);
14421 		if (veb) {
14422 			if (vsi->type != I40E_VSI_MAIN) {
14423 				dev_info(&vsi->back->pdev->dev,
14424 					 "New VSI creation error, uplink seid of LAN VSI expected.\n");
14425 				return NULL;
14426 			}
14427 			/* We come up by default in VEPA mode if SRIOV is not
14428 			 * already enabled, in which case we can't force VEPA
14429 			 * mode.
14430 			 */
14431 			if (!test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
14432 				veb->bridge_mode = BRIDGE_MODE_VEPA;
14433 				clear_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
14434 			}
14435 			i40e_config_bridge_mode(veb);
14436 		}
14437 		veb = i40e_pf_get_veb_by_seid(pf, vsi->uplink_seid);
14438 		if (!veb) {
14439 			dev_info(&pf->pdev->dev, "couldn't add VEB\n");
14440 			return NULL;
14441 		}
14442 
14443 		vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14444 		uplink_seid = veb->seid;
14445 	}
14446 
14447 	/* get vsi sw struct */
14448 	v_idx = i40e_vsi_mem_alloc(pf, type);
14449 	if (v_idx < 0)
14450 		goto err_alloc;
14451 	vsi = pf->vsi[v_idx];
14452 	if (!vsi)
14453 		goto err_alloc;
14454 	vsi->type = type;
14455 	vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
14456 
14457 	if (type == I40E_VSI_MAIN)
14458 		pf->lan_vsi = v_idx;
14459 	else if (type == I40E_VSI_SRIOV)
14460 		vsi->vf_id = param1;
14461 	/* assign it some queues */
14462 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14463 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14464 
14465 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14466 	if (ret < 0) {
14467 		dev_info(&pf->pdev->dev,
14468 			 "failed to get tracking for %d queues for VSI %d err=%d\n",
14469 			 alloc_queue_pairs, vsi->seid, ret);
14470 		goto err_vsi;
14471 	}
14472 	vsi->base_queue = ret;
14473 
14474 	/* get a VSI from the hardware */
14475 	vsi->uplink_seid = uplink_seid;
14476 	ret = i40e_add_vsi(vsi);
14477 	if (ret)
14478 		goto err_vsi;
14479 
14480 	switch (vsi->type) {
14481 	/* setup the netdev if needed */
14482 	case I40E_VSI_MAIN:
14483 	case I40E_VSI_VMDQ2:
14484 		ret = i40e_config_netdev(vsi);
14485 		if (ret)
14486 			goto err_netdev;
14487 		ret = i40e_netif_set_realnum_tx_rx_queues(vsi);
14488 		if (ret)
14489 			goto err_netdev;
14490 		if (vsi->type == I40E_VSI_MAIN) {
14491 			ret = i40e_devlink_create_port(pf);
14492 			if (ret)
14493 				goto err_netdev;
14494 			SET_NETDEV_DEVLINK_PORT(vsi->netdev, &pf->devlink_port);
14495 		}
14496 		ret = register_netdev(vsi->netdev);
14497 		if (ret)
14498 			goto err_dl_port;
14499 		vsi->netdev_registered = true;
14500 		netif_carrier_off(vsi->netdev);
14501 #ifdef CONFIG_I40E_DCB
14502 		/* Setup DCB netlink interface */
14503 		i40e_dcbnl_setup(vsi);
14504 #endif /* CONFIG_I40E_DCB */
14505 		fallthrough;
14506 	case I40E_VSI_FDIR:
14507 		/* set up vectors and rings if needed */
14508 		ret = i40e_vsi_setup_vectors(vsi);
14509 		if (ret)
14510 			goto err_msix;
14511 
14512 		ret = i40e_alloc_rings(vsi);
14513 		if (ret)
14514 			goto err_rings;
14515 
14516 		/* map all of the rings to the q_vectors */
14517 		i40e_vsi_map_rings_to_vectors(vsi);
14518 
14519 		i40e_vsi_reset_stats(vsi);
14520 		break;
14521 	default:
14522 		/* no netdev or rings for the other VSI types */
14523 		break;
14524 	}
14525 
14526 	if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps) &&
14527 	    vsi->type == I40E_VSI_VMDQ2) {
14528 		ret = i40e_vsi_config_rss(vsi);
14529 		if (ret)
14530 			goto err_config;
14531 	}
14532 	return vsi;
14533 
14534 err_config:
14535 	i40e_vsi_clear_rings(vsi);
14536 err_rings:
14537 	i40e_vsi_free_q_vectors(vsi);
14538 err_msix:
14539 	if (vsi->netdev_registered) {
14540 		vsi->netdev_registered = false;
14541 		unregister_netdev(vsi->netdev);
14542 		free_netdev(vsi->netdev);
14543 		vsi->netdev = NULL;
14544 	}
14545 err_dl_port:
14546 	if (vsi->type == I40E_VSI_MAIN)
14547 		i40e_devlink_destroy_port(pf);
14548 err_netdev:
14549 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14550 err_vsi:
14551 	i40e_vsi_clear(vsi);
14552 err_alloc:
14553 	return NULL;
14554 }
14555 
14556 /**
14557  * i40e_veb_get_bw_info - Query VEB BW information
14558  * @veb: the veb to query
14559  *
14560  * Query the Tx scheduler BW configuration data for given VEB
14561  **/
14562 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
14563 {
14564 	struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
14565 	struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
14566 	struct i40e_pf *pf = veb->pf;
14567 	struct i40e_hw *hw = &pf->hw;
14568 	u32 tc_bw_max;
14569 	int ret = 0;
14570 	int i;
14571 
14572 	ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
14573 						  &bw_data, NULL);
14574 	if (ret) {
14575 		dev_info(&pf->pdev->dev,
14576 			 "query veb bw 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 	ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
14583 						   &ets_data, NULL);
14584 	if (ret) {
14585 		dev_info(&pf->pdev->dev,
14586 			 "query veb bw ets config failed, err %pe aq_err %s\n",
14587 			 ERR_PTR(ret),
14588 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14589 		goto out;
14590 	}
14591 
14592 	veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
14593 	veb->bw_max_quanta = ets_data.tc_bw_max;
14594 	veb->is_abs_credits = bw_data.absolute_credits_enable;
14595 	veb->enabled_tc = ets_data.tc_valid_bits;
14596 	tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
14597 		    (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
14598 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
14599 		veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
14600 		veb->bw_tc_limit_credits[i] =
14601 					le16_to_cpu(bw_data.tc_bw_limits[i]);
14602 		veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
14603 	}
14604 
14605 out:
14606 	return ret;
14607 }
14608 
14609 /**
14610  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
14611  * @pf: board private structure
14612  *
14613  * On error: returns error code (negative)
14614  * On success: returns vsi index in PF (positive)
14615  **/
14616 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
14617 {
14618 	int ret = -ENOENT;
14619 	struct i40e_veb *veb;
14620 	int i;
14621 
14622 	/* Need to protect the allocation of switch elements at the PF level */
14623 	mutex_lock(&pf->switch_mutex);
14624 
14625 	/* VEB list may be fragmented if VEB creation/destruction has
14626 	 * been happening.  We can afford to do a quick scan to look
14627 	 * for any free slots in the list.
14628 	 *
14629 	 * find next empty veb slot, looping back around if necessary
14630 	 */
14631 	i = 0;
14632 	while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
14633 		i++;
14634 	if (i >= I40E_MAX_VEB) {
14635 		ret = -ENOMEM;
14636 		goto err_alloc_veb;  /* out of VEB slots! */
14637 	}
14638 
14639 	veb = kzalloc(sizeof(*veb), GFP_KERNEL);
14640 	if (!veb) {
14641 		ret = -ENOMEM;
14642 		goto err_alloc_veb;
14643 	}
14644 	veb->pf = pf;
14645 	veb->idx = i;
14646 	veb->enabled_tc = 1;
14647 
14648 	pf->veb[i] = veb;
14649 	ret = i;
14650 err_alloc_veb:
14651 	mutex_unlock(&pf->switch_mutex);
14652 	return ret;
14653 }
14654 
14655 /**
14656  * i40e_switch_branch_release - Delete a branch of the switch tree
14657  * @branch: where to start deleting
14658  *
14659  * This uses recursion to find the tips of the branch to be
14660  * removed, deleting until we get back to and can delete this VEB.
14661  **/
14662 static void i40e_switch_branch_release(struct i40e_veb *branch)
14663 {
14664 	struct i40e_pf *pf = branch->pf;
14665 	u16 branch_seid = branch->seid;
14666 	u16 veb_idx = branch->idx;
14667 	struct i40e_vsi *vsi;
14668 	struct i40e_veb *veb;
14669 	int i;
14670 
14671 	/* release any VEBs on this VEB - RECURSION */
14672 	i40e_pf_for_each_veb(pf, i, veb)
14673 		if (veb->uplink_seid == branch->seid)
14674 			i40e_switch_branch_release(veb);
14675 
14676 	/* Release the VSIs on this VEB, but not the owner VSI.
14677 	 *
14678 	 * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
14679 	 *       the VEB itself, so don't use (*branch) after this loop.
14680 	 */
14681 	i40e_pf_for_each_vsi(pf, i, vsi)
14682 		if (vsi->uplink_seid == branch_seid &&
14683 		    (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14684 			i40e_vsi_release(vsi);
14685 
14686 	/* There's one corner case where the VEB might not have been
14687 	 * removed, so double check it here and remove it if needed.
14688 	 * This case happens if the veb was created from the debugfs
14689 	 * commands and no VSIs were added to it.
14690 	 */
14691 	if (pf->veb[veb_idx])
14692 		i40e_veb_release(pf->veb[veb_idx]);
14693 }
14694 
14695 /**
14696  * i40e_veb_clear - remove veb struct
14697  * @veb: the veb to remove
14698  **/
14699 static void i40e_veb_clear(struct i40e_veb *veb)
14700 {
14701 	if (!veb)
14702 		return;
14703 
14704 	if (veb->pf) {
14705 		struct i40e_pf *pf = veb->pf;
14706 
14707 		mutex_lock(&pf->switch_mutex);
14708 		if (pf->veb[veb->idx] == veb)
14709 			pf->veb[veb->idx] = NULL;
14710 		mutex_unlock(&pf->switch_mutex);
14711 	}
14712 
14713 	kfree(veb);
14714 }
14715 
14716 /**
14717  * i40e_veb_release - Delete a VEB and free its resources
14718  * @veb: the VEB being removed
14719  **/
14720 void i40e_veb_release(struct i40e_veb *veb)
14721 {
14722 	struct i40e_vsi *vsi, *vsi_it;
14723 	struct i40e_pf *pf;
14724 	int i, n = 0;
14725 
14726 	pf = veb->pf;
14727 
14728 	/* find the remaining VSI and check for extras */
14729 	i40e_pf_for_each_vsi(pf, i, vsi_it)
14730 		if (vsi_it->uplink_seid == veb->seid) {
14731 			if (vsi_it->flags & I40E_VSI_FLAG_VEB_OWNER)
14732 				vsi = vsi_it;
14733 			n++;
14734 		}
14735 
14736 	/* Floating VEB has to be empty and regular one must have
14737 	 * single owner VSI.
14738 	 */
14739 	if ((veb->uplink_seid && n != 1) || (!veb->uplink_seid && n != 0)) {
14740 		dev_info(&pf->pdev->dev,
14741 			 "can't remove VEB %d with %d VSIs left\n",
14742 			 veb->seid, n);
14743 		return;
14744 	}
14745 
14746 	/* For regular VEB move the owner VSI to uplink port */
14747 	if (veb->uplink_seid) {
14748 		vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
14749 		vsi->uplink_seid = veb->uplink_seid;
14750 		vsi->veb_idx = I40E_NO_VEB;
14751 	}
14752 
14753 	i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14754 	i40e_veb_clear(veb);
14755 }
14756 
14757 /**
14758  * i40e_add_veb - create the VEB in the switch
14759  * @veb: the VEB to be instantiated
14760  * @vsi: the controlling VSI
14761  **/
14762 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
14763 {
14764 	struct i40e_pf *pf = veb->pf;
14765 	bool enable_stats = !!test_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags);
14766 	int ret;
14767 
14768 	ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi ? vsi->seid : 0,
14769 			      veb->enabled_tc, vsi ? false : true,
14770 			      &veb->seid, enable_stats, NULL);
14771 
14772 	/* get a VEB from the hardware */
14773 	if (ret) {
14774 		dev_info(&pf->pdev->dev,
14775 			 "couldn't add VEB, err %pe aq_err %s\n",
14776 			 ERR_PTR(ret),
14777 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14778 		return -EPERM;
14779 	}
14780 
14781 	/* get statistics counter */
14782 	ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
14783 					 &veb->stats_idx, NULL, NULL, NULL);
14784 	if (ret) {
14785 		dev_info(&pf->pdev->dev,
14786 			 "couldn't get VEB statistics idx, err %pe aq_err %s\n",
14787 			 ERR_PTR(ret),
14788 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14789 		return -EPERM;
14790 	}
14791 	ret = i40e_veb_get_bw_info(veb);
14792 	if (ret) {
14793 		dev_info(&pf->pdev->dev,
14794 			 "couldn't get VEB bw info, err %pe aq_err %s\n",
14795 			 ERR_PTR(ret),
14796 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14797 		i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14798 		return -ENOENT;
14799 	}
14800 
14801 	if (vsi) {
14802 		vsi->uplink_seid = veb->seid;
14803 		vsi->veb_idx = veb->idx;
14804 		vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14805 	}
14806 
14807 	return 0;
14808 }
14809 
14810 /**
14811  * i40e_veb_setup - Set up a VEB
14812  * @pf: board private structure
14813  * @uplink_seid: the switch element to link to
14814  * @vsi_seid: the initial VSI seid
14815  * @enabled_tc: Enabled TC bit-map
14816  *
14817  * This allocates the sw VEB structure and links it into the switch
14818  * It is possible and legal for this to be a duplicate of an already
14819  * existing VEB.  It is also possible for both uplink and vsi seids
14820  * to be zero, in order to create a floating VEB.
14821  *
14822  * Returns pointer to the successfully allocated VEB sw struct on
14823  * success, otherwise returns NULL on failure.
14824  **/
14825 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 uplink_seid,
14826 				u16 vsi_seid, u8 enabled_tc)
14827 {
14828 	struct i40e_vsi *vsi = NULL;
14829 	struct i40e_veb *veb;
14830 	int veb_idx;
14831 	int ret;
14832 
14833 	/* if one seid is 0, the other must be 0 to create a floating relay */
14834 	if ((uplink_seid == 0 || vsi_seid == 0) &&
14835 	    (uplink_seid + vsi_seid != 0)) {
14836 		dev_info(&pf->pdev->dev,
14837 			 "one, not both seid's are 0: uplink=%d vsi=%d\n",
14838 			 uplink_seid, vsi_seid);
14839 		return NULL;
14840 	}
14841 
14842 	/* make sure there is such a vsi and uplink */
14843 	if (vsi_seid) {
14844 		vsi = i40e_pf_get_vsi_by_seid(pf, vsi_seid);
14845 		if (!vsi) {
14846 			dev_err(&pf->pdev->dev, "vsi seid %d not found\n",
14847 				vsi_seid);
14848 			return NULL;
14849 		}
14850 	}
14851 
14852 	/* get veb sw struct */
14853 	veb_idx = i40e_veb_mem_alloc(pf);
14854 	if (veb_idx < 0)
14855 		goto err_alloc;
14856 	veb = pf->veb[veb_idx];
14857 	veb->uplink_seid = uplink_seid;
14858 	veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14859 
14860 	/* create the VEB in the switch */
14861 	ret = i40e_add_veb(veb, vsi);
14862 	if (ret)
14863 		goto err_veb;
14864 
14865 	if (vsi && vsi->idx == pf->lan_vsi)
14866 		pf->lan_veb = veb->idx;
14867 
14868 	return veb;
14869 
14870 err_veb:
14871 	i40e_veb_clear(veb);
14872 err_alloc:
14873 	return NULL;
14874 }
14875 
14876 /**
14877  * i40e_setup_pf_switch_element - set PF vars based on switch type
14878  * @pf: board private structure
14879  * @ele: element we are building info from
14880  * @num_reported: total number of elements
14881  * @printconfig: should we print the contents
14882  *
14883  * helper function to assist in extracting a few useful SEID values.
14884  **/
14885 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14886 				struct i40e_aqc_switch_config_element_resp *ele,
14887 				u16 num_reported, bool printconfig)
14888 {
14889 	u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14890 	u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14891 	u8 element_type = ele->element_type;
14892 	u16 seid = le16_to_cpu(ele->seid);
14893 	struct i40e_veb *veb;
14894 
14895 	if (printconfig)
14896 		dev_info(&pf->pdev->dev,
14897 			 "type=%d seid=%d uplink=%d downlink=%d\n",
14898 			 element_type, seid, uplink_seid, downlink_seid);
14899 
14900 	switch (element_type) {
14901 	case I40E_SWITCH_ELEMENT_TYPE_MAC:
14902 		pf->mac_seid = seid;
14903 		break;
14904 	case I40E_SWITCH_ELEMENT_TYPE_VEB:
14905 		/* Main VEB? */
14906 		if (uplink_seid != pf->mac_seid)
14907 			break;
14908 		veb = i40e_pf_get_main_veb(pf);
14909 		if (!veb) {
14910 			int v;
14911 
14912 			/* find existing or else empty VEB */
14913 			veb = i40e_pf_get_veb_by_seid(pf, seid);
14914 			if (veb) {
14915 				pf->lan_veb = veb->idx;
14916 			} else {
14917 				v = i40e_veb_mem_alloc(pf);
14918 				if (v < 0)
14919 					break;
14920 				pf->lan_veb = v;
14921 			}
14922 		}
14923 
14924 		/* Try to get again main VEB as pf->lan_veb may have changed */
14925 		veb = i40e_pf_get_main_veb(pf);
14926 		if (!veb)
14927 			break;
14928 
14929 		veb->seid = seid;
14930 		veb->uplink_seid = pf->mac_seid;
14931 		veb->pf = pf;
14932 		break;
14933 	case I40E_SWITCH_ELEMENT_TYPE_VSI:
14934 		if (num_reported != 1)
14935 			break;
14936 		/* This is immediately after a reset so we can assume this is
14937 		 * the PF's VSI
14938 		 */
14939 		pf->mac_seid = uplink_seid;
14940 		pf->main_vsi_seid = seid;
14941 		if (printconfig)
14942 			dev_info(&pf->pdev->dev,
14943 				 "pf_seid=%d main_vsi_seid=%d\n",
14944 				 downlink_seid, pf->main_vsi_seid);
14945 		break;
14946 	case I40E_SWITCH_ELEMENT_TYPE_PF:
14947 	case I40E_SWITCH_ELEMENT_TYPE_VF:
14948 	case I40E_SWITCH_ELEMENT_TYPE_EMP:
14949 	case I40E_SWITCH_ELEMENT_TYPE_BMC:
14950 	case I40E_SWITCH_ELEMENT_TYPE_PE:
14951 	case I40E_SWITCH_ELEMENT_TYPE_PA:
14952 		/* ignore these for now */
14953 		break;
14954 	default:
14955 		dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
14956 			 element_type, seid);
14957 		break;
14958 	}
14959 }
14960 
14961 /**
14962  * i40e_fetch_switch_configuration - Get switch config from firmware
14963  * @pf: board private structure
14964  * @printconfig: should we print the contents
14965  *
14966  * Get the current switch configuration from the device and
14967  * extract a few useful SEID values.
14968  **/
14969 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
14970 {
14971 	struct i40e_aqc_get_switch_config_resp *sw_config;
14972 	u16 next_seid = 0;
14973 	int ret = 0;
14974 	u8 *aq_buf;
14975 	int i;
14976 
14977 	aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
14978 	if (!aq_buf)
14979 		return -ENOMEM;
14980 
14981 	sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
14982 	do {
14983 		u16 num_reported, num_total;
14984 
14985 		ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
14986 						I40E_AQ_LARGE_BUF,
14987 						&next_seid, NULL);
14988 		if (ret) {
14989 			dev_info(&pf->pdev->dev,
14990 				 "get switch config failed err %d aq_err %s\n",
14991 				 ret,
14992 				 i40e_aq_str(&pf->hw,
14993 					     pf->hw.aq.asq_last_status));
14994 			kfree(aq_buf);
14995 			return -ENOENT;
14996 		}
14997 
14998 		num_reported = le16_to_cpu(sw_config->header.num_reported);
14999 		num_total = le16_to_cpu(sw_config->header.num_total);
15000 
15001 		if (printconfig)
15002 			dev_info(&pf->pdev->dev,
15003 				 "header: %d reported %d total\n",
15004 				 num_reported, num_total);
15005 
15006 		for (i = 0; i < num_reported; i++) {
15007 			struct i40e_aqc_switch_config_element_resp *ele =
15008 				&sw_config->element[i];
15009 
15010 			i40e_setup_pf_switch_element(pf, ele, num_reported,
15011 						     printconfig);
15012 		}
15013 	} while (next_seid != 0);
15014 
15015 	kfree(aq_buf);
15016 	return ret;
15017 }
15018 
15019 /**
15020  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
15021  * @pf: board private structure
15022  * @reinit: if the Main VSI needs to re-initialized.
15023  * @lock_acquired: indicates whether or not the lock has been acquired
15024  *
15025  * Returns 0 on success, negative value on failure
15026  **/
15027 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired)
15028 {
15029 	struct i40e_vsi *main_vsi;
15030 	u16 flags = 0;
15031 	int ret;
15032 
15033 	/* find out what's out there already */
15034 	ret = i40e_fetch_switch_configuration(pf, false);
15035 	if (ret) {
15036 		dev_info(&pf->pdev->dev,
15037 			 "couldn't fetch switch config, err %pe aq_err %s\n",
15038 			 ERR_PTR(ret),
15039 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15040 		return ret;
15041 	}
15042 	i40e_pf_reset_stats(pf);
15043 
15044 	/* set the switch config bit for the whole device to
15045 	 * support limited promisc or true promisc
15046 	 * when user requests promisc. The default is limited
15047 	 * promisc.
15048 	*/
15049 
15050 	if ((pf->hw.pf_id == 0) &&
15051 	    !test_bit(I40E_FLAG_TRUE_PROMISC_ENA, pf->flags)) {
15052 		flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15053 		pf->last_sw_conf_flags = flags;
15054 	}
15055 
15056 	if (pf->hw.pf_id == 0) {
15057 		u16 valid_flags;
15058 
15059 		valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15060 		ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
15061 						NULL);
15062 		if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
15063 			dev_info(&pf->pdev->dev,
15064 				 "couldn't set switch config bits, err %pe aq_err %s\n",
15065 				 ERR_PTR(ret),
15066 				 i40e_aq_str(&pf->hw,
15067 					     pf->hw.aq.asq_last_status));
15068 			/* not a fatal problem, just keep going */
15069 		}
15070 		pf->last_sw_conf_valid_flags = valid_flags;
15071 	}
15072 
15073 	/* first time setup */
15074 	main_vsi = i40e_pf_get_main_vsi(pf);
15075 	if (!main_vsi || reinit) {
15076 		struct i40e_veb *veb;
15077 		u16 uplink_seid;
15078 
15079 		/* Set up the PF VSI associated with the PF's main VSI
15080 		 * that is already in the HW switch
15081 		 */
15082 		veb = i40e_pf_get_main_veb(pf);
15083 		if (veb)
15084 			uplink_seid = veb->seid;
15085 		else
15086 			uplink_seid = pf->mac_seid;
15087 		if (!main_vsi)
15088 			main_vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN,
15089 						  uplink_seid, 0);
15090 		else if (reinit)
15091 			main_vsi = i40e_vsi_reinit_setup(main_vsi);
15092 		if (!main_vsi) {
15093 			dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
15094 			i40e_cloud_filter_exit(pf);
15095 			i40e_fdir_teardown(pf);
15096 			return -EAGAIN;
15097 		}
15098 	} else {
15099 		/* force a reset of TC and queue layout configurations */
15100 		main_vsi->seid = pf->main_vsi_seid;
15101 		i40e_vsi_reconfig_tc(main_vsi);
15102 	}
15103 	i40e_vlan_stripping_disable(main_vsi);
15104 
15105 	i40e_fdir_sb_setup(pf);
15106 
15107 	/* Setup static PF queue filter control settings */
15108 	ret = i40e_setup_pf_filter_control(pf);
15109 	if (ret) {
15110 		dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
15111 			 ret);
15112 		/* Failure here should not stop continuing other steps */
15113 	}
15114 
15115 	/* enable RSS in the HW, even for only one queue, as the stack can use
15116 	 * the hash
15117 	 */
15118 	if (test_bit(I40E_FLAG_RSS_ENA, pf->flags))
15119 		i40e_pf_config_rss(pf);
15120 
15121 	/* fill in link information and enable LSE reporting */
15122 	i40e_link_event(pf);
15123 
15124 	i40e_ptp_init(pf);
15125 
15126 	if (!lock_acquired)
15127 		rtnl_lock();
15128 
15129 	/* repopulate tunnel port filters */
15130 	udp_tunnel_nic_reset_ntf(main_vsi->netdev);
15131 
15132 	if (!lock_acquired)
15133 		rtnl_unlock();
15134 
15135 	return ret;
15136 }
15137 
15138 /**
15139  * i40e_determine_queue_usage - Work out queue distribution
15140  * @pf: board private structure
15141  **/
15142 static void i40e_determine_queue_usage(struct i40e_pf *pf)
15143 {
15144 	int queues_left;
15145 	int q_max;
15146 
15147 	pf->num_lan_qps = 0;
15148 
15149 	/* Find the max queues to be put into basic use.  We'll always be
15150 	 * using TC0, whether or not DCB is running, and TC0 will get the
15151 	 * big RSS set.
15152 	 */
15153 	queues_left = pf->hw.func_caps.num_tx_qp;
15154 
15155 	if ((queues_left == 1) ||
15156 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
15157 		/* one qp for PF, no queues for anything else */
15158 		queues_left = 0;
15159 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15160 
15161 		/* make sure all the fancies are disabled */
15162 		clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
15163 		clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
15164 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15165 		clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
15166 		clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15167 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15168 		clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
15169 		clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
15170 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15171 	} else if (!test_bit(I40E_FLAG_RSS_ENA, pf->flags) &&
15172 		   !test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
15173 		   !test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
15174 		   !test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags)) {
15175 		/* one qp for PF */
15176 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15177 		queues_left -= pf->num_lan_qps;
15178 
15179 		clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
15180 		clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
15181 		clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15182 		clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
15183 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15184 		clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
15185 		set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15186 	} else {
15187 		/* Not enough queues for all TCs */
15188 		if (test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags) &&
15189 		    queues_left < I40E_MAX_TRAFFIC_CLASS) {
15190 			clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15191 			clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15192 			dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
15193 		}
15194 
15195 		/* limit lan qps to the smaller of qps, cpus or msix */
15196 		q_max = max_t(int, pf->rss_size_max, num_online_cpus());
15197 		q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
15198 		q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
15199 		pf->num_lan_qps = q_max;
15200 
15201 		queues_left -= pf->num_lan_qps;
15202 	}
15203 
15204 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
15205 		if (queues_left > 1) {
15206 			queues_left -= 1; /* save 1 queue for FD */
15207 		} else {
15208 			clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15209 			set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15210 			dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
15211 		}
15212 	}
15213 
15214 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
15215 	    pf->num_vf_qps && pf->num_req_vfs && queues_left) {
15216 		pf->num_req_vfs = min_t(int, pf->num_req_vfs,
15217 					(queues_left / pf->num_vf_qps));
15218 		queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
15219 	}
15220 
15221 	if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags) &&
15222 	    pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
15223 		pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
15224 					  (queues_left / pf->num_vmdq_qps));
15225 		queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
15226 	}
15227 
15228 	pf->queues_left = queues_left;
15229 	dev_dbg(&pf->pdev->dev,
15230 		"qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
15231 		pf->hw.func_caps.num_tx_qp,
15232 		!!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags),
15233 		pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
15234 		pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
15235 		queues_left);
15236 }
15237 
15238 /**
15239  * i40e_setup_pf_filter_control - Setup PF static filter control
15240  * @pf: PF to be setup
15241  *
15242  * i40e_setup_pf_filter_control sets up a PF's initial filter control
15243  * settings. If PE/FCoE are enabled then it will also set the per PF
15244  * based filter sizes required for them. It also enables Flow director,
15245  * ethertype and macvlan type filter settings for the pf.
15246  *
15247  * Returns 0 on success, negative on failure
15248  **/
15249 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
15250 {
15251 	struct i40e_filter_control_settings *settings = &pf->filter_settings;
15252 
15253 	settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
15254 
15255 	/* Flow Director is enabled */
15256 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) ||
15257 	    test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags))
15258 		settings->enable_fdir = true;
15259 
15260 	/* Ethtype and MACVLAN filters enabled for PF */
15261 	settings->enable_ethtype = true;
15262 	settings->enable_macvlan = true;
15263 
15264 	if (i40e_set_filter_control(&pf->hw, settings))
15265 		return -ENOENT;
15266 
15267 	return 0;
15268 }
15269 
15270 #define INFO_STRING_LEN 255
15271 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
15272 static void i40e_print_features(struct i40e_pf *pf)
15273 {
15274 	struct i40e_vsi *main_vsi = i40e_pf_get_main_vsi(pf);
15275 	struct i40e_hw *hw = &pf->hw;
15276 	char *buf;
15277 	int i;
15278 
15279 	buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
15280 	if (!buf)
15281 		return;
15282 
15283 	i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
15284 #ifdef CONFIG_PCI_IOV
15285 	i += scnprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
15286 #endif
15287 	i += scnprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
15288 		       pf->hw.func_caps.num_vsis, main_vsi->num_queue_pairs);
15289 	if (test_bit(I40E_FLAG_RSS_ENA, pf->flags))
15290 		i += scnprintf(&buf[i], REMAIN(i), " RSS");
15291 	if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags))
15292 		i += scnprintf(&buf[i], REMAIN(i), " FD_ATR");
15293 	if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
15294 		i += scnprintf(&buf[i], REMAIN(i), " FD_SB");
15295 		i += scnprintf(&buf[i], REMAIN(i), " NTUPLE");
15296 	}
15297 	if (test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
15298 		i += scnprintf(&buf[i], REMAIN(i), " DCB");
15299 	i += scnprintf(&buf[i], REMAIN(i), " VxLAN");
15300 	i += scnprintf(&buf[i], REMAIN(i), " Geneve");
15301 	if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
15302 		i += scnprintf(&buf[i], REMAIN(i), " PTP");
15303 	if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags))
15304 		i += scnprintf(&buf[i], REMAIN(i), " VEB");
15305 	else
15306 		i += scnprintf(&buf[i], REMAIN(i), " VEPA");
15307 
15308 	dev_info(&pf->pdev->dev, "%s\n", buf);
15309 	kfree(buf);
15310 	WARN_ON(i > INFO_STRING_LEN);
15311 }
15312 
15313 /**
15314  * i40e_get_platform_mac_addr - get platform-specific MAC address
15315  * @pdev: PCI device information struct
15316  * @pf: board private structure
15317  *
15318  * Look up the MAC address for the device. First we'll try
15319  * eth_platform_get_mac_address, which will check Open Firmware, or arch
15320  * specific fallback. Otherwise, we'll default to the stored value in
15321  * firmware.
15322  **/
15323 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
15324 {
15325 	if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
15326 		i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
15327 }
15328 
15329 /**
15330  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
15331  * @fec_cfg: FEC option to set in flags
15332  * @flags: ptr to flags in which we set FEC option
15333  **/
15334 void i40e_set_fec_in_flags(u8 fec_cfg, unsigned long *flags)
15335 {
15336 	if (fec_cfg & I40E_AQ_SET_FEC_AUTO) {
15337 		set_bit(I40E_FLAG_RS_FEC, flags);
15338 		set_bit(I40E_FLAG_BASE_R_FEC, flags);
15339 	}
15340 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
15341 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
15342 		set_bit(I40E_FLAG_RS_FEC, flags);
15343 		clear_bit(I40E_FLAG_BASE_R_FEC, flags);
15344 	}
15345 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
15346 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
15347 		set_bit(I40E_FLAG_BASE_R_FEC, flags);
15348 		clear_bit(I40E_FLAG_RS_FEC, flags);
15349 	}
15350 	if (fec_cfg == 0) {
15351 		clear_bit(I40E_FLAG_RS_FEC, flags);
15352 		clear_bit(I40E_FLAG_BASE_R_FEC, flags);
15353 	}
15354 }
15355 
15356 /**
15357  * i40e_check_recovery_mode - check if we are running transition firmware
15358  * @pf: board private structure
15359  *
15360  * Check registers indicating the firmware runs in recovery mode. Sets the
15361  * appropriate driver state.
15362  *
15363  * Returns true if the recovery mode was detected, false otherwise
15364  **/
15365 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
15366 {
15367 	u32 val = rd32(&pf->hw, I40E_GL_FWSTS);
15368 
15369 	if (val & I40E_GL_FWSTS_FWS1B_MASK) {
15370 		dev_crit(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
15371 		dev_crit(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
15372 		set_bit(__I40E_RECOVERY_MODE, pf->state);
15373 
15374 		return true;
15375 	}
15376 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15377 		dev_info(&pf->pdev->dev, "Please do Power-On Reset to initialize adapter in normal mode with full functionality.\n");
15378 
15379 	return false;
15380 }
15381 
15382 /**
15383  * i40e_pf_loop_reset - perform reset in a loop.
15384  * @pf: board private structure
15385  *
15386  * This function is useful when a NIC is about to enter recovery mode.
15387  * When a NIC's internal data structures are corrupted the NIC's
15388  * firmware is going to enter recovery mode.
15389  * Right after a POR it takes about 7 minutes for firmware to enter
15390  * recovery mode. Until that time a NIC is in some kind of intermediate
15391  * state. After that time period the NIC almost surely enters
15392  * recovery mode. The only way for a driver to detect intermediate
15393  * state is to issue a series of pf-resets and check a return value.
15394  * If a PF reset returns success then the firmware could be in recovery
15395  * mode so the caller of this code needs to check for recovery mode
15396  * if this function returns success. There is a little chance that
15397  * firmware will hang in intermediate state forever.
15398  * Since waiting 7 minutes is quite a lot of time this function waits
15399  * 10 seconds and then gives up by returning an error.
15400  *
15401  * Return 0 on success, negative on failure.
15402  **/
15403 static int i40e_pf_loop_reset(struct i40e_pf *pf)
15404 {
15405 	/* wait max 10 seconds for PF reset to succeed */
15406 	const unsigned long time_end = jiffies + 10 * HZ;
15407 	struct i40e_hw *hw = &pf->hw;
15408 	int ret;
15409 
15410 	ret = i40e_pf_reset(hw);
15411 	while (ret != 0 && time_before(jiffies, time_end)) {
15412 		usleep_range(10000, 20000);
15413 		ret = i40e_pf_reset(hw);
15414 	}
15415 
15416 	if (ret == 0)
15417 		pf->pfr_count++;
15418 	else
15419 		dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
15420 
15421 	return ret;
15422 }
15423 
15424 /**
15425  * i40e_check_fw_empr - check if FW issued unexpected EMP Reset
15426  * @pf: board private structure
15427  *
15428  * Check FW registers to determine if FW issued unexpected EMP Reset.
15429  * Every time when unexpected EMP Reset occurs the FW increments
15430  * a counter of unexpected EMP Resets. When the counter reaches 10
15431  * the FW should enter the Recovery mode
15432  *
15433  * Returns true if FW issued unexpected EMP Reset
15434  **/
15435 static bool i40e_check_fw_empr(struct i40e_pf *pf)
15436 {
15437 	const u32 fw_sts = rd32(&pf->hw, I40E_GL_FWSTS) &
15438 			   I40E_GL_FWSTS_FWS1B_MASK;
15439 	return (fw_sts > I40E_GL_FWSTS_FWS1B_EMPR_0) &&
15440 	       (fw_sts <= I40E_GL_FWSTS_FWS1B_EMPR_10);
15441 }
15442 
15443 /**
15444  * i40e_handle_resets - handle EMP resets and PF resets
15445  * @pf: board private structure
15446  *
15447  * Handle both EMP resets and PF resets and conclude whether there are
15448  * any issues regarding these resets. If there are any issues then
15449  * generate log entry.
15450  *
15451  * Return 0 if NIC is healthy or negative value when there are issues
15452  * with resets
15453  **/
15454 static int i40e_handle_resets(struct i40e_pf *pf)
15455 {
15456 	const int pfr = i40e_pf_loop_reset(pf);
15457 	const bool is_empr = i40e_check_fw_empr(pf);
15458 
15459 	if (is_empr || pfr != 0)
15460 		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");
15461 
15462 	return is_empr ? -EIO : pfr;
15463 }
15464 
15465 /**
15466  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
15467  * @pf: board private structure
15468  * @hw: ptr to the hardware info
15469  *
15470  * This function does a minimal setup of all subsystems needed for running
15471  * recovery mode.
15472  *
15473  * Returns 0 on success, negative on failure
15474  **/
15475 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
15476 {
15477 	struct i40e_vsi *vsi;
15478 	int err;
15479 	int v_idx;
15480 
15481 	pci_set_drvdata(pf->pdev, pf);
15482 	pci_save_state(pf->pdev);
15483 
15484 	/* set up periodic task facility */
15485 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15486 	pf->service_timer_period = HZ;
15487 
15488 	INIT_WORK(&pf->service_task, i40e_service_task);
15489 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15490 
15491 	err = i40e_init_interrupt_scheme(pf);
15492 	if (err)
15493 		goto err_switch_setup;
15494 
15495 	/* The number of VSIs reported by the FW is the minimum guaranteed
15496 	 * to us; HW supports far more and we share the remaining pool with
15497 	 * the other PFs. We allocate space for more than the guarantee with
15498 	 * the understanding that we might not get them all later.
15499 	 */
15500 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15501 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15502 	else
15503 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15504 
15505 	/* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
15506 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15507 			  GFP_KERNEL);
15508 	if (!pf->vsi) {
15509 		err = -ENOMEM;
15510 		goto err_switch_setup;
15511 	}
15512 
15513 	/* We allocate one VSI which is needed as absolute minimum
15514 	 * in order to register the netdev
15515 	 */
15516 	v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
15517 	if (v_idx < 0) {
15518 		err = v_idx;
15519 		goto err_switch_setup;
15520 	}
15521 	pf->lan_vsi = v_idx;
15522 	vsi = pf->vsi[v_idx];
15523 	if (!vsi) {
15524 		err = -EFAULT;
15525 		goto err_switch_setup;
15526 	}
15527 	vsi->alloc_queue_pairs = 1;
15528 	err = i40e_config_netdev(vsi);
15529 	if (err)
15530 		goto err_switch_setup;
15531 	err = register_netdev(vsi->netdev);
15532 	if (err)
15533 		goto err_switch_setup;
15534 	vsi->netdev_registered = true;
15535 	i40e_dbg_pf_init(pf);
15536 
15537 	err = i40e_setup_misc_vector_for_recovery_mode(pf);
15538 	if (err)
15539 		goto err_switch_setup;
15540 
15541 	/* tell the firmware that we're starting */
15542 	i40e_send_version(pf);
15543 
15544 	/* since everything's happy, start the service_task timer */
15545 	mod_timer(&pf->service_timer,
15546 		  round_jiffies(jiffies + pf->service_timer_period));
15547 
15548 	return 0;
15549 
15550 err_switch_setup:
15551 	i40e_reset_interrupt_capability(pf);
15552 	timer_shutdown_sync(&pf->service_timer);
15553 	i40e_shutdown_adminq(hw);
15554 	iounmap(hw->hw_addr);
15555 	pci_release_mem_regions(pf->pdev);
15556 	pci_disable_device(pf->pdev);
15557 	i40e_free_pf(pf);
15558 
15559 	return err;
15560 }
15561 
15562 /**
15563  * i40e_set_subsystem_device_id - set subsystem device id
15564  * @hw: pointer to the hardware info
15565  *
15566  * Set PCI subsystem device id either from a pci_dev structure or
15567  * a specific FW register.
15568  **/
15569 static inline void i40e_set_subsystem_device_id(struct i40e_hw *hw)
15570 {
15571 	struct i40e_pf *pf = i40e_hw_to_pf(hw);
15572 
15573 	hw->subsystem_device_id = pf->pdev->subsystem_device ?
15574 		pf->pdev->subsystem_device :
15575 		(ushort)(rd32(hw, I40E_PFPCI_SUBSYSID) & USHRT_MAX);
15576 }
15577 
15578 /**
15579  * i40e_probe - Device initialization routine
15580  * @pdev: PCI device information struct
15581  * @ent: entry in i40e_pci_tbl
15582  *
15583  * i40e_probe initializes a PF identified by a pci_dev structure.
15584  * The OS initialization, configuring of the PF private structure,
15585  * and a hardware reset occur.
15586  *
15587  * Returns 0 on success, negative on failure
15588  **/
15589 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
15590 {
15591 	struct i40e_aq_get_phy_abilities_resp abilities;
15592 #ifdef CONFIG_I40E_DCB
15593 	enum i40e_get_fw_lldp_status_resp lldp_status;
15594 #endif /* CONFIG_I40E_DCB */
15595 	struct i40e_vsi *vsi;
15596 	struct i40e_pf *pf;
15597 	struct i40e_hw *hw;
15598 	u16 wol_nvm_bits;
15599 	char nvm_ver[32];
15600 	u16 link_status;
15601 #ifdef CONFIG_I40E_DCB
15602 	int status;
15603 #endif /* CONFIG_I40E_DCB */
15604 	int err;
15605 	u32 val;
15606 
15607 	err = pci_enable_device_mem(pdev);
15608 	if (err)
15609 		return err;
15610 
15611 	/* set up for high or low dma */
15612 	err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
15613 	if (err) {
15614 		dev_err(&pdev->dev,
15615 			"DMA configuration failed: 0x%x\n", err);
15616 		goto err_dma;
15617 	}
15618 
15619 	/* set up pci connections */
15620 	err = pci_request_mem_regions(pdev, i40e_driver_name);
15621 	if (err) {
15622 		dev_info(&pdev->dev,
15623 			 "pci_request_selected_regions failed %d\n", err);
15624 		goto err_pci_reg;
15625 	}
15626 
15627 	pci_set_master(pdev);
15628 
15629 	/* Now that we have a PCI connection, we need to do the
15630 	 * low level device setup.  This is primarily setting up
15631 	 * the Admin Queue structures and then querying for the
15632 	 * device's current profile information.
15633 	 */
15634 	pf = i40e_alloc_pf(&pdev->dev);
15635 	if (!pf) {
15636 		err = -ENOMEM;
15637 		goto err_pf_alloc;
15638 	}
15639 	pf->next_vsi = 0;
15640 	pf->pdev = pdev;
15641 	set_bit(__I40E_DOWN, pf->state);
15642 
15643 	hw = &pf->hw;
15644 
15645 	pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
15646 				I40E_MAX_CSR_SPACE);
15647 	/* We believe that the highest register to read is
15648 	 * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
15649 	 * is not less than that before mapping to prevent a
15650 	 * kernel panic.
15651 	 */
15652 	if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
15653 		dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
15654 			pf->ioremap_len);
15655 		err = -ENOMEM;
15656 		goto err_ioremap;
15657 	}
15658 	hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
15659 	if (!hw->hw_addr) {
15660 		err = -EIO;
15661 		dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
15662 			 (unsigned int)pci_resource_start(pdev, 0),
15663 			 pf->ioremap_len, err);
15664 		goto err_ioremap;
15665 	}
15666 	hw->vendor_id = pdev->vendor;
15667 	hw->device_id = pdev->device;
15668 	pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
15669 	hw->subsystem_vendor_id = pdev->subsystem_vendor;
15670 	i40e_set_subsystem_device_id(hw);
15671 	hw->bus.device = PCI_SLOT(pdev->devfn);
15672 	hw->bus.func = PCI_FUNC(pdev->devfn);
15673 	hw->bus.bus_id = pdev->bus->number;
15674 
15675 	/* Select something other than the 802.1ad ethertype for the
15676 	 * switch to use internally and drop on ingress.
15677 	 */
15678 	hw->switch_tag = 0xffff;
15679 	hw->first_tag = ETH_P_8021AD;
15680 	hw->second_tag = ETH_P_8021Q;
15681 
15682 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
15683 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
15684 	INIT_LIST_HEAD(&pf->ddp_old_prof);
15685 
15686 	/* set up the locks for the AQ, do this only once in probe
15687 	 * and destroy them only once in remove
15688 	 */
15689 	mutex_init(&hw->aq.asq_mutex);
15690 	mutex_init(&hw->aq.arq_mutex);
15691 
15692 	pf->msg_enable = netif_msg_init(debug,
15693 					NETIF_MSG_DRV |
15694 					NETIF_MSG_PROBE |
15695 					NETIF_MSG_LINK);
15696 	if (debug < -1)
15697 		pf->hw.debug_mask = debug;
15698 
15699 	/* do a special CORER for clearing PXE mode once at init */
15700 	if (hw->revision_id == 0 &&
15701 	    (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
15702 		wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
15703 		i40e_flush(hw);
15704 		msleep(200);
15705 		pf->corer_count++;
15706 
15707 		i40e_clear_pxe_mode(hw);
15708 	}
15709 
15710 	/* Reset here to make sure all is clean and to define PF 'n' */
15711 	i40e_clear_hw(hw);
15712 
15713 	err = i40e_set_mac_type(hw);
15714 	if (err) {
15715 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15716 			 err);
15717 		goto err_pf_reset;
15718 	}
15719 
15720 	err = i40e_handle_resets(pf);
15721 	if (err)
15722 		goto err_pf_reset;
15723 
15724 	i40e_check_recovery_mode(pf);
15725 
15726 	if (is_kdump_kernel()) {
15727 		hw->aq.num_arq_entries = I40E_MIN_ARQ_LEN;
15728 		hw->aq.num_asq_entries = I40E_MIN_ASQ_LEN;
15729 	} else {
15730 		hw->aq.num_arq_entries = I40E_AQ_LEN;
15731 		hw->aq.num_asq_entries = I40E_AQ_LEN;
15732 	}
15733 	hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15734 	hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15735 
15736 	snprintf(pf->int_name, sizeof(pf->int_name) - 1,
15737 		 "%s-%s:misc",
15738 		 dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
15739 
15740 	err = i40e_init_shared_code(hw);
15741 	if (err) {
15742 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15743 			 err);
15744 		goto err_pf_reset;
15745 	}
15746 
15747 	/* set up a default setting for link flow control */
15748 	pf->hw.fc.requested_mode = I40E_FC_NONE;
15749 
15750 	err = i40e_init_adminq(hw);
15751 	if (err) {
15752 		if (err == -EIO)
15753 			dev_info(&pdev->dev,
15754 				 "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",
15755 				 hw->aq.api_maj_ver,
15756 				 hw->aq.api_min_ver,
15757 				 I40E_FW_API_VERSION_MAJOR,
15758 				 I40E_FW_MINOR_VERSION(hw));
15759 		else
15760 			dev_info(&pdev->dev,
15761 				 "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
15762 
15763 		goto err_pf_reset;
15764 	}
15765 	i40e_get_oem_version(hw);
15766 	i40e_get_pba_string(hw);
15767 
15768 	/* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
15769 	i40e_nvm_version_str(hw, nvm_ver, sizeof(nvm_ver));
15770 	dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
15771 		 hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
15772 		 hw->aq.api_maj_ver, hw->aq.api_min_ver, nvm_ver,
15773 		 hw->vendor_id, hw->device_id, hw->subsystem_vendor_id,
15774 		 hw->subsystem_device_id);
15775 
15776 	if (i40e_is_aq_api_ver_ge(hw, I40E_FW_API_VERSION_MAJOR,
15777 				  I40E_FW_MINOR_VERSION(hw) + 1))
15778 		dev_dbg(&pdev->dev,
15779 			"The driver for the device detected a newer version of the NVM image v%u.%u than v%u.%u.\n",
15780 			 hw->aq.api_maj_ver,
15781 			 hw->aq.api_min_ver,
15782 			 I40E_FW_API_VERSION_MAJOR,
15783 			 I40E_FW_MINOR_VERSION(hw));
15784 	else if (i40e_is_aq_api_ver_lt(hw, 1, 4))
15785 		dev_info(&pdev->dev,
15786 			 "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",
15787 			 hw->aq.api_maj_ver,
15788 			 hw->aq.api_min_ver,
15789 			 I40E_FW_API_VERSION_MAJOR,
15790 			 I40E_FW_MINOR_VERSION(hw));
15791 
15792 	i40e_verify_eeprom(pf);
15793 
15794 	/* Rev 0 hardware was never productized */
15795 	if (hw->revision_id < 1)
15796 		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");
15797 
15798 	i40e_clear_pxe_mode(hw);
15799 
15800 	err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
15801 	if (err)
15802 		goto err_adminq_setup;
15803 
15804 	err = i40e_sw_init(pf);
15805 	if (err) {
15806 		dev_info(&pdev->dev, "sw_init failed: %d\n", err);
15807 		goto err_sw_init;
15808 	}
15809 
15810 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15811 		return i40e_init_recovery_mode(pf, hw);
15812 
15813 	err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
15814 				hw->func_caps.num_rx_qp, 0, 0);
15815 	if (err) {
15816 		dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
15817 		goto err_init_lan_hmc;
15818 	}
15819 
15820 	err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
15821 	if (err) {
15822 		dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
15823 		err = -ENOENT;
15824 		goto err_configure_lan_hmc;
15825 	}
15826 
15827 	/* Disable LLDP for NICs that have firmware versions lower than v4.3.
15828 	 * Ignore error return codes because if it was already disabled via
15829 	 * hardware settings this will fail
15830 	 */
15831 	if (test_bit(I40E_HW_CAP_STOP_FW_LLDP, pf->hw.caps)) {
15832 		dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
15833 		i40e_aq_stop_lldp(hw, true, false, NULL);
15834 	}
15835 
15836 	/* allow a platform config to override the HW addr */
15837 	i40e_get_platform_mac_addr(pdev, pf);
15838 
15839 	if (!is_valid_ether_addr(hw->mac.addr)) {
15840 		dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
15841 		err = -EIO;
15842 		goto err_mac_addr;
15843 	}
15844 	dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
15845 	ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
15846 	i40e_get_port_mac_addr(hw, hw->mac.port_addr);
15847 	if (is_valid_ether_addr(hw->mac.port_addr))
15848 		set_bit(I40E_HW_CAP_PORT_ID_VALID, pf->hw.caps);
15849 
15850 	i40e_ptp_alloc_pins(pf);
15851 	pci_set_drvdata(pdev, pf);
15852 	pci_save_state(pdev);
15853 
15854 #ifdef CONFIG_I40E_DCB
15855 	status = i40e_get_fw_lldp_status(&pf->hw, &lldp_status);
15856 	(!status &&
15857 	 lldp_status == I40E_GET_FW_LLDP_STATUS_ENABLED) ?
15858 		(clear_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags)) :
15859 		(set_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags));
15860 	dev_info(&pdev->dev,
15861 		 test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags) ?
15862 			"FW LLDP is disabled\n" :
15863 			"FW LLDP is enabled\n");
15864 
15865 	/* Enable FW to write default DCB config on link-up */
15866 	i40e_aq_set_dcb_parameters(hw, true, NULL);
15867 
15868 	err = i40e_init_pf_dcb(pf);
15869 	if (err) {
15870 		dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
15871 		clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15872 		clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15873 		/* Continue without DCB enabled */
15874 	}
15875 #endif /* CONFIG_I40E_DCB */
15876 
15877 	/* set up periodic task facility */
15878 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15879 	pf->service_timer_period = HZ;
15880 
15881 	INIT_WORK(&pf->service_task, i40e_service_task);
15882 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15883 
15884 	/* NVM bit on means WoL disabled for the port */
15885 	i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15886 	if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15887 		pf->wol_en = false;
15888 	else
15889 		pf->wol_en = true;
15890 	device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15891 
15892 	/* set up the main switch operations */
15893 	i40e_determine_queue_usage(pf);
15894 	err = i40e_init_interrupt_scheme(pf);
15895 	if (err)
15896 		goto err_switch_setup;
15897 
15898 	/* Reduce Tx and Rx pairs for kdump
15899 	 * When MSI-X is enabled, it's not allowed to use more TC queue
15900 	 * pairs than MSI-X vectors (pf->num_lan_msix) exist. Thus
15901 	 * vsi->num_queue_pairs will be equal to pf->num_lan_msix, i.e., 1.
15902 	 */
15903 	if (is_kdump_kernel())
15904 		pf->num_lan_msix = 1;
15905 
15906 	pf->udp_tunnel_nic.set_port = i40e_udp_tunnel_set_port;
15907 	pf->udp_tunnel_nic.unset_port = i40e_udp_tunnel_unset_port;
15908 	pf->udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP;
15909 	pf->udp_tunnel_nic.shared = &pf->udp_tunnel_shared;
15910 	pf->udp_tunnel_nic.tables[0].n_entries = I40E_MAX_PF_UDP_OFFLOAD_PORTS;
15911 	pf->udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
15912 						    UDP_TUNNEL_TYPE_GENEVE;
15913 
15914 	/* The number of VSIs reported by the FW is the minimum guaranteed
15915 	 * to us; HW supports far more and we share the remaining pool with
15916 	 * the other PFs. We allocate space for more than the guarantee with
15917 	 * the understanding that we might not get them all later.
15918 	 */
15919 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15920 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15921 	else
15922 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15923 	if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
15924 		dev_warn(&pf->pdev->dev,
15925 			 "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
15926 			 pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
15927 		pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
15928 	}
15929 
15930 	/* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15931 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15932 			  GFP_KERNEL);
15933 	if (!pf->vsi) {
15934 		err = -ENOMEM;
15935 		goto err_switch_setup;
15936 	}
15937 
15938 #ifdef CONFIG_PCI_IOV
15939 	/* prep for VF support */
15940 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
15941 	    test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
15942 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15943 		if (pci_num_vf(pdev))
15944 			set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
15945 	}
15946 #endif
15947 	err = i40e_setup_pf_switch(pf, false, false);
15948 	if (err) {
15949 		dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
15950 		goto err_vsis;
15951 	}
15952 
15953 	vsi = i40e_pf_get_main_vsi(pf);
15954 	INIT_LIST_HEAD(&vsi->ch_list);
15955 
15956 	/* if FDIR VSI was set up, start it now */
15957 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
15958 	if (vsi)
15959 		i40e_vsi_open(vsi);
15960 
15961 	/* The driver only wants link up/down and module qualification
15962 	 * reports from firmware.  Note the negative logic.
15963 	 */
15964 	err = i40e_aq_set_phy_int_mask(&pf->hw,
15965 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
15966 					 I40E_AQ_EVENT_MEDIA_NA |
15967 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
15968 	if (err)
15969 		dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
15970 			 ERR_PTR(err),
15971 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15972 
15973 	/* Reconfigure hardware for allowing smaller MSS in the case
15974 	 * of TSO, so that we avoid the MDD being fired and causing
15975 	 * a reset in the case of small MSS+TSO.
15976 	 */
15977 	val = rd32(hw, I40E_REG_MSS);
15978 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
15979 		val &= ~I40E_REG_MSS_MIN_MASK;
15980 		val |= I40E_64BYTE_MSS;
15981 		wr32(hw, I40E_REG_MSS, val);
15982 	}
15983 
15984 	if (test_bit(I40E_HW_CAP_RESTART_AUTONEG, pf->hw.caps)) {
15985 		msleep(75);
15986 		err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
15987 		if (err)
15988 			dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
15989 				 ERR_PTR(err),
15990 				 i40e_aq_str(&pf->hw,
15991 					     pf->hw.aq.asq_last_status));
15992 	}
15993 	/* The main driver is (mostly) up and happy. We need to set this state
15994 	 * before setting up the misc vector or we get a race and the vector
15995 	 * ends up disabled forever.
15996 	 */
15997 	clear_bit(__I40E_DOWN, pf->state);
15998 
15999 	/* In case of MSIX we are going to setup the misc vector right here
16000 	 * to handle admin queue events etc. In case of legacy and MSI
16001 	 * the misc functionality and queue processing is combined in
16002 	 * the same vector and that gets setup at open.
16003 	 */
16004 	if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
16005 		err = i40e_setup_misc_vector(pf);
16006 		if (err) {
16007 			dev_info(&pdev->dev,
16008 				 "setup of misc vector failed: %d\n", err);
16009 			i40e_cloud_filter_exit(pf);
16010 			i40e_fdir_teardown(pf);
16011 			goto err_vsis;
16012 		}
16013 	}
16014 
16015 #ifdef CONFIG_PCI_IOV
16016 	/* prep for VF support */
16017 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
16018 	    test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
16019 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
16020 		/* disable link interrupts for VFs */
16021 		val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
16022 		val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
16023 		wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
16024 		i40e_flush(hw);
16025 
16026 		if (pci_num_vf(pdev)) {
16027 			dev_info(&pdev->dev,
16028 				 "Active VFs found, allocating resources.\n");
16029 			err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
16030 			if (err)
16031 				dev_info(&pdev->dev,
16032 					 "Error %d allocating resources for existing VFs\n",
16033 					 err);
16034 		}
16035 	}
16036 #endif /* CONFIG_PCI_IOV */
16037 
16038 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
16039 		pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
16040 						      pf->num_iwarp_msix,
16041 						      I40E_IWARP_IRQ_PILE_ID);
16042 		if (pf->iwarp_base_vector < 0) {
16043 			dev_info(&pdev->dev,
16044 				 "failed to get tracking for %d vectors for IWARP err=%d\n",
16045 				 pf->num_iwarp_msix, pf->iwarp_base_vector);
16046 			clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
16047 		}
16048 	}
16049 
16050 	i40e_dbg_pf_init(pf);
16051 
16052 	/* tell the firmware that we're starting */
16053 	i40e_send_version(pf);
16054 
16055 	/* since everything's happy, start the service_task timer */
16056 	mod_timer(&pf->service_timer,
16057 		  round_jiffies(jiffies + pf->service_timer_period));
16058 
16059 	/* add this PF to client device list and launch a client service task */
16060 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
16061 		err = i40e_lan_add_device(pf);
16062 		if (err)
16063 			dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
16064 				 err);
16065 	}
16066 
16067 #define PCI_SPEED_SIZE 8
16068 #define PCI_WIDTH_SIZE 8
16069 	/* Devices on the IOSF bus do not have this information
16070 	 * and will report PCI Gen 1 x 1 by default so don't bother
16071 	 * checking them.
16072 	 */
16073 	if (!test_bit(I40E_HW_CAP_NO_PCI_LINK_CHECK, pf->hw.caps)) {
16074 		char speed[PCI_SPEED_SIZE] = "Unknown";
16075 		char width[PCI_WIDTH_SIZE] = "Unknown";
16076 
16077 		/* Get the negotiated link width and speed from PCI config
16078 		 * space
16079 		 */
16080 		pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
16081 					  &link_status);
16082 
16083 		i40e_set_pci_config_data(hw, link_status);
16084 
16085 		switch (hw->bus.speed) {
16086 		case i40e_bus_speed_8000:
16087 			strscpy(speed, "8.0", PCI_SPEED_SIZE); break;
16088 		case i40e_bus_speed_5000:
16089 			strscpy(speed, "5.0", PCI_SPEED_SIZE); break;
16090 		case i40e_bus_speed_2500:
16091 			strscpy(speed, "2.5", PCI_SPEED_SIZE); break;
16092 		default:
16093 			break;
16094 		}
16095 		switch (hw->bus.width) {
16096 		case i40e_bus_width_pcie_x8:
16097 			strscpy(width, "8", PCI_WIDTH_SIZE); break;
16098 		case i40e_bus_width_pcie_x4:
16099 			strscpy(width, "4", PCI_WIDTH_SIZE); break;
16100 		case i40e_bus_width_pcie_x2:
16101 			strscpy(width, "2", PCI_WIDTH_SIZE); break;
16102 		case i40e_bus_width_pcie_x1:
16103 			strscpy(width, "1", PCI_WIDTH_SIZE); break;
16104 		default:
16105 			break;
16106 		}
16107 
16108 		dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
16109 			 speed, width);
16110 
16111 		if (hw->bus.width < i40e_bus_width_pcie_x8 ||
16112 		    hw->bus.speed < i40e_bus_speed_8000) {
16113 			dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
16114 			dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
16115 		}
16116 	}
16117 
16118 	/* get the requested speeds from the fw */
16119 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
16120 	if (err)
16121 		dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %pe last_status =  %s\n",
16122 			ERR_PTR(err),
16123 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16124 	pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
16125 
16126 	/* set the FEC config due to the board capabilities */
16127 	i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, pf->flags);
16128 
16129 	/* get the supported phy types from the fw */
16130 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
16131 	if (err)
16132 		dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %pe last_status =  %s\n",
16133 			ERR_PTR(err),
16134 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16135 
16136 	/* make sure the MFS hasn't been set lower than the default */
16137 #define MAX_FRAME_SIZE_DEFAULT 0x2600
16138 	val = FIELD_GET(I40E_PRTGL_SAH_MFS_MASK,
16139 			rd32(&pf->hw, I40E_PRTGL_SAH));
16140 	if (val < MAX_FRAME_SIZE_DEFAULT)
16141 		dev_warn(&pdev->dev, "MFS for port %x (%d) has been set below the default (%d)\n",
16142 			 pf->hw.port, val, MAX_FRAME_SIZE_DEFAULT);
16143 
16144 	/* Add a filter to drop all Flow control frames from any VSI from being
16145 	 * transmitted. By doing so we stop a malicious VF from sending out
16146 	 * PAUSE or PFC frames and potentially controlling traffic for other
16147 	 * PF/VF VSIs.
16148 	 * The FW can still send Flow control frames if enabled.
16149 	 */
16150 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
16151 						       pf->main_vsi_seid);
16152 
16153 	if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
16154 	    (pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
16155 		set_bit(I40E_HW_CAP_PHY_CONTROLS_LEDS, pf->hw.caps);
16156 	if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
16157 		set_bit(I40E_HW_CAP_CRT_RETIMER, pf->hw.caps);
16158 	/* print a string summarizing features */
16159 	i40e_print_features(pf);
16160 
16161 	i40e_devlink_register(pf);
16162 
16163 	return 0;
16164 
16165 	/* Unwind what we've done if something failed in the setup */
16166 err_vsis:
16167 	set_bit(__I40E_DOWN, pf->state);
16168 	i40e_clear_interrupt_scheme(pf);
16169 	kfree(pf->vsi);
16170 err_switch_setup:
16171 	i40e_reset_interrupt_capability(pf);
16172 	timer_shutdown_sync(&pf->service_timer);
16173 err_mac_addr:
16174 err_configure_lan_hmc:
16175 	(void)i40e_shutdown_lan_hmc(hw);
16176 err_init_lan_hmc:
16177 	kfree(pf->qp_pile);
16178 err_sw_init:
16179 err_adminq_setup:
16180 err_pf_reset:
16181 	iounmap(hw->hw_addr);
16182 err_ioremap:
16183 	i40e_free_pf(pf);
16184 err_pf_alloc:
16185 	pci_release_mem_regions(pdev);
16186 err_pci_reg:
16187 err_dma:
16188 	pci_disable_device(pdev);
16189 	return err;
16190 }
16191 
16192 /**
16193  * i40e_remove - Device removal routine
16194  * @pdev: PCI device information struct
16195  *
16196  * i40e_remove is called by the PCI subsystem to alert the driver
16197  * that is should release a PCI device.  This could be caused by a
16198  * Hot-Plug event, or because the driver is going to be removed from
16199  * memory.
16200  **/
16201 static void i40e_remove(struct pci_dev *pdev)
16202 {
16203 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16204 	struct i40e_hw *hw = &pf->hw;
16205 	struct i40e_vsi *vsi;
16206 	struct i40e_veb *veb;
16207 	int ret_code;
16208 	int i;
16209 
16210 	i40e_devlink_unregister(pf);
16211 
16212 	i40e_dbg_pf_exit(pf);
16213 
16214 	i40e_ptp_stop(pf);
16215 
16216 	/* Disable RSS in hw */
16217 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
16218 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
16219 
16220 	/* Grab __I40E_RESET_RECOVERY_PENDING and set __I40E_IN_REMOVE
16221 	 * flags, once they are set, i40e_rebuild should not be called as
16222 	 * i40e_prep_for_reset always returns early.
16223 	 */
16224 	while (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
16225 		usleep_range(1000, 2000);
16226 	set_bit(__I40E_IN_REMOVE, pf->state);
16227 
16228 	if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags)) {
16229 		set_bit(__I40E_VF_RESETS_DISABLED, pf->state);
16230 		i40e_free_vfs(pf);
16231 		clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
16232 	}
16233 	/* no more scheduling of any task */
16234 	set_bit(__I40E_SUSPENDED, pf->state);
16235 	set_bit(__I40E_DOWN, pf->state);
16236 	if (pf->service_timer.function)
16237 		timer_shutdown_sync(&pf->service_timer);
16238 	if (pf->service_task.func)
16239 		cancel_work_sync(&pf->service_task);
16240 
16241 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
16242 		struct i40e_vsi *vsi = pf->vsi[0];
16243 
16244 		/* We know that we have allocated only one vsi for this PF,
16245 		 * it was just for registering netdevice, so the interface
16246 		 * could be visible in the 'ifconfig' output
16247 		 */
16248 		unregister_netdev(vsi->netdev);
16249 		free_netdev(vsi->netdev);
16250 
16251 		goto unmap;
16252 	}
16253 
16254 	/* Client close must be called explicitly here because the timer
16255 	 * has been stopped.
16256 	 */
16257 	i40e_notify_client_of_netdev_close(pf, false);
16258 
16259 	i40e_fdir_teardown(pf);
16260 
16261 	/* If there is a switch structure or any orphans, remove them.
16262 	 * This will leave only the PF's VSI remaining.
16263 	 */
16264 	i40e_pf_for_each_veb(pf, i, veb)
16265 		if (veb->uplink_seid == pf->mac_seid ||
16266 		    veb->uplink_seid == 0)
16267 			i40e_switch_branch_release(veb);
16268 
16269 	/* Now we can shutdown the PF's VSIs, just before we kill
16270 	 * adminq and hmc.
16271 	 */
16272 	i40e_pf_for_each_vsi(pf, i, vsi) {
16273 		i40e_vsi_close(vsi);
16274 		i40e_vsi_release(vsi);
16275 		pf->vsi[i] = NULL;
16276 	}
16277 
16278 	i40e_cloud_filter_exit(pf);
16279 
16280 	/* remove attached clients */
16281 	if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
16282 		ret_code = i40e_lan_del_device(pf);
16283 		if (ret_code)
16284 			dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
16285 				 ret_code);
16286 	}
16287 
16288 	/* shutdown and destroy the HMC */
16289 	if (hw->hmc.hmc_obj) {
16290 		ret_code = i40e_shutdown_lan_hmc(hw);
16291 		if (ret_code)
16292 			dev_warn(&pdev->dev,
16293 				 "Failed to destroy the HMC resources: %d\n",
16294 				 ret_code);
16295 	}
16296 
16297 unmap:
16298 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16299 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16300 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
16301 		free_irq(pf->pdev->irq, pf);
16302 
16303 	/* shutdown the adminq */
16304 	i40e_shutdown_adminq(hw);
16305 
16306 	/* destroy the locks only once, here */
16307 	mutex_destroy(&hw->aq.arq_mutex);
16308 	mutex_destroy(&hw->aq.asq_mutex);
16309 
16310 	/* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
16311 	rtnl_lock();
16312 	i40e_clear_interrupt_scheme(pf);
16313 	i40e_pf_for_each_vsi(pf, i, vsi) {
16314 		if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
16315 			i40e_vsi_clear_rings(vsi);
16316 
16317 		i40e_vsi_clear(vsi);
16318 		pf->vsi[i] = NULL;
16319 	}
16320 	rtnl_unlock();
16321 
16322 	i40e_pf_for_each_veb(pf, i, veb) {
16323 		kfree(veb);
16324 		pf->veb[i] = NULL;
16325 	}
16326 
16327 	kfree(pf->qp_pile);
16328 	kfree(pf->vsi);
16329 
16330 	iounmap(hw->hw_addr);
16331 	i40e_free_pf(pf);
16332 	pci_release_mem_regions(pdev);
16333 
16334 	pci_disable_device(pdev);
16335 }
16336 
16337 /**
16338  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
16339  * using the mac_address_write admin q function
16340  * @pf: pointer to i40e_pf struct
16341  **/
16342 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
16343 {
16344 	struct i40e_vsi *main_vsi = i40e_pf_get_main_vsi(pf);
16345 	struct i40e_hw *hw = &pf->hw;
16346 	u8 mac_addr[6];
16347 	u16 flags = 0;
16348 	int ret;
16349 
16350 	/* Get current MAC address in case it's an LAA */
16351 	if (main_vsi && main_vsi->netdev) {
16352 		ether_addr_copy(mac_addr, main_vsi->netdev->dev_addr);
16353 	} else {
16354 		dev_err(&pf->pdev->dev,
16355 			"Failed to retrieve MAC address; using default\n");
16356 		ether_addr_copy(mac_addr, hw->mac.addr);
16357 	}
16358 
16359 	/* The FW expects the mac address write cmd to first be called with
16360 	 * one of these flags before calling it again with the multicast
16361 	 * enable flags.
16362 	 */
16363 	flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
16364 
16365 	if (hw->func_caps.flex10_enable && hw->partition_id != 1)
16366 		flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
16367 
16368 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16369 	if (ret) {
16370 		dev_err(&pf->pdev->dev,
16371 			"Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
16372 		return;
16373 	}
16374 
16375 	flags = I40E_AQC_MC_MAG_EN
16376 			| I40E_AQC_WOL_PRESERVE_ON_PFR
16377 			| I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
16378 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16379 	if (ret)
16380 		dev_err(&pf->pdev->dev,
16381 			"Failed to enable Multicast Magic Packet wake up\n");
16382 }
16383 
16384 /**
16385  * i40e_io_suspend - suspend all IO operations
16386  * @pf: pointer to i40e_pf struct
16387  *
16388  **/
16389 static int i40e_io_suspend(struct i40e_pf *pf)
16390 {
16391 	struct i40e_hw *hw = &pf->hw;
16392 
16393 	set_bit(__I40E_DOWN, pf->state);
16394 
16395 	/* Ensure service task will not be running */
16396 	del_timer_sync(&pf->service_timer);
16397 	cancel_work_sync(&pf->service_task);
16398 
16399 	/* Client close must be called explicitly here because the timer
16400 	 * has been stopped.
16401 	 */
16402 	i40e_notify_client_of_netdev_close(pf, false);
16403 
16404 	if (test_bit(I40E_HW_CAP_WOL_MC_MAGIC_PKT_WAKE, pf->hw.caps) &&
16405 	    pf->wol_en)
16406 		i40e_enable_mc_magic_wake(pf);
16407 
16408 	/* Since we're going to destroy queues during the
16409 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16410 	 * whole section
16411 	 */
16412 	rtnl_lock();
16413 
16414 	i40e_prep_for_reset(pf);
16415 
16416 	wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16417 	wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16418 
16419 	/* Clear the interrupt scheme and release our IRQs so that the system
16420 	 * can safely hibernate even when there are a large number of CPUs.
16421 	 * Otherwise hibernation might fail when mapping all the vectors back
16422 	 * to CPU0.
16423 	 */
16424 	i40e_clear_interrupt_scheme(pf);
16425 
16426 	rtnl_unlock();
16427 
16428 	return 0;
16429 }
16430 
16431 /**
16432  * i40e_io_resume - resume IO operations
16433  * @pf: pointer to i40e_pf struct
16434  *
16435  **/
16436 static int i40e_io_resume(struct i40e_pf *pf)
16437 {
16438 	struct device *dev = &pf->pdev->dev;
16439 	int err;
16440 
16441 	/* We need to hold the RTNL lock prior to restoring interrupt schemes,
16442 	 * since we're going to be restoring queues
16443 	 */
16444 	rtnl_lock();
16445 
16446 	/* We cleared the interrupt scheme when we suspended, so we need to
16447 	 * restore it now to resume device functionality.
16448 	 */
16449 	err = i40e_restore_interrupt_scheme(pf);
16450 	if (err) {
16451 		dev_err(dev, "Cannot restore interrupt scheme: %d\n",
16452 			err);
16453 	}
16454 
16455 	clear_bit(__I40E_DOWN, pf->state);
16456 	i40e_reset_and_rebuild(pf, false, true);
16457 
16458 	rtnl_unlock();
16459 
16460 	/* Clear suspended state last after everything is recovered */
16461 	clear_bit(__I40E_SUSPENDED, pf->state);
16462 
16463 	/* Restart the service task */
16464 	mod_timer(&pf->service_timer,
16465 		  round_jiffies(jiffies + pf->service_timer_period));
16466 
16467 	return 0;
16468 }
16469 
16470 /**
16471  * i40e_pci_error_detected - warning that something funky happened in PCI land
16472  * @pdev: PCI device information struct
16473  * @error: the type of PCI error
16474  *
16475  * Called to warn that something happened and the error handling steps
16476  * are in progress.  Allows the driver to quiesce things, be ready for
16477  * remediation.
16478  **/
16479 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
16480 						pci_channel_state_t error)
16481 {
16482 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16483 
16484 	dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
16485 
16486 	if (!pf) {
16487 		dev_info(&pdev->dev,
16488 			 "Cannot recover - error happened during device probe\n");
16489 		return PCI_ERS_RESULT_DISCONNECT;
16490 	}
16491 
16492 	/* shutdown all operations */
16493 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16494 		i40e_io_suspend(pf);
16495 
16496 	/* Request a slot reset */
16497 	return PCI_ERS_RESULT_NEED_RESET;
16498 }
16499 
16500 /**
16501  * i40e_pci_error_slot_reset - a PCI slot reset just happened
16502  * @pdev: PCI device information struct
16503  *
16504  * Called to find if the driver can work with the device now that
16505  * the pci slot has been reset.  If a basic connection seems good
16506  * (registers are readable and have sane content) then return a
16507  * happy little PCI_ERS_RESULT_xxx.
16508  **/
16509 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
16510 {
16511 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16512 	pci_ers_result_t result;
16513 	u32 reg;
16514 
16515 	dev_dbg(&pdev->dev, "%s\n", __func__);
16516 	/* enable I/O and memory of the device  */
16517 	if (pci_enable_device(pdev)) {
16518 		dev_info(&pdev->dev,
16519 			 "Cannot re-enable PCI device after reset.\n");
16520 		result = PCI_ERS_RESULT_DISCONNECT;
16521 	} else {
16522 		pci_set_master(pdev);
16523 		pci_restore_state(pdev);
16524 		pci_save_state(pdev);
16525 		pci_wake_from_d3(pdev, false);
16526 
16527 		reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
16528 		if (reg == 0)
16529 			result = PCI_ERS_RESULT_RECOVERED;
16530 		else
16531 			result = PCI_ERS_RESULT_DISCONNECT;
16532 	}
16533 
16534 	return result;
16535 }
16536 
16537 /**
16538  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
16539  * @pdev: PCI device information struct
16540  */
16541 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
16542 {
16543 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16544 
16545 	i40e_prep_for_reset(pf);
16546 }
16547 
16548 /**
16549  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
16550  * @pdev: PCI device information struct
16551  */
16552 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
16553 {
16554 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16555 
16556 	if (test_bit(__I40E_IN_REMOVE, pf->state))
16557 		return;
16558 
16559 	i40e_reset_and_rebuild(pf, false, false);
16560 #ifdef CONFIG_PCI_IOV
16561 	i40e_restore_all_vfs_msi_state(pdev);
16562 #endif /* CONFIG_PCI_IOV */
16563 }
16564 
16565 /**
16566  * i40e_pci_error_resume - restart operations after PCI error recovery
16567  * @pdev: PCI device information struct
16568  *
16569  * Called to allow the driver to bring things back up after PCI error
16570  * and/or reset recovery has finished.
16571  **/
16572 static void i40e_pci_error_resume(struct pci_dev *pdev)
16573 {
16574 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16575 
16576 	dev_dbg(&pdev->dev, "%s\n", __func__);
16577 	if (test_bit(__I40E_SUSPENDED, pf->state))
16578 		return;
16579 
16580 	i40e_io_resume(pf);
16581 }
16582 
16583 /**
16584  * i40e_shutdown - PCI callback for shutting down
16585  * @pdev: PCI device information struct
16586  **/
16587 static void i40e_shutdown(struct pci_dev *pdev)
16588 {
16589 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16590 	struct i40e_hw *hw = &pf->hw;
16591 
16592 	set_bit(__I40E_SUSPENDED, pf->state);
16593 	set_bit(__I40E_DOWN, pf->state);
16594 
16595 	del_timer_sync(&pf->service_timer);
16596 	cancel_work_sync(&pf->service_task);
16597 	i40e_cloud_filter_exit(pf);
16598 	i40e_fdir_teardown(pf);
16599 
16600 	/* Client close must be called explicitly here because the timer
16601 	 * has been stopped.
16602 	 */
16603 	i40e_notify_client_of_netdev_close(pf, false);
16604 
16605 	if (test_bit(I40E_HW_CAP_WOL_MC_MAGIC_PKT_WAKE, pf->hw.caps) &&
16606 	    pf->wol_en)
16607 		i40e_enable_mc_magic_wake(pf);
16608 
16609 	i40e_prep_for_reset(pf);
16610 
16611 	wr32(hw, I40E_PFPM_APM,
16612 	     (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16613 	wr32(hw, I40E_PFPM_WUFC,
16614 	     (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16615 
16616 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16617 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16618 	    !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
16619 		free_irq(pf->pdev->irq, pf);
16620 
16621 	/* Since we're going to destroy queues during the
16622 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16623 	 * whole section
16624 	 */
16625 	rtnl_lock();
16626 	i40e_clear_interrupt_scheme(pf);
16627 	rtnl_unlock();
16628 
16629 	if (system_state == SYSTEM_POWER_OFF) {
16630 		pci_wake_from_d3(pdev, pf->wol_en);
16631 		pci_set_power_state(pdev, PCI_D3hot);
16632 	}
16633 }
16634 
16635 /**
16636  * i40e_suspend - PM callback for moving to D3
16637  * @dev: generic device information structure
16638  **/
16639 static int i40e_suspend(struct device *dev)
16640 {
16641 	struct i40e_pf *pf = dev_get_drvdata(dev);
16642 
16643 	/* If we're already suspended, then there is nothing to do */
16644 	if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
16645 		return 0;
16646 	return i40e_io_suspend(pf);
16647 }
16648 
16649 /**
16650  * i40e_resume - PM callback for waking up from D3
16651  * @dev: generic device information structure
16652  **/
16653 static int i40e_resume(struct device *dev)
16654 {
16655 	struct i40e_pf *pf = dev_get_drvdata(dev);
16656 
16657 	/* If we're not suspended, then there is nothing to do */
16658 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16659 		return 0;
16660 	return i40e_io_resume(pf);
16661 }
16662 
16663 static const struct pci_error_handlers i40e_err_handler = {
16664 	.error_detected = i40e_pci_error_detected,
16665 	.slot_reset = i40e_pci_error_slot_reset,
16666 	.reset_prepare = i40e_pci_error_reset_prepare,
16667 	.reset_done = i40e_pci_error_reset_done,
16668 	.resume = i40e_pci_error_resume,
16669 };
16670 
16671 static DEFINE_SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
16672 
16673 static struct pci_driver i40e_driver = {
16674 	.name     = i40e_driver_name,
16675 	.id_table = i40e_pci_tbl,
16676 	.probe    = i40e_probe,
16677 	.remove   = i40e_remove,
16678 	.driver.pm = pm_sleep_ptr(&i40e_pm_ops),
16679 	.shutdown = i40e_shutdown,
16680 	.err_handler = &i40e_err_handler,
16681 	.sriov_configure = i40e_pci_sriov_configure,
16682 };
16683 
16684 /**
16685  * i40e_init_module - Driver registration routine
16686  *
16687  * i40e_init_module is the first routine called when the driver is
16688  * loaded. All it does is register with the PCI subsystem.
16689  **/
16690 static int __init i40e_init_module(void)
16691 {
16692 	int err;
16693 
16694 	pr_info("%s: %s\n", i40e_driver_name, i40e_driver_string);
16695 	pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
16696 
16697 	/* There is no need to throttle the number of active tasks because
16698 	 * each device limits its own task using a state bit for scheduling
16699 	 * the service task, and the device tasks do not interfere with each
16700 	 * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
16701 	 * since we need to be able to guarantee forward progress even under
16702 	 * memory pressure.
16703 	 */
16704 	i40e_wq = alloc_workqueue("%s", 0, 0, i40e_driver_name);
16705 	if (!i40e_wq) {
16706 		pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
16707 		return -ENOMEM;
16708 	}
16709 
16710 	i40e_dbg_init();
16711 	err = pci_register_driver(&i40e_driver);
16712 	if (err) {
16713 		destroy_workqueue(i40e_wq);
16714 		i40e_dbg_exit();
16715 		return err;
16716 	}
16717 
16718 	return 0;
16719 }
16720 module_init(i40e_init_module);
16721 
16722 /**
16723  * i40e_exit_module - Driver exit cleanup routine
16724  *
16725  * i40e_exit_module is called just before the driver is removed
16726  * from memory.
16727  **/
16728 static void __exit i40e_exit_module(void)
16729 {
16730 	pci_unregister_driver(&i40e_driver);
16731 	destroy_workqueue(i40e_wq);
16732 	ida_destroy(&i40e_client_ida);
16733 	i40e_dbg_exit();
16734 }
16735 module_exit(i40e_exit_module);
16736