1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2013 - 2021 Intel Corporation. */
3 
4 #include <linux/etherdevice.h>
5 #include <linux/of_net.h>
6 #include <linux/pci.h>
7 #include <linux/bpf.h>
8 #include <generated/utsrelease.h>
9 #include <linux/crash_dump.h>
10 
11 /* Local includes */
12 #include "i40e.h"
13 #include "i40e_diag.h"
14 #include "i40e_xsk.h"
15 #include <net/udp_tunnel.h>
16 #include <net/xdp_sock_drv.h>
17 /* All i40e tracepoints are defined by the include below, which
18  * must be included exactly once across the whole kernel with
19  * CREATE_TRACE_POINTS defined
20  */
21 #define CREATE_TRACE_POINTS
22 #include "i40e_trace.h"
23 
24 const char i40e_driver_name[] = "i40e";
25 static const char i40e_driver_string[] =
26 			"Intel(R) Ethernet Connection XL710 Network Driver";
27 
28 static const char i40e_copyright[] = "Copyright (c) 2013 - 2019 Intel Corporation.";
29 
30 /* a bit of forward declarations */
31 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi);
32 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired);
33 static int i40e_add_vsi(struct i40e_vsi *vsi);
34 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi);
35 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired);
36 static int i40e_setup_misc_vector(struct i40e_pf *pf);
37 static void i40e_determine_queue_usage(struct i40e_pf *pf);
38 static int i40e_setup_pf_filter_control(struct i40e_pf *pf);
39 static void i40e_prep_for_reset(struct i40e_pf *pf);
40 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
41 				   bool lock_acquired);
42 static int i40e_reset(struct i40e_pf *pf);
43 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired);
44 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf);
45 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf);
46 static bool i40e_check_recovery_mode(struct i40e_pf *pf);
47 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw);
48 static void i40e_fdir_sb_setup(struct i40e_pf *pf);
49 static int i40e_veb_get_bw_info(struct i40e_veb *veb);
50 static int i40e_get_capabilities(struct i40e_pf *pf,
51 				 enum i40e_admin_queue_opc list_type);
52 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf);
53 
54 /* i40e_pci_tbl - PCI Device ID Table
55  *
56  * Last entry must be all 0s
57  *
58  * { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
59  *   Class, Class Mask, private data (not used) }
60  */
61 static const struct pci_device_id i40e_pci_tbl[] = {
62 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_XL710), 0},
63 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QEMU), 0},
64 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_B), 0},
65 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_C), 0},
66 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_A), 0},
67 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_B), 0},
68 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_C), 0},
69 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_BC), 0},
70 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T), 0},
71 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T4), 0},
72 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_BC), 0},
73 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_SFP), 0},
74 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_B), 0},
75 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_X722), 0},
76 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_X722), 0},
77 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722), 0},
78 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_X722), 0},
79 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_X722), 0},
80 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_I_X722), 0},
81 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722_A), 0},
82 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2), 0},
83 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A), 0},
84 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_X710_N3000), 0},
85 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_XXV710_N3000), 0},
86 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B), 0},
87 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28), 0},
88 	/* required last entry */
89 	{0, }
90 };
91 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
92 
93 #define I40E_MAX_VF_COUNT 128
94 static int debug = -1;
95 module_param(debug, uint, 0);
96 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
97 
98 MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
99 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
100 MODULE_LICENSE("GPL v2");
101 
102 static struct workqueue_struct *i40e_wq;
103 
104 static void netdev_hw_addr_refcnt(struct i40e_mac_filter *f,
105 				  struct net_device *netdev, int delta)
106 {
107 	struct netdev_hw_addr *ha;
108 
109 	if (!f || !netdev)
110 		return;
111 
112 	netdev_for_each_mc_addr(ha, netdev) {
113 		if (ether_addr_equal(ha->addr, f->macaddr)) {
114 			ha->refcount += delta;
115 			if (ha->refcount <= 0)
116 				ha->refcount = 1;
117 			break;
118 		}
119 	}
120 }
121 
122 /**
123  * i40e_allocate_dma_mem_d - OS specific memory alloc for shared code
124  * @hw:   pointer to the HW structure
125  * @mem:  ptr to mem struct to fill out
126  * @size: size of memory requested
127  * @alignment: what to align the allocation to
128  **/
129 int i40e_allocate_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem,
130 			    u64 size, u32 alignment)
131 {
132 	struct i40e_pf *pf = (struct i40e_pf *)hw->back;
133 
134 	mem->size = ALIGN(size, alignment);
135 	mem->va = dma_alloc_coherent(&pf->pdev->dev, mem->size, &mem->pa,
136 				     GFP_KERNEL);
137 	if (!mem->va)
138 		return -ENOMEM;
139 
140 	return 0;
141 }
142 
143 /**
144  * i40e_free_dma_mem_d - OS specific memory free for shared code
145  * @hw:   pointer to the HW structure
146  * @mem:  ptr to mem struct to free
147  **/
148 int i40e_free_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem)
149 {
150 	struct i40e_pf *pf = (struct i40e_pf *)hw->back;
151 
152 	dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
153 	mem->va = NULL;
154 	mem->pa = 0;
155 	mem->size = 0;
156 
157 	return 0;
158 }
159 
160 /**
161  * i40e_allocate_virt_mem_d - OS specific memory alloc for shared code
162  * @hw:   pointer to the HW structure
163  * @mem:  ptr to mem struct to fill out
164  * @size: size of memory requested
165  **/
166 int i40e_allocate_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem,
167 			     u32 size)
168 {
169 	mem->size = size;
170 	mem->va = kzalloc(size, GFP_KERNEL);
171 
172 	if (!mem->va)
173 		return -ENOMEM;
174 
175 	return 0;
176 }
177 
178 /**
179  * i40e_free_virt_mem_d - OS specific memory free for shared code
180  * @hw:   pointer to the HW structure
181  * @mem:  ptr to mem struct to free
182  **/
183 int i40e_free_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem)
184 {
185 	/* it's ok to kfree a NULL pointer */
186 	kfree(mem->va);
187 	mem->va = NULL;
188 	mem->size = 0;
189 
190 	return 0;
191 }
192 
193 /**
194  * i40e_get_lump - find a lump of free generic resource
195  * @pf: board private structure
196  * @pile: the pile of resource to search
197  * @needed: the number of items needed
198  * @id: an owner id to stick on the items assigned
199  *
200  * Returns the base item index of the lump, or negative for error
201  **/
202 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
203 			 u16 needed, u16 id)
204 {
205 	int ret = -ENOMEM;
206 	int i, j;
207 
208 	if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
209 		dev_info(&pf->pdev->dev,
210 			 "param err: pile=%s needed=%d id=0x%04x\n",
211 			 pile ? "<valid>" : "<null>", needed, id);
212 		return -EINVAL;
213 	}
214 
215 	/* Allocate last queue in the pile for FDIR VSI queue
216 	 * so it doesn't fragment the qp_pile
217 	 */
218 	if (pile == pf->qp_pile && pf->vsi[id]->type == I40E_VSI_FDIR) {
219 		if (pile->list[pile->num_entries - 1] & I40E_PILE_VALID_BIT) {
220 			dev_err(&pf->pdev->dev,
221 				"Cannot allocate queue %d for I40E_VSI_FDIR\n",
222 				pile->num_entries - 1);
223 			return -ENOMEM;
224 		}
225 		pile->list[pile->num_entries - 1] = id | I40E_PILE_VALID_BIT;
226 		return pile->num_entries - 1;
227 	}
228 
229 	i = 0;
230 	while (i < pile->num_entries) {
231 		/* skip already allocated entries */
232 		if (pile->list[i] & I40E_PILE_VALID_BIT) {
233 			i++;
234 			continue;
235 		}
236 
237 		/* do we have enough in this lump? */
238 		for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
239 			if (pile->list[i+j] & I40E_PILE_VALID_BIT)
240 				break;
241 		}
242 
243 		if (j == needed) {
244 			/* there was enough, so assign it to the requestor */
245 			for (j = 0; j < needed; j++)
246 				pile->list[i+j] = id | I40E_PILE_VALID_BIT;
247 			ret = i;
248 			break;
249 		}
250 
251 		/* not enough, so skip over it and continue looking */
252 		i += j;
253 	}
254 
255 	return ret;
256 }
257 
258 /**
259  * i40e_put_lump - return a lump of generic resource
260  * @pile: the pile of resource to search
261  * @index: the base item index
262  * @id: the owner id of the items assigned
263  *
264  * Returns the count of items in the lump
265  **/
266 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
267 {
268 	int valid_id = (id | I40E_PILE_VALID_BIT);
269 	int count = 0;
270 	u16 i;
271 
272 	if (!pile || index >= pile->num_entries)
273 		return -EINVAL;
274 
275 	for (i = index;
276 	     i < pile->num_entries && pile->list[i] == valid_id;
277 	     i++) {
278 		pile->list[i] = 0;
279 		count++;
280 	}
281 
282 
283 	return count;
284 }
285 
286 /**
287  * i40e_find_vsi_from_id - searches for the vsi with the given id
288  * @pf: the pf structure to search for the vsi
289  * @id: id of the vsi it is searching for
290  **/
291 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
292 {
293 	int i;
294 
295 	for (i = 0; i < pf->num_alloc_vsi; i++)
296 		if (pf->vsi[i] && (pf->vsi[i]->id == id))
297 			return pf->vsi[i];
298 
299 	return NULL;
300 }
301 
302 /**
303  * i40e_service_event_schedule - Schedule the service task to wake up
304  * @pf: board private structure
305  *
306  * If not already scheduled, this puts the task into the work queue
307  **/
308 void i40e_service_event_schedule(struct i40e_pf *pf)
309 {
310 	if ((!test_bit(__I40E_DOWN, pf->state) &&
311 	     !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) ||
312 	      test_bit(__I40E_RECOVERY_MODE, pf->state))
313 		queue_work(i40e_wq, &pf->service_task);
314 }
315 
316 /**
317  * i40e_tx_timeout - Respond to a Tx Hang
318  * @netdev: network interface device structure
319  * @txqueue: queue number timing out
320  *
321  * If any port has noticed a Tx timeout, it is likely that the whole
322  * device is munged, not just the one netdev port, so go for the full
323  * reset.
324  **/
325 static void i40e_tx_timeout(struct net_device *netdev, unsigned int txqueue)
326 {
327 	struct i40e_netdev_priv *np = netdev_priv(netdev);
328 	struct i40e_vsi *vsi = np->vsi;
329 	struct i40e_pf *pf = vsi->back;
330 	struct i40e_ring *tx_ring = NULL;
331 	unsigned int i;
332 	u32 head, val;
333 
334 	pf->tx_timeout_count++;
335 
336 	/* with txqueue index, find the tx_ring struct */
337 	for (i = 0; i < vsi->num_queue_pairs; i++) {
338 		if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
339 			if (txqueue ==
340 			    vsi->tx_rings[i]->queue_index) {
341 				tx_ring = vsi->tx_rings[i];
342 				break;
343 			}
344 		}
345 	}
346 
347 	if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
348 		pf->tx_timeout_recovery_level = 1;  /* reset after some time */
349 	else if (time_before(jiffies,
350 		      (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
351 		return;   /* don't do any new action before the next timeout */
352 
353 	/* don't kick off another recovery if one is already pending */
354 	if (test_and_set_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state))
355 		return;
356 
357 	if (tx_ring) {
358 		head = i40e_get_head(tx_ring);
359 		/* Read interrupt register */
360 		if (pf->flags & I40E_FLAG_MSIX_ENABLED)
361 			val = rd32(&pf->hw,
362 			     I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
363 						tx_ring->vsi->base_vector - 1));
364 		else
365 			val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
366 
367 		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",
368 			    vsi->seid, txqueue, tx_ring->next_to_clean,
369 			    head, tx_ring->next_to_use,
370 			    readl(tx_ring->tail), val);
371 	}
372 
373 	pf->tx_timeout_last_recovery = jiffies;
374 	netdev_info(netdev, "tx_timeout recovery level %d, txqueue %d\n",
375 		    pf->tx_timeout_recovery_level, txqueue);
376 
377 	switch (pf->tx_timeout_recovery_level) {
378 	case 1:
379 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
380 		break;
381 	case 2:
382 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
383 		break;
384 	case 3:
385 		set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
386 		break;
387 	default:
388 		netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in non-recoverable state.\n");
389 		set_bit(__I40E_DOWN_REQUESTED, pf->state);
390 		set_bit(__I40E_VSI_DOWN_REQUESTED, vsi->state);
391 		break;
392 	}
393 
394 	i40e_service_event_schedule(pf);
395 	pf->tx_timeout_recovery_level++;
396 }
397 
398 /**
399  * i40e_get_vsi_stats_struct - Get System Network Statistics
400  * @vsi: the VSI we care about
401  *
402  * Returns the address of the device statistics structure.
403  * The statistics are actually updated from the service task.
404  **/
405 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
406 {
407 	return &vsi->net_stats;
408 }
409 
410 /**
411  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
412  * @ring: Tx ring to get statistics from
413  * @stats: statistics entry to be updated
414  **/
415 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
416 					    struct rtnl_link_stats64 *stats)
417 {
418 	u64 bytes, packets;
419 	unsigned int start;
420 
421 	do {
422 		start = u64_stats_fetch_begin(&ring->syncp);
423 		packets = ring->stats.packets;
424 		bytes   = ring->stats.bytes;
425 	} while (u64_stats_fetch_retry(&ring->syncp, start));
426 
427 	stats->tx_packets += packets;
428 	stats->tx_bytes   += bytes;
429 }
430 
431 /**
432  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
433  * @netdev: network interface device structure
434  * @stats: data structure to store statistics
435  *
436  * Returns the address of the device statistics structure.
437  * The statistics are actually updated from the service task.
438  **/
439 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
440 				  struct rtnl_link_stats64 *stats)
441 {
442 	struct i40e_netdev_priv *np = netdev_priv(netdev);
443 	struct i40e_vsi *vsi = np->vsi;
444 	struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
445 	struct i40e_ring *ring;
446 	int i;
447 
448 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
449 		return;
450 
451 	if (!vsi->tx_rings)
452 		return;
453 
454 	rcu_read_lock();
455 	for (i = 0; i < vsi->num_queue_pairs; i++) {
456 		u64 bytes, packets;
457 		unsigned int start;
458 
459 		ring = READ_ONCE(vsi->tx_rings[i]);
460 		if (!ring)
461 			continue;
462 		i40e_get_netdev_stats_struct_tx(ring, stats);
463 
464 		if (i40e_enabled_xdp_vsi(vsi)) {
465 			ring = READ_ONCE(vsi->xdp_rings[i]);
466 			if (!ring)
467 				continue;
468 			i40e_get_netdev_stats_struct_tx(ring, stats);
469 		}
470 
471 		ring = READ_ONCE(vsi->rx_rings[i]);
472 		if (!ring)
473 			continue;
474 		do {
475 			start   = u64_stats_fetch_begin(&ring->syncp);
476 			packets = ring->stats.packets;
477 			bytes   = ring->stats.bytes;
478 		} while (u64_stats_fetch_retry(&ring->syncp, start));
479 
480 		stats->rx_packets += packets;
481 		stats->rx_bytes   += bytes;
482 
483 	}
484 	rcu_read_unlock();
485 
486 	/* following stats updated by i40e_watchdog_subtask() */
487 	stats->multicast	= vsi_stats->multicast;
488 	stats->tx_errors	= vsi_stats->tx_errors;
489 	stats->tx_dropped	= vsi_stats->tx_dropped;
490 	stats->rx_errors	= vsi_stats->rx_errors;
491 	stats->rx_dropped	= vsi_stats->rx_dropped;
492 	stats->rx_crc_errors	= vsi_stats->rx_crc_errors;
493 	stats->rx_length_errors	= vsi_stats->rx_length_errors;
494 }
495 
496 /**
497  * i40e_vsi_reset_stats - Resets all stats of the given vsi
498  * @vsi: the VSI to have its stats reset
499  **/
500 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
501 {
502 	struct rtnl_link_stats64 *ns;
503 	int i;
504 
505 	if (!vsi)
506 		return;
507 
508 	ns = i40e_get_vsi_stats_struct(vsi);
509 	memset(ns, 0, sizeof(*ns));
510 	memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
511 	memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
512 	memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
513 	if (vsi->rx_rings && vsi->rx_rings[0]) {
514 		for (i = 0; i < vsi->num_queue_pairs; i++) {
515 			memset(&vsi->rx_rings[i]->stats, 0,
516 			       sizeof(vsi->rx_rings[i]->stats));
517 			memset(&vsi->rx_rings[i]->rx_stats, 0,
518 			       sizeof(vsi->rx_rings[i]->rx_stats));
519 			memset(&vsi->tx_rings[i]->stats, 0,
520 			       sizeof(vsi->tx_rings[i]->stats));
521 			memset(&vsi->tx_rings[i]->tx_stats, 0,
522 			       sizeof(vsi->tx_rings[i]->tx_stats));
523 		}
524 	}
525 	vsi->stat_offsets_loaded = false;
526 }
527 
528 /**
529  * i40e_pf_reset_stats - Reset all of the stats for the given PF
530  * @pf: the PF to be reset
531  **/
532 void i40e_pf_reset_stats(struct i40e_pf *pf)
533 {
534 	int i;
535 
536 	memset(&pf->stats, 0, sizeof(pf->stats));
537 	memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
538 	pf->stat_offsets_loaded = false;
539 
540 	for (i = 0; i < I40E_MAX_VEB; i++) {
541 		if (pf->veb[i]) {
542 			memset(&pf->veb[i]->stats, 0,
543 			       sizeof(pf->veb[i]->stats));
544 			memset(&pf->veb[i]->stats_offsets, 0,
545 			       sizeof(pf->veb[i]->stats_offsets));
546 			memset(&pf->veb[i]->tc_stats, 0,
547 			       sizeof(pf->veb[i]->tc_stats));
548 			memset(&pf->veb[i]->tc_stats_offsets, 0,
549 			       sizeof(pf->veb[i]->tc_stats_offsets));
550 			pf->veb[i]->stat_offsets_loaded = false;
551 		}
552 	}
553 	pf->hw_csum_rx_error = 0;
554 }
555 
556 /**
557  * i40e_compute_pci_to_hw_id - compute index form PCI function.
558  * @vsi: ptr to the VSI to read from.
559  * @hw: ptr to the hardware info.
560  **/
561 static u32 i40e_compute_pci_to_hw_id(struct i40e_vsi *vsi, struct i40e_hw *hw)
562 {
563 	int pf_count = i40e_get_pf_count(hw);
564 
565 	if (vsi->type == I40E_VSI_SRIOV)
566 		return (hw->port * BIT(7)) / pf_count + vsi->vf_id;
567 
568 	return hw->port + BIT(7);
569 }
570 
571 /**
572  * i40e_stat_update64 - read and update a 64 bit stat from the chip.
573  * @hw: ptr to the hardware info.
574  * @hireg: the high 32 bit reg to read.
575  * @loreg: the low 32 bit reg to read.
576  * @offset_loaded: has the initial offset been loaded yet.
577  * @offset: ptr to current offset value.
578  * @stat: ptr to the stat.
579  *
580  * Since the device stats are not reset at PFReset, they will not
581  * be zeroed when the driver starts.  We'll save the first values read
582  * and use them as offsets to be subtracted from the raw values in order
583  * to report stats that count from zero.
584  **/
585 static void i40e_stat_update64(struct i40e_hw *hw, u32 hireg, u32 loreg,
586 			       bool offset_loaded, u64 *offset, u64 *stat)
587 {
588 	u64 new_data;
589 
590 	new_data = rd64(hw, loreg);
591 
592 	if (!offset_loaded || new_data < *offset)
593 		*offset = new_data;
594 	*stat = new_data - *offset;
595 }
596 
597 /**
598  * i40e_stat_update48 - read and update a 48 bit stat from the chip
599  * @hw: ptr to the hardware info
600  * @hireg: the high 32 bit reg to read
601  * @loreg: the low 32 bit reg to read
602  * @offset_loaded: has the initial offset been loaded yet
603  * @offset: ptr to current offset value
604  * @stat: ptr to the stat
605  *
606  * Since the device stats are not reset at PFReset, they likely will not
607  * be zeroed when the driver starts.  We'll save the first values read
608  * and use them as offsets to be subtracted from the raw values in order
609  * to report stats that count from zero.  In the process, we also manage
610  * the potential roll-over.
611  **/
612 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
613 			       bool offset_loaded, u64 *offset, u64 *stat)
614 {
615 	u64 new_data;
616 
617 	if (hw->device_id == I40E_DEV_ID_QEMU) {
618 		new_data = rd32(hw, loreg);
619 		new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
620 	} else {
621 		new_data = rd64(hw, loreg);
622 	}
623 	if (!offset_loaded)
624 		*offset = new_data;
625 	if (likely(new_data >= *offset))
626 		*stat = new_data - *offset;
627 	else
628 		*stat = (new_data + BIT_ULL(48)) - *offset;
629 	*stat &= 0xFFFFFFFFFFFFULL;
630 }
631 
632 /**
633  * i40e_stat_update32 - read and update a 32 bit stat from the chip
634  * @hw: ptr to the hardware info
635  * @reg: the hw reg to read
636  * @offset_loaded: has the initial offset been loaded yet
637  * @offset: ptr to current offset value
638  * @stat: ptr to the stat
639  **/
640 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
641 			       bool offset_loaded, u64 *offset, u64 *stat)
642 {
643 	u32 new_data;
644 
645 	new_data = rd32(hw, reg);
646 	if (!offset_loaded)
647 		*offset = new_data;
648 	if (likely(new_data >= *offset))
649 		*stat = (u32)(new_data - *offset);
650 	else
651 		*stat = (u32)((new_data + BIT_ULL(32)) - *offset);
652 }
653 
654 /**
655  * i40e_stat_update_and_clear32 - read and clear hw reg, update a 32 bit stat
656  * @hw: ptr to the hardware info
657  * @reg: the hw reg to read and clear
658  * @stat: ptr to the stat
659  **/
660 static void i40e_stat_update_and_clear32(struct i40e_hw *hw, u32 reg, u64 *stat)
661 {
662 	u32 new_data = rd32(hw, reg);
663 
664 	wr32(hw, reg, 1); /* must write a nonzero value to clear register */
665 	*stat += new_data;
666 }
667 
668 /**
669  * i40e_stats_update_rx_discards - update rx_discards.
670  * @vsi: ptr to the VSI to be updated.
671  * @hw: ptr to the hardware info.
672  * @stat_idx: VSI's stat_counter_idx.
673  * @offset_loaded: ptr to the VSI's stat_offsets_loaded.
674  * @stat_offset: ptr to stat_offset to store first read of specific register.
675  * @stat: ptr to VSI's stat to be updated.
676  **/
677 static void
678 i40e_stats_update_rx_discards(struct i40e_vsi *vsi, struct i40e_hw *hw,
679 			      int stat_idx, bool offset_loaded,
680 			      struct i40e_eth_stats *stat_offset,
681 			      struct i40e_eth_stats *stat)
682 {
683 	u64 rx_rdpc, rx_rxerr;
684 
685 	i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx), offset_loaded,
686 			   &stat_offset->rx_discards, &rx_rdpc);
687 	i40e_stat_update64(hw,
688 			   I40E_GL_RXERR1H(i40e_compute_pci_to_hw_id(vsi, hw)),
689 			   I40E_GL_RXERR1L(i40e_compute_pci_to_hw_id(vsi, hw)),
690 			   offset_loaded, &stat_offset->rx_discards_other,
691 			   &rx_rxerr);
692 
693 	stat->rx_discards = rx_rdpc + rx_rxerr;
694 }
695 
696 /**
697  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
698  * @vsi: the VSI to be updated
699  **/
700 void i40e_update_eth_stats(struct i40e_vsi *vsi)
701 {
702 	int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
703 	struct i40e_pf *pf = vsi->back;
704 	struct i40e_hw *hw = &pf->hw;
705 	struct i40e_eth_stats *oes;
706 	struct i40e_eth_stats *es;     /* device's eth stats */
707 
708 	es = &vsi->eth_stats;
709 	oes = &vsi->eth_stats_offsets;
710 
711 	/* Gather up the stats that the hw collects */
712 	i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
713 			   vsi->stat_offsets_loaded,
714 			   &oes->tx_errors, &es->tx_errors);
715 	i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx),
716 			   vsi->stat_offsets_loaded,
717 			   &oes->rx_discards, &es->rx_discards);
718 	i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
719 			   vsi->stat_offsets_loaded,
720 			   &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
721 
722 	i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
723 			   I40E_GLV_GORCL(stat_idx),
724 			   vsi->stat_offsets_loaded,
725 			   &oes->rx_bytes, &es->rx_bytes);
726 	i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
727 			   I40E_GLV_UPRCL(stat_idx),
728 			   vsi->stat_offsets_loaded,
729 			   &oes->rx_unicast, &es->rx_unicast);
730 	i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
731 			   I40E_GLV_MPRCL(stat_idx),
732 			   vsi->stat_offsets_loaded,
733 			   &oes->rx_multicast, &es->rx_multicast);
734 	i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
735 			   I40E_GLV_BPRCL(stat_idx),
736 			   vsi->stat_offsets_loaded,
737 			   &oes->rx_broadcast, &es->rx_broadcast);
738 
739 	i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
740 			   I40E_GLV_GOTCL(stat_idx),
741 			   vsi->stat_offsets_loaded,
742 			   &oes->tx_bytes, &es->tx_bytes);
743 	i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
744 			   I40E_GLV_UPTCL(stat_idx),
745 			   vsi->stat_offsets_loaded,
746 			   &oes->tx_unicast, &es->tx_unicast);
747 	i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
748 			   I40E_GLV_MPTCL(stat_idx),
749 			   vsi->stat_offsets_loaded,
750 			   &oes->tx_multicast, &es->tx_multicast);
751 	i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
752 			   I40E_GLV_BPTCL(stat_idx),
753 			   vsi->stat_offsets_loaded,
754 			   &oes->tx_broadcast, &es->tx_broadcast);
755 
756 	i40e_stats_update_rx_discards(vsi, hw, stat_idx,
757 				      vsi->stat_offsets_loaded, oes, es);
758 
759 	vsi->stat_offsets_loaded = true;
760 }
761 
762 /**
763  * i40e_update_veb_stats - Update Switch component statistics
764  * @veb: the VEB being updated
765  **/
766 void i40e_update_veb_stats(struct i40e_veb *veb)
767 {
768 	struct i40e_pf *pf = veb->pf;
769 	struct i40e_hw *hw = &pf->hw;
770 	struct i40e_eth_stats *oes;
771 	struct i40e_eth_stats *es;     /* device's eth stats */
772 	struct i40e_veb_tc_stats *veb_oes;
773 	struct i40e_veb_tc_stats *veb_es;
774 	int i, idx = 0;
775 
776 	idx = veb->stats_idx;
777 	es = &veb->stats;
778 	oes = &veb->stats_offsets;
779 	veb_es = &veb->tc_stats;
780 	veb_oes = &veb->tc_stats_offsets;
781 
782 	/* Gather up the stats that the hw collects */
783 	i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
784 			   veb->stat_offsets_loaded,
785 			   &oes->tx_discards, &es->tx_discards);
786 	if (hw->revision_id > 0)
787 		i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
788 				   veb->stat_offsets_loaded,
789 				   &oes->rx_unknown_protocol,
790 				   &es->rx_unknown_protocol);
791 	i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
792 			   veb->stat_offsets_loaded,
793 			   &oes->rx_bytes, &es->rx_bytes);
794 	i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
795 			   veb->stat_offsets_loaded,
796 			   &oes->rx_unicast, &es->rx_unicast);
797 	i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
798 			   veb->stat_offsets_loaded,
799 			   &oes->rx_multicast, &es->rx_multicast);
800 	i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
801 			   veb->stat_offsets_loaded,
802 			   &oes->rx_broadcast, &es->rx_broadcast);
803 
804 	i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
805 			   veb->stat_offsets_loaded,
806 			   &oes->tx_bytes, &es->tx_bytes);
807 	i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
808 			   veb->stat_offsets_loaded,
809 			   &oes->tx_unicast, &es->tx_unicast);
810 	i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
811 			   veb->stat_offsets_loaded,
812 			   &oes->tx_multicast, &es->tx_multicast);
813 	i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
814 			   veb->stat_offsets_loaded,
815 			   &oes->tx_broadcast, &es->tx_broadcast);
816 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
817 		i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
818 				   I40E_GLVEBTC_RPCL(i, idx),
819 				   veb->stat_offsets_loaded,
820 				   &veb_oes->tc_rx_packets[i],
821 				   &veb_es->tc_rx_packets[i]);
822 		i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
823 				   I40E_GLVEBTC_RBCL(i, idx),
824 				   veb->stat_offsets_loaded,
825 				   &veb_oes->tc_rx_bytes[i],
826 				   &veb_es->tc_rx_bytes[i]);
827 		i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
828 				   I40E_GLVEBTC_TPCL(i, idx),
829 				   veb->stat_offsets_loaded,
830 				   &veb_oes->tc_tx_packets[i],
831 				   &veb_es->tc_tx_packets[i]);
832 		i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
833 				   I40E_GLVEBTC_TBCL(i, idx),
834 				   veb->stat_offsets_loaded,
835 				   &veb_oes->tc_tx_bytes[i],
836 				   &veb_es->tc_tx_bytes[i]);
837 	}
838 	veb->stat_offsets_loaded = true;
839 }
840 
841 /**
842  * i40e_update_vsi_stats - Update the vsi statistics counters.
843  * @vsi: the VSI to be updated
844  *
845  * There are a few instances where we store the same stat in a
846  * couple of different structs.  This is partly because we have
847  * the netdev stats that need to be filled out, which is slightly
848  * different from the "eth_stats" defined by the chip and used in
849  * VF communications.  We sort it out here.
850  **/
851 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
852 {
853 	u64 rx_page, rx_buf, rx_reuse, rx_alloc, rx_waive, rx_busy;
854 	struct i40e_pf *pf = vsi->back;
855 	struct rtnl_link_stats64 *ons;
856 	struct rtnl_link_stats64 *ns;   /* netdev stats */
857 	struct i40e_eth_stats *oes;
858 	struct i40e_eth_stats *es;     /* device's eth stats */
859 	u64 tx_restart, tx_busy;
860 	struct i40e_ring *p;
861 	u64 bytes, packets;
862 	unsigned int start;
863 	u64 tx_linearize;
864 	u64 tx_force_wb;
865 	u64 tx_stopped;
866 	u64 rx_p, rx_b;
867 	u64 tx_p, tx_b;
868 	u16 q;
869 
870 	if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
871 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
872 		return;
873 
874 	ns = i40e_get_vsi_stats_struct(vsi);
875 	ons = &vsi->net_stats_offsets;
876 	es = &vsi->eth_stats;
877 	oes = &vsi->eth_stats_offsets;
878 
879 	/* Gather up the netdev and vsi stats that the driver collects
880 	 * on the fly during packet processing
881 	 */
882 	rx_b = rx_p = 0;
883 	tx_b = tx_p = 0;
884 	tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
885 	tx_stopped = 0;
886 	rx_page = 0;
887 	rx_buf = 0;
888 	rx_reuse = 0;
889 	rx_alloc = 0;
890 	rx_waive = 0;
891 	rx_busy = 0;
892 	rcu_read_lock();
893 	for (q = 0; q < vsi->num_queue_pairs; q++) {
894 		/* locate Tx ring */
895 		p = READ_ONCE(vsi->tx_rings[q]);
896 		if (!p)
897 			continue;
898 
899 		do {
900 			start = u64_stats_fetch_begin(&p->syncp);
901 			packets = p->stats.packets;
902 			bytes = p->stats.bytes;
903 		} while (u64_stats_fetch_retry(&p->syncp, start));
904 		tx_b += bytes;
905 		tx_p += packets;
906 		tx_restart += p->tx_stats.restart_queue;
907 		tx_busy += p->tx_stats.tx_busy;
908 		tx_linearize += p->tx_stats.tx_linearize;
909 		tx_force_wb += p->tx_stats.tx_force_wb;
910 		tx_stopped += p->tx_stats.tx_stopped;
911 
912 		/* locate Rx ring */
913 		p = READ_ONCE(vsi->rx_rings[q]);
914 		if (!p)
915 			continue;
916 
917 		do {
918 			start = u64_stats_fetch_begin(&p->syncp);
919 			packets = p->stats.packets;
920 			bytes = p->stats.bytes;
921 		} while (u64_stats_fetch_retry(&p->syncp, start));
922 		rx_b += bytes;
923 		rx_p += packets;
924 		rx_buf += p->rx_stats.alloc_buff_failed;
925 		rx_page += p->rx_stats.alloc_page_failed;
926 		rx_reuse += p->rx_stats.page_reuse_count;
927 		rx_alloc += p->rx_stats.page_alloc_count;
928 		rx_waive += p->rx_stats.page_waive_count;
929 		rx_busy += p->rx_stats.page_busy_count;
930 
931 		if (i40e_enabled_xdp_vsi(vsi)) {
932 			/* locate XDP ring */
933 			p = READ_ONCE(vsi->xdp_rings[q]);
934 			if (!p)
935 				continue;
936 
937 			do {
938 				start = u64_stats_fetch_begin(&p->syncp);
939 				packets = p->stats.packets;
940 				bytes = p->stats.bytes;
941 			} while (u64_stats_fetch_retry(&p->syncp, start));
942 			tx_b += bytes;
943 			tx_p += packets;
944 			tx_restart += p->tx_stats.restart_queue;
945 			tx_busy += p->tx_stats.tx_busy;
946 			tx_linearize += p->tx_stats.tx_linearize;
947 			tx_force_wb += p->tx_stats.tx_force_wb;
948 		}
949 	}
950 	rcu_read_unlock();
951 	vsi->tx_restart = tx_restart;
952 	vsi->tx_busy = tx_busy;
953 	vsi->tx_linearize = tx_linearize;
954 	vsi->tx_force_wb = tx_force_wb;
955 	vsi->tx_stopped = tx_stopped;
956 	vsi->rx_page_failed = rx_page;
957 	vsi->rx_buf_failed = rx_buf;
958 	vsi->rx_page_reuse = rx_reuse;
959 	vsi->rx_page_alloc = rx_alloc;
960 	vsi->rx_page_waive = rx_waive;
961 	vsi->rx_page_busy = rx_busy;
962 
963 	ns->rx_packets = rx_p;
964 	ns->rx_bytes = rx_b;
965 	ns->tx_packets = tx_p;
966 	ns->tx_bytes = tx_b;
967 
968 	/* update netdev stats from eth stats */
969 	i40e_update_eth_stats(vsi);
970 	ons->tx_errors = oes->tx_errors;
971 	ns->tx_errors = es->tx_errors;
972 	ons->multicast = oes->rx_multicast;
973 	ns->multicast = es->rx_multicast;
974 	ons->rx_dropped = oes->rx_discards;
975 	ns->rx_dropped = es->rx_discards;
976 	ons->tx_dropped = oes->tx_discards;
977 	ns->tx_dropped = es->tx_discards;
978 
979 	/* pull in a couple PF stats if this is the main vsi */
980 	if (vsi == pf->vsi[pf->lan_vsi]) {
981 		ns->rx_crc_errors = pf->stats.crc_errors;
982 		ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
983 		ns->rx_length_errors = pf->stats.rx_length_errors;
984 	}
985 }
986 
987 /**
988  * i40e_update_pf_stats - Update the PF statistics counters.
989  * @pf: the PF to be updated
990  **/
991 static void i40e_update_pf_stats(struct i40e_pf *pf)
992 {
993 	struct i40e_hw_port_stats *osd = &pf->stats_offsets;
994 	struct i40e_hw_port_stats *nsd = &pf->stats;
995 	struct i40e_hw *hw = &pf->hw;
996 	u32 val;
997 	int i;
998 
999 	i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
1000 			   I40E_GLPRT_GORCL(hw->port),
1001 			   pf->stat_offsets_loaded,
1002 			   &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
1003 	i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
1004 			   I40E_GLPRT_GOTCL(hw->port),
1005 			   pf->stat_offsets_loaded,
1006 			   &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
1007 	i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
1008 			   pf->stat_offsets_loaded,
1009 			   &osd->eth.rx_discards,
1010 			   &nsd->eth.rx_discards);
1011 	i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
1012 			   I40E_GLPRT_UPRCL(hw->port),
1013 			   pf->stat_offsets_loaded,
1014 			   &osd->eth.rx_unicast,
1015 			   &nsd->eth.rx_unicast);
1016 	i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
1017 			   I40E_GLPRT_MPRCL(hw->port),
1018 			   pf->stat_offsets_loaded,
1019 			   &osd->eth.rx_multicast,
1020 			   &nsd->eth.rx_multicast);
1021 	i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
1022 			   I40E_GLPRT_BPRCL(hw->port),
1023 			   pf->stat_offsets_loaded,
1024 			   &osd->eth.rx_broadcast,
1025 			   &nsd->eth.rx_broadcast);
1026 	i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
1027 			   I40E_GLPRT_UPTCL(hw->port),
1028 			   pf->stat_offsets_loaded,
1029 			   &osd->eth.tx_unicast,
1030 			   &nsd->eth.tx_unicast);
1031 	i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
1032 			   I40E_GLPRT_MPTCL(hw->port),
1033 			   pf->stat_offsets_loaded,
1034 			   &osd->eth.tx_multicast,
1035 			   &nsd->eth.tx_multicast);
1036 	i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
1037 			   I40E_GLPRT_BPTCL(hw->port),
1038 			   pf->stat_offsets_loaded,
1039 			   &osd->eth.tx_broadcast,
1040 			   &nsd->eth.tx_broadcast);
1041 
1042 	i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
1043 			   pf->stat_offsets_loaded,
1044 			   &osd->tx_dropped_link_down,
1045 			   &nsd->tx_dropped_link_down);
1046 
1047 	i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
1048 			   pf->stat_offsets_loaded,
1049 			   &osd->crc_errors, &nsd->crc_errors);
1050 
1051 	i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
1052 			   pf->stat_offsets_loaded,
1053 			   &osd->illegal_bytes, &nsd->illegal_bytes);
1054 
1055 	i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
1056 			   pf->stat_offsets_loaded,
1057 			   &osd->mac_local_faults,
1058 			   &nsd->mac_local_faults);
1059 	i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
1060 			   pf->stat_offsets_loaded,
1061 			   &osd->mac_remote_faults,
1062 			   &nsd->mac_remote_faults);
1063 
1064 	i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
1065 			   pf->stat_offsets_loaded,
1066 			   &osd->rx_length_errors,
1067 			   &nsd->rx_length_errors);
1068 
1069 	i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
1070 			   pf->stat_offsets_loaded,
1071 			   &osd->link_xon_rx, &nsd->link_xon_rx);
1072 	i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
1073 			   pf->stat_offsets_loaded,
1074 			   &osd->link_xon_tx, &nsd->link_xon_tx);
1075 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
1076 			   pf->stat_offsets_loaded,
1077 			   &osd->link_xoff_rx, &nsd->link_xoff_rx);
1078 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
1079 			   pf->stat_offsets_loaded,
1080 			   &osd->link_xoff_tx, &nsd->link_xoff_tx);
1081 
1082 	for (i = 0; i < 8; i++) {
1083 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
1084 				   pf->stat_offsets_loaded,
1085 				   &osd->priority_xoff_rx[i],
1086 				   &nsd->priority_xoff_rx[i]);
1087 		i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
1088 				   pf->stat_offsets_loaded,
1089 				   &osd->priority_xon_rx[i],
1090 				   &nsd->priority_xon_rx[i]);
1091 		i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
1092 				   pf->stat_offsets_loaded,
1093 				   &osd->priority_xon_tx[i],
1094 				   &nsd->priority_xon_tx[i]);
1095 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
1096 				   pf->stat_offsets_loaded,
1097 				   &osd->priority_xoff_tx[i],
1098 				   &nsd->priority_xoff_tx[i]);
1099 		i40e_stat_update32(hw,
1100 				   I40E_GLPRT_RXON2OFFCNT(hw->port, i),
1101 				   pf->stat_offsets_loaded,
1102 				   &osd->priority_xon_2_xoff[i],
1103 				   &nsd->priority_xon_2_xoff[i]);
1104 	}
1105 
1106 	i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
1107 			   I40E_GLPRT_PRC64L(hw->port),
1108 			   pf->stat_offsets_loaded,
1109 			   &osd->rx_size_64, &nsd->rx_size_64);
1110 	i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
1111 			   I40E_GLPRT_PRC127L(hw->port),
1112 			   pf->stat_offsets_loaded,
1113 			   &osd->rx_size_127, &nsd->rx_size_127);
1114 	i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
1115 			   I40E_GLPRT_PRC255L(hw->port),
1116 			   pf->stat_offsets_loaded,
1117 			   &osd->rx_size_255, &nsd->rx_size_255);
1118 	i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
1119 			   I40E_GLPRT_PRC511L(hw->port),
1120 			   pf->stat_offsets_loaded,
1121 			   &osd->rx_size_511, &nsd->rx_size_511);
1122 	i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
1123 			   I40E_GLPRT_PRC1023L(hw->port),
1124 			   pf->stat_offsets_loaded,
1125 			   &osd->rx_size_1023, &nsd->rx_size_1023);
1126 	i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
1127 			   I40E_GLPRT_PRC1522L(hw->port),
1128 			   pf->stat_offsets_loaded,
1129 			   &osd->rx_size_1522, &nsd->rx_size_1522);
1130 	i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
1131 			   I40E_GLPRT_PRC9522L(hw->port),
1132 			   pf->stat_offsets_loaded,
1133 			   &osd->rx_size_big, &nsd->rx_size_big);
1134 
1135 	i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1136 			   I40E_GLPRT_PTC64L(hw->port),
1137 			   pf->stat_offsets_loaded,
1138 			   &osd->tx_size_64, &nsd->tx_size_64);
1139 	i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1140 			   I40E_GLPRT_PTC127L(hw->port),
1141 			   pf->stat_offsets_loaded,
1142 			   &osd->tx_size_127, &nsd->tx_size_127);
1143 	i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1144 			   I40E_GLPRT_PTC255L(hw->port),
1145 			   pf->stat_offsets_loaded,
1146 			   &osd->tx_size_255, &nsd->tx_size_255);
1147 	i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1148 			   I40E_GLPRT_PTC511L(hw->port),
1149 			   pf->stat_offsets_loaded,
1150 			   &osd->tx_size_511, &nsd->tx_size_511);
1151 	i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1152 			   I40E_GLPRT_PTC1023L(hw->port),
1153 			   pf->stat_offsets_loaded,
1154 			   &osd->tx_size_1023, &nsd->tx_size_1023);
1155 	i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1156 			   I40E_GLPRT_PTC1522L(hw->port),
1157 			   pf->stat_offsets_loaded,
1158 			   &osd->tx_size_1522, &nsd->tx_size_1522);
1159 	i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1160 			   I40E_GLPRT_PTC9522L(hw->port),
1161 			   pf->stat_offsets_loaded,
1162 			   &osd->tx_size_big, &nsd->tx_size_big);
1163 
1164 	i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1165 			   pf->stat_offsets_loaded,
1166 			   &osd->rx_undersize, &nsd->rx_undersize);
1167 	i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1168 			   pf->stat_offsets_loaded,
1169 			   &osd->rx_fragments, &nsd->rx_fragments);
1170 	i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1171 			   pf->stat_offsets_loaded,
1172 			   &osd->rx_oversize, &nsd->rx_oversize);
1173 	i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1174 			   pf->stat_offsets_loaded,
1175 			   &osd->rx_jabber, &nsd->rx_jabber);
1176 
1177 	/* FDIR stats */
1178 	i40e_stat_update_and_clear32(hw,
1179 			I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(hw->pf_id)),
1180 			&nsd->fd_atr_match);
1181 	i40e_stat_update_and_clear32(hw,
1182 			I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(hw->pf_id)),
1183 			&nsd->fd_sb_match);
1184 	i40e_stat_update_and_clear32(hw,
1185 			I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(hw->pf_id)),
1186 			&nsd->fd_atr_tunnel_match);
1187 
1188 	val = rd32(hw, I40E_PRTPM_EEE_STAT);
1189 	nsd->tx_lpi_status =
1190 		       (val & I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK) >>
1191 			I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_SHIFT;
1192 	nsd->rx_lpi_status =
1193 		       (val & I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK) >>
1194 			I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_SHIFT;
1195 	i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1196 			   pf->stat_offsets_loaded,
1197 			   &osd->tx_lpi_count, &nsd->tx_lpi_count);
1198 	i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1199 			   pf->stat_offsets_loaded,
1200 			   &osd->rx_lpi_count, &nsd->rx_lpi_count);
1201 
1202 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED &&
1203 	    !test_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
1204 		nsd->fd_sb_status = true;
1205 	else
1206 		nsd->fd_sb_status = false;
1207 
1208 	if (pf->flags & I40E_FLAG_FD_ATR_ENABLED &&
1209 	    !test_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
1210 		nsd->fd_atr_status = true;
1211 	else
1212 		nsd->fd_atr_status = false;
1213 
1214 	pf->stat_offsets_loaded = true;
1215 }
1216 
1217 /**
1218  * i40e_update_stats - Update the various statistics counters.
1219  * @vsi: the VSI to be updated
1220  *
1221  * Update the various stats for this VSI and its related entities.
1222  **/
1223 void i40e_update_stats(struct i40e_vsi *vsi)
1224 {
1225 	struct i40e_pf *pf = vsi->back;
1226 
1227 	if (vsi == pf->vsi[pf->lan_vsi])
1228 		i40e_update_pf_stats(pf);
1229 
1230 	i40e_update_vsi_stats(vsi);
1231 }
1232 
1233 /**
1234  * i40e_count_filters - counts VSI mac filters
1235  * @vsi: the VSI to be searched
1236  *
1237  * Returns count of mac filters
1238  **/
1239 int i40e_count_filters(struct i40e_vsi *vsi)
1240 {
1241 	struct i40e_mac_filter *f;
1242 	struct hlist_node *h;
1243 	int bkt;
1244 	int cnt = 0;
1245 
1246 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
1247 		++cnt;
1248 
1249 	return cnt;
1250 }
1251 
1252 /**
1253  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1254  * @vsi: the VSI to be searched
1255  * @macaddr: the MAC address
1256  * @vlan: the vlan
1257  *
1258  * Returns ptr to the filter object or NULL
1259  **/
1260 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1261 						const u8 *macaddr, s16 vlan)
1262 {
1263 	struct i40e_mac_filter *f;
1264 	u64 key;
1265 
1266 	if (!vsi || !macaddr)
1267 		return NULL;
1268 
1269 	key = i40e_addr_to_hkey(macaddr);
1270 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1271 		if ((ether_addr_equal(macaddr, f->macaddr)) &&
1272 		    (vlan == f->vlan))
1273 			return f;
1274 	}
1275 	return NULL;
1276 }
1277 
1278 /**
1279  * i40e_find_mac - Find a mac addr in the macvlan filters list
1280  * @vsi: the VSI to be searched
1281  * @macaddr: the MAC address we are searching for
1282  *
1283  * Returns the first filter with the provided MAC address or NULL if
1284  * MAC address was not found
1285  **/
1286 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1287 {
1288 	struct i40e_mac_filter *f;
1289 	u64 key;
1290 
1291 	if (!vsi || !macaddr)
1292 		return NULL;
1293 
1294 	key = i40e_addr_to_hkey(macaddr);
1295 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1296 		if ((ether_addr_equal(macaddr, f->macaddr)))
1297 			return f;
1298 	}
1299 	return NULL;
1300 }
1301 
1302 /**
1303  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1304  * @vsi: the VSI to be searched
1305  *
1306  * Returns true if VSI is in vlan mode or false otherwise
1307  **/
1308 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1309 {
1310 	/* If we have a PVID, always operate in VLAN mode */
1311 	if (vsi->info.pvid)
1312 		return true;
1313 
1314 	/* We need to operate in VLAN mode whenever we have any filters with
1315 	 * a VLAN other than I40E_VLAN_ALL. We could check the table each
1316 	 * time, incurring search cost repeatedly. However, we can notice two
1317 	 * things:
1318 	 *
1319 	 * 1) the only place where we can gain a VLAN filter is in
1320 	 *    i40e_add_filter.
1321 	 *
1322 	 * 2) the only place where filters are actually removed is in
1323 	 *    i40e_sync_filters_subtask.
1324 	 *
1325 	 * Thus, we can simply use a boolean value, has_vlan_filters which we
1326 	 * will set to true when we add a VLAN filter in i40e_add_filter. Then
1327 	 * we have to perform the full search after deleting filters in
1328 	 * i40e_sync_filters_subtask, but we already have to search
1329 	 * filters here and can perform the check at the same time. This
1330 	 * results in avoiding embedding a loop for VLAN mode inside another
1331 	 * loop over all the filters, and should maintain correctness as noted
1332 	 * above.
1333 	 */
1334 	return vsi->has_vlan_filter;
1335 }
1336 
1337 /**
1338  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1339  * @vsi: the VSI to configure
1340  * @tmp_add_list: list of filters ready to be added
1341  * @tmp_del_list: list of filters ready to be deleted
1342  * @vlan_filters: the number of active VLAN filters
1343  *
1344  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1345  * behave as expected. If we have any active VLAN filters remaining or about
1346  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1347  * so that they only match against untagged traffic. If we no longer have any
1348  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1349  * so that they match against both tagged and untagged traffic. In this way,
1350  * we ensure that we correctly receive the desired traffic. This ensures that
1351  * when we have an active VLAN we will receive only untagged traffic and
1352  * traffic matching active VLANs. If we have no active VLANs then we will
1353  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1354  *
1355  * Finally, in a similar fashion, this function also corrects filters when
1356  * there is an active PVID assigned to this VSI.
1357  *
1358  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1359  *
1360  * This function is only expected to be called from within
1361  * i40e_sync_vsi_filters.
1362  *
1363  * NOTE: This function expects to be called while under the
1364  * mac_filter_hash_lock
1365  */
1366 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1367 					 struct hlist_head *tmp_add_list,
1368 					 struct hlist_head *tmp_del_list,
1369 					 int vlan_filters)
1370 {
1371 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1372 	struct i40e_mac_filter *f, *add_head;
1373 	struct i40e_new_mac_filter *new;
1374 	struct hlist_node *h;
1375 	int bkt, new_vlan;
1376 
1377 	/* To determine if a particular filter needs to be replaced we
1378 	 * have the three following conditions:
1379 	 *
1380 	 * a) if we have a PVID assigned, then all filters which are
1381 	 *    not marked as VLAN=PVID must be replaced with filters that
1382 	 *    are.
1383 	 * b) otherwise, if we have any active VLANS, all filters
1384 	 *    which are marked as VLAN=-1 must be replaced with
1385 	 *    filters marked as VLAN=0
1386 	 * c) finally, if we do not have any active VLANS, all filters
1387 	 *    which are marked as VLAN=0 must be replaced with filters
1388 	 *    marked as VLAN=-1
1389 	 */
1390 
1391 	/* Update the filters about to be added in place */
1392 	hlist_for_each_entry(new, tmp_add_list, hlist) {
1393 		if (pvid && new->f->vlan != pvid)
1394 			new->f->vlan = pvid;
1395 		else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1396 			new->f->vlan = 0;
1397 		else if (!vlan_filters && new->f->vlan == 0)
1398 			new->f->vlan = I40E_VLAN_ANY;
1399 	}
1400 
1401 	/* Update the remaining active filters */
1402 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1403 		/* Combine the checks for whether a filter needs to be changed
1404 		 * and then determine the new VLAN inside the if block, in
1405 		 * order to avoid duplicating code for adding the new filter
1406 		 * then deleting the old filter.
1407 		 */
1408 		if ((pvid && f->vlan != pvid) ||
1409 		    (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1410 		    (!vlan_filters && f->vlan == 0)) {
1411 			/* Determine the new vlan we will be adding */
1412 			if (pvid)
1413 				new_vlan = pvid;
1414 			else if (vlan_filters)
1415 				new_vlan = 0;
1416 			else
1417 				new_vlan = I40E_VLAN_ANY;
1418 
1419 			/* Create the new filter */
1420 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1421 			if (!add_head)
1422 				return -ENOMEM;
1423 
1424 			/* Create a temporary i40e_new_mac_filter */
1425 			new = kzalloc(sizeof(*new), GFP_ATOMIC);
1426 			if (!new)
1427 				return -ENOMEM;
1428 
1429 			new->f = add_head;
1430 			new->state = add_head->state;
1431 
1432 			/* Add the new filter to the tmp list */
1433 			hlist_add_head(&new->hlist, tmp_add_list);
1434 
1435 			/* Put the original filter into the delete list */
1436 			f->state = I40E_FILTER_REMOVE;
1437 			hash_del(&f->hlist);
1438 			hlist_add_head(&f->hlist, tmp_del_list);
1439 		}
1440 	}
1441 
1442 	vsi->has_vlan_filter = !!vlan_filters;
1443 
1444 	return 0;
1445 }
1446 
1447 /**
1448  * i40e_get_vf_new_vlan - Get new vlan id on a vf
1449  * @vsi: the vsi to configure
1450  * @new_mac: new mac filter to be added
1451  * @f: existing mac filter, replaced with new_mac->f if new_mac is not NULL
1452  * @vlan_filters: the number of active VLAN filters
1453  * @trusted: flag if the VF is trusted
1454  *
1455  * Get new VLAN id based on current VLAN filters, trust, PVID
1456  * and vf-vlan-prune-disable flag.
1457  *
1458  * Returns the value of the new vlan filter or
1459  * the old value if no new filter is needed.
1460  */
1461 static s16 i40e_get_vf_new_vlan(struct i40e_vsi *vsi,
1462 				struct i40e_new_mac_filter *new_mac,
1463 				struct i40e_mac_filter *f,
1464 				int vlan_filters,
1465 				bool trusted)
1466 {
1467 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1468 	struct i40e_pf *pf = vsi->back;
1469 	bool is_any;
1470 
1471 	if (new_mac)
1472 		f = new_mac->f;
1473 
1474 	if (pvid && f->vlan != pvid)
1475 		return pvid;
1476 
1477 	is_any = (trusted ||
1478 		  !(pf->flags & I40E_FLAG_VF_VLAN_PRUNING));
1479 
1480 	if ((vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1481 	    (!is_any && !vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1482 	    (is_any && !vlan_filters && f->vlan == 0)) {
1483 		if (is_any)
1484 			return I40E_VLAN_ANY;
1485 		else
1486 			return 0;
1487 	}
1488 
1489 	return f->vlan;
1490 }
1491 
1492 /**
1493  * i40e_correct_vf_mac_vlan_filters - Correct non-VLAN VF filters if necessary
1494  * @vsi: the vsi to configure
1495  * @tmp_add_list: list of filters ready to be added
1496  * @tmp_del_list: list of filters ready to be deleted
1497  * @vlan_filters: the number of active VLAN filters
1498  * @trusted: flag if the VF is trusted
1499  *
1500  * Correct VF VLAN filters based on current VLAN filters, trust, PVID
1501  * and vf-vlan-prune-disable flag.
1502  *
1503  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1504  *
1505  * This function is only expected to be called from within
1506  * i40e_sync_vsi_filters.
1507  *
1508  * NOTE: This function expects to be called while under the
1509  * mac_filter_hash_lock
1510  */
1511 static int i40e_correct_vf_mac_vlan_filters(struct i40e_vsi *vsi,
1512 					    struct hlist_head *tmp_add_list,
1513 					    struct hlist_head *tmp_del_list,
1514 					    int vlan_filters,
1515 					    bool trusted)
1516 {
1517 	struct i40e_mac_filter *f, *add_head;
1518 	struct i40e_new_mac_filter *new_mac;
1519 	struct hlist_node *h;
1520 	int bkt, new_vlan;
1521 
1522 	hlist_for_each_entry(new_mac, tmp_add_list, hlist) {
1523 		new_mac->f->vlan = i40e_get_vf_new_vlan(vsi, new_mac, NULL,
1524 							vlan_filters, trusted);
1525 	}
1526 
1527 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1528 		new_vlan = i40e_get_vf_new_vlan(vsi, NULL, f, vlan_filters,
1529 						trusted);
1530 		if (new_vlan != f->vlan) {
1531 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1532 			if (!add_head)
1533 				return -ENOMEM;
1534 			/* Create a temporary i40e_new_mac_filter */
1535 			new_mac = kzalloc(sizeof(*new_mac), GFP_ATOMIC);
1536 			if (!new_mac)
1537 				return -ENOMEM;
1538 			new_mac->f = add_head;
1539 			new_mac->state = add_head->state;
1540 
1541 			/* Add the new filter to the tmp list */
1542 			hlist_add_head(&new_mac->hlist, tmp_add_list);
1543 
1544 			/* Put the original filter into the delete list */
1545 			f->state = I40E_FILTER_REMOVE;
1546 			hash_del(&f->hlist);
1547 			hlist_add_head(&f->hlist, tmp_del_list);
1548 		}
1549 	}
1550 
1551 	vsi->has_vlan_filter = !!vlan_filters;
1552 	return 0;
1553 }
1554 
1555 /**
1556  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1557  * @vsi: the PF Main VSI - inappropriate for any other VSI
1558  * @macaddr: the MAC address
1559  *
1560  * Remove whatever filter the firmware set up so the driver can manage
1561  * its own filtering intelligently.
1562  **/
1563 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1564 {
1565 	struct i40e_aqc_remove_macvlan_element_data element;
1566 	struct i40e_pf *pf = vsi->back;
1567 
1568 	/* Only appropriate for the PF main VSI */
1569 	if (vsi->type != I40E_VSI_MAIN)
1570 		return;
1571 
1572 	memset(&element, 0, sizeof(element));
1573 	ether_addr_copy(element.mac_addr, macaddr);
1574 	element.vlan_tag = 0;
1575 	/* Ignore error returns, some firmware does it this way... */
1576 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1577 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1578 
1579 	memset(&element, 0, sizeof(element));
1580 	ether_addr_copy(element.mac_addr, macaddr);
1581 	element.vlan_tag = 0;
1582 	/* ...and some firmware does it this way. */
1583 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1584 			I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1585 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1586 }
1587 
1588 /**
1589  * i40e_add_filter - Add a mac/vlan filter to the VSI
1590  * @vsi: the VSI to be searched
1591  * @macaddr: the MAC address
1592  * @vlan: the vlan
1593  *
1594  * Returns ptr to the filter object or NULL when no memory available.
1595  *
1596  * NOTE: This function is expected to be called with mac_filter_hash_lock
1597  * being held.
1598  **/
1599 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1600 					const u8 *macaddr, s16 vlan)
1601 {
1602 	struct i40e_mac_filter *f;
1603 	u64 key;
1604 
1605 	if (!vsi || !macaddr)
1606 		return NULL;
1607 
1608 	f = i40e_find_filter(vsi, macaddr, vlan);
1609 	if (!f) {
1610 		f = kzalloc(sizeof(*f), GFP_ATOMIC);
1611 		if (!f)
1612 			return NULL;
1613 
1614 		/* Update the boolean indicating if we need to function in
1615 		 * VLAN mode.
1616 		 */
1617 		if (vlan >= 0)
1618 			vsi->has_vlan_filter = true;
1619 
1620 		ether_addr_copy(f->macaddr, macaddr);
1621 		f->vlan = vlan;
1622 		f->state = I40E_FILTER_NEW;
1623 		INIT_HLIST_NODE(&f->hlist);
1624 
1625 		key = i40e_addr_to_hkey(macaddr);
1626 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
1627 
1628 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1629 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1630 	}
1631 
1632 	/* If we're asked to add a filter that has been marked for removal, it
1633 	 * is safe to simply restore it to active state. __i40e_del_filter
1634 	 * will have simply deleted any filters which were previously marked
1635 	 * NEW or FAILED, so if it is currently marked REMOVE it must have
1636 	 * previously been ACTIVE. Since we haven't yet run the sync filters
1637 	 * task, just restore this filter to the ACTIVE state so that the
1638 	 * sync task leaves it in place
1639 	 */
1640 	if (f->state == I40E_FILTER_REMOVE)
1641 		f->state = I40E_FILTER_ACTIVE;
1642 
1643 	return f;
1644 }
1645 
1646 /**
1647  * __i40e_del_filter - Remove a specific filter from the VSI
1648  * @vsi: VSI to remove from
1649  * @f: the filter to remove from the list
1650  *
1651  * This function should be called instead of i40e_del_filter only if you know
1652  * the exact filter you will remove already, such as via i40e_find_filter or
1653  * i40e_find_mac.
1654  *
1655  * NOTE: This function is expected to be called with mac_filter_hash_lock
1656  * being held.
1657  * ANOTHER NOTE: This function MUST be called from within the context of
1658  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1659  * instead of list_for_each_entry().
1660  **/
1661 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1662 {
1663 	if (!f)
1664 		return;
1665 
1666 	/* If the filter was never added to firmware then we can just delete it
1667 	 * directly and we don't want to set the status to remove or else an
1668 	 * admin queue command will unnecessarily fire.
1669 	 */
1670 	if ((f->state == I40E_FILTER_FAILED) ||
1671 	    (f->state == I40E_FILTER_NEW)) {
1672 		hash_del(&f->hlist);
1673 		kfree(f);
1674 	} else {
1675 		f->state = I40E_FILTER_REMOVE;
1676 	}
1677 
1678 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1679 	set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1680 }
1681 
1682 /**
1683  * i40e_del_filter - Remove a MAC/VLAN filter from the VSI
1684  * @vsi: the VSI to be searched
1685  * @macaddr: the MAC address
1686  * @vlan: the VLAN
1687  *
1688  * NOTE: This function is expected to be called with mac_filter_hash_lock
1689  * being held.
1690  * ANOTHER NOTE: This function MUST be called from within the context of
1691  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1692  * instead of list_for_each_entry().
1693  **/
1694 void i40e_del_filter(struct i40e_vsi *vsi, const u8 *macaddr, s16 vlan)
1695 {
1696 	struct i40e_mac_filter *f;
1697 
1698 	if (!vsi || !macaddr)
1699 		return;
1700 
1701 	f = i40e_find_filter(vsi, macaddr, vlan);
1702 	__i40e_del_filter(vsi, f);
1703 }
1704 
1705 /**
1706  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1707  * @vsi: the VSI to be searched
1708  * @macaddr: the mac address to be filtered
1709  *
1710  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1711  * go through all the macvlan filters and add a macvlan filter for each
1712  * unique vlan that already exists. If a PVID has been assigned, instead only
1713  * add the macaddr to that VLAN.
1714  *
1715  * Returns last filter added on success, else NULL
1716  **/
1717 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1718 					    const u8 *macaddr)
1719 {
1720 	struct i40e_mac_filter *f, *add = NULL;
1721 	struct hlist_node *h;
1722 	int bkt;
1723 
1724 	if (vsi->info.pvid)
1725 		return i40e_add_filter(vsi, macaddr,
1726 				       le16_to_cpu(vsi->info.pvid));
1727 
1728 	if (!i40e_is_vsi_in_vlan(vsi))
1729 		return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1730 
1731 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1732 		if (f->state == I40E_FILTER_REMOVE)
1733 			continue;
1734 		add = i40e_add_filter(vsi, macaddr, f->vlan);
1735 		if (!add)
1736 			return NULL;
1737 	}
1738 
1739 	return add;
1740 }
1741 
1742 /**
1743  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1744  * @vsi: the VSI to be searched
1745  * @macaddr: the mac address to be removed
1746  *
1747  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1748  * associated with.
1749  *
1750  * Returns 0 for success, or error
1751  **/
1752 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1753 {
1754 	struct i40e_mac_filter *f;
1755 	struct hlist_node *h;
1756 	bool found = false;
1757 	int bkt;
1758 
1759 	lockdep_assert_held(&vsi->mac_filter_hash_lock);
1760 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1761 		if (ether_addr_equal(macaddr, f->macaddr)) {
1762 			__i40e_del_filter(vsi, f);
1763 			found = true;
1764 		}
1765 	}
1766 
1767 	if (found)
1768 		return 0;
1769 	else
1770 		return -ENOENT;
1771 }
1772 
1773 /**
1774  * i40e_set_mac - NDO callback to set mac address
1775  * @netdev: network interface device structure
1776  * @p: pointer to an address structure
1777  *
1778  * Returns 0 on success, negative on failure
1779  **/
1780 static int i40e_set_mac(struct net_device *netdev, void *p)
1781 {
1782 	struct i40e_netdev_priv *np = netdev_priv(netdev);
1783 	struct i40e_vsi *vsi = np->vsi;
1784 	struct i40e_pf *pf = vsi->back;
1785 	struct i40e_hw *hw = &pf->hw;
1786 	struct sockaddr *addr = p;
1787 
1788 	if (!is_valid_ether_addr(addr->sa_data))
1789 		return -EADDRNOTAVAIL;
1790 
1791 	if (test_bit(__I40E_DOWN, pf->state) ||
1792 	    test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1793 		return -EADDRNOTAVAIL;
1794 
1795 	if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1796 		netdev_info(netdev, "returning to hw mac address %pM\n",
1797 			    hw->mac.addr);
1798 	else
1799 		netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1800 
1801 	/* Copy the address first, so that we avoid a possible race with
1802 	 * .set_rx_mode().
1803 	 * - Remove old address from MAC filter
1804 	 * - Copy new address
1805 	 * - Add new address to MAC filter
1806 	 */
1807 	spin_lock_bh(&vsi->mac_filter_hash_lock);
1808 	i40e_del_mac_filter(vsi, netdev->dev_addr);
1809 	eth_hw_addr_set(netdev, addr->sa_data);
1810 	i40e_add_mac_filter(vsi, netdev->dev_addr);
1811 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
1812 
1813 	if (vsi->type == I40E_VSI_MAIN) {
1814 		int ret;
1815 
1816 		ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1817 						addr->sa_data, NULL);
1818 		if (ret)
1819 			netdev_info(netdev, "Ignoring error from firmware on LAA update, status %pe, AQ ret %s\n",
1820 				    ERR_PTR(ret),
1821 				    i40e_aq_str(hw, hw->aq.asq_last_status));
1822 	}
1823 
1824 	/* schedule our worker thread which will take care of
1825 	 * applying the new filter changes
1826 	 */
1827 	i40e_service_event_schedule(pf);
1828 	return 0;
1829 }
1830 
1831 /**
1832  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1833  * @vsi: vsi structure
1834  * @seed: RSS hash seed
1835  * @lut: pointer to lookup table of lut_size
1836  * @lut_size: size of the lookup table
1837  **/
1838 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1839 			      u8 *lut, u16 lut_size)
1840 {
1841 	struct i40e_pf *pf = vsi->back;
1842 	struct i40e_hw *hw = &pf->hw;
1843 	int ret = 0;
1844 
1845 	if (seed) {
1846 		struct i40e_aqc_get_set_rss_key_data *seed_dw =
1847 			(struct i40e_aqc_get_set_rss_key_data *)seed;
1848 		ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1849 		if (ret) {
1850 			dev_info(&pf->pdev->dev,
1851 				 "Cannot set RSS key, err %pe aq_err %s\n",
1852 				 ERR_PTR(ret),
1853 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1854 			return ret;
1855 		}
1856 	}
1857 	if (lut) {
1858 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
1859 
1860 		ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1861 		if (ret) {
1862 			dev_info(&pf->pdev->dev,
1863 				 "Cannot set RSS lut, err %pe aq_err %s\n",
1864 				 ERR_PTR(ret),
1865 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1866 			return ret;
1867 		}
1868 	}
1869 	return ret;
1870 }
1871 
1872 /**
1873  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1874  * @vsi: VSI structure
1875  **/
1876 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1877 {
1878 	struct i40e_pf *pf = vsi->back;
1879 	u8 seed[I40E_HKEY_ARRAY_SIZE];
1880 	u8 *lut;
1881 	int ret;
1882 
1883 	if (!(pf->hw_features & I40E_HW_RSS_AQ_CAPABLE))
1884 		return 0;
1885 	if (!vsi->rss_size)
1886 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
1887 				      vsi->num_queue_pairs);
1888 	if (!vsi->rss_size)
1889 		return -EINVAL;
1890 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1891 	if (!lut)
1892 		return -ENOMEM;
1893 
1894 	/* Use the user configured hash keys and lookup table if there is one,
1895 	 * otherwise use default
1896 	 */
1897 	if (vsi->rss_lut_user)
1898 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1899 	else
1900 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1901 	if (vsi->rss_hkey_user)
1902 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1903 	else
1904 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1905 	ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1906 	kfree(lut);
1907 	return ret;
1908 }
1909 
1910 /**
1911  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1912  * @vsi: the VSI being configured,
1913  * @ctxt: VSI context structure
1914  * @enabled_tc: number of traffic classes to enable
1915  *
1916  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1917  **/
1918 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1919 					   struct i40e_vsi_context *ctxt,
1920 					   u8 enabled_tc)
1921 {
1922 	u16 qcount = 0, max_qcount, qmap, sections = 0;
1923 	int i, override_q, pow, num_qps, ret;
1924 	u8 netdev_tc = 0, offset = 0;
1925 
1926 	if (vsi->type != I40E_VSI_MAIN)
1927 		return -EINVAL;
1928 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1929 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1930 	vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1931 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1932 	num_qps = vsi->mqprio_qopt.qopt.count[0];
1933 
1934 	/* find the next higher power-of-2 of num queue pairs */
1935 	pow = ilog2(num_qps);
1936 	if (!is_power_of_2(num_qps))
1937 		pow++;
1938 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1939 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1940 
1941 	/* Setup queue offset/count for all TCs for given VSI */
1942 	max_qcount = vsi->mqprio_qopt.qopt.count[0];
1943 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1944 		/* See if the given TC is enabled for the given VSI */
1945 		if (vsi->tc_config.enabled_tc & BIT(i)) {
1946 			offset = vsi->mqprio_qopt.qopt.offset[i];
1947 			qcount = vsi->mqprio_qopt.qopt.count[i];
1948 			if (qcount > max_qcount)
1949 				max_qcount = qcount;
1950 			vsi->tc_config.tc_info[i].qoffset = offset;
1951 			vsi->tc_config.tc_info[i].qcount = qcount;
1952 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1953 		} else {
1954 			/* TC is not enabled so set the offset to
1955 			 * default queue and allocate one queue
1956 			 * for the given TC.
1957 			 */
1958 			vsi->tc_config.tc_info[i].qoffset = 0;
1959 			vsi->tc_config.tc_info[i].qcount = 1;
1960 			vsi->tc_config.tc_info[i].netdev_tc = 0;
1961 		}
1962 	}
1963 
1964 	/* Set actual Tx/Rx queue pairs */
1965 	vsi->num_queue_pairs = offset + qcount;
1966 
1967 	/* Setup queue TC[0].qmap for given VSI context */
1968 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1969 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1970 	ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1971 	ctxt->info.valid_sections |= cpu_to_le16(sections);
1972 
1973 	/* Reconfigure RSS for main VSI with max queue count */
1974 	vsi->rss_size = max_qcount;
1975 	ret = i40e_vsi_config_rss(vsi);
1976 	if (ret) {
1977 		dev_info(&vsi->back->pdev->dev,
1978 			 "Failed to reconfig rss for num_queues (%u)\n",
1979 			 max_qcount);
1980 		return ret;
1981 	}
1982 	vsi->reconfig_rss = true;
1983 	dev_dbg(&vsi->back->pdev->dev,
1984 		"Reconfigured rss with num_queues (%u)\n", max_qcount);
1985 
1986 	/* Find queue count available for channel VSIs and starting offset
1987 	 * for channel VSIs
1988 	 */
1989 	override_q = vsi->mqprio_qopt.qopt.count[0];
1990 	if (override_q && override_q < vsi->num_queue_pairs) {
1991 		vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
1992 		vsi->next_base_queue = override_q;
1993 	}
1994 	return 0;
1995 }
1996 
1997 /**
1998  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
1999  * @vsi: the VSI being setup
2000  * @ctxt: VSI context structure
2001  * @enabled_tc: Enabled TCs bitmap
2002  * @is_add: True if called before Add VSI
2003  *
2004  * Setup VSI queue mapping for enabled traffic classes.
2005  **/
2006 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
2007 				     struct i40e_vsi_context *ctxt,
2008 				     u8 enabled_tc,
2009 				     bool is_add)
2010 {
2011 	struct i40e_pf *pf = vsi->back;
2012 	u16 num_tc_qps = 0;
2013 	u16 sections = 0;
2014 	u8 netdev_tc = 0;
2015 	u16 numtc = 1;
2016 	u16 qcount;
2017 	u8 offset;
2018 	u16 qmap;
2019 	int i;
2020 
2021 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
2022 	offset = 0;
2023 	/* zero out queue mapping, it will get updated on the end of the function */
2024 	memset(ctxt->info.queue_mapping, 0, sizeof(ctxt->info.queue_mapping));
2025 
2026 	if (vsi->type == I40E_VSI_MAIN) {
2027 		/* This code helps add more queue to the VSI if we have
2028 		 * more cores than RSS can support, the higher cores will
2029 		 * be served by ATR or other filters. Furthermore, the
2030 		 * non-zero req_queue_pairs says that user requested a new
2031 		 * queue count via ethtool's set_channels, so use this
2032 		 * value for queues distribution across traffic classes
2033 		 * We need at least one queue pair for the interface
2034 		 * to be usable as we see in else statement.
2035 		 */
2036 		if (vsi->req_queue_pairs > 0)
2037 			vsi->num_queue_pairs = vsi->req_queue_pairs;
2038 		else if (pf->flags & I40E_FLAG_MSIX_ENABLED)
2039 			vsi->num_queue_pairs = pf->num_lan_msix;
2040 		else
2041 			vsi->num_queue_pairs = 1;
2042 	}
2043 
2044 	/* Number of queues per enabled TC */
2045 	if (vsi->type == I40E_VSI_MAIN ||
2046 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs != 0))
2047 		num_tc_qps = vsi->num_queue_pairs;
2048 	else
2049 		num_tc_qps = vsi->alloc_queue_pairs;
2050 
2051 	if (enabled_tc && (vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
2052 		/* Find numtc from enabled TC bitmap */
2053 		for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2054 			if (enabled_tc & BIT(i)) /* TC is enabled */
2055 				numtc++;
2056 		}
2057 		if (!numtc) {
2058 			dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
2059 			numtc = 1;
2060 		}
2061 		num_tc_qps = num_tc_qps / numtc;
2062 		num_tc_qps = min_t(int, num_tc_qps,
2063 				   i40e_pf_get_max_q_per_tc(pf));
2064 	}
2065 
2066 	vsi->tc_config.numtc = numtc;
2067 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
2068 
2069 	/* Do not allow use more TC queue pairs than MSI-X vectors exist */
2070 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
2071 		num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
2072 
2073 	/* Setup queue offset/count for all TCs for given VSI */
2074 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2075 		/* See if the given TC is enabled for the given VSI */
2076 		if (vsi->tc_config.enabled_tc & BIT(i)) {
2077 			/* TC is enabled */
2078 			int pow, num_qps;
2079 
2080 			switch (vsi->type) {
2081 			case I40E_VSI_MAIN:
2082 				if (!(pf->flags & (I40E_FLAG_FD_SB_ENABLED |
2083 				    I40E_FLAG_FD_ATR_ENABLED)) ||
2084 				    vsi->tc_config.enabled_tc != 1) {
2085 					qcount = min_t(int, pf->alloc_rss_size,
2086 						       num_tc_qps);
2087 					break;
2088 				}
2089 				fallthrough;
2090 			case I40E_VSI_FDIR:
2091 			case I40E_VSI_SRIOV:
2092 			case I40E_VSI_VMDQ2:
2093 			default:
2094 				qcount = num_tc_qps;
2095 				WARN_ON(i != 0);
2096 				break;
2097 			}
2098 			vsi->tc_config.tc_info[i].qoffset = offset;
2099 			vsi->tc_config.tc_info[i].qcount = qcount;
2100 
2101 			/* find the next higher power-of-2 of num queue pairs */
2102 			num_qps = qcount;
2103 			pow = 0;
2104 			while (num_qps && (BIT_ULL(pow) < qcount)) {
2105 				pow++;
2106 				num_qps >>= 1;
2107 			}
2108 
2109 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
2110 			qmap =
2111 			    (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
2112 			    (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
2113 
2114 			offset += qcount;
2115 		} else {
2116 			/* TC is not enabled so set the offset to
2117 			 * default queue and allocate one queue
2118 			 * for the given TC.
2119 			 */
2120 			vsi->tc_config.tc_info[i].qoffset = 0;
2121 			vsi->tc_config.tc_info[i].qcount = 1;
2122 			vsi->tc_config.tc_info[i].netdev_tc = 0;
2123 
2124 			qmap = 0;
2125 		}
2126 		ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
2127 	}
2128 	/* Do not change previously set num_queue_pairs for PFs and VFs*/
2129 	if ((vsi->type == I40E_VSI_MAIN && numtc != 1) ||
2130 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs == 0) ||
2131 	    (vsi->type != I40E_VSI_MAIN && vsi->type != I40E_VSI_SRIOV))
2132 		vsi->num_queue_pairs = offset;
2133 
2134 	/* Scheduler section valid can only be set for ADD VSI */
2135 	if (is_add) {
2136 		sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
2137 
2138 		ctxt->info.up_enable_bits = enabled_tc;
2139 	}
2140 	if (vsi->type == I40E_VSI_SRIOV) {
2141 		ctxt->info.mapping_flags |=
2142 				     cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
2143 		for (i = 0; i < vsi->num_queue_pairs; i++)
2144 			ctxt->info.queue_mapping[i] =
2145 					       cpu_to_le16(vsi->base_queue + i);
2146 	} else {
2147 		ctxt->info.mapping_flags |=
2148 					cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
2149 		ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
2150 	}
2151 	ctxt->info.valid_sections |= cpu_to_le16(sections);
2152 }
2153 
2154 /**
2155  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
2156  * @netdev: the netdevice
2157  * @addr: address to add
2158  *
2159  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
2160  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2161  */
2162 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
2163 {
2164 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2165 	struct i40e_vsi *vsi = np->vsi;
2166 
2167 	if (i40e_add_mac_filter(vsi, addr))
2168 		return 0;
2169 	else
2170 		return -ENOMEM;
2171 }
2172 
2173 /**
2174  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
2175  * @netdev: the netdevice
2176  * @addr: address to add
2177  *
2178  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
2179  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2180  */
2181 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
2182 {
2183 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2184 	struct i40e_vsi *vsi = np->vsi;
2185 
2186 	/* Under some circumstances, we might receive a request to delete
2187 	 * our own device address from our uc list. Because we store the
2188 	 * device address in the VSI's MAC/VLAN filter list, we need to ignore
2189 	 * such requests and not delete our device address from this list.
2190 	 */
2191 	if (ether_addr_equal(addr, netdev->dev_addr))
2192 		return 0;
2193 
2194 	i40e_del_mac_filter(vsi, addr);
2195 
2196 	return 0;
2197 }
2198 
2199 /**
2200  * i40e_set_rx_mode - NDO callback to set the netdev filters
2201  * @netdev: network interface device structure
2202  **/
2203 static void i40e_set_rx_mode(struct net_device *netdev)
2204 {
2205 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2206 	struct i40e_vsi *vsi = np->vsi;
2207 
2208 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2209 
2210 	__dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2211 	__dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2212 
2213 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2214 
2215 	/* check for other flag changes */
2216 	if (vsi->current_netdev_flags != vsi->netdev->flags) {
2217 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2218 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
2219 	}
2220 }
2221 
2222 /**
2223  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
2224  * @vsi: Pointer to VSI struct
2225  * @from: Pointer to list which contains MAC filter entries - changes to
2226  *        those entries needs to be undone.
2227  *
2228  * MAC filter entries from this list were slated for deletion.
2229  **/
2230 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
2231 					 struct hlist_head *from)
2232 {
2233 	struct i40e_mac_filter *f;
2234 	struct hlist_node *h;
2235 
2236 	hlist_for_each_entry_safe(f, h, from, hlist) {
2237 		u64 key = i40e_addr_to_hkey(f->macaddr);
2238 
2239 		/* Move the element back into MAC filter list*/
2240 		hlist_del(&f->hlist);
2241 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
2242 	}
2243 }
2244 
2245 /**
2246  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
2247  * @vsi: Pointer to vsi struct
2248  * @from: Pointer to list which contains MAC filter entries - changes to
2249  *        those entries needs to be undone.
2250  *
2251  * MAC filter entries from this list were slated for addition.
2252  **/
2253 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
2254 					 struct hlist_head *from)
2255 {
2256 	struct i40e_new_mac_filter *new;
2257 	struct hlist_node *h;
2258 
2259 	hlist_for_each_entry_safe(new, h, from, hlist) {
2260 		/* We can simply free the wrapper structure */
2261 		hlist_del(&new->hlist);
2262 		netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2263 		kfree(new);
2264 	}
2265 }
2266 
2267 /**
2268  * i40e_next_filter - Get the next non-broadcast filter from a list
2269  * @next: pointer to filter in list
2270  *
2271  * Returns the next non-broadcast filter in the list. Required so that we
2272  * ignore broadcast filters within the list, since these are not handled via
2273  * the normal firmware update path.
2274  */
2275 static
2276 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2277 {
2278 	hlist_for_each_entry_continue(next, hlist) {
2279 		if (!is_broadcast_ether_addr(next->f->macaddr))
2280 			return next;
2281 	}
2282 
2283 	return NULL;
2284 }
2285 
2286 /**
2287  * i40e_update_filter_state - Update filter state based on return data
2288  * from firmware
2289  * @count: Number of filters added
2290  * @add_list: return data from fw
2291  * @add_head: pointer to first filter in current batch
2292  *
2293  * MAC filter entries from list were slated to be added to device. Returns
2294  * number of successful filters. Note that 0 does NOT mean success!
2295  **/
2296 static int
2297 i40e_update_filter_state(int count,
2298 			 struct i40e_aqc_add_macvlan_element_data *add_list,
2299 			 struct i40e_new_mac_filter *add_head)
2300 {
2301 	int retval = 0;
2302 	int i;
2303 
2304 	for (i = 0; i < count; i++) {
2305 		/* Always check status of each filter. We don't need to check
2306 		 * the firmware return status because we pre-set the filter
2307 		 * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2308 		 * request to the adminq. Thus, if it no longer matches then
2309 		 * we know the filter is active.
2310 		 */
2311 		if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2312 			add_head->state = I40E_FILTER_FAILED;
2313 		} else {
2314 			add_head->state = I40E_FILTER_ACTIVE;
2315 			retval++;
2316 		}
2317 
2318 		add_head = i40e_next_filter(add_head);
2319 		if (!add_head)
2320 			break;
2321 	}
2322 
2323 	return retval;
2324 }
2325 
2326 /**
2327  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2328  * @vsi: ptr to the VSI
2329  * @vsi_name: name to display in messages
2330  * @list: the list of filters to send to firmware
2331  * @num_del: the number of filters to delete
2332  * @retval: Set to -EIO on failure to delete
2333  *
2334  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2335  * *retval instead of a return value so that success does not force ret_val to
2336  * be set to 0. This ensures that a sequence of calls to this function
2337  * preserve the previous value of *retval on successful delete.
2338  */
2339 static
2340 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2341 			  struct i40e_aqc_remove_macvlan_element_data *list,
2342 			  int num_del, int *retval)
2343 {
2344 	struct i40e_hw *hw = &vsi->back->hw;
2345 	enum i40e_admin_queue_err aq_status;
2346 	int aq_ret;
2347 
2348 	aq_ret = i40e_aq_remove_macvlan_v2(hw, vsi->seid, list, num_del, NULL,
2349 					   &aq_status);
2350 
2351 	/* Explicitly ignore and do not report when firmware returns ENOENT */
2352 	if (aq_ret && !(aq_status == I40E_AQ_RC_ENOENT)) {
2353 		*retval = -EIO;
2354 		dev_info(&vsi->back->pdev->dev,
2355 			 "ignoring delete macvlan error on %s, err %pe, aq_err %s\n",
2356 			 vsi_name, ERR_PTR(aq_ret),
2357 			 i40e_aq_str(hw, aq_status));
2358 	}
2359 }
2360 
2361 /**
2362  * i40e_aqc_add_filters - Request firmware to add a set of filters
2363  * @vsi: ptr to the VSI
2364  * @vsi_name: name to display in messages
2365  * @list: the list of filters to send to firmware
2366  * @add_head: Position in the add hlist
2367  * @num_add: the number of filters to add
2368  *
2369  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2370  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2371  * space for more filters.
2372  */
2373 static
2374 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2375 			  struct i40e_aqc_add_macvlan_element_data *list,
2376 			  struct i40e_new_mac_filter *add_head,
2377 			  int num_add)
2378 {
2379 	struct i40e_hw *hw = &vsi->back->hw;
2380 	enum i40e_admin_queue_err aq_status;
2381 	int fcnt;
2382 
2383 	i40e_aq_add_macvlan_v2(hw, vsi->seid, list, num_add, NULL, &aq_status);
2384 	fcnt = i40e_update_filter_state(num_add, list, add_head);
2385 
2386 	if (fcnt != num_add) {
2387 		if (vsi->type == I40E_VSI_MAIN) {
2388 			set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2389 			dev_warn(&vsi->back->pdev->dev,
2390 				 "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2391 				 i40e_aq_str(hw, aq_status), vsi_name);
2392 		} else if (vsi->type == I40E_VSI_SRIOV ||
2393 			   vsi->type == I40E_VSI_VMDQ1 ||
2394 			   vsi->type == I40E_VSI_VMDQ2) {
2395 			dev_warn(&vsi->back->pdev->dev,
2396 				 "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2397 				 i40e_aq_str(hw, aq_status), vsi_name,
2398 					     vsi_name);
2399 		} else {
2400 			dev_warn(&vsi->back->pdev->dev,
2401 				 "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2402 				 i40e_aq_str(hw, aq_status), vsi_name,
2403 					     vsi->type);
2404 		}
2405 	}
2406 }
2407 
2408 /**
2409  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2410  * @vsi: pointer to the VSI
2411  * @vsi_name: the VSI name
2412  * @f: filter data
2413  *
2414  * This function sets or clears the promiscuous broadcast flags for VLAN
2415  * filters in order to properly receive broadcast frames. Assumes that only
2416  * broadcast filters are passed.
2417  *
2418  * Returns status indicating success or failure;
2419  **/
2420 static int
2421 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2422 			  struct i40e_mac_filter *f)
2423 {
2424 	bool enable = f->state == I40E_FILTER_NEW;
2425 	struct i40e_hw *hw = &vsi->back->hw;
2426 	int aq_ret;
2427 
2428 	if (f->vlan == I40E_VLAN_ANY) {
2429 		aq_ret = i40e_aq_set_vsi_broadcast(hw,
2430 						   vsi->seid,
2431 						   enable,
2432 						   NULL);
2433 	} else {
2434 		aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2435 							    vsi->seid,
2436 							    enable,
2437 							    f->vlan,
2438 							    NULL);
2439 	}
2440 
2441 	if (aq_ret) {
2442 		set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2443 		dev_warn(&vsi->back->pdev->dev,
2444 			 "Error %s, forcing overflow promiscuous on %s\n",
2445 			 i40e_aq_str(hw, hw->aq.asq_last_status),
2446 			 vsi_name);
2447 	}
2448 
2449 	return aq_ret;
2450 }
2451 
2452 /**
2453  * i40e_set_promiscuous - set promiscuous mode
2454  * @pf: board private structure
2455  * @promisc: promisc on or off
2456  *
2457  * There are different ways of setting promiscuous mode on a PF depending on
2458  * what state/environment we're in.  This identifies and sets it appropriately.
2459  * Returns 0 on success.
2460  **/
2461 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2462 {
2463 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
2464 	struct i40e_hw *hw = &pf->hw;
2465 	int aq_ret;
2466 
2467 	if (vsi->type == I40E_VSI_MAIN &&
2468 	    pf->lan_veb != I40E_NO_VEB &&
2469 	    !(pf->flags & I40E_FLAG_MFP_ENABLED)) {
2470 		/* set defport ON for Main VSI instead of true promisc
2471 		 * this way we will get all unicast/multicast and VLAN
2472 		 * promisc behavior but will not get VF or VMDq traffic
2473 		 * replicated on the Main VSI.
2474 		 */
2475 		if (promisc)
2476 			aq_ret = i40e_aq_set_default_vsi(hw,
2477 							 vsi->seid,
2478 							 NULL);
2479 		else
2480 			aq_ret = i40e_aq_clear_default_vsi(hw,
2481 							   vsi->seid,
2482 							   NULL);
2483 		if (aq_ret) {
2484 			dev_info(&pf->pdev->dev,
2485 				 "Set default VSI failed, err %pe, aq_err %s\n",
2486 				 ERR_PTR(aq_ret),
2487 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2488 		}
2489 	} else {
2490 		aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2491 						  hw,
2492 						  vsi->seid,
2493 						  promisc, NULL,
2494 						  true);
2495 		if (aq_ret) {
2496 			dev_info(&pf->pdev->dev,
2497 				 "set unicast promisc failed, err %pe, aq_err %s\n",
2498 				 ERR_PTR(aq_ret),
2499 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2500 		}
2501 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2502 						  hw,
2503 						  vsi->seid,
2504 						  promisc, NULL);
2505 		if (aq_ret) {
2506 			dev_info(&pf->pdev->dev,
2507 				 "set multicast promisc failed, err %pe, aq_err %s\n",
2508 				 ERR_PTR(aq_ret),
2509 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2510 		}
2511 	}
2512 
2513 	if (!aq_ret)
2514 		pf->cur_promisc = promisc;
2515 
2516 	return aq_ret;
2517 }
2518 
2519 /**
2520  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2521  * @vsi: ptr to the VSI
2522  *
2523  * Push any outstanding VSI filter changes through the AdminQ.
2524  *
2525  * Returns 0 or error value
2526  **/
2527 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2528 {
2529 	struct hlist_head tmp_add_list, tmp_del_list;
2530 	struct i40e_mac_filter *f;
2531 	struct i40e_new_mac_filter *new, *add_head = NULL;
2532 	struct i40e_hw *hw = &vsi->back->hw;
2533 	bool old_overflow, new_overflow;
2534 	unsigned int failed_filters = 0;
2535 	unsigned int vlan_filters = 0;
2536 	char vsi_name[16] = "PF";
2537 	int filter_list_len = 0;
2538 	u32 changed_flags = 0;
2539 	struct hlist_node *h;
2540 	struct i40e_pf *pf;
2541 	int num_add = 0;
2542 	int num_del = 0;
2543 	int aq_ret = 0;
2544 	int retval = 0;
2545 	u16 cmd_flags;
2546 	int list_size;
2547 	int bkt;
2548 
2549 	/* empty array typed pointers, kcalloc later */
2550 	struct i40e_aqc_add_macvlan_element_data *add_list;
2551 	struct i40e_aqc_remove_macvlan_element_data *del_list;
2552 
2553 	while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2554 		usleep_range(1000, 2000);
2555 	pf = vsi->back;
2556 
2557 	old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2558 
2559 	if (vsi->netdev) {
2560 		changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2561 		vsi->current_netdev_flags = vsi->netdev->flags;
2562 	}
2563 
2564 	INIT_HLIST_HEAD(&tmp_add_list);
2565 	INIT_HLIST_HEAD(&tmp_del_list);
2566 
2567 	if (vsi->type == I40E_VSI_SRIOV)
2568 		snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2569 	else if (vsi->type != I40E_VSI_MAIN)
2570 		snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2571 
2572 	if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2573 		vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2574 
2575 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2576 		/* Create a list of filters to delete. */
2577 		hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2578 			if (f->state == I40E_FILTER_REMOVE) {
2579 				/* Move the element into temporary del_list */
2580 				hash_del(&f->hlist);
2581 				hlist_add_head(&f->hlist, &tmp_del_list);
2582 
2583 				/* Avoid counting removed filters */
2584 				continue;
2585 			}
2586 			if (f->state == I40E_FILTER_NEW) {
2587 				/* Create a temporary i40e_new_mac_filter */
2588 				new = kzalloc(sizeof(*new), GFP_ATOMIC);
2589 				if (!new)
2590 					goto err_no_memory_locked;
2591 
2592 				/* Store pointer to the real filter */
2593 				new->f = f;
2594 				new->state = f->state;
2595 
2596 				/* Add it to the hash list */
2597 				hlist_add_head(&new->hlist, &tmp_add_list);
2598 			}
2599 
2600 			/* Count the number of active (current and new) VLAN
2601 			 * filters we have now. Does not count filters which
2602 			 * are marked for deletion.
2603 			 */
2604 			if (f->vlan > 0)
2605 				vlan_filters++;
2606 		}
2607 
2608 		if (vsi->type != I40E_VSI_SRIOV)
2609 			retval = i40e_correct_mac_vlan_filters
2610 				(vsi, &tmp_add_list, &tmp_del_list,
2611 				 vlan_filters);
2612 		else if (pf->vf)
2613 			retval = i40e_correct_vf_mac_vlan_filters
2614 				(vsi, &tmp_add_list, &tmp_del_list,
2615 				 vlan_filters, pf->vf[vsi->vf_id].trusted);
2616 
2617 		hlist_for_each_entry(new, &tmp_add_list, hlist)
2618 			netdev_hw_addr_refcnt(new->f, vsi->netdev, 1);
2619 
2620 		if (retval)
2621 			goto err_no_memory_locked;
2622 
2623 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2624 	}
2625 
2626 	/* Now process 'del_list' outside the lock */
2627 	if (!hlist_empty(&tmp_del_list)) {
2628 		filter_list_len = hw->aq.asq_buf_size /
2629 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2630 		list_size = filter_list_len *
2631 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2632 		del_list = kzalloc(list_size, GFP_ATOMIC);
2633 		if (!del_list)
2634 			goto err_no_memory;
2635 
2636 		hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2637 			cmd_flags = 0;
2638 
2639 			/* handle broadcast filters by updating the broadcast
2640 			 * promiscuous flag and release filter list.
2641 			 */
2642 			if (is_broadcast_ether_addr(f->macaddr)) {
2643 				i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2644 
2645 				hlist_del(&f->hlist);
2646 				kfree(f);
2647 				continue;
2648 			}
2649 
2650 			/* add to delete list */
2651 			ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2652 			if (f->vlan == I40E_VLAN_ANY) {
2653 				del_list[num_del].vlan_tag = 0;
2654 				cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2655 			} else {
2656 				del_list[num_del].vlan_tag =
2657 					cpu_to_le16((u16)(f->vlan));
2658 			}
2659 
2660 			cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2661 			del_list[num_del].flags = cmd_flags;
2662 			num_del++;
2663 
2664 			/* flush a full buffer */
2665 			if (num_del == filter_list_len) {
2666 				i40e_aqc_del_filters(vsi, vsi_name, del_list,
2667 						     num_del, &retval);
2668 				memset(del_list, 0, list_size);
2669 				num_del = 0;
2670 			}
2671 			/* Release memory for MAC filter entries which were
2672 			 * synced up with HW.
2673 			 */
2674 			hlist_del(&f->hlist);
2675 			kfree(f);
2676 		}
2677 
2678 		if (num_del) {
2679 			i40e_aqc_del_filters(vsi, vsi_name, del_list,
2680 					     num_del, &retval);
2681 		}
2682 
2683 		kfree(del_list);
2684 		del_list = NULL;
2685 	}
2686 
2687 	if (!hlist_empty(&tmp_add_list)) {
2688 		/* Do all the adds now. */
2689 		filter_list_len = hw->aq.asq_buf_size /
2690 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2691 		list_size = filter_list_len *
2692 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2693 		add_list = kzalloc(list_size, GFP_ATOMIC);
2694 		if (!add_list)
2695 			goto err_no_memory;
2696 
2697 		num_add = 0;
2698 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2699 			/* handle broadcast filters by updating the broadcast
2700 			 * promiscuous flag instead of adding a MAC filter.
2701 			 */
2702 			if (is_broadcast_ether_addr(new->f->macaddr)) {
2703 				if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2704 							      new->f))
2705 					new->state = I40E_FILTER_FAILED;
2706 				else
2707 					new->state = I40E_FILTER_ACTIVE;
2708 				continue;
2709 			}
2710 
2711 			/* add to add array */
2712 			if (num_add == 0)
2713 				add_head = new;
2714 			cmd_flags = 0;
2715 			ether_addr_copy(add_list[num_add].mac_addr,
2716 					new->f->macaddr);
2717 			if (new->f->vlan == I40E_VLAN_ANY) {
2718 				add_list[num_add].vlan_tag = 0;
2719 				cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2720 			} else {
2721 				add_list[num_add].vlan_tag =
2722 					cpu_to_le16((u16)(new->f->vlan));
2723 			}
2724 			add_list[num_add].queue_number = 0;
2725 			/* set invalid match method for later detection */
2726 			add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2727 			cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2728 			add_list[num_add].flags = cpu_to_le16(cmd_flags);
2729 			num_add++;
2730 
2731 			/* flush a full buffer */
2732 			if (num_add == filter_list_len) {
2733 				i40e_aqc_add_filters(vsi, vsi_name, add_list,
2734 						     add_head, num_add);
2735 				memset(add_list, 0, list_size);
2736 				num_add = 0;
2737 			}
2738 		}
2739 		if (num_add) {
2740 			i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2741 					     num_add);
2742 		}
2743 		/* Now move all of the filters from the temp add list back to
2744 		 * the VSI's list.
2745 		 */
2746 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2747 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2748 			/* Only update the state if we're still NEW */
2749 			if (new->f->state == I40E_FILTER_NEW)
2750 				new->f->state = new->state;
2751 			hlist_del(&new->hlist);
2752 			netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2753 			kfree(new);
2754 		}
2755 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2756 		kfree(add_list);
2757 		add_list = NULL;
2758 	}
2759 
2760 	/* Determine the number of active and failed filters. */
2761 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2762 	vsi->active_filters = 0;
2763 	hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2764 		if (f->state == I40E_FILTER_ACTIVE)
2765 			vsi->active_filters++;
2766 		else if (f->state == I40E_FILTER_FAILED)
2767 			failed_filters++;
2768 	}
2769 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2770 
2771 	/* Check if we are able to exit overflow promiscuous mode. We can
2772 	 * safely exit if we didn't just enter, we no longer have any failed
2773 	 * filters, and we have reduced filters below the threshold value.
2774 	 */
2775 	if (old_overflow && !failed_filters &&
2776 	    vsi->active_filters < vsi->promisc_threshold) {
2777 		dev_info(&pf->pdev->dev,
2778 			 "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2779 			 vsi_name);
2780 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2781 		vsi->promisc_threshold = 0;
2782 	}
2783 
2784 	/* if the VF is not trusted do not do promisc */
2785 	if (vsi->type == I40E_VSI_SRIOV && pf->vf &&
2786 	    !pf->vf[vsi->vf_id].trusted) {
2787 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2788 		goto out;
2789 	}
2790 
2791 	new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2792 
2793 	/* If we are entering overflow promiscuous, we need to calculate a new
2794 	 * threshold for when we are safe to exit
2795 	 */
2796 	if (!old_overflow && new_overflow)
2797 		vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2798 
2799 	/* check for changes in promiscuous modes */
2800 	if (changed_flags & IFF_ALLMULTI) {
2801 		bool cur_multipromisc;
2802 
2803 		cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2804 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2805 							       vsi->seid,
2806 							       cur_multipromisc,
2807 							       NULL);
2808 		if (aq_ret) {
2809 			retval = i40e_aq_rc_to_posix(aq_ret,
2810 						     hw->aq.asq_last_status);
2811 			dev_info(&pf->pdev->dev,
2812 				 "set multi promisc failed on %s, err %pe aq_err %s\n",
2813 				 vsi_name,
2814 				 ERR_PTR(aq_ret),
2815 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2816 		} else {
2817 			dev_info(&pf->pdev->dev, "%s allmulti mode.\n",
2818 				 cur_multipromisc ? "entering" : "leaving");
2819 		}
2820 	}
2821 
2822 	if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2823 		bool cur_promisc;
2824 
2825 		cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2826 			       new_overflow);
2827 		aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2828 		if (aq_ret) {
2829 			retval = i40e_aq_rc_to_posix(aq_ret,
2830 						     hw->aq.asq_last_status);
2831 			dev_info(&pf->pdev->dev,
2832 				 "Setting promiscuous %s failed on %s, err %pe aq_err %s\n",
2833 				 cur_promisc ? "on" : "off",
2834 				 vsi_name,
2835 				 ERR_PTR(aq_ret),
2836 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2837 		}
2838 	}
2839 out:
2840 	/* if something went wrong then set the changed flag so we try again */
2841 	if (retval)
2842 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2843 
2844 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2845 	return retval;
2846 
2847 err_no_memory:
2848 	/* Restore elements on the temporary add and delete lists */
2849 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2850 err_no_memory_locked:
2851 	i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2852 	i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2853 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2854 
2855 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2856 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2857 	return -ENOMEM;
2858 }
2859 
2860 /**
2861  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2862  * @pf: board private structure
2863  **/
2864 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2865 {
2866 	int v;
2867 
2868 	if (!pf)
2869 		return;
2870 	if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2871 		return;
2872 	if (test_bit(__I40E_VF_DISABLE, pf->state)) {
2873 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
2874 		return;
2875 	}
2876 
2877 	for (v = 0; v < pf->num_alloc_vsi; v++) {
2878 		if (pf->vsi[v] &&
2879 		    (pf->vsi[v]->flags & I40E_VSI_FLAG_FILTER_CHANGED) &&
2880 		    !test_bit(__I40E_VSI_RELEASING, pf->vsi[v]->state)) {
2881 			int ret = i40e_sync_vsi_filters(pf->vsi[v]);
2882 
2883 			if (ret) {
2884 				/* come back and try again later */
2885 				set_bit(__I40E_MACVLAN_SYNC_PENDING,
2886 					pf->state);
2887 				break;
2888 			}
2889 		}
2890 	}
2891 }
2892 
2893 /**
2894  * i40e_calculate_vsi_rx_buf_len - Calculates buffer length
2895  *
2896  * @vsi: VSI to calculate rx_buf_len from
2897  */
2898 static u16 i40e_calculate_vsi_rx_buf_len(struct i40e_vsi *vsi)
2899 {
2900 	if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
2901 		return SKB_WITH_OVERHEAD(I40E_RXBUFFER_2048);
2902 
2903 	return PAGE_SIZE < 8192 ? I40E_RXBUFFER_3072 : I40E_RXBUFFER_2048;
2904 }
2905 
2906 /**
2907  * i40e_max_vsi_frame_size - returns the maximum allowed frame size for VSI
2908  * @vsi: the vsi
2909  * @xdp_prog: XDP program
2910  **/
2911 static int i40e_max_vsi_frame_size(struct i40e_vsi *vsi,
2912 				   struct bpf_prog *xdp_prog)
2913 {
2914 	u16 rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
2915 	u16 chain_len;
2916 
2917 	if (xdp_prog && !xdp_prog->aux->xdp_has_frags)
2918 		chain_len = 1;
2919 	else
2920 		chain_len = I40E_MAX_CHAINED_RX_BUFFERS;
2921 
2922 	return min_t(u16, rx_buf_len * chain_len, I40E_MAX_RXBUFFER);
2923 }
2924 
2925 /**
2926  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2927  * @netdev: network interface device structure
2928  * @new_mtu: new value for maximum frame size
2929  *
2930  * Returns 0 on success, negative on failure
2931  **/
2932 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2933 {
2934 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2935 	struct i40e_vsi *vsi = np->vsi;
2936 	struct i40e_pf *pf = vsi->back;
2937 	int frame_size;
2938 
2939 	frame_size = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
2940 	if (new_mtu > frame_size - I40E_PACKET_HDR_PAD) {
2941 		netdev_err(netdev, "Error changing mtu to %d, Max is %d\n",
2942 			   new_mtu, frame_size - I40E_PACKET_HDR_PAD);
2943 		return -EINVAL;
2944 	}
2945 
2946 	netdev_dbg(netdev, "changing MTU from %d to %d\n",
2947 		   netdev->mtu, new_mtu);
2948 	netdev->mtu = new_mtu;
2949 	if (netif_running(netdev))
2950 		i40e_vsi_reinit_locked(vsi);
2951 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2952 	set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2953 	return 0;
2954 }
2955 
2956 /**
2957  * i40e_ioctl - Access the hwtstamp interface
2958  * @netdev: network interface device structure
2959  * @ifr: interface request data
2960  * @cmd: ioctl command
2961  **/
2962 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2963 {
2964 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2965 	struct i40e_pf *pf = np->vsi->back;
2966 
2967 	switch (cmd) {
2968 	case SIOCGHWTSTAMP:
2969 		return i40e_ptp_get_ts_config(pf, ifr);
2970 	case SIOCSHWTSTAMP:
2971 		return i40e_ptp_set_ts_config(pf, ifr);
2972 	default:
2973 		return -EOPNOTSUPP;
2974 	}
2975 }
2976 
2977 /**
2978  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2979  * @vsi: the vsi being adjusted
2980  **/
2981 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2982 {
2983 	struct i40e_vsi_context ctxt;
2984 	int ret;
2985 
2986 	/* Don't modify stripping options if a port VLAN is active */
2987 	if (vsi->info.pvid)
2988 		return;
2989 
2990 	if ((vsi->info.valid_sections &
2991 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2992 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2993 		return;  /* already enabled */
2994 
2995 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2996 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2997 				    I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
2998 
2999 	ctxt.seid = vsi->seid;
3000 	ctxt.info = vsi->info;
3001 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3002 	if (ret) {
3003 		dev_info(&vsi->back->pdev->dev,
3004 			 "update vlan stripping failed, err %pe aq_err %s\n",
3005 			 ERR_PTR(ret),
3006 			 i40e_aq_str(&vsi->back->hw,
3007 				     vsi->back->hw.aq.asq_last_status));
3008 	}
3009 }
3010 
3011 /**
3012  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
3013  * @vsi: the vsi being adjusted
3014  **/
3015 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
3016 {
3017 	struct i40e_vsi_context ctxt;
3018 	int ret;
3019 
3020 	/* Don't modify stripping options if a port VLAN is active */
3021 	if (vsi->info.pvid)
3022 		return;
3023 
3024 	if ((vsi->info.valid_sections &
3025 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
3026 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
3027 	     I40E_AQ_VSI_PVLAN_EMOD_MASK))
3028 		return;  /* already disabled */
3029 
3030 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3031 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3032 				    I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
3033 
3034 	ctxt.seid = vsi->seid;
3035 	ctxt.info = vsi->info;
3036 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3037 	if (ret) {
3038 		dev_info(&vsi->back->pdev->dev,
3039 			 "update vlan stripping failed, err %pe aq_err %s\n",
3040 			 ERR_PTR(ret),
3041 			 i40e_aq_str(&vsi->back->hw,
3042 				     vsi->back->hw.aq.asq_last_status));
3043 	}
3044 }
3045 
3046 /**
3047  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
3048  * @vsi: the vsi being configured
3049  * @vid: vlan id to be added (0 = untagged only , -1 = any)
3050  *
3051  * This is a helper function for adding a new MAC/VLAN filter with the
3052  * specified VLAN for each existing MAC address already in the hash table.
3053  * This function does *not* perform any accounting to update filters based on
3054  * VLAN mode.
3055  *
3056  * NOTE: this function expects to be called while under the
3057  * mac_filter_hash_lock
3058  **/
3059 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3060 {
3061 	struct i40e_mac_filter *f, *add_f;
3062 	struct hlist_node *h;
3063 	int bkt;
3064 
3065 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3066 		/* If we're asked to add a filter that has been marked for
3067 		 * removal, it is safe to simply restore it to active state.
3068 		 * __i40e_del_filter will have simply deleted any filters which
3069 		 * were previously marked NEW or FAILED, so if it is currently
3070 		 * marked REMOVE it must have previously been ACTIVE. Since we
3071 		 * haven't yet run the sync filters task, just restore this
3072 		 * filter to the ACTIVE state so that the sync task leaves it
3073 		 * in place.
3074 		 */
3075 		if (f->state == I40E_FILTER_REMOVE && f->vlan == vid) {
3076 			f->state = I40E_FILTER_ACTIVE;
3077 			continue;
3078 		} else if (f->state == I40E_FILTER_REMOVE) {
3079 			continue;
3080 		}
3081 		add_f = i40e_add_filter(vsi, f->macaddr, vid);
3082 		if (!add_f) {
3083 			dev_info(&vsi->back->pdev->dev,
3084 				 "Could not add vlan filter %d for %pM\n",
3085 				 vid, f->macaddr);
3086 			return -ENOMEM;
3087 		}
3088 	}
3089 
3090 	return 0;
3091 }
3092 
3093 /**
3094  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
3095  * @vsi: the VSI being configured
3096  * @vid: VLAN id to be added
3097  **/
3098 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
3099 {
3100 	int err;
3101 
3102 	if (vsi->info.pvid)
3103 		return -EINVAL;
3104 
3105 	/* The network stack will attempt to add VID=0, with the intention to
3106 	 * receive priority tagged packets with a VLAN of 0. Our HW receives
3107 	 * these packets by default when configured to receive untagged
3108 	 * packets, so we don't need to add a filter for this case.
3109 	 * Additionally, HW interprets adding a VID=0 filter as meaning to
3110 	 * receive *only* tagged traffic and stops receiving untagged traffic.
3111 	 * Thus, we do not want to actually add a filter for VID=0
3112 	 */
3113 	if (!vid)
3114 		return 0;
3115 
3116 	/* Locked once because all functions invoked below iterates list*/
3117 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3118 	err = i40e_add_vlan_all_mac(vsi, vid);
3119 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3120 	if (err)
3121 		return err;
3122 
3123 	/* schedule our worker thread which will take care of
3124 	 * applying the new filter changes
3125 	 */
3126 	i40e_service_event_schedule(vsi->back);
3127 	return 0;
3128 }
3129 
3130 /**
3131  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
3132  * @vsi: the vsi being configured
3133  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
3134  *
3135  * This function should be used to remove all VLAN filters which match the
3136  * given VID. It does not schedule the service event and does not take the
3137  * mac_filter_hash_lock so it may be combined with other operations under
3138  * a single invocation of the mac_filter_hash_lock.
3139  *
3140  * NOTE: this function expects to be called while under the
3141  * mac_filter_hash_lock
3142  */
3143 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3144 {
3145 	struct i40e_mac_filter *f;
3146 	struct hlist_node *h;
3147 	int bkt;
3148 
3149 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3150 		if (f->vlan == vid)
3151 			__i40e_del_filter(vsi, f);
3152 	}
3153 }
3154 
3155 /**
3156  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
3157  * @vsi: the VSI being configured
3158  * @vid: VLAN id to be removed
3159  **/
3160 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
3161 {
3162 	if (!vid || vsi->info.pvid)
3163 		return;
3164 
3165 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3166 	i40e_rm_vlan_all_mac(vsi, vid);
3167 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3168 
3169 	/* schedule our worker thread which will take care of
3170 	 * applying the new filter changes
3171 	 */
3172 	i40e_service_event_schedule(vsi->back);
3173 }
3174 
3175 /**
3176  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
3177  * @netdev: network interface to be adjusted
3178  * @proto: unused protocol value
3179  * @vid: vlan id to be added
3180  *
3181  * net_device_ops implementation for adding vlan ids
3182  **/
3183 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
3184 				__always_unused __be16 proto, u16 vid)
3185 {
3186 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3187 	struct i40e_vsi *vsi = np->vsi;
3188 	int ret = 0;
3189 
3190 	if (vid >= VLAN_N_VID)
3191 		return -EINVAL;
3192 
3193 	ret = i40e_vsi_add_vlan(vsi, vid);
3194 	if (!ret)
3195 		set_bit(vid, vsi->active_vlans);
3196 
3197 	return ret;
3198 }
3199 
3200 /**
3201  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
3202  * @netdev: network interface to be adjusted
3203  * @proto: unused protocol value
3204  * @vid: vlan id to be added
3205  **/
3206 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
3207 				    __always_unused __be16 proto, u16 vid)
3208 {
3209 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3210 	struct i40e_vsi *vsi = np->vsi;
3211 
3212 	if (vid >= VLAN_N_VID)
3213 		return;
3214 	set_bit(vid, vsi->active_vlans);
3215 }
3216 
3217 /**
3218  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
3219  * @netdev: network interface to be adjusted
3220  * @proto: unused protocol value
3221  * @vid: vlan id to be removed
3222  *
3223  * net_device_ops implementation for removing vlan ids
3224  **/
3225 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
3226 				 __always_unused __be16 proto, u16 vid)
3227 {
3228 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3229 	struct i40e_vsi *vsi = np->vsi;
3230 
3231 	/* return code is ignored as there is nothing a user
3232 	 * can do about failure to remove and a log message was
3233 	 * already printed from the other function
3234 	 */
3235 	i40e_vsi_kill_vlan(vsi, vid);
3236 
3237 	clear_bit(vid, vsi->active_vlans);
3238 
3239 	return 0;
3240 }
3241 
3242 /**
3243  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
3244  * @vsi: the vsi being brought back up
3245  **/
3246 static void i40e_restore_vlan(struct i40e_vsi *vsi)
3247 {
3248 	u16 vid;
3249 
3250 	if (!vsi->netdev)
3251 		return;
3252 
3253 	if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
3254 		i40e_vlan_stripping_enable(vsi);
3255 	else
3256 		i40e_vlan_stripping_disable(vsi);
3257 
3258 	for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
3259 		i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
3260 					vid);
3261 }
3262 
3263 /**
3264  * i40e_vsi_add_pvid - Add pvid for the VSI
3265  * @vsi: the vsi being adjusted
3266  * @vid: the vlan id to set as a PVID
3267  **/
3268 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
3269 {
3270 	struct i40e_vsi_context ctxt;
3271 	int ret;
3272 
3273 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3274 	vsi->info.pvid = cpu_to_le16(vid);
3275 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
3276 				    I40E_AQ_VSI_PVLAN_INSERT_PVID |
3277 				    I40E_AQ_VSI_PVLAN_EMOD_STR;
3278 
3279 	ctxt.seid = vsi->seid;
3280 	ctxt.info = vsi->info;
3281 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3282 	if (ret) {
3283 		dev_info(&vsi->back->pdev->dev,
3284 			 "add pvid failed, err %pe aq_err %s\n",
3285 			 ERR_PTR(ret),
3286 			 i40e_aq_str(&vsi->back->hw,
3287 				     vsi->back->hw.aq.asq_last_status));
3288 		return -ENOENT;
3289 	}
3290 
3291 	return 0;
3292 }
3293 
3294 /**
3295  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
3296  * @vsi: the vsi being adjusted
3297  *
3298  * Just use the vlan_rx_register() service to put it back to normal
3299  **/
3300 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
3301 {
3302 	vsi->info.pvid = 0;
3303 
3304 	i40e_vlan_stripping_disable(vsi);
3305 }
3306 
3307 /**
3308  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
3309  * @vsi: ptr to the VSI
3310  *
3311  * If this function returns with an error, then it's possible one or
3312  * more of the rings is populated (while the rest are not).  It is the
3313  * callers duty to clean those orphaned rings.
3314  *
3315  * Return 0 on success, negative on failure
3316  **/
3317 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3318 {
3319 	int i, err = 0;
3320 
3321 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3322 		err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3323 
3324 	if (!i40e_enabled_xdp_vsi(vsi))
3325 		return err;
3326 
3327 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3328 		err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3329 
3330 	return err;
3331 }
3332 
3333 /**
3334  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3335  * @vsi: ptr to the VSI
3336  *
3337  * Free VSI's transmit software resources
3338  **/
3339 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3340 {
3341 	int i;
3342 
3343 	if (vsi->tx_rings) {
3344 		for (i = 0; i < vsi->num_queue_pairs; i++)
3345 			if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3346 				i40e_free_tx_resources(vsi->tx_rings[i]);
3347 	}
3348 
3349 	if (vsi->xdp_rings) {
3350 		for (i = 0; i < vsi->num_queue_pairs; i++)
3351 			if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3352 				i40e_free_tx_resources(vsi->xdp_rings[i]);
3353 	}
3354 }
3355 
3356 /**
3357  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3358  * @vsi: ptr to the VSI
3359  *
3360  * If this function returns with an error, then it's possible one or
3361  * more of the rings is populated (while the rest are not).  It is the
3362  * callers duty to clean those orphaned rings.
3363  *
3364  * Return 0 on success, negative on failure
3365  **/
3366 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3367 {
3368 	int i, err = 0;
3369 
3370 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3371 		err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3372 	return err;
3373 }
3374 
3375 /**
3376  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3377  * @vsi: ptr to the VSI
3378  *
3379  * Free all receive software resources
3380  **/
3381 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3382 {
3383 	int i;
3384 
3385 	if (!vsi->rx_rings)
3386 		return;
3387 
3388 	for (i = 0; i < vsi->num_queue_pairs; i++)
3389 		if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3390 			i40e_free_rx_resources(vsi->rx_rings[i]);
3391 }
3392 
3393 /**
3394  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3395  * @ring: The Tx ring to configure
3396  *
3397  * This enables/disables XPS for a given Tx descriptor ring
3398  * based on the TCs enabled for the VSI that ring belongs to.
3399  **/
3400 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3401 {
3402 	int cpu;
3403 
3404 	if (!ring->q_vector || !ring->netdev || ring->ch)
3405 		return;
3406 
3407 	/* We only initialize XPS once, so as not to overwrite user settings */
3408 	if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3409 		return;
3410 
3411 	cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3412 	netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3413 			    ring->queue_index);
3414 }
3415 
3416 /**
3417  * i40e_xsk_pool - Retrieve the AF_XDP buffer pool if XDP and ZC is enabled
3418  * @ring: The Tx or Rx ring
3419  *
3420  * Returns the AF_XDP buffer pool or NULL.
3421  **/
3422 static struct xsk_buff_pool *i40e_xsk_pool(struct i40e_ring *ring)
3423 {
3424 	bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3425 	int qid = ring->queue_index;
3426 
3427 	if (ring_is_xdp(ring))
3428 		qid -= ring->vsi->alloc_queue_pairs;
3429 
3430 	if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3431 		return NULL;
3432 
3433 	return xsk_get_pool_from_qid(ring->vsi->netdev, qid);
3434 }
3435 
3436 /**
3437  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3438  * @ring: The Tx ring to configure
3439  *
3440  * Configure the Tx descriptor ring in the HMC context.
3441  **/
3442 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3443 {
3444 	struct i40e_vsi *vsi = ring->vsi;
3445 	u16 pf_q = vsi->base_queue + ring->queue_index;
3446 	struct i40e_hw *hw = &vsi->back->hw;
3447 	struct i40e_hmc_obj_txq tx_ctx;
3448 	u32 qtx_ctl = 0;
3449 	int err = 0;
3450 
3451 	if (ring_is_xdp(ring))
3452 		ring->xsk_pool = i40e_xsk_pool(ring);
3453 
3454 	/* some ATR related tx ring init */
3455 	if (vsi->back->flags & I40E_FLAG_FD_ATR_ENABLED) {
3456 		ring->atr_sample_rate = vsi->back->atr_sample_rate;
3457 		ring->atr_count = 0;
3458 	} else {
3459 		ring->atr_sample_rate = 0;
3460 	}
3461 
3462 	/* configure XPS */
3463 	i40e_config_xps_tx_ring(ring);
3464 
3465 	/* clear the context structure first */
3466 	memset(&tx_ctx, 0, sizeof(tx_ctx));
3467 
3468 	tx_ctx.new_context = 1;
3469 	tx_ctx.base = (ring->dma / 128);
3470 	tx_ctx.qlen = ring->count;
3471 	tx_ctx.fd_ena = !!(vsi->back->flags & (I40E_FLAG_FD_SB_ENABLED |
3472 					       I40E_FLAG_FD_ATR_ENABLED));
3473 	tx_ctx.timesync_ena = !!(vsi->back->flags & I40E_FLAG_PTP);
3474 	/* FDIR VSI tx ring can still use RS bit and writebacks */
3475 	if (vsi->type != I40E_VSI_FDIR)
3476 		tx_ctx.head_wb_ena = 1;
3477 	tx_ctx.head_wb_addr = ring->dma +
3478 			      (ring->count * sizeof(struct i40e_tx_desc));
3479 
3480 	/* As part of VSI creation/update, FW allocates certain
3481 	 * Tx arbitration queue sets for each TC enabled for
3482 	 * the VSI. The FW returns the handles to these queue
3483 	 * sets as part of the response buffer to Add VSI,
3484 	 * Update VSI, etc. AQ commands. It is expected that
3485 	 * these queue set handles be associated with the Tx
3486 	 * queues by the driver as part of the TX queue context
3487 	 * initialization. This has to be done regardless of
3488 	 * DCB as by default everything is mapped to TC0.
3489 	 */
3490 
3491 	if (ring->ch)
3492 		tx_ctx.rdylist =
3493 			le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3494 
3495 	else
3496 		tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3497 
3498 	tx_ctx.rdylist_act = 0;
3499 
3500 	/* clear the context in the HMC */
3501 	err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3502 	if (err) {
3503 		dev_info(&vsi->back->pdev->dev,
3504 			 "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3505 			 ring->queue_index, pf_q, err);
3506 		return -ENOMEM;
3507 	}
3508 
3509 	/* set the context in the HMC */
3510 	err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3511 	if (err) {
3512 		dev_info(&vsi->back->pdev->dev,
3513 			 "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3514 			 ring->queue_index, pf_q, err);
3515 		return -ENOMEM;
3516 	}
3517 
3518 	/* Now associate this queue with this PCI function */
3519 	if (ring->ch) {
3520 		if (ring->ch->type == I40E_VSI_VMDQ2)
3521 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3522 		else
3523 			return -EINVAL;
3524 
3525 		qtx_ctl |= (ring->ch->vsi_number <<
3526 			    I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3527 			    I40E_QTX_CTL_VFVM_INDX_MASK;
3528 	} else {
3529 		if (vsi->type == I40E_VSI_VMDQ2) {
3530 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3531 			qtx_ctl |= ((vsi->id) << I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3532 				    I40E_QTX_CTL_VFVM_INDX_MASK;
3533 		} else {
3534 			qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3535 		}
3536 	}
3537 
3538 	qtx_ctl |= ((hw->pf_id << I40E_QTX_CTL_PF_INDX_SHIFT) &
3539 		    I40E_QTX_CTL_PF_INDX_MASK);
3540 	wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3541 	i40e_flush(hw);
3542 
3543 	/* cache tail off for easier writes later */
3544 	ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3545 
3546 	return 0;
3547 }
3548 
3549 /**
3550  * i40e_rx_offset - Return expected offset into page to access data
3551  * @rx_ring: Ring we are requesting offset of
3552  *
3553  * Returns the offset value for ring into the data buffer.
3554  */
3555 static unsigned int i40e_rx_offset(struct i40e_ring *rx_ring)
3556 {
3557 	return ring_uses_build_skb(rx_ring) ? I40E_SKB_PAD : 0;
3558 }
3559 
3560 /**
3561  * i40e_configure_rx_ring - Configure a receive ring context
3562  * @ring: The Rx ring to configure
3563  *
3564  * Configure the Rx descriptor ring in the HMC context.
3565  **/
3566 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3567 {
3568 	struct i40e_vsi *vsi = ring->vsi;
3569 	u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3570 	u16 pf_q = vsi->base_queue + ring->queue_index;
3571 	struct i40e_hw *hw = &vsi->back->hw;
3572 	struct i40e_hmc_obj_rxq rx_ctx;
3573 	int err = 0;
3574 	bool ok;
3575 	int ret;
3576 
3577 	bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3578 
3579 	/* clear the context structure first */
3580 	memset(&rx_ctx, 0, sizeof(rx_ctx));
3581 
3582 	if (ring->vsi->type == I40E_VSI_MAIN)
3583 		xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq);
3584 
3585 	ring->xsk_pool = i40e_xsk_pool(ring);
3586 	if (ring->xsk_pool) {
3587 		ring->rx_buf_len =
3588 		  xsk_pool_get_rx_frame_size(ring->xsk_pool);
3589 		ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3590 						 MEM_TYPE_XSK_BUFF_POOL,
3591 						 NULL);
3592 		if (ret)
3593 			return ret;
3594 		dev_info(&vsi->back->pdev->dev,
3595 			 "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n",
3596 			 ring->queue_index);
3597 
3598 	} else {
3599 		ring->rx_buf_len = vsi->rx_buf_len;
3600 		if (ring->vsi->type == I40E_VSI_MAIN) {
3601 			ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3602 							 MEM_TYPE_PAGE_SHARED,
3603 							 NULL);
3604 			if (ret)
3605 				return ret;
3606 		}
3607 	}
3608 
3609 	xdp_init_buff(&ring->xdp, i40e_rx_pg_size(ring) / 2, &ring->xdp_rxq);
3610 
3611 	rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3612 				    BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3613 
3614 	rx_ctx.base = (ring->dma / 128);
3615 	rx_ctx.qlen = ring->count;
3616 
3617 	/* use 16 byte descriptors */
3618 	rx_ctx.dsize = 0;
3619 
3620 	/* descriptor type is always zero
3621 	 * rx_ctx.dtype = 0;
3622 	 */
3623 	rx_ctx.hsplit_0 = 0;
3624 
3625 	rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3626 	if (hw->revision_id == 0)
3627 		rx_ctx.lrxqthresh = 0;
3628 	else
3629 		rx_ctx.lrxqthresh = 1;
3630 	rx_ctx.crcstrip = 1;
3631 	rx_ctx.l2tsel = 1;
3632 	/* this controls whether VLAN is stripped from inner headers */
3633 	rx_ctx.showiv = 0;
3634 	/* set the prefena field to 1 because the manual says to */
3635 	rx_ctx.prefena = 1;
3636 
3637 	/* clear the context in the HMC */
3638 	err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3639 	if (err) {
3640 		dev_info(&vsi->back->pdev->dev,
3641 			 "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3642 			 ring->queue_index, pf_q, err);
3643 		return -ENOMEM;
3644 	}
3645 
3646 	/* set the context in the HMC */
3647 	err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3648 	if (err) {
3649 		dev_info(&vsi->back->pdev->dev,
3650 			 "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3651 			 ring->queue_index, pf_q, err);
3652 		return -ENOMEM;
3653 	}
3654 
3655 	/* configure Rx buffer alignment */
3656 	if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX)) {
3657 		if (I40E_2K_TOO_SMALL_WITH_PADDING) {
3658 			dev_info(&vsi->back->pdev->dev,
3659 				 "2k Rx buffer is too small to fit standard MTU and skb_shared_info\n");
3660 			return -EOPNOTSUPP;
3661 		}
3662 		clear_ring_build_skb_enabled(ring);
3663 	} else {
3664 		set_ring_build_skb_enabled(ring);
3665 	}
3666 
3667 	ring->rx_offset = i40e_rx_offset(ring);
3668 
3669 	/* cache tail for quicker writes, and clear the reg before use */
3670 	ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3671 	writel(0, ring->tail);
3672 
3673 	if (ring->xsk_pool) {
3674 		xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
3675 		ok = i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring));
3676 	} else {
3677 		ok = !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3678 	}
3679 	if (!ok) {
3680 		/* Log this in case the user has forgotten to give the kernel
3681 		 * any buffers, even later in the application.
3682 		 */
3683 		dev_info(&vsi->back->pdev->dev,
3684 			 "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3685 			 ring->xsk_pool ? "AF_XDP ZC enabled " : "",
3686 			 ring->queue_index, pf_q);
3687 	}
3688 
3689 	return 0;
3690 }
3691 
3692 /**
3693  * i40e_vsi_configure_tx - Configure the VSI for Tx
3694  * @vsi: VSI structure describing this set of rings and resources
3695  *
3696  * Configure the Tx VSI for operation.
3697  **/
3698 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3699 {
3700 	int err = 0;
3701 	u16 i;
3702 
3703 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3704 		err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3705 
3706 	if (err || !i40e_enabled_xdp_vsi(vsi))
3707 		return err;
3708 
3709 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3710 		err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3711 
3712 	return err;
3713 }
3714 
3715 /**
3716  * i40e_vsi_configure_rx - Configure the VSI for Rx
3717  * @vsi: the VSI being configured
3718  *
3719  * Configure the Rx VSI for operation.
3720  **/
3721 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3722 {
3723 	int err = 0;
3724 	u16 i;
3725 
3726 	vsi->max_frame = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
3727 	vsi->rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
3728 
3729 #if (PAGE_SIZE < 8192)
3730 	if (vsi->netdev && !I40E_2K_TOO_SMALL_WITH_PADDING &&
3731 	    vsi->netdev->mtu <= ETH_DATA_LEN) {
3732 		vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3733 		vsi->max_frame = vsi->rx_buf_len;
3734 	}
3735 #endif
3736 
3737 	/* set up individual rings */
3738 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3739 		err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3740 
3741 	return err;
3742 }
3743 
3744 /**
3745  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3746  * @vsi: ptr to the VSI
3747  **/
3748 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3749 {
3750 	struct i40e_ring *tx_ring, *rx_ring;
3751 	u16 qoffset, qcount;
3752 	int i, n;
3753 
3754 	if (!(vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
3755 		/* Reset the TC information */
3756 		for (i = 0; i < vsi->num_queue_pairs; i++) {
3757 			rx_ring = vsi->rx_rings[i];
3758 			tx_ring = vsi->tx_rings[i];
3759 			rx_ring->dcb_tc = 0;
3760 			tx_ring->dcb_tc = 0;
3761 		}
3762 		return;
3763 	}
3764 
3765 	for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3766 		if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3767 			continue;
3768 
3769 		qoffset = vsi->tc_config.tc_info[n].qoffset;
3770 		qcount = vsi->tc_config.tc_info[n].qcount;
3771 		for (i = qoffset; i < (qoffset + qcount); i++) {
3772 			rx_ring = vsi->rx_rings[i];
3773 			tx_ring = vsi->tx_rings[i];
3774 			rx_ring->dcb_tc = n;
3775 			tx_ring->dcb_tc = n;
3776 		}
3777 	}
3778 }
3779 
3780 /**
3781  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3782  * @vsi: ptr to the VSI
3783  **/
3784 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3785 {
3786 	if (vsi->netdev)
3787 		i40e_set_rx_mode(vsi->netdev);
3788 }
3789 
3790 /**
3791  * i40e_reset_fdir_filter_cnt - Reset flow director filter counters
3792  * @pf: Pointer to the targeted PF
3793  *
3794  * Set all flow director counters to 0.
3795  */
3796 static void i40e_reset_fdir_filter_cnt(struct i40e_pf *pf)
3797 {
3798 	pf->fd_tcp4_filter_cnt = 0;
3799 	pf->fd_udp4_filter_cnt = 0;
3800 	pf->fd_sctp4_filter_cnt = 0;
3801 	pf->fd_ip4_filter_cnt = 0;
3802 	pf->fd_tcp6_filter_cnt = 0;
3803 	pf->fd_udp6_filter_cnt = 0;
3804 	pf->fd_sctp6_filter_cnt = 0;
3805 	pf->fd_ip6_filter_cnt = 0;
3806 }
3807 
3808 /**
3809  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3810  * @vsi: Pointer to the targeted VSI
3811  *
3812  * This function replays the hlist on the hw where all the SB Flow Director
3813  * filters were saved.
3814  **/
3815 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3816 {
3817 	struct i40e_fdir_filter *filter;
3818 	struct i40e_pf *pf = vsi->back;
3819 	struct hlist_node *node;
3820 
3821 	if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
3822 		return;
3823 
3824 	/* Reset FDir counters as we're replaying all existing filters */
3825 	i40e_reset_fdir_filter_cnt(pf);
3826 
3827 	hlist_for_each_entry_safe(filter, node,
3828 				  &pf->fdir_filter_list, fdir_node) {
3829 		i40e_add_del_fdir(vsi, filter, true);
3830 	}
3831 }
3832 
3833 /**
3834  * i40e_vsi_configure - Set up the VSI for action
3835  * @vsi: the VSI being configured
3836  **/
3837 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3838 {
3839 	int err;
3840 
3841 	i40e_set_vsi_rx_mode(vsi);
3842 	i40e_restore_vlan(vsi);
3843 	i40e_vsi_config_dcb_rings(vsi);
3844 	err = i40e_vsi_configure_tx(vsi);
3845 	if (!err)
3846 		err = i40e_vsi_configure_rx(vsi);
3847 
3848 	return err;
3849 }
3850 
3851 /**
3852  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3853  * @vsi: the VSI being configured
3854  **/
3855 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3856 {
3857 	bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3858 	struct i40e_pf *pf = vsi->back;
3859 	struct i40e_hw *hw = &pf->hw;
3860 	u16 vector;
3861 	int i, q;
3862 	u32 qp;
3863 
3864 	/* The interrupt indexing is offset by 1 in the PFINT_ITRn
3865 	 * and PFINT_LNKLSTn registers, e.g.:
3866 	 *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3867 	 */
3868 	qp = vsi->base_queue;
3869 	vector = vsi->base_vector;
3870 	for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3871 		struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3872 
3873 		q_vector->rx.next_update = jiffies + 1;
3874 		q_vector->rx.target_itr =
3875 			ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3876 		wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3877 		     q_vector->rx.target_itr >> 1);
3878 		q_vector->rx.current_itr = q_vector->rx.target_itr;
3879 
3880 		q_vector->tx.next_update = jiffies + 1;
3881 		q_vector->tx.target_itr =
3882 			ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3883 		wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3884 		     q_vector->tx.target_itr >> 1);
3885 		q_vector->tx.current_itr = q_vector->tx.target_itr;
3886 
3887 		wr32(hw, I40E_PFINT_RATEN(vector - 1),
3888 		     i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3889 
3890 		/* begin of linked list for RX queue assigned to this vector */
3891 		wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3892 		for (q = 0; q < q_vector->num_ringpairs; q++) {
3893 			u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3894 			u32 val;
3895 
3896 			val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3897 			      (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3898 			      (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3899 			      (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3900 			      (I40E_QUEUE_TYPE_TX <<
3901 			       I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3902 
3903 			wr32(hw, I40E_QINT_RQCTL(qp), val);
3904 
3905 			if (has_xdp) {
3906 				/* TX queue with next queue set to TX */
3907 				val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3908 				      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3909 				      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3910 				      (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3911 				      (I40E_QUEUE_TYPE_TX <<
3912 				       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3913 
3914 				wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3915 			}
3916 			/* TX queue with next RX or end of linked list */
3917 			val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3918 			      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3919 			      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3920 			      ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3921 			      (I40E_QUEUE_TYPE_RX <<
3922 			       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3923 
3924 			/* Terminate the linked list */
3925 			if (q == (q_vector->num_ringpairs - 1))
3926 				val |= (I40E_QUEUE_END_OF_LIST <<
3927 					I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3928 
3929 			wr32(hw, I40E_QINT_TQCTL(qp), val);
3930 			qp++;
3931 		}
3932 	}
3933 
3934 	i40e_flush(hw);
3935 }
3936 
3937 /**
3938  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3939  * @pf: pointer to private device data structure
3940  **/
3941 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3942 {
3943 	struct i40e_hw *hw = &pf->hw;
3944 	u32 val;
3945 
3946 	/* clear things first */
3947 	wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3948 	rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3949 
3950 	val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3951 	      I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3952 	      I40E_PFINT_ICR0_ENA_GRST_MASK          |
3953 	      I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3954 	      I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3955 	      I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3956 	      I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3957 	      I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3958 
3959 	if (pf->flags & I40E_FLAG_IWARP_ENABLED)
3960 		val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3961 
3962 	if (pf->flags & I40E_FLAG_PTP)
3963 		val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3964 
3965 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
3966 
3967 	/* SW_ITR_IDX = 0, but don't change INTENA */
3968 	wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3969 					I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
3970 
3971 	/* OTHER_ITR_IDX = 0 */
3972 	wr32(hw, I40E_PFINT_STAT_CTL0, 0);
3973 }
3974 
3975 /**
3976  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
3977  * @vsi: the VSI being configured
3978  **/
3979 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
3980 {
3981 	u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
3982 	struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3983 	struct i40e_pf *pf = vsi->back;
3984 	struct i40e_hw *hw = &pf->hw;
3985 
3986 	/* set the ITR configuration */
3987 	q_vector->rx.next_update = jiffies + 1;
3988 	q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
3989 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr >> 1);
3990 	q_vector->rx.current_itr = q_vector->rx.target_itr;
3991 	q_vector->tx.next_update = jiffies + 1;
3992 	q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
3993 	wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr >> 1);
3994 	q_vector->tx.current_itr = q_vector->tx.target_itr;
3995 
3996 	i40e_enable_misc_int_causes(pf);
3997 
3998 	/* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
3999 	wr32(hw, I40E_PFINT_LNKLST0, 0);
4000 
4001 	/* Associate the queue pair to the vector and enable the queue
4002 	 * interrupt RX queue in linked list with next queue set to TX
4003 	 */
4004 	wr32(hw, I40E_QINT_RQCTL(0), I40E_QINT_RQCTL_VAL(nextqp, 0, TX));
4005 
4006 	if (i40e_enabled_xdp_vsi(vsi)) {
4007 		/* TX queue in linked list with next queue set to TX */
4008 		wr32(hw, I40E_QINT_TQCTL(nextqp),
4009 		     I40E_QINT_TQCTL_VAL(nextqp, 0, TX));
4010 	}
4011 
4012 	/* last TX queue so the next RX queue doesn't matter */
4013 	wr32(hw, I40E_QINT_TQCTL(0),
4014 	     I40E_QINT_TQCTL_VAL(I40E_QUEUE_END_OF_LIST, 0, RX));
4015 	i40e_flush(hw);
4016 }
4017 
4018 /**
4019  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
4020  * @pf: board private structure
4021  **/
4022 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
4023 {
4024 	struct i40e_hw *hw = &pf->hw;
4025 
4026 	wr32(hw, I40E_PFINT_DYN_CTL0,
4027 	     I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
4028 	i40e_flush(hw);
4029 }
4030 
4031 /**
4032  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
4033  * @pf: board private structure
4034  **/
4035 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
4036 {
4037 	struct i40e_hw *hw = &pf->hw;
4038 	u32 val;
4039 
4040 	val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
4041 	      I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
4042 	      (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
4043 
4044 	wr32(hw, I40E_PFINT_DYN_CTL0, val);
4045 	i40e_flush(hw);
4046 }
4047 
4048 /**
4049  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
4050  * @irq: interrupt number
4051  * @data: pointer to a q_vector
4052  **/
4053 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
4054 {
4055 	struct i40e_q_vector *q_vector = data;
4056 
4057 	if (!q_vector->tx.ring && !q_vector->rx.ring)
4058 		return IRQ_HANDLED;
4059 
4060 	napi_schedule_irqoff(&q_vector->napi);
4061 
4062 	return IRQ_HANDLED;
4063 }
4064 
4065 /**
4066  * i40e_irq_affinity_notify - Callback for affinity changes
4067  * @notify: context as to what irq was changed
4068  * @mask: the new affinity mask
4069  *
4070  * This is a callback function used by the irq_set_affinity_notifier function
4071  * so that we may register to receive changes to the irq affinity masks.
4072  **/
4073 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
4074 				     const cpumask_t *mask)
4075 {
4076 	struct i40e_q_vector *q_vector =
4077 		container_of(notify, struct i40e_q_vector, affinity_notify);
4078 
4079 	cpumask_copy(&q_vector->affinity_mask, mask);
4080 }
4081 
4082 /**
4083  * i40e_irq_affinity_release - Callback for affinity notifier release
4084  * @ref: internal core kernel usage
4085  *
4086  * This is a callback function used by the irq_set_affinity_notifier function
4087  * to inform the current notification subscriber that they will no longer
4088  * receive notifications.
4089  **/
4090 static void i40e_irq_affinity_release(struct kref *ref) {}
4091 
4092 /**
4093  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
4094  * @vsi: the VSI being configured
4095  * @basename: name for the vector
4096  *
4097  * Allocates MSI-X vectors and requests interrupts from the kernel.
4098  **/
4099 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
4100 {
4101 	int q_vectors = vsi->num_q_vectors;
4102 	struct i40e_pf *pf = vsi->back;
4103 	int base = vsi->base_vector;
4104 	int rx_int_idx = 0;
4105 	int tx_int_idx = 0;
4106 	int vector, err;
4107 	int irq_num;
4108 	int cpu;
4109 
4110 	for (vector = 0; vector < q_vectors; vector++) {
4111 		struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
4112 
4113 		irq_num = pf->msix_entries[base + vector].vector;
4114 
4115 		if (q_vector->tx.ring && q_vector->rx.ring) {
4116 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4117 				 "%s-%s-%d", basename, "TxRx", rx_int_idx++);
4118 			tx_int_idx++;
4119 		} else if (q_vector->rx.ring) {
4120 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4121 				 "%s-%s-%d", basename, "rx", rx_int_idx++);
4122 		} else if (q_vector->tx.ring) {
4123 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4124 				 "%s-%s-%d", basename, "tx", tx_int_idx++);
4125 		} else {
4126 			/* skip this unused q_vector */
4127 			continue;
4128 		}
4129 		err = request_irq(irq_num,
4130 				  vsi->irq_handler,
4131 				  0,
4132 				  q_vector->name,
4133 				  q_vector);
4134 		if (err) {
4135 			dev_info(&pf->pdev->dev,
4136 				 "MSIX request_irq failed, error: %d\n", err);
4137 			goto free_queue_irqs;
4138 		}
4139 
4140 		/* register for affinity change notifications */
4141 		q_vector->irq_num = irq_num;
4142 		q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
4143 		q_vector->affinity_notify.release = i40e_irq_affinity_release;
4144 		irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
4145 		/* Spread affinity hints out across online CPUs.
4146 		 *
4147 		 * get_cpu_mask returns a static constant mask with
4148 		 * a permanent lifetime so it's ok to pass to
4149 		 * irq_update_affinity_hint without making a copy.
4150 		 */
4151 		cpu = cpumask_local_spread(q_vector->v_idx, -1);
4152 		irq_update_affinity_hint(irq_num, get_cpu_mask(cpu));
4153 	}
4154 
4155 	vsi->irqs_ready = true;
4156 	return 0;
4157 
4158 free_queue_irqs:
4159 	while (vector) {
4160 		vector--;
4161 		irq_num = pf->msix_entries[base + vector].vector;
4162 		irq_set_affinity_notifier(irq_num, NULL);
4163 		irq_update_affinity_hint(irq_num, NULL);
4164 		free_irq(irq_num, &vsi->q_vectors[vector]);
4165 	}
4166 	return err;
4167 }
4168 
4169 /**
4170  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
4171  * @vsi: the VSI being un-configured
4172  **/
4173 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
4174 {
4175 	struct i40e_pf *pf = vsi->back;
4176 	struct i40e_hw *hw = &pf->hw;
4177 	int base = vsi->base_vector;
4178 	int i;
4179 
4180 	/* disable interrupt causation from each queue */
4181 	for (i = 0; i < vsi->num_queue_pairs; i++) {
4182 		u32 val;
4183 
4184 		val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
4185 		val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
4186 		wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
4187 
4188 		val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
4189 		val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
4190 		wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
4191 
4192 		if (!i40e_enabled_xdp_vsi(vsi))
4193 			continue;
4194 		wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
4195 	}
4196 
4197 	/* disable each interrupt */
4198 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4199 		for (i = vsi->base_vector;
4200 		     i < (vsi->num_q_vectors + vsi->base_vector); i++)
4201 			wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
4202 
4203 		i40e_flush(hw);
4204 		for (i = 0; i < vsi->num_q_vectors; i++)
4205 			synchronize_irq(pf->msix_entries[i + base].vector);
4206 	} else {
4207 		/* Legacy and MSI mode - this stops all interrupt handling */
4208 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
4209 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
4210 		i40e_flush(hw);
4211 		synchronize_irq(pf->pdev->irq);
4212 	}
4213 }
4214 
4215 /**
4216  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
4217  * @vsi: the VSI being configured
4218  **/
4219 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
4220 {
4221 	struct i40e_pf *pf = vsi->back;
4222 	int i;
4223 
4224 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4225 		for (i = 0; i < vsi->num_q_vectors; i++)
4226 			i40e_irq_dynamic_enable(vsi, i);
4227 	} else {
4228 		i40e_irq_dynamic_enable_icr0(pf);
4229 	}
4230 
4231 	i40e_flush(&pf->hw);
4232 	return 0;
4233 }
4234 
4235 /**
4236  * i40e_free_misc_vector - Free the vector that handles non-queue events
4237  * @pf: board private structure
4238  **/
4239 static void i40e_free_misc_vector(struct i40e_pf *pf)
4240 {
4241 	/* Disable ICR 0 */
4242 	wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
4243 	i40e_flush(&pf->hw);
4244 
4245 	if (pf->flags & I40E_FLAG_MSIX_ENABLED && pf->msix_entries) {
4246 		free_irq(pf->msix_entries[0].vector, pf);
4247 		clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
4248 	}
4249 }
4250 
4251 /**
4252  * i40e_intr - MSI/Legacy and non-queue interrupt handler
4253  * @irq: interrupt number
4254  * @data: pointer to a q_vector
4255  *
4256  * This is the handler used for all MSI/Legacy interrupts, and deals
4257  * with both queue and non-queue interrupts.  This is also used in
4258  * MSIX mode to handle the non-queue interrupts.
4259  **/
4260 static irqreturn_t i40e_intr(int irq, void *data)
4261 {
4262 	struct i40e_pf *pf = (struct i40e_pf *)data;
4263 	struct i40e_hw *hw = &pf->hw;
4264 	irqreturn_t ret = IRQ_NONE;
4265 	u32 icr0, icr0_remaining;
4266 	u32 val, ena_mask;
4267 
4268 	icr0 = rd32(hw, I40E_PFINT_ICR0);
4269 	ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
4270 
4271 	/* if sharing a legacy IRQ, we might get called w/o an intr pending */
4272 	if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
4273 		goto enable_intr;
4274 
4275 	/* if interrupt but no bits showing, must be SWINT */
4276 	if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
4277 	    (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
4278 		pf->sw_int_count++;
4279 
4280 	if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
4281 	    (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
4282 		ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4283 		dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
4284 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
4285 	}
4286 
4287 	/* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
4288 	if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
4289 		struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
4290 		struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4291 
4292 		/* We do not have a way to disarm Queue causes while leaving
4293 		 * interrupt enabled for all other causes, ideally
4294 		 * interrupt should be disabled while we are in NAPI but
4295 		 * this is not a performance path and napi_schedule()
4296 		 * can deal with rescheduling.
4297 		 */
4298 		if (!test_bit(__I40E_DOWN, pf->state))
4299 			napi_schedule_irqoff(&q_vector->napi);
4300 	}
4301 
4302 	if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
4303 		ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
4304 		set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
4305 		i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
4306 	}
4307 
4308 	if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
4309 		ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
4310 		set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
4311 	}
4312 
4313 	if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
4314 		/* disable any further VFLR event notifications */
4315 		if (test_bit(__I40E_VF_RESETS_DISABLED, pf->state)) {
4316 			u32 reg = rd32(hw, I40E_PFINT_ICR0_ENA);
4317 
4318 			reg &= ~I40E_PFINT_ICR0_VFLR_MASK;
4319 			wr32(hw, I40E_PFINT_ICR0_ENA, reg);
4320 		} else {
4321 			ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
4322 			set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
4323 		}
4324 	}
4325 
4326 	if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
4327 		if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4328 			set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
4329 		ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
4330 		val = rd32(hw, I40E_GLGEN_RSTAT);
4331 		val = (val & I40E_GLGEN_RSTAT_RESET_TYPE_MASK)
4332 		       >> I40E_GLGEN_RSTAT_RESET_TYPE_SHIFT;
4333 		if (val == I40E_RESET_CORER) {
4334 			pf->corer_count++;
4335 		} else if (val == I40E_RESET_GLOBR) {
4336 			pf->globr_count++;
4337 		} else if (val == I40E_RESET_EMPR) {
4338 			pf->empr_count++;
4339 			set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
4340 		}
4341 	}
4342 
4343 	if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
4344 		icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
4345 		dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4346 		dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4347 			 rd32(hw, I40E_PFHMC_ERRORINFO),
4348 			 rd32(hw, I40E_PFHMC_ERRORDATA));
4349 	}
4350 
4351 	if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4352 		u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4353 
4354 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_EVENT0_MASK)
4355 			schedule_work(&pf->ptp_extts0_work);
4356 
4357 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK)
4358 			i40e_ptp_tx_hwtstamp(pf);
4359 
4360 		icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4361 	}
4362 
4363 	/* If a critical error is pending we have no choice but to reset the
4364 	 * device.
4365 	 * Report and mask out any remaining unexpected interrupts.
4366 	 */
4367 	icr0_remaining = icr0 & ena_mask;
4368 	if (icr0_remaining) {
4369 		dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4370 			 icr0_remaining);
4371 		if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4372 		    (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4373 		    (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4374 			dev_info(&pf->pdev->dev, "device will be reset\n");
4375 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4376 			i40e_service_event_schedule(pf);
4377 		}
4378 		ena_mask &= ~icr0_remaining;
4379 	}
4380 	ret = IRQ_HANDLED;
4381 
4382 enable_intr:
4383 	/* re-enable interrupt causes */
4384 	wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4385 	if (!test_bit(__I40E_DOWN, pf->state) ||
4386 	    test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4387 		i40e_service_event_schedule(pf);
4388 		i40e_irq_dynamic_enable_icr0(pf);
4389 	}
4390 
4391 	return ret;
4392 }
4393 
4394 /**
4395  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4396  * @tx_ring:  tx ring to clean
4397  * @budget:   how many cleans we're allowed
4398  *
4399  * Returns true if there's any budget left (e.g. the clean is finished)
4400  **/
4401 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4402 {
4403 	struct i40e_vsi *vsi = tx_ring->vsi;
4404 	u16 i = tx_ring->next_to_clean;
4405 	struct i40e_tx_buffer *tx_buf;
4406 	struct i40e_tx_desc *tx_desc;
4407 
4408 	tx_buf = &tx_ring->tx_bi[i];
4409 	tx_desc = I40E_TX_DESC(tx_ring, i);
4410 	i -= tx_ring->count;
4411 
4412 	do {
4413 		struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4414 
4415 		/* if next_to_watch is not set then there is no work pending */
4416 		if (!eop_desc)
4417 			break;
4418 
4419 		/* prevent any other reads prior to eop_desc */
4420 		smp_rmb();
4421 
4422 		/* if the descriptor isn't done, no work yet to do */
4423 		if (!(eop_desc->cmd_type_offset_bsz &
4424 		      cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4425 			break;
4426 
4427 		/* clear next_to_watch to prevent false hangs */
4428 		tx_buf->next_to_watch = NULL;
4429 
4430 		tx_desc->buffer_addr = 0;
4431 		tx_desc->cmd_type_offset_bsz = 0;
4432 		/* move past filter desc */
4433 		tx_buf++;
4434 		tx_desc++;
4435 		i++;
4436 		if (unlikely(!i)) {
4437 			i -= tx_ring->count;
4438 			tx_buf = tx_ring->tx_bi;
4439 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4440 		}
4441 		/* unmap skb header data */
4442 		dma_unmap_single(tx_ring->dev,
4443 				 dma_unmap_addr(tx_buf, dma),
4444 				 dma_unmap_len(tx_buf, len),
4445 				 DMA_TO_DEVICE);
4446 		if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4447 			kfree(tx_buf->raw_buf);
4448 
4449 		tx_buf->raw_buf = NULL;
4450 		tx_buf->tx_flags = 0;
4451 		tx_buf->next_to_watch = NULL;
4452 		dma_unmap_len_set(tx_buf, len, 0);
4453 		tx_desc->buffer_addr = 0;
4454 		tx_desc->cmd_type_offset_bsz = 0;
4455 
4456 		/* move us past the eop_desc for start of next FD desc */
4457 		tx_buf++;
4458 		tx_desc++;
4459 		i++;
4460 		if (unlikely(!i)) {
4461 			i -= tx_ring->count;
4462 			tx_buf = tx_ring->tx_bi;
4463 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4464 		}
4465 
4466 		/* update budget accounting */
4467 		budget--;
4468 	} while (likely(budget));
4469 
4470 	i += tx_ring->count;
4471 	tx_ring->next_to_clean = i;
4472 
4473 	if (vsi->back->flags & I40E_FLAG_MSIX_ENABLED)
4474 		i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4475 
4476 	return budget > 0;
4477 }
4478 
4479 /**
4480  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4481  * @irq: interrupt number
4482  * @data: pointer to a q_vector
4483  **/
4484 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4485 {
4486 	struct i40e_q_vector *q_vector = data;
4487 	struct i40e_vsi *vsi;
4488 
4489 	if (!q_vector->tx.ring)
4490 		return IRQ_HANDLED;
4491 
4492 	vsi = q_vector->tx.ring->vsi;
4493 	i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4494 
4495 	return IRQ_HANDLED;
4496 }
4497 
4498 /**
4499  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4500  * @vsi: the VSI being configured
4501  * @v_idx: vector index
4502  * @qp_idx: queue pair index
4503  **/
4504 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4505 {
4506 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4507 	struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4508 	struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4509 
4510 	tx_ring->q_vector = q_vector;
4511 	tx_ring->next = q_vector->tx.ring;
4512 	q_vector->tx.ring = tx_ring;
4513 	q_vector->tx.count++;
4514 
4515 	/* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4516 	if (i40e_enabled_xdp_vsi(vsi)) {
4517 		struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4518 
4519 		xdp_ring->q_vector = q_vector;
4520 		xdp_ring->next = q_vector->tx.ring;
4521 		q_vector->tx.ring = xdp_ring;
4522 		q_vector->tx.count++;
4523 	}
4524 
4525 	rx_ring->q_vector = q_vector;
4526 	rx_ring->next = q_vector->rx.ring;
4527 	q_vector->rx.ring = rx_ring;
4528 	q_vector->rx.count++;
4529 }
4530 
4531 /**
4532  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4533  * @vsi: the VSI being configured
4534  *
4535  * This function maps descriptor rings to the queue-specific vectors
4536  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4537  * one vector per queue pair, but on a constrained vector budget, we
4538  * group the queue pairs as "efficiently" as possible.
4539  **/
4540 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4541 {
4542 	int qp_remaining = vsi->num_queue_pairs;
4543 	int q_vectors = vsi->num_q_vectors;
4544 	int num_ringpairs;
4545 	int v_start = 0;
4546 	int qp_idx = 0;
4547 
4548 	/* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4549 	 * group them so there are multiple queues per vector.
4550 	 * It is also important to go through all the vectors available to be
4551 	 * sure that if we don't use all the vectors, that the remaining vectors
4552 	 * are cleared. This is especially important when decreasing the
4553 	 * number of queues in use.
4554 	 */
4555 	for (; v_start < q_vectors; v_start++) {
4556 		struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4557 
4558 		num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4559 
4560 		q_vector->num_ringpairs = num_ringpairs;
4561 		q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4562 
4563 		q_vector->rx.count = 0;
4564 		q_vector->tx.count = 0;
4565 		q_vector->rx.ring = NULL;
4566 		q_vector->tx.ring = NULL;
4567 
4568 		while (num_ringpairs--) {
4569 			i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4570 			qp_idx++;
4571 			qp_remaining--;
4572 		}
4573 	}
4574 }
4575 
4576 /**
4577  * i40e_vsi_request_irq - Request IRQ from the OS
4578  * @vsi: the VSI being configured
4579  * @basename: name for the vector
4580  **/
4581 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4582 {
4583 	struct i40e_pf *pf = vsi->back;
4584 	int err;
4585 
4586 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
4587 		err = i40e_vsi_request_irq_msix(vsi, basename);
4588 	else if (pf->flags & I40E_FLAG_MSI_ENABLED)
4589 		err = request_irq(pf->pdev->irq, i40e_intr, 0,
4590 				  pf->int_name, pf);
4591 	else
4592 		err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4593 				  pf->int_name, pf);
4594 
4595 	if (err)
4596 		dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4597 
4598 	return err;
4599 }
4600 
4601 #ifdef CONFIG_NET_POLL_CONTROLLER
4602 /**
4603  * i40e_netpoll - A Polling 'interrupt' handler
4604  * @netdev: network interface device structure
4605  *
4606  * This is used by netconsole to send skbs without having to re-enable
4607  * interrupts.  It's not called while the normal interrupt routine is executing.
4608  **/
4609 static void i40e_netpoll(struct net_device *netdev)
4610 {
4611 	struct i40e_netdev_priv *np = netdev_priv(netdev);
4612 	struct i40e_vsi *vsi = np->vsi;
4613 	struct i40e_pf *pf = vsi->back;
4614 	int i;
4615 
4616 	/* if interface is down do nothing */
4617 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
4618 		return;
4619 
4620 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4621 		for (i = 0; i < vsi->num_q_vectors; i++)
4622 			i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4623 	} else {
4624 		i40e_intr(pf->pdev->irq, netdev);
4625 	}
4626 }
4627 #endif
4628 
4629 #define I40E_QTX_ENA_WAIT_COUNT 50
4630 
4631 /**
4632  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4633  * @pf: the PF being configured
4634  * @pf_q: the PF queue
4635  * @enable: enable or disable state of the queue
4636  *
4637  * This routine will wait for the given Tx queue of the PF to reach the
4638  * enabled or disabled state.
4639  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4640  * multiple retries; else will return 0 in case of success.
4641  **/
4642 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4643 {
4644 	int i;
4645 	u32 tx_reg;
4646 
4647 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4648 		tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4649 		if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4650 			break;
4651 
4652 		usleep_range(10, 20);
4653 	}
4654 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4655 		return -ETIMEDOUT;
4656 
4657 	return 0;
4658 }
4659 
4660 /**
4661  * i40e_control_tx_q - Start or stop a particular Tx queue
4662  * @pf: the PF structure
4663  * @pf_q: the PF queue to configure
4664  * @enable: start or stop the queue
4665  *
4666  * This function enables or disables a single queue. Note that any delay
4667  * required after the operation is expected to be handled by the caller of
4668  * this function.
4669  **/
4670 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4671 {
4672 	struct i40e_hw *hw = &pf->hw;
4673 	u32 tx_reg;
4674 	int i;
4675 
4676 	/* warn the TX unit of coming changes */
4677 	i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4678 	if (!enable)
4679 		usleep_range(10, 20);
4680 
4681 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4682 		tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4683 		if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4684 		    ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4685 			break;
4686 		usleep_range(1000, 2000);
4687 	}
4688 
4689 	/* Skip if the queue is already in the requested state */
4690 	if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4691 		return;
4692 
4693 	/* turn on/off the queue */
4694 	if (enable) {
4695 		wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4696 		tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4697 	} else {
4698 		tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4699 	}
4700 
4701 	wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4702 }
4703 
4704 /**
4705  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4706  * @seid: VSI SEID
4707  * @pf: the PF structure
4708  * @pf_q: the PF queue to configure
4709  * @is_xdp: true if the queue is used for XDP
4710  * @enable: start or stop the queue
4711  **/
4712 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4713 			   bool is_xdp, bool enable)
4714 {
4715 	int ret;
4716 
4717 	i40e_control_tx_q(pf, pf_q, enable);
4718 
4719 	/* wait for the change to finish */
4720 	ret = i40e_pf_txq_wait(pf, pf_q, enable);
4721 	if (ret) {
4722 		dev_info(&pf->pdev->dev,
4723 			 "VSI seid %d %sTx ring %d %sable timeout\n",
4724 			 seid, (is_xdp ? "XDP " : ""), pf_q,
4725 			 (enable ? "en" : "dis"));
4726 	}
4727 
4728 	return ret;
4729 }
4730 
4731 /**
4732  * i40e_vsi_enable_tx - Start a VSI's rings
4733  * @vsi: the VSI being configured
4734  **/
4735 static int i40e_vsi_enable_tx(struct i40e_vsi *vsi)
4736 {
4737 	struct i40e_pf *pf = vsi->back;
4738 	int i, pf_q, ret = 0;
4739 
4740 	pf_q = vsi->base_queue;
4741 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4742 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4743 					     pf_q,
4744 					     false /*is xdp*/, true);
4745 		if (ret)
4746 			break;
4747 
4748 		if (!i40e_enabled_xdp_vsi(vsi))
4749 			continue;
4750 
4751 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4752 					     pf_q + vsi->alloc_queue_pairs,
4753 					     true /*is xdp*/, true);
4754 		if (ret)
4755 			break;
4756 	}
4757 	return ret;
4758 }
4759 
4760 /**
4761  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4762  * @pf: the PF being configured
4763  * @pf_q: the PF queue
4764  * @enable: enable or disable state of the queue
4765  *
4766  * This routine will wait for the given Rx queue of the PF to reach the
4767  * enabled or disabled state.
4768  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4769  * multiple retries; else will return 0 in case of success.
4770  **/
4771 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4772 {
4773 	int i;
4774 	u32 rx_reg;
4775 
4776 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4777 		rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4778 		if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4779 			break;
4780 
4781 		usleep_range(10, 20);
4782 	}
4783 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4784 		return -ETIMEDOUT;
4785 
4786 	return 0;
4787 }
4788 
4789 /**
4790  * i40e_control_rx_q - Start or stop a particular Rx queue
4791  * @pf: the PF structure
4792  * @pf_q: the PF queue to configure
4793  * @enable: start or stop the queue
4794  *
4795  * This function enables or disables a single queue. Note that
4796  * any delay required after the operation is expected to be
4797  * handled by the caller of this function.
4798  **/
4799 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4800 {
4801 	struct i40e_hw *hw = &pf->hw;
4802 	u32 rx_reg;
4803 	int i;
4804 
4805 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4806 		rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4807 		if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4808 		    ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4809 			break;
4810 		usleep_range(1000, 2000);
4811 	}
4812 
4813 	/* Skip if the queue is already in the requested state */
4814 	if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4815 		return;
4816 
4817 	/* turn on/off the queue */
4818 	if (enable)
4819 		rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4820 	else
4821 		rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4822 
4823 	wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4824 }
4825 
4826 /**
4827  * i40e_control_wait_rx_q
4828  * @pf: the PF structure
4829  * @pf_q: queue being configured
4830  * @enable: start or stop the rings
4831  *
4832  * This function enables or disables a single queue along with waiting
4833  * for the change to finish. The caller of this function should handle
4834  * the delays needed in the case of disabling queues.
4835  **/
4836 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4837 {
4838 	int ret = 0;
4839 
4840 	i40e_control_rx_q(pf, pf_q, enable);
4841 
4842 	/* wait for the change to finish */
4843 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4844 	if (ret)
4845 		return ret;
4846 
4847 	return ret;
4848 }
4849 
4850 /**
4851  * i40e_vsi_enable_rx - Start a VSI's rings
4852  * @vsi: the VSI being configured
4853  **/
4854 static int i40e_vsi_enable_rx(struct i40e_vsi *vsi)
4855 {
4856 	struct i40e_pf *pf = vsi->back;
4857 	int i, pf_q, ret = 0;
4858 
4859 	pf_q = vsi->base_queue;
4860 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4861 		ret = i40e_control_wait_rx_q(pf, pf_q, true);
4862 		if (ret) {
4863 			dev_info(&pf->pdev->dev,
4864 				 "VSI seid %d Rx ring %d enable timeout\n",
4865 				 vsi->seid, pf_q);
4866 			break;
4867 		}
4868 	}
4869 
4870 	return ret;
4871 }
4872 
4873 /**
4874  * i40e_vsi_start_rings - Start a VSI's rings
4875  * @vsi: the VSI being configured
4876  **/
4877 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4878 {
4879 	int ret = 0;
4880 
4881 	/* do rx first for enable and last for disable */
4882 	ret = i40e_vsi_enable_rx(vsi);
4883 	if (ret)
4884 		return ret;
4885 	ret = i40e_vsi_enable_tx(vsi);
4886 
4887 	return ret;
4888 }
4889 
4890 #define I40E_DISABLE_TX_GAP_MSEC	50
4891 
4892 /**
4893  * i40e_vsi_stop_rings - Stop a VSI's rings
4894  * @vsi: the VSI being configured
4895  **/
4896 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4897 {
4898 	struct i40e_pf *pf = vsi->back;
4899 	int pf_q, err, q_end;
4900 
4901 	/* When port TX is suspended, don't wait */
4902 	if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4903 		return i40e_vsi_stop_rings_no_wait(vsi);
4904 
4905 	q_end = vsi->base_queue + vsi->num_queue_pairs;
4906 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4907 		i40e_pre_tx_queue_cfg(&pf->hw, (u32)pf_q, false);
4908 
4909 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++) {
4910 		err = i40e_control_wait_rx_q(pf, pf_q, false);
4911 		if (err)
4912 			dev_info(&pf->pdev->dev,
4913 				 "VSI seid %d Rx ring %d disable timeout\n",
4914 				 vsi->seid, pf_q);
4915 	}
4916 
4917 	msleep(I40E_DISABLE_TX_GAP_MSEC);
4918 	pf_q = vsi->base_queue;
4919 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4920 		wr32(&pf->hw, I40E_QTX_ENA(pf_q), 0);
4921 
4922 	i40e_vsi_wait_queues_disabled(vsi);
4923 }
4924 
4925 /**
4926  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4927  * @vsi: the VSI being shutdown
4928  *
4929  * This function stops all the rings for a VSI but does not delay to verify
4930  * that rings have been disabled. It is expected that the caller is shutting
4931  * down multiple VSIs at once and will delay together for all the VSIs after
4932  * initiating the shutdown. This is particularly useful for shutting down lots
4933  * of VFs together. Otherwise, a large delay can be incurred while configuring
4934  * each VSI in serial.
4935  **/
4936 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4937 {
4938 	struct i40e_pf *pf = vsi->back;
4939 	int i, pf_q;
4940 
4941 	pf_q = vsi->base_queue;
4942 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4943 		i40e_control_tx_q(pf, pf_q, false);
4944 		i40e_control_rx_q(pf, pf_q, false);
4945 	}
4946 }
4947 
4948 /**
4949  * i40e_vsi_free_irq - Free the irq association with the OS
4950  * @vsi: the VSI being configured
4951  **/
4952 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4953 {
4954 	struct i40e_pf *pf = vsi->back;
4955 	struct i40e_hw *hw = &pf->hw;
4956 	int base = vsi->base_vector;
4957 	u32 val, qp;
4958 	int i;
4959 
4960 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4961 		if (!vsi->q_vectors)
4962 			return;
4963 
4964 		if (!vsi->irqs_ready)
4965 			return;
4966 
4967 		vsi->irqs_ready = false;
4968 		for (i = 0; i < vsi->num_q_vectors; i++) {
4969 			int irq_num;
4970 			u16 vector;
4971 
4972 			vector = i + base;
4973 			irq_num = pf->msix_entries[vector].vector;
4974 
4975 			/* free only the irqs that were actually requested */
4976 			if (!vsi->q_vectors[i] ||
4977 			    !vsi->q_vectors[i]->num_ringpairs)
4978 				continue;
4979 
4980 			/* clear the affinity notifier in the IRQ descriptor */
4981 			irq_set_affinity_notifier(irq_num, NULL);
4982 			/* remove our suggested affinity mask for this IRQ */
4983 			irq_update_affinity_hint(irq_num, NULL);
4984 			free_irq(irq_num, vsi->q_vectors[i]);
4985 
4986 			/* Tear down the interrupt queue link list
4987 			 *
4988 			 * We know that they come in pairs and always
4989 			 * the Rx first, then the Tx.  To clear the
4990 			 * link list, stick the EOL value into the
4991 			 * next_q field of the registers.
4992 			 */
4993 			val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
4994 			qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4995 				>> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4996 			val |= I40E_QUEUE_END_OF_LIST
4997 				<< I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4998 			wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
4999 
5000 			while (qp != I40E_QUEUE_END_OF_LIST) {
5001 				u32 next;
5002 
5003 				val = rd32(hw, I40E_QINT_RQCTL(qp));
5004 
5005 				val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5006 					 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5007 					 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5008 					 I40E_QINT_RQCTL_INTEVENT_MASK);
5009 
5010 				val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5011 					 I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5012 
5013 				wr32(hw, I40E_QINT_RQCTL(qp), val);
5014 
5015 				val = rd32(hw, I40E_QINT_TQCTL(qp));
5016 
5017 				next = (val & I40E_QINT_TQCTL_NEXTQ_INDX_MASK)
5018 					>> I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT;
5019 
5020 				val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5021 					 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5022 					 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5023 					 I40E_QINT_TQCTL_INTEVENT_MASK);
5024 
5025 				val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5026 					 I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5027 
5028 				wr32(hw, I40E_QINT_TQCTL(qp), val);
5029 				qp = next;
5030 			}
5031 		}
5032 	} else {
5033 		free_irq(pf->pdev->irq, pf);
5034 
5035 		val = rd32(hw, I40E_PFINT_LNKLST0);
5036 		qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
5037 			>> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
5038 		val |= I40E_QUEUE_END_OF_LIST
5039 			<< I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
5040 		wr32(hw, I40E_PFINT_LNKLST0, val);
5041 
5042 		val = rd32(hw, I40E_QINT_RQCTL(qp));
5043 		val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5044 			 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5045 			 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5046 			 I40E_QINT_RQCTL_INTEVENT_MASK);
5047 
5048 		val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5049 			I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5050 
5051 		wr32(hw, I40E_QINT_RQCTL(qp), val);
5052 
5053 		val = rd32(hw, I40E_QINT_TQCTL(qp));
5054 
5055 		val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5056 			 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5057 			 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5058 			 I40E_QINT_TQCTL_INTEVENT_MASK);
5059 
5060 		val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5061 			I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5062 
5063 		wr32(hw, I40E_QINT_TQCTL(qp), val);
5064 	}
5065 }
5066 
5067 /**
5068  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
5069  * @vsi: the VSI being configured
5070  * @v_idx: Index of vector to be freed
5071  *
5072  * This function frees the memory allocated to the q_vector.  In addition if
5073  * NAPI is enabled it will delete any references to the NAPI struct prior
5074  * to freeing the q_vector.
5075  **/
5076 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
5077 {
5078 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
5079 	struct i40e_ring *ring;
5080 
5081 	if (!q_vector)
5082 		return;
5083 
5084 	/* disassociate q_vector from rings */
5085 	i40e_for_each_ring(ring, q_vector->tx)
5086 		ring->q_vector = NULL;
5087 
5088 	i40e_for_each_ring(ring, q_vector->rx)
5089 		ring->q_vector = NULL;
5090 
5091 	/* only VSI w/ an associated netdev is set up w/ NAPI */
5092 	if (vsi->netdev)
5093 		netif_napi_del(&q_vector->napi);
5094 
5095 	vsi->q_vectors[v_idx] = NULL;
5096 
5097 	kfree_rcu(q_vector, rcu);
5098 }
5099 
5100 /**
5101  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
5102  * @vsi: the VSI being un-configured
5103  *
5104  * This frees the memory allocated to the q_vectors and
5105  * deletes references to the NAPI struct.
5106  **/
5107 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
5108 {
5109 	int v_idx;
5110 
5111 	for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
5112 		i40e_free_q_vector(vsi, v_idx);
5113 }
5114 
5115 /**
5116  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
5117  * @pf: board private structure
5118  **/
5119 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
5120 {
5121 	/* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
5122 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
5123 		pci_disable_msix(pf->pdev);
5124 		kfree(pf->msix_entries);
5125 		pf->msix_entries = NULL;
5126 		kfree(pf->irq_pile);
5127 		pf->irq_pile = NULL;
5128 	} else if (pf->flags & I40E_FLAG_MSI_ENABLED) {
5129 		pci_disable_msi(pf->pdev);
5130 	}
5131 	pf->flags &= ~(I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
5132 }
5133 
5134 /**
5135  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
5136  * @pf: board private structure
5137  *
5138  * We go through and clear interrupt specific resources and reset the structure
5139  * to pre-load conditions
5140  **/
5141 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
5142 {
5143 	int i;
5144 
5145 	if (test_bit(__I40E_MISC_IRQ_REQUESTED, pf->state))
5146 		i40e_free_misc_vector(pf);
5147 
5148 	i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
5149 		      I40E_IWARP_IRQ_PILE_ID);
5150 
5151 	i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
5152 	for (i = 0; i < pf->num_alloc_vsi; i++)
5153 		if (pf->vsi[i])
5154 			i40e_vsi_free_q_vectors(pf->vsi[i]);
5155 	i40e_reset_interrupt_capability(pf);
5156 }
5157 
5158 /**
5159  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5160  * @vsi: the VSI being configured
5161  **/
5162 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
5163 {
5164 	int q_idx;
5165 
5166 	if (!vsi->netdev)
5167 		return;
5168 
5169 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5170 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5171 
5172 		if (q_vector->rx.ring || q_vector->tx.ring)
5173 			napi_enable(&q_vector->napi);
5174 	}
5175 }
5176 
5177 /**
5178  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
5179  * @vsi: the VSI being configured
5180  **/
5181 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
5182 {
5183 	int q_idx;
5184 
5185 	if (!vsi->netdev)
5186 		return;
5187 
5188 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5189 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5190 
5191 		if (q_vector->rx.ring || q_vector->tx.ring)
5192 			napi_disable(&q_vector->napi);
5193 	}
5194 }
5195 
5196 /**
5197  * i40e_vsi_close - Shut down a VSI
5198  * @vsi: the vsi to be quelled
5199  **/
5200 static void i40e_vsi_close(struct i40e_vsi *vsi)
5201 {
5202 	struct i40e_pf *pf = vsi->back;
5203 	if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
5204 		i40e_down(vsi);
5205 	i40e_vsi_free_irq(vsi);
5206 	i40e_vsi_free_tx_resources(vsi);
5207 	i40e_vsi_free_rx_resources(vsi);
5208 	vsi->current_netdev_flags = 0;
5209 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
5210 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
5211 		set_bit(__I40E_CLIENT_RESET, pf->state);
5212 }
5213 
5214 /**
5215  * i40e_quiesce_vsi - Pause a given VSI
5216  * @vsi: the VSI being paused
5217  **/
5218 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
5219 {
5220 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
5221 		return;
5222 
5223 	set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
5224 	if (vsi->netdev && netif_running(vsi->netdev))
5225 		vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
5226 	else
5227 		i40e_vsi_close(vsi);
5228 }
5229 
5230 /**
5231  * i40e_unquiesce_vsi - Resume a given VSI
5232  * @vsi: the VSI being resumed
5233  **/
5234 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
5235 {
5236 	if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
5237 		return;
5238 
5239 	if (vsi->netdev && netif_running(vsi->netdev))
5240 		vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
5241 	else
5242 		i40e_vsi_open(vsi);   /* this clears the DOWN bit */
5243 }
5244 
5245 /**
5246  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
5247  * @pf: the PF
5248  **/
5249 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
5250 {
5251 	int v;
5252 
5253 	for (v = 0; v < pf->num_alloc_vsi; v++) {
5254 		if (pf->vsi[v])
5255 			i40e_quiesce_vsi(pf->vsi[v]);
5256 	}
5257 }
5258 
5259 /**
5260  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
5261  * @pf: the PF
5262  **/
5263 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
5264 {
5265 	int v;
5266 
5267 	for (v = 0; v < pf->num_alloc_vsi; v++) {
5268 		if (pf->vsi[v])
5269 			i40e_unquiesce_vsi(pf->vsi[v]);
5270 	}
5271 }
5272 
5273 /**
5274  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
5275  * @vsi: the VSI being configured
5276  *
5277  * Wait until all queues on a given VSI have been disabled.
5278  **/
5279 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
5280 {
5281 	struct i40e_pf *pf = vsi->back;
5282 	int i, pf_q, ret;
5283 
5284 	pf_q = vsi->base_queue;
5285 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
5286 		/* Check and wait for the Tx queue */
5287 		ret = i40e_pf_txq_wait(pf, pf_q, false);
5288 		if (ret) {
5289 			dev_info(&pf->pdev->dev,
5290 				 "VSI seid %d Tx ring %d disable timeout\n",
5291 				 vsi->seid, pf_q);
5292 			return ret;
5293 		}
5294 
5295 		if (!i40e_enabled_xdp_vsi(vsi))
5296 			goto wait_rx;
5297 
5298 		/* Check and wait for the XDP Tx queue */
5299 		ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
5300 				       false);
5301 		if (ret) {
5302 			dev_info(&pf->pdev->dev,
5303 				 "VSI seid %d XDP Tx ring %d disable timeout\n",
5304 				 vsi->seid, pf_q);
5305 			return ret;
5306 		}
5307 wait_rx:
5308 		/* Check and wait for the Rx queue */
5309 		ret = i40e_pf_rxq_wait(pf, pf_q, false);
5310 		if (ret) {
5311 			dev_info(&pf->pdev->dev,
5312 				 "VSI seid %d Rx ring %d disable timeout\n",
5313 				 vsi->seid, pf_q);
5314 			return ret;
5315 		}
5316 	}
5317 
5318 	return 0;
5319 }
5320 
5321 #ifdef CONFIG_I40E_DCB
5322 /**
5323  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
5324  * @pf: the PF
5325  *
5326  * This function waits for the queues to be in disabled state for all the
5327  * VSIs that are managed by this PF.
5328  **/
5329 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
5330 {
5331 	int v, ret = 0;
5332 
5333 	for (v = 0; v < pf->hw.func_caps.num_vsis; v++) {
5334 		if (pf->vsi[v]) {
5335 			ret = i40e_vsi_wait_queues_disabled(pf->vsi[v]);
5336 			if (ret)
5337 				break;
5338 		}
5339 	}
5340 
5341 	return ret;
5342 }
5343 
5344 #endif
5345 
5346 /**
5347  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
5348  * @pf: pointer to PF
5349  *
5350  * Get TC map for ISCSI PF type that will include iSCSI TC
5351  * and LAN TC.
5352  **/
5353 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
5354 {
5355 	struct i40e_dcb_app_priority_table app;
5356 	struct i40e_hw *hw = &pf->hw;
5357 	u8 enabled_tc = 1; /* TC0 is always enabled */
5358 	u8 tc, i;
5359 	/* Get the iSCSI APP TLV */
5360 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5361 
5362 	for (i = 0; i < dcbcfg->numapps; i++) {
5363 		app = dcbcfg->app[i];
5364 		if (app.selector == I40E_APP_SEL_TCPIP &&
5365 		    app.protocolid == I40E_APP_PROTOID_ISCSI) {
5366 			tc = dcbcfg->etscfg.prioritytable[app.priority];
5367 			enabled_tc |= BIT(tc);
5368 			break;
5369 		}
5370 	}
5371 
5372 	return enabled_tc;
5373 }
5374 
5375 /**
5376  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5377  * @dcbcfg: the corresponding DCBx configuration structure
5378  *
5379  * Return the number of TCs from given DCBx configuration
5380  **/
5381 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5382 {
5383 	int i, tc_unused = 0;
5384 	u8 num_tc = 0;
5385 	u8 ret = 0;
5386 
5387 	/* Scan the ETS Config Priority Table to find
5388 	 * traffic class enabled for a given priority
5389 	 * and create a bitmask of enabled TCs
5390 	 */
5391 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5392 		num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5393 
5394 	/* Now scan the bitmask to check for
5395 	 * contiguous TCs starting with TC0
5396 	 */
5397 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5398 		if (num_tc & BIT(i)) {
5399 			if (!tc_unused) {
5400 				ret++;
5401 			} else {
5402 				pr_err("Non-contiguous TC - Disabling DCB\n");
5403 				return 1;
5404 			}
5405 		} else {
5406 			tc_unused = 1;
5407 		}
5408 	}
5409 
5410 	/* There is always at least TC0 */
5411 	if (!ret)
5412 		ret = 1;
5413 
5414 	return ret;
5415 }
5416 
5417 /**
5418  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5419  * @dcbcfg: the corresponding DCBx configuration structure
5420  *
5421  * Query the current DCB configuration and return the number of
5422  * traffic classes enabled from the given DCBX config
5423  **/
5424 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5425 {
5426 	u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5427 	u8 enabled_tc = 1;
5428 	u8 i;
5429 
5430 	for (i = 0; i < num_tc; i++)
5431 		enabled_tc |= BIT(i);
5432 
5433 	return enabled_tc;
5434 }
5435 
5436 /**
5437  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5438  * @pf: PF being queried
5439  *
5440  * Query the current MQPRIO configuration and return the number of
5441  * traffic classes enabled.
5442  **/
5443 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5444 {
5445 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
5446 	u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5447 	u8 enabled_tc = 1, i;
5448 
5449 	for (i = 1; i < num_tc; i++)
5450 		enabled_tc |= BIT(i);
5451 	return enabled_tc;
5452 }
5453 
5454 /**
5455  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5456  * @pf: PF being queried
5457  *
5458  * Return number of traffic classes enabled for the given PF
5459  **/
5460 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5461 {
5462 	struct i40e_hw *hw = &pf->hw;
5463 	u8 i, enabled_tc = 1;
5464 	u8 num_tc = 0;
5465 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5466 
5467 	if (i40e_is_tc_mqprio_enabled(pf))
5468 		return pf->vsi[pf->lan_vsi]->mqprio_qopt.qopt.num_tc;
5469 
5470 	/* If neither MQPRIO nor DCB is enabled, then always use single TC */
5471 	if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5472 		return 1;
5473 
5474 	/* SFP mode will be enabled for all TCs on port */
5475 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5476 		return i40e_dcb_get_num_tc(dcbcfg);
5477 
5478 	/* MFP mode return count of enabled TCs for this PF */
5479 	if (pf->hw.func_caps.iscsi)
5480 		enabled_tc =  i40e_get_iscsi_tc_map(pf);
5481 	else
5482 		return 1; /* Only TC0 */
5483 
5484 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5485 		if (enabled_tc & BIT(i))
5486 			num_tc++;
5487 	}
5488 	return num_tc;
5489 }
5490 
5491 /**
5492  * i40e_pf_get_tc_map - Get bitmap for enabled traffic classes
5493  * @pf: PF being queried
5494  *
5495  * Return a bitmap for enabled traffic classes for this PF.
5496  **/
5497 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5498 {
5499 	if (i40e_is_tc_mqprio_enabled(pf))
5500 		return i40e_mqprio_get_enabled_tc(pf);
5501 
5502 	/* If neither MQPRIO nor DCB is enabled for this PF then just return
5503 	 * default TC
5504 	 */
5505 	if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5506 		return I40E_DEFAULT_TRAFFIC_CLASS;
5507 
5508 	/* SFP mode we want PF to be enabled for all TCs */
5509 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5510 		return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5511 
5512 	/* MFP enabled and iSCSI PF type */
5513 	if (pf->hw.func_caps.iscsi)
5514 		return i40e_get_iscsi_tc_map(pf);
5515 	else
5516 		return I40E_DEFAULT_TRAFFIC_CLASS;
5517 }
5518 
5519 /**
5520  * i40e_vsi_get_bw_info - Query VSI BW Information
5521  * @vsi: the VSI being queried
5522  *
5523  * Returns 0 on success, negative value on failure
5524  **/
5525 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5526 {
5527 	struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5528 	struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5529 	struct i40e_pf *pf = vsi->back;
5530 	struct i40e_hw *hw = &pf->hw;
5531 	u32 tc_bw_max;
5532 	int ret;
5533 	int i;
5534 
5535 	/* Get the VSI level BW configuration */
5536 	ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5537 	if (ret) {
5538 		dev_info(&pf->pdev->dev,
5539 			 "couldn't get PF vsi bw config, err %pe aq_err %s\n",
5540 			 ERR_PTR(ret),
5541 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5542 		return -EINVAL;
5543 	}
5544 
5545 	/* Get the VSI level BW configuration per TC */
5546 	ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5547 					       NULL);
5548 	if (ret) {
5549 		dev_info(&pf->pdev->dev,
5550 			 "couldn't get PF vsi ets bw config, err %pe aq_err %s\n",
5551 			 ERR_PTR(ret),
5552 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5553 		return -EINVAL;
5554 	}
5555 
5556 	if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5557 		dev_info(&pf->pdev->dev,
5558 			 "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5559 			 bw_config.tc_valid_bits,
5560 			 bw_ets_config.tc_valid_bits);
5561 		/* Still continuing */
5562 	}
5563 
5564 	vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5565 	vsi->bw_max_quanta = bw_config.max_bw;
5566 	tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5567 		    (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5568 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5569 		vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5570 		vsi->bw_ets_limit_credits[i] =
5571 					le16_to_cpu(bw_ets_config.credits[i]);
5572 		/* 3 bits out of 4 for each TC */
5573 		vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5574 	}
5575 
5576 	return 0;
5577 }
5578 
5579 /**
5580  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5581  * @vsi: the VSI being configured
5582  * @enabled_tc: TC bitmap
5583  * @bw_share: BW shared credits per TC
5584  *
5585  * Returns 0 on success, negative value on failure
5586  **/
5587 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5588 				       u8 *bw_share)
5589 {
5590 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5591 	struct i40e_pf *pf = vsi->back;
5592 	int ret;
5593 	int i;
5594 
5595 	/* There is no need to reset BW when mqprio mode is on.  */
5596 	if (i40e_is_tc_mqprio_enabled(pf))
5597 		return 0;
5598 	if (!vsi->mqprio_qopt.qopt.hw && !(pf->flags & I40E_FLAG_DCB_ENABLED)) {
5599 		ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5600 		if (ret)
5601 			dev_info(&pf->pdev->dev,
5602 				 "Failed to reset tx rate for vsi->seid %u\n",
5603 				 vsi->seid);
5604 		return ret;
5605 	}
5606 	memset(&bw_data, 0, sizeof(bw_data));
5607 	bw_data.tc_valid_bits = enabled_tc;
5608 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5609 		bw_data.tc_bw_credits[i] = bw_share[i];
5610 
5611 	ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5612 	if (ret) {
5613 		dev_info(&pf->pdev->dev,
5614 			 "AQ command Config VSI BW allocation per TC failed = %d\n",
5615 			 pf->hw.aq.asq_last_status);
5616 		return -EINVAL;
5617 	}
5618 
5619 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5620 		vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5621 
5622 	return 0;
5623 }
5624 
5625 /**
5626  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5627  * @vsi: the VSI being configured
5628  * @enabled_tc: TC map to be enabled
5629  *
5630  **/
5631 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5632 {
5633 	struct net_device *netdev = vsi->netdev;
5634 	struct i40e_pf *pf = vsi->back;
5635 	struct i40e_hw *hw = &pf->hw;
5636 	u8 netdev_tc = 0;
5637 	int i;
5638 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5639 
5640 	if (!netdev)
5641 		return;
5642 
5643 	if (!enabled_tc) {
5644 		netdev_reset_tc(netdev);
5645 		return;
5646 	}
5647 
5648 	/* Set up actual enabled TCs on the VSI */
5649 	if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5650 		return;
5651 
5652 	/* set per TC queues for the VSI */
5653 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5654 		/* Only set TC queues for enabled tcs
5655 		 *
5656 		 * e.g. For a VSI that has TC0 and TC3 enabled the
5657 		 * enabled_tc bitmap would be 0x00001001; the driver
5658 		 * will set the numtc for netdev as 2 that will be
5659 		 * referenced by the netdev layer as TC 0 and 1.
5660 		 */
5661 		if (vsi->tc_config.enabled_tc & BIT(i))
5662 			netdev_set_tc_queue(netdev,
5663 					vsi->tc_config.tc_info[i].netdev_tc,
5664 					vsi->tc_config.tc_info[i].qcount,
5665 					vsi->tc_config.tc_info[i].qoffset);
5666 	}
5667 
5668 	if (i40e_is_tc_mqprio_enabled(pf))
5669 		return;
5670 
5671 	/* Assign UP2TC map for the VSI */
5672 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5673 		/* Get the actual TC# for the UP */
5674 		u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5675 		/* Get the mapped netdev TC# for the UP */
5676 		netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5677 		netdev_set_prio_tc_map(netdev, i, netdev_tc);
5678 	}
5679 }
5680 
5681 /**
5682  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5683  * @vsi: the VSI being configured
5684  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5685  **/
5686 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5687 				      struct i40e_vsi_context *ctxt)
5688 {
5689 	/* copy just the sections touched not the entire info
5690 	 * since not all sections are valid as returned by
5691 	 * update vsi params
5692 	 */
5693 	vsi->info.mapping_flags = ctxt->info.mapping_flags;
5694 	memcpy(&vsi->info.queue_mapping,
5695 	       &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5696 	memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5697 	       sizeof(vsi->info.tc_mapping));
5698 }
5699 
5700 /**
5701  * i40e_update_adq_vsi_queues - update queue mapping for ADq VSI
5702  * @vsi: the VSI being reconfigured
5703  * @vsi_offset: offset from main VF VSI
5704  */
5705 int i40e_update_adq_vsi_queues(struct i40e_vsi *vsi, int vsi_offset)
5706 {
5707 	struct i40e_vsi_context ctxt = {};
5708 	struct i40e_pf *pf;
5709 	struct i40e_hw *hw;
5710 	int ret;
5711 
5712 	if (!vsi)
5713 		return -EINVAL;
5714 	pf = vsi->back;
5715 	hw = &pf->hw;
5716 
5717 	ctxt.seid = vsi->seid;
5718 	ctxt.pf_num = hw->pf_id;
5719 	ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id + vsi_offset;
5720 	ctxt.uplink_seid = vsi->uplink_seid;
5721 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5722 	ctxt.flags = I40E_AQ_VSI_TYPE_VF;
5723 	ctxt.info = vsi->info;
5724 
5725 	i40e_vsi_setup_queue_map(vsi, &ctxt, vsi->tc_config.enabled_tc,
5726 				 false);
5727 	if (vsi->reconfig_rss) {
5728 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
5729 				      vsi->num_queue_pairs);
5730 		ret = i40e_vsi_config_rss(vsi);
5731 		if (ret) {
5732 			dev_info(&pf->pdev->dev, "Failed to reconfig rss for num_queues\n");
5733 			return ret;
5734 		}
5735 		vsi->reconfig_rss = false;
5736 	}
5737 
5738 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5739 	if (ret) {
5740 		dev_info(&pf->pdev->dev, "Update vsi config failed, err %pe aq_err %s\n",
5741 			 ERR_PTR(ret),
5742 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5743 		return ret;
5744 	}
5745 	/* update the local VSI info with updated queue map */
5746 	i40e_vsi_update_queue_map(vsi, &ctxt);
5747 	vsi->info.valid_sections = 0;
5748 
5749 	return ret;
5750 }
5751 
5752 /**
5753  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5754  * @vsi: VSI to be configured
5755  * @enabled_tc: TC bitmap
5756  *
5757  * This configures a particular VSI for TCs that are mapped to the
5758  * given TC bitmap. It uses default bandwidth share for TCs across
5759  * VSIs to configure TC for a particular VSI.
5760  *
5761  * NOTE:
5762  * It is expected that the VSI queues have been quisced before calling
5763  * this function.
5764  **/
5765 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5766 {
5767 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5768 	struct i40e_pf *pf = vsi->back;
5769 	struct i40e_hw *hw = &pf->hw;
5770 	struct i40e_vsi_context ctxt;
5771 	int ret = 0;
5772 	int i;
5773 
5774 	/* Check if enabled_tc is same as existing or new TCs */
5775 	if (vsi->tc_config.enabled_tc == enabled_tc &&
5776 	    vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5777 		return ret;
5778 
5779 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
5780 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5781 		if (enabled_tc & BIT(i))
5782 			bw_share[i] = 1;
5783 	}
5784 
5785 	ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5786 	if (ret) {
5787 		struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5788 
5789 		dev_info(&pf->pdev->dev,
5790 			 "Failed configuring TC map %d for VSI %d\n",
5791 			 enabled_tc, vsi->seid);
5792 		ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5793 						  &bw_config, NULL);
5794 		if (ret) {
5795 			dev_info(&pf->pdev->dev,
5796 				 "Failed querying vsi bw info, err %pe aq_err %s\n",
5797 				 ERR_PTR(ret),
5798 				 i40e_aq_str(hw, hw->aq.asq_last_status));
5799 			goto out;
5800 		}
5801 		if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5802 			u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5803 
5804 			if (!valid_tc)
5805 				valid_tc = bw_config.tc_valid_bits;
5806 			/* Always enable TC0, no matter what */
5807 			valid_tc |= 1;
5808 			dev_info(&pf->pdev->dev,
5809 				 "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5810 				 enabled_tc, bw_config.tc_valid_bits, valid_tc);
5811 			enabled_tc = valid_tc;
5812 		}
5813 
5814 		ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5815 		if (ret) {
5816 			dev_err(&pf->pdev->dev,
5817 				"Unable to  configure TC map %d for VSI %d\n",
5818 				enabled_tc, vsi->seid);
5819 			goto out;
5820 		}
5821 	}
5822 
5823 	/* Update Queue Pairs Mapping for currently enabled UPs */
5824 	ctxt.seid = vsi->seid;
5825 	ctxt.pf_num = vsi->back->hw.pf_id;
5826 	ctxt.vf_num = 0;
5827 	ctxt.uplink_seid = vsi->uplink_seid;
5828 	ctxt.info = vsi->info;
5829 	if (i40e_is_tc_mqprio_enabled(pf)) {
5830 		ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5831 		if (ret)
5832 			goto out;
5833 	} else {
5834 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5835 	}
5836 
5837 	/* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5838 	 * queues changed.
5839 	 */
5840 	if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5841 		vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5842 				      vsi->num_queue_pairs);
5843 		ret = i40e_vsi_config_rss(vsi);
5844 		if (ret) {
5845 			dev_info(&vsi->back->pdev->dev,
5846 				 "Failed to reconfig rss for num_queues\n");
5847 			return ret;
5848 		}
5849 		vsi->reconfig_rss = false;
5850 	}
5851 	if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
5852 		ctxt.info.valid_sections |=
5853 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5854 		ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5855 	}
5856 
5857 	/* Update the VSI after updating the VSI queue-mapping
5858 	 * information
5859 	 */
5860 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5861 	if (ret) {
5862 		dev_info(&pf->pdev->dev,
5863 			 "Update vsi tc config failed, err %pe aq_err %s\n",
5864 			 ERR_PTR(ret),
5865 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5866 		goto out;
5867 	}
5868 	/* update the local VSI info with updated queue map */
5869 	i40e_vsi_update_queue_map(vsi, &ctxt);
5870 	vsi->info.valid_sections = 0;
5871 
5872 	/* Update current VSI BW information */
5873 	ret = i40e_vsi_get_bw_info(vsi);
5874 	if (ret) {
5875 		dev_info(&pf->pdev->dev,
5876 			 "Failed updating vsi bw info, err %pe aq_err %s\n",
5877 			 ERR_PTR(ret),
5878 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5879 		goto out;
5880 	}
5881 
5882 	/* Update the netdev TC setup */
5883 	i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5884 out:
5885 	return ret;
5886 }
5887 
5888 /**
5889  * i40e_get_link_speed - Returns link speed for the interface
5890  * @vsi: VSI to be configured
5891  *
5892  **/
5893 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5894 {
5895 	struct i40e_pf *pf = vsi->back;
5896 
5897 	switch (pf->hw.phy.link_info.link_speed) {
5898 	case I40E_LINK_SPEED_40GB:
5899 		return 40000;
5900 	case I40E_LINK_SPEED_25GB:
5901 		return 25000;
5902 	case I40E_LINK_SPEED_20GB:
5903 		return 20000;
5904 	case I40E_LINK_SPEED_10GB:
5905 		return 10000;
5906 	case I40E_LINK_SPEED_1GB:
5907 		return 1000;
5908 	default:
5909 		return -EINVAL;
5910 	}
5911 }
5912 
5913 /**
5914  * i40e_bw_bytes_to_mbits - Convert max_tx_rate from bytes to mbits
5915  * @vsi: Pointer to vsi structure
5916  * @max_tx_rate: max TX rate in bytes to be converted into Mbits
5917  *
5918  * Helper function to convert units before send to set BW limit
5919  **/
5920 static u64 i40e_bw_bytes_to_mbits(struct i40e_vsi *vsi, u64 max_tx_rate)
5921 {
5922 	if (max_tx_rate < I40E_BW_MBPS_DIVISOR) {
5923 		dev_warn(&vsi->back->pdev->dev,
5924 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
5925 		max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5926 	} else {
5927 		do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
5928 	}
5929 
5930 	return max_tx_rate;
5931 }
5932 
5933 /**
5934  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5935  * @vsi: VSI to be configured
5936  * @seid: seid of the channel/VSI
5937  * @max_tx_rate: max TX rate to be configured as BW limit
5938  *
5939  * Helper function to set BW limit for a given VSI
5940  **/
5941 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5942 {
5943 	struct i40e_pf *pf = vsi->back;
5944 	u64 credits = 0;
5945 	int speed = 0;
5946 	int ret = 0;
5947 
5948 	speed = i40e_get_link_speed(vsi);
5949 	if (max_tx_rate > speed) {
5950 		dev_err(&pf->pdev->dev,
5951 			"Invalid max tx rate %llu specified for VSI seid %d.",
5952 			max_tx_rate, seid);
5953 		return -EINVAL;
5954 	}
5955 	if (max_tx_rate && max_tx_rate < I40E_BW_CREDIT_DIVISOR) {
5956 		dev_warn(&pf->pdev->dev,
5957 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
5958 		max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5959 	}
5960 
5961 	/* Tx rate credits are in values of 50Mbps, 0 is disabled */
5962 	credits = max_tx_rate;
5963 	do_div(credits, I40E_BW_CREDIT_DIVISOR);
5964 	ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
5965 					  I40E_MAX_BW_INACTIVE_ACCUM, NULL);
5966 	if (ret)
5967 		dev_err(&pf->pdev->dev,
5968 			"Failed set tx rate (%llu Mbps) for vsi->seid %u, err %pe aq_err %s\n",
5969 			max_tx_rate, seid, ERR_PTR(ret),
5970 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5971 	return ret;
5972 }
5973 
5974 /**
5975  * i40e_remove_queue_channels - Remove queue channels for the TCs
5976  * @vsi: VSI to be configured
5977  *
5978  * Remove queue channels for the TCs
5979  **/
5980 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
5981 {
5982 	enum i40e_admin_queue_err last_aq_status;
5983 	struct i40e_cloud_filter *cfilter;
5984 	struct i40e_channel *ch, *ch_tmp;
5985 	struct i40e_pf *pf = vsi->back;
5986 	struct hlist_node *node;
5987 	int ret, i;
5988 
5989 	/* Reset rss size that was stored when reconfiguring rss for
5990 	 * channel VSIs with non-power-of-2 queue count.
5991 	 */
5992 	vsi->current_rss_size = 0;
5993 
5994 	/* perform cleanup for channels if they exist */
5995 	if (list_empty(&vsi->ch_list))
5996 		return;
5997 
5998 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5999 		struct i40e_vsi *p_vsi;
6000 
6001 		list_del(&ch->list);
6002 		p_vsi = ch->parent_vsi;
6003 		if (!p_vsi || !ch->initialized) {
6004 			kfree(ch);
6005 			continue;
6006 		}
6007 		/* Reset queue contexts */
6008 		for (i = 0; i < ch->num_queue_pairs; i++) {
6009 			struct i40e_ring *tx_ring, *rx_ring;
6010 			u16 pf_q;
6011 
6012 			pf_q = ch->base_queue + i;
6013 			tx_ring = vsi->tx_rings[pf_q];
6014 			tx_ring->ch = NULL;
6015 
6016 			rx_ring = vsi->rx_rings[pf_q];
6017 			rx_ring->ch = NULL;
6018 		}
6019 
6020 		/* Reset BW configured for this VSI via mqprio */
6021 		ret = i40e_set_bw_limit(vsi, ch->seid, 0);
6022 		if (ret)
6023 			dev_info(&vsi->back->pdev->dev,
6024 				 "Failed to reset tx rate for ch->seid %u\n",
6025 				 ch->seid);
6026 
6027 		/* delete cloud filters associated with this channel */
6028 		hlist_for_each_entry_safe(cfilter, node,
6029 					  &pf->cloud_filter_list, cloud_node) {
6030 			if (cfilter->seid != ch->seid)
6031 				continue;
6032 
6033 			hash_del(&cfilter->cloud_node);
6034 			if (cfilter->dst_port)
6035 				ret = i40e_add_del_cloud_filter_big_buf(vsi,
6036 									cfilter,
6037 									false);
6038 			else
6039 				ret = i40e_add_del_cloud_filter(vsi, cfilter,
6040 								false);
6041 			last_aq_status = pf->hw.aq.asq_last_status;
6042 			if (ret)
6043 				dev_info(&pf->pdev->dev,
6044 					 "Failed to delete cloud filter, err %pe aq_err %s\n",
6045 					 ERR_PTR(ret),
6046 					 i40e_aq_str(&pf->hw, last_aq_status));
6047 			kfree(cfilter);
6048 		}
6049 
6050 		/* delete VSI from FW */
6051 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
6052 					     NULL);
6053 		if (ret)
6054 			dev_err(&vsi->back->pdev->dev,
6055 				"unable to remove channel (%d) for parent VSI(%d)\n",
6056 				ch->seid, p_vsi->seid);
6057 		kfree(ch);
6058 	}
6059 	INIT_LIST_HEAD(&vsi->ch_list);
6060 }
6061 
6062 /**
6063  * i40e_get_max_queues_for_channel
6064  * @vsi: ptr to VSI to which channels are associated with
6065  *
6066  * Helper function which returns max value among the queue counts set on the
6067  * channels/TCs created.
6068  **/
6069 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
6070 {
6071 	struct i40e_channel *ch, *ch_tmp;
6072 	int max = 0;
6073 
6074 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6075 		if (!ch->initialized)
6076 			continue;
6077 		if (ch->num_queue_pairs > max)
6078 			max = ch->num_queue_pairs;
6079 	}
6080 
6081 	return max;
6082 }
6083 
6084 /**
6085  * i40e_validate_num_queues - validate num_queues w.r.t channel
6086  * @pf: ptr to PF device
6087  * @num_queues: number of queues
6088  * @vsi: the parent VSI
6089  * @reconfig_rss: indicates should the RSS be reconfigured or not
6090  *
6091  * This function validates number of queues in the context of new channel
6092  * which is being established and determines if RSS should be reconfigured
6093  * or not for parent VSI.
6094  **/
6095 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
6096 				    struct i40e_vsi *vsi, bool *reconfig_rss)
6097 {
6098 	int max_ch_queues;
6099 
6100 	if (!reconfig_rss)
6101 		return -EINVAL;
6102 
6103 	*reconfig_rss = false;
6104 	if (vsi->current_rss_size) {
6105 		if (num_queues > vsi->current_rss_size) {
6106 			dev_dbg(&pf->pdev->dev,
6107 				"Error: num_queues (%d) > vsi's current_size(%d)\n",
6108 				num_queues, vsi->current_rss_size);
6109 			return -EINVAL;
6110 		} else if ((num_queues < vsi->current_rss_size) &&
6111 			   (!is_power_of_2(num_queues))) {
6112 			dev_dbg(&pf->pdev->dev,
6113 				"Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
6114 				num_queues, vsi->current_rss_size);
6115 			return -EINVAL;
6116 		}
6117 	}
6118 
6119 	if (!is_power_of_2(num_queues)) {
6120 		/* Find the max num_queues configured for channel if channel
6121 		 * exist.
6122 		 * if channel exist, then enforce 'num_queues' to be more than
6123 		 * max ever queues configured for channel.
6124 		 */
6125 		max_ch_queues = i40e_get_max_queues_for_channel(vsi);
6126 		if (num_queues < max_ch_queues) {
6127 			dev_dbg(&pf->pdev->dev,
6128 				"Error: num_queues (%d) < max queues configured for channel(%d)\n",
6129 				num_queues, max_ch_queues);
6130 			return -EINVAL;
6131 		}
6132 		*reconfig_rss = true;
6133 	}
6134 
6135 	return 0;
6136 }
6137 
6138 /**
6139  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
6140  * @vsi: the VSI being setup
6141  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
6142  *
6143  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
6144  **/
6145 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
6146 {
6147 	struct i40e_pf *pf = vsi->back;
6148 	u8 seed[I40E_HKEY_ARRAY_SIZE];
6149 	struct i40e_hw *hw = &pf->hw;
6150 	int local_rss_size;
6151 	u8 *lut;
6152 	int ret;
6153 
6154 	if (!vsi->rss_size)
6155 		return -EINVAL;
6156 
6157 	if (rss_size > vsi->rss_size)
6158 		return -EINVAL;
6159 
6160 	local_rss_size = min_t(int, vsi->rss_size, rss_size);
6161 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
6162 	if (!lut)
6163 		return -ENOMEM;
6164 
6165 	/* Ignoring user configured lut if there is one */
6166 	i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
6167 
6168 	/* Use user configured hash key if there is one, otherwise
6169 	 * use default.
6170 	 */
6171 	if (vsi->rss_hkey_user)
6172 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
6173 	else
6174 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
6175 
6176 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
6177 	if (ret) {
6178 		dev_info(&pf->pdev->dev,
6179 			 "Cannot set RSS lut, err %pe aq_err %s\n",
6180 			 ERR_PTR(ret),
6181 			 i40e_aq_str(hw, hw->aq.asq_last_status));
6182 		kfree(lut);
6183 		return ret;
6184 	}
6185 	kfree(lut);
6186 
6187 	/* Do the update w.r.t. storing rss_size */
6188 	if (!vsi->orig_rss_size)
6189 		vsi->orig_rss_size = vsi->rss_size;
6190 	vsi->current_rss_size = local_rss_size;
6191 
6192 	return ret;
6193 }
6194 
6195 /**
6196  * i40e_channel_setup_queue_map - Setup a channel queue map
6197  * @pf: ptr to PF device
6198  * @ctxt: VSI context structure
6199  * @ch: ptr to channel structure
6200  *
6201  * Setup queue map for a specific channel
6202  **/
6203 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
6204 					 struct i40e_vsi_context *ctxt,
6205 					 struct i40e_channel *ch)
6206 {
6207 	u16 qcount, qmap, sections = 0;
6208 	u8 offset = 0;
6209 	int pow;
6210 
6211 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
6212 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
6213 
6214 	qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
6215 	ch->num_queue_pairs = qcount;
6216 
6217 	/* find the next higher power-of-2 of num queue pairs */
6218 	pow = ilog2(qcount);
6219 	if (!is_power_of_2(qcount))
6220 		pow++;
6221 
6222 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
6223 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
6224 
6225 	/* Setup queue TC[0].qmap for given VSI context */
6226 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
6227 
6228 	ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
6229 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
6230 	ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
6231 	ctxt->info.valid_sections |= cpu_to_le16(sections);
6232 }
6233 
6234 /**
6235  * i40e_add_channel - add a channel by adding VSI
6236  * @pf: ptr to PF device
6237  * @uplink_seid: underlying HW switching element (VEB) ID
6238  * @ch: ptr to channel structure
6239  *
6240  * Add a channel (VSI) using add_vsi and queue_map
6241  **/
6242 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
6243 			    struct i40e_channel *ch)
6244 {
6245 	struct i40e_hw *hw = &pf->hw;
6246 	struct i40e_vsi_context ctxt;
6247 	u8 enabled_tc = 0x1; /* TC0 enabled */
6248 	int ret;
6249 
6250 	if (ch->type != I40E_VSI_VMDQ2) {
6251 		dev_info(&pf->pdev->dev,
6252 			 "add new vsi failed, ch->type %d\n", ch->type);
6253 		return -EINVAL;
6254 	}
6255 
6256 	memset(&ctxt, 0, sizeof(ctxt));
6257 	ctxt.pf_num = hw->pf_id;
6258 	ctxt.vf_num = 0;
6259 	ctxt.uplink_seid = uplink_seid;
6260 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
6261 	if (ch->type == I40E_VSI_VMDQ2)
6262 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
6263 
6264 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED) {
6265 		ctxt.info.valid_sections |=
6266 		     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6267 		ctxt.info.switch_id =
6268 		   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6269 	}
6270 
6271 	/* Set queue map for a given VSI context */
6272 	i40e_channel_setup_queue_map(pf, &ctxt, ch);
6273 
6274 	/* Now time to create VSI */
6275 	ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
6276 	if (ret) {
6277 		dev_info(&pf->pdev->dev,
6278 			 "add new vsi failed, err %pe aq_err %s\n",
6279 			 ERR_PTR(ret),
6280 			 i40e_aq_str(&pf->hw,
6281 				     pf->hw.aq.asq_last_status));
6282 		return -ENOENT;
6283 	}
6284 
6285 	/* Success, update channel, set enabled_tc only if the channel
6286 	 * is not a macvlan
6287 	 */
6288 	ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
6289 	ch->seid = ctxt.seid;
6290 	ch->vsi_number = ctxt.vsi_number;
6291 	ch->stat_counter_idx = le16_to_cpu(ctxt.info.stat_counter_idx);
6292 
6293 	/* copy just the sections touched not the entire info
6294 	 * since not all sections are valid as returned by
6295 	 * update vsi params
6296 	 */
6297 	ch->info.mapping_flags = ctxt.info.mapping_flags;
6298 	memcpy(&ch->info.queue_mapping,
6299 	       &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
6300 	memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
6301 	       sizeof(ctxt.info.tc_mapping));
6302 
6303 	return 0;
6304 }
6305 
6306 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
6307 				  u8 *bw_share)
6308 {
6309 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
6310 	int ret;
6311 	int i;
6312 
6313 	memset(&bw_data, 0, sizeof(bw_data));
6314 	bw_data.tc_valid_bits = ch->enabled_tc;
6315 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6316 		bw_data.tc_bw_credits[i] = bw_share[i];
6317 
6318 	ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
6319 				       &bw_data, NULL);
6320 	if (ret) {
6321 		dev_info(&vsi->back->pdev->dev,
6322 			 "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
6323 			 vsi->back->hw.aq.asq_last_status, ch->seid);
6324 		return -EINVAL;
6325 	}
6326 
6327 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6328 		ch->info.qs_handle[i] = bw_data.qs_handles[i];
6329 
6330 	return 0;
6331 }
6332 
6333 /**
6334  * i40e_channel_config_tx_ring - config TX ring associated with new channel
6335  * @pf: ptr to PF device
6336  * @vsi: the VSI being setup
6337  * @ch: ptr to channel structure
6338  *
6339  * Configure TX rings associated with channel (VSI) since queues are being
6340  * from parent VSI.
6341  **/
6342 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
6343 				       struct i40e_vsi *vsi,
6344 				       struct i40e_channel *ch)
6345 {
6346 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
6347 	int ret;
6348 	int i;
6349 
6350 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
6351 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6352 		if (ch->enabled_tc & BIT(i))
6353 			bw_share[i] = 1;
6354 	}
6355 
6356 	/* configure BW for new VSI */
6357 	ret = i40e_channel_config_bw(vsi, ch, bw_share);
6358 	if (ret) {
6359 		dev_info(&vsi->back->pdev->dev,
6360 			 "Failed configuring TC map %d for channel (seid %u)\n",
6361 			 ch->enabled_tc, ch->seid);
6362 		return ret;
6363 	}
6364 
6365 	for (i = 0; i < ch->num_queue_pairs; i++) {
6366 		struct i40e_ring *tx_ring, *rx_ring;
6367 		u16 pf_q;
6368 
6369 		pf_q = ch->base_queue + i;
6370 
6371 		/* Get to TX ring ptr of main VSI, for re-setup TX queue
6372 		 * context
6373 		 */
6374 		tx_ring = vsi->tx_rings[pf_q];
6375 		tx_ring->ch = ch;
6376 
6377 		/* Get the RX ring ptr */
6378 		rx_ring = vsi->rx_rings[pf_q];
6379 		rx_ring->ch = ch;
6380 	}
6381 
6382 	return 0;
6383 }
6384 
6385 /**
6386  * i40e_setup_hw_channel - setup new channel
6387  * @pf: ptr to PF device
6388  * @vsi: the VSI being setup
6389  * @ch: ptr to channel structure
6390  * @uplink_seid: underlying HW switching element (VEB) ID
6391  * @type: type of channel to be created (VMDq2/VF)
6392  *
6393  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6394  * and configures TX rings accordingly
6395  **/
6396 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
6397 					struct i40e_vsi *vsi,
6398 					struct i40e_channel *ch,
6399 					u16 uplink_seid, u8 type)
6400 {
6401 	int ret;
6402 
6403 	ch->initialized = false;
6404 	ch->base_queue = vsi->next_base_queue;
6405 	ch->type = type;
6406 
6407 	/* Proceed with creation of channel (VMDq2) VSI */
6408 	ret = i40e_add_channel(pf, uplink_seid, ch);
6409 	if (ret) {
6410 		dev_info(&pf->pdev->dev,
6411 			 "failed to add_channel using uplink_seid %u\n",
6412 			 uplink_seid);
6413 		return ret;
6414 	}
6415 
6416 	/* Mark the successful creation of channel */
6417 	ch->initialized = true;
6418 
6419 	/* Reconfigure TX queues using QTX_CTL register */
6420 	ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6421 	if (ret) {
6422 		dev_info(&pf->pdev->dev,
6423 			 "failed to configure TX rings for channel %u\n",
6424 			 ch->seid);
6425 		return ret;
6426 	}
6427 
6428 	/* update 'next_base_queue' */
6429 	vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6430 	dev_dbg(&pf->pdev->dev,
6431 		"Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6432 		ch->seid, ch->vsi_number, ch->stat_counter_idx,
6433 		ch->num_queue_pairs,
6434 		vsi->next_base_queue);
6435 	return ret;
6436 }
6437 
6438 /**
6439  * i40e_setup_channel - setup new channel using uplink element
6440  * @pf: ptr to PF device
6441  * @vsi: pointer to the VSI to set up the channel within
6442  * @ch: ptr to channel structure
6443  *
6444  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6445  * and uplink switching element (uplink_seid)
6446  **/
6447 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6448 			       struct i40e_channel *ch)
6449 {
6450 	u8 vsi_type;
6451 	u16 seid;
6452 	int ret;
6453 
6454 	if (vsi->type == I40E_VSI_MAIN) {
6455 		vsi_type = I40E_VSI_VMDQ2;
6456 	} else {
6457 		dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6458 			vsi->type);
6459 		return false;
6460 	}
6461 
6462 	/* underlying switching element */
6463 	seid = pf->vsi[pf->lan_vsi]->uplink_seid;
6464 
6465 	/* create channel (VSI), configure TX rings */
6466 	ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6467 	if (ret) {
6468 		dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6469 		return false;
6470 	}
6471 
6472 	return ch->initialized ? true : false;
6473 }
6474 
6475 /**
6476  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6477  * @vsi: ptr to VSI which has PF backing
6478  *
6479  * Sets up switch mode correctly if it needs to be changed and perform
6480  * what are allowed modes.
6481  **/
6482 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6483 {
6484 	u8 mode;
6485 	struct i40e_pf *pf = vsi->back;
6486 	struct i40e_hw *hw = &pf->hw;
6487 	int ret;
6488 
6489 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6490 	if (ret)
6491 		return -EINVAL;
6492 
6493 	if (hw->dev_caps.switch_mode) {
6494 		/* if switch mode is set, support mode2 (non-tunneled for
6495 		 * cloud filter) for now
6496 		 */
6497 		u32 switch_mode = hw->dev_caps.switch_mode &
6498 				  I40E_SWITCH_MODE_MASK;
6499 		if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6500 			if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6501 				return 0;
6502 			dev_err(&pf->pdev->dev,
6503 				"Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6504 				hw->dev_caps.switch_mode);
6505 			return -EINVAL;
6506 		}
6507 	}
6508 
6509 	/* Set Bit 7 to be valid */
6510 	mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6511 
6512 	/* Set L4type for TCP support */
6513 	mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6514 
6515 	/* Set cloud filter mode */
6516 	mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6517 
6518 	/* Prep mode field for set_switch_config */
6519 	ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6520 					pf->last_sw_conf_valid_flags,
6521 					mode, NULL);
6522 	if (ret && hw->aq.asq_last_status != I40E_AQ_RC_ESRCH)
6523 		dev_err(&pf->pdev->dev,
6524 			"couldn't set switch config bits, err %pe aq_err %s\n",
6525 			ERR_PTR(ret),
6526 			i40e_aq_str(hw,
6527 				    hw->aq.asq_last_status));
6528 
6529 	return ret;
6530 }
6531 
6532 /**
6533  * i40e_create_queue_channel - function to create channel
6534  * @vsi: VSI to be configured
6535  * @ch: ptr to channel (it contains channel specific params)
6536  *
6537  * This function creates channel (VSI) using num_queues specified by user,
6538  * reconfigs RSS if needed.
6539  **/
6540 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6541 			      struct i40e_channel *ch)
6542 {
6543 	struct i40e_pf *pf = vsi->back;
6544 	bool reconfig_rss;
6545 	int err;
6546 
6547 	if (!ch)
6548 		return -EINVAL;
6549 
6550 	if (!ch->num_queue_pairs) {
6551 		dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6552 			ch->num_queue_pairs);
6553 		return -EINVAL;
6554 	}
6555 
6556 	/* validate user requested num_queues for channel */
6557 	err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6558 				       &reconfig_rss);
6559 	if (err) {
6560 		dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6561 			 ch->num_queue_pairs);
6562 		return -EINVAL;
6563 	}
6564 
6565 	/* By default we are in VEPA mode, if this is the first VF/VMDq
6566 	 * VSI to be added switch to VEB mode.
6567 	 */
6568 
6569 	if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
6570 		pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
6571 
6572 		if (vsi->type == I40E_VSI_MAIN) {
6573 			if (i40e_is_tc_mqprio_enabled(pf))
6574 				i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
6575 			else
6576 				i40e_do_reset_safe(pf, I40E_PF_RESET_FLAG);
6577 		}
6578 		/* now onwards for main VSI, number of queues will be value
6579 		 * of TC0's queue count
6580 		 */
6581 	}
6582 
6583 	/* By this time, vsi->cnt_q_avail shall be set to non-zero and
6584 	 * it should be more than num_queues
6585 	 */
6586 	if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6587 		dev_dbg(&pf->pdev->dev,
6588 			"Error: cnt_q_avail (%u) less than num_queues %d\n",
6589 			vsi->cnt_q_avail, ch->num_queue_pairs);
6590 		return -EINVAL;
6591 	}
6592 
6593 	/* reconfig_rss only if vsi type is MAIN_VSI */
6594 	if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6595 		err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6596 		if (err) {
6597 			dev_info(&pf->pdev->dev,
6598 				 "Error: unable to reconfig rss for num_queues (%u)\n",
6599 				 ch->num_queue_pairs);
6600 			return -EINVAL;
6601 		}
6602 	}
6603 
6604 	if (!i40e_setup_channel(pf, vsi, ch)) {
6605 		dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6606 		return -EINVAL;
6607 	}
6608 
6609 	dev_info(&pf->pdev->dev,
6610 		 "Setup channel (id:%u) utilizing num_queues %d\n",
6611 		 ch->seid, ch->num_queue_pairs);
6612 
6613 	/* configure VSI for BW limit */
6614 	if (ch->max_tx_rate) {
6615 		u64 credits = ch->max_tx_rate;
6616 
6617 		if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6618 			return -EINVAL;
6619 
6620 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
6621 		dev_dbg(&pf->pdev->dev,
6622 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6623 			ch->max_tx_rate,
6624 			credits,
6625 			ch->seid);
6626 	}
6627 
6628 	/* in case of VF, this will be main SRIOV VSI */
6629 	ch->parent_vsi = vsi;
6630 
6631 	/* and update main_vsi's count for queue_available to use */
6632 	vsi->cnt_q_avail -= ch->num_queue_pairs;
6633 
6634 	return 0;
6635 }
6636 
6637 /**
6638  * i40e_configure_queue_channels - Add queue channel for the given TCs
6639  * @vsi: VSI to be configured
6640  *
6641  * Configures queue channel mapping to the given TCs
6642  **/
6643 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6644 {
6645 	struct i40e_channel *ch;
6646 	u64 max_rate = 0;
6647 	int ret = 0, i;
6648 
6649 	/* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6650 	vsi->tc_seid_map[0] = vsi->seid;
6651 	for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6652 		if (vsi->tc_config.enabled_tc & BIT(i)) {
6653 			ch = kzalloc(sizeof(*ch), GFP_KERNEL);
6654 			if (!ch) {
6655 				ret = -ENOMEM;
6656 				goto err_free;
6657 			}
6658 
6659 			INIT_LIST_HEAD(&ch->list);
6660 			ch->num_queue_pairs =
6661 				vsi->tc_config.tc_info[i].qcount;
6662 			ch->base_queue =
6663 				vsi->tc_config.tc_info[i].qoffset;
6664 
6665 			/* Bandwidth limit through tc interface is in bytes/s,
6666 			 * change to Mbit/s
6667 			 */
6668 			max_rate = vsi->mqprio_qopt.max_rate[i];
6669 			do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6670 			ch->max_tx_rate = max_rate;
6671 
6672 			list_add_tail(&ch->list, &vsi->ch_list);
6673 
6674 			ret = i40e_create_queue_channel(vsi, ch);
6675 			if (ret) {
6676 				dev_err(&vsi->back->pdev->dev,
6677 					"Failed creating queue channel with TC%d: queues %d\n",
6678 					i, ch->num_queue_pairs);
6679 				goto err_free;
6680 			}
6681 			vsi->tc_seid_map[i] = ch->seid;
6682 		}
6683 	}
6684 
6685 	/* reset to reconfigure TX queue contexts */
6686 	i40e_do_reset(vsi->back, I40E_PF_RESET_FLAG, true);
6687 	return ret;
6688 
6689 err_free:
6690 	i40e_remove_queue_channels(vsi);
6691 	return ret;
6692 }
6693 
6694 /**
6695  * i40e_veb_config_tc - Configure TCs for given VEB
6696  * @veb: given VEB
6697  * @enabled_tc: TC bitmap
6698  *
6699  * Configures given TC bitmap for VEB (switching) element
6700  **/
6701 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6702 {
6703 	struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6704 	struct i40e_pf *pf = veb->pf;
6705 	int ret = 0;
6706 	int i;
6707 
6708 	/* No TCs or already enabled TCs just return */
6709 	if (!enabled_tc || veb->enabled_tc == enabled_tc)
6710 		return ret;
6711 
6712 	bw_data.tc_valid_bits = enabled_tc;
6713 	/* bw_data.absolute_credits is not set (relative) */
6714 
6715 	/* Enable ETS TCs with equal BW Share for now */
6716 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6717 		if (enabled_tc & BIT(i))
6718 			bw_data.tc_bw_share_credits[i] = 1;
6719 	}
6720 
6721 	ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6722 						   &bw_data, NULL);
6723 	if (ret) {
6724 		dev_info(&pf->pdev->dev,
6725 			 "VEB bw config failed, err %pe aq_err %s\n",
6726 			 ERR_PTR(ret),
6727 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6728 		goto out;
6729 	}
6730 
6731 	/* Update the BW information */
6732 	ret = i40e_veb_get_bw_info(veb);
6733 	if (ret) {
6734 		dev_info(&pf->pdev->dev,
6735 			 "Failed getting veb bw config, err %pe aq_err %s\n",
6736 			 ERR_PTR(ret),
6737 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6738 	}
6739 
6740 out:
6741 	return ret;
6742 }
6743 
6744 #ifdef CONFIG_I40E_DCB
6745 /**
6746  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6747  * @pf: PF struct
6748  *
6749  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6750  * the caller would've quiesce all the VSIs before calling
6751  * this function
6752  **/
6753 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6754 {
6755 	u8 tc_map = 0;
6756 	int ret;
6757 	u8 v;
6758 
6759 	/* Enable the TCs available on PF to all VEBs */
6760 	tc_map = i40e_pf_get_tc_map(pf);
6761 	if (tc_map == I40E_DEFAULT_TRAFFIC_CLASS)
6762 		return;
6763 
6764 	for (v = 0; v < I40E_MAX_VEB; v++) {
6765 		if (!pf->veb[v])
6766 			continue;
6767 		ret = i40e_veb_config_tc(pf->veb[v], tc_map);
6768 		if (ret) {
6769 			dev_info(&pf->pdev->dev,
6770 				 "Failed configuring TC for VEB seid=%d\n",
6771 				 pf->veb[v]->seid);
6772 			/* Will try to configure as many components */
6773 		}
6774 	}
6775 
6776 	/* Update each VSI */
6777 	for (v = 0; v < pf->num_alloc_vsi; v++) {
6778 		if (!pf->vsi[v])
6779 			continue;
6780 
6781 		/* - Enable all TCs for the LAN VSI
6782 		 * - For all others keep them at TC0 for now
6783 		 */
6784 		if (v == pf->lan_vsi)
6785 			tc_map = i40e_pf_get_tc_map(pf);
6786 		else
6787 			tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6788 
6789 		ret = i40e_vsi_config_tc(pf->vsi[v], tc_map);
6790 		if (ret) {
6791 			dev_info(&pf->pdev->dev,
6792 				 "Failed configuring TC for VSI seid=%d\n",
6793 				 pf->vsi[v]->seid);
6794 			/* Will try to configure as many components */
6795 		} else {
6796 			/* Re-configure VSI vectors based on updated TC map */
6797 			i40e_vsi_map_rings_to_vectors(pf->vsi[v]);
6798 			if (pf->vsi[v]->netdev)
6799 				i40e_dcbnl_set_all(pf->vsi[v]);
6800 		}
6801 	}
6802 }
6803 
6804 /**
6805  * i40e_resume_port_tx - Resume port Tx
6806  * @pf: PF struct
6807  *
6808  * Resume a port's Tx and issue a PF reset in case of failure to
6809  * resume.
6810  **/
6811 static int i40e_resume_port_tx(struct i40e_pf *pf)
6812 {
6813 	struct i40e_hw *hw = &pf->hw;
6814 	int ret;
6815 
6816 	ret = i40e_aq_resume_port_tx(hw, NULL);
6817 	if (ret) {
6818 		dev_info(&pf->pdev->dev,
6819 			 "Resume Port Tx failed, err %pe aq_err %s\n",
6820 			  ERR_PTR(ret),
6821 			  i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6822 		/* Schedule PF reset to recover */
6823 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6824 		i40e_service_event_schedule(pf);
6825 	}
6826 
6827 	return ret;
6828 }
6829 
6830 /**
6831  * i40e_suspend_port_tx - Suspend port Tx
6832  * @pf: PF struct
6833  *
6834  * Suspend a port's Tx and issue a PF reset in case of failure.
6835  **/
6836 static int i40e_suspend_port_tx(struct i40e_pf *pf)
6837 {
6838 	struct i40e_hw *hw = &pf->hw;
6839 	int ret;
6840 
6841 	ret = i40e_aq_suspend_port_tx(hw, pf->mac_seid, NULL);
6842 	if (ret) {
6843 		dev_info(&pf->pdev->dev,
6844 			 "Suspend Port Tx failed, err %pe aq_err %s\n",
6845 			 ERR_PTR(ret),
6846 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6847 		/* Schedule PF reset to recover */
6848 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6849 		i40e_service_event_schedule(pf);
6850 	}
6851 
6852 	return ret;
6853 }
6854 
6855 /**
6856  * i40e_hw_set_dcb_config - Program new DCBX settings into HW
6857  * @pf: PF being configured
6858  * @new_cfg: New DCBX configuration
6859  *
6860  * Program DCB settings into HW and reconfigure VEB/VSIs on
6861  * given PF. Uses "Set LLDP MIB" AQC to program the hardware.
6862  **/
6863 static int i40e_hw_set_dcb_config(struct i40e_pf *pf,
6864 				  struct i40e_dcbx_config *new_cfg)
6865 {
6866 	struct i40e_dcbx_config *old_cfg = &pf->hw.local_dcbx_config;
6867 	int ret;
6868 
6869 	/* Check if need reconfiguration */
6870 	if (!memcmp(&new_cfg, &old_cfg, sizeof(new_cfg))) {
6871 		dev_dbg(&pf->pdev->dev, "No Change in DCB Config required.\n");
6872 		return 0;
6873 	}
6874 
6875 	/* Config change disable all VSIs */
6876 	i40e_pf_quiesce_all_vsi(pf);
6877 
6878 	/* Copy the new config to the current config */
6879 	*old_cfg = *new_cfg;
6880 	old_cfg->etsrec = old_cfg->etscfg;
6881 	ret = i40e_set_dcb_config(&pf->hw);
6882 	if (ret) {
6883 		dev_info(&pf->pdev->dev,
6884 			 "Set DCB Config failed, err %pe aq_err %s\n",
6885 			 ERR_PTR(ret),
6886 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6887 		goto out;
6888 	}
6889 
6890 	/* Changes in configuration update VEB/VSI */
6891 	i40e_dcb_reconfigure(pf);
6892 out:
6893 	/* In case of reset do not try to resume anything */
6894 	if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
6895 		/* Re-start the VSIs if disabled */
6896 		ret = i40e_resume_port_tx(pf);
6897 		/* In case of error no point in resuming VSIs */
6898 		if (ret)
6899 			goto err;
6900 		i40e_pf_unquiesce_all_vsi(pf);
6901 	}
6902 err:
6903 	return ret;
6904 }
6905 
6906 /**
6907  * i40e_hw_dcb_config - Program new DCBX settings into HW
6908  * @pf: PF being configured
6909  * @new_cfg: New DCBX configuration
6910  *
6911  * Program DCB settings into HW and reconfigure VEB/VSIs on
6912  * given PF
6913  **/
6914 int i40e_hw_dcb_config(struct i40e_pf *pf, struct i40e_dcbx_config *new_cfg)
6915 {
6916 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6917 	u8 prio_type[I40E_MAX_TRAFFIC_CLASS] = {0};
6918 	u32 mfs_tc[I40E_MAX_TRAFFIC_CLASS];
6919 	struct i40e_dcbx_config *old_cfg;
6920 	u8 mode[I40E_MAX_TRAFFIC_CLASS];
6921 	struct i40e_rx_pb_config pb_cfg;
6922 	struct i40e_hw *hw = &pf->hw;
6923 	u8 num_ports = hw->num_ports;
6924 	bool need_reconfig;
6925 	int ret = -EINVAL;
6926 	u8 lltc_map = 0;
6927 	u8 tc_map = 0;
6928 	u8 new_numtc;
6929 	u8 i;
6930 
6931 	dev_dbg(&pf->pdev->dev, "Configuring DCB registers directly\n");
6932 	/* Un-pack information to Program ETS HW via shared API
6933 	 * numtc, tcmap
6934 	 * LLTC map
6935 	 * ETS/NON-ETS arbiter mode
6936 	 * max exponent (credit refills)
6937 	 * Total number of ports
6938 	 * PFC priority bit-map
6939 	 * Priority Table
6940 	 * BW % per TC
6941 	 * Arbiter mode between UPs sharing same TC
6942 	 * TSA table (ETS or non-ETS)
6943 	 * EEE enabled or not
6944 	 * MFS TC table
6945 	 */
6946 
6947 	new_numtc = i40e_dcb_get_num_tc(new_cfg);
6948 
6949 	memset(&ets_data, 0, sizeof(ets_data));
6950 	for (i = 0; i < new_numtc; i++) {
6951 		tc_map |= BIT(i);
6952 		switch (new_cfg->etscfg.tsatable[i]) {
6953 		case I40E_IEEE_TSA_ETS:
6954 			prio_type[i] = I40E_DCB_PRIO_TYPE_ETS;
6955 			ets_data.tc_bw_share_credits[i] =
6956 					new_cfg->etscfg.tcbwtable[i];
6957 			break;
6958 		case I40E_IEEE_TSA_STRICT:
6959 			prio_type[i] = I40E_DCB_PRIO_TYPE_STRICT;
6960 			lltc_map |= BIT(i);
6961 			ets_data.tc_bw_share_credits[i] =
6962 					I40E_DCB_STRICT_PRIO_CREDITS;
6963 			break;
6964 		default:
6965 			/* Invalid TSA type */
6966 			need_reconfig = false;
6967 			goto out;
6968 		}
6969 	}
6970 
6971 	old_cfg = &hw->local_dcbx_config;
6972 	/* Check if need reconfiguration */
6973 	need_reconfig = i40e_dcb_need_reconfig(pf, old_cfg, new_cfg);
6974 
6975 	/* If needed, enable/disable frame tagging, disable all VSIs
6976 	 * and suspend port tx
6977 	 */
6978 	if (need_reconfig) {
6979 		/* Enable DCB tagging only when more than one TC */
6980 		if (new_numtc > 1)
6981 			pf->flags |= I40E_FLAG_DCB_ENABLED;
6982 		else
6983 			pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6984 
6985 		set_bit(__I40E_PORT_SUSPENDED, pf->state);
6986 		/* Reconfiguration needed quiesce all VSIs */
6987 		i40e_pf_quiesce_all_vsi(pf);
6988 		ret = i40e_suspend_port_tx(pf);
6989 		if (ret)
6990 			goto err;
6991 	}
6992 
6993 	/* Configure Port ETS Tx Scheduler */
6994 	ets_data.tc_valid_bits = tc_map;
6995 	ets_data.tc_strict_priority_flags = lltc_map;
6996 	ret = i40e_aq_config_switch_comp_ets
6997 		(hw, pf->mac_seid, &ets_data,
6998 		 i40e_aqc_opc_modify_switching_comp_ets, NULL);
6999 	if (ret) {
7000 		dev_info(&pf->pdev->dev,
7001 			 "Modify Port ETS failed, err %pe aq_err %s\n",
7002 			 ERR_PTR(ret),
7003 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7004 		goto out;
7005 	}
7006 
7007 	/* Configure Rx ETS HW */
7008 	memset(&mode, I40E_DCB_ARB_MODE_ROUND_ROBIN, sizeof(mode));
7009 	i40e_dcb_hw_set_num_tc(hw, new_numtc);
7010 	i40e_dcb_hw_rx_fifo_config(hw, I40E_DCB_ARB_MODE_ROUND_ROBIN,
7011 				   I40E_DCB_ARB_MODE_STRICT_PRIORITY,
7012 				   I40E_DCB_DEFAULT_MAX_EXPONENT,
7013 				   lltc_map);
7014 	i40e_dcb_hw_rx_cmd_monitor_config(hw, new_numtc, num_ports);
7015 	i40e_dcb_hw_rx_ets_bw_config(hw, new_cfg->etscfg.tcbwtable, mode,
7016 				     prio_type);
7017 	i40e_dcb_hw_pfc_config(hw, new_cfg->pfc.pfcenable,
7018 			       new_cfg->etscfg.prioritytable);
7019 	i40e_dcb_hw_rx_up2tc_config(hw, new_cfg->etscfg.prioritytable);
7020 
7021 	/* Configure Rx Packet Buffers in HW */
7022 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7023 		mfs_tc[i] = pf->vsi[pf->lan_vsi]->netdev->mtu;
7024 		mfs_tc[i] += I40E_PACKET_HDR_PAD;
7025 	}
7026 
7027 	i40e_dcb_hw_calculate_pool_sizes(hw, num_ports,
7028 					 false, new_cfg->pfc.pfcenable,
7029 					 mfs_tc, &pb_cfg);
7030 	i40e_dcb_hw_rx_pb_config(hw, &pf->pb_cfg, &pb_cfg);
7031 
7032 	/* Update the local Rx Packet buffer config */
7033 	pf->pb_cfg = pb_cfg;
7034 
7035 	/* Inform the FW about changes to DCB configuration */
7036 	ret = i40e_aq_dcb_updated(&pf->hw, NULL);
7037 	if (ret) {
7038 		dev_info(&pf->pdev->dev,
7039 			 "DCB Updated failed, err %pe aq_err %s\n",
7040 			 ERR_PTR(ret),
7041 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7042 		goto out;
7043 	}
7044 
7045 	/* Update the port DCBx configuration */
7046 	*old_cfg = *new_cfg;
7047 
7048 	/* Changes in configuration update VEB/VSI */
7049 	i40e_dcb_reconfigure(pf);
7050 out:
7051 	/* Re-start the VSIs if disabled */
7052 	if (need_reconfig) {
7053 		ret = i40e_resume_port_tx(pf);
7054 
7055 		clear_bit(__I40E_PORT_SUSPENDED, pf->state);
7056 		/* In case of error no point in resuming VSIs */
7057 		if (ret)
7058 			goto err;
7059 
7060 		/* Wait for the PF's queues to be disabled */
7061 		ret = i40e_pf_wait_queues_disabled(pf);
7062 		if (ret) {
7063 			/* Schedule PF reset to recover */
7064 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
7065 			i40e_service_event_schedule(pf);
7066 			goto err;
7067 		} else {
7068 			i40e_pf_unquiesce_all_vsi(pf);
7069 			set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7070 			set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
7071 		}
7072 		/* registers are set, lets apply */
7073 		if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB)
7074 			ret = i40e_hw_set_dcb_config(pf, new_cfg);
7075 	}
7076 
7077 err:
7078 	return ret;
7079 }
7080 
7081 /**
7082  * i40e_dcb_sw_default_config - Set default DCB configuration when DCB in SW
7083  * @pf: PF being queried
7084  *
7085  * Set default DCB configuration in case DCB is to be done in SW.
7086  **/
7087 int i40e_dcb_sw_default_config(struct i40e_pf *pf)
7088 {
7089 	struct i40e_dcbx_config *dcb_cfg = &pf->hw.local_dcbx_config;
7090 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
7091 	struct i40e_hw *hw = &pf->hw;
7092 	int err;
7093 
7094 	if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB) {
7095 		/* Update the local cached instance with TC0 ETS */
7096 		memset(&pf->tmp_cfg, 0, sizeof(struct i40e_dcbx_config));
7097 		pf->tmp_cfg.etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7098 		pf->tmp_cfg.etscfg.maxtcs = 0;
7099 		pf->tmp_cfg.etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7100 		pf->tmp_cfg.etscfg.tsatable[0] = I40E_IEEE_TSA_ETS;
7101 		pf->tmp_cfg.pfc.willing = I40E_IEEE_DEFAULT_PFC_WILLING;
7102 		pf->tmp_cfg.pfc.pfccap = I40E_MAX_TRAFFIC_CLASS;
7103 		/* FW needs one App to configure HW */
7104 		pf->tmp_cfg.numapps = I40E_IEEE_DEFAULT_NUM_APPS;
7105 		pf->tmp_cfg.app[0].selector = I40E_APP_SEL_ETHTYPE;
7106 		pf->tmp_cfg.app[0].priority = I40E_IEEE_DEFAULT_APP_PRIO;
7107 		pf->tmp_cfg.app[0].protocolid = I40E_APP_PROTOID_FCOE;
7108 
7109 		return i40e_hw_set_dcb_config(pf, &pf->tmp_cfg);
7110 	}
7111 
7112 	memset(&ets_data, 0, sizeof(ets_data));
7113 	ets_data.tc_valid_bits = I40E_DEFAULT_TRAFFIC_CLASS; /* TC0 only */
7114 	ets_data.tc_strict_priority_flags = 0; /* ETS */
7115 	ets_data.tc_bw_share_credits[0] = I40E_IEEE_DEFAULT_ETS_TCBW; /* 100% to TC0 */
7116 
7117 	/* Enable ETS on the Physical port */
7118 	err = i40e_aq_config_switch_comp_ets
7119 		(hw, pf->mac_seid, &ets_data,
7120 		 i40e_aqc_opc_enable_switching_comp_ets, NULL);
7121 	if (err) {
7122 		dev_info(&pf->pdev->dev,
7123 			 "Enable Port ETS failed, err %pe aq_err %s\n",
7124 			 ERR_PTR(err),
7125 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7126 		err = -ENOENT;
7127 		goto out;
7128 	}
7129 
7130 	/* Update the local cached instance with TC0 ETS */
7131 	dcb_cfg->etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7132 	dcb_cfg->etscfg.cbs = 0;
7133 	dcb_cfg->etscfg.maxtcs = I40E_MAX_TRAFFIC_CLASS;
7134 	dcb_cfg->etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7135 
7136 out:
7137 	return err;
7138 }
7139 
7140 /**
7141  * i40e_init_pf_dcb - Initialize DCB configuration
7142  * @pf: PF being configured
7143  *
7144  * Query the current DCB configuration and cache it
7145  * in the hardware structure
7146  **/
7147 static int i40e_init_pf_dcb(struct i40e_pf *pf)
7148 {
7149 	struct i40e_hw *hw = &pf->hw;
7150 	int err;
7151 
7152 	/* Do not enable DCB for SW1 and SW2 images even if the FW is capable
7153 	 * Also do not enable DCBx if FW LLDP agent is disabled
7154 	 */
7155 	if (pf->hw_features & I40E_HW_NO_DCB_SUPPORT) {
7156 		dev_info(&pf->pdev->dev, "DCB is not supported.\n");
7157 		err = -EOPNOTSUPP;
7158 		goto out;
7159 	}
7160 	if (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) {
7161 		dev_info(&pf->pdev->dev, "FW LLDP is disabled, attempting SW DCB\n");
7162 		err = i40e_dcb_sw_default_config(pf);
7163 		if (err) {
7164 			dev_info(&pf->pdev->dev, "Could not initialize SW DCB\n");
7165 			goto out;
7166 		}
7167 		dev_info(&pf->pdev->dev, "SW DCB initialization succeeded.\n");
7168 		pf->dcbx_cap = DCB_CAP_DCBX_HOST |
7169 			       DCB_CAP_DCBX_VER_IEEE;
7170 		/* at init capable but disabled */
7171 		pf->flags |= I40E_FLAG_DCB_CAPABLE;
7172 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7173 		goto out;
7174 	}
7175 	err = i40e_init_dcb(hw, true);
7176 	if (!err) {
7177 		/* Device/Function is not DCBX capable */
7178 		if ((!hw->func_caps.dcb) ||
7179 		    (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
7180 			dev_info(&pf->pdev->dev,
7181 				 "DCBX offload is not supported or is disabled for this PF.\n");
7182 		} else {
7183 			/* When status is not DISABLED then DCBX in FW */
7184 			pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
7185 				       DCB_CAP_DCBX_VER_IEEE;
7186 
7187 			pf->flags |= I40E_FLAG_DCB_CAPABLE;
7188 			/* Enable DCB tagging only when more than one TC
7189 			 * or explicitly disable if only one TC
7190 			 */
7191 			if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
7192 				pf->flags |= I40E_FLAG_DCB_ENABLED;
7193 			else
7194 				pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7195 			dev_dbg(&pf->pdev->dev,
7196 				"DCBX offload is supported for this PF.\n");
7197 		}
7198 	} else if (pf->hw.aq.asq_last_status == I40E_AQ_RC_EPERM) {
7199 		dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
7200 		pf->flags |= I40E_FLAG_DISABLE_FW_LLDP;
7201 	} else {
7202 		dev_info(&pf->pdev->dev,
7203 			 "Query for DCB configuration failed, err %pe aq_err %s\n",
7204 			 ERR_PTR(err),
7205 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7206 	}
7207 
7208 out:
7209 	return err;
7210 }
7211 #endif /* CONFIG_I40E_DCB */
7212 
7213 /**
7214  * i40e_print_link_message - print link up or down
7215  * @vsi: the VSI for which link needs a message
7216  * @isup: true of link is up, false otherwise
7217  */
7218 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
7219 {
7220 	enum i40e_aq_link_speed new_speed;
7221 	struct i40e_pf *pf = vsi->back;
7222 	char *speed = "Unknown";
7223 	char *fc = "Unknown";
7224 	char *fec = "";
7225 	char *req_fec = "";
7226 	char *an = "";
7227 
7228 	if (isup)
7229 		new_speed = pf->hw.phy.link_info.link_speed;
7230 	else
7231 		new_speed = I40E_LINK_SPEED_UNKNOWN;
7232 
7233 	if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
7234 		return;
7235 	vsi->current_isup = isup;
7236 	vsi->current_speed = new_speed;
7237 	if (!isup) {
7238 		netdev_info(vsi->netdev, "NIC Link is Down\n");
7239 		return;
7240 	}
7241 
7242 	/* Warn user if link speed on NPAR enabled partition is not at
7243 	 * least 10GB
7244 	 */
7245 	if (pf->hw.func_caps.npar_enable &&
7246 	    (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
7247 	     pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
7248 		netdev_warn(vsi->netdev,
7249 			    "The partition detected link speed that is less than 10Gbps\n");
7250 
7251 	switch (pf->hw.phy.link_info.link_speed) {
7252 	case I40E_LINK_SPEED_40GB:
7253 		speed = "40 G";
7254 		break;
7255 	case I40E_LINK_SPEED_20GB:
7256 		speed = "20 G";
7257 		break;
7258 	case I40E_LINK_SPEED_25GB:
7259 		speed = "25 G";
7260 		break;
7261 	case I40E_LINK_SPEED_10GB:
7262 		speed = "10 G";
7263 		break;
7264 	case I40E_LINK_SPEED_5GB:
7265 		speed = "5 G";
7266 		break;
7267 	case I40E_LINK_SPEED_2_5GB:
7268 		speed = "2.5 G";
7269 		break;
7270 	case I40E_LINK_SPEED_1GB:
7271 		speed = "1000 M";
7272 		break;
7273 	case I40E_LINK_SPEED_100MB:
7274 		speed = "100 M";
7275 		break;
7276 	default:
7277 		break;
7278 	}
7279 
7280 	switch (pf->hw.fc.current_mode) {
7281 	case I40E_FC_FULL:
7282 		fc = "RX/TX";
7283 		break;
7284 	case I40E_FC_TX_PAUSE:
7285 		fc = "TX";
7286 		break;
7287 	case I40E_FC_RX_PAUSE:
7288 		fc = "RX";
7289 		break;
7290 	default:
7291 		fc = "None";
7292 		break;
7293 	}
7294 
7295 	if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
7296 		req_fec = "None";
7297 		fec = "None";
7298 		an = "False";
7299 
7300 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7301 			an = "True";
7302 
7303 		if (pf->hw.phy.link_info.fec_info &
7304 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7305 			fec = "CL74 FC-FEC/BASE-R";
7306 		else if (pf->hw.phy.link_info.fec_info &
7307 			 I40E_AQ_CONFIG_FEC_RS_ENA)
7308 			fec = "CL108 RS-FEC";
7309 
7310 		/* 'CL108 RS-FEC' should be displayed when RS is requested, or
7311 		 * both RS and FC are requested
7312 		 */
7313 		if (vsi->back->hw.phy.link_info.req_fec_info &
7314 		    (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
7315 			if (vsi->back->hw.phy.link_info.req_fec_info &
7316 			    I40E_AQ_REQUEST_FEC_RS)
7317 				req_fec = "CL108 RS-FEC";
7318 			else
7319 				req_fec = "CL74 FC-FEC/BASE-R";
7320 		}
7321 		netdev_info(vsi->netdev,
7322 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7323 			    speed, req_fec, fec, an, fc);
7324 	} else if (pf->hw.device_id == I40E_DEV_ID_KX_X722) {
7325 		req_fec = "None";
7326 		fec = "None";
7327 		an = "False";
7328 
7329 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7330 			an = "True";
7331 
7332 		if (pf->hw.phy.link_info.fec_info &
7333 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7334 			fec = "CL74 FC-FEC/BASE-R";
7335 
7336 		if (pf->hw.phy.link_info.req_fec_info &
7337 		    I40E_AQ_REQUEST_FEC_KR)
7338 			req_fec = "CL74 FC-FEC/BASE-R";
7339 
7340 		netdev_info(vsi->netdev,
7341 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7342 			    speed, req_fec, fec, an, fc);
7343 	} else {
7344 		netdev_info(vsi->netdev,
7345 			    "NIC Link is Up, %sbps Full Duplex, Flow Control: %s\n",
7346 			    speed, fc);
7347 	}
7348 
7349 }
7350 
7351 /**
7352  * i40e_up_complete - Finish the last steps of bringing up a connection
7353  * @vsi: the VSI being configured
7354  **/
7355 static int i40e_up_complete(struct i40e_vsi *vsi)
7356 {
7357 	struct i40e_pf *pf = vsi->back;
7358 	int err;
7359 
7360 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
7361 		i40e_vsi_configure_msix(vsi);
7362 	else
7363 		i40e_configure_msi_and_legacy(vsi);
7364 
7365 	/* start rings */
7366 	err = i40e_vsi_start_rings(vsi);
7367 	if (err)
7368 		return err;
7369 
7370 	clear_bit(__I40E_VSI_DOWN, vsi->state);
7371 	i40e_napi_enable_all(vsi);
7372 	i40e_vsi_enable_irq(vsi);
7373 
7374 	if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
7375 	    (vsi->netdev)) {
7376 		i40e_print_link_message(vsi, true);
7377 		netif_tx_start_all_queues(vsi->netdev);
7378 		netif_carrier_on(vsi->netdev);
7379 	}
7380 
7381 	/* replay FDIR SB filters */
7382 	if (vsi->type == I40E_VSI_FDIR) {
7383 		/* reset fd counters */
7384 		pf->fd_add_err = 0;
7385 		pf->fd_atr_cnt = 0;
7386 		i40e_fdir_filter_restore(vsi);
7387 	}
7388 
7389 	/* On the next run of the service_task, notify any clients of the new
7390 	 * opened netdev
7391 	 */
7392 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7393 	i40e_service_event_schedule(pf);
7394 
7395 	return 0;
7396 }
7397 
7398 /**
7399  * i40e_vsi_reinit_locked - Reset the VSI
7400  * @vsi: the VSI being configured
7401  *
7402  * Rebuild the ring structs after some configuration
7403  * has changed, e.g. MTU size.
7404  **/
7405 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
7406 {
7407 	struct i40e_pf *pf = vsi->back;
7408 
7409 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
7410 		usleep_range(1000, 2000);
7411 	i40e_down(vsi);
7412 
7413 	i40e_up(vsi);
7414 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
7415 }
7416 
7417 /**
7418  * i40e_force_link_state - Force the link status
7419  * @pf: board private structure
7420  * @is_up: whether the link state should be forced up or down
7421  **/
7422 static int i40e_force_link_state(struct i40e_pf *pf, bool is_up)
7423 {
7424 	struct i40e_aq_get_phy_abilities_resp abilities;
7425 	struct i40e_aq_set_phy_config config = {0};
7426 	bool non_zero_phy_type = is_up;
7427 	struct i40e_hw *hw = &pf->hw;
7428 	u64 mask;
7429 	u8 speed;
7430 	int err;
7431 
7432 	/* Card might've been put in an unstable state by other drivers
7433 	 * and applications, which causes incorrect speed values being
7434 	 * set on startup. In order to clear speed registers, we call
7435 	 * get_phy_capabilities twice, once to get initial state of
7436 	 * available speeds, and once to get current PHY config.
7437 	 */
7438 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
7439 					   NULL);
7440 	if (err) {
7441 		dev_err(&pf->pdev->dev,
7442 			"failed to get phy cap., ret =  %pe last_status =  %s\n",
7443 			ERR_PTR(err),
7444 			i40e_aq_str(hw, hw->aq.asq_last_status));
7445 		return err;
7446 	}
7447 	speed = abilities.link_speed;
7448 
7449 	/* Get the current phy config */
7450 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
7451 					   NULL);
7452 	if (err) {
7453 		dev_err(&pf->pdev->dev,
7454 			"failed to get phy cap., ret =  %pe last_status =  %s\n",
7455 			ERR_PTR(err),
7456 			i40e_aq_str(hw, hw->aq.asq_last_status));
7457 		return err;
7458 	}
7459 
7460 	/* If link needs to go up, but was not forced to go down,
7461 	 * and its speed values are OK, no need for a flap
7462 	 * if non_zero_phy_type was set, still need to force up
7463 	 */
7464 	if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED)
7465 		non_zero_phy_type = true;
7466 	else if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
7467 		return 0;
7468 
7469 	/* To force link we need to set bits for all supported PHY types,
7470 	 * but there are now more than 32, so we need to split the bitmap
7471 	 * across two fields.
7472 	 */
7473 	mask = I40E_PHY_TYPES_BITMASK;
7474 	config.phy_type =
7475 		non_zero_phy_type ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
7476 	config.phy_type_ext =
7477 		non_zero_phy_type ? (u8)((mask >> 32) & 0xff) : 0;
7478 	/* Copy the old settings, except of phy_type */
7479 	config.abilities = abilities.abilities;
7480 	if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED) {
7481 		if (is_up)
7482 			config.abilities |= I40E_AQ_PHY_ENABLE_LINK;
7483 		else
7484 			config.abilities &= ~(I40E_AQ_PHY_ENABLE_LINK);
7485 	}
7486 	if (abilities.link_speed != 0)
7487 		config.link_speed = abilities.link_speed;
7488 	else
7489 		config.link_speed = speed;
7490 	config.eee_capability = abilities.eee_capability;
7491 	config.eeer = abilities.eeer_val;
7492 	config.low_power_ctrl = abilities.d3_lpan;
7493 	config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
7494 			    I40E_AQ_PHY_FEC_CONFIG_MASK;
7495 	err = i40e_aq_set_phy_config(hw, &config, NULL);
7496 
7497 	if (err) {
7498 		dev_err(&pf->pdev->dev,
7499 			"set phy config ret =  %pe last_status =  %s\n",
7500 			ERR_PTR(err),
7501 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7502 		return err;
7503 	}
7504 
7505 	/* Update the link info */
7506 	err = i40e_update_link_info(hw);
7507 	if (err) {
7508 		/* Wait a little bit (on 40G cards it sometimes takes a really
7509 		 * long time for link to come back from the atomic reset)
7510 		 * and try once more
7511 		 */
7512 		msleep(1000);
7513 		i40e_update_link_info(hw);
7514 	}
7515 
7516 	i40e_aq_set_link_restart_an(hw, is_up, NULL);
7517 
7518 	return 0;
7519 }
7520 
7521 /**
7522  * i40e_up - Bring the connection back up after being down
7523  * @vsi: the VSI being configured
7524  **/
7525 int i40e_up(struct i40e_vsi *vsi)
7526 {
7527 	int err;
7528 
7529 	if (vsi->type == I40E_VSI_MAIN &&
7530 	    (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7531 	     vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7532 		i40e_force_link_state(vsi->back, true);
7533 
7534 	err = i40e_vsi_configure(vsi);
7535 	if (!err)
7536 		err = i40e_up_complete(vsi);
7537 
7538 	return err;
7539 }
7540 
7541 /**
7542  * i40e_down - Shutdown the connection processing
7543  * @vsi: the VSI being stopped
7544  **/
7545 void i40e_down(struct i40e_vsi *vsi)
7546 {
7547 	int i;
7548 
7549 	/* It is assumed that the caller of this function
7550 	 * sets the vsi->state __I40E_VSI_DOWN bit.
7551 	 */
7552 	if (vsi->netdev) {
7553 		netif_carrier_off(vsi->netdev);
7554 		netif_tx_disable(vsi->netdev);
7555 	}
7556 	i40e_vsi_disable_irq(vsi);
7557 	i40e_vsi_stop_rings(vsi);
7558 	if (vsi->type == I40E_VSI_MAIN &&
7559 	   (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7560 	    vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7561 		i40e_force_link_state(vsi->back, false);
7562 	i40e_napi_disable_all(vsi);
7563 
7564 	for (i = 0; i < vsi->num_queue_pairs; i++) {
7565 		i40e_clean_tx_ring(vsi->tx_rings[i]);
7566 		if (i40e_enabled_xdp_vsi(vsi)) {
7567 			/* Make sure that in-progress ndo_xdp_xmit and
7568 			 * ndo_xsk_wakeup calls are completed.
7569 			 */
7570 			synchronize_rcu();
7571 			i40e_clean_tx_ring(vsi->xdp_rings[i]);
7572 		}
7573 		i40e_clean_rx_ring(vsi->rx_rings[i]);
7574 	}
7575 
7576 }
7577 
7578 /**
7579  * i40e_validate_mqprio_qopt- validate queue mapping info
7580  * @vsi: the VSI being configured
7581  * @mqprio_qopt: queue parametrs
7582  **/
7583 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
7584 				     struct tc_mqprio_qopt_offload *mqprio_qopt)
7585 {
7586 	u64 sum_max_rate = 0;
7587 	u64 max_rate = 0;
7588 	int i;
7589 
7590 	if (mqprio_qopt->qopt.offset[0] != 0 ||
7591 	    mqprio_qopt->qopt.num_tc < 1 ||
7592 	    mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
7593 		return -EINVAL;
7594 	for (i = 0; ; i++) {
7595 		if (!mqprio_qopt->qopt.count[i])
7596 			return -EINVAL;
7597 		if (mqprio_qopt->min_rate[i]) {
7598 			dev_err(&vsi->back->pdev->dev,
7599 				"Invalid min tx rate (greater than 0) specified\n");
7600 			return -EINVAL;
7601 		}
7602 		max_rate = mqprio_qopt->max_rate[i];
7603 		do_div(max_rate, I40E_BW_MBPS_DIVISOR);
7604 		sum_max_rate += max_rate;
7605 
7606 		if (i >= mqprio_qopt->qopt.num_tc - 1)
7607 			break;
7608 		if (mqprio_qopt->qopt.offset[i + 1] !=
7609 		    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7610 			return -EINVAL;
7611 	}
7612 	if (vsi->num_queue_pairs <
7613 	    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
7614 		dev_err(&vsi->back->pdev->dev,
7615 			"Failed to create traffic channel, insufficient number of queues.\n");
7616 		return -EINVAL;
7617 	}
7618 	if (sum_max_rate > i40e_get_link_speed(vsi)) {
7619 		dev_err(&vsi->back->pdev->dev,
7620 			"Invalid max tx rate specified\n");
7621 		return -EINVAL;
7622 	}
7623 	return 0;
7624 }
7625 
7626 /**
7627  * i40e_vsi_set_default_tc_config - set default values for tc configuration
7628  * @vsi: the VSI being configured
7629  **/
7630 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
7631 {
7632 	u16 qcount;
7633 	int i;
7634 
7635 	/* Only TC0 is enabled */
7636 	vsi->tc_config.numtc = 1;
7637 	vsi->tc_config.enabled_tc = 1;
7638 	qcount = min_t(int, vsi->alloc_queue_pairs,
7639 		       i40e_pf_get_max_q_per_tc(vsi->back));
7640 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7641 		/* For the TC that is not enabled set the offset to default
7642 		 * queue and allocate one queue for the given TC.
7643 		 */
7644 		vsi->tc_config.tc_info[i].qoffset = 0;
7645 		if (i == 0)
7646 			vsi->tc_config.tc_info[i].qcount = qcount;
7647 		else
7648 			vsi->tc_config.tc_info[i].qcount = 1;
7649 		vsi->tc_config.tc_info[i].netdev_tc = 0;
7650 	}
7651 }
7652 
7653 /**
7654  * i40e_del_macvlan_filter
7655  * @hw: pointer to the HW structure
7656  * @seid: seid of the channel VSI
7657  * @macaddr: the mac address to apply as a filter
7658  * @aq_err: store the admin Q error
7659  *
7660  * This function deletes a mac filter on the channel VSI which serves as the
7661  * macvlan. Returns 0 on success.
7662  **/
7663 static int i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
7664 				   const u8 *macaddr, int *aq_err)
7665 {
7666 	struct i40e_aqc_remove_macvlan_element_data element;
7667 	int status;
7668 
7669 	memset(&element, 0, sizeof(element));
7670 	ether_addr_copy(element.mac_addr, macaddr);
7671 	element.vlan_tag = 0;
7672 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
7673 	status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
7674 	*aq_err = hw->aq.asq_last_status;
7675 
7676 	return status;
7677 }
7678 
7679 /**
7680  * i40e_add_macvlan_filter
7681  * @hw: pointer to the HW structure
7682  * @seid: seid of the channel VSI
7683  * @macaddr: the mac address to apply as a filter
7684  * @aq_err: store the admin Q error
7685  *
7686  * This function adds a mac filter on the channel VSI which serves as the
7687  * macvlan. Returns 0 on success.
7688  **/
7689 static int i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
7690 				   const u8 *macaddr, int *aq_err)
7691 {
7692 	struct i40e_aqc_add_macvlan_element_data element;
7693 	u16 cmd_flags = 0;
7694 	int status;
7695 
7696 	ether_addr_copy(element.mac_addr, macaddr);
7697 	element.vlan_tag = 0;
7698 	element.queue_number = 0;
7699 	element.match_method = I40E_AQC_MM_ERR_NO_RES;
7700 	cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
7701 	element.flags = cpu_to_le16(cmd_flags);
7702 	status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
7703 	*aq_err = hw->aq.asq_last_status;
7704 
7705 	return status;
7706 }
7707 
7708 /**
7709  * i40e_reset_ch_rings - Reset the queue contexts in a channel
7710  * @vsi: the VSI we want to access
7711  * @ch: the channel we want to access
7712  */
7713 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
7714 {
7715 	struct i40e_ring *tx_ring, *rx_ring;
7716 	u16 pf_q;
7717 	int i;
7718 
7719 	for (i = 0; i < ch->num_queue_pairs; i++) {
7720 		pf_q = ch->base_queue + i;
7721 		tx_ring = vsi->tx_rings[pf_q];
7722 		tx_ring->ch = NULL;
7723 		rx_ring = vsi->rx_rings[pf_q];
7724 		rx_ring->ch = NULL;
7725 	}
7726 }
7727 
7728 /**
7729  * i40e_free_macvlan_channels
7730  * @vsi: the VSI we want to access
7731  *
7732  * This function frees the Qs of the channel VSI from
7733  * the stack and also deletes the channel VSIs which
7734  * serve as macvlans.
7735  */
7736 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
7737 {
7738 	struct i40e_channel *ch, *ch_tmp;
7739 	int ret;
7740 
7741 	if (list_empty(&vsi->macvlan_list))
7742 		return;
7743 
7744 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7745 		struct i40e_vsi *parent_vsi;
7746 
7747 		if (i40e_is_channel_macvlan(ch)) {
7748 			i40e_reset_ch_rings(vsi, ch);
7749 			clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7750 			netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
7751 			netdev_set_sb_channel(ch->fwd->netdev, 0);
7752 			kfree(ch->fwd);
7753 			ch->fwd = NULL;
7754 		}
7755 
7756 		list_del(&ch->list);
7757 		parent_vsi = ch->parent_vsi;
7758 		if (!parent_vsi || !ch->initialized) {
7759 			kfree(ch);
7760 			continue;
7761 		}
7762 
7763 		/* remove the VSI */
7764 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
7765 					     NULL);
7766 		if (ret)
7767 			dev_err(&vsi->back->pdev->dev,
7768 				"unable to remove channel (%d) for parent VSI(%d)\n",
7769 				ch->seid, parent_vsi->seid);
7770 		kfree(ch);
7771 	}
7772 	vsi->macvlan_cnt = 0;
7773 }
7774 
7775 /**
7776  * i40e_fwd_ring_up - bring the macvlan device up
7777  * @vsi: the VSI we want to access
7778  * @vdev: macvlan netdevice
7779  * @fwd: the private fwd structure
7780  */
7781 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7782 			    struct i40e_fwd_adapter *fwd)
7783 {
7784 	struct i40e_channel *ch = NULL, *ch_tmp, *iter;
7785 	int ret = 0, num_tc = 1,  i, aq_err;
7786 	struct i40e_pf *pf = vsi->back;
7787 	struct i40e_hw *hw = &pf->hw;
7788 
7789 	/* Go through the list and find an available channel */
7790 	list_for_each_entry_safe(iter, ch_tmp, &vsi->macvlan_list, list) {
7791 		if (!i40e_is_channel_macvlan(iter)) {
7792 			iter->fwd = fwd;
7793 			/* record configuration for macvlan interface in vdev */
7794 			for (i = 0; i < num_tc; i++)
7795 				netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7796 							     i,
7797 							     iter->num_queue_pairs,
7798 							     iter->base_queue);
7799 			for (i = 0; i < iter->num_queue_pairs; i++) {
7800 				struct i40e_ring *tx_ring, *rx_ring;
7801 				u16 pf_q;
7802 
7803 				pf_q = iter->base_queue + i;
7804 
7805 				/* Get to TX ring ptr */
7806 				tx_ring = vsi->tx_rings[pf_q];
7807 				tx_ring->ch = iter;
7808 
7809 				/* Get the RX ring ptr */
7810 				rx_ring = vsi->rx_rings[pf_q];
7811 				rx_ring->ch = iter;
7812 			}
7813 			ch = iter;
7814 			break;
7815 		}
7816 	}
7817 
7818 	if (!ch)
7819 		return -EINVAL;
7820 
7821 	/* Guarantee all rings are updated before we update the
7822 	 * MAC address filter.
7823 	 */
7824 	wmb();
7825 
7826 	/* Add a mac filter */
7827 	ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7828 	if (ret) {
7829 		/* if we cannot add the MAC rule then disable the offload */
7830 		macvlan_release_l2fw_offload(vdev);
7831 		for (i = 0; i < ch->num_queue_pairs; i++) {
7832 			struct i40e_ring *rx_ring;
7833 			u16 pf_q;
7834 
7835 			pf_q = ch->base_queue + i;
7836 			rx_ring = vsi->rx_rings[pf_q];
7837 			rx_ring->netdev = NULL;
7838 		}
7839 		dev_info(&pf->pdev->dev,
7840 			 "Error adding mac filter on macvlan err %pe, aq_err %s\n",
7841 			  ERR_PTR(ret),
7842 			  i40e_aq_str(hw, aq_err));
7843 		netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7844 	}
7845 
7846 	return ret;
7847 }
7848 
7849 /**
7850  * i40e_setup_macvlans - create the channels which will be macvlans
7851  * @vsi: the VSI we want to access
7852  * @macvlan_cnt: no. of macvlans to be setup
7853  * @qcnt: no. of Qs per macvlan
7854  * @vdev: macvlan netdevice
7855  */
7856 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7857 			       struct net_device *vdev)
7858 {
7859 	struct i40e_pf *pf = vsi->back;
7860 	struct i40e_hw *hw = &pf->hw;
7861 	struct i40e_vsi_context ctxt;
7862 	u16 sections, qmap, num_qps;
7863 	struct i40e_channel *ch;
7864 	int i, pow, ret = 0;
7865 	u8 offset = 0;
7866 
7867 	if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7868 		return -EINVAL;
7869 
7870 	num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7871 
7872 	/* find the next higher power-of-2 of num queue pairs */
7873 	pow = fls(roundup_pow_of_two(num_qps) - 1);
7874 
7875 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7876 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7877 
7878 	/* Setup context bits for the main VSI */
7879 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7880 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7881 	memset(&ctxt, 0, sizeof(ctxt));
7882 	ctxt.seid = vsi->seid;
7883 	ctxt.pf_num = vsi->back->hw.pf_id;
7884 	ctxt.vf_num = 0;
7885 	ctxt.uplink_seid = vsi->uplink_seid;
7886 	ctxt.info = vsi->info;
7887 	ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7888 	ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7889 	ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7890 	ctxt.info.valid_sections |= cpu_to_le16(sections);
7891 
7892 	/* Reconfigure RSS for main VSI with new max queue count */
7893 	vsi->rss_size = max_t(u16, num_qps, qcnt);
7894 	ret = i40e_vsi_config_rss(vsi);
7895 	if (ret) {
7896 		dev_info(&pf->pdev->dev,
7897 			 "Failed to reconfig RSS for num_queues (%u)\n",
7898 			 vsi->rss_size);
7899 		return ret;
7900 	}
7901 	vsi->reconfig_rss = true;
7902 	dev_dbg(&vsi->back->pdev->dev,
7903 		"Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7904 	vsi->next_base_queue = num_qps;
7905 	vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7906 
7907 	/* Update the VSI after updating the VSI queue-mapping
7908 	 * information
7909 	 */
7910 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7911 	if (ret) {
7912 		dev_info(&pf->pdev->dev,
7913 			 "Update vsi tc config failed, err %pe aq_err %s\n",
7914 			 ERR_PTR(ret),
7915 			 i40e_aq_str(hw, hw->aq.asq_last_status));
7916 		return ret;
7917 	}
7918 	/* update the local VSI info with updated queue map */
7919 	i40e_vsi_update_queue_map(vsi, &ctxt);
7920 	vsi->info.valid_sections = 0;
7921 
7922 	/* Create channels for macvlans */
7923 	INIT_LIST_HEAD(&vsi->macvlan_list);
7924 	for (i = 0; i < macvlan_cnt; i++) {
7925 		ch = kzalloc(sizeof(*ch), GFP_KERNEL);
7926 		if (!ch) {
7927 			ret = -ENOMEM;
7928 			goto err_free;
7929 		}
7930 		INIT_LIST_HEAD(&ch->list);
7931 		ch->num_queue_pairs = qcnt;
7932 		if (!i40e_setup_channel(pf, vsi, ch)) {
7933 			ret = -EINVAL;
7934 			kfree(ch);
7935 			goto err_free;
7936 		}
7937 		ch->parent_vsi = vsi;
7938 		vsi->cnt_q_avail -= ch->num_queue_pairs;
7939 		vsi->macvlan_cnt++;
7940 		list_add_tail(&ch->list, &vsi->macvlan_list);
7941 	}
7942 
7943 	return ret;
7944 
7945 err_free:
7946 	dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
7947 	i40e_free_macvlan_channels(vsi);
7948 
7949 	return ret;
7950 }
7951 
7952 /**
7953  * i40e_fwd_add - configure macvlans
7954  * @netdev: net device to configure
7955  * @vdev: macvlan netdevice
7956  **/
7957 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
7958 {
7959 	struct i40e_netdev_priv *np = netdev_priv(netdev);
7960 	u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
7961 	struct i40e_vsi *vsi = np->vsi;
7962 	struct i40e_pf *pf = vsi->back;
7963 	struct i40e_fwd_adapter *fwd;
7964 	int avail_macvlan, ret;
7965 
7966 	if ((pf->flags & I40E_FLAG_DCB_ENABLED)) {
7967 		netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
7968 		return ERR_PTR(-EINVAL);
7969 	}
7970 	if (i40e_is_tc_mqprio_enabled(pf)) {
7971 		netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
7972 		return ERR_PTR(-EINVAL);
7973 	}
7974 	if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
7975 		netdev_info(netdev, "Not enough vectors available to support macvlans\n");
7976 		return ERR_PTR(-EINVAL);
7977 	}
7978 
7979 	/* The macvlan device has to be a single Q device so that the
7980 	 * tc_to_txq field can be reused to pick the tx queue.
7981 	 */
7982 	if (netif_is_multiqueue(vdev))
7983 		return ERR_PTR(-ERANGE);
7984 
7985 	if (!vsi->macvlan_cnt) {
7986 		/* reserve bit 0 for the pf device */
7987 		set_bit(0, vsi->fwd_bitmask);
7988 
7989 		/* Try to reserve as many queues as possible for macvlans. First
7990 		 * reserve 3/4th of max vectors, then half, then quarter and
7991 		 * calculate Qs per macvlan as you go
7992 		 */
7993 		vectors = pf->num_lan_msix;
7994 		if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
7995 			/* allocate 4 Qs per macvlan and 32 Qs to the PF*/
7996 			q_per_macvlan = 4;
7997 			macvlan_cnt = (vectors - 32) / 4;
7998 		} else if (vectors <= 64 && vectors > 32) {
7999 			/* allocate 2 Qs per macvlan and 16 Qs to the PF*/
8000 			q_per_macvlan = 2;
8001 			macvlan_cnt = (vectors - 16) / 2;
8002 		} else if (vectors <= 32 && vectors > 16) {
8003 			/* allocate 1 Q per macvlan and 16 Qs to the PF*/
8004 			q_per_macvlan = 1;
8005 			macvlan_cnt = vectors - 16;
8006 		} else if (vectors <= 16 && vectors > 8) {
8007 			/* allocate 1 Q per macvlan and 8 Qs to the PF */
8008 			q_per_macvlan = 1;
8009 			macvlan_cnt = vectors - 8;
8010 		} else {
8011 			/* allocate 1 Q per macvlan and 1 Q to the PF */
8012 			q_per_macvlan = 1;
8013 			macvlan_cnt = vectors - 1;
8014 		}
8015 
8016 		if (macvlan_cnt == 0)
8017 			return ERR_PTR(-EBUSY);
8018 
8019 		/* Quiesce VSI queues */
8020 		i40e_quiesce_vsi(vsi);
8021 
8022 		/* sets up the macvlans but does not "enable" them */
8023 		ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
8024 					  vdev);
8025 		if (ret)
8026 			return ERR_PTR(ret);
8027 
8028 		/* Unquiesce VSI */
8029 		i40e_unquiesce_vsi(vsi);
8030 	}
8031 	avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
8032 					    vsi->macvlan_cnt);
8033 	if (avail_macvlan >= I40E_MAX_MACVLANS)
8034 		return ERR_PTR(-EBUSY);
8035 
8036 	/* create the fwd struct */
8037 	fwd = kzalloc(sizeof(*fwd), GFP_KERNEL);
8038 	if (!fwd)
8039 		return ERR_PTR(-ENOMEM);
8040 
8041 	set_bit(avail_macvlan, vsi->fwd_bitmask);
8042 	fwd->bit_no = avail_macvlan;
8043 	netdev_set_sb_channel(vdev, avail_macvlan);
8044 	fwd->netdev = vdev;
8045 
8046 	if (!netif_running(netdev))
8047 		return fwd;
8048 
8049 	/* Set fwd ring up */
8050 	ret = i40e_fwd_ring_up(vsi, vdev, fwd);
8051 	if (ret) {
8052 		/* unbind the queues and drop the subordinate channel config */
8053 		netdev_unbind_sb_channel(netdev, vdev);
8054 		netdev_set_sb_channel(vdev, 0);
8055 
8056 		kfree(fwd);
8057 		return ERR_PTR(-EINVAL);
8058 	}
8059 
8060 	return fwd;
8061 }
8062 
8063 /**
8064  * i40e_del_all_macvlans - Delete all the mac filters on the channels
8065  * @vsi: the VSI we want to access
8066  */
8067 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
8068 {
8069 	struct i40e_channel *ch, *ch_tmp;
8070 	struct i40e_pf *pf = vsi->back;
8071 	struct i40e_hw *hw = &pf->hw;
8072 	int aq_err, ret = 0;
8073 
8074 	if (list_empty(&vsi->macvlan_list))
8075 		return;
8076 
8077 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8078 		if (i40e_is_channel_macvlan(ch)) {
8079 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8080 						      i40e_channel_mac(ch),
8081 						      &aq_err);
8082 			if (!ret) {
8083 				/* Reset queue contexts */
8084 				i40e_reset_ch_rings(vsi, ch);
8085 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8086 				netdev_unbind_sb_channel(vsi->netdev,
8087 							 ch->fwd->netdev);
8088 				netdev_set_sb_channel(ch->fwd->netdev, 0);
8089 				kfree(ch->fwd);
8090 				ch->fwd = NULL;
8091 			}
8092 		}
8093 	}
8094 }
8095 
8096 /**
8097  * i40e_fwd_del - delete macvlan interfaces
8098  * @netdev: net device to configure
8099  * @vdev: macvlan netdevice
8100  */
8101 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
8102 {
8103 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8104 	struct i40e_fwd_adapter *fwd = vdev;
8105 	struct i40e_channel *ch, *ch_tmp;
8106 	struct i40e_vsi *vsi = np->vsi;
8107 	struct i40e_pf *pf = vsi->back;
8108 	struct i40e_hw *hw = &pf->hw;
8109 	int aq_err, ret = 0;
8110 
8111 	/* Find the channel associated with the macvlan and del mac filter */
8112 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8113 		if (i40e_is_channel_macvlan(ch) &&
8114 		    ether_addr_equal(i40e_channel_mac(ch),
8115 				     fwd->netdev->dev_addr)) {
8116 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8117 						      i40e_channel_mac(ch),
8118 						      &aq_err);
8119 			if (!ret) {
8120 				/* Reset queue contexts */
8121 				i40e_reset_ch_rings(vsi, ch);
8122 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8123 				netdev_unbind_sb_channel(netdev, fwd->netdev);
8124 				netdev_set_sb_channel(fwd->netdev, 0);
8125 				kfree(ch->fwd);
8126 				ch->fwd = NULL;
8127 			} else {
8128 				dev_info(&pf->pdev->dev,
8129 					 "Error deleting mac filter on macvlan err %pe, aq_err %s\n",
8130 					  ERR_PTR(ret),
8131 					  i40e_aq_str(hw, aq_err));
8132 			}
8133 			break;
8134 		}
8135 	}
8136 }
8137 
8138 /**
8139  * i40e_setup_tc - configure multiple traffic classes
8140  * @netdev: net device to configure
8141  * @type_data: tc offload data
8142  **/
8143 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
8144 {
8145 	struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
8146 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8147 	struct i40e_vsi *vsi = np->vsi;
8148 	struct i40e_pf *pf = vsi->back;
8149 	u8 enabled_tc = 0, num_tc, hw;
8150 	bool need_reset = false;
8151 	int old_queue_pairs;
8152 	int ret = -EINVAL;
8153 	u16 mode;
8154 	int i;
8155 
8156 	old_queue_pairs = vsi->num_queue_pairs;
8157 	num_tc = mqprio_qopt->qopt.num_tc;
8158 	hw = mqprio_qopt->qopt.hw;
8159 	mode = mqprio_qopt->mode;
8160 	if (!hw) {
8161 		pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8162 		memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8163 		goto config_tc;
8164 	}
8165 
8166 	/* Check if MFP enabled */
8167 	if (pf->flags & I40E_FLAG_MFP_ENABLED) {
8168 		netdev_info(netdev,
8169 			    "Configuring TC not supported in MFP mode\n");
8170 		return ret;
8171 	}
8172 	switch (mode) {
8173 	case TC_MQPRIO_MODE_DCB:
8174 		pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8175 
8176 		/* Check if DCB enabled to continue */
8177 		if (!(pf->flags & I40E_FLAG_DCB_ENABLED)) {
8178 			netdev_info(netdev,
8179 				    "DCB is not enabled for adapter\n");
8180 			return ret;
8181 		}
8182 
8183 		/* Check whether tc count is within enabled limit */
8184 		if (num_tc > i40e_pf_get_num_tc(pf)) {
8185 			netdev_info(netdev,
8186 				    "TC count greater than enabled on link for adapter\n");
8187 			return ret;
8188 		}
8189 		break;
8190 	case TC_MQPRIO_MODE_CHANNEL:
8191 		if (pf->flags & I40E_FLAG_DCB_ENABLED) {
8192 			netdev_info(netdev,
8193 				    "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
8194 			return ret;
8195 		}
8196 		if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
8197 			return ret;
8198 		ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
8199 		if (ret)
8200 			return ret;
8201 		memcpy(&vsi->mqprio_qopt, mqprio_qopt,
8202 		       sizeof(*mqprio_qopt));
8203 		pf->flags |= I40E_FLAG_TC_MQPRIO;
8204 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
8205 		break;
8206 	default:
8207 		return -EINVAL;
8208 	}
8209 
8210 config_tc:
8211 	/* Generate TC map for number of tc requested */
8212 	for (i = 0; i < num_tc; i++)
8213 		enabled_tc |= BIT(i);
8214 
8215 	/* Requesting same TC configuration as already enabled */
8216 	if (enabled_tc == vsi->tc_config.enabled_tc &&
8217 	    mode != TC_MQPRIO_MODE_CHANNEL)
8218 		return 0;
8219 
8220 	/* Quiesce VSI queues */
8221 	i40e_quiesce_vsi(vsi);
8222 
8223 	if (!hw && !i40e_is_tc_mqprio_enabled(pf))
8224 		i40e_remove_queue_channels(vsi);
8225 
8226 	/* Configure VSI for enabled TCs */
8227 	ret = i40e_vsi_config_tc(vsi, enabled_tc);
8228 	if (ret) {
8229 		netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
8230 			    vsi->seid);
8231 		need_reset = true;
8232 		goto exit;
8233 	} else if (enabled_tc &&
8234 		   (!is_power_of_2(vsi->tc_config.tc_info[0].qcount))) {
8235 		netdev_info(netdev,
8236 			    "Failed to create channel. Override queues (%u) not power of 2\n",
8237 			    vsi->tc_config.tc_info[0].qcount);
8238 		ret = -EINVAL;
8239 		need_reset = true;
8240 		goto exit;
8241 	}
8242 
8243 	dev_info(&vsi->back->pdev->dev,
8244 		 "Setup channel (id:%u) utilizing num_queues %d\n",
8245 		 vsi->seid, vsi->tc_config.tc_info[0].qcount);
8246 
8247 	if (i40e_is_tc_mqprio_enabled(pf)) {
8248 		if (vsi->mqprio_qopt.max_rate[0]) {
8249 			u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
8250 						  vsi->mqprio_qopt.max_rate[0]);
8251 
8252 			ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
8253 			if (!ret) {
8254 				u64 credits = max_tx_rate;
8255 
8256 				do_div(credits, I40E_BW_CREDIT_DIVISOR);
8257 				dev_dbg(&vsi->back->pdev->dev,
8258 					"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
8259 					max_tx_rate,
8260 					credits,
8261 					vsi->seid);
8262 			} else {
8263 				need_reset = true;
8264 				goto exit;
8265 			}
8266 		}
8267 		ret = i40e_configure_queue_channels(vsi);
8268 		if (ret) {
8269 			vsi->num_queue_pairs = old_queue_pairs;
8270 			netdev_info(netdev,
8271 				    "Failed configuring queue channels\n");
8272 			need_reset = true;
8273 			goto exit;
8274 		}
8275 	}
8276 
8277 exit:
8278 	/* Reset the configuration data to defaults, only TC0 is enabled */
8279 	if (need_reset) {
8280 		i40e_vsi_set_default_tc_config(vsi);
8281 		need_reset = false;
8282 	}
8283 
8284 	/* Unquiesce VSI */
8285 	i40e_unquiesce_vsi(vsi);
8286 	return ret;
8287 }
8288 
8289 /**
8290  * i40e_set_cld_element - sets cloud filter element data
8291  * @filter: cloud filter rule
8292  * @cld: ptr to cloud filter element data
8293  *
8294  * This is helper function to copy data into cloud filter element
8295  **/
8296 static inline void
8297 i40e_set_cld_element(struct i40e_cloud_filter *filter,
8298 		     struct i40e_aqc_cloud_filters_element_data *cld)
8299 {
8300 	u32 ipa;
8301 	int i;
8302 
8303 	memset(cld, 0, sizeof(*cld));
8304 	ether_addr_copy(cld->outer_mac, filter->dst_mac);
8305 	ether_addr_copy(cld->inner_mac, filter->src_mac);
8306 
8307 	if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
8308 		return;
8309 
8310 	if (filter->n_proto == ETH_P_IPV6) {
8311 #define IPV6_MAX_INDEX	(ARRAY_SIZE(filter->dst_ipv6) - 1)
8312 		for (i = 0; i < ARRAY_SIZE(filter->dst_ipv6); i++) {
8313 			ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
8314 
8315 			*(__le32 *)&cld->ipaddr.raw_v6.data[i * 2] = cpu_to_le32(ipa);
8316 		}
8317 	} else {
8318 		ipa = be32_to_cpu(filter->dst_ipv4);
8319 
8320 		memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
8321 	}
8322 
8323 	cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
8324 
8325 	/* tenant_id is not supported by FW now, once the support is enabled
8326 	 * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
8327 	 */
8328 	if (filter->tenant_id)
8329 		return;
8330 }
8331 
8332 /**
8333  * i40e_add_del_cloud_filter - Add/del cloud filter
8334  * @vsi: pointer to VSI
8335  * @filter: cloud filter rule
8336  * @add: if true, add, if false, delete
8337  *
8338  * Add or delete a cloud filter for a specific flow spec.
8339  * Returns 0 if the filter were successfully added.
8340  **/
8341 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
8342 			      struct i40e_cloud_filter *filter, bool add)
8343 {
8344 	struct i40e_aqc_cloud_filters_element_data cld_filter;
8345 	struct i40e_pf *pf = vsi->back;
8346 	int ret;
8347 	static const u16 flag_table[128] = {
8348 		[I40E_CLOUD_FILTER_FLAGS_OMAC]  =
8349 			I40E_AQC_ADD_CLOUD_FILTER_OMAC,
8350 		[I40E_CLOUD_FILTER_FLAGS_IMAC]  =
8351 			I40E_AQC_ADD_CLOUD_FILTER_IMAC,
8352 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
8353 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
8354 		[I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
8355 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
8356 		[I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
8357 			I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
8358 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
8359 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
8360 		[I40E_CLOUD_FILTER_FLAGS_IIP] =
8361 			I40E_AQC_ADD_CLOUD_FILTER_IIP,
8362 	};
8363 
8364 	if (filter->flags >= ARRAY_SIZE(flag_table))
8365 		return -EIO;
8366 
8367 	memset(&cld_filter, 0, sizeof(cld_filter));
8368 
8369 	/* copy element needed to add cloud filter from filter */
8370 	i40e_set_cld_element(filter, &cld_filter);
8371 
8372 	if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
8373 		cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
8374 					     I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
8375 
8376 	if (filter->n_proto == ETH_P_IPV6)
8377 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8378 						I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8379 	else
8380 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8381 						I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8382 
8383 	if (add)
8384 		ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
8385 						&cld_filter, 1);
8386 	else
8387 		ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
8388 						&cld_filter, 1);
8389 	if (ret)
8390 		dev_dbg(&pf->pdev->dev,
8391 			"Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
8392 			add ? "add" : "delete", filter->dst_port, ret,
8393 			pf->hw.aq.asq_last_status);
8394 	else
8395 		dev_info(&pf->pdev->dev,
8396 			 "%s cloud filter for VSI: %d\n",
8397 			 add ? "Added" : "Deleted", filter->seid);
8398 	return ret;
8399 }
8400 
8401 /**
8402  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
8403  * @vsi: pointer to VSI
8404  * @filter: cloud filter rule
8405  * @add: if true, add, if false, delete
8406  *
8407  * Add or delete a cloud filter for a specific flow spec using big buffer.
8408  * Returns 0 if the filter were successfully added.
8409  **/
8410 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
8411 				      struct i40e_cloud_filter *filter,
8412 				      bool add)
8413 {
8414 	struct i40e_aqc_cloud_filters_element_bb cld_filter;
8415 	struct i40e_pf *pf = vsi->back;
8416 	int ret;
8417 
8418 	/* Both (src/dst) valid mac_addr are not supported */
8419 	if ((is_valid_ether_addr(filter->dst_mac) &&
8420 	     is_valid_ether_addr(filter->src_mac)) ||
8421 	    (is_multicast_ether_addr(filter->dst_mac) &&
8422 	     is_multicast_ether_addr(filter->src_mac)))
8423 		return -EOPNOTSUPP;
8424 
8425 	/* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
8426 	 * ports are not supported via big buffer now.
8427 	 */
8428 	if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
8429 		return -EOPNOTSUPP;
8430 
8431 	/* adding filter using src_port/src_ip is not supported at this stage */
8432 	if (filter->src_port ||
8433 	    (filter->src_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8434 	    !ipv6_addr_any(&filter->ip.v6.src_ip6))
8435 		return -EOPNOTSUPP;
8436 
8437 	memset(&cld_filter, 0, sizeof(cld_filter));
8438 
8439 	/* copy element needed to add cloud filter from filter */
8440 	i40e_set_cld_element(filter, &cld_filter.element);
8441 
8442 	if (is_valid_ether_addr(filter->dst_mac) ||
8443 	    is_valid_ether_addr(filter->src_mac) ||
8444 	    is_multicast_ether_addr(filter->dst_mac) ||
8445 	    is_multicast_ether_addr(filter->src_mac)) {
8446 		/* MAC + IP : unsupported mode */
8447 		if (filter->dst_ipv4)
8448 			return -EOPNOTSUPP;
8449 
8450 		/* since we validated that L4 port must be valid before
8451 		 * we get here, start with respective "flags" value
8452 		 * and update if vlan is present or not
8453 		 */
8454 		cld_filter.element.flags =
8455 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
8456 
8457 		if (filter->vlan_id) {
8458 			cld_filter.element.flags =
8459 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
8460 		}
8461 
8462 	} else if ((filter->dst_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8463 		   !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
8464 		cld_filter.element.flags =
8465 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
8466 		if (filter->n_proto == ETH_P_IPV6)
8467 			cld_filter.element.flags |=
8468 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8469 		else
8470 			cld_filter.element.flags |=
8471 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8472 	} else {
8473 		dev_err(&pf->pdev->dev,
8474 			"either mac or ip has to be valid for cloud filter\n");
8475 		return -EINVAL;
8476 	}
8477 
8478 	/* Now copy L4 port in Byte 6..7 in general fields */
8479 	cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
8480 						be16_to_cpu(filter->dst_port);
8481 
8482 	if (add) {
8483 		/* Validate current device switch mode, change if necessary */
8484 		ret = i40e_validate_and_set_switch_mode(vsi);
8485 		if (ret) {
8486 			dev_err(&pf->pdev->dev,
8487 				"failed to set switch mode, ret %d\n",
8488 				ret);
8489 			return ret;
8490 		}
8491 
8492 		ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
8493 						   &cld_filter, 1);
8494 	} else {
8495 		ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
8496 						   &cld_filter, 1);
8497 	}
8498 
8499 	if (ret)
8500 		dev_dbg(&pf->pdev->dev,
8501 			"Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
8502 			add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
8503 	else
8504 		dev_info(&pf->pdev->dev,
8505 			 "%s cloud filter for VSI: %d, L4 port: %d\n",
8506 			 add ? "add" : "delete", filter->seid,
8507 			 ntohs(filter->dst_port));
8508 	return ret;
8509 }
8510 
8511 /**
8512  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
8513  * @vsi: Pointer to VSI
8514  * @f: Pointer to struct flow_cls_offload
8515  * @filter: Pointer to cloud filter structure
8516  *
8517  **/
8518 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
8519 				 struct flow_cls_offload *f,
8520 				 struct i40e_cloud_filter *filter)
8521 {
8522 	struct flow_rule *rule = flow_cls_offload_flow_rule(f);
8523 	struct flow_dissector *dissector = rule->match.dissector;
8524 	u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
8525 	struct i40e_pf *pf = vsi->back;
8526 	u8 field_flags = 0;
8527 
8528 	if (dissector->used_keys &
8529 	    ~(BIT_ULL(FLOW_DISSECTOR_KEY_CONTROL) |
8530 	      BIT_ULL(FLOW_DISSECTOR_KEY_BASIC) |
8531 	      BIT_ULL(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
8532 	      BIT_ULL(FLOW_DISSECTOR_KEY_VLAN) |
8533 	      BIT_ULL(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
8534 	      BIT_ULL(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
8535 	      BIT_ULL(FLOW_DISSECTOR_KEY_PORTS) |
8536 	      BIT_ULL(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
8537 		dev_err(&pf->pdev->dev, "Unsupported key used: 0x%llx\n",
8538 			dissector->used_keys);
8539 		return -EOPNOTSUPP;
8540 	}
8541 
8542 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
8543 		struct flow_match_enc_keyid match;
8544 
8545 		flow_rule_match_enc_keyid(rule, &match);
8546 		if (match.mask->keyid != 0)
8547 			field_flags |= I40E_CLOUD_FIELD_TEN_ID;
8548 
8549 		filter->tenant_id = be32_to_cpu(match.key->keyid);
8550 	}
8551 
8552 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
8553 		struct flow_match_basic match;
8554 
8555 		flow_rule_match_basic(rule, &match);
8556 		n_proto_key = ntohs(match.key->n_proto);
8557 		n_proto_mask = ntohs(match.mask->n_proto);
8558 
8559 		if (n_proto_key == ETH_P_ALL) {
8560 			n_proto_key = 0;
8561 			n_proto_mask = 0;
8562 		}
8563 		filter->n_proto = n_proto_key & n_proto_mask;
8564 		filter->ip_proto = match.key->ip_proto;
8565 	}
8566 
8567 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
8568 		struct flow_match_eth_addrs match;
8569 
8570 		flow_rule_match_eth_addrs(rule, &match);
8571 
8572 		/* use is_broadcast and is_zero to check for all 0xf or 0 */
8573 		if (!is_zero_ether_addr(match.mask->dst)) {
8574 			if (is_broadcast_ether_addr(match.mask->dst)) {
8575 				field_flags |= I40E_CLOUD_FIELD_OMAC;
8576 			} else {
8577 				dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
8578 					match.mask->dst);
8579 				return -EIO;
8580 			}
8581 		}
8582 
8583 		if (!is_zero_ether_addr(match.mask->src)) {
8584 			if (is_broadcast_ether_addr(match.mask->src)) {
8585 				field_flags |= I40E_CLOUD_FIELD_IMAC;
8586 			} else {
8587 				dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
8588 					match.mask->src);
8589 				return -EIO;
8590 			}
8591 		}
8592 		ether_addr_copy(filter->dst_mac, match.key->dst);
8593 		ether_addr_copy(filter->src_mac, match.key->src);
8594 	}
8595 
8596 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
8597 		struct flow_match_vlan match;
8598 
8599 		flow_rule_match_vlan(rule, &match);
8600 		if (match.mask->vlan_id) {
8601 			if (match.mask->vlan_id == VLAN_VID_MASK) {
8602 				field_flags |= I40E_CLOUD_FIELD_IVLAN;
8603 
8604 			} else {
8605 				dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
8606 					match.mask->vlan_id);
8607 				return -EIO;
8608 			}
8609 		}
8610 
8611 		filter->vlan_id = cpu_to_be16(match.key->vlan_id);
8612 	}
8613 
8614 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
8615 		struct flow_match_control match;
8616 
8617 		flow_rule_match_control(rule, &match);
8618 		addr_type = match.key->addr_type;
8619 	}
8620 
8621 	if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
8622 		struct flow_match_ipv4_addrs match;
8623 
8624 		flow_rule_match_ipv4_addrs(rule, &match);
8625 		if (match.mask->dst) {
8626 			if (match.mask->dst == cpu_to_be32(0xffffffff)) {
8627 				field_flags |= I40E_CLOUD_FIELD_IIP;
8628 			} else {
8629 				dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
8630 					&match.mask->dst);
8631 				return -EIO;
8632 			}
8633 		}
8634 
8635 		if (match.mask->src) {
8636 			if (match.mask->src == cpu_to_be32(0xffffffff)) {
8637 				field_flags |= I40E_CLOUD_FIELD_IIP;
8638 			} else {
8639 				dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
8640 					&match.mask->src);
8641 				return -EIO;
8642 			}
8643 		}
8644 
8645 		if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
8646 			dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
8647 			return -EIO;
8648 		}
8649 		filter->dst_ipv4 = match.key->dst;
8650 		filter->src_ipv4 = match.key->src;
8651 	}
8652 
8653 	if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
8654 		struct flow_match_ipv6_addrs match;
8655 
8656 		flow_rule_match_ipv6_addrs(rule, &match);
8657 
8658 		/* src and dest IPV6 address should not be LOOPBACK
8659 		 * (0:0:0:0:0:0:0:1), which can be represented as ::1
8660 		 */
8661 		if (ipv6_addr_loopback(&match.key->dst) ||
8662 		    ipv6_addr_loopback(&match.key->src)) {
8663 			dev_err(&pf->pdev->dev,
8664 				"Bad ipv6, addr is LOOPBACK\n");
8665 			return -EIO;
8666 		}
8667 		if (!ipv6_addr_any(&match.mask->dst) ||
8668 		    !ipv6_addr_any(&match.mask->src))
8669 			field_flags |= I40E_CLOUD_FIELD_IIP;
8670 
8671 		memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
8672 		       sizeof(filter->src_ipv6));
8673 		memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
8674 		       sizeof(filter->dst_ipv6));
8675 	}
8676 
8677 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
8678 		struct flow_match_ports match;
8679 
8680 		flow_rule_match_ports(rule, &match);
8681 		if (match.mask->src) {
8682 			if (match.mask->src == cpu_to_be16(0xffff)) {
8683 				field_flags |= I40E_CLOUD_FIELD_IIP;
8684 			} else {
8685 				dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
8686 					be16_to_cpu(match.mask->src));
8687 				return -EIO;
8688 			}
8689 		}
8690 
8691 		if (match.mask->dst) {
8692 			if (match.mask->dst == cpu_to_be16(0xffff)) {
8693 				field_flags |= I40E_CLOUD_FIELD_IIP;
8694 			} else {
8695 				dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
8696 					be16_to_cpu(match.mask->dst));
8697 				return -EIO;
8698 			}
8699 		}
8700 
8701 		filter->dst_port = match.key->dst;
8702 		filter->src_port = match.key->src;
8703 
8704 		switch (filter->ip_proto) {
8705 		case IPPROTO_TCP:
8706 		case IPPROTO_UDP:
8707 			break;
8708 		default:
8709 			dev_err(&pf->pdev->dev,
8710 				"Only UDP and TCP transport are supported\n");
8711 			return -EINVAL;
8712 		}
8713 	}
8714 	filter->flags = field_flags;
8715 	return 0;
8716 }
8717 
8718 /**
8719  * i40e_handle_tclass: Forward to a traffic class on the device
8720  * @vsi: Pointer to VSI
8721  * @tc: traffic class index on the device
8722  * @filter: Pointer to cloud filter structure
8723  *
8724  **/
8725 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
8726 			      struct i40e_cloud_filter *filter)
8727 {
8728 	struct i40e_channel *ch, *ch_tmp;
8729 
8730 	/* direct to a traffic class on the same device */
8731 	if (tc == 0) {
8732 		filter->seid = vsi->seid;
8733 		return 0;
8734 	} else if (vsi->tc_config.enabled_tc & BIT(tc)) {
8735 		if (!filter->dst_port) {
8736 			dev_err(&vsi->back->pdev->dev,
8737 				"Specify destination port to direct to traffic class that is not default\n");
8738 			return -EINVAL;
8739 		}
8740 		if (list_empty(&vsi->ch_list))
8741 			return -EINVAL;
8742 		list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
8743 					 list) {
8744 			if (ch->seid == vsi->tc_seid_map[tc])
8745 				filter->seid = ch->seid;
8746 		}
8747 		return 0;
8748 	}
8749 	dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
8750 	return -EINVAL;
8751 }
8752 
8753 /**
8754  * i40e_configure_clsflower - Configure tc flower filters
8755  * @vsi: Pointer to VSI
8756  * @cls_flower: Pointer to struct flow_cls_offload
8757  *
8758  **/
8759 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
8760 				    struct flow_cls_offload *cls_flower)
8761 {
8762 	int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
8763 	struct i40e_cloud_filter *filter = NULL;
8764 	struct i40e_pf *pf = vsi->back;
8765 	int err = 0;
8766 
8767 	if (tc < 0) {
8768 		dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
8769 		return -EOPNOTSUPP;
8770 	}
8771 
8772 	if (!tc) {
8773 		dev_err(&pf->pdev->dev, "Unable to add filter because of invalid destination");
8774 		return -EINVAL;
8775 	}
8776 
8777 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
8778 	    test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
8779 		return -EBUSY;
8780 
8781 	if (pf->fdir_pf_active_filters ||
8782 	    (!hlist_empty(&pf->fdir_filter_list))) {
8783 		dev_err(&vsi->back->pdev->dev,
8784 			"Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
8785 		return -EINVAL;
8786 	}
8787 
8788 	if (vsi->back->flags & I40E_FLAG_FD_SB_ENABLED) {
8789 		dev_err(&vsi->back->pdev->dev,
8790 			"Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
8791 		vsi->back->flags &= ~I40E_FLAG_FD_SB_ENABLED;
8792 		vsi->back->flags |= I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8793 	}
8794 
8795 	filter = kzalloc(sizeof(*filter), GFP_KERNEL);
8796 	if (!filter)
8797 		return -ENOMEM;
8798 
8799 	filter->cookie = cls_flower->cookie;
8800 
8801 	err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8802 	if (err < 0)
8803 		goto err;
8804 
8805 	err = i40e_handle_tclass(vsi, tc, filter);
8806 	if (err < 0)
8807 		goto err;
8808 
8809 	/* Add cloud filter */
8810 	if (filter->dst_port)
8811 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8812 	else
8813 		err = i40e_add_del_cloud_filter(vsi, filter, true);
8814 
8815 	if (err) {
8816 		dev_err(&pf->pdev->dev, "Failed to add cloud filter, err %d\n",
8817 			err);
8818 		goto err;
8819 	}
8820 
8821 	/* add filter to the ordered list */
8822 	INIT_HLIST_NODE(&filter->cloud_node);
8823 
8824 	hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8825 
8826 	pf->num_cloud_filters++;
8827 
8828 	return err;
8829 err:
8830 	kfree(filter);
8831 	return err;
8832 }
8833 
8834 /**
8835  * i40e_find_cloud_filter - Find the could filter in the list
8836  * @vsi: Pointer to VSI
8837  * @cookie: filter specific cookie
8838  *
8839  **/
8840 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8841 							unsigned long *cookie)
8842 {
8843 	struct i40e_cloud_filter *filter = NULL;
8844 	struct hlist_node *node2;
8845 
8846 	hlist_for_each_entry_safe(filter, node2,
8847 				  &vsi->back->cloud_filter_list, cloud_node)
8848 		if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8849 			return filter;
8850 	return NULL;
8851 }
8852 
8853 /**
8854  * i40e_delete_clsflower - Remove tc flower filters
8855  * @vsi: Pointer to VSI
8856  * @cls_flower: Pointer to struct flow_cls_offload
8857  *
8858  **/
8859 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8860 				 struct flow_cls_offload *cls_flower)
8861 {
8862 	struct i40e_cloud_filter *filter = NULL;
8863 	struct i40e_pf *pf = vsi->back;
8864 	int err = 0;
8865 
8866 	filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8867 
8868 	if (!filter)
8869 		return -EINVAL;
8870 
8871 	hash_del(&filter->cloud_node);
8872 
8873 	if (filter->dst_port)
8874 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8875 	else
8876 		err = i40e_add_del_cloud_filter(vsi, filter, false);
8877 
8878 	kfree(filter);
8879 	if (err) {
8880 		dev_err(&pf->pdev->dev,
8881 			"Failed to delete cloud filter, err %pe\n",
8882 			ERR_PTR(err));
8883 		return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8884 	}
8885 
8886 	pf->num_cloud_filters--;
8887 	if (!pf->num_cloud_filters)
8888 		if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
8889 		    !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
8890 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
8891 			pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8892 			pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
8893 		}
8894 	return 0;
8895 }
8896 
8897 /**
8898  * i40e_setup_tc_cls_flower - flower classifier offloads
8899  * @np: net device to configure
8900  * @cls_flower: offload data
8901  **/
8902 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8903 				    struct flow_cls_offload *cls_flower)
8904 {
8905 	struct i40e_vsi *vsi = np->vsi;
8906 
8907 	switch (cls_flower->command) {
8908 	case FLOW_CLS_REPLACE:
8909 		return i40e_configure_clsflower(vsi, cls_flower);
8910 	case FLOW_CLS_DESTROY:
8911 		return i40e_delete_clsflower(vsi, cls_flower);
8912 	case FLOW_CLS_STATS:
8913 		return -EOPNOTSUPP;
8914 	default:
8915 		return -EOPNOTSUPP;
8916 	}
8917 }
8918 
8919 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8920 				  void *cb_priv)
8921 {
8922 	struct i40e_netdev_priv *np = cb_priv;
8923 
8924 	if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8925 		return -EOPNOTSUPP;
8926 
8927 	switch (type) {
8928 	case TC_SETUP_CLSFLOWER:
8929 		return i40e_setup_tc_cls_flower(np, type_data);
8930 
8931 	default:
8932 		return -EOPNOTSUPP;
8933 	}
8934 }
8935 
8936 static LIST_HEAD(i40e_block_cb_list);
8937 
8938 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8939 			   void *type_data)
8940 {
8941 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8942 
8943 	switch (type) {
8944 	case TC_SETUP_QDISC_MQPRIO:
8945 		return i40e_setup_tc(netdev, type_data);
8946 	case TC_SETUP_BLOCK:
8947 		return flow_block_cb_setup_simple(type_data,
8948 						  &i40e_block_cb_list,
8949 						  i40e_setup_tc_block_cb,
8950 						  np, np, true);
8951 	default:
8952 		return -EOPNOTSUPP;
8953 	}
8954 }
8955 
8956 /**
8957  * i40e_open - Called when a network interface is made active
8958  * @netdev: network interface device structure
8959  *
8960  * The open entry point is called when a network interface is made
8961  * active by the system (IFF_UP).  At this point all resources needed
8962  * for transmit and receive operations are allocated, the interrupt
8963  * handler is registered with the OS, the netdev watchdog subtask is
8964  * enabled, and the stack is notified that the interface is ready.
8965  *
8966  * Returns 0 on success, negative value on failure
8967  **/
8968 int i40e_open(struct net_device *netdev)
8969 {
8970 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8971 	struct i40e_vsi *vsi = np->vsi;
8972 	struct i40e_pf *pf = vsi->back;
8973 	int err;
8974 
8975 	/* disallow open during test or if eeprom is broken */
8976 	if (test_bit(__I40E_TESTING, pf->state) ||
8977 	    test_bit(__I40E_BAD_EEPROM, pf->state))
8978 		return -EBUSY;
8979 
8980 	netif_carrier_off(netdev);
8981 
8982 	if (i40e_force_link_state(pf, true))
8983 		return -EAGAIN;
8984 
8985 	err = i40e_vsi_open(vsi);
8986 	if (err)
8987 		return err;
8988 
8989 	/* configure global TSO hardware offload settings */
8990 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
8991 						       TCP_FLAG_FIN) >> 16);
8992 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
8993 						       TCP_FLAG_FIN |
8994 						       TCP_FLAG_CWR) >> 16);
8995 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
8996 	udp_tunnel_get_rx_info(netdev);
8997 
8998 	return 0;
8999 }
9000 
9001 /**
9002  * i40e_netif_set_realnum_tx_rx_queues - Update number of tx/rx queues
9003  * @vsi: vsi structure
9004  *
9005  * This updates netdev's number of tx/rx queues
9006  *
9007  * Returns status of setting tx/rx queues
9008  **/
9009 static int i40e_netif_set_realnum_tx_rx_queues(struct i40e_vsi *vsi)
9010 {
9011 	int ret;
9012 
9013 	ret = netif_set_real_num_rx_queues(vsi->netdev,
9014 					   vsi->num_queue_pairs);
9015 	if (ret)
9016 		return ret;
9017 
9018 	return netif_set_real_num_tx_queues(vsi->netdev,
9019 					    vsi->num_queue_pairs);
9020 }
9021 
9022 /**
9023  * i40e_vsi_open -
9024  * @vsi: the VSI to open
9025  *
9026  * Finish initialization of the VSI.
9027  *
9028  * Returns 0 on success, negative value on failure
9029  *
9030  * Note: expects to be called while under rtnl_lock()
9031  **/
9032 int i40e_vsi_open(struct i40e_vsi *vsi)
9033 {
9034 	struct i40e_pf *pf = vsi->back;
9035 	char int_name[I40E_INT_NAME_STR_LEN];
9036 	int err;
9037 
9038 	/* allocate descriptors */
9039 	err = i40e_vsi_setup_tx_resources(vsi);
9040 	if (err)
9041 		goto err_setup_tx;
9042 	err = i40e_vsi_setup_rx_resources(vsi);
9043 	if (err)
9044 		goto err_setup_rx;
9045 
9046 	err = i40e_vsi_configure(vsi);
9047 	if (err)
9048 		goto err_setup_rx;
9049 
9050 	if (vsi->netdev) {
9051 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
9052 			 dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
9053 		err = i40e_vsi_request_irq(vsi, int_name);
9054 		if (err)
9055 			goto err_setup_rx;
9056 
9057 		/* Notify the stack of the actual queue counts. */
9058 		err = i40e_netif_set_realnum_tx_rx_queues(vsi);
9059 		if (err)
9060 			goto err_set_queues;
9061 
9062 	} else if (vsi->type == I40E_VSI_FDIR) {
9063 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
9064 			 dev_driver_string(&pf->pdev->dev),
9065 			 dev_name(&pf->pdev->dev));
9066 		err = i40e_vsi_request_irq(vsi, int_name);
9067 		if (err)
9068 			goto err_setup_rx;
9069 
9070 	} else {
9071 		err = -EINVAL;
9072 		goto err_setup_rx;
9073 	}
9074 
9075 	err = i40e_up_complete(vsi);
9076 	if (err)
9077 		goto err_up_complete;
9078 
9079 	return 0;
9080 
9081 err_up_complete:
9082 	i40e_down(vsi);
9083 err_set_queues:
9084 	i40e_vsi_free_irq(vsi);
9085 err_setup_rx:
9086 	i40e_vsi_free_rx_resources(vsi);
9087 err_setup_tx:
9088 	i40e_vsi_free_tx_resources(vsi);
9089 	if (vsi == pf->vsi[pf->lan_vsi])
9090 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
9091 
9092 	return err;
9093 }
9094 
9095 /**
9096  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
9097  * @pf: Pointer to PF
9098  *
9099  * This function destroys the hlist where all the Flow Director
9100  * filters were saved.
9101  **/
9102 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
9103 {
9104 	struct i40e_fdir_filter *filter;
9105 	struct i40e_flex_pit *pit_entry, *tmp;
9106 	struct hlist_node *node2;
9107 
9108 	hlist_for_each_entry_safe(filter, node2,
9109 				  &pf->fdir_filter_list, fdir_node) {
9110 		hlist_del(&filter->fdir_node);
9111 		kfree(filter);
9112 	}
9113 
9114 	list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
9115 		list_del(&pit_entry->list);
9116 		kfree(pit_entry);
9117 	}
9118 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
9119 
9120 	list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
9121 		list_del(&pit_entry->list);
9122 		kfree(pit_entry);
9123 	}
9124 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
9125 
9126 	pf->fdir_pf_active_filters = 0;
9127 	i40e_reset_fdir_filter_cnt(pf);
9128 
9129 	/* Reprogram the default input set for TCP/IPv4 */
9130 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9131 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9132 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9133 
9134 	/* Reprogram the default input set for TCP/IPv6 */
9135 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_TCP,
9136 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9137 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9138 
9139 	/* Reprogram the default input set for UDP/IPv4 */
9140 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
9141 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9142 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9143 
9144 	/* Reprogram the default input set for UDP/IPv6 */
9145 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_UDP,
9146 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9147 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9148 
9149 	/* Reprogram the default input set for SCTP/IPv4 */
9150 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
9151 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9152 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9153 
9154 	/* Reprogram the default input set for SCTP/IPv6 */
9155 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_SCTP,
9156 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9157 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9158 
9159 	/* Reprogram the default input set for Other/IPv4 */
9160 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
9161 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9162 
9163 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
9164 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9165 
9166 	/* Reprogram the default input set for Other/IPv6 */
9167 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_OTHER,
9168 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9169 
9170 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV6,
9171 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9172 }
9173 
9174 /**
9175  * i40e_cloud_filter_exit - Cleans up the cloud filters
9176  * @pf: Pointer to PF
9177  *
9178  * This function destroys the hlist where all the cloud filters
9179  * were saved.
9180  **/
9181 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
9182 {
9183 	struct i40e_cloud_filter *cfilter;
9184 	struct hlist_node *node;
9185 
9186 	hlist_for_each_entry_safe(cfilter, node,
9187 				  &pf->cloud_filter_list, cloud_node) {
9188 		hlist_del(&cfilter->cloud_node);
9189 		kfree(cfilter);
9190 	}
9191 	pf->num_cloud_filters = 0;
9192 
9193 	if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
9194 	    !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
9195 		pf->flags |= I40E_FLAG_FD_SB_ENABLED;
9196 		pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
9197 		pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
9198 	}
9199 }
9200 
9201 /**
9202  * i40e_close - Disables a network interface
9203  * @netdev: network interface device structure
9204  *
9205  * The close entry point is called when an interface is de-activated
9206  * by the OS.  The hardware is still under the driver's control, but
9207  * this netdev interface is disabled.
9208  *
9209  * Returns 0, this is not allowed to fail
9210  **/
9211 int i40e_close(struct net_device *netdev)
9212 {
9213 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9214 	struct i40e_vsi *vsi = np->vsi;
9215 
9216 	i40e_vsi_close(vsi);
9217 
9218 	return 0;
9219 }
9220 
9221 /**
9222  * i40e_do_reset - Start a PF or Core Reset sequence
9223  * @pf: board private structure
9224  * @reset_flags: which reset is requested
9225  * @lock_acquired: indicates whether or not the lock has been acquired
9226  * before this function was called.
9227  *
9228  * The essential difference in resets is that the PF Reset
9229  * doesn't clear the packet buffers, doesn't reset the PE
9230  * firmware, and doesn't bother the other PFs on the chip.
9231  **/
9232 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
9233 {
9234 	u32 val;
9235 
9236 	/* do the biggest reset indicated */
9237 	if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
9238 
9239 		/* Request a Global Reset
9240 		 *
9241 		 * This will start the chip's countdown to the actual full
9242 		 * chip reset event, and a warning interrupt to be sent
9243 		 * to all PFs, including the requestor.  Our handler
9244 		 * for the warning interrupt will deal with the shutdown
9245 		 * and recovery of the switch setup.
9246 		 */
9247 		dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
9248 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9249 		val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
9250 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9251 
9252 	} else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
9253 
9254 		/* Request a Core Reset
9255 		 *
9256 		 * Same as Global Reset, except does *not* include the MAC/PHY
9257 		 */
9258 		dev_dbg(&pf->pdev->dev, "CoreR requested\n");
9259 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9260 		val |= I40E_GLGEN_RTRIG_CORER_MASK;
9261 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9262 		i40e_flush(&pf->hw);
9263 
9264 	} else if (reset_flags & I40E_PF_RESET_FLAG) {
9265 
9266 		/* Request a PF Reset
9267 		 *
9268 		 * Resets only the PF-specific registers
9269 		 *
9270 		 * This goes directly to the tear-down and rebuild of
9271 		 * the switch, since we need to do all the recovery as
9272 		 * for the Core Reset.
9273 		 */
9274 		dev_dbg(&pf->pdev->dev, "PFR requested\n");
9275 		i40e_handle_reset_warning(pf, lock_acquired);
9276 
9277 	} else if (reset_flags & I40E_PF_RESET_AND_REBUILD_FLAG) {
9278 		/* Request a PF Reset
9279 		 *
9280 		 * Resets PF and reinitializes PFs VSI.
9281 		 */
9282 		i40e_prep_for_reset(pf);
9283 		i40e_reset_and_rebuild(pf, true, lock_acquired);
9284 		dev_info(&pf->pdev->dev,
9285 			 pf->flags & I40E_FLAG_DISABLE_FW_LLDP ?
9286 			 "FW LLDP is disabled\n" :
9287 			 "FW LLDP is enabled\n");
9288 
9289 	} else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
9290 		int v;
9291 
9292 		/* Find the VSI(s) that requested a re-init */
9293 		dev_info(&pf->pdev->dev,
9294 			 "VSI reinit requested\n");
9295 		for (v = 0; v < pf->num_alloc_vsi; v++) {
9296 			struct i40e_vsi *vsi = pf->vsi[v];
9297 
9298 			if (vsi != NULL &&
9299 			    test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
9300 					       vsi->state))
9301 				i40e_vsi_reinit_locked(pf->vsi[v]);
9302 		}
9303 	} else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
9304 		int v;
9305 
9306 		/* Find the VSI(s) that needs to be brought down */
9307 		dev_info(&pf->pdev->dev, "VSI down requested\n");
9308 		for (v = 0; v < pf->num_alloc_vsi; v++) {
9309 			struct i40e_vsi *vsi = pf->vsi[v];
9310 
9311 			if (vsi != NULL &&
9312 			    test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
9313 					       vsi->state)) {
9314 				set_bit(__I40E_VSI_DOWN, vsi->state);
9315 				i40e_down(vsi);
9316 			}
9317 		}
9318 	} else {
9319 		dev_info(&pf->pdev->dev,
9320 			 "bad reset request 0x%08x\n", reset_flags);
9321 	}
9322 }
9323 
9324 #ifdef CONFIG_I40E_DCB
9325 /**
9326  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
9327  * @pf: board private structure
9328  * @old_cfg: current DCB config
9329  * @new_cfg: new DCB config
9330  **/
9331 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
9332 			    struct i40e_dcbx_config *old_cfg,
9333 			    struct i40e_dcbx_config *new_cfg)
9334 {
9335 	bool need_reconfig = false;
9336 
9337 	/* Check if ETS configuration has changed */
9338 	if (memcmp(&new_cfg->etscfg,
9339 		   &old_cfg->etscfg,
9340 		   sizeof(new_cfg->etscfg))) {
9341 		/* If Priority Table has changed reconfig is needed */
9342 		if (memcmp(&new_cfg->etscfg.prioritytable,
9343 			   &old_cfg->etscfg.prioritytable,
9344 			   sizeof(new_cfg->etscfg.prioritytable))) {
9345 			need_reconfig = true;
9346 			dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
9347 		}
9348 
9349 		if (memcmp(&new_cfg->etscfg.tcbwtable,
9350 			   &old_cfg->etscfg.tcbwtable,
9351 			   sizeof(new_cfg->etscfg.tcbwtable)))
9352 			dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
9353 
9354 		if (memcmp(&new_cfg->etscfg.tsatable,
9355 			   &old_cfg->etscfg.tsatable,
9356 			   sizeof(new_cfg->etscfg.tsatable)))
9357 			dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
9358 	}
9359 
9360 	/* Check if PFC configuration has changed */
9361 	if (memcmp(&new_cfg->pfc,
9362 		   &old_cfg->pfc,
9363 		   sizeof(new_cfg->pfc))) {
9364 		need_reconfig = true;
9365 		dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
9366 	}
9367 
9368 	/* Check if APP Table has changed */
9369 	if (memcmp(&new_cfg->app,
9370 		   &old_cfg->app,
9371 		   sizeof(new_cfg->app))) {
9372 		need_reconfig = true;
9373 		dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
9374 	}
9375 
9376 	dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
9377 	return need_reconfig;
9378 }
9379 
9380 /**
9381  * i40e_handle_lldp_event - Handle LLDP Change MIB event
9382  * @pf: board private structure
9383  * @e: event info posted on ARQ
9384  **/
9385 static int i40e_handle_lldp_event(struct i40e_pf *pf,
9386 				  struct i40e_arq_event_info *e)
9387 {
9388 	struct i40e_aqc_lldp_get_mib *mib =
9389 		(struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
9390 	struct i40e_hw *hw = &pf->hw;
9391 	struct i40e_dcbx_config tmp_dcbx_cfg;
9392 	bool need_reconfig = false;
9393 	int ret = 0;
9394 	u8 type;
9395 
9396 	/* X710-T*L 2.5G and 5G speeds don't support DCB */
9397 	if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9398 	    (hw->phy.link_info.link_speed &
9399 	     ~(I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB)) &&
9400 	     !(pf->flags & I40E_FLAG_DCB_CAPABLE))
9401 		/* let firmware decide if the DCB should be disabled */
9402 		pf->flags |= I40E_FLAG_DCB_CAPABLE;
9403 
9404 	/* Not DCB capable or capability disabled */
9405 	if (!(pf->flags & I40E_FLAG_DCB_CAPABLE))
9406 		return ret;
9407 
9408 	/* Ignore if event is not for Nearest Bridge */
9409 	type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
9410 		& I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
9411 	dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
9412 	if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
9413 		return ret;
9414 
9415 	/* Check MIB Type and return if event for Remote MIB update */
9416 	type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
9417 	dev_dbg(&pf->pdev->dev,
9418 		"LLDP event mib type %s\n", type ? "remote" : "local");
9419 	if (type == I40E_AQ_LLDP_MIB_REMOTE) {
9420 		/* Update the remote cached instance and return */
9421 		ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
9422 				I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
9423 				&hw->remote_dcbx_config);
9424 		goto exit;
9425 	}
9426 
9427 	/* Store the old configuration */
9428 	tmp_dcbx_cfg = hw->local_dcbx_config;
9429 
9430 	/* Reset the old DCBx configuration data */
9431 	memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
9432 	/* Get updated DCBX data from firmware */
9433 	ret = i40e_get_dcb_config(&pf->hw);
9434 	if (ret) {
9435 		/* X710-T*L 2.5G and 5G speeds don't support DCB */
9436 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9437 		    (hw->phy.link_info.link_speed &
9438 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
9439 			dev_warn(&pf->pdev->dev,
9440 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
9441 			pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
9442 		} else {
9443 			dev_info(&pf->pdev->dev,
9444 				 "Failed querying DCB configuration data from firmware, err %pe aq_err %s\n",
9445 				 ERR_PTR(ret),
9446 				 i40e_aq_str(&pf->hw,
9447 					     pf->hw.aq.asq_last_status));
9448 		}
9449 		goto exit;
9450 	}
9451 
9452 	/* No change detected in DCBX configs */
9453 	if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
9454 		    sizeof(tmp_dcbx_cfg))) {
9455 		dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
9456 		goto exit;
9457 	}
9458 
9459 	need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
9460 					       &hw->local_dcbx_config);
9461 
9462 	i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
9463 
9464 	if (!need_reconfig)
9465 		goto exit;
9466 
9467 	/* Enable DCB tagging only when more than one TC */
9468 	if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
9469 		pf->flags |= I40E_FLAG_DCB_ENABLED;
9470 	else
9471 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9472 
9473 	set_bit(__I40E_PORT_SUSPENDED, pf->state);
9474 	/* Reconfiguration needed quiesce all VSIs */
9475 	i40e_pf_quiesce_all_vsi(pf);
9476 
9477 	/* Changes in configuration update VEB/VSI */
9478 	i40e_dcb_reconfigure(pf);
9479 
9480 	ret = i40e_resume_port_tx(pf);
9481 
9482 	clear_bit(__I40E_PORT_SUSPENDED, pf->state);
9483 	/* In case of error no point in resuming VSIs */
9484 	if (ret)
9485 		goto exit;
9486 
9487 	/* Wait for the PF's queues to be disabled */
9488 	ret = i40e_pf_wait_queues_disabled(pf);
9489 	if (ret) {
9490 		/* Schedule PF reset to recover */
9491 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9492 		i40e_service_event_schedule(pf);
9493 	} else {
9494 		i40e_pf_unquiesce_all_vsi(pf);
9495 		set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
9496 		set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
9497 	}
9498 
9499 exit:
9500 	return ret;
9501 }
9502 #endif /* CONFIG_I40E_DCB */
9503 
9504 /**
9505  * i40e_do_reset_safe - Protected reset path for userland calls.
9506  * @pf: board private structure
9507  * @reset_flags: which reset is requested
9508  *
9509  **/
9510 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
9511 {
9512 	rtnl_lock();
9513 	i40e_do_reset(pf, reset_flags, true);
9514 	rtnl_unlock();
9515 }
9516 
9517 /**
9518  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
9519  * @pf: board private structure
9520  * @e: event info posted on ARQ
9521  *
9522  * Handler for LAN Queue Overflow Event generated by the firmware for PF
9523  * and VF queues
9524  **/
9525 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
9526 					   struct i40e_arq_event_info *e)
9527 {
9528 	struct i40e_aqc_lan_overflow *data =
9529 		(struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
9530 	u32 queue = le32_to_cpu(data->prtdcb_rupto);
9531 	u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
9532 	struct i40e_hw *hw = &pf->hw;
9533 	struct i40e_vf *vf;
9534 	u16 vf_id;
9535 
9536 	dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
9537 		queue, qtx_ctl);
9538 
9539 	/* Queue belongs to VF, find the VF and issue VF reset */
9540 	if (((qtx_ctl & I40E_QTX_CTL_PFVF_Q_MASK)
9541 	    >> I40E_QTX_CTL_PFVF_Q_SHIFT) == I40E_QTX_CTL_VF_QUEUE) {
9542 		vf_id = (u16)((qtx_ctl & I40E_QTX_CTL_VFVM_INDX_MASK)
9543 			 >> I40E_QTX_CTL_VFVM_INDX_SHIFT);
9544 		vf_id -= hw->func_caps.vf_base_id;
9545 		vf = &pf->vf[vf_id];
9546 		i40e_vc_notify_vf_reset(vf);
9547 		/* Allow VF to process pending reset notification */
9548 		msleep(20);
9549 		i40e_reset_vf(vf, false);
9550 	}
9551 }
9552 
9553 /**
9554  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
9555  * @pf: board private structure
9556  **/
9557 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
9558 {
9559 	u32 val, fcnt_prog;
9560 
9561 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9562 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
9563 	return fcnt_prog;
9564 }
9565 
9566 /**
9567  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
9568  * @pf: board private structure
9569  **/
9570 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
9571 {
9572 	u32 val, fcnt_prog;
9573 
9574 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9575 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
9576 		    ((val & I40E_PFQF_FDSTAT_BEST_CNT_MASK) >>
9577 		      I40E_PFQF_FDSTAT_BEST_CNT_SHIFT);
9578 	return fcnt_prog;
9579 }
9580 
9581 /**
9582  * i40e_get_global_fd_count - Get total FD filters programmed on device
9583  * @pf: board private structure
9584  **/
9585 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
9586 {
9587 	u32 val, fcnt_prog;
9588 
9589 	val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
9590 	fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
9591 		    ((val & I40E_GLQF_FDCNT_0_BESTCNT_MASK) >>
9592 		     I40E_GLQF_FDCNT_0_BESTCNT_SHIFT);
9593 	return fcnt_prog;
9594 }
9595 
9596 /**
9597  * i40e_reenable_fdir_sb - Restore FDir SB capability
9598  * @pf: board private structure
9599  **/
9600 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
9601 {
9602 	if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
9603 		if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
9604 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9605 			dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
9606 }
9607 
9608 /**
9609  * i40e_reenable_fdir_atr - Restore FDir ATR capability
9610  * @pf: board private structure
9611  **/
9612 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
9613 {
9614 	if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
9615 		/* ATR uses the same filtering logic as SB rules. It only
9616 		 * functions properly if the input set mask is at the default
9617 		 * settings. It is safe to restore the default input set
9618 		 * because there are no active TCPv4 filter rules.
9619 		 */
9620 		i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9621 					I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9622 					I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9623 
9624 		if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
9625 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9626 			dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
9627 	}
9628 }
9629 
9630 /**
9631  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
9632  * @pf: board private structure
9633  * @filter: FDir filter to remove
9634  */
9635 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
9636 				       struct i40e_fdir_filter *filter)
9637 {
9638 	/* Update counters */
9639 	pf->fdir_pf_active_filters--;
9640 	pf->fd_inv = 0;
9641 
9642 	switch (filter->flow_type) {
9643 	case TCP_V4_FLOW:
9644 		pf->fd_tcp4_filter_cnt--;
9645 		break;
9646 	case UDP_V4_FLOW:
9647 		pf->fd_udp4_filter_cnt--;
9648 		break;
9649 	case SCTP_V4_FLOW:
9650 		pf->fd_sctp4_filter_cnt--;
9651 		break;
9652 	case TCP_V6_FLOW:
9653 		pf->fd_tcp6_filter_cnt--;
9654 		break;
9655 	case UDP_V6_FLOW:
9656 		pf->fd_udp6_filter_cnt--;
9657 		break;
9658 	case SCTP_V6_FLOW:
9659 		pf->fd_udp6_filter_cnt--;
9660 		break;
9661 	case IP_USER_FLOW:
9662 		switch (filter->ipl4_proto) {
9663 		case IPPROTO_TCP:
9664 			pf->fd_tcp4_filter_cnt--;
9665 			break;
9666 		case IPPROTO_UDP:
9667 			pf->fd_udp4_filter_cnt--;
9668 			break;
9669 		case IPPROTO_SCTP:
9670 			pf->fd_sctp4_filter_cnt--;
9671 			break;
9672 		case IPPROTO_IP:
9673 			pf->fd_ip4_filter_cnt--;
9674 			break;
9675 		}
9676 		break;
9677 	case IPV6_USER_FLOW:
9678 		switch (filter->ipl4_proto) {
9679 		case IPPROTO_TCP:
9680 			pf->fd_tcp6_filter_cnt--;
9681 			break;
9682 		case IPPROTO_UDP:
9683 			pf->fd_udp6_filter_cnt--;
9684 			break;
9685 		case IPPROTO_SCTP:
9686 			pf->fd_sctp6_filter_cnt--;
9687 			break;
9688 		case IPPROTO_IP:
9689 			pf->fd_ip6_filter_cnt--;
9690 			break;
9691 		}
9692 		break;
9693 	}
9694 
9695 	/* Remove the filter from the list and free memory */
9696 	hlist_del(&filter->fdir_node);
9697 	kfree(filter);
9698 }
9699 
9700 /**
9701  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
9702  * @pf: board private structure
9703  **/
9704 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
9705 {
9706 	struct i40e_fdir_filter *filter;
9707 	u32 fcnt_prog, fcnt_avail;
9708 	struct hlist_node *node;
9709 
9710 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9711 		return;
9712 
9713 	/* Check if we have enough room to re-enable FDir SB capability. */
9714 	fcnt_prog = i40e_get_global_fd_count(pf);
9715 	fcnt_avail = pf->fdir_pf_filter_count;
9716 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
9717 	    (pf->fd_add_err == 0) ||
9718 	    (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
9719 		i40e_reenable_fdir_sb(pf);
9720 
9721 	/* We should wait for even more space before re-enabling ATR.
9722 	 * Additionally, we cannot enable ATR as long as we still have TCP SB
9723 	 * rules active.
9724 	 */
9725 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
9726 	    pf->fd_tcp4_filter_cnt == 0 && pf->fd_tcp6_filter_cnt == 0)
9727 		i40e_reenable_fdir_atr(pf);
9728 
9729 	/* if hw had a problem adding a filter, delete it */
9730 	if (pf->fd_inv > 0) {
9731 		hlist_for_each_entry_safe(filter, node,
9732 					  &pf->fdir_filter_list, fdir_node)
9733 			if (filter->fd_id == pf->fd_inv)
9734 				i40e_delete_invalid_filter(pf, filter);
9735 	}
9736 }
9737 
9738 #define I40E_MIN_FD_FLUSH_INTERVAL 10
9739 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
9740 /**
9741  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
9742  * @pf: board private structure
9743  **/
9744 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
9745 {
9746 	unsigned long min_flush_time;
9747 	int flush_wait_retry = 50;
9748 	bool disable_atr = false;
9749 	int fd_room;
9750 	int reg;
9751 
9752 	if (!time_after(jiffies, pf->fd_flush_timestamp +
9753 				 (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
9754 		return;
9755 
9756 	/* If the flush is happening too quick and we have mostly SB rules we
9757 	 * should not re-enable ATR for some time.
9758 	 */
9759 	min_flush_time = pf->fd_flush_timestamp +
9760 			 (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
9761 	fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
9762 
9763 	if (!(time_after(jiffies, min_flush_time)) &&
9764 	    (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
9765 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9766 			dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
9767 		disable_atr = true;
9768 	}
9769 
9770 	pf->fd_flush_timestamp = jiffies;
9771 	set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9772 	/* flush all filters */
9773 	wr32(&pf->hw, I40E_PFQF_CTL_1,
9774 	     I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
9775 	i40e_flush(&pf->hw);
9776 	pf->fd_flush_cnt++;
9777 	pf->fd_add_err = 0;
9778 	do {
9779 		/* Check FD flush status every 5-6msec */
9780 		usleep_range(5000, 6000);
9781 		reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
9782 		if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
9783 			break;
9784 	} while (flush_wait_retry--);
9785 	if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
9786 		dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
9787 	} else {
9788 		/* replay sideband filters */
9789 		i40e_fdir_filter_restore(pf->vsi[pf->lan_vsi]);
9790 		if (!disable_atr && !pf->fd_tcp4_filter_cnt)
9791 			clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9792 		clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
9793 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9794 			dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
9795 	}
9796 }
9797 
9798 /**
9799  * i40e_get_current_atr_cnt - Get the count of total FD ATR filters programmed
9800  * @pf: board private structure
9801  **/
9802 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
9803 {
9804 	return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
9805 }
9806 
9807 /**
9808  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
9809  * @pf: board private structure
9810  **/
9811 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
9812 {
9813 
9814 	/* if interface is down do nothing */
9815 	if (test_bit(__I40E_DOWN, pf->state))
9816 		return;
9817 
9818 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9819 		i40e_fdir_flush_and_replay(pf);
9820 
9821 	i40e_fdir_check_and_reenable(pf);
9822 
9823 }
9824 
9825 /**
9826  * i40e_vsi_link_event - notify VSI of a link event
9827  * @vsi: vsi to be notified
9828  * @link_up: link up or down
9829  **/
9830 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
9831 {
9832 	if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
9833 		return;
9834 
9835 	switch (vsi->type) {
9836 	case I40E_VSI_MAIN:
9837 		if (!vsi->netdev || !vsi->netdev_registered)
9838 			break;
9839 
9840 		if (link_up) {
9841 			netif_carrier_on(vsi->netdev);
9842 			netif_tx_wake_all_queues(vsi->netdev);
9843 		} else {
9844 			netif_carrier_off(vsi->netdev);
9845 			netif_tx_stop_all_queues(vsi->netdev);
9846 		}
9847 		break;
9848 
9849 	case I40E_VSI_SRIOV:
9850 	case I40E_VSI_VMDQ2:
9851 	case I40E_VSI_CTRL:
9852 	case I40E_VSI_IWARP:
9853 	case I40E_VSI_MIRROR:
9854 	default:
9855 		/* there is no notification for other VSIs */
9856 		break;
9857 	}
9858 }
9859 
9860 /**
9861  * i40e_veb_link_event - notify elements on the veb of a link event
9862  * @veb: veb to be notified
9863  * @link_up: link up or down
9864  **/
9865 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
9866 {
9867 	struct i40e_pf *pf;
9868 	int i;
9869 
9870 	if (!veb || !veb->pf)
9871 		return;
9872 	pf = veb->pf;
9873 
9874 	/* depth first... */
9875 	for (i = 0; i < I40E_MAX_VEB; i++)
9876 		if (pf->veb[i] && (pf->veb[i]->uplink_seid == veb->seid))
9877 			i40e_veb_link_event(pf->veb[i], link_up);
9878 
9879 	/* ... now the local VSIs */
9880 	for (i = 0; i < pf->num_alloc_vsi; i++)
9881 		if (pf->vsi[i] && (pf->vsi[i]->uplink_seid == veb->seid))
9882 			i40e_vsi_link_event(pf->vsi[i], link_up);
9883 }
9884 
9885 /**
9886  * i40e_link_event - Update netif_carrier status
9887  * @pf: board private structure
9888  **/
9889 static void i40e_link_event(struct i40e_pf *pf)
9890 {
9891 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9892 	u8 new_link_speed, old_link_speed;
9893 	bool new_link, old_link;
9894 	int status;
9895 #ifdef CONFIG_I40E_DCB
9896 	int err;
9897 #endif /* CONFIG_I40E_DCB */
9898 
9899 	/* set this to force the get_link_status call to refresh state */
9900 	pf->hw.phy.get_link_info = true;
9901 	old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9902 	status = i40e_get_link_status(&pf->hw, &new_link);
9903 
9904 	/* On success, disable temp link polling */
9905 	if (status == 0) {
9906 		clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9907 	} else {
9908 		/* Enable link polling temporarily until i40e_get_link_status
9909 		 * returns 0
9910 		 */
9911 		set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9912 		dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9913 			status);
9914 		return;
9915 	}
9916 
9917 	old_link_speed = pf->hw.phy.link_info_old.link_speed;
9918 	new_link_speed = pf->hw.phy.link_info.link_speed;
9919 
9920 	if (new_link == old_link &&
9921 	    new_link_speed == old_link_speed &&
9922 	    (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9923 	     new_link == netif_carrier_ok(vsi->netdev)))
9924 		return;
9925 
9926 	i40e_print_link_message(vsi, new_link);
9927 
9928 	/* Notify the base of the switch tree connected to
9929 	 * the link.  Floating VEBs are not notified.
9930 	 */
9931 	if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
9932 		i40e_veb_link_event(pf->veb[pf->lan_veb], new_link);
9933 	else
9934 		i40e_vsi_link_event(vsi, new_link);
9935 
9936 	if (pf->vf)
9937 		i40e_vc_notify_link_state(pf);
9938 
9939 	if (pf->flags & I40E_FLAG_PTP)
9940 		i40e_ptp_set_increment(pf);
9941 #ifdef CONFIG_I40E_DCB
9942 	if (new_link == old_link)
9943 		return;
9944 	/* Not SW DCB so firmware will take care of default settings */
9945 	if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED)
9946 		return;
9947 
9948 	/* We cover here only link down, as after link up in case of SW DCB
9949 	 * SW LLDP agent will take care of setting it up
9950 	 */
9951 	if (!new_link) {
9952 		dev_dbg(&pf->pdev->dev, "Reconfig DCB to single TC as result of Link Down\n");
9953 		memset(&pf->tmp_cfg, 0, sizeof(pf->tmp_cfg));
9954 		err = i40e_dcb_sw_default_config(pf);
9955 		if (err) {
9956 			pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
9957 				       I40E_FLAG_DCB_ENABLED);
9958 		} else {
9959 			pf->dcbx_cap = DCB_CAP_DCBX_HOST |
9960 				       DCB_CAP_DCBX_VER_IEEE;
9961 			pf->flags |= I40E_FLAG_DCB_CAPABLE;
9962 			pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9963 		}
9964 	}
9965 #endif /* CONFIG_I40E_DCB */
9966 }
9967 
9968 /**
9969  * i40e_watchdog_subtask - periodic checks not using event driven response
9970  * @pf: board private structure
9971  **/
9972 static void i40e_watchdog_subtask(struct i40e_pf *pf)
9973 {
9974 	int i;
9975 
9976 	/* if interface is down do nothing */
9977 	if (test_bit(__I40E_DOWN, pf->state) ||
9978 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
9979 		return;
9980 
9981 	/* make sure we don't do these things too often */
9982 	if (time_before(jiffies, (pf->service_timer_previous +
9983 				  pf->service_timer_period)))
9984 		return;
9985 	pf->service_timer_previous = jiffies;
9986 
9987 	if ((pf->flags & I40E_FLAG_LINK_POLLING_ENABLED) ||
9988 	    test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
9989 		i40e_link_event(pf);
9990 
9991 	/* Update the stats for active netdevs so the network stack
9992 	 * can look at updated numbers whenever it cares to
9993 	 */
9994 	for (i = 0; i < pf->num_alloc_vsi; i++)
9995 		if (pf->vsi[i] && pf->vsi[i]->netdev)
9996 			i40e_update_stats(pf->vsi[i]);
9997 
9998 	if (pf->flags & I40E_FLAG_VEB_STATS_ENABLED) {
9999 		/* Update the stats for the active switching components */
10000 		for (i = 0; i < I40E_MAX_VEB; i++)
10001 			if (pf->veb[i])
10002 				i40e_update_veb_stats(pf->veb[i]);
10003 	}
10004 
10005 	i40e_ptp_rx_hang(pf);
10006 	i40e_ptp_tx_hang(pf);
10007 }
10008 
10009 /**
10010  * i40e_reset_subtask - Set up for resetting the device and driver
10011  * @pf: board private structure
10012  **/
10013 static void i40e_reset_subtask(struct i40e_pf *pf)
10014 {
10015 	u32 reset_flags = 0;
10016 
10017 	if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
10018 		reset_flags |= BIT(__I40E_REINIT_REQUESTED);
10019 		clear_bit(__I40E_REINIT_REQUESTED, pf->state);
10020 	}
10021 	if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
10022 		reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
10023 		clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
10024 	}
10025 	if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
10026 		reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
10027 		clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
10028 	}
10029 	if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
10030 		reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
10031 		clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
10032 	}
10033 	if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
10034 		reset_flags |= BIT(__I40E_DOWN_REQUESTED);
10035 		clear_bit(__I40E_DOWN_REQUESTED, pf->state);
10036 	}
10037 
10038 	/* If there's a recovery already waiting, it takes
10039 	 * precedence before starting a new reset sequence.
10040 	 */
10041 	if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
10042 		i40e_prep_for_reset(pf);
10043 		i40e_reset(pf);
10044 		i40e_rebuild(pf, false, false);
10045 	}
10046 
10047 	/* If we're already down or resetting, just bail */
10048 	if (reset_flags &&
10049 	    !test_bit(__I40E_DOWN, pf->state) &&
10050 	    !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
10051 		i40e_do_reset(pf, reset_flags, false);
10052 	}
10053 }
10054 
10055 /**
10056  * i40e_handle_link_event - Handle link event
10057  * @pf: board private structure
10058  * @e: event info posted on ARQ
10059  **/
10060 static void i40e_handle_link_event(struct i40e_pf *pf,
10061 				   struct i40e_arq_event_info *e)
10062 {
10063 	struct i40e_aqc_get_link_status *status =
10064 		(struct i40e_aqc_get_link_status *)&e->desc.params.raw;
10065 
10066 	/* Do a new status request to re-enable LSE reporting
10067 	 * and load new status information into the hw struct
10068 	 * This completely ignores any state information
10069 	 * in the ARQ event info, instead choosing to always
10070 	 * issue the AQ update link status command.
10071 	 */
10072 	i40e_link_event(pf);
10073 
10074 	/* Check if module meets thermal requirements */
10075 	if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
10076 		dev_err(&pf->pdev->dev,
10077 			"Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
10078 		dev_err(&pf->pdev->dev,
10079 			"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10080 	} else {
10081 		/* check for unqualified module, if link is down, suppress
10082 		 * the message if link was forced to be down.
10083 		 */
10084 		if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
10085 		    (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
10086 		    (!(status->link_info & I40E_AQ_LINK_UP)) &&
10087 		    (!(pf->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED))) {
10088 			dev_err(&pf->pdev->dev,
10089 				"Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
10090 			dev_err(&pf->pdev->dev,
10091 				"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10092 		}
10093 	}
10094 }
10095 
10096 /**
10097  * i40e_clean_adminq_subtask - Clean the AdminQ rings
10098  * @pf: board private structure
10099  **/
10100 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
10101 {
10102 	struct i40e_arq_event_info event;
10103 	struct i40e_hw *hw = &pf->hw;
10104 	u16 pending, i = 0;
10105 	u16 opcode;
10106 	u32 oldval;
10107 	int ret;
10108 	u32 val;
10109 
10110 	/* Do not run clean AQ when PF reset fails */
10111 	if (test_bit(__I40E_RESET_FAILED, pf->state))
10112 		return;
10113 
10114 	/* check for error indications */
10115 	val = rd32(&pf->hw, pf->hw.aq.arq.len);
10116 	oldval = val;
10117 	if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
10118 		if (hw->debug_mask & I40E_DEBUG_AQ)
10119 			dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
10120 		val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
10121 	}
10122 	if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
10123 		if (hw->debug_mask & I40E_DEBUG_AQ)
10124 			dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
10125 		val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
10126 		pf->arq_overflows++;
10127 	}
10128 	if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
10129 		if (hw->debug_mask & I40E_DEBUG_AQ)
10130 			dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
10131 		val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
10132 	}
10133 	if (oldval != val)
10134 		wr32(&pf->hw, pf->hw.aq.arq.len, val);
10135 
10136 	val = rd32(&pf->hw, pf->hw.aq.asq.len);
10137 	oldval = val;
10138 	if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
10139 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10140 			dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
10141 		val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
10142 	}
10143 	if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
10144 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10145 			dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
10146 		val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
10147 	}
10148 	if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
10149 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10150 			dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
10151 		val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
10152 	}
10153 	if (oldval != val)
10154 		wr32(&pf->hw, pf->hw.aq.asq.len, val);
10155 
10156 	event.buf_len = I40E_MAX_AQ_BUF_SIZE;
10157 	event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
10158 	if (!event.msg_buf)
10159 		return;
10160 
10161 	do {
10162 		ret = i40e_clean_arq_element(hw, &event, &pending);
10163 		if (ret == -EALREADY)
10164 			break;
10165 		else if (ret) {
10166 			dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
10167 			break;
10168 		}
10169 
10170 		opcode = le16_to_cpu(event.desc.opcode);
10171 		switch (opcode) {
10172 
10173 		case i40e_aqc_opc_get_link_status:
10174 			rtnl_lock();
10175 			i40e_handle_link_event(pf, &event);
10176 			rtnl_unlock();
10177 			break;
10178 		case i40e_aqc_opc_send_msg_to_pf:
10179 			ret = i40e_vc_process_vf_msg(pf,
10180 					le16_to_cpu(event.desc.retval),
10181 					le32_to_cpu(event.desc.cookie_high),
10182 					le32_to_cpu(event.desc.cookie_low),
10183 					event.msg_buf,
10184 					event.msg_len);
10185 			break;
10186 		case i40e_aqc_opc_lldp_update_mib:
10187 			dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
10188 #ifdef CONFIG_I40E_DCB
10189 			rtnl_lock();
10190 			i40e_handle_lldp_event(pf, &event);
10191 			rtnl_unlock();
10192 #endif /* CONFIG_I40E_DCB */
10193 			break;
10194 		case i40e_aqc_opc_event_lan_overflow:
10195 			dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
10196 			i40e_handle_lan_overflow_event(pf, &event);
10197 			break;
10198 		case i40e_aqc_opc_send_msg_to_peer:
10199 			dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
10200 			break;
10201 		case i40e_aqc_opc_nvm_erase:
10202 		case i40e_aqc_opc_nvm_update:
10203 		case i40e_aqc_opc_oem_post_update:
10204 			i40e_debug(&pf->hw, I40E_DEBUG_NVM,
10205 				   "ARQ NVM operation 0x%04x completed\n",
10206 				   opcode);
10207 			break;
10208 		default:
10209 			dev_info(&pf->pdev->dev,
10210 				 "ARQ: Unknown event 0x%04x ignored\n",
10211 				 opcode);
10212 			break;
10213 		}
10214 	} while (i++ < pf->adminq_work_limit);
10215 
10216 	if (i < pf->adminq_work_limit)
10217 		clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
10218 
10219 	/* re-enable Admin queue interrupt cause */
10220 	val = rd32(hw, I40E_PFINT_ICR0_ENA);
10221 	val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
10222 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
10223 	i40e_flush(hw);
10224 
10225 	kfree(event.msg_buf);
10226 }
10227 
10228 /**
10229  * i40e_verify_eeprom - make sure eeprom is good to use
10230  * @pf: board private structure
10231  **/
10232 static void i40e_verify_eeprom(struct i40e_pf *pf)
10233 {
10234 	int err;
10235 
10236 	err = i40e_diag_eeprom_test(&pf->hw);
10237 	if (err) {
10238 		/* retry in case of garbage read */
10239 		err = i40e_diag_eeprom_test(&pf->hw);
10240 		if (err) {
10241 			dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
10242 				 err);
10243 			set_bit(__I40E_BAD_EEPROM, pf->state);
10244 		}
10245 	}
10246 
10247 	if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
10248 		dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
10249 		clear_bit(__I40E_BAD_EEPROM, pf->state);
10250 	}
10251 }
10252 
10253 /**
10254  * i40e_enable_pf_switch_lb
10255  * @pf: pointer to the PF structure
10256  *
10257  * enable switch loop back or die - no point in a return value
10258  **/
10259 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
10260 {
10261 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10262 	struct i40e_vsi_context ctxt;
10263 	int ret;
10264 
10265 	ctxt.seid = pf->main_vsi_seid;
10266 	ctxt.pf_num = pf->hw.pf_id;
10267 	ctxt.vf_num = 0;
10268 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10269 	if (ret) {
10270 		dev_info(&pf->pdev->dev,
10271 			 "couldn't get PF vsi config, err %pe aq_err %s\n",
10272 			 ERR_PTR(ret),
10273 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10274 		return;
10275 	}
10276 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10277 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10278 	ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10279 
10280 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10281 	if (ret) {
10282 		dev_info(&pf->pdev->dev,
10283 			 "update vsi switch failed, err %pe aq_err %s\n",
10284 			 ERR_PTR(ret),
10285 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10286 	}
10287 }
10288 
10289 /**
10290  * i40e_disable_pf_switch_lb
10291  * @pf: pointer to the PF structure
10292  *
10293  * disable switch loop back or die - no point in a return value
10294  **/
10295 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
10296 {
10297 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10298 	struct i40e_vsi_context ctxt;
10299 	int ret;
10300 
10301 	ctxt.seid = pf->main_vsi_seid;
10302 	ctxt.pf_num = pf->hw.pf_id;
10303 	ctxt.vf_num = 0;
10304 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10305 	if (ret) {
10306 		dev_info(&pf->pdev->dev,
10307 			 "couldn't get PF vsi config, err %pe aq_err %s\n",
10308 			 ERR_PTR(ret),
10309 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10310 		return;
10311 	}
10312 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10313 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10314 	ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10315 
10316 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10317 	if (ret) {
10318 		dev_info(&pf->pdev->dev,
10319 			 "update vsi switch failed, err %pe aq_err %s\n",
10320 			 ERR_PTR(ret),
10321 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10322 	}
10323 }
10324 
10325 /**
10326  * i40e_config_bridge_mode - Configure the HW bridge mode
10327  * @veb: pointer to the bridge instance
10328  *
10329  * Configure the loop back mode for the LAN VSI that is downlink to the
10330  * specified HW bridge instance. It is expected this function is called
10331  * when a new HW bridge is instantiated.
10332  **/
10333 static void i40e_config_bridge_mode(struct i40e_veb *veb)
10334 {
10335 	struct i40e_pf *pf = veb->pf;
10336 
10337 	if (pf->hw.debug_mask & I40E_DEBUG_LAN)
10338 		dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
10339 			 veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
10340 	if (veb->bridge_mode & BRIDGE_MODE_VEPA)
10341 		i40e_disable_pf_switch_lb(pf);
10342 	else
10343 		i40e_enable_pf_switch_lb(pf);
10344 }
10345 
10346 /**
10347  * i40e_reconstitute_veb - rebuild the VEB and anything connected to it
10348  * @veb: pointer to the VEB instance
10349  *
10350  * This is a recursive function that first builds the attached VSIs then
10351  * recurses in to build the next layer of VEB.  We track the connections
10352  * through our own index numbers because the seid's from the HW could
10353  * change across the reset.
10354  **/
10355 static int i40e_reconstitute_veb(struct i40e_veb *veb)
10356 {
10357 	struct i40e_vsi *ctl_vsi = NULL;
10358 	struct i40e_pf *pf = veb->pf;
10359 	int v, veb_idx;
10360 	int ret;
10361 
10362 	/* build VSI that owns this VEB, temporarily attached to base VEB */
10363 	for (v = 0; v < pf->num_alloc_vsi && !ctl_vsi; v++) {
10364 		if (pf->vsi[v] &&
10365 		    pf->vsi[v]->veb_idx == veb->idx &&
10366 		    pf->vsi[v]->flags & I40E_VSI_FLAG_VEB_OWNER) {
10367 			ctl_vsi = pf->vsi[v];
10368 			break;
10369 		}
10370 	}
10371 	if (!ctl_vsi) {
10372 		dev_info(&pf->pdev->dev,
10373 			 "missing owner VSI for veb_idx %d\n", veb->idx);
10374 		ret = -ENOENT;
10375 		goto end_reconstitute;
10376 	}
10377 	if (ctl_vsi != pf->vsi[pf->lan_vsi])
10378 		ctl_vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
10379 	ret = i40e_add_vsi(ctl_vsi);
10380 	if (ret) {
10381 		dev_info(&pf->pdev->dev,
10382 			 "rebuild of veb_idx %d owner VSI failed: %d\n",
10383 			 veb->idx, ret);
10384 		goto end_reconstitute;
10385 	}
10386 	i40e_vsi_reset_stats(ctl_vsi);
10387 
10388 	/* create the VEB in the switch and move the VSI onto the VEB */
10389 	ret = i40e_add_veb(veb, ctl_vsi);
10390 	if (ret)
10391 		goto end_reconstitute;
10392 
10393 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
10394 		veb->bridge_mode = BRIDGE_MODE_VEB;
10395 	else
10396 		veb->bridge_mode = BRIDGE_MODE_VEPA;
10397 	i40e_config_bridge_mode(veb);
10398 
10399 	/* create the remaining VSIs attached to this VEB */
10400 	for (v = 0; v < pf->num_alloc_vsi; v++) {
10401 		if (!pf->vsi[v] || pf->vsi[v] == ctl_vsi)
10402 			continue;
10403 
10404 		if (pf->vsi[v]->veb_idx == veb->idx) {
10405 			struct i40e_vsi *vsi = pf->vsi[v];
10406 
10407 			vsi->uplink_seid = veb->seid;
10408 			ret = i40e_add_vsi(vsi);
10409 			if (ret) {
10410 				dev_info(&pf->pdev->dev,
10411 					 "rebuild of vsi_idx %d failed: %d\n",
10412 					 v, ret);
10413 				goto end_reconstitute;
10414 			}
10415 			i40e_vsi_reset_stats(vsi);
10416 		}
10417 	}
10418 
10419 	/* create any VEBs attached to this VEB - RECURSION */
10420 	for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
10421 		if (pf->veb[veb_idx] && pf->veb[veb_idx]->veb_idx == veb->idx) {
10422 			pf->veb[veb_idx]->uplink_seid = veb->seid;
10423 			ret = i40e_reconstitute_veb(pf->veb[veb_idx]);
10424 			if (ret)
10425 				break;
10426 		}
10427 	}
10428 
10429 end_reconstitute:
10430 	return ret;
10431 }
10432 
10433 /**
10434  * i40e_get_capabilities - get info about the HW
10435  * @pf: the PF struct
10436  * @list_type: AQ capability to be queried
10437  **/
10438 static int i40e_get_capabilities(struct i40e_pf *pf,
10439 				 enum i40e_admin_queue_opc list_type)
10440 {
10441 	struct i40e_aqc_list_capabilities_element_resp *cap_buf;
10442 	u16 data_size;
10443 	int buf_len;
10444 	int err;
10445 
10446 	buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
10447 	do {
10448 		cap_buf = kzalloc(buf_len, GFP_KERNEL);
10449 		if (!cap_buf)
10450 			return -ENOMEM;
10451 
10452 		/* this loads the data into the hw struct for us */
10453 		err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
10454 						    &data_size, list_type,
10455 						    NULL);
10456 		/* data loaded, buffer no longer needed */
10457 		kfree(cap_buf);
10458 
10459 		if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
10460 			/* retry with a larger buffer */
10461 			buf_len = data_size;
10462 		} else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK || err) {
10463 			dev_info(&pf->pdev->dev,
10464 				 "capability discovery failed, err %pe aq_err %s\n",
10465 				 ERR_PTR(err),
10466 				 i40e_aq_str(&pf->hw,
10467 					     pf->hw.aq.asq_last_status));
10468 			return -ENODEV;
10469 		}
10470 	} while (err);
10471 
10472 	if (pf->hw.debug_mask & I40E_DEBUG_USER) {
10473 		if (list_type == i40e_aqc_opc_list_func_capabilities) {
10474 			dev_info(&pf->pdev->dev,
10475 				 "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",
10476 				 pf->hw.pf_id, pf->hw.func_caps.num_vfs,
10477 				 pf->hw.func_caps.num_msix_vectors,
10478 				 pf->hw.func_caps.num_msix_vectors_vf,
10479 				 pf->hw.func_caps.fd_filters_guaranteed,
10480 				 pf->hw.func_caps.fd_filters_best_effort,
10481 				 pf->hw.func_caps.num_tx_qp,
10482 				 pf->hw.func_caps.num_vsis);
10483 		} else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
10484 			dev_info(&pf->pdev->dev,
10485 				 "switch_mode=0x%04x, function_valid=0x%08x\n",
10486 				 pf->hw.dev_caps.switch_mode,
10487 				 pf->hw.dev_caps.valid_functions);
10488 			dev_info(&pf->pdev->dev,
10489 				 "SR-IOV=%d, num_vfs for all function=%u\n",
10490 				 pf->hw.dev_caps.sr_iov_1_1,
10491 				 pf->hw.dev_caps.num_vfs);
10492 			dev_info(&pf->pdev->dev,
10493 				 "num_vsis=%u, num_rx:%u, num_tx=%u\n",
10494 				 pf->hw.dev_caps.num_vsis,
10495 				 pf->hw.dev_caps.num_rx_qp,
10496 				 pf->hw.dev_caps.num_tx_qp);
10497 		}
10498 	}
10499 	if (list_type == i40e_aqc_opc_list_func_capabilities) {
10500 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
10501 		       + pf->hw.func_caps.num_vfs)
10502 		if (pf->hw.revision_id == 0 &&
10503 		    pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
10504 			dev_info(&pf->pdev->dev,
10505 				 "got num_vsis %d, setting num_vsis to %d\n",
10506 				 pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
10507 			pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
10508 		}
10509 	}
10510 	return 0;
10511 }
10512 
10513 static int i40e_vsi_clear(struct i40e_vsi *vsi);
10514 
10515 /**
10516  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
10517  * @pf: board private structure
10518  **/
10519 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
10520 {
10521 	struct i40e_vsi *vsi;
10522 
10523 	/* quick workaround for an NVM issue that leaves a critical register
10524 	 * uninitialized
10525 	 */
10526 	if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
10527 		static const u32 hkey[] = {
10528 			0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
10529 			0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
10530 			0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
10531 			0x95b3a76d};
10532 		int i;
10533 
10534 		for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
10535 			wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
10536 	}
10537 
10538 	if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
10539 		return;
10540 
10541 	/* find existing VSI and see if it needs configuring */
10542 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10543 
10544 	/* create a new VSI if none exists */
10545 	if (!vsi) {
10546 		vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR,
10547 				     pf->vsi[pf->lan_vsi]->seid, 0);
10548 		if (!vsi) {
10549 			dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
10550 			pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
10551 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
10552 			return;
10553 		}
10554 	}
10555 
10556 	i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
10557 }
10558 
10559 /**
10560  * i40e_fdir_teardown - release the Flow Director resources
10561  * @pf: board private structure
10562  **/
10563 static void i40e_fdir_teardown(struct i40e_pf *pf)
10564 {
10565 	struct i40e_vsi *vsi;
10566 
10567 	i40e_fdir_filter_exit(pf);
10568 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10569 	if (vsi)
10570 		i40e_vsi_release(vsi);
10571 }
10572 
10573 /**
10574  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
10575  * @vsi: PF main vsi
10576  * @seid: seid of main or channel VSIs
10577  *
10578  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
10579  * existed before reset
10580  **/
10581 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
10582 {
10583 	struct i40e_cloud_filter *cfilter;
10584 	struct i40e_pf *pf = vsi->back;
10585 	struct hlist_node *node;
10586 	int ret;
10587 
10588 	/* Add cloud filters back if they exist */
10589 	hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
10590 				  cloud_node) {
10591 		if (cfilter->seid != seid)
10592 			continue;
10593 
10594 		if (cfilter->dst_port)
10595 			ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
10596 								true);
10597 		else
10598 			ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
10599 
10600 		if (ret) {
10601 			dev_dbg(&pf->pdev->dev,
10602 				"Failed to rebuild cloud filter, err %pe aq_err %s\n",
10603 				ERR_PTR(ret),
10604 				i40e_aq_str(&pf->hw,
10605 					    pf->hw.aq.asq_last_status));
10606 			return ret;
10607 		}
10608 	}
10609 	return 0;
10610 }
10611 
10612 /**
10613  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
10614  * @vsi: PF main vsi
10615  *
10616  * Rebuilds channel VSIs if they existed before reset
10617  **/
10618 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
10619 {
10620 	struct i40e_channel *ch, *ch_tmp;
10621 	int ret;
10622 
10623 	if (list_empty(&vsi->ch_list))
10624 		return 0;
10625 
10626 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
10627 		if (!ch->initialized)
10628 			break;
10629 		/* Proceed with creation of channel (VMDq2) VSI */
10630 		ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
10631 		if (ret) {
10632 			dev_info(&vsi->back->pdev->dev,
10633 				 "failed to rebuild channels using uplink_seid %u\n",
10634 				 vsi->uplink_seid);
10635 			return ret;
10636 		}
10637 		/* Reconfigure TX queues using QTX_CTL register */
10638 		ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
10639 		if (ret) {
10640 			dev_info(&vsi->back->pdev->dev,
10641 				 "failed to configure TX rings for channel %u\n",
10642 				 ch->seid);
10643 			return ret;
10644 		}
10645 		/* update 'next_base_queue' */
10646 		vsi->next_base_queue = vsi->next_base_queue +
10647 							ch->num_queue_pairs;
10648 		if (ch->max_tx_rate) {
10649 			u64 credits = ch->max_tx_rate;
10650 
10651 			if (i40e_set_bw_limit(vsi, ch->seid,
10652 					      ch->max_tx_rate))
10653 				return -EINVAL;
10654 
10655 			do_div(credits, I40E_BW_CREDIT_DIVISOR);
10656 			dev_dbg(&vsi->back->pdev->dev,
10657 				"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10658 				ch->max_tx_rate,
10659 				credits,
10660 				ch->seid);
10661 		}
10662 		ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
10663 		if (ret) {
10664 			dev_dbg(&vsi->back->pdev->dev,
10665 				"Failed to rebuild cloud filters for channel VSI %u\n",
10666 				ch->seid);
10667 			return ret;
10668 		}
10669 	}
10670 	return 0;
10671 }
10672 
10673 /**
10674  * i40e_clean_xps_state - clean xps state for every tx_ring
10675  * @vsi: ptr to the VSI
10676  **/
10677 static void i40e_clean_xps_state(struct i40e_vsi *vsi)
10678 {
10679 	int i;
10680 
10681 	if (vsi->tx_rings)
10682 		for (i = 0; i < vsi->num_queue_pairs; i++)
10683 			if (vsi->tx_rings[i])
10684 				clear_bit(__I40E_TX_XPS_INIT_DONE,
10685 					  vsi->tx_rings[i]->state);
10686 }
10687 
10688 /**
10689  * i40e_prep_for_reset - prep for the core to reset
10690  * @pf: board private structure
10691  *
10692  * Close up the VFs and other things in prep for PF Reset.
10693   **/
10694 static void i40e_prep_for_reset(struct i40e_pf *pf)
10695 {
10696 	struct i40e_hw *hw = &pf->hw;
10697 	int ret = 0;
10698 	u32 v;
10699 
10700 	clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
10701 	if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
10702 		return;
10703 	if (i40e_check_asq_alive(&pf->hw))
10704 		i40e_vc_notify_reset(pf);
10705 
10706 	dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
10707 
10708 	/* quiesce the VSIs and their queues that are not already DOWN */
10709 	i40e_pf_quiesce_all_vsi(pf);
10710 
10711 	for (v = 0; v < pf->num_alloc_vsi; v++) {
10712 		if (pf->vsi[v]) {
10713 			i40e_clean_xps_state(pf->vsi[v]);
10714 			pf->vsi[v]->seid = 0;
10715 		}
10716 	}
10717 
10718 	i40e_shutdown_adminq(&pf->hw);
10719 
10720 	/* call shutdown HMC */
10721 	if (hw->hmc.hmc_obj) {
10722 		ret = i40e_shutdown_lan_hmc(hw);
10723 		if (ret)
10724 			dev_warn(&pf->pdev->dev,
10725 				 "shutdown_lan_hmc failed: %d\n", ret);
10726 	}
10727 
10728 	/* Save the current PTP time so that we can restore the time after the
10729 	 * reset completes.
10730 	 */
10731 	i40e_ptp_save_hw_time(pf);
10732 }
10733 
10734 /**
10735  * i40e_send_version - update firmware with driver version
10736  * @pf: PF struct
10737  */
10738 static void i40e_send_version(struct i40e_pf *pf)
10739 {
10740 	struct i40e_driver_version dv;
10741 
10742 	dv.major_version = 0xff;
10743 	dv.minor_version = 0xff;
10744 	dv.build_version = 0xff;
10745 	dv.subbuild_version = 0;
10746 	strscpy(dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string));
10747 	i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
10748 }
10749 
10750 /**
10751  * i40e_get_oem_version - get OEM specific version information
10752  * @hw: pointer to the hardware structure
10753  **/
10754 static void i40e_get_oem_version(struct i40e_hw *hw)
10755 {
10756 	u16 block_offset = 0xffff;
10757 	u16 block_length = 0;
10758 	u16 capabilities = 0;
10759 	u16 gen_snap = 0;
10760 	u16 release = 0;
10761 
10762 #define I40E_SR_NVM_OEM_VERSION_PTR		0x1B
10763 #define I40E_NVM_OEM_LENGTH_OFFSET		0x00
10764 #define I40E_NVM_OEM_CAPABILITIES_OFFSET	0x01
10765 #define I40E_NVM_OEM_GEN_OFFSET			0x02
10766 #define I40E_NVM_OEM_RELEASE_OFFSET		0x03
10767 #define I40E_NVM_OEM_CAPABILITIES_MASK		0x000F
10768 #define I40E_NVM_OEM_LENGTH			3
10769 
10770 	/* Check if pointer to OEM version block is valid. */
10771 	i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
10772 	if (block_offset == 0xffff)
10773 		return;
10774 
10775 	/* Check if OEM version block has correct length. */
10776 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
10777 			   &block_length);
10778 	if (block_length < I40E_NVM_OEM_LENGTH)
10779 		return;
10780 
10781 	/* Check if OEM version format is as expected. */
10782 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
10783 			   &capabilities);
10784 	if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
10785 		return;
10786 
10787 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
10788 			   &gen_snap);
10789 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
10790 			   &release);
10791 	hw->nvm.oem_ver = (gen_snap << I40E_OEM_SNAP_SHIFT) | release;
10792 	hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
10793 }
10794 
10795 /**
10796  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
10797  * @pf: board private structure
10798  **/
10799 static int i40e_reset(struct i40e_pf *pf)
10800 {
10801 	struct i40e_hw *hw = &pf->hw;
10802 	int ret;
10803 
10804 	ret = i40e_pf_reset(hw);
10805 	if (ret) {
10806 		dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
10807 		set_bit(__I40E_RESET_FAILED, pf->state);
10808 		clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10809 	} else {
10810 		pf->pfr_count++;
10811 	}
10812 	return ret;
10813 }
10814 
10815 /**
10816  * i40e_rebuild - rebuild using a saved config
10817  * @pf: board private structure
10818  * @reinit: if the Main VSI needs to re-initialized.
10819  * @lock_acquired: indicates whether or not the lock has been acquired
10820  * before this function was called.
10821  **/
10822 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
10823 {
10824 	const bool is_recovery_mode_reported = i40e_check_recovery_mode(pf);
10825 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10826 	struct i40e_hw *hw = &pf->hw;
10827 	int ret;
10828 	u32 val;
10829 	int v;
10830 
10831 	if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10832 	    is_recovery_mode_reported)
10833 		i40e_set_ethtool_ops(pf->vsi[pf->lan_vsi]->netdev);
10834 
10835 	if (test_bit(__I40E_DOWN, pf->state) &&
10836 	    !test_bit(__I40E_RECOVERY_MODE, pf->state))
10837 		goto clear_recovery;
10838 	dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
10839 
10840 	/* rebuild the basics for the AdminQ, HMC, and initial HW switch */
10841 	ret = i40e_init_adminq(&pf->hw);
10842 	if (ret) {
10843 		dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %pe aq_err %s\n",
10844 			 ERR_PTR(ret),
10845 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10846 		goto clear_recovery;
10847 	}
10848 	i40e_get_oem_version(&pf->hw);
10849 
10850 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state)) {
10851 		/* The following delay is necessary for firmware update. */
10852 		mdelay(1000);
10853 	}
10854 
10855 	/* re-verify the eeprom if we just had an EMP reset */
10856 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
10857 		i40e_verify_eeprom(pf);
10858 
10859 	/* if we are going out of or into recovery mode we have to act
10860 	 * accordingly with regard to resources initialization
10861 	 * and deinitialization
10862 	 */
10863 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10864 		if (i40e_get_capabilities(pf,
10865 					  i40e_aqc_opc_list_func_capabilities))
10866 			goto end_unlock;
10867 
10868 		if (is_recovery_mode_reported) {
10869 			/* we're staying in recovery mode so we'll reinitialize
10870 			 * misc vector here
10871 			 */
10872 			if (i40e_setup_misc_vector_for_recovery_mode(pf))
10873 				goto end_unlock;
10874 		} else {
10875 			if (!lock_acquired)
10876 				rtnl_lock();
10877 			/* we're going out of recovery mode so we'll free
10878 			 * the IRQ allocated specifically for recovery mode
10879 			 * and restore the interrupt scheme
10880 			 */
10881 			free_irq(pf->pdev->irq, pf);
10882 			i40e_clear_interrupt_scheme(pf);
10883 			if (i40e_restore_interrupt_scheme(pf))
10884 				goto end_unlock;
10885 		}
10886 
10887 		/* tell the firmware that we're starting */
10888 		i40e_send_version(pf);
10889 
10890 		/* bail out in case recovery mode was detected, as there is
10891 		 * no need for further configuration.
10892 		 */
10893 		goto end_unlock;
10894 	}
10895 
10896 	i40e_clear_pxe_mode(hw);
10897 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10898 	if (ret)
10899 		goto end_core_reset;
10900 
10901 	ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10902 				hw->func_caps.num_rx_qp, 0, 0);
10903 	if (ret) {
10904 		dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10905 		goto end_core_reset;
10906 	}
10907 	ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10908 	if (ret) {
10909 		dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10910 		goto end_core_reset;
10911 	}
10912 
10913 #ifdef CONFIG_I40E_DCB
10914 	/* Enable FW to write a default DCB config on link-up
10915 	 * unless I40E_FLAG_TC_MQPRIO was enabled or DCB
10916 	 * is not supported with new link speed
10917 	 */
10918 	if (i40e_is_tc_mqprio_enabled(pf)) {
10919 		i40e_aq_set_dcb_parameters(hw, false, NULL);
10920 	} else {
10921 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
10922 		    (hw->phy.link_info.link_speed &
10923 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
10924 			i40e_aq_set_dcb_parameters(hw, false, NULL);
10925 			dev_warn(&pf->pdev->dev,
10926 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
10927 			pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10928 		} else {
10929 			i40e_aq_set_dcb_parameters(hw, true, NULL);
10930 			ret = i40e_init_pf_dcb(pf);
10931 			if (ret) {
10932 				dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n",
10933 					 ret);
10934 				pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10935 				/* Continue without DCB enabled */
10936 			}
10937 		}
10938 	}
10939 
10940 #endif /* CONFIG_I40E_DCB */
10941 	if (!lock_acquired)
10942 		rtnl_lock();
10943 	ret = i40e_setup_pf_switch(pf, reinit, true);
10944 	if (ret)
10945 		goto end_unlock;
10946 
10947 	/* The driver only wants link up/down and module qualification
10948 	 * reports from firmware.  Note the negative logic.
10949 	 */
10950 	ret = i40e_aq_set_phy_int_mask(&pf->hw,
10951 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
10952 					 I40E_AQ_EVENT_MEDIA_NA |
10953 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10954 	if (ret)
10955 		dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
10956 			 ERR_PTR(ret),
10957 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10958 
10959 	/* Rebuild the VSIs and VEBs that existed before reset.
10960 	 * They are still in our local switch element arrays, so only
10961 	 * need to rebuild the switch model in the HW.
10962 	 *
10963 	 * If there were VEBs but the reconstitution failed, we'll try
10964 	 * to recover minimal use by getting the basic PF VSI working.
10965 	 */
10966 	if (vsi->uplink_seid != pf->mac_seid) {
10967 		dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
10968 		/* find the one VEB connected to the MAC, and find orphans */
10969 		for (v = 0; v < I40E_MAX_VEB; v++) {
10970 			if (!pf->veb[v])
10971 				continue;
10972 
10973 			if (pf->veb[v]->uplink_seid == pf->mac_seid ||
10974 			    pf->veb[v]->uplink_seid == 0) {
10975 				ret = i40e_reconstitute_veb(pf->veb[v]);
10976 
10977 				if (!ret)
10978 					continue;
10979 
10980 				/* If Main VEB failed, we're in deep doodoo,
10981 				 * so give up rebuilding the switch and set up
10982 				 * for minimal rebuild of PF VSI.
10983 				 * If orphan failed, we'll report the error
10984 				 * but try to keep going.
10985 				 */
10986 				if (pf->veb[v]->uplink_seid == pf->mac_seid) {
10987 					dev_info(&pf->pdev->dev,
10988 						 "rebuild of switch failed: %d, will try to set up simple PF connection\n",
10989 						 ret);
10990 					vsi->uplink_seid = pf->mac_seid;
10991 					break;
10992 				} else if (pf->veb[v]->uplink_seid == 0) {
10993 					dev_info(&pf->pdev->dev,
10994 						 "rebuild of orphan VEB failed: %d\n",
10995 						 ret);
10996 				}
10997 			}
10998 		}
10999 	}
11000 
11001 	if (vsi->uplink_seid == pf->mac_seid) {
11002 		dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
11003 		/* no VEB, so rebuild only the Main VSI */
11004 		ret = i40e_add_vsi(vsi);
11005 		if (ret) {
11006 			dev_info(&pf->pdev->dev,
11007 				 "rebuild of Main VSI failed: %d\n", ret);
11008 			goto end_unlock;
11009 		}
11010 	}
11011 
11012 	if (vsi->mqprio_qopt.max_rate[0]) {
11013 		u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
11014 						  vsi->mqprio_qopt.max_rate[0]);
11015 		u64 credits = 0;
11016 
11017 		ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
11018 		if (ret)
11019 			goto end_unlock;
11020 
11021 		credits = max_tx_rate;
11022 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
11023 		dev_dbg(&vsi->back->pdev->dev,
11024 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
11025 			max_tx_rate,
11026 			credits,
11027 			vsi->seid);
11028 	}
11029 
11030 	ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
11031 	if (ret)
11032 		goto end_unlock;
11033 
11034 	/* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
11035 	 * for this main VSI if they exist
11036 	 */
11037 	ret = i40e_rebuild_channels(vsi);
11038 	if (ret)
11039 		goto end_unlock;
11040 
11041 	/* Reconfigure hardware for allowing smaller MSS in the case
11042 	 * of TSO, so that we avoid the MDD being fired and causing
11043 	 * a reset in the case of small MSS+TSO.
11044 	 */
11045 #define I40E_REG_MSS          0x000E64DC
11046 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
11047 #define I40E_64BYTE_MSS       0x400000
11048 	val = rd32(hw, I40E_REG_MSS);
11049 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
11050 		val &= ~I40E_REG_MSS_MIN_MASK;
11051 		val |= I40E_64BYTE_MSS;
11052 		wr32(hw, I40E_REG_MSS, val);
11053 	}
11054 
11055 	if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
11056 		msleep(75);
11057 		ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
11058 		if (ret)
11059 			dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
11060 				 ERR_PTR(ret),
11061 				 i40e_aq_str(&pf->hw,
11062 					     pf->hw.aq.asq_last_status));
11063 	}
11064 	/* reinit the misc interrupt */
11065 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11066 		ret = i40e_setup_misc_vector(pf);
11067 		if (ret)
11068 			goto end_unlock;
11069 	}
11070 
11071 	/* Add a filter to drop all Flow control frames from any VSI from being
11072 	 * transmitted. By doing so we stop a malicious VF from sending out
11073 	 * PAUSE or PFC frames and potentially controlling traffic for other
11074 	 * PF/VF VSIs.
11075 	 * The FW can still send Flow control frames if enabled.
11076 	 */
11077 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
11078 						       pf->main_vsi_seid);
11079 
11080 	/* restart the VSIs that were rebuilt and running before the reset */
11081 	i40e_pf_unquiesce_all_vsi(pf);
11082 
11083 	/* Release the RTNL lock before we start resetting VFs */
11084 	if (!lock_acquired)
11085 		rtnl_unlock();
11086 
11087 	/* Restore promiscuous settings */
11088 	ret = i40e_set_promiscuous(pf, pf->cur_promisc);
11089 	if (ret)
11090 		dev_warn(&pf->pdev->dev,
11091 			 "Failed to restore promiscuous setting: %s, err %pe aq_err %s\n",
11092 			 pf->cur_promisc ? "on" : "off",
11093 			 ERR_PTR(ret),
11094 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11095 
11096 	i40e_reset_all_vfs(pf, true);
11097 
11098 	/* tell the firmware that we're starting */
11099 	i40e_send_version(pf);
11100 
11101 	/* We've already released the lock, so don't do it again */
11102 	goto end_core_reset;
11103 
11104 end_unlock:
11105 	if (!lock_acquired)
11106 		rtnl_unlock();
11107 end_core_reset:
11108 	clear_bit(__I40E_RESET_FAILED, pf->state);
11109 clear_recovery:
11110 	clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
11111 	clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
11112 }
11113 
11114 /**
11115  * i40e_reset_and_rebuild - reset and rebuild using a saved config
11116  * @pf: board private structure
11117  * @reinit: if the Main VSI needs to re-initialized.
11118  * @lock_acquired: indicates whether or not the lock has been acquired
11119  * before this function was called.
11120  **/
11121 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
11122 				   bool lock_acquired)
11123 {
11124 	int ret;
11125 
11126 	if (test_bit(__I40E_IN_REMOVE, pf->state))
11127 		return;
11128 	/* Now we wait for GRST to settle out.
11129 	 * We don't have to delete the VEBs or VSIs from the hw switch
11130 	 * because the reset will make them disappear.
11131 	 */
11132 	ret = i40e_reset(pf);
11133 	if (!ret)
11134 		i40e_rebuild(pf, reinit, lock_acquired);
11135 }
11136 
11137 /**
11138  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
11139  * @pf: board private structure
11140  *
11141  * Close up the VFs and other things in prep for a Core Reset,
11142  * then get ready to rebuild the world.
11143  * @lock_acquired: indicates whether or not the lock has been acquired
11144  * before this function was called.
11145  **/
11146 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
11147 {
11148 	i40e_prep_for_reset(pf);
11149 	i40e_reset_and_rebuild(pf, false, lock_acquired);
11150 }
11151 
11152 /**
11153  * i40e_handle_mdd_event
11154  * @pf: pointer to the PF structure
11155  *
11156  * Called from the MDD irq handler to identify possibly malicious vfs
11157  **/
11158 static void i40e_handle_mdd_event(struct i40e_pf *pf)
11159 {
11160 	struct i40e_hw *hw = &pf->hw;
11161 	bool mdd_detected = false;
11162 	struct i40e_vf *vf;
11163 	u32 reg;
11164 	int i;
11165 
11166 	if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
11167 		return;
11168 
11169 	/* find what triggered the MDD event */
11170 	reg = rd32(hw, I40E_GL_MDET_TX);
11171 	if (reg & I40E_GL_MDET_TX_VALID_MASK) {
11172 		u8 pf_num = (reg & I40E_GL_MDET_TX_PF_NUM_MASK) >>
11173 				I40E_GL_MDET_TX_PF_NUM_SHIFT;
11174 		u16 vf_num = (reg & I40E_GL_MDET_TX_VF_NUM_MASK) >>
11175 				I40E_GL_MDET_TX_VF_NUM_SHIFT;
11176 		u8 event = (reg & I40E_GL_MDET_TX_EVENT_MASK) >>
11177 				I40E_GL_MDET_TX_EVENT_SHIFT;
11178 		u16 queue = ((reg & I40E_GL_MDET_TX_QUEUE_MASK) >>
11179 				I40E_GL_MDET_TX_QUEUE_SHIFT) -
11180 				pf->hw.func_caps.base_queue;
11181 		if (netif_msg_tx_err(pf))
11182 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
11183 				 event, queue, pf_num, vf_num);
11184 		wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
11185 		mdd_detected = true;
11186 	}
11187 	reg = rd32(hw, I40E_GL_MDET_RX);
11188 	if (reg & I40E_GL_MDET_RX_VALID_MASK) {
11189 		u8 func = (reg & I40E_GL_MDET_RX_FUNCTION_MASK) >>
11190 				I40E_GL_MDET_RX_FUNCTION_SHIFT;
11191 		u8 event = (reg & I40E_GL_MDET_RX_EVENT_MASK) >>
11192 				I40E_GL_MDET_RX_EVENT_SHIFT;
11193 		u16 queue = ((reg & I40E_GL_MDET_RX_QUEUE_MASK) >>
11194 				I40E_GL_MDET_RX_QUEUE_SHIFT) -
11195 				pf->hw.func_caps.base_queue;
11196 		if (netif_msg_rx_err(pf))
11197 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
11198 				 event, queue, func);
11199 		wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
11200 		mdd_detected = true;
11201 	}
11202 
11203 	if (mdd_detected) {
11204 		reg = rd32(hw, I40E_PF_MDET_TX);
11205 		if (reg & I40E_PF_MDET_TX_VALID_MASK) {
11206 			wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
11207 			dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
11208 		}
11209 		reg = rd32(hw, I40E_PF_MDET_RX);
11210 		if (reg & I40E_PF_MDET_RX_VALID_MASK) {
11211 			wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
11212 			dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
11213 		}
11214 	}
11215 
11216 	/* see if one of the VFs needs its hand slapped */
11217 	for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
11218 		vf = &(pf->vf[i]);
11219 		reg = rd32(hw, I40E_VP_MDET_TX(i));
11220 		if (reg & I40E_VP_MDET_TX_VALID_MASK) {
11221 			wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
11222 			vf->num_mdd_events++;
11223 			dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
11224 				 i);
11225 			dev_info(&pf->pdev->dev,
11226 				 "Use PF Control I/F to re-enable the VF\n");
11227 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11228 		}
11229 
11230 		reg = rd32(hw, I40E_VP_MDET_RX(i));
11231 		if (reg & I40E_VP_MDET_RX_VALID_MASK) {
11232 			wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
11233 			vf->num_mdd_events++;
11234 			dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
11235 				 i);
11236 			dev_info(&pf->pdev->dev,
11237 				 "Use PF Control I/F to re-enable the VF\n");
11238 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11239 		}
11240 	}
11241 
11242 	/* re-enable mdd interrupt cause */
11243 	clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
11244 	reg = rd32(hw, I40E_PFINT_ICR0_ENA);
11245 	reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
11246 	wr32(hw, I40E_PFINT_ICR0_ENA, reg);
11247 	i40e_flush(hw);
11248 }
11249 
11250 /**
11251  * i40e_service_task - Run the driver's async subtasks
11252  * @work: pointer to work_struct containing our data
11253  **/
11254 static void i40e_service_task(struct work_struct *work)
11255 {
11256 	struct i40e_pf *pf = container_of(work,
11257 					  struct i40e_pf,
11258 					  service_task);
11259 	unsigned long start_time = jiffies;
11260 
11261 	/* don't bother with service tasks if a reset is in progress */
11262 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
11263 	    test_bit(__I40E_SUSPENDED, pf->state))
11264 		return;
11265 
11266 	if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
11267 		return;
11268 
11269 	if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
11270 		i40e_detect_recover_hung(pf->vsi[pf->lan_vsi]);
11271 		i40e_sync_filters_subtask(pf);
11272 		i40e_reset_subtask(pf);
11273 		i40e_handle_mdd_event(pf);
11274 		i40e_vc_process_vflr_event(pf);
11275 		i40e_watchdog_subtask(pf);
11276 		i40e_fdir_reinit_subtask(pf);
11277 		if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
11278 			/* Client subtask will reopen next time through. */
11279 			i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi],
11280 							   true);
11281 		} else {
11282 			i40e_client_subtask(pf);
11283 			if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
11284 					       pf->state))
11285 				i40e_notify_client_of_l2_param_changes(
11286 								pf->vsi[pf->lan_vsi]);
11287 		}
11288 		i40e_sync_filters_subtask(pf);
11289 	} else {
11290 		i40e_reset_subtask(pf);
11291 	}
11292 
11293 	i40e_clean_adminq_subtask(pf);
11294 
11295 	/* flush memory to make sure state is correct before next watchdog */
11296 	smp_mb__before_atomic();
11297 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
11298 
11299 	/* If the tasks have taken longer than one timer cycle or there
11300 	 * is more work to be done, reschedule the service task now
11301 	 * rather than wait for the timer to tick again.
11302 	 */
11303 	if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
11304 	    test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)		 ||
11305 	    test_bit(__I40E_MDD_EVENT_PENDING, pf->state)		 ||
11306 	    test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
11307 		i40e_service_event_schedule(pf);
11308 }
11309 
11310 /**
11311  * i40e_service_timer - timer callback
11312  * @t: timer list pointer
11313  **/
11314 static void i40e_service_timer(struct timer_list *t)
11315 {
11316 	struct i40e_pf *pf = from_timer(pf, t, service_timer);
11317 
11318 	mod_timer(&pf->service_timer,
11319 		  round_jiffies(jiffies + pf->service_timer_period));
11320 	i40e_service_event_schedule(pf);
11321 }
11322 
11323 /**
11324  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
11325  * @vsi: the VSI being configured
11326  **/
11327 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
11328 {
11329 	struct i40e_pf *pf = vsi->back;
11330 
11331 	switch (vsi->type) {
11332 	case I40E_VSI_MAIN:
11333 		vsi->alloc_queue_pairs = pf->num_lan_qps;
11334 		if (!vsi->num_tx_desc)
11335 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11336 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11337 		if (!vsi->num_rx_desc)
11338 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11339 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11340 		if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11341 			vsi->num_q_vectors = pf->num_lan_msix;
11342 		else
11343 			vsi->num_q_vectors = 1;
11344 
11345 		break;
11346 
11347 	case I40E_VSI_FDIR:
11348 		vsi->alloc_queue_pairs = 1;
11349 		vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11350 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11351 		vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11352 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11353 		vsi->num_q_vectors = pf->num_fdsb_msix;
11354 		break;
11355 
11356 	case I40E_VSI_VMDQ2:
11357 		vsi->alloc_queue_pairs = pf->num_vmdq_qps;
11358 		if (!vsi->num_tx_desc)
11359 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11360 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11361 		if (!vsi->num_rx_desc)
11362 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11363 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11364 		vsi->num_q_vectors = pf->num_vmdq_msix;
11365 		break;
11366 
11367 	case I40E_VSI_SRIOV:
11368 		vsi->alloc_queue_pairs = pf->num_vf_qps;
11369 		if (!vsi->num_tx_desc)
11370 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11371 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11372 		if (!vsi->num_rx_desc)
11373 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11374 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11375 		break;
11376 
11377 	default:
11378 		WARN_ON(1);
11379 		return -ENODATA;
11380 	}
11381 
11382 	if (is_kdump_kernel()) {
11383 		vsi->num_tx_desc = I40E_MIN_NUM_DESCRIPTORS;
11384 		vsi->num_rx_desc = I40E_MIN_NUM_DESCRIPTORS;
11385 	}
11386 
11387 	return 0;
11388 }
11389 
11390 /**
11391  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
11392  * @vsi: VSI pointer
11393  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
11394  *
11395  * On error: returns error code (negative)
11396  * On success: returns 0
11397  **/
11398 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
11399 {
11400 	struct i40e_ring **next_rings;
11401 	int size;
11402 	int ret = 0;
11403 
11404 	/* allocate memory for both Tx, XDP Tx and Rx ring pointers */
11405 	size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
11406 	       (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
11407 	vsi->tx_rings = kzalloc(size, GFP_KERNEL);
11408 	if (!vsi->tx_rings)
11409 		return -ENOMEM;
11410 	next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
11411 	if (i40e_enabled_xdp_vsi(vsi)) {
11412 		vsi->xdp_rings = next_rings;
11413 		next_rings += vsi->alloc_queue_pairs;
11414 	}
11415 	vsi->rx_rings = next_rings;
11416 
11417 	if (alloc_qvectors) {
11418 		/* allocate memory for q_vector pointers */
11419 		size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
11420 		vsi->q_vectors = kzalloc(size, GFP_KERNEL);
11421 		if (!vsi->q_vectors) {
11422 			ret = -ENOMEM;
11423 			goto err_vectors;
11424 		}
11425 	}
11426 	return ret;
11427 
11428 err_vectors:
11429 	kfree(vsi->tx_rings);
11430 	return ret;
11431 }
11432 
11433 /**
11434  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
11435  * @pf: board private structure
11436  * @type: type of VSI
11437  *
11438  * On error: returns error code (negative)
11439  * On success: returns vsi index in PF (positive)
11440  **/
11441 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
11442 {
11443 	int ret = -ENODEV;
11444 	struct i40e_vsi *vsi;
11445 	int vsi_idx;
11446 	int i;
11447 
11448 	/* Need to protect the allocation of the VSIs at the PF level */
11449 	mutex_lock(&pf->switch_mutex);
11450 
11451 	/* VSI list may be fragmented if VSI creation/destruction has
11452 	 * been happening.  We can afford to do a quick scan to look
11453 	 * for any free VSIs in the list.
11454 	 *
11455 	 * find next empty vsi slot, looping back around if necessary
11456 	 */
11457 	i = pf->next_vsi;
11458 	while (i < pf->num_alloc_vsi && pf->vsi[i])
11459 		i++;
11460 	if (i >= pf->num_alloc_vsi) {
11461 		i = 0;
11462 		while (i < pf->next_vsi && pf->vsi[i])
11463 			i++;
11464 	}
11465 
11466 	if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
11467 		vsi_idx = i;             /* Found one! */
11468 	} else {
11469 		ret = -ENODEV;
11470 		goto unlock_pf;  /* out of VSI slots! */
11471 	}
11472 	pf->next_vsi = ++i;
11473 
11474 	vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
11475 	if (!vsi) {
11476 		ret = -ENOMEM;
11477 		goto unlock_pf;
11478 	}
11479 	vsi->type = type;
11480 	vsi->back = pf;
11481 	set_bit(__I40E_VSI_DOWN, vsi->state);
11482 	vsi->flags = 0;
11483 	vsi->idx = vsi_idx;
11484 	vsi->int_rate_limit = 0;
11485 	vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
11486 				pf->rss_table_size : 64;
11487 	vsi->netdev_registered = false;
11488 	vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
11489 	hash_init(vsi->mac_filter_hash);
11490 	vsi->irqs_ready = false;
11491 
11492 	if (type == I40E_VSI_MAIN) {
11493 		vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
11494 		if (!vsi->af_xdp_zc_qps)
11495 			goto err_rings;
11496 	}
11497 
11498 	ret = i40e_set_num_rings_in_vsi(vsi);
11499 	if (ret)
11500 		goto err_rings;
11501 
11502 	ret = i40e_vsi_alloc_arrays(vsi, true);
11503 	if (ret)
11504 		goto err_rings;
11505 
11506 	/* Setup default MSIX irq handler for VSI */
11507 	i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
11508 
11509 	/* Initialize VSI lock */
11510 	spin_lock_init(&vsi->mac_filter_hash_lock);
11511 	pf->vsi[vsi_idx] = vsi;
11512 	ret = vsi_idx;
11513 	goto unlock_pf;
11514 
11515 err_rings:
11516 	bitmap_free(vsi->af_xdp_zc_qps);
11517 	pf->next_vsi = i - 1;
11518 	kfree(vsi);
11519 unlock_pf:
11520 	mutex_unlock(&pf->switch_mutex);
11521 	return ret;
11522 }
11523 
11524 /**
11525  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
11526  * @vsi: VSI pointer
11527  * @free_qvectors: a bool to specify if q_vectors need to be freed.
11528  *
11529  * On error: returns error code (negative)
11530  * On success: returns 0
11531  **/
11532 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
11533 {
11534 	/* free the ring and vector containers */
11535 	if (free_qvectors) {
11536 		kfree(vsi->q_vectors);
11537 		vsi->q_vectors = NULL;
11538 	}
11539 	kfree(vsi->tx_rings);
11540 	vsi->tx_rings = NULL;
11541 	vsi->rx_rings = NULL;
11542 	vsi->xdp_rings = NULL;
11543 }
11544 
11545 /**
11546  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
11547  * and lookup table
11548  * @vsi: Pointer to VSI structure
11549  */
11550 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
11551 {
11552 	if (!vsi)
11553 		return;
11554 
11555 	kfree(vsi->rss_hkey_user);
11556 	vsi->rss_hkey_user = NULL;
11557 
11558 	kfree(vsi->rss_lut_user);
11559 	vsi->rss_lut_user = NULL;
11560 }
11561 
11562 /**
11563  * i40e_vsi_clear - Deallocate the VSI provided
11564  * @vsi: the VSI being un-configured
11565  **/
11566 static int i40e_vsi_clear(struct i40e_vsi *vsi)
11567 {
11568 	struct i40e_pf *pf;
11569 
11570 	if (!vsi)
11571 		return 0;
11572 
11573 	if (!vsi->back)
11574 		goto free_vsi;
11575 	pf = vsi->back;
11576 
11577 	mutex_lock(&pf->switch_mutex);
11578 	if (!pf->vsi[vsi->idx]) {
11579 		dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
11580 			vsi->idx, vsi->idx, vsi->type);
11581 		goto unlock_vsi;
11582 	}
11583 
11584 	if (pf->vsi[vsi->idx] != vsi) {
11585 		dev_err(&pf->pdev->dev,
11586 			"pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
11587 			pf->vsi[vsi->idx]->idx,
11588 			pf->vsi[vsi->idx]->type,
11589 			vsi->idx, vsi->type);
11590 		goto unlock_vsi;
11591 	}
11592 
11593 	/* updates the PF for this cleared vsi */
11594 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
11595 	i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
11596 
11597 	bitmap_free(vsi->af_xdp_zc_qps);
11598 	i40e_vsi_free_arrays(vsi, true);
11599 	i40e_clear_rss_config_user(vsi);
11600 
11601 	pf->vsi[vsi->idx] = NULL;
11602 	if (vsi->idx < pf->next_vsi)
11603 		pf->next_vsi = vsi->idx;
11604 
11605 unlock_vsi:
11606 	mutex_unlock(&pf->switch_mutex);
11607 free_vsi:
11608 	kfree(vsi);
11609 
11610 	return 0;
11611 }
11612 
11613 /**
11614  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
11615  * @vsi: the VSI being cleaned
11616  **/
11617 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
11618 {
11619 	int i;
11620 
11621 	if (vsi->tx_rings && vsi->tx_rings[0]) {
11622 		for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11623 			kfree_rcu(vsi->tx_rings[i], rcu);
11624 			WRITE_ONCE(vsi->tx_rings[i], NULL);
11625 			WRITE_ONCE(vsi->rx_rings[i], NULL);
11626 			if (vsi->xdp_rings)
11627 				WRITE_ONCE(vsi->xdp_rings[i], NULL);
11628 		}
11629 	}
11630 }
11631 
11632 /**
11633  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
11634  * @vsi: the VSI being configured
11635  **/
11636 static int i40e_alloc_rings(struct i40e_vsi *vsi)
11637 {
11638 	int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
11639 	struct i40e_pf *pf = vsi->back;
11640 	struct i40e_ring *ring;
11641 
11642 	/* Set basic values in the rings to be used later during open() */
11643 	for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11644 		/* allocate space for both Tx and Rx in one shot */
11645 		ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
11646 		if (!ring)
11647 			goto err_out;
11648 
11649 		ring->queue_index = i;
11650 		ring->reg_idx = vsi->base_queue + i;
11651 		ring->ring_active = false;
11652 		ring->vsi = vsi;
11653 		ring->netdev = vsi->netdev;
11654 		ring->dev = &pf->pdev->dev;
11655 		ring->count = vsi->num_tx_desc;
11656 		ring->size = 0;
11657 		ring->dcb_tc = 0;
11658 		if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11659 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11660 		ring->itr_setting = pf->tx_itr_default;
11661 		WRITE_ONCE(vsi->tx_rings[i], ring++);
11662 
11663 		if (!i40e_enabled_xdp_vsi(vsi))
11664 			goto setup_rx;
11665 
11666 		ring->queue_index = vsi->alloc_queue_pairs + i;
11667 		ring->reg_idx = vsi->base_queue + ring->queue_index;
11668 		ring->ring_active = false;
11669 		ring->vsi = vsi;
11670 		ring->netdev = NULL;
11671 		ring->dev = &pf->pdev->dev;
11672 		ring->count = vsi->num_tx_desc;
11673 		ring->size = 0;
11674 		ring->dcb_tc = 0;
11675 		if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11676 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11677 		set_ring_xdp(ring);
11678 		ring->itr_setting = pf->tx_itr_default;
11679 		WRITE_ONCE(vsi->xdp_rings[i], ring++);
11680 
11681 setup_rx:
11682 		ring->queue_index = i;
11683 		ring->reg_idx = vsi->base_queue + i;
11684 		ring->ring_active = false;
11685 		ring->vsi = vsi;
11686 		ring->netdev = vsi->netdev;
11687 		ring->dev = &pf->pdev->dev;
11688 		ring->count = vsi->num_rx_desc;
11689 		ring->size = 0;
11690 		ring->dcb_tc = 0;
11691 		ring->itr_setting = pf->rx_itr_default;
11692 		WRITE_ONCE(vsi->rx_rings[i], ring);
11693 	}
11694 
11695 	return 0;
11696 
11697 err_out:
11698 	i40e_vsi_clear_rings(vsi);
11699 	return -ENOMEM;
11700 }
11701 
11702 /**
11703  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
11704  * @pf: board private structure
11705  * @vectors: the number of MSI-X vectors to request
11706  *
11707  * Returns the number of vectors reserved, or error
11708  **/
11709 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
11710 {
11711 	vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
11712 					I40E_MIN_MSIX, vectors);
11713 	if (vectors < 0) {
11714 		dev_info(&pf->pdev->dev,
11715 			 "MSI-X vector reservation failed: %d\n", vectors);
11716 		vectors = 0;
11717 	}
11718 
11719 	return vectors;
11720 }
11721 
11722 /**
11723  * i40e_init_msix - Setup the MSIX capability
11724  * @pf: board private structure
11725  *
11726  * Work with the OS to set up the MSIX vectors needed.
11727  *
11728  * Returns the number of vectors reserved or negative on failure
11729  **/
11730 static int i40e_init_msix(struct i40e_pf *pf)
11731 {
11732 	struct i40e_hw *hw = &pf->hw;
11733 	int cpus, extra_vectors;
11734 	int vectors_left;
11735 	int v_budget, i;
11736 	int v_actual;
11737 	int iwarp_requested = 0;
11738 
11739 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
11740 		return -ENODEV;
11741 
11742 	/* The number of vectors we'll request will be comprised of:
11743 	 *   - Add 1 for "other" cause for Admin Queue events, etc.
11744 	 *   - The number of LAN queue pairs
11745 	 *	- Queues being used for RSS.
11746 	 *		We don't need as many as max_rss_size vectors.
11747 	 *		use rss_size instead in the calculation since that
11748 	 *		is governed by number of cpus in the system.
11749 	 *	- assumes symmetric Tx/Rx pairing
11750 	 *   - The number of VMDq pairs
11751 	 *   - The CPU count within the NUMA node if iWARP is enabled
11752 	 * Once we count this up, try the request.
11753 	 *
11754 	 * If we can't get what we want, we'll simplify to nearly nothing
11755 	 * and try again.  If that still fails, we punt.
11756 	 */
11757 	vectors_left = hw->func_caps.num_msix_vectors;
11758 	v_budget = 0;
11759 
11760 	/* reserve one vector for miscellaneous handler */
11761 	if (vectors_left) {
11762 		v_budget++;
11763 		vectors_left--;
11764 	}
11765 
11766 	/* reserve some vectors for the main PF traffic queues. Initially we
11767 	 * only reserve at most 50% of the available vectors, in the case that
11768 	 * the number of online CPUs is large. This ensures that we can enable
11769 	 * extra features as well. Once we've enabled the other features, we
11770 	 * will use any remaining vectors to reach as close as we can to the
11771 	 * number of online CPUs.
11772 	 */
11773 	cpus = num_online_cpus();
11774 	pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
11775 	vectors_left -= pf->num_lan_msix;
11776 
11777 	/* reserve one vector for sideband flow director */
11778 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11779 		if (vectors_left) {
11780 			pf->num_fdsb_msix = 1;
11781 			v_budget++;
11782 			vectors_left--;
11783 		} else {
11784 			pf->num_fdsb_msix = 0;
11785 		}
11786 	}
11787 
11788 	/* can we reserve enough for iWARP? */
11789 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11790 		iwarp_requested = pf->num_iwarp_msix;
11791 
11792 		if (!vectors_left)
11793 			pf->num_iwarp_msix = 0;
11794 		else if (vectors_left < pf->num_iwarp_msix)
11795 			pf->num_iwarp_msix = 1;
11796 		v_budget += pf->num_iwarp_msix;
11797 		vectors_left -= pf->num_iwarp_msix;
11798 	}
11799 
11800 	/* any vectors left over go for VMDq support */
11801 	if (pf->flags & I40E_FLAG_VMDQ_ENABLED) {
11802 		if (!vectors_left) {
11803 			pf->num_vmdq_msix = 0;
11804 			pf->num_vmdq_qps = 0;
11805 		} else {
11806 			int vmdq_vecs_wanted =
11807 				pf->num_vmdq_vsis * pf->num_vmdq_qps;
11808 			int vmdq_vecs =
11809 				min_t(int, vectors_left, vmdq_vecs_wanted);
11810 
11811 			/* if we're short on vectors for what's desired, we limit
11812 			 * the queues per vmdq.  If this is still more than are
11813 			 * available, the user will need to change the number of
11814 			 * queues/vectors used by the PF later with the ethtool
11815 			 * channels command
11816 			 */
11817 			if (vectors_left < vmdq_vecs_wanted) {
11818 				pf->num_vmdq_qps = 1;
11819 				vmdq_vecs_wanted = pf->num_vmdq_vsis;
11820 				vmdq_vecs = min_t(int,
11821 						  vectors_left,
11822 						  vmdq_vecs_wanted);
11823 			}
11824 			pf->num_vmdq_msix = pf->num_vmdq_qps;
11825 
11826 			v_budget += vmdq_vecs;
11827 			vectors_left -= vmdq_vecs;
11828 		}
11829 	}
11830 
11831 	/* On systems with a large number of SMP cores, we previously limited
11832 	 * the number of vectors for num_lan_msix to be at most 50% of the
11833 	 * available vectors, to allow for other features. Now, we add back
11834 	 * the remaining vectors. However, we ensure that the total
11835 	 * num_lan_msix will not exceed num_online_cpus(). To do this, we
11836 	 * calculate the number of vectors we can add without going over the
11837 	 * cap of CPUs. For systems with a small number of CPUs this will be
11838 	 * zero.
11839 	 */
11840 	extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11841 	pf->num_lan_msix += extra_vectors;
11842 	vectors_left -= extra_vectors;
11843 
11844 	WARN(vectors_left < 0,
11845 	     "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11846 
11847 	v_budget += pf->num_lan_msix;
11848 	pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
11849 				   GFP_KERNEL);
11850 	if (!pf->msix_entries)
11851 		return -ENOMEM;
11852 
11853 	for (i = 0; i < v_budget; i++)
11854 		pf->msix_entries[i].entry = i;
11855 	v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11856 
11857 	if (v_actual < I40E_MIN_MSIX) {
11858 		pf->flags &= ~I40E_FLAG_MSIX_ENABLED;
11859 		kfree(pf->msix_entries);
11860 		pf->msix_entries = NULL;
11861 		pci_disable_msix(pf->pdev);
11862 		return -ENODEV;
11863 
11864 	} else if (v_actual == I40E_MIN_MSIX) {
11865 		/* Adjust for minimal MSIX use */
11866 		pf->num_vmdq_vsis = 0;
11867 		pf->num_vmdq_qps = 0;
11868 		pf->num_lan_qps = 1;
11869 		pf->num_lan_msix = 1;
11870 
11871 	} else if (v_actual != v_budget) {
11872 		/* If we have limited resources, we will start with no vectors
11873 		 * for the special features and then allocate vectors to some
11874 		 * of these features based on the policy and at the end disable
11875 		 * the features that did not get any vectors.
11876 		 */
11877 		int vec;
11878 
11879 		dev_info(&pf->pdev->dev,
11880 			 "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11881 			 v_actual, v_budget);
11882 		/* reserve the misc vector */
11883 		vec = v_actual - 1;
11884 
11885 		/* Scale vector usage down */
11886 		pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11887 		pf->num_vmdq_vsis = 1;
11888 		pf->num_vmdq_qps = 1;
11889 
11890 		/* partition out the remaining vectors */
11891 		switch (vec) {
11892 		case 2:
11893 			pf->num_lan_msix = 1;
11894 			break;
11895 		case 3:
11896 			if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11897 				pf->num_lan_msix = 1;
11898 				pf->num_iwarp_msix = 1;
11899 			} else {
11900 				pf->num_lan_msix = 2;
11901 			}
11902 			break;
11903 		default:
11904 			if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11905 				pf->num_iwarp_msix = min_t(int, (vec / 3),
11906 						 iwarp_requested);
11907 				pf->num_vmdq_vsis = min_t(int, (vec / 3),
11908 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11909 			} else {
11910 				pf->num_vmdq_vsis = min_t(int, (vec / 2),
11911 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11912 			}
11913 			if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11914 				pf->num_fdsb_msix = 1;
11915 				vec--;
11916 			}
11917 			pf->num_lan_msix = min_t(int,
11918 			       (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
11919 							      pf->num_lan_msix);
11920 			pf->num_lan_qps = pf->num_lan_msix;
11921 			break;
11922 		}
11923 	}
11924 
11925 	if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
11926 	    (pf->num_fdsb_msix == 0)) {
11927 		dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
11928 		pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
11929 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11930 	}
11931 	if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
11932 	    (pf->num_vmdq_msix == 0)) {
11933 		dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
11934 		pf->flags &= ~I40E_FLAG_VMDQ_ENABLED;
11935 	}
11936 
11937 	if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
11938 	    (pf->num_iwarp_msix == 0)) {
11939 		dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
11940 		pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
11941 	}
11942 	i40e_debug(&pf->hw, I40E_DEBUG_INIT,
11943 		   "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
11944 		   pf->num_lan_msix,
11945 		   pf->num_vmdq_msix * pf->num_vmdq_vsis,
11946 		   pf->num_fdsb_msix,
11947 		   pf->num_iwarp_msix);
11948 
11949 	return v_actual;
11950 }
11951 
11952 /**
11953  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
11954  * @vsi: the VSI being configured
11955  * @v_idx: index of the vector in the vsi struct
11956  *
11957  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
11958  **/
11959 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx)
11960 {
11961 	struct i40e_q_vector *q_vector;
11962 
11963 	/* allocate q_vector */
11964 	q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
11965 	if (!q_vector)
11966 		return -ENOMEM;
11967 
11968 	q_vector->vsi = vsi;
11969 	q_vector->v_idx = v_idx;
11970 	cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
11971 
11972 	if (vsi->netdev)
11973 		netif_napi_add(vsi->netdev, &q_vector->napi, i40e_napi_poll);
11974 
11975 	/* tie q_vector and vsi together */
11976 	vsi->q_vectors[v_idx] = q_vector;
11977 
11978 	return 0;
11979 }
11980 
11981 /**
11982  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
11983  * @vsi: the VSI being configured
11984  *
11985  * We allocate one q_vector per queue interrupt.  If allocation fails we
11986  * return -ENOMEM.
11987  **/
11988 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
11989 {
11990 	struct i40e_pf *pf = vsi->back;
11991 	int err, v_idx, num_q_vectors;
11992 
11993 	/* if not MSIX, give the one vector only to the LAN VSI */
11994 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11995 		num_q_vectors = vsi->num_q_vectors;
11996 	else if (vsi == pf->vsi[pf->lan_vsi])
11997 		num_q_vectors = 1;
11998 	else
11999 		return -EINVAL;
12000 
12001 	for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
12002 		err = i40e_vsi_alloc_q_vector(vsi, v_idx);
12003 		if (err)
12004 			goto err_out;
12005 	}
12006 
12007 	return 0;
12008 
12009 err_out:
12010 	while (v_idx--)
12011 		i40e_free_q_vector(vsi, v_idx);
12012 
12013 	return err;
12014 }
12015 
12016 /**
12017  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
12018  * @pf: board private structure to initialize
12019  **/
12020 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
12021 {
12022 	int vectors = 0;
12023 	ssize_t size;
12024 
12025 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
12026 		vectors = i40e_init_msix(pf);
12027 		if (vectors < 0) {
12028 			pf->flags &= ~(I40E_FLAG_MSIX_ENABLED	|
12029 				       I40E_FLAG_IWARP_ENABLED	|
12030 				       I40E_FLAG_RSS_ENABLED	|
12031 				       I40E_FLAG_DCB_CAPABLE	|
12032 				       I40E_FLAG_DCB_ENABLED	|
12033 				       I40E_FLAG_SRIOV_ENABLED	|
12034 				       I40E_FLAG_FD_SB_ENABLED	|
12035 				       I40E_FLAG_FD_ATR_ENABLED	|
12036 				       I40E_FLAG_VMDQ_ENABLED);
12037 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
12038 
12039 			/* rework the queue expectations without MSIX */
12040 			i40e_determine_queue_usage(pf);
12041 		}
12042 	}
12043 
12044 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED) &&
12045 	    (pf->flags & I40E_FLAG_MSI_ENABLED)) {
12046 		dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
12047 		vectors = pci_enable_msi(pf->pdev);
12048 		if (vectors < 0) {
12049 			dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
12050 				 vectors);
12051 			pf->flags &= ~I40E_FLAG_MSI_ENABLED;
12052 		}
12053 		vectors = 1;  /* one MSI or Legacy vector */
12054 	}
12055 
12056 	if (!(pf->flags & (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED)))
12057 		dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
12058 
12059 	/* set up vector assignment tracking */
12060 	size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
12061 	pf->irq_pile = kzalloc(size, GFP_KERNEL);
12062 	if (!pf->irq_pile)
12063 		return -ENOMEM;
12064 
12065 	pf->irq_pile->num_entries = vectors;
12066 
12067 	/* track first vector for misc interrupts, ignore return */
12068 	(void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
12069 
12070 	return 0;
12071 }
12072 
12073 /**
12074  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
12075  * @pf: private board data structure
12076  *
12077  * Restore the interrupt scheme that was cleared when we suspended the
12078  * device. This should be called during resume to re-allocate the q_vectors
12079  * and reacquire IRQs.
12080  */
12081 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
12082 {
12083 	int err, i;
12084 
12085 	/* We cleared the MSI and MSI-X flags when disabling the old interrupt
12086 	 * scheme. We need to re-enabled them here in order to attempt to
12087 	 * re-acquire the MSI or MSI-X vectors
12088 	 */
12089 	pf->flags |= (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
12090 
12091 	err = i40e_init_interrupt_scheme(pf);
12092 	if (err)
12093 		return err;
12094 
12095 	/* Now that we've re-acquired IRQs, we need to remap the vectors and
12096 	 * rings together again.
12097 	 */
12098 	for (i = 0; i < pf->num_alloc_vsi; i++) {
12099 		if (pf->vsi[i]) {
12100 			err = i40e_vsi_alloc_q_vectors(pf->vsi[i]);
12101 			if (err)
12102 				goto err_unwind;
12103 			i40e_vsi_map_rings_to_vectors(pf->vsi[i]);
12104 		}
12105 	}
12106 
12107 	err = i40e_setup_misc_vector(pf);
12108 	if (err)
12109 		goto err_unwind;
12110 
12111 	if (pf->flags & I40E_FLAG_IWARP_ENABLED)
12112 		i40e_client_update_msix_info(pf);
12113 
12114 	return 0;
12115 
12116 err_unwind:
12117 	while (i--) {
12118 		if (pf->vsi[i])
12119 			i40e_vsi_free_q_vectors(pf->vsi[i]);
12120 	}
12121 
12122 	return err;
12123 }
12124 
12125 /**
12126  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
12127  * non queue events in recovery mode
12128  * @pf: board private structure
12129  *
12130  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
12131  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
12132  * This is handled differently than in recovery mode since no Tx/Rx resources
12133  * are being allocated.
12134  **/
12135 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
12136 {
12137 	int err;
12138 
12139 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
12140 		err = i40e_setup_misc_vector(pf);
12141 
12142 		if (err) {
12143 			dev_info(&pf->pdev->dev,
12144 				 "MSI-X misc vector request failed, error %d\n",
12145 				 err);
12146 			return err;
12147 		}
12148 	} else {
12149 		u32 flags = pf->flags & I40E_FLAG_MSI_ENABLED ? 0 : IRQF_SHARED;
12150 
12151 		err = request_irq(pf->pdev->irq, i40e_intr, flags,
12152 				  pf->int_name, pf);
12153 
12154 		if (err) {
12155 			dev_info(&pf->pdev->dev,
12156 				 "MSI/legacy misc vector request failed, error %d\n",
12157 				 err);
12158 			return err;
12159 		}
12160 		i40e_enable_misc_int_causes(pf);
12161 		i40e_irq_dynamic_enable_icr0(pf);
12162 	}
12163 
12164 	return 0;
12165 }
12166 
12167 /**
12168  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
12169  * @pf: board private structure
12170  *
12171  * This sets up the handler for MSIX 0, which is used to manage the
12172  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
12173  * when in MSI or Legacy interrupt mode.
12174  **/
12175 static int i40e_setup_misc_vector(struct i40e_pf *pf)
12176 {
12177 	struct i40e_hw *hw = &pf->hw;
12178 	int err = 0;
12179 
12180 	/* Only request the IRQ once, the first time through. */
12181 	if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
12182 		err = request_irq(pf->msix_entries[0].vector,
12183 				  i40e_intr, 0, pf->int_name, pf);
12184 		if (err) {
12185 			clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
12186 			dev_info(&pf->pdev->dev,
12187 				 "request_irq for %s failed: %d\n",
12188 				 pf->int_name, err);
12189 			return -EFAULT;
12190 		}
12191 	}
12192 
12193 	i40e_enable_misc_int_causes(pf);
12194 
12195 	/* associate no queues to the misc vector */
12196 	wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
12197 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K >> 1);
12198 
12199 	i40e_flush(hw);
12200 
12201 	i40e_irq_dynamic_enable_icr0(pf);
12202 
12203 	return err;
12204 }
12205 
12206 /**
12207  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
12208  * @vsi: Pointer to vsi structure
12209  * @seed: Buffter to store the hash keys
12210  * @lut: Buffer to store the lookup table entries
12211  * @lut_size: Size of buffer to store the lookup table entries
12212  *
12213  * Return 0 on success, negative on failure
12214  */
12215 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
12216 			   u8 *lut, u16 lut_size)
12217 {
12218 	struct i40e_pf *pf = vsi->back;
12219 	struct i40e_hw *hw = &pf->hw;
12220 	int ret = 0;
12221 
12222 	if (seed) {
12223 		ret = i40e_aq_get_rss_key(hw, vsi->id,
12224 			(struct i40e_aqc_get_set_rss_key_data *)seed);
12225 		if (ret) {
12226 			dev_info(&pf->pdev->dev,
12227 				 "Cannot get RSS key, err %pe aq_err %s\n",
12228 				 ERR_PTR(ret),
12229 				 i40e_aq_str(&pf->hw,
12230 					     pf->hw.aq.asq_last_status));
12231 			return ret;
12232 		}
12233 	}
12234 
12235 	if (lut) {
12236 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
12237 
12238 		ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
12239 		if (ret) {
12240 			dev_info(&pf->pdev->dev,
12241 				 "Cannot get RSS lut, err %pe aq_err %s\n",
12242 				 ERR_PTR(ret),
12243 				 i40e_aq_str(&pf->hw,
12244 					     pf->hw.aq.asq_last_status));
12245 			return ret;
12246 		}
12247 	}
12248 
12249 	return ret;
12250 }
12251 
12252 /**
12253  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
12254  * @vsi: Pointer to vsi structure
12255  * @seed: RSS hash seed
12256  * @lut: Lookup table
12257  * @lut_size: Lookup table size
12258  *
12259  * Returns 0 on success, negative on failure
12260  **/
12261 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
12262 			       const u8 *lut, u16 lut_size)
12263 {
12264 	struct i40e_pf *pf = vsi->back;
12265 	struct i40e_hw *hw = &pf->hw;
12266 	u16 vf_id = vsi->vf_id;
12267 	u8 i;
12268 
12269 	/* Fill out hash function seed */
12270 	if (seed) {
12271 		u32 *seed_dw = (u32 *)seed;
12272 
12273 		if (vsi->type == I40E_VSI_MAIN) {
12274 			for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12275 				wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
12276 		} else if (vsi->type == I40E_VSI_SRIOV) {
12277 			for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
12278 				wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
12279 		} else {
12280 			dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
12281 		}
12282 	}
12283 
12284 	if (lut) {
12285 		u32 *lut_dw = (u32 *)lut;
12286 
12287 		if (vsi->type == I40E_VSI_MAIN) {
12288 			if (lut_size != I40E_HLUT_ARRAY_SIZE)
12289 				return -EINVAL;
12290 			for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12291 				wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
12292 		} else if (vsi->type == I40E_VSI_SRIOV) {
12293 			if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
12294 				return -EINVAL;
12295 			for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12296 				wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
12297 		} else {
12298 			dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12299 		}
12300 	}
12301 	i40e_flush(hw);
12302 
12303 	return 0;
12304 }
12305 
12306 /**
12307  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
12308  * @vsi: Pointer to VSI structure
12309  * @seed: Buffer to store the keys
12310  * @lut: Buffer to store the lookup table entries
12311  * @lut_size: Size of buffer to store the lookup table entries
12312  *
12313  * Returns 0 on success, negative on failure
12314  */
12315 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
12316 			    u8 *lut, u16 lut_size)
12317 {
12318 	struct i40e_pf *pf = vsi->back;
12319 	struct i40e_hw *hw = &pf->hw;
12320 	u16 i;
12321 
12322 	if (seed) {
12323 		u32 *seed_dw = (u32 *)seed;
12324 
12325 		for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12326 			seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
12327 	}
12328 	if (lut) {
12329 		u32 *lut_dw = (u32 *)lut;
12330 
12331 		if (lut_size != I40E_HLUT_ARRAY_SIZE)
12332 			return -EINVAL;
12333 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12334 			lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
12335 	}
12336 
12337 	return 0;
12338 }
12339 
12340 /**
12341  * i40e_config_rss - Configure RSS keys and lut
12342  * @vsi: Pointer to VSI structure
12343  * @seed: RSS hash seed
12344  * @lut: Lookup table
12345  * @lut_size: Lookup table size
12346  *
12347  * Returns 0 on success, negative on failure
12348  */
12349 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12350 {
12351 	struct i40e_pf *pf = vsi->back;
12352 
12353 	if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12354 		return i40e_config_rss_aq(vsi, seed, lut, lut_size);
12355 	else
12356 		return i40e_config_rss_reg(vsi, seed, lut, lut_size);
12357 }
12358 
12359 /**
12360  * i40e_get_rss - Get RSS keys and lut
12361  * @vsi: Pointer to VSI structure
12362  * @seed: Buffer to store the keys
12363  * @lut: Buffer to store the lookup table entries
12364  * @lut_size: Size of buffer to store the lookup table entries
12365  *
12366  * Returns 0 on success, negative on failure
12367  */
12368 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12369 {
12370 	struct i40e_pf *pf = vsi->back;
12371 
12372 	if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12373 		return i40e_get_rss_aq(vsi, seed, lut, lut_size);
12374 	else
12375 		return i40e_get_rss_reg(vsi, seed, lut, lut_size);
12376 }
12377 
12378 /**
12379  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
12380  * @pf: Pointer to board private structure
12381  * @lut: Lookup table
12382  * @rss_table_size: Lookup table size
12383  * @rss_size: Range of queue number for hashing
12384  */
12385 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
12386 		       u16 rss_table_size, u16 rss_size)
12387 {
12388 	u16 i;
12389 
12390 	for (i = 0; i < rss_table_size; i++)
12391 		lut[i] = i % rss_size;
12392 }
12393 
12394 /**
12395  * i40e_pf_config_rss - Prepare for RSS if used
12396  * @pf: board private structure
12397  **/
12398 static int i40e_pf_config_rss(struct i40e_pf *pf)
12399 {
12400 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12401 	u8 seed[I40E_HKEY_ARRAY_SIZE];
12402 	u8 *lut;
12403 	struct i40e_hw *hw = &pf->hw;
12404 	u32 reg_val;
12405 	u64 hena;
12406 	int ret;
12407 
12408 	/* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
12409 	hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
12410 		((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
12411 	hena |= i40e_pf_get_default_rss_hena(pf);
12412 
12413 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
12414 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
12415 
12416 	/* Determine the RSS table size based on the hardware capabilities */
12417 	reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
12418 	reg_val = (pf->rss_table_size == 512) ?
12419 			(reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
12420 			(reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
12421 	i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
12422 
12423 	/* Determine the RSS size of the VSI */
12424 	if (!vsi->rss_size) {
12425 		u16 qcount;
12426 		/* If the firmware does something weird during VSI init, we
12427 		 * could end up with zero TCs. Check for that to avoid
12428 		 * divide-by-zero. It probably won't pass traffic, but it also
12429 		 * won't panic.
12430 		 */
12431 		qcount = vsi->num_queue_pairs /
12432 			 (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
12433 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12434 	}
12435 	if (!vsi->rss_size)
12436 		return -EINVAL;
12437 
12438 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
12439 	if (!lut)
12440 		return -ENOMEM;
12441 
12442 	/* Use user configured lut if there is one, otherwise use default */
12443 	if (vsi->rss_lut_user)
12444 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
12445 	else
12446 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
12447 
12448 	/* Use user configured hash key if there is one, otherwise
12449 	 * use default.
12450 	 */
12451 	if (vsi->rss_hkey_user)
12452 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
12453 	else
12454 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
12455 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
12456 	kfree(lut);
12457 
12458 	return ret;
12459 }
12460 
12461 /**
12462  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
12463  * @pf: board private structure
12464  * @queue_count: the requested queue count for rss.
12465  *
12466  * returns 0 if rss is not enabled, if enabled returns the final rss queue
12467  * count which may be different from the requested queue count.
12468  * Note: expects to be called while under rtnl_lock()
12469  **/
12470 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
12471 {
12472 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12473 	int new_rss_size;
12474 
12475 	if (!(pf->flags & I40E_FLAG_RSS_ENABLED))
12476 		return 0;
12477 
12478 	queue_count = min_t(int, queue_count, num_online_cpus());
12479 	new_rss_size = min_t(int, queue_count, pf->rss_size_max);
12480 
12481 	if (queue_count != vsi->num_queue_pairs) {
12482 		u16 qcount;
12483 
12484 		vsi->req_queue_pairs = queue_count;
12485 		i40e_prep_for_reset(pf);
12486 		if (test_bit(__I40E_IN_REMOVE, pf->state))
12487 			return pf->alloc_rss_size;
12488 
12489 		pf->alloc_rss_size = new_rss_size;
12490 
12491 		i40e_reset_and_rebuild(pf, true, true);
12492 
12493 		/* Discard the user configured hash keys and lut, if less
12494 		 * queues are enabled.
12495 		 */
12496 		if (queue_count < vsi->rss_size) {
12497 			i40e_clear_rss_config_user(vsi);
12498 			dev_dbg(&pf->pdev->dev,
12499 				"discard user configured hash keys and lut\n");
12500 		}
12501 
12502 		/* Reset vsi->rss_size, as number of enabled queues changed */
12503 		qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
12504 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12505 
12506 		i40e_pf_config_rss(pf);
12507 	}
12508 	dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
12509 		 vsi->req_queue_pairs, pf->rss_size_max);
12510 	return pf->alloc_rss_size;
12511 }
12512 
12513 /**
12514  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
12515  * @pf: board private structure
12516  **/
12517 int i40e_get_partition_bw_setting(struct i40e_pf *pf)
12518 {
12519 	bool min_valid, max_valid;
12520 	u32 max_bw, min_bw;
12521 	int status;
12522 
12523 	status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
12524 					   &min_valid, &max_valid);
12525 
12526 	if (!status) {
12527 		if (min_valid)
12528 			pf->min_bw = min_bw;
12529 		if (max_valid)
12530 			pf->max_bw = max_bw;
12531 	}
12532 
12533 	return status;
12534 }
12535 
12536 /**
12537  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
12538  * @pf: board private structure
12539  **/
12540 int i40e_set_partition_bw_setting(struct i40e_pf *pf)
12541 {
12542 	struct i40e_aqc_configure_partition_bw_data bw_data;
12543 	int status;
12544 
12545 	memset(&bw_data, 0, sizeof(bw_data));
12546 
12547 	/* Set the valid bit for this PF */
12548 	bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
12549 	bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
12550 	bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
12551 
12552 	/* Set the new bandwidths */
12553 	status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
12554 
12555 	return status;
12556 }
12557 
12558 /**
12559  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
12560  * @pf: board private structure
12561  **/
12562 int i40e_commit_partition_bw_setting(struct i40e_pf *pf)
12563 {
12564 	/* Commit temporary BW setting to permanent NVM image */
12565 	enum i40e_admin_queue_err last_aq_status;
12566 	u16 nvm_word;
12567 	int ret;
12568 
12569 	if (pf->hw.partition_id != 1) {
12570 		dev_info(&pf->pdev->dev,
12571 			 "Commit BW only works on partition 1! This is partition %d",
12572 			 pf->hw.partition_id);
12573 		ret = -EOPNOTSUPP;
12574 		goto bw_commit_out;
12575 	}
12576 
12577 	/* Acquire NVM for read access */
12578 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
12579 	last_aq_status = pf->hw.aq.asq_last_status;
12580 	if (ret) {
12581 		dev_info(&pf->pdev->dev,
12582 			 "Cannot acquire NVM for read access, err %pe aq_err %s\n",
12583 			 ERR_PTR(ret),
12584 			 i40e_aq_str(&pf->hw, last_aq_status));
12585 		goto bw_commit_out;
12586 	}
12587 
12588 	/* Read word 0x10 of NVM - SW compatibility word 1 */
12589 	ret = i40e_aq_read_nvm(&pf->hw,
12590 			       I40E_SR_NVM_CONTROL_WORD,
12591 			       0x10, sizeof(nvm_word), &nvm_word,
12592 			       false, NULL);
12593 	/* Save off last admin queue command status before releasing
12594 	 * the NVM
12595 	 */
12596 	last_aq_status = pf->hw.aq.asq_last_status;
12597 	i40e_release_nvm(&pf->hw);
12598 	if (ret) {
12599 		dev_info(&pf->pdev->dev, "NVM read error, err %pe aq_err %s\n",
12600 			 ERR_PTR(ret),
12601 			 i40e_aq_str(&pf->hw, last_aq_status));
12602 		goto bw_commit_out;
12603 	}
12604 
12605 	/* Wait a bit for NVM release to complete */
12606 	msleep(50);
12607 
12608 	/* Acquire NVM for write access */
12609 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
12610 	last_aq_status = pf->hw.aq.asq_last_status;
12611 	if (ret) {
12612 		dev_info(&pf->pdev->dev,
12613 			 "Cannot acquire NVM for write 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 	/* Write it back out unchanged to initiate update NVM,
12619 	 * which will force a write of the shadow (alt) RAM to
12620 	 * the NVM - thus storing the bandwidth values permanently.
12621 	 */
12622 	ret = i40e_aq_update_nvm(&pf->hw,
12623 				 I40E_SR_NVM_CONTROL_WORD,
12624 				 0x10, sizeof(nvm_word),
12625 				 &nvm_word, true, 0, NULL);
12626 	/* Save off last admin queue command status before releasing
12627 	 * the NVM
12628 	 */
12629 	last_aq_status = pf->hw.aq.asq_last_status;
12630 	i40e_release_nvm(&pf->hw);
12631 	if (ret)
12632 		dev_info(&pf->pdev->dev,
12633 			 "BW settings NOT SAVED, err %pe aq_err %s\n",
12634 			 ERR_PTR(ret),
12635 			 i40e_aq_str(&pf->hw, last_aq_status));
12636 bw_commit_out:
12637 
12638 	return ret;
12639 }
12640 
12641 /**
12642  * i40e_is_total_port_shutdown_enabled - read NVM and return value
12643  * if total port shutdown feature is enabled for this PF
12644  * @pf: board private structure
12645  **/
12646 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf)
12647 {
12648 #define I40E_TOTAL_PORT_SHUTDOWN_ENABLED	BIT(4)
12649 #define I40E_FEATURES_ENABLE_PTR		0x2A
12650 #define I40E_CURRENT_SETTING_PTR		0x2B
12651 #define I40E_LINK_BEHAVIOR_WORD_OFFSET		0x2D
12652 #define I40E_LINK_BEHAVIOR_WORD_LENGTH		0x1
12653 #define I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED	BIT(0)
12654 #define I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH	4
12655 	u16 sr_emp_sr_settings_ptr = 0;
12656 	u16 features_enable = 0;
12657 	u16 link_behavior = 0;
12658 	int read_status = 0;
12659 	bool ret = false;
12660 
12661 	read_status = i40e_read_nvm_word(&pf->hw,
12662 					 I40E_SR_EMP_SR_SETTINGS_PTR,
12663 					 &sr_emp_sr_settings_ptr);
12664 	if (read_status)
12665 		goto err_nvm;
12666 	read_status = i40e_read_nvm_word(&pf->hw,
12667 					 sr_emp_sr_settings_ptr +
12668 					 I40E_FEATURES_ENABLE_PTR,
12669 					 &features_enable);
12670 	if (read_status)
12671 		goto err_nvm;
12672 	if (I40E_TOTAL_PORT_SHUTDOWN_ENABLED & features_enable) {
12673 		read_status = i40e_read_nvm_module_data(&pf->hw,
12674 							I40E_SR_EMP_SR_SETTINGS_PTR,
12675 							I40E_CURRENT_SETTING_PTR,
12676 							I40E_LINK_BEHAVIOR_WORD_OFFSET,
12677 							I40E_LINK_BEHAVIOR_WORD_LENGTH,
12678 							&link_behavior);
12679 		if (read_status)
12680 			goto err_nvm;
12681 		link_behavior >>= (pf->hw.port * I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH);
12682 		ret = I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED & link_behavior;
12683 	}
12684 	return ret;
12685 
12686 err_nvm:
12687 	dev_warn(&pf->pdev->dev,
12688 		 "total-port-shutdown feature is off due to read nvm error: %pe\n",
12689 		 ERR_PTR(read_status));
12690 	return ret;
12691 }
12692 
12693 /**
12694  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
12695  * @pf: board private structure to initialize
12696  *
12697  * i40e_sw_init initializes the Adapter private data structure.
12698  * Fields are initialized based on PCI device information and
12699  * OS network device settings (MTU size).
12700  **/
12701 static int i40e_sw_init(struct i40e_pf *pf)
12702 {
12703 	int err = 0;
12704 	int size;
12705 	u16 pow;
12706 
12707 	/* Set default capability flags */
12708 	pf->flags = I40E_FLAG_RX_CSUM_ENABLED |
12709 		    I40E_FLAG_MSI_ENABLED     |
12710 		    I40E_FLAG_MSIX_ENABLED;
12711 
12712 	/* Set default ITR */
12713 	pf->rx_itr_default = I40E_ITR_RX_DEF;
12714 	pf->tx_itr_default = I40E_ITR_TX_DEF;
12715 
12716 	/* Depending on PF configurations, it is possible that the RSS
12717 	 * maximum might end up larger than the available queues
12718 	 */
12719 	pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
12720 	pf->alloc_rss_size = 1;
12721 	pf->rss_table_size = pf->hw.func_caps.rss_table_size;
12722 	pf->rss_size_max = min_t(int, pf->rss_size_max,
12723 				 pf->hw.func_caps.num_tx_qp);
12724 
12725 	/* find the next higher power-of-2 of num cpus */
12726 	pow = roundup_pow_of_two(num_online_cpus());
12727 	pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
12728 
12729 	if (pf->hw.func_caps.rss) {
12730 		pf->flags |= I40E_FLAG_RSS_ENABLED;
12731 		pf->alloc_rss_size = min_t(int, pf->rss_size_max,
12732 					   num_online_cpus());
12733 	}
12734 
12735 	/* MFP mode enabled */
12736 	if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
12737 		pf->flags |= I40E_FLAG_MFP_ENABLED;
12738 		dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
12739 		if (i40e_get_partition_bw_setting(pf)) {
12740 			dev_warn(&pf->pdev->dev,
12741 				 "Could not get partition bw settings\n");
12742 		} else {
12743 			dev_info(&pf->pdev->dev,
12744 				 "Partition BW Min = %8.8x, Max = %8.8x\n",
12745 				 pf->min_bw, pf->max_bw);
12746 
12747 			/* nudge the Tx scheduler */
12748 			i40e_set_partition_bw_setting(pf);
12749 		}
12750 	}
12751 
12752 	if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
12753 	    (pf->hw.func_caps.fd_filters_best_effort > 0)) {
12754 		pf->flags |= I40E_FLAG_FD_ATR_ENABLED;
12755 		pf->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
12756 		if (pf->flags & I40E_FLAG_MFP_ENABLED &&
12757 		    pf->hw.num_partitions > 1)
12758 			dev_info(&pf->pdev->dev,
12759 				 "Flow Director Sideband mode Disabled in MFP mode\n");
12760 		else
12761 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12762 		pf->fdir_pf_filter_count =
12763 				 pf->hw.func_caps.fd_filters_guaranteed;
12764 		pf->hw.fdir_shared_filter_count =
12765 				 pf->hw.func_caps.fd_filters_best_effort;
12766 	}
12767 
12768 	if (pf->hw.mac.type == I40E_MAC_X722) {
12769 		pf->hw_features |= (I40E_HW_RSS_AQ_CAPABLE |
12770 				    I40E_HW_128_QP_RSS_CAPABLE |
12771 				    I40E_HW_ATR_EVICT_CAPABLE |
12772 				    I40E_HW_WB_ON_ITR_CAPABLE |
12773 				    I40E_HW_MULTIPLE_TCP_UDP_RSS_PCTYPE |
12774 				    I40E_HW_NO_PCI_LINK_CHECK |
12775 				    I40E_HW_USE_SET_LLDP_MIB |
12776 				    I40E_HW_GENEVE_OFFLOAD_CAPABLE |
12777 				    I40E_HW_PTP_L4_CAPABLE |
12778 				    I40E_HW_WOL_MC_MAGIC_PKT_WAKE |
12779 				    I40E_HW_OUTER_UDP_CSUM_CAPABLE);
12780 
12781 #define I40E_FDEVICT_PCTYPE_DEFAULT 0xc03
12782 		if (rd32(&pf->hw, I40E_GLQF_FDEVICTENA(1)) !=
12783 		    I40E_FDEVICT_PCTYPE_DEFAULT) {
12784 			dev_warn(&pf->pdev->dev,
12785 				 "FD EVICT PCTYPES are not right, disable FD HW EVICT\n");
12786 			pf->hw_features &= ~I40E_HW_ATR_EVICT_CAPABLE;
12787 		}
12788 	} else if ((pf->hw.aq.api_maj_ver > 1) ||
12789 		   ((pf->hw.aq.api_maj_ver == 1) &&
12790 		    (pf->hw.aq.api_min_ver > 4))) {
12791 		/* Supported in FW API version higher than 1.4 */
12792 		pf->hw_features |= I40E_HW_GENEVE_OFFLOAD_CAPABLE;
12793 	}
12794 
12795 	/* Enable HW ATR eviction if possible */
12796 	if (pf->hw_features & I40E_HW_ATR_EVICT_CAPABLE)
12797 		pf->flags |= I40E_FLAG_HW_ATR_EVICT_ENABLED;
12798 
12799 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12800 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 33)) ||
12801 	    (pf->hw.aq.fw_maj_ver < 4))) {
12802 		pf->hw_features |= I40E_HW_RESTART_AUTONEG;
12803 		/* No DCB support  for FW < v4.33 */
12804 		pf->hw_features |= I40E_HW_NO_DCB_SUPPORT;
12805 	}
12806 
12807 	/* Disable FW LLDP if FW < v4.3 */
12808 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12809 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 3)) ||
12810 	    (pf->hw.aq.fw_maj_ver < 4)))
12811 		pf->hw_features |= I40E_HW_STOP_FW_LLDP;
12812 
12813 	/* Use the FW Set LLDP MIB API if FW > v4.40 */
12814 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12815 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver >= 40)) ||
12816 	    (pf->hw.aq.fw_maj_ver >= 5)))
12817 		pf->hw_features |= I40E_HW_USE_SET_LLDP_MIB;
12818 
12819 	/* Enable PTP L4 if FW > v6.0 */
12820 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
12821 	    pf->hw.aq.fw_maj_ver >= 6)
12822 		pf->hw_features |= I40E_HW_PTP_L4_CAPABLE;
12823 
12824 	if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
12825 		pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
12826 		pf->flags |= I40E_FLAG_VMDQ_ENABLED;
12827 		pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
12828 	}
12829 
12830 	if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
12831 		pf->flags |= I40E_FLAG_IWARP_ENABLED;
12832 		/* IWARP needs one extra vector for CQP just like MISC.*/
12833 		pf->num_iwarp_msix = (int)num_online_cpus() + 1;
12834 	}
12835 	/* Stopping FW LLDP engine is supported on XL710 and X722
12836 	 * starting from FW versions determined in i40e_init_adminq.
12837 	 * Stopping the FW LLDP engine is not supported on XL710
12838 	 * if NPAR is functioning so unset this hw flag in this case.
12839 	 */
12840 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
12841 	    pf->hw.func_caps.npar_enable &&
12842 	    (pf->hw.flags & I40E_HW_FLAG_FW_LLDP_STOPPABLE))
12843 		pf->hw.flags &= ~I40E_HW_FLAG_FW_LLDP_STOPPABLE;
12844 
12845 #ifdef CONFIG_PCI_IOV
12846 	if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
12847 		pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
12848 		pf->flags |= I40E_FLAG_SRIOV_ENABLED;
12849 		pf->num_req_vfs = min_t(int,
12850 					pf->hw.func_caps.num_vfs,
12851 					I40E_MAX_VF_COUNT);
12852 	}
12853 #endif /* CONFIG_PCI_IOV */
12854 	pf->eeprom_version = 0xDEAD;
12855 	pf->lan_veb = I40E_NO_VEB;
12856 	pf->lan_vsi = I40E_NO_VSI;
12857 
12858 	/* By default FW has this off for performance reasons */
12859 	pf->flags &= ~I40E_FLAG_VEB_STATS_ENABLED;
12860 
12861 	/* set up queue assignment tracking */
12862 	size = sizeof(struct i40e_lump_tracking)
12863 		+ (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
12864 	pf->qp_pile = kzalloc(size, GFP_KERNEL);
12865 	if (!pf->qp_pile) {
12866 		err = -ENOMEM;
12867 		goto sw_init_done;
12868 	}
12869 	pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
12870 
12871 	pf->tx_timeout_recovery_level = 1;
12872 
12873 	if (pf->hw.mac.type != I40E_MAC_X722 &&
12874 	    i40e_is_total_port_shutdown_enabled(pf)) {
12875 		/* Link down on close must be on when total port shutdown
12876 		 * is enabled for a given port
12877 		 */
12878 		pf->flags |= (I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED |
12879 			      I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED);
12880 		dev_info(&pf->pdev->dev,
12881 			 "total-port-shutdown was enabled, link-down-on-close is forced on\n");
12882 	}
12883 	mutex_init(&pf->switch_mutex);
12884 
12885 sw_init_done:
12886 	return err;
12887 }
12888 
12889 /**
12890  * i40e_set_ntuple - set the ntuple feature flag and take action
12891  * @pf: board private structure to initialize
12892  * @features: the feature set that the stack is suggesting
12893  *
12894  * returns a bool to indicate if reset needs to happen
12895  **/
12896 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12897 {
12898 	bool need_reset = false;
12899 
12900 	/* Check if Flow Director n-tuple support was enabled or disabled.  If
12901 	 * the state changed, we need to reset.
12902 	 */
12903 	if (features & NETIF_F_NTUPLE) {
12904 		/* Enable filters and mark for reset */
12905 		if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
12906 			need_reset = true;
12907 		/* enable FD_SB only if there is MSI-X vector and no cloud
12908 		 * filters exist
12909 		 */
12910 		if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12911 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12912 			pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
12913 		}
12914 	} else {
12915 		/* turn off filters, mark for reset and clear SW filter list */
12916 		if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
12917 			need_reset = true;
12918 			i40e_fdir_filter_exit(pf);
12919 		}
12920 		pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
12921 		clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12922 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
12923 
12924 		/* reset fd counters */
12925 		pf->fd_add_err = 0;
12926 		pf->fd_atr_cnt = 0;
12927 		/* if ATR was auto disabled it can be re-enabled. */
12928 		if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12929 			if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
12930 			    (I40E_DEBUG_FD & pf->hw.debug_mask))
12931 				dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12932 	}
12933 	return need_reset;
12934 }
12935 
12936 /**
12937  * i40e_clear_rss_lut - clear the rx hash lookup table
12938  * @vsi: the VSI being configured
12939  **/
12940 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12941 {
12942 	struct i40e_pf *pf = vsi->back;
12943 	struct i40e_hw *hw = &pf->hw;
12944 	u16 vf_id = vsi->vf_id;
12945 	u8 i;
12946 
12947 	if (vsi->type == I40E_VSI_MAIN) {
12948 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12949 			wr32(hw, I40E_PFQF_HLUT(i), 0);
12950 	} else if (vsi->type == I40E_VSI_SRIOV) {
12951 		for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12952 			i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12953 	} else {
12954 		dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12955 	}
12956 }
12957 
12958 /**
12959  * i40e_set_loopback - turn on/off loopback mode on underlying PF
12960  * @vsi: ptr to VSI
12961  * @ena: flag to indicate the on/off setting
12962  */
12963 static int i40e_set_loopback(struct i40e_vsi *vsi, bool ena)
12964 {
12965 	bool if_running = netif_running(vsi->netdev) &&
12966 			  !test_and_set_bit(__I40E_VSI_DOWN, vsi->state);
12967 	int ret;
12968 
12969 	if (if_running)
12970 		i40e_down(vsi);
12971 
12972 	ret = i40e_aq_set_mac_loopback(&vsi->back->hw, ena, NULL);
12973 	if (ret)
12974 		netdev_err(vsi->netdev, "Failed to toggle loopback state\n");
12975 	if (if_running)
12976 		i40e_up(vsi);
12977 
12978 	return ret;
12979 }
12980 
12981 /**
12982  * i40e_set_features - set the netdev feature flags
12983  * @netdev: ptr to the netdev being adjusted
12984  * @features: the feature set that the stack is suggesting
12985  * Note: expects to be called while under rtnl_lock()
12986  **/
12987 static int i40e_set_features(struct net_device *netdev,
12988 			     netdev_features_t features)
12989 {
12990 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12991 	struct i40e_vsi *vsi = np->vsi;
12992 	struct i40e_pf *pf = vsi->back;
12993 	bool need_reset;
12994 
12995 	if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
12996 		i40e_pf_config_rss(pf);
12997 	else if (!(features & NETIF_F_RXHASH) &&
12998 		 netdev->features & NETIF_F_RXHASH)
12999 		i40e_clear_rss_lut(vsi);
13000 
13001 	if (features & NETIF_F_HW_VLAN_CTAG_RX)
13002 		i40e_vlan_stripping_enable(vsi);
13003 	else
13004 		i40e_vlan_stripping_disable(vsi);
13005 
13006 	if (!(features & NETIF_F_HW_TC) &&
13007 	    (netdev->features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
13008 		dev_err(&pf->pdev->dev,
13009 			"Offloaded tc filters active, can't turn hw_tc_offload off");
13010 		return -EINVAL;
13011 	}
13012 
13013 	if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
13014 		i40e_del_all_macvlans(vsi);
13015 
13016 	need_reset = i40e_set_ntuple(pf, features);
13017 
13018 	if (need_reset)
13019 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13020 
13021 	if ((features ^ netdev->features) & NETIF_F_LOOPBACK)
13022 		return i40e_set_loopback(vsi, !!(features & NETIF_F_LOOPBACK));
13023 
13024 	return 0;
13025 }
13026 
13027 static int i40e_udp_tunnel_set_port(struct net_device *netdev,
13028 				    unsigned int table, unsigned int idx,
13029 				    struct udp_tunnel_info *ti)
13030 {
13031 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13032 	struct i40e_hw *hw = &np->vsi->back->hw;
13033 	u8 type, filter_index;
13034 	int ret;
13035 
13036 	type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? I40E_AQC_TUNNEL_TYPE_VXLAN :
13037 						   I40E_AQC_TUNNEL_TYPE_NGE;
13038 
13039 	ret = i40e_aq_add_udp_tunnel(hw, ntohs(ti->port), type, &filter_index,
13040 				     NULL);
13041 	if (ret) {
13042 		netdev_info(netdev, "add UDP port failed, err %pe aq_err %s\n",
13043 			    ERR_PTR(ret),
13044 			    i40e_aq_str(hw, hw->aq.asq_last_status));
13045 		return -EIO;
13046 	}
13047 
13048 	udp_tunnel_nic_set_port_priv(netdev, table, idx, filter_index);
13049 	return 0;
13050 }
13051 
13052 static int i40e_udp_tunnel_unset_port(struct net_device *netdev,
13053 				      unsigned int table, unsigned int idx,
13054 				      struct udp_tunnel_info *ti)
13055 {
13056 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13057 	struct i40e_hw *hw = &np->vsi->back->hw;
13058 	int ret;
13059 
13060 	ret = i40e_aq_del_udp_tunnel(hw, ti->hw_priv, NULL);
13061 	if (ret) {
13062 		netdev_info(netdev, "delete UDP port failed, err %pe aq_err %s\n",
13063 			    ERR_PTR(ret),
13064 			    i40e_aq_str(hw, hw->aq.asq_last_status));
13065 		return -EIO;
13066 	}
13067 
13068 	return 0;
13069 }
13070 
13071 static int i40e_get_phys_port_id(struct net_device *netdev,
13072 				 struct netdev_phys_item_id *ppid)
13073 {
13074 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13075 	struct i40e_pf *pf = np->vsi->back;
13076 	struct i40e_hw *hw = &pf->hw;
13077 
13078 	if (!(pf->hw_features & I40E_HW_PORT_ID_VALID))
13079 		return -EOPNOTSUPP;
13080 
13081 	ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
13082 	memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
13083 
13084 	return 0;
13085 }
13086 
13087 /**
13088  * i40e_ndo_fdb_add - add an entry to the hardware database
13089  * @ndm: the input from the stack
13090  * @tb: pointer to array of nladdr (unused)
13091  * @dev: the net device pointer
13092  * @addr: the MAC address entry being added
13093  * @vid: VLAN ID
13094  * @flags: instructions from stack about fdb operation
13095  * @extack: netlink extended ack, unused currently
13096  */
13097 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
13098 			    struct net_device *dev,
13099 			    const unsigned char *addr, u16 vid,
13100 			    u16 flags,
13101 			    struct netlink_ext_ack *extack)
13102 {
13103 	struct i40e_netdev_priv *np = netdev_priv(dev);
13104 	struct i40e_pf *pf = np->vsi->back;
13105 	int err = 0;
13106 
13107 	if (!(pf->flags & I40E_FLAG_SRIOV_ENABLED))
13108 		return -EOPNOTSUPP;
13109 
13110 	if (vid) {
13111 		pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
13112 		return -EINVAL;
13113 	}
13114 
13115 	/* Hardware does not support aging addresses so if a
13116 	 * ndm_state is given only allow permanent addresses
13117 	 */
13118 	if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
13119 		netdev_info(dev, "FDB only supports static addresses\n");
13120 		return -EINVAL;
13121 	}
13122 
13123 	if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
13124 		err = dev_uc_add_excl(dev, addr);
13125 	else if (is_multicast_ether_addr(addr))
13126 		err = dev_mc_add_excl(dev, addr);
13127 	else
13128 		err = -EINVAL;
13129 
13130 	/* Only return duplicate errors if NLM_F_EXCL is set */
13131 	if (err == -EEXIST && !(flags & NLM_F_EXCL))
13132 		err = 0;
13133 
13134 	return err;
13135 }
13136 
13137 /**
13138  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
13139  * @dev: the netdev being configured
13140  * @nlh: RTNL message
13141  * @flags: bridge flags
13142  * @extack: netlink extended ack
13143  *
13144  * Inserts a new hardware bridge if not already created and
13145  * enables the bridging mode requested (VEB or VEPA). If the
13146  * hardware bridge has already been inserted and the request
13147  * is to change the mode then that requires a PF reset to
13148  * allow rebuild of the components with required hardware
13149  * bridge mode enabled.
13150  *
13151  * Note: expects to be called while under rtnl_lock()
13152  **/
13153 static int i40e_ndo_bridge_setlink(struct net_device *dev,
13154 				   struct nlmsghdr *nlh,
13155 				   u16 flags,
13156 				   struct netlink_ext_ack *extack)
13157 {
13158 	struct i40e_netdev_priv *np = netdev_priv(dev);
13159 	struct i40e_vsi *vsi = np->vsi;
13160 	struct i40e_pf *pf = vsi->back;
13161 	struct i40e_veb *veb = NULL;
13162 	struct nlattr *attr, *br_spec;
13163 	int i, rem;
13164 
13165 	/* Only for PF VSI for now */
13166 	if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13167 		return -EOPNOTSUPP;
13168 
13169 	/* Find the HW bridge for PF VSI */
13170 	for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13171 		if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13172 			veb = pf->veb[i];
13173 	}
13174 
13175 	br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
13176 	if (!br_spec)
13177 		return -EINVAL;
13178 
13179 	nla_for_each_nested(attr, br_spec, rem) {
13180 		__u16 mode;
13181 
13182 		if (nla_type(attr) != IFLA_BRIDGE_MODE)
13183 			continue;
13184 
13185 		mode = nla_get_u16(attr);
13186 		if ((mode != BRIDGE_MODE_VEPA) &&
13187 		    (mode != BRIDGE_MODE_VEB))
13188 			return -EINVAL;
13189 
13190 		/* Insert a new HW bridge */
13191 		if (!veb) {
13192 			veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
13193 					     vsi->tc_config.enabled_tc);
13194 			if (veb) {
13195 				veb->bridge_mode = mode;
13196 				i40e_config_bridge_mode(veb);
13197 			} else {
13198 				/* No Bridge HW offload available */
13199 				return -ENOENT;
13200 			}
13201 			break;
13202 		} else if (mode != veb->bridge_mode) {
13203 			/* Existing HW bridge but different mode needs reset */
13204 			veb->bridge_mode = mode;
13205 			/* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
13206 			if (mode == BRIDGE_MODE_VEB)
13207 				pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
13208 			else
13209 				pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
13210 			i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13211 			break;
13212 		}
13213 	}
13214 
13215 	return 0;
13216 }
13217 
13218 /**
13219  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
13220  * @skb: skb buff
13221  * @pid: process id
13222  * @seq: RTNL message seq #
13223  * @dev: the netdev being configured
13224  * @filter_mask: unused
13225  * @nlflags: netlink flags passed in
13226  *
13227  * Return the mode in which the hardware bridge is operating in
13228  * i.e VEB or VEPA.
13229  **/
13230 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
13231 				   struct net_device *dev,
13232 				   u32 __always_unused filter_mask,
13233 				   int nlflags)
13234 {
13235 	struct i40e_netdev_priv *np = netdev_priv(dev);
13236 	struct i40e_vsi *vsi = np->vsi;
13237 	struct i40e_pf *pf = vsi->back;
13238 	struct i40e_veb *veb = NULL;
13239 	int i;
13240 
13241 	/* Only for PF VSI for now */
13242 	if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13243 		return -EOPNOTSUPP;
13244 
13245 	/* Find the HW bridge for the PF VSI */
13246 	for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13247 		if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13248 			veb = pf->veb[i];
13249 	}
13250 
13251 	if (!veb)
13252 		return 0;
13253 
13254 	return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
13255 				       0, 0, nlflags, filter_mask, NULL);
13256 }
13257 
13258 /**
13259  * i40e_features_check - Validate encapsulated packet conforms to limits
13260  * @skb: skb buff
13261  * @dev: This physical port's netdev
13262  * @features: Offload features that the stack believes apply
13263  **/
13264 static netdev_features_t i40e_features_check(struct sk_buff *skb,
13265 					     struct net_device *dev,
13266 					     netdev_features_t features)
13267 {
13268 	size_t len;
13269 
13270 	/* No point in doing any of this if neither checksum nor GSO are
13271 	 * being requested for this frame.  We can rule out both by just
13272 	 * checking for CHECKSUM_PARTIAL
13273 	 */
13274 	if (skb->ip_summed != CHECKSUM_PARTIAL)
13275 		return features;
13276 
13277 	/* We cannot support GSO if the MSS is going to be less than
13278 	 * 64 bytes.  If it is then we need to drop support for GSO.
13279 	 */
13280 	if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
13281 		features &= ~NETIF_F_GSO_MASK;
13282 
13283 	/* MACLEN can support at most 63 words */
13284 	len = skb_network_header(skb) - skb->data;
13285 	if (len & ~(63 * 2))
13286 		goto out_err;
13287 
13288 	/* IPLEN and EIPLEN can support at most 127 dwords */
13289 	len = skb_transport_header(skb) - skb_network_header(skb);
13290 	if (len & ~(127 * 4))
13291 		goto out_err;
13292 
13293 	if (skb->encapsulation) {
13294 		/* L4TUNLEN can support 127 words */
13295 		len = skb_inner_network_header(skb) - skb_transport_header(skb);
13296 		if (len & ~(127 * 2))
13297 			goto out_err;
13298 
13299 		/* IPLEN can support at most 127 dwords */
13300 		len = skb_inner_transport_header(skb) -
13301 		      skb_inner_network_header(skb);
13302 		if (len & ~(127 * 4))
13303 			goto out_err;
13304 	}
13305 
13306 	/* No need to validate L4LEN as TCP is the only protocol with a
13307 	 * flexible value and we support all possible values supported
13308 	 * by TCP, which is at most 15 dwords
13309 	 */
13310 
13311 	return features;
13312 out_err:
13313 	return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
13314 }
13315 
13316 /**
13317  * i40e_xdp_setup - add/remove an XDP program
13318  * @vsi: VSI to changed
13319  * @prog: XDP program
13320  * @extack: netlink extended ack
13321  **/
13322 static int i40e_xdp_setup(struct i40e_vsi *vsi, struct bpf_prog *prog,
13323 			  struct netlink_ext_ack *extack)
13324 {
13325 	int frame_size = i40e_max_vsi_frame_size(vsi, prog);
13326 	struct i40e_pf *pf = vsi->back;
13327 	struct bpf_prog *old_prog;
13328 	bool need_reset;
13329 	int i;
13330 
13331 	/* Don't allow frames that span over multiple buffers */
13332 	if (vsi->netdev->mtu > frame_size - I40E_PACKET_HDR_PAD) {
13333 		NL_SET_ERR_MSG_MOD(extack, "MTU too large for linear frames and XDP prog does not support frags");
13334 		return -EINVAL;
13335 	}
13336 
13337 	/* When turning XDP on->off/off->on we reset and rebuild the rings. */
13338 	need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
13339 
13340 	if (need_reset)
13341 		i40e_prep_for_reset(pf);
13342 
13343 	/* VSI shall be deleted in a moment, just return EINVAL */
13344 	if (test_bit(__I40E_IN_REMOVE, pf->state))
13345 		return -EINVAL;
13346 
13347 	old_prog = xchg(&vsi->xdp_prog, prog);
13348 
13349 	if (need_reset) {
13350 		if (!prog) {
13351 			xdp_features_clear_redirect_target(vsi->netdev);
13352 			/* Wait until ndo_xsk_wakeup completes. */
13353 			synchronize_rcu();
13354 		}
13355 		i40e_reset_and_rebuild(pf, true, true);
13356 	}
13357 
13358 	if (!i40e_enabled_xdp_vsi(vsi) && prog) {
13359 		if (i40e_realloc_rx_bi_zc(vsi, true))
13360 			return -ENOMEM;
13361 	} else if (i40e_enabled_xdp_vsi(vsi) && !prog) {
13362 		if (i40e_realloc_rx_bi_zc(vsi, false))
13363 			return -ENOMEM;
13364 	}
13365 
13366 	for (i = 0; i < vsi->num_queue_pairs; i++)
13367 		WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
13368 
13369 	if (old_prog)
13370 		bpf_prog_put(old_prog);
13371 
13372 	/* Kick start the NAPI context if there is an AF_XDP socket open
13373 	 * on that queue id. This so that receiving will start.
13374 	 */
13375 	if (need_reset && prog) {
13376 		for (i = 0; i < vsi->num_queue_pairs; i++)
13377 			if (vsi->xdp_rings[i]->xsk_pool)
13378 				(void)i40e_xsk_wakeup(vsi->netdev, i,
13379 						      XDP_WAKEUP_RX);
13380 		xdp_features_set_redirect_target(vsi->netdev, true);
13381 	}
13382 
13383 	return 0;
13384 }
13385 
13386 /**
13387  * i40e_enter_busy_conf - Enters busy config state
13388  * @vsi: vsi
13389  *
13390  * Returns 0 on success, <0 for failure.
13391  **/
13392 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
13393 {
13394 	struct i40e_pf *pf = vsi->back;
13395 	int timeout = 50;
13396 
13397 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
13398 		timeout--;
13399 		if (!timeout)
13400 			return -EBUSY;
13401 		usleep_range(1000, 2000);
13402 	}
13403 
13404 	return 0;
13405 }
13406 
13407 /**
13408  * i40e_exit_busy_conf - Exits busy config state
13409  * @vsi: vsi
13410  **/
13411 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
13412 {
13413 	struct i40e_pf *pf = vsi->back;
13414 
13415 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
13416 }
13417 
13418 /**
13419  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
13420  * @vsi: vsi
13421  * @queue_pair: queue pair
13422  **/
13423 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
13424 {
13425 	memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
13426 	       sizeof(vsi->rx_rings[queue_pair]->rx_stats));
13427 	memset(&vsi->tx_rings[queue_pair]->stats, 0,
13428 	       sizeof(vsi->tx_rings[queue_pair]->stats));
13429 	if (i40e_enabled_xdp_vsi(vsi)) {
13430 		memset(&vsi->xdp_rings[queue_pair]->stats, 0,
13431 		       sizeof(vsi->xdp_rings[queue_pair]->stats));
13432 	}
13433 }
13434 
13435 /**
13436  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
13437  * @vsi: vsi
13438  * @queue_pair: queue pair
13439  **/
13440 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
13441 {
13442 	i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
13443 	if (i40e_enabled_xdp_vsi(vsi)) {
13444 		/* Make sure that in-progress ndo_xdp_xmit calls are
13445 		 * completed.
13446 		 */
13447 		synchronize_rcu();
13448 		i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
13449 	}
13450 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13451 }
13452 
13453 /**
13454  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
13455  * @vsi: vsi
13456  * @queue_pair: queue pair
13457  * @enable: true for enable, false for disable
13458  **/
13459 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
13460 					bool enable)
13461 {
13462 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13463 	struct i40e_q_vector *q_vector = rxr->q_vector;
13464 
13465 	if (!vsi->netdev)
13466 		return;
13467 
13468 	/* All rings in a qp belong to the same qvector. */
13469 	if (q_vector->rx.ring || q_vector->tx.ring) {
13470 		if (enable)
13471 			napi_enable(&q_vector->napi);
13472 		else
13473 			napi_disable(&q_vector->napi);
13474 	}
13475 }
13476 
13477 /**
13478  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
13479  * @vsi: vsi
13480  * @queue_pair: queue pair
13481  * @enable: true for enable, false for disable
13482  *
13483  * Returns 0 on success, <0 on failure.
13484  **/
13485 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
13486 					bool enable)
13487 {
13488 	struct i40e_pf *pf = vsi->back;
13489 	int pf_q, ret = 0;
13490 
13491 	pf_q = vsi->base_queue + queue_pair;
13492 	ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
13493 				     false /*is xdp*/, enable);
13494 	if (ret) {
13495 		dev_info(&pf->pdev->dev,
13496 			 "VSI seid %d Tx ring %d %sable timeout\n",
13497 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13498 		return ret;
13499 	}
13500 
13501 	i40e_control_rx_q(pf, pf_q, enable);
13502 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
13503 	if (ret) {
13504 		dev_info(&pf->pdev->dev,
13505 			 "VSI seid %d Rx ring %d %sable timeout\n",
13506 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13507 		return ret;
13508 	}
13509 
13510 	/* Due to HW errata, on Rx disable only, the register can
13511 	 * indicate done before it really is. Needs 50ms to be sure
13512 	 */
13513 	if (!enable)
13514 		mdelay(50);
13515 
13516 	if (!i40e_enabled_xdp_vsi(vsi))
13517 		return ret;
13518 
13519 	ret = i40e_control_wait_tx_q(vsi->seid, pf,
13520 				     pf_q + vsi->alloc_queue_pairs,
13521 				     true /*is xdp*/, enable);
13522 	if (ret) {
13523 		dev_info(&pf->pdev->dev,
13524 			 "VSI seid %d XDP Tx ring %d %sable timeout\n",
13525 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13526 	}
13527 
13528 	return ret;
13529 }
13530 
13531 /**
13532  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
13533  * @vsi: vsi
13534  * @queue_pair: queue_pair
13535  **/
13536 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
13537 {
13538 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13539 	struct i40e_pf *pf = vsi->back;
13540 	struct i40e_hw *hw = &pf->hw;
13541 
13542 	/* All rings in a qp belong to the same qvector. */
13543 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
13544 		i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
13545 	else
13546 		i40e_irq_dynamic_enable_icr0(pf);
13547 
13548 	i40e_flush(hw);
13549 }
13550 
13551 /**
13552  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
13553  * @vsi: vsi
13554  * @queue_pair: queue_pair
13555  **/
13556 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
13557 {
13558 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13559 	struct i40e_pf *pf = vsi->back;
13560 	struct i40e_hw *hw = &pf->hw;
13561 
13562 	/* For simplicity, instead of removing the qp interrupt causes
13563 	 * from the interrupt linked list, we simply disable the interrupt, and
13564 	 * leave the list intact.
13565 	 *
13566 	 * All rings in a qp belong to the same qvector.
13567 	 */
13568 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
13569 		u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
13570 
13571 		wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
13572 		i40e_flush(hw);
13573 		synchronize_irq(pf->msix_entries[intpf].vector);
13574 	} else {
13575 		/* Legacy and MSI mode - this stops all interrupt handling */
13576 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
13577 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
13578 		i40e_flush(hw);
13579 		synchronize_irq(pf->pdev->irq);
13580 	}
13581 }
13582 
13583 /**
13584  * i40e_queue_pair_disable - Disables a queue pair
13585  * @vsi: vsi
13586  * @queue_pair: queue pair
13587  *
13588  * Returns 0 on success, <0 on failure.
13589  **/
13590 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
13591 {
13592 	int err;
13593 
13594 	err = i40e_enter_busy_conf(vsi);
13595 	if (err)
13596 		return err;
13597 
13598 	i40e_queue_pair_disable_irq(vsi, queue_pair);
13599 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
13600 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13601 	i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
13602 	i40e_queue_pair_clean_rings(vsi, queue_pair);
13603 	i40e_queue_pair_reset_stats(vsi, queue_pair);
13604 
13605 	return err;
13606 }
13607 
13608 /**
13609  * i40e_queue_pair_enable - Enables a queue pair
13610  * @vsi: vsi
13611  * @queue_pair: queue pair
13612  *
13613  * Returns 0 on success, <0 on failure.
13614  **/
13615 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
13616 {
13617 	int err;
13618 
13619 	err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
13620 	if (err)
13621 		return err;
13622 
13623 	if (i40e_enabled_xdp_vsi(vsi)) {
13624 		err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
13625 		if (err)
13626 			return err;
13627 	}
13628 
13629 	err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
13630 	if (err)
13631 		return err;
13632 
13633 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
13634 	i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
13635 	i40e_queue_pair_enable_irq(vsi, queue_pair);
13636 
13637 	i40e_exit_busy_conf(vsi);
13638 
13639 	return err;
13640 }
13641 
13642 /**
13643  * i40e_xdp - implements ndo_bpf for i40e
13644  * @dev: netdevice
13645  * @xdp: XDP command
13646  **/
13647 static int i40e_xdp(struct net_device *dev,
13648 		    struct netdev_bpf *xdp)
13649 {
13650 	struct i40e_netdev_priv *np = netdev_priv(dev);
13651 	struct i40e_vsi *vsi = np->vsi;
13652 
13653 	if (vsi->type != I40E_VSI_MAIN)
13654 		return -EINVAL;
13655 
13656 	switch (xdp->command) {
13657 	case XDP_SETUP_PROG:
13658 		return i40e_xdp_setup(vsi, xdp->prog, xdp->extack);
13659 	case XDP_SETUP_XSK_POOL:
13660 		return i40e_xsk_pool_setup(vsi, xdp->xsk.pool,
13661 					   xdp->xsk.queue_id);
13662 	default:
13663 		return -EINVAL;
13664 	}
13665 }
13666 
13667 static const struct net_device_ops i40e_netdev_ops = {
13668 	.ndo_open		= i40e_open,
13669 	.ndo_stop		= i40e_close,
13670 	.ndo_start_xmit		= i40e_lan_xmit_frame,
13671 	.ndo_get_stats64	= i40e_get_netdev_stats_struct,
13672 	.ndo_set_rx_mode	= i40e_set_rx_mode,
13673 	.ndo_validate_addr	= eth_validate_addr,
13674 	.ndo_set_mac_address	= i40e_set_mac,
13675 	.ndo_change_mtu		= i40e_change_mtu,
13676 	.ndo_eth_ioctl		= i40e_ioctl,
13677 	.ndo_tx_timeout		= i40e_tx_timeout,
13678 	.ndo_vlan_rx_add_vid	= i40e_vlan_rx_add_vid,
13679 	.ndo_vlan_rx_kill_vid	= i40e_vlan_rx_kill_vid,
13680 #ifdef CONFIG_NET_POLL_CONTROLLER
13681 	.ndo_poll_controller	= i40e_netpoll,
13682 #endif
13683 	.ndo_setup_tc		= __i40e_setup_tc,
13684 	.ndo_select_queue	= i40e_lan_select_queue,
13685 	.ndo_set_features	= i40e_set_features,
13686 	.ndo_set_vf_mac		= i40e_ndo_set_vf_mac,
13687 	.ndo_set_vf_vlan	= i40e_ndo_set_vf_port_vlan,
13688 	.ndo_get_vf_stats	= i40e_get_vf_stats,
13689 	.ndo_set_vf_rate	= i40e_ndo_set_vf_bw,
13690 	.ndo_get_vf_config	= i40e_ndo_get_vf_config,
13691 	.ndo_set_vf_link_state	= i40e_ndo_set_vf_link_state,
13692 	.ndo_set_vf_spoofchk	= i40e_ndo_set_vf_spoofchk,
13693 	.ndo_set_vf_trust	= i40e_ndo_set_vf_trust,
13694 	.ndo_get_phys_port_id	= i40e_get_phys_port_id,
13695 	.ndo_fdb_add		= i40e_ndo_fdb_add,
13696 	.ndo_features_check	= i40e_features_check,
13697 	.ndo_bridge_getlink	= i40e_ndo_bridge_getlink,
13698 	.ndo_bridge_setlink	= i40e_ndo_bridge_setlink,
13699 	.ndo_bpf		= i40e_xdp,
13700 	.ndo_xdp_xmit		= i40e_xdp_xmit,
13701 	.ndo_xsk_wakeup	        = i40e_xsk_wakeup,
13702 	.ndo_dfwd_add_station	= i40e_fwd_add,
13703 	.ndo_dfwd_del_station	= i40e_fwd_del,
13704 };
13705 
13706 /**
13707  * i40e_config_netdev - Setup the netdev flags
13708  * @vsi: the VSI being configured
13709  *
13710  * Returns 0 on success, negative value on failure
13711  **/
13712 static int i40e_config_netdev(struct i40e_vsi *vsi)
13713 {
13714 	struct i40e_pf *pf = vsi->back;
13715 	struct i40e_hw *hw = &pf->hw;
13716 	struct i40e_netdev_priv *np;
13717 	struct net_device *netdev;
13718 	u8 broadcast[ETH_ALEN];
13719 	u8 mac_addr[ETH_ALEN];
13720 	int etherdev_size;
13721 	netdev_features_t hw_enc_features;
13722 	netdev_features_t hw_features;
13723 
13724 	etherdev_size = sizeof(struct i40e_netdev_priv);
13725 	netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
13726 	if (!netdev)
13727 		return -ENOMEM;
13728 
13729 	vsi->netdev = netdev;
13730 	np = netdev_priv(netdev);
13731 	np->vsi = vsi;
13732 
13733 	hw_enc_features = NETIF_F_SG			|
13734 			  NETIF_F_HW_CSUM		|
13735 			  NETIF_F_HIGHDMA		|
13736 			  NETIF_F_SOFT_FEATURES		|
13737 			  NETIF_F_TSO			|
13738 			  NETIF_F_TSO_ECN		|
13739 			  NETIF_F_TSO6			|
13740 			  NETIF_F_GSO_GRE		|
13741 			  NETIF_F_GSO_GRE_CSUM		|
13742 			  NETIF_F_GSO_PARTIAL		|
13743 			  NETIF_F_GSO_IPXIP4		|
13744 			  NETIF_F_GSO_IPXIP6		|
13745 			  NETIF_F_GSO_UDP_TUNNEL	|
13746 			  NETIF_F_GSO_UDP_TUNNEL_CSUM	|
13747 			  NETIF_F_GSO_UDP_L4		|
13748 			  NETIF_F_SCTP_CRC		|
13749 			  NETIF_F_RXHASH		|
13750 			  NETIF_F_RXCSUM		|
13751 			  0;
13752 
13753 	if (!(pf->hw_features & I40E_HW_OUTER_UDP_CSUM_CAPABLE))
13754 		netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
13755 
13756 	netdev->udp_tunnel_nic_info = &pf->udp_tunnel_nic;
13757 
13758 	netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
13759 
13760 	netdev->hw_enc_features |= hw_enc_features;
13761 
13762 	/* record features VLANs can make use of */
13763 	netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
13764 
13765 #define I40E_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE |		\
13766 				   NETIF_F_GSO_GRE_CSUM |	\
13767 				   NETIF_F_GSO_IPXIP4 |		\
13768 				   NETIF_F_GSO_IPXIP6 |		\
13769 				   NETIF_F_GSO_UDP_TUNNEL |	\
13770 				   NETIF_F_GSO_UDP_TUNNEL_CSUM)
13771 
13772 	netdev->gso_partial_features = I40E_GSO_PARTIAL_FEATURES;
13773 	netdev->features |= NETIF_F_GSO_PARTIAL |
13774 			    I40E_GSO_PARTIAL_FEATURES;
13775 
13776 	netdev->mpls_features |= NETIF_F_SG;
13777 	netdev->mpls_features |= NETIF_F_HW_CSUM;
13778 	netdev->mpls_features |= NETIF_F_TSO;
13779 	netdev->mpls_features |= NETIF_F_TSO6;
13780 	netdev->mpls_features |= I40E_GSO_PARTIAL_FEATURES;
13781 
13782 	/* enable macvlan offloads */
13783 	netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
13784 
13785 	hw_features = hw_enc_features		|
13786 		      NETIF_F_HW_VLAN_CTAG_TX	|
13787 		      NETIF_F_HW_VLAN_CTAG_RX;
13788 
13789 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
13790 		hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
13791 
13792 	netdev->hw_features |= hw_features | NETIF_F_LOOPBACK;
13793 
13794 	netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
13795 	netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
13796 
13797 	netdev->features &= ~NETIF_F_HW_TC;
13798 
13799 	if (vsi->type == I40E_VSI_MAIN) {
13800 		SET_NETDEV_DEV(netdev, &pf->pdev->dev);
13801 		ether_addr_copy(mac_addr, hw->mac.perm_addr);
13802 		/* The following steps are necessary for two reasons. First,
13803 		 * some older NVM configurations load a default MAC-VLAN
13804 		 * filter that will accept any tagged packet, and we want to
13805 		 * replace this with a normal filter. Additionally, it is
13806 		 * possible our MAC address was provided by the platform using
13807 		 * Open Firmware or similar.
13808 		 *
13809 		 * Thus, we need to remove the default filter and install one
13810 		 * specific to the MAC address.
13811 		 */
13812 		i40e_rm_default_mac_filter(vsi, mac_addr);
13813 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13814 		i40e_add_mac_filter(vsi, mac_addr);
13815 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13816 
13817 		netdev->xdp_features = NETDEV_XDP_ACT_BASIC |
13818 				       NETDEV_XDP_ACT_REDIRECT |
13819 				       NETDEV_XDP_ACT_XSK_ZEROCOPY |
13820 				       NETDEV_XDP_ACT_RX_SG;
13821 		netdev->xdp_zc_max_segs = I40E_MAX_BUFFER_TXD;
13822 	} else {
13823 		/* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
13824 		 * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
13825 		 * the end, which is 4 bytes long, so force truncation of the
13826 		 * original name by IFNAMSIZ - 4
13827 		 */
13828 		snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d",
13829 			 IFNAMSIZ - 4,
13830 			 pf->vsi[pf->lan_vsi]->netdev->name);
13831 		eth_random_addr(mac_addr);
13832 
13833 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13834 		i40e_add_mac_filter(vsi, mac_addr);
13835 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13836 	}
13837 
13838 	/* Add the broadcast filter so that we initially will receive
13839 	 * broadcast packets. Note that when a new VLAN is first added the
13840 	 * driver will convert all filters marked I40E_VLAN_ANY into VLAN
13841 	 * specific filters as part of transitioning into "vlan" operation.
13842 	 * When more VLANs are added, the driver will copy each existing MAC
13843 	 * filter and add it for the new VLAN.
13844 	 *
13845 	 * Broadcast filters are handled specially by
13846 	 * i40e_sync_filters_subtask, as the driver must to set the broadcast
13847 	 * promiscuous bit instead of adding this directly as a MAC/VLAN
13848 	 * filter. The subtask will update the correct broadcast promiscuous
13849 	 * bits as VLANs become active or inactive.
13850 	 */
13851 	eth_broadcast_addr(broadcast);
13852 	spin_lock_bh(&vsi->mac_filter_hash_lock);
13853 	i40e_add_mac_filter(vsi, broadcast);
13854 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
13855 
13856 	eth_hw_addr_set(netdev, mac_addr);
13857 	ether_addr_copy(netdev->perm_addr, mac_addr);
13858 
13859 	/* i40iw_net_event() reads 16 bytes from neigh->primary_key */
13860 	netdev->neigh_priv_len = sizeof(u32) * 4;
13861 
13862 	netdev->priv_flags |= IFF_UNICAST_FLT;
13863 	netdev->priv_flags |= IFF_SUPP_NOFCS;
13864 	/* Setup netdev TC information */
13865 	i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
13866 
13867 	netdev->netdev_ops = &i40e_netdev_ops;
13868 	netdev->watchdog_timeo = 5 * HZ;
13869 	i40e_set_ethtool_ops(netdev);
13870 
13871 	/* MTU range: 68 - 9706 */
13872 	netdev->min_mtu = ETH_MIN_MTU;
13873 	netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13874 
13875 	return 0;
13876 }
13877 
13878 /**
13879  * i40e_vsi_delete - Delete a VSI from the switch
13880  * @vsi: the VSI being removed
13881  *
13882  * Returns 0 on success, negative value on failure
13883  **/
13884 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13885 {
13886 	/* remove default VSI is not allowed */
13887 	if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13888 		return;
13889 
13890 	i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13891 }
13892 
13893 /**
13894  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13895  * @vsi: the VSI being queried
13896  *
13897  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13898  **/
13899 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13900 {
13901 	struct i40e_veb *veb;
13902 	struct i40e_pf *pf = vsi->back;
13903 
13904 	/* Uplink is not a bridge so default to VEB */
13905 	if (vsi->veb_idx >= I40E_MAX_VEB)
13906 		return 1;
13907 
13908 	veb = pf->veb[vsi->veb_idx];
13909 	if (!veb) {
13910 		dev_info(&pf->pdev->dev,
13911 			 "There is no veb associated with the bridge\n");
13912 		return -ENOENT;
13913 	}
13914 
13915 	/* Uplink is a bridge in VEPA mode */
13916 	if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13917 		return 0;
13918 	} else {
13919 		/* Uplink is a bridge in VEB mode */
13920 		return 1;
13921 	}
13922 
13923 	/* VEPA is now default bridge, so return 0 */
13924 	return 0;
13925 }
13926 
13927 /**
13928  * i40e_add_vsi - Add a VSI to the switch
13929  * @vsi: the VSI being configured
13930  *
13931  * This initializes a VSI context depending on the VSI type to be added and
13932  * passes it down to the add_vsi aq command.
13933  **/
13934 static int i40e_add_vsi(struct i40e_vsi *vsi)
13935 {
13936 	int ret = -ENODEV;
13937 	struct i40e_pf *pf = vsi->back;
13938 	struct i40e_hw *hw = &pf->hw;
13939 	struct i40e_vsi_context ctxt;
13940 	struct i40e_mac_filter *f;
13941 	struct hlist_node *h;
13942 	int bkt;
13943 
13944 	u8 enabled_tc = 0x1; /* TC0 enabled */
13945 	int f_count = 0;
13946 
13947 	memset(&ctxt, 0, sizeof(ctxt));
13948 	switch (vsi->type) {
13949 	case I40E_VSI_MAIN:
13950 		/* The PF's main VSI is already setup as part of the
13951 		 * device initialization, so we'll not bother with
13952 		 * the add_vsi call, but we will retrieve the current
13953 		 * VSI context.
13954 		 */
13955 		ctxt.seid = pf->main_vsi_seid;
13956 		ctxt.pf_num = pf->hw.pf_id;
13957 		ctxt.vf_num = 0;
13958 		ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13959 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13960 		if (ret) {
13961 			dev_info(&pf->pdev->dev,
13962 				 "couldn't get PF vsi config, err %pe aq_err %s\n",
13963 				 ERR_PTR(ret),
13964 				 i40e_aq_str(&pf->hw,
13965 					     pf->hw.aq.asq_last_status));
13966 			return -ENOENT;
13967 		}
13968 		vsi->info = ctxt.info;
13969 		vsi->info.valid_sections = 0;
13970 
13971 		vsi->seid = ctxt.seid;
13972 		vsi->id = ctxt.vsi_number;
13973 
13974 		enabled_tc = i40e_pf_get_tc_map(pf);
13975 
13976 		/* Source pruning is enabled by default, so the flag is
13977 		 * negative logic - if it's set, we need to fiddle with
13978 		 * the VSI to disable source pruning.
13979 		 */
13980 		if (pf->flags & I40E_FLAG_SOURCE_PRUNING_DISABLED) {
13981 			memset(&ctxt, 0, sizeof(ctxt));
13982 			ctxt.seid = pf->main_vsi_seid;
13983 			ctxt.pf_num = pf->hw.pf_id;
13984 			ctxt.vf_num = 0;
13985 			ctxt.info.valid_sections |=
13986 				     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13987 			ctxt.info.switch_id =
13988 				   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13989 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13990 			if (ret) {
13991 				dev_info(&pf->pdev->dev,
13992 					 "update vsi failed, err %d aq_err %s\n",
13993 					 ret,
13994 					 i40e_aq_str(&pf->hw,
13995 						     pf->hw.aq.asq_last_status));
13996 				ret = -ENOENT;
13997 				goto err;
13998 			}
13999 		}
14000 
14001 		/* MFP mode setup queue map and update VSI */
14002 		if ((pf->flags & I40E_FLAG_MFP_ENABLED) &&
14003 		    !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
14004 			memset(&ctxt, 0, sizeof(ctxt));
14005 			ctxt.seid = pf->main_vsi_seid;
14006 			ctxt.pf_num = pf->hw.pf_id;
14007 			ctxt.vf_num = 0;
14008 			i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
14009 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
14010 			if (ret) {
14011 				dev_info(&pf->pdev->dev,
14012 					 "update vsi failed, err %pe aq_err %s\n",
14013 					 ERR_PTR(ret),
14014 					 i40e_aq_str(&pf->hw,
14015 						    pf->hw.aq.asq_last_status));
14016 				ret = -ENOENT;
14017 				goto err;
14018 			}
14019 			/* update the local VSI info queue map */
14020 			i40e_vsi_update_queue_map(vsi, &ctxt);
14021 			vsi->info.valid_sections = 0;
14022 		} else {
14023 			/* Default/Main VSI is only enabled for TC0
14024 			 * reconfigure it to enable all TCs that are
14025 			 * available on the port in SFP mode.
14026 			 * For MFP case the iSCSI PF would use this
14027 			 * flow to enable LAN+iSCSI TC.
14028 			 */
14029 			ret = i40e_vsi_config_tc(vsi, enabled_tc);
14030 			if (ret) {
14031 				/* Single TC condition is not fatal,
14032 				 * message and continue
14033 				 */
14034 				dev_info(&pf->pdev->dev,
14035 					 "failed to configure TCs for main VSI tc_map 0x%08x, err %pe aq_err %s\n",
14036 					 enabled_tc,
14037 					 ERR_PTR(ret),
14038 					 i40e_aq_str(&pf->hw,
14039 						    pf->hw.aq.asq_last_status));
14040 			}
14041 		}
14042 		break;
14043 
14044 	case I40E_VSI_FDIR:
14045 		ctxt.pf_num = hw->pf_id;
14046 		ctxt.vf_num = 0;
14047 		ctxt.uplink_seid = vsi->uplink_seid;
14048 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14049 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
14050 		if ((pf->flags & I40E_FLAG_VEB_MODE_ENABLED) &&
14051 		    (i40e_is_vsi_uplink_mode_veb(vsi))) {
14052 			ctxt.info.valid_sections |=
14053 			     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14054 			ctxt.info.switch_id =
14055 			   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14056 		}
14057 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14058 		break;
14059 
14060 	case I40E_VSI_VMDQ2:
14061 		ctxt.pf_num = hw->pf_id;
14062 		ctxt.vf_num = 0;
14063 		ctxt.uplink_seid = vsi->uplink_seid;
14064 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14065 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
14066 
14067 		/* This VSI is connected to VEB so the switch_id
14068 		 * should be set to zero by default.
14069 		 */
14070 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14071 			ctxt.info.valid_sections |=
14072 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14073 			ctxt.info.switch_id =
14074 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14075 		}
14076 
14077 		/* Setup the VSI tx/rx queue map for TC0 only for now */
14078 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14079 		break;
14080 
14081 	case I40E_VSI_SRIOV:
14082 		ctxt.pf_num = hw->pf_id;
14083 		ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
14084 		ctxt.uplink_seid = vsi->uplink_seid;
14085 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14086 		ctxt.flags = I40E_AQ_VSI_TYPE_VF;
14087 
14088 		/* This VSI is connected to VEB so the switch_id
14089 		 * should be set to zero by default.
14090 		 */
14091 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14092 			ctxt.info.valid_sections |=
14093 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14094 			ctxt.info.switch_id =
14095 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14096 		}
14097 
14098 		if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
14099 			ctxt.info.valid_sections |=
14100 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
14101 			ctxt.info.queueing_opt_flags |=
14102 				(I40E_AQ_VSI_QUE_OPT_TCP_ENA |
14103 				 I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
14104 		}
14105 
14106 		ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
14107 		ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
14108 		if (pf->vf[vsi->vf_id].spoofchk) {
14109 			ctxt.info.valid_sections |=
14110 				cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
14111 			ctxt.info.sec_flags |=
14112 				(I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
14113 				 I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
14114 		}
14115 		/* Setup the VSI tx/rx queue map for TC0 only for now */
14116 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14117 		break;
14118 
14119 	case I40E_VSI_IWARP:
14120 		/* send down message to iWARP */
14121 		break;
14122 
14123 	default:
14124 		return -ENODEV;
14125 	}
14126 
14127 	if (vsi->type != I40E_VSI_MAIN) {
14128 		ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
14129 		if (ret) {
14130 			dev_info(&vsi->back->pdev->dev,
14131 				 "add vsi failed, err %pe aq_err %s\n",
14132 				 ERR_PTR(ret),
14133 				 i40e_aq_str(&pf->hw,
14134 					     pf->hw.aq.asq_last_status));
14135 			ret = -ENOENT;
14136 			goto err;
14137 		}
14138 		vsi->info = ctxt.info;
14139 		vsi->info.valid_sections = 0;
14140 		vsi->seid = ctxt.seid;
14141 		vsi->id = ctxt.vsi_number;
14142 	}
14143 
14144 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14145 	vsi->active_filters = 0;
14146 	/* If macvlan filters already exist, force them to get loaded */
14147 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
14148 		f->state = I40E_FILTER_NEW;
14149 		f_count++;
14150 	}
14151 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14152 	clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
14153 
14154 	if (f_count) {
14155 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
14156 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
14157 	}
14158 
14159 	/* Update VSI BW information */
14160 	ret = i40e_vsi_get_bw_info(vsi);
14161 	if (ret) {
14162 		dev_info(&pf->pdev->dev,
14163 			 "couldn't get vsi bw info, err %pe aq_err %s\n",
14164 			 ERR_PTR(ret),
14165 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14166 		/* VSI is already added so not tearing that up */
14167 		ret = 0;
14168 	}
14169 
14170 err:
14171 	return ret;
14172 }
14173 
14174 /**
14175  * i40e_vsi_release - Delete a VSI and free its resources
14176  * @vsi: the VSI being removed
14177  *
14178  * Returns 0 on success or < 0 on error
14179  **/
14180 int i40e_vsi_release(struct i40e_vsi *vsi)
14181 {
14182 	struct i40e_mac_filter *f;
14183 	struct hlist_node *h;
14184 	struct i40e_veb *veb = NULL;
14185 	struct i40e_pf *pf;
14186 	u16 uplink_seid;
14187 	int i, n, bkt;
14188 
14189 	pf = vsi->back;
14190 
14191 	/* release of a VEB-owner or last VSI is not allowed */
14192 	if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
14193 		dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
14194 			 vsi->seid, vsi->uplink_seid);
14195 		return -ENODEV;
14196 	}
14197 	if (vsi == pf->vsi[pf->lan_vsi] &&
14198 	    !test_bit(__I40E_DOWN, pf->state)) {
14199 		dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
14200 		return -ENODEV;
14201 	}
14202 	set_bit(__I40E_VSI_RELEASING, vsi->state);
14203 	uplink_seid = vsi->uplink_seid;
14204 	if (vsi->type != I40E_VSI_SRIOV) {
14205 		if (vsi->netdev_registered) {
14206 			vsi->netdev_registered = false;
14207 			if (vsi->netdev) {
14208 				/* results in a call to i40e_close() */
14209 				unregister_netdev(vsi->netdev);
14210 			}
14211 		} else {
14212 			i40e_vsi_close(vsi);
14213 		}
14214 		i40e_vsi_disable_irq(vsi);
14215 	}
14216 
14217 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14218 
14219 	/* clear the sync flag on all filters */
14220 	if (vsi->netdev) {
14221 		__dev_uc_unsync(vsi->netdev, NULL);
14222 		__dev_mc_unsync(vsi->netdev, NULL);
14223 	}
14224 
14225 	/* make sure any remaining filters are marked for deletion */
14226 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
14227 		__i40e_del_filter(vsi, f);
14228 
14229 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14230 
14231 	i40e_sync_vsi_filters(vsi);
14232 
14233 	i40e_vsi_delete(vsi);
14234 	i40e_vsi_free_q_vectors(vsi);
14235 	if (vsi->netdev) {
14236 		free_netdev(vsi->netdev);
14237 		vsi->netdev = NULL;
14238 	}
14239 	i40e_vsi_clear_rings(vsi);
14240 	i40e_vsi_clear(vsi);
14241 
14242 	/* If this was the last thing on the VEB, except for the
14243 	 * controlling VSI, remove the VEB, which puts the controlling
14244 	 * VSI onto the next level down in the switch.
14245 	 *
14246 	 * Well, okay, there's one more exception here: don't remove
14247 	 * the orphan VEBs yet.  We'll wait for an explicit remove request
14248 	 * from up the network stack.
14249 	 */
14250 	for (n = 0, i = 0; i < pf->num_alloc_vsi; i++) {
14251 		if (pf->vsi[i] &&
14252 		    pf->vsi[i]->uplink_seid == uplink_seid &&
14253 		    (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14254 			n++;      /* count the VSIs */
14255 		}
14256 	}
14257 	for (i = 0; i < I40E_MAX_VEB; i++) {
14258 		if (!pf->veb[i])
14259 			continue;
14260 		if (pf->veb[i]->uplink_seid == uplink_seid)
14261 			n++;     /* count the VEBs */
14262 		if (pf->veb[i]->seid == uplink_seid)
14263 			veb = pf->veb[i];
14264 	}
14265 	if (n == 0 && veb && veb->uplink_seid != 0)
14266 		i40e_veb_release(veb);
14267 
14268 	return 0;
14269 }
14270 
14271 /**
14272  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
14273  * @vsi: ptr to the VSI
14274  *
14275  * This should only be called after i40e_vsi_mem_alloc() which allocates the
14276  * corresponding SW VSI structure and initializes num_queue_pairs for the
14277  * newly allocated VSI.
14278  *
14279  * Returns 0 on success or negative on failure
14280  **/
14281 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
14282 {
14283 	int ret = -ENOENT;
14284 	struct i40e_pf *pf = vsi->back;
14285 
14286 	if (vsi->q_vectors[0]) {
14287 		dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
14288 			 vsi->seid);
14289 		return -EEXIST;
14290 	}
14291 
14292 	if (vsi->base_vector) {
14293 		dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
14294 			 vsi->seid, vsi->base_vector);
14295 		return -EEXIST;
14296 	}
14297 
14298 	ret = i40e_vsi_alloc_q_vectors(vsi);
14299 	if (ret) {
14300 		dev_info(&pf->pdev->dev,
14301 			 "failed to allocate %d q_vector for VSI %d, ret=%d\n",
14302 			 vsi->num_q_vectors, vsi->seid, ret);
14303 		vsi->num_q_vectors = 0;
14304 		goto vector_setup_out;
14305 	}
14306 
14307 	/* In Legacy mode, we do not have to get any other vector since we
14308 	 * piggyback on the misc/ICR0 for queue interrupts.
14309 	*/
14310 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
14311 		return ret;
14312 	if (vsi->num_q_vectors)
14313 		vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
14314 						 vsi->num_q_vectors, vsi->idx);
14315 	if (vsi->base_vector < 0) {
14316 		dev_info(&pf->pdev->dev,
14317 			 "failed to get tracking for %d vectors for VSI %d, err=%d\n",
14318 			 vsi->num_q_vectors, vsi->seid, vsi->base_vector);
14319 		i40e_vsi_free_q_vectors(vsi);
14320 		ret = -ENOENT;
14321 		goto vector_setup_out;
14322 	}
14323 
14324 vector_setup_out:
14325 	return ret;
14326 }
14327 
14328 /**
14329  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
14330  * @vsi: pointer to the vsi.
14331  *
14332  * This re-allocates a vsi's queue resources.
14333  *
14334  * Returns pointer to the successfully allocated and configured VSI sw struct
14335  * on success, otherwise returns NULL on failure.
14336  **/
14337 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
14338 {
14339 	u16 alloc_queue_pairs;
14340 	struct i40e_pf *pf;
14341 	u8 enabled_tc;
14342 	int ret;
14343 
14344 	if (!vsi)
14345 		return NULL;
14346 
14347 	pf = vsi->back;
14348 
14349 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
14350 	i40e_vsi_clear_rings(vsi);
14351 
14352 	i40e_vsi_free_arrays(vsi, false);
14353 	i40e_set_num_rings_in_vsi(vsi);
14354 	ret = i40e_vsi_alloc_arrays(vsi, false);
14355 	if (ret)
14356 		goto err_vsi;
14357 
14358 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14359 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14360 
14361 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14362 	if (ret < 0) {
14363 		dev_info(&pf->pdev->dev,
14364 			 "failed to get tracking for %d queues for VSI %d err %d\n",
14365 			 alloc_queue_pairs, vsi->seid, ret);
14366 		goto err_vsi;
14367 	}
14368 	vsi->base_queue = ret;
14369 
14370 	/* Update the FW view of the VSI. Force a reset of TC and queue
14371 	 * layout configurations.
14372 	 */
14373 	enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
14374 	pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
14375 	pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
14376 	i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
14377 	if (vsi->type == I40E_VSI_MAIN)
14378 		i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
14379 
14380 	/* assign it some queues */
14381 	ret = i40e_alloc_rings(vsi);
14382 	if (ret)
14383 		goto err_rings;
14384 
14385 	/* map all of the rings to the q_vectors */
14386 	i40e_vsi_map_rings_to_vectors(vsi);
14387 	return vsi;
14388 
14389 err_rings:
14390 	i40e_vsi_free_q_vectors(vsi);
14391 	if (vsi->netdev_registered) {
14392 		vsi->netdev_registered = false;
14393 		unregister_netdev(vsi->netdev);
14394 		free_netdev(vsi->netdev);
14395 		vsi->netdev = NULL;
14396 	}
14397 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14398 err_vsi:
14399 	i40e_vsi_clear(vsi);
14400 	return NULL;
14401 }
14402 
14403 /**
14404  * i40e_vsi_setup - Set up a VSI by a given type
14405  * @pf: board private structure
14406  * @type: VSI type
14407  * @uplink_seid: the switch element to link to
14408  * @param1: usage depends upon VSI type. For VF types, indicates VF id
14409  *
14410  * This allocates the sw VSI structure and its queue resources, then add a VSI
14411  * to the identified VEB.
14412  *
14413  * Returns pointer to the successfully allocated and configure VSI sw struct on
14414  * success, otherwise returns NULL on failure.
14415  **/
14416 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
14417 				u16 uplink_seid, u32 param1)
14418 {
14419 	struct i40e_vsi *vsi = NULL;
14420 	struct i40e_veb *veb = NULL;
14421 	u16 alloc_queue_pairs;
14422 	int ret, i;
14423 	int v_idx;
14424 
14425 	/* The requested uplink_seid must be either
14426 	 *     - the PF's port seid
14427 	 *              no VEB is needed because this is the PF
14428 	 *              or this is a Flow Director special case VSI
14429 	 *     - seid of an existing VEB
14430 	 *     - seid of a VSI that owns an existing VEB
14431 	 *     - seid of a VSI that doesn't own a VEB
14432 	 *              a new VEB is created and the VSI becomes the owner
14433 	 *     - seid of the PF VSI, which is what creates the first VEB
14434 	 *              this is a special case of the previous
14435 	 *
14436 	 * Find which uplink_seid we were given and create a new VEB if needed
14437 	 */
14438 	for (i = 0; i < I40E_MAX_VEB; i++) {
14439 		if (pf->veb[i] && pf->veb[i]->seid == uplink_seid) {
14440 			veb = pf->veb[i];
14441 			break;
14442 		}
14443 	}
14444 
14445 	if (!veb && uplink_seid != pf->mac_seid) {
14446 
14447 		for (i = 0; i < pf->num_alloc_vsi; i++) {
14448 			if (pf->vsi[i] && pf->vsi[i]->seid == uplink_seid) {
14449 				vsi = pf->vsi[i];
14450 				break;
14451 			}
14452 		}
14453 		if (!vsi) {
14454 			dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
14455 				 uplink_seid);
14456 			return NULL;
14457 		}
14458 
14459 		if (vsi->uplink_seid == pf->mac_seid)
14460 			veb = i40e_veb_setup(pf, 0, pf->mac_seid, vsi->seid,
14461 					     vsi->tc_config.enabled_tc);
14462 		else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14463 			veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
14464 					     vsi->tc_config.enabled_tc);
14465 		if (veb) {
14466 			if (vsi->seid != pf->vsi[pf->lan_vsi]->seid) {
14467 				dev_info(&vsi->back->pdev->dev,
14468 					 "New VSI creation error, uplink seid of LAN VSI expected.\n");
14469 				return NULL;
14470 			}
14471 			/* We come up by default in VEPA mode if SRIOV is not
14472 			 * already enabled, in which case we can't force VEPA
14473 			 * mode.
14474 			 */
14475 			if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
14476 				veb->bridge_mode = BRIDGE_MODE_VEPA;
14477 				pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
14478 			}
14479 			i40e_config_bridge_mode(veb);
14480 		}
14481 		for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
14482 			if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
14483 				veb = pf->veb[i];
14484 		}
14485 		if (!veb) {
14486 			dev_info(&pf->pdev->dev, "couldn't add VEB\n");
14487 			return NULL;
14488 		}
14489 
14490 		vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14491 		uplink_seid = veb->seid;
14492 	}
14493 
14494 	/* get vsi sw struct */
14495 	v_idx = i40e_vsi_mem_alloc(pf, type);
14496 	if (v_idx < 0)
14497 		goto err_alloc;
14498 	vsi = pf->vsi[v_idx];
14499 	if (!vsi)
14500 		goto err_alloc;
14501 	vsi->type = type;
14502 	vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
14503 
14504 	if (type == I40E_VSI_MAIN)
14505 		pf->lan_vsi = v_idx;
14506 	else if (type == I40E_VSI_SRIOV)
14507 		vsi->vf_id = param1;
14508 	/* assign it some queues */
14509 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14510 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14511 
14512 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14513 	if (ret < 0) {
14514 		dev_info(&pf->pdev->dev,
14515 			 "failed to get tracking for %d queues for VSI %d err=%d\n",
14516 			 alloc_queue_pairs, vsi->seid, ret);
14517 		goto err_vsi;
14518 	}
14519 	vsi->base_queue = ret;
14520 
14521 	/* get a VSI from the hardware */
14522 	vsi->uplink_seid = uplink_seid;
14523 	ret = i40e_add_vsi(vsi);
14524 	if (ret)
14525 		goto err_vsi;
14526 
14527 	switch (vsi->type) {
14528 	/* setup the netdev if needed */
14529 	case I40E_VSI_MAIN:
14530 	case I40E_VSI_VMDQ2:
14531 		ret = i40e_config_netdev(vsi);
14532 		if (ret)
14533 			goto err_netdev;
14534 		ret = i40e_netif_set_realnum_tx_rx_queues(vsi);
14535 		if (ret)
14536 			goto err_netdev;
14537 		ret = register_netdev(vsi->netdev);
14538 		if (ret)
14539 			goto err_netdev;
14540 		vsi->netdev_registered = true;
14541 		netif_carrier_off(vsi->netdev);
14542 #ifdef CONFIG_I40E_DCB
14543 		/* Setup DCB netlink interface */
14544 		i40e_dcbnl_setup(vsi);
14545 #endif /* CONFIG_I40E_DCB */
14546 		fallthrough;
14547 	case I40E_VSI_FDIR:
14548 		/* set up vectors and rings if needed */
14549 		ret = i40e_vsi_setup_vectors(vsi);
14550 		if (ret)
14551 			goto err_msix;
14552 
14553 		ret = i40e_alloc_rings(vsi);
14554 		if (ret)
14555 			goto err_rings;
14556 
14557 		/* map all of the rings to the q_vectors */
14558 		i40e_vsi_map_rings_to_vectors(vsi);
14559 
14560 		i40e_vsi_reset_stats(vsi);
14561 		break;
14562 	default:
14563 		/* no netdev or rings for the other VSI types */
14564 		break;
14565 	}
14566 
14567 	if ((pf->hw_features & I40E_HW_RSS_AQ_CAPABLE) &&
14568 	    (vsi->type == I40E_VSI_VMDQ2)) {
14569 		ret = i40e_vsi_config_rss(vsi);
14570 	}
14571 	return vsi;
14572 
14573 err_rings:
14574 	i40e_vsi_free_q_vectors(vsi);
14575 err_msix:
14576 	if (vsi->netdev_registered) {
14577 		vsi->netdev_registered = false;
14578 		unregister_netdev(vsi->netdev);
14579 		free_netdev(vsi->netdev);
14580 		vsi->netdev = NULL;
14581 	}
14582 err_netdev:
14583 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14584 err_vsi:
14585 	i40e_vsi_clear(vsi);
14586 err_alloc:
14587 	return NULL;
14588 }
14589 
14590 /**
14591  * i40e_veb_get_bw_info - Query VEB BW information
14592  * @veb: the veb to query
14593  *
14594  * Query the Tx scheduler BW configuration data for given VEB
14595  **/
14596 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
14597 {
14598 	struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
14599 	struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
14600 	struct i40e_pf *pf = veb->pf;
14601 	struct i40e_hw *hw = &pf->hw;
14602 	u32 tc_bw_max;
14603 	int ret = 0;
14604 	int i;
14605 
14606 	ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
14607 						  &bw_data, NULL);
14608 	if (ret) {
14609 		dev_info(&pf->pdev->dev,
14610 			 "query veb bw config failed, err %pe aq_err %s\n",
14611 			 ERR_PTR(ret),
14612 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14613 		goto out;
14614 	}
14615 
14616 	ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
14617 						   &ets_data, NULL);
14618 	if (ret) {
14619 		dev_info(&pf->pdev->dev,
14620 			 "query veb bw ets config failed, err %pe aq_err %s\n",
14621 			 ERR_PTR(ret),
14622 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14623 		goto out;
14624 	}
14625 
14626 	veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
14627 	veb->bw_max_quanta = ets_data.tc_bw_max;
14628 	veb->is_abs_credits = bw_data.absolute_credits_enable;
14629 	veb->enabled_tc = ets_data.tc_valid_bits;
14630 	tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
14631 		    (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
14632 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
14633 		veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
14634 		veb->bw_tc_limit_credits[i] =
14635 					le16_to_cpu(bw_data.tc_bw_limits[i]);
14636 		veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
14637 	}
14638 
14639 out:
14640 	return ret;
14641 }
14642 
14643 /**
14644  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
14645  * @pf: board private structure
14646  *
14647  * On error: returns error code (negative)
14648  * On success: returns vsi index in PF (positive)
14649  **/
14650 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
14651 {
14652 	int ret = -ENOENT;
14653 	struct i40e_veb *veb;
14654 	int i;
14655 
14656 	/* Need to protect the allocation of switch elements at the PF level */
14657 	mutex_lock(&pf->switch_mutex);
14658 
14659 	/* VEB list may be fragmented if VEB creation/destruction has
14660 	 * been happening.  We can afford to do a quick scan to look
14661 	 * for any free slots in the list.
14662 	 *
14663 	 * find next empty veb slot, looping back around if necessary
14664 	 */
14665 	i = 0;
14666 	while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
14667 		i++;
14668 	if (i >= I40E_MAX_VEB) {
14669 		ret = -ENOMEM;
14670 		goto err_alloc_veb;  /* out of VEB slots! */
14671 	}
14672 
14673 	veb = kzalloc(sizeof(*veb), GFP_KERNEL);
14674 	if (!veb) {
14675 		ret = -ENOMEM;
14676 		goto err_alloc_veb;
14677 	}
14678 	veb->pf = pf;
14679 	veb->idx = i;
14680 	veb->enabled_tc = 1;
14681 
14682 	pf->veb[i] = veb;
14683 	ret = i;
14684 err_alloc_veb:
14685 	mutex_unlock(&pf->switch_mutex);
14686 	return ret;
14687 }
14688 
14689 /**
14690  * i40e_switch_branch_release - Delete a branch of the switch tree
14691  * @branch: where to start deleting
14692  *
14693  * This uses recursion to find the tips of the branch to be
14694  * removed, deleting until we get back to and can delete this VEB.
14695  **/
14696 static void i40e_switch_branch_release(struct i40e_veb *branch)
14697 {
14698 	struct i40e_pf *pf = branch->pf;
14699 	u16 branch_seid = branch->seid;
14700 	u16 veb_idx = branch->idx;
14701 	int i;
14702 
14703 	/* release any VEBs on this VEB - RECURSION */
14704 	for (i = 0; i < I40E_MAX_VEB; i++) {
14705 		if (!pf->veb[i])
14706 			continue;
14707 		if (pf->veb[i]->uplink_seid == branch->seid)
14708 			i40e_switch_branch_release(pf->veb[i]);
14709 	}
14710 
14711 	/* Release the VSIs on this VEB, but not the owner VSI.
14712 	 *
14713 	 * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
14714 	 *       the VEB itself, so don't use (*branch) after this loop.
14715 	 */
14716 	for (i = 0; i < pf->num_alloc_vsi; i++) {
14717 		if (!pf->vsi[i])
14718 			continue;
14719 		if (pf->vsi[i]->uplink_seid == branch_seid &&
14720 		   (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14721 			i40e_vsi_release(pf->vsi[i]);
14722 		}
14723 	}
14724 
14725 	/* There's one corner case where the VEB might not have been
14726 	 * removed, so double check it here and remove it if needed.
14727 	 * This case happens if the veb was created from the debugfs
14728 	 * commands and no VSIs were added to it.
14729 	 */
14730 	if (pf->veb[veb_idx])
14731 		i40e_veb_release(pf->veb[veb_idx]);
14732 }
14733 
14734 /**
14735  * i40e_veb_clear - remove veb struct
14736  * @veb: the veb to remove
14737  **/
14738 static void i40e_veb_clear(struct i40e_veb *veb)
14739 {
14740 	if (!veb)
14741 		return;
14742 
14743 	if (veb->pf) {
14744 		struct i40e_pf *pf = veb->pf;
14745 
14746 		mutex_lock(&pf->switch_mutex);
14747 		if (pf->veb[veb->idx] == veb)
14748 			pf->veb[veb->idx] = NULL;
14749 		mutex_unlock(&pf->switch_mutex);
14750 	}
14751 
14752 	kfree(veb);
14753 }
14754 
14755 /**
14756  * i40e_veb_release - Delete a VEB and free its resources
14757  * @veb: the VEB being removed
14758  **/
14759 void i40e_veb_release(struct i40e_veb *veb)
14760 {
14761 	struct i40e_vsi *vsi = NULL;
14762 	struct i40e_pf *pf;
14763 	int i, n = 0;
14764 
14765 	pf = veb->pf;
14766 
14767 	/* find the remaining VSI and check for extras */
14768 	for (i = 0; i < pf->num_alloc_vsi; i++) {
14769 		if (pf->vsi[i] && pf->vsi[i]->uplink_seid == veb->seid) {
14770 			n++;
14771 			vsi = pf->vsi[i];
14772 		}
14773 	}
14774 	if (n != 1) {
14775 		dev_info(&pf->pdev->dev,
14776 			 "can't remove VEB %d with %d VSIs left\n",
14777 			 veb->seid, n);
14778 		return;
14779 	}
14780 
14781 	/* move the remaining VSI to uplink veb */
14782 	vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
14783 	if (veb->uplink_seid) {
14784 		vsi->uplink_seid = veb->uplink_seid;
14785 		if (veb->uplink_seid == pf->mac_seid)
14786 			vsi->veb_idx = I40E_NO_VEB;
14787 		else
14788 			vsi->veb_idx = veb->veb_idx;
14789 	} else {
14790 		/* floating VEB */
14791 		vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
14792 		vsi->veb_idx = pf->vsi[pf->lan_vsi]->veb_idx;
14793 	}
14794 
14795 	i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14796 	i40e_veb_clear(veb);
14797 }
14798 
14799 /**
14800  * i40e_add_veb - create the VEB in the switch
14801  * @veb: the VEB to be instantiated
14802  * @vsi: the controlling VSI
14803  **/
14804 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
14805 {
14806 	struct i40e_pf *pf = veb->pf;
14807 	bool enable_stats = !!(pf->flags & I40E_FLAG_VEB_STATS_ENABLED);
14808 	int ret;
14809 
14810 	ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi->seid,
14811 			      veb->enabled_tc, false,
14812 			      &veb->seid, enable_stats, NULL);
14813 
14814 	/* get a VEB from the hardware */
14815 	if (ret) {
14816 		dev_info(&pf->pdev->dev,
14817 			 "couldn't add VEB, err %pe aq_err %s\n",
14818 			 ERR_PTR(ret),
14819 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14820 		return -EPERM;
14821 	}
14822 
14823 	/* get statistics counter */
14824 	ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
14825 					 &veb->stats_idx, NULL, NULL, NULL);
14826 	if (ret) {
14827 		dev_info(&pf->pdev->dev,
14828 			 "couldn't get VEB statistics idx, err %pe aq_err %s\n",
14829 			 ERR_PTR(ret),
14830 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14831 		return -EPERM;
14832 	}
14833 	ret = i40e_veb_get_bw_info(veb);
14834 	if (ret) {
14835 		dev_info(&pf->pdev->dev,
14836 			 "couldn't get VEB bw info, err %pe aq_err %s\n",
14837 			 ERR_PTR(ret),
14838 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14839 		i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14840 		return -ENOENT;
14841 	}
14842 
14843 	vsi->uplink_seid = veb->seid;
14844 	vsi->veb_idx = veb->idx;
14845 	vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14846 
14847 	return 0;
14848 }
14849 
14850 /**
14851  * i40e_veb_setup - Set up a VEB
14852  * @pf: board private structure
14853  * @flags: VEB setup flags
14854  * @uplink_seid: the switch element to link to
14855  * @vsi_seid: the initial VSI seid
14856  * @enabled_tc: Enabled TC bit-map
14857  *
14858  * This allocates the sw VEB structure and links it into the switch
14859  * It is possible and legal for this to be a duplicate of an already
14860  * existing VEB.  It is also possible for both uplink and vsi seids
14861  * to be zero, in order to create a floating VEB.
14862  *
14863  * Returns pointer to the successfully allocated VEB sw struct on
14864  * success, otherwise returns NULL on failure.
14865  **/
14866 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 flags,
14867 				u16 uplink_seid, u16 vsi_seid,
14868 				u8 enabled_tc)
14869 {
14870 	struct i40e_veb *veb, *uplink_veb = NULL;
14871 	int vsi_idx, veb_idx;
14872 	int ret;
14873 
14874 	/* if one seid is 0, the other must be 0 to create a floating relay */
14875 	if ((uplink_seid == 0 || vsi_seid == 0) &&
14876 	    (uplink_seid + vsi_seid != 0)) {
14877 		dev_info(&pf->pdev->dev,
14878 			 "one, not both seid's are 0: uplink=%d vsi=%d\n",
14879 			 uplink_seid, vsi_seid);
14880 		return NULL;
14881 	}
14882 
14883 	/* make sure there is such a vsi and uplink */
14884 	for (vsi_idx = 0; vsi_idx < pf->num_alloc_vsi; vsi_idx++)
14885 		if (pf->vsi[vsi_idx] && pf->vsi[vsi_idx]->seid == vsi_seid)
14886 			break;
14887 	if (vsi_idx == pf->num_alloc_vsi && vsi_seid != 0) {
14888 		dev_info(&pf->pdev->dev, "vsi seid %d not found\n",
14889 			 vsi_seid);
14890 		return NULL;
14891 	}
14892 
14893 	if (uplink_seid && uplink_seid != pf->mac_seid) {
14894 		for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
14895 			if (pf->veb[veb_idx] &&
14896 			    pf->veb[veb_idx]->seid == uplink_seid) {
14897 				uplink_veb = pf->veb[veb_idx];
14898 				break;
14899 			}
14900 		}
14901 		if (!uplink_veb) {
14902 			dev_info(&pf->pdev->dev,
14903 				 "uplink seid %d not found\n", uplink_seid);
14904 			return NULL;
14905 		}
14906 	}
14907 
14908 	/* get veb sw struct */
14909 	veb_idx = i40e_veb_mem_alloc(pf);
14910 	if (veb_idx < 0)
14911 		goto err_alloc;
14912 	veb = pf->veb[veb_idx];
14913 	veb->flags = flags;
14914 	veb->uplink_seid = uplink_seid;
14915 	veb->veb_idx = (uplink_veb ? uplink_veb->idx : I40E_NO_VEB);
14916 	veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14917 
14918 	/* create the VEB in the switch */
14919 	ret = i40e_add_veb(veb, pf->vsi[vsi_idx]);
14920 	if (ret)
14921 		goto err_veb;
14922 	if (vsi_idx == pf->lan_vsi)
14923 		pf->lan_veb = veb->idx;
14924 
14925 	return veb;
14926 
14927 err_veb:
14928 	i40e_veb_clear(veb);
14929 err_alloc:
14930 	return NULL;
14931 }
14932 
14933 /**
14934  * i40e_setup_pf_switch_element - set PF vars based on switch type
14935  * @pf: board private structure
14936  * @ele: element we are building info from
14937  * @num_reported: total number of elements
14938  * @printconfig: should we print the contents
14939  *
14940  * helper function to assist in extracting a few useful SEID values.
14941  **/
14942 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14943 				struct i40e_aqc_switch_config_element_resp *ele,
14944 				u16 num_reported, bool printconfig)
14945 {
14946 	u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14947 	u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14948 	u8 element_type = ele->element_type;
14949 	u16 seid = le16_to_cpu(ele->seid);
14950 
14951 	if (printconfig)
14952 		dev_info(&pf->pdev->dev,
14953 			 "type=%d seid=%d uplink=%d downlink=%d\n",
14954 			 element_type, seid, uplink_seid, downlink_seid);
14955 
14956 	switch (element_type) {
14957 	case I40E_SWITCH_ELEMENT_TYPE_MAC:
14958 		pf->mac_seid = seid;
14959 		break;
14960 	case I40E_SWITCH_ELEMENT_TYPE_VEB:
14961 		/* Main VEB? */
14962 		if (uplink_seid != pf->mac_seid)
14963 			break;
14964 		if (pf->lan_veb >= I40E_MAX_VEB) {
14965 			int v;
14966 
14967 			/* find existing or else empty VEB */
14968 			for (v = 0; v < I40E_MAX_VEB; v++) {
14969 				if (pf->veb[v] && (pf->veb[v]->seid == seid)) {
14970 					pf->lan_veb = v;
14971 					break;
14972 				}
14973 			}
14974 			if (pf->lan_veb >= I40E_MAX_VEB) {
14975 				v = i40e_veb_mem_alloc(pf);
14976 				if (v < 0)
14977 					break;
14978 				pf->lan_veb = v;
14979 			}
14980 		}
14981 		if (pf->lan_veb >= I40E_MAX_VEB)
14982 			break;
14983 
14984 		pf->veb[pf->lan_veb]->seid = seid;
14985 		pf->veb[pf->lan_veb]->uplink_seid = pf->mac_seid;
14986 		pf->veb[pf->lan_veb]->pf = pf;
14987 		pf->veb[pf->lan_veb]->veb_idx = I40E_NO_VEB;
14988 		break;
14989 	case I40E_SWITCH_ELEMENT_TYPE_VSI:
14990 		if (num_reported != 1)
14991 			break;
14992 		/* This is immediately after a reset so we can assume this is
14993 		 * the PF's VSI
14994 		 */
14995 		pf->mac_seid = uplink_seid;
14996 		pf->pf_seid = downlink_seid;
14997 		pf->main_vsi_seid = seid;
14998 		if (printconfig)
14999 			dev_info(&pf->pdev->dev,
15000 				 "pf_seid=%d main_vsi_seid=%d\n",
15001 				 pf->pf_seid, pf->main_vsi_seid);
15002 		break;
15003 	case I40E_SWITCH_ELEMENT_TYPE_PF:
15004 	case I40E_SWITCH_ELEMENT_TYPE_VF:
15005 	case I40E_SWITCH_ELEMENT_TYPE_EMP:
15006 	case I40E_SWITCH_ELEMENT_TYPE_BMC:
15007 	case I40E_SWITCH_ELEMENT_TYPE_PE:
15008 	case I40E_SWITCH_ELEMENT_TYPE_PA:
15009 		/* ignore these for now */
15010 		break;
15011 	default:
15012 		dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
15013 			 element_type, seid);
15014 		break;
15015 	}
15016 }
15017 
15018 /**
15019  * i40e_fetch_switch_configuration - Get switch config from firmware
15020  * @pf: board private structure
15021  * @printconfig: should we print the contents
15022  *
15023  * Get the current switch configuration from the device and
15024  * extract a few useful SEID values.
15025  **/
15026 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
15027 {
15028 	struct i40e_aqc_get_switch_config_resp *sw_config;
15029 	u16 next_seid = 0;
15030 	int ret = 0;
15031 	u8 *aq_buf;
15032 	int i;
15033 
15034 	aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
15035 	if (!aq_buf)
15036 		return -ENOMEM;
15037 
15038 	sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
15039 	do {
15040 		u16 num_reported, num_total;
15041 
15042 		ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
15043 						I40E_AQ_LARGE_BUF,
15044 						&next_seid, NULL);
15045 		if (ret) {
15046 			dev_info(&pf->pdev->dev,
15047 				 "get switch config failed err %d aq_err %s\n",
15048 				 ret,
15049 				 i40e_aq_str(&pf->hw,
15050 					     pf->hw.aq.asq_last_status));
15051 			kfree(aq_buf);
15052 			return -ENOENT;
15053 		}
15054 
15055 		num_reported = le16_to_cpu(sw_config->header.num_reported);
15056 		num_total = le16_to_cpu(sw_config->header.num_total);
15057 
15058 		if (printconfig)
15059 			dev_info(&pf->pdev->dev,
15060 				 "header: %d reported %d total\n",
15061 				 num_reported, num_total);
15062 
15063 		for (i = 0; i < num_reported; i++) {
15064 			struct i40e_aqc_switch_config_element_resp *ele =
15065 				&sw_config->element[i];
15066 
15067 			i40e_setup_pf_switch_element(pf, ele, num_reported,
15068 						     printconfig);
15069 		}
15070 	} while (next_seid != 0);
15071 
15072 	kfree(aq_buf);
15073 	return ret;
15074 }
15075 
15076 /**
15077  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
15078  * @pf: board private structure
15079  * @reinit: if the Main VSI needs to re-initialized.
15080  * @lock_acquired: indicates whether or not the lock has been acquired
15081  *
15082  * Returns 0 on success, negative value on failure
15083  **/
15084 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired)
15085 {
15086 	u16 flags = 0;
15087 	int ret;
15088 
15089 	/* find out what's out there already */
15090 	ret = i40e_fetch_switch_configuration(pf, false);
15091 	if (ret) {
15092 		dev_info(&pf->pdev->dev,
15093 			 "couldn't fetch switch config, err %pe aq_err %s\n",
15094 			 ERR_PTR(ret),
15095 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15096 		return ret;
15097 	}
15098 	i40e_pf_reset_stats(pf);
15099 
15100 	/* set the switch config bit for the whole device to
15101 	 * support limited promisc or true promisc
15102 	 * when user requests promisc. The default is limited
15103 	 * promisc.
15104 	*/
15105 
15106 	if ((pf->hw.pf_id == 0) &&
15107 	    !(pf->flags & I40E_FLAG_TRUE_PROMISC_SUPPORT)) {
15108 		flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15109 		pf->last_sw_conf_flags = flags;
15110 	}
15111 
15112 	if (pf->hw.pf_id == 0) {
15113 		u16 valid_flags;
15114 
15115 		valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15116 		ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
15117 						NULL);
15118 		if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
15119 			dev_info(&pf->pdev->dev,
15120 				 "couldn't set switch config bits, err %pe aq_err %s\n",
15121 				 ERR_PTR(ret),
15122 				 i40e_aq_str(&pf->hw,
15123 					     pf->hw.aq.asq_last_status));
15124 			/* not a fatal problem, just keep going */
15125 		}
15126 		pf->last_sw_conf_valid_flags = valid_flags;
15127 	}
15128 
15129 	/* first time setup */
15130 	if (pf->lan_vsi == I40E_NO_VSI || reinit) {
15131 		struct i40e_vsi *vsi = NULL;
15132 		u16 uplink_seid;
15133 
15134 		/* Set up the PF VSI associated with the PF's main VSI
15135 		 * that is already in the HW switch
15136 		 */
15137 		if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
15138 			uplink_seid = pf->veb[pf->lan_veb]->seid;
15139 		else
15140 			uplink_seid = pf->mac_seid;
15141 		if (pf->lan_vsi == I40E_NO_VSI)
15142 			vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN, uplink_seid, 0);
15143 		else if (reinit)
15144 			vsi = i40e_vsi_reinit_setup(pf->vsi[pf->lan_vsi]);
15145 		if (!vsi) {
15146 			dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
15147 			i40e_cloud_filter_exit(pf);
15148 			i40e_fdir_teardown(pf);
15149 			return -EAGAIN;
15150 		}
15151 	} else {
15152 		/* force a reset of TC and queue layout configurations */
15153 		u8 enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
15154 
15155 		pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
15156 		pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
15157 		i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
15158 	}
15159 	i40e_vlan_stripping_disable(pf->vsi[pf->lan_vsi]);
15160 
15161 	i40e_fdir_sb_setup(pf);
15162 
15163 	/* Setup static PF queue filter control settings */
15164 	ret = i40e_setup_pf_filter_control(pf);
15165 	if (ret) {
15166 		dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
15167 			 ret);
15168 		/* Failure here should not stop continuing other steps */
15169 	}
15170 
15171 	/* enable RSS in the HW, even for only one queue, as the stack can use
15172 	 * the hash
15173 	 */
15174 	if ((pf->flags & I40E_FLAG_RSS_ENABLED))
15175 		i40e_pf_config_rss(pf);
15176 
15177 	/* fill in link information and enable LSE reporting */
15178 	i40e_link_event(pf);
15179 
15180 	/* Initialize user-specific link properties */
15181 	pf->fc_autoneg_status = ((pf->hw.phy.link_info.an_info &
15182 				  I40E_AQ_AN_COMPLETED) ? true : false);
15183 
15184 	i40e_ptp_init(pf);
15185 
15186 	if (!lock_acquired)
15187 		rtnl_lock();
15188 
15189 	/* repopulate tunnel port filters */
15190 	udp_tunnel_nic_reset_ntf(pf->vsi[pf->lan_vsi]->netdev);
15191 
15192 	if (!lock_acquired)
15193 		rtnl_unlock();
15194 
15195 	return ret;
15196 }
15197 
15198 /**
15199  * i40e_determine_queue_usage - Work out queue distribution
15200  * @pf: board private structure
15201  **/
15202 static void i40e_determine_queue_usage(struct i40e_pf *pf)
15203 {
15204 	int queues_left;
15205 	int q_max;
15206 
15207 	pf->num_lan_qps = 0;
15208 
15209 	/* Find the max queues to be put into basic use.  We'll always be
15210 	 * using TC0, whether or not DCB is running, and TC0 will get the
15211 	 * big RSS set.
15212 	 */
15213 	queues_left = pf->hw.func_caps.num_tx_qp;
15214 
15215 	if ((queues_left == 1) ||
15216 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED)) {
15217 		/* one qp for PF, no queues for anything else */
15218 		queues_left = 0;
15219 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15220 
15221 		/* make sure all the fancies are disabled */
15222 		pf->flags &= ~(I40E_FLAG_RSS_ENABLED	|
15223 			       I40E_FLAG_IWARP_ENABLED	|
15224 			       I40E_FLAG_FD_SB_ENABLED	|
15225 			       I40E_FLAG_FD_ATR_ENABLED	|
15226 			       I40E_FLAG_DCB_CAPABLE	|
15227 			       I40E_FLAG_DCB_ENABLED	|
15228 			       I40E_FLAG_SRIOV_ENABLED	|
15229 			       I40E_FLAG_VMDQ_ENABLED);
15230 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15231 	} else if (!(pf->flags & (I40E_FLAG_RSS_ENABLED |
15232 				  I40E_FLAG_FD_SB_ENABLED |
15233 				  I40E_FLAG_FD_ATR_ENABLED |
15234 				  I40E_FLAG_DCB_CAPABLE))) {
15235 		/* one qp for PF */
15236 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15237 		queues_left -= pf->num_lan_qps;
15238 
15239 		pf->flags &= ~(I40E_FLAG_RSS_ENABLED	|
15240 			       I40E_FLAG_IWARP_ENABLED	|
15241 			       I40E_FLAG_FD_SB_ENABLED	|
15242 			       I40E_FLAG_FD_ATR_ENABLED	|
15243 			       I40E_FLAG_DCB_ENABLED	|
15244 			       I40E_FLAG_VMDQ_ENABLED);
15245 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15246 	} else {
15247 		/* Not enough queues for all TCs */
15248 		if ((pf->flags & I40E_FLAG_DCB_CAPABLE) &&
15249 		    (queues_left < I40E_MAX_TRAFFIC_CLASS)) {
15250 			pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
15251 					I40E_FLAG_DCB_ENABLED);
15252 			dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
15253 		}
15254 
15255 		/* limit lan qps to the smaller of qps, cpus or msix */
15256 		q_max = max_t(int, pf->rss_size_max, num_online_cpus());
15257 		q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
15258 		q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
15259 		pf->num_lan_qps = q_max;
15260 
15261 		queues_left -= pf->num_lan_qps;
15262 	}
15263 
15264 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15265 		if (queues_left > 1) {
15266 			queues_left -= 1; /* save 1 queue for FD */
15267 		} else {
15268 			pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
15269 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15270 			dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
15271 		}
15272 	}
15273 
15274 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15275 	    pf->num_vf_qps && pf->num_req_vfs && queues_left) {
15276 		pf->num_req_vfs = min_t(int, pf->num_req_vfs,
15277 					(queues_left / pf->num_vf_qps));
15278 		queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
15279 	}
15280 
15281 	if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
15282 	    pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
15283 		pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
15284 					  (queues_left / pf->num_vmdq_qps));
15285 		queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
15286 	}
15287 
15288 	pf->queues_left = queues_left;
15289 	dev_dbg(&pf->pdev->dev,
15290 		"qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
15291 		pf->hw.func_caps.num_tx_qp,
15292 		!!(pf->flags & I40E_FLAG_FD_SB_ENABLED),
15293 		pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
15294 		pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
15295 		queues_left);
15296 }
15297 
15298 /**
15299  * i40e_setup_pf_filter_control - Setup PF static filter control
15300  * @pf: PF to be setup
15301  *
15302  * i40e_setup_pf_filter_control sets up a PF's initial filter control
15303  * settings. If PE/FCoE are enabled then it will also set the per PF
15304  * based filter sizes required for them. It also enables Flow director,
15305  * ethertype and macvlan type filter settings for the pf.
15306  *
15307  * Returns 0 on success, negative on failure
15308  **/
15309 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
15310 {
15311 	struct i40e_filter_control_settings *settings = &pf->filter_settings;
15312 
15313 	settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
15314 
15315 	/* Flow Director is enabled */
15316 	if (pf->flags & (I40E_FLAG_FD_SB_ENABLED | I40E_FLAG_FD_ATR_ENABLED))
15317 		settings->enable_fdir = true;
15318 
15319 	/* Ethtype and MACVLAN filters enabled for PF */
15320 	settings->enable_ethtype = true;
15321 	settings->enable_macvlan = true;
15322 
15323 	if (i40e_set_filter_control(&pf->hw, settings))
15324 		return -ENOENT;
15325 
15326 	return 0;
15327 }
15328 
15329 #define INFO_STRING_LEN 255
15330 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
15331 static void i40e_print_features(struct i40e_pf *pf)
15332 {
15333 	struct i40e_hw *hw = &pf->hw;
15334 	char *buf;
15335 	int i;
15336 
15337 	buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
15338 	if (!buf)
15339 		return;
15340 
15341 	i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
15342 #ifdef CONFIG_PCI_IOV
15343 	i += scnprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
15344 #endif
15345 	i += scnprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
15346 		      pf->hw.func_caps.num_vsis,
15347 		      pf->vsi[pf->lan_vsi]->num_queue_pairs);
15348 	if (pf->flags & I40E_FLAG_RSS_ENABLED)
15349 		i += scnprintf(&buf[i], REMAIN(i), " RSS");
15350 	if (pf->flags & I40E_FLAG_FD_ATR_ENABLED)
15351 		i += scnprintf(&buf[i], REMAIN(i), " FD_ATR");
15352 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15353 		i += scnprintf(&buf[i], REMAIN(i), " FD_SB");
15354 		i += scnprintf(&buf[i], REMAIN(i), " NTUPLE");
15355 	}
15356 	if (pf->flags & I40E_FLAG_DCB_CAPABLE)
15357 		i += scnprintf(&buf[i], REMAIN(i), " DCB");
15358 	i += scnprintf(&buf[i], REMAIN(i), " VxLAN");
15359 	i += scnprintf(&buf[i], REMAIN(i), " Geneve");
15360 	if (pf->flags & I40E_FLAG_PTP)
15361 		i += scnprintf(&buf[i], REMAIN(i), " PTP");
15362 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
15363 		i += scnprintf(&buf[i], REMAIN(i), " VEB");
15364 	else
15365 		i += scnprintf(&buf[i], REMAIN(i), " VEPA");
15366 
15367 	dev_info(&pf->pdev->dev, "%s\n", buf);
15368 	kfree(buf);
15369 	WARN_ON(i > INFO_STRING_LEN);
15370 }
15371 
15372 /**
15373  * i40e_get_platform_mac_addr - get platform-specific MAC address
15374  * @pdev: PCI device information struct
15375  * @pf: board private structure
15376  *
15377  * Look up the MAC address for the device. First we'll try
15378  * eth_platform_get_mac_address, which will check Open Firmware, or arch
15379  * specific fallback. Otherwise, we'll default to the stored value in
15380  * firmware.
15381  **/
15382 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
15383 {
15384 	if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
15385 		i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
15386 }
15387 
15388 /**
15389  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
15390  * @fec_cfg: FEC option to set in flags
15391  * @flags: ptr to flags in which we set FEC option
15392  **/
15393 void i40e_set_fec_in_flags(u8 fec_cfg, u32 *flags)
15394 {
15395 	if (fec_cfg & I40E_AQ_SET_FEC_AUTO)
15396 		*flags |= I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC;
15397 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
15398 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
15399 		*flags |= I40E_FLAG_RS_FEC;
15400 		*flags &= ~I40E_FLAG_BASE_R_FEC;
15401 	}
15402 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
15403 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
15404 		*flags |= I40E_FLAG_BASE_R_FEC;
15405 		*flags &= ~I40E_FLAG_RS_FEC;
15406 	}
15407 	if (fec_cfg == 0)
15408 		*flags &= ~(I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC);
15409 }
15410 
15411 /**
15412  * i40e_check_recovery_mode - check if we are running transition firmware
15413  * @pf: board private structure
15414  *
15415  * Check registers indicating the firmware runs in recovery mode. Sets the
15416  * appropriate driver state.
15417  *
15418  * Returns true if the recovery mode was detected, false otherwise
15419  **/
15420 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
15421 {
15422 	u32 val = rd32(&pf->hw, I40E_GL_FWSTS);
15423 
15424 	if (val & I40E_GL_FWSTS_FWS1B_MASK) {
15425 		dev_crit(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
15426 		dev_crit(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
15427 		set_bit(__I40E_RECOVERY_MODE, pf->state);
15428 
15429 		return true;
15430 	}
15431 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15432 		dev_info(&pf->pdev->dev, "Please do Power-On Reset to initialize adapter in normal mode with full functionality.\n");
15433 
15434 	return false;
15435 }
15436 
15437 /**
15438  * i40e_pf_loop_reset - perform reset in a loop.
15439  * @pf: board private structure
15440  *
15441  * This function is useful when a NIC is about to enter recovery mode.
15442  * When a NIC's internal data structures are corrupted the NIC's
15443  * firmware is going to enter recovery mode.
15444  * Right after a POR it takes about 7 minutes for firmware to enter
15445  * recovery mode. Until that time a NIC is in some kind of intermediate
15446  * state. After that time period the NIC almost surely enters
15447  * recovery mode. The only way for a driver to detect intermediate
15448  * state is to issue a series of pf-resets and check a return value.
15449  * If a PF reset returns success then the firmware could be in recovery
15450  * mode so the caller of this code needs to check for recovery mode
15451  * if this function returns success. There is a little chance that
15452  * firmware will hang in intermediate state forever.
15453  * Since waiting 7 minutes is quite a lot of time this function waits
15454  * 10 seconds and then gives up by returning an error.
15455  *
15456  * Return 0 on success, negative on failure.
15457  **/
15458 static int i40e_pf_loop_reset(struct i40e_pf *pf)
15459 {
15460 	/* wait max 10 seconds for PF reset to succeed */
15461 	const unsigned long time_end = jiffies + 10 * HZ;
15462 	struct i40e_hw *hw = &pf->hw;
15463 	int ret;
15464 
15465 	ret = i40e_pf_reset(hw);
15466 	while (ret != 0 && time_before(jiffies, time_end)) {
15467 		usleep_range(10000, 20000);
15468 		ret = i40e_pf_reset(hw);
15469 	}
15470 
15471 	if (ret == 0)
15472 		pf->pfr_count++;
15473 	else
15474 		dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
15475 
15476 	return ret;
15477 }
15478 
15479 /**
15480  * i40e_check_fw_empr - check if FW issued unexpected EMP Reset
15481  * @pf: board private structure
15482  *
15483  * Check FW registers to determine if FW issued unexpected EMP Reset.
15484  * Every time when unexpected EMP Reset occurs the FW increments
15485  * a counter of unexpected EMP Resets. When the counter reaches 10
15486  * the FW should enter the Recovery mode
15487  *
15488  * Returns true if FW issued unexpected EMP Reset
15489  **/
15490 static bool i40e_check_fw_empr(struct i40e_pf *pf)
15491 {
15492 	const u32 fw_sts = rd32(&pf->hw, I40E_GL_FWSTS) &
15493 			   I40E_GL_FWSTS_FWS1B_MASK;
15494 	return (fw_sts > I40E_GL_FWSTS_FWS1B_EMPR_0) &&
15495 	       (fw_sts <= I40E_GL_FWSTS_FWS1B_EMPR_10);
15496 }
15497 
15498 /**
15499  * i40e_handle_resets - handle EMP resets and PF resets
15500  * @pf: board private structure
15501  *
15502  * Handle both EMP resets and PF resets and conclude whether there are
15503  * any issues regarding these resets. If there are any issues then
15504  * generate log entry.
15505  *
15506  * Return 0 if NIC is healthy or negative value when there are issues
15507  * with resets
15508  **/
15509 static int i40e_handle_resets(struct i40e_pf *pf)
15510 {
15511 	const int pfr = i40e_pf_loop_reset(pf);
15512 	const bool is_empr = i40e_check_fw_empr(pf);
15513 
15514 	if (is_empr || pfr != 0)
15515 		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");
15516 
15517 	return is_empr ? -EIO : pfr;
15518 }
15519 
15520 /**
15521  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
15522  * @pf: board private structure
15523  * @hw: ptr to the hardware info
15524  *
15525  * This function does a minimal setup of all subsystems needed for running
15526  * recovery mode.
15527  *
15528  * Returns 0 on success, negative on failure
15529  **/
15530 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
15531 {
15532 	struct i40e_vsi *vsi;
15533 	int err;
15534 	int v_idx;
15535 
15536 	pci_set_drvdata(pf->pdev, pf);
15537 	pci_save_state(pf->pdev);
15538 
15539 	/* set up periodic task facility */
15540 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15541 	pf->service_timer_period = HZ;
15542 
15543 	INIT_WORK(&pf->service_task, i40e_service_task);
15544 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15545 
15546 	err = i40e_init_interrupt_scheme(pf);
15547 	if (err)
15548 		goto err_switch_setup;
15549 
15550 	/* The number of VSIs reported by the FW is the minimum guaranteed
15551 	 * to us; HW supports far more and we share the remaining pool with
15552 	 * the other PFs. We allocate space for more than the guarantee with
15553 	 * the understanding that we might not get them all later.
15554 	 */
15555 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15556 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15557 	else
15558 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15559 
15560 	/* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
15561 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15562 			  GFP_KERNEL);
15563 	if (!pf->vsi) {
15564 		err = -ENOMEM;
15565 		goto err_switch_setup;
15566 	}
15567 
15568 	/* We allocate one VSI which is needed as absolute minimum
15569 	 * in order to register the netdev
15570 	 */
15571 	v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
15572 	if (v_idx < 0) {
15573 		err = v_idx;
15574 		goto err_switch_setup;
15575 	}
15576 	pf->lan_vsi = v_idx;
15577 	vsi = pf->vsi[v_idx];
15578 	if (!vsi) {
15579 		err = -EFAULT;
15580 		goto err_switch_setup;
15581 	}
15582 	vsi->alloc_queue_pairs = 1;
15583 	err = i40e_config_netdev(vsi);
15584 	if (err)
15585 		goto err_switch_setup;
15586 	err = register_netdev(vsi->netdev);
15587 	if (err)
15588 		goto err_switch_setup;
15589 	vsi->netdev_registered = true;
15590 	i40e_dbg_pf_init(pf);
15591 
15592 	err = i40e_setup_misc_vector_for_recovery_mode(pf);
15593 	if (err)
15594 		goto err_switch_setup;
15595 
15596 	/* tell the firmware that we're starting */
15597 	i40e_send_version(pf);
15598 
15599 	/* since everything's happy, start the service_task timer */
15600 	mod_timer(&pf->service_timer,
15601 		  round_jiffies(jiffies + pf->service_timer_period));
15602 
15603 	return 0;
15604 
15605 err_switch_setup:
15606 	i40e_reset_interrupt_capability(pf);
15607 	timer_shutdown_sync(&pf->service_timer);
15608 	i40e_shutdown_adminq(hw);
15609 	iounmap(hw->hw_addr);
15610 	pci_release_mem_regions(pf->pdev);
15611 	pci_disable_device(pf->pdev);
15612 	kfree(pf);
15613 
15614 	return err;
15615 }
15616 
15617 /**
15618  * i40e_set_subsystem_device_id - set subsystem device id
15619  * @hw: pointer to the hardware info
15620  *
15621  * Set PCI subsystem device id either from a pci_dev structure or
15622  * a specific FW register.
15623  **/
15624 static inline void i40e_set_subsystem_device_id(struct i40e_hw *hw)
15625 {
15626 	struct pci_dev *pdev = ((struct i40e_pf *)hw->back)->pdev;
15627 
15628 	hw->subsystem_device_id = pdev->subsystem_device ?
15629 		pdev->subsystem_device :
15630 		(ushort)(rd32(hw, I40E_PFPCI_SUBSYSID) & USHRT_MAX);
15631 }
15632 
15633 /**
15634  * i40e_probe - Device initialization routine
15635  * @pdev: PCI device information struct
15636  * @ent: entry in i40e_pci_tbl
15637  *
15638  * i40e_probe initializes a PF identified by a pci_dev structure.
15639  * The OS initialization, configuring of the PF private structure,
15640  * and a hardware reset occur.
15641  *
15642  * Returns 0 on success, negative on failure
15643  **/
15644 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
15645 {
15646 	struct i40e_aq_get_phy_abilities_resp abilities;
15647 #ifdef CONFIG_I40E_DCB
15648 	enum i40e_get_fw_lldp_status_resp lldp_status;
15649 #endif /* CONFIG_I40E_DCB */
15650 	struct i40e_pf *pf;
15651 	struct i40e_hw *hw;
15652 	static u16 pfs_found;
15653 	u16 wol_nvm_bits;
15654 	u16 link_status;
15655 #ifdef CONFIG_I40E_DCB
15656 	int status;
15657 #endif /* CONFIG_I40E_DCB */
15658 	int err;
15659 	u32 val;
15660 	u32 i;
15661 
15662 	err = pci_enable_device_mem(pdev);
15663 	if (err)
15664 		return err;
15665 
15666 	/* set up for high or low dma */
15667 	err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
15668 	if (err) {
15669 		dev_err(&pdev->dev,
15670 			"DMA configuration failed: 0x%x\n", err);
15671 		goto err_dma;
15672 	}
15673 
15674 	/* set up pci connections */
15675 	err = pci_request_mem_regions(pdev, i40e_driver_name);
15676 	if (err) {
15677 		dev_info(&pdev->dev,
15678 			 "pci_request_selected_regions failed %d\n", err);
15679 		goto err_pci_reg;
15680 	}
15681 
15682 	pci_set_master(pdev);
15683 
15684 	/* Now that we have a PCI connection, we need to do the
15685 	 * low level device setup.  This is primarily setting up
15686 	 * the Admin Queue structures and then querying for the
15687 	 * device's current profile information.
15688 	 */
15689 	pf = kzalloc(sizeof(*pf), GFP_KERNEL);
15690 	if (!pf) {
15691 		err = -ENOMEM;
15692 		goto err_pf_alloc;
15693 	}
15694 	pf->next_vsi = 0;
15695 	pf->pdev = pdev;
15696 	set_bit(__I40E_DOWN, pf->state);
15697 
15698 	hw = &pf->hw;
15699 	hw->back = pf;
15700 
15701 	pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
15702 				I40E_MAX_CSR_SPACE);
15703 	/* We believe that the highest register to read is
15704 	 * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
15705 	 * is not less than that before mapping to prevent a
15706 	 * kernel panic.
15707 	 */
15708 	if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
15709 		dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
15710 			pf->ioremap_len);
15711 		err = -ENOMEM;
15712 		goto err_ioremap;
15713 	}
15714 	hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
15715 	if (!hw->hw_addr) {
15716 		err = -EIO;
15717 		dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
15718 			 (unsigned int)pci_resource_start(pdev, 0),
15719 			 pf->ioremap_len, err);
15720 		goto err_ioremap;
15721 	}
15722 	hw->vendor_id = pdev->vendor;
15723 	hw->device_id = pdev->device;
15724 	pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
15725 	hw->subsystem_vendor_id = pdev->subsystem_vendor;
15726 	i40e_set_subsystem_device_id(hw);
15727 	hw->bus.device = PCI_SLOT(pdev->devfn);
15728 	hw->bus.func = PCI_FUNC(pdev->devfn);
15729 	hw->bus.bus_id = pdev->bus->number;
15730 	pf->instance = pfs_found;
15731 
15732 	/* Select something other than the 802.1ad ethertype for the
15733 	 * switch to use internally and drop on ingress.
15734 	 */
15735 	hw->switch_tag = 0xffff;
15736 	hw->first_tag = ETH_P_8021AD;
15737 	hw->second_tag = ETH_P_8021Q;
15738 
15739 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
15740 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
15741 	INIT_LIST_HEAD(&pf->ddp_old_prof);
15742 
15743 	/* set up the locks for the AQ, do this only once in probe
15744 	 * and destroy them only once in remove
15745 	 */
15746 	mutex_init(&hw->aq.asq_mutex);
15747 	mutex_init(&hw->aq.arq_mutex);
15748 
15749 	pf->msg_enable = netif_msg_init(debug,
15750 					NETIF_MSG_DRV |
15751 					NETIF_MSG_PROBE |
15752 					NETIF_MSG_LINK);
15753 	if (debug < -1)
15754 		pf->hw.debug_mask = debug;
15755 
15756 	/* do a special CORER for clearing PXE mode once at init */
15757 	if (hw->revision_id == 0 &&
15758 	    (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
15759 		wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
15760 		i40e_flush(hw);
15761 		msleep(200);
15762 		pf->corer_count++;
15763 
15764 		i40e_clear_pxe_mode(hw);
15765 	}
15766 
15767 	/* Reset here to make sure all is clean and to define PF 'n' */
15768 	i40e_clear_hw(hw);
15769 
15770 	err = i40e_set_mac_type(hw);
15771 	if (err) {
15772 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15773 			 err);
15774 		goto err_pf_reset;
15775 	}
15776 
15777 	err = i40e_handle_resets(pf);
15778 	if (err)
15779 		goto err_pf_reset;
15780 
15781 	i40e_check_recovery_mode(pf);
15782 
15783 	if (is_kdump_kernel()) {
15784 		hw->aq.num_arq_entries = I40E_MIN_ARQ_LEN;
15785 		hw->aq.num_asq_entries = I40E_MIN_ASQ_LEN;
15786 	} else {
15787 		hw->aq.num_arq_entries = I40E_AQ_LEN;
15788 		hw->aq.num_asq_entries = I40E_AQ_LEN;
15789 	}
15790 	hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15791 	hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15792 	pf->adminq_work_limit = I40E_AQ_WORK_LIMIT;
15793 
15794 	snprintf(pf->int_name, sizeof(pf->int_name) - 1,
15795 		 "%s-%s:misc",
15796 		 dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
15797 
15798 	err = i40e_init_shared_code(hw);
15799 	if (err) {
15800 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15801 			 err);
15802 		goto err_pf_reset;
15803 	}
15804 
15805 	/* set up a default setting for link flow control */
15806 	pf->hw.fc.requested_mode = I40E_FC_NONE;
15807 
15808 	err = i40e_init_adminq(hw);
15809 	if (err) {
15810 		if (err == -EIO)
15811 			dev_info(&pdev->dev,
15812 				 "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",
15813 				 hw->aq.api_maj_ver,
15814 				 hw->aq.api_min_ver,
15815 				 I40E_FW_API_VERSION_MAJOR,
15816 				 I40E_FW_MINOR_VERSION(hw));
15817 		else
15818 			dev_info(&pdev->dev,
15819 				 "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
15820 
15821 		goto err_pf_reset;
15822 	}
15823 	i40e_get_oem_version(hw);
15824 
15825 	/* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
15826 	dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
15827 		 hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
15828 		 hw->aq.api_maj_ver, hw->aq.api_min_ver,
15829 		 i40e_nvm_version_str(hw), hw->vendor_id, hw->device_id,
15830 		 hw->subsystem_vendor_id, hw->subsystem_device_id);
15831 
15832 	if (hw->aq.api_maj_ver == I40E_FW_API_VERSION_MAJOR &&
15833 	    hw->aq.api_min_ver > I40E_FW_MINOR_VERSION(hw))
15834 		dev_dbg(&pdev->dev,
15835 			"The driver for the device detected a newer version of the NVM image v%u.%u than v%u.%u.\n",
15836 			 hw->aq.api_maj_ver,
15837 			 hw->aq.api_min_ver,
15838 			 I40E_FW_API_VERSION_MAJOR,
15839 			 I40E_FW_MINOR_VERSION(hw));
15840 	else if (hw->aq.api_maj_ver == 1 && hw->aq.api_min_ver < 4)
15841 		dev_info(&pdev->dev,
15842 			 "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",
15843 			 hw->aq.api_maj_ver,
15844 			 hw->aq.api_min_ver,
15845 			 I40E_FW_API_VERSION_MAJOR,
15846 			 I40E_FW_MINOR_VERSION(hw));
15847 
15848 	i40e_verify_eeprom(pf);
15849 
15850 	/* Rev 0 hardware was never productized */
15851 	if (hw->revision_id < 1)
15852 		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");
15853 
15854 	i40e_clear_pxe_mode(hw);
15855 
15856 	err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
15857 	if (err)
15858 		goto err_adminq_setup;
15859 
15860 	err = i40e_sw_init(pf);
15861 	if (err) {
15862 		dev_info(&pdev->dev, "sw_init failed: %d\n", err);
15863 		goto err_sw_init;
15864 	}
15865 
15866 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15867 		return i40e_init_recovery_mode(pf, hw);
15868 
15869 	err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
15870 				hw->func_caps.num_rx_qp, 0, 0);
15871 	if (err) {
15872 		dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
15873 		goto err_init_lan_hmc;
15874 	}
15875 
15876 	err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
15877 	if (err) {
15878 		dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
15879 		err = -ENOENT;
15880 		goto err_configure_lan_hmc;
15881 	}
15882 
15883 	/* Disable LLDP for NICs that have firmware versions lower than v4.3.
15884 	 * Ignore error return codes because if it was already disabled via
15885 	 * hardware settings this will fail
15886 	 */
15887 	if (pf->hw_features & I40E_HW_STOP_FW_LLDP) {
15888 		dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
15889 		i40e_aq_stop_lldp(hw, true, false, NULL);
15890 	}
15891 
15892 	/* allow a platform config to override the HW addr */
15893 	i40e_get_platform_mac_addr(pdev, pf);
15894 
15895 	if (!is_valid_ether_addr(hw->mac.addr)) {
15896 		dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
15897 		err = -EIO;
15898 		goto err_mac_addr;
15899 	}
15900 	dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
15901 	ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
15902 	i40e_get_port_mac_addr(hw, hw->mac.port_addr);
15903 	if (is_valid_ether_addr(hw->mac.port_addr))
15904 		pf->hw_features |= I40E_HW_PORT_ID_VALID;
15905 
15906 	i40e_ptp_alloc_pins(pf);
15907 	pci_set_drvdata(pdev, pf);
15908 	pci_save_state(pdev);
15909 
15910 #ifdef CONFIG_I40E_DCB
15911 	status = i40e_get_fw_lldp_status(&pf->hw, &lldp_status);
15912 	(!status &&
15913 	 lldp_status == I40E_GET_FW_LLDP_STATUS_ENABLED) ?
15914 		(pf->flags &= ~I40E_FLAG_DISABLE_FW_LLDP) :
15915 		(pf->flags |= I40E_FLAG_DISABLE_FW_LLDP);
15916 	dev_info(&pdev->dev,
15917 		 (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) ?
15918 			"FW LLDP is disabled\n" :
15919 			"FW LLDP is enabled\n");
15920 
15921 	/* Enable FW to write default DCB config on link-up */
15922 	i40e_aq_set_dcb_parameters(hw, true, NULL);
15923 
15924 	err = i40e_init_pf_dcb(pf);
15925 	if (err) {
15926 		dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
15927 		pf->flags &= ~(I40E_FLAG_DCB_CAPABLE | I40E_FLAG_DCB_ENABLED);
15928 		/* Continue without DCB enabled */
15929 	}
15930 #endif /* CONFIG_I40E_DCB */
15931 
15932 	/* set up periodic task facility */
15933 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15934 	pf->service_timer_period = HZ;
15935 
15936 	INIT_WORK(&pf->service_task, i40e_service_task);
15937 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15938 
15939 	/* NVM bit on means WoL disabled for the port */
15940 	i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15941 	if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15942 		pf->wol_en = false;
15943 	else
15944 		pf->wol_en = true;
15945 	device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15946 
15947 	/* set up the main switch operations */
15948 	i40e_determine_queue_usage(pf);
15949 	err = i40e_init_interrupt_scheme(pf);
15950 	if (err)
15951 		goto err_switch_setup;
15952 
15953 	/* Reduce Tx and Rx pairs for kdump
15954 	 * When MSI-X is enabled, it's not allowed to use more TC queue
15955 	 * pairs than MSI-X vectors (pf->num_lan_msix) exist. Thus
15956 	 * vsi->num_queue_pairs will be equal to pf->num_lan_msix, i.e., 1.
15957 	 */
15958 	if (is_kdump_kernel())
15959 		pf->num_lan_msix = 1;
15960 
15961 	pf->udp_tunnel_nic.set_port = i40e_udp_tunnel_set_port;
15962 	pf->udp_tunnel_nic.unset_port = i40e_udp_tunnel_unset_port;
15963 	pf->udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP;
15964 	pf->udp_tunnel_nic.shared = &pf->udp_tunnel_shared;
15965 	pf->udp_tunnel_nic.tables[0].n_entries = I40E_MAX_PF_UDP_OFFLOAD_PORTS;
15966 	pf->udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
15967 						    UDP_TUNNEL_TYPE_GENEVE;
15968 
15969 	/* The number of VSIs reported by the FW is the minimum guaranteed
15970 	 * to us; HW supports far more and we share the remaining pool with
15971 	 * the other PFs. We allocate space for more than the guarantee with
15972 	 * the understanding that we might not get them all later.
15973 	 */
15974 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15975 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15976 	else
15977 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15978 	if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
15979 		dev_warn(&pf->pdev->dev,
15980 			 "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
15981 			 pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
15982 		pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
15983 	}
15984 
15985 	/* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15986 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15987 			  GFP_KERNEL);
15988 	if (!pf->vsi) {
15989 		err = -ENOMEM;
15990 		goto err_switch_setup;
15991 	}
15992 
15993 #ifdef CONFIG_PCI_IOV
15994 	/* prep for VF support */
15995 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15996 	    (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15997 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15998 		if (pci_num_vf(pdev))
15999 			pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
16000 	}
16001 #endif
16002 	err = i40e_setup_pf_switch(pf, false, false);
16003 	if (err) {
16004 		dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
16005 		goto err_vsis;
16006 	}
16007 	INIT_LIST_HEAD(&pf->vsi[pf->lan_vsi]->ch_list);
16008 
16009 	/* if FDIR VSI was set up, start it now */
16010 	for (i = 0; i < pf->num_alloc_vsi; i++) {
16011 		if (pf->vsi[i] && pf->vsi[i]->type == I40E_VSI_FDIR) {
16012 			i40e_vsi_open(pf->vsi[i]);
16013 			break;
16014 		}
16015 	}
16016 
16017 	/* The driver only wants link up/down and module qualification
16018 	 * reports from firmware.  Note the negative logic.
16019 	 */
16020 	err = i40e_aq_set_phy_int_mask(&pf->hw,
16021 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
16022 					 I40E_AQ_EVENT_MEDIA_NA |
16023 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
16024 	if (err)
16025 		dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
16026 			 ERR_PTR(err),
16027 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16028 
16029 	/* Reconfigure hardware for allowing smaller MSS in the case
16030 	 * of TSO, so that we avoid the MDD being fired and causing
16031 	 * a reset in the case of small MSS+TSO.
16032 	 */
16033 	val = rd32(hw, I40E_REG_MSS);
16034 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
16035 		val &= ~I40E_REG_MSS_MIN_MASK;
16036 		val |= I40E_64BYTE_MSS;
16037 		wr32(hw, I40E_REG_MSS, val);
16038 	}
16039 
16040 	if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
16041 		msleep(75);
16042 		err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
16043 		if (err)
16044 			dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
16045 				 ERR_PTR(err),
16046 				 i40e_aq_str(&pf->hw,
16047 					     pf->hw.aq.asq_last_status));
16048 	}
16049 	/* The main driver is (mostly) up and happy. We need to set this state
16050 	 * before setting up the misc vector or we get a race and the vector
16051 	 * ends up disabled forever.
16052 	 */
16053 	clear_bit(__I40E_DOWN, pf->state);
16054 
16055 	/* In case of MSIX we are going to setup the misc vector right here
16056 	 * to handle admin queue events etc. In case of legacy and MSI
16057 	 * the misc functionality and queue processing is combined in
16058 	 * the same vector and that gets setup at open.
16059 	 */
16060 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
16061 		err = i40e_setup_misc_vector(pf);
16062 		if (err) {
16063 			dev_info(&pdev->dev,
16064 				 "setup of misc vector failed: %d\n", err);
16065 			i40e_cloud_filter_exit(pf);
16066 			i40e_fdir_teardown(pf);
16067 			goto err_vsis;
16068 		}
16069 	}
16070 
16071 #ifdef CONFIG_PCI_IOV
16072 	/* prep for VF support */
16073 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
16074 	    (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
16075 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
16076 		/* disable link interrupts for VFs */
16077 		val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
16078 		val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
16079 		wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
16080 		i40e_flush(hw);
16081 
16082 		if (pci_num_vf(pdev)) {
16083 			dev_info(&pdev->dev,
16084 				 "Active VFs found, allocating resources.\n");
16085 			err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
16086 			if (err)
16087 				dev_info(&pdev->dev,
16088 					 "Error %d allocating resources for existing VFs\n",
16089 					 err);
16090 		}
16091 	}
16092 #endif /* CONFIG_PCI_IOV */
16093 
16094 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16095 		pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
16096 						      pf->num_iwarp_msix,
16097 						      I40E_IWARP_IRQ_PILE_ID);
16098 		if (pf->iwarp_base_vector < 0) {
16099 			dev_info(&pdev->dev,
16100 				 "failed to get tracking for %d vectors for IWARP err=%d\n",
16101 				 pf->num_iwarp_msix, pf->iwarp_base_vector);
16102 			pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
16103 		}
16104 	}
16105 
16106 	i40e_dbg_pf_init(pf);
16107 
16108 	/* tell the firmware that we're starting */
16109 	i40e_send_version(pf);
16110 
16111 	/* since everything's happy, start the service_task timer */
16112 	mod_timer(&pf->service_timer,
16113 		  round_jiffies(jiffies + pf->service_timer_period));
16114 
16115 	/* add this PF to client device list and launch a client service task */
16116 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16117 		err = i40e_lan_add_device(pf);
16118 		if (err)
16119 			dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
16120 				 err);
16121 	}
16122 
16123 #define PCI_SPEED_SIZE 8
16124 #define PCI_WIDTH_SIZE 8
16125 	/* Devices on the IOSF bus do not have this information
16126 	 * and will report PCI Gen 1 x 1 by default so don't bother
16127 	 * checking them.
16128 	 */
16129 	if (!(pf->hw_features & I40E_HW_NO_PCI_LINK_CHECK)) {
16130 		char speed[PCI_SPEED_SIZE] = "Unknown";
16131 		char width[PCI_WIDTH_SIZE] = "Unknown";
16132 
16133 		/* Get the negotiated link width and speed from PCI config
16134 		 * space
16135 		 */
16136 		pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
16137 					  &link_status);
16138 
16139 		i40e_set_pci_config_data(hw, link_status);
16140 
16141 		switch (hw->bus.speed) {
16142 		case i40e_bus_speed_8000:
16143 			strscpy(speed, "8.0", PCI_SPEED_SIZE); break;
16144 		case i40e_bus_speed_5000:
16145 			strscpy(speed, "5.0", PCI_SPEED_SIZE); break;
16146 		case i40e_bus_speed_2500:
16147 			strscpy(speed, "2.5", PCI_SPEED_SIZE); break;
16148 		default:
16149 			break;
16150 		}
16151 		switch (hw->bus.width) {
16152 		case i40e_bus_width_pcie_x8:
16153 			strscpy(width, "8", PCI_WIDTH_SIZE); break;
16154 		case i40e_bus_width_pcie_x4:
16155 			strscpy(width, "4", PCI_WIDTH_SIZE); break;
16156 		case i40e_bus_width_pcie_x2:
16157 			strscpy(width, "2", PCI_WIDTH_SIZE); break;
16158 		case i40e_bus_width_pcie_x1:
16159 			strscpy(width, "1", PCI_WIDTH_SIZE); break;
16160 		default:
16161 			break;
16162 		}
16163 
16164 		dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
16165 			 speed, width);
16166 
16167 		if (hw->bus.width < i40e_bus_width_pcie_x8 ||
16168 		    hw->bus.speed < i40e_bus_speed_8000) {
16169 			dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
16170 			dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
16171 		}
16172 	}
16173 
16174 	/* get the requested speeds from the fw */
16175 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
16176 	if (err)
16177 		dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %pe last_status =  %s\n",
16178 			ERR_PTR(err),
16179 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16180 	pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
16181 
16182 	/* set the FEC config due to the board capabilities */
16183 	i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, &pf->flags);
16184 
16185 	/* get the supported phy types from the fw */
16186 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
16187 	if (err)
16188 		dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %pe last_status =  %s\n",
16189 			ERR_PTR(err),
16190 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16191 
16192 	/* make sure the MFS hasn't been set lower than the default */
16193 #define MAX_FRAME_SIZE_DEFAULT 0x2600
16194 	val = (rd32(&pf->hw, I40E_PRTGL_SAH) &
16195 	       I40E_PRTGL_SAH_MFS_MASK) >> I40E_PRTGL_SAH_MFS_SHIFT;
16196 	if (val < MAX_FRAME_SIZE_DEFAULT)
16197 		dev_warn(&pdev->dev, "MFS for port %x has been set below the default: %x\n",
16198 			 i, val);
16199 
16200 	/* Add a filter to drop all Flow control frames from any VSI from being
16201 	 * transmitted. By doing so we stop a malicious VF from sending out
16202 	 * PAUSE or PFC frames and potentially controlling traffic for other
16203 	 * PF/VF VSIs.
16204 	 * The FW can still send Flow control frames if enabled.
16205 	 */
16206 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
16207 						       pf->main_vsi_seid);
16208 
16209 	if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
16210 		(pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
16211 		pf->hw_features |= I40E_HW_PHY_CONTROLS_LEDS;
16212 	if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
16213 		pf->hw_features |= I40E_HW_HAVE_CRT_RETIMER;
16214 	/* print a string summarizing features */
16215 	i40e_print_features(pf);
16216 
16217 	return 0;
16218 
16219 	/* Unwind what we've done if something failed in the setup */
16220 err_vsis:
16221 	set_bit(__I40E_DOWN, pf->state);
16222 	i40e_clear_interrupt_scheme(pf);
16223 	kfree(pf->vsi);
16224 err_switch_setup:
16225 	i40e_reset_interrupt_capability(pf);
16226 	timer_shutdown_sync(&pf->service_timer);
16227 err_mac_addr:
16228 err_configure_lan_hmc:
16229 	(void)i40e_shutdown_lan_hmc(hw);
16230 err_init_lan_hmc:
16231 	kfree(pf->qp_pile);
16232 err_sw_init:
16233 err_adminq_setup:
16234 err_pf_reset:
16235 	iounmap(hw->hw_addr);
16236 err_ioremap:
16237 	kfree(pf);
16238 err_pf_alloc:
16239 	pci_release_mem_regions(pdev);
16240 err_pci_reg:
16241 err_dma:
16242 	pci_disable_device(pdev);
16243 	return err;
16244 }
16245 
16246 /**
16247  * i40e_remove - Device removal routine
16248  * @pdev: PCI device information struct
16249  *
16250  * i40e_remove is called by the PCI subsystem to alert the driver
16251  * that is should release a PCI device.  This could be caused by a
16252  * Hot-Plug event, or because the driver is going to be removed from
16253  * memory.
16254  **/
16255 static void i40e_remove(struct pci_dev *pdev)
16256 {
16257 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16258 	struct i40e_hw *hw = &pf->hw;
16259 	int ret_code;
16260 	int i;
16261 
16262 	i40e_dbg_pf_exit(pf);
16263 
16264 	i40e_ptp_stop(pf);
16265 
16266 	/* Disable RSS in hw */
16267 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
16268 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
16269 
16270 	/* Grab __I40E_RESET_RECOVERY_PENDING and set __I40E_IN_REMOVE
16271 	 * flags, once they are set, i40e_rebuild should not be called as
16272 	 * i40e_prep_for_reset always returns early.
16273 	 */
16274 	while (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
16275 		usleep_range(1000, 2000);
16276 	set_bit(__I40E_IN_REMOVE, pf->state);
16277 
16278 	if (pf->flags & I40E_FLAG_SRIOV_ENABLED) {
16279 		set_bit(__I40E_VF_RESETS_DISABLED, pf->state);
16280 		i40e_free_vfs(pf);
16281 		pf->flags &= ~I40E_FLAG_SRIOV_ENABLED;
16282 	}
16283 	/* no more scheduling of any task */
16284 	set_bit(__I40E_SUSPENDED, pf->state);
16285 	set_bit(__I40E_DOWN, pf->state);
16286 	if (pf->service_timer.function)
16287 		timer_shutdown_sync(&pf->service_timer);
16288 	if (pf->service_task.func)
16289 		cancel_work_sync(&pf->service_task);
16290 
16291 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
16292 		struct i40e_vsi *vsi = pf->vsi[0];
16293 
16294 		/* We know that we have allocated only one vsi for this PF,
16295 		 * it was just for registering netdevice, so the interface
16296 		 * could be visible in the 'ifconfig' output
16297 		 */
16298 		unregister_netdev(vsi->netdev);
16299 		free_netdev(vsi->netdev);
16300 
16301 		goto unmap;
16302 	}
16303 
16304 	/* Client close must be called explicitly here because the timer
16305 	 * has been stopped.
16306 	 */
16307 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16308 
16309 	i40e_fdir_teardown(pf);
16310 
16311 	/* If there is a switch structure or any orphans, remove them.
16312 	 * This will leave only the PF's VSI remaining.
16313 	 */
16314 	for (i = 0; i < I40E_MAX_VEB; i++) {
16315 		if (!pf->veb[i])
16316 			continue;
16317 
16318 		if (pf->veb[i]->uplink_seid == pf->mac_seid ||
16319 		    pf->veb[i]->uplink_seid == 0)
16320 			i40e_switch_branch_release(pf->veb[i]);
16321 	}
16322 
16323 	/* Now we can shutdown the PF's VSI, just before we kill
16324 	 * adminq and hmc.
16325 	 */
16326 	if (pf->vsi[pf->lan_vsi])
16327 		i40e_vsi_release(pf->vsi[pf->lan_vsi]);
16328 
16329 	i40e_cloud_filter_exit(pf);
16330 
16331 	/* remove attached clients */
16332 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16333 		ret_code = i40e_lan_del_device(pf);
16334 		if (ret_code)
16335 			dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
16336 				 ret_code);
16337 	}
16338 
16339 	/* shutdown and destroy the HMC */
16340 	if (hw->hmc.hmc_obj) {
16341 		ret_code = i40e_shutdown_lan_hmc(hw);
16342 		if (ret_code)
16343 			dev_warn(&pdev->dev,
16344 				 "Failed to destroy the HMC resources: %d\n",
16345 				 ret_code);
16346 	}
16347 
16348 unmap:
16349 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16350 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16351 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16352 		free_irq(pf->pdev->irq, pf);
16353 
16354 	/* shutdown the adminq */
16355 	i40e_shutdown_adminq(hw);
16356 
16357 	/* destroy the locks only once, here */
16358 	mutex_destroy(&hw->aq.arq_mutex);
16359 	mutex_destroy(&hw->aq.asq_mutex);
16360 
16361 	/* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
16362 	rtnl_lock();
16363 	i40e_clear_interrupt_scheme(pf);
16364 	for (i = 0; i < pf->num_alloc_vsi; i++) {
16365 		if (pf->vsi[i]) {
16366 			if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
16367 				i40e_vsi_clear_rings(pf->vsi[i]);
16368 			i40e_vsi_clear(pf->vsi[i]);
16369 			pf->vsi[i] = NULL;
16370 		}
16371 	}
16372 	rtnl_unlock();
16373 
16374 	for (i = 0; i < I40E_MAX_VEB; i++) {
16375 		kfree(pf->veb[i]);
16376 		pf->veb[i] = NULL;
16377 	}
16378 
16379 	kfree(pf->qp_pile);
16380 	kfree(pf->vsi);
16381 
16382 	iounmap(hw->hw_addr);
16383 	kfree(pf);
16384 	pci_release_mem_regions(pdev);
16385 
16386 	pci_disable_device(pdev);
16387 }
16388 
16389 /**
16390  * i40e_pci_error_detected - warning that something funky happened in PCI land
16391  * @pdev: PCI device information struct
16392  * @error: the type of PCI error
16393  *
16394  * Called to warn that something happened and the error handling steps
16395  * are in progress.  Allows the driver to quiesce things, be ready for
16396  * remediation.
16397  **/
16398 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
16399 						pci_channel_state_t error)
16400 {
16401 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16402 
16403 	dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
16404 
16405 	if (!pf) {
16406 		dev_info(&pdev->dev,
16407 			 "Cannot recover - error happened during device probe\n");
16408 		return PCI_ERS_RESULT_DISCONNECT;
16409 	}
16410 
16411 	/* shutdown all operations */
16412 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16413 		i40e_prep_for_reset(pf);
16414 
16415 	/* Request a slot reset */
16416 	return PCI_ERS_RESULT_NEED_RESET;
16417 }
16418 
16419 /**
16420  * i40e_pci_error_slot_reset - a PCI slot reset just happened
16421  * @pdev: PCI device information struct
16422  *
16423  * Called to find if the driver can work with the device now that
16424  * the pci slot has been reset.  If a basic connection seems good
16425  * (registers are readable and have sane content) then return a
16426  * happy little PCI_ERS_RESULT_xxx.
16427  **/
16428 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
16429 {
16430 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16431 	pci_ers_result_t result;
16432 	u32 reg;
16433 
16434 	dev_dbg(&pdev->dev, "%s\n", __func__);
16435 	if (pci_enable_device_mem(pdev)) {
16436 		dev_info(&pdev->dev,
16437 			 "Cannot re-enable PCI device after reset.\n");
16438 		result = PCI_ERS_RESULT_DISCONNECT;
16439 	} else {
16440 		pci_set_master(pdev);
16441 		pci_restore_state(pdev);
16442 		pci_save_state(pdev);
16443 		pci_wake_from_d3(pdev, false);
16444 
16445 		reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
16446 		if (reg == 0)
16447 			result = PCI_ERS_RESULT_RECOVERED;
16448 		else
16449 			result = PCI_ERS_RESULT_DISCONNECT;
16450 	}
16451 
16452 	return result;
16453 }
16454 
16455 /**
16456  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
16457  * @pdev: PCI device information struct
16458  */
16459 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
16460 {
16461 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16462 
16463 	i40e_prep_for_reset(pf);
16464 }
16465 
16466 /**
16467  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
16468  * @pdev: PCI device information struct
16469  */
16470 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
16471 {
16472 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16473 
16474 	if (test_bit(__I40E_IN_REMOVE, pf->state))
16475 		return;
16476 
16477 	i40e_reset_and_rebuild(pf, false, false);
16478 }
16479 
16480 /**
16481  * i40e_pci_error_resume - restart operations after PCI error recovery
16482  * @pdev: PCI device information struct
16483  *
16484  * Called to allow the driver to bring things back up after PCI error
16485  * and/or reset recovery has finished.
16486  **/
16487 static void i40e_pci_error_resume(struct pci_dev *pdev)
16488 {
16489 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16490 
16491 	dev_dbg(&pdev->dev, "%s\n", __func__);
16492 	if (test_bit(__I40E_SUSPENDED, pf->state))
16493 		return;
16494 
16495 	i40e_handle_reset_warning(pf, false);
16496 }
16497 
16498 /**
16499  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
16500  * using the mac_address_write admin q function
16501  * @pf: pointer to i40e_pf struct
16502  **/
16503 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
16504 {
16505 	struct i40e_hw *hw = &pf->hw;
16506 	u8 mac_addr[6];
16507 	u16 flags = 0;
16508 	int ret;
16509 
16510 	/* Get current MAC address in case it's an LAA */
16511 	if (pf->vsi[pf->lan_vsi] && pf->vsi[pf->lan_vsi]->netdev) {
16512 		ether_addr_copy(mac_addr,
16513 				pf->vsi[pf->lan_vsi]->netdev->dev_addr);
16514 	} else {
16515 		dev_err(&pf->pdev->dev,
16516 			"Failed to retrieve MAC address; using default\n");
16517 		ether_addr_copy(mac_addr, hw->mac.addr);
16518 	}
16519 
16520 	/* The FW expects the mac address write cmd to first be called with
16521 	 * one of these flags before calling it again with the multicast
16522 	 * enable flags.
16523 	 */
16524 	flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
16525 
16526 	if (hw->func_caps.flex10_enable && hw->partition_id != 1)
16527 		flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
16528 
16529 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16530 	if (ret) {
16531 		dev_err(&pf->pdev->dev,
16532 			"Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
16533 		return;
16534 	}
16535 
16536 	flags = I40E_AQC_MC_MAG_EN
16537 			| I40E_AQC_WOL_PRESERVE_ON_PFR
16538 			| I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
16539 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16540 	if (ret)
16541 		dev_err(&pf->pdev->dev,
16542 			"Failed to enable Multicast Magic Packet wake up\n");
16543 }
16544 
16545 /**
16546  * i40e_shutdown - PCI callback for shutting down
16547  * @pdev: PCI device information struct
16548  **/
16549 static void i40e_shutdown(struct pci_dev *pdev)
16550 {
16551 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16552 	struct i40e_hw *hw = &pf->hw;
16553 
16554 	set_bit(__I40E_SUSPENDED, pf->state);
16555 	set_bit(__I40E_DOWN, pf->state);
16556 
16557 	del_timer_sync(&pf->service_timer);
16558 	cancel_work_sync(&pf->service_task);
16559 	i40e_cloud_filter_exit(pf);
16560 	i40e_fdir_teardown(pf);
16561 
16562 	/* Client close must be called explicitly here because the timer
16563 	 * has been stopped.
16564 	 */
16565 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16566 
16567 	if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16568 		i40e_enable_mc_magic_wake(pf);
16569 
16570 	i40e_prep_for_reset(pf);
16571 
16572 	wr32(hw, I40E_PFPM_APM,
16573 	     (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16574 	wr32(hw, I40E_PFPM_WUFC,
16575 	     (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16576 
16577 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16578 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16579 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16580 		free_irq(pf->pdev->irq, pf);
16581 
16582 	/* Since we're going to destroy queues during the
16583 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16584 	 * whole section
16585 	 */
16586 	rtnl_lock();
16587 	i40e_clear_interrupt_scheme(pf);
16588 	rtnl_unlock();
16589 
16590 	if (system_state == SYSTEM_POWER_OFF) {
16591 		pci_wake_from_d3(pdev, pf->wol_en);
16592 		pci_set_power_state(pdev, PCI_D3hot);
16593 	}
16594 }
16595 
16596 /**
16597  * i40e_suspend - PM callback for moving to D3
16598  * @dev: generic device information structure
16599  **/
16600 static int __maybe_unused i40e_suspend(struct device *dev)
16601 {
16602 	struct i40e_pf *pf = dev_get_drvdata(dev);
16603 	struct i40e_hw *hw = &pf->hw;
16604 
16605 	/* If we're already suspended, then there is nothing to do */
16606 	if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
16607 		return 0;
16608 
16609 	set_bit(__I40E_DOWN, pf->state);
16610 
16611 	/* Ensure service task will not be running */
16612 	del_timer_sync(&pf->service_timer);
16613 	cancel_work_sync(&pf->service_task);
16614 
16615 	/* Client close must be called explicitly here because the timer
16616 	 * has been stopped.
16617 	 */
16618 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16619 
16620 	if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16621 		i40e_enable_mc_magic_wake(pf);
16622 
16623 	/* Since we're going to destroy queues during the
16624 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16625 	 * whole section
16626 	 */
16627 	rtnl_lock();
16628 
16629 	i40e_prep_for_reset(pf);
16630 
16631 	wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16632 	wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16633 
16634 	/* Clear the interrupt scheme and release our IRQs so that the system
16635 	 * can safely hibernate even when there are a large number of CPUs.
16636 	 * Otherwise hibernation might fail when mapping all the vectors back
16637 	 * to CPU0.
16638 	 */
16639 	i40e_clear_interrupt_scheme(pf);
16640 
16641 	rtnl_unlock();
16642 
16643 	return 0;
16644 }
16645 
16646 /**
16647  * i40e_resume - PM callback for waking up from D3
16648  * @dev: generic device information structure
16649  **/
16650 static int __maybe_unused i40e_resume(struct device *dev)
16651 {
16652 	struct i40e_pf *pf = dev_get_drvdata(dev);
16653 	int err;
16654 
16655 	/* If we're not suspended, then there is nothing to do */
16656 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16657 		return 0;
16658 
16659 	/* We need to hold the RTNL lock prior to restoring interrupt schemes,
16660 	 * since we're going to be restoring queues
16661 	 */
16662 	rtnl_lock();
16663 
16664 	/* We cleared the interrupt scheme when we suspended, so we need to
16665 	 * restore it now to resume device functionality.
16666 	 */
16667 	err = i40e_restore_interrupt_scheme(pf);
16668 	if (err) {
16669 		dev_err(dev, "Cannot restore interrupt scheme: %d\n",
16670 			err);
16671 	}
16672 
16673 	clear_bit(__I40E_DOWN, pf->state);
16674 	i40e_reset_and_rebuild(pf, false, true);
16675 
16676 	rtnl_unlock();
16677 
16678 	/* Clear suspended state last after everything is recovered */
16679 	clear_bit(__I40E_SUSPENDED, pf->state);
16680 
16681 	/* Restart the service task */
16682 	mod_timer(&pf->service_timer,
16683 		  round_jiffies(jiffies + pf->service_timer_period));
16684 
16685 	return 0;
16686 }
16687 
16688 static const struct pci_error_handlers i40e_err_handler = {
16689 	.error_detected = i40e_pci_error_detected,
16690 	.slot_reset = i40e_pci_error_slot_reset,
16691 	.reset_prepare = i40e_pci_error_reset_prepare,
16692 	.reset_done = i40e_pci_error_reset_done,
16693 	.resume = i40e_pci_error_resume,
16694 };
16695 
16696 static SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
16697 
16698 static struct pci_driver i40e_driver = {
16699 	.name     = i40e_driver_name,
16700 	.id_table = i40e_pci_tbl,
16701 	.probe    = i40e_probe,
16702 	.remove   = i40e_remove,
16703 	.driver   = {
16704 		.pm = &i40e_pm_ops,
16705 	},
16706 	.shutdown = i40e_shutdown,
16707 	.err_handler = &i40e_err_handler,
16708 	.sriov_configure = i40e_pci_sriov_configure,
16709 };
16710 
16711 /**
16712  * i40e_init_module - Driver registration routine
16713  *
16714  * i40e_init_module is the first routine called when the driver is
16715  * loaded. All it does is register with the PCI subsystem.
16716  **/
16717 static int __init i40e_init_module(void)
16718 {
16719 	int err;
16720 
16721 	pr_info("%s: %s\n", i40e_driver_name, i40e_driver_string);
16722 	pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
16723 
16724 	/* There is no need to throttle the number of active tasks because
16725 	 * each device limits its own task using a state bit for scheduling
16726 	 * the service task, and the device tasks do not interfere with each
16727 	 * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
16728 	 * since we need to be able to guarantee forward progress even under
16729 	 * memory pressure.
16730 	 */
16731 	i40e_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, i40e_driver_name);
16732 	if (!i40e_wq) {
16733 		pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
16734 		return -ENOMEM;
16735 	}
16736 
16737 	i40e_dbg_init();
16738 	err = pci_register_driver(&i40e_driver);
16739 	if (err) {
16740 		destroy_workqueue(i40e_wq);
16741 		i40e_dbg_exit();
16742 		return err;
16743 	}
16744 
16745 	return 0;
16746 }
16747 module_init(i40e_init_module);
16748 
16749 /**
16750  * i40e_exit_module - Driver exit cleanup routine
16751  *
16752  * i40e_exit_module is called just before the driver is removed
16753  * from memory.
16754  **/
16755 static void __exit i40e_exit_module(void)
16756 {
16757 	pci_unregister_driver(&i40e_driver);
16758 	destroy_workqueue(i40e_wq);
16759 	ida_destroy(&i40e_client_ida);
16760 	i40e_dbg_exit();
16761 }
16762 module_exit(i40e_exit_module);
16763