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 (ether_addr_equal(netdev->dev_addr, addr->sa_data)) {
1792 		netdev_info(netdev, "already using mac address %pM\n",
1793 			    addr->sa_data);
1794 		return 0;
1795 	}
1796 
1797 	if (test_bit(__I40E_DOWN, pf->state) ||
1798 	    test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1799 		return -EADDRNOTAVAIL;
1800 
1801 	if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1802 		netdev_info(netdev, "returning to hw mac address %pM\n",
1803 			    hw->mac.addr);
1804 	else
1805 		netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1806 
1807 	/* Copy the address first, so that we avoid a possible race with
1808 	 * .set_rx_mode().
1809 	 * - Remove old address from MAC filter
1810 	 * - Copy new address
1811 	 * - Add new address to MAC filter
1812 	 */
1813 	spin_lock_bh(&vsi->mac_filter_hash_lock);
1814 	i40e_del_mac_filter(vsi, netdev->dev_addr);
1815 	eth_hw_addr_set(netdev, addr->sa_data);
1816 	i40e_add_mac_filter(vsi, netdev->dev_addr);
1817 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
1818 
1819 	if (vsi->type == I40E_VSI_MAIN) {
1820 		int ret;
1821 
1822 		ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1823 						addr->sa_data, NULL);
1824 		if (ret)
1825 			netdev_info(netdev, "Ignoring error from firmware on LAA update, status %pe, AQ ret %s\n",
1826 				    ERR_PTR(ret),
1827 				    i40e_aq_str(hw, hw->aq.asq_last_status));
1828 	}
1829 
1830 	/* schedule our worker thread which will take care of
1831 	 * applying the new filter changes
1832 	 */
1833 	i40e_service_event_schedule(pf);
1834 	return 0;
1835 }
1836 
1837 /**
1838  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1839  * @vsi: vsi structure
1840  * @seed: RSS hash seed
1841  * @lut: pointer to lookup table of lut_size
1842  * @lut_size: size of the lookup table
1843  **/
1844 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1845 			      u8 *lut, u16 lut_size)
1846 {
1847 	struct i40e_pf *pf = vsi->back;
1848 	struct i40e_hw *hw = &pf->hw;
1849 	int ret = 0;
1850 
1851 	if (seed) {
1852 		struct i40e_aqc_get_set_rss_key_data *seed_dw =
1853 			(struct i40e_aqc_get_set_rss_key_data *)seed;
1854 		ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1855 		if (ret) {
1856 			dev_info(&pf->pdev->dev,
1857 				 "Cannot set RSS key, err %pe aq_err %s\n",
1858 				 ERR_PTR(ret),
1859 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1860 			return ret;
1861 		}
1862 	}
1863 	if (lut) {
1864 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
1865 
1866 		ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1867 		if (ret) {
1868 			dev_info(&pf->pdev->dev,
1869 				 "Cannot set RSS lut, err %pe aq_err %s\n",
1870 				 ERR_PTR(ret),
1871 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1872 			return ret;
1873 		}
1874 	}
1875 	return ret;
1876 }
1877 
1878 /**
1879  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1880  * @vsi: VSI structure
1881  **/
1882 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1883 {
1884 	struct i40e_pf *pf = vsi->back;
1885 	u8 seed[I40E_HKEY_ARRAY_SIZE];
1886 	u8 *lut;
1887 	int ret;
1888 
1889 	if (!(pf->hw_features & I40E_HW_RSS_AQ_CAPABLE))
1890 		return 0;
1891 	if (!vsi->rss_size)
1892 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
1893 				      vsi->num_queue_pairs);
1894 	if (!vsi->rss_size)
1895 		return -EINVAL;
1896 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1897 	if (!lut)
1898 		return -ENOMEM;
1899 
1900 	/* Use the user configured hash keys and lookup table if there is one,
1901 	 * otherwise use default
1902 	 */
1903 	if (vsi->rss_lut_user)
1904 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1905 	else
1906 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1907 	if (vsi->rss_hkey_user)
1908 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1909 	else
1910 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1911 	ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1912 	kfree(lut);
1913 	return ret;
1914 }
1915 
1916 /**
1917  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1918  * @vsi: the VSI being configured,
1919  * @ctxt: VSI context structure
1920  * @enabled_tc: number of traffic classes to enable
1921  *
1922  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1923  **/
1924 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1925 					   struct i40e_vsi_context *ctxt,
1926 					   u8 enabled_tc)
1927 {
1928 	u16 qcount = 0, max_qcount, qmap, sections = 0;
1929 	int i, override_q, pow, num_qps, ret;
1930 	u8 netdev_tc = 0, offset = 0;
1931 
1932 	if (vsi->type != I40E_VSI_MAIN)
1933 		return -EINVAL;
1934 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1935 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1936 	vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1937 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1938 	num_qps = vsi->mqprio_qopt.qopt.count[0];
1939 
1940 	/* find the next higher power-of-2 of num queue pairs */
1941 	pow = ilog2(num_qps);
1942 	if (!is_power_of_2(num_qps))
1943 		pow++;
1944 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1945 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1946 
1947 	/* Setup queue offset/count for all TCs for given VSI */
1948 	max_qcount = vsi->mqprio_qopt.qopt.count[0];
1949 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1950 		/* See if the given TC is enabled for the given VSI */
1951 		if (vsi->tc_config.enabled_tc & BIT(i)) {
1952 			offset = vsi->mqprio_qopt.qopt.offset[i];
1953 			qcount = vsi->mqprio_qopt.qopt.count[i];
1954 			if (qcount > max_qcount)
1955 				max_qcount = qcount;
1956 			vsi->tc_config.tc_info[i].qoffset = offset;
1957 			vsi->tc_config.tc_info[i].qcount = qcount;
1958 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1959 		} else {
1960 			/* TC is not enabled so set the offset to
1961 			 * default queue and allocate one queue
1962 			 * for the given TC.
1963 			 */
1964 			vsi->tc_config.tc_info[i].qoffset = 0;
1965 			vsi->tc_config.tc_info[i].qcount = 1;
1966 			vsi->tc_config.tc_info[i].netdev_tc = 0;
1967 		}
1968 	}
1969 
1970 	/* Set actual Tx/Rx queue pairs */
1971 	vsi->num_queue_pairs = offset + qcount;
1972 
1973 	/* Setup queue TC[0].qmap for given VSI context */
1974 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1975 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1976 	ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1977 	ctxt->info.valid_sections |= cpu_to_le16(sections);
1978 
1979 	/* Reconfigure RSS for main VSI with max queue count */
1980 	vsi->rss_size = max_qcount;
1981 	ret = i40e_vsi_config_rss(vsi);
1982 	if (ret) {
1983 		dev_info(&vsi->back->pdev->dev,
1984 			 "Failed to reconfig rss for num_queues (%u)\n",
1985 			 max_qcount);
1986 		return ret;
1987 	}
1988 	vsi->reconfig_rss = true;
1989 	dev_dbg(&vsi->back->pdev->dev,
1990 		"Reconfigured rss with num_queues (%u)\n", max_qcount);
1991 
1992 	/* Find queue count available for channel VSIs and starting offset
1993 	 * for channel VSIs
1994 	 */
1995 	override_q = vsi->mqprio_qopt.qopt.count[0];
1996 	if (override_q && override_q < vsi->num_queue_pairs) {
1997 		vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
1998 		vsi->next_base_queue = override_q;
1999 	}
2000 	return 0;
2001 }
2002 
2003 /**
2004  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
2005  * @vsi: the VSI being setup
2006  * @ctxt: VSI context structure
2007  * @enabled_tc: Enabled TCs bitmap
2008  * @is_add: True if called before Add VSI
2009  *
2010  * Setup VSI queue mapping for enabled traffic classes.
2011  **/
2012 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
2013 				     struct i40e_vsi_context *ctxt,
2014 				     u8 enabled_tc,
2015 				     bool is_add)
2016 {
2017 	struct i40e_pf *pf = vsi->back;
2018 	u16 num_tc_qps = 0;
2019 	u16 sections = 0;
2020 	u8 netdev_tc = 0;
2021 	u16 numtc = 1;
2022 	u16 qcount;
2023 	u8 offset;
2024 	u16 qmap;
2025 	int i;
2026 
2027 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
2028 	offset = 0;
2029 	/* zero out queue mapping, it will get updated on the end of the function */
2030 	memset(ctxt->info.queue_mapping, 0, sizeof(ctxt->info.queue_mapping));
2031 
2032 	if (vsi->type == I40E_VSI_MAIN) {
2033 		/* This code helps add more queue to the VSI if we have
2034 		 * more cores than RSS can support, the higher cores will
2035 		 * be served by ATR or other filters. Furthermore, the
2036 		 * non-zero req_queue_pairs says that user requested a new
2037 		 * queue count via ethtool's set_channels, so use this
2038 		 * value for queues distribution across traffic classes
2039 		 * We need at least one queue pair for the interface
2040 		 * to be usable as we see in else statement.
2041 		 */
2042 		if (vsi->req_queue_pairs > 0)
2043 			vsi->num_queue_pairs = vsi->req_queue_pairs;
2044 		else if (pf->flags & I40E_FLAG_MSIX_ENABLED)
2045 			vsi->num_queue_pairs = pf->num_lan_msix;
2046 		else
2047 			vsi->num_queue_pairs = 1;
2048 	}
2049 
2050 	/* Number of queues per enabled TC */
2051 	if (vsi->type == I40E_VSI_MAIN ||
2052 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs != 0))
2053 		num_tc_qps = vsi->num_queue_pairs;
2054 	else
2055 		num_tc_qps = vsi->alloc_queue_pairs;
2056 
2057 	if (enabled_tc && (vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
2058 		/* Find numtc from enabled TC bitmap */
2059 		for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2060 			if (enabled_tc & BIT(i)) /* TC is enabled */
2061 				numtc++;
2062 		}
2063 		if (!numtc) {
2064 			dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
2065 			numtc = 1;
2066 		}
2067 		num_tc_qps = num_tc_qps / numtc;
2068 		num_tc_qps = min_t(int, num_tc_qps,
2069 				   i40e_pf_get_max_q_per_tc(pf));
2070 	}
2071 
2072 	vsi->tc_config.numtc = numtc;
2073 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
2074 
2075 	/* Do not allow use more TC queue pairs than MSI-X vectors exist */
2076 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
2077 		num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
2078 
2079 	/* Setup queue offset/count for all TCs for given VSI */
2080 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2081 		/* See if the given TC is enabled for the given VSI */
2082 		if (vsi->tc_config.enabled_tc & BIT(i)) {
2083 			/* TC is enabled */
2084 			int pow, num_qps;
2085 
2086 			switch (vsi->type) {
2087 			case I40E_VSI_MAIN:
2088 				if (!(pf->flags & (I40E_FLAG_FD_SB_ENABLED |
2089 				    I40E_FLAG_FD_ATR_ENABLED)) ||
2090 				    vsi->tc_config.enabled_tc != 1) {
2091 					qcount = min_t(int, pf->alloc_rss_size,
2092 						       num_tc_qps);
2093 					break;
2094 				}
2095 				fallthrough;
2096 			case I40E_VSI_FDIR:
2097 			case I40E_VSI_SRIOV:
2098 			case I40E_VSI_VMDQ2:
2099 			default:
2100 				qcount = num_tc_qps;
2101 				WARN_ON(i != 0);
2102 				break;
2103 			}
2104 			vsi->tc_config.tc_info[i].qoffset = offset;
2105 			vsi->tc_config.tc_info[i].qcount = qcount;
2106 
2107 			/* find the next higher power-of-2 of num queue pairs */
2108 			num_qps = qcount;
2109 			pow = 0;
2110 			while (num_qps && (BIT_ULL(pow) < qcount)) {
2111 				pow++;
2112 				num_qps >>= 1;
2113 			}
2114 
2115 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
2116 			qmap =
2117 			    (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
2118 			    (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
2119 
2120 			offset += qcount;
2121 		} else {
2122 			/* TC is not enabled so set the offset to
2123 			 * default queue and allocate one queue
2124 			 * for the given TC.
2125 			 */
2126 			vsi->tc_config.tc_info[i].qoffset = 0;
2127 			vsi->tc_config.tc_info[i].qcount = 1;
2128 			vsi->tc_config.tc_info[i].netdev_tc = 0;
2129 
2130 			qmap = 0;
2131 		}
2132 		ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
2133 	}
2134 	/* Do not change previously set num_queue_pairs for PFs and VFs*/
2135 	if ((vsi->type == I40E_VSI_MAIN && numtc != 1) ||
2136 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs == 0) ||
2137 	    (vsi->type != I40E_VSI_MAIN && vsi->type != I40E_VSI_SRIOV))
2138 		vsi->num_queue_pairs = offset;
2139 
2140 	/* Scheduler section valid can only be set for ADD VSI */
2141 	if (is_add) {
2142 		sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
2143 
2144 		ctxt->info.up_enable_bits = enabled_tc;
2145 	}
2146 	if (vsi->type == I40E_VSI_SRIOV) {
2147 		ctxt->info.mapping_flags |=
2148 				     cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
2149 		for (i = 0; i < vsi->num_queue_pairs; i++)
2150 			ctxt->info.queue_mapping[i] =
2151 					       cpu_to_le16(vsi->base_queue + i);
2152 	} else {
2153 		ctxt->info.mapping_flags |=
2154 					cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
2155 		ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
2156 	}
2157 	ctxt->info.valid_sections |= cpu_to_le16(sections);
2158 }
2159 
2160 /**
2161  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
2162  * @netdev: the netdevice
2163  * @addr: address to add
2164  *
2165  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
2166  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2167  */
2168 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
2169 {
2170 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2171 	struct i40e_vsi *vsi = np->vsi;
2172 
2173 	if (i40e_add_mac_filter(vsi, addr))
2174 		return 0;
2175 	else
2176 		return -ENOMEM;
2177 }
2178 
2179 /**
2180  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
2181  * @netdev: the netdevice
2182  * @addr: address to add
2183  *
2184  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
2185  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2186  */
2187 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
2188 {
2189 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2190 	struct i40e_vsi *vsi = np->vsi;
2191 
2192 	/* Under some circumstances, we might receive a request to delete
2193 	 * our own device address from our uc list. Because we store the
2194 	 * device address in the VSI's MAC/VLAN filter list, we need to ignore
2195 	 * such requests and not delete our device address from this list.
2196 	 */
2197 	if (ether_addr_equal(addr, netdev->dev_addr))
2198 		return 0;
2199 
2200 	i40e_del_mac_filter(vsi, addr);
2201 
2202 	return 0;
2203 }
2204 
2205 /**
2206  * i40e_set_rx_mode - NDO callback to set the netdev filters
2207  * @netdev: network interface device structure
2208  **/
2209 static void i40e_set_rx_mode(struct net_device *netdev)
2210 {
2211 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2212 	struct i40e_vsi *vsi = np->vsi;
2213 
2214 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2215 
2216 	__dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2217 	__dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2218 
2219 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2220 
2221 	/* check for other flag changes */
2222 	if (vsi->current_netdev_flags != vsi->netdev->flags) {
2223 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2224 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
2225 	}
2226 }
2227 
2228 /**
2229  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
2230  * @vsi: Pointer to VSI struct
2231  * @from: Pointer to list which contains MAC filter entries - changes to
2232  *        those entries needs to be undone.
2233  *
2234  * MAC filter entries from this list were slated for deletion.
2235  **/
2236 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
2237 					 struct hlist_head *from)
2238 {
2239 	struct i40e_mac_filter *f;
2240 	struct hlist_node *h;
2241 
2242 	hlist_for_each_entry_safe(f, h, from, hlist) {
2243 		u64 key = i40e_addr_to_hkey(f->macaddr);
2244 
2245 		/* Move the element back into MAC filter list*/
2246 		hlist_del(&f->hlist);
2247 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
2248 	}
2249 }
2250 
2251 /**
2252  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
2253  * @vsi: Pointer to vsi struct
2254  * @from: Pointer to list which contains MAC filter entries - changes to
2255  *        those entries needs to be undone.
2256  *
2257  * MAC filter entries from this list were slated for addition.
2258  **/
2259 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
2260 					 struct hlist_head *from)
2261 {
2262 	struct i40e_new_mac_filter *new;
2263 	struct hlist_node *h;
2264 
2265 	hlist_for_each_entry_safe(new, h, from, hlist) {
2266 		/* We can simply free the wrapper structure */
2267 		hlist_del(&new->hlist);
2268 		netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2269 		kfree(new);
2270 	}
2271 }
2272 
2273 /**
2274  * i40e_next_filter - Get the next non-broadcast filter from a list
2275  * @next: pointer to filter in list
2276  *
2277  * Returns the next non-broadcast filter in the list. Required so that we
2278  * ignore broadcast filters within the list, since these are not handled via
2279  * the normal firmware update path.
2280  */
2281 static
2282 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2283 {
2284 	hlist_for_each_entry_continue(next, hlist) {
2285 		if (!is_broadcast_ether_addr(next->f->macaddr))
2286 			return next;
2287 	}
2288 
2289 	return NULL;
2290 }
2291 
2292 /**
2293  * i40e_update_filter_state - Update filter state based on return data
2294  * from firmware
2295  * @count: Number of filters added
2296  * @add_list: return data from fw
2297  * @add_head: pointer to first filter in current batch
2298  *
2299  * MAC filter entries from list were slated to be added to device. Returns
2300  * number of successful filters. Note that 0 does NOT mean success!
2301  **/
2302 static int
2303 i40e_update_filter_state(int count,
2304 			 struct i40e_aqc_add_macvlan_element_data *add_list,
2305 			 struct i40e_new_mac_filter *add_head)
2306 {
2307 	int retval = 0;
2308 	int i;
2309 
2310 	for (i = 0; i < count; i++) {
2311 		/* Always check status of each filter. We don't need to check
2312 		 * the firmware return status because we pre-set the filter
2313 		 * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2314 		 * request to the adminq. Thus, if it no longer matches then
2315 		 * we know the filter is active.
2316 		 */
2317 		if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2318 			add_head->state = I40E_FILTER_FAILED;
2319 		} else {
2320 			add_head->state = I40E_FILTER_ACTIVE;
2321 			retval++;
2322 		}
2323 
2324 		add_head = i40e_next_filter(add_head);
2325 		if (!add_head)
2326 			break;
2327 	}
2328 
2329 	return retval;
2330 }
2331 
2332 /**
2333  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2334  * @vsi: ptr to the VSI
2335  * @vsi_name: name to display in messages
2336  * @list: the list of filters to send to firmware
2337  * @num_del: the number of filters to delete
2338  * @retval: Set to -EIO on failure to delete
2339  *
2340  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2341  * *retval instead of a return value so that success does not force ret_val to
2342  * be set to 0. This ensures that a sequence of calls to this function
2343  * preserve the previous value of *retval on successful delete.
2344  */
2345 static
2346 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2347 			  struct i40e_aqc_remove_macvlan_element_data *list,
2348 			  int num_del, int *retval)
2349 {
2350 	struct i40e_hw *hw = &vsi->back->hw;
2351 	enum i40e_admin_queue_err aq_status;
2352 	int aq_ret;
2353 
2354 	aq_ret = i40e_aq_remove_macvlan_v2(hw, vsi->seid, list, num_del, NULL,
2355 					   &aq_status);
2356 
2357 	/* Explicitly ignore and do not report when firmware returns ENOENT */
2358 	if (aq_ret && !(aq_status == I40E_AQ_RC_ENOENT)) {
2359 		*retval = -EIO;
2360 		dev_info(&vsi->back->pdev->dev,
2361 			 "ignoring delete macvlan error on %s, err %pe, aq_err %s\n",
2362 			 vsi_name, ERR_PTR(aq_ret),
2363 			 i40e_aq_str(hw, aq_status));
2364 	}
2365 }
2366 
2367 /**
2368  * i40e_aqc_add_filters - Request firmware to add a set of filters
2369  * @vsi: ptr to the VSI
2370  * @vsi_name: name to display in messages
2371  * @list: the list of filters to send to firmware
2372  * @add_head: Position in the add hlist
2373  * @num_add: the number of filters to add
2374  *
2375  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2376  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2377  * space for more filters.
2378  */
2379 static
2380 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2381 			  struct i40e_aqc_add_macvlan_element_data *list,
2382 			  struct i40e_new_mac_filter *add_head,
2383 			  int num_add)
2384 {
2385 	struct i40e_hw *hw = &vsi->back->hw;
2386 	enum i40e_admin_queue_err aq_status;
2387 	int fcnt;
2388 
2389 	i40e_aq_add_macvlan_v2(hw, vsi->seid, list, num_add, NULL, &aq_status);
2390 	fcnt = i40e_update_filter_state(num_add, list, add_head);
2391 
2392 	if (fcnt != num_add) {
2393 		if (vsi->type == I40E_VSI_MAIN) {
2394 			set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2395 			dev_warn(&vsi->back->pdev->dev,
2396 				 "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2397 				 i40e_aq_str(hw, aq_status), vsi_name);
2398 		} else if (vsi->type == I40E_VSI_SRIOV ||
2399 			   vsi->type == I40E_VSI_VMDQ1 ||
2400 			   vsi->type == I40E_VSI_VMDQ2) {
2401 			dev_warn(&vsi->back->pdev->dev,
2402 				 "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2403 				 i40e_aq_str(hw, aq_status), vsi_name,
2404 					     vsi_name);
2405 		} else {
2406 			dev_warn(&vsi->back->pdev->dev,
2407 				 "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2408 				 i40e_aq_str(hw, aq_status), vsi_name,
2409 					     vsi->type);
2410 		}
2411 	}
2412 }
2413 
2414 /**
2415  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2416  * @vsi: pointer to the VSI
2417  * @vsi_name: the VSI name
2418  * @f: filter data
2419  *
2420  * This function sets or clears the promiscuous broadcast flags for VLAN
2421  * filters in order to properly receive broadcast frames. Assumes that only
2422  * broadcast filters are passed.
2423  *
2424  * Returns status indicating success or failure;
2425  **/
2426 static int
2427 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2428 			  struct i40e_mac_filter *f)
2429 {
2430 	bool enable = f->state == I40E_FILTER_NEW;
2431 	struct i40e_hw *hw = &vsi->back->hw;
2432 	int aq_ret;
2433 
2434 	if (f->vlan == I40E_VLAN_ANY) {
2435 		aq_ret = i40e_aq_set_vsi_broadcast(hw,
2436 						   vsi->seid,
2437 						   enable,
2438 						   NULL);
2439 	} else {
2440 		aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2441 							    vsi->seid,
2442 							    enable,
2443 							    f->vlan,
2444 							    NULL);
2445 	}
2446 
2447 	if (aq_ret) {
2448 		set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2449 		dev_warn(&vsi->back->pdev->dev,
2450 			 "Error %s, forcing overflow promiscuous on %s\n",
2451 			 i40e_aq_str(hw, hw->aq.asq_last_status),
2452 			 vsi_name);
2453 	}
2454 
2455 	return aq_ret;
2456 }
2457 
2458 /**
2459  * i40e_set_promiscuous - set promiscuous mode
2460  * @pf: board private structure
2461  * @promisc: promisc on or off
2462  *
2463  * There are different ways of setting promiscuous mode on a PF depending on
2464  * what state/environment we're in.  This identifies and sets it appropriately.
2465  * Returns 0 on success.
2466  **/
2467 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2468 {
2469 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
2470 	struct i40e_hw *hw = &pf->hw;
2471 	int aq_ret;
2472 
2473 	if (vsi->type == I40E_VSI_MAIN &&
2474 	    pf->lan_veb != I40E_NO_VEB &&
2475 	    !(pf->flags & I40E_FLAG_MFP_ENABLED)) {
2476 		/* set defport ON for Main VSI instead of true promisc
2477 		 * this way we will get all unicast/multicast and VLAN
2478 		 * promisc behavior but will not get VF or VMDq traffic
2479 		 * replicated on the Main VSI.
2480 		 */
2481 		if (promisc)
2482 			aq_ret = i40e_aq_set_default_vsi(hw,
2483 							 vsi->seid,
2484 							 NULL);
2485 		else
2486 			aq_ret = i40e_aq_clear_default_vsi(hw,
2487 							   vsi->seid,
2488 							   NULL);
2489 		if (aq_ret) {
2490 			dev_info(&pf->pdev->dev,
2491 				 "Set default VSI failed, err %pe, aq_err %s\n",
2492 				 ERR_PTR(aq_ret),
2493 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2494 		}
2495 	} else {
2496 		aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2497 						  hw,
2498 						  vsi->seid,
2499 						  promisc, NULL,
2500 						  true);
2501 		if (aq_ret) {
2502 			dev_info(&pf->pdev->dev,
2503 				 "set unicast promisc failed, err %pe, aq_err %s\n",
2504 				 ERR_PTR(aq_ret),
2505 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2506 		}
2507 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2508 						  hw,
2509 						  vsi->seid,
2510 						  promisc, NULL);
2511 		if (aq_ret) {
2512 			dev_info(&pf->pdev->dev,
2513 				 "set multicast promisc failed, err %pe, aq_err %s\n",
2514 				 ERR_PTR(aq_ret),
2515 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2516 		}
2517 	}
2518 
2519 	if (!aq_ret)
2520 		pf->cur_promisc = promisc;
2521 
2522 	return aq_ret;
2523 }
2524 
2525 /**
2526  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2527  * @vsi: ptr to the VSI
2528  *
2529  * Push any outstanding VSI filter changes through the AdminQ.
2530  *
2531  * Returns 0 or error value
2532  **/
2533 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2534 {
2535 	struct hlist_head tmp_add_list, tmp_del_list;
2536 	struct i40e_mac_filter *f;
2537 	struct i40e_new_mac_filter *new, *add_head = NULL;
2538 	struct i40e_hw *hw = &vsi->back->hw;
2539 	bool old_overflow, new_overflow;
2540 	unsigned int failed_filters = 0;
2541 	unsigned int vlan_filters = 0;
2542 	char vsi_name[16] = "PF";
2543 	int filter_list_len = 0;
2544 	u32 changed_flags = 0;
2545 	struct hlist_node *h;
2546 	struct i40e_pf *pf;
2547 	int num_add = 0;
2548 	int num_del = 0;
2549 	int aq_ret = 0;
2550 	int retval = 0;
2551 	u16 cmd_flags;
2552 	int list_size;
2553 	int bkt;
2554 
2555 	/* empty array typed pointers, kcalloc later */
2556 	struct i40e_aqc_add_macvlan_element_data *add_list;
2557 	struct i40e_aqc_remove_macvlan_element_data *del_list;
2558 
2559 	while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2560 		usleep_range(1000, 2000);
2561 	pf = vsi->back;
2562 
2563 	old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2564 
2565 	if (vsi->netdev) {
2566 		changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2567 		vsi->current_netdev_flags = vsi->netdev->flags;
2568 	}
2569 
2570 	INIT_HLIST_HEAD(&tmp_add_list);
2571 	INIT_HLIST_HEAD(&tmp_del_list);
2572 
2573 	if (vsi->type == I40E_VSI_SRIOV)
2574 		snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2575 	else if (vsi->type != I40E_VSI_MAIN)
2576 		snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2577 
2578 	if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2579 		vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2580 
2581 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2582 		/* Create a list of filters to delete. */
2583 		hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2584 			if (f->state == I40E_FILTER_REMOVE) {
2585 				/* Move the element into temporary del_list */
2586 				hash_del(&f->hlist);
2587 				hlist_add_head(&f->hlist, &tmp_del_list);
2588 
2589 				/* Avoid counting removed filters */
2590 				continue;
2591 			}
2592 			if (f->state == I40E_FILTER_NEW) {
2593 				/* Create a temporary i40e_new_mac_filter */
2594 				new = kzalloc(sizeof(*new), GFP_ATOMIC);
2595 				if (!new)
2596 					goto err_no_memory_locked;
2597 
2598 				/* Store pointer to the real filter */
2599 				new->f = f;
2600 				new->state = f->state;
2601 
2602 				/* Add it to the hash list */
2603 				hlist_add_head(&new->hlist, &tmp_add_list);
2604 			}
2605 
2606 			/* Count the number of active (current and new) VLAN
2607 			 * filters we have now. Does not count filters which
2608 			 * are marked for deletion.
2609 			 */
2610 			if (f->vlan > 0)
2611 				vlan_filters++;
2612 		}
2613 
2614 		if (vsi->type != I40E_VSI_SRIOV)
2615 			retval = i40e_correct_mac_vlan_filters
2616 				(vsi, &tmp_add_list, &tmp_del_list,
2617 				 vlan_filters);
2618 		else
2619 			retval = i40e_correct_vf_mac_vlan_filters
2620 				(vsi, &tmp_add_list, &tmp_del_list,
2621 				 vlan_filters, pf->vf[vsi->vf_id].trusted);
2622 
2623 		hlist_for_each_entry(new, &tmp_add_list, hlist)
2624 			netdev_hw_addr_refcnt(new->f, vsi->netdev, 1);
2625 
2626 		if (retval)
2627 			goto err_no_memory_locked;
2628 
2629 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2630 	}
2631 
2632 	/* Now process 'del_list' outside the lock */
2633 	if (!hlist_empty(&tmp_del_list)) {
2634 		filter_list_len = hw->aq.asq_buf_size /
2635 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2636 		list_size = filter_list_len *
2637 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2638 		del_list = kzalloc(list_size, GFP_ATOMIC);
2639 		if (!del_list)
2640 			goto err_no_memory;
2641 
2642 		hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2643 			cmd_flags = 0;
2644 
2645 			/* handle broadcast filters by updating the broadcast
2646 			 * promiscuous flag and release filter list.
2647 			 */
2648 			if (is_broadcast_ether_addr(f->macaddr)) {
2649 				i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2650 
2651 				hlist_del(&f->hlist);
2652 				kfree(f);
2653 				continue;
2654 			}
2655 
2656 			/* add to delete list */
2657 			ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2658 			if (f->vlan == I40E_VLAN_ANY) {
2659 				del_list[num_del].vlan_tag = 0;
2660 				cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2661 			} else {
2662 				del_list[num_del].vlan_tag =
2663 					cpu_to_le16((u16)(f->vlan));
2664 			}
2665 
2666 			cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2667 			del_list[num_del].flags = cmd_flags;
2668 			num_del++;
2669 
2670 			/* flush a full buffer */
2671 			if (num_del == filter_list_len) {
2672 				i40e_aqc_del_filters(vsi, vsi_name, del_list,
2673 						     num_del, &retval);
2674 				memset(del_list, 0, list_size);
2675 				num_del = 0;
2676 			}
2677 			/* Release memory for MAC filter entries which were
2678 			 * synced up with HW.
2679 			 */
2680 			hlist_del(&f->hlist);
2681 			kfree(f);
2682 		}
2683 
2684 		if (num_del) {
2685 			i40e_aqc_del_filters(vsi, vsi_name, del_list,
2686 					     num_del, &retval);
2687 		}
2688 
2689 		kfree(del_list);
2690 		del_list = NULL;
2691 	}
2692 
2693 	if (!hlist_empty(&tmp_add_list)) {
2694 		/* Do all the adds now. */
2695 		filter_list_len = hw->aq.asq_buf_size /
2696 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2697 		list_size = filter_list_len *
2698 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2699 		add_list = kzalloc(list_size, GFP_ATOMIC);
2700 		if (!add_list)
2701 			goto err_no_memory;
2702 
2703 		num_add = 0;
2704 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2705 			/* handle broadcast filters by updating the broadcast
2706 			 * promiscuous flag instead of adding a MAC filter.
2707 			 */
2708 			if (is_broadcast_ether_addr(new->f->macaddr)) {
2709 				if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2710 							      new->f))
2711 					new->state = I40E_FILTER_FAILED;
2712 				else
2713 					new->state = I40E_FILTER_ACTIVE;
2714 				continue;
2715 			}
2716 
2717 			/* add to add array */
2718 			if (num_add == 0)
2719 				add_head = new;
2720 			cmd_flags = 0;
2721 			ether_addr_copy(add_list[num_add].mac_addr,
2722 					new->f->macaddr);
2723 			if (new->f->vlan == I40E_VLAN_ANY) {
2724 				add_list[num_add].vlan_tag = 0;
2725 				cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2726 			} else {
2727 				add_list[num_add].vlan_tag =
2728 					cpu_to_le16((u16)(new->f->vlan));
2729 			}
2730 			add_list[num_add].queue_number = 0;
2731 			/* set invalid match method for later detection */
2732 			add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2733 			cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2734 			add_list[num_add].flags = cpu_to_le16(cmd_flags);
2735 			num_add++;
2736 
2737 			/* flush a full buffer */
2738 			if (num_add == filter_list_len) {
2739 				i40e_aqc_add_filters(vsi, vsi_name, add_list,
2740 						     add_head, num_add);
2741 				memset(add_list, 0, list_size);
2742 				num_add = 0;
2743 			}
2744 		}
2745 		if (num_add) {
2746 			i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2747 					     num_add);
2748 		}
2749 		/* Now move all of the filters from the temp add list back to
2750 		 * the VSI's list.
2751 		 */
2752 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2753 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2754 			/* Only update the state if we're still NEW */
2755 			if (new->f->state == I40E_FILTER_NEW)
2756 				new->f->state = new->state;
2757 			hlist_del(&new->hlist);
2758 			netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2759 			kfree(new);
2760 		}
2761 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2762 		kfree(add_list);
2763 		add_list = NULL;
2764 	}
2765 
2766 	/* Determine the number of active and failed filters. */
2767 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2768 	vsi->active_filters = 0;
2769 	hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2770 		if (f->state == I40E_FILTER_ACTIVE)
2771 			vsi->active_filters++;
2772 		else if (f->state == I40E_FILTER_FAILED)
2773 			failed_filters++;
2774 	}
2775 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2776 
2777 	/* Check if we are able to exit overflow promiscuous mode. We can
2778 	 * safely exit if we didn't just enter, we no longer have any failed
2779 	 * filters, and we have reduced filters below the threshold value.
2780 	 */
2781 	if (old_overflow && !failed_filters &&
2782 	    vsi->active_filters < vsi->promisc_threshold) {
2783 		dev_info(&pf->pdev->dev,
2784 			 "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2785 			 vsi_name);
2786 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2787 		vsi->promisc_threshold = 0;
2788 	}
2789 
2790 	/* if the VF is not trusted do not do promisc */
2791 	if ((vsi->type == I40E_VSI_SRIOV) && !pf->vf[vsi->vf_id].trusted) {
2792 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2793 		goto out;
2794 	}
2795 
2796 	new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2797 
2798 	/* If we are entering overflow promiscuous, we need to calculate a new
2799 	 * threshold for when we are safe to exit
2800 	 */
2801 	if (!old_overflow && new_overflow)
2802 		vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2803 
2804 	/* check for changes in promiscuous modes */
2805 	if (changed_flags & IFF_ALLMULTI) {
2806 		bool cur_multipromisc;
2807 
2808 		cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2809 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2810 							       vsi->seid,
2811 							       cur_multipromisc,
2812 							       NULL);
2813 		if (aq_ret) {
2814 			retval = i40e_aq_rc_to_posix(aq_ret,
2815 						     hw->aq.asq_last_status);
2816 			dev_info(&pf->pdev->dev,
2817 				 "set multi promisc failed on %s, err %pe aq_err %s\n",
2818 				 vsi_name,
2819 				 ERR_PTR(aq_ret),
2820 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2821 		} else {
2822 			dev_info(&pf->pdev->dev, "%s allmulti mode.\n",
2823 				 cur_multipromisc ? "entering" : "leaving");
2824 		}
2825 	}
2826 
2827 	if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2828 		bool cur_promisc;
2829 
2830 		cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2831 			       new_overflow);
2832 		aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2833 		if (aq_ret) {
2834 			retval = i40e_aq_rc_to_posix(aq_ret,
2835 						     hw->aq.asq_last_status);
2836 			dev_info(&pf->pdev->dev,
2837 				 "Setting promiscuous %s failed on %s, err %pe aq_err %s\n",
2838 				 cur_promisc ? "on" : "off",
2839 				 vsi_name,
2840 				 ERR_PTR(aq_ret),
2841 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2842 		}
2843 	}
2844 out:
2845 	/* if something went wrong then set the changed flag so we try again */
2846 	if (retval)
2847 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2848 
2849 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2850 	return retval;
2851 
2852 err_no_memory:
2853 	/* Restore elements on the temporary add and delete lists */
2854 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2855 err_no_memory_locked:
2856 	i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2857 	i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2858 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2859 
2860 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2861 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2862 	return -ENOMEM;
2863 }
2864 
2865 /**
2866  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2867  * @pf: board private structure
2868  **/
2869 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2870 {
2871 	int v;
2872 
2873 	if (!pf)
2874 		return;
2875 	if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2876 		return;
2877 	if (test_bit(__I40E_VF_DISABLE, pf->state)) {
2878 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
2879 		return;
2880 	}
2881 
2882 	for (v = 0; v < pf->num_alloc_vsi; v++) {
2883 		if (pf->vsi[v] &&
2884 		    (pf->vsi[v]->flags & I40E_VSI_FLAG_FILTER_CHANGED) &&
2885 		    !test_bit(__I40E_VSI_RELEASING, pf->vsi[v]->state)) {
2886 			int ret = i40e_sync_vsi_filters(pf->vsi[v]);
2887 
2888 			if (ret) {
2889 				/* come back and try again later */
2890 				set_bit(__I40E_MACVLAN_SYNC_PENDING,
2891 					pf->state);
2892 				break;
2893 			}
2894 		}
2895 	}
2896 }
2897 
2898 /**
2899  * i40e_calculate_vsi_rx_buf_len - Calculates buffer length
2900  *
2901  * @vsi: VSI to calculate rx_buf_len from
2902  */
2903 static u16 i40e_calculate_vsi_rx_buf_len(struct i40e_vsi *vsi)
2904 {
2905 	if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
2906 		return SKB_WITH_OVERHEAD(I40E_RXBUFFER_2048);
2907 
2908 	return PAGE_SIZE < 8192 ? I40E_RXBUFFER_3072 : I40E_RXBUFFER_2048;
2909 }
2910 
2911 /**
2912  * i40e_max_vsi_frame_size - returns the maximum allowed frame size for VSI
2913  * @vsi: the vsi
2914  * @xdp_prog: XDP program
2915  **/
2916 static int i40e_max_vsi_frame_size(struct i40e_vsi *vsi,
2917 				   struct bpf_prog *xdp_prog)
2918 {
2919 	u16 rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
2920 	u16 chain_len;
2921 
2922 	if (xdp_prog && !xdp_prog->aux->xdp_has_frags)
2923 		chain_len = 1;
2924 	else
2925 		chain_len = I40E_MAX_CHAINED_RX_BUFFERS;
2926 
2927 	return min_t(u16, rx_buf_len * chain_len, I40E_MAX_RXBUFFER);
2928 }
2929 
2930 /**
2931  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2932  * @netdev: network interface device structure
2933  * @new_mtu: new value for maximum frame size
2934  *
2935  * Returns 0 on success, negative on failure
2936  **/
2937 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2938 {
2939 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2940 	struct i40e_vsi *vsi = np->vsi;
2941 	struct i40e_pf *pf = vsi->back;
2942 	int frame_size;
2943 
2944 	frame_size = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
2945 	if (new_mtu > frame_size - I40E_PACKET_HDR_PAD) {
2946 		netdev_err(netdev, "Error changing mtu to %d, Max is %d\n",
2947 			   new_mtu, frame_size - I40E_PACKET_HDR_PAD);
2948 		return -EINVAL;
2949 	}
2950 
2951 	netdev_dbg(netdev, "changing MTU from %d to %d\n",
2952 		   netdev->mtu, new_mtu);
2953 	netdev->mtu = new_mtu;
2954 	if (netif_running(netdev))
2955 		i40e_vsi_reinit_locked(vsi);
2956 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2957 	set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2958 	return 0;
2959 }
2960 
2961 /**
2962  * i40e_ioctl - Access the hwtstamp interface
2963  * @netdev: network interface device structure
2964  * @ifr: interface request data
2965  * @cmd: ioctl command
2966  **/
2967 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2968 {
2969 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2970 	struct i40e_pf *pf = np->vsi->back;
2971 
2972 	switch (cmd) {
2973 	case SIOCGHWTSTAMP:
2974 		return i40e_ptp_get_ts_config(pf, ifr);
2975 	case SIOCSHWTSTAMP:
2976 		return i40e_ptp_set_ts_config(pf, ifr);
2977 	default:
2978 		return -EOPNOTSUPP;
2979 	}
2980 }
2981 
2982 /**
2983  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2984  * @vsi: the vsi being adjusted
2985  **/
2986 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2987 {
2988 	struct i40e_vsi_context ctxt;
2989 	int ret;
2990 
2991 	/* Don't modify stripping options if a port VLAN is active */
2992 	if (vsi->info.pvid)
2993 		return;
2994 
2995 	if ((vsi->info.valid_sections &
2996 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2997 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2998 		return;  /* already enabled */
2999 
3000 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3001 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3002 				    I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
3003 
3004 	ctxt.seid = vsi->seid;
3005 	ctxt.info = vsi->info;
3006 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3007 	if (ret) {
3008 		dev_info(&vsi->back->pdev->dev,
3009 			 "update vlan stripping failed, err %pe aq_err %s\n",
3010 			 ERR_PTR(ret),
3011 			 i40e_aq_str(&vsi->back->hw,
3012 				     vsi->back->hw.aq.asq_last_status));
3013 	}
3014 }
3015 
3016 /**
3017  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
3018  * @vsi: the vsi being adjusted
3019  **/
3020 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
3021 {
3022 	struct i40e_vsi_context ctxt;
3023 	int ret;
3024 
3025 	/* Don't modify stripping options if a port VLAN is active */
3026 	if (vsi->info.pvid)
3027 		return;
3028 
3029 	if ((vsi->info.valid_sections &
3030 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
3031 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
3032 	     I40E_AQ_VSI_PVLAN_EMOD_MASK))
3033 		return;  /* already disabled */
3034 
3035 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3036 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3037 				    I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
3038 
3039 	ctxt.seid = vsi->seid;
3040 	ctxt.info = vsi->info;
3041 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3042 	if (ret) {
3043 		dev_info(&vsi->back->pdev->dev,
3044 			 "update vlan stripping failed, err %pe aq_err %s\n",
3045 			 ERR_PTR(ret),
3046 			 i40e_aq_str(&vsi->back->hw,
3047 				     vsi->back->hw.aq.asq_last_status));
3048 	}
3049 }
3050 
3051 /**
3052  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
3053  * @vsi: the vsi being configured
3054  * @vid: vlan id to be added (0 = untagged only , -1 = any)
3055  *
3056  * This is a helper function for adding a new MAC/VLAN filter with the
3057  * specified VLAN for each existing MAC address already in the hash table.
3058  * This function does *not* perform any accounting to update filters based on
3059  * VLAN mode.
3060  *
3061  * NOTE: this function expects to be called while under the
3062  * mac_filter_hash_lock
3063  **/
3064 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3065 {
3066 	struct i40e_mac_filter *f, *add_f;
3067 	struct hlist_node *h;
3068 	int bkt;
3069 
3070 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3071 		/* If we're asked to add a filter that has been marked for
3072 		 * removal, it is safe to simply restore it to active state.
3073 		 * __i40e_del_filter will have simply deleted any filters which
3074 		 * were previously marked NEW or FAILED, so if it is currently
3075 		 * marked REMOVE it must have previously been ACTIVE. Since we
3076 		 * haven't yet run the sync filters task, just restore this
3077 		 * filter to the ACTIVE state so that the sync task leaves it
3078 		 * in place.
3079 		 */
3080 		if (f->state == I40E_FILTER_REMOVE && f->vlan == vid) {
3081 			f->state = I40E_FILTER_ACTIVE;
3082 			continue;
3083 		} else if (f->state == I40E_FILTER_REMOVE) {
3084 			continue;
3085 		}
3086 		add_f = i40e_add_filter(vsi, f->macaddr, vid);
3087 		if (!add_f) {
3088 			dev_info(&vsi->back->pdev->dev,
3089 				 "Could not add vlan filter %d for %pM\n",
3090 				 vid, f->macaddr);
3091 			return -ENOMEM;
3092 		}
3093 	}
3094 
3095 	return 0;
3096 }
3097 
3098 /**
3099  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
3100  * @vsi: the VSI being configured
3101  * @vid: VLAN id to be added
3102  **/
3103 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
3104 {
3105 	int err;
3106 
3107 	if (vsi->info.pvid)
3108 		return -EINVAL;
3109 
3110 	/* The network stack will attempt to add VID=0, with the intention to
3111 	 * receive priority tagged packets with a VLAN of 0. Our HW receives
3112 	 * these packets by default when configured to receive untagged
3113 	 * packets, so we don't need to add a filter for this case.
3114 	 * Additionally, HW interprets adding a VID=0 filter as meaning to
3115 	 * receive *only* tagged traffic and stops receiving untagged traffic.
3116 	 * Thus, we do not want to actually add a filter for VID=0
3117 	 */
3118 	if (!vid)
3119 		return 0;
3120 
3121 	/* Locked once because all functions invoked below iterates list*/
3122 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3123 	err = i40e_add_vlan_all_mac(vsi, vid);
3124 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3125 	if (err)
3126 		return err;
3127 
3128 	/* schedule our worker thread which will take care of
3129 	 * applying the new filter changes
3130 	 */
3131 	i40e_service_event_schedule(vsi->back);
3132 	return 0;
3133 }
3134 
3135 /**
3136  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
3137  * @vsi: the vsi being configured
3138  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
3139  *
3140  * This function should be used to remove all VLAN filters which match the
3141  * given VID. It does not schedule the service event and does not take the
3142  * mac_filter_hash_lock so it may be combined with other operations under
3143  * a single invocation of the mac_filter_hash_lock.
3144  *
3145  * NOTE: this function expects to be called while under the
3146  * mac_filter_hash_lock
3147  */
3148 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3149 {
3150 	struct i40e_mac_filter *f;
3151 	struct hlist_node *h;
3152 	int bkt;
3153 
3154 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3155 		if (f->vlan == vid)
3156 			__i40e_del_filter(vsi, f);
3157 	}
3158 }
3159 
3160 /**
3161  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
3162  * @vsi: the VSI being configured
3163  * @vid: VLAN id to be removed
3164  **/
3165 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
3166 {
3167 	if (!vid || vsi->info.pvid)
3168 		return;
3169 
3170 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3171 	i40e_rm_vlan_all_mac(vsi, vid);
3172 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3173 
3174 	/* schedule our worker thread which will take care of
3175 	 * applying the new filter changes
3176 	 */
3177 	i40e_service_event_schedule(vsi->back);
3178 }
3179 
3180 /**
3181  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
3182  * @netdev: network interface to be adjusted
3183  * @proto: unused protocol value
3184  * @vid: vlan id to be added
3185  *
3186  * net_device_ops implementation for adding vlan ids
3187  **/
3188 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
3189 				__always_unused __be16 proto, u16 vid)
3190 {
3191 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3192 	struct i40e_vsi *vsi = np->vsi;
3193 	int ret = 0;
3194 
3195 	if (vid >= VLAN_N_VID)
3196 		return -EINVAL;
3197 
3198 	ret = i40e_vsi_add_vlan(vsi, vid);
3199 	if (!ret)
3200 		set_bit(vid, vsi->active_vlans);
3201 
3202 	return ret;
3203 }
3204 
3205 /**
3206  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
3207  * @netdev: network interface to be adjusted
3208  * @proto: unused protocol value
3209  * @vid: vlan id to be added
3210  **/
3211 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
3212 				    __always_unused __be16 proto, u16 vid)
3213 {
3214 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3215 	struct i40e_vsi *vsi = np->vsi;
3216 
3217 	if (vid >= VLAN_N_VID)
3218 		return;
3219 	set_bit(vid, vsi->active_vlans);
3220 }
3221 
3222 /**
3223  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
3224  * @netdev: network interface to be adjusted
3225  * @proto: unused protocol value
3226  * @vid: vlan id to be removed
3227  *
3228  * net_device_ops implementation for removing vlan ids
3229  **/
3230 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
3231 				 __always_unused __be16 proto, u16 vid)
3232 {
3233 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3234 	struct i40e_vsi *vsi = np->vsi;
3235 
3236 	/* return code is ignored as there is nothing a user
3237 	 * can do about failure to remove and a log message was
3238 	 * already printed from the other function
3239 	 */
3240 	i40e_vsi_kill_vlan(vsi, vid);
3241 
3242 	clear_bit(vid, vsi->active_vlans);
3243 
3244 	return 0;
3245 }
3246 
3247 /**
3248  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
3249  * @vsi: the vsi being brought back up
3250  **/
3251 static void i40e_restore_vlan(struct i40e_vsi *vsi)
3252 {
3253 	u16 vid;
3254 
3255 	if (!vsi->netdev)
3256 		return;
3257 
3258 	if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
3259 		i40e_vlan_stripping_enable(vsi);
3260 	else
3261 		i40e_vlan_stripping_disable(vsi);
3262 
3263 	for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
3264 		i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
3265 					vid);
3266 }
3267 
3268 /**
3269  * i40e_vsi_add_pvid - Add pvid for the VSI
3270  * @vsi: the vsi being adjusted
3271  * @vid: the vlan id to set as a PVID
3272  **/
3273 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
3274 {
3275 	struct i40e_vsi_context ctxt;
3276 	int ret;
3277 
3278 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3279 	vsi->info.pvid = cpu_to_le16(vid);
3280 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
3281 				    I40E_AQ_VSI_PVLAN_INSERT_PVID |
3282 				    I40E_AQ_VSI_PVLAN_EMOD_STR;
3283 
3284 	ctxt.seid = vsi->seid;
3285 	ctxt.info = vsi->info;
3286 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3287 	if (ret) {
3288 		dev_info(&vsi->back->pdev->dev,
3289 			 "add pvid failed, err %pe aq_err %s\n",
3290 			 ERR_PTR(ret),
3291 			 i40e_aq_str(&vsi->back->hw,
3292 				     vsi->back->hw.aq.asq_last_status));
3293 		return -ENOENT;
3294 	}
3295 
3296 	return 0;
3297 }
3298 
3299 /**
3300  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
3301  * @vsi: the vsi being adjusted
3302  *
3303  * Just use the vlan_rx_register() service to put it back to normal
3304  **/
3305 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
3306 {
3307 	vsi->info.pvid = 0;
3308 
3309 	i40e_vlan_stripping_disable(vsi);
3310 }
3311 
3312 /**
3313  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
3314  * @vsi: ptr to the VSI
3315  *
3316  * If this function returns with an error, then it's possible one or
3317  * more of the rings is populated (while the rest are not).  It is the
3318  * callers duty to clean those orphaned rings.
3319  *
3320  * Return 0 on success, negative on failure
3321  **/
3322 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3323 {
3324 	int i, err = 0;
3325 
3326 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3327 		err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3328 
3329 	if (!i40e_enabled_xdp_vsi(vsi))
3330 		return err;
3331 
3332 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3333 		err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3334 
3335 	return err;
3336 }
3337 
3338 /**
3339  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3340  * @vsi: ptr to the VSI
3341  *
3342  * Free VSI's transmit software resources
3343  **/
3344 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3345 {
3346 	int i;
3347 
3348 	if (vsi->tx_rings) {
3349 		for (i = 0; i < vsi->num_queue_pairs; i++)
3350 			if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3351 				i40e_free_tx_resources(vsi->tx_rings[i]);
3352 	}
3353 
3354 	if (vsi->xdp_rings) {
3355 		for (i = 0; i < vsi->num_queue_pairs; i++)
3356 			if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3357 				i40e_free_tx_resources(vsi->xdp_rings[i]);
3358 	}
3359 }
3360 
3361 /**
3362  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3363  * @vsi: ptr to the VSI
3364  *
3365  * If this function returns with an error, then it's possible one or
3366  * more of the rings is populated (while the rest are not).  It is the
3367  * callers duty to clean those orphaned rings.
3368  *
3369  * Return 0 on success, negative on failure
3370  **/
3371 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3372 {
3373 	int i, err = 0;
3374 
3375 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3376 		err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3377 	return err;
3378 }
3379 
3380 /**
3381  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3382  * @vsi: ptr to the VSI
3383  *
3384  * Free all receive software resources
3385  **/
3386 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3387 {
3388 	int i;
3389 
3390 	if (!vsi->rx_rings)
3391 		return;
3392 
3393 	for (i = 0; i < vsi->num_queue_pairs; i++)
3394 		if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3395 			i40e_free_rx_resources(vsi->rx_rings[i]);
3396 }
3397 
3398 /**
3399  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3400  * @ring: The Tx ring to configure
3401  *
3402  * This enables/disables XPS for a given Tx descriptor ring
3403  * based on the TCs enabled for the VSI that ring belongs to.
3404  **/
3405 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3406 {
3407 	int cpu;
3408 
3409 	if (!ring->q_vector || !ring->netdev || ring->ch)
3410 		return;
3411 
3412 	/* We only initialize XPS once, so as not to overwrite user settings */
3413 	if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3414 		return;
3415 
3416 	cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3417 	netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3418 			    ring->queue_index);
3419 }
3420 
3421 /**
3422  * i40e_xsk_pool - Retrieve the AF_XDP buffer pool if XDP and ZC is enabled
3423  * @ring: The Tx or Rx ring
3424  *
3425  * Returns the AF_XDP buffer pool or NULL.
3426  **/
3427 static struct xsk_buff_pool *i40e_xsk_pool(struct i40e_ring *ring)
3428 {
3429 	bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3430 	int qid = ring->queue_index;
3431 
3432 	if (ring_is_xdp(ring))
3433 		qid -= ring->vsi->alloc_queue_pairs;
3434 
3435 	if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3436 		return NULL;
3437 
3438 	return xsk_get_pool_from_qid(ring->vsi->netdev, qid);
3439 }
3440 
3441 /**
3442  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3443  * @ring: The Tx ring to configure
3444  *
3445  * Configure the Tx descriptor ring in the HMC context.
3446  **/
3447 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3448 {
3449 	struct i40e_vsi *vsi = ring->vsi;
3450 	u16 pf_q = vsi->base_queue + ring->queue_index;
3451 	struct i40e_hw *hw = &vsi->back->hw;
3452 	struct i40e_hmc_obj_txq tx_ctx;
3453 	u32 qtx_ctl = 0;
3454 	int err = 0;
3455 
3456 	if (ring_is_xdp(ring))
3457 		ring->xsk_pool = i40e_xsk_pool(ring);
3458 
3459 	/* some ATR related tx ring init */
3460 	if (vsi->back->flags & I40E_FLAG_FD_ATR_ENABLED) {
3461 		ring->atr_sample_rate = vsi->back->atr_sample_rate;
3462 		ring->atr_count = 0;
3463 	} else {
3464 		ring->atr_sample_rate = 0;
3465 	}
3466 
3467 	/* configure XPS */
3468 	i40e_config_xps_tx_ring(ring);
3469 
3470 	/* clear the context structure first */
3471 	memset(&tx_ctx, 0, sizeof(tx_ctx));
3472 
3473 	tx_ctx.new_context = 1;
3474 	tx_ctx.base = (ring->dma / 128);
3475 	tx_ctx.qlen = ring->count;
3476 	tx_ctx.fd_ena = !!(vsi->back->flags & (I40E_FLAG_FD_SB_ENABLED |
3477 					       I40E_FLAG_FD_ATR_ENABLED));
3478 	tx_ctx.timesync_ena = !!(vsi->back->flags & I40E_FLAG_PTP);
3479 	/* FDIR VSI tx ring can still use RS bit and writebacks */
3480 	if (vsi->type != I40E_VSI_FDIR)
3481 		tx_ctx.head_wb_ena = 1;
3482 	tx_ctx.head_wb_addr = ring->dma +
3483 			      (ring->count * sizeof(struct i40e_tx_desc));
3484 
3485 	/* As part of VSI creation/update, FW allocates certain
3486 	 * Tx arbitration queue sets for each TC enabled for
3487 	 * the VSI. The FW returns the handles to these queue
3488 	 * sets as part of the response buffer to Add VSI,
3489 	 * Update VSI, etc. AQ commands. It is expected that
3490 	 * these queue set handles be associated with the Tx
3491 	 * queues by the driver as part of the TX queue context
3492 	 * initialization. This has to be done regardless of
3493 	 * DCB as by default everything is mapped to TC0.
3494 	 */
3495 
3496 	if (ring->ch)
3497 		tx_ctx.rdylist =
3498 			le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3499 
3500 	else
3501 		tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3502 
3503 	tx_ctx.rdylist_act = 0;
3504 
3505 	/* clear the context in the HMC */
3506 	err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3507 	if (err) {
3508 		dev_info(&vsi->back->pdev->dev,
3509 			 "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3510 			 ring->queue_index, pf_q, err);
3511 		return -ENOMEM;
3512 	}
3513 
3514 	/* set the context in the HMC */
3515 	err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3516 	if (err) {
3517 		dev_info(&vsi->back->pdev->dev,
3518 			 "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3519 			 ring->queue_index, pf_q, err);
3520 		return -ENOMEM;
3521 	}
3522 
3523 	/* Now associate this queue with this PCI function */
3524 	if (ring->ch) {
3525 		if (ring->ch->type == I40E_VSI_VMDQ2)
3526 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3527 		else
3528 			return -EINVAL;
3529 
3530 		qtx_ctl |= (ring->ch->vsi_number <<
3531 			    I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3532 			    I40E_QTX_CTL_VFVM_INDX_MASK;
3533 	} else {
3534 		if (vsi->type == I40E_VSI_VMDQ2) {
3535 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3536 			qtx_ctl |= ((vsi->id) << I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3537 				    I40E_QTX_CTL_VFVM_INDX_MASK;
3538 		} else {
3539 			qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3540 		}
3541 	}
3542 
3543 	qtx_ctl |= ((hw->pf_id << I40E_QTX_CTL_PF_INDX_SHIFT) &
3544 		    I40E_QTX_CTL_PF_INDX_MASK);
3545 	wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3546 	i40e_flush(hw);
3547 
3548 	/* cache tail off for easier writes later */
3549 	ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3550 
3551 	return 0;
3552 }
3553 
3554 /**
3555  * i40e_rx_offset - Return expected offset into page to access data
3556  * @rx_ring: Ring we are requesting offset of
3557  *
3558  * Returns the offset value for ring into the data buffer.
3559  */
3560 static unsigned int i40e_rx_offset(struct i40e_ring *rx_ring)
3561 {
3562 	return ring_uses_build_skb(rx_ring) ? I40E_SKB_PAD : 0;
3563 }
3564 
3565 /**
3566  * i40e_configure_rx_ring - Configure a receive ring context
3567  * @ring: The Rx ring to configure
3568  *
3569  * Configure the Rx descriptor ring in the HMC context.
3570  **/
3571 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3572 {
3573 	struct i40e_vsi *vsi = ring->vsi;
3574 	u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3575 	u16 pf_q = vsi->base_queue + ring->queue_index;
3576 	struct i40e_hw *hw = &vsi->back->hw;
3577 	struct i40e_hmc_obj_rxq rx_ctx;
3578 	int err = 0;
3579 	bool ok;
3580 	int ret;
3581 
3582 	bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3583 
3584 	/* clear the context structure first */
3585 	memset(&rx_ctx, 0, sizeof(rx_ctx));
3586 
3587 	if (ring->vsi->type == I40E_VSI_MAIN)
3588 		xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq);
3589 
3590 	ring->xsk_pool = i40e_xsk_pool(ring);
3591 	if (ring->xsk_pool) {
3592 		ring->rx_buf_len =
3593 		  xsk_pool_get_rx_frame_size(ring->xsk_pool);
3594 		/* For AF_XDP ZC, we disallow packets to span on
3595 		 * multiple buffers, thus letting us skip that
3596 		 * handling in the fast-path.
3597 		 */
3598 		chain_len = 1;
3599 		ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3600 						 MEM_TYPE_XSK_BUFF_POOL,
3601 						 NULL);
3602 		if (ret)
3603 			return ret;
3604 		dev_info(&vsi->back->pdev->dev,
3605 			 "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n",
3606 			 ring->queue_index);
3607 
3608 	} else {
3609 		ring->rx_buf_len = vsi->rx_buf_len;
3610 		if (ring->vsi->type == I40E_VSI_MAIN) {
3611 			ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3612 							 MEM_TYPE_PAGE_SHARED,
3613 							 NULL);
3614 			if (ret)
3615 				return ret;
3616 		}
3617 	}
3618 
3619 	xdp_init_buff(&ring->xdp, i40e_rx_pg_size(ring) / 2, &ring->xdp_rxq);
3620 
3621 	rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3622 				    BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3623 
3624 	rx_ctx.base = (ring->dma / 128);
3625 	rx_ctx.qlen = ring->count;
3626 
3627 	/* use 16 byte descriptors */
3628 	rx_ctx.dsize = 0;
3629 
3630 	/* descriptor type is always zero
3631 	 * rx_ctx.dtype = 0;
3632 	 */
3633 	rx_ctx.hsplit_0 = 0;
3634 
3635 	rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3636 	if (hw->revision_id == 0)
3637 		rx_ctx.lrxqthresh = 0;
3638 	else
3639 		rx_ctx.lrxqthresh = 1;
3640 	rx_ctx.crcstrip = 1;
3641 	rx_ctx.l2tsel = 1;
3642 	/* this controls whether VLAN is stripped from inner headers */
3643 	rx_ctx.showiv = 0;
3644 	/* set the prefena field to 1 because the manual says to */
3645 	rx_ctx.prefena = 1;
3646 
3647 	/* clear the context in the HMC */
3648 	err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3649 	if (err) {
3650 		dev_info(&vsi->back->pdev->dev,
3651 			 "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3652 			 ring->queue_index, pf_q, err);
3653 		return -ENOMEM;
3654 	}
3655 
3656 	/* set the context in the HMC */
3657 	err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3658 	if (err) {
3659 		dev_info(&vsi->back->pdev->dev,
3660 			 "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3661 			 ring->queue_index, pf_q, err);
3662 		return -ENOMEM;
3663 	}
3664 
3665 	/* configure Rx buffer alignment */
3666 	if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX)) {
3667 		if (I40E_2K_TOO_SMALL_WITH_PADDING) {
3668 			dev_info(&vsi->back->pdev->dev,
3669 				 "2k Rx buffer is too small to fit standard MTU and skb_shared_info\n");
3670 			return -EOPNOTSUPP;
3671 		}
3672 		clear_ring_build_skb_enabled(ring);
3673 	} else {
3674 		set_ring_build_skb_enabled(ring);
3675 	}
3676 
3677 	ring->rx_offset = i40e_rx_offset(ring);
3678 
3679 	/* cache tail for quicker writes, and clear the reg before use */
3680 	ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3681 	writel(0, ring->tail);
3682 
3683 	if (ring->xsk_pool) {
3684 		xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
3685 		ok = i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring));
3686 	} else {
3687 		ok = !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3688 	}
3689 	if (!ok) {
3690 		/* Log this in case the user has forgotten to give the kernel
3691 		 * any buffers, even later in the application.
3692 		 */
3693 		dev_info(&vsi->back->pdev->dev,
3694 			 "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3695 			 ring->xsk_pool ? "AF_XDP ZC enabled " : "",
3696 			 ring->queue_index, pf_q);
3697 	}
3698 
3699 	return 0;
3700 }
3701 
3702 /**
3703  * i40e_vsi_configure_tx - Configure the VSI for Tx
3704  * @vsi: VSI structure describing this set of rings and resources
3705  *
3706  * Configure the Tx VSI for operation.
3707  **/
3708 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3709 {
3710 	int err = 0;
3711 	u16 i;
3712 
3713 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3714 		err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3715 
3716 	if (err || !i40e_enabled_xdp_vsi(vsi))
3717 		return err;
3718 
3719 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3720 		err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3721 
3722 	return err;
3723 }
3724 
3725 /**
3726  * i40e_vsi_configure_rx - Configure the VSI for Rx
3727  * @vsi: the VSI being configured
3728  *
3729  * Configure the Rx VSI for operation.
3730  **/
3731 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3732 {
3733 	int err = 0;
3734 	u16 i;
3735 
3736 	vsi->max_frame = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
3737 	vsi->rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
3738 
3739 #if (PAGE_SIZE < 8192)
3740 	if (vsi->netdev && !I40E_2K_TOO_SMALL_WITH_PADDING &&
3741 	    vsi->netdev->mtu <= ETH_DATA_LEN) {
3742 		vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3743 		vsi->max_frame = vsi->rx_buf_len;
3744 	}
3745 #endif
3746 
3747 	/* set up individual rings */
3748 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3749 		err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3750 
3751 	return err;
3752 }
3753 
3754 /**
3755  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3756  * @vsi: ptr to the VSI
3757  **/
3758 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3759 {
3760 	struct i40e_ring *tx_ring, *rx_ring;
3761 	u16 qoffset, qcount;
3762 	int i, n;
3763 
3764 	if (!(vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
3765 		/* Reset the TC information */
3766 		for (i = 0; i < vsi->num_queue_pairs; i++) {
3767 			rx_ring = vsi->rx_rings[i];
3768 			tx_ring = vsi->tx_rings[i];
3769 			rx_ring->dcb_tc = 0;
3770 			tx_ring->dcb_tc = 0;
3771 		}
3772 		return;
3773 	}
3774 
3775 	for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3776 		if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3777 			continue;
3778 
3779 		qoffset = vsi->tc_config.tc_info[n].qoffset;
3780 		qcount = vsi->tc_config.tc_info[n].qcount;
3781 		for (i = qoffset; i < (qoffset + qcount); i++) {
3782 			rx_ring = vsi->rx_rings[i];
3783 			tx_ring = vsi->tx_rings[i];
3784 			rx_ring->dcb_tc = n;
3785 			tx_ring->dcb_tc = n;
3786 		}
3787 	}
3788 }
3789 
3790 /**
3791  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3792  * @vsi: ptr to the VSI
3793  **/
3794 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3795 {
3796 	if (vsi->netdev)
3797 		i40e_set_rx_mode(vsi->netdev);
3798 }
3799 
3800 /**
3801  * i40e_reset_fdir_filter_cnt - Reset flow director filter counters
3802  * @pf: Pointer to the targeted PF
3803  *
3804  * Set all flow director counters to 0.
3805  */
3806 static void i40e_reset_fdir_filter_cnt(struct i40e_pf *pf)
3807 {
3808 	pf->fd_tcp4_filter_cnt = 0;
3809 	pf->fd_udp4_filter_cnt = 0;
3810 	pf->fd_sctp4_filter_cnt = 0;
3811 	pf->fd_ip4_filter_cnt = 0;
3812 	pf->fd_tcp6_filter_cnt = 0;
3813 	pf->fd_udp6_filter_cnt = 0;
3814 	pf->fd_sctp6_filter_cnt = 0;
3815 	pf->fd_ip6_filter_cnt = 0;
3816 }
3817 
3818 /**
3819  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3820  * @vsi: Pointer to the targeted VSI
3821  *
3822  * This function replays the hlist on the hw where all the SB Flow Director
3823  * filters were saved.
3824  **/
3825 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3826 {
3827 	struct i40e_fdir_filter *filter;
3828 	struct i40e_pf *pf = vsi->back;
3829 	struct hlist_node *node;
3830 
3831 	if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
3832 		return;
3833 
3834 	/* Reset FDir counters as we're replaying all existing filters */
3835 	i40e_reset_fdir_filter_cnt(pf);
3836 
3837 	hlist_for_each_entry_safe(filter, node,
3838 				  &pf->fdir_filter_list, fdir_node) {
3839 		i40e_add_del_fdir(vsi, filter, true);
3840 	}
3841 }
3842 
3843 /**
3844  * i40e_vsi_configure - Set up the VSI for action
3845  * @vsi: the VSI being configured
3846  **/
3847 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3848 {
3849 	int err;
3850 
3851 	i40e_set_vsi_rx_mode(vsi);
3852 	i40e_restore_vlan(vsi);
3853 	i40e_vsi_config_dcb_rings(vsi);
3854 	err = i40e_vsi_configure_tx(vsi);
3855 	if (!err)
3856 		err = i40e_vsi_configure_rx(vsi);
3857 
3858 	return err;
3859 }
3860 
3861 /**
3862  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3863  * @vsi: the VSI being configured
3864  **/
3865 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3866 {
3867 	bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3868 	struct i40e_pf *pf = vsi->back;
3869 	struct i40e_hw *hw = &pf->hw;
3870 	u16 vector;
3871 	int i, q;
3872 	u32 qp;
3873 
3874 	/* The interrupt indexing is offset by 1 in the PFINT_ITRn
3875 	 * and PFINT_LNKLSTn registers, e.g.:
3876 	 *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3877 	 */
3878 	qp = vsi->base_queue;
3879 	vector = vsi->base_vector;
3880 	for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3881 		struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3882 
3883 		q_vector->rx.next_update = jiffies + 1;
3884 		q_vector->rx.target_itr =
3885 			ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3886 		wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3887 		     q_vector->rx.target_itr >> 1);
3888 		q_vector->rx.current_itr = q_vector->rx.target_itr;
3889 
3890 		q_vector->tx.next_update = jiffies + 1;
3891 		q_vector->tx.target_itr =
3892 			ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3893 		wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3894 		     q_vector->tx.target_itr >> 1);
3895 		q_vector->tx.current_itr = q_vector->tx.target_itr;
3896 
3897 		wr32(hw, I40E_PFINT_RATEN(vector - 1),
3898 		     i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3899 
3900 		/* begin of linked list for RX queue assigned to this vector */
3901 		wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3902 		for (q = 0; q < q_vector->num_ringpairs; q++) {
3903 			u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3904 			u32 val;
3905 
3906 			val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3907 			      (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3908 			      (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3909 			      (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3910 			      (I40E_QUEUE_TYPE_TX <<
3911 			       I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3912 
3913 			wr32(hw, I40E_QINT_RQCTL(qp), val);
3914 
3915 			if (has_xdp) {
3916 				/* TX queue with next queue set to TX */
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 << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3921 				      (I40E_QUEUE_TYPE_TX <<
3922 				       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3923 
3924 				wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3925 			}
3926 			/* TX queue with next RX or end of linked list */
3927 			val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3928 			      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3929 			      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3930 			      ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3931 			      (I40E_QUEUE_TYPE_RX <<
3932 			       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3933 
3934 			/* Terminate the linked list */
3935 			if (q == (q_vector->num_ringpairs - 1))
3936 				val |= (I40E_QUEUE_END_OF_LIST <<
3937 					I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3938 
3939 			wr32(hw, I40E_QINT_TQCTL(qp), val);
3940 			qp++;
3941 		}
3942 	}
3943 
3944 	i40e_flush(hw);
3945 }
3946 
3947 /**
3948  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3949  * @pf: pointer to private device data structure
3950  **/
3951 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3952 {
3953 	struct i40e_hw *hw = &pf->hw;
3954 	u32 val;
3955 
3956 	/* clear things first */
3957 	wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3958 	rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3959 
3960 	val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3961 	      I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3962 	      I40E_PFINT_ICR0_ENA_GRST_MASK          |
3963 	      I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3964 	      I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3965 	      I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3966 	      I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3967 	      I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3968 
3969 	if (pf->flags & I40E_FLAG_IWARP_ENABLED)
3970 		val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3971 
3972 	if (pf->flags & I40E_FLAG_PTP)
3973 		val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3974 
3975 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
3976 
3977 	/* SW_ITR_IDX = 0, but don't change INTENA */
3978 	wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3979 					I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
3980 
3981 	/* OTHER_ITR_IDX = 0 */
3982 	wr32(hw, I40E_PFINT_STAT_CTL0, 0);
3983 }
3984 
3985 /**
3986  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
3987  * @vsi: the VSI being configured
3988  **/
3989 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
3990 {
3991 	u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
3992 	struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3993 	struct i40e_pf *pf = vsi->back;
3994 	struct i40e_hw *hw = &pf->hw;
3995 
3996 	/* set the ITR configuration */
3997 	q_vector->rx.next_update = jiffies + 1;
3998 	q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
3999 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr >> 1);
4000 	q_vector->rx.current_itr = q_vector->rx.target_itr;
4001 	q_vector->tx.next_update = jiffies + 1;
4002 	q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
4003 	wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr >> 1);
4004 	q_vector->tx.current_itr = q_vector->tx.target_itr;
4005 
4006 	i40e_enable_misc_int_causes(pf);
4007 
4008 	/* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
4009 	wr32(hw, I40E_PFINT_LNKLST0, 0);
4010 
4011 	/* Associate the queue pair to the vector and enable the queue
4012 	 * interrupt RX queue in linked list with next queue set to TX
4013 	 */
4014 	wr32(hw, I40E_QINT_RQCTL(0), I40E_QINT_RQCTL_VAL(nextqp, 0, TX));
4015 
4016 	if (i40e_enabled_xdp_vsi(vsi)) {
4017 		/* TX queue in linked list with next queue set to TX */
4018 		wr32(hw, I40E_QINT_TQCTL(nextqp),
4019 		     I40E_QINT_TQCTL_VAL(nextqp, 0, TX));
4020 	}
4021 
4022 	/* last TX queue so the next RX queue doesn't matter */
4023 	wr32(hw, I40E_QINT_TQCTL(0),
4024 	     I40E_QINT_TQCTL_VAL(I40E_QUEUE_END_OF_LIST, 0, RX));
4025 	i40e_flush(hw);
4026 }
4027 
4028 /**
4029  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
4030  * @pf: board private structure
4031  **/
4032 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
4033 {
4034 	struct i40e_hw *hw = &pf->hw;
4035 
4036 	wr32(hw, I40E_PFINT_DYN_CTL0,
4037 	     I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
4038 	i40e_flush(hw);
4039 }
4040 
4041 /**
4042  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
4043  * @pf: board private structure
4044  **/
4045 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
4046 {
4047 	struct i40e_hw *hw = &pf->hw;
4048 	u32 val;
4049 
4050 	val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
4051 	      I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
4052 	      (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
4053 
4054 	wr32(hw, I40E_PFINT_DYN_CTL0, val);
4055 	i40e_flush(hw);
4056 }
4057 
4058 /**
4059  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
4060  * @irq: interrupt number
4061  * @data: pointer to a q_vector
4062  **/
4063 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
4064 {
4065 	struct i40e_q_vector *q_vector = data;
4066 
4067 	if (!q_vector->tx.ring && !q_vector->rx.ring)
4068 		return IRQ_HANDLED;
4069 
4070 	napi_schedule_irqoff(&q_vector->napi);
4071 
4072 	return IRQ_HANDLED;
4073 }
4074 
4075 /**
4076  * i40e_irq_affinity_notify - Callback for affinity changes
4077  * @notify: context as to what irq was changed
4078  * @mask: the new affinity mask
4079  *
4080  * This is a callback function used by the irq_set_affinity_notifier function
4081  * so that we may register to receive changes to the irq affinity masks.
4082  **/
4083 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
4084 				     const cpumask_t *mask)
4085 {
4086 	struct i40e_q_vector *q_vector =
4087 		container_of(notify, struct i40e_q_vector, affinity_notify);
4088 
4089 	cpumask_copy(&q_vector->affinity_mask, mask);
4090 }
4091 
4092 /**
4093  * i40e_irq_affinity_release - Callback for affinity notifier release
4094  * @ref: internal core kernel usage
4095  *
4096  * This is a callback function used by the irq_set_affinity_notifier function
4097  * to inform the current notification subscriber that they will no longer
4098  * receive notifications.
4099  **/
4100 static void i40e_irq_affinity_release(struct kref *ref) {}
4101 
4102 /**
4103  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
4104  * @vsi: the VSI being configured
4105  * @basename: name for the vector
4106  *
4107  * Allocates MSI-X vectors and requests interrupts from the kernel.
4108  **/
4109 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
4110 {
4111 	int q_vectors = vsi->num_q_vectors;
4112 	struct i40e_pf *pf = vsi->back;
4113 	int base = vsi->base_vector;
4114 	int rx_int_idx = 0;
4115 	int tx_int_idx = 0;
4116 	int vector, err;
4117 	int irq_num;
4118 	int cpu;
4119 
4120 	for (vector = 0; vector < q_vectors; vector++) {
4121 		struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
4122 
4123 		irq_num = pf->msix_entries[base + vector].vector;
4124 
4125 		if (q_vector->tx.ring && q_vector->rx.ring) {
4126 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4127 				 "%s-%s-%d", basename, "TxRx", rx_int_idx++);
4128 			tx_int_idx++;
4129 		} else if (q_vector->rx.ring) {
4130 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4131 				 "%s-%s-%d", basename, "rx", rx_int_idx++);
4132 		} else if (q_vector->tx.ring) {
4133 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4134 				 "%s-%s-%d", basename, "tx", tx_int_idx++);
4135 		} else {
4136 			/* skip this unused q_vector */
4137 			continue;
4138 		}
4139 		err = request_irq(irq_num,
4140 				  vsi->irq_handler,
4141 				  0,
4142 				  q_vector->name,
4143 				  q_vector);
4144 		if (err) {
4145 			dev_info(&pf->pdev->dev,
4146 				 "MSIX request_irq failed, error: %d\n", err);
4147 			goto free_queue_irqs;
4148 		}
4149 
4150 		/* register for affinity change notifications */
4151 		q_vector->irq_num = irq_num;
4152 		q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
4153 		q_vector->affinity_notify.release = i40e_irq_affinity_release;
4154 		irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
4155 		/* Spread affinity hints out across online CPUs.
4156 		 *
4157 		 * get_cpu_mask returns a static constant mask with
4158 		 * a permanent lifetime so it's ok to pass to
4159 		 * irq_update_affinity_hint without making a copy.
4160 		 */
4161 		cpu = cpumask_local_spread(q_vector->v_idx, -1);
4162 		irq_update_affinity_hint(irq_num, get_cpu_mask(cpu));
4163 	}
4164 
4165 	vsi->irqs_ready = true;
4166 	return 0;
4167 
4168 free_queue_irqs:
4169 	while (vector) {
4170 		vector--;
4171 		irq_num = pf->msix_entries[base + vector].vector;
4172 		irq_set_affinity_notifier(irq_num, NULL);
4173 		irq_update_affinity_hint(irq_num, NULL);
4174 		free_irq(irq_num, &vsi->q_vectors[vector]);
4175 	}
4176 	return err;
4177 }
4178 
4179 /**
4180  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
4181  * @vsi: the VSI being un-configured
4182  **/
4183 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
4184 {
4185 	struct i40e_pf *pf = vsi->back;
4186 	struct i40e_hw *hw = &pf->hw;
4187 	int base = vsi->base_vector;
4188 	int i;
4189 
4190 	/* disable interrupt causation from each queue */
4191 	for (i = 0; i < vsi->num_queue_pairs; i++) {
4192 		u32 val;
4193 
4194 		val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
4195 		val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
4196 		wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
4197 
4198 		val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
4199 		val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
4200 		wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
4201 
4202 		if (!i40e_enabled_xdp_vsi(vsi))
4203 			continue;
4204 		wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
4205 	}
4206 
4207 	/* disable each interrupt */
4208 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4209 		for (i = vsi->base_vector;
4210 		     i < (vsi->num_q_vectors + vsi->base_vector); i++)
4211 			wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
4212 
4213 		i40e_flush(hw);
4214 		for (i = 0; i < vsi->num_q_vectors; i++)
4215 			synchronize_irq(pf->msix_entries[i + base].vector);
4216 	} else {
4217 		/* Legacy and MSI mode - this stops all interrupt handling */
4218 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
4219 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
4220 		i40e_flush(hw);
4221 		synchronize_irq(pf->pdev->irq);
4222 	}
4223 }
4224 
4225 /**
4226  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
4227  * @vsi: the VSI being configured
4228  **/
4229 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
4230 {
4231 	struct i40e_pf *pf = vsi->back;
4232 	int i;
4233 
4234 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4235 		for (i = 0; i < vsi->num_q_vectors; i++)
4236 			i40e_irq_dynamic_enable(vsi, i);
4237 	} else {
4238 		i40e_irq_dynamic_enable_icr0(pf);
4239 	}
4240 
4241 	i40e_flush(&pf->hw);
4242 	return 0;
4243 }
4244 
4245 /**
4246  * i40e_free_misc_vector - Free the vector that handles non-queue events
4247  * @pf: board private structure
4248  **/
4249 static void i40e_free_misc_vector(struct i40e_pf *pf)
4250 {
4251 	/* Disable ICR 0 */
4252 	wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
4253 	i40e_flush(&pf->hw);
4254 
4255 	if (pf->flags & I40E_FLAG_MSIX_ENABLED && pf->msix_entries) {
4256 		free_irq(pf->msix_entries[0].vector, pf);
4257 		clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
4258 	}
4259 }
4260 
4261 /**
4262  * i40e_intr - MSI/Legacy and non-queue interrupt handler
4263  * @irq: interrupt number
4264  * @data: pointer to a q_vector
4265  *
4266  * This is the handler used for all MSI/Legacy interrupts, and deals
4267  * with both queue and non-queue interrupts.  This is also used in
4268  * MSIX mode to handle the non-queue interrupts.
4269  **/
4270 static irqreturn_t i40e_intr(int irq, void *data)
4271 {
4272 	struct i40e_pf *pf = (struct i40e_pf *)data;
4273 	struct i40e_hw *hw = &pf->hw;
4274 	irqreturn_t ret = IRQ_NONE;
4275 	u32 icr0, icr0_remaining;
4276 	u32 val, ena_mask;
4277 
4278 	icr0 = rd32(hw, I40E_PFINT_ICR0);
4279 	ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
4280 
4281 	/* if sharing a legacy IRQ, we might get called w/o an intr pending */
4282 	if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
4283 		goto enable_intr;
4284 
4285 	/* if interrupt but no bits showing, must be SWINT */
4286 	if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
4287 	    (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
4288 		pf->sw_int_count++;
4289 
4290 	if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
4291 	    (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
4292 		ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4293 		dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
4294 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
4295 	}
4296 
4297 	/* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
4298 	if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
4299 		struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
4300 		struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4301 
4302 		/* We do not have a way to disarm Queue causes while leaving
4303 		 * interrupt enabled for all other causes, ideally
4304 		 * interrupt should be disabled while we are in NAPI but
4305 		 * this is not a performance path and napi_schedule()
4306 		 * can deal with rescheduling.
4307 		 */
4308 		if (!test_bit(__I40E_DOWN, pf->state))
4309 			napi_schedule_irqoff(&q_vector->napi);
4310 	}
4311 
4312 	if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
4313 		ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
4314 		set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
4315 		i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
4316 	}
4317 
4318 	if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
4319 		ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
4320 		set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
4321 	}
4322 
4323 	if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
4324 		/* disable any further VFLR event notifications */
4325 		if (test_bit(__I40E_VF_RESETS_DISABLED, pf->state)) {
4326 			u32 reg = rd32(hw, I40E_PFINT_ICR0_ENA);
4327 
4328 			reg &= ~I40E_PFINT_ICR0_VFLR_MASK;
4329 			wr32(hw, I40E_PFINT_ICR0_ENA, reg);
4330 		} else {
4331 			ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
4332 			set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
4333 		}
4334 	}
4335 
4336 	if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
4337 		if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4338 			set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
4339 		ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
4340 		val = rd32(hw, I40E_GLGEN_RSTAT);
4341 		val = (val & I40E_GLGEN_RSTAT_RESET_TYPE_MASK)
4342 		       >> I40E_GLGEN_RSTAT_RESET_TYPE_SHIFT;
4343 		if (val == I40E_RESET_CORER) {
4344 			pf->corer_count++;
4345 		} else if (val == I40E_RESET_GLOBR) {
4346 			pf->globr_count++;
4347 		} else if (val == I40E_RESET_EMPR) {
4348 			pf->empr_count++;
4349 			set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
4350 		}
4351 	}
4352 
4353 	if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
4354 		icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
4355 		dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4356 		dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4357 			 rd32(hw, I40E_PFHMC_ERRORINFO),
4358 			 rd32(hw, I40E_PFHMC_ERRORDATA));
4359 	}
4360 
4361 	if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4362 		u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4363 
4364 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_EVENT0_MASK)
4365 			schedule_work(&pf->ptp_extts0_work);
4366 
4367 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK)
4368 			i40e_ptp_tx_hwtstamp(pf);
4369 
4370 		icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4371 	}
4372 
4373 	/* If a critical error is pending we have no choice but to reset the
4374 	 * device.
4375 	 * Report and mask out any remaining unexpected interrupts.
4376 	 */
4377 	icr0_remaining = icr0 & ena_mask;
4378 	if (icr0_remaining) {
4379 		dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4380 			 icr0_remaining);
4381 		if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4382 		    (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4383 		    (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4384 			dev_info(&pf->pdev->dev, "device will be reset\n");
4385 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4386 			i40e_service_event_schedule(pf);
4387 		}
4388 		ena_mask &= ~icr0_remaining;
4389 	}
4390 	ret = IRQ_HANDLED;
4391 
4392 enable_intr:
4393 	/* re-enable interrupt causes */
4394 	wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4395 	if (!test_bit(__I40E_DOWN, pf->state) ||
4396 	    test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4397 		i40e_service_event_schedule(pf);
4398 		i40e_irq_dynamic_enable_icr0(pf);
4399 	}
4400 
4401 	return ret;
4402 }
4403 
4404 /**
4405  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4406  * @tx_ring:  tx ring to clean
4407  * @budget:   how many cleans we're allowed
4408  *
4409  * Returns true if there's any budget left (e.g. the clean is finished)
4410  **/
4411 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4412 {
4413 	struct i40e_vsi *vsi = tx_ring->vsi;
4414 	u16 i = tx_ring->next_to_clean;
4415 	struct i40e_tx_buffer *tx_buf;
4416 	struct i40e_tx_desc *tx_desc;
4417 
4418 	tx_buf = &tx_ring->tx_bi[i];
4419 	tx_desc = I40E_TX_DESC(tx_ring, i);
4420 	i -= tx_ring->count;
4421 
4422 	do {
4423 		struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4424 
4425 		/* if next_to_watch is not set then there is no work pending */
4426 		if (!eop_desc)
4427 			break;
4428 
4429 		/* prevent any other reads prior to eop_desc */
4430 		smp_rmb();
4431 
4432 		/* if the descriptor isn't done, no work yet to do */
4433 		if (!(eop_desc->cmd_type_offset_bsz &
4434 		      cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4435 			break;
4436 
4437 		/* clear next_to_watch to prevent false hangs */
4438 		tx_buf->next_to_watch = NULL;
4439 
4440 		tx_desc->buffer_addr = 0;
4441 		tx_desc->cmd_type_offset_bsz = 0;
4442 		/* move past filter desc */
4443 		tx_buf++;
4444 		tx_desc++;
4445 		i++;
4446 		if (unlikely(!i)) {
4447 			i -= tx_ring->count;
4448 			tx_buf = tx_ring->tx_bi;
4449 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4450 		}
4451 		/* unmap skb header data */
4452 		dma_unmap_single(tx_ring->dev,
4453 				 dma_unmap_addr(tx_buf, dma),
4454 				 dma_unmap_len(tx_buf, len),
4455 				 DMA_TO_DEVICE);
4456 		if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4457 			kfree(tx_buf->raw_buf);
4458 
4459 		tx_buf->raw_buf = NULL;
4460 		tx_buf->tx_flags = 0;
4461 		tx_buf->next_to_watch = NULL;
4462 		dma_unmap_len_set(tx_buf, len, 0);
4463 		tx_desc->buffer_addr = 0;
4464 		tx_desc->cmd_type_offset_bsz = 0;
4465 
4466 		/* move us past the eop_desc for start of next FD desc */
4467 		tx_buf++;
4468 		tx_desc++;
4469 		i++;
4470 		if (unlikely(!i)) {
4471 			i -= tx_ring->count;
4472 			tx_buf = tx_ring->tx_bi;
4473 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4474 		}
4475 
4476 		/* update budget accounting */
4477 		budget--;
4478 	} while (likely(budget));
4479 
4480 	i += tx_ring->count;
4481 	tx_ring->next_to_clean = i;
4482 
4483 	if (vsi->back->flags & I40E_FLAG_MSIX_ENABLED)
4484 		i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4485 
4486 	return budget > 0;
4487 }
4488 
4489 /**
4490  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4491  * @irq: interrupt number
4492  * @data: pointer to a q_vector
4493  **/
4494 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4495 {
4496 	struct i40e_q_vector *q_vector = data;
4497 	struct i40e_vsi *vsi;
4498 
4499 	if (!q_vector->tx.ring)
4500 		return IRQ_HANDLED;
4501 
4502 	vsi = q_vector->tx.ring->vsi;
4503 	i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4504 
4505 	return IRQ_HANDLED;
4506 }
4507 
4508 /**
4509  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4510  * @vsi: the VSI being configured
4511  * @v_idx: vector index
4512  * @qp_idx: queue pair index
4513  **/
4514 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4515 {
4516 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4517 	struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4518 	struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4519 
4520 	tx_ring->q_vector = q_vector;
4521 	tx_ring->next = q_vector->tx.ring;
4522 	q_vector->tx.ring = tx_ring;
4523 	q_vector->tx.count++;
4524 
4525 	/* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4526 	if (i40e_enabled_xdp_vsi(vsi)) {
4527 		struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4528 
4529 		xdp_ring->q_vector = q_vector;
4530 		xdp_ring->next = q_vector->tx.ring;
4531 		q_vector->tx.ring = xdp_ring;
4532 		q_vector->tx.count++;
4533 	}
4534 
4535 	rx_ring->q_vector = q_vector;
4536 	rx_ring->next = q_vector->rx.ring;
4537 	q_vector->rx.ring = rx_ring;
4538 	q_vector->rx.count++;
4539 }
4540 
4541 /**
4542  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4543  * @vsi: the VSI being configured
4544  *
4545  * This function maps descriptor rings to the queue-specific vectors
4546  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4547  * one vector per queue pair, but on a constrained vector budget, we
4548  * group the queue pairs as "efficiently" as possible.
4549  **/
4550 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4551 {
4552 	int qp_remaining = vsi->num_queue_pairs;
4553 	int q_vectors = vsi->num_q_vectors;
4554 	int num_ringpairs;
4555 	int v_start = 0;
4556 	int qp_idx = 0;
4557 
4558 	/* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4559 	 * group them so there are multiple queues per vector.
4560 	 * It is also important to go through all the vectors available to be
4561 	 * sure that if we don't use all the vectors, that the remaining vectors
4562 	 * are cleared. This is especially important when decreasing the
4563 	 * number of queues in use.
4564 	 */
4565 	for (; v_start < q_vectors; v_start++) {
4566 		struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4567 
4568 		num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4569 
4570 		q_vector->num_ringpairs = num_ringpairs;
4571 		q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4572 
4573 		q_vector->rx.count = 0;
4574 		q_vector->tx.count = 0;
4575 		q_vector->rx.ring = NULL;
4576 		q_vector->tx.ring = NULL;
4577 
4578 		while (num_ringpairs--) {
4579 			i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4580 			qp_idx++;
4581 			qp_remaining--;
4582 		}
4583 	}
4584 }
4585 
4586 /**
4587  * i40e_vsi_request_irq - Request IRQ from the OS
4588  * @vsi: the VSI being configured
4589  * @basename: name for the vector
4590  **/
4591 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4592 {
4593 	struct i40e_pf *pf = vsi->back;
4594 	int err;
4595 
4596 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
4597 		err = i40e_vsi_request_irq_msix(vsi, basename);
4598 	else if (pf->flags & I40E_FLAG_MSI_ENABLED)
4599 		err = request_irq(pf->pdev->irq, i40e_intr, 0,
4600 				  pf->int_name, pf);
4601 	else
4602 		err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4603 				  pf->int_name, pf);
4604 
4605 	if (err)
4606 		dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4607 
4608 	return err;
4609 }
4610 
4611 #ifdef CONFIG_NET_POLL_CONTROLLER
4612 /**
4613  * i40e_netpoll - A Polling 'interrupt' handler
4614  * @netdev: network interface device structure
4615  *
4616  * This is used by netconsole to send skbs without having to re-enable
4617  * interrupts.  It's not called while the normal interrupt routine is executing.
4618  **/
4619 static void i40e_netpoll(struct net_device *netdev)
4620 {
4621 	struct i40e_netdev_priv *np = netdev_priv(netdev);
4622 	struct i40e_vsi *vsi = np->vsi;
4623 	struct i40e_pf *pf = vsi->back;
4624 	int i;
4625 
4626 	/* if interface is down do nothing */
4627 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
4628 		return;
4629 
4630 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4631 		for (i = 0; i < vsi->num_q_vectors; i++)
4632 			i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4633 	} else {
4634 		i40e_intr(pf->pdev->irq, netdev);
4635 	}
4636 }
4637 #endif
4638 
4639 #define I40E_QTX_ENA_WAIT_COUNT 50
4640 
4641 /**
4642  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4643  * @pf: the PF being configured
4644  * @pf_q: the PF queue
4645  * @enable: enable or disable state of the queue
4646  *
4647  * This routine will wait for the given Tx queue of the PF to reach the
4648  * enabled or disabled state.
4649  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4650  * multiple retries; else will return 0 in case of success.
4651  **/
4652 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4653 {
4654 	int i;
4655 	u32 tx_reg;
4656 
4657 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4658 		tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4659 		if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4660 			break;
4661 
4662 		usleep_range(10, 20);
4663 	}
4664 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4665 		return -ETIMEDOUT;
4666 
4667 	return 0;
4668 }
4669 
4670 /**
4671  * i40e_control_tx_q - Start or stop a particular Tx queue
4672  * @pf: the PF structure
4673  * @pf_q: the PF queue to configure
4674  * @enable: start or stop the queue
4675  *
4676  * This function enables or disables a single queue. Note that any delay
4677  * required after the operation is expected to be handled by the caller of
4678  * this function.
4679  **/
4680 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4681 {
4682 	struct i40e_hw *hw = &pf->hw;
4683 	u32 tx_reg;
4684 	int i;
4685 
4686 	/* warn the TX unit of coming changes */
4687 	i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4688 	if (!enable)
4689 		usleep_range(10, 20);
4690 
4691 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4692 		tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4693 		if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4694 		    ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4695 			break;
4696 		usleep_range(1000, 2000);
4697 	}
4698 
4699 	/* Skip if the queue is already in the requested state */
4700 	if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4701 		return;
4702 
4703 	/* turn on/off the queue */
4704 	if (enable) {
4705 		wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4706 		tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4707 	} else {
4708 		tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4709 	}
4710 
4711 	wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4712 }
4713 
4714 /**
4715  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4716  * @seid: VSI SEID
4717  * @pf: the PF structure
4718  * @pf_q: the PF queue to configure
4719  * @is_xdp: true if the queue is used for XDP
4720  * @enable: start or stop the queue
4721  **/
4722 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4723 			   bool is_xdp, bool enable)
4724 {
4725 	int ret;
4726 
4727 	i40e_control_tx_q(pf, pf_q, enable);
4728 
4729 	/* wait for the change to finish */
4730 	ret = i40e_pf_txq_wait(pf, pf_q, enable);
4731 	if (ret) {
4732 		dev_info(&pf->pdev->dev,
4733 			 "VSI seid %d %sTx ring %d %sable timeout\n",
4734 			 seid, (is_xdp ? "XDP " : ""), pf_q,
4735 			 (enable ? "en" : "dis"));
4736 	}
4737 
4738 	return ret;
4739 }
4740 
4741 /**
4742  * i40e_vsi_enable_tx - Start a VSI's rings
4743  * @vsi: the VSI being configured
4744  **/
4745 static int i40e_vsi_enable_tx(struct i40e_vsi *vsi)
4746 {
4747 	struct i40e_pf *pf = vsi->back;
4748 	int i, pf_q, ret = 0;
4749 
4750 	pf_q = vsi->base_queue;
4751 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4752 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4753 					     pf_q,
4754 					     false /*is xdp*/, true);
4755 		if (ret)
4756 			break;
4757 
4758 		if (!i40e_enabled_xdp_vsi(vsi))
4759 			continue;
4760 
4761 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4762 					     pf_q + vsi->alloc_queue_pairs,
4763 					     true /*is xdp*/, true);
4764 		if (ret)
4765 			break;
4766 	}
4767 	return ret;
4768 }
4769 
4770 /**
4771  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4772  * @pf: the PF being configured
4773  * @pf_q: the PF queue
4774  * @enable: enable or disable state of the queue
4775  *
4776  * This routine will wait for the given Rx queue of the PF to reach the
4777  * enabled or disabled state.
4778  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4779  * multiple retries; else will return 0 in case of success.
4780  **/
4781 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4782 {
4783 	int i;
4784 	u32 rx_reg;
4785 
4786 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4787 		rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4788 		if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4789 			break;
4790 
4791 		usleep_range(10, 20);
4792 	}
4793 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4794 		return -ETIMEDOUT;
4795 
4796 	return 0;
4797 }
4798 
4799 /**
4800  * i40e_control_rx_q - Start or stop a particular Rx queue
4801  * @pf: the PF structure
4802  * @pf_q: the PF queue to configure
4803  * @enable: start or stop the queue
4804  *
4805  * This function enables or disables a single queue. Note that
4806  * any delay required after the operation is expected to be
4807  * handled by the caller of this function.
4808  **/
4809 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4810 {
4811 	struct i40e_hw *hw = &pf->hw;
4812 	u32 rx_reg;
4813 	int i;
4814 
4815 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4816 		rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4817 		if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4818 		    ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4819 			break;
4820 		usleep_range(1000, 2000);
4821 	}
4822 
4823 	/* Skip if the queue is already in the requested state */
4824 	if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4825 		return;
4826 
4827 	/* turn on/off the queue */
4828 	if (enable)
4829 		rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4830 	else
4831 		rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4832 
4833 	wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4834 }
4835 
4836 /**
4837  * i40e_control_wait_rx_q
4838  * @pf: the PF structure
4839  * @pf_q: queue being configured
4840  * @enable: start or stop the rings
4841  *
4842  * This function enables or disables a single queue along with waiting
4843  * for the change to finish. The caller of this function should handle
4844  * the delays needed in the case of disabling queues.
4845  **/
4846 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4847 {
4848 	int ret = 0;
4849 
4850 	i40e_control_rx_q(pf, pf_q, enable);
4851 
4852 	/* wait for the change to finish */
4853 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4854 	if (ret)
4855 		return ret;
4856 
4857 	return ret;
4858 }
4859 
4860 /**
4861  * i40e_vsi_enable_rx - Start a VSI's rings
4862  * @vsi: the VSI being configured
4863  **/
4864 static int i40e_vsi_enable_rx(struct i40e_vsi *vsi)
4865 {
4866 	struct i40e_pf *pf = vsi->back;
4867 	int i, pf_q, ret = 0;
4868 
4869 	pf_q = vsi->base_queue;
4870 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4871 		ret = i40e_control_wait_rx_q(pf, pf_q, true);
4872 		if (ret) {
4873 			dev_info(&pf->pdev->dev,
4874 				 "VSI seid %d Rx ring %d enable timeout\n",
4875 				 vsi->seid, pf_q);
4876 			break;
4877 		}
4878 	}
4879 
4880 	return ret;
4881 }
4882 
4883 /**
4884  * i40e_vsi_start_rings - Start a VSI's rings
4885  * @vsi: the VSI being configured
4886  **/
4887 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4888 {
4889 	int ret = 0;
4890 
4891 	/* do rx first for enable and last for disable */
4892 	ret = i40e_vsi_enable_rx(vsi);
4893 	if (ret)
4894 		return ret;
4895 	ret = i40e_vsi_enable_tx(vsi);
4896 
4897 	return ret;
4898 }
4899 
4900 #define I40E_DISABLE_TX_GAP_MSEC	50
4901 
4902 /**
4903  * i40e_vsi_stop_rings - Stop a VSI's rings
4904  * @vsi: the VSI being configured
4905  **/
4906 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4907 {
4908 	struct i40e_pf *pf = vsi->back;
4909 	int pf_q, err, q_end;
4910 
4911 	/* When port TX is suspended, don't wait */
4912 	if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4913 		return i40e_vsi_stop_rings_no_wait(vsi);
4914 
4915 	q_end = vsi->base_queue + vsi->num_queue_pairs;
4916 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4917 		i40e_pre_tx_queue_cfg(&pf->hw, (u32)pf_q, false);
4918 
4919 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++) {
4920 		err = i40e_control_wait_rx_q(pf, pf_q, false);
4921 		if (err)
4922 			dev_info(&pf->pdev->dev,
4923 				 "VSI seid %d Rx ring %d disable timeout\n",
4924 				 vsi->seid, pf_q);
4925 	}
4926 
4927 	msleep(I40E_DISABLE_TX_GAP_MSEC);
4928 	pf_q = vsi->base_queue;
4929 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4930 		wr32(&pf->hw, I40E_QTX_ENA(pf_q), 0);
4931 
4932 	i40e_vsi_wait_queues_disabled(vsi);
4933 }
4934 
4935 /**
4936  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4937  * @vsi: the VSI being shutdown
4938  *
4939  * This function stops all the rings for a VSI but does not delay to verify
4940  * that rings have been disabled. It is expected that the caller is shutting
4941  * down multiple VSIs at once and will delay together for all the VSIs after
4942  * initiating the shutdown. This is particularly useful for shutting down lots
4943  * of VFs together. Otherwise, a large delay can be incurred while configuring
4944  * each VSI in serial.
4945  **/
4946 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4947 {
4948 	struct i40e_pf *pf = vsi->back;
4949 	int i, pf_q;
4950 
4951 	pf_q = vsi->base_queue;
4952 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4953 		i40e_control_tx_q(pf, pf_q, false);
4954 		i40e_control_rx_q(pf, pf_q, false);
4955 	}
4956 }
4957 
4958 /**
4959  * i40e_vsi_free_irq - Free the irq association with the OS
4960  * @vsi: the VSI being configured
4961  **/
4962 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4963 {
4964 	struct i40e_pf *pf = vsi->back;
4965 	struct i40e_hw *hw = &pf->hw;
4966 	int base = vsi->base_vector;
4967 	u32 val, qp;
4968 	int i;
4969 
4970 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4971 		if (!vsi->q_vectors)
4972 			return;
4973 
4974 		if (!vsi->irqs_ready)
4975 			return;
4976 
4977 		vsi->irqs_ready = false;
4978 		for (i = 0; i < vsi->num_q_vectors; i++) {
4979 			int irq_num;
4980 			u16 vector;
4981 
4982 			vector = i + base;
4983 			irq_num = pf->msix_entries[vector].vector;
4984 
4985 			/* free only the irqs that were actually requested */
4986 			if (!vsi->q_vectors[i] ||
4987 			    !vsi->q_vectors[i]->num_ringpairs)
4988 				continue;
4989 
4990 			/* clear the affinity notifier in the IRQ descriptor */
4991 			irq_set_affinity_notifier(irq_num, NULL);
4992 			/* remove our suggested affinity mask for this IRQ */
4993 			irq_update_affinity_hint(irq_num, NULL);
4994 			free_irq(irq_num, vsi->q_vectors[i]);
4995 
4996 			/* Tear down the interrupt queue link list
4997 			 *
4998 			 * We know that they come in pairs and always
4999 			 * the Rx first, then the Tx.  To clear the
5000 			 * link list, stick the EOL value into the
5001 			 * next_q field of the registers.
5002 			 */
5003 			val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
5004 			qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
5005 				>> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
5006 			val |= I40E_QUEUE_END_OF_LIST
5007 				<< I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
5008 			wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
5009 
5010 			while (qp != I40E_QUEUE_END_OF_LIST) {
5011 				u32 next;
5012 
5013 				val = rd32(hw, I40E_QINT_RQCTL(qp));
5014 
5015 				val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5016 					 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5017 					 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5018 					 I40E_QINT_RQCTL_INTEVENT_MASK);
5019 
5020 				val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5021 					 I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5022 
5023 				wr32(hw, I40E_QINT_RQCTL(qp), val);
5024 
5025 				val = rd32(hw, I40E_QINT_TQCTL(qp));
5026 
5027 				next = (val & I40E_QINT_TQCTL_NEXTQ_INDX_MASK)
5028 					>> I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT;
5029 
5030 				val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5031 					 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5032 					 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5033 					 I40E_QINT_TQCTL_INTEVENT_MASK);
5034 
5035 				val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5036 					 I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5037 
5038 				wr32(hw, I40E_QINT_TQCTL(qp), val);
5039 				qp = next;
5040 			}
5041 		}
5042 	} else {
5043 		free_irq(pf->pdev->irq, pf);
5044 
5045 		val = rd32(hw, I40E_PFINT_LNKLST0);
5046 		qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
5047 			>> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
5048 		val |= I40E_QUEUE_END_OF_LIST
5049 			<< I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
5050 		wr32(hw, I40E_PFINT_LNKLST0, val);
5051 
5052 		val = rd32(hw, I40E_QINT_RQCTL(qp));
5053 		val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5054 			 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5055 			 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5056 			 I40E_QINT_RQCTL_INTEVENT_MASK);
5057 
5058 		val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5059 			I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5060 
5061 		wr32(hw, I40E_QINT_RQCTL(qp), val);
5062 
5063 		val = rd32(hw, I40E_QINT_TQCTL(qp));
5064 
5065 		val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5066 			 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5067 			 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5068 			 I40E_QINT_TQCTL_INTEVENT_MASK);
5069 
5070 		val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5071 			I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5072 
5073 		wr32(hw, I40E_QINT_TQCTL(qp), val);
5074 	}
5075 }
5076 
5077 /**
5078  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
5079  * @vsi: the VSI being configured
5080  * @v_idx: Index of vector to be freed
5081  *
5082  * This function frees the memory allocated to the q_vector.  In addition if
5083  * NAPI is enabled it will delete any references to the NAPI struct prior
5084  * to freeing the q_vector.
5085  **/
5086 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
5087 {
5088 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
5089 	struct i40e_ring *ring;
5090 
5091 	if (!q_vector)
5092 		return;
5093 
5094 	/* disassociate q_vector from rings */
5095 	i40e_for_each_ring(ring, q_vector->tx)
5096 		ring->q_vector = NULL;
5097 
5098 	i40e_for_each_ring(ring, q_vector->rx)
5099 		ring->q_vector = NULL;
5100 
5101 	/* only VSI w/ an associated netdev is set up w/ NAPI */
5102 	if (vsi->netdev)
5103 		netif_napi_del(&q_vector->napi);
5104 
5105 	vsi->q_vectors[v_idx] = NULL;
5106 
5107 	kfree_rcu(q_vector, rcu);
5108 }
5109 
5110 /**
5111  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
5112  * @vsi: the VSI being un-configured
5113  *
5114  * This frees the memory allocated to the q_vectors and
5115  * deletes references to the NAPI struct.
5116  **/
5117 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
5118 {
5119 	int v_idx;
5120 
5121 	for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
5122 		i40e_free_q_vector(vsi, v_idx);
5123 }
5124 
5125 /**
5126  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
5127  * @pf: board private structure
5128  **/
5129 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
5130 {
5131 	/* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
5132 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
5133 		pci_disable_msix(pf->pdev);
5134 		kfree(pf->msix_entries);
5135 		pf->msix_entries = NULL;
5136 		kfree(pf->irq_pile);
5137 		pf->irq_pile = NULL;
5138 	} else if (pf->flags & I40E_FLAG_MSI_ENABLED) {
5139 		pci_disable_msi(pf->pdev);
5140 	}
5141 	pf->flags &= ~(I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
5142 }
5143 
5144 /**
5145  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
5146  * @pf: board private structure
5147  *
5148  * We go through and clear interrupt specific resources and reset the structure
5149  * to pre-load conditions
5150  **/
5151 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
5152 {
5153 	int i;
5154 
5155 	if (test_bit(__I40E_MISC_IRQ_REQUESTED, pf->state))
5156 		i40e_free_misc_vector(pf);
5157 
5158 	i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
5159 		      I40E_IWARP_IRQ_PILE_ID);
5160 
5161 	i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
5162 	for (i = 0; i < pf->num_alloc_vsi; i++)
5163 		if (pf->vsi[i])
5164 			i40e_vsi_free_q_vectors(pf->vsi[i]);
5165 	i40e_reset_interrupt_capability(pf);
5166 }
5167 
5168 /**
5169  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5170  * @vsi: the VSI being configured
5171  **/
5172 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
5173 {
5174 	int q_idx;
5175 
5176 	if (!vsi->netdev)
5177 		return;
5178 
5179 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5180 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5181 
5182 		if (q_vector->rx.ring || q_vector->tx.ring)
5183 			napi_enable(&q_vector->napi);
5184 	}
5185 }
5186 
5187 /**
5188  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
5189  * @vsi: the VSI being configured
5190  **/
5191 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
5192 {
5193 	int q_idx;
5194 
5195 	if (!vsi->netdev)
5196 		return;
5197 
5198 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5199 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5200 
5201 		if (q_vector->rx.ring || q_vector->tx.ring)
5202 			napi_disable(&q_vector->napi);
5203 	}
5204 }
5205 
5206 /**
5207  * i40e_vsi_close - Shut down a VSI
5208  * @vsi: the vsi to be quelled
5209  **/
5210 static void i40e_vsi_close(struct i40e_vsi *vsi)
5211 {
5212 	struct i40e_pf *pf = vsi->back;
5213 	if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
5214 		i40e_down(vsi);
5215 	i40e_vsi_free_irq(vsi);
5216 	i40e_vsi_free_tx_resources(vsi);
5217 	i40e_vsi_free_rx_resources(vsi);
5218 	vsi->current_netdev_flags = 0;
5219 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
5220 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
5221 		set_bit(__I40E_CLIENT_RESET, pf->state);
5222 }
5223 
5224 /**
5225  * i40e_quiesce_vsi - Pause a given VSI
5226  * @vsi: the VSI being paused
5227  **/
5228 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
5229 {
5230 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
5231 		return;
5232 
5233 	set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
5234 	if (vsi->netdev && netif_running(vsi->netdev))
5235 		vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
5236 	else
5237 		i40e_vsi_close(vsi);
5238 }
5239 
5240 /**
5241  * i40e_unquiesce_vsi - Resume a given VSI
5242  * @vsi: the VSI being resumed
5243  **/
5244 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
5245 {
5246 	if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
5247 		return;
5248 
5249 	if (vsi->netdev && netif_running(vsi->netdev))
5250 		vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
5251 	else
5252 		i40e_vsi_open(vsi);   /* this clears the DOWN bit */
5253 }
5254 
5255 /**
5256  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
5257  * @pf: the PF
5258  **/
5259 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
5260 {
5261 	int v;
5262 
5263 	for (v = 0; v < pf->num_alloc_vsi; v++) {
5264 		if (pf->vsi[v])
5265 			i40e_quiesce_vsi(pf->vsi[v]);
5266 	}
5267 }
5268 
5269 /**
5270  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
5271  * @pf: the PF
5272  **/
5273 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
5274 {
5275 	int v;
5276 
5277 	for (v = 0; v < pf->num_alloc_vsi; v++) {
5278 		if (pf->vsi[v])
5279 			i40e_unquiesce_vsi(pf->vsi[v]);
5280 	}
5281 }
5282 
5283 /**
5284  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
5285  * @vsi: the VSI being configured
5286  *
5287  * Wait until all queues on a given VSI have been disabled.
5288  **/
5289 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
5290 {
5291 	struct i40e_pf *pf = vsi->back;
5292 	int i, pf_q, ret;
5293 
5294 	pf_q = vsi->base_queue;
5295 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
5296 		/* Check and wait for the Tx queue */
5297 		ret = i40e_pf_txq_wait(pf, pf_q, false);
5298 		if (ret) {
5299 			dev_info(&pf->pdev->dev,
5300 				 "VSI seid %d Tx ring %d disable timeout\n",
5301 				 vsi->seid, pf_q);
5302 			return ret;
5303 		}
5304 
5305 		if (!i40e_enabled_xdp_vsi(vsi))
5306 			goto wait_rx;
5307 
5308 		/* Check and wait for the XDP Tx queue */
5309 		ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
5310 				       false);
5311 		if (ret) {
5312 			dev_info(&pf->pdev->dev,
5313 				 "VSI seid %d XDP Tx ring %d disable timeout\n",
5314 				 vsi->seid, pf_q);
5315 			return ret;
5316 		}
5317 wait_rx:
5318 		/* Check and wait for the Rx queue */
5319 		ret = i40e_pf_rxq_wait(pf, pf_q, false);
5320 		if (ret) {
5321 			dev_info(&pf->pdev->dev,
5322 				 "VSI seid %d Rx ring %d disable timeout\n",
5323 				 vsi->seid, pf_q);
5324 			return ret;
5325 		}
5326 	}
5327 
5328 	return 0;
5329 }
5330 
5331 #ifdef CONFIG_I40E_DCB
5332 /**
5333  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
5334  * @pf: the PF
5335  *
5336  * This function waits for the queues to be in disabled state for all the
5337  * VSIs that are managed by this PF.
5338  **/
5339 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
5340 {
5341 	int v, ret = 0;
5342 
5343 	for (v = 0; v < pf->hw.func_caps.num_vsis; v++) {
5344 		if (pf->vsi[v]) {
5345 			ret = i40e_vsi_wait_queues_disabled(pf->vsi[v]);
5346 			if (ret)
5347 				break;
5348 		}
5349 	}
5350 
5351 	return ret;
5352 }
5353 
5354 #endif
5355 
5356 /**
5357  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
5358  * @pf: pointer to PF
5359  *
5360  * Get TC map for ISCSI PF type that will include iSCSI TC
5361  * and LAN TC.
5362  **/
5363 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
5364 {
5365 	struct i40e_dcb_app_priority_table app;
5366 	struct i40e_hw *hw = &pf->hw;
5367 	u8 enabled_tc = 1; /* TC0 is always enabled */
5368 	u8 tc, i;
5369 	/* Get the iSCSI APP TLV */
5370 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5371 
5372 	for (i = 0; i < dcbcfg->numapps; i++) {
5373 		app = dcbcfg->app[i];
5374 		if (app.selector == I40E_APP_SEL_TCPIP &&
5375 		    app.protocolid == I40E_APP_PROTOID_ISCSI) {
5376 			tc = dcbcfg->etscfg.prioritytable[app.priority];
5377 			enabled_tc |= BIT(tc);
5378 			break;
5379 		}
5380 	}
5381 
5382 	return enabled_tc;
5383 }
5384 
5385 /**
5386  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5387  * @dcbcfg: the corresponding DCBx configuration structure
5388  *
5389  * Return the number of TCs from given DCBx configuration
5390  **/
5391 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5392 {
5393 	int i, tc_unused = 0;
5394 	u8 num_tc = 0;
5395 	u8 ret = 0;
5396 
5397 	/* Scan the ETS Config Priority Table to find
5398 	 * traffic class enabled for a given priority
5399 	 * and create a bitmask of enabled TCs
5400 	 */
5401 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5402 		num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5403 
5404 	/* Now scan the bitmask to check for
5405 	 * contiguous TCs starting with TC0
5406 	 */
5407 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5408 		if (num_tc & BIT(i)) {
5409 			if (!tc_unused) {
5410 				ret++;
5411 			} else {
5412 				pr_err("Non-contiguous TC - Disabling DCB\n");
5413 				return 1;
5414 			}
5415 		} else {
5416 			tc_unused = 1;
5417 		}
5418 	}
5419 
5420 	/* There is always at least TC0 */
5421 	if (!ret)
5422 		ret = 1;
5423 
5424 	return ret;
5425 }
5426 
5427 /**
5428  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5429  * @dcbcfg: the corresponding DCBx configuration structure
5430  *
5431  * Query the current DCB configuration and return the number of
5432  * traffic classes enabled from the given DCBX config
5433  **/
5434 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5435 {
5436 	u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5437 	u8 enabled_tc = 1;
5438 	u8 i;
5439 
5440 	for (i = 0; i < num_tc; i++)
5441 		enabled_tc |= BIT(i);
5442 
5443 	return enabled_tc;
5444 }
5445 
5446 /**
5447  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5448  * @pf: PF being queried
5449  *
5450  * Query the current MQPRIO configuration and return the number of
5451  * traffic classes enabled.
5452  **/
5453 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5454 {
5455 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
5456 	u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5457 	u8 enabled_tc = 1, i;
5458 
5459 	for (i = 1; i < num_tc; i++)
5460 		enabled_tc |= BIT(i);
5461 	return enabled_tc;
5462 }
5463 
5464 /**
5465  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5466  * @pf: PF being queried
5467  *
5468  * Return number of traffic classes enabled for the given PF
5469  **/
5470 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5471 {
5472 	struct i40e_hw *hw = &pf->hw;
5473 	u8 i, enabled_tc = 1;
5474 	u8 num_tc = 0;
5475 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5476 
5477 	if (i40e_is_tc_mqprio_enabled(pf))
5478 		return pf->vsi[pf->lan_vsi]->mqprio_qopt.qopt.num_tc;
5479 
5480 	/* If neither MQPRIO nor DCB is enabled, then always use single TC */
5481 	if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5482 		return 1;
5483 
5484 	/* SFP mode will be enabled for all TCs on port */
5485 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5486 		return i40e_dcb_get_num_tc(dcbcfg);
5487 
5488 	/* MFP mode return count of enabled TCs for this PF */
5489 	if (pf->hw.func_caps.iscsi)
5490 		enabled_tc =  i40e_get_iscsi_tc_map(pf);
5491 	else
5492 		return 1; /* Only TC0 */
5493 
5494 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5495 		if (enabled_tc & BIT(i))
5496 			num_tc++;
5497 	}
5498 	return num_tc;
5499 }
5500 
5501 /**
5502  * i40e_pf_get_tc_map - Get bitmap for enabled traffic classes
5503  * @pf: PF being queried
5504  *
5505  * Return a bitmap for enabled traffic classes for this PF.
5506  **/
5507 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5508 {
5509 	if (i40e_is_tc_mqprio_enabled(pf))
5510 		return i40e_mqprio_get_enabled_tc(pf);
5511 
5512 	/* If neither MQPRIO nor DCB is enabled for this PF then just return
5513 	 * default TC
5514 	 */
5515 	if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5516 		return I40E_DEFAULT_TRAFFIC_CLASS;
5517 
5518 	/* SFP mode we want PF to be enabled for all TCs */
5519 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5520 		return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5521 
5522 	/* MFP enabled and iSCSI PF type */
5523 	if (pf->hw.func_caps.iscsi)
5524 		return i40e_get_iscsi_tc_map(pf);
5525 	else
5526 		return I40E_DEFAULT_TRAFFIC_CLASS;
5527 }
5528 
5529 /**
5530  * i40e_vsi_get_bw_info - Query VSI BW Information
5531  * @vsi: the VSI being queried
5532  *
5533  * Returns 0 on success, negative value on failure
5534  **/
5535 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5536 {
5537 	struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5538 	struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5539 	struct i40e_pf *pf = vsi->back;
5540 	struct i40e_hw *hw = &pf->hw;
5541 	u32 tc_bw_max;
5542 	int ret;
5543 	int i;
5544 
5545 	/* Get the VSI level BW configuration */
5546 	ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5547 	if (ret) {
5548 		dev_info(&pf->pdev->dev,
5549 			 "couldn't get PF vsi bw config, err %pe aq_err %s\n",
5550 			 ERR_PTR(ret),
5551 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5552 		return -EINVAL;
5553 	}
5554 
5555 	/* Get the VSI level BW configuration per TC */
5556 	ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5557 					       NULL);
5558 	if (ret) {
5559 		dev_info(&pf->pdev->dev,
5560 			 "couldn't get PF vsi ets bw config, err %pe aq_err %s\n",
5561 			 ERR_PTR(ret),
5562 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5563 		return -EINVAL;
5564 	}
5565 
5566 	if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5567 		dev_info(&pf->pdev->dev,
5568 			 "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5569 			 bw_config.tc_valid_bits,
5570 			 bw_ets_config.tc_valid_bits);
5571 		/* Still continuing */
5572 	}
5573 
5574 	vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5575 	vsi->bw_max_quanta = bw_config.max_bw;
5576 	tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5577 		    (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5578 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5579 		vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5580 		vsi->bw_ets_limit_credits[i] =
5581 					le16_to_cpu(bw_ets_config.credits[i]);
5582 		/* 3 bits out of 4 for each TC */
5583 		vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5584 	}
5585 
5586 	return 0;
5587 }
5588 
5589 /**
5590  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5591  * @vsi: the VSI being configured
5592  * @enabled_tc: TC bitmap
5593  * @bw_share: BW shared credits per TC
5594  *
5595  * Returns 0 on success, negative value on failure
5596  **/
5597 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5598 				       u8 *bw_share)
5599 {
5600 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5601 	struct i40e_pf *pf = vsi->back;
5602 	int ret;
5603 	int i;
5604 
5605 	/* There is no need to reset BW when mqprio mode is on.  */
5606 	if (i40e_is_tc_mqprio_enabled(pf))
5607 		return 0;
5608 	if (!vsi->mqprio_qopt.qopt.hw && !(pf->flags & I40E_FLAG_DCB_ENABLED)) {
5609 		ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5610 		if (ret)
5611 			dev_info(&pf->pdev->dev,
5612 				 "Failed to reset tx rate for vsi->seid %u\n",
5613 				 vsi->seid);
5614 		return ret;
5615 	}
5616 	memset(&bw_data, 0, sizeof(bw_data));
5617 	bw_data.tc_valid_bits = enabled_tc;
5618 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5619 		bw_data.tc_bw_credits[i] = bw_share[i];
5620 
5621 	ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5622 	if (ret) {
5623 		dev_info(&pf->pdev->dev,
5624 			 "AQ command Config VSI BW allocation per TC failed = %d\n",
5625 			 pf->hw.aq.asq_last_status);
5626 		return -EINVAL;
5627 	}
5628 
5629 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5630 		vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5631 
5632 	return 0;
5633 }
5634 
5635 /**
5636  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5637  * @vsi: the VSI being configured
5638  * @enabled_tc: TC map to be enabled
5639  *
5640  **/
5641 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5642 {
5643 	struct net_device *netdev = vsi->netdev;
5644 	struct i40e_pf *pf = vsi->back;
5645 	struct i40e_hw *hw = &pf->hw;
5646 	u8 netdev_tc = 0;
5647 	int i;
5648 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5649 
5650 	if (!netdev)
5651 		return;
5652 
5653 	if (!enabled_tc) {
5654 		netdev_reset_tc(netdev);
5655 		return;
5656 	}
5657 
5658 	/* Set up actual enabled TCs on the VSI */
5659 	if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5660 		return;
5661 
5662 	/* set per TC queues for the VSI */
5663 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5664 		/* Only set TC queues for enabled tcs
5665 		 *
5666 		 * e.g. For a VSI that has TC0 and TC3 enabled the
5667 		 * enabled_tc bitmap would be 0x00001001; the driver
5668 		 * will set the numtc for netdev as 2 that will be
5669 		 * referenced by the netdev layer as TC 0 and 1.
5670 		 */
5671 		if (vsi->tc_config.enabled_tc & BIT(i))
5672 			netdev_set_tc_queue(netdev,
5673 					vsi->tc_config.tc_info[i].netdev_tc,
5674 					vsi->tc_config.tc_info[i].qcount,
5675 					vsi->tc_config.tc_info[i].qoffset);
5676 	}
5677 
5678 	if (i40e_is_tc_mqprio_enabled(pf))
5679 		return;
5680 
5681 	/* Assign UP2TC map for the VSI */
5682 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5683 		/* Get the actual TC# for the UP */
5684 		u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5685 		/* Get the mapped netdev TC# for the UP */
5686 		netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5687 		netdev_set_prio_tc_map(netdev, i, netdev_tc);
5688 	}
5689 }
5690 
5691 /**
5692  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5693  * @vsi: the VSI being configured
5694  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5695  **/
5696 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5697 				      struct i40e_vsi_context *ctxt)
5698 {
5699 	/* copy just the sections touched not the entire info
5700 	 * since not all sections are valid as returned by
5701 	 * update vsi params
5702 	 */
5703 	vsi->info.mapping_flags = ctxt->info.mapping_flags;
5704 	memcpy(&vsi->info.queue_mapping,
5705 	       &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5706 	memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5707 	       sizeof(vsi->info.tc_mapping));
5708 }
5709 
5710 /**
5711  * i40e_update_adq_vsi_queues - update queue mapping for ADq VSI
5712  * @vsi: the VSI being reconfigured
5713  * @vsi_offset: offset from main VF VSI
5714  */
5715 int i40e_update_adq_vsi_queues(struct i40e_vsi *vsi, int vsi_offset)
5716 {
5717 	struct i40e_vsi_context ctxt = {};
5718 	struct i40e_pf *pf;
5719 	struct i40e_hw *hw;
5720 	int ret;
5721 
5722 	if (!vsi)
5723 		return I40E_ERR_PARAM;
5724 	pf = vsi->back;
5725 	hw = &pf->hw;
5726 
5727 	ctxt.seid = vsi->seid;
5728 	ctxt.pf_num = hw->pf_id;
5729 	ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id + vsi_offset;
5730 	ctxt.uplink_seid = vsi->uplink_seid;
5731 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5732 	ctxt.flags = I40E_AQ_VSI_TYPE_VF;
5733 	ctxt.info = vsi->info;
5734 
5735 	i40e_vsi_setup_queue_map(vsi, &ctxt, vsi->tc_config.enabled_tc,
5736 				 false);
5737 	if (vsi->reconfig_rss) {
5738 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
5739 				      vsi->num_queue_pairs);
5740 		ret = i40e_vsi_config_rss(vsi);
5741 		if (ret) {
5742 			dev_info(&pf->pdev->dev, "Failed to reconfig rss for num_queues\n");
5743 			return ret;
5744 		}
5745 		vsi->reconfig_rss = false;
5746 	}
5747 
5748 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5749 	if (ret) {
5750 		dev_info(&pf->pdev->dev, "Update vsi config failed, err %pe aq_err %s\n",
5751 			 ERR_PTR(ret),
5752 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5753 		return ret;
5754 	}
5755 	/* update the local VSI info with updated queue map */
5756 	i40e_vsi_update_queue_map(vsi, &ctxt);
5757 	vsi->info.valid_sections = 0;
5758 
5759 	return ret;
5760 }
5761 
5762 /**
5763  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5764  * @vsi: VSI to be configured
5765  * @enabled_tc: TC bitmap
5766  *
5767  * This configures a particular VSI for TCs that are mapped to the
5768  * given TC bitmap. It uses default bandwidth share for TCs across
5769  * VSIs to configure TC for a particular VSI.
5770  *
5771  * NOTE:
5772  * It is expected that the VSI queues have been quisced before calling
5773  * this function.
5774  **/
5775 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5776 {
5777 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5778 	struct i40e_pf *pf = vsi->back;
5779 	struct i40e_hw *hw = &pf->hw;
5780 	struct i40e_vsi_context ctxt;
5781 	int ret = 0;
5782 	int i;
5783 
5784 	/* Check if enabled_tc is same as existing or new TCs */
5785 	if (vsi->tc_config.enabled_tc == enabled_tc &&
5786 	    vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5787 		return ret;
5788 
5789 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
5790 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5791 		if (enabled_tc & BIT(i))
5792 			bw_share[i] = 1;
5793 	}
5794 
5795 	ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5796 	if (ret) {
5797 		struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5798 
5799 		dev_info(&pf->pdev->dev,
5800 			 "Failed configuring TC map %d for VSI %d\n",
5801 			 enabled_tc, vsi->seid);
5802 		ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5803 						  &bw_config, NULL);
5804 		if (ret) {
5805 			dev_info(&pf->pdev->dev,
5806 				 "Failed querying vsi bw info, err %pe aq_err %s\n",
5807 				 ERR_PTR(ret),
5808 				 i40e_aq_str(hw, hw->aq.asq_last_status));
5809 			goto out;
5810 		}
5811 		if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5812 			u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5813 
5814 			if (!valid_tc)
5815 				valid_tc = bw_config.tc_valid_bits;
5816 			/* Always enable TC0, no matter what */
5817 			valid_tc |= 1;
5818 			dev_info(&pf->pdev->dev,
5819 				 "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5820 				 enabled_tc, bw_config.tc_valid_bits, valid_tc);
5821 			enabled_tc = valid_tc;
5822 		}
5823 
5824 		ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5825 		if (ret) {
5826 			dev_err(&pf->pdev->dev,
5827 				"Unable to  configure TC map %d for VSI %d\n",
5828 				enabled_tc, vsi->seid);
5829 			goto out;
5830 		}
5831 	}
5832 
5833 	/* Update Queue Pairs Mapping for currently enabled UPs */
5834 	ctxt.seid = vsi->seid;
5835 	ctxt.pf_num = vsi->back->hw.pf_id;
5836 	ctxt.vf_num = 0;
5837 	ctxt.uplink_seid = vsi->uplink_seid;
5838 	ctxt.info = vsi->info;
5839 	if (i40e_is_tc_mqprio_enabled(pf)) {
5840 		ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5841 		if (ret)
5842 			goto out;
5843 	} else {
5844 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5845 	}
5846 
5847 	/* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5848 	 * queues changed.
5849 	 */
5850 	if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5851 		vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5852 				      vsi->num_queue_pairs);
5853 		ret = i40e_vsi_config_rss(vsi);
5854 		if (ret) {
5855 			dev_info(&vsi->back->pdev->dev,
5856 				 "Failed to reconfig rss for num_queues\n");
5857 			return ret;
5858 		}
5859 		vsi->reconfig_rss = false;
5860 	}
5861 	if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
5862 		ctxt.info.valid_sections |=
5863 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5864 		ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5865 	}
5866 
5867 	/* Update the VSI after updating the VSI queue-mapping
5868 	 * information
5869 	 */
5870 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5871 	if (ret) {
5872 		dev_info(&pf->pdev->dev,
5873 			 "Update vsi tc config failed, err %pe aq_err %s\n",
5874 			 ERR_PTR(ret),
5875 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5876 		goto out;
5877 	}
5878 	/* update the local VSI info with updated queue map */
5879 	i40e_vsi_update_queue_map(vsi, &ctxt);
5880 	vsi->info.valid_sections = 0;
5881 
5882 	/* Update current VSI BW information */
5883 	ret = i40e_vsi_get_bw_info(vsi);
5884 	if (ret) {
5885 		dev_info(&pf->pdev->dev,
5886 			 "Failed updating vsi bw info, err %pe aq_err %s\n",
5887 			 ERR_PTR(ret),
5888 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5889 		goto out;
5890 	}
5891 
5892 	/* Update the netdev TC setup */
5893 	i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5894 out:
5895 	return ret;
5896 }
5897 
5898 /**
5899  * i40e_get_link_speed - Returns link speed for the interface
5900  * @vsi: VSI to be configured
5901  *
5902  **/
5903 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5904 {
5905 	struct i40e_pf *pf = vsi->back;
5906 
5907 	switch (pf->hw.phy.link_info.link_speed) {
5908 	case I40E_LINK_SPEED_40GB:
5909 		return 40000;
5910 	case I40E_LINK_SPEED_25GB:
5911 		return 25000;
5912 	case I40E_LINK_SPEED_20GB:
5913 		return 20000;
5914 	case I40E_LINK_SPEED_10GB:
5915 		return 10000;
5916 	case I40E_LINK_SPEED_1GB:
5917 		return 1000;
5918 	default:
5919 		return -EINVAL;
5920 	}
5921 }
5922 
5923 /**
5924  * i40e_bw_bytes_to_mbits - Convert max_tx_rate from bytes to mbits
5925  * @vsi: Pointer to vsi structure
5926  * @max_tx_rate: max TX rate in bytes to be converted into Mbits
5927  *
5928  * Helper function to convert units before send to set BW limit
5929  **/
5930 static u64 i40e_bw_bytes_to_mbits(struct i40e_vsi *vsi, u64 max_tx_rate)
5931 {
5932 	if (max_tx_rate < I40E_BW_MBPS_DIVISOR) {
5933 		dev_warn(&vsi->back->pdev->dev,
5934 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
5935 		max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5936 	} else {
5937 		do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
5938 	}
5939 
5940 	return max_tx_rate;
5941 }
5942 
5943 /**
5944  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5945  * @vsi: VSI to be configured
5946  * @seid: seid of the channel/VSI
5947  * @max_tx_rate: max TX rate to be configured as BW limit
5948  *
5949  * Helper function to set BW limit for a given VSI
5950  **/
5951 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5952 {
5953 	struct i40e_pf *pf = vsi->back;
5954 	u64 credits = 0;
5955 	int speed = 0;
5956 	int ret = 0;
5957 
5958 	speed = i40e_get_link_speed(vsi);
5959 	if (max_tx_rate > speed) {
5960 		dev_err(&pf->pdev->dev,
5961 			"Invalid max tx rate %llu specified for VSI seid %d.",
5962 			max_tx_rate, seid);
5963 		return -EINVAL;
5964 	}
5965 	if (max_tx_rate && max_tx_rate < I40E_BW_CREDIT_DIVISOR) {
5966 		dev_warn(&pf->pdev->dev,
5967 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
5968 		max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5969 	}
5970 
5971 	/* Tx rate credits are in values of 50Mbps, 0 is disabled */
5972 	credits = max_tx_rate;
5973 	do_div(credits, I40E_BW_CREDIT_DIVISOR);
5974 	ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
5975 					  I40E_MAX_BW_INACTIVE_ACCUM, NULL);
5976 	if (ret)
5977 		dev_err(&pf->pdev->dev,
5978 			"Failed set tx rate (%llu Mbps) for vsi->seid %u, err %pe aq_err %s\n",
5979 			max_tx_rate, seid, ERR_PTR(ret),
5980 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5981 	return ret;
5982 }
5983 
5984 /**
5985  * i40e_remove_queue_channels - Remove queue channels for the TCs
5986  * @vsi: VSI to be configured
5987  *
5988  * Remove queue channels for the TCs
5989  **/
5990 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
5991 {
5992 	enum i40e_admin_queue_err last_aq_status;
5993 	struct i40e_cloud_filter *cfilter;
5994 	struct i40e_channel *ch, *ch_tmp;
5995 	struct i40e_pf *pf = vsi->back;
5996 	struct hlist_node *node;
5997 	int ret, i;
5998 
5999 	/* Reset rss size that was stored when reconfiguring rss for
6000 	 * channel VSIs with non-power-of-2 queue count.
6001 	 */
6002 	vsi->current_rss_size = 0;
6003 
6004 	/* perform cleanup for channels if they exist */
6005 	if (list_empty(&vsi->ch_list))
6006 		return;
6007 
6008 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6009 		struct i40e_vsi *p_vsi;
6010 
6011 		list_del(&ch->list);
6012 		p_vsi = ch->parent_vsi;
6013 		if (!p_vsi || !ch->initialized) {
6014 			kfree(ch);
6015 			continue;
6016 		}
6017 		/* Reset queue contexts */
6018 		for (i = 0; i < ch->num_queue_pairs; i++) {
6019 			struct i40e_ring *tx_ring, *rx_ring;
6020 			u16 pf_q;
6021 
6022 			pf_q = ch->base_queue + i;
6023 			tx_ring = vsi->tx_rings[pf_q];
6024 			tx_ring->ch = NULL;
6025 
6026 			rx_ring = vsi->rx_rings[pf_q];
6027 			rx_ring->ch = NULL;
6028 		}
6029 
6030 		/* Reset BW configured for this VSI via mqprio */
6031 		ret = i40e_set_bw_limit(vsi, ch->seid, 0);
6032 		if (ret)
6033 			dev_info(&vsi->back->pdev->dev,
6034 				 "Failed to reset tx rate for ch->seid %u\n",
6035 				 ch->seid);
6036 
6037 		/* delete cloud filters associated with this channel */
6038 		hlist_for_each_entry_safe(cfilter, node,
6039 					  &pf->cloud_filter_list, cloud_node) {
6040 			if (cfilter->seid != ch->seid)
6041 				continue;
6042 
6043 			hash_del(&cfilter->cloud_node);
6044 			if (cfilter->dst_port)
6045 				ret = i40e_add_del_cloud_filter_big_buf(vsi,
6046 									cfilter,
6047 									false);
6048 			else
6049 				ret = i40e_add_del_cloud_filter(vsi, cfilter,
6050 								false);
6051 			last_aq_status = pf->hw.aq.asq_last_status;
6052 			if (ret)
6053 				dev_info(&pf->pdev->dev,
6054 					 "Failed to delete cloud filter, err %pe aq_err %s\n",
6055 					 ERR_PTR(ret),
6056 					 i40e_aq_str(&pf->hw, last_aq_status));
6057 			kfree(cfilter);
6058 		}
6059 
6060 		/* delete VSI from FW */
6061 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
6062 					     NULL);
6063 		if (ret)
6064 			dev_err(&vsi->back->pdev->dev,
6065 				"unable to remove channel (%d) for parent VSI(%d)\n",
6066 				ch->seid, p_vsi->seid);
6067 		kfree(ch);
6068 	}
6069 	INIT_LIST_HEAD(&vsi->ch_list);
6070 }
6071 
6072 /**
6073  * i40e_get_max_queues_for_channel
6074  * @vsi: ptr to VSI to which channels are associated with
6075  *
6076  * Helper function which returns max value among the queue counts set on the
6077  * channels/TCs created.
6078  **/
6079 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
6080 {
6081 	struct i40e_channel *ch, *ch_tmp;
6082 	int max = 0;
6083 
6084 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6085 		if (!ch->initialized)
6086 			continue;
6087 		if (ch->num_queue_pairs > max)
6088 			max = ch->num_queue_pairs;
6089 	}
6090 
6091 	return max;
6092 }
6093 
6094 /**
6095  * i40e_validate_num_queues - validate num_queues w.r.t channel
6096  * @pf: ptr to PF device
6097  * @num_queues: number of queues
6098  * @vsi: the parent VSI
6099  * @reconfig_rss: indicates should the RSS be reconfigured or not
6100  *
6101  * This function validates number of queues in the context of new channel
6102  * which is being established and determines if RSS should be reconfigured
6103  * or not for parent VSI.
6104  **/
6105 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
6106 				    struct i40e_vsi *vsi, bool *reconfig_rss)
6107 {
6108 	int max_ch_queues;
6109 
6110 	if (!reconfig_rss)
6111 		return -EINVAL;
6112 
6113 	*reconfig_rss = false;
6114 	if (vsi->current_rss_size) {
6115 		if (num_queues > vsi->current_rss_size) {
6116 			dev_dbg(&pf->pdev->dev,
6117 				"Error: num_queues (%d) > vsi's current_size(%d)\n",
6118 				num_queues, vsi->current_rss_size);
6119 			return -EINVAL;
6120 		} else if ((num_queues < vsi->current_rss_size) &&
6121 			   (!is_power_of_2(num_queues))) {
6122 			dev_dbg(&pf->pdev->dev,
6123 				"Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
6124 				num_queues, vsi->current_rss_size);
6125 			return -EINVAL;
6126 		}
6127 	}
6128 
6129 	if (!is_power_of_2(num_queues)) {
6130 		/* Find the max num_queues configured for channel if channel
6131 		 * exist.
6132 		 * if channel exist, then enforce 'num_queues' to be more than
6133 		 * max ever queues configured for channel.
6134 		 */
6135 		max_ch_queues = i40e_get_max_queues_for_channel(vsi);
6136 		if (num_queues < max_ch_queues) {
6137 			dev_dbg(&pf->pdev->dev,
6138 				"Error: num_queues (%d) < max queues configured for channel(%d)\n",
6139 				num_queues, max_ch_queues);
6140 			return -EINVAL;
6141 		}
6142 		*reconfig_rss = true;
6143 	}
6144 
6145 	return 0;
6146 }
6147 
6148 /**
6149  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
6150  * @vsi: the VSI being setup
6151  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
6152  *
6153  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
6154  **/
6155 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
6156 {
6157 	struct i40e_pf *pf = vsi->back;
6158 	u8 seed[I40E_HKEY_ARRAY_SIZE];
6159 	struct i40e_hw *hw = &pf->hw;
6160 	int local_rss_size;
6161 	u8 *lut;
6162 	int ret;
6163 
6164 	if (!vsi->rss_size)
6165 		return -EINVAL;
6166 
6167 	if (rss_size > vsi->rss_size)
6168 		return -EINVAL;
6169 
6170 	local_rss_size = min_t(int, vsi->rss_size, rss_size);
6171 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
6172 	if (!lut)
6173 		return -ENOMEM;
6174 
6175 	/* Ignoring user configured lut if there is one */
6176 	i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
6177 
6178 	/* Use user configured hash key if there is one, otherwise
6179 	 * use default.
6180 	 */
6181 	if (vsi->rss_hkey_user)
6182 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
6183 	else
6184 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
6185 
6186 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
6187 	if (ret) {
6188 		dev_info(&pf->pdev->dev,
6189 			 "Cannot set RSS lut, err %pe aq_err %s\n",
6190 			 ERR_PTR(ret),
6191 			 i40e_aq_str(hw, hw->aq.asq_last_status));
6192 		kfree(lut);
6193 		return ret;
6194 	}
6195 	kfree(lut);
6196 
6197 	/* Do the update w.r.t. storing rss_size */
6198 	if (!vsi->orig_rss_size)
6199 		vsi->orig_rss_size = vsi->rss_size;
6200 	vsi->current_rss_size = local_rss_size;
6201 
6202 	return ret;
6203 }
6204 
6205 /**
6206  * i40e_channel_setup_queue_map - Setup a channel queue map
6207  * @pf: ptr to PF device
6208  * @ctxt: VSI context structure
6209  * @ch: ptr to channel structure
6210  *
6211  * Setup queue map for a specific channel
6212  **/
6213 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
6214 					 struct i40e_vsi_context *ctxt,
6215 					 struct i40e_channel *ch)
6216 {
6217 	u16 qcount, qmap, sections = 0;
6218 	u8 offset = 0;
6219 	int pow;
6220 
6221 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
6222 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
6223 
6224 	qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
6225 	ch->num_queue_pairs = qcount;
6226 
6227 	/* find the next higher power-of-2 of num queue pairs */
6228 	pow = ilog2(qcount);
6229 	if (!is_power_of_2(qcount))
6230 		pow++;
6231 
6232 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
6233 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
6234 
6235 	/* Setup queue TC[0].qmap for given VSI context */
6236 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
6237 
6238 	ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
6239 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
6240 	ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
6241 	ctxt->info.valid_sections |= cpu_to_le16(sections);
6242 }
6243 
6244 /**
6245  * i40e_add_channel - add a channel by adding VSI
6246  * @pf: ptr to PF device
6247  * @uplink_seid: underlying HW switching element (VEB) ID
6248  * @ch: ptr to channel structure
6249  *
6250  * Add a channel (VSI) using add_vsi and queue_map
6251  **/
6252 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
6253 			    struct i40e_channel *ch)
6254 {
6255 	struct i40e_hw *hw = &pf->hw;
6256 	struct i40e_vsi_context ctxt;
6257 	u8 enabled_tc = 0x1; /* TC0 enabled */
6258 	int ret;
6259 
6260 	if (ch->type != I40E_VSI_VMDQ2) {
6261 		dev_info(&pf->pdev->dev,
6262 			 "add new vsi failed, ch->type %d\n", ch->type);
6263 		return -EINVAL;
6264 	}
6265 
6266 	memset(&ctxt, 0, sizeof(ctxt));
6267 	ctxt.pf_num = hw->pf_id;
6268 	ctxt.vf_num = 0;
6269 	ctxt.uplink_seid = uplink_seid;
6270 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
6271 	if (ch->type == I40E_VSI_VMDQ2)
6272 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
6273 
6274 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED) {
6275 		ctxt.info.valid_sections |=
6276 		     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6277 		ctxt.info.switch_id =
6278 		   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6279 	}
6280 
6281 	/* Set queue map for a given VSI context */
6282 	i40e_channel_setup_queue_map(pf, &ctxt, ch);
6283 
6284 	/* Now time to create VSI */
6285 	ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
6286 	if (ret) {
6287 		dev_info(&pf->pdev->dev,
6288 			 "add new vsi failed, err %pe aq_err %s\n",
6289 			 ERR_PTR(ret),
6290 			 i40e_aq_str(&pf->hw,
6291 				     pf->hw.aq.asq_last_status));
6292 		return -ENOENT;
6293 	}
6294 
6295 	/* Success, update channel, set enabled_tc only if the channel
6296 	 * is not a macvlan
6297 	 */
6298 	ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
6299 	ch->seid = ctxt.seid;
6300 	ch->vsi_number = ctxt.vsi_number;
6301 	ch->stat_counter_idx = le16_to_cpu(ctxt.info.stat_counter_idx);
6302 
6303 	/* copy just the sections touched not the entire info
6304 	 * since not all sections are valid as returned by
6305 	 * update vsi params
6306 	 */
6307 	ch->info.mapping_flags = ctxt.info.mapping_flags;
6308 	memcpy(&ch->info.queue_mapping,
6309 	       &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
6310 	memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
6311 	       sizeof(ctxt.info.tc_mapping));
6312 
6313 	return 0;
6314 }
6315 
6316 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
6317 				  u8 *bw_share)
6318 {
6319 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
6320 	int ret;
6321 	int i;
6322 
6323 	memset(&bw_data, 0, sizeof(bw_data));
6324 	bw_data.tc_valid_bits = ch->enabled_tc;
6325 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6326 		bw_data.tc_bw_credits[i] = bw_share[i];
6327 
6328 	ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
6329 				       &bw_data, NULL);
6330 	if (ret) {
6331 		dev_info(&vsi->back->pdev->dev,
6332 			 "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
6333 			 vsi->back->hw.aq.asq_last_status, ch->seid);
6334 		return -EINVAL;
6335 	}
6336 
6337 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6338 		ch->info.qs_handle[i] = bw_data.qs_handles[i];
6339 
6340 	return 0;
6341 }
6342 
6343 /**
6344  * i40e_channel_config_tx_ring - config TX ring associated with new channel
6345  * @pf: ptr to PF device
6346  * @vsi: the VSI being setup
6347  * @ch: ptr to channel structure
6348  *
6349  * Configure TX rings associated with channel (VSI) since queues are being
6350  * from parent VSI.
6351  **/
6352 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
6353 				       struct i40e_vsi *vsi,
6354 				       struct i40e_channel *ch)
6355 {
6356 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
6357 	int ret;
6358 	int i;
6359 
6360 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
6361 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6362 		if (ch->enabled_tc & BIT(i))
6363 			bw_share[i] = 1;
6364 	}
6365 
6366 	/* configure BW for new VSI */
6367 	ret = i40e_channel_config_bw(vsi, ch, bw_share);
6368 	if (ret) {
6369 		dev_info(&vsi->back->pdev->dev,
6370 			 "Failed configuring TC map %d for channel (seid %u)\n",
6371 			 ch->enabled_tc, ch->seid);
6372 		return ret;
6373 	}
6374 
6375 	for (i = 0; i < ch->num_queue_pairs; i++) {
6376 		struct i40e_ring *tx_ring, *rx_ring;
6377 		u16 pf_q;
6378 
6379 		pf_q = ch->base_queue + i;
6380 
6381 		/* Get to TX ring ptr of main VSI, for re-setup TX queue
6382 		 * context
6383 		 */
6384 		tx_ring = vsi->tx_rings[pf_q];
6385 		tx_ring->ch = ch;
6386 
6387 		/* Get the RX ring ptr */
6388 		rx_ring = vsi->rx_rings[pf_q];
6389 		rx_ring->ch = ch;
6390 	}
6391 
6392 	return 0;
6393 }
6394 
6395 /**
6396  * i40e_setup_hw_channel - setup new channel
6397  * @pf: ptr to PF device
6398  * @vsi: the VSI being setup
6399  * @ch: ptr to channel structure
6400  * @uplink_seid: underlying HW switching element (VEB) ID
6401  * @type: type of channel to be created (VMDq2/VF)
6402  *
6403  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6404  * and configures TX rings accordingly
6405  **/
6406 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
6407 					struct i40e_vsi *vsi,
6408 					struct i40e_channel *ch,
6409 					u16 uplink_seid, u8 type)
6410 {
6411 	int ret;
6412 
6413 	ch->initialized = false;
6414 	ch->base_queue = vsi->next_base_queue;
6415 	ch->type = type;
6416 
6417 	/* Proceed with creation of channel (VMDq2) VSI */
6418 	ret = i40e_add_channel(pf, uplink_seid, ch);
6419 	if (ret) {
6420 		dev_info(&pf->pdev->dev,
6421 			 "failed to add_channel using uplink_seid %u\n",
6422 			 uplink_seid);
6423 		return ret;
6424 	}
6425 
6426 	/* Mark the successful creation of channel */
6427 	ch->initialized = true;
6428 
6429 	/* Reconfigure TX queues using QTX_CTL register */
6430 	ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6431 	if (ret) {
6432 		dev_info(&pf->pdev->dev,
6433 			 "failed to configure TX rings for channel %u\n",
6434 			 ch->seid);
6435 		return ret;
6436 	}
6437 
6438 	/* update 'next_base_queue' */
6439 	vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6440 	dev_dbg(&pf->pdev->dev,
6441 		"Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6442 		ch->seid, ch->vsi_number, ch->stat_counter_idx,
6443 		ch->num_queue_pairs,
6444 		vsi->next_base_queue);
6445 	return ret;
6446 }
6447 
6448 /**
6449  * i40e_setup_channel - setup new channel using uplink element
6450  * @pf: ptr to PF device
6451  * @vsi: pointer to the VSI to set up the channel within
6452  * @ch: ptr to channel structure
6453  *
6454  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6455  * and uplink switching element (uplink_seid)
6456  **/
6457 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6458 			       struct i40e_channel *ch)
6459 {
6460 	u8 vsi_type;
6461 	u16 seid;
6462 	int ret;
6463 
6464 	if (vsi->type == I40E_VSI_MAIN) {
6465 		vsi_type = I40E_VSI_VMDQ2;
6466 	} else {
6467 		dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6468 			vsi->type);
6469 		return false;
6470 	}
6471 
6472 	/* underlying switching element */
6473 	seid = pf->vsi[pf->lan_vsi]->uplink_seid;
6474 
6475 	/* create channel (VSI), configure TX rings */
6476 	ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6477 	if (ret) {
6478 		dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6479 		return false;
6480 	}
6481 
6482 	return ch->initialized ? true : false;
6483 }
6484 
6485 /**
6486  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6487  * @vsi: ptr to VSI which has PF backing
6488  *
6489  * Sets up switch mode correctly if it needs to be changed and perform
6490  * what are allowed modes.
6491  **/
6492 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6493 {
6494 	u8 mode;
6495 	struct i40e_pf *pf = vsi->back;
6496 	struct i40e_hw *hw = &pf->hw;
6497 	int ret;
6498 
6499 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6500 	if (ret)
6501 		return -EINVAL;
6502 
6503 	if (hw->dev_caps.switch_mode) {
6504 		/* if switch mode is set, support mode2 (non-tunneled for
6505 		 * cloud filter) for now
6506 		 */
6507 		u32 switch_mode = hw->dev_caps.switch_mode &
6508 				  I40E_SWITCH_MODE_MASK;
6509 		if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6510 			if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6511 				return 0;
6512 			dev_err(&pf->pdev->dev,
6513 				"Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6514 				hw->dev_caps.switch_mode);
6515 			return -EINVAL;
6516 		}
6517 	}
6518 
6519 	/* Set Bit 7 to be valid */
6520 	mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6521 
6522 	/* Set L4type for TCP support */
6523 	mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6524 
6525 	/* Set cloud filter mode */
6526 	mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6527 
6528 	/* Prep mode field for set_switch_config */
6529 	ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6530 					pf->last_sw_conf_valid_flags,
6531 					mode, NULL);
6532 	if (ret && hw->aq.asq_last_status != I40E_AQ_RC_ESRCH)
6533 		dev_err(&pf->pdev->dev,
6534 			"couldn't set switch config bits, err %pe aq_err %s\n",
6535 			ERR_PTR(ret),
6536 			i40e_aq_str(hw,
6537 				    hw->aq.asq_last_status));
6538 
6539 	return ret;
6540 }
6541 
6542 /**
6543  * i40e_create_queue_channel - function to create channel
6544  * @vsi: VSI to be configured
6545  * @ch: ptr to channel (it contains channel specific params)
6546  *
6547  * This function creates channel (VSI) using num_queues specified by user,
6548  * reconfigs RSS if needed.
6549  **/
6550 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6551 			      struct i40e_channel *ch)
6552 {
6553 	struct i40e_pf *pf = vsi->back;
6554 	bool reconfig_rss;
6555 	int err;
6556 
6557 	if (!ch)
6558 		return -EINVAL;
6559 
6560 	if (!ch->num_queue_pairs) {
6561 		dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6562 			ch->num_queue_pairs);
6563 		return -EINVAL;
6564 	}
6565 
6566 	/* validate user requested num_queues for channel */
6567 	err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6568 				       &reconfig_rss);
6569 	if (err) {
6570 		dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6571 			 ch->num_queue_pairs);
6572 		return -EINVAL;
6573 	}
6574 
6575 	/* By default we are in VEPA mode, if this is the first VF/VMDq
6576 	 * VSI to be added switch to VEB mode.
6577 	 */
6578 
6579 	if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
6580 		pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
6581 
6582 		if (vsi->type == I40E_VSI_MAIN) {
6583 			if (i40e_is_tc_mqprio_enabled(pf))
6584 				i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
6585 			else
6586 				i40e_do_reset_safe(pf, I40E_PF_RESET_FLAG);
6587 		}
6588 		/* now onwards for main VSI, number of queues will be value
6589 		 * of TC0's queue count
6590 		 */
6591 	}
6592 
6593 	/* By this time, vsi->cnt_q_avail shall be set to non-zero and
6594 	 * it should be more than num_queues
6595 	 */
6596 	if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6597 		dev_dbg(&pf->pdev->dev,
6598 			"Error: cnt_q_avail (%u) less than num_queues %d\n",
6599 			vsi->cnt_q_avail, ch->num_queue_pairs);
6600 		return -EINVAL;
6601 	}
6602 
6603 	/* reconfig_rss only if vsi type is MAIN_VSI */
6604 	if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6605 		err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6606 		if (err) {
6607 			dev_info(&pf->pdev->dev,
6608 				 "Error: unable to reconfig rss for num_queues (%u)\n",
6609 				 ch->num_queue_pairs);
6610 			return -EINVAL;
6611 		}
6612 	}
6613 
6614 	if (!i40e_setup_channel(pf, vsi, ch)) {
6615 		dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6616 		return -EINVAL;
6617 	}
6618 
6619 	dev_info(&pf->pdev->dev,
6620 		 "Setup channel (id:%u) utilizing num_queues %d\n",
6621 		 ch->seid, ch->num_queue_pairs);
6622 
6623 	/* configure VSI for BW limit */
6624 	if (ch->max_tx_rate) {
6625 		u64 credits = ch->max_tx_rate;
6626 
6627 		if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6628 			return -EINVAL;
6629 
6630 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
6631 		dev_dbg(&pf->pdev->dev,
6632 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6633 			ch->max_tx_rate,
6634 			credits,
6635 			ch->seid);
6636 	}
6637 
6638 	/* in case of VF, this will be main SRIOV VSI */
6639 	ch->parent_vsi = vsi;
6640 
6641 	/* and update main_vsi's count for queue_available to use */
6642 	vsi->cnt_q_avail -= ch->num_queue_pairs;
6643 
6644 	return 0;
6645 }
6646 
6647 /**
6648  * i40e_configure_queue_channels - Add queue channel for the given TCs
6649  * @vsi: VSI to be configured
6650  *
6651  * Configures queue channel mapping to the given TCs
6652  **/
6653 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6654 {
6655 	struct i40e_channel *ch;
6656 	u64 max_rate = 0;
6657 	int ret = 0, i;
6658 
6659 	/* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6660 	vsi->tc_seid_map[0] = vsi->seid;
6661 	for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6662 		if (vsi->tc_config.enabled_tc & BIT(i)) {
6663 			ch = kzalloc(sizeof(*ch), GFP_KERNEL);
6664 			if (!ch) {
6665 				ret = -ENOMEM;
6666 				goto err_free;
6667 			}
6668 
6669 			INIT_LIST_HEAD(&ch->list);
6670 			ch->num_queue_pairs =
6671 				vsi->tc_config.tc_info[i].qcount;
6672 			ch->base_queue =
6673 				vsi->tc_config.tc_info[i].qoffset;
6674 
6675 			/* Bandwidth limit through tc interface is in bytes/s,
6676 			 * change to Mbit/s
6677 			 */
6678 			max_rate = vsi->mqprio_qopt.max_rate[i];
6679 			do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6680 			ch->max_tx_rate = max_rate;
6681 
6682 			list_add_tail(&ch->list, &vsi->ch_list);
6683 
6684 			ret = i40e_create_queue_channel(vsi, ch);
6685 			if (ret) {
6686 				dev_err(&vsi->back->pdev->dev,
6687 					"Failed creating queue channel with TC%d: queues %d\n",
6688 					i, ch->num_queue_pairs);
6689 				goto err_free;
6690 			}
6691 			vsi->tc_seid_map[i] = ch->seid;
6692 		}
6693 	}
6694 
6695 	/* reset to reconfigure TX queue contexts */
6696 	i40e_do_reset(vsi->back, I40E_PF_RESET_FLAG, true);
6697 	return ret;
6698 
6699 err_free:
6700 	i40e_remove_queue_channels(vsi);
6701 	return ret;
6702 }
6703 
6704 /**
6705  * i40e_veb_config_tc - Configure TCs for given VEB
6706  * @veb: given VEB
6707  * @enabled_tc: TC bitmap
6708  *
6709  * Configures given TC bitmap for VEB (switching) element
6710  **/
6711 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6712 {
6713 	struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6714 	struct i40e_pf *pf = veb->pf;
6715 	int ret = 0;
6716 	int i;
6717 
6718 	/* No TCs or already enabled TCs just return */
6719 	if (!enabled_tc || veb->enabled_tc == enabled_tc)
6720 		return ret;
6721 
6722 	bw_data.tc_valid_bits = enabled_tc;
6723 	/* bw_data.absolute_credits is not set (relative) */
6724 
6725 	/* Enable ETS TCs with equal BW Share for now */
6726 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6727 		if (enabled_tc & BIT(i))
6728 			bw_data.tc_bw_share_credits[i] = 1;
6729 	}
6730 
6731 	ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6732 						   &bw_data, NULL);
6733 	if (ret) {
6734 		dev_info(&pf->pdev->dev,
6735 			 "VEB bw config failed, err %pe aq_err %s\n",
6736 			 ERR_PTR(ret),
6737 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6738 		goto out;
6739 	}
6740 
6741 	/* Update the BW information */
6742 	ret = i40e_veb_get_bw_info(veb);
6743 	if (ret) {
6744 		dev_info(&pf->pdev->dev,
6745 			 "Failed getting veb bw config, err %pe aq_err %s\n",
6746 			 ERR_PTR(ret),
6747 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6748 	}
6749 
6750 out:
6751 	return ret;
6752 }
6753 
6754 #ifdef CONFIG_I40E_DCB
6755 /**
6756  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6757  * @pf: PF struct
6758  *
6759  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6760  * the caller would've quiesce all the VSIs before calling
6761  * this function
6762  **/
6763 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6764 {
6765 	u8 tc_map = 0;
6766 	int ret;
6767 	u8 v;
6768 
6769 	/* Enable the TCs available on PF to all VEBs */
6770 	tc_map = i40e_pf_get_tc_map(pf);
6771 	if (tc_map == I40E_DEFAULT_TRAFFIC_CLASS)
6772 		return;
6773 
6774 	for (v = 0; v < I40E_MAX_VEB; v++) {
6775 		if (!pf->veb[v])
6776 			continue;
6777 		ret = i40e_veb_config_tc(pf->veb[v], tc_map);
6778 		if (ret) {
6779 			dev_info(&pf->pdev->dev,
6780 				 "Failed configuring TC for VEB seid=%d\n",
6781 				 pf->veb[v]->seid);
6782 			/* Will try to configure as many components */
6783 		}
6784 	}
6785 
6786 	/* Update each VSI */
6787 	for (v = 0; v < pf->num_alloc_vsi; v++) {
6788 		if (!pf->vsi[v])
6789 			continue;
6790 
6791 		/* - Enable all TCs for the LAN VSI
6792 		 * - For all others keep them at TC0 for now
6793 		 */
6794 		if (v == pf->lan_vsi)
6795 			tc_map = i40e_pf_get_tc_map(pf);
6796 		else
6797 			tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6798 
6799 		ret = i40e_vsi_config_tc(pf->vsi[v], tc_map);
6800 		if (ret) {
6801 			dev_info(&pf->pdev->dev,
6802 				 "Failed configuring TC for VSI seid=%d\n",
6803 				 pf->vsi[v]->seid);
6804 			/* Will try to configure as many components */
6805 		} else {
6806 			/* Re-configure VSI vectors based on updated TC map */
6807 			i40e_vsi_map_rings_to_vectors(pf->vsi[v]);
6808 			if (pf->vsi[v]->netdev)
6809 				i40e_dcbnl_set_all(pf->vsi[v]);
6810 		}
6811 	}
6812 }
6813 
6814 /**
6815  * i40e_resume_port_tx - Resume port Tx
6816  * @pf: PF struct
6817  *
6818  * Resume a port's Tx and issue a PF reset in case of failure to
6819  * resume.
6820  **/
6821 static int i40e_resume_port_tx(struct i40e_pf *pf)
6822 {
6823 	struct i40e_hw *hw = &pf->hw;
6824 	int ret;
6825 
6826 	ret = i40e_aq_resume_port_tx(hw, NULL);
6827 	if (ret) {
6828 		dev_info(&pf->pdev->dev,
6829 			 "Resume Port Tx failed, err %pe aq_err %s\n",
6830 			  ERR_PTR(ret),
6831 			  i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6832 		/* Schedule PF reset to recover */
6833 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6834 		i40e_service_event_schedule(pf);
6835 	}
6836 
6837 	return ret;
6838 }
6839 
6840 /**
6841  * i40e_suspend_port_tx - Suspend port Tx
6842  * @pf: PF struct
6843  *
6844  * Suspend a port's Tx and issue a PF reset in case of failure.
6845  **/
6846 static int i40e_suspend_port_tx(struct i40e_pf *pf)
6847 {
6848 	struct i40e_hw *hw = &pf->hw;
6849 	int ret;
6850 
6851 	ret = i40e_aq_suspend_port_tx(hw, pf->mac_seid, NULL);
6852 	if (ret) {
6853 		dev_info(&pf->pdev->dev,
6854 			 "Suspend Port Tx failed, err %pe aq_err %s\n",
6855 			 ERR_PTR(ret),
6856 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6857 		/* Schedule PF reset to recover */
6858 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6859 		i40e_service_event_schedule(pf);
6860 	}
6861 
6862 	return ret;
6863 }
6864 
6865 /**
6866  * i40e_hw_set_dcb_config - Program new DCBX settings into HW
6867  * @pf: PF being configured
6868  * @new_cfg: New DCBX configuration
6869  *
6870  * Program DCB settings into HW and reconfigure VEB/VSIs on
6871  * given PF. Uses "Set LLDP MIB" AQC to program the hardware.
6872  **/
6873 static int i40e_hw_set_dcb_config(struct i40e_pf *pf,
6874 				  struct i40e_dcbx_config *new_cfg)
6875 {
6876 	struct i40e_dcbx_config *old_cfg = &pf->hw.local_dcbx_config;
6877 	int ret;
6878 
6879 	/* Check if need reconfiguration */
6880 	if (!memcmp(&new_cfg, &old_cfg, sizeof(new_cfg))) {
6881 		dev_dbg(&pf->pdev->dev, "No Change in DCB Config required.\n");
6882 		return 0;
6883 	}
6884 
6885 	/* Config change disable all VSIs */
6886 	i40e_pf_quiesce_all_vsi(pf);
6887 
6888 	/* Copy the new config to the current config */
6889 	*old_cfg = *new_cfg;
6890 	old_cfg->etsrec = old_cfg->etscfg;
6891 	ret = i40e_set_dcb_config(&pf->hw);
6892 	if (ret) {
6893 		dev_info(&pf->pdev->dev,
6894 			 "Set DCB Config failed, err %pe aq_err %s\n",
6895 			 ERR_PTR(ret),
6896 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6897 		goto out;
6898 	}
6899 
6900 	/* Changes in configuration update VEB/VSI */
6901 	i40e_dcb_reconfigure(pf);
6902 out:
6903 	/* In case of reset do not try to resume anything */
6904 	if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
6905 		/* Re-start the VSIs if disabled */
6906 		ret = i40e_resume_port_tx(pf);
6907 		/* In case of error no point in resuming VSIs */
6908 		if (ret)
6909 			goto err;
6910 		i40e_pf_unquiesce_all_vsi(pf);
6911 	}
6912 err:
6913 	return ret;
6914 }
6915 
6916 /**
6917  * i40e_hw_dcb_config - Program new DCBX settings into HW
6918  * @pf: PF being configured
6919  * @new_cfg: New DCBX configuration
6920  *
6921  * Program DCB settings into HW and reconfigure VEB/VSIs on
6922  * given PF
6923  **/
6924 int i40e_hw_dcb_config(struct i40e_pf *pf, struct i40e_dcbx_config *new_cfg)
6925 {
6926 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6927 	u8 prio_type[I40E_MAX_TRAFFIC_CLASS] = {0};
6928 	u32 mfs_tc[I40E_MAX_TRAFFIC_CLASS];
6929 	struct i40e_dcbx_config *old_cfg;
6930 	u8 mode[I40E_MAX_TRAFFIC_CLASS];
6931 	struct i40e_rx_pb_config pb_cfg;
6932 	struct i40e_hw *hw = &pf->hw;
6933 	u8 num_ports = hw->num_ports;
6934 	bool need_reconfig;
6935 	int ret = -EINVAL;
6936 	u8 lltc_map = 0;
6937 	u8 tc_map = 0;
6938 	u8 new_numtc;
6939 	u8 i;
6940 
6941 	dev_dbg(&pf->pdev->dev, "Configuring DCB registers directly\n");
6942 	/* Un-pack information to Program ETS HW via shared API
6943 	 * numtc, tcmap
6944 	 * LLTC map
6945 	 * ETS/NON-ETS arbiter mode
6946 	 * max exponent (credit refills)
6947 	 * Total number of ports
6948 	 * PFC priority bit-map
6949 	 * Priority Table
6950 	 * BW % per TC
6951 	 * Arbiter mode between UPs sharing same TC
6952 	 * TSA table (ETS or non-ETS)
6953 	 * EEE enabled or not
6954 	 * MFS TC table
6955 	 */
6956 
6957 	new_numtc = i40e_dcb_get_num_tc(new_cfg);
6958 
6959 	memset(&ets_data, 0, sizeof(ets_data));
6960 	for (i = 0; i < new_numtc; i++) {
6961 		tc_map |= BIT(i);
6962 		switch (new_cfg->etscfg.tsatable[i]) {
6963 		case I40E_IEEE_TSA_ETS:
6964 			prio_type[i] = I40E_DCB_PRIO_TYPE_ETS;
6965 			ets_data.tc_bw_share_credits[i] =
6966 					new_cfg->etscfg.tcbwtable[i];
6967 			break;
6968 		case I40E_IEEE_TSA_STRICT:
6969 			prio_type[i] = I40E_DCB_PRIO_TYPE_STRICT;
6970 			lltc_map |= BIT(i);
6971 			ets_data.tc_bw_share_credits[i] =
6972 					I40E_DCB_STRICT_PRIO_CREDITS;
6973 			break;
6974 		default:
6975 			/* Invalid TSA type */
6976 			need_reconfig = false;
6977 			goto out;
6978 		}
6979 	}
6980 
6981 	old_cfg = &hw->local_dcbx_config;
6982 	/* Check if need reconfiguration */
6983 	need_reconfig = i40e_dcb_need_reconfig(pf, old_cfg, new_cfg);
6984 
6985 	/* If needed, enable/disable frame tagging, disable all VSIs
6986 	 * and suspend port tx
6987 	 */
6988 	if (need_reconfig) {
6989 		/* Enable DCB tagging only when more than one TC */
6990 		if (new_numtc > 1)
6991 			pf->flags |= I40E_FLAG_DCB_ENABLED;
6992 		else
6993 			pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6994 
6995 		set_bit(__I40E_PORT_SUSPENDED, pf->state);
6996 		/* Reconfiguration needed quiesce all VSIs */
6997 		i40e_pf_quiesce_all_vsi(pf);
6998 		ret = i40e_suspend_port_tx(pf);
6999 		if (ret)
7000 			goto err;
7001 	}
7002 
7003 	/* Configure Port ETS Tx Scheduler */
7004 	ets_data.tc_valid_bits = tc_map;
7005 	ets_data.tc_strict_priority_flags = lltc_map;
7006 	ret = i40e_aq_config_switch_comp_ets
7007 		(hw, pf->mac_seid, &ets_data,
7008 		 i40e_aqc_opc_modify_switching_comp_ets, NULL);
7009 	if (ret) {
7010 		dev_info(&pf->pdev->dev,
7011 			 "Modify Port ETS failed, err %pe aq_err %s\n",
7012 			 ERR_PTR(ret),
7013 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7014 		goto out;
7015 	}
7016 
7017 	/* Configure Rx ETS HW */
7018 	memset(&mode, I40E_DCB_ARB_MODE_ROUND_ROBIN, sizeof(mode));
7019 	i40e_dcb_hw_set_num_tc(hw, new_numtc);
7020 	i40e_dcb_hw_rx_fifo_config(hw, I40E_DCB_ARB_MODE_ROUND_ROBIN,
7021 				   I40E_DCB_ARB_MODE_STRICT_PRIORITY,
7022 				   I40E_DCB_DEFAULT_MAX_EXPONENT,
7023 				   lltc_map);
7024 	i40e_dcb_hw_rx_cmd_monitor_config(hw, new_numtc, num_ports);
7025 	i40e_dcb_hw_rx_ets_bw_config(hw, new_cfg->etscfg.tcbwtable, mode,
7026 				     prio_type);
7027 	i40e_dcb_hw_pfc_config(hw, new_cfg->pfc.pfcenable,
7028 			       new_cfg->etscfg.prioritytable);
7029 	i40e_dcb_hw_rx_up2tc_config(hw, new_cfg->etscfg.prioritytable);
7030 
7031 	/* Configure Rx Packet Buffers in HW */
7032 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7033 		mfs_tc[i] = pf->vsi[pf->lan_vsi]->netdev->mtu;
7034 		mfs_tc[i] += I40E_PACKET_HDR_PAD;
7035 	}
7036 
7037 	i40e_dcb_hw_calculate_pool_sizes(hw, num_ports,
7038 					 false, new_cfg->pfc.pfcenable,
7039 					 mfs_tc, &pb_cfg);
7040 	i40e_dcb_hw_rx_pb_config(hw, &pf->pb_cfg, &pb_cfg);
7041 
7042 	/* Update the local Rx Packet buffer config */
7043 	pf->pb_cfg = pb_cfg;
7044 
7045 	/* Inform the FW about changes to DCB configuration */
7046 	ret = i40e_aq_dcb_updated(&pf->hw, NULL);
7047 	if (ret) {
7048 		dev_info(&pf->pdev->dev,
7049 			 "DCB Updated failed, err %pe aq_err %s\n",
7050 			 ERR_PTR(ret),
7051 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7052 		goto out;
7053 	}
7054 
7055 	/* Update the port DCBx configuration */
7056 	*old_cfg = *new_cfg;
7057 
7058 	/* Changes in configuration update VEB/VSI */
7059 	i40e_dcb_reconfigure(pf);
7060 out:
7061 	/* Re-start the VSIs if disabled */
7062 	if (need_reconfig) {
7063 		ret = i40e_resume_port_tx(pf);
7064 
7065 		clear_bit(__I40E_PORT_SUSPENDED, pf->state);
7066 		/* In case of error no point in resuming VSIs */
7067 		if (ret)
7068 			goto err;
7069 
7070 		/* Wait for the PF's queues to be disabled */
7071 		ret = i40e_pf_wait_queues_disabled(pf);
7072 		if (ret) {
7073 			/* Schedule PF reset to recover */
7074 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
7075 			i40e_service_event_schedule(pf);
7076 			goto err;
7077 		} else {
7078 			i40e_pf_unquiesce_all_vsi(pf);
7079 			set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7080 			set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
7081 		}
7082 		/* registers are set, lets apply */
7083 		if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB)
7084 			ret = i40e_hw_set_dcb_config(pf, new_cfg);
7085 	}
7086 
7087 err:
7088 	return ret;
7089 }
7090 
7091 /**
7092  * i40e_dcb_sw_default_config - Set default DCB configuration when DCB in SW
7093  * @pf: PF being queried
7094  *
7095  * Set default DCB configuration in case DCB is to be done in SW.
7096  **/
7097 int i40e_dcb_sw_default_config(struct i40e_pf *pf)
7098 {
7099 	struct i40e_dcbx_config *dcb_cfg = &pf->hw.local_dcbx_config;
7100 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
7101 	struct i40e_hw *hw = &pf->hw;
7102 	int err;
7103 
7104 	if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB) {
7105 		/* Update the local cached instance with TC0 ETS */
7106 		memset(&pf->tmp_cfg, 0, sizeof(struct i40e_dcbx_config));
7107 		pf->tmp_cfg.etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7108 		pf->tmp_cfg.etscfg.maxtcs = 0;
7109 		pf->tmp_cfg.etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7110 		pf->tmp_cfg.etscfg.tsatable[0] = I40E_IEEE_TSA_ETS;
7111 		pf->tmp_cfg.pfc.willing = I40E_IEEE_DEFAULT_PFC_WILLING;
7112 		pf->tmp_cfg.pfc.pfccap = I40E_MAX_TRAFFIC_CLASS;
7113 		/* FW needs one App to configure HW */
7114 		pf->tmp_cfg.numapps = I40E_IEEE_DEFAULT_NUM_APPS;
7115 		pf->tmp_cfg.app[0].selector = I40E_APP_SEL_ETHTYPE;
7116 		pf->tmp_cfg.app[0].priority = I40E_IEEE_DEFAULT_APP_PRIO;
7117 		pf->tmp_cfg.app[0].protocolid = I40E_APP_PROTOID_FCOE;
7118 
7119 		return i40e_hw_set_dcb_config(pf, &pf->tmp_cfg);
7120 	}
7121 
7122 	memset(&ets_data, 0, sizeof(ets_data));
7123 	ets_data.tc_valid_bits = I40E_DEFAULT_TRAFFIC_CLASS; /* TC0 only */
7124 	ets_data.tc_strict_priority_flags = 0; /* ETS */
7125 	ets_data.tc_bw_share_credits[0] = I40E_IEEE_DEFAULT_ETS_TCBW; /* 100% to TC0 */
7126 
7127 	/* Enable ETS on the Physical port */
7128 	err = i40e_aq_config_switch_comp_ets
7129 		(hw, pf->mac_seid, &ets_data,
7130 		 i40e_aqc_opc_enable_switching_comp_ets, NULL);
7131 	if (err) {
7132 		dev_info(&pf->pdev->dev,
7133 			 "Enable Port ETS failed, err %pe aq_err %s\n",
7134 			 ERR_PTR(err),
7135 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7136 		err = -ENOENT;
7137 		goto out;
7138 	}
7139 
7140 	/* Update the local cached instance with TC0 ETS */
7141 	dcb_cfg->etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7142 	dcb_cfg->etscfg.cbs = 0;
7143 	dcb_cfg->etscfg.maxtcs = I40E_MAX_TRAFFIC_CLASS;
7144 	dcb_cfg->etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7145 
7146 out:
7147 	return err;
7148 }
7149 
7150 /**
7151  * i40e_init_pf_dcb - Initialize DCB configuration
7152  * @pf: PF being configured
7153  *
7154  * Query the current DCB configuration and cache it
7155  * in the hardware structure
7156  **/
7157 static int i40e_init_pf_dcb(struct i40e_pf *pf)
7158 {
7159 	struct i40e_hw *hw = &pf->hw;
7160 	int err;
7161 
7162 	/* Do not enable DCB for SW1 and SW2 images even if the FW is capable
7163 	 * Also do not enable DCBx if FW LLDP agent is disabled
7164 	 */
7165 	if (pf->hw_features & I40E_HW_NO_DCB_SUPPORT) {
7166 		dev_info(&pf->pdev->dev, "DCB is not supported.\n");
7167 		err = I40E_NOT_SUPPORTED;
7168 		goto out;
7169 	}
7170 	if (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) {
7171 		dev_info(&pf->pdev->dev, "FW LLDP is disabled, attempting SW DCB\n");
7172 		err = i40e_dcb_sw_default_config(pf);
7173 		if (err) {
7174 			dev_info(&pf->pdev->dev, "Could not initialize SW DCB\n");
7175 			goto out;
7176 		}
7177 		dev_info(&pf->pdev->dev, "SW DCB initialization succeeded.\n");
7178 		pf->dcbx_cap = DCB_CAP_DCBX_HOST |
7179 			       DCB_CAP_DCBX_VER_IEEE;
7180 		/* at init capable but disabled */
7181 		pf->flags |= I40E_FLAG_DCB_CAPABLE;
7182 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7183 		goto out;
7184 	}
7185 	err = i40e_init_dcb(hw, true);
7186 	if (!err) {
7187 		/* Device/Function is not DCBX capable */
7188 		if ((!hw->func_caps.dcb) ||
7189 		    (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
7190 			dev_info(&pf->pdev->dev,
7191 				 "DCBX offload is not supported or is disabled for this PF.\n");
7192 		} else {
7193 			/* When status is not DISABLED then DCBX in FW */
7194 			pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
7195 				       DCB_CAP_DCBX_VER_IEEE;
7196 
7197 			pf->flags |= I40E_FLAG_DCB_CAPABLE;
7198 			/* Enable DCB tagging only when more than one TC
7199 			 * or explicitly disable if only one TC
7200 			 */
7201 			if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
7202 				pf->flags |= I40E_FLAG_DCB_ENABLED;
7203 			else
7204 				pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7205 			dev_dbg(&pf->pdev->dev,
7206 				"DCBX offload is supported for this PF.\n");
7207 		}
7208 	} else if (pf->hw.aq.asq_last_status == I40E_AQ_RC_EPERM) {
7209 		dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
7210 		pf->flags |= I40E_FLAG_DISABLE_FW_LLDP;
7211 	} else {
7212 		dev_info(&pf->pdev->dev,
7213 			 "Query for DCB configuration failed, err %pe aq_err %s\n",
7214 			 ERR_PTR(err),
7215 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7216 	}
7217 
7218 out:
7219 	return err;
7220 }
7221 #endif /* CONFIG_I40E_DCB */
7222 
7223 /**
7224  * i40e_print_link_message - print link up or down
7225  * @vsi: the VSI for which link needs a message
7226  * @isup: true of link is up, false otherwise
7227  */
7228 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
7229 {
7230 	enum i40e_aq_link_speed new_speed;
7231 	struct i40e_pf *pf = vsi->back;
7232 	char *speed = "Unknown";
7233 	char *fc = "Unknown";
7234 	char *fec = "";
7235 	char *req_fec = "";
7236 	char *an = "";
7237 
7238 	if (isup)
7239 		new_speed = pf->hw.phy.link_info.link_speed;
7240 	else
7241 		new_speed = I40E_LINK_SPEED_UNKNOWN;
7242 
7243 	if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
7244 		return;
7245 	vsi->current_isup = isup;
7246 	vsi->current_speed = new_speed;
7247 	if (!isup) {
7248 		netdev_info(vsi->netdev, "NIC Link is Down\n");
7249 		return;
7250 	}
7251 
7252 	/* Warn user if link speed on NPAR enabled partition is not at
7253 	 * least 10GB
7254 	 */
7255 	if (pf->hw.func_caps.npar_enable &&
7256 	    (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
7257 	     pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
7258 		netdev_warn(vsi->netdev,
7259 			    "The partition detected link speed that is less than 10Gbps\n");
7260 
7261 	switch (pf->hw.phy.link_info.link_speed) {
7262 	case I40E_LINK_SPEED_40GB:
7263 		speed = "40 G";
7264 		break;
7265 	case I40E_LINK_SPEED_20GB:
7266 		speed = "20 G";
7267 		break;
7268 	case I40E_LINK_SPEED_25GB:
7269 		speed = "25 G";
7270 		break;
7271 	case I40E_LINK_SPEED_10GB:
7272 		speed = "10 G";
7273 		break;
7274 	case I40E_LINK_SPEED_5GB:
7275 		speed = "5 G";
7276 		break;
7277 	case I40E_LINK_SPEED_2_5GB:
7278 		speed = "2.5 G";
7279 		break;
7280 	case I40E_LINK_SPEED_1GB:
7281 		speed = "1000 M";
7282 		break;
7283 	case I40E_LINK_SPEED_100MB:
7284 		speed = "100 M";
7285 		break;
7286 	default:
7287 		break;
7288 	}
7289 
7290 	switch (pf->hw.fc.current_mode) {
7291 	case I40E_FC_FULL:
7292 		fc = "RX/TX";
7293 		break;
7294 	case I40E_FC_TX_PAUSE:
7295 		fc = "TX";
7296 		break;
7297 	case I40E_FC_RX_PAUSE:
7298 		fc = "RX";
7299 		break;
7300 	default:
7301 		fc = "None";
7302 		break;
7303 	}
7304 
7305 	if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
7306 		req_fec = "None";
7307 		fec = "None";
7308 		an = "False";
7309 
7310 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7311 			an = "True";
7312 
7313 		if (pf->hw.phy.link_info.fec_info &
7314 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7315 			fec = "CL74 FC-FEC/BASE-R";
7316 		else if (pf->hw.phy.link_info.fec_info &
7317 			 I40E_AQ_CONFIG_FEC_RS_ENA)
7318 			fec = "CL108 RS-FEC";
7319 
7320 		/* 'CL108 RS-FEC' should be displayed when RS is requested, or
7321 		 * both RS and FC are requested
7322 		 */
7323 		if (vsi->back->hw.phy.link_info.req_fec_info &
7324 		    (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
7325 			if (vsi->back->hw.phy.link_info.req_fec_info &
7326 			    I40E_AQ_REQUEST_FEC_RS)
7327 				req_fec = "CL108 RS-FEC";
7328 			else
7329 				req_fec = "CL74 FC-FEC/BASE-R";
7330 		}
7331 		netdev_info(vsi->netdev,
7332 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7333 			    speed, req_fec, fec, an, fc);
7334 	} else if (pf->hw.device_id == I40E_DEV_ID_KX_X722) {
7335 		req_fec = "None";
7336 		fec = "None";
7337 		an = "False";
7338 
7339 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7340 			an = "True";
7341 
7342 		if (pf->hw.phy.link_info.fec_info &
7343 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7344 			fec = "CL74 FC-FEC/BASE-R";
7345 
7346 		if (pf->hw.phy.link_info.req_fec_info &
7347 		    I40E_AQ_REQUEST_FEC_KR)
7348 			req_fec = "CL74 FC-FEC/BASE-R";
7349 
7350 		netdev_info(vsi->netdev,
7351 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7352 			    speed, req_fec, fec, an, fc);
7353 	} else {
7354 		netdev_info(vsi->netdev,
7355 			    "NIC Link is Up, %sbps Full Duplex, Flow Control: %s\n",
7356 			    speed, fc);
7357 	}
7358 
7359 }
7360 
7361 /**
7362  * i40e_up_complete - Finish the last steps of bringing up a connection
7363  * @vsi: the VSI being configured
7364  **/
7365 static int i40e_up_complete(struct i40e_vsi *vsi)
7366 {
7367 	struct i40e_pf *pf = vsi->back;
7368 	int err;
7369 
7370 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
7371 		i40e_vsi_configure_msix(vsi);
7372 	else
7373 		i40e_configure_msi_and_legacy(vsi);
7374 
7375 	/* start rings */
7376 	err = i40e_vsi_start_rings(vsi);
7377 	if (err)
7378 		return err;
7379 
7380 	clear_bit(__I40E_VSI_DOWN, vsi->state);
7381 	i40e_napi_enable_all(vsi);
7382 	i40e_vsi_enable_irq(vsi);
7383 
7384 	if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
7385 	    (vsi->netdev)) {
7386 		i40e_print_link_message(vsi, true);
7387 		netif_tx_start_all_queues(vsi->netdev);
7388 		netif_carrier_on(vsi->netdev);
7389 	}
7390 
7391 	/* replay FDIR SB filters */
7392 	if (vsi->type == I40E_VSI_FDIR) {
7393 		/* reset fd counters */
7394 		pf->fd_add_err = 0;
7395 		pf->fd_atr_cnt = 0;
7396 		i40e_fdir_filter_restore(vsi);
7397 	}
7398 
7399 	/* On the next run of the service_task, notify any clients of the new
7400 	 * opened netdev
7401 	 */
7402 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7403 	i40e_service_event_schedule(pf);
7404 
7405 	return 0;
7406 }
7407 
7408 /**
7409  * i40e_vsi_reinit_locked - Reset the VSI
7410  * @vsi: the VSI being configured
7411  *
7412  * Rebuild the ring structs after some configuration
7413  * has changed, e.g. MTU size.
7414  **/
7415 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
7416 {
7417 	struct i40e_pf *pf = vsi->back;
7418 
7419 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
7420 		usleep_range(1000, 2000);
7421 	i40e_down(vsi);
7422 
7423 	i40e_up(vsi);
7424 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
7425 }
7426 
7427 /**
7428  * i40e_force_link_state - Force the link status
7429  * @pf: board private structure
7430  * @is_up: whether the link state should be forced up or down
7431  **/
7432 static int i40e_force_link_state(struct i40e_pf *pf, bool is_up)
7433 {
7434 	struct i40e_aq_get_phy_abilities_resp abilities;
7435 	struct i40e_aq_set_phy_config config = {0};
7436 	bool non_zero_phy_type = is_up;
7437 	struct i40e_hw *hw = &pf->hw;
7438 	u64 mask;
7439 	u8 speed;
7440 	int err;
7441 
7442 	/* Card might've been put in an unstable state by other drivers
7443 	 * and applications, which causes incorrect speed values being
7444 	 * set on startup. In order to clear speed registers, we call
7445 	 * get_phy_capabilities twice, once to get initial state of
7446 	 * available speeds, and once to get current PHY config.
7447 	 */
7448 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
7449 					   NULL);
7450 	if (err) {
7451 		dev_err(&pf->pdev->dev,
7452 			"failed to get phy cap., ret =  %pe last_status =  %s\n",
7453 			ERR_PTR(err),
7454 			i40e_aq_str(hw, hw->aq.asq_last_status));
7455 		return err;
7456 	}
7457 	speed = abilities.link_speed;
7458 
7459 	/* Get the current phy config */
7460 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
7461 					   NULL);
7462 	if (err) {
7463 		dev_err(&pf->pdev->dev,
7464 			"failed to get phy cap., ret =  %pe last_status =  %s\n",
7465 			ERR_PTR(err),
7466 			i40e_aq_str(hw, hw->aq.asq_last_status));
7467 		return err;
7468 	}
7469 
7470 	/* If link needs to go up, but was not forced to go down,
7471 	 * and its speed values are OK, no need for a flap
7472 	 * if non_zero_phy_type was set, still need to force up
7473 	 */
7474 	if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED)
7475 		non_zero_phy_type = true;
7476 	else if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
7477 		return I40E_SUCCESS;
7478 
7479 	/* To force link we need to set bits for all supported PHY types,
7480 	 * but there are now more than 32, so we need to split the bitmap
7481 	 * across two fields.
7482 	 */
7483 	mask = I40E_PHY_TYPES_BITMASK;
7484 	config.phy_type =
7485 		non_zero_phy_type ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
7486 	config.phy_type_ext =
7487 		non_zero_phy_type ? (u8)((mask >> 32) & 0xff) : 0;
7488 	/* Copy the old settings, except of phy_type */
7489 	config.abilities = abilities.abilities;
7490 	if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED) {
7491 		if (is_up)
7492 			config.abilities |= I40E_AQ_PHY_ENABLE_LINK;
7493 		else
7494 			config.abilities &= ~(I40E_AQ_PHY_ENABLE_LINK);
7495 	}
7496 	if (abilities.link_speed != 0)
7497 		config.link_speed = abilities.link_speed;
7498 	else
7499 		config.link_speed = speed;
7500 	config.eee_capability = abilities.eee_capability;
7501 	config.eeer = abilities.eeer_val;
7502 	config.low_power_ctrl = abilities.d3_lpan;
7503 	config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
7504 			    I40E_AQ_PHY_FEC_CONFIG_MASK;
7505 	err = i40e_aq_set_phy_config(hw, &config, NULL);
7506 
7507 	if (err) {
7508 		dev_err(&pf->pdev->dev,
7509 			"set phy config ret =  %pe last_status =  %s\n",
7510 			ERR_PTR(err),
7511 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7512 		return err;
7513 	}
7514 
7515 	/* Update the link info */
7516 	err = i40e_update_link_info(hw);
7517 	if (err) {
7518 		/* Wait a little bit (on 40G cards it sometimes takes a really
7519 		 * long time for link to come back from the atomic reset)
7520 		 * and try once more
7521 		 */
7522 		msleep(1000);
7523 		i40e_update_link_info(hw);
7524 	}
7525 
7526 	i40e_aq_set_link_restart_an(hw, is_up, NULL);
7527 
7528 	return I40E_SUCCESS;
7529 }
7530 
7531 /**
7532  * i40e_up - Bring the connection back up after being down
7533  * @vsi: the VSI being configured
7534  **/
7535 int i40e_up(struct i40e_vsi *vsi)
7536 {
7537 	int err;
7538 
7539 	if (vsi->type == I40E_VSI_MAIN &&
7540 	    (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7541 	     vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7542 		i40e_force_link_state(vsi->back, true);
7543 
7544 	err = i40e_vsi_configure(vsi);
7545 	if (!err)
7546 		err = i40e_up_complete(vsi);
7547 
7548 	return err;
7549 }
7550 
7551 /**
7552  * i40e_down - Shutdown the connection processing
7553  * @vsi: the VSI being stopped
7554  **/
7555 void i40e_down(struct i40e_vsi *vsi)
7556 {
7557 	int i;
7558 
7559 	/* It is assumed that the caller of this function
7560 	 * sets the vsi->state __I40E_VSI_DOWN bit.
7561 	 */
7562 	if (vsi->netdev) {
7563 		netif_carrier_off(vsi->netdev);
7564 		netif_tx_disable(vsi->netdev);
7565 	}
7566 	i40e_vsi_disable_irq(vsi);
7567 	i40e_vsi_stop_rings(vsi);
7568 	if (vsi->type == I40E_VSI_MAIN &&
7569 	   (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7570 	    vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7571 		i40e_force_link_state(vsi->back, false);
7572 	i40e_napi_disable_all(vsi);
7573 
7574 	for (i = 0; i < vsi->num_queue_pairs; i++) {
7575 		i40e_clean_tx_ring(vsi->tx_rings[i]);
7576 		if (i40e_enabled_xdp_vsi(vsi)) {
7577 			/* Make sure that in-progress ndo_xdp_xmit and
7578 			 * ndo_xsk_wakeup calls are completed.
7579 			 */
7580 			synchronize_rcu();
7581 			i40e_clean_tx_ring(vsi->xdp_rings[i]);
7582 		}
7583 		i40e_clean_rx_ring(vsi->rx_rings[i]);
7584 	}
7585 
7586 }
7587 
7588 /**
7589  * i40e_validate_mqprio_qopt- validate queue mapping info
7590  * @vsi: the VSI being configured
7591  * @mqprio_qopt: queue parametrs
7592  **/
7593 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
7594 				     struct tc_mqprio_qopt_offload *mqprio_qopt)
7595 {
7596 	u64 sum_max_rate = 0;
7597 	u64 max_rate = 0;
7598 	int i;
7599 
7600 	if (mqprio_qopt->qopt.offset[0] != 0 ||
7601 	    mqprio_qopt->qopt.num_tc < 1 ||
7602 	    mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
7603 		return -EINVAL;
7604 	for (i = 0; ; i++) {
7605 		if (!mqprio_qopt->qopt.count[i])
7606 			return -EINVAL;
7607 		if (mqprio_qopt->min_rate[i]) {
7608 			dev_err(&vsi->back->pdev->dev,
7609 				"Invalid min tx rate (greater than 0) specified\n");
7610 			return -EINVAL;
7611 		}
7612 		max_rate = mqprio_qopt->max_rate[i];
7613 		do_div(max_rate, I40E_BW_MBPS_DIVISOR);
7614 		sum_max_rate += max_rate;
7615 
7616 		if (i >= mqprio_qopt->qopt.num_tc - 1)
7617 			break;
7618 		if (mqprio_qopt->qopt.offset[i + 1] !=
7619 		    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7620 			return -EINVAL;
7621 	}
7622 	if (vsi->num_queue_pairs <
7623 	    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
7624 		dev_err(&vsi->back->pdev->dev,
7625 			"Failed to create traffic channel, insufficient number of queues.\n");
7626 		return -EINVAL;
7627 	}
7628 	if (sum_max_rate > i40e_get_link_speed(vsi)) {
7629 		dev_err(&vsi->back->pdev->dev,
7630 			"Invalid max tx rate specified\n");
7631 		return -EINVAL;
7632 	}
7633 	return 0;
7634 }
7635 
7636 /**
7637  * i40e_vsi_set_default_tc_config - set default values for tc configuration
7638  * @vsi: the VSI being configured
7639  **/
7640 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
7641 {
7642 	u16 qcount;
7643 	int i;
7644 
7645 	/* Only TC0 is enabled */
7646 	vsi->tc_config.numtc = 1;
7647 	vsi->tc_config.enabled_tc = 1;
7648 	qcount = min_t(int, vsi->alloc_queue_pairs,
7649 		       i40e_pf_get_max_q_per_tc(vsi->back));
7650 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7651 		/* For the TC that is not enabled set the offset to default
7652 		 * queue and allocate one queue for the given TC.
7653 		 */
7654 		vsi->tc_config.tc_info[i].qoffset = 0;
7655 		if (i == 0)
7656 			vsi->tc_config.tc_info[i].qcount = qcount;
7657 		else
7658 			vsi->tc_config.tc_info[i].qcount = 1;
7659 		vsi->tc_config.tc_info[i].netdev_tc = 0;
7660 	}
7661 }
7662 
7663 /**
7664  * i40e_del_macvlan_filter
7665  * @hw: pointer to the HW structure
7666  * @seid: seid of the channel VSI
7667  * @macaddr: the mac address to apply as a filter
7668  * @aq_err: store the admin Q error
7669  *
7670  * This function deletes a mac filter on the channel VSI which serves as the
7671  * macvlan. Returns 0 on success.
7672  **/
7673 static int i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
7674 				   const u8 *macaddr, int *aq_err)
7675 {
7676 	struct i40e_aqc_remove_macvlan_element_data element;
7677 	int status;
7678 
7679 	memset(&element, 0, sizeof(element));
7680 	ether_addr_copy(element.mac_addr, macaddr);
7681 	element.vlan_tag = 0;
7682 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
7683 	status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
7684 	*aq_err = hw->aq.asq_last_status;
7685 
7686 	return status;
7687 }
7688 
7689 /**
7690  * i40e_add_macvlan_filter
7691  * @hw: pointer to the HW structure
7692  * @seid: seid of the channel VSI
7693  * @macaddr: the mac address to apply as a filter
7694  * @aq_err: store the admin Q error
7695  *
7696  * This function adds a mac filter on the channel VSI which serves as the
7697  * macvlan. Returns 0 on success.
7698  **/
7699 static int i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
7700 				   const u8 *macaddr, int *aq_err)
7701 {
7702 	struct i40e_aqc_add_macvlan_element_data element;
7703 	u16 cmd_flags = 0;
7704 	int status;
7705 
7706 	ether_addr_copy(element.mac_addr, macaddr);
7707 	element.vlan_tag = 0;
7708 	element.queue_number = 0;
7709 	element.match_method = I40E_AQC_MM_ERR_NO_RES;
7710 	cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
7711 	element.flags = cpu_to_le16(cmd_flags);
7712 	status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
7713 	*aq_err = hw->aq.asq_last_status;
7714 
7715 	return status;
7716 }
7717 
7718 /**
7719  * i40e_reset_ch_rings - Reset the queue contexts in a channel
7720  * @vsi: the VSI we want to access
7721  * @ch: the channel we want to access
7722  */
7723 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
7724 {
7725 	struct i40e_ring *tx_ring, *rx_ring;
7726 	u16 pf_q;
7727 	int i;
7728 
7729 	for (i = 0; i < ch->num_queue_pairs; i++) {
7730 		pf_q = ch->base_queue + i;
7731 		tx_ring = vsi->tx_rings[pf_q];
7732 		tx_ring->ch = NULL;
7733 		rx_ring = vsi->rx_rings[pf_q];
7734 		rx_ring->ch = NULL;
7735 	}
7736 }
7737 
7738 /**
7739  * i40e_free_macvlan_channels
7740  * @vsi: the VSI we want to access
7741  *
7742  * This function frees the Qs of the channel VSI from
7743  * the stack and also deletes the channel VSIs which
7744  * serve as macvlans.
7745  */
7746 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
7747 {
7748 	struct i40e_channel *ch, *ch_tmp;
7749 	int ret;
7750 
7751 	if (list_empty(&vsi->macvlan_list))
7752 		return;
7753 
7754 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7755 		struct i40e_vsi *parent_vsi;
7756 
7757 		if (i40e_is_channel_macvlan(ch)) {
7758 			i40e_reset_ch_rings(vsi, ch);
7759 			clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7760 			netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
7761 			netdev_set_sb_channel(ch->fwd->netdev, 0);
7762 			kfree(ch->fwd);
7763 			ch->fwd = NULL;
7764 		}
7765 
7766 		list_del(&ch->list);
7767 		parent_vsi = ch->parent_vsi;
7768 		if (!parent_vsi || !ch->initialized) {
7769 			kfree(ch);
7770 			continue;
7771 		}
7772 
7773 		/* remove the VSI */
7774 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
7775 					     NULL);
7776 		if (ret)
7777 			dev_err(&vsi->back->pdev->dev,
7778 				"unable to remove channel (%d) for parent VSI(%d)\n",
7779 				ch->seid, parent_vsi->seid);
7780 		kfree(ch);
7781 	}
7782 	vsi->macvlan_cnt = 0;
7783 }
7784 
7785 /**
7786  * i40e_fwd_ring_up - bring the macvlan device up
7787  * @vsi: the VSI we want to access
7788  * @vdev: macvlan netdevice
7789  * @fwd: the private fwd structure
7790  */
7791 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7792 			    struct i40e_fwd_adapter *fwd)
7793 {
7794 	struct i40e_channel *ch = NULL, *ch_tmp, *iter;
7795 	int ret = 0, num_tc = 1,  i, aq_err;
7796 	struct i40e_pf *pf = vsi->back;
7797 	struct i40e_hw *hw = &pf->hw;
7798 
7799 	/* Go through the list and find an available channel */
7800 	list_for_each_entry_safe(iter, ch_tmp, &vsi->macvlan_list, list) {
7801 		if (!i40e_is_channel_macvlan(iter)) {
7802 			iter->fwd = fwd;
7803 			/* record configuration for macvlan interface in vdev */
7804 			for (i = 0; i < num_tc; i++)
7805 				netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7806 							     i,
7807 							     iter->num_queue_pairs,
7808 							     iter->base_queue);
7809 			for (i = 0; i < iter->num_queue_pairs; i++) {
7810 				struct i40e_ring *tx_ring, *rx_ring;
7811 				u16 pf_q;
7812 
7813 				pf_q = iter->base_queue + i;
7814 
7815 				/* Get to TX ring ptr */
7816 				tx_ring = vsi->tx_rings[pf_q];
7817 				tx_ring->ch = iter;
7818 
7819 				/* Get the RX ring ptr */
7820 				rx_ring = vsi->rx_rings[pf_q];
7821 				rx_ring->ch = iter;
7822 			}
7823 			ch = iter;
7824 			break;
7825 		}
7826 	}
7827 
7828 	if (!ch)
7829 		return -EINVAL;
7830 
7831 	/* Guarantee all rings are updated before we update the
7832 	 * MAC address filter.
7833 	 */
7834 	wmb();
7835 
7836 	/* Add a mac filter */
7837 	ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7838 	if (ret) {
7839 		/* if we cannot add the MAC rule then disable the offload */
7840 		macvlan_release_l2fw_offload(vdev);
7841 		for (i = 0; i < ch->num_queue_pairs; i++) {
7842 			struct i40e_ring *rx_ring;
7843 			u16 pf_q;
7844 
7845 			pf_q = ch->base_queue + i;
7846 			rx_ring = vsi->rx_rings[pf_q];
7847 			rx_ring->netdev = NULL;
7848 		}
7849 		dev_info(&pf->pdev->dev,
7850 			 "Error adding mac filter on macvlan err %pe, aq_err %s\n",
7851 			  ERR_PTR(ret),
7852 			  i40e_aq_str(hw, aq_err));
7853 		netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7854 	}
7855 
7856 	return ret;
7857 }
7858 
7859 /**
7860  * i40e_setup_macvlans - create the channels which will be macvlans
7861  * @vsi: the VSI we want to access
7862  * @macvlan_cnt: no. of macvlans to be setup
7863  * @qcnt: no. of Qs per macvlan
7864  * @vdev: macvlan netdevice
7865  */
7866 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7867 			       struct net_device *vdev)
7868 {
7869 	struct i40e_pf *pf = vsi->back;
7870 	struct i40e_hw *hw = &pf->hw;
7871 	struct i40e_vsi_context ctxt;
7872 	u16 sections, qmap, num_qps;
7873 	struct i40e_channel *ch;
7874 	int i, pow, ret = 0;
7875 	u8 offset = 0;
7876 
7877 	if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7878 		return -EINVAL;
7879 
7880 	num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7881 
7882 	/* find the next higher power-of-2 of num queue pairs */
7883 	pow = fls(roundup_pow_of_two(num_qps) - 1);
7884 
7885 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7886 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7887 
7888 	/* Setup context bits for the main VSI */
7889 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7890 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7891 	memset(&ctxt, 0, sizeof(ctxt));
7892 	ctxt.seid = vsi->seid;
7893 	ctxt.pf_num = vsi->back->hw.pf_id;
7894 	ctxt.vf_num = 0;
7895 	ctxt.uplink_seid = vsi->uplink_seid;
7896 	ctxt.info = vsi->info;
7897 	ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7898 	ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7899 	ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7900 	ctxt.info.valid_sections |= cpu_to_le16(sections);
7901 
7902 	/* Reconfigure RSS for main VSI with new max queue count */
7903 	vsi->rss_size = max_t(u16, num_qps, qcnt);
7904 	ret = i40e_vsi_config_rss(vsi);
7905 	if (ret) {
7906 		dev_info(&pf->pdev->dev,
7907 			 "Failed to reconfig RSS for num_queues (%u)\n",
7908 			 vsi->rss_size);
7909 		return ret;
7910 	}
7911 	vsi->reconfig_rss = true;
7912 	dev_dbg(&vsi->back->pdev->dev,
7913 		"Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7914 	vsi->next_base_queue = num_qps;
7915 	vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7916 
7917 	/* Update the VSI after updating the VSI queue-mapping
7918 	 * information
7919 	 */
7920 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7921 	if (ret) {
7922 		dev_info(&pf->pdev->dev,
7923 			 "Update vsi tc config failed, err %pe aq_err %s\n",
7924 			 ERR_PTR(ret),
7925 			 i40e_aq_str(hw, hw->aq.asq_last_status));
7926 		return ret;
7927 	}
7928 	/* update the local VSI info with updated queue map */
7929 	i40e_vsi_update_queue_map(vsi, &ctxt);
7930 	vsi->info.valid_sections = 0;
7931 
7932 	/* Create channels for macvlans */
7933 	INIT_LIST_HEAD(&vsi->macvlan_list);
7934 	for (i = 0; i < macvlan_cnt; i++) {
7935 		ch = kzalloc(sizeof(*ch), GFP_KERNEL);
7936 		if (!ch) {
7937 			ret = -ENOMEM;
7938 			goto err_free;
7939 		}
7940 		INIT_LIST_HEAD(&ch->list);
7941 		ch->num_queue_pairs = qcnt;
7942 		if (!i40e_setup_channel(pf, vsi, ch)) {
7943 			ret = -EINVAL;
7944 			kfree(ch);
7945 			goto err_free;
7946 		}
7947 		ch->parent_vsi = vsi;
7948 		vsi->cnt_q_avail -= ch->num_queue_pairs;
7949 		vsi->macvlan_cnt++;
7950 		list_add_tail(&ch->list, &vsi->macvlan_list);
7951 	}
7952 
7953 	return ret;
7954 
7955 err_free:
7956 	dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
7957 	i40e_free_macvlan_channels(vsi);
7958 
7959 	return ret;
7960 }
7961 
7962 /**
7963  * i40e_fwd_add - configure macvlans
7964  * @netdev: net device to configure
7965  * @vdev: macvlan netdevice
7966  **/
7967 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
7968 {
7969 	struct i40e_netdev_priv *np = netdev_priv(netdev);
7970 	u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
7971 	struct i40e_vsi *vsi = np->vsi;
7972 	struct i40e_pf *pf = vsi->back;
7973 	struct i40e_fwd_adapter *fwd;
7974 	int avail_macvlan, ret;
7975 
7976 	if ((pf->flags & I40E_FLAG_DCB_ENABLED)) {
7977 		netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
7978 		return ERR_PTR(-EINVAL);
7979 	}
7980 	if (i40e_is_tc_mqprio_enabled(pf)) {
7981 		netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
7982 		return ERR_PTR(-EINVAL);
7983 	}
7984 	if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
7985 		netdev_info(netdev, "Not enough vectors available to support macvlans\n");
7986 		return ERR_PTR(-EINVAL);
7987 	}
7988 
7989 	/* The macvlan device has to be a single Q device so that the
7990 	 * tc_to_txq field can be reused to pick the tx queue.
7991 	 */
7992 	if (netif_is_multiqueue(vdev))
7993 		return ERR_PTR(-ERANGE);
7994 
7995 	if (!vsi->macvlan_cnt) {
7996 		/* reserve bit 0 for the pf device */
7997 		set_bit(0, vsi->fwd_bitmask);
7998 
7999 		/* Try to reserve as many queues as possible for macvlans. First
8000 		 * reserve 3/4th of max vectors, then half, then quarter and
8001 		 * calculate Qs per macvlan as you go
8002 		 */
8003 		vectors = pf->num_lan_msix;
8004 		if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
8005 			/* allocate 4 Qs per macvlan and 32 Qs to the PF*/
8006 			q_per_macvlan = 4;
8007 			macvlan_cnt = (vectors - 32) / 4;
8008 		} else if (vectors <= 64 && vectors > 32) {
8009 			/* allocate 2 Qs per macvlan and 16 Qs to the PF*/
8010 			q_per_macvlan = 2;
8011 			macvlan_cnt = (vectors - 16) / 2;
8012 		} else if (vectors <= 32 && vectors > 16) {
8013 			/* allocate 1 Q per macvlan and 16 Qs to the PF*/
8014 			q_per_macvlan = 1;
8015 			macvlan_cnt = vectors - 16;
8016 		} else if (vectors <= 16 && vectors > 8) {
8017 			/* allocate 1 Q per macvlan and 8 Qs to the PF */
8018 			q_per_macvlan = 1;
8019 			macvlan_cnt = vectors - 8;
8020 		} else {
8021 			/* allocate 1 Q per macvlan and 1 Q to the PF */
8022 			q_per_macvlan = 1;
8023 			macvlan_cnt = vectors - 1;
8024 		}
8025 
8026 		if (macvlan_cnt == 0)
8027 			return ERR_PTR(-EBUSY);
8028 
8029 		/* Quiesce VSI queues */
8030 		i40e_quiesce_vsi(vsi);
8031 
8032 		/* sets up the macvlans but does not "enable" them */
8033 		ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
8034 					  vdev);
8035 		if (ret)
8036 			return ERR_PTR(ret);
8037 
8038 		/* Unquiesce VSI */
8039 		i40e_unquiesce_vsi(vsi);
8040 	}
8041 	avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
8042 					    vsi->macvlan_cnt);
8043 	if (avail_macvlan >= I40E_MAX_MACVLANS)
8044 		return ERR_PTR(-EBUSY);
8045 
8046 	/* create the fwd struct */
8047 	fwd = kzalloc(sizeof(*fwd), GFP_KERNEL);
8048 	if (!fwd)
8049 		return ERR_PTR(-ENOMEM);
8050 
8051 	set_bit(avail_macvlan, vsi->fwd_bitmask);
8052 	fwd->bit_no = avail_macvlan;
8053 	netdev_set_sb_channel(vdev, avail_macvlan);
8054 	fwd->netdev = vdev;
8055 
8056 	if (!netif_running(netdev))
8057 		return fwd;
8058 
8059 	/* Set fwd ring up */
8060 	ret = i40e_fwd_ring_up(vsi, vdev, fwd);
8061 	if (ret) {
8062 		/* unbind the queues and drop the subordinate channel config */
8063 		netdev_unbind_sb_channel(netdev, vdev);
8064 		netdev_set_sb_channel(vdev, 0);
8065 
8066 		kfree(fwd);
8067 		return ERR_PTR(-EINVAL);
8068 	}
8069 
8070 	return fwd;
8071 }
8072 
8073 /**
8074  * i40e_del_all_macvlans - Delete all the mac filters on the channels
8075  * @vsi: the VSI we want to access
8076  */
8077 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
8078 {
8079 	struct i40e_channel *ch, *ch_tmp;
8080 	struct i40e_pf *pf = vsi->back;
8081 	struct i40e_hw *hw = &pf->hw;
8082 	int aq_err, ret = 0;
8083 
8084 	if (list_empty(&vsi->macvlan_list))
8085 		return;
8086 
8087 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8088 		if (i40e_is_channel_macvlan(ch)) {
8089 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8090 						      i40e_channel_mac(ch),
8091 						      &aq_err);
8092 			if (!ret) {
8093 				/* Reset queue contexts */
8094 				i40e_reset_ch_rings(vsi, ch);
8095 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8096 				netdev_unbind_sb_channel(vsi->netdev,
8097 							 ch->fwd->netdev);
8098 				netdev_set_sb_channel(ch->fwd->netdev, 0);
8099 				kfree(ch->fwd);
8100 				ch->fwd = NULL;
8101 			}
8102 		}
8103 	}
8104 }
8105 
8106 /**
8107  * i40e_fwd_del - delete macvlan interfaces
8108  * @netdev: net device to configure
8109  * @vdev: macvlan netdevice
8110  */
8111 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
8112 {
8113 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8114 	struct i40e_fwd_adapter *fwd = vdev;
8115 	struct i40e_channel *ch, *ch_tmp;
8116 	struct i40e_vsi *vsi = np->vsi;
8117 	struct i40e_pf *pf = vsi->back;
8118 	struct i40e_hw *hw = &pf->hw;
8119 	int aq_err, ret = 0;
8120 
8121 	/* Find the channel associated with the macvlan and del mac filter */
8122 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8123 		if (i40e_is_channel_macvlan(ch) &&
8124 		    ether_addr_equal(i40e_channel_mac(ch),
8125 				     fwd->netdev->dev_addr)) {
8126 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8127 						      i40e_channel_mac(ch),
8128 						      &aq_err);
8129 			if (!ret) {
8130 				/* Reset queue contexts */
8131 				i40e_reset_ch_rings(vsi, ch);
8132 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8133 				netdev_unbind_sb_channel(netdev, fwd->netdev);
8134 				netdev_set_sb_channel(fwd->netdev, 0);
8135 				kfree(ch->fwd);
8136 				ch->fwd = NULL;
8137 			} else {
8138 				dev_info(&pf->pdev->dev,
8139 					 "Error deleting mac filter on macvlan err %pe, aq_err %s\n",
8140 					  ERR_PTR(ret),
8141 					  i40e_aq_str(hw, aq_err));
8142 			}
8143 			break;
8144 		}
8145 	}
8146 }
8147 
8148 /**
8149  * i40e_setup_tc - configure multiple traffic classes
8150  * @netdev: net device to configure
8151  * @type_data: tc offload data
8152  **/
8153 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
8154 {
8155 	struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
8156 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8157 	struct i40e_vsi *vsi = np->vsi;
8158 	struct i40e_pf *pf = vsi->back;
8159 	u8 enabled_tc = 0, num_tc, hw;
8160 	bool need_reset = false;
8161 	int old_queue_pairs;
8162 	int ret = -EINVAL;
8163 	u16 mode;
8164 	int i;
8165 
8166 	old_queue_pairs = vsi->num_queue_pairs;
8167 	num_tc = mqprio_qopt->qopt.num_tc;
8168 	hw = mqprio_qopt->qopt.hw;
8169 	mode = mqprio_qopt->mode;
8170 	if (!hw) {
8171 		pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8172 		memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8173 		goto config_tc;
8174 	}
8175 
8176 	/* Check if MFP enabled */
8177 	if (pf->flags & I40E_FLAG_MFP_ENABLED) {
8178 		netdev_info(netdev,
8179 			    "Configuring TC not supported in MFP mode\n");
8180 		return ret;
8181 	}
8182 	switch (mode) {
8183 	case TC_MQPRIO_MODE_DCB:
8184 		pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8185 
8186 		/* Check if DCB enabled to continue */
8187 		if (!(pf->flags & I40E_FLAG_DCB_ENABLED)) {
8188 			netdev_info(netdev,
8189 				    "DCB is not enabled for adapter\n");
8190 			return ret;
8191 		}
8192 
8193 		/* Check whether tc count is within enabled limit */
8194 		if (num_tc > i40e_pf_get_num_tc(pf)) {
8195 			netdev_info(netdev,
8196 				    "TC count greater than enabled on link for adapter\n");
8197 			return ret;
8198 		}
8199 		break;
8200 	case TC_MQPRIO_MODE_CHANNEL:
8201 		if (pf->flags & I40E_FLAG_DCB_ENABLED) {
8202 			netdev_info(netdev,
8203 				    "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
8204 			return ret;
8205 		}
8206 		if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
8207 			return ret;
8208 		ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
8209 		if (ret)
8210 			return ret;
8211 		memcpy(&vsi->mqprio_qopt, mqprio_qopt,
8212 		       sizeof(*mqprio_qopt));
8213 		pf->flags |= I40E_FLAG_TC_MQPRIO;
8214 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
8215 		break;
8216 	default:
8217 		return -EINVAL;
8218 	}
8219 
8220 config_tc:
8221 	/* Generate TC map for number of tc requested */
8222 	for (i = 0; i < num_tc; i++)
8223 		enabled_tc |= BIT(i);
8224 
8225 	/* Requesting same TC configuration as already enabled */
8226 	if (enabled_tc == vsi->tc_config.enabled_tc &&
8227 	    mode != TC_MQPRIO_MODE_CHANNEL)
8228 		return 0;
8229 
8230 	/* Quiesce VSI queues */
8231 	i40e_quiesce_vsi(vsi);
8232 
8233 	if (!hw && !i40e_is_tc_mqprio_enabled(pf))
8234 		i40e_remove_queue_channels(vsi);
8235 
8236 	/* Configure VSI for enabled TCs */
8237 	ret = i40e_vsi_config_tc(vsi, enabled_tc);
8238 	if (ret) {
8239 		netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
8240 			    vsi->seid);
8241 		need_reset = true;
8242 		goto exit;
8243 	} else if (enabled_tc &&
8244 		   (!is_power_of_2(vsi->tc_config.tc_info[0].qcount))) {
8245 		netdev_info(netdev,
8246 			    "Failed to create channel. Override queues (%u) not power of 2\n",
8247 			    vsi->tc_config.tc_info[0].qcount);
8248 		ret = -EINVAL;
8249 		need_reset = true;
8250 		goto exit;
8251 	}
8252 
8253 	dev_info(&vsi->back->pdev->dev,
8254 		 "Setup channel (id:%u) utilizing num_queues %d\n",
8255 		 vsi->seid, vsi->tc_config.tc_info[0].qcount);
8256 
8257 	if (i40e_is_tc_mqprio_enabled(pf)) {
8258 		if (vsi->mqprio_qopt.max_rate[0]) {
8259 			u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
8260 						  vsi->mqprio_qopt.max_rate[0]);
8261 
8262 			ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
8263 			if (!ret) {
8264 				u64 credits = max_tx_rate;
8265 
8266 				do_div(credits, I40E_BW_CREDIT_DIVISOR);
8267 				dev_dbg(&vsi->back->pdev->dev,
8268 					"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
8269 					max_tx_rate,
8270 					credits,
8271 					vsi->seid);
8272 			} else {
8273 				need_reset = true;
8274 				goto exit;
8275 			}
8276 		}
8277 		ret = i40e_configure_queue_channels(vsi);
8278 		if (ret) {
8279 			vsi->num_queue_pairs = old_queue_pairs;
8280 			netdev_info(netdev,
8281 				    "Failed configuring queue channels\n");
8282 			need_reset = true;
8283 			goto exit;
8284 		}
8285 	}
8286 
8287 exit:
8288 	/* Reset the configuration data to defaults, only TC0 is enabled */
8289 	if (need_reset) {
8290 		i40e_vsi_set_default_tc_config(vsi);
8291 		need_reset = false;
8292 	}
8293 
8294 	/* Unquiesce VSI */
8295 	i40e_unquiesce_vsi(vsi);
8296 	return ret;
8297 }
8298 
8299 /**
8300  * i40e_set_cld_element - sets cloud filter element data
8301  * @filter: cloud filter rule
8302  * @cld: ptr to cloud filter element data
8303  *
8304  * This is helper function to copy data into cloud filter element
8305  **/
8306 static inline void
8307 i40e_set_cld_element(struct i40e_cloud_filter *filter,
8308 		     struct i40e_aqc_cloud_filters_element_data *cld)
8309 {
8310 	u32 ipa;
8311 	int i;
8312 
8313 	memset(cld, 0, sizeof(*cld));
8314 	ether_addr_copy(cld->outer_mac, filter->dst_mac);
8315 	ether_addr_copy(cld->inner_mac, filter->src_mac);
8316 
8317 	if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
8318 		return;
8319 
8320 	if (filter->n_proto == ETH_P_IPV6) {
8321 #define IPV6_MAX_INDEX	(ARRAY_SIZE(filter->dst_ipv6) - 1)
8322 		for (i = 0; i < ARRAY_SIZE(filter->dst_ipv6); i++) {
8323 			ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
8324 
8325 			*(__le32 *)&cld->ipaddr.raw_v6.data[i * 2] = cpu_to_le32(ipa);
8326 		}
8327 	} else {
8328 		ipa = be32_to_cpu(filter->dst_ipv4);
8329 
8330 		memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
8331 	}
8332 
8333 	cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
8334 
8335 	/* tenant_id is not supported by FW now, once the support is enabled
8336 	 * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
8337 	 */
8338 	if (filter->tenant_id)
8339 		return;
8340 }
8341 
8342 /**
8343  * i40e_add_del_cloud_filter - Add/del cloud filter
8344  * @vsi: pointer to VSI
8345  * @filter: cloud filter rule
8346  * @add: if true, add, if false, delete
8347  *
8348  * Add or delete a cloud filter for a specific flow spec.
8349  * Returns 0 if the filter were successfully added.
8350  **/
8351 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
8352 			      struct i40e_cloud_filter *filter, bool add)
8353 {
8354 	struct i40e_aqc_cloud_filters_element_data cld_filter;
8355 	struct i40e_pf *pf = vsi->back;
8356 	int ret;
8357 	static const u16 flag_table[128] = {
8358 		[I40E_CLOUD_FILTER_FLAGS_OMAC]  =
8359 			I40E_AQC_ADD_CLOUD_FILTER_OMAC,
8360 		[I40E_CLOUD_FILTER_FLAGS_IMAC]  =
8361 			I40E_AQC_ADD_CLOUD_FILTER_IMAC,
8362 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
8363 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
8364 		[I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
8365 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
8366 		[I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
8367 			I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
8368 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
8369 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
8370 		[I40E_CLOUD_FILTER_FLAGS_IIP] =
8371 			I40E_AQC_ADD_CLOUD_FILTER_IIP,
8372 	};
8373 
8374 	if (filter->flags >= ARRAY_SIZE(flag_table))
8375 		return I40E_ERR_CONFIG;
8376 
8377 	memset(&cld_filter, 0, sizeof(cld_filter));
8378 
8379 	/* copy element needed to add cloud filter from filter */
8380 	i40e_set_cld_element(filter, &cld_filter);
8381 
8382 	if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
8383 		cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
8384 					     I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
8385 
8386 	if (filter->n_proto == ETH_P_IPV6)
8387 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8388 						I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8389 	else
8390 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8391 						I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8392 
8393 	if (add)
8394 		ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
8395 						&cld_filter, 1);
8396 	else
8397 		ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
8398 						&cld_filter, 1);
8399 	if (ret)
8400 		dev_dbg(&pf->pdev->dev,
8401 			"Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
8402 			add ? "add" : "delete", filter->dst_port, ret,
8403 			pf->hw.aq.asq_last_status);
8404 	else
8405 		dev_info(&pf->pdev->dev,
8406 			 "%s cloud filter for VSI: %d\n",
8407 			 add ? "Added" : "Deleted", filter->seid);
8408 	return ret;
8409 }
8410 
8411 /**
8412  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
8413  * @vsi: pointer to VSI
8414  * @filter: cloud filter rule
8415  * @add: if true, add, if false, delete
8416  *
8417  * Add or delete a cloud filter for a specific flow spec using big buffer.
8418  * Returns 0 if the filter were successfully added.
8419  **/
8420 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
8421 				      struct i40e_cloud_filter *filter,
8422 				      bool add)
8423 {
8424 	struct i40e_aqc_cloud_filters_element_bb cld_filter;
8425 	struct i40e_pf *pf = vsi->back;
8426 	int ret;
8427 
8428 	/* Both (src/dst) valid mac_addr are not supported */
8429 	if ((is_valid_ether_addr(filter->dst_mac) &&
8430 	     is_valid_ether_addr(filter->src_mac)) ||
8431 	    (is_multicast_ether_addr(filter->dst_mac) &&
8432 	     is_multicast_ether_addr(filter->src_mac)))
8433 		return -EOPNOTSUPP;
8434 
8435 	/* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
8436 	 * ports are not supported via big buffer now.
8437 	 */
8438 	if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
8439 		return -EOPNOTSUPP;
8440 
8441 	/* adding filter using src_port/src_ip is not supported at this stage */
8442 	if (filter->src_port ||
8443 	    (filter->src_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8444 	    !ipv6_addr_any(&filter->ip.v6.src_ip6))
8445 		return -EOPNOTSUPP;
8446 
8447 	memset(&cld_filter, 0, sizeof(cld_filter));
8448 
8449 	/* copy element needed to add cloud filter from filter */
8450 	i40e_set_cld_element(filter, &cld_filter.element);
8451 
8452 	if (is_valid_ether_addr(filter->dst_mac) ||
8453 	    is_valid_ether_addr(filter->src_mac) ||
8454 	    is_multicast_ether_addr(filter->dst_mac) ||
8455 	    is_multicast_ether_addr(filter->src_mac)) {
8456 		/* MAC + IP : unsupported mode */
8457 		if (filter->dst_ipv4)
8458 			return -EOPNOTSUPP;
8459 
8460 		/* since we validated that L4 port must be valid before
8461 		 * we get here, start with respective "flags" value
8462 		 * and update if vlan is present or not
8463 		 */
8464 		cld_filter.element.flags =
8465 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
8466 
8467 		if (filter->vlan_id) {
8468 			cld_filter.element.flags =
8469 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
8470 		}
8471 
8472 	} else if ((filter->dst_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8473 		   !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
8474 		cld_filter.element.flags =
8475 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
8476 		if (filter->n_proto == ETH_P_IPV6)
8477 			cld_filter.element.flags |=
8478 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8479 		else
8480 			cld_filter.element.flags |=
8481 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8482 	} else {
8483 		dev_err(&pf->pdev->dev,
8484 			"either mac or ip has to be valid for cloud filter\n");
8485 		return -EINVAL;
8486 	}
8487 
8488 	/* Now copy L4 port in Byte 6..7 in general fields */
8489 	cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
8490 						be16_to_cpu(filter->dst_port);
8491 
8492 	if (add) {
8493 		/* Validate current device switch mode, change if necessary */
8494 		ret = i40e_validate_and_set_switch_mode(vsi);
8495 		if (ret) {
8496 			dev_err(&pf->pdev->dev,
8497 				"failed to set switch mode, ret %d\n",
8498 				ret);
8499 			return ret;
8500 		}
8501 
8502 		ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
8503 						   &cld_filter, 1);
8504 	} else {
8505 		ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
8506 						   &cld_filter, 1);
8507 	}
8508 
8509 	if (ret)
8510 		dev_dbg(&pf->pdev->dev,
8511 			"Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
8512 			add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
8513 	else
8514 		dev_info(&pf->pdev->dev,
8515 			 "%s cloud filter for VSI: %d, L4 port: %d\n",
8516 			 add ? "add" : "delete", filter->seid,
8517 			 ntohs(filter->dst_port));
8518 	return ret;
8519 }
8520 
8521 /**
8522  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
8523  * @vsi: Pointer to VSI
8524  * @f: Pointer to struct flow_cls_offload
8525  * @filter: Pointer to cloud filter structure
8526  *
8527  **/
8528 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
8529 				 struct flow_cls_offload *f,
8530 				 struct i40e_cloud_filter *filter)
8531 {
8532 	struct flow_rule *rule = flow_cls_offload_flow_rule(f);
8533 	struct flow_dissector *dissector = rule->match.dissector;
8534 	u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
8535 	struct i40e_pf *pf = vsi->back;
8536 	u8 field_flags = 0;
8537 
8538 	if (dissector->used_keys &
8539 	    ~(BIT(FLOW_DISSECTOR_KEY_CONTROL) |
8540 	      BIT(FLOW_DISSECTOR_KEY_BASIC) |
8541 	      BIT(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
8542 	      BIT(FLOW_DISSECTOR_KEY_VLAN) |
8543 	      BIT(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
8544 	      BIT(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
8545 	      BIT(FLOW_DISSECTOR_KEY_PORTS) |
8546 	      BIT(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
8547 		dev_err(&pf->pdev->dev, "Unsupported key used: 0x%x\n",
8548 			dissector->used_keys);
8549 		return -EOPNOTSUPP;
8550 	}
8551 
8552 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
8553 		struct flow_match_enc_keyid match;
8554 
8555 		flow_rule_match_enc_keyid(rule, &match);
8556 		if (match.mask->keyid != 0)
8557 			field_flags |= I40E_CLOUD_FIELD_TEN_ID;
8558 
8559 		filter->tenant_id = be32_to_cpu(match.key->keyid);
8560 	}
8561 
8562 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
8563 		struct flow_match_basic match;
8564 
8565 		flow_rule_match_basic(rule, &match);
8566 		n_proto_key = ntohs(match.key->n_proto);
8567 		n_proto_mask = ntohs(match.mask->n_proto);
8568 
8569 		if (n_proto_key == ETH_P_ALL) {
8570 			n_proto_key = 0;
8571 			n_proto_mask = 0;
8572 		}
8573 		filter->n_proto = n_proto_key & n_proto_mask;
8574 		filter->ip_proto = match.key->ip_proto;
8575 	}
8576 
8577 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
8578 		struct flow_match_eth_addrs match;
8579 
8580 		flow_rule_match_eth_addrs(rule, &match);
8581 
8582 		/* use is_broadcast and is_zero to check for all 0xf or 0 */
8583 		if (!is_zero_ether_addr(match.mask->dst)) {
8584 			if (is_broadcast_ether_addr(match.mask->dst)) {
8585 				field_flags |= I40E_CLOUD_FIELD_OMAC;
8586 			} else {
8587 				dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
8588 					match.mask->dst);
8589 				return I40E_ERR_CONFIG;
8590 			}
8591 		}
8592 
8593 		if (!is_zero_ether_addr(match.mask->src)) {
8594 			if (is_broadcast_ether_addr(match.mask->src)) {
8595 				field_flags |= I40E_CLOUD_FIELD_IMAC;
8596 			} else {
8597 				dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
8598 					match.mask->src);
8599 				return I40E_ERR_CONFIG;
8600 			}
8601 		}
8602 		ether_addr_copy(filter->dst_mac, match.key->dst);
8603 		ether_addr_copy(filter->src_mac, match.key->src);
8604 	}
8605 
8606 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
8607 		struct flow_match_vlan match;
8608 
8609 		flow_rule_match_vlan(rule, &match);
8610 		if (match.mask->vlan_id) {
8611 			if (match.mask->vlan_id == VLAN_VID_MASK) {
8612 				field_flags |= I40E_CLOUD_FIELD_IVLAN;
8613 
8614 			} else {
8615 				dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
8616 					match.mask->vlan_id);
8617 				return I40E_ERR_CONFIG;
8618 			}
8619 		}
8620 
8621 		filter->vlan_id = cpu_to_be16(match.key->vlan_id);
8622 	}
8623 
8624 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
8625 		struct flow_match_control match;
8626 
8627 		flow_rule_match_control(rule, &match);
8628 		addr_type = match.key->addr_type;
8629 	}
8630 
8631 	if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
8632 		struct flow_match_ipv4_addrs match;
8633 
8634 		flow_rule_match_ipv4_addrs(rule, &match);
8635 		if (match.mask->dst) {
8636 			if (match.mask->dst == cpu_to_be32(0xffffffff)) {
8637 				field_flags |= I40E_CLOUD_FIELD_IIP;
8638 			} else {
8639 				dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
8640 					&match.mask->dst);
8641 				return I40E_ERR_CONFIG;
8642 			}
8643 		}
8644 
8645 		if (match.mask->src) {
8646 			if (match.mask->src == cpu_to_be32(0xffffffff)) {
8647 				field_flags |= I40E_CLOUD_FIELD_IIP;
8648 			} else {
8649 				dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
8650 					&match.mask->src);
8651 				return I40E_ERR_CONFIG;
8652 			}
8653 		}
8654 
8655 		if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
8656 			dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
8657 			return I40E_ERR_CONFIG;
8658 		}
8659 		filter->dst_ipv4 = match.key->dst;
8660 		filter->src_ipv4 = match.key->src;
8661 	}
8662 
8663 	if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
8664 		struct flow_match_ipv6_addrs match;
8665 
8666 		flow_rule_match_ipv6_addrs(rule, &match);
8667 
8668 		/* src and dest IPV6 address should not be LOOPBACK
8669 		 * (0:0:0:0:0:0:0:1), which can be represented as ::1
8670 		 */
8671 		if (ipv6_addr_loopback(&match.key->dst) ||
8672 		    ipv6_addr_loopback(&match.key->src)) {
8673 			dev_err(&pf->pdev->dev,
8674 				"Bad ipv6, addr is LOOPBACK\n");
8675 			return I40E_ERR_CONFIG;
8676 		}
8677 		if (!ipv6_addr_any(&match.mask->dst) ||
8678 		    !ipv6_addr_any(&match.mask->src))
8679 			field_flags |= I40E_CLOUD_FIELD_IIP;
8680 
8681 		memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
8682 		       sizeof(filter->src_ipv6));
8683 		memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
8684 		       sizeof(filter->dst_ipv6));
8685 	}
8686 
8687 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
8688 		struct flow_match_ports match;
8689 
8690 		flow_rule_match_ports(rule, &match);
8691 		if (match.mask->src) {
8692 			if (match.mask->src == cpu_to_be16(0xffff)) {
8693 				field_flags |= I40E_CLOUD_FIELD_IIP;
8694 			} else {
8695 				dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
8696 					be16_to_cpu(match.mask->src));
8697 				return I40E_ERR_CONFIG;
8698 			}
8699 		}
8700 
8701 		if (match.mask->dst) {
8702 			if (match.mask->dst == cpu_to_be16(0xffff)) {
8703 				field_flags |= I40E_CLOUD_FIELD_IIP;
8704 			} else {
8705 				dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
8706 					be16_to_cpu(match.mask->dst));
8707 				return I40E_ERR_CONFIG;
8708 			}
8709 		}
8710 
8711 		filter->dst_port = match.key->dst;
8712 		filter->src_port = match.key->src;
8713 
8714 		switch (filter->ip_proto) {
8715 		case IPPROTO_TCP:
8716 		case IPPROTO_UDP:
8717 			break;
8718 		default:
8719 			dev_err(&pf->pdev->dev,
8720 				"Only UDP and TCP transport are supported\n");
8721 			return -EINVAL;
8722 		}
8723 	}
8724 	filter->flags = field_flags;
8725 	return 0;
8726 }
8727 
8728 /**
8729  * i40e_handle_tclass: Forward to a traffic class on the device
8730  * @vsi: Pointer to VSI
8731  * @tc: traffic class index on the device
8732  * @filter: Pointer to cloud filter structure
8733  *
8734  **/
8735 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
8736 			      struct i40e_cloud_filter *filter)
8737 {
8738 	struct i40e_channel *ch, *ch_tmp;
8739 
8740 	/* direct to a traffic class on the same device */
8741 	if (tc == 0) {
8742 		filter->seid = vsi->seid;
8743 		return 0;
8744 	} else if (vsi->tc_config.enabled_tc & BIT(tc)) {
8745 		if (!filter->dst_port) {
8746 			dev_err(&vsi->back->pdev->dev,
8747 				"Specify destination port to direct to traffic class that is not default\n");
8748 			return -EINVAL;
8749 		}
8750 		if (list_empty(&vsi->ch_list))
8751 			return -EINVAL;
8752 		list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
8753 					 list) {
8754 			if (ch->seid == vsi->tc_seid_map[tc])
8755 				filter->seid = ch->seid;
8756 		}
8757 		return 0;
8758 	}
8759 	dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
8760 	return -EINVAL;
8761 }
8762 
8763 /**
8764  * i40e_configure_clsflower - Configure tc flower filters
8765  * @vsi: Pointer to VSI
8766  * @cls_flower: Pointer to struct flow_cls_offload
8767  *
8768  **/
8769 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
8770 				    struct flow_cls_offload *cls_flower)
8771 {
8772 	int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
8773 	struct i40e_cloud_filter *filter = NULL;
8774 	struct i40e_pf *pf = vsi->back;
8775 	int err = 0;
8776 
8777 	if (tc < 0) {
8778 		dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
8779 		return -EOPNOTSUPP;
8780 	}
8781 
8782 	if (!tc) {
8783 		dev_err(&pf->pdev->dev, "Unable to add filter because of invalid destination");
8784 		return -EINVAL;
8785 	}
8786 
8787 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
8788 	    test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
8789 		return -EBUSY;
8790 
8791 	if (pf->fdir_pf_active_filters ||
8792 	    (!hlist_empty(&pf->fdir_filter_list))) {
8793 		dev_err(&vsi->back->pdev->dev,
8794 			"Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
8795 		return -EINVAL;
8796 	}
8797 
8798 	if (vsi->back->flags & I40E_FLAG_FD_SB_ENABLED) {
8799 		dev_err(&vsi->back->pdev->dev,
8800 			"Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
8801 		vsi->back->flags &= ~I40E_FLAG_FD_SB_ENABLED;
8802 		vsi->back->flags |= I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8803 	}
8804 
8805 	filter = kzalloc(sizeof(*filter), GFP_KERNEL);
8806 	if (!filter)
8807 		return -ENOMEM;
8808 
8809 	filter->cookie = cls_flower->cookie;
8810 
8811 	err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8812 	if (err < 0)
8813 		goto err;
8814 
8815 	err = i40e_handle_tclass(vsi, tc, filter);
8816 	if (err < 0)
8817 		goto err;
8818 
8819 	/* Add cloud filter */
8820 	if (filter->dst_port)
8821 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8822 	else
8823 		err = i40e_add_del_cloud_filter(vsi, filter, true);
8824 
8825 	if (err) {
8826 		dev_err(&pf->pdev->dev, "Failed to add cloud filter, err %d\n",
8827 			err);
8828 		goto err;
8829 	}
8830 
8831 	/* add filter to the ordered list */
8832 	INIT_HLIST_NODE(&filter->cloud_node);
8833 
8834 	hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8835 
8836 	pf->num_cloud_filters++;
8837 
8838 	return err;
8839 err:
8840 	kfree(filter);
8841 	return err;
8842 }
8843 
8844 /**
8845  * i40e_find_cloud_filter - Find the could filter in the list
8846  * @vsi: Pointer to VSI
8847  * @cookie: filter specific cookie
8848  *
8849  **/
8850 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8851 							unsigned long *cookie)
8852 {
8853 	struct i40e_cloud_filter *filter = NULL;
8854 	struct hlist_node *node2;
8855 
8856 	hlist_for_each_entry_safe(filter, node2,
8857 				  &vsi->back->cloud_filter_list, cloud_node)
8858 		if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8859 			return filter;
8860 	return NULL;
8861 }
8862 
8863 /**
8864  * i40e_delete_clsflower - Remove tc flower filters
8865  * @vsi: Pointer to VSI
8866  * @cls_flower: Pointer to struct flow_cls_offload
8867  *
8868  **/
8869 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8870 				 struct flow_cls_offload *cls_flower)
8871 {
8872 	struct i40e_cloud_filter *filter = NULL;
8873 	struct i40e_pf *pf = vsi->back;
8874 	int err = 0;
8875 
8876 	filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8877 
8878 	if (!filter)
8879 		return -EINVAL;
8880 
8881 	hash_del(&filter->cloud_node);
8882 
8883 	if (filter->dst_port)
8884 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8885 	else
8886 		err = i40e_add_del_cloud_filter(vsi, filter, false);
8887 
8888 	kfree(filter);
8889 	if (err) {
8890 		dev_err(&pf->pdev->dev,
8891 			"Failed to delete cloud filter, err %pe\n",
8892 			ERR_PTR(err));
8893 		return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8894 	}
8895 
8896 	pf->num_cloud_filters--;
8897 	if (!pf->num_cloud_filters)
8898 		if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
8899 		    !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
8900 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
8901 			pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8902 			pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
8903 		}
8904 	return 0;
8905 }
8906 
8907 /**
8908  * i40e_setup_tc_cls_flower - flower classifier offloads
8909  * @np: net device to configure
8910  * @cls_flower: offload data
8911  **/
8912 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8913 				    struct flow_cls_offload *cls_flower)
8914 {
8915 	struct i40e_vsi *vsi = np->vsi;
8916 
8917 	switch (cls_flower->command) {
8918 	case FLOW_CLS_REPLACE:
8919 		return i40e_configure_clsflower(vsi, cls_flower);
8920 	case FLOW_CLS_DESTROY:
8921 		return i40e_delete_clsflower(vsi, cls_flower);
8922 	case FLOW_CLS_STATS:
8923 		return -EOPNOTSUPP;
8924 	default:
8925 		return -EOPNOTSUPP;
8926 	}
8927 }
8928 
8929 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8930 				  void *cb_priv)
8931 {
8932 	struct i40e_netdev_priv *np = cb_priv;
8933 
8934 	if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8935 		return -EOPNOTSUPP;
8936 
8937 	switch (type) {
8938 	case TC_SETUP_CLSFLOWER:
8939 		return i40e_setup_tc_cls_flower(np, type_data);
8940 
8941 	default:
8942 		return -EOPNOTSUPP;
8943 	}
8944 }
8945 
8946 static LIST_HEAD(i40e_block_cb_list);
8947 
8948 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8949 			   void *type_data)
8950 {
8951 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8952 
8953 	switch (type) {
8954 	case TC_SETUP_QDISC_MQPRIO:
8955 		return i40e_setup_tc(netdev, type_data);
8956 	case TC_SETUP_BLOCK:
8957 		return flow_block_cb_setup_simple(type_data,
8958 						  &i40e_block_cb_list,
8959 						  i40e_setup_tc_block_cb,
8960 						  np, np, true);
8961 	default:
8962 		return -EOPNOTSUPP;
8963 	}
8964 }
8965 
8966 /**
8967  * i40e_open - Called when a network interface is made active
8968  * @netdev: network interface device structure
8969  *
8970  * The open entry point is called when a network interface is made
8971  * active by the system (IFF_UP).  At this point all resources needed
8972  * for transmit and receive operations are allocated, the interrupt
8973  * handler is registered with the OS, the netdev watchdog subtask is
8974  * enabled, and the stack is notified that the interface is ready.
8975  *
8976  * Returns 0 on success, negative value on failure
8977  **/
8978 int i40e_open(struct net_device *netdev)
8979 {
8980 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8981 	struct i40e_vsi *vsi = np->vsi;
8982 	struct i40e_pf *pf = vsi->back;
8983 	int err;
8984 
8985 	/* disallow open during test or if eeprom is broken */
8986 	if (test_bit(__I40E_TESTING, pf->state) ||
8987 	    test_bit(__I40E_BAD_EEPROM, pf->state))
8988 		return -EBUSY;
8989 
8990 	netif_carrier_off(netdev);
8991 
8992 	if (i40e_force_link_state(pf, true))
8993 		return -EAGAIN;
8994 
8995 	err = i40e_vsi_open(vsi);
8996 	if (err)
8997 		return err;
8998 
8999 	/* configure global TSO hardware offload settings */
9000 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
9001 						       TCP_FLAG_FIN) >> 16);
9002 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
9003 						       TCP_FLAG_FIN |
9004 						       TCP_FLAG_CWR) >> 16);
9005 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
9006 	udp_tunnel_get_rx_info(netdev);
9007 
9008 	return 0;
9009 }
9010 
9011 /**
9012  * i40e_netif_set_realnum_tx_rx_queues - Update number of tx/rx queues
9013  * @vsi: vsi structure
9014  *
9015  * This updates netdev's number of tx/rx queues
9016  *
9017  * Returns status of setting tx/rx queues
9018  **/
9019 static int i40e_netif_set_realnum_tx_rx_queues(struct i40e_vsi *vsi)
9020 {
9021 	int ret;
9022 
9023 	ret = netif_set_real_num_rx_queues(vsi->netdev,
9024 					   vsi->num_queue_pairs);
9025 	if (ret)
9026 		return ret;
9027 
9028 	return netif_set_real_num_tx_queues(vsi->netdev,
9029 					    vsi->num_queue_pairs);
9030 }
9031 
9032 /**
9033  * i40e_vsi_open -
9034  * @vsi: the VSI to open
9035  *
9036  * Finish initialization of the VSI.
9037  *
9038  * Returns 0 on success, negative value on failure
9039  *
9040  * Note: expects to be called while under rtnl_lock()
9041  **/
9042 int i40e_vsi_open(struct i40e_vsi *vsi)
9043 {
9044 	struct i40e_pf *pf = vsi->back;
9045 	char int_name[I40E_INT_NAME_STR_LEN];
9046 	int err;
9047 
9048 	/* allocate descriptors */
9049 	err = i40e_vsi_setup_tx_resources(vsi);
9050 	if (err)
9051 		goto err_setup_tx;
9052 	err = i40e_vsi_setup_rx_resources(vsi);
9053 	if (err)
9054 		goto err_setup_rx;
9055 
9056 	err = i40e_vsi_configure(vsi);
9057 	if (err)
9058 		goto err_setup_rx;
9059 
9060 	if (vsi->netdev) {
9061 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
9062 			 dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
9063 		err = i40e_vsi_request_irq(vsi, int_name);
9064 		if (err)
9065 			goto err_setup_rx;
9066 
9067 		/* Notify the stack of the actual queue counts. */
9068 		err = i40e_netif_set_realnum_tx_rx_queues(vsi);
9069 		if (err)
9070 			goto err_set_queues;
9071 
9072 	} else if (vsi->type == I40E_VSI_FDIR) {
9073 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
9074 			 dev_driver_string(&pf->pdev->dev),
9075 			 dev_name(&pf->pdev->dev));
9076 		err = i40e_vsi_request_irq(vsi, int_name);
9077 		if (err)
9078 			goto err_setup_rx;
9079 
9080 	} else {
9081 		err = -EINVAL;
9082 		goto err_setup_rx;
9083 	}
9084 
9085 	err = i40e_up_complete(vsi);
9086 	if (err)
9087 		goto err_up_complete;
9088 
9089 	return 0;
9090 
9091 err_up_complete:
9092 	i40e_down(vsi);
9093 err_set_queues:
9094 	i40e_vsi_free_irq(vsi);
9095 err_setup_rx:
9096 	i40e_vsi_free_rx_resources(vsi);
9097 err_setup_tx:
9098 	i40e_vsi_free_tx_resources(vsi);
9099 	if (vsi == pf->vsi[pf->lan_vsi])
9100 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
9101 
9102 	return err;
9103 }
9104 
9105 /**
9106  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
9107  * @pf: Pointer to PF
9108  *
9109  * This function destroys the hlist where all the Flow Director
9110  * filters were saved.
9111  **/
9112 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
9113 {
9114 	struct i40e_fdir_filter *filter;
9115 	struct i40e_flex_pit *pit_entry, *tmp;
9116 	struct hlist_node *node2;
9117 
9118 	hlist_for_each_entry_safe(filter, node2,
9119 				  &pf->fdir_filter_list, fdir_node) {
9120 		hlist_del(&filter->fdir_node);
9121 		kfree(filter);
9122 	}
9123 
9124 	list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
9125 		list_del(&pit_entry->list);
9126 		kfree(pit_entry);
9127 	}
9128 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
9129 
9130 	list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
9131 		list_del(&pit_entry->list);
9132 		kfree(pit_entry);
9133 	}
9134 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
9135 
9136 	pf->fdir_pf_active_filters = 0;
9137 	i40e_reset_fdir_filter_cnt(pf);
9138 
9139 	/* Reprogram the default input set for TCP/IPv4 */
9140 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
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 TCP/IPv6 */
9145 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_TCP,
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 UDP/IPv4 */
9150 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
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 UDP/IPv6 */
9155 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_UDP,
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 SCTP/IPv4 */
9160 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
9161 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9162 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9163 
9164 	/* Reprogram the default input set for SCTP/IPv6 */
9165 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_SCTP,
9166 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9167 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9168 
9169 	/* Reprogram the default input set for Other/IPv4 */
9170 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
9171 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9172 
9173 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
9174 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9175 
9176 	/* Reprogram the default input set for Other/IPv6 */
9177 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_OTHER,
9178 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9179 
9180 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV6,
9181 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9182 }
9183 
9184 /**
9185  * i40e_cloud_filter_exit - Cleans up the cloud filters
9186  * @pf: Pointer to PF
9187  *
9188  * This function destroys the hlist where all the cloud filters
9189  * were saved.
9190  **/
9191 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
9192 {
9193 	struct i40e_cloud_filter *cfilter;
9194 	struct hlist_node *node;
9195 
9196 	hlist_for_each_entry_safe(cfilter, node,
9197 				  &pf->cloud_filter_list, cloud_node) {
9198 		hlist_del(&cfilter->cloud_node);
9199 		kfree(cfilter);
9200 	}
9201 	pf->num_cloud_filters = 0;
9202 
9203 	if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
9204 	    !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
9205 		pf->flags |= I40E_FLAG_FD_SB_ENABLED;
9206 		pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
9207 		pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
9208 	}
9209 }
9210 
9211 /**
9212  * i40e_close - Disables a network interface
9213  * @netdev: network interface device structure
9214  *
9215  * The close entry point is called when an interface is de-activated
9216  * by the OS.  The hardware is still under the driver's control, but
9217  * this netdev interface is disabled.
9218  *
9219  * Returns 0, this is not allowed to fail
9220  **/
9221 int i40e_close(struct net_device *netdev)
9222 {
9223 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9224 	struct i40e_vsi *vsi = np->vsi;
9225 
9226 	i40e_vsi_close(vsi);
9227 
9228 	return 0;
9229 }
9230 
9231 /**
9232  * i40e_do_reset - Start a PF or Core Reset sequence
9233  * @pf: board private structure
9234  * @reset_flags: which reset is requested
9235  * @lock_acquired: indicates whether or not the lock has been acquired
9236  * before this function was called.
9237  *
9238  * The essential difference in resets is that the PF Reset
9239  * doesn't clear the packet buffers, doesn't reset the PE
9240  * firmware, and doesn't bother the other PFs on the chip.
9241  **/
9242 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
9243 {
9244 	u32 val;
9245 
9246 	/* do the biggest reset indicated */
9247 	if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
9248 
9249 		/* Request a Global Reset
9250 		 *
9251 		 * This will start the chip's countdown to the actual full
9252 		 * chip reset event, and a warning interrupt to be sent
9253 		 * to all PFs, including the requestor.  Our handler
9254 		 * for the warning interrupt will deal with the shutdown
9255 		 * and recovery of the switch setup.
9256 		 */
9257 		dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
9258 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9259 		val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
9260 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9261 
9262 	} else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
9263 
9264 		/* Request a Core Reset
9265 		 *
9266 		 * Same as Global Reset, except does *not* include the MAC/PHY
9267 		 */
9268 		dev_dbg(&pf->pdev->dev, "CoreR requested\n");
9269 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9270 		val |= I40E_GLGEN_RTRIG_CORER_MASK;
9271 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9272 		i40e_flush(&pf->hw);
9273 
9274 	} else if (reset_flags & I40E_PF_RESET_FLAG) {
9275 
9276 		/* Request a PF Reset
9277 		 *
9278 		 * Resets only the PF-specific registers
9279 		 *
9280 		 * This goes directly to the tear-down and rebuild of
9281 		 * the switch, since we need to do all the recovery as
9282 		 * for the Core Reset.
9283 		 */
9284 		dev_dbg(&pf->pdev->dev, "PFR requested\n");
9285 		i40e_handle_reset_warning(pf, lock_acquired);
9286 
9287 	} else if (reset_flags & I40E_PF_RESET_AND_REBUILD_FLAG) {
9288 		/* Request a PF Reset
9289 		 *
9290 		 * Resets PF and reinitializes PFs VSI.
9291 		 */
9292 		i40e_prep_for_reset(pf);
9293 		i40e_reset_and_rebuild(pf, true, lock_acquired);
9294 		dev_info(&pf->pdev->dev,
9295 			 pf->flags & I40E_FLAG_DISABLE_FW_LLDP ?
9296 			 "FW LLDP is disabled\n" :
9297 			 "FW LLDP is enabled\n");
9298 
9299 	} else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
9300 		int v;
9301 
9302 		/* Find the VSI(s) that requested a re-init */
9303 		dev_info(&pf->pdev->dev,
9304 			 "VSI reinit requested\n");
9305 		for (v = 0; v < pf->num_alloc_vsi; v++) {
9306 			struct i40e_vsi *vsi = pf->vsi[v];
9307 
9308 			if (vsi != NULL &&
9309 			    test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
9310 					       vsi->state))
9311 				i40e_vsi_reinit_locked(pf->vsi[v]);
9312 		}
9313 	} else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
9314 		int v;
9315 
9316 		/* Find the VSI(s) that needs to be brought down */
9317 		dev_info(&pf->pdev->dev, "VSI down requested\n");
9318 		for (v = 0; v < pf->num_alloc_vsi; v++) {
9319 			struct i40e_vsi *vsi = pf->vsi[v];
9320 
9321 			if (vsi != NULL &&
9322 			    test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
9323 					       vsi->state)) {
9324 				set_bit(__I40E_VSI_DOWN, vsi->state);
9325 				i40e_down(vsi);
9326 			}
9327 		}
9328 	} else {
9329 		dev_info(&pf->pdev->dev,
9330 			 "bad reset request 0x%08x\n", reset_flags);
9331 	}
9332 }
9333 
9334 #ifdef CONFIG_I40E_DCB
9335 /**
9336  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
9337  * @pf: board private structure
9338  * @old_cfg: current DCB config
9339  * @new_cfg: new DCB config
9340  **/
9341 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
9342 			    struct i40e_dcbx_config *old_cfg,
9343 			    struct i40e_dcbx_config *new_cfg)
9344 {
9345 	bool need_reconfig = false;
9346 
9347 	/* Check if ETS configuration has changed */
9348 	if (memcmp(&new_cfg->etscfg,
9349 		   &old_cfg->etscfg,
9350 		   sizeof(new_cfg->etscfg))) {
9351 		/* If Priority Table has changed reconfig is needed */
9352 		if (memcmp(&new_cfg->etscfg.prioritytable,
9353 			   &old_cfg->etscfg.prioritytable,
9354 			   sizeof(new_cfg->etscfg.prioritytable))) {
9355 			need_reconfig = true;
9356 			dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
9357 		}
9358 
9359 		if (memcmp(&new_cfg->etscfg.tcbwtable,
9360 			   &old_cfg->etscfg.tcbwtable,
9361 			   sizeof(new_cfg->etscfg.tcbwtable)))
9362 			dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
9363 
9364 		if (memcmp(&new_cfg->etscfg.tsatable,
9365 			   &old_cfg->etscfg.tsatable,
9366 			   sizeof(new_cfg->etscfg.tsatable)))
9367 			dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
9368 	}
9369 
9370 	/* Check if PFC configuration has changed */
9371 	if (memcmp(&new_cfg->pfc,
9372 		   &old_cfg->pfc,
9373 		   sizeof(new_cfg->pfc))) {
9374 		need_reconfig = true;
9375 		dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
9376 	}
9377 
9378 	/* Check if APP Table has changed */
9379 	if (memcmp(&new_cfg->app,
9380 		   &old_cfg->app,
9381 		   sizeof(new_cfg->app))) {
9382 		need_reconfig = true;
9383 		dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
9384 	}
9385 
9386 	dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
9387 	return need_reconfig;
9388 }
9389 
9390 /**
9391  * i40e_handle_lldp_event - Handle LLDP Change MIB event
9392  * @pf: board private structure
9393  * @e: event info posted on ARQ
9394  **/
9395 static int i40e_handle_lldp_event(struct i40e_pf *pf,
9396 				  struct i40e_arq_event_info *e)
9397 {
9398 	struct i40e_aqc_lldp_get_mib *mib =
9399 		(struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
9400 	struct i40e_hw *hw = &pf->hw;
9401 	struct i40e_dcbx_config tmp_dcbx_cfg;
9402 	bool need_reconfig = false;
9403 	int ret = 0;
9404 	u8 type;
9405 
9406 	/* X710-T*L 2.5G and 5G speeds don't support DCB */
9407 	if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9408 	    (hw->phy.link_info.link_speed &
9409 	     ~(I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB)) &&
9410 	     !(pf->flags & I40E_FLAG_DCB_CAPABLE))
9411 		/* let firmware decide if the DCB should be disabled */
9412 		pf->flags |= I40E_FLAG_DCB_CAPABLE;
9413 
9414 	/* Not DCB capable or capability disabled */
9415 	if (!(pf->flags & I40E_FLAG_DCB_CAPABLE))
9416 		return ret;
9417 
9418 	/* Ignore if event is not for Nearest Bridge */
9419 	type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
9420 		& I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
9421 	dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
9422 	if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
9423 		return ret;
9424 
9425 	/* Check MIB Type and return if event for Remote MIB update */
9426 	type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
9427 	dev_dbg(&pf->pdev->dev,
9428 		"LLDP event mib type %s\n", type ? "remote" : "local");
9429 	if (type == I40E_AQ_LLDP_MIB_REMOTE) {
9430 		/* Update the remote cached instance and return */
9431 		ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
9432 				I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
9433 				&hw->remote_dcbx_config);
9434 		goto exit;
9435 	}
9436 
9437 	/* Store the old configuration */
9438 	tmp_dcbx_cfg = hw->local_dcbx_config;
9439 
9440 	/* Reset the old DCBx configuration data */
9441 	memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
9442 	/* Get updated DCBX data from firmware */
9443 	ret = i40e_get_dcb_config(&pf->hw);
9444 	if (ret) {
9445 		/* X710-T*L 2.5G and 5G speeds don't support DCB */
9446 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9447 		    (hw->phy.link_info.link_speed &
9448 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
9449 			dev_warn(&pf->pdev->dev,
9450 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
9451 			pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
9452 		} else {
9453 			dev_info(&pf->pdev->dev,
9454 				 "Failed querying DCB configuration data from firmware, err %pe aq_err %s\n",
9455 				 ERR_PTR(ret),
9456 				 i40e_aq_str(&pf->hw,
9457 					     pf->hw.aq.asq_last_status));
9458 		}
9459 		goto exit;
9460 	}
9461 
9462 	/* No change detected in DCBX configs */
9463 	if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
9464 		    sizeof(tmp_dcbx_cfg))) {
9465 		dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
9466 		goto exit;
9467 	}
9468 
9469 	need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
9470 					       &hw->local_dcbx_config);
9471 
9472 	i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
9473 
9474 	if (!need_reconfig)
9475 		goto exit;
9476 
9477 	/* Enable DCB tagging only when more than one TC */
9478 	if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
9479 		pf->flags |= I40E_FLAG_DCB_ENABLED;
9480 	else
9481 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9482 
9483 	set_bit(__I40E_PORT_SUSPENDED, pf->state);
9484 	/* Reconfiguration needed quiesce all VSIs */
9485 	i40e_pf_quiesce_all_vsi(pf);
9486 
9487 	/* Changes in configuration update VEB/VSI */
9488 	i40e_dcb_reconfigure(pf);
9489 
9490 	ret = i40e_resume_port_tx(pf);
9491 
9492 	clear_bit(__I40E_PORT_SUSPENDED, pf->state);
9493 	/* In case of error no point in resuming VSIs */
9494 	if (ret)
9495 		goto exit;
9496 
9497 	/* Wait for the PF's queues to be disabled */
9498 	ret = i40e_pf_wait_queues_disabled(pf);
9499 	if (ret) {
9500 		/* Schedule PF reset to recover */
9501 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9502 		i40e_service_event_schedule(pf);
9503 	} else {
9504 		i40e_pf_unquiesce_all_vsi(pf);
9505 		set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
9506 		set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
9507 	}
9508 
9509 exit:
9510 	return ret;
9511 }
9512 #endif /* CONFIG_I40E_DCB */
9513 
9514 /**
9515  * i40e_do_reset_safe - Protected reset path for userland calls.
9516  * @pf: board private structure
9517  * @reset_flags: which reset is requested
9518  *
9519  **/
9520 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
9521 {
9522 	rtnl_lock();
9523 	i40e_do_reset(pf, reset_flags, true);
9524 	rtnl_unlock();
9525 }
9526 
9527 /**
9528  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
9529  * @pf: board private structure
9530  * @e: event info posted on ARQ
9531  *
9532  * Handler for LAN Queue Overflow Event generated by the firmware for PF
9533  * and VF queues
9534  **/
9535 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
9536 					   struct i40e_arq_event_info *e)
9537 {
9538 	struct i40e_aqc_lan_overflow *data =
9539 		(struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
9540 	u32 queue = le32_to_cpu(data->prtdcb_rupto);
9541 	u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
9542 	struct i40e_hw *hw = &pf->hw;
9543 	struct i40e_vf *vf;
9544 	u16 vf_id;
9545 
9546 	dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
9547 		queue, qtx_ctl);
9548 
9549 	/* Queue belongs to VF, find the VF and issue VF reset */
9550 	if (((qtx_ctl & I40E_QTX_CTL_PFVF_Q_MASK)
9551 	    >> I40E_QTX_CTL_PFVF_Q_SHIFT) == I40E_QTX_CTL_VF_QUEUE) {
9552 		vf_id = (u16)((qtx_ctl & I40E_QTX_CTL_VFVM_INDX_MASK)
9553 			 >> I40E_QTX_CTL_VFVM_INDX_SHIFT);
9554 		vf_id -= hw->func_caps.vf_base_id;
9555 		vf = &pf->vf[vf_id];
9556 		i40e_vc_notify_vf_reset(vf);
9557 		/* Allow VF to process pending reset notification */
9558 		msleep(20);
9559 		i40e_reset_vf(vf, false);
9560 	}
9561 }
9562 
9563 /**
9564  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
9565  * @pf: board private structure
9566  **/
9567 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
9568 {
9569 	u32 val, fcnt_prog;
9570 
9571 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9572 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
9573 	return fcnt_prog;
9574 }
9575 
9576 /**
9577  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
9578  * @pf: board private structure
9579  **/
9580 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
9581 {
9582 	u32 val, fcnt_prog;
9583 
9584 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9585 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
9586 		    ((val & I40E_PFQF_FDSTAT_BEST_CNT_MASK) >>
9587 		      I40E_PFQF_FDSTAT_BEST_CNT_SHIFT);
9588 	return fcnt_prog;
9589 }
9590 
9591 /**
9592  * i40e_get_global_fd_count - Get total FD filters programmed on device
9593  * @pf: board private structure
9594  **/
9595 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
9596 {
9597 	u32 val, fcnt_prog;
9598 
9599 	val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
9600 	fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
9601 		    ((val & I40E_GLQF_FDCNT_0_BESTCNT_MASK) >>
9602 		     I40E_GLQF_FDCNT_0_BESTCNT_SHIFT);
9603 	return fcnt_prog;
9604 }
9605 
9606 /**
9607  * i40e_reenable_fdir_sb - Restore FDir SB capability
9608  * @pf: board private structure
9609  **/
9610 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
9611 {
9612 	if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
9613 		if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
9614 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9615 			dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
9616 }
9617 
9618 /**
9619  * i40e_reenable_fdir_atr - Restore FDir ATR capability
9620  * @pf: board private structure
9621  **/
9622 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
9623 {
9624 	if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
9625 		/* ATR uses the same filtering logic as SB rules. It only
9626 		 * functions properly if the input set mask is at the default
9627 		 * settings. It is safe to restore the default input set
9628 		 * because there are no active TCPv4 filter rules.
9629 		 */
9630 		i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9631 					I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9632 					I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9633 
9634 		if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
9635 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9636 			dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
9637 	}
9638 }
9639 
9640 /**
9641  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
9642  * @pf: board private structure
9643  * @filter: FDir filter to remove
9644  */
9645 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
9646 				       struct i40e_fdir_filter *filter)
9647 {
9648 	/* Update counters */
9649 	pf->fdir_pf_active_filters--;
9650 	pf->fd_inv = 0;
9651 
9652 	switch (filter->flow_type) {
9653 	case TCP_V4_FLOW:
9654 		pf->fd_tcp4_filter_cnt--;
9655 		break;
9656 	case UDP_V4_FLOW:
9657 		pf->fd_udp4_filter_cnt--;
9658 		break;
9659 	case SCTP_V4_FLOW:
9660 		pf->fd_sctp4_filter_cnt--;
9661 		break;
9662 	case TCP_V6_FLOW:
9663 		pf->fd_tcp6_filter_cnt--;
9664 		break;
9665 	case UDP_V6_FLOW:
9666 		pf->fd_udp6_filter_cnt--;
9667 		break;
9668 	case SCTP_V6_FLOW:
9669 		pf->fd_udp6_filter_cnt--;
9670 		break;
9671 	case IP_USER_FLOW:
9672 		switch (filter->ipl4_proto) {
9673 		case IPPROTO_TCP:
9674 			pf->fd_tcp4_filter_cnt--;
9675 			break;
9676 		case IPPROTO_UDP:
9677 			pf->fd_udp4_filter_cnt--;
9678 			break;
9679 		case IPPROTO_SCTP:
9680 			pf->fd_sctp4_filter_cnt--;
9681 			break;
9682 		case IPPROTO_IP:
9683 			pf->fd_ip4_filter_cnt--;
9684 			break;
9685 		}
9686 		break;
9687 	case IPV6_USER_FLOW:
9688 		switch (filter->ipl4_proto) {
9689 		case IPPROTO_TCP:
9690 			pf->fd_tcp6_filter_cnt--;
9691 			break;
9692 		case IPPROTO_UDP:
9693 			pf->fd_udp6_filter_cnt--;
9694 			break;
9695 		case IPPROTO_SCTP:
9696 			pf->fd_sctp6_filter_cnt--;
9697 			break;
9698 		case IPPROTO_IP:
9699 			pf->fd_ip6_filter_cnt--;
9700 			break;
9701 		}
9702 		break;
9703 	}
9704 
9705 	/* Remove the filter from the list and free memory */
9706 	hlist_del(&filter->fdir_node);
9707 	kfree(filter);
9708 }
9709 
9710 /**
9711  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
9712  * @pf: board private structure
9713  **/
9714 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
9715 {
9716 	struct i40e_fdir_filter *filter;
9717 	u32 fcnt_prog, fcnt_avail;
9718 	struct hlist_node *node;
9719 
9720 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9721 		return;
9722 
9723 	/* Check if we have enough room to re-enable FDir SB capability. */
9724 	fcnt_prog = i40e_get_global_fd_count(pf);
9725 	fcnt_avail = pf->fdir_pf_filter_count;
9726 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
9727 	    (pf->fd_add_err == 0) ||
9728 	    (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
9729 		i40e_reenable_fdir_sb(pf);
9730 
9731 	/* We should wait for even more space before re-enabling ATR.
9732 	 * Additionally, we cannot enable ATR as long as we still have TCP SB
9733 	 * rules active.
9734 	 */
9735 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
9736 	    pf->fd_tcp4_filter_cnt == 0 && pf->fd_tcp6_filter_cnt == 0)
9737 		i40e_reenable_fdir_atr(pf);
9738 
9739 	/* if hw had a problem adding a filter, delete it */
9740 	if (pf->fd_inv > 0) {
9741 		hlist_for_each_entry_safe(filter, node,
9742 					  &pf->fdir_filter_list, fdir_node)
9743 			if (filter->fd_id == pf->fd_inv)
9744 				i40e_delete_invalid_filter(pf, filter);
9745 	}
9746 }
9747 
9748 #define I40E_MIN_FD_FLUSH_INTERVAL 10
9749 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
9750 /**
9751  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
9752  * @pf: board private structure
9753  **/
9754 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
9755 {
9756 	unsigned long min_flush_time;
9757 	int flush_wait_retry = 50;
9758 	bool disable_atr = false;
9759 	int fd_room;
9760 	int reg;
9761 
9762 	if (!time_after(jiffies, pf->fd_flush_timestamp +
9763 				 (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
9764 		return;
9765 
9766 	/* If the flush is happening too quick and we have mostly SB rules we
9767 	 * should not re-enable ATR for some time.
9768 	 */
9769 	min_flush_time = pf->fd_flush_timestamp +
9770 			 (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
9771 	fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
9772 
9773 	if (!(time_after(jiffies, min_flush_time)) &&
9774 	    (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
9775 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9776 			dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
9777 		disable_atr = true;
9778 	}
9779 
9780 	pf->fd_flush_timestamp = jiffies;
9781 	set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9782 	/* flush all filters */
9783 	wr32(&pf->hw, I40E_PFQF_CTL_1,
9784 	     I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
9785 	i40e_flush(&pf->hw);
9786 	pf->fd_flush_cnt++;
9787 	pf->fd_add_err = 0;
9788 	do {
9789 		/* Check FD flush status every 5-6msec */
9790 		usleep_range(5000, 6000);
9791 		reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
9792 		if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
9793 			break;
9794 	} while (flush_wait_retry--);
9795 	if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
9796 		dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
9797 	} else {
9798 		/* replay sideband filters */
9799 		i40e_fdir_filter_restore(pf->vsi[pf->lan_vsi]);
9800 		if (!disable_atr && !pf->fd_tcp4_filter_cnt)
9801 			clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9802 		clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
9803 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9804 			dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
9805 	}
9806 }
9807 
9808 /**
9809  * i40e_get_current_atr_cnt - Get the count of total FD ATR filters programmed
9810  * @pf: board private structure
9811  **/
9812 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
9813 {
9814 	return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
9815 }
9816 
9817 /**
9818  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
9819  * @pf: board private structure
9820  **/
9821 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
9822 {
9823 
9824 	/* if interface is down do nothing */
9825 	if (test_bit(__I40E_DOWN, pf->state))
9826 		return;
9827 
9828 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9829 		i40e_fdir_flush_and_replay(pf);
9830 
9831 	i40e_fdir_check_and_reenable(pf);
9832 
9833 }
9834 
9835 /**
9836  * i40e_vsi_link_event - notify VSI of a link event
9837  * @vsi: vsi to be notified
9838  * @link_up: link up or down
9839  **/
9840 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
9841 {
9842 	if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
9843 		return;
9844 
9845 	switch (vsi->type) {
9846 	case I40E_VSI_MAIN:
9847 		if (!vsi->netdev || !vsi->netdev_registered)
9848 			break;
9849 
9850 		if (link_up) {
9851 			netif_carrier_on(vsi->netdev);
9852 			netif_tx_wake_all_queues(vsi->netdev);
9853 		} else {
9854 			netif_carrier_off(vsi->netdev);
9855 			netif_tx_stop_all_queues(vsi->netdev);
9856 		}
9857 		break;
9858 
9859 	case I40E_VSI_SRIOV:
9860 	case I40E_VSI_VMDQ2:
9861 	case I40E_VSI_CTRL:
9862 	case I40E_VSI_IWARP:
9863 	case I40E_VSI_MIRROR:
9864 	default:
9865 		/* there is no notification for other VSIs */
9866 		break;
9867 	}
9868 }
9869 
9870 /**
9871  * i40e_veb_link_event - notify elements on the veb of a link event
9872  * @veb: veb to be notified
9873  * @link_up: link up or down
9874  **/
9875 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
9876 {
9877 	struct i40e_pf *pf;
9878 	int i;
9879 
9880 	if (!veb || !veb->pf)
9881 		return;
9882 	pf = veb->pf;
9883 
9884 	/* depth first... */
9885 	for (i = 0; i < I40E_MAX_VEB; i++)
9886 		if (pf->veb[i] && (pf->veb[i]->uplink_seid == veb->seid))
9887 			i40e_veb_link_event(pf->veb[i], link_up);
9888 
9889 	/* ... now the local VSIs */
9890 	for (i = 0; i < pf->num_alloc_vsi; i++)
9891 		if (pf->vsi[i] && (pf->vsi[i]->uplink_seid == veb->seid))
9892 			i40e_vsi_link_event(pf->vsi[i], link_up);
9893 }
9894 
9895 /**
9896  * i40e_link_event - Update netif_carrier status
9897  * @pf: board private structure
9898  **/
9899 static void i40e_link_event(struct i40e_pf *pf)
9900 {
9901 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9902 	u8 new_link_speed, old_link_speed;
9903 	bool new_link, old_link;
9904 	int status;
9905 #ifdef CONFIG_I40E_DCB
9906 	int err;
9907 #endif /* CONFIG_I40E_DCB */
9908 
9909 	/* set this to force the get_link_status call to refresh state */
9910 	pf->hw.phy.get_link_info = true;
9911 	old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9912 	status = i40e_get_link_status(&pf->hw, &new_link);
9913 
9914 	/* On success, disable temp link polling */
9915 	if (status == I40E_SUCCESS) {
9916 		clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9917 	} else {
9918 		/* Enable link polling temporarily until i40e_get_link_status
9919 		 * returns I40E_SUCCESS
9920 		 */
9921 		set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9922 		dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9923 			status);
9924 		return;
9925 	}
9926 
9927 	old_link_speed = pf->hw.phy.link_info_old.link_speed;
9928 	new_link_speed = pf->hw.phy.link_info.link_speed;
9929 
9930 	if (new_link == old_link &&
9931 	    new_link_speed == old_link_speed &&
9932 	    (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9933 	     new_link == netif_carrier_ok(vsi->netdev)))
9934 		return;
9935 
9936 	i40e_print_link_message(vsi, new_link);
9937 
9938 	/* Notify the base of the switch tree connected to
9939 	 * the link.  Floating VEBs are not notified.
9940 	 */
9941 	if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
9942 		i40e_veb_link_event(pf->veb[pf->lan_veb], new_link);
9943 	else
9944 		i40e_vsi_link_event(vsi, new_link);
9945 
9946 	if (pf->vf)
9947 		i40e_vc_notify_link_state(pf);
9948 
9949 	if (pf->flags & I40E_FLAG_PTP)
9950 		i40e_ptp_set_increment(pf);
9951 #ifdef CONFIG_I40E_DCB
9952 	if (new_link == old_link)
9953 		return;
9954 	/* Not SW DCB so firmware will take care of default settings */
9955 	if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED)
9956 		return;
9957 
9958 	/* We cover here only link down, as after link up in case of SW DCB
9959 	 * SW LLDP agent will take care of setting it up
9960 	 */
9961 	if (!new_link) {
9962 		dev_dbg(&pf->pdev->dev, "Reconfig DCB to single TC as result of Link Down\n");
9963 		memset(&pf->tmp_cfg, 0, sizeof(pf->tmp_cfg));
9964 		err = i40e_dcb_sw_default_config(pf);
9965 		if (err) {
9966 			pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
9967 				       I40E_FLAG_DCB_ENABLED);
9968 		} else {
9969 			pf->dcbx_cap = DCB_CAP_DCBX_HOST |
9970 				       DCB_CAP_DCBX_VER_IEEE;
9971 			pf->flags |= I40E_FLAG_DCB_CAPABLE;
9972 			pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9973 		}
9974 	}
9975 #endif /* CONFIG_I40E_DCB */
9976 }
9977 
9978 /**
9979  * i40e_watchdog_subtask - periodic checks not using event driven response
9980  * @pf: board private structure
9981  **/
9982 static void i40e_watchdog_subtask(struct i40e_pf *pf)
9983 {
9984 	int i;
9985 
9986 	/* if interface is down do nothing */
9987 	if (test_bit(__I40E_DOWN, pf->state) ||
9988 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
9989 		return;
9990 
9991 	/* make sure we don't do these things too often */
9992 	if (time_before(jiffies, (pf->service_timer_previous +
9993 				  pf->service_timer_period)))
9994 		return;
9995 	pf->service_timer_previous = jiffies;
9996 
9997 	if ((pf->flags & I40E_FLAG_LINK_POLLING_ENABLED) ||
9998 	    test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
9999 		i40e_link_event(pf);
10000 
10001 	/* Update the stats for active netdevs so the network stack
10002 	 * can look at updated numbers whenever it cares to
10003 	 */
10004 	for (i = 0; i < pf->num_alloc_vsi; i++)
10005 		if (pf->vsi[i] && pf->vsi[i]->netdev)
10006 			i40e_update_stats(pf->vsi[i]);
10007 
10008 	if (pf->flags & I40E_FLAG_VEB_STATS_ENABLED) {
10009 		/* Update the stats for the active switching components */
10010 		for (i = 0; i < I40E_MAX_VEB; i++)
10011 			if (pf->veb[i])
10012 				i40e_update_veb_stats(pf->veb[i]);
10013 	}
10014 
10015 	i40e_ptp_rx_hang(pf);
10016 	i40e_ptp_tx_hang(pf);
10017 }
10018 
10019 /**
10020  * i40e_reset_subtask - Set up for resetting the device and driver
10021  * @pf: board private structure
10022  **/
10023 static void i40e_reset_subtask(struct i40e_pf *pf)
10024 {
10025 	u32 reset_flags = 0;
10026 
10027 	if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
10028 		reset_flags |= BIT(__I40E_REINIT_REQUESTED);
10029 		clear_bit(__I40E_REINIT_REQUESTED, pf->state);
10030 	}
10031 	if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
10032 		reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
10033 		clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
10034 	}
10035 	if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
10036 		reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
10037 		clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
10038 	}
10039 	if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
10040 		reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
10041 		clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
10042 	}
10043 	if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
10044 		reset_flags |= BIT(__I40E_DOWN_REQUESTED);
10045 		clear_bit(__I40E_DOWN_REQUESTED, pf->state);
10046 	}
10047 
10048 	/* If there's a recovery already waiting, it takes
10049 	 * precedence before starting a new reset sequence.
10050 	 */
10051 	if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
10052 		i40e_prep_for_reset(pf);
10053 		i40e_reset(pf);
10054 		i40e_rebuild(pf, false, false);
10055 	}
10056 
10057 	/* If we're already down or resetting, just bail */
10058 	if (reset_flags &&
10059 	    !test_bit(__I40E_DOWN, pf->state) &&
10060 	    !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
10061 		i40e_do_reset(pf, reset_flags, false);
10062 	}
10063 }
10064 
10065 /**
10066  * i40e_handle_link_event - Handle link event
10067  * @pf: board private structure
10068  * @e: event info posted on ARQ
10069  **/
10070 static void i40e_handle_link_event(struct i40e_pf *pf,
10071 				   struct i40e_arq_event_info *e)
10072 {
10073 	struct i40e_aqc_get_link_status *status =
10074 		(struct i40e_aqc_get_link_status *)&e->desc.params.raw;
10075 
10076 	/* Do a new status request to re-enable LSE reporting
10077 	 * and load new status information into the hw struct
10078 	 * This completely ignores any state information
10079 	 * in the ARQ event info, instead choosing to always
10080 	 * issue the AQ update link status command.
10081 	 */
10082 	i40e_link_event(pf);
10083 
10084 	/* Check if module meets thermal requirements */
10085 	if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
10086 		dev_err(&pf->pdev->dev,
10087 			"Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
10088 		dev_err(&pf->pdev->dev,
10089 			"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10090 	} else {
10091 		/* check for unqualified module, if link is down, suppress
10092 		 * the message if link was forced to be down.
10093 		 */
10094 		if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
10095 		    (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
10096 		    (!(status->link_info & I40E_AQ_LINK_UP)) &&
10097 		    (!(pf->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED))) {
10098 			dev_err(&pf->pdev->dev,
10099 				"Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
10100 			dev_err(&pf->pdev->dev,
10101 				"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10102 		}
10103 	}
10104 }
10105 
10106 /**
10107  * i40e_clean_adminq_subtask - Clean the AdminQ rings
10108  * @pf: board private structure
10109  **/
10110 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
10111 {
10112 	struct i40e_arq_event_info event;
10113 	struct i40e_hw *hw = &pf->hw;
10114 	u16 pending, i = 0;
10115 	u16 opcode;
10116 	u32 oldval;
10117 	int ret;
10118 	u32 val;
10119 
10120 	/* Do not run clean AQ when PF reset fails */
10121 	if (test_bit(__I40E_RESET_FAILED, pf->state))
10122 		return;
10123 
10124 	/* check for error indications */
10125 	val = rd32(&pf->hw, pf->hw.aq.arq.len);
10126 	oldval = val;
10127 	if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
10128 		if (hw->debug_mask & I40E_DEBUG_AQ)
10129 			dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
10130 		val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
10131 	}
10132 	if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
10133 		if (hw->debug_mask & I40E_DEBUG_AQ)
10134 			dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
10135 		val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
10136 		pf->arq_overflows++;
10137 	}
10138 	if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
10139 		if (hw->debug_mask & I40E_DEBUG_AQ)
10140 			dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
10141 		val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
10142 	}
10143 	if (oldval != val)
10144 		wr32(&pf->hw, pf->hw.aq.arq.len, val);
10145 
10146 	val = rd32(&pf->hw, pf->hw.aq.asq.len);
10147 	oldval = val;
10148 	if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
10149 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10150 			dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
10151 		val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
10152 	}
10153 	if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
10154 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10155 			dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
10156 		val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
10157 	}
10158 	if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
10159 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10160 			dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
10161 		val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
10162 	}
10163 	if (oldval != val)
10164 		wr32(&pf->hw, pf->hw.aq.asq.len, val);
10165 
10166 	event.buf_len = I40E_MAX_AQ_BUF_SIZE;
10167 	event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
10168 	if (!event.msg_buf)
10169 		return;
10170 
10171 	do {
10172 		ret = i40e_clean_arq_element(hw, &event, &pending);
10173 		if (ret == I40E_ERR_ADMIN_QUEUE_NO_WORK)
10174 			break;
10175 		else if (ret) {
10176 			dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
10177 			break;
10178 		}
10179 
10180 		opcode = le16_to_cpu(event.desc.opcode);
10181 		switch (opcode) {
10182 
10183 		case i40e_aqc_opc_get_link_status:
10184 			rtnl_lock();
10185 			i40e_handle_link_event(pf, &event);
10186 			rtnl_unlock();
10187 			break;
10188 		case i40e_aqc_opc_send_msg_to_pf:
10189 			ret = i40e_vc_process_vf_msg(pf,
10190 					le16_to_cpu(event.desc.retval),
10191 					le32_to_cpu(event.desc.cookie_high),
10192 					le32_to_cpu(event.desc.cookie_low),
10193 					event.msg_buf,
10194 					event.msg_len);
10195 			break;
10196 		case i40e_aqc_opc_lldp_update_mib:
10197 			dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
10198 #ifdef CONFIG_I40E_DCB
10199 			rtnl_lock();
10200 			i40e_handle_lldp_event(pf, &event);
10201 			rtnl_unlock();
10202 #endif /* CONFIG_I40E_DCB */
10203 			break;
10204 		case i40e_aqc_opc_event_lan_overflow:
10205 			dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
10206 			i40e_handle_lan_overflow_event(pf, &event);
10207 			break;
10208 		case i40e_aqc_opc_send_msg_to_peer:
10209 			dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
10210 			break;
10211 		case i40e_aqc_opc_nvm_erase:
10212 		case i40e_aqc_opc_nvm_update:
10213 		case i40e_aqc_opc_oem_post_update:
10214 			i40e_debug(&pf->hw, I40E_DEBUG_NVM,
10215 				   "ARQ NVM operation 0x%04x completed\n",
10216 				   opcode);
10217 			break;
10218 		default:
10219 			dev_info(&pf->pdev->dev,
10220 				 "ARQ: Unknown event 0x%04x ignored\n",
10221 				 opcode);
10222 			break;
10223 		}
10224 	} while (i++ < pf->adminq_work_limit);
10225 
10226 	if (i < pf->adminq_work_limit)
10227 		clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
10228 
10229 	/* re-enable Admin queue interrupt cause */
10230 	val = rd32(hw, I40E_PFINT_ICR0_ENA);
10231 	val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
10232 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
10233 	i40e_flush(hw);
10234 
10235 	kfree(event.msg_buf);
10236 }
10237 
10238 /**
10239  * i40e_verify_eeprom - make sure eeprom is good to use
10240  * @pf: board private structure
10241  **/
10242 static void i40e_verify_eeprom(struct i40e_pf *pf)
10243 {
10244 	int err;
10245 
10246 	err = i40e_diag_eeprom_test(&pf->hw);
10247 	if (err) {
10248 		/* retry in case of garbage read */
10249 		err = i40e_diag_eeprom_test(&pf->hw);
10250 		if (err) {
10251 			dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
10252 				 err);
10253 			set_bit(__I40E_BAD_EEPROM, pf->state);
10254 		}
10255 	}
10256 
10257 	if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
10258 		dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
10259 		clear_bit(__I40E_BAD_EEPROM, pf->state);
10260 	}
10261 }
10262 
10263 /**
10264  * i40e_enable_pf_switch_lb
10265  * @pf: pointer to the PF structure
10266  *
10267  * enable switch loop back or die - no point in a return value
10268  **/
10269 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
10270 {
10271 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10272 	struct i40e_vsi_context ctxt;
10273 	int ret;
10274 
10275 	ctxt.seid = pf->main_vsi_seid;
10276 	ctxt.pf_num = pf->hw.pf_id;
10277 	ctxt.vf_num = 0;
10278 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10279 	if (ret) {
10280 		dev_info(&pf->pdev->dev,
10281 			 "couldn't get PF vsi config, err %pe aq_err %s\n",
10282 			 ERR_PTR(ret),
10283 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10284 		return;
10285 	}
10286 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10287 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10288 	ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10289 
10290 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10291 	if (ret) {
10292 		dev_info(&pf->pdev->dev,
10293 			 "update vsi switch failed, err %pe aq_err %s\n",
10294 			 ERR_PTR(ret),
10295 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10296 	}
10297 }
10298 
10299 /**
10300  * i40e_disable_pf_switch_lb
10301  * @pf: pointer to the PF structure
10302  *
10303  * disable switch loop back or die - no point in a return value
10304  **/
10305 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
10306 {
10307 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10308 	struct i40e_vsi_context ctxt;
10309 	int ret;
10310 
10311 	ctxt.seid = pf->main_vsi_seid;
10312 	ctxt.pf_num = pf->hw.pf_id;
10313 	ctxt.vf_num = 0;
10314 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10315 	if (ret) {
10316 		dev_info(&pf->pdev->dev,
10317 			 "couldn't get PF vsi config, err %pe aq_err %s\n",
10318 			 ERR_PTR(ret),
10319 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10320 		return;
10321 	}
10322 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10323 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10324 	ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10325 
10326 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10327 	if (ret) {
10328 		dev_info(&pf->pdev->dev,
10329 			 "update vsi switch failed, err %pe aq_err %s\n",
10330 			 ERR_PTR(ret),
10331 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10332 	}
10333 }
10334 
10335 /**
10336  * i40e_config_bridge_mode - Configure the HW bridge mode
10337  * @veb: pointer to the bridge instance
10338  *
10339  * Configure the loop back mode for the LAN VSI that is downlink to the
10340  * specified HW bridge instance. It is expected this function is called
10341  * when a new HW bridge is instantiated.
10342  **/
10343 static void i40e_config_bridge_mode(struct i40e_veb *veb)
10344 {
10345 	struct i40e_pf *pf = veb->pf;
10346 
10347 	if (pf->hw.debug_mask & I40E_DEBUG_LAN)
10348 		dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
10349 			 veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
10350 	if (veb->bridge_mode & BRIDGE_MODE_VEPA)
10351 		i40e_disable_pf_switch_lb(pf);
10352 	else
10353 		i40e_enable_pf_switch_lb(pf);
10354 }
10355 
10356 /**
10357  * i40e_reconstitute_veb - rebuild the VEB and anything connected to it
10358  * @veb: pointer to the VEB instance
10359  *
10360  * This is a recursive function that first builds the attached VSIs then
10361  * recurses in to build the next layer of VEB.  We track the connections
10362  * through our own index numbers because the seid's from the HW could
10363  * change across the reset.
10364  **/
10365 static int i40e_reconstitute_veb(struct i40e_veb *veb)
10366 {
10367 	struct i40e_vsi *ctl_vsi = NULL;
10368 	struct i40e_pf *pf = veb->pf;
10369 	int v, veb_idx;
10370 	int ret;
10371 
10372 	/* build VSI that owns this VEB, temporarily attached to base VEB */
10373 	for (v = 0; v < pf->num_alloc_vsi && !ctl_vsi; v++) {
10374 		if (pf->vsi[v] &&
10375 		    pf->vsi[v]->veb_idx == veb->idx &&
10376 		    pf->vsi[v]->flags & I40E_VSI_FLAG_VEB_OWNER) {
10377 			ctl_vsi = pf->vsi[v];
10378 			break;
10379 		}
10380 	}
10381 	if (!ctl_vsi) {
10382 		dev_info(&pf->pdev->dev,
10383 			 "missing owner VSI for veb_idx %d\n", veb->idx);
10384 		ret = -ENOENT;
10385 		goto end_reconstitute;
10386 	}
10387 	if (ctl_vsi != pf->vsi[pf->lan_vsi])
10388 		ctl_vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
10389 	ret = i40e_add_vsi(ctl_vsi);
10390 	if (ret) {
10391 		dev_info(&pf->pdev->dev,
10392 			 "rebuild of veb_idx %d owner VSI failed: %d\n",
10393 			 veb->idx, ret);
10394 		goto end_reconstitute;
10395 	}
10396 	i40e_vsi_reset_stats(ctl_vsi);
10397 
10398 	/* create the VEB in the switch and move the VSI onto the VEB */
10399 	ret = i40e_add_veb(veb, ctl_vsi);
10400 	if (ret)
10401 		goto end_reconstitute;
10402 
10403 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
10404 		veb->bridge_mode = BRIDGE_MODE_VEB;
10405 	else
10406 		veb->bridge_mode = BRIDGE_MODE_VEPA;
10407 	i40e_config_bridge_mode(veb);
10408 
10409 	/* create the remaining VSIs attached to this VEB */
10410 	for (v = 0; v < pf->num_alloc_vsi; v++) {
10411 		if (!pf->vsi[v] || pf->vsi[v] == ctl_vsi)
10412 			continue;
10413 
10414 		if (pf->vsi[v]->veb_idx == veb->idx) {
10415 			struct i40e_vsi *vsi = pf->vsi[v];
10416 
10417 			vsi->uplink_seid = veb->seid;
10418 			ret = i40e_add_vsi(vsi);
10419 			if (ret) {
10420 				dev_info(&pf->pdev->dev,
10421 					 "rebuild of vsi_idx %d failed: %d\n",
10422 					 v, ret);
10423 				goto end_reconstitute;
10424 			}
10425 			i40e_vsi_reset_stats(vsi);
10426 		}
10427 	}
10428 
10429 	/* create any VEBs attached to this VEB - RECURSION */
10430 	for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
10431 		if (pf->veb[veb_idx] && pf->veb[veb_idx]->veb_idx == veb->idx) {
10432 			pf->veb[veb_idx]->uplink_seid = veb->seid;
10433 			ret = i40e_reconstitute_veb(pf->veb[veb_idx]);
10434 			if (ret)
10435 				break;
10436 		}
10437 	}
10438 
10439 end_reconstitute:
10440 	return ret;
10441 }
10442 
10443 /**
10444  * i40e_get_capabilities - get info about the HW
10445  * @pf: the PF struct
10446  * @list_type: AQ capability to be queried
10447  **/
10448 static int i40e_get_capabilities(struct i40e_pf *pf,
10449 				 enum i40e_admin_queue_opc list_type)
10450 {
10451 	struct i40e_aqc_list_capabilities_element_resp *cap_buf;
10452 	u16 data_size;
10453 	int buf_len;
10454 	int err;
10455 
10456 	buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
10457 	do {
10458 		cap_buf = kzalloc(buf_len, GFP_KERNEL);
10459 		if (!cap_buf)
10460 			return -ENOMEM;
10461 
10462 		/* this loads the data into the hw struct for us */
10463 		err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
10464 						    &data_size, list_type,
10465 						    NULL);
10466 		/* data loaded, buffer no longer needed */
10467 		kfree(cap_buf);
10468 
10469 		if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
10470 			/* retry with a larger buffer */
10471 			buf_len = data_size;
10472 		} else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK || err) {
10473 			dev_info(&pf->pdev->dev,
10474 				 "capability discovery failed, err %pe aq_err %s\n",
10475 				 ERR_PTR(err),
10476 				 i40e_aq_str(&pf->hw,
10477 					     pf->hw.aq.asq_last_status));
10478 			return -ENODEV;
10479 		}
10480 	} while (err);
10481 
10482 	if (pf->hw.debug_mask & I40E_DEBUG_USER) {
10483 		if (list_type == i40e_aqc_opc_list_func_capabilities) {
10484 			dev_info(&pf->pdev->dev,
10485 				 "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",
10486 				 pf->hw.pf_id, pf->hw.func_caps.num_vfs,
10487 				 pf->hw.func_caps.num_msix_vectors,
10488 				 pf->hw.func_caps.num_msix_vectors_vf,
10489 				 pf->hw.func_caps.fd_filters_guaranteed,
10490 				 pf->hw.func_caps.fd_filters_best_effort,
10491 				 pf->hw.func_caps.num_tx_qp,
10492 				 pf->hw.func_caps.num_vsis);
10493 		} else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
10494 			dev_info(&pf->pdev->dev,
10495 				 "switch_mode=0x%04x, function_valid=0x%08x\n",
10496 				 pf->hw.dev_caps.switch_mode,
10497 				 pf->hw.dev_caps.valid_functions);
10498 			dev_info(&pf->pdev->dev,
10499 				 "SR-IOV=%d, num_vfs for all function=%u\n",
10500 				 pf->hw.dev_caps.sr_iov_1_1,
10501 				 pf->hw.dev_caps.num_vfs);
10502 			dev_info(&pf->pdev->dev,
10503 				 "num_vsis=%u, num_rx:%u, num_tx=%u\n",
10504 				 pf->hw.dev_caps.num_vsis,
10505 				 pf->hw.dev_caps.num_rx_qp,
10506 				 pf->hw.dev_caps.num_tx_qp);
10507 		}
10508 	}
10509 	if (list_type == i40e_aqc_opc_list_func_capabilities) {
10510 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
10511 		       + pf->hw.func_caps.num_vfs)
10512 		if (pf->hw.revision_id == 0 &&
10513 		    pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
10514 			dev_info(&pf->pdev->dev,
10515 				 "got num_vsis %d, setting num_vsis to %d\n",
10516 				 pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
10517 			pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
10518 		}
10519 	}
10520 	return 0;
10521 }
10522 
10523 static int i40e_vsi_clear(struct i40e_vsi *vsi);
10524 
10525 /**
10526  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
10527  * @pf: board private structure
10528  **/
10529 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
10530 {
10531 	struct i40e_vsi *vsi;
10532 
10533 	/* quick workaround for an NVM issue that leaves a critical register
10534 	 * uninitialized
10535 	 */
10536 	if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
10537 		static const u32 hkey[] = {
10538 			0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
10539 			0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
10540 			0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
10541 			0x95b3a76d};
10542 		int i;
10543 
10544 		for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
10545 			wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
10546 	}
10547 
10548 	if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
10549 		return;
10550 
10551 	/* find existing VSI and see if it needs configuring */
10552 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10553 
10554 	/* create a new VSI if none exists */
10555 	if (!vsi) {
10556 		vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR,
10557 				     pf->vsi[pf->lan_vsi]->seid, 0);
10558 		if (!vsi) {
10559 			dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
10560 			pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
10561 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
10562 			return;
10563 		}
10564 	}
10565 
10566 	i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
10567 }
10568 
10569 /**
10570  * i40e_fdir_teardown - release the Flow Director resources
10571  * @pf: board private structure
10572  **/
10573 static void i40e_fdir_teardown(struct i40e_pf *pf)
10574 {
10575 	struct i40e_vsi *vsi;
10576 
10577 	i40e_fdir_filter_exit(pf);
10578 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10579 	if (vsi)
10580 		i40e_vsi_release(vsi);
10581 }
10582 
10583 /**
10584  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
10585  * @vsi: PF main vsi
10586  * @seid: seid of main or channel VSIs
10587  *
10588  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
10589  * existed before reset
10590  **/
10591 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
10592 {
10593 	struct i40e_cloud_filter *cfilter;
10594 	struct i40e_pf *pf = vsi->back;
10595 	struct hlist_node *node;
10596 	int ret;
10597 
10598 	/* Add cloud filters back if they exist */
10599 	hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
10600 				  cloud_node) {
10601 		if (cfilter->seid != seid)
10602 			continue;
10603 
10604 		if (cfilter->dst_port)
10605 			ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
10606 								true);
10607 		else
10608 			ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
10609 
10610 		if (ret) {
10611 			dev_dbg(&pf->pdev->dev,
10612 				"Failed to rebuild cloud filter, err %pe aq_err %s\n",
10613 				ERR_PTR(ret),
10614 				i40e_aq_str(&pf->hw,
10615 					    pf->hw.aq.asq_last_status));
10616 			return ret;
10617 		}
10618 	}
10619 	return 0;
10620 }
10621 
10622 /**
10623  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
10624  * @vsi: PF main vsi
10625  *
10626  * Rebuilds channel VSIs if they existed before reset
10627  **/
10628 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
10629 {
10630 	struct i40e_channel *ch, *ch_tmp;
10631 	int ret;
10632 
10633 	if (list_empty(&vsi->ch_list))
10634 		return 0;
10635 
10636 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
10637 		if (!ch->initialized)
10638 			break;
10639 		/* Proceed with creation of channel (VMDq2) VSI */
10640 		ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
10641 		if (ret) {
10642 			dev_info(&vsi->back->pdev->dev,
10643 				 "failed to rebuild channels using uplink_seid %u\n",
10644 				 vsi->uplink_seid);
10645 			return ret;
10646 		}
10647 		/* Reconfigure TX queues using QTX_CTL register */
10648 		ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
10649 		if (ret) {
10650 			dev_info(&vsi->back->pdev->dev,
10651 				 "failed to configure TX rings for channel %u\n",
10652 				 ch->seid);
10653 			return ret;
10654 		}
10655 		/* update 'next_base_queue' */
10656 		vsi->next_base_queue = vsi->next_base_queue +
10657 							ch->num_queue_pairs;
10658 		if (ch->max_tx_rate) {
10659 			u64 credits = ch->max_tx_rate;
10660 
10661 			if (i40e_set_bw_limit(vsi, ch->seid,
10662 					      ch->max_tx_rate))
10663 				return -EINVAL;
10664 
10665 			do_div(credits, I40E_BW_CREDIT_DIVISOR);
10666 			dev_dbg(&vsi->back->pdev->dev,
10667 				"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10668 				ch->max_tx_rate,
10669 				credits,
10670 				ch->seid);
10671 		}
10672 		ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
10673 		if (ret) {
10674 			dev_dbg(&vsi->back->pdev->dev,
10675 				"Failed to rebuild cloud filters for channel VSI %u\n",
10676 				ch->seid);
10677 			return ret;
10678 		}
10679 	}
10680 	return 0;
10681 }
10682 
10683 /**
10684  * i40e_clean_xps_state - clean xps state for every tx_ring
10685  * @vsi: ptr to the VSI
10686  **/
10687 static void i40e_clean_xps_state(struct i40e_vsi *vsi)
10688 {
10689 	int i;
10690 
10691 	if (vsi->tx_rings)
10692 		for (i = 0; i < vsi->num_queue_pairs; i++)
10693 			if (vsi->tx_rings[i])
10694 				clear_bit(__I40E_TX_XPS_INIT_DONE,
10695 					  vsi->tx_rings[i]->state);
10696 }
10697 
10698 /**
10699  * i40e_prep_for_reset - prep for the core to reset
10700  * @pf: board private structure
10701  *
10702  * Close up the VFs and other things in prep for PF Reset.
10703   **/
10704 static void i40e_prep_for_reset(struct i40e_pf *pf)
10705 {
10706 	struct i40e_hw *hw = &pf->hw;
10707 	int ret = 0;
10708 	u32 v;
10709 
10710 	clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
10711 	if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
10712 		return;
10713 	if (i40e_check_asq_alive(&pf->hw))
10714 		i40e_vc_notify_reset(pf);
10715 
10716 	dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
10717 
10718 	/* quiesce the VSIs and their queues that are not already DOWN */
10719 	i40e_pf_quiesce_all_vsi(pf);
10720 
10721 	for (v = 0; v < pf->num_alloc_vsi; v++) {
10722 		if (pf->vsi[v]) {
10723 			i40e_clean_xps_state(pf->vsi[v]);
10724 			pf->vsi[v]->seid = 0;
10725 		}
10726 	}
10727 
10728 	i40e_shutdown_adminq(&pf->hw);
10729 
10730 	/* call shutdown HMC */
10731 	if (hw->hmc.hmc_obj) {
10732 		ret = i40e_shutdown_lan_hmc(hw);
10733 		if (ret)
10734 			dev_warn(&pf->pdev->dev,
10735 				 "shutdown_lan_hmc failed: %d\n", ret);
10736 	}
10737 
10738 	/* Save the current PTP time so that we can restore the time after the
10739 	 * reset completes.
10740 	 */
10741 	i40e_ptp_save_hw_time(pf);
10742 }
10743 
10744 /**
10745  * i40e_send_version - update firmware with driver version
10746  * @pf: PF struct
10747  */
10748 static void i40e_send_version(struct i40e_pf *pf)
10749 {
10750 	struct i40e_driver_version dv;
10751 
10752 	dv.major_version = 0xff;
10753 	dv.minor_version = 0xff;
10754 	dv.build_version = 0xff;
10755 	dv.subbuild_version = 0;
10756 	strscpy(dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string));
10757 	i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
10758 }
10759 
10760 /**
10761  * i40e_get_oem_version - get OEM specific version information
10762  * @hw: pointer to the hardware structure
10763  **/
10764 static void i40e_get_oem_version(struct i40e_hw *hw)
10765 {
10766 	u16 block_offset = 0xffff;
10767 	u16 block_length = 0;
10768 	u16 capabilities = 0;
10769 	u16 gen_snap = 0;
10770 	u16 release = 0;
10771 
10772 #define I40E_SR_NVM_OEM_VERSION_PTR		0x1B
10773 #define I40E_NVM_OEM_LENGTH_OFFSET		0x00
10774 #define I40E_NVM_OEM_CAPABILITIES_OFFSET	0x01
10775 #define I40E_NVM_OEM_GEN_OFFSET			0x02
10776 #define I40E_NVM_OEM_RELEASE_OFFSET		0x03
10777 #define I40E_NVM_OEM_CAPABILITIES_MASK		0x000F
10778 #define I40E_NVM_OEM_LENGTH			3
10779 
10780 	/* Check if pointer to OEM version block is valid. */
10781 	i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
10782 	if (block_offset == 0xffff)
10783 		return;
10784 
10785 	/* Check if OEM version block has correct length. */
10786 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
10787 			   &block_length);
10788 	if (block_length < I40E_NVM_OEM_LENGTH)
10789 		return;
10790 
10791 	/* Check if OEM version format is as expected. */
10792 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
10793 			   &capabilities);
10794 	if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
10795 		return;
10796 
10797 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
10798 			   &gen_snap);
10799 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
10800 			   &release);
10801 	hw->nvm.oem_ver = (gen_snap << I40E_OEM_SNAP_SHIFT) | release;
10802 	hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
10803 }
10804 
10805 /**
10806  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
10807  * @pf: board private structure
10808  **/
10809 static int i40e_reset(struct i40e_pf *pf)
10810 {
10811 	struct i40e_hw *hw = &pf->hw;
10812 	int ret;
10813 
10814 	ret = i40e_pf_reset(hw);
10815 	if (ret) {
10816 		dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
10817 		set_bit(__I40E_RESET_FAILED, pf->state);
10818 		clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10819 	} else {
10820 		pf->pfr_count++;
10821 	}
10822 	return ret;
10823 }
10824 
10825 /**
10826  * i40e_rebuild - rebuild using a saved config
10827  * @pf: board private structure
10828  * @reinit: if the Main VSI needs to re-initialized.
10829  * @lock_acquired: indicates whether or not the lock has been acquired
10830  * before this function was called.
10831  **/
10832 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
10833 {
10834 	const bool is_recovery_mode_reported = i40e_check_recovery_mode(pf);
10835 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10836 	struct i40e_hw *hw = &pf->hw;
10837 	int ret;
10838 	u32 val;
10839 	int v;
10840 
10841 	if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10842 	    is_recovery_mode_reported)
10843 		i40e_set_ethtool_ops(pf->vsi[pf->lan_vsi]->netdev);
10844 
10845 	if (test_bit(__I40E_DOWN, pf->state) &&
10846 	    !test_bit(__I40E_RECOVERY_MODE, pf->state))
10847 		goto clear_recovery;
10848 	dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
10849 
10850 	/* rebuild the basics for the AdminQ, HMC, and initial HW switch */
10851 	ret = i40e_init_adminq(&pf->hw);
10852 	if (ret) {
10853 		dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %pe aq_err %s\n",
10854 			 ERR_PTR(ret),
10855 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10856 		goto clear_recovery;
10857 	}
10858 	i40e_get_oem_version(&pf->hw);
10859 
10860 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state)) {
10861 		/* The following delay is necessary for firmware update. */
10862 		mdelay(1000);
10863 	}
10864 
10865 	/* re-verify the eeprom if we just had an EMP reset */
10866 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
10867 		i40e_verify_eeprom(pf);
10868 
10869 	/* if we are going out of or into recovery mode we have to act
10870 	 * accordingly with regard to resources initialization
10871 	 * and deinitialization
10872 	 */
10873 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10874 		if (i40e_get_capabilities(pf,
10875 					  i40e_aqc_opc_list_func_capabilities))
10876 			goto end_unlock;
10877 
10878 		if (is_recovery_mode_reported) {
10879 			/* we're staying in recovery mode so we'll reinitialize
10880 			 * misc vector here
10881 			 */
10882 			if (i40e_setup_misc_vector_for_recovery_mode(pf))
10883 				goto end_unlock;
10884 		} else {
10885 			if (!lock_acquired)
10886 				rtnl_lock();
10887 			/* we're going out of recovery mode so we'll free
10888 			 * the IRQ allocated specifically for recovery mode
10889 			 * and restore the interrupt scheme
10890 			 */
10891 			free_irq(pf->pdev->irq, pf);
10892 			i40e_clear_interrupt_scheme(pf);
10893 			if (i40e_restore_interrupt_scheme(pf))
10894 				goto end_unlock;
10895 		}
10896 
10897 		/* tell the firmware that we're starting */
10898 		i40e_send_version(pf);
10899 
10900 		/* bail out in case recovery mode was detected, as there is
10901 		 * no need for further configuration.
10902 		 */
10903 		goto end_unlock;
10904 	}
10905 
10906 	i40e_clear_pxe_mode(hw);
10907 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10908 	if (ret)
10909 		goto end_core_reset;
10910 
10911 	ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10912 				hw->func_caps.num_rx_qp, 0, 0);
10913 	if (ret) {
10914 		dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10915 		goto end_core_reset;
10916 	}
10917 	ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10918 	if (ret) {
10919 		dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10920 		goto end_core_reset;
10921 	}
10922 
10923 #ifdef CONFIG_I40E_DCB
10924 	/* Enable FW to write a default DCB config on link-up
10925 	 * unless I40E_FLAG_TC_MQPRIO was enabled or DCB
10926 	 * is not supported with new link speed
10927 	 */
10928 	if (i40e_is_tc_mqprio_enabled(pf)) {
10929 		i40e_aq_set_dcb_parameters(hw, false, NULL);
10930 	} else {
10931 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
10932 		    (hw->phy.link_info.link_speed &
10933 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
10934 			i40e_aq_set_dcb_parameters(hw, false, NULL);
10935 			dev_warn(&pf->pdev->dev,
10936 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
10937 			pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10938 		} else {
10939 			i40e_aq_set_dcb_parameters(hw, true, NULL);
10940 			ret = i40e_init_pf_dcb(pf);
10941 			if (ret) {
10942 				dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n",
10943 					 ret);
10944 				pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10945 				/* Continue without DCB enabled */
10946 			}
10947 		}
10948 	}
10949 
10950 #endif /* CONFIG_I40E_DCB */
10951 	if (!lock_acquired)
10952 		rtnl_lock();
10953 	ret = i40e_setup_pf_switch(pf, reinit, true);
10954 	if (ret)
10955 		goto end_unlock;
10956 
10957 	/* The driver only wants link up/down and module qualification
10958 	 * reports from firmware.  Note the negative logic.
10959 	 */
10960 	ret = i40e_aq_set_phy_int_mask(&pf->hw,
10961 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
10962 					 I40E_AQ_EVENT_MEDIA_NA |
10963 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10964 	if (ret)
10965 		dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
10966 			 ERR_PTR(ret),
10967 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10968 
10969 	/* Rebuild the VSIs and VEBs that existed before reset.
10970 	 * They are still in our local switch element arrays, so only
10971 	 * need to rebuild the switch model in the HW.
10972 	 *
10973 	 * If there were VEBs but the reconstitution failed, we'll try
10974 	 * to recover minimal use by getting the basic PF VSI working.
10975 	 */
10976 	if (vsi->uplink_seid != pf->mac_seid) {
10977 		dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
10978 		/* find the one VEB connected to the MAC, and find orphans */
10979 		for (v = 0; v < I40E_MAX_VEB; v++) {
10980 			if (!pf->veb[v])
10981 				continue;
10982 
10983 			if (pf->veb[v]->uplink_seid == pf->mac_seid ||
10984 			    pf->veb[v]->uplink_seid == 0) {
10985 				ret = i40e_reconstitute_veb(pf->veb[v]);
10986 
10987 				if (!ret)
10988 					continue;
10989 
10990 				/* If Main VEB failed, we're in deep doodoo,
10991 				 * so give up rebuilding the switch and set up
10992 				 * for minimal rebuild of PF VSI.
10993 				 * If orphan failed, we'll report the error
10994 				 * but try to keep going.
10995 				 */
10996 				if (pf->veb[v]->uplink_seid == pf->mac_seid) {
10997 					dev_info(&pf->pdev->dev,
10998 						 "rebuild of switch failed: %d, will try to set up simple PF connection\n",
10999 						 ret);
11000 					vsi->uplink_seid = pf->mac_seid;
11001 					break;
11002 				} else if (pf->veb[v]->uplink_seid == 0) {
11003 					dev_info(&pf->pdev->dev,
11004 						 "rebuild of orphan VEB failed: %d\n",
11005 						 ret);
11006 				}
11007 			}
11008 		}
11009 	}
11010 
11011 	if (vsi->uplink_seid == pf->mac_seid) {
11012 		dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
11013 		/* no VEB, so rebuild only the Main VSI */
11014 		ret = i40e_add_vsi(vsi);
11015 		if (ret) {
11016 			dev_info(&pf->pdev->dev,
11017 				 "rebuild of Main VSI failed: %d\n", ret);
11018 			goto end_unlock;
11019 		}
11020 	}
11021 
11022 	if (vsi->mqprio_qopt.max_rate[0]) {
11023 		u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
11024 						  vsi->mqprio_qopt.max_rate[0]);
11025 		u64 credits = 0;
11026 
11027 		ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
11028 		if (ret)
11029 			goto end_unlock;
11030 
11031 		credits = max_tx_rate;
11032 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
11033 		dev_dbg(&vsi->back->pdev->dev,
11034 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
11035 			max_tx_rate,
11036 			credits,
11037 			vsi->seid);
11038 	}
11039 
11040 	ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
11041 	if (ret)
11042 		goto end_unlock;
11043 
11044 	/* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
11045 	 * for this main VSI if they exist
11046 	 */
11047 	ret = i40e_rebuild_channels(vsi);
11048 	if (ret)
11049 		goto end_unlock;
11050 
11051 	/* Reconfigure hardware for allowing smaller MSS in the case
11052 	 * of TSO, so that we avoid the MDD being fired and causing
11053 	 * a reset in the case of small MSS+TSO.
11054 	 */
11055 #define I40E_REG_MSS          0x000E64DC
11056 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
11057 #define I40E_64BYTE_MSS       0x400000
11058 	val = rd32(hw, I40E_REG_MSS);
11059 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
11060 		val &= ~I40E_REG_MSS_MIN_MASK;
11061 		val |= I40E_64BYTE_MSS;
11062 		wr32(hw, I40E_REG_MSS, val);
11063 	}
11064 
11065 	if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
11066 		msleep(75);
11067 		ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
11068 		if (ret)
11069 			dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
11070 				 ERR_PTR(ret),
11071 				 i40e_aq_str(&pf->hw,
11072 					     pf->hw.aq.asq_last_status));
11073 	}
11074 	/* reinit the misc interrupt */
11075 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11076 		ret = i40e_setup_misc_vector(pf);
11077 		if (ret)
11078 			goto end_unlock;
11079 	}
11080 
11081 	/* Add a filter to drop all Flow control frames from any VSI from being
11082 	 * transmitted. By doing so we stop a malicious VF from sending out
11083 	 * PAUSE or PFC frames and potentially controlling traffic for other
11084 	 * PF/VF VSIs.
11085 	 * The FW can still send Flow control frames if enabled.
11086 	 */
11087 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
11088 						       pf->main_vsi_seid);
11089 
11090 	/* restart the VSIs that were rebuilt and running before the reset */
11091 	i40e_pf_unquiesce_all_vsi(pf);
11092 
11093 	/* Release the RTNL lock before we start resetting VFs */
11094 	if (!lock_acquired)
11095 		rtnl_unlock();
11096 
11097 	/* Restore promiscuous settings */
11098 	ret = i40e_set_promiscuous(pf, pf->cur_promisc);
11099 	if (ret)
11100 		dev_warn(&pf->pdev->dev,
11101 			 "Failed to restore promiscuous setting: %s, err %pe aq_err %s\n",
11102 			 pf->cur_promisc ? "on" : "off",
11103 			 ERR_PTR(ret),
11104 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11105 
11106 	i40e_reset_all_vfs(pf, true);
11107 
11108 	/* tell the firmware that we're starting */
11109 	i40e_send_version(pf);
11110 
11111 	/* We've already released the lock, so don't do it again */
11112 	goto end_core_reset;
11113 
11114 end_unlock:
11115 	if (!lock_acquired)
11116 		rtnl_unlock();
11117 end_core_reset:
11118 	clear_bit(__I40E_RESET_FAILED, pf->state);
11119 clear_recovery:
11120 	clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
11121 	clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
11122 }
11123 
11124 /**
11125  * i40e_reset_and_rebuild - reset and rebuild using a saved config
11126  * @pf: board private structure
11127  * @reinit: if the Main VSI needs to re-initialized.
11128  * @lock_acquired: indicates whether or not the lock has been acquired
11129  * before this function was called.
11130  **/
11131 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
11132 				   bool lock_acquired)
11133 {
11134 	int ret;
11135 
11136 	if (test_bit(__I40E_IN_REMOVE, pf->state))
11137 		return;
11138 	/* Now we wait for GRST to settle out.
11139 	 * We don't have to delete the VEBs or VSIs from the hw switch
11140 	 * because the reset will make them disappear.
11141 	 */
11142 	ret = i40e_reset(pf);
11143 	if (!ret)
11144 		i40e_rebuild(pf, reinit, lock_acquired);
11145 }
11146 
11147 /**
11148  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
11149  * @pf: board private structure
11150  *
11151  * Close up the VFs and other things in prep for a Core Reset,
11152  * then get ready to rebuild the world.
11153  * @lock_acquired: indicates whether or not the lock has been acquired
11154  * before this function was called.
11155  **/
11156 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
11157 {
11158 	i40e_prep_for_reset(pf);
11159 	i40e_reset_and_rebuild(pf, false, lock_acquired);
11160 }
11161 
11162 /**
11163  * i40e_handle_mdd_event
11164  * @pf: pointer to the PF structure
11165  *
11166  * Called from the MDD irq handler to identify possibly malicious vfs
11167  **/
11168 static void i40e_handle_mdd_event(struct i40e_pf *pf)
11169 {
11170 	struct i40e_hw *hw = &pf->hw;
11171 	bool mdd_detected = false;
11172 	struct i40e_vf *vf;
11173 	u32 reg;
11174 	int i;
11175 
11176 	if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
11177 		return;
11178 
11179 	/* find what triggered the MDD event */
11180 	reg = rd32(hw, I40E_GL_MDET_TX);
11181 	if (reg & I40E_GL_MDET_TX_VALID_MASK) {
11182 		u8 pf_num = (reg & I40E_GL_MDET_TX_PF_NUM_MASK) >>
11183 				I40E_GL_MDET_TX_PF_NUM_SHIFT;
11184 		u16 vf_num = (reg & I40E_GL_MDET_TX_VF_NUM_MASK) >>
11185 				I40E_GL_MDET_TX_VF_NUM_SHIFT;
11186 		u8 event = (reg & I40E_GL_MDET_TX_EVENT_MASK) >>
11187 				I40E_GL_MDET_TX_EVENT_SHIFT;
11188 		u16 queue = ((reg & I40E_GL_MDET_TX_QUEUE_MASK) >>
11189 				I40E_GL_MDET_TX_QUEUE_SHIFT) -
11190 				pf->hw.func_caps.base_queue;
11191 		if (netif_msg_tx_err(pf))
11192 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
11193 				 event, queue, pf_num, vf_num);
11194 		wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
11195 		mdd_detected = true;
11196 	}
11197 	reg = rd32(hw, I40E_GL_MDET_RX);
11198 	if (reg & I40E_GL_MDET_RX_VALID_MASK) {
11199 		u8 func = (reg & I40E_GL_MDET_RX_FUNCTION_MASK) >>
11200 				I40E_GL_MDET_RX_FUNCTION_SHIFT;
11201 		u8 event = (reg & I40E_GL_MDET_RX_EVENT_MASK) >>
11202 				I40E_GL_MDET_RX_EVENT_SHIFT;
11203 		u16 queue = ((reg & I40E_GL_MDET_RX_QUEUE_MASK) >>
11204 				I40E_GL_MDET_RX_QUEUE_SHIFT) -
11205 				pf->hw.func_caps.base_queue;
11206 		if (netif_msg_rx_err(pf))
11207 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
11208 				 event, queue, func);
11209 		wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
11210 		mdd_detected = true;
11211 	}
11212 
11213 	if (mdd_detected) {
11214 		reg = rd32(hw, I40E_PF_MDET_TX);
11215 		if (reg & I40E_PF_MDET_TX_VALID_MASK) {
11216 			wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
11217 			dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
11218 		}
11219 		reg = rd32(hw, I40E_PF_MDET_RX);
11220 		if (reg & I40E_PF_MDET_RX_VALID_MASK) {
11221 			wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
11222 			dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
11223 		}
11224 	}
11225 
11226 	/* see if one of the VFs needs its hand slapped */
11227 	for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
11228 		vf = &(pf->vf[i]);
11229 		reg = rd32(hw, I40E_VP_MDET_TX(i));
11230 		if (reg & I40E_VP_MDET_TX_VALID_MASK) {
11231 			wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
11232 			vf->num_mdd_events++;
11233 			dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
11234 				 i);
11235 			dev_info(&pf->pdev->dev,
11236 				 "Use PF Control I/F to re-enable the VF\n");
11237 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11238 		}
11239 
11240 		reg = rd32(hw, I40E_VP_MDET_RX(i));
11241 		if (reg & I40E_VP_MDET_RX_VALID_MASK) {
11242 			wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
11243 			vf->num_mdd_events++;
11244 			dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
11245 				 i);
11246 			dev_info(&pf->pdev->dev,
11247 				 "Use PF Control I/F to re-enable the VF\n");
11248 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11249 		}
11250 	}
11251 
11252 	/* re-enable mdd interrupt cause */
11253 	clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
11254 	reg = rd32(hw, I40E_PFINT_ICR0_ENA);
11255 	reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
11256 	wr32(hw, I40E_PFINT_ICR0_ENA, reg);
11257 	i40e_flush(hw);
11258 }
11259 
11260 /**
11261  * i40e_service_task - Run the driver's async subtasks
11262  * @work: pointer to work_struct containing our data
11263  **/
11264 static void i40e_service_task(struct work_struct *work)
11265 {
11266 	struct i40e_pf *pf = container_of(work,
11267 					  struct i40e_pf,
11268 					  service_task);
11269 	unsigned long start_time = jiffies;
11270 
11271 	/* don't bother with service tasks if a reset is in progress */
11272 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
11273 	    test_bit(__I40E_SUSPENDED, pf->state))
11274 		return;
11275 
11276 	if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
11277 		return;
11278 
11279 	if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
11280 		i40e_detect_recover_hung(pf->vsi[pf->lan_vsi]);
11281 		i40e_sync_filters_subtask(pf);
11282 		i40e_reset_subtask(pf);
11283 		i40e_handle_mdd_event(pf);
11284 		i40e_vc_process_vflr_event(pf);
11285 		i40e_watchdog_subtask(pf);
11286 		i40e_fdir_reinit_subtask(pf);
11287 		if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
11288 			/* Client subtask will reopen next time through. */
11289 			i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi],
11290 							   true);
11291 		} else {
11292 			i40e_client_subtask(pf);
11293 			if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
11294 					       pf->state))
11295 				i40e_notify_client_of_l2_param_changes(
11296 								pf->vsi[pf->lan_vsi]);
11297 		}
11298 		i40e_sync_filters_subtask(pf);
11299 	} else {
11300 		i40e_reset_subtask(pf);
11301 	}
11302 
11303 	i40e_clean_adminq_subtask(pf);
11304 
11305 	/* flush memory to make sure state is correct before next watchdog */
11306 	smp_mb__before_atomic();
11307 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
11308 
11309 	/* If the tasks have taken longer than one timer cycle or there
11310 	 * is more work to be done, reschedule the service task now
11311 	 * rather than wait for the timer to tick again.
11312 	 */
11313 	if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
11314 	    test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)		 ||
11315 	    test_bit(__I40E_MDD_EVENT_PENDING, pf->state)		 ||
11316 	    test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
11317 		i40e_service_event_schedule(pf);
11318 }
11319 
11320 /**
11321  * i40e_service_timer - timer callback
11322  * @t: timer list pointer
11323  **/
11324 static void i40e_service_timer(struct timer_list *t)
11325 {
11326 	struct i40e_pf *pf = from_timer(pf, t, service_timer);
11327 
11328 	mod_timer(&pf->service_timer,
11329 		  round_jiffies(jiffies + pf->service_timer_period));
11330 	i40e_service_event_schedule(pf);
11331 }
11332 
11333 /**
11334  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
11335  * @vsi: the VSI being configured
11336  **/
11337 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
11338 {
11339 	struct i40e_pf *pf = vsi->back;
11340 
11341 	switch (vsi->type) {
11342 	case I40E_VSI_MAIN:
11343 		vsi->alloc_queue_pairs = pf->num_lan_qps;
11344 		if (!vsi->num_tx_desc)
11345 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11346 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11347 		if (!vsi->num_rx_desc)
11348 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11349 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11350 		if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11351 			vsi->num_q_vectors = pf->num_lan_msix;
11352 		else
11353 			vsi->num_q_vectors = 1;
11354 
11355 		break;
11356 
11357 	case I40E_VSI_FDIR:
11358 		vsi->alloc_queue_pairs = 1;
11359 		vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11360 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11361 		vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11362 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11363 		vsi->num_q_vectors = pf->num_fdsb_msix;
11364 		break;
11365 
11366 	case I40E_VSI_VMDQ2:
11367 		vsi->alloc_queue_pairs = pf->num_vmdq_qps;
11368 		if (!vsi->num_tx_desc)
11369 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11370 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11371 		if (!vsi->num_rx_desc)
11372 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11373 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11374 		vsi->num_q_vectors = pf->num_vmdq_msix;
11375 		break;
11376 
11377 	case I40E_VSI_SRIOV:
11378 		vsi->alloc_queue_pairs = pf->num_vf_qps;
11379 		if (!vsi->num_tx_desc)
11380 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11381 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11382 		if (!vsi->num_rx_desc)
11383 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11384 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11385 		break;
11386 
11387 	default:
11388 		WARN_ON(1);
11389 		return -ENODATA;
11390 	}
11391 
11392 	if (is_kdump_kernel()) {
11393 		vsi->num_tx_desc = I40E_MIN_NUM_DESCRIPTORS;
11394 		vsi->num_rx_desc = I40E_MIN_NUM_DESCRIPTORS;
11395 	}
11396 
11397 	return 0;
11398 }
11399 
11400 /**
11401  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
11402  * @vsi: VSI pointer
11403  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
11404  *
11405  * On error: returns error code (negative)
11406  * On success: returns 0
11407  **/
11408 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
11409 {
11410 	struct i40e_ring **next_rings;
11411 	int size;
11412 	int ret = 0;
11413 
11414 	/* allocate memory for both Tx, XDP Tx and Rx ring pointers */
11415 	size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
11416 	       (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
11417 	vsi->tx_rings = kzalloc(size, GFP_KERNEL);
11418 	if (!vsi->tx_rings)
11419 		return -ENOMEM;
11420 	next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
11421 	if (i40e_enabled_xdp_vsi(vsi)) {
11422 		vsi->xdp_rings = next_rings;
11423 		next_rings += vsi->alloc_queue_pairs;
11424 	}
11425 	vsi->rx_rings = next_rings;
11426 
11427 	if (alloc_qvectors) {
11428 		/* allocate memory for q_vector pointers */
11429 		size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
11430 		vsi->q_vectors = kzalloc(size, GFP_KERNEL);
11431 		if (!vsi->q_vectors) {
11432 			ret = -ENOMEM;
11433 			goto err_vectors;
11434 		}
11435 	}
11436 	return ret;
11437 
11438 err_vectors:
11439 	kfree(vsi->tx_rings);
11440 	return ret;
11441 }
11442 
11443 /**
11444  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
11445  * @pf: board private structure
11446  * @type: type of VSI
11447  *
11448  * On error: returns error code (negative)
11449  * On success: returns vsi index in PF (positive)
11450  **/
11451 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
11452 {
11453 	int ret = -ENODEV;
11454 	struct i40e_vsi *vsi;
11455 	int vsi_idx;
11456 	int i;
11457 
11458 	/* Need to protect the allocation of the VSIs at the PF level */
11459 	mutex_lock(&pf->switch_mutex);
11460 
11461 	/* VSI list may be fragmented if VSI creation/destruction has
11462 	 * been happening.  We can afford to do a quick scan to look
11463 	 * for any free VSIs in the list.
11464 	 *
11465 	 * find next empty vsi slot, looping back around if necessary
11466 	 */
11467 	i = pf->next_vsi;
11468 	while (i < pf->num_alloc_vsi && pf->vsi[i])
11469 		i++;
11470 	if (i >= pf->num_alloc_vsi) {
11471 		i = 0;
11472 		while (i < pf->next_vsi && pf->vsi[i])
11473 			i++;
11474 	}
11475 
11476 	if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
11477 		vsi_idx = i;             /* Found one! */
11478 	} else {
11479 		ret = -ENODEV;
11480 		goto unlock_pf;  /* out of VSI slots! */
11481 	}
11482 	pf->next_vsi = ++i;
11483 
11484 	vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
11485 	if (!vsi) {
11486 		ret = -ENOMEM;
11487 		goto unlock_pf;
11488 	}
11489 	vsi->type = type;
11490 	vsi->back = pf;
11491 	set_bit(__I40E_VSI_DOWN, vsi->state);
11492 	vsi->flags = 0;
11493 	vsi->idx = vsi_idx;
11494 	vsi->int_rate_limit = 0;
11495 	vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
11496 				pf->rss_table_size : 64;
11497 	vsi->netdev_registered = false;
11498 	vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
11499 	hash_init(vsi->mac_filter_hash);
11500 	vsi->irqs_ready = false;
11501 
11502 	if (type == I40E_VSI_MAIN) {
11503 		vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
11504 		if (!vsi->af_xdp_zc_qps)
11505 			goto err_rings;
11506 	}
11507 
11508 	ret = i40e_set_num_rings_in_vsi(vsi);
11509 	if (ret)
11510 		goto err_rings;
11511 
11512 	ret = i40e_vsi_alloc_arrays(vsi, true);
11513 	if (ret)
11514 		goto err_rings;
11515 
11516 	/* Setup default MSIX irq handler for VSI */
11517 	i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
11518 
11519 	/* Initialize VSI lock */
11520 	spin_lock_init(&vsi->mac_filter_hash_lock);
11521 	pf->vsi[vsi_idx] = vsi;
11522 	ret = vsi_idx;
11523 	goto unlock_pf;
11524 
11525 err_rings:
11526 	bitmap_free(vsi->af_xdp_zc_qps);
11527 	pf->next_vsi = i - 1;
11528 	kfree(vsi);
11529 unlock_pf:
11530 	mutex_unlock(&pf->switch_mutex);
11531 	return ret;
11532 }
11533 
11534 /**
11535  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
11536  * @vsi: VSI pointer
11537  * @free_qvectors: a bool to specify if q_vectors need to be freed.
11538  *
11539  * On error: returns error code (negative)
11540  * On success: returns 0
11541  **/
11542 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
11543 {
11544 	/* free the ring and vector containers */
11545 	if (free_qvectors) {
11546 		kfree(vsi->q_vectors);
11547 		vsi->q_vectors = NULL;
11548 	}
11549 	kfree(vsi->tx_rings);
11550 	vsi->tx_rings = NULL;
11551 	vsi->rx_rings = NULL;
11552 	vsi->xdp_rings = NULL;
11553 }
11554 
11555 /**
11556  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
11557  * and lookup table
11558  * @vsi: Pointer to VSI structure
11559  */
11560 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
11561 {
11562 	if (!vsi)
11563 		return;
11564 
11565 	kfree(vsi->rss_hkey_user);
11566 	vsi->rss_hkey_user = NULL;
11567 
11568 	kfree(vsi->rss_lut_user);
11569 	vsi->rss_lut_user = NULL;
11570 }
11571 
11572 /**
11573  * i40e_vsi_clear - Deallocate the VSI provided
11574  * @vsi: the VSI being un-configured
11575  **/
11576 static int i40e_vsi_clear(struct i40e_vsi *vsi)
11577 {
11578 	struct i40e_pf *pf;
11579 
11580 	if (!vsi)
11581 		return 0;
11582 
11583 	if (!vsi->back)
11584 		goto free_vsi;
11585 	pf = vsi->back;
11586 
11587 	mutex_lock(&pf->switch_mutex);
11588 	if (!pf->vsi[vsi->idx]) {
11589 		dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
11590 			vsi->idx, vsi->idx, vsi->type);
11591 		goto unlock_vsi;
11592 	}
11593 
11594 	if (pf->vsi[vsi->idx] != vsi) {
11595 		dev_err(&pf->pdev->dev,
11596 			"pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
11597 			pf->vsi[vsi->idx]->idx,
11598 			pf->vsi[vsi->idx]->type,
11599 			vsi->idx, vsi->type);
11600 		goto unlock_vsi;
11601 	}
11602 
11603 	/* updates the PF for this cleared vsi */
11604 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
11605 	i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
11606 
11607 	bitmap_free(vsi->af_xdp_zc_qps);
11608 	i40e_vsi_free_arrays(vsi, true);
11609 	i40e_clear_rss_config_user(vsi);
11610 
11611 	pf->vsi[vsi->idx] = NULL;
11612 	if (vsi->idx < pf->next_vsi)
11613 		pf->next_vsi = vsi->idx;
11614 
11615 unlock_vsi:
11616 	mutex_unlock(&pf->switch_mutex);
11617 free_vsi:
11618 	kfree(vsi);
11619 
11620 	return 0;
11621 }
11622 
11623 /**
11624  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
11625  * @vsi: the VSI being cleaned
11626  **/
11627 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
11628 {
11629 	int i;
11630 
11631 	if (vsi->tx_rings && vsi->tx_rings[0]) {
11632 		for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11633 			kfree_rcu(vsi->tx_rings[i], rcu);
11634 			WRITE_ONCE(vsi->tx_rings[i], NULL);
11635 			WRITE_ONCE(vsi->rx_rings[i], NULL);
11636 			if (vsi->xdp_rings)
11637 				WRITE_ONCE(vsi->xdp_rings[i], NULL);
11638 		}
11639 	}
11640 }
11641 
11642 /**
11643  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
11644  * @vsi: the VSI being configured
11645  **/
11646 static int i40e_alloc_rings(struct i40e_vsi *vsi)
11647 {
11648 	int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
11649 	struct i40e_pf *pf = vsi->back;
11650 	struct i40e_ring *ring;
11651 
11652 	/* Set basic values in the rings to be used later during open() */
11653 	for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11654 		/* allocate space for both Tx and Rx in one shot */
11655 		ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
11656 		if (!ring)
11657 			goto err_out;
11658 
11659 		ring->queue_index = i;
11660 		ring->reg_idx = vsi->base_queue + i;
11661 		ring->ring_active = false;
11662 		ring->vsi = vsi;
11663 		ring->netdev = vsi->netdev;
11664 		ring->dev = &pf->pdev->dev;
11665 		ring->count = vsi->num_tx_desc;
11666 		ring->size = 0;
11667 		ring->dcb_tc = 0;
11668 		if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11669 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11670 		ring->itr_setting = pf->tx_itr_default;
11671 		WRITE_ONCE(vsi->tx_rings[i], ring++);
11672 
11673 		if (!i40e_enabled_xdp_vsi(vsi))
11674 			goto setup_rx;
11675 
11676 		ring->queue_index = vsi->alloc_queue_pairs + i;
11677 		ring->reg_idx = vsi->base_queue + ring->queue_index;
11678 		ring->ring_active = false;
11679 		ring->vsi = vsi;
11680 		ring->netdev = NULL;
11681 		ring->dev = &pf->pdev->dev;
11682 		ring->count = vsi->num_tx_desc;
11683 		ring->size = 0;
11684 		ring->dcb_tc = 0;
11685 		if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11686 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11687 		set_ring_xdp(ring);
11688 		ring->itr_setting = pf->tx_itr_default;
11689 		WRITE_ONCE(vsi->xdp_rings[i], ring++);
11690 
11691 setup_rx:
11692 		ring->queue_index = i;
11693 		ring->reg_idx = vsi->base_queue + i;
11694 		ring->ring_active = false;
11695 		ring->vsi = vsi;
11696 		ring->netdev = vsi->netdev;
11697 		ring->dev = &pf->pdev->dev;
11698 		ring->count = vsi->num_rx_desc;
11699 		ring->size = 0;
11700 		ring->dcb_tc = 0;
11701 		ring->itr_setting = pf->rx_itr_default;
11702 		WRITE_ONCE(vsi->rx_rings[i], ring);
11703 	}
11704 
11705 	return 0;
11706 
11707 err_out:
11708 	i40e_vsi_clear_rings(vsi);
11709 	return -ENOMEM;
11710 }
11711 
11712 /**
11713  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
11714  * @pf: board private structure
11715  * @vectors: the number of MSI-X vectors to request
11716  *
11717  * Returns the number of vectors reserved, or error
11718  **/
11719 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
11720 {
11721 	vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
11722 					I40E_MIN_MSIX, vectors);
11723 	if (vectors < 0) {
11724 		dev_info(&pf->pdev->dev,
11725 			 "MSI-X vector reservation failed: %d\n", vectors);
11726 		vectors = 0;
11727 	}
11728 
11729 	return vectors;
11730 }
11731 
11732 /**
11733  * i40e_init_msix - Setup the MSIX capability
11734  * @pf: board private structure
11735  *
11736  * Work with the OS to set up the MSIX vectors needed.
11737  *
11738  * Returns the number of vectors reserved or negative on failure
11739  **/
11740 static int i40e_init_msix(struct i40e_pf *pf)
11741 {
11742 	struct i40e_hw *hw = &pf->hw;
11743 	int cpus, extra_vectors;
11744 	int vectors_left;
11745 	int v_budget, i;
11746 	int v_actual;
11747 	int iwarp_requested = 0;
11748 
11749 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
11750 		return -ENODEV;
11751 
11752 	/* The number of vectors we'll request will be comprised of:
11753 	 *   - Add 1 for "other" cause for Admin Queue events, etc.
11754 	 *   - The number of LAN queue pairs
11755 	 *	- Queues being used for RSS.
11756 	 *		We don't need as many as max_rss_size vectors.
11757 	 *		use rss_size instead in the calculation since that
11758 	 *		is governed by number of cpus in the system.
11759 	 *	- assumes symmetric Tx/Rx pairing
11760 	 *   - The number of VMDq pairs
11761 	 *   - The CPU count within the NUMA node if iWARP is enabled
11762 	 * Once we count this up, try the request.
11763 	 *
11764 	 * If we can't get what we want, we'll simplify to nearly nothing
11765 	 * and try again.  If that still fails, we punt.
11766 	 */
11767 	vectors_left = hw->func_caps.num_msix_vectors;
11768 	v_budget = 0;
11769 
11770 	/* reserve one vector for miscellaneous handler */
11771 	if (vectors_left) {
11772 		v_budget++;
11773 		vectors_left--;
11774 	}
11775 
11776 	/* reserve some vectors for the main PF traffic queues. Initially we
11777 	 * only reserve at most 50% of the available vectors, in the case that
11778 	 * the number of online CPUs is large. This ensures that we can enable
11779 	 * extra features as well. Once we've enabled the other features, we
11780 	 * will use any remaining vectors to reach as close as we can to the
11781 	 * number of online CPUs.
11782 	 */
11783 	cpus = num_online_cpus();
11784 	pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
11785 	vectors_left -= pf->num_lan_msix;
11786 
11787 	/* reserve one vector for sideband flow director */
11788 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11789 		if (vectors_left) {
11790 			pf->num_fdsb_msix = 1;
11791 			v_budget++;
11792 			vectors_left--;
11793 		} else {
11794 			pf->num_fdsb_msix = 0;
11795 		}
11796 	}
11797 
11798 	/* can we reserve enough for iWARP? */
11799 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11800 		iwarp_requested = pf->num_iwarp_msix;
11801 
11802 		if (!vectors_left)
11803 			pf->num_iwarp_msix = 0;
11804 		else if (vectors_left < pf->num_iwarp_msix)
11805 			pf->num_iwarp_msix = 1;
11806 		v_budget += pf->num_iwarp_msix;
11807 		vectors_left -= pf->num_iwarp_msix;
11808 	}
11809 
11810 	/* any vectors left over go for VMDq support */
11811 	if (pf->flags & I40E_FLAG_VMDQ_ENABLED) {
11812 		if (!vectors_left) {
11813 			pf->num_vmdq_msix = 0;
11814 			pf->num_vmdq_qps = 0;
11815 		} else {
11816 			int vmdq_vecs_wanted =
11817 				pf->num_vmdq_vsis * pf->num_vmdq_qps;
11818 			int vmdq_vecs =
11819 				min_t(int, vectors_left, vmdq_vecs_wanted);
11820 
11821 			/* if we're short on vectors for what's desired, we limit
11822 			 * the queues per vmdq.  If this is still more than are
11823 			 * available, the user will need to change the number of
11824 			 * queues/vectors used by the PF later with the ethtool
11825 			 * channels command
11826 			 */
11827 			if (vectors_left < vmdq_vecs_wanted) {
11828 				pf->num_vmdq_qps = 1;
11829 				vmdq_vecs_wanted = pf->num_vmdq_vsis;
11830 				vmdq_vecs = min_t(int,
11831 						  vectors_left,
11832 						  vmdq_vecs_wanted);
11833 			}
11834 			pf->num_vmdq_msix = pf->num_vmdq_qps;
11835 
11836 			v_budget += vmdq_vecs;
11837 			vectors_left -= vmdq_vecs;
11838 		}
11839 	}
11840 
11841 	/* On systems with a large number of SMP cores, we previously limited
11842 	 * the number of vectors for num_lan_msix to be at most 50% of the
11843 	 * available vectors, to allow for other features. Now, we add back
11844 	 * the remaining vectors. However, we ensure that the total
11845 	 * num_lan_msix will not exceed num_online_cpus(). To do this, we
11846 	 * calculate the number of vectors we can add without going over the
11847 	 * cap of CPUs. For systems with a small number of CPUs this will be
11848 	 * zero.
11849 	 */
11850 	extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11851 	pf->num_lan_msix += extra_vectors;
11852 	vectors_left -= extra_vectors;
11853 
11854 	WARN(vectors_left < 0,
11855 	     "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11856 
11857 	v_budget += pf->num_lan_msix;
11858 	pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
11859 				   GFP_KERNEL);
11860 	if (!pf->msix_entries)
11861 		return -ENOMEM;
11862 
11863 	for (i = 0; i < v_budget; i++)
11864 		pf->msix_entries[i].entry = i;
11865 	v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11866 
11867 	if (v_actual < I40E_MIN_MSIX) {
11868 		pf->flags &= ~I40E_FLAG_MSIX_ENABLED;
11869 		kfree(pf->msix_entries);
11870 		pf->msix_entries = NULL;
11871 		pci_disable_msix(pf->pdev);
11872 		return -ENODEV;
11873 
11874 	} else if (v_actual == I40E_MIN_MSIX) {
11875 		/* Adjust for minimal MSIX use */
11876 		pf->num_vmdq_vsis = 0;
11877 		pf->num_vmdq_qps = 0;
11878 		pf->num_lan_qps = 1;
11879 		pf->num_lan_msix = 1;
11880 
11881 	} else if (v_actual != v_budget) {
11882 		/* If we have limited resources, we will start with no vectors
11883 		 * for the special features and then allocate vectors to some
11884 		 * of these features based on the policy and at the end disable
11885 		 * the features that did not get any vectors.
11886 		 */
11887 		int vec;
11888 
11889 		dev_info(&pf->pdev->dev,
11890 			 "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11891 			 v_actual, v_budget);
11892 		/* reserve the misc vector */
11893 		vec = v_actual - 1;
11894 
11895 		/* Scale vector usage down */
11896 		pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11897 		pf->num_vmdq_vsis = 1;
11898 		pf->num_vmdq_qps = 1;
11899 
11900 		/* partition out the remaining vectors */
11901 		switch (vec) {
11902 		case 2:
11903 			pf->num_lan_msix = 1;
11904 			break;
11905 		case 3:
11906 			if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11907 				pf->num_lan_msix = 1;
11908 				pf->num_iwarp_msix = 1;
11909 			} else {
11910 				pf->num_lan_msix = 2;
11911 			}
11912 			break;
11913 		default:
11914 			if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11915 				pf->num_iwarp_msix = min_t(int, (vec / 3),
11916 						 iwarp_requested);
11917 				pf->num_vmdq_vsis = min_t(int, (vec / 3),
11918 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11919 			} else {
11920 				pf->num_vmdq_vsis = min_t(int, (vec / 2),
11921 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11922 			}
11923 			if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11924 				pf->num_fdsb_msix = 1;
11925 				vec--;
11926 			}
11927 			pf->num_lan_msix = min_t(int,
11928 			       (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
11929 							      pf->num_lan_msix);
11930 			pf->num_lan_qps = pf->num_lan_msix;
11931 			break;
11932 		}
11933 	}
11934 
11935 	if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
11936 	    (pf->num_fdsb_msix == 0)) {
11937 		dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
11938 		pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
11939 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11940 	}
11941 	if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
11942 	    (pf->num_vmdq_msix == 0)) {
11943 		dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
11944 		pf->flags &= ~I40E_FLAG_VMDQ_ENABLED;
11945 	}
11946 
11947 	if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
11948 	    (pf->num_iwarp_msix == 0)) {
11949 		dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
11950 		pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
11951 	}
11952 	i40e_debug(&pf->hw, I40E_DEBUG_INIT,
11953 		   "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
11954 		   pf->num_lan_msix,
11955 		   pf->num_vmdq_msix * pf->num_vmdq_vsis,
11956 		   pf->num_fdsb_msix,
11957 		   pf->num_iwarp_msix);
11958 
11959 	return v_actual;
11960 }
11961 
11962 /**
11963  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
11964  * @vsi: the VSI being configured
11965  * @v_idx: index of the vector in the vsi struct
11966  *
11967  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
11968  **/
11969 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx)
11970 {
11971 	struct i40e_q_vector *q_vector;
11972 
11973 	/* allocate q_vector */
11974 	q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
11975 	if (!q_vector)
11976 		return -ENOMEM;
11977 
11978 	q_vector->vsi = vsi;
11979 	q_vector->v_idx = v_idx;
11980 	cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
11981 
11982 	if (vsi->netdev)
11983 		netif_napi_add(vsi->netdev, &q_vector->napi, i40e_napi_poll);
11984 
11985 	/* tie q_vector and vsi together */
11986 	vsi->q_vectors[v_idx] = q_vector;
11987 
11988 	return 0;
11989 }
11990 
11991 /**
11992  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
11993  * @vsi: the VSI being configured
11994  *
11995  * We allocate one q_vector per queue interrupt.  If allocation fails we
11996  * return -ENOMEM.
11997  **/
11998 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
11999 {
12000 	struct i40e_pf *pf = vsi->back;
12001 	int err, v_idx, num_q_vectors;
12002 
12003 	/* if not MSIX, give the one vector only to the LAN VSI */
12004 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
12005 		num_q_vectors = vsi->num_q_vectors;
12006 	else if (vsi == pf->vsi[pf->lan_vsi])
12007 		num_q_vectors = 1;
12008 	else
12009 		return -EINVAL;
12010 
12011 	for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
12012 		err = i40e_vsi_alloc_q_vector(vsi, v_idx);
12013 		if (err)
12014 			goto err_out;
12015 	}
12016 
12017 	return 0;
12018 
12019 err_out:
12020 	while (v_idx--)
12021 		i40e_free_q_vector(vsi, v_idx);
12022 
12023 	return err;
12024 }
12025 
12026 /**
12027  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
12028  * @pf: board private structure to initialize
12029  **/
12030 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
12031 {
12032 	int vectors = 0;
12033 	ssize_t size;
12034 
12035 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
12036 		vectors = i40e_init_msix(pf);
12037 		if (vectors < 0) {
12038 			pf->flags &= ~(I40E_FLAG_MSIX_ENABLED	|
12039 				       I40E_FLAG_IWARP_ENABLED	|
12040 				       I40E_FLAG_RSS_ENABLED	|
12041 				       I40E_FLAG_DCB_CAPABLE	|
12042 				       I40E_FLAG_DCB_ENABLED	|
12043 				       I40E_FLAG_SRIOV_ENABLED	|
12044 				       I40E_FLAG_FD_SB_ENABLED	|
12045 				       I40E_FLAG_FD_ATR_ENABLED	|
12046 				       I40E_FLAG_VMDQ_ENABLED);
12047 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
12048 
12049 			/* rework the queue expectations without MSIX */
12050 			i40e_determine_queue_usage(pf);
12051 		}
12052 	}
12053 
12054 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED) &&
12055 	    (pf->flags & I40E_FLAG_MSI_ENABLED)) {
12056 		dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
12057 		vectors = pci_enable_msi(pf->pdev);
12058 		if (vectors < 0) {
12059 			dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
12060 				 vectors);
12061 			pf->flags &= ~I40E_FLAG_MSI_ENABLED;
12062 		}
12063 		vectors = 1;  /* one MSI or Legacy vector */
12064 	}
12065 
12066 	if (!(pf->flags & (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED)))
12067 		dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
12068 
12069 	/* set up vector assignment tracking */
12070 	size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
12071 	pf->irq_pile = kzalloc(size, GFP_KERNEL);
12072 	if (!pf->irq_pile)
12073 		return -ENOMEM;
12074 
12075 	pf->irq_pile->num_entries = vectors;
12076 
12077 	/* track first vector for misc interrupts, ignore return */
12078 	(void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
12079 
12080 	return 0;
12081 }
12082 
12083 /**
12084  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
12085  * @pf: private board data structure
12086  *
12087  * Restore the interrupt scheme that was cleared when we suspended the
12088  * device. This should be called during resume to re-allocate the q_vectors
12089  * and reacquire IRQs.
12090  */
12091 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
12092 {
12093 	int err, i;
12094 
12095 	/* We cleared the MSI and MSI-X flags when disabling the old interrupt
12096 	 * scheme. We need to re-enabled them here in order to attempt to
12097 	 * re-acquire the MSI or MSI-X vectors
12098 	 */
12099 	pf->flags |= (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
12100 
12101 	err = i40e_init_interrupt_scheme(pf);
12102 	if (err)
12103 		return err;
12104 
12105 	/* Now that we've re-acquired IRQs, we need to remap the vectors and
12106 	 * rings together again.
12107 	 */
12108 	for (i = 0; i < pf->num_alloc_vsi; i++) {
12109 		if (pf->vsi[i]) {
12110 			err = i40e_vsi_alloc_q_vectors(pf->vsi[i]);
12111 			if (err)
12112 				goto err_unwind;
12113 			i40e_vsi_map_rings_to_vectors(pf->vsi[i]);
12114 		}
12115 	}
12116 
12117 	err = i40e_setup_misc_vector(pf);
12118 	if (err)
12119 		goto err_unwind;
12120 
12121 	if (pf->flags & I40E_FLAG_IWARP_ENABLED)
12122 		i40e_client_update_msix_info(pf);
12123 
12124 	return 0;
12125 
12126 err_unwind:
12127 	while (i--) {
12128 		if (pf->vsi[i])
12129 			i40e_vsi_free_q_vectors(pf->vsi[i]);
12130 	}
12131 
12132 	return err;
12133 }
12134 
12135 /**
12136  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
12137  * non queue events in recovery mode
12138  * @pf: board private structure
12139  *
12140  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
12141  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
12142  * This is handled differently than in recovery mode since no Tx/Rx resources
12143  * are being allocated.
12144  **/
12145 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
12146 {
12147 	int err;
12148 
12149 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
12150 		err = i40e_setup_misc_vector(pf);
12151 
12152 		if (err) {
12153 			dev_info(&pf->pdev->dev,
12154 				 "MSI-X misc vector request failed, error %d\n",
12155 				 err);
12156 			return err;
12157 		}
12158 	} else {
12159 		u32 flags = pf->flags & I40E_FLAG_MSI_ENABLED ? 0 : IRQF_SHARED;
12160 
12161 		err = request_irq(pf->pdev->irq, i40e_intr, flags,
12162 				  pf->int_name, pf);
12163 
12164 		if (err) {
12165 			dev_info(&pf->pdev->dev,
12166 				 "MSI/legacy misc vector request failed, error %d\n",
12167 				 err);
12168 			return err;
12169 		}
12170 		i40e_enable_misc_int_causes(pf);
12171 		i40e_irq_dynamic_enable_icr0(pf);
12172 	}
12173 
12174 	return 0;
12175 }
12176 
12177 /**
12178  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
12179  * @pf: board private structure
12180  *
12181  * This sets up the handler for MSIX 0, which is used to manage the
12182  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
12183  * when in MSI or Legacy interrupt mode.
12184  **/
12185 static int i40e_setup_misc_vector(struct i40e_pf *pf)
12186 {
12187 	struct i40e_hw *hw = &pf->hw;
12188 	int err = 0;
12189 
12190 	/* Only request the IRQ once, the first time through. */
12191 	if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
12192 		err = request_irq(pf->msix_entries[0].vector,
12193 				  i40e_intr, 0, pf->int_name, pf);
12194 		if (err) {
12195 			clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
12196 			dev_info(&pf->pdev->dev,
12197 				 "request_irq for %s failed: %d\n",
12198 				 pf->int_name, err);
12199 			return -EFAULT;
12200 		}
12201 	}
12202 
12203 	i40e_enable_misc_int_causes(pf);
12204 
12205 	/* associate no queues to the misc vector */
12206 	wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
12207 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K >> 1);
12208 
12209 	i40e_flush(hw);
12210 
12211 	i40e_irq_dynamic_enable_icr0(pf);
12212 
12213 	return err;
12214 }
12215 
12216 /**
12217  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
12218  * @vsi: Pointer to vsi structure
12219  * @seed: Buffter to store the hash keys
12220  * @lut: Buffer to store the lookup table entries
12221  * @lut_size: Size of buffer to store the lookup table entries
12222  *
12223  * Return 0 on success, negative on failure
12224  */
12225 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
12226 			   u8 *lut, u16 lut_size)
12227 {
12228 	struct i40e_pf *pf = vsi->back;
12229 	struct i40e_hw *hw = &pf->hw;
12230 	int ret = 0;
12231 
12232 	if (seed) {
12233 		ret = i40e_aq_get_rss_key(hw, vsi->id,
12234 			(struct i40e_aqc_get_set_rss_key_data *)seed);
12235 		if (ret) {
12236 			dev_info(&pf->pdev->dev,
12237 				 "Cannot get RSS key, err %pe aq_err %s\n",
12238 				 ERR_PTR(ret),
12239 				 i40e_aq_str(&pf->hw,
12240 					     pf->hw.aq.asq_last_status));
12241 			return ret;
12242 		}
12243 	}
12244 
12245 	if (lut) {
12246 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
12247 
12248 		ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
12249 		if (ret) {
12250 			dev_info(&pf->pdev->dev,
12251 				 "Cannot get RSS lut, err %pe aq_err %s\n",
12252 				 ERR_PTR(ret),
12253 				 i40e_aq_str(&pf->hw,
12254 					     pf->hw.aq.asq_last_status));
12255 			return ret;
12256 		}
12257 	}
12258 
12259 	return ret;
12260 }
12261 
12262 /**
12263  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
12264  * @vsi: Pointer to vsi structure
12265  * @seed: RSS hash seed
12266  * @lut: Lookup table
12267  * @lut_size: Lookup table size
12268  *
12269  * Returns 0 on success, negative on failure
12270  **/
12271 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
12272 			       const u8 *lut, u16 lut_size)
12273 {
12274 	struct i40e_pf *pf = vsi->back;
12275 	struct i40e_hw *hw = &pf->hw;
12276 	u16 vf_id = vsi->vf_id;
12277 	u8 i;
12278 
12279 	/* Fill out hash function seed */
12280 	if (seed) {
12281 		u32 *seed_dw = (u32 *)seed;
12282 
12283 		if (vsi->type == I40E_VSI_MAIN) {
12284 			for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12285 				wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
12286 		} else if (vsi->type == I40E_VSI_SRIOV) {
12287 			for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
12288 				wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
12289 		} else {
12290 			dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
12291 		}
12292 	}
12293 
12294 	if (lut) {
12295 		u32 *lut_dw = (u32 *)lut;
12296 
12297 		if (vsi->type == I40E_VSI_MAIN) {
12298 			if (lut_size != I40E_HLUT_ARRAY_SIZE)
12299 				return -EINVAL;
12300 			for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12301 				wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
12302 		} else if (vsi->type == I40E_VSI_SRIOV) {
12303 			if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
12304 				return -EINVAL;
12305 			for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12306 				wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
12307 		} else {
12308 			dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12309 		}
12310 	}
12311 	i40e_flush(hw);
12312 
12313 	return 0;
12314 }
12315 
12316 /**
12317  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
12318  * @vsi: Pointer to VSI structure
12319  * @seed: Buffer to store the keys
12320  * @lut: Buffer to store the lookup table entries
12321  * @lut_size: Size of buffer to store the lookup table entries
12322  *
12323  * Returns 0 on success, negative on failure
12324  */
12325 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
12326 			    u8 *lut, u16 lut_size)
12327 {
12328 	struct i40e_pf *pf = vsi->back;
12329 	struct i40e_hw *hw = &pf->hw;
12330 	u16 i;
12331 
12332 	if (seed) {
12333 		u32 *seed_dw = (u32 *)seed;
12334 
12335 		for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12336 			seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
12337 	}
12338 	if (lut) {
12339 		u32 *lut_dw = (u32 *)lut;
12340 
12341 		if (lut_size != I40E_HLUT_ARRAY_SIZE)
12342 			return -EINVAL;
12343 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12344 			lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
12345 	}
12346 
12347 	return 0;
12348 }
12349 
12350 /**
12351  * i40e_config_rss - Configure RSS keys and lut
12352  * @vsi: Pointer to VSI structure
12353  * @seed: RSS hash seed
12354  * @lut: Lookup table
12355  * @lut_size: Lookup table size
12356  *
12357  * Returns 0 on success, negative on failure
12358  */
12359 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12360 {
12361 	struct i40e_pf *pf = vsi->back;
12362 
12363 	if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12364 		return i40e_config_rss_aq(vsi, seed, lut, lut_size);
12365 	else
12366 		return i40e_config_rss_reg(vsi, seed, lut, lut_size);
12367 }
12368 
12369 /**
12370  * i40e_get_rss - Get RSS keys and lut
12371  * @vsi: Pointer to VSI structure
12372  * @seed: Buffer to store the keys
12373  * @lut: Buffer to store the lookup table entries
12374  * @lut_size: Size of buffer to store the lookup table entries
12375  *
12376  * Returns 0 on success, negative on failure
12377  */
12378 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12379 {
12380 	struct i40e_pf *pf = vsi->back;
12381 
12382 	if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12383 		return i40e_get_rss_aq(vsi, seed, lut, lut_size);
12384 	else
12385 		return i40e_get_rss_reg(vsi, seed, lut, lut_size);
12386 }
12387 
12388 /**
12389  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
12390  * @pf: Pointer to board private structure
12391  * @lut: Lookup table
12392  * @rss_table_size: Lookup table size
12393  * @rss_size: Range of queue number for hashing
12394  */
12395 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
12396 		       u16 rss_table_size, u16 rss_size)
12397 {
12398 	u16 i;
12399 
12400 	for (i = 0; i < rss_table_size; i++)
12401 		lut[i] = i % rss_size;
12402 }
12403 
12404 /**
12405  * i40e_pf_config_rss - Prepare for RSS if used
12406  * @pf: board private structure
12407  **/
12408 static int i40e_pf_config_rss(struct i40e_pf *pf)
12409 {
12410 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12411 	u8 seed[I40E_HKEY_ARRAY_SIZE];
12412 	u8 *lut;
12413 	struct i40e_hw *hw = &pf->hw;
12414 	u32 reg_val;
12415 	u64 hena;
12416 	int ret;
12417 
12418 	/* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
12419 	hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
12420 		((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
12421 	hena |= i40e_pf_get_default_rss_hena(pf);
12422 
12423 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
12424 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
12425 
12426 	/* Determine the RSS table size based on the hardware capabilities */
12427 	reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
12428 	reg_val = (pf->rss_table_size == 512) ?
12429 			(reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
12430 			(reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
12431 	i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
12432 
12433 	/* Determine the RSS size of the VSI */
12434 	if (!vsi->rss_size) {
12435 		u16 qcount;
12436 		/* If the firmware does something weird during VSI init, we
12437 		 * could end up with zero TCs. Check for that to avoid
12438 		 * divide-by-zero. It probably won't pass traffic, but it also
12439 		 * won't panic.
12440 		 */
12441 		qcount = vsi->num_queue_pairs /
12442 			 (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
12443 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12444 	}
12445 	if (!vsi->rss_size)
12446 		return -EINVAL;
12447 
12448 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
12449 	if (!lut)
12450 		return -ENOMEM;
12451 
12452 	/* Use user configured lut if there is one, otherwise use default */
12453 	if (vsi->rss_lut_user)
12454 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
12455 	else
12456 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
12457 
12458 	/* Use user configured hash key if there is one, otherwise
12459 	 * use default.
12460 	 */
12461 	if (vsi->rss_hkey_user)
12462 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
12463 	else
12464 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
12465 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
12466 	kfree(lut);
12467 
12468 	return ret;
12469 }
12470 
12471 /**
12472  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
12473  * @pf: board private structure
12474  * @queue_count: the requested queue count for rss.
12475  *
12476  * returns 0 if rss is not enabled, if enabled returns the final rss queue
12477  * count which may be different from the requested queue count.
12478  * Note: expects to be called while under rtnl_lock()
12479  **/
12480 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
12481 {
12482 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12483 	int new_rss_size;
12484 
12485 	if (!(pf->flags & I40E_FLAG_RSS_ENABLED))
12486 		return 0;
12487 
12488 	queue_count = min_t(int, queue_count, num_online_cpus());
12489 	new_rss_size = min_t(int, queue_count, pf->rss_size_max);
12490 
12491 	if (queue_count != vsi->num_queue_pairs) {
12492 		u16 qcount;
12493 
12494 		vsi->req_queue_pairs = queue_count;
12495 		i40e_prep_for_reset(pf);
12496 		if (test_bit(__I40E_IN_REMOVE, pf->state))
12497 			return pf->alloc_rss_size;
12498 
12499 		pf->alloc_rss_size = new_rss_size;
12500 
12501 		i40e_reset_and_rebuild(pf, true, true);
12502 
12503 		/* Discard the user configured hash keys and lut, if less
12504 		 * queues are enabled.
12505 		 */
12506 		if (queue_count < vsi->rss_size) {
12507 			i40e_clear_rss_config_user(vsi);
12508 			dev_dbg(&pf->pdev->dev,
12509 				"discard user configured hash keys and lut\n");
12510 		}
12511 
12512 		/* Reset vsi->rss_size, as number of enabled queues changed */
12513 		qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
12514 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12515 
12516 		i40e_pf_config_rss(pf);
12517 	}
12518 	dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
12519 		 vsi->req_queue_pairs, pf->rss_size_max);
12520 	return pf->alloc_rss_size;
12521 }
12522 
12523 /**
12524  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
12525  * @pf: board private structure
12526  **/
12527 int i40e_get_partition_bw_setting(struct i40e_pf *pf)
12528 {
12529 	bool min_valid, max_valid;
12530 	u32 max_bw, min_bw;
12531 	int status;
12532 
12533 	status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
12534 					   &min_valid, &max_valid);
12535 
12536 	if (!status) {
12537 		if (min_valid)
12538 			pf->min_bw = min_bw;
12539 		if (max_valid)
12540 			pf->max_bw = max_bw;
12541 	}
12542 
12543 	return status;
12544 }
12545 
12546 /**
12547  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
12548  * @pf: board private structure
12549  **/
12550 int i40e_set_partition_bw_setting(struct i40e_pf *pf)
12551 {
12552 	struct i40e_aqc_configure_partition_bw_data bw_data;
12553 	int status;
12554 
12555 	memset(&bw_data, 0, sizeof(bw_data));
12556 
12557 	/* Set the valid bit for this PF */
12558 	bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
12559 	bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
12560 	bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
12561 
12562 	/* Set the new bandwidths */
12563 	status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
12564 
12565 	return status;
12566 }
12567 
12568 /**
12569  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
12570  * @pf: board private structure
12571  **/
12572 int i40e_commit_partition_bw_setting(struct i40e_pf *pf)
12573 {
12574 	/* Commit temporary BW setting to permanent NVM image */
12575 	enum i40e_admin_queue_err last_aq_status;
12576 	u16 nvm_word;
12577 	int ret;
12578 
12579 	if (pf->hw.partition_id != 1) {
12580 		dev_info(&pf->pdev->dev,
12581 			 "Commit BW only works on partition 1! This is partition %d",
12582 			 pf->hw.partition_id);
12583 		ret = I40E_NOT_SUPPORTED;
12584 		goto bw_commit_out;
12585 	}
12586 
12587 	/* Acquire NVM for read access */
12588 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
12589 	last_aq_status = pf->hw.aq.asq_last_status;
12590 	if (ret) {
12591 		dev_info(&pf->pdev->dev,
12592 			 "Cannot acquire NVM for read access, err %pe aq_err %s\n",
12593 			 ERR_PTR(ret),
12594 			 i40e_aq_str(&pf->hw, last_aq_status));
12595 		goto bw_commit_out;
12596 	}
12597 
12598 	/* Read word 0x10 of NVM - SW compatibility word 1 */
12599 	ret = i40e_aq_read_nvm(&pf->hw,
12600 			       I40E_SR_NVM_CONTROL_WORD,
12601 			       0x10, sizeof(nvm_word), &nvm_word,
12602 			       false, NULL);
12603 	/* Save off last admin queue command status before releasing
12604 	 * the NVM
12605 	 */
12606 	last_aq_status = pf->hw.aq.asq_last_status;
12607 	i40e_release_nvm(&pf->hw);
12608 	if (ret) {
12609 		dev_info(&pf->pdev->dev, "NVM read error, err %pe aq_err %s\n",
12610 			 ERR_PTR(ret),
12611 			 i40e_aq_str(&pf->hw, last_aq_status));
12612 		goto bw_commit_out;
12613 	}
12614 
12615 	/* Wait a bit for NVM release to complete */
12616 	msleep(50);
12617 
12618 	/* Acquire NVM for write access */
12619 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
12620 	last_aq_status = pf->hw.aq.asq_last_status;
12621 	if (ret) {
12622 		dev_info(&pf->pdev->dev,
12623 			 "Cannot acquire NVM for write access, err %pe aq_err %s\n",
12624 			 ERR_PTR(ret),
12625 			 i40e_aq_str(&pf->hw, last_aq_status));
12626 		goto bw_commit_out;
12627 	}
12628 	/* Write it back out unchanged to initiate update NVM,
12629 	 * which will force a write of the shadow (alt) RAM to
12630 	 * the NVM - thus storing the bandwidth values permanently.
12631 	 */
12632 	ret = i40e_aq_update_nvm(&pf->hw,
12633 				 I40E_SR_NVM_CONTROL_WORD,
12634 				 0x10, sizeof(nvm_word),
12635 				 &nvm_word, true, 0, NULL);
12636 	/* Save off last admin queue command status before releasing
12637 	 * the NVM
12638 	 */
12639 	last_aq_status = pf->hw.aq.asq_last_status;
12640 	i40e_release_nvm(&pf->hw);
12641 	if (ret)
12642 		dev_info(&pf->pdev->dev,
12643 			 "BW settings NOT SAVED, err %pe aq_err %s\n",
12644 			 ERR_PTR(ret),
12645 			 i40e_aq_str(&pf->hw, last_aq_status));
12646 bw_commit_out:
12647 
12648 	return ret;
12649 }
12650 
12651 /**
12652  * i40e_is_total_port_shutdown_enabled - read NVM and return value
12653  * if total port shutdown feature is enabled for this PF
12654  * @pf: board private structure
12655  **/
12656 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf)
12657 {
12658 #define I40E_TOTAL_PORT_SHUTDOWN_ENABLED	BIT(4)
12659 #define I40E_FEATURES_ENABLE_PTR		0x2A
12660 #define I40E_CURRENT_SETTING_PTR		0x2B
12661 #define I40E_LINK_BEHAVIOR_WORD_OFFSET		0x2D
12662 #define I40E_LINK_BEHAVIOR_WORD_LENGTH		0x1
12663 #define I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED	BIT(0)
12664 #define I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH	4
12665 	int read_status = I40E_SUCCESS;
12666 	u16 sr_emp_sr_settings_ptr = 0;
12667 	u16 features_enable = 0;
12668 	u16 link_behavior = 0;
12669 	bool ret = false;
12670 
12671 	read_status = i40e_read_nvm_word(&pf->hw,
12672 					 I40E_SR_EMP_SR_SETTINGS_PTR,
12673 					 &sr_emp_sr_settings_ptr);
12674 	if (read_status)
12675 		goto err_nvm;
12676 	read_status = i40e_read_nvm_word(&pf->hw,
12677 					 sr_emp_sr_settings_ptr +
12678 					 I40E_FEATURES_ENABLE_PTR,
12679 					 &features_enable);
12680 	if (read_status)
12681 		goto err_nvm;
12682 	if (I40E_TOTAL_PORT_SHUTDOWN_ENABLED & features_enable) {
12683 		read_status = i40e_read_nvm_module_data(&pf->hw,
12684 							I40E_SR_EMP_SR_SETTINGS_PTR,
12685 							I40E_CURRENT_SETTING_PTR,
12686 							I40E_LINK_BEHAVIOR_WORD_OFFSET,
12687 							I40E_LINK_BEHAVIOR_WORD_LENGTH,
12688 							&link_behavior);
12689 		if (read_status)
12690 			goto err_nvm;
12691 		link_behavior >>= (pf->hw.port * I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH);
12692 		ret = I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED & link_behavior;
12693 	}
12694 	return ret;
12695 
12696 err_nvm:
12697 	dev_warn(&pf->pdev->dev,
12698 		 "total-port-shutdown feature is off due to read nvm error: %pe\n",
12699 		 ERR_PTR(read_status));
12700 	return ret;
12701 }
12702 
12703 /**
12704  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
12705  * @pf: board private structure to initialize
12706  *
12707  * i40e_sw_init initializes the Adapter private data structure.
12708  * Fields are initialized based on PCI device information and
12709  * OS network device settings (MTU size).
12710  **/
12711 static int i40e_sw_init(struct i40e_pf *pf)
12712 {
12713 	int err = 0;
12714 	int size;
12715 	u16 pow;
12716 
12717 	/* Set default capability flags */
12718 	pf->flags = I40E_FLAG_RX_CSUM_ENABLED |
12719 		    I40E_FLAG_MSI_ENABLED     |
12720 		    I40E_FLAG_MSIX_ENABLED;
12721 
12722 	/* Set default ITR */
12723 	pf->rx_itr_default = I40E_ITR_RX_DEF;
12724 	pf->tx_itr_default = I40E_ITR_TX_DEF;
12725 
12726 	/* Depending on PF configurations, it is possible that the RSS
12727 	 * maximum might end up larger than the available queues
12728 	 */
12729 	pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
12730 	pf->alloc_rss_size = 1;
12731 	pf->rss_table_size = pf->hw.func_caps.rss_table_size;
12732 	pf->rss_size_max = min_t(int, pf->rss_size_max,
12733 				 pf->hw.func_caps.num_tx_qp);
12734 
12735 	/* find the next higher power-of-2 of num cpus */
12736 	pow = roundup_pow_of_two(num_online_cpus());
12737 	pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
12738 
12739 	if (pf->hw.func_caps.rss) {
12740 		pf->flags |= I40E_FLAG_RSS_ENABLED;
12741 		pf->alloc_rss_size = min_t(int, pf->rss_size_max,
12742 					   num_online_cpus());
12743 	}
12744 
12745 	/* MFP mode enabled */
12746 	if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
12747 		pf->flags |= I40E_FLAG_MFP_ENABLED;
12748 		dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
12749 		if (i40e_get_partition_bw_setting(pf)) {
12750 			dev_warn(&pf->pdev->dev,
12751 				 "Could not get partition bw settings\n");
12752 		} else {
12753 			dev_info(&pf->pdev->dev,
12754 				 "Partition BW Min = %8.8x, Max = %8.8x\n",
12755 				 pf->min_bw, pf->max_bw);
12756 
12757 			/* nudge the Tx scheduler */
12758 			i40e_set_partition_bw_setting(pf);
12759 		}
12760 	}
12761 
12762 	if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
12763 	    (pf->hw.func_caps.fd_filters_best_effort > 0)) {
12764 		pf->flags |= I40E_FLAG_FD_ATR_ENABLED;
12765 		pf->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
12766 		if (pf->flags & I40E_FLAG_MFP_ENABLED &&
12767 		    pf->hw.num_partitions > 1)
12768 			dev_info(&pf->pdev->dev,
12769 				 "Flow Director Sideband mode Disabled in MFP mode\n");
12770 		else
12771 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12772 		pf->fdir_pf_filter_count =
12773 				 pf->hw.func_caps.fd_filters_guaranteed;
12774 		pf->hw.fdir_shared_filter_count =
12775 				 pf->hw.func_caps.fd_filters_best_effort;
12776 	}
12777 
12778 	if (pf->hw.mac.type == I40E_MAC_X722) {
12779 		pf->hw_features |= (I40E_HW_RSS_AQ_CAPABLE |
12780 				    I40E_HW_128_QP_RSS_CAPABLE |
12781 				    I40E_HW_ATR_EVICT_CAPABLE |
12782 				    I40E_HW_WB_ON_ITR_CAPABLE |
12783 				    I40E_HW_MULTIPLE_TCP_UDP_RSS_PCTYPE |
12784 				    I40E_HW_NO_PCI_LINK_CHECK |
12785 				    I40E_HW_USE_SET_LLDP_MIB |
12786 				    I40E_HW_GENEVE_OFFLOAD_CAPABLE |
12787 				    I40E_HW_PTP_L4_CAPABLE |
12788 				    I40E_HW_WOL_MC_MAGIC_PKT_WAKE |
12789 				    I40E_HW_OUTER_UDP_CSUM_CAPABLE);
12790 
12791 #define I40E_FDEVICT_PCTYPE_DEFAULT 0xc03
12792 		if (rd32(&pf->hw, I40E_GLQF_FDEVICTENA(1)) !=
12793 		    I40E_FDEVICT_PCTYPE_DEFAULT) {
12794 			dev_warn(&pf->pdev->dev,
12795 				 "FD EVICT PCTYPES are not right, disable FD HW EVICT\n");
12796 			pf->hw_features &= ~I40E_HW_ATR_EVICT_CAPABLE;
12797 		}
12798 	} else if ((pf->hw.aq.api_maj_ver > 1) ||
12799 		   ((pf->hw.aq.api_maj_ver == 1) &&
12800 		    (pf->hw.aq.api_min_ver > 4))) {
12801 		/* Supported in FW API version higher than 1.4 */
12802 		pf->hw_features |= I40E_HW_GENEVE_OFFLOAD_CAPABLE;
12803 	}
12804 
12805 	/* Enable HW ATR eviction if possible */
12806 	if (pf->hw_features & I40E_HW_ATR_EVICT_CAPABLE)
12807 		pf->flags |= I40E_FLAG_HW_ATR_EVICT_ENABLED;
12808 
12809 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12810 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 33)) ||
12811 	    (pf->hw.aq.fw_maj_ver < 4))) {
12812 		pf->hw_features |= I40E_HW_RESTART_AUTONEG;
12813 		/* No DCB support  for FW < v4.33 */
12814 		pf->hw_features |= I40E_HW_NO_DCB_SUPPORT;
12815 	}
12816 
12817 	/* Disable FW LLDP if FW < v4.3 */
12818 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12819 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 3)) ||
12820 	    (pf->hw.aq.fw_maj_ver < 4)))
12821 		pf->hw_features |= I40E_HW_STOP_FW_LLDP;
12822 
12823 	/* Use the FW Set LLDP MIB API if FW > v4.40 */
12824 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12825 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver >= 40)) ||
12826 	    (pf->hw.aq.fw_maj_ver >= 5)))
12827 		pf->hw_features |= I40E_HW_USE_SET_LLDP_MIB;
12828 
12829 	/* Enable PTP L4 if FW > v6.0 */
12830 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
12831 	    pf->hw.aq.fw_maj_ver >= 6)
12832 		pf->hw_features |= I40E_HW_PTP_L4_CAPABLE;
12833 
12834 	if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
12835 		pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
12836 		pf->flags |= I40E_FLAG_VMDQ_ENABLED;
12837 		pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
12838 	}
12839 
12840 	if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
12841 		pf->flags |= I40E_FLAG_IWARP_ENABLED;
12842 		/* IWARP needs one extra vector for CQP just like MISC.*/
12843 		pf->num_iwarp_msix = (int)num_online_cpus() + 1;
12844 	}
12845 	/* Stopping FW LLDP engine is supported on XL710 and X722
12846 	 * starting from FW versions determined in i40e_init_adminq.
12847 	 * Stopping the FW LLDP engine is not supported on XL710
12848 	 * if NPAR is functioning so unset this hw flag in this case.
12849 	 */
12850 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
12851 	    pf->hw.func_caps.npar_enable &&
12852 	    (pf->hw.flags & I40E_HW_FLAG_FW_LLDP_STOPPABLE))
12853 		pf->hw.flags &= ~I40E_HW_FLAG_FW_LLDP_STOPPABLE;
12854 
12855 #ifdef CONFIG_PCI_IOV
12856 	if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
12857 		pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
12858 		pf->flags |= I40E_FLAG_SRIOV_ENABLED;
12859 		pf->num_req_vfs = min_t(int,
12860 					pf->hw.func_caps.num_vfs,
12861 					I40E_MAX_VF_COUNT);
12862 	}
12863 #endif /* CONFIG_PCI_IOV */
12864 	pf->eeprom_version = 0xDEAD;
12865 	pf->lan_veb = I40E_NO_VEB;
12866 	pf->lan_vsi = I40E_NO_VSI;
12867 
12868 	/* By default FW has this off for performance reasons */
12869 	pf->flags &= ~I40E_FLAG_VEB_STATS_ENABLED;
12870 
12871 	/* set up queue assignment tracking */
12872 	size = sizeof(struct i40e_lump_tracking)
12873 		+ (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
12874 	pf->qp_pile = kzalloc(size, GFP_KERNEL);
12875 	if (!pf->qp_pile) {
12876 		err = -ENOMEM;
12877 		goto sw_init_done;
12878 	}
12879 	pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
12880 
12881 	pf->tx_timeout_recovery_level = 1;
12882 
12883 	if (pf->hw.mac.type != I40E_MAC_X722 &&
12884 	    i40e_is_total_port_shutdown_enabled(pf)) {
12885 		/* Link down on close must be on when total port shutdown
12886 		 * is enabled for a given port
12887 		 */
12888 		pf->flags |= (I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED |
12889 			      I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED);
12890 		dev_info(&pf->pdev->dev,
12891 			 "total-port-shutdown was enabled, link-down-on-close is forced on\n");
12892 	}
12893 	mutex_init(&pf->switch_mutex);
12894 
12895 sw_init_done:
12896 	return err;
12897 }
12898 
12899 /**
12900  * i40e_set_ntuple - set the ntuple feature flag and take action
12901  * @pf: board private structure to initialize
12902  * @features: the feature set that the stack is suggesting
12903  *
12904  * returns a bool to indicate if reset needs to happen
12905  **/
12906 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12907 {
12908 	bool need_reset = false;
12909 
12910 	/* Check if Flow Director n-tuple support was enabled or disabled.  If
12911 	 * the state changed, we need to reset.
12912 	 */
12913 	if (features & NETIF_F_NTUPLE) {
12914 		/* Enable filters and mark for reset */
12915 		if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
12916 			need_reset = true;
12917 		/* enable FD_SB only if there is MSI-X vector and no cloud
12918 		 * filters exist
12919 		 */
12920 		if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12921 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12922 			pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
12923 		}
12924 	} else {
12925 		/* turn off filters, mark for reset and clear SW filter list */
12926 		if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
12927 			need_reset = true;
12928 			i40e_fdir_filter_exit(pf);
12929 		}
12930 		pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
12931 		clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12932 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
12933 
12934 		/* reset fd counters */
12935 		pf->fd_add_err = 0;
12936 		pf->fd_atr_cnt = 0;
12937 		/* if ATR was auto disabled it can be re-enabled. */
12938 		if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12939 			if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
12940 			    (I40E_DEBUG_FD & pf->hw.debug_mask))
12941 				dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12942 	}
12943 	return need_reset;
12944 }
12945 
12946 /**
12947  * i40e_clear_rss_lut - clear the rx hash lookup table
12948  * @vsi: the VSI being configured
12949  **/
12950 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12951 {
12952 	struct i40e_pf *pf = vsi->back;
12953 	struct i40e_hw *hw = &pf->hw;
12954 	u16 vf_id = vsi->vf_id;
12955 	u8 i;
12956 
12957 	if (vsi->type == I40E_VSI_MAIN) {
12958 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12959 			wr32(hw, I40E_PFQF_HLUT(i), 0);
12960 	} else if (vsi->type == I40E_VSI_SRIOV) {
12961 		for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12962 			i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12963 	} else {
12964 		dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12965 	}
12966 }
12967 
12968 /**
12969  * i40e_set_loopback - turn on/off loopback mode on underlying PF
12970  * @vsi: ptr to VSI
12971  * @ena: flag to indicate the on/off setting
12972  */
12973 static int i40e_set_loopback(struct i40e_vsi *vsi, bool ena)
12974 {
12975 	bool if_running = netif_running(vsi->netdev) &&
12976 			  !test_and_set_bit(__I40E_VSI_DOWN, vsi->state);
12977 	int ret;
12978 
12979 	if (if_running)
12980 		i40e_down(vsi);
12981 
12982 	ret = i40e_aq_set_mac_loopback(&vsi->back->hw, ena, NULL);
12983 	if (ret)
12984 		netdev_err(vsi->netdev, "Failed to toggle loopback state\n");
12985 	if (if_running)
12986 		i40e_up(vsi);
12987 
12988 	return ret;
12989 }
12990 
12991 /**
12992  * i40e_set_features - set the netdev feature flags
12993  * @netdev: ptr to the netdev being adjusted
12994  * @features: the feature set that the stack is suggesting
12995  * Note: expects to be called while under rtnl_lock()
12996  **/
12997 static int i40e_set_features(struct net_device *netdev,
12998 			     netdev_features_t features)
12999 {
13000 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13001 	struct i40e_vsi *vsi = np->vsi;
13002 	struct i40e_pf *pf = vsi->back;
13003 	bool need_reset;
13004 
13005 	if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
13006 		i40e_pf_config_rss(pf);
13007 	else if (!(features & NETIF_F_RXHASH) &&
13008 		 netdev->features & NETIF_F_RXHASH)
13009 		i40e_clear_rss_lut(vsi);
13010 
13011 	if (features & NETIF_F_HW_VLAN_CTAG_RX)
13012 		i40e_vlan_stripping_enable(vsi);
13013 	else
13014 		i40e_vlan_stripping_disable(vsi);
13015 
13016 	if (!(features & NETIF_F_HW_TC) &&
13017 	    (netdev->features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
13018 		dev_err(&pf->pdev->dev,
13019 			"Offloaded tc filters active, can't turn hw_tc_offload off");
13020 		return -EINVAL;
13021 	}
13022 
13023 	if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
13024 		i40e_del_all_macvlans(vsi);
13025 
13026 	need_reset = i40e_set_ntuple(pf, features);
13027 
13028 	if (need_reset)
13029 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13030 
13031 	if ((features ^ netdev->features) & NETIF_F_LOOPBACK)
13032 		return i40e_set_loopback(vsi, !!(features & NETIF_F_LOOPBACK));
13033 
13034 	return 0;
13035 }
13036 
13037 static int i40e_udp_tunnel_set_port(struct net_device *netdev,
13038 				    unsigned int table, unsigned int idx,
13039 				    struct udp_tunnel_info *ti)
13040 {
13041 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13042 	struct i40e_hw *hw = &np->vsi->back->hw;
13043 	u8 type, filter_index;
13044 	int ret;
13045 
13046 	type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? I40E_AQC_TUNNEL_TYPE_VXLAN :
13047 						   I40E_AQC_TUNNEL_TYPE_NGE;
13048 
13049 	ret = i40e_aq_add_udp_tunnel(hw, ntohs(ti->port), type, &filter_index,
13050 				     NULL);
13051 	if (ret) {
13052 		netdev_info(netdev, "add UDP port failed, err %pe aq_err %s\n",
13053 			    ERR_PTR(ret),
13054 			    i40e_aq_str(hw, hw->aq.asq_last_status));
13055 		return -EIO;
13056 	}
13057 
13058 	udp_tunnel_nic_set_port_priv(netdev, table, idx, filter_index);
13059 	return 0;
13060 }
13061 
13062 static int i40e_udp_tunnel_unset_port(struct net_device *netdev,
13063 				      unsigned int table, unsigned int idx,
13064 				      struct udp_tunnel_info *ti)
13065 {
13066 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13067 	struct i40e_hw *hw = &np->vsi->back->hw;
13068 	int ret;
13069 
13070 	ret = i40e_aq_del_udp_tunnel(hw, ti->hw_priv, NULL);
13071 	if (ret) {
13072 		netdev_info(netdev, "delete UDP port failed, err %pe aq_err %s\n",
13073 			    ERR_PTR(ret),
13074 			    i40e_aq_str(hw, hw->aq.asq_last_status));
13075 		return -EIO;
13076 	}
13077 
13078 	return 0;
13079 }
13080 
13081 static int i40e_get_phys_port_id(struct net_device *netdev,
13082 				 struct netdev_phys_item_id *ppid)
13083 {
13084 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13085 	struct i40e_pf *pf = np->vsi->back;
13086 	struct i40e_hw *hw = &pf->hw;
13087 
13088 	if (!(pf->hw_features & I40E_HW_PORT_ID_VALID))
13089 		return -EOPNOTSUPP;
13090 
13091 	ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
13092 	memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
13093 
13094 	return 0;
13095 }
13096 
13097 /**
13098  * i40e_ndo_fdb_add - add an entry to the hardware database
13099  * @ndm: the input from the stack
13100  * @tb: pointer to array of nladdr (unused)
13101  * @dev: the net device pointer
13102  * @addr: the MAC address entry being added
13103  * @vid: VLAN ID
13104  * @flags: instructions from stack about fdb operation
13105  * @extack: netlink extended ack, unused currently
13106  */
13107 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
13108 			    struct net_device *dev,
13109 			    const unsigned char *addr, u16 vid,
13110 			    u16 flags,
13111 			    struct netlink_ext_ack *extack)
13112 {
13113 	struct i40e_netdev_priv *np = netdev_priv(dev);
13114 	struct i40e_pf *pf = np->vsi->back;
13115 	int err = 0;
13116 
13117 	if (!(pf->flags & I40E_FLAG_SRIOV_ENABLED))
13118 		return -EOPNOTSUPP;
13119 
13120 	if (vid) {
13121 		pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
13122 		return -EINVAL;
13123 	}
13124 
13125 	/* Hardware does not support aging addresses so if a
13126 	 * ndm_state is given only allow permanent addresses
13127 	 */
13128 	if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
13129 		netdev_info(dev, "FDB only supports static addresses\n");
13130 		return -EINVAL;
13131 	}
13132 
13133 	if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
13134 		err = dev_uc_add_excl(dev, addr);
13135 	else if (is_multicast_ether_addr(addr))
13136 		err = dev_mc_add_excl(dev, addr);
13137 	else
13138 		err = -EINVAL;
13139 
13140 	/* Only return duplicate errors if NLM_F_EXCL is set */
13141 	if (err == -EEXIST && !(flags & NLM_F_EXCL))
13142 		err = 0;
13143 
13144 	return err;
13145 }
13146 
13147 /**
13148  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
13149  * @dev: the netdev being configured
13150  * @nlh: RTNL message
13151  * @flags: bridge flags
13152  * @extack: netlink extended ack
13153  *
13154  * Inserts a new hardware bridge if not already created and
13155  * enables the bridging mode requested (VEB or VEPA). If the
13156  * hardware bridge has already been inserted and the request
13157  * is to change the mode then that requires a PF reset to
13158  * allow rebuild of the components with required hardware
13159  * bridge mode enabled.
13160  *
13161  * Note: expects to be called while under rtnl_lock()
13162  **/
13163 static int i40e_ndo_bridge_setlink(struct net_device *dev,
13164 				   struct nlmsghdr *nlh,
13165 				   u16 flags,
13166 				   struct netlink_ext_ack *extack)
13167 {
13168 	struct i40e_netdev_priv *np = netdev_priv(dev);
13169 	struct i40e_vsi *vsi = np->vsi;
13170 	struct i40e_pf *pf = vsi->back;
13171 	struct i40e_veb *veb = NULL;
13172 	struct nlattr *attr, *br_spec;
13173 	int i, rem;
13174 
13175 	/* Only for PF VSI for now */
13176 	if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13177 		return -EOPNOTSUPP;
13178 
13179 	/* Find the HW bridge for PF VSI */
13180 	for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13181 		if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13182 			veb = pf->veb[i];
13183 	}
13184 
13185 	br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
13186 	if (!br_spec)
13187 		return -EINVAL;
13188 
13189 	nla_for_each_nested(attr, br_spec, rem) {
13190 		__u16 mode;
13191 
13192 		if (nla_type(attr) != IFLA_BRIDGE_MODE)
13193 			continue;
13194 
13195 		mode = nla_get_u16(attr);
13196 		if ((mode != BRIDGE_MODE_VEPA) &&
13197 		    (mode != BRIDGE_MODE_VEB))
13198 			return -EINVAL;
13199 
13200 		/* Insert a new HW bridge */
13201 		if (!veb) {
13202 			veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
13203 					     vsi->tc_config.enabled_tc);
13204 			if (veb) {
13205 				veb->bridge_mode = mode;
13206 				i40e_config_bridge_mode(veb);
13207 			} else {
13208 				/* No Bridge HW offload available */
13209 				return -ENOENT;
13210 			}
13211 			break;
13212 		} else if (mode != veb->bridge_mode) {
13213 			/* Existing HW bridge but different mode needs reset */
13214 			veb->bridge_mode = mode;
13215 			/* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
13216 			if (mode == BRIDGE_MODE_VEB)
13217 				pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
13218 			else
13219 				pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
13220 			i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13221 			break;
13222 		}
13223 	}
13224 
13225 	return 0;
13226 }
13227 
13228 /**
13229  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
13230  * @skb: skb buff
13231  * @pid: process id
13232  * @seq: RTNL message seq #
13233  * @dev: the netdev being configured
13234  * @filter_mask: unused
13235  * @nlflags: netlink flags passed in
13236  *
13237  * Return the mode in which the hardware bridge is operating in
13238  * i.e VEB or VEPA.
13239  **/
13240 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
13241 				   struct net_device *dev,
13242 				   u32 __always_unused filter_mask,
13243 				   int nlflags)
13244 {
13245 	struct i40e_netdev_priv *np = netdev_priv(dev);
13246 	struct i40e_vsi *vsi = np->vsi;
13247 	struct i40e_pf *pf = vsi->back;
13248 	struct i40e_veb *veb = NULL;
13249 	int i;
13250 
13251 	/* Only for PF VSI for now */
13252 	if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13253 		return -EOPNOTSUPP;
13254 
13255 	/* Find the HW bridge for the PF VSI */
13256 	for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13257 		if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13258 			veb = pf->veb[i];
13259 	}
13260 
13261 	if (!veb)
13262 		return 0;
13263 
13264 	return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
13265 				       0, 0, nlflags, filter_mask, NULL);
13266 }
13267 
13268 /**
13269  * i40e_features_check - Validate encapsulated packet conforms to limits
13270  * @skb: skb buff
13271  * @dev: This physical port's netdev
13272  * @features: Offload features that the stack believes apply
13273  **/
13274 static netdev_features_t i40e_features_check(struct sk_buff *skb,
13275 					     struct net_device *dev,
13276 					     netdev_features_t features)
13277 {
13278 	size_t len;
13279 
13280 	/* No point in doing any of this if neither checksum nor GSO are
13281 	 * being requested for this frame.  We can rule out both by just
13282 	 * checking for CHECKSUM_PARTIAL
13283 	 */
13284 	if (skb->ip_summed != CHECKSUM_PARTIAL)
13285 		return features;
13286 
13287 	/* We cannot support GSO if the MSS is going to be less than
13288 	 * 64 bytes.  If it is then we need to drop support for GSO.
13289 	 */
13290 	if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
13291 		features &= ~NETIF_F_GSO_MASK;
13292 
13293 	/* MACLEN can support at most 63 words */
13294 	len = skb_network_header(skb) - skb->data;
13295 	if (len & ~(63 * 2))
13296 		goto out_err;
13297 
13298 	/* IPLEN and EIPLEN can support at most 127 dwords */
13299 	len = skb_transport_header(skb) - skb_network_header(skb);
13300 	if (len & ~(127 * 4))
13301 		goto out_err;
13302 
13303 	if (skb->encapsulation) {
13304 		/* L4TUNLEN can support 127 words */
13305 		len = skb_inner_network_header(skb) - skb_transport_header(skb);
13306 		if (len & ~(127 * 2))
13307 			goto out_err;
13308 
13309 		/* IPLEN can support at most 127 dwords */
13310 		len = skb_inner_transport_header(skb) -
13311 		      skb_inner_network_header(skb);
13312 		if (len & ~(127 * 4))
13313 			goto out_err;
13314 	}
13315 
13316 	/* No need to validate L4LEN as TCP is the only protocol with a
13317 	 * flexible value and we support all possible values supported
13318 	 * by TCP, which is at most 15 dwords
13319 	 */
13320 
13321 	return features;
13322 out_err:
13323 	return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
13324 }
13325 
13326 /**
13327  * i40e_xdp_setup - add/remove an XDP program
13328  * @vsi: VSI to changed
13329  * @prog: XDP program
13330  * @extack: netlink extended ack
13331  **/
13332 static int i40e_xdp_setup(struct i40e_vsi *vsi, struct bpf_prog *prog,
13333 			  struct netlink_ext_ack *extack)
13334 {
13335 	int frame_size = i40e_max_vsi_frame_size(vsi, prog);
13336 	struct i40e_pf *pf = vsi->back;
13337 	struct bpf_prog *old_prog;
13338 	bool need_reset;
13339 	int i;
13340 
13341 	/* Don't allow frames that span over multiple buffers */
13342 	if (vsi->netdev->mtu > frame_size - I40E_PACKET_HDR_PAD) {
13343 		NL_SET_ERR_MSG_MOD(extack, "MTU too large for linear frames and XDP prog does not support frags");
13344 		return -EINVAL;
13345 	}
13346 
13347 	/* When turning XDP on->off/off->on we reset and rebuild the rings. */
13348 	need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
13349 
13350 	if (need_reset)
13351 		i40e_prep_for_reset(pf);
13352 
13353 	/* VSI shall be deleted in a moment, just return EINVAL */
13354 	if (test_bit(__I40E_IN_REMOVE, pf->state))
13355 		return -EINVAL;
13356 
13357 	old_prog = xchg(&vsi->xdp_prog, prog);
13358 
13359 	if (need_reset) {
13360 		if (!prog) {
13361 			xdp_features_clear_redirect_target(vsi->netdev);
13362 			/* Wait until ndo_xsk_wakeup completes. */
13363 			synchronize_rcu();
13364 		}
13365 		i40e_reset_and_rebuild(pf, true, true);
13366 	}
13367 
13368 	if (!i40e_enabled_xdp_vsi(vsi) && prog) {
13369 		if (i40e_realloc_rx_bi_zc(vsi, true))
13370 			return -ENOMEM;
13371 	} else if (i40e_enabled_xdp_vsi(vsi) && !prog) {
13372 		if (i40e_realloc_rx_bi_zc(vsi, false))
13373 			return -ENOMEM;
13374 	}
13375 
13376 	for (i = 0; i < vsi->num_queue_pairs; i++)
13377 		WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
13378 
13379 	if (old_prog)
13380 		bpf_prog_put(old_prog);
13381 
13382 	/* Kick start the NAPI context if there is an AF_XDP socket open
13383 	 * on that queue id. This so that receiving will start.
13384 	 */
13385 	if (need_reset && prog) {
13386 		for (i = 0; i < vsi->num_queue_pairs; i++)
13387 			if (vsi->xdp_rings[i]->xsk_pool)
13388 				(void)i40e_xsk_wakeup(vsi->netdev, i,
13389 						      XDP_WAKEUP_RX);
13390 		xdp_features_set_redirect_target(vsi->netdev, true);
13391 	}
13392 
13393 	return 0;
13394 }
13395 
13396 /**
13397  * i40e_enter_busy_conf - Enters busy config state
13398  * @vsi: vsi
13399  *
13400  * Returns 0 on success, <0 for failure.
13401  **/
13402 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
13403 {
13404 	struct i40e_pf *pf = vsi->back;
13405 	int timeout = 50;
13406 
13407 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
13408 		timeout--;
13409 		if (!timeout)
13410 			return -EBUSY;
13411 		usleep_range(1000, 2000);
13412 	}
13413 
13414 	return 0;
13415 }
13416 
13417 /**
13418  * i40e_exit_busy_conf - Exits busy config state
13419  * @vsi: vsi
13420  **/
13421 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
13422 {
13423 	struct i40e_pf *pf = vsi->back;
13424 
13425 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
13426 }
13427 
13428 /**
13429  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
13430  * @vsi: vsi
13431  * @queue_pair: queue pair
13432  **/
13433 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
13434 {
13435 	memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
13436 	       sizeof(vsi->rx_rings[queue_pair]->rx_stats));
13437 	memset(&vsi->tx_rings[queue_pair]->stats, 0,
13438 	       sizeof(vsi->tx_rings[queue_pair]->stats));
13439 	if (i40e_enabled_xdp_vsi(vsi)) {
13440 		memset(&vsi->xdp_rings[queue_pair]->stats, 0,
13441 		       sizeof(vsi->xdp_rings[queue_pair]->stats));
13442 	}
13443 }
13444 
13445 /**
13446  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
13447  * @vsi: vsi
13448  * @queue_pair: queue pair
13449  **/
13450 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
13451 {
13452 	i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
13453 	if (i40e_enabled_xdp_vsi(vsi)) {
13454 		/* Make sure that in-progress ndo_xdp_xmit calls are
13455 		 * completed.
13456 		 */
13457 		synchronize_rcu();
13458 		i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
13459 	}
13460 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13461 }
13462 
13463 /**
13464  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
13465  * @vsi: vsi
13466  * @queue_pair: queue pair
13467  * @enable: true for enable, false for disable
13468  **/
13469 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
13470 					bool enable)
13471 {
13472 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13473 	struct i40e_q_vector *q_vector = rxr->q_vector;
13474 
13475 	if (!vsi->netdev)
13476 		return;
13477 
13478 	/* All rings in a qp belong to the same qvector. */
13479 	if (q_vector->rx.ring || q_vector->tx.ring) {
13480 		if (enable)
13481 			napi_enable(&q_vector->napi);
13482 		else
13483 			napi_disable(&q_vector->napi);
13484 	}
13485 }
13486 
13487 /**
13488  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
13489  * @vsi: vsi
13490  * @queue_pair: queue pair
13491  * @enable: true for enable, false for disable
13492  *
13493  * Returns 0 on success, <0 on failure.
13494  **/
13495 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
13496 					bool enable)
13497 {
13498 	struct i40e_pf *pf = vsi->back;
13499 	int pf_q, ret = 0;
13500 
13501 	pf_q = vsi->base_queue + queue_pair;
13502 	ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
13503 				     false /*is xdp*/, enable);
13504 	if (ret) {
13505 		dev_info(&pf->pdev->dev,
13506 			 "VSI seid %d Tx ring %d %sable timeout\n",
13507 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13508 		return ret;
13509 	}
13510 
13511 	i40e_control_rx_q(pf, pf_q, enable);
13512 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
13513 	if (ret) {
13514 		dev_info(&pf->pdev->dev,
13515 			 "VSI seid %d Rx ring %d %sable timeout\n",
13516 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13517 		return ret;
13518 	}
13519 
13520 	/* Due to HW errata, on Rx disable only, the register can
13521 	 * indicate done before it really is. Needs 50ms to be sure
13522 	 */
13523 	if (!enable)
13524 		mdelay(50);
13525 
13526 	if (!i40e_enabled_xdp_vsi(vsi))
13527 		return ret;
13528 
13529 	ret = i40e_control_wait_tx_q(vsi->seid, pf,
13530 				     pf_q + vsi->alloc_queue_pairs,
13531 				     true /*is xdp*/, enable);
13532 	if (ret) {
13533 		dev_info(&pf->pdev->dev,
13534 			 "VSI seid %d XDP Tx ring %d %sable timeout\n",
13535 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13536 	}
13537 
13538 	return ret;
13539 }
13540 
13541 /**
13542  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
13543  * @vsi: vsi
13544  * @queue_pair: queue_pair
13545  **/
13546 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
13547 {
13548 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13549 	struct i40e_pf *pf = vsi->back;
13550 	struct i40e_hw *hw = &pf->hw;
13551 
13552 	/* All rings in a qp belong to the same qvector. */
13553 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
13554 		i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
13555 	else
13556 		i40e_irq_dynamic_enable_icr0(pf);
13557 
13558 	i40e_flush(hw);
13559 }
13560 
13561 /**
13562  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
13563  * @vsi: vsi
13564  * @queue_pair: queue_pair
13565  **/
13566 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
13567 {
13568 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13569 	struct i40e_pf *pf = vsi->back;
13570 	struct i40e_hw *hw = &pf->hw;
13571 
13572 	/* For simplicity, instead of removing the qp interrupt causes
13573 	 * from the interrupt linked list, we simply disable the interrupt, and
13574 	 * leave the list intact.
13575 	 *
13576 	 * All rings in a qp belong to the same qvector.
13577 	 */
13578 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
13579 		u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
13580 
13581 		wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
13582 		i40e_flush(hw);
13583 		synchronize_irq(pf->msix_entries[intpf].vector);
13584 	} else {
13585 		/* Legacy and MSI mode - this stops all interrupt handling */
13586 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
13587 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
13588 		i40e_flush(hw);
13589 		synchronize_irq(pf->pdev->irq);
13590 	}
13591 }
13592 
13593 /**
13594  * i40e_queue_pair_disable - Disables a queue pair
13595  * @vsi: vsi
13596  * @queue_pair: queue pair
13597  *
13598  * Returns 0 on success, <0 on failure.
13599  **/
13600 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
13601 {
13602 	int err;
13603 
13604 	err = i40e_enter_busy_conf(vsi);
13605 	if (err)
13606 		return err;
13607 
13608 	i40e_queue_pair_disable_irq(vsi, queue_pair);
13609 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
13610 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13611 	i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
13612 	i40e_queue_pair_clean_rings(vsi, queue_pair);
13613 	i40e_queue_pair_reset_stats(vsi, queue_pair);
13614 
13615 	return err;
13616 }
13617 
13618 /**
13619  * i40e_queue_pair_enable - Enables a queue pair
13620  * @vsi: vsi
13621  * @queue_pair: queue pair
13622  *
13623  * Returns 0 on success, <0 on failure.
13624  **/
13625 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
13626 {
13627 	int err;
13628 
13629 	err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
13630 	if (err)
13631 		return err;
13632 
13633 	if (i40e_enabled_xdp_vsi(vsi)) {
13634 		err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
13635 		if (err)
13636 			return err;
13637 	}
13638 
13639 	err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
13640 	if (err)
13641 		return err;
13642 
13643 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
13644 	i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
13645 	i40e_queue_pair_enable_irq(vsi, queue_pair);
13646 
13647 	i40e_exit_busy_conf(vsi);
13648 
13649 	return err;
13650 }
13651 
13652 /**
13653  * i40e_xdp - implements ndo_bpf for i40e
13654  * @dev: netdevice
13655  * @xdp: XDP command
13656  **/
13657 static int i40e_xdp(struct net_device *dev,
13658 		    struct netdev_bpf *xdp)
13659 {
13660 	struct i40e_netdev_priv *np = netdev_priv(dev);
13661 	struct i40e_vsi *vsi = np->vsi;
13662 
13663 	if (vsi->type != I40E_VSI_MAIN)
13664 		return -EINVAL;
13665 
13666 	switch (xdp->command) {
13667 	case XDP_SETUP_PROG:
13668 		return i40e_xdp_setup(vsi, xdp->prog, xdp->extack);
13669 	case XDP_SETUP_XSK_POOL:
13670 		return i40e_xsk_pool_setup(vsi, xdp->xsk.pool,
13671 					   xdp->xsk.queue_id);
13672 	default:
13673 		return -EINVAL;
13674 	}
13675 }
13676 
13677 static const struct net_device_ops i40e_netdev_ops = {
13678 	.ndo_open		= i40e_open,
13679 	.ndo_stop		= i40e_close,
13680 	.ndo_start_xmit		= i40e_lan_xmit_frame,
13681 	.ndo_get_stats64	= i40e_get_netdev_stats_struct,
13682 	.ndo_set_rx_mode	= i40e_set_rx_mode,
13683 	.ndo_validate_addr	= eth_validate_addr,
13684 	.ndo_set_mac_address	= i40e_set_mac,
13685 	.ndo_change_mtu		= i40e_change_mtu,
13686 	.ndo_eth_ioctl		= i40e_ioctl,
13687 	.ndo_tx_timeout		= i40e_tx_timeout,
13688 	.ndo_vlan_rx_add_vid	= i40e_vlan_rx_add_vid,
13689 	.ndo_vlan_rx_kill_vid	= i40e_vlan_rx_kill_vid,
13690 #ifdef CONFIG_NET_POLL_CONTROLLER
13691 	.ndo_poll_controller	= i40e_netpoll,
13692 #endif
13693 	.ndo_setup_tc		= __i40e_setup_tc,
13694 	.ndo_select_queue	= i40e_lan_select_queue,
13695 	.ndo_set_features	= i40e_set_features,
13696 	.ndo_set_vf_mac		= i40e_ndo_set_vf_mac,
13697 	.ndo_set_vf_vlan	= i40e_ndo_set_vf_port_vlan,
13698 	.ndo_get_vf_stats	= i40e_get_vf_stats,
13699 	.ndo_set_vf_rate	= i40e_ndo_set_vf_bw,
13700 	.ndo_get_vf_config	= i40e_ndo_get_vf_config,
13701 	.ndo_set_vf_link_state	= i40e_ndo_set_vf_link_state,
13702 	.ndo_set_vf_spoofchk	= i40e_ndo_set_vf_spoofchk,
13703 	.ndo_set_vf_trust	= i40e_ndo_set_vf_trust,
13704 	.ndo_get_phys_port_id	= i40e_get_phys_port_id,
13705 	.ndo_fdb_add		= i40e_ndo_fdb_add,
13706 	.ndo_features_check	= i40e_features_check,
13707 	.ndo_bridge_getlink	= i40e_ndo_bridge_getlink,
13708 	.ndo_bridge_setlink	= i40e_ndo_bridge_setlink,
13709 	.ndo_bpf		= i40e_xdp,
13710 	.ndo_xdp_xmit		= i40e_xdp_xmit,
13711 	.ndo_xsk_wakeup	        = i40e_xsk_wakeup,
13712 	.ndo_dfwd_add_station	= i40e_fwd_add,
13713 	.ndo_dfwd_del_station	= i40e_fwd_del,
13714 };
13715 
13716 /**
13717  * i40e_config_netdev - Setup the netdev flags
13718  * @vsi: the VSI being configured
13719  *
13720  * Returns 0 on success, negative value on failure
13721  **/
13722 static int i40e_config_netdev(struct i40e_vsi *vsi)
13723 {
13724 	struct i40e_pf *pf = vsi->back;
13725 	struct i40e_hw *hw = &pf->hw;
13726 	struct i40e_netdev_priv *np;
13727 	struct net_device *netdev;
13728 	u8 broadcast[ETH_ALEN];
13729 	u8 mac_addr[ETH_ALEN];
13730 	int etherdev_size;
13731 	netdev_features_t hw_enc_features;
13732 	netdev_features_t hw_features;
13733 
13734 	etherdev_size = sizeof(struct i40e_netdev_priv);
13735 	netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
13736 	if (!netdev)
13737 		return -ENOMEM;
13738 
13739 	vsi->netdev = netdev;
13740 	np = netdev_priv(netdev);
13741 	np->vsi = vsi;
13742 
13743 	hw_enc_features = NETIF_F_SG			|
13744 			  NETIF_F_HW_CSUM		|
13745 			  NETIF_F_HIGHDMA		|
13746 			  NETIF_F_SOFT_FEATURES		|
13747 			  NETIF_F_TSO			|
13748 			  NETIF_F_TSO_ECN		|
13749 			  NETIF_F_TSO6			|
13750 			  NETIF_F_GSO_GRE		|
13751 			  NETIF_F_GSO_GRE_CSUM		|
13752 			  NETIF_F_GSO_PARTIAL		|
13753 			  NETIF_F_GSO_IPXIP4		|
13754 			  NETIF_F_GSO_IPXIP6		|
13755 			  NETIF_F_GSO_UDP_TUNNEL	|
13756 			  NETIF_F_GSO_UDP_TUNNEL_CSUM	|
13757 			  NETIF_F_GSO_UDP_L4		|
13758 			  NETIF_F_SCTP_CRC		|
13759 			  NETIF_F_RXHASH		|
13760 			  NETIF_F_RXCSUM		|
13761 			  0;
13762 
13763 	if (!(pf->hw_features & I40E_HW_OUTER_UDP_CSUM_CAPABLE))
13764 		netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
13765 
13766 	netdev->udp_tunnel_nic_info = &pf->udp_tunnel_nic;
13767 
13768 	netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
13769 
13770 	netdev->hw_enc_features |= hw_enc_features;
13771 
13772 	/* record features VLANs can make use of */
13773 	netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
13774 
13775 #define I40E_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE |		\
13776 				   NETIF_F_GSO_GRE_CSUM |	\
13777 				   NETIF_F_GSO_IPXIP4 |		\
13778 				   NETIF_F_GSO_IPXIP6 |		\
13779 				   NETIF_F_GSO_UDP_TUNNEL |	\
13780 				   NETIF_F_GSO_UDP_TUNNEL_CSUM)
13781 
13782 	netdev->gso_partial_features = I40E_GSO_PARTIAL_FEATURES;
13783 	netdev->features |= NETIF_F_GSO_PARTIAL |
13784 			    I40E_GSO_PARTIAL_FEATURES;
13785 
13786 	netdev->mpls_features |= NETIF_F_SG;
13787 	netdev->mpls_features |= NETIF_F_HW_CSUM;
13788 	netdev->mpls_features |= NETIF_F_TSO;
13789 	netdev->mpls_features |= NETIF_F_TSO6;
13790 	netdev->mpls_features |= I40E_GSO_PARTIAL_FEATURES;
13791 
13792 	/* enable macvlan offloads */
13793 	netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
13794 
13795 	hw_features = hw_enc_features		|
13796 		      NETIF_F_HW_VLAN_CTAG_TX	|
13797 		      NETIF_F_HW_VLAN_CTAG_RX;
13798 
13799 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
13800 		hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
13801 
13802 	netdev->hw_features |= hw_features | NETIF_F_LOOPBACK;
13803 
13804 	netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
13805 	netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
13806 
13807 	netdev->features &= ~NETIF_F_HW_TC;
13808 
13809 	if (vsi->type == I40E_VSI_MAIN) {
13810 		SET_NETDEV_DEV(netdev, &pf->pdev->dev);
13811 		ether_addr_copy(mac_addr, hw->mac.perm_addr);
13812 		/* The following steps are necessary for two reasons. First,
13813 		 * some older NVM configurations load a default MAC-VLAN
13814 		 * filter that will accept any tagged packet, and we want to
13815 		 * replace this with a normal filter. Additionally, it is
13816 		 * possible our MAC address was provided by the platform using
13817 		 * Open Firmware or similar.
13818 		 *
13819 		 * Thus, we need to remove the default filter and install one
13820 		 * specific to the MAC address.
13821 		 */
13822 		i40e_rm_default_mac_filter(vsi, mac_addr);
13823 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13824 		i40e_add_mac_filter(vsi, mac_addr);
13825 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13826 
13827 		netdev->xdp_features = NETDEV_XDP_ACT_BASIC |
13828 				       NETDEV_XDP_ACT_REDIRECT |
13829 				       NETDEV_XDP_ACT_XSK_ZEROCOPY |
13830 				       NETDEV_XDP_ACT_RX_SG;
13831 	} else {
13832 		/* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
13833 		 * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
13834 		 * the end, which is 4 bytes long, so force truncation of the
13835 		 * original name by IFNAMSIZ - 4
13836 		 */
13837 		snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d",
13838 			 IFNAMSIZ - 4,
13839 			 pf->vsi[pf->lan_vsi]->netdev->name);
13840 		eth_random_addr(mac_addr);
13841 
13842 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13843 		i40e_add_mac_filter(vsi, mac_addr);
13844 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13845 	}
13846 
13847 	/* Add the broadcast filter so that we initially will receive
13848 	 * broadcast packets. Note that when a new VLAN is first added the
13849 	 * driver will convert all filters marked I40E_VLAN_ANY into VLAN
13850 	 * specific filters as part of transitioning into "vlan" operation.
13851 	 * When more VLANs are added, the driver will copy each existing MAC
13852 	 * filter and add it for the new VLAN.
13853 	 *
13854 	 * Broadcast filters are handled specially by
13855 	 * i40e_sync_filters_subtask, as the driver must to set the broadcast
13856 	 * promiscuous bit instead of adding this directly as a MAC/VLAN
13857 	 * filter. The subtask will update the correct broadcast promiscuous
13858 	 * bits as VLANs become active or inactive.
13859 	 */
13860 	eth_broadcast_addr(broadcast);
13861 	spin_lock_bh(&vsi->mac_filter_hash_lock);
13862 	i40e_add_mac_filter(vsi, broadcast);
13863 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
13864 
13865 	eth_hw_addr_set(netdev, mac_addr);
13866 	ether_addr_copy(netdev->perm_addr, mac_addr);
13867 
13868 	/* i40iw_net_event() reads 16 bytes from neigh->primary_key */
13869 	netdev->neigh_priv_len = sizeof(u32) * 4;
13870 
13871 	netdev->priv_flags |= IFF_UNICAST_FLT;
13872 	netdev->priv_flags |= IFF_SUPP_NOFCS;
13873 	/* Setup netdev TC information */
13874 	i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
13875 
13876 	netdev->netdev_ops = &i40e_netdev_ops;
13877 	netdev->watchdog_timeo = 5 * HZ;
13878 	i40e_set_ethtool_ops(netdev);
13879 
13880 	/* MTU range: 68 - 9706 */
13881 	netdev->min_mtu = ETH_MIN_MTU;
13882 	netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13883 
13884 	return 0;
13885 }
13886 
13887 /**
13888  * i40e_vsi_delete - Delete a VSI from the switch
13889  * @vsi: the VSI being removed
13890  *
13891  * Returns 0 on success, negative value on failure
13892  **/
13893 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13894 {
13895 	/* remove default VSI is not allowed */
13896 	if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13897 		return;
13898 
13899 	i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13900 }
13901 
13902 /**
13903  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13904  * @vsi: the VSI being queried
13905  *
13906  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13907  **/
13908 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13909 {
13910 	struct i40e_veb *veb;
13911 	struct i40e_pf *pf = vsi->back;
13912 
13913 	/* Uplink is not a bridge so default to VEB */
13914 	if (vsi->veb_idx >= I40E_MAX_VEB)
13915 		return 1;
13916 
13917 	veb = pf->veb[vsi->veb_idx];
13918 	if (!veb) {
13919 		dev_info(&pf->pdev->dev,
13920 			 "There is no veb associated with the bridge\n");
13921 		return -ENOENT;
13922 	}
13923 
13924 	/* Uplink is a bridge in VEPA mode */
13925 	if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13926 		return 0;
13927 	} else {
13928 		/* Uplink is a bridge in VEB mode */
13929 		return 1;
13930 	}
13931 
13932 	/* VEPA is now default bridge, so return 0 */
13933 	return 0;
13934 }
13935 
13936 /**
13937  * i40e_add_vsi - Add a VSI to the switch
13938  * @vsi: the VSI being configured
13939  *
13940  * This initializes a VSI context depending on the VSI type to be added and
13941  * passes it down to the add_vsi aq command.
13942  **/
13943 static int i40e_add_vsi(struct i40e_vsi *vsi)
13944 {
13945 	int ret = -ENODEV;
13946 	struct i40e_pf *pf = vsi->back;
13947 	struct i40e_hw *hw = &pf->hw;
13948 	struct i40e_vsi_context ctxt;
13949 	struct i40e_mac_filter *f;
13950 	struct hlist_node *h;
13951 	int bkt;
13952 
13953 	u8 enabled_tc = 0x1; /* TC0 enabled */
13954 	int f_count = 0;
13955 
13956 	memset(&ctxt, 0, sizeof(ctxt));
13957 	switch (vsi->type) {
13958 	case I40E_VSI_MAIN:
13959 		/* The PF's main VSI is already setup as part of the
13960 		 * device initialization, so we'll not bother with
13961 		 * the add_vsi call, but we will retrieve the current
13962 		 * VSI context.
13963 		 */
13964 		ctxt.seid = pf->main_vsi_seid;
13965 		ctxt.pf_num = pf->hw.pf_id;
13966 		ctxt.vf_num = 0;
13967 		ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13968 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13969 		if (ret) {
13970 			dev_info(&pf->pdev->dev,
13971 				 "couldn't get PF vsi config, err %pe aq_err %s\n",
13972 				 ERR_PTR(ret),
13973 				 i40e_aq_str(&pf->hw,
13974 					     pf->hw.aq.asq_last_status));
13975 			return -ENOENT;
13976 		}
13977 		vsi->info = ctxt.info;
13978 		vsi->info.valid_sections = 0;
13979 
13980 		vsi->seid = ctxt.seid;
13981 		vsi->id = ctxt.vsi_number;
13982 
13983 		enabled_tc = i40e_pf_get_tc_map(pf);
13984 
13985 		/* Source pruning is enabled by default, so the flag is
13986 		 * negative logic - if it's set, we need to fiddle with
13987 		 * the VSI to disable source pruning.
13988 		 */
13989 		if (pf->flags & I40E_FLAG_SOURCE_PRUNING_DISABLED) {
13990 			memset(&ctxt, 0, sizeof(ctxt));
13991 			ctxt.seid = pf->main_vsi_seid;
13992 			ctxt.pf_num = pf->hw.pf_id;
13993 			ctxt.vf_num = 0;
13994 			ctxt.info.valid_sections |=
13995 				     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13996 			ctxt.info.switch_id =
13997 				   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13998 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13999 			if (ret) {
14000 				dev_info(&pf->pdev->dev,
14001 					 "update vsi failed, err %d aq_err %s\n",
14002 					 ret,
14003 					 i40e_aq_str(&pf->hw,
14004 						     pf->hw.aq.asq_last_status));
14005 				ret = -ENOENT;
14006 				goto err;
14007 			}
14008 		}
14009 
14010 		/* MFP mode setup queue map and update VSI */
14011 		if ((pf->flags & I40E_FLAG_MFP_ENABLED) &&
14012 		    !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
14013 			memset(&ctxt, 0, sizeof(ctxt));
14014 			ctxt.seid = pf->main_vsi_seid;
14015 			ctxt.pf_num = pf->hw.pf_id;
14016 			ctxt.vf_num = 0;
14017 			i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
14018 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
14019 			if (ret) {
14020 				dev_info(&pf->pdev->dev,
14021 					 "update vsi failed, err %pe aq_err %s\n",
14022 					 ERR_PTR(ret),
14023 					 i40e_aq_str(&pf->hw,
14024 						    pf->hw.aq.asq_last_status));
14025 				ret = -ENOENT;
14026 				goto err;
14027 			}
14028 			/* update the local VSI info queue map */
14029 			i40e_vsi_update_queue_map(vsi, &ctxt);
14030 			vsi->info.valid_sections = 0;
14031 		} else {
14032 			/* Default/Main VSI is only enabled for TC0
14033 			 * reconfigure it to enable all TCs that are
14034 			 * available on the port in SFP mode.
14035 			 * For MFP case the iSCSI PF would use this
14036 			 * flow to enable LAN+iSCSI TC.
14037 			 */
14038 			ret = i40e_vsi_config_tc(vsi, enabled_tc);
14039 			if (ret) {
14040 				/* Single TC condition is not fatal,
14041 				 * message and continue
14042 				 */
14043 				dev_info(&pf->pdev->dev,
14044 					 "failed to configure TCs for main VSI tc_map 0x%08x, err %pe aq_err %s\n",
14045 					 enabled_tc,
14046 					 ERR_PTR(ret),
14047 					 i40e_aq_str(&pf->hw,
14048 						    pf->hw.aq.asq_last_status));
14049 			}
14050 		}
14051 		break;
14052 
14053 	case I40E_VSI_FDIR:
14054 		ctxt.pf_num = hw->pf_id;
14055 		ctxt.vf_num = 0;
14056 		ctxt.uplink_seid = vsi->uplink_seid;
14057 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14058 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
14059 		if ((pf->flags & I40E_FLAG_VEB_MODE_ENABLED) &&
14060 		    (i40e_is_vsi_uplink_mode_veb(vsi))) {
14061 			ctxt.info.valid_sections |=
14062 			     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14063 			ctxt.info.switch_id =
14064 			   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14065 		}
14066 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14067 		break;
14068 
14069 	case I40E_VSI_VMDQ2:
14070 		ctxt.pf_num = hw->pf_id;
14071 		ctxt.vf_num = 0;
14072 		ctxt.uplink_seid = vsi->uplink_seid;
14073 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14074 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
14075 
14076 		/* This VSI is connected to VEB so the switch_id
14077 		 * should be set to zero by default.
14078 		 */
14079 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14080 			ctxt.info.valid_sections |=
14081 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14082 			ctxt.info.switch_id =
14083 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14084 		}
14085 
14086 		/* Setup the VSI tx/rx queue map for TC0 only for now */
14087 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14088 		break;
14089 
14090 	case I40E_VSI_SRIOV:
14091 		ctxt.pf_num = hw->pf_id;
14092 		ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
14093 		ctxt.uplink_seid = vsi->uplink_seid;
14094 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14095 		ctxt.flags = I40E_AQ_VSI_TYPE_VF;
14096 
14097 		/* This VSI is connected to VEB so the switch_id
14098 		 * should be set to zero by default.
14099 		 */
14100 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14101 			ctxt.info.valid_sections |=
14102 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14103 			ctxt.info.switch_id =
14104 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14105 		}
14106 
14107 		if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
14108 			ctxt.info.valid_sections |=
14109 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
14110 			ctxt.info.queueing_opt_flags |=
14111 				(I40E_AQ_VSI_QUE_OPT_TCP_ENA |
14112 				 I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
14113 		}
14114 
14115 		ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
14116 		ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
14117 		if (pf->vf[vsi->vf_id].spoofchk) {
14118 			ctxt.info.valid_sections |=
14119 				cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
14120 			ctxt.info.sec_flags |=
14121 				(I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
14122 				 I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
14123 		}
14124 		/* Setup the VSI tx/rx queue map for TC0 only for now */
14125 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14126 		break;
14127 
14128 	case I40E_VSI_IWARP:
14129 		/* send down message to iWARP */
14130 		break;
14131 
14132 	default:
14133 		return -ENODEV;
14134 	}
14135 
14136 	if (vsi->type != I40E_VSI_MAIN) {
14137 		ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
14138 		if (ret) {
14139 			dev_info(&vsi->back->pdev->dev,
14140 				 "add vsi failed, err %pe aq_err %s\n",
14141 				 ERR_PTR(ret),
14142 				 i40e_aq_str(&pf->hw,
14143 					     pf->hw.aq.asq_last_status));
14144 			ret = -ENOENT;
14145 			goto err;
14146 		}
14147 		vsi->info = ctxt.info;
14148 		vsi->info.valid_sections = 0;
14149 		vsi->seid = ctxt.seid;
14150 		vsi->id = ctxt.vsi_number;
14151 	}
14152 
14153 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14154 	vsi->active_filters = 0;
14155 	/* If macvlan filters already exist, force them to get loaded */
14156 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
14157 		f->state = I40E_FILTER_NEW;
14158 		f_count++;
14159 	}
14160 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14161 	clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
14162 
14163 	if (f_count) {
14164 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
14165 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
14166 	}
14167 
14168 	/* Update VSI BW information */
14169 	ret = i40e_vsi_get_bw_info(vsi);
14170 	if (ret) {
14171 		dev_info(&pf->pdev->dev,
14172 			 "couldn't get vsi bw info, err %pe aq_err %s\n",
14173 			 ERR_PTR(ret),
14174 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14175 		/* VSI is already added so not tearing that up */
14176 		ret = 0;
14177 	}
14178 
14179 err:
14180 	return ret;
14181 }
14182 
14183 /**
14184  * i40e_vsi_release - Delete a VSI and free its resources
14185  * @vsi: the VSI being removed
14186  *
14187  * Returns 0 on success or < 0 on error
14188  **/
14189 int i40e_vsi_release(struct i40e_vsi *vsi)
14190 {
14191 	struct i40e_mac_filter *f;
14192 	struct hlist_node *h;
14193 	struct i40e_veb *veb = NULL;
14194 	struct i40e_pf *pf;
14195 	u16 uplink_seid;
14196 	int i, n, bkt;
14197 
14198 	pf = vsi->back;
14199 
14200 	/* release of a VEB-owner or last VSI is not allowed */
14201 	if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
14202 		dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
14203 			 vsi->seid, vsi->uplink_seid);
14204 		return -ENODEV;
14205 	}
14206 	if (vsi == pf->vsi[pf->lan_vsi] &&
14207 	    !test_bit(__I40E_DOWN, pf->state)) {
14208 		dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
14209 		return -ENODEV;
14210 	}
14211 	set_bit(__I40E_VSI_RELEASING, vsi->state);
14212 	uplink_seid = vsi->uplink_seid;
14213 	if (vsi->type != I40E_VSI_SRIOV) {
14214 		if (vsi->netdev_registered) {
14215 			vsi->netdev_registered = false;
14216 			if (vsi->netdev) {
14217 				/* results in a call to i40e_close() */
14218 				unregister_netdev(vsi->netdev);
14219 			}
14220 		} else {
14221 			i40e_vsi_close(vsi);
14222 		}
14223 		i40e_vsi_disable_irq(vsi);
14224 	}
14225 
14226 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14227 
14228 	/* clear the sync flag on all filters */
14229 	if (vsi->netdev) {
14230 		__dev_uc_unsync(vsi->netdev, NULL);
14231 		__dev_mc_unsync(vsi->netdev, NULL);
14232 	}
14233 
14234 	/* make sure any remaining filters are marked for deletion */
14235 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
14236 		__i40e_del_filter(vsi, f);
14237 
14238 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14239 
14240 	i40e_sync_vsi_filters(vsi);
14241 
14242 	i40e_vsi_delete(vsi);
14243 	i40e_vsi_free_q_vectors(vsi);
14244 	if (vsi->netdev) {
14245 		free_netdev(vsi->netdev);
14246 		vsi->netdev = NULL;
14247 	}
14248 	i40e_vsi_clear_rings(vsi);
14249 	i40e_vsi_clear(vsi);
14250 
14251 	/* If this was the last thing on the VEB, except for the
14252 	 * controlling VSI, remove the VEB, which puts the controlling
14253 	 * VSI onto the next level down in the switch.
14254 	 *
14255 	 * Well, okay, there's one more exception here: don't remove
14256 	 * the orphan VEBs yet.  We'll wait for an explicit remove request
14257 	 * from up the network stack.
14258 	 */
14259 	for (n = 0, i = 0; i < pf->num_alloc_vsi; i++) {
14260 		if (pf->vsi[i] &&
14261 		    pf->vsi[i]->uplink_seid == uplink_seid &&
14262 		    (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14263 			n++;      /* count the VSIs */
14264 		}
14265 	}
14266 	for (i = 0; i < I40E_MAX_VEB; i++) {
14267 		if (!pf->veb[i])
14268 			continue;
14269 		if (pf->veb[i]->uplink_seid == uplink_seid)
14270 			n++;     /* count the VEBs */
14271 		if (pf->veb[i]->seid == uplink_seid)
14272 			veb = pf->veb[i];
14273 	}
14274 	if (n == 0 && veb && veb->uplink_seid != 0)
14275 		i40e_veb_release(veb);
14276 
14277 	return 0;
14278 }
14279 
14280 /**
14281  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
14282  * @vsi: ptr to the VSI
14283  *
14284  * This should only be called after i40e_vsi_mem_alloc() which allocates the
14285  * corresponding SW VSI structure and initializes num_queue_pairs for the
14286  * newly allocated VSI.
14287  *
14288  * Returns 0 on success or negative on failure
14289  **/
14290 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
14291 {
14292 	int ret = -ENOENT;
14293 	struct i40e_pf *pf = vsi->back;
14294 
14295 	if (vsi->q_vectors[0]) {
14296 		dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
14297 			 vsi->seid);
14298 		return -EEXIST;
14299 	}
14300 
14301 	if (vsi->base_vector) {
14302 		dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
14303 			 vsi->seid, vsi->base_vector);
14304 		return -EEXIST;
14305 	}
14306 
14307 	ret = i40e_vsi_alloc_q_vectors(vsi);
14308 	if (ret) {
14309 		dev_info(&pf->pdev->dev,
14310 			 "failed to allocate %d q_vector for VSI %d, ret=%d\n",
14311 			 vsi->num_q_vectors, vsi->seid, ret);
14312 		vsi->num_q_vectors = 0;
14313 		goto vector_setup_out;
14314 	}
14315 
14316 	/* In Legacy mode, we do not have to get any other vector since we
14317 	 * piggyback on the misc/ICR0 for queue interrupts.
14318 	*/
14319 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
14320 		return ret;
14321 	if (vsi->num_q_vectors)
14322 		vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
14323 						 vsi->num_q_vectors, vsi->idx);
14324 	if (vsi->base_vector < 0) {
14325 		dev_info(&pf->pdev->dev,
14326 			 "failed to get tracking for %d vectors for VSI %d, err=%d\n",
14327 			 vsi->num_q_vectors, vsi->seid, vsi->base_vector);
14328 		i40e_vsi_free_q_vectors(vsi);
14329 		ret = -ENOENT;
14330 		goto vector_setup_out;
14331 	}
14332 
14333 vector_setup_out:
14334 	return ret;
14335 }
14336 
14337 /**
14338  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
14339  * @vsi: pointer to the vsi.
14340  *
14341  * This re-allocates a vsi's queue resources.
14342  *
14343  * Returns pointer to the successfully allocated and configured VSI sw struct
14344  * on success, otherwise returns NULL on failure.
14345  **/
14346 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
14347 {
14348 	u16 alloc_queue_pairs;
14349 	struct i40e_pf *pf;
14350 	u8 enabled_tc;
14351 	int ret;
14352 
14353 	if (!vsi)
14354 		return NULL;
14355 
14356 	pf = vsi->back;
14357 
14358 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
14359 	i40e_vsi_clear_rings(vsi);
14360 
14361 	i40e_vsi_free_arrays(vsi, false);
14362 	i40e_set_num_rings_in_vsi(vsi);
14363 	ret = i40e_vsi_alloc_arrays(vsi, false);
14364 	if (ret)
14365 		goto err_vsi;
14366 
14367 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14368 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14369 
14370 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14371 	if (ret < 0) {
14372 		dev_info(&pf->pdev->dev,
14373 			 "failed to get tracking for %d queues for VSI %d err %d\n",
14374 			 alloc_queue_pairs, vsi->seid, ret);
14375 		goto err_vsi;
14376 	}
14377 	vsi->base_queue = ret;
14378 
14379 	/* Update the FW view of the VSI. Force a reset of TC and queue
14380 	 * layout configurations.
14381 	 */
14382 	enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
14383 	pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
14384 	pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
14385 	i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
14386 	if (vsi->type == I40E_VSI_MAIN)
14387 		i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
14388 
14389 	/* assign it some queues */
14390 	ret = i40e_alloc_rings(vsi);
14391 	if (ret)
14392 		goto err_rings;
14393 
14394 	/* map all of the rings to the q_vectors */
14395 	i40e_vsi_map_rings_to_vectors(vsi);
14396 	return vsi;
14397 
14398 err_rings:
14399 	i40e_vsi_free_q_vectors(vsi);
14400 	if (vsi->netdev_registered) {
14401 		vsi->netdev_registered = false;
14402 		unregister_netdev(vsi->netdev);
14403 		free_netdev(vsi->netdev);
14404 		vsi->netdev = NULL;
14405 	}
14406 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14407 err_vsi:
14408 	i40e_vsi_clear(vsi);
14409 	return NULL;
14410 }
14411 
14412 /**
14413  * i40e_vsi_setup - Set up a VSI by a given type
14414  * @pf: board private structure
14415  * @type: VSI type
14416  * @uplink_seid: the switch element to link to
14417  * @param1: usage depends upon VSI type. For VF types, indicates VF id
14418  *
14419  * This allocates the sw VSI structure and its queue resources, then add a VSI
14420  * to the identified VEB.
14421  *
14422  * Returns pointer to the successfully allocated and configure VSI sw struct on
14423  * success, otherwise returns NULL on failure.
14424  **/
14425 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
14426 				u16 uplink_seid, u32 param1)
14427 {
14428 	struct i40e_vsi *vsi = NULL;
14429 	struct i40e_veb *veb = NULL;
14430 	u16 alloc_queue_pairs;
14431 	int ret, i;
14432 	int v_idx;
14433 
14434 	/* The requested uplink_seid must be either
14435 	 *     - the PF's port seid
14436 	 *              no VEB is needed because this is the PF
14437 	 *              or this is a Flow Director special case VSI
14438 	 *     - seid of an existing VEB
14439 	 *     - seid of a VSI that owns an existing VEB
14440 	 *     - seid of a VSI that doesn't own a VEB
14441 	 *              a new VEB is created and the VSI becomes the owner
14442 	 *     - seid of the PF VSI, which is what creates the first VEB
14443 	 *              this is a special case of the previous
14444 	 *
14445 	 * Find which uplink_seid we were given and create a new VEB if needed
14446 	 */
14447 	for (i = 0; i < I40E_MAX_VEB; i++) {
14448 		if (pf->veb[i] && pf->veb[i]->seid == uplink_seid) {
14449 			veb = pf->veb[i];
14450 			break;
14451 		}
14452 	}
14453 
14454 	if (!veb && uplink_seid != pf->mac_seid) {
14455 
14456 		for (i = 0; i < pf->num_alloc_vsi; i++) {
14457 			if (pf->vsi[i] && pf->vsi[i]->seid == uplink_seid) {
14458 				vsi = pf->vsi[i];
14459 				break;
14460 			}
14461 		}
14462 		if (!vsi) {
14463 			dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
14464 				 uplink_seid);
14465 			return NULL;
14466 		}
14467 
14468 		if (vsi->uplink_seid == pf->mac_seid)
14469 			veb = i40e_veb_setup(pf, 0, pf->mac_seid, vsi->seid,
14470 					     vsi->tc_config.enabled_tc);
14471 		else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14472 			veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
14473 					     vsi->tc_config.enabled_tc);
14474 		if (veb) {
14475 			if (vsi->seid != pf->vsi[pf->lan_vsi]->seid) {
14476 				dev_info(&vsi->back->pdev->dev,
14477 					 "New VSI creation error, uplink seid of LAN VSI expected.\n");
14478 				return NULL;
14479 			}
14480 			/* We come up by default in VEPA mode if SRIOV is not
14481 			 * already enabled, in which case we can't force VEPA
14482 			 * mode.
14483 			 */
14484 			if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
14485 				veb->bridge_mode = BRIDGE_MODE_VEPA;
14486 				pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
14487 			}
14488 			i40e_config_bridge_mode(veb);
14489 		}
14490 		for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
14491 			if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
14492 				veb = pf->veb[i];
14493 		}
14494 		if (!veb) {
14495 			dev_info(&pf->pdev->dev, "couldn't add VEB\n");
14496 			return NULL;
14497 		}
14498 
14499 		vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14500 		uplink_seid = veb->seid;
14501 	}
14502 
14503 	/* get vsi sw struct */
14504 	v_idx = i40e_vsi_mem_alloc(pf, type);
14505 	if (v_idx < 0)
14506 		goto err_alloc;
14507 	vsi = pf->vsi[v_idx];
14508 	if (!vsi)
14509 		goto err_alloc;
14510 	vsi->type = type;
14511 	vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
14512 
14513 	if (type == I40E_VSI_MAIN)
14514 		pf->lan_vsi = v_idx;
14515 	else if (type == I40E_VSI_SRIOV)
14516 		vsi->vf_id = param1;
14517 	/* assign it some queues */
14518 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14519 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14520 
14521 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14522 	if (ret < 0) {
14523 		dev_info(&pf->pdev->dev,
14524 			 "failed to get tracking for %d queues for VSI %d err=%d\n",
14525 			 alloc_queue_pairs, vsi->seid, ret);
14526 		goto err_vsi;
14527 	}
14528 	vsi->base_queue = ret;
14529 
14530 	/* get a VSI from the hardware */
14531 	vsi->uplink_seid = uplink_seid;
14532 	ret = i40e_add_vsi(vsi);
14533 	if (ret)
14534 		goto err_vsi;
14535 
14536 	switch (vsi->type) {
14537 	/* setup the netdev if needed */
14538 	case I40E_VSI_MAIN:
14539 	case I40E_VSI_VMDQ2:
14540 		ret = i40e_config_netdev(vsi);
14541 		if (ret)
14542 			goto err_netdev;
14543 		ret = i40e_netif_set_realnum_tx_rx_queues(vsi);
14544 		if (ret)
14545 			goto err_netdev;
14546 		ret = register_netdev(vsi->netdev);
14547 		if (ret)
14548 			goto err_netdev;
14549 		vsi->netdev_registered = true;
14550 		netif_carrier_off(vsi->netdev);
14551 #ifdef CONFIG_I40E_DCB
14552 		/* Setup DCB netlink interface */
14553 		i40e_dcbnl_setup(vsi);
14554 #endif /* CONFIG_I40E_DCB */
14555 		fallthrough;
14556 	case I40E_VSI_FDIR:
14557 		/* set up vectors and rings if needed */
14558 		ret = i40e_vsi_setup_vectors(vsi);
14559 		if (ret)
14560 			goto err_msix;
14561 
14562 		ret = i40e_alloc_rings(vsi);
14563 		if (ret)
14564 			goto err_rings;
14565 
14566 		/* map all of the rings to the q_vectors */
14567 		i40e_vsi_map_rings_to_vectors(vsi);
14568 
14569 		i40e_vsi_reset_stats(vsi);
14570 		break;
14571 	default:
14572 		/* no netdev or rings for the other VSI types */
14573 		break;
14574 	}
14575 
14576 	if ((pf->hw_features & I40E_HW_RSS_AQ_CAPABLE) &&
14577 	    (vsi->type == I40E_VSI_VMDQ2)) {
14578 		ret = i40e_vsi_config_rss(vsi);
14579 	}
14580 	return vsi;
14581 
14582 err_rings:
14583 	i40e_vsi_free_q_vectors(vsi);
14584 err_msix:
14585 	if (vsi->netdev_registered) {
14586 		vsi->netdev_registered = false;
14587 		unregister_netdev(vsi->netdev);
14588 		free_netdev(vsi->netdev);
14589 		vsi->netdev = NULL;
14590 	}
14591 err_netdev:
14592 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14593 err_vsi:
14594 	i40e_vsi_clear(vsi);
14595 err_alloc:
14596 	return NULL;
14597 }
14598 
14599 /**
14600  * i40e_veb_get_bw_info - Query VEB BW information
14601  * @veb: the veb to query
14602  *
14603  * Query the Tx scheduler BW configuration data for given VEB
14604  **/
14605 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
14606 {
14607 	struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
14608 	struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
14609 	struct i40e_pf *pf = veb->pf;
14610 	struct i40e_hw *hw = &pf->hw;
14611 	u32 tc_bw_max;
14612 	int ret = 0;
14613 	int i;
14614 
14615 	ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
14616 						  &bw_data, NULL);
14617 	if (ret) {
14618 		dev_info(&pf->pdev->dev,
14619 			 "query veb bw config failed, err %pe aq_err %s\n",
14620 			 ERR_PTR(ret),
14621 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14622 		goto out;
14623 	}
14624 
14625 	ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
14626 						   &ets_data, NULL);
14627 	if (ret) {
14628 		dev_info(&pf->pdev->dev,
14629 			 "query veb bw ets config failed, err %pe aq_err %s\n",
14630 			 ERR_PTR(ret),
14631 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14632 		goto out;
14633 	}
14634 
14635 	veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
14636 	veb->bw_max_quanta = ets_data.tc_bw_max;
14637 	veb->is_abs_credits = bw_data.absolute_credits_enable;
14638 	veb->enabled_tc = ets_data.tc_valid_bits;
14639 	tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
14640 		    (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
14641 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
14642 		veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
14643 		veb->bw_tc_limit_credits[i] =
14644 					le16_to_cpu(bw_data.tc_bw_limits[i]);
14645 		veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
14646 	}
14647 
14648 out:
14649 	return ret;
14650 }
14651 
14652 /**
14653  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
14654  * @pf: board private structure
14655  *
14656  * On error: returns error code (negative)
14657  * On success: returns vsi index in PF (positive)
14658  **/
14659 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
14660 {
14661 	int ret = -ENOENT;
14662 	struct i40e_veb *veb;
14663 	int i;
14664 
14665 	/* Need to protect the allocation of switch elements at the PF level */
14666 	mutex_lock(&pf->switch_mutex);
14667 
14668 	/* VEB list may be fragmented if VEB creation/destruction has
14669 	 * been happening.  We can afford to do a quick scan to look
14670 	 * for any free slots in the list.
14671 	 *
14672 	 * find next empty veb slot, looping back around if necessary
14673 	 */
14674 	i = 0;
14675 	while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
14676 		i++;
14677 	if (i >= I40E_MAX_VEB) {
14678 		ret = -ENOMEM;
14679 		goto err_alloc_veb;  /* out of VEB slots! */
14680 	}
14681 
14682 	veb = kzalloc(sizeof(*veb), GFP_KERNEL);
14683 	if (!veb) {
14684 		ret = -ENOMEM;
14685 		goto err_alloc_veb;
14686 	}
14687 	veb->pf = pf;
14688 	veb->idx = i;
14689 	veb->enabled_tc = 1;
14690 
14691 	pf->veb[i] = veb;
14692 	ret = i;
14693 err_alloc_veb:
14694 	mutex_unlock(&pf->switch_mutex);
14695 	return ret;
14696 }
14697 
14698 /**
14699  * i40e_switch_branch_release - Delete a branch of the switch tree
14700  * @branch: where to start deleting
14701  *
14702  * This uses recursion to find the tips of the branch to be
14703  * removed, deleting until we get back to and can delete this VEB.
14704  **/
14705 static void i40e_switch_branch_release(struct i40e_veb *branch)
14706 {
14707 	struct i40e_pf *pf = branch->pf;
14708 	u16 branch_seid = branch->seid;
14709 	u16 veb_idx = branch->idx;
14710 	int i;
14711 
14712 	/* release any VEBs on this VEB - RECURSION */
14713 	for (i = 0; i < I40E_MAX_VEB; i++) {
14714 		if (!pf->veb[i])
14715 			continue;
14716 		if (pf->veb[i]->uplink_seid == branch->seid)
14717 			i40e_switch_branch_release(pf->veb[i]);
14718 	}
14719 
14720 	/* Release the VSIs on this VEB, but not the owner VSI.
14721 	 *
14722 	 * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
14723 	 *       the VEB itself, so don't use (*branch) after this loop.
14724 	 */
14725 	for (i = 0; i < pf->num_alloc_vsi; i++) {
14726 		if (!pf->vsi[i])
14727 			continue;
14728 		if (pf->vsi[i]->uplink_seid == branch_seid &&
14729 		   (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14730 			i40e_vsi_release(pf->vsi[i]);
14731 		}
14732 	}
14733 
14734 	/* There's one corner case where the VEB might not have been
14735 	 * removed, so double check it here and remove it if needed.
14736 	 * This case happens if the veb was created from the debugfs
14737 	 * commands and no VSIs were added to it.
14738 	 */
14739 	if (pf->veb[veb_idx])
14740 		i40e_veb_release(pf->veb[veb_idx]);
14741 }
14742 
14743 /**
14744  * i40e_veb_clear - remove veb struct
14745  * @veb: the veb to remove
14746  **/
14747 static void i40e_veb_clear(struct i40e_veb *veb)
14748 {
14749 	if (!veb)
14750 		return;
14751 
14752 	if (veb->pf) {
14753 		struct i40e_pf *pf = veb->pf;
14754 
14755 		mutex_lock(&pf->switch_mutex);
14756 		if (pf->veb[veb->idx] == veb)
14757 			pf->veb[veb->idx] = NULL;
14758 		mutex_unlock(&pf->switch_mutex);
14759 	}
14760 
14761 	kfree(veb);
14762 }
14763 
14764 /**
14765  * i40e_veb_release - Delete a VEB and free its resources
14766  * @veb: the VEB being removed
14767  **/
14768 void i40e_veb_release(struct i40e_veb *veb)
14769 {
14770 	struct i40e_vsi *vsi = NULL;
14771 	struct i40e_pf *pf;
14772 	int i, n = 0;
14773 
14774 	pf = veb->pf;
14775 
14776 	/* find the remaining VSI and check for extras */
14777 	for (i = 0; i < pf->num_alloc_vsi; i++) {
14778 		if (pf->vsi[i] && pf->vsi[i]->uplink_seid == veb->seid) {
14779 			n++;
14780 			vsi = pf->vsi[i];
14781 		}
14782 	}
14783 	if (n != 1) {
14784 		dev_info(&pf->pdev->dev,
14785 			 "can't remove VEB %d with %d VSIs left\n",
14786 			 veb->seid, n);
14787 		return;
14788 	}
14789 
14790 	/* move the remaining VSI to uplink veb */
14791 	vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
14792 	if (veb->uplink_seid) {
14793 		vsi->uplink_seid = veb->uplink_seid;
14794 		if (veb->uplink_seid == pf->mac_seid)
14795 			vsi->veb_idx = I40E_NO_VEB;
14796 		else
14797 			vsi->veb_idx = veb->veb_idx;
14798 	} else {
14799 		/* floating VEB */
14800 		vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
14801 		vsi->veb_idx = pf->vsi[pf->lan_vsi]->veb_idx;
14802 	}
14803 
14804 	i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14805 	i40e_veb_clear(veb);
14806 }
14807 
14808 /**
14809  * i40e_add_veb - create the VEB in the switch
14810  * @veb: the VEB to be instantiated
14811  * @vsi: the controlling VSI
14812  **/
14813 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
14814 {
14815 	struct i40e_pf *pf = veb->pf;
14816 	bool enable_stats = !!(pf->flags & I40E_FLAG_VEB_STATS_ENABLED);
14817 	int ret;
14818 
14819 	ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi->seid,
14820 			      veb->enabled_tc, false,
14821 			      &veb->seid, enable_stats, NULL);
14822 
14823 	/* get a VEB from the hardware */
14824 	if (ret) {
14825 		dev_info(&pf->pdev->dev,
14826 			 "couldn't add VEB, err %pe aq_err %s\n",
14827 			 ERR_PTR(ret),
14828 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14829 		return -EPERM;
14830 	}
14831 
14832 	/* get statistics counter */
14833 	ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
14834 					 &veb->stats_idx, NULL, NULL, NULL);
14835 	if (ret) {
14836 		dev_info(&pf->pdev->dev,
14837 			 "couldn't get VEB statistics idx, err %pe aq_err %s\n",
14838 			 ERR_PTR(ret),
14839 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14840 		return -EPERM;
14841 	}
14842 	ret = i40e_veb_get_bw_info(veb);
14843 	if (ret) {
14844 		dev_info(&pf->pdev->dev,
14845 			 "couldn't get VEB bw info, err %pe aq_err %s\n",
14846 			 ERR_PTR(ret),
14847 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14848 		i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14849 		return -ENOENT;
14850 	}
14851 
14852 	vsi->uplink_seid = veb->seid;
14853 	vsi->veb_idx = veb->idx;
14854 	vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14855 
14856 	return 0;
14857 }
14858 
14859 /**
14860  * i40e_veb_setup - Set up a VEB
14861  * @pf: board private structure
14862  * @flags: VEB setup flags
14863  * @uplink_seid: the switch element to link to
14864  * @vsi_seid: the initial VSI seid
14865  * @enabled_tc: Enabled TC bit-map
14866  *
14867  * This allocates the sw VEB structure and links it into the switch
14868  * It is possible and legal for this to be a duplicate of an already
14869  * existing VEB.  It is also possible for both uplink and vsi seids
14870  * to be zero, in order to create a floating VEB.
14871  *
14872  * Returns pointer to the successfully allocated VEB sw struct on
14873  * success, otherwise returns NULL on failure.
14874  **/
14875 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 flags,
14876 				u16 uplink_seid, u16 vsi_seid,
14877 				u8 enabled_tc)
14878 {
14879 	struct i40e_veb *veb, *uplink_veb = NULL;
14880 	int vsi_idx, veb_idx;
14881 	int ret;
14882 
14883 	/* if one seid is 0, the other must be 0 to create a floating relay */
14884 	if ((uplink_seid == 0 || vsi_seid == 0) &&
14885 	    (uplink_seid + vsi_seid != 0)) {
14886 		dev_info(&pf->pdev->dev,
14887 			 "one, not both seid's are 0: uplink=%d vsi=%d\n",
14888 			 uplink_seid, vsi_seid);
14889 		return NULL;
14890 	}
14891 
14892 	/* make sure there is such a vsi and uplink */
14893 	for (vsi_idx = 0; vsi_idx < pf->num_alloc_vsi; vsi_idx++)
14894 		if (pf->vsi[vsi_idx] && pf->vsi[vsi_idx]->seid == vsi_seid)
14895 			break;
14896 	if (vsi_idx == pf->num_alloc_vsi && vsi_seid != 0) {
14897 		dev_info(&pf->pdev->dev, "vsi seid %d not found\n",
14898 			 vsi_seid);
14899 		return NULL;
14900 	}
14901 
14902 	if (uplink_seid && uplink_seid != pf->mac_seid) {
14903 		for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
14904 			if (pf->veb[veb_idx] &&
14905 			    pf->veb[veb_idx]->seid == uplink_seid) {
14906 				uplink_veb = pf->veb[veb_idx];
14907 				break;
14908 			}
14909 		}
14910 		if (!uplink_veb) {
14911 			dev_info(&pf->pdev->dev,
14912 				 "uplink seid %d not found\n", uplink_seid);
14913 			return NULL;
14914 		}
14915 	}
14916 
14917 	/* get veb sw struct */
14918 	veb_idx = i40e_veb_mem_alloc(pf);
14919 	if (veb_idx < 0)
14920 		goto err_alloc;
14921 	veb = pf->veb[veb_idx];
14922 	veb->flags = flags;
14923 	veb->uplink_seid = uplink_seid;
14924 	veb->veb_idx = (uplink_veb ? uplink_veb->idx : I40E_NO_VEB);
14925 	veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14926 
14927 	/* create the VEB in the switch */
14928 	ret = i40e_add_veb(veb, pf->vsi[vsi_idx]);
14929 	if (ret)
14930 		goto err_veb;
14931 	if (vsi_idx == pf->lan_vsi)
14932 		pf->lan_veb = veb->idx;
14933 
14934 	return veb;
14935 
14936 err_veb:
14937 	i40e_veb_clear(veb);
14938 err_alloc:
14939 	return NULL;
14940 }
14941 
14942 /**
14943  * i40e_setup_pf_switch_element - set PF vars based on switch type
14944  * @pf: board private structure
14945  * @ele: element we are building info from
14946  * @num_reported: total number of elements
14947  * @printconfig: should we print the contents
14948  *
14949  * helper function to assist in extracting a few useful SEID values.
14950  **/
14951 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14952 				struct i40e_aqc_switch_config_element_resp *ele,
14953 				u16 num_reported, bool printconfig)
14954 {
14955 	u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14956 	u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14957 	u8 element_type = ele->element_type;
14958 	u16 seid = le16_to_cpu(ele->seid);
14959 
14960 	if (printconfig)
14961 		dev_info(&pf->pdev->dev,
14962 			 "type=%d seid=%d uplink=%d downlink=%d\n",
14963 			 element_type, seid, uplink_seid, downlink_seid);
14964 
14965 	switch (element_type) {
14966 	case I40E_SWITCH_ELEMENT_TYPE_MAC:
14967 		pf->mac_seid = seid;
14968 		break;
14969 	case I40E_SWITCH_ELEMENT_TYPE_VEB:
14970 		/* Main VEB? */
14971 		if (uplink_seid != pf->mac_seid)
14972 			break;
14973 		if (pf->lan_veb >= I40E_MAX_VEB) {
14974 			int v;
14975 
14976 			/* find existing or else empty VEB */
14977 			for (v = 0; v < I40E_MAX_VEB; v++) {
14978 				if (pf->veb[v] && (pf->veb[v]->seid == seid)) {
14979 					pf->lan_veb = v;
14980 					break;
14981 				}
14982 			}
14983 			if (pf->lan_veb >= I40E_MAX_VEB) {
14984 				v = i40e_veb_mem_alloc(pf);
14985 				if (v < 0)
14986 					break;
14987 				pf->lan_veb = v;
14988 			}
14989 		}
14990 		if (pf->lan_veb >= I40E_MAX_VEB)
14991 			break;
14992 
14993 		pf->veb[pf->lan_veb]->seid = seid;
14994 		pf->veb[pf->lan_veb]->uplink_seid = pf->mac_seid;
14995 		pf->veb[pf->lan_veb]->pf = pf;
14996 		pf->veb[pf->lan_veb]->veb_idx = I40E_NO_VEB;
14997 		break;
14998 	case I40E_SWITCH_ELEMENT_TYPE_VSI:
14999 		if (num_reported != 1)
15000 			break;
15001 		/* This is immediately after a reset so we can assume this is
15002 		 * the PF's VSI
15003 		 */
15004 		pf->mac_seid = uplink_seid;
15005 		pf->pf_seid = downlink_seid;
15006 		pf->main_vsi_seid = seid;
15007 		if (printconfig)
15008 			dev_info(&pf->pdev->dev,
15009 				 "pf_seid=%d main_vsi_seid=%d\n",
15010 				 pf->pf_seid, pf->main_vsi_seid);
15011 		break;
15012 	case I40E_SWITCH_ELEMENT_TYPE_PF:
15013 	case I40E_SWITCH_ELEMENT_TYPE_VF:
15014 	case I40E_SWITCH_ELEMENT_TYPE_EMP:
15015 	case I40E_SWITCH_ELEMENT_TYPE_BMC:
15016 	case I40E_SWITCH_ELEMENT_TYPE_PE:
15017 	case I40E_SWITCH_ELEMENT_TYPE_PA:
15018 		/* ignore these for now */
15019 		break;
15020 	default:
15021 		dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
15022 			 element_type, seid);
15023 		break;
15024 	}
15025 }
15026 
15027 /**
15028  * i40e_fetch_switch_configuration - Get switch config from firmware
15029  * @pf: board private structure
15030  * @printconfig: should we print the contents
15031  *
15032  * Get the current switch configuration from the device and
15033  * extract a few useful SEID values.
15034  **/
15035 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
15036 {
15037 	struct i40e_aqc_get_switch_config_resp *sw_config;
15038 	u16 next_seid = 0;
15039 	int ret = 0;
15040 	u8 *aq_buf;
15041 	int i;
15042 
15043 	aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
15044 	if (!aq_buf)
15045 		return -ENOMEM;
15046 
15047 	sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
15048 	do {
15049 		u16 num_reported, num_total;
15050 
15051 		ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
15052 						I40E_AQ_LARGE_BUF,
15053 						&next_seid, NULL);
15054 		if (ret) {
15055 			dev_info(&pf->pdev->dev,
15056 				 "get switch config failed err %d aq_err %s\n",
15057 				 ret,
15058 				 i40e_aq_str(&pf->hw,
15059 					     pf->hw.aq.asq_last_status));
15060 			kfree(aq_buf);
15061 			return -ENOENT;
15062 		}
15063 
15064 		num_reported = le16_to_cpu(sw_config->header.num_reported);
15065 		num_total = le16_to_cpu(sw_config->header.num_total);
15066 
15067 		if (printconfig)
15068 			dev_info(&pf->pdev->dev,
15069 				 "header: %d reported %d total\n",
15070 				 num_reported, num_total);
15071 
15072 		for (i = 0; i < num_reported; i++) {
15073 			struct i40e_aqc_switch_config_element_resp *ele =
15074 				&sw_config->element[i];
15075 
15076 			i40e_setup_pf_switch_element(pf, ele, num_reported,
15077 						     printconfig);
15078 		}
15079 	} while (next_seid != 0);
15080 
15081 	kfree(aq_buf);
15082 	return ret;
15083 }
15084 
15085 /**
15086  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
15087  * @pf: board private structure
15088  * @reinit: if the Main VSI needs to re-initialized.
15089  * @lock_acquired: indicates whether or not the lock has been acquired
15090  *
15091  * Returns 0 on success, negative value on failure
15092  **/
15093 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired)
15094 {
15095 	u16 flags = 0;
15096 	int ret;
15097 
15098 	/* find out what's out there already */
15099 	ret = i40e_fetch_switch_configuration(pf, false);
15100 	if (ret) {
15101 		dev_info(&pf->pdev->dev,
15102 			 "couldn't fetch switch config, err %pe aq_err %s\n",
15103 			 ERR_PTR(ret),
15104 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15105 		return ret;
15106 	}
15107 	i40e_pf_reset_stats(pf);
15108 
15109 	/* set the switch config bit for the whole device to
15110 	 * support limited promisc or true promisc
15111 	 * when user requests promisc. The default is limited
15112 	 * promisc.
15113 	*/
15114 
15115 	if ((pf->hw.pf_id == 0) &&
15116 	    !(pf->flags & I40E_FLAG_TRUE_PROMISC_SUPPORT)) {
15117 		flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15118 		pf->last_sw_conf_flags = flags;
15119 	}
15120 
15121 	if (pf->hw.pf_id == 0) {
15122 		u16 valid_flags;
15123 
15124 		valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15125 		ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
15126 						NULL);
15127 		if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
15128 			dev_info(&pf->pdev->dev,
15129 				 "couldn't set switch config bits, err %pe aq_err %s\n",
15130 				 ERR_PTR(ret),
15131 				 i40e_aq_str(&pf->hw,
15132 					     pf->hw.aq.asq_last_status));
15133 			/* not a fatal problem, just keep going */
15134 		}
15135 		pf->last_sw_conf_valid_flags = valid_flags;
15136 	}
15137 
15138 	/* first time setup */
15139 	if (pf->lan_vsi == I40E_NO_VSI || reinit) {
15140 		struct i40e_vsi *vsi = NULL;
15141 		u16 uplink_seid;
15142 
15143 		/* Set up the PF VSI associated with the PF's main VSI
15144 		 * that is already in the HW switch
15145 		 */
15146 		if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
15147 			uplink_seid = pf->veb[pf->lan_veb]->seid;
15148 		else
15149 			uplink_seid = pf->mac_seid;
15150 		if (pf->lan_vsi == I40E_NO_VSI)
15151 			vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN, uplink_seid, 0);
15152 		else if (reinit)
15153 			vsi = i40e_vsi_reinit_setup(pf->vsi[pf->lan_vsi]);
15154 		if (!vsi) {
15155 			dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
15156 			i40e_cloud_filter_exit(pf);
15157 			i40e_fdir_teardown(pf);
15158 			return -EAGAIN;
15159 		}
15160 	} else {
15161 		/* force a reset of TC and queue layout configurations */
15162 		u8 enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
15163 
15164 		pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
15165 		pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
15166 		i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
15167 	}
15168 	i40e_vlan_stripping_disable(pf->vsi[pf->lan_vsi]);
15169 
15170 	i40e_fdir_sb_setup(pf);
15171 
15172 	/* Setup static PF queue filter control settings */
15173 	ret = i40e_setup_pf_filter_control(pf);
15174 	if (ret) {
15175 		dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
15176 			 ret);
15177 		/* Failure here should not stop continuing other steps */
15178 	}
15179 
15180 	/* enable RSS in the HW, even for only one queue, as the stack can use
15181 	 * the hash
15182 	 */
15183 	if ((pf->flags & I40E_FLAG_RSS_ENABLED))
15184 		i40e_pf_config_rss(pf);
15185 
15186 	/* fill in link information and enable LSE reporting */
15187 	i40e_link_event(pf);
15188 
15189 	/* Initialize user-specific link properties */
15190 	pf->fc_autoneg_status = ((pf->hw.phy.link_info.an_info &
15191 				  I40E_AQ_AN_COMPLETED) ? true : false);
15192 
15193 	i40e_ptp_init(pf);
15194 
15195 	if (!lock_acquired)
15196 		rtnl_lock();
15197 
15198 	/* repopulate tunnel port filters */
15199 	udp_tunnel_nic_reset_ntf(pf->vsi[pf->lan_vsi]->netdev);
15200 
15201 	if (!lock_acquired)
15202 		rtnl_unlock();
15203 
15204 	return ret;
15205 }
15206 
15207 /**
15208  * i40e_determine_queue_usage - Work out queue distribution
15209  * @pf: board private structure
15210  **/
15211 static void i40e_determine_queue_usage(struct i40e_pf *pf)
15212 {
15213 	int queues_left;
15214 	int q_max;
15215 
15216 	pf->num_lan_qps = 0;
15217 
15218 	/* Find the max queues to be put into basic use.  We'll always be
15219 	 * using TC0, whether or not DCB is running, and TC0 will get the
15220 	 * big RSS set.
15221 	 */
15222 	queues_left = pf->hw.func_caps.num_tx_qp;
15223 
15224 	if ((queues_left == 1) ||
15225 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED)) {
15226 		/* one qp for PF, no queues for anything else */
15227 		queues_left = 0;
15228 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15229 
15230 		/* make sure all the fancies are disabled */
15231 		pf->flags &= ~(I40E_FLAG_RSS_ENABLED	|
15232 			       I40E_FLAG_IWARP_ENABLED	|
15233 			       I40E_FLAG_FD_SB_ENABLED	|
15234 			       I40E_FLAG_FD_ATR_ENABLED	|
15235 			       I40E_FLAG_DCB_CAPABLE	|
15236 			       I40E_FLAG_DCB_ENABLED	|
15237 			       I40E_FLAG_SRIOV_ENABLED	|
15238 			       I40E_FLAG_VMDQ_ENABLED);
15239 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15240 	} else if (!(pf->flags & (I40E_FLAG_RSS_ENABLED |
15241 				  I40E_FLAG_FD_SB_ENABLED |
15242 				  I40E_FLAG_FD_ATR_ENABLED |
15243 				  I40E_FLAG_DCB_CAPABLE))) {
15244 		/* one qp for PF */
15245 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15246 		queues_left -= pf->num_lan_qps;
15247 
15248 		pf->flags &= ~(I40E_FLAG_RSS_ENABLED	|
15249 			       I40E_FLAG_IWARP_ENABLED	|
15250 			       I40E_FLAG_FD_SB_ENABLED	|
15251 			       I40E_FLAG_FD_ATR_ENABLED	|
15252 			       I40E_FLAG_DCB_ENABLED	|
15253 			       I40E_FLAG_VMDQ_ENABLED);
15254 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15255 	} else {
15256 		/* Not enough queues for all TCs */
15257 		if ((pf->flags & I40E_FLAG_DCB_CAPABLE) &&
15258 		    (queues_left < I40E_MAX_TRAFFIC_CLASS)) {
15259 			pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
15260 					I40E_FLAG_DCB_ENABLED);
15261 			dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
15262 		}
15263 
15264 		/* limit lan qps to the smaller of qps, cpus or msix */
15265 		q_max = max_t(int, pf->rss_size_max, num_online_cpus());
15266 		q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
15267 		q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
15268 		pf->num_lan_qps = q_max;
15269 
15270 		queues_left -= pf->num_lan_qps;
15271 	}
15272 
15273 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15274 		if (queues_left > 1) {
15275 			queues_left -= 1; /* save 1 queue for FD */
15276 		} else {
15277 			pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
15278 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15279 			dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
15280 		}
15281 	}
15282 
15283 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15284 	    pf->num_vf_qps && pf->num_req_vfs && queues_left) {
15285 		pf->num_req_vfs = min_t(int, pf->num_req_vfs,
15286 					(queues_left / pf->num_vf_qps));
15287 		queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
15288 	}
15289 
15290 	if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
15291 	    pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
15292 		pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
15293 					  (queues_left / pf->num_vmdq_qps));
15294 		queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
15295 	}
15296 
15297 	pf->queues_left = queues_left;
15298 	dev_dbg(&pf->pdev->dev,
15299 		"qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
15300 		pf->hw.func_caps.num_tx_qp,
15301 		!!(pf->flags & I40E_FLAG_FD_SB_ENABLED),
15302 		pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
15303 		pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
15304 		queues_left);
15305 }
15306 
15307 /**
15308  * i40e_setup_pf_filter_control - Setup PF static filter control
15309  * @pf: PF to be setup
15310  *
15311  * i40e_setup_pf_filter_control sets up a PF's initial filter control
15312  * settings. If PE/FCoE are enabled then it will also set the per PF
15313  * based filter sizes required for them. It also enables Flow director,
15314  * ethertype and macvlan type filter settings for the pf.
15315  *
15316  * Returns 0 on success, negative on failure
15317  **/
15318 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
15319 {
15320 	struct i40e_filter_control_settings *settings = &pf->filter_settings;
15321 
15322 	settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
15323 
15324 	/* Flow Director is enabled */
15325 	if (pf->flags & (I40E_FLAG_FD_SB_ENABLED | I40E_FLAG_FD_ATR_ENABLED))
15326 		settings->enable_fdir = true;
15327 
15328 	/* Ethtype and MACVLAN filters enabled for PF */
15329 	settings->enable_ethtype = true;
15330 	settings->enable_macvlan = true;
15331 
15332 	if (i40e_set_filter_control(&pf->hw, settings))
15333 		return -ENOENT;
15334 
15335 	return 0;
15336 }
15337 
15338 #define INFO_STRING_LEN 255
15339 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
15340 static void i40e_print_features(struct i40e_pf *pf)
15341 {
15342 	struct i40e_hw *hw = &pf->hw;
15343 	char *buf;
15344 	int i;
15345 
15346 	buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
15347 	if (!buf)
15348 		return;
15349 
15350 	i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
15351 #ifdef CONFIG_PCI_IOV
15352 	i += scnprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
15353 #endif
15354 	i += scnprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
15355 		      pf->hw.func_caps.num_vsis,
15356 		      pf->vsi[pf->lan_vsi]->num_queue_pairs);
15357 	if (pf->flags & I40E_FLAG_RSS_ENABLED)
15358 		i += scnprintf(&buf[i], REMAIN(i), " RSS");
15359 	if (pf->flags & I40E_FLAG_FD_ATR_ENABLED)
15360 		i += scnprintf(&buf[i], REMAIN(i), " FD_ATR");
15361 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15362 		i += scnprintf(&buf[i], REMAIN(i), " FD_SB");
15363 		i += scnprintf(&buf[i], REMAIN(i), " NTUPLE");
15364 	}
15365 	if (pf->flags & I40E_FLAG_DCB_CAPABLE)
15366 		i += scnprintf(&buf[i], REMAIN(i), " DCB");
15367 	i += scnprintf(&buf[i], REMAIN(i), " VxLAN");
15368 	i += scnprintf(&buf[i], REMAIN(i), " Geneve");
15369 	if (pf->flags & I40E_FLAG_PTP)
15370 		i += scnprintf(&buf[i], REMAIN(i), " PTP");
15371 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
15372 		i += scnprintf(&buf[i], REMAIN(i), " VEB");
15373 	else
15374 		i += scnprintf(&buf[i], REMAIN(i), " VEPA");
15375 
15376 	dev_info(&pf->pdev->dev, "%s\n", buf);
15377 	kfree(buf);
15378 	WARN_ON(i > INFO_STRING_LEN);
15379 }
15380 
15381 /**
15382  * i40e_get_platform_mac_addr - get platform-specific MAC address
15383  * @pdev: PCI device information struct
15384  * @pf: board private structure
15385  *
15386  * Look up the MAC address for the device. First we'll try
15387  * eth_platform_get_mac_address, which will check Open Firmware, or arch
15388  * specific fallback. Otherwise, we'll default to the stored value in
15389  * firmware.
15390  **/
15391 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
15392 {
15393 	if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
15394 		i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
15395 }
15396 
15397 /**
15398  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
15399  * @fec_cfg: FEC option to set in flags
15400  * @flags: ptr to flags in which we set FEC option
15401  **/
15402 void i40e_set_fec_in_flags(u8 fec_cfg, u32 *flags)
15403 {
15404 	if (fec_cfg & I40E_AQ_SET_FEC_AUTO)
15405 		*flags |= I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC;
15406 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
15407 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
15408 		*flags |= I40E_FLAG_RS_FEC;
15409 		*flags &= ~I40E_FLAG_BASE_R_FEC;
15410 	}
15411 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
15412 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
15413 		*flags |= I40E_FLAG_BASE_R_FEC;
15414 		*flags &= ~I40E_FLAG_RS_FEC;
15415 	}
15416 	if (fec_cfg == 0)
15417 		*flags &= ~(I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC);
15418 }
15419 
15420 /**
15421  * i40e_check_recovery_mode - check if we are running transition firmware
15422  * @pf: board private structure
15423  *
15424  * Check registers indicating the firmware runs in recovery mode. Sets the
15425  * appropriate driver state.
15426  *
15427  * Returns true if the recovery mode was detected, false otherwise
15428  **/
15429 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
15430 {
15431 	u32 val = rd32(&pf->hw, I40E_GL_FWSTS);
15432 
15433 	if (val & I40E_GL_FWSTS_FWS1B_MASK) {
15434 		dev_crit(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
15435 		dev_crit(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
15436 		set_bit(__I40E_RECOVERY_MODE, pf->state);
15437 
15438 		return true;
15439 	}
15440 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15441 		dev_info(&pf->pdev->dev, "Please do Power-On Reset to initialize adapter in normal mode with full functionality.\n");
15442 
15443 	return false;
15444 }
15445 
15446 /**
15447  * i40e_pf_loop_reset - perform reset in a loop.
15448  * @pf: board private structure
15449  *
15450  * This function is useful when a NIC is about to enter recovery mode.
15451  * When a NIC's internal data structures are corrupted the NIC's
15452  * firmware is going to enter recovery mode.
15453  * Right after a POR it takes about 7 minutes for firmware to enter
15454  * recovery mode. Until that time a NIC is in some kind of intermediate
15455  * state. After that time period the NIC almost surely enters
15456  * recovery mode. The only way for a driver to detect intermediate
15457  * state is to issue a series of pf-resets and check a return value.
15458  * If a PF reset returns success then the firmware could be in recovery
15459  * mode so the caller of this code needs to check for recovery mode
15460  * if this function returns success. There is a little chance that
15461  * firmware will hang in intermediate state forever.
15462  * Since waiting 7 minutes is quite a lot of time this function waits
15463  * 10 seconds and then gives up by returning an error.
15464  *
15465  * Return 0 on success, negative on failure.
15466  **/
15467 static int i40e_pf_loop_reset(struct i40e_pf *pf)
15468 {
15469 	/* wait max 10 seconds for PF reset to succeed */
15470 	const unsigned long time_end = jiffies + 10 * HZ;
15471 	struct i40e_hw *hw = &pf->hw;
15472 	int ret;
15473 
15474 	ret = i40e_pf_reset(hw);
15475 	while (ret != I40E_SUCCESS && time_before(jiffies, time_end)) {
15476 		usleep_range(10000, 20000);
15477 		ret = i40e_pf_reset(hw);
15478 	}
15479 
15480 	if (ret == I40E_SUCCESS)
15481 		pf->pfr_count++;
15482 	else
15483 		dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
15484 
15485 	return ret;
15486 }
15487 
15488 /**
15489  * i40e_check_fw_empr - check if FW issued unexpected EMP Reset
15490  * @pf: board private structure
15491  *
15492  * Check FW registers to determine if FW issued unexpected EMP Reset.
15493  * Every time when unexpected EMP Reset occurs the FW increments
15494  * a counter of unexpected EMP Resets. When the counter reaches 10
15495  * the FW should enter the Recovery mode
15496  *
15497  * Returns true if FW issued unexpected EMP Reset
15498  **/
15499 static bool i40e_check_fw_empr(struct i40e_pf *pf)
15500 {
15501 	const u32 fw_sts = rd32(&pf->hw, I40E_GL_FWSTS) &
15502 			   I40E_GL_FWSTS_FWS1B_MASK;
15503 	return (fw_sts > I40E_GL_FWSTS_FWS1B_EMPR_0) &&
15504 	       (fw_sts <= I40E_GL_FWSTS_FWS1B_EMPR_10);
15505 }
15506 
15507 /**
15508  * i40e_handle_resets - handle EMP resets and PF resets
15509  * @pf: board private structure
15510  *
15511  * Handle both EMP resets and PF resets and conclude whether there are
15512  * any issues regarding these resets. If there are any issues then
15513  * generate log entry.
15514  *
15515  * Return 0 if NIC is healthy or negative value when there are issues
15516  * with resets
15517  **/
15518 static int i40e_handle_resets(struct i40e_pf *pf)
15519 {
15520 	const int pfr = i40e_pf_loop_reset(pf);
15521 	const bool is_empr = i40e_check_fw_empr(pf);
15522 
15523 	if (is_empr || pfr != I40E_SUCCESS)
15524 		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");
15525 
15526 	return is_empr ? I40E_ERR_RESET_FAILED : pfr;
15527 }
15528 
15529 /**
15530  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
15531  * @pf: board private structure
15532  * @hw: ptr to the hardware info
15533  *
15534  * This function does a minimal setup of all subsystems needed for running
15535  * recovery mode.
15536  *
15537  * Returns 0 on success, negative on failure
15538  **/
15539 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
15540 {
15541 	struct i40e_vsi *vsi;
15542 	int err;
15543 	int v_idx;
15544 
15545 	pci_set_drvdata(pf->pdev, pf);
15546 	pci_save_state(pf->pdev);
15547 
15548 	/* set up periodic task facility */
15549 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15550 	pf->service_timer_period = HZ;
15551 
15552 	INIT_WORK(&pf->service_task, i40e_service_task);
15553 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15554 
15555 	err = i40e_init_interrupt_scheme(pf);
15556 	if (err)
15557 		goto err_switch_setup;
15558 
15559 	/* The number of VSIs reported by the FW is the minimum guaranteed
15560 	 * to us; HW supports far more and we share the remaining pool with
15561 	 * the other PFs. We allocate space for more than the guarantee with
15562 	 * the understanding that we might not get them all later.
15563 	 */
15564 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15565 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15566 	else
15567 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15568 
15569 	/* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
15570 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15571 			  GFP_KERNEL);
15572 	if (!pf->vsi) {
15573 		err = -ENOMEM;
15574 		goto err_switch_setup;
15575 	}
15576 
15577 	/* We allocate one VSI which is needed as absolute minimum
15578 	 * in order to register the netdev
15579 	 */
15580 	v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
15581 	if (v_idx < 0) {
15582 		err = v_idx;
15583 		goto err_switch_setup;
15584 	}
15585 	pf->lan_vsi = v_idx;
15586 	vsi = pf->vsi[v_idx];
15587 	if (!vsi) {
15588 		err = -EFAULT;
15589 		goto err_switch_setup;
15590 	}
15591 	vsi->alloc_queue_pairs = 1;
15592 	err = i40e_config_netdev(vsi);
15593 	if (err)
15594 		goto err_switch_setup;
15595 	err = register_netdev(vsi->netdev);
15596 	if (err)
15597 		goto err_switch_setup;
15598 	vsi->netdev_registered = true;
15599 	i40e_dbg_pf_init(pf);
15600 
15601 	err = i40e_setup_misc_vector_for_recovery_mode(pf);
15602 	if (err)
15603 		goto err_switch_setup;
15604 
15605 	/* tell the firmware that we're starting */
15606 	i40e_send_version(pf);
15607 
15608 	/* since everything's happy, start the service_task timer */
15609 	mod_timer(&pf->service_timer,
15610 		  round_jiffies(jiffies + pf->service_timer_period));
15611 
15612 	return 0;
15613 
15614 err_switch_setup:
15615 	i40e_reset_interrupt_capability(pf);
15616 	timer_shutdown_sync(&pf->service_timer);
15617 	i40e_shutdown_adminq(hw);
15618 	iounmap(hw->hw_addr);
15619 	pci_release_mem_regions(pf->pdev);
15620 	pci_disable_device(pf->pdev);
15621 	kfree(pf);
15622 
15623 	return err;
15624 }
15625 
15626 /**
15627  * i40e_set_subsystem_device_id - set subsystem device id
15628  * @hw: pointer to the hardware info
15629  *
15630  * Set PCI subsystem device id either from a pci_dev structure or
15631  * a specific FW register.
15632  **/
15633 static inline void i40e_set_subsystem_device_id(struct i40e_hw *hw)
15634 {
15635 	struct pci_dev *pdev = ((struct i40e_pf *)hw->back)->pdev;
15636 
15637 	hw->subsystem_device_id = pdev->subsystem_device ?
15638 		pdev->subsystem_device :
15639 		(ushort)(rd32(hw, I40E_PFPCI_SUBSYSID) & USHRT_MAX);
15640 }
15641 
15642 /**
15643  * i40e_probe - Device initialization routine
15644  * @pdev: PCI device information struct
15645  * @ent: entry in i40e_pci_tbl
15646  *
15647  * i40e_probe initializes a PF identified by a pci_dev structure.
15648  * The OS initialization, configuring of the PF private structure,
15649  * and a hardware reset occur.
15650  *
15651  * Returns 0 on success, negative on failure
15652  **/
15653 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
15654 {
15655 	struct i40e_aq_get_phy_abilities_resp abilities;
15656 #ifdef CONFIG_I40E_DCB
15657 	enum i40e_get_fw_lldp_status_resp lldp_status;
15658 #endif /* CONFIG_I40E_DCB */
15659 	struct i40e_pf *pf;
15660 	struct i40e_hw *hw;
15661 	static u16 pfs_found;
15662 	u16 wol_nvm_bits;
15663 	u16 link_status;
15664 #ifdef CONFIG_I40E_DCB
15665 	int status;
15666 #endif /* CONFIG_I40E_DCB */
15667 	int err;
15668 	u32 val;
15669 	u32 i;
15670 
15671 	err = pci_enable_device_mem(pdev);
15672 	if (err)
15673 		return err;
15674 
15675 	/* set up for high or low dma */
15676 	err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
15677 	if (err) {
15678 		dev_err(&pdev->dev,
15679 			"DMA configuration failed: 0x%x\n", err);
15680 		goto err_dma;
15681 	}
15682 
15683 	/* set up pci connections */
15684 	err = pci_request_mem_regions(pdev, i40e_driver_name);
15685 	if (err) {
15686 		dev_info(&pdev->dev,
15687 			 "pci_request_selected_regions failed %d\n", err);
15688 		goto err_pci_reg;
15689 	}
15690 
15691 	pci_set_master(pdev);
15692 
15693 	/* Now that we have a PCI connection, we need to do the
15694 	 * low level device setup.  This is primarily setting up
15695 	 * the Admin Queue structures and then querying for the
15696 	 * device's current profile information.
15697 	 */
15698 	pf = kzalloc(sizeof(*pf), GFP_KERNEL);
15699 	if (!pf) {
15700 		err = -ENOMEM;
15701 		goto err_pf_alloc;
15702 	}
15703 	pf->next_vsi = 0;
15704 	pf->pdev = pdev;
15705 	set_bit(__I40E_DOWN, pf->state);
15706 
15707 	hw = &pf->hw;
15708 	hw->back = pf;
15709 
15710 	pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
15711 				I40E_MAX_CSR_SPACE);
15712 	/* We believe that the highest register to read is
15713 	 * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
15714 	 * is not less than that before mapping to prevent a
15715 	 * kernel panic.
15716 	 */
15717 	if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
15718 		dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
15719 			pf->ioremap_len);
15720 		err = -ENOMEM;
15721 		goto err_ioremap;
15722 	}
15723 	hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
15724 	if (!hw->hw_addr) {
15725 		err = -EIO;
15726 		dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
15727 			 (unsigned int)pci_resource_start(pdev, 0),
15728 			 pf->ioremap_len, err);
15729 		goto err_ioremap;
15730 	}
15731 	hw->vendor_id = pdev->vendor;
15732 	hw->device_id = pdev->device;
15733 	pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
15734 	hw->subsystem_vendor_id = pdev->subsystem_vendor;
15735 	i40e_set_subsystem_device_id(hw);
15736 	hw->bus.device = PCI_SLOT(pdev->devfn);
15737 	hw->bus.func = PCI_FUNC(pdev->devfn);
15738 	hw->bus.bus_id = pdev->bus->number;
15739 	pf->instance = pfs_found;
15740 
15741 	/* Select something other than the 802.1ad ethertype for the
15742 	 * switch to use internally and drop on ingress.
15743 	 */
15744 	hw->switch_tag = 0xffff;
15745 	hw->first_tag = ETH_P_8021AD;
15746 	hw->second_tag = ETH_P_8021Q;
15747 
15748 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
15749 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
15750 	INIT_LIST_HEAD(&pf->ddp_old_prof);
15751 
15752 	/* set up the locks for the AQ, do this only once in probe
15753 	 * and destroy them only once in remove
15754 	 */
15755 	mutex_init(&hw->aq.asq_mutex);
15756 	mutex_init(&hw->aq.arq_mutex);
15757 
15758 	pf->msg_enable = netif_msg_init(debug,
15759 					NETIF_MSG_DRV |
15760 					NETIF_MSG_PROBE |
15761 					NETIF_MSG_LINK);
15762 	if (debug < -1)
15763 		pf->hw.debug_mask = debug;
15764 
15765 	/* do a special CORER for clearing PXE mode once at init */
15766 	if (hw->revision_id == 0 &&
15767 	    (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
15768 		wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
15769 		i40e_flush(hw);
15770 		msleep(200);
15771 		pf->corer_count++;
15772 
15773 		i40e_clear_pxe_mode(hw);
15774 	}
15775 
15776 	/* Reset here to make sure all is clean and to define PF 'n' */
15777 	i40e_clear_hw(hw);
15778 
15779 	err = i40e_set_mac_type(hw);
15780 	if (err) {
15781 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15782 			 err);
15783 		goto err_pf_reset;
15784 	}
15785 
15786 	err = i40e_handle_resets(pf);
15787 	if (err)
15788 		goto err_pf_reset;
15789 
15790 	i40e_check_recovery_mode(pf);
15791 
15792 	if (is_kdump_kernel()) {
15793 		hw->aq.num_arq_entries = I40E_MIN_ARQ_LEN;
15794 		hw->aq.num_asq_entries = I40E_MIN_ASQ_LEN;
15795 	} else {
15796 		hw->aq.num_arq_entries = I40E_AQ_LEN;
15797 		hw->aq.num_asq_entries = I40E_AQ_LEN;
15798 	}
15799 	hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15800 	hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15801 	pf->adminq_work_limit = I40E_AQ_WORK_LIMIT;
15802 
15803 	snprintf(pf->int_name, sizeof(pf->int_name) - 1,
15804 		 "%s-%s:misc",
15805 		 dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
15806 
15807 	err = i40e_init_shared_code(hw);
15808 	if (err) {
15809 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15810 			 err);
15811 		goto err_pf_reset;
15812 	}
15813 
15814 	/* set up a default setting for link flow control */
15815 	pf->hw.fc.requested_mode = I40E_FC_NONE;
15816 
15817 	err = i40e_init_adminq(hw);
15818 	if (err) {
15819 		if (err == I40E_ERR_FIRMWARE_API_VERSION)
15820 			dev_info(&pdev->dev,
15821 				 "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",
15822 				 hw->aq.api_maj_ver,
15823 				 hw->aq.api_min_ver,
15824 				 I40E_FW_API_VERSION_MAJOR,
15825 				 I40E_FW_MINOR_VERSION(hw));
15826 		else
15827 			dev_info(&pdev->dev,
15828 				 "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
15829 
15830 		goto err_pf_reset;
15831 	}
15832 	i40e_get_oem_version(hw);
15833 
15834 	/* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
15835 	dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
15836 		 hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
15837 		 hw->aq.api_maj_ver, hw->aq.api_min_ver,
15838 		 i40e_nvm_version_str(hw), hw->vendor_id, hw->device_id,
15839 		 hw->subsystem_vendor_id, hw->subsystem_device_id);
15840 
15841 	if (hw->aq.api_maj_ver == I40E_FW_API_VERSION_MAJOR &&
15842 	    hw->aq.api_min_ver > I40E_FW_MINOR_VERSION(hw))
15843 		dev_dbg(&pdev->dev,
15844 			"The driver for the device detected a newer version of the NVM image v%u.%u than v%u.%u.\n",
15845 			 hw->aq.api_maj_ver,
15846 			 hw->aq.api_min_ver,
15847 			 I40E_FW_API_VERSION_MAJOR,
15848 			 I40E_FW_MINOR_VERSION(hw));
15849 	else if (hw->aq.api_maj_ver == 1 && hw->aq.api_min_ver < 4)
15850 		dev_info(&pdev->dev,
15851 			 "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",
15852 			 hw->aq.api_maj_ver,
15853 			 hw->aq.api_min_ver,
15854 			 I40E_FW_API_VERSION_MAJOR,
15855 			 I40E_FW_MINOR_VERSION(hw));
15856 
15857 	i40e_verify_eeprom(pf);
15858 
15859 	/* Rev 0 hardware was never productized */
15860 	if (hw->revision_id < 1)
15861 		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");
15862 
15863 	i40e_clear_pxe_mode(hw);
15864 
15865 	err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
15866 	if (err)
15867 		goto err_adminq_setup;
15868 
15869 	err = i40e_sw_init(pf);
15870 	if (err) {
15871 		dev_info(&pdev->dev, "sw_init failed: %d\n", err);
15872 		goto err_sw_init;
15873 	}
15874 
15875 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15876 		return i40e_init_recovery_mode(pf, hw);
15877 
15878 	err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
15879 				hw->func_caps.num_rx_qp, 0, 0);
15880 	if (err) {
15881 		dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
15882 		goto err_init_lan_hmc;
15883 	}
15884 
15885 	err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
15886 	if (err) {
15887 		dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
15888 		err = -ENOENT;
15889 		goto err_configure_lan_hmc;
15890 	}
15891 
15892 	/* Disable LLDP for NICs that have firmware versions lower than v4.3.
15893 	 * Ignore error return codes because if it was already disabled via
15894 	 * hardware settings this will fail
15895 	 */
15896 	if (pf->hw_features & I40E_HW_STOP_FW_LLDP) {
15897 		dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
15898 		i40e_aq_stop_lldp(hw, true, false, NULL);
15899 	}
15900 
15901 	/* allow a platform config to override the HW addr */
15902 	i40e_get_platform_mac_addr(pdev, pf);
15903 
15904 	if (!is_valid_ether_addr(hw->mac.addr)) {
15905 		dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
15906 		err = -EIO;
15907 		goto err_mac_addr;
15908 	}
15909 	dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
15910 	ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
15911 	i40e_get_port_mac_addr(hw, hw->mac.port_addr);
15912 	if (is_valid_ether_addr(hw->mac.port_addr))
15913 		pf->hw_features |= I40E_HW_PORT_ID_VALID;
15914 
15915 	i40e_ptp_alloc_pins(pf);
15916 	pci_set_drvdata(pdev, pf);
15917 	pci_save_state(pdev);
15918 
15919 #ifdef CONFIG_I40E_DCB
15920 	status = i40e_get_fw_lldp_status(&pf->hw, &lldp_status);
15921 	(!status &&
15922 	 lldp_status == I40E_GET_FW_LLDP_STATUS_ENABLED) ?
15923 		(pf->flags &= ~I40E_FLAG_DISABLE_FW_LLDP) :
15924 		(pf->flags |= I40E_FLAG_DISABLE_FW_LLDP);
15925 	dev_info(&pdev->dev,
15926 		 (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) ?
15927 			"FW LLDP is disabled\n" :
15928 			"FW LLDP is enabled\n");
15929 
15930 	/* Enable FW to write default DCB config on link-up */
15931 	i40e_aq_set_dcb_parameters(hw, true, NULL);
15932 
15933 	err = i40e_init_pf_dcb(pf);
15934 	if (err) {
15935 		dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
15936 		pf->flags &= ~(I40E_FLAG_DCB_CAPABLE | I40E_FLAG_DCB_ENABLED);
15937 		/* Continue without DCB enabled */
15938 	}
15939 #endif /* CONFIG_I40E_DCB */
15940 
15941 	/* set up periodic task facility */
15942 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15943 	pf->service_timer_period = HZ;
15944 
15945 	INIT_WORK(&pf->service_task, i40e_service_task);
15946 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15947 
15948 	/* NVM bit on means WoL disabled for the port */
15949 	i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15950 	if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15951 		pf->wol_en = false;
15952 	else
15953 		pf->wol_en = true;
15954 	device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15955 
15956 	/* set up the main switch operations */
15957 	i40e_determine_queue_usage(pf);
15958 	err = i40e_init_interrupt_scheme(pf);
15959 	if (err)
15960 		goto err_switch_setup;
15961 
15962 	/* Reduce Tx and Rx pairs for kdump
15963 	 * When MSI-X is enabled, it's not allowed to use more TC queue
15964 	 * pairs than MSI-X vectors (pf->num_lan_msix) exist. Thus
15965 	 * vsi->num_queue_pairs will be equal to pf->num_lan_msix, i.e., 1.
15966 	 */
15967 	if (is_kdump_kernel())
15968 		pf->num_lan_msix = 1;
15969 
15970 	pf->udp_tunnel_nic.set_port = i40e_udp_tunnel_set_port;
15971 	pf->udp_tunnel_nic.unset_port = i40e_udp_tunnel_unset_port;
15972 	pf->udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP;
15973 	pf->udp_tunnel_nic.shared = &pf->udp_tunnel_shared;
15974 	pf->udp_tunnel_nic.tables[0].n_entries = I40E_MAX_PF_UDP_OFFLOAD_PORTS;
15975 	pf->udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
15976 						    UDP_TUNNEL_TYPE_GENEVE;
15977 
15978 	/* The number of VSIs reported by the FW is the minimum guaranteed
15979 	 * to us; HW supports far more and we share the remaining pool with
15980 	 * the other PFs. We allocate space for more than the guarantee with
15981 	 * the understanding that we might not get them all later.
15982 	 */
15983 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15984 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15985 	else
15986 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15987 	if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
15988 		dev_warn(&pf->pdev->dev,
15989 			 "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
15990 			 pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
15991 		pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
15992 	}
15993 
15994 	/* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15995 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15996 			  GFP_KERNEL);
15997 	if (!pf->vsi) {
15998 		err = -ENOMEM;
15999 		goto err_switch_setup;
16000 	}
16001 
16002 #ifdef CONFIG_PCI_IOV
16003 	/* prep for VF support */
16004 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
16005 	    (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
16006 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
16007 		if (pci_num_vf(pdev))
16008 			pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
16009 	}
16010 #endif
16011 	err = i40e_setup_pf_switch(pf, false, false);
16012 	if (err) {
16013 		dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
16014 		goto err_vsis;
16015 	}
16016 	INIT_LIST_HEAD(&pf->vsi[pf->lan_vsi]->ch_list);
16017 
16018 	/* if FDIR VSI was set up, start it now */
16019 	for (i = 0; i < pf->num_alloc_vsi; i++) {
16020 		if (pf->vsi[i] && pf->vsi[i]->type == I40E_VSI_FDIR) {
16021 			i40e_vsi_open(pf->vsi[i]);
16022 			break;
16023 		}
16024 	}
16025 
16026 	/* The driver only wants link up/down and module qualification
16027 	 * reports from firmware.  Note the negative logic.
16028 	 */
16029 	err = i40e_aq_set_phy_int_mask(&pf->hw,
16030 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
16031 					 I40E_AQ_EVENT_MEDIA_NA |
16032 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
16033 	if (err)
16034 		dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
16035 			 ERR_PTR(err),
16036 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16037 
16038 	/* Reconfigure hardware for allowing smaller MSS in the case
16039 	 * of TSO, so that we avoid the MDD being fired and causing
16040 	 * a reset in the case of small MSS+TSO.
16041 	 */
16042 	val = rd32(hw, I40E_REG_MSS);
16043 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
16044 		val &= ~I40E_REG_MSS_MIN_MASK;
16045 		val |= I40E_64BYTE_MSS;
16046 		wr32(hw, I40E_REG_MSS, val);
16047 	}
16048 
16049 	if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
16050 		msleep(75);
16051 		err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
16052 		if (err)
16053 			dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
16054 				 ERR_PTR(err),
16055 				 i40e_aq_str(&pf->hw,
16056 					     pf->hw.aq.asq_last_status));
16057 	}
16058 	/* The main driver is (mostly) up and happy. We need to set this state
16059 	 * before setting up the misc vector or we get a race and the vector
16060 	 * ends up disabled forever.
16061 	 */
16062 	clear_bit(__I40E_DOWN, pf->state);
16063 
16064 	/* In case of MSIX we are going to setup the misc vector right here
16065 	 * to handle admin queue events etc. In case of legacy and MSI
16066 	 * the misc functionality and queue processing is combined in
16067 	 * the same vector and that gets setup at open.
16068 	 */
16069 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
16070 		err = i40e_setup_misc_vector(pf);
16071 		if (err) {
16072 			dev_info(&pdev->dev,
16073 				 "setup of misc vector failed: %d\n", err);
16074 			i40e_cloud_filter_exit(pf);
16075 			i40e_fdir_teardown(pf);
16076 			goto err_vsis;
16077 		}
16078 	}
16079 
16080 #ifdef CONFIG_PCI_IOV
16081 	/* prep for VF support */
16082 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
16083 	    (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
16084 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
16085 		/* disable link interrupts for VFs */
16086 		val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
16087 		val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
16088 		wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
16089 		i40e_flush(hw);
16090 
16091 		if (pci_num_vf(pdev)) {
16092 			dev_info(&pdev->dev,
16093 				 "Active VFs found, allocating resources.\n");
16094 			err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
16095 			if (err)
16096 				dev_info(&pdev->dev,
16097 					 "Error %d allocating resources for existing VFs\n",
16098 					 err);
16099 		}
16100 	}
16101 #endif /* CONFIG_PCI_IOV */
16102 
16103 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16104 		pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
16105 						      pf->num_iwarp_msix,
16106 						      I40E_IWARP_IRQ_PILE_ID);
16107 		if (pf->iwarp_base_vector < 0) {
16108 			dev_info(&pdev->dev,
16109 				 "failed to get tracking for %d vectors for IWARP err=%d\n",
16110 				 pf->num_iwarp_msix, pf->iwarp_base_vector);
16111 			pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
16112 		}
16113 	}
16114 
16115 	i40e_dbg_pf_init(pf);
16116 
16117 	/* tell the firmware that we're starting */
16118 	i40e_send_version(pf);
16119 
16120 	/* since everything's happy, start the service_task timer */
16121 	mod_timer(&pf->service_timer,
16122 		  round_jiffies(jiffies + pf->service_timer_period));
16123 
16124 	/* add this PF to client device list and launch a client service task */
16125 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16126 		err = i40e_lan_add_device(pf);
16127 		if (err)
16128 			dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
16129 				 err);
16130 	}
16131 
16132 #define PCI_SPEED_SIZE 8
16133 #define PCI_WIDTH_SIZE 8
16134 	/* Devices on the IOSF bus do not have this information
16135 	 * and will report PCI Gen 1 x 1 by default so don't bother
16136 	 * checking them.
16137 	 */
16138 	if (!(pf->hw_features & I40E_HW_NO_PCI_LINK_CHECK)) {
16139 		char speed[PCI_SPEED_SIZE] = "Unknown";
16140 		char width[PCI_WIDTH_SIZE] = "Unknown";
16141 
16142 		/* Get the negotiated link width and speed from PCI config
16143 		 * space
16144 		 */
16145 		pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
16146 					  &link_status);
16147 
16148 		i40e_set_pci_config_data(hw, link_status);
16149 
16150 		switch (hw->bus.speed) {
16151 		case i40e_bus_speed_8000:
16152 			strscpy(speed, "8.0", PCI_SPEED_SIZE); break;
16153 		case i40e_bus_speed_5000:
16154 			strscpy(speed, "5.0", PCI_SPEED_SIZE); break;
16155 		case i40e_bus_speed_2500:
16156 			strscpy(speed, "2.5", PCI_SPEED_SIZE); break;
16157 		default:
16158 			break;
16159 		}
16160 		switch (hw->bus.width) {
16161 		case i40e_bus_width_pcie_x8:
16162 			strscpy(width, "8", PCI_WIDTH_SIZE); break;
16163 		case i40e_bus_width_pcie_x4:
16164 			strscpy(width, "4", PCI_WIDTH_SIZE); break;
16165 		case i40e_bus_width_pcie_x2:
16166 			strscpy(width, "2", PCI_WIDTH_SIZE); break;
16167 		case i40e_bus_width_pcie_x1:
16168 			strscpy(width, "1", PCI_WIDTH_SIZE); break;
16169 		default:
16170 			break;
16171 		}
16172 
16173 		dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
16174 			 speed, width);
16175 
16176 		if (hw->bus.width < i40e_bus_width_pcie_x8 ||
16177 		    hw->bus.speed < i40e_bus_speed_8000) {
16178 			dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
16179 			dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
16180 		}
16181 	}
16182 
16183 	/* get the requested speeds from the fw */
16184 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
16185 	if (err)
16186 		dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %pe last_status =  %s\n",
16187 			ERR_PTR(err),
16188 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16189 	pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
16190 
16191 	/* set the FEC config due to the board capabilities */
16192 	i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, &pf->flags);
16193 
16194 	/* get the supported phy types from the fw */
16195 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
16196 	if (err)
16197 		dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %pe last_status =  %s\n",
16198 			ERR_PTR(err),
16199 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16200 
16201 	/* make sure the MFS hasn't been set lower than the default */
16202 #define MAX_FRAME_SIZE_DEFAULT 0x2600
16203 	val = (rd32(&pf->hw, I40E_PRTGL_SAH) &
16204 	       I40E_PRTGL_SAH_MFS_MASK) >> I40E_PRTGL_SAH_MFS_SHIFT;
16205 	if (val < MAX_FRAME_SIZE_DEFAULT)
16206 		dev_warn(&pdev->dev, "MFS for port %x has been set below the default: %x\n",
16207 			 i, val);
16208 
16209 	/* Add a filter to drop all Flow control frames from any VSI from being
16210 	 * transmitted. By doing so we stop a malicious VF from sending out
16211 	 * PAUSE or PFC frames and potentially controlling traffic for other
16212 	 * PF/VF VSIs.
16213 	 * The FW can still send Flow control frames if enabled.
16214 	 */
16215 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
16216 						       pf->main_vsi_seid);
16217 
16218 	if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
16219 		(pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
16220 		pf->hw_features |= I40E_HW_PHY_CONTROLS_LEDS;
16221 	if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
16222 		pf->hw_features |= I40E_HW_HAVE_CRT_RETIMER;
16223 	/* print a string summarizing features */
16224 	i40e_print_features(pf);
16225 
16226 	return 0;
16227 
16228 	/* Unwind what we've done if something failed in the setup */
16229 err_vsis:
16230 	set_bit(__I40E_DOWN, pf->state);
16231 	i40e_clear_interrupt_scheme(pf);
16232 	kfree(pf->vsi);
16233 err_switch_setup:
16234 	i40e_reset_interrupt_capability(pf);
16235 	timer_shutdown_sync(&pf->service_timer);
16236 err_mac_addr:
16237 err_configure_lan_hmc:
16238 	(void)i40e_shutdown_lan_hmc(hw);
16239 err_init_lan_hmc:
16240 	kfree(pf->qp_pile);
16241 err_sw_init:
16242 err_adminq_setup:
16243 err_pf_reset:
16244 	iounmap(hw->hw_addr);
16245 err_ioremap:
16246 	kfree(pf);
16247 err_pf_alloc:
16248 	pci_release_mem_regions(pdev);
16249 err_pci_reg:
16250 err_dma:
16251 	pci_disable_device(pdev);
16252 	return err;
16253 }
16254 
16255 /**
16256  * i40e_remove - Device removal routine
16257  * @pdev: PCI device information struct
16258  *
16259  * i40e_remove is called by the PCI subsystem to alert the driver
16260  * that is should release a PCI device.  This could be caused by a
16261  * Hot-Plug event, or because the driver is going to be removed from
16262  * memory.
16263  **/
16264 static void i40e_remove(struct pci_dev *pdev)
16265 {
16266 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16267 	struct i40e_hw *hw = &pf->hw;
16268 	int ret_code;
16269 	int i;
16270 
16271 	i40e_dbg_pf_exit(pf);
16272 
16273 	i40e_ptp_stop(pf);
16274 
16275 	/* Disable RSS in hw */
16276 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
16277 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
16278 
16279 	/* Grab __I40E_RESET_RECOVERY_PENDING and set __I40E_IN_REMOVE
16280 	 * flags, once they are set, i40e_rebuild should not be called as
16281 	 * i40e_prep_for_reset always returns early.
16282 	 */
16283 	while (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
16284 		usleep_range(1000, 2000);
16285 	set_bit(__I40E_IN_REMOVE, pf->state);
16286 
16287 	if (pf->flags & I40E_FLAG_SRIOV_ENABLED) {
16288 		set_bit(__I40E_VF_RESETS_DISABLED, pf->state);
16289 		i40e_free_vfs(pf);
16290 		pf->flags &= ~I40E_FLAG_SRIOV_ENABLED;
16291 	}
16292 	/* no more scheduling of any task */
16293 	set_bit(__I40E_SUSPENDED, pf->state);
16294 	set_bit(__I40E_DOWN, pf->state);
16295 	if (pf->service_timer.function)
16296 		timer_shutdown_sync(&pf->service_timer);
16297 	if (pf->service_task.func)
16298 		cancel_work_sync(&pf->service_task);
16299 
16300 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
16301 		struct i40e_vsi *vsi = pf->vsi[0];
16302 
16303 		/* We know that we have allocated only one vsi for this PF,
16304 		 * it was just for registering netdevice, so the interface
16305 		 * could be visible in the 'ifconfig' output
16306 		 */
16307 		unregister_netdev(vsi->netdev);
16308 		free_netdev(vsi->netdev);
16309 
16310 		goto unmap;
16311 	}
16312 
16313 	/* Client close must be called explicitly here because the timer
16314 	 * has been stopped.
16315 	 */
16316 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16317 
16318 	i40e_fdir_teardown(pf);
16319 
16320 	/* If there is a switch structure or any orphans, remove them.
16321 	 * This will leave only the PF's VSI remaining.
16322 	 */
16323 	for (i = 0; i < I40E_MAX_VEB; i++) {
16324 		if (!pf->veb[i])
16325 			continue;
16326 
16327 		if (pf->veb[i]->uplink_seid == pf->mac_seid ||
16328 		    pf->veb[i]->uplink_seid == 0)
16329 			i40e_switch_branch_release(pf->veb[i]);
16330 	}
16331 
16332 	/* Now we can shutdown the PF's VSI, just before we kill
16333 	 * adminq and hmc.
16334 	 */
16335 	if (pf->vsi[pf->lan_vsi])
16336 		i40e_vsi_release(pf->vsi[pf->lan_vsi]);
16337 
16338 	i40e_cloud_filter_exit(pf);
16339 
16340 	/* remove attached clients */
16341 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16342 		ret_code = i40e_lan_del_device(pf);
16343 		if (ret_code)
16344 			dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
16345 				 ret_code);
16346 	}
16347 
16348 	/* shutdown and destroy the HMC */
16349 	if (hw->hmc.hmc_obj) {
16350 		ret_code = i40e_shutdown_lan_hmc(hw);
16351 		if (ret_code)
16352 			dev_warn(&pdev->dev,
16353 				 "Failed to destroy the HMC resources: %d\n",
16354 				 ret_code);
16355 	}
16356 
16357 unmap:
16358 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16359 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16360 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16361 		free_irq(pf->pdev->irq, pf);
16362 
16363 	/* shutdown the adminq */
16364 	i40e_shutdown_adminq(hw);
16365 
16366 	/* destroy the locks only once, here */
16367 	mutex_destroy(&hw->aq.arq_mutex);
16368 	mutex_destroy(&hw->aq.asq_mutex);
16369 
16370 	/* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
16371 	rtnl_lock();
16372 	i40e_clear_interrupt_scheme(pf);
16373 	for (i = 0; i < pf->num_alloc_vsi; i++) {
16374 		if (pf->vsi[i]) {
16375 			if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
16376 				i40e_vsi_clear_rings(pf->vsi[i]);
16377 			i40e_vsi_clear(pf->vsi[i]);
16378 			pf->vsi[i] = NULL;
16379 		}
16380 	}
16381 	rtnl_unlock();
16382 
16383 	for (i = 0; i < I40E_MAX_VEB; i++) {
16384 		kfree(pf->veb[i]);
16385 		pf->veb[i] = NULL;
16386 	}
16387 
16388 	kfree(pf->qp_pile);
16389 	kfree(pf->vsi);
16390 
16391 	iounmap(hw->hw_addr);
16392 	kfree(pf);
16393 	pci_release_mem_regions(pdev);
16394 
16395 	pci_disable_device(pdev);
16396 }
16397 
16398 /**
16399  * i40e_pci_error_detected - warning that something funky happened in PCI land
16400  * @pdev: PCI device information struct
16401  * @error: the type of PCI error
16402  *
16403  * Called to warn that something happened and the error handling steps
16404  * are in progress.  Allows the driver to quiesce things, be ready for
16405  * remediation.
16406  **/
16407 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
16408 						pci_channel_state_t error)
16409 {
16410 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16411 
16412 	dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
16413 
16414 	if (!pf) {
16415 		dev_info(&pdev->dev,
16416 			 "Cannot recover - error happened during device probe\n");
16417 		return PCI_ERS_RESULT_DISCONNECT;
16418 	}
16419 
16420 	/* shutdown all operations */
16421 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16422 		i40e_prep_for_reset(pf);
16423 
16424 	/* Request a slot reset */
16425 	return PCI_ERS_RESULT_NEED_RESET;
16426 }
16427 
16428 /**
16429  * i40e_pci_error_slot_reset - a PCI slot reset just happened
16430  * @pdev: PCI device information struct
16431  *
16432  * Called to find if the driver can work with the device now that
16433  * the pci slot has been reset.  If a basic connection seems good
16434  * (registers are readable and have sane content) then return a
16435  * happy little PCI_ERS_RESULT_xxx.
16436  **/
16437 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
16438 {
16439 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16440 	pci_ers_result_t result;
16441 	u32 reg;
16442 
16443 	dev_dbg(&pdev->dev, "%s\n", __func__);
16444 	if (pci_enable_device_mem(pdev)) {
16445 		dev_info(&pdev->dev,
16446 			 "Cannot re-enable PCI device after reset.\n");
16447 		result = PCI_ERS_RESULT_DISCONNECT;
16448 	} else {
16449 		pci_set_master(pdev);
16450 		pci_restore_state(pdev);
16451 		pci_save_state(pdev);
16452 		pci_wake_from_d3(pdev, false);
16453 
16454 		reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
16455 		if (reg == 0)
16456 			result = PCI_ERS_RESULT_RECOVERED;
16457 		else
16458 			result = PCI_ERS_RESULT_DISCONNECT;
16459 	}
16460 
16461 	return result;
16462 }
16463 
16464 /**
16465  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
16466  * @pdev: PCI device information struct
16467  */
16468 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
16469 {
16470 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16471 
16472 	i40e_prep_for_reset(pf);
16473 }
16474 
16475 /**
16476  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
16477  * @pdev: PCI device information struct
16478  */
16479 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
16480 {
16481 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16482 
16483 	if (test_bit(__I40E_IN_REMOVE, pf->state))
16484 		return;
16485 
16486 	i40e_reset_and_rebuild(pf, false, false);
16487 }
16488 
16489 /**
16490  * i40e_pci_error_resume - restart operations after PCI error recovery
16491  * @pdev: PCI device information struct
16492  *
16493  * Called to allow the driver to bring things back up after PCI error
16494  * and/or reset recovery has finished.
16495  **/
16496 static void i40e_pci_error_resume(struct pci_dev *pdev)
16497 {
16498 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16499 
16500 	dev_dbg(&pdev->dev, "%s\n", __func__);
16501 	if (test_bit(__I40E_SUSPENDED, pf->state))
16502 		return;
16503 
16504 	i40e_handle_reset_warning(pf, false);
16505 }
16506 
16507 /**
16508  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
16509  * using the mac_address_write admin q function
16510  * @pf: pointer to i40e_pf struct
16511  **/
16512 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
16513 {
16514 	struct i40e_hw *hw = &pf->hw;
16515 	u8 mac_addr[6];
16516 	u16 flags = 0;
16517 	int ret;
16518 
16519 	/* Get current MAC address in case it's an LAA */
16520 	if (pf->vsi[pf->lan_vsi] && pf->vsi[pf->lan_vsi]->netdev) {
16521 		ether_addr_copy(mac_addr,
16522 				pf->vsi[pf->lan_vsi]->netdev->dev_addr);
16523 	} else {
16524 		dev_err(&pf->pdev->dev,
16525 			"Failed to retrieve MAC address; using default\n");
16526 		ether_addr_copy(mac_addr, hw->mac.addr);
16527 	}
16528 
16529 	/* The FW expects the mac address write cmd to first be called with
16530 	 * one of these flags before calling it again with the multicast
16531 	 * enable flags.
16532 	 */
16533 	flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
16534 
16535 	if (hw->func_caps.flex10_enable && hw->partition_id != 1)
16536 		flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
16537 
16538 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16539 	if (ret) {
16540 		dev_err(&pf->pdev->dev,
16541 			"Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
16542 		return;
16543 	}
16544 
16545 	flags = I40E_AQC_MC_MAG_EN
16546 			| I40E_AQC_WOL_PRESERVE_ON_PFR
16547 			| I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
16548 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16549 	if (ret)
16550 		dev_err(&pf->pdev->dev,
16551 			"Failed to enable Multicast Magic Packet wake up\n");
16552 }
16553 
16554 /**
16555  * i40e_shutdown - PCI callback for shutting down
16556  * @pdev: PCI device information struct
16557  **/
16558 static void i40e_shutdown(struct pci_dev *pdev)
16559 {
16560 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16561 	struct i40e_hw *hw = &pf->hw;
16562 
16563 	set_bit(__I40E_SUSPENDED, pf->state);
16564 	set_bit(__I40E_DOWN, pf->state);
16565 
16566 	del_timer_sync(&pf->service_timer);
16567 	cancel_work_sync(&pf->service_task);
16568 	i40e_cloud_filter_exit(pf);
16569 	i40e_fdir_teardown(pf);
16570 
16571 	/* Client close must be called explicitly here because the timer
16572 	 * has been stopped.
16573 	 */
16574 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16575 
16576 	if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16577 		i40e_enable_mc_magic_wake(pf);
16578 
16579 	i40e_prep_for_reset(pf);
16580 
16581 	wr32(hw, I40E_PFPM_APM,
16582 	     (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16583 	wr32(hw, I40E_PFPM_WUFC,
16584 	     (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16585 
16586 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16587 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16588 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16589 		free_irq(pf->pdev->irq, pf);
16590 
16591 	/* Since we're going to destroy queues during the
16592 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16593 	 * whole section
16594 	 */
16595 	rtnl_lock();
16596 	i40e_clear_interrupt_scheme(pf);
16597 	rtnl_unlock();
16598 
16599 	if (system_state == SYSTEM_POWER_OFF) {
16600 		pci_wake_from_d3(pdev, pf->wol_en);
16601 		pci_set_power_state(pdev, PCI_D3hot);
16602 	}
16603 }
16604 
16605 /**
16606  * i40e_suspend - PM callback for moving to D3
16607  * @dev: generic device information structure
16608  **/
16609 static int __maybe_unused i40e_suspend(struct device *dev)
16610 {
16611 	struct i40e_pf *pf = dev_get_drvdata(dev);
16612 	struct i40e_hw *hw = &pf->hw;
16613 
16614 	/* If we're already suspended, then there is nothing to do */
16615 	if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
16616 		return 0;
16617 
16618 	set_bit(__I40E_DOWN, pf->state);
16619 
16620 	/* Ensure service task will not be running */
16621 	del_timer_sync(&pf->service_timer);
16622 	cancel_work_sync(&pf->service_task);
16623 
16624 	/* Client close must be called explicitly here because the timer
16625 	 * has been stopped.
16626 	 */
16627 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16628 
16629 	if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16630 		i40e_enable_mc_magic_wake(pf);
16631 
16632 	/* Since we're going to destroy queues during the
16633 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16634 	 * whole section
16635 	 */
16636 	rtnl_lock();
16637 
16638 	i40e_prep_for_reset(pf);
16639 
16640 	wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16641 	wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16642 
16643 	/* Clear the interrupt scheme and release our IRQs so that the system
16644 	 * can safely hibernate even when there are a large number of CPUs.
16645 	 * Otherwise hibernation might fail when mapping all the vectors back
16646 	 * to CPU0.
16647 	 */
16648 	i40e_clear_interrupt_scheme(pf);
16649 
16650 	rtnl_unlock();
16651 
16652 	return 0;
16653 }
16654 
16655 /**
16656  * i40e_resume - PM callback for waking up from D3
16657  * @dev: generic device information structure
16658  **/
16659 static int __maybe_unused i40e_resume(struct device *dev)
16660 {
16661 	struct i40e_pf *pf = dev_get_drvdata(dev);
16662 	int err;
16663 
16664 	/* If we're not suspended, then there is nothing to do */
16665 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16666 		return 0;
16667 
16668 	/* We need to hold the RTNL lock prior to restoring interrupt schemes,
16669 	 * since we're going to be restoring queues
16670 	 */
16671 	rtnl_lock();
16672 
16673 	/* We cleared the interrupt scheme when we suspended, so we need to
16674 	 * restore it now to resume device functionality.
16675 	 */
16676 	err = i40e_restore_interrupt_scheme(pf);
16677 	if (err) {
16678 		dev_err(dev, "Cannot restore interrupt scheme: %d\n",
16679 			err);
16680 	}
16681 
16682 	clear_bit(__I40E_DOWN, pf->state);
16683 	i40e_reset_and_rebuild(pf, false, true);
16684 
16685 	rtnl_unlock();
16686 
16687 	/* Clear suspended state last after everything is recovered */
16688 	clear_bit(__I40E_SUSPENDED, pf->state);
16689 
16690 	/* Restart the service task */
16691 	mod_timer(&pf->service_timer,
16692 		  round_jiffies(jiffies + pf->service_timer_period));
16693 
16694 	return 0;
16695 }
16696 
16697 static const struct pci_error_handlers i40e_err_handler = {
16698 	.error_detected = i40e_pci_error_detected,
16699 	.slot_reset = i40e_pci_error_slot_reset,
16700 	.reset_prepare = i40e_pci_error_reset_prepare,
16701 	.reset_done = i40e_pci_error_reset_done,
16702 	.resume = i40e_pci_error_resume,
16703 };
16704 
16705 static SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
16706 
16707 static struct pci_driver i40e_driver = {
16708 	.name     = i40e_driver_name,
16709 	.id_table = i40e_pci_tbl,
16710 	.probe    = i40e_probe,
16711 	.remove   = i40e_remove,
16712 	.driver   = {
16713 		.pm = &i40e_pm_ops,
16714 	},
16715 	.shutdown = i40e_shutdown,
16716 	.err_handler = &i40e_err_handler,
16717 	.sriov_configure = i40e_pci_sriov_configure,
16718 };
16719 
16720 /**
16721  * i40e_init_module - Driver registration routine
16722  *
16723  * i40e_init_module is the first routine called when the driver is
16724  * loaded. All it does is register with the PCI subsystem.
16725  **/
16726 static int __init i40e_init_module(void)
16727 {
16728 	int err;
16729 
16730 	pr_info("%s: %s\n", i40e_driver_name, i40e_driver_string);
16731 	pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
16732 
16733 	/* There is no need to throttle the number of active tasks because
16734 	 * each device limits its own task using a state bit for scheduling
16735 	 * the service task, and the device tasks do not interfere with each
16736 	 * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
16737 	 * since we need to be able to guarantee forward progress even under
16738 	 * memory pressure.
16739 	 */
16740 	i40e_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, i40e_driver_name);
16741 	if (!i40e_wq) {
16742 		pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
16743 		return -ENOMEM;
16744 	}
16745 
16746 	i40e_dbg_init();
16747 	err = pci_register_driver(&i40e_driver);
16748 	if (err) {
16749 		destroy_workqueue(i40e_wq);
16750 		i40e_dbg_exit();
16751 		return err;
16752 	}
16753 
16754 	return 0;
16755 }
16756 module_init(i40e_init_module);
16757 
16758 /**
16759  * i40e_exit_module - Driver exit cleanup routine
16760  *
16761  * i40e_exit_module is called just before the driver is removed
16762  * from memory.
16763  **/
16764 static void __exit i40e_exit_module(void)
16765 {
16766 	pci_unregister_driver(&i40e_driver);
16767 	destroy_workqueue(i40e_wq);
16768 	ida_destroy(&i40e_client_ida);
16769 	i40e_dbg_exit();
16770 }
16771 module_exit(i40e_exit_module);
16772