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_10G_BASE_T), 0},
70 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T4), 0},
71 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_BC), 0},
72 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_SFP), 0},
73 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_B), 0},
74 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_X722), 0},
75 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_X722), 0},
76 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722), 0},
77 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_X722), 0},
78 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_X722), 0},
79 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_I_X722), 0},
80 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722_A), 0},
81 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2), 0},
82 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A), 0},
83 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_X710_N3000), 0},
84 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_XXV710_N3000), 0},
85 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B), 0},
86 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28), 0},
87 	/* required last entry */
88 	{0, }
89 };
90 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
91 
92 #define I40E_MAX_VF_COUNT 128
93 static int debug = -1;
94 module_param(debug, uint, 0);
95 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
96 
97 MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
98 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
99 MODULE_LICENSE("GPL v2");
100 
101 static struct workqueue_struct *i40e_wq;
102 
103 static void netdev_hw_addr_refcnt(struct i40e_mac_filter *f,
104 				  struct net_device *netdev, int delta)
105 {
106 	struct netdev_hw_addr *ha;
107 
108 	if (!f || !netdev)
109 		return;
110 
111 	netdev_for_each_mc_addr(ha, netdev) {
112 		if (ether_addr_equal(ha->addr, f->macaddr)) {
113 			ha->refcount += delta;
114 			if (ha->refcount <= 0)
115 				ha->refcount = 1;
116 			break;
117 		}
118 	}
119 }
120 
121 /**
122  * i40e_allocate_dma_mem_d - OS specific memory alloc for shared code
123  * @hw:   pointer to the HW structure
124  * @mem:  ptr to mem struct to fill out
125  * @size: size of memory requested
126  * @alignment: what to align the allocation to
127  **/
128 int i40e_allocate_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem,
129 			    u64 size, u32 alignment)
130 {
131 	struct i40e_pf *pf = (struct i40e_pf *)hw->back;
132 
133 	mem->size = ALIGN(size, alignment);
134 	mem->va = dma_alloc_coherent(&pf->pdev->dev, mem->size, &mem->pa,
135 				     GFP_KERNEL);
136 	if (!mem->va)
137 		return -ENOMEM;
138 
139 	return 0;
140 }
141 
142 /**
143  * i40e_free_dma_mem_d - OS specific memory free for shared code
144  * @hw:   pointer to the HW structure
145  * @mem:  ptr to mem struct to free
146  **/
147 int i40e_free_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem)
148 {
149 	struct i40e_pf *pf = (struct i40e_pf *)hw->back;
150 
151 	dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
152 	mem->va = NULL;
153 	mem->pa = 0;
154 	mem->size = 0;
155 
156 	return 0;
157 }
158 
159 /**
160  * i40e_allocate_virt_mem_d - OS specific memory alloc for shared code
161  * @hw:   pointer to the HW structure
162  * @mem:  ptr to mem struct to fill out
163  * @size: size of memory requested
164  **/
165 int i40e_allocate_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem,
166 			     u32 size)
167 {
168 	mem->size = size;
169 	mem->va = kzalloc(size, GFP_KERNEL);
170 
171 	if (!mem->va)
172 		return -ENOMEM;
173 
174 	return 0;
175 }
176 
177 /**
178  * i40e_free_virt_mem_d - OS specific memory free for shared code
179  * @hw:   pointer to the HW structure
180  * @mem:  ptr to mem struct to free
181  **/
182 int i40e_free_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem)
183 {
184 	/* it's ok to kfree a NULL pointer */
185 	kfree(mem->va);
186 	mem->va = NULL;
187 	mem->size = 0;
188 
189 	return 0;
190 }
191 
192 /**
193  * i40e_get_lump - find a lump of free generic resource
194  * @pf: board private structure
195  * @pile: the pile of resource to search
196  * @needed: the number of items needed
197  * @id: an owner id to stick on the items assigned
198  *
199  * Returns the base item index of the lump, or negative for error
200  **/
201 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
202 			 u16 needed, u16 id)
203 {
204 	int ret = -ENOMEM;
205 	int i, j;
206 
207 	if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
208 		dev_info(&pf->pdev->dev,
209 			 "param err: pile=%s needed=%d id=0x%04x\n",
210 			 pile ? "<valid>" : "<null>", needed, id);
211 		return -EINVAL;
212 	}
213 
214 	/* Allocate last queue in the pile for FDIR VSI queue
215 	 * so it doesn't fragment the qp_pile
216 	 */
217 	if (pile == pf->qp_pile && pf->vsi[id]->type == I40E_VSI_FDIR) {
218 		if (pile->list[pile->num_entries - 1] & I40E_PILE_VALID_BIT) {
219 			dev_err(&pf->pdev->dev,
220 				"Cannot allocate queue %d for I40E_VSI_FDIR\n",
221 				pile->num_entries - 1);
222 			return -ENOMEM;
223 		}
224 		pile->list[pile->num_entries - 1] = id | I40E_PILE_VALID_BIT;
225 		return pile->num_entries - 1;
226 	}
227 
228 	i = 0;
229 	while (i < pile->num_entries) {
230 		/* skip already allocated entries */
231 		if (pile->list[i] & I40E_PILE_VALID_BIT) {
232 			i++;
233 			continue;
234 		}
235 
236 		/* do we have enough in this lump? */
237 		for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
238 			if (pile->list[i+j] & I40E_PILE_VALID_BIT)
239 				break;
240 		}
241 
242 		if (j == needed) {
243 			/* there was enough, so assign it to the requestor */
244 			for (j = 0; j < needed; j++)
245 				pile->list[i+j] = id | I40E_PILE_VALID_BIT;
246 			ret = i;
247 			break;
248 		}
249 
250 		/* not enough, so skip over it and continue looking */
251 		i += j;
252 	}
253 
254 	return ret;
255 }
256 
257 /**
258  * i40e_put_lump - return a lump of generic resource
259  * @pile: the pile of resource to search
260  * @index: the base item index
261  * @id: the owner id of the items assigned
262  *
263  * Returns the count of items in the lump
264  **/
265 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
266 {
267 	int valid_id = (id | I40E_PILE_VALID_BIT);
268 	int count = 0;
269 	u16 i;
270 
271 	if (!pile || index >= pile->num_entries)
272 		return -EINVAL;
273 
274 	for (i = index;
275 	     i < pile->num_entries && pile->list[i] == valid_id;
276 	     i++) {
277 		pile->list[i] = 0;
278 		count++;
279 	}
280 
281 
282 	return count;
283 }
284 
285 /**
286  * i40e_find_vsi_from_id - searches for the vsi with the given id
287  * @pf: the pf structure to search for the vsi
288  * @id: id of the vsi it is searching for
289  **/
290 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
291 {
292 	int i;
293 
294 	for (i = 0; i < pf->num_alloc_vsi; i++)
295 		if (pf->vsi[i] && (pf->vsi[i]->id == id))
296 			return pf->vsi[i];
297 
298 	return NULL;
299 }
300 
301 /**
302  * i40e_service_event_schedule - Schedule the service task to wake up
303  * @pf: board private structure
304  *
305  * If not already scheduled, this puts the task into the work queue
306  **/
307 void i40e_service_event_schedule(struct i40e_pf *pf)
308 {
309 	if ((!test_bit(__I40E_DOWN, pf->state) &&
310 	     !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) ||
311 	      test_bit(__I40E_RECOVERY_MODE, pf->state))
312 		queue_work(i40e_wq, &pf->service_task);
313 }
314 
315 /**
316  * i40e_tx_timeout - Respond to a Tx Hang
317  * @netdev: network interface device structure
318  * @txqueue: queue number timing out
319  *
320  * If any port has noticed a Tx timeout, it is likely that the whole
321  * device is munged, not just the one netdev port, so go for the full
322  * reset.
323  **/
324 static void i40e_tx_timeout(struct net_device *netdev, unsigned int txqueue)
325 {
326 	struct i40e_netdev_priv *np = netdev_priv(netdev);
327 	struct i40e_vsi *vsi = np->vsi;
328 	struct i40e_pf *pf = vsi->back;
329 	struct i40e_ring *tx_ring = NULL;
330 	unsigned int i;
331 	u32 head, val;
332 
333 	pf->tx_timeout_count++;
334 
335 	/* with txqueue index, find the tx_ring struct */
336 	for (i = 0; i < vsi->num_queue_pairs; i++) {
337 		if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
338 			if (txqueue ==
339 			    vsi->tx_rings[i]->queue_index) {
340 				tx_ring = vsi->tx_rings[i];
341 				break;
342 			}
343 		}
344 	}
345 
346 	if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
347 		pf->tx_timeout_recovery_level = 1;  /* reset after some time */
348 	else if (time_before(jiffies,
349 		      (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
350 		return;   /* don't do any new action before the next timeout */
351 
352 	/* don't kick off another recovery if one is already pending */
353 	if (test_and_set_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state))
354 		return;
355 
356 	if (tx_ring) {
357 		head = i40e_get_head(tx_ring);
358 		/* Read interrupt register */
359 		if (pf->flags & I40E_FLAG_MSIX_ENABLED)
360 			val = rd32(&pf->hw,
361 			     I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
362 						tx_ring->vsi->base_vector - 1));
363 		else
364 			val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
365 
366 		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",
367 			    vsi->seid, txqueue, tx_ring->next_to_clean,
368 			    head, tx_ring->next_to_use,
369 			    readl(tx_ring->tail), val);
370 	}
371 
372 	pf->tx_timeout_last_recovery = jiffies;
373 	netdev_info(netdev, "tx_timeout recovery level %d, txqueue %d\n",
374 		    pf->tx_timeout_recovery_level, txqueue);
375 
376 	switch (pf->tx_timeout_recovery_level) {
377 	case 1:
378 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
379 		break;
380 	case 2:
381 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
382 		break;
383 	case 3:
384 		set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
385 		break;
386 	default:
387 		netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in non-recoverable state.\n");
388 		set_bit(__I40E_DOWN_REQUESTED, pf->state);
389 		set_bit(__I40E_VSI_DOWN_REQUESTED, vsi->state);
390 		break;
391 	}
392 
393 	i40e_service_event_schedule(pf);
394 	pf->tx_timeout_recovery_level++;
395 }
396 
397 /**
398  * i40e_get_vsi_stats_struct - Get System Network Statistics
399  * @vsi: the VSI we care about
400  *
401  * Returns the address of the device statistics structure.
402  * The statistics are actually updated from the service task.
403  **/
404 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
405 {
406 	return &vsi->net_stats;
407 }
408 
409 /**
410  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
411  * @ring: Tx ring to get statistics from
412  * @stats: statistics entry to be updated
413  **/
414 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
415 					    struct rtnl_link_stats64 *stats)
416 {
417 	u64 bytes, packets;
418 	unsigned int start;
419 
420 	do {
421 		start = u64_stats_fetch_begin_irq(&ring->syncp);
422 		packets = ring->stats.packets;
423 		bytes   = ring->stats.bytes;
424 	} while (u64_stats_fetch_retry_irq(&ring->syncp, start));
425 
426 	stats->tx_packets += packets;
427 	stats->tx_bytes   += bytes;
428 }
429 
430 /**
431  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
432  * @netdev: network interface device structure
433  * @stats: data structure to store statistics
434  *
435  * Returns the address of the device statistics structure.
436  * The statistics are actually updated from the service task.
437  **/
438 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
439 				  struct rtnl_link_stats64 *stats)
440 {
441 	struct i40e_netdev_priv *np = netdev_priv(netdev);
442 	struct i40e_vsi *vsi = np->vsi;
443 	struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
444 	struct i40e_ring *ring;
445 	int i;
446 
447 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
448 		return;
449 
450 	if (!vsi->tx_rings)
451 		return;
452 
453 	rcu_read_lock();
454 	for (i = 0; i < vsi->num_queue_pairs; i++) {
455 		u64 bytes, packets;
456 		unsigned int start;
457 
458 		ring = READ_ONCE(vsi->tx_rings[i]);
459 		if (!ring)
460 			continue;
461 		i40e_get_netdev_stats_struct_tx(ring, stats);
462 
463 		if (i40e_enabled_xdp_vsi(vsi)) {
464 			ring = READ_ONCE(vsi->xdp_rings[i]);
465 			if (!ring)
466 				continue;
467 			i40e_get_netdev_stats_struct_tx(ring, stats);
468 		}
469 
470 		ring = READ_ONCE(vsi->rx_rings[i]);
471 		if (!ring)
472 			continue;
473 		do {
474 			start   = u64_stats_fetch_begin_irq(&ring->syncp);
475 			packets = ring->stats.packets;
476 			bytes   = ring->stats.bytes;
477 		} while (u64_stats_fetch_retry_irq(&ring->syncp, start));
478 
479 		stats->rx_packets += packets;
480 		stats->rx_bytes   += bytes;
481 
482 	}
483 	rcu_read_unlock();
484 
485 	/* following stats updated by i40e_watchdog_subtask() */
486 	stats->multicast	= vsi_stats->multicast;
487 	stats->tx_errors	= vsi_stats->tx_errors;
488 	stats->tx_dropped	= vsi_stats->tx_dropped;
489 	stats->rx_errors	= vsi_stats->rx_errors;
490 	stats->rx_dropped	= vsi_stats->rx_dropped;
491 	stats->rx_crc_errors	= vsi_stats->rx_crc_errors;
492 	stats->rx_length_errors	= vsi_stats->rx_length_errors;
493 }
494 
495 /**
496  * i40e_vsi_reset_stats - Resets all stats of the given vsi
497  * @vsi: the VSI to have its stats reset
498  **/
499 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
500 {
501 	struct rtnl_link_stats64 *ns;
502 	int i;
503 
504 	if (!vsi)
505 		return;
506 
507 	ns = i40e_get_vsi_stats_struct(vsi);
508 	memset(ns, 0, sizeof(*ns));
509 	memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
510 	memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
511 	memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
512 	if (vsi->rx_rings && vsi->rx_rings[0]) {
513 		for (i = 0; i < vsi->num_queue_pairs; i++) {
514 			memset(&vsi->rx_rings[i]->stats, 0,
515 			       sizeof(vsi->rx_rings[i]->stats));
516 			memset(&vsi->rx_rings[i]->rx_stats, 0,
517 			       sizeof(vsi->rx_rings[i]->rx_stats));
518 			memset(&vsi->tx_rings[i]->stats, 0,
519 			       sizeof(vsi->tx_rings[i]->stats));
520 			memset(&vsi->tx_rings[i]->tx_stats, 0,
521 			       sizeof(vsi->tx_rings[i]->tx_stats));
522 		}
523 	}
524 	vsi->stat_offsets_loaded = false;
525 }
526 
527 /**
528  * i40e_pf_reset_stats - Reset all of the stats for the given PF
529  * @pf: the PF to be reset
530  **/
531 void i40e_pf_reset_stats(struct i40e_pf *pf)
532 {
533 	int i;
534 
535 	memset(&pf->stats, 0, sizeof(pf->stats));
536 	memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
537 	pf->stat_offsets_loaded = false;
538 
539 	for (i = 0; i < I40E_MAX_VEB; i++) {
540 		if (pf->veb[i]) {
541 			memset(&pf->veb[i]->stats, 0,
542 			       sizeof(pf->veb[i]->stats));
543 			memset(&pf->veb[i]->stats_offsets, 0,
544 			       sizeof(pf->veb[i]->stats_offsets));
545 			memset(&pf->veb[i]->tc_stats, 0,
546 			       sizeof(pf->veb[i]->tc_stats));
547 			memset(&pf->veb[i]->tc_stats_offsets, 0,
548 			       sizeof(pf->veb[i]->tc_stats_offsets));
549 			pf->veb[i]->stat_offsets_loaded = false;
550 		}
551 	}
552 	pf->hw_csum_rx_error = 0;
553 }
554 
555 /**
556  * i40e_compute_pci_to_hw_id - compute index form PCI function.
557  * @vsi: ptr to the VSI to read from.
558  * @hw: ptr to the hardware info.
559  **/
560 static u32 i40e_compute_pci_to_hw_id(struct i40e_vsi *vsi, struct i40e_hw *hw)
561 {
562 	int pf_count = i40e_get_pf_count(hw);
563 
564 	if (vsi->type == I40E_VSI_SRIOV)
565 		return (hw->port * BIT(7)) / pf_count + vsi->vf_id;
566 
567 	return hw->port + BIT(7);
568 }
569 
570 /**
571  * i40e_stat_update64 - read and update a 64 bit stat from the chip.
572  * @hw: ptr to the hardware info.
573  * @hireg: the high 32 bit reg to read.
574  * @loreg: the low 32 bit reg to read.
575  * @offset_loaded: has the initial offset been loaded yet.
576  * @offset: ptr to current offset value.
577  * @stat: ptr to the stat.
578  *
579  * Since the device stats are not reset at PFReset, they will not
580  * be zeroed when the driver starts.  We'll save the first values read
581  * and use them as offsets to be subtracted from the raw values in order
582  * to report stats that count from zero.
583  **/
584 static void i40e_stat_update64(struct i40e_hw *hw, u32 hireg, u32 loreg,
585 			       bool offset_loaded, u64 *offset, u64 *stat)
586 {
587 	u64 new_data;
588 
589 	new_data = rd64(hw, loreg);
590 
591 	if (!offset_loaded || new_data < *offset)
592 		*offset = new_data;
593 	*stat = new_data - *offset;
594 }
595 
596 /**
597  * i40e_stat_update48 - read and update a 48 bit stat from the chip
598  * @hw: ptr to the hardware info
599  * @hireg: the high 32 bit reg to read
600  * @loreg: the low 32 bit reg to read
601  * @offset_loaded: has the initial offset been loaded yet
602  * @offset: ptr to current offset value
603  * @stat: ptr to the stat
604  *
605  * Since the device stats are not reset at PFReset, they likely will not
606  * be zeroed when the driver starts.  We'll save the first values read
607  * and use them as offsets to be subtracted from the raw values in order
608  * to report stats that count from zero.  In the process, we also manage
609  * the potential roll-over.
610  **/
611 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
612 			       bool offset_loaded, u64 *offset, u64 *stat)
613 {
614 	u64 new_data;
615 
616 	if (hw->device_id == I40E_DEV_ID_QEMU) {
617 		new_data = rd32(hw, loreg);
618 		new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
619 	} else {
620 		new_data = rd64(hw, loreg);
621 	}
622 	if (!offset_loaded)
623 		*offset = new_data;
624 	if (likely(new_data >= *offset))
625 		*stat = new_data - *offset;
626 	else
627 		*stat = (new_data + BIT_ULL(48)) - *offset;
628 	*stat &= 0xFFFFFFFFFFFFULL;
629 }
630 
631 /**
632  * i40e_stat_update32 - read and update a 32 bit stat from the chip
633  * @hw: ptr to the hardware info
634  * @reg: the hw reg to read
635  * @offset_loaded: has the initial offset been loaded yet
636  * @offset: ptr to current offset value
637  * @stat: ptr to the stat
638  **/
639 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
640 			       bool offset_loaded, u64 *offset, u64 *stat)
641 {
642 	u32 new_data;
643 
644 	new_data = rd32(hw, reg);
645 	if (!offset_loaded)
646 		*offset = new_data;
647 	if (likely(new_data >= *offset))
648 		*stat = (u32)(new_data - *offset);
649 	else
650 		*stat = (u32)((new_data + BIT_ULL(32)) - *offset);
651 }
652 
653 /**
654  * i40e_stat_update_and_clear32 - read and clear hw reg, update a 32 bit stat
655  * @hw: ptr to the hardware info
656  * @reg: the hw reg to read and clear
657  * @stat: ptr to the stat
658  **/
659 static void i40e_stat_update_and_clear32(struct i40e_hw *hw, u32 reg, u64 *stat)
660 {
661 	u32 new_data = rd32(hw, reg);
662 
663 	wr32(hw, reg, 1); /* must write a nonzero value to clear register */
664 	*stat += new_data;
665 }
666 
667 /**
668  * i40e_stats_update_rx_discards - update rx_discards.
669  * @vsi: ptr to the VSI to be updated.
670  * @hw: ptr to the hardware info.
671  * @stat_idx: VSI's stat_counter_idx.
672  * @offset_loaded: ptr to the VSI's stat_offsets_loaded.
673  * @stat_offset: ptr to stat_offset to store first read of specific register.
674  * @stat: ptr to VSI's stat to be updated.
675  **/
676 static void
677 i40e_stats_update_rx_discards(struct i40e_vsi *vsi, struct i40e_hw *hw,
678 			      int stat_idx, bool offset_loaded,
679 			      struct i40e_eth_stats *stat_offset,
680 			      struct i40e_eth_stats *stat)
681 {
682 	u64 rx_rdpc, rx_rxerr;
683 
684 	i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx), offset_loaded,
685 			   &stat_offset->rx_discards, &rx_rdpc);
686 	i40e_stat_update64(hw,
687 			   I40E_GL_RXERR1H(i40e_compute_pci_to_hw_id(vsi, hw)),
688 			   I40E_GL_RXERR1L(i40e_compute_pci_to_hw_id(vsi, hw)),
689 			   offset_loaded, &stat_offset->rx_discards_other,
690 			   &rx_rxerr);
691 
692 	stat->rx_discards = rx_rdpc + rx_rxerr;
693 }
694 
695 /**
696  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
697  * @vsi: the VSI to be updated
698  **/
699 void i40e_update_eth_stats(struct i40e_vsi *vsi)
700 {
701 	int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
702 	struct i40e_pf *pf = vsi->back;
703 	struct i40e_hw *hw = &pf->hw;
704 	struct i40e_eth_stats *oes;
705 	struct i40e_eth_stats *es;     /* device's eth stats */
706 
707 	es = &vsi->eth_stats;
708 	oes = &vsi->eth_stats_offsets;
709 
710 	/* Gather up the stats that the hw collects */
711 	i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
712 			   vsi->stat_offsets_loaded,
713 			   &oes->tx_errors, &es->tx_errors);
714 	i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx),
715 			   vsi->stat_offsets_loaded,
716 			   &oes->rx_discards, &es->rx_discards);
717 	i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
718 			   vsi->stat_offsets_loaded,
719 			   &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
720 
721 	i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
722 			   I40E_GLV_GORCL(stat_idx),
723 			   vsi->stat_offsets_loaded,
724 			   &oes->rx_bytes, &es->rx_bytes);
725 	i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
726 			   I40E_GLV_UPRCL(stat_idx),
727 			   vsi->stat_offsets_loaded,
728 			   &oes->rx_unicast, &es->rx_unicast);
729 	i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
730 			   I40E_GLV_MPRCL(stat_idx),
731 			   vsi->stat_offsets_loaded,
732 			   &oes->rx_multicast, &es->rx_multicast);
733 	i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
734 			   I40E_GLV_BPRCL(stat_idx),
735 			   vsi->stat_offsets_loaded,
736 			   &oes->rx_broadcast, &es->rx_broadcast);
737 
738 	i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
739 			   I40E_GLV_GOTCL(stat_idx),
740 			   vsi->stat_offsets_loaded,
741 			   &oes->tx_bytes, &es->tx_bytes);
742 	i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
743 			   I40E_GLV_UPTCL(stat_idx),
744 			   vsi->stat_offsets_loaded,
745 			   &oes->tx_unicast, &es->tx_unicast);
746 	i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
747 			   I40E_GLV_MPTCL(stat_idx),
748 			   vsi->stat_offsets_loaded,
749 			   &oes->tx_multicast, &es->tx_multicast);
750 	i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
751 			   I40E_GLV_BPTCL(stat_idx),
752 			   vsi->stat_offsets_loaded,
753 			   &oes->tx_broadcast, &es->tx_broadcast);
754 
755 	i40e_stats_update_rx_discards(vsi, hw, stat_idx,
756 				      vsi->stat_offsets_loaded, oes, es);
757 
758 	vsi->stat_offsets_loaded = true;
759 }
760 
761 /**
762  * i40e_update_veb_stats - Update Switch component statistics
763  * @veb: the VEB being updated
764  **/
765 void i40e_update_veb_stats(struct i40e_veb *veb)
766 {
767 	struct i40e_pf *pf = veb->pf;
768 	struct i40e_hw *hw = &pf->hw;
769 	struct i40e_eth_stats *oes;
770 	struct i40e_eth_stats *es;     /* device's eth stats */
771 	struct i40e_veb_tc_stats *veb_oes;
772 	struct i40e_veb_tc_stats *veb_es;
773 	int i, idx = 0;
774 
775 	idx = veb->stats_idx;
776 	es = &veb->stats;
777 	oes = &veb->stats_offsets;
778 	veb_es = &veb->tc_stats;
779 	veb_oes = &veb->tc_stats_offsets;
780 
781 	/* Gather up the stats that the hw collects */
782 	i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
783 			   veb->stat_offsets_loaded,
784 			   &oes->tx_discards, &es->tx_discards);
785 	if (hw->revision_id > 0)
786 		i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
787 				   veb->stat_offsets_loaded,
788 				   &oes->rx_unknown_protocol,
789 				   &es->rx_unknown_protocol);
790 	i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
791 			   veb->stat_offsets_loaded,
792 			   &oes->rx_bytes, &es->rx_bytes);
793 	i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
794 			   veb->stat_offsets_loaded,
795 			   &oes->rx_unicast, &es->rx_unicast);
796 	i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
797 			   veb->stat_offsets_loaded,
798 			   &oes->rx_multicast, &es->rx_multicast);
799 	i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
800 			   veb->stat_offsets_loaded,
801 			   &oes->rx_broadcast, &es->rx_broadcast);
802 
803 	i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
804 			   veb->stat_offsets_loaded,
805 			   &oes->tx_bytes, &es->tx_bytes);
806 	i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
807 			   veb->stat_offsets_loaded,
808 			   &oes->tx_unicast, &es->tx_unicast);
809 	i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
810 			   veb->stat_offsets_loaded,
811 			   &oes->tx_multicast, &es->tx_multicast);
812 	i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
813 			   veb->stat_offsets_loaded,
814 			   &oes->tx_broadcast, &es->tx_broadcast);
815 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
816 		i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
817 				   I40E_GLVEBTC_RPCL(i, idx),
818 				   veb->stat_offsets_loaded,
819 				   &veb_oes->tc_rx_packets[i],
820 				   &veb_es->tc_rx_packets[i]);
821 		i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
822 				   I40E_GLVEBTC_RBCL(i, idx),
823 				   veb->stat_offsets_loaded,
824 				   &veb_oes->tc_rx_bytes[i],
825 				   &veb_es->tc_rx_bytes[i]);
826 		i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
827 				   I40E_GLVEBTC_TPCL(i, idx),
828 				   veb->stat_offsets_loaded,
829 				   &veb_oes->tc_tx_packets[i],
830 				   &veb_es->tc_tx_packets[i]);
831 		i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
832 				   I40E_GLVEBTC_TBCL(i, idx),
833 				   veb->stat_offsets_loaded,
834 				   &veb_oes->tc_tx_bytes[i],
835 				   &veb_es->tc_tx_bytes[i]);
836 	}
837 	veb->stat_offsets_loaded = true;
838 }
839 
840 /**
841  * i40e_update_vsi_stats - Update the vsi statistics counters.
842  * @vsi: the VSI to be updated
843  *
844  * There are a few instances where we store the same stat in a
845  * couple of different structs.  This is partly because we have
846  * the netdev stats that need to be filled out, which is slightly
847  * different from the "eth_stats" defined by the chip and used in
848  * VF communications.  We sort it out here.
849  **/
850 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
851 {
852 	u64 rx_page, rx_buf, rx_reuse, rx_alloc, rx_waive, rx_busy;
853 	struct i40e_pf *pf = vsi->back;
854 	struct rtnl_link_stats64 *ons;
855 	struct rtnl_link_stats64 *ns;   /* netdev stats */
856 	struct i40e_eth_stats *oes;
857 	struct i40e_eth_stats *es;     /* device's eth stats */
858 	u64 tx_restart, tx_busy;
859 	struct i40e_ring *p;
860 	u64 bytes, packets;
861 	unsigned int start;
862 	u64 tx_linearize;
863 	u64 tx_force_wb;
864 	u64 tx_stopped;
865 	u64 rx_p, rx_b;
866 	u64 tx_p, tx_b;
867 	u16 q;
868 
869 	if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
870 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
871 		return;
872 
873 	ns = i40e_get_vsi_stats_struct(vsi);
874 	ons = &vsi->net_stats_offsets;
875 	es = &vsi->eth_stats;
876 	oes = &vsi->eth_stats_offsets;
877 
878 	/* Gather up the netdev and vsi stats that the driver collects
879 	 * on the fly during packet processing
880 	 */
881 	rx_b = rx_p = 0;
882 	tx_b = tx_p = 0;
883 	tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
884 	tx_stopped = 0;
885 	rx_page = 0;
886 	rx_buf = 0;
887 	rx_reuse = 0;
888 	rx_alloc = 0;
889 	rx_waive = 0;
890 	rx_busy = 0;
891 	rcu_read_lock();
892 	for (q = 0; q < vsi->num_queue_pairs; q++) {
893 		/* locate Tx ring */
894 		p = READ_ONCE(vsi->tx_rings[q]);
895 		if (!p)
896 			continue;
897 
898 		do {
899 			start = u64_stats_fetch_begin_irq(&p->syncp);
900 			packets = p->stats.packets;
901 			bytes = p->stats.bytes;
902 		} while (u64_stats_fetch_retry_irq(&p->syncp, start));
903 		tx_b += bytes;
904 		tx_p += packets;
905 		tx_restart += p->tx_stats.restart_queue;
906 		tx_busy += p->tx_stats.tx_busy;
907 		tx_linearize += p->tx_stats.tx_linearize;
908 		tx_force_wb += p->tx_stats.tx_force_wb;
909 		tx_stopped += p->tx_stats.tx_stopped;
910 
911 		/* locate Rx ring */
912 		p = READ_ONCE(vsi->rx_rings[q]);
913 		if (!p)
914 			continue;
915 
916 		do {
917 			start = u64_stats_fetch_begin_irq(&p->syncp);
918 			packets = p->stats.packets;
919 			bytes = p->stats.bytes;
920 		} while (u64_stats_fetch_retry_irq(&p->syncp, start));
921 		rx_b += bytes;
922 		rx_p += packets;
923 		rx_buf += p->rx_stats.alloc_buff_failed;
924 		rx_page += p->rx_stats.alloc_page_failed;
925 		rx_reuse += p->rx_stats.page_reuse_count;
926 		rx_alloc += p->rx_stats.page_alloc_count;
927 		rx_waive += p->rx_stats.page_waive_count;
928 		rx_busy += p->rx_stats.page_busy_count;
929 
930 		if (i40e_enabled_xdp_vsi(vsi)) {
931 			/* locate XDP ring */
932 			p = READ_ONCE(vsi->xdp_rings[q]);
933 			if (!p)
934 				continue;
935 
936 			do {
937 				start = u64_stats_fetch_begin_irq(&p->syncp);
938 				packets = p->stats.packets;
939 				bytes = p->stats.bytes;
940 			} while (u64_stats_fetch_retry_irq(&p->syncp, start));
941 			tx_b += bytes;
942 			tx_p += packets;
943 			tx_restart += p->tx_stats.restart_queue;
944 			tx_busy += p->tx_stats.tx_busy;
945 			tx_linearize += p->tx_stats.tx_linearize;
946 			tx_force_wb += p->tx_stats.tx_force_wb;
947 		}
948 	}
949 	rcu_read_unlock();
950 	vsi->tx_restart = tx_restart;
951 	vsi->tx_busy = tx_busy;
952 	vsi->tx_linearize = tx_linearize;
953 	vsi->tx_force_wb = tx_force_wb;
954 	vsi->tx_stopped = tx_stopped;
955 	vsi->rx_page_failed = rx_page;
956 	vsi->rx_buf_failed = rx_buf;
957 	vsi->rx_page_reuse = rx_reuse;
958 	vsi->rx_page_alloc = rx_alloc;
959 	vsi->rx_page_waive = rx_waive;
960 	vsi->rx_page_busy = rx_busy;
961 
962 	ns->rx_packets = rx_p;
963 	ns->rx_bytes = rx_b;
964 	ns->tx_packets = tx_p;
965 	ns->tx_bytes = tx_b;
966 
967 	/* update netdev stats from eth stats */
968 	i40e_update_eth_stats(vsi);
969 	ons->tx_errors = oes->tx_errors;
970 	ns->tx_errors = es->tx_errors;
971 	ons->multicast = oes->rx_multicast;
972 	ns->multicast = es->rx_multicast;
973 	ons->rx_dropped = oes->rx_discards;
974 	ns->rx_dropped = es->rx_discards;
975 	ons->tx_dropped = oes->tx_discards;
976 	ns->tx_dropped = es->tx_discards;
977 
978 	/* pull in a couple PF stats if this is the main vsi */
979 	if (vsi == pf->vsi[pf->lan_vsi]) {
980 		ns->rx_crc_errors = pf->stats.crc_errors;
981 		ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
982 		ns->rx_length_errors = pf->stats.rx_length_errors;
983 	}
984 }
985 
986 /**
987  * i40e_update_pf_stats - Update the PF statistics counters.
988  * @pf: the PF to be updated
989  **/
990 static void i40e_update_pf_stats(struct i40e_pf *pf)
991 {
992 	struct i40e_hw_port_stats *osd = &pf->stats_offsets;
993 	struct i40e_hw_port_stats *nsd = &pf->stats;
994 	struct i40e_hw *hw = &pf->hw;
995 	u32 val;
996 	int i;
997 
998 	i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
999 			   I40E_GLPRT_GORCL(hw->port),
1000 			   pf->stat_offsets_loaded,
1001 			   &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
1002 	i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
1003 			   I40E_GLPRT_GOTCL(hw->port),
1004 			   pf->stat_offsets_loaded,
1005 			   &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
1006 	i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
1007 			   pf->stat_offsets_loaded,
1008 			   &osd->eth.rx_discards,
1009 			   &nsd->eth.rx_discards);
1010 	i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
1011 			   I40E_GLPRT_UPRCL(hw->port),
1012 			   pf->stat_offsets_loaded,
1013 			   &osd->eth.rx_unicast,
1014 			   &nsd->eth.rx_unicast);
1015 	i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
1016 			   I40E_GLPRT_MPRCL(hw->port),
1017 			   pf->stat_offsets_loaded,
1018 			   &osd->eth.rx_multicast,
1019 			   &nsd->eth.rx_multicast);
1020 	i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
1021 			   I40E_GLPRT_BPRCL(hw->port),
1022 			   pf->stat_offsets_loaded,
1023 			   &osd->eth.rx_broadcast,
1024 			   &nsd->eth.rx_broadcast);
1025 	i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
1026 			   I40E_GLPRT_UPTCL(hw->port),
1027 			   pf->stat_offsets_loaded,
1028 			   &osd->eth.tx_unicast,
1029 			   &nsd->eth.tx_unicast);
1030 	i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
1031 			   I40E_GLPRT_MPTCL(hw->port),
1032 			   pf->stat_offsets_loaded,
1033 			   &osd->eth.tx_multicast,
1034 			   &nsd->eth.tx_multicast);
1035 	i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
1036 			   I40E_GLPRT_BPTCL(hw->port),
1037 			   pf->stat_offsets_loaded,
1038 			   &osd->eth.tx_broadcast,
1039 			   &nsd->eth.tx_broadcast);
1040 
1041 	i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
1042 			   pf->stat_offsets_loaded,
1043 			   &osd->tx_dropped_link_down,
1044 			   &nsd->tx_dropped_link_down);
1045 
1046 	i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
1047 			   pf->stat_offsets_loaded,
1048 			   &osd->crc_errors, &nsd->crc_errors);
1049 
1050 	i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
1051 			   pf->stat_offsets_loaded,
1052 			   &osd->illegal_bytes, &nsd->illegal_bytes);
1053 
1054 	i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
1055 			   pf->stat_offsets_loaded,
1056 			   &osd->mac_local_faults,
1057 			   &nsd->mac_local_faults);
1058 	i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
1059 			   pf->stat_offsets_loaded,
1060 			   &osd->mac_remote_faults,
1061 			   &nsd->mac_remote_faults);
1062 
1063 	i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
1064 			   pf->stat_offsets_loaded,
1065 			   &osd->rx_length_errors,
1066 			   &nsd->rx_length_errors);
1067 
1068 	i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
1069 			   pf->stat_offsets_loaded,
1070 			   &osd->link_xon_rx, &nsd->link_xon_rx);
1071 	i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
1072 			   pf->stat_offsets_loaded,
1073 			   &osd->link_xon_tx, &nsd->link_xon_tx);
1074 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
1075 			   pf->stat_offsets_loaded,
1076 			   &osd->link_xoff_rx, &nsd->link_xoff_rx);
1077 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
1078 			   pf->stat_offsets_loaded,
1079 			   &osd->link_xoff_tx, &nsd->link_xoff_tx);
1080 
1081 	for (i = 0; i < 8; i++) {
1082 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
1083 				   pf->stat_offsets_loaded,
1084 				   &osd->priority_xoff_rx[i],
1085 				   &nsd->priority_xoff_rx[i]);
1086 		i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
1087 				   pf->stat_offsets_loaded,
1088 				   &osd->priority_xon_rx[i],
1089 				   &nsd->priority_xon_rx[i]);
1090 		i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
1091 				   pf->stat_offsets_loaded,
1092 				   &osd->priority_xon_tx[i],
1093 				   &nsd->priority_xon_tx[i]);
1094 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
1095 				   pf->stat_offsets_loaded,
1096 				   &osd->priority_xoff_tx[i],
1097 				   &nsd->priority_xoff_tx[i]);
1098 		i40e_stat_update32(hw,
1099 				   I40E_GLPRT_RXON2OFFCNT(hw->port, i),
1100 				   pf->stat_offsets_loaded,
1101 				   &osd->priority_xon_2_xoff[i],
1102 				   &nsd->priority_xon_2_xoff[i]);
1103 	}
1104 
1105 	i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
1106 			   I40E_GLPRT_PRC64L(hw->port),
1107 			   pf->stat_offsets_loaded,
1108 			   &osd->rx_size_64, &nsd->rx_size_64);
1109 	i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
1110 			   I40E_GLPRT_PRC127L(hw->port),
1111 			   pf->stat_offsets_loaded,
1112 			   &osd->rx_size_127, &nsd->rx_size_127);
1113 	i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
1114 			   I40E_GLPRT_PRC255L(hw->port),
1115 			   pf->stat_offsets_loaded,
1116 			   &osd->rx_size_255, &nsd->rx_size_255);
1117 	i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
1118 			   I40E_GLPRT_PRC511L(hw->port),
1119 			   pf->stat_offsets_loaded,
1120 			   &osd->rx_size_511, &nsd->rx_size_511);
1121 	i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
1122 			   I40E_GLPRT_PRC1023L(hw->port),
1123 			   pf->stat_offsets_loaded,
1124 			   &osd->rx_size_1023, &nsd->rx_size_1023);
1125 	i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
1126 			   I40E_GLPRT_PRC1522L(hw->port),
1127 			   pf->stat_offsets_loaded,
1128 			   &osd->rx_size_1522, &nsd->rx_size_1522);
1129 	i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
1130 			   I40E_GLPRT_PRC9522L(hw->port),
1131 			   pf->stat_offsets_loaded,
1132 			   &osd->rx_size_big, &nsd->rx_size_big);
1133 
1134 	i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1135 			   I40E_GLPRT_PTC64L(hw->port),
1136 			   pf->stat_offsets_loaded,
1137 			   &osd->tx_size_64, &nsd->tx_size_64);
1138 	i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1139 			   I40E_GLPRT_PTC127L(hw->port),
1140 			   pf->stat_offsets_loaded,
1141 			   &osd->tx_size_127, &nsd->tx_size_127);
1142 	i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1143 			   I40E_GLPRT_PTC255L(hw->port),
1144 			   pf->stat_offsets_loaded,
1145 			   &osd->tx_size_255, &nsd->tx_size_255);
1146 	i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1147 			   I40E_GLPRT_PTC511L(hw->port),
1148 			   pf->stat_offsets_loaded,
1149 			   &osd->tx_size_511, &nsd->tx_size_511);
1150 	i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1151 			   I40E_GLPRT_PTC1023L(hw->port),
1152 			   pf->stat_offsets_loaded,
1153 			   &osd->tx_size_1023, &nsd->tx_size_1023);
1154 	i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1155 			   I40E_GLPRT_PTC1522L(hw->port),
1156 			   pf->stat_offsets_loaded,
1157 			   &osd->tx_size_1522, &nsd->tx_size_1522);
1158 	i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1159 			   I40E_GLPRT_PTC9522L(hw->port),
1160 			   pf->stat_offsets_loaded,
1161 			   &osd->tx_size_big, &nsd->tx_size_big);
1162 
1163 	i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1164 			   pf->stat_offsets_loaded,
1165 			   &osd->rx_undersize, &nsd->rx_undersize);
1166 	i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1167 			   pf->stat_offsets_loaded,
1168 			   &osd->rx_fragments, &nsd->rx_fragments);
1169 	i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1170 			   pf->stat_offsets_loaded,
1171 			   &osd->rx_oversize, &nsd->rx_oversize);
1172 	i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1173 			   pf->stat_offsets_loaded,
1174 			   &osd->rx_jabber, &nsd->rx_jabber);
1175 
1176 	/* FDIR stats */
1177 	i40e_stat_update_and_clear32(hw,
1178 			I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(hw->pf_id)),
1179 			&nsd->fd_atr_match);
1180 	i40e_stat_update_and_clear32(hw,
1181 			I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(hw->pf_id)),
1182 			&nsd->fd_sb_match);
1183 	i40e_stat_update_and_clear32(hw,
1184 			I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(hw->pf_id)),
1185 			&nsd->fd_atr_tunnel_match);
1186 
1187 	val = rd32(hw, I40E_PRTPM_EEE_STAT);
1188 	nsd->tx_lpi_status =
1189 		       (val & I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK) >>
1190 			I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_SHIFT;
1191 	nsd->rx_lpi_status =
1192 		       (val & I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK) >>
1193 			I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_SHIFT;
1194 	i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1195 			   pf->stat_offsets_loaded,
1196 			   &osd->tx_lpi_count, &nsd->tx_lpi_count);
1197 	i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1198 			   pf->stat_offsets_loaded,
1199 			   &osd->rx_lpi_count, &nsd->rx_lpi_count);
1200 
1201 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED &&
1202 	    !test_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
1203 		nsd->fd_sb_status = true;
1204 	else
1205 		nsd->fd_sb_status = false;
1206 
1207 	if (pf->flags & I40E_FLAG_FD_ATR_ENABLED &&
1208 	    !test_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
1209 		nsd->fd_atr_status = true;
1210 	else
1211 		nsd->fd_atr_status = false;
1212 
1213 	pf->stat_offsets_loaded = true;
1214 }
1215 
1216 /**
1217  * i40e_update_stats - Update the various statistics counters.
1218  * @vsi: the VSI to be updated
1219  *
1220  * Update the various stats for this VSI and its related entities.
1221  **/
1222 void i40e_update_stats(struct i40e_vsi *vsi)
1223 {
1224 	struct i40e_pf *pf = vsi->back;
1225 
1226 	if (vsi == pf->vsi[pf->lan_vsi])
1227 		i40e_update_pf_stats(pf);
1228 
1229 	i40e_update_vsi_stats(vsi);
1230 }
1231 
1232 /**
1233  * i40e_count_filters - counts VSI mac filters
1234  * @vsi: the VSI to be searched
1235  *
1236  * Returns count of mac filters
1237  **/
1238 int i40e_count_filters(struct i40e_vsi *vsi)
1239 {
1240 	struct i40e_mac_filter *f;
1241 	struct hlist_node *h;
1242 	int bkt;
1243 	int cnt = 0;
1244 
1245 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
1246 		++cnt;
1247 
1248 	return cnt;
1249 }
1250 
1251 /**
1252  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1253  * @vsi: the VSI to be searched
1254  * @macaddr: the MAC address
1255  * @vlan: the vlan
1256  *
1257  * Returns ptr to the filter object or NULL
1258  **/
1259 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1260 						const u8 *macaddr, s16 vlan)
1261 {
1262 	struct i40e_mac_filter *f;
1263 	u64 key;
1264 
1265 	if (!vsi || !macaddr)
1266 		return NULL;
1267 
1268 	key = i40e_addr_to_hkey(macaddr);
1269 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1270 		if ((ether_addr_equal(macaddr, f->macaddr)) &&
1271 		    (vlan == f->vlan))
1272 			return f;
1273 	}
1274 	return NULL;
1275 }
1276 
1277 /**
1278  * i40e_find_mac - Find a mac addr in the macvlan filters list
1279  * @vsi: the VSI to be searched
1280  * @macaddr: the MAC address we are searching for
1281  *
1282  * Returns the first filter with the provided MAC address or NULL if
1283  * MAC address was not found
1284  **/
1285 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1286 {
1287 	struct i40e_mac_filter *f;
1288 	u64 key;
1289 
1290 	if (!vsi || !macaddr)
1291 		return NULL;
1292 
1293 	key = i40e_addr_to_hkey(macaddr);
1294 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1295 		if ((ether_addr_equal(macaddr, f->macaddr)))
1296 			return f;
1297 	}
1298 	return NULL;
1299 }
1300 
1301 /**
1302  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1303  * @vsi: the VSI to be searched
1304  *
1305  * Returns true if VSI is in vlan mode or false otherwise
1306  **/
1307 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1308 {
1309 	/* If we have a PVID, always operate in VLAN mode */
1310 	if (vsi->info.pvid)
1311 		return true;
1312 
1313 	/* We need to operate in VLAN mode whenever we have any filters with
1314 	 * a VLAN other than I40E_VLAN_ALL. We could check the table each
1315 	 * time, incurring search cost repeatedly. However, we can notice two
1316 	 * things:
1317 	 *
1318 	 * 1) the only place where we can gain a VLAN filter is in
1319 	 *    i40e_add_filter.
1320 	 *
1321 	 * 2) the only place where filters are actually removed is in
1322 	 *    i40e_sync_filters_subtask.
1323 	 *
1324 	 * Thus, we can simply use a boolean value, has_vlan_filters which we
1325 	 * will set to true when we add a VLAN filter in i40e_add_filter. Then
1326 	 * we have to perform the full search after deleting filters in
1327 	 * i40e_sync_filters_subtask, but we already have to search
1328 	 * filters here and can perform the check at the same time. This
1329 	 * results in avoiding embedding a loop for VLAN mode inside another
1330 	 * loop over all the filters, and should maintain correctness as noted
1331 	 * above.
1332 	 */
1333 	return vsi->has_vlan_filter;
1334 }
1335 
1336 /**
1337  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1338  * @vsi: the VSI to configure
1339  * @tmp_add_list: list of filters ready to be added
1340  * @tmp_del_list: list of filters ready to be deleted
1341  * @vlan_filters: the number of active VLAN filters
1342  *
1343  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1344  * behave as expected. If we have any active VLAN filters remaining or about
1345  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1346  * so that they only match against untagged traffic. If we no longer have any
1347  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1348  * so that they match against both tagged and untagged traffic. In this way,
1349  * we ensure that we correctly receive the desired traffic. This ensures that
1350  * when we have an active VLAN we will receive only untagged traffic and
1351  * traffic matching active VLANs. If we have no active VLANs then we will
1352  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1353  *
1354  * Finally, in a similar fashion, this function also corrects filters when
1355  * there is an active PVID assigned to this VSI.
1356  *
1357  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1358  *
1359  * This function is only expected to be called from within
1360  * i40e_sync_vsi_filters.
1361  *
1362  * NOTE: This function expects to be called while under the
1363  * mac_filter_hash_lock
1364  */
1365 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1366 					 struct hlist_head *tmp_add_list,
1367 					 struct hlist_head *tmp_del_list,
1368 					 int vlan_filters)
1369 {
1370 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1371 	struct i40e_mac_filter *f, *add_head;
1372 	struct i40e_new_mac_filter *new;
1373 	struct hlist_node *h;
1374 	int bkt, new_vlan;
1375 
1376 	/* To determine if a particular filter needs to be replaced we
1377 	 * have the three following conditions:
1378 	 *
1379 	 * a) if we have a PVID assigned, then all filters which are
1380 	 *    not marked as VLAN=PVID must be replaced with filters that
1381 	 *    are.
1382 	 * b) otherwise, if we have any active VLANS, all filters
1383 	 *    which are marked as VLAN=-1 must be replaced with
1384 	 *    filters marked as VLAN=0
1385 	 * c) finally, if we do not have any active VLANS, all filters
1386 	 *    which are marked as VLAN=0 must be replaced with filters
1387 	 *    marked as VLAN=-1
1388 	 */
1389 
1390 	/* Update the filters about to be added in place */
1391 	hlist_for_each_entry(new, tmp_add_list, hlist) {
1392 		if (pvid && new->f->vlan != pvid)
1393 			new->f->vlan = pvid;
1394 		else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1395 			new->f->vlan = 0;
1396 		else if (!vlan_filters && new->f->vlan == 0)
1397 			new->f->vlan = I40E_VLAN_ANY;
1398 	}
1399 
1400 	/* Update the remaining active filters */
1401 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1402 		/* Combine the checks for whether a filter needs to be changed
1403 		 * and then determine the new VLAN inside the if block, in
1404 		 * order to avoid duplicating code for adding the new filter
1405 		 * then deleting the old filter.
1406 		 */
1407 		if ((pvid && f->vlan != pvid) ||
1408 		    (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1409 		    (!vlan_filters && f->vlan == 0)) {
1410 			/* Determine the new vlan we will be adding */
1411 			if (pvid)
1412 				new_vlan = pvid;
1413 			else if (vlan_filters)
1414 				new_vlan = 0;
1415 			else
1416 				new_vlan = I40E_VLAN_ANY;
1417 
1418 			/* Create the new filter */
1419 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1420 			if (!add_head)
1421 				return -ENOMEM;
1422 
1423 			/* Create a temporary i40e_new_mac_filter */
1424 			new = kzalloc(sizeof(*new), GFP_ATOMIC);
1425 			if (!new)
1426 				return -ENOMEM;
1427 
1428 			new->f = add_head;
1429 			new->state = add_head->state;
1430 
1431 			/* Add the new filter to the tmp list */
1432 			hlist_add_head(&new->hlist, tmp_add_list);
1433 
1434 			/* Put the original filter into the delete list */
1435 			f->state = I40E_FILTER_REMOVE;
1436 			hash_del(&f->hlist);
1437 			hlist_add_head(&f->hlist, tmp_del_list);
1438 		}
1439 	}
1440 
1441 	vsi->has_vlan_filter = !!vlan_filters;
1442 
1443 	return 0;
1444 }
1445 
1446 /**
1447  * i40e_get_vf_new_vlan - Get new vlan id on a vf
1448  * @vsi: the vsi to configure
1449  * @new_mac: new mac filter to be added
1450  * @f: existing mac filter, replaced with new_mac->f if new_mac is not NULL
1451  * @vlan_filters: the number of active VLAN filters
1452  * @trusted: flag if the VF is trusted
1453  *
1454  * Get new VLAN id based on current VLAN filters, trust, PVID
1455  * and vf-vlan-prune-disable flag.
1456  *
1457  * Returns the value of the new vlan filter or
1458  * the old value if no new filter is needed.
1459  */
1460 static s16 i40e_get_vf_new_vlan(struct i40e_vsi *vsi,
1461 				struct i40e_new_mac_filter *new_mac,
1462 				struct i40e_mac_filter *f,
1463 				int vlan_filters,
1464 				bool trusted)
1465 {
1466 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1467 	struct i40e_pf *pf = vsi->back;
1468 	bool is_any;
1469 
1470 	if (new_mac)
1471 		f = new_mac->f;
1472 
1473 	if (pvid && f->vlan != pvid)
1474 		return pvid;
1475 
1476 	is_any = (trusted ||
1477 		  !(pf->flags & I40E_FLAG_VF_VLAN_PRUNING));
1478 
1479 	if ((vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1480 	    (!is_any && !vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1481 	    (is_any && !vlan_filters && f->vlan == 0)) {
1482 		if (is_any)
1483 			return I40E_VLAN_ANY;
1484 		else
1485 			return 0;
1486 	}
1487 
1488 	return f->vlan;
1489 }
1490 
1491 /**
1492  * i40e_correct_vf_mac_vlan_filters - Correct non-VLAN VF filters if necessary
1493  * @vsi: the vsi to configure
1494  * @tmp_add_list: list of filters ready to be added
1495  * @tmp_del_list: list of filters ready to be deleted
1496  * @vlan_filters: the number of active VLAN filters
1497  * @trusted: flag if the VF is trusted
1498  *
1499  * Correct VF VLAN filters based on current VLAN filters, trust, PVID
1500  * and vf-vlan-prune-disable flag.
1501  *
1502  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1503  *
1504  * This function is only expected to be called from within
1505  * i40e_sync_vsi_filters.
1506  *
1507  * NOTE: This function expects to be called while under the
1508  * mac_filter_hash_lock
1509  */
1510 static int i40e_correct_vf_mac_vlan_filters(struct i40e_vsi *vsi,
1511 					    struct hlist_head *tmp_add_list,
1512 					    struct hlist_head *tmp_del_list,
1513 					    int vlan_filters,
1514 					    bool trusted)
1515 {
1516 	struct i40e_mac_filter *f, *add_head;
1517 	struct i40e_new_mac_filter *new_mac;
1518 	struct hlist_node *h;
1519 	int bkt, new_vlan;
1520 
1521 	hlist_for_each_entry(new_mac, tmp_add_list, hlist) {
1522 		new_mac->f->vlan = i40e_get_vf_new_vlan(vsi, new_mac, NULL,
1523 							vlan_filters, trusted);
1524 	}
1525 
1526 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1527 		new_vlan = i40e_get_vf_new_vlan(vsi, NULL, f, vlan_filters,
1528 						trusted);
1529 		if (new_vlan != f->vlan) {
1530 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1531 			if (!add_head)
1532 				return -ENOMEM;
1533 			/* Create a temporary i40e_new_mac_filter */
1534 			new_mac = kzalloc(sizeof(*new_mac), GFP_ATOMIC);
1535 			if (!new_mac)
1536 				return -ENOMEM;
1537 			new_mac->f = add_head;
1538 			new_mac->state = add_head->state;
1539 
1540 			/* Add the new filter to the tmp list */
1541 			hlist_add_head(&new_mac->hlist, tmp_add_list);
1542 
1543 			/* Put the original filter into the delete list */
1544 			f->state = I40E_FILTER_REMOVE;
1545 			hash_del(&f->hlist);
1546 			hlist_add_head(&f->hlist, tmp_del_list);
1547 		}
1548 	}
1549 
1550 	vsi->has_vlan_filter = !!vlan_filters;
1551 	return 0;
1552 }
1553 
1554 /**
1555  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1556  * @vsi: the PF Main VSI - inappropriate for any other VSI
1557  * @macaddr: the MAC address
1558  *
1559  * Remove whatever filter the firmware set up so the driver can manage
1560  * its own filtering intelligently.
1561  **/
1562 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1563 {
1564 	struct i40e_aqc_remove_macvlan_element_data element;
1565 	struct i40e_pf *pf = vsi->back;
1566 
1567 	/* Only appropriate for the PF main VSI */
1568 	if (vsi->type != I40E_VSI_MAIN)
1569 		return;
1570 
1571 	memset(&element, 0, sizeof(element));
1572 	ether_addr_copy(element.mac_addr, macaddr);
1573 	element.vlan_tag = 0;
1574 	/* Ignore error returns, some firmware does it this way... */
1575 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1576 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1577 
1578 	memset(&element, 0, sizeof(element));
1579 	ether_addr_copy(element.mac_addr, macaddr);
1580 	element.vlan_tag = 0;
1581 	/* ...and some firmware does it this way. */
1582 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1583 			I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1584 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1585 }
1586 
1587 /**
1588  * i40e_add_filter - Add a mac/vlan filter to the VSI
1589  * @vsi: the VSI to be searched
1590  * @macaddr: the MAC address
1591  * @vlan: the vlan
1592  *
1593  * Returns ptr to the filter object or NULL when no memory available.
1594  *
1595  * NOTE: This function is expected to be called with mac_filter_hash_lock
1596  * being held.
1597  **/
1598 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1599 					const u8 *macaddr, s16 vlan)
1600 {
1601 	struct i40e_mac_filter *f;
1602 	u64 key;
1603 
1604 	if (!vsi || !macaddr)
1605 		return NULL;
1606 
1607 	f = i40e_find_filter(vsi, macaddr, vlan);
1608 	if (!f) {
1609 		f = kzalloc(sizeof(*f), GFP_ATOMIC);
1610 		if (!f)
1611 			return NULL;
1612 
1613 		/* Update the boolean indicating if we need to function in
1614 		 * VLAN mode.
1615 		 */
1616 		if (vlan >= 0)
1617 			vsi->has_vlan_filter = true;
1618 
1619 		ether_addr_copy(f->macaddr, macaddr);
1620 		f->vlan = vlan;
1621 		f->state = I40E_FILTER_NEW;
1622 		INIT_HLIST_NODE(&f->hlist);
1623 
1624 		key = i40e_addr_to_hkey(macaddr);
1625 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
1626 
1627 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1628 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1629 	}
1630 
1631 	/* If we're asked to add a filter that has been marked for removal, it
1632 	 * is safe to simply restore it to active state. __i40e_del_filter
1633 	 * will have simply deleted any filters which were previously marked
1634 	 * NEW or FAILED, so if it is currently marked REMOVE it must have
1635 	 * previously been ACTIVE. Since we haven't yet run the sync filters
1636 	 * task, just restore this filter to the ACTIVE state so that the
1637 	 * sync task leaves it in place
1638 	 */
1639 	if (f->state == I40E_FILTER_REMOVE)
1640 		f->state = I40E_FILTER_ACTIVE;
1641 
1642 	return f;
1643 }
1644 
1645 /**
1646  * __i40e_del_filter - Remove a specific filter from the VSI
1647  * @vsi: VSI to remove from
1648  * @f: the filter to remove from the list
1649  *
1650  * This function should be called instead of i40e_del_filter only if you know
1651  * the exact filter you will remove already, such as via i40e_find_filter or
1652  * i40e_find_mac.
1653  *
1654  * NOTE: This function is expected to be called with mac_filter_hash_lock
1655  * being held.
1656  * ANOTHER NOTE: This function MUST be called from within the context of
1657  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1658  * instead of list_for_each_entry().
1659  **/
1660 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1661 {
1662 	if (!f)
1663 		return;
1664 
1665 	/* If the filter was never added to firmware then we can just delete it
1666 	 * directly and we don't want to set the status to remove or else an
1667 	 * admin queue command will unnecessarily fire.
1668 	 */
1669 	if ((f->state == I40E_FILTER_FAILED) ||
1670 	    (f->state == I40E_FILTER_NEW)) {
1671 		hash_del(&f->hlist);
1672 		kfree(f);
1673 	} else {
1674 		f->state = I40E_FILTER_REMOVE;
1675 	}
1676 
1677 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1678 	set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1679 }
1680 
1681 /**
1682  * i40e_del_filter - Remove a MAC/VLAN filter from the VSI
1683  * @vsi: the VSI to be searched
1684  * @macaddr: the MAC address
1685  * @vlan: the VLAN
1686  *
1687  * NOTE: This function is expected to be called with mac_filter_hash_lock
1688  * being held.
1689  * ANOTHER NOTE: This function MUST be called from within the context of
1690  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1691  * instead of list_for_each_entry().
1692  **/
1693 void i40e_del_filter(struct i40e_vsi *vsi, const u8 *macaddr, s16 vlan)
1694 {
1695 	struct i40e_mac_filter *f;
1696 
1697 	if (!vsi || !macaddr)
1698 		return;
1699 
1700 	f = i40e_find_filter(vsi, macaddr, vlan);
1701 	__i40e_del_filter(vsi, f);
1702 }
1703 
1704 /**
1705  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1706  * @vsi: the VSI to be searched
1707  * @macaddr: the mac address to be filtered
1708  *
1709  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1710  * go through all the macvlan filters and add a macvlan filter for each
1711  * unique vlan that already exists. If a PVID has been assigned, instead only
1712  * add the macaddr to that VLAN.
1713  *
1714  * Returns last filter added on success, else NULL
1715  **/
1716 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1717 					    const u8 *macaddr)
1718 {
1719 	struct i40e_mac_filter *f, *add = NULL;
1720 	struct hlist_node *h;
1721 	int bkt;
1722 
1723 	if (vsi->info.pvid)
1724 		return i40e_add_filter(vsi, macaddr,
1725 				       le16_to_cpu(vsi->info.pvid));
1726 
1727 	if (!i40e_is_vsi_in_vlan(vsi))
1728 		return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1729 
1730 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1731 		if (f->state == I40E_FILTER_REMOVE)
1732 			continue;
1733 		add = i40e_add_filter(vsi, macaddr, f->vlan);
1734 		if (!add)
1735 			return NULL;
1736 	}
1737 
1738 	return add;
1739 }
1740 
1741 /**
1742  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1743  * @vsi: the VSI to be searched
1744  * @macaddr: the mac address to be removed
1745  *
1746  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1747  * associated with.
1748  *
1749  * Returns 0 for success, or error
1750  **/
1751 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1752 {
1753 	struct i40e_mac_filter *f;
1754 	struct hlist_node *h;
1755 	bool found = false;
1756 	int bkt;
1757 
1758 	lockdep_assert_held(&vsi->mac_filter_hash_lock);
1759 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1760 		if (ether_addr_equal(macaddr, f->macaddr)) {
1761 			__i40e_del_filter(vsi, f);
1762 			found = true;
1763 		}
1764 	}
1765 
1766 	if (found)
1767 		return 0;
1768 	else
1769 		return -ENOENT;
1770 }
1771 
1772 /**
1773  * i40e_set_mac - NDO callback to set mac address
1774  * @netdev: network interface device structure
1775  * @p: pointer to an address structure
1776  *
1777  * Returns 0 on success, negative on failure
1778  **/
1779 static int i40e_set_mac(struct net_device *netdev, void *p)
1780 {
1781 	struct i40e_netdev_priv *np = netdev_priv(netdev);
1782 	struct i40e_vsi *vsi = np->vsi;
1783 	struct i40e_pf *pf = vsi->back;
1784 	struct i40e_hw *hw = &pf->hw;
1785 	struct sockaddr *addr = p;
1786 
1787 	if (!is_valid_ether_addr(addr->sa_data))
1788 		return -EADDRNOTAVAIL;
1789 
1790 	if (ether_addr_equal(netdev->dev_addr, addr->sa_data)) {
1791 		netdev_info(netdev, "already using mac address %pM\n",
1792 			    addr->sa_data);
1793 		return 0;
1794 	}
1795 
1796 	if (test_bit(__I40E_DOWN, pf->state) ||
1797 	    test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1798 		return -EADDRNOTAVAIL;
1799 
1800 	if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1801 		netdev_info(netdev, "returning to hw mac address %pM\n",
1802 			    hw->mac.addr);
1803 	else
1804 		netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1805 
1806 	/* Copy the address first, so that we avoid a possible race with
1807 	 * .set_rx_mode().
1808 	 * - Remove old address from MAC filter
1809 	 * - Copy new address
1810 	 * - Add new address to MAC filter
1811 	 */
1812 	spin_lock_bh(&vsi->mac_filter_hash_lock);
1813 	i40e_del_mac_filter(vsi, netdev->dev_addr);
1814 	eth_hw_addr_set(netdev, addr->sa_data);
1815 	i40e_add_mac_filter(vsi, netdev->dev_addr);
1816 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
1817 
1818 	if (vsi->type == I40E_VSI_MAIN) {
1819 		i40e_status ret;
1820 
1821 		ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1822 						addr->sa_data, NULL);
1823 		if (ret)
1824 			netdev_info(netdev, "Ignoring error from firmware on LAA update, status %s, AQ ret %s\n",
1825 				    i40e_stat_str(hw, ret),
1826 				    i40e_aq_str(hw, hw->aq.asq_last_status));
1827 	}
1828 
1829 	/* schedule our worker thread which will take care of
1830 	 * applying the new filter changes
1831 	 */
1832 	i40e_service_event_schedule(pf);
1833 	return 0;
1834 }
1835 
1836 /**
1837  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1838  * @vsi: vsi structure
1839  * @seed: RSS hash seed
1840  * @lut: pointer to lookup table of lut_size
1841  * @lut_size: size of the lookup table
1842  **/
1843 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1844 			      u8 *lut, u16 lut_size)
1845 {
1846 	struct i40e_pf *pf = vsi->back;
1847 	struct i40e_hw *hw = &pf->hw;
1848 	int ret = 0;
1849 
1850 	if (seed) {
1851 		struct i40e_aqc_get_set_rss_key_data *seed_dw =
1852 			(struct i40e_aqc_get_set_rss_key_data *)seed;
1853 		ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1854 		if (ret) {
1855 			dev_info(&pf->pdev->dev,
1856 				 "Cannot set RSS key, err %s aq_err %s\n",
1857 				 i40e_stat_str(hw, ret),
1858 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1859 			return ret;
1860 		}
1861 	}
1862 	if (lut) {
1863 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
1864 
1865 		ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1866 		if (ret) {
1867 			dev_info(&pf->pdev->dev,
1868 				 "Cannot set RSS lut, err %s aq_err %s\n",
1869 				 i40e_stat_str(hw, ret),
1870 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1871 			return ret;
1872 		}
1873 	}
1874 	return ret;
1875 }
1876 
1877 /**
1878  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1879  * @vsi: VSI structure
1880  **/
1881 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1882 {
1883 	struct i40e_pf *pf = vsi->back;
1884 	u8 seed[I40E_HKEY_ARRAY_SIZE];
1885 	u8 *lut;
1886 	int ret;
1887 
1888 	if (!(pf->hw_features & I40E_HW_RSS_AQ_CAPABLE))
1889 		return 0;
1890 	if (!vsi->rss_size)
1891 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
1892 				      vsi->num_queue_pairs);
1893 	if (!vsi->rss_size)
1894 		return -EINVAL;
1895 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1896 	if (!lut)
1897 		return -ENOMEM;
1898 
1899 	/* Use the user configured hash keys and lookup table if there is one,
1900 	 * otherwise use default
1901 	 */
1902 	if (vsi->rss_lut_user)
1903 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1904 	else
1905 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1906 	if (vsi->rss_hkey_user)
1907 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1908 	else
1909 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1910 	ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1911 	kfree(lut);
1912 	return ret;
1913 }
1914 
1915 /**
1916  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1917  * @vsi: the VSI being configured,
1918  * @ctxt: VSI context structure
1919  * @enabled_tc: number of traffic classes to enable
1920  *
1921  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1922  **/
1923 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1924 					   struct i40e_vsi_context *ctxt,
1925 					   u8 enabled_tc)
1926 {
1927 	u16 qcount = 0, max_qcount, qmap, sections = 0;
1928 	int i, override_q, pow, num_qps, ret;
1929 	u8 netdev_tc = 0, offset = 0;
1930 
1931 	if (vsi->type != I40E_VSI_MAIN)
1932 		return -EINVAL;
1933 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1934 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1935 	vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1936 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1937 	num_qps = vsi->mqprio_qopt.qopt.count[0];
1938 
1939 	/* find the next higher power-of-2 of num queue pairs */
1940 	pow = ilog2(num_qps);
1941 	if (!is_power_of_2(num_qps))
1942 		pow++;
1943 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1944 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1945 
1946 	/* Setup queue offset/count for all TCs for given VSI */
1947 	max_qcount = vsi->mqprio_qopt.qopt.count[0];
1948 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1949 		/* See if the given TC is enabled for the given VSI */
1950 		if (vsi->tc_config.enabled_tc & BIT(i)) {
1951 			offset = vsi->mqprio_qopt.qopt.offset[i];
1952 			qcount = vsi->mqprio_qopt.qopt.count[i];
1953 			if (qcount > max_qcount)
1954 				max_qcount = qcount;
1955 			vsi->tc_config.tc_info[i].qoffset = offset;
1956 			vsi->tc_config.tc_info[i].qcount = qcount;
1957 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1958 		} else {
1959 			/* TC is not enabled so set the offset to
1960 			 * default queue and allocate one queue
1961 			 * for the given TC.
1962 			 */
1963 			vsi->tc_config.tc_info[i].qoffset = 0;
1964 			vsi->tc_config.tc_info[i].qcount = 1;
1965 			vsi->tc_config.tc_info[i].netdev_tc = 0;
1966 		}
1967 	}
1968 
1969 	/* Set actual Tx/Rx queue pairs */
1970 	vsi->num_queue_pairs = offset + qcount;
1971 
1972 	/* Setup queue TC[0].qmap for given VSI context */
1973 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1974 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1975 	ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1976 	ctxt->info.valid_sections |= cpu_to_le16(sections);
1977 
1978 	/* Reconfigure RSS for main VSI with max queue count */
1979 	vsi->rss_size = max_qcount;
1980 	ret = i40e_vsi_config_rss(vsi);
1981 	if (ret) {
1982 		dev_info(&vsi->back->pdev->dev,
1983 			 "Failed to reconfig rss for num_queues (%u)\n",
1984 			 max_qcount);
1985 		return ret;
1986 	}
1987 	vsi->reconfig_rss = true;
1988 	dev_dbg(&vsi->back->pdev->dev,
1989 		"Reconfigured rss with num_queues (%u)\n", max_qcount);
1990 
1991 	/* Find queue count available for channel VSIs and starting offset
1992 	 * for channel VSIs
1993 	 */
1994 	override_q = vsi->mqprio_qopt.qopt.count[0];
1995 	if (override_q && override_q < vsi->num_queue_pairs) {
1996 		vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
1997 		vsi->next_base_queue = override_q;
1998 	}
1999 	return 0;
2000 }
2001 
2002 /**
2003  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
2004  * @vsi: the VSI being setup
2005  * @ctxt: VSI context structure
2006  * @enabled_tc: Enabled TCs bitmap
2007  * @is_add: True if called before Add VSI
2008  *
2009  * Setup VSI queue mapping for enabled traffic classes.
2010  **/
2011 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
2012 				     struct i40e_vsi_context *ctxt,
2013 				     u8 enabled_tc,
2014 				     bool is_add)
2015 {
2016 	struct i40e_pf *pf = vsi->back;
2017 	u16 num_tc_qps = 0;
2018 	u16 sections = 0;
2019 	u8 netdev_tc = 0;
2020 	u16 numtc = 1;
2021 	u16 qcount;
2022 	u8 offset;
2023 	u16 qmap;
2024 	int i;
2025 
2026 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
2027 	offset = 0;
2028 	/* zero out queue mapping, it will get updated on the end of the function */
2029 	memset(ctxt->info.queue_mapping, 0, sizeof(ctxt->info.queue_mapping));
2030 
2031 	if (vsi->type == I40E_VSI_MAIN) {
2032 		/* This code helps add more queue to the VSI if we have
2033 		 * more cores than RSS can support, the higher cores will
2034 		 * be served by ATR or other filters. Furthermore, the
2035 		 * non-zero req_queue_pairs says that user requested a new
2036 		 * queue count via ethtool's set_channels, so use this
2037 		 * value for queues distribution across traffic classes
2038 		 * We need at least one queue pair for the interface
2039 		 * to be usable as we see in else statement.
2040 		 */
2041 		if (vsi->req_queue_pairs > 0)
2042 			vsi->num_queue_pairs = vsi->req_queue_pairs;
2043 		else if (pf->flags & I40E_FLAG_MSIX_ENABLED)
2044 			vsi->num_queue_pairs = pf->num_lan_msix;
2045 		else
2046 			vsi->num_queue_pairs = 1;
2047 	}
2048 
2049 	/* Number of queues per enabled TC */
2050 	if (vsi->type == I40E_VSI_MAIN ||
2051 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs != 0))
2052 		num_tc_qps = vsi->num_queue_pairs;
2053 	else
2054 		num_tc_qps = vsi->alloc_queue_pairs;
2055 
2056 	if (enabled_tc && (vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
2057 		/* Find numtc from enabled TC bitmap */
2058 		for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2059 			if (enabled_tc & BIT(i)) /* TC is enabled */
2060 				numtc++;
2061 		}
2062 		if (!numtc) {
2063 			dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
2064 			numtc = 1;
2065 		}
2066 		num_tc_qps = num_tc_qps / numtc;
2067 		num_tc_qps = min_t(int, num_tc_qps,
2068 				   i40e_pf_get_max_q_per_tc(pf));
2069 	}
2070 
2071 	vsi->tc_config.numtc = numtc;
2072 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
2073 
2074 	/* Do not allow use more TC queue pairs than MSI-X vectors exist */
2075 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
2076 		num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
2077 
2078 	/* Setup queue offset/count for all TCs for given VSI */
2079 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2080 		/* See if the given TC is enabled for the given VSI */
2081 		if (vsi->tc_config.enabled_tc & BIT(i)) {
2082 			/* TC is enabled */
2083 			int pow, num_qps;
2084 
2085 			switch (vsi->type) {
2086 			case I40E_VSI_MAIN:
2087 				if (!(pf->flags & (I40E_FLAG_FD_SB_ENABLED |
2088 				    I40E_FLAG_FD_ATR_ENABLED)) ||
2089 				    vsi->tc_config.enabled_tc != 1) {
2090 					qcount = min_t(int, pf->alloc_rss_size,
2091 						       num_tc_qps);
2092 					break;
2093 				}
2094 				fallthrough;
2095 			case I40E_VSI_FDIR:
2096 			case I40E_VSI_SRIOV:
2097 			case I40E_VSI_VMDQ2:
2098 			default:
2099 				qcount = num_tc_qps;
2100 				WARN_ON(i != 0);
2101 				break;
2102 			}
2103 			vsi->tc_config.tc_info[i].qoffset = offset;
2104 			vsi->tc_config.tc_info[i].qcount = qcount;
2105 
2106 			/* find the next higher power-of-2 of num queue pairs */
2107 			num_qps = qcount;
2108 			pow = 0;
2109 			while (num_qps && (BIT_ULL(pow) < qcount)) {
2110 				pow++;
2111 				num_qps >>= 1;
2112 			}
2113 
2114 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
2115 			qmap =
2116 			    (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
2117 			    (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
2118 
2119 			offset += qcount;
2120 		} else {
2121 			/* TC is not enabled so set the offset to
2122 			 * default queue and allocate one queue
2123 			 * for the given TC.
2124 			 */
2125 			vsi->tc_config.tc_info[i].qoffset = 0;
2126 			vsi->tc_config.tc_info[i].qcount = 1;
2127 			vsi->tc_config.tc_info[i].netdev_tc = 0;
2128 
2129 			qmap = 0;
2130 		}
2131 		ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
2132 	}
2133 	/* Do not change previously set num_queue_pairs for PFs and VFs*/
2134 	if ((vsi->type == I40E_VSI_MAIN && numtc != 1) ||
2135 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs == 0) ||
2136 	    (vsi->type != I40E_VSI_MAIN && vsi->type != I40E_VSI_SRIOV))
2137 		vsi->num_queue_pairs = offset;
2138 
2139 	/* Scheduler section valid can only be set for ADD VSI */
2140 	if (is_add) {
2141 		sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
2142 
2143 		ctxt->info.up_enable_bits = enabled_tc;
2144 	}
2145 	if (vsi->type == I40E_VSI_SRIOV) {
2146 		ctxt->info.mapping_flags |=
2147 				     cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
2148 		for (i = 0; i < vsi->num_queue_pairs; i++)
2149 			ctxt->info.queue_mapping[i] =
2150 					       cpu_to_le16(vsi->base_queue + i);
2151 	} else {
2152 		ctxt->info.mapping_flags |=
2153 					cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
2154 		ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
2155 	}
2156 	ctxt->info.valid_sections |= cpu_to_le16(sections);
2157 }
2158 
2159 /**
2160  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
2161  * @netdev: the netdevice
2162  * @addr: address to add
2163  *
2164  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
2165  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2166  */
2167 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
2168 {
2169 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2170 	struct i40e_vsi *vsi = np->vsi;
2171 
2172 	if (i40e_add_mac_filter(vsi, addr))
2173 		return 0;
2174 	else
2175 		return -ENOMEM;
2176 }
2177 
2178 /**
2179  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
2180  * @netdev: the netdevice
2181  * @addr: address to add
2182  *
2183  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
2184  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2185  */
2186 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
2187 {
2188 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2189 	struct i40e_vsi *vsi = np->vsi;
2190 
2191 	/* Under some circumstances, we might receive a request to delete
2192 	 * our own device address from our uc list. Because we store the
2193 	 * device address in the VSI's MAC/VLAN filter list, we need to ignore
2194 	 * such requests and not delete our device address from this list.
2195 	 */
2196 	if (ether_addr_equal(addr, netdev->dev_addr))
2197 		return 0;
2198 
2199 	i40e_del_mac_filter(vsi, addr);
2200 
2201 	return 0;
2202 }
2203 
2204 /**
2205  * i40e_set_rx_mode - NDO callback to set the netdev filters
2206  * @netdev: network interface device structure
2207  **/
2208 static void i40e_set_rx_mode(struct net_device *netdev)
2209 {
2210 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2211 	struct i40e_vsi *vsi = np->vsi;
2212 
2213 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2214 
2215 	__dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2216 	__dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2217 
2218 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2219 
2220 	/* check for other flag changes */
2221 	if (vsi->current_netdev_flags != vsi->netdev->flags) {
2222 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2223 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
2224 	}
2225 }
2226 
2227 /**
2228  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
2229  * @vsi: Pointer to VSI struct
2230  * @from: Pointer to list which contains MAC filter entries - changes to
2231  *        those entries needs to be undone.
2232  *
2233  * MAC filter entries from this list were slated for deletion.
2234  **/
2235 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
2236 					 struct hlist_head *from)
2237 {
2238 	struct i40e_mac_filter *f;
2239 	struct hlist_node *h;
2240 
2241 	hlist_for_each_entry_safe(f, h, from, hlist) {
2242 		u64 key = i40e_addr_to_hkey(f->macaddr);
2243 
2244 		/* Move the element back into MAC filter list*/
2245 		hlist_del(&f->hlist);
2246 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
2247 	}
2248 }
2249 
2250 /**
2251  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
2252  * @vsi: Pointer to vsi struct
2253  * @from: Pointer to list which contains MAC filter entries - changes to
2254  *        those entries needs to be undone.
2255  *
2256  * MAC filter entries from this list were slated for addition.
2257  **/
2258 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
2259 					 struct hlist_head *from)
2260 {
2261 	struct i40e_new_mac_filter *new;
2262 	struct hlist_node *h;
2263 
2264 	hlist_for_each_entry_safe(new, h, from, hlist) {
2265 		/* We can simply free the wrapper structure */
2266 		hlist_del(&new->hlist);
2267 		netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2268 		kfree(new);
2269 	}
2270 }
2271 
2272 /**
2273  * i40e_next_filter - Get the next non-broadcast filter from a list
2274  * @next: pointer to filter in list
2275  *
2276  * Returns the next non-broadcast filter in the list. Required so that we
2277  * ignore broadcast filters within the list, since these are not handled via
2278  * the normal firmware update path.
2279  */
2280 static
2281 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2282 {
2283 	hlist_for_each_entry_continue(next, hlist) {
2284 		if (!is_broadcast_ether_addr(next->f->macaddr))
2285 			return next;
2286 	}
2287 
2288 	return NULL;
2289 }
2290 
2291 /**
2292  * i40e_update_filter_state - Update filter state based on return data
2293  * from firmware
2294  * @count: Number of filters added
2295  * @add_list: return data from fw
2296  * @add_head: pointer to first filter in current batch
2297  *
2298  * MAC filter entries from list were slated to be added to device. Returns
2299  * number of successful filters. Note that 0 does NOT mean success!
2300  **/
2301 static int
2302 i40e_update_filter_state(int count,
2303 			 struct i40e_aqc_add_macvlan_element_data *add_list,
2304 			 struct i40e_new_mac_filter *add_head)
2305 {
2306 	int retval = 0;
2307 	int i;
2308 
2309 	for (i = 0; i < count; i++) {
2310 		/* Always check status of each filter. We don't need to check
2311 		 * the firmware return status because we pre-set the filter
2312 		 * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2313 		 * request to the adminq. Thus, if it no longer matches then
2314 		 * we know the filter is active.
2315 		 */
2316 		if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2317 			add_head->state = I40E_FILTER_FAILED;
2318 		} else {
2319 			add_head->state = I40E_FILTER_ACTIVE;
2320 			retval++;
2321 		}
2322 
2323 		add_head = i40e_next_filter(add_head);
2324 		if (!add_head)
2325 			break;
2326 	}
2327 
2328 	return retval;
2329 }
2330 
2331 /**
2332  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2333  * @vsi: ptr to the VSI
2334  * @vsi_name: name to display in messages
2335  * @list: the list of filters to send to firmware
2336  * @num_del: the number of filters to delete
2337  * @retval: Set to -EIO on failure to delete
2338  *
2339  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2340  * *retval instead of a return value so that success does not force ret_val to
2341  * be set to 0. This ensures that a sequence of calls to this function
2342  * preserve the previous value of *retval on successful delete.
2343  */
2344 static
2345 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2346 			  struct i40e_aqc_remove_macvlan_element_data *list,
2347 			  int num_del, int *retval)
2348 {
2349 	struct i40e_hw *hw = &vsi->back->hw;
2350 	enum i40e_admin_queue_err aq_status;
2351 	i40e_status aq_ret;
2352 
2353 	aq_ret = i40e_aq_remove_macvlan_v2(hw, vsi->seid, list, num_del, NULL,
2354 					   &aq_status);
2355 
2356 	/* Explicitly ignore and do not report when firmware returns ENOENT */
2357 	if (aq_ret && !(aq_status == I40E_AQ_RC_ENOENT)) {
2358 		*retval = -EIO;
2359 		dev_info(&vsi->back->pdev->dev,
2360 			 "ignoring delete macvlan error on %s, err %s, aq_err %s\n",
2361 			 vsi_name, i40e_stat_str(hw, aq_ret),
2362 			 i40e_aq_str(hw, aq_status));
2363 	}
2364 }
2365 
2366 /**
2367  * i40e_aqc_add_filters - Request firmware to add a set of filters
2368  * @vsi: ptr to the VSI
2369  * @vsi_name: name to display in messages
2370  * @list: the list of filters to send to firmware
2371  * @add_head: Position in the add hlist
2372  * @num_add: the number of filters to add
2373  *
2374  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2375  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2376  * space for more filters.
2377  */
2378 static
2379 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2380 			  struct i40e_aqc_add_macvlan_element_data *list,
2381 			  struct i40e_new_mac_filter *add_head,
2382 			  int num_add)
2383 {
2384 	struct i40e_hw *hw = &vsi->back->hw;
2385 	enum i40e_admin_queue_err aq_status;
2386 	int fcnt;
2387 
2388 	i40e_aq_add_macvlan_v2(hw, vsi->seid, list, num_add, NULL, &aq_status);
2389 	fcnt = i40e_update_filter_state(num_add, list, add_head);
2390 
2391 	if (fcnt != num_add) {
2392 		if (vsi->type == I40E_VSI_MAIN) {
2393 			set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2394 			dev_warn(&vsi->back->pdev->dev,
2395 				 "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2396 				 i40e_aq_str(hw, aq_status), vsi_name);
2397 		} else if (vsi->type == I40E_VSI_SRIOV ||
2398 			   vsi->type == I40E_VSI_VMDQ1 ||
2399 			   vsi->type == I40E_VSI_VMDQ2) {
2400 			dev_warn(&vsi->back->pdev->dev,
2401 				 "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2402 				 i40e_aq_str(hw, aq_status), vsi_name,
2403 					     vsi_name);
2404 		} else {
2405 			dev_warn(&vsi->back->pdev->dev,
2406 				 "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2407 				 i40e_aq_str(hw, aq_status), vsi_name,
2408 					     vsi->type);
2409 		}
2410 	}
2411 }
2412 
2413 /**
2414  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2415  * @vsi: pointer to the VSI
2416  * @vsi_name: the VSI name
2417  * @f: filter data
2418  *
2419  * This function sets or clears the promiscuous broadcast flags for VLAN
2420  * filters in order to properly receive broadcast frames. Assumes that only
2421  * broadcast filters are passed.
2422  *
2423  * Returns status indicating success or failure;
2424  **/
2425 static i40e_status
2426 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2427 			  struct i40e_mac_filter *f)
2428 {
2429 	bool enable = f->state == I40E_FILTER_NEW;
2430 	struct i40e_hw *hw = &vsi->back->hw;
2431 	i40e_status aq_ret;
2432 
2433 	if (f->vlan == I40E_VLAN_ANY) {
2434 		aq_ret = i40e_aq_set_vsi_broadcast(hw,
2435 						   vsi->seid,
2436 						   enable,
2437 						   NULL);
2438 	} else {
2439 		aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2440 							    vsi->seid,
2441 							    enable,
2442 							    f->vlan,
2443 							    NULL);
2444 	}
2445 
2446 	if (aq_ret) {
2447 		set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2448 		dev_warn(&vsi->back->pdev->dev,
2449 			 "Error %s, forcing overflow promiscuous on %s\n",
2450 			 i40e_aq_str(hw, hw->aq.asq_last_status),
2451 			 vsi_name);
2452 	}
2453 
2454 	return aq_ret;
2455 }
2456 
2457 /**
2458  * i40e_set_promiscuous - set promiscuous mode
2459  * @pf: board private structure
2460  * @promisc: promisc on or off
2461  *
2462  * There are different ways of setting promiscuous mode on a PF depending on
2463  * what state/environment we're in.  This identifies and sets it appropriately.
2464  * Returns 0 on success.
2465  **/
2466 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2467 {
2468 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
2469 	struct i40e_hw *hw = &pf->hw;
2470 	i40e_status aq_ret;
2471 
2472 	if (vsi->type == I40E_VSI_MAIN &&
2473 	    pf->lan_veb != I40E_NO_VEB &&
2474 	    !(pf->flags & I40E_FLAG_MFP_ENABLED)) {
2475 		/* set defport ON for Main VSI instead of true promisc
2476 		 * this way we will get all unicast/multicast and VLAN
2477 		 * promisc behavior but will not get VF or VMDq traffic
2478 		 * replicated on the Main VSI.
2479 		 */
2480 		if (promisc)
2481 			aq_ret = i40e_aq_set_default_vsi(hw,
2482 							 vsi->seid,
2483 							 NULL);
2484 		else
2485 			aq_ret = i40e_aq_clear_default_vsi(hw,
2486 							   vsi->seid,
2487 							   NULL);
2488 		if (aq_ret) {
2489 			dev_info(&pf->pdev->dev,
2490 				 "Set default VSI failed, err %s, aq_err %s\n",
2491 				 i40e_stat_str(hw, aq_ret),
2492 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2493 		}
2494 	} else {
2495 		aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2496 						  hw,
2497 						  vsi->seid,
2498 						  promisc, NULL,
2499 						  true);
2500 		if (aq_ret) {
2501 			dev_info(&pf->pdev->dev,
2502 				 "set unicast promisc failed, err %s, aq_err %s\n",
2503 				 i40e_stat_str(hw, aq_ret),
2504 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2505 		}
2506 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2507 						  hw,
2508 						  vsi->seid,
2509 						  promisc, NULL);
2510 		if (aq_ret) {
2511 			dev_info(&pf->pdev->dev,
2512 				 "set multicast promisc failed, err %s, aq_err %s\n",
2513 				 i40e_stat_str(hw, aq_ret),
2514 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2515 		}
2516 	}
2517 
2518 	if (!aq_ret)
2519 		pf->cur_promisc = promisc;
2520 
2521 	return aq_ret;
2522 }
2523 
2524 /**
2525  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2526  * @vsi: ptr to the VSI
2527  *
2528  * Push any outstanding VSI filter changes through the AdminQ.
2529  *
2530  * Returns 0 or error value
2531  **/
2532 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2533 {
2534 	struct hlist_head tmp_add_list, tmp_del_list;
2535 	struct i40e_mac_filter *f;
2536 	struct i40e_new_mac_filter *new, *add_head = NULL;
2537 	struct i40e_hw *hw = &vsi->back->hw;
2538 	bool old_overflow, new_overflow;
2539 	unsigned int failed_filters = 0;
2540 	unsigned int vlan_filters = 0;
2541 	char vsi_name[16] = "PF";
2542 	int filter_list_len = 0;
2543 	i40e_status aq_ret = 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 retval = 0;
2550 	u16 cmd_flags;
2551 	int list_size;
2552 	int bkt;
2553 
2554 	/* empty array typed pointers, kcalloc later */
2555 	struct i40e_aqc_add_macvlan_element_data *add_list;
2556 	struct i40e_aqc_remove_macvlan_element_data *del_list;
2557 
2558 	while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2559 		usleep_range(1000, 2000);
2560 	pf = vsi->back;
2561 
2562 	old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2563 
2564 	if (vsi->netdev) {
2565 		changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2566 		vsi->current_netdev_flags = vsi->netdev->flags;
2567 	}
2568 
2569 	INIT_HLIST_HEAD(&tmp_add_list);
2570 	INIT_HLIST_HEAD(&tmp_del_list);
2571 
2572 	if (vsi->type == I40E_VSI_SRIOV)
2573 		snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2574 	else if (vsi->type != I40E_VSI_MAIN)
2575 		snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2576 
2577 	if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2578 		vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2579 
2580 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2581 		/* Create a list of filters to delete. */
2582 		hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2583 			if (f->state == I40E_FILTER_REMOVE) {
2584 				/* Move the element into temporary del_list */
2585 				hash_del(&f->hlist);
2586 				hlist_add_head(&f->hlist, &tmp_del_list);
2587 
2588 				/* Avoid counting removed filters */
2589 				continue;
2590 			}
2591 			if (f->state == I40E_FILTER_NEW) {
2592 				/* Create a temporary i40e_new_mac_filter */
2593 				new = kzalloc(sizeof(*new), GFP_ATOMIC);
2594 				if (!new)
2595 					goto err_no_memory_locked;
2596 
2597 				/* Store pointer to the real filter */
2598 				new->f = f;
2599 				new->state = f->state;
2600 
2601 				/* Add it to the hash list */
2602 				hlist_add_head(&new->hlist, &tmp_add_list);
2603 			}
2604 
2605 			/* Count the number of active (current and new) VLAN
2606 			 * filters we have now. Does not count filters which
2607 			 * are marked for deletion.
2608 			 */
2609 			if (f->vlan > 0)
2610 				vlan_filters++;
2611 		}
2612 
2613 		if (vsi->type != I40E_VSI_SRIOV)
2614 			retval = i40e_correct_mac_vlan_filters
2615 				(vsi, &tmp_add_list, &tmp_del_list,
2616 				 vlan_filters);
2617 		else
2618 			retval = i40e_correct_vf_mac_vlan_filters
2619 				(vsi, &tmp_add_list, &tmp_del_list,
2620 				 vlan_filters, pf->vf[vsi->vf_id].trusted);
2621 
2622 		hlist_for_each_entry(new, &tmp_add_list, hlist)
2623 			netdev_hw_addr_refcnt(new->f, vsi->netdev, 1);
2624 
2625 		if (retval)
2626 			goto err_no_memory_locked;
2627 
2628 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2629 	}
2630 
2631 	/* Now process 'del_list' outside the lock */
2632 	if (!hlist_empty(&tmp_del_list)) {
2633 		filter_list_len = hw->aq.asq_buf_size /
2634 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2635 		list_size = filter_list_len *
2636 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2637 		del_list = kzalloc(list_size, GFP_ATOMIC);
2638 		if (!del_list)
2639 			goto err_no_memory;
2640 
2641 		hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2642 			cmd_flags = 0;
2643 
2644 			/* handle broadcast filters by updating the broadcast
2645 			 * promiscuous flag and release filter list.
2646 			 */
2647 			if (is_broadcast_ether_addr(f->macaddr)) {
2648 				i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2649 
2650 				hlist_del(&f->hlist);
2651 				kfree(f);
2652 				continue;
2653 			}
2654 
2655 			/* add to delete list */
2656 			ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2657 			if (f->vlan == I40E_VLAN_ANY) {
2658 				del_list[num_del].vlan_tag = 0;
2659 				cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2660 			} else {
2661 				del_list[num_del].vlan_tag =
2662 					cpu_to_le16((u16)(f->vlan));
2663 			}
2664 
2665 			cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2666 			del_list[num_del].flags = cmd_flags;
2667 			num_del++;
2668 
2669 			/* flush a full buffer */
2670 			if (num_del == filter_list_len) {
2671 				i40e_aqc_del_filters(vsi, vsi_name, del_list,
2672 						     num_del, &retval);
2673 				memset(del_list, 0, list_size);
2674 				num_del = 0;
2675 			}
2676 			/* Release memory for MAC filter entries which were
2677 			 * synced up with HW.
2678 			 */
2679 			hlist_del(&f->hlist);
2680 			kfree(f);
2681 		}
2682 
2683 		if (num_del) {
2684 			i40e_aqc_del_filters(vsi, vsi_name, del_list,
2685 					     num_del, &retval);
2686 		}
2687 
2688 		kfree(del_list);
2689 		del_list = NULL;
2690 	}
2691 
2692 	if (!hlist_empty(&tmp_add_list)) {
2693 		/* Do all the adds now. */
2694 		filter_list_len = hw->aq.asq_buf_size /
2695 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2696 		list_size = filter_list_len *
2697 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2698 		add_list = kzalloc(list_size, GFP_ATOMIC);
2699 		if (!add_list)
2700 			goto err_no_memory;
2701 
2702 		num_add = 0;
2703 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2704 			/* handle broadcast filters by updating the broadcast
2705 			 * promiscuous flag instead of adding a MAC filter.
2706 			 */
2707 			if (is_broadcast_ether_addr(new->f->macaddr)) {
2708 				if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2709 							      new->f))
2710 					new->state = I40E_FILTER_FAILED;
2711 				else
2712 					new->state = I40E_FILTER_ACTIVE;
2713 				continue;
2714 			}
2715 
2716 			/* add to add array */
2717 			if (num_add == 0)
2718 				add_head = new;
2719 			cmd_flags = 0;
2720 			ether_addr_copy(add_list[num_add].mac_addr,
2721 					new->f->macaddr);
2722 			if (new->f->vlan == I40E_VLAN_ANY) {
2723 				add_list[num_add].vlan_tag = 0;
2724 				cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2725 			} else {
2726 				add_list[num_add].vlan_tag =
2727 					cpu_to_le16((u16)(new->f->vlan));
2728 			}
2729 			add_list[num_add].queue_number = 0;
2730 			/* set invalid match method for later detection */
2731 			add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2732 			cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2733 			add_list[num_add].flags = cpu_to_le16(cmd_flags);
2734 			num_add++;
2735 
2736 			/* flush a full buffer */
2737 			if (num_add == filter_list_len) {
2738 				i40e_aqc_add_filters(vsi, vsi_name, add_list,
2739 						     add_head, num_add);
2740 				memset(add_list, 0, list_size);
2741 				num_add = 0;
2742 			}
2743 		}
2744 		if (num_add) {
2745 			i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2746 					     num_add);
2747 		}
2748 		/* Now move all of the filters from the temp add list back to
2749 		 * the VSI's list.
2750 		 */
2751 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2752 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2753 			/* Only update the state if we're still NEW */
2754 			if (new->f->state == I40E_FILTER_NEW)
2755 				new->f->state = new->state;
2756 			hlist_del(&new->hlist);
2757 			netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2758 			kfree(new);
2759 		}
2760 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2761 		kfree(add_list);
2762 		add_list = NULL;
2763 	}
2764 
2765 	/* Determine the number of active and failed filters. */
2766 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2767 	vsi->active_filters = 0;
2768 	hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2769 		if (f->state == I40E_FILTER_ACTIVE)
2770 			vsi->active_filters++;
2771 		else if (f->state == I40E_FILTER_FAILED)
2772 			failed_filters++;
2773 	}
2774 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2775 
2776 	/* Check if we are able to exit overflow promiscuous mode. We can
2777 	 * safely exit if we didn't just enter, we no longer have any failed
2778 	 * filters, and we have reduced filters below the threshold value.
2779 	 */
2780 	if (old_overflow && !failed_filters &&
2781 	    vsi->active_filters < vsi->promisc_threshold) {
2782 		dev_info(&pf->pdev->dev,
2783 			 "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2784 			 vsi_name);
2785 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2786 		vsi->promisc_threshold = 0;
2787 	}
2788 
2789 	/* if the VF is not trusted do not do promisc */
2790 	if ((vsi->type == I40E_VSI_SRIOV) && !pf->vf[vsi->vf_id].trusted) {
2791 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2792 		goto out;
2793 	}
2794 
2795 	new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2796 
2797 	/* If we are entering overflow promiscuous, we need to calculate a new
2798 	 * threshold for when we are safe to exit
2799 	 */
2800 	if (!old_overflow && new_overflow)
2801 		vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2802 
2803 	/* check for changes in promiscuous modes */
2804 	if (changed_flags & IFF_ALLMULTI) {
2805 		bool cur_multipromisc;
2806 
2807 		cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2808 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2809 							       vsi->seid,
2810 							       cur_multipromisc,
2811 							       NULL);
2812 		if (aq_ret) {
2813 			retval = i40e_aq_rc_to_posix(aq_ret,
2814 						     hw->aq.asq_last_status);
2815 			dev_info(&pf->pdev->dev,
2816 				 "set multi promisc failed on %s, err %s aq_err %s\n",
2817 				 vsi_name,
2818 				 i40e_stat_str(hw, aq_ret),
2819 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2820 		} else {
2821 			dev_info(&pf->pdev->dev, "%s allmulti mode.\n",
2822 				 cur_multipromisc ? "entering" : "leaving");
2823 		}
2824 	}
2825 
2826 	if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2827 		bool cur_promisc;
2828 
2829 		cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2830 			       new_overflow);
2831 		aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2832 		if (aq_ret) {
2833 			retval = i40e_aq_rc_to_posix(aq_ret,
2834 						     hw->aq.asq_last_status);
2835 			dev_info(&pf->pdev->dev,
2836 				 "Setting promiscuous %s failed on %s, err %s aq_err %s\n",
2837 				 cur_promisc ? "on" : "off",
2838 				 vsi_name,
2839 				 i40e_stat_str(hw, aq_ret),
2840 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2841 		}
2842 	}
2843 out:
2844 	/* if something went wrong then set the changed flag so we try again */
2845 	if (retval)
2846 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2847 
2848 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2849 	return retval;
2850 
2851 err_no_memory:
2852 	/* Restore elements on the temporary add and delete lists */
2853 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2854 err_no_memory_locked:
2855 	i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2856 	i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2857 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2858 
2859 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2860 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2861 	return -ENOMEM;
2862 }
2863 
2864 /**
2865  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2866  * @pf: board private structure
2867  **/
2868 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2869 {
2870 	int v;
2871 
2872 	if (!pf)
2873 		return;
2874 	if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2875 		return;
2876 	if (test_bit(__I40E_VF_DISABLE, pf->state)) {
2877 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
2878 		return;
2879 	}
2880 
2881 	for (v = 0; v < pf->num_alloc_vsi; v++) {
2882 		if (pf->vsi[v] &&
2883 		    (pf->vsi[v]->flags & I40E_VSI_FLAG_FILTER_CHANGED) &&
2884 		    !test_bit(__I40E_VSI_RELEASING, pf->vsi[v]->state)) {
2885 			int ret = i40e_sync_vsi_filters(pf->vsi[v]);
2886 
2887 			if (ret) {
2888 				/* come back and try again later */
2889 				set_bit(__I40E_MACVLAN_SYNC_PENDING,
2890 					pf->state);
2891 				break;
2892 			}
2893 		}
2894 	}
2895 }
2896 
2897 /**
2898  * i40e_max_xdp_frame_size - returns the maximum allowed frame size for XDP
2899  * @vsi: the vsi
2900  **/
2901 static int i40e_max_xdp_frame_size(struct i40e_vsi *vsi)
2902 {
2903 	if (PAGE_SIZE >= 8192 || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
2904 		return I40E_RXBUFFER_2048;
2905 	else
2906 		return I40E_RXBUFFER_3072;
2907 }
2908 
2909 /**
2910  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2911  * @netdev: network interface device structure
2912  * @new_mtu: new value for maximum frame size
2913  *
2914  * Returns 0 on success, negative on failure
2915  **/
2916 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2917 {
2918 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2919 	struct i40e_vsi *vsi = np->vsi;
2920 	struct i40e_pf *pf = vsi->back;
2921 
2922 	if (i40e_enabled_xdp_vsi(vsi)) {
2923 		int frame_size = new_mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
2924 
2925 		if (frame_size > i40e_max_xdp_frame_size(vsi))
2926 			return -EINVAL;
2927 	}
2928 
2929 	netdev_dbg(netdev, "changing MTU from %d to %d\n",
2930 		   netdev->mtu, new_mtu);
2931 	netdev->mtu = new_mtu;
2932 	if (netif_running(netdev))
2933 		i40e_vsi_reinit_locked(vsi);
2934 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2935 	set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2936 	return 0;
2937 }
2938 
2939 /**
2940  * i40e_ioctl - Access the hwtstamp interface
2941  * @netdev: network interface device structure
2942  * @ifr: interface request data
2943  * @cmd: ioctl command
2944  **/
2945 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2946 {
2947 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2948 	struct i40e_pf *pf = np->vsi->back;
2949 
2950 	switch (cmd) {
2951 	case SIOCGHWTSTAMP:
2952 		return i40e_ptp_get_ts_config(pf, ifr);
2953 	case SIOCSHWTSTAMP:
2954 		return i40e_ptp_set_ts_config(pf, ifr);
2955 	default:
2956 		return -EOPNOTSUPP;
2957 	}
2958 }
2959 
2960 /**
2961  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2962  * @vsi: the vsi being adjusted
2963  **/
2964 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2965 {
2966 	struct i40e_vsi_context ctxt;
2967 	i40e_status ret;
2968 
2969 	/* Don't modify stripping options if a port VLAN is active */
2970 	if (vsi->info.pvid)
2971 		return;
2972 
2973 	if ((vsi->info.valid_sections &
2974 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2975 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2976 		return;  /* already enabled */
2977 
2978 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2979 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2980 				    I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
2981 
2982 	ctxt.seid = vsi->seid;
2983 	ctxt.info = vsi->info;
2984 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2985 	if (ret) {
2986 		dev_info(&vsi->back->pdev->dev,
2987 			 "update vlan stripping failed, err %s aq_err %s\n",
2988 			 i40e_stat_str(&vsi->back->hw, ret),
2989 			 i40e_aq_str(&vsi->back->hw,
2990 				     vsi->back->hw.aq.asq_last_status));
2991 	}
2992 }
2993 
2994 /**
2995  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
2996  * @vsi: the vsi being adjusted
2997  **/
2998 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
2999 {
3000 	struct i40e_vsi_context ctxt;
3001 	i40e_status ret;
3002 
3003 	/* Don't modify stripping options if a port VLAN is active */
3004 	if (vsi->info.pvid)
3005 		return;
3006 
3007 	if ((vsi->info.valid_sections &
3008 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
3009 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
3010 	     I40E_AQ_VSI_PVLAN_EMOD_MASK))
3011 		return;  /* already disabled */
3012 
3013 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3014 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3015 				    I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
3016 
3017 	ctxt.seid = vsi->seid;
3018 	ctxt.info = vsi->info;
3019 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3020 	if (ret) {
3021 		dev_info(&vsi->back->pdev->dev,
3022 			 "update vlan stripping failed, err %s aq_err %s\n",
3023 			 i40e_stat_str(&vsi->back->hw, ret),
3024 			 i40e_aq_str(&vsi->back->hw,
3025 				     vsi->back->hw.aq.asq_last_status));
3026 	}
3027 }
3028 
3029 /**
3030  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
3031  * @vsi: the vsi being configured
3032  * @vid: vlan id to be added (0 = untagged only , -1 = any)
3033  *
3034  * This is a helper function for adding a new MAC/VLAN filter with the
3035  * specified VLAN for each existing MAC address already in the hash table.
3036  * This function does *not* perform any accounting to update filters based on
3037  * VLAN mode.
3038  *
3039  * NOTE: this function expects to be called while under the
3040  * mac_filter_hash_lock
3041  **/
3042 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3043 {
3044 	struct i40e_mac_filter *f, *add_f;
3045 	struct hlist_node *h;
3046 	int bkt;
3047 
3048 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3049 		/* If we're asked to add a filter that has been marked for
3050 		 * removal, it is safe to simply restore it to active state.
3051 		 * __i40e_del_filter will have simply deleted any filters which
3052 		 * were previously marked NEW or FAILED, so if it is currently
3053 		 * marked REMOVE it must have previously been ACTIVE. Since we
3054 		 * haven't yet run the sync filters task, just restore this
3055 		 * filter to the ACTIVE state so that the sync task leaves it
3056 		 * in place.
3057 		 */
3058 		if (f->state == I40E_FILTER_REMOVE && f->vlan == vid) {
3059 			f->state = I40E_FILTER_ACTIVE;
3060 			continue;
3061 		} else if (f->state == I40E_FILTER_REMOVE) {
3062 			continue;
3063 		}
3064 		add_f = i40e_add_filter(vsi, f->macaddr, vid);
3065 		if (!add_f) {
3066 			dev_info(&vsi->back->pdev->dev,
3067 				 "Could not add vlan filter %d for %pM\n",
3068 				 vid, f->macaddr);
3069 			return -ENOMEM;
3070 		}
3071 	}
3072 
3073 	return 0;
3074 }
3075 
3076 /**
3077  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
3078  * @vsi: the VSI being configured
3079  * @vid: VLAN id to be added
3080  **/
3081 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
3082 {
3083 	int err;
3084 
3085 	if (vsi->info.pvid)
3086 		return -EINVAL;
3087 
3088 	/* The network stack will attempt to add VID=0, with the intention to
3089 	 * receive priority tagged packets with a VLAN of 0. Our HW receives
3090 	 * these packets by default when configured to receive untagged
3091 	 * packets, so we don't need to add a filter for this case.
3092 	 * Additionally, HW interprets adding a VID=0 filter as meaning to
3093 	 * receive *only* tagged traffic and stops receiving untagged traffic.
3094 	 * Thus, we do not want to actually add a filter for VID=0
3095 	 */
3096 	if (!vid)
3097 		return 0;
3098 
3099 	/* Locked once because all functions invoked below iterates list*/
3100 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3101 	err = i40e_add_vlan_all_mac(vsi, vid);
3102 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3103 	if (err)
3104 		return err;
3105 
3106 	/* schedule our worker thread which will take care of
3107 	 * applying the new filter changes
3108 	 */
3109 	i40e_service_event_schedule(vsi->back);
3110 	return 0;
3111 }
3112 
3113 /**
3114  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
3115  * @vsi: the vsi being configured
3116  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
3117  *
3118  * This function should be used to remove all VLAN filters which match the
3119  * given VID. It does not schedule the service event and does not take the
3120  * mac_filter_hash_lock so it may be combined with other operations under
3121  * a single invocation of the mac_filter_hash_lock.
3122  *
3123  * NOTE: this function expects to be called while under the
3124  * mac_filter_hash_lock
3125  */
3126 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3127 {
3128 	struct i40e_mac_filter *f;
3129 	struct hlist_node *h;
3130 	int bkt;
3131 
3132 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3133 		if (f->vlan == vid)
3134 			__i40e_del_filter(vsi, f);
3135 	}
3136 }
3137 
3138 /**
3139  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
3140  * @vsi: the VSI being configured
3141  * @vid: VLAN id to be removed
3142  **/
3143 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
3144 {
3145 	if (!vid || vsi->info.pvid)
3146 		return;
3147 
3148 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3149 	i40e_rm_vlan_all_mac(vsi, vid);
3150 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3151 
3152 	/* schedule our worker thread which will take care of
3153 	 * applying the new filter changes
3154 	 */
3155 	i40e_service_event_schedule(vsi->back);
3156 }
3157 
3158 /**
3159  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
3160  * @netdev: network interface to be adjusted
3161  * @proto: unused protocol value
3162  * @vid: vlan id to be added
3163  *
3164  * net_device_ops implementation for adding vlan ids
3165  **/
3166 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
3167 				__always_unused __be16 proto, u16 vid)
3168 {
3169 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3170 	struct i40e_vsi *vsi = np->vsi;
3171 	int ret = 0;
3172 
3173 	if (vid >= VLAN_N_VID)
3174 		return -EINVAL;
3175 
3176 	ret = i40e_vsi_add_vlan(vsi, vid);
3177 	if (!ret)
3178 		set_bit(vid, vsi->active_vlans);
3179 
3180 	return ret;
3181 }
3182 
3183 /**
3184  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
3185  * @netdev: network interface to be adjusted
3186  * @proto: unused protocol value
3187  * @vid: vlan id to be added
3188  **/
3189 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
3190 				    __always_unused __be16 proto, u16 vid)
3191 {
3192 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3193 	struct i40e_vsi *vsi = np->vsi;
3194 
3195 	if (vid >= VLAN_N_VID)
3196 		return;
3197 	set_bit(vid, vsi->active_vlans);
3198 }
3199 
3200 /**
3201  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
3202  * @netdev: network interface to be adjusted
3203  * @proto: unused protocol value
3204  * @vid: vlan id to be removed
3205  *
3206  * net_device_ops implementation for removing vlan ids
3207  **/
3208 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
3209 				 __always_unused __be16 proto, u16 vid)
3210 {
3211 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3212 	struct i40e_vsi *vsi = np->vsi;
3213 
3214 	/* return code is ignored as there is nothing a user
3215 	 * can do about failure to remove and a log message was
3216 	 * already printed from the other function
3217 	 */
3218 	i40e_vsi_kill_vlan(vsi, vid);
3219 
3220 	clear_bit(vid, vsi->active_vlans);
3221 
3222 	return 0;
3223 }
3224 
3225 /**
3226  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
3227  * @vsi: the vsi being brought back up
3228  **/
3229 static void i40e_restore_vlan(struct i40e_vsi *vsi)
3230 {
3231 	u16 vid;
3232 
3233 	if (!vsi->netdev)
3234 		return;
3235 
3236 	if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
3237 		i40e_vlan_stripping_enable(vsi);
3238 	else
3239 		i40e_vlan_stripping_disable(vsi);
3240 
3241 	for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
3242 		i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
3243 					vid);
3244 }
3245 
3246 /**
3247  * i40e_vsi_add_pvid - Add pvid for the VSI
3248  * @vsi: the vsi being adjusted
3249  * @vid: the vlan id to set as a PVID
3250  **/
3251 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
3252 {
3253 	struct i40e_vsi_context ctxt;
3254 	i40e_status ret;
3255 
3256 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3257 	vsi->info.pvid = cpu_to_le16(vid);
3258 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
3259 				    I40E_AQ_VSI_PVLAN_INSERT_PVID |
3260 				    I40E_AQ_VSI_PVLAN_EMOD_STR;
3261 
3262 	ctxt.seid = vsi->seid;
3263 	ctxt.info = vsi->info;
3264 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3265 	if (ret) {
3266 		dev_info(&vsi->back->pdev->dev,
3267 			 "add pvid failed, err %s aq_err %s\n",
3268 			 i40e_stat_str(&vsi->back->hw, ret),
3269 			 i40e_aq_str(&vsi->back->hw,
3270 				     vsi->back->hw.aq.asq_last_status));
3271 		return -ENOENT;
3272 	}
3273 
3274 	return 0;
3275 }
3276 
3277 /**
3278  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
3279  * @vsi: the vsi being adjusted
3280  *
3281  * Just use the vlan_rx_register() service to put it back to normal
3282  **/
3283 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
3284 {
3285 	vsi->info.pvid = 0;
3286 
3287 	i40e_vlan_stripping_disable(vsi);
3288 }
3289 
3290 /**
3291  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
3292  * @vsi: ptr to the VSI
3293  *
3294  * If this function returns with an error, then it's possible one or
3295  * more of the rings is populated (while the rest are not).  It is the
3296  * callers duty to clean those orphaned rings.
3297  *
3298  * Return 0 on success, negative on failure
3299  **/
3300 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3301 {
3302 	int i, err = 0;
3303 
3304 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3305 		err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3306 
3307 	if (!i40e_enabled_xdp_vsi(vsi))
3308 		return err;
3309 
3310 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3311 		err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3312 
3313 	return err;
3314 }
3315 
3316 /**
3317  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3318  * @vsi: ptr to the VSI
3319  *
3320  * Free VSI's transmit software resources
3321  **/
3322 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3323 {
3324 	int i;
3325 
3326 	if (vsi->tx_rings) {
3327 		for (i = 0; i < vsi->num_queue_pairs; i++)
3328 			if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3329 				i40e_free_tx_resources(vsi->tx_rings[i]);
3330 	}
3331 
3332 	if (vsi->xdp_rings) {
3333 		for (i = 0; i < vsi->num_queue_pairs; i++)
3334 			if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3335 				i40e_free_tx_resources(vsi->xdp_rings[i]);
3336 	}
3337 }
3338 
3339 /**
3340  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3341  * @vsi: ptr to the VSI
3342  *
3343  * If this function returns with an error, then it's possible one or
3344  * more of the rings is populated (while the rest are not).  It is the
3345  * callers duty to clean those orphaned rings.
3346  *
3347  * Return 0 on success, negative on failure
3348  **/
3349 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3350 {
3351 	int i, err = 0;
3352 
3353 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3354 		err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3355 	return err;
3356 }
3357 
3358 /**
3359  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3360  * @vsi: ptr to the VSI
3361  *
3362  * Free all receive software resources
3363  **/
3364 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3365 {
3366 	int i;
3367 
3368 	if (!vsi->rx_rings)
3369 		return;
3370 
3371 	for (i = 0; i < vsi->num_queue_pairs; i++)
3372 		if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3373 			i40e_free_rx_resources(vsi->rx_rings[i]);
3374 }
3375 
3376 /**
3377  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3378  * @ring: The Tx ring to configure
3379  *
3380  * This enables/disables XPS for a given Tx descriptor ring
3381  * based on the TCs enabled for the VSI that ring belongs to.
3382  **/
3383 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3384 {
3385 	int cpu;
3386 
3387 	if (!ring->q_vector || !ring->netdev || ring->ch)
3388 		return;
3389 
3390 	/* We only initialize XPS once, so as not to overwrite user settings */
3391 	if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3392 		return;
3393 
3394 	cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3395 	netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3396 			    ring->queue_index);
3397 }
3398 
3399 /**
3400  * i40e_xsk_pool - Retrieve the AF_XDP buffer pool if XDP and ZC is enabled
3401  * @ring: The Tx or Rx ring
3402  *
3403  * Returns the AF_XDP buffer pool or NULL.
3404  **/
3405 static struct xsk_buff_pool *i40e_xsk_pool(struct i40e_ring *ring)
3406 {
3407 	bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3408 	int qid = ring->queue_index;
3409 
3410 	if (ring_is_xdp(ring))
3411 		qid -= ring->vsi->alloc_queue_pairs;
3412 
3413 	if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3414 		return NULL;
3415 
3416 	return xsk_get_pool_from_qid(ring->vsi->netdev, qid);
3417 }
3418 
3419 /**
3420  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3421  * @ring: The Tx ring to configure
3422  *
3423  * Configure the Tx descriptor ring in the HMC context.
3424  **/
3425 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3426 {
3427 	struct i40e_vsi *vsi = ring->vsi;
3428 	u16 pf_q = vsi->base_queue + ring->queue_index;
3429 	struct i40e_hw *hw = &vsi->back->hw;
3430 	struct i40e_hmc_obj_txq tx_ctx;
3431 	i40e_status err = 0;
3432 	u32 qtx_ctl = 0;
3433 
3434 	if (ring_is_xdp(ring))
3435 		ring->xsk_pool = i40e_xsk_pool(ring);
3436 
3437 	/* some ATR related tx ring init */
3438 	if (vsi->back->flags & I40E_FLAG_FD_ATR_ENABLED) {
3439 		ring->atr_sample_rate = vsi->back->atr_sample_rate;
3440 		ring->atr_count = 0;
3441 	} else {
3442 		ring->atr_sample_rate = 0;
3443 	}
3444 
3445 	/* configure XPS */
3446 	i40e_config_xps_tx_ring(ring);
3447 
3448 	/* clear the context structure first */
3449 	memset(&tx_ctx, 0, sizeof(tx_ctx));
3450 
3451 	tx_ctx.new_context = 1;
3452 	tx_ctx.base = (ring->dma / 128);
3453 	tx_ctx.qlen = ring->count;
3454 	tx_ctx.fd_ena = !!(vsi->back->flags & (I40E_FLAG_FD_SB_ENABLED |
3455 					       I40E_FLAG_FD_ATR_ENABLED));
3456 	tx_ctx.timesync_ena = !!(vsi->back->flags & I40E_FLAG_PTP);
3457 	/* FDIR VSI tx ring can still use RS bit and writebacks */
3458 	if (vsi->type != I40E_VSI_FDIR)
3459 		tx_ctx.head_wb_ena = 1;
3460 	tx_ctx.head_wb_addr = ring->dma +
3461 			      (ring->count * sizeof(struct i40e_tx_desc));
3462 
3463 	/* As part of VSI creation/update, FW allocates certain
3464 	 * Tx arbitration queue sets for each TC enabled for
3465 	 * the VSI. The FW returns the handles to these queue
3466 	 * sets as part of the response buffer to Add VSI,
3467 	 * Update VSI, etc. AQ commands. It is expected that
3468 	 * these queue set handles be associated with the Tx
3469 	 * queues by the driver as part of the TX queue context
3470 	 * initialization. This has to be done regardless of
3471 	 * DCB as by default everything is mapped to TC0.
3472 	 */
3473 
3474 	if (ring->ch)
3475 		tx_ctx.rdylist =
3476 			le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3477 
3478 	else
3479 		tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3480 
3481 	tx_ctx.rdylist_act = 0;
3482 
3483 	/* clear the context in the HMC */
3484 	err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3485 	if (err) {
3486 		dev_info(&vsi->back->pdev->dev,
3487 			 "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3488 			 ring->queue_index, pf_q, err);
3489 		return -ENOMEM;
3490 	}
3491 
3492 	/* set the context in the HMC */
3493 	err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3494 	if (err) {
3495 		dev_info(&vsi->back->pdev->dev,
3496 			 "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3497 			 ring->queue_index, pf_q, err);
3498 		return -ENOMEM;
3499 	}
3500 
3501 	/* Now associate this queue with this PCI function */
3502 	if (ring->ch) {
3503 		if (ring->ch->type == I40E_VSI_VMDQ2)
3504 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3505 		else
3506 			return -EINVAL;
3507 
3508 		qtx_ctl |= (ring->ch->vsi_number <<
3509 			    I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3510 			    I40E_QTX_CTL_VFVM_INDX_MASK;
3511 	} else {
3512 		if (vsi->type == I40E_VSI_VMDQ2) {
3513 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3514 			qtx_ctl |= ((vsi->id) << I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3515 				    I40E_QTX_CTL_VFVM_INDX_MASK;
3516 		} else {
3517 			qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3518 		}
3519 	}
3520 
3521 	qtx_ctl |= ((hw->pf_id << I40E_QTX_CTL_PF_INDX_SHIFT) &
3522 		    I40E_QTX_CTL_PF_INDX_MASK);
3523 	wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3524 	i40e_flush(hw);
3525 
3526 	/* cache tail off for easier writes later */
3527 	ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3528 
3529 	return 0;
3530 }
3531 
3532 /**
3533  * i40e_rx_offset - Return expected offset into page to access data
3534  * @rx_ring: Ring we are requesting offset of
3535  *
3536  * Returns the offset value for ring into the data buffer.
3537  */
3538 static unsigned int i40e_rx_offset(struct i40e_ring *rx_ring)
3539 {
3540 	return ring_uses_build_skb(rx_ring) ? I40E_SKB_PAD : 0;
3541 }
3542 
3543 /**
3544  * i40e_configure_rx_ring - Configure a receive ring context
3545  * @ring: The Rx ring to configure
3546  *
3547  * Configure the Rx descriptor ring in the HMC context.
3548  **/
3549 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3550 {
3551 	struct i40e_vsi *vsi = ring->vsi;
3552 	u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3553 	u16 pf_q = vsi->base_queue + ring->queue_index;
3554 	struct i40e_hw *hw = &vsi->back->hw;
3555 	struct i40e_hmc_obj_rxq rx_ctx;
3556 	i40e_status err = 0;
3557 	bool ok;
3558 	int ret;
3559 
3560 	bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3561 
3562 	/* clear the context structure first */
3563 	memset(&rx_ctx, 0, sizeof(rx_ctx));
3564 
3565 	if (ring->vsi->type == I40E_VSI_MAIN)
3566 		xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq);
3567 
3568 	kfree(ring->rx_bi);
3569 	ring->xsk_pool = i40e_xsk_pool(ring);
3570 	if (ring->xsk_pool) {
3571 		ret = i40e_alloc_rx_bi_zc(ring);
3572 		if (ret)
3573 			return ret;
3574 		ring->rx_buf_len =
3575 		  xsk_pool_get_rx_frame_size(ring->xsk_pool);
3576 		/* For AF_XDP ZC, we disallow packets to span on
3577 		 * multiple buffers, thus letting us skip that
3578 		 * handling in the fast-path.
3579 		 */
3580 		chain_len = 1;
3581 		ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3582 						 MEM_TYPE_XSK_BUFF_POOL,
3583 						 NULL);
3584 		if (ret)
3585 			return ret;
3586 		dev_info(&vsi->back->pdev->dev,
3587 			 "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n",
3588 			 ring->queue_index);
3589 
3590 	} else {
3591 		ret = i40e_alloc_rx_bi(ring);
3592 		if (ret)
3593 			return ret;
3594 		ring->rx_buf_len = vsi->rx_buf_len;
3595 		if (ring->vsi->type == I40E_VSI_MAIN) {
3596 			ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3597 							 MEM_TYPE_PAGE_SHARED,
3598 							 NULL);
3599 			if (ret)
3600 				return ret;
3601 		}
3602 	}
3603 
3604 	rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3605 				    BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3606 
3607 	rx_ctx.base = (ring->dma / 128);
3608 	rx_ctx.qlen = ring->count;
3609 
3610 	/* use 16 byte descriptors */
3611 	rx_ctx.dsize = 0;
3612 
3613 	/* descriptor type is always zero
3614 	 * rx_ctx.dtype = 0;
3615 	 */
3616 	rx_ctx.hsplit_0 = 0;
3617 
3618 	rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3619 	if (hw->revision_id == 0)
3620 		rx_ctx.lrxqthresh = 0;
3621 	else
3622 		rx_ctx.lrxqthresh = 1;
3623 	rx_ctx.crcstrip = 1;
3624 	rx_ctx.l2tsel = 1;
3625 	/* this controls whether VLAN is stripped from inner headers */
3626 	rx_ctx.showiv = 0;
3627 	/* set the prefena field to 1 because the manual says to */
3628 	rx_ctx.prefena = 1;
3629 
3630 	/* clear the context in the HMC */
3631 	err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3632 	if (err) {
3633 		dev_info(&vsi->back->pdev->dev,
3634 			 "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3635 			 ring->queue_index, pf_q, err);
3636 		return -ENOMEM;
3637 	}
3638 
3639 	/* set the context in the HMC */
3640 	err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3641 	if (err) {
3642 		dev_info(&vsi->back->pdev->dev,
3643 			 "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3644 			 ring->queue_index, pf_q, err);
3645 		return -ENOMEM;
3646 	}
3647 
3648 	/* configure Rx buffer alignment */
3649 	if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
3650 		clear_ring_build_skb_enabled(ring);
3651 	else
3652 		set_ring_build_skb_enabled(ring);
3653 
3654 	ring->rx_offset = i40e_rx_offset(ring);
3655 
3656 	/* cache tail for quicker writes, and clear the reg before use */
3657 	ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3658 	writel(0, ring->tail);
3659 
3660 	if (ring->xsk_pool) {
3661 		xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
3662 		ok = i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring));
3663 	} else {
3664 		ok = !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3665 	}
3666 	if (!ok) {
3667 		/* Log this in case the user has forgotten to give the kernel
3668 		 * any buffers, even later in the application.
3669 		 */
3670 		dev_info(&vsi->back->pdev->dev,
3671 			 "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3672 			 ring->xsk_pool ? "AF_XDP ZC enabled " : "",
3673 			 ring->queue_index, pf_q);
3674 	}
3675 
3676 	return 0;
3677 }
3678 
3679 /**
3680  * i40e_vsi_configure_tx - Configure the VSI for Tx
3681  * @vsi: VSI structure describing this set of rings and resources
3682  *
3683  * Configure the Tx VSI for operation.
3684  **/
3685 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3686 {
3687 	int err = 0;
3688 	u16 i;
3689 
3690 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3691 		err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3692 
3693 	if (err || !i40e_enabled_xdp_vsi(vsi))
3694 		return err;
3695 
3696 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3697 		err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3698 
3699 	return err;
3700 }
3701 
3702 /**
3703  * i40e_vsi_configure_rx - Configure the VSI for Rx
3704  * @vsi: the VSI being configured
3705  *
3706  * Configure the Rx VSI for operation.
3707  **/
3708 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3709 {
3710 	int err = 0;
3711 	u16 i;
3712 
3713 	if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX)) {
3714 		vsi->max_frame = I40E_MAX_RXBUFFER;
3715 		vsi->rx_buf_len = I40E_RXBUFFER_2048;
3716 #if (PAGE_SIZE < 8192)
3717 	} else if (!I40E_2K_TOO_SMALL_WITH_PADDING &&
3718 		   (vsi->netdev->mtu <= ETH_DATA_LEN)) {
3719 		vsi->max_frame = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3720 		vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3721 #endif
3722 	} else {
3723 		vsi->max_frame = I40E_MAX_RXBUFFER;
3724 		vsi->rx_buf_len = (PAGE_SIZE < 8192) ? I40E_RXBUFFER_3072 :
3725 						       I40E_RXBUFFER_2048;
3726 	}
3727 
3728 	/* set up individual rings */
3729 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3730 		err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3731 
3732 	return err;
3733 }
3734 
3735 /**
3736  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3737  * @vsi: ptr to the VSI
3738  **/
3739 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3740 {
3741 	struct i40e_ring *tx_ring, *rx_ring;
3742 	u16 qoffset, qcount;
3743 	int i, n;
3744 
3745 	if (!(vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
3746 		/* Reset the TC information */
3747 		for (i = 0; i < vsi->num_queue_pairs; i++) {
3748 			rx_ring = vsi->rx_rings[i];
3749 			tx_ring = vsi->tx_rings[i];
3750 			rx_ring->dcb_tc = 0;
3751 			tx_ring->dcb_tc = 0;
3752 		}
3753 		return;
3754 	}
3755 
3756 	for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3757 		if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3758 			continue;
3759 
3760 		qoffset = vsi->tc_config.tc_info[n].qoffset;
3761 		qcount = vsi->tc_config.tc_info[n].qcount;
3762 		for (i = qoffset; i < (qoffset + qcount); i++) {
3763 			rx_ring = vsi->rx_rings[i];
3764 			tx_ring = vsi->tx_rings[i];
3765 			rx_ring->dcb_tc = n;
3766 			tx_ring->dcb_tc = n;
3767 		}
3768 	}
3769 }
3770 
3771 /**
3772  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3773  * @vsi: ptr to the VSI
3774  **/
3775 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3776 {
3777 	if (vsi->netdev)
3778 		i40e_set_rx_mode(vsi->netdev);
3779 }
3780 
3781 /**
3782  * i40e_reset_fdir_filter_cnt - Reset flow director filter counters
3783  * @pf: Pointer to the targeted PF
3784  *
3785  * Set all flow director counters to 0.
3786  */
3787 static void i40e_reset_fdir_filter_cnt(struct i40e_pf *pf)
3788 {
3789 	pf->fd_tcp4_filter_cnt = 0;
3790 	pf->fd_udp4_filter_cnt = 0;
3791 	pf->fd_sctp4_filter_cnt = 0;
3792 	pf->fd_ip4_filter_cnt = 0;
3793 	pf->fd_tcp6_filter_cnt = 0;
3794 	pf->fd_udp6_filter_cnt = 0;
3795 	pf->fd_sctp6_filter_cnt = 0;
3796 	pf->fd_ip6_filter_cnt = 0;
3797 }
3798 
3799 /**
3800  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3801  * @vsi: Pointer to the targeted VSI
3802  *
3803  * This function replays the hlist on the hw where all the SB Flow Director
3804  * filters were saved.
3805  **/
3806 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3807 {
3808 	struct i40e_fdir_filter *filter;
3809 	struct i40e_pf *pf = vsi->back;
3810 	struct hlist_node *node;
3811 
3812 	if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
3813 		return;
3814 
3815 	/* Reset FDir counters as we're replaying all existing filters */
3816 	i40e_reset_fdir_filter_cnt(pf);
3817 
3818 	hlist_for_each_entry_safe(filter, node,
3819 				  &pf->fdir_filter_list, fdir_node) {
3820 		i40e_add_del_fdir(vsi, filter, true);
3821 	}
3822 }
3823 
3824 /**
3825  * i40e_vsi_configure - Set up the VSI for action
3826  * @vsi: the VSI being configured
3827  **/
3828 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3829 {
3830 	int err;
3831 
3832 	i40e_set_vsi_rx_mode(vsi);
3833 	i40e_restore_vlan(vsi);
3834 	i40e_vsi_config_dcb_rings(vsi);
3835 	err = i40e_vsi_configure_tx(vsi);
3836 	if (!err)
3837 		err = i40e_vsi_configure_rx(vsi);
3838 
3839 	return err;
3840 }
3841 
3842 /**
3843  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3844  * @vsi: the VSI being configured
3845  **/
3846 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3847 {
3848 	bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3849 	struct i40e_pf *pf = vsi->back;
3850 	struct i40e_hw *hw = &pf->hw;
3851 	u16 vector;
3852 	int i, q;
3853 	u32 qp;
3854 
3855 	/* The interrupt indexing is offset by 1 in the PFINT_ITRn
3856 	 * and PFINT_LNKLSTn registers, e.g.:
3857 	 *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3858 	 */
3859 	qp = vsi->base_queue;
3860 	vector = vsi->base_vector;
3861 	for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3862 		struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3863 
3864 		q_vector->rx.next_update = jiffies + 1;
3865 		q_vector->rx.target_itr =
3866 			ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3867 		wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3868 		     q_vector->rx.target_itr >> 1);
3869 		q_vector->rx.current_itr = q_vector->rx.target_itr;
3870 
3871 		q_vector->tx.next_update = jiffies + 1;
3872 		q_vector->tx.target_itr =
3873 			ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3874 		wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3875 		     q_vector->tx.target_itr >> 1);
3876 		q_vector->tx.current_itr = q_vector->tx.target_itr;
3877 
3878 		wr32(hw, I40E_PFINT_RATEN(vector - 1),
3879 		     i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3880 
3881 		/* Linked list for the queuepairs assigned to this vector */
3882 		wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3883 		for (q = 0; q < q_vector->num_ringpairs; q++) {
3884 			u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3885 			u32 val;
3886 
3887 			val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3888 			      (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3889 			      (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3890 			      (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3891 			      (I40E_QUEUE_TYPE_TX <<
3892 			       I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3893 
3894 			wr32(hw, I40E_QINT_RQCTL(qp), val);
3895 
3896 			if (has_xdp) {
3897 				val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3898 				      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3899 				      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3900 				      (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3901 				      (I40E_QUEUE_TYPE_TX <<
3902 				       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3903 
3904 				wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3905 			}
3906 
3907 			val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3908 			      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3909 			      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3910 			      ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3911 			      (I40E_QUEUE_TYPE_RX <<
3912 			       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3913 
3914 			/* Terminate the linked list */
3915 			if (q == (q_vector->num_ringpairs - 1))
3916 				val |= (I40E_QUEUE_END_OF_LIST <<
3917 					I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3918 
3919 			wr32(hw, I40E_QINT_TQCTL(qp), val);
3920 			qp++;
3921 		}
3922 	}
3923 
3924 	i40e_flush(hw);
3925 }
3926 
3927 /**
3928  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3929  * @pf: pointer to private device data structure
3930  **/
3931 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3932 {
3933 	struct i40e_hw *hw = &pf->hw;
3934 	u32 val;
3935 
3936 	/* clear things first */
3937 	wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3938 	rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3939 
3940 	val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3941 	      I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3942 	      I40E_PFINT_ICR0_ENA_GRST_MASK          |
3943 	      I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3944 	      I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3945 	      I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3946 	      I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3947 	      I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3948 
3949 	if (pf->flags & I40E_FLAG_IWARP_ENABLED)
3950 		val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3951 
3952 	if (pf->flags & I40E_FLAG_PTP)
3953 		val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3954 
3955 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
3956 
3957 	/* SW_ITR_IDX = 0, but don't change INTENA */
3958 	wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3959 					I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
3960 
3961 	/* OTHER_ITR_IDX = 0 */
3962 	wr32(hw, I40E_PFINT_STAT_CTL0, 0);
3963 }
3964 
3965 /**
3966  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
3967  * @vsi: the VSI being configured
3968  **/
3969 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
3970 {
3971 	u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
3972 	struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3973 	struct i40e_pf *pf = vsi->back;
3974 	struct i40e_hw *hw = &pf->hw;
3975 	u32 val;
3976 
3977 	/* set the ITR configuration */
3978 	q_vector->rx.next_update = jiffies + 1;
3979 	q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
3980 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr >> 1);
3981 	q_vector->rx.current_itr = q_vector->rx.target_itr;
3982 	q_vector->tx.next_update = jiffies + 1;
3983 	q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
3984 	wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr >> 1);
3985 	q_vector->tx.current_itr = q_vector->tx.target_itr;
3986 
3987 	i40e_enable_misc_int_causes(pf);
3988 
3989 	/* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
3990 	wr32(hw, I40E_PFINT_LNKLST0, 0);
3991 
3992 	/* Associate the queue pair to the vector and enable the queue int */
3993 	val = I40E_QINT_RQCTL_CAUSE_ENA_MASK		       |
3994 	      (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT)  |
3995 	      (nextqp	   << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT)|
3996 	      (I40E_QUEUE_TYPE_TX << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3997 
3998 	wr32(hw, I40E_QINT_RQCTL(0), val);
3999 
4000 	if (i40e_enabled_xdp_vsi(vsi)) {
4001 		val = I40E_QINT_TQCTL_CAUSE_ENA_MASK		     |
4002 		      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT)|
4003 		      (I40E_QUEUE_TYPE_TX
4004 		       << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
4005 
4006 		wr32(hw, I40E_QINT_TQCTL(nextqp), val);
4007 	}
4008 
4009 	val = I40E_QINT_TQCTL_CAUSE_ENA_MASK		      |
4010 	      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
4011 	      (I40E_QUEUE_END_OF_LIST << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
4012 
4013 	wr32(hw, I40E_QINT_TQCTL(0), val);
4014 	i40e_flush(hw);
4015 }
4016 
4017 /**
4018  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
4019  * @pf: board private structure
4020  **/
4021 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
4022 {
4023 	struct i40e_hw *hw = &pf->hw;
4024 
4025 	wr32(hw, I40E_PFINT_DYN_CTL0,
4026 	     I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
4027 	i40e_flush(hw);
4028 }
4029 
4030 /**
4031  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
4032  * @pf: board private structure
4033  **/
4034 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
4035 {
4036 	struct i40e_hw *hw = &pf->hw;
4037 	u32 val;
4038 
4039 	val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
4040 	      I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
4041 	      (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
4042 
4043 	wr32(hw, I40E_PFINT_DYN_CTL0, val);
4044 	i40e_flush(hw);
4045 }
4046 
4047 /**
4048  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
4049  * @irq: interrupt number
4050  * @data: pointer to a q_vector
4051  **/
4052 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
4053 {
4054 	struct i40e_q_vector *q_vector = data;
4055 
4056 	if (!q_vector->tx.ring && !q_vector->rx.ring)
4057 		return IRQ_HANDLED;
4058 
4059 	napi_schedule_irqoff(&q_vector->napi);
4060 
4061 	return IRQ_HANDLED;
4062 }
4063 
4064 /**
4065  * i40e_irq_affinity_notify - Callback for affinity changes
4066  * @notify: context as to what irq was changed
4067  * @mask: the new affinity mask
4068  *
4069  * This is a callback function used by the irq_set_affinity_notifier function
4070  * so that we may register to receive changes to the irq affinity masks.
4071  **/
4072 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
4073 				     const cpumask_t *mask)
4074 {
4075 	struct i40e_q_vector *q_vector =
4076 		container_of(notify, struct i40e_q_vector, affinity_notify);
4077 
4078 	cpumask_copy(&q_vector->affinity_mask, mask);
4079 }
4080 
4081 /**
4082  * i40e_irq_affinity_release - Callback for affinity notifier release
4083  * @ref: internal core kernel usage
4084  *
4085  * This is a callback function used by the irq_set_affinity_notifier function
4086  * to inform the current notification subscriber that they will no longer
4087  * receive notifications.
4088  **/
4089 static void i40e_irq_affinity_release(struct kref *ref) {}
4090 
4091 /**
4092  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
4093  * @vsi: the VSI being configured
4094  * @basename: name for the vector
4095  *
4096  * Allocates MSI-X vectors and requests interrupts from the kernel.
4097  **/
4098 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
4099 {
4100 	int q_vectors = vsi->num_q_vectors;
4101 	struct i40e_pf *pf = vsi->back;
4102 	int base = vsi->base_vector;
4103 	int rx_int_idx = 0;
4104 	int tx_int_idx = 0;
4105 	int vector, err;
4106 	int irq_num;
4107 	int cpu;
4108 
4109 	for (vector = 0; vector < q_vectors; vector++) {
4110 		struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
4111 
4112 		irq_num = pf->msix_entries[base + vector].vector;
4113 
4114 		if (q_vector->tx.ring && q_vector->rx.ring) {
4115 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4116 				 "%s-%s-%d", basename, "TxRx", rx_int_idx++);
4117 			tx_int_idx++;
4118 		} else if (q_vector->rx.ring) {
4119 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4120 				 "%s-%s-%d", basename, "rx", rx_int_idx++);
4121 		} else if (q_vector->tx.ring) {
4122 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4123 				 "%s-%s-%d", basename, "tx", tx_int_idx++);
4124 		} else {
4125 			/* skip this unused q_vector */
4126 			continue;
4127 		}
4128 		err = request_irq(irq_num,
4129 				  vsi->irq_handler,
4130 				  0,
4131 				  q_vector->name,
4132 				  q_vector);
4133 		if (err) {
4134 			dev_info(&pf->pdev->dev,
4135 				 "MSIX request_irq failed, error: %d\n", err);
4136 			goto free_queue_irqs;
4137 		}
4138 
4139 		/* register for affinity change notifications */
4140 		q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
4141 		q_vector->affinity_notify.release = i40e_irq_affinity_release;
4142 		irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
4143 		/* Spread affinity hints out across online CPUs.
4144 		 *
4145 		 * get_cpu_mask returns a static constant mask with
4146 		 * a permanent lifetime so it's ok to pass to
4147 		 * irq_update_affinity_hint without making a copy.
4148 		 */
4149 		cpu = cpumask_local_spread(q_vector->v_idx, -1);
4150 		irq_update_affinity_hint(irq_num, get_cpu_mask(cpu));
4151 	}
4152 
4153 	vsi->irqs_ready = true;
4154 	return 0;
4155 
4156 free_queue_irqs:
4157 	while (vector) {
4158 		vector--;
4159 		irq_num = pf->msix_entries[base + vector].vector;
4160 		irq_set_affinity_notifier(irq_num, NULL);
4161 		irq_update_affinity_hint(irq_num, NULL);
4162 		free_irq(irq_num, &vsi->q_vectors[vector]);
4163 	}
4164 	return err;
4165 }
4166 
4167 /**
4168  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
4169  * @vsi: the VSI being un-configured
4170  **/
4171 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
4172 {
4173 	struct i40e_pf *pf = vsi->back;
4174 	struct i40e_hw *hw = &pf->hw;
4175 	int base = vsi->base_vector;
4176 	int i;
4177 
4178 	/* disable interrupt causation from each queue */
4179 	for (i = 0; i < vsi->num_queue_pairs; i++) {
4180 		u32 val;
4181 
4182 		val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
4183 		val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
4184 		wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
4185 
4186 		val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
4187 		val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
4188 		wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
4189 
4190 		if (!i40e_enabled_xdp_vsi(vsi))
4191 			continue;
4192 		wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
4193 	}
4194 
4195 	/* disable each interrupt */
4196 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4197 		for (i = vsi->base_vector;
4198 		     i < (vsi->num_q_vectors + vsi->base_vector); i++)
4199 			wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
4200 
4201 		i40e_flush(hw);
4202 		for (i = 0; i < vsi->num_q_vectors; i++)
4203 			synchronize_irq(pf->msix_entries[i + base].vector);
4204 	} else {
4205 		/* Legacy and MSI mode - this stops all interrupt handling */
4206 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
4207 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
4208 		i40e_flush(hw);
4209 		synchronize_irq(pf->pdev->irq);
4210 	}
4211 }
4212 
4213 /**
4214  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
4215  * @vsi: the VSI being configured
4216  **/
4217 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
4218 {
4219 	struct i40e_pf *pf = vsi->back;
4220 	int i;
4221 
4222 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4223 		for (i = 0; i < vsi->num_q_vectors; i++)
4224 			i40e_irq_dynamic_enable(vsi, i);
4225 	} else {
4226 		i40e_irq_dynamic_enable_icr0(pf);
4227 	}
4228 
4229 	i40e_flush(&pf->hw);
4230 	return 0;
4231 }
4232 
4233 /**
4234  * i40e_free_misc_vector - Free the vector that handles non-queue events
4235  * @pf: board private structure
4236  **/
4237 static void i40e_free_misc_vector(struct i40e_pf *pf)
4238 {
4239 	/* Disable ICR 0 */
4240 	wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
4241 	i40e_flush(&pf->hw);
4242 
4243 	if (pf->flags & I40E_FLAG_MSIX_ENABLED && pf->msix_entries) {
4244 		free_irq(pf->msix_entries[0].vector, pf);
4245 		clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
4246 	}
4247 }
4248 
4249 /**
4250  * i40e_intr - MSI/Legacy and non-queue interrupt handler
4251  * @irq: interrupt number
4252  * @data: pointer to a q_vector
4253  *
4254  * This is the handler used for all MSI/Legacy interrupts, and deals
4255  * with both queue and non-queue interrupts.  This is also used in
4256  * MSIX mode to handle the non-queue interrupts.
4257  **/
4258 static irqreturn_t i40e_intr(int irq, void *data)
4259 {
4260 	struct i40e_pf *pf = (struct i40e_pf *)data;
4261 	struct i40e_hw *hw = &pf->hw;
4262 	irqreturn_t ret = IRQ_NONE;
4263 	u32 icr0, icr0_remaining;
4264 	u32 val, ena_mask;
4265 
4266 	icr0 = rd32(hw, I40E_PFINT_ICR0);
4267 	ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
4268 
4269 	/* if sharing a legacy IRQ, we might get called w/o an intr pending */
4270 	if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
4271 		goto enable_intr;
4272 
4273 	/* if interrupt but no bits showing, must be SWINT */
4274 	if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
4275 	    (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
4276 		pf->sw_int_count++;
4277 
4278 	if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
4279 	    (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
4280 		ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4281 		dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
4282 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
4283 	}
4284 
4285 	/* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
4286 	if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
4287 		struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
4288 		struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4289 
4290 		/* We do not have a way to disarm Queue causes while leaving
4291 		 * interrupt enabled for all other causes, ideally
4292 		 * interrupt should be disabled while we are in NAPI but
4293 		 * this is not a performance path and napi_schedule()
4294 		 * can deal with rescheduling.
4295 		 */
4296 		if (!test_bit(__I40E_DOWN, pf->state))
4297 			napi_schedule_irqoff(&q_vector->napi);
4298 	}
4299 
4300 	if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
4301 		ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
4302 		set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
4303 		i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
4304 	}
4305 
4306 	if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
4307 		ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
4308 		set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
4309 	}
4310 
4311 	if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
4312 		/* disable any further VFLR event notifications */
4313 		if (test_bit(__I40E_VF_RESETS_DISABLED, pf->state)) {
4314 			u32 reg = rd32(hw, I40E_PFINT_ICR0_ENA);
4315 
4316 			reg &= ~I40E_PFINT_ICR0_VFLR_MASK;
4317 			wr32(hw, I40E_PFINT_ICR0_ENA, reg);
4318 		} else {
4319 			ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
4320 			set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
4321 		}
4322 	}
4323 
4324 	if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
4325 		if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4326 			set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
4327 		ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
4328 		val = rd32(hw, I40E_GLGEN_RSTAT);
4329 		val = (val & I40E_GLGEN_RSTAT_RESET_TYPE_MASK)
4330 		       >> I40E_GLGEN_RSTAT_RESET_TYPE_SHIFT;
4331 		if (val == I40E_RESET_CORER) {
4332 			pf->corer_count++;
4333 		} else if (val == I40E_RESET_GLOBR) {
4334 			pf->globr_count++;
4335 		} else if (val == I40E_RESET_EMPR) {
4336 			pf->empr_count++;
4337 			set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
4338 		}
4339 	}
4340 
4341 	if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
4342 		icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
4343 		dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4344 		dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4345 			 rd32(hw, I40E_PFHMC_ERRORINFO),
4346 			 rd32(hw, I40E_PFHMC_ERRORDATA));
4347 	}
4348 
4349 	if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4350 		u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4351 
4352 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_EVENT0_MASK)
4353 			schedule_work(&pf->ptp_extts0_work);
4354 
4355 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK)
4356 			i40e_ptp_tx_hwtstamp(pf);
4357 
4358 		icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4359 	}
4360 
4361 	/* If a critical error is pending we have no choice but to reset the
4362 	 * device.
4363 	 * Report and mask out any remaining unexpected interrupts.
4364 	 */
4365 	icr0_remaining = icr0 & ena_mask;
4366 	if (icr0_remaining) {
4367 		dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4368 			 icr0_remaining);
4369 		if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4370 		    (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4371 		    (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4372 			dev_info(&pf->pdev->dev, "device will be reset\n");
4373 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4374 			i40e_service_event_schedule(pf);
4375 		}
4376 		ena_mask &= ~icr0_remaining;
4377 	}
4378 	ret = IRQ_HANDLED;
4379 
4380 enable_intr:
4381 	/* re-enable interrupt causes */
4382 	wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4383 	if (!test_bit(__I40E_DOWN, pf->state) ||
4384 	    test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4385 		i40e_service_event_schedule(pf);
4386 		i40e_irq_dynamic_enable_icr0(pf);
4387 	}
4388 
4389 	return ret;
4390 }
4391 
4392 /**
4393  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4394  * @tx_ring:  tx ring to clean
4395  * @budget:   how many cleans we're allowed
4396  *
4397  * Returns true if there's any budget left (e.g. the clean is finished)
4398  **/
4399 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4400 {
4401 	struct i40e_vsi *vsi = tx_ring->vsi;
4402 	u16 i = tx_ring->next_to_clean;
4403 	struct i40e_tx_buffer *tx_buf;
4404 	struct i40e_tx_desc *tx_desc;
4405 
4406 	tx_buf = &tx_ring->tx_bi[i];
4407 	tx_desc = I40E_TX_DESC(tx_ring, i);
4408 	i -= tx_ring->count;
4409 
4410 	do {
4411 		struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4412 
4413 		/* if next_to_watch is not set then there is no work pending */
4414 		if (!eop_desc)
4415 			break;
4416 
4417 		/* prevent any other reads prior to eop_desc */
4418 		smp_rmb();
4419 
4420 		/* if the descriptor isn't done, no work yet to do */
4421 		if (!(eop_desc->cmd_type_offset_bsz &
4422 		      cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4423 			break;
4424 
4425 		/* clear next_to_watch to prevent false hangs */
4426 		tx_buf->next_to_watch = NULL;
4427 
4428 		tx_desc->buffer_addr = 0;
4429 		tx_desc->cmd_type_offset_bsz = 0;
4430 		/* move past filter desc */
4431 		tx_buf++;
4432 		tx_desc++;
4433 		i++;
4434 		if (unlikely(!i)) {
4435 			i -= tx_ring->count;
4436 			tx_buf = tx_ring->tx_bi;
4437 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4438 		}
4439 		/* unmap skb header data */
4440 		dma_unmap_single(tx_ring->dev,
4441 				 dma_unmap_addr(tx_buf, dma),
4442 				 dma_unmap_len(tx_buf, len),
4443 				 DMA_TO_DEVICE);
4444 		if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4445 			kfree(tx_buf->raw_buf);
4446 
4447 		tx_buf->raw_buf = NULL;
4448 		tx_buf->tx_flags = 0;
4449 		tx_buf->next_to_watch = NULL;
4450 		dma_unmap_len_set(tx_buf, len, 0);
4451 		tx_desc->buffer_addr = 0;
4452 		tx_desc->cmd_type_offset_bsz = 0;
4453 
4454 		/* move us past the eop_desc for start of next FD desc */
4455 		tx_buf++;
4456 		tx_desc++;
4457 		i++;
4458 		if (unlikely(!i)) {
4459 			i -= tx_ring->count;
4460 			tx_buf = tx_ring->tx_bi;
4461 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4462 		}
4463 
4464 		/* update budget accounting */
4465 		budget--;
4466 	} while (likely(budget));
4467 
4468 	i += tx_ring->count;
4469 	tx_ring->next_to_clean = i;
4470 
4471 	if (vsi->back->flags & I40E_FLAG_MSIX_ENABLED)
4472 		i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4473 
4474 	return budget > 0;
4475 }
4476 
4477 /**
4478  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4479  * @irq: interrupt number
4480  * @data: pointer to a q_vector
4481  **/
4482 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4483 {
4484 	struct i40e_q_vector *q_vector = data;
4485 	struct i40e_vsi *vsi;
4486 
4487 	if (!q_vector->tx.ring)
4488 		return IRQ_HANDLED;
4489 
4490 	vsi = q_vector->tx.ring->vsi;
4491 	i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4492 
4493 	return IRQ_HANDLED;
4494 }
4495 
4496 /**
4497  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4498  * @vsi: the VSI being configured
4499  * @v_idx: vector index
4500  * @qp_idx: queue pair index
4501  **/
4502 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4503 {
4504 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4505 	struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4506 	struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4507 
4508 	tx_ring->q_vector = q_vector;
4509 	tx_ring->next = q_vector->tx.ring;
4510 	q_vector->tx.ring = tx_ring;
4511 	q_vector->tx.count++;
4512 
4513 	/* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4514 	if (i40e_enabled_xdp_vsi(vsi)) {
4515 		struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4516 
4517 		xdp_ring->q_vector = q_vector;
4518 		xdp_ring->next = q_vector->tx.ring;
4519 		q_vector->tx.ring = xdp_ring;
4520 		q_vector->tx.count++;
4521 	}
4522 
4523 	rx_ring->q_vector = q_vector;
4524 	rx_ring->next = q_vector->rx.ring;
4525 	q_vector->rx.ring = rx_ring;
4526 	q_vector->rx.count++;
4527 }
4528 
4529 /**
4530  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4531  * @vsi: the VSI being configured
4532  *
4533  * This function maps descriptor rings to the queue-specific vectors
4534  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4535  * one vector per queue pair, but on a constrained vector budget, we
4536  * group the queue pairs as "efficiently" as possible.
4537  **/
4538 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4539 {
4540 	int qp_remaining = vsi->num_queue_pairs;
4541 	int q_vectors = vsi->num_q_vectors;
4542 	int num_ringpairs;
4543 	int v_start = 0;
4544 	int qp_idx = 0;
4545 
4546 	/* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4547 	 * group them so there are multiple queues per vector.
4548 	 * It is also important to go through all the vectors available to be
4549 	 * sure that if we don't use all the vectors, that the remaining vectors
4550 	 * are cleared. This is especially important when decreasing the
4551 	 * number of queues in use.
4552 	 */
4553 	for (; v_start < q_vectors; v_start++) {
4554 		struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4555 
4556 		num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4557 
4558 		q_vector->num_ringpairs = num_ringpairs;
4559 		q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4560 
4561 		q_vector->rx.count = 0;
4562 		q_vector->tx.count = 0;
4563 		q_vector->rx.ring = NULL;
4564 		q_vector->tx.ring = NULL;
4565 
4566 		while (num_ringpairs--) {
4567 			i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4568 			qp_idx++;
4569 			qp_remaining--;
4570 		}
4571 	}
4572 }
4573 
4574 /**
4575  * i40e_vsi_request_irq - Request IRQ from the OS
4576  * @vsi: the VSI being configured
4577  * @basename: name for the vector
4578  **/
4579 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4580 {
4581 	struct i40e_pf *pf = vsi->back;
4582 	int err;
4583 
4584 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
4585 		err = i40e_vsi_request_irq_msix(vsi, basename);
4586 	else if (pf->flags & I40E_FLAG_MSI_ENABLED)
4587 		err = request_irq(pf->pdev->irq, i40e_intr, 0,
4588 				  pf->int_name, pf);
4589 	else
4590 		err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4591 				  pf->int_name, pf);
4592 
4593 	if (err)
4594 		dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4595 
4596 	return err;
4597 }
4598 
4599 #ifdef CONFIG_NET_POLL_CONTROLLER
4600 /**
4601  * i40e_netpoll - A Polling 'interrupt' handler
4602  * @netdev: network interface device structure
4603  *
4604  * This is used by netconsole to send skbs without having to re-enable
4605  * interrupts.  It's not called while the normal interrupt routine is executing.
4606  **/
4607 static void i40e_netpoll(struct net_device *netdev)
4608 {
4609 	struct i40e_netdev_priv *np = netdev_priv(netdev);
4610 	struct i40e_vsi *vsi = np->vsi;
4611 	struct i40e_pf *pf = vsi->back;
4612 	int i;
4613 
4614 	/* if interface is down do nothing */
4615 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
4616 		return;
4617 
4618 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4619 		for (i = 0; i < vsi->num_q_vectors; i++)
4620 			i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4621 	} else {
4622 		i40e_intr(pf->pdev->irq, netdev);
4623 	}
4624 }
4625 #endif
4626 
4627 #define I40E_QTX_ENA_WAIT_COUNT 50
4628 
4629 /**
4630  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4631  * @pf: the PF being configured
4632  * @pf_q: the PF queue
4633  * @enable: enable or disable state of the queue
4634  *
4635  * This routine will wait for the given Tx queue of the PF to reach the
4636  * enabled or disabled state.
4637  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4638  * multiple retries; else will return 0 in case of success.
4639  **/
4640 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4641 {
4642 	int i;
4643 	u32 tx_reg;
4644 
4645 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4646 		tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4647 		if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4648 			break;
4649 
4650 		usleep_range(10, 20);
4651 	}
4652 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4653 		return -ETIMEDOUT;
4654 
4655 	return 0;
4656 }
4657 
4658 /**
4659  * i40e_control_tx_q - Start or stop a particular Tx queue
4660  * @pf: the PF structure
4661  * @pf_q: the PF queue to configure
4662  * @enable: start or stop the queue
4663  *
4664  * This function enables or disables a single queue. Note that any delay
4665  * required after the operation is expected to be handled by the caller of
4666  * this function.
4667  **/
4668 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4669 {
4670 	struct i40e_hw *hw = &pf->hw;
4671 	u32 tx_reg;
4672 	int i;
4673 
4674 	/* warn the TX unit of coming changes */
4675 	i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4676 	if (!enable)
4677 		usleep_range(10, 20);
4678 
4679 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4680 		tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4681 		if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4682 		    ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4683 			break;
4684 		usleep_range(1000, 2000);
4685 	}
4686 
4687 	/* Skip if the queue is already in the requested state */
4688 	if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4689 		return;
4690 
4691 	/* turn on/off the queue */
4692 	if (enable) {
4693 		wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4694 		tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4695 	} else {
4696 		tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4697 	}
4698 
4699 	wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4700 }
4701 
4702 /**
4703  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4704  * @seid: VSI SEID
4705  * @pf: the PF structure
4706  * @pf_q: the PF queue to configure
4707  * @is_xdp: true if the queue is used for XDP
4708  * @enable: start or stop the queue
4709  **/
4710 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4711 			   bool is_xdp, bool enable)
4712 {
4713 	int ret;
4714 
4715 	i40e_control_tx_q(pf, pf_q, enable);
4716 
4717 	/* wait for the change to finish */
4718 	ret = i40e_pf_txq_wait(pf, pf_q, enable);
4719 	if (ret) {
4720 		dev_info(&pf->pdev->dev,
4721 			 "VSI seid %d %sTx ring %d %sable timeout\n",
4722 			 seid, (is_xdp ? "XDP " : ""), pf_q,
4723 			 (enable ? "en" : "dis"));
4724 	}
4725 
4726 	return ret;
4727 }
4728 
4729 /**
4730  * i40e_vsi_enable_tx - Start a VSI's rings
4731  * @vsi: the VSI being configured
4732  **/
4733 static int i40e_vsi_enable_tx(struct i40e_vsi *vsi)
4734 {
4735 	struct i40e_pf *pf = vsi->back;
4736 	int i, pf_q, ret = 0;
4737 
4738 	pf_q = vsi->base_queue;
4739 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4740 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4741 					     pf_q,
4742 					     false /*is xdp*/, true);
4743 		if (ret)
4744 			break;
4745 
4746 		if (!i40e_enabled_xdp_vsi(vsi))
4747 			continue;
4748 
4749 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4750 					     pf_q + vsi->alloc_queue_pairs,
4751 					     true /*is xdp*/, true);
4752 		if (ret)
4753 			break;
4754 	}
4755 	return ret;
4756 }
4757 
4758 /**
4759  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4760  * @pf: the PF being configured
4761  * @pf_q: the PF queue
4762  * @enable: enable or disable state of the queue
4763  *
4764  * This routine will wait for the given Rx queue of the PF to reach the
4765  * enabled or disabled state.
4766  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4767  * multiple retries; else will return 0 in case of success.
4768  **/
4769 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4770 {
4771 	int i;
4772 	u32 rx_reg;
4773 
4774 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4775 		rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4776 		if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4777 			break;
4778 
4779 		usleep_range(10, 20);
4780 	}
4781 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4782 		return -ETIMEDOUT;
4783 
4784 	return 0;
4785 }
4786 
4787 /**
4788  * i40e_control_rx_q - Start or stop a particular Rx queue
4789  * @pf: the PF structure
4790  * @pf_q: the PF queue to configure
4791  * @enable: start or stop the queue
4792  *
4793  * This function enables or disables a single queue. Note that
4794  * any delay required after the operation is expected to be
4795  * handled by the caller of this function.
4796  **/
4797 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4798 {
4799 	struct i40e_hw *hw = &pf->hw;
4800 	u32 rx_reg;
4801 	int i;
4802 
4803 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4804 		rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4805 		if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4806 		    ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4807 			break;
4808 		usleep_range(1000, 2000);
4809 	}
4810 
4811 	/* Skip if the queue is already in the requested state */
4812 	if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4813 		return;
4814 
4815 	/* turn on/off the queue */
4816 	if (enable)
4817 		rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4818 	else
4819 		rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4820 
4821 	wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4822 }
4823 
4824 /**
4825  * i40e_control_wait_rx_q
4826  * @pf: the PF structure
4827  * @pf_q: queue being configured
4828  * @enable: start or stop the rings
4829  *
4830  * This function enables or disables a single queue along with waiting
4831  * for the change to finish. The caller of this function should handle
4832  * the delays needed in the case of disabling queues.
4833  **/
4834 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4835 {
4836 	int ret = 0;
4837 
4838 	i40e_control_rx_q(pf, pf_q, enable);
4839 
4840 	/* wait for the change to finish */
4841 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4842 	if (ret)
4843 		return ret;
4844 
4845 	return ret;
4846 }
4847 
4848 /**
4849  * i40e_vsi_enable_rx - Start a VSI's rings
4850  * @vsi: the VSI being configured
4851  **/
4852 static int i40e_vsi_enable_rx(struct i40e_vsi *vsi)
4853 {
4854 	struct i40e_pf *pf = vsi->back;
4855 	int i, pf_q, ret = 0;
4856 
4857 	pf_q = vsi->base_queue;
4858 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4859 		ret = i40e_control_wait_rx_q(pf, pf_q, true);
4860 		if (ret) {
4861 			dev_info(&pf->pdev->dev,
4862 				 "VSI seid %d Rx ring %d enable timeout\n",
4863 				 vsi->seid, pf_q);
4864 			break;
4865 		}
4866 	}
4867 
4868 	return ret;
4869 }
4870 
4871 /**
4872  * i40e_vsi_start_rings - Start a VSI's rings
4873  * @vsi: the VSI being configured
4874  **/
4875 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4876 {
4877 	int ret = 0;
4878 
4879 	/* do rx first for enable and last for disable */
4880 	ret = i40e_vsi_enable_rx(vsi);
4881 	if (ret)
4882 		return ret;
4883 	ret = i40e_vsi_enable_tx(vsi);
4884 
4885 	return ret;
4886 }
4887 
4888 #define I40E_DISABLE_TX_GAP_MSEC	50
4889 
4890 /**
4891  * i40e_vsi_stop_rings - Stop a VSI's rings
4892  * @vsi: the VSI being configured
4893  **/
4894 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4895 {
4896 	struct i40e_pf *pf = vsi->back;
4897 	int pf_q, err, q_end;
4898 
4899 	/* When port TX is suspended, don't wait */
4900 	if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4901 		return i40e_vsi_stop_rings_no_wait(vsi);
4902 
4903 	q_end = vsi->base_queue + vsi->num_queue_pairs;
4904 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4905 		i40e_pre_tx_queue_cfg(&pf->hw, (u32)pf_q, false);
4906 
4907 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++) {
4908 		err = i40e_control_wait_rx_q(pf, pf_q, false);
4909 		if (err)
4910 			dev_info(&pf->pdev->dev,
4911 				 "VSI seid %d Rx ring %d disable timeout\n",
4912 				 vsi->seid, pf_q);
4913 	}
4914 
4915 	msleep(I40E_DISABLE_TX_GAP_MSEC);
4916 	pf_q = vsi->base_queue;
4917 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4918 		wr32(&pf->hw, I40E_QTX_ENA(pf_q), 0);
4919 
4920 	i40e_vsi_wait_queues_disabled(vsi);
4921 }
4922 
4923 /**
4924  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4925  * @vsi: the VSI being shutdown
4926  *
4927  * This function stops all the rings for a VSI but does not delay to verify
4928  * that rings have been disabled. It is expected that the caller is shutting
4929  * down multiple VSIs at once and will delay together for all the VSIs after
4930  * initiating the shutdown. This is particularly useful for shutting down lots
4931  * of VFs together. Otherwise, a large delay can be incurred while configuring
4932  * each VSI in serial.
4933  **/
4934 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4935 {
4936 	struct i40e_pf *pf = vsi->back;
4937 	int i, pf_q;
4938 
4939 	pf_q = vsi->base_queue;
4940 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4941 		i40e_control_tx_q(pf, pf_q, false);
4942 		i40e_control_rx_q(pf, pf_q, false);
4943 	}
4944 }
4945 
4946 /**
4947  * i40e_vsi_free_irq - Free the irq association with the OS
4948  * @vsi: the VSI being configured
4949  **/
4950 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4951 {
4952 	struct i40e_pf *pf = vsi->back;
4953 	struct i40e_hw *hw = &pf->hw;
4954 	int base = vsi->base_vector;
4955 	u32 val, qp;
4956 	int i;
4957 
4958 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4959 		if (!vsi->q_vectors)
4960 			return;
4961 
4962 		if (!vsi->irqs_ready)
4963 			return;
4964 
4965 		vsi->irqs_ready = false;
4966 		for (i = 0; i < vsi->num_q_vectors; i++) {
4967 			int irq_num;
4968 			u16 vector;
4969 
4970 			vector = i + base;
4971 			irq_num = pf->msix_entries[vector].vector;
4972 
4973 			/* free only the irqs that were actually requested */
4974 			if (!vsi->q_vectors[i] ||
4975 			    !vsi->q_vectors[i]->num_ringpairs)
4976 				continue;
4977 
4978 			/* clear the affinity notifier in the IRQ descriptor */
4979 			irq_set_affinity_notifier(irq_num, NULL);
4980 			/* remove our suggested affinity mask for this IRQ */
4981 			irq_update_affinity_hint(irq_num, NULL);
4982 			free_irq(irq_num, vsi->q_vectors[i]);
4983 
4984 			/* Tear down the interrupt queue link list
4985 			 *
4986 			 * We know that they come in pairs and always
4987 			 * the Rx first, then the Tx.  To clear the
4988 			 * link list, stick the EOL value into the
4989 			 * next_q field of the registers.
4990 			 */
4991 			val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
4992 			qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4993 				>> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4994 			val |= I40E_QUEUE_END_OF_LIST
4995 				<< I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4996 			wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
4997 
4998 			while (qp != I40E_QUEUE_END_OF_LIST) {
4999 				u32 next;
5000 
5001 				val = rd32(hw, I40E_QINT_RQCTL(qp));
5002 
5003 				val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5004 					 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5005 					 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5006 					 I40E_QINT_RQCTL_INTEVENT_MASK);
5007 
5008 				val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5009 					 I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5010 
5011 				wr32(hw, I40E_QINT_RQCTL(qp), val);
5012 
5013 				val = rd32(hw, I40E_QINT_TQCTL(qp));
5014 
5015 				next = (val & I40E_QINT_TQCTL_NEXTQ_INDX_MASK)
5016 					>> I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT;
5017 
5018 				val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5019 					 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5020 					 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5021 					 I40E_QINT_TQCTL_INTEVENT_MASK);
5022 
5023 				val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5024 					 I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5025 
5026 				wr32(hw, I40E_QINT_TQCTL(qp), val);
5027 				qp = next;
5028 			}
5029 		}
5030 	} else {
5031 		free_irq(pf->pdev->irq, pf);
5032 
5033 		val = rd32(hw, I40E_PFINT_LNKLST0);
5034 		qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
5035 			>> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
5036 		val |= I40E_QUEUE_END_OF_LIST
5037 			<< I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
5038 		wr32(hw, I40E_PFINT_LNKLST0, val);
5039 
5040 		val = rd32(hw, I40E_QINT_RQCTL(qp));
5041 		val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5042 			 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5043 			 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5044 			 I40E_QINT_RQCTL_INTEVENT_MASK);
5045 
5046 		val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5047 			I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5048 
5049 		wr32(hw, I40E_QINT_RQCTL(qp), val);
5050 
5051 		val = rd32(hw, I40E_QINT_TQCTL(qp));
5052 
5053 		val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5054 			 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5055 			 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5056 			 I40E_QINT_TQCTL_INTEVENT_MASK);
5057 
5058 		val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5059 			I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5060 
5061 		wr32(hw, I40E_QINT_TQCTL(qp), val);
5062 	}
5063 }
5064 
5065 /**
5066  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
5067  * @vsi: the VSI being configured
5068  * @v_idx: Index of vector to be freed
5069  *
5070  * This function frees the memory allocated to the q_vector.  In addition if
5071  * NAPI is enabled it will delete any references to the NAPI struct prior
5072  * to freeing the q_vector.
5073  **/
5074 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
5075 {
5076 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
5077 	struct i40e_ring *ring;
5078 
5079 	if (!q_vector)
5080 		return;
5081 
5082 	/* disassociate q_vector from rings */
5083 	i40e_for_each_ring(ring, q_vector->tx)
5084 		ring->q_vector = NULL;
5085 
5086 	i40e_for_each_ring(ring, q_vector->rx)
5087 		ring->q_vector = NULL;
5088 
5089 	/* only VSI w/ an associated netdev is set up w/ NAPI */
5090 	if (vsi->netdev)
5091 		netif_napi_del(&q_vector->napi);
5092 
5093 	vsi->q_vectors[v_idx] = NULL;
5094 
5095 	kfree_rcu(q_vector, rcu);
5096 }
5097 
5098 /**
5099  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
5100  * @vsi: the VSI being un-configured
5101  *
5102  * This frees the memory allocated to the q_vectors and
5103  * deletes references to the NAPI struct.
5104  **/
5105 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
5106 {
5107 	int v_idx;
5108 
5109 	for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
5110 		i40e_free_q_vector(vsi, v_idx);
5111 }
5112 
5113 /**
5114  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
5115  * @pf: board private structure
5116  **/
5117 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
5118 {
5119 	/* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
5120 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
5121 		pci_disable_msix(pf->pdev);
5122 		kfree(pf->msix_entries);
5123 		pf->msix_entries = NULL;
5124 		kfree(pf->irq_pile);
5125 		pf->irq_pile = NULL;
5126 	} else if (pf->flags & I40E_FLAG_MSI_ENABLED) {
5127 		pci_disable_msi(pf->pdev);
5128 	}
5129 	pf->flags &= ~(I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
5130 }
5131 
5132 /**
5133  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
5134  * @pf: board private structure
5135  *
5136  * We go through and clear interrupt specific resources and reset the structure
5137  * to pre-load conditions
5138  **/
5139 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
5140 {
5141 	int i;
5142 
5143 	if (test_bit(__I40E_MISC_IRQ_REQUESTED, pf->state))
5144 		i40e_free_misc_vector(pf);
5145 
5146 	i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
5147 		      I40E_IWARP_IRQ_PILE_ID);
5148 
5149 	i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
5150 	for (i = 0; i < pf->num_alloc_vsi; i++)
5151 		if (pf->vsi[i])
5152 			i40e_vsi_free_q_vectors(pf->vsi[i]);
5153 	i40e_reset_interrupt_capability(pf);
5154 }
5155 
5156 /**
5157  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5158  * @vsi: the VSI being configured
5159  **/
5160 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
5161 {
5162 	int q_idx;
5163 
5164 	if (!vsi->netdev)
5165 		return;
5166 
5167 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5168 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5169 
5170 		if (q_vector->rx.ring || q_vector->tx.ring)
5171 			napi_enable(&q_vector->napi);
5172 	}
5173 }
5174 
5175 /**
5176  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
5177  * @vsi: the VSI being configured
5178  **/
5179 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
5180 {
5181 	int q_idx;
5182 
5183 	if (!vsi->netdev)
5184 		return;
5185 
5186 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5187 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5188 
5189 		if (q_vector->rx.ring || q_vector->tx.ring)
5190 			napi_disable(&q_vector->napi);
5191 	}
5192 }
5193 
5194 /**
5195  * i40e_vsi_close - Shut down a VSI
5196  * @vsi: the vsi to be quelled
5197  **/
5198 static void i40e_vsi_close(struct i40e_vsi *vsi)
5199 {
5200 	struct i40e_pf *pf = vsi->back;
5201 	if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
5202 		i40e_down(vsi);
5203 	i40e_vsi_free_irq(vsi);
5204 	i40e_vsi_free_tx_resources(vsi);
5205 	i40e_vsi_free_rx_resources(vsi);
5206 	vsi->current_netdev_flags = 0;
5207 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
5208 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
5209 		set_bit(__I40E_CLIENT_RESET, pf->state);
5210 }
5211 
5212 /**
5213  * i40e_quiesce_vsi - Pause a given VSI
5214  * @vsi: the VSI being paused
5215  **/
5216 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
5217 {
5218 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
5219 		return;
5220 
5221 	set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
5222 	if (vsi->netdev && netif_running(vsi->netdev))
5223 		vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
5224 	else
5225 		i40e_vsi_close(vsi);
5226 }
5227 
5228 /**
5229  * i40e_unquiesce_vsi - Resume a given VSI
5230  * @vsi: the VSI being resumed
5231  **/
5232 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
5233 {
5234 	if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
5235 		return;
5236 
5237 	if (vsi->netdev && netif_running(vsi->netdev))
5238 		vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
5239 	else
5240 		i40e_vsi_open(vsi);   /* this clears the DOWN bit */
5241 }
5242 
5243 /**
5244  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
5245  * @pf: the PF
5246  **/
5247 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
5248 {
5249 	int v;
5250 
5251 	for (v = 0; v < pf->num_alloc_vsi; v++) {
5252 		if (pf->vsi[v])
5253 			i40e_quiesce_vsi(pf->vsi[v]);
5254 	}
5255 }
5256 
5257 /**
5258  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
5259  * @pf: the PF
5260  **/
5261 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
5262 {
5263 	int v;
5264 
5265 	for (v = 0; v < pf->num_alloc_vsi; v++) {
5266 		if (pf->vsi[v])
5267 			i40e_unquiesce_vsi(pf->vsi[v]);
5268 	}
5269 }
5270 
5271 /**
5272  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
5273  * @vsi: the VSI being configured
5274  *
5275  * Wait until all queues on a given VSI have been disabled.
5276  **/
5277 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
5278 {
5279 	struct i40e_pf *pf = vsi->back;
5280 	int i, pf_q, ret;
5281 
5282 	pf_q = vsi->base_queue;
5283 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
5284 		/* Check and wait for the Tx queue */
5285 		ret = i40e_pf_txq_wait(pf, pf_q, false);
5286 		if (ret) {
5287 			dev_info(&pf->pdev->dev,
5288 				 "VSI seid %d Tx ring %d disable timeout\n",
5289 				 vsi->seid, pf_q);
5290 			return ret;
5291 		}
5292 
5293 		if (!i40e_enabled_xdp_vsi(vsi))
5294 			goto wait_rx;
5295 
5296 		/* Check and wait for the XDP Tx queue */
5297 		ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
5298 				       false);
5299 		if (ret) {
5300 			dev_info(&pf->pdev->dev,
5301 				 "VSI seid %d XDP Tx ring %d disable timeout\n",
5302 				 vsi->seid, pf_q);
5303 			return ret;
5304 		}
5305 wait_rx:
5306 		/* Check and wait for the Rx queue */
5307 		ret = i40e_pf_rxq_wait(pf, pf_q, false);
5308 		if (ret) {
5309 			dev_info(&pf->pdev->dev,
5310 				 "VSI seid %d Rx ring %d disable timeout\n",
5311 				 vsi->seid, pf_q);
5312 			return ret;
5313 		}
5314 	}
5315 
5316 	return 0;
5317 }
5318 
5319 #ifdef CONFIG_I40E_DCB
5320 /**
5321  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
5322  * @pf: the PF
5323  *
5324  * This function waits for the queues to be in disabled state for all the
5325  * VSIs that are managed by this PF.
5326  **/
5327 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
5328 {
5329 	int v, ret = 0;
5330 
5331 	for (v = 0; v < pf->hw.func_caps.num_vsis; v++) {
5332 		if (pf->vsi[v]) {
5333 			ret = i40e_vsi_wait_queues_disabled(pf->vsi[v]);
5334 			if (ret)
5335 				break;
5336 		}
5337 	}
5338 
5339 	return ret;
5340 }
5341 
5342 #endif
5343 
5344 /**
5345  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
5346  * @pf: pointer to PF
5347  *
5348  * Get TC map for ISCSI PF type that will include iSCSI TC
5349  * and LAN TC.
5350  **/
5351 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
5352 {
5353 	struct i40e_dcb_app_priority_table app;
5354 	struct i40e_hw *hw = &pf->hw;
5355 	u8 enabled_tc = 1; /* TC0 is always enabled */
5356 	u8 tc, i;
5357 	/* Get the iSCSI APP TLV */
5358 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5359 
5360 	for (i = 0; i < dcbcfg->numapps; i++) {
5361 		app = dcbcfg->app[i];
5362 		if (app.selector == I40E_APP_SEL_TCPIP &&
5363 		    app.protocolid == I40E_APP_PROTOID_ISCSI) {
5364 			tc = dcbcfg->etscfg.prioritytable[app.priority];
5365 			enabled_tc |= BIT(tc);
5366 			break;
5367 		}
5368 	}
5369 
5370 	return enabled_tc;
5371 }
5372 
5373 /**
5374  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5375  * @dcbcfg: the corresponding DCBx configuration structure
5376  *
5377  * Return the number of TCs from given DCBx configuration
5378  **/
5379 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5380 {
5381 	int i, tc_unused = 0;
5382 	u8 num_tc = 0;
5383 	u8 ret = 0;
5384 
5385 	/* Scan the ETS Config Priority Table to find
5386 	 * traffic class enabled for a given priority
5387 	 * and create a bitmask of enabled TCs
5388 	 */
5389 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5390 		num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5391 
5392 	/* Now scan the bitmask to check for
5393 	 * contiguous TCs starting with TC0
5394 	 */
5395 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5396 		if (num_tc & BIT(i)) {
5397 			if (!tc_unused) {
5398 				ret++;
5399 			} else {
5400 				pr_err("Non-contiguous TC - Disabling DCB\n");
5401 				return 1;
5402 			}
5403 		} else {
5404 			tc_unused = 1;
5405 		}
5406 	}
5407 
5408 	/* There is always at least TC0 */
5409 	if (!ret)
5410 		ret = 1;
5411 
5412 	return ret;
5413 }
5414 
5415 /**
5416  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5417  * @dcbcfg: the corresponding DCBx configuration structure
5418  *
5419  * Query the current DCB configuration and return the number of
5420  * traffic classes enabled from the given DCBX config
5421  **/
5422 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5423 {
5424 	u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5425 	u8 enabled_tc = 1;
5426 	u8 i;
5427 
5428 	for (i = 0; i < num_tc; i++)
5429 		enabled_tc |= BIT(i);
5430 
5431 	return enabled_tc;
5432 }
5433 
5434 /**
5435  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5436  * @pf: PF being queried
5437  *
5438  * Query the current MQPRIO configuration and return the number of
5439  * traffic classes enabled.
5440  **/
5441 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5442 {
5443 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
5444 	u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5445 	u8 enabled_tc = 1, i;
5446 
5447 	for (i = 1; i < num_tc; i++)
5448 		enabled_tc |= BIT(i);
5449 	return enabled_tc;
5450 }
5451 
5452 /**
5453  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5454  * @pf: PF being queried
5455  *
5456  * Return number of traffic classes enabled for the given PF
5457  **/
5458 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5459 {
5460 	struct i40e_hw *hw = &pf->hw;
5461 	u8 i, enabled_tc = 1;
5462 	u8 num_tc = 0;
5463 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5464 
5465 	if (i40e_is_tc_mqprio_enabled(pf))
5466 		return pf->vsi[pf->lan_vsi]->mqprio_qopt.qopt.num_tc;
5467 
5468 	/* If neither MQPRIO nor DCB is enabled, then always use single TC */
5469 	if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5470 		return 1;
5471 
5472 	/* SFP mode will be enabled for all TCs on port */
5473 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5474 		return i40e_dcb_get_num_tc(dcbcfg);
5475 
5476 	/* MFP mode return count of enabled TCs for this PF */
5477 	if (pf->hw.func_caps.iscsi)
5478 		enabled_tc =  i40e_get_iscsi_tc_map(pf);
5479 	else
5480 		return 1; /* Only TC0 */
5481 
5482 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5483 		if (enabled_tc & BIT(i))
5484 			num_tc++;
5485 	}
5486 	return num_tc;
5487 }
5488 
5489 /**
5490  * i40e_pf_get_tc_map - Get bitmap for enabled traffic classes
5491  * @pf: PF being queried
5492  *
5493  * Return a bitmap for enabled traffic classes for this PF.
5494  **/
5495 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5496 {
5497 	if (i40e_is_tc_mqprio_enabled(pf))
5498 		return i40e_mqprio_get_enabled_tc(pf);
5499 
5500 	/* If neither MQPRIO nor DCB is enabled for this PF then just return
5501 	 * default TC
5502 	 */
5503 	if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5504 		return I40E_DEFAULT_TRAFFIC_CLASS;
5505 
5506 	/* SFP mode we want PF to be enabled for all TCs */
5507 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5508 		return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5509 
5510 	/* MFP enabled and iSCSI PF type */
5511 	if (pf->hw.func_caps.iscsi)
5512 		return i40e_get_iscsi_tc_map(pf);
5513 	else
5514 		return I40E_DEFAULT_TRAFFIC_CLASS;
5515 }
5516 
5517 /**
5518  * i40e_vsi_get_bw_info - Query VSI BW Information
5519  * @vsi: the VSI being queried
5520  *
5521  * Returns 0 on success, negative value on failure
5522  **/
5523 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5524 {
5525 	struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5526 	struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5527 	struct i40e_pf *pf = vsi->back;
5528 	struct i40e_hw *hw = &pf->hw;
5529 	i40e_status ret;
5530 	u32 tc_bw_max;
5531 	int i;
5532 
5533 	/* Get the VSI level BW configuration */
5534 	ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5535 	if (ret) {
5536 		dev_info(&pf->pdev->dev,
5537 			 "couldn't get PF vsi bw config, err %s aq_err %s\n",
5538 			 i40e_stat_str(&pf->hw, ret),
5539 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5540 		return -EINVAL;
5541 	}
5542 
5543 	/* Get the VSI level BW configuration per TC */
5544 	ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5545 					       NULL);
5546 	if (ret) {
5547 		dev_info(&pf->pdev->dev,
5548 			 "couldn't get PF vsi ets bw config, err %s aq_err %s\n",
5549 			 i40e_stat_str(&pf->hw, ret),
5550 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5551 		return -EINVAL;
5552 	}
5553 
5554 	if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5555 		dev_info(&pf->pdev->dev,
5556 			 "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5557 			 bw_config.tc_valid_bits,
5558 			 bw_ets_config.tc_valid_bits);
5559 		/* Still continuing */
5560 	}
5561 
5562 	vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5563 	vsi->bw_max_quanta = bw_config.max_bw;
5564 	tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5565 		    (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5566 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5567 		vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5568 		vsi->bw_ets_limit_credits[i] =
5569 					le16_to_cpu(bw_ets_config.credits[i]);
5570 		/* 3 bits out of 4 for each TC */
5571 		vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5572 	}
5573 
5574 	return 0;
5575 }
5576 
5577 /**
5578  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5579  * @vsi: the VSI being configured
5580  * @enabled_tc: TC bitmap
5581  * @bw_share: BW shared credits per TC
5582  *
5583  * Returns 0 on success, negative value on failure
5584  **/
5585 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5586 				       u8 *bw_share)
5587 {
5588 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5589 	struct i40e_pf *pf = vsi->back;
5590 	i40e_status ret;
5591 	int i;
5592 
5593 	/* There is no need to reset BW when mqprio mode is on.  */
5594 	if (i40e_is_tc_mqprio_enabled(pf))
5595 		return 0;
5596 	if (!vsi->mqprio_qopt.qopt.hw && !(pf->flags & I40E_FLAG_DCB_ENABLED)) {
5597 		ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5598 		if (ret)
5599 			dev_info(&pf->pdev->dev,
5600 				 "Failed to reset tx rate for vsi->seid %u\n",
5601 				 vsi->seid);
5602 		return ret;
5603 	}
5604 	memset(&bw_data, 0, sizeof(bw_data));
5605 	bw_data.tc_valid_bits = enabled_tc;
5606 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5607 		bw_data.tc_bw_credits[i] = bw_share[i];
5608 
5609 	ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5610 	if (ret) {
5611 		dev_info(&pf->pdev->dev,
5612 			 "AQ command Config VSI BW allocation per TC failed = %d\n",
5613 			 pf->hw.aq.asq_last_status);
5614 		return -EINVAL;
5615 	}
5616 
5617 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5618 		vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5619 
5620 	return 0;
5621 }
5622 
5623 /**
5624  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5625  * @vsi: the VSI being configured
5626  * @enabled_tc: TC map to be enabled
5627  *
5628  **/
5629 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5630 {
5631 	struct net_device *netdev = vsi->netdev;
5632 	struct i40e_pf *pf = vsi->back;
5633 	struct i40e_hw *hw = &pf->hw;
5634 	u8 netdev_tc = 0;
5635 	int i;
5636 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5637 
5638 	if (!netdev)
5639 		return;
5640 
5641 	if (!enabled_tc) {
5642 		netdev_reset_tc(netdev);
5643 		return;
5644 	}
5645 
5646 	/* Set up actual enabled TCs on the VSI */
5647 	if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5648 		return;
5649 
5650 	/* set per TC queues for the VSI */
5651 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5652 		/* Only set TC queues for enabled tcs
5653 		 *
5654 		 * e.g. For a VSI that has TC0 and TC3 enabled the
5655 		 * enabled_tc bitmap would be 0x00001001; the driver
5656 		 * will set the numtc for netdev as 2 that will be
5657 		 * referenced by the netdev layer as TC 0 and 1.
5658 		 */
5659 		if (vsi->tc_config.enabled_tc & BIT(i))
5660 			netdev_set_tc_queue(netdev,
5661 					vsi->tc_config.tc_info[i].netdev_tc,
5662 					vsi->tc_config.tc_info[i].qcount,
5663 					vsi->tc_config.tc_info[i].qoffset);
5664 	}
5665 
5666 	if (i40e_is_tc_mqprio_enabled(pf))
5667 		return;
5668 
5669 	/* Assign UP2TC map for the VSI */
5670 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5671 		/* Get the actual TC# for the UP */
5672 		u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5673 		/* Get the mapped netdev TC# for the UP */
5674 		netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5675 		netdev_set_prio_tc_map(netdev, i, netdev_tc);
5676 	}
5677 }
5678 
5679 /**
5680  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5681  * @vsi: the VSI being configured
5682  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5683  **/
5684 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5685 				      struct i40e_vsi_context *ctxt)
5686 {
5687 	/* copy just the sections touched not the entire info
5688 	 * since not all sections are valid as returned by
5689 	 * update vsi params
5690 	 */
5691 	vsi->info.mapping_flags = ctxt->info.mapping_flags;
5692 	memcpy(&vsi->info.queue_mapping,
5693 	       &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5694 	memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5695 	       sizeof(vsi->info.tc_mapping));
5696 }
5697 
5698 /**
5699  * i40e_update_adq_vsi_queues - update queue mapping for ADq VSI
5700  * @vsi: the VSI being reconfigured
5701  * @vsi_offset: offset from main VF VSI
5702  */
5703 int i40e_update_adq_vsi_queues(struct i40e_vsi *vsi, int vsi_offset)
5704 {
5705 	struct i40e_vsi_context ctxt = {};
5706 	struct i40e_pf *pf;
5707 	struct i40e_hw *hw;
5708 	int ret;
5709 
5710 	if (!vsi)
5711 		return I40E_ERR_PARAM;
5712 	pf = vsi->back;
5713 	hw = &pf->hw;
5714 
5715 	ctxt.seid = vsi->seid;
5716 	ctxt.pf_num = hw->pf_id;
5717 	ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id + vsi_offset;
5718 	ctxt.uplink_seid = vsi->uplink_seid;
5719 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5720 	ctxt.flags = I40E_AQ_VSI_TYPE_VF;
5721 	ctxt.info = vsi->info;
5722 
5723 	i40e_vsi_setup_queue_map(vsi, &ctxt, vsi->tc_config.enabled_tc,
5724 				 false);
5725 	if (vsi->reconfig_rss) {
5726 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
5727 				      vsi->num_queue_pairs);
5728 		ret = i40e_vsi_config_rss(vsi);
5729 		if (ret) {
5730 			dev_info(&pf->pdev->dev, "Failed to reconfig rss for num_queues\n");
5731 			return ret;
5732 		}
5733 		vsi->reconfig_rss = false;
5734 	}
5735 
5736 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5737 	if (ret) {
5738 		dev_info(&pf->pdev->dev, "Update vsi config failed, err %s aq_err %s\n",
5739 			 i40e_stat_str(hw, ret),
5740 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5741 		return ret;
5742 	}
5743 	/* update the local VSI info with updated queue map */
5744 	i40e_vsi_update_queue_map(vsi, &ctxt);
5745 	vsi->info.valid_sections = 0;
5746 
5747 	return ret;
5748 }
5749 
5750 /**
5751  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5752  * @vsi: VSI to be configured
5753  * @enabled_tc: TC bitmap
5754  *
5755  * This configures a particular VSI for TCs that are mapped to the
5756  * given TC bitmap. It uses default bandwidth share for TCs across
5757  * VSIs to configure TC for a particular VSI.
5758  *
5759  * NOTE:
5760  * It is expected that the VSI queues have been quisced before calling
5761  * this function.
5762  **/
5763 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5764 {
5765 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5766 	struct i40e_pf *pf = vsi->back;
5767 	struct i40e_hw *hw = &pf->hw;
5768 	struct i40e_vsi_context ctxt;
5769 	int ret = 0;
5770 	int i;
5771 
5772 	/* Check if enabled_tc is same as existing or new TCs */
5773 	if (vsi->tc_config.enabled_tc == enabled_tc &&
5774 	    vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5775 		return ret;
5776 
5777 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
5778 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5779 		if (enabled_tc & BIT(i))
5780 			bw_share[i] = 1;
5781 	}
5782 
5783 	ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5784 	if (ret) {
5785 		struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5786 
5787 		dev_info(&pf->pdev->dev,
5788 			 "Failed configuring TC map %d for VSI %d\n",
5789 			 enabled_tc, vsi->seid);
5790 		ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5791 						  &bw_config, NULL);
5792 		if (ret) {
5793 			dev_info(&pf->pdev->dev,
5794 				 "Failed querying vsi bw info, err %s aq_err %s\n",
5795 				 i40e_stat_str(hw, ret),
5796 				 i40e_aq_str(hw, hw->aq.asq_last_status));
5797 			goto out;
5798 		}
5799 		if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5800 			u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5801 
5802 			if (!valid_tc)
5803 				valid_tc = bw_config.tc_valid_bits;
5804 			/* Always enable TC0, no matter what */
5805 			valid_tc |= 1;
5806 			dev_info(&pf->pdev->dev,
5807 				 "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5808 				 enabled_tc, bw_config.tc_valid_bits, valid_tc);
5809 			enabled_tc = valid_tc;
5810 		}
5811 
5812 		ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5813 		if (ret) {
5814 			dev_err(&pf->pdev->dev,
5815 				"Unable to  configure TC map %d for VSI %d\n",
5816 				enabled_tc, vsi->seid);
5817 			goto out;
5818 		}
5819 	}
5820 
5821 	/* Update Queue Pairs Mapping for currently enabled UPs */
5822 	ctxt.seid = vsi->seid;
5823 	ctxt.pf_num = vsi->back->hw.pf_id;
5824 	ctxt.vf_num = 0;
5825 	ctxt.uplink_seid = vsi->uplink_seid;
5826 	ctxt.info = vsi->info;
5827 	if (i40e_is_tc_mqprio_enabled(pf)) {
5828 		ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5829 		if (ret)
5830 			goto out;
5831 	} else {
5832 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5833 	}
5834 
5835 	/* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5836 	 * queues changed.
5837 	 */
5838 	if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5839 		vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5840 				      vsi->num_queue_pairs);
5841 		ret = i40e_vsi_config_rss(vsi);
5842 		if (ret) {
5843 			dev_info(&vsi->back->pdev->dev,
5844 				 "Failed to reconfig rss for num_queues\n");
5845 			return ret;
5846 		}
5847 		vsi->reconfig_rss = false;
5848 	}
5849 	if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
5850 		ctxt.info.valid_sections |=
5851 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5852 		ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5853 	}
5854 
5855 	/* Update the VSI after updating the VSI queue-mapping
5856 	 * information
5857 	 */
5858 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5859 	if (ret) {
5860 		dev_info(&pf->pdev->dev,
5861 			 "Update vsi tc config failed, err %s aq_err %s\n",
5862 			 i40e_stat_str(hw, ret),
5863 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5864 		goto out;
5865 	}
5866 	/* update the local VSI info with updated queue map */
5867 	i40e_vsi_update_queue_map(vsi, &ctxt);
5868 	vsi->info.valid_sections = 0;
5869 
5870 	/* Update current VSI BW information */
5871 	ret = i40e_vsi_get_bw_info(vsi);
5872 	if (ret) {
5873 		dev_info(&pf->pdev->dev,
5874 			 "Failed updating vsi bw info, err %s aq_err %s\n",
5875 			 i40e_stat_str(hw, ret),
5876 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5877 		goto out;
5878 	}
5879 
5880 	/* Update the netdev TC setup */
5881 	i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5882 out:
5883 	return ret;
5884 }
5885 
5886 /**
5887  * i40e_get_link_speed - Returns link speed for the interface
5888  * @vsi: VSI to be configured
5889  *
5890  **/
5891 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5892 {
5893 	struct i40e_pf *pf = vsi->back;
5894 
5895 	switch (pf->hw.phy.link_info.link_speed) {
5896 	case I40E_LINK_SPEED_40GB:
5897 		return 40000;
5898 	case I40E_LINK_SPEED_25GB:
5899 		return 25000;
5900 	case I40E_LINK_SPEED_20GB:
5901 		return 20000;
5902 	case I40E_LINK_SPEED_10GB:
5903 		return 10000;
5904 	case I40E_LINK_SPEED_1GB:
5905 		return 1000;
5906 	default:
5907 		return -EINVAL;
5908 	}
5909 }
5910 
5911 /**
5912  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5913  * @vsi: VSI to be configured
5914  * @seid: seid of the channel/VSI
5915  * @max_tx_rate: max TX rate to be configured as BW limit
5916  *
5917  * Helper function to set BW limit for a given VSI
5918  **/
5919 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5920 {
5921 	struct i40e_pf *pf = vsi->back;
5922 	u64 credits = 0;
5923 	int speed = 0;
5924 	int ret = 0;
5925 
5926 	speed = i40e_get_link_speed(vsi);
5927 	if (max_tx_rate > speed) {
5928 		dev_err(&pf->pdev->dev,
5929 			"Invalid max tx rate %llu specified for VSI seid %d.",
5930 			max_tx_rate, seid);
5931 		return -EINVAL;
5932 	}
5933 	if (max_tx_rate && max_tx_rate < 50) {
5934 		dev_warn(&pf->pdev->dev,
5935 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
5936 		max_tx_rate = 50;
5937 	}
5938 
5939 	/* Tx rate credits are in values of 50Mbps, 0 is disabled */
5940 	credits = max_tx_rate;
5941 	do_div(credits, I40E_BW_CREDIT_DIVISOR);
5942 	ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
5943 					  I40E_MAX_BW_INACTIVE_ACCUM, NULL);
5944 	if (ret)
5945 		dev_err(&pf->pdev->dev,
5946 			"Failed set tx rate (%llu Mbps) for vsi->seid %u, err %s aq_err %s\n",
5947 			max_tx_rate, seid, i40e_stat_str(&pf->hw, ret),
5948 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5949 	return ret;
5950 }
5951 
5952 /**
5953  * i40e_remove_queue_channels - Remove queue channels for the TCs
5954  * @vsi: VSI to be configured
5955  *
5956  * Remove queue channels for the TCs
5957  **/
5958 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
5959 {
5960 	enum i40e_admin_queue_err last_aq_status;
5961 	struct i40e_cloud_filter *cfilter;
5962 	struct i40e_channel *ch, *ch_tmp;
5963 	struct i40e_pf *pf = vsi->back;
5964 	struct hlist_node *node;
5965 	int ret, i;
5966 
5967 	/* Reset rss size that was stored when reconfiguring rss for
5968 	 * channel VSIs with non-power-of-2 queue count.
5969 	 */
5970 	vsi->current_rss_size = 0;
5971 
5972 	/* perform cleanup for channels if they exist */
5973 	if (list_empty(&vsi->ch_list))
5974 		return;
5975 
5976 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5977 		struct i40e_vsi *p_vsi;
5978 
5979 		list_del(&ch->list);
5980 		p_vsi = ch->parent_vsi;
5981 		if (!p_vsi || !ch->initialized) {
5982 			kfree(ch);
5983 			continue;
5984 		}
5985 		/* Reset queue contexts */
5986 		for (i = 0; i < ch->num_queue_pairs; i++) {
5987 			struct i40e_ring *tx_ring, *rx_ring;
5988 			u16 pf_q;
5989 
5990 			pf_q = ch->base_queue + i;
5991 			tx_ring = vsi->tx_rings[pf_q];
5992 			tx_ring->ch = NULL;
5993 
5994 			rx_ring = vsi->rx_rings[pf_q];
5995 			rx_ring->ch = NULL;
5996 		}
5997 
5998 		/* Reset BW configured for this VSI via mqprio */
5999 		ret = i40e_set_bw_limit(vsi, ch->seid, 0);
6000 		if (ret)
6001 			dev_info(&vsi->back->pdev->dev,
6002 				 "Failed to reset tx rate for ch->seid %u\n",
6003 				 ch->seid);
6004 
6005 		/* delete cloud filters associated with this channel */
6006 		hlist_for_each_entry_safe(cfilter, node,
6007 					  &pf->cloud_filter_list, cloud_node) {
6008 			if (cfilter->seid != ch->seid)
6009 				continue;
6010 
6011 			hash_del(&cfilter->cloud_node);
6012 			if (cfilter->dst_port)
6013 				ret = i40e_add_del_cloud_filter_big_buf(vsi,
6014 									cfilter,
6015 									false);
6016 			else
6017 				ret = i40e_add_del_cloud_filter(vsi, cfilter,
6018 								false);
6019 			last_aq_status = pf->hw.aq.asq_last_status;
6020 			if (ret)
6021 				dev_info(&pf->pdev->dev,
6022 					 "Failed to delete cloud filter, err %s aq_err %s\n",
6023 					 i40e_stat_str(&pf->hw, ret),
6024 					 i40e_aq_str(&pf->hw, last_aq_status));
6025 			kfree(cfilter);
6026 		}
6027 
6028 		/* delete VSI from FW */
6029 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
6030 					     NULL);
6031 		if (ret)
6032 			dev_err(&vsi->back->pdev->dev,
6033 				"unable to remove channel (%d) for parent VSI(%d)\n",
6034 				ch->seid, p_vsi->seid);
6035 		kfree(ch);
6036 	}
6037 	INIT_LIST_HEAD(&vsi->ch_list);
6038 }
6039 
6040 /**
6041  * i40e_get_max_queues_for_channel
6042  * @vsi: ptr to VSI to which channels are associated with
6043  *
6044  * Helper function which returns max value among the queue counts set on the
6045  * channels/TCs created.
6046  **/
6047 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
6048 {
6049 	struct i40e_channel *ch, *ch_tmp;
6050 	int max = 0;
6051 
6052 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6053 		if (!ch->initialized)
6054 			continue;
6055 		if (ch->num_queue_pairs > max)
6056 			max = ch->num_queue_pairs;
6057 	}
6058 
6059 	return max;
6060 }
6061 
6062 /**
6063  * i40e_validate_num_queues - validate num_queues w.r.t channel
6064  * @pf: ptr to PF device
6065  * @num_queues: number of queues
6066  * @vsi: the parent VSI
6067  * @reconfig_rss: indicates should the RSS be reconfigured or not
6068  *
6069  * This function validates number of queues in the context of new channel
6070  * which is being established and determines if RSS should be reconfigured
6071  * or not for parent VSI.
6072  **/
6073 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
6074 				    struct i40e_vsi *vsi, bool *reconfig_rss)
6075 {
6076 	int max_ch_queues;
6077 
6078 	if (!reconfig_rss)
6079 		return -EINVAL;
6080 
6081 	*reconfig_rss = false;
6082 	if (vsi->current_rss_size) {
6083 		if (num_queues > vsi->current_rss_size) {
6084 			dev_dbg(&pf->pdev->dev,
6085 				"Error: num_queues (%d) > vsi's current_size(%d)\n",
6086 				num_queues, vsi->current_rss_size);
6087 			return -EINVAL;
6088 		} else if ((num_queues < vsi->current_rss_size) &&
6089 			   (!is_power_of_2(num_queues))) {
6090 			dev_dbg(&pf->pdev->dev,
6091 				"Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
6092 				num_queues, vsi->current_rss_size);
6093 			return -EINVAL;
6094 		}
6095 	}
6096 
6097 	if (!is_power_of_2(num_queues)) {
6098 		/* Find the max num_queues configured for channel if channel
6099 		 * exist.
6100 		 * if channel exist, then enforce 'num_queues' to be more than
6101 		 * max ever queues configured for channel.
6102 		 */
6103 		max_ch_queues = i40e_get_max_queues_for_channel(vsi);
6104 		if (num_queues < max_ch_queues) {
6105 			dev_dbg(&pf->pdev->dev,
6106 				"Error: num_queues (%d) < max queues configured for channel(%d)\n",
6107 				num_queues, max_ch_queues);
6108 			return -EINVAL;
6109 		}
6110 		*reconfig_rss = true;
6111 	}
6112 
6113 	return 0;
6114 }
6115 
6116 /**
6117  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
6118  * @vsi: the VSI being setup
6119  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
6120  *
6121  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
6122  **/
6123 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
6124 {
6125 	struct i40e_pf *pf = vsi->back;
6126 	u8 seed[I40E_HKEY_ARRAY_SIZE];
6127 	struct i40e_hw *hw = &pf->hw;
6128 	int local_rss_size;
6129 	u8 *lut;
6130 	int ret;
6131 
6132 	if (!vsi->rss_size)
6133 		return -EINVAL;
6134 
6135 	if (rss_size > vsi->rss_size)
6136 		return -EINVAL;
6137 
6138 	local_rss_size = min_t(int, vsi->rss_size, rss_size);
6139 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
6140 	if (!lut)
6141 		return -ENOMEM;
6142 
6143 	/* Ignoring user configured lut if there is one */
6144 	i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
6145 
6146 	/* Use user configured hash key if there is one, otherwise
6147 	 * use default.
6148 	 */
6149 	if (vsi->rss_hkey_user)
6150 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
6151 	else
6152 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
6153 
6154 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
6155 	if (ret) {
6156 		dev_info(&pf->pdev->dev,
6157 			 "Cannot set RSS lut, err %s aq_err %s\n",
6158 			 i40e_stat_str(hw, ret),
6159 			 i40e_aq_str(hw, hw->aq.asq_last_status));
6160 		kfree(lut);
6161 		return ret;
6162 	}
6163 	kfree(lut);
6164 
6165 	/* Do the update w.r.t. storing rss_size */
6166 	if (!vsi->orig_rss_size)
6167 		vsi->orig_rss_size = vsi->rss_size;
6168 	vsi->current_rss_size = local_rss_size;
6169 
6170 	return ret;
6171 }
6172 
6173 /**
6174  * i40e_channel_setup_queue_map - Setup a channel queue map
6175  * @pf: ptr to PF device
6176  * @ctxt: VSI context structure
6177  * @ch: ptr to channel structure
6178  *
6179  * Setup queue map for a specific channel
6180  **/
6181 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
6182 					 struct i40e_vsi_context *ctxt,
6183 					 struct i40e_channel *ch)
6184 {
6185 	u16 qcount, qmap, sections = 0;
6186 	u8 offset = 0;
6187 	int pow;
6188 
6189 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
6190 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
6191 
6192 	qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
6193 	ch->num_queue_pairs = qcount;
6194 
6195 	/* find the next higher power-of-2 of num queue pairs */
6196 	pow = ilog2(qcount);
6197 	if (!is_power_of_2(qcount))
6198 		pow++;
6199 
6200 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
6201 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
6202 
6203 	/* Setup queue TC[0].qmap for given VSI context */
6204 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
6205 
6206 	ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
6207 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
6208 	ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
6209 	ctxt->info.valid_sections |= cpu_to_le16(sections);
6210 }
6211 
6212 /**
6213  * i40e_add_channel - add a channel by adding VSI
6214  * @pf: ptr to PF device
6215  * @uplink_seid: underlying HW switching element (VEB) ID
6216  * @ch: ptr to channel structure
6217  *
6218  * Add a channel (VSI) using add_vsi and queue_map
6219  **/
6220 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
6221 			    struct i40e_channel *ch)
6222 {
6223 	struct i40e_hw *hw = &pf->hw;
6224 	struct i40e_vsi_context ctxt;
6225 	u8 enabled_tc = 0x1; /* TC0 enabled */
6226 	int ret;
6227 
6228 	if (ch->type != I40E_VSI_VMDQ2) {
6229 		dev_info(&pf->pdev->dev,
6230 			 "add new vsi failed, ch->type %d\n", ch->type);
6231 		return -EINVAL;
6232 	}
6233 
6234 	memset(&ctxt, 0, sizeof(ctxt));
6235 	ctxt.pf_num = hw->pf_id;
6236 	ctxt.vf_num = 0;
6237 	ctxt.uplink_seid = uplink_seid;
6238 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
6239 	if (ch->type == I40E_VSI_VMDQ2)
6240 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
6241 
6242 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED) {
6243 		ctxt.info.valid_sections |=
6244 		     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6245 		ctxt.info.switch_id =
6246 		   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6247 	}
6248 
6249 	/* Set queue map for a given VSI context */
6250 	i40e_channel_setup_queue_map(pf, &ctxt, ch);
6251 
6252 	/* Now time to create VSI */
6253 	ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
6254 	if (ret) {
6255 		dev_info(&pf->pdev->dev,
6256 			 "add new vsi failed, err %s aq_err %s\n",
6257 			 i40e_stat_str(&pf->hw, ret),
6258 			 i40e_aq_str(&pf->hw,
6259 				     pf->hw.aq.asq_last_status));
6260 		return -ENOENT;
6261 	}
6262 
6263 	/* Success, update channel, set enabled_tc only if the channel
6264 	 * is not a macvlan
6265 	 */
6266 	ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
6267 	ch->seid = ctxt.seid;
6268 	ch->vsi_number = ctxt.vsi_number;
6269 	ch->stat_counter_idx = le16_to_cpu(ctxt.info.stat_counter_idx);
6270 
6271 	/* copy just the sections touched not the entire info
6272 	 * since not all sections are valid as returned by
6273 	 * update vsi params
6274 	 */
6275 	ch->info.mapping_flags = ctxt.info.mapping_flags;
6276 	memcpy(&ch->info.queue_mapping,
6277 	       &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
6278 	memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
6279 	       sizeof(ctxt.info.tc_mapping));
6280 
6281 	return 0;
6282 }
6283 
6284 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
6285 				  u8 *bw_share)
6286 {
6287 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
6288 	i40e_status ret;
6289 	int i;
6290 
6291 	memset(&bw_data, 0, sizeof(bw_data));
6292 	bw_data.tc_valid_bits = ch->enabled_tc;
6293 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6294 		bw_data.tc_bw_credits[i] = bw_share[i];
6295 
6296 	ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
6297 				       &bw_data, NULL);
6298 	if (ret) {
6299 		dev_info(&vsi->back->pdev->dev,
6300 			 "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
6301 			 vsi->back->hw.aq.asq_last_status, ch->seid);
6302 		return -EINVAL;
6303 	}
6304 
6305 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6306 		ch->info.qs_handle[i] = bw_data.qs_handles[i];
6307 
6308 	return 0;
6309 }
6310 
6311 /**
6312  * i40e_channel_config_tx_ring - config TX ring associated with new channel
6313  * @pf: ptr to PF device
6314  * @vsi: the VSI being setup
6315  * @ch: ptr to channel structure
6316  *
6317  * Configure TX rings associated with channel (VSI) since queues are being
6318  * from parent VSI.
6319  **/
6320 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
6321 				       struct i40e_vsi *vsi,
6322 				       struct i40e_channel *ch)
6323 {
6324 	i40e_status ret;
6325 	int i;
6326 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
6327 
6328 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
6329 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6330 		if (ch->enabled_tc & BIT(i))
6331 			bw_share[i] = 1;
6332 	}
6333 
6334 	/* configure BW for new VSI */
6335 	ret = i40e_channel_config_bw(vsi, ch, bw_share);
6336 	if (ret) {
6337 		dev_info(&vsi->back->pdev->dev,
6338 			 "Failed configuring TC map %d for channel (seid %u)\n",
6339 			 ch->enabled_tc, ch->seid);
6340 		return ret;
6341 	}
6342 
6343 	for (i = 0; i < ch->num_queue_pairs; i++) {
6344 		struct i40e_ring *tx_ring, *rx_ring;
6345 		u16 pf_q;
6346 
6347 		pf_q = ch->base_queue + i;
6348 
6349 		/* Get to TX ring ptr of main VSI, for re-setup TX queue
6350 		 * context
6351 		 */
6352 		tx_ring = vsi->tx_rings[pf_q];
6353 		tx_ring->ch = ch;
6354 
6355 		/* Get the RX ring ptr */
6356 		rx_ring = vsi->rx_rings[pf_q];
6357 		rx_ring->ch = ch;
6358 	}
6359 
6360 	return 0;
6361 }
6362 
6363 /**
6364  * i40e_setup_hw_channel - setup new channel
6365  * @pf: ptr to PF device
6366  * @vsi: the VSI being setup
6367  * @ch: ptr to channel structure
6368  * @uplink_seid: underlying HW switching element (VEB) ID
6369  * @type: type of channel to be created (VMDq2/VF)
6370  *
6371  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6372  * and configures TX rings accordingly
6373  **/
6374 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
6375 					struct i40e_vsi *vsi,
6376 					struct i40e_channel *ch,
6377 					u16 uplink_seid, u8 type)
6378 {
6379 	int ret;
6380 
6381 	ch->initialized = false;
6382 	ch->base_queue = vsi->next_base_queue;
6383 	ch->type = type;
6384 
6385 	/* Proceed with creation of channel (VMDq2) VSI */
6386 	ret = i40e_add_channel(pf, uplink_seid, ch);
6387 	if (ret) {
6388 		dev_info(&pf->pdev->dev,
6389 			 "failed to add_channel using uplink_seid %u\n",
6390 			 uplink_seid);
6391 		return ret;
6392 	}
6393 
6394 	/* Mark the successful creation of channel */
6395 	ch->initialized = true;
6396 
6397 	/* Reconfigure TX queues using QTX_CTL register */
6398 	ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6399 	if (ret) {
6400 		dev_info(&pf->pdev->dev,
6401 			 "failed to configure TX rings for channel %u\n",
6402 			 ch->seid);
6403 		return ret;
6404 	}
6405 
6406 	/* update 'next_base_queue' */
6407 	vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6408 	dev_dbg(&pf->pdev->dev,
6409 		"Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6410 		ch->seid, ch->vsi_number, ch->stat_counter_idx,
6411 		ch->num_queue_pairs,
6412 		vsi->next_base_queue);
6413 	return ret;
6414 }
6415 
6416 /**
6417  * i40e_setup_channel - setup new channel using uplink element
6418  * @pf: ptr to PF device
6419  * @vsi: pointer to the VSI to set up the channel within
6420  * @ch: ptr to channel structure
6421  *
6422  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6423  * and uplink switching element (uplink_seid)
6424  **/
6425 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6426 			       struct i40e_channel *ch)
6427 {
6428 	u8 vsi_type;
6429 	u16 seid;
6430 	int ret;
6431 
6432 	if (vsi->type == I40E_VSI_MAIN) {
6433 		vsi_type = I40E_VSI_VMDQ2;
6434 	} else {
6435 		dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6436 			vsi->type);
6437 		return false;
6438 	}
6439 
6440 	/* underlying switching element */
6441 	seid = pf->vsi[pf->lan_vsi]->uplink_seid;
6442 
6443 	/* create channel (VSI), configure TX rings */
6444 	ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6445 	if (ret) {
6446 		dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6447 		return false;
6448 	}
6449 
6450 	return ch->initialized ? true : false;
6451 }
6452 
6453 /**
6454  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6455  * @vsi: ptr to VSI which has PF backing
6456  *
6457  * Sets up switch mode correctly if it needs to be changed and perform
6458  * what are allowed modes.
6459  **/
6460 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6461 {
6462 	u8 mode;
6463 	struct i40e_pf *pf = vsi->back;
6464 	struct i40e_hw *hw = &pf->hw;
6465 	int ret;
6466 
6467 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6468 	if (ret)
6469 		return -EINVAL;
6470 
6471 	if (hw->dev_caps.switch_mode) {
6472 		/* if switch mode is set, support mode2 (non-tunneled for
6473 		 * cloud filter) for now
6474 		 */
6475 		u32 switch_mode = hw->dev_caps.switch_mode &
6476 				  I40E_SWITCH_MODE_MASK;
6477 		if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6478 			if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6479 				return 0;
6480 			dev_err(&pf->pdev->dev,
6481 				"Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6482 				hw->dev_caps.switch_mode);
6483 			return -EINVAL;
6484 		}
6485 	}
6486 
6487 	/* Set Bit 7 to be valid */
6488 	mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6489 
6490 	/* Set L4type for TCP support */
6491 	mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6492 
6493 	/* Set cloud filter mode */
6494 	mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6495 
6496 	/* Prep mode field for set_switch_config */
6497 	ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6498 					pf->last_sw_conf_valid_flags,
6499 					mode, NULL);
6500 	if (ret && hw->aq.asq_last_status != I40E_AQ_RC_ESRCH)
6501 		dev_err(&pf->pdev->dev,
6502 			"couldn't set switch config bits, err %s aq_err %s\n",
6503 			i40e_stat_str(hw, ret),
6504 			i40e_aq_str(hw,
6505 				    hw->aq.asq_last_status));
6506 
6507 	return ret;
6508 }
6509 
6510 /**
6511  * i40e_create_queue_channel - function to create channel
6512  * @vsi: VSI to be configured
6513  * @ch: ptr to channel (it contains channel specific params)
6514  *
6515  * This function creates channel (VSI) using num_queues specified by user,
6516  * reconfigs RSS if needed.
6517  **/
6518 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6519 			      struct i40e_channel *ch)
6520 {
6521 	struct i40e_pf *pf = vsi->back;
6522 	bool reconfig_rss;
6523 	int err;
6524 
6525 	if (!ch)
6526 		return -EINVAL;
6527 
6528 	if (!ch->num_queue_pairs) {
6529 		dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6530 			ch->num_queue_pairs);
6531 		return -EINVAL;
6532 	}
6533 
6534 	/* validate user requested num_queues for channel */
6535 	err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6536 				       &reconfig_rss);
6537 	if (err) {
6538 		dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6539 			 ch->num_queue_pairs);
6540 		return -EINVAL;
6541 	}
6542 
6543 	/* By default we are in VEPA mode, if this is the first VF/VMDq
6544 	 * VSI to be added switch to VEB mode.
6545 	 */
6546 
6547 	if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
6548 		pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
6549 
6550 		if (vsi->type == I40E_VSI_MAIN) {
6551 			if (i40e_is_tc_mqprio_enabled(pf))
6552 				i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
6553 			else
6554 				i40e_do_reset_safe(pf, I40E_PF_RESET_FLAG);
6555 		}
6556 		/* now onwards for main VSI, number of queues will be value
6557 		 * of TC0's queue count
6558 		 */
6559 	}
6560 
6561 	/* By this time, vsi->cnt_q_avail shall be set to non-zero and
6562 	 * it should be more than num_queues
6563 	 */
6564 	if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6565 		dev_dbg(&pf->pdev->dev,
6566 			"Error: cnt_q_avail (%u) less than num_queues %d\n",
6567 			vsi->cnt_q_avail, ch->num_queue_pairs);
6568 		return -EINVAL;
6569 	}
6570 
6571 	/* reconfig_rss only if vsi type is MAIN_VSI */
6572 	if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6573 		err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6574 		if (err) {
6575 			dev_info(&pf->pdev->dev,
6576 				 "Error: unable to reconfig rss for num_queues (%u)\n",
6577 				 ch->num_queue_pairs);
6578 			return -EINVAL;
6579 		}
6580 	}
6581 
6582 	if (!i40e_setup_channel(pf, vsi, ch)) {
6583 		dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6584 		return -EINVAL;
6585 	}
6586 
6587 	dev_info(&pf->pdev->dev,
6588 		 "Setup channel (id:%u) utilizing num_queues %d\n",
6589 		 ch->seid, ch->num_queue_pairs);
6590 
6591 	/* configure VSI for BW limit */
6592 	if (ch->max_tx_rate) {
6593 		u64 credits = ch->max_tx_rate;
6594 
6595 		if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6596 			return -EINVAL;
6597 
6598 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
6599 		dev_dbg(&pf->pdev->dev,
6600 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6601 			ch->max_tx_rate,
6602 			credits,
6603 			ch->seid);
6604 	}
6605 
6606 	/* in case of VF, this will be main SRIOV VSI */
6607 	ch->parent_vsi = vsi;
6608 
6609 	/* and update main_vsi's count for queue_available to use */
6610 	vsi->cnt_q_avail -= ch->num_queue_pairs;
6611 
6612 	return 0;
6613 }
6614 
6615 /**
6616  * i40e_configure_queue_channels - Add queue channel for the given TCs
6617  * @vsi: VSI to be configured
6618  *
6619  * Configures queue channel mapping to the given TCs
6620  **/
6621 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6622 {
6623 	struct i40e_channel *ch;
6624 	u64 max_rate = 0;
6625 	int ret = 0, i;
6626 
6627 	/* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6628 	vsi->tc_seid_map[0] = vsi->seid;
6629 	for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6630 		if (vsi->tc_config.enabled_tc & BIT(i)) {
6631 			ch = kzalloc(sizeof(*ch), GFP_KERNEL);
6632 			if (!ch) {
6633 				ret = -ENOMEM;
6634 				goto err_free;
6635 			}
6636 
6637 			INIT_LIST_HEAD(&ch->list);
6638 			ch->num_queue_pairs =
6639 				vsi->tc_config.tc_info[i].qcount;
6640 			ch->base_queue =
6641 				vsi->tc_config.tc_info[i].qoffset;
6642 
6643 			/* Bandwidth limit through tc interface is in bytes/s,
6644 			 * change to Mbit/s
6645 			 */
6646 			max_rate = vsi->mqprio_qopt.max_rate[i];
6647 			do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6648 			ch->max_tx_rate = max_rate;
6649 
6650 			list_add_tail(&ch->list, &vsi->ch_list);
6651 
6652 			ret = i40e_create_queue_channel(vsi, ch);
6653 			if (ret) {
6654 				dev_err(&vsi->back->pdev->dev,
6655 					"Failed creating queue channel with TC%d: queues %d\n",
6656 					i, ch->num_queue_pairs);
6657 				goto err_free;
6658 			}
6659 			vsi->tc_seid_map[i] = ch->seid;
6660 		}
6661 	}
6662 
6663 	/* reset to reconfigure TX queue contexts */
6664 	i40e_do_reset(vsi->back, I40E_PF_RESET_FLAG, true);
6665 	return ret;
6666 
6667 err_free:
6668 	i40e_remove_queue_channels(vsi);
6669 	return ret;
6670 }
6671 
6672 /**
6673  * i40e_veb_config_tc - Configure TCs for given VEB
6674  * @veb: given VEB
6675  * @enabled_tc: TC bitmap
6676  *
6677  * Configures given TC bitmap for VEB (switching) element
6678  **/
6679 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6680 {
6681 	struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6682 	struct i40e_pf *pf = veb->pf;
6683 	int ret = 0;
6684 	int i;
6685 
6686 	/* No TCs or already enabled TCs just return */
6687 	if (!enabled_tc || veb->enabled_tc == enabled_tc)
6688 		return ret;
6689 
6690 	bw_data.tc_valid_bits = enabled_tc;
6691 	/* bw_data.absolute_credits is not set (relative) */
6692 
6693 	/* Enable ETS TCs with equal BW Share for now */
6694 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6695 		if (enabled_tc & BIT(i))
6696 			bw_data.tc_bw_share_credits[i] = 1;
6697 	}
6698 
6699 	ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6700 						   &bw_data, NULL);
6701 	if (ret) {
6702 		dev_info(&pf->pdev->dev,
6703 			 "VEB bw config failed, err %s aq_err %s\n",
6704 			 i40e_stat_str(&pf->hw, ret),
6705 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6706 		goto out;
6707 	}
6708 
6709 	/* Update the BW information */
6710 	ret = i40e_veb_get_bw_info(veb);
6711 	if (ret) {
6712 		dev_info(&pf->pdev->dev,
6713 			 "Failed getting veb bw config, err %s aq_err %s\n",
6714 			 i40e_stat_str(&pf->hw, ret),
6715 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6716 	}
6717 
6718 out:
6719 	return ret;
6720 }
6721 
6722 #ifdef CONFIG_I40E_DCB
6723 /**
6724  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6725  * @pf: PF struct
6726  *
6727  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6728  * the caller would've quiesce all the VSIs before calling
6729  * this function
6730  **/
6731 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6732 {
6733 	u8 tc_map = 0;
6734 	int ret;
6735 	u8 v;
6736 
6737 	/* Enable the TCs available on PF to all VEBs */
6738 	tc_map = i40e_pf_get_tc_map(pf);
6739 	if (tc_map == I40E_DEFAULT_TRAFFIC_CLASS)
6740 		return;
6741 
6742 	for (v = 0; v < I40E_MAX_VEB; v++) {
6743 		if (!pf->veb[v])
6744 			continue;
6745 		ret = i40e_veb_config_tc(pf->veb[v], tc_map);
6746 		if (ret) {
6747 			dev_info(&pf->pdev->dev,
6748 				 "Failed configuring TC for VEB seid=%d\n",
6749 				 pf->veb[v]->seid);
6750 			/* Will try to configure as many components */
6751 		}
6752 	}
6753 
6754 	/* Update each VSI */
6755 	for (v = 0; v < pf->num_alloc_vsi; v++) {
6756 		if (!pf->vsi[v])
6757 			continue;
6758 
6759 		/* - Enable all TCs for the LAN VSI
6760 		 * - For all others keep them at TC0 for now
6761 		 */
6762 		if (v == pf->lan_vsi)
6763 			tc_map = i40e_pf_get_tc_map(pf);
6764 		else
6765 			tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6766 
6767 		ret = i40e_vsi_config_tc(pf->vsi[v], tc_map);
6768 		if (ret) {
6769 			dev_info(&pf->pdev->dev,
6770 				 "Failed configuring TC for VSI seid=%d\n",
6771 				 pf->vsi[v]->seid);
6772 			/* Will try to configure as many components */
6773 		} else {
6774 			/* Re-configure VSI vectors based on updated TC map */
6775 			i40e_vsi_map_rings_to_vectors(pf->vsi[v]);
6776 			if (pf->vsi[v]->netdev)
6777 				i40e_dcbnl_set_all(pf->vsi[v]);
6778 		}
6779 	}
6780 }
6781 
6782 /**
6783  * i40e_resume_port_tx - Resume port Tx
6784  * @pf: PF struct
6785  *
6786  * Resume a port's Tx and issue a PF reset in case of failure to
6787  * resume.
6788  **/
6789 static int i40e_resume_port_tx(struct i40e_pf *pf)
6790 {
6791 	struct i40e_hw *hw = &pf->hw;
6792 	int ret;
6793 
6794 	ret = i40e_aq_resume_port_tx(hw, NULL);
6795 	if (ret) {
6796 		dev_info(&pf->pdev->dev,
6797 			 "Resume Port Tx failed, err %s aq_err %s\n",
6798 			  i40e_stat_str(&pf->hw, ret),
6799 			  i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6800 		/* Schedule PF reset to recover */
6801 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6802 		i40e_service_event_schedule(pf);
6803 	}
6804 
6805 	return ret;
6806 }
6807 
6808 /**
6809  * i40e_suspend_port_tx - Suspend port Tx
6810  * @pf: PF struct
6811  *
6812  * Suspend a port's Tx and issue a PF reset in case of failure.
6813  **/
6814 static int i40e_suspend_port_tx(struct i40e_pf *pf)
6815 {
6816 	struct i40e_hw *hw = &pf->hw;
6817 	int ret;
6818 
6819 	ret = i40e_aq_suspend_port_tx(hw, pf->mac_seid, NULL);
6820 	if (ret) {
6821 		dev_info(&pf->pdev->dev,
6822 			 "Suspend Port Tx failed, err %s aq_err %s\n",
6823 			 i40e_stat_str(&pf->hw, ret),
6824 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6825 		/* Schedule PF reset to recover */
6826 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6827 		i40e_service_event_schedule(pf);
6828 	}
6829 
6830 	return ret;
6831 }
6832 
6833 /**
6834  * i40e_hw_set_dcb_config - Program new DCBX settings into HW
6835  * @pf: PF being configured
6836  * @new_cfg: New DCBX configuration
6837  *
6838  * Program DCB settings into HW and reconfigure VEB/VSIs on
6839  * given PF. Uses "Set LLDP MIB" AQC to program the hardware.
6840  **/
6841 static int i40e_hw_set_dcb_config(struct i40e_pf *pf,
6842 				  struct i40e_dcbx_config *new_cfg)
6843 {
6844 	struct i40e_dcbx_config *old_cfg = &pf->hw.local_dcbx_config;
6845 	int ret;
6846 
6847 	/* Check if need reconfiguration */
6848 	if (!memcmp(&new_cfg, &old_cfg, sizeof(new_cfg))) {
6849 		dev_dbg(&pf->pdev->dev, "No Change in DCB Config required.\n");
6850 		return 0;
6851 	}
6852 
6853 	/* Config change disable all VSIs */
6854 	i40e_pf_quiesce_all_vsi(pf);
6855 
6856 	/* Copy the new config to the current config */
6857 	*old_cfg = *new_cfg;
6858 	old_cfg->etsrec = old_cfg->etscfg;
6859 	ret = i40e_set_dcb_config(&pf->hw);
6860 	if (ret) {
6861 		dev_info(&pf->pdev->dev,
6862 			 "Set DCB Config failed, err %s aq_err %s\n",
6863 			 i40e_stat_str(&pf->hw, ret),
6864 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6865 		goto out;
6866 	}
6867 
6868 	/* Changes in configuration update VEB/VSI */
6869 	i40e_dcb_reconfigure(pf);
6870 out:
6871 	/* In case of reset do not try to resume anything */
6872 	if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
6873 		/* Re-start the VSIs if disabled */
6874 		ret = i40e_resume_port_tx(pf);
6875 		/* In case of error no point in resuming VSIs */
6876 		if (ret)
6877 			goto err;
6878 		i40e_pf_unquiesce_all_vsi(pf);
6879 	}
6880 err:
6881 	return ret;
6882 }
6883 
6884 /**
6885  * i40e_hw_dcb_config - Program new DCBX settings into HW
6886  * @pf: PF being configured
6887  * @new_cfg: New DCBX configuration
6888  *
6889  * Program DCB settings into HW and reconfigure VEB/VSIs on
6890  * given PF
6891  **/
6892 int i40e_hw_dcb_config(struct i40e_pf *pf, struct i40e_dcbx_config *new_cfg)
6893 {
6894 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6895 	u8 prio_type[I40E_MAX_TRAFFIC_CLASS] = {0};
6896 	u32 mfs_tc[I40E_MAX_TRAFFIC_CLASS];
6897 	struct i40e_dcbx_config *old_cfg;
6898 	u8 mode[I40E_MAX_TRAFFIC_CLASS];
6899 	struct i40e_rx_pb_config pb_cfg;
6900 	struct i40e_hw *hw = &pf->hw;
6901 	u8 num_ports = hw->num_ports;
6902 	bool need_reconfig;
6903 	int ret = -EINVAL;
6904 	u8 lltc_map = 0;
6905 	u8 tc_map = 0;
6906 	u8 new_numtc;
6907 	u8 i;
6908 
6909 	dev_dbg(&pf->pdev->dev, "Configuring DCB registers directly\n");
6910 	/* Un-pack information to Program ETS HW via shared API
6911 	 * numtc, tcmap
6912 	 * LLTC map
6913 	 * ETS/NON-ETS arbiter mode
6914 	 * max exponent (credit refills)
6915 	 * Total number of ports
6916 	 * PFC priority bit-map
6917 	 * Priority Table
6918 	 * BW % per TC
6919 	 * Arbiter mode between UPs sharing same TC
6920 	 * TSA table (ETS or non-ETS)
6921 	 * EEE enabled or not
6922 	 * MFS TC table
6923 	 */
6924 
6925 	new_numtc = i40e_dcb_get_num_tc(new_cfg);
6926 
6927 	memset(&ets_data, 0, sizeof(ets_data));
6928 	for (i = 0; i < new_numtc; i++) {
6929 		tc_map |= BIT(i);
6930 		switch (new_cfg->etscfg.tsatable[i]) {
6931 		case I40E_IEEE_TSA_ETS:
6932 			prio_type[i] = I40E_DCB_PRIO_TYPE_ETS;
6933 			ets_data.tc_bw_share_credits[i] =
6934 					new_cfg->etscfg.tcbwtable[i];
6935 			break;
6936 		case I40E_IEEE_TSA_STRICT:
6937 			prio_type[i] = I40E_DCB_PRIO_TYPE_STRICT;
6938 			lltc_map |= BIT(i);
6939 			ets_data.tc_bw_share_credits[i] =
6940 					I40E_DCB_STRICT_PRIO_CREDITS;
6941 			break;
6942 		default:
6943 			/* Invalid TSA type */
6944 			need_reconfig = false;
6945 			goto out;
6946 		}
6947 	}
6948 
6949 	old_cfg = &hw->local_dcbx_config;
6950 	/* Check if need reconfiguration */
6951 	need_reconfig = i40e_dcb_need_reconfig(pf, old_cfg, new_cfg);
6952 
6953 	/* If needed, enable/disable frame tagging, disable all VSIs
6954 	 * and suspend port tx
6955 	 */
6956 	if (need_reconfig) {
6957 		/* Enable DCB tagging only when more than one TC */
6958 		if (new_numtc > 1)
6959 			pf->flags |= I40E_FLAG_DCB_ENABLED;
6960 		else
6961 			pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6962 
6963 		set_bit(__I40E_PORT_SUSPENDED, pf->state);
6964 		/* Reconfiguration needed quiesce all VSIs */
6965 		i40e_pf_quiesce_all_vsi(pf);
6966 		ret = i40e_suspend_port_tx(pf);
6967 		if (ret)
6968 			goto err;
6969 	}
6970 
6971 	/* Configure Port ETS Tx Scheduler */
6972 	ets_data.tc_valid_bits = tc_map;
6973 	ets_data.tc_strict_priority_flags = lltc_map;
6974 	ret = i40e_aq_config_switch_comp_ets
6975 		(hw, pf->mac_seid, &ets_data,
6976 		 i40e_aqc_opc_modify_switching_comp_ets, NULL);
6977 	if (ret) {
6978 		dev_info(&pf->pdev->dev,
6979 			 "Modify Port ETS failed, err %s aq_err %s\n",
6980 			 i40e_stat_str(&pf->hw, ret),
6981 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6982 		goto out;
6983 	}
6984 
6985 	/* Configure Rx ETS HW */
6986 	memset(&mode, I40E_DCB_ARB_MODE_ROUND_ROBIN, sizeof(mode));
6987 	i40e_dcb_hw_set_num_tc(hw, new_numtc);
6988 	i40e_dcb_hw_rx_fifo_config(hw, I40E_DCB_ARB_MODE_ROUND_ROBIN,
6989 				   I40E_DCB_ARB_MODE_STRICT_PRIORITY,
6990 				   I40E_DCB_DEFAULT_MAX_EXPONENT,
6991 				   lltc_map);
6992 	i40e_dcb_hw_rx_cmd_monitor_config(hw, new_numtc, num_ports);
6993 	i40e_dcb_hw_rx_ets_bw_config(hw, new_cfg->etscfg.tcbwtable, mode,
6994 				     prio_type);
6995 	i40e_dcb_hw_pfc_config(hw, new_cfg->pfc.pfcenable,
6996 			       new_cfg->etscfg.prioritytable);
6997 	i40e_dcb_hw_rx_up2tc_config(hw, new_cfg->etscfg.prioritytable);
6998 
6999 	/* Configure Rx Packet Buffers in HW */
7000 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7001 		mfs_tc[i] = pf->vsi[pf->lan_vsi]->netdev->mtu;
7002 		mfs_tc[i] += I40E_PACKET_HDR_PAD;
7003 	}
7004 
7005 	i40e_dcb_hw_calculate_pool_sizes(hw, num_ports,
7006 					 false, new_cfg->pfc.pfcenable,
7007 					 mfs_tc, &pb_cfg);
7008 	i40e_dcb_hw_rx_pb_config(hw, &pf->pb_cfg, &pb_cfg);
7009 
7010 	/* Update the local Rx Packet buffer config */
7011 	pf->pb_cfg = pb_cfg;
7012 
7013 	/* Inform the FW about changes to DCB configuration */
7014 	ret = i40e_aq_dcb_updated(&pf->hw, NULL);
7015 	if (ret) {
7016 		dev_info(&pf->pdev->dev,
7017 			 "DCB Updated failed, err %s aq_err %s\n",
7018 			 i40e_stat_str(&pf->hw, ret),
7019 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7020 		goto out;
7021 	}
7022 
7023 	/* Update the port DCBx configuration */
7024 	*old_cfg = *new_cfg;
7025 
7026 	/* Changes in configuration update VEB/VSI */
7027 	i40e_dcb_reconfigure(pf);
7028 out:
7029 	/* Re-start the VSIs if disabled */
7030 	if (need_reconfig) {
7031 		ret = i40e_resume_port_tx(pf);
7032 
7033 		clear_bit(__I40E_PORT_SUSPENDED, pf->state);
7034 		/* In case of error no point in resuming VSIs */
7035 		if (ret)
7036 			goto err;
7037 
7038 		/* Wait for the PF's queues to be disabled */
7039 		ret = i40e_pf_wait_queues_disabled(pf);
7040 		if (ret) {
7041 			/* Schedule PF reset to recover */
7042 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
7043 			i40e_service_event_schedule(pf);
7044 			goto err;
7045 		} else {
7046 			i40e_pf_unquiesce_all_vsi(pf);
7047 			set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7048 			set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
7049 		}
7050 		/* registers are set, lets apply */
7051 		if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB)
7052 			ret = i40e_hw_set_dcb_config(pf, new_cfg);
7053 	}
7054 
7055 err:
7056 	return ret;
7057 }
7058 
7059 /**
7060  * i40e_dcb_sw_default_config - Set default DCB configuration when DCB in SW
7061  * @pf: PF being queried
7062  *
7063  * Set default DCB configuration in case DCB is to be done in SW.
7064  **/
7065 int i40e_dcb_sw_default_config(struct i40e_pf *pf)
7066 {
7067 	struct i40e_dcbx_config *dcb_cfg = &pf->hw.local_dcbx_config;
7068 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
7069 	struct i40e_hw *hw = &pf->hw;
7070 	int err;
7071 
7072 	if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB) {
7073 		/* Update the local cached instance with TC0 ETS */
7074 		memset(&pf->tmp_cfg, 0, sizeof(struct i40e_dcbx_config));
7075 		pf->tmp_cfg.etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7076 		pf->tmp_cfg.etscfg.maxtcs = 0;
7077 		pf->tmp_cfg.etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7078 		pf->tmp_cfg.etscfg.tsatable[0] = I40E_IEEE_TSA_ETS;
7079 		pf->tmp_cfg.pfc.willing = I40E_IEEE_DEFAULT_PFC_WILLING;
7080 		pf->tmp_cfg.pfc.pfccap = I40E_MAX_TRAFFIC_CLASS;
7081 		/* FW needs one App to configure HW */
7082 		pf->tmp_cfg.numapps = I40E_IEEE_DEFAULT_NUM_APPS;
7083 		pf->tmp_cfg.app[0].selector = I40E_APP_SEL_ETHTYPE;
7084 		pf->tmp_cfg.app[0].priority = I40E_IEEE_DEFAULT_APP_PRIO;
7085 		pf->tmp_cfg.app[0].protocolid = I40E_APP_PROTOID_FCOE;
7086 
7087 		return i40e_hw_set_dcb_config(pf, &pf->tmp_cfg);
7088 	}
7089 
7090 	memset(&ets_data, 0, sizeof(ets_data));
7091 	ets_data.tc_valid_bits = I40E_DEFAULT_TRAFFIC_CLASS; /* TC0 only */
7092 	ets_data.tc_strict_priority_flags = 0; /* ETS */
7093 	ets_data.tc_bw_share_credits[0] = I40E_IEEE_DEFAULT_ETS_TCBW; /* 100% to TC0 */
7094 
7095 	/* Enable ETS on the Physical port */
7096 	err = i40e_aq_config_switch_comp_ets
7097 		(hw, pf->mac_seid, &ets_data,
7098 		 i40e_aqc_opc_enable_switching_comp_ets, NULL);
7099 	if (err) {
7100 		dev_info(&pf->pdev->dev,
7101 			 "Enable Port ETS failed, err %s aq_err %s\n",
7102 			 i40e_stat_str(&pf->hw, err),
7103 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7104 		err = -ENOENT;
7105 		goto out;
7106 	}
7107 
7108 	/* Update the local cached instance with TC0 ETS */
7109 	dcb_cfg->etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7110 	dcb_cfg->etscfg.cbs = 0;
7111 	dcb_cfg->etscfg.maxtcs = I40E_MAX_TRAFFIC_CLASS;
7112 	dcb_cfg->etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7113 
7114 out:
7115 	return err;
7116 }
7117 
7118 /**
7119  * i40e_init_pf_dcb - Initialize DCB configuration
7120  * @pf: PF being configured
7121  *
7122  * Query the current DCB configuration and cache it
7123  * in the hardware structure
7124  **/
7125 static int i40e_init_pf_dcb(struct i40e_pf *pf)
7126 {
7127 	struct i40e_hw *hw = &pf->hw;
7128 	int err;
7129 
7130 	/* Do not enable DCB for SW1 and SW2 images even if the FW is capable
7131 	 * Also do not enable DCBx if FW LLDP agent is disabled
7132 	 */
7133 	if (pf->hw_features & I40E_HW_NO_DCB_SUPPORT) {
7134 		dev_info(&pf->pdev->dev, "DCB is not supported.\n");
7135 		err = I40E_NOT_SUPPORTED;
7136 		goto out;
7137 	}
7138 	if (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) {
7139 		dev_info(&pf->pdev->dev, "FW LLDP is disabled, attempting SW DCB\n");
7140 		err = i40e_dcb_sw_default_config(pf);
7141 		if (err) {
7142 			dev_info(&pf->pdev->dev, "Could not initialize SW DCB\n");
7143 			goto out;
7144 		}
7145 		dev_info(&pf->pdev->dev, "SW DCB initialization succeeded.\n");
7146 		pf->dcbx_cap = DCB_CAP_DCBX_HOST |
7147 			       DCB_CAP_DCBX_VER_IEEE;
7148 		/* at init capable but disabled */
7149 		pf->flags |= I40E_FLAG_DCB_CAPABLE;
7150 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7151 		goto out;
7152 	}
7153 	err = i40e_init_dcb(hw, true);
7154 	if (!err) {
7155 		/* Device/Function is not DCBX capable */
7156 		if ((!hw->func_caps.dcb) ||
7157 		    (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
7158 			dev_info(&pf->pdev->dev,
7159 				 "DCBX offload is not supported or is disabled for this PF.\n");
7160 		} else {
7161 			/* When status is not DISABLED then DCBX in FW */
7162 			pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
7163 				       DCB_CAP_DCBX_VER_IEEE;
7164 
7165 			pf->flags |= I40E_FLAG_DCB_CAPABLE;
7166 			/* Enable DCB tagging only when more than one TC
7167 			 * or explicitly disable if only one TC
7168 			 */
7169 			if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
7170 				pf->flags |= I40E_FLAG_DCB_ENABLED;
7171 			else
7172 				pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7173 			dev_dbg(&pf->pdev->dev,
7174 				"DCBX offload is supported for this PF.\n");
7175 		}
7176 	} else if (pf->hw.aq.asq_last_status == I40E_AQ_RC_EPERM) {
7177 		dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
7178 		pf->flags |= I40E_FLAG_DISABLE_FW_LLDP;
7179 	} else {
7180 		dev_info(&pf->pdev->dev,
7181 			 "Query for DCB configuration failed, err %s aq_err %s\n",
7182 			 i40e_stat_str(&pf->hw, err),
7183 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7184 	}
7185 
7186 out:
7187 	return err;
7188 }
7189 #endif /* CONFIG_I40E_DCB */
7190 
7191 /**
7192  * i40e_print_link_message - print link up or down
7193  * @vsi: the VSI for which link needs a message
7194  * @isup: true of link is up, false otherwise
7195  */
7196 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
7197 {
7198 	enum i40e_aq_link_speed new_speed;
7199 	struct i40e_pf *pf = vsi->back;
7200 	char *speed = "Unknown";
7201 	char *fc = "Unknown";
7202 	char *fec = "";
7203 	char *req_fec = "";
7204 	char *an = "";
7205 
7206 	if (isup)
7207 		new_speed = pf->hw.phy.link_info.link_speed;
7208 	else
7209 		new_speed = I40E_LINK_SPEED_UNKNOWN;
7210 
7211 	if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
7212 		return;
7213 	vsi->current_isup = isup;
7214 	vsi->current_speed = new_speed;
7215 	if (!isup) {
7216 		netdev_info(vsi->netdev, "NIC Link is Down\n");
7217 		return;
7218 	}
7219 
7220 	/* Warn user if link speed on NPAR enabled partition is not at
7221 	 * least 10GB
7222 	 */
7223 	if (pf->hw.func_caps.npar_enable &&
7224 	    (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
7225 	     pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
7226 		netdev_warn(vsi->netdev,
7227 			    "The partition detected link speed that is less than 10Gbps\n");
7228 
7229 	switch (pf->hw.phy.link_info.link_speed) {
7230 	case I40E_LINK_SPEED_40GB:
7231 		speed = "40 G";
7232 		break;
7233 	case I40E_LINK_SPEED_20GB:
7234 		speed = "20 G";
7235 		break;
7236 	case I40E_LINK_SPEED_25GB:
7237 		speed = "25 G";
7238 		break;
7239 	case I40E_LINK_SPEED_10GB:
7240 		speed = "10 G";
7241 		break;
7242 	case I40E_LINK_SPEED_5GB:
7243 		speed = "5 G";
7244 		break;
7245 	case I40E_LINK_SPEED_2_5GB:
7246 		speed = "2.5 G";
7247 		break;
7248 	case I40E_LINK_SPEED_1GB:
7249 		speed = "1000 M";
7250 		break;
7251 	case I40E_LINK_SPEED_100MB:
7252 		speed = "100 M";
7253 		break;
7254 	default:
7255 		break;
7256 	}
7257 
7258 	switch (pf->hw.fc.current_mode) {
7259 	case I40E_FC_FULL:
7260 		fc = "RX/TX";
7261 		break;
7262 	case I40E_FC_TX_PAUSE:
7263 		fc = "TX";
7264 		break;
7265 	case I40E_FC_RX_PAUSE:
7266 		fc = "RX";
7267 		break;
7268 	default:
7269 		fc = "None";
7270 		break;
7271 	}
7272 
7273 	if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
7274 		req_fec = "None";
7275 		fec = "None";
7276 		an = "False";
7277 
7278 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7279 			an = "True";
7280 
7281 		if (pf->hw.phy.link_info.fec_info &
7282 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7283 			fec = "CL74 FC-FEC/BASE-R";
7284 		else if (pf->hw.phy.link_info.fec_info &
7285 			 I40E_AQ_CONFIG_FEC_RS_ENA)
7286 			fec = "CL108 RS-FEC";
7287 
7288 		/* 'CL108 RS-FEC' should be displayed when RS is requested, or
7289 		 * both RS and FC are requested
7290 		 */
7291 		if (vsi->back->hw.phy.link_info.req_fec_info &
7292 		    (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
7293 			if (vsi->back->hw.phy.link_info.req_fec_info &
7294 			    I40E_AQ_REQUEST_FEC_RS)
7295 				req_fec = "CL108 RS-FEC";
7296 			else
7297 				req_fec = "CL74 FC-FEC/BASE-R";
7298 		}
7299 		netdev_info(vsi->netdev,
7300 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7301 			    speed, req_fec, fec, an, fc);
7302 	} else if (pf->hw.device_id == I40E_DEV_ID_KX_X722) {
7303 		req_fec = "None";
7304 		fec = "None";
7305 		an = "False";
7306 
7307 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7308 			an = "True";
7309 
7310 		if (pf->hw.phy.link_info.fec_info &
7311 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7312 			fec = "CL74 FC-FEC/BASE-R";
7313 
7314 		if (pf->hw.phy.link_info.req_fec_info &
7315 		    I40E_AQ_REQUEST_FEC_KR)
7316 			req_fec = "CL74 FC-FEC/BASE-R";
7317 
7318 		netdev_info(vsi->netdev,
7319 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7320 			    speed, req_fec, fec, an, fc);
7321 	} else {
7322 		netdev_info(vsi->netdev,
7323 			    "NIC Link is Up, %sbps Full Duplex, Flow Control: %s\n",
7324 			    speed, fc);
7325 	}
7326 
7327 }
7328 
7329 /**
7330  * i40e_up_complete - Finish the last steps of bringing up a connection
7331  * @vsi: the VSI being configured
7332  **/
7333 static int i40e_up_complete(struct i40e_vsi *vsi)
7334 {
7335 	struct i40e_pf *pf = vsi->back;
7336 	int err;
7337 
7338 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
7339 		i40e_vsi_configure_msix(vsi);
7340 	else
7341 		i40e_configure_msi_and_legacy(vsi);
7342 
7343 	/* start rings */
7344 	err = i40e_vsi_start_rings(vsi);
7345 	if (err)
7346 		return err;
7347 
7348 	clear_bit(__I40E_VSI_DOWN, vsi->state);
7349 	i40e_napi_enable_all(vsi);
7350 	i40e_vsi_enable_irq(vsi);
7351 
7352 	if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
7353 	    (vsi->netdev)) {
7354 		i40e_print_link_message(vsi, true);
7355 		netif_tx_start_all_queues(vsi->netdev);
7356 		netif_carrier_on(vsi->netdev);
7357 	}
7358 
7359 	/* replay FDIR SB filters */
7360 	if (vsi->type == I40E_VSI_FDIR) {
7361 		/* reset fd counters */
7362 		pf->fd_add_err = 0;
7363 		pf->fd_atr_cnt = 0;
7364 		i40e_fdir_filter_restore(vsi);
7365 	}
7366 
7367 	/* On the next run of the service_task, notify any clients of the new
7368 	 * opened netdev
7369 	 */
7370 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7371 	i40e_service_event_schedule(pf);
7372 
7373 	return 0;
7374 }
7375 
7376 /**
7377  * i40e_vsi_reinit_locked - Reset the VSI
7378  * @vsi: the VSI being configured
7379  *
7380  * Rebuild the ring structs after some configuration
7381  * has changed, e.g. MTU size.
7382  **/
7383 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
7384 {
7385 	struct i40e_pf *pf = vsi->back;
7386 
7387 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
7388 		usleep_range(1000, 2000);
7389 	i40e_down(vsi);
7390 
7391 	i40e_up(vsi);
7392 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
7393 }
7394 
7395 /**
7396  * i40e_force_link_state - Force the link status
7397  * @pf: board private structure
7398  * @is_up: whether the link state should be forced up or down
7399  **/
7400 static i40e_status i40e_force_link_state(struct i40e_pf *pf, bool is_up)
7401 {
7402 	struct i40e_aq_get_phy_abilities_resp abilities;
7403 	struct i40e_aq_set_phy_config config = {0};
7404 	bool non_zero_phy_type = is_up;
7405 	struct i40e_hw *hw = &pf->hw;
7406 	i40e_status err;
7407 	u64 mask;
7408 	u8 speed;
7409 
7410 	/* Card might've been put in an unstable state by other drivers
7411 	 * and applications, which causes incorrect speed values being
7412 	 * set on startup. In order to clear speed registers, we call
7413 	 * get_phy_capabilities twice, once to get initial state of
7414 	 * available speeds, and once to get current PHY config.
7415 	 */
7416 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
7417 					   NULL);
7418 	if (err) {
7419 		dev_err(&pf->pdev->dev,
7420 			"failed to get phy cap., ret =  %s last_status =  %s\n",
7421 			i40e_stat_str(hw, err),
7422 			i40e_aq_str(hw, hw->aq.asq_last_status));
7423 		return err;
7424 	}
7425 	speed = abilities.link_speed;
7426 
7427 	/* Get the current phy config */
7428 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
7429 					   NULL);
7430 	if (err) {
7431 		dev_err(&pf->pdev->dev,
7432 			"failed to get phy cap., ret =  %s last_status =  %s\n",
7433 			i40e_stat_str(hw, err),
7434 			i40e_aq_str(hw, hw->aq.asq_last_status));
7435 		return err;
7436 	}
7437 
7438 	/* If link needs to go up, but was not forced to go down,
7439 	 * and its speed values are OK, no need for a flap
7440 	 * if non_zero_phy_type was set, still need to force up
7441 	 */
7442 	if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED)
7443 		non_zero_phy_type = true;
7444 	else if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
7445 		return I40E_SUCCESS;
7446 
7447 	/* To force link we need to set bits for all supported PHY types,
7448 	 * but there are now more than 32, so we need to split the bitmap
7449 	 * across two fields.
7450 	 */
7451 	mask = I40E_PHY_TYPES_BITMASK;
7452 	config.phy_type =
7453 		non_zero_phy_type ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
7454 	config.phy_type_ext =
7455 		non_zero_phy_type ? (u8)((mask >> 32) & 0xff) : 0;
7456 	/* Copy the old settings, except of phy_type */
7457 	config.abilities = abilities.abilities;
7458 	if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED) {
7459 		if (is_up)
7460 			config.abilities |= I40E_AQ_PHY_ENABLE_LINK;
7461 		else
7462 			config.abilities &= ~(I40E_AQ_PHY_ENABLE_LINK);
7463 	}
7464 	if (abilities.link_speed != 0)
7465 		config.link_speed = abilities.link_speed;
7466 	else
7467 		config.link_speed = speed;
7468 	config.eee_capability = abilities.eee_capability;
7469 	config.eeer = abilities.eeer_val;
7470 	config.low_power_ctrl = abilities.d3_lpan;
7471 	config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
7472 			    I40E_AQ_PHY_FEC_CONFIG_MASK;
7473 	err = i40e_aq_set_phy_config(hw, &config, NULL);
7474 
7475 	if (err) {
7476 		dev_err(&pf->pdev->dev,
7477 			"set phy config ret =  %s last_status =  %s\n",
7478 			i40e_stat_str(&pf->hw, err),
7479 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7480 		return err;
7481 	}
7482 
7483 	/* Update the link info */
7484 	err = i40e_update_link_info(hw);
7485 	if (err) {
7486 		/* Wait a little bit (on 40G cards it sometimes takes a really
7487 		 * long time for link to come back from the atomic reset)
7488 		 * and try once more
7489 		 */
7490 		msleep(1000);
7491 		i40e_update_link_info(hw);
7492 	}
7493 
7494 	i40e_aq_set_link_restart_an(hw, is_up, NULL);
7495 
7496 	return I40E_SUCCESS;
7497 }
7498 
7499 /**
7500  * i40e_up - Bring the connection back up after being down
7501  * @vsi: the VSI being configured
7502  **/
7503 int i40e_up(struct i40e_vsi *vsi)
7504 {
7505 	int err;
7506 
7507 	if (vsi->type == I40E_VSI_MAIN &&
7508 	    (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7509 	     vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7510 		i40e_force_link_state(vsi->back, true);
7511 
7512 	err = i40e_vsi_configure(vsi);
7513 	if (!err)
7514 		err = i40e_up_complete(vsi);
7515 
7516 	return err;
7517 }
7518 
7519 /**
7520  * i40e_down - Shutdown the connection processing
7521  * @vsi: the VSI being stopped
7522  **/
7523 void i40e_down(struct i40e_vsi *vsi)
7524 {
7525 	int i;
7526 
7527 	/* It is assumed that the caller of this function
7528 	 * sets the vsi->state __I40E_VSI_DOWN bit.
7529 	 */
7530 	if (vsi->netdev) {
7531 		netif_carrier_off(vsi->netdev);
7532 		netif_tx_disable(vsi->netdev);
7533 	}
7534 	i40e_vsi_disable_irq(vsi);
7535 	i40e_vsi_stop_rings(vsi);
7536 	if (vsi->type == I40E_VSI_MAIN &&
7537 	   (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7538 	    vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7539 		i40e_force_link_state(vsi->back, false);
7540 	i40e_napi_disable_all(vsi);
7541 
7542 	for (i = 0; i < vsi->num_queue_pairs; i++) {
7543 		i40e_clean_tx_ring(vsi->tx_rings[i]);
7544 		if (i40e_enabled_xdp_vsi(vsi)) {
7545 			/* Make sure that in-progress ndo_xdp_xmit and
7546 			 * ndo_xsk_wakeup calls are completed.
7547 			 */
7548 			synchronize_rcu();
7549 			i40e_clean_tx_ring(vsi->xdp_rings[i]);
7550 		}
7551 		i40e_clean_rx_ring(vsi->rx_rings[i]);
7552 	}
7553 
7554 }
7555 
7556 /**
7557  * i40e_validate_mqprio_qopt- validate queue mapping info
7558  * @vsi: the VSI being configured
7559  * @mqprio_qopt: queue parametrs
7560  **/
7561 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
7562 				     struct tc_mqprio_qopt_offload *mqprio_qopt)
7563 {
7564 	u64 sum_max_rate = 0;
7565 	u64 max_rate = 0;
7566 	int i;
7567 
7568 	if (mqprio_qopt->qopt.offset[0] != 0 ||
7569 	    mqprio_qopt->qopt.num_tc < 1 ||
7570 	    mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
7571 		return -EINVAL;
7572 	for (i = 0; ; i++) {
7573 		if (!mqprio_qopt->qopt.count[i])
7574 			return -EINVAL;
7575 		if (mqprio_qopt->min_rate[i]) {
7576 			dev_err(&vsi->back->pdev->dev,
7577 				"Invalid min tx rate (greater than 0) specified\n");
7578 			return -EINVAL;
7579 		}
7580 		max_rate = mqprio_qopt->max_rate[i];
7581 		do_div(max_rate, I40E_BW_MBPS_DIVISOR);
7582 		sum_max_rate += max_rate;
7583 
7584 		if (i >= mqprio_qopt->qopt.num_tc - 1)
7585 			break;
7586 		if (mqprio_qopt->qopt.offset[i + 1] !=
7587 		    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7588 			return -EINVAL;
7589 	}
7590 	if (vsi->num_queue_pairs <
7591 	    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
7592 		dev_err(&vsi->back->pdev->dev,
7593 			"Failed to create traffic channel, insufficient number of queues.\n");
7594 		return -EINVAL;
7595 	}
7596 	if (sum_max_rate > i40e_get_link_speed(vsi)) {
7597 		dev_err(&vsi->back->pdev->dev,
7598 			"Invalid max tx rate specified\n");
7599 		return -EINVAL;
7600 	}
7601 	return 0;
7602 }
7603 
7604 /**
7605  * i40e_vsi_set_default_tc_config - set default values for tc configuration
7606  * @vsi: the VSI being configured
7607  **/
7608 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
7609 {
7610 	u16 qcount;
7611 	int i;
7612 
7613 	/* Only TC0 is enabled */
7614 	vsi->tc_config.numtc = 1;
7615 	vsi->tc_config.enabled_tc = 1;
7616 	qcount = min_t(int, vsi->alloc_queue_pairs,
7617 		       i40e_pf_get_max_q_per_tc(vsi->back));
7618 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7619 		/* For the TC that is not enabled set the offset to default
7620 		 * queue and allocate one queue for the given TC.
7621 		 */
7622 		vsi->tc_config.tc_info[i].qoffset = 0;
7623 		if (i == 0)
7624 			vsi->tc_config.tc_info[i].qcount = qcount;
7625 		else
7626 			vsi->tc_config.tc_info[i].qcount = 1;
7627 		vsi->tc_config.tc_info[i].netdev_tc = 0;
7628 	}
7629 }
7630 
7631 /**
7632  * i40e_del_macvlan_filter
7633  * @hw: pointer to the HW structure
7634  * @seid: seid of the channel VSI
7635  * @macaddr: the mac address to apply as a filter
7636  * @aq_err: store the admin Q error
7637  *
7638  * This function deletes a mac filter on the channel VSI which serves as the
7639  * macvlan. Returns 0 on success.
7640  **/
7641 static i40e_status i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
7642 					   const u8 *macaddr, int *aq_err)
7643 {
7644 	struct i40e_aqc_remove_macvlan_element_data element;
7645 	i40e_status status;
7646 
7647 	memset(&element, 0, sizeof(element));
7648 	ether_addr_copy(element.mac_addr, macaddr);
7649 	element.vlan_tag = 0;
7650 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
7651 	status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
7652 	*aq_err = hw->aq.asq_last_status;
7653 
7654 	return status;
7655 }
7656 
7657 /**
7658  * i40e_add_macvlan_filter
7659  * @hw: pointer to the HW structure
7660  * @seid: seid of the channel VSI
7661  * @macaddr: the mac address to apply as a filter
7662  * @aq_err: store the admin Q error
7663  *
7664  * This function adds a mac filter on the channel VSI which serves as the
7665  * macvlan. Returns 0 on success.
7666  **/
7667 static i40e_status i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
7668 					   const u8 *macaddr, int *aq_err)
7669 {
7670 	struct i40e_aqc_add_macvlan_element_data element;
7671 	i40e_status status;
7672 	u16 cmd_flags = 0;
7673 
7674 	ether_addr_copy(element.mac_addr, macaddr);
7675 	element.vlan_tag = 0;
7676 	element.queue_number = 0;
7677 	element.match_method = I40E_AQC_MM_ERR_NO_RES;
7678 	cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
7679 	element.flags = cpu_to_le16(cmd_flags);
7680 	status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
7681 	*aq_err = hw->aq.asq_last_status;
7682 
7683 	return status;
7684 }
7685 
7686 /**
7687  * i40e_reset_ch_rings - Reset the queue contexts in a channel
7688  * @vsi: the VSI we want to access
7689  * @ch: the channel we want to access
7690  */
7691 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
7692 {
7693 	struct i40e_ring *tx_ring, *rx_ring;
7694 	u16 pf_q;
7695 	int i;
7696 
7697 	for (i = 0; i < ch->num_queue_pairs; i++) {
7698 		pf_q = ch->base_queue + i;
7699 		tx_ring = vsi->tx_rings[pf_q];
7700 		tx_ring->ch = NULL;
7701 		rx_ring = vsi->rx_rings[pf_q];
7702 		rx_ring->ch = NULL;
7703 	}
7704 }
7705 
7706 /**
7707  * i40e_free_macvlan_channels
7708  * @vsi: the VSI we want to access
7709  *
7710  * This function frees the Qs of the channel VSI from
7711  * the stack and also deletes the channel VSIs which
7712  * serve as macvlans.
7713  */
7714 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
7715 {
7716 	struct i40e_channel *ch, *ch_tmp;
7717 	int ret;
7718 
7719 	if (list_empty(&vsi->macvlan_list))
7720 		return;
7721 
7722 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7723 		struct i40e_vsi *parent_vsi;
7724 
7725 		if (i40e_is_channel_macvlan(ch)) {
7726 			i40e_reset_ch_rings(vsi, ch);
7727 			clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7728 			netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
7729 			netdev_set_sb_channel(ch->fwd->netdev, 0);
7730 			kfree(ch->fwd);
7731 			ch->fwd = NULL;
7732 		}
7733 
7734 		list_del(&ch->list);
7735 		parent_vsi = ch->parent_vsi;
7736 		if (!parent_vsi || !ch->initialized) {
7737 			kfree(ch);
7738 			continue;
7739 		}
7740 
7741 		/* remove the VSI */
7742 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
7743 					     NULL);
7744 		if (ret)
7745 			dev_err(&vsi->back->pdev->dev,
7746 				"unable to remove channel (%d) for parent VSI(%d)\n",
7747 				ch->seid, parent_vsi->seid);
7748 		kfree(ch);
7749 	}
7750 	vsi->macvlan_cnt = 0;
7751 }
7752 
7753 /**
7754  * i40e_fwd_ring_up - bring the macvlan device up
7755  * @vsi: the VSI we want to access
7756  * @vdev: macvlan netdevice
7757  * @fwd: the private fwd structure
7758  */
7759 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7760 			    struct i40e_fwd_adapter *fwd)
7761 {
7762 	struct i40e_channel *ch = NULL, *ch_tmp, *iter;
7763 	int ret = 0, num_tc = 1,  i, aq_err;
7764 	struct i40e_pf *pf = vsi->back;
7765 	struct i40e_hw *hw = &pf->hw;
7766 
7767 	/* Go through the list and find an available channel */
7768 	list_for_each_entry_safe(iter, ch_tmp, &vsi->macvlan_list, list) {
7769 		if (!i40e_is_channel_macvlan(iter)) {
7770 			iter->fwd = fwd;
7771 			/* record configuration for macvlan interface in vdev */
7772 			for (i = 0; i < num_tc; i++)
7773 				netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7774 							     i,
7775 							     iter->num_queue_pairs,
7776 							     iter->base_queue);
7777 			for (i = 0; i < iter->num_queue_pairs; i++) {
7778 				struct i40e_ring *tx_ring, *rx_ring;
7779 				u16 pf_q;
7780 
7781 				pf_q = iter->base_queue + i;
7782 
7783 				/* Get to TX ring ptr */
7784 				tx_ring = vsi->tx_rings[pf_q];
7785 				tx_ring->ch = iter;
7786 
7787 				/* Get the RX ring ptr */
7788 				rx_ring = vsi->rx_rings[pf_q];
7789 				rx_ring->ch = iter;
7790 			}
7791 			ch = iter;
7792 			break;
7793 		}
7794 	}
7795 
7796 	if (!ch)
7797 		return -EINVAL;
7798 
7799 	/* Guarantee all rings are updated before we update the
7800 	 * MAC address filter.
7801 	 */
7802 	wmb();
7803 
7804 	/* Add a mac filter */
7805 	ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7806 	if (ret) {
7807 		/* if we cannot add the MAC rule then disable the offload */
7808 		macvlan_release_l2fw_offload(vdev);
7809 		for (i = 0; i < ch->num_queue_pairs; i++) {
7810 			struct i40e_ring *rx_ring;
7811 			u16 pf_q;
7812 
7813 			pf_q = ch->base_queue + i;
7814 			rx_ring = vsi->rx_rings[pf_q];
7815 			rx_ring->netdev = NULL;
7816 		}
7817 		dev_info(&pf->pdev->dev,
7818 			 "Error adding mac filter on macvlan err %s, aq_err %s\n",
7819 			  i40e_stat_str(hw, ret),
7820 			  i40e_aq_str(hw, aq_err));
7821 		netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7822 	}
7823 
7824 	return ret;
7825 }
7826 
7827 /**
7828  * i40e_setup_macvlans - create the channels which will be macvlans
7829  * @vsi: the VSI we want to access
7830  * @macvlan_cnt: no. of macvlans to be setup
7831  * @qcnt: no. of Qs per macvlan
7832  * @vdev: macvlan netdevice
7833  */
7834 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7835 			       struct net_device *vdev)
7836 {
7837 	struct i40e_pf *pf = vsi->back;
7838 	struct i40e_hw *hw = &pf->hw;
7839 	struct i40e_vsi_context ctxt;
7840 	u16 sections, qmap, num_qps;
7841 	struct i40e_channel *ch;
7842 	int i, pow, ret = 0;
7843 	u8 offset = 0;
7844 
7845 	if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7846 		return -EINVAL;
7847 
7848 	num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7849 
7850 	/* find the next higher power-of-2 of num queue pairs */
7851 	pow = fls(roundup_pow_of_two(num_qps) - 1);
7852 
7853 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7854 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7855 
7856 	/* Setup context bits for the main VSI */
7857 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7858 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7859 	memset(&ctxt, 0, sizeof(ctxt));
7860 	ctxt.seid = vsi->seid;
7861 	ctxt.pf_num = vsi->back->hw.pf_id;
7862 	ctxt.vf_num = 0;
7863 	ctxt.uplink_seid = vsi->uplink_seid;
7864 	ctxt.info = vsi->info;
7865 	ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7866 	ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7867 	ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7868 	ctxt.info.valid_sections |= cpu_to_le16(sections);
7869 
7870 	/* Reconfigure RSS for main VSI with new max queue count */
7871 	vsi->rss_size = max_t(u16, num_qps, qcnt);
7872 	ret = i40e_vsi_config_rss(vsi);
7873 	if (ret) {
7874 		dev_info(&pf->pdev->dev,
7875 			 "Failed to reconfig RSS for num_queues (%u)\n",
7876 			 vsi->rss_size);
7877 		return ret;
7878 	}
7879 	vsi->reconfig_rss = true;
7880 	dev_dbg(&vsi->back->pdev->dev,
7881 		"Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7882 	vsi->next_base_queue = num_qps;
7883 	vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7884 
7885 	/* Update the VSI after updating the VSI queue-mapping
7886 	 * information
7887 	 */
7888 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7889 	if (ret) {
7890 		dev_info(&pf->pdev->dev,
7891 			 "Update vsi tc config failed, err %s aq_err %s\n",
7892 			 i40e_stat_str(hw, ret),
7893 			 i40e_aq_str(hw, hw->aq.asq_last_status));
7894 		return ret;
7895 	}
7896 	/* update the local VSI info with updated queue map */
7897 	i40e_vsi_update_queue_map(vsi, &ctxt);
7898 	vsi->info.valid_sections = 0;
7899 
7900 	/* Create channels for macvlans */
7901 	INIT_LIST_HEAD(&vsi->macvlan_list);
7902 	for (i = 0; i < macvlan_cnt; i++) {
7903 		ch = kzalloc(sizeof(*ch), GFP_KERNEL);
7904 		if (!ch) {
7905 			ret = -ENOMEM;
7906 			goto err_free;
7907 		}
7908 		INIT_LIST_HEAD(&ch->list);
7909 		ch->num_queue_pairs = qcnt;
7910 		if (!i40e_setup_channel(pf, vsi, ch)) {
7911 			ret = -EINVAL;
7912 			kfree(ch);
7913 			goto err_free;
7914 		}
7915 		ch->parent_vsi = vsi;
7916 		vsi->cnt_q_avail -= ch->num_queue_pairs;
7917 		vsi->macvlan_cnt++;
7918 		list_add_tail(&ch->list, &vsi->macvlan_list);
7919 	}
7920 
7921 	return ret;
7922 
7923 err_free:
7924 	dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
7925 	i40e_free_macvlan_channels(vsi);
7926 
7927 	return ret;
7928 }
7929 
7930 /**
7931  * i40e_fwd_add - configure macvlans
7932  * @netdev: net device to configure
7933  * @vdev: macvlan netdevice
7934  **/
7935 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
7936 {
7937 	struct i40e_netdev_priv *np = netdev_priv(netdev);
7938 	u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
7939 	struct i40e_vsi *vsi = np->vsi;
7940 	struct i40e_pf *pf = vsi->back;
7941 	struct i40e_fwd_adapter *fwd;
7942 	int avail_macvlan, ret;
7943 
7944 	if ((pf->flags & I40E_FLAG_DCB_ENABLED)) {
7945 		netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
7946 		return ERR_PTR(-EINVAL);
7947 	}
7948 	if (i40e_is_tc_mqprio_enabled(pf)) {
7949 		netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
7950 		return ERR_PTR(-EINVAL);
7951 	}
7952 	if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
7953 		netdev_info(netdev, "Not enough vectors available to support macvlans\n");
7954 		return ERR_PTR(-EINVAL);
7955 	}
7956 
7957 	/* The macvlan device has to be a single Q device so that the
7958 	 * tc_to_txq field can be reused to pick the tx queue.
7959 	 */
7960 	if (netif_is_multiqueue(vdev))
7961 		return ERR_PTR(-ERANGE);
7962 
7963 	if (!vsi->macvlan_cnt) {
7964 		/* reserve bit 0 for the pf device */
7965 		set_bit(0, vsi->fwd_bitmask);
7966 
7967 		/* Try to reserve as many queues as possible for macvlans. First
7968 		 * reserve 3/4th of max vectors, then half, then quarter and
7969 		 * calculate Qs per macvlan as you go
7970 		 */
7971 		vectors = pf->num_lan_msix;
7972 		if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
7973 			/* allocate 4 Qs per macvlan and 32 Qs to the PF*/
7974 			q_per_macvlan = 4;
7975 			macvlan_cnt = (vectors - 32) / 4;
7976 		} else if (vectors <= 64 && vectors > 32) {
7977 			/* allocate 2 Qs per macvlan and 16 Qs to the PF*/
7978 			q_per_macvlan = 2;
7979 			macvlan_cnt = (vectors - 16) / 2;
7980 		} else if (vectors <= 32 && vectors > 16) {
7981 			/* allocate 1 Q per macvlan and 16 Qs to the PF*/
7982 			q_per_macvlan = 1;
7983 			macvlan_cnt = vectors - 16;
7984 		} else if (vectors <= 16 && vectors > 8) {
7985 			/* allocate 1 Q per macvlan and 8 Qs to the PF */
7986 			q_per_macvlan = 1;
7987 			macvlan_cnt = vectors - 8;
7988 		} else {
7989 			/* allocate 1 Q per macvlan and 1 Q to the PF */
7990 			q_per_macvlan = 1;
7991 			macvlan_cnt = vectors - 1;
7992 		}
7993 
7994 		if (macvlan_cnt == 0)
7995 			return ERR_PTR(-EBUSY);
7996 
7997 		/* Quiesce VSI queues */
7998 		i40e_quiesce_vsi(vsi);
7999 
8000 		/* sets up the macvlans but does not "enable" them */
8001 		ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
8002 					  vdev);
8003 		if (ret)
8004 			return ERR_PTR(ret);
8005 
8006 		/* Unquiesce VSI */
8007 		i40e_unquiesce_vsi(vsi);
8008 	}
8009 	avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
8010 					    vsi->macvlan_cnt);
8011 	if (avail_macvlan >= I40E_MAX_MACVLANS)
8012 		return ERR_PTR(-EBUSY);
8013 
8014 	/* create the fwd struct */
8015 	fwd = kzalloc(sizeof(*fwd), GFP_KERNEL);
8016 	if (!fwd)
8017 		return ERR_PTR(-ENOMEM);
8018 
8019 	set_bit(avail_macvlan, vsi->fwd_bitmask);
8020 	fwd->bit_no = avail_macvlan;
8021 	netdev_set_sb_channel(vdev, avail_macvlan);
8022 	fwd->netdev = vdev;
8023 
8024 	if (!netif_running(netdev))
8025 		return fwd;
8026 
8027 	/* Set fwd ring up */
8028 	ret = i40e_fwd_ring_up(vsi, vdev, fwd);
8029 	if (ret) {
8030 		/* unbind the queues and drop the subordinate channel config */
8031 		netdev_unbind_sb_channel(netdev, vdev);
8032 		netdev_set_sb_channel(vdev, 0);
8033 
8034 		kfree(fwd);
8035 		return ERR_PTR(-EINVAL);
8036 	}
8037 
8038 	return fwd;
8039 }
8040 
8041 /**
8042  * i40e_del_all_macvlans - Delete all the mac filters on the channels
8043  * @vsi: the VSI we want to access
8044  */
8045 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
8046 {
8047 	struct i40e_channel *ch, *ch_tmp;
8048 	struct i40e_pf *pf = vsi->back;
8049 	struct i40e_hw *hw = &pf->hw;
8050 	int aq_err, ret = 0;
8051 
8052 	if (list_empty(&vsi->macvlan_list))
8053 		return;
8054 
8055 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8056 		if (i40e_is_channel_macvlan(ch)) {
8057 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8058 						      i40e_channel_mac(ch),
8059 						      &aq_err);
8060 			if (!ret) {
8061 				/* Reset queue contexts */
8062 				i40e_reset_ch_rings(vsi, ch);
8063 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8064 				netdev_unbind_sb_channel(vsi->netdev,
8065 							 ch->fwd->netdev);
8066 				netdev_set_sb_channel(ch->fwd->netdev, 0);
8067 				kfree(ch->fwd);
8068 				ch->fwd = NULL;
8069 			}
8070 		}
8071 	}
8072 }
8073 
8074 /**
8075  * i40e_fwd_del - delete macvlan interfaces
8076  * @netdev: net device to configure
8077  * @vdev: macvlan netdevice
8078  */
8079 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
8080 {
8081 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8082 	struct i40e_fwd_adapter *fwd = vdev;
8083 	struct i40e_channel *ch, *ch_tmp;
8084 	struct i40e_vsi *vsi = np->vsi;
8085 	struct i40e_pf *pf = vsi->back;
8086 	struct i40e_hw *hw = &pf->hw;
8087 	int aq_err, ret = 0;
8088 
8089 	/* Find the channel associated with the macvlan and del mac filter */
8090 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8091 		if (i40e_is_channel_macvlan(ch) &&
8092 		    ether_addr_equal(i40e_channel_mac(ch),
8093 				     fwd->netdev->dev_addr)) {
8094 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8095 						      i40e_channel_mac(ch),
8096 						      &aq_err);
8097 			if (!ret) {
8098 				/* Reset queue contexts */
8099 				i40e_reset_ch_rings(vsi, ch);
8100 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8101 				netdev_unbind_sb_channel(netdev, fwd->netdev);
8102 				netdev_set_sb_channel(fwd->netdev, 0);
8103 				kfree(ch->fwd);
8104 				ch->fwd = NULL;
8105 			} else {
8106 				dev_info(&pf->pdev->dev,
8107 					 "Error deleting mac filter on macvlan err %s, aq_err %s\n",
8108 					  i40e_stat_str(hw, ret),
8109 					  i40e_aq_str(hw, aq_err));
8110 			}
8111 			break;
8112 		}
8113 	}
8114 }
8115 
8116 /**
8117  * i40e_setup_tc - configure multiple traffic classes
8118  * @netdev: net device to configure
8119  * @type_data: tc offload data
8120  **/
8121 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
8122 {
8123 	struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
8124 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8125 	struct i40e_vsi *vsi = np->vsi;
8126 	struct i40e_pf *pf = vsi->back;
8127 	u8 enabled_tc = 0, num_tc, hw;
8128 	bool need_reset = false;
8129 	int old_queue_pairs;
8130 	int ret = -EINVAL;
8131 	u16 mode;
8132 	int i;
8133 
8134 	old_queue_pairs = vsi->num_queue_pairs;
8135 	num_tc = mqprio_qopt->qopt.num_tc;
8136 	hw = mqprio_qopt->qopt.hw;
8137 	mode = mqprio_qopt->mode;
8138 	if (!hw) {
8139 		pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8140 		memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8141 		goto config_tc;
8142 	}
8143 
8144 	/* Check if MFP enabled */
8145 	if (pf->flags & I40E_FLAG_MFP_ENABLED) {
8146 		netdev_info(netdev,
8147 			    "Configuring TC not supported in MFP mode\n");
8148 		return ret;
8149 	}
8150 	switch (mode) {
8151 	case TC_MQPRIO_MODE_DCB:
8152 		pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8153 
8154 		/* Check if DCB enabled to continue */
8155 		if (!(pf->flags & I40E_FLAG_DCB_ENABLED)) {
8156 			netdev_info(netdev,
8157 				    "DCB is not enabled for adapter\n");
8158 			return ret;
8159 		}
8160 
8161 		/* Check whether tc count is within enabled limit */
8162 		if (num_tc > i40e_pf_get_num_tc(pf)) {
8163 			netdev_info(netdev,
8164 				    "TC count greater than enabled on link for adapter\n");
8165 			return ret;
8166 		}
8167 		break;
8168 	case TC_MQPRIO_MODE_CHANNEL:
8169 		if (pf->flags & I40E_FLAG_DCB_ENABLED) {
8170 			netdev_info(netdev,
8171 				    "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
8172 			return ret;
8173 		}
8174 		if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
8175 			return ret;
8176 		ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
8177 		if (ret)
8178 			return ret;
8179 		memcpy(&vsi->mqprio_qopt, mqprio_qopt,
8180 		       sizeof(*mqprio_qopt));
8181 		pf->flags |= I40E_FLAG_TC_MQPRIO;
8182 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
8183 		break;
8184 	default:
8185 		return -EINVAL;
8186 	}
8187 
8188 config_tc:
8189 	/* Generate TC map for number of tc requested */
8190 	for (i = 0; i < num_tc; i++)
8191 		enabled_tc |= BIT(i);
8192 
8193 	/* Requesting same TC configuration as already enabled */
8194 	if (enabled_tc == vsi->tc_config.enabled_tc &&
8195 	    mode != TC_MQPRIO_MODE_CHANNEL)
8196 		return 0;
8197 
8198 	/* Quiesce VSI queues */
8199 	i40e_quiesce_vsi(vsi);
8200 
8201 	if (!hw && !i40e_is_tc_mqprio_enabled(pf))
8202 		i40e_remove_queue_channels(vsi);
8203 
8204 	/* Configure VSI for enabled TCs */
8205 	ret = i40e_vsi_config_tc(vsi, enabled_tc);
8206 	if (ret) {
8207 		netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
8208 			    vsi->seid);
8209 		need_reset = true;
8210 		goto exit;
8211 	} else if (enabled_tc &&
8212 		   (!is_power_of_2(vsi->tc_config.tc_info[0].qcount))) {
8213 		netdev_info(netdev,
8214 			    "Failed to create channel. Override queues (%u) not power of 2\n",
8215 			    vsi->tc_config.tc_info[0].qcount);
8216 		ret = -EINVAL;
8217 		need_reset = true;
8218 		goto exit;
8219 	}
8220 
8221 	dev_info(&vsi->back->pdev->dev,
8222 		 "Setup channel (id:%u) utilizing num_queues %d\n",
8223 		 vsi->seid, vsi->tc_config.tc_info[0].qcount);
8224 
8225 	if (i40e_is_tc_mqprio_enabled(pf)) {
8226 		if (vsi->mqprio_qopt.max_rate[0]) {
8227 			u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0];
8228 
8229 			do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
8230 			ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
8231 			if (!ret) {
8232 				u64 credits = max_tx_rate;
8233 
8234 				do_div(credits, I40E_BW_CREDIT_DIVISOR);
8235 				dev_dbg(&vsi->back->pdev->dev,
8236 					"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
8237 					max_tx_rate,
8238 					credits,
8239 					vsi->seid);
8240 			} else {
8241 				need_reset = true;
8242 				goto exit;
8243 			}
8244 		}
8245 		ret = i40e_configure_queue_channels(vsi);
8246 		if (ret) {
8247 			vsi->num_queue_pairs = old_queue_pairs;
8248 			netdev_info(netdev,
8249 				    "Failed configuring queue channels\n");
8250 			need_reset = true;
8251 			goto exit;
8252 		}
8253 	}
8254 
8255 exit:
8256 	/* Reset the configuration data to defaults, only TC0 is enabled */
8257 	if (need_reset) {
8258 		i40e_vsi_set_default_tc_config(vsi);
8259 		need_reset = false;
8260 	}
8261 
8262 	/* Unquiesce VSI */
8263 	i40e_unquiesce_vsi(vsi);
8264 	return ret;
8265 }
8266 
8267 /**
8268  * i40e_set_cld_element - sets cloud filter element data
8269  * @filter: cloud filter rule
8270  * @cld: ptr to cloud filter element data
8271  *
8272  * This is helper function to copy data into cloud filter element
8273  **/
8274 static inline void
8275 i40e_set_cld_element(struct i40e_cloud_filter *filter,
8276 		     struct i40e_aqc_cloud_filters_element_data *cld)
8277 {
8278 	u32 ipa;
8279 	int i;
8280 
8281 	memset(cld, 0, sizeof(*cld));
8282 	ether_addr_copy(cld->outer_mac, filter->dst_mac);
8283 	ether_addr_copy(cld->inner_mac, filter->src_mac);
8284 
8285 	if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
8286 		return;
8287 
8288 	if (filter->n_proto == ETH_P_IPV6) {
8289 #define IPV6_MAX_INDEX	(ARRAY_SIZE(filter->dst_ipv6) - 1)
8290 		for (i = 0; i < ARRAY_SIZE(filter->dst_ipv6); i++) {
8291 			ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
8292 
8293 			*(__le32 *)&cld->ipaddr.raw_v6.data[i * 2] = cpu_to_le32(ipa);
8294 		}
8295 	} else {
8296 		ipa = be32_to_cpu(filter->dst_ipv4);
8297 
8298 		memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
8299 	}
8300 
8301 	cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
8302 
8303 	/* tenant_id is not supported by FW now, once the support is enabled
8304 	 * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
8305 	 */
8306 	if (filter->tenant_id)
8307 		return;
8308 }
8309 
8310 /**
8311  * i40e_add_del_cloud_filter - Add/del cloud filter
8312  * @vsi: pointer to VSI
8313  * @filter: cloud filter rule
8314  * @add: if true, add, if false, delete
8315  *
8316  * Add or delete a cloud filter for a specific flow spec.
8317  * Returns 0 if the filter were successfully added.
8318  **/
8319 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
8320 			      struct i40e_cloud_filter *filter, bool add)
8321 {
8322 	struct i40e_aqc_cloud_filters_element_data cld_filter;
8323 	struct i40e_pf *pf = vsi->back;
8324 	int ret;
8325 	static const u16 flag_table[128] = {
8326 		[I40E_CLOUD_FILTER_FLAGS_OMAC]  =
8327 			I40E_AQC_ADD_CLOUD_FILTER_OMAC,
8328 		[I40E_CLOUD_FILTER_FLAGS_IMAC]  =
8329 			I40E_AQC_ADD_CLOUD_FILTER_IMAC,
8330 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
8331 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
8332 		[I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
8333 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
8334 		[I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
8335 			I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
8336 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
8337 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
8338 		[I40E_CLOUD_FILTER_FLAGS_IIP] =
8339 			I40E_AQC_ADD_CLOUD_FILTER_IIP,
8340 	};
8341 
8342 	if (filter->flags >= ARRAY_SIZE(flag_table))
8343 		return I40E_ERR_CONFIG;
8344 
8345 	memset(&cld_filter, 0, sizeof(cld_filter));
8346 
8347 	/* copy element needed to add cloud filter from filter */
8348 	i40e_set_cld_element(filter, &cld_filter);
8349 
8350 	if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
8351 		cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
8352 					     I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
8353 
8354 	if (filter->n_proto == ETH_P_IPV6)
8355 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8356 						I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8357 	else
8358 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8359 						I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8360 
8361 	if (add)
8362 		ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
8363 						&cld_filter, 1);
8364 	else
8365 		ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
8366 						&cld_filter, 1);
8367 	if (ret)
8368 		dev_dbg(&pf->pdev->dev,
8369 			"Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
8370 			add ? "add" : "delete", filter->dst_port, ret,
8371 			pf->hw.aq.asq_last_status);
8372 	else
8373 		dev_info(&pf->pdev->dev,
8374 			 "%s cloud filter for VSI: %d\n",
8375 			 add ? "Added" : "Deleted", filter->seid);
8376 	return ret;
8377 }
8378 
8379 /**
8380  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
8381  * @vsi: pointer to VSI
8382  * @filter: cloud filter rule
8383  * @add: if true, add, if false, delete
8384  *
8385  * Add or delete a cloud filter for a specific flow spec using big buffer.
8386  * Returns 0 if the filter were successfully added.
8387  **/
8388 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
8389 				      struct i40e_cloud_filter *filter,
8390 				      bool add)
8391 {
8392 	struct i40e_aqc_cloud_filters_element_bb cld_filter;
8393 	struct i40e_pf *pf = vsi->back;
8394 	int ret;
8395 
8396 	/* Both (src/dst) valid mac_addr are not supported */
8397 	if ((is_valid_ether_addr(filter->dst_mac) &&
8398 	     is_valid_ether_addr(filter->src_mac)) ||
8399 	    (is_multicast_ether_addr(filter->dst_mac) &&
8400 	     is_multicast_ether_addr(filter->src_mac)))
8401 		return -EOPNOTSUPP;
8402 
8403 	/* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
8404 	 * ports are not supported via big buffer now.
8405 	 */
8406 	if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
8407 		return -EOPNOTSUPP;
8408 
8409 	/* adding filter using src_port/src_ip is not supported at this stage */
8410 	if (filter->src_port ||
8411 	    (filter->src_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8412 	    !ipv6_addr_any(&filter->ip.v6.src_ip6))
8413 		return -EOPNOTSUPP;
8414 
8415 	memset(&cld_filter, 0, sizeof(cld_filter));
8416 
8417 	/* copy element needed to add cloud filter from filter */
8418 	i40e_set_cld_element(filter, &cld_filter.element);
8419 
8420 	if (is_valid_ether_addr(filter->dst_mac) ||
8421 	    is_valid_ether_addr(filter->src_mac) ||
8422 	    is_multicast_ether_addr(filter->dst_mac) ||
8423 	    is_multicast_ether_addr(filter->src_mac)) {
8424 		/* MAC + IP : unsupported mode */
8425 		if (filter->dst_ipv4)
8426 			return -EOPNOTSUPP;
8427 
8428 		/* since we validated that L4 port must be valid before
8429 		 * we get here, start with respective "flags" value
8430 		 * and update if vlan is present or not
8431 		 */
8432 		cld_filter.element.flags =
8433 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
8434 
8435 		if (filter->vlan_id) {
8436 			cld_filter.element.flags =
8437 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
8438 		}
8439 
8440 	} else if ((filter->dst_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8441 		   !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
8442 		cld_filter.element.flags =
8443 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
8444 		if (filter->n_proto == ETH_P_IPV6)
8445 			cld_filter.element.flags |=
8446 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8447 		else
8448 			cld_filter.element.flags |=
8449 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8450 	} else {
8451 		dev_err(&pf->pdev->dev,
8452 			"either mac or ip has to be valid for cloud filter\n");
8453 		return -EINVAL;
8454 	}
8455 
8456 	/* Now copy L4 port in Byte 6..7 in general fields */
8457 	cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
8458 						be16_to_cpu(filter->dst_port);
8459 
8460 	if (add) {
8461 		/* Validate current device switch mode, change if necessary */
8462 		ret = i40e_validate_and_set_switch_mode(vsi);
8463 		if (ret) {
8464 			dev_err(&pf->pdev->dev,
8465 				"failed to set switch mode, ret %d\n",
8466 				ret);
8467 			return ret;
8468 		}
8469 
8470 		ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
8471 						   &cld_filter, 1);
8472 	} else {
8473 		ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
8474 						   &cld_filter, 1);
8475 	}
8476 
8477 	if (ret)
8478 		dev_dbg(&pf->pdev->dev,
8479 			"Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
8480 			add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
8481 	else
8482 		dev_info(&pf->pdev->dev,
8483 			 "%s cloud filter for VSI: %d, L4 port: %d\n",
8484 			 add ? "add" : "delete", filter->seid,
8485 			 ntohs(filter->dst_port));
8486 	return ret;
8487 }
8488 
8489 /**
8490  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
8491  * @vsi: Pointer to VSI
8492  * @f: Pointer to struct flow_cls_offload
8493  * @filter: Pointer to cloud filter structure
8494  *
8495  **/
8496 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
8497 				 struct flow_cls_offload *f,
8498 				 struct i40e_cloud_filter *filter)
8499 {
8500 	struct flow_rule *rule = flow_cls_offload_flow_rule(f);
8501 	struct flow_dissector *dissector = rule->match.dissector;
8502 	u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
8503 	struct i40e_pf *pf = vsi->back;
8504 	u8 field_flags = 0;
8505 
8506 	if (dissector->used_keys &
8507 	    ~(BIT(FLOW_DISSECTOR_KEY_CONTROL) |
8508 	      BIT(FLOW_DISSECTOR_KEY_BASIC) |
8509 	      BIT(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
8510 	      BIT(FLOW_DISSECTOR_KEY_VLAN) |
8511 	      BIT(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
8512 	      BIT(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
8513 	      BIT(FLOW_DISSECTOR_KEY_PORTS) |
8514 	      BIT(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
8515 		dev_err(&pf->pdev->dev, "Unsupported key used: 0x%x\n",
8516 			dissector->used_keys);
8517 		return -EOPNOTSUPP;
8518 	}
8519 
8520 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
8521 		struct flow_match_enc_keyid match;
8522 
8523 		flow_rule_match_enc_keyid(rule, &match);
8524 		if (match.mask->keyid != 0)
8525 			field_flags |= I40E_CLOUD_FIELD_TEN_ID;
8526 
8527 		filter->tenant_id = be32_to_cpu(match.key->keyid);
8528 	}
8529 
8530 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
8531 		struct flow_match_basic match;
8532 
8533 		flow_rule_match_basic(rule, &match);
8534 		n_proto_key = ntohs(match.key->n_proto);
8535 		n_proto_mask = ntohs(match.mask->n_proto);
8536 
8537 		if (n_proto_key == ETH_P_ALL) {
8538 			n_proto_key = 0;
8539 			n_proto_mask = 0;
8540 		}
8541 		filter->n_proto = n_proto_key & n_proto_mask;
8542 		filter->ip_proto = match.key->ip_proto;
8543 	}
8544 
8545 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
8546 		struct flow_match_eth_addrs match;
8547 
8548 		flow_rule_match_eth_addrs(rule, &match);
8549 
8550 		/* use is_broadcast and is_zero to check for all 0xf or 0 */
8551 		if (!is_zero_ether_addr(match.mask->dst)) {
8552 			if (is_broadcast_ether_addr(match.mask->dst)) {
8553 				field_flags |= I40E_CLOUD_FIELD_OMAC;
8554 			} else {
8555 				dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
8556 					match.mask->dst);
8557 				return I40E_ERR_CONFIG;
8558 			}
8559 		}
8560 
8561 		if (!is_zero_ether_addr(match.mask->src)) {
8562 			if (is_broadcast_ether_addr(match.mask->src)) {
8563 				field_flags |= I40E_CLOUD_FIELD_IMAC;
8564 			} else {
8565 				dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
8566 					match.mask->src);
8567 				return I40E_ERR_CONFIG;
8568 			}
8569 		}
8570 		ether_addr_copy(filter->dst_mac, match.key->dst);
8571 		ether_addr_copy(filter->src_mac, match.key->src);
8572 	}
8573 
8574 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
8575 		struct flow_match_vlan match;
8576 
8577 		flow_rule_match_vlan(rule, &match);
8578 		if (match.mask->vlan_id) {
8579 			if (match.mask->vlan_id == VLAN_VID_MASK) {
8580 				field_flags |= I40E_CLOUD_FIELD_IVLAN;
8581 
8582 			} else {
8583 				dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
8584 					match.mask->vlan_id);
8585 				return I40E_ERR_CONFIG;
8586 			}
8587 		}
8588 
8589 		filter->vlan_id = cpu_to_be16(match.key->vlan_id);
8590 	}
8591 
8592 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
8593 		struct flow_match_control match;
8594 
8595 		flow_rule_match_control(rule, &match);
8596 		addr_type = match.key->addr_type;
8597 	}
8598 
8599 	if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
8600 		struct flow_match_ipv4_addrs match;
8601 
8602 		flow_rule_match_ipv4_addrs(rule, &match);
8603 		if (match.mask->dst) {
8604 			if (match.mask->dst == cpu_to_be32(0xffffffff)) {
8605 				field_flags |= I40E_CLOUD_FIELD_IIP;
8606 			} else {
8607 				dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
8608 					&match.mask->dst);
8609 				return I40E_ERR_CONFIG;
8610 			}
8611 		}
8612 
8613 		if (match.mask->src) {
8614 			if (match.mask->src == cpu_to_be32(0xffffffff)) {
8615 				field_flags |= I40E_CLOUD_FIELD_IIP;
8616 			} else {
8617 				dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
8618 					&match.mask->src);
8619 				return I40E_ERR_CONFIG;
8620 			}
8621 		}
8622 
8623 		if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
8624 			dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
8625 			return I40E_ERR_CONFIG;
8626 		}
8627 		filter->dst_ipv4 = match.key->dst;
8628 		filter->src_ipv4 = match.key->src;
8629 	}
8630 
8631 	if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
8632 		struct flow_match_ipv6_addrs match;
8633 
8634 		flow_rule_match_ipv6_addrs(rule, &match);
8635 
8636 		/* src and dest IPV6 address should not be LOOPBACK
8637 		 * (0:0:0:0:0:0:0:1), which can be represented as ::1
8638 		 */
8639 		if (ipv6_addr_loopback(&match.key->dst) ||
8640 		    ipv6_addr_loopback(&match.key->src)) {
8641 			dev_err(&pf->pdev->dev,
8642 				"Bad ipv6, addr is LOOPBACK\n");
8643 			return I40E_ERR_CONFIG;
8644 		}
8645 		if (!ipv6_addr_any(&match.mask->dst) ||
8646 		    !ipv6_addr_any(&match.mask->src))
8647 			field_flags |= I40E_CLOUD_FIELD_IIP;
8648 
8649 		memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
8650 		       sizeof(filter->src_ipv6));
8651 		memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
8652 		       sizeof(filter->dst_ipv6));
8653 	}
8654 
8655 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
8656 		struct flow_match_ports match;
8657 
8658 		flow_rule_match_ports(rule, &match);
8659 		if (match.mask->src) {
8660 			if (match.mask->src == cpu_to_be16(0xffff)) {
8661 				field_flags |= I40E_CLOUD_FIELD_IIP;
8662 			} else {
8663 				dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
8664 					be16_to_cpu(match.mask->src));
8665 				return I40E_ERR_CONFIG;
8666 			}
8667 		}
8668 
8669 		if (match.mask->dst) {
8670 			if (match.mask->dst == cpu_to_be16(0xffff)) {
8671 				field_flags |= I40E_CLOUD_FIELD_IIP;
8672 			} else {
8673 				dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
8674 					be16_to_cpu(match.mask->dst));
8675 				return I40E_ERR_CONFIG;
8676 			}
8677 		}
8678 
8679 		filter->dst_port = match.key->dst;
8680 		filter->src_port = match.key->src;
8681 
8682 		switch (filter->ip_proto) {
8683 		case IPPROTO_TCP:
8684 		case IPPROTO_UDP:
8685 			break;
8686 		default:
8687 			dev_err(&pf->pdev->dev,
8688 				"Only UDP and TCP transport are supported\n");
8689 			return -EINVAL;
8690 		}
8691 	}
8692 	filter->flags = field_flags;
8693 	return 0;
8694 }
8695 
8696 /**
8697  * i40e_handle_tclass: Forward to a traffic class on the device
8698  * @vsi: Pointer to VSI
8699  * @tc: traffic class index on the device
8700  * @filter: Pointer to cloud filter structure
8701  *
8702  **/
8703 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
8704 			      struct i40e_cloud_filter *filter)
8705 {
8706 	struct i40e_channel *ch, *ch_tmp;
8707 
8708 	/* direct to a traffic class on the same device */
8709 	if (tc == 0) {
8710 		filter->seid = vsi->seid;
8711 		return 0;
8712 	} else if (vsi->tc_config.enabled_tc & BIT(tc)) {
8713 		if (!filter->dst_port) {
8714 			dev_err(&vsi->back->pdev->dev,
8715 				"Specify destination port to direct to traffic class that is not default\n");
8716 			return -EINVAL;
8717 		}
8718 		if (list_empty(&vsi->ch_list))
8719 			return -EINVAL;
8720 		list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
8721 					 list) {
8722 			if (ch->seid == vsi->tc_seid_map[tc])
8723 				filter->seid = ch->seid;
8724 		}
8725 		return 0;
8726 	}
8727 	dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
8728 	return -EINVAL;
8729 }
8730 
8731 /**
8732  * i40e_configure_clsflower - Configure tc flower filters
8733  * @vsi: Pointer to VSI
8734  * @cls_flower: Pointer to struct flow_cls_offload
8735  *
8736  **/
8737 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
8738 				    struct flow_cls_offload *cls_flower)
8739 {
8740 	int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
8741 	struct i40e_cloud_filter *filter = NULL;
8742 	struct i40e_pf *pf = vsi->back;
8743 	int err = 0;
8744 
8745 	if (tc < 0) {
8746 		dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
8747 		return -EOPNOTSUPP;
8748 	}
8749 
8750 	if (!tc) {
8751 		dev_err(&pf->pdev->dev, "Unable to add filter because of invalid destination");
8752 		return -EINVAL;
8753 	}
8754 
8755 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
8756 	    test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
8757 		return -EBUSY;
8758 
8759 	if (pf->fdir_pf_active_filters ||
8760 	    (!hlist_empty(&pf->fdir_filter_list))) {
8761 		dev_err(&vsi->back->pdev->dev,
8762 			"Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
8763 		return -EINVAL;
8764 	}
8765 
8766 	if (vsi->back->flags & I40E_FLAG_FD_SB_ENABLED) {
8767 		dev_err(&vsi->back->pdev->dev,
8768 			"Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
8769 		vsi->back->flags &= ~I40E_FLAG_FD_SB_ENABLED;
8770 		vsi->back->flags |= I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8771 	}
8772 
8773 	filter = kzalloc(sizeof(*filter), GFP_KERNEL);
8774 	if (!filter)
8775 		return -ENOMEM;
8776 
8777 	filter->cookie = cls_flower->cookie;
8778 
8779 	err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8780 	if (err < 0)
8781 		goto err;
8782 
8783 	err = i40e_handle_tclass(vsi, tc, filter);
8784 	if (err < 0)
8785 		goto err;
8786 
8787 	/* Add cloud filter */
8788 	if (filter->dst_port)
8789 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8790 	else
8791 		err = i40e_add_del_cloud_filter(vsi, filter, true);
8792 
8793 	if (err) {
8794 		dev_err(&pf->pdev->dev, "Failed to add cloud filter, err %d\n",
8795 			err);
8796 		goto err;
8797 	}
8798 
8799 	/* add filter to the ordered list */
8800 	INIT_HLIST_NODE(&filter->cloud_node);
8801 
8802 	hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8803 
8804 	pf->num_cloud_filters++;
8805 
8806 	return err;
8807 err:
8808 	kfree(filter);
8809 	return err;
8810 }
8811 
8812 /**
8813  * i40e_find_cloud_filter - Find the could filter in the list
8814  * @vsi: Pointer to VSI
8815  * @cookie: filter specific cookie
8816  *
8817  **/
8818 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8819 							unsigned long *cookie)
8820 {
8821 	struct i40e_cloud_filter *filter = NULL;
8822 	struct hlist_node *node2;
8823 
8824 	hlist_for_each_entry_safe(filter, node2,
8825 				  &vsi->back->cloud_filter_list, cloud_node)
8826 		if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8827 			return filter;
8828 	return NULL;
8829 }
8830 
8831 /**
8832  * i40e_delete_clsflower - Remove tc flower filters
8833  * @vsi: Pointer to VSI
8834  * @cls_flower: Pointer to struct flow_cls_offload
8835  *
8836  **/
8837 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8838 				 struct flow_cls_offload *cls_flower)
8839 {
8840 	struct i40e_cloud_filter *filter = NULL;
8841 	struct i40e_pf *pf = vsi->back;
8842 	int err = 0;
8843 
8844 	filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8845 
8846 	if (!filter)
8847 		return -EINVAL;
8848 
8849 	hash_del(&filter->cloud_node);
8850 
8851 	if (filter->dst_port)
8852 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8853 	else
8854 		err = i40e_add_del_cloud_filter(vsi, filter, false);
8855 
8856 	kfree(filter);
8857 	if (err) {
8858 		dev_err(&pf->pdev->dev,
8859 			"Failed to delete cloud filter, err %s\n",
8860 			i40e_stat_str(&pf->hw, err));
8861 		return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8862 	}
8863 
8864 	pf->num_cloud_filters--;
8865 	if (!pf->num_cloud_filters)
8866 		if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
8867 		    !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
8868 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
8869 			pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8870 			pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
8871 		}
8872 	return 0;
8873 }
8874 
8875 /**
8876  * i40e_setup_tc_cls_flower - flower classifier offloads
8877  * @np: net device to configure
8878  * @cls_flower: offload data
8879  **/
8880 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8881 				    struct flow_cls_offload *cls_flower)
8882 {
8883 	struct i40e_vsi *vsi = np->vsi;
8884 
8885 	switch (cls_flower->command) {
8886 	case FLOW_CLS_REPLACE:
8887 		return i40e_configure_clsflower(vsi, cls_flower);
8888 	case FLOW_CLS_DESTROY:
8889 		return i40e_delete_clsflower(vsi, cls_flower);
8890 	case FLOW_CLS_STATS:
8891 		return -EOPNOTSUPP;
8892 	default:
8893 		return -EOPNOTSUPP;
8894 	}
8895 }
8896 
8897 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8898 				  void *cb_priv)
8899 {
8900 	struct i40e_netdev_priv *np = cb_priv;
8901 
8902 	if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8903 		return -EOPNOTSUPP;
8904 
8905 	switch (type) {
8906 	case TC_SETUP_CLSFLOWER:
8907 		return i40e_setup_tc_cls_flower(np, type_data);
8908 
8909 	default:
8910 		return -EOPNOTSUPP;
8911 	}
8912 }
8913 
8914 static LIST_HEAD(i40e_block_cb_list);
8915 
8916 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8917 			   void *type_data)
8918 {
8919 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8920 
8921 	switch (type) {
8922 	case TC_SETUP_QDISC_MQPRIO:
8923 		return i40e_setup_tc(netdev, type_data);
8924 	case TC_SETUP_BLOCK:
8925 		return flow_block_cb_setup_simple(type_data,
8926 						  &i40e_block_cb_list,
8927 						  i40e_setup_tc_block_cb,
8928 						  np, np, true);
8929 	default:
8930 		return -EOPNOTSUPP;
8931 	}
8932 }
8933 
8934 /**
8935  * i40e_open - Called when a network interface is made active
8936  * @netdev: network interface device structure
8937  *
8938  * The open entry point is called when a network interface is made
8939  * active by the system (IFF_UP).  At this point all resources needed
8940  * for transmit and receive operations are allocated, the interrupt
8941  * handler is registered with the OS, the netdev watchdog subtask is
8942  * enabled, and the stack is notified that the interface is ready.
8943  *
8944  * Returns 0 on success, negative value on failure
8945  **/
8946 int i40e_open(struct net_device *netdev)
8947 {
8948 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8949 	struct i40e_vsi *vsi = np->vsi;
8950 	struct i40e_pf *pf = vsi->back;
8951 	int err;
8952 
8953 	/* disallow open during test or if eeprom is broken */
8954 	if (test_bit(__I40E_TESTING, pf->state) ||
8955 	    test_bit(__I40E_BAD_EEPROM, pf->state))
8956 		return -EBUSY;
8957 
8958 	netif_carrier_off(netdev);
8959 
8960 	if (i40e_force_link_state(pf, true))
8961 		return -EAGAIN;
8962 
8963 	err = i40e_vsi_open(vsi);
8964 	if (err)
8965 		return err;
8966 
8967 	/* configure global TSO hardware offload settings */
8968 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
8969 						       TCP_FLAG_FIN) >> 16);
8970 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
8971 						       TCP_FLAG_FIN |
8972 						       TCP_FLAG_CWR) >> 16);
8973 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
8974 	udp_tunnel_get_rx_info(netdev);
8975 
8976 	return 0;
8977 }
8978 
8979 /**
8980  * i40e_netif_set_realnum_tx_rx_queues - Update number of tx/rx queues
8981  * @vsi: vsi structure
8982  *
8983  * This updates netdev's number of tx/rx queues
8984  *
8985  * Returns status of setting tx/rx queues
8986  **/
8987 static int i40e_netif_set_realnum_tx_rx_queues(struct i40e_vsi *vsi)
8988 {
8989 	int ret;
8990 
8991 	ret = netif_set_real_num_rx_queues(vsi->netdev,
8992 					   vsi->num_queue_pairs);
8993 	if (ret)
8994 		return ret;
8995 
8996 	return netif_set_real_num_tx_queues(vsi->netdev,
8997 					    vsi->num_queue_pairs);
8998 }
8999 
9000 /**
9001  * i40e_vsi_open -
9002  * @vsi: the VSI to open
9003  *
9004  * Finish initialization of the VSI.
9005  *
9006  * Returns 0 on success, negative value on failure
9007  *
9008  * Note: expects to be called while under rtnl_lock()
9009  **/
9010 int i40e_vsi_open(struct i40e_vsi *vsi)
9011 {
9012 	struct i40e_pf *pf = vsi->back;
9013 	char int_name[I40E_INT_NAME_STR_LEN];
9014 	int err;
9015 
9016 	/* allocate descriptors */
9017 	err = i40e_vsi_setup_tx_resources(vsi);
9018 	if (err)
9019 		goto err_setup_tx;
9020 	err = i40e_vsi_setup_rx_resources(vsi);
9021 	if (err)
9022 		goto err_setup_rx;
9023 
9024 	err = i40e_vsi_configure(vsi);
9025 	if (err)
9026 		goto err_setup_rx;
9027 
9028 	if (vsi->netdev) {
9029 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
9030 			 dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
9031 		err = i40e_vsi_request_irq(vsi, int_name);
9032 		if (err)
9033 			goto err_setup_rx;
9034 
9035 		/* Notify the stack of the actual queue counts. */
9036 		err = i40e_netif_set_realnum_tx_rx_queues(vsi);
9037 		if (err)
9038 			goto err_set_queues;
9039 
9040 	} else if (vsi->type == I40E_VSI_FDIR) {
9041 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
9042 			 dev_driver_string(&pf->pdev->dev),
9043 			 dev_name(&pf->pdev->dev));
9044 		err = i40e_vsi_request_irq(vsi, int_name);
9045 		if (err)
9046 			goto err_setup_rx;
9047 
9048 	} else {
9049 		err = -EINVAL;
9050 		goto err_setup_rx;
9051 	}
9052 
9053 	err = i40e_up_complete(vsi);
9054 	if (err)
9055 		goto err_up_complete;
9056 
9057 	return 0;
9058 
9059 err_up_complete:
9060 	i40e_down(vsi);
9061 err_set_queues:
9062 	i40e_vsi_free_irq(vsi);
9063 err_setup_rx:
9064 	i40e_vsi_free_rx_resources(vsi);
9065 err_setup_tx:
9066 	i40e_vsi_free_tx_resources(vsi);
9067 	if (vsi == pf->vsi[pf->lan_vsi])
9068 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
9069 
9070 	return err;
9071 }
9072 
9073 /**
9074  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
9075  * @pf: Pointer to PF
9076  *
9077  * This function destroys the hlist where all the Flow Director
9078  * filters were saved.
9079  **/
9080 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
9081 {
9082 	struct i40e_fdir_filter *filter;
9083 	struct i40e_flex_pit *pit_entry, *tmp;
9084 	struct hlist_node *node2;
9085 
9086 	hlist_for_each_entry_safe(filter, node2,
9087 				  &pf->fdir_filter_list, fdir_node) {
9088 		hlist_del(&filter->fdir_node);
9089 		kfree(filter);
9090 	}
9091 
9092 	list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
9093 		list_del(&pit_entry->list);
9094 		kfree(pit_entry);
9095 	}
9096 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
9097 
9098 	list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
9099 		list_del(&pit_entry->list);
9100 		kfree(pit_entry);
9101 	}
9102 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
9103 
9104 	pf->fdir_pf_active_filters = 0;
9105 	i40e_reset_fdir_filter_cnt(pf);
9106 
9107 	/* Reprogram the default input set for TCP/IPv4 */
9108 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9109 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9110 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9111 
9112 	/* Reprogram the default input set for TCP/IPv6 */
9113 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_TCP,
9114 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9115 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9116 
9117 	/* Reprogram the default input set for UDP/IPv4 */
9118 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
9119 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9120 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9121 
9122 	/* Reprogram the default input set for UDP/IPv6 */
9123 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_UDP,
9124 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9125 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9126 
9127 	/* Reprogram the default input set for SCTP/IPv4 */
9128 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
9129 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9130 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9131 
9132 	/* Reprogram the default input set for SCTP/IPv6 */
9133 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_SCTP,
9134 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9135 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9136 
9137 	/* Reprogram the default input set for Other/IPv4 */
9138 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
9139 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9140 
9141 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
9142 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9143 
9144 	/* Reprogram the default input set for Other/IPv6 */
9145 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_OTHER,
9146 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9147 
9148 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV6,
9149 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9150 }
9151 
9152 /**
9153  * i40e_cloud_filter_exit - Cleans up the cloud filters
9154  * @pf: Pointer to PF
9155  *
9156  * This function destroys the hlist where all the cloud filters
9157  * were saved.
9158  **/
9159 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
9160 {
9161 	struct i40e_cloud_filter *cfilter;
9162 	struct hlist_node *node;
9163 
9164 	hlist_for_each_entry_safe(cfilter, node,
9165 				  &pf->cloud_filter_list, cloud_node) {
9166 		hlist_del(&cfilter->cloud_node);
9167 		kfree(cfilter);
9168 	}
9169 	pf->num_cloud_filters = 0;
9170 
9171 	if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
9172 	    !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
9173 		pf->flags |= I40E_FLAG_FD_SB_ENABLED;
9174 		pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
9175 		pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
9176 	}
9177 }
9178 
9179 /**
9180  * i40e_close - Disables a network interface
9181  * @netdev: network interface device structure
9182  *
9183  * The close entry point is called when an interface is de-activated
9184  * by the OS.  The hardware is still under the driver's control, but
9185  * this netdev interface is disabled.
9186  *
9187  * Returns 0, this is not allowed to fail
9188  **/
9189 int i40e_close(struct net_device *netdev)
9190 {
9191 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9192 	struct i40e_vsi *vsi = np->vsi;
9193 
9194 	i40e_vsi_close(vsi);
9195 
9196 	return 0;
9197 }
9198 
9199 /**
9200  * i40e_do_reset - Start a PF or Core Reset sequence
9201  * @pf: board private structure
9202  * @reset_flags: which reset is requested
9203  * @lock_acquired: indicates whether or not the lock has been acquired
9204  * before this function was called.
9205  *
9206  * The essential difference in resets is that the PF Reset
9207  * doesn't clear the packet buffers, doesn't reset the PE
9208  * firmware, and doesn't bother the other PFs on the chip.
9209  **/
9210 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
9211 {
9212 	u32 val;
9213 
9214 	/* do the biggest reset indicated */
9215 	if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
9216 
9217 		/* Request a Global Reset
9218 		 *
9219 		 * This will start the chip's countdown to the actual full
9220 		 * chip reset event, and a warning interrupt to be sent
9221 		 * to all PFs, including the requestor.  Our handler
9222 		 * for the warning interrupt will deal with the shutdown
9223 		 * and recovery of the switch setup.
9224 		 */
9225 		dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
9226 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9227 		val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
9228 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9229 
9230 	} else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
9231 
9232 		/* Request a Core Reset
9233 		 *
9234 		 * Same as Global Reset, except does *not* include the MAC/PHY
9235 		 */
9236 		dev_dbg(&pf->pdev->dev, "CoreR requested\n");
9237 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9238 		val |= I40E_GLGEN_RTRIG_CORER_MASK;
9239 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9240 		i40e_flush(&pf->hw);
9241 
9242 	} else if (reset_flags & I40E_PF_RESET_FLAG) {
9243 
9244 		/* Request a PF Reset
9245 		 *
9246 		 * Resets only the PF-specific registers
9247 		 *
9248 		 * This goes directly to the tear-down and rebuild of
9249 		 * the switch, since we need to do all the recovery as
9250 		 * for the Core Reset.
9251 		 */
9252 		dev_dbg(&pf->pdev->dev, "PFR requested\n");
9253 		i40e_handle_reset_warning(pf, lock_acquired);
9254 
9255 	} else if (reset_flags & I40E_PF_RESET_AND_REBUILD_FLAG) {
9256 		/* Request a PF Reset
9257 		 *
9258 		 * Resets PF and reinitializes PFs VSI.
9259 		 */
9260 		i40e_prep_for_reset(pf);
9261 		i40e_reset_and_rebuild(pf, true, lock_acquired);
9262 		dev_info(&pf->pdev->dev,
9263 			 pf->flags & I40E_FLAG_DISABLE_FW_LLDP ?
9264 			 "FW LLDP is disabled\n" :
9265 			 "FW LLDP is enabled\n");
9266 
9267 	} else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
9268 		int v;
9269 
9270 		/* Find the VSI(s) that requested a re-init */
9271 		dev_info(&pf->pdev->dev,
9272 			 "VSI reinit requested\n");
9273 		for (v = 0; v < pf->num_alloc_vsi; v++) {
9274 			struct i40e_vsi *vsi = pf->vsi[v];
9275 
9276 			if (vsi != NULL &&
9277 			    test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
9278 					       vsi->state))
9279 				i40e_vsi_reinit_locked(pf->vsi[v]);
9280 		}
9281 	} else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
9282 		int v;
9283 
9284 		/* Find the VSI(s) that needs to be brought down */
9285 		dev_info(&pf->pdev->dev, "VSI down requested\n");
9286 		for (v = 0; v < pf->num_alloc_vsi; v++) {
9287 			struct i40e_vsi *vsi = pf->vsi[v];
9288 
9289 			if (vsi != NULL &&
9290 			    test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
9291 					       vsi->state)) {
9292 				set_bit(__I40E_VSI_DOWN, vsi->state);
9293 				i40e_down(vsi);
9294 			}
9295 		}
9296 	} else {
9297 		dev_info(&pf->pdev->dev,
9298 			 "bad reset request 0x%08x\n", reset_flags);
9299 	}
9300 }
9301 
9302 #ifdef CONFIG_I40E_DCB
9303 /**
9304  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
9305  * @pf: board private structure
9306  * @old_cfg: current DCB config
9307  * @new_cfg: new DCB config
9308  **/
9309 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
9310 			    struct i40e_dcbx_config *old_cfg,
9311 			    struct i40e_dcbx_config *new_cfg)
9312 {
9313 	bool need_reconfig = false;
9314 
9315 	/* Check if ETS configuration has changed */
9316 	if (memcmp(&new_cfg->etscfg,
9317 		   &old_cfg->etscfg,
9318 		   sizeof(new_cfg->etscfg))) {
9319 		/* If Priority Table has changed reconfig is needed */
9320 		if (memcmp(&new_cfg->etscfg.prioritytable,
9321 			   &old_cfg->etscfg.prioritytable,
9322 			   sizeof(new_cfg->etscfg.prioritytable))) {
9323 			need_reconfig = true;
9324 			dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
9325 		}
9326 
9327 		if (memcmp(&new_cfg->etscfg.tcbwtable,
9328 			   &old_cfg->etscfg.tcbwtable,
9329 			   sizeof(new_cfg->etscfg.tcbwtable)))
9330 			dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
9331 
9332 		if (memcmp(&new_cfg->etscfg.tsatable,
9333 			   &old_cfg->etscfg.tsatable,
9334 			   sizeof(new_cfg->etscfg.tsatable)))
9335 			dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
9336 	}
9337 
9338 	/* Check if PFC configuration has changed */
9339 	if (memcmp(&new_cfg->pfc,
9340 		   &old_cfg->pfc,
9341 		   sizeof(new_cfg->pfc))) {
9342 		need_reconfig = true;
9343 		dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
9344 	}
9345 
9346 	/* Check if APP Table has changed */
9347 	if (memcmp(&new_cfg->app,
9348 		   &old_cfg->app,
9349 		   sizeof(new_cfg->app))) {
9350 		need_reconfig = true;
9351 		dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
9352 	}
9353 
9354 	dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
9355 	return need_reconfig;
9356 }
9357 
9358 /**
9359  * i40e_handle_lldp_event - Handle LLDP Change MIB event
9360  * @pf: board private structure
9361  * @e: event info posted on ARQ
9362  **/
9363 static int i40e_handle_lldp_event(struct i40e_pf *pf,
9364 				  struct i40e_arq_event_info *e)
9365 {
9366 	struct i40e_aqc_lldp_get_mib *mib =
9367 		(struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
9368 	struct i40e_hw *hw = &pf->hw;
9369 	struct i40e_dcbx_config tmp_dcbx_cfg;
9370 	bool need_reconfig = false;
9371 	int ret = 0;
9372 	u8 type;
9373 
9374 	/* X710-T*L 2.5G and 5G speeds don't support DCB */
9375 	if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9376 	    (hw->phy.link_info.link_speed &
9377 	     ~(I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB)) &&
9378 	     !(pf->flags & I40E_FLAG_DCB_CAPABLE))
9379 		/* let firmware decide if the DCB should be disabled */
9380 		pf->flags |= I40E_FLAG_DCB_CAPABLE;
9381 
9382 	/* Not DCB capable or capability disabled */
9383 	if (!(pf->flags & I40E_FLAG_DCB_CAPABLE))
9384 		return ret;
9385 
9386 	/* Ignore if event is not for Nearest Bridge */
9387 	type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
9388 		& I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
9389 	dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
9390 	if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
9391 		return ret;
9392 
9393 	/* Check MIB Type and return if event for Remote MIB update */
9394 	type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
9395 	dev_dbg(&pf->pdev->dev,
9396 		"LLDP event mib type %s\n", type ? "remote" : "local");
9397 	if (type == I40E_AQ_LLDP_MIB_REMOTE) {
9398 		/* Update the remote cached instance and return */
9399 		ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
9400 				I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
9401 				&hw->remote_dcbx_config);
9402 		goto exit;
9403 	}
9404 
9405 	/* Store the old configuration */
9406 	tmp_dcbx_cfg = hw->local_dcbx_config;
9407 
9408 	/* Reset the old DCBx configuration data */
9409 	memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
9410 	/* Get updated DCBX data from firmware */
9411 	ret = i40e_get_dcb_config(&pf->hw);
9412 	if (ret) {
9413 		/* X710-T*L 2.5G and 5G speeds don't support DCB */
9414 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9415 		    (hw->phy.link_info.link_speed &
9416 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
9417 			dev_warn(&pf->pdev->dev,
9418 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
9419 			pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
9420 		} else {
9421 			dev_info(&pf->pdev->dev,
9422 				 "Failed querying DCB configuration data from firmware, err %s aq_err %s\n",
9423 				 i40e_stat_str(&pf->hw, ret),
9424 				 i40e_aq_str(&pf->hw,
9425 					     pf->hw.aq.asq_last_status));
9426 		}
9427 		goto exit;
9428 	}
9429 
9430 	/* No change detected in DCBX configs */
9431 	if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
9432 		    sizeof(tmp_dcbx_cfg))) {
9433 		dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
9434 		goto exit;
9435 	}
9436 
9437 	need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
9438 					       &hw->local_dcbx_config);
9439 
9440 	i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
9441 
9442 	if (!need_reconfig)
9443 		goto exit;
9444 
9445 	/* Enable DCB tagging only when more than one TC */
9446 	if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
9447 		pf->flags |= I40E_FLAG_DCB_ENABLED;
9448 	else
9449 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9450 
9451 	set_bit(__I40E_PORT_SUSPENDED, pf->state);
9452 	/* Reconfiguration needed quiesce all VSIs */
9453 	i40e_pf_quiesce_all_vsi(pf);
9454 
9455 	/* Changes in configuration update VEB/VSI */
9456 	i40e_dcb_reconfigure(pf);
9457 
9458 	ret = i40e_resume_port_tx(pf);
9459 
9460 	clear_bit(__I40E_PORT_SUSPENDED, pf->state);
9461 	/* In case of error no point in resuming VSIs */
9462 	if (ret)
9463 		goto exit;
9464 
9465 	/* Wait for the PF's queues to be disabled */
9466 	ret = i40e_pf_wait_queues_disabled(pf);
9467 	if (ret) {
9468 		/* Schedule PF reset to recover */
9469 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9470 		i40e_service_event_schedule(pf);
9471 	} else {
9472 		i40e_pf_unquiesce_all_vsi(pf);
9473 		set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
9474 		set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
9475 	}
9476 
9477 exit:
9478 	return ret;
9479 }
9480 #endif /* CONFIG_I40E_DCB */
9481 
9482 /**
9483  * i40e_do_reset_safe - Protected reset path for userland calls.
9484  * @pf: board private structure
9485  * @reset_flags: which reset is requested
9486  *
9487  **/
9488 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
9489 {
9490 	rtnl_lock();
9491 	i40e_do_reset(pf, reset_flags, true);
9492 	rtnl_unlock();
9493 }
9494 
9495 /**
9496  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
9497  * @pf: board private structure
9498  * @e: event info posted on ARQ
9499  *
9500  * Handler for LAN Queue Overflow Event generated by the firmware for PF
9501  * and VF queues
9502  **/
9503 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
9504 					   struct i40e_arq_event_info *e)
9505 {
9506 	struct i40e_aqc_lan_overflow *data =
9507 		(struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
9508 	u32 queue = le32_to_cpu(data->prtdcb_rupto);
9509 	u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
9510 	struct i40e_hw *hw = &pf->hw;
9511 	struct i40e_vf *vf;
9512 	u16 vf_id;
9513 
9514 	dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
9515 		queue, qtx_ctl);
9516 
9517 	/* Queue belongs to VF, find the VF and issue VF reset */
9518 	if (((qtx_ctl & I40E_QTX_CTL_PFVF_Q_MASK)
9519 	    >> I40E_QTX_CTL_PFVF_Q_SHIFT) == I40E_QTX_CTL_VF_QUEUE) {
9520 		vf_id = (u16)((qtx_ctl & I40E_QTX_CTL_VFVM_INDX_MASK)
9521 			 >> I40E_QTX_CTL_VFVM_INDX_SHIFT);
9522 		vf_id -= hw->func_caps.vf_base_id;
9523 		vf = &pf->vf[vf_id];
9524 		i40e_vc_notify_vf_reset(vf);
9525 		/* Allow VF to process pending reset notification */
9526 		msleep(20);
9527 		i40e_reset_vf(vf, false);
9528 	}
9529 }
9530 
9531 /**
9532  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
9533  * @pf: board private structure
9534  **/
9535 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
9536 {
9537 	u32 val, fcnt_prog;
9538 
9539 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9540 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
9541 	return fcnt_prog;
9542 }
9543 
9544 /**
9545  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
9546  * @pf: board private structure
9547  **/
9548 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
9549 {
9550 	u32 val, fcnt_prog;
9551 
9552 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9553 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
9554 		    ((val & I40E_PFQF_FDSTAT_BEST_CNT_MASK) >>
9555 		      I40E_PFQF_FDSTAT_BEST_CNT_SHIFT);
9556 	return fcnt_prog;
9557 }
9558 
9559 /**
9560  * i40e_get_global_fd_count - Get total FD filters programmed on device
9561  * @pf: board private structure
9562  **/
9563 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
9564 {
9565 	u32 val, fcnt_prog;
9566 
9567 	val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
9568 	fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
9569 		    ((val & I40E_GLQF_FDCNT_0_BESTCNT_MASK) >>
9570 		     I40E_GLQF_FDCNT_0_BESTCNT_SHIFT);
9571 	return fcnt_prog;
9572 }
9573 
9574 /**
9575  * i40e_reenable_fdir_sb - Restore FDir SB capability
9576  * @pf: board private structure
9577  **/
9578 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
9579 {
9580 	if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
9581 		if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
9582 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9583 			dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
9584 }
9585 
9586 /**
9587  * i40e_reenable_fdir_atr - Restore FDir ATR capability
9588  * @pf: board private structure
9589  **/
9590 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
9591 {
9592 	if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
9593 		/* ATR uses the same filtering logic as SB rules. It only
9594 		 * functions properly if the input set mask is at the default
9595 		 * settings. It is safe to restore the default input set
9596 		 * because there are no active TCPv4 filter rules.
9597 		 */
9598 		i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9599 					I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9600 					I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9601 
9602 		if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
9603 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9604 			dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
9605 	}
9606 }
9607 
9608 /**
9609  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
9610  * @pf: board private structure
9611  * @filter: FDir filter to remove
9612  */
9613 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
9614 				       struct i40e_fdir_filter *filter)
9615 {
9616 	/* Update counters */
9617 	pf->fdir_pf_active_filters--;
9618 	pf->fd_inv = 0;
9619 
9620 	switch (filter->flow_type) {
9621 	case TCP_V4_FLOW:
9622 		pf->fd_tcp4_filter_cnt--;
9623 		break;
9624 	case UDP_V4_FLOW:
9625 		pf->fd_udp4_filter_cnt--;
9626 		break;
9627 	case SCTP_V4_FLOW:
9628 		pf->fd_sctp4_filter_cnt--;
9629 		break;
9630 	case TCP_V6_FLOW:
9631 		pf->fd_tcp6_filter_cnt--;
9632 		break;
9633 	case UDP_V6_FLOW:
9634 		pf->fd_udp6_filter_cnt--;
9635 		break;
9636 	case SCTP_V6_FLOW:
9637 		pf->fd_udp6_filter_cnt--;
9638 		break;
9639 	case IP_USER_FLOW:
9640 		switch (filter->ipl4_proto) {
9641 		case IPPROTO_TCP:
9642 			pf->fd_tcp4_filter_cnt--;
9643 			break;
9644 		case IPPROTO_UDP:
9645 			pf->fd_udp4_filter_cnt--;
9646 			break;
9647 		case IPPROTO_SCTP:
9648 			pf->fd_sctp4_filter_cnt--;
9649 			break;
9650 		case IPPROTO_IP:
9651 			pf->fd_ip4_filter_cnt--;
9652 			break;
9653 		}
9654 		break;
9655 	case IPV6_USER_FLOW:
9656 		switch (filter->ipl4_proto) {
9657 		case IPPROTO_TCP:
9658 			pf->fd_tcp6_filter_cnt--;
9659 			break;
9660 		case IPPROTO_UDP:
9661 			pf->fd_udp6_filter_cnt--;
9662 			break;
9663 		case IPPROTO_SCTP:
9664 			pf->fd_sctp6_filter_cnt--;
9665 			break;
9666 		case IPPROTO_IP:
9667 			pf->fd_ip6_filter_cnt--;
9668 			break;
9669 		}
9670 		break;
9671 	}
9672 
9673 	/* Remove the filter from the list and free memory */
9674 	hlist_del(&filter->fdir_node);
9675 	kfree(filter);
9676 }
9677 
9678 /**
9679  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
9680  * @pf: board private structure
9681  **/
9682 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
9683 {
9684 	struct i40e_fdir_filter *filter;
9685 	u32 fcnt_prog, fcnt_avail;
9686 	struct hlist_node *node;
9687 
9688 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9689 		return;
9690 
9691 	/* Check if we have enough room to re-enable FDir SB capability. */
9692 	fcnt_prog = i40e_get_global_fd_count(pf);
9693 	fcnt_avail = pf->fdir_pf_filter_count;
9694 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
9695 	    (pf->fd_add_err == 0) ||
9696 	    (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
9697 		i40e_reenable_fdir_sb(pf);
9698 
9699 	/* We should wait for even more space before re-enabling ATR.
9700 	 * Additionally, we cannot enable ATR as long as we still have TCP SB
9701 	 * rules active.
9702 	 */
9703 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
9704 	    pf->fd_tcp4_filter_cnt == 0 && pf->fd_tcp6_filter_cnt == 0)
9705 		i40e_reenable_fdir_atr(pf);
9706 
9707 	/* if hw had a problem adding a filter, delete it */
9708 	if (pf->fd_inv > 0) {
9709 		hlist_for_each_entry_safe(filter, node,
9710 					  &pf->fdir_filter_list, fdir_node)
9711 			if (filter->fd_id == pf->fd_inv)
9712 				i40e_delete_invalid_filter(pf, filter);
9713 	}
9714 }
9715 
9716 #define I40E_MIN_FD_FLUSH_INTERVAL 10
9717 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
9718 /**
9719  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
9720  * @pf: board private structure
9721  **/
9722 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
9723 {
9724 	unsigned long min_flush_time;
9725 	int flush_wait_retry = 50;
9726 	bool disable_atr = false;
9727 	int fd_room;
9728 	int reg;
9729 
9730 	if (!time_after(jiffies, pf->fd_flush_timestamp +
9731 				 (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
9732 		return;
9733 
9734 	/* If the flush is happening too quick and we have mostly SB rules we
9735 	 * should not re-enable ATR for some time.
9736 	 */
9737 	min_flush_time = pf->fd_flush_timestamp +
9738 			 (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
9739 	fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
9740 
9741 	if (!(time_after(jiffies, min_flush_time)) &&
9742 	    (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
9743 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9744 			dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
9745 		disable_atr = true;
9746 	}
9747 
9748 	pf->fd_flush_timestamp = jiffies;
9749 	set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9750 	/* flush all filters */
9751 	wr32(&pf->hw, I40E_PFQF_CTL_1,
9752 	     I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
9753 	i40e_flush(&pf->hw);
9754 	pf->fd_flush_cnt++;
9755 	pf->fd_add_err = 0;
9756 	do {
9757 		/* Check FD flush status every 5-6msec */
9758 		usleep_range(5000, 6000);
9759 		reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
9760 		if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
9761 			break;
9762 	} while (flush_wait_retry--);
9763 	if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
9764 		dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
9765 	} else {
9766 		/* replay sideband filters */
9767 		i40e_fdir_filter_restore(pf->vsi[pf->lan_vsi]);
9768 		if (!disable_atr && !pf->fd_tcp4_filter_cnt)
9769 			clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9770 		clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
9771 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9772 			dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
9773 	}
9774 }
9775 
9776 /**
9777  * i40e_get_current_atr_cnt - Get the count of total FD ATR filters programmed
9778  * @pf: board private structure
9779  **/
9780 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
9781 {
9782 	return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
9783 }
9784 
9785 /**
9786  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
9787  * @pf: board private structure
9788  **/
9789 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
9790 {
9791 
9792 	/* if interface is down do nothing */
9793 	if (test_bit(__I40E_DOWN, pf->state))
9794 		return;
9795 
9796 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9797 		i40e_fdir_flush_and_replay(pf);
9798 
9799 	i40e_fdir_check_and_reenable(pf);
9800 
9801 }
9802 
9803 /**
9804  * i40e_vsi_link_event - notify VSI of a link event
9805  * @vsi: vsi to be notified
9806  * @link_up: link up or down
9807  **/
9808 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
9809 {
9810 	if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
9811 		return;
9812 
9813 	switch (vsi->type) {
9814 	case I40E_VSI_MAIN:
9815 		if (!vsi->netdev || !vsi->netdev_registered)
9816 			break;
9817 
9818 		if (link_up) {
9819 			netif_carrier_on(vsi->netdev);
9820 			netif_tx_wake_all_queues(vsi->netdev);
9821 		} else {
9822 			netif_carrier_off(vsi->netdev);
9823 			netif_tx_stop_all_queues(vsi->netdev);
9824 		}
9825 		break;
9826 
9827 	case I40E_VSI_SRIOV:
9828 	case I40E_VSI_VMDQ2:
9829 	case I40E_VSI_CTRL:
9830 	case I40E_VSI_IWARP:
9831 	case I40E_VSI_MIRROR:
9832 	default:
9833 		/* there is no notification for other VSIs */
9834 		break;
9835 	}
9836 }
9837 
9838 /**
9839  * i40e_veb_link_event - notify elements on the veb of a link event
9840  * @veb: veb to be notified
9841  * @link_up: link up or down
9842  **/
9843 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
9844 {
9845 	struct i40e_pf *pf;
9846 	int i;
9847 
9848 	if (!veb || !veb->pf)
9849 		return;
9850 	pf = veb->pf;
9851 
9852 	/* depth first... */
9853 	for (i = 0; i < I40E_MAX_VEB; i++)
9854 		if (pf->veb[i] && (pf->veb[i]->uplink_seid == veb->seid))
9855 			i40e_veb_link_event(pf->veb[i], link_up);
9856 
9857 	/* ... now the local VSIs */
9858 	for (i = 0; i < pf->num_alloc_vsi; i++)
9859 		if (pf->vsi[i] && (pf->vsi[i]->uplink_seid == veb->seid))
9860 			i40e_vsi_link_event(pf->vsi[i], link_up);
9861 }
9862 
9863 /**
9864  * i40e_link_event - Update netif_carrier status
9865  * @pf: board private structure
9866  **/
9867 static void i40e_link_event(struct i40e_pf *pf)
9868 {
9869 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9870 	u8 new_link_speed, old_link_speed;
9871 	i40e_status status;
9872 	bool new_link, old_link;
9873 #ifdef CONFIG_I40E_DCB
9874 	int err;
9875 #endif /* CONFIG_I40E_DCB */
9876 
9877 	/* set this to force the get_link_status call to refresh state */
9878 	pf->hw.phy.get_link_info = true;
9879 	old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9880 	status = i40e_get_link_status(&pf->hw, &new_link);
9881 
9882 	/* On success, disable temp link polling */
9883 	if (status == I40E_SUCCESS) {
9884 		clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9885 	} else {
9886 		/* Enable link polling temporarily until i40e_get_link_status
9887 		 * returns I40E_SUCCESS
9888 		 */
9889 		set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9890 		dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9891 			status);
9892 		return;
9893 	}
9894 
9895 	old_link_speed = pf->hw.phy.link_info_old.link_speed;
9896 	new_link_speed = pf->hw.phy.link_info.link_speed;
9897 
9898 	if (new_link == old_link &&
9899 	    new_link_speed == old_link_speed &&
9900 	    (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9901 	     new_link == netif_carrier_ok(vsi->netdev)))
9902 		return;
9903 
9904 	i40e_print_link_message(vsi, new_link);
9905 
9906 	/* Notify the base of the switch tree connected to
9907 	 * the link.  Floating VEBs are not notified.
9908 	 */
9909 	if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
9910 		i40e_veb_link_event(pf->veb[pf->lan_veb], new_link);
9911 	else
9912 		i40e_vsi_link_event(vsi, new_link);
9913 
9914 	if (pf->vf)
9915 		i40e_vc_notify_link_state(pf);
9916 
9917 	if (pf->flags & I40E_FLAG_PTP)
9918 		i40e_ptp_set_increment(pf);
9919 #ifdef CONFIG_I40E_DCB
9920 	if (new_link == old_link)
9921 		return;
9922 	/* Not SW DCB so firmware will take care of default settings */
9923 	if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED)
9924 		return;
9925 
9926 	/* We cover here only link down, as after link up in case of SW DCB
9927 	 * SW LLDP agent will take care of setting it up
9928 	 */
9929 	if (!new_link) {
9930 		dev_dbg(&pf->pdev->dev, "Reconfig DCB to single TC as result of Link Down\n");
9931 		memset(&pf->tmp_cfg, 0, sizeof(pf->tmp_cfg));
9932 		err = i40e_dcb_sw_default_config(pf);
9933 		if (err) {
9934 			pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
9935 				       I40E_FLAG_DCB_ENABLED);
9936 		} else {
9937 			pf->dcbx_cap = DCB_CAP_DCBX_HOST |
9938 				       DCB_CAP_DCBX_VER_IEEE;
9939 			pf->flags |= I40E_FLAG_DCB_CAPABLE;
9940 			pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9941 		}
9942 	}
9943 #endif /* CONFIG_I40E_DCB */
9944 }
9945 
9946 /**
9947  * i40e_watchdog_subtask - periodic checks not using event driven response
9948  * @pf: board private structure
9949  **/
9950 static void i40e_watchdog_subtask(struct i40e_pf *pf)
9951 {
9952 	int i;
9953 
9954 	/* if interface is down do nothing */
9955 	if (test_bit(__I40E_DOWN, pf->state) ||
9956 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
9957 		return;
9958 
9959 	/* make sure we don't do these things too often */
9960 	if (time_before(jiffies, (pf->service_timer_previous +
9961 				  pf->service_timer_period)))
9962 		return;
9963 	pf->service_timer_previous = jiffies;
9964 
9965 	if ((pf->flags & I40E_FLAG_LINK_POLLING_ENABLED) ||
9966 	    test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
9967 		i40e_link_event(pf);
9968 
9969 	/* Update the stats for active netdevs so the network stack
9970 	 * can look at updated numbers whenever it cares to
9971 	 */
9972 	for (i = 0; i < pf->num_alloc_vsi; i++)
9973 		if (pf->vsi[i] && pf->vsi[i]->netdev)
9974 			i40e_update_stats(pf->vsi[i]);
9975 
9976 	if (pf->flags & I40E_FLAG_VEB_STATS_ENABLED) {
9977 		/* Update the stats for the active switching components */
9978 		for (i = 0; i < I40E_MAX_VEB; i++)
9979 			if (pf->veb[i])
9980 				i40e_update_veb_stats(pf->veb[i]);
9981 	}
9982 
9983 	i40e_ptp_rx_hang(pf);
9984 	i40e_ptp_tx_hang(pf);
9985 }
9986 
9987 /**
9988  * i40e_reset_subtask - Set up for resetting the device and driver
9989  * @pf: board private structure
9990  **/
9991 static void i40e_reset_subtask(struct i40e_pf *pf)
9992 {
9993 	u32 reset_flags = 0;
9994 
9995 	if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
9996 		reset_flags |= BIT(__I40E_REINIT_REQUESTED);
9997 		clear_bit(__I40E_REINIT_REQUESTED, pf->state);
9998 	}
9999 	if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
10000 		reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
10001 		clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
10002 	}
10003 	if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
10004 		reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
10005 		clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
10006 	}
10007 	if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
10008 		reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
10009 		clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
10010 	}
10011 	if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
10012 		reset_flags |= BIT(__I40E_DOWN_REQUESTED);
10013 		clear_bit(__I40E_DOWN_REQUESTED, pf->state);
10014 	}
10015 
10016 	/* If there's a recovery already waiting, it takes
10017 	 * precedence before starting a new reset sequence.
10018 	 */
10019 	if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
10020 		i40e_prep_for_reset(pf);
10021 		i40e_reset(pf);
10022 		i40e_rebuild(pf, false, false);
10023 	}
10024 
10025 	/* If we're already down or resetting, just bail */
10026 	if (reset_flags &&
10027 	    !test_bit(__I40E_DOWN, pf->state) &&
10028 	    !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
10029 		i40e_do_reset(pf, reset_flags, false);
10030 	}
10031 }
10032 
10033 /**
10034  * i40e_handle_link_event - Handle link event
10035  * @pf: board private structure
10036  * @e: event info posted on ARQ
10037  **/
10038 static void i40e_handle_link_event(struct i40e_pf *pf,
10039 				   struct i40e_arq_event_info *e)
10040 {
10041 	struct i40e_aqc_get_link_status *status =
10042 		(struct i40e_aqc_get_link_status *)&e->desc.params.raw;
10043 
10044 	/* Do a new status request to re-enable LSE reporting
10045 	 * and load new status information into the hw struct
10046 	 * This completely ignores any state information
10047 	 * in the ARQ event info, instead choosing to always
10048 	 * issue the AQ update link status command.
10049 	 */
10050 	i40e_link_event(pf);
10051 
10052 	/* Check if module meets thermal requirements */
10053 	if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
10054 		dev_err(&pf->pdev->dev,
10055 			"Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
10056 		dev_err(&pf->pdev->dev,
10057 			"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10058 	} else {
10059 		/* check for unqualified module, if link is down, suppress
10060 		 * the message if link was forced to be down.
10061 		 */
10062 		if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
10063 		    (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
10064 		    (!(status->link_info & I40E_AQ_LINK_UP)) &&
10065 		    (!(pf->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED))) {
10066 			dev_err(&pf->pdev->dev,
10067 				"Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
10068 			dev_err(&pf->pdev->dev,
10069 				"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10070 		}
10071 	}
10072 }
10073 
10074 /**
10075  * i40e_clean_adminq_subtask - Clean the AdminQ rings
10076  * @pf: board private structure
10077  **/
10078 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
10079 {
10080 	struct i40e_arq_event_info event;
10081 	struct i40e_hw *hw = &pf->hw;
10082 	u16 pending, i = 0;
10083 	i40e_status ret;
10084 	u16 opcode;
10085 	u32 oldval;
10086 	u32 val;
10087 
10088 	/* Do not run clean AQ when PF reset fails */
10089 	if (test_bit(__I40E_RESET_FAILED, pf->state))
10090 		return;
10091 
10092 	/* check for error indications */
10093 	val = rd32(&pf->hw, pf->hw.aq.arq.len);
10094 	oldval = val;
10095 	if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
10096 		if (hw->debug_mask & I40E_DEBUG_AQ)
10097 			dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
10098 		val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
10099 	}
10100 	if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
10101 		if (hw->debug_mask & I40E_DEBUG_AQ)
10102 			dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
10103 		val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
10104 		pf->arq_overflows++;
10105 	}
10106 	if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
10107 		if (hw->debug_mask & I40E_DEBUG_AQ)
10108 			dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
10109 		val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
10110 	}
10111 	if (oldval != val)
10112 		wr32(&pf->hw, pf->hw.aq.arq.len, val);
10113 
10114 	val = rd32(&pf->hw, pf->hw.aq.asq.len);
10115 	oldval = val;
10116 	if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
10117 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10118 			dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
10119 		val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
10120 	}
10121 	if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
10122 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10123 			dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
10124 		val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
10125 	}
10126 	if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
10127 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10128 			dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
10129 		val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
10130 	}
10131 	if (oldval != val)
10132 		wr32(&pf->hw, pf->hw.aq.asq.len, val);
10133 
10134 	event.buf_len = I40E_MAX_AQ_BUF_SIZE;
10135 	event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
10136 	if (!event.msg_buf)
10137 		return;
10138 
10139 	do {
10140 		ret = i40e_clean_arq_element(hw, &event, &pending);
10141 		if (ret == I40E_ERR_ADMIN_QUEUE_NO_WORK)
10142 			break;
10143 		else if (ret) {
10144 			dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
10145 			break;
10146 		}
10147 
10148 		opcode = le16_to_cpu(event.desc.opcode);
10149 		switch (opcode) {
10150 
10151 		case i40e_aqc_opc_get_link_status:
10152 			rtnl_lock();
10153 			i40e_handle_link_event(pf, &event);
10154 			rtnl_unlock();
10155 			break;
10156 		case i40e_aqc_opc_send_msg_to_pf:
10157 			ret = i40e_vc_process_vf_msg(pf,
10158 					le16_to_cpu(event.desc.retval),
10159 					le32_to_cpu(event.desc.cookie_high),
10160 					le32_to_cpu(event.desc.cookie_low),
10161 					event.msg_buf,
10162 					event.msg_len);
10163 			break;
10164 		case i40e_aqc_opc_lldp_update_mib:
10165 			dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
10166 #ifdef CONFIG_I40E_DCB
10167 			rtnl_lock();
10168 			i40e_handle_lldp_event(pf, &event);
10169 			rtnl_unlock();
10170 #endif /* CONFIG_I40E_DCB */
10171 			break;
10172 		case i40e_aqc_opc_event_lan_overflow:
10173 			dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
10174 			i40e_handle_lan_overflow_event(pf, &event);
10175 			break;
10176 		case i40e_aqc_opc_send_msg_to_peer:
10177 			dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
10178 			break;
10179 		case i40e_aqc_opc_nvm_erase:
10180 		case i40e_aqc_opc_nvm_update:
10181 		case i40e_aqc_opc_oem_post_update:
10182 			i40e_debug(&pf->hw, I40E_DEBUG_NVM,
10183 				   "ARQ NVM operation 0x%04x completed\n",
10184 				   opcode);
10185 			break;
10186 		default:
10187 			dev_info(&pf->pdev->dev,
10188 				 "ARQ: Unknown event 0x%04x ignored\n",
10189 				 opcode);
10190 			break;
10191 		}
10192 	} while (i++ < pf->adminq_work_limit);
10193 
10194 	if (i < pf->adminq_work_limit)
10195 		clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
10196 
10197 	/* re-enable Admin queue interrupt cause */
10198 	val = rd32(hw, I40E_PFINT_ICR0_ENA);
10199 	val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
10200 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
10201 	i40e_flush(hw);
10202 
10203 	kfree(event.msg_buf);
10204 }
10205 
10206 /**
10207  * i40e_verify_eeprom - make sure eeprom is good to use
10208  * @pf: board private structure
10209  **/
10210 static void i40e_verify_eeprom(struct i40e_pf *pf)
10211 {
10212 	int err;
10213 
10214 	err = i40e_diag_eeprom_test(&pf->hw);
10215 	if (err) {
10216 		/* retry in case of garbage read */
10217 		err = i40e_diag_eeprom_test(&pf->hw);
10218 		if (err) {
10219 			dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
10220 				 err);
10221 			set_bit(__I40E_BAD_EEPROM, pf->state);
10222 		}
10223 	}
10224 
10225 	if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
10226 		dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
10227 		clear_bit(__I40E_BAD_EEPROM, pf->state);
10228 	}
10229 }
10230 
10231 /**
10232  * i40e_enable_pf_switch_lb
10233  * @pf: pointer to the PF structure
10234  *
10235  * enable switch loop back or die - no point in a return value
10236  **/
10237 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
10238 {
10239 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10240 	struct i40e_vsi_context ctxt;
10241 	int ret;
10242 
10243 	ctxt.seid = pf->main_vsi_seid;
10244 	ctxt.pf_num = pf->hw.pf_id;
10245 	ctxt.vf_num = 0;
10246 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10247 	if (ret) {
10248 		dev_info(&pf->pdev->dev,
10249 			 "couldn't get PF vsi config, err %s aq_err %s\n",
10250 			 i40e_stat_str(&pf->hw, ret),
10251 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10252 		return;
10253 	}
10254 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10255 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10256 	ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10257 
10258 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10259 	if (ret) {
10260 		dev_info(&pf->pdev->dev,
10261 			 "update vsi switch failed, err %s aq_err %s\n",
10262 			 i40e_stat_str(&pf->hw, ret),
10263 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10264 	}
10265 }
10266 
10267 /**
10268  * i40e_disable_pf_switch_lb
10269  * @pf: pointer to the PF structure
10270  *
10271  * disable switch loop back or die - no point in a return value
10272  **/
10273 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
10274 {
10275 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10276 	struct i40e_vsi_context ctxt;
10277 	int ret;
10278 
10279 	ctxt.seid = pf->main_vsi_seid;
10280 	ctxt.pf_num = pf->hw.pf_id;
10281 	ctxt.vf_num = 0;
10282 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10283 	if (ret) {
10284 		dev_info(&pf->pdev->dev,
10285 			 "couldn't get PF vsi config, err %s aq_err %s\n",
10286 			 i40e_stat_str(&pf->hw, ret),
10287 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10288 		return;
10289 	}
10290 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10291 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10292 	ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10293 
10294 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10295 	if (ret) {
10296 		dev_info(&pf->pdev->dev,
10297 			 "update vsi switch failed, err %s aq_err %s\n",
10298 			 i40e_stat_str(&pf->hw, ret),
10299 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10300 	}
10301 }
10302 
10303 /**
10304  * i40e_config_bridge_mode - Configure the HW bridge mode
10305  * @veb: pointer to the bridge instance
10306  *
10307  * Configure the loop back mode for the LAN VSI that is downlink to the
10308  * specified HW bridge instance. It is expected this function is called
10309  * when a new HW bridge is instantiated.
10310  **/
10311 static void i40e_config_bridge_mode(struct i40e_veb *veb)
10312 {
10313 	struct i40e_pf *pf = veb->pf;
10314 
10315 	if (pf->hw.debug_mask & I40E_DEBUG_LAN)
10316 		dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
10317 			 veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
10318 	if (veb->bridge_mode & BRIDGE_MODE_VEPA)
10319 		i40e_disable_pf_switch_lb(pf);
10320 	else
10321 		i40e_enable_pf_switch_lb(pf);
10322 }
10323 
10324 /**
10325  * i40e_reconstitute_veb - rebuild the VEB and anything connected to it
10326  * @veb: pointer to the VEB instance
10327  *
10328  * This is a recursive function that first builds the attached VSIs then
10329  * recurses in to build the next layer of VEB.  We track the connections
10330  * through our own index numbers because the seid's from the HW could
10331  * change across the reset.
10332  **/
10333 static int i40e_reconstitute_veb(struct i40e_veb *veb)
10334 {
10335 	struct i40e_vsi *ctl_vsi = NULL;
10336 	struct i40e_pf *pf = veb->pf;
10337 	int v, veb_idx;
10338 	int ret;
10339 
10340 	/* build VSI that owns this VEB, temporarily attached to base VEB */
10341 	for (v = 0; v < pf->num_alloc_vsi && !ctl_vsi; v++) {
10342 		if (pf->vsi[v] &&
10343 		    pf->vsi[v]->veb_idx == veb->idx &&
10344 		    pf->vsi[v]->flags & I40E_VSI_FLAG_VEB_OWNER) {
10345 			ctl_vsi = pf->vsi[v];
10346 			break;
10347 		}
10348 	}
10349 	if (!ctl_vsi) {
10350 		dev_info(&pf->pdev->dev,
10351 			 "missing owner VSI for veb_idx %d\n", veb->idx);
10352 		ret = -ENOENT;
10353 		goto end_reconstitute;
10354 	}
10355 	if (ctl_vsi != pf->vsi[pf->lan_vsi])
10356 		ctl_vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
10357 	ret = i40e_add_vsi(ctl_vsi);
10358 	if (ret) {
10359 		dev_info(&pf->pdev->dev,
10360 			 "rebuild of veb_idx %d owner VSI failed: %d\n",
10361 			 veb->idx, ret);
10362 		goto end_reconstitute;
10363 	}
10364 	i40e_vsi_reset_stats(ctl_vsi);
10365 
10366 	/* create the VEB in the switch and move the VSI onto the VEB */
10367 	ret = i40e_add_veb(veb, ctl_vsi);
10368 	if (ret)
10369 		goto end_reconstitute;
10370 
10371 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
10372 		veb->bridge_mode = BRIDGE_MODE_VEB;
10373 	else
10374 		veb->bridge_mode = BRIDGE_MODE_VEPA;
10375 	i40e_config_bridge_mode(veb);
10376 
10377 	/* create the remaining VSIs attached to this VEB */
10378 	for (v = 0; v < pf->num_alloc_vsi; v++) {
10379 		if (!pf->vsi[v] || pf->vsi[v] == ctl_vsi)
10380 			continue;
10381 
10382 		if (pf->vsi[v]->veb_idx == veb->idx) {
10383 			struct i40e_vsi *vsi = pf->vsi[v];
10384 
10385 			vsi->uplink_seid = veb->seid;
10386 			ret = i40e_add_vsi(vsi);
10387 			if (ret) {
10388 				dev_info(&pf->pdev->dev,
10389 					 "rebuild of vsi_idx %d failed: %d\n",
10390 					 v, ret);
10391 				goto end_reconstitute;
10392 			}
10393 			i40e_vsi_reset_stats(vsi);
10394 		}
10395 	}
10396 
10397 	/* create any VEBs attached to this VEB - RECURSION */
10398 	for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
10399 		if (pf->veb[veb_idx] && pf->veb[veb_idx]->veb_idx == veb->idx) {
10400 			pf->veb[veb_idx]->uplink_seid = veb->seid;
10401 			ret = i40e_reconstitute_veb(pf->veb[veb_idx]);
10402 			if (ret)
10403 				break;
10404 		}
10405 	}
10406 
10407 end_reconstitute:
10408 	return ret;
10409 }
10410 
10411 /**
10412  * i40e_get_capabilities - get info about the HW
10413  * @pf: the PF struct
10414  * @list_type: AQ capability to be queried
10415  **/
10416 static int i40e_get_capabilities(struct i40e_pf *pf,
10417 				 enum i40e_admin_queue_opc list_type)
10418 {
10419 	struct i40e_aqc_list_capabilities_element_resp *cap_buf;
10420 	u16 data_size;
10421 	int buf_len;
10422 	int err;
10423 
10424 	buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
10425 	do {
10426 		cap_buf = kzalloc(buf_len, GFP_KERNEL);
10427 		if (!cap_buf)
10428 			return -ENOMEM;
10429 
10430 		/* this loads the data into the hw struct for us */
10431 		err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
10432 						    &data_size, list_type,
10433 						    NULL);
10434 		/* data loaded, buffer no longer needed */
10435 		kfree(cap_buf);
10436 
10437 		if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
10438 			/* retry with a larger buffer */
10439 			buf_len = data_size;
10440 		} else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK || err) {
10441 			dev_info(&pf->pdev->dev,
10442 				 "capability discovery failed, err %s aq_err %s\n",
10443 				 i40e_stat_str(&pf->hw, err),
10444 				 i40e_aq_str(&pf->hw,
10445 					     pf->hw.aq.asq_last_status));
10446 			return -ENODEV;
10447 		}
10448 	} while (err);
10449 
10450 	if (pf->hw.debug_mask & I40E_DEBUG_USER) {
10451 		if (list_type == i40e_aqc_opc_list_func_capabilities) {
10452 			dev_info(&pf->pdev->dev,
10453 				 "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",
10454 				 pf->hw.pf_id, pf->hw.func_caps.num_vfs,
10455 				 pf->hw.func_caps.num_msix_vectors,
10456 				 pf->hw.func_caps.num_msix_vectors_vf,
10457 				 pf->hw.func_caps.fd_filters_guaranteed,
10458 				 pf->hw.func_caps.fd_filters_best_effort,
10459 				 pf->hw.func_caps.num_tx_qp,
10460 				 pf->hw.func_caps.num_vsis);
10461 		} else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
10462 			dev_info(&pf->pdev->dev,
10463 				 "switch_mode=0x%04x, function_valid=0x%08x\n",
10464 				 pf->hw.dev_caps.switch_mode,
10465 				 pf->hw.dev_caps.valid_functions);
10466 			dev_info(&pf->pdev->dev,
10467 				 "SR-IOV=%d, num_vfs for all function=%u\n",
10468 				 pf->hw.dev_caps.sr_iov_1_1,
10469 				 pf->hw.dev_caps.num_vfs);
10470 			dev_info(&pf->pdev->dev,
10471 				 "num_vsis=%u, num_rx:%u, num_tx=%u\n",
10472 				 pf->hw.dev_caps.num_vsis,
10473 				 pf->hw.dev_caps.num_rx_qp,
10474 				 pf->hw.dev_caps.num_tx_qp);
10475 		}
10476 	}
10477 	if (list_type == i40e_aqc_opc_list_func_capabilities) {
10478 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
10479 		       + pf->hw.func_caps.num_vfs)
10480 		if (pf->hw.revision_id == 0 &&
10481 		    pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
10482 			dev_info(&pf->pdev->dev,
10483 				 "got num_vsis %d, setting num_vsis to %d\n",
10484 				 pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
10485 			pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
10486 		}
10487 	}
10488 	return 0;
10489 }
10490 
10491 static int i40e_vsi_clear(struct i40e_vsi *vsi);
10492 
10493 /**
10494  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
10495  * @pf: board private structure
10496  **/
10497 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
10498 {
10499 	struct i40e_vsi *vsi;
10500 
10501 	/* quick workaround for an NVM issue that leaves a critical register
10502 	 * uninitialized
10503 	 */
10504 	if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
10505 		static const u32 hkey[] = {
10506 			0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
10507 			0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
10508 			0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
10509 			0x95b3a76d};
10510 		int i;
10511 
10512 		for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
10513 			wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
10514 	}
10515 
10516 	if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
10517 		return;
10518 
10519 	/* find existing VSI and see if it needs configuring */
10520 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10521 
10522 	/* create a new VSI if none exists */
10523 	if (!vsi) {
10524 		vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR,
10525 				     pf->vsi[pf->lan_vsi]->seid, 0);
10526 		if (!vsi) {
10527 			dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
10528 			pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
10529 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
10530 			return;
10531 		}
10532 	}
10533 
10534 	i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
10535 }
10536 
10537 /**
10538  * i40e_fdir_teardown - release the Flow Director resources
10539  * @pf: board private structure
10540  **/
10541 static void i40e_fdir_teardown(struct i40e_pf *pf)
10542 {
10543 	struct i40e_vsi *vsi;
10544 
10545 	i40e_fdir_filter_exit(pf);
10546 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10547 	if (vsi)
10548 		i40e_vsi_release(vsi);
10549 }
10550 
10551 /**
10552  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
10553  * @vsi: PF main vsi
10554  * @seid: seid of main or channel VSIs
10555  *
10556  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
10557  * existed before reset
10558  **/
10559 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
10560 {
10561 	struct i40e_cloud_filter *cfilter;
10562 	struct i40e_pf *pf = vsi->back;
10563 	struct hlist_node *node;
10564 	i40e_status ret;
10565 
10566 	/* Add cloud filters back if they exist */
10567 	hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
10568 				  cloud_node) {
10569 		if (cfilter->seid != seid)
10570 			continue;
10571 
10572 		if (cfilter->dst_port)
10573 			ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
10574 								true);
10575 		else
10576 			ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
10577 
10578 		if (ret) {
10579 			dev_dbg(&pf->pdev->dev,
10580 				"Failed to rebuild cloud filter, err %s aq_err %s\n",
10581 				i40e_stat_str(&pf->hw, ret),
10582 				i40e_aq_str(&pf->hw,
10583 					    pf->hw.aq.asq_last_status));
10584 			return ret;
10585 		}
10586 	}
10587 	return 0;
10588 }
10589 
10590 /**
10591  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
10592  * @vsi: PF main vsi
10593  *
10594  * Rebuilds channel VSIs if they existed before reset
10595  **/
10596 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
10597 {
10598 	struct i40e_channel *ch, *ch_tmp;
10599 	i40e_status ret;
10600 
10601 	if (list_empty(&vsi->ch_list))
10602 		return 0;
10603 
10604 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
10605 		if (!ch->initialized)
10606 			break;
10607 		/* Proceed with creation of channel (VMDq2) VSI */
10608 		ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
10609 		if (ret) {
10610 			dev_info(&vsi->back->pdev->dev,
10611 				 "failed to rebuild channels using uplink_seid %u\n",
10612 				 vsi->uplink_seid);
10613 			return ret;
10614 		}
10615 		/* Reconfigure TX queues using QTX_CTL register */
10616 		ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
10617 		if (ret) {
10618 			dev_info(&vsi->back->pdev->dev,
10619 				 "failed to configure TX rings for channel %u\n",
10620 				 ch->seid);
10621 			return ret;
10622 		}
10623 		/* update 'next_base_queue' */
10624 		vsi->next_base_queue = vsi->next_base_queue +
10625 							ch->num_queue_pairs;
10626 		if (ch->max_tx_rate) {
10627 			u64 credits = ch->max_tx_rate;
10628 
10629 			if (i40e_set_bw_limit(vsi, ch->seid,
10630 					      ch->max_tx_rate))
10631 				return -EINVAL;
10632 
10633 			do_div(credits, I40E_BW_CREDIT_DIVISOR);
10634 			dev_dbg(&vsi->back->pdev->dev,
10635 				"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10636 				ch->max_tx_rate,
10637 				credits,
10638 				ch->seid);
10639 		}
10640 		ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
10641 		if (ret) {
10642 			dev_dbg(&vsi->back->pdev->dev,
10643 				"Failed to rebuild cloud filters for channel VSI %u\n",
10644 				ch->seid);
10645 			return ret;
10646 		}
10647 	}
10648 	return 0;
10649 }
10650 
10651 /**
10652  * i40e_prep_for_reset - prep for the core to reset
10653  * @pf: board private structure
10654  *
10655  * Close up the VFs and other things in prep for PF Reset.
10656   **/
10657 static void i40e_prep_for_reset(struct i40e_pf *pf)
10658 {
10659 	struct i40e_hw *hw = &pf->hw;
10660 	i40e_status ret = 0;
10661 	u32 v;
10662 
10663 	clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
10664 	if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
10665 		return;
10666 	if (i40e_check_asq_alive(&pf->hw))
10667 		i40e_vc_notify_reset(pf);
10668 
10669 	dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
10670 
10671 	/* quiesce the VSIs and their queues that are not already DOWN */
10672 	i40e_pf_quiesce_all_vsi(pf);
10673 
10674 	for (v = 0; v < pf->num_alloc_vsi; v++) {
10675 		if (pf->vsi[v])
10676 			pf->vsi[v]->seid = 0;
10677 	}
10678 
10679 	i40e_shutdown_adminq(&pf->hw);
10680 
10681 	/* call shutdown HMC */
10682 	if (hw->hmc.hmc_obj) {
10683 		ret = i40e_shutdown_lan_hmc(hw);
10684 		if (ret)
10685 			dev_warn(&pf->pdev->dev,
10686 				 "shutdown_lan_hmc failed: %d\n", ret);
10687 	}
10688 
10689 	/* Save the current PTP time so that we can restore the time after the
10690 	 * reset completes.
10691 	 */
10692 	i40e_ptp_save_hw_time(pf);
10693 }
10694 
10695 /**
10696  * i40e_send_version - update firmware with driver version
10697  * @pf: PF struct
10698  */
10699 static void i40e_send_version(struct i40e_pf *pf)
10700 {
10701 	struct i40e_driver_version dv;
10702 
10703 	dv.major_version = 0xff;
10704 	dv.minor_version = 0xff;
10705 	dv.build_version = 0xff;
10706 	dv.subbuild_version = 0;
10707 	strlcpy(dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string));
10708 	i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
10709 }
10710 
10711 /**
10712  * i40e_get_oem_version - get OEM specific version information
10713  * @hw: pointer to the hardware structure
10714  **/
10715 static void i40e_get_oem_version(struct i40e_hw *hw)
10716 {
10717 	u16 block_offset = 0xffff;
10718 	u16 block_length = 0;
10719 	u16 capabilities = 0;
10720 	u16 gen_snap = 0;
10721 	u16 release = 0;
10722 
10723 #define I40E_SR_NVM_OEM_VERSION_PTR		0x1B
10724 #define I40E_NVM_OEM_LENGTH_OFFSET		0x00
10725 #define I40E_NVM_OEM_CAPABILITIES_OFFSET	0x01
10726 #define I40E_NVM_OEM_GEN_OFFSET			0x02
10727 #define I40E_NVM_OEM_RELEASE_OFFSET		0x03
10728 #define I40E_NVM_OEM_CAPABILITIES_MASK		0x000F
10729 #define I40E_NVM_OEM_LENGTH			3
10730 
10731 	/* Check if pointer to OEM version block is valid. */
10732 	i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
10733 	if (block_offset == 0xffff)
10734 		return;
10735 
10736 	/* Check if OEM version block has correct length. */
10737 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
10738 			   &block_length);
10739 	if (block_length < I40E_NVM_OEM_LENGTH)
10740 		return;
10741 
10742 	/* Check if OEM version format is as expected. */
10743 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
10744 			   &capabilities);
10745 	if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
10746 		return;
10747 
10748 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
10749 			   &gen_snap);
10750 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
10751 			   &release);
10752 	hw->nvm.oem_ver = (gen_snap << I40E_OEM_SNAP_SHIFT) | release;
10753 	hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
10754 }
10755 
10756 /**
10757  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
10758  * @pf: board private structure
10759  **/
10760 static int i40e_reset(struct i40e_pf *pf)
10761 {
10762 	struct i40e_hw *hw = &pf->hw;
10763 	i40e_status ret;
10764 
10765 	ret = i40e_pf_reset(hw);
10766 	if (ret) {
10767 		dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
10768 		set_bit(__I40E_RESET_FAILED, pf->state);
10769 		clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10770 	} else {
10771 		pf->pfr_count++;
10772 	}
10773 	return ret;
10774 }
10775 
10776 /**
10777  * i40e_rebuild - rebuild using a saved config
10778  * @pf: board private structure
10779  * @reinit: if the Main VSI needs to re-initialized.
10780  * @lock_acquired: indicates whether or not the lock has been acquired
10781  * before this function was called.
10782  **/
10783 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
10784 {
10785 	const bool is_recovery_mode_reported = i40e_check_recovery_mode(pf);
10786 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10787 	struct i40e_hw *hw = &pf->hw;
10788 	i40e_status ret;
10789 	u32 val;
10790 	int v;
10791 
10792 	if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10793 	    is_recovery_mode_reported)
10794 		i40e_set_ethtool_ops(pf->vsi[pf->lan_vsi]->netdev);
10795 
10796 	if (test_bit(__I40E_DOWN, pf->state) &&
10797 	    !test_bit(__I40E_RECOVERY_MODE, pf->state))
10798 		goto clear_recovery;
10799 	dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
10800 
10801 	/* rebuild the basics for the AdminQ, HMC, and initial HW switch */
10802 	ret = i40e_init_adminq(&pf->hw);
10803 	if (ret) {
10804 		dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %s aq_err %s\n",
10805 			 i40e_stat_str(&pf->hw, ret),
10806 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10807 		goto clear_recovery;
10808 	}
10809 	i40e_get_oem_version(&pf->hw);
10810 
10811 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state)) {
10812 		/* The following delay is necessary for firmware update. */
10813 		mdelay(1000);
10814 	}
10815 
10816 	/* re-verify the eeprom if we just had an EMP reset */
10817 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
10818 		i40e_verify_eeprom(pf);
10819 
10820 	/* if we are going out of or into recovery mode we have to act
10821 	 * accordingly with regard to resources initialization
10822 	 * and deinitialization
10823 	 */
10824 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10825 		if (i40e_get_capabilities(pf,
10826 					  i40e_aqc_opc_list_func_capabilities))
10827 			goto end_unlock;
10828 
10829 		if (is_recovery_mode_reported) {
10830 			/* we're staying in recovery mode so we'll reinitialize
10831 			 * misc vector here
10832 			 */
10833 			if (i40e_setup_misc_vector_for_recovery_mode(pf))
10834 				goto end_unlock;
10835 		} else {
10836 			if (!lock_acquired)
10837 				rtnl_lock();
10838 			/* we're going out of recovery mode so we'll free
10839 			 * the IRQ allocated specifically for recovery mode
10840 			 * and restore the interrupt scheme
10841 			 */
10842 			free_irq(pf->pdev->irq, pf);
10843 			i40e_clear_interrupt_scheme(pf);
10844 			if (i40e_restore_interrupt_scheme(pf))
10845 				goto end_unlock;
10846 		}
10847 
10848 		/* tell the firmware that we're starting */
10849 		i40e_send_version(pf);
10850 
10851 		/* bail out in case recovery mode was detected, as there is
10852 		 * no need for further configuration.
10853 		 */
10854 		goto end_unlock;
10855 	}
10856 
10857 	i40e_clear_pxe_mode(hw);
10858 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10859 	if (ret)
10860 		goto end_core_reset;
10861 
10862 	ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10863 				hw->func_caps.num_rx_qp, 0, 0);
10864 	if (ret) {
10865 		dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10866 		goto end_core_reset;
10867 	}
10868 	ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10869 	if (ret) {
10870 		dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10871 		goto end_core_reset;
10872 	}
10873 
10874 #ifdef CONFIG_I40E_DCB
10875 	/* Enable FW to write a default DCB config on link-up
10876 	 * unless I40E_FLAG_TC_MQPRIO was enabled or DCB
10877 	 * is not supported with new link speed
10878 	 */
10879 	if (i40e_is_tc_mqprio_enabled(pf)) {
10880 		i40e_aq_set_dcb_parameters(hw, false, NULL);
10881 	} else {
10882 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
10883 		    (hw->phy.link_info.link_speed &
10884 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
10885 			i40e_aq_set_dcb_parameters(hw, false, NULL);
10886 			dev_warn(&pf->pdev->dev,
10887 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
10888 			pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10889 		} else {
10890 			i40e_aq_set_dcb_parameters(hw, true, NULL);
10891 			ret = i40e_init_pf_dcb(pf);
10892 			if (ret) {
10893 				dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n",
10894 					 ret);
10895 				pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10896 				/* Continue without DCB enabled */
10897 			}
10898 		}
10899 	}
10900 
10901 #endif /* CONFIG_I40E_DCB */
10902 	if (!lock_acquired)
10903 		rtnl_lock();
10904 	ret = i40e_setup_pf_switch(pf, reinit, true);
10905 	if (ret)
10906 		goto end_unlock;
10907 
10908 	/* The driver only wants link up/down and module qualification
10909 	 * reports from firmware.  Note the negative logic.
10910 	 */
10911 	ret = i40e_aq_set_phy_int_mask(&pf->hw,
10912 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
10913 					 I40E_AQ_EVENT_MEDIA_NA |
10914 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10915 	if (ret)
10916 		dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
10917 			 i40e_stat_str(&pf->hw, ret),
10918 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10919 
10920 	/* Rebuild the VSIs and VEBs that existed before reset.
10921 	 * They are still in our local switch element arrays, so only
10922 	 * need to rebuild the switch model in the HW.
10923 	 *
10924 	 * If there were VEBs but the reconstitution failed, we'll try
10925 	 * to recover minimal use by getting the basic PF VSI working.
10926 	 */
10927 	if (vsi->uplink_seid != pf->mac_seid) {
10928 		dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
10929 		/* find the one VEB connected to the MAC, and find orphans */
10930 		for (v = 0; v < I40E_MAX_VEB; v++) {
10931 			if (!pf->veb[v])
10932 				continue;
10933 
10934 			if (pf->veb[v]->uplink_seid == pf->mac_seid ||
10935 			    pf->veb[v]->uplink_seid == 0) {
10936 				ret = i40e_reconstitute_veb(pf->veb[v]);
10937 
10938 				if (!ret)
10939 					continue;
10940 
10941 				/* If Main VEB failed, we're in deep doodoo,
10942 				 * so give up rebuilding the switch and set up
10943 				 * for minimal rebuild of PF VSI.
10944 				 * If orphan failed, we'll report the error
10945 				 * but try to keep going.
10946 				 */
10947 				if (pf->veb[v]->uplink_seid == pf->mac_seid) {
10948 					dev_info(&pf->pdev->dev,
10949 						 "rebuild of switch failed: %d, will try to set up simple PF connection\n",
10950 						 ret);
10951 					vsi->uplink_seid = pf->mac_seid;
10952 					break;
10953 				} else if (pf->veb[v]->uplink_seid == 0) {
10954 					dev_info(&pf->pdev->dev,
10955 						 "rebuild of orphan VEB failed: %d\n",
10956 						 ret);
10957 				}
10958 			}
10959 		}
10960 	}
10961 
10962 	if (vsi->uplink_seid == pf->mac_seid) {
10963 		dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
10964 		/* no VEB, so rebuild only the Main VSI */
10965 		ret = i40e_add_vsi(vsi);
10966 		if (ret) {
10967 			dev_info(&pf->pdev->dev,
10968 				 "rebuild of Main VSI failed: %d\n", ret);
10969 			goto end_unlock;
10970 		}
10971 	}
10972 
10973 	if (vsi->mqprio_qopt.max_rate[0]) {
10974 		u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0];
10975 		u64 credits = 0;
10976 
10977 		do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
10978 		ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
10979 		if (ret)
10980 			goto end_unlock;
10981 
10982 		credits = max_tx_rate;
10983 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
10984 		dev_dbg(&vsi->back->pdev->dev,
10985 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10986 			max_tx_rate,
10987 			credits,
10988 			vsi->seid);
10989 	}
10990 
10991 	ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
10992 	if (ret)
10993 		goto end_unlock;
10994 
10995 	/* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
10996 	 * for this main VSI if they exist
10997 	 */
10998 	ret = i40e_rebuild_channels(vsi);
10999 	if (ret)
11000 		goto end_unlock;
11001 
11002 	/* Reconfigure hardware for allowing smaller MSS in the case
11003 	 * of TSO, so that we avoid the MDD being fired and causing
11004 	 * a reset in the case of small MSS+TSO.
11005 	 */
11006 #define I40E_REG_MSS          0x000E64DC
11007 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
11008 #define I40E_64BYTE_MSS       0x400000
11009 	val = rd32(hw, I40E_REG_MSS);
11010 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
11011 		val &= ~I40E_REG_MSS_MIN_MASK;
11012 		val |= I40E_64BYTE_MSS;
11013 		wr32(hw, I40E_REG_MSS, val);
11014 	}
11015 
11016 	if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
11017 		msleep(75);
11018 		ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
11019 		if (ret)
11020 			dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
11021 				 i40e_stat_str(&pf->hw, ret),
11022 				 i40e_aq_str(&pf->hw,
11023 					     pf->hw.aq.asq_last_status));
11024 	}
11025 	/* reinit the misc interrupt */
11026 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11027 		ret = i40e_setup_misc_vector(pf);
11028 
11029 	/* Add a filter to drop all Flow control frames from any VSI from being
11030 	 * transmitted. By doing so we stop a malicious VF from sending out
11031 	 * PAUSE or PFC frames and potentially controlling traffic for other
11032 	 * PF/VF VSIs.
11033 	 * The FW can still send Flow control frames if enabled.
11034 	 */
11035 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
11036 						       pf->main_vsi_seid);
11037 
11038 	/* restart the VSIs that were rebuilt and running before the reset */
11039 	i40e_pf_unquiesce_all_vsi(pf);
11040 
11041 	/* Release the RTNL lock before we start resetting VFs */
11042 	if (!lock_acquired)
11043 		rtnl_unlock();
11044 
11045 	/* Restore promiscuous settings */
11046 	ret = i40e_set_promiscuous(pf, pf->cur_promisc);
11047 	if (ret)
11048 		dev_warn(&pf->pdev->dev,
11049 			 "Failed to restore promiscuous setting: %s, err %s aq_err %s\n",
11050 			 pf->cur_promisc ? "on" : "off",
11051 			 i40e_stat_str(&pf->hw, ret),
11052 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11053 
11054 	i40e_reset_all_vfs(pf, true);
11055 
11056 	/* tell the firmware that we're starting */
11057 	i40e_send_version(pf);
11058 
11059 	/* We've already released the lock, so don't do it again */
11060 	goto end_core_reset;
11061 
11062 end_unlock:
11063 	if (!lock_acquired)
11064 		rtnl_unlock();
11065 end_core_reset:
11066 	clear_bit(__I40E_RESET_FAILED, pf->state);
11067 clear_recovery:
11068 	clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
11069 	clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
11070 }
11071 
11072 /**
11073  * i40e_reset_and_rebuild - reset and rebuild using a saved config
11074  * @pf: board private structure
11075  * @reinit: if the Main VSI needs to re-initialized.
11076  * @lock_acquired: indicates whether or not the lock has been acquired
11077  * before this function was called.
11078  **/
11079 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
11080 				   bool lock_acquired)
11081 {
11082 	int ret;
11083 
11084 	if (test_bit(__I40E_IN_REMOVE, pf->state))
11085 		return;
11086 	/* Now we wait for GRST to settle out.
11087 	 * We don't have to delete the VEBs or VSIs from the hw switch
11088 	 * because the reset will make them disappear.
11089 	 */
11090 	ret = i40e_reset(pf);
11091 	if (!ret)
11092 		i40e_rebuild(pf, reinit, lock_acquired);
11093 }
11094 
11095 /**
11096  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
11097  * @pf: board private structure
11098  *
11099  * Close up the VFs and other things in prep for a Core Reset,
11100  * then get ready to rebuild the world.
11101  * @lock_acquired: indicates whether or not the lock has been acquired
11102  * before this function was called.
11103  **/
11104 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
11105 {
11106 	i40e_prep_for_reset(pf);
11107 	i40e_reset_and_rebuild(pf, false, lock_acquired);
11108 }
11109 
11110 /**
11111  * i40e_handle_mdd_event
11112  * @pf: pointer to the PF structure
11113  *
11114  * Called from the MDD irq handler to identify possibly malicious vfs
11115  **/
11116 static void i40e_handle_mdd_event(struct i40e_pf *pf)
11117 {
11118 	struct i40e_hw *hw = &pf->hw;
11119 	bool mdd_detected = false;
11120 	struct i40e_vf *vf;
11121 	u32 reg;
11122 	int i;
11123 
11124 	if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
11125 		return;
11126 
11127 	/* find what triggered the MDD event */
11128 	reg = rd32(hw, I40E_GL_MDET_TX);
11129 	if (reg & I40E_GL_MDET_TX_VALID_MASK) {
11130 		u8 pf_num = (reg & I40E_GL_MDET_TX_PF_NUM_MASK) >>
11131 				I40E_GL_MDET_TX_PF_NUM_SHIFT;
11132 		u16 vf_num = (reg & I40E_GL_MDET_TX_VF_NUM_MASK) >>
11133 				I40E_GL_MDET_TX_VF_NUM_SHIFT;
11134 		u8 event = (reg & I40E_GL_MDET_TX_EVENT_MASK) >>
11135 				I40E_GL_MDET_TX_EVENT_SHIFT;
11136 		u16 queue = ((reg & I40E_GL_MDET_TX_QUEUE_MASK) >>
11137 				I40E_GL_MDET_TX_QUEUE_SHIFT) -
11138 				pf->hw.func_caps.base_queue;
11139 		if (netif_msg_tx_err(pf))
11140 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
11141 				 event, queue, pf_num, vf_num);
11142 		wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
11143 		mdd_detected = true;
11144 	}
11145 	reg = rd32(hw, I40E_GL_MDET_RX);
11146 	if (reg & I40E_GL_MDET_RX_VALID_MASK) {
11147 		u8 func = (reg & I40E_GL_MDET_RX_FUNCTION_MASK) >>
11148 				I40E_GL_MDET_RX_FUNCTION_SHIFT;
11149 		u8 event = (reg & I40E_GL_MDET_RX_EVENT_MASK) >>
11150 				I40E_GL_MDET_RX_EVENT_SHIFT;
11151 		u16 queue = ((reg & I40E_GL_MDET_RX_QUEUE_MASK) >>
11152 				I40E_GL_MDET_RX_QUEUE_SHIFT) -
11153 				pf->hw.func_caps.base_queue;
11154 		if (netif_msg_rx_err(pf))
11155 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
11156 				 event, queue, func);
11157 		wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
11158 		mdd_detected = true;
11159 	}
11160 
11161 	if (mdd_detected) {
11162 		reg = rd32(hw, I40E_PF_MDET_TX);
11163 		if (reg & I40E_PF_MDET_TX_VALID_MASK) {
11164 			wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
11165 			dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
11166 		}
11167 		reg = rd32(hw, I40E_PF_MDET_RX);
11168 		if (reg & I40E_PF_MDET_RX_VALID_MASK) {
11169 			wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
11170 			dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
11171 		}
11172 	}
11173 
11174 	/* see if one of the VFs needs its hand slapped */
11175 	for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
11176 		vf = &(pf->vf[i]);
11177 		reg = rd32(hw, I40E_VP_MDET_TX(i));
11178 		if (reg & I40E_VP_MDET_TX_VALID_MASK) {
11179 			wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
11180 			vf->num_mdd_events++;
11181 			dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
11182 				 i);
11183 			dev_info(&pf->pdev->dev,
11184 				 "Use PF Control I/F to re-enable the VF\n");
11185 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11186 		}
11187 
11188 		reg = rd32(hw, I40E_VP_MDET_RX(i));
11189 		if (reg & I40E_VP_MDET_RX_VALID_MASK) {
11190 			wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
11191 			vf->num_mdd_events++;
11192 			dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
11193 				 i);
11194 			dev_info(&pf->pdev->dev,
11195 				 "Use PF Control I/F to re-enable the VF\n");
11196 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11197 		}
11198 	}
11199 
11200 	/* re-enable mdd interrupt cause */
11201 	clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
11202 	reg = rd32(hw, I40E_PFINT_ICR0_ENA);
11203 	reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
11204 	wr32(hw, I40E_PFINT_ICR0_ENA, reg);
11205 	i40e_flush(hw);
11206 }
11207 
11208 /**
11209  * i40e_service_task - Run the driver's async subtasks
11210  * @work: pointer to work_struct containing our data
11211  **/
11212 static void i40e_service_task(struct work_struct *work)
11213 {
11214 	struct i40e_pf *pf = container_of(work,
11215 					  struct i40e_pf,
11216 					  service_task);
11217 	unsigned long start_time = jiffies;
11218 
11219 	/* don't bother with service tasks if a reset is in progress */
11220 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
11221 	    test_bit(__I40E_SUSPENDED, pf->state))
11222 		return;
11223 
11224 	if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
11225 		return;
11226 
11227 	if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
11228 		i40e_detect_recover_hung(pf->vsi[pf->lan_vsi]);
11229 		i40e_sync_filters_subtask(pf);
11230 		i40e_reset_subtask(pf);
11231 		i40e_handle_mdd_event(pf);
11232 		i40e_vc_process_vflr_event(pf);
11233 		i40e_watchdog_subtask(pf);
11234 		i40e_fdir_reinit_subtask(pf);
11235 		if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
11236 			/* Client subtask will reopen next time through. */
11237 			i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi],
11238 							   true);
11239 		} else {
11240 			i40e_client_subtask(pf);
11241 			if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
11242 					       pf->state))
11243 				i40e_notify_client_of_l2_param_changes(
11244 								pf->vsi[pf->lan_vsi]);
11245 		}
11246 		i40e_sync_filters_subtask(pf);
11247 	} else {
11248 		i40e_reset_subtask(pf);
11249 	}
11250 
11251 	i40e_clean_adminq_subtask(pf);
11252 
11253 	/* flush memory to make sure state is correct before next watchdog */
11254 	smp_mb__before_atomic();
11255 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
11256 
11257 	/* If the tasks have taken longer than one timer cycle or there
11258 	 * is more work to be done, reschedule the service task now
11259 	 * rather than wait for the timer to tick again.
11260 	 */
11261 	if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
11262 	    test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)		 ||
11263 	    test_bit(__I40E_MDD_EVENT_PENDING, pf->state)		 ||
11264 	    test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
11265 		i40e_service_event_schedule(pf);
11266 }
11267 
11268 /**
11269  * i40e_service_timer - timer callback
11270  * @t: timer list pointer
11271  **/
11272 static void i40e_service_timer(struct timer_list *t)
11273 {
11274 	struct i40e_pf *pf = from_timer(pf, t, service_timer);
11275 
11276 	mod_timer(&pf->service_timer,
11277 		  round_jiffies(jiffies + pf->service_timer_period));
11278 	i40e_service_event_schedule(pf);
11279 }
11280 
11281 /**
11282  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
11283  * @vsi: the VSI being configured
11284  **/
11285 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
11286 {
11287 	struct i40e_pf *pf = vsi->back;
11288 
11289 	switch (vsi->type) {
11290 	case I40E_VSI_MAIN:
11291 		vsi->alloc_queue_pairs = pf->num_lan_qps;
11292 		if (!vsi->num_tx_desc)
11293 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11294 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11295 		if (!vsi->num_rx_desc)
11296 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11297 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11298 		if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11299 			vsi->num_q_vectors = pf->num_lan_msix;
11300 		else
11301 			vsi->num_q_vectors = 1;
11302 
11303 		break;
11304 
11305 	case I40E_VSI_FDIR:
11306 		vsi->alloc_queue_pairs = 1;
11307 		vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11308 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11309 		vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11310 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11311 		vsi->num_q_vectors = pf->num_fdsb_msix;
11312 		break;
11313 
11314 	case I40E_VSI_VMDQ2:
11315 		vsi->alloc_queue_pairs = pf->num_vmdq_qps;
11316 		if (!vsi->num_tx_desc)
11317 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11318 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11319 		if (!vsi->num_rx_desc)
11320 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11321 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11322 		vsi->num_q_vectors = pf->num_vmdq_msix;
11323 		break;
11324 
11325 	case I40E_VSI_SRIOV:
11326 		vsi->alloc_queue_pairs = pf->num_vf_qps;
11327 		if (!vsi->num_tx_desc)
11328 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11329 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11330 		if (!vsi->num_rx_desc)
11331 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11332 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11333 		break;
11334 
11335 	default:
11336 		WARN_ON(1);
11337 		return -ENODATA;
11338 	}
11339 
11340 	if (is_kdump_kernel()) {
11341 		vsi->num_tx_desc = I40E_MIN_NUM_DESCRIPTORS;
11342 		vsi->num_rx_desc = I40E_MIN_NUM_DESCRIPTORS;
11343 	}
11344 
11345 	return 0;
11346 }
11347 
11348 /**
11349  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
11350  * @vsi: VSI pointer
11351  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
11352  *
11353  * On error: returns error code (negative)
11354  * On success: returns 0
11355  **/
11356 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
11357 {
11358 	struct i40e_ring **next_rings;
11359 	int size;
11360 	int ret = 0;
11361 
11362 	/* allocate memory for both Tx, XDP Tx and Rx ring pointers */
11363 	size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
11364 	       (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
11365 	vsi->tx_rings = kzalloc(size, GFP_KERNEL);
11366 	if (!vsi->tx_rings)
11367 		return -ENOMEM;
11368 	next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
11369 	if (i40e_enabled_xdp_vsi(vsi)) {
11370 		vsi->xdp_rings = next_rings;
11371 		next_rings += vsi->alloc_queue_pairs;
11372 	}
11373 	vsi->rx_rings = next_rings;
11374 
11375 	if (alloc_qvectors) {
11376 		/* allocate memory for q_vector pointers */
11377 		size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
11378 		vsi->q_vectors = kzalloc(size, GFP_KERNEL);
11379 		if (!vsi->q_vectors) {
11380 			ret = -ENOMEM;
11381 			goto err_vectors;
11382 		}
11383 	}
11384 	return ret;
11385 
11386 err_vectors:
11387 	kfree(vsi->tx_rings);
11388 	return ret;
11389 }
11390 
11391 /**
11392  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
11393  * @pf: board private structure
11394  * @type: type of VSI
11395  *
11396  * On error: returns error code (negative)
11397  * On success: returns vsi index in PF (positive)
11398  **/
11399 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
11400 {
11401 	int ret = -ENODEV;
11402 	struct i40e_vsi *vsi;
11403 	int vsi_idx;
11404 	int i;
11405 
11406 	/* Need to protect the allocation of the VSIs at the PF level */
11407 	mutex_lock(&pf->switch_mutex);
11408 
11409 	/* VSI list may be fragmented if VSI creation/destruction has
11410 	 * been happening.  We can afford to do a quick scan to look
11411 	 * for any free VSIs in the list.
11412 	 *
11413 	 * find next empty vsi slot, looping back around if necessary
11414 	 */
11415 	i = pf->next_vsi;
11416 	while (i < pf->num_alloc_vsi && pf->vsi[i])
11417 		i++;
11418 	if (i >= pf->num_alloc_vsi) {
11419 		i = 0;
11420 		while (i < pf->next_vsi && pf->vsi[i])
11421 			i++;
11422 	}
11423 
11424 	if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
11425 		vsi_idx = i;             /* Found one! */
11426 	} else {
11427 		ret = -ENODEV;
11428 		goto unlock_pf;  /* out of VSI slots! */
11429 	}
11430 	pf->next_vsi = ++i;
11431 
11432 	vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
11433 	if (!vsi) {
11434 		ret = -ENOMEM;
11435 		goto unlock_pf;
11436 	}
11437 	vsi->type = type;
11438 	vsi->back = pf;
11439 	set_bit(__I40E_VSI_DOWN, vsi->state);
11440 	vsi->flags = 0;
11441 	vsi->idx = vsi_idx;
11442 	vsi->int_rate_limit = 0;
11443 	vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
11444 				pf->rss_table_size : 64;
11445 	vsi->netdev_registered = false;
11446 	vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
11447 	hash_init(vsi->mac_filter_hash);
11448 	vsi->irqs_ready = false;
11449 
11450 	if (type == I40E_VSI_MAIN) {
11451 		vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
11452 		if (!vsi->af_xdp_zc_qps)
11453 			goto err_rings;
11454 	}
11455 
11456 	ret = i40e_set_num_rings_in_vsi(vsi);
11457 	if (ret)
11458 		goto err_rings;
11459 
11460 	ret = i40e_vsi_alloc_arrays(vsi, true);
11461 	if (ret)
11462 		goto err_rings;
11463 
11464 	/* Setup default MSIX irq handler for VSI */
11465 	i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
11466 
11467 	/* Initialize VSI lock */
11468 	spin_lock_init(&vsi->mac_filter_hash_lock);
11469 	pf->vsi[vsi_idx] = vsi;
11470 	ret = vsi_idx;
11471 	goto unlock_pf;
11472 
11473 err_rings:
11474 	bitmap_free(vsi->af_xdp_zc_qps);
11475 	pf->next_vsi = i - 1;
11476 	kfree(vsi);
11477 unlock_pf:
11478 	mutex_unlock(&pf->switch_mutex);
11479 	return ret;
11480 }
11481 
11482 /**
11483  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
11484  * @vsi: VSI pointer
11485  * @free_qvectors: a bool to specify if q_vectors need to be freed.
11486  *
11487  * On error: returns error code (negative)
11488  * On success: returns 0
11489  **/
11490 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
11491 {
11492 	/* free the ring and vector containers */
11493 	if (free_qvectors) {
11494 		kfree(vsi->q_vectors);
11495 		vsi->q_vectors = NULL;
11496 	}
11497 	kfree(vsi->tx_rings);
11498 	vsi->tx_rings = NULL;
11499 	vsi->rx_rings = NULL;
11500 	vsi->xdp_rings = NULL;
11501 }
11502 
11503 /**
11504  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
11505  * and lookup table
11506  * @vsi: Pointer to VSI structure
11507  */
11508 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
11509 {
11510 	if (!vsi)
11511 		return;
11512 
11513 	kfree(vsi->rss_hkey_user);
11514 	vsi->rss_hkey_user = NULL;
11515 
11516 	kfree(vsi->rss_lut_user);
11517 	vsi->rss_lut_user = NULL;
11518 }
11519 
11520 /**
11521  * i40e_vsi_clear - Deallocate the VSI provided
11522  * @vsi: the VSI being un-configured
11523  **/
11524 static int i40e_vsi_clear(struct i40e_vsi *vsi)
11525 {
11526 	struct i40e_pf *pf;
11527 
11528 	if (!vsi)
11529 		return 0;
11530 
11531 	if (!vsi->back)
11532 		goto free_vsi;
11533 	pf = vsi->back;
11534 
11535 	mutex_lock(&pf->switch_mutex);
11536 	if (!pf->vsi[vsi->idx]) {
11537 		dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
11538 			vsi->idx, vsi->idx, vsi->type);
11539 		goto unlock_vsi;
11540 	}
11541 
11542 	if (pf->vsi[vsi->idx] != vsi) {
11543 		dev_err(&pf->pdev->dev,
11544 			"pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
11545 			pf->vsi[vsi->idx]->idx,
11546 			pf->vsi[vsi->idx]->type,
11547 			vsi->idx, vsi->type);
11548 		goto unlock_vsi;
11549 	}
11550 
11551 	/* updates the PF for this cleared vsi */
11552 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
11553 	i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
11554 
11555 	bitmap_free(vsi->af_xdp_zc_qps);
11556 	i40e_vsi_free_arrays(vsi, true);
11557 	i40e_clear_rss_config_user(vsi);
11558 
11559 	pf->vsi[vsi->idx] = NULL;
11560 	if (vsi->idx < pf->next_vsi)
11561 		pf->next_vsi = vsi->idx;
11562 
11563 unlock_vsi:
11564 	mutex_unlock(&pf->switch_mutex);
11565 free_vsi:
11566 	kfree(vsi);
11567 
11568 	return 0;
11569 }
11570 
11571 /**
11572  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
11573  * @vsi: the VSI being cleaned
11574  **/
11575 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
11576 {
11577 	int i;
11578 
11579 	if (vsi->tx_rings && vsi->tx_rings[0]) {
11580 		for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11581 			kfree_rcu(vsi->tx_rings[i], rcu);
11582 			WRITE_ONCE(vsi->tx_rings[i], NULL);
11583 			WRITE_ONCE(vsi->rx_rings[i], NULL);
11584 			if (vsi->xdp_rings)
11585 				WRITE_ONCE(vsi->xdp_rings[i], NULL);
11586 		}
11587 	}
11588 }
11589 
11590 /**
11591  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
11592  * @vsi: the VSI being configured
11593  **/
11594 static int i40e_alloc_rings(struct i40e_vsi *vsi)
11595 {
11596 	int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
11597 	struct i40e_pf *pf = vsi->back;
11598 	struct i40e_ring *ring;
11599 
11600 	/* Set basic values in the rings to be used later during open() */
11601 	for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11602 		/* allocate space for both Tx and Rx in one shot */
11603 		ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
11604 		if (!ring)
11605 			goto err_out;
11606 
11607 		ring->queue_index = i;
11608 		ring->reg_idx = vsi->base_queue + i;
11609 		ring->ring_active = false;
11610 		ring->vsi = vsi;
11611 		ring->netdev = vsi->netdev;
11612 		ring->dev = &pf->pdev->dev;
11613 		ring->count = vsi->num_tx_desc;
11614 		ring->size = 0;
11615 		ring->dcb_tc = 0;
11616 		if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11617 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11618 		ring->itr_setting = pf->tx_itr_default;
11619 		WRITE_ONCE(vsi->tx_rings[i], ring++);
11620 
11621 		if (!i40e_enabled_xdp_vsi(vsi))
11622 			goto setup_rx;
11623 
11624 		ring->queue_index = vsi->alloc_queue_pairs + i;
11625 		ring->reg_idx = vsi->base_queue + ring->queue_index;
11626 		ring->ring_active = false;
11627 		ring->vsi = vsi;
11628 		ring->netdev = NULL;
11629 		ring->dev = &pf->pdev->dev;
11630 		ring->count = vsi->num_tx_desc;
11631 		ring->size = 0;
11632 		ring->dcb_tc = 0;
11633 		if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11634 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11635 		set_ring_xdp(ring);
11636 		ring->itr_setting = pf->tx_itr_default;
11637 		WRITE_ONCE(vsi->xdp_rings[i], ring++);
11638 
11639 setup_rx:
11640 		ring->queue_index = i;
11641 		ring->reg_idx = vsi->base_queue + i;
11642 		ring->ring_active = false;
11643 		ring->vsi = vsi;
11644 		ring->netdev = vsi->netdev;
11645 		ring->dev = &pf->pdev->dev;
11646 		ring->count = vsi->num_rx_desc;
11647 		ring->size = 0;
11648 		ring->dcb_tc = 0;
11649 		ring->itr_setting = pf->rx_itr_default;
11650 		WRITE_ONCE(vsi->rx_rings[i], ring);
11651 	}
11652 
11653 	return 0;
11654 
11655 err_out:
11656 	i40e_vsi_clear_rings(vsi);
11657 	return -ENOMEM;
11658 }
11659 
11660 /**
11661  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
11662  * @pf: board private structure
11663  * @vectors: the number of MSI-X vectors to request
11664  *
11665  * Returns the number of vectors reserved, or error
11666  **/
11667 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
11668 {
11669 	vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
11670 					I40E_MIN_MSIX, vectors);
11671 	if (vectors < 0) {
11672 		dev_info(&pf->pdev->dev,
11673 			 "MSI-X vector reservation failed: %d\n", vectors);
11674 		vectors = 0;
11675 	}
11676 
11677 	return vectors;
11678 }
11679 
11680 /**
11681  * i40e_init_msix - Setup the MSIX capability
11682  * @pf: board private structure
11683  *
11684  * Work with the OS to set up the MSIX vectors needed.
11685  *
11686  * Returns the number of vectors reserved or negative on failure
11687  **/
11688 static int i40e_init_msix(struct i40e_pf *pf)
11689 {
11690 	struct i40e_hw *hw = &pf->hw;
11691 	int cpus, extra_vectors;
11692 	int vectors_left;
11693 	int v_budget, i;
11694 	int v_actual;
11695 	int iwarp_requested = 0;
11696 
11697 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
11698 		return -ENODEV;
11699 
11700 	/* The number of vectors we'll request will be comprised of:
11701 	 *   - Add 1 for "other" cause for Admin Queue events, etc.
11702 	 *   - The number of LAN queue pairs
11703 	 *	- Queues being used for RSS.
11704 	 *		We don't need as many as max_rss_size vectors.
11705 	 *		use rss_size instead in the calculation since that
11706 	 *		is governed by number of cpus in the system.
11707 	 *	- assumes symmetric Tx/Rx pairing
11708 	 *   - The number of VMDq pairs
11709 	 *   - The CPU count within the NUMA node if iWARP is enabled
11710 	 * Once we count this up, try the request.
11711 	 *
11712 	 * If we can't get what we want, we'll simplify to nearly nothing
11713 	 * and try again.  If that still fails, we punt.
11714 	 */
11715 	vectors_left = hw->func_caps.num_msix_vectors;
11716 	v_budget = 0;
11717 
11718 	/* reserve one vector for miscellaneous handler */
11719 	if (vectors_left) {
11720 		v_budget++;
11721 		vectors_left--;
11722 	}
11723 
11724 	/* reserve some vectors for the main PF traffic queues. Initially we
11725 	 * only reserve at most 50% of the available vectors, in the case that
11726 	 * the number of online CPUs is large. This ensures that we can enable
11727 	 * extra features as well. Once we've enabled the other features, we
11728 	 * will use any remaining vectors to reach as close as we can to the
11729 	 * number of online CPUs.
11730 	 */
11731 	cpus = num_online_cpus();
11732 	pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
11733 	vectors_left -= pf->num_lan_msix;
11734 
11735 	/* reserve one vector for sideband flow director */
11736 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11737 		if (vectors_left) {
11738 			pf->num_fdsb_msix = 1;
11739 			v_budget++;
11740 			vectors_left--;
11741 		} else {
11742 			pf->num_fdsb_msix = 0;
11743 		}
11744 	}
11745 
11746 	/* can we reserve enough for iWARP? */
11747 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11748 		iwarp_requested = pf->num_iwarp_msix;
11749 
11750 		if (!vectors_left)
11751 			pf->num_iwarp_msix = 0;
11752 		else if (vectors_left < pf->num_iwarp_msix)
11753 			pf->num_iwarp_msix = 1;
11754 		v_budget += pf->num_iwarp_msix;
11755 		vectors_left -= pf->num_iwarp_msix;
11756 	}
11757 
11758 	/* any vectors left over go for VMDq support */
11759 	if (pf->flags & I40E_FLAG_VMDQ_ENABLED) {
11760 		if (!vectors_left) {
11761 			pf->num_vmdq_msix = 0;
11762 			pf->num_vmdq_qps = 0;
11763 		} else {
11764 			int vmdq_vecs_wanted =
11765 				pf->num_vmdq_vsis * pf->num_vmdq_qps;
11766 			int vmdq_vecs =
11767 				min_t(int, vectors_left, vmdq_vecs_wanted);
11768 
11769 			/* if we're short on vectors for what's desired, we limit
11770 			 * the queues per vmdq.  If this is still more than are
11771 			 * available, the user will need to change the number of
11772 			 * queues/vectors used by the PF later with the ethtool
11773 			 * channels command
11774 			 */
11775 			if (vectors_left < vmdq_vecs_wanted) {
11776 				pf->num_vmdq_qps = 1;
11777 				vmdq_vecs_wanted = pf->num_vmdq_vsis;
11778 				vmdq_vecs = min_t(int,
11779 						  vectors_left,
11780 						  vmdq_vecs_wanted);
11781 			}
11782 			pf->num_vmdq_msix = pf->num_vmdq_qps;
11783 
11784 			v_budget += vmdq_vecs;
11785 			vectors_left -= vmdq_vecs;
11786 		}
11787 	}
11788 
11789 	/* On systems with a large number of SMP cores, we previously limited
11790 	 * the number of vectors for num_lan_msix to be at most 50% of the
11791 	 * available vectors, to allow for other features. Now, we add back
11792 	 * the remaining vectors. However, we ensure that the total
11793 	 * num_lan_msix will not exceed num_online_cpus(). To do this, we
11794 	 * calculate the number of vectors we can add without going over the
11795 	 * cap of CPUs. For systems with a small number of CPUs this will be
11796 	 * zero.
11797 	 */
11798 	extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11799 	pf->num_lan_msix += extra_vectors;
11800 	vectors_left -= extra_vectors;
11801 
11802 	WARN(vectors_left < 0,
11803 	     "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11804 
11805 	v_budget += pf->num_lan_msix;
11806 	pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
11807 				   GFP_KERNEL);
11808 	if (!pf->msix_entries)
11809 		return -ENOMEM;
11810 
11811 	for (i = 0; i < v_budget; i++)
11812 		pf->msix_entries[i].entry = i;
11813 	v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11814 
11815 	if (v_actual < I40E_MIN_MSIX) {
11816 		pf->flags &= ~I40E_FLAG_MSIX_ENABLED;
11817 		kfree(pf->msix_entries);
11818 		pf->msix_entries = NULL;
11819 		pci_disable_msix(pf->pdev);
11820 		return -ENODEV;
11821 
11822 	} else if (v_actual == I40E_MIN_MSIX) {
11823 		/* Adjust for minimal MSIX use */
11824 		pf->num_vmdq_vsis = 0;
11825 		pf->num_vmdq_qps = 0;
11826 		pf->num_lan_qps = 1;
11827 		pf->num_lan_msix = 1;
11828 
11829 	} else if (v_actual != v_budget) {
11830 		/* If we have limited resources, we will start with no vectors
11831 		 * for the special features and then allocate vectors to some
11832 		 * of these features based on the policy and at the end disable
11833 		 * the features that did not get any vectors.
11834 		 */
11835 		int vec;
11836 
11837 		dev_info(&pf->pdev->dev,
11838 			 "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11839 			 v_actual, v_budget);
11840 		/* reserve the misc vector */
11841 		vec = v_actual - 1;
11842 
11843 		/* Scale vector usage down */
11844 		pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11845 		pf->num_vmdq_vsis = 1;
11846 		pf->num_vmdq_qps = 1;
11847 
11848 		/* partition out the remaining vectors */
11849 		switch (vec) {
11850 		case 2:
11851 			pf->num_lan_msix = 1;
11852 			break;
11853 		case 3:
11854 			if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11855 				pf->num_lan_msix = 1;
11856 				pf->num_iwarp_msix = 1;
11857 			} else {
11858 				pf->num_lan_msix = 2;
11859 			}
11860 			break;
11861 		default:
11862 			if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11863 				pf->num_iwarp_msix = min_t(int, (vec / 3),
11864 						 iwarp_requested);
11865 				pf->num_vmdq_vsis = min_t(int, (vec / 3),
11866 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11867 			} else {
11868 				pf->num_vmdq_vsis = min_t(int, (vec / 2),
11869 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11870 			}
11871 			if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11872 				pf->num_fdsb_msix = 1;
11873 				vec--;
11874 			}
11875 			pf->num_lan_msix = min_t(int,
11876 			       (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
11877 							      pf->num_lan_msix);
11878 			pf->num_lan_qps = pf->num_lan_msix;
11879 			break;
11880 		}
11881 	}
11882 
11883 	if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
11884 	    (pf->num_fdsb_msix == 0)) {
11885 		dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
11886 		pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
11887 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11888 	}
11889 	if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
11890 	    (pf->num_vmdq_msix == 0)) {
11891 		dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
11892 		pf->flags &= ~I40E_FLAG_VMDQ_ENABLED;
11893 	}
11894 
11895 	if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
11896 	    (pf->num_iwarp_msix == 0)) {
11897 		dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
11898 		pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
11899 	}
11900 	i40e_debug(&pf->hw, I40E_DEBUG_INIT,
11901 		   "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
11902 		   pf->num_lan_msix,
11903 		   pf->num_vmdq_msix * pf->num_vmdq_vsis,
11904 		   pf->num_fdsb_msix,
11905 		   pf->num_iwarp_msix);
11906 
11907 	return v_actual;
11908 }
11909 
11910 /**
11911  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
11912  * @vsi: the VSI being configured
11913  * @v_idx: index of the vector in the vsi struct
11914  *
11915  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
11916  **/
11917 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx)
11918 {
11919 	struct i40e_q_vector *q_vector;
11920 
11921 	/* allocate q_vector */
11922 	q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
11923 	if (!q_vector)
11924 		return -ENOMEM;
11925 
11926 	q_vector->vsi = vsi;
11927 	q_vector->v_idx = v_idx;
11928 	cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
11929 
11930 	if (vsi->netdev)
11931 		netif_napi_add(vsi->netdev, &q_vector->napi,
11932 			       i40e_napi_poll, NAPI_POLL_WEIGHT);
11933 
11934 	/* tie q_vector and vsi together */
11935 	vsi->q_vectors[v_idx] = q_vector;
11936 
11937 	return 0;
11938 }
11939 
11940 /**
11941  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
11942  * @vsi: the VSI being configured
11943  *
11944  * We allocate one q_vector per queue interrupt.  If allocation fails we
11945  * return -ENOMEM.
11946  **/
11947 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
11948 {
11949 	struct i40e_pf *pf = vsi->back;
11950 	int err, v_idx, num_q_vectors;
11951 
11952 	/* if not MSIX, give the one vector only to the LAN VSI */
11953 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11954 		num_q_vectors = vsi->num_q_vectors;
11955 	else if (vsi == pf->vsi[pf->lan_vsi])
11956 		num_q_vectors = 1;
11957 	else
11958 		return -EINVAL;
11959 
11960 	for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
11961 		err = i40e_vsi_alloc_q_vector(vsi, v_idx);
11962 		if (err)
11963 			goto err_out;
11964 	}
11965 
11966 	return 0;
11967 
11968 err_out:
11969 	while (v_idx--)
11970 		i40e_free_q_vector(vsi, v_idx);
11971 
11972 	return err;
11973 }
11974 
11975 /**
11976  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
11977  * @pf: board private structure to initialize
11978  **/
11979 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
11980 {
11981 	int vectors = 0;
11982 	ssize_t size;
11983 
11984 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11985 		vectors = i40e_init_msix(pf);
11986 		if (vectors < 0) {
11987 			pf->flags &= ~(I40E_FLAG_MSIX_ENABLED	|
11988 				       I40E_FLAG_IWARP_ENABLED	|
11989 				       I40E_FLAG_RSS_ENABLED	|
11990 				       I40E_FLAG_DCB_CAPABLE	|
11991 				       I40E_FLAG_DCB_ENABLED	|
11992 				       I40E_FLAG_SRIOV_ENABLED	|
11993 				       I40E_FLAG_FD_SB_ENABLED	|
11994 				       I40E_FLAG_FD_ATR_ENABLED	|
11995 				       I40E_FLAG_VMDQ_ENABLED);
11996 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11997 
11998 			/* rework the queue expectations without MSIX */
11999 			i40e_determine_queue_usage(pf);
12000 		}
12001 	}
12002 
12003 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED) &&
12004 	    (pf->flags & I40E_FLAG_MSI_ENABLED)) {
12005 		dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
12006 		vectors = pci_enable_msi(pf->pdev);
12007 		if (vectors < 0) {
12008 			dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
12009 				 vectors);
12010 			pf->flags &= ~I40E_FLAG_MSI_ENABLED;
12011 		}
12012 		vectors = 1;  /* one MSI or Legacy vector */
12013 	}
12014 
12015 	if (!(pf->flags & (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED)))
12016 		dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
12017 
12018 	/* set up vector assignment tracking */
12019 	size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
12020 	pf->irq_pile = kzalloc(size, GFP_KERNEL);
12021 	if (!pf->irq_pile)
12022 		return -ENOMEM;
12023 
12024 	pf->irq_pile->num_entries = vectors;
12025 
12026 	/* track first vector for misc interrupts, ignore return */
12027 	(void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
12028 
12029 	return 0;
12030 }
12031 
12032 /**
12033  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
12034  * @pf: private board data structure
12035  *
12036  * Restore the interrupt scheme that was cleared when we suspended the
12037  * device. This should be called during resume to re-allocate the q_vectors
12038  * and reacquire IRQs.
12039  */
12040 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
12041 {
12042 	int err, i;
12043 
12044 	/* We cleared the MSI and MSI-X flags when disabling the old interrupt
12045 	 * scheme. We need to re-enabled them here in order to attempt to
12046 	 * re-acquire the MSI or MSI-X vectors
12047 	 */
12048 	pf->flags |= (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
12049 
12050 	err = i40e_init_interrupt_scheme(pf);
12051 	if (err)
12052 		return err;
12053 
12054 	/* Now that we've re-acquired IRQs, we need to remap the vectors and
12055 	 * rings together again.
12056 	 */
12057 	for (i = 0; i < pf->num_alloc_vsi; i++) {
12058 		if (pf->vsi[i]) {
12059 			err = i40e_vsi_alloc_q_vectors(pf->vsi[i]);
12060 			if (err)
12061 				goto err_unwind;
12062 			i40e_vsi_map_rings_to_vectors(pf->vsi[i]);
12063 		}
12064 	}
12065 
12066 	err = i40e_setup_misc_vector(pf);
12067 	if (err)
12068 		goto err_unwind;
12069 
12070 	if (pf->flags & I40E_FLAG_IWARP_ENABLED)
12071 		i40e_client_update_msix_info(pf);
12072 
12073 	return 0;
12074 
12075 err_unwind:
12076 	while (i--) {
12077 		if (pf->vsi[i])
12078 			i40e_vsi_free_q_vectors(pf->vsi[i]);
12079 	}
12080 
12081 	return err;
12082 }
12083 
12084 /**
12085  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
12086  * non queue events in recovery mode
12087  * @pf: board private structure
12088  *
12089  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
12090  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
12091  * This is handled differently than in recovery mode since no Tx/Rx resources
12092  * are being allocated.
12093  **/
12094 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
12095 {
12096 	int err;
12097 
12098 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
12099 		err = i40e_setup_misc_vector(pf);
12100 
12101 		if (err) {
12102 			dev_info(&pf->pdev->dev,
12103 				 "MSI-X misc vector request failed, error %d\n",
12104 				 err);
12105 			return err;
12106 		}
12107 	} else {
12108 		u32 flags = pf->flags & I40E_FLAG_MSI_ENABLED ? 0 : IRQF_SHARED;
12109 
12110 		err = request_irq(pf->pdev->irq, i40e_intr, flags,
12111 				  pf->int_name, pf);
12112 
12113 		if (err) {
12114 			dev_info(&pf->pdev->dev,
12115 				 "MSI/legacy misc vector request failed, error %d\n",
12116 				 err);
12117 			return err;
12118 		}
12119 		i40e_enable_misc_int_causes(pf);
12120 		i40e_irq_dynamic_enable_icr0(pf);
12121 	}
12122 
12123 	return 0;
12124 }
12125 
12126 /**
12127  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
12128  * @pf: board private structure
12129  *
12130  * This sets up the handler for MSIX 0, which is used to manage the
12131  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
12132  * when in MSI or Legacy interrupt mode.
12133  **/
12134 static int i40e_setup_misc_vector(struct i40e_pf *pf)
12135 {
12136 	struct i40e_hw *hw = &pf->hw;
12137 	int err = 0;
12138 
12139 	/* Only request the IRQ once, the first time through. */
12140 	if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
12141 		err = request_irq(pf->msix_entries[0].vector,
12142 				  i40e_intr, 0, pf->int_name, pf);
12143 		if (err) {
12144 			clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
12145 			dev_info(&pf->pdev->dev,
12146 				 "request_irq for %s failed: %d\n",
12147 				 pf->int_name, err);
12148 			return -EFAULT;
12149 		}
12150 	}
12151 
12152 	i40e_enable_misc_int_causes(pf);
12153 
12154 	/* associate no queues to the misc vector */
12155 	wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
12156 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K >> 1);
12157 
12158 	i40e_flush(hw);
12159 
12160 	i40e_irq_dynamic_enable_icr0(pf);
12161 
12162 	return err;
12163 }
12164 
12165 /**
12166  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
12167  * @vsi: Pointer to vsi structure
12168  * @seed: Buffter to store the hash keys
12169  * @lut: Buffer to store the lookup table entries
12170  * @lut_size: Size of buffer to store the lookup table entries
12171  *
12172  * Return 0 on success, negative on failure
12173  */
12174 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
12175 			   u8 *lut, u16 lut_size)
12176 {
12177 	struct i40e_pf *pf = vsi->back;
12178 	struct i40e_hw *hw = &pf->hw;
12179 	int ret = 0;
12180 
12181 	if (seed) {
12182 		ret = i40e_aq_get_rss_key(hw, vsi->id,
12183 			(struct i40e_aqc_get_set_rss_key_data *)seed);
12184 		if (ret) {
12185 			dev_info(&pf->pdev->dev,
12186 				 "Cannot get RSS key, err %s aq_err %s\n",
12187 				 i40e_stat_str(&pf->hw, ret),
12188 				 i40e_aq_str(&pf->hw,
12189 					     pf->hw.aq.asq_last_status));
12190 			return ret;
12191 		}
12192 	}
12193 
12194 	if (lut) {
12195 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
12196 
12197 		ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
12198 		if (ret) {
12199 			dev_info(&pf->pdev->dev,
12200 				 "Cannot get RSS lut, err %s aq_err %s\n",
12201 				 i40e_stat_str(&pf->hw, ret),
12202 				 i40e_aq_str(&pf->hw,
12203 					     pf->hw.aq.asq_last_status));
12204 			return ret;
12205 		}
12206 	}
12207 
12208 	return ret;
12209 }
12210 
12211 /**
12212  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
12213  * @vsi: Pointer to vsi structure
12214  * @seed: RSS hash seed
12215  * @lut: Lookup table
12216  * @lut_size: Lookup table size
12217  *
12218  * Returns 0 on success, negative on failure
12219  **/
12220 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
12221 			       const u8 *lut, u16 lut_size)
12222 {
12223 	struct i40e_pf *pf = vsi->back;
12224 	struct i40e_hw *hw = &pf->hw;
12225 	u16 vf_id = vsi->vf_id;
12226 	u8 i;
12227 
12228 	/* Fill out hash function seed */
12229 	if (seed) {
12230 		u32 *seed_dw = (u32 *)seed;
12231 
12232 		if (vsi->type == I40E_VSI_MAIN) {
12233 			for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12234 				wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
12235 		} else if (vsi->type == I40E_VSI_SRIOV) {
12236 			for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
12237 				wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
12238 		} else {
12239 			dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
12240 		}
12241 	}
12242 
12243 	if (lut) {
12244 		u32 *lut_dw = (u32 *)lut;
12245 
12246 		if (vsi->type == I40E_VSI_MAIN) {
12247 			if (lut_size != I40E_HLUT_ARRAY_SIZE)
12248 				return -EINVAL;
12249 			for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12250 				wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
12251 		} else if (vsi->type == I40E_VSI_SRIOV) {
12252 			if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
12253 				return -EINVAL;
12254 			for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12255 				wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
12256 		} else {
12257 			dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12258 		}
12259 	}
12260 	i40e_flush(hw);
12261 
12262 	return 0;
12263 }
12264 
12265 /**
12266  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
12267  * @vsi: Pointer to VSI structure
12268  * @seed: Buffer to store the keys
12269  * @lut: Buffer to store the lookup table entries
12270  * @lut_size: Size of buffer to store the lookup table entries
12271  *
12272  * Returns 0 on success, negative on failure
12273  */
12274 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
12275 			    u8 *lut, u16 lut_size)
12276 {
12277 	struct i40e_pf *pf = vsi->back;
12278 	struct i40e_hw *hw = &pf->hw;
12279 	u16 i;
12280 
12281 	if (seed) {
12282 		u32 *seed_dw = (u32 *)seed;
12283 
12284 		for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12285 			seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
12286 	}
12287 	if (lut) {
12288 		u32 *lut_dw = (u32 *)lut;
12289 
12290 		if (lut_size != I40E_HLUT_ARRAY_SIZE)
12291 			return -EINVAL;
12292 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12293 			lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
12294 	}
12295 
12296 	return 0;
12297 }
12298 
12299 /**
12300  * i40e_config_rss - Configure RSS keys and lut
12301  * @vsi: Pointer to VSI structure
12302  * @seed: RSS hash seed
12303  * @lut: Lookup table
12304  * @lut_size: Lookup table size
12305  *
12306  * Returns 0 on success, negative on failure
12307  */
12308 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12309 {
12310 	struct i40e_pf *pf = vsi->back;
12311 
12312 	if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12313 		return i40e_config_rss_aq(vsi, seed, lut, lut_size);
12314 	else
12315 		return i40e_config_rss_reg(vsi, seed, lut, lut_size);
12316 }
12317 
12318 /**
12319  * i40e_get_rss - Get RSS keys and lut
12320  * @vsi: Pointer to VSI structure
12321  * @seed: Buffer to store the keys
12322  * @lut: Buffer to store the lookup table entries
12323  * @lut_size: Size of buffer to store the lookup table entries
12324  *
12325  * Returns 0 on success, negative on failure
12326  */
12327 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12328 {
12329 	struct i40e_pf *pf = vsi->back;
12330 
12331 	if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12332 		return i40e_get_rss_aq(vsi, seed, lut, lut_size);
12333 	else
12334 		return i40e_get_rss_reg(vsi, seed, lut, lut_size);
12335 }
12336 
12337 /**
12338  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
12339  * @pf: Pointer to board private structure
12340  * @lut: Lookup table
12341  * @rss_table_size: Lookup table size
12342  * @rss_size: Range of queue number for hashing
12343  */
12344 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
12345 		       u16 rss_table_size, u16 rss_size)
12346 {
12347 	u16 i;
12348 
12349 	for (i = 0; i < rss_table_size; i++)
12350 		lut[i] = i % rss_size;
12351 }
12352 
12353 /**
12354  * i40e_pf_config_rss - Prepare for RSS if used
12355  * @pf: board private structure
12356  **/
12357 static int i40e_pf_config_rss(struct i40e_pf *pf)
12358 {
12359 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12360 	u8 seed[I40E_HKEY_ARRAY_SIZE];
12361 	u8 *lut;
12362 	struct i40e_hw *hw = &pf->hw;
12363 	u32 reg_val;
12364 	u64 hena;
12365 	int ret;
12366 
12367 	/* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
12368 	hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
12369 		((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
12370 	hena |= i40e_pf_get_default_rss_hena(pf);
12371 
12372 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
12373 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
12374 
12375 	/* Determine the RSS table size based on the hardware capabilities */
12376 	reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
12377 	reg_val = (pf->rss_table_size == 512) ?
12378 			(reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
12379 			(reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
12380 	i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
12381 
12382 	/* Determine the RSS size of the VSI */
12383 	if (!vsi->rss_size) {
12384 		u16 qcount;
12385 		/* If the firmware does something weird during VSI init, we
12386 		 * could end up with zero TCs. Check for that to avoid
12387 		 * divide-by-zero. It probably won't pass traffic, but it also
12388 		 * won't panic.
12389 		 */
12390 		qcount = vsi->num_queue_pairs /
12391 			 (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
12392 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12393 	}
12394 	if (!vsi->rss_size)
12395 		return -EINVAL;
12396 
12397 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
12398 	if (!lut)
12399 		return -ENOMEM;
12400 
12401 	/* Use user configured lut if there is one, otherwise use default */
12402 	if (vsi->rss_lut_user)
12403 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
12404 	else
12405 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
12406 
12407 	/* Use user configured hash key if there is one, otherwise
12408 	 * use default.
12409 	 */
12410 	if (vsi->rss_hkey_user)
12411 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
12412 	else
12413 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
12414 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
12415 	kfree(lut);
12416 
12417 	return ret;
12418 }
12419 
12420 /**
12421  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
12422  * @pf: board private structure
12423  * @queue_count: the requested queue count for rss.
12424  *
12425  * returns 0 if rss is not enabled, if enabled returns the final rss queue
12426  * count which may be different from the requested queue count.
12427  * Note: expects to be called while under rtnl_lock()
12428  **/
12429 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
12430 {
12431 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12432 	int new_rss_size;
12433 
12434 	if (!(pf->flags & I40E_FLAG_RSS_ENABLED))
12435 		return 0;
12436 
12437 	queue_count = min_t(int, queue_count, num_online_cpus());
12438 	new_rss_size = min_t(int, queue_count, pf->rss_size_max);
12439 
12440 	if (queue_count != vsi->num_queue_pairs) {
12441 		u16 qcount;
12442 
12443 		vsi->req_queue_pairs = queue_count;
12444 		i40e_prep_for_reset(pf);
12445 		if (test_bit(__I40E_IN_REMOVE, pf->state))
12446 			return pf->alloc_rss_size;
12447 
12448 		pf->alloc_rss_size = new_rss_size;
12449 
12450 		i40e_reset_and_rebuild(pf, true, true);
12451 
12452 		/* Discard the user configured hash keys and lut, if less
12453 		 * queues are enabled.
12454 		 */
12455 		if (queue_count < vsi->rss_size) {
12456 			i40e_clear_rss_config_user(vsi);
12457 			dev_dbg(&pf->pdev->dev,
12458 				"discard user configured hash keys and lut\n");
12459 		}
12460 
12461 		/* Reset vsi->rss_size, as number of enabled queues changed */
12462 		qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
12463 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12464 
12465 		i40e_pf_config_rss(pf);
12466 	}
12467 	dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
12468 		 vsi->req_queue_pairs, pf->rss_size_max);
12469 	return pf->alloc_rss_size;
12470 }
12471 
12472 /**
12473  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
12474  * @pf: board private structure
12475  **/
12476 i40e_status i40e_get_partition_bw_setting(struct i40e_pf *pf)
12477 {
12478 	i40e_status status;
12479 	bool min_valid, max_valid;
12480 	u32 max_bw, min_bw;
12481 
12482 	status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
12483 					   &min_valid, &max_valid);
12484 
12485 	if (!status) {
12486 		if (min_valid)
12487 			pf->min_bw = min_bw;
12488 		if (max_valid)
12489 			pf->max_bw = max_bw;
12490 	}
12491 
12492 	return status;
12493 }
12494 
12495 /**
12496  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
12497  * @pf: board private structure
12498  **/
12499 i40e_status i40e_set_partition_bw_setting(struct i40e_pf *pf)
12500 {
12501 	struct i40e_aqc_configure_partition_bw_data bw_data;
12502 	i40e_status status;
12503 
12504 	memset(&bw_data, 0, sizeof(bw_data));
12505 
12506 	/* Set the valid bit for this PF */
12507 	bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
12508 	bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
12509 	bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
12510 
12511 	/* Set the new bandwidths */
12512 	status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
12513 
12514 	return status;
12515 }
12516 
12517 /**
12518  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
12519  * @pf: board private structure
12520  **/
12521 i40e_status i40e_commit_partition_bw_setting(struct i40e_pf *pf)
12522 {
12523 	/* Commit temporary BW setting to permanent NVM image */
12524 	enum i40e_admin_queue_err last_aq_status;
12525 	i40e_status ret;
12526 	u16 nvm_word;
12527 
12528 	if (pf->hw.partition_id != 1) {
12529 		dev_info(&pf->pdev->dev,
12530 			 "Commit BW only works on partition 1! This is partition %d",
12531 			 pf->hw.partition_id);
12532 		ret = I40E_NOT_SUPPORTED;
12533 		goto bw_commit_out;
12534 	}
12535 
12536 	/* Acquire NVM for read access */
12537 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
12538 	last_aq_status = pf->hw.aq.asq_last_status;
12539 	if (ret) {
12540 		dev_info(&pf->pdev->dev,
12541 			 "Cannot acquire NVM for read access, err %s aq_err %s\n",
12542 			 i40e_stat_str(&pf->hw, ret),
12543 			 i40e_aq_str(&pf->hw, last_aq_status));
12544 		goto bw_commit_out;
12545 	}
12546 
12547 	/* Read word 0x10 of NVM - SW compatibility word 1 */
12548 	ret = i40e_aq_read_nvm(&pf->hw,
12549 			       I40E_SR_NVM_CONTROL_WORD,
12550 			       0x10, sizeof(nvm_word), &nvm_word,
12551 			       false, NULL);
12552 	/* Save off last admin queue command status before releasing
12553 	 * the NVM
12554 	 */
12555 	last_aq_status = pf->hw.aq.asq_last_status;
12556 	i40e_release_nvm(&pf->hw);
12557 	if (ret) {
12558 		dev_info(&pf->pdev->dev, "NVM read error, err %s aq_err %s\n",
12559 			 i40e_stat_str(&pf->hw, ret),
12560 			 i40e_aq_str(&pf->hw, last_aq_status));
12561 		goto bw_commit_out;
12562 	}
12563 
12564 	/* Wait a bit for NVM release to complete */
12565 	msleep(50);
12566 
12567 	/* Acquire NVM for write access */
12568 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
12569 	last_aq_status = pf->hw.aq.asq_last_status;
12570 	if (ret) {
12571 		dev_info(&pf->pdev->dev,
12572 			 "Cannot acquire NVM for write access, err %s aq_err %s\n",
12573 			 i40e_stat_str(&pf->hw, ret),
12574 			 i40e_aq_str(&pf->hw, last_aq_status));
12575 		goto bw_commit_out;
12576 	}
12577 	/* Write it back out unchanged to initiate update NVM,
12578 	 * which will force a write of the shadow (alt) RAM to
12579 	 * the NVM - thus storing the bandwidth values permanently.
12580 	 */
12581 	ret = i40e_aq_update_nvm(&pf->hw,
12582 				 I40E_SR_NVM_CONTROL_WORD,
12583 				 0x10, sizeof(nvm_word),
12584 				 &nvm_word, true, 0, NULL);
12585 	/* Save off last admin queue command status before releasing
12586 	 * the NVM
12587 	 */
12588 	last_aq_status = pf->hw.aq.asq_last_status;
12589 	i40e_release_nvm(&pf->hw);
12590 	if (ret)
12591 		dev_info(&pf->pdev->dev,
12592 			 "BW settings NOT SAVED, err %s aq_err %s\n",
12593 			 i40e_stat_str(&pf->hw, ret),
12594 			 i40e_aq_str(&pf->hw, last_aq_status));
12595 bw_commit_out:
12596 
12597 	return ret;
12598 }
12599 
12600 /**
12601  * i40e_is_total_port_shutdown_enabled - read NVM and return value
12602  * if total port shutdown feature is enabled for this PF
12603  * @pf: board private structure
12604  **/
12605 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf)
12606 {
12607 #define I40E_TOTAL_PORT_SHUTDOWN_ENABLED	BIT(4)
12608 #define I40E_FEATURES_ENABLE_PTR		0x2A
12609 #define I40E_CURRENT_SETTING_PTR		0x2B
12610 #define I40E_LINK_BEHAVIOR_WORD_OFFSET		0x2D
12611 #define I40E_LINK_BEHAVIOR_WORD_LENGTH		0x1
12612 #define I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED	BIT(0)
12613 #define I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH	4
12614 	i40e_status read_status = I40E_SUCCESS;
12615 	u16 sr_emp_sr_settings_ptr = 0;
12616 	u16 features_enable = 0;
12617 	u16 link_behavior = 0;
12618 	bool ret = false;
12619 
12620 	read_status = i40e_read_nvm_word(&pf->hw,
12621 					 I40E_SR_EMP_SR_SETTINGS_PTR,
12622 					 &sr_emp_sr_settings_ptr);
12623 	if (read_status)
12624 		goto err_nvm;
12625 	read_status = i40e_read_nvm_word(&pf->hw,
12626 					 sr_emp_sr_settings_ptr +
12627 					 I40E_FEATURES_ENABLE_PTR,
12628 					 &features_enable);
12629 	if (read_status)
12630 		goto err_nvm;
12631 	if (I40E_TOTAL_PORT_SHUTDOWN_ENABLED & features_enable) {
12632 		read_status = i40e_read_nvm_module_data(&pf->hw,
12633 							I40E_SR_EMP_SR_SETTINGS_PTR,
12634 							I40E_CURRENT_SETTING_PTR,
12635 							I40E_LINK_BEHAVIOR_WORD_OFFSET,
12636 							I40E_LINK_BEHAVIOR_WORD_LENGTH,
12637 							&link_behavior);
12638 		if (read_status)
12639 			goto err_nvm;
12640 		link_behavior >>= (pf->hw.port * I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH);
12641 		ret = I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED & link_behavior;
12642 	}
12643 	return ret;
12644 
12645 err_nvm:
12646 	dev_warn(&pf->pdev->dev,
12647 		 "total-port-shutdown feature is off due to read nvm error: %s\n",
12648 		 i40e_stat_str(&pf->hw, read_status));
12649 	return ret;
12650 }
12651 
12652 /**
12653  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
12654  * @pf: board private structure to initialize
12655  *
12656  * i40e_sw_init initializes the Adapter private data structure.
12657  * Fields are initialized based on PCI device information and
12658  * OS network device settings (MTU size).
12659  **/
12660 static int i40e_sw_init(struct i40e_pf *pf)
12661 {
12662 	int err = 0;
12663 	int size;
12664 	u16 pow;
12665 
12666 	/* Set default capability flags */
12667 	pf->flags = I40E_FLAG_RX_CSUM_ENABLED |
12668 		    I40E_FLAG_MSI_ENABLED     |
12669 		    I40E_FLAG_MSIX_ENABLED;
12670 
12671 	/* Set default ITR */
12672 	pf->rx_itr_default = I40E_ITR_RX_DEF;
12673 	pf->tx_itr_default = I40E_ITR_TX_DEF;
12674 
12675 	/* Depending on PF configurations, it is possible that the RSS
12676 	 * maximum might end up larger than the available queues
12677 	 */
12678 	pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
12679 	pf->alloc_rss_size = 1;
12680 	pf->rss_table_size = pf->hw.func_caps.rss_table_size;
12681 	pf->rss_size_max = min_t(int, pf->rss_size_max,
12682 				 pf->hw.func_caps.num_tx_qp);
12683 
12684 	/* find the next higher power-of-2 of num cpus */
12685 	pow = roundup_pow_of_two(num_online_cpus());
12686 	pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
12687 
12688 	if (pf->hw.func_caps.rss) {
12689 		pf->flags |= I40E_FLAG_RSS_ENABLED;
12690 		pf->alloc_rss_size = min_t(int, pf->rss_size_max,
12691 					   num_online_cpus());
12692 	}
12693 
12694 	/* MFP mode enabled */
12695 	if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
12696 		pf->flags |= I40E_FLAG_MFP_ENABLED;
12697 		dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
12698 		if (i40e_get_partition_bw_setting(pf)) {
12699 			dev_warn(&pf->pdev->dev,
12700 				 "Could not get partition bw settings\n");
12701 		} else {
12702 			dev_info(&pf->pdev->dev,
12703 				 "Partition BW Min = %8.8x, Max = %8.8x\n",
12704 				 pf->min_bw, pf->max_bw);
12705 
12706 			/* nudge the Tx scheduler */
12707 			i40e_set_partition_bw_setting(pf);
12708 		}
12709 	}
12710 
12711 	if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
12712 	    (pf->hw.func_caps.fd_filters_best_effort > 0)) {
12713 		pf->flags |= I40E_FLAG_FD_ATR_ENABLED;
12714 		pf->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
12715 		if (pf->flags & I40E_FLAG_MFP_ENABLED &&
12716 		    pf->hw.num_partitions > 1)
12717 			dev_info(&pf->pdev->dev,
12718 				 "Flow Director Sideband mode Disabled in MFP mode\n");
12719 		else
12720 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12721 		pf->fdir_pf_filter_count =
12722 				 pf->hw.func_caps.fd_filters_guaranteed;
12723 		pf->hw.fdir_shared_filter_count =
12724 				 pf->hw.func_caps.fd_filters_best_effort;
12725 	}
12726 
12727 	if (pf->hw.mac.type == I40E_MAC_X722) {
12728 		pf->hw_features |= (I40E_HW_RSS_AQ_CAPABLE |
12729 				    I40E_HW_128_QP_RSS_CAPABLE |
12730 				    I40E_HW_ATR_EVICT_CAPABLE |
12731 				    I40E_HW_WB_ON_ITR_CAPABLE |
12732 				    I40E_HW_MULTIPLE_TCP_UDP_RSS_PCTYPE |
12733 				    I40E_HW_NO_PCI_LINK_CHECK |
12734 				    I40E_HW_USE_SET_LLDP_MIB |
12735 				    I40E_HW_GENEVE_OFFLOAD_CAPABLE |
12736 				    I40E_HW_PTP_L4_CAPABLE |
12737 				    I40E_HW_WOL_MC_MAGIC_PKT_WAKE |
12738 				    I40E_HW_OUTER_UDP_CSUM_CAPABLE);
12739 
12740 #define I40E_FDEVICT_PCTYPE_DEFAULT 0xc03
12741 		if (rd32(&pf->hw, I40E_GLQF_FDEVICTENA(1)) !=
12742 		    I40E_FDEVICT_PCTYPE_DEFAULT) {
12743 			dev_warn(&pf->pdev->dev,
12744 				 "FD EVICT PCTYPES are not right, disable FD HW EVICT\n");
12745 			pf->hw_features &= ~I40E_HW_ATR_EVICT_CAPABLE;
12746 		}
12747 	} else if ((pf->hw.aq.api_maj_ver > 1) ||
12748 		   ((pf->hw.aq.api_maj_ver == 1) &&
12749 		    (pf->hw.aq.api_min_ver > 4))) {
12750 		/* Supported in FW API version higher than 1.4 */
12751 		pf->hw_features |= I40E_HW_GENEVE_OFFLOAD_CAPABLE;
12752 	}
12753 
12754 	/* Enable HW ATR eviction if possible */
12755 	if (pf->hw_features & I40E_HW_ATR_EVICT_CAPABLE)
12756 		pf->flags |= I40E_FLAG_HW_ATR_EVICT_ENABLED;
12757 
12758 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12759 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 33)) ||
12760 	    (pf->hw.aq.fw_maj_ver < 4))) {
12761 		pf->hw_features |= I40E_HW_RESTART_AUTONEG;
12762 		/* No DCB support  for FW < v4.33 */
12763 		pf->hw_features |= I40E_HW_NO_DCB_SUPPORT;
12764 	}
12765 
12766 	/* Disable FW LLDP if FW < v4.3 */
12767 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12768 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 3)) ||
12769 	    (pf->hw.aq.fw_maj_ver < 4)))
12770 		pf->hw_features |= I40E_HW_STOP_FW_LLDP;
12771 
12772 	/* Use the FW Set LLDP MIB API if FW > v4.40 */
12773 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12774 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver >= 40)) ||
12775 	    (pf->hw.aq.fw_maj_ver >= 5)))
12776 		pf->hw_features |= I40E_HW_USE_SET_LLDP_MIB;
12777 
12778 	/* Enable PTP L4 if FW > v6.0 */
12779 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
12780 	    pf->hw.aq.fw_maj_ver >= 6)
12781 		pf->hw_features |= I40E_HW_PTP_L4_CAPABLE;
12782 
12783 	if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
12784 		pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
12785 		pf->flags |= I40E_FLAG_VMDQ_ENABLED;
12786 		pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
12787 	}
12788 
12789 	if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
12790 		pf->flags |= I40E_FLAG_IWARP_ENABLED;
12791 		/* IWARP needs one extra vector for CQP just like MISC.*/
12792 		pf->num_iwarp_msix = (int)num_online_cpus() + 1;
12793 	}
12794 	/* Stopping FW LLDP engine is supported on XL710 and X722
12795 	 * starting from FW versions determined in i40e_init_adminq.
12796 	 * Stopping the FW LLDP engine is not supported on XL710
12797 	 * if NPAR is functioning so unset this hw flag in this case.
12798 	 */
12799 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
12800 	    pf->hw.func_caps.npar_enable &&
12801 	    (pf->hw.flags & I40E_HW_FLAG_FW_LLDP_STOPPABLE))
12802 		pf->hw.flags &= ~I40E_HW_FLAG_FW_LLDP_STOPPABLE;
12803 
12804 #ifdef CONFIG_PCI_IOV
12805 	if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
12806 		pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
12807 		pf->flags |= I40E_FLAG_SRIOV_ENABLED;
12808 		pf->num_req_vfs = min_t(int,
12809 					pf->hw.func_caps.num_vfs,
12810 					I40E_MAX_VF_COUNT);
12811 	}
12812 #endif /* CONFIG_PCI_IOV */
12813 	pf->eeprom_version = 0xDEAD;
12814 	pf->lan_veb = I40E_NO_VEB;
12815 	pf->lan_vsi = I40E_NO_VSI;
12816 
12817 	/* By default FW has this off for performance reasons */
12818 	pf->flags &= ~I40E_FLAG_VEB_STATS_ENABLED;
12819 
12820 	/* set up queue assignment tracking */
12821 	size = sizeof(struct i40e_lump_tracking)
12822 		+ (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
12823 	pf->qp_pile = kzalloc(size, GFP_KERNEL);
12824 	if (!pf->qp_pile) {
12825 		err = -ENOMEM;
12826 		goto sw_init_done;
12827 	}
12828 	pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
12829 
12830 	pf->tx_timeout_recovery_level = 1;
12831 
12832 	if (pf->hw.mac.type != I40E_MAC_X722 &&
12833 	    i40e_is_total_port_shutdown_enabled(pf)) {
12834 		/* Link down on close must be on when total port shutdown
12835 		 * is enabled for a given port
12836 		 */
12837 		pf->flags |= (I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED |
12838 			      I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED);
12839 		dev_info(&pf->pdev->dev,
12840 			 "total-port-shutdown was enabled, link-down-on-close is forced on\n");
12841 	}
12842 	mutex_init(&pf->switch_mutex);
12843 
12844 sw_init_done:
12845 	return err;
12846 }
12847 
12848 /**
12849  * i40e_set_ntuple - set the ntuple feature flag and take action
12850  * @pf: board private structure to initialize
12851  * @features: the feature set that the stack is suggesting
12852  *
12853  * returns a bool to indicate if reset needs to happen
12854  **/
12855 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12856 {
12857 	bool need_reset = false;
12858 
12859 	/* Check if Flow Director n-tuple support was enabled or disabled.  If
12860 	 * the state changed, we need to reset.
12861 	 */
12862 	if (features & NETIF_F_NTUPLE) {
12863 		/* Enable filters and mark for reset */
12864 		if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
12865 			need_reset = true;
12866 		/* enable FD_SB only if there is MSI-X vector and no cloud
12867 		 * filters exist
12868 		 */
12869 		if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12870 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12871 			pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
12872 		}
12873 	} else {
12874 		/* turn off filters, mark for reset and clear SW filter list */
12875 		if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
12876 			need_reset = true;
12877 			i40e_fdir_filter_exit(pf);
12878 		}
12879 		pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
12880 		clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12881 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
12882 
12883 		/* reset fd counters */
12884 		pf->fd_add_err = 0;
12885 		pf->fd_atr_cnt = 0;
12886 		/* if ATR was auto disabled it can be re-enabled. */
12887 		if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12888 			if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
12889 			    (I40E_DEBUG_FD & pf->hw.debug_mask))
12890 				dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12891 	}
12892 	return need_reset;
12893 }
12894 
12895 /**
12896  * i40e_clear_rss_lut - clear the rx hash lookup table
12897  * @vsi: the VSI being configured
12898  **/
12899 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12900 {
12901 	struct i40e_pf *pf = vsi->back;
12902 	struct i40e_hw *hw = &pf->hw;
12903 	u16 vf_id = vsi->vf_id;
12904 	u8 i;
12905 
12906 	if (vsi->type == I40E_VSI_MAIN) {
12907 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12908 			wr32(hw, I40E_PFQF_HLUT(i), 0);
12909 	} else if (vsi->type == I40E_VSI_SRIOV) {
12910 		for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12911 			i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12912 	} else {
12913 		dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12914 	}
12915 }
12916 
12917 /**
12918  * i40e_set_features - set the netdev feature flags
12919  * @netdev: ptr to the netdev being adjusted
12920  * @features: the feature set that the stack is suggesting
12921  * Note: expects to be called while under rtnl_lock()
12922  **/
12923 static int i40e_set_features(struct net_device *netdev,
12924 			     netdev_features_t features)
12925 {
12926 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12927 	struct i40e_vsi *vsi = np->vsi;
12928 	struct i40e_pf *pf = vsi->back;
12929 	bool need_reset;
12930 
12931 	if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
12932 		i40e_pf_config_rss(pf);
12933 	else if (!(features & NETIF_F_RXHASH) &&
12934 		 netdev->features & NETIF_F_RXHASH)
12935 		i40e_clear_rss_lut(vsi);
12936 
12937 	if (features & NETIF_F_HW_VLAN_CTAG_RX)
12938 		i40e_vlan_stripping_enable(vsi);
12939 	else
12940 		i40e_vlan_stripping_disable(vsi);
12941 
12942 	if (!(features & NETIF_F_HW_TC) &&
12943 	    (netdev->features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
12944 		dev_err(&pf->pdev->dev,
12945 			"Offloaded tc filters active, can't turn hw_tc_offload off");
12946 		return -EINVAL;
12947 	}
12948 
12949 	if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
12950 		i40e_del_all_macvlans(vsi);
12951 
12952 	need_reset = i40e_set_ntuple(pf, features);
12953 
12954 	if (need_reset)
12955 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12956 
12957 	return 0;
12958 }
12959 
12960 static int i40e_udp_tunnel_set_port(struct net_device *netdev,
12961 				    unsigned int table, unsigned int idx,
12962 				    struct udp_tunnel_info *ti)
12963 {
12964 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12965 	struct i40e_hw *hw = &np->vsi->back->hw;
12966 	u8 type, filter_index;
12967 	i40e_status ret;
12968 
12969 	type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? I40E_AQC_TUNNEL_TYPE_VXLAN :
12970 						   I40E_AQC_TUNNEL_TYPE_NGE;
12971 
12972 	ret = i40e_aq_add_udp_tunnel(hw, ntohs(ti->port), type, &filter_index,
12973 				     NULL);
12974 	if (ret) {
12975 		netdev_info(netdev, "add UDP port failed, err %s aq_err %s\n",
12976 			    i40e_stat_str(hw, ret),
12977 			    i40e_aq_str(hw, hw->aq.asq_last_status));
12978 		return -EIO;
12979 	}
12980 
12981 	udp_tunnel_nic_set_port_priv(netdev, table, idx, filter_index);
12982 	return 0;
12983 }
12984 
12985 static int i40e_udp_tunnel_unset_port(struct net_device *netdev,
12986 				      unsigned int table, unsigned int idx,
12987 				      struct udp_tunnel_info *ti)
12988 {
12989 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12990 	struct i40e_hw *hw = &np->vsi->back->hw;
12991 	i40e_status ret;
12992 
12993 	ret = i40e_aq_del_udp_tunnel(hw, ti->hw_priv, NULL);
12994 	if (ret) {
12995 		netdev_info(netdev, "delete UDP port failed, err %s aq_err %s\n",
12996 			    i40e_stat_str(hw, ret),
12997 			    i40e_aq_str(hw, hw->aq.asq_last_status));
12998 		return -EIO;
12999 	}
13000 
13001 	return 0;
13002 }
13003 
13004 static int i40e_get_phys_port_id(struct net_device *netdev,
13005 				 struct netdev_phys_item_id *ppid)
13006 {
13007 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13008 	struct i40e_pf *pf = np->vsi->back;
13009 	struct i40e_hw *hw = &pf->hw;
13010 
13011 	if (!(pf->hw_features & I40E_HW_PORT_ID_VALID))
13012 		return -EOPNOTSUPP;
13013 
13014 	ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
13015 	memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
13016 
13017 	return 0;
13018 }
13019 
13020 /**
13021  * i40e_ndo_fdb_add - add an entry to the hardware database
13022  * @ndm: the input from the stack
13023  * @tb: pointer to array of nladdr (unused)
13024  * @dev: the net device pointer
13025  * @addr: the MAC address entry being added
13026  * @vid: VLAN ID
13027  * @flags: instructions from stack about fdb operation
13028  * @extack: netlink extended ack, unused currently
13029  */
13030 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
13031 			    struct net_device *dev,
13032 			    const unsigned char *addr, u16 vid,
13033 			    u16 flags,
13034 			    struct netlink_ext_ack *extack)
13035 {
13036 	struct i40e_netdev_priv *np = netdev_priv(dev);
13037 	struct i40e_pf *pf = np->vsi->back;
13038 	int err = 0;
13039 
13040 	if (!(pf->flags & I40E_FLAG_SRIOV_ENABLED))
13041 		return -EOPNOTSUPP;
13042 
13043 	if (vid) {
13044 		pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
13045 		return -EINVAL;
13046 	}
13047 
13048 	/* Hardware does not support aging addresses so if a
13049 	 * ndm_state is given only allow permanent addresses
13050 	 */
13051 	if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
13052 		netdev_info(dev, "FDB only supports static addresses\n");
13053 		return -EINVAL;
13054 	}
13055 
13056 	if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
13057 		err = dev_uc_add_excl(dev, addr);
13058 	else if (is_multicast_ether_addr(addr))
13059 		err = dev_mc_add_excl(dev, addr);
13060 	else
13061 		err = -EINVAL;
13062 
13063 	/* Only return duplicate errors if NLM_F_EXCL is set */
13064 	if (err == -EEXIST && !(flags & NLM_F_EXCL))
13065 		err = 0;
13066 
13067 	return err;
13068 }
13069 
13070 /**
13071  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
13072  * @dev: the netdev being configured
13073  * @nlh: RTNL message
13074  * @flags: bridge flags
13075  * @extack: netlink extended ack
13076  *
13077  * Inserts a new hardware bridge if not already created and
13078  * enables the bridging mode requested (VEB or VEPA). If the
13079  * hardware bridge has already been inserted and the request
13080  * is to change the mode then that requires a PF reset to
13081  * allow rebuild of the components with required hardware
13082  * bridge mode enabled.
13083  *
13084  * Note: expects to be called while under rtnl_lock()
13085  **/
13086 static int i40e_ndo_bridge_setlink(struct net_device *dev,
13087 				   struct nlmsghdr *nlh,
13088 				   u16 flags,
13089 				   struct netlink_ext_ack *extack)
13090 {
13091 	struct i40e_netdev_priv *np = netdev_priv(dev);
13092 	struct i40e_vsi *vsi = np->vsi;
13093 	struct i40e_pf *pf = vsi->back;
13094 	struct i40e_veb *veb = NULL;
13095 	struct nlattr *attr, *br_spec;
13096 	int i, rem;
13097 
13098 	/* Only for PF VSI for now */
13099 	if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13100 		return -EOPNOTSUPP;
13101 
13102 	/* Find the HW bridge for PF VSI */
13103 	for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13104 		if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13105 			veb = pf->veb[i];
13106 	}
13107 
13108 	br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
13109 
13110 	nla_for_each_nested(attr, br_spec, rem) {
13111 		__u16 mode;
13112 
13113 		if (nla_type(attr) != IFLA_BRIDGE_MODE)
13114 			continue;
13115 
13116 		mode = nla_get_u16(attr);
13117 		if ((mode != BRIDGE_MODE_VEPA) &&
13118 		    (mode != BRIDGE_MODE_VEB))
13119 			return -EINVAL;
13120 
13121 		/* Insert a new HW bridge */
13122 		if (!veb) {
13123 			veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
13124 					     vsi->tc_config.enabled_tc);
13125 			if (veb) {
13126 				veb->bridge_mode = mode;
13127 				i40e_config_bridge_mode(veb);
13128 			} else {
13129 				/* No Bridge HW offload available */
13130 				return -ENOENT;
13131 			}
13132 			break;
13133 		} else if (mode != veb->bridge_mode) {
13134 			/* Existing HW bridge but different mode needs reset */
13135 			veb->bridge_mode = mode;
13136 			/* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
13137 			if (mode == BRIDGE_MODE_VEB)
13138 				pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
13139 			else
13140 				pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
13141 			i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13142 			break;
13143 		}
13144 	}
13145 
13146 	return 0;
13147 }
13148 
13149 /**
13150  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
13151  * @skb: skb buff
13152  * @pid: process id
13153  * @seq: RTNL message seq #
13154  * @dev: the netdev being configured
13155  * @filter_mask: unused
13156  * @nlflags: netlink flags passed in
13157  *
13158  * Return the mode in which the hardware bridge is operating in
13159  * i.e VEB or VEPA.
13160  **/
13161 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
13162 				   struct net_device *dev,
13163 				   u32 __always_unused filter_mask,
13164 				   int nlflags)
13165 {
13166 	struct i40e_netdev_priv *np = netdev_priv(dev);
13167 	struct i40e_vsi *vsi = np->vsi;
13168 	struct i40e_pf *pf = vsi->back;
13169 	struct i40e_veb *veb = NULL;
13170 	int i;
13171 
13172 	/* Only for PF VSI for now */
13173 	if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13174 		return -EOPNOTSUPP;
13175 
13176 	/* Find the HW bridge for the PF VSI */
13177 	for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13178 		if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13179 			veb = pf->veb[i];
13180 	}
13181 
13182 	if (!veb)
13183 		return 0;
13184 
13185 	return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
13186 				       0, 0, nlflags, filter_mask, NULL);
13187 }
13188 
13189 /**
13190  * i40e_features_check - Validate encapsulated packet conforms to limits
13191  * @skb: skb buff
13192  * @dev: This physical port's netdev
13193  * @features: Offload features that the stack believes apply
13194  **/
13195 static netdev_features_t i40e_features_check(struct sk_buff *skb,
13196 					     struct net_device *dev,
13197 					     netdev_features_t features)
13198 {
13199 	size_t len;
13200 
13201 	/* No point in doing any of this if neither checksum nor GSO are
13202 	 * being requested for this frame.  We can rule out both by just
13203 	 * checking for CHECKSUM_PARTIAL
13204 	 */
13205 	if (skb->ip_summed != CHECKSUM_PARTIAL)
13206 		return features;
13207 
13208 	/* We cannot support GSO if the MSS is going to be less than
13209 	 * 64 bytes.  If it is then we need to drop support for GSO.
13210 	 */
13211 	if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
13212 		features &= ~NETIF_F_GSO_MASK;
13213 
13214 	/* MACLEN can support at most 63 words */
13215 	len = skb_network_header(skb) - skb->data;
13216 	if (len & ~(63 * 2))
13217 		goto out_err;
13218 
13219 	/* IPLEN and EIPLEN can support at most 127 dwords */
13220 	len = skb_transport_header(skb) - skb_network_header(skb);
13221 	if (len & ~(127 * 4))
13222 		goto out_err;
13223 
13224 	if (skb->encapsulation) {
13225 		/* L4TUNLEN can support 127 words */
13226 		len = skb_inner_network_header(skb) - skb_transport_header(skb);
13227 		if (len & ~(127 * 2))
13228 			goto out_err;
13229 
13230 		/* IPLEN can support at most 127 dwords */
13231 		len = skb_inner_transport_header(skb) -
13232 		      skb_inner_network_header(skb);
13233 		if (len & ~(127 * 4))
13234 			goto out_err;
13235 	}
13236 
13237 	/* No need to validate L4LEN as TCP is the only protocol with a
13238 	 * flexible value and we support all possible values supported
13239 	 * by TCP, which is at most 15 dwords
13240 	 */
13241 
13242 	return features;
13243 out_err:
13244 	return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
13245 }
13246 
13247 /**
13248  * i40e_xdp_setup - add/remove an XDP program
13249  * @vsi: VSI to changed
13250  * @prog: XDP program
13251  * @extack: netlink extended ack
13252  **/
13253 static int i40e_xdp_setup(struct i40e_vsi *vsi, struct bpf_prog *prog,
13254 			  struct netlink_ext_ack *extack)
13255 {
13256 	int frame_size = vsi->netdev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
13257 	struct i40e_pf *pf = vsi->back;
13258 	struct bpf_prog *old_prog;
13259 	bool need_reset;
13260 	int i;
13261 
13262 	/* Don't allow frames that span over multiple buffers */
13263 	if (frame_size > vsi->rx_buf_len) {
13264 		NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
13265 		return -EINVAL;
13266 	}
13267 
13268 	/* When turning XDP on->off/off->on we reset and rebuild the rings. */
13269 	need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
13270 
13271 	if (need_reset)
13272 		i40e_prep_for_reset(pf);
13273 
13274 	/* VSI shall be deleted in a moment, just return EINVAL */
13275 	if (test_bit(__I40E_IN_REMOVE, pf->state))
13276 		return -EINVAL;
13277 
13278 	old_prog = xchg(&vsi->xdp_prog, prog);
13279 
13280 	if (need_reset) {
13281 		if (!prog)
13282 			/* Wait until ndo_xsk_wakeup completes. */
13283 			synchronize_rcu();
13284 		i40e_reset_and_rebuild(pf, true, true);
13285 	}
13286 
13287 	for (i = 0; i < vsi->num_queue_pairs; i++)
13288 		WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
13289 
13290 	if (old_prog)
13291 		bpf_prog_put(old_prog);
13292 
13293 	/* Kick start the NAPI context if there is an AF_XDP socket open
13294 	 * on that queue id. This so that receiving will start.
13295 	 */
13296 	if (need_reset && prog)
13297 		for (i = 0; i < vsi->num_queue_pairs; i++)
13298 			if (vsi->xdp_rings[i]->xsk_pool)
13299 				(void)i40e_xsk_wakeup(vsi->netdev, i,
13300 						      XDP_WAKEUP_RX);
13301 
13302 	return 0;
13303 }
13304 
13305 /**
13306  * i40e_enter_busy_conf - Enters busy config state
13307  * @vsi: vsi
13308  *
13309  * Returns 0 on success, <0 for failure.
13310  **/
13311 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
13312 {
13313 	struct i40e_pf *pf = vsi->back;
13314 	int timeout = 50;
13315 
13316 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
13317 		timeout--;
13318 		if (!timeout)
13319 			return -EBUSY;
13320 		usleep_range(1000, 2000);
13321 	}
13322 
13323 	return 0;
13324 }
13325 
13326 /**
13327  * i40e_exit_busy_conf - Exits busy config state
13328  * @vsi: vsi
13329  **/
13330 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
13331 {
13332 	struct i40e_pf *pf = vsi->back;
13333 
13334 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
13335 }
13336 
13337 /**
13338  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
13339  * @vsi: vsi
13340  * @queue_pair: queue pair
13341  **/
13342 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
13343 {
13344 	memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
13345 	       sizeof(vsi->rx_rings[queue_pair]->rx_stats));
13346 	memset(&vsi->tx_rings[queue_pair]->stats, 0,
13347 	       sizeof(vsi->tx_rings[queue_pair]->stats));
13348 	if (i40e_enabled_xdp_vsi(vsi)) {
13349 		memset(&vsi->xdp_rings[queue_pair]->stats, 0,
13350 		       sizeof(vsi->xdp_rings[queue_pair]->stats));
13351 	}
13352 }
13353 
13354 /**
13355  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
13356  * @vsi: vsi
13357  * @queue_pair: queue pair
13358  **/
13359 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
13360 {
13361 	i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
13362 	if (i40e_enabled_xdp_vsi(vsi)) {
13363 		/* Make sure that in-progress ndo_xdp_xmit calls are
13364 		 * completed.
13365 		 */
13366 		synchronize_rcu();
13367 		i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
13368 	}
13369 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13370 }
13371 
13372 /**
13373  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
13374  * @vsi: vsi
13375  * @queue_pair: queue pair
13376  * @enable: true for enable, false for disable
13377  **/
13378 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
13379 					bool enable)
13380 {
13381 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13382 	struct i40e_q_vector *q_vector = rxr->q_vector;
13383 
13384 	if (!vsi->netdev)
13385 		return;
13386 
13387 	/* All rings in a qp belong to the same qvector. */
13388 	if (q_vector->rx.ring || q_vector->tx.ring) {
13389 		if (enable)
13390 			napi_enable(&q_vector->napi);
13391 		else
13392 			napi_disable(&q_vector->napi);
13393 	}
13394 }
13395 
13396 /**
13397  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
13398  * @vsi: vsi
13399  * @queue_pair: queue pair
13400  * @enable: true for enable, false for disable
13401  *
13402  * Returns 0 on success, <0 on failure.
13403  **/
13404 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
13405 					bool enable)
13406 {
13407 	struct i40e_pf *pf = vsi->back;
13408 	int pf_q, ret = 0;
13409 
13410 	pf_q = vsi->base_queue + queue_pair;
13411 	ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
13412 				     false /*is xdp*/, enable);
13413 	if (ret) {
13414 		dev_info(&pf->pdev->dev,
13415 			 "VSI seid %d Tx ring %d %sable timeout\n",
13416 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13417 		return ret;
13418 	}
13419 
13420 	i40e_control_rx_q(pf, pf_q, enable);
13421 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
13422 	if (ret) {
13423 		dev_info(&pf->pdev->dev,
13424 			 "VSI seid %d Rx ring %d %sable timeout\n",
13425 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13426 		return ret;
13427 	}
13428 
13429 	/* Due to HW errata, on Rx disable only, the register can
13430 	 * indicate done before it really is. Needs 50ms to be sure
13431 	 */
13432 	if (!enable)
13433 		mdelay(50);
13434 
13435 	if (!i40e_enabled_xdp_vsi(vsi))
13436 		return ret;
13437 
13438 	ret = i40e_control_wait_tx_q(vsi->seid, pf,
13439 				     pf_q + vsi->alloc_queue_pairs,
13440 				     true /*is xdp*/, enable);
13441 	if (ret) {
13442 		dev_info(&pf->pdev->dev,
13443 			 "VSI seid %d XDP Tx ring %d %sable timeout\n",
13444 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13445 	}
13446 
13447 	return ret;
13448 }
13449 
13450 /**
13451  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
13452  * @vsi: vsi
13453  * @queue_pair: queue_pair
13454  **/
13455 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
13456 {
13457 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13458 	struct i40e_pf *pf = vsi->back;
13459 	struct i40e_hw *hw = &pf->hw;
13460 
13461 	/* All rings in a qp belong to the same qvector. */
13462 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
13463 		i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
13464 	else
13465 		i40e_irq_dynamic_enable_icr0(pf);
13466 
13467 	i40e_flush(hw);
13468 }
13469 
13470 /**
13471  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
13472  * @vsi: vsi
13473  * @queue_pair: queue_pair
13474  **/
13475 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
13476 {
13477 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13478 	struct i40e_pf *pf = vsi->back;
13479 	struct i40e_hw *hw = &pf->hw;
13480 
13481 	/* For simplicity, instead of removing the qp interrupt causes
13482 	 * from the interrupt linked list, we simply disable the interrupt, and
13483 	 * leave the list intact.
13484 	 *
13485 	 * All rings in a qp belong to the same qvector.
13486 	 */
13487 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
13488 		u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
13489 
13490 		wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
13491 		i40e_flush(hw);
13492 		synchronize_irq(pf->msix_entries[intpf].vector);
13493 	} else {
13494 		/* Legacy and MSI mode - this stops all interrupt handling */
13495 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
13496 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
13497 		i40e_flush(hw);
13498 		synchronize_irq(pf->pdev->irq);
13499 	}
13500 }
13501 
13502 /**
13503  * i40e_queue_pair_disable - Disables a queue pair
13504  * @vsi: vsi
13505  * @queue_pair: queue pair
13506  *
13507  * Returns 0 on success, <0 on failure.
13508  **/
13509 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
13510 {
13511 	int err;
13512 
13513 	err = i40e_enter_busy_conf(vsi);
13514 	if (err)
13515 		return err;
13516 
13517 	i40e_queue_pair_disable_irq(vsi, queue_pair);
13518 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
13519 	i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
13520 	i40e_queue_pair_clean_rings(vsi, queue_pair);
13521 	i40e_queue_pair_reset_stats(vsi, queue_pair);
13522 
13523 	return err;
13524 }
13525 
13526 /**
13527  * i40e_queue_pair_enable - Enables a queue pair
13528  * @vsi: vsi
13529  * @queue_pair: queue pair
13530  *
13531  * Returns 0 on success, <0 on failure.
13532  **/
13533 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
13534 {
13535 	int err;
13536 
13537 	err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
13538 	if (err)
13539 		return err;
13540 
13541 	if (i40e_enabled_xdp_vsi(vsi)) {
13542 		err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
13543 		if (err)
13544 			return err;
13545 	}
13546 
13547 	err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
13548 	if (err)
13549 		return err;
13550 
13551 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
13552 	i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
13553 	i40e_queue_pair_enable_irq(vsi, queue_pair);
13554 
13555 	i40e_exit_busy_conf(vsi);
13556 
13557 	return err;
13558 }
13559 
13560 /**
13561  * i40e_xdp - implements ndo_bpf for i40e
13562  * @dev: netdevice
13563  * @xdp: XDP command
13564  **/
13565 static int i40e_xdp(struct net_device *dev,
13566 		    struct netdev_bpf *xdp)
13567 {
13568 	struct i40e_netdev_priv *np = netdev_priv(dev);
13569 	struct i40e_vsi *vsi = np->vsi;
13570 
13571 	if (vsi->type != I40E_VSI_MAIN)
13572 		return -EINVAL;
13573 
13574 	switch (xdp->command) {
13575 	case XDP_SETUP_PROG:
13576 		return i40e_xdp_setup(vsi, xdp->prog, xdp->extack);
13577 	case XDP_SETUP_XSK_POOL:
13578 		return i40e_xsk_pool_setup(vsi, xdp->xsk.pool,
13579 					   xdp->xsk.queue_id);
13580 	default:
13581 		return -EINVAL;
13582 	}
13583 }
13584 
13585 static const struct net_device_ops i40e_netdev_ops = {
13586 	.ndo_open		= i40e_open,
13587 	.ndo_stop		= i40e_close,
13588 	.ndo_start_xmit		= i40e_lan_xmit_frame,
13589 	.ndo_get_stats64	= i40e_get_netdev_stats_struct,
13590 	.ndo_set_rx_mode	= i40e_set_rx_mode,
13591 	.ndo_validate_addr	= eth_validate_addr,
13592 	.ndo_set_mac_address	= i40e_set_mac,
13593 	.ndo_change_mtu		= i40e_change_mtu,
13594 	.ndo_eth_ioctl		= i40e_ioctl,
13595 	.ndo_tx_timeout		= i40e_tx_timeout,
13596 	.ndo_vlan_rx_add_vid	= i40e_vlan_rx_add_vid,
13597 	.ndo_vlan_rx_kill_vid	= i40e_vlan_rx_kill_vid,
13598 #ifdef CONFIG_NET_POLL_CONTROLLER
13599 	.ndo_poll_controller	= i40e_netpoll,
13600 #endif
13601 	.ndo_setup_tc		= __i40e_setup_tc,
13602 	.ndo_select_queue	= i40e_lan_select_queue,
13603 	.ndo_set_features	= i40e_set_features,
13604 	.ndo_set_vf_mac		= i40e_ndo_set_vf_mac,
13605 	.ndo_set_vf_vlan	= i40e_ndo_set_vf_port_vlan,
13606 	.ndo_get_vf_stats	= i40e_get_vf_stats,
13607 	.ndo_set_vf_rate	= i40e_ndo_set_vf_bw,
13608 	.ndo_get_vf_config	= i40e_ndo_get_vf_config,
13609 	.ndo_set_vf_link_state	= i40e_ndo_set_vf_link_state,
13610 	.ndo_set_vf_spoofchk	= i40e_ndo_set_vf_spoofchk,
13611 	.ndo_set_vf_trust	= i40e_ndo_set_vf_trust,
13612 	.ndo_get_phys_port_id	= i40e_get_phys_port_id,
13613 	.ndo_fdb_add		= i40e_ndo_fdb_add,
13614 	.ndo_features_check	= i40e_features_check,
13615 	.ndo_bridge_getlink	= i40e_ndo_bridge_getlink,
13616 	.ndo_bridge_setlink	= i40e_ndo_bridge_setlink,
13617 	.ndo_bpf		= i40e_xdp,
13618 	.ndo_xdp_xmit		= i40e_xdp_xmit,
13619 	.ndo_xsk_wakeup	        = i40e_xsk_wakeup,
13620 	.ndo_dfwd_add_station	= i40e_fwd_add,
13621 	.ndo_dfwd_del_station	= i40e_fwd_del,
13622 };
13623 
13624 /**
13625  * i40e_config_netdev - Setup the netdev flags
13626  * @vsi: the VSI being configured
13627  *
13628  * Returns 0 on success, negative value on failure
13629  **/
13630 static int i40e_config_netdev(struct i40e_vsi *vsi)
13631 {
13632 	struct i40e_pf *pf = vsi->back;
13633 	struct i40e_hw *hw = &pf->hw;
13634 	struct i40e_netdev_priv *np;
13635 	struct net_device *netdev;
13636 	u8 broadcast[ETH_ALEN];
13637 	u8 mac_addr[ETH_ALEN];
13638 	int etherdev_size;
13639 	netdev_features_t hw_enc_features;
13640 	netdev_features_t hw_features;
13641 
13642 	etherdev_size = sizeof(struct i40e_netdev_priv);
13643 	netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
13644 	if (!netdev)
13645 		return -ENOMEM;
13646 
13647 	vsi->netdev = netdev;
13648 	np = netdev_priv(netdev);
13649 	np->vsi = vsi;
13650 
13651 	hw_enc_features = NETIF_F_SG			|
13652 			  NETIF_F_HW_CSUM		|
13653 			  NETIF_F_HIGHDMA		|
13654 			  NETIF_F_SOFT_FEATURES		|
13655 			  NETIF_F_TSO			|
13656 			  NETIF_F_TSO_ECN		|
13657 			  NETIF_F_TSO6			|
13658 			  NETIF_F_GSO_GRE		|
13659 			  NETIF_F_GSO_GRE_CSUM		|
13660 			  NETIF_F_GSO_PARTIAL		|
13661 			  NETIF_F_GSO_IPXIP4		|
13662 			  NETIF_F_GSO_IPXIP6		|
13663 			  NETIF_F_GSO_UDP_TUNNEL	|
13664 			  NETIF_F_GSO_UDP_TUNNEL_CSUM	|
13665 			  NETIF_F_GSO_UDP_L4		|
13666 			  NETIF_F_SCTP_CRC		|
13667 			  NETIF_F_RXHASH		|
13668 			  NETIF_F_RXCSUM		|
13669 			  0;
13670 
13671 	if (!(pf->hw_features & I40E_HW_OUTER_UDP_CSUM_CAPABLE))
13672 		netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
13673 
13674 	netdev->udp_tunnel_nic_info = &pf->udp_tunnel_nic;
13675 
13676 	netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
13677 
13678 	netdev->hw_enc_features |= hw_enc_features;
13679 
13680 	/* record features VLANs can make use of */
13681 	netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
13682 
13683 #define I40E_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE |		\
13684 				   NETIF_F_GSO_GRE_CSUM |	\
13685 				   NETIF_F_GSO_IPXIP4 |		\
13686 				   NETIF_F_GSO_IPXIP6 |		\
13687 				   NETIF_F_GSO_UDP_TUNNEL |	\
13688 				   NETIF_F_GSO_UDP_TUNNEL_CSUM)
13689 
13690 	netdev->gso_partial_features = I40E_GSO_PARTIAL_FEATURES;
13691 	netdev->features |= NETIF_F_GSO_PARTIAL |
13692 			    I40E_GSO_PARTIAL_FEATURES;
13693 
13694 	netdev->mpls_features |= NETIF_F_SG;
13695 	netdev->mpls_features |= NETIF_F_HW_CSUM;
13696 	netdev->mpls_features |= NETIF_F_TSO;
13697 	netdev->mpls_features |= NETIF_F_TSO6;
13698 	netdev->mpls_features |= I40E_GSO_PARTIAL_FEATURES;
13699 
13700 	/* enable macvlan offloads */
13701 	netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
13702 
13703 	hw_features = hw_enc_features		|
13704 		      NETIF_F_HW_VLAN_CTAG_TX	|
13705 		      NETIF_F_HW_VLAN_CTAG_RX;
13706 
13707 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
13708 		hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
13709 
13710 	netdev->hw_features |= hw_features;
13711 
13712 	netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
13713 	netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
13714 
13715 	netdev->features &= ~NETIF_F_HW_TC;
13716 
13717 	if (vsi->type == I40E_VSI_MAIN) {
13718 		SET_NETDEV_DEV(netdev, &pf->pdev->dev);
13719 		ether_addr_copy(mac_addr, hw->mac.perm_addr);
13720 		/* The following steps are necessary for two reasons. First,
13721 		 * some older NVM configurations load a default MAC-VLAN
13722 		 * filter that will accept any tagged packet, and we want to
13723 		 * replace this with a normal filter. Additionally, it is
13724 		 * possible our MAC address was provided by the platform using
13725 		 * Open Firmware or similar.
13726 		 *
13727 		 * Thus, we need to remove the default filter and install one
13728 		 * specific to the MAC address.
13729 		 */
13730 		i40e_rm_default_mac_filter(vsi, mac_addr);
13731 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13732 		i40e_add_mac_filter(vsi, mac_addr);
13733 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13734 	} else {
13735 		/* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
13736 		 * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
13737 		 * the end, which is 4 bytes long, so force truncation of the
13738 		 * original name by IFNAMSIZ - 4
13739 		 */
13740 		snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d",
13741 			 IFNAMSIZ - 4,
13742 			 pf->vsi[pf->lan_vsi]->netdev->name);
13743 		eth_random_addr(mac_addr);
13744 
13745 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13746 		i40e_add_mac_filter(vsi, mac_addr);
13747 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13748 	}
13749 
13750 	/* Add the broadcast filter so that we initially will receive
13751 	 * broadcast packets. Note that when a new VLAN is first added the
13752 	 * driver will convert all filters marked I40E_VLAN_ANY into VLAN
13753 	 * specific filters as part of transitioning into "vlan" operation.
13754 	 * When more VLANs are added, the driver will copy each existing MAC
13755 	 * filter and add it for the new VLAN.
13756 	 *
13757 	 * Broadcast filters are handled specially by
13758 	 * i40e_sync_filters_subtask, as the driver must to set the broadcast
13759 	 * promiscuous bit instead of adding this directly as a MAC/VLAN
13760 	 * filter. The subtask will update the correct broadcast promiscuous
13761 	 * bits as VLANs become active or inactive.
13762 	 */
13763 	eth_broadcast_addr(broadcast);
13764 	spin_lock_bh(&vsi->mac_filter_hash_lock);
13765 	i40e_add_mac_filter(vsi, broadcast);
13766 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
13767 
13768 	eth_hw_addr_set(netdev, mac_addr);
13769 	ether_addr_copy(netdev->perm_addr, mac_addr);
13770 
13771 	/* i40iw_net_event() reads 16 bytes from neigh->primary_key */
13772 	netdev->neigh_priv_len = sizeof(u32) * 4;
13773 
13774 	netdev->priv_flags |= IFF_UNICAST_FLT;
13775 	netdev->priv_flags |= IFF_SUPP_NOFCS;
13776 	/* Setup netdev TC information */
13777 	i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
13778 
13779 	netdev->netdev_ops = &i40e_netdev_ops;
13780 	netdev->watchdog_timeo = 5 * HZ;
13781 	i40e_set_ethtool_ops(netdev);
13782 
13783 	/* MTU range: 68 - 9706 */
13784 	netdev->min_mtu = ETH_MIN_MTU;
13785 	netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13786 
13787 	return 0;
13788 }
13789 
13790 /**
13791  * i40e_vsi_delete - Delete a VSI from the switch
13792  * @vsi: the VSI being removed
13793  *
13794  * Returns 0 on success, negative value on failure
13795  **/
13796 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13797 {
13798 	/* remove default VSI is not allowed */
13799 	if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13800 		return;
13801 
13802 	i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13803 }
13804 
13805 /**
13806  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13807  * @vsi: the VSI being queried
13808  *
13809  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13810  **/
13811 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13812 {
13813 	struct i40e_veb *veb;
13814 	struct i40e_pf *pf = vsi->back;
13815 
13816 	/* Uplink is not a bridge so default to VEB */
13817 	if (vsi->veb_idx >= I40E_MAX_VEB)
13818 		return 1;
13819 
13820 	veb = pf->veb[vsi->veb_idx];
13821 	if (!veb) {
13822 		dev_info(&pf->pdev->dev,
13823 			 "There is no veb associated with the bridge\n");
13824 		return -ENOENT;
13825 	}
13826 
13827 	/* Uplink is a bridge in VEPA mode */
13828 	if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13829 		return 0;
13830 	} else {
13831 		/* Uplink is a bridge in VEB mode */
13832 		return 1;
13833 	}
13834 
13835 	/* VEPA is now default bridge, so return 0 */
13836 	return 0;
13837 }
13838 
13839 /**
13840  * i40e_add_vsi - Add a VSI to the switch
13841  * @vsi: the VSI being configured
13842  *
13843  * This initializes a VSI context depending on the VSI type to be added and
13844  * passes it down to the add_vsi aq command.
13845  **/
13846 static int i40e_add_vsi(struct i40e_vsi *vsi)
13847 {
13848 	int ret = -ENODEV;
13849 	struct i40e_pf *pf = vsi->back;
13850 	struct i40e_hw *hw = &pf->hw;
13851 	struct i40e_vsi_context ctxt;
13852 	struct i40e_mac_filter *f;
13853 	struct hlist_node *h;
13854 	int bkt;
13855 
13856 	u8 enabled_tc = 0x1; /* TC0 enabled */
13857 	int f_count = 0;
13858 
13859 	memset(&ctxt, 0, sizeof(ctxt));
13860 	switch (vsi->type) {
13861 	case I40E_VSI_MAIN:
13862 		/* The PF's main VSI is already setup as part of the
13863 		 * device initialization, so we'll not bother with
13864 		 * the add_vsi call, but we will retrieve the current
13865 		 * VSI context.
13866 		 */
13867 		ctxt.seid = pf->main_vsi_seid;
13868 		ctxt.pf_num = pf->hw.pf_id;
13869 		ctxt.vf_num = 0;
13870 		ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13871 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13872 		if (ret) {
13873 			dev_info(&pf->pdev->dev,
13874 				 "couldn't get PF vsi config, err %s aq_err %s\n",
13875 				 i40e_stat_str(&pf->hw, ret),
13876 				 i40e_aq_str(&pf->hw,
13877 					     pf->hw.aq.asq_last_status));
13878 			return -ENOENT;
13879 		}
13880 		vsi->info = ctxt.info;
13881 		vsi->info.valid_sections = 0;
13882 
13883 		vsi->seid = ctxt.seid;
13884 		vsi->id = ctxt.vsi_number;
13885 
13886 		enabled_tc = i40e_pf_get_tc_map(pf);
13887 
13888 		/* Source pruning is enabled by default, so the flag is
13889 		 * negative logic - if it's set, we need to fiddle with
13890 		 * the VSI to disable source pruning.
13891 		 */
13892 		if (pf->flags & I40E_FLAG_SOURCE_PRUNING_DISABLED) {
13893 			memset(&ctxt, 0, sizeof(ctxt));
13894 			ctxt.seid = pf->main_vsi_seid;
13895 			ctxt.pf_num = pf->hw.pf_id;
13896 			ctxt.vf_num = 0;
13897 			ctxt.info.valid_sections |=
13898 				     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13899 			ctxt.info.switch_id =
13900 				   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13901 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13902 			if (ret) {
13903 				dev_info(&pf->pdev->dev,
13904 					 "update vsi failed, err %s aq_err %s\n",
13905 					 i40e_stat_str(&pf->hw, ret),
13906 					 i40e_aq_str(&pf->hw,
13907 						     pf->hw.aq.asq_last_status));
13908 				ret = -ENOENT;
13909 				goto err;
13910 			}
13911 		}
13912 
13913 		/* MFP mode setup queue map and update VSI */
13914 		if ((pf->flags & I40E_FLAG_MFP_ENABLED) &&
13915 		    !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
13916 			memset(&ctxt, 0, sizeof(ctxt));
13917 			ctxt.seid = pf->main_vsi_seid;
13918 			ctxt.pf_num = pf->hw.pf_id;
13919 			ctxt.vf_num = 0;
13920 			i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
13921 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13922 			if (ret) {
13923 				dev_info(&pf->pdev->dev,
13924 					 "update vsi failed, err %s aq_err %s\n",
13925 					 i40e_stat_str(&pf->hw, ret),
13926 					 i40e_aq_str(&pf->hw,
13927 						    pf->hw.aq.asq_last_status));
13928 				ret = -ENOENT;
13929 				goto err;
13930 			}
13931 			/* update the local VSI info queue map */
13932 			i40e_vsi_update_queue_map(vsi, &ctxt);
13933 			vsi->info.valid_sections = 0;
13934 		} else {
13935 			/* Default/Main VSI is only enabled for TC0
13936 			 * reconfigure it to enable all TCs that are
13937 			 * available on the port in SFP mode.
13938 			 * For MFP case the iSCSI PF would use this
13939 			 * flow to enable LAN+iSCSI TC.
13940 			 */
13941 			ret = i40e_vsi_config_tc(vsi, enabled_tc);
13942 			if (ret) {
13943 				/* Single TC condition is not fatal,
13944 				 * message and continue
13945 				 */
13946 				dev_info(&pf->pdev->dev,
13947 					 "failed to configure TCs for main VSI tc_map 0x%08x, err %s aq_err %s\n",
13948 					 enabled_tc,
13949 					 i40e_stat_str(&pf->hw, ret),
13950 					 i40e_aq_str(&pf->hw,
13951 						    pf->hw.aq.asq_last_status));
13952 			}
13953 		}
13954 		break;
13955 
13956 	case I40E_VSI_FDIR:
13957 		ctxt.pf_num = hw->pf_id;
13958 		ctxt.vf_num = 0;
13959 		ctxt.uplink_seid = vsi->uplink_seid;
13960 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13961 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13962 		if ((pf->flags & I40E_FLAG_VEB_MODE_ENABLED) &&
13963 		    (i40e_is_vsi_uplink_mode_veb(vsi))) {
13964 			ctxt.info.valid_sections |=
13965 			     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13966 			ctxt.info.switch_id =
13967 			   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13968 		}
13969 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13970 		break;
13971 
13972 	case I40E_VSI_VMDQ2:
13973 		ctxt.pf_num = hw->pf_id;
13974 		ctxt.vf_num = 0;
13975 		ctxt.uplink_seid = vsi->uplink_seid;
13976 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13977 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
13978 
13979 		/* This VSI is connected to VEB so the switch_id
13980 		 * should be set to zero by default.
13981 		 */
13982 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13983 			ctxt.info.valid_sections |=
13984 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13985 			ctxt.info.switch_id =
13986 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13987 		}
13988 
13989 		/* Setup the VSI tx/rx queue map for TC0 only for now */
13990 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13991 		break;
13992 
13993 	case I40E_VSI_SRIOV:
13994 		ctxt.pf_num = hw->pf_id;
13995 		ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
13996 		ctxt.uplink_seid = vsi->uplink_seid;
13997 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13998 		ctxt.flags = I40E_AQ_VSI_TYPE_VF;
13999 
14000 		/* This VSI is connected to VEB so the switch_id
14001 		 * should be set to zero by default.
14002 		 */
14003 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14004 			ctxt.info.valid_sections |=
14005 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14006 			ctxt.info.switch_id =
14007 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14008 		}
14009 
14010 		if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
14011 			ctxt.info.valid_sections |=
14012 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
14013 			ctxt.info.queueing_opt_flags |=
14014 				(I40E_AQ_VSI_QUE_OPT_TCP_ENA |
14015 				 I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
14016 		}
14017 
14018 		ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
14019 		ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
14020 		if (pf->vf[vsi->vf_id].spoofchk) {
14021 			ctxt.info.valid_sections |=
14022 				cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
14023 			ctxt.info.sec_flags |=
14024 				(I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
14025 				 I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
14026 		}
14027 		/* Setup the VSI tx/rx queue map for TC0 only for now */
14028 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14029 		break;
14030 
14031 	case I40E_VSI_IWARP:
14032 		/* send down message to iWARP */
14033 		break;
14034 
14035 	default:
14036 		return -ENODEV;
14037 	}
14038 
14039 	if (vsi->type != I40E_VSI_MAIN) {
14040 		ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
14041 		if (ret) {
14042 			dev_info(&vsi->back->pdev->dev,
14043 				 "add vsi failed, err %s aq_err %s\n",
14044 				 i40e_stat_str(&pf->hw, ret),
14045 				 i40e_aq_str(&pf->hw,
14046 					     pf->hw.aq.asq_last_status));
14047 			ret = -ENOENT;
14048 			goto err;
14049 		}
14050 		vsi->info = ctxt.info;
14051 		vsi->info.valid_sections = 0;
14052 		vsi->seid = ctxt.seid;
14053 		vsi->id = ctxt.vsi_number;
14054 	}
14055 
14056 	vsi->active_filters = 0;
14057 	clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
14058 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14059 	/* If macvlan filters already exist, force them to get loaded */
14060 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
14061 		f->state = I40E_FILTER_NEW;
14062 		f_count++;
14063 	}
14064 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14065 
14066 	if (f_count) {
14067 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
14068 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
14069 	}
14070 
14071 	/* Update VSI BW information */
14072 	ret = i40e_vsi_get_bw_info(vsi);
14073 	if (ret) {
14074 		dev_info(&pf->pdev->dev,
14075 			 "couldn't get vsi bw info, err %s aq_err %s\n",
14076 			 i40e_stat_str(&pf->hw, ret),
14077 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14078 		/* VSI is already added so not tearing that up */
14079 		ret = 0;
14080 	}
14081 
14082 err:
14083 	return ret;
14084 }
14085 
14086 /**
14087  * i40e_vsi_release - Delete a VSI and free its resources
14088  * @vsi: the VSI being removed
14089  *
14090  * Returns 0 on success or < 0 on error
14091  **/
14092 int i40e_vsi_release(struct i40e_vsi *vsi)
14093 {
14094 	struct i40e_mac_filter *f;
14095 	struct hlist_node *h;
14096 	struct i40e_veb *veb = NULL;
14097 	struct i40e_pf *pf;
14098 	u16 uplink_seid;
14099 	int i, n, bkt;
14100 
14101 	pf = vsi->back;
14102 
14103 	/* release of a VEB-owner or last VSI is not allowed */
14104 	if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
14105 		dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
14106 			 vsi->seid, vsi->uplink_seid);
14107 		return -ENODEV;
14108 	}
14109 	if (vsi == pf->vsi[pf->lan_vsi] &&
14110 	    !test_bit(__I40E_DOWN, pf->state)) {
14111 		dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
14112 		return -ENODEV;
14113 	}
14114 	set_bit(__I40E_VSI_RELEASING, vsi->state);
14115 	uplink_seid = vsi->uplink_seid;
14116 	if (vsi->type != I40E_VSI_SRIOV) {
14117 		if (vsi->netdev_registered) {
14118 			vsi->netdev_registered = false;
14119 			if (vsi->netdev) {
14120 				/* results in a call to i40e_close() */
14121 				unregister_netdev(vsi->netdev);
14122 			}
14123 		} else {
14124 			i40e_vsi_close(vsi);
14125 		}
14126 		i40e_vsi_disable_irq(vsi);
14127 	}
14128 
14129 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14130 
14131 	/* clear the sync flag on all filters */
14132 	if (vsi->netdev) {
14133 		__dev_uc_unsync(vsi->netdev, NULL);
14134 		__dev_mc_unsync(vsi->netdev, NULL);
14135 	}
14136 
14137 	/* make sure any remaining filters are marked for deletion */
14138 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
14139 		__i40e_del_filter(vsi, f);
14140 
14141 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14142 
14143 	i40e_sync_vsi_filters(vsi);
14144 
14145 	i40e_vsi_delete(vsi);
14146 	i40e_vsi_free_q_vectors(vsi);
14147 	if (vsi->netdev) {
14148 		free_netdev(vsi->netdev);
14149 		vsi->netdev = NULL;
14150 	}
14151 	i40e_vsi_clear_rings(vsi);
14152 	i40e_vsi_clear(vsi);
14153 
14154 	/* If this was the last thing on the VEB, except for the
14155 	 * controlling VSI, remove the VEB, which puts the controlling
14156 	 * VSI onto the next level down in the switch.
14157 	 *
14158 	 * Well, okay, there's one more exception here: don't remove
14159 	 * the orphan VEBs yet.  We'll wait for an explicit remove request
14160 	 * from up the network stack.
14161 	 */
14162 	for (n = 0, i = 0; i < pf->num_alloc_vsi; i++) {
14163 		if (pf->vsi[i] &&
14164 		    pf->vsi[i]->uplink_seid == uplink_seid &&
14165 		    (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14166 			n++;      /* count the VSIs */
14167 		}
14168 	}
14169 	for (i = 0; i < I40E_MAX_VEB; i++) {
14170 		if (!pf->veb[i])
14171 			continue;
14172 		if (pf->veb[i]->uplink_seid == uplink_seid)
14173 			n++;     /* count the VEBs */
14174 		if (pf->veb[i]->seid == uplink_seid)
14175 			veb = pf->veb[i];
14176 	}
14177 	if (n == 0 && veb && veb->uplink_seid != 0)
14178 		i40e_veb_release(veb);
14179 
14180 	return 0;
14181 }
14182 
14183 /**
14184  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
14185  * @vsi: ptr to the VSI
14186  *
14187  * This should only be called after i40e_vsi_mem_alloc() which allocates the
14188  * corresponding SW VSI structure and initializes num_queue_pairs for the
14189  * newly allocated VSI.
14190  *
14191  * Returns 0 on success or negative on failure
14192  **/
14193 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
14194 {
14195 	int ret = -ENOENT;
14196 	struct i40e_pf *pf = vsi->back;
14197 
14198 	if (vsi->q_vectors[0]) {
14199 		dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
14200 			 vsi->seid);
14201 		return -EEXIST;
14202 	}
14203 
14204 	if (vsi->base_vector) {
14205 		dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
14206 			 vsi->seid, vsi->base_vector);
14207 		return -EEXIST;
14208 	}
14209 
14210 	ret = i40e_vsi_alloc_q_vectors(vsi);
14211 	if (ret) {
14212 		dev_info(&pf->pdev->dev,
14213 			 "failed to allocate %d q_vector for VSI %d, ret=%d\n",
14214 			 vsi->num_q_vectors, vsi->seid, ret);
14215 		vsi->num_q_vectors = 0;
14216 		goto vector_setup_out;
14217 	}
14218 
14219 	/* In Legacy mode, we do not have to get any other vector since we
14220 	 * piggyback on the misc/ICR0 for queue interrupts.
14221 	*/
14222 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
14223 		return ret;
14224 	if (vsi->num_q_vectors)
14225 		vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
14226 						 vsi->num_q_vectors, vsi->idx);
14227 	if (vsi->base_vector < 0) {
14228 		dev_info(&pf->pdev->dev,
14229 			 "failed to get tracking for %d vectors for VSI %d, err=%d\n",
14230 			 vsi->num_q_vectors, vsi->seid, vsi->base_vector);
14231 		i40e_vsi_free_q_vectors(vsi);
14232 		ret = -ENOENT;
14233 		goto vector_setup_out;
14234 	}
14235 
14236 vector_setup_out:
14237 	return ret;
14238 }
14239 
14240 /**
14241  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
14242  * @vsi: pointer to the vsi.
14243  *
14244  * This re-allocates a vsi's queue resources.
14245  *
14246  * Returns pointer to the successfully allocated and configured VSI sw struct
14247  * on success, otherwise returns NULL on failure.
14248  **/
14249 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
14250 {
14251 	u16 alloc_queue_pairs;
14252 	struct i40e_pf *pf;
14253 	u8 enabled_tc;
14254 	int ret;
14255 
14256 	if (!vsi)
14257 		return NULL;
14258 
14259 	pf = vsi->back;
14260 
14261 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
14262 	i40e_vsi_clear_rings(vsi);
14263 
14264 	i40e_vsi_free_arrays(vsi, false);
14265 	i40e_set_num_rings_in_vsi(vsi);
14266 	ret = i40e_vsi_alloc_arrays(vsi, false);
14267 	if (ret)
14268 		goto err_vsi;
14269 
14270 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14271 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14272 
14273 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14274 	if (ret < 0) {
14275 		dev_info(&pf->pdev->dev,
14276 			 "failed to get tracking for %d queues for VSI %d err %d\n",
14277 			 alloc_queue_pairs, vsi->seid, ret);
14278 		goto err_vsi;
14279 	}
14280 	vsi->base_queue = ret;
14281 
14282 	/* Update the FW view of the VSI. Force a reset of TC and queue
14283 	 * layout configurations.
14284 	 */
14285 	enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
14286 	pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
14287 	pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
14288 	i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
14289 	if (vsi->type == I40E_VSI_MAIN)
14290 		i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
14291 
14292 	/* assign it some queues */
14293 	ret = i40e_alloc_rings(vsi);
14294 	if (ret)
14295 		goto err_rings;
14296 
14297 	/* map all of the rings to the q_vectors */
14298 	i40e_vsi_map_rings_to_vectors(vsi);
14299 	return vsi;
14300 
14301 err_rings:
14302 	i40e_vsi_free_q_vectors(vsi);
14303 	if (vsi->netdev_registered) {
14304 		vsi->netdev_registered = false;
14305 		unregister_netdev(vsi->netdev);
14306 		free_netdev(vsi->netdev);
14307 		vsi->netdev = NULL;
14308 	}
14309 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14310 err_vsi:
14311 	i40e_vsi_clear(vsi);
14312 	return NULL;
14313 }
14314 
14315 /**
14316  * i40e_vsi_setup - Set up a VSI by a given type
14317  * @pf: board private structure
14318  * @type: VSI type
14319  * @uplink_seid: the switch element to link to
14320  * @param1: usage depends upon VSI type. For VF types, indicates VF id
14321  *
14322  * This allocates the sw VSI structure and its queue resources, then add a VSI
14323  * to the identified VEB.
14324  *
14325  * Returns pointer to the successfully allocated and configure VSI sw struct on
14326  * success, otherwise returns NULL on failure.
14327  **/
14328 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
14329 				u16 uplink_seid, u32 param1)
14330 {
14331 	struct i40e_vsi *vsi = NULL;
14332 	struct i40e_veb *veb = NULL;
14333 	u16 alloc_queue_pairs;
14334 	int ret, i;
14335 	int v_idx;
14336 
14337 	/* The requested uplink_seid must be either
14338 	 *     - the PF's port seid
14339 	 *              no VEB is needed because this is the PF
14340 	 *              or this is a Flow Director special case VSI
14341 	 *     - seid of an existing VEB
14342 	 *     - seid of a VSI that owns an existing VEB
14343 	 *     - seid of a VSI that doesn't own a VEB
14344 	 *              a new VEB is created and the VSI becomes the owner
14345 	 *     - seid of the PF VSI, which is what creates the first VEB
14346 	 *              this is a special case of the previous
14347 	 *
14348 	 * Find which uplink_seid we were given and create a new VEB if needed
14349 	 */
14350 	for (i = 0; i < I40E_MAX_VEB; i++) {
14351 		if (pf->veb[i] && pf->veb[i]->seid == uplink_seid) {
14352 			veb = pf->veb[i];
14353 			break;
14354 		}
14355 	}
14356 
14357 	if (!veb && uplink_seid != pf->mac_seid) {
14358 
14359 		for (i = 0; i < pf->num_alloc_vsi; i++) {
14360 			if (pf->vsi[i] && pf->vsi[i]->seid == uplink_seid) {
14361 				vsi = pf->vsi[i];
14362 				break;
14363 			}
14364 		}
14365 		if (!vsi) {
14366 			dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
14367 				 uplink_seid);
14368 			return NULL;
14369 		}
14370 
14371 		if (vsi->uplink_seid == pf->mac_seid)
14372 			veb = i40e_veb_setup(pf, 0, pf->mac_seid, vsi->seid,
14373 					     vsi->tc_config.enabled_tc);
14374 		else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14375 			veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
14376 					     vsi->tc_config.enabled_tc);
14377 		if (veb) {
14378 			if (vsi->seid != pf->vsi[pf->lan_vsi]->seid) {
14379 				dev_info(&vsi->back->pdev->dev,
14380 					 "New VSI creation error, uplink seid of LAN VSI expected.\n");
14381 				return NULL;
14382 			}
14383 			/* We come up by default in VEPA mode if SRIOV is not
14384 			 * already enabled, in which case we can't force VEPA
14385 			 * mode.
14386 			 */
14387 			if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
14388 				veb->bridge_mode = BRIDGE_MODE_VEPA;
14389 				pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
14390 			}
14391 			i40e_config_bridge_mode(veb);
14392 		}
14393 		for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
14394 			if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
14395 				veb = pf->veb[i];
14396 		}
14397 		if (!veb) {
14398 			dev_info(&pf->pdev->dev, "couldn't add VEB\n");
14399 			return NULL;
14400 		}
14401 
14402 		vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14403 		uplink_seid = veb->seid;
14404 	}
14405 
14406 	/* get vsi sw struct */
14407 	v_idx = i40e_vsi_mem_alloc(pf, type);
14408 	if (v_idx < 0)
14409 		goto err_alloc;
14410 	vsi = pf->vsi[v_idx];
14411 	if (!vsi)
14412 		goto err_alloc;
14413 	vsi->type = type;
14414 	vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
14415 
14416 	if (type == I40E_VSI_MAIN)
14417 		pf->lan_vsi = v_idx;
14418 	else if (type == I40E_VSI_SRIOV)
14419 		vsi->vf_id = param1;
14420 	/* assign it some queues */
14421 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14422 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14423 
14424 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14425 	if (ret < 0) {
14426 		dev_info(&pf->pdev->dev,
14427 			 "failed to get tracking for %d queues for VSI %d err=%d\n",
14428 			 alloc_queue_pairs, vsi->seid, ret);
14429 		goto err_vsi;
14430 	}
14431 	vsi->base_queue = ret;
14432 
14433 	/* get a VSI from the hardware */
14434 	vsi->uplink_seid = uplink_seid;
14435 	ret = i40e_add_vsi(vsi);
14436 	if (ret)
14437 		goto err_vsi;
14438 
14439 	switch (vsi->type) {
14440 	/* setup the netdev if needed */
14441 	case I40E_VSI_MAIN:
14442 	case I40E_VSI_VMDQ2:
14443 		ret = i40e_config_netdev(vsi);
14444 		if (ret)
14445 			goto err_netdev;
14446 		ret = i40e_netif_set_realnum_tx_rx_queues(vsi);
14447 		if (ret)
14448 			goto err_netdev;
14449 		ret = register_netdev(vsi->netdev);
14450 		if (ret)
14451 			goto err_netdev;
14452 		vsi->netdev_registered = true;
14453 		netif_carrier_off(vsi->netdev);
14454 #ifdef CONFIG_I40E_DCB
14455 		/* Setup DCB netlink interface */
14456 		i40e_dcbnl_setup(vsi);
14457 #endif /* CONFIG_I40E_DCB */
14458 		fallthrough;
14459 	case I40E_VSI_FDIR:
14460 		/* set up vectors and rings if needed */
14461 		ret = i40e_vsi_setup_vectors(vsi);
14462 		if (ret)
14463 			goto err_msix;
14464 
14465 		ret = i40e_alloc_rings(vsi);
14466 		if (ret)
14467 			goto err_rings;
14468 
14469 		/* map all of the rings to the q_vectors */
14470 		i40e_vsi_map_rings_to_vectors(vsi);
14471 
14472 		i40e_vsi_reset_stats(vsi);
14473 		break;
14474 	default:
14475 		/* no netdev or rings for the other VSI types */
14476 		break;
14477 	}
14478 
14479 	if ((pf->hw_features & I40E_HW_RSS_AQ_CAPABLE) &&
14480 	    (vsi->type == I40E_VSI_VMDQ2)) {
14481 		ret = i40e_vsi_config_rss(vsi);
14482 	}
14483 	return vsi;
14484 
14485 err_rings:
14486 	i40e_vsi_free_q_vectors(vsi);
14487 err_msix:
14488 	if (vsi->netdev_registered) {
14489 		vsi->netdev_registered = false;
14490 		unregister_netdev(vsi->netdev);
14491 		free_netdev(vsi->netdev);
14492 		vsi->netdev = NULL;
14493 	}
14494 err_netdev:
14495 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14496 err_vsi:
14497 	i40e_vsi_clear(vsi);
14498 err_alloc:
14499 	return NULL;
14500 }
14501 
14502 /**
14503  * i40e_veb_get_bw_info - Query VEB BW information
14504  * @veb: the veb to query
14505  *
14506  * Query the Tx scheduler BW configuration data for given VEB
14507  **/
14508 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
14509 {
14510 	struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
14511 	struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
14512 	struct i40e_pf *pf = veb->pf;
14513 	struct i40e_hw *hw = &pf->hw;
14514 	u32 tc_bw_max;
14515 	int ret = 0;
14516 	int i;
14517 
14518 	ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
14519 						  &bw_data, NULL);
14520 	if (ret) {
14521 		dev_info(&pf->pdev->dev,
14522 			 "query veb bw config failed, err %s aq_err %s\n",
14523 			 i40e_stat_str(&pf->hw, ret),
14524 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14525 		goto out;
14526 	}
14527 
14528 	ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
14529 						   &ets_data, NULL);
14530 	if (ret) {
14531 		dev_info(&pf->pdev->dev,
14532 			 "query veb bw ets config failed, err %s aq_err %s\n",
14533 			 i40e_stat_str(&pf->hw, ret),
14534 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14535 		goto out;
14536 	}
14537 
14538 	veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
14539 	veb->bw_max_quanta = ets_data.tc_bw_max;
14540 	veb->is_abs_credits = bw_data.absolute_credits_enable;
14541 	veb->enabled_tc = ets_data.tc_valid_bits;
14542 	tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
14543 		    (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
14544 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
14545 		veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
14546 		veb->bw_tc_limit_credits[i] =
14547 					le16_to_cpu(bw_data.tc_bw_limits[i]);
14548 		veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
14549 	}
14550 
14551 out:
14552 	return ret;
14553 }
14554 
14555 /**
14556  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
14557  * @pf: board private structure
14558  *
14559  * On error: returns error code (negative)
14560  * On success: returns vsi index in PF (positive)
14561  **/
14562 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
14563 {
14564 	int ret = -ENOENT;
14565 	struct i40e_veb *veb;
14566 	int i;
14567 
14568 	/* Need to protect the allocation of switch elements at the PF level */
14569 	mutex_lock(&pf->switch_mutex);
14570 
14571 	/* VEB list may be fragmented if VEB creation/destruction has
14572 	 * been happening.  We can afford to do a quick scan to look
14573 	 * for any free slots in the list.
14574 	 *
14575 	 * find next empty veb slot, looping back around if necessary
14576 	 */
14577 	i = 0;
14578 	while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
14579 		i++;
14580 	if (i >= I40E_MAX_VEB) {
14581 		ret = -ENOMEM;
14582 		goto err_alloc_veb;  /* out of VEB slots! */
14583 	}
14584 
14585 	veb = kzalloc(sizeof(*veb), GFP_KERNEL);
14586 	if (!veb) {
14587 		ret = -ENOMEM;
14588 		goto err_alloc_veb;
14589 	}
14590 	veb->pf = pf;
14591 	veb->idx = i;
14592 	veb->enabled_tc = 1;
14593 
14594 	pf->veb[i] = veb;
14595 	ret = i;
14596 err_alloc_veb:
14597 	mutex_unlock(&pf->switch_mutex);
14598 	return ret;
14599 }
14600 
14601 /**
14602  * i40e_switch_branch_release - Delete a branch of the switch tree
14603  * @branch: where to start deleting
14604  *
14605  * This uses recursion to find the tips of the branch to be
14606  * removed, deleting until we get back to and can delete this VEB.
14607  **/
14608 static void i40e_switch_branch_release(struct i40e_veb *branch)
14609 {
14610 	struct i40e_pf *pf = branch->pf;
14611 	u16 branch_seid = branch->seid;
14612 	u16 veb_idx = branch->idx;
14613 	int i;
14614 
14615 	/* release any VEBs on this VEB - RECURSION */
14616 	for (i = 0; i < I40E_MAX_VEB; i++) {
14617 		if (!pf->veb[i])
14618 			continue;
14619 		if (pf->veb[i]->uplink_seid == branch->seid)
14620 			i40e_switch_branch_release(pf->veb[i]);
14621 	}
14622 
14623 	/* Release the VSIs on this VEB, but not the owner VSI.
14624 	 *
14625 	 * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
14626 	 *       the VEB itself, so don't use (*branch) after this loop.
14627 	 */
14628 	for (i = 0; i < pf->num_alloc_vsi; i++) {
14629 		if (!pf->vsi[i])
14630 			continue;
14631 		if (pf->vsi[i]->uplink_seid == branch_seid &&
14632 		   (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14633 			i40e_vsi_release(pf->vsi[i]);
14634 		}
14635 	}
14636 
14637 	/* There's one corner case where the VEB might not have been
14638 	 * removed, so double check it here and remove it if needed.
14639 	 * This case happens if the veb was created from the debugfs
14640 	 * commands and no VSIs were added to it.
14641 	 */
14642 	if (pf->veb[veb_idx])
14643 		i40e_veb_release(pf->veb[veb_idx]);
14644 }
14645 
14646 /**
14647  * i40e_veb_clear - remove veb struct
14648  * @veb: the veb to remove
14649  **/
14650 static void i40e_veb_clear(struct i40e_veb *veb)
14651 {
14652 	if (!veb)
14653 		return;
14654 
14655 	if (veb->pf) {
14656 		struct i40e_pf *pf = veb->pf;
14657 
14658 		mutex_lock(&pf->switch_mutex);
14659 		if (pf->veb[veb->idx] == veb)
14660 			pf->veb[veb->idx] = NULL;
14661 		mutex_unlock(&pf->switch_mutex);
14662 	}
14663 
14664 	kfree(veb);
14665 }
14666 
14667 /**
14668  * i40e_veb_release - Delete a VEB and free its resources
14669  * @veb: the VEB being removed
14670  **/
14671 void i40e_veb_release(struct i40e_veb *veb)
14672 {
14673 	struct i40e_vsi *vsi = NULL;
14674 	struct i40e_pf *pf;
14675 	int i, n = 0;
14676 
14677 	pf = veb->pf;
14678 
14679 	/* find the remaining VSI and check for extras */
14680 	for (i = 0; i < pf->num_alloc_vsi; i++) {
14681 		if (pf->vsi[i] && pf->vsi[i]->uplink_seid == veb->seid) {
14682 			n++;
14683 			vsi = pf->vsi[i];
14684 		}
14685 	}
14686 	if (n != 1) {
14687 		dev_info(&pf->pdev->dev,
14688 			 "can't remove VEB %d with %d VSIs left\n",
14689 			 veb->seid, n);
14690 		return;
14691 	}
14692 
14693 	/* move the remaining VSI to uplink veb */
14694 	vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
14695 	if (veb->uplink_seid) {
14696 		vsi->uplink_seid = veb->uplink_seid;
14697 		if (veb->uplink_seid == pf->mac_seid)
14698 			vsi->veb_idx = I40E_NO_VEB;
14699 		else
14700 			vsi->veb_idx = veb->veb_idx;
14701 	} else {
14702 		/* floating VEB */
14703 		vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
14704 		vsi->veb_idx = pf->vsi[pf->lan_vsi]->veb_idx;
14705 	}
14706 
14707 	i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14708 	i40e_veb_clear(veb);
14709 }
14710 
14711 /**
14712  * i40e_add_veb - create the VEB in the switch
14713  * @veb: the VEB to be instantiated
14714  * @vsi: the controlling VSI
14715  **/
14716 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
14717 {
14718 	struct i40e_pf *pf = veb->pf;
14719 	bool enable_stats = !!(pf->flags & I40E_FLAG_VEB_STATS_ENABLED);
14720 	int ret;
14721 
14722 	ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi->seid,
14723 			      veb->enabled_tc, false,
14724 			      &veb->seid, enable_stats, NULL);
14725 
14726 	/* get a VEB from the hardware */
14727 	if (ret) {
14728 		dev_info(&pf->pdev->dev,
14729 			 "couldn't add VEB, err %s aq_err %s\n",
14730 			 i40e_stat_str(&pf->hw, ret),
14731 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14732 		return -EPERM;
14733 	}
14734 
14735 	/* get statistics counter */
14736 	ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
14737 					 &veb->stats_idx, NULL, NULL, NULL);
14738 	if (ret) {
14739 		dev_info(&pf->pdev->dev,
14740 			 "couldn't get VEB statistics idx, err %s aq_err %s\n",
14741 			 i40e_stat_str(&pf->hw, ret),
14742 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14743 		return -EPERM;
14744 	}
14745 	ret = i40e_veb_get_bw_info(veb);
14746 	if (ret) {
14747 		dev_info(&pf->pdev->dev,
14748 			 "couldn't get VEB bw info, err %s aq_err %s\n",
14749 			 i40e_stat_str(&pf->hw, ret),
14750 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14751 		i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14752 		return -ENOENT;
14753 	}
14754 
14755 	vsi->uplink_seid = veb->seid;
14756 	vsi->veb_idx = veb->idx;
14757 	vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14758 
14759 	return 0;
14760 }
14761 
14762 /**
14763  * i40e_veb_setup - Set up a VEB
14764  * @pf: board private structure
14765  * @flags: VEB setup flags
14766  * @uplink_seid: the switch element to link to
14767  * @vsi_seid: the initial VSI seid
14768  * @enabled_tc: Enabled TC bit-map
14769  *
14770  * This allocates the sw VEB structure and links it into the switch
14771  * It is possible and legal for this to be a duplicate of an already
14772  * existing VEB.  It is also possible for both uplink and vsi seids
14773  * to be zero, in order to create a floating VEB.
14774  *
14775  * Returns pointer to the successfully allocated VEB sw struct on
14776  * success, otherwise returns NULL on failure.
14777  **/
14778 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 flags,
14779 				u16 uplink_seid, u16 vsi_seid,
14780 				u8 enabled_tc)
14781 {
14782 	struct i40e_veb *veb, *uplink_veb = NULL;
14783 	int vsi_idx, veb_idx;
14784 	int ret;
14785 
14786 	/* if one seid is 0, the other must be 0 to create a floating relay */
14787 	if ((uplink_seid == 0 || vsi_seid == 0) &&
14788 	    (uplink_seid + vsi_seid != 0)) {
14789 		dev_info(&pf->pdev->dev,
14790 			 "one, not both seid's are 0: uplink=%d vsi=%d\n",
14791 			 uplink_seid, vsi_seid);
14792 		return NULL;
14793 	}
14794 
14795 	/* make sure there is such a vsi and uplink */
14796 	for (vsi_idx = 0; vsi_idx < pf->num_alloc_vsi; vsi_idx++)
14797 		if (pf->vsi[vsi_idx] && pf->vsi[vsi_idx]->seid == vsi_seid)
14798 			break;
14799 	if (vsi_idx == pf->num_alloc_vsi && vsi_seid != 0) {
14800 		dev_info(&pf->pdev->dev, "vsi seid %d not found\n",
14801 			 vsi_seid);
14802 		return NULL;
14803 	}
14804 
14805 	if (uplink_seid && uplink_seid != pf->mac_seid) {
14806 		for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
14807 			if (pf->veb[veb_idx] &&
14808 			    pf->veb[veb_idx]->seid == uplink_seid) {
14809 				uplink_veb = pf->veb[veb_idx];
14810 				break;
14811 			}
14812 		}
14813 		if (!uplink_veb) {
14814 			dev_info(&pf->pdev->dev,
14815 				 "uplink seid %d not found\n", uplink_seid);
14816 			return NULL;
14817 		}
14818 	}
14819 
14820 	/* get veb sw struct */
14821 	veb_idx = i40e_veb_mem_alloc(pf);
14822 	if (veb_idx < 0)
14823 		goto err_alloc;
14824 	veb = pf->veb[veb_idx];
14825 	veb->flags = flags;
14826 	veb->uplink_seid = uplink_seid;
14827 	veb->veb_idx = (uplink_veb ? uplink_veb->idx : I40E_NO_VEB);
14828 	veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14829 
14830 	/* create the VEB in the switch */
14831 	ret = i40e_add_veb(veb, pf->vsi[vsi_idx]);
14832 	if (ret)
14833 		goto err_veb;
14834 	if (vsi_idx == pf->lan_vsi)
14835 		pf->lan_veb = veb->idx;
14836 
14837 	return veb;
14838 
14839 err_veb:
14840 	i40e_veb_clear(veb);
14841 err_alloc:
14842 	return NULL;
14843 }
14844 
14845 /**
14846  * i40e_setup_pf_switch_element - set PF vars based on switch type
14847  * @pf: board private structure
14848  * @ele: element we are building info from
14849  * @num_reported: total number of elements
14850  * @printconfig: should we print the contents
14851  *
14852  * helper function to assist in extracting a few useful SEID values.
14853  **/
14854 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14855 				struct i40e_aqc_switch_config_element_resp *ele,
14856 				u16 num_reported, bool printconfig)
14857 {
14858 	u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14859 	u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14860 	u8 element_type = ele->element_type;
14861 	u16 seid = le16_to_cpu(ele->seid);
14862 
14863 	if (printconfig)
14864 		dev_info(&pf->pdev->dev,
14865 			 "type=%d seid=%d uplink=%d downlink=%d\n",
14866 			 element_type, seid, uplink_seid, downlink_seid);
14867 
14868 	switch (element_type) {
14869 	case I40E_SWITCH_ELEMENT_TYPE_MAC:
14870 		pf->mac_seid = seid;
14871 		break;
14872 	case I40E_SWITCH_ELEMENT_TYPE_VEB:
14873 		/* Main VEB? */
14874 		if (uplink_seid != pf->mac_seid)
14875 			break;
14876 		if (pf->lan_veb >= I40E_MAX_VEB) {
14877 			int v;
14878 
14879 			/* find existing or else empty VEB */
14880 			for (v = 0; v < I40E_MAX_VEB; v++) {
14881 				if (pf->veb[v] && (pf->veb[v]->seid == seid)) {
14882 					pf->lan_veb = v;
14883 					break;
14884 				}
14885 			}
14886 			if (pf->lan_veb >= I40E_MAX_VEB) {
14887 				v = i40e_veb_mem_alloc(pf);
14888 				if (v < 0)
14889 					break;
14890 				pf->lan_veb = v;
14891 			}
14892 		}
14893 		if (pf->lan_veb >= I40E_MAX_VEB)
14894 			break;
14895 
14896 		pf->veb[pf->lan_veb]->seid = seid;
14897 		pf->veb[pf->lan_veb]->uplink_seid = pf->mac_seid;
14898 		pf->veb[pf->lan_veb]->pf = pf;
14899 		pf->veb[pf->lan_veb]->veb_idx = I40E_NO_VEB;
14900 		break;
14901 	case I40E_SWITCH_ELEMENT_TYPE_VSI:
14902 		if (num_reported != 1)
14903 			break;
14904 		/* This is immediately after a reset so we can assume this is
14905 		 * the PF's VSI
14906 		 */
14907 		pf->mac_seid = uplink_seid;
14908 		pf->pf_seid = downlink_seid;
14909 		pf->main_vsi_seid = seid;
14910 		if (printconfig)
14911 			dev_info(&pf->pdev->dev,
14912 				 "pf_seid=%d main_vsi_seid=%d\n",
14913 				 pf->pf_seid, pf->main_vsi_seid);
14914 		break;
14915 	case I40E_SWITCH_ELEMENT_TYPE_PF:
14916 	case I40E_SWITCH_ELEMENT_TYPE_VF:
14917 	case I40E_SWITCH_ELEMENT_TYPE_EMP:
14918 	case I40E_SWITCH_ELEMENT_TYPE_BMC:
14919 	case I40E_SWITCH_ELEMENT_TYPE_PE:
14920 	case I40E_SWITCH_ELEMENT_TYPE_PA:
14921 		/* ignore these for now */
14922 		break;
14923 	default:
14924 		dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
14925 			 element_type, seid);
14926 		break;
14927 	}
14928 }
14929 
14930 /**
14931  * i40e_fetch_switch_configuration - Get switch config from firmware
14932  * @pf: board private structure
14933  * @printconfig: should we print the contents
14934  *
14935  * Get the current switch configuration from the device and
14936  * extract a few useful SEID values.
14937  **/
14938 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
14939 {
14940 	struct i40e_aqc_get_switch_config_resp *sw_config;
14941 	u16 next_seid = 0;
14942 	int ret = 0;
14943 	u8 *aq_buf;
14944 	int i;
14945 
14946 	aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
14947 	if (!aq_buf)
14948 		return -ENOMEM;
14949 
14950 	sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
14951 	do {
14952 		u16 num_reported, num_total;
14953 
14954 		ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
14955 						I40E_AQ_LARGE_BUF,
14956 						&next_seid, NULL);
14957 		if (ret) {
14958 			dev_info(&pf->pdev->dev,
14959 				 "get switch config failed err %s aq_err %s\n",
14960 				 i40e_stat_str(&pf->hw, ret),
14961 				 i40e_aq_str(&pf->hw,
14962 					     pf->hw.aq.asq_last_status));
14963 			kfree(aq_buf);
14964 			return -ENOENT;
14965 		}
14966 
14967 		num_reported = le16_to_cpu(sw_config->header.num_reported);
14968 		num_total = le16_to_cpu(sw_config->header.num_total);
14969 
14970 		if (printconfig)
14971 			dev_info(&pf->pdev->dev,
14972 				 "header: %d reported %d total\n",
14973 				 num_reported, num_total);
14974 
14975 		for (i = 0; i < num_reported; i++) {
14976 			struct i40e_aqc_switch_config_element_resp *ele =
14977 				&sw_config->element[i];
14978 
14979 			i40e_setup_pf_switch_element(pf, ele, num_reported,
14980 						     printconfig);
14981 		}
14982 	} while (next_seid != 0);
14983 
14984 	kfree(aq_buf);
14985 	return ret;
14986 }
14987 
14988 /**
14989  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
14990  * @pf: board private structure
14991  * @reinit: if the Main VSI needs to re-initialized.
14992  * @lock_acquired: indicates whether or not the lock has been acquired
14993  *
14994  * Returns 0 on success, negative value on failure
14995  **/
14996 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired)
14997 {
14998 	u16 flags = 0;
14999 	int ret;
15000 
15001 	/* find out what's out there already */
15002 	ret = i40e_fetch_switch_configuration(pf, false);
15003 	if (ret) {
15004 		dev_info(&pf->pdev->dev,
15005 			 "couldn't fetch switch config, err %s aq_err %s\n",
15006 			 i40e_stat_str(&pf->hw, ret),
15007 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15008 		return ret;
15009 	}
15010 	i40e_pf_reset_stats(pf);
15011 
15012 	/* set the switch config bit for the whole device to
15013 	 * support limited promisc or true promisc
15014 	 * when user requests promisc. The default is limited
15015 	 * promisc.
15016 	*/
15017 
15018 	if ((pf->hw.pf_id == 0) &&
15019 	    !(pf->flags & I40E_FLAG_TRUE_PROMISC_SUPPORT)) {
15020 		flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15021 		pf->last_sw_conf_flags = flags;
15022 	}
15023 
15024 	if (pf->hw.pf_id == 0) {
15025 		u16 valid_flags;
15026 
15027 		valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15028 		ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
15029 						NULL);
15030 		if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
15031 			dev_info(&pf->pdev->dev,
15032 				 "couldn't set switch config bits, err %s aq_err %s\n",
15033 				 i40e_stat_str(&pf->hw, ret),
15034 				 i40e_aq_str(&pf->hw,
15035 					     pf->hw.aq.asq_last_status));
15036 			/* not a fatal problem, just keep going */
15037 		}
15038 		pf->last_sw_conf_valid_flags = valid_flags;
15039 	}
15040 
15041 	/* first time setup */
15042 	if (pf->lan_vsi == I40E_NO_VSI || reinit) {
15043 		struct i40e_vsi *vsi = NULL;
15044 		u16 uplink_seid;
15045 
15046 		/* Set up the PF VSI associated with the PF's main VSI
15047 		 * that is already in the HW switch
15048 		 */
15049 		if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
15050 			uplink_seid = pf->veb[pf->lan_veb]->seid;
15051 		else
15052 			uplink_seid = pf->mac_seid;
15053 		if (pf->lan_vsi == I40E_NO_VSI)
15054 			vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN, uplink_seid, 0);
15055 		else if (reinit)
15056 			vsi = i40e_vsi_reinit_setup(pf->vsi[pf->lan_vsi]);
15057 		if (!vsi) {
15058 			dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
15059 			i40e_cloud_filter_exit(pf);
15060 			i40e_fdir_teardown(pf);
15061 			return -EAGAIN;
15062 		}
15063 	} else {
15064 		/* force a reset of TC and queue layout configurations */
15065 		u8 enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
15066 
15067 		pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
15068 		pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
15069 		i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
15070 	}
15071 	i40e_vlan_stripping_disable(pf->vsi[pf->lan_vsi]);
15072 
15073 	i40e_fdir_sb_setup(pf);
15074 
15075 	/* Setup static PF queue filter control settings */
15076 	ret = i40e_setup_pf_filter_control(pf);
15077 	if (ret) {
15078 		dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
15079 			 ret);
15080 		/* Failure here should not stop continuing other steps */
15081 	}
15082 
15083 	/* enable RSS in the HW, even for only one queue, as the stack can use
15084 	 * the hash
15085 	 */
15086 	if ((pf->flags & I40E_FLAG_RSS_ENABLED))
15087 		i40e_pf_config_rss(pf);
15088 
15089 	/* fill in link information and enable LSE reporting */
15090 	i40e_link_event(pf);
15091 
15092 	/* Initialize user-specific link properties */
15093 	pf->fc_autoneg_status = ((pf->hw.phy.link_info.an_info &
15094 				  I40E_AQ_AN_COMPLETED) ? true : false);
15095 
15096 	i40e_ptp_init(pf);
15097 
15098 	if (!lock_acquired)
15099 		rtnl_lock();
15100 
15101 	/* repopulate tunnel port filters */
15102 	udp_tunnel_nic_reset_ntf(pf->vsi[pf->lan_vsi]->netdev);
15103 
15104 	if (!lock_acquired)
15105 		rtnl_unlock();
15106 
15107 	return ret;
15108 }
15109 
15110 /**
15111  * i40e_determine_queue_usage - Work out queue distribution
15112  * @pf: board private structure
15113  **/
15114 static void i40e_determine_queue_usage(struct i40e_pf *pf)
15115 {
15116 	int queues_left;
15117 	int q_max;
15118 
15119 	pf->num_lan_qps = 0;
15120 
15121 	/* Find the max queues to be put into basic use.  We'll always be
15122 	 * using TC0, whether or not DCB is running, and TC0 will get the
15123 	 * big RSS set.
15124 	 */
15125 	queues_left = pf->hw.func_caps.num_tx_qp;
15126 
15127 	if ((queues_left == 1) ||
15128 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED)) {
15129 		/* one qp for PF, no queues for anything else */
15130 		queues_left = 0;
15131 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15132 
15133 		/* make sure all the fancies are disabled */
15134 		pf->flags &= ~(I40E_FLAG_RSS_ENABLED	|
15135 			       I40E_FLAG_IWARP_ENABLED	|
15136 			       I40E_FLAG_FD_SB_ENABLED	|
15137 			       I40E_FLAG_FD_ATR_ENABLED	|
15138 			       I40E_FLAG_DCB_CAPABLE	|
15139 			       I40E_FLAG_DCB_ENABLED	|
15140 			       I40E_FLAG_SRIOV_ENABLED	|
15141 			       I40E_FLAG_VMDQ_ENABLED);
15142 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15143 	} else if (!(pf->flags & (I40E_FLAG_RSS_ENABLED |
15144 				  I40E_FLAG_FD_SB_ENABLED |
15145 				  I40E_FLAG_FD_ATR_ENABLED |
15146 				  I40E_FLAG_DCB_CAPABLE))) {
15147 		/* one qp for PF */
15148 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15149 		queues_left -= pf->num_lan_qps;
15150 
15151 		pf->flags &= ~(I40E_FLAG_RSS_ENABLED	|
15152 			       I40E_FLAG_IWARP_ENABLED	|
15153 			       I40E_FLAG_FD_SB_ENABLED	|
15154 			       I40E_FLAG_FD_ATR_ENABLED	|
15155 			       I40E_FLAG_DCB_ENABLED	|
15156 			       I40E_FLAG_VMDQ_ENABLED);
15157 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15158 	} else {
15159 		/* Not enough queues for all TCs */
15160 		if ((pf->flags & I40E_FLAG_DCB_CAPABLE) &&
15161 		    (queues_left < I40E_MAX_TRAFFIC_CLASS)) {
15162 			pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
15163 					I40E_FLAG_DCB_ENABLED);
15164 			dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
15165 		}
15166 
15167 		/* limit lan qps to the smaller of qps, cpus or msix */
15168 		q_max = max_t(int, pf->rss_size_max, num_online_cpus());
15169 		q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
15170 		q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
15171 		pf->num_lan_qps = q_max;
15172 
15173 		queues_left -= pf->num_lan_qps;
15174 	}
15175 
15176 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15177 		if (queues_left > 1) {
15178 			queues_left -= 1; /* save 1 queue for FD */
15179 		} else {
15180 			pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
15181 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15182 			dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
15183 		}
15184 	}
15185 
15186 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15187 	    pf->num_vf_qps && pf->num_req_vfs && queues_left) {
15188 		pf->num_req_vfs = min_t(int, pf->num_req_vfs,
15189 					(queues_left / pf->num_vf_qps));
15190 		queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
15191 	}
15192 
15193 	if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
15194 	    pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
15195 		pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
15196 					  (queues_left / pf->num_vmdq_qps));
15197 		queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
15198 	}
15199 
15200 	pf->queues_left = queues_left;
15201 	dev_dbg(&pf->pdev->dev,
15202 		"qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
15203 		pf->hw.func_caps.num_tx_qp,
15204 		!!(pf->flags & I40E_FLAG_FD_SB_ENABLED),
15205 		pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
15206 		pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
15207 		queues_left);
15208 }
15209 
15210 /**
15211  * i40e_setup_pf_filter_control - Setup PF static filter control
15212  * @pf: PF to be setup
15213  *
15214  * i40e_setup_pf_filter_control sets up a PF's initial filter control
15215  * settings. If PE/FCoE are enabled then it will also set the per PF
15216  * based filter sizes required for them. It also enables Flow director,
15217  * ethertype and macvlan type filter settings for the pf.
15218  *
15219  * Returns 0 on success, negative on failure
15220  **/
15221 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
15222 {
15223 	struct i40e_filter_control_settings *settings = &pf->filter_settings;
15224 
15225 	settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
15226 
15227 	/* Flow Director is enabled */
15228 	if (pf->flags & (I40E_FLAG_FD_SB_ENABLED | I40E_FLAG_FD_ATR_ENABLED))
15229 		settings->enable_fdir = true;
15230 
15231 	/* Ethtype and MACVLAN filters enabled for PF */
15232 	settings->enable_ethtype = true;
15233 	settings->enable_macvlan = true;
15234 
15235 	if (i40e_set_filter_control(&pf->hw, settings))
15236 		return -ENOENT;
15237 
15238 	return 0;
15239 }
15240 
15241 #define INFO_STRING_LEN 255
15242 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
15243 static void i40e_print_features(struct i40e_pf *pf)
15244 {
15245 	struct i40e_hw *hw = &pf->hw;
15246 	char *buf;
15247 	int i;
15248 
15249 	buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
15250 	if (!buf)
15251 		return;
15252 
15253 	i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
15254 #ifdef CONFIG_PCI_IOV
15255 	i += scnprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
15256 #endif
15257 	i += scnprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
15258 		      pf->hw.func_caps.num_vsis,
15259 		      pf->vsi[pf->lan_vsi]->num_queue_pairs);
15260 	if (pf->flags & I40E_FLAG_RSS_ENABLED)
15261 		i += scnprintf(&buf[i], REMAIN(i), " RSS");
15262 	if (pf->flags & I40E_FLAG_FD_ATR_ENABLED)
15263 		i += scnprintf(&buf[i], REMAIN(i), " FD_ATR");
15264 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15265 		i += scnprintf(&buf[i], REMAIN(i), " FD_SB");
15266 		i += scnprintf(&buf[i], REMAIN(i), " NTUPLE");
15267 	}
15268 	if (pf->flags & I40E_FLAG_DCB_CAPABLE)
15269 		i += scnprintf(&buf[i], REMAIN(i), " DCB");
15270 	i += scnprintf(&buf[i], REMAIN(i), " VxLAN");
15271 	i += scnprintf(&buf[i], REMAIN(i), " Geneve");
15272 	if (pf->flags & I40E_FLAG_PTP)
15273 		i += scnprintf(&buf[i], REMAIN(i), " PTP");
15274 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
15275 		i += scnprintf(&buf[i], REMAIN(i), " VEB");
15276 	else
15277 		i += scnprintf(&buf[i], REMAIN(i), " VEPA");
15278 
15279 	dev_info(&pf->pdev->dev, "%s\n", buf);
15280 	kfree(buf);
15281 	WARN_ON(i > INFO_STRING_LEN);
15282 }
15283 
15284 /**
15285  * i40e_get_platform_mac_addr - get platform-specific MAC address
15286  * @pdev: PCI device information struct
15287  * @pf: board private structure
15288  *
15289  * Look up the MAC address for the device. First we'll try
15290  * eth_platform_get_mac_address, which will check Open Firmware, or arch
15291  * specific fallback. Otherwise, we'll default to the stored value in
15292  * firmware.
15293  **/
15294 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
15295 {
15296 	if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
15297 		i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
15298 }
15299 
15300 /**
15301  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
15302  * @fec_cfg: FEC option to set in flags
15303  * @flags: ptr to flags in which we set FEC option
15304  **/
15305 void i40e_set_fec_in_flags(u8 fec_cfg, u32 *flags)
15306 {
15307 	if (fec_cfg & I40E_AQ_SET_FEC_AUTO)
15308 		*flags |= I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC;
15309 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
15310 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
15311 		*flags |= I40E_FLAG_RS_FEC;
15312 		*flags &= ~I40E_FLAG_BASE_R_FEC;
15313 	}
15314 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
15315 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
15316 		*flags |= I40E_FLAG_BASE_R_FEC;
15317 		*flags &= ~I40E_FLAG_RS_FEC;
15318 	}
15319 	if (fec_cfg == 0)
15320 		*flags &= ~(I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC);
15321 }
15322 
15323 /**
15324  * i40e_check_recovery_mode - check if we are running transition firmware
15325  * @pf: board private structure
15326  *
15327  * Check registers indicating the firmware runs in recovery mode. Sets the
15328  * appropriate driver state.
15329  *
15330  * Returns true if the recovery mode was detected, false otherwise
15331  **/
15332 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
15333 {
15334 	u32 val = rd32(&pf->hw, I40E_GL_FWSTS);
15335 
15336 	if (val & I40E_GL_FWSTS_FWS1B_MASK) {
15337 		dev_crit(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
15338 		dev_crit(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
15339 		set_bit(__I40E_RECOVERY_MODE, pf->state);
15340 
15341 		return true;
15342 	}
15343 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15344 		dev_info(&pf->pdev->dev, "Please do Power-On Reset to initialize adapter in normal mode with full functionality.\n");
15345 
15346 	return false;
15347 }
15348 
15349 /**
15350  * i40e_pf_loop_reset - perform reset in a loop.
15351  * @pf: board private structure
15352  *
15353  * This function is useful when a NIC is about to enter recovery mode.
15354  * When a NIC's internal data structures are corrupted the NIC's
15355  * firmware is going to enter recovery mode.
15356  * Right after a POR it takes about 7 minutes for firmware to enter
15357  * recovery mode. Until that time a NIC is in some kind of intermediate
15358  * state. After that time period the NIC almost surely enters
15359  * recovery mode. The only way for a driver to detect intermediate
15360  * state is to issue a series of pf-resets and check a return value.
15361  * If a PF reset returns success then the firmware could be in recovery
15362  * mode so the caller of this code needs to check for recovery mode
15363  * if this function returns success. There is a little chance that
15364  * firmware will hang in intermediate state forever.
15365  * Since waiting 7 minutes is quite a lot of time this function waits
15366  * 10 seconds and then gives up by returning an error.
15367  *
15368  * Return 0 on success, negative on failure.
15369  **/
15370 static i40e_status i40e_pf_loop_reset(struct i40e_pf *pf)
15371 {
15372 	/* wait max 10 seconds for PF reset to succeed */
15373 	const unsigned long time_end = jiffies + 10 * HZ;
15374 
15375 	struct i40e_hw *hw = &pf->hw;
15376 	i40e_status ret;
15377 
15378 	ret = i40e_pf_reset(hw);
15379 	while (ret != I40E_SUCCESS && time_before(jiffies, time_end)) {
15380 		usleep_range(10000, 20000);
15381 		ret = i40e_pf_reset(hw);
15382 	}
15383 
15384 	if (ret == I40E_SUCCESS)
15385 		pf->pfr_count++;
15386 	else
15387 		dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
15388 
15389 	return ret;
15390 }
15391 
15392 /**
15393  * i40e_check_fw_empr - check if FW issued unexpected EMP Reset
15394  * @pf: board private structure
15395  *
15396  * Check FW registers to determine if FW issued unexpected EMP Reset.
15397  * Every time when unexpected EMP Reset occurs the FW increments
15398  * a counter of unexpected EMP Resets. When the counter reaches 10
15399  * the FW should enter the Recovery mode
15400  *
15401  * Returns true if FW issued unexpected EMP Reset
15402  **/
15403 static bool i40e_check_fw_empr(struct i40e_pf *pf)
15404 {
15405 	const u32 fw_sts = rd32(&pf->hw, I40E_GL_FWSTS) &
15406 			   I40E_GL_FWSTS_FWS1B_MASK;
15407 	return (fw_sts > I40E_GL_FWSTS_FWS1B_EMPR_0) &&
15408 	       (fw_sts <= I40E_GL_FWSTS_FWS1B_EMPR_10);
15409 }
15410 
15411 /**
15412  * i40e_handle_resets - handle EMP resets and PF resets
15413  * @pf: board private structure
15414  *
15415  * Handle both EMP resets and PF resets and conclude whether there are
15416  * any issues regarding these resets. If there are any issues then
15417  * generate log entry.
15418  *
15419  * Return 0 if NIC is healthy or negative value when there are issues
15420  * with resets
15421  **/
15422 static i40e_status i40e_handle_resets(struct i40e_pf *pf)
15423 {
15424 	const i40e_status pfr = i40e_pf_loop_reset(pf);
15425 	const bool is_empr = i40e_check_fw_empr(pf);
15426 
15427 	if (is_empr || pfr != I40E_SUCCESS)
15428 		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");
15429 
15430 	return is_empr ? I40E_ERR_RESET_FAILED : pfr;
15431 }
15432 
15433 /**
15434  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
15435  * @pf: board private structure
15436  * @hw: ptr to the hardware info
15437  *
15438  * This function does a minimal setup of all subsystems needed for running
15439  * recovery mode.
15440  *
15441  * Returns 0 on success, negative on failure
15442  **/
15443 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
15444 {
15445 	struct i40e_vsi *vsi;
15446 	int err;
15447 	int v_idx;
15448 
15449 	pci_save_state(pf->pdev);
15450 
15451 	/* set up periodic task facility */
15452 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15453 	pf->service_timer_period = HZ;
15454 
15455 	INIT_WORK(&pf->service_task, i40e_service_task);
15456 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15457 
15458 	err = i40e_init_interrupt_scheme(pf);
15459 	if (err)
15460 		goto err_switch_setup;
15461 
15462 	/* The number of VSIs reported by the FW is the minimum guaranteed
15463 	 * to us; HW supports far more and we share the remaining pool with
15464 	 * the other PFs. We allocate space for more than the guarantee with
15465 	 * the understanding that we might not get them all later.
15466 	 */
15467 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15468 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15469 	else
15470 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15471 
15472 	/* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
15473 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15474 			  GFP_KERNEL);
15475 	if (!pf->vsi) {
15476 		err = -ENOMEM;
15477 		goto err_switch_setup;
15478 	}
15479 
15480 	/* We allocate one VSI which is needed as absolute minimum
15481 	 * in order to register the netdev
15482 	 */
15483 	v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
15484 	if (v_idx < 0) {
15485 		err = v_idx;
15486 		goto err_switch_setup;
15487 	}
15488 	pf->lan_vsi = v_idx;
15489 	vsi = pf->vsi[v_idx];
15490 	if (!vsi) {
15491 		err = -EFAULT;
15492 		goto err_switch_setup;
15493 	}
15494 	vsi->alloc_queue_pairs = 1;
15495 	err = i40e_config_netdev(vsi);
15496 	if (err)
15497 		goto err_switch_setup;
15498 	err = register_netdev(vsi->netdev);
15499 	if (err)
15500 		goto err_switch_setup;
15501 	vsi->netdev_registered = true;
15502 	i40e_dbg_pf_init(pf);
15503 
15504 	err = i40e_setup_misc_vector_for_recovery_mode(pf);
15505 	if (err)
15506 		goto err_switch_setup;
15507 
15508 	/* tell the firmware that we're starting */
15509 	i40e_send_version(pf);
15510 
15511 	/* since everything's happy, start the service_task timer */
15512 	mod_timer(&pf->service_timer,
15513 		  round_jiffies(jiffies + pf->service_timer_period));
15514 
15515 	return 0;
15516 
15517 err_switch_setup:
15518 	i40e_reset_interrupt_capability(pf);
15519 	del_timer_sync(&pf->service_timer);
15520 	i40e_shutdown_adminq(hw);
15521 	iounmap(hw->hw_addr);
15522 	pci_disable_pcie_error_reporting(pf->pdev);
15523 	pci_release_mem_regions(pf->pdev);
15524 	pci_disable_device(pf->pdev);
15525 	kfree(pf);
15526 
15527 	return err;
15528 }
15529 
15530 /**
15531  * i40e_set_subsystem_device_id - set subsystem device id
15532  * @hw: pointer to the hardware info
15533  *
15534  * Set PCI subsystem device id either from a pci_dev structure or
15535  * a specific FW register.
15536  **/
15537 static inline void i40e_set_subsystem_device_id(struct i40e_hw *hw)
15538 {
15539 	struct pci_dev *pdev = ((struct i40e_pf *)hw->back)->pdev;
15540 
15541 	hw->subsystem_device_id = pdev->subsystem_device ?
15542 		pdev->subsystem_device :
15543 		(ushort)(rd32(hw, I40E_PFPCI_SUBSYSID) & USHRT_MAX);
15544 }
15545 
15546 /**
15547  * i40e_probe - Device initialization routine
15548  * @pdev: PCI device information struct
15549  * @ent: entry in i40e_pci_tbl
15550  *
15551  * i40e_probe initializes a PF identified by a pci_dev structure.
15552  * The OS initialization, configuring of the PF private structure,
15553  * and a hardware reset occur.
15554  *
15555  * Returns 0 on success, negative on failure
15556  **/
15557 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
15558 {
15559 	struct i40e_aq_get_phy_abilities_resp abilities;
15560 #ifdef CONFIG_I40E_DCB
15561 	enum i40e_get_fw_lldp_status_resp lldp_status;
15562 	i40e_status status;
15563 #endif /* CONFIG_I40E_DCB */
15564 	struct i40e_pf *pf;
15565 	struct i40e_hw *hw;
15566 	static u16 pfs_found;
15567 	u16 wol_nvm_bits;
15568 	u16 link_status;
15569 	int err;
15570 	u32 val;
15571 	u32 i;
15572 
15573 	err = pci_enable_device_mem(pdev);
15574 	if (err)
15575 		return err;
15576 
15577 	/* set up for high or low dma */
15578 	err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
15579 	if (err) {
15580 		dev_err(&pdev->dev,
15581 			"DMA configuration failed: 0x%x\n", err);
15582 		goto err_dma;
15583 	}
15584 
15585 	/* set up pci connections */
15586 	err = pci_request_mem_regions(pdev, i40e_driver_name);
15587 	if (err) {
15588 		dev_info(&pdev->dev,
15589 			 "pci_request_selected_regions failed %d\n", err);
15590 		goto err_pci_reg;
15591 	}
15592 
15593 	pci_enable_pcie_error_reporting(pdev);
15594 	pci_set_master(pdev);
15595 
15596 	/* Now that we have a PCI connection, we need to do the
15597 	 * low level device setup.  This is primarily setting up
15598 	 * the Admin Queue structures and then querying for the
15599 	 * device's current profile information.
15600 	 */
15601 	pf = kzalloc(sizeof(*pf), GFP_KERNEL);
15602 	if (!pf) {
15603 		err = -ENOMEM;
15604 		goto err_pf_alloc;
15605 	}
15606 	pf->next_vsi = 0;
15607 	pf->pdev = pdev;
15608 	set_bit(__I40E_DOWN, pf->state);
15609 
15610 	hw = &pf->hw;
15611 	hw->back = pf;
15612 
15613 	pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
15614 				I40E_MAX_CSR_SPACE);
15615 	/* We believe that the highest register to read is
15616 	 * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
15617 	 * is not less than that before mapping to prevent a
15618 	 * kernel panic.
15619 	 */
15620 	if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
15621 		dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
15622 			pf->ioremap_len);
15623 		err = -ENOMEM;
15624 		goto err_ioremap;
15625 	}
15626 	hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
15627 	if (!hw->hw_addr) {
15628 		err = -EIO;
15629 		dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
15630 			 (unsigned int)pci_resource_start(pdev, 0),
15631 			 pf->ioremap_len, err);
15632 		goto err_ioremap;
15633 	}
15634 	hw->vendor_id = pdev->vendor;
15635 	hw->device_id = pdev->device;
15636 	pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
15637 	hw->subsystem_vendor_id = pdev->subsystem_vendor;
15638 	i40e_set_subsystem_device_id(hw);
15639 	hw->bus.device = PCI_SLOT(pdev->devfn);
15640 	hw->bus.func = PCI_FUNC(pdev->devfn);
15641 	hw->bus.bus_id = pdev->bus->number;
15642 	pf->instance = pfs_found;
15643 
15644 	/* Select something other than the 802.1ad ethertype for the
15645 	 * switch to use internally and drop on ingress.
15646 	 */
15647 	hw->switch_tag = 0xffff;
15648 	hw->first_tag = ETH_P_8021AD;
15649 	hw->second_tag = ETH_P_8021Q;
15650 
15651 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
15652 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
15653 	INIT_LIST_HEAD(&pf->ddp_old_prof);
15654 
15655 	/* set up the locks for the AQ, do this only once in probe
15656 	 * and destroy them only once in remove
15657 	 */
15658 	mutex_init(&hw->aq.asq_mutex);
15659 	mutex_init(&hw->aq.arq_mutex);
15660 
15661 	pf->msg_enable = netif_msg_init(debug,
15662 					NETIF_MSG_DRV |
15663 					NETIF_MSG_PROBE |
15664 					NETIF_MSG_LINK);
15665 	if (debug < -1)
15666 		pf->hw.debug_mask = debug;
15667 
15668 	/* do a special CORER for clearing PXE mode once at init */
15669 	if (hw->revision_id == 0 &&
15670 	    (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
15671 		wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
15672 		i40e_flush(hw);
15673 		msleep(200);
15674 		pf->corer_count++;
15675 
15676 		i40e_clear_pxe_mode(hw);
15677 	}
15678 
15679 	/* Reset here to make sure all is clean and to define PF 'n' */
15680 	i40e_clear_hw(hw);
15681 
15682 	err = i40e_set_mac_type(hw);
15683 	if (err) {
15684 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15685 			 err);
15686 		goto err_pf_reset;
15687 	}
15688 
15689 	err = i40e_handle_resets(pf);
15690 	if (err)
15691 		goto err_pf_reset;
15692 
15693 	i40e_check_recovery_mode(pf);
15694 
15695 	if (is_kdump_kernel()) {
15696 		hw->aq.num_arq_entries = I40E_MIN_ARQ_LEN;
15697 		hw->aq.num_asq_entries = I40E_MIN_ASQ_LEN;
15698 	} else {
15699 		hw->aq.num_arq_entries = I40E_AQ_LEN;
15700 		hw->aq.num_asq_entries = I40E_AQ_LEN;
15701 	}
15702 	hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15703 	hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15704 	pf->adminq_work_limit = I40E_AQ_WORK_LIMIT;
15705 
15706 	snprintf(pf->int_name, sizeof(pf->int_name) - 1,
15707 		 "%s-%s:misc",
15708 		 dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
15709 
15710 	err = i40e_init_shared_code(hw);
15711 	if (err) {
15712 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15713 			 err);
15714 		goto err_pf_reset;
15715 	}
15716 
15717 	/* set up a default setting for link flow control */
15718 	pf->hw.fc.requested_mode = I40E_FC_NONE;
15719 
15720 	err = i40e_init_adminq(hw);
15721 	if (err) {
15722 		if (err == I40E_ERR_FIRMWARE_API_VERSION)
15723 			dev_info(&pdev->dev,
15724 				 "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",
15725 				 hw->aq.api_maj_ver,
15726 				 hw->aq.api_min_ver,
15727 				 I40E_FW_API_VERSION_MAJOR,
15728 				 I40E_FW_MINOR_VERSION(hw));
15729 		else
15730 			dev_info(&pdev->dev,
15731 				 "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
15732 
15733 		goto err_pf_reset;
15734 	}
15735 	i40e_get_oem_version(hw);
15736 
15737 	/* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
15738 	dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
15739 		 hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
15740 		 hw->aq.api_maj_ver, hw->aq.api_min_ver,
15741 		 i40e_nvm_version_str(hw), hw->vendor_id, hw->device_id,
15742 		 hw->subsystem_vendor_id, hw->subsystem_device_id);
15743 
15744 	if (hw->aq.api_maj_ver == I40E_FW_API_VERSION_MAJOR &&
15745 	    hw->aq.api_min_ver > I40E_FW_MINOR_VERSION(hw))
15746 		dev_dbg(&pdev->dev,
15747 			"The driver for the device detected a newer version of the NVM image v%u.%u than v%u.%u.\n",
15748 			 hw->aq.api_maj_ver,
15749 			 hw->aq.api_min_ver,
15750 			 I40E_FW_API_VERSION_MAJOR,
15751 			 I40E_FW_MINOR_VERSION(hw));
15752 	else if (hw->aq.api_maj_ver == 1 && hw->aq.api_min_ver < 4)
15753 		dev_info(&pdev->dev,
15754 			 "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",
15755 			 hw->aq.api_maj_ver,
15756 			 hw->aq.api_min_ver,
15757 			 I40E_FW_API_VERSION_MAJOR,
15758 			 I40E_FW_MINOR_VERSION(hw));
15759 
15760 	i40e_verify_eeprom(pf);
15761 
15762 	/* Rev 0 hardware was never productized */
15763 	if (hw->revision_id < 1)
15764 		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");
15765 
15766 	i40e_clear_pxe_mode(hw);
15767 
15768 	err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
15769 	if (err)
15770 		goto err_adminq_setup;
15771 
15772 	err = i40e_sw_init(pf);
15773 	if (err) {
15774 		dev_info(&pdev->dev, "sw_init failed: %d\n", err);
15775 		goto err_sw_init;
15776 	}
15777 
15778 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15779 		return i40e_init_recovery_mode(pf, hw);
15780 
15781 	err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
15782 				hw->func_caps.num_rx_qp, 0, 0);
15783 	if (err) {
15784 		dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
15785 		goto err_init_lan_hmc;
15786 	}
15787 
15788 	err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
15789 	if (err) {
15790 		dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
15791 		err = -ENOENT;
15792 		goto err_configure_lan_hmc;
15793 	}
15794 
15795 	/* Disable LLDP for NICs that have firmware versions lower than v4.3.
15796 	 * Ignore error return codes because if it was already disabled via
15797 	 * hardware settings this will fail
15798 	 */
15799 	if (pf->hw_features & I40E_HW_STOP_FW_LLDP) {
15800 		dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
15801 		i40e_aq_stop_lldp(hw, true, false, NULL);
15802 	}
15803 
15804 	/* allow a platform config to override the HW addr */
15805 	i40e_get_platform_mac_addr(pdev, pf);
15806 
15807 	if (!is_valid_ether_addr(hw->mac.addr)) {
15808 		dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
15809 		err = -EIO;
15810 		goto err_mac_addr;
15811 	}
15812 	dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
15813 	ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
15814 	i40e_get_port_mac_addr(hw, hw->mac.port_addr);
15815 	if (is_valid_ether_addr(hw->mac.port_addr))
15816 		pf->hw_features |= I40E_HW_PORT_ID_VALID;
15817 
15818 	i40e_ptp_alloc_pins(pf);
15819 	pci_set_drvdata(pdev, pf);
15820 	pci_save_state(pdev);
15821 
15822 #ifdef CONFIG_I40E_DCB
15823 	status = i40e_get_fw_lldp_status(&pf->hw, &lldp_status);
15824 	(!status &&
15825 	 lldp_status == I40E_GET_FW_LLDP_STATUS_ENABLED) ?
15826 		(pf->flags &= ~I40E_FLAG_DISABLE_FW_LLDP) :
15827 		(pf->flags |= I40E_FLAG_DISABLE_FW_LLDP);
15828 	dev_info(&pdev->dev,
15829 		 (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) ?
15830 			"FW LLDP is disabled\n" :
15831 			"FW LLDP is enabled\n");
15832 
15833 	/* Enable FW to write default DCB config on link-up */
15834 	i40e_aq_set_dcb_parameters(hw, true, NULL);
15835 
15836 	err = i40e_init_pf_dcb(pf);
15837 	if (err) {
15838 		dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
15839 		pf->flags &= ~(I40E_FLAG_DCB_CAPABLE | I40E_FLAG_DCB_ENABLED);
15840 		/* Continue without DCB enabled */
15841 	}
15842 #endif /* CONFIG_I40E_DCB */
15843 
15844 	/* set up periodic task facility */
15845 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15846 	pf->service_timer_period = HZ;
15847 
15848 	INIT_WORK(&pf->service_task, i40e_service_task);
15849 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15850 
15851 	/* NVM bit on means WoL disabled for the port */
15852 	i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15853 	if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15854 		pf->wol_en = false;
15855 	else
15856 		pf->wol_en = true;
15857 	device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15858 
15859 	/* set up the main switch operations */
15860 	i40e_determine_queue_usage(pf);
15861 	err = i40e_init_interrupt_scheme(pf);
15862 	if (err)
15863 		goto err_switch_setup;
15864 
15865 	/* Reduce Tx and Rx pairs for kdump
15866 	 * When MSI-X is enabled, it's not allowed to use more TC queue
15867 	 * pairs than MSI-X vectors (pf->num_lan_msix) exist. Thus
15868 	 * vsi->num_queue_pairs will be equal to pf->num_lan_msix, i.e., 1.
15869 	 */
15870 	if (is_kdump_kernel())
15871 		pf->num_lan_msix = 1;
15872 
15873 	pf->udp_tunnel_nic.set_port = i40e_udp_tunnel_set_port;
15874 	pf->udp_tunnel_nic.unset_port = i40e_udp_tunnel_unset_port;
15875 	pf->udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP;
15876 	pf->udp_tunnel_nic.shared = &pf->udp_tunnel_shared;
15877 	pf->udp_tunnel_nic.tables[0].n_entries = I40E_MAX_PF_UDP_OFFLOAD_PORTS;
15878 	pf->udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
15879 						    UDP_TUNNEL_TYPE_GENEVE;
15880 
15881 	/* The number of VSIs reported by the FW is the minimum guaranteed
15882 	 * to us; HW supports far more and we share the remaining pool with
15883 	 * the other PFs. We allocate space for more than the guarantee with
15884 	 * the understanding that we might not get them all later.
15885 	 */
15886 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15887 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15888 	else
15889 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15890 	if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
15891 		dev_warn(&pf->pdev->dev,
15892 			 "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
15893 			 pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
15894 		pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
15895 	}
15896 
15897 	/* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15898 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15899 			  GFP_KERNEL);
15900 	if (!pf->vsi) {
15901 		err = -ENOMEM;
15902 		goto err_switch_setup;
15903 	}
15904 
15905 #ifdef CONFIG_PCI_IOV
15906 	/* prep for VF support */
15907 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15908 	    (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15909 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15910 		if (pci_num_vf(pdev))
15911 			pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
15912 	}
15913 #endif
15914 	err = i40e_setup_pf_switch(pf, false, false);
15915 	if (err) {
15916 		dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
15917 		goto err_vsis;
15918 	}
15919 	INIT_LIST_HEAD(&pf->vsi[pf->lan_vsi]->ch_list);
15920 
15921 	/* if FDIR VSI was set up, start it now */
15922 	for (i = 0; i < pf->num_alloc_vsi; i++) {
15923 		if (pf->vsi[i] && pf->vsi[i]->type == I40E_VSI_FDIR) {
15924 			i40e_vsi_open(pf->vsi[i]);
15925 			break;
15926 		}
15927 	}
15928 
15929 	/* The driver only wants link up/down and module qualification
15930 	 * reports from firmware.  Note the negative logic.
15931 	 */
15932 	err = i40e_aq_set_phy_int_mask(&pf->hw,
15933 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
15934 					 I40E_AQ_EVENT_MEDIA_NA |
15935 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
15936 	if (err)
15937 		dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
15938 			 i40e_stat_str(&pf->hw, err),
15939 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15940 
15941 	/* Reconfigure hardware for allowing smaller MSS in the case
15942 	 * of TSO, so that we avoid the MDD being fired and causing
15943 	 * a reset in the case of small MSS+TSO.
15944 	 */
15945 	val = rd32(hw, I40E_REG_MSS);
15946 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
15947 		val &= ~I40E_REG_MSS_MIN_MASK;
15948 		val |= I40E_64BYTE_MSS;
15949 		wr32(hw, I40E_REG_MSS, val);
15950 	}
15951 
15952 	if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
15953 		msleep(75);
15954 		err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
15955 		if (err)
15956 			dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
15957 				 i40e_stat_str(&pf->hw, err),
15958 				 i40e_aq_str(&pf->hw,
15959 					     pf->hw.aq.asq_last_status));
15960 	}
15961 	/* The main driver is (mostly) up and happy. We need to set this state
15962 	 * before setting up the misc vector or we get a race and the vector
15963 	 * ends up disabled forever.
15964 	 */
15965 	clear_bit(__I40E_DOWN, pf->state);
15966 
15967 	/* In case of MSIX we are going to setup the misc vector right here
15968 	 * to handle admin queue events etc. In case of legacy and MSI
15969 	 * the misc functionality and queue processing is combined in
15970 	 * the same vector and that gets setup at open.
15971 	 */
15972 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
15973 		err = i40e_setup_misc_vector(pf);
15974 		if (err) {
15975 			dev_info(&pdev->dev,
15976 				 "setup of misc vector failed: %d\n", err);
15977 			i40e_cloud_filter_exit(pf);
15978 			i40e_fdir_teardown(pf);
15979 			goto err_vsis;
15980 		}
15981 	}
15982 
15983 #ifdef CONFIG_PCI_IOV
15984 	/* prep for VF support */
15985 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15986 	    (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15987 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15988 		/* disable link interrupts for VFs */
15989 		val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
15990 		val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
15991 		wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
15992 		i40e_flush(hw);
15993 
15994 		if (pci_num_vf(pdev)) {
15995 			dev_info(&pdev->dev,
15996 				 "Active VFs found, allocating resources.\n");
15997 			err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
15998 			if (err)
15999 				dev_info(&pdev->dev,
16000 					 "Error %d allocating resources for existing VFs\n",
16001 					 err);
16002 		}
16003 	}
16004 #endif /* CONFIG_PCI_IOV */
16005 
16006 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16007 		pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
16008 						      pf->num_iwarp_msix,
16009 						      I40E_IWARP_IRQ_PILE_ID);
16010 		if (pf->iwarp_base_vector < 0) {
16011 			dev_info(&pdev->dev,
16012 				 "failed to get tracking for %d vectors for IWARP err=%d\n",
16013 				 pf->num_iwarp_msix, pf->iwarp_base_vector);
16014 			pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
16015 		}
16016 	}
16017 
16018 	i40e_dbg_pf_init(pf);
16019 
16020 	/* tell the firmware that we're starting */
16021 	i40e_send_version(pf);
16022 
16023 	/* since everything's happy, start the service_task timer */
16024 	mod_timer(&pf->service_timer,
16025 		  round_jiffies(jiffies + pf->service_timer_period));
16026 
16027 	/* add this PF to client device list and launch a client service task */
16028 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16029 		err = i40e_lan_add_device(pf);
16030 		if (err)
16031 			dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
16032 				 err);
16033 	}
16034 
16035 #define PCI_SPEED_SIZE 8
16036 #define PCI_WIDTH_SIZE 8
16037 	/* Devices on the IOSF bus do not have this information
16038 	 * and will report PCI Gen 1 x 1 by default so don't bother
16039 	 * checking them.
16040 	 */
16041 	if (!(pf->hw_features & I40E_HW_NO_PCI_LINK_CHECK)) {
16042 		char speed[PCI_SPEED_SIZE] = "Unknown";
16043 		char width[PCI_WIDTH_SIZE] = "Unknown";
16044 
16045 		/* Get the negotiated link width and speed from PCI config
16046 		 * space
16047 		 */
16048 		pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
16049 					  &link_status);
16050 
16051 		i40e_set_pci_config_data(hw, link_status);
16052 
16053 		switch (hw->bus.speed) {
16054 		case i40e_bus_speed_8000:
16055 			strlcpy(speed, "8.0", PCI_SPEED_SIZE); break;
16056 		case i40e_bus_speed_5000:
16057 			strlcpy(speed, "5.0", PCI_SPEED_SIZE); break;
16058 		case i40e_bus_speed_2500:
16059 			strlcpy(speed, "2.5", PCI_SPEED_SIZE); break;
16060 		default:
16061 			break;
16062 		}
16063 		switch (hw->bus.width) {
16064 		case i40e_bus_width_pcie_x8:
16065 			strlcpy(width, "8", PCI_WIDTH_SIZE); break;
16066 		case i40e_bus_width_pcie_x4:
16067 			strlcpy(width, "4", PCI_WIDTH_SIZE); break;
16068 		case i40e_bus_width_pcie_x2:
16069 			strlcpy(width, "2", PCI_WIDTH_SIZE); break;
16070 		case i40e_bus_width_pcie_x1:
16071 			strlcpy(width, "1", PCI_WIDTH_SIZE); break;
16072 		default:
16073 			break;
16074 		}
16075 
16076 		dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
16077 			 speed, width);
16078 
16079 		if (hw->bus.width < i40e_bus_width_pcie_x8 ||
16080 		    hw->bus.speed < i40e_bus_speed_8000) {
16081 			dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
16082 			dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
16083 		}
16084 	}
16085 
16086 	/* get the requested speeds from the fw */
16087 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
16088 	if (err)
16089 		dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %s last_status =  %s\n",
16090 			i40e_stat_str(&pf->hw, err),
16091 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16092 	pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
16093 
16094 	/* set the FEC config due to the board capabilities */
16095 	i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, &pf->flags);
16096 
16097 	/* get the supported phy types from the fw */
16098 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
16099 	if (err)
16100 		dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %s last_status =  %s\n",
16101 			i40e_stat_str(&pf->hw, err),
16102 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16103 
16104 	/* make sure the MFS hasn't been set lower than the default */
16105 #define MAX_FRAME_SIZE_DEFAULT 0x2600
16106 	val = (rd32(&pf->hw, I40E_PRTGL_SAH) &
16107 	       I40E_PRTGL_SAH_MFS_MASK) >> I40E_PRTGL_SAH_MFS_SHIFT;
16108 	if (val < MAX_FRAME_SIZE_DEFAULT)
16109 		dev_warn(&pdev->dev, "MFS for port %x has been set below the default: %x\n",
16110 			 i, val);
16111 
16112 	/* Add a filter to drop all Flow control frames from any VSI from being
16113 	 * transmitted. By doing so we stop a malicious VF from sending out
16114 	 * PAUSE or PFC frames and potentially controlling traffic for other
16115 	 * PF/VF VSIs.
16116 	 * The FW can still send Flow control frames if enabled.
16117 	 */
16118 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
16119 						       pf->main_vsi_seid);
16120 
16121 	if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
16122 		(pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
16123 		pf->hw_features |= I40E_HW_PHY_CONTROLS_LEDS;
16124 	if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
16125 		pf->hw_features |= I40E_HW_HAVE_CRT_RETIMER;
16126 	/* print a string summarizing features */
16127 	i40e_print_features(pf);
16128 
16129 	return 0;
16130 
16131 	/* Unwind what we've done if something failed in the setup */
16132 err_vsis:
16133 	set_bit(__I40E_DOWN, pf->state);
16134 	i40e_clear_interrupt_scheme(pf);
16135 	kfree(pf->vsi);
16136 err_switch_setup:
16137 	i40e_reset_interrupt_capability(pf);
16138 	del_timer_sync(&pf->service_timer);
16139 err_mac_addr:
16140 err_configure_lan_hmc:
16141 	(void)i40e_shutdown_lan_hmc(hw);
16142 err_init_lan_hmc:
16143 	kfree(pf->qp_pile);
16144 err_sw_init:
16145 err_adminq_setup:
16146 err_pf_reset:
16147 	iounmap(hw->hw_addr);
16148 err_ioremap:
16149 	kfree(pf);
16150 err_pf_alloc:
16151 	pci_disable_pcie_error_reporting(pdev);
16152 	pci_release_mem_regions(pdev);
16153 err_pci_reg:
16154 err_dma:
16155 	pci_disable_device(pdev);
16156 	return err;
16157 }
16158 
16159 /**
16160  * i40e_remove - Device removal routine
16161  * @pdev: PCI device information struct
16162  *
16163  * i40e_remove is called by the PCI subsystem to alert the driver
16164  * that is should release a PCI device.  This could be caused by a
16165  * Hot-Plug event, or because the driver is going to be removed from
16166  * memory.
16167  **/
16168 static void i40e_remove(struct pci_dev *pdev)
16169 {
16170 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16171 	struct i40e_hw *hw = &pf->hw;
16172 	i40e_status ret_code;
16173 	int i;
16174 
16175 	i40e_dbg_pf_exit(pf);
16176 
16177 	i40e_ptp_stop(pf);
16178 
16179 	/* Disable RSS in hw */
16180 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
16181 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
16182 
16183 	/* Grab __I40E_RESET_RECOVERY_PENDING and set __I40E_IN_REMOVE
16184 	 * flags, once they are set, i40e_rebuild should not be called as
16185 	 * i40e_prep_for_reset always returns early.
16186 	 */
16187 	while (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
16188 		usleep_range(1000, 2000);
16189 	set_bit(__I40E_IN_REMOVE, pf->state);
16190 
16191 	if (pf->flags & I40E_FLAG_SRIOV_ENABLED) {
16192 		set_bit(__I40E_VF_RESETS_DISABLED, pf->state);
16193 		i40e_free_vfs(pf);
16194 		pf->flags &= ~I40E_FLAG_SRIOV_ENABLED;
16195 	}
16196 	/* no more scheduling of any task */
16197 	set_bit(__I40E_SUSPENDED, pf->state);
16198 	set_bit(__I40E_DOWN, pf->state);
16199 	if (pf->service_timer.function)
16200 		del_timer_sync(&pf->service_timer);
16201 	if (pf->service_task.func)
16202 		cancel_work_sync(&pf->service_task);
16203 
16204 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
16205 		struct i40e_vsi *vsi = pf->vsi[0];
16206 
16207 		/* We know that we have allocated only one vsi for this PF,
16208 		 * it was just for registering netdevice, so the interface
16209 		 * could be visible in the 'ifconfig' output
16210 		 */
16211 		unregister_netdev(vsi->netdev);
16212 		free_netdev(vsi->netdev);
16213 
16214 		goto unmap;
16215 	}
16216 
16217 	/* Client close must be called explicitly here because the timer
16218 	 * has been stopped.
16219 	 */
16220 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16221 
16222 	i40e_fdir_teardown(pf);
16223 
16224 	/* If there is a switch structure or any orphans, remove them.
16225 	 * This will leave only the PF's VSI remaining.
16226 	 */
16227 	for (i = 0; i < I40E_MAX_VEB; i++) {
16228 		if (!pf->veb[i])
16229 			continue;
16230 
16231 		if (pf->veb[i]->uplink_seid == pf->mac_seid ||
16232 		    pf->veb[i]->uplink_seid == 0)
16233 			i40e_switch_branch_release(pf->veb[i]);
16234 	}
16235 
16236 	/* Now we can shutdown the PF's VSI, just before we kill
16237 	 * adminq and hmc.
16238 	 */
16239 	if (pf->vsi[pf->lan_vsi])
16240 		i40e_vsi_release(pf->vsi[pf->lan_vsi]);
16241 
16242 	i40e_cloud_filter_exit(pf);
16243 
16244 	/* remove attached clients */
16245 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16246 		ret_code = i40e_lan_del_device(pf);
16247 		if (ret_code)
16248 			dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
16249 				 ret_code);
16250 	}
16251 
16252 	/* shutdown and destroy the HMC */
16253 	if (hw->hmc.hmc_obj) {
16254 		ret_code = i40e_shutdown_lan_hmc(hw);
16255 		if (ret_code)
16256 			dev_warn(&pdev->dev,
16257 				 "Failed to destroy the HMC resources: %d\n",
16258 				 ret_code);
16259 	}
16260 
16261 unmap:
16262 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16263 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16264 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16265 		free_irq(pf->pdev->irq, pf);
16266 
16267 	/* shutdown the adminq */
16268 	i40e_shutdown_adminq(hw);
16269 
16270 	/* destroy the locks only once, here */
16271 	mutex_destroy(&hw->aq.arq_mutex);
16272 	mutex_destroy(&hw->aq.asq_mutex);
16273 
16274 	/* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
16275 	rtnl_lock();
16276 	i40e_clear_interrupt_scheme(pf);
16277 	for (i = 0; i < pf->num_alloc_vsi; i++) {
16278 		if (pf->vsi[i]) {
16279 			if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
16280 				i40e_vsi_clear_rings(pf->vsi[i]);
16281 			i40e_vsi_clear(pf->vsi[i]);
16282 			pf->vsi[i] = NULL;
16283 		}
16284 	}
16285 	rtnl_unlock();
16286 
16287 	for (i = 0; i < I40E_MAX_VEB; i++) {
16288 		kfree(pf->veb[i]);
16289 		pf->veb[i] = NULL;
16290 	}
16291 
16292 	kfree(pf->qp_pile);
16293 	kfree(pf->vsi);
16294 
16295 	iounmap(hw->hw_addr);
16296 	kfree(pf);
16297 	pci_release_mem_regions(pdev);
16298 
16299 	pci_disable_pcie_error_reporting(pdev);
16300 	pci_disable_device(pdev);
16301 }
16302 
16303 /**
16304  * i40e_pci_error_detected - warning that something funky happened in PCI land
16305  * @pdev: PCI device information struct
16306  * @error: the type of PCI error
16307  *
16308  * Called to warn that something happened and the error handling steps
16309  * are in progress.  Allows the driver to quiesce things, be ready for
16310  * remediation.
16311  **/
16312 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
16313 						pci_channel_state_t error)
16314 {
16315 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16316 
16317 	dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
16318 
16319 	if (!pf) {
16320 		dev_info(&pdev->dev,
16321 			 "Cannot recover - error happened during device probe\n");
16322 		return PCI_ERS_RESULT_DISCONNECT;
16323 	}
16324 
16325 	/* shutdown all operations */
16326 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16327 		i40e_prep_for_reset(pf);
16328 
16329 	/* Request a slot reset */
16330 	return PCI_ERS_RESULT_NEED_RESET;
16331 }
16332 
16333 /**
16334  * i40e_pci_error_slot_reset - a PCI slot reset just happened
16335  * @pdev: PCI device information struct
16336  *
16337  * Called to find if the driver can work with the device now that
16338  * the pci slot has been reset.  If a basic connection seems good
16339  * (registers are readable and have sane content) then return a
16340  * happy little PCI_ERS_RESULT_xxx.
16341  **/
16342 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
16343 {
16344 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16345 	pci_ers_result_t result;
16346 	u32 reg;
16347 
16348 	dev_dbg(&pdev->dev, "%s\n", __func__);
16349 	if (pci_enable_device_mem(pdev)) {
16350 		dev_info(&pdev->dev,
16351 			 "Cannot re-enable PCI device after reset.\n");
16352 		result = PCI_ERS_RESULT_DISCONNECT;
16353 	} else {
16354 		pci_set_master(pdev);
16355 		pci_restore_state(pdev);
16356 		pci_save_state(pdev);
16357 		pci_wake_from_d3(pdev, false);
16358 
16359 		reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
16360 		if (reg == 0)
16361 			result = PCI_ERS_RESULT_RECOVERED;
16362 		else
16363 			result = PCI_ERS_RESULT_DISCONNECT;
16364 	}
16365 
16366 	return result;
16367 }
16368 
16369 /**
16370  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
16371  * @pdev: PCI device information struct
16372  */
16373 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
16374 {
16375 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16376 
16377 	i40e_prep_for_reset(pf);
16378 }
16379 
16380 /**
16381  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
16382  * @pdev: PCI device information struct
16383  */
16384 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
16385 {
16386 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16387 
16388 	if (test_bit(__I40E_IN_REMOVE, pf->state))
16389 		return;
16390 
16391 	i40e_reset_and_rebuild(pf, false, false);
16392 }
16393 
16394 /**
16395  * i40e_pci_error_resume - restart operations after PCI error recovery
16396  * @pdev: PCI device information struct
16397  *
16398  * Called to allow the driver to bring things back up after PCI error
16399  * and/or reset recovery has finished.
16400  **/
16401 static void i40e_pci_error_resume(struct pci_dev *pdev)
16402 {
16403 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16404 
16405 	dev_dbg(&pdev->dev, "%s\n", __func__);
16406 	if (test_bit(__I40E_SUSPENDED, pf->state))
16407 		return;
16408 
16409 	i40e_handle_reset_warning(pf, false);
16410 }
16411 
16412 /**
16413  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
16414  * using the mac_address_write admin q function
16415  * @pf: pointer to i40e_pf struct
16416  **/
16417 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
16418 {
16419 	struct i40e_hw *hw = &pf->hw;
16420 	i40e_status ret;
16421 	u8 mac_addr[6];
16422 	u16 flags = 0;
16423 
16424 	/* Get current MAC address in case it's an LAA */
16425 	if (pf->vsi[pf->lan_vsi] && pf->vsi[pf->lan_vsi]->netdev) {
16426 		ether_addr_copy(mac_addr,
16427 				pf->vsi[pf->lan_vsi]->netdev->dev_addr);
16428 	} else {
16429 		dev_err(&pf->pdev->dev,
16430 			"Failed to retrieve MAC address; using default\n");
16431 		ether_addr_copy(mac_addr, hw->mac.addr);
16432 	}
16433 
16434 	/* The FW expects the mac address write cmd to first be called with
16435 	 * one of these flags before calling it again with the multicast
16436 	 * enable flags.
16437 	 */
16438 	flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
16439 
16440 	if (hw->func_caps.flex10_enable && hw->partition_id != 1)
16441 		flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
16442 
16443 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16444 	if (ret) {
16445 		dev_err(&pf->pdev->dev,
16446 			"Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
16447 		return;
16448 	}
16449 
16450 	flags = I40E_AQC_MC_MAG_EN
16451 			| I40E_AQC_WOL_PRESERVE_ON_PFR
16452 			| I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
16453 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16454 	if (ret)
16455 		dev_err(&pf->pdev->dev,
16456 			"Failed to enable Multicast Magic Packet wake up\n");
16457 }
16458 
16459 /**
16460  * i40e_shutdown - PCI callback for shutting down
16461  * @pdev: PCI device information struct
16462  **/
16463 static void i40e_shutdown(struct pci_dev *pdev)
16464 {
16465 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16466 	struct i40e_hw *hw = &pf->hw;
16467 
16468 	set_bit(__I40E_SUSPENDED, pf->state);
16469 	set_bit(__I40E_DOWN, pf->state);
16470 
16471 	del_timer_sync(&pf->service_timer);
16472 	cancel_work_sync(&pf->service_task);
16473 	i40e_cloud_filter_exit(pf);
16474 	i40e_fdir_teardown(pf);
16475 
16476 	/* Client close must be called explicitly here because the timer
16477 	 * has been stopped.
16478 	 */
16479 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16480 
16481 	if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16482 		i40e_enable_mc_magic_wake(pf);
16483 
16484 	i40e_prep_for_reset(pf);
16485 
16486 	wr32(hw, I40E_PFPM_APM,
16487 	     (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16488 	wr32(hw, I40E_PFPM_WUFC,
16489 	     (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16490 
16491 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16492 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16493 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16494 		free_irq(pf->pdev->irq, pf);
16495 
16496 	/* Since we're going to destroy queues during the
16497 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16498 	 * whole section
16499 	 */
16500 	rtnl_lock();
16501 	i40e_clear_interrupt_scheme(pf);
16502 	rtnl_unlock();
16503 
16504 	if (system_state == SYSTEM_POWER_OFF) {
16505 		pci_wake_from_d3(pdev, pf->wol_en);
16506 		pci_set_power_state(pdev, PCI_D3hot);
16507 	}
16508 }
16509 
16510 /**
16511  * i40e_suspend - PM callback for moving to D3
16512  * @dev: generic device information structure
16513  **/
16514 static int __maybe_unused i40e_suspend(struct device *dev)
16515 {
16516 	struct i40e_pf *pf = dev_get_drvdata(dev);
16517 	struct i40e_hw *hw = &pf->hw;
16518 
16519 	/* If we're already suspended, then there is nothing to do */
16520 	if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
16521 		return 0;
16522 
16523 	set_bit(__I40E_DOWN, pf->state);
16524 
16525 	/* Ensure service task will not be running */
16526 	del_timer_sync(&pf->service_timer);
16527 	cancel_work_sync(&pf->service_task);
16528 
16529 	/* Client close must be called explicitly here because the timer
16530 	 * has been stopped.
16531 	 */
16532 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16533 
16534 	if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16535 		i40e_enable_mc_magic_wake(pf);
16536 
16537 	/* Since we're going to destroy queues during the
16538 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16539 	 * whole section
16540 	 */
16541 	rtnl_lock();
16542 
16543 	i40e_prep_for_reset(pf);
16544 
16545 	wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16546 	wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16547 
16548 	/* Clear the interrupt scheme and release our IRQs so that the system
16549 	 * can safely hibernate even when there are a large number of CPUs.
16550 	 * Otherwise hibernation might fail when mapping all the vectors back
16551 	 * to CPU0.
16552 	 */
16553 	i40e_clear_interrupt_scheme(pf);
16554 
16555 	rtnl_unlock();
16556 
16557 	return 0;
16558 }
16559 
16560 /**
16561  * i40e_resume - PM callback for waking up from D3
16562  * @dev: generic device information structure
16563  **/
16564 static int __maybe_unused i40e_resume(struct device *dev)
16565 {
16566 	struct i40e_pf *pf = dev_get_drvdata(dev);
16567 	int err;
16568 
16569 	/* If we're not suspended, then there is nothing to do */
16570 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16571 		return 0;
16572 
16573 	/* We need to hold the RTNL lock prior to restoring interrupt schemes,
16574 	 * since we're going to be restoring queues
16575 	 */
16576 	rtnl_lock();
16577 
16578 	/* We cleared the interrupt scheme when we suspended, so we need to
16579 	 * restore it now to resume device functionality.
16580 	 */
16581 	err = i40e_restore_interrupt_scheme(pf);
16582 	if (err) {
16583 		dev_err(dev, "Cannot restore interrupt scheme: %d\n",
16584 			err);
16585 	}
16586 
16587 	clear_bit(__I40E_DOWN, pf->state);
16588 	i40e_reset_and_rebuild(pf, false, true);
16589 
16590 	rtnl_unlock();
16591 
16592 	/* Clear suspended state last after everything is recovered */
16593 	clear_bit(__I40E_SUSPENDED, pf->state);
16594 
16595 	/* Restart the service task */
16596 	mod_timer(&pf->service_timer,
16597 		  round_jiffies(jiffies + pf->service_timer_period));
16598 
16599 	return 0;
16600 }
16601 
16602 static const struct pci_error_handlers i40e_err_handler = {
16603 	.error_detected = i40e_pci_error_detected,
16604 	.slot_reset = i40e_pci_error_slot_reset,
16605 	.reset_prepare = i40e_pci_error_reset_prepare,
16606 	.reset_done = i40e_pci_error_reset_done,
16607 	.resume = i40e_pci_error_resume,
16608 };
16609 
16610 static SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
16611 
16612 static struct pci_driver i40e_driver = {
16613 	.name     = i40e_driver_name,
16614 	.id_table = i40e_pci_tbl,
16615 	.probe    = i40e_probe,
16616 	.remove   = i40e_remove,
16617 	.driver   = {
16618 		.pm = &i40e_pm_ops,
16619 	},
16620 	.shutdown = i40e_shutdown,
16621 	.err_handler = &i40e_err_handler,
16622 	.sriov_configure = i40e_pci_sriov_configure,
16623 };
16624 
16625 /**
16626  * i40e_init_module - Driver registration routine
16627  *
16628  * i40e_init_module is the first routine called when the driver is
16629  * loaded. All it does is register with the PCI subsystem.
16630  **/
16631 static int __init i40e_init_module(void)
16632 {
16633 	pr_info("%s: %s\n", i40e_driver_name, i40e_driver_string);
16634 	pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
16635 
16636 	/* There is no need to throttle the number of active tasks because
16637 	 * each device limits its own task using a state bit for scheduling
16638 	 * the service task, and the device tasks do not interfere with each
16639 	 * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
16640 	 * since we need to be able to guarantee forward progress even under
16641 	 * memory pressure.
16642 	 */
16643 	i40e_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, i40e_driver_name);
16644 	if (!i40e_wq) {
16645 		pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
16646 		return -ENOMEM;
16647 	}
16648 
16649 	i40e_dbg_init();
16650 	return pci_register_driver(&i40e_driver);
16651 }
16652 module_init(i40e_init_module);
16653 
16654 /**
16655  * i40e_exit_module - Driver exit cleanup routine
16656  *
16657  * i40e_exit_module is called just before the driver is removed
16658  * from memory.
16659  **/
16660 static void __exit i40e_exit_module(void)
16661 {
16662 	pci_unregister_driver(&i40e_driver);
16663 	destroy_workqueue(i40e_wq);
16664 	ida_destroy(&i40e_client_ida);
16665 	i40e_dbg_exit();
16666 }
16667 module_exit(i40e_exit_module);
16668