1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2013 - 2021 Intel Corporation. */
3 
4 #include <linux/etherdevice.h>
5 #include <linux/of_net.h>
6 #include <linux/pci.h>
7 #include <linux/bpf.h>
8 #include <generated/utsrelease.h>
9 #include <linux/crash_dump.h>
10 
11 /* Local includes */
12 #include "i40e.h"
13 #include "i40e_diag.h"
14 #include "i40e_xsk.h"
15 #include <net/udp_tunnel.h>
16 #include <net/xdp_sock_drv.h>
17 /* All i40e tracepoints are defined by the include below, which
18  * must be included exactly once across the whole kernel with
19  * CREATE_TRACE_POINTS defined
20  */
21 #define CREATE_TRACE_POINTS
22 #include "i40e_trace.h"
23 
24 const char i40e_driver_name[] = "i40e";
25 static const char i40e_driver_string[] =
26 			"Intel(R) Ethernet Connection XL710 Network Driver";
27 
28 static const char i40e_copyright[] = "Copyright (c) 2013 - 2019 Intel Corporation.";
29 
30 /* a bit of forward declarations */
31 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi);
32 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired);
33 static int i40e_add_vsi(struct i40e_vsi *vsi);
34 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi);
35 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired);
36 static int i40e_setup_misc_vector(struct i40e_pf *pf);
37 static void i40e_determine_queue_usage(struct i40e_pf *pf);
38 static int i40e_setup_pf_filter_control(struct i40e_pf *pf);
39 static void i40e_prep_for_reset(struct i40e_pf *pf);
40 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
41 				   bool lock_acquired);
42 static int i40e_reset(struct i40e_pf *pf);
43 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired);
44 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf);
45 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf);
46 static bool i40e_check_recovery_mode(struct i40e_pf *pf);
47 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw);
48 static void i40e_fdir_sb_setup(struct i40e_pf *pf);
49 static int i40e_veb_get_bw_info(struct i40e_veb *veb);
50 static int i40e_get_capabilities(struct i40e_pf *pf,
51 				 enum i40e_admin_queue_opc list_type);
52 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf);
53 
54 /* i40e_pci_tbl - PCI Device ID Table
55  *
56  * Last entry must be all 0s
57  *
58  * { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
59  *   Class, Class Mask, private data (not used) }
60  */
61 static const struct pci_device_id i40e_pci_tbl[] = {
62 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_XL710), 0},
63 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QEMU), 0},
64 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_B), 0},
65 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_C), 0},
66 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_A), 0},
67 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_B), 0},
68 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_C), 0},
69 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_BC), 0},
70 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T), 0},
71 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T4), 0},
72 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_BC), 0},
73 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_SFP), 0},
74 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_B), 0},
75 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_X722), 0},
76 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_X722), 0},
77 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722), 0},
78 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_X722), 0},
79 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_X722), 0},
80 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_I_X722), 0},
81 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722_A), 0},
82 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2), 0},
83 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A), 0},
84 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_X710_N3000), 0},
85 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_XXV710_N3000), 0},
86 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B), 0},
87 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28), 0},
88 	/* required last entry */
89 	{0, }
90 };
91 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
92 
93 #define I40E_MAX_VF_COUNT 128
94 static int debug = -1;
95 module_param(debug, uint, 0);
96 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
97 
98 MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
99 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
100 MODULE_LICENSE("GPL v2");
101 
102 static struct workqueue_struct *i40e_wq;
103 
104 static void netdev_hw_addr_refcnt(struct i40e_mac_filter *f,
105 				  struct net_device *netdev, int delta)
106 {
107 	struct netdev_hw_addr *ha;
108 
109 	if (!f || !netdev)
110 		return;
111 
112 	netdev_for_each_mc_addr(ha, netdev) {
113 		if (ether_addr_equal(ha->addr, f->macaddr)) {
114 			ha->refcount += delta;
115 			if (ha->refcount <= 0)
116 				ha->refcount = 1;
117 			break;
118 		}
119 	}
120 }
121 
122 /**
123  * i40e_allocate_dma_mem_d - OS specific memory alloc for shared code
124  * @hw:   pointer to the HW structure
125  * @mem:  ptr to mem struct to fill out
126  * @size: size of memory requested
127  * @alignment: what to align the allocation to
128  **/
129 int i40e_allocate_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem,
130 			    u64 size, u32 alignment)
131 {
132 	struct i40e_pf *pf = (struct i40e_pf *)hw->back;
133 
134 	mem->size = ALIGN(size, alignment);
135 	mem->va = dma_alloc_coherent(&pf->pdev->dev, mem->size, &mem->pa,
136 				     GFP_KERNEL);
137 	if (!mem->va)
138 		return -ENOMEM;
139 
140 	return 0;
141 }
142 
143 /**
144  * i40e_free_dma_mem_d - OS specific memory free for shared code
145  * @hw:   pointer to the HW structure
146  * @mem:  ptr to mem struct to free
147  **/
148 int i40e_free_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem)
149 {
150 	struct i40e_pf *pf = (struct i40e_pf *)hw->back;
151 
152 	dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
153 	mem->va = NULL;
154 	mem->pa = 0;
155 	mem->size = 0;
156 
157 	return 0;
158 }
159 
160 /**
161  * i40e_allocate_virt_mem_d - OS specific memory alloc for shared code
162  * @hw:   pointer to the HW structure
163  * @mem:  ptr to mem struct to fill out
164  * @size: size of memory requested
165  **/
166 int i40e_allocate_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem,
167 			     u32 size)
168 {
169 	mem->size = size;
170 	mem->va = kzalloc(size, GFP_KERNEL);
171 
172 	if (!mem->va)
173 		return -ENOMEM;
174 
175 	return 0;
176 }
177 
178 /**
179  * i40e_free_virt_mem_d - OS specific memory free for shared code
180  * @hw:   pointer to the HW structure
181  * @mem:  ptr to mem struct to free
182  **/
183 int i40e_free_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem)
184 {
185 	/* it's ok to kfree a NULL pointer */
186 	kfree(mem->va);
187 	mem->va = NULL;
188 	mem->size = 0;
189 
190 	return 0;
191 }
192 
193 /**
194  * i40e_get_lump - find a lump of free generic resource
195  * @pf: board private structure
196  * @pile: the pile of resource to search
197  * @needed: the number of items needed
198  * @id: an owner id to stick on the items assigned
199  *
200  * Returns the base item index of the lump, or negative for error
201  **/
202 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
203 			 u16 needed, u16 id)
204 {
205 	int ret = -ENOMEM;
206 	int i, j;
207 
208 	if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
209 		dev_info(&pf->pdev->dev,
210 			 "param err: pile=%s needed=%d id=0x%04x\n",
211 			 pile ? "<valid>" : "<null>", needed, id);
212 		return -EINVAL;
213 	}
214 
215 	/* Allocate last queue in the pile for FDIR VSI queue
216 	 * so it doesn't fragment the qp_pile
217 	 */
218 	if (pile == pf->qp_pile && pf->vsi[id]->type == I40E_VSI_FDIR) {
219 		if (pile->list[pile->num_entries - 1] & I40E_PILE_VALID_BIT) {
220 			dev_err(&pf->pdev->dev,
221 				"Cannot allocate queue %d for I40E_VSI_FDIR\n",
222 				pile->num_entries - 1);
223 			return -ENOMEM;
224 		}
225 		pile->list[pile->num_entries - 1] = id | I40E_PILE_VALID_BIT;
226 		return pile->num_entries - 1;
227 	}
228 
229 	i = 0;
230 	while (i < pile->num_entries) {
231 		/* skip already allocated entries */
232 		if (pile->list[i] & I40E_PILE_VALID_BIT) {
233 			i++;
234 			continue;
235 		}
236 
237 		/* do we have enough in this lump? */
238 		for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
239 			if (pile->list[i+j] & I40E_PILE_VALID_BIT)
240 				break;
241 		}
242 
243 		if (j == needed) {
244 			/* there was enough, so assign it to the requestor */
245 			for (j = 0; j < needed; j++)
246 				pile->list[i+j] = id | I40E_PILE_VALID_BIT;
247 			ret = i;
248 			break;
249 		}
250 
251 		/* not enough, so skip over it and continue looking */
252 		i += j;
253 	}
254 
255 	return ret;
256 }
257 
258 /**
259  * i40e_put_lump - return a lump of generic resource
260  * @pile: the pile of resource to search
261  * @index: the base item index
262  * @id: the owner id of the items assigned
263  *
264  * Returns the count of items in the lump
265  **/
266 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
267 {
268 	int valid_id = (id | I40E_PILE_VALID_BIT);
269 	int count = 0;
270 	u16 i;
271 
272 	if (!pile || index >= pile->num_entries)
273 		return -EINVAL;
274 
275 	for (i = index;
276 	     i < pile->num_entries && pile->list[i] == valid_id;
277 	     i++) {
278 		pile->list[i] = 0;
279 		count++;
280 	}
281 
282 
283 	return count;
284 }
285 
286 /**
287  * i40e_find_vsi_from_id - searches for the vsi with the given id
288  * @pf: the pf structure to search for the vsi
289  * @id: id of the vsi it is searching for
290  **/
291 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
292 {
293 	int i;
294 
295 	for (i = 0; i < pf->num_alloc_vsi; i++)
296 		if (pf->vsi[i] && (pf->vsi[i]->id == id))
297 			return pf->vsi[i];
298 
299 	return NULL;
300 }
301 
302 /**
303  * i40e_service_event_schedule - Schedule the service task to wake up
304  * @pf: board private structure
305  *
306  * If not already scheduled, this puts the task into the work queue
307  **/
308 void i40e_service_event_schedule(struct i40e_pf *pf)
309 {
310 	if ((!test_bit(__I40E_DOWN, pf->state) &&
311 	     !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) ||
312 	      test_bit(__I40E_RECOVERY_MODE, pf->state))
313 		queue_work(i40e_wq, &pf->service_task);
314 }
315 
316 /**
317  * i40e_tx_timeout - Respond to a Tx Hang
318  * @netdev: network interface device structure
319  * @txqueue: queue number timing out
320  *
321  * If any port has noticed a Tx timeout, it is likely that the whole
322  * device is munged, not just the one netdev port, so go for the full
323  * reset.
324  **/
325 static void i40e_tx_timeout(struct net_device *netdev, unsigned int txqueue)
326 {
327 	struct i40e_netdev_priv *np = netdev_priv(netdev);
328 	struct i40e_vsi *vsi = np->vsi;
329 	struct i40e_pf *pf = vsi->back;
330 	struct i40e_ring *tx_ring = NULL;
331 	unsigned int i;
332 	u32 head, val;
333 
334 	pf->tx_timeout_count++;
335 
336 	/* with txqueue index, find the tx_ring struct */
337 	for (i = 0; i < vsi->num_queue_pairs; i++) {
338 		if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
339 			if (txqueue ==
340 			    vsi->tx_rings[i]->queue_index) {
341 				tx_ring = vsi->tx_rings[i];
342 				break;
343 			}
344 		}
345 	}
346 
347 	if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
348 		pf->tx_timeout_recovery_level = 1;  /* reset after some time */
349 	else if (time_before(jiffies,
350 		      (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
351 		return;   /* don't do any new action before the next timeout */
352 
353 	/* don't kick off another recovery if one is already pending */
354 	if (test_and_set_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state))
355 		return;
356 
357 	if (tx_ring) {
358 		head = i40e_get_head(tx_ring);
359 		/* Read interrupt register */
360 		if (pf->flags & I40E_FLAG_MSIX_ENABLED)
361 			val = rd32(&pf->hw,
362 			     I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
363 						tx_ring->vsi->base_vector - 1));
364 		else
365 			val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
366 
367 		netdev_info(netdev, "tx_timeout: VSI_seid: %d, Q %d, NTC: 0x%x, HWB: 0x%x, NTU: 0x%x, TAIL: 0x%x, INT: 0x%x\n",
368 			    vsi->seid, txqueue, tx_ring->next_to_clean,
369 			    head, tx_ring->next_to_use,
370 			    readl(tx_ring->tail), val);
371 	}
372 
373 	pf->tx_timeout_last_recovery = jiffies;
374 	netdev_info(netdev, "tx_timeout recovery level %d, txqueue %d\n",
375 		    pf->tx_timeout_recovery_level, txqueue);
376 
377 	switch (pf->tx_timeout_recovery_level) {
378 	case 1:
379 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
380 		break;
381 	case 2:
382 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
383 		break;
384 	case 3:
385 		set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
386 		break;
387 	default:
388 		netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in non-recoverable state.\n");
389 		set_bit(__I40E_DOWN_REQUESTED, pf->state);
390 		set_bit(__I40E_VSI_DOWN_REQUESTED, vsi->state);
391 		break;
392 	}
393 
394 	i40e_service_event_schedule(pf);
395 	pf->tx_timeout_recovery_level++;
396 }
397 
398 /**
399  * i40e_get_vsi_stats_struct - Get System Network Statistics
400  * @vsi: the VSI we care about
401  *
402  * Returns the address of the device statistics structure.
403  * The statistics are actually updated from the service task.
404  **/
405 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
406 {
407 	return &vsi->net_stats;
408 }
409 
410 /**
411  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
412  * @ring: Tx ring to get statistics from
413  * @stats: statistics entry to be updated
414  **/
415 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
416 					    struct rtnl_link_stats64 *stats)
417 {
418 	u64 bytes, packets;
419 	unsigned int start;
420 
421 	do {
422 		start = u64_stats_fetch_begin_irq(&ring->syncp);
423 		packets = ring->stats.packets;
424 		bytes   = ring->stats.bytes;
425 	} while (u64_stats_fetch_retry_irq(&ring->syncp, start));
426 
427 	stats->tx_packets += packets;
428 	stats->tx_bytes   += bytes;
429 }
430 
431 /**
432  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
433  * @netdev: network interface device structure
434  * @stats: data structure to store statistics
435  *
436  * Returns the address of the device statistics structure.
437  * The statistics are actually updated from the service task.
438  **/
439 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
440 				  struct rtnl_link_stats64 *stats)
441 {
442 	struct i40e_netdev_priv *np = netdev_priv(netdev);
443 	struct i40e_vsi *vsi = np->vsi;
444 	struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
445 	struct i40e_ring *ring;
446 	int i;
447 
448 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
449 		return;
450 
451 	if (!vsi->tx_rings)
452 		return;
453 
454 	rcu_read_lock();
455 	for (i = 0; i < vsi->num_queue_pairs; i++) {
456 		u64 bytes, packets;
457 		unsigned int start;
458 
459 		ring = READ_ONCE(vsi->tx_rings[i]);
460 		if (!ring)
461 			continue;
462 		i40e_get_netdev_stats_struct_tx(ring, stats);
463 
464 		if (i40e_enabled_xdp_vsi(vsi)) {
465 			ring = READ_ONCE(vsi->xdp_rings[i]);
466 			if (!ring)
467 				continue;
468 			i40e_get_netdev_stats_struct_tx(ring, stats);
469 		}
470 
471 		ring = READ_ONCE(vsi->rx_rings[i]);
472 		if (!ring)
473 			continue;
474 		do {
475 			start   = u64_stats_fetch_begin_irq(&ring->syncp);
476 			packets = ring->stats.packets;
477 			bytes   = ring->stats.bytes;
478 		} while (u64_stats_fetch_retry_irq(&ring->syncp, start));
479 
480 		stats->rx_packets += packets;
481 		stats->rx_bytes   += bytes;
482 
483 	}
484 	rcu_read_unlock();
485 
486 	/* following stats updated by i40e_watchdog_subtask() */
487 	stats->multicast	= vsi_stats->multicast;
488 	stats->tx_errors	= vsi_stats->tx_errors;
489 	stats->tx_dropped	= vsi_stats->tx_dropped;
490 	stats->rx_errors	= vsi_stats->rx_errors;
491 	stats->rx_dropped	= vsi_stats->rx_dropped;
492 	stats->rx_crc_errors	= vsi_stats->rx_crc_errors;
493 	stats->rx_length_errors	= vsi_stats->rx_length_errors;
494 }
495 
496 /**
497  * i40e_vsi_reset_stats - Resets all stats of the given vsi
498  * @vsi: the VSI to have its stats reset
499  **/
500 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
501 {
502 	struct rtnl_link_stats64 *ns;
503 	int i;
504 
505 	if (!vsi)
506 		return;
507 
508 	ns = i40e_get_vsi_stats_struct(vsi);
509 	memset(ns, 0, sizeof(*ns));
510 	memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
511 	memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
512 	memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
513 	if (vsi->rx_rings && vsi->rx_rings[0]) {
514 		for (i = 0; i < vsi->num_queue_pairs; i++) {
515 			memset(&vsi->rx_rings[i]->stats, 0,
516 			       sizeof(vsi->rx_rings[i]->stats));
517 			memset(&vsi->rx_rings[i]->rx_stats, 0,
518 			       sizeof(vsi->rx_rings[i]->rx_stats));
519 			memset(&vsi->tx_rings[i]->stats, 0,
520 			       sizeof(vsi->tx_rings[i]->stats));
521 			memset(&vsi->tx_rings[i]->tx_stats, 0,
522 			       sizeof(vsi->tx_rings[i]->tx_stats));
523 		}
524 	}
525 	vsi->stat_offsets_loaded = false;
526 }
527 
528 /**
529  * i40e_pf_reset_stats - Reset all of the stats for the given PF
530  * @pf: the PF to be reset
531  **/
532 void i40e_pf_reset_stats(struct i40e_pf *pf)
533 {
534 	int i;
535 
536 	memset(&pf->stats, 0, sizeof(pf->stats));
537 	memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
538 	pf->stat_offsets_loaded = false;
539 
540 	for (i = 0; i < I40E_MAX_VEB; i++) {
541 		if (pf->veb[i]) {
542 			memset(&pf->veb[i]->stats, 0,
543 			       sizeof(pf->veb[i]->stats));
544 			memset(&pf->veb[i]->stats_offsets, 0,
545 			       sizeof(pf->veb[i]->stats_offsets));
546 			memset(&pf->veb[i]->tc_stats, 0,
547 			       sizeof(pf->veb[i]->tc_stats));
548 			memset(&pf->veb[i]->tc_stats_offsets, 0,
549 			       sizeof(pf->veb[i]->tc_stats_offsets));
550 			pf->veb[i]->stat_offsets_loaded = false;
551 		}
552 	}
553 	pf->hw_csum_rx_error = 0;
554 }
555 
556 /**
557  * i40e_compute_pci_to_hw_id - compute index form PCI function.
558  * @vsi: ptr to the VSI to read from.
559  * @hw: ptr to the hardware info.
560  **/
561 static u32 i40e_compute_pci_to_hw_id(struct i40e_vsi *vsi, struct i40e_hw *hw)
562 {
563 	int pf_count = i40e_get_pf_count(hw);
564 
565 	if (vsi->type == I40E_VSI_SRIOV)
566 		return (hw->port * BIT(7)) / pf_count + vsi->vf_id;
567 
568 	return hw->port + BIT(7);
569 }
570 
571 /**
572  * i40e_stat_update64 - read and update a 64 bit stat from the chip.
573  * @hw: ptr to the hardware info.
574  * @hireg: the high 32 bit reg to read.
575  * @loreg: the low 32 bit reg to read.
576  * @offset_loaded: has the initial offset been loaded yet.
577  * @offset: ptr to current offset value.
578  * @stat: ptr to the stat.
579  *
580  * Since the device stats are not reset at PFReset, they will not
581  * be zeroed when the driver starts.  We'll save the first values read
582  * and use them as offsets to be subtracted from the raw values in order
583  * to report stats that count from zero.
584  **/
585 static void i40e_stat_update64(struct i40e_hw *hw, u32 hireg, u32 loreg,
586 			       bool offset_loaded, u64 *offset, u64 *stat)
587 {
588 	u64 new_data;
589 
590 	new_data = rd64(hw, loreg);
591 
592 	if (!offset_loaded || new_data < *offset)
593 		*offset = new_data;
594 	*stat = new_data - *offset;
595 }
596 
597 /**
598  * i40e_stat_update48 - read and update a 48 bit stat from the chip
599  * @hw: ptr to the hardware info
600  * @hireg: the high 32 bit reg to read
601  * @loreg: the low 32 bit reg to read
602  * @offset_loaded: has the initial offset been loaded yet
603  * @offset: ptr to current offset value
604  * @stat: ptr to the stat
605  *
606  * Since the device stats are not reset at PFReset, they likely will not
607  * be zeroed when the driver starts.  We'll save the first values read
608  * and use them as offsets to be subtracted from the raw values in order
609  * to report stats that count from zero.  In the process, we also manage
610  * the potential roll-over.
611  **/
612 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
613 			       bool offset_loaded, u64 *offset, u64 *stat)
614 {
615 	u64 new_data;
616 
617 	if (hw->device_id == I40E_DEV_ID_QEMU) {
618 		new_data = rd32(hw, loreg);
619 		new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
620 	} else {
621 		new_data = rd64(hw, loreg);
622 	}
623 	if (!offset_loaded)
624 		*offset = new_data;
625 	if (likely(new_data >= *offset))
626 		*stat = new_data - *offset;
627 	else
628 		*stat = (new_data + BIT_ULL(48)) - *offset;
629 	*stat &= 0xFFFFFFFFFFFFULL;
630 }
631 
632 /**
633  * i40e_stat_update32 - read and update a 32 bit stat from the chip
634  * @hw: ptr to the hardware info
635  * @reg: the hw reg to read
636  * @offset_loaded: has the initial offset been loaded yet
637  * @offset: ptr to current offset value
638  * @stat: ptr to the stat
639  **/
640 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
641 			       bool offset_loaded, u64 *offset, u64 *stat)
642 {
643 	u32 new_data;
644 
645 	new_data = rd32(hw, reg);
646 	if (!offset_loaded)
647 		*offset = new_data;
648 	if (likely(new_data >= *offset))
649 		*stat = (u32)(new_data - *offset);
650 	else
651 		*stat = (u32)((new_data + BIT_ULL(32)) - *offset);
652 }
653 
654 /**
655  * i40e_stat_update_and_clear32 - read and clear hw reg, update a 32 bit stat
656  * @hw: ptr to the hardware info
657  * @reg: the hw reg to read and clear
658  * @stat: ptr to the stat
659  **/
660 static void i40e_stat_update_and_clear32(struct i40e_hw *hw, u32 reg, u64 *stat)
661 {
662 	u32 new_data = rd32(hw, reg);
663 
664 	wr32(hw, reg, 1); /* must write a nonzero value to clear register */
665 	*stat += new_data;
666 }
667 
668 /**
669  * i40e_stats_update_rx_discards - update rx_discards.
670  * @vsi: ptr to the VSI to be updated.
671  * @hw: ptr to the hardware info.
672  * @stat_idx: VSI's stat_counter_idx.
673  * @offset_loaded: ptr to the VSI's stat_offsets_loaded.
674  * @stat_offset: ptr to stat_offset to store first read of specific register.
675  * @stat: ptr to VSI's stat to be updated.
676  **/
677 static void
678 i40e_stats_update_rx_discards(struct i40e_vsi *vsi, struct i40e_hw *hw,
679 			      int stat_idx, bool offset_loaded,
680 			      struct i40e_eth_stats *stat_offset,
681 			      struct i40e_eth_stats *stat)
682 {
683 	u64 rx_rdpc, rx_rxerr;
684 
685 	i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx), offset_loaded,
686 			   &stat_offset->rx_discards, &rx_rdpc);
687 	i40e_stat_update64(hw,
688 			   I40E_GL_RXERR1H(i40e_compute_pci_to_hw_id(vsi, hw)),
689 			   I40E_GL_RXERR1L(i40e_compute_pci_to_hw_id(vsi, hw)),
690 			   offset_loaded, &stat_offset->rx_discards_other,
691 			   &rx_rxerr);
692 
693 	stat->rx_discards = rx_rdpc + rx_rxerr;
694 }
695 
696 /**
697  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
698  * @vsi: the VSI to be updated
699  **/
700 void i40e_update_eth_stats(struct i40e_vsi *vsi)
701 {
702 	int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
703 	struct i40e_pf *pf = vsi->back;
704 	struct i40e_hw *hw = &pf->hw;
705 	struct i40e_eth_stats *oes;
706 	struct i40e_eth_stats *es;     /* device's eth stats */
707 
708 	es = &vsi->eth_stats;
709 	oes = &vsi->eth_stats_offsets;
710 
711 	/* Gather up the stats that the hw collects */
712 	i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
713 			   vsi->stat_offsets_loaded,
714 			   &oes->tx_errors, &es->tx_errors);
715 	i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx),
716 			   vsi->stat_offsets_loaded,
717 			   &oes->rx_discards, &es->rx_discards);
718 	i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
719 			   vsi->stat_offsets_loaded,
720 			   &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
721 
722 	i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
723 			   I40E_GLV_GORCL(stat_idx),
724 			   vsi->stat_offsets_loaded,
725 			   &oes->rx_bytes, &es->rx_bytes);
726 	i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
727 			   I40E_GLV_UPRCL(stat_idx),
728 			   vsi->stat_offsets_loaded,
729 			   &oes->rx_unicast, &es->rx_unicast);
730 	i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
731 			   I40E_GLV_MPRCL(stat_idx),
732 			   vsi->stat_offsets_loaded,
733 			   &oes->rx_multicast, &es->rx_multicast);
734 	i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
735 			   I40E_GLV_BPRCL(stat_idx),
736 			   vsi->stat_offsets_loaded,
737 			   &oes->rx_broadcast, &es->rx_broadcast);
738 
739 	i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
740 			   I40E_GLV_GOTCL(stat_idx),
741 			   vsi->stat_offsets_loaded,
742 			   &oes->tx_bytes, &es->tx_bytes);
743 	i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
744 			   I40E_GLV_UPTCL(stat_idx),
745 			   vsi->stat_offsets_loaded,
746 			   &oes->tx_unicast, &es->tx_unicast);
747 	i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
748 			   I40E_GLV_MPTCL(stat_idx),
749 			   vsi->stat_offsets_loaded,
750 			   &oes->tx_multicast, &es->tx_multicast);
751 	i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
752 			   I40E_GLV_BPTCL(stat_idx),
753 			   vsi->stat_offsets_loaded,
754 			   &oes->tx_broadcast, &es->tx_broadcast);
755 
756 	i40e_stats_update_rx_discards(vsi, hw, stat_idx,
757 				      vsi->stat_offsets_loaded, oes, es);
758 
759 	vsi->stat_offsets_loaded = true;
760 }
761 
762 /**
763  * i40e_update_veb_stats - Update Switch component statistics
764  * @veb: the VEB being updated
765  **/
766 void i40e_update_veb_stats(struct i40e_veb *veb)
767 {
768 	struct i40e_pf *pf = veb->pf;
769 	struct i40e_hw *hw = &pf->hw;
770 	struct i40e_eth_stats *oes;
771 	struct i40e_eth_stats *es;     /* device's eth stats */
772 	struct i40e_veb_tc_stats *veb_oes;
773 	struct i40e_veb_tc_stats *veb_es;
774 	int i, idx = 0;
775 
776 	idx = veb->stats_idx;
777 	es = &veb->stats;
778 	oes = &veb->stats_offsets;
779 	veb_es = &veb->tc_stats;
780 	veb_oes = &veb->tc_stats_offsets;
781 
782 	/* Gather up the stats that the hw collects */
783 	i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
784 			   veb->stat_offsets_loaded,
785 			   &oes->tx_discards, &es->tx_discards);
786 	if (hw->revision_id > 0)
787 		i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
788 				   veb->stat_offsets_loaded,
789 				   &oes->rx_unknown_protocol,
790 				   &es->rx_unknown_protocol);
791 	i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
792 			   veb->stat_offsets_loaded,
793 			   &oes->rx_bytes, &es->rx_bytes);
794 	i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
795 			   veb->stat_offsets_loaded,
796 			   &oes->rx_unicast, &es->rx_unicast);
797 	i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
798 			   veb->stat_offsets_loaded,
799 			   &oes->rx_multicast, &es->rx_multicast);
800 	i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
801 			   veb->stat_offsets_loaded,
802 			   &oes->rx_broadcast, &es->rx_broadcast);
803 
804 	i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
805 			   veb->stat_offsets_loaded,
806 			   &oes->tx_bytes, &es->tx_bytes);
807 	i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
808 			   veb->stat_offsets_loaded,
809 			   &oes->tx_unicast, &es->tx_unicast);
810 	i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
811 			   veb->stat_offsets_loaded,
812 			   &oes->tx_multicast, &es->tx_multicast);
813 	i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
814 			   veb->stat_offsets_loaded,
815 			   &oes->tx_broadcast, &es->tx_broadcast);
816 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
817 		i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
818 				   I40E_GLVEBTC_RPCL(i, idx),
819 				   veb->stat_offsets_loaded,
820 				   &veb_oes->tc_rx_packets[i],
821 				   &veb_es->tc_rx_packets[i]);
822 		i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
823 				   I40E_GLVEBTC_RBCL(i, idx),
824 				   veb->stat_offsets_loaded,
825 				   &veb_oes->tc_rx_bytes[i],
826 				   &veb_es->tc_rx_bytes[i]);
827 		i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
828 				   I40E_GLVEBTC_TPCL(i, idx),
829 				   veb->stat_offsets_loaded,
830 				   &veb_oes->tc_tx_packets[i],
831 				   &veb_es->tc_tx_packets[i]);
832 		i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
833 				   I40E_GLVEBTC_TBCL(i, idx),
834 				   veb->stat_offsets_loaded,
835 				   &veb_oes->tc_tx_bytes[i],
836 				   &veb_es->tc_tx_bytes[i]);
837 	}
838 	veb->stat_offsets_loaded = true;
839 }
840 
841 /**
842  * i40e_update_vsi_stats - Update the vsi statistics counters.
843  * @vsi: the VSI to be updated
844  *
845  * There are a few instances where we store the same stat in a
846  * couple of different structs.  This is partly because we have
847  * the netdev stats that need to be filled out, which is slightly
848  * different from the "eth_stats" defined by the chip and used in
849  * VF communications.  We sort it out here.
850  **/
851 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
852 {
853 	u64 rx_page, rx_buf, rx_reuse, rx_alloc, rx_waive, rx_busy;
854 	struct i40e_pf *pf = vsi->back;
855 	struct rtnl_link_stats64 *ons;
856 	struct rtnl_link_stats64 *ns;   /* netdev stats */
857 	struct i40e_eth_stats *oes;
858 	struct i40e_eth_stats *es;     /* device's eth stats */
859 	u64 tx_restart, tx_busy;
860 	struct i40e_ring *p;
861 	u64 bytes, packets;
862 	unsigned int start;
863 	u64 tx_linearize;
864 	u64 tx_force_wb;
865 	u64 tx_stopped;
866 	u64 rx_p, rx_b;
867 	u64 tx_p, tx_b;
868 	u16 q;
869 
870 	if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
871 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
872 		return;
873 
874 	ns = i40e_get_vsi_stats_struct(vsi);
875 	ons = &vsi->net_stats_offsets;
876 	es = &vsi->eth_stats;
877 	oes = &vsi->eth_stats_offsets;
878 
879 	/* Gather up the netdev and vsi stats that the driver collects
880 	 * on the fly during packet processing
881 	 */
882 	rx_b = rx_p = 0;
883 	tx_b = tx_p = 0;
884 	tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
885 	tx_stopped = 0;
886 	rx_page = 0;
887 	rx_buf = 0;
888 	rx_reuse = 0;
889 	rx_alloc = 0;
890 	rx_waive = 0;
891 	rx_busy = 0;
892 	rcu_read_lock();
893 	for (q = 0; q < vsi->num_queue_pairs; q++) {
894 		/* locate Tx ring */
895 		p = READ_ONCE(vsi->tx_rings[q]);
896 		if (!p)
897 			continue;
898 
899 		do {
900 			start = u64_stats_fetch_begin_irq(&p->syncp);
901 			packets = p->stats.packets;
902 			bytes = p->stats.bytes;
903 		} while (u64_stats_fetch_retry_irq(&p->syncp, start));
904 		tx_b += bytes;
905 		tx_p += packets;
906 		tx_restart += p->tx_stats.restart_queue;
907 		tx_busy += p->tx_stats.tx_busy;
908 		tx_linearize += p->tx_stats.tx_linearize;
909 		tx_force_wb += p->tx_stats.tx_force_wb;
910 		tx_stopped += p->tx_stats.tx_stopped;
911 
912 		/* locate Rx ring */
913 		p = READ_ONCE(vsi->rx_rings[q]);
914 		if (!p)
915 			continue;
916 
917 		do {
918 			start = u64_stats_fetch_begin_irq(&p->syncp);
919 			packets = p->stats.packets;
920 			bytes = p->stats.bytes;
921 		} while (u64_stats_fetch_retry_irq(&p->syncp, start));
922 		rx_b += bytes;
923 		rx_p += packets;
924 		rx_buf += p->rx_stats.alloc_buff_failed;
925 		rx_page += p->rx_stats.alloc_page_failed;
926 		rx_reuse += p->rx_stats.page_reuse_count;
927 		rx_alloc += p->rx_stats.page_alloc_count;
928 		rx_waive += p->rx_stats.page_waive_count;
929 		rx_busy += p->rx_stats.page_busy_count;
930 
931 		if (i40e_enabled_xdp_vsi(vsi)) {
932 			/* locate XDP ring */
933 			p = READ_ONCE(vsi->xdp_rings[q]);
934 			if (!p)
935 				continue;
936 
937 			do {
938 				start = u64_stats_fetch_begin_irq(&p->syncp);
939 				packets = p->stats.packets;
940 				bytes = p->stats.bytes;
941 			} while (u64_stats_fetch_retry_irq(&p->syncp, start));
942 			tx_b += bytes;
943 			tx_p += packets;
944 			tx_restart += p->tx_stats.restart_queue;
945 			tx_busy += p->tx_stats.tx_busy;
946 			tx_linearize += p->tx_stats.tx_linearize;
947 			tx_force_wb += p->tx_stats.tx_force_wb;
948 		}
949 	}
950 	rcu_read_unlock();
951 	vsi->tx_restart = tx_restart;
952 	vsi->tx_busy = tx_busy;
953 	vsi->tx_linearize = tx_linearize;
954 	vsi->tx_force_wb = tx_force_wb;
955 	vsi->tx_stopped = tx_stopped;
956 	vsi->rx_page_failed = rx_page;
957 	vsi->rx_buf_failed = rx_buf;
958 	vsi->rx_page_reuse = rx_reuse;
959 	vsi->rx_page_alloc = rx_alloc;
960 	vsi->rx_page_waive = rx_waive;
961 	vsi->rx_page_busy = rx_busy;
962 
963 	ns->rx_packets = rx_p;
964 	ns->rx_bytes = rx_b;
965 	ns->tx_packets = tx_p;
966 	ns->tx_bytes = tx_b;
967 
968 	/* update netdev stats from eth stats */
969 	i40e_update_eth_stats(vsi);
970 	ons->tx_errors = oes->tx_errors;
971 	ns->tx_errors = es->tx_errors;
972 	ons->multicast = oes->rx_multicast;
973 	ns->multicast = es->rx_multicast;
974 	ons->rx_dropped = oes->rx_discards;
975 	ns->rx_dropped = es->rx_discards;
976 	ons->tx_dropped = oes->tx_discards;
977 	ns->tx_dropped = es->tx_discards;
978 
979 	/* pull in a couple PF stats if this is the main vsi */
980 	if (vsi == pf->vsi[pf->lan_vsi]) {
981 		ns->rx_crc_errors = pf->stats.crc_errors;
982 		ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
983 		ns->rx_length_errors = pf->stats.rx_length_errors;
984 	}
985 }
986 
987 /**
988  * i40e_update_pf_stats - Update the PF statistics counters.
989  * @pf: the PF to be updated
990  **/
991 static void i40e_update_pf_stats(struct i40e_pf *pf)
992 {
993 	struct i40e_hw_port_stats *osd = &pf->stats_offsets;
994 	struct i40e_hw_port_stats *nsd = &pf->stats;
995 	struct i40e_hw *hw = &pf->hw;
996 	u32 val;
997 	int i;
998 
999 	i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
1000 			   I40E_GLPRT_GORCL(hw->port),
1001 			   pf->stat_offsets_loaded,
1002 			   &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
1003 	i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
1004 			   I40E_GLPRT_GOTCL(hw->port),
1005 			   pf->stat_offsets_loaded,
1006 			   &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
1007 	i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
1008 			   pf->stat_offsets_loaded,
1009 			   &osd->eth.rx_discards,
1010 			   &nsd->eth.rx_discards);
1011 	i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
1012 			   I40E_GLPRT_UPRCL(hw->port),
1013 			   pf->stat_offsets_loaded,
1014 			   &osd->eth.rx_unicast,
1015 			   &nsd->eth.rx_unicast);
1016 	i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
1017 			   I40E_GLPRT_MPRCL(hw->port),
1018 			   pf->stat_offsets_loaded,
1019 			   &osd->eth.rx_multicast,
1020 			   &nsd->eth.rx_multicast);
1021 	i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
1022 			   I40E_GLPRT_BPRCL(hw->port),
1023 			   pf->stat_offsets_loaded,
1024 			   &osd->eth.rx_broadcast,
1025 			   &nsd->eth.rx_broadcast);
1026 	i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
1027 			   I40E_GLPRT_UPTCL(hw->port),
1028 			   pf->stat_offsets_loaded,
1029 			   &osd->eth.tx_unicast,
1030 			   &nsd->eth.tx_unicast);
1031 	i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
1032 			   I40E_GLPRT_MPTCL(hw->port),
1033 			   pf->stat_offsets_loaded,
1034 			   &osd->eth.tx_multicast,
1035 			   &nsd->eth.tx_multicast);
1036 	i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
1037 			   I40E_GLPRT_BPTCL(hw->port),
1038 			   pf->stat_offsets_loaded,
1039 			   &osd->eth.tx_broadcast,
1040 			   &nsd->eth.tx_broadcast);
1041 
1042 	i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
1043 			   pf->stat_offsets_loaded,
1044 			   &osd->tx_dropped_link_down,
1045 			   &nsd->tx_dropped_link_down);
1046 
1047 	i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
1048 			   pf->stat_offsets_loaded,
1049 			   &osd->crc_errors, &nsd->crc_errors);
1050 
1051 	i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
1052 			   pf->stat_offsets_loaded,
1053 			   &osd->illegal_bytes, &nsd->illegal_bytes);
1054 
1055 	i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
1056 			   pf->stat_offsets_loaded,
1057 			   &osd->mac_local_faults,
1058 			   &nsd->mac_local_faults);
1059 	i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
1060 			   pf->stat_offsets_loaded,
1061 			   &osd->mac_remote_faults,
1062 			   &nsd->mac_remote_faults);
1063 
1064 	i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
1065 			   pf->stat_offsets_loaded,
1066 			   &osd->rx_length_errors,
1067 			   &nsd->rx_length_errors);
1068 
1069 	i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
1070 			   pf->stat_offsets_loaded,
1071 			   &osd->link_xon_rx, &nsd->link_xon_rx);
1072 	i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
1073 			   pf->stat_offsets_loaded,
1074 			   &osd->link_xon_tx, &nsd->link_xon_tx);
1075 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
1076 			   pf->stat_offsets_loaded,
1077 			   &osd->link_xoff_rx, &nsd->link_xoff_rx);
1078 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
1079 			   pf->stat_offsets_loaded,
1080 			   &osd->link_xoff_tx, &nsd->link_xoff_tx);
1081 
1082 	for (i = 0; i < 8; i++) {
1083 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
1084 				   pf->stat_offsets_loaded,
1085 				   &osd->priority_xoff_rx[i],
1086 				   &nsd->priority_xoff_rx[i]);
1087 		i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
1088 				   pf->stat_offsets_loaded,
1089 				   &osd->priority_xon_rx[i],
1090 				   &nsd->priority_xon_rx[i]);
1091 		i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
1092 				   pf->stat_offsets_loaded,
1093 				   &osd->priority_xon_tx[i],
1094 				   &nsd->priority_xon_tx[i]);
1095 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
1096 				   pf->stat_offsets_loaded,
1097 				   &osd->priority_xoff_tx[i],
1098 				   &nsd->priority_xoff_tx[i]);
1099 		i40e_stat_update32(hw,
1100 				   I40E_GLPRT_RXON2OFFCNT(hw->port, i),
1101 				   pf->stat_offsets_loaded,
1102 				   &osd->priority_xon_2_xoff[i],
1103 				   &nsd->priority_xon_2_xoff[i]);
1104 	}
1105 
1106 	i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
1107 			   I40E_GLPRT_PRC64L(hw->port),
1108 			   pf->stat_offsets_loaded,
1109 			   &osd->rx_size_64, &nsd->rx_size_64);
1110 	i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
1111 			   I40E_GLPRT_PRC127L(hw->port),
1112 			   pf->stat_offsets_loaded,
1113 			   &osd->rx_size_127, &nsd->rx_size_127);
1114 	i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
1115 			   I40E_GLPRT_PRC255L(hw->port),
1116 			   pf->stat_offsets_loaded,
1117 			   &osd->rx_size_255, &nsd->rx_size_255);
1118 	i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
1119 			   I40E_GLPRT_PRC511L(hw->port),
1120 			   pf->stat_offsets_loaded,
1121 			   &osd->rx_size_511, &nsd->rx_size_511);
1122 	i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
1123 			   I40E_GLPRT_PRC1023L(hw->port),
1124 			   pf->stat_offsets_loaded,
1125 			   &osd->rx_size_1023, &nsd->rx_size_1023);
1126 	i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
1127 			   I40E_GLPRT_PRC1522L(hw->port),
1128 			   pf->stat_offsets_loaded,
1129 			   &osd->rx_size_1522, &nsd->rx_size_1522);
1130 	i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
1131 			   I40E_GLPRT_PRC9522L(hw->port),
1132 			   pf->stat_offsets_loaded,
1133 			   &osd->rx_size_big, &nsd->rx_size_big);
1134 
1135 	i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1136 			   I40E_GLPRT_PTC64L(hw->port),
1137 			   pf->stat_offsets_loaded,
1138 			   &osd->tx_size_64, &nsd->tx_size_64);
1139 	i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1140 			   I40E_GLPRT_PTC127L(hw->port),
1141 			   pf->stat_offsets_loaded,
1142 			   &osd->tx_size_127, &nsd->tx_size_127);
1143 	i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1144 			   I40E_GLPRT_PTC255L(hw->port),
1145 			   pf->stat_offsets_loaded,
1146 			   &osd->tx_size_255, &nsd->tx_size_255);
1147 	i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1148 			   I40E_GLPRT_PTC511L(hw->port),
1149 			   pf->stat_offsets_loaded,
1150 			   &osd->tx_size_511, &nsd->tx_size_511);
1151 	i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1152 			   I40E_GLPRT_PTC1023L(hw->port),
1153 			   pf->stat_offsets_loaded,
1154 			   &osd->tx_size_1023, &nsd->tx_size_1023);
1155 	i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1156 			   I40E_GLPRT_PTC1522L(hw->port),
1157 			   pf->stat_offsets_loaded,
1158 			   &osd->tx_size_1522, &nsd->tx_size_1522);
1159 	i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1160 			   I40E_GLPRT_PTC9522L(hw->port),
1161 			   pf->stat_offsets_loaded,
1162 			   &osd->tx_size_big, &nsd->tx_size_big);
1163 
1164 	i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1165 			   pf->stat_offsets_loaded,
1166 			   &osd->rx_undersize, &nsd->rx_undersize);
1167 	i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1168 			   pf->stat_offsets_loaded,
1169 			   &osd->rx_fragments, &nsd->rx_fragments);
1170 	i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1171 			   pf->stat_offsets_loaded,
1172 			   &osd->rx_oversize, &nsd->rx_oversize);
1173 	i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1174 			   pf->stat_offsets_loaded,
1175 			   &osd->rx_jabber, &nsd->rx_jabber);
1176 
1177 	/* FDIR stats */
1178 	i40e_stat_update_and_clear32(hw,
1179 			I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(hw->pf_id)),
1180 			&nsd->fd_atr_match);
1181 	i40e_stat_update_and_clear32(hw,
1182 			I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(hw->pf_id)),
1183 			&nsd->fd_sb_match);
1184 	i40e_stat_update_and_clear32(hw,
1185 			I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(hw->pf_id)),
1186 			&nsd->fd_atr_tunnel_match);
1187 
1188 	val = rd32(hw, I40E_PRTPM_EEE_STAT);
1189 	nsd->tx_lpi_status =
1190 		       (val & I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK) >>
1191 			I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_SHIFT;
1192 	nsd->rx_lpi_status =
1193 		       (val & I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK) >>
1194 			I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_SHIFT;
1195 	i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1196 			   pf->stat_offsets_loaded,
1197 			   &osd->tx_lpi_count, &nsd->tx_lpi_count);
1198 	i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1199 			   pf->stat_offsets_loaded,
1200 			   &osd->rx_lpi_count, &nsd->rx_lpi_count);
1201 
1202 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED &&
1203 	    !test_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
1204 		nsd->fd_sb_status = true;
1205 	else
1206 		nsd->fd_sb_status = false;
1207 
1208 	if (pf->flags & I40E_FLAG_FD_ATR_ENABLED &&
1209 	    !test_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
1210 		nsd->fd_atr_status = true;
1211 	else
1212 		nsd->fd_atr_status = false;
1213 
1214 	pf->stat_offsets_loaded = true;
1215 }
1216 
1217 /**
1218  * i40e_update_stats - Update the various statistics counters.
1219  * @vsi: the VSI to be updated
1220  *
1221  * Update the various stats for this VSI and its related entities.
1222  **/
1223 void i40e_update_stats(struct i40e_vsi *vsi)
1224 {
1225 	struct i40e_pf *pf = vsi->back;
1226 
1227 	if (vsi == pf->vsi[pf->lan_vsi])
1228 		i40e_update_pf_stats(pf);
1229 
1230 	i40e_update_vsi_stats(vsi);
1231 }
1232 
1233 /**
1234  * i40e_count_filters - counts VSI mac filters
1235  * @vsi: the VSI to be searched
1236  *
1237  * Returns count of mac filters
1238  **/
1239 int i40e_count_filters(struct i40e_vsi *vsi)
1240 {
1241 	struct i40e_mac_filter *f;
1242 	struct hlist_node *h;
1243 	int bkt;
1244 	int cnt = 0;
1245 
1246 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
1247 		++cnt;
1248 
1249 	return cnt;
1250 }
1251 
1252 /**
1253  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1254  * @vsi: the VSI to be searched
1255  * @macaddr: the MAC address
1256  * @vlan: the vlan
1257  *
1258  * Returns ptr to the filter object or NULL
1259  **/
1260 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1261 						const u8 *macaddr, s16 vlan)
1262 {
1263 	struct i40e_mac_filter *f;
1264 	u64 key;
1265 
1266 	if (!vsi || !macaddr)
1267 		return NULL;
1268 
1269 	key = i40e_addr_to_hkey(macaddr);
1270 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1271 		if ((ether_addr_equal(macaddr, f->macaddr)) &&
1272 		    (vlan == f->vlan))
1273 			return f;
1274 	}
1275 	return NULL;
1276 }
1277 
1278 /**
1279  * i40e_find_mac - Find a mac addr in the macvlan filters list
1280  * @vsi: the VSI to be searched
1281  * @macaddr: the MAC address we are searching for
1282  *
1283  * Returns the first filter with the provided MAC address or NULL if
1284  * MAC address was not found
1285  **/
1286 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1287 {
1288 	struct i40e_mac_filter *f;
1289 	u64 key;
1290 
1291 	if (!vsi || !macaddr)
1292 		return NULL;
1293 
1294 	key = i40e_addr_to_hkey(macaddr);
1295 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1296 		if ((ether_addr_equal(macaddr, f->macaddr)))
1297 			return f;
1298 	}
1299 	return NULL;
1300 }
1301 
1302 /**
1303  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1304  * @vsi: the VSI to be searched
1305  *
1306  * Returns true if VSI is in vlan mode or false otherwise
1307  **/
1308 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1309 {
1310 	/* If we have a PVID, always operate in VLAN mode */
1311 	if (vsi->info.pvid)
1312 		return true;
1313 
1314 	/* We need to operate in VLAN mode whenever we have any filters with
1315 	 * a VLAN other than I40E_VLAN_ALL. We could check the table each
1316 	 * time, incurring search cost repeatedly. However, we can notice two
1317 	 * things:
1318 	 *
1319 	 * 1) the only place where we can gain a VLAN filter is in
1320 	 *    i40e_add_filter.
1321 	 *
1322 	 * 2) the only place where filters are actually removed is in
1323 	 *    i40e_sync_filters_subtask.
1324 	 *
1325 	 * Thus, we can simply use a boolean value, has_vlan_filters which we
1326 	 * will set to true when we add a VLAN filter in i40e_add_filter. Then
1327 	 * we have to perform the full search after deleting filters in
1328 	 * i40e_sync_filters_subtask, but we already have to search
1329 	 * filters here and can perform the check at the same time. This
1330 	 * results in avoiding embedding a loop for VLAN mode inside another
1331 	 * loop over all the filters, and should maintain correctness as noted
1332 	 * above.
1333 	 */
1334 	return vsi->has_vlan_filter;
1335 }
1336 
1337 /**
1338  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1339  * @vsi: the VSI to configure
1340  * @tmp_add_list: list of filters ready to be added
1341  * @tmp_del_list: list of filters ready to be deleted
1342  * @vlan_filters: the number of active VLAN filters
1343  *
1344  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1345  * behave as expected. If we have any active VLAN filters remaining or about
1346  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1347  * so that they only match against untagged traffic. If we no longer have any
1348  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1349  * so that they match against both tagged and untagged traffic. In this way,
1350  * we ensure that we correctly receive the desired traffic. This ensures that
1351  * when we have an active VLAN we will receive only untagged traffic and
1352  * traffic matching active VLANs. If we have no active VLANs then we will
1353  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1354  *
1355  * Finally, in a similar fashion, this function also corrects filters when
1356  * there is an active PVID assigned to this VSI.
1357  *
1358  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1359  *
1360  * This function is only expected to be called from within
1361  * i40e_sync_vsi_filters.
1362  *
1363  * NOTE: This function expects to be called while under the
1364  * mac_filter_hash_lock
1365  */
1366 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1367 					 struct hlist_head *tmp_add_list,
1368 					 struct hlist_head *tmp_del_list,
1369 					 int vlan_filters)
1370 {
1371 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1372 	struct i40e_mac_filter *f, *add_head;
1373 	struct i40e_new_mac_filter *new;
1374 	struct hlist_node *h;
1375 	int bkt, new_vlan;
1376 
1377 	/* To determine if a particular filter needs to be replaced we
1378 	 * have the three following conditions:
1379 	 *
1380 	 * a) if we have a PVID assigned, then all filters which are
1381 	 *    not marked as VLAN=PVID must be replaced with filters that
1382 	 *    are.
1383 	 * b) otherwise, if we have any active VLANS, all filters
1384 	 *    which are marked as VLAN=-1 must be replaced with
1385 	 *    filters marked as VLAN=0
1386 	 * c) finally, if we do not have any active VLANS, all filters
1387 	 *    which are marked as VLAN=0 must be replaced with filters
1388 	 *    marked as VLAN=-1
1389 	 */
1390 
1391 	/* Update the filters about to be added in place */
1392 	hlist_for_each_entry(new, tmp_add_list, hlist) {
1393 		if (pvid && new->f->vlan != pvid)
1394 			new->f->vlan = pvid;
1395 		else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1396 			new->f->vlan = 0;
1397 		else if (!vlan_filters && new->f->vlan == 0)
1398 			new->f->vlan = I40E_VLAN_ANY;
1399 	}
1400 
1401 	/* Update the remaining active filters */
1402 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1403 		/* Combine the checks for whether a filter needs to be changed
1404 		 * and then determine the new VLAN inside the if block, in
1405 		 * order to avoid duplicating code for adding the new filter
1406 		 * then deleting the old filter.
1407 		 */
1408 		if ((pvid && f->vlan != pvid) ||
1409 		    (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1410 		    (!vlan_filters && f->vlan == 0)) {
1411 			/* Determine the new vlan we will be adding */
1412 			if (pvid)
1413 				new_vlan = pvid;
1414 			else if (vlan_filters)
1415 				new_vlan = 0;
1416 			else
1417 				new_vlan = I40E_VLAN_ANY;
1418 
1419 			/* Create the new filter */
1420 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1421 			if (!add_head)
1422 				return -ENOMEM;
1423 
1424 			/* Create a temporary i40e_new_mac_filter */
1425 			new = kzalloc(sizeof(*new), GFP_ATOMIC);
1426 			if (!new)
1427 				return -ENOMEM;
1428 
1429 			new->f = add_head;
1430 			new->state = add_head->state;
1431 
1432 			/* Add the new filter to the tmp list */
1433 			hlist_add_head(&new->hlist, tmp_add_list);
1434 
1435 			/* Put the original filter into the delete list */
1436 			f->state = I40E_FILTER_REMOVE;
1437 			hash_del(&f->hlist);
1438 			hlist_add_head(&f->hlist, tmp_del_list);
1439 		}
1440 	}
1441 
1442 	vsi->has_vlan_filter = !!vlan_filters;
1443 
1444 	return 0;
1445 }
1446 
1447 /**
1448  * i40e_get_vf_new_vlan - Get new vlan id on a vf
1449  * @vsi: the vsi to configure
1450  * @new_mac: new mac filter to be added
1451  * @f: existing mac filter, replaced with new_mac->f if new_mac is not NULL
1452  * @vlan_filters: the number of active VLAN filters
1453  * @trusted: flag if the VF is trusted
1454  *
1455  * Get new VLAN id based on current VLAN filters, trust, PVID
1456  * and vf-vlan-prune-disable flag.
1457  *
1458  * Returns the value of the new vlan filter or
1459  * the old value if no new filter is needed.
1460  */
1461 static s16 i40e_get_vf_new_vlan(struct i40e_vsi *vsi,
1462 				struct i40e_new_mac_filter *new_mac,
1463 				struct i40e_mac_filter *f,
1464 				int vlan_filters,
1465 				bool trusted)
1466 {
1467 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1468 	struct i40e_pf *pf = vsi->back;
1469 	bool is_any;
1470 
1471 	if (new_mac)
1472 		f = new_mac->f;
1473 
1474 	if (pvid && f->vlan != pvid)
1475 		return pvid;
1476 
1477 	is_any = (trusted ||
1478 		  !(pf->flags & I40E_FLAG_VF_VLAN_PRUNING));
1479 
1480 	if ((vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1481 	    (!is_any && !vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1482 	    (is_any && !vlan_filters && f->vlan == 0)) {
1483 		if (is_any)
1484 			return I40E_VLAN_ANY;
1485 		else
1486 			return 0;
1487 	}
1488 
1489 	return f->vlan;
1490 }
1491 
1492 /**
1493  * i40e_correct_vf_mac_vlan_filters - Correct non-VLAN VF filters if necessary
1494  * @vsi: the vsi to configure
1495  * @tmp_add_list: list of filters ready to be added
1496  * @tmp_del_list: list of filters ready to be deleted
1497  * @vlan_filters: the number of active VLAN filters
1498  * @trusted: flag if the VF is trusted
1499  *
1500  * Correct VF VLAN filters based on current VLAN filters, trust, PVID
1501  * and vf-vlan-prune-disable flag.
1502  *
1503  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1504  *
1505  * This function is only expected to be called from within
1506  * i40e_sync_vsi_filters.
1507  *
1508  * NOTE: This function expects to be called while under the
1509  * mac_filter_hash_lock
1510  */
1511 static int i40e_correct_vf_mac_vlan_filters(struct i40e_vsi *vsi,
1512 					    struct hlist_head *tmp_add_list,
1513 					    struct hlist_head *tmp_del_list,
1514 					    int vlan_filters,
1515 					    bool trusted)
1516 {
1517 	struct i40e_mac_filter *f, *add_head;
1518 	struct i40e_new_mac_filter *new_mac;
1519 	struct hlist_node *h;
1520 	int bkt, new_vlan;
1521 
1522 	hlist_for_each_entry(new_mac, tmp_add_list, hlist) {
1523 		new_mac->f->vlan = i40e_get_vf_new_vlan(vsi, new_mac, NULL,
1524 							vlan_filters, trusted);
1525 	}
1526 
1527 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1528 		new_vlan = i40e_get_vf_new_vlan(vsi, NULL, f, vlan_filters,
1529 						trusted);
1530 		if (new_vlan != f->vlan) {
1531 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1532 			if (!add_head)
1533 				return -ENOMEM;
1534 			/* Create a temporary i40e_new_mac_filter */
1535 			new_mac = kzalloc(sizeof(*new_mac), GFP_ATOMIC);
1536 			if (!new_mac)
1537 				return -ENOMEM;
1538 			new_mac->f = add_head;
1539 			new_mac->state = add_head->state;
1540 
1541 			/* Add the new filter to the tmp list */
1542 			hlist_add_head(&new_mac->hlist, tmp_add_list);
1543 
1544 			/* Put the original filter into the delete list */
1545 			f->state = I40E_FILTER_REMOVE;
1546 			hash_del(&f->hlist);
1547 			hlist_add_head(&f->hlist, tmp_del_list);
1548 		}
1549 	}
1550 
1551 	vsi->has_vlan_filter = !!vlan_filters;
1552 	return 0;
1553 }
1554 
1555 /**
1556  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1557  * @vsi: the PF Main VSI - inappropriate for any other VSI
1558  * @macaddr: the MAC address
1559  *
1560  * Remove whatever filter the firmware set up so the driver can manage
1561  * its own filtering intelligently.
1562  **/
1563 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1564 {
1565 	struct i40e_aqc_remove_macvlan_element_data element;
1566 	struct i40e_pf *pf = vsi->back;
1567 
1568 	/* Only appropriate for the PF main VSI */
1569 	if (vsi->type != I40E_VSI_MAIN)
1570 		return;
1571 
1572 	memset(&element, 0, sizeof(element));
1573 	ether_addr_copy(element.mac_addr, macaddr);
1574 	element.vlan_tag = 0;
1575 	/* Ignore error returns, some firmware does it this way... */
1576 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1577 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1578 
1579 	memset(&element, 0, sizeof(element));
1580 	ether_addr_copy(element.mac_addr, macaddr);
1581 	element.vlan_tag = 0;
1582 	/* ...and some firmware does it this way. */
1583 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1584 			I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1585 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1586 }
1587 
1588 /**
1589  * i40e_add_filter - Add a mac/vlan filter to the VSI
1590  * @vsi: the VSI to be searched
1591  * @macaddr: the MAC address
1592  * @vlan: the vlan
1593  *
1594  * Returns ptr to the filter object or NULL when no memory available.
1595  *
1596  * NOTE: This function is expected to be called with mac_filter_hash_lock
1597  * being held.
1598  **/
1599 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1600 					const u8 *macaddr, s16 vlan)
1601 {
1602 	struct i40e_mac_filter *f;
1603 	u64 key;
1604 
1605 	if (!vsi || !macaddr)
1606 		return NULL;
1607 
1608 	f = i40e_find_filter(vsi, macaddr, vlan);
1609 	if (!f) {
1610 		f = kzalloc(sizeof(*f), GFP_ATOMIC);
1611 		if (!f)
1612 			return NULL;
1613 
1614 		/* Update the boolean indicating if we need to function in
1615 		 * VLAN mode.
1616 		 */
1617 		if (vlan >= 0)
1618 			vsi->has_vlan_filter = true;
1619 
1620 		ether_addr_copy(f->macaddr, macaddr);
1621 		f->vlan = vlan;
1622 		f->state = I40E_FILTER_NEW;
1623 		INIT_HLIST_NODE(&f->hlist);
1624 
1625 		key = i40e_addr_to_hkey(macaddr);
1626 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
1627 
1628 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1629 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1630 	}
1631 
1632 	/* If we're asked to add a filter that has been marked for removal, it
1633 	 * is safe to simply restore it to active state. __i40e_del_filter
1634 	 * will have simply deleted any filters which were previously marked
1635 	 * NEW or FAILED, so if it is currently marked REMOVE it must have
1636 	 * previously been ACTIVE. Since we haven't yet run the sync filters
1637 	 * task, just restore this filter to the ACTIVE state so that the
1638 	 * sync task leaves it in place
1639 	 */
1640 	if (f->state == I40E_FILTER_REMOVE)
1641 		f->state = I40E_FILTER_ACTIVE;
1642 
1643 	return f;
1644 }
1645 
1646 /**
1647  * __i40e_del_filter - Remove a specific filter from the VSI
1648  * @vsi: VSI to remove from
1649  * @f: the filter to remove from the list
1650  *
1651  * This function should be called instead of i40e_del_filter only if you know
1652  * the exact filter you will remove already, such as via i40e_find_filter or
1653  * i40e_find_mac.
1654  *
1655  * NOTE: This function is expected to be called with mac_filter_hash_lock
1656  * being held.
1657  * ANOTHER NOTE: This function MUST be called from within the context of
1658  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1659  * instead of list_for_each_entry().
1660  **/
1661 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1662 {
1663 	if (!f)
1664 		return;
1665 
1666 	/* If the filter was never added to firmware then we can just delete it
1667 	 * directly and we don't want to set the status to remove or else an
1668 	 * admin queue command will unnecessarily fire.
1669 	 */
1670 	if ((f->state == I40E_FILTER_FAILED) ||
1671 	    (f->state == I40E_FILTER_NEW)) {
1672 		hash_del(&f->hlist);
1673 		kfree(f);
1674 	} else {
1675 		f->state = I40E_FILTER_REMOVE;
1676 	}
1677 
1678 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1679 	set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1680 }
1681 
1682 /**
1683  * i40e_del_filter - Remove a MAC/VLAN filter from the VSI
1684  * @vsi: the VSI to be searched
1685  * @macaddr: the MAC address
1686  * @vlan: the VLAN
1687  *
1688  * NOTE: This function is expected to be called with mac_filter_hash_lock
1689  * being held.
1690  * ANOTHER NOTE: This function MUST be called from within the context of
1691  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1692  * instead of list_for_each_entry().
1693  **/
1694 void i40e_del_filter(struct i40e_vsi *vsi, const u8 *macaddr, s16 vlan)
1695 {
1696 	struct i40e_mac_filter *f;
1697 
1698 	if (!vsi || !macaddr)
1699 		return;
1700 
1701 	f = i40e_find_filter(vsi, macaddr, vlan);
1702 	__i40e_del_filter(vsi, f);
1703 }
1704 
1705 /**
1706  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1707  * @vsi: the VSI to be searched
1708  * @macaddr: the mac address to be filtered
1709  *
1710  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1711  * go through all the macvlan filters and add a macvlan filter for each
1712  * unique vlan that already exists. If a PVID has been assigned, instead only
1713  * add the macaddr to that VLAN.
1714  *
1715  * Returns last filter added on success, else NULL
1716  **/
1717 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1718 					    const u8 *macaddr)
1719 {
1720 	struct i40e_mac_filter *f, *add = NULL;
1721 	struct hlist_node *h;
1722 	int bkt;
1723 
1724 	if (vsi->info.pvid)
1725 		return i40e_add_filter(vsi, macaddr,
1726 				       le16_to_cpu(vsi->info.pvid));
1727 
1728 	if (!i40e_is_vsi_in_vlan(vsi))
1729 		return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1730 
1731 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1732 		if (f->state == I40E_FILTER_REMOVE)
1733 			continue;
1734 		add = i40e_add_filter(vsi, macaddr, f->vlan);
1735 		if (!add)
1736 			return NULL;
1737 	}
1738 
1739 	return add;
1740 }
1741 
1742 /**
1743  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1744  * @vsi: the VSI to be searched
1745  * @macaddr: the mac address to be removed
1746  *
1747  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1748  * associated with.
1749  *
1750  * Returns 0 for success, or error
1751  **/
1752 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1753 {
1754 	struct i40e_mac_filter *f;
1755 	struct hlist_node *h;
1756 	bool found = false;
1757 	int bkt;
1758 
1759 	lockdep_assert_held(&vsi->mac_filter_hash_lock);
1760 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1761 		if (ether_addr_equal(macaddr, f->macaddr)) {
1762 			__i40e_del_filter(vsi, f);
1763 			found = true;
1764 		}
1765 	}
1766 
1767 	if (found)
1768 		return 0;
1769 	else
1770 		return -ENOENT;
1771 }
1772 
1773 /**
1774  * i40e_set_mac - NDO callback to set mac address
1775  * @netdev: network interface device structure
1776  * @p: pointer to an address structure
1777  *
1778  * Returns 0 on success, negative on failure
1779  **/
1780 static int i40e_set_mac(struct net_device *netdev, void *p)
1781 {
1782 	struct i40e_netdev_priv *np = netdev_priv(netdev);
1783 	struct i40e_vsi *vsi = np->vsi;
1784 	struct i40e_pf *pf = vsi->back;
1785 	struct i40e_hw *hw = &pf->hw;
1786 	struct sockaddr *addr = p;
1787 
1788 	if (!is_valid_ether_addr(addr->sa_data))
1789 		return -EADDRNOTAVAIL;
1790 
1791 	if (ether_addr_equal(netdev->dev_addr, addr->sa_data)) {
1792 		netdev_info(netdev, "already using mac address %pM\n",
1793 			    addr->sa_data);
1794 		return 0;
1795 	}
1796 
1797 	if (test_bit(__I40E_DOWN, pf->state) ||
1798 	    test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1799 		return -EADDRNOTAVAIL;
1800 
1801 	if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1802 		netdev_info(netdev, "returning to hw mac address %pM\n",
1803 			    hw->mac.addr);
1804 	else
1805 		netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1806 
1807 	/* Copy the address first, so that we avoid a possible race with
1808 	 * .set_rx_mode().
1809 	 * - Remove old address from MAC filter
1810 	 * - Copy new address
1811 	 * - Add new address to MAC filter
1812 	 */
1813 	spin_lock_bh(&vsi->mac_filter_hash_lock);
1814 	i40e_del_mac_filter(vsi, netdev->dev_addr);
1815 	eth_hw_addr_set(netdev, addr->sa_data);
1816 	i40e_add_mac_filter(vsi, netdev->dev_addr);
1817 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
1818 
1819 	if (vsi->type == I40E_VSI_MAIN) {
1820 		i40e_status ret;
1821 
1822 		ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1823 						addr->sa_data, NULL);
1824 		if (ret)
1825 			netdev_info(netdev, "Ignoring error from firmware on LAA update, status %s, AQ ret %s\n",
1826 				    i40e_stat_str(hw, ret),
1827 				    i40e_aq_str(hw, hw->aq.asq_last_status));
1828 	}
1829 
1830 	/* schedule our worker thread which will take care of
1831 	 * applying the new filter changes
1832 	 */
1833 	i40e_service_event_schedule(pf);
1834 	return 0;
1835 }
1836 
1837 /**
1838  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1839  * @vsi: vsi structure
1840  * @seed: RSS hash seed
1841  * @lut: pointer to lookup table of lut_size
1842  * @lut_size: size of the lookup table
1843  **/
1844 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1845 			      u8 *lut, u16 lut_size)
1846 {
1847 	struct i40e_pf *pf = vsi->back;
1848 	struct i40e_hw *hw = &pf->hw;
1849 	int ret = 0;
1850 
1851 	if (seed) {
1852 		struct i40e_aqc_get_set_rss_key_data *seed_dw =
1853 			(struct i40e_aqc_get_set_rss_key_data *)seed;
1854 		ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1855 		if (ret) {
1856 			dev_info(&pf->pdev->dev,
1857 				 "Cannot set RSS key, err %s aq_err %s\n",
1858 				 i40e_stat_str(hw, ret),
1859 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1860 			return ret;
1861 		}
1862 	}
1863 	if (lut) {
1864 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
1865 
1866 		ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1867 		if (ret) {
1868 			dev_info(&pf->pdev->dev,
1869 				 "Cannot set RSS lut, err %s aq_err %s\n",
1870 				 i40e_stat_str(hw, ret),
1871 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1872 			return ret;
1873 		}
1874 	}
1875 	return ret;
1876 }
1877 
1878 /**
1879  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1880  * @vsi: VSI structure
1881  **/
1882 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1883 {
1884 	struct i40e_pf *pf = vsi->back;
1885 	u8 seed[I40E_HKEY_ARRAY_SIZE];
1886 	u8 *lut;
1887 	int ret;
1888 
1889 	if (!(pf->hw_features & I40E_HW_RSS_AQ_CAPABLE))
1890 		return 0;
1891 	if (!vsi->rss_size)
1892 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
1893 				      vsi->num_queue_pairs);
1894 	if (!vsi->rss_size)
1895 		return -EINVAL;
1896 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1897 	if (!lut)
1898 		return -ENOMEM;
1899 
1900 	/* Use the user configured hash keys and lookup table if there is one,
1901 	 * otherwise use default
1902 	 */
1903 	if (vsi->rss_lut_user)
1904 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1905 	else
1906 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1907 	if (vsi->rss_hkey_user)
1908 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1909 	else
1910 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1911 	ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1912 	kfree(lut);
1913 	return ret;
1914 }
1915 
1916 /**
1917  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1918  * @vsi: the VSI being configured,
1919  * @ctxt: VSI context structure
1920  * @enabled_tc: number of traffic classes to enable
1921  *
1922  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1923  **/
1924 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1925 					   struct i40e_vsi_context *ctxt,
1926 					   u8 enabled_tc)
1927 {
1928 	u16 qcount = 0, max_qcount, qmap, sections = 0;
1929 	int i, override_q, pow, num_qps, ret;
1930 	u8 netdev_tc = 0, offset = 0;
1931 
1932 	if (vsi->type != I40E_VSI_MAIN)
1933 		return -EINVAL;
1934 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1935 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1936 	vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1937 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1938 	num_qps = vsi->mqprio_qopt.qopt.count[0];
1939 
1940 	/* find the next higher power-of-2 of num queue pairs */
1941 	pow = ilog2(num_qps);
1942 	if (!is_power_of_2(num_qps))
1943 		pow++;
1944 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1945 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1946 
1947 	/* Setup queue offset/count for all TCs for given VSI */
1948 	max_qcount = vsi->mqprio_qopt.qopt.count[0];
1949 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1950 		/* See if the given TC is enabled for the given VSI */
1951 		if (vsi->tc_config.enabled_tc & BIT(i)) {
1952 			offset = vsi->mqprio_qopt.qopt.offset[i];
1953 			qcount = vsi->mqprio_qopt.qopt.count[i];
1954 			if (qcount > max_qcount)
1955 				max_qcount = qcount;
1956 			vsi->tc_config.tc_info[i].qoffset = offset;
1957 			vsi->tc_config.tc_info[i].qcount = qcount;
1958 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1959 		} else {
1960 			/* TC is not enabled so set the offset to
1961 			 * default queue and allocate one queue
1962 			 * for the given TC.
1963 			 */
1964 			vsi->tc_config.tc_info[i].qoffset = 0;
1965 			vsi->tc_config.tc_info[i].qcount = 1;
1966 			vsi->tc_config.tc_info[i].netdev_tc = 0;
1967 		}
1968 	}
1969 
1970 	/* Set actual Tx/Rx queue pairs */
1971 	vsi->num_queue_pairs = offset + qcount;
1972 
1973 	/* Setup queue TC[0].qmap for given VSI context */
1974 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1975 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1976 	ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1977 	ctxt->info.valid_sections |= cpu_to_le16(sections);
1978 
1979 	/* Reconfigure RSS for main VSI with max queue count */
1980 	vsi->rss_size = max_qcount;
1981 	ret = i40e_vsi_config_rss(vsi);
1982 	if (ret) {
1983 		dev_info(&vsi->back->pdev->dev,
1984 			 "Failed to reconfig rss for num_queues (%u)\n",
1985 			 max_qcount);
1986 		return ret;
1987 	}
1988 	vsi->reconfig_rss = true;
1989 	dev_dbg(&vsi->back->pdev->dev,
1990 		"Reconfigured rss with num_queues (%u)\n", max_qcount);
1991 
1992 	/* Find queue count available for channel VSIs and starting offset
1993 	 * for channel VSIs
1994 	 */
1995 	override_q = vsi->mqprio_qopt.qopt.count[0];
1996 	if (override_q && override_q < vsi->num_queue_pairs) {
1997 		vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
1998 		vsi->next_base_queue = override_q;
1999 	}
2000 	return 0;
2001 }
2002 
2003 /**
2004  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
2005  * @vsi: the VSI being setup
2006  * @ctxt: VSI context structure
2007  * @enabled_tc: Enabled TCs bitmap
2008  * @is_add: True if called before Add VSI
2009  *
2010  * Setup VSI queue mapping for enabled traffic classes.
2011  **/
2012 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
2013 				     struct i40e_vsi_context *ctxt,
2014 				     u8 enabled_tc,
2015 				     bool is_add)
2016 {
2017 	struct i40e_pf *pf = vsi->back;
2018 	u16 num_tc_qps = 0;
2019 	u16 sections = 0;
2020 	u8 netdev_tc = 0;
2021 	u16 numtc = 1;
2022 	u16 qcount;
2023 	u8 offset;
2024 	u16 qmap;
2025 	int i;
2026 
2027 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
2028 	offset = 0;
2029 	/* zero out queue mapping, it will get updated on the end of the function */
2030 	memset(ctxt->info.queue_mapping, 0, sizeof(ctxt->info.queue_mapping));
2031 
2032 	if (vsi->type == I40E_VSI_MAIN) {
2033 		/* This code helps add more queue to the VSI if we have
2034 		 * more cores than RSS can support, the higher cores will
2035 		 * be served by ATR or other filters. Furthermore, the
2036 		 * non-zero req_queue_pairs says that user requested a new
2037 		 * queue count via ethtool's set_channels, so use this
2038 		 * value for queues distribution across traffic classes
2039 		 * We need at least one queue pair for the interface
2040 		 * to be usable as we see in else statement.
2041 		 */
2042 		if (vsi->req_queue_pairs > 0)
2043 			vsi->num_queue_pairs = vsi->req_queue_pairs;
2044 		else if (pf->flags & I40E_FLAG_MSIX_ENABLED)
2045 			vsi->num_queue_pairs = pf->num_lan_msix;
2046 		else
2047 			vsi->num_queue_pairs = 1;
2048 	}
2049 
2050 	/* Number of queues per enabled TC */
2051 	if (vsi->type == I40E_VSI_MAIN ||
2052 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs != 0))
2053 		num_tc_qps = vsi->num_queue_pairs;
2054 	else
2055 		num_tc_qps = vsi->alloc_queue_pairs;
2056 
2057 	if (enabled_tc && (vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
2058 		/* Find numtc from enabled TC bitmap */
2059 		for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2060 			if (enabled_tc & BIT(i)) /* TC is enabled */
2061 				numtc++;
2062 		}
2063 		if (!numtc) {
2064 			dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
2065 			numtc = 1;
2066 		}
2067 		num_tc_qps = num_tc_qps / numtc;
2068 		num_tc_qps = min_t(int, num_tc_qps,
2069 				   i40e_pf_get_max_q_per_tc(pf));
2070 	}
2071 
2072 	vsi->tc_config.numtc = numtc;
2073 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
2074 
2075 	/* Do not allow use more TC queue pairs than MSI-X vectors exist */
2076 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
2077 		num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
2078 
2079 	/* Setup queue offset/count for all TCs for given VSI */
2080 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2081 		/* See if the given TC is enabled for the given VSI */
2082 		if (vsi->tc_config.enabled_tc & BIT(i)) {
2083 			/* TC is enabled */
2084 			int pow, num_qps;
2085 
2086 			switch (vsi->type) {
2087 			case I40E_VSI_MAIN:
2088 				if (!(pf->flags & (I40E_FLAG_FD_SB_ENABLED |
2089 				    I40E_FLAG_FD_ATR_ENABLED)) ||
2090 				    vsi->tc_config.enabled_tc != 1) {
2091 					qcount = min_t(int, pf->alloc_rss_size,
2092 						       num_tc_qps);
2093 					break;
2094 				}
2095 				fallthrough;
2096 			case I40E_VSI_FDIR:
2097 			case I40E_VSI_SRIOV:
2098 			case I40E_VSI_VMDQ2:
2099 			default:
2100 				qcount = num_tc_qps;
2101 				WARN_ON(i != 0);
2102 				break;
2103 			}
2104 			vsi->tc_config.tc_info[i].qoffset = offset;
2105 			vsi->tc_config.tc_info[i].qcount = qcount;
2106 
2107 			/* find the next higher power-of-2 of num queue pairs */
2108 			num_qps = qcount;
2109 			pow = 0;
2110 			while (num_qps && (BIT_ULL(pow) < qcount)) {
2111 				pow++;
2112 				num_qps >>= 1;
2113 			}
2114 
2115 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
2116 			qmap =
2117 			    (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
2118 			    (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
2119 
2120 			offset += qcount;
2121 		} else {
2122 			/* TC is not enabled so set the offset to
2123 			 * default queue and allocate one queue
2124 			 * for the given TC.
2125 			 */
2126 			vsi->tc_config.tc_info[i].qoffset = 0;
2127 			vsi->tc_config.tc_info[i].qcount = 1;
2128 			vsi->tc_config.tc_info[i].netdev_tc = 0;
2129 
2130 			qmap = 0;
2131 		}
2132 		ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
2133 	}
2134 	/* Do not change previously set num_queue_pairs for PFs and VFs*/
2135 	if ((vsi->type == I40E_VSI_MAIN && numtc != 1) ||
2136 	    (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs == 0) ||
2137 	    (vsi->type != I40E_VSI_MAIN && vsi->type != I40E_VSI_SRIOV))
2138 		vsi->num_queue_pairs = offset;
2139 
2140 	/* Scheduler section valid can only be set for ADD VSI */
2141 	if (is_add) {
2142 		sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
2143 
2144 		ctxt->info.up_enable_bits = enabled_tc;
2145 	}
2146 	if (vsi->type == I40E_VSI_SRIOV) {
2147 		ctxt->info.mapping_flags |=
2148 				     cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
2149 		for (i = 0; i < vsi->num_queue_pairs; i++)
2150 			ctxt->info.queue_mapping[i] =
2151 					       cpu_to_le16(vsi->base_queue + i);
2152 	} else {
2153 		ctxt->info.mapping_flags |=
2154 					cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
2155 		ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
2156 	}
2157 	ctxt->info.valid_sections |= cpu_to_le16(sections);
2158 }
2159 
2160 /**
2161  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
2162  * @netdev: the netdevice
2163  * @addr: address to add
2164  *
2165  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
2166  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2167  */
2168 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
2169 {
2170 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2171 	struct i40e_vsi *vsi = np->vsi;
2172 
2173 	if (i40e_add_mac_filter(vsi, addr))
2174 		return 0;
2175 	else
2176 		return -ENOMEM;
2177 }
2178 
2179 /**
2180  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
2181  * @netdev: the netdevice
2182  * @addr: address to add
2183  *
2184  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
2185  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2186  */
2187 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
2188 {
2189 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2190 	struct i40e_vsi *vsi = np->vsi;
2191 
2192 	/* Under some circumstances, we might receive a request to delete
2193 	 * our own device address from our uc list. Because we store the
2194 	 * device address in the VSI's MAC/VLAN filter list, we need to ignore
2195 	 * such requests and not delete our device address from this list.
2196 	 */
2197 	if (ether_addr_equal(addr, netdev->dev_addr))
2198 		return 0;
2199 
2200 	i40e_del_mac_filter(vsi, addr);
2201 
2202 	return 0;
2203 }
2204 
2205 /**
2206  * i40e_set_rx_mode - NDO callback to set the netdev filters
2207  * @netdev: network interface device structure
2208  **/
2209 static void i40e_set_rx_mode(struct net_device *netdev)
2210 {
2211 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2212 	struct i40e_vsi *vsi = np->vsi;
2213 
2214 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2215 
2216 	__dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2217 	__dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2218 
2219 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2220 
2221 	/* check for other flag changes */
2222 	if (vsi->current_netdev_flags != vsi->netdev->flags) {
2223 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2224 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
2225 	}
2226 }
2227 
2228 /**
2229  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
2230  * @vsi: Pointer to VSI struct
2231  * @from: Pointer to list which contains MAC filter entries - changes to
2232  *        those entries needs to be undone.
2233  *
2234  * MAC filter entries from this list were slated for deletion.
2235  **/
2236 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
2237 					 struct hlist_head *from)
2238 {
2239 	struct i40e_mac_filter *f;
2240 	struct hlist_node *h;
2241 
2242 	hlist_for_each_entry_safe(f, h, from, hlist) {
2243 		u64 key = i40e_addr_to_hkey(f->macaddr);
2244 
2245 		/* Move the element back into MAC filter list*/
2246 		hlist_del(&f->hlist);
2247 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
2248 	}
2249 }
2250 
2251 /**
2252  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
2253  * @vsi: Pointer to vsi struct
2254  * @from: Pointer to list which contains MAC filter entries - changes to
2255  *        those entries needs to be undone.
2256  *
2257  * MAC filter entries from this list were slated for addition.
2258  **/
2259 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
2260 					 struct hlist_head *from)
2261 {
2262 	struct i40e_new_mac_filter *new;
2263 	struct hlist_node *h;
2264 
2265 	hlist_for_each_entry_safe(new, h, from, hlist) {
2266 		/* We can simply free the wrapper structure */
2267 		hlist_del(&new->hlist);
2268 		netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2269 		kfree(new);
2270 	}
2271 }
2272 
2273 /**
2274  * i40e_next_filter - Get the next non-broadcast filter from a list
2275  * @next: pointer to filter in list
2276  *
2277  * Returns the next non-broadcast filter in the list. Required so that we
2278  * ignore broadcast filters within the list, since these are not handled via
2279  * the normal firmware update path.
2280  */
2281 static
2282 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2283 {
2284 	hlist_for_each_entry_continue(next, hlist) {
2285 		if (!is_broadcast_ether_addr(next->f->macaddr))
2286 			return next;
2287 	}
2288 
2289 	return NULL;
2290 }
2291 
2292 /**
2293  * i40e_update_filter_state - Update filter state based on return data
2294  * from firmware
2295  * @count: Number of filters added
2296  * @add_list: return data from fw
2297  * @add_head: pointer to first filter in current batch
2298  *
2299  * MAC filter entries from list were slated to be added to device. Returns
2300  * number of successful filters. Note that 0 does NOT mean success!
2301  **/
2302 static int
2303 i40e_update_filter_state(int count,
2304 			 struct i40e_aqc_add_macvlan_element_data *add_list,
2305 			 struct i40e_new_mac_filter *add_head)
2306 {
2307 	int retval = 0;
2308 	int i;
2309 
2310 	for (i = 0; i < count; i++) {
2311 		/* Always check status of each filter. We don't need to check
2312 		 * the firmware return status because we pre-set the filter
2313 		 * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2314 		 * request to the adminq. Thus, if it no longer matches then
2315 		 * we know the filter is active.
2316 		 */
2317 		if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2318 			add_head->state = I40E_FILTER_FAILED;
2319 		} else {
2320 			add_head->state = I40E_FILTER_ACTIVE;
2321 			retval++;
2322 		}
2323 
2324 		add_head = i40e_next_filter(add_head);
2325 		if (!add_head)
2326 			break;
2327 	}
2328 
2329 	return retval;
2330 }
2331 
2332 /**
2333  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2334  * @vsi: ptr to the VSI
2335  * @vsi_name: name to display in messages
2336  * @list: the list of filters to send to firmware
2337  * @num_del: the number of filters to delete
2338  * @retval: Set to -EIO on failure to delete
2339  *
2340  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2341  * *retval instead of a return value so that success does not force ret_val to
2342  * be set to 0. This ensures that a sequence of calls to this function
2343  * preserve the previous value of *retval on successful delete.
2344  */
2345 static
2346 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2347 			  struct i40e_aqc_remove_macvlan_element_data *list,
2348 			  int num_del, int *retval)
2349 {
2350 	struct i40e_hw *hw = &vsi->back->hw;
2351 	enum i40e_admin_queue_err aq_status;
2352 	i40e_status aq_ret;
2353 
2354 	aq_ret = i40e_aq_remove_macvlan_v2(hw, vsi->seid, list, num_del, NULL,
2355 					   &aq_status);
2356 
2357 	/* Explicitly ignore and do not report when firmware returns ENOENT */
2358 	if (aq_ret && !(aq_status == I40E_AQ_RC_ENOENT)) {
2359 		*retval = -EIO;
2360 		dev_info(&vsi->back->pdev->dev,
2361 			 "ignoring delete macvlan error on %s, err %s, aq_err %s\n",
2362 			 vsi_name, i40e_stat_str(hw, aq_ret),
2363 			 i40e_aq_str(hw, aq_status));
2364 	}
2365 }
2366 
2367 /**
2368  * i40e_aqc_add_filters - Request firmware to add a set of filters
2369  * @vsi: ptr to the VSI
2370  * @vsi_name: name to display in messages
2371  * @list: the list of filters to send to firmware
2372  * @add_head: Position in the add hlist
2373  * @num_add: the number of filters to add
2374  *
2375  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2376  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2377  * space for more filters.
2378  */
2379 static
2380 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2381 			  struct i40e_aqc_add_macvlan_element_data *list,
2382 			  struct i40e_new_mac_filter *add_head,
2383 			  int num_add)
2384 {
2385 	struct i40e_hw *hw = &vsi->back->hw;
2386 	enum i40e_admin_queue_err aq_status;
2387 	int fcnt;
2388 
2389 	i40e_aq_add_macvlan_v2(hw, vsi->seid, list, num_add, NULL, &aq_status);
2390 	fcnt = i40e_update_filter_state(num_add, list, add_head);
2391 
2392 	if (fcnt != num_add) {
2393 		if (vsi->type == I40E_VSI_MAIN) {
2394 			set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2395 			dev_warn(&vsi->back->pdev->dev,
2396 				 "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2397 				 i40e_aq_str(hw, aq_status), vsi_name);
2398 		} else if (vsi->type == I40E_VSI_SRIOV ||
2399 			   vsi->type == I40E_VSI_VMDQ1 ||
2400 			   vsi->type == I40E_VSI_VMDQ2) {
2401 			dev_warn(&vsi->back->pdev->dev,
2402 				 "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2403 				 i40e_aq_str(hw, aq_status), vsi_name,
2404 					     vsi_name);
2405 		} else {
2406 			dev_warn(&vsi->back->pdev->dev,
2407 				 "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2408 				 i40e_aq_str(hw, aq_status), vsi_name,
2409 					     vsi->type);
2410 		}
2411 	}
2412 }
2413 
2414 /**
2415  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2416  * @vsi: pointer to the VSI
2417  * @vsi_name: the VSI name
2418  * @f: filter data
2419  *
2420  * This function sets or clears the promiscuous broadcast flags for VLAN
2421  * filters in order to properly receive broadcast frames. Assumes that only
2422  * broadcast filters are passed.
2423  *
2424  * Returns status indicating success or failure;
2425  **/
2426 static i40e_status
2427 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2428 			  struct i40e_mac_filter *f)
2429 {
2430 	bool enable = f->state == I40E_FILTER_NEW;
2431 	struct i40e_hw *hw = &vsi->back->hw;
2432 	i40e_status aq_ret;
2433 
2434 	if (f->vlan == I40E_VLAN_ANY) {
2435 		aq_ret = i40e_aq_set_vsi_broadcast(hw,
2436 						   vsi->seid,
2437 						   enable,
2438 						   NULL);
2439 	} else {
2440 		aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2441 							    vsi->seid,
2442 							    enable,
2443 							    f->vlan,
2444 							    NULL);
2445 	}
2446 
2447 	if (aq_ret) {
2448 		set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2449 		dev_warn(&vsi->back->pdev->dev,
2450 			 "Error %s, forcing overflow promiscuous on %s\n",
2451 			 i40e_aq_str(hw, hw->aq.asq_last_status),
2452 			 vsi_name);
2453 	}
2454 
2455 	return aq_ret;
2456 }
2457 
2458 /**
2459  * i40e_set_promiscuous - set promiscuous mode
2460  * @pf: board private structure
2461  * @promisc: promisc on or off
2462  *
2463  * There are different ways of setting promiscuous mode on a PF depending on
2464  * what state/environment we're in.  This identifies and sets it appropriately.
2465  * Returns 0 on success.
2466  **/
2467 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2468 {
2469 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
2470 	struct i40e_hw *hw = &pf->hw;
2471 	i40e_status aq_ret;
2472 
2473 	if (vsi->type == I40E_VSI_MAIN &&
2474 	    pf->lan_veb != I40E_NO_VEB &&
2475 	    !(pf->flags & I40E_FLAG_MFP_ENABLED)) {
2476 		/* set defport ON for Main VSI instead of true promisc
2477 		 * this way we will get all unicast/multicast and VLAN
2478 		 * promisc behavior but will not get VF or VMDq traffic
2479 		 * replicated on the Main VSI.
2480 		 */
2481 		if (promisc)
2482 			aq_ret = i40e_aq_set_default_vsi(hw,
2483 							 vsi->seid,
2484 							 NULL);
2485 		else
2486 			aq_ret = i40e_aq_clear_default_vsi(hw,
2487 							   vsi->seid,
2488 							   NULL);
2489 		if (aq_ret) {
2490 			dev_info(&pf->pdev->dev,
2491 				 "Set default VSI failed, err %s, aq_err %s\n",
2492 				 i40e_stat_str(hw, aq_ret),
2493 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2494 		}
2495 	} else {
2496 		aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2497 						  hw,
2498 						  vsi->seid,
2499 						  promisc, NULL,
2500 						  true);
2501 		if (aq_ret) {
2502 			dev_info(&pf->pdev->dev,
2503 				 "set unicast promisc failed, err %s, aq_err %s\n",
2504 				 i40e_stat_str(hw, aq_ret),
2505 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2506 		}
2507 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2508 						  hw,
2509 						  vsi->seid,
2510 						  promisc, NULL);
2511 		if (aq_ret) {
2512 			dev_info(&pf->pdev->dev,
2513 				 "set multicast promisc failed, err %s, aq_err %s\n",
2514 				 i40e_stat_str(hw, aq_ret),
2515 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2516 		}
2517 	}
2518 
2519 	if (!aq_ret)
2520 		pf->cur_promisc = promisc;
2521 
2522 	return aq_ret;
2523 }
2524 
2525 /**
2526  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2527  * @vsi: ptr to the VSI
2528  *
2529  * Push any outstanding VSI filter changes through the AdminQ.
2530  *
2531  * Returns 0 or error value
2532  **/
2533 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2534 {
2535 	struct hlist_head tmp_add_list, tmp_del_list;
2536 	struct i40e_mac_filter *f;
2537 	struct i40e_new_mac_filter *new, *add_head = NULL;
2538 	struct i40e_hw *hw = &vsi->back->hw;
2539 	bool old_overflow, new_overflow;
2540 	unsigned int failed_filters = 0;
2541 	unsigned int vlan_filters = 0;
2542 	char vsi_name[16] = "PF";
2543 	int filter_list_len = 0;
2544 	i40e_status aq_ret = 0;
2545 	u32 changed_flags = 0;
2546 	struct hlist_node *h;
2547 	struct i40e_pf *pf;
2548 	int num_add = 0;
2549 	int num_del = 0;
2550 	int retval = 0;
2551 	u16 cmd_flags;
2552 	int list_size;
2553 	int bkt;
2554 
2555 	/* empty array typed pointers, kcalloc later */
2556 	struct i40e_aqc_add_macvlan_element_data *add_list;
2557 	struct i40e_aqc_remove_macvlan_element_data *del_list;
2558 
2559 	while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2560 		usleep_range(1000, 2000);
2561 	pf = vsi->back;
2562 
2563 	old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2564 
2565 	if (vsi->netdev) {
2566 		changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2567 		vsi->current_netdev_flags = vsi->netdev->flags;
2568 	}
2569 
2570 	INIT_HLIST_HEAD(&tmp_add_list);
2571 	INIT_HLIST_HEAD(&tmp_del_list);
2572 
2573 	if (vsi->type == I40E_VSI_SRIOV)
2574 		snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2575 	else if (vsi->type != I40E_VSI_MAIN)
2576 		snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2577 
2578 	if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2579 		vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2580 
2581 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2582 		/* Create a list of filters to delete. */
2583 		hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2584 			if (f->state == I40E_FILTER_REMOVE) {
2585 				/* Move the element into temporary del_list */
2586 				hash_del(&f->hlist);
2587 				hlist_add_head(&f->hlist, &tmp_del_list);
2588 
2589 				/* Avoid counting removed filters */
2590 				continue;
2591 			}
2592 			if (f->state == I40E_FILTER_NEW) {
2593 				/* Create a temporary i40e_new_mac_filter */
2594 				new = kzalloc(sizeof(*new), GFP_ATOMIC);
2595 				if (!new)
2596 					goto err_no_memory_locked;
2597 
2598 				/* Store pointer to the real filter */
2599 				new->f = f;
2600 				new->state = f->state;
2601 
2602 				/* Add it to the hash list */
2603 				hlist_add_head(&new->hlist, &tmp_add_list);
2604 			}
2605 
2606 			/* Count the number of active (current and new) VLAN
2607 			 * filters we have now. Does not count filters which
2608 			 * are marked for deletion.
2609 			 */
2610 			if (f->vlan > 0)
2611 				vlan_filters++;
2612 		}
2613 
2614 		if (vsi->type != I40E_VSI_SRIOV)
2615 			retval = i40e_correct_mac_vlan_filters
2616 				(vsi, &tmp_add_list, &tmp_del_list,
2617 				 vlan_filters);
2618 		else
2619 			retval = i40e_correct_vf_mac_vlan_filters
2620 				(vsi, &tmp_add_list, &tmp_del_list,
2621 				 vlan_filters, pf->vf[vsi->vf_id].trusted);
2622 
2623 		hlist_for_each_entry(new, &tmp_add_list, hlist)
2624 			netdev_hw_addr_refcnt(new->f, vsi->netdev, 1);
2625 
2626 		if (retval)
2627 			goto err_no_memory_locked;
2628 
2629 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2630 	}
2631 
2632 	/* Now process 'del_list' outside the lock */
2633 	if (!hlist_empty(&tmp_del_list)) {
2634 		filter_list_len = hw->aq.asq_buf_size /
2635 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2636 		list_size = filter_list_len *
2637 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2638 		del_list = kzalloc(list_size, GFP_ATOMIC);
2639 		if (!del_list)
2640 			goto err_no_memory;
2641 
2642 		hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2643 			cmd_flags = 0;
2644 
2645 			/* handle broadcast filters by updating the broadcast
2646 			 * promiscuous flag and release filter list.
2647 			 */
2648 			if (is_broadcast_ether_addr(f->macaddr)) {
2649 				i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2650 
2651 				hlist_del(&f->hlist);
2652 				kfree(f);
2653 				continue;
2654 			}
2655 
2656 			/* add to delete list */
2657 			ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2658 			if (f->vlan == I40E_VLAN_ANY) {
2659 				del_list[num_del].vlan_tag = 0;
2660 				cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2661 			} else {
2662 				del_list[num_del].vlan_tag =
2663 					cpu_to_le16((u16)(f->vlan));
2664 			}
2665 
2666 			cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2667 			del_list[num_del].flags = cmd_flags;
2668 			num_del++;
2669 
2670 			/* flush a full buffer */
2671 			if (num_del == filter_list_len) {
2672 				i40e_aqc_del_filters(vsi, vsi_name, del_list,
2673 						     num_del, &retval);
2674 				memset(del_list, 0, list_size);
2675 				num_del = 0;
2676 			}
2677 			/* Release memory for MAC filter entries which were
2678 			 * synced up with HW.
2679 			 */
2680 			hlist_del(&f->hlist);
2681 			kfree(f);
2682 		}
2683 
2684 		if (num_del) {
2685 			i40e_aqc_del_filters(vsi, vsi_name, del_list,
2686 					     num_del, &retval);
2687 		}
2688 
2689 		kfree(del_list);
2690 		del_list = NULL;
2691 	}
2692 
2693 	if (!hlist_empty(&tmp_add_list)) {
2694 		/* Do all the adds now. */
2695 		filter_list_len = hw->aq.asq_buf_size /
2696 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2697 		list_size = filter_list_len *
2698 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2699 		add_list = kzalloc(list_size, GFP_ATOMIC);
2700 		if (!add_list)
2701 			goto err_no_memory;
2702 
2703 		num_add = 0;
2704 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2705 			/* handle broadcast filters by updating the broadcast
2706 			 * promiscuous flag instead of adding a MAC filter.
2707 			 */
2708 			if (is_broadcast_ether_addr(new->f->macaddr)) {
2709 				if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2710 							      new->f))
2711 					new->state = I40E_FILTER_FAILED;
2712 				else
2713 					new->state = I40E_FILTER_ACTIVE;
2714 				continue;
2715 			}
2716 
2717 			/* add to add array */
2718 			if (num_add == 0)
2719 				add_head = new;
2720 			cmd_flags = 0;
2721 			ether_addr_copy(add_list[num_add].mac_addr,
2722 					new->f->macaddr);
2723 			if (new->f->vlan == I40E_VLAN_ANY) {
2724 				add_list[num_add].vlan_tag = 0;
2725 				cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2726 			} else {
2727 				add_list[num_add].vlan_tag =
2728 					cpu_to_le16((u16)(new->f->vlan));
2729 			}
2730 			add_list[num_add].queue_number = 0;
2731 			/* set invalid match method for later detection */
2732 			add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2733 			cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2734 			add_list[num_add].flags = cpu_to_le16(cmd_flags);
2735 			num_add++;
2736 
2737 			/* flush a full buffer */
2738 			if (num_add == filter_list_len) {
2739 				i40e_aqc_add_filters(vsi, vsi_name, add_list,
2740 						     add_head, num_add);
2741 				memset(add_list, 0, list_size);
2742 				num_add = 0;
2743 			}
2744 		}
2745 		if (num_add) {
2746 			i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2747 					     num_add);
2748 		}
2749 		/* Now move all of the filters from the temp add list back to
2750 		 * the VSI's list.
2751 		 */
2752 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2753 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2754 			/* Only update the state if we're still NEW */
2755 			if (new->f->state == I40E_FILTER_NEW)
2756 				new->f->state = new->state;
2757 			hlist_del(&new->hlist);
2758 			netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2759 			kfree(new);
2760 		}
2761 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2762 		kfree(add_list);
2763 		add_list = NULL;
2764 	}
2765 
2766 	/* Determine the number of active and failed filters. */
2767 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2768 	vsi->active_filters = 0;
2769 	hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2770 		if (f->state == I40E_FILTER_ACTIVE)
2771 			vsi->active_filters++;
2772 		else if (f->state == I40E_FILTER_FAILED)
2773 			failed_filters++;
2774 	}
2775 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2776 
2777 	/* Check if we are able to exit overflow promiscuous mode. We can
2778 	 * safely exit if we didn't just enter, we no longer have any failed
2779 	 * filters, and we have reduced filters below the threshold value.
2780 	 */
2781 	if (old_overflow && !failed_filters &&
2782 	    vsi->active_filters < vsi->promisc_threshold) {
2783 		dev_info(&pf->pdev->dev,
2784 			 "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2785 			 vsi_name);
2786 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2787 		vsi->promisc_threshold = 0;
2788 	}
2789 
2790 	/* if the VF is not trusted do not do promisc */
2791 	if ((vsi->type == I40E_VSI_SRIOV) && !pf->vf[vsi->vf_id].trusted) {
2792 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2793 		goto out;
2794 	}
2795 
2796 	new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2797 
2798 	/* If we are entering overflow promiscuous, we need to calculate a new
2799 	 * threshold for when we are safe to exit
2800 	 */
2801 	if (!old_overflow && new_overflow)
2802 		vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2803 
2804 	/* check for changes in promiscuous modes */
2805 	if (changed_flags & IFF_ALLMULTI) {
2806 		bool cur_multipromisc;
2807 
2808 		cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2809 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2810 							       vsi->seid,
2811 							       cur_multipromisc,
2812 							       NULL);
2813 		if (aq_ret) {
2814 			retval = i40e_aq_rc_to_posix(aq_ret,
2815 						     hw->aq.asq_last_status);
2816 			dev_info(&pf->pdev->dev,
2817 				 "set multi promisc failed on %s, err %s aq_err %s\n",
2818 				 vsi_name,
2819 				 i40e_stat_str(hw, aq_ret),
2820 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2821 		} else {
2822 			dev_info(&pf->pdev->dev, "%s allmulti mode.\n",
2823 				 cur_multipromisc ? "entering" : "leaving");
2824 		}
2825 	}
2826 
2827 	if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2828 		bool cur_promisc;
2829 
2830 		cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2831 			       new_overflow);
2832 		aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2833 		if (aq_ret) {
2834 			retval = i40e_aq_rc_to_posix(aq_ret,
2835 						     hw->aq.asq_last_status);
2836 			dev_info(&pf->pdev->dev,
2837 				 "Setting promiscuous %s failed on %s, err %s aq_err %s\n",
2838 				 cur_promisc ? "on" : "off",
2839 				 vsi_name,
2840 				 i40e_stat_str(hw, aq_ret),
2841 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2842 		}
2843 	}
2844 out:
2845 	/* if something went wrong then set the changed flag so we try again */
2846 	if (retval)
2847 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2848 
2849 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2850 	return retval;
2851 
2852 err_no_memory:
2853 	/* Restore elements on the temporary add and delete lists */
2854 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2855 err_no_memory_locked:
2856 	i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2857 	i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2858 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2859 
2860 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2861 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2862 	return -ENOMEM;
2863 }
2864 
2865 /**
2866  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2867  * @pf: board private structure
2868  **/
2869 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2870 {
2871 	int v;
2872 
2873 	if (!pf)
2874 		return;
2875 	if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2876 		return;
2877 	if (test_bit(__I40E_VF_DISABLE, pf->state)) {
2878 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
2879 		return;
2880 	}
2881 
2882 	for (v = 0; v < pf->num_alloc_vsi; v++) {
2883 		if (pf->vsi[v] &&
2884 		    (pf->vsi[v]->flags & I40E_VSI_FLAG_FILTER_CHANGED) &&
2885 		    !test_bit(__I40E_VSI_RELEASING, pf->vsi[v]->state)) {
2886 			int ret = i40e_sync_vsi_filters(pf->vsi[v]);
2887 
2888 			if (ret) {
2889 				/* come back and try again later */
2890 				set_bit(__I40E_MACVLAN_SYNC_PENDING,
2891 					pf->state);
2892 				break;
2893 			}
2894 		}
2895 	}
2896 }
2897 
2898 /**
2899  * i40e_max_xdp_frame_size - returns the maximum allowed frame size for XDP
2900  * @vsi: the vsi
2901  **/
2902 static int i40e_max_xdp_frame_size(struct i40e_vsi *vsi)
2903 {
2904 	if (PAGE_SIZE >= 8192 || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
2905 		return I40E_RXBUFFER_2048;
2906 	else
2907 		return I40E_RXBUFFER_3072;
2908 }
2909 
2910 /**
2911  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2912  * @netdev: network interface device structure
2913  * @new_mtu: new value for maximum frame size
2914  *
2915  * Returns 0 on success, negative on failure
2916  **/
2917 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2918 {
2919 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2920 	struct i40e_vsi *vsi = np->vsi;
2921 	struct i40e_pf *pf = vsi->back;
2922 
2923 	if (i40e_enabled_xdp_vsi(vsi)) {
2924 		int frame_size = new_mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
2925 
2926 		if (frame_size > i40e_max_xdp_frame_size(vsi))
2927 			return -EINVAL;
2928 	}
2929 
2930 	netdev_dbg(netdev, "changing MTU from %d to %d\n",
2931 		   netdev->mtu, new_mtu);
2932 	netdev->mtu = new_mtu;
2933 	if (netif_running(netdev))
2934 		i40e_vsi_reinit_locked(vsi);
2935 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2936 	set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2937 	return 0;
2938 }
2939 
2940 /**
2941  * i40e_ioctl - Access the hwtstamp interface
2942  * @netdev: network interface device structure
2943  * @ifr: interface request data
2944  * @cmd: ioctl command
2945  **/
2946 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2947 {
2948 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2949 	struct i40e_pf *pf = np->vsi->back;
2950 
2951 	switch (cmd) {
2952 	case SIOCGHWTSTAMP:
2953 		return i40e_ptp_get_ts_config(pf, ifr);
2954 	case SIOCSHWTSTAMP:
2955 		return i40e_ptp_set_ts_config(pf, ifr);
2956 	default:
2957 		return -EOPNOTSUPP;
2958 	}
2959 }
2960 
2961 /**
2962  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2963  * @vsi: the vsi being adjusted
2964  **/
2965 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2966 {
2967 	struct i40e_vsi_context ctxt;
2968 	i40e_status ret;
2969 
2970 	/* Don't modify stripping options if a port VLAN is active */
2971 	if (vsi->info.pvid)
2972 		return;
2973 
2974 	if ((vsi->info.valid_sections &
2975 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2976 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2977 		return;  /* already enabled */
2978 
2979 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2980 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2981 				    I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
2982 
2983 	ctxt.seid = vsi->seid;
2984 	ctxt.info = vsi->info;
2985 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2986 	if (ret) {
2987 		dev_info(&vsi->back->pdev->dev,
2988 			 "update vlan stripping failed, err %s aq_err %s\n",
2989 			 i40e_stat_str(&vsi->back->hw, ret),
2990 			 i40e_aq_str(&vsi->back->hw,
2991 				     vsi->back->hw.aq.asq_last_status));
2992 	}
2993 }
2994 
2995 /**
2996  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
2997  * @vsi: the vsi being adjusted
2998  **/
2999 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
3000 {
3001 	struct i40e_vsi_context ctxt;
3002 	i40e_status ret;
3003 
3004 	/* Don't modify stripping options if a port VLAN is active */
3005 	if (vsi->info.pvid)
3006 		return;
3007 
3008 	if ((vsi->info.valid_sections &
3009 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
3010 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
3011 	     I40E_AQ_VSI_PVLAN_EMOD_MASK))
3012 		return;  /* already disabled */
3013 
3014 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3015 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3016 				    I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
3017 
3018 	ctxt.seid = vsi->seid;
3019 	ctxt.info = vsi->info;
3020 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3021 	if (ret) {
3022 		dev_info(&vsi->back->pdev->dev,
3023 			 "update vlan stripping failed, err %s aq_err %s\n",
3024 			 i40e_stat_str(&vsi->back->hw, ret),
3025 			 i40e_aq_str(&vsi->back->hw,
3026 				     vsi->back->hw.aq.asq_last_status));
3027 	}
3028 }
3029 
3030 /**
3031  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
3032  * @vsi: the vsi being configured
3033  * @vid: vlan id to be added (0 = untagged only , -1 = any)
3034  *
3035  * This is a helper function for adding a new MAC/VLAN filter with the
3036  * specified VLAN for each existing MAC address already in the hash table.
3037  * This function does *not* perform any accounting to update filters based on
3038  * VLAN mode.
3039  *
3040  * NOTE: this function expects to be called while under the
3041  * mac_filter_hash_lock
3042  **/
3043 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3044 {
3045 	struct i40e_mac_filter *f, *add_f;
3046 	struct hlist_node *h;
3047 	int bkt;
3048 
3049 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3050 		/* If we're asked to add a filter that has been marked for
3051 		 * removal, it is safe to simply restore it to active state.
3052 		 * __i40e_del_filter will have simply deleted any filters which
3053 		 * were previously marked NEW or FAILED, so if it is currently
3054 		 * marked REMOVE it must have previously been ACTIVE. Since we
3055 		 * haven't yet run the sync filters task, just restore this
3056 		 * filter to the ACTIVE state so that the sync task leaves it
3057 		 * in place.
3058 		 */
3059 		if (f->state == I40E_FILTER_REMOVE && f->vlan == vid) {
3060 			f->state = I40E_FILTER_ACTIVE;
3061 			continue;
3062 		} else if (f->state == I40E_FILTER_REMOVE) {
3063 			continue;
3064 		}
3065 		add_f = i40e_add_filter(vsi, f->macaddr, vid);
3066 		if (!add_f) {
3067 			dev_info(&vsi->back->pdev->dev,
3068 				 "Could not add vlan filter %d for %pM\n",
3069 				 vid, f->macaddr);
3070 			return -ENOMEM;
3071 		}
3072 	}
3073 
3074 	return 0;
3075 }
3076 
3077 /**
3078  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
3079  * @vsi: the VSI being configured
3080  * @vid: VLAN id to be added
3081  **/
3082 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
3083 {
3084 	int err;
3085 
3086 	if (vsi->info.pvid)
3087 		return -EINVAL;
3088 
3089 	/* The network stack will attempt to add VID=0, with the intention to
3090 	 * receive priority tagged packets with a VLAN of 0. Our HW receives
3091 	 * these packets by default when configured to receive untagged
3092 	 * packets, so we don't need to add a filter for this case.
3093 	 * Additionally, HW interprets adding a VID=0 filter as meaning to
3094 	 * receive *only* tagged traffic and stops receiving untagged traffic.
3095 	 * Thus, we do not want to actually add a filter for VID=0
3096 	 */
3097 	if (!vid)
3098 		return 0;
3099 
3100 	/* Locked once because all functions invoked below iterates list*/
3101 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3102 	err = i40e_add_vlan_all_mac(vsi, vid);
3103 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3104 	if (err)
3105 		return err;
3106 
3107 	/* schedule our worker thread which will take care of
3108 	 * applying the new filter changes
3109 	 */
3110 	i40e_service_event_schedule(vsi->back);
3111 	return 0;
3112 }
3113 
3114 /**
3115  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
3116  * @vsi: the vsi being configured
3117  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
3118  *
3119  * This function should be used to remove all VLAN filters which match the
3120  * given VID. It does not schedule the service event and does not take the
3121  * mac_filter_hash_lock so it may be combined with other operations under
3122  * a single invocation of the mac_filter_hash_lock.
3123  *
3124  * NOTE: this function expects to be called while under the
3125  * mac_filter_hash_lock
3126  */
3127 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3128 {
3129 	struct i40e_mac_filter *f;
3130 	struct hlist_node *h;
3131 	int bkt;
3132 
3133 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3134 		if (f->vlan == vid)
3135 			__i40e_del_filter(vsi, f);
3136 	}
3137 }
3138 
3139 /**
3140  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
3141  * @vsi: the VSI being configured
3142  * @vid: VLAN id to be removed
3143  **/
3144 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
3145 {
3146 	if (!vid || vsi->info.pvid)
3147 		return;
3148 
3149 	spin_lock_bh(&vsi->mac_filter_hash_lock);
3150 	i40e_rm_vlan_all_mac(vsi, vid);
3151 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
3152 
3153 	/* schedule our worker thread which will take care of
3154 	 * applying the new filter changes
3155 	 */
3156 	i40e_service_event_schedule(vsi->back);
3157 }
3158 
3159 /**
3160  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
3161  * @netdev: network interface to be adjusted
3162  * @proto: unused protocol value
3163  * @vid: vlan id to be added
3164  *
3165  * net_device_ops implementation for adding vlan ids
3166  **/
3167 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
3168 				__always_unused __be16 proto, u16 vid)
3169 {
3170 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3171 	struct i40e_vsi *vsi = np->vsi;
3172 	int ret = 0;
3173 
3174 	if (vid >= VLAN_N_VID)
3175 		return -EINVAL;
3176 
3177 	ret = i40e_vsi_add_vlan(vsi, vid);
3178 	if (!ret)
3179 		set_bit(vid, vsi->active_vlans);
3180 
3181 	return ret;
3182 }
3183 
3184 /**
3185  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
3186  * @netdev: network interface to be adjusted
3187  * @proto: unused protocol value
3188  * @vid: vlan id to be added
3189  **/
3190 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
3191 				    __always_unused __be16 proto, u16 vid)
3192 {
3193 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3194 	struct i40e_vsi *vsi = np->vsi;
3195 
3196 	if (vid >= VLAN_N_VID)
3197 		return;
3198 	set_bit(vid, vsi->active_vlans);
3199 }
3200 
3201 /**
3202  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
3203  * @netdev: network interface to be adjusted
3204  * @proto: unused protocol value
3205  * @vid: vlan id to be removed
3206  *
3207  * net_device_ops implementation for removing vlan ids
3208  **/
3209 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
3210 				 __always_unused __be16 proto, u16 vid)
3211 {
3212 	struct i40e_netdev_priv *np = netdev_priv(netdev);
3213 	struct i40e_vsi *vsi = np->vsi;
3214 
3215 	/* return code is ignored as there is nothing a user
3216 	 * can do about failure to remove and a log message was
3217 	 * already printed from the other function
3218 	 */
3219 	i40e_vsi_kill_vlan(vsi, vid);
3220 
3221 	clear_bit(vid, vsi->active_vlans);
3222 
3223 	return 0;
3224 }
3225 
3226 /**
3227  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
3228  * @vsi: the vsi being brought back up
3229  **/
3230 static void i40e_restore_vlan(struct i40e_vsi *vsi)
3231 {
3232 	u16 vid;
3233 
3234 	if (!vsi->netdev)
3235 		return;
3236 
3237 	if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
3238 		i40e_vlan_stripping_enable(vsi);
3239 	else
3240 		i40e_vlan_stripping_disable(vsi);
3241 
3242 	for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
3243 		i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
3244 					vid);
3245 }
3246 
3247 /**
3248  * i40e_vsi_add_pvid - Add pvid for the VSI
3249  * @vsi: the vsi being adjusted
3250  * @vid: the vlan id to set as a PVID
3251  **/
3252 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
3253 {
3254 	struct i40e_vsi_context ctxt;
3255 	i40e_status ret;
3256 
3257 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3258 	vsi->info.pvid = cpu_to_le16(vid);
3259 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
3260 				    I40E_AQ_VSI_PVLAN_INSERT_PVID |
3261 				    I40E_AQ_VSI_PVLAN_EMOD_STR;
3262 
3263 	ctxt.seid = vsi->seid;
3264 	ctxt.info = vsi->info;
3265 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3266 	if (ret) {
3267 		dev_info(&vsi->back->pdev->dev,
3268 			 "add pvid failed, err %s aq_err %s\n",
3269 			 i40e_stat_str(&vsi->back->hw, ret),
3270 			 i40e_aq_str(&vsi->back->hw,
3271 				     vsi->back->hw.aq.asq_last_status));
3272 		return -ENOENT;
3273 	}
3274 
3275 	return 0;
3276 }
3277 
3278 /**
3279  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
3280  * @vsi: the vsi being adjusted
3281  *
3282  * Just use the vlan_rx_register() service to put it back to normal
3283  **/
3284 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
3285 {
3286 	vsi->info.pvid = 0;
3287 
3288 	i40e_vlan_stripping_disable(vsi);
3289 }
3290 
3291 /**
3292  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
3293  * @vsi: ptr to the VSI
3294  *
3295  * If this function returns with an error, then it's possible one or
3296  * more of the rings is populated (while the rest are not).  It is the
3297  * callers duty to clean those orphaned rings.
3298  *
3299  * Return 0 on success, negative on failure
3300  **/
3301 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3302 {
3303 	int i, err = 0;
3304 
3305 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3306 		err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3307 
3308 	if (!i40e_enabled_xdp_vsi(vsi))
3309 		return err;
3310 
3311 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3312 		err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3313 
3314 	return err;
3315 }
3316 
3317 /**
3318  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3319  * @vsi: ptr to the VSI
3320  *
3321  * Free VSI's transmit software resources
3322  **/
3323 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3324 {
3325 	int i;
3326 
3327 	if (vsi->tx_rings) {
3328 		for (i = 0; i < vsi->num_queue_pairs; i++)
3329 			if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3330 				i40e_free_tx_resources(vsi->tx_rings[i]);
3331 	}
3332 
3333 	if (vsi->xdp_rings) {
3334 		for (i = 0; i < vsi->num_queue_pairs; i++)
3335 			if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3336 				i40e_free_tx_resources(vsi->xdp_rings[i]);
3337 	}
3338 }
3339 
3340 /**
3341  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3342  * @vsi: ptr to the VSI
3343  *
3344  * If this function returns with an error, then it's possible one or
3345  * more of the rings is populated (while the rest are not).  It is the
3346  * callers duty to clean those orphaned rings.
3347  *
3348  * Return 0 on success, negative on failure
3349  **/
3350 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3351 {
3352 	int i, err = 0;
3353 
3354 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3355 		err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3356 	return err;
3357 }
3358 
3359 /**
3360  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3361  * @vsi: ptr to the VSI
3362  *
3363  * Free all receive software resources
3364  **/
3365 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3366 {
3367 	int i;
3368 
3369 	if (!vsi->rx_rings)
3370 		return;
3371 
3372 	for (i = 0; i < vsi->num_queue_pairs; i++)
3373 		if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3374 			i40e_free_rx_resources(vsi->rx_rings[i]);
3375 }
3376 
3377 /**
3378  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3379  * @ring: The Tx ring to configure
3380  *
3381  * This enables/disables XPS for a given Tx descriptor ring
3382  * based on the TCs enabled for the VSI that ring belongs to.
3383  **/
3384 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3385 {
3386 	int cpu;
3387 
3388 	if (!ring->q_vector || !ring->netdev || ring->ch)
3389 		return;
3390 
3391 	/* We only initialize XPS once, so as not to overwrite user settings */
3392 	if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3393 		return;
3394 
3395 	cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3396 	netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3397 			    ring->queue_index);
3398 }
3399 
3400 /**
3401  * i40e_xsk_pool - Retrieve the AF_XDP buffer pool if XDP and ZC is enabled
3402  * @ring: The Tx or Rx ring
3403  *
3404  * Returns the AF_XDP buffer pool or NULL.
3405  **/
3406 static struct xsk_buff_pool *i40e_xsk_pool(struct i40e_ring *ring)
3407 {
3408 	bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3409 	int qid = ring->queue_index;
3410 
3411 	if (ring_is_xdp(ring))
3412 		qid -= ring->vsi->alloc_queue_pairs;
3413 
3414 	if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3415 		return NULL;
3416 
3417 	return xsk_get_pool_from_qid(ring->vsi->netdev, qid);
3418 }
3419 
3420 /**
3421  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3422  * @ring: The Tx ring to configure
3423  *
3424  * Configure the Tx descriptor ring in the HMC context.
3425  **/
3426 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3427 {
3428 	struct i40e_vsi *vsi = ring->vsi;
3429 	u16 pf_q = vsi->base_queue + ring->queue_index;
3430 	struct i40e_hw *hw = &vsi->back->hw;
3431 	struct i40e_hmc_obj_txq tx_ctx;
3432 	i40e_status err = 0;
3433 	u32 qtx_ctl = 0;
3434 
3435 	if (ring_is_xdp(ring))
3436 		ring->xsk_pool = i40e_xsk_pool(ring);
3437 
3438 	/* some ATR related tx ring init */
3439 	if (vsi->back->flags & I40E_FLAG_FD_ATR_ENABLED) {
3440 		ring->atr_sample_rate = vsi->back->atr_sample_rate;
3441 		ring->atr_count = 0;
3442 	} else {
3443 		ring->atr_sample_rate = 0;
3444 	}
3445 
3446 	/* configure XPS */
3447 	i40e_config_xps_tx_ring(ring);
3448 
3449 	/* clear the context structure first */
3450 	memset(&tx_ctx, 0, sizeof(tx_ctx));
3451 
3452 	tx_ctx.new_context = 1;
3453 	tx_ctx.base = (ring->dma / 128);
3454 	tx_ctx.qlen = ring->count;
3455 	tx_ctx.fd_ena = !!(vsi->back->flags & (I40E_FLAG_FD_SB_ENABLED |
3456 					       I40E_FLAG_FD_ATR_ENABLED));
3457 	tx_ctx.timesync_ena = !!(vsi->back->flags & I40E_FLAG_PTP);
3458 	/* FDIR VSI tx ring can still use RS bit and writebacks */
3459 	if (vsi->type != I40E_VSI_FDIR)
3460 		tx_ctx.head_wb_ena = 1;
3461 	tx_ctx.head_wb_addr = ring->dma +
3462 			      (ring->count * sizeof(struct i40e_tx_desc));
3463 
3464 	/* As part of VSI creation/update, FW allocates certain
3465 	 * Tx arbitration queue sets for each TC enabled for
3466 	 * the VSI. The FW returns the handles to these queue
3467 	 * sets as part of the response buffer to Add VSI,
3468 	 * Update VSI, etc. AQ commands. It is expected that
3469 	 * these queue set handles be associated with the Tx
3470 	 * queues by the driver as part of the TX queue context
3471 	 * initialization. This has to be done regardless of
3472 	 * DCB as by default everything is mapped to TC0.
3473 	 */
3474 
3475 	if (ring->ch)
3476 		tx_ctx.rdylist =
3477 			le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3478 
3479 	else
3480 		tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3481 
3482 	tx_ctx.rdylist_act = 0;
3483 
3484 	/* clear the context in the HMC */
3485 	err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3486 	if (err) {
3487 		dev_info(&vsi->back->pdev->dev,
3488 			 "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3489 			 ring->queue_index, pf_q, err);
3490 		return -ENOMEM;
3491 	}
3492 
3493 	/* set the context in the HMC */
3494 	err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3495 	if (err) {
3496 		dev_info(&vsi->back->pdev->dev,
3497 			 "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3498 			 ring->queue_index, pf_q, err);
3499 		return -ENOMEM;
3500 	}
3501 
3502 	/* Now associate this queue with this PCI function */
3503 	if (ring->ch) {
3504 		if (ring->ch->type == I40E_VSI_VMDQ2)
3505 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3506 		else
3507 			return -EINVAL;
3508 
3509 		qtx_ctl |= (ring->ch->vsi_number <<
3510 			    I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3511 			    I40E_QTX_CTL_VFVM_INDX_MASK;
3512 	} else {
3513 		if (vsi->type == I40E_VSI_VMDQ2) {
3514 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3515 			qtx_ctl |= ((vsi->id) << I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3516 				    I40E_QTX_CTL_VFVM_INDX_MASK;
3517 		} else {
3518 			qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3519 		}
3520 	}
3521 
3522 	qtx_ctl |= ((hw->pf_id << I40E_QTX_CTL_PF_INDX_SHIFT) &
3523 		    I40E_QTX_CTL_PF_INDX_MASK);
3524 	wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3525 	i40e_flush(hw);
3526 
3527 	/* cache tail off for easier writes later */
3528 	ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3529 
3530 	return 0;
3531 }
3532 
3533 /**
3534  * i40e_rx_offset - Return expected offset into page to access data
3535  * @rx_ring: Ring we are requesting offset of
3536  *
3537  * Returns the offset value for ring into the data buffer.
3538  */
3539 static unsigned int i40e_rx_offset(struct i40e_ring *rx_ring)
3540 {
3541 	return ring_uses_build_skb(rx_ring) ? I40E_SKB_PAD : 0;
3542 }
3543 
3544 /**
3545  * i40e_configure_rx_ring - Configure a receive ring context
3546  * @ring: The Rx ring to configure
3547  *
3548  * Configure the Rx descriptor ring in the HMC context.
3549  **/
3550 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3551 {
3552 	struct i40e_vsi *vsi = ring->vsi;
3553 	u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3554 	u16 pf_q = vsi->base_queue + ring->queue_index;
3555 	struct i40e_hw *hw = &vsi->back->hw;
3556 	struct i40e_hmc_obj_rxq rx_ctx;
3557 	i40e_status err = 0;
3558 	bool ok;
3559 	int ret;
3560 
3561 	bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3562 
3563 	/* clear the context structure first */
3564 	memset(&rx_ctx, 0, sizeof(rx_ctx));
3565 
3566 	if (ring->vsi->type == I40E_VSI_MAIN)
3567 		xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq);
3568 
3569 	kfree(ring->rx_bi);
3570 	ring->xsk_pool = i40e_xsk_pool(ring);
3571 	if (ring->xsk_pool) {
3572 		ret = i40e_alloc_rx_bi_zc(ring);
3573 		if (ret)
3574 			return ret;
3575 		ring->rx_buf_len =
3576 		  xsk_pool_get_rx_frame_size(ring->xsk_pool);
3577 		/* For AF_XDP ZC, we disallow packets to span on
3578 		 * multiple buffers, thus letting us skip that
3579 		 * handling in the fast-path.
3580 		 */
3581 		chain_len = 1;
3582 		ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3583 						 MEM_TYPE_XSK_BUFF_POOL,
3584 						 NULL);
3585 		if (ret)
3586 			return ret;
3587 		dev_info(&vsi->back->pdev->dev,
3588 			 "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n",
3589 			 ring->queue_index);
3590 
3591 	} else {
3592 		ret = i40e_alloc_rx_bi(ring);
3593 		if (ret)
3594 			return ret;
3595 		ring->rx_buf_len = vsi->rx_buf_len;
3596 		if (ring->vsi->type == I40E_VSI_MAIN) {
3597 			ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3598 							 MEM_TYPE_PAGE_SHARED,
3599 							 NULL);
3600 			if (ret)
3601 				return ret;
3602 		}
3603 	}
3604 
3605 	rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3606 				    BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3607 
3608 	rx_ctx.base = (ring->dma / 128);
3609 	rx_ctx.qlen = ring->count;
3610 
3611 	/* use 16 byte descriptors */
3612 	rx_ctx.dsize = 0;
3613 
3614 	/* descriptor type is always zero
3615 	 * rx_ctx.dtype = 0;
3616 	 */
3617 	rx_ctx.hsplit_0 = 0;
3618 
3619 	rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3620 	if (hw->revision_id == 0)
3621 		rx_ctx.lrxqthresh = 0;
3622 	else
3623 		rx_ctx.lrxqthresh = 1;
3624 	rx_ctx.crcstrip = 1;
3625 	rx_ctx.l2tsel = 1;
3626 	/* this controls whether VLAN is stripped from inner headers */
3627 	rx_ctx.showiv = 0;
3628 	/* set the prefena field to 1 because the manual says to */
3629 	rx_ctx.prefena = 1;
3630 
3631 	/* clear the context in the HMC */
3632 	err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3633 	if (err) {
3634 		dev_info(&vsi->back->pdev->dev,
3635 			 "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3636 			 ring->queue_index, pf_q, err);
3637 		return -ENOMEM;
3638 	}
3639 
3640 	/* set the context in the HMC */
3641 	err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3642 	if (err) {
3643 		dev_info(&vsi->back->pdev->dev,
3644 			 "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3645 			 ring->queue_index, pf_q, err);
3646 		return -ENOMEM;
3647 	}
3648 
3649 	/* configure Rx buffer alignment */
3650 	if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
3651 		clear_ring_build_skb_enabled(ring);
3652 	else
3653 		set_ring_build_skb_enabled(ring);
3654 
3655 	ring->rx_offset = i40e_rx_offset(ring);
3656 
3657 	/* cache tail for quicker writes, and clear the reg before use */
3658 	ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3659 	writel(0, ring->tail);
3660 
3661 	if (ring->xsk_pool) {
3662 		xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
3663 		ok = i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring));
3664 	} else {
3665 		ok = !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3666 	}
3667 	if (!ok) {
3668 		/* Log this in case the user has forgotten to give the kernel
3669 		 * any buffers, even later in the application.
3670 		 */
3671 		dev_info(&vsi->back->pdev->dev,
3672 			 "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3673 			 ring->xsk_pool ? "AF_XDP ZC enabled " : "",
3674 			 ring->queue_index, pf_q);
3675 	}
3676 
3677 	return 0;
3678 }
3679 
3680 /**
3681  * i40e_vsi_configure_tx - Configure the VSI for Tx
3682  * @vsi: VSI structure describing this set of rings and resources
3683  *
3684  * Configure the Tx VSI for operation.
3685  **/
3686 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3687 {
3688 	int err = 0;
3689 	u16 i;
3690 
3691 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3692 		err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3693 
3694 	if (err || !i40e_enabled_xdp_vsi(vsi))
3695 		return err;
3696 
3697 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3698 		err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3699 
3700 	return err;
3701 }
3702 
3703 /**
3704  * i40e_vsi_configure_rx - Configure the VSI for Rx
3705  * @vsi: the VSI being configured
3706  *
3707  * Configure the Rx VSI for operation.
3708  **/
3709 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3710 {
3711 	int err = 0;
3712 	u16 i;
3713 
3714 	if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX)) {
3715 		vsi->max_frame = I40E_MAX_RXBUFFER;
3716 		vsi->rx_buf_len = I40E_RXBUFFER_2048;
3717 #if (PAGE_SIZE < 8192)
3718 	} else if (!I40E_2K_TOO_SMALL_WITH_PADDING &&
3719 		   (vsi->netdev->mtu <= ETH_DATA_LEN)) {
3720 		vsi->max_frame = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3721 		vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3722 #endif
3723 	} else {
3724 		vsi->max_frame = I40E_MAX_RXBUFFER;
3725 		vsi->rx_buf_len = (PAGE_SIZE < 8192) ? I40E_RXBUFFER_3072 :
3726 						       I40E_RXBUFFER_2048;
3727 	}
3728 
3729 	/* set up individual rings */
3730 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3731 		err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3732 
3733 	return err;
3734 }
3735 
3736 /**
3737  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3738  * @vsi: ptr to the VSI
3739  **/
3740 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3741 {
3742 	struct i40e_ring *tx_ring, *rx_ring;
3743 	u16 qoffset, qcount;
3744 	int i, n;
3745 
3746 	if (!(vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
3747 		/* Reset the TC information */
3748 		for (i = 0; i < vsi->num_queue_pairs; i++) {
3749 			rx_ring = vsi->rx_rings[i];
3750 			tx_ring = vsi->tx_rings[i];
3751 			rx_ring->dcb_tc = 0;
3752 			tx_ring->dcb_tc = 0;
3753 		}
3754 		return;
3755 	}
3756 
3757 	for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3758 		if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3759 			continue;
3760 
3761 		qoffset = vsi->tc_config.tc_info[n].qoffset;
3762 		qcount = vsi->tc_config.tc_info[n].qcount;
3763 		for (i = qoffset; i < (qoffset + qcount); i++) {
3764 			rx_ring = vsi->rx_rings[i];
3765 			tx_ring = vsi->tx_rings[i];
3766 			rx_ring->dcb_tc = n;
3767 			tx_ring->dcb_tc = n;
3768 		}
3769 	}
3770 }
3771 
3772 /**
3773  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3774  * @vsi: ptr to the VSI
3775  **/
3776 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3777 {
3778 	if (vsi->netdev)
3779 		i40e_set_rx_mode(vsi->netdev);
3780 }
3781 
3782 /**
3783  * i40e_reset_fdir_filter_cnt - Reset flow director filter counters
3784  * @pf: Pointer to the targeted PF
3785  *
3786  * Set all flow director counters to 0.
3787  */
3788 static void i40e_reset_fdir_filter_cnt(struct i40e_pf *pf)
3789 {
3790 	pf->fd_tcp4_filter_cnt = 0;
3791 	pf->fd_udp4_filter_cnt = 0;
3792 	pf->fd_sctp4_filter_cnt = 0;
3793 	pf->fd_ip4_filter_cnt = 0;
3794 	pf->fd_tcp6_filter_cnt = 0;
3795 	pf->fd_udp6_filter_cnt = 0;
3796 	pf->fd_sctp6_filter_cnt = 0;
3797 	pf->fd_ip6_filter_cnt = 0;
3798 }
3799 
3800 /**
3801  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3802  * @vsi: Pointer to the targeted VSI
3803  *
3804  * This function replays the hlist on the hw where all the SB Flow Director
3805  * filters were saved.
3806  **/
3807 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3808 {
3809 	struct i40e_fdir_filter *filter;
3810 	struct i40e_pf *pf = vsi->back;
3811 	struct hlist_node *node;
3812 
3813 	if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
3814 		return;
3815 
3816 	/* Reset FDir counters as we're replaying all existing filters */
3817 	i40e_reset_fdir_filter_cnt(pf);
3818 
3819 	hlist_for_each_entry_safe(filter, node,
3820 				  &pf->fdir_filter_list, fdir_node) {
3821 		i40e_add_del_fdir(vsi, filter, true);
3822 	}
3823 }
3824 
3825 /**
3826  * i40e_vsi_configure - Set up the VSI for action
3827  * @vsi: the VSI being configured
3828  **/
3829 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3830 {
3831 	int err;
3832 
3833 	i40e_set_vsi_rx_mode(vsi);
3834 	i40e_restore_vlan(vsi);
3835 	i40e_vsi_config_dcb_rings(vsi);
3836 	err = i40e_vsi_configure_tx(vsi);
3837 	if (!err)
3838 		err = i40e_vsi_configure_rx(vsi);
3839 
3840 	return err;
3841 }
3842 
3843 /**
3844  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3845  * @vsi: the VSI being configured
3846  **/
3847 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3848 {
3849 	bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3850 	struct i40e_pf *pf = vsi->back;
3851 	struct i40e_hw *hw = &pf->hw;
3852 	u16 vector;
3853 	int i, q;
3854 	u32 qp;
3855 
3856 	/* The interrupt indexing is offset by 1 in the PFINT_ITRn
3857 	 * and PFINT_LNKLSTn registers, e.g.:
3858 	 *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3859 	 */
3860 	qp = vsi->base_queue;
3861 	vector = vsi->base_vector;
3862 	for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3863 		struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3864 
3865 		q_vector->rx.next_update = jiffies + 1;
3866 		q_vector->rx.target_itr =
3867 			ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3868 		wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3869 		     q_vector->rx.target_itr >> 1);
3870 		q_vector->rx.current_itr = q_vector->rx.target_itr;
3871 
3872 		q_vector->tx.next_update = jiffies + 1;
3873 		q_vector->tx.target_itr =
3874 			ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3875 		wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3876 		     q_vector->tx.target_itr >> 1);
3877 		q_vector->tx.current_itr = q_vector->tx.target_itr;
3878 
3879 		wr32(hw, I40E_PFINT_RATEN(vector - 1),
3880 		     i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3881 
3882 		/* begin of linked list for RX queue assigned to this vector */
3883 		wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3884 		for (q = 0; q < q_vector->num_ringpairs; q++) {
3885 			u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3886 			u32 val;
3887 
3888 			val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3889 			      (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3890 			      (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3891 			      (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3892 			      (I40E_QUEUE_TYPE_TX <<
3893 			       I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3894 
3895 			wr32(hw, I40E_QINT_RQCTL(qp), val);
3896 
3897 			if (has_xdp) {
3898 				/* TX queue with next queue set to TX */
3899 				val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3900 				      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3901 				      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3902 				      (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3903 				      (I40E_QUEUE_TYPE_TX <<
3904 				       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3905 
3906 				wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3907 			}
3908 			/* TX queue with next RX or end of linked list */
3909 			val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3910 			      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3911 			      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3912 			      ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3913 			      (I40E_QUEUE_TYPE_RX <<
3914 			       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3915 
3916 			/* Terminate the linked list */
3917 			if (q == (q_vector->num_ringpairs - 1))
3918 				val |= (I40E_QUEUE_END_OF_LIST <<
3919 					I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3920 
3921 			wr32(hw, I40E_QINT_TQCTL(qp), val);
3922 			qp++;
3923 		}
3924 	}
3925 
3926 	i40e_flush(hw);
3927 }
3928 
3929 /**
3930  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3931  * @pf: pointer to private device data structure
3932  **/
3933 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3934 {
3935 	struct i40e_hw *hw = &pf->hw;
3936 	u32 val;
3937 
3938 	/* clear things first */
3939 	wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3940 	rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3941 
3942 	val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3943 	      I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3944 	      I40E_PFINT_ICR0_ENA_GRST_MASK          |
3945 	      I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3946 	      I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3947 	      I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3948 	      I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3949 	      I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3950 
3951 	if (pf->flags & I40E_FLAG_IWARP_ENABLED)
3952 		val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3953 
3954 	if (pf->flags & I40E_FLAG_PTP)
3955 		val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3956 
3957 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
3958 
3959 	/* SW_ITR_IDX = 0, but don't change INTENA */
3960 	wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3961 					I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
3962 
3963 	/* OTHER_ITR_IDX = 0 */
3964 	wr32(hw, I40E_PFINT_STAT_CTL0, 0);
3965 }
3966 
3967 /**
3968  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
3969  * @vsi: the VSI being configured
3970  **/
3971 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
3972 {
3973 	u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
3974 	struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3975 	struct i40e_pf *pf = vsi->back;
3976 	struct i40e_hw *hw = &pf->hw;
3977 
3978 	/* set the ITR configuration */
3979 	q_vector->rx.next_update = jiffies + 1;
3980 	q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
3981 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr >> 1);
3982 	q_vector->rx.current_itr = q_vector->rx.target_itr;
3983 	q_vector->tx.next_update = jiffies + 1;
3984 	q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
3985 	wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr >> 1);
3986 	q_vector->tx.current_itr = q_vector->tx.target_itr;
3987 
3988 	i40e_enable_misc_int_causes(pf);
3989 
3990 	/* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
3991 	wr32(hw, I40E_PFINT_LNKLST0, 0);
3992 
3993 	/* Associate the queue pair to the vector and enable the queue
3994 	 * interrupt RX queue in linked list with next queue set to TX
3995 	 */
3996 	wr32(hw, I40E_QINT_RQCTL(0), I40E_QINT_RQCTL_VAL(nextqp, 0, TX));
3997 
3998 	if (i40e_enabled_xdp_vsi(vsi)) {
3999 		/* TX queue in linked list with next queue set to TX */
4000 		wr32(hw, I40E_QINT_TQCTL(nextqp),
4001 		     I40E_QINT_TQCTL_VAL(nextqp, 0, TX));
4002 	}
4003 
4004 	/* last TX queue so the next RX queue doesn't matter */
4005 	wr32(hw, I40E_QINT_TQCTL(0),
4006 	     I40E_QINT_TQCTL_VAL(I40E_QUEUE_END_OF_LIST, 0, RX));
4007 	i40e_flush(hw);
4008 }
4009 
4010 /**
4011  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
4012  * @pf: board private structure
4013  **/
4014 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
4015 {
4016 	struct i40e_hw *hw = &pf->hw;
4017 
4018 	wr32(hw, I40E_PFINT_DYN_CTL0,
4019 	     I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
4020 	i40e_flush(hw);
4021 }
4022 
4023 /**
4024  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
4025  * @pf: board private structure
4026  **/
4027 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
4028 {
4029 	struct i40e_hw *hw = &pf->hw;
4030 	u32 val;
4031 
4032 	val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
4033 	      I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
4034 	      (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
4035 
4036 	wr32(hw, I40E_PFINT_DYN_CTL0, val);
4037 	i40e_flush(hw);
4038 }
4039 
4040 /**
4041  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
4042  * @irq: interrupt number
4043  * @data: pointer to a q_vector
4044  **/
4045 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
4046 {
4047 	struct i40e_q_vector *q_vector = data;
4048 
4049 	if (!q_vector->tx.ring && !q_vector->rx.ring)
4050 		return IRQ_HANDLED;
4051 
4052 	napi_schedule_irqoff(&q_vector->napi);
4053 
4054 	return IRQ_HANDLED;
4055 }
4056 
4057 /**
4058  * i40e_irq_affinity_notify - Callback for affinity changes
4059  * @notify: context as to what irq was changed
4060  * @mask: the new affinity mask
4061  *
4062  * This is a callback function used by the irq_set_affinity_notifier function
4063  * so that we may register to receive changes to the irq affinity masks.
4064  **/
4065 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
4066 				     const cpumask_t *mask)
4067 {
4068 	struct i40e_q_vector *q_vector =
4069 		container_of(notify, struct i40e_q_vector, affinity_notify);
4070 
4071 	cpumask_copy(&q_vector->affinity_mask, mask);
4072 }
4073 
4074 /**
4075  * i40e_irq_affinity_release - Callback for affinity notifier release
4076  * @ref: internal core kernel usage
4077  *
4078  * This is a callback function used by the irq_set_affinity_notifier function
4079  * to inform the current notification subscriber that they will no longer
4080  * receive notifications.
4081  **/
4082 static void i40e_irq_affinity_release(struct kref *ref) {}
4083 
4084 /**
4085  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
4086  * @vsi: the VSI being configured
4087  * @basename: name for the vector
4088  *
4089  * Allocates MSI-X vectors and requests interrupts from the kernel.
4090  **/
4091 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
4092 {
4093 	int q_vectors = vsi->num_q_vectors;
4094 	struct i40e_pf *pf = vsi->back;
4095 	int base = vsi->base_vector;
4096 	int rx_int_idx = 0;
4097 	int tx_int_idx = 0;
4098 	int vector, err;
4099 	int irq_num;
4100 	int cpu;
4101 
4102 	for (vector = 0; vector < q_vectors; vector++) {
4103 		struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
4104 
4105 		irq_num = pf->msix_entries[base + vector].vector;
4106 
4107 		if (q_vector->tx.ring && q_vector->rx.ring) {
4108 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4109 				 "%s-%s-%d", basename, "TxRx", rx_int_idx++);
4110 			tx_int_idx++;
4111 		} else if (q_vector->rx.ring) {
4112 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4113 				 "%s-%s-%d", basename, "rx", rx_int_idx++);
4114 		} else if (q_vector->tx.ring) {
4115 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4116 				 "%s-%s-%d", basename, "tx", tx_int_idx++);
4117 		} else {
4118 			/* skip this unused q_vector */
4119 			continue;
4120 		}
4121 		err = request_irq(irq_num,
4122 				  vsi->irq_handler,
4123 				  0,
4124 				  q_vector->name,
4125 				  q_vector);
4126 		if (err) {
4127 			dev_info(&pf->pdev->dev,
4128 				 "MSIX request_irq failed, error: %d\n", err);
4129 			goto free_queue_irqs;
4130 		}
4131 
4132 		/* register for affinity change notifications */
4133 		q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
4134 		q_vector->affinity_notify.release = i40e_irq_affinity_release;
4135 		irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
4136 		/* Spread affinity hints out across online CPUs.
4137 		 *
4138 		 * get_cpu_mask returns a static constant mask with
4139 		 * a permanent lifetime so it's ok to pass to
4140 		 * irq_update_affinity_hint without making a copy.
4141 		 */
4142 		cpu = cpumask_local_spread(q_vector->v_idx, -1);
4143 		irq_update_affinity_hint(irq_num, get_cpu_mask(cpu));
4144 	}
4145 
4146 	vsi->irqs_ready = true;
4147 	return 0;
4148 
4149 free_queue_irqs:
4150 	while (vector) {
4151 		vector--;
4152 		irq_num = pf->msix_entries[base + vector].vector;
4153 		irq_set_affinity_notifier(irq_num, NULL);
4154 		irq_update_affinity_hint(irq_num, NULL);
4155 		free_irq(irq_num, &vsi->q_vectors[vector]);
4156 	}
4157 	return err;
4158 }
4159 
4160 /**
4161  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
4162  * @vsi: the VSI being un-configured
4163  **/
4164 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
4165 {
4166 	struct i40e_pf *pf = vsi->back;
4167 	struct i40e_hw *hw = &pf->hw;
4168 	int base = vsi->base_vector;
4169 	int i;
4170 
4171 	/* disable interrupt causation from each queue */
4172 	for (i = 0; i < vsi->num_queue_pairs; i++) {
4173 		u32 val;
4174 
4175 		val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
4176 		val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
4177 		wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
4178 
4179 		val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
4180 		val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
4181 		wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
4182 
4183 		if (!i40e_enabled_xdp_vsi(vsi))
4184 			continue;
4185 		wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
4186 	}
4187 
4188 	/* disable each interrupt */
4189 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4190 		for (i = vsi->base_vector;
4191 		     i < (vsi->num_q_vectors + vsi->base_vector); i++)
4192 			wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
4193 
4194 		i40e_flush(hw);
4195 		for (i = 0; i < vsi->num_q_vectors; i++)
4196 			synchronize_irq(pf->msix_entries[i + base].vector);
4197 	} else {
4198 		/* Legacy and MSI mode - this stops all interrupt handling */
4199 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
4200 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
4201 		i40e_flush(hw);
4202 		synchronize_irq(pf->pdev->irq);
4203 	}
4204 }
4205 
4206 /**
4207  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
4208  * @vsi: the VSI being configured
4209  **/
4210 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
4211 {
4212 	struct i40e_pf *pf = vsi->back;
4213 	int i;
4214 
4215 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4216 		for (i = 0; i < vsi->num_q_vectors; i++)
4217 			i40e_irq_dynamic_enable(vsi, i);
4218 	} else {
4219 		i40e_irq_dynamic_enable_icr0(pf);
4220 	}
4221 
4222 	i40e_flush(&pf->hw);
4223 	return 0;
4224 }
4225 
4226 /**
4227  * i40e_free_misc_vector - Free the vector that handles non-queue events
4228  * @pf: board private structure
4229  **/
4230 static void i40e_free_misc_vector(struct i40e_pf *pf)
4231 {
4232 	/* Disable ICR 0 */
4233 	wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
4234 	i40e_flush(&pf->hw);
4235 
4236 	if (pf->flags & I40E_FLAG_MSIX_ENABLED && pf->msix_entries) {
4237 		free_irq(pf->msix_entries[0].vector, pf);
4238 		clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
4239 	}
4240 }
4241 
4242 /**
4243  * i40e_intr - MSI/Legacy and non-queue interrupt handler
4244  * @irq: interrupt number
4245  * @data: pointer to a q_vector
4246  *
4247  * This is the handler used for all MSI/Legacy interrupts, and deals
4248  * with both queue and non-queue interrupts.  This is also used in
4249  * MSIX mode to handle the non-queue interrupts.
4250  **/
4251 static irqreturn_t i40e_intr(int irq, void *data)
4252 {
4253 	struct i40e_pf *pf = (struct i40e_pf *)data;
4254 	struct i40e_hw *hw = &pf->hw;
4255 	irqreturn_t ret = IRQ_NONE;
4256 	u32 icr0, icr0_remaining;
4257 	u32 val, ena_mask;
4258 
4259 	icr0 = rd32(hw, I40E_PFINT_ICR0);
4260 	ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
4261 
4262 	/* if sharing a legacy IRQ, we might get called w/o an intr pending */
4263 	if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
4264 		goto enable_intr;
4265 
4266 	/* if interrupt but no bits showing, must be SWINT */
4267 	if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
4268 	    (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
4269 		pf->sw_int_count++;
4270 
4271 	if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
4272 	    (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
4273 		ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4274 		dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
4275 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
4276 	}
4277 
4278 	/* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
4279 	if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
4280 		struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
4281 		struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4282 
4283 		/* We do not have a way to disarm Queue causes while leaving
4284 		 * interrupt enabled for all other causes, ideally
4285 		 * interrupt should be disabled while we are in NAPI but
4286 		 * this is not a performance path and napi_schedule()
4287 		 * can deal with rescheduling.
4288 		 */
4289 		if (!test_bit(__I40E_DOWN, pf->state))
4290 			napi_schedule_irqoff(&q_vector->napi);
4291 	}
4292 
4293 	if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
4294 		ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
4295 		set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
4296 		i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
4297 	}
4298 
4299 	if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
4300 		ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
4301 		set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
4302 	}
4303 
4304 	if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
4305 		/* disable any further VFLR event notifications */
4306 		if (test_bit(__I40E_VF_RESETS_DISABLED, pf->state)) {
4307 			u32 reg = rd32(hw, I40E_PFINT_ICR0_ENA);
4308 
4309 			reg &= ~I40E_PFINT_ICR0_VFLR_MASK;
4310 			wr32(hw, I40E_PFINT_ICR0_ENA, reg);
4311 		} else {
4312 			ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
4313 			set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
4314 		}
4315 	}
4316 
4317 	if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
4318 		if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4319 			set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
4320 		ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
4321 		val = rd32(hw, I40E_GLGEN_RSTAT);
4322 		val = (val & I40E_GLGEN_RSTAT_RESET_TYPE_MASK)
4323 		       >> I40E_GLGEN_RSTAT_RESET_TYPE_SHIFT;
4324 		if (val == I40E_RESET_CORER) {
4325 			pf->corer_count++;
4326 		} else if (val == I40E_RESET_GLOBR) {
4327 			pf->globr_count++;
4328 		} else if (val == I40E_RESET_EMPR) {
4329 			pf->empr_count++;
4330 			set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
4331 		}
4332 	}
4333 
4334 	if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
4335 		icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
4336 		dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4337 		dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4338 			 rd32(hw, I40E_PFHMC_ERRORINFO),
4339 			 rd32(hw, I40E_PFHMC_ERRORDATA));
4340 	}
4341 
4342 	if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4343 		u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4344 
4345 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_EVENT0_MASK)
4346 			schedule_work(&pf->ptp_extts0_work);
4347 
4348 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK)
4349 			i40e_ptp_tx_hwtstamp(pf);
4350 
4351 		icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4352 	}
4353 
4354 	/* If a critical error is pending we have no choice but to reset the
4355 	 * device.
4356 	 * Report and mask out any remaining unexpected interrupts.
4357 	 */
4358 	icr0_remaining = icr0 & ena_mask;
4359 	if (icr0_remaining) {
4360 		dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4361 			 icr0_remaining);
4362 		if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4363 		    (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4364 		    (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4365 			dev_info(&pf->pdev->dev, "device will be reset\n");
4366 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4367 			i40e_service_event_schedule(pf);
4368 		}
4369 		ena_mask &= ~icr0_remaining;
4370 	}
4371 	ret = IRQ_HANDLED;
4372 
4373 enable_intr:
4374 	/* re-enable interrupt causes */
4375 	wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4376 	if (!test_bit(__I40E_DOWN, pf->state) ||
4377 	    test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4378 		i40e_service_event_schedule(pf);
4379 		i40e_irq_dynamic_enable_icr0(pf);
4380 	}
4381 
4382 	return ret;
4383 }
4384 
4385 /**
4386  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4387  * @tx_ring:  tx ring to clean
4388  * @budget:   how many cleans we're allowed
4389  *
4390  * Returns true if there's any budget left (e.g. the clean is finished)
4391  **/
4392 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4393 {
4394 	struct i40e_vsi *vsi = tx_ring->vsi;
4395 	u16 i = tx_ring->next_to_clean;
4396 	struct i40e_tx_buffer *tx_buf;
4397 	struct i40e_tx_desc *tx_desc;
4398 
4399 	tx_buf = &tx_ring->tx_bi[i];
4400 	tx_desc = I40E_TX_DESC(tx_ring, i);
4401 	i -= tx_ring->count;
4402 
4403 	do {
4404 		struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4405 
4406 		/* if next_to_watch is not set then there is no work pending */
4407 		if (!eop_desc)
4408 			break;
4409 
4410 		/* prevent any other reads prior to eop_desc */
4411 		smp_rmb();
4412 
4413 		/* if the descriptor isn't done, no work yet to do */
4414 		if (!(eop_desc->cmd_type_offset_bsz &
4415 		      cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4416 			break;
4417 
4418 		/* clear next_to_watch to prevent false hangs */
4419 		tx_buf->next_to_watch = NULL;
4420 
4421 		tx_desc->buffer_addr = 0;
4422 		tx_desc->cmd_type_offset_bsz = 0;
4423 		/* move past filter desc */
4424 		tx_buf++;
4425 		tx_desc++;
4426 		i++;
4427 		if (unlikely(!i)) {
4428 			i -= tx_ring->count;
4429 			tx_buf = tx_ring->tx_bi;
4430 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4431 		}
4432 		/* unmap skb header data */
4433 		dma_unmap_single(tx_ring->dev,
4434 				 dma_unmap_addr(tx_buf, dma),
4435 				 dma_unmap_len(tx_buf, len),
4436 				 DMA_TO_DEVICE);
4437 		if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4438 			kfree(tx_buf->raw_buf);
4439 
4440 		tx_buf->raw_buf = NULL;
4441 		tx_buf->tx_flags = 0;
4442 		tx_buf->next_to_watch = NULL;
4443 		dma_unmap_len_set(tx_buf, len, 0);
4444 		tx_desc->buffer_addr = 0;
4445 		tx_desc->cmd_type_offset_bsz = 0;
4446 
4447 		/* move us past the eop_desc for start of next FD desc */
4448 		tx_buf++;
4449 		tx_desc++;
4450 		i++;
4451 		if (unlikely(!i)) {
4452 			i -= tx_ring->count;
4453 			tx_buf = tx_ring->tx_bi;
4454 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4455 		}
4456 
4457 		/* update budget accounting */
4458 		budget--;
4459 	} while (likely(budget));
4460 
4461 	i += tx_ring->count;
4462 	tx_ring->next_to_clean = i;
4463 
4464 	if (vsi->back->flags & I40E_FLAG_MSIX_ENABLED)
4465 		i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4466 
4467 	return budget > 0;
4468 }
4469 
4470 /**
4471  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4472  * @irq: interrupt number
4473  * @data: pointer to a q_vector
4474  **/
4475 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4476 {
4477 	struct i40e_q_vector *q_vector = data;
4478 	struct i40e_vsi *vsi;
4479 
4480 	if (!q_vector->tx.ring)
4481 		return IRQ_HANDLED;
4482 
4483 	vsi = q_vector->tx.ring->vsi;
4484 	i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4485 
4486 	return IRQ_HANDLED;
4487 }
4488 
4489 /**
4490  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4491  * @vsi: the VSI being configured
4492  * @v_idx: vector index
4493  * @qp_idx: queue pair index
4494  **/
4495 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4496 {
4497 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4498 	struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4499 	struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4500 
4501 	tx_ring->q_vector = q_vector;
4502 	tx_ring->next = q_vector->tx.ring;
4503 	q_vector->tx.ring = tx_ring;
4504 	q_vector->tx.count++;
4505 
4506 	/* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4507 	if (i40e_enabled_xdp_vsi(vsi)) {
4508 		struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4509 
4510 		xdp_ring->q_vector = q_vector;
4511 		xdp_ring->next = q_vector->tx.ring;
4512 		q_vector->tx.ring = xdp_ring;
4513 		q_vector->tx.count++;
4514 	}
4515 
4516 	rx_ring->q_vector = q_vector;
4517 	rx_ring->next = q_vector->rx.ring;
4518 	q_vector->rx.ring = rx_ring;
4519 	q_vector->rx.count++;
4520 }
4521 
4522 /**
4523  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4524  * @vsi: the VSI being configured
4525  *
4526  * This function maps descriptor rings to the queue-specific vectors
4527  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4528  * one vector per queue pair, but on a constrained vector budget, we
4529  * group the queue pairs as "efficiently" as possible.
4530  **/
4531 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4532 {
4533 	int qp_remaining = vsi->num_queue_pairs;
4534 	int q_vectors = vsi->num_q_vectors;
4535 	int num_ringpairs;
4536 	int v_start = 0;
4537 	int qp_idx = 0;
4538 
4539 	/* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4540 	 * group them so there are multiple queues per vector.
4541 	 * It is also important to go through all the vectors available to be
4542 	 * sure that if we don't use all the vectors, that the remaining vectors
4543 	 * are cleared. This is especially important when decreasing the
4544 	 * number of queues in use.
4545 	 */
4546 	for (; v_start < q_vectors; v_start++) {
4547 		struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4548 
4549 		num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4550 
4551 		q_vector->num_ringpairs = num_ringpairs;
4552 		q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4553 
4554 		q_vector->rx.count = 0;
4555 		q_vector->tx.count = 0;
4556 		q_vector->rx.ring = NULL;
4557 		q_vector->tx.ring = NULL;
4558 
4559 		while (num_ringpairs--) {
4560 			i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4561 			qp_idx++;
4562 			qp_remaining--;
4563 		}
4564 	}
4565 }
4566 
4567 /**
4568  * i40e_vsi_request_irq - Request IRQ from the OS
4569  * @vsi: the VSI being configured
4570  * @basename: name for the vector
4571  **/
4572 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4573 {
4574 	struct i40e_pf *pf = vsi->back;
4575 	int err;
4576 
4577 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
4578 		err = i40e_vsi_request_irq_msix(vsi, basename);
4579 	else if (pf->flags & I40E_FLAG_MSI_ENABLED)
4580 		err = request_irq(pf->pdev->irq, i40e_intr, 0,
4581 				  pf->int_name, pf);
4582 	else
4583 		err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4584 				  pf->int_name, pf);
4585 
4586 	if (err)
4587 		dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4588 
4589 	return err;
4590 }
4591 
4592 #ifdef CONFIG_NET_POLL_CONTROLLER
4593 /**
4594  * i40e_netpoll - A Polling 'interrupt' handler
4595  * @netdev: network interface device structure
4596  *
4597  * This is used by netconsole to send skbs without having to re-enable
4598  * interrupts.  It's not called while the normal interrupt routine is executing.
4599  **/
4600 static void i40e_netpoll(struct net_device *netdev)
4601 {
4602 	struct i40e_netdev_priv *np = netdev_priv(netdev);
4603 	struct i40e_vsi *vsi = np->vsi;
4604 	struct i40e_pf *pf = vsi->back;
4605 	int i;
4606 
4607 	/* if interface is down do nothing */
4608 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
4609 		return;
4610 
4611 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4612 		for (i = 0; i < vsi->num_q_vectors; i++)
4613 			i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4614 	} else {
4615 		i40e_intr(pf->pdev->irq, netdev);
4616 	}
4617 }
4618 #endif
4619 
4620 #define I40E_QTX_ENA_WAIT_COUNT 50
4621 
4622 /**
4623  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4624  * @pf: the PF being configured
4625  * @pf_q: the PF queue
4626  * @enable: enable or disable state of the queue
4627  *
4628  * This routine will wait for the given Tx queue of the PF to reach the
4629  * enabled or disabled state.
4630  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4631  * multiple retries; else will return 0 in case of success.
4632  **/
4633 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4634 {
4635 	int i;
4636 	u32 tx_reg;
4637 
4638 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4639 		tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4640 		if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4641 			break;
4642 
4643 		usleep_range(10, 20);
4644 	}
4645 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4646 		return -ETIMEDOUT;
4647 
4648 	return 0;
4649 }
4650 
4651 /**
4652  * i40e_control_tx_q - Start or stop a particular Tx queue
4653  * @pf: the PF structure
4654  * @pf_q: the PF queue to configure
4655  * @enable: start or stop the queue
4656  *
4657  * This function enables or disables a single queue. Note that any delay
4658  * required after the operation is expected to be handled by the caller of
4659  * this function.
4660  **/
4661 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4662 {
4663 	struct i40e_hw *hw = &pf->hw;
4664 	u32 tx_reg;
4665 	int i;
4666 
4667 	/* warn the TX unit of coming changes */
4668 	i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4669 	if (!enable)
4670 		usleep_range(10, 20);
4671 
4672 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4673 		tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4674 		if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4675 		    ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4676 			break;
4677 		usleep_range(1000, 2000);
4678 	}
4679 
4680 	/* Skip if the queue is already in the requested state */
4681 	if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4682 		return;
4683 
4684 	/* turn on/off the queue */
4685 	if (enable) {
4686 		wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4687 		tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4688 	} else {
4689 		tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4690 	}
4691 
4692 	wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4693 }
4694 
4695 /**
4696  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4697  * @seid: VSI SEID
4698  * @pf: the PF structure
4699  * @pf_q: the PF queue to configure
4700  * @is_xdp: true if the queue is used for XDP
4701  * @enable: start or stop the queue
4702  **/
4703 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4704 			   bool is_xdp, bool enable)
4705 {
4706 	int ret;
4707 
4708 	i40e_control_tx_q(pf, pf_q, enable);
4709 
4710 	/* wait for the change to finish */
4711 	ret = i40e_pf_txq_wait(pf, pf_q, enable);
4712 	if (ret) {
4713 		dev_info(&pf->pdev->dev,
4714 			 "VSI seid %d %sTx ring %d %sable timeout\n",
4715 			 seid, (is_xdp ? "XDP " : ""), pf_q,
4716 			 (enable ? "en" : "dis"));
4717 	}
4718 
4719 	return ret;
4720 }
4721 
4722 /**
4723  * i40e_vsi_enable_tx - Start a VSI's rings
4724  * @vsi: the VSI being configured
4725  **/
4726 static int i40e_vsi_enable_tx(struct i40e_vsi *vsi)
4727 {
4728 	struct i40e_pf *pf = vsi->back;
4729 	int i, pf_q, ret = 0;
4730 
4731 	pf_q = vsi->base_queue;
4732 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4733 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4734 					     pf_q,
4735 					     false /*is xdp*/, true);
4736 		if (ret)
4737 			break;
4738 
4739 		if (!i40e_enabled_xdp_vsi(vsi))
4740 			continue;
4741 
4742 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4743 					     pf_q + vsi->alloc_queue_pairs,
4744 					     true /*is xdp*/, true);
4745 		if (ret)
4746 			break;
4747 	}
4748 	return ret;
4749 }
4750 
4751 /**
4752  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4753  * @pf: the PF being configured
4754  * @pf_q: the PF queue
4755  * @enable: enable or disable state of the queue
4756  *
4757  * This routine will wait for the given Rx queue of the PF to reach the
4758  * enabled or disabled state.
4759  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4760  * multiple retries; else will return 0 in case of success.
4761  **/
4762 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4763 {
4764 	int i;
4765 	u32 rx_reg;
4766 
4767 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4768 		rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4769 		if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4770 			break;
4771 
4772 		usleep_range(10, 20);
4773 	}
4774 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4775 		return -ETIMEDOUT;
4776 
4777 	return 0;
4778 }
4779 
4780 /**
4781  * i40e_control_rx_q - Start or stop a particular Rx queue
4782  * @pf: the PF structure
4783  * @pf_q: the PF queue to configure
4784  * @enable: start or stop the queue
4785  *
4786  * This function enables or disables a single queue. Note that
4787  * any delay required after the operation is expected to be
4788  * handled by the caller of this function.
4789  **/
4790 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4791 {
4792 	struct i40e_hw *hw = &pf->hw;
4793 	u32 rx_reg;
4794 	int i;
4795 
4796 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4797 		rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4798 		if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4799 		    ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4800 			break;
4801 		usleep_range(1000, 2000);
4802 	}
4803 
4804 	/* Skip if the queue is already in the requested state */
4805 	if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4806 		return;
4807 
4808 	/* turn on/off the queue */
4809 	if (enable)
4810 		rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4811 	else
4812 		rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4813 
4814 	wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4815 }
4816 
4817 /**
4818  * i40e_control_wait_rx_q
4819  * @pf: the PF structure
4820  * @pf_q: queue being configured
4821  * @enable: start or stop the rings
4822  *
4823  * This function enables or disables a single queue along with waiting
4824  * for the change to finish. The caller of this function should handle
4825  * the delays needed in the case of disabling queues.
4826  **/
4827 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4828 {
4829 	int ret = 0;
4830 
4831 	i40e_control_rx_q(pf, pf_q, enable);
4832 
4833 	/* wait for the change to finish */
4834 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4835 	if (ret)
4836 		return ret;
4837 
4838 	return ret;
4839 }
4840 
4841 /**
4842  * i40e_vsi_enable_rx - Start a VSI's rings
4843  * @vsi: the VSI being configured
4844  **/
4845 static int i40e_vsi_enable_rx(struct i40e_vsi *vsi)
4846 {
4847 	struct i40e_pf *pf = vsi->back;
4848 	int i, pf_q, ret = 0;
4849 
4850 	pf_q = vsi->base_queue;
4851 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4852 		ret = i40e_control_wait_rx_q(pf, pf_q, true);
4853 		if (ret) {
4854 			dev_info(&pf->pdev->dev,
4855 				 "VSI seid %d Rx ring %d enable timeout\n",
4856 				 vsi->seid, pf_q);
4857 			break;
4858 		}
4859 	}
4860 
4861 	return ret;
4862 }
4863 
4864 /**
4865  * i40e_vsi_start_rings - Start a VSI's rings
4866  * @vsi: the VSI being configured
4867  **/
4868 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4869 {
4870 	int ret = 0;
4871 
4872 	/* do rx first for enable and last for disable */
4873 	ret = i40e_vsi_enable_rx(vsi);
4874 	if (ret)
4875 		return ret;
4876 	ret = i40e_vsi_enable_tx(vsi);
4877 
4878 	return ret;
4879 }
4880 
4881 #define I40E_DISABLE_TX_GAP_MSEC	50
4882 
4883 /**
4884  * i40e_vsi_stop_rings - Stop a VSI's rings
4885  * @vsi: the VSI being configured
4886  **/
4887 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4888 {
4889 	struct i40e_pf *pf = vsi->back;
4890 	int pf_q, err, q_end;
4891 
4892 	/* When port TX is suspended, don't wait */
4893 	if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4894 		return i40e_vsi_stop_rings_no_wait(vsi);
4895 
4896 	q_end = vsi->base_queue + vsi->num_queue_pairs;
4897 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4898 		i40e_pre_tx_queue_cfg(&pf->hw, (u32)pf_q, false);
4899 
4900 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++) {
4901 		err = i40e_control_wait_rx_q(pf, pf_q, false);
4902 		if (err)
4903 			dev_info(&pf->pdev->dev,
4904 				 "VSI seid %d Rx ring %d disable timeout\n",
4905 				 vsi->seid, pf_q);
4906 	}
4907 
4908 	msleep(I40E_DISABLE_TX_GAP_MSEC);
4909 	pf_q = vsi->base_queue;
4910 	for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4911 		wr32(&pf->hw, I40E_QTX_ENA(pf_q), 0);
4912 
4913 	i40e_vsi_wait_queues_disabled(vsi);
4914 }
4915 
4916 /**
4917  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4918  * @vsi: the VSI being shutdown
4919  *
4920  * This function stops all the rings for a VSI but does not delay to verify
4921  * that rings have been disabled. It is expected that the caller is shutting
4922  * down multiple VSIs at once and will delay together for all the VSIs after
4923  * initiating the shutdown. This is particularly useful for shutting down lots
4924  * of VFs together. Otherwise, a large delay can be incurred while configuring
4925  * each VSI in serial.
4926  **/
4927 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4928 {
4929 	struct i40e_pf *pf = vsi->back;
4930 	int i, pf_q;
4931 
4932 	pf_q = vsi->base_queue;
4933 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4934 		i40e_control_tx_q(pf, pf_q, false);
4935 		i40e_control_rx_q(pf, pf_q, false);
4936 	}
4937 }
4938 
4939 /**
4940  * i40e_vsi_free_irq - Free the irq association with the OS
4941  * @vsi: the VSI being configured
4942  **/
4943 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4944 {
4945 	struct i40e_pf *pf = vsi->back;
4946 	struct i40e_hw *hw = &pf->hw;
4947 	int base = vsi->base_vector;
4948 	u32 val, qp;
4949 	int i;
4950 
4951 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4952 		if (!vsi->q_vectors)
4953 			return;
4954 
4955 		if (!vsi->irqs_ready)
4956 			return;
4957 
4958 		vsi->irqs_ready = false;
4959 		for (i = 0; i < vsi->num_q_vectors; i++) {
4960 			int irq_num;
4961 			u16 vector;
4962 
4963 			vector = i + base;
4964 			irq_num = pf->msix_entries[vector].vector;
4965 
4966 			/* free only the irqs that were actually requested */
4967 			if (!vsi->q_vectors[i] ||
4968 			    !vsi->q_vectors[i]->num_ringpairs)
4969 				continue;
4970 
4971 			/* clear the affinity notifier in the IRQ descriptor */
4972 			irq_set_affinity_notifier(irq_num, NULL);
4973 			/* remove our suggested affinity mask for this IRQ */
4974 			irq_update_affinity_hint(irq_num, NULL);
4975 			free_irq(irq_num, vsi->q_vectors[i]);
4976 
4977 			/* Tear down the interrupt queue link list
4978 			 *
4979 			 * We know that they come in pairs and always
4980 			 * the Rx first, then the Tx.  To clear the
4981 			 * link list, stick the EOL value into the
4982 			 * next_q field of the registers.
4983 			 */
4984 			val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
4985 			qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4986 				>> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4987 			val |= I40E_QUEUE_END_OF_LIST
4988 				<< I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4989 			wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
4990 
4991 			while (qp != I40E_QUEUE_END_OF_LIST) {
4992 				u32 next;
4993 
4994 				val = rd32(hw, I40E_QINT_RQCTL(qp));
4995 
4996 				val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4997 					 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4998 					 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4999 					 I40E_QINT_RQCTL_INTEVENT_MASK);
5000 
5001 				val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5002 					 I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5003 
5004 				wr32(hw, I40E_QINT_RQCTL(qp), val);
5005 
5006 				val = rd32(hw, I40E_QINT_TQCTL(qp));
5007 
5008 				next = (val & I40E_QINT_TQCTL_NEXTQ_INDX_MASK)
5009 					>> I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT;
5010 
5011 				val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5012 					 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5013 					 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5014 					 I40E_QINT_TQCTL_INTEVENT_MASK);
5015 
5016 				val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5017 					 I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5018 
5019 				wr32(hw, I40E_QINT_TQCTL(qp), val);
5020 				qp = next;
5021 			}
5022 		}
5023 	} else {
5024 		free_irq(pf->pdev->irq, pf);
5025 
5026 		val = rd32(hw, I40E_PFINT_LNKLST0);
5027 		qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
5028 			>> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
5029 		val |= I40E_QUEUE_END_OF_LIST
5030 			<< I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
5031 		wr32(hw, I40E_PFINT_LNKLST0, val);
5032 
5033 		val = rd32(hw, I40E_QINT_RQCTL(qp));
5034 		val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5035 			 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5036 			 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5037 			 I40E_QINT_RQCTL_INTEVENT_MASK);
5038 
5039 		val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5040 			I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5041 
5042 		wr32(hw, I40E_QINT_RQCTL(qp), val);
5043 
5044 		val = rd32(hw, I40E_QINT_TQCTL(qp));
5045 
5046 		val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5047 			 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5048 			 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5049 			 I40E_QINT_TQCTL_INTEVENT_MASK);
5050 
5051 		val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5052 			I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5053 
5054 		wr32(hw, I40E_QINT_TQCTL(qp), val);
5055 	}
5056 }
5057 
5058 /**
5059  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
5060  * @vsi: the VSI being configured
5061  * @v_idx: Index of vector to be freed
5062  *
5063  * This function frees the memory allocated to the q_vector.  In addition if
5064  * NAPI is enabled it will delete any references to the NAPI struct prior
5065  * to freeing the q_vector.
5066  **/
5067 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
5068 {
5069 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
5070 	struct i40e_ring *ring;
5071 
5072 	if (!q_vector)
5073 		return;
5074 
5075 	/* disassociate q_vector from rings */
5076 	i40e_for_each_ring(ring, q_vector->tx)
5077 		ring->q_vector = NULL;
5078 
5079 	i40e_for_each_ring(ring, q_vector->rx)
5080 		ring->q_vector = NULL;
5081 
5082 	/* only VSI w/ an associated netdev is set up w/ NAPI */
5083 	if (vsi->netdev)
5084 		netif_napi_del(&q_vector->napi);
5085 
5086 	vsi->q_vectors[v_idx] = NULL;
5087 
5088 	kfree_rcu(q_vector, rcu);
5089 }
5090 
5091 /**
5092  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
5093  * @vsi: the VSI being un-configured
5094  *
5095  * This frees the memory allocated to the q_vectors and
5096  * deletes references to the NAPI struct.
5097  **/
5098 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
5099 {
5100 	int v_idx;
5101 
5102 	for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
5103 		i40e_free_q_vector(vsi, v_idx);
5104 }
5105 
5106 /**
5107  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
5108  * @pf: board private structure
5109  **/
5110 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
5111 {
5112 	/* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
5113 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
5114 		pci_disable_msix(pf->pdev);
5115 		kfree(pf->msix_entries);
5116 		pf->msix_entries = NULL;
5117 		kfree(pf->irq_pile);
5118 		pf->irq_pile = NULL;
5119 	} else if (pf->flags & I40E_FLAG_MSI_ENABLED) {
5120 		pci_disable_msi(pf->pdev);
5121 	}
5122 	pf->flags &= ~(I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
5123 }
5124 
5125 /**
5126  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
5127  * @pf: board private structure
5128  *
5129  * We go through and clear interrupt specific resources and reset the structure
5130  * to pre-load conditions
5131  **/
5132 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
5133 {
5134 	int i;
5135 
5136 	if (test_bit(__I40E_MISC_IRQ_REQUESTED, pf->state))
5137 		i40e_free_misc_vector(pf);
5138 
5139 	i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
5140 		      I40E_IWARP_IRQ_PILE_ID);
5141 
5142 	i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
5143 	for (i = 0; i < pf->num_alloc_vsi; i++)
5144 		if (pf->vsi[i])
5145 			i40e_vsi_free_q_vectors(pf->vsi[i]);
5146 	i40e_reset_interrupt_capability(pf);
5147 }
5148 
5149 /**
5150  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5151  * @vsi: the VSI being configured
5152  **/
5153 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
5154 {
5155 	int q_idx;
5156 
5157 	if (!vsi->netdev)
5158 		return;
5159 
5160 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5161 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5162 
5163 		if (q_vector->rx.ring || q_vector->tx.ring)
5164 			napi_enable(&q_vector->napi);
5165 	}
5166 }
5167 
5168 /**
5169  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
5170  * @vsi: the VSI being configured
5171  **/
5172 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
5173 {
5174 	int q_idx;
5175 
5176 	if (!vsi->netdev)
5177 		return;
5178 
5179 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5180 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5181 
5182 		if (q_vector->rx.ring || q_vector->tx.ring)
5183 			napi_disable(&q_vector->napi);
5184 	}
5185 }
5186 
5187 /**
5188  * i40e_vsi_close - Shut down a VSI
5189  * @vsi: the vsi to be quelled
5190  **/
5191 static void i40e_vsi_close(struct i40e_vsi *vsi)
5192 {
5193 	struct i40e_pf *pf = vsi->back;
5194 	if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
5195 		i40e_down(vsi);
5196 	i40e_vsi_free_irq(vsi);
5197 	i40e_vsi_free_tx_resources(vsi);
5198 	i40e_vsi_free_rx_resources(vsi);
5199 	vsi->current_netdev_flags = 0;
5200 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
5201 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
5202 		set_bit(__I40E_CLIENT_RESET, pf->state);
5203 }
5204 
5205 /**
5206  * i40e_quiesce_vsi - Pause a given VSI
5207  * @vsi: the VSI being paused
5208  **/
5209 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
5210 {
5211 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
5212 		return;
5213 
5214 	set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
5215 	if (vsi->netdev && netif_running(vsi->netdev))
5216 		vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
5217 	else
5218 		i40e_vsi_close(vsi);
5219 }
5220 
5221 /**
5222  * i40e_unquiesce_vsi - Resume a given VSI
5223  * @vsi: the VSI being resumed
5224  **/
5225 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
5226 {
5227 	if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
5228 		return;
5229 
5230 	if (vsi->netdev && netif_running(vsi->netdev))
5231 		vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
5232 	else
5233 		i40e_vsi_open(vsi);   /* this clears the DOWN bit */
5234 }
5235 
5236 /**
5237  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
5238  * @pf: the PF
5239  **/
5240 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
5241 {
5242 	int v;
5243 
5244 	for (v = 0; v < pf->num_alloc_vsi; v++) {
5245 		if (pf->vsi[v])
5246 			i40e_quiesce_vsi(pf->vsi[v]);
5247 	}
5248 }
5249 
5250 /**
5251  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
5252  * @pf: the PF
5253  **/
5254 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
5255 {
5256 	int v;
5257 
5258 	for (v = 0; v < pf->num_alloc_vsi; v++) {
5259 		if (pf->vsi[v])
5260 			i40e_unquiesce_vsi(pf->vsi[v]);
5261 	}
5262 }
5263 
5264 /**
5265  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
5266  * @vsi: the VSI being configured
5267  *
5268  * Wait until all queues on a given VSI have been disabled.
5269  **/
5270 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
5271 {
5272 	struct i40e_pf *pf = vsi->back;
5273 	int i, pf_q, ret;
5274 
5275 	pf_q = vsi->base_queue;
5276 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
5277 		/* Check and wait for the Tx queue */
5278 		ret = i40e_pf_txq_wait(pf, pf_q, false);
5279 		if (ret) {
5280 			dev_info(&pf->pdev->dev,
5281 				 "VSI seid %d Tx ring %d disable timeout\n",
5282 				 vsi->seid, pf_q);
5283 			return ret;
5284 		}
5285 
5286 		if (!i40e_enabled_xdp_vsi(vsi))
5287 			goto wait_rx;
5288 
5289 		/* Check and wait for the XDP Tx queue */
5290 		ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
5291 				       false);
5292 		if (ret) {
5293 			dev_info(&pf->pdev->dev,
5294 				 "VSI seid %d XDP Tx ring %d disable timeout\n",
5295 				 vsi->seid, pf_q);
5296 			return ret;
5297 		}
5298 wait_rx:
5299 		/* Check and wait for the Rx queue */
5300 		ret = i40e_pf_rxq_wait(pf, pf_q, false);
5301 		if (ret) {
5302 			dev_info(&pf->pdev->dev,
5303 				 "VSI seid %d Rx ring %d disable timeout\n",
5304 				 vsi->seid, pf_q);
5305 			return ret;
5306 		}
5307 	}
5308 
5309 	return 0;
5310 }
5311 
5312 #ifdef CONFIG_I40E_DCB
5313 /**
5314  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
5315  * @pf: the PF
5316  *
5317  * This function waits for the queues to be in disabled state for all the
5318  * VSIs that are managed by this PF.
5319  **/
5320 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
5321 {
5322 	int v, ret = 0;
5323 
5324 	for (v = 0; v < pf->hw.func_caps.num_vsis; v++) {
5325 		if (pf->vsi[v]) {
5326 			ret = i40e_vsi_wait_queues_disabled(pf->vsi[v]);
5327 			if (ret)
5328 				break;
5329 		}
5330 	}
5331 
5332 	return ret;
5333 }
5334 
5335 #endif
5336 
5337 /**
5338  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
5339  * @pf: pointer to PF
5340  *
5341  * Get TC map for ISCSI PF type that will include iSCSI TC
5342  * and LAN TC.
5343  **/
5344 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
5345 {
5346 	struct i40e_dcb_app_priority_table app;
5347 	struct i40e_hw *hw = &pf->hw;
5348 	u8 enabled_tc = 1; /* TC0 is always enabled */
5349 	u8 tc, i;
5350 	/* Get the iSCSI APP TLV */
5351 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5352 
5353 	for (i = 0; i < dcbcfg->numapps; i++) {
5354 		app = dcbcfg->app[i];
5355 		if (app.selector == I40E_APP_SEL_TCPIP &&
5356 		    app.protocolid == I40E_APP_PROTOID_ISCSI) {
5357 			tc = dcbcfg->etscfg.prioritytable[app.priority];
5358 			enabled_tc |= BIT(tc);
5359 			break;
5360 		}
5361 	}
5362 
5363 	return enabled_tc;
5364 }
5365 
5366 /**
5367  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5368  * @dcbcfg: the corresponding DCBx configuration structure
5369  *
5370  * Return the number of TCs from given DCBx configuration
5371  **/
5372 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5373 {
5374 	int i, tc_unused = 0;
5375 	u8 num_tc = 0;
5376 	u8 ret = 0;
5377 
5378 	/* Scan the ETS Config Priority Table to find
5379 	 * traffic class enabled for a given priority
5380 	 * and create a bitmask of enabled TCs
5381 	 */
5382 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5383 		num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5384 
5385 	/* Now scan the bitmask to check for
5386 	 * contiguous TCs starting with TC0
5387 	 */
5388 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5389 		if (num_tc & BIT(i)) {
5390 			if (!tc_unused) {
5391 				ret++;
5392 			} else {
5393 				pr_err("Non-contiguous TC - Disabling DCB\n");
5394 				return 1;
5395 			}
5396 		} else {
5397 			tc_unused = 1;
5398 		}
5399 	}
5400 
5401 	/* There is always at least TC0 */
5402 	if (!ret)
5403 		ret = 1;
5404 
5405 	return ret;
5406 }
5407 
5408 /**
5409  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5410  * @dcbcfg: the corresponding DCBx configuration structure
5411  *
5412  * Query the current DCB configuration and return the number of
5413  * traffic classes enabled from the given DCBX config
5414  **/
5415 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5416 {
5417 	u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5418 	u8 enabled_tc = 1;
5419 	u8 i;
5420 
5421 	for (i = 0; i < num_tc; i++)
5422 		enabled_tc |= BIT(i);
5423 
5424 	return enabled_tc;
5425 }
5426 
5427 /**
5428  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5429  * @pf: PF being queried
5430  *
5431  * Query the current MQPRIO configuration and return the number of
5432  * traffic classes enabled.
5433  **/
5434 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5435 {
5436 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
5437 	u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5438 	u8 enabled_tc = 1, i;
5439 
5440 	for (i = 1; i < num_tc; i++)
5441 		enabled_tc |= BIT(i);
5442 	return enabled_tc;
5443 }
5444 
5445 /**
5446  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5447  * @pf: PF being queried
5448  *
5449  * Return number of traffic classes enabled for the given PF
5450  **/
5451 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5452 {
5453 	struct i40e_hw *hw = &pf->hw;
5454 	u8 i, enabled_tc = 1;
5455 	u8 num_tc = 0;
5456 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5457 
5458 	if (i40e_is_tc_mqprio_enabled(pf))
5459 		return pf->vsi[pf->lan_vsi]->mqprio_qopt.qopt.num_tc;
5460 
5461 	/* If neither MQPRIO nor DCB is enabled, then always use single TC */
5462 	if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5463 		return 1;
5464 
5465 	/* SFP mode will be enabled for all TCs on port */
5466 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5467 		return i40e_dcb_get_num_tc(dcbcfg);
5468 
5469 	/* MFP mode return count of enabled TCs for this PF */
5470 	if (pf->hw.func_caps.iscsi)
5471 		enabled_tc =  i40e_get_iscsi_tc_map(pf);
5472 	else
5473 		return 1; /* Only TC0 */
5474 
5475 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5476 		if (enabled_tc & BIT(i))
5477 			num_tc++;
5478 	}
5479 	return num_tc;
5480 }
5481 
5482 /**
5483  * i40e_pf_get_tc_map - Get bitmap for enabled traffic classes
5484  * @pf: PF being queried
5485  *
5486  * Return a bitmap for enabled traffic classes for this PF.
5487  **/
5488 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5489 {
5490 	if (i40e_is_tc_mqprio_enabled(pf))
5491 		return i40e_mqprio_get_enabled_tc(pf);
5492 
5493 	/* If neither MQPRIO nor DCB is enabled for this PF then just return
5494 	 * default TC
5495 	 */
5496 	if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5497 		return I40E_DEFAULT_TRAFFIC_CLASS;
5498 
5499 	/* SFP mode we want PF to be enabled for all TCs */
5500 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5501 		return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5502 
5503 	/* MFP enabled and iSCSI PF type */
5504 	if (pf->hw.func_caps.iscsi)
5505 		return i40e_get_iscsi_tc_map(pf);
5506 	else
5507 		return I40E_DEFAULT_TRAFFIC_CLASS;
5508 }
5509 
5510 /**
5511  * i40e_vsi_get_bw_info - Query VSI BW Information
5512  * @vsi: the VSI being queried
5513  *
5514  * Returns 0 on success, negative value on failure
5515  **/
5516 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5517 {
5518 	struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5519 	struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5520 	struct i40e_pf *pf = vsi->back;
5521 	struct i40e_hw *hw = &pf->hw;
5522 	i40e_status ret;
5523 	u32 tc_bw_max;
5524 	int i;
5525 
5526 	/* Get the VSI level BW configuration */
5527 	ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5528 	if (ret) {
5529 		dev_info(&pf->pdev->dev,
5530 			 "couldn't get PF vsi bw config, err %s aq_err %s\n",
5531 			 i40e_stat_str(&pf->hw, ret),
5532 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5533 		return -EINVAL;
5534 	}
5535 
5536 	/* Get the VSI level BW configuration per TC */
5537 	ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5538 					       NULL);
5539 	if (ret) {
5540 		dev_info(&pf->pdev->dev,
5541 			 "couldn't get PF vsi ets bw config, err %s aq_err %s\n",
5542 			 i40e_stat_str(&pf->hw, ret),
5543 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5544 		return -EINVAL;
5545 	}
5546 
5547 	if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5548 		dev_info(&pf->pdev->dev,
5549 			 "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5550 			 bw_config.tc_valid_bits,
5551 			 bw_ets_config.tc_valid_bits);
5552 		/* Still continuing */
5553 	}
5554 
5555 	vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5556 	vsi->bw_max_quanta = bw_config.max_bw;
5557 	tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5558 		    (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5559 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5560 		vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5561 		vsi->bw_ets_limit_credits[i] =
5562 					le16_to_cpu(bw_ets_config.credits[i]);
5563 		/* 3 bits out of 4 for each TC */
5564 		vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5565 	}
5566 
5567 	return 0;
5568 }
5569 
5570 /**
5571  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5572  * @vsi: the VSI being configured
5573  * @enabled_tc: TC bitmap
5574  * @bw_share: BW shared credits per TC
5575  *
5576  * Returns 0 on success, negative value on failure
5577  **/
5578 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5579 				       u8 *bw_share)
5580 {
5581 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5582 	struct i40e_pf *pf = vsi->back;
5583 	i40e_status ret;
5584 	int i;
5585 
5586 	/* There is no need to reset BW when mqprio mode is on.  */
5587 	if (i40e_is_tc_mqprio_enabled(pf))
5588 		return 0;
5589 	if (!vsi->mqprio_qopt.qopt.hw && !(pf->flags & I40E_FLAG_DCB_ENABLED)) {
5590 		ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5591 		if (ret)
5592 			dev_info(&pf->pdev->dev,
5593 				 "Failed to reset tx rate for vsi->seid %u\n",
5594 				 vsi->seid);
5595 		return ret;
5596 	}
5597 	memset(&bw_data, 0, sizeof(bw_data));
5598 	bw_data.tc_valid_bits = enabled_tc;
5599 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5600 		bw_data.tc_bw_credits[i] = bw_share[i];
5601 
5602 	ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5603 	if (ret) {
5604 		dev_info(&pf->pdev->dev,
5605 			 "AQ command Config VSI BW allocation per TC failed = %d\n",
5606 			 pf->hw.aq.asq_last_status);
5607 		return -EINVAL;
5608 	}
5609 
5610 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5611 		vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5612 
5613 	return 0;
5614 }
5615 
5616 /**
5617  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5618  * @vsi: the VSI being configured
5619  * @enabled_tc: TC map to be enabled
5620  *
5621  **/
5622 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5623 {
5624 	struct net_device *netdev = vsi->netdev;
5625 	struct i40e_pf *pf = vsi->back;
5626 	struct i40e_hw *hw = &pf->hw;
5627 	u8 netdev_tc = 0;
5628 	int i;
5629 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5630 
5631 	if (!netdev)
5632 		return;
5633 
5634 	if (!enabled_tc) {
5635 		netdev_reset_tc(netdev);
5636 		return;
5637 	}
5638 
5639 	/* Set up actual enabled TCs on the VSI */
5640 	if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5641 		return;
5642 
5643 	/* set per TC queues for the VSI */
5644 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5645 		/* Only set TC queues for enabled tcs
5646 		 *
5647 		 * e.g. For a VSI that has TC0 and TC3 enabled the
5648 		 * enabled_tc bitmap would be 0x00001001; the driver
5649 		 * will set the numtc for netdev as 2 that will be
5650 		 * referenced by the netdev layer as TC 0 and 1.
5651 		 */
5652 		if (vsi->tc_config.enabled_tc & BIT(i))
5653 			netdev_set_tc_queue(netdev,
5654 					vsi->tc_config.tc_info[i].netdev_tc,
5655 					vsi->tc_config.tc_info[i].qcount,
5656 					vsi->tc_config.tc_info[i].qoffset);
5657 	}
5658 
5659 	if (i40e_is_tc_mqprio_enabled(pf))
5660 		return;
5661 
5662 	/* Assign UP2TC map for the VSI */
5663 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5664 		/* Get the actual TC# for the UP */
5665 		u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5666 		/* Get the mapped netdev TC# for the UP */
5667 		netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5668 		netdev_set_prio_tc_map(netdev, i, netdev_tc);
5669 	}
5670 }
5671 
5672 /**
5673  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5674  * @vsi: the VSI being configured
5675  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5676  **/
5677 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5678 				      struct i40e_vsi_context *ctxt)
5679 {
5680 	/* copy just the sections touched not the entire info
5681 	 * since not all sections are valid as returned by
5682 	 * update vsi params
5683 	 */
5684 	vsi->info.mapping_flags = ctxt->info.mapping_flags;
5685 	memcpy(&vsi->info.queue_mapping,
5686 	       &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5687 	memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5688 	       sizeof(vsi->info.tc_mapping));
5689 }
5690 
5691 /**
5692  * i40e_update_adq_vsi_queues - update queue mapping for ADq VSI
5693  * @vsi: the VSI being reconfigured
5694  * @vsi_offset: offset from main VF VSI
5695  */
5696 int i40e_update_adq_vsi_queues(struct i40e_vsi *vsi, int vsi_offset)
5697 {
5698 	struct i40e_vsi_context ctxt = {};
5699 	struct i40e_pf *pf;
5700 	struct i40e_hw *hw;
5701 	int ret;
5702 
5703 	if (!vsi)
5704 		return I40E_ERR_PARAM;
5705 	pf = vsi->back;
5706 	hw = &pf->hw;
5707 
5708 	ctxt.seid = vsi->seid;
5709 	ctxt.pf_num = hw->pf_id;
5710 	ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id + vsi_offset;
5711 	ctxt.uplink_seid = vsi->uplink_seid;
5712 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5713 	ctxt.flags = I40E_AQ_VSI_TYPE_VF;
5714 	ctxt.info = vsi->info;
5715 
5716 	i40e_vsi_setup_queue_map(vsi, &ctxt, vsi->tc_config.enabled_tc,
5717 				 false);
5718 	if (vsi->reconfig_rss) {
5719 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
5720 				      vsi->num_queue_pairs);
5721 		ret = i40e_vsi_config_rss(vsi);
5722 		if (ret) {
5723 			dev_info(&pf->pdev->dev, "Failed to reconfig rss for num_queues\n");
5724 			return ret;
5725 		}
5726 		vsi->reconfig_rss = false;
5727 	}
5728 
5729 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5730 	if (ret) {
5731 		dev_info(&pf->pdev->dev, "Update vsi config failed, err %s aq_err %s\n",
5732 			 i40e_stat_str(hw, ret),
5733 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5734 		return ret;
5735 	}
5736 	/* update the local VSI info with updated queue map */
5737 	i40e_vsi_update_queue_map(vsi, &ctxt);
5738 	vsi->info.valid_sections = 0;
5739 
5740 	return ret;
5741 }
5742 
5743 /**
5744  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5745  * @vsi: VSI to be configured
5746  * @enabled_tc: TC bitmap
5747  *
5748  * This configures a particular VSI for TCs that are mapped to the
5749  * given TC bitmap. It uses default bandwidth share for TCs across
5750  * VSIs to configure TC for a particular VSI.
5751  *
5752  * NOTE:
5753  * It is expected that the VSI queues have been quisced before calling
5754  * this function.
5755  **/
5756 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5757 {
5758 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5759 	struct i40e_pf *pf = vsi->back;
5760 	struct i40e_hw *hw = &pf->hw;
5761 	struct i40e_vsi_context ctxt;
5762 	int ret = 0;
5763 	int i;
5764 
5765 	/* Check if enabled_tc is same as existing or new TCs */
5766 	if (vsi->tc_config.enabled_tc == enabled_tc &&
5767 	    vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5768 		return ret;
5769 
5770 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
5771 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5772 		if (enabled_tc & BIT(i))
5773 			bw_share[i] = 1;
5774 	}
5775 
5776 	ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5777 	if (ret) {
5778 		struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5779 
5780 		dev_info(&pf->pdev->dev,
5781 			 "Failed configuring TC map %d for VSI %d\n",
5782 			 enabled_tc, vsi->seid);
5783 		ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5784 						  &bw_config, NULL);
5785 		if (ret) {
5786 			dev_info(&pf->pdev->dev,
5787 				 "Failed querying vsi bw info, err %s aq_err %s\n",
5788 				 i40e_stat_str(hw, ret),
5789 				 i40e_aq_str(hw, hw->aq.asq_last_status));
5790 			goto out;
5791 		}
5792 		if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5793 			u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5794 
5795 			if (!valid_tc)
5796 				valid_tc = bw_config.tc_valid_bits;
5797 			/* Always enable TC0, no matter what */
5798 			valid_tc |= 1;
5799 			dev_info(&pf->pdev->dev,
5800 				 "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5801 				 enabled_tc, bw_config.tc_valid_bits, valid_tc);
5802 			enabled_tc = valid_tc;
5803 		}
5804 
5805 		ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5806 		if (ret) {
5807 			dev_err(&pf->pdev->dev,
5808 				"Unable to  configure TC map %d for VSI %d\n",
5809 				enabled_tc, vsi->seid);
5810 			goto out;
5811 		}
5812 	}
5813 
5814 	/* Update Queue Pairs Mapping for currently enabled UPs */
5815 	ctxt.seid = vsi->seid;
5816 	ctxt.pf_num = vsi->back->hw.pf_id;
5817 	ctxt.vf_num = 0;
5818 	ctxt.uplink_seid = vsi->uplink_seid;
5819 	ctxt.info = vsi->info;
5820 	if (i40e_is_tc_mqprio_enabled(pf)) {
5821 		ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5822 		if (ret)
5823 			goto out;
5824 	} else {
5825 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5826 	}
5827 
5828 	/* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5829 	 * queues changed.
5830 	 */
5831 	if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5832 		vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5833 				      vsi->num_queue_pairs);
5834 		ret = i40e_vsi_config_rss(vsi);
5835 		if (ret) {
5836 			dev_info(&vsi->back->pdev->dev,
5837 				 "Failed to reconfig rss for num_queues\n");
5838 			return ret;
5839 		}
5840 		vsi->reconfig_rss = false;
5841 	}
5842 	if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
5843 		ctxt.info.valid_sections |=
5844 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5845 		ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5846 	}
5847 
5848 	/* Update the VSI after updating the VSI queue-mapping
5849 	 * information
5850 	 */
5851 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5852 	if (ret) {
5853 		dev_info(&pf->pdev->dev,
5854 			 "Update vsi tc config failed, err %s aq_err %s\n",
5855 			 i40e_stat_str(hw, ret),
5856 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5857 		goto out;
5858 	}
5859 	/* update the local VSI info with updated queue map */
5860 	i40e_vsi_update_queue_map(vsi, &ctxt);
5861 	vsi->info.valid_sections = 0;
5862 
5863 	/* Update current VSI BW information */
5864 	ret = i40e_vsi_get_bw_info(vsi);
5865 	if (ret) {
5866 		dev_info(&pf->pdev->dev,
5867 			 "Failed updating vsi bw info, err %s aq_err %s\n",
5868 			 i40e_stat_str(hw, ret),
5869 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5870 		goto out;
5871 	}
5872 
5873 	/* Update the netdev TC setup */
5874 	i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5875 out:
5876 	return ret;
5877 }
5878 
5879 /**
5880  * i40e_get_link_speed - Returns link speed for the interface
5881  * @vsi: VSI to be configured
5882  *
5883  **/
5884 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5885 {
5886 	struct i40e_pf *pf = vsi->back;
5887 
5888 	switch (pf->hw.phy.link_info.link_speed) {
5889 	case I40E_LINK_SPEED_40GB:
5890 		return 40000;
5891 	case I40E_LINK_SPEED_25GB:
5892 		return 25000;
5893 	case I40E_LINK_SPEED_20GB:
5894 		return 20000;
5895 	case I40E_LINK_SPEED_10GB:
5896 		return 10000;
5897 	case I40E_LINK_SPEED_1GB:
5898 		return 1000;
5899 	default:
5900 		return -EINVAL;
5901 	}
5902 }
5903 
5904 /**
5905  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5906  * @vsi: VSI to be configured
5907  * @seid: seid of the channel/VSI
5908  * @max_tx_rate: max TX rate to be configured as BW limit
5909  *
5910  * Helper function to set BW limit for a given VSI
5911  **/
5912 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5913 {
5914 	struct i40e_pf *pf = vsi->back;
5915 	u64 credits = 0;
5916 	int speed = 0;
5917 	int ret = 0;
5918 
5919 	speed = i40e_get_link_speed(vsi);
5920 	if (max_tx_rate > speed) {
5921 		dev_err(&pf->pdev->dev,
5922 			"Invalid max tx rate %llu specified for VSI seid %d.",
5923 			max_tx_rate, seid);
5924 		return -EINVAL;
5925 	}
5926 	if (max_tx_rate && max_tx_rate < 50) {
5927 		dev_warn(&pf->pdev->dev,
5928 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
5929 		max_tx_rate = 50;
5930 	}
5931 
5932 	/* Tx rate credits are in values of 50Mbps, 0 is disabled */
5933 	credits = max_tx_rate;
5934 	do_div(credits, I40E_BW_CREDIT_DIVISOR);
5935 	ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
5936 					  I40E_MAX_BW_INACTIVE_ACCUM, NULL);
5937 	if (ret)
5938 		dev_err(&pf->pdev->dev,
5939 			"Failed set tx rate (%llu Mbps) for vsi->seid %u, err %s aq_err %s\n",
5940 			max_tx_rate, seid, i40e_stat_str(&pf->hw, ret),
5941 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5942 	return ret;
5943 }
5944 
5945 /**
5946  * i40e_remove_queue_channels - Remove queue channels for the TCs
5947  * @vsi: VSI to be configured
5948  *
5949  * Remove queue channels for the TCs
5950  **/
5951 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
5952 {
5953 	enum i40e_admin_queue_err last_aq_status;
5954 	struct i40e_cloud_filter *cfilter;
5955 	struct i40e_channel *ch, *ch_tmp;
5956 	struct i40e_pf *pf = vsi->back;
5957 	struct hlist_node *node;
5958 	int ret, i;
5959 
5960 	/* Reset rss size that was stored when reconfiguring rss for
5961 	 * channel VSIs with non-power-of-2 queue count.
5962 	 */
5963 	vsi->current_rss_size = 0;
5964 
5965 	/* perform cleanup for channels if they exist */
5966 	if (list_empty(&vsi->ch_list))
5967 		return;
5968 
5969 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5970 		struct i40e_vsi *p_vsi;
5971 
5972 		list_del(&ch->list);
5973 		p_vsi = ch->parent_vsi;
5974 		if (!p_vsi || !ch->initialized) {
5975 			kfree(ch);
5976 			continue;
5977 		}
5978 		/* Reset queue contexts */
5979 		for (i = 0; i < ch->num_queue_pairs; i++) {
5980 			struct i40e_ring *tx_ring, *rx_ring;
5981 			u16 pf_q;
5982 
5983 			pf_q = ch->base_queue + i;
5984 			tx_ring = vsi->tx_rings[pf_q];
5985 			tx_ring->ch = NULL;
5986 
5987 			rx_ring = vsi->rx_rings[pf_q];
5988 			rx_ring->ch = NULL;
5989 		}
5990 
5991 		/* Reset BW configured for this VSI via mqprio */
5992 		ret = i40e_set_bw_limit(vsi, ch->seid, 0);
5993 		if (ret)
5994 			dev_info(&vsi->back->pdev->dev,
5995 				 "Failed to reset tx rate for ch->seid %u\n",
5996 				 ch->seid);
5997 
5998 		/* delete cloud filters associated with this channel */
5999 		hlist_for_each_entry_safe(cfilter, node,
6000 					  &pf->cloud_filter_list, cloud_node) {
6001 			if (cfilter->seid != ch->seid)
6002 				continue;
6003 
6004 			hash_del(&cfilter->cloud_node);
6005 			if (cfilter->dst_port)
6006 				ret = i40e_add_del_cloud_filter_big_buf(vsi,
6007 									cfilter,
6008 									false);
6009 			else
6010 				ret = i40e_add_del_cloud_filter(vsi, cfilter,
6011 								false);
6012 			last_aq_status = pf->hw.aq.asq_last_status;
6013 			if (ret)
6014 				dev_info(&pf->pdev->dev,
6015 					 "Failed to delete cloud filter, err %s aq_err %s\n",
6016 					 i40e_stat_str(&pf->hw, ret),
6017 					 i40e_aq_str(&pf->hw, last_aq_status));
6018 			kfree(cfilter);
6019 		}
6020 
6021 		/* delete VSI from FW */
6022 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
6023 					     NULL);
6024 		if (ret)
6025 			dev_err(&vsi->back->pdev->dev,
6026 				"unable to remove channel (%d) for parent VSI(%d)\n",
6027 				ch->seid, p_vsi->seid);
6028 		kfree(ch);
6029 	}
6030 	INIT_LIST_HEAD(&vsi->ch_list);
6031 }
6032 
6033 /**
6034  * i40e_get_max_queues_for_channel
6035  * @vsi: ptr to VSI to which channels are associated with
6036  *
6037  * Helper function which returns max value among the queue counts set on the
6038  * channels/TCs created.
6039  **/
6040 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
6041 {
6042 	struct i40e_channel *ch, *ch_tmp;
6043 	int max = 0;
6044 
6045 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6046 		if (!ch->initialized)
6047 			continue;
6048 		if (ch->num_queue_pairs > max)
6049 			max = ch->num_queue_pairs;
6050 	}
6051 
6052 	return max;
6053 }
6054 
6055 /**
6056  * i40e_validate_num_queues - validate num_queues w.r.t channel
6057  * @pf: ptr to PF device
6058  * @num_queues: number of queues
6059  * @vsi: the parent VSI
6060  * @reconfig_rss: indicates should the RSS be reconfigured or not
6061  *
6062  * This function validates number of queues in the context of new channel
6063  * which is being established and determines if RSS should be reconfigured
6064  * or not for parent VSI.
6065  **/
6066 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
6067 				    struct i40e_vsi *vsi, bool *reconfig_rss)
6068 {
6069 	int max_ch_queues;
6070 
6071 	if (!reconfig_rss)
6072 		return -EINVAL;
6073 
6074 	*reconfig_rss = false;
6075 	if (vsi->current_rss_size) {
6076 		if (num_queues > vsi->current_rss_size) {
6077 			dev_dbg(&pf->pdev->dev,
6078 				"Error: num_queues (%d) > vsi's current_size(%d)\n",
6079 				num_queues, vsi->current_rss_size);
6080 			return -EINVAL;
6081 		} else if ((num_queues < vsi->current_rss_size) &&
6082 			   (!is_power_of_2(num_queues))) {
6083 			dev_dbg(&pf->pdev->dev,
6084 				"Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
6085 				num_queues, vsi->current_rss_size);
6086 			return -EINVAL;
6087 		}
6088 	}
6089 
6090 	if (!is_power_of_2(num_queues)) {
6091 		/* Find the max num_queues configured for channel if channel
6092 		 * exist.
6093 		 * if channel exist, then enforce 'num_queues' to be more than
6094 		 * max ever queues configured for channel.
6095 		 */
6096 		max_ch_queues = i40e_get_max_queues_for_channel(vsi);
6097 		if (num_queues < max_ch_queues) {
6098 			dev_dbg(&pf->pdev->dev,
6099 				"Error: num_queues (%d) < max queues configured for channel(%d)\n",
6100 				num_queues, max_ch_queues);
6101 			return -EINVAL;
6102 		}
6103 		*reconfig_rss = true;
6104 	}
6105 
6106 	return 0;
6107 }
6108 
6109 /**
6110  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
6111  * @vsi: the VSI being setup
6112  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
6113  *
6114  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
6115  **/
6116 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
6117 {
6118 	struct i40e_pf *pf = vsi->back;
6119 	u8 seed[I40E_HKEY_ARRAY_SIZE];
6120 	struct i40e_hw *hw = &pf->hw;
6121 	int local_rss_size;
6122 	u8 *lut;
6123 	int ret;
6124 
6125 	if (!vsi->rss_size)
6126 		return -EINVAL;
6127 
6128 	if (rss_size > vsi->rss_size)
6129 		return -EINVAL;
6130 
6131 	local_rss_size = min_t(int, vsi->rss_size, rss_size);
6132 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
6133 	if (!lut)
6134 		return -ENOMEM;
6135 
6136 	/* Ignoring user configured lut if there is one */
6137 	i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
6138 
6139 	/* Use user configured hash key if there is one, otherwise
6140 	 * use default.
6141 	 */
6142 	if (vsi->rss_hkey_user)
6143 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
6144 	else
6145 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
6146 
6147 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
6148 	if (ret) {
6149 		dev_info(&pf->pdev->dev,
6150 			 "Cannot set RSS lut, err %s aq_err %s\n",
6151 			 i40e_stat_str(hw, ret),
6152 			 i40e_aq_str(hw, hw->aq.asq_last_status));
6153 		kfree(lut);
6154 		return ret;
6155 	}
6156 	kfree(lut);
6157 
6158 	/* Do the update w.r.t. storing rss_size */
6159 	if (!vsi->orig_rss_size)
6160 		vsi->orig_rss_size = vsi->rss_size;
6161 	vsi->current_rss_size = local_rss_size;
6162 
6163 	return ret;
6164 }
6165 
6166 /**
6167  * i40e_channel_setup_queue_map - Setup a channel queue map
6168  * @pf: ptr to PF device
6169  * @ctxt: VSI context structure
6170  * @ch: ptr to channel structure
6171  *
6172  * Setup queue map for a specific channel
6173  **/
6174 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
6175 					 struct i40e_vsi_context *ctxt,
6176 					 struct i40e_channel *ch)
6177 {
6178 	u16 qcount, qmap, sections = 0;
6179 	u8 offset = 0;
6180 	int pow;
6181 
6182 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
6183 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
6184 
6185 	qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
6186 	ch->num_queue_pairs = qcount;
6187 
6188 	/* find the next higher power-of-2 of num queue pairs */
6189 	pow = ilog2(qcount);
6190 	if (!is_power_of_2(qcount))
6191 		pow++;
6192 
6193 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
6194 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
6195 
6196 	/* Setup queue TC[0].qmap for given VSI context */
6197 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
6198 
6199 	ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
6200 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
6201 	ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
6202 	ctxt->info.valid_sections |= cpu_to_le16(sections);
6203 }
6204 
6205 /**
6206  * i40e_add_channel - add a channel by adding VSI
6207  * @pf: ptr to PF device
6208  * @uplink_seid: underlying HW switching element (VEB) ID
6209  * @ch: ptr to channel structure
6210  *
6211  * Add a channel (VSI) using add_vsi and queue_map
6212  **/
6213 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
6214 			    struct i40e_channel *ch)
6215 {
6216 	struct i40e_hw *hw = &pf->hw;
6217 	struct i40e_vsi_context ctxt;
6218 	u8 enabled_tc = 0x1; /* TC0 enabled */
6219 	int ret;
6220 
6221 	if (ch->type != I40E_VSI_VMDQ2) {
6222 		dev_info(&pf->pdev->dev,
6223 			 "add new vsi failed, ch->type %d\n", ch->type);
6224 		return -EINVAL;
6225 	}
6226 
6227 	memset(&ctxt, 0, sizeof(ctxt));
6228 	ctxt.pf_num = hw->pf_id;
6229 	ctxt.vf_num = 0;
6230 	ctxt.uplink_seid = uplink_seid;
6231 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
6232 	if (ch->type == I40E_VSI_VMDQ2)
6233 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
6234 
6235 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED) {
6236 		ctxt.info.valid_sections |=
6237 		     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6238 		ctxt.info.switch_id =
6239 		   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6240 	}
6241 
6242 	/* Set queue map for a given VSI context */
6243 	i40e_channel_setup_queue_map(pf, &ctxt, ch);
6244 
6245 	/* Now time to create VSI */
6246 	ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
6247 	if (ret) {
6248 		dev_info(&pf->pdev->dev,
6249 			 "add new vsi failed, err %s aq_err %s\n",
6250 			 i40e_stat_str(&pf->hw, ret),
6251 			 i40e_aq_str(&pf->hw,
6252 				     pf->hw.aq.asq_last_status));
6253 		return -ENOENT;
6254 	}
6255 
6256 	/* Success, update channel, set enabled_tc only if the channel
6257 	 * is not a macvlan
6258 	 */
6259 	ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
6260 	ch->seid = ctxt.seid;
6261 	ch->vsi_number = ctxt.vsi_number;
6262 	ch->stat_counter_idx = le16_to_cpu(ctxt.info.stat_counter_idx);
6263 
6264 	/* copy just the sections touched not the entire info
6265 	 * since not all sections are valid as returned by
6266 	 * update vsi params
6267 	 */
6268 	ch->info.mapping_flags = ctxt.info.mapping_flags;
6269 	memcpy(&ch->info.queue_mapping,
6270 	       &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
6271 	memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
6272 	       sizeof(ctxt.info.tc_mapping));
6273 
6274 	return 0;
6275 }
6276 
6277 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
6278 				  u8 *bw_share)
6279 {
6280 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
6281 	i40e_status ret;
6282 	int i;
6283 
6284 	memset(&bw_data, 0, sizeof(bw_data));
6285 	bw_data.tc_valid_bits = ch->enabled_tc;
6286 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6287 		bw_data.tc_bw_credits[i] = bw_share[i];
6288 
6289 	ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
6290 				       &bw_data, NULL);
6291 	if (ret) {
6292 		dev_info(&vsi->back->pdev->dev,
6293 			 "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
6294 			 vsi->back->hw.aq.asq_last_status, ch->seid);
6295 		return -EINVAL;
6296 	}
6297 
6298 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6299 		ch->info.qs_handle[i] = bw_data.qs_handles[i];
6300 
6301 	return 0;
6302 }
6303 
6304 /**
6305  * i40e_channel_config_tx_ring - config TX ring associated with new channel
6306  * @pf: ptr to PF device
6307  * @vsi: the VSI being setup
6308  * @ch: ptr to channel structure
6309  *
6310  * Configure TX rings associated with channel (VSI) since queues are being
6311  * from parent VSI.
6312  **/
6313 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
6314 				       struct i40e_vsi *vsi,
6315 				       struct i40e_channel *ch)
6316 {
6317 	i40e_status ret;
6318 	int i;
6319 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
6320 
6321 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
6322 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6323 		if (ch->enabled_tc & BIT(i))
6324 			bw_share[i] = 1;
6325 	}
6326 
6327 	/* configure BW for new VSI */
6328 	ret = i40e_channel_config_bw(vsi, ch, bw_share);
6329 	if (ret) {
6330 		dev_info(&vsi->back->pdev->dev,
6331 			 "Failed configuring TC map %d for channel (seid %u)\n",
6332 			 ch->enabled_tc, ch->seid);
6333 		return ret;
6334 	}
6335 
6336 	for (i = 0; i < ch->num_queue_pairs; i++) {
6337 		struct i40e_ring *tx_ring, *rx_ring;
6338 		u16 pf_q;
6339 
6340 		pf_q = ch->base_queue + i;
6341 
6342 		/* Get to TX ring ptr of main VSI, for re-setup TX queue
6343 		 * context
6344 		 */
6345 		tx_ring = vsi->tx_rings[pf_q];
6346 		tx_ring->ch = ch;
6347 
6348 		/* Get the RX ring ptr */
6349 		rx_ring = vsi->rx_rings[pf_q];
6350 		rx_ring->ch = ch;
6351 	}
6352 
6353 	return 0;
6354 }
6355 
6356 /**
6357  * i40e_setup_hw_channel - setup new channel
6358  * @pf: ptr to PF device
6359  * @vsi: the VSI being setup
6360  * @ch: ptr to channel structure
6361  * @uplink_seid: underlying HW switching element (VEB) ID
6362  * @type: type of channel to be created (VMDq2/VF)
6363  *
6364  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6365  * and configures TX rings accordingly
6366  **/
6367 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
6368 					struct i40e_vsi *vsi,
6369 					struct i40e_channel *ch,
6370 					u16 uplink_seid, u8 type)
6371 {
6372 	int ret;
6373 
6374 	ch->initialized = false;
6375 	ch->base_queue = vsi->next_base_queue;
6376 	ch->type = type;
6377 
6378 	/* Proceed with creation of channel (VMDq2) VSI */
6379 	ret = i40e_add_channel(pf, uplink_seid, ch);
6380 	if (ret) {
6381 		dev_info(&pf->pdev->dev,
6382 			 "failed to add_channel using uplink_seid %u\n",
6383 			 uplink_seid);
6384 		return ret;
6385 	}
6386 
6387 	/* Mark the successful creation of channel */
6388 	ch->initialized = true;
6389 
6390 	/* Reconfigure TX queues using QTX_CTL register */
6391 	ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6392 	if (ret) {
6393 		dev_info(&pf->pdev->dev,
6394 			 "failed to configure TX rings for channel %u\n",
6395 			 ch->seid);
6396 		return ret;
6397 	}
6398 
6399 	/* update 'next_base_queue' */
6400 	vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6401 	dev_dbg(&pf->pdev->dev,
6402 		"Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6403 		ch->seid, ch->vsi_number, ch->stat_counter_idx,
6404 		ch->num_queue_pairs,
6405 		vsi->next_base_queue);
6406 	return ret;
6407 }
6408 
6409 /**
6410  * i40e_setup_channel - setup new channel using uplink element
6411  * @pf: ptr to PF device
6412  * @vsi: pointer to the VSI to set up the channel within
6413  * @ch: ptr to channel structure
6414  *
6415  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6416  * and uplink switching element (uplink_seid)
6417  **/
6418 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6419 			       struct i40e_channel *ch)
6420 {
6421 	u8 vsi_type;
6422 	u16 seid;
6423 	int ret;
6424 
6425 	if (vsi->type == I40E_VSI_MAIN) {
6426 		vsi_type = I40E_VSI_VMDQ2;
6427 	} else {
6428 		dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6429 			vsi->type);
6430 		return false;
6431 	}
6432 
6433 	/* underlying switching element */
6434 	seid = pf->vsi[pf->lan_vsi]->uplink_seid;
6435 
6436 	/* create channel (VSI), configure TX rings */
6437 	ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6438 	if (ret) {
6439 		dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6440 		return false;
6441 	}
6442 
6443 	return ch->initialized ? true : false;
6444 }
6445 
6446 /**
6447  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6448  * @vsi: ptr to VSI which has PF backing
6449  *
6450  * Sets up switch mode correctly if it needs to be changed and perform
6451  * what are allowed modes.
6452  **/
6453 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6454 {
6455 	u8 mode;
6456 	struct i40e_pf *pf = vsi->back;
6457 	struct i40e_hw *hw = &pf->hw;
6458 	int ret;
6459 
6460 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6461 	if (ret)
6462 		return -EINVAL;
6463 
6464 	if (hw->dev_caps.switch_mode) {
6465 		/* if switch mode is set, support mode2 (non-tunneled for
6466 		 * cloud filter) for now
6467 		 */
6468 		u32 switch_mode = hw->dev_caps.switch_mode &
6469 				  I40E_SWITCH_MODE_MASK;
6470 		if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6471 			if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6472 				return 0;
6473 			dev_err(&pf->pdev->dev,
6474 				"Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6475 				hw->dev_caps.switch_mode);
6476 			return -EINVAL;
6477 		}
6478 	}
6479 
6480 	/* Set Bit 7 to be valid */
6481 	mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6482 
6483 	/* Set L4type for TCP support */
6484 	mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6485 
6486 	/* Set cloud filter mode */
6487 	mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6488 
6489 	/* Prep mode field for set_switch_config */
6490 	ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6491 					pf->last_sw_conf_valid_flags,
6492 					mode, NULL);
6493 	if (ret && hw->aq.asq_last_status != I40E_AQ_RC_ESRCH)
6494 		dev_err(&pf->pdev->dev,
6495 			"couldn't set switch config bits, err %s aq_err %s\n",
6496 			i40e_stat_str(hw, ret),
6497 			i40e_aq_str(hw,
6498 				    hw->aq.asq_last_status));
6499 
6500 	return ret;
6501 }
6502 
6503 /**
6504  * i40e_create_queue_channel - function to create channel
6505  * @vsi: VSI to be configured
6506  * @ch: ptr to channel (it contains channel specific params)
6507  *
6508  * This function creates channel (VSI) using num_queues specified by user,
6509  * reconfigs RSS if needed.
6510  **/
6511 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6512 			      struct i40e_channel *ch)
6513 {
6514 	struct i40e_pf *pf = vsi->back;
6515 	bool reconfig_rss;
6516 	int err;
6517 
6518 	if (!ch)
6519 		return -EINVAL;
6520 
6521 	if (!ch->num_queue_pairs) {
6522 		dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6523 			ch->num_queue_pairs);
6524 		return -EINVAL;
6525 	}
6526 
6527 	/* validate user requested num_queues for channel */
6528 	err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6529 				       &reconfig_rss);
6530 	if (err) {
6531 		dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6532 			 ch->num_queue_pairs);
6533 		return -EINVAL;
6534 	}
6535 
6536 	/* By default we are in VEPA mode, if this is the first VF/VMDq
6537 	 * VSI to be added switch to VEB mode.
6538 	 */
6539 
6540 	if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
6541 		pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
6542 
6543 		if (vsi->type == I40E_VSI_MAIN) {
6544 			if (i40e_is_tc_mqprio_enabled(pf))
6545 				i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
6546 			else
6547 				i40e_do_reset_safe(pf, I40E_PF_RESET_FLAG);
6548 		}
6549 		/* now onwards for main VSI, number of queues will be value
6550 		 * of TC0's queue count
6551 		 */
6552 	}
6553 
6554 	/* By this time, vsi->cnt_q_avail shall be set to non-zero and
6555 	 * it should be more than num_queues
6556 	 */
6557 	if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6558 		dev_dbg(&pf->pdev->dev,
6559 			"Error: cnt_q_avail (%u) less than num_queues %d\n",
6560 			vsi->cnt_q_avail, ch->num_queue_pairs);
6561 		return -EINVAL;
6562 	}
6563 
6564 	/* reconfig_rss only if vsi type is MAIN_VSI */
6565 	if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6566 		err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6567 		if (err) {
6568 			dev_info(&pf->pdev->dev,
6569 				 "Error: unable to reconfig rss for num_queues (%u)\n",
6570 				 ch->num_queue_pairs);
6571 			return -EINVAL;
6572 		}
6573 	}
6574 
6575 	if (!i40e_setup_channel(pf, vsi, ch)) {
6576 		dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6577 		return -EINVAL;
6578 	}
6579 
6580 	dev_info(&pf->pdev->dev,
6581 		 "Setup channel (id:%u) utilizing num_queues %d\n",
6582 		 ch->seid, ch->num_queue_pairs);
6583 
6584 	/* configure VSI for BW limit */
6585 	if (ch->max_tx_rate) {
6586 		u64 credits = ch->max_tx_rate;
6587 
6588 		if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6589 			return -EINVAL;
6590 
6591 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
6592 		dev_dbg(&pf->pdev->dev,
6593 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6594 			ch->max_tx_rate,
6595 			credits,
6596 			ch->seid);
6597 	}
6598 
6599 	/* in case of VF, this will be main SRIOV VSI */
6600 	ch->parent_vsi = vsi;
6601 
6602 	/* and update main_vsi's count for queue_available to use */
6603 	vsi->cnt_q_avail -= ch->num_queue_pairs;
6604 
6605 	return 0;
6606 }
6607 
6608 /**
6609  * i40e_configure_queue_channels - Add queue channel for the given TCs
6610  * @vsi: VSI to be configured
6611  *
6612  * Configures queue channel mapping to the given TCs
6613  **/
6614 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6615 {
6616 	struct i40e_channel *ch;
6617 	u64 max_rate = 0;
6618 	int ret = 0, i;
6619 
6620 	/* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6621 	vsi->tc_seid_map[0] = vsi->seid;
6622 	for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6623 		if (vsi->tc_config.enabled_tc & BIT(i)) {
6624 			ch = kzalloc(sizeof(*ch), GFP_KERNEL);
6625 			if (!ch) {
6626 				ret = -ENOMEM;
6627 				goto err_free;
6628 			}
6629 
6630 			INIT_LIST_HEAD(&ch->list);
6631 			ch->num_queue_pairs =
6632 				vsi->tc_config.tc_info[i].qcount;
6633 			ch->base_queue =
6634 				vsi->tc_config.tc_info[i].qoffset;
6635 
6636 			/* Bandwidth limit through tc interface is in bytes/s,
6637 			 * change to Mbit/s
6638 			 */
6639 			max_rate = vsi->mqprio_qopt.max_rate[i];
6640 			do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6641 			ch->max_tx_rate = max_rate;
6642 
6643 			list_add_tail(&ch->list, &vsi->ch_list);
6644 
6645 			ret = i40e_create_queue_channel(vsi, ch);
6646 			if (ret) {
6647 				dev_err(&vsi->back->pdev->dev,
6648 					"Failed creating queue channel with TC%d: queues %d\n",
6649 					i, ch->num_queue_pairs);
6650 				goto err_free;
6651 			}
6652 			vsi->tc_seid_map[i] = ch->seid;
6653 		}
6654 	}
6655 
6656 	/* reset to reconfigure TX queue contexts */
6657 	i40e_do_reset(vsi->back, I40E_PF_RESET_FLAG, true);
6658 	return ret;
6659 
6660 err_free:
6661 	i40e_remove_queue_channels(vsi);
6662 	return ret;
6663 }
6664 
6665 /**
6666  * i40e_veb_config_tc - Configure TCs for given VEB
6667  * @veb: given VEB
6668  * @enabled_tc: TC bitmap
6669  *
6670  * Configures given TC bitmap for VEB (switching) element
6671  **/
6672 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6673 {
6674 	struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6675 	struct i40e_pf *pf = veb->pf;
6676 	int ret = 0;
6677 	int i;
6678 
6679 	/* No TCs or already enabled TCs just return */
6680 	if (!enabled_tc || veb->enabled_tc == enabled_tc)
6681 		return ret;
6682 
6683 	bw_data.tc_valid_bits = enabled_tc;
6684 	/* bw_data.absolute_credits is not set (relative) */
6685 
6686 	/* Enable ETS TCs with equal BW Share for now */
6687 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6688 		if (enabled_tc & BIT(i))
6689 			bw_data.tc_bw_share_credits[i] = 1;
6690 	}
6691 
6692 	ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6693 						   &bw_data, NULL);
6694 	if (ret) {
6695 		dev_info(&pf->pdev->dev,
6696 			 "VEB bw config failed, err %s aq_err %s\n",
6697 			 i40e_stat_str(&pf->hw, ret),
6698 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6699 		goto out;
6700 	}
6701 
6702 	/* Update the BW information */
6703 	ret = i40e_veb_get_bw_info(veb);
6704 	if (ret) {
6705 		dev_info(&pf->pdev->dev,
6706 			 "Failed getting veb bw config, err %s aq_err %s\n",
6707 			 i40e_stat_str(&pf->hw, ret),
6708 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6709 	}
6710 
6711 out:
6712 	return ret;
6713 }
6714 
6715 #ifdef CONFIG_I40E_DCB
6716 /**
6717  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6718  * @pf: PF struct
6719  *
6720  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6721  * the caller would've quiesce all the VSIs before calling
6722  * this function
6723  **/
6724 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6725 {
6726 	u8 tc_map = 0;
6727 	int ret;
6728 	u8 v;
6729 
6730 	/* Enable the TCs available on PF to all VEBs */
6731 	tc_map = i40e_pf_get_tc_map(pf);
6732 	if (tc_map == I40E_DEFAULT_TRAFFIC_CLASS)
6733 		return;
6734 
6735 	for (v = 0; v < I40E_MAX_VEB; v++) {
6736 		if (!pf->veb[v])
6737 			continue;
6738 		ret = i40e_veb_config_tc(pf->veb[v], tc_map);
6739 		if (ret) {
6740 			dev_info(&pf->pdev->dev,
6741 				 "Failed configuring TC for VEB seid=%d\n",
6742 				 pf->veb[v]->seid);
6743 			/* Will try to configure as many components */
6744 		}
6745 	}
6746 
6747 	/* Update each VSI */
6748 	for (v = 0; v < pf->num_alloc_vsi; v++) {
6749 		if (!pf->vsi[v])
6750 			continue;
6751 
6752 		/* - Enable all TCs for the LAN VSI
6753 		 * - For all others keep them at TC0 for now
6754 		 */
6755 		if (v == pf->lan_vsi)
6756 			tc_map = i40e_pf_get_tc_map(pf);
6757 		else
6758 			tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6759 
6760 		ret = i40e_vsi_config_tc(pf->vsi[v], tc_map);
6761 		if (ret) {
6762 			dev_info(&pf->pdev->dev,
6763 				 "Failed configuring TC for VSI seid=%d\n",
6764 				 pf->vsi[v]->seid);
6765 			/* Will try to configure as many components */
6766 		} else {
6767 			/* Re-configure VSI vectors based on updated TC map */
6768 			i40e_vsi_map_rings_to_vectors(pf->vsi[v]);
6769 			if (pf->vsi[v]->netdev)
6770 				i40e_dcbnl_set_all(pf->vsi[v]);
6771 		}
6772 	}
6773 }
6774 
6775 /**
6776  * i40e_resume_port_tx - Resume port Tx
6777  * @pf: PF struct
6778  *
6779  * Resume a port's Tx and issue a PF reset in case of failure to
6780  * resume.
6781  **/
6782 static int i40e_resume_port_tx(struct i40e_pf *pf)
6783 {
6784 	struct i40e_hw *hw = &pf->hw;
6785 	int ret;
6786 
6787 	ret = i40e_aq_resume_port_tx(hw, NULL);
6788 	if (ret) {
6789 		dev_info(&pf->pdev->dev,
6790 			 "Resume Port Tx failed, err %s aq_err %s\n",
6791 			  i40e_stat_str(&pf->hw, ret),
6792 			  i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6793 		/* Schedule PF reset to recover */
6794 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6795 		i40e_service_event_schedule(pf);
6796 	}
6797 
6798 	return ret;
6799 }
6800 
6801 /**
6802  * i40e_suspend_port_tx - Suspend port Tx
6803  * @pf: PF struct
6804  *
6805  * Suspend a port's Tx and issue a PF reset in case of failure.
6806  **/
6807 static int i40e_suspend_port_tx(struct i40e_pf *pf)
6808 {
6809 	struct i40e_hw *hw = &pf->hw;
6810 	int ret;
6811 
6812 	ret = i40e_aq_suspend_port_tx(hw, pf->mac_seid, NULL);
6813 	if (ret) {
6814 		dev_info(&pf->pdev->dev,
6815 			 "Suspend Port Tx failed, err %s aq_err %s\n",
6816 			 i40e_stat_str(&pf->hw, ret),
6817 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6818 		/* Schedule PF reset to recover */
6819 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6820 		i40e_service_event_schedule(pf);
6821 	}
6822 
6823 	return ret;
6824 }
6825 
6826 /**
6827  * i40e_hw_set_dcb_config - Program new DCBX settings into HW
6828  * @pf: PF being configured
6829  * @new_cfg: New DCBX configuration
6830  *
6831  * Program DCB settings into HW and reconfigure VEB/VSIs on
6832  * given PF. Uses "Set LLDP MIB" AQC to program the hardware.
6833  **/
6834 static int i40e_hw_set_dcb_config(struct i40e_pf *pf,
6835 				  struct i40e_dcbx_config *new_cfg)
6836 {
6837 	struct i40e_dcbx_config *old_cfg = &pf->hw.local_dcbx_config;
6838 	int ret;
6839 
6840 	/* Check if need reconfiguration */
6841 	if (!memcmp(&new_cfg, &old_cfg, sizeof(new_cfg))) {
6842 		dev_dbg(&pf->pdev->dev, "No Change in DCB Config required.\n");
6843 		return 0;
6844 	}
6845 
6846 	/* Config change disable all VSIs */
6847 	i40e_pf_quiesce_all_vsi(pf);
6848 
6849 	/* Copy the new config to the current config */
6850 	*old_cfg = *new_cfg;
6851 	old_cfg->etsrec = old_cfg->etscfg;
6852 	ret = i40e_set_dcb_config(&pf->hw);
6853 	if (ret) {
6854 		dev_info(&pf->pdev->dev,
6855 			 "Set DCB Config failed, err %s aq_err %s\n",
6856 			 i40e_stat_str(&pf->hw, ret),
6857 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6858 		goto out;
6859 	}
6860 
6861 	/* Changes in configuration update VEB/VSI */
6862 	i40e_dcb_reconfigure(pf);
6863 out:
6864 	/* In case of reset do not try to resume anything */
6865 	if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
6866 		/* Re-start the VSIs if disabled */
6867 		ret = i40e_resume_port_tx(pf);
6868 		/* In case of error no point in resuming VSIs */
6869 		if (ret)
6870 			goto err;
6871 		i40e_pf_unquiesce_all_vsi(pf);
6872 	}
6873 err:
6874 	return ret;
6875 }
6876 
6877 /**
6878  * i40e_hw_dcb_config - Program new DCBX settings into HW
6879  * @pf: PF being configured
6880  * @new_cfg: New DCBX configuration
6881  *
6882  * Program DCB settings into HW and reconfigure VEB/VSIs on
6883  * given PF
6884  **/
6885 int i40e_hw_dcb_config(struct i40e_pf *pf, struct i40e_dcbx_config *new_cfg)
6886 {
6887 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6888 	u8 prio_type[I40E_MAX_TRAFFIC_CLASS] = {0};
6889 	u32 mfs_tc[I40E_MAX_TRAFFIC_CLASS];
6890 	struct i40e_dcbx_config *old_cfg;
6891 	u8 mode[I40E_MAX_TRAFFIC_CLASS];
6892 	struct i40e_rx_pb_config pb_cfg;
6893 	struct i40e_hw *hw = &pf->hw;
6894 	u8 num_ports = hw->num_ports;
6895 	bool need_reconfig;
6896 	int ret = -EINVAL;
6897 	u8 lltc_map = 0;
6898 	u8 tc_map = 0;
6899 	u8 new_numtc;
6900 	u8 i;
6901 
6902 	dev_dbg(&pf->pdev->dev, "Configuring DCB registers directly\n");
6903 	/* Un-pack information to Program ETS HW via shared API
6904 	 * numtc, tcmap
6905 	 * LLTC map
6906 	 * ETS/NON-ETS arbiter mode
6907 	 * max exponent (credit refills)
6908 	 * Total number of ports
6909 	 * PFC priority bit-map
6910 	 * Priority Table
6911 	 * BW % per TC
6912 	 * Arbiter mode between UPs sharing same TC
6913 	 * TSA table (ETS or non-ETS)
6914 	 * EEE enabled or not
6915 	 * MFS TC table
6916 	 */
6917 
6918 	new_numtc = i40e_dcb_get_num_tc(new_cfg);
6919 
6920 	memset(&ets_data, 0, sizeof(ets_data));
6921 	for (i = 0; i < new_numtc; i++) {
6922 		tc_map |= BIT(i);
6923 		switch (new_cfg->etscfg.tsatable[i]) {
6924 		case I40E_IEEE_TSA_ETS:
6925 			prio_type[i] = I40E_DCB_PRIO_TYPE_ETS;
6926 			ets_data.tc_bw_share_credits[i] =
6927 					new_cfg->etscfg.tcbwtable[i];
6928 			break;
6929 		case I40E_IEEE_TSA_STRICT:
6930 			prio_type[i] = I40E_DCB_PRIO_TYPE_STRICT;
6931 			lltc_map |= BIT(i);
6932 			ets_data.tc_bw_share_credits[i] =
6933 					I40E_DCB_STRICT_PRIO_CREDITS;
6934 			break;
6935 		default:
6936 			/* Invalid TSA type */
6937 			need_reconfig = false;
6938 			goto out;
6939 		}
6940 	}
6941 
6942 	old_cfg = &hw->local_dcbx_config;
6943 	/* Check if need reconfiguration */
6944 	need_reconfig = i40e_dcb_need_reconfig(pf, old_cfg, new_cfg);
6945 
6946 	/* If needed, enable/disable frame tagging, disable all VSIs
6947 	 * and suspend port tx
6948 	 */
6949 	if (need_reconfig) {
6950 		/* Enable DCB tagging only when more than one TC */
6951 		if (new_numtc > 1)
6952 			pf->flags |= I40E_FLAG_DCB_ENABLED;
6953 		else
6954 			pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6955 
6956 		set_bit(__I40E_PORT_SUSPENDED, pf->state);
6957 		/* Reconfiguration needed quiesce all VSIs */
6958 		i40e_pf_quiesce_all_vsi(pf);
6959 		ret = i40e_suspend_port_tx(pf);
6960 		if (ret)
6961 			goto err;
6962 	}
6963 
6964 	/* Configure Port ETS Tx Scheduler */
6965 	ets_data.tc_valid_bits = tc_map;
6966 	ets_data.tc_strict_priority_flags = lltc_map;
6967 	ret = i40e_aq_config_switch_comp_ets
6968 		(hw, pf->mac_seid, &ets_data,
6969 		 i40e_aqc_opc_modify_switching_comp_ets, NULL);
6970 	if (ret) {
6971 		dev_info(&pf->pdev->dev,
6972 			 "Modify Port ETS failed, err %s aq_err %s\n",
6973 			 i40e_stat_str(&pf->hw, ret),
6974 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6975 		goto out;
6976 	}
6977 
6978 	/* Configure Rx ETS HW */
6979 	memset(&mode, I40E_DCB_ARB_MODE_ROUND_ROBIN, sizeof(mode));
6980 	i40e_dcb_hw_set_num_tc(hw, new_numtc);
6981 	i40e_dcb_hw_rx_fifo_config(hw, I40E_DCB_ARB_MODE_ROUND_ROBIN,
6982 				   I40E_DCB_ARB_MODE_STRICT_PRIORITY,
6983 				   I40E_DCB_DEFAULT_MAX_EXPONENT,
6984 				   lltc_map);
6985 	i40e_dcb_hw_rx_cmd_monitor_config(hw, new_numtc, num_ports);
6986 	i40e_dcb_hw_rx_ets_bw_config(hw, new_cfg->etscfg.tcbwtable, mode,
6987 				     prio_type);
6988 	i40e_dcb_hw_pfc_config(hw, new_cfg->pfc.pfcenable,
6989 			       new_cfg->etscfg.prioritytable);
6990 	i40e_dcb_hw_rx_up2tc_config(hw, new_cfg->etscfg.prioritytable);
6991 
6992 	/* Configure Rx Packet Buffers in HW */
6993 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6994 		mfs_tc[i] = pf->vsi[pf->lan_vsi]->netdev->mtu;
6995 		mfs_tc[i] += I40E_PACKET_HDR_PAD;
6996 	}
6997 
6998 	i40e_dcb_hw_calculate_pool_sizes(hw, num_ports,
6999 					 false, new_cfg->pfc.pfcenable,
7000 					 mfs_tc, &pb_cfg);
7001 	i40e_dcb_hw_rx_pb_config(hw, &pf->pb_cfg, &pb_cfg);
7002 
7003 	/* Update the local Rx Packet buffer config */
7004 	pf->pb_cfg = pb_cfg;
7005 
7006 	/* Inform the FW about changes to DCB configuration */
7007 	ret = i40e_aq_dcb_updated(&pf->hw, NULL);
7008 	if (ret) {
7009 		dev_info(&pf->pdev->dev,
7010 			 "DCB Updated failed, err %s aq_err %s\n",
7011 			 i40e_stat_str(&pf->hw, ret),
7012 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7013 		goto out;
7014 	}
7015 
7016 	/* Update the port DCBx configuration */
7017 	*old_cfg = *new_cfg;
7018 
7019 	/* Changes in configuration update VEB/VSI */
7020 	i40e_dcb_reconfigure(pf);
7021 out:
7022 	/* Re-start the VSIs if disabled */
7023 	if (need_reconfig) {
7024 		ret = i40e_resume_port_tx(pf);
7025 
7026 		clear_bit(__I40E_PORT_SUSPENDED, pf->state);
7027 		/* In case of error no point in resuming VSIs */
7028 		if (ret)
7029 			goto err;
7030 
7031 		/* Wait for the PF's queues to be disabled */
7032 		ret = i40e_pf_wait_queues_disabled(pf);
7033 		if (ret) {
7034 			/* Schedule PF reset to recover */
7035 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
7036 			i40e_service_event_schedule(pf);
7037 			goto err;
7038 		} else {
7039 			i40e_pf_unquiesce_all_vsi(pf);
7040 			set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7041 			set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
7042 		}
7043 		/* registers are set, lets apply */
7044 		if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB)
7045 			ret = i40e_hw_set_dcb_config(pf, new_cfg);
7046 	}
7047 
7048 err:
7049 	return ret;
7050 }
7051 
7052 /**
7053  * i40e_dcb_sw_default_config - Set default DCB configuration when DCB in SW
7054  * @pf: PF being queried
7055  *
7056  * Set default DCB configuration in case DCB is to be done in SW.
7057  **/
7058 int i40e_dcb_sw_default_config(struct i40e_pf *pf)
7059 {
7060 	struct i40e_dcbx_config *dcb_cfg = &pf->hw.local_dcbx_config;
7061 	struct i40e_aqc_configure_switching_comp_ets_data ets_data;
7062 	struct i40e_hw *hw = &pf->hw;
7063 	int err;
7064 
7065 	if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB) {
7066 		/* Update the local cached instance with TC0 ETS */
7067 		memset(&pf->tmp_cfg, 0, sizeof(struct i40e_dcbx_config));
7068 		pf->tmp_cfg.etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7069 		pf->tmp_cfg.etscfg.maxtcs = 0;
7070 		pf->tmp_cfg.etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7071 		pf->tmp_cfg.etscfg.tsatable[0] = I40E_IEEE_TSA_ETS;
7072 		pf->tmp_cfg.pfc.willing = I40E_IEEE_DEFAULT_PFC_WILLING;
7073 		pf->tmp_cfg.pfc.pfccap = I40E_MAX_TRAFFIC_CLASS;
7074 		/* FW needs one App to configure HW */
7075 		pf->tmp_cfg.numapps = I40E_IEEE_DEFAULT_NUM_APPS;
7076 		pf->tmp_cfg.app[0].selector = I40E_APP_SEL_ETHTYPE;
7077 		pf->tmp_cfg.app[0].priority = I40E_IEEE_DEFAULT_APP_PRIO;
7078 		pf->tmp_cfg.app[0].protocolid = I40E_APP_PROTOID_FCOE;
7079 
7080 		return i40e_hw_set_dcb_config(pf, &pf->tmp_cfg);
7081 	}
7082 
7083 	memset(&ets_data, 0, sizeof(ets_data));
7084 	ets_data.tc_valid_bits = I40E_DEFAULT_TRAFFIC_CLASS; /* TC0 only */
7085 	ets_data.tc_strict_priority_flags = 0; /* ETS */
7086 	ets_data.tc_bw_share_credits[0] = I40E_IEEE_DEFAULT_ETS_TCBW; /* 100% to TC0 */
7087 
7088 	/* Enable ETS on the Physical port */
7089 	err = i40e_aq_config_switch_comp_ets
7090 		(hw, pf->mac_seid, &ets_data,
7091 		 i40e_aqc_opc_enable_switching_comp_ets, NULL);
7092 	if (err) {
7093 		dev_info(&pf->pdev->dev,
7094 			 "Enable Port ETS failed, err %s aq_err %s\n",
7095 			 i40e_stat_str(&pf->hw, err),
7096 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7097 		err = -ENOENT;
7098 		goto out;
7099 	}
7100 
7101 	/* Update the local cached instance with TC0 ETS */
7102 	dcb_cfg->etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7103 	dcb_cfg->etscfg.cbs = 0;
7104 	dcb_cfg->etscfg.maxtcs = I40E_MAX_TRAFFIC_CLASS;
7105 	dcb_cfg->etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7106 
7107 out:
7108 	return err;
7109 }
7110 
7111 /**
7112  * i40e_init_pf_dcb - Initialize DCB configuration
7113  * @pf: PF being configured
7114  *
7115  * Query the current DCB configuration and cache it
7116  * in the hardware structure
7117  **/
7118 static int i40e_init_pf_dcb(struct i40e_pf *pf)
7119 {
7120 	struct i40e_hw *hw = &pf->hw;
7121 	int err;
7122 
7123 	/* Do not enable DCB for SW1 and SW2 images even if the FW is capable
7124 	 * Also do not enable DCBx if FW LLDP agent is disabled
7125 	 */
7126 	if (pf->hw_features & I40E_HW_NO_DCB_SUPPORT) {
7127 		dev_info(&pf->pdev->dev, "DCB is not supported.\n");
7128 		err = I40E_NOT_SUPPORTED;
7129 		goto out;
7130 	}
7131 	if (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) {
7132 		dev_info(&pf->pdev->dev, "FW LLDP is disabled, attempting SW DCB\n");
7133 		err = i40e_dcb_sw_default_config(pf);
7134 		if (err) {
7135 			dev_info(&pf->pdev->dev, "Could not initialize SW DCB\n");
7136 			goto out;
7137 		}
7138 		dev_info(&pf->pdev->dev, "SW DCB initialization succeeded.\n");
7139 		pf->dcbx_cap = DCB_CAP_DCBX_HOST |
7140 			       DCB_CAP_DCBX_VER_IEEE;
7141 		/* at init capable but disabled */
7142 		pf->flags |= I40E_FLAG_DCB_CAPABLE;
7143 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7144 		goto out;
7145 	}
7146 	err = i40e_init_dcb(hw, true);
7147 	if (!err) {
7148 		/* Device/Function is not DCBX capable */
7149 		if ((!hw->func_caps.dcb) ||
7150 		    (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
7151 			dev_info(&pf->pdev->dev,
7152 				 "DCBX offload is not supported or is disabled for this PF.\n");
7153 		} else {
7154 			/* When status is not DISABLED then DCBX in FW */
7155 			pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
7156 				       DCB_CAP_DCBX_VER_IEEE;
7157 
7158 			pf->flags |= I40E_FLAG_DCB_CAPABLE;
7159 			/* Enable DCB tagging only when more than one TC
7160 			 * or explicitly disable if only one TC
7161 			 */
7162 			if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
7163 				pf->flags |= I40E_FLAG_DCB_ENABLED;
7164 			else
7165 				pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7166 			dev_dbg(&pf->pdev->dev,
7167 				"DCBX offload is supported for this PF.\n");
7168 		}
7169 	} else if (pf->hw.aq.asq_last_status == I40E_AQ_RC_EPERM) {
7170 		dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
7171 		pf->flags |= I40E_FLAG_DISABLE_FW_LLDP;
7172 	} else {
7173 		dev_info(&pf->pdev->dev,
7174 			 "Query for DCB configuration failed, err %s aq_err %s\n",
7175 			 i40e_stat_str(&pf->hw, err),
7176 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7177 	}
7178 
7179 out:
7180 	return err;
7181 }
7182 #endif /* CONFIG_I40E_DCB */
7183 
7184 /**
7185  * i40e_print_link_message - print link up or down
7186  * @vsi: the VSI for which link needs a message
7187  * @isup: true of link is up, false otherwise
7188  */
7189 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
7190 {
7191 	enum i40e_aq_link_speed new_speed;
7192 	struct i40e_pf *pf = vsi->back;
7193 	char *speed = "Unknown";
7194 	char *fc = "Unknown";
7195 	char *fec = "";
7196 	char *req_fec = "";
7197 	char *an = "";
7198 
7199 	if (isup)
7200 		new_speed = pf->hw.phy.link_info.link_speed;
7201 	else
7202 		new_speed = I40E_LINK_SPEED_UNKNOWN;
7203 
7204 	if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
7205 		return;
7206 	vsi->current_isup = isup;
7207 	vsi->current_speed = new_speed;
7208 	if (!isup) {
7209 		netdev_info(vsi->netdev, "NIC Link is Down\n");
7210 		return;
7211 	}
7212 
7213 	/* Warn user if link speed on NPAR enabled partition is not at
7214 	 * least 10GB
7215 	 */
7216 	if (pf->hw.func_caps.npar_enable &&
7217 	    (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
7218 	     pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
7219 		netdev_warn(vsi->netdev,
7220 			    "The partition detected link speed that is less than 10Gbps\n");
7221 
7222 	switch (pf->hw.phy.link_info.link_speed) {
7223 	case I40E_LINK_SPEED_40GB:
7224 		speed = "40 G";
7225 		break;
7226 	case I40E_LINK_SPEED_20GB:
7227 		speed = "20 G";
7228 		break;
7229 	case I40E_LINK_SPEED_25GB:
7230 		speed = "25 G";
7231 		break;
7232 	case I40E_LINK_SPEED_10GB:
7233 		speed = "10 G";
7234 		break;
7235 	case I40E_LINK_SPEED_5GB:
7236 		speed = "5 G";
7237 		break;
7238 	case I40E_LINK_SPEED_2_5GB:
7239 		speed = "2.5 G";
7240 		break;
7241 	case I40E_LINK_SPEED_1GB:
7242 		speed = "1000 M";
7243 		break;
7244 	case I40E_LINK_SPEED_100MB:
7245 		speed = "100 M";
7246 		break;
7247 	default:
7248 		break;
7249 	}
7250 
7251 	switch (pf->hw.fc.current_mode) {
7252 	case I40E_FC_FULL:
7253 		fc = "RX/TX";
7254 		break;
7255 	case I40E_FC_TX_PAUSE:
7256 		fc = "TX";
7257 		break;
7258 	case I40E_FC_RX_PAUSE:
7259 		fc = "RX";
7260 		break;
7261 	default:
7262 		fc = "None";
7263 		break;
7264 	}
7265 
7266 	if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
7267 		req_fec = "None";
7268 		fec = "None";
7269 		an = "False";
7270 
7271 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7272 			an = "True";
7273 
7274 		if (pf->hw.phy.link_info.fec_info &
7275 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7276 			fec = "CL74 FC-FEC/BASE-R";
7277 		else if (pf->hw.phy.link_info.fec_info &
7278 			 I40E_AQ_CONFIG_FEC_RS_ENA)
7279 			fec = "CL108 RS-FEC";
7280 
7281 		/* 'CL108 RS-FEC' should be displayed when RS is requested, or
7282 		 * both RS and FC are requested
7283 		 */
7284 		if (vsi->back->hw.phy.link_info.req_fec_info &
7285 		    (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
7286 			if (vsi->back->hw.phy.link_info.req_fec_info &
7287 			    I40E_AQ_REQUEST_FEC_RS)
7288 				req_fec = "CL108 RS-FEC";
7289 			else
7290 				req_fec = "CL74 FC-FEC/BASE-R";
7291 		}
7292 		netdev_info(vsi->netdev,
7293 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7294 			    speed, req_fec, fec, an, fc);
7295 	} else if (pf->hw.device_id == I40E_DEV_ID_KX_X722) {
7296 		req_fec = "None";
7297 		fec = "None";
7298 		an = "False";
7299 
7300 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7301 			an = "True";
7302 
7303 		if (pf->hw.phy.link_info.fec_info &
7304 		    I40E_AQ_CONFIG_FEC_KR_ENA)
7305 			fec = "CL74 FC-FEC/BASE-R";
7306 
7307 		if (pf->hw.phy.link_info.req_fec_info &
7308 		    I40E_AQ_REQUEST_FEC_KR)
7309 			req_fec = "CL74 FC-FEC/BASE-R";
7310 
7311 		netdev_info(vsi->netdev,
7312 			    "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7313 			    speed, req_fec, fec, an, fc);
7314 	} else {
7315 		netdev_info(vsi->netdev,
7316 			    "NIC Link is Up, %sbps Full Duplex, Flow Control: %s\n",
7317 			    speed, fc);
7318 	}
7319 
7320 }
7321 
7322 /**
7323  * i40e_up_complete - Finish the last steps of bringing up a connection
7324  * @vsi: the VSI being configured
7325  **/
7326 static int i40e_up_complete(struct i40e_vsi *vsi)
7327 {
7328 	struct i40e_pf *pf = vsi->back;
7329 	int err;
7330 
7331 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
7332 		i40e_vsi_configure_msix(vsi);
7333 	else
7334 		i40e_configure_msi_and_legacy(vsi);
7335 
7336 	/* start rings */
7337 	err = i40e_vsi_start_rings(vsi);
7338 	if (err)
7339 		return err;
7340 
7341 	clear_bit(__I40E_VSI_DOWN, vsi->state);
7342 	i40e_napi_enable_all(vsi);
7343 	i40e_vsi_enable_irq(vsi);
7344 
7345 	if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
7346 	    (vsi->netdev)) {
7347 		i40e_print_link_message(vsi, true);
7348 		netif_tx_start_all_queues(vsi->netdev);
7349 		netif_carrier_on(vsi->netdev);
7350 	}
7351 
7352 	/* replay FDIR SB filters */
7353 	if (vsi->type == I40E_VSI_FDIR) {
7354 		/* reset fd counters */
7355 		pf->fd_add_err = 0;
7356 		pf->fd_atr_cnt = 0;
7357 		i40e_fdir_filter_restore(vsi);
7358 	}
7359 
7360 	/* On the next run of the service_task, notify any clients of the new
7361 	 * opened netdev
7362 	 */
7363 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7364 	i40e_service_event_schedule(pf);
7365 
7366 	return 0;
7367 }
7368 
7369 /**
7370  * i40e_vsi_reinit_locked - Reset the VSI
7371  * @vsi: the VSI being configured
7372  *
7373  * Rebuild the ring structs after some configuration
7374  * has changed, e.g. MTU size.
7375  **/
7376 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
7377 {
7378 	struct i40e_pf *pf = vsi->back;
7379 
7380 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
7381 		usleep_range(1000, 2000);
7382 	i40e_down(vsi);
7383 
7384 	i40e_up(vsi);
7385 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
7386 }
7387 
7388 /**
7389  * i40e_force_link_state - Force the link status
7390  * @pf: board private structure
7391  * @is_up: whether the link state should be forced up or down
7392  **/
7393 static i40e_status i40e_force_link_state(struct i40e_pf *pf, bool is_up)
7394 {
7395 	struct i40e_aq_get_phy_abilities_resp abilities;
7396 	struct i40e_aq_set_phy_config config = {0};
7397 	bool non_zero_phy_type = is_up;
7398 	struct i40e_hw *hw = &pf->hw;
7399 	i40e_status err;
7400 	u64 mask;
7401 	u8 speed;
7402 
7403 	/* Card might've been put in an unstable state by other drivers
7404 	 * and applications, which causes incorrect speed values being
7405 	 * set on startup. In order to clear speed registers, we call
7406 	 * get_phy_capabilities twice, once to get initial state of
7407 	 * available speeds, and once to get current PHY config.
7408 	 */
7409 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
7410 					   NULL);
7411 	if (err) {
7412 		dev_err(&pf->pdev->dev,
7413 			"failed to get phy cap., ret =  %s last_status =  %s\n",
7414 			i40e_stat_str(hw, err),
7415 			i40e_aq_str(hw, hw->aq.asq_last_status));
7416 		return err;
7417 	}
7418 	speed = abilities.link_speed;
7419 
7420 	/* Get the current phy config */
7421 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
7422 					   NULL);
7423 	if (err) {
7424 		dev_err(&pf->pdev->dev,
7425 			"failed to get phy cap., ret =  %s last_status =  %s\n",
7426 			i40e_stat_str(hw, err),
7427 			i40e_aq_str(hw, hw->aq.asq_last_status));
7428 		return err;
7429 	}
7430 
7431 	/* If link needs to go up, but was not forced to go down,
7432 	 * and its speed values are OK, no need for a flap
7433 	 * if non_zero_phy_type was set, still need to force up
7434 	 */
7435 	if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED)
7436 		non_zero_phy_type = true;
7437 	else if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
7438 		return I40E_SUCCESS;
7439 
7440 	/* To force link we need to set bits for all supported PHY types,
7441 	 * but there are now more than 32, so we need to split the bitmap
7442 	 * across two fields.
7443 	 */
7444 	mask = I40E_PHY_TYPES_BITMASK;
7445 	config.phy_type =
7446 		non_zero_phy_type ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
7447 	config.phy_type_ext =
7448 		non_zero_phy_type ? (u8)((mask >> 32) & 0xff) : 0;
7449 	/* Copy the old settings, except of phy_type */
7450 	config.abilities = abilities.abilities;
7451 	if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED) {
7452 		if (is_up)
7453 			config.abilities |= I40E_AQ_PHY_ENABLE_LINK;
7454 		else
7455 			config.abilities &= ~(I40E_AQ_PHY_ENABLE_LINK);
7456 	}
7457 	if (abilities.link_speed != 0)
7458 		config.link_speed = abilities.link_speed;
7459 	else
7460 		config.link_speed = speed;
7461 	config.eee_capability = abilities.eee_capability;
7462 	config.eeer = abilities.eeer_val;
7463 	config.low_power_ctrl = abilities.d3_lpan;
7464 	config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
7465 			    I40E_AQ_PHY_FEC_CONFIG_MASK;
7466 	err = i40e_aq_set_phy_config(hw, &config, NULL);
7467 
7468 	if (err) {
7469 		dev_err(&pf->pdev->dev,
7470 			"set phy config ret =  %s last_status =  %s\n",
7471 			i40e_stat_str(&pf->hw, err),
7472 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7473 		return err;
7474 	}
7475 
7476 	/* Update the link info */
7477 	err = i40e_update_link_info(hw);
7478 	if (err) {
7479 		/* Wait a little bit (on 40G cards it sometimes takes a really
7480 		 * long time for link to come back from the atomic reset)
7481 		 * and try once more
7482 		 */
7483 		msleep(1000);
7484 		i40e_update_link_info(hw);
7485 	}
7486 
7487 	i40e_aq_set_link_restart_an(hw, is_up, NULL);
7488 
7489 	return I40E_SUCCESS;
7490 }
7491 
7492 /**
7493  * i40e_up - Bring the connection back up after being down
7494  * @vsi: the VSI being configured
7495  **/
7496 int i40e_up(struct i40e_vsi *vsi)
7497 {
7498 	int err;
7499 
7500 	if (vsi->type == I40E_VSI_MAIN &&
7501 	    (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7502 	     vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7503 		i40e_force_link_state(vsi->back, true);
7504 
7505 	err = i40e_vsi_configure(vsi);
7506 	if (!err)
7507 		err = i40e_up_complete(vsi);
7508 
7509 	return err;
7510 }
7511 
7512 /**
7513  * i40e_down - Shutdown the connection processing
7514  * @vsi: the VSI being stopped
7515  **/
7516 void i40e_down(struct i40e_vsi *vsi)
7517 {
7518 	int i;
7519 
7520 	/* It is assumed that the caller of this function
7521 	 * sets the vsi->state __I40E_VSI_DOWN bit.
7522 	 */
7523 	if (vsi->netdev) {
7524 		netif_carrier_off(vsi->netdev);
7525 		netif_tx_disable(vsi->netdev);
7526 	}
7527 	i40e_vsi_disable_irq(vsi);
7528 	i40e_vsi_stop_rings(vsi);
7529 	if (vsi->type == I40E_VSI_MAIN &&
7530 	   (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7531 	    vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7532 		i40e_force_link_state(vsi->back, false);
7533 	i40e_napi_disable_all(vsi);
7534 
7535 	for (i = 0; i < vsi->num_queue_pairs; i++) {
7536 		i40e_clean_tx_ring(vsi->tx_rings[i]);
7537 		if (i40e_enabled_xdp_vsi(vsi)) {
7538 			/* Make sure that in-progress ndo_xdp_xmit and
7539 			 * ndo_xsk_wakeup calls are completed.
7540 			 */
7541 			synchronize_rcu();
7542 			i40e_clean_tx_ring(vsi->xdp_rings[i]);
7543 		}
7544 		i40e_clean_rx_ring(vsi->rx_rings[i]);
7545 	}
7546 
7547 }
7548 
7549 /**
7550  * i40e_validate_mqprio_qopt- validate queue mapping info
7551  * @vsi: the VSI being configured
7552  * @mqprio_qopt: queue parametrs
7553  **/
7554 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
7555 				     struct tc_mqprio_qopt_offload *mqprio_qopt)
7556 {
7557 	u64 sum_max_rate = 0;
7558 	u64 max_rate = 0;
7559 	int i;
7560 
7561 	if (mqprio_qopt->qopt.offset[0] != 0 ||
7562 	    mqprio_qopt->qopt.num_tc < 1 ||
7563 	    mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
7564 		return -EINVAL;
7565 	for (i = 0; ; i++) {
7566 		if (!mqprio_qopt->qopt.count[i])
7567 			return -EINVAL;
7568 		if (mqprio_qopt->min_rate[i]) {
7569 			dev_err(&vsi->back->pdev->dev,
7570 				"Invalid min tx rate (greater than 0) specified\n");
7571 			return -EINVAL;
7572 		}
7573 		max_rate = mqprio_qopt->max_rate[i];
7574 		do_div(max_rate, I40E_BW_MBPS_DIVISOR);
7575 		sum_max_rate += max_rate;
7576 
7577 		if (i >= mqprio_qopt->qopt.num_tc - 1)
7578 			break;
7579 		if (mqprio_qopt->qopt.offset[i + 1] !=
7580 		    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7581 			return -EINVAL;
7582 	}
7583 	if (vsi->num_queue_pairs <
7584 	    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
7585 		dev_err(&vsi->back->pdev->dev,
7586 			"Failed to create traffic channel, insufficient number of queues.\n");
7587 		return -EINVAL;
7588 	}
7589 	if (sum_max_rate > i40e_get_link_speed(vsi)) {
7590 		dev_err(&vsi->back->pdev->dev,
7591 			"Invalid max tx rate specified\n");
7592 		return -EINVAL;
7593 	}
7594 	return 0;
7595 }
7596 
7597 /**
7598  * i40e_vsi_set_default_tc_config - set default values for tc configuration
7599  * @vsi: the VSI being configured
7600  **/
7601 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
7602 {
7603 	u16 qcount;
7604 	int i;
7605 
7606 	/* Only TC0 is enabled */
7607 	vsi->tc_config.numtc = 1;
7608 	vsi->tc_config.enabled_tc = 1;
7609 	qcount = min_t(int, vsi->alloc_queue_pairs,
7610 		       i40e_pf_get_max_q_per_tc(vsi->back));
7611 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7612 		/* For the TC that is not enabled set the offset to default
7613 		 * queue and allocate one queue for the given TC.
7614 		 */
7615 		vsi->tc_config.tc_info[i].qoffset = 0;
7616 		if (i == 0)
7617 			vsi->tc_config.tc_info[i].qcount = qcount;
7618 		else
7619 			vsi->tc_config.tc_info[i].qcount = 1;
7620 		vsi->tc_config.tc_info[i].netdev_tc = 0;
7621 	}
7622 }
7623 
7624 /**
7625  * i40e_del_macvlan_filter
7626  * @hw: pointer to the HW structure
7627  * @seid: seid of the channel VSI
7628  * @macaddr: the mac address to apply as a filter
7629  * @aq_err: store the admin Q error
7630  *
7631  * This function deletes a mac filter on the channel VSI which serves as the
7632  * macvlan. Returns 0 on success.
7633  **/
7634 static i40e_status i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
7635 					   const u8 *macaddr, int *aq_err)
7636 {
7637 	struct i40e_aqc_remove_macvlan_element_data element;
7638 	i40e_status status;
7639 
7640 	memset(&element, 0, sizeof(element));
7641 	ether_addr_copy(element.mac_addr, macaddr);
7642 	element.vlan_tag = 0;
7643 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
7644 	status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
7645 	*aq_err = hw->aq.asq_last_status;
7646 
7647 	return status;
7648 }
7649 
7650 /**
7651  * i40e_add_macvlan_filter
7652  * @hw: pointer to the HW structure
7653  * @seid: seid of the channel VSI
7654  * @macaddr: the mac address to apply as a filter
7655  * @aq_err: store the admin Q error
7656  *
7657  * This function adds a mac filter on the channel VSI which serves as the
7658  * macvlan. Returns 0 on success.
7659  **/
7660 static i40e_status i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
7661 					   const u8 *macaddr, int *aq_err)
7662 {
7663 	struct i40e_aqc_add_macvlan_element_data element;
7664 	i40e_status status;
7665 	u16 cmd_flags = 0;
7666 
7667 	ether_addr_copy(element.mac_addr, macaddr);
7668 	element.vlan_tag = 0;
7669 	element.queue_number = 0;
7670 	element.match_method = I40E_AQC_MM_ERR_NO_RES;
7671 	cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
7672 	element.flags = cpu_to_le16(cmd_flags);
7673 	status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
7674 	*aq_err = hw->aq.asq_last_status;
7675 
7676 	return status;
7677 }
7678 
7679 /**
7680  * i40e_reset_ch_rings - Reset the queue contexts in a channel
7681  * @vsi: the VSI we want to access
7682  * @ch: the channel we want to access
7683  */
7684 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
7685 {
7686 	struct i40e_ring *tx_ring, *rx_ring;
7687 	u16 pf_q;
7688 	int i;
7689 
7690 	for (i = 0; i < ch->num_queue_pairs; i++) {
7691 		pf_q = ch->base_queue + i;
7692 		tx_ring = vsi->tx_rings[pf_q];
7693 		tx_ring->ch = NULL;
7694 		rx_ring = vsi->rx_rings[pf_q];
7695 		rx_ring->ch = NULL;
7696 	}
7697 }
7698 
7699 /**
7700  * i40e_free_macvlan_channels
7701  * @vsi: the VSI we want to access
7702  *
7703  * This function frees the Qs of the channel VSI from
7704  * the stack and also deletes the channel VSIs which
7705  * serve as macvlans.
7706  */
7707 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
7708 {
7709 	struct i40e_channel *ch, *ch_tmp;
7710 	int ret;
7711 
7712 	if (list_empty(&vsi->macvlan_list))
7713 		return;
7714 
7715 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7716 		struct i40e_vsi *parent_vsi;
7717 
7718 		if (i40e_is_channel_macvlan(ch)) {
7719 			i40e_reset_ch_rings(vsi, ch);
7720 			clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7721 			netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
7722 			netdev_set_sb_channel(ch->fwd->netdev, 0);
7723 			kfree(ch->fwd);
7724 			ch->fwd = NULL;
7725 		}
7726 
7727 		list_del(&ch->list);
7728 		parent_vsi = ch->parent_vsi;
7729 		if (!parent_vsi || !ch->initialized) {
7730 			kfree(ch);
7731 			continue;
7732 		}
7733 
7734 		/* remove the VSI */
7735 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
7736 					     NULL);
7737 		if (ret)
7738 			dev_err(&vsi->back->pdev->dev,
7739 				"unable to remove channel (%d) for parent VSI(%d)\n",
7740 				ch->seid, parent_vsi->seid);
7741 		kfree(ch);
7742 	}
7743 	vsi->macvlan_cnt = 0;
7744 }
7745 
7746 /**
7747  * i40e_fwd_ring_up - bring the macvlan device up
7748  * @vsi: the VSI we want to access
7749  * @vdev: macvlan netdevice
7750  * @fwd: the private fwd structure
7751  */
7752 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7753 			    struct i40e_fwd_adapter *fwd)
7754 {
7755 	struct i40e_channel *ch = NULL, *ch_tmp, *iter;
7756 	int ret = 0, num_tc = 1,  i, aq_err;
7757 	struct i40e_pf *pf = vsi->back;
7758 	struct i40e_hw *hw = &pf->hw;
7759 
7760 	/* Go through the list and find an available channel */
7761 	list_for_each_entry_safe(iter, ch_tmp, &vsi->macvlan_list, list) {
7762 		if (!i40e_is_channel_macvlan(iter)) {
7763 			iter->fwd = fwd;
7764 			/* record configuration for macvlan interface in vdev */
7765 			for (i = 0; i < num_tc; i++)
7766 				netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7767 							     i,
7768 							     iter->num_queue_pairs,
7769 							     iter->base_queue);
7770 			for (i = 0; i < iter->num_queue_pairs; i++) {
7771 				struct i40e_ring *tx_ring, *rx_ring;
7772 				u16 pf_q;
7773 
7774 				pf_q = iter->base_queue + i;
7775 
7776 				/* Get to TX ring ptr */
7777 				tx_ring = vsi->tx_rings[pf_q];
7778 				tx_ring->ch = iter;
7779 
7780 				/* Get the RX ring ptr */
7781 				rx_ring = vsi->rx_rings[pf_q];
7782 				rx_ring->ch = iter;
7783 			}
7784 			ch = iter;
7785 			break;
7786 		}
7787 	}
7788 
7789 	if (!ch)
7790 		return -EINVAL;
7791 
7792 	/* Guarantee all rings are updated before we update the
7793 	 * MAC address filter.
7794 	 */
7795 	wmb();
7796 
7797 	/* Add a mac filter */
7798 	ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7799 	if (ret) {
7800 		/* if we cannot add the MAC rule then disable the offload */
7801 		macvlan_release_l2fw_offload(vdev);
7802 		for (i = 0; i < ch->num_queue_pairs; i++) {
7803 			struct i40e_ring *rx_ring;
7804 			u16 pf_q;
7805 
7806 			pf_q = ch->base_queue + i;
7807 			rx_ring = vsi->rx_rings[pf_q];
7808 			rx_ring->netdev = NULL;
7809 		}
7810 		dev_info(&pf->pdev->dev,
7811 			 "Error adding mac filter on macvlan err %s, aq_err %s\n",
7812 			  i40e_stat_str(hw, ret),
7813 			  i40e_aq_str(hw, aq_err));
7814 		netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7815 	}
7816 
7817 	return ret;
7818 }
7819 
7820 /**
7821  * i40e_setup_macvlans - create the channels which will be macvlans
7822  * @vsi: the VSI we want to access
7823  * @macvlan_cnt: no. of macvlans to be setup
7824  * @qcnt: no. of Qs per macvlan
7825  * @vdev: macvlan netdevice
7826  */
7827 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7828 			       struct net_device *vdev)
7829 {
7830 	struct i40e_pf *pf = vsi->back;
7831 	struct i40e_hw *hw = &pf->hw;
7832 	struct i40e_vsi_context ctxt;
7833 	u16 sections, qmap, num_qps;
7834 	struct i40e_channel *ch;
7835 	int i, pow, ret = 0;
7836 	u8 offset = 0;
7837 
7838 	if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7839 		return -EINVAL;
7840 
7841 	num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7842 
7843 	/* find the next higher power-of-2 of num queue pairs */
7844 	pow = fls(roundup_pow_of_two(num_qps) - 1);
7845 
7846 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7847 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7848 
7849 	/* Setup context bits for the main VSI */
7850 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7851 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7852 	memset(&ctxt, 0, sizeof(ctxt));
7853 	ctxt.seid = vsi->seid;
7854 	ctxt.pf_num = vsi->back->hw.pf_id;
7855 	ctxt.vf_num = 0;
7856 	ctxt.uplink_seid = vsi->uplink_seid;
7857 	ctxt.info = vsi->info;
7858 	ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7859 	ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7860 	ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7861 	ctxt.info.valid_sections |= cpu_to_le16(sections);
7862 
7863 	/* Reconfigure RSS for main VSI with new max queue count */
7864 	vsi->rss_size = max_t(u16, num_qps, qcnt);
7865 	ret = i40e_vsi_config_rss(vsi);
7866 	if (ret) {
7867 		dev_info(&pf->pdev->dev,
7868 			 "Failed to reconfig RSS for num_queues (%u)\n",
7869 			 vsi->rss_size);
7870 		return ret;
7871 	}
7872 	vsi->reconfig_rss = true;
7873 	dev_dbg(&vsi->back->pdev->dev,
7874 		"Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7875 	vsi->next_base_queue = num_qps;
7876 	vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7877 
7878 	/* Update the VSI after updating the VSI queue-mapping
7879 	 * information
7880 	 */
7881 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7882 	if (ret) {
7883 		dev_info(&pf->pdev->dev,
7884 			 "Update vsi tc config failed, err %s aq_err %s\n",
7885 			 i40e_stat_str(hw, ret),
7886 			 i40e_aq_str(hw, hw->aq.asq_last_status));
7887 		return ret;
7888 	}
7889 	/* update the local VSI info with updated queue map */
7890 	i40e_vsi_update_queue_map(vsi, &ctxt);
7891 	vsi->info.valid_sections = 0;
7892 
7893 	/* Create channels for macvlans */
7894 	INIT_LIST_HEAD(&vsi->macvlan_list);
7895 	for (i = 0; i < macvlan_cnt; i++) {
7896 		ch = kzalloc(sizeof(*ch), GFP_KERNEL);
7897 		if (!ch) {
7898 			ret = -ENOMEM;
7899 			goto err_free;
7900 		}
7901 		INIT_LIST_HEAD(&ch->list);
7902 		ch->num_queue_pairs = qcnt;
7903 		if (!i40e_setup_channel(pf, vsi, ch)) {
7904 			ret = -EINVAL;
7905 			kfree(ch);
7906 			goto err_free;
7907 		}
7908 		ch->parent_vsi = vsi;
7909 		vsi->cnt_q_avail -= ch->num_queue_pairs;
7910 		vsi->macvlan_cnt++;
7911 		list_add_tail(&ch->list, &vsi->macvlan_list);
7912 	}
7913 
7914 	return ret;
7915 
7916 err_free:
7917 	dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
7918 	i40e_free_macvlan_channels(vsi);
7919 
7920 	return ret;
7921 }
7922 
7923 /**
7924  * i40e_fwd_add - configure macvlans
7925  * @netdev: net device to configure
7926  * @vdev: macvlan netdevice
7927  **/
7928 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
7929 {
7930 	struct i40e_netdev_priv *np = netdev_priv(netdev);
7931 	u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
7932 	struct i40e_vsi *vsi = np->vsi;
7933 	struct i40e_pf *pf = vsi->back;
7934 	struct i40e_fwd_adapter *fwd;
7935 	int avail_macvlan, ret;
7936 
7937 	if ((pf->flags & I40E_FLAG_DCB_ENABLED)) {
7938 		netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
7939 		return ERR_PTR(-EINVAL);
7940 	}
7941 	if (i40e_is_tc_mqprio_enabled(pf)) {
7942 		netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
7943 		return ERR_PTR(-EINVAL);
7944 	}
7945 	if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
7946 		netdev_info(netdev, "Not enough vectors available to support macvlans\n");
7947 		return ERR_PTR(-EINVAL);
7948 	}
7949 
7950 	/* The macvlan device has to be a single Q device so that the
7951 	 * tc_to_txq field can be reused to pick the tx queue.
7952 	 */
7953 	if (netif_is_multiqueue(vdev))
7954 		return ERR_PTR(-ERANGE);
7955 
7956 	if (!vsi->macvlan_cnt) {
7957 		/* reserve bit 0 for the pf device */
7958 		set_bit(0, vsi->fwd_bitmask);
7959 
7960 		/* Try to reserve as many queues as possible for macvlans. First
7961 		 * reserve 3/4th of max vectors, then half, then quarter and
7962 		 * calculate Qs per macvlan as you go
7963 		 */
7964 		vectors = pf->num_lan_msix;
7965 		if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
7966 			/* allocate 4 Qs per macvlan and 32 Qs to the PF*/
7967 			q_per_macvlan = 4;
7968 			macvlan_cnt = (vectors - 32) / 4;
7969 		} else if (vectors <= 64 && vectors > 32) {
7970 			/* allocate 2 Qs per macvlan and 16 Qs to the PF*/
7971 			q_per_macvlan = 2;
7972 			macvlan_cnt = (vectors - 16) / 2;
7973 		} else if (vectors <= 32 && vectors > 16) {
7974 			/* allocate 1 Q per macvlan and 16 Qs to the PF*/
7975 			q_per_macvlan = 1;
7976 			macvlan_cnt = vectors - 16;
7977 		} else if (vectors <= 16 && vectors > 8) {
7978 			/* allocate 1 Q per macvlan and 8 Qs to the PF */
7979 			q_per_macvlan = 1;
7980 			macvlan_cnt = vectors - 8;
7981 		} else {
7982 			/* allocate 1 Q per macvlan and 1 Q to the PF */
7983 			q_per_macvlan = 1;
7984 			macvlan_cnt = vectors - 1;
7985 		}
7986 
7987 		if (macvlan_cnt == 0)
7988 			return ERR_PTR(-EBUSY);
7989 
7990 		/* Quiesce VSI queues */
7991 		i40e_quiesce_vsi(vsi);
7992 
7993 		/* sets up the macvlans but does not "enable" them */
7994 		ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
7995 					  vdev);
7996 		if (ret)
7997 			return ERR_PTR(ret);
7998 
7999 		/* Unquiesce VSI */
8000 		i40e_unquiesce_vsi(vsi);
8001 	}
8002 	avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
8003 					    vsi->macvlan_cnt);
8004 	if (avail_macvlan >= I40E_MAX_MACVLANS)
8005 		return ERR_PTR(-EBUSY);
8006 
8007 	/* create the fwd struct */
8008 	fwd = kzalloc(sizeof(*fwd), GFP_KERNEL);
8009 	if (!fwd)
8010 		return ERR_PTR(-ENOMEM);
8011 
8012 	set_bit(avail_macvlan, vsi->fwd_bitmask);
8013 	fwd->bit_no = avail_macvlan;
8014 	netdev_set_sb_channel(vdev, avail_macvlan);
8015 	fwd->netdev = vdev;
8016 
8017 	if (!netif_running(netdev))
8018 		return fwd;
8019 
8020 	/* Set fwd ring up */
8021 	ret = i40e_fwd_ring_up(vsi, vdev, fwd);
8022 	if (ret) {
8023 		/* unbind the queues and drop the subordinate channel config */
8024 		netdev_unbind_sb_channel(netdev, vdev);
8025 		netdev_set_sb_channel(vdev, 0);
8026 
8027 		kfree(fwd);
8028 		return ERR_PTR(-EINVAL);
8029 	}
8030 
8031 	return fwd;
8032 }
8033 
8034 /**
8035  * i40e_del_all_macvlans - Delete all the mac filters on the channels
8036  * @vsi: the VSI we want to access
8037  */
8038 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
8039 {
8040 	struct i40e_channel *ch, *ch_tmp;
8041 	struct i40e_pf *pf = vsi->back;
8042 	struct i40e_hw *hw = &pf->hw;
8043 	int aq_err, ret = 0;
8044 
8045 	if (list_empty(&vsi->macvlan_list))
8046 		return;
8047 
8048 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8049 		if (i40e_is_channel_macvlan(ch)) {
8050 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8051 						      i40e_channel_mac(ch),
8052 						      &aq_err);
8053 			if (!ret) {
8054 				/* Reset queue contexts */
8055 				i40e_reset_ch_rings(vsi, ch);
8056 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8057 				netdev_unbind_sb_channel(vsi->netdev,
8058 							 ch->fwd->netdev);
8059 				netdev_set_sb_channel(ch->fwd->netdev, 0);
8060 				kfree(ch->fwd);
8061 				ch->fwd = NULL;
8062 			}
8063 		}
8064 	}
8065 }
8066 
8067 /**
8068  * i40e_fwd_del - delete macvlan interfaces
8069  * @netdev: net device to configure
8070  * @vdev: macvlan netdevice
8071  */
8072 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
8073 {
8074 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8075 	struct i40e_fwd_adapter *fwd = vdev;
8076 	struct i40e_channel *ch, *ch_tmp;
8077 	struct i40e_vsi *vsi = np->vsi;
8078 	struct i40e_pf *pf = vsi->back;
8079 	struct i40e_hw *hw = &pf->hw;
8080 	int aq_err, ret = 0;
8081 
8082 	/* Find the channel associated with the macvlan and del mac filter */
8083 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8084 		if (i40e_is_channel_macvlan(ch) &&
8085 		    ether_addr_equal(i40e_channel_mac(ch),
8086 				     fwd->netdev->dev_addr)) {
8087 			ret = i40e_del_macvlan_filter(hw, ch->seid,
8088 						      i40e_channel_mac(ch),
8089 						      &aq_err);
8090 			if (!ret) {
8091 				/* Reset queue contexts */
8092 				i40e_reset_ch_rings(vsi, ch);
8093 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8094 				netdev_unbind_sb_channel(netdev, fwd->netdev);
8095 				netdev_set_sb_channel(fwd->netdev, 0);
8096 				kfree(ch->fwd);
8097 				ch->fwd = NULL;
8098 			} else {
8099 				dev_info(&pf->pdev->dev,
8100 					 "Error deleting mac filter on macvlan err %s, aq_err %s\n",
8101 					  i40e_stat_str(hw, ret),
8102 					  i40e_aq_str(hw, aq_err));
8103 			}
8104 			break;
8105 		}
8106 	}
8107 }
8108 
8109 /**
8110  * i40e_setup_tc - configure multiple traffic classes
8111  * @netdev: net device to configure
8112  * @type_data: tc offload data
8113  **/
8114 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
8115 {
8116 	struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
8117 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8118 	struct i40e_vsi *vsi = np->vsi;
8119 	struct i40e_pf *pf = vsi->back;
8120 	u8 enabled_tc = 0, num_tc, hw;
8121 	bool need_reset = false;
8122 	int old_queue_pairs;
8123 	int ret = -EINVAL;
8124 	u16 mode;
8125 	int i;
8126 
8127 	old_queue_pairs = vsi->num_queue_pairs;
8128 	num_tc = mqprio_qopt->qopt.num_tc;
8129 	hw = mqprio_qopt->qopt.hw;
8130 	mode = mqprio_qopt->mode;
8131 	if (!hw) {
8132 		pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8133 		memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8134 		goto config_tc;
8135 	}
8136 
8137 	/* Check if MFP enabled */
8138 	if (pf->flags & I40E_FLAG_MFP_ENABLED) {
8139 		netdev_info(netdev,
8140 			    "Configuring TC not supported in MFP mode\n");
8141 		return ret;
8142 	}
8143 	switch (mode) {
8144 	case TC_MQPRIO_MODE_DCB:
8145 		pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8146 
8147 		/* Check if DCB enabled to continue */
8148 		if (!(pf->flags & I40E_FLAG_DCB_ENABLED)) {
8149 			netdev_info(netdev,
8150 				    "DCB is not enabled for adapter\n");
8151 			return ret;
8152 		}
8153 
8154 		/* Check whether tc count is within enabled limit */
8155 		if (num_tc > i40e_pf_get_num_tc(pf)) {
8156 			netdev_info(netdev,
8157 				    "TC count greater than enabled on link for adapter\n");
8158 			return ret;
8159 		}
8160 		break;
8161 	case TC_MQPRIO_MODE_CHANNEL:
8162 		if (pf->flags & I40E_FLAG_DCB_ENABLED) {
8163 			netdev_info(netdev,
8164 				    "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
8165 			return ret;
8166 		}
8167 		if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
8168 			return ret;
8169 		ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
8170 		if (ret)
8171 			return ret;
8172 		memcpy(&vsi->mqprio_qopt, mqprio_qopt,
8173 		       sizeof(*mqprio_qopt));
8174 		pf->flags |= I40E_FLAG_TC_MQPRIO;
8175 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
8176 		break;
8177 	default:
8178 		return -EINVAL;
8179 	}
8180 
8181 config_tc:
8182 	/* Generate TC map for number of tc requested */
8183 	for (i = 0; i < num_tc; i++)
8184 		enabled_tc |= BIT(i);
8185 
8186 	/* Requesting same TC configuration as already enabled */
8187 	if (enabled_tc == vsi->tc_config.enabled_tc &&
8188 	    mode != TC_MQPRIO_MODE_CHANNEL)
8189 		return 0;
8190 
8191 	/* Quiesce VSI queues */
8192 	i40e_quiesce_vsi(vsi);
8193 
8194 	if (!hw && !i40e_is_tc_mqprio_enabled(pf))
8195 		i40e_remove_queue_channels(vsi);
8196 
8197 	/* Configure VSI for enabled TCs */
8198 	ret = i40e_vsi_config_tc(vsi, enabled_tc);
8199 	if (ret) {
8200 		netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
8201 			    vsi->seid);
8202 		need_reset = true;
8203 		goto exit;
8204 	} else if (enabled_tc &&
8205 		   (!is_power_of_2(vsi->tc_config.tc_info[0].qcount))) {
8206 		netdev_info(netdev,
8207 			    "Failed to create channel. Override queues (%u) not power of 2\n",
8208 			    vsi->tc_config.tc_info[0].qcount);
8209 		ret = -EINVAL;
8210 		need_reset = true;
8211 		goto exit;
8212 	}
8213 
8214 	dev_info(&vsi->back->pdev->dev,
8215 		 "Setup channel (id:%u) utilizing num_queues %d\n",
8216 		 vsi->seid, vsi->tc_config.tc_info[0].qcount);
8217 
8218 	if (i40e_is_tc_mqprio_enabled(pf)) {
8219 		if (vsi->mqprio_qopt.max_rate[0]) {
8220 			u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0];
8221 
8222 			do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
8223 			ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
8224 			if (!ret) {
8225 				u64 credits = max_tx_rate;
8226 
8227 				do_div(credits, I40E_BW_CREDIT_DIVISOR);
8228 				dev_dbg(&vsi->back->pdev->dev,
8229 					"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
8230 					max_tx_rate,
8231 					credits,
8232 					vsi->seid);
8233 			} else {
8234 				need_reset = true;
8235 				goto exit;
8236 			}
8237 		}
8238 		ret = i40e_configure_queue_channels(vsi);
8239 		if (ret) {
8240 			vsi->num_queue_pairs = old_queue_pairs;
8241 			netdev_info(netdev,
8242 				    "Failed configuring queue channels\n");
8243 			need_reset = true;
8244 			goto exit;
8245 		}
8246 	}
8247 
8248 exit:
8249 	/* Reset the configuration data to defaults, only TC0 is enabled */
8250 	if (need_reset) {
8251 		i40e_vsi_set_default_tc_config(vsi);
8252 		need_reset = false;
8253 	}
8254 
8255 	/* Unquiesce VSI */
8256 	i40e_unquiesce_vsi(vsi);
8257 	return ret;
8258 }
8259 
8260 /**
8261  * i40e_set_cld_element - sets cloud filter element data
8262  * @filter: cloud filter rule
8263  * @cld: ptr to cloud filter element data
8264  *
8265  * This is helper function to copy data into cloud filter element
8266  **/
8267 static inline void
8268 i40e_set_cld_element(struct i40e_cloud_filter *filter,
8269 		     struct i40e_aqc_cloud_filters_element_data *cld)
8270 {
8271 	u32 ipa;
8272 	int i;
8273 
8274 	memset(cld, 0, sizeof(*cld));
8275 	ether_addr_copy(cld->outer_mac, filter->dst_mac);
8276 	ether_addr_copy(cld->inner_mac, filter->src_mac);
8277 
8278 	if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
8279 		return;
8280 
8281 	if (filter->n_proto == ETH_P_IPV6) {
8282 #define IPV6_MAX_INDEX	(ARRAY_SIZE(filter->dst_ipv6) - 1)
8283 		for (i = 0; i < ARRAY_SIZE(filter->dst_ipv6); i++) {
8284 			ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
8285 
8286 			*(__le32 *)&cld->ipaddr.raw_v6.data[i * 2] = cpu_to_le32(ipa);
8287 		}
8288 	} else {
8289 		ipa = be32_to_cpu(filter->dst_ipv4);
8290 
8291 		memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
8292 	}
8293 
8294 	cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
8295 
8296 	/* tenant_id is not supported by FW now, once the support is enabled
8297 	 * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
8298 	 */
8299 	if (filter->tenant_id)
8300 		return;
8301 }
8302 
8303 /**
8304  * i40e_add_del_cloud_filter - Add/del cloud filter
8305  * @vsi: pointer to VSI
8306  * @filter: cloud filter rule
8307  * @add: if true, add, if false, delete
8308  *
8309  * Add or delete a cloud filter for a specific flow spec.
8310  * Returns 0 if the filter were successfully added.
8311  **/
8312 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
8313 			      struct i40e_cloud_filter *filter, bool add)
8314 {
8315 	struct i40e_aqc_cloud_filters_element_data cld_filter;
8316 	struct i40e_pf *pf = vsi->back;
8317 	int ret;
8318 	static const u16 flag_table[128] = {
8319 		[I40E_CLOUD_FILTER_FLAGS_OMAC]  =
8320 			I40E_AQC_ADD_CLOUD_FILTER_OMAC,
8321 		[I40E_CLOUD_FILTER_FLAGS_IMAC]  =
8322 			I40E_AQC_ADD_CLOUD_FILTER_IMAC,
8323 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
8324 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
8325 		[I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
8326 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
8327 		[I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
8328 			I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
8329 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
8330 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
8331 		[I40E_CLOUD_FILTER_FLAGS_IIP] =
8332 			I40E_AQC_ADD_CLOUD_FILTER_IIP,
8333 	};
8334 
8335 	if (filter->flags >= ARRAY_SIZE(flag_table))
8336 		return I40E_ERR_CONFIG;
8337 
8338 	memset(&cld_filter, 0, sizeof(cld_filter));
8339 
8340 	/* copy element needed to add cloud filter from filter */
8341 	i40e_set_cld_element(filter, &cld_filter);
8342 
8343 	if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
8344 		cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
8345 					     I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
8346 
8347 	if (filter->n_proto == ETH_P_IPV6)
8348 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8349 						I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8350 	else
8351 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8352 						I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8353 
8354 	if (add)
8355 		ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
8356 						&cld_filter, 1);
8357 	else
8358 		ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
8359 						&cld_filter, 1);
8360 	if (ret)
8361 		dev_dbg(&pf->pdev->dev,
8362 			"Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
8363 			add ? "add" : "delete", filter->dst_port, ret,
8364 			pf->hw.aq.asq_last_status);
8365 	else
8366 		dev_info(&pf->pdev->dev,
8367 			 "%s cloud filter for VSI: %d\n",
8368 			 add ? "Added" : "Deleted", filter->seid);
8369 	return ret;
8370 }
8371 
8372 /**
8373  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
8374  * @vsi: pointer to VSI
8375  * @filter: cloud filter rule
8376  * @add: if true, add, if false, delete
8377  *
8378  * Add or delete a cloud filter for a specific flow spec using big buffer.
8379  * Returns 0 if the filter were successfully added.
8380  **/
8381 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
8382 				      struct i40e_cloud_filter *filter,
8383 				      bool add)
8384 {
8385 	struct i40e_aqc_cloud_filters_element_bb cld_filter;
8386 	struct i40e_pf *pf = vsi->back;
8387 	int ret;
8388 
8389 	/* Both (src/dst) valid mac_addr are not supported */
8390 	if ((is_valid_ether_addr(filter->dst_mac) &&
8391 	     is_valid_ether_addr(filter->src_mac)) ||
8392 	    (is_multicast_ether_addr(filter->dst_mac) &&
8393 	     is_multicast_ether_addr(filter->src_mac)))
8394 		return -EOPNOTSUPP;
8395 
8396 	/* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
8397 	 * ports are not supported via big buffer now.
8398 	 */
8399 	if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
8400 		return -EOPNOTSUPP;
8401 
8402 	/* adding filter using src_port/src_ip is not supported at this stage */
8403 	if (filter->src_port ||
8404 	    (filter->src_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8405 	    !ipv6_addr_any(&filter->ip.v6.src_ip6))
8406 		return -EOPNOTSUPP;
8407 
8408 	memset(&cld_filter, 0, sizeof(cld_filter));
8409 
8410 	/* copy element needed to add cloud filter from filter */
8411 	i40e_set_cld_element(filter, &cld_filter.element);
8412 
8413 	if (is_valid_ether_addr(filter->dst_mac) ||
8414 	    is_valid_ether_addr(filter->src_mac) ||
8415 	    is_multicast_ether_addr(filter->dst_mac) ||
8416 	    is_multicast_ether_addr(filter->src_mac)) {
8417 		/* MAC + IP : unsupported mode */
8418 		if (filter->dst_ipv4)
8419 			return -EOPNOTSUPP;
8420 
8421 		/* since we validated that L4 port must be valid before
8422 		 * we get here, start with respective "flags" value
8423 		 * and update if vlan is present or not
8424 		 */
8425 		cld_filter.element.flags =
8426 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
8427 
8428 		if (filter->vlan_id) {
8429 			cld_filter.element.flags =
8430 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
8431 		}
8432 
8433 	} else if ((filter->dst_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8434 		   !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
8435 		cld_filter.element.flags =
8436 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
8437 		if (filter->n_proto == ETH_P_IPV6)
8438 			cld_filter.element.flags |=
8439 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8440 		else
8441 			cld_filter.element.flags |=
8442 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8443 	} else {
8444 		dev_err(&pf->pdev->dev,
8445 			"either mac or ip has to be valid for cloud filter\n");
8446 		return -EINVAL;
8447 	}
8448 
8449 	/* Now copy L4 port in Byte 6..7 in general fields */
8450 	cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
8451 						be16_to_cpu(filter->dst_port);
8452 
8453 	if (add) {
8454 		/* Validate current device switch mode, change if necessary */
8455 		ret = i40e_validate_and_set_switch_mode(vsi);
8456 		if (ret) {
8457 			dev_err(&pf->pdev->dev,
8458 				"failed to set switch mode, ret %d\n",
8459 				ret);
8460 			return ret;
8461 		}
8462 
8463 		ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
8464 						   &cld_filter, 1);
8465 	} else {
8466 		ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
8467 						   &cld_filter, 1);
8468 	}
8469 
8470 	if (ret)
8471 		dev_dbg(&pf->pdev->dev,
8472 			"Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
8473 			add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
8474 	else
8475 		dev_info(&pf->pdev->dev,
8476 			 "%s cloud filter for VSI: %d, L4 port: %d\n",
8477 			 add ? "add" : "delete", filter->seid,
8478 			 ntohs(filter->dst_port));
8479 	return ret;
8480 }
8481 
8482 /**
8483  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
8484  * @vsi: Pointer to VSI
8485  * @f: Pointer to struct flow_cls_offload
8486  * @filter: Pointer to cloud filter structure
8487  *
8488  **/
8489 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
8490 				 struct flow_cls_offload *f,
8491 				 struct i40e_cloud_filter *filter)
8492 {
8493 	struct flow_rule *rule = flow_cls_offload_flow_rule(f);
8494 	struct flow_dissector *dissector = rule->match.dissector;
8495 	u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
8496 	struct i40e_pf *pf = vsi->back;
8497 	u8 field_flags = 0;
8498 
8499 	if (dissector->used_keys &
8500 	    ~(BIT(FLOW_DISSECTOR_KEY_CONTROL) |
8501 	      BIT(FLOW_DISSECTOR_KEY_BASIC) |
8502 	      BIT(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
8503 	      BIT(FLOW_DISSECTOR_KEY_VLAN) |
8504 	      BIT(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
8505 	      BIT(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
8506 	      BIT(FLOW_DISSECTOR_KEY_PORTS) |
8507 	      BIT(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
8508 		dev_err(&pf->pdev->dev, "Unsupported key used: 0x%x\n",
8509 			dissector->used_keys);
8510 		return -EOPNOTSUPP;
8511 	}
8512 
8513 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
8514 		struct flow_match_enc_keyid match;
8515 
8516 		flow_rule_match_enc_keyid(rule, &match);
8517 		if (match.mask->keyid != 0)
8518 			field_flags |= I40E_CLOUD_FIELD_TEN_ID;
8519 
8520 		filter->tenant_id = be32_to_cpu(match.key->keyid);
8521 	}
8522 
8523 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
8524 		struct flow_match_basic match;
8525 
8526 		flow_rule_match_basic(rule, &match);
8527 		n_proto_key = ntohs(match.key->n_proto);
8528 		n_proto_mask = ntohs(match.mask->n_proto);
8529 
8530 		if (n_proto_key == ETH_P_ALL) {
8531 			n_proto_key = 0;
8532 			n_proto_mask = 0;
8533 		}
8534 		filter->n_proto = n_proto_key & n_proto_mask;
8535 		filter->ip_proto = match.key->ip_proto;
8536 	}
8537 
8538 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
8539 		struct flow_match_eth_addrs match;
8540 
8541 		flow_rule_match_eth_addrs(rule, &match);
8542 
8543 		/* use is_broadcast and is_zero to check for all 0xf or 0 */
8544 		if (!is_zero_ether_addr(match.mask->dst)) {
8545 			if (is_broadcast_ether_addr(match.mask->dst)) {
8546 				field_flags |= I40E_CLOUD_FIELD_OMAC;
8547 			} else {
8548 				dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
8549 					match.mask->dst);
8550 				return I40E_ERR_CONFIG;
8551 			}
8552 		}
8553 
8554 		if (!is_zero_ether_addr(match.mask->src)) {
8555 			if (is_broadcast_ether_addr(match.mask->src)) {
8556 				field_flags |= I40E_CLOUD_FIELD_IMAC;
8557 			} else {
8558 				dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
8559 					match.mask->src);
8560 				return I40E_ERR_CONFIG;
8561 			}
8562 		}
8563 		ether_addr_copy(filter->dst_mac, match.key->dst);
8564 		ether_addr_copy(filter->src_mac, match.key->src);
8565 	}
8566 
8567 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
8568 		struct flow_match_vlan match;
8569 
8570 		flow_rule_match_vlan(rule, &match);
8571 		if (match.mask->vlan_id) {
8572 			if (match.mask->vlan_id == VLAN_VID_MASK) {
8573 				field_flags |= I40E_CLOUD_FIELD_IVLAN;
8574 
8575 			} else {
8576 				dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
8577 					match.mask->vlan_id);
8578 				return I40E_ERR_CONFIG;
8579 			}
8580 		}
8581 
8582 		filter->vlan_id = cpu_to_be16(match.key->vlan_id);
8583 	}
8584 
8585 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
8586 		struct flow_match_control match;
8587 
8588 		flow_rule_match_control(rule, &match);
8589 		addr_type = match.key->addr_type;
8590 	}
8591 
8592 	if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
8593 		struct flow_match_ipv4_addrs match;
8594 
8595 		flow_rule_match_ipv4_addrs(rule, &match);
8596 		if (match.mask->dst) {
8597 			if (match.mask->dst == cpu_to_be32(0xffffffff)) {
8598 				field_flags |= I40E_CLOUD_FIELD_IIP;
8599 			} else {
8600 				dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
8601 					&match.mask->dst);
8602 				return I40E_ERR_CONFIG;
8603 			}
8604 		}
8605 
8606 		if (match.mask->src) {
8607 			if (match.mask->src == cpu_to_be32(0xffffffff)) {
8608 				field_flags |= I40E_CLOUD_FIELD_IIP;
8609 			} else {
8610 				dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
8611 					&match.mask->src);
8612 				return I40E_ERR_CONFIG;
8613 			}
8614 		}
8615 
8616 		if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
8617 			dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
8618 			return I40E_ERR_CONFIG;
8619 		}
8620 		filter->dst_ipv4 = match.key->dst;
8621 		filter->src_ipv4 = match.key->src;
8622 	}
8623 
8624 	if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
8625 		struct flow_match_ipv6_addrs match;
8626 
8627 		flow_rule_match_ipv6_addrs(rule, &match);
8628 
8629 		/* src and dest IPV6 address should not be LOOPBACK
8630 		 * (0:0:0:0:0:0:0:1), which can be represented as ::1
8631 		 */
8632 		if (ipv6_addr_loopback(&match.key->dst) ||
8633 		    ipv6_addr_loopback(&match.key->src)) {
8634 			dev_err(&pf->pdev->dev,
8635 				"Bad ipv6, addr is LOOPBACK\n");
8636 			return I40E_ERR_CONFIG;
8637 		}
8638 		if (!ipv6_addr_any(&match.mask->dst) ||
8639 		    !ipv6_addr_any(&match.mask->src))
8640 			field_flags |= I40E_CLOUD_FIELD_IIP;
8641 
8642 		memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
8643 		       sizeof(filter->src_ipv6));
8644 		memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
8645 		       sizeof(filter->dst_ipv6));
8646 	}
8647 
8648 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
8649 		struct flow_match_ports match;
8650 
8651 		flow_rule_match_ports(rule, &match);
8652 		if (match.mask->src) {
8653 			if (match.mask->src == cpu_to_be16(0xffff)) {
8654 				field_flags |= I40E_CLOUD_FIELD_IIP;
8655 			} else {
8656 				dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
8657 					be16_to_cpu(match.mask->src));
8658 				return I40E_ERR_CONFIG;
8659 			}
8660 		}
8661 
8662 		if (match.mask->dst) {
8663 			if (match.mask->dst == cpu_to_be16(0xffff)) {
8664 				field_flags |= I40E_CLOUD_FIELD_IIP;
8665 			} else {
8666 				dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
8667 					be16_to_cpu(match.mask->dst));
8668 				return I40E_ERR_CONFIG;
8669 			}
8670 		}
8671 
8672 		filter->dst_port = match.key->dst;
8673 		filter->src_port = match.key->src;
8674 
8675 		switch (filter->ip_proto) {
8676 		case IPPROTO_TCP:
8677 		case IPPROTO_UDP:
8678 			break;
8679 		default:
8680 			dev_err(&pf->pdev->dev,
8681 				"Only UDP and TCP transport are supported\n");
8682 			return -EINVAL;
8683 		}
8684 	}
8685 	filter->flags = field_flags;
8686 	return 0;
8687 }
8688 
8689 /**
8690  * i40e_handle_tclass: Forward to a traffic class on the device
8691  * @vsi: Pointer to VSI
8692  * @tc: traffic class index on the device
8693  * @filter: Pointer to cloud filter structure
8694  *
8695  **/
8696 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
8697 			      struct i40e_cloud_filter *filter)
8698 {
8699 	struct i40e_channel *ch, *ch_tmp;
8700 
8701 	/* direct to a traffic class on the same device */
8702 	if (tc == 0) {
8703 		filter->seid = vsi->seid;
8704 		return 0;
8705 	} else if (vsi->tc_config.enabled_tc & BIT(tc)) {
8706 		if (!filter->dst_port) {
8707 			dev_err(&vsi->back->pdev->dev,
8708 				"Specify destination port to direct to traffic class that is not default\n");
8709 			return -EINVAL;
8710 		}
8711 		if (list_empty(&vsi->ch_list))
8712 			return -EINVAL;
8713 		list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
8714 					 list) {
8715 			if (ch->seid == vsi->tc_seid_map[tc])
8716 				filter->seid = ch->seid;
8717 		}
8718 		return 0;
8719 	}
8720 	dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
8721 	return -EINVAL;
8722 }
8723 
8724 /**
8725  * i40e_configure_clsflower - Configure tc flower filters
8726  * @vsi: Pointer to VSI
8727  * @cls_flower: Pointer to struct flow_cls_offload
8728  *
8729  **/
8730 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
8731 				    struct flow_cls_offload *cls_flower)
8732 {
8733 	int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
8734 	struct i40e_cloud_filter *filter = NULL;
8735 	struct i40e_pf *pf = vsi->back;
8736 	int err = 0;
8737 
8738 	if (tc < 0) {
8739 		dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
8740 		return -EOPNOTSUPP;
8741 	}
8742 
8743 	if (!tc) {
8744 		dev_err(&pf->pdev->dev, "Unable to add filter because of invalid destination");
8745 		return -EINVAL;
8746 	}
8747 
8748 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
8749 	    test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
8750 		return -EBUSY;
8751 
8752 	if (pf->fdir_pf_active_filters ||
8753 	    (!hlist_empty(&pf->fdir_filter_list))) {
8754 		dev_err(&vsi->back->pdev->dev,
8755 			"Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
8756 		return -EINVAL;
8757 	}
8758 
8759 	if (vsi->back->flags & I40E_FLAG_FD_SB_ENABLED) {
8760 		dev_err(&vsi->back->pdev->dev,
8761 			"Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
8762 		vsi->back->flags &= ~I40E_FLAG_FD_SB_ENABLED;
8763 		vsi->back->flags |= I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8764 	}
8765 
8766 	filter = kzalloc(sizeof(*filter), GFP_KERNEL);
8767 	if (!filter)
8768 		return -ENOMEM;
8769 
8770 	filter->cookie = cls_flower->cookie;
8771 
8772 	err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8773 	if (err < 0)
8774 		goto err;
8775 
8776 	err = i40e_handle_tclass(vsi, tc, filter);
8777 	if (err < 0)
8778 		goto err;
8779 
8780 	/* Add cloud filter */
8781 	if (filter->dst_port)
8782 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8783 	else
8784 		err = i40e_add_del_cloud_filter(vsi, filter, true);
8785 
8786 	if (err) {
8787 		dev_err(&pf->pdev->dev, "Failed to add cloud filter, err %d\n",
8788 			err);
8789 		goto err;
8790 	}
8791 
8792 	/* add filter to the ordered list */
8793 	INIT_HLIST_NODE(&filter->cloud_node);
8794 
8795 	hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8796 
8797 	pf->num_cloud_filters++;
8798 
8799 	return err;
8800 err:
8801 	kfree(filter);
8802 	return err;
8803 }
8804 
8805 /**
8806  * i40e_find_cloud_filter - Find the could filter in the list
8807  * @vsi: Pointer to VSI
8808  * @cookie: filter specific cookie
8809  *
8810  **/
8811 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8812 							unsigned long *cookie)
8813 {
8814 	struct i40e_cloud_filter *filter = NULL;
8815 	struct hlist_node *node2;
8816 
8817 	hlist_for_each_entry_safe(filter, node2,
8818 				  &vsi->back->cloud_filter_list, cloud_node)
8819 		if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8820 			return filter;
8821 	return NULL;
8822 }
8823 
8824 /**
8825  * i40e_delete_clsflower - Remove tc flower filters
8826  * @vsi: Pointer to VSI
8827  * @cls_flower: Pointer to struct flow_cls_offload
8828  *
8829  **/
8830 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8831 				 struct flow_cls_offload *cls_flower)
8832 {
8833 	struct i40e_cloud_filter *filter = NULL;
8834 	struct i40e_pf *pf = vsi->back;
8835 	int err = 0;
8836 
8837 	filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8838 
8839 	if (!filter)
8840 		return -EINVAL;
8841 
8842 	hash_del(&filter->cloud_node);
8843 
8844 	if (filter->dst_port)
8845 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8846 	else
8847 		err = i40e_add_del_cloud_filter(vsi, filter, false);
8848 
8849 	kfree(filter);
8850 	if (err) {
8851 		dev_err(&pf->pdev->dev,
8852 			"Failed to delete cloud filter, err %s\n",
8853 			i40e_stat_str(&pf->hw, err));
8854 		return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8855 	}
8856 
8857 	pf->num_cloud_filters--;
8858 	if (!pf->num_cloud_filters)
8859 		if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
8860 		    !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
8861 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
8862 			pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8863 			pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
8864 		}
8865 	return 0;
8866 }
8867 
8868 /**
8869  * i40e_setup_tc_cls_flower - flower classifier offloads
8870  * @np: net device to configure
8871  * @cls_flower: offload data
8872  **/
8873 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8874 				    struct flow_cls_offload *cls_flower)
8875 {
8876 	struct i40e_vsi *vsi = np->vsi;
8877 
8878 	switch (cls_flower->command) {
8879 	case FLOW_CLS_REPLACE:
8880 		return i40e_configure_clsflower(vsi, cls_flower);
8881 	case FLOW_CLS_DESTROY:
8882 		return i40e_delete_clsflower(vsi, cls_flower);
8883 	case FLOW_CLS_STATS:
8884 		return -EOPNOTSUPP;
8885 	default:
8886 		return -EOPNOTSUPP;
8887 	}
8888 }
8889 
8890 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8891 				  void *cb_priv)
8892 {
8893 	struct i40e_netdev_priv *np = cb_priv;
8894 
8895 	if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8896 		return -EOPNOTSUPP;
8897 
8898 	switch (type) {
8899 	case TC_SETUP_CLSFLOWER:
8900 		return i40e_setup_tc_cls_flower(np, type_data);
8901 
8902 	default:
8903 		return -EOPNOTSUPP;
8904 	}
8905 }
8906 
8907 static LIST_HEAD(i40e_block_cb_list);
8908 
8909 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8910 			   void *type_data)
8911 {
8912 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8913 
8914 	switch (type) {
8915 	case TC_SETUP_QDISC_MQPRIO:
8916 		return i40e_setup_tc(netdev, type_data);
8917 	case TC_SETUP_BLOCK:
8918 		return flow_block_cb_setup_simple(type_data,
8919 						  &i40e_block_cb_list,
8920 						  i40e_setup_tc_block_cb,
8921 						  np, np, true);
8922 	default:
8923 		return -EOPNOTSUPP;
8924 	}
8925 }
8926 
8927 /**
8928  * i40e_open - Called when a network interface is made active
8929  * @netdev: network interface device structure
8930  *
8931  * The open entry point is called when a network interface is made
8932  * active by the system (IFF_UP).  At this point all resources needed
8933  * for transmit and receive operations are allocated, the interrupt
8934  * handler is registered with the OS, the netdev watchdog subtask is
8935  * enabled, and the stack is notified that the interface is ready.
8936  *
8937  * Returns 0 on success, negative value on failure
8938  **/
8939 int i40e_open(struct net_device *netdev)
8940 {
8941 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8942 	struct i40e_vsi *vsi = np->vsi;
8943 	struct i40e_pf *pf = vsi->back;
8944 	int err;
8945 
8946 	/* disallow open during test or if eeprom is broken */
8947 	if (test_bit(__I40E_TESTING, pf->state) ||
8948 	    test_bit(__I40E_BAD_EEPROM, pf->state))
8949 		return -EBUSY;
8950 
8951 	netif_carrier_off(netdev);
8952 
8953 	if (i40e_force_link_state(pf, true))
8954 		return -EAGAIN;
8955 
8956 	err = i40e_vsi_open(vsi);
8957 	if (err)
8958 		return err;
8959 
8960 	/* configure global TSO hardware offload settings */
8961 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
8962 						       TCP_FLAG_FIN) >> 16);
8963 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
8964 						       TCP_FLAG_FIN |
8965 						       TCP_FLAG_CWR) >> 16);
8966 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
8967 	udp_tunnel_get_rx_info(netdev);
8968 
8969 	return 0;
8970 }
8971 
8972 /**
8973  * i40e_netif_set_realnum_tx_rx_queues - Update number of tx/rx queues
8974  * @vsi: vsi structure
8975  *
8976  * This updates netdev's number of tx/rx queues
8977  *
8978  * Returns status of setting tx/rx queues
8979  **/
8980 static int i40e_netif_set_realnum_tx_rx_queues(struct i40e_vsi *vsi)
8981 {
8982 	int ret;
8983 
8984 	ret = netif_set_real_num_rx_queues(vsi->netdev,
8985 					   vsi->num_queue_pairs);
8986 	if (ret)
8987 		return ret;
8988 
8989 	return netif_set_real_num_tx_queues(vsi->netdev,
8990 					    vsi->num_queue_pairs);
8991 }
8992 
8993 /**
8994  * i40e_vsi_open -
8995  * @vsi: the VSI to open
8996  *
8997  * Finish initialization of the VSI.
8998  *
8999  * Returns 0 on success, negative value on failure
9000  *
9001  * Note: expects to be called while under rtnl_lock()
9002  **/
9003 int i40e_vsi_open(struct i40e_vsi *vsi)
9004 {
9005 	struct i40e_pf *pf = vsi->back;
9006 	char int_name[I40E_INT_NAME_STR_LEN];
9007 	int err;
9008 
9009 	/* allocate descriptors */
9010 	err = i40e_vsi_setup_tx_resources(vsi);
9011 	if (err)
9012 		goto err_setup_tx;
9013 	err = i40e_vsi_setup_rx_resources(vsi);
9014 	if (err)
9015 		goto err_setup_rx;
9016 
9017 	err = i40e_vsi_configure(vsi);
9018 	if (err)
9019 		goto err_setup_rx;
9020 
9021 	if (vsi->netdev) {
9022 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
9023 			 dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
9024 		err = i40e_vsi_request_irq(vsi, int_name);
9025 		if (err)
9026 			goto err_setup_rx;
9027 
9028 		/* Notify the stack of the actual queue counts. */
9029 		err = i40e_netif_set_realnum_tx_rx_queues(vsi);
9030 		if (err)
9031 			goto err_set_queues;
9032 
9033 	} else if (vsi->type == I40E_VSI_FDIR) {
9034 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
9035 			 dev_driver_string(&pf->pdev->dev),
9036 			 dev_name(&pf->pdev->dev));
9037 		err = i40e_vsi_request_irq(vsi, int_name);
9038 		if (err)
9039 			goto err_setup_rx;
9040 
9041 	} else {
9042 		err = -EINVAL;
9043 		goto err_setup_rx;
9044 	}
9045 
9046 	err = i40e_up_complete(vsi);
9047 	if (err)
9048 		goto err_up_complete;
9049 
9050 	return 0;
9051 
9052 err_up_complete:
9053 	i40e_down(vsi);
9054 err_set_queues:
9055 	i40e_vsi_free_irq(vsi);
9056 err_setup_rx:
9057 	i40e_vsi_free_rx_resources(vsi);
9058 err_setup_tx:
9059 	i40e_vsi_free_tx_resources(vsi);
9060 	if (vsi == pf->vsi[pf->lan_vsi])
9061 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
9062 
9063 	return err;
9064 }
9065 
9066 /**
9067  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
9068  * @pf: Pointer to PF
9069  *
9070  * This function destroys the hlist where all the Flow Director
9071  * filters were saved.
9072  **/
9073 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
9074 {
9075 	struct i40e_fdir_filter *filter;
9076 	struct i40e_flex_pit *pit_entry, *tmp;
9077 	struct hlist_node *node2;
9078 
9079 	hlist_for_each_entry_safe(filter, node2,
9080 				  &pf->fdir_filter_list, fdir_node) {
9081 		hlist_del(&filter->fdir_node);
9082 		kfree(filter);
9083 	}
9084 
9085 	list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
9086 		list_del(&pit_entry->list);
9087 		kfree(pit_entry);
9088 	}
9089 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
9090 
9091 	list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
9092 		list_del(&pit_entry->list);
9093 		kfree(pit_entry);
9094 	}
9095 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
9096 
9097 	pf->fdir_pf_active_filters = 0;
9098 	i40e_reset_fdir_filter_cnt(pf);
9099 
9100 	/* Reprogram the default input set for TCP/IPv4 */
9101 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9102 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9103 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9104 
9105 	/* Reprogram the default input set for TCP/IPv6 */
9106 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_TCP,
9107 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9108 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9109 
9110 	/* Reprogram the default input set for UDP/IPv4 */
9111 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
9112 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9113 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9114 
9115 	/* Reprogram the default input set for UDP/IPv6 */
9116 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_UDP,
9117 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9118 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9119 
9120 	/* Reprogram the default input set for SCTP/IPv4 */
9121 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
9122 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9123 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9124 
9125 	/* Reprogram the default input set for SCTP/IPv6 */
9126 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_SCTP,
9127 				I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9128 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9129 
9130 	/* Reprogram the default input set for Other/IPv4 */
9131 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
9132 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9133 
9134 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
9135 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9136 
9137 	/* Reprogram the default input set for Other/IPv6 */
9138 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_OTHER,
9139 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9140 
9141 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV6,
9142 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9143 }
9144 
9145 /**
9146  * i40e_cloud_filter_exit - Cleans up the cloud filters
9147  * @pf: Pointer to PF
9148  *
9149  * This function destroys the hlist where all the cloud filters
9150  * were saved.
9151  **/
9152 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
9153 {
9154 	struct i40e_cloud_filter *cfilter;
9155 	struct hlist_node *node;
9156 
9157 	hlist_for_each_entry_safe(cfilter, node,
9158 				  &pf->cloud_filter_list, cloud_node) {
9159 		hlist_del(&cfilter->cloud_node);
9160 		kfree(cfilter);
9161 	}
9162 	pf->num_cloud_filters = 0;
9163 
9164 	if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
9165 	    !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
9166 		pf->flags |= I40E_FLAG_FD_SB_ENABLED;
9167 		pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
9168 		pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
9169 	}
9170 }
9171 
9172 /**
9173  * i40e_close - Disables a network interface
9174  * @netdev: network interface device structure
9175  *
9176  * The close entry point is called when an interface is de-activated
9177  * by the OS.  The hardware is still under the driver's control, but
9178  * this netdev interface is disabled.
9179  *
9180  * Returns 0, this is not allowed to fail
9181  **/
9182 int i40e_close(struct net_device *netdev)
9183 {
9184 	struct i40e_netdev_priv *np = netdev_priv(netdev);
9185 	struct i40e_vsi *vsi = np->vsi;
9186 
9187 	i40e_vsi_close(vsi);
9188 
9189 	return 0;
9190 }
9191 
9192 /**
9193  * i40e_do_reset - Start a PF or Core Reset sequence
9194  * @pf: board private structure
9195  * @reset_flags: which reset is requested
9196  * @lock_acquired: indicates whether or not the lock has been acquired
9197  * before this function was called.
9198  *
9199  * The essential difference in resets is that the PF Reset
9200  * doesn't clear the packet buffers, doesn't reset the PE
9201  * firmware, and doesn't bother the other PFs on the chip.
9202  **/
9203 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
9204 {
9205 	u32 val;
9206 
9207 	/* do the biggest reset indicated */
9208 	if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
9209 
9210 		/* Request a Global Reset
9211 		 *
9212 		 * This will start the chip's countdown to the actual full
9213 		 * chip reset event, and a warning interrupt to be sent
9214 		 * to all PFs, including the requestor.  Our handler
9215 		 * for the warning interrupt will deal with the shutdown
9216 		 * and recovery of the switch setup.
9217 		 */
9218 		dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
9219 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9220 		val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
9221 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9222 
9223 	} else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
9224 
9225 		/* Request a Core Reset
9226 		 *
9227 		 * Same as Global Reset, except does *not* include the MAC/PHY
9228 		 */
9229 		dev_dbg(&pf->pdev->dev, "CoreR requested\n");
9230 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9231 		val |= I40E_GLGEN_RTRIG_CORER_MASK;
9232 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9233 		i40e_flush(&pf->hw);
9234 
9235 	} else if (reset_flags & I40E_PF_RESET_FLAG) {
9236 
9237 		/* Request a PF Reset
9238 		 *
9239 		 * Resets only the PF-specific registers
9240 		 *
9241 		 * This goes directly to the tear-down and rebuild of
9242 		 * the switch, since we need to do all the recovery as
9243 		 * for the Core Reset.
9244 		 */
9245 		dev_dbg(&pf->pdev->dev, "PFR requested\n");
9246 		i40e_handle_reset_warning(pf, lock_acquired);
9247 
9248 	} else if (reset_flags & I40E_PF_RESET_AND_REBUILD_FLAG) {
9249 		/* Request a PF Reset
9250 		 *
9251 		 * Resets PF and reinitializes PFs VSI.
9252 		 */
9253 		i40e_prep_for_reset(pf);
9254 		i40e_reset_and_rebuild(pf, true, lock_acquired);
9255 		dev_info(&pf->pdev->dev,
9256 			 pf->flags & I40E_FLAG_DISABLE_FW_LLDP ?
9257 			 "FW LLDP is disabled\n" :
9258 			 "FW LLDP is enabled\n");
9259 
9260 	} else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
9261 		int v;
9262 
9263 		/* Find the VSI(s) that requested a re-init */
9264 		dev_info(&pf->pdev->dev,
9265 			 "VSI reinit requested\n");
9266 		for (v = 0; v < pf->num_alloc_vsi; v++) {
9267 			struct i40e_vsi *vsi = pf->vsi[v];
9268 
9269 			if (vsi != NULL &&
9270 			    test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
9271 					       vsi->state))
9272 				i40e_vsi_reinit_locked(pf->vsi[v]);
9273 		}
9274 	} else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
9275 		int v;
9276 
9277 		/* Find the VSI(s) that needs to be brought down */
9278 		dev_info(&pf->pdev->dev, "VSI down requested\n");
9279 		for (v = 0; v < pf->num_alloc_vsi; v++) {
9280 			struct i40e_vsi *vsi = pf->vsi[v];
9281 
9282 			if (vsi != NULL &&
9283 			    test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
9284 					       vsi->state)) {
9285 				set_bit(__I40E_VSI_DOWN, vsi->state);
9286 				i40e_down(vsi);
9287 			}
9288 		}
9289 	} else {
9290 		dev_info(&pf->pdev->dev,
9291 			 "bad reset request 0x%08x\n", reset_flags);
9292 	}
9293 }
9294 
9295 #ifdef CONFIG_I40E_DCB
9296 /**
9297  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
9298  * @pf: board private structure
9299  * @old_cfg: current DCB config
9300  * @new_cfg: new DCB config
9301  **/
9302 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
9303 			    struct i40e_dcbx_config *old_cfg,
9304 			    struct i40e_dcbx_config *new_cfg)
9305 {
9306 	bool need_reconfig = false;
9307 
9308 	/* Check if ETS configuration has changed */
9309 	if (memcmp(&new_cfg->etscfg,
9310 		   &old_cfg->etscfg,
9311 		   sizeof(new_cfg->etscfg))) {
9312 		/* If Priority Table has changed reconfig is needed */
9313 		if (memcmp(&new_cfg->etscfg.prioritytable,
9314 			   &old_cfg->etscfg.prioritytable,
9315 			   sizeof(new_cfg->etscfg.prioritytable))) {
9316 			need_reconfig = true;
9317 			dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
9318 		}
9319 
9320 		if (memcmp(&new_cfg->etscfg.tcbwtable,
9321 			   &old_cfg->etscfg.tcbwtable,
9322 			   sizeof(new_cfg->etscfg.tcbwtable)))
9323 			dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
9324 
9325 		if (memcmp(&new_cfg->etscfg.tsatable,
9326 			   &old_cfg->etscfg.tsatable,
9327 			   sizeof(new_cfg->etscfg.tsatable)))
9328 			dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
9329 	}
9330 
9331 	/* Check if PFC configuration has changed */
9332 	if (memcmp(&new_cfg->pfc,
9333 		   &old_cfg->pfc,
9334 		   sizeof(new_cfg->pfc))) {
9335 		need_reconfig = true;
9336 		dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
9337 	}
9338 
9339 	/* Check if APP Table has changed */
9340 	if (memcmp(&new_cfg->app,
9341 		   &old_cfg->app,
9342 		   sizeof(new_cfg->app))) {
9343 		need_reconfig = true;
9344 		dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
9345 	}
9346 
9347 	dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
9348 	return need_reconfig;
9349 }
9350 
9351 /**
9352  * i40e_handle_lldp_event - Handle LLDP Change MIB event
9353  * @pf: board private structure
9354  * @e: event info posted on ARQ
9355  **/
9356 static int i40e_handle_lldp_event(struct i40e_pf *pf,
9357 				  struct i40e_arq_event_info *e)
9358 {
9359 	struct i40e_aqc_lldp_get_mib *mib =
9360 		(struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
9361 	struct i40e_hw *hw = &pf->hw;
9362 	struct i40e_dcbx_config tmp_dcbx_cfg;
9363 	bool need_reconfig = false;
9364 	int ret = 0;
9365 	u8 type;
9366 
9367 	/* X710-T*L 2.5G and 5G speeds don't support DCB */
9368 	if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9369 	    (hw->phy.link_info.link_speed &
9370 	     ~(I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB)) &&
9371 	     !(pf->flags & I40E_FLAG_DCB_CAPABLE))
9372 		/* let firmware decide if the DCB should be disabled */
9373 		pf->flags |= I40E_FLAG_DCB_CAPABLE;
9374 
9375 	/* Not DCB capable or capability disabled */
9376 	if (!(pf->flags & I40E_FLAG_DCB_CAPABLE))
9377 		return ret;
9378 
9379 	/* Ignore if event is not for Nearest Bridge */
9380 	type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
9381 		& I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
9382 	dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
9383 	if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
9384 		return ret;
9385 
9386 	/* Check MIB Type and return if event for Remote MIB update */
9387 	type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
9388 	dev_dbg(&pf->pdev->dev,
9389 		"LLDP event mib type %s\n", type ? "remote" : "local");
9390 	if (type == I40E_AQ_LLDP_MIB_REMOTE) {
9391 		/* Update the remote cached instance and return */
9392 		ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
9393 				I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
9394 				&hw->remote_dcbx_config);
9395 		goto exit;
9396 	}
9397 
9398 	/* Store the old configuration */
9399 	tmp_dcbx_cfg = hw->local_dcbx_config;
9400 
9401 	/* Reset the old DCBx configuration data */
9402 	memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
9403 	/* Get updated DCBX data from firmware */
9404 	ret = i40e_get_dcb_config(&pf->hw);
9405 	if (ret) {
9406 		/* X710-T*L 2.5G and 5G speeds don't support DCB */
9407 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9408 		    (hw->phy.link_info.link_speed &
9409 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
9410 			dev_warn(&pf->pdev->dev,
9411 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
9412 			pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
9413 		} else {
9414 			dev_info(&pf->pdev->dev,
9415 				 "Failed querying DCB configuration data from firmware, err %s aq_err %s\n",
9416 				 i40e_stat_str(&pf->hw, ret),
9417 				 i40e_aq_str(&pf->hw,
9418 					     pf->hw.aq.asq_last_status));
9419 		}
9420 		goto exit;
9421 	}
9422 
9423 	/* No change detected in DCBX configs */
9424 	if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
9425 		    sizeof(tmp_dcbx_cfg))) {
9426 		dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
9427 		goto exit;
9428 	}
9429 
9430 	need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
9431 					       &hw->local_dcbx_config);
9432 
9433 	i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
9434 
9435 	if (!need_reconfig)
9436 		goto exit;
9437 
9438 	/* Enable DCB tagging only when more than one TC */
9439 	if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
9440 		pf->flags |= I40E_FLAG_DCB_ENABLED;
9441 	else
9442 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9443 
9444 	set_bit(__I40E_PORT_SUSPENDED, pf->state);
9445 	/* Reconfiguration needed quiesce all VSIs */
9446 	i40e_pf_quiesce_all_vsi(pf);
9447 
9448 	/* Changes in configuration update VEB/VSI */
9449 	i40e_dcb_reconfigure(pf);
9450 
9451 	ret = i40e_resume_port_tx(pf);
9452 
9453 	clear_bit(__I40E_PORT_SUSPENDED, pf->state);
9454 	/* In case of error no point in resuming VSIs */
9455 	if (ret)
9456 		goto exit;
9457 
9458 	/* Wait for the PF's queues to be disabled */
9459 	ret = i40e_pf_wait_queues_disabled(pf);
9460 	if (ret) {
9461 		/* Schedule PF reset to recover */
9462 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9463 		i40e_service_event_schedule(pf);
9464 	} else {
9465 		i40e_pf_unquiesce_all_vsi(pf);
9466 		set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
9467 		set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
9468 	}
9469 
9470 exit:
9471 	return ret;
9472 }
9473 #endif /* CONFIG_I40E_DCB */
9474 
9475 /**
9476  * i40e_do_reset_safe - Protected reset path for userland calls.
9477  * @pf: board private structure
9478  * @reset_flags: which reset is requested
9479  *
9480  **/
9481 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
9482 {
9483 	rtnl_lock();
9484 	i40e_do_reset(pf, reset_flags, true);
9485 	rtnl_unlock();
9486 }
9487 
9488 /**
9489  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
9490  * @pf: board private structure
9491  * @e: event info posted on ARQ
9492  *
9493  * Handler for LAN Queue Overflow Event generated by the firmware for PF
9494  * and VF queues
9495  **/
9496 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
9497 					   struct i40e_arq_event_info *e)
9498 {
9499 	struct i40e_aqc_lan_overflow *data =
9500 		(struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
9501 	u32 queue = le32_to_cpu(data->prtdcb_rupto);
9502 	u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
9503 	struct i40e_hw *hw = &pf->hw;
9504 	struct i40e_vf *vf;
9505 	u16 vf_id;
9506 
9507 	dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
9508 		queue, qtx_ctl);
9509 
9510 	/* Queue belongs to VF, find the VF and issue VF reset */
9511 	if (((qtx_ctl & I40E_QTX_CTL_PFVF_Q_MASK)
9512 	    >> I40E_QTX_CTL_PFVF_Q_SHIFT) == I40E_QTX_CTL_VF_QUEUE) {
9513 		vf_id = (u16)((qtx_ctl & I40E_QTX_CTL_VFVM_INDX_MASK)
9514 			 >> I40E_QTX_CTL_VFVM_INDX_SHIFT);
9515 		vf_id -= hw->func_caps.vf_base_id;
9516 		vf = &pf->vf[vf_id];
9517 		i40e_vc_notify_vf_reset(vf);
9518 		/* Allow VF to process pending reset notification */
9519 		msleep(20);
9520 		i40e_reset_vf(vf, false);
9521 	}
9522 }
9523 
9524 /**
9525  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
9526  * @pf: board private structure
9527  **/
9528 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
9529 {
9530 	u32 val, fcnt_prog;
9531 
9532 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9533 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
9534 	return fcnt_prog;
9535 }
9536 
9537 /**
9538  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
9539  * @pf: board private structure
9540  **/
9541 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
9542 {
9543 	u32 val, fcnt_prog;
9544 
9545 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9546 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
9547 		    ((val & I40E_PFQF_FDSTAT_BEST_CNT_MASK) >>
9548 		      I40E_PFQF_FDSTAT_BEST_CNT_SHIFT);
9549 	return fcnt_prog;
9550 }
9551 
9552 /**
9553  * i40e_get_global_fd_count - Get total FD filters programmed on device
9554  * @pf: board private structure
9555  **/
9556 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
9557 {
9558 	u32 val, fcnt_prog;
9559 
9560 	val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
9561 	fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
9562 		    ((val & I40E_GLQF_FDCNT_0_BESTCNT_MASK) >>
9563 		     I40E_GLQF_FDCNT_0_BESTCNT_SHIFT);
9564 	return fcnt_prog;
9565 }
9566 
9567 /**
9568  * i40e_reenable_fdir_sb - Restore FDir SB capability
9569  * @pf: board private structure
9570  **/
9571 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
9572 {
9573 	if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
9574 		if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
9575 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9576 			dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
9577 }
9578 
9579 /**
9580  * i40e_reenable_fdir_atr - Restore FDir ATR capability
9581  * @pf: board private structure
9582  **/
9583 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
9584 {
9585 	if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
9586 		/* ATR uses the same filtering logic as SB rules. It only
9587 		 * functions properly if the input set mask is at the default
9588 		 * settings. It is safe to restore the default input set
9589 		 * because there are no active TCPv4 filter rules.
9590 		 */
9591 		i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9592 					I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9593 					I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9594 
9595 		if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
9596 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
9597 			dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
9598 	}
9599 }
9600 
9601 /**
9602  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
9603  * @pf: board private structure
9604  * @filter: FDir filter to remove
9605  */
9606 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
9607 				       struct i40e_fdir_filter *filter)
9608 {
9609 	/* Update counters */
9610 	pf->fdir_pf_active_filters--;
9611 	pf->fd_inv = 0;
9612 
9613 	switch (filter->flow_type) {
9614 	case TCP_V4_FLOW:
9615 		pf->fd_tcp4_filter_cnt--;
9616 		break;
9617 	case UDP_V4_FLOW:
9618 		pf->fd_udp4_filter_cnt--;
9619 		break;
9620 	case SCTP_V4_FLOW:
9621 		pf->fd_sctp4_filter_cnt--;
9622 		break;
9623 	case TCP_V6_FLOW:
9624 		pf->fd_tcp6_filter_cnt--;
9625 		break;
9626 	case UDP_V6_FLOW:
9627 		pf->fd_udp6_filter_cnt--;
9628 		break;
9629 	case SCTP_V6_FLOW:
9630 		pf->fd_udp6_filter_cnt--;
9631 		break;
9632 	case IP_USER_FLOW:
9633 		switch (filter->ipl4_proto) {
9634 		case IPPROTO_TCP:
9635 			pf->fd_tcp4_filter_cnt--;
9636 			break;
9637 		case IPPROTO_UDP:
9638 			pf->fd_udp4_filter_cnt--;
9639 			break;
9640 		case IPPROTO_SCTP:
9641 			pf->fd_sctp4_filter_cnt--;
9642 			break;
9643 		case IPPROTO_IP:
9644 			pf->fd_ip4_filter_cnt--;
9645 			break;
9646 		}
9647 		break;
9648 	case IPV6_USER_FLOW:
9649 		switch (filter->ipl4_proto) {
9650 		case IPPROTO_TCP:
9651 			pf->fd_tcp6_filter_cnt--;
9652 			break;
9653 		case IPPROTO_UDP:
9654 			pf->fd_udp6_filter_cnt--;
9655 			break;
9656 		case IPPROTO_SCTP:
9657 			pf->fd_sctp6_filter_cnt--;
9658 			break;
9659 		case IPPROTO_IP:
9660 			pf->fd_ip6_filter_cnt--;
9661 			break;
9662 		}
9663 		break;
9664 	}
9665 
9666 	/* Remove the filter from the list and free memory */
9667 	hlist_del(&filter->fdir_node);
9668 	kfree(filter);
9669 }
9670 
9671 /**
9672  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
9673  * @pf: board private structure
9674  **/
9675 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
9676 {
9677 	struct i40e_fdir_filter *filter;
9678 	u32 fcnt_prog, fcnt_avail;
9679 	struct hlist_node *node;
9680 
9681 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9682 		return;
9683 
9684 	/* Check if we have enough room to re-enable FDir SB capability. */
9685 	fcnt_prog = i40e_get_global_fd_count(pf);
9686 	fcnt_avail = pf->fdir_pf_filter_count;
9687 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
9688 	    (pf->fd_add_err == 0) ||
9689 	    (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
9690 		i40e_reenable_fdir_sb(pf);
9691 
9692 	/* We should wait for even more space before re-enabling ATR.
9693 	 * Additionally, we cannot enable ATR as long as we still have TCP SB
9694 	 * rules active.
9695 	 */
9696 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
9697 	    pf->fd_tcp4_filter_cnt == 0 && pf->fd_tcp6_filter_cnt == 0)
9698 		i40e_reenable_fdir_atr(pf);
9699 
9700 	/* if hw had a problem adding a filter, delete it */
9701 	if (pf->fd_inv > 0) {
9702 		hlist_for_each_entry_safe(filter, node,
9703 					  &pf->fdir_filter_list, fdir_node)
9704 			if (filter->fd_id == pf->fd_inv)
9705 				i40e_delete_invalid_filter(pf, filter);
9706 	}
9707 }
9708 
9709 #define I40E_MIN_FD_FLUSH_INTERVAL 10
9710 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
9711 /**
9712  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
9713  * @pf: board private structure
9714  **/
9715 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
9716 {
9717 	unsigned long min_flush_time;
9718 	int flush_wait_retry = 50;
9719 	bool disable_atr = false;
9720 	int fd_room;
9721 	int reg;
9722 
9723 	if (!time_after(jiffies, pf->fd_flush_timestamp +
9724 				 (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
9725 		return;
9726 
9727 	/* If the flush is happening too quick and we have mostly SB rules we
9728 	 * should not re-enable ATR for some time.
9729 	 */
9730 	min_flush_time = pf->fd_flush_timestamp +
9731 			 (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
9732 	fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
9733 
9734 	if (!(time_after(jiffies, min_flush_time)) &&
9735 	    (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
9736 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9737 			dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
9738 		disable_atr = true;
9739 	}
9740 
9741 	pf->fd_flush_timestamp = jiffies;
9742 	set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9743 	/* flush all filters */
9744 	wr32(&pf->hw, I40E_PFQF_CTL_1,
9745 	     I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
9746 	i40e_flush(&pf->hw);
9747 	pf->fd_flush_cnt++;
9748 	pf->fd_add_err = 0;
9749 	do {
9750 		/* Check FD flush status every 5-6msec */
9751 		usleep_range(5000, 6000);
9752 		reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
9753 		if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
9754 			break;
9755 	} while (flush_wait_retry--);
9756 	if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
9757 		dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
9758 	} else {
9759 		/* replay sideband filters */
9760 		i40e_fdir_filter_restore(pf->vsi[pf->lan_vsi]);
9761 		if (!disable_atr && !pf->fd_tcp4_filter_cnt)
9762 			clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9763 		clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
9764 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
9765 			dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
9766 	}
9767 }
9768 
9769 /**
9770  * i40e_get_current_atr_cnt - Get the count of total FD ATR filters programmed
9771  * @pf: board private structure
9772  **/
9773 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
9774 {
9775 	return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
9776 }
9777 
9778 /**
9779  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
9780  * @pf: board private structure
9781  **/
9782 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
9783 {
9784 
9785 	/* if interface is down do nothing */
9786 	if (test_bit(__I40E_DOWN, pf->state))
9787 		return;
9788 
9789 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9790 		i40e_fdir_flush_and_replay(pf);
9791 
9792 	i40e_fdir_check_and_reenable(pf);
9793 
9794 }
9795 
9796 /**
9797  * i40e_vsi_link_event - notify VSI of a link event
9798  * @vsi: vsi to be notified
9799  * @link_up: link up or down
9800  **/
9801 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
9802 {
9803 	if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
9804 		return;
9805 
9806 	switch (vsi->type) {
9807 	case I40E_VSI_MAIN:
9808 		if (!vsi->netdev || !vsi->netdev_registered)
9809 			break;
9810 
9811 		if (link_up) {
9812 			netif_carrier_on(vsi->netdev);
9813 			netif_tx_wake_all_queues(vsi->netdev);
9814 		} else {
9815 			netif_carrier_off(vsi->netdev);
9816 			netif_tx_stop_all_queues(vsi->netdev);
9817 		}
9818 		break;
9819 
9820 	case I40E_VSI_SRIOV:
9821 	case I40E_VSI_VMDQ2:
9822 	case I40E_VSI_CTRL:
9823 	case I40E_VSI_IWARP:
9824 	case I40E_VSI_MIRROR:
9825 	default:
9826 		/* there is no notification for other VSIs */
9827 		break;
9828 	}
9829 }
9830 
9831 /**
9832  * i40e_veb_link_event - notify elements on the veb of a link event
9833  * @veb: veb to be notified
9834  * @link_up: link up or down
9835  **/
9836 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
9837 {
9838 	struct i40e_pf *pf;
9839 	int i;
9840 
9841 	if (!veb || !veb->pf)
9842 		return;
9843 	pf = veb->pf;
9844 
9845 	/* depth first... */
9846 	for (i = 0; i < I40E_MAX_VEB; i++)
9847 		if (pf->veb[i] && (pf->veb[i]->uplink_seid == veb->seid))
9848 			i40e_veb_link_event(pf->veb[i], link_up);
9849 
9850 	/* ... now the local VSIs */
9851 	for (i = 0; i < pf->num_alloc_vsi; i++)
9852 		if (pf->vsi[i] && (pf->vsi[i]->uplink_seid == veb->seid))
9853 			i40e_vsi_link_event(pf->vsi[i], link_up);
9854 }
9855 
9856 /**
9857  * i40e_link_event - Update netif_carrier status
9858  * @pf: board private structure
9859  **/
9860 static void i40e_link_event(struct i40e_pf *pf)
9861 {
9862 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9863 	u8 new_link_speed, old_link_speed;
9864 	i40e_status status;
9865 	bool new_link, old_link;
9866 #ifdef CONFIG_I40E_DCB
9867 	int err;
9868 #endif /* CONFIG_I40E_DCB */
9869 
9870 	/* set this to force the get_link_status call to refresh state */
9871 	pf->hw.phy.get_link_info = true;
9872 	old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9873 	status = i40e_get_link_status(&pf->hw, &new_link);
9874 
9875 	/* On success, disable temp link polling */
9876 	if (status == I40E_SUCCESS) {
9877 		clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9878 	} else {
9879 		/* Enable link polling temporarily until i40e_get_link_status
9880 		 * returns I40E_SUCCESS
9881 		 */
9882 		set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9883 		dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9884 			status);
9885 		return;
9886 	}
9887 
9888 	old_link_speed = pf->hw.phy.link_info_old.link_speed;
9889 	new_link_speed = pf->hw.phy.link_info.link_speed;
9890 
9891 	if (new_link == old_link &&
9892 	    new_link_speed == old_link_speed &&
9893 	    (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9894 	     new_link == netif_carrier_ok(vsi->netdev)))
9895 		return;
9896 
9897 	i40e_print_link_message(vsi, new_link);
9898 
9899 	/* Notify the base of the switch tree connected to
9900 	 * the link.  Floating VEBs are not notified.
9901 	 */
9902 	if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
9903 		i40e_veb_link_event(pf->veb[pf->lan_veb], new_link);
9904 	else
9905 		i40e_vsi_link_event(vsi, new_link);
9906 
9907 	if (pf->vf)
9908 		i40e_vc_notify_link_state(pf);
9909 
9910 	if (pf->flags & I40E_FLAG_PTP)
9911 		i40e_ptp_set_increment(pf);
9912 #ifdef CONFIG_I40E_DCB
9913 	if (new_link == old_link)
9914 		return;
9915 	/* Not SW DCB so firmware will take care of default settings */
9916 	if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED)
9917 		return;
9918 
9919 	/* We cover here only link down, as after link up in case of SW DCB
9920 	 * SW LLDP agent will take care of setting it up
9921 	 */
9922 	if (!new_link) {
9923 		dev_dbg(&pf->pdev->dev, "Reconfig DCB to single TC as result of Link Down\n");
9924 		memset(&pf->tmp_cfg, 0, sizeof(pf->tmp_cfg));
9925 		err = i40e_dcb_sw_default_config(pf);
9926 		if (err) {
9927 			pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
9928 				       I40E_FLAG_DCB_ENABLED);
9929 		} else {
9930 			pf->dcbx_cap = DCB_CAP_DCBX_HOST |
9931 				       DCB_CAP_DCBX_VER_IEEE;
9932 			pf->flags |= I40E_FLAG_DCB_CAPABLE;
9933 			pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9934 		}
9935 	}
9936 #endif /* CONFIG_I40E_DCB */
9937 }
9938 
9939 /**
9940  * i40e_watchdog_subtask - periodic checks not using event driven response
9941  * @pf: board private structure
9942  **/
9943 static void i40e_watchdog_subtask(struct i40e_pf *pf)
9944 {
9945 	int i;
9946 
9947 	/* if interface is down do nothing */
9948 	if (test_bit(__I40E_DOWN, pf->state) ||
9949 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
9950 		return;
9951 
9952 	/* make sure we don't do these things too often */
9953 	if (time_before(jiffies, (pf->service_timer_previous +
9954 				  pf->service_timer_period)))
9955 		return;
9956 	pf->service_timer_previous = jiffies;
9957 
9958 	if ((pf->flags & I40E_FLAG_LINK_POLLING_ENABLED) ||
9959 	    test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
9960 		i40e_link_event(pf);
9961 
9962 	/* Update the stats for active netdevs so the network stack
9963 	 * can look at updated numbers whenever it cares to
9964 	 */
9965 	for (i = 0; i < pf->num_alloc_vsi; i++)
9966 		if (pf->vsi[i] && pf->vsi[i]->netdev)
9967 			i40e_update_stats(pf->vsi[i]);
9968 
9969 	if (pf->flags & I40E_FLAG_VEB_STATS_ENABLED) {
9970 		/* Update the stats for the active switching components */
9971 		for (i = 0; i < I40E_MAX_VEB; i++)
9972 			if (pf->veb[i])
9973 				i40e_update_veb_stats(pf->veb[i]);
9974 	}
9975 
9976 	i40e_ptp_rx_hang(pf);
9977 	i40e_ptp_tx_hang(pf);
9978 }
9979 
9980 /**
9981  * i40e_reset_subtask - Set up for resetting the device and driver
9982  * @pf: board private structure
9983  **/
9984 static void i40e_reset_subtask(struct i40e_pf *pf)
9985 {
9986 	u32 reset_flags = 0;
9987 
9988 	if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
9989 		reset_flags |= BIT(__I40E_REINIT_REQUESTED);
9990 		clear_bit(__I40E_REINIT_REQUESTED, pf->state);
9991 	}
9992 	if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
9993 		reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
9994 		clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9995 	}
9996 	if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
9997 		reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
9998 		clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
9999 	}
10000 	if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
10001 		reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
10002 		clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
10003 	}
10004 	if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
10005 		reset_flags |= BIT(__I40E_DOWN_REQUESTED);
10006 		clear_bit(__I40E_DOWN_REQUESTED, pf->state);
10007 	}
10008 
10009 	/* If there's a recovery already waiting, it takes
10010 	 * precedence before starting a new reset sequence.
10011 	 */
10012 	if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
10013 		i40e_prep_for_reset(pf);
10014 		i40e_reset(pf);
10015 		i40e_rebuild(pf, false, false);
10016 	}
10017 
10018 	/* If we're already down or resetting, just bail */
10019 	if (reset_flags &&
10020 	    !test_bit(__I40E_DOWN, pf->state) &&
10021 	    !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
10022 		i40e_do_reset(pf, reset_flags, false);
10023 	}
10024 }
10025 
10026 /**
10027  * i40e_handle_link_event - Handle link event
10028  * @pf: board private structure
10029  * @e: event info posted on ARQ
10030  **/
10031 static void i40e_handle_link_event(struct i40e_pf *pf,
10032 				   struct i40e_arq_event_info *e)
10033 {
10034 	struct i40e_aqc_get_link_status *status =
10035 		(struct i40e_aqc_get_link_status *)&e->desc.params.raw;
10036 
10037 	/* Do a new status request to re-enable LSE reporting
10038 	 * and load new status information into the hw struct
10039 	 * This completely ignores any state information
10040 	 * in the ARQ event info, instead choosing to always
10041 	 * issue the AQ update link status command.
10042 	 */
10043 	i40e_link_event(pf);
10044 
10045 	/* Check if module meets thermal requirements */
10046 	if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
10047 		dev_err(&pf->pdev->dev,
10048 			"Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
10049 		dev_err(&pf->pdev->dev,
10050 			"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10051 	} else {
10052 		/* check for unqualified module, if link is down, suppress
10053 		 * the message if link was forced to be down.
10054 		 */
10055 		if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
10056 		    (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
10057 		    (!(status->link_info & I40E_AQ_LINK_UP)) &&
10058 		    (!(pf->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED))) {
10059 			dev_err(&pf->pdev->dev,
10060 				"Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
10061 			dev_err(&pf->pdev->dev,
10062 				"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10063 		}
10064 	}
10065 }
10066 
10067 /**
10068  * i40e_clean_adminq_subtask - Clean the AdminQ rings
10069  * @pf: board private structure
10070  **/
10071 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
10072 {
10073 	struct i40e_arq_event_info event;
10074 	struct i40e_hw *hw = &pf->hw;
10075 	u16 pending, i = 0;
10076 	i40e_status ret;
10077 	u16 opcode;
10078 	u32 oldval;
10079 	u32 val;
10080 
10081 	/* Do not run clean AQ when PF reset fails */
10082 	if (test_bit(__I40E_RESET_FAILED, pf->state))
10083 		return;
10084 
10085 	/* check for error indications */
10086 	val = rd32(&pf->hw, pf->hw.aq.arq.len);
10087 	oldval = val;
10088 	if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
10089 		if (hw->debug_mask & I40E_DEBUG_AQ)
10090 			dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
10091 		val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
10092 	}
10093 	if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
10094 		if (hw->debug_mask & I40E_DEBUG_AQ)
10095 			dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
10096 		val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
10097 		pf->arq_overflows++;
10098 	}
10099 	if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
10100 		if (hw->debug_mask & I40E_DEBUG_AQ)
10101 			dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
10102 		val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
10103 	}
10104 	if (oldval != val)
10105 		wr32(&pf->hw, pf->hw.aq.arq.len, val);
10106 
10107 	val = rd32(&pf->hw, pf->hw.aq.asq.len);
10108 	oldval = val;
10109 	if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
10110 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10111 			dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
10112 		val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
10113 	}
10114 	if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
10115 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10116 			dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
10117 		val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
10118 	}
10119 	if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
10120 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10121 			dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
10122 		val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
10123 	}
10124 	if (oldval != val)
10125 		wr32(&pf->hw, pf->hw.aq.asq.len, val);
10126 
10127 	event.buf_len = I40E_MAX_AQ_BUF_SIZE;
10128 	event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
10129 	if (!event.msg_buf)
10130 		return;
10131 
10132 	do {
10133 		ret = i40e_clean_arq_element(hw, &event, &pending);
10134 		if (ret == I40E_ERR_ADMIN_QUEUE_NO_WORK)
10135 			break;
10136 		else if (ret) {
10137 			dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
10138 			break;
10139 		}
10140 
10141 		opcode = le16_to_cpu(event.desc.opcode);
10142 		switch (opcode) {
10143 
10144 		case i40e_aqc_opc_get_link_status:
10145 			rtnl_lock();
10146 			i40e_handle_link_event(pf, &event);
10147 			rtnl_unlock();
10148 			break;
10149 		case i40e_aqc_opc_send_msg_to_pf:
10150 			ret = i40e_vc_process_vf_msg(pf,
10151 					le16_to_cpu(event.desc.retval),
10152 					le32_to_cpu(event.desc.cookie_high),
10153 					le32_to_cpu(event.desc.cookie_low),
10154 					event.msg_buf,
10155 					event.msg_len);
10156 			break;
10157 		case i40e_aqc_opc_lldp_update_mib:
10158 			dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
10159 #ifdef CONFIG_I40E_DCB
10160 			rtnl_lock();
10161 			i40e_handle_lldp_event(pf, &event);
10162 			rtnl_unlock();
10163 #endif /* CONFIG_I40E_DCB */
10164 			break;
10165 		case i40e_aqc_opc_event_lan_overflow:
10166 			dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
10167 			i40e_handle_lan_overflow_event(pf, &event);
10168 			break;
10169 		case i40e_aqc_opc_send_msg_to_peer:
10170 			dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
10171 			break;
10172 		case i40e_aqc_opc_nvm_erase:
10173 		case i40e_aqc_opc_nvm_update:
10174 		case i40e_aqc_opc_oem_post_update:
10175 			i40e_debug(&pf->hw, I40E_DEBUG_NVM,
10176 				   "ARQ NVM operation 0x%04x completed\n",
10177 				   opcode);
10178 			break;
10179 		default:
10180 			dev_info(&pf->pdev->dev,
10181 				 "ARQ: Unknown event 0x%04x ignored\n",
10182 				 opcode);
10183 			break;
10184 		}
10185 	} while (i++ < pf->adminq_work_limit);
10186 
10187 	if (i < pf->adminq_work_limit)
10188 		clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
10189 
10190 	/* re-enable Admin queue interrupt cause */
10191 	val = rd32(hw, I40E_PFINT_ICR0_ENA);
10192 	val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
10193 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
10194 	i40e_flush(hw);
10195 
10196 	kfree(event.msg_buf);
10197 }
10198 
10199 /**
10200  * i40e_verify_eeprom - make sure eeprom is good to use
10201  * @pf: board private structure
10202  **/
10203 static void i40e_verify_eeprom(struct i40e_pf *pf)
10204 {
10205 	int err;
10206 
10207 	err = i40e_diag_eeprom_test(&pf->hw);
10208 	if (err) {
10209 		/* retry in case of garbage read */
10210 		err = i40e_diag_eeprom_test(&pf->hw);
10211 		if (err) {
10212 			dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
10213 				 err);
10214 			set_bit(__I40E_BAD_EEPROM, pf->state);
10215 		}
10216 	}
10217 
10218 	if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
10219 		dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
10220 		clear_bit(__I40E_BAD_EEPROM, pf->state);
10221 	}
10222 }
10223 
10224 /**
10225  * i40e_enable_pf_switch_lb
10226  * @pf: pointer to the PF structure
10227  *
10228  * enable switch loop back or die - no point in a return value
10229  **/
10230 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
10231 {
10232 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10233 	struct i40e_vsi_context ctxt;
10234 	int ret;
10235 
10236 	ctxt.seid = pf->main_vsi_seid;
10237 	ctxt.pf_num = pf->hw.pf_id;
10238 	ctxt.vf_num = 0;
10239 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10240 	if (ret) {
10241 		dev_info(&pf->pdev->dev,
10242 			 "couldn't get PF vsi config, err %s aq_err %s\n",
10243 			 i40e_stat_str(&pf->hw, ret),
10244 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10245 		return;
10246 	}
10247 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10248 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10249 	ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10250 
10251 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10252 	if (ret) {
10253 		dev_info(&pf->pdev->dev,
10254 			 "update vsi switch failed, err %s aq_err %s\n",
10255 			 i40e_stat_str(&pf->hw, ret),
10256 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10257 	}
10258 }
10259 
10260 /**
10261  * i40e_disable_pf_switch_lb
10262  * @pf: pointer to the PF structure
10263  *
10264  * disable switch loop back or die - no point in a return value
10265  **/
10266 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
10267 {
10268 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10269 	struct i40e_vsi_context ctxt;
10270 	int ret;
10271 
10272 	ctxt.seid = pf->main_vsi_seid;
10273 	ctxt.pf_num = pf->hw.pf_id;
10274 	ctxt.vf_num = 0;
10275 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10276 	if (ret) {
10277 		dev_info(&pf->pdev->dev,
10278 			 "couldn't get PF vsi config, err %s aq_err %s\n",
10279 			 i40e_stat_str(&pf->hw, ret),
10280 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10281 		return;
10282 	}
10283 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10284 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10285 	ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10286 
10287 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10288 	if (ret) {
10289 		dev_info(&pf->pdev->dev,
10290 			 "update vsi switch failed, err %s aq_err %s\n",
10291 			 i40e_stat_str(&pf->hw, ret),
10292 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10293 	}
10294 }
10295 
10296 /**
10297  * i40e_config_bridge_mode - Configure the HW bridge mode
10298  * @veb: pointer to the bridge instance
10299  *
10300  * Configure the loop back mode for the LAN VSI that is downlink to the
10301  * specified HW bridge instance. It is expected this function is called
10302  * when a new HW bridge is instantiated.
10303  **/
10304 static void i40e_config_bridge_mode(struct i40e_veb *veb)
10305 {
10306 	struct i40e_pf *pf = veb->pf;
10307 
10308 	if (pf->hw.debug_mask & I40E_DEBUG_LAN)
10309 		dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
10310 			 veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
10311 	if (veb->bridge_mode & BRIDGE_MODE_VEPA)
10312 		i40e_disable_pf_switch_lb(pf);
10313 	else
10314 		i40e_enable_pf_switch_lb(pf);
10315 }
10316 
10317 /**
10318  * i40e_reconstitute_veb - rebuild the VEB and anything connected to it
10319  * @veb: pointer to the VEB instance
10320  *
10321  * This is a recursive function that first builds the attached VSIs then
10322  * recurses in to build the next layer of VEB.  We track the connections
10323  * through our own index numbers because the seid's from the HW could
10324  * change across the reset.
10325  **/
10326 static int i40e_reconstitute_veb(struct i40e_veb *veb)
10327 {
10328 	struct i40e_vsi *ctl_vsi = NULL;
10329 	struct i40e_pf *pf = veb->pf;
10330 	int v, veb_idx;
10331 	int ret;
10332 
10333 	/* build VSI that owns this VEB, temporarily attached to base VEB */
10334 	for (v = 0; v < pf->num_alloc_vsi && !ctl_vsi; v++) {
10335 		if (pf->vsi[v] &&
10336 		    pf->vsi[v]->veb_idx == veb->idx &&
10337 		    pf->vsi[v]->flags & I40E_VSI_FLAG_VEB_OWNER) {
10338 			ctl_vsi = pf->vsi[v];
10339 			break;
10340 		}
10341 	}
10342 	if (!ctl_vsi) {
10343 		dev_info(&pf->pdev->dev,
10344 			 "missing owner VSI for veb_idx %d\n", veb->idx);
10345 		ret = -ENOENT;
10346 		goto end_reconstitute;
10347 	}
10348 	if (ctl_vsi != pf->vsi[pf->lan_vsi])
10349 		ctl_vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
10350 	ret = i40e_add_vsi(ctl_vsi);
10351 	if (ret) {
10352 		dev_info(&pf->pdev->dev,
10353 			 "rebuild of veb_idx %d owner VSI failed: %d\n",
10354 			 veb->idx, ret);
10355 		goto end_reconstitute;
10356 	}
10357 	i40e_vsi_reset_stats(ctl_vsi);
10358 
10359 	/* create the VEB in the switch and move the VSI onto the VEB */
10360 	ret = i40e_add_veb(veb, ctl_vsi);
10361 	if (ret)
10362 		goto end_reconstitute;
10363 
10364 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
10365 		veb->bridge_mode = BRIDGE_MODE_VEB;
10366 	else
10367 		veb->bridge_mode = BRIDGE_MODE_VEPA;
10368 	i40e_config_bridge_mode(veb);
10369 
10370 	/* create the remaining VSIs attached to this VEB */
10371 	for (v = 0; v < pf->num_alloc_vsi; v++) {
10372 		if (!pf->vsi[v] || pf->vsi[v] == ctl_vsi)
10373 			continue;
10374 
10375 		if (pf->vsi[v]->veb_idx == veb->idx) {
10376 			struct i40e_vsi *vsi = pf->vsi[v];
10377 
10378 			vsi->uplink_seid = veb->seid;
10379 			ret = i40e_add_vsi(vsi);
10380 			if (ret) {
10381 				dev_info(&pf->pdev->dev,
10382 					 "rebuild of vsi_idx %d failed: %d\n",
10383 					 v, ret);
10384 				goto end_reconstitute;
10385 			}
10386 			i40e_vsi_reset_stats(vsi);
10387 		}
10388 	}
10389 
10390 	/* create any VEBs attached to this VEB - RECURSION */
10391 	for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
10392 		if (pf->veb[veb_idx] && pf->veb[veb_idx]->veb_idx == veb->idx) {
10393 			pf->veb[veb_idx]->uplink_seid = veb->seid;
10394 			ret = i40e_reconstitute_veb(pf->veb[veb_idx]);
10395 			if (ret)
10396 				break;
10397 		}
10398 	}
10399 
10400 end_reconstitute:
10401 	return ret;
10402 }
10403 
10404 /**
10405  * i40e_get_capabilities - get info about the HW
10406  * @pf: the PF struct
10407  * @list_type: AQ capability to be queried
10408  **/
10409 static int i40e_get_capabilities(struct i40e_pf *pf,
10410 				 enum i40e_admin_queue_opc list_type)
10411 {
10412 	struct i40e_aqc_list_capabilities_element_resp *cap_buf;
10413 	u16 data_size;
10414 	int buf_len;
10415 	int err;
10416 
10417 	buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
10418 	do {
10419 		cap_buf = kzalloc(buf_len, GFP_KERNEL);
10420 		if (!cap_buf)
10421 			return -ENOMEM;
10422 
10423 		/* this loads the data into the hw struct for us */
10424 		err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
10425 						    &data_size, list_type,
10426 						    NULL);
10427 		/* data loaded, buffer no longer needed */
10428 		kfree(cap_buf);
10429 
10430 		if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
10431 			/* retry with a larger buffer */
10432 			buf_len = data_size;
10433 		} else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK || err) {
10434 			dev_info(&pf->pdev->dev,
10435 				 "capability discovery failed, err %s aq_err %s\n",
10436 				 i40e_stat_str(&pf->hw, err),
10437 				 i40e_aq_str(&pf->hw,
10438 					     pf->hw.aq.asq_last_status));
10439 			return -ENODEV;
10440 		}
10441 	} while (err);
10442 
10443 	if (pf->hw.debug_mask & I40E_DEBUG_USER) {
10444 		if (list_type == i40e_aqc_opc_list_func_capabilities) {
10445 			dev_info(&pf->pdev->dev,
10446 				 "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",
10447 				 pf->hw.pf_id, pf->hw.func_caps.num_vfs,
10448 				 pf->hw.func_caps.num_msix_vectors,
10449 				 pf->hw.func_caps.num_msix_vectors_vf,
10450 				 pf->hw.func_caps.fd_filters_guaranteed,
10451 				 pf->hw.func_caps.fd_filters_best_effort,
10452 				 pf->hw.func_caps.num_tx_qp,
10453 				 pf->hw.func_caps.num_vsis);
10454 		} else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
10455 			dev_info(&pf->pdev->dev,
10456 				 "switch_mode=0x%04x, function_valid=0x%08x\n",
10457 				 pf->hw.dev_caps.switch_mode,
10458 				 pf->hw.dev_caps.valid_functions);
10459 			dev_info(&pf->pdev->dev,
10460 				 "SR-IOV=%d, num_vfs for all function=%u\n",
10461 				 pf->hw.dev_caps.sr_iov_1_1,
10462 				 pf->hw.dev_caps.num_vfs);
10463 			dev_info(&pf->pdev->dev,
10464 				 "num_vsis=%u, num_rx:%u, num_tx=%u\n",
10465 				 pf->hw.dev_caps.num_vsis,
10466 				 pf->hw.dev_caps.num_rx_qp,
10467 				 pf->hw.dev_caps.num_tx_qp);
10468 		}
10469 	}
10470 	if (list_type == i40e_aqc_opc_list_func_capabilities) {
10471 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
10472 		       + pf->hw.func_caps.num_vfs)
10473 		if (pf->hw.revision_id == 0 &&
10474 		    pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
10475 			dev_info(&pf->pdev->dev,
10476 				 "got num_vsis %d, setting num_vsis to %d\n",
10477 				 pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
10478 			pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
10479 		}
10480 	}
10481 	return 0;
10482 }
10483 
10484 static int i40e_vsi_clear(struct i40e_vsi *vsi);
10485 
10486 /**
10487  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
10488  * @pf: board private structure
10489  **/
10490 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
10491 {
10492 	struct i40e_vsi *vsi;
10493 
10494 	/* quick workaround for an NVM issue that leaves a critical register
10495 	 * uninitialized
10496 	 */
10497 	if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
10498 		static const u32 hkey[] = {
10499 			0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
10500 			0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
10501 			0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
10502 			0x95b3a76d};
10503 		int i;
10504 
10505 		for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
10506 			wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
10507 	}
10508 
10509 	if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
10510 		return;
10511 
10512 	/* find existing VSI and see if it needs configuring */
10513 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10514 
10515 	/* create a new VSI if none exists */
10516 	if (!vsi) {
10517 		vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR,
10518 				     pf->vsi[pf->lan_vsi]->seid, 0);
10519 		if (!vsi) {
10520 			dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
10521 			pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
10522 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
10523 			return;
10524 		}
10525 	}
10526 
10527 	i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
10528 }
10529 
10530 /**
10531  * i40e_fdir_teardown - release the Flow Director resources
10532  * @pf: board private structure
10533  **/
10534 static void i40e_fdir_teardown(struct i40e_pf *pf)
10535 {
10536 	struct i40e_vsi *vsi;
10537 
10538 	i40e_fdir_filter_exit(pf);
10539 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10540 	if (vsi)
10541 		i40e_vsi_release(vsi);
10542 }
10543 
10544 /**
10545  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
10546  * @vsi: PF main vsi
10547  * @seid: seid of main or channel VSIs
10548  *
10549  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
10550  * existed before reset
10551  **/
10552 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
10553 {
10554 	struct i40e_cloud_filter *cfilter;
10555 	struct i40e_pf *pf = vsi->back;
10556 	struct hlist_node *node;
10557 	i40e_status ret;
10558 
10559 	/* Add cloud filters back if they exist */
10560 	hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
10561 				  cloud_node) {
10562 		if (cfilter->seid != seid)
10563 			continue;
10564 
10565 		if (cfilter->dst_port)
10566 			ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
10567 								true);
10568 		else
10569 			ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
10570 
10571 		if (ret) {
10572 			dev_dbg(&pf->pdev->dev,
10573 				"Failed to rebuild cloud filter, err %s aq_err %s\n",
10574 				i40e_stat_str(&pf->hw, ret),
10575 				i40e_aq_str(&pf->hw,
10576 					    pf->hw.aq.asq_last_status));
10577 			return ret;
10578 		}
10579 	}
10580 	return 0;
10581 }
10582 
10583 /**
10584  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
10585  * @vsi: PF main vsi
10586  *
10587  * Rebuilds channel VSIs if they existed before reset
10588  **/
10589 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
10590 {
10591 	struct i40e_channel *ch, *ch_tmp;
10592 	i40e_status ret;
10593 
10594 	if (list_empty(&vsi->ch_list))
10595 		return 0;
10596 
10597 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
10598 		if (!ch->initialized)
10599 			break;
10600 		/* Proceed with creation of channel (VMDq2) VSI */
10601 		ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
10602 		if (ret) {
10603 			dev_info(&vsi->back->pdev->dev,
10604 				 "failed to rebuild channels using uplink_seid %u\n",
10605 				 vsi->uplink_seid);
10606 			return ret;
10607 		}
10608 		/* Reconfigure TX queues using QTX_CTL register */
10609 		ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
10610 		if (ret) {
10611 			dev_info(&vsi->back->pdev->dev,
10612 				 "failed to configure TX rings for channel %u\n",
10613 				 ch->seid);
10614 			return ret;
10615 		}
10616 		/* update 'next_base_queue' */
10617 		vsi->next_base_queue = vsi->next_base_queue +
10618 							ch->num_queue_pairs;
10619 		if (ch->max_tx_rate) {
10620 			u64 credits = ch->max_tx_rate;
10621 
10622 			if (i40e_set_bw_limit(vsi, ch->seid,
10623 					      ch->max_tx_rate))
10624 				return -EINVAL;
10625 
10626 			do_div(credits, I40E_BW_CREDIT_DIVISOR);
10627 			dev_dbg(&vsi->back->pdev->dev,
10628 				"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10629 				ch->max_tx_rate,
10630 				credits,
10631 				ch->seid);
10632 		}
10633 		ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
10634 		if (ret) {
10635 			dev_dbg(&vsi->back->pdev->dev,
10636 				"Failed to rebuild cloud filters for channel VSI %u\n",
10637 				ch->seid);
10638 			return ret;
10639 		}
10640 	}
10641 	return 0;
10642 }
10643 
10644 /**
10645  * i40e_prep_for_reset - prep for the core to reset
10646  * @pf: board private structure
10647  *
10648  * Close up the VFs and other things in prep for PF Reset.
10649   **/
10650 static void i40e_prep_for_reset(struct i40e_pf *pf)
10651 {
10652 	struct i40e_hw *hw = &pf->hw;
10653 	i40e_status ret = 0;
10654 	u32 v;
10655 
10656 	clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
10657 	if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
10658 		return;
10659 	if (i40e_check_asq_alive(&pf->hw))
10660 		i40e_vc_notify_reset(pf);
10661 
10662 	dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
10663 
10664 	/* quiesce the VSIs and their queues that are not already DOWN */
10665 	i40e_pf_quiesce_all_vsi(pf);
10666 
10667 	for (v = 0; v < pf->num_alloc_vsi; v++) {
10668 		if (pf->vsi[v])
10669 			pf->vsi[v]->seid = 0;
10670 	}
10671 
10672 	i40e_shutdown_adminq(&pf->hw);
10673 
10674 	/* call shutdown HMC */
10675 	if (hw->hmc.hmc_obj) {
10676 		ret = i40e_shutdown_lan_hmc(hw);
10677 		if (ret)
10678 			dev_warn(&pf->pdev->dev,
10679 				 "shutdown_lan_hmc failed: %d\n", ret);
10680 	}
10681 
10682 	/* Save the current PTP time so that we can restore the time after the
10683 	 * reset completes.
10684 	 */
10685 	i40e_ptp_save_hw_time(pf);
10686 }
10687 
10688 /**
10689  * i40e_send_version - update firmware with driver version
10690  * @pf: PF struct
10691  */
10692 static void i40e_send_version(struct i40e_pf *pf)
10693 {
10694 	struct i40e_driver_version dv;
10695 
10696 	dv.major_version = 0xff;
10697 	dv.minor_version = 0xff;
10698 	dv.build_version = 0xff;
10699 	dv.subbuild_version = 0;
10700 	strscpy(dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string));
10701 	i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
10702 }
10703 
10704 /**
10705  * i40e_get_oem_version - get OEM specific version information
10706  * @hw: pointer to the hardware structure
10707  **/
10708 static void i40e_get_oem_version(struct i40e_hw *hw)
10709 {
10710 	u16 block_offset = 0xffff;
10711 	u16 block_length = 0;
10712 	u16 capabilities = 0;
10713 	u16 gen_snap = 0;
10714 	u16 release = 0;
10715 
10716 #define I40E_SR_NVM_OEM_VERSION_PTR		0x1B
10717 #define I40E_NVM_OEM_LENGTH_OFFSET		0x00
10718 #define I40E_NVM_OEM_CAPABILITIES_OFFSET	0x01
10719 #define I40E_NVM_OEM_GEN_OFFSET			0x02
10720 #define I40E_NVM_OEM_RELEASE_OFFSET		0x03
10721 #define I40E_NVM_OEM_CAPABILITIES_MASK		0x000F
10722 #define I40E_NVM_OEM_LENGTH			3
10723 
10724 	/* Check if pointer to OEM version block is valid. */
10725 	i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
10726 	if (block_offset == 0xffff)
10727 		return;
10728 
10729 	/* Check if OEM version block has correct length. */
10730 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
10731 			   &block_length);
10732 	if (block_length < I40E_NVM_OEM_LENGTH)
10733 		return;
10734 
10735 	/* Check if OEM version format is as expected. */
10736 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
10737 			   &capabilities);
10738 	if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
10739 		return;
10740 
10741 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
10742 			   &gen_snap);
10743 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
10744 			   &release);
10745 	hw->nvm.oem_ver = (gen_snap << I40E_OEM_SNAP_SHIFT) | release;
10746 	hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
10747 }
10748 
10749 /**
10750  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
10751  * @pf: board private structure
10752  **/
10753 static int i40e_reset(struct i40e_pf *pf)
10754 {
10755 	struct i40e_hw *hw = &pf->hw;
10756 	i40e_status ret;
10757 
10758 	ret = i40e_pf_reset(hw);
10759 	if (ret) {
10760 		dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
10761 		set_bit(__I40E_RESET_FAILED, pf->state);
10762 		clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10763 	} else {
10764 		pf->pfr_count++;
10765 	}
10766 	return ret;
10767 }
10768 
10769 /**
10770  * i40e_rebuild - rebuild using a saved config
10771  * @pf: board private structure
10772  * @reinit: if the Main VSI needs to re-initialized.
10773  * @lock_acquired: indicates whether or not the lock has been acquired
10774  * before this function was called.
10775  **/
10776 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
10777 {
10778 	const bool is_recovery_mode_reported = i40e_check_recovery_mode(pf);
10779 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10780 	struct i40e_hw *hw = &pf->hw;
10781 	i40e_status ret;
10782 	u32 val;
10783 	int v;
10784 
10785 	if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10786 	    is_recovery_mode_reported)
10787 		i40e_set_ethtool_ops(pf->vsi[pf->lan_vsi]->netdev);
10788 
10789 	if (test_bit(__I40E_DOWN, pf->state) &&
10790 	    !test_bit(__I40E_RECOVERY_MODE, pf->state))
10791 		goto clear_recovery;
10792 	dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
10793 
10794 	/* rebuild the basics for the AdminQ, HMC, and initial HW switch */
10795 	ret = i40e_init_adminq(&pf->hw);
10796 	if (ret) {
10797 		dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %s aq_err %s\n",
10798 			 i40e_stat_str(&pf->hw, ret),
10799 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10800 		goto clear_recovery;
10801 	}
10802 	i40e_get_oem_version(&pf->hw);
10803 
10804 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state)) {
10805 		/* The following delay is necessary for firmware update. */
10806 		mdelay(1000);
10807 	}
10808 
10809 	/* re-verify the eeprom if we just had an EMP reset */
10810 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
10811 		i40e_verify_eeprom(pf);
10812 
10813 	/* if we are going out of or into recovery mode we have to act
10814 	 * accordingly with regard to resources initialization
10815 	 * and deinitialization
10816 	 */
10817 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10818 		if (i40e_get_capabilities(pf,
10819 					  i40e_aqc_opc_list_func_capabilities))
10820 			goto end_unlock;
10821 
10822 		if (is_recovery_mode_reported) {
10823 			/* we're staying in recovery mode so we'll reinitialize
10824 			 * misc vector here
10825 			 */
10826 			if (i40e_setup_misc_vector_for_recovery_mode(pf))
10827 				goto end_unlock;
10828 		} else {
10829 			if (!lock_acquired)
10830 				rtnl_lock();
10831 			/* we're going out of recovery mode so we'll free
10832 			 * the IRQ allocated specifically for recovery mode
10833 			 * and restore the interrupt scheme
10834 			 */
10835 			free_irq(pf->pdev->irq, pf);
10836 			i40e_clear_interrupt_scheme(pf);
10837 			if (i40e_restore_interrupt_scheme(pf))
10838 				goto end_unlock;
10839 		}
10840 
10841 		/* tell the firmware that we're starting */
10842 		i40e_send_version(pf);
10843 
10844 		/* bail out in case recovery mode was detected, as there is
10845 		 * no need for further configuration.
10846 		 */
10847 		goto end_unlock;
10848 	}
10849 
10850 	i40e_clear_pxe_mode(hw);
10851 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10852 	if (ret)
10853 		goto end_core_reset;
10854 
10855 	ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10856 				hw->func_caps.num_rx_qp, 0, 0);
10857 	if (ret) {
10858 		dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10859 		goto end_core_reset;
10860 	}
10861 	ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10862 	if (ret) {
10863 		dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10864 		goto end_core_reset;
10865 	}
10866 
10867 #ifdef CONFIG_I40E_DCB
10868 	/* Enable FW to write a default DCB config on link-up
10869 	 * unless I40E_FLAG_TC_MQPRIO was enabled or DCB
10870 	 * is not supported with new link speed
10871 	 */
10872 	if (i40e_is_tc_mqprio_enabled(pf)) {
10873 		i40e_aq_set_dcb_parameters(hw, false, NULL);
10874 	} else {
10875 		if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
10876 		    (hw->phy.link_info.link_speed &
10877 		     (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
10878 			i40e_aq_set_dcb_parameters(hw, false, NULL);
10879 			dev_warn(&pf->pdev->dev,
10880 				 "DCB is not supported for X710-T*L 2.5/5G speeds\n");
10881 			pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10882 		} else {
10883 			i40e_aq_set_dcb_parameters(hw, true, NULL);
10884 			ret = i40e_init_pf_dcb(pf);
10885 			if (ret) {
10886 				dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n",
10887 					 ret);
10888 				pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10889 				/* Continue without DCB enabled */
10890 			}
10891 		}
10892 	}
10893 
10894 #endif /* CONFIG_I40E_DCB */
10895 	if (!lock_acquired)
10896 		rtnl_lock();
10897 	ret = i40e_setup_pf_switch(pf, reinit, true);
10898 	if (ret)
10899 		goto end_unlock;
10900 
10901 	/* The driver only wants link up/down and module qualification
10902 	 * reports from firmware.  Note the negative logic.
10903 	 */
10904 	ret = i40e_aq_set_phy_int_mask(&pf->hw,
10905 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
10906 					 I40E_AQ_EVENT_MEDIA_NA |
10907 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10908 	if (ret)
10909 		dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
10910 			 i40e_stat_str(&pf->hw, ret),
10911 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10912 
10913 	/* Rebuild the VSIs and VEBs that existed before reset.
10914 	 * They are still in our local switch element arrays, so only
10915 	 * need to rebuild the switch model in the HW.
10916 	 *
10917 	 * If there were VEBs but the reconstitution failed, we'll try
10918 	 * to recover minimal use by getting the basic PF VSI working.
10919 	 */
10920 	if (vsi->uplink_seid != pf->mac_seid) {
10921 		dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
10922 		/* find the one VEB connected to the MAC, and find orphans */
10923 		for (v = 0; v < I40E_MAX_VEB; v++) {
10924 			if (!pf->veb[v])
10925 				continue;
10926 
10927 			if (pf->veb[v]->uplink_seid == pf->mac_seid ||
10928 			    pf->veb[v]->uplink_seid == 0) {
10929 				ret = i40e_reconstitute_veb(pf->veb[v]);
10930 
10931 				if (!ret)
10932 					continue;
10933 
10934 				/* If Main VEB failed, we're in deep doodoo,
10935 				 * so give up rebuilding the switch and set up
10936 				 * for minimal rebuild of PF VSI.
10937 				 * If orphan failed, we'll report the error
10938 				 * but try to keep going.
10939 				 */
10940 				if (pf->veb[v]->uplink_seid == pf->mac_seid) {
10941 					dev_info(&pf->pdev->dev,
10942 						 "rebuild of switch failed: %d, will try to set up simple PF connection\n",
10943 						 ret);
10944 					vsi->uplink_seid = pf->mac_seid;
10945 					break;
10946 				} else if (pf->veb[v]->uplink_seid == 0) {
10947 					dev_info(&pf->pdev->dev,
10948 						 "rebuild of orphan VEB failed: %d\n",
10949 						 ret);
10950 				}
10951 			}
10952 		}
10953 	}
10954 
10955 	if (vsi->uplink_seid == pf->mac_seid) {
10956 		dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
10957 		/* no VEB, so rebuild only the Main VSI */
10958 		ret = i40e_add_vsi(vsi);
10959 		if (ret) {
10960 			dev_info(&pf->pdev->dev,
10961 				 "rebuild of Main VSI failed: %d\n", ret);
10962 			goto end_unlock;
10963 		}
10964 	}
10965 
10966 	if (vsi->mqprio_qopt.max_rate[0]) {
10967 		u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0];
10968 		u64 credits = 0;
10969 
10970 		do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
10971 		ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
10972 		if (ret)
10973 			goto end_unlock;
10974 
10975 		credits = max_tx_rate;
10976 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
10977 		dev_dbg(&vsi->back->pdev->dev,
10978 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10979 			max_tx_rate,
10980 			credits,
10981 			vsi->seid);
10982 	}
10983 
10984 	ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
10985 	if (ret)
10986 		goto end_unlock;
10987 
10988 	/* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
10989 	 * for this main VSI if they exist
10990 	 */
10991 	ret = i40e_rebuild_channels(vsi);
10992 	if (ret)
10993 		goto end_unlock;
10994 
10995 	/* Reconfigure hardware for allowing smaller MSS in the case
10996 	 * of TSO, so that we avoid the MDD being fired and causing
10997 	 * a reset in the case of small MSS+TSO.
10998 	 */
10999 #define I40E_REG_MSS          0x000E64DC
11000 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
11001 #define I40E_64BYTE_MSS       0x400000
11002 	val = rd32(hw, I40E_REG_MSS);
11003 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
11004 		val &= ~I40E_REG_MSS_MIN_MASK;
11005 		val |= I40E_64BYTE_MSS;
11006 		wr32(hw, I40E_REG_MSS, val);
11007 	}
11008 
11009 	if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
11010 		msleep(75);
11011 		ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
11012 		if (ret)
11013 			dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
11014 				 i40e_stat_str(&pf->hw, ret),
11015 				 i40e_aq_str(&pf->hw,
11016 					     pf->hw.aq.asq_last_status));
11017 	}
11018 	/* reinit the misc interrupt */
11019 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11020 		ret = i40e_setup_misc_vector(pf);
11021 
11022 	/* Add a filter to drop all Flow control frames from any VSI from being
11023 	 * transmitted. By doing so we stop a malicious VF from sending out
11024 	 * PAUSE or PFC frames and potentially controlling traffic for other
11025 	 * PF/VF VSIs.
11026 	 * The FW can still send Flow control frames if enabled.
11027 	 */
11028 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
11029 						       pf->main_vsi_seid);
11030 
11031 	/* restart the VSIs that were rebuilt and running before the reset */
11032 	i40e_pf_unquiesce_all_vsi(pf);
11033 
11034 	/* Release the RTNL lock before we start resetting VFs */
11035 	if (!lock_acquired)
11036 		rtnl_unlock();
11037 
11038 	/* Restore promiscuous settings */
11039 	ret = i40e_set_promiscuous(pf, pf->cur_promisc);
11040 	if (ret)
11041 		dev_warn(&pf->pdev->dev,
11042 			 "Failed to restore promiscuous setting: %s, err %s aq_err %s\n",
11043 			 pf->cur_promisc ? "on" : "off",
11044 			 i40e_stat_str(&pf->hw, ret),
11045 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11046 
11047 	i40e_reset_all_vfs(pf, true);
11048 
11049 	/* tell the firmware that we're starting */
11050 	i40e_send_version(pf);
11051 
11052 	/* We've already released the lock, so don't do it again */
11053 	goto end_core_reset;
11054 
11055 end_unlock:
11056 	if (!lock_acquired)
11057 		rtnl_unlock();
11058 end_core_reset:
11059 	clear_bit(__I40E_RESET_FAILED, pf->state);
11060 clear_recovery:
11061 	clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
11062 	clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
11063 }
11064 
11065 /**
11066  * i40e_reset_and_rebuild - reset and rebuild using a saved config
11067  * @pf: board private structure
11068  * @reinit: if the Main VSI needs to re-initialized.
11069  * @lock_acquired: indicates whether or not the lock has been acquired
11070  * before this function was called.
11071  **/
11072 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
11073 				   bool lock_acquired)
11074 {
11075 	int ret;
11076 
11077 	if (test_bit(__I40E_IN_REMOVE, pf->state))
11078 		return;
11079 	/* Now we wait for GRST to settle out.
11080 	 * We don't have to delete the VEBs or VSIs from the hw switch
11081 	 * because the reset will make them disappear.
11082 	 */
11083 	ret = i40e_reset(pf);
11084 	if (!ret)
11085 		i40e_rebuild(pf, reinit, lock_acquired);
11086 }
11087 
11088 /**
11089  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
11090  * @pf: board private structure
11091  *
11092  * Close up the VFs and other things in prep for a Core Reset,
11093  * then get ready to rebuild the world.
11094  * @lock_acquired: indicates whether or not the lock has been acquired
11095  * before this function was called.
11096  **/
11097 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
11098 {
11099 	i40e_prep_for_reset(pf);
11100 	i40e_reset_and_rebuild(pf, false, lock_acquired);
11101 }
11102 
11103 /**
11104  * i40e_handle_mdd_event
11105  * @pf: pointer to the PF structure
11106  *
11107  * Called from the MDD irq handler to identify possibly malicious vfs
11108  **/
11109 static void i40e_handle_mdd_event(struct i40e_pf *pf)
11110 {
11111 	struct i40e_hw *hw = &pf->hw;
11112 	bool mdd_detected = false;
11113 	struct i40e_vf *vf;
11114 	u32 reg;
11115 	int i;
11116 
11117 	if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
11118 		return;
11119 
11120 	/* find what triggered the MDD event */
11121 	reg = rd32(hw, I40E_GL_MDET_TX);
11122 	if (reg & I40E_GL_MDET_TX_VALID_MASK) {
11123 		u8 pf_num = (reg & I40E_GL_MDET_TX_PF_NUM_MASK) >>
11124 				I40E_GL_MDET_TX_PF_NUM_SHIFT;
11125 		u16 vf_num = (reg & I40E_GL_MDET_TX_VF_NUM_MASK) >>
11126 				I40E_GL_MDET_TX_VF_NUM_SHIFT;
11127 		u8 event = (reg & I40E_GL_MDET_TX_EVENT_MASK) >>
11128 				I40E_GL_MDET_TX_EVENT_SHIFT;
11129 		u16 queue = ((reg & I40E_GL_MDET_TX_QUEUE_MASK) >>
11130 				I40E_GL_MDET_TX_QUEUE_SHIFT) -
11131 				pf->hw.func_caps.base_queue;
11132 		if (netif_msg_tx_err(pf))
11133 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
11134 				 event, queue, pf_num, vf_num);
11135 		wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
11136 		mdd_detected = true;
11137 	}
11138 	reg = rd32(hw, I40E_GL_MDET_RX);
11139 	if (reg & I40E_GL_MDET_RX_VALID_MASK) {
11140 		u8 func = (reg & I40E_GL_MDET_RX_FUNCTION_MASK) >>
11141 				I40E_GL_MDET_RX_FUNCTION_SHIFT;
11142 		u8 event = (reg & I40E_GL_MDET_RX_EVENT_MASK) >>
11143 				I40E_GL_MDET_RX_EVENT_SHIFT;
11144 		u16 queue = ((reg & I40E_GL_MDET_RX_QUEUE_MASK) >>
11145 				I40E_GL_MDET_RX_QUEUE_SHIFT) -
11146 				pf->hw.func_caps.base_queue;
11147 		if (netif_msg_rx_err(pf))
11148 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
11149 				 event, queue, func);
11150 		wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
11151 		mdd_detected = true;
11152 	}
11153 
11154 	if (mdd_detected) {
11155 		reg = rd32(hw, I40E_PF_MDET_TX);
11156 		if (reg & I40E_PF_MDET_TX_VALID_MASK) {
11157 			wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
11158 			dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
11159 		}
11160 		reg = rd32(hw, I40E_PF_MDET_RX);
11161 		if (reg & I40E_PF_MDET_RX_VALID_MASK) {
11162 			wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
11163 			dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
11164 		}
11165 	}
11166 
11167 	/* see if one of the VFs needs its hand slapped */
11168 	for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
11169 		vf = &(pf->vf[i]);
11170 		reg = rd32(hw, I40E_VP_MDET_TX(i));
11171 		if (reg & I40E_VP_MDET_TX_VALID_MASK) {
11172 			wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
11173 			vf->num_mdd_events++;
11174 			dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
11175 				 i);
11176 			dev_info(&pf->pdev->dev,
11177 				 "Use PF Control I/F to re-enable the VF\n");
11178 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11179 		}
11180 
11181 		reg = rd32(hw, I40E_VP_MDET_RX(i));
11182 		if (reg & I40E_VP_MDET_RX_VALID_MASK) {
11183 			wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
11184 			vf->num_mdd_events++;
11185 			dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
11186 				 i);
11187 			dev_info(&pf->pdev->dev,
11188 				 "Use PF Control I/F to re-enable the VF\n");
11189 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11190 		}
11191 	}
11192 
11193 	/* re-enable mdd interrupt cause */
11194 	clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
11195 	reg = rd32(hw, I40E_PFINT_ICR0_ENA);
11196 	reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
11197 	wr32(hw, I40E_PFINT_ICR0_ENA, reg);
11198 	i40e_flush(hw);
11199 }
11200 
11201 /**
11202  * i40e_service_task - Run the driver's async subtasks
11203  * @work: pointer to work_struct containing our data
11204  **/
11205 static void i40e_service_task(struct work_struct *work)
11206 {
11207 	struct i40e_pf *pf = container_of(work,
11208 					  struct i40e_pf,
11209 					  service_task);
11210 	unsigned long start_time = jiffies;
11211 
11212 	/* don't bother with service tasks if a reset is in progress */
11213 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
11214 	    test_bit(__I40E_SUSPENDED, pf->state))
11215 		return;
11216 
11217 	if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
11218 		return;
11219 
11220 	if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
11221 		i40e_detect_recover_hung(pf->vsi[pf->lan_vsi]);
11222 		i40e_sync_filters_subtask(pf);
11223 		i40e_reset_subtask(pf);
11224 		i40e_handle_mdd_event(pf);
11225 		i40e_vc_process_vflr_event(pf);
11226 		i40e_watchdog_subtask(pf);
11227 		i40e_fdir_reinit_subtask(pf);
11228 		if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
11229 			/* Client subtask will reopen next time through. */
11230 			i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi],
11231 							   true);
11232 		} else {
11233 			i40e_client_subtask(pf);
11234 			if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
11235 					       pf->state))
11236 				i40e_notify_client_of_l2_param_changes(
11237 								pf->vsi[pf->lan_vsi]);
11238 		}
11239 		i40e_sync_filters_subtask(pf);
11240 	} else {
11241 		i40e_reset_subtask(pf);
11242 	}
11243 
11244 	i40e_clean_adminq_subtask(pf);
11245 
11246 	/* flush memory to make sure state is correct before next watchdog */
11247 	smp_mb__before_atomic();
11248 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
11249 
11250 	/* If the tasks have taken longer than one timer cycle or there
11251 	 * is more work to be done, reschedule the service task now
11252 	 * rather than wait for the timer to tick again.
11253 	 */
11254 	if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
11255 	    test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)		 ||
11256 	    test_bit(__I40E_MDD_EVENT_PENDING, pf->state)		 ||
11257 	    test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
11258 		i40e_service_event_schedule(pf);
11259 }
11260 
11261 /**
11262  * i40e_service_timer - timer callback
11263  * @t: timer list pointer
11264  **/
11265 static void i40e_service_timer(struct timer_list *t)
11266 {
11267 	struct i40e_pf *pf = from_timer(pf, t, service_timer);
11268 
11269 	mod_timer(&pf->service_timer,
11270 		  round_jiffies(jiffies + pf->service_timer_period));
11271 	i40e_service_event_schedule(pf);
11272 }
11273 
11274 /**
11275  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
11276  * @vsi: the VSI being configured
11277  **/
11278 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
11279 {
11280 	struct i40e_pf *pf = vsi->back;
11281 
11282 	switch (vsi->type) {
11283 	case I40E_VSI_MAIN:
11284 		vsi->alloc_queue_pairs = pf->num_lan_qps;
11285 		if (!vsi->num_tx_desc)
11286 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11287 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11288 		if (!vsi->num_rx_desc)
11289 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11290 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11291 		if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11292 			vsi->num_q_vectors = pf->num_lan_msix;
11293 		else
11294 			vsi->num_q_vectors = 1;
11295 
11296 		break;
11297 
11298 	case I40E_VSI_FDIR:
11299 		vsi->alloc_queue_pairs = 1;
11300 		vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11301 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11302 		vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11303 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
11304 		vsi->num_q_vectors = pf->num_fdsb_msix;
11305 		break;
11306 
11307 	case I40E_VSI_VMDQ2:
11308 		vsi->alloc_queue_pairs = pf->num_vmdq_qps;
11309 		if (!vsi->num_tx_desc)
11310 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11311 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11312 		if (!vsi->num_rx_desc)
11313 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11314 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11315 		vsi->num_q_vectors = pf->num_vmdq_msix;
11316 		break;
11317 
11318 	case I40E_VSI_SRIOV:
11319 		vsi->alloc_queue_pairs = pf->num_vf_qps;
11320 		if (!vsi->num_tx_desc)
11321 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11322 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11323 		if (!vsi->num_rx_desc)
11324 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11325 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
11326 		break;
11327 
11328 	default:
11329 		WARN_ON(1);
11330 		return -ENODATA;
11331 	}
11332 
11333 	if (is_kdump_kernel()) {
11334 		vsi->num_tx_desc = I40E_MIN_NUM_DESCRIPTORS;
11335 		vsi->num_rx_desc = I40E_MIN_NUM_DESCRIPTORS;
11336 	}
11337 
11338 	return 0;
11339 }
11340 
11341 /**
11342  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
11343  * @vsi: VSI pointer
11344  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
11345  *
11346  * On error: returns error code (negative)
11347  * On success: returns 0
11348  **/
11349 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
11350 {
11351 	struct i40e_ring **next_rings;
11352 	int size;
11353 	int ret = 0;
11354 
11355 	/* allocate memory for both Tx, XDP Tx and Rx ring pointers */
11356 	size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
11357 	       (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
11358 	vsi->tx_rings = kzalloc(size, GFP_KERNEL);
11359 	if (!vsi->tx_rings)
11360 		return -ENOMEM;
11361 	next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
11362 	if (i40e_enabled_xdp_vsi(vsi)) {
11363 		vsi->xdp_rings = next_rings;
11364 		next_rings += vsi->alloc_queue_pairs;
11365 	}
11366 	vsi->rx_rings = next_rings;
11367 
11368 	if (alloc_qvectors) {
11369 		/* allocate memory for q_vector pointers */
11370 		size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
11371 		vsi->q_vectors = kzalloc(size, GFP_KERNEL);
11372 		if (!vsi->q_vectors) {
11373 			ret = -ENOMEM;
11374 			goto err_vectors;
11375 		}
11376 	}
11377 	return ret;
11378 
11379 err_vectors:
11380 	kfree(vsi->tx_rings);
11381 	return ret;
11382 }
11383 
11384 /**
11385  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
11386  * @pf: board private structure
11387  * @type: type of VSI
11388  *
11389  * On error: returns error code (negative)
11390  * On success: returns vsi index in PF (positive)
11391  **/
11392 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
11393 {
11394 	int ret = -ENODEV;
11395 	struct i40e_vsi *vsi;
11396 	int vsi_idx;
11397 	int i;
11398 
11399 	/* Need to protect the allocation of the VSIs at the PF level */
11400 	mutex_lock(&pf->switch_mutex);
11401 
11402 	/* VSI list may be fragmented if VSI creation/destruction has
11403 	 * been happening.  We can afford to do a quick scan to look
11404 	 * for any free VSIs in the list.
11405 	 *
11406 	 * find next empty vsi slot, looping back around if necessary
11407 	 */
11408 	i = pf->next_vsi;
11409 	while (i < pf->num_alloc_vsi && pf->vsi[i])
11410 		i++;
11411 	if (i >= pf->num_alloc_vsi) {
11412 		i = 0;
11413 		while (i < pf->next_vsi && pf->vsi[i])
11414 			i++;
11415 	}
11416 
11417 	if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
11418 		vsi_idx = i;             /* Found one! */
11419 	} else {
11420 		ret = -ENODEV;
11421 		goto unlock_pf;  /* out of VSI slots! */
11422 	}
11423 	pf->next_vsi = ++i;
11424 
11425 	vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
11426 	if (!vsi) {
11427 		ret = -ENOMEM;
11428 		goto unlock_pf;
11429 	}
11430 	vsi->type = type;
11431 	vsi->back = pf;
11432 	set_bit(__I40E_VSI_DOWN, vsi->state);
11433 	vsi->flags = 0;
11434 	vsi->idx = vsi_idx;
11435 	vsi->int_rate_limit = 0;
11436 	vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
11437 				pf->rss_table_size : 64;
11438 	vsi->netdev_registered = false;
11439 	vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
11440 	hash_init(vsi->mac_filter_hash);
11441 	vsi->irqs_ready = false;
11442 
11443 	if (type == I40E_VSI_MAIN) {
11444 		vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
11445 		if (!vsi->af_xdp_zc_qps)
11446 			goto err_rings;
11447 	}
11448 
11449 	ret = i40e_set_num_rings_in_vsi(vsi);
11450 	if (ret)
11451 		goto err_rings;
11452 
11453 	ret = i40e_vsi_alloc_arrays(vsi, true);
11454 	if (ret)
11455 		goto err_rings;
11456 
11457 	/* Setup default MSIX irq handler for VSI */
11458 	i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
11459 
11460 	/* Initialize VSI lock */
11461 	spin_lock_init(&vsi->mac_filter_hash_lock);
11462 	pf->vsi[vsi_idx] = vsi;
11463 	ret = vsi_idx;
11464 	goto unlock_pf;
11465 
11466 err_rings:
11467 	bitmap_free(vsi->af_xdp_zc_qps);
11468 	pf->next_vsi = i - 1;
11469 	kfree(vsi);
11470 unlock_pf:
11471 	mutex_unlock(&pf->switch_mutex);
11472 	return ret;
11473 }
11474 
11475 /**
11476  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
11477  * @vsi: VSI pointer
11478  * @free_qvectors: a bool to specify if q_vectors need to be freed.
11479  *
11480  * On error: returns error code (negative)
11481  * On success: returns 0
11482  **/
11483 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
11484 {
11485 	/* free the ring and vector containers */
11486 	if (free_qvectors) {
11487 		kfree(vsi->q_vectors);
11488 		vsi->q_vectors = NULL;
11489 	}
11490 	kfree(vsi->tx_rings);
11491 	vsi->tx_rings = NULL;
11492 	vsi->rx_rings = NULL;
11493 	vsi->xdp_rings = NULL;
11494 }
11495 
11496 /**
11497  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
11498  * and lookup table
11499  * @vsi: Pointer to VSI structure
11500  */
11501 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
11502 {
11503 	if (!vsi)
11504 		return;
11505 
11506 	kfree(vsi->rss_hkey_user);
11507 	vsi->rss_hkey_user = NULL;
11508 
11509 	kfree(vsi->rss_lut_user);
11510 	vsi->rss_lut_user = NULL;
11511 }
11512 
11513 /**
11514  * i40e_vsi_clear - Deallocate the VSI provided
11515  * @vsi: the VSI being un-configured
11516  **/
11517 static int i40e_vsi_clear(struct i40e_vsi *vsi)
11518 {
11519 	struct i40e_pf *pf;
11520 
11521 	if (!vsi)
11522 		return 0;
11523 
11524 	if (!vsi->back)
11525 		goto free_vsi;
11526 	pf = vsi->back;
11527 
11528 	mutex_lock(&pf->switch_mutex);
11529 	if (!pf->vsi[vsi->idx]) {
11530 		dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
11531 			vsi->idx, vsi->idx, vsi->type);
11532 		goto unlock_vsi;
11533 	}
11534 
11535 	if (pf->vsi[vsi->idx] != vsi) {
11536 		dev_err(&pf->pdev->dev,
11537 			"pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
11538 			pf->vsi[vsi->idx]->idx,
11539 			pf->vsi[vsi->idx]->type,
11540 			vsi->idx, vsi->type);
11541 		goto unlock_vsi;
11542 	}
11543 
11544 	/* updates the PF for this cleared vsi */
11545 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
11546 	i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
11547 
11548 	bitmap_free(vsi->af_xdp_zc_qps);
11549 	i40e_vsi_free_arrays(vsi, true);
11550 	i40e_clear_rss_config_user(vsi);
11551 
11552 	pf->vsi[vsi->idx] = NULL;
11553 	if (vsi->idx < pf->next_vsi)
11554 		pf->next_vsi = vsi->idx;
11555 
11556 unlock_vsi:
11557 	mutex_unlock(&pf->switch_mutex);
11558 free_vsi:
11559 	kfree(vsi);
11560 
11561 	return 0;
11562 }
11563 
11564 /**
11565  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
11566  * @vsi: the VSI being cleaned
11567  **/
11568 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
11569 {
11570 	int i;
11571 
11572 	if (vsi->tx_rings && vsi->tx_rings[0]) {
11573 		for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11574 			kfree_rcu(vsi->tx_rings[i], rcu);
11575 			WRITE_ONCE(vsi->tx_rings[i], NULL);
11576 			WRITE_ONCE(vsi->rx_rings[i], NULL);
11577 			if (vsi->xdp_rings)
11578 				WRITE_ONCE(vsi->xdp_rings[i], NULL);
11579 		}
11580 	}
11581 }
11582 
11583 /**
11584  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
11585  * @vsi: the VSI being configured
11586  **/
11587 static int i40e_alloc_rings(struct i40e_vsi *vsi)
11588 {
11589 	int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
11590 	struct i40e_pf *pf = vsi->back;
11591 	struct i40e_ring *ring;
11592 
11593 	/* Set basic values in the rings to be used later during open() */
11594 	for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11595 		/* allocate space for both Tx and Rx in one shot */
11596 		ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
11597 		if (!ring)
11598 			goto err_out;
11599 
11600 		ring->queue_index = i;
11601 		ring->reg_idx = vsi->base_queue + i;
11602 		ring->ring_active = false;
11603 		ring->vsi = vsi;
11604 		ring->netdev = vsi->netdev;
11605 		ring->dev = &pf->pdev->dev;
11606 		ring->count = vsi->num_tx_desc;
11607 		ring->size = 0;
11608 		ring->dcb_tc = 0;
11609 		if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11610 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11611 		ring->itr_setting = pf->tx_itr_default;
11612 		WRITE_ONCE(vsi->tx_rings[i], ring++);
11613 
11614 		if (!i40e_enabled_xdp_vsi(vsi))
11615 			goto setup_rx;
11616 
11617 		ring->queue_index = vsi->alloc_queue_pairs + i;
11618 		ring->reg_idx = vsi->base_queue + ring->queue_index;
11619 		ring->ring_active = false;
11620 		ring->vsi = vsi;
11621 		ring->netdev = NULL;
11622 		ring->dev = &pf->pdev->dev;
11623 		ring->count = vsi->num_tx_desc;
11624 		ring->size = 0;
11625 		ring->dcb_tc = 0;
11626 		if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11627 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11628 		set_ring_xdp(ring);
11629 		ring->itr_setting = pf->tx_itr_default;
11630 		WRITE_ONCE(vsi->xdp_rings[i], ring++);
11631 
11632 setup_rx:
11633 		ring->queue_index = i;
11634 		ring->reg_idx = vsi->base_queue + i;
11635 		ring->ring_active = false;
11636 		ring->vsi = vsi;
11637 		ring->netdev = vsi->netdev;
11638 		ring->dev = &pf->pdev->dev;
11639 		ring->count = vsi->num_rx_desc;
11640 		ring->size = 0;
11641 		ring->dcb_tc = 0;
11642 		ring->itr_setting = pf->rx_itr_default;
11643 		WRITE_ONCE(vsi->rx_rings[i], ring);
11644 	}
11645 
11646 	return 0;
11647 
11648 err_out:
11649 	i40e_vsi_clear_rings(vsi);
11650 	return -ENOMEM;
11651 }
11652 
11653 /**
11654  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
11655  * @pf: board private structure
11656  * @vectors: the number of MSI-X vectors to request
11657  *
11658  * Returns the number of vectors reserved, or error
11659  **/
11660 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
11661 {
11662 	vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
11663 					I40E_MIN_MSIX, vectors);
11664 	if (vectors < 0) {
11665 		dev_info(&pf->pdev->dev,
11666 			 "MSI-X vector reservation failed: %d\n", vectors);
11667 		vectors = 0;
11668 	}
11669 
11670 	return vectors;
11671 }
11672 
11673 /**
11674  * i40e_init_msix - Setup the MSIX capability
11675  * @pf: board private structure
11676  *
11677  * Work with the OS to set up the MSIX vectors needed.
11678  *
11679  * Returns the number of vectors reserved or negative on failure
11680  **/
11681 static int i40e_init_msix(struct i40e_pf *pf)
11682 {
11683 	struct i40e_hw *hw = &pf->hw;
11684 	int cpus, extra_vectors;
11685 	int vectors_left;
11686 	int v_budget, i;
11687 	int v_actual;
11688 	int iwarp_requested = 0;
11689 
11690 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
11691 		return -ENODEV;
11692 
11693 	/* The number of vectors we'll request will be comprised of:
11694 	 *   - Add 1 for "other" cause for Admin Queue events, etc.
11695 	 *   - The number of LAN queue pairs
11696 	 *	- Queues being used for RSS.
11697 	 *		We don't need as many as max_rss_size vectors.
11698 	 *		use rss_size instead in the calculation since that
11699 	 *		is governed by number of cpus in the system.
11700 	 *	- assumes symmetric Tx/Rx pairing
11701 	 *   - The number of VMDq pairs
11702 	 *   - The CPU count within the NUMA node if iWARP is enabled
11703 	 * Once we count this up, try the request.
11704 	 *
11705 	 * If we can't get what we want, we'll simplify to nearly nothing
11706 	 * and try again.  If that still fails, we punt.
11707 	 */
11708 	vectors_left = hw->func_caps.num_msix_vectors;
11709 	v_budget = 0;
11710 
11711 	/* reserve one vector for miscellaneous handler */
11712 	if (vectors_left) {
11713 		v_budget++;
11714 		vectors_left--;
11715 	}
11716 
11717 	/* reserve some vectors for the main PF traffic queues. Initially we
11718 	 * only reserve at most 50% of the available vectors, in the case that
11719 	 * the number of online CPUs is large. This ensures that we can enable
11720 	 * extra features as well. Once we've enabled the other features, we
11721 	 * will use any remaining vectors to reach as close as we can to the
11722 	 * number of online CPUs.
11723 	 */
11724 	cpus = num_online_cpus();
11725 	pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
11726 	vectors_left -= pf->num_lan_msix;
11727 
11728 	/* reserve one vector for sideband flow director */
11729 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11730 		if (vectors_left) {
11731 			pf->num_fdsb_msix = 1;
11732 			v_budget++;
11733 			vectors_left--;
11734 		} else {
11735 			pf->num_fdsb_msix = 0;
11736 		}
11737 	}
11738 
11739 	/* can we reserve enough for iWARP? */
11740 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11741 		iwarp_requested = pf->num_iwarp_msix;
11742 
11743 		if (!vectors_left)
11744 			pf->num_iwarp_msix = 0;
11745 		else if (vectors_left < pf->num_iwarp_msix)
11746 			pf->num_iwarp_msix = 1;
11747 		v_budget += pf->num_iwarp_msix;
11748 		vectors_left -= pf->num_iwarp_msix;
11749 	}
11750 
11751 	/* any vectors left over go for VMDq support */
11752 	if (pf->flags & I40E_FLAG_VMDQ_ENABLED) {
11753 		if (!vectors_left) {
11754 			pf->num_vmdq_msix = 0;
11755 			pf->num_vmdq_qps = 0;
11756 		} else {
11757 			int vmdq_vecs_wanted =
11758 				pf->num_vmdq_vsis * pf->num_vmdq_qps;
11759 			int vmdq_vecs =
11760 				min_t(int, vectors_left, vmdq_vecs_wanted);
11761 
11762 			/* if we're short on vectors for what's desired, we limit
11763 			 * the queues per vmdq.  If this is still more than are
11764 			 * available, the user will need to change the number of
11765 			 * queues/vectors used by the PF later with the ethtool
11766 			 * channels command
11767 			 */
11768 			if (vectors_left < vmdq_vecs_wanted) {
11769 				pf->num_vmdq_qps = 1;
11770 				vmdq_vecs_wanted = pf->num_vmdq_vsis;
11771 				vmdq_vecs = min_t(int,
11772 						  vectors_left,
11773 						  vmdq_vecs_wanted);
11774 			}
11775 			pf->num_vmdq_msix = pf->num_vmdq_qps;
11776 
11777 			v_budget += vmdq_vecs;
11778 			vectors_left -= vmdq_vecs;
11779 		}
11780 	}
11781 
11782 	/* On systems with a large number of SMP cores, we previously limited
11783 	 * the number of vectors for num_lan_msix to be at most 50% of the
11784 	 * available vectors, to allow for other features. Now, we add back
11785 	 * the remaining vectors. However, we ensure that the total
11786 	 * num_lan_msix will not exceed num_online_cpus(). To do this, we
11787 	 * calculate the number of vectors we can add without going over the
11788 	 * cap of CPUs. For systems with a small number of CPUs this will be
11789 	 * zero.
11790 	 */
11791 	extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11792 	pf->num_lan_msix += extra_vectors;
11793 	vectors_left -= extra_vectors;
11794 
11795 	WARN(vectors_left < 0,
11796 	     "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11797 
11798 	v_budget += pf->num_lan_msix;
11799 	pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
11800 				   GFP_KERNEL);
11801 	if (!pf->msix_entries)
11802 		return -ENOMEM;
11803 
11804 	for (i = 0; i < v_budget; i++)
11805 		pf->msix_entries[i].entry = i;
11806 	v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11807 
11808 	if (v_actual < I40E_MIN_MSIX) {
11809 		pf->flags &= ~I40E_FLAG_MSIX_ENABLED;
11810 		kfree(pf->msix_entries);
11811 		pf->msix_entries = NULL;
11812 		pci_disable_msix(pf->pdev);
11813 		return -ENODEV;
11814 
11815 	} else if (v_actual == I40E_MIN_MSIX) {
11816 		/* Adjust for minimal MSIX use */
11817 		pf->num_vmdq_vsis = 0;
11818 		pf->num_vmdq_qps = 0;
11819 		pf->num_lan_qps = 1;
11820 		pf->num_lan_msix = 1;
11821 
11822 	} else if (v_actual != v_budget) {
11823 		/* If we have limited resources, we will start with no vectors
11824 		 * for the special features and then allocate vectors to some
11825 		 * of these features based on the policy and at the end disable
11826 		 * the features that did not get any vectors.
11827 		 */
11828 		int vec;
11829 
11830 		dev_info(&pf->pdev->dev,
11831 			 "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11832 			 v_actual, v_budget);
11833 		/* reserve the misc vector */
11834 		vec = v_actual - 1;
11835 
11836 		/* Scale vector usage down */
11837 		pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11838 		pf->num_vmdq_vsis = 1;
11839 		pf->num_vmdq_qps = 1;
11840 
11841 		/* partition out the remaining vectors */
11842 		switch (vec) {
11843 		case 2:
11844 			pf->num_lan_msix = 1;
11845 			break;
11846 		case 3:
11847 			if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11848 				pf->num_lan_msix = 1;
11849 				pf->num_iwarp_msix = 1;
11850 			} else {
11851 				pf->num_lan_msix = 2;
11852 			}
11853 			break;
11854 		default:
11855 			if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11856 				pf->num_iwarp_msix = min_t(int, (vec / 3),
11857 						 iwarp_requested);
11858 				pf->num_vmdq_vsis = min_t(int, (vec / 3),
11859 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11860 			} else {
11861 				pf->num_vmdq_vsis = min_t(int, (vec / 2),
11862 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11863 			}
11864 			if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11865 				pf->num_fdsb_msix = 1;
11866 				vec--;
11867 			}
11868 			pf->num_lan_msix = min_t(int,
11869 			       (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
11870 							      pf->num_lan_msix);
11871 			pf->num_lan_qps = pf->num_lan_msix;
11872 			break;
11873 		}
11874 	}
11875 
11876 	if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
11877 	    (pf->num_fdsb_msix == 0)) {
11878 		dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
11879 		pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
11880 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11881 	}
11882 	if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
11883 	    (pf->num_vmdq_msix == 0)) {
11884 		dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
11885 		pf->flags &= ~I40E_FLAG_VMDQ_ENABLED;
11886 	}
11887 
11888 	if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
11889 	    (pf->num_iwarp_msix == 0)) {
11890 		dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
11891 		pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
11892 	}
11893 	i40e_debug(&pf->hw, I40E_DEBUG_INIT,
11894 		   "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
11895 		   pf->num_lan_msix,
11896 		   pf->num_vmdq_msix * pf->num_vmdq_vsis,
11897 		   pf->num_fdsb_msix,
11898 		   pf->num_iwarp_msix);
11899 
11900 	return v_actual;
11901 }
11902 
11903 /**
11904  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
11905  * @vsi: the VSI being configured
11906  * @v_idx: index of the vector in the vsi struct
11907  *
11908  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
11909  **/
11910 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx)
11911 {
11912 	struct i40e_q_vector *q_vector;
11913 
11914 	/* allocate q_vector */
11915 	q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
11916 	if (!q_vector)
11917 		return -ENOMEM;
11918 
11919 	q_vector->vsi = vsi;
11920 	q_vector->v_idx = v_idx;
11921 	cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
11922 
11923 	if (vsi->netdev)
11924 		netif_napi_add(vsi->netdev, &q_vector->napi,
11925 			       i40e_napi_poll, NAPI_POLL_WEIGHT);
11926 
11927 	/* tie q_vector and vsi together */
11928 	vsi->q_vectors[v_idx] = q_vector;
11929 
11930 	return 0;
11931 }
11932 
11933 /**
11934  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
11935  * @vsi: the VSI being configured
11936  *
11937  * We allocate one q_vector per queue interrupt.  If allocation fails we
11938  * return -ENOMEM.
11939  **/
11940 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
11941 {
11942 	struct i40e_pf *pf = vsi->back;
11943 	int err, v_idx, num_q_vectors;
11944 
11945 	/* if not MSIX, give the one vector only to the LAN VSI */
11946 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11947 		num_q_vectors = vsi->num_q_vectors;
11948 	else if (vsi == pf->vsi[pf->lan_vsi])
11949 		num_q_vectors = 1;
11950 	else
11951 		return -EINVAL;
11952 
11953 	for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
11954 		err = i40e_vsi_alloc_q_vector(vsi, v_idx);
11955 		if (err)
11956 			goto err_out;
11957 	}
11958 
11959 	return 0;
11960 
11961 err_out:
11962 	while (v_idx--)
11963 		i40e_free_q_vector(vsi, v_idx);
11964 
11965 	return err;
11966 }
11967 
11968 /**
11969  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
11970  * @pf: board private structure to initialize
11971  **/
11972 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
11973 {
11974 	int vectors = 0;
11975 	ssize_t size;
11976 
11977 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11978 		vectors = i40e_init_msix(pf);
11979 		if (vectors < 0) {
11980 			pf->flags &= ~(I40E_FLAG_MSIX_ENABLED	|
11981 				       I40E_FLAG_IWARP_ENABLED	|
11982 				       I40E_FLAG_RSS_ENABLED	|
11983 				       I40E_FLAG_DCB_CAPABLE	|
11984 				       I40E_FLAG_DCB_ENABLED	|
11985 				       I40E_FLAG_SRIOV_ENABLED	|
11986 				       I40E_FLAG_FD_SB_ENABLED	|
11987 				       I40E_FLAG_FD_ATR_ENABLED	|
11988 				       I40E_FLAG_VMDQ_ENABLED);
11989 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11990 
11991 			/* rework the queue expectations without MSIX */
11992 			i40e_determine_queue_usage(pf);
11993 		}
11994 	}
11995 
11996 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED) &&
11997 	    (pf->flags & I40E_FLAG_MSI_ENABLED)) {
11998 		dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
11999 		vectors = pci_enable_msi(pf->pdev);
12000 		if (vectors < 0) {
12001 			dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
12002 				 vectors);
12003 			pf->flags &= ~I40E_FLAG_MSI_ENABLED;
12004 		}
12005 		vectors = 1;  /* one MSI or Legacy vector */
12006 	}
12007 
12008 	if (!(pf->flags & (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED)))
12009 		dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
12010 
12011 	/* set up vector assignment tracking */
12012 	size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
12013 	pf->irq_pile = kzalloc(size, GFP_KERNEL);
12014 	if (!pf->irq_pile)
12015 		return -ENOMEM;
12016 
12017 	pf->irq_pile->num_entries = vectors;
12018 
12019 	/* track first vector for misc interrupts, ignore return */
12020 	(void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
12021 
12022 	return 0;
12023 }
12024 
12025 /**
12026  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
12027  * @pf: private board data structure
12028  *
12029  * Restore the interrupt scheme that was cleared when we suspended the
12030  * device. This should be called during resume to re-allocate the q_vectors
12031  * and reacquire IRQs.
12032  */
12033 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
12034 {
12035 	int err, i;
12036 
12037 	/* We cleared the MSI and MSI-X flags when disabling the old interrupt
12038 	 * scheme. We need to re-enabled them here in order to attempt to
12039 	 * re-acquire the MSI or MSI-X vectors
12040 	 */
12041 	pf->flags |= (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
12042 
12043 	err = i40e_init_interrupt_scheme(pf);
12044 	if (err)
12045 		return err;
12046 
12047 	/* Now that we've re-acquired IRQs, we need to remap the vectors and
12048 	 * rings together again.
12049 	 */
12050 	for (i = 0; i < pf->num_alloc_vsi; i++) {
12051 		if (pf->vsi[i]) {
12052 			err = i40e_vsi_alloc_q_vectors(pf->vsi[i]);
12053 			if (err)
12054 				goto err_unwind;
12055 			i40e_vsi_map_rings_to_vectors(pf->vsi[i]);
12056 		}
12057 	}
12058 
12059 	err = i40e_setup_misc_vector(pf);
12060 	if (err)
12061 		goto err_unwind;
12062 
12063 	if (pf->flags & I40E_FLAG_IWARP_ENABLED)
12064 		i40e_client_update_msix_info(pf);
12065 
12066 	return 0;
12067 
12068 err_unwind:
12069 	while (i--) {
12070 		if (pf->vsi[i])
12071 			i40e_vsi_free_q_vectors(pf->vsi[i]);
12072 	}
12073 
12074 	return err;
12075 }
12076 
12077 /**
12078  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
12079  * non queue events in recovery mode
12080  * @pf: board private structure
12081  *
12082  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
12083  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
12084  * This is handled differently than in recovery mode since no Tx/Rx resources
12085  * are being allocated.
12086  **/
12087 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
12088 {
12089 	int err;
12090 
12091 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
12092 		err = i40e_setup_misc_vector(pf);
12093 
12094 		if (err) {
12095 			dev_info(&pf->pdev->dev,
12096 				 "MSI-X misc vector request failed, error %d\n",
12097 				 err);
12098 			return err;
12099 		}
12100 	} else {
12101 		u32 flags = pf->flags & I40E_FLAG_MSI_ENABLED ? 0 : IRQF_SHARED;
12102 
12103 		err = request_irq(pf->pdev->irq, i40e_intr, flags,
12104 				  pf->int_name, pf);
12105 
12106 		if (err) {
12107 			dev_info(&pf->pdev->dev,
12108 				 "MSI/legacy misc vector request failed, error %d\n",
12109 				 err);
12110 			return err;
12111 		}
12112 		i40e_enable_misc_int_causes(pf);
12113 		i40e_irq_dynamic_enable_icr0(pf);
12114 	}
12115 
12116 	return 0;
12117 }
12118 
12119 /**
12120  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
12121  * @pf: board private structure
12122  *
12123  * This sets up the handler for MSIX 0, which is used to manage the
12124  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
12125  * when in MSI or Legacy interrupt mode.
12126  **/
12127 static int i40e_setup_misc_vector(struct i40e_pf *pf)
12128 {
12129 	struct i40e_hw *hw = &pf->hw;
12130 	int err = 0;
12131 
12132 	/* Only request the IRQ once, the first time through. */
12133 	if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
12134 		err = request_irq(pf->msix_entries[0].vector,
12135 				  i40e_intr, 0, pf->int_name, pf);
12136 		if (err) {
12137 			clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
12138 			dev_info(&pf->pdev->dev,
12139 				 "request_irq for %s failed: %d\n",
12140 				 pf->int_name, err);
12141 			return -EFAULT;
12142 		}
12143 	}
12144 
12145 	i40e_enable_misc_int_causes(pf);
12146 
12147 	/* associate no queues to the misc vector */
12148 	wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
12149 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K >> 1);
12150 
12151 	i40e_flush(hw);
12152 
12153 	i40e_irq_dynamic_enable_icr0(pf);
12154 
12155 	return err;
12156 }
12157 
12158 /**
12159  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
12160  * @vsi: Pointer to vsi structure
12161  * @seed: Buffter to store the hash keys
12162  * @lut: Buffer to store the lookup table entries
12163  * @lut_size: Size of buffer to store the lookup table entries
12164  *
12165  * Return 0 on success, negative on failure
12166  */
12167 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
12168 			   u8 *lut, u16 lut_size)
12169 {
12170 	struct i40e_pf *pf = vsi->back;
12171 	struct i40e_hw *hw = &pf->hw;
12172 	int ret = 0;
12173 
12174 	if (seed) {
12175 		ret = i40e_aq_get_rss_key(hw, vsi->id,
12176 			(struct i40e_aqc_get_set_rss_key_data *)seed);
12177 		if (ret) {
12178 			dev_info(&pf->pdev->dev,
12179 				 "Cannot get RSS key, err %s aq_err %s\n",
12180 				 i40e_stat_str(&pf->hw, ret),
12181 				 i40e_aq_str(&pf->hw,
12182 					     pf->hw.aq.asq_last_status));
12183 			return ret;
12184 		}
12185 	}
12186 
12187 	if (lut) {
12188 		bool pf_lut = vsi->type == I40E_VSI_MAIN;
12189 
12190 		ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
12191 		if (ret) {
12192 			dev_info(&pf->pdev->dev,
12193 				 "Cannot get RSS lut, err %s aq_err %s\n",
12194 				 i40e_stat_str(&pf->hw, ret),
12195 				 i40e_aq_str(&pf->hw,
12196 					     pf->hw.aq.asq_last_status));
12197 			return ret;
12198 		}
12199 	}
12200 
12201 	return ret;
12202 }
12203 
12204 /**
12205  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
12206  * @vsi: Pointer to vsi structure
12207  * @seed: RSS hash seed
12208  * @lut: Lookup table
12209  * @lut_size: Lookup table size
12210  *
12211  * Returns 0 on success, negative on failure
12212  **/
12213 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
12214 			       const u8 *lut, u16 lut_size)
12215 {
12216 	struct i40e_pf *pf = vsi->back;
12217 	struct i40e_hw *hw = &pf->hw;
12218 	u16 vf_id = vsi->vf_id;
12219 	u8 i;
12220 
12221 	/* Fill out hash function seed */
12222 	if (seed) {
12223 		u32 *seed_dw = (u32 *)seed;
12224 
12225 		if (vsi->type == I40E_VSI_MAIN) {
12226 			for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12227 				wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
12228 		} else if (vsi->type == I40E_VSI_SRIOV) {
12229 			for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
12230 				wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
12231 		} else {
12232 			dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
12233 		}
12234 	}
12235 
12236 	if (lut) {
12237 		u32 *lut_dw = (u32 *)lut;
12238 
12239 		if (vsi->type == I40E_VSI_MAIN) {
12240 			if (lut_size != I40E_HLUT_ARRAY_SIZE)
12241 				return -EINVAL;
12242 			for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12243 				wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
12244 		} else if (vsi->type == I40E_VSI_SRIOV) {
12245 			if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
12246 				return -EINVAL;
12247 			for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12248 				wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
12249 		} else {
12250 			dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12251 		}
12252 	}
12253 	i40e_flush(hw);
12254 
12255 	return 0;
12256 }
12257 
12258 /**
12259  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
12260  * @vsi: Pointer to VSI structure
12261  * @seed: Buffer to store the keys
12262  * @lut: Buffer to store the lookup table entries
12263  * @lut_size: Size of buffer to store the lookup table entries
12264  *
12265  * Returns 0 on success, negative on failure
12266  */
12267 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
12268 			    u8 *lut, u16 lut_size)
12269 {
12270 	struct i40e_pf *pf = vsi->back;
12271 	struct i40e_hw *hw = &pf->hw;
12272 	u16 i;
12273 
12274 	if (seed) {
12275 		u32 *seed_dw = (u32 *)seed;
12276 
12277 		for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12278 			seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
12279 	}
12280 	if (lut) {
12281 		u32 *lut_dw = (u32 *)lut;
12282 
12283 		if (lut_size != I40E_HLUT_ARRAY_SIZE)
12284 			return -EINVAL;
12285 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12286 			lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
12287 	}
12288 
12289 	return 0;
12290 }
12291 
12292 /**
12293  * i40e_config_rss - Configure RSS keys and lut
12294  * @vsi: Pointer to VSI structure
12295  * @seed: RSS hash seed
12296  * @lut: Lookup table
12297  * @lut_size: Lookup table size
12298  *
12299  * Returns 0 on success, negative on failure
12300  */
12301 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12302 {
12303 	struct i40e_pf *pf = vsi->back;
12304 
12305 	if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12306 		return i40e_config_rss_aq(vsi, seed, lut, lut_size);
12307 	else
12308 		return i40e_config_rss_reg(vsi, seed, lut, lut_size);
12309 }
12310 
12311 /**
12312  * i40e_get_rss - Get RSS keys and lut
12313  * @vsi: Pointer to VSI structure
12314  * @seed: Buffer to store the keys
12315  * @lut: Buffer to store the lookup table entries
12316  * @lut_size: Size of buffer to store the lookup table entries
12317  *
12318  * Returns 0 on success, negative on failure
12319  */
12320 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12321 {
12322 	struct i40e_pf *pf = vsi->back;
12323 
12324 	if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12325 		return i40e_get_rss_aq(vsi, seed, lut, lut_size);
12326 	else
12327 		return i40e_get_rss_reg(vsi, seed, lut, lut_size);
12328 }
12329 
12330 /**
12331  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
12332  * @pf: Pointer to board private structure
12333  * @lut: Lookup table
12334  * @rss_table_size: Lookup table size
12335  * @rss_size: Range of queue number for hashing
12336  */
12337 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
12338 		       u16 rss_table_size, u16 rss_size)
12339 {
12340 	u16 i;
12341 
12342 	for (i = 0; i < rss_table_size; i++)
12343 		lut[i] = i % rss_size;
12344 }
12345 
12346 /**
12347  * i40e_pf_config_rss - Prepare for RSS if used
12348  * @pf: board private structure
12349  **/
12350 static int i40e_pf_config_rss(struct i40e_pf *pf)
12351 {
12352 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12353 	u8 seed[I40E_HKEY_ARRAY_SIZE];
12354 	u8 *lut;
12355 	struct i40e_hw *hw = &pf->hw;
12356 	u32 reg_val;
12357 	u64 hena;
12358 	int ret;
12359 
12360 	/* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
12361 	hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
12362 		((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
12363 	hena |= i40e_pf_get_default_rss_hena(pf);
12364 
12365 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
12366 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
12367 
12368 	/* Determine the RSS table size based on the hardware capabilities */
12369 	reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
12370 	reg_val = (pf->rss_table_size == 512) ?
12371 			(reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
12372 			(reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
12373 	i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
12374 
12375 	/* Determine the RSS size of the VSI */
12376 	if (!vsi->rss_size) {
12377 		u16 qcount;
12378 		/* If the firmware does something weird during VSI init, we
12379 		 * could end up with zero TCs. Check for that to avoid
12380 		 * divide-by-zero. It probably won't pass traffic, but it also
12381 		 * won't panic.
12382 		 */
12383 		qcount = vsi->num_queue_pairs /
12384 			 (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
12385 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12386 	}
12387 	if (!vsi->rss_size)
12388 		return -EINVAL;
12389 
12390 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
12391 	if (!lut)
12392 		return -ENOMEM;
12393 
12394 	/* Use user configured lut if there is one, otherwise use default */
12395 	if (vsi->rss_lut_user)
12396 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
12397 	else
12398 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
12399 
12400 	/* Use user configured hash key if there is one, otherwise
12401 	 * use default.
12402 	 */
12403 	if (vsi->rss_hkey_user)
12404 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
12405 	else
12406 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
12407 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
12408 	kfree(lut);
12409 
12410 	return ret;
12411 }
12412 
12413 /**
12414  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
12415  * @pf: board private structure
12416  * @queue_count: the requested queue count for rss.
12417  *
12418  * returns 0 if rss is not enabled, if enabled returns the final rss queue
12419  * count which may be different from the requested queue count.
12420  * Note: expects to be called while under rtnl_lock()
12421  **/
12422 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
12423 {
12424 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12425 	int new_rss_size;
12426 
12427 	if (!(pf->flags & I40E_FLAG_RSS_ENABLED))
12428 		return 0;
12429 
12430 	queue_count = min_t(int, queue_count, num_online_cpus());
12431 	new_rss_size = min_t(int, queue_count, pf->rss_size_max);
12432 
12433 	if (queue_count != vsi->num_queue_pairs) {
12434 		u16 qcount;
12435 
12436 		vsi->req_queue_pairs = queue_count;
12437 		i40e_prep_for_reset(pf);
12438 		if (test_bit(__I40E_IN_REMOVE, pf->state))
12439 			return pf->alloc_rss_size;
12440 
12441 		pf->alloc_rss_size = new_rss_size;
12442 
12443 		i40e_reset_and_rebuild(pf, true, true);
12444 
12445 		/* Discard the user configured hash keys and lut, if less
12446 		 * queues are enabled.
12447 		 */
12448 		if (queue_count < vsi->rss_size) {
12449 			i40e_clear_rss_config_user(vsi);
12450 			dev_dbg(&pf->pdev->dev,
12451 				"discard user configured hash keys and lut\n");
12452 		}
12453 
12454 		/* Reset vsi->rss_size, as number of enabled queues changed */
12455 		qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
12456 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12457 
12458 		i40e_pf_config_rss(pf);
12459 	}
12460 	dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
12461 		 vsi->req_queue_pairs, pf->rss_size_max);
12462 	return pf->alloc_rss_size;
12463 }
12464 
12465 /**
12466  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
12467  * @pf: board private structure
12468  **/
12469 i40e_status i40e_get_partition_bw_setting(struct i40e_pf *pf)
12470 {
12471 	i40e_status status;
12472 	bool min_valid, max_valid;
12473 	u32 max_bw, min_bw;
12474 
12475 	status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
12476 					   &min_valid, &max_valid);
12477 
12478 	if (!status) {
12479 		if (min_valid)
12480 			pf->min_bw = min_bw;
12481 		if (max_valid)
12482 			pf->max_bw = max_bw;
12483 	}
12484 
12485 	return status;
12486 }
12487 
12488 /**
12489  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
12490  * @pf: board private structure
12491  **/
12492 i40e_status i40e_set_partition_bw_setting(struct i40e_pf *pf)
12493 {
12494 	struct i40e_aqc_configure_partition_bw_data bw_data;
12495 	i40e_status status;
12496 
12497 	memset(&bw_data, 0, sizeof(bw_data));
12498 
12499 	/* Set the valid bit for this PF */
12500 	bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
12501 	bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
12502 	bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
12503 
12504 	/* Set the new bandwidths */
12505 	status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
12506 
12507 	return status;
12508 }
12509 
12510 /**
12511  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
12512  * @pf: board private structure
12513  **/
12514 i40e_status i40e_commit_partition_bw_setting(struct i40e_pf *pf)
12515 {
12516 	/* Commit temporary BW setting to permanent NVM image */
12517 	enum i40e_admin_queue_err last_aq_status;
12518 	i40e_status ret;
12519 	u16 nvm_word;
12520 
12521 	if (pf->hw.partition_id != 1) {
12522 		dev_info(&pf->pdev->dev,
12523 			 "Commit BW only works on partition 1! This is partition %d",
12524 			 pf->hw.partition_id);
12525 		ret = I40E_NOT_SUPPORTED;
12526 		goto bw_commit_out;
12527 	}
12528 
12529 	/* Acquire NVM for read access */
12530 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
12531 	last_aq_status = pf->hw.aq.asq_last_status;
12532 	if (ret) {
12533 		dev_info(&pf->pdev->dev,
12534 			 "Cannot acquire NVM for read access, err %s aq_err %s\n",
12535 			 i40e_stat_str(&pf->hw, ret),
12536 			 i40e_aq_str(&pf->hw, last_aq_status));
12537 		goto bw_commit_out;
12538 	}
12539 
12540 	/* Read word 0x10 of NVM - SW compatibility word 1 */
12541 	ret = i40e_aq_read_nvm(&pf->hw,
12542 			       I40E_SR_NVM_CONTROL_WORD,
12543 			       0x10, sizeof(nvm_word), &nvm_word,
12544 			       false, NULL);
12545 	/* Save off last admin queue command status before releasing
12546 	 * the NVM
12547 	 */
12548 	last_aq_status = pf->hw.aq.asq_last_status;
12549 	i40e_release_nvm(&pf->hw);
12550 	if (ret) {
12551 		dev_info(&pf->pdev->dev, "NVM read error, err %s aq_err %s\n",
12552 			 i40e_stat_str(&pf->hw, ret),
12553 			 i40e_aq_str(&pf->hw, last_aq_status));
12554 		goto bw_commit_out;
12555 	}
12556 
12557 	/* Wait a bit for NVM release to complete */
12558 	msleep(50);
12559 
12560 	/* Acquire NVM for write access */
12561 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
12562 	last_aq_status = pf->hw.aq.asq_last_status;
12563 	if (ret) {
12564 		dev_info(&pf->pdev->dev,
12565 			 "Cannot acquire NVM for write access, err %s aq_err %s\n",
12566 			 i40e_stat_str(&pf->hw, ret),
12567 			 i40e_aq_str(&pf->hw, last_aq_status));
12568 		goto bw_commit_out;
12569 	}
12570 	/* Write it back out unchanged to initiate update NVM,
12571 	 * which will force a write of the shadow (alt) RAM to
12572 	 * the NVM - thus storing the bandwidth values permanently.
12573 	 */
12574 	ret = i40e_aq_update_nvm(&pf->hw,
12575 				 I40E_SR_NVM_CONTROL_WORD,
12576 				 0x10, sizeof(nvm_word),
12577 				 &nvm_word, true, 0, NULL);
12578 	/* Save off last admin queue command status before releasing
12579 	 * the NVM
12580 	 */
12581 	last_aq_status = pf->hw.aq.asq_last_status;
12582 	i40e_release_nvm(&pf->hw);
12583 	if (ret)
12584 		dev_info(&pf->pdev->dev,
12585 			 "BW settings NOT SAVED, err %s aq_err %s\n",
12586 			 i40e_stat_str(&pf->hw, ret),
12587 			 i40e_aq_str(&pf->hw, last_aq_status));
12588 bw_commit_out:
12589 
12590 	return ret;
12591 }
12592 
12593 /**
12594  * i40e_is_total_port_shutdown_enabled - read NVM and return value
12595  * if total port shutdown feature is enabled for this PF
12596  * @pf: board private structure
12597  **/
12598 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf)
12599 {
12600 #define I40E_TOTAL_PORT_SHUTDOWN_ENABLED	BIT(4)
12601 #define I40E_FEATURES_ENABLE_PTR		0x2A
12602 #define I40E_CURRENT_SETTING_PTR		0x2B
12603 #define I40E_LINK_BEHAVIOR_WORD_OFFSET		0x2D
12604 #define I40E_LINK_BEHAVIOR_WORD_LENGTH		0x1
12605 #define I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED	BIT(0)
12606 #define I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH	4
12607 	i40e_status read_status = I40E_SUCCESS;
12608 	u16 sr_emp_sr_settings_ptr = 0;
12609 	u16 features_enable = 0;
12610 	u16 link_behavior = 0;
12611 	bool ret = false;
12612 
12613 	read_status = i40e_read_nvm_word(&pf->hw,
12614 					 I40E_SR_EMP_SR_SETTINGS_PTR,
12615 					 &sr_emp_sr_settings_ptr);
12616 	if (read_status)
12617 		goto err_nvm;
12618 	read_status = i40e_read_nvm_word(&pf->hw,
12619 					 sr_emp_sr_settings_ptr +
12620 					 I40E_FEATURES_ENABLE_PTR,
12621 					 &features_enable);
12622 	if (read_status)
12623 		goto err_nvm;
12624 	if (I40E_TOTAL_PORT_SHUTDOWN_ENABLED & features_enable) {
12625 		read_status = i40e_read_nvm_module_data(&pf->hw,
12626 							I40E_SR_EMP_SR_SETTINGS_PTR,
12627 							I40E_CURRENT_SETTING_PTR,
12628 							I40E_LINK_BEHAVIOR_WORD_OFFSET,
12629 							I40E_LINK_BEHAVIOR_WORD_LENGTH,
12630 							&link_behavior);
12631 		if (read_status)
12632 			goto err_nvm;
12633 		link_behavior >>= (pf->hw.port * I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH);
12634 		ret = I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED & link_behavior;
12635 	}
12636 	return ret;
12637 
12638 err_nvm:
12639 	dev_warn(&pf->pdev->dev,
12640 		 "total-port-shutdown feature is off due to read nvm error: %s\n",
12641 		 i40e_stat_str(&pf->hw, read_status));
12642 	return ret;
12643 }
12644 
12645 /**
12646  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
12647  * @pf: board private structure to initialize
12648  *
12649  * i40e_sw_init initializes the Adapter private data structure.
12650  * Fields are initialized based on PCI device information and
12651  * OS network device settings (MTU size).
12652  **/
12653 static int i40e_sw_init(struct i40e_pf *pf)
12654 {
12655 	int err = 0;
12656 	int size;
12657 	u16 pow;
12658 
12659 	/* Set default capability flags */
12660 	pf->flags = I40E_FLAG_RX_CSUM_ENABLED |
12661 		    I40E_FLAG_MSI_ENABLED     |
12662 		    I40E_FLAG_MSIX_ENABLED;
12663 
12664 	/* Set default ITR */
12665 	pf->rx_itr_default = I40E_ITR_RX_DEF;
12666 	pf->tx_itr_default = I40E_ITR_TX_DEF;
12667 
12668 	/* Depending on PF configurations, it is possible that the RSS
12669 	 * maximum might end up larger than the available queues
12670 	 */
12671 	pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
12672 	pf->alloc_rss_size = 1;
12673 	pf->rss_table_size = pf->hw.func_caps.rss_table_size;
12674 	pf->rss_size_max = min_t(int, pf->rss_size_max,
12675 				 pf->hw.func_caps.num_tx_qp);
12676 
12677 	/* find the next higher power-of-2 of num cpus */
12678 	pow = roundup_pow_of_two(num_online_cpus());
12679 	pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
12680 
12681 	if (pf->hw.func_caps.rss) {
12682 		pf->flags |= I40E_FLAG_RSS_ENABLED;
12683 		pf->alloc_rss_size = min_t(int, pf->rss_size_max,
12684 					   num_online_cpus());
12685 	}
12686 
12687 	/* MFP mode enabled */
12688 	if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
12689 		pf->flags |= I40E_FLAG_MFP_ENABLED;
12690 		dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
12691 		if (i40e_get_partition_bw_setting(pf)) {
12692 			dev_warn(&pf->pdev->dev,
12693 				 "Could not get partition bw settings\n");
12694 		} else {
12695 			dev_info(&pf->pdev->dev,
12696 				 "Partition BW Min = %8.8x, Max = %8.8x\n",
12697 				 pf->min_bw, pf->max_bw);
12698 
12699 			/* nudge the Tx scheduler */
12700 			i40e_set_partition_bw_setting(pf);
12701 		}
12702 	}
12703 
12704 	if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
12705 	    (pf->hw.func_caps.fd_filters_best_effort > 0)) {
12706 		pf->flags |= I40E_FLAG_FD_ATR_ENABLED;
12707 		pf->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
12708 		if (pf->flags & I40E_FLAG_MFP_ENABLED &&
12709 		    pf->hw.num_partitions > 1)
12710 			dev_info(&pf->pdev->dev,
12711 				 "Flow Director Sideband mode Disabled in MFP mode\n");
12712 		else
12713 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12714 		pf->fdir_pf_filter_count =
12715 				 pf->hw.func_caps.fd_filters_guaranteed;
12716 		pf->hw.fdir_shared_filter_count =
12717 				 pf->hw.func_caps.fd_filters_best_effort;
12718 	}
12719 
12720 	if (pf->hw.mac.type == I40E_MAC_X722) {
12721 		pf->hw_features |= (I40E_HW_RSS_AQ_CAPABLE |
12722 				    I40E_HW_128_QP_RSS_CAPABLE |
12723 				    I40E_HW_ATR_EVICT_CAPABLE |
12724 				    I40E_HW_WB_ON_ITR_CAPABLE |
12725 				    I40E_HW_MULTIPLE_TCP_UDP_RSS_PCTYPE |
12726 				    I40E_HW_NO_PCI_LINK_CHECK |
12727 				    I40E_HW_USE_SET_LLDP_MIB |
12728 				    I40E_HW_GENEVE_OFFLOAD_CAPABLE |
12729 				    I40E_HW_PTP_L4_CAPABLE |
12730 				    I40E_HW_WOL_MC_MAGIC_PKT_WAKE |
12731 				    I40E_HW_OUTER_UDP_CSUM_CAPABLE);
12732 
12733 #define I40E_FDEVICT_PCTYPE_DEFAULT 0xc03
12734 		if (rd32(&pf->hw, I40E_GLQF_FDEVICTENA(1)) !=
12735 		    I40E_FDEVICT_PCTYPE_DEFAULT) {
12736 			dev_warn(&pf->pdev->dev,
12737 				 "FD EVICT PCTYPES are not right, disable FD HW EVICT\n");
12738 			pf->hw_features &= ~I40E_HW_ATR_EVICT_CAPABLE;
12739 		}
12740 	} else if ((pf->hw.aq.api_maj_ver > 1) ||
12741 		   ((pf->hw.aq.api_maj_ver == 1) &&
12742 		    (pf->hw.aq.api_min_ver > 4))) {
12743 		/* Supported in FW API version higher than 1.4 */
12744 		pf->hw_features |= I40E_HW_GENEVE_OFFLOAD_CAPABLE;
12745 	}
12746 
12747 	/* Enable HW ATR eviction if possible */
12748 	if (pf->hw_features & I40E_HW_ATR_EVICT_CAPABLE)
12749 		pf->flags |= I40E_FLAG_HW_ATR_EVICT_ENABLED;
12750 
12751 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12752 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 33)) ||
12753 	    (pf->hw.aq.fw_maj_ver < 4))) {
12754 		pf->hw_features |= I40E_HW_RESTART_AUTONEG;
12755 		/* No DCB support  for FW < v4.33 */
12756 		pf->hw_features |= I40E_HW_NO_DCB_SUPPORT;
12757 	}
12758 
12759 	/* Disable FW LLDP if FW < v4.3 */
12760 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12761 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 3)) ||
12762 	    (pf->hw.aq.fw_maj_ver < 4)))
12763 		pf->hw_features |= I40E_HW_STOP_FW_LLDP;
12764 
12765 	/* Use the FW Set LLDP MIB API if FW > v4.40 */
12766 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12767 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver >= 40)) ||
12768 	    (pf->hw.aq.fw_maj_ver >= 5)))
12769 		pf->hw_features |= I40E_HW_USE_SET_LLDP_MIB;
12770 
12771 	/* Enable PTP L4 if FW > v6.0 */
12772 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
12773 	    pf->hw.aq.fw_maj_ver >= 6)
12774 		pf->hw_features |= I40E_HW_PTP_L4_CAPABLE;
12775 
12776 	if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
12777 		pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
12778 		pf->flags |= I40E_FLAG_VMDQ_ENABLED;
12779 		pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
12780 	}
12781 
12782 	if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
12783 		pf->flags |= I40E_FLAG_IWARP_ENABLED;
12784 		/* IWARP needs one extra vector for CQP just like MISC.*/
12785 		pf->num_iwarp_msix = (int)num_online_cpus() + 1;
12786 	}
12787 	/* Stopping FW LLDP engine is supported on XL710 and X722
12788 	 * starting from FW versions determined in i40e_init_adminq.
12789 	 * Stopping the FW LLDP engine is not supported on XL710
12790 	 * if NPAR is functioning so unset this hw flag in this case.
12791 	 */
12792 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
12793 	    pf->hw.func_caps.npar_enable &&
12794 	    (pf->hw.flags & I40E_HW_FLAG_FW_LLDP_STOPPABLE))
12795 		pf->hw.flags &= ~I40E_HW_FLAG_FW_LLDP_STOPPABLE;
12796 
12797 #ifdef CONFIG_PCI_IOV
12798 	if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
12799 		pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
12800 		pf->flags |= I40E_FLAG_SRIOV_ENABLED;
12801 		pf->num_req_vfs = min_t(int,
12802 					pf->hw.func_caps.num_vfs,
12803 					I40E_MAX_VF_COUNT);
12804 	}
12805 #endif /* CONFIG_PCI_IOV */
12806 	pf->eeprom_version = 0xDEAD;
12807 	pf->lan_veb = I40E_NO_VEB;
12808 	pf->lan_vsi = I40E_NO_VSI;
12809 
12810 	/* By default FW has this off for performance reasons */
12811 	pf->flags &= ~I40E_FLAG_VEB_STATS_ENABLED;
12812 
12813 	/* set up queue assignment tracking */
12814 	size = sizeof(struct i40e_lump_tracking)
12815 		+ (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
12816 	pf->qp_pile = kzalloc(size, GFP_KERNEL);
12817 	if (!pf->qp_pile) {
12818 		err = -ENOMEM;
12819 		goto sw_init_done;
12820 	}
12821 	pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
12822 
12823 	pf->tx_timeout_recovery_level = 1;
12824 
12825 	if (pf->hw.mac.type != I40E_MAC_X722 &&
12826 	    i40e_is_total_port_shutdown_enabled(pf)) {
12827 		/* Link down on close must be on when total port shutdown
12828 		 * is enabled for a given port
12829 		 */
12830 		pf->flags |= (I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED |
12831 			      I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED);
12832 		dev_info(&pf->pdev->dev,
12833 			 "total-port-shutdown was enabled, link-down-on-close is forced on\n");
12834 	}
12835 	mutex_init(&pf->switch_mutex);
12836 
12837 sw_init_done:
12838 	return err;
12839 }
12840 
12841 /**
12842  * i40e_set_ntuple - set the ntuple feature flag and take action
12843  * @pf: board private structure to initialize
12844  * @features: the feature set that the stack is suggesting
12845  *
12846  * returns a bool to indicate if reset needs to happen
12847  **/
12848 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12849 {
12850 	bool need_reset = false;
12851 
12852 	/* Check if Flow Director n-tuple support was enabled or disabled.  If
12853 	 * the state changed, we need to reset.
12854 	 */
12855 	if (features & NETIF_F_NTUPLE) {
12856 		/* Enable filters and mark for reset */
12857 		if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
12858 			need_reset = true;
12859 		/* enable FD_SB only if there is MSI-X vector and no cloud
12860 		 * filters exist
12861 		 */
12862 		if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12863 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12864 			pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
12865 		}
12866 	} else {
12867 		/* turn off filters, mark for reset and clear SW filter list */
12868 		if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
12869 			need_reset = true;
12870 			i40e_fdir_filter_exit(pf);
12871 		}
12872 		pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
12873 		clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12874 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
12875 
12876 		/* reset fd counters */
12877 		pf->fd_add_err = 0;
12878 		pf->fd_atr_cnt = 0;
12879 		/* if ATR was auto disabled it can be re-enabled. */
12880 		if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12881 			if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
12882 			    (I40E_DEBUG_FD & pf->hw.debug_mask))
12883 				dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12884 	}
12885 	return need_reset;
12886 }
12887 
12888 /**
12889  * i40e_clear_rss_lut - clear the rx hash lookup table
12890  * @vsi: the VSI being configured
12891  **/
12892 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12893 {
12894 	struct i40e_pf *pf = vsi->back;
12895 	struct i40e_hw *hw = &pf->hw;
12896 	u16 vf_id = vsi->vf_id;
12897 	u8 i;
12898 
12899 	if (vsi->type == I40E_VSI_MAIN) {
12900 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12901 			wr32(hw, I40E_PFQF_HLUT(i), 0);
12902 	} else if (vsi->type == I40E_VSI_SRIOV) {
12903 		for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12904 			i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12905 	} else {
12906 		dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12907 	}
12908 }
12909 
12910 /**
12911  * i40e_set_features - set the netdev feature flags
12912  * @netdev: ptr to the netdev being adjusted
12913  * @features: the feature set that the stack is suggesting
12914  * Note: expects to be called while under rtnl_lock()
12915  **/
12916 static int i40e_set_features(struct net_device *netdev,
12917 			     netdev_features_t features)
12918 {
12919 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12920 	struct i40e_vsi *vsi = np->vsi;
12921 	struct i40e_pf *pf = vsi->back;
12922 	bool need_reset;
12923 
12924 	if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
12925 		i40e_pf_config_rss(pf);
12926 	else if (!(features & NETIF_F_RXHASH) &&
12927 		 netdev->features & NETIF_F_RXHASH)
12928 		i40e_clear_rss_lut(vsi);
12929 
12930 	if (features & NETIF_F_HW_VLAN_CTAG_RX)
12931 		i40e_vlan_stripping_enable(vsi);
12932 	else
12933 		i40e_vlan_stripping_disable(vsi);
12934 
12935 	if (!(features & NETIF_F_HW_TC) &&
12936 	    (netdev->features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
12937 		dev_err(&pf->pdev->dev,
12938 			"Offloaded tc filters active, can't turn hw_tc_offload off");
12939 		return -EINVAL;
12940 	}
12941 
12942 	if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
12943 		i40e_del_all_macvlans(vsi);
12944 
12945 	need_reset = i40e_set_ntuple(pf, features);
12946 
12947 	if (need_reset)
12948 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12949 
12950 	return 0;
12951 }
12952 
12953 static int i40e_udp_tunnel_set_port(struct net_device *netdev,
12954 				    unsigned int table, unsigned int idx,
12955 				    struct udp_tunnel_info *ti)
12956 {
12957 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12958 	struct i40e_hw *hw = &np->vsi->back->hw;
12959 	u8 type, filter_index;
12960 	i40e_status ret;
12961 
12962 	type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? I40E_AQC_TUNNEL_TYPE_VXLAN :
12963 						   I40E_AQC_TUNNEL_TYPE_NGE;
12964 
12965 	ret = i40e_aq_add_udp_tunnel(hw, ntohs(ti->port), type, &filter_index,
12966 				     NULL);
12967 	if (ret) {
12968 		netdev_info(netdev, "add UDP port failed, err %s aq_err %s\n",
12969 			    i40e_stat_str(hw, ret),
12970 			    i40e_aq_str(hw, hw->aq.asq_last_status));
12971 		return -EIO;
12972 	}
12973 
12974 	udp_tunnel_nic_set_port_priv(netdev, table, idx, filter_index);
12975 	return 0;
12976 }
12977 
12978 static int i40e_udp_tunnel_unset_port(struct net_device *netdev,
12979 				      unsigned int table, unsigned int idx,
12980 				      struct udp_tunnel_info *ti)
12981 {
12982 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12983 	struct i40e_hw *hw = &np->vsi->back->hw;
12984 	i40e_status ret;
12985 
12986 	ret = i40e_aq_del_udp_tunnel(hw, ti->hw_priv, NULL);
12987 	if (ret) {
12988 		netdev_info(netdev, "delete UDP port failed, err %s aq_err %s\n",
12989 			    i40e_stat_str(hw, ret),
12990 			    i40e_aq_str(hw, hw->aq.asq_last_status));
12991 		return -EIO;
12992 	}
12993 
12994 	return 0;
12995 }
12996 
12997 static int i40e_get_phys_port_id(struct net_device *netdev,
12998 				 struct netdev_phys_item_id *ppid)
12999 {
13000 	struct i40e_netdev_priv *np = netdev_priv(netdev);
13001 	struct i40e_pf *pf = np->vsi->back;
13002 	struct i40e_hw *hw = &pf->hw;
13003 
13004 	if (!(pf->hw_features & I40E_HW_PORT_ID_VALID))
13005 		return -EOPNOTSUPP;
13006 
13007 	ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
13008 	memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
13009 
13010 	return 0;
13011 }
13012 
13013 /**
13014  * i40e_ndo_fdb_add - add an entry to the hardware database
13015  * @ndm: the input from the stack
13016  * @tb: pointer to array of nladdr (unused)
13017  * @dev: the net device pointer
13018  * @addr: the MAC address entry being added
13019  * @vid: VLAN ID
13020  * @flags: instructions from stack about fdb operation
13021  * @extack: netlink extended ack, unused currently
13022  */
13023 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
13024 			    struct net_device *dev,
13025 			    const unsigned char *addr, u16 vid,
13026 			    u16 flags,
13027 			    struct netlink_ext_ack *extack)
13028 {
13029 	struct i40e_netdev_priv *np = netdev_priv(dev);
13030 	struct i40e_pf *pf = np->vsi->back;
13031 	int err = 0;
13032 
13033 	if (!(pf->flags & I40E_FLAG_SRIOV_ENABLED))
13034 		return -EOPNOTSUPP;
13035 
13036 	if (vid) {
13037 		pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
13038 		return -EINVAL;
13039 	}
13040 
13041 	/* Hardware does not support aging addresses so if a
13042 	 * ndm_state is given only allow permanent addresses
13043 	 */
13044 	if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
13045 		netdev_info(dev, "FDB only supports static addresses\n");
13046 		return -EINVAL;
13047 	}
13048 
13049 	if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
13050 		err = dev_uc_add_excl(dev, addr);
13051 	else if (is_multicast_ether_addr(addr))
13052 		err = dev_mc_add_excl(dev, addr);
13053 	else
13054 		err = -EINVAL;
13055 
13056 	/* Only return duplicate errors if NLM_F_EXCL is set */
13057 	if (err == -EEXIST && !(flags & NLM_F_EXCL))
13058 		err = 0;
13059 
13060 	return err;
13061 }
13062 
13063 /**
13064  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
13065  * @dev: the netdev being configured
13066  * @nlh: RTNL message
13067  * @flags: bridge flags
13068  * @extack: netlink extended ack
13069  *
13070  * Inserts a new hardware bridge if not already created and
13071  * enables the bridging mode requested (VEB or VEPA). If the
13072  * hardware bridge has already been inserted and the request
13073  * is to change the mode then that requires a PF reset to
13074  * allow rebuild of the components with required hardware
13075  * bridge mode enabled.
13076  *
13077  * Note: expects to be called while under rtnl_lock()
13078  **/
13079 static int i40e_ndo_bridge_setlink(struct net_device *dev,
13080 				   struct nlmsghdr *nlh,
13081 				   u16 flags,
13082 				   struct netlink_ext_ack *extack)
13083 {
13084 	struct i40e_netdev_priv *np = netdev_priv(dev);
13085 	struct i40e_vsi *vsi = np->vsi;
13086 	struct i40e_pf *pf = vsi->back;
13087 	struct i40e_veb *veb = NULL;
13088 	struct nlattr *attr, *br_spec;
13089 	int i, rem;
13090 
13091 	/* Only for PF VSI for now */
13092 	if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13093 		return -EOPNOTSUPP;
13094 
13095 	/* Find the HW bridge for PF VSI */
13096 	for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13097 		if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13098 			veb = pf->veb[i];
13099 	}
13100 
13101 	br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
13102 
13103 	nla_for_each_nested(attr, br_spec, rem) {
13104 		__u16 mode;
13105 
13106 		if (nla_type(attr) != IFLA_BRIDGE_MODE)
13107 			continue;
13108 
13109 		mode = nla_get_u16(attr);
13110 		if ((mode != BRIDGE_MODE_VEPA) &&
13111 		    (mode != BRIDGE_MODE_VEB))
13112 			return -EINVAL;
13113 
13114 		/* Insert a new HW bridge */
13115 		if (!veb) {
13116 			veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
13117 					     vsi->tc_config.enabled_tc);
13118 			if (veb) {
13119 				veb->bridge_mode = mode;
13120 				i40e_config_bridge_mode(veb);
13121 			} else {
13122 				/* No Bridge HW offload available */
13123 				return -ENOENT;
13124 			}
13125 			break;
13126 		} else if (mode != veb->bridge_mode) {
13127 			/* Existing HW bridge but different mode needs reset */
13128 			veb->bridge_mode = mode;
13129 			/* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
13130 			if (mode == BRIDGE_MODE_VEB)
13131 				pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
13132 			else
13133 				pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
13134 			i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13135 			break;
13136 		}
13137 	}
13138 
13139 	return 0;
13140 }
13141 
13142 /**
13143  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
13144  * @skb: skb buff
13145  * @pid: process id
13146  * @seq: RTNL message seq #
13147  * @dev: the netdev being configured
13148  * @filter_mask: unused
13149  * @nlflags: netlink flags passed in
13150  *
13151  * Return the mode in which the hardware bridge is operating in
13152  * i.e VEB or VEPA.
13153  **/
13154 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
13155 				   struct net_device *dev,
13156 				   u32 __always_unused filter_mask,
13157 				   int nlflags)
13158 {
13159 	struct i40e_netdev_priv *np = netdev_priv(dev);
13160 	struct i40e_vsi *vsi = np->vsi;
13161 	struct i40e_pf *pf = vsi->back;
13162 	struct i40e_veb *veb = NULL;
13163 	int i;
13164 
13165 	/* Only for PF VSI for now */
13166 	if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13167 		return -EOPNOTSUPP;
13168 
13169 	/* Find the HW bridge for the PF VSI */
13170 	for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13171 		if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13172 			veb = pf->veb[i];
13173 	}
13174 
13175 	if (!veb)
13176 		return 0;
13177 
13178 	return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
13179 				       0, 0, nlflags, filter_mask, NULL);
13180 }
13181 
13182 /**
13183  * i40e_features_check - Validate encapsulated packet conforms to limits
13184  * @skb: skb buff
13185  * @dev: This physical port's netdev
13186  * @features: Offload features that the stack believes apply
13187  **/
13188 static netdev_features_t i40e_features_check(struct sk_buff *skb,
13189 					     struct net_device *dev,
13190 					     netdev_features_t features)
13191 {
13192 	size_t len;
13193 
13194 	/* No point in doing any of this if neither checksum nor GSO are
13195 	 * being requested for this frame.  We can rule out both by just
13196 	 * checking for CHECKSUM_PARTIAL
13197 	 */
13198 	if (skb->ip_summed != CHECKSUM_PARTIAL)
13199 		return features;
13200 
13201 	/* We cannot support GSO if the MSS is going to be less than
13202 	 * 64 bytes.  If it is then we need to drop support for GSO.
13203 	 */
13204 	if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
13205 		features &= ~NETIF_F_GSO_MASK;
13206 
13207 	/* MACLEN can support at most 63 words */
13208 	len = skb_network_header(skb) - skb->data;
13209 	if (len & ~(63 * 2))
13210 		goto out_err;
13211 
13212 	/* IPLEN and EIPLEN can support at most 127 dwords */
13213 	len = skb_transport_header(skb) - skb_network_header(skb);
13214 	if (len & ~(127 * 4))
13215 		goto out_err;
13216 
13217 	if (skb->encapsulation) {
13218 		/* L4TUNLEN can support 127 words */
13219 		len = skb_inner_network_header(skb) - skb_transport_header(skb);
13220 		if (len & ~(127 * 2))
13221 			goto out_err;
13222 
13223 		/* IPLEN can support at most 127 dwords */
13224 		len = skb_inner_transport_header(skb) -
13225 		      skb_inner_network_header(skb);
13226 		if (len & ~(127 * 4))
13227 			goto out_err;
13228 	}
13229 
13230 	/* No need to validate L4LEN as TCP is the only protocol with a
13231 	 * flexible value and we support all possible values supported
13232 	 * by TCP, which is at most 15 dwords
13233 	 */
13234 
13235 	return features;
13236 out_err:
13237 	return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
13238 }
13239 
13240 /**
13241  * i40e_xdp_setup - add/remove an XDP program
13242  * @vsi: VSI to changed
13243  * @prog: XDP program
13244  * @extack: netlink extended ack
13245  **/
13246 static int i40e_xdp_setup(struct i40e_vsi *vsi, struct bpf_prog *prog,
13247 			  struct netlink_ext_ack *extack)
13248 {
13249 	int frame_size = vsi->netdev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
13250 	struct i40e_pf *pf = vsi->back;
13251 	struct bpf_prog *old_prog;
13252 	bool need_reset;
13253 	int i;
13254 
13255 	/* Don't allow frames that span over multiple buffers */
13256 	if (frame_size > vsi->rx_buf_len) {
13257 		NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
13258 		return -EINVAL;
13259 	}
13260 
13261 	/* When turning XDP on->off/off->on we reset and rebuild the rings. */
13262 	need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
13263 
13264 	if (need_reset)
13265 		i40e_prep_for_reset(pf);
13266 
13267 	/* VSI shall be deleted in a moment, just return EINVAL */
13268 	if (test_bit(__I40E_IN_REMOVE, pf->state))
13269 		return -EINVAL;
13270 
13271 	old_prog = xchg(&vsi->xdp_prog, prog);
13272 
13273 	if (need_reset) {
13274 		if (!prog)
13275 			/* Wait until ndo_xsk_wakeup completes. */
13276 			synchronize_rcu();
13277 		i40e_reset_and_rebuild(pf, true, true);
13278 	}
13279 
13280 	for (i = 0; i < vsi->num_queue_pairs; i++)
13281 		WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
13282 
13283 	if (old_prog)
13284 		bpf_prog_put(old_prog);
13285 
13286 	/* Kick start the NAPI context if there is an AF_XDP socket open
13287 	 * on that queue id. This so that receiving will start.
13288 	 */
13289 	if (need_reset && prog)
13290 		for (i = 0; i < vsi->num_queue_pairs; i++)
13291 			if (vsi->xdp_rings[i]->xsk_pool)
13292 				(void)i40e_xsk_wakeup(vsi->netdev, i,
13293 						      XDP_WAKEUP_RX);
13294 
13295 	return 0;
13296 }
13297 
13298 /**
13299  * i40e_enter_busy_conf - Enters busy config state
13300  * @vsi: vsi
13301  *
13302  * Returns 0 on success, <0 for failure.
13303  **/
13304 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
13305 {
13306 	struct i40e_pf *pf = vsi->back;
13307 	int timeout = 50;
13308 
13309 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
13310 		timeout--;
13311 		if (!timeout)
13312 			return -EBUSY;
13313 		usleep_range(1000, 2000);
13314 	}
13315 
13316 	return 0;
13317 }
13318 
13319 /**
13320  * i40e_exit_busy_conf - Exits busy config state
13321  * @vsi: vsi
13322  **/
13323 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
13324 {
13325 	struct i40e_pf *pf = vsi->back;
13326 
13327 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
13328 }
13329 
13330 /**
13331  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
13332  * @vsi: vsi
13333  * @queue_pair: queue pair
13334  **/
13335 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
13336 {
13337 	memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
13338 	       sizeof(vsi->rx_rings[queue_pair]->rx_stats));
13339 	memset(&vsi->tx_rings[queue_pair]->stats, 0,
13340 	       sizeof(vsi->tx_rings[queue_pair]->stats));
13341 	if (i40e_enabled_xdp_vsi(vsi)) {
13342 		memset(&vsi->xdp_rings[queue_pair]->stats, 0,
13343 		       sizeof(vsi->xdp_rings[queue_pair]->stats));
13344 	}
13345 }
13346 
13347 /**
13348  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
13349  * @vsi: vsi
13350  * @queue_pair: queue pair
13351  **/
13352 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
13353 {
13354 	i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
13355 	if (i40e_enabled_xdp_vsi(vsi)) {
13356 		/* Make sure that in-progress ndo_xdp_xmit calls are
13357 		 * completed.
13358 		 */
13359 		synchronize_rcu();
13360 		i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
13361 	}
13362 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13363 }
13364 
13365 /**
13366  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
13367  * @vsi: vsi
13368  * @queue_pair: queue pair
13369  * @enable: true for enable, false for disable
13370  **/
13371 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
13372 					bool enable)
13373 {
13374 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13375 	struct i40e_q_vector *q_vector = rxr->q_vector;
13376 
13377 	if (!vsi->netdev)
13378 		return;
13379 
13380 	/* All rings in a qp belong to the same qvector. */
13381 	if (q_vector->rx.ring || q_vector->tx.ring) {
13382 		if (enable)
13383 			napi_enable(&q_vector->napi);
13384 		else
13385 			napi_disable(&q_vector->napi);
13386 	}
13387 }
13388 
13389 /**
13390  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
13391  * @vsi: vsi
13392  * @queue_pair: queue pair
13393  * @enable: true for enable, false for disable
13394  *
13395  * Returns 0 on success, <0 on failure.
13396  **/
13397 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
13398 					bool enable)
13399 {
13400 	struct i40e_pf *pf = vsi->back;
13401 	int pf_q, ret = 0;
13402 
13403 	pf_q = vsi->base_queue + queue_pair;
13404 	ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
13405 				     false /*is xdp*/, enable);
13406 	if (ret) {
13407 		dev_info(&pf->pdev->dev,
13408 			 "VSI seid %d Tx ring %d %sable timeout\n",
13409 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13410 		return ret;
13411 	}
13412 
13413 	i40e_control_rx_q(pf, pf_q, enable);
13414 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
13415 	if (ret) {
13416 		dev_info(&pf->pdev->dev,
13417 			 "VSI seid %d Rx ring %d %sable timeout\n",
13418 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13419 		return ret;
13420 	}
13421 
13422 	/* Due to HW errata, on Rx disable only, the register can
13423 	 * indicate done before it really is. Needs 50ms to be sure
13424 	 */
13425 	if (!enable)
13426 		mdelay(50);
13427 
13428 	if (!i40e_enabled_xdp_vsi(vsi))
13429 		return ret;
13430 
13431 	ret = i40e_control_wait_tx_q(vsi->seid, pf,
13432 				     pf_q + vsi->alloc_queue_pairs,
13433 				     true /*is xdp*/, enable);
13434 	if (ret) {
13435 		dev_info(&pf->pdev->dev,
13436 			 "VSI seid %d XDP Tx ring %d %sable timeout\n",
13437 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
13438 	}
13439 
13440 	return ret;
13441 }
13442 
13443 /**
13444  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
13445  * @vsi: vsi
13446  * @queue_pair: queue_pair
13447  **/
13448 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
13449 {
13450 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13451 	struct i40e_pf *pf = vsi->back;
13452 	struct i40e_hw *hw = &pf->hw;
13453 
13454 	/* All rings in a qp belong to the same qvector. */
13455 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
13456 		i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
13457 	else
13458 		i40e_irq_dynamic_enable_icr0(pf);
13459 
13460 	i40e_flush(hw);
13461 }
13462 
13463 /**
13464  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
13465  * @vsi: vsi
13466  * @queue_pair: queue_pair
13467  **/
13468 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
13469 {
13470 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13471 	struct i40e_pf *pf = vsi->back;
13472 	struct i40e_hw *hw = &pf->hw;
13473 
13474 	/* For simplicity, instead of removing the qp interrupt causes
13475 	 * from the interrupt linked list, we simply disable the interrupt, and
13476 	 * leave the list intact.
13477 	 *
13478 	 * All rings in a qp belong to the same qvector.
13479 	 */
13480 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
13481 		u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
13482 
13483 		wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
13484 		i40e_flush(hw);
13485 		synchronize_irq(pf->msix_entries[intpf].vector);
13486 	} else {
13487 		/* Legacy and MSI mode - this stops all interrupt handling */
13488 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
13489 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
13490 		i40e_flush(hw);
13491 		synchronize_irq(pf->pdev->irq);
13492 	}
13493 }
13494 
13495 /**
13496  * i40e_queue_pair_disable - Disables a queue pair
13497  * @vsi: vsi
13498  * @queue_pair: queue pair
13499  *
13500  * Returns 0 on success, <0 on failure.
13501  **/
13502 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
13503 {
13504 	int err;
13505 
13506 	err = i40e_enter_busy_conf(vsi);
13507 	if (err)
13508 		return err;
13509 
13510 	i40e_queue_pair_disable_irq(vsi, queue_pair);
13511 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
13512 	i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
13513 	i40e_queue_pair_clean_rings(vsi, queue_pair);
13514 	i40e_queue_pair_reset_stats(vsi, queue_pair);
13515 
13516 	return err;
13517 }
13518 
13519 /**
13520  * i40e_queue_pair_enable - Enables a queue pair
13521  * @vsi: vsi
13522  * @queue_pair: queue pair
13523  *
13524  * Returns 0 on success, <0 on failure.
13525  **/
13526 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
13527 {
13528 	int err;
13529 
13530 	err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
13531 	if (err)
13532 		return err;
13533 
13534 	if (i40e_enabled_xdp_vsi(vsi)) {
13535 		err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
13536 		if (err)
13537 			return err;
13538 	}
13539 
13540 	err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
13541 	if (err)
13542 		return err;
13543 
13544 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
13545 	i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
13546 	i40e_queue_pair_enable_irq(vsi, queue_pair);
13547 
13548 	i40e_exit_busy_conf(vsi);
13549 
13550 	return err;
13551 }
13552 
13553 /**
13554  * i40e_xdp - implements ndo_bpf for i40e
13555  * @dev: netdevice
13556  * @xdp: XDP command
13557  **/
13558 static int i40e_xdp(struct net_device *dev,
13559 		    struct netdev_bpf *xdp)
13560 {
13561 	struct i40e_netdev_priv *np = netdev_priv(dev);
13562 	struct i40e_vsi *vsi = np->vsi;
13563 
13564 	if (vsi->type != I40E_VSI_MAIN)
13565 		return -EINVAL;
13566 
13567 	switch (xdp->command) {
13568 	case XDP_SETUP_PROG:
13569 		return i40e_xdp_setup(vsi, xdp->prog, xdp->extack);
13570 	case XDP_SETUP_XSK_POOL:
13571 		return i40e_xsk_pool_setup(vsi, xdp->xsk.pool,
13572 					   xdp->xsk.queue_id);
13573 	default:
13574 		return -EINVAL;
13575 	}
13576 }
13577 
13578 static const struct net_device_ops i40e_netdev_ops = {
13579 	.ndo_open		= i40e_open,
13580 	.ndo_stop		= i40e_close,
13581 	.ndo_start_xmit		= i40e_lan_xmit_frame,
13582 	.ndo_get_stats64	= i40e_get_netdev_stats_struct,
13583 	.ndo_set_rx_mode	= i40e_set_rx_mode,
13584 	.ndo_validate_addr	= eth_validate_addr,
13585 	.ndo_set_mac_address	= i40e_set_mac,
13586 	.ndo_change_mtu		= i40e_change_mtu,
13587 	.ndo_eth_ioctl		= i40e_ioctl,
13588 	.ndo_tx_timeout		= i40e_tx_timeout,
13589 	.ndo_vlan_rx_add_vid	= i40e_vlan_rx_add_vid,
13590 	.ndo_vlan_rx_kill_vid	= i40e_vlan_rx_kill_vid,
13591 #ifdef CONFIG_NET_POLL_CONTROLLER
13592 	.ndo_poll_controller	= i40e_netpoll,
13593 #endif
13594 	.ndo_setup_tc		= __i40e_setup_tc,
13595 	.ndo_select_queue	= i40e_lan_select_queue,
13596 	.ndo_set_features	= i40e_set_features,
13597 	.ndo_set_vf_mac		= i40e_ndo_set_vf_mac,
13598 	.ndo_set_vf_vlan	= i40e_ndo_set_vf_port_vlan,
13599 	.ndo_get_vf_stats	= i40e_get_vf_stats,
13600 	.ndo_set_vf_rate	= i40e_ndo_set_vf_bw,
13601 	.ndo_get_vf_config	= i40e_ndo_get_vf_config,
13602 	.ndo_set_vf_link_state	= i40e_ndo_set_vf_link_state,
13603 	.ndo_set_vf_spoofchk	= i40e_ndo_set_vf_spoofchk,
13604 	.ndo_set_vf_trust	= i40e_ndo_set_vf_trust,
13605 	.ndo_get_phys_port_id	= i40e_get_phys_port_id,
13606 	.ndo_fdb_add		= i40e_ndo_fdb_add,
13607 	.ndo_features_check	= i40e_features_check,
13608 	.ndo_bridge_getlink	= i40e_ndo_bridge_getlink,
13609 	.ndo_bridge_setlink	= i40e_ndo_bridge_setlink,
13610 	.ndo_bpf		= i40e_xdp,
13611 	.ndo_xdp_xmit		= i40e_xdp_xmit,
13612 	.ndo_xsk_wakeup	        = i40e_xsk_wakeup,
13613 	.ndo_dfwd_add_station	= i40e_fwd_add,
13614 	.ndo_dfwd_del_station	= i40e_fwd_del,
13615 };
13616 
13617 /**
13618  * i40e_config_netdev - Setup the netdev flags
13619  * @vsi: the VSI being configured
13620  *
13621  * Returns 0 on success, negative value on failure
13622  **/
13623 static int i40e_config_netdev(struct i40e_vsi *vsi)
13624 {
13625 	struct i40e_pf *pf = vsi->back;
13626 	struct i40e_hw *hw = &pf->hw;
13627 	struct i40e_netdev_priv *np;
13628 	struct net_device *netdev;
13629 	u8 broadcast[ETH_ALEN];
13630 	u8 mac_addr[ETH_ALEN];
13631 	int etherdev_size;
13632 	netdev_features_t hw_enc_features;
13633 	netdev_features_t hw_features;
13634 
13635 	etherdev_size = sizeof(struct i40e_netdev_priv);
13636 	netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
13637 	if (!netdev)
13638 		return -ENOMEM;
13639 
13640 	vsi->netdev = netdev;
13641 	np = netdev_priv(netdev);
13642 	np->vsi = vsi;
13643 
13644 	hw_enc_features = NETIF_F_SG			|
13645 			  NETIF_F_HW_CSUM		|
13646 			  NETIF_F_HIGHDMA		|
13647 			  NETIF_F_SOFT_FEATURES		|
13648 			  NETIF_F_TSO			|
13649 			  NETIF_F_TSO_ECN		|
13650 			  NETIF_F_TSO6			|
13651 			  NETIF_F_GSO_GRE		|
13652 			  NETIF_F_GSO_GRE_CSUM		|
13653 			  NETIF_F_GSO_PARTIAL		|
13654 			  NETIF_F_GSO_IPXIP4		|
13655 			  NETIF_F_GSO_IPXIP6		|
13656 			  NETIF_F_GSO_UDP_TUNNEL	|
13657 			  NETIF_F_GSO_UDP_TUNNEL_CSUM	|
13658 			  NETIF_F_GSO_UDP_L4		|
13659 			  NETIF_F_SCTP_CRC		|
13660 			  NETIF_F_RXHASH		|
13661 			  NETIF_F_RXCSUM		|
13662 			  0;
13663 
13664 	if (!(pf->hw_features & I40E_HW_OUTER_UDP_CSUM_CAPABLE))
13665 		netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
13666 
13667 	netdev->udp_tunnel_nic_info = &pf->udp_tunnel_nic;
13668 
13669 	netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
13670 
13671 	netdev->hw_enc_features |= hw_enc_features;
13672 
13673 	/* record features VLANs can make use of */
13674 	netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
13675 
13676 #define I40E_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE |		\
13677 				   NETIF_F_GSO_GRE_CSUM |	\
13678 				   NETIF_F_GSO_IPXIP4 |		\
13679 				   NETIF_F_GSO_IPXIP6 |		\
13680 				   NETIF_F_GSO_UDP_TUNNEL |	\
13681 				   NETIF_F_GSO_UDP_TUNNEL_CSUM)
13682 
13683 	netdev->gso_partial_features = I40E_GSO_PARTIAL_FEATURES;
13684 	netdev->features |= NETIF_F_GSO_PARTIAL |
13685 			    I40E_GSO_PARTIAL_FEATURES;
13686 
13687 	netdev->mpls_features |= NETIF_F_SG;
13688 	netdev->mpls_features |= NETIF_F_HW_CSUM;
13689 	netdev->mpls_features |= NETIF_F_TSO;
13690 	netdev->mpls_features |= NETIF_F_TSO6;
13691 	netdev->mpls_features |= I40E_GSO_PARTIAL_FEATURES;
13692 
13693 	/* enable macvlan offloads */
13694 	netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
13695 
13696 	hw_features = hw_enc_features		|
13697 		      NETIF_F_HW_VLAN_CTAG_TX	|
13698 		      NETIF_F_HW_VLAN_CTAG_RX;
13699 
13700 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
13701 		hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
13702 
13703 	netdev->hw_features |= hw_features;
13704 
13705 	netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
13706 	netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
13707 
13708 	netdev->features &= ~NETIF_F_HW_TC;
13709 
13710 	if (vsi->type == I40E_VSI_MAIN) {
13711 		SET_NETDEV_DEV(netdev, &pf->pdev->dev);
13712 		ether_addr_copy(mac_addr, hw->mac.perm_addr);
13713 		/* The following steps are necessary for two reasons. First,
13714 		 * some older NVM configurations load a default MAC-VLAN
13715 		 * filter that will accept any tagged packet, and we want to
13716 		 * replace this with a normal filter. Additionally, it is
13717 		 * possible our MAC address was provided by the platform using
13718 		 * Open Firmware or similar.
13719 		 *
13720 		 * Thus, we need to remove the default filter and install one
13721 		 * specific to the MAC address.
13722 		 */
13723 		i40e_rm_default_mac_filter(vsi, mac_addr);
13724 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13725 		i40e_add_mac_filter(vsi, mac_addr);
13726 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13727 	} else {
13728 		/* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
13729 		 * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
13730 		 * the end, which is 4 bytes long, so force truncation of the
13731 		 * original name by IFNAMSIZ - 4
13732 		 */
13733 		snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d",
13734 			 IFNAMSIZ - 4,
13735 			 pf->vsi[pf->lan_vsi]->netdev->name);
13736 		eth_random_addr(mac_addr);
13737 
13738 		spin_lock_bh(&vsi->mac_filter_hash_lock);
13739 		i40e_add_mac_filter(vsi, mac_addr);
13740 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
13741 	}
13742 
13743 	/* Add the broadcast filter so that we initially will receive
13744 	 * broadcast packets. Note that when a new VLAN is first added the
13745 	 * driver will convert all filters marked I40E_VLAN_ANY into VLAN
13746 	 * specific filters as part of transitioning into "vlan" operation.
13747 	 * When more VLANs are added, the driver will copy each existing MAC
13748 	 * filter and add it for the new VLAN.
13749 	 *
13750 	 * Broadcast filters are handled specially by
13751 	 * i40e_sync_filters_subtask, as the driver must to set the broadcast
13752 	 * promiscuous bit instead of adding this directly as a MAC/VLAN
13753 	 * filter. The subtask will update the correct broadcast promiscuous
13754 	 * bits as VLANs become active or inactive.
13755 	 */
13756 	eth_broadcast_addr(broadcast);
13757 	spin_lock_bh(&vsi->mac_filter_hash_lock);
13758 	i40e_add_mac_filter(vsi, broadcast);
13759 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
13760 
13761 	eth_hw_addr_set(netdev, mac_addr);
13762 	ether_addr_copy(netdev->perm_addr, mac_addr);
13763 
13764 	/* i40iw_net_event() reads 16 bytes from neigh->primary_key */
13765 	netdev->neigh_priv_len = sizeof(u32) * 4;
13766 
13767 	netdev->priv_flags |= IFF_UNICAST_FLT;
13768 	netdev->priv_flags |= IFF_SUPP_NOFCS;
13769 	/* Setup netdev TC information */
13770 	i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
13771 
13772 	netdev->netdev_ops = &i40e_netdev_ops;
13773 	netdev->watchdog_timeo = 5 * HZ;
13774 	i40e_set_ethtool_ops(netdev);
13775 
13776 	/* MTU range: 68 - 9706 */
13777 	netdev->min_mtu = ETH_MIN_MTU;
13778 	netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13779 
13780 	return 0;
13781 }
13782 
13783 /**
13784  * i40e_vsi_delete - Delete a VSI from the switch
13785  * @vsi: the VSI being removed
13786  *
13787  * Returns 0 on success, negative value on failure
13788  **/
13789 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13790 {
13791 	/* remove default VSI is not allowed */
13792 	if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13793 		return;
13794 
13795 	i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13796 }
13797 
13798 /**
13799  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13800  * @vsi: the VSI being queried
13801  *
13802  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13803  **/
13804 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13805 {
13806 	struct i40e_veb *veb;
13807 	struct i40e_pf *pf = vsi->back;
13808 
13809 	/* Uplink is not a bridge so default to VEB */
13810 	if (vsi->veb_idx >= I40E_MAX_VEB)
13811 		return 1;
13812 
13813 	veb = pf->veb[vsi->veb_idx];
13814 	if (!veb) {
13815 		dev_info(&pf->pdev->dev,
13816 			 "There is no veb associated with the bridge\n");
13817 		return -ENOENT;
13818 	}
13819 
13820 	/* Uplink is a bridge in VEPA mode */
13821 	if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13822 		return 0;
13823 	} else {
13824 		/* Uplink is a bridge in VEB mode */
13825 		return 1;
13826 	}
13827 
13828 	/* VEPA is now default bridge, so return 0 */
13829 	return 0;
13830 }
13831 
13832 /**
13833  * i40e_add_vsi - Add a VSI to the switch
13834  * @vsi: the VSI being configured
13835  *
13836  * This initializes a VSI context depending on the VSI type to be added and
13837  * passes it down to the add_vsi aq command.
13838  **/
13839 static int i40e_add_vsi(struct i40e_vsi *vsi)
13840 {
13841 	int ret = -ENODEV;
13842 	struct i40e_pf *pf = vsi->back;
13843 	struct i40e_hw *hw = &pf->hw;
13844 	struct i40e_vsi_context ctxt;
13845 	struct i40e_mac_filter *f;
13846 	struct hlist_node *h;
13847 	int bkt;
13848 
13849 	u8 enabled_tc = 0x1; /* TC0 enabled */
13850 	int f_count = 0;
13851 
13852 	memset(&ctxt, 0, sizeof(ctxt));
13853 	switch (vsi->type) {
13854 	case I40E_VSI_MAIN:
13855 		/* The PF's main VSI is already setup as part of the
13856 		 * device initialization, so we'll not bother with
13857 		 * the add_vsi call, but we will retrieve the current
13858 		 * VSI context.
13859 		 */
13860 		ctxt.seid = pf->main_vsi_seid;
13861 		ctxt.pf_num = pf->hw.pf_id;
13862 		ctxt.vf_num = 0;
13863 		ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13864 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13865 		if (ret) {
13866 			dev_info(&pf->pdev->dev,
13867 				 "couldn't get PF vsi config, err %s aq_err %s\n",
13868 				 i40e_stat_str(&pf->hw, ret),
13869 				 i40e_aq_str(&pf->hw,
13870 					     pf->hw.aq.asq_last_status));
13871 			return -ENOENT;
13872 		}
13873 		vsi->info = ctxt.info;
13874 		vsi->info.valid_sections = 0;
13875 
13876 		vsi->seid = ctxt.seid;
13877 		vsi->id = ctxt.vsi_number;
13878 
13879 		enabled_tc = i40e_pf_get_tc_map(pf);
13880 
13881 		/* Source pruning is enabled by default, so the flag is
13882 		 * negative logic - if it's set, we need to fiddle with
13883 		 * the VSI to disable source pruning.
13884 		 */
13885 		if (pf->flags & I40E_FLAG_SOURCE_PRUNING_DISABLED) {
13886 			memset(&ctxt, 0, sizeof(ctxt));
13887 			ctxt.seid = pf->main_vsi_seid;
13888 			ctxt.pf_num = pf->hw.pf_id;
13889 			ctxt.vf_num = 0;
13890 			ctxt.info.valid_sections |=
13891 				     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13892 			ctxt.info.switch_id =
13893 				   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13894 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13895 			if (ret) {
13896 				dev_info(&pf->pdev->dev,
13897 					 "update vsi failed, err %s aq_err %s\n",
13898 					 i40e_stat_str(&pf->hw, ret),
13899 					 i40e_aq_str(&pf->hw,
13900 						     pf->hw.aq.asq_last_status));
13901 				ret = -ENOENT;
13902 				goto err;
13903 			}
13904 		}
13905 
13906 		/* MFP mode setup queue map and update VSI */
13907 		if ((pf->flags & I40E_FLAG_MFP_ENABLED) &&
13908 		    !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
13909 			memset(&ctxt, 0, sizeof(ctxt));
13910 			ctxt.seid = pf->main_vsi_seid;
13911 			ctxt.pf_num = pf->hw.pf_id;
13912 			ctxt.vf_num = 0;
13913 			i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
13914 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13915 			if (ret) {
13916 				dev_info(&pf->pdev->dev,
13917 					 "update vsi failed, err %s aq_err %s\n",
13918 					 i40e_stat_str(&pf->hw, ret),
13919 					 i40e_aq_str(&pf->hw,
13920 						    pf->hw.aq.asq_last_status));
13921 				ret = -ENOENT;
13922 				goto err;
13923 			}
13924 			/* update the local VSI info queue map */
13925 			i40e_vsi_update_queue_map(vsi, &ctxt);
13926 			vsi->info.valid_sections = 0;
13927 		} else {
13928 			/* Default/Main VSI is only enabled for TC0
13929 			 * reconfigure it to enable all TCs that are
13930 			 * available on the port in SFP mode.
13931 			 * For MFP case the iSCSI PF would use this
13932 			 * flow to enable LAN+iSCSI TC.
13933 			 */
13934 			ret = i40e_vsi_config_tc(vsi, enabled_tc);
13935 			if (ret) {
13936 				/* Single TC condition is not fatal,
13937 				 * message and continue
13938 				 */
13939 				dev_info(&pf->pdev->dev,
13940 					 "failed to configure TCs for main VSI tc_map 0x%08x, err %s aq_err %s\n",
13941 					 enabled_tc,
13942 					 i40e_stat_str(&pf->hw, ret),
13943 					 i40e_aq_str(&pf->hw,
13944 						    pf->hw.aq.asq_last_status));
13945 			}
13946 		}
13947 		break;
13948 
13949 	case I40E_VSI_FDIR:
13950 		ctxt.pf_num = hw->pf_id;
13951 		ctxt.vf_num = 0;
13952 		ctxt.uplink_seid = vsi->uplink_seid;
13953 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13954 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13955 		if ((pf->flags & I40E_FLAG_VEB_MODE_ENABLED) &&
13956 		    (i40e_is_vsi_uplink_mode_veb(vsi))) {
13957 			ctxt.info.valid_sections |=
13958 			     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13959 			ctxt.info.switch_id =
13960 			   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13961 		}
13962 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13963 		break;
13964 
13965 	case I40E_VSI_VMDQ2:
13966 		ctxt.pf_num = hw->pf_id;
13967 		ctxt.vf_num = 0;
13968 		ctxt.uplink_seid = vsi->uplink_seid;
13969 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13970 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
13971 
13972 		/* This VSI is connected to VEB so the switch_id
13973 		 * should be set to zero by default.
13974 		 */
13975 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13976 			ctxt.info.valid_sections |=
13977 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13978 			ctxt.info.switch_id =
13979 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13980 		}
13981 
13982 		/* Setup the VSI tx/rx queue map for TC0 only for now */
13983 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13984 		break;
13985 
13986 	case I40E_VSI_SRIOV:
13987 		ctxt.pf_num = hw->pf_id;
13988 		ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
13989 		ctxt.uplink_seid = vsi->uplink_seid;
13990 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13991 		ctxt.flags = I40E_AQ_VSI_TYPE_VF;
13992 
13993 		/* This VSI is connected to VEB so the switch_id
13994 		 * should be set to zero by default.
13995 		 */
13996 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13997 			ctxt.info.valid_sections |=
13998 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13999 			ctxt.info.switch_id =
14000 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14001 		}
14002 
14003 		if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
14004 			ctxt.info.valid_sections |=
14005 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
14006 			ctxt.info.queueing_opt_flags |=
14007 				(I40E_AQ_VSI_QUE_OPT_TCP_ENA |
14008 				 I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
14009 		}
14010 
14011 		ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
14012 		ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
14013 		if (pf->vf[vsi->vf_id].spoofchk) {
14014 			ctxt.info.valid_sections |=
14015 				cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
14016 			ctxt.info.sec_flags |=
14017 				(I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
14018 				 I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
14019 		}
14020 		/* Setup the VSI tx/rx queue map for TC0 only for now */
14021 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14022 		break;
14023 
14024 	case I40E_VSI_IWARP:
14025 		/* send down message to iWARP */
14026 		break;
14027 
14028 	default:
14029 		return -ENODEV;
14030 	}
14031 
14032 	if (vsi->type != I40E_VSI_MAIN) {
14033 		ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
14034 		if (ret) {
14035 			dev_info(&vsi->back->pdev->dev,
14036 				 "add vsi failed, err %s aq_err %s\n",
14037 				 i40e_stat_str(&pf->hw, ret),
14038 				 i40e_aq_str(&pf->hw,
14039 					     pf->hw.aq.asq_last_status));
14040 			ret = -ENOENT;
14041 			goto err;
14042 		}
14043 		vsi->info = ctxt.info;
14044 		vsi->info.valid_sections = 0;
14045 		vsi->seid = ctxt.seid;
14046 		vsi->id = ctxt.vsi_number;
14047 	}
14048 
14049 	vsi->active_filters = 0;
14050 	clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
14051 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14052 	/* If macvlan filters already exist, force them to get loaded */
14053 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
14054 		f->state = I40E_FILTER_NEW;
14055 		f_count++;
14056 	}
14057 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14058 
14059 	if (f_count) {
14060 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
14061 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
14062 	}
14063 
14064 	/* Update VSI BW information */
14065 	ret = i40e_vsi_get_bw_info(vsi);
14066 	if (ret) {
14067 		dev_info(&pf->pdev->dev,
14068 			 "couldn't get vsi bw info, err %s aq_err %s\n",
14069 			 i40e_stat_str(&pf->hw, ret),
14070 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14071 		/* VSI is already added so not tearing that up */
14072 		ret = 0;
14073 	}
14074 
14075 err:
14076 	return ret;
14077 }
14078 
14079 /**
14080  * i40e_vsi_release - Delete a VSI and free its resources
14081  * @vsi: the VSI being removed
14082  *
14083  * Returns 0 on success or < 0 on error
14084  **/
14085 int i40e_vsi_release(struct i40e_vsi *vsi)
14086 {
14087 	struct i40e_mac_filter *f;
14088 	struct hlist_node *h;
14089 	struct i40e_veb *veb = NULL;
14090 	struct i40e_pf *pf;
14091 	u16 uplink_seid;
14092 	int i, n, bkt;
14093 
14094 	pf = vsi->back;
14095 
14096 	/* release of a VEB-owner or last VSI is not allowed */
14097 	if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
14098 		dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
14099 			 vsi->seid, vsi->uplink_seid);
14100 		return -ENODEV;
14101 	}
14102 	if (vsi == pf->vsi[pf->lan_vsi] &&
14103 	    !test_bit(__I40E_DOWN, pf->state)) {
14104 		dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
14105 		return -ENODEV;
14106 	}
14107 	set_bit(__I40E_VSI_RELEASING, vsi->state);
14108 	uplink_seid = vsi->uplink_seid;
14109 	if (vsi->type != I40E_VSI_SRIOV) {
14110 		if (vsi->netdev_registered) {
14111 			vsi->netdev_registered = false;
14112 			if (vsi->netdev) {
14113 				/* results in a call to i40e_close() */
14114 				unregister_netdev(vsi->netdev);
14115 			}
14116 		} else {
14117 			i40e_vsi_close(vsi);
14118 		}
14119 		i40e_vsi_disable_irq(vsi);
14120 	}
14121 
14122 	spin_lock_bh(&vsi->mac_filter_hash_lock);
14123 
14124 	/* clear the sync flag on all filters */
14125 	if (vsi->netdev) {
14126 		__dev_uc_unsync(vsi->netdev, NULL);
14127 		__dev_mc_unsync(vsi->netdev, NULL);
14128 	}
14129 
14130 	/* make sure any remaining filters are marked for deletion */
14131 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
14132 		__i40e_del_filter(vsi, f);
14133 
14134 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
14135 
14136 	i40e_sync_vsi_filters(vsi);
14137 
14138 	i40e_vsi_delete(vsi);
14139 	i40e_vsi_free_q_vectors(vsi);
14140 	if (vsi->netdev) {
14141 		free_netdev(vsi->netdev);
14142 		vsi->netdev = NULL;
14143 	}
14144 	i40e_vsi_clear_rings(vsi);
14145 	i40e_vsi_clear(vsi);
14146 
14147 	/* If this was the last thing on the VEB, except for the
14148 	 * controlling VSI, remove the VEB, which puts the controlling
14149 	 * VSI onto the next level down in the switch.
14150 	 *
14151 	 * Well, okay, there's one more exception here: don't remove
14152 	 * the orphan VEBs yet.  We'll wait for an explicit remove request
14153 	 * from up the network stack.
14154 	 */
14155 	for (n = 0, i = 0; i < pf->num_alloc_vsi; i++) {
14156 		if (pf->vsi[i] &&
14157 		    pf->vsi[i]->uplink_seid == uplink_seid &&
14158 		    (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14159 			n++;      /* count the VSIs */
14160 		}
14161 	}
14162 	for (i = 0; i < I40E_MAX_VEB; i++) {
14163 		if (!pf->veb[i])
14164 			continue;
14165 		if (pf->veb[i]->uplink_seid == uplink_seid)
14166 			n++;     /* count the VEBs */
14167 		if (pf->veb[i]->seid == uplink_seid)
14168 			veb = pf->veb[i];
14169 	}
14170 	if (n == 0 && veb && veb->uplink_seid != 0)
14171 		i40e_veb_release(veb);
14172 
14173 	return 0;
14174 }
14175 
14176 /**
14177  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
14178  * @vsi: ptr to the VSI
14179  *
14180  * This should only be called after i40e_vsi_mem_alloc() which allocates the
14181  * corresponding SW VSI structure and initializes num_queue_pairs for the
14182  * newly allocated VSI.
14183  *
14184  * Returns 0 on success or negative on failure
14185  **/
14186 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
14187 {
14188 	int ret = -ENOENT;
14189 	struct i40e_pf *pf = vsi->back;
14190 
14191 	if (vsi->q_vectors[0]) {
14192 		dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
14193 			 vsi->seid);
14194 		return -EEXIST;
14195 	}
14196 
14197 	if (vsi->base_vector) {
14198 		dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
14199 			 vsi->seid, vsi->base_vector);
14200 		return -EEXIST;
14201 	}
14202 
14203 	ret = i40e_vsi_alloc_q_vectors(vsi);
14204 	if (ret) {
14205 		dev_info(&pf->pdev->dev,
14206 			 "failed to allocate %d q_vector for VSI %d, ret=%d\n",
14207 			 vsi->num_q_vectors, vsi->seid, ret);
14208 		vsi->num_q_vectors = 0;
14209 		goto vector_setup_out;
14210 	}
14211 
14212 	/* In Legacy mode, we do not have to get any other vector since we
14213 	 * piggyback on the misc/ICR0 for queue interrupts.
14214 	*/
14215 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
14216 		return ret;
14217 	if (vsi->num_q_vectors)
14218 		vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
14219 						 vsi->num_q_vectors, vsi->idx);
14220 	if (vsi->base_vector < 0) {
14221 		dev_info(&pf->pdev->dev,
14222 			 "failed to get tracking for %d vectors for VSI %d, err=%d\n",
14223 			 vsi->num_q_vectors, vsi->seid, vsi->base_vector);
14224 		i40e_vsi_free_q_vectors(vsi);
14225 		ret = -ENOENT;
14226 		goto vector_setup_out;
14227 	}
14228 
14229 vector_setup_out:
14230 	return ret;
14231 }
14232 
14233 /**
14234  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
14235  * @vsi: pointer to the vsi.
14236  *
14237  * This re-allocates a vsi's queue resources.
14238  *
14239  * Returns pointer to the successfully allocated and configured VSI sw struct
14240  * on success, otherwise returns NULL on failure.
14241  **/
14242 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
14243 {
14244 	u16 alloc_queue_pairs;
14245 	struct i40e_pf *pf;
14246 	u8 enabled_tc;
14247 	int ret;
14248 
14249 	if (!vsi)
14250 		return NULL;
14251 
14252 	pf = vsi->back;
14253 
14254 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
14255 	i40e_vsi_clear_rings(vsi);
14256 
14257 	i40e_vsi_free_arrays(vsi, false);
14258 	i40e_set_num_rings_in_vsi(vsi);
14259 	ret = i40e_vsi_alloc_arrays(vsi, false);
14260 	if (ret)
14261 		goto err_vsi;
14262 
14263 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14264 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14265 
14266 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14267 	if (ret < 0) {
14268 		dev_info(&pf->pdev->dev,
14269 			 "failed to get tracking for %d queues for VSI %d err %d\n",
14270 			 alloc_queue_pairs, vsi->seid, ret);
14271 		goto err_vsi;
14272 	}
14273 	vsi->base_queue = ret;
14274 
14275 	/* Update the FW view of the VSI. Force a reset of TC and queue
14276 	 * layout configurations.
14277 	 */
14278 	enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
14279 	pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
14280 	pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
14281 	i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
14282 	if (vsi->type == I40E_VSI_MAIN)
14283 		i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
14284 
14285 	/* assign it some queues */
14286 	ret = i40e_alloc_rings(vsi);
14287 	if (ret)
14288 		goto err_rings;
14289 
14290 	/* map all of the rings to the q_vectors */
14291 	i40e_vsi_map_rings_to_vectors(vsi);
14292 	return vsi;
14293 
14294 err_rings:
14295 	i40e_vsi_free_q_vectors(vsi);
14296 	if (vsi->netdev_registered) {
14297 		vsi->netdev_registered = false;
14298 		unregister_netdev(vsi->netdev);
14299 		free_netdev(vsi->netdev);
14300 		vsi->netdev = NULL;
14301 	}
14302 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14303 err_vsi:
14304 	i40e_vsi_clear(vsi);
14305 	return NULL;
14306 }
14307 
14308 /**
14309  * i40e_vsi_setup - Set up a VSI by a given type
14310  * @pf: board private structure
14311  * @type: VSI type
14312  * @uplink_seid: the switch element to link to
14313  * @param1: usage depends upon VSI type. For VF types, indicates VF id
14314  *
14315  * This allocates the sw VSI structure and its queue resources, then add a VSI
14316  * to the identified VEB.
14317  *
14318  * Returns pointer to the successfully allocated and configure VSI sw struct on
14319  * success, otherwise returns NULL on failure.
14320  **/
14321 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
14322 				u16 uplink_seid, u32 param1)
14323 {
14324 	struct i40e_vsi *vsi = NULL;
14325 	struct i40e_veb *veb = NULL;
14326 	u16 alloc_queue_pairs;
14327 	int ret, i;
14328 	int v_idx;
14329 
14330 	/* The requested uplink_seid must be either
14331 	 *     - the PF's port seid
14332 	 *              no VEB is needed because this is the PF
14333 	 *              or this is a Flow Director special case VSI
14334 	 *     - seid of an existing VEB
14335 	 *     - seid of a VSI that owns an existing VEB
14336 	 *     - seid of a VSI that doesn't own a VEB
14337 	 *              a new VEB is created and the VSI becomes the owner
14338 	 *     - seid of the PF VSI, which is what creates the first VEB
14339 	 *              this is a special case of the previous
14340 	 *
14341 	 * Find which uplink_seid we were given and create a new VEB if needed
14342 	 */
14343 	for (i = 0; i < I40E_MAX_VEB; i++) {
14344 		if (pf->veb[i] && pf->veb[i]->seid == uplink_seid) {
14345 			veb = pf->veb[i];
14346 			break;
14347 		}
14348 	}
14349 
14350 	if (!veb && uplink_seid != pf->mac_seid) {
14351 
14352 		for (i = 0; i < pf->num_alloc_vsi; i++) {
14353 			if (pf->vsi[i] && pf->vsi[i]->seid == uplink_seid) {
14354 				vsi = pf->vsi[i];
14355 				break;
14356 			}
14357 		}
14358 		if (!vsi) {
14359 			dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
14360 				 uplink_seid);
14361 			return NULL;
14362 		}
14363 
14364 		if (vsi->uplink_seid == pf->mac_seid)
14365 			veb = i40e_veb_setup(pf, 0, pf->mac_seid, vsi->seid,
14366 					     vsi->tc_config.enabled_tc);
14367 		else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14368 			veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
14369 					     vsi->tc_config.enabled_tc);
14370 		if (veb) {
14371 			if (vsi->seid != pf->vsi[pf->lan_vsi]->seid) {
14372 				dev_info(&vsi->back->pdev->dev,
14373 					 "New VSI creation error, uplink seid of LAN VSI expected.\n");
14374 				return NULL;
14375 			}
14376 			/* We come up by default in VEPA mode if SRIOV is not
14377 			 * already enabled, in which case we can't force VEPA
14378 			 * mode.
14379 			 */
14380 			if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
14381 				veb->bridge_mode = BRIDGE_MODE_VEPA;
14382 				pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
14383 			}
14384 			i40e_config_bridge_mode(veb);
14385 		}
14386 		for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
14387 			if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
14388 				veb = pf->veb[i];
14389 		}
14390 		if (!veb) {
14391 			dev_info(&pf->pdev->dev, "couldn't add VEB\n");
14392 			return NULL;
14393 		}
14394 
14395 		vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14396 		uplink_seid = veb->seid;
14397 	}
14398 
14399 	/* get vsi sw struct */
14400 	v_idx = i40e_vsi_mem_alloc(pf, type);
14401 	if (v_idx < 0)
14402 		goto err_alloc;
14403 	vsi = pf->vsi[v_idx];
14404 	if (!vsi)
14405 		goto err_alloc;
14406 	vsi->type = type;
14407 	vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
14408 
14409 	if (type == I40E_VSI_MAIN)
14410 		pf->lan_vsi = v_idx;
14411 	else if (type == I40E_VSI_SRIOV)
14412 		vsi->vf_id = param1;
14413 	/* assign it some queues */
14414 	alloc_queue_pairs = vsi->alloc_queue_pairs *
14415 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14416 
14417 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14418 	if (ret < 0) {
14419 		dev_info(&pf->pdev->dev,
14420 			 "failed to get tracking for %d queues for VSI %d err=%d\n",
14421 			 alloc_queue_pairs, vsi->seid, ret);
14422 		goto err_vsi;
14423 	}
14424 	vsi->base_queue = ret;
14425 
14426 	/* get a VSI from the hardware */
14427 	vsi->uplink_seid = uplink_seid;
14428 	ret = i40e_add_vsi(vsi);
14429 	if (ret)
14430 		goto err_vsi;
14431 
14432 	switch (vsi->type) {
14433 	/* setup the netdev if needed */
14434 	case I40E_VSI_MAIN:
14435 	case I40E_VSI_VMDQ2:
14436 		ret = i40e_config_netdev(vsi);
14437 		if (ret)
14438 			goto err_netdev;
14439 		ret = i40e_netif_set_realnum_tx_rx_queues(vsi);
14440 		if (ret)
14441 			goto err_netdev;
14442 		ret = register_netdev(vsi->netdev);
14443 		if (ret)
14444 			goto err_netdev;
14445 		vsi->netdev_registered = true;
14446 		netif_carrier_off(vsi->netdev);
14447 #ifdef CONFIG_I40E_DCB
14448 		/* Setup DCB netlink interface */
14449 		i40e_dcbnl_setup(vsi);
14450 #endif /* CONFIG_I40E_DCB */
14451 		fallthrough;
14452 	case I40E_VSI_FDIR:
14453 		/* set up vectors and rings if needed */
14454 		ret = i40e_vsi_setup_vectors(vsi);
14455 		if (ret)
14456 			goto err_msix;
14457 
14458 		ret = i40e_alloc_rings(vsi);
14459 		if (ret)
14460 			goto err_rings;
14461 
14462 		/* map all of the rings to the q_vectors */
14463 		i40e_vsi_map_rings_to_vectors(vsi);
14464 
14465 		i40e_vsi_reset_stats(vsi);
14466 		break;
14467 	default:
14468 		/* no netdev or rings for the other VSI types */
14469 		break;
14470 	}
14471 
14472 	if ((pf->hw_features & I40E_HW_RSS_AQ_CAPABLE) &&
14473 	    (vsi->type == I40E_VSI_VMDQ2)) {
14474 		ret = i40e_vsi_config_rss(vsi);
14475 	}
14476 	return vsi;
14477 
14478 err_rings:
14479 	i40e_vsi_free_q_vectors(vsi);
14480 err_msix:
14481 	if (vsi->netdev_registered) {
14482 		vsi->netdev_registered = false;
14483 		unregister_netdev(vsi->netdev);
14484 		free_netdev(vsi->netdev);
14485 		vsi->netdev = NULL;
14486 	}
14487 err_netdev:
14488 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14489 err_vsi:
14490 	i40e_vsi_clear(vsi);
14491 err_alloc:
14492 	return NULL;
14493 }
14494 
14495 /**
14496  * i40e_veb_get_bw_info - Query VEB BW information
14497  * @veb: the veb to query
14498  *
14499  * Query the Tx scheduler BW configuration data for given VEB
14500  **/
14501 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
14502 {
14503 	struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
14504 	struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
14505 	struct i40e_pf *pf = veb->pf;
14506 	struct i40e_hw *hw = &pf->hw;
14507 	u32 tc_bw_max;
14508 	int ret = 0;
14509 	int i;
14510 
14511 	ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
14512 						  &bw_data, NULL);
14513 	if (ret) {
14514 		dev_info(&pf->pdev->dev,
14515 			 "query veb bw config failed, err %s aq_err %s\n",
14516 			 i40e_stat_str(&pf->hw, ret),
14517 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14518 		goto out;
14519 	}
14520 
14521 	ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
14522 						   &ets_data, NULL);
14523 	if (ret) {
14524 		dev_info(&pf->pdev->dev,
14525 			 "query veb bw ets config failed, err %s aq_err %s\n",
14526 			 i40e_stat_str(&pf->hw, ret),
14527 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14528 		goto out;
14529 	}
14530 
14531 	veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
14532 	veb->bw_max_quanta = ets_data.tc_bw_max;
14533 	veb->is_abs_credits = bw_data.absolute_credits_enable;
14534 	veb->enabled_tc = ets_data.tc_valid_bits;
14535 	tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
14536 		    (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
14537 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
14538 		veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
14539 		veb->bw_tc_limit_credits[i] =
14540 					le16_to_cpu(bw_data.tc_bw_limits[i]);
14541 		veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
14542 	}
14543 
14544 out:
14545 	return ret;
14546 }
14547 
14548 /**
14549  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
14550  * @pf: board private structure
14551  *
14552  * On error: returns error code (negative)
14553  * On success: returns vsi index in PF (positive)
14554  **/
14555 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
14556 {
14557 	int ret = -ENOENT;
14558 	struct i40e_veb *veb;
14559 	int i;
14560 
14561 	/* Need to protect the allocation of switch elements at the PF level */
14562 	mutex_lock(&pf->switch_mutex);
14563 
14564 	/* VEB list may be fragmented if VEB creation/destruction has
14565 	 * been happening.  We can afford to do a quick scan to look
14566 	 * for any free slots in the list.
14567 	 *
14568 	 * find next empty veb slot, looping back around if necessary
14569 	 */
14570 	i = 0;
14571 	while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
14572 		i++;
14573 	if (i >= I40E_MAX_VEB) {
14574 		ret = -ENOMEM;
14575 		goto err_alloc_veb;  /* out of VEB slots! */
14576 	}
14577 
14578 	veb = kzalloc(sizeof(*veb), GFP_KERNEL);
14579 	if (!veb) {
14580 		ret = -ENOMEM;
14581 		goto err_alloc_veb;
14582 	}
14583 	veb->pf = pf;
14584 	veb->idx = i;
14585 	veb->enabled_tc = 1;
14586 
14587 	pf->veb[i] = veb;
14588 	ret = i;
14589 err_alloc_veb:
14590 	mutex_unlock(&pf->switch_mutex);
14591 	return ret;
14592 }
14593 
14594 /**
14595  * i40e_switch_branch_release - Delete a branch of the switch tree
14596  * @branch: where to start deleting
14597  *
14598  * This uses recursion to find the tips of the branch to be
14599  * removed, deleting until we get back to and can delete this VEB.
14600  **/
14601 static void i40e_switch_branch_release(struct i40e_veb *branch)
14602 {
14603 	struct i40e_pf *pf = branch->pf;
14604 	u16 branch_seid = branch->seid;
14605 	u16 veb_idx = branch->idx;
14606 	int i;
14607 
14608 	/* release any VEBs on this VEB - RECURSION */
14609 	for (i = 0; i < I40E_MAX_VEB; i++) {
14610 		if (!pf->veb[i])
14611 			continue;
14612 		if (pf->veb[i]->uplink_seid == branch->seid)
14613 			i40e_switch_branch_release(pf->veb[i]);
14614 	}
14615 
14616 	/* Release the VSIs on this VEB, but not the owner VSI.
14617 	 *
14618 	 * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
14619 	 *       the VEB itself, so don't use (*branch) after this loop.
14620 	 */
14621 	for (i = 0; i < pf->num_alloc_vsi; i++) {
14622 		if (!pf->vsi[i])
14623 			continue;
14624 		if (pf->vsi[i]->uplink_seid == branch_seid &&
14625 		   (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14626 			i40e_vsi_release(pf->vsi[i]);
14627 		}
14628 	}
14629 
14630 	/* There's one corner case where the VEB might not have been
14631 	 * removed, so double check it here and remove it if needed.
14632 	 * This case happens if the veb was created from the debugfs
14633 	 * commands and no VSIs were added to it.
14634 	 */
14635 	if (pf->veb[veb_idx])
14636 		i40e_veb_release(pf->veb[veb_idx]);
14637 }
14638 
14639 /**
14640  * i40e_veb_clear - remove veb struct
14641  * @veb: the veb to remove
14642  **/
14643 static void i40e_veb_clear(struct i40e_veb *veb)
14644 {
14645 	if (!veb)
14646 		return;
14647 
14648 	if (veb->pf) {
14649 		struct i40e_pf *pf = veb->pf;
14650 
14651 		mutex_lock(&pf->switch_mutex);
14652 		if (pf->veb[veb->idx] == veb)
14653 			pf->veb[veb->idx] = NULL;
14654 		mutex_unlock(&pf->switch_mutex);
14655 	}
14656 
14657 	kfree(veb);
14658 }
14659 
14660 /**
14661  * i40e_veb_release - Delete a VEB and free its resources
14662  * @veb: the VEB being removed
14663  **/
14664 void i40e_veb_release(struct i40e_veb *veb)
14665 {
14666 	struct i40e_vsi *vsi = NULL;
14667 	struct i40e_pf *pf;
14668 	int i, n = 0;
14669 
14670 	pf = veb->pf;
14671 
14672 	/* find the remaining VSI and check for extras */
14673 	for (i = 0; i < pf->num_alloc_vsi; i++) {
14674 		if (pf->vsi[i] && pf->vsi[i]->uplink_seid == veb->seid) {
14675 			n++;
14676 			vsi = pf->vsi[i];
14677 		}
14678 	}
14679 	if (n != 1) {
14680 		dev_info(&pf->pdev->dev,
14681 			 "can't remove VEB %d with %d VSIs left\n",
14682 			 veb->seid, n);
14683 		return;
14684 	}
14685 
14686 	/* move the remaining VSI to uplink veb */
14687 	vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
14688 	if (veb->uplink_seid) {
14689 		vsi->uplink_seid = veb->uplink_seid;
14690 		if (veb->uplink_seid == pf->mac_seid)
14691 			vsi->veb_idx = I40E_NO_VEB;
14692 		else
14693 			vsi->veb_idx = veb->veb_idx;
14694 	} else {
14695 		/* floating VEB */
14696 		vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
14697 		vsi->veb_idx = pf->vsi[pf->lan_vsi]->veb_idx;
14698 	}
14699 
14700 	i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14701 	i40e_veb_clear(veb);
14702 }
14703 
14704 /**
14705  * i40e_add_veb - create the VEB in the switch
14706  * @veb: the VEB to be instantiated
14707  * @vsi: the controlling VSI
14708  **/
14709 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
14710 {
14711 	struct i40e_pf *pf = veb->pf;
14712 	bool enable_stats = !!(pf->flags & I40E_FLAG_VEB_STATS_ENABLED);
14713 	int ret;
14714 
14715 	ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi->seid,
14716 			      veb->enabled_tc, false,
14717 			      &veb->seid, enable_stats, NULL);
14718 
14719 	/* get a VEB from the hardware */
14720 	if (ret) {
14721 		dev_info(&pf->pdev->dev,
14722 			 "couldn't add VEB, err %s aq_err %s\n",
14723 			 i40e_stat_str(&pf->hw, ret),
14724 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14725 		return -EPERM;
14726 	}
14727 
14728 	/* get statistics counter */
14729 	ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
14730 					 &veb->stats_idx, NULL, NULL, NULL);
14731 	if (ret) {
14732 		dev_info(&pf->pdev->dev,
14733 			 "couldn't get VEB statistics idx, err %s aq_err %s\n",
14734 			 i40e_stat_str(&pf->hw, ret),
14735 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14736 		return -EPERM;
14737 	}
14738 	ret = i40e_veb_get_bw_info(veb);
14739 	if (ret) {
14740 		dev_info(&pf->pdev->dev,
14741 			 "couldn't get VEB bw info, err %s aq_err %s\n",
14742 			 i40e_stat_str(&pf->hw, ret),
14743 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14744 		i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14745 		return -ENOENT;
14746 	}
14747 
14748 	vsi->uplink_seid = veb->seid;
14749 	vsi->veb_idx = veb->idx;
14750 	vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14751 
14752 	return 0;
14753 }
14754 
14755 /**
14756  * i40e_veb_setup - Set up a VEB
14757  * @pf: board private structure
14758  * @flags: VEB setup flags
14759  * @uplink_seid: the switch element to link to
14760  * @vsi_seid: the initial VSI seid
14761  * @enabled_tc: Enabled TC bit-map
14762  *
14763  * This allocates the sw VEB structure and links it into the switch
14764  * It is possible and legal for this to be a duplicate of an already
14765  * existing VEB.  It is also possible for both uplink and vsi seids
14766  * to be zero, in order to create a floating VEB.
14767  *
14768  * Returns pointer to the successfully allocated VEB sw struct on
14769  * success, otherwise returns NULL on failure.
14770  **/
14771 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 flags,
14772 				u16 uplink_seid, u16 vsi_seid,
14773 				u8 enabled_tc)
14774 {
14775 	struct i40e_veb *veb, *uplink_veb = NULL;
14776 	int vsi_idx, veb_idx;
14777 	int ret;
14778 
14779 	/* if one seid is 0, the other must be 0 to create a floating relay */
14780 	if ((uplink_seid == 0 || vsi_seid == 0) &&
14781 	    (uplink_seid + vsi_seid != 0)) {
14782 		dev_info(&pf->pdev->dev,
14783 			 "one, not both seid's are 0: uplink=%d vsi=%d\n",
14784 			 uplink_seid, vsi_seid);
14785 		return NULL;
14786 	}
14787 
14788 	/* make sure there is such a vsi and uplink */
14789 	for (vsi_idx = 0; vsi_idx < pf->num_alloc_vsi; vsi_idx++)
14790 		if (pf->vsi[vsi_idx] && pf->vsi[vsi_idx]->seid == vsi_seid)
14791 			break;
14792 	if (vsi_idx == pf->num_alloc_vsi && vsi_seid != 0) {
14793 		dev_info(&pf->pdev->dev, "vsi seid %d not found\n",
14794 			 vsi_seid);
14795 		return NULL;
14796 	}
14797 
14798 	if (uplink_seid && uplink_seid != pf->mac_seid) {
14799 		for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
14800 			if (pf->veb[veb_idx] &&
14801 			    pf->veb[veb_idx]->seid == uplink_seid) {
14802 				uplink_veb = pf->veb[veb_idx];
14803 				break;
14804 			}
14805 		}
14806 		if (!uplink_veb) {
14807 			dev_info(&pf->pdev->dev,
14808 				 "uplink seid %d not found\n", uplink_seid);
14809 			return NULL;
14810 		}
14811 	}
14812 
14813 	/* get veb sw struct */
14814 	veb_idx = i40e_veb_mem_alloc(pf);
14815 	if (veb_idx < 0)
14816 		goto err_alloc;
14817 	veb = pf->veb[veb_idx];
14818 	veb->flags = flags;
14819 	veb->uplink_seid = uplink_seid;
14820 	veb->veb_idx = (uplink_veb ? uplink_veb->idx : I40E_NO_VEB);
14821 	veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14822 
14823 	/* create the VEB in the switch */
14824 	ret = i40e_add_veb(veb, pf->vsi[vsi_idx]);
14825 	if (ret)
14826 		goto err_veb;
14827 	if (vsi_idx == pf->lan_vsi)
14828 		pf->lan_veb = veb->idx;
14829 
14830 	return veb;
14831 
14832 err_veb:
14833 	i40e_veb_clear(veb);
14834 err_alloc:
14835 	return NULL;
14836 }
14837 
14838 /**
14839  * i40e_setup_pf_switch_element - set PF vars based on switch type
14840  * @pf: board private structure
14841  * @ele: element we are building info from
14842  * @num_reported: total number of elements
14843  * @printconfig: should we print the contents
14844  *
14845  * helper function to assist in extracting a few useful SEID values.
14846  **/
14847 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14848 				struct i40e_aqc_switch_config_element_resp *ele,
14849 				u16 num_reported, bool printconfig)
14850 {
14851 	u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14852 	u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14853 	u8 element_type = ele->element_type;
14854 	u16 seid = le16_to_cpu(ele->seid);
14855 
14856 	if (printconfig)
14857 		dev_info(&pf->pdev->dev,
14858 			 "type=%d seid=%d uplink=%d downlink=%d\n",
14859 			 element_type, seid, uplink_seid, downlink_seid);
14860 
14861 	switch (element_type) {
14862 	case I40E_SWITCH_ELEMENT_TYPE_MAC:
14863 		pf->mac_seid = seid;
14864 		break;
14865 	case I40E_SWITCH_ELEMENT_TYPE_VEB:
14866 		/* Main VEB? */
14867 		if (uplink_seid != pf->mac_seid)
14868 			break;
14869 		if (pf->lan_veb >= I40E_MAX_VEB) {
14870 			int v;
14871 
14872 			/* find existing or else empty VEB */
14873 			for (v = 0; v < I40E_MAX_VEB; v++) {
14874 				if (pf->veb[v] && (pf->veb[v]->seid == seid)) {
14875 					pf->lan_veb = v;
14876 					break;
14877 				}
14878 			}
14879 			if (pf->lan_veb >= I40E_MAX_VEB) {
14880 				v = i40e_veb_mem_alloc(pf);
14881 				if (v < 0)
14882 					break;
14883 				pf->lan_veb = v;
14884 			}
14885 		}
14886 		if (pf->lan_veb >= I40E_MAX_VEB)
14887 			break;
14888 
14889 		pf->veb[pf->lan_veb]->seid = seid;
14890 		pf->veb[pf->lan_veb]->uplink_seid = pf->mac_seid;
14891 		pf->veb[pf->lan_veb]->pf = pf;
14892 		pf->veb[pf->lan_veb]->veb_idx = I40E_NO_VEB;
14893 		break;
14894 	case I40E_SWITCH_ELEMENT_TYPE_VSI:
14895 		if (num_reported != 1)
14896 			break;
14897 		/* This is immediately after a reset so we can assume this is
14898 		 * the PF's VSI
14899 		 */
14900 		pf->mac_seid = uplink_seid;
14901 		pf->pf_seid = downlink_seid;
14902 		pf->main_vsi_seid = seid;
14903 		if (printconfig)
14904 			dev_info(&pf->pdev->dev,
14905 				 "pf_seid=%d main_vsi_seid=%d\n",
14906 				 pf->pf_seid, pf->main_vsi_seid);
14907 		break;
14908 	case I40E_SWITCH_ELEMENT_TYPE_PF:
14909 	case I40E_SWITCH_ELEMENT_TYPE_VF:
14910 	case I40E_SWITCH_ELEMENT_TYPE_EMP:
14911 	case I40E_SWITCH_ELEMENT_TYPE_BMC:
14912 	case I40E_SWITCH_ELEMENT_TYPE_PE:
14913 	case I40E_SWITCH_ELEMENT_TYPE_PA:
14914 		/* ignore these for now */
14915 		break;
14916 	default:
14917 		dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
14918 			 element_type, seid);
14919 		break;
14920 	}
14921 }
14922 
14923 /**
14924  * i40e_fetch_switch_configuration - Get switch config from firmware
14925  * @pf: board private structure
14926  * @printconfig: should we print the contents
14927  *
14928  * Get the current switch configuration from the device and
14929  * extract a few useful SEID values.
14930  **/
14931 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
14932 {
14933 	struct i40e_aqc_get_switch_config_resp *sw_config;
14934 	u16 next_seid = 0;
14935 	int ret = 0;
14936 	u8 *aq_buf;
14937 	int i;
14938 
14939 	aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
14940 	if (!aq_buf)
14941 		return -ENOMEM;
14942 
14943 	sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
14944 	do {
14945 		u16 num_reported, num_total;
14946 
14947 		ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
14948 						I40E_AQ_LARGE_BUF,
14949 						&next_seid, NULL);
14950 		if (ret) {
14951 			dev_info(&pf->pdev->dev,
14952 				 "get switch config failed err %s aq_err %s\n",
14953 				 i40e_stat_str(&pf->hw, ret),
14954 				 i40e_aq_str(&pf->hw,
14955 					     pf->hw.aq.asq_last_status));
14956 			kfree(aq_buf);
14957 			return -ENOENT;
14958 		}
14959 
14960 		num_reported = le16_to_cpu(sw_config->header.num_reported);
14961 		num_total = le16_to_cpu(sw_config->header.num_total);
14962 
14963 		if (printconfig)
14964 			dev_info(&pf->pdev->dev,
14965 				 "header: %d reported %d total\n",
14966 				 num_reported, num_total);
14967 
14968 		for (i = 0; i < num_reported; i++) {
14969 			struct i40e_aqc_switch_config_element_resp *ele =
14970 				&sw_config->element[i];
14971 
14972 			i40e_setup_pf_switch_element(pf, ele, num_reported,
14973 						     printconfig);
14974 		}
14975 	} while (next_seid != 0);
14976 
14977 	kfree(aq_buf);
14978 	return ret;
14979 }
14980 
14981 /**
14982  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
14983  * @pf: board private structure
14984  * @reinit: if the Main VSI needs to re-initialized.
14985  * @lock_acquired: indicates whether or not the lock has been acquired
14986  *
14987  * Returns 0 on success, negative value on failure
14988  **/
14989 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired)
14990 {
14991 	u16 flags = 0;
14992 	int ret;
14993 
14994 	/* find out what's out there already */
14995 	ret = i40e_fetch_switch_configuration(pf, false);
14996 	if (ret) {
14997 		dev_info(&pf->pdev->dev,
14998 			 "couldn't fetch switch config, err %s aq_err %s\n",
14999 			 i40e_stat_str(&pf->hw, ret),
15000 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15001 		return ret;
15002 	}
15003 	i40e_pf_reset_stats(pf);
15004 
15005 	/* set the switch config bit for the whole device to
15006 	 * support limited promisc or true promisc
15007 	 * when user requests promisc. The default is limited
15008 	 * promisc.
15009 	*/
15010 
15011 	if ((pf->hw.pf_id == 0) &&
15012 	    !(pf->flags & I40E_FLAG_TRUE_PROMISC_SUPPORT)) {
15013 		flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15014 		pf->last_sw_conf_flags = flags;
15015 	}
15016 
15017 	if (pf->hw.pf_id == 0) {
15018 		u16 valid_flags;
15019 
15020 		valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15021 		ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
15022 						NULL);
15023 		if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
15024 			dev_info(&pf->pdev->dev,
15025 				 "couldn't set switch config bits, err %s aq_err %s\n",
15026 				 i40e_stat_str(&pf->hw, ret),
15027 				 i40e_aq_str(&pf->hw,
15028 					     pf->hw.aq.asq_last_status));
15029 			/* not a fatal problem, just keep going */
15030 		}
15031 		pf->last_sw_conf_valid_flags = valid_flags;
15032 	}
15033 
15034 	/* first time setup */
15035 	if (pf->lan_vsi == I40E_NO_VSI || reinit) {
15036 		struct i40e_vsi *vsi = NULL;
15037 		u16 uplink_seid;
15038 
15039 		/* Set up the PF VSI associated with the PF's main VSI
15040 		 * that is already in the HW switch
15041 		 */
15042 		if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
15043 			uplink_seid = pf->veb[pf->lan_veb]->seid;
15044 		else
15045 			uplink_seid = pf->mac_seid;
15046 		if (pf->lan_vsi == I40E_NO_VSI)
15047 			vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN, uplink_seid, 0);
15048 		else if (reinit)
15049 			vsi = i40e_vsi_reinit_setup(pf->vsi[pf->lan_vsi]);
15050 		if (!vsi) {
15051 			dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
15052 			i40e_cloud_filter_exit(pf);
15053 			i40e_fdir_teardown(pf);
15054 			return -EAGAIN;
15055 		}
15056 	} else {
15057 		/* force a reset of TC and queue layout configurations */
15058 		u8 enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
15059 
15060 		pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
15061 		pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
15062 		i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
15063 	}
15064 	i40e_vlan_stripping_disable(pf->vsi[pf->lan_vsi]);
15065 
15066 	i40e_fdir_sb_setup(pf);
15067 
15068 	/* Setup static PF queue filter control settings */
15069 	ret = i40e_setup_pf_filter_control(pf);
15070 	if (ret) {
15071 		dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
15072 			 ret);
15073 		/* Failure here should not stop continuing other steps */
15074 	}
15075 
15076 	/* enable RSS in the HW, even for only one queue, as the stack can use
15077 	 * the hash
15078 	 */
15079 	if ((pf->flags & I40E_FLAG_RSS_ENABLED))
15080 		i40e_pf_config_rss(pf);
15081 
15082 	/* fill in link information and enable LSE reporting */
15083 	i40e_link_event(pf);
15084 
15085 	/* Initialize user-specific link properties */
15086 	pf->fc_autoneg_status = ((pf->hw.phy.link_info.an_info &
15087 				  I40E_AQ_AN_COMPLETED) ? true : false);
15088 
15089 	i40e_ptp_init(pf);
15090 
15091 	if (!lock_acquired)
15092 		rtnl_lock();
15093 
15094 	/* repopulate tunnel port filters */
15095 	udp_tunnel_nic_reset_ntf(pf->vsi[pf->lan_vsi]->netdev);
15096 
15097 	if (!lock_acquired)
15098 		rtnl_unlock();
15099 
15100 	return ret;
15101 }
15102 
15103 /**
15104  * i40e_determine_queue_usage - Work out queue distribution
15105  * @pf: board private structure
15106  **/
15107 static void i40e_determine_queue_usage(struct i40e_pf *pf)
15108 {
15109 	int queues_left;
15110 	int q_max;
15111 
15112 	pf->num_lan_qps = 0;
15113 
15114 	/* Find the max queues to be put into basic use.  We'll always be
15115 	 * using TC0, whether or not DCB is running, and TC0 will get the
15116 	 * big RSS set.
15117 	 */
15118 	queues_left = pf->hw.func_caps.num_tx_qp;
15119 
15120 	if ((queues_left == 1) ||
15121 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED)) {
15122 		/* one qp for PF, no queues for anything else */
15123 		queues_left = 0;
15124 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15125 
15126 		/* make sure all the fancies are disabled */
15127 		pf->flags &= ~(I40E_FLAG_RSS_ENABLED	|
15128 			       I40E_FLAG_IWARP_ENABLED	|
15129 			       I40E_FLAG_FD_SB_ENABLED	|
15130 			       I40E_FLAG_FD_ATR_ENABLED	|
15131 			       I40E_FLAG_DCB_CAPABLE	|
15132 			       I40E_FLAG_DCB_ENABLED	|
15133 			       I40E_FLAG_SRIOV_ENABLED	|
15134 			       I40E_FLAG_VMDQ_ENABLED);
15135 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15136 	} else if (!(pf->flags & (I40E_FLAG_RSS_ENABLED |
15137 				  I40E_FLAG_FD_SB_ENABLED |
15138 				  I40E_FLAG_FD_ATR_ENABLED |
15139 				  I40E_FLAG_DCB_CAPABLE))) {
15140 		/* one qp for PF */
15141 		pf->alloc_rss_size = pf->num_lan_qps = 1;
15142 		queues_left -= pf->num_lan_qps;
15143 
15144 		pf->flags &= ~(I40E_FLAG_RSS_ENABLED	|
15145 			       I40E_FLAG_IWARP_ENABLED	|
15146 			       I40E_FLAG_FD_SB_ENABLED	|
15147 			       I40E_FLAG_FD_ATR_ENABLED	|
15148 			       I40E_FLAG_DCB_ENABLED	|
15149 			       I40E_FLAG_VMDQ_ENABLED);
15150 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15151 	} else {
15152 		/* Not enough queues for all TCs */
15153 		if ((pf->flags & I40E_FLAG_DCB_CAPABLE) &&
15154 		    (queues_left < I40E_MAX_TRAFFIC_CLASS)) {
15155 			pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
15156 					I40E_FLAG_DCB_ENABLED);
15157 			dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
15158 		}
15159 
15160 		/* limit lan qps to the smaller of qps, cpus or msix */
15161 		q_max = max_t(int, pf->rss_size_max, num_online_cpus());
15162 		q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
15163 		q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
15164 		pf->num_lan_qps = q_max;
15165 
15166 		queues_left -= pf->num_lan_qps;
15167 	}
15168 
15169 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15170 		if (queues_left > 1) {
15171 			queues_left -= 1; /* save 1 queue for FD */
15172 		} else {
15173 			pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
15174 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15175 			dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
15176 		}
15177 	}
15178 
15179 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15180 	    pf->num_vf_qps && pf->num_req_vfs && queues_left) {
15181 		pf->num_req_vfs = min_t(int, pf->num_req_vfs,
15182 					(queues_left / pf->num_vf_qps));
15183 		queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
15184 	}
15185 
15186 	if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
15187 	    pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
15188 		pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
15189 					  (queues_left / pf->num_vmdq_qps));
15190 		queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
15191 	}
15192 
15193 	pf->queues_left = queues_left;
15194 	dev_dbg(&pf->pdev->dev,
15195 		"qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
15196 		pf->hw.func_caps.num_tx_qp,
15197 		!!(pf->flags & I40E_FLAG_FD_SB_ENABLED),
15198 		pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
15199 		pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
15200 		queues_left);
15201 }
15202 
15203 /**
15204  * i40e_setup_pf_filter_control - Setup PF static filter control
15205  * @pf: PF to be setup
15206  *
15207  * i40e_setup_pf_filter_control sets up a PF's initial filter control
15208  * settings. If PE/FCoE are enabled then it will also set the per PF
15209  * based filter sizes required for them. It also enables Flow director,
15210  * ethertype and macvlan type filter settings for the pf.
15211  *
15212  * Returns 0 on success, negative on failure
15213  **/
15214 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
15215 {
15216 	struct i40e_filter_control_settings *settings = &pf->filter_settings;
15217 
15218 	settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
15219 
15220 	/* Flow Director is enabled */
15221 	if (pf->flags & (I40E_FLAG_FD_SB_ENABLED | I40E_FLAG_FD_ATR_ENABLED))
15222 		settings->enable_fdir = true;
15223 
15224 	/* Ethtype and MACVLAN filters enabled for PF */
15225 	settings->enable_ethtype = true;
15226 	settings->enable_macvlan = true;
15227 
15228 	if (i40e_set_filter_control(&pf->hw, settings))
15229 		return -ENOENT;
15230 
15231 	return 0;
15232 }
15233 
15234 #define INFO_STRING_LEN 255
15235 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
15236 static void i40e_print_features(struct i40e_pf *pf)
15237 {
15238 	struct i40e_hw *hw = &pf->hw;
15239 	char *buf;
15240 	int i;
15241 
15242 	buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
15243 	if (!buf)
15244 		return;
15245 
15246 	i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
15247 #ifdef CONFIG_PCI_IOV
15248 	i += scnprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
15249 #endif
15250 	i += scnprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
15251 		      pf->hw.func_caps.num_vsis,
15252 		      pf->vsi[pf->lan_vsi]->num_queue_pairs);
15253 	if (pf->flags & I40E_FLAG_RSS_ENABLED)
15254 		i += scnprintf(&buf[i], REMAIN(i), " RSS");
15255 	if (pf->flags & I40E_FLAG_FD_ATR_ENABLED)
15256 		i += scnprintf(&buf[i], REMAIN(i), " FD_ATR");
15257 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15258 		i += scnprintf(&buf[i], REMAIN(i), " FD_SB");
15259 		i += scnprintf(&buf[i], REMAIN(i), " NTUPLE");
15260 	}
15261 	if (pf->flags & I40E_FLAG_DCB_CAPABLE)
15262 		i += scnprintf(&buf[i], REMAIN(i), " DCB");
15263 	i += scnprintf(&buf[i], REMAIN(i), " VxLAN");
15264 	i += scnprintf(&buf[i], REMAIN(i), " Geneve");
15265 	if (pf->flags & I40E_FLAG_PTP)
15266 		i += scnprintf(&buf[i], REMAIN(i), " PTP");
15267 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
15268 		i += scnprintf(&buf[i], REMAIN(i), " VEB");
15269 	else
15270 		i += scnprintf(&buf[i], REMAIN(i), " VEPA");
15271 
15272 	dev_info(&pf->pdev->dev, "%s\n", buf);
15273 	kfree(buf);
15274 	WARN_ON(i > INFO_STRING_LEN);
15275 }
15276 
15277 /**
15278  * i40e_get_platform_mac_addr - get platform-specific MAC address
15279  * @pdev: PCI device information struct
15280  * @pf: board private structure
15281  *
15282  * Look up the MAC address for the device. First we'll try
15283  * eth_platform_get_mac_address, which will check Open Firmware, or arch
15284  * specific fallback. Otherwise, we'll default to the stored value in
15285  * firmware.
15286  **/
15287 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
15288 {
15289 	if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
15290 		i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
15291 }
15292 
15293 /**
15294  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
15295  * @fec_cfg: FEC option to set in flags
15296  * @flags: ptr to flags in which we set FEC option
15297  **/
15298 void i40e_set_fec_in_flags(u8 fec_cfg, u32 *flags)
15299 {
15300 	if (fec_cfg & I40E_AQ_SET_FEC_AUTO)
15301 		*flags |= I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC;
15302 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
15303 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
15304 		*flags |= I40E_FLAG_RS_FEC;
15305 		*flags &= ~I40E_FLAG_BASE_R_FEC;
15306 	}
15307 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
15308 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
15309 		*flags |= I40E_FLAG_BASE_R_FEC;
15310 		*flags &= ~I40E_FLAG_RS_FEC;
15311 	}
15312 	if (fec_cfg == 0)
15313 		*flags &= ~(I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC);
15314 }
15315 
15316 /**
15317  * i40e_check_recovery_mode - check if we are running transition firmware
15318  * @pf: board private structure
15319  *
15320  * Check registers indicating the firmware runs in recovery mode. Sets the
15321  * appropriate driver state.
15322  *
15323  * Returns true if the recovery mode was detected, false otherwise
15324  **/
15325 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
15326 {
15327 	u32 val = rd32(&pf->hw, I40E_GL_FWSTS);
15328 
15329 	if (val & I40E_GL_FWSTS_FWS1B_MASK) {
15330 		dev_crit(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
15331 		dev_crit(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
15332 		set_bit(__I40E_RECOVERY_MODE, pf->state);
15333 
15334 		return true;
15335 	}
15336 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15337 		dev_info(&pf->pdev->dev, "Please do Power-On Reset to initialize adapter in normal mode with full functionality.\n");
15338 
15339 	return false;
15340 }
15341 
15342 /**
15343  * i40e_pf_loop_reset - perform reset in a loop.
15344  * @pf: board private structure
15345  *
15346  * This function is useful when a NIC is about to enter recovery mode.
15347  * When a NIC's internal data structures are corrupted the NIC's
15348  * firmware is going to enter recovery mode.
15349  * Right after a POR it takes about 7 minutes for firmware to enter
15350  * recovery mode. Until that time a NIC is in some kind of intermediate
15351  * state. After that time period the NIC almost surely enters
15352  * recovery mode. The only way for a driver to detect intermediate
15353  * state is to issue a series of pf-resets and check a return value.
15354  * If a PF reset returns success then the firmware could be in recovery
15355  * mode so the caller of this code needs to check for recovery mode
15356  * if this function returns success. There is a little chance that
15357  * firmware will hang in intermediate state forever.
15358  * Since waiting 7 minutes is quite a lot of time this function waits
15359  * 10 seconds and then gives up by returning an error.
15360  *
15361  * Return 0 on success, negative on failure.
15362  **/
15363 static i40e_status i40e_pf_loop_reset(struct i40e_pf *pf)
15364 {
15365 	/* wait max 10 seconds for PF reset to succeed */
15366 	const unsigned long time_end = jiffies + 10 * HZ;
15367 
15368 	struct i40e_hw *hw = &pf->hw;
15369 	i40e_status ret;
15370 
15371 	ret = i40e_pf_reset(hw);
15372 	while (ret != I40E_SUCCESS && time_before(jiffies, time_end)) {
15373 		usleep_range(10000, 20000);
15374 		ret = i40e_pf_reset(hw);
15375 	}
15376 
15377 	if (ret == I40E_SUCCESS)
15378 		pf->pfr_count++;
15379 	else
15380 		dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
15381 
15382 	return ret;
15383 }
15384 
15385 /**
15386  * i40e_check_fw_empr - check if FW issued unexpected EMP Reset
15387  * @pf: board private structure
15388  *
15389  * Check FW registers to determine if FW issued unexpected EMP Reset.
15390  * Every time when unexpected EMP Reset occurs the FW increments
15391  * a counter of unexpected EMP Resets. When the counter reaches 10
15392  * the FW should enter the Recovery mode
15393  *
15394  * Returns true if FW issued unexpected EMP Reset
15395  **/
15396 static bool i40e_check_fw_empr(struct i40e_pf *pf)
15397 {
15398 	const u32 fw_sts = rd32(&pf->hw, I40E_GL_FWSTS) &
15399 			   I40E_GL_FWSTS_FWS1B_MASK;
15400 	return (fw_sts > I40E_GL_FWSTS_FWS1B_EMPR_0) &&
15401 	       (fw_sts <= I40E_GL_FWSTS_FWS1B_EMPR_10);
15402 }
15403 
15404 /**
15405  * i40e_handle_resets - handle EMP resets and PF resets
15406  * @pf: board private structure
15407  *
15408  * Handle both EMP resets and PF resets and conclude whether there are
15409  * any issues regarding these resets. If there are any issues then
15410  * generate log entry.
15411  *
15412  * Return 0 if NIC is healthy or negative value when there are issues
15413  * with resets
15414  **/
15415 static i40e_status i40e_handle_resets(struct i40e_pf *pf)
15416 {
15417 	const i40e_status pfr = i40e_pf_loop_reset(pf);
15418 	const bool is_empr = i40e_check_fw_empr(pf);
15419 
15420 	if (is_empr || pfr != I40E_SUCCESS)
15421 		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");
15422 
15423 	return is_empr ? I40E_ERR_RESET_FAILED : pfr;
15424 }
15425 
15426 /**
15427  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
15428  * @pf: board private structure
15429  * @hw: ptr to the hardware info
15430  *
15431  * This function does a minimal setup of all subsystems needed for running
15432  * recovery mode.
15433  *
15434  * Returns 0 on success, negative on failure
15435  **/
15436 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
15437 {
15438 	struct i40e_vsi *vsi;
15439 	int err;
15440 	int v_idx;
15441 
15442 	pci_save_state(pf->pdev);
15443 
15444 	/* set up periodic task facility */
15445 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15446 	pf->service_timer_period = HZ;
15447 
15448 	INIT_WORK(&pf->service_task, i40e_service_task);
15449 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15450 
15451 	err = i40e_init_interrupt_scheme(pf);
15452 	if (err)
15453 		goto err_switch_setup;
15454 
15455 	/* The number of VSIs reported by the FW is the minimum guaranteed
15456 	 * to us; HW supports far more and we share the remaining pool with
15457 	 * the other PFs. We allocate space for more than the guarantee with
15458 	 * the understanding that we might not get them all later.
15459 	 */
15460 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15461 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15462 	else
15463 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15464 
15465 	/* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
15466 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15467 			  GFP_KERNEL);
15468 	if (!pf->vsi) {
15469 		err = -ENOMEM;
15470 		goto err_switch_setup;
15471 	}
15472 
15473 	/* We allocate one VSI which is needed as absolute minimum
15474 	 * in order to register the netdev
15475 	 */
15476 	v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
15477 	if (v_idx < 0) {
15478 		err = v_idx;
15479 		goto err_switch_setup;
15480 	}
15481 	pf->lan_vsi = v_idx;
15482 	vsi = pf->vsi[v_idx];
15483 	if (!vsi) {
15484 		err = -EFAULT;
15485 		goto err_switch_setup;
15486 	}
15487 	vsi->alloc_queue_pairs = 1;
15488 	err = i40e_config_netdev(vsi);
15489 	if (err)
15490 		goto err_switch_setup;
15491 	err = register_netdev(vsi->netdev);
15492 	if (err)
15493 		goto err_switch_setup;
15494 	vsi->netdev_registered = true;
15495 	i40e_dbg_pf_init(pf);
15496 
15497 	err = i40e_setup_misc_vector_for_recovery_mode(pf);
15498 	if (err)
15499 		goto err_switch_setup;
15500 
15501 	/* tell the firmware that we're starting */
15502 	i40e_send_version(pf);
15503 
15504 	/* since everything's happy, start the service_task timer */
15505 	mod_timer(&pf->service_timer,
15506 		  round_jiffies(jiffies + pf->service_timer_period));
15507 
15508 	return 0;
15509 
15510 err_switch_setup:
15511 	i40e_reset_interrupt_capability(pf);
15512 	del_timer_sync(&pf->service_timer);
15513 	i40e_shutdown_adminq(hw);
15514 	iounmap(hw->hw_addr);
15515 	pci_disable_pcie_error_reporting(pf->pdev);
15516 	pci_release_mem_regions(pf->pdev);
15517 	pci_disable_device(pf->pdev);
15518 	kfree(pf);
15519 
15520 	return err;
15521 }
15522 
15523 /**
15524  * i40e_set_subsystem_device_id - set subsystem device id
15525  * @hw: pointer to the hardware info
15526  *
15527  * Set PCI subsystem device id either from a pci_dev structure or
15528  * a specific FW register.
15529  **/
15530 static inline void i40e_set_subsystem_device_id(struct i40e_hw *hw)
15531 {
15532 	struct pci_dev *pdev = ((struct i40e_pf *)hw->back)->pdev;
15533 
15534 	hw->subsystem_device_id = pdev->subsystem_device ?
15535 		pdev->subsystem_device :
15536 		(ushort)(rd32(hw, I40E_PFPCI_SUBSYSID) & USHRT_MAX);
15537 }
15538 
15539 /**
15540  * i40e_probe - Device initialization routine
15541  * @pdev: PCI device information struct
15542  * @ent: entry in i40e_pci_tbl
15543  *
15544  * i40e_probe initializes a PF identified by a pci_dev structure.
15545  * The OS initialization, configuring of the PF private structure,
15546  * and a hardware reset occur.
15547  *
15548  * Returns 0 on success, negative on failure
15549  **/
15550 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
15551 {
15552 	struct i40e_aq_get_phy_abilities_resp abilities;
15553 #ifdef CONFIG_I40E_DCB
15554 	enum i40e_get_fw_lldp_status_resp lldp_status;
15555 	i40e_status status;
15556 #endif /* CONFIG_I40E_DCB */
15557 	struct i40e_pf *pf;
15558 	struct i40e_hw *hw;
15559 	static u16 pfs_found;
15560 	u16 wol_nvm_bits;
15561 	u16 link_status;
15562 	int err;
15563 	u32 val;
15564 	u32 i;
15565 
15566 	err = pci_enable_device_mem(pdev);
15567 	if (err)
15568 		return err;
15569 
15570 	/* set up for high or low dma */
15571 	err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
15572 	if (err) {
15573 		dev_err(&pdev->dev,
15574 			"DMA configuration failed: 0x%x\n", err);
15575 		goto err_dma;
15576 	}
15577 
15578 	/* set up pci connections */
15579 	err = pci_request_mem_regions(pdev, i40e_driver_name);
15580 	if (err) {
15581 		dev_info(&pdev->dev,
15582 			 "pci_request_selected_regions failed %d\n", err);
15583 		goto err_pci_reg;
15584 	}
15585 
15586 	pci_enable_pcie_error_reporting(pdev);
15587 	pci_set_master(pdev);
15588 
15589 	/* Now that we have a PCI connection, we need to do the
15590 	 * low level device setup.  This is primarily setting up
15591 	 * the Admin Queue structures and then querying for the
15592 	 * device's current profile information.
15593 	 */
15594 	pf = kzalloc(sizeof(*pf), GFP_KERNEL);
15595 	if (!pf) {
15596 		err = -ENOMEM;
15597 		goto err_pf_alloc;
15598 	}
15599 	pf->next_vsi = 0;
15600 	pf->pdev = pdev;
15601 	set_bit(__I40E_DOWN, pf->state);
15602 
15603 	hw = &pf->hw;
15604 	hw->back = pf;
15605 
15606 	pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
15607 				I40E_MAX_CSR_SPACE);
15608 	/* We believe that the highest register to read is
15609 	 * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
15610 	 * is not less than that before mapping to prevent a
15611 	 * kernel panic.
15612 	 */
15613 	if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
15614 		dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
15615 			pf->ioremap_len);
15616 		err = -ENOMEM;
15617 		goto err_ioremap;
15618 	}
15619 	hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
15620 	if (!hw->hw_addr) {
15621 		err = -EIO;
15622 		dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
15623 			 (unsigned int)pci_resource_start(pdev, 0),
15624 			 pf->ioremap_len, err);
15625 		goto err_ioremap;
15626 	}
15627 	hw->vendor_id = pdev->vendor;
15628 	hw->device_id = pdev->device;
15629 	pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
15630 	hw->subsystem_vendor_id = pdev->subsystem_vendor;
15631 	i40e_set_subsystem_device_id(hw);
15632 	hw->bus.device = PCI_SLOT(pdev->devfn);
15633 	hw->bus.func = PCI_FUNC(pdev->devfn);
15634 	hw->bus.bus_id = pdev->bus->number;
15635 	pf->instance = pfs_found;
15636 
15637 	/* Select something other than the 802.1ad ethertype for the
15638 	 * switch to use internally and drop on ingress.
15639 	 */
15640 	hw->switch_tag = 0xffff;
15641 	hw->first_tag = ETH_P_8021AD;
15642 	hw->second_tag = ETH_P_8021Q;
15643 
15644 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
15645 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
15646 	INIT_LIST_HEAD(&pf->ddp_old_prof);
15647 
15648 	/* set up the locks for the AQ, do this only once in probe
15649 	 * and destroy them only once in remove
15650 	 */
15651 	mutex_init(&hw->aq.asq_mutex);
15652 	mutex_init(&hw->aq.arq_mutex);
15653 
15654 	pf->msg_enable = netif_msg_init(debug,
15655 					NETIF_MSG_DRV |
15656 					NETIF_MSG_PROBE |
15657 					NETIF_MSG_LINK);
15658 	if (debug < -1)
15659 		pf->hw.debug_mask = debug;
15660 
15661 	/* do a special CORER for clearing PXE mode once at init */
15662 	if (hw->revision_id == 0 &&
15663 	    (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
15664 		wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
15665 		i40e_flush(hw);
15666 		msleep(200);
15667 		pf->corer_count++;
15668 
15669 		i40e_clear_pxe_mode(hw);
15670 	}
15671 
15672 	/* Reset here to make sure all is clean and to define PF 'n' */
15673 	i40e_clear_hw(hw);
15674 
15675 	err = i40e_set_mac_type(hw);
15676 	if (err) {
15677 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15678 			 err);
15679 		goto err_pf_reset;
15680 	}
15681 
15682 	err = i40e_handle_resets(pf);
15683 	if (err)
15684 		goto err_pf_reset;
15685 
15686 	i40e_check_recovery_mode(pf);
15687 
15688 	if (is_kdump_kernel()) {
15689 		hw->aq.num_arq_entries = I40E_MIN_ARQ_LEN;
15690 		hw->aq.num_asq_entries = I40E_MIN_ASQ_LEN;
15691 	} else {
15692 		hw->aq.num_arq_entries = I40E_AQ_LEN;
15693 		hw->aq.num_asq_entries = I40E_AQ_LEN;
15694 	}
15695 	hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15696 	hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15697 	pf->adminq_work_limit = I40E_AQ_WORK_LIMIT;
15698 
15699 	snprintf(pf->int_name, sizeof(pf->int_name) - 1,
15700 		 "%s-%s:misc",
15701 		 dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
15702 
15703 	err = i40e_init_shared_code(hw);
15704 	if (err) {
15705 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15706 			 err);
15707 		goto err_pf_reset;
15708 	}
15709 
15710 	/* set up a default setting for link flow control */
15711 	pf->hw.fc.requested_mode = I40E_FC_NONE;
15712 
15713 	err = i40e_init_adminq(hw);
15714 	if (err) {
15715 		if (err == I40E_ERR_FIRMWARE_API_VERSION)
15716 			dev_info(&pdev->dev,
15717 				 "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",
15718 				 hw->aq.api_maj_ver,
15719 				 hw->aq.api_min_ver,
15720 				 I40E_FW_API_VERSION_MAJOR,
15721 				 I40E_FW_MINOR_VERSION(hw));
15722 		else
15723 			dev_info(&pdev->dev,
15724 				 "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
15725 
15726 		goto err_pf_reset;
15727 	}
15728 	i40e_get_oem_version(hw);
15729 
15730 	/* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
15731 	dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
15732 		 hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
15733 		 hw->aq.api_maj_ver, hw->aq.api_min_ver,
15734 		 i40e_nvm_version_str(hw), hw->vendor_id, hw->device_id,
15735 		 hw->subsystem_vendor_id, hw->subsystem_device_id);
15736 
15737 	if (hw->aq.api_maj_ver == I40E_FW_API_VERSION_MAJOR &&
15738 	    hw->aq.api_min_ver > I40E_FW_MINOR_VERSION(hw))
15739 		dev_dbg(&pdev->dev,
15740 			"The driver for the device detected a newer version of the NVM image v%u.%u than v%u.%u.\n",
15741 			 hw->aq.api_maj_ver,
15742 			 hw->aq.api_min_ver,
15743 			 I40E_FW_API_VERSION_MAJOR,
15744 			 I40E_FW_MINOR_VERSION(hw));
15745 	else if (hw->aq.api_maj_ver == 1 && hw->aq.api_min_ver < 4)
15746 		dev_info(&pdev->dev,
15747 			 "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",
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 
15753 	i40e_verify_eeprom(pf);
15754 
15755 	/* Rev 0 hardware was never productized */
15756 	if (hw->revision_id < 1)
15757 		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");
15758 
15759 	i40e_clear_pxe_mode(hw);
15760 
15761 	err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
15762 	if (err)
15763 		goto err_adminq_setup;
15764 
15765 	err = i40e_sw_init(pf);
15766 	if (err) {
15767 		dev_info(&pdev->dev, "sw_init failed: %d\n", err);
15768 		goto err_sw_init;
15769 	}
15770 
15771 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15772 		return i40e_init_recovery_mode(pf, hw);
15773 
15774 	err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
15775 				hw->func_caps.num_rx_qp, 0, 0);
15776 	if (err) {
15777 		dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
15778 		goto err_init_lan_hmc;
15779 	}
15780 
15781 	err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
15782 	if (err) {
15783 		dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
15784 		err = -ENOENT;
15785 		goto err_configure_lan_hmc;
15786 	}
15787 
15788 	/* Disable LLDP for NICs that have firmware versions lower than v4.3.
15789 	 * Ignore error return codes because if it was already disabled via
15790 	 * hardware settings this will fail
15791 	 */
15792 	if (pf->hw_features & I40E_HW_STOP_FW_LLDP) {
15793 		dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
15794 		i40e_aq_stop_lldp(hw, true, false, NULL);
15795 	}
15796 
15797 	/* allow a platform config to override the HW addr */
15798 	i40e_get_platform_mac_addr(pdev, pf);
15799 
15800 	if (!is_valid_ether_addr(hw->mac.addr)) {
15801 		dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
15802 		err = -EIO;
15803 		goto err_mac_addr;
15804 	}
15805 	dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
15806 	ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
15807 	i40e_get_port_mac_addr(hw, hw->mac.port_addr);
15808 	if (is_valid_ether_addr(hw->mac.port_addr))
15809 		pf->hw_features |= I40E_HW_PORT_ID_VALID;
15810 
15811 	i40e_ptp_alloc_pins(pf);
15812 	pci_set_drvdata(pdev, pf);
15813 	pci_save_state(pdev);
15814 
15815 #ifdef CONFIG_I40E_DCB
15816 	status = i40e_get_fw_lldp_status(&pf->hw, &lldp_status);
15817 	(!status &&
15818 	 lldp_status == I40E_GET_FW_LLDP_STATUS_ENABLED) ?
15819 		(pf->flags &= ~I40E_FLAG_DISABLE_FW_LLDP) :
15820 		(pf->flags |= I40E_FLAG_DISABLE_FW_LLDP);
15821 	dev_info(&pdev->dev,
15822 		 (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) ?
15823 			"FW LLDP is disabled\n" :
15824 			"FW LLDP is enabled\n");
15825 
15826 	/* Enable FW to write default DCB config on link-up */
15827 	i40e_aq_set_dcb_parameters(hw, true, NULL);
15828 
15829 	err = i40e_init_pf_dcb(pf);
15830 	if (err) {
15831 		dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
15832 		pf->flags &= ~(I40E_FLAG_DCB_CAPABLE | I40E_FLAG_DCB_ENABLED);
15833 		/* Continue without DCB enabled */
15834 	}
15835 #endif /* CONFIG_I40E_DCB */
15836 
15837 	/* set up periodic task facility */
15838 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
15839 	pf->service_timer_period = HZ;
15840 
15841 	INIT_WORK(&pf->service_task, i40e_service_task);
15842 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15843 
15844 	/* NVM bit on means WoL disabled for the port */
15845 	i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15846 	if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15847 		pf->wol_en = false;
15848 	else
15849 		pf->wol_en = true;
15850 	device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15851 
15852 	/* set up the main switch operations */
15853 	i40e_determine_queue_usage(pf);
15854 	err = i40e_init_interrupt_scheme(pf);
15855 	if (err)
15856 		goto err_switch_setup;
15857 
15858 	/* Reduce Tx and Rx pairs for kdump
15859 	 * When MSI-X is enabled, it's not allowed to use more TC queue
15860 	 * pairs than MSI-X vectors (pf->num_lan_msix) exist. Thus
15861 	 * vsi->num_queue_pairs will be equal to pf->num_lan_msix, i.e., 1.
15862 	 */
15863 	if (is_kdump_kernel())
15864 		pf->num_lan_msix = 1;
15865 
15866 	pf->udp_tunnel_nic.set_port = i40e_udp_tunnel_set_port;
15867 	pf->udp_tunnel_nic.unset_port = i40e_udp_tunnel_unset_port;
15868 	pf->udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP;
15869 	pf->udp_tunnel_nic.shared = &pf->udp_tunnel_shared;
15870 	pf->udp_tunnel_nic.tables[0].n_entries = I40E_MAX_PF_UDP_OFFLOAD_PORTS;
15871 	pf->udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
15872 						    UDP_TUNNEL_TYPE_GENEVE;
15873 
15874 	/* The number of VSIs reported by the FW is the minimum guaranteed
15875 	 * to us; HW supports far more and we share the remaining pool with
15876 	 * the other PFs. We allocate space for more than the guarantee with
15877 	 * the understanding that we might not get them all later.
15878 	 */
15879 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15880 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15881 	else
15882 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15883 	if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
15884 		dev_warn(&pf->pdev->dev,
15885 			 "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
15886 			 pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
15887 		pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
15888 	}
15889 
15890 	/* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15891 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15892 			  GFP_KERNEL);
15893 	if (!pf->vsi) {
15894 		err = -ENOMEM;
15895 		goto err_switch_setup;
15896 	}
15897 
15898 #ifdef CONFIG_PCI_IOV
15899 	/* prep for VF support */
15900 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15901 	    (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15902 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15903 		if (pci_num_vf(pdev))
15904 			pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
15905 	}
15906 #endif
15907 	err = i40e_setup_pf_switch(pf, false, false);
15908 	if (err) {
15909 		dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
15910 		goto err_vsis;
15911 	}
15912 	INIT_LIST_HEAD(&pf->vsi[pf->lan_vsi]->ch_list);
15913 
15914 	/* if FDIR VSI was set up, start it now */
15915 	for (i = 0; i < pf->num_alloc_vsi; i++) {
15916 		if (pf->vsi[i] && pf->vsi[i]->type == I40E_VSI_FDIR) {
15917 			i40e_vsi_open(pf->vsi[i]);
15918 			break;
15919 		}
15920 	}
15921 
15922 	/* The driver only wants link up/down and module qualification
15923 	 * reports from firmware.  Note the negative logic.
15924 	 */
15925 	err = i40e_aq_set_phy_int_mask(&pf->hw,
15926 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
15927 					 I40E_AQ_EVENT_MEDIA_NA |
15928 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
15929 	if (err)
15930 		dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
15931 			 i40e_stat_str(&pf->hw, err),
15932 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15933 
15934 	/* Reconfigure hardware for allowing smaller MSS in the case
15935 	 * of TSO, so that we avoid the MDD being fired and causing
15936 	 * a reset in the case of small MSS+TSO.
15937 	 */
15938 	val = rd32(hw, I40E_REG_MSS);
15939 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
15940 		val &= ~I40E_REG_MSS_MIN_MASK;
15941 		val |= I40E_64BYTE_MSS;
15942 		wr32(hw, I40E_REG_MSS, val);
15943 	}
15944 
15945 	if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
15946 		msleep(75);
15947 		err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
15948 		if (err)
15949 			dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
15950 				 i40e_stat_str(&pf->hw, err),
15951 				 i40e_aq_str(&pf->hw,
15952 					     pf->hw.aq.asq_last_status));
15953 	}
15954 	/* The main driver is (mostly) up and happy. We need to set this state
15955 	 * before setting up the misc vector or we get a race and the vector
15956 	 * ends up disabled forever.
15957 	 */
15958 	clear_bit(__I40E_DOWN, pf->state);
15959 
15960 	/* In case of MSIX we are going to setup the misc vector right here
15961 	 * to handle admin queue events etc. In case of legacy and MSI
15962 	 * the misc functionality and queue processing is combined in
15963 	 * the same vector and that gets setup at open.
15964 	 */
15965 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
15966 		err = i40e_setup_misc_vector(pf);
15967 		if (err) {
15968 			dev_info(&pdev->dev,
15969 				 "setup of misc vector failed: %d\n", err);
15970 			i40e_cloud_filter_exit(pf);
15971 			i40e_fdir_teardown(pf);
15972 			goto err_vsis;
15973 		}
15974 	}
15975 
15976 #ifdef CONFIG_PCI_IOV
15977 	/* prep for VF support */
15978 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15979 	    (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15980 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15981 		/* disable link interrupts for VFs */
15982 		val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
15983 		val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
15984 		wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
15985 		i40e_flush(hw);
15986 
15987 		if (pci_num_vf(pdev)) {
15988 			dev_info(&pdev->dev,
15989 				 "Active VFs found, allocating resources.\n");
15990 			err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
15991 			if (err)
15992 				dev_info(&pdev->dev,
15993 					 "Error %d allocating resources for existing VFs\n",
15994 					 err);
15995 		}
15996 	}
15997 #endif /* CONFIG_PCI_IOV */
15998 
15999 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16000 		pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
16001 						      pf->num_iwarp_msix,
16002 						      I40E_IWARP_IRQ_PILE_ID);
16003 		if (pf->iwarp_base_vector < 0) {
16004 			dev_info(&pdev->dev,
16005 				 "failed to get tracking for %d vectors for IWARP err=%d\n",
16006 				 pf->num_iwarp_msix, pf->iwarp_base_vector);
16007 			pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
16008 		}
16009 	}
16010 
16011 	i40e_dbg_pf_init(pf);
16012 
16013 	/* tell the firmware that we're starting */
16014 	i40e_send_version(pf);
16015 
16016 	/* since everything's happy, start the service_task timer */
16017 	mod_timer(&pf->service_timer,
16018 		  round_jiffies(jiffies + pf->service_timer_period));
16019 
16020 	/* add this PF to client device list and launch a client service task */
16021 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16022 		err = i40e_lan_add_device(pf);
16023 		if (err)
16024 			dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
16025 				 err);
16026 	}
16027 
16028 #define PCI_SPEED_SIZE 8
16029 #define PCI_WIDTH_SIZE 8
16030 	/* Devices on the IOSF bus do not have this information
16031 	 * and will report PCI Gen 1 x 1 by default so don't bother
16032 	 * checking them.
16033 	 */
16034 	if (!(pf->hw_features & I40E_HW_NO_PCI_LINK_CHECK)) {
16035 		char speed[PCI_SPEED_SIZE] = "Unknown";
16036 		char width[PCI_WIDTH_SIZE] = "Unknown";
16037 
16038 		/* Get the negotiated link width and speed from PCI config
16039 		 * space
16040 		 */
16041 		pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
16042 					  &link_status);
16043 
16044 		i40e_set_pci_config_data(hw, link_status);
16045 
16046 		switch (hw->bus.speed) {
16047 		case i40e_bus_speed_8000:
16048 			strscpy(speed, "8.0", PCI_SPEED_SIZE); break;
16049 		case i40e_bus_speed_5000:
16050 			strscpy(speed, "5.0", PCI_SPEED_SIZE); break;
16051 		case i40e_bus_speed_2500:
16052 			strscpy(speed, "2.5", PCI_SPEED_SIZE); break;
16053 		default:
16054 			break;
16055 		}
16056 		switch (hw->bus.width) {
16057 		case i40e_bus_width_pcie_x8:
16058 			strscpy(width, "8", PCI_WIDTH_SIZE); break;
16059 		case i40e_bus_width_pcie_x4:
16060 			strscpy(width, "4", PCI_WIDTH_SIZE); break;
16061 		case i40e_bus_width_pcie_x2:
16062 			strscpy(width, "2", PCI_WIDTH_SIZE); break;
16063 		case i40e_bus_width_pcie_x1:
16064 			strscpy(width, "1", PCI_WIDTH_SIZE); break;
16065 		default:
16066 			break;
16067 		}
16068 
16069 		dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
16070 			 speed, width);
16071 
16072 		if (hw->bus.width < i40e_bus_width_pcie_x8 ||
16073 		    hw->bus.speed < i40e_bus_speed_8000) {
16074 			dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
16075 			dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
16076 		}
16077 	}
16078 
16079 	/* get the requested speeds from the fw */
16080 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
16081 	if (err)
16082 		dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %s last_status =  %s\n",
16083 			i40e_stat_str(&pf->hw, err),
16084 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16085 	pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
16086 
16087 	/* set the FEC config due to the board capabilities */
16088 	i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, &pf->flags);
16089 
16090 	/* get the supported phy types from the fw */
16091 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
16092 	if (err)
16093 		dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %s last_status =  %s\n",
16094 			i40e_stat_str(&pf->hw, err),
16095 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16096 
16097 	/* make sure the MFS hasn't been set lower than the default */
16098 #define MAX_FRAME_SIZE_DEFAULT 0x2600
16099 	val = (rd32(&pf->hw, I40E_PRTGL_SAH) &
16100 	       I40E_PRTGL_SAH_MFS_MASK) >> I40E_PRTGL_SAH_MFS_SHIFT;
16101 	if (val < MAX_FRAME_SIZE_DEFAULT)
16102 		dev_warn(&pdev->dev, "MFS for port %x has been set below the default: %x\n",
16103 			 i, val);
16104 
16105 	/* Add a filter to drop all Flow control frames from any VSI from being
16106 	 * transmitted. By doing so we stop a malicious VF from sending out
16107 	 * PAUSE or PFC frames and potentially controlling traffic for other
16108 	 * PF/VF VSIs.
16109 	 * The FW can still send Flow control frames if enabled.
16110 	 */
16111 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
16112 						       pf->main_vsi_seid);
16113 
16114 	if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
16115 		(pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
16116 		pf->hw_features |= I40E_HW_PHY_CONTROLS_LEDS;
16117 	if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
16118 		pf->hw_features |= I40E_HW_HAVE_CRT_RETIMER;
16119 	/* print a string summarizing features */
16120 	i40e_print_features(pf);
16121 
16122 	return 0;
16123 
16124 	/* Unwind what we've done if something failed in the setup */
16125 err_vsis:
16126 	set_bit(__I40E_DOWN, pf->state);
16127 	i40e_clear_interrupt_scheme(pf);
16128 	kfree(pf->vsi);
16129 err_switch_setup:
16130 	i40e_reset_interrupt_capability(pf);
16131 	del_timer_sync(&pf->service_timer);
16132 err_mac_addr:
16133 err_configure_lan_hmc:
16134 	(void)i40e_shutdown_lan_hmc(hw);
16135 err_init_lan_hmc:
16136 	kfree(pf->qp_pile);
16137 err_sw_init:
16138 err_adminq_setup:
16139 err_pf_reset:
16140 	iounmap(hw->hw_addr);
16141 err_ioremap:
16142 	kfree(pf);
16143 err_pf_alloc:
16144 	pci_disable_pcie_error_reporting(pdev);
16145 	pci_release_mem_regions(pdev);
16146 err_pci_reg:
16147 err_dma:
16148 	pci_disable_device(pdev);
16149 	return err;
16150 }
16151 
16152 /**
16153  * i40e_remove - Device removal routine
16154  * @pdev: PCI device information struct
16155  *
16156  * i40e_remove is called by the PCI subsystem to alert the driver
16157  * that is should release a PCI device.  This could be caused by a
16158  * Hot-Plug event, or because the driver is going to be removed from
16159  * memory.
16160  **/
16161 static void i40e_remove(struct pci_dev *pdev)
16162 {
16163 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16164 	struct i40e_hw *hw = &pf->hw;
16165 	i40e_status ret_code;
16166 	int i;
16167 
16168 	i40e_dbg_pf_exit(pf);
16169 
16170 	i40e_ptp_stop(pf);
16171 
16172 	/* Disable RSS in hw */
16173 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
16174 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
16175 
16176 	/* Grab __I40E_RESET_RECOVERY_PENDING and set __I40E_IN_REMOVE
16177 	 * flags, once they are set, i40e_rebuild should not be called as
16178 	 * i40e_prep_for_reset always returns early.
16179 	 */
16180 	while (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
16181 		usleep_range(1000, 2000);
16182 	set_bit(__I40E_IN_REMOVE, pf->state);
16183 
16184 	if (pf->flags & I40E_FLAG_SRIOV_ENABLED) {
16185 		set_bit(__I40E_VF_RESETS_DISABLED, pf->state);
16186 		i40e_free_vfs(pf);
16187 		pf->flags &= ~I40E_FLAG_SRIOV_ENABLED;
16188 	}
16189 	/* no more scheduling of any task */
16190 	set_bit(__I40E_SUSPENDED, pf->state);
16191 	set_bit(__I40E_DOWN, pf->state);
16192 	if (pf->service_timer.function)
16193 		del_timer_sync(&pf->service_timer);
16194 	if (pf->service_task.func)
16195 		cancel_work_sync(&pf->service_task);
16196 
16197 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
16198 		struct i40e_vsi *vsi = pf->vsi[0];
16199 
16200 		/* We know that we have allocated only one vsi for this PF,
16201 		 * it was just for registering netdevice, so the interface
16202 		 * could be visible in the 'ifconfig' output
16203 		 */
16204 		unregister_netdev(vsi->netdev);
16205 		free_netdev(vsi->netdev);
16206 
16207 		goto unmap;
16208 	}
16209 
16210 	/* Client close must be called explicitly here because the timer
16211 	 * has been stopped.
16212 	 */
16213 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16214 
16215 	i40e_fdir_teardown(pf);
16216 
16217 	/* If there is a switch structure or any orphans, remove them.
16218 	 * This will leave only the PF's VSI remaining.
16219 	 */
16220 	for (i = 0; i < I40E_MAX_VEB; i++) {
16221 		if (!pf->veb[i])
16222 			continue;
16223 
16224 		if (pf->veb[i]->uplink_seid == pf->mac_seid ||
16225 		    pf->veb[i]->uplink_seid == 0)
16226 			i40e_switch_branch_release(pf->veb[i]);
16227 	}
16228 
16229 	/* Now we can shutdown the PF's VSI, just before we kill
16230 	 * adminq and hmc.
16231 	 */
16232 	if (pf->vsi[pf->lan_vsi])
16233 		i40e_vsi_release(pf->vsi[pf->lan_vsi]);
16234 
16235 	i40e_cloud_filter_exit(pf);
16236 
16237 	/* remove attached clients */
16238 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16239 		ret_code = i40e_lan_del_device(pf);
16240 		if (ret_code)
16241 			dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
16242 				 ret_code);
16243 	}
16244 
16245 	/* shutdown and destroy the HMC */
16246 	if (hw->hmc.hmc_obj) {
16247 		ret_code = i40e_shutdown_lan_hmc(hw);
16248 		if (ret_code)
16249 			dev_warn(&pdev->dev,
16250 				 "Failed to destroy the HMC resources: %d\n",
16251 				 ret_code);
16252 	}
16253 
16254 unmap:
16255 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16256 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16257 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16258 		free_irq(pf->pdev->irq, pf);
16259 
16260 	/* shutdown the adminq */
16261 	i40e_shutdown_adminq(hw);
16262 
16263 	/* destroy the locks only once, here */
16264 	mutex_destroy(&hw->aq.arq_mutex);
16265 	mutex_destroy(&hw->aq.asq_mutex);
16266 
16267 	/* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
16268 	rtnl_lock();
16269 	i40e_clear_interrupt_scheme(pf);
16270 	for (i = 0; i < pf->num_alloc_vsi; i++) {
16271 		if (pf->vsi[i]) {
16272 			if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
16273 				i40e_vsi_clear_rings(pf->vsi[i]);
16274 			i40e_vsi_clear(pf->vsi[i]);
16275 			pf->vsi[i] = NULL;
16276 		}
16277 	}
16278 	rtnl_unlock();
16279 
16280 	for (i = 0; i < I40E_MAX_VEB; i++) {
16281 		kfree(pf->veb[i]);
16282 		pf->veb[i] = NULL;
16283 	}
16284 
16285 	kfree(pf->qp_pile);
16286 	kfree(pf->vsi);
16287 
16288 	iounmap(hw->hw_addr);
16289 	kfree(pf);
16290 	pci_release_mem_regions(pdev);
16291 
16292 	pci_disable_pcie_error_reporting(pdev);
16293 	pci_disable_device(pdev);
16294 }
16295 
16296 /**
16297  * i40e_pci_error_detected - warning that something funky happened in PCI land
16298  * @pdev: PCI device information struct
16299  * @error: the type of PCI error
16300  *
16301  * Called to warn that something happened and the error handling steps
16302  * are in progress.  Allows the driver to quiesce things, be ready for
16303  * remediation.
16304  **/
16305 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
16306 						pci_channel_state_t error)
16307 {
16308 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16309 
16310 	dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
16311 
16312 	if (!pf) {
16313 		dev_info(&pdev->dev,
16314 			 "Cannot recover - error happened during device probe\n");
16315 		return PCI_ERS_RESULT_DISCONNECT;
16316 	}
16317 
16318 	/* shutdown all operations */
16319 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16320 		i40e_prep_for_reset(pf);
16321 
16322 	/* Request a slot reset */
16323 	return PCI_ERS_RESULT_NEED_RESET;
16324 }
16325 
16326 /**
16327  * i40e_pci_error_slot_reset - a PCI slot reset just happened
16328  * @pdev: PCI device information struct
16329  *
16330  * Called to find if the driver can work with the device now that
16331  * the pci slot has been reset.  If a basic connection seems good
16332  * (registers are readable and have sane content) then return a
16333  * happy little PCI_ERS_RESULT_xxx.
16334  **/
16335 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
16336 {
16337 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16338 	pci_ers_result_t result;
16339 	u32 reg;
16340 
16341 	dev_dbg(&pdev->dev, "%s\n", __func__);
16342 	if (pci_enable_device_mem(pdev)) {
16343 		dev_info(&pdev->dev,
16344 			 "Cannot re-enable PCI device after reset.\n");
16345 		result = PCI_ERS_RESULT_DISCONNECT;
16346 	} else {
16347 		pci_set_master(pdev);
16348 		pci_restore_state(pdev);
16349 		pci_save_state(pdev);
16350 		pci_wake_from_d3(pdev, false);
16351 
16352 		reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
16353 		if (reg == 0)
16354 			result = PCI_ERS_RESULT_RECOVERED;
16355 		else
16356 			result = PCI_ERS_RESULT_DISCONNECT;
16357 	}
16358 
16359 	return result;
16360 }
16361 
16362 /**
16363  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
16364  * @pdev: PCI device information struct
16365  */
16366 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
16367 {
16368 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16369 
16370 	i40e_prep_for_reset(pf);
16371 }
16372 
16373 /**
16374  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
16375  * @pdev: PCI device information struct
16376  */
16377 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
16378 {
16379 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16380 
16381 	if (test_bit(__I40E_IN_REMOVE, pf->state))
16382 		return;
16383 
16384 	i40e_reset_and_rebuild(pf, false, false);
16385 }
16386 
16387 /**
16388  * i40e_pci_error_resume - restart operations after PCI error recovery
16389  * @pdev: PCI device information struct
16390  *
16391  * Called to allow the driver to bring things back up after PCI error
16392  * and/or reset recovery has finished.
16393  **/
16394 static void i40e_pci_error_resume(struct pci_dev *pdev)
16395 {
16396 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16397 
16398 	dev_dbg(&pdev->dev, "%s\n", __func__);
16399 	if (test_bit(__I40E_SUSPENDED, pf->state))
16400 		return;
16401 
16402 	i40e_handle_reset_warning(pf, false);
16403 }
16404 
16405 /**
16406  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
16407  * using the mac_address_write admin q function
16408  * @pf: pointer to i40e_pf struct
16409  **/
16410 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
16411 {
16412 	struct i40e_hw *hw = &pf->hw;
16413 	i40e_status ret;
16414 	u8 mac_addr[6];
16415 	u16 flags = 0;
16416 
16417 	/* Get current MAC address in case it's an LAA */
16418 	if (pf->vsi[pf->lan_vsi] && pf->vsi[pf->lan_vsi]->netdev) {
16419 		ether_addr_copy(mac_addr,
16420 				pf->vsi[pf->lan_vsi]->netdev->dev_addr);
16421 	} else {
16422 		dev_err(&pf->pdev->dev,
16423 			"Failed to retrieve MAC address; using default\n");
16424 		ether_addr_copy(mac_addr, hw->mac.addr);
16425 	}
16426 
16427 	/* The FW expects the mac address write cmd to first be called with
16428 	 * one of these flags before calling it again with the multicast
16429 	 * enable flags.
16430 	 */
16431 	flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
16432 
16433 	if (hw->func_caps.flex10_enable && hw->partition_id != 1)
16434 		flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
16435 
16436 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16437 	if (ret) {
16438 		dev_err(&pf->pdev->dev,
16439 			"Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
16440 		return;
16441 	}
16442 
16443 	flags = I40E_AQC_MC_MAG_EN
16444 			| I40E_AQC_WOL_PRESERVE_ON_PFR
16445 			| I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
16446 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16447 	if (ret)
16448 		dev_err(&pf->pdev->dev,
16449 			"Failed to enable Multicast Magic Packet wake up\n");
16450 }
16451 
16452 /**
16453  * i40e_shutdown - PCI callback for shutting down
16454  * @pdev: PCI device information struct
16455  **/
16456 static void i40e_shutdown(struct pci_dev *pdev)
16457 {
16458 	struct i40e_pf *pf = pci_get_drvdata(pdev);
16459 	struct i40e_hw *hw = &pf->hw;
16460 
16461 	set_bit(__I40E_SUSPENDED, pf->state);
16462 	set_bit(__I40E_DOWN, pf->state);
16463 
16464 	del_timer_sync(&pf->service_timer);
16465 	cancel_work_sync(&pf->service_task);
16466 	i40e_cloud_filter_exit(pf);
16467 	i40e_fdir_teardown(pf);
16468 
16469 	/* Client close must be called explicitly here because the timer
16470 	 * has been stopped.
16471 	 */
16472 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16473 
16474 	if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16475 		i40e_enable_mc_magic_wake(pf);
16476 
16477 	i40e_prep_for_reset(pf);
16478 
16479 	wr32(hw, I40E_PFPM_APM,
16480 	     (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16481 	wr32(hw, I40E_PFPM_WUFC,
16482 	     (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16483 
16484 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
16485 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16486 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16487 		free_irq(pf->pdev->irq, pf);
16488 
16489 	/* Since we're going to destroy queues during the
16490 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16491 	 * whole section
16492 	 */
16493 	rtnl_lock();
16494 	i40e_clear_interrupt_scheme(pf);
16495 	rtnl_unlock();
16496 
16497 	if (system_state == SYSTEM_POWER_OFF) {
16498 		pci_wake_from_d3(pdev, pf->wol_en);
16499 		pci_set_power_state(pdev, PCI_D3hot);
16500 	}
16501 }
16502 
16503 /**
16504  * i40e_suspend - PM callback for moving to D3
16505  * @dev: generic device information structure
16506  **/
16507 static int __maybe_unused i40e_suspend(struct device *dev)
16508 {
16509 	struct i40e_pf *pf = dev_get_drvdata(dev);
16510 	struct i40e_hw *hw = &pf->hw;
16511 
16512 	/* If we're already suspended, then there is nothing to do */
16513 	if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
16514 		return 0;
16515 
16516 	set_bit(__I40E_DOWN, pf->state);
16517 
16518 	/* Ensure service task will not be running */
16519 	del_timer_sync(&pf->service_timer);
16520 	cancel_work_sync(&pf->service_task);
16521 
16522 	/* Client close must be called explicitly here because the timer
16523 	 * has been stopped.
16524 	 */
16525 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16526 
16527 	if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16528 		i40e_enable_mc_magic_wake(pf);
16529 
16530 	/* Since we're going to destroy queues during the
16531 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16532 	 * whole section
16533 	 */
16534 	rtnl_lock();
16535 
16536 	i40e_prep_for_reset(pf);
16537 
16538 	wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16539 	wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16540 
16541 	/* Clear the interrupt scheme and release our IRQs so that the system
16542 	 * can safely hibernate even when there are a large number of CPUs.
16543 	 * Otherwise hibernation might fail when mapping all the vectors back
16544 	 * to CPU0.
16545 	 */
16546 	i40e_clear_interrupt_scheme(pf);
16547 
16548 	rtnl_unlock();
16549 
16550 	return 0;
16551 }
16552 
16553 /**
16554  * i40e_resume - PM callback for waking up from D3
16555  * @dev: generic device information structure
16556  **/
16557 static int __maybe_unused i40e_resume(struct device *dev)
16558 {
16559 	struct i40e_pf *pf = dev_get_drvdata(dev);
16560 	int err;
16561 
16562 	/* If we're not suspended, then there is nothing to do */
16563 	if (!test_bit(__I40E_SUSPENDED, pf->state))
16564 		return 0;
16565 
16566 	/* We need to hold the RTNL lock prior to restoring interrupt schemes,
16567 	 * since we're going to be restoring queues
16568 	 */
16569 	rtnl_lock();
16570 
16571 	/* We cleared the interrupt scheme when we suspended, so we need to
16572 	 * restore it now to resume device functionality.
16573 	 */
16574 	err = i40e_restore_interrupt_scheme(pf);
16575 	if (err) {
16576 		dev_err(dev, "Cannot restore interrupt scheme: %d\n",
16577 			err);
16578 	}
16579 
16580 	clear_bit(__I40E_DOWN, pf->state);
16581 	i40e_reset_and_rebuild(pf, false, true);
16582 
16583 	rtnl_unlock();
16584 
16585 	/* Clear suspended state last after everything is recovered */
16586 	clear_bit(__I40E_SUSPENDED, pf->state);
16587 
16588 	/* Restart the service task */
16589 	mod_timer(&pf->service_timer,
16590 		  round_jiffies(jiffies + pf->service_timer_period));
16591 
16592 	return 0;
16593 }
16594 
16595 static const struct pci_error_handlers i40e_err_handler = {
16596 	.error_detected = i40e_pci_error_detected,
16597 	.slot_reset = i40e_pci_error_slot_reset,
16598 	.reset_prepare = i40e_pci_error_reset_prepare,
16599 	.reset_done = i40e_pci_error_reset_done,
16600 	.resume = i40e_pci_error_resume,
16601 };
16602 
16603 static SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
16604 
16605 static struct pci_driver i40e_driver = {
16606 	.name     = i40e_driver_name,
16607 	.id_table = i40e_pci_tbl,
16608 	.probe    = i40e_probe,
16609 	.remove   = i40e_remove,
16610 	.driver   = {
16611 		.pm = &i40e_pm_ops,
16612 	},
16613 	.shutdown = i40e_shutdown,
16614 	.err_handler = &i40e_err_handler,
16615 	.sriov_configure = i40e_pci_sriov_configure,
16616 };
16617 
16618 /**
16619  * i40e_init_module - Driver registration routine
16620  *
16621  * i40e_init_module is the first routine called when the driver is
16622  * loaded. All it does is register with the PCI subsystem.
16623  **/
16624 static int __init i40e_init_module(void)
16625 {
16626 	pr_info("%s: %s\n", i40e_driver_name, i40e_driver_string);
16627 	pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
16628 
16629 	/* There is no need to throttle the number of active tasks because
16630 	 * each device limits its own task using a state bit for scheduling
16631 	 * the service task, and the device tasks do not interfere with each
16632 	 * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
16633 	 * since we need to be able to guarantee forward progress even under
16634 	 * memory pressure.
16635 	 */
16636 	i40e_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, i40e_driver_name);
16637 	if (!i40e_wq) {
16638 		pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
16639 		return -ENOMEM;
16640 	}
16641 
16642 	i40e_dbg_init();
16643 	return pci_register_driver(&i40e_driver);
16644 }
16645 module_init(i40e_init_module);
16646 
16647 /**
16648  * i40e_exit_module - Driver exit cleanup routine
16649  *
16650  * i40e_exit_module is called just before the driver is removed
16651  * from memory.
16652  **/
16653 static void __exit i40e_exit_module(void)
16654 {
16655 	pci_unregister_driver(&i40e_driver);
16656 	destroy_workqueue(i40e_wq);
16657 	ida_destroy(&i40e_client_ida);
16658 	i40e_dbg_exit();
16659 }
16660 module_exit(i40e_exit_module);
16661