xref: /linux/drivers/net/ethernet/ibm/ibmvnic.c (revision a3a02a52bcfcbcc4a637d4b68bf1bc391c9fad02)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /**************************************************************************/
3 /*                                                                        */
4 /*  IBM System i and System p Virtual NIC Device Driver                   */
5 /*  Copyright (C) 2014 IBM Corp.                                          */
6 /*  Santiago Leon (santi_leon@yahoo.com)                                  */
7 /*  Thomas Falcon (tlfalcon@linux.vnet.ibm.com)                           */
8 /*  John Allen (jallen@linux.vnet.ibm.com)                                */
9 /*                                                                        */
10 /*                                                                        */
11 /* This module contains the implementation of a virtual ethernet device   */
12 /* for use with IBM i/p Series LPAR Linux. It utilizes the logical LAN    */
13 /* option of the RS/6000 Platform Architecture to interface with virtual  */
14 /* ethernet NICs that are presented to the partition by the hypervisor.   */
15 /*									   */
16 /* Messages are passed between the VNIC driver and the VNIC server using  */
17 /* Command/Response Queues (CRQs) and sub CRQs (sCRQs). CRQs are used to  */
18 /* issue and receive commands that initiate communication with the server */
19 /* on driver initialization. Sub CRQs (sCRQs) are similar to CRQs, but    */
20 /* are used by the driver to notify the server that a packet is           */
21 /* ready for transmission or that a buffer has been added to receive a    */
22 /* packet. Subsequently, sCRQs are used by the server to notify the       */
23 /* driver that a packet transmission has been completed or that a packet  */
24 /* has been received and placed in a waiting buffer.                      */
25 /*                                                                        */
26 /* In lieu of a more conventional "on-the-fly" DMA mapping strategy in    */
27 /* which skbs are DMA mapped and immediately unmapped when the transmit   */
28 /* or receive has been completed, the VNIC driver is required to use      */
29 /* "long term mapping". This entails that large, continuous DMA mapped    */
30 /* buffers are allocated on driver initialization and these buffers are   */
31 /* then continuously reused to pass skbs to and from the VNIC server.     */
32 /*                                                                        */
33 /**************************************************************************/
34 
35 #include <linux/module.h>
36 #include <linux/moduleparam.h>
37 #include <linux/types.h>
38 #include <linux/errno.h>
39 #include <linux/completion.h>
40 #include <linux/ioport.h>
41 #include <linux/dma-mapping.h>
42 #include <linux/kernel.h>
43 #include <linux/netdevice.h>
44 #include <linux/etherdevice.h>
45 #include <linux/skbuff.h>
46 #include <linux/init.h>
47 #include <linux/delay.h>
48 #include <linux/mm.h>
49 #include <linux/ethtool.h>
50 #include <linux/proc_fs.h>
51 #include <linux/if_arp.h>
52 #include <linux/in.h>
53 #include <linux/ip.h>
54 #include <linux/ipv6.h>
55 #include <linux/irq.h>
56 #include <linux/irqdomain.h>
57 #include <linux/kthread.h>
58 #include <linux/seq_file.h>
59 #include <linux/interrupt.h>
60 #include <net/net_namespace.h>
61 #include <asm/hvcall.h>
62 #include <linux/atomic.h>
63 #include <asm/vio.h>
64 #include <asm/xive.h>
65 #include <asm/iommu.h>
66 #include <linux/uaccess.h>
67 #include <asm/firmware.h>
68 #include <linux/workqueue.h>
69 #include <linux/if_vlan.h>
70 #include <linux/utsname.h>
71 #include <linux/cpu.h>
72 
73 #include "ibmvnic.h"
74 
75 static const char ibmvnic_driver_name[] = "ibmvnic";
76 static const char ibmvnic_driver_string[] = "IBM System i/p Virtual NIC Driver";
77 
78 MODULE_AUTHOR("Santiago Leon");
79 MODULE_DESCRIPTION("IBM System i/p Virtual NIC Driver");
80 MODULE_LICENSE("GPL");
81 MODULE_VERSION(IBMVNIC_DRIVER_VERSION);
82 
83 static int ibmvnic_version = IBMVNIC_INITIAL_VERSION;
84 static void release_sub_crqs(struct ibmvnic_adapter *, bool);
85 static int ibmvnic_reset_crq(struct ibmvnic_adapter *);
86 static int ibmvnic_send_crq_init(struct ibmvnic_adapter *);
87 static int ibmvnic_reenable_crq_queue(struct ibmvnic_adapter *);
88 static int ibmvnic_send_crq(struct ibmvnic_adapter *, union ibmvnic_crq *);
89 static int send_subcrq_indirect(struct ibmvnic_adapter *, u64, u64, u64);
90 static irqreturn_t ibmvnic_interrupt_rx(int irq, void *instance);
91 static int enable_scrq_irq(struct ibmvnic_adapter *,
92 			   struct ibmvnic_sub_crq_queue *);
93 static int disable_scrq_irq(struct ibmvnic_adapter *,
94 			    struct ibmvnic_sub_crq_queue *);
95 static int pending_scrq(struct ibmvnic_adapter *,
96 			struct ibmvnic_sub_crq_queue *);
97 static union sub_crq *ibmvnic_next_scrq(struct ibmvnic_adapter *,
98 					struct ibmvnic_sub_crq_queue *);
99 static int ibmvnic_poll(struct napi_struct *napi, int data);
100 static int reset_sub_crq_queues(struct ibmvnic_adapter *adapter);
101 static inline void reinit_init_done(struct ibmvnic_adapter *adapter);
102 static void send_query_map(struct ibmvnic_adapter *adapter);
103 static int send_request_map(struct ibmvnic_adapter *, dma_addr_t, u32, u8);
104 static int send_request_unmap(struct ibmvnic_adapter *, u8);
105 static int send_login(struct ibmvnic_adapter *adapter);
106 static void send_query_cap(struct ibmvnic_adapter *adapter);
107 static int init_sub_crqs(struct ibmvnic_adapter *);
108 static int init_sub_crq_irqs(struct ibmvnic_adapter *adapter);
109 static int ibmvnic_reset_init(struct ibmvnic_adapter *, bool reset);
110 static void release_crq_queue(struct ibmvnic_adapter *);
111 static int __ibmvnic_set_mac(struct net_device *, u8 *);
112 static int init_crq_queue(struct ibmvnic_adapter *adapter);
113 static int send_query_phys_parms(struct ibmvnic_adapter *adapter);
114 static void ibmvnic_tx_scrq_clean_buffer(struct ibmvnic_adapter *adapter,
115 					 struct ibmvnic_sub_crq_queue *tx_scrq);
116 static void free_long_term_buff(struct ibmvnic_adapter *adapter,
117 				struct ibmvnic_long_term_buff *ltb);
118 static void ibmvnic_disable_irqs(struct ibmvnic_adapter *adapter);
119 static void flush_reset_queue(struct ibmvnic_adapter *adapter);
120 
121 struct ibmvnic_stat {
122 	char name[ETH_GSTRING_LEN];
123 	int offset;
124 };
125 
126 #define IBMVNIC_STAT_OFF(stat) (offsetof(struct ibmvnic_adapter, stats) + \
127 			     offsetof(struct ibmvnic_statistics, stat))
128 #define IBMVNIC_GET_STAT(a, off) (*((u64 *)(((unsigned long)(a)) + (off))))
129 
130 static const struct ibmvnic_stat ibmvnic_stats[] = {
131 	{"rx_packets", IBMVNIC_STAT_OFF(rx_packets)},
132 	{"rx_bytes", IBMVNIC_STAT_OFF(rx_bytes)},
133 	{"tx_packets", IBMVNIC_STAT_OFF(tx_packets)},
134 	{"tx_bytes", IBMVNIC_STAT_OFF(tx_bytes)},
135 	{"ucast_tx_packets", IBMVNIC_STAT_OFF(ucast_tx_packets)},
136 	{"ucast_rx_packets", IBMVNIC_STAT_OFF(ucast_rx_packets)},
137 	{"mcast_tx_packets", IBMVNIC_STAT_OFF(mcast_tx_packets)},
138 	{"mcast_rx_packets", IBMVNIC_STAT_OFF(mcast_rx_packets)},
139 	{"bcast_tx_packets", IBMVNIC_STAT_OFF(bcast_tx_packets)},
140 	{"bcast_rx_packets", IBMVNIC_STAT_OFF(bcast_rx_packets)},
141 	{"align_errors", IBMVNIC_STAT_OFF(align_errors)},
142 	{"fcs_errors", IBMVNIC_STAT_OFF(fcs_errors)},
143 	{"single_collision_frames", IBMVNIC_STAT_OFF(single_collision_frames)},
144 	{"multi_collision_frames", IBMVNIC_STAT_OFF(multi_collision_frames)},
145 	{"sqe_test_errors", IBMVNIC_STAT_OFF(sqe_test_errors)},
146 	{"deferred_tx", IBMVNIC_STAT_OFF(deferred_tx)},
147 	{"late_collisions", IBMVNIC_STAT_OFF(late_collisions)},
148 	{"excess_collisions", IBMVNIC_STAT_OFF(excess_collisions)},
149 	{"internal_mac_tx_errors", IBMVNIC_STAT_OFF(internal_mac_tx_errors)},
150 	{"carrier_sense", IBMVNIC_STAT_OFF(carrier_sense)},
151 	{"too_long_frames", IBMVNIC_STAT_OFF(too_long_frames)},
152 	{"internal_mac_rx_errors", IBMVNIC_STAT_OFF(internal_mac_rx_errors)},
153 };
154 
155 static int send_crq_init_complete(struct ibmvnic_adapter *adapter)
156 {
157 	union ibmvnic_crq crq;
158 
159 	memset(&crq, 0, sizeof(crq));
160 	crq.generic.first = IBMVNIC_CRQ_INIT_CMD;
161 	crq.generic.cmd = IBMVNIC_CRQ_INIT_COMPLETE;
162 
163 	return ibmvnic_send_crq(adapter, &crq);
164 }
165 
166 static int send_version_xchg(struct ibmvnic_adapter *adapter)
167 {
168 	union ibmvnic_crq crq;
169 
170 	memset(&crq, 0, sizeof(crq));
171 	crq.version_exchange.first = IBMVNIC_CRQ_CMD;
172 	crq.version_exchange.cmd = VERSION_EXCHANGE;
173 	crq.version_exchange.version = cpu_to_be16(ibmvnic_version);
174 
175 	return ibmvnic_send_crq(adapter, &crq);
176 }
177 
178 static void ibmvnic_clean_queue_affinity(struct ibmvnic_adapter *adapter,
179 					 struct ibmvnic_sub_crq_queue *queue)
180 {
181 	if (!(queue && queue->irq))
182 		return;
183 
184 	cpumask_clear(queue->affinity_mask);
185 
186 	if (irq_set_affinity_and_hint(queue->irq, NULL))
187 		netdev_warn(adapter->netdev,
188 			    "%s: Clear affinity failed, queue addr = %p, IRQ = %d\n",
189 			    __func__, queue, queue->irq);
190 }
191 
192 static void ibmvnic_clean_affinity(struct ibmvnic_adapter *adapter)
193 {
194 	struct ibmvnic_sub_crq_queue **rxqs;
195 	struct ibmvnic_sub_crq_queue **txqs;
196 	int num_rxqs, num_txqs;
197 	int i;
198 
199 	rxqs = adapter->rx_scrq;
200 	txqs = adapter->tx_scrq;
201 	num_txqs = adapter->num_active_tx_scrqs;
202 	num_rxqs = adapter->num_active_rx_scrqs;
203 
204 	netdev_dbg(adapter->netdev, "%s: Cleaning irq affinity hints", __func__);
205 	if (txqs) {
206 		for (i = 0; i < num_txqs; i++)
207 			ibmvnic_clean_queue_affinity(adapter, txqs[i]);
208 	}
209 	if (rxqs) {
210 		for (i = 0; i < num_rxqs; i++)
211 			ibmvnic_clean_queue_affinity(adapter, rxqs[i]);
212 	}
213 }
214 
215 static int ibmvnic_set_queue_affinity(struct ibmvnic_sub_crq_queue *queue,
216 				      unsigned int *cpu, int *stragglers,
217 				      int stride)
218 {
219 	cpumask_var_t mask;
220 	int i;
221 	int rc = 0;
222 
223 	if (!(queue && queue->irq))
224 		return rc;
225 
226 	/* cpumask_var_t is either a pointer or array, allocation works here */
227 	if (!zalloc_cpumask_var(&mask, GFP_KERNEL))
228 		return -ENOMEM;
229 
230 	/* while we have extra cpu give one extra to this irq */
231 	if (*stragglers) {
232 		stride++;
233 		(*stragglers)--;
234 	}
235 	/* atomic write is safer than writing bit by bit directly */
236 	for (i = 0; i < stride; i++) {
237 		cpumask_set_cpu(*cpu, mask);
238 		*cpu = cpumask_next_wrap(*cpu, cpu_online_mask,
239 					 nr_cpu_ids, false);
240 	}
241 	/* set queue affinity mask */
242 	cpumask_copy(queue->affinity_mask, mask);
243 	rc = irq_set_affinity_and_hint(queue->irq, queue->affinity_mask);
244 	free_cpumask_var(mask);
245 
246 	return rc;
247 }
248 
249 /* assumes cpu read lock is held */
250 static void ibmvnic_set_affinity(struct ibmvnic_adapter *adapter)
251 {
252 	struct ibmvnic_sub_crq_queue **rxqs = adapter->rx_scrq;
253 	struct ibmvnic_sub_crq_queue **txqs = adapter->tx_scrq;
254 	struct ibmvnic_sub_crq_queue *queue;
255 	int num_rxqs = adapter->num_active_rx_scrqs, i_rxqs = 0;
256 	int num_txqs = adapter->num_active_tx_scrqs, i_txqs = 0;
257 	int total_queues, stride, stragglers, i;
258 	unsigned int num_cpu, cpu;
259 	bool is_rx_queue;
260 	int rc = 0;
261 
262 	netdev_dbg(adapter->netdev, "%s: Setting irq affinity hints", __func__);
263 	if (!(adapter->rx_scrq && adapter->tx_scrq)) {
264 		netdev_warn(adapter->netdev,
265 			    "%s: Set affinity failed, queues not allocated\n",
266 			    __func__);
267 		return;
268 	}
269 
270 	total_queues = num_rxqs + num_txqs;
271 	num_cpu = num_online_cpus();
272 	/* number of cpu's assigned per irq */
273 	stride = max_t(int, num_cpu / total_queues, 1);
274 	/* number of leftover cpu's */
275 	stragglers = num_cpu >= total_queues ? num_cpu % total_queues : 0;
276 	/* next available cpu to assign irq to */
277 	cpu = cpumask_next(-1, cpu_online_mask);
278 
279 	for (i = 0; i < total_queues; i++) {
280 		is_rx_queue = false;
281 		/* balance core load by alternating rx and tx assignments
282 		 * ex: TX0 -> RX0 -> TX1 -> RX1 etc.
283 		 */
284 		if ((i % 2 == 1 && i_rxqs < num_rxqs) || i_txqs == num_txqs) {
285 			queue = rxqs[i_rxqs++];
286 			is_rx_queue = true;
287 		} else {
288 			queue = txqs[i_txqs++];
289 		}
290 
291 		rc = ibmvnic_set_queue_affinity(queue, &cpu, &stragglers,
292 						stride);
293 		if (rc)
294 			goto out;
295 
296 		if (!queue || is_rx_queue)
297 			continue;
298 
299 		rc = __netif_set_xps_queue(adapter->netdev,
300 					   cpumask_bits(queue->affinity_mask),
301 					   i_txqs - 1, XPS_CPUS);
302 		if (rc)
303 			netdev_warn(adapter->netdev, "%s: Set XPS on queue %d failed, rc = %d.\n",
304 				    __func__, i_txqs - 1, rc);
305 	}
306 
307 out:
308 	if (rc) {
309 		netdev_warn(adapter->netdev,
310 			    "%s: Set affinity failed, queue addr = %p, IRQ = %d, rc = %d.\n",
311 			    __func__, queue, queue->irq, rc);
312 		ibmvnic_clean_affinity(adapter);
313 	}
314 }
315 
316 static int ibmvnic_cpu_online(unsigned int cpu, struct hlist_node *node)
317 {
318 	struct ibmvnic_adapter *adapter;
319 
320 	adapter = hlist_entry_safe(node, struct ibmvnic_adapter, node);
321 	ibmvnic_set_affinity(adapter);
322 	return 0;
323 }
324 
325 static int ibmvnic_cpu_dead(unsigned int cpu, struct hlist_node *node)
326 {
327 	struct ibmvnic_adapter *adapter;
328 
329 	adapter = hlist_entry_safe(node, struct ibmvnic_adapter, node_dead);
330 	ibmvnic_set_affinity(adapter);
331 	return 0;
332 }
333 
334 static int ibmvnic_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
335 {
336 	struct ibmvnic_adapter *adapter;
337 
338 	adapter = hlist_entry_safe(node, struct ibmvnic_adapter, node);
339 	ibmvnic_clean_affinity(adapter);
340 	return 0;
341 }
342 
343 static enum cpuhp_state ibmvnic_online;
344 
345 static int ibmvnic_cpu_notif_add(struct ibmvnic_adapter *adapter)
346 {
347 	int ret;
348 
349 	ret = cpuhp_state_add_instance_nocalls(ibmvnic_online, &adapter->node);
350 	if (ret)
351 		return ret;
352 	ret = cpuhp_state_add_instance_nocalls(CPUHP_IBMVNIC_DEAD,
353 					       &adapter->node_dead);
354 	if (!ret)
355 		return ret;
356 	cpuhp_state_remove_instance_nocalls(ibmvnic_online, &adapter->node);
357 	return ret;
358 }
359 
360 static void ibmvnic_cpu_notif_remove(struct ibmvnic_adapter *adapter)
361 {
362 	cpuhp_state_remove_instance_nocalls(ibmvnic_online, &adapter->node);
363 	cpuhp_state_remove_instance_nocalls(CPUHP_IBMVNIC_DEAD,
364 					    &adapter->node_dead);
365 }
366 
367 static long h_reg_sub_crq(unsigned long unit_address, unsigned long token,
368 			  unsigned long length, unsigned long *number,
369 			  unsigned long *irq)
370 {
371 	unsigned long retbuf[PLPAR_HCALL_BUFSIZE];
372 	long rc;
373 
374 	rc = plpar_hcall(H_REG_SUB_CRQ, retbuf, unit_address, token, length);
375 	*number = retbuf[0];
376 	*irq = retbuf[1];
377 
378 	return rc;
379 }
380 
381 /**
382  * ibmvnic_wait_for_completion - Check device state and wait for completion
383  * @adapter: private device data
384  * @comp_done: completion structure to wait for
385  * @timeout: time to wait in milliseconds
386  *
387  * Wait for a completion signal or until the timeout limit is reached
388  * while checking that the device is still active.
389  */
390 static int ibmvnic_wait_for_completion(struct ibmvnic_adapter *adapter,
391 				       struct completion *comp_done,
392 				       unsigned long timeout)
393 {
394 	struct net_device *netdev;
395 	unsigned long div_timeout;
396 	u8 retry;
397 
398 	netdev = adapter->netdev;
399 	retry = 5;
400 	div_timeout = msecs_to_jiffies(timeout / retry);
401 	while (true) {
402 		if (!adapter->crq.active) {
403 			netdev_err(netdev, "Device down!\n");
404 			return -ENODEV;
405 		}
406 		if (!retry--)
407 			break;
408 		if (wait_for_completion_timeout(comp_done, div_timeout))
409 			return 0;
410 	}
411 	netdev_err(netdev, "Operation timed out.\n");
412 	return -ETIMEDOUT;
413 }
414 
415 /**
416  * reuse_ltb() - Check if a long term buffer can be reused
417  * @ltb:  The long term buffer to be checked
418  * @size: The size of the long term buffer.
419  *
420  * An LTB can be reused unless its size has changed.
421  *
422  * Return: Return true if the LTB can be reused, false otherwise.
423  */
424 static bool reuse_ltb(struct ibmvnic_long_term_buff *ltb, int size)
425 {
426 	return (ltb->buff && ltb->size == size);
427 }
428 
429 /**
430  * alloc_long_term_buff() - Allocate a long term buffer (LTB)
431  *
432  * @adapter: ibmvnic adapter associated to the LTB
433  * @ltb:     container object for the LTB
434  * @size:    size of the LTB
435  *
436  * Allocate an LTB of the specified size and notify VIOS.
437  *
438  * If the given @ltb already has the correct size, reuse it. Otherwise if
439  * its non-NULL, free it. Then allocate a new one of the correct size.
440  * Notify the VIOS either way since we may now be working with a new VIOS.
441  *
442  * Allocating larger chunks of memory during resets, specially LPM or under
443  * low memory situations can cause resets to fail/timeout and for LPAR to
444  * lose connectivity. So hold onto the LTB even if we fail to communicate
445  * with the VIOS and reuse it on next open. Free LTB when adapter is closed.
446  *
447  * Return: 0 if we were able to allocate the LTB and notify the VIOS and
448  *	   a negative value otherwise.
449  */
450 static int alloc_long_term_buff(struct ibmvnic_adapter *adapter,
451 				struct ibmvnic_long_term_buff *ltb, int size)
452 {
453 	struct device *dev = &adapter->vdev->dev;
454 	u64 prev = 0;
455 	int rc;
456 
457 	if (!reuse_ltb(ltb, size)) {
458 		dev_dbg(dev,
459 			"LTB size changed from 0x%llx to 0x%x, reallocating\n",
460 			 ltb->size, size);
461 		prev = ltb->size;
462 		free_long_term_buff(adapter, ltb);
463 	}
464 
465 	if (ltb->buff) {
466 		dev_dbg(dev, "Reusing LTB [map %d, size 0x%llx]\n",
467 			ltb->map_id, ltb->size);
468 	} else {
469 		ltb->buff = dma_alloc_coherent(dev, size, &ltb->addr,
470 					       GFP_KERNEL);
471 		if (!ltb->buff) {
472 			dev_err(dev, "Couldn't alloc long term buffer\n");
473 			return -ENOMEM;
474 		}
475 		ltb->size = size;
476 
477 		ltb->map_id = find_first_zero_bit(adapter->map_ids,
478 						  MAX_MAP_ID);
479 		bitmap_set(adapter->map_ids, ltb->map_id, 1);
480 
481 		dev_dbg(dev,
482 			"Allocated new LTB [map %d, size 0x%llx was 0x%llx]\n",
483 			 ltb->map_id, ltb->size, prev);
484 	}
485 
486 	/* Ensure ltb is zeroed - specially when reusing it. */
487 	memset(ltb->buff, 0, ltb->size);
488 
489 	mutex_lock(&adapter->fw_lock);
490 	adapter->fw_done_rc = 0;
491 	reinit_completion(&adapter->fw_done);
492 
493 	rc = send_request_map(adapter, ltb->addr, ltb->size, ltb->map_id);
494 	if (rc) {
495 		dev_err(dev, "send_request_map failed, rc = %d\n", rc);
496 		goto out;
497 	}
498 
499 	rc = ibmvnic_wait_for_completion(adapter, &adapter->fw_done, 10000);
500 	if (rc) {
501 		dev_err(dev, "LTB map request aborted or timed out, rc = %d\n",
502 			rc);
503 		goto out;
504 	}
505 
506 	if (adapter->fw_done_rc) {
507 		dev_err(dev, "Couldn't map LTB, rc = %d\n",
508 			adapter->fw_done_rc);
509 		rc = -EIO;
510 		goto out;
511 	}
512 	rc = 0;
513 out:
514 	/* don't free LTB on communication error - see function header */
515 	mutex_unlock(&adapter->fw_lock);
516 	return rc;
517 }
518 
519 static void free_long_term_buff(struct ibmvnic_adapter *adapter,
520 				struct ibmvnic_long_term_buff *ltb)
521 {
522 	struct device *dev = &adapter->vdev->dev;
523 
524 	if (!ltb->buff)
525 		return;
526 
527 	/* VIOS automatically unmaps the long term buffer at remote
528 	 * end for the following resets:
529 	 * FAILOVER, MOBILITY, TIMEOUT.
530 	 */
531 	if (adapter->reset_reason != VNIC_RESET_FAILOVER &&
532 	    adapter->reset_reason != VNIC_RESET_MOBILITY &&
533 	    adapter->reset_reason != VNIC_RESET_TIMEOUT)
534 		send_request_unmap(adapter, ltb->map_id);
535 
536 	dma_free_coherent(dev, ltb->size, ltb->buff, ltb->addr);
537 
538 	ltb->buff = NULL;
539 	/* mark this map_id free */
540 	bitmap_clear(adapter->map_ids, ltb->map_id, 1);
541 	ltb->map_id = 0;
542 }
543 
544 /**
545  * free_ltb_set - free the given set of long term buffers (LTBS)
546  * @adapter: The ibmvnic adapter containing this ltb set
547  * @ltb_set: The ltb_set to be freed
548  *
549  * Free the set of LTBs in the given set.
550  */
551 
552 static void free_ltb_set(struct ibmvnic_adapter *adapter,
553 			 struct ibmvnic_ltb_set *ltb_set)
554 {
555 	int i;
556 
557 	for (i = 0; i < ltb_set->num_ltbs; i++)
558 		free_long_term_buff(adapter, &ltb_set->ltbs[i]);
559 
560 	kfree(ltb_set->ltbs);
561 	ltb_set->ltbs = NULL;
562 	ltb_set->num_ltbs = 0;
563 }
564 
565 /**
566  * alloc_ltb_set() - Allocate a set of long term buffers (LTBs)
567  *
568  * @adapter: ibmvnic adapter associated to the LTB
569  * @ltb_set: container object for the set of LTBs
570  * @num_buffs: Number of buffers in the LTB
571  * @buff_size: Size of each buffer in the LTB
572  *
573  * Allocate a set of LTBs to accommodate @num_buffs buffers of @buff_size
574  * each. We currently cap size each LTB to IBMVNIC_ONE_LTB_SIZE. If the
575  * new set of LTBs have fewer LTBs than the old set, free the excess LTBs.
576  * If new set needs more than in old set, allocate the remaining ones.
577  * Try and reuse as many LTBs as possible and avoid reallocation.
578  *
579  * Any changes to this allocation strategy must be reflected in
580  * map_rxpool_buff_to_ltb() and map_txpool_buff_to_ltb().
581  */
582 static int alloc_ltb_set(struct ibmvnic_adapter *adapter,
583 			 struct ibmvnic_ltb_set *ltb_set, int num_buffs,
584 			 int buff_size)
585 {
586 	struct device *dev = &adapter->vdev->dev;
587 	struct ibmvnic_ltb_set old_set;
588 	struct ibmvnic_ltb_set new_set;
589 	int rem_size;
590 	int tot_size;		/* size of all ltbs */
591 	int ltb_size;		/* size of one ltb */
592 	int nltbs;
593 	int rc;
594 	int n;
595 	int i;
596 
597 	dev_dbg(dev, "%s() num_buffs %d, buff_size %d\n", __func__, num_buffs,
598 		buff_size);
599 
600 	ltb_size = rounddown(IBMVNIC_ONE_LTB_SIZE, buff_size);
601 	tot_size = num_buffs * buff_size;
602 
603 	if (ltb_size > tot_size)
604 		ltb_size = tot_size;
605 
606 	nltbs = tot_size / ltb_size;
607 	if (tot_size % ltb_size)
608 		nltbs++;
609 
610 	old_set = *ltb_set;
611 
612 	if (old_set.num_ltbs == nltbs) {
613 		new_set = old_set;
614 	} else {
615 		int tmp = nltbs * sizeof(struct ibmvnic_long_term_buff);
616 
617 		new_set.ltbs = kzalloc(tmp, GFP_KERNEL);
618 		if (!new_set.ltbs)
619 			return -ENOMEM;
620 
621 		new_set.num_ltbs = nltbs;
622 
623 		/* Free any excess ltbs in old set */
624 		for (i = new_set.num_ltbs; i < old_set.num_ltbs; i++)
625 			free_long_term_buff(adapter, &old_set.ltbs[i]);
626 
627 		/* Copy remaining ltbs to new set. All LTBs except the
628 		 * last one are of the same size. alloc_long_term_buff()
629 		 * will realloc if the size changes.
630 		 */
631 		n = min(old_set.num_ltbs, new_set.num_ltbs);
632 		for (i = 0; i < n; i++)
633 			new_set.ltbs[i] = old_set.ltbs[i];
634 
635 		/* Any additional ltbs in new set will have NULL ltbs for
636 		 * now and will be allocated in alloc_long_term_buff().
637 		 */
638 
639 		/* We no longer need the old_set so free it. Note that we
640 		 * may have reused some ltbs from old set and freed excess
641 		 * ltbs above. So we only need to free the container now
642 		 * not the LTBs themselves. (i.e. dont free_ltb_set()!)
643 		 */
644 		kfree(old_set.ltbs);
645 		old_set.ltbs = NULL;
646 		old_set.num_ltbs = 0;
647 
648 		/* Install the new set. If allocations fail below, we will
649 		 * retry later and know what size LTBs we need.
650 		 */
651 		*ltb_set = new_set;
652 	}
653 
654 	i = 0;
655 	rem_size = tot_size;
656 	while (rem_size) {
657 		if (ltb_size > rem_size)
658 			ltb_size = rem_size;
659 
660 		rem_size -= ltb_size;
661 
662 		rc = alloc_long_term_buff(adapter, &new_set.ltbs[i], ltb_size);
663 		if (rc)
664 			goto out;
665 		i++;
666 	}
667 
668 	WARN_ON(i != new_set.num_ltbs);
669 
670 	return 0;
671 out:
672 	/* We may have allocated one/more LTBs before failing and we
673 	 * want to try and reuse on next reset. So don't free ltb set.
674 	 */
675 	return rc;
676 }
677 
678 /**
679  * map_rxpool_buf_to_ltb - Map given rxpool buffer to offset in an LTB.
680  * @rxpool: The receive buffer pool containing buffer
681  * @bufidx: Index of buffer in rxpool
682  * @ltbp: (Output) pointer to the long term buffer containing the buffer
683  * @offset: (Output) offset of buffer in the LTB from @ltbp
684  *
685  * Map the given buffer identified by [rxpool, bufidx] to an LTB in the
686  * pool and its corresponding offset. Assume for now that each LTB is of
687  * different size but could possibly be optimized based on the allocation
688  * strategy in alloc_ltb_set().
689  */
690 static void map_rxpool_buf_to_ltb(struct ibmvnic_rx_pool *rxpool,
691 				  unsigned int bufidx,
692 				  struct ibmvnic_long_term_buff **ltbp,
693 				  unsigned int *offset)
694 {
695 	struct ibmvnic_long_term_buff *ltb;
696 	int nbufs;	/* # of buffers in one ltb */
697 	int i;
698 
699 	WARN_ON(bufidx >= rxpool->size);
700 
701 	for (i = 0; i < rxpool->ltb_set.num_ltbs; i++) {
702 		ltb = &rxpool->ltb_set.ltbs[i];
703 		nbufs = ltb->size / rxpool->buff_size;
704 		if (bufidx < nbufs)
705 			break;
706 		bufidx -= nbufs;
707 	}
708 
709 	*ltbp = ltb;
710 	*offset = bufidx * rxpool->buff_size;
711 }
712 
713 /**
714  * map_txpool_buf_to_ltb - Map given txpool buffer to offset in an LTB.
715  * @txpool: The transmit buffer pool containing buffer
716  * @bufidx: Index of buffer in txpool
717  * @ltbp: (Output) pointer to the long term buffer (LTB) containing the buffer
718  * @offset: (Output) offset of buffer in the LTB from @ltbp
719  *
720  * Map the given buffer identified by [txpool, bufidx] to an LTB in the
721  * pool and its corresponding offset.
722  */
723 static void map_txpool_buf_to_ltb(struct ibmvnic_tx_pool *txpool,
724 				  unsigned int bufidx,
725 				  struct ibmvnic_long_term_buff **ltbp,
726 				  unsigned int *offset)
727 {
728 	struct ibmvnic_long_term_buff *ltb;
729 	int nbufs;	/* # of buffers in one ltb */
730 	int i;
731 
732 	WARN_ON_ONCE(bufidx >= txpool->num_buffers);
733 
734 	for (i = 0; i < txpool->ltb_set.num_ltbs; i++) {
735 		ltb = &txpool->ltb_set.ltbs[i];
736 		nbufs = ltb->size / txpool->buf_size;
737 		if (bufidx < nbufs)
738 			break;
739 		bufidx -= nbufs;
740 	}
741 
742 	*ltbp = ltb;
743 	*offset = bufidx * txpool->buf_size;
744 }
745 
746 static void deactivate_rx_pools(struct ibmvnic_adapter *adapter)
747 {
748 	int i;
749 
750 	for (i = 0; i < adapter->num_active_rx_pools; i++)
751 		adapter->rx_pool[i].active = 0;
752 }
753 
754 static void replenish_rx_pool(struct ibmvnic_adapter *adapter,
755 			      struct ibmvnic_rx_pool *pool)
756 {
757 	int count = pool->size - atomic_read(&pool->available);
758 	u64 handle = adapter->rx_scrq[pool->index]->handle;
759 	struct device *dev = &adapter->vdev->dev;
760 	struct ibmvnic_ind_xmit_queue *ind_bufp;
761 	struct ibmvnic_sub_crq_queue *rx_scrq;
762 	struct ibmvnic_long_term_buff *ltb;
763 	union sub_crq *sub_crq;
764 	int buffers_added = 0;
765 	unsigned long lpar_rc;
766 	struct sk_buff *skb;
767 	unsigned int offset;
768 	dma_addr_t dma_addr;
769 	unsigned char *dst;
770 	int shift = 0;
771 	int bufidx;
772 	int i;
773 
774 	if (!pool->active)
775 		return;
776 
777 	rx_scrq = adapter->rx_scrq[pool->index];
778 	ind_bufp = &rx_scrq->ind_buf;
779 
780 	/* netdev_skb_alloc() could have failed after we saved a few skbs
781 	 * in the indir_buf and we would not have sent them to VIOS yet.
782 	 * To account for them, start the loop at ind_bufp->index rather
783 	 * than 0. If we pushed all the skbs to VIOS, ind_bufp->index will
784 	 * be 0.
785 	 */
786 	for (i = ind_bufp->index; i < count; ++i) {
787 		bufidx = pool->free_map[pool->next_free];
788 
789 		/* We maybe reusing the skb from earlier resets. Allocate
790 		 * only if necessary. But since the LTB may have changed
791 		 * during reset (see init_rx_pools()), update LTB below
792 		 * even if reusing skb.
793 		 */
794 		skb = pool->rx_buff[bufidx].skb;
795 		if (!skb) {
796 			skb = netdev_alloc_skb(adapter->netdev,
797 					       pool->buff_size);
798 			if (!skb) {
799 				dev_err(dev, "Couldn't replenish rx buff\n");
800 				adapter->replenish_no_mem++;
801 				break;
802 			}
803 		}
804 
805 		pool->free_map[pool->next_free] = IBMVNIC_INVALID_MAP;
806 		pool->next_free = (pool->next_free + 1) % pool->size;
807 
808 		/* Copy the skb to the long term mapped DMA buffer */
809 		map_rxpool_buf_to_ltb(pool, bufidx, &ltb, &offset);
810 		dst = ltb->buff + offset;
811 		memset(dst, 0, pool->buff_size);
812 		dma_addr = ltb->addr + offset;
813 
814 		/* add the skb to an rx_buff in the pool */
815 		pool->rx_buff[bufidx].data = dst;
816 		pool->rx_buff[bufidx].dma = dma_addr;
817 		pool->rx_buff[bufidx].skb = skb;
818 		pool->rx_buff[bufidx].pool_index = pool->index;
819 		pool->rx_buff[bufidx].size = pool->buff_size;
820 
821 		/* queue the rx_buff for the next send_subcrq_indirect */
822 		sub_crq = &ind_bufp->indir_arr[ind_bufp->index++];
823 		memset(sub_crq, 0, sizeof(*sub_crq));
824 		sub_crq->rx_add.first = IBMVNIC_CRQ_CMD;
825 		sub_crq->rx_add.correlator =
826 		    cpu_to_be64((u64)&pool->rx_buff[bufidx]);
827 		sub_crq->rx_add.ioba = cpu_to_be32(dma_addr);
828 		sub_crq->rx_add.map_id = ltb->map_id;
829 
830 		/* The length field of the sCRQ is defined to be 24 bits so the
831 		 * buffer size needs to be left shifted by a byte before it is
832 		 * converted to big endian to prevent the last byte from being
833 		 * truncated.
834 		 */
835 #ifdef __LITTLE_ENDIAN__
836 		shift = 8;
837 #endif
838 		sub_crq->rx_add.len = cpu_to_be32(pool->buff_size << shift);
839 
840 		/* if send_subcrq_indirect queue is full, flush to VIOS */
841 		if (ind_bufp->index == IBMVNIC_MAX_IND_DESCS ||
842 		    i == count - 1) {
843 			lpar_rc =
844 				send_subcrq_indirect(adapter, handle,
845 						     (u64)ind_bufp->indir_dma,
846 						     (u64)ind_bufp->index);
847 			if (lpar_rc != H_SUCCESS)
848 				goto failure;
849 			buffers_added += ind_bufp->index;
850 			adapter->replenish_add_buff_success += ind_bufp->index;
851 			ind_bufp->index = 0;
852 		}
853 	}
854 	atomic_add(buffers_added, &pool->available);
855 	return;
856 
857 failure:
858 	if (lpar_rc != H_PARAMETER && lpar_rc != H_CLOSED)
859 		dev_err_ratelimited(dev, "rx: replenish packet buffer failed\n");
860 	for (i = ind_bufp->index - 1; i >= 0; --i) {
861 		struct ibmvnic_rx_buff *rx_buff;
862 
863 		pool->next_free = pool->next_free == 0 ?
864 				  pool->size - 1 : pool->next_free - 1;
865 		sub_crq = &ind_bufp->indir_arr[i];
866 		rx_buff = (struct ibmvnic_rx_buff *)
867 				be64_to_cpu(sub_crq->rx_add.correlator);
868 		bufidx = (int)(rx_buff - pool->rx_buff);
869 		pool->free_map[pool->next_free] = bufidx;
870 		dev_kfree_skb_any(pool->rx_buff[bufidx].skb);
871 		pool->rx_buff[bufidx].skb = NULL;
872 	}
873 	adapter->replenish_add_buff_failure += ind_bufp->index;
874 	atomic_add(buffers_added, &pool->available);
875 	ind_bufp->index = 0;
876 	if (lpar_rc == H_CLOSED || adapter->failover_pending) {
877 		/* Disable buffer pool replenishment and report carrier off if
878 		 * queue is closed or pending failover.
879 		 * Firmware guarantees that a signal will be sent to the
880 		 * driver, triggering a reset.
881 		 */
882 		deactivate_rx_pools(adapter);
883 		netif_carrier_off(adapter->netdev);
884 	}
885 }
886 
887 static void replenish_pools(struct ibmvnic_adapter *adapter)
888 {
889 	int i;
890 
891 	adapter->replenish_task_cycles++;
892 	for (i = 0; i < adapter->num_active_rx_pools; i++) {
893 		if (adapter->rx_pool[i].active)
894 			replenish_rx_pool(adapter, &adapter->rx_pool[i]);
895 	}
896 
897 	netdev_dbg(adapter->netdev, "Replenished %d pools\n", i);
898 }
899 
900 static void release_stats_buffers(struct ibmvnic_adapter *adapter)
901 {
902 	kfree(adapter->tx_stats_buffers);
903 	kfree(adapter->rx_stats_buffers);
904 	adapter->tx_stats_buffers = NULL;
905 	adapter->rx_stats_buffers = NULL;
906 }
907 
908 static int init_stats_buffers(struct ibmvnic_adapter *adapter)
909 {
910 	adapter->tx_stats_buffers =
911 				kcalloc(IBMVNIC_MAX_QUEUES,
912 					sizeof(struct ibmvnic_tx_queue_stats),
913 					GFP_KERNEL);
914 	if (!adapter->tx_stats_buffers)
915 		return -ENOMEM;
916 
917 	adapter->rx_stats_buffers =
918 				kcalloc(IBMVNIC_MAX_QUEUES,
919 					sizeof(struct ibmvnic_rx_queue_stats),
920 					GFP_KERNEL);
921 	if (!adapter->rx_stats_buffers)
922 		return -ENOMEM;
923 
924 	return 0;
925 }
926 
927 static void release_stats_token(struct ibmvnic_adapter *adapter)
928 {
929 	struct device *dev = &adapter->vdev->dev;
930 
931 	if (!adapter->stats_token)
932 		return;
933 
934 	dma_unmap_single(dev, adapter->stats_token,
935 			 sizeof(struct ibmvnic_statistics),
936 			 DMA_FROM_DEVICE);
937 	adapter->stats_token = 0;
938 }
939 
940 static int init_stats_token(struct ibmvnic_adapter *adapter)
941 {
942 	struct device *dev = &adapter->vdev->dev;
943 	dma_addr_t stok;
944 	int rc;
945 
946 	stok = dma_map_single(dev, &adapter->stats,
947 			      sizeof(struct ibmvnic_statistics),
948 			      DMA_FROM_DEVICE);
949 	rc = dma_mapping_error(dev, stok);
950 	if (rc) {
951 		dev_err(dev, "Couldn't map stats buffer, rc = %d\n", rc);
952 		return rc;
953 	}
954 
955 	adapter->stats_token = stok;
956 	netdev_dbg(adapter->netdev, "Stats token initialized (%llx)\n", stok);
957 	return 0;
958 }
959 
960 /**
961  * release_rx_pools() - Release any rx pools attached to @adapter.
962  * @adapter: ibmvnic adapter
963  *
964  * Safe to call this multiple times - even if no pools are attached.
965  */
966 static void release_rx_pools(struct ibmvnic_adapter *adapter)
967 {
968 	struct ibmvnic_rx_pool *rx_pool;
969 	int i, j;
970 
971 	if (!adapter->rx_pool)
972 		return;
973 
974 	for (i = 0; i < adapter->num_active_rx_pools; i++) {
975 		rx_pool = &adapter->rx_pool[i];
976 
977 		netdev_dbg(adapter->netdev, "Releasing rx_pool[%d]\n", i);
978 
979 		kfree(rx_pool->free_map);
980 
981 		free_ltb_set(adapter, &rx_pool->ltb_set);
982 
983 		if (!rx_pool->rx_buff)
984 			continue;
985 
986 		for (j = 0; j < rx_pool->size; j++) {
987 			if (rx_pool->rx_buff[j].skb) {
988 				dev_kfree_skb_any(rx_pool->rx_buff[j].skb);
989 				rx_pool->rx_buff[j].skb = NULL;
990 			}
991 		}
992 
993 		kfree(rx_pool->rx_buff);
994 	}
995 
996 	kfree(adapter->rx_pool);
997 	adapter->rx_pool = NULL;
998 	adapter->num_active_rx_pools = 0;
999 	adapter->prev_rx_pool_size = 0;
1000 }
1001 
1002 /**
1003  * reuse_rx_pools() - Check if the existing rx pools can be reused.
1004  * @adapter: ibmvnic adapter
1005  *
1006  * Check if the existing rx pools in the adapter can be reused. The
1007  * pools can be reused if the pool parameters (number of pools,
1008  * number of buffers in the pool and size of each buffer) have not
1009  * changed.
1010  *
1011  * NOTE: This assumes that all pools have the same number of buffers
1012  *       which is the case currently. If that changes, we must fix this.
1013  *
1014  * Return: true if the rx pools can be reused, false otherwise.
1015  */
1016 static bool reuse_rx_pools(struct ibmvnic_adapter *adapter)
1017 {
1018 	u64 old_num_pools, new_num_pools;
1019 	u64 old_pool_size, new_pool_size;
1020 	u64 old_buff_size, new_buff_size;
1021 
1022 	if (!adapter->rx_pool)
1023 		return false;
1024 
1025 	old_num_pools = adapter->num_active_rx_pools;
1026 	new_num_pools = adapter->req_rx_queues;
1027 
1028 	old_pool_size = adapter->prev_rx_pool_size;
1029 	new_pool_size = adapter->req_rx_add_entries_per_subcrq;
1030 
1031 	old_buff_size = adapter->prev_rx_buf_sz;
1032 	new_buff_size = adapter->cur_rx_buf_sz;
1033 
1034 	if (old_buff_size != new_buff_size ||
1035 	    old_num_pools != new_num_pools ||
1036 	    old_pool_size != new_pool_size)
1037 		return false;
1038 
1039 	return true;
1040 }
1041 
1042 /**
1043  * init_rx_pools(): Initialize the set of receiver pools in the adapter.
1044  * @netdev: net device associated with the vnic interface
1045  *
1046  * Initialize the set of receiver pools in the ibmvnic adapter associated
1047  * with the net_device @netdev. If possible, reuse the existing rx pools.
1048  * Otherwise free any existing pools and  allocate a new set of pools
1049  * before initializing them.
1050  *
1051  * Return: 0 on success and negative value on error.
1052  */
1053 static int init_rx_pools(struct net_device *netdev)
1054 {
1055 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
1056 	struct device *dev = &adapter->vdev->dev;
1057 	struct ibmvnic_rx_pool *rx_pool;
1058 	u64 num_pools;
1059 	u64 pool_size;		/* # of buffers in one pool */
1060 	u64 buff_size;
1061 	int i, j, rc;
1062 
1063 	pool_size = adapter->req_rx_add_entries_per_subcrq;
1064 	num_pools = adapter->req_rx_queues;
1065 	buff_size = adapter->cur_rx_buf_sz;
1066 
1067 	if (reuse_rx_pools(adapter)) {
1068 		dev_dbg(dev, "Reusing rx pools\n");
1069 		goto update_ltb;
1070 	}
1071 
1072 	/* Allocate/populate the pools. */
1073 	release_rx_pools(adapter);
1074 
1075 	adapter->rx_pool = kcalloc(num_pools,
1076 				   sizeof(struct ibmvnic_rx_pool),
1077 				   GFP_KERNEL);
1078 	if (!adapter->rx_pool) {
1079 		dev_err(dev, "Failed to allocate rx pools\n");
1080 		return -ENOMEM;
1081 	}
1082 
1083 	/* Set num_active_rx_pools early. If we fail below after partial
1084 	 * allocation, release_rx_pools() will know how many to look for.
1085 	 */
1086 	adapter->num_active_rx_pools = num_pools;
1087 
1088 	for (i = 0; i < num_pools; i++) {
1089 		rx_pool = &adapter->rx_pool[i];
1090 
1091 		netdev_dbg(adapter->netdev,
1092 			   "Initializing rx_pool[%d], %lld buffs, %lld bytes each\n",
1093 			   i, pool_size, buff_size);
1094 
1095 		rx_pool->size = pool_size;
1096 		rx_pool->index = i;
1097 		rx_pool->buff_size = ALIGN(buff_size, L1_CACHE_BYTES);
1098 
1099 		rx_pool->free_map = kcalloc(rx_pool->size, sizeof(int),
1100 					    GFP_KERNEL);
1101 		if (!rx_pool->free_map) {
1102 			dev_err(dev, "Couldn't alloc free_map %d\n", i);
1103 			rc = -ENOMEM;
1104 			goto out_release;
1105 		}
1106 
1107 		rx_pool->rx_buff = kcalloc(rx_pool->size,
1108 					   sizeof(struct ibmvnic_rx_buff),
1109 					   GFP_KERNEL);
1110 		if (!rx_pool->rx_buff) {
1111 			dev_err(dev, "Couldn't alloc rx buffers\n");
1112 			rc = -ENOMEM;
1113 			goto out_release;
1114 		}
1115 	}
1116 
1117 	adapter->prev_rx_pool_size = pool_size;
1118 	adapter->prev_rx_buf_sz = adapter->cur_rx_buf_sz;
1119 
1120 update_ltb:
1121 	for (i = 0; i < num_pools; i++) {
1122 		rx_pool = &adapter->rx_pool[i];
1123 		dev_dbg(dev, "Updating LTB for rx pool %d [%d, %d]\n",
1124 			i, rx_pool->size, rx_pool->buff_size);
1125 
1126 		rc = alloc_ltb_set(adapter, &rx_pool->ltb_set,
1127 				   rx_pool->size, rx_pool->buff_size);
1128 		if (rc)
1129 			goto out;
1130 
1131 		for (j = 0; j < rx_pool->size; ++j) {
1132 			struct ibmvnic_rx_buff *rx_buff;
1133 
1134 			rx_pool->free_map[j] = j;
1135 
1136 			/* NOTE: Don't clear rx_buff->skb here - will leak
1137 			 * memory! replenish_rx_pool() will reuse skbs or
1138 			 * allocate as necessary.
1139 			 */
1140 			rx_buff = &rx_pool->rx_buff[j];
1141 			rx_buff->dma = 0;
1142 			rx_buff->data = 0;
1143 			rx_buff->size = 0;
1144 			rx_buff->pool_index = 0;
1145 		}
1146 
1147 		/* Mark pool "empty" so replenish_rx_pools() will
1148 		 * update the LTB info for each buffer
1149 		 */
1150 		atomic_set(&rx_pool->available, 0);
1151 		rx_pool->next_alloc = 0;
1152 		rx_pool->next_free = 0;
1153 		/* replenish_rx_pool() may have called deactivate_rx_pools()
1154 		 * on failover. Ensure pool is active now.
1155 		 */
1156 		rx_pool->active = 1;
1157 	}
1158 	return 0;
1159 out_release:
1160 	release_rx_pools(adapter);
1161 out:
1162 	/* We failed to allocate one or more LTBs or map them on the VIOS.
1163 	 * Hold onto the pools and any LTBs that we did allocate/map.
1164 	 */
1165 	return rc;
1166 }
1167 
1168 static void release_vpd_data(struct ibmvnic_adapter *adapter)
1169 {
1170 	if (!adapter->vpd)
1171 		return;
1172 
1173 	kfree(adapter->vpd->buff);
1174 	kfree(adapter->vpd);
1175 
1176 	adapter->vpd = NULL;
1177 }
1178 
1179 static void release_one_tx_pool(struct ibmvnic_adapter *adapter,
1180 				struct ibmvnic_tx_pool *tx_pool)
1181 {
1182 	kfree(tx_pool->tx_buff);
1183 	kfree(tx_pool->free_map);
1184 	free_ltb_set(adapter, &tx_pool->ltb_set);
1185 }
1186 
1187 /**
1188  * release_tx_pools() - Release any tx pools attached to @adapter.
1189  * @adapter: ibmvnic adapter
1190  *
1191  * Safe to call this multiple times - even if no pools are attached.
1192  */
1193 static void release_tx_pools(struct ibmvnic_adapter *adapter)
1194 {
1195 	int i;
1196 
1197 	/* init_tx_pools() ensures that ->tx_pool and ->tso_pool are
1198 	 * both NULL or both non-NULL. So we only need to check one.
1199 	 */
1200 	if (!adapter->tx_pool)
1201 		return;
1202 
1203 	for (i = 0; i < adapter->num_active_tx_pools; i++) {
1204 		release_one_tx_pool(adapter, &adapter->tx_pool[i]);
1205 		release_one_tx_pool(adapter, &adapter->tso_pool[i]);
1206 	}
1207 
1208 	kfree(adapter->tx_pool);
1209 	adapter->tx_pool = NULL;
1210 	kfree(adapter->tso_pool);
1211 	adapter->tso_pool = NULL;
1212 	adapter->num_active_tx_pools = 0;
1213 	adapter->prev_tx_pool_size = 0;
1214 }
1215 
1216 static int init_one_tx_pool(struct net_device *netdev,
1217 			    struct ibmvnic_tx_pool *tx_pool,
1218 			    int pool_size, int buf_size)
1219 {
1220 	int i;
1221 
1222 	tx_pool->tx_buff = kcalloc(pool_size,
1223 				   sizeof(struct ibmvnic_tx_buff),
1224 				   GFP_KERNEL);
1225 	if (!tx_pool->tx_buff)
1226 		return -ENOMEM;
1227 
1228 	tx_pool->free_map = kcalloc(pool_size, sizeof(int), GFP_KERNEL);
1229 	if (!tx_pool->free_map) {
1230 		kfree(tx_pool->tx_buff);
1231 		tx_pool->tx_buff = NULL;
1232 		return -ENOMEM;
1233 	}
1234 
1235 	for (i = 0; i < pool_size; i++)
1236 		tx_pool->free_map[i] = i;
1237 
1238 	tx_pool->consumer_index = 0;
1239 	tx_pool->producer_index = 0;
1240 	tx_pool->num_buffers = pool_size;
1241 	tx_pool->buf_size = buf_size;
1242 
1243 	return 0;
1244 }
1245 
1246 /**
1247  * reuse_tx_pools() - Check if the existing tx pools can be reused.
1248  * @adapter: ibmvnic adapter
1249  *
1250  * Check if the existing tx pools in the adapter can be reused. The
1251  * pools can be reused if the pool parameters (number of pools,
1252  * number of buffers in the pool and mtu) have not changed.
1253  *
1254  * NOTE: This assumes that all pools have the same number of buffers
1255  *       which is the case currently. If that changes, we must fix this.
1256  *
1257  * Return: true if the tx pools can be reused, false otherwise.
1258  */
1259 static bool reuse_tx_pools(struct ibmvnic_adapter *adapter)
1260 {
1261 	u64 old_num_pools, new_num_pools;
1262 	u64 old_pool_size, new_pool_size;
1263 	u64 old_mtu, new_mtu;
1264 
1265 	if (!adapter->tx_pool)
1266 		return false;
1267 
1268 	old_num_pools = adapter->num_active_tx_pools;
1269 	new_num_pools = adapter->num_active_tx_scrqs;
1270 	old_pool_size = adapter->prev_tx_pool_size;
1271 	new_pool_size = adapter->req_tx_entries_per_subcrq;
1272 	old_mtu = adapter->prev_mtu;
1273 	new_mtu = adapter->req_mtu;
1274 
1275 	if (old_mtu != new_mtu ||
1276 	    old_num_pools != new_num_pools ||
1277 	    old_pool_size != new_pool_size)
1278 		return false;
1279 
1280 	return true;
1281 }
1282 
1283 /**
1284  * init_tx_pools(): Initialize the set of transmit pools in the adapter.
1285  * @netdev: net device associated with the vnic interface
1286  *
1287  * Initialize the set of transmit pools in the ibmvnic adapter associated
1288  * with the net_device @netdev. If possible, reuse the existing tx pools.
1289  * Otherwise free any existing pools and  allocate a new set of pools
1290  * before initializing them.
1291  *
1292  * Return: 0 on success and negative value on error.
1293  */
1294 static int init_tx_pools(struct net_device *netdev)
1295 {
1296 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
1297 	struct device *dev = &adapter->vdev->dev;
1298 	int num_pools;
1299 	u64 pool_size;		/* # of buffers in pool */
1300 	u64 buff_size;
1301 	int i, j, rc;
1302 
1303 	num_pools = adapter->req_tx_queues;
1304 
1305 	/* We must notify the VIOS about the LTB on all resets - but we only
1306 	 * need to alloc/populate pools if either the number of buffers or
1307 	 * size of each buffer in the pool has changed.
1308 	 */
1309 	if (reuse_tx_pools(adapter)) {
1310 		netdev_dbg(netdev, "Reusing tx pools\n");
1311 		goto update_ltb;
1312 	}
1313 
1314 	/* Allocate/populate the pools. */
1315 	release_tx_pools(adapter);
1316 
1317 	pool_size = adapter->req_tx_entries_per_subcrq;
1318 	num_pools = adapter->num_active_tx_scrqs;
1319 
1320 	adapter->tx_pool = kcalloc(num_pools,
1321 				   sizeof(struct ibmvnic_tx_pool), GFP_KERNEL);
1322 	if (!adapter->tx_pool)
1323 		return -ENOMEM;
1324 
1325 	adapter->tso_pool = kcalloc(num_pools,
1326 				    sizeof(struct ibmvnic_tx_pool), GFP_KERNEL);
1327 	/* To simplify release_tx_pools() ensure that ->tx_pool and
1328 	 * ->tso_pool are either both NULL or both non-NULL.
1329 	 */
1330 	if (!adapter->tso_pool) {
1331 		kfree(adapter->tx_pool);
1332 		adapter->tx_pool = NULL;
1333 		return -ENOMEM;
1334 	}
1335 
1336 	/* Set num_active_tx_pools early. If we fail below after partial
1337 	 * allocation, release_tx_pools() will know how many to look for.
1338 	 */
1339 	adapter->num_active_tx_pools = num_pools;
1340 
1341 	buff_size = adapter->req_mtu + VLAN_HLEN;
1342 	buff_size = ALIGN(buff_size, L1_CACHE_BYTES);
1343 
1344 	for (i = 0; i < num_pools; i++) {
1345 		dev_dbg(dev, "Init tx pool %d [%llu, %llu]\n",
1346 			i, adapter->req_tx_entries_per_subcrq, buff_size);
1347 
1348 		rc = init_one_tx_pool(netdev, &adapter->tx_pool[i],
1349 				      pool_size, buff_size);
1350 		if (rc)
1351 			goto out_release;
1352 
1353 		rc = init_one_tx_pool(netdev, &adapter->tso_pool[i],
1354 				      IBMVNIC_TSO_BUFS,
1355 				      IBMVNIC_TSO_BUF_SZ);
1356 		if (rc)
1357 			goto out_release;
1358 	}
1359 
1360 	adapter->prev_tx_pool_size = pool_size;
1361 	adapter->prev_mtu = adapter->req_mtu;
1362 
1363 update_ltb:
1364 	/* NOTE: All tx_pools have the same number of buffers (which is
1365 	 *       same as pool_size). All tso_pools have IBMVNIC_TSO_BUFS
1366 	 *       buffers (see calls init_one_tx_pool() for these).
1367 	 *       For consistency, we use tx_pool->num_buffers and
1368 	 *       tso_pool->num_buffers below.
1369 	 */
1370 	rc = -1;
1371 	for (i = 0; i < num_pools; i++) {
1372 		struct ibmvnic_tx_pool *tso_pool;
1373 		struct ibmvnic_tx_pool *tx_pool;
1374 
1375 		tx_pool = &adapter->tx_pool[i];
1376 
1377 		dev_dbg(dev, "Updating LTB for tx pool %d [%d, %d]\n",
1378 			i, tx_pool->num_buffers, tx_pool->buf_size);
1379 
1380 		rc = alloc_ltb_set(adapter, &tx_pool->ltb_set,
1381 				   tx_pool->num_buffers, tx_pool->buf_size);
1382 		if (rc)
1383 			goto out;
1384 
1385 		tx_pool->consumer_index = 0;
1386 		tx_pool->producer_index = 0;
1387 
1388 		for (j = 0; j < tx_pool->num_buffers; j++)
1389 			tx_pool->free_map[j] = j;
1390 
1391 		tso_pool = &adapter->tso_pool[i];
1392 
1393 		dev_dbg(dev, "Updating LTB for tso pool %d [%d, %d]\n",
1394 			i, tso_pool->num_buffers, tso_pool->buf_size);
1395 
1396 		rc = alloc_ltb_set(adapter, &tso_pool->ltb_set,
1397 				   tso_pool->num_buffers, tso_pool->buf_size);
1398 		if (rc)
1399 			goto out;
1400 
1401 		tso_pool->consumer_index = 0;
1402 		tso_pool->producer_index = 0;
1403 
1404 		for (j = 0; j < tso_pool->num_buffers; j++)
1405 			tso_pool->free_map[j] = j;
1406 	}
1407 
1408 	return 0;
1409 out_release:
1410 	release_tx_pools(adapter);
1411 out:
1412 	/* We failed to allocate one or more LTBs or map them on the VIOS.
1413 	 * Hold onto the pools and any LTBs that we did allocate/map.
1414 	 */
1415 	return rc;
1416 }
1417 
1418 static void ibmvnic_napi_enable(struct ibmvnic_adapter *adapter)
1419 {
1420 	int i;
1421 
1422 	if (adapter->napi_enabled)
1423 		return;
1424 
1425 	for (i = 0; i < adapter->req_rx_queues; i++)
1426 		napi_enable(&adapter->napi[i]);
1427 
1428 	adapter->napi_enabled = true;
1429 }
1430 
1431 static void ibmvnic_napi_disable(struct ibmvnic_adapter *adapter)
1432 {
1433 	int i;
1434 
1435 	if (!adapter->napi_enabled)
1436 		return;
1437 
1438 	for (i = 0; i < adapter->req_rx_queues; i++) {
1439 		netdev_dbg(adapter->netdev, "Disabling napi[%d]\n", i);
1440 		napi_disable(&adapter->napi[i]);
1441 	}
1442 
1443 	adapter->napi_enabled = false;
1444 }
1445 
1446 static int init_napi(struct ibmvnic_adapter *adapter)
1447 {
1448 	int i;
1449 
1450 	adapter->napi = kcalloc(adapter->req_rx_queues,
1451 				sizeof(struct napi_struct), GFP_KERNEL);
1452 	if (!adapter->napi)
1453 		return -ENOMEM;
1454 
1455 	for (i = 0; i < adapter->req_rx_queues; i++) {
1456 		netdev_dbg(adapter->netdev, "Adding napi[%d]\n", i);
1457 		netif_napi_add(adapter->netdev, &adapter->napi[i],
1458 			       ibmvnic_poll);
1459 	}
1460 
1461 	adapter->num_active_rx_napi = adapter->req_rx_queues;
1462 	return 0;
1463 }
1464 
1465 static void release_napi(struct ibmvnic_adapter *adapter)
1466 {
1467 	int i;
1468 
1469 	if (!adapter->napi)
1470 		return;
1471 
1472 	for (i = 0; i < adapter->num_active_rx_napi; i++) {
1473 		netdev_dbg(adapter->netdev, "Releasing napi[%d]\n", i);
1474 		netif_napi_del(&adapter->napi[i]);
1475 	}
1476 
1477 	kfree(adapter->napi);
1478 	adapter->napi = NULL;
1479 	adapter->num_active_rx_napi = 0;
1480 	adapter->napi_enabled = false;
1481 }
1482 
1483 static const char *adapter_state_to_string(enum vnic_state state)
1484 {
1485 	switch (state) {
1486 	case VNIC_PROBING:
1487 		return "PROBING";
1488 	case VNIC_PROBED:
1489 		return "PROBED";
1490 	case VNIC_OPENING:
1491 		return "OPENING";
1492 	case VNIC_OPEN:
1493 		return "OPEN";
1494 	case VNIC_CLOSING:
1495 		return "CLOSING";
1496 	case VNIC_CLOSED:
1497 		return "CLOSED";
1498 	case VNIC_REMOVING:
1499 		return "REMOVING";
1500 	case VNIC_REMOVED:
1501 		return "REMOVED";
1502 	case VNIC_DOWN:
1503 		return "DOWN";
1504 	}
1505 	return "UNKNOWN";
1506 }
1507 
1508 static int ibmvnic_login(struct net_device *netdev)
1509 {
1510 	unsigned long flags, timeout = msecs_to_jiffies(20000);
1511 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
1512 	int retry_count = 0;
1513 	int retries = 10;
1514 	bool retry;
1515 	int rc;
1516 
1517 	do {
1518 		retry = false;
1519 		if (retry_count > retries) {
1520 			netdev_warn(netdev, "Login attempts exceeded\n");
1521 			return -EACCES;
1522 		}
1523 
1524 		adapter->init_done_rc = 0;
1525 		reinit_completion(&adapter->init_done);
1526 		rc = send_login(adapter);
1527 		if (rc)
1528 			return rc;
1529 
1530 		if (!wait_for_completion_timeout(&adapter->init_done,
1531 						 timeout)) {
1532 			netdev_warn(netdev, "Login timed out\n");
1533 			adapter->login_pending = false;
1534 			goto partial_reset;
1535 		}
1536 
1537 		if (adapter->init_done_rc == ABORTED) {
1538 			netdev_warn(netdev, "Login aborted, retrying...\n");
1539 			retry = true;
1540 			adapter->init_done_rc = 0;
1541 			retry_count++;
1542 			/* FW or device may be busy, so
1543 			 * wait a bit before retrying login
1544 			 */
1545 			msleep(500);
1546 		} else if (adapter->init_done_rc == PARTIALSUCCESS) {
1547 			retry_count++;
1548 			release_sub_crqs(adapter, 1);
1549 
1550 			retry = true;
1551 			netdev_dbg(netdev,
1552 				   "Received partial success, retrying...\n");
1553 			adapter->init_done_rc = 0;
1554 			reinit_completion(&adapter->init_done);
1555 			send_query_cap(adapter);
1556 			if (!wait_for_completion_timeout(&adapter->init_done,
1557 							 timeout)) {
1558 				netdev_warn(netdev,
1559 					    "Capabilities query timed out\n");
1560 				return -ETIMEDOUT;
1561 			}
1562 
1563 			rc = init_sub_crqs(adapter);
1564 			if (rc) {
1565 				netdev_warn(netdev,
1566 					    "SCRQ initialization failed\n");
1567 				return rc;
1568 			}
1569 
1570 			rc = init_sub_crq_irqs(adapter);
1571 			if (rc) {
1572 				netdev_warn(netdev,
1573 					    "SCRQ irq initialization failed\n");
1574 				return rc;
1575 			}
1576 		/* Default/timeout error handling, reset and start fresh */
1577 		} else if (adapter->init_done_rc) {
1578 			netdev_warn(netdev, "Adapter login failed, init_done_rc = %d\n",
1579 				    adapter->init_done_rc);
1580 
1581 partial_reset:
1582 			/* adapter login failed, so free any CRQs or sub-CRQs
1583 			 * and register again before attempting to login again.
1584 			 * If we don't do this then the VIOS may think that
1585 			 * we are already logged in and reject any subsequent
1586 			 * attempts
1587 			 */
1588 			netdev_warn(netdev,
1589 				    "Freeing and re-registering CRQs before attempting to login again\n");
1590 			retry = true;
1591 			adapter->init_done_rc = 0;
1592 			release_sub_crqs(adapter, true);
1593 			/* Much of this is similar logic as ibmvnic_probe(),
1594 			 * we are essentially re-initializing communication
1595 			 * with the server. We really should not run any
1596 			 * resets/failovers here because this is already a form
1597 			 * of reset and we do not want parallel resets occurring
1598 			 */
1599 			do {
1600 				reinit_init_done(adapter);
1601 				/* Clear any failovers we got in the previous
1602 				 * pass since we are re-initializing the CRQ
1603 				 */
1604 				adapter->failover_pending = false;
1605 				release_crq_queue(adapter);
1606 				/* If we don't sleep here then we risk an
1607 				 * unnecessary failover event from the VIOS.
1608 				 * This is a known VIOS issue caused by a vnic
1609 				 * device freeing and registering a CRQ too
1610 				 * quickly.
1611 				 */
1612 				msleep(1500);
1613 				/* Avoid any resets, since we are currently
1614 				 * resetting.
1615 				 */
1616 				spin_lock_irqsave(&adapter->rwi_lock, flags);
1617 				flush_reset_queue(adapter);
1618 				spin_unlock_irqrestore(&adapter->rwi_lock,
1619 						       flags);
1620 
1621 				rc = init_crq_queue(adapter);
1622 				if (rc) {
1623 					netdev_err(netdev, "login recovery: init CRQ failed %d\n",
1624 						   rc);
1625 					return -EIO;
1626 				}
1627 
1628 				rc = ibmvnic_reset_init(adapter, false);
1629 				if (rc)
1630 					netdev_err(netdev, "login recovery: Reset init failed %d\n",
1631 						   rc);
1632 				/* IBMVNIC_CRQ_INIT will return EAGAIN if it
1633 				 * fails, since ibmvnic_reset_init will free
1634 				 * irq's in failure, we won't be able to receive
1635 				 * new CRQs so we need to keep trying. probe()
1636 				 * handles this similarly.
1637 				 */
1638 			} while (rc == -EAGAIN && retry_count++ < retries);
1639 		}
1640 	} while (retry);
1641 
1642 	__ibmvnic_set_mac(netdev, adapter->mac_addr);
1643 
1644 	netdev_dbg(netdev, "[S:%s] Login succeeded\n", adapter_state_to_string(adapter->state));
1645 	return 0;
1646 }
1647 
1648 static void release_login_buffer(struct ibmvnic_adapter *adapter)
1649 {
1650 	if (!adapter->login_buf)
1651 		return;
1652 
1653 	dma_unmap_single(&adapter->vdev->dev, adapter->login_buf_token,
1654 			 adapter->login_buf_sz, DMA_TO_DEVICE);
1655 	kfree(adapter->login_buf);
1656 	adapter->login_buf = NULL;
1657 }
1658 
1659 static void release_login_rsp_buffer(struct ibmvnic_adapter *adapter)
1660 {
1661 	if (!adapter->login_rsp_buf)
1662 		return;
1663 
1664 	dma_unmap_single(&adapter->vdev->dev, adapter->login_rsp_buf_token,
1665 			 adapter->login_rsp_buf_sz, DMA_FROM_DEVICE);
1666 	kfree(adapter->login_rsp_buf);
1667 	adapter->login_rsp_buf = NULL;
1668 }
1669 
1670 static void release_resources(struct ibmvnic_adapter *adapter)
1671 {
1672 	release_vpd_data(adapter);
1673 
1674 	release_napi(adapter);
1675 	release_login_buffer(adapter);
1676 	release_login_rsp_buffer(adapter);
1677 }
1678 
1679 static int set_link_state(struct ibmvnic_adapter *adapter, u8 link_state)
1680 {
1681 	struct net_device *netdev = adapter->netdev;
1682 	unsigned long timeout = msecs_to_jiffies(20000);
1683 	union ibmvnic_crq crq;
1684 	bool resend;
1685 	int rc;
1686 
1687 	netdev_dbg(netdev, "setting link state %d\n", link_state);
1688 
1689 	memset(&crq, 0, sizeof(crq));
1690 	crq.logical_link_state.first = IBMVNIC_CRQ_CMD;
1691 	crq.logical_link_state.cmd = LOGICAL_LINK_STATE;
1692 	crq.logical_link_state.link_state = link_state;
1693 
1694 	do {
1695 		resend = false;
1696 
1697 		reinit_completion(&adapter->init_done);
1698 		rc = ibmvnic_send_crq(adapter, &crq);
1699 		if (rc) {
1700 			netdev_err(netdev, "Failed to set link state\n");
1701 			return rc;
1702 		}
1703 
1704 		if (!wait_for_completion_timeout(&adapter->init_done,
1705 						 timeout)) {
1706 			netdev_err(netdev, "timeout setting link state\n");
1707 			return -ETIMEDOUT;
1708 		}
1709 
1710 		if (adapter->init_done_rc == PARTIALSUCCESS) {
1711 			/* Partuial success, delay and re-send */
1712 			mdelay(1000);
1713 			resend = true;
1714 		} else if (adapter->init_done_rc) {
1715 			netdev_warn(netdev, "Unable to set link state, rc=%d\n",
1716 				    adapter->init_done_rc);
1717 			return adapter->init_done_rc;
1718 		}
1719 	} while (resend);
1720 
1721 	return 0;
1722 }
1723 
1724 static int set_real_num_queues(struct net_device *netdev)
1725 {
1726 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
1727 	int rc;
1728 
1729 	netdev_dbg(netdev, "Setting real tx/rx queues (%llx/%llx)\n",
1730 		   adapter->req_tx_queues, adapter->req_rx_queues);
1731 
1732 	rc = netif_set_real_num_tx_queues(netdev, adapter->req_tx_queues);
1733 	if (rc) {
1734 		netdev_err(netdev, "failed to set the number of tx queues\n");
1735 		return rc;
1736 	}
1737 
1738 	rc = netif_set_real_num_rx_queues(netdev, adapter->req_rx_queues);
1739 	if (rc)
1740 		netdev_err(netdev, "failed to set the number of rx queues\n");
1741 
1742 	return rc;
1743 }
1744 
1745 static int ibmvnic_get_vpd(struct ibmvnic_adapter *adapter)
1746 {
1747 	struct device *dev = &adapter->vdev->dev;
1748 	union ibmvnic_crq crq;
1749 	int len = 0;
1750 	int rc;
1751 
1752 	if (adapter->vpd->buff)
1753 		len = adapter->vpd->len;
1754 
1755 	mutex_lock(&adapter->fw_lock);
1756 	adapter->fw_done_rc = 0;
1757 	reinit_completion(&adapter->fw_done);
1758 
1759 	crq.get_vpd_size.first = IBMVNIC_CRQ_CMD;
1760 	crq.get_vpd_size.cmd = GET_VPD_SIZE;
1761 	rc = ibmvnic_send_crq(adapter, &crq);
1762 	if (rc) {
1763 		mutex_unlock(&adapter->fw_lock);
1764 		return rc;
1765 	}
1766 
1767 	rc = ibmvnic_wait_for_completion(adapter, &adapter->fw_done, 10000);
1768 	if (rc) {
1769 		dev_err(dev, "Could not retrieve VPD size, rc = %d\n", rc);
1770 		mutex_unlock(&adapter->fw_lock);
1771 		return rc;
1772 	}
1773 	mutex_unlock(&adapter->fw_lock);
1774 
1775 	if (!adapter->vpd->len)
1776 		return -ENODATA;
1777 
1778 	if (!adapter->vpd->buff)
1779 		adapter->vpd->buff = kzalloc(adapter->vpd->len, GFP_KERNEL);
1780 	else if (adapter->vpd->len != len)
1781 		adapter->vpd->buff =
1782 			krealloc(adapter->vpd->buff,
1783 				 adapter->vpd->len, GFP_KERNEL);
1784 
1785 	if (!adapter->vpd->buff) {
1786 		dev_err(dev, "Could allocate VPD buffer\n");
1787 		return -ENOMEM;
1788 	}
1789 
1790 	adapter->vpd->dma_addr =
1791 		dma_map_single(dev, adapter->vpd->buff, adapter->vpd->len,
1792 			       DMA_FROM_DEVICE);
1793 	if (dma_mapping_error(dev, adapter->vpd->dma_addr)) {
1794 		dev_err(dev, "Could not map VPD buffer\n");
1795 		kfree(adapter->vpd->buff);
1796 		adapter->vpd->buff = NULL;
1797 		return -ENOMEM;
1798 	}
1799 
1800 	mutex_lock(&adapter->fw_lock);
1801 	adapter->fw_done_rc = 0;
1802 	reinit_completion(&adapter->fw_done);
1803 
1804 	crq.get_vpd.first = IBMVNIC_CRQ_CMD;
1805 	crq.get_vpd.cmd = GET_VPD;
1806 	crq.get_vpd.ioba = cpu_to_be32(adapter->vpd->dma_addr);
1807 	crq.get_vpd.len = cpu_to_be32((u32)adapter->vpd->len);
1808 	rc = ibmvnic_send_crq(adapter, &crq);
1809 	if (rc) {
1810 		kfree(adapter->vpd->buff);
1811 		adapter->vpd->buff = NULL;
1812 		mutex_unlock(&adapter->fw_lock);
1813 		return rc;
1814 	}
1815 
1816 	rc = ibmvnic_wait_for_completion(adapter, &adapter->fw_done, 10000);
1817 	if (rc) {
1818 		dev_err(dev, "Unable to retrieve VPD, rc = %d\n", rc);
1819 		kfree(adapter->vpd->buff);
1820 		adapter->vpd->buff = NULL;
1821 		mutex_unlock(&adapter->fw_lock);
1822 		return rc;
1823 	}
1824 
1825 	mutex_unlock(&adapter->fw_lock);
1826 	return 0;
1827 }
1828 
1829 static int init_resources(struct ibmvnic_adapter *adapter)
1830 {
1831 	struct net_device *netdev = adapter->netdev;
1832 	int rc;
1833 
1834 	rc = set_real_num_queues(netdev);
1835 	if (rc)
1836 		return rc;
1837 
1838 	adapter->vpd = kzalloc(sizeof(*adapter->vpd), GFP_KERNEL);
1839 	if (!adapter->vpd)
1840 		return -ENOMEM;
1841 
1842 	/* Vital Product Data (VPD) */
1843 	rc = ibmvnic_get_vpd(adapter);
1844 	if (rc) {
1845 		netdev_err(netdev, "failed to initialize Vital Product Data (VPD)\n");
1846 		return rc;
1847 	}
1848 
1849 	rc = init_napi(adapter);
1850 	if (rc)
1851 		return rc;
1852 
1853 	send_query_map(adapter);
1854 
1855 	rc = init_rx_pools(netdev);
1856 	if (rc)
1857 		return rc;
1858 
1859 	rc = init_tx_pools(netdev);
1860 	return rc;
1861 }
1862 
1863 static int __ibmvnic_open(struct net_device *netdev)
1864 {
1865 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
1866 	enum vnic_state prev_state = adapter->state;
1867 	int i, rc;
1868 
1869 	adapter->state = VNIC_OPENING;
1870 	replenish_pools(adapter);
1871 	ibmvnic_napi_enable(adapter);
1872 
1873 	/* We're ready to receive frames, enable the sub-crq interrupts and
1874 	 * set the logical link state to up
1875 	 */
1876 	for (i = 0; i < adapter->req_rx_queues; i++) {
1877 		netdev_dbg(netdev, "Enabling rx_scrq[%d] irq\n", i);
1878 		if (prev_state == VNIC_CLOSED)
1879 			enable_irq(adapter->rx_scrq[i]->irq);
1880 		enable_scrq_irq(adapter, adapter->rx_scrq[i]);
1881 	}
1882 
1883 	for (i = 0; i < adapter->req_tx_queues; i++) {
1884 		netdev_dbg(netdev, "Enabling tx_scrq[%d] irq\n", i);
1885 		if (prev_state == VNIC_CLOSED)
1886 			enable_irq(adapter->tx_scrq[i]->irq);
1887 		enable_scrq_irq(adapter, adapter->tx_scrq[i]);
1888 		/* netdev_tx_reset_queue will reset dql stats. During NON_FATAL
1889 		 * resets, don't reset the stats because there could be batched
1890 		 * skb's waiting to be sent. If we reset dql stats, we risk
1891 		 * num_completed being greater than num_queued. This will cause
1892 		 * a BUG_ON in dql_completed().
1893 		 */
1894 		if (adapter->reset_reason != VNIC_RESET_NON_FATAL)
1895 			netdev_tx_reset_queue(netdev_get_tx_queue(netdev, i));
1896 	}
1897 
1898 	rc = set_link_state(adapter, IBMVNIC_LOGICAL_LNK_UP);
1899 	if (rc) {
1900 		ibmvnic_napi_disable(adapter);
1901 		ibmvnic_disable_irqs(adapter);
1902 		return rc;
1903 	}
1904 
1905 	adapter->tx_queues_active = true;
1906 
1907 	/* Since queues were stopped until now, there shouldn't be any
1908 	 * one in ibmvnic_complete_tx() or ibmvnic_xmit() so maybe we
1909 	 * don't need the synchronize_rcu()? Leaving it for consistency
1910 	 * with setting ->tx_queues_active = false.
1911 	 */
1912 	synchronize_rcu();
1913 
1914 	netif_tx_start_all_queues(netdev);
1915 
1916 	if (prev_state == VNIC_CLOSED) {
1917 		for (i = 0; i < adapter->req_rx_queues; i++)
1918 			napi_schedule(&adapter->napi[i]);
1919 	}
1920 
1921 	adapter->state = VNIC_OPEN;
1922 	return rc;
1923 }
1924 
1925 static int ibmvnic_open(struct net_device *netdev)
1926 {
1927 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
1928 	int rc;
1929 
1930 	ASSERT_RTNL();
1931 
1932 	/* If device failover is pending or we are about to reset, just set
1933 	 * device state and return. Device operation will be handled by reset
1934 	 * routine.
1935 	 *
1936 	 * It should be safe to overwrite the adapter->state here. Since
1937 	 * we hold the rtnl, either the reset has not actually started or
1938 	 * the rtnl got dropped during the set_link_state() in do_reset().
1939 	 * In the former case, no one else is changing the state (again we
1940 	 * have the rtnl) and in the latter case, do_reset() will detect and
1941 	 * honor our setting below.
1942 	 */
1943 	if (adapter->failover_pending || (test_bit(0, &adapter->resetting))) {
1944 		netdev_dbg(netdev, "[S:%s FOP:%d] Resetting, deferring open\n",
1945 			   adapter_state_to_string(adapter->state),
1946 			   adapter->failover_pending);
1947 		adapter->state = VNIC_OPEN;
1948 		rc = 0;
1949 		goto out;
1950 	}
1951 
1952 	if (adapter->state != VNIC_CLOSED) {
1953 		rc = ibmvnic_login(netdev);
1954 		if (rc)
1955 			goto out;
1956 
1957 		rc = init_resources(adapter);
1958 		if (rc) {
1959 			netdev_err(netdev, "failed to initialize resources\n");
1960 			goto out;
1961 		}
1962 	}
1963 
1964 	rc = __ibmvnic_open(netdev);
1965 
1966 out:
1967 	/* If open failed and there is a pending failover or in-progress reset,
1968 	 * set device state and return. Device operation will be handled by
1969 	 * reset routine. See also comments above regarding rtnl.
1970 	 */
1971 	if (rc &&
1972 	    (adapter->failover_pending || (test_bit(0, &adapter->resetting)))) {
1973 		adapter->state = VNIC_OPEN;
1974 		rc = 0;
1975 	}
1976 
1977 	if (rc) {
1978 		release_resources(adapter);
1979 		release_rx_pools(adapter);
1980 		release_tx_pools(adapter);
1981 	}
1982 
1983 	return rc;
1984 }
1985 
1986 static void clean_rx_pools(struct ibmvnic_adapter *adapter)
1987 {
1988 	struct ibmvnic_rx_pool *rx_pool;
1989 	struct ibmvnic_rx_buff *rx_buff;
1990 	u64 rx_entries;
1991 	int rx_scrqs;
1992 	int i, j;
1993 
1994 	if (!adapter->rx_pool)
1995 		return;
1996 
1997 	rx_scrqs = adapter->num_active_rx_pools;
1998 	rx_entries = adapter->req_rx_add_entries_per_subcrq;
1999 
2000 	/* Free any remaining skbs in the rx buffer pools */
2001 	for (i = 0; i < rx_scrqs; i++) {
2002 		rx_pool = &adapter->rx_pool[i];
2003 		if (!rx_pool || !rx_pool->rx_buff)
2004 			continue;
2005 
2006 		netdev_dbg(adapter->netdev, "Cleaning rx_pool[%d]\n", i);
2007 		for (j = 0; j < rx_entries; j++) {
2008 			rx_buff = &rx_pool->rx_buff[j];
2009 			if (rx_buff && rx_buff->skb) {
2010 				dev_kfree_skb_any(rx_buff->skb);
2011 				rx_buff->skb = NULL;
2012 			}
2013 		}
2014 	}
2015 }
2016 
2017 static void clean_one_tx_pool(struct ibmvnic_adapter *adapter,
2018 			      struct ibmvnic_tx_pool *tx_pool)
2019 {
2020 	struct ibmvnic_tx_buff *tx_buff;
2021 	u64 tx_entries;
2022 	int i;
2023 
2024 	if (!tx_pool || !tx_pool->tx_buff)
2025 		return;
2026 
2027 	tx_entries = tx_pool->num_buffers;
2028 
2029 	for (i = 0; i < tx_entries; i++) {
2030 		tx_buff = &tx_pool->tx_buff[i];
2031 		if (tx_buff && tx_buff->skb) {
2032 			dev_kfree_skb_any(tx_buff->skb);
2033 			tx_buff->skb = NULL;
2034 		}
2035 	}
2036 }
2037 
2038 static void clean_tx_pools(struct ibmvnic_adapter *adapter)
2039 {
2040 	int tx_scrqs;
2041 	int i;
2042 
2043 	if (!adapter->tx_pool || !adapter->tso_pool)
2044 		return;
2045 
2046 	tx_scrqs = adapter->num_active_tx_pools;
2047 
2048 	/* Free any remaining skbs in the tx buffer pools */
2049 	for (i = 0; i < tx_scrqs; i++) {
2050 		netdev_dbg(adapter->netdev, "Cleaning tx_pool[%d]\n", i);
2051 		clean_one_tx_pool(adapter, &adapter->tx_pool[i]);
2052 		clean_one_tx_pool(adapter, &adapter->tso_pool[i]);
2053 	}
2054 }
2055 
2056 static void ibmvnic_disable_irqs(struct ibmvnic_adapter *adapter)
2057 {
2058 	struct net_device *netdev = adapter->netdev;
2059 	int i;
2060 
2061 	if (adapter->tx_scrq) {
2062 		for (i = 0; i < adapter->req_tx_queues; i++)
2063 			if (adapter->tx_scrq[i]->irq) {
2064 				netdev_dbg(netdev,
2065 					   "Disabling tx_scrq[%d] irq\n", i);
2066 				disable_scrq_irq(adapter, adapter->tx_scrq[i]);
2067 				disable_irq(adapter->tx_scrq[i]->irq);
2068 			}
2069 	}
2070 
2071 	if (adapter->rx_scrq) {
2072 		for (i = 0; i < adapter->req_rx_queues; i++) {
2073 			if (adapter->rx_scrq[i]->irq) {
2074 				netdev_dbg(netdev,
2075 					   "Disabling rx_scrq[%d] irq\n", i);
2076 				disable_scrq_irq(adapter, adapter->rx_scrq[i]);
2077 				disable_irq(adapter->rx_scrq[i]->irq);
2078 			}
2079 		}
2080 	}
2081 }
2082 
2083 static void ibmvnic_cleanup(struct net_device *netdev)
2084 {
2085 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
2086 
2087 	/* ensure that transmissions are stopped if called by do_reset */
2088 
2089 	adapter->tx_queues_active = false;
2090 
2091 	/* Ensure complete_tx() and ibmvnic_xmit() see ->tx_queues_active
2092 	 * update so they don't restart a queue after we stop it below.
2093 	 */
2094 	synchronize_rcu();
2095 
2096 	if (test_bit(0, &adapter->resetting))
2097 		netif_tx_disable(netdev);
2098 	else
2099 		netif_tx_stop_all_queues(netdev);
2100 
2101 	ibmvnic_napi_disable(adapter);
2102 	ibmvnic_disable_irqs(adapter);
2103 }
2104 
2105 static int __ibmvnic_close(struct net_device *netdev)
2106 {
2107 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
2108 	int rc = 0;
2109 
2110 	adapter->state = VNIC_CLOSING;
2111 	rc = set_link_state(adapter, IBMVNIC_LOGICAL_LNK_DN);
2112 	adapter->state = VNIC_CLOSED;
2113 	return rc;
2114 }
2115 
2116 static int ibmvnic_close(struct net_device *netdev)
2117 {
2118 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
2119 	int rc;
2120 
2121 	netdev_dbg(netdev, "[S:%s FOP:%d FRR:%d] Closing\n",
2122 		   adapter_state_to_string(adapter->state),
2123 		   adapter->failover_pending,
2124 		   adapter->force_reset_recovery);
2125 
2126 	/* If device failover is pending, just set device state and return.
2127 	 * Device operation will be handled by reset routine.
2128 	 */
2129 	if (adapter->failover_pending) {
2130 		adapter->state = VNIC_CLOSED;
2131 		return 0;
2132 	}
2133 
2134 	rc = __ibmvnic_close(netdev);
2135 	ibmvnic_cleanup(netdev);
2136 	clean_rx_pools(adapter);
2137 	clean_tx_pools(adapter);
2138 
2139 	return rc;
2140 }
2141 
2142 /**
2143  * build_hdr_data - creates L2/L3/L4 header data buffer
2144  * @hdr_field: bitfield determining needed headers
2145  * @skb: socket buffer
2146  * @hdr_len: array of header lengths
2147  * @hdr_data: buffer to write the header to
2148  *
2149  * Reads hdr_field to determine which headers are needed by firmware.
2150  * Builds a buffer containing these headers.  Saves individual header
2151  * lengths and total buffer length to be used to build descriptors.
2152  */
2153 static int build_hdr_data(u8 hdr_field, struct sk_buff *skb,
2154 			  int *hdr_len, u8 *hdr_data)
2155 {
2156 	int len = 0;
2157 	u8 *hdr;
2158 
2159 	if (skb_vlan_tagged(skb) && !skb_vlan_tag_present(skb))
2160 		hdr_len[0] = sizeof(struct vlan_ethhdr);
2161 	else
2162 		hdr_len[0] = sizeof(struct ethhdr);
2163 
2164 	if (skb->protocol == htons(ETH_P_IP)) {
2165 		hdr_len[1] = ip_hdr(skb)->ihl * 4;
2166 		if (ip_hdr(skb)->protocol == IPPROTO_TCP)
2167 			hdr_len[2] = tcp_hdrlen(skb);
2168 		else if (ip_hdr(skb)->protocol == IPPROTO_UDP)
2169 			hdr_len[2] = sizeof(struct udphdr);
2170 	} else if (skb->protocol == htons(ETH_P_IPV6)) {
2171 		hdr_len[1] = sizeof(struct ipv6hdr);
2172 		if (ipv6_hdr(skb)->nexthdr == IPPROTO_TCP)
2173 			hdr_len[2] = tcp_hdrlen(skb);
2174 		else if (ipv6_hdr(skb)->nexthdr == IPPROTO_UDP)
2175 			hdr_len[2] = sizeof(struct udphdr);
2176 	} else if (skb->protocol == htons(ETH_P_ARP)) {
2177 		hdr_len[1] = arp_hdr_len(skb->dev);
2178 		hdr_len[2] = 0;
2179 	}
2180 
2181 	memset(hdr_data, 0, 120);
2182 	if ((hdr_field >> 6) & 1) {
2183 		hdr = skb_mac_header(skb);
2184 		memcpy(hdr_data, hdr, hdr_len[0]);
2185 		len += hdr_len[0];
2186 	}
2187 
2188 	if ((hdr_field >> 5) & 1) {
2189 		hdr = skb_network_header(skb);
2190 		memcpy(hdr_data + len, hdr, hdr_len[1]);
2191 		len += hdr_len[1];
2192 	}
2193 
2194 	if ((hdr_field >> 4) & 1) {
2195 		hdr = skb_transport_header(skb);
2196 		memcpy(hdr_data + len, hdr, hdr_len[2]);
2197 		len += hdr_len[2];
2198 	}
2199 	return len;
2200 }
2201 
2202 /**
2203  * create_hdr_descs - create header and header extension descriptors
2204  * @hdr_field: bitfield determining needed headers
2205  * @hdr_data: buffer containing header data
2206  * @len: length of data buffer
2207  * @hdr_len: array of individual header lengths
2208  * @scrq_arr: descriptor array
2209  *
2210  * Creates header and, if needed, header extension descriptors and
2211  * places them in a descriptor array, scrq_arr
2212  */
2213 
2214 static int create_hdr_descs(u8 hdr_field, u8 *hdr_data, int len, int *hdr_len,
2215 			    union sub_crq *scrq_arr)
2216 {
2217 	union sub_crq hdr_desc;
2218 	int tmp_len = len;
2219 	int num_descs = 0;
2220 	u8 *data, *cur;
2221 	int tmp;
2222 
2223 	while (tmp_len > 0) {
2224 		cur = hdr_data + len - tmp_len;
2225 
2226 		memset(&hdr_desc, 0, sizeof(hdr_desc));
2227 		if (cur != hdr_data) {
2228 			data = hdr_desc.hdr_ext.data;
2229 			tmp = tmp_len > 29 ? 29 : tmp_len;
2230 			hdr_desc.hdr_ext.first = IBMVNIC_CRQ_CMD;
2231 			hdr_desc.hdr_ext.type = IBMVNIC_HDR_EXT_DESC;
2232 			hdr_desc.hdr_ext.len = tmp;
2233 		} else {
2234 			data = hdr_desc.hdr.data;
2235 			tmp = tmp_len > 24 ? 24 : tmp_len;
2236 			hdr_desc.hdr.first = IBMVNIC_CRQ_CMD;
2237 			hdr_desc.hdr.type = IBMVNIC_HDR_DESC;
2238 			hdr_desc.hdr.len = tmp;
2239 			hdr_desc.hdr.l2_len = (u8)hdr_len[0];
2240 			hdr_desc.hdr.l3_len = cpu_to_be16((u16)hdr_len[1]);
2241 			hdr_desc.hdr.l4_len = (u8)hdr_len[2];
2242 			hdr_desc.hdr.flag = hdr_field << 1;
2243 		}
2244 		memcpy(data, cur, tmp);
2245 		tmp_len -= tmp;
2246 		*scrq_arr = hdr_desc;
2247 		scrq_arr++;
2248 		num_descs++;
2249 	}
2250 
2251 	return num_descs;
2252 }
2253 
2254 /**
2255  * build_hdr_descs_arr - build a header descriptor array
2256  * @skb: tx socket buffer
2257  * @indir_arr: indirect array
2258  * @num_entries: number of descriptors to be sent
2259  * @hdr_field: bit field determining which headers will be sent
2260  *
2261  * This function will build a TX descriptor array with applicable
2262  * L2/L3/L4 packet header descriptors to be sent by send_subcrq_indirect.
2263  */
2264 
2265 static void build_hdr_descs_arr(struct sk_buff *skb,
2266 				union sub_crq *indir_arr,
2267 				int *num_entries, u8 hdr_field)
2268 {
2269 	int hdr_len[3] = {0, 0, 0};
2270 	u8 hdr_data[140] = {0};
2271 	int tot_len;
2272 
2273 	tot_len = build_hdr_data(hdr_field, skb, hdr_len,
2274 				 hdr_data);
2275 	*num_entries += create_hdr_descs(hdr_field, hdr_data, tot_len, hdr_len,
2276 					 indir_arr + 1);
2277 }
2278 
2279 static int ibmvnic_xmit_workarounds(struct sk_buff *skb,
2280 				    struct net_device *netdev)
2281 {
2282 	/* For some backing devices, mishandling of small packets
2283 	 * can result in a loss of connection or TX stall. Device
2284 	 * architects recommend that no packet should be smaller
2285 	 * than the minimum MTU value provided to the driver, so
2286 	 * pad any packets to that length
2287 	 */
2288 	if (skb->len < netdev->min_mtu)
2289 		return skb_put_padto(skb, netdev->min_mtu);
2290 
2291 	return 0;
2292 }
2293 
2294 static void ibmvnic_tx_scrq_clean_buffer(struct ibmvnic_adapter *adapter,
2295 					 struct ibmvnic_sub_crq_queue *tx_scrq)
2296 {
2297 	struct ibmvnic_ind_xmit_queue *ind_bufp;
2298 	struct ibmvnic_tx_buff *tx_buff;
2299 	struct ibmvnic_tx_pool *tx_pool;
2300 	union sub_crq tx_scrq_entry;
2301 	int queue_num;
2302 	int entries;
2303 	int index;
2304 	int i;
2305 
2306 	ind_bufp = &tx_scrq->ind_buf;
2307 	entries = (u64)ind_bufp->index;
2308 	queue_num = tx_scrq->pool_index;
2309 
2310 	for (i = entries - 1; i >= 0; --i) {
2311 		tx_scrq_entry = ind_bufp->indir_arr[i];
2312 		if (tx_scrq_entry.v1.type != IBMVNIC_TX_DESC)
2313 			continue;
2314 		index = be32_to_cpu(tx_scrq_entry.v1.correlator);
2315 		if (index & IBMVNIC_TSO_POOL_MASK) {
2316 			tx_pool = &adapter->tso_pool[queue_num];
2317 			index &= ~IBMVNIC_TSO_POOL_MASK;
2318 		} else {
2319 			tx_pool = &adapter->tx_pool[queue_num];
2320 		}
2321 		tx_pool->free_map[tx_pool->consumer_index] = index;
2322 		tx_pool->consumer_index = tx_pool->consumer_index == 0 ?
2323 					  tx_pool->num_buffers - 1 :
2324 					  tx_pool->consumer_index - 1;
2325 		tx_buff = &tx_pool->tx_buff[index];
2326 		adapter->netdev->stats.tx_packets--;
2327 		adapter->netdev->stats.tx_bytes -= tx_buff->skb->len;
2328 		adapter->tx_stats_buffers[queue_num].packets--;
2329 		adapter->tx_stats_buffers[queue_num].bytes -=
2330 						tx_buff->skb->len;
2331 		dev_kfree_skb_any(tx_buff->skb);
2332 		tx_buff->skb = NULL;
2333 		adapter->netdev->stats.tx_dropped++;
2334 	}
2335 
2336 	ind_bufp->index = 0;
2337 
2338 	if (atomic_sub_return(entries, &tx_scrq->used) <=
2339 	    (adapter->req_tx_entries_per_subcrq / 2) &&
2340 	    __netif_subqueue_stopped(adapter->netdev, queue_num)) {
2341 		rcu_read_lock();
2342 
2343 		if (adapter->tx_queues_active) {
2344 			netif_wake_subqueue(adapter->netdev, queue_num);
2345 			netdev_dbg(adapter->netdev, "Started queue %d\n",
2346 				   queue_num);
2347 		}
2348 
2349 		rcu_read_unlock();
2350 	}
2351 }
2352 
2353 static int ibmvnic_tx_scrq_flush(struct ibmvnic_adapter *adapter,
2354 				 struct ibmvnic_sub_crq_queue *tx_scrq)
2355 {
2356 	struct ibmvnic_ind_xmit_queue *ind_bufp;
2357 	u64 dma_addr;
2358 	u64 entries;
2359 	u64 handle;
2360 	int rc;
2361 
2362 	ind_bufp = &tx_scrq->ind_buf;
2363 	dma_addr = (u64)ind_bufp->indir_dma;
2364 	entries = (u64)ind_bufp->index;
2365 	handle = tx_scrq->handle;
2366 
2367 	if (!entries)
2368 		return 0;
2369 	rc = send_subcrq_indirect(adapter, handle, dma_addr, entries);
2370 	if (rc)
2371 		ibmvnic_tx_scrq_clean_buffer(adapter, tx_scrq);
2372 	else
2373 		ind_bufp->index = 0;
2374 	return rc;
2375 }
2376 
2377 static netdev_tx_t ibmvnic_xmit(struct sk_buff *skb, struct net_device *netdev)
2378 {
2379 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
2380 	int queue_num = skb_get_queue_mapping(skb);
2381 	u8 *hdrs = (u8 *)&adapter->tx_rx_desc_req;
2382 	struct device *dev = &adapter->vdev->dev;
2383 	struct ibmvnic_ind_xmit_queue *ind_bufp;
2384 	struct ibmvnic_tx_buff *tx_buff = NULL;
2385 	struct ibmvnic_sub_crq_queue *tx_scrq;
2386 	struct ibmvnic_long_term_buff *ltb;
2387 	struct ibmvnic_tx_pool *tx_pool;
2388 	unsigned int tx_send_failed = 0;
2389 	netdev_tx_t ret = NETDEV_TX_OK;
2390 	unsigned int tx_map_failed = 0;
2391 	union sub_crq indir_arr[16];
2392 	unsigned int tx_dropped = 0;
2393 	unsigned int tx_packets = 0;
2394 	unsigned int tx_bytes = 0;
2395 	dma_addr_t data_dma_addr;
2396 	struct netdev_queue *txq;
2397 	unsigned long lpar_rc;
2398 	union sub_crq tx_crq;
2399 	unsigned int offset;
2400 	int num_entries = 1;
2401 	unsigned char *dst;
2402 	int bufidx = 0;
2403 	u8 proto = 0;
2404 
2405 	/* If a reset is in progress, drop the packet since
2406 	 * the scrqs may get torn down. Otherwise use the
2407 	 * rcu to ensure reset waits for us to complete.
2408 	 */
2409 	rcu_read_lock();
2410 	if (!adapter->tx_queues_active) {
2411 		dev_kfree_skb_any(skb);
2412 
2413 		tx_send_failed++;
2414 		tx_dropped++;
2415 		ret = NETDEV_TX_OK;
2416 		goto out;
2417 	}
2418 
2419 	tx_scrq = adapter->tx_scrq[queue_num];
2420 	txq = netdev_get_tx_queue(netdev, queue_num);
2421 	ind_bufp = &tx_scrq->ind_buf;
2422 
2423 	if (ibmvnic_xmit_workarounds(skb, netdev)) {
2424 		tx_dropped++;
2425 		tx_send_failed++;
2426 		ret = NETDEV_TX_OK;
2427 		lpar_rc = ibmvnic_tx_scrq_flush(adapter, tx_scrq);
2428 		if (lpar_rc != H_SUCCESS)
2429 			goto tx_err;
2430 		goto out;
2431 	}
2432 
2433 	if (skb_is_gso(skb))
2434 		tx_pool = &adapter->tso_pool[queue_num];
2435 	else
2436 		tx_pool = &adapter->tx_pool[queue_num];
2437 
2438 	bufidx = tx_pool->free_map[tx_pool->consumer_index];
2439 
2440 	if (bufidx == IBMVNIC_INVALID_MAP) {
2441 		dev_kfree_skb_any(skb);
2442 		tx_send_failed++;
2443 		tx_dropped++;
2444 		ret = NETDEV_TX_OK;
2445 		lpar_rc = ibmvnic_tx_scrq_flush(adapter, tx_scrq);
2446 		if (lpar_rc != H_SUCCESS)
2447 			goto tx_err;
2448 		goto out;
2449 	}
2450 
2451 	tx_pool->free_map[tx_pool->consumer_index] = IBMVNIC_INVALID_MAP;
2452 
2453 	map_txpool_buf_to_ltb(tx_pool, bufidx, &ltb, &offset);
2454 
2455 	dst = ltb->buff + offset;
2456 	memset(dst, 0, tx_pool->buf_size);
2457 	data_dma_addr = ltb->addr + offset;
2458 
2459 	if (skb_shinfo(skb)->nr_frags) {
2460 		int cur, i;
2461 
2462 		/* Copy the head */
2463 		skb_copy_from_linear_data(skb, dst, skb_headlen(skb));
2464 		cur = skb_headlen(skb);
2465 
2466 		/* Copy the frags */
2467 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2468 			const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2469 
2470 			memcpy(dst + cur, skb_frag_address(frag),
2471 			       skb_frag_size(frag));
2472 			cur += skb_frag_size(frag);
2473 		}
2474 	} else {
2475 		skb_copy_from_linear_data(skb, dst, skb->len);
2476 	}
2477 
2478 	/* post changes to long_term_buff *dst before VIOS accessing it */
2479 	dma_wmb();
2480 
2481 	tx_pool->consumer_index =
2482 	    (tx_pool->consumer_index + 1) % tx_pool->num_buffers;
2483 
2484 	tx_buff = &tx_pool->tx_buff[bufidx];
2485 
2486 	/* Sanity checks on our free map to make sure it points to an index
2487 	 * that is not being occupied by another skb. If skb memory is
2488 	 * not freed then we see congestion control kick in and halt tx.
2489 	 */
2490 	if (unlikely(tx_buff->skb)) {
2491 		dev_warn_ratelimited(dev, "TX free map points to untracked skb (%s %d idx=%d)\n",
2492 				     skb_is_gso(skb) ? "tso_pool" : "tx_pool",
2493 				     queue_num, bufidx);
2494 		dev_kfree_skb_any(tx_buff->skb);
2495 	}
2496 
2497 	tx_buff->skb = skb;
2498 	tx_buff->index = bufidx;
2499 	tx_buff->pool_index = queue_num;
2500 
2501 	memset(&tx_crq, 0, sizeof(tx_crq));
2502 	tx_crq.v1.first = IBMVNIC_CRQ_CMD;
2503 	tx_crq.v1.type = IBMVNIC_TX_DESC;
2504 	tx_crq.v1.n_crq_elem = 1;
2505 	tx_crq.v1.n_sge = 1;
2506 	tx_crq.v1.flags1 = IBMVNIC_TX_COMP_NEEDED;
2507 
2508 	if (skb_is_gso(skb))
2509 		tx_crq.v1.correlator =
2510 			cpu_to_be32(bufidx | IBMVNIC_TSO_POOL_MASK);
2511 	else
2512 		tx_crq.v1.correlator = cpu_to_be32(bufidx);
2513 	tx_crq.v1.dma_reg = cpu_to_be16(ltb->map_id);
2514 	tx_crq.v1.sge_len = cpu_to_be32(skb->len);
2515 	tx_crq.v1.ioba = cpu_to_be64(data_dma_addr);
2516 
2517 	if (adapter->vlan_header_insertion && skb_vlan_tag_present(skb)) {
2518 		tx_crq.v1.flags2 |= IBMVNIC_TX_VLAN_INSERT;
2519 		tx_crq.v1.vlan_id = cpu_to_be16(skb->vlan_tci);
2520 	}
2521 
2522 	if (skb->protocol == htons(ETH_P_IP)) {
2523 		tx_crq.v1.flags1 |= IBMVNIC_TX_PROT_IPV4;
2524 		proto = ip_hdr(skb)->protocol;
2525 	} else if (skb->protocol == htons(ETH_P_IPV6)) {
2526 		tx_crq.v1.flags1 |= IBMVNIC_TX_PROT_IPV6;
2527 		proto = ipv6_hdr(skb)->nexthdr;
2528 	}
2529 
2530 	if (proto == IPPROTO_TCP)
2531 		tx_crq.v1.flags1 |= IBMVNIC_TX_PROT_TCP;
2532 	else if (proto == IPPROTO_UDP)
2533 		tx_crq.v1.flags1 |= IBMVNIC_TX_PROT_UDP;
2534 
2535 	if (skb->ip_summed == CHECKSUM_PARTIAL) {
2536 		tx_crq.v1.flags1 |= IBMVNIC_TX_CHKSUM_OFFLOAD;
2537 		hdrs += 2;
2538 	}
2539 	if (skb_is_gso(skb)) {
2540 		tx_crq.v1.flags1 |= IBMVNIC_TX_LSO;
2541 		tx_crq.v1.mss = cpu_to_be16(skb_shinfo(skb)->gso_size);
2542 		hdrs += 2;
2543 	}
2544 
2545 	if ((*hdrs >> 7) & 1)
2546 		build_hdr_descs_arr(skb, indir_arr, &num_entries, *hdrs);
2547 
2548 	tx_crq.v1.n_crq_elem = num_entries;
2549 	tx_buff->num_entries = num_entries;
2550 	/* flush buffer if current entry can not fit */
2551 	if (num_entries + ind_bufp->index > IBMVNIC_MAX_IND_DESCS) {
2552 		lpar_rc = ibmvnic_tx_scrq_flush(adapter, tx_scrq);
2553 		if (lpar_rc != H_SUCCESS)
2554 			goto tx_flush_err;
2555 	}
2556 
2557 	indir_arr[0] = tx_crq;
2558 	memcpy(&ind_bufp->indir_arr[ind_bufp->index], &indir_arr[0],
2559 	       num_entries * sizeof(struct ibmvnic_generic_scrq));
2560 	ind_bufp->index += num_entries;
2561 	if (__netdev_tx_sent_queue(txq, skb->len,
2562 				   netdev_xmit_more() &&
2563 				   ind_bufp->index < IBMVNIC_MAX_IND_DESCS)) {
2564 		lpar_rc = ibmvnic_tx_scrq_flush(adapter, tx_scrq);
2565 		if (lpar_rc != H_SUCCESS)
2566 			goto tx_err;
2567 	}
2568 
2569 	if (atomic_add_return(num_entries, &tx_scrq->used)
2570 					>= adapter->req_tx_entries_per_subcrq) {
2571 		netdev_dbg(netdev, "Stopping queue %d\n", queue_num);
2572 		netif_stop_subqueue(netdev, queue_num);
2573 	}
2574 
2575 	tx_packets++;
2576 	tx_bytes += skb->len;
2577 	txq_trans_cond_update(txq);
2578 	ret = NETDEV_TX_OK;
2579 	goto out;
2580 
2581 tx_flush_err:
2582 	dev_kfree_skb_any(skb);
2583 	tx_buff->skb = NULL;
2584 	tx_pool->consumer_index = tx_pool->consumer_index == 0 ?
2585 				  tx_pool->num_buffers - 1 :
2586 				  tx_pool->consumer_index - 1;
2587 	tx_dropped++;
2588 tx_err:
2589 	if (lpar_rc != H_CLOSED && lpar_rc != H_PARAMETER)
2590 		dev_err_ratelimited(dev, "tx: send failed\n");
2591 
2592 	if (lpar_rc == H_CLOSED || adapter->failover_pending) {
2593 		/* Disable TX and report carrier off if queue is closed
2594 		 * or pending failover.
2595 		 * Firmware guarantees that a signal will be sent to the
2596 		 * driver, triggering a reset or some other action.
2597 		 */
2598 		netif_tx_stop_all_queues(netdev);
2599 		netif_carrier_off(netdev);
2600 	}
2601 out:
2602 	rcu_read_unlock();
2603 	netdev->stats.tx_dropped += tx_dropped;
2604 	netdev->stats.tx_bytes += tx_bytes;
2605 	netdev->stats.tx_packets += tx_packets;
2606 	adapter->tx_send_failed += tx_send_failed;
2607 	adapter->tx_map_failed += tx_map_failed;
2608 	adapter->tx_stats_buffers[queue_num].packets += tx_packets;
2609 	adapter->tx_stats_buffers[queue_num].bytes += tx_bytes;
2610 	adapter->tx_stats_buffers[queue_num].dropped_packets += tx_dropped;
2611 
2612 	return ret;
2613 }
2614 
2615 static void ibmvnic_set_multi(struct net_device *netdev)
2616 {
2617 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
2618 	struct netdev_hw_addr *ha;
2619 	union ibmvnic_crq crq;
2620 
2621 	memset(&crq, 0, sizeof(crq));
2622 	crq.request_capability.first = IBMVNIC_CRQ_CMD;
2623 	crq.request_capability.cmd = REQUEST_CAPABILITY;
2624 
2625 	if (netdev->flags & IFF_PROMISC) {
2626 		if (!adapter->promisc_supported)
2627 			return;
2628 	} else {
2629 		if (netdev->flags & IFF_ALLMULTI) {
2630 			/* Accept all multicast */
2631 			memset(&crq, 0, sizeof(crq));
2632 			crq.multicast_ctrl.first = IBMVNIC_CRQ_CMD;
2633 			crq.multicast_ctrl.cmd = MULTICAST_CTRL;
2634 			crq.multicast_ctrl.flags = IBMVNIC_ENABLE_ALL;
2635 			ibmvnic_send_crq(adapter, &crq);
2636 		} else if (netdev_mc_empty(netdev)) {
2637 			/* Reject all multicast */
2638 			memset(&crq, 0, sizeof(crq));
2639 			crq.multicast_ctrl.first = IBMVNIC_CRQ_CMD;
2640 			crq.multicast_ctrl.cmd = MULTICAST_CTRL;
2641 			crq.multicast_ctrl.flags = IBMVNIC_DISABLE_ALL;
2642 			ibmvnic_send_crq(adapter, &crq);
2643 		} else {
2644 			/* Accept one or more multicast(s) */
2645 			netdev_for_each_mc_addr(ha, netdev) {
2646 				memset(&crq, 0, sizeof(crq));
2647 				crq.multicast_ctrl.first = IBMVNIC_CRQ_CMD;
2648 				crq.multicast_ctrl.cmd = MULTICAST_CTRL;
2649 				crq.multicast_ctrl.flags = IBMVNIC_ENABLE_MC;
2650 				ether_addr_copy(&crq.multicast_ctrl.mac_addr[0],
2651 						ha->addr);
2652 				ibmvnic_send_crq(adapter, &crq);
2653 			}
2654 		}
2655 	}
2656 }
2657 
2658 static int __ibmvnic_set_mac(struct net_device *netdev, u8 *dev_addr)
2659 {
2660 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
2661 	union ibmvnic_crq crq;
2662 	int rc;
2663 
2664 	if (!is_valid_ether_addr(dev_addr)) {
2665 		rc = -EADDRNOTAVAIL;
2666 		goto err;
2667 	}
2668 
2669 	memset(&crq, 0, sizeof(crq));
2670 	crq.change_mac_addr.first = IBMVNIC_CRQ_CMD;
2671 	crq.change_mac_addr.cmd = CHANGE_MAC_ADDR;
2672 	ether_addr_copy(&crq.change_mac_addr.mac_addr[0], dev_addr);
2673 
2674 	mutex_lock(&adapter->fw_lock);
2675 	adapter->fw_done_rc = 0;
2676 	reinit_completion(&adapter->fw_done);
2677 
2678 	rc = ibmvnic_send_crq(adapter, &crq);
2679 	if (rc) {
2680 		rc = -EIO;
2681 		mutex_unlock(&adapter->fw_lock);
2682 		goto err;
2683 	}
2684 
2685 	rc = ibmvnic_wait_for_completion(adapter, &adapter->fw_done, 10000);
2686 	/* netdev->dev_addr is changed in handle_change_mac_rsp function */
2687 	if (rc || adapter->fw_done_rc) {
2688 		rc = -EIO;
2689 		mutex_unlock(&adapter->fw_lock);
2690 		goto err;
2691 	}
2692 	mutex_unlock(&adapter->fw_lock);
2693 	return 0;
2694 err:
2695 	ether_addr_copy(adapter->mac_addr, netdev->dev_addr);
2696 	return rc;
2697 }
2698 
2699 static int ibmvnic_set_mac(struct net_device *netdev, void *p)
2700 {
2701 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
2702 	struct sockaddr *addr = p;
2703 	int rc;
2704 
2705 	rc = 0;
2706 	if (!is_valid_ether_addr(addr->sa_data))
2707 		return -EADDRNOTAVAIL;
2708 
2709 	ether_addr_copy(adapter->mac_addr, addr->sa_data);
2710 	if (adapter->state != VNIC_PROBED)
2711 		rc = __ibmvnic_set_mac(netdev, addr->sa_data);
2712 
2713 	return rc;
2714 }
2715 
2716 static const char *reset_reason_to_string(enum ibmvnic_reset_reason reason)
2717 {
2718 	switch (reason) {
2719 	case VNIC_RESET_FAILOVER:
2720 		return "FAILOVER";
2721 	case VNIC_RESET_MOBILITY:
2722 		return "MOBILITY";
2723 	case VNIC_RESET_FATAL:
2724 		return "FATAL";
2725 	case VNIC_RESET_NON_FATAL:
2726 		return "NON_FATAL";
2727 	case VNIC_RESET_TIMEOUT:
2728 		return "TIMEOUT";
2729 	case VNIC_RESET_CHANGE_PARAM:
2730 		return "CHANGE_PARAM";
2731 	case VNIC_RESET_PASSIVE_INIT:
2732 		return "PASSIVE_INIT";
2733 	}
2734 	return "UNKNOWN";
2735 }
2736 
2737 /*
2738  * Initialize the init_done completion and return code values. We
2739  * can get a transport event just after registering the CRQ and the
2740  * tasklet will use this to communicate the transport event. To ensure
2741  * we don't miss the notification/error, initialize these _before_
2742  * regisering the CRQ.
2743  */
2744 static inline void reinit_init_done(struct ibmvnic_adapter *adapter)
2745 {
2746 	reinit_completion(&adapter->init_done);
2747 	adapter->init_done_rc = 0;
2748 }
2749 
2750 /*
2751  * do_reset returns zero if we are able to keep processing reset events, or
2752  * non-zero if we hit a fatal error and must halt.
2753  */
2754 static int do_reset(struct ibmvnic_adapter *adapter,
2755 		    struct ibmvnic_rwi *rwi, u32 reset_state)
2756 {
2757 	struct net_device *netdev = adapter->netdev;
2758 	u64 old_num_rx_queues, old_num_tx_queues;
2759 	u64 old_num_rx_slots, old_num_tx_slots;
2760 	int rc;
2761 
2762 	netdev_dbg(adapter->netdev,
2763 		   "[S:%s FOP:%d] Reset reason: %s, reset_state: %s\n",
2764 		   adapter_state_to_string(adapter->state),
2765 		   adapter->failover_pending,
2766 		   reset_reason_to_string(rwi->reset_reason),
2767 		   adapter_state_to_string(reset_state));
2768 
2769 	adapter->reset_reason = rwi->reset_reason;
2770 	/* requestor of VNIC_RESET_CHANGE_PARAM already has the rtnl lock */
2771 	if (!(adapter->reset_reason == VNIC_RESET_CHANGE_PARAM))
2772 		rtnl_lock();
2773 
2774 	/* Now that we have the rtnl lock, clear any pending failover.
2775 	 * This will ensure ibmvnic_open() has either completed or will
2776 	 * block until failover is complete.
2777 	 */
2778 	if (rwi->reset_reason == VNIC_RESET_FAILOVER)
2779 		adapter->failover_pending = false;
2780 
2781 	/* read the state and check (again) after getting rtnl */
2782 	reset_state = adapter->state;
2783 
2784 	if (reset_state == VNIC_REMOVING || reset_state == VNIC_REMOVED) {
2785 		rc = -EBUSY;
2786 		goto out;
2787 	}
2788 
2789 	netif_carrier_off(netdev);
2790 
2791 	old_num_rx_queues = adapter->req_rx_queues;
2792 	old_num_tx_queues = adapter->req_tx_queues;
2793 	old_num_rx_slots = adapter->req_rx_add_entries_per_subcrq;
2794 	old_num_tx_slots = adapter->req_tx_entries_per_subcrq;
2795 
2796 	ibmvnic_cleanup(netdev);
2797 
2798 	if (reset_state == VNIC_OPEN &&
2799 	    adapter->reset_reason != VNIC_RESET_MOBILITY &&
2800 	    adapter->reset_reason != VNIC_RESET_FAILOVER) {
2801 		if (adapter->reset_reason == VNIC_RESET_CHANGE_PARAM) {
2802 			rc = __ibmvnic_close(netdev);
2803 			if (rc)
2804 				goto out;
2805 		} else {
2806 			adapter->state = VNIC_CLOSING;
2807 
2808 			/* Release the RTNL lock before link state change and
2809 			 * re-acquire after the link state change to allow
2810 			 * linkwatch_event to grab the RTNL lock and run during
2811 			 * a reset.
2812 			 */
2813 			rtnl_unlock();
2814 			rc = set_link_state(adapter, IBMVNIC_LOGICAL_LNK_DN);
2815 			rtnl_lock();
2816 			if (rc)
2817 				goto out;
2818 
2819 			if (adapter->state == VNIC_OPEN) {
2820 				/* When we dropped rtnl, ibmvnic_open() got
2821 				 * it and noticed that we are resetting and
2822 				 * set the adapter state to OPEN. Update our
2823 				 * new "target" state, and resume the reset
2824 				 * from VNIC_CLOSING state.
2825 				 */
2826 				netdev_dbg(netdev,
2827 					   "Open changed state from %s, updating.\n",
2828 					   adapter_state_to_string(reset_state));
2829 				reset_state = VNIC_OPEN;
2830 				adapter->state = VNIC_CLOSING;
2831 			}
2832 
2833 			if (adapter->state != VNIC_CLOSING) {
2834 				/* If someone else changed the adapter state
2835 				 * when we dropped the rtnl, fail the reset
2836 				 */
2837 				rc = -EAGAIN;
2838 				goto out;
2839 			}
2840 			adapter->state = VNIC_CLOSED;
2841 		}
2842 	}
2843 
2844 	if (adapter->reset_reason == VNIC_RESET_CHANGE_PARAM) {
2845 		release_resources(adapter);
2846 		release_sub_crqs(adapter, 1);
2847 		release_crq_queue(adapter);
2848 	}
2849 
2850 	if (adapter->reset_reason != VNIC_RESET_NON_FATAL) {
2851 		/* remove the closed state so when we call open it appears
2852 		 * we are coming from the probed state.
2853 		 */
2854 		adapter->state = VNIC_PROBED;
2855 
2856 		reinit_init_done(adapter);
2857 
2858 		if (adapter->reset_reason == VNIC_RESET_CHANGE_PARAM) {
2859 			rc = init_crq_queue(adapter);
2860 		} else if (adapter->reset_reason == VNIC_RESET_MOBILITY) {
2861 			rc = ibmvnic_reenable_crq_queue(adapter);
2862 			release_sub_crqs(adapter, 1);
2863 		} else {
2864 			rc = ibmvnic_reset_crq(adapter);
2865 			if (rc == H_CLOSED || rc == H_SUCCESS) {
2866 				rc = vio_enable_interrupts(adapter->vdev);
2867 				if (rc)
2868 					netdev_err(adapter->netdev,
2869 						   "Reset failed to enable interrupts. rc=%d\n",
2870 						   rc);
2871 			}
2872 		}
2873 
2874 		if (rc) {
2875 			netdev_err(adapter->netdev,
2876 				   "Reset couldn't initialize crq. rc=%d\n", rc);
2877 			goto out;
2878 		}
2879 
2880 		rc = ibmvnic_reset_init(adapter, true);
2881 		if (rc)
2882 			goto out;
2883 
2884 		/* If the adapter was in PROBE or DOWN state prior to the reset,
2885 		 * exit here.
2886 		 */
2887 		if (reset_state == VNIC_PROBED || reset_state == VNIC_DOWN) {
2888 			rc = 0;
2889 			goto out;
2890 		}
2891 
2892 		rc = ibmvnic_login(netdev);
2893 		if (rc)
2894 			goto out;
2895 
2896 		if (adapter->reset_reason == VNIC_RESET_CHANGE_PARAM) {
2897 			rc = init_resources(adapter);
2898 			if (rc)
2899 				goto out;
2900 		} else if (adapter->req_rx_queues != old_num_rx_queues ||
2901 		    adapter->req_tx_queues != old_num_tx_queues ||
2902 		    adapter->req_rx_add_entries_per_subcrq !=
2903 		    old_num_rx_slots ||
2904 		    adapter->req_tx_entries_per_subcrq !=
2905 		    old_num_tx_slots ||
2906 		    !adapter->rx_pool ||
2907 		    !adapter->tso_pool ||
2908 		    !adapter->tx_pool) {
2909 			release_napi(adapter);
2910 			release_vpd_data(adapter);
2911 
2912 			rc = init_resources(adapter);
2913 			if (rc)
2914 				goto out;
2915 
2916 		} else {
2917 			rc = init_tx_pools(netdev);
2918 			if (rc) {
2919 				netdev_dbg(netdev,
2920 					   "init tx pools failed (%d)\n",
2921 					   rc);
2922 				goto out;
2923 			}
2924 
2925 			rc = init_rx_pools(netdev);
2926 			if (rc) {
2927 				netdev_dbg(netdev,
2928 					   "init rx pools failed (%d)\n",
2929 					   rc);
2930 				goto out;
2931 			}
2932 		}
2933 		ibmvnic_disable_irqs(adapter);
2934 	}
2935 	adapter->state = VNIC_CLOSED;
2936 
2937 	if (reset_state == VNIC_CLOSED) {
2938 		rc = 0;
2939 		goto out;
2940 	}
2941 
2942 	rc = __ibmvnic_open(netdev);
2943 	if (rc) {
2944 		rc = IBMVNIC_OPEN_FAILED;
2945 		goto out;
2946 	}
2947 
2948 	/* refresh device's multicast list */
2949 	ibmvnic_set_multi(netdev);
2950 
2951 	if (adapter->reset_reason == VNIC_RESET_FAILOVER ||
2952 	    adapter->reset_reason == VNIC_RESET_MOBILITY)
2953 		__netdev_notify_peers(netdev);
2954 
2955 	rc = 0;
2956 
2957 out:
2958 	/* restore the adapter state if reset failed */
2959 	if (rc)
2960 		adapter->state = reset_state;
2961 	/* requestor of VNIC_RESET_CHANGE_PARAM should still hold the rtnl lock */
2962 	if (!(adapter->reset_reason == VNIC_RESET_CHANGE_PARAM))
2963 		rtnl_unlock();
2964 
2965 	netdev_dbg(adapter->netdev, "[S:%s FOP:%d] Reset done, rc %d\n",
2966 		   adapter_state_to_string(adapter->state),
2967 		   adapter->failover_pending, rc);
2968 	return rc;
2969 }
2970 
2971 static int do_hard_reset(struct ibmvnic_adapter *adapter,
2972 			 struct ibmvnic_rwi *rwi, u32 reset_state)
2973 {
2974 	struct net_device *netdev = adapter->netdev;
2975 	int rc;
2976 
2977 	netdev_dbg(adapter->netdev, "Hard resetting driver (%s)\n",
2978 		   reset_reason_to_string(rwi->reset_reason));
2979 
2980 	/* read the state and check (again) after getting rtnl */
2981 	reset_state = adapter->state;
2982 
2983 	if (reset_state == VNIC_REMOVING || reset_state == VNIC_REMOVED) {
2984 		rc = -EBUSY;
2985 		goto out;
2986 	}
2987 
2988 	netif_carrier_off(netdev);
2989 	adapter->reset_reason = rwi->reset_reason;
2990 
2991 	ibmvnic_cleanup(netdev);
2992 	release_resources(adapter);
2993 	release_sub_crqs(adapter, 0);
2994 	release_crq_queue(adapter);
2995 
2996 	/* remove the closed state so when we call open it appears
2997 	 * we are coming from the probed state.
2998 	 */
2999 	adapter->state = VNIC_PROBED;
3000 
3001 	reinit_init_done(adapter);
3002 
3003 	rc = init_crq_queue(adapter);
3004 	if (rc) {
3005 		netdev_err(adapter->netdev,
3006 			   "Couldn't initialize crq. rc=%d\n", rc);
3007 		goto out;
3008 	}
3009 
3010 	rc = ibmvnic_reset_init(adapter, false);
3011 	if (rc)
3012 		goto out;
3013 
3014 	/* If the adapter was in PROBE or DOWN state prior to the reset,
3015 	 * exit here.
3016 	 */
3017 	if (reset_state == VNIC_PROBED || reset_state == VNIC_DOWN)
3018 		goto out;
3019 
3020 	rc = ibmvnic_login(netdev);
3021 	if (rc)
3022 		goto out;
3023 
3024 	rc = init_resources(adapter);
3025 	if (rc)
3026 		goto out;
3027 
3028 	ibmvnic_disable_irqs(adapter);
3029 	adapter->state = VNIC_CLOSED;
3030 
3031 	if (reset_state == VNIC_CLOSED)
3032 		goto out;
3033 
3034 	rc = __ibmvnic_open(netdev);
3035 	if (rc) {
3036 		rc = IBMVNIC_OPEN_FAILED;
3037 		goto out;
3038 	}
3039 
3040 	__netdev_notify_peers(netdev);
3041 out:
3042 	/* restore adapter state if reset failed */
3043 	if (rc)
3044 		adapter->state = reset_state;
3045 	netdev_dbg(adapter->netdev, "[S:%s FOP:%d] Hard reset done, rc %d\n",
3046 		   adapter_state_to_string(adapter->state),
3047 		   adapter->failover_pending, rc);
3048 	return rc;
3049 }
3050 
3051 static struct ibmvnic_rwi *get_next_rwi(struct ibmvnic_adapter *adapter)
3052 {
3053 	struct ibmvnic_rwi *rwi;
3054 	unsigned long flags;
3055 
3056 	spin_lock_irqsave(&adapter->rwi_lock, flags);
3057 
3058 	if (!list_empty(&adapter->rwi_list)) {
3059 		rwi = list_first_entry(&adapter->rwi_list, struct ibmvnic_rwi,
3060 				       list);
3061 		list_del(&rwi->list);
3062 	} else {
3063 		rwi = NULL;
3064 	}
3065 
3066 	spin_unlock_irqrestore(&adapter->rwi_lock, flags);
3067 	return rwi;
3068 }
3069 
3070 /**
3071  * do_passive_init - complete probing when partner device is detected.
3072  * @adapter: ibmvnic_adapter struct
3073  *
3074  * If the ibmvnic device does not have a partner device to communicate with at boot
3075  * and that partner device comes online at a later time, this function is called
3076  * to complete the initialization process of ibmvnic device.
3077  * Caller is expected to hold rtnl_lock().
3078  *
3079  * Returns non-zero if sub-CRQs are not initialized properly leaving the device
3080  * in the down state.
3081  * Returns 0 upon success and the device is in PROBED state.
3082  */
3083 
3084 static int do_passive_init(struct ibmvnic_adapter *adapter)
3085 {
3086 	unsigned long timeout = msecs_to_jiffies(30000);
3087 	struct net_device *netdev = adapter->netdev;
3088 	struct device *dev = &adapter->vdev->dev;
3089 	int rc;
3090 
3091 	netdev_dbg(netdev, "Partner device found, probing.\n");
3092 
3093 	adapter->state = VNIC_PROBING;
3094 	reinit_completion(&adapter->init_done);
3095 	adapter->init_done_rc = 0;
3096 	adapter->crq.active = true;
3097 
3098 	rc = send_crq_init_complete(adapter);
3099 	if (rc)
3100 		goto out;
3101 
3102 	rc = send_version_xchg(adapter);
3103 	if (rc)
3104 		netdev_dbg(adapter->netdev, "send_version_xchg failed, rc=%d\n", rc);
3105 
3106 	if (!wait_for_completion_timeout(&adapter->init_done, timeout)) {
3107 		dev_err(dev, "Initialization sequence timed out\n");
3108 		rc = -ETIMEDOUT;
3109 		goto out;
3110 	}
3111 
3112 	rc = init_sub_crqs(adapter);
3113 	if (rc) {
3114 		dev_err(dev, "Initialization of sub crqs failed, rc=%d\n", rc);
3115 		goto out;
3116 	}
3117 
3118 	rc = init_sub_crq_irqs(adapter);
3119 	if (rc) {
3120 		dev_err(dev, "Failed to initialize sub crq irqs\n, rc=%d", rc);
3121 		goto init_failed;
3122 	}
3123 
3124 	netdev->mtu = adapter->req_mtu - ETH_HLEN;
3125 	netdev->min_mtu = adapter->min_mtu - ETH_HLEN;
3126 	netdev->max_mtu = adapter->max_mtu - ETH_HLEN;
3127 
3128 	adapter->state = VNIC_PROBED;
3129 	netdev_dbg(netdev, "Probed successfully. Waiting for signal from partner device.\n");
3130 
3131 	return 0;
3132 
3133 init_failed:
3134 	release_sub_crqs(adapter, 1);
3135 out:
3136 	adapter->state = VNIC_DOWN;
3137 	return rc;
3138 }
3139 
3140 static void __ibmvnic_reset(struct work_struct *work)
3141 {
3142 	struct ibmvnic_adapter *adapter;
3143 	unsigned int timeout = 5000;
3144 	struct ibmvnic_rwi *tmprwi;
3145 	bool saved_state = false;
3146 	struct ibmvnic_rwi *rwi;
3147 	unsigned long flags;
3148 	struct device *dev;
3149 	bool need_reset;
3150 	int num_fails = 0;
3151 	u32 reset_state;
3152 	int rc = 0;
3153 
3154 	adapter = container_of(work, struct ibmvnic_adapter, ibmvnic_reset);
3155 		dev = &adapter->vdev->dev;
3156 
3157 	/* Wait for ibmvnic_probe() to complete. If probe is taking too long
3158 	 * or if another reset is in progress, defer work for now. If probe
3159 	 * eventually fails it will flush and terminate our work.
3160 	 *
3161 	 * Three possibilities here:
3162 	 * 1. Adpater being removed  - just return
3163 	 * 2. Timed out on probe or another reset in progress - delay the work
3164 	 * 3. Completed probe - perform any resets in queue
3165 	 */
3166 	if (adapter->state == VNIC_PROBING &&
3167 	    !wait_for_completion_timeout(&adapter->probe_done, timeout)) {
3168 		dev_err(dev, "Reset thread timed out on probe");
3169 		queue_delayed_work(system_long_wq,
3170 				   &adapter->ibmvnic_delayed_reset,
3171 				   IBMVNIC_RESET_DELAY);
3172 		return;
3173 	}
3174 
3175 	/* adapter is done with probe (i.e state is never VNIC_PROBING now) */
3176 	if (adapter->state == VNIC_REMOVING)
3177 		return;
3178 
3179 	/* ->rwi_list is stable now (no one else is removing entries) */
3180 
3181 	/* ibmvnic_probe() may have purged the reset queue after we were
3182 	 * scheduled to process a reset so there maybe no resets to process.
3183 	 * Before setting the ->resetting bit though, we have to make sure
3184 	 * that there is infact a reset to process. Otherwise we may race
3185 	 * with ibmvnic_open() and end up leaving the vnic down:
3186 	 *
3187 	 *	__ibmvnic_reset()	    ibmvnic_open()
3188 	 *	-----------------	    --------------
3189 	 *
3190 	 *  set ->resetting bit
3191 	 *  				find ->resetting bit is set
3192 	 *  				set ->state to IBMVNIC_OPEN (i.e
3193 	 *  				assume reset will open device)
3194 	 *  				return
3195 	 *  find reset queue empty
3196 	 *  return
3197 	 *
3198 	 *  	Neither performed vnic login/open and vnic stays down
3199 	 *
3200 	 * If we hold the lock and conditionally set the bit, either we
3201 	 * or ibmvnic_open() will complete the open.
3202 	 */
3203 	need_reset = false;
3204 	spin_lock(&adapter->rwi_lock);
3205 	if (!list_empty(&adapter->rwi_list)) {
3206 		if (test_and_set_bit_lock(0, &adapter->resetting)) {
3207 			queue_delayed_work(system_long_wq,
3208 					   &adapter->ibmvnic_delayed_reset,
3209 					   IBMVNIC_RESET_DELAY);
3210 		} else {
3211 			need_reset = true;
3212 		}
3213 	}
3214 	spin_unlock(&adapter->rwi_lock);
3215 
3216 	if (!need_reset)
3217 		return;
3218 
3219 	rwi = get_next_rwi(adapter);
3220 	while (rwi) {
3221 		spin_lock_irqsave(&adapter->state_lock, flags);
3222 
3223 		if (adapter->state == VNIC_REMOVING ||
3224 		    adapter->state == VNIC_REMOVED) {
3225 			spin_unlock_irqrestore(&adapter->state_lock, flags);
3226 			kfree(rwi);
3227 			rc = EBUSY;
3228 			break;
3229 		}
3230 
3231 		if (!saved_state) {
3232 			reset_state = adapter->state;
3233 			saved_state = true;
3234 		}
3235 		spin_unlock_irqrestore(&adapter->state_lock, flags);
3236 
3237 		if (rwi->reset_reason == VNIC_RESET_PASSIVE_INIT) {
3238 			rtnl_lock();
3239 			rc = do_passive_init(adapter);
3240 			rtnl_unlock();
3241 			if (!rc)
3242 				netif_carrier_on(adapter->netdev);
3243 		} else if (adapter->force_reset_recovery) {
3244 			/* Since we are doing a hard reset now, clear the
3245 			 * failover_pending flag so we don't ignore any
3246 			 * future MOBILITY or other resets.
3247 			 */
3248 			adapter->failover_pending = false;
3249 
3250 			/* Transport event occurred during previous reset */
3251 			if (adapter->wait_for_reset) {
3252 				/* Previous was CHANGE_PARAM; caller locked */
3253 				adapter->force_reset_recovery = false;
3254 				rc = do_hard_reset(adapter, rwi, reset_state);
3255 			} else {
3256 				rtnl_lock();
3257 				adapter->force_reset_recovery = false;
3258 				rc = do_hard_reset(adapter, rwi, reset_state);
3259 				rtnl_unlock();
3260 			}
3261 			if (rc)
3262 				num_fails++;
3263 			else
3264 				num_fails = 0;
3265 
3266 			/* If auto-priority-failover is enabled we can get
3267 			 * back to back failovers during resets, resulting
3268 			 * in at least two failed resets (from high-priority
3269 			 * backing device to low-priority one and then back)
3270 			 * If resets continue to fail beyond that, give the
3271 			 * adapter some time to settle down before retrying.
3272 			 */
3273 			if (num_fails >= 3) {
3274 				netdev_dbg(adapter->netdev,
3275 					   "[S:%s] Hard reset failed %d times, waiting 60 secs\n",
3276 					   adapter_state_to_string(adapter->state),
3277 					   num_fails);
3278 				set_current_state(TASK_UNINTERRUPTIBLE);
3279 				schedule_timeout(60 * HZ);
3280 			}
3281 		} else {
3282 			rc = do_reset(adapter, rwi, reset_state);
3283 		}
3284 		tmprwi = rwi;
3285 		adapter->last_reset_time = jiffies;
3286 
3287 		if (rc)
3288 			netdev_dbg(adapter->netdev, "Reset failed, rc=%d\n", rc);
3289 
3290 		rwi = get_next_rwi(adapter);
3291 
3292 		/*
3293 		 * If there are no resets queued and the previous reset failed,
3294 		 * the adapter would be in an undefined state. So retry the
3295 		 * previous reset as a hard reset.
3296 		 *
3297 		 * Else, free the previous rwi and, if there is another reset
3298 		 * queued, process the new reset even if previous reset failed
3299 		 * (the previous reset could have failed because of a fail
3300 		 * over for instance, so process the fail over).
3301 		 */
3302 		if (!rwi && rc)
3303 			rwi = tmprwi;
3304 		else
3305 			kfree(tmprwi);
3306 
3307 		if (rwi && (rwi->reset_reason == VNIC_RESET_FAILOVER ||
3308 			    rwi->reset_reason == VNIC_RESET_MOBILITY || rc))
3309 			adapter->force_reset_recovery = true;
3310 	}
3311 
3312 	if (adapter->wait_for_reset) {
3313 		adapter->reset_done_rc = rc;
3314 		complete(&adapter->reset_done);
3315 	}
3316 
3317 	clear_bit_unlock(0, &adapter->resetting);
3318 
3319 	netdev_dbg(adapter->netdev,
3320 		   "[S:%s FRR:%d WFR:%d] Done processing resets\n",
3321 		   adapter_state_to_string(adapter->state),
3322 		   adapter->force_reset_recovery,
3323 		   adapter->wait_for_reset);
3324 }
3325 
3326 static void __ibmvnic_delayed_reset(struct work_struct *work)
3327 {
3328 	struct ibmvnic_adapter *adapter;
3329 
3330 	adapter = container_of(work, struct ibmvnic_adapter,
3331 			       ibmvnic_delayed_reset.work);
3332 	__ibmvnic_reset(&adapter->ibmvnic_reset);
3333 }
3334 
3335 static void flush_reset_queue(struct ibmvnic_adapter *adapter)
3336 {
3337 	struct list_head *entry, *tmp_entry;
3338 
3339 	if (!list_empty(&adapter->rwi_list)) {
3340 		list_for_each_safe(entry, tmp_entry, &adapter->rwi_list) {
3341 			list_del(entry);
3342 			kfree(list_entry(entry, struct ibmvnic_rwi, list));
3343 		}
3344 	}
3345 }
3346 
3347 static int ibmvnic_reset(struct ibmvnic_adapter *adapter,
3348 			 enum ibmvnic_reset_reason reason)
3349 {
3350 	struct net_device *netdev = adapter->netdev;
3351 	struct ibmvnic_rwi *rwi, *tmp;
3352 	unsigned long flags;
3353 	int ret;
3354 
3355 	spin_lock_irqsave(&adapter->rwi_lock, flags);
3356 
3357 	/* If failover is pending don't schedule any other reset.
3358 	 * Instead let the failover complete. If there is already a
3359 	 * a failover reset scheduled, we will detect and drop the
3360 	 * duplicate reset when walking the ->rwi_list below.
3361 	 */
3362 	if (adapter->state == VNIC_REMOVING ||
3363 	    adapter->state == VNIC_REMOVED ||
3364 	    (adapter->failover_pending && reason != VNIC_RESET_FAILOVER)) {
3365 		ret = EBUSY;
3366 		netdev_dbg(netdev, "Adapter removing or pending failover, skipping reset\n");
3367 		goto err;
3368 	}
3369 
3370 	list_for_each_entry(tmp, &adapter->rwi_list, list) {
3371 		if (tmp->reset_reason == reason) {
3372 			netdev_dbg(netdev, "Skipping matching reset, reason=%s\n",
3373 				   reset_reason_to_string(reason));
3374 			ret = EBUSY;
3375 			goto err;
3376 		}
3377 	}
3378 
3379 	rwi = kzalloc(sizeof(*rwi), GFP_ATOMIC);
3380 	if (!rwi) {
3381 		ret = ENOMEM;
3382 		goto err;
3383 	}
3384 	/* if we just received a transport event,
3385 	 * flush reset queue and process this reset
3386 	 */
3387 	if (adapter->force_reset_recovery)
3388 		flush_reset_queue(adapter);
3389 
3390 	rwi->reset_reason = reason;
3391 	list_add_tail(&rwi->list, &adapter->rwi_list);
3392 	netdev_dbg(adapter->netdev, "Scheduling reset (reason %s)\n",
3393 		   reset_reason_to_string(reason));
3394 	queue_work(system_long_wq, &adapter->ibmvnic_reset);
3395 
3396 	ret = 0;
3397 err:
3398 	/* ibmvnic_close() below can block, so drop the lock first */
3399 	spin_unlock_irqrestore(&adapter->rwi_lock, flags);
3400 
3401 	if (ret == ENOMEM)
3402 		ibmvnic_close(netdev);
3403 
3404 	return -ret;
3405 }
3406 
3407 static void ibmvnic_tx_timeout(struct net_device *dev, unsigned int txqueue)
3408 {
3409 	struct ibmvnic_adapter *adapter = netdev_priv(dev);
3410 
3411 	if (test_bit(0, &adapter->resetting)) {
3412 		netdev_err(adapter->netdev,
3413 			   "Adapter is resetting, skip timeout reset\n");
3414 		return;
3415 	}
3416 	/* No queuing up reset until at least 5 seconds (default watchdog val)
3417 	 * after last reset
3418 	 */
3419 	if (time_before(jiffies, (adapter->last_reset_time + dev->watchdog_timeo))) {
3420 		netdev_dbg(dev, "Not yet time to tx timeout.\n");
3421 		return;
3422 	}
3423 	ibmvnic_reset(adapter, VNIC_RESET_TIMEOUT);
3424 }
3425 
3426 static void remove_buff_from_pool(struct ibmvnic_adapter *adapter,
3427 				  struct ibmvnic_rx_buff *rx_buff)
3428 {
3429 	struct ibmvnic_rx_pool *pool = &adapter->rx_pool[rx_buff->pool_index];
3430 
3431 	rx_buff->skb = NULL;
3432 
3433 	pool->free_map[pool->next_alloc] = (int)(rx_buff - pool->rx_buff);
3434 	pool->next_alloc = (pool->next_alloc + 1) % pool->size;
3435 
3436 	atomic_dec(&pool->available);
3437 }
3438 
3439 static int ibmvnic_poll(struct napi_struct *napi, int budget)
3440 {
3441 	struct ibmvnic_sub_crq_queue *rx_scrq;
3442 	struct ibmvnic_adapter *adapter;
3443 	struct net_device *netdev;
3444 	int frames_processed;
3445 	int scrq_num;
3446 
3447 	netdev = napi->dev;
3448 	adapter = netdev_priv(netdev);
3449 	scrq_num = (int)(napi - adapter->napi);
3450 	frames_processed = 0;
3451 	rx_scrq = adapter->rx_scrq[scrq_num];
3452 
3453 restart_poll:
3454 	while (frames_processed < budget) {
3455 		struct sk_buff *skb;
3456 		struct ibmvnic_rx_buff *rx_buff;
3457 		union sub_crq *next;
3458 		u32 length;
3459 		u16 offset;
3460 		u8 flags = 0;
3461 
3462 		if (unlikely(test_bit(0, &adapter->resetting) &&
3463 			     adapter->reset_reason != VNIC_RESET_NON_FATAL)) {
3464 			enable_scrq_irq(adapter, rx_scrq);
3465 			napi_complete_done(napi, frames_processed);
3466 			return frames_processed;
3467 		}
3468 
3469 		if (!pending_scrq(adapter, rx_scrq))
3470 			break;
3471 		next = ibmvnic_next_scrq(adapter, rx_scrq);
3472 		rx_buff = (struct ibmvnic_rx_buff *)
3473 			  be64_to_cpu(next->rx_comp.correlator);
3474 		/* do error checking */
3475 		if (next->rx_comp.rc) {
3476 			netdev_dbg(netdev, "rx buffer returned with rc %x\n",
3477 				   be16_to_cpu(next->rx_comp.rc));
3478 			/* free the entry */
3479 			next->rx_comp.first = 0;
3480 			dev_kfree_skb_any(rx_buff->skb);
3481 			remove_buff_from_pool(adapter, rx_buff);
3482 			continue;
3483 		} else if (!rx_buff->skb) {
3484 			/* free the entry */
3485 			next->rx_comp.first = 0;
3486 			remove_buff_from_pool(adapter, rx_buff);
3487 			continue;
3488 		}
3489 
3490 		length = be32_to_cpu(next->rx_comp.len);
3491 		offset = be16_to_cpu(next->rx_comp.off_frame_data);
3492 		flags = next->rx_comp.flags;
3493 		skb = rx_buff->skb;
3494 		/* load long_term_buff before copying to skb */
3495 		dma_rmb();
3496 		skb_copy_to_linear_data(skb, rx_buff->data + offset,
3497 					length);
3498 
3499 		/* VLAN Header has been stripped by the system firmware and
3500 		 * needs to be inserted by the driver
3501 		 */
3502 		if (adapter->rx_vlan_header_insertion &&
3503 		    (flags & IBMVNIC_VLAN_STRIPPED))
3504 			__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q),
3505 					       ntohs(next->rx_comp.vlan_tci));
3506 
3507 		/* free the entry */
3508 		next->rx_comp.first = 0;
3509 		remove_buff_from_pool(adapter, rx_buff);
3510 
3511 		skb_put(skb, length);
3512 		skb->protocol = eth_type_trans(skb, netdev);
3513 		skb_record_rx_queue(skb, scrq_num);
3514 
3515 		if (flags & IBMVNIC_IP_CHKSUM_GOOD &&
3516 		    flags & IBMVNIC_TCP_UDP_CHKSUM_GOOD) {
3517 			skb->ip_summed = CHECKSUM_UNNECESSARY;
3518 		}
3519 
3520 		length = skb->len;
3521 		napi_gro_receive(napi, skb); /* send it up */
3522 		netdev->stats.rx_packets++;
3523 		netdev->stats.rx_bytes += length;
3524 		adapter->rx_stats_buffers[scrq_num].packets++;
3525 		adapter->rx_stats_buffers[scrq_num].bytes += length;
3526 		frames_processed++;
3527 	}
3528 
3529 	if (adapter->state != VNIC_CLOSING &&
3530 	    ((atomic_read(&adapter->rx_pool[scrq_num].available) <
3531 	      adapter->req_rx_add_entries_per_subcrq / 2) ||
3532 	      frames_processed < budget))
3533 		replenish_rx_pool(adapter, &adapter->rx_pool[scrq_num]);
3534 	if (frames_processed < budget) {
3535 		if (napi_complete_done(napi, frames_processed)) {
3536 			enable_scrq_irq(adapter, rx_scrq);
3537 			if (pending_scrq(adapter, rx_scrq)) {
3538 				if (napi_schedule(napi)) {
3539 					disable_scrq_irq(adapter, rx_scrq);
3540 					goto restart_poll;
3541 				}
3542 			}
3543 		}
3544 	}
3545 	return frames_processed;
3546 }
3547 
3548 static int wait_for_reset(struct ibmvnic_adapter *adapter)
3549 {
3550 	int rc, ret;
3551 
3552 	adapter->fallback.mtu = adapter->req_mtu;
3553 	adapter->fallback.rx_queues = adapter->req_rx_queues;
3554 	adapter->fallback.tx_queues = adapter->req_tx_queues;
3555 	adapter->fallback.rx_entries = adapter->req_rx_add_entries_per_subcrq;
3556 	adapter->fallback.tx_entries = adapter->req_tx_entries_per_subcrq;
3557 
3558 	reinit_completion(&adapter->reset_done);
3559 	adapter->wait_for_reset = true;
3560 	rc = ibmvnic_reset(adapter, VNIC_RESET_CHANGE_PARAM);
3561 
3562 	if (rc) {
3563 		ret = rc;
3564 		goto out;
3565 	}
3566 	rc = ibmvnic_wait_for_completion(adapter, &adapter->reset_done, 60000);
3567 	if (rc) {
3568 		ret = -ENODEV;
3569 		goto out;
3570 	}
3571 
3572 	ret = 0;
3573 	if (adapter->reset_done_rc) {
3574 		ret = -EIO;
3575 		adapter->desired.mtu = adapter->fallback.mtu;
3576 		adapter->desired.rx_queues = adapter->fallback.rx_queues;
3577 		adapter->desired.tx_queues = adapter->fallback.tx_queues;
3578 		adapter->desired.rx_entries = adapter->fallback.rx_entries;
3579 		adapter->desired.tx_entries = adapter->fallback.tx_entries;
3580 
3581 		reinit_completion(&adapter->reset_done);
3582 		adapter->wait_for_reset = true;
3583 		rc = ibmvnic_reset(adapter, VNIC_RESET_CHANGE_PARAM);
3584 		if (rc) {
3585 			ret = rc;
3586 			goto out;
3587 		}
3588 		rc = ibmvnic_wait_for_completion(adapter, &adapter->reset_done,
3589 						 60000);
3590 		if (rc) {
3591 			ret = -ENODEV;
3592 			goto out;
3593 		}
3594 	}
3595 out:
3596 	adapter->wait_for_reset = false;
3597 
3598 	return ret;
3599 }
3600 
3601 static int ibmvnic_change_mtu(struct net_device *netdev, int new_mtu)
3602 {
3603 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
3604 
3605 	adapter->desired.mtu = new_mtu + ETH_HLEN;
3606 
3607 	return wait_for_reset(adapter);
3608 }
3609 
3610 static netdev_features_t ibmvnic_features_check(struct sk_buff *skb,
3611 						struct net_device *dev,
3612 						netdev_features_t features)
3613 {
3614 	/* Some backing hardware adapters can not
3615 	 * handle packets with a MSS less than 224
3616 	 * or with only one segment.
3617 	 */
3618 	if (skb_is_gso(skb)) {
3619 		if (skb_shinfo(skb)->gso_size < 224 ||
3620 		    skb_shinfo(skb)->gso_segs == 1)
3621 			features &= ~NETIF_F_GSO_MASK;
3622 	}
3623 
3624 	return features;
3625 }
3626 
3627 static const struct net_device_ops ibmvnic_netdev_ops = {
3628 	.ndo_open		= ibmvnic_open,
3629 	.ndo_stop		= ibmvnic_close,
3630 	.ndo_start_xmit		= ibmvnic_xmit,
3631 	.ndo_set_rx_mode	= ibmvnic_set_multi,
3632 	.ndo_set_mac_address	= ibmvnic_set_mac,
3633 	.ndo_validate_addr	= eth_validate_addr,
3634 	.ndo_tx_timeout		= ibmvnic_tx_timeout,
3635 	.ndo_change_mtu		= ibmvnic_change_mtu,
3636 	.ndo_features_check     = ibmvnic_features_check,
3637 };
3638 
3639 /* ethtool functions */
3640 
3641 static int ibmvnic_get_link_ksettings(struct net_device *netdev,
3642 				      struct ethtool_link_ksettings *cmd)
3643 {
3644 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
3645 	int rc;
3646 
3647 	rc = send_query_phys_parms(adapter);
3648 	if (rc) {
3649 		adapter->speed = SPEED_UNKNOWN;
3650 		adapter->duplex = DUPLEX_UNKNOWN;
3651 	}
3652 	cmd->base.speed = adapter->speed;
3653 	cmd->base.duplex = adapter->duplex;
3654 	cmd->base.port = PORT_FIBRE;
3655 	cmd->base.phy_address = 0;
3656 	cmd->base.autoneg = AUTONEG_ENABLE;
3657 
3658 	return 0;
3659 }
3660 
3661 static void ibmvnic_get_drvinfo(struct net_device *netdev,
3662 				struct ethtool_drvinfo *info)
3663 {
3664 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
3665 
3666 	strscpy(info->driver, ibmvnic_driver_name, sizeof(info->driver));
3667 	strscpy(info->version, IBMVNIC_DRIVER_VERSION, sizeof(info->version));
3668 	strscpy(info->fw_version, adapter->fw_version,
3669 		sizeof(info->fw_version));
3670 }
3671 
3672 static u32 ibmvnic_get_msglevel(struct net_device *netdev)
3673 {
3674 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
3675 
3676 	return adapter->msg_enable;
3677 }
3678 
3679 static void ibmvnic_set_msglevel(struct net_device *netdev, u32 data)
3680 {
3681 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
3682 
3683 	adapter->msg_enable = data;
3684 }
3685 
3686 static u32 ibmvnic_get_link(struct net_device *netdev)
3687 {
3688 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
3689 
3690 	/* Don't need to send a query because we request a logical link up at
3691 	 * init and then we wait for link state indications
3692 	 */
3693 	return adapter->logical_link_state;
3694 }
3695 
3696 static void ibmvnic_get_ringparam(struct net_device *netdev,
3697 				  struct ethtool_ringparam *ring,
3698 				  struct kernel_ethtool_ringparam *kernel_ring,
3699 				  struct netlink_ext_ack *extack)
3700 {
3701 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
3702 
3703 	ring->rx_max_pending = adapter->max_rx_add_entries_per_subcrq;
3704 	ring->tx_max_pending = adapter->max_tx_entries_per_subcrq;
3705 	ring->rx_mini_max_pending = 0;
3706 	ring->rx_jumbo_max_pending = 0;
3707 	ring->rx_pending = adapter->req_rx_add_entries_per_subcrq;
3708 	ring->tx_pending = adapter->req_tx_entries_per_subcrq;
3709 	ring->rx_mini_pending = 0;
3710 	ring->rx_jumbo_pending = 0;
3711 }
3712 
3713 static int ibmvnic_set_ringparam(struct net_device *netdev,
3714 				 struct ethtool_ringparam *ring,
3715 				 struct kernel_ethtool_ringparam *kernel_ring,
3716 				 struct netlink_ext_ack *extack)
3717 {
3718 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
3719 
3720 	if (ring->rx_pending > adapter->max_rx_add_entries_per_subcrq  ||
3721 	    ring->tx_pending > adapter->max_tx_entries_per_subcrq) {
3722 		netdev_err(netdev, "Invalid request.\n");
3723 		netdev_err(netdev, "Max tx buffers = %llu\n",
3724 			   adapter->max_rx_add_entries_per_subcrq);
3725 		netdev_err(netdev, "Max rx buffers = %llu\n",
3726 			   adapter->max_tx_entries_per_subcrq);
3727 		return -EINVAL;
3728 	}
3729 
3730 	adapter->desired.rx_entries = ring->rx_pending;
3731 	adapter->desired.tx_entries = ring->tx_pending;
3732 
3733 	return wait_for_reset(adapter);
3734 }
3735 
3736 static void ibmvnic_get_channels(struct net_device *netdev,
3737 				 struct ethtool_channels *channels)
3738 {
3739 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
3740 
3741 	channels->max_rx = adapter->max_rx_queues;
3742 	channels->max_tx = adapter->max_tx_queues;
3743 	channels->max_other = 0;
3744 	channels->max_combined = 0;
3745 	channels->rx_count = adapter->req_rx_queues;
3746 	channels->tx_count = adapter->req_tx_queues;
3747 	channels->other_count = 0;
3748 	channels->combined_count = 0;
3749 }
3750 
3751 static int ibmvnic_set_channels(struct net_device *netdev,
3752 				struct ethtool_channels *channels)
3753 {
3754 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
3755 
3756 	adapter->desired.rx_queues = channels->rx_count;
3757 	adapter->desired.tx_queues = channels->tx_count;
3758 
3759 	return wait_for_reset(adapter);
3760 }
3761 
3762 static void ibmvnic_get_strings(struct net_device *dev, u32 stringset, u8 *data)
3763 {
3764 	struct ibmvnic_adapter *adapter = netdev_priv(dev);
3765 	int i;
3766 
3767 	if (stringset != ETH_SS_STATS)
3768 		return;
3769 
3770 	for (i = 0; i < ARRAY_SIZE(ibmvnic_stats); i++, data += ETH_GSTRING_LEN)
3771 		memcpy(data, ibmvnic_stats[i].name, ETH_GSTRING_LEN);
3772 
3773 	for (i = 0; i < adapter->req_tx_queues; i++) {
3774 		snprintf(data, ETH_GSTRING_LEN, "tx%d_packets", i);
3775 		data += ETH_GSTRING_LEN;
3776 
3777 		snprintf(data, ETH_GSTRING_LEN, "tx%d_bytes", i);
3778 		data += ETH_GSTRING_LEN;
3779 
3780 		snprintf(data, ETH_GSTRING_LEN, "tx%d_dropped_packets", i);
3781 		data += ETH_GSTRING_LEN;
3782 	}
3783 
3784 	for (i = 0; i < adapter->req_rx_queues; i++) {
3785 		snprintf(data, ETH_GSTRING_LEN, "rx%d_packets", i);
3786 		data += ETH_GSTRING_LEN;
3787 
3788 		snprintf(data, ETH_GSTRING_LEN, "rx%d_bytes", i);
3789 		data += ETH_GSTRING_LEN;
3790 
3791 		snprintf(data, ETH_GSTRING_LEN, "rx%d_interrupts", i);
3792 		data += ETH_GSTRING_LEN;
3793 	}
3794 }
3795 
3796 static int ibmvnic_get_sset_count(struct net_device *dev, int sset)
3797 {
3798 	struct ibmvnic_adapter *adapter = netdev_priv(dev);
3799 
3800 	switch (sset) {
3801 	case ETH_SS_STATS:
3802 		return ARRAY_SIZE(ibmvnic_stats) +
3803 		       adapter->req_tx_queues * NUM_TX_STATS +
3804 		       adapter->req_rx_queues * NUM_RX_STATS;
3805 	default:
3806 		return -EOPNOTSUPP;
3807 	}
3808 }
3809 
3810 static void ibmvnic_get_ethtool_stats(struct net_device *dev,
3811 				      struct ethtool_stats *stats, u64 *data)
3812 {
3813 	struct ibmvnic_adapter *adapter = netdev_priv(dev);
3814 	union ibmvnic_crq crq;
3815 	int i, j;
3816 	int rc;
3817 
3818 	memset(&crq, 0, sizeof(crq));
3819 	crq.request_statistics.first = IBMVNIC_CRQ_CMD;
3820 	crq.request_statistics.cmd = REQUEST_STATISTICS;
3821 	crq.request_statistics.ioba = cpu_to_be32(adapter->stats_token);
3822 	crq.request_statistics.len =
3823 	    cpu_to_be32(sizeof(struct ibmvnic_statistics));
3824 
3825 	/* Wait for data to be written */
3826 	reinit_completion(&adapter->stats_done);
3827 	rc = ibmvnic_send_crq(adapter, &crq);
3828 	if (rc)
3829 		return;
3830 	rc = ibmvnic_wait_for_completion(adapter, &adapter->stats_done, 10000);
3831 	if (rc)
3832 		return;
3833 
3834 	for (i = 0; i < ARRAY_SIZE(ibmvnic_stats); i++)
3835 		data[i] = be64_to_cpu(IBMVNIC_GET_STAT
3836 				      (adapter, ibmvnic_stats[i].offset));
3837 
3838 	for (j = 0; j < adapter->req_tx_queues; j++) {
3839 		data[i] = adapter->tx_stats_buffers[j].packets;
3840 		i++;
3841 		data[i] = adapter->tx_stats_buffers[j].bytes;
3842 		i++;
3843 		data[i] = adapter->tx_stats_buffers[j].dropped_packets;
3844 		i++;
3845 	}
3846 
3847 	for (j = 0; j < adapter->req_rx_queues; j++) {
3848 		data[i] = adapter->rx_stats_buffers[j].packets;
3849 		i++;
3850 		data[i] = adapter->rx_stats_buffers[j].bytes;
3851 		i++;
3852 		data[i] = adapter->rx_stats_buffers[j].interrupts;
3853 		i++;
3854 	}
3855 }
3856 
3857 static const struct ethtool_ops ibmvnic_ethtool_ops = {
3858 	.get_drvinfo		= ibmvnic_get_drvinfo,
3859 	.get_msglevel		= ibmvnic_get_msglevel,
3860 	.set_msglevel		= ibmvnic_set_msglevel,
3861 	.get_link		= ibmvnic_get_link,
3862 	.get_ringparam		= ibmvnic_get_ringparam,
3863 	.set_ringparam		= ibmvnic_set_ringparam,
3864 	.get_channels		= ibmvnic_get_channels,
3865 	.set_channels		= ibmvnic_set_channels,
3866 	.get_strings            = ibmvnic_get_strings,
3867 	.get_sset_count         = ibmvnic_get_sset_count,
3868 	.get_ethtool_stats	= ibmvnic_get_ethtool_stats,
3869 	.get_link_ksettings	= ibmvnic_get_link_ksettings,
3870 };
3871 
3872 /* Routines for managing CRQs/sCRQs  */
3873 
3874 static int reset_one_sub_crq_queue(struct ibmvnic_adapter *adapter,
3875 				   struct ibmvnic_sub_crq_queue *scrq)
3876 {
3877 	int rc;
3878 
3879 	if (!scrq) {
3880 		netdev_dbg(adapter->netdev, "Invalid scrq reset.\n");
3881 		return -EINVAL;
3882 	}
3883 
3884 	if (scrq->irq) {
3885 		free_irq(scrq->irq, scrq);
3886 		irq_dispose_mapping(scrq->irq);
3887 		scrq->irq = 0;
3888 	}
3889 
3890 	if (scrq->msgs) {
3891 		memset(scrq->msgs, 0, 4 * PAGE_SIZE);
3892 		atomic_set(&scrq->used, 0);
3893 		scrq->cur = 0;
3894 		scrq->ind_buf.index = 0;
3895 	} else {
3896 		netdev_dbg(adapter->netdev, "Invalid scrq reset\n");
3897 		return -EINVAL;
3898 	}
3899 
3900 	rc = h_reg_sub_crq(adapter->vdev->unit_address, scrq->msg_token,
3901 			   4 * PAGE_SIZE, &scrq->crq_num, &scrq->hw_irq);
3902 	return rc;
3903 }
3904 
3905 static int reset_sub_crq_queues(struct ibmvnic_adapter *adapter)
3906 {
3907 	int i, rc;
3908 
3909 	if (!adapter->tx_scrq || !adapter->rx_scrq)
3910 		return -EINVAL;
3911 
3912 	ibmvnic_clean_affinity(adapter);
3913 
3914 	for (i = 0; i < adapter->req_tx_queues; i++) {
3915 		netdev_dbg(adapter->netdev, "Re-setting tx_scrq[%d]\n", i);
3916 		rc = reset_one_sub_crq_queue(adapter, adapter->tx_scrq[i]);
3917 		if (rc)
3918 			return rc;
3919 	}
3920 
3921 	for (i = 0; i < adapter->req_rx_queues; i++) {
3922 		netdev_dbg(adapter->netdev, "Re-setting rx_scrq[%d]\n", i);
3923 		rc = reset_one_sub_crq_queue(adapter, adapter->rx_scrq[i]);
3924 		if (rc)
3925 			return rc;
3926 	}
3927 
3928 	return rc;
3929 }
3930 
3931 static void release_sub_crq_queue(struct ibmvnic_adapter *adapter,
3932 				  struct ibmvnic_sub_crq_queue *scrq,
3933 				  bool do_h_free)
3934 {
3935 	struct device *dev = &adapter->vdev->dev;
3936 	long rc;
3937 
3938 	netdev_dbg(adapter->netdev, "Releasing sub-CRQ\n");
3939 
3940 	if (do_h_free) {
3941 		/* Close the sub-crqs */
3942 		do {
3943 			rc = plpar_hcall_norets(H_FREE_SUB_CRQ,
3944 						adapter->vdev->unit_address,
3945 						scrq->crq_num);
3946 		} while (rc == H_BUSY || H_IS_LONG_BUSY(rc));
3947 
3948 		if (rc) {
3949 			netdev_err(adapter->netdev,
3950 				   "Failed to release sub-CRQ %16lx, rc = %ld\n",
3951 				   scrq->crq_num, rc);
3952 		}
3953 	}
3954 
3955 	dma_free_coherent(dev,
3956 			  IBMVNIC_IND_ARR_SZ,
3957 			  scrq->ind_buf.indir_arr,
3958 			  scrq->ind_buf.indir_dma);
3959 
3960 	dma_unmap_single(dev, scrq->msg_token, 4 * PAGE_SIZE,
3961 			 DMA_BIDIRECTIONAL);
3962 	free_pages((unsigned long)scrq->msgs, 2);
3963 	free_cpumask_var(scrq->affinity_mask);
3964 	kfree(scrq);
3965 }
3966 
3967 static struct ibmvnic_sub_crq_queue *init_sub_crq_queue(struct ibmvnic_adapter
3968 							*adapter)
3969 {
3970 	struct device *dev = &adapter->vdev->dev;
3971 	struct ibmvnic_sub_crq_queue *scrq;
3972 	int rc;
3973 
3974 	scrq = kzalloc(sizeof(*scrq), GFP_KERNEL);
3975 	if (!scrq)
3976 		return NULL;
3977 
3978 	scrq->msgs =
3979 		(union sub_crq *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, 2);
3980 	if (!scrq->msgs) {
3981 		dev_warn(dev, "Couldn't allocate crq queue messages page\n");
3982 		goto zero_page_failed;
3983 	}
3984 	if (!zalloc_cpumask_var(&scrq->affinity_mask, GFP_KERNEL))
3985 		goto cpumask_alloc_failed;
3986 
3987 	scrq->msg_token = dma_map_single(dev, scrq->msgs, 4 * PAGE_SIZE,
3988 					 DMA_BIDIRECTIONAL);
3989 	if (dma_mapping_error(dev, scrq->msg_token)) {
3990 		dev_warn(dev, "Couldn't map crq queue messages page\n");
3991 		goto map_failed;
3992 	}
3993 
3994 	rc = h_reg_sub_crq(adapter->vdev->unit_address, scrq->msg_token,
3995 			   4 * PAGE_SIZE, &scrq->crq_num, &scrq->hw_irq);
3996 
3997 	if (rc == H_RESOURCE)
3998 		rc = ibmvnic_reset_crq(adapter);
3999 
4000 	if (rc == H_CLOSED) {
4001 		dev_warn(dev, "Partner adapter not ready, waiting.\n");
4002 	} else if (rc) {
4003 		dev_warn(dev, "Error %d registering sub-crq\n", rc);
4004 		goto reg_failed;
4005 	}
4006 
4007 	scrq->adapter = adapter;
4008 	scrq->size = 4 * PAGE_SIZE / sizeof(*scrq->msgs);
4009 	scrq->ind_buf.index = 0;
4010 
4011 	scrq->ind_buf.indir_arr =
4012 		dma_alloc_coherent(dev,
4013 				   IBMVNIC_IND_ARR_SZ,
4014 				   &scrq->ind_buf.indir_dma,
4015 				   GFP_KERNEL);
4016 
4017 	if (!scrq->ind_buf.indir_arr)
4018 		goto indir_failed;
4019 
4020 	spin_lock_init(&scrq->lock);
4021 
4022 	netdev_dbg(adapter->netdev,
4023 		   "sub-crq initialized, num %lx, hw_irq=%lx, irq=%x\n",
4024 		   scrq->crq_num, scrq->hw_irq, scrq->irq);
4025 
4026 	return scrq;
4027 
4028 indir_failed:
4029 	do {
4030 		rc = plpar_hcall_norets(H_FREE_SUB_CRQ,
4031 					adapter->vdev->unit_address,
4032 					scrq->crq_num);
4033 	} while (rc == H_BUSY || rc == H_IS_LONG_BUSY(rc));
4034 reg_failed:
4035 	dma_unmap_single(dev, scrq->msg_token, 4 * PAGE_SIZE,
4036 			 DMA_BIDIRECTIONAL);
4037 map_failed:
4038 	free_cpumask_var(scrq->affinity_mask);
4039 cpumask_alloc_failed:
4040 	free_pages((unsigned long)scrq->msgs, 2);
4041 zero_page_failed:
4042 	kfree(scrq);
4043 
4044 	return NULL;
4045 }
4046 
4047 static void release_sub_crqs(struct ibmvnic_adapter *adapter, bool do_h_free)
4048 {
4049 	int i;
4050 
4051 	ibmvnic_clean_affinity(adapter);
4052 	if (adapter->tx_scrq) {
4053 		for (i = 0; i < adapter->num_active_tx_scrqs; i++) {
4054 			if (!adapter->tx_scrq[i])
4055 				continue;
4056 
4057 			netdev_dbg(adapter->netdev, "Releasing tx_scrq[%d]\n",
4058 				   i);
4059 			ibmvnic_tx_scrq_clean_buffer(adapter, adapter->tx_scrq[i]);
4060 			if (adapter->tx_scrq[i]->irq) {
4061 				free_irq(adapter->tx_scrq[i]->irq,
4062 					 adapter->tx_scrq[i]);
4063 				irq_dispose_mapping(adapter->tx_scrq[i]->irq);
4064 				adapter->tx_scrq[i]->irq = 0;
4065 			}
4066 
4067 			release_sub_crq_queue(adapter, adapter->tx_scrq[i],
4068 					      do_h_free);
4069 		}
4070 
4071 		kfree(adapter->tx_scrq);
4072 		adapter->tx_scrq = NULL;
4073 		adapter->num_active_tx_scrqs = 0;
4074 	}
4075 
4076 	/* Clean any remaining outstanding SKBs
4077 	 * we freed the irq so we won't be hearing
4078 	 * from them
4079 	 */
4080 	clean_tx_pools(adapter);
4081 
4082 	if (adapter->rx_scrq) {
4083 		for (i = 0; i < adapter->num_active_rx_scrqs; i++) {
4084 			if (!adapter->rx_scrq[i])
4085 				continue;
4086 
4087 			netdev_dbg(adapter->netdev, "Releasing rx_scrq[%d]\n",
4088 				   i);
4089 			if (adapter->rx_scrq[i]->irq) {
4090 				free_irq(adapter->rx_scrq[i]->irq,
4091 					 adapter->rx_scrq[i]);
4092 				irq_dispose_mapping(adapter->rx_scrq[i]->irq);
4093 				adapter->rx_scrq[i]->irq = 0;
4094 			}
4095 
4096 			release_sub_crq_queue(adapter, adapter->rx_scrq[i],
4097 					      do_h_free);
4098 		}
4099 
4100 		kfree(adapter->rx_scrq);
4101 		adapter->rx_scrq = NULL;
4102 		adapter->num_active_rx_scrqs = 0;
4103 	}
4104 }
4105 
4106 static int disable_scrq_irq(struct ibmvnic_adapter *adapter,
4107 			    struct ibmvnic_sub_crq_queue *scrq)
4108 {
4109 	struct device *dev = &adapter->vdev->dev;
4110 	unsigned long rc;
4111 
4112 	rc = plpar_hcall_norets(H_VIOCTL, adapter->vdev->unit_address,
4113 				H_DISABLE_VIO_INTERRUPT, scrq->hw_irq, 0, 0);
4114 	if (rc)
4115 		dev_err(dev, "Couldn't disable scrq irq 0x%lx. rc=%ld\n",
4116 			scrq->hw_irq, rc);
4117 	return rc;
4118 }
4119 
4120 /* We can not use the IRQ chip EOI handler because that has the
4121  * unintended effect of changing the interrupt priority.
4122  */
4123 static void ibmvnic_xics_eoi(struct device *dev, struct ibmvnic_sub_crq_queue *scrq)
4124 {
4125 	u64 val = 0xff000000 | scrq->hw_irq;
4126 	unsigned long rc;
4127 
4128 	rc = plpar_hcall_norets(H_EOI, val);
4129 	if (rc)
4130 		dev_err(dev, "H_EOI FAILED irq 0x%llx. rc=%ld\n", val, rc);
4131 }
4132 
4133 /* Due to a firmware bug, the hypervisor can send an interrupt to a
4134  * transmit or receive queue just prior to a partition migration.
4135  * Force an EOI after migration.
4136  */
4137 static void ibmvnic_clear_pending_interrupt(struct device *dev,
4138 					    struct ibmvnic_sub_crq_queue *scrq)
4139 {
4140 	if (!xive_enabled())
4141 		ibmvnic_xics_eoi(dev, scrq);
4142 }
4143 
4144 static int enable_scrq_irq(struct ibmvnic_adapter *adapter,
4145 			   struct ibmvnic_sub_crq_queue *scrq)
4146 {
4147 	struct device *dev = &adapter->vdev->dev;
4148 	unsigned long rc;
4149 
4150 	if (scrq->hw_irq > 0x100000000ULL) {
4151 		dev_err(dev, "bad hw_irq = %lx\n", scrq->hw_irq);
4152 		return 1;
4153 	}
4154 
4155 	if (test_bit(0, &adapter->resetting) &&
4156 	    adapter->reset_reason == VNIC_RESET_MOBILITY) {
4157 		ibmvnic_clear_pending_interrupt(dev, scrq);
4158 	}
4159 
4160 	rc = plpar_hcall_norets(H_VIOCTL, adapter->vdev->unit_address,
4161 				H_ENABLE_VIO_INTERRUPT, scrq->hw_irq, 0, 0);
4162 	if (rc)
4163 		dev_err(dev, "Couldn't enable scrq irq 0x%lx. rc=%ld\n",
4164 			scrq->hw_irq, rc);
4165 	return rc;
4166 }
4167 
4168 static int ibmvnic_complete_tx(struct ibmvnic_adapter *adapter,
4169 			       struct ibmvnic_sub_crq_queue *scrq)
4170 {
4171 	struct device *dev = &adapter->vdev->dev;
4172 	struct ibmvnic_tx_pool *tx_pool;
4173 	struct ibmvnic_tx_buff *txbuff;
4174 	struct netdev_queue *txq;
4175 	union sub_crq *next;
4176 	int index;
4177 	int i;
4178 
4179 restart_loop:
4180 	while (pending_scrq(adapter, scrq)) {
4181 		unsigned int pool = scrq->pool_index;
4182 		int num_entries = 0;
4183 		int total_bytes = 0;
4184 		int num_packets = 0;
4185 
4186 		next = ibmvnic_next_scrq(adapter, scrq);
4187 		for (i = 0; i < next->tx_comp.num_comps; i++) {
4188 			index = be32_to_cpu(next->tx_comp.correlators[i]);
4189 			if (index & IBMVNIC_TSO_POOL_MASK) {
4190 				tx_pool = &adapter->tso_pool[pool];
4191 				index &= ~IBMVNIC_TSO_POOL_MASK;
4192 			} else {
4193 				tx_pool = &adapter->tx_pool[pool];
4194 			}
4195 
4196 			txbuff = &tx_pool->tx_buff[index];
4197 			num_packets++;
4198 			num_entries += txbuff->num_entries;
4199 			if (txbuff->skb) {
4200 				total_bytes += txbuff->skb->len;
4201 				if (next->tx_comp.rcs[i]) {
4202 					dev_err(dev, "tx error %x\n",
4203 						next->tx_comp.rcs[i]);
4204 					dev_kfree_skb_irq(txbuff->skb);
4205 				} else {
4206 					dev_consume_skb_irq(txbuff->skb);
4207 				}
4208 				txbuff->skb = NULL;
4209 			} else {
4210 				netdev_warn(adapter->netdev,
4211 					    "TX completion received with NULL socket buffer\n");
4212 			}
4213 			tx_pool->free_map[tx_pool->producer_index] = index;
4214 			tx_pool->producer_index =
4215 				(tx_pool->producer_index + 1) %
4216 					tx_pool->num_buffers;
4217 		}
4218 		/* remove tx_comp scrq*/
4219 		next->tx_comp.first = 0;
4220 
4221 		txq = netdev_get_tx_queue(adapter->netdev, scrq->pool_index);
4222 		netdev_tx_completed_queue(txq, num_packets, total_bytes);
4223 
4224 		if (atomic_sub_return(num_entries, &scrq->used) <=
4225 		    (adapter->req_tx_entries_per_subcrq / 2) &&
4226 		    __netif_subqueue_stopped(adapter->netdev,
4227 					     scrq->pool_index)) {
4228 			rcu_read_lock();
4229 			if (adapter->tx_queues_active) {
4230 				netif_wake_subqueue(adapter->netdev,
4231 						    scrq->pool_index);
4232 				netdev_dbg(adapter->netdev,
4233 					   "Started queue %d\n",
4234 					   scrq->pool_index);
4235 			}
4236 			rcu_read_unlock();
4237 		}
4238 	}
4239 
4240 	enable_scrq_irq(adapter, scrq);
4241 
4242 	if (pending_scrq(adapter, scrq)) {
4243 		disable_scrq_irq(adapter, scrq);
4244 		goto restart_loop;
4245 	}
4246 
4247 	return 0;
4248 }
4249 
4250 static irqreturn_t ibmvnic_interrupt_tx(int irq, void *instance)
4251 {
4252 	struct ibmvnic_sub_crq_queue *scrq = instance;
4253 	struct ibmvnic_adapter *adapter = scrq->adapter;
4254 
4255 	disable_scrq_irq(adapter, scrq);
4256 	ibmvnic_complete_tx(adapter, scrq);
4257 
4258 	return IRQ_HANDLED;
4259 }
4260 
4261 static irqreturn_t ibmvnic_interrupt_rx(int irq, void *instance)
4262 {
4263 	struct ibmvnic_sub_crq_queue *scrq = instance;
4264 	struct ibmvnic_adapter *adapter = scrq->adapter;
4265 
4266 	/* When booting a kdump kernel we can hit pending interrupts
4267 	 * prior to completing driver initialization.
4268 	 */
4269 	if (unlikely(adapter->state != VNIC_OPEN))
4270 		return IRQ_NONE;
4271 
4272 	adapter->rx_stats_buffers[scrq->scrq_num].interrupts++;
4273 
4274 	if (napi_schedule_prep(&adapter->napi[scrq->scrq_num])) {
4275 		disable_scrq_irq(adapter, scrq);
4276 		__napi_schedule(&adapter->napi[scrq->scrq_num]);
4277 	}
4278 
4279 	return IRQ_HANDLED;
4280 }
4281 
4282 static int init_sub_crq_irqs(struct ibmvnic_adapter *adapter)
4283 {
4284 	struct device *dev = &adapter->vdev->dev;
4285 	struct ibmvnic_sub_crq_queue *scrq;
4286 	int i = 0, j = 0;
4287 	int rc = 0;
4288 
4289 	for (i = 0; i < adapter->req_tx_queues; i++) {
4290 		netdev_dbg(adapter->netdev, "Initializing tx_scrq[%d] irq\n",
4291 			   i);
4292 		scrq = adapter->tx_scrq[i];
4293 		scrq->irq = irq_create_mapping(NULL, scrq->hw_irq);
4294 
4295 		if (!scrq->irq) {
4296 			rc = -EINVAL;
4297 			dev_err(dev, "Error mapping irq\n");
4298 			goto req_tx_irq_failed;
4299 		}
4300 
4301 		snprintf(scrq->name, sizeof(scrq->name), "ibmvnic-%x-tx%d",
4302 			 adapter->vdev->unit_address, i);
4303 		rc = request_irq(scrq->irq, ibmvnic_interrupt_tx,
4304 				 0, scrq->name, scrq);
4305 
4306 		if (rc) {
4307 			dev_err(dev, "Couldn't register tx irq 0x%x. rc=%d\n",
4308 				scrq->irq, rc);
4309 			irq_dispose_mapping(scrq->irq);
4310 			goto req_tx_irq_failed;
4311 		}
4312 	}
4313 
4314 	for (i = 0; i < adapter->req_rx_queues; i++) {
4315 		netdev_dbg(adapter->netdev, "Initializing rx_scrq[%d] irq\n",
4316 			   i);
4317 		scrq = adapter->rx_scrq[i];
4318 		scrq->irq = irq_create_mapping(NULL, scrq->hw_irq);
4319 		if (!scrq->irq) {
4320 			rc = -EINVAL;
4321 			dev_err(dev, "Error mapping irq\n");
4322 			goto req_rx_irq_failed;
4323 		}
4324 		snprintf(scrq->name, sizeof(scrq->name), "ibmvnic-%x-rx%d",
4325 			 adapter->vdev->unit_address, i);
4326 		rc = request_irq(scrq->irq, ibmvnic_interrupt_rx,
4327 				 0, scrq->name, scrq);
4328 		if (rc) {
4329 			dev_err(dev, "Couldn't register rx irq 0x%x. rc=%d\n",
4330 				scrq->irq, rc);
4331 			irq_dispose_mapping(scrq->irq);
4332 			goto req_rx_irq_failed;
4333 		}
4334 	}
4335 
4336 	cpus_read_lock();
4337 	ibmvnic_set_affinity(adapter);
4338 	cpus_read_unlock();
4339 
4340 	return rc;
4341 
4342 req_rx_irq_failed:
4343 	for (j = 0; j < i; j++) {
4344 		free_irq(adapter->rx_scrq[j]->irq, adapter->rx_scrq[j]);
4345 		irq_dispose_mapping(adapter->rx_scrq[j]->irq);
4346 	}
4347 	i = adapter->req_tx_queues;
4348 req_tx_irq_failed:
4349 	for (j = 0; j < i; j++) {
4350 		free_irq(adapter->tx_scrq[j]->irq, adapter->tx_scrq[j]);
4351 		irq_dispose_mapping(adapter->tx_scrq[j]->irq);
4352 	}
4353 	release_sub_crqs(adapter, 1);
4354 	return rc;
4355 }
4356 
4357 static int init_sub_crqs(struct ibmvnic_adapter *adapter)
4358 {
4359 	struct device *dev = &adapter->vdev->dev;
4360 	struct ibmvnic_sub_crq_queue **allqueues;
4361 	int registered_queues = 0;
4362 	int total_queues;
4363 	int more = 0;
4364 	int i;
4365 
4366 	total_queues = adapter->req_tx_queues + adapter->req_rx_queues;
4367 
4368 	allqueues = kcalloc(total_queues, sizeof(*allqueues), GFP_KERNEL);
4369 	if (!allqueues)
4370 		return -ENOMEM;
4371 
4372 	for (i = 0; i < total_queues; i++) {
4373 		allqueues[i] = init_sub_crq_queue(adapter);
4374 		if (!allqueues[i]) {
4375 			dev_warn(dev, "Couldn't allocate all sub-crqs\n");
4376 			break;
4377 		}
4378 		registered_queues++;
4379 	}
4380 
4381 	/* Make sure we were able to register the minimum number of queues */
4382 	if (registered_queues <
4383 	    adapter->min_tx_queues + adapter->min_rx_queues) {
4384 		dev_err(dev, "Fatal: Couldn't init  min number of sub-crqs\n");
4385 		goto tx_failed;
4386 	}
4387 
4388 	/* Distribute the failed allocated queues*/
4389 	for (i = 0; i < total_queues - registered_queues + more ; i++) {
4390 		netdev_dbg(adapter->netdev, "Reducing number of queues\n");
4391 		switch (i % 3) {
4392 		case 0:
4393 			if (adapter->req_rx_queues > adapter->min_rx_queues)
4394 				adapter->req_rx_queues--;
4395 			else
4396 				more++;
4397 			break;
4398 		case 1:
4399 			if (adapter->req_tx_queues > adapter->min_tx_queues)
4400 				adapter->req_tx_queues--;
4401 			else
4402 				more++;
4403 			break;
4404 		}
4405 	}
4406 
4407 	adapter->tx_scrq = kcalloc(adapter->req_tx_queues,
4408 				   sizeof(*adapter->tx_scrq), GFP_KERNEL);
4409 	if (!adapter->tx_scrq)
4410 		goto tx_failed;
4411 
4412 	for (i = 0; i < adapter->req_tx_queues; i++) {
4413 		adapter->tx_scrq[i] = allqueues[i];
4414 		adapter->tx_scrq[i]->pool_index = i;
4415 		adapter->num_active_tx_scrqs++;
4416 	}
4417 
4418 	adapter->rx_scrq = kcalloc(adapter->req_rx_queues,
4419 				   sizeof(*adapter->rx_scrq), GFP_KERNEL);
4420 	if (!adapter->rx_scrq)
4421 		goto rx_failed;
4422 
4423 	for (i = 0; i < adapter->req_rx_queues; i++) {
4424 		adapter->rx_scrq[i] = allqueues[i + adapter->req_tx_queues];
4425 		adapter->rx_scrq[i]->scrq_num = i;
4426 		adapter->num_active_rx_scrqs++;
4427 	}
4428 
4429 	kfree(allqueues);
4430 	return 0;
4431 
4432 rx_failed:
4433 	kfree(adapter->tx_scrq);
4434 	adapter->tx_scrq = NULL;
4435 tx_failed:
4436 	for (i = 0; i < registered_queues; i++)
4437 		release_sub_crq_queue(adapter, allqueues[i], 1);
4438 	kfree(allqueues);
4439 	return -ENOMEM;
4440 }
4441 
4442 static void send_request_cap(struct ibmvnic_adapter *adapter, int retry)
4443 {
4444 	struct device *dev = &adapter->vdev->dev;
4445 	union ibmvnic_crq crq;
4446 	int max_entries;
4447 	int cap_reqs;
4448 
4449 	/* We send out 6 or 7 REQUEST_CAPABILITY CRQs below (depending on
4450 	 * the PROMISC flag). Initialize this count upfront. When the tasklet
4451 	 * receives a response to all of these, it will send the next protocol
4452 	 * message (QUERY_IP_OFFLOAD).
4453 	 */
4454 	if (!(adapter->netdev->flags & IFF_PROMISC) ||
4455 	    adapter->promisc_supported)
4456 		cap_reqs = 7;
4457 	else
4458 		cap_reqs = 6;
4459 
4460 	if (!retry) {
4461 		/* Sub-CRQ entries are 32 byte long */
4462 		int entries_page = 4 * PAGE_SIZE / (sizeof(u64) * 4);
4463 
4464 		atomic_set(&adapter->running_cap_crqs, cap_reqs);
4465 
4466 		if (adapter->min_tx_entries_per_subcrq > entries_page ||
4467 		    adapter->min_rx_add_entries_per_subcrq > entries_page) {
4468 			dev_err(dev, "Fatal, invalid entries per sub-crq\n");
4469 			return;
4470 		}
4471 
4472 		if (adapter->desired.mtu)
4473 			adapter->req_mtu = adapter->desired.mtu;
4474 		else
4475 			adapter->req_mtu = adapter->netdev->mtu + ETH_HLEN;
4476 
4477 		if (!adapter->desired.tx_entries)
4478 			adapter->desired.tx_entries =
4479 					adapter->max_tx_entries_per_subcrq;
4480 		if (!adapter->desired.rx_entries)
4481 			adapter->desired.rx_entries =
4482 					adapter->max_rx_add_entries_per_subcrq;
4483 
4484 		max_entries = IBMVNIC_LTB_SET_SIZE /
4485 			      (adapter->req_mtu + IBMVNIC_BUFFER_HLEN);
4486 
4487 		if ((adapter->req_mtu + IBMVNIC_BUFFER_HLEN) *
4488 			adapter->desired.tx_entries > IBMVNIC_LTB_SET_SIZE) {
4489 			adapter->desired.tx_entries = max_entries;
4490 		}
4491 
4492 		if ((adapter->req_mtu + IBMVNIC_BUFFER_HLEN) *
4493 			adapter->desired.rx_entries > IBMVNIC_LTB_SET_SIZE) {
4494 			adapter->desired.rx_entries = max_entries;
4495 		}
4496 
4497 		if (adapter->desired.tx_entries)
4498 			adapter->req_tx_entries_per_subcrq =
4499 					adapter->desired.tx_entries;
4500 		else
4501 			adapter->req_tx_entries_per_subcrq =
4502 					adapter->max_tx_entries_per_subcrq;
4503 
4504 		if (adapter->desired.rx_entries)
4505 			adapter->req_rx_add_entries_per_subcrq =
4506 					adapter->desired.rx_entries;
4507 		else
4508 			adapter->req_rx_add_entries_per_subcrq =
4509 					adapter->max_rx_add_entries_per_subcrq;
4510 
4511 		if (adapter->desired.tx_queues)
4512 			adapter->req_tx_queues =
4513 					adapter->desired.tx_queues;
4514 		else
4515 			adapter->req_tx_queues =
4516 					adapter->opt_tx_comp_sub_queues;
4517 
4518 		if (adapter->desired.rx_queues)
4519 			adapter->req_rx_queues =
4520 					adapter->desired.rx_queues;
4521 		else
4522 			adapter->req_rx_queues =
4523 					adapter->opt_rx_comp_queues;
4524 
4525 		adapter->req_rx_add_queues = adapter->max_rx_add_queues;
4526 	} else {
4527 		atomic_add(cap_reqs, &adapter->running_cap_crqs);
4528 	}
4529 	memset(&crq, 0, sizeof(crq));
4530 	crq.request_capability.first = IBMVNIC_CRQ_CMD;
4531 	crq.request_capability.cmd = REQUEST_CAPABILITY;
4532 
4533 	crq.request_capability.capability = cpu_to_be16(REQ_TX_QUEUES);
4534 	crq.request_capability.number = cpu_to_be64(adapter->req_tx_queues);
4535 	cap_reqs--;
4536 	ibmvnic_send_crq(adapter, &crq);
4537 
4538 	crq.request_capability.capability = cpu_to_be16(REQ_RX_QUEUES);
4539 	crq.request_capability.number = cpu_to_be64(adapter->req_rx_queues);
4540 	cap_reqs--;
4541 	ibmvnic_send_crq(adapter, &crq);
4542 
4543 	crq.request_capability.capability = cpu_to_be16(REQ_RX_ADD_QUEUES);
4544 	crq.request_capability.number = cpu_to_be64(adapter->req_rx_add_queues);
4545 	cap_reqs--;
4546 	ibmvnic_send_crq(adapter, &crq);
4547 
4548 	crq.request_capability.capability =
4549 	    cpu_to_be16(REQ_TX_ENTRIES_PER_SUBCRQ);
4550 	crq.request_capability.number =
4551 	    cpu_to_be64(adapter->req_tx_entries_per_subcrq);
4552 	cap_reqs--;
4553 	ibmvnic_send_crq(adapter, &crq);
4554 
4555 	crq.request_capability.capability =
4556 	    cpu_to_be16(REQ_RX_ADD_ENTRIES_PER_SUBCRQ);
4557 	crq.request_capability.number =
4558 	    cpu_to_be64(adapter->req_rx_add_entries_per_subcrq);
4559 	cap_reqs--;
4560 	ibmvnic_send_crq(adapter, &crq);
4561 
4562 	crq.request_capability.capability = cpu_to_be16(REQ_MTU);
4563 	crq.request_capability.number = cpu_to_be64(adapter->req_mtu);
4564 	cap_reqs--;
4565 	ibmvnic_send_crq(adapter, &crq);
4566 
4567 	if (adapter->netdev->flags & IFF_PROMISC) {
4568 		if (adapter->promisc_supported) {
4569 			crq.request_capability.capability =
4570 			    cpu_to_be16(PROMISC_REQUESTED);
4571 			crq.request_capability.number = cpu_to_be64(1);
4572 			cap_reqs--;
4573 			ibmvnic_send_crq(adapter, &crq);
4574 		}
4575 	} else {
4576 		crq.request_capability.capability =
4577 		    cpu_to_be16(PROMISC_REQUESTED);
4578 		crq.request_capability.number = cpu_to_be64(0);
4579 		cap_reqs--;
4580 		ibmvnic_send_crq(adapter, &crq);
4581 	}
4582 
4583 	/* Keep at end to catch any discrepancy between expected and actual
4584 	 * CRQs sent.
4585 	 */
4586 	WARN_ON(cap_reqs != 0);
4587 }
4588 
4589 static int pending_scrq(struct ibmvnic_adapter *adapter,
4590 			struct ibmvnic_sub_crq_queue *scrq)
4591 {
4592 	union sub_crq *entry = &scrq->msgs[scrq->cur];
4593 	int rc;
4594 
4595 	rc = !!(entry->generic.first & IBMVNIC_CRQ_CMD_RSP);
4596 
4597 	/* Ensure that the SCRQ valid flag is loaded prior to loading the
4598 	 * contents of the SCRQ descriptor
4599 	 */
4600 	dma_rmb();
4601 
4602 	return rc;
4603 }
4604 
4605 static union sub_crq *ibmvnic_next_scrq(struct ibmvnic_adapter *adapter,
4606 					struct ibmvnic_sub_crq_queue *scrq)
4607 {
4608 	union sub_crq *entry;
4609 	unsigned long flags;
4610 
4611 	spin_lock_irqsave(&scrq->lock, flags);
4612 	entry = &scrq->msgs[scrq->cur];
4613 	if (entry->generic.first & IBMVNIC_CRQ_CMD_RSP) {
4614 		if (++scrq->cur == scrq->size)
4615 			scrq->cur = 0;
4616 	} else {
4617 		entry = NULL;
4618 	}
4619 	spin_unlock_irqrestore(&scrq->lock, flags);
4620 
4621 	/* Ensure that the SCRQ valid flag is loaded prior to loading the
4622 	 * contents of the SCRQ descriptor
4623 	 */
4624 	dma_rmb();
4625 
4626 	return entry;
4627 }
4628 
4629 static union ibmvnic_crq *ibmvnic_next_crq(struct ibmvnic_adapter *adapter)
4630 {
4631 	struct ibmvnic_crq_queue *queue = &adapter->crq;
4632 	union ibmvnic_crq *crq;
4633 
4634 	crq = &queue->msgs[queue->cur];
4635 	if (crq->generic.first & IBMVNIC_CRQ_CMD_RSP) {
4636 		if (++queue->cur == queue->size)
4637 			queue->cur = 0;
4638 	} else {
4639 		crq = NULL;
4640 	}
4641 
4642 	return crq;
4643 }
4644 
4645 static void print_subcrq_error(struct device *dev, int rc, const char *func)
4646 {
4647 	switch (rc) {
4648 	case H_PARAMETER:
4649 		dev_warn_ratelimited(dev,
4650 				     "%s failed: Send request is malformed or adapter failover pending. (rc=%d)\n",
4651 				     func, rc);
4652 		break;
4653 	case H_CLOSED:
4654 		dev_warn_ratelimited(dev,
4655 				     "%s failed: Backing queue closed. Adapter is down or failover pending. (rc=%d)\n",
4656 				     func, rc);
4657 		break;
4658 	default:
4659 		dev_err_ratelimited(dev, "%s failed: (rc=%d)\n", func, rc);
4660 		break;
4661 	}
4662 }
4663 
4664 static int send_subcrq_indirect(struct ibmvnic_adapter *adapter,
4665 				u64 remote_handle, u64 ioba, u64 num_entries)
4666 {
4667 	unsigned int ua = adapter->vdev->unit_address;
4668 	struct device *dev = &adapter->vdev->dev;
4669 	int rc;
4670 
4671 	/* Make sure the hypervisor sees the complete request */
4672 	dma_wmb();
4673 	rc = plpar_hcall_norets(H_SEND_SUB_CRQ_INDIRECT, ua,
4674 				cpu_to_be64(remote_handle),
4675 				ioba, num_entries);
4676 
4677 	if (rc)
4678 		print_subcrq_error(dev, rc, __func__);
4679 
4680 	return rc;
4681 }
4682 
4683 static int ibmvnic_send_crq(struct ibmvnic_adapter *adapter,
4684 			    union ibmvnic_crq *crq)
4685 {
4686 	unsigned int ua = adapter->vdev->unit_address;
4687 	struct device *dev = &adapter->vdev->dev;
4688 	u64 *u64_crq = (u64 *)crq;
4689 	int rc;
4690 
4691 	netdev_dbg(adapter->netdev, "Sending CRQ: %016lx %016lx\n",
4692 		   (unsigned long)cpu_to_be64(u64_crq[0]),
4693 		   (unsigned long)cpu_to_be64(u64_crq[1]));
4694 
4695 	if (!adapter->crq.active &&
4696 	    crq->generic.first != IBMVNIC_CRQ_INIT_CMD) {
4697 		dev_warn(dev, "Invalid request detected while CRQ is inactive, possible device state change during reset\n");
4698 		return -EINVAL;
4699 	}
4700 
4701 	/* Make sure the hypervisor sees the complete request */
4702 	dma_wmb();
4703 
4704 	rc = plpar_hcall_norets(H_SEND_CRQ, ua,
4705 				cpu_to_be64(u64_crq[0]),
4706 				cpu_to_be64(u64_crq[1]));
4707 
4708 	if (rc) {
4709 		if (rc == H_CLOSED) {
4710 			dev_warn(dev, "CRQ Queue closed\n");
4711 			/* do not reset, report the fail, wait for passive init from server */
4712 		}
4713 
4714 		dev_warn(dev, "Send error (rc=%d)\n", rc);
4715 	}
4716 
4717 	return rc;
4718 }
4719 
4720 static int ibmvnic_send_crq_init(struct ibmvnic_adapter *adapter)
4721 {
4722 	struct device *dev = &adapter->vdev->dev;
4723 	union ibmvnic_crq crq;
4724 	int retries = 100;
4725 	int rc;
4726 
4727 	memset(&crq, 0, sizeof(crq));
4728 	crq.generic.first = IBMVNIC_CRQ_INIT_CMD;
4729 	crq.generic.cmd = IBMVNIC_CRQ_INIT;
4730 	netdev_dbg(adapter->netdev, "Sending CRQ init\n");
4731 
4732 	do {
4733 		rc = ibmvnic_send_crq(adapter, &crq);
4734 		if (rc != H_CLOSED)
4735 			break;
4736 		retries--;
4737 		msleep(50);
4738 
4739 	} while (retries > 0);
4740 
4741 	if (rc) {
4742 		dev_err(dev, "Failed to send init request, rc = %d\n", rc);
4743 		return rc;
4744 	}
4745 
4746 	return 0;
4747 }
4748 
4749 struct vnic_login_client_data {
4750 	u8	type;
4751 	__be16	len;
4752 	char	name[];
4753 } __packed;
4754 
4755 static int vnic_client_data_len(struct ibmvnic_adapter *adapter)
4756 {
4757 	int len;
4758 
4759 	/* Calculate the amount of buffer space needed for the
4760 	 * vnic client data in the login buffer. There are four entries,
4761 	 * OS name, LPAR name, device name, and a null last entry.
4762 	 */
4763 	len = 4 * sizeof(struct vnic_login_client_data);
4764 	len += 6; /* "Linux" plus NULL */
4765 	len += strlen(utsname()->nodename) + 1;
4766 	len += strlen(adapter->netdev->name) + 1;
4767 
4768 	return len;
4769 }
4770 
4771 static void vnic_add_client_data(struct ibmvnic_adapter *adapter,
4772 				 struct vnic_login_client_data *vlcd)
4773 {
4774 	const char *os_name = "Linux";
4775 	int len;
4776 
4777 	/* Type 1 - LPAR OS */
4778 	vlcd->type = 1;
4779 	len = strlen(os_name) + 1;
4780 	vlcd->len = cpu_to_be16(len);
4781 	strscpy(vlcd->name, os_name, len);
4782 	vlcd = (struct vnic_login_client_data *)(vlcd->name + len);
4783 
4784 	/* Type 2 - LPAR name */
4785 	vlcd->type = 2;
4786 	len = strlen(utsname()->nodename) + 1;
4787 	vlcd->len = cpu_to_be16(len);
4788 	strscpy(vlcd->name, utsname()->nodename, len);
4789 	vlcd = (struct vnic_login_client_data *)(vlcd->name + len);
4790 
4791 	/* Type 3 - device name */
4792 	vlcd->type = 3;
4793 	len = strlen(adapter->netdev->name) + 1;
4794 	vlcd->len = cpu_to_be16(len);
4795 	strscpy(vlcd->name, adapter->netdev->name, len);
4796 }
4797 
4798 static int send_login(struct ibmvnic_adapter *adapter)
4799 {
4800 	struct ibmvnic_login_rsp_buffer *login_rsp_buffer;
4801 	struct ibmvnic_login_buffer *login_buffer;
4802 	struct device *dev = &adapter->vdev->dev;
4803 	struct vnic_login_client_data *vlcd;
4804 	dma_addr_t rsp_buffer_token;
4805 	dma_addr_t buffer_token;
4806 	size_t rsp_buffer_size;
4807 	union ibmvnic_crq crq;
4808 	int client_data_len;
4809 	size_t buffer_size;
4810 	__be64 *tx_list_p;
4811 	__be64 *rx_list_p;
4812 	int rc;
4813 	int i;
4814 
4815 	if (!adapter->tx_scrq || !adapter->rx_scrq) {
4816 		netdev_err(adapter->netdev,
4817 			   "RX or TX queues are not allocated, device login failed\n");
4818 		return -ENOMEM;
4819 	}
4820 
4821 	release_login_buffer(adapter);
4822 	release_login_rsp_buffer(adapter);
4823 
4824 	client_data_len = vnic_client_data_len(adapter);
4825 
4826 	buffer_size =
4827 	    sizeof(struct ibmvnic_login_buffer) +
4828 	    sizeof(u64) * (adapter->req_tx_queues + adapter->req_rx_queues) +
4829 	    client_data_len;
4830 
4831 	login_buffer = kzalloc(buffer_size, GFP_ATOMIC);
4832 	if (!login_buffer)
4833 		goto buf_alloc_failed;
4834 
4835 	buffer_token = dma_map_single(dev, login_buffer, buffer_size,
4836 				      DMA_TO_DEVICE);
4837 	if (dma_mapping_error(dev, buffer_token)) {
4838 		dev_err(dev, "Couldn't map login buffer\n");
4839 		goto buf_map_failed;
4840 	}
4841 
4842 	rsp_buffer_size = sizeof(struct ibmvnic_login_rsp_buffer) +
4843 			  sizeof(u64) * adapter->req_tx_queues +
4844 			  sizeof(u64) * adapter->req_rx_queues +
4845 			  sizeof(u64) * adapter->req_rx_queues +
4846 			  sizeof(u8) * IBMVNIC_TX_DESC_VERSIONS;
4847 
4848 	login_rsp_buffer = kmalloc(rsp_buffer_size, GFP_ATOMIC);
4849 	if (!login_rsp_buffer)
4850 		goto buf_rsp_alloc_failed;
4851 
4852 	rsp_buffer_token = dma_map_single(dev, login_rsp_buffer,
4853 					  rsp_buffer_size, DMA_FROM_DEVICE);
4854 	if (dma_mapping_error(dev, rsp_buffer_token)) {
4855 		dev_err(dev, "Couldn't map login rsp buffer\n");
4856 		goto buf_rsp_map_failed;
4857 	}
4858 
4859 	adapter->login_buf = login_buffer;
4860 	adapter->login_buf_token = buffer_token;
4861 	adapter->login_buf_sz = buffer_size;
4862 	adapter->login_rsp_buf = login_rsp_buffer;
4863 	adapter->login_rsp_buf_token = rsp_buffer_token;
4864 	adapter->login_rsp_buf_sz = rsp_buffer_size;
4865 
4866 	login_buffer->len = cpu_to_be32(buffer_size);
4867 	login_buffer->version = cpu_to_be32(INITIAL_VERSION_LB);
4868 	login_buffer->num_txcomp_subcrqs = cpu_to_be32(adapter->req_tx_queues);
4869 	login_buffer->off_txcomp_subcrqs =
4870 	    cpu_to_be32(sizeof(struct ibmvnic_login_buffer));
4871 	login_buffer->num_rxcomp_subcrqs = cpu_to_be32(adapter->req_rx_queues);
4872 	login_buffer->off_rxcomp_subcrqs =
4873 	    cpu_to_be32(sizeof(struct ibmvnic_login_buffer) +
4874 			sizeof(u64) * adapter->req_tx_queues);
4875 	login_buffer->login_rsp_ioba = cpu_to_be32(rsp_buffer_token);
4876 	login_buffer->login_rsp_len = cpu_to_be32(rsp_buffer_size);
4877 
4878 	tx_list_p = (__be64 *)((char *)login_buffer +
4879 				      sizeof(struct ibmvnic_login_buffer));
4880 	rx_list_p = (__be64 *)((char *)login_buffer +
4881 				      sizeof(struct ibmvnic_login_buffer) +
4882 				      sizeof(u64) * adapter->req_tx_queues);
4883 
4884 	for (i = 0; i < adapter->req_tx_queues; i++) {
4885 		if (adapter->tx_scrq[i]) {
4886 			tx_list_p[i] =
4887 				cpu_to_be64(adapter->tx_scrq[i]->crq_num);
4888 		}
4889 	}
4890 
4891 	for (i = 0; i < adapter->req_rx_queues; i++) {
4892 		if (adapter->rx_scrq[i]) {
4893 			rx_list_p[i] =
4894 				cpu_to_be64(adapter->rx_scrq[i]->crq_num);
4895 		}
4896 	}
4897 
4898 	/* Insert vNIC login client data */
4899 	vlcd = (struct vnic_login_client_data *)
4900 		((char *)rx_list_p + (sizeof(u64) * adapter->req_rx_queues));
4901 	login_buffer->client_data_offset =
4902 			cpu_to_be32((char *)vlcd - (char *)login_buffer);
4903 	login_buffer->client_data_len = cpu_to_be32(client_data_len);
4904 
4905 	vnic_add_client_data(adapter, vlcd);
4906 
4907 	netdev_dbg(adapter->netdev, "Login Buffer:\n");
4908 	for (i = 0; i < (adapter->login_buf_sz - 1) / 8 + 1; i++) {
4909 		netdev_dbg(adapter->netdev, "%016lx\n",
4910 			   ((unsigned long *)(adapter->login_buf))[i]);
4911 	}
4912 
4913 	memset(&crq, 0, sizeof(crq));
4914 	crq.login.first = IBMVNIC_CRQ_CMD;
4915 	crq.login.cmd = LOGIN;
4916 	crq.login.ioba = cpu_to_be32(buffer_token);
4917 	crq.login.len = cpu_to_be32(buffer_size);
4918 
4919 	adapter->login_pending = true;
4920 	rc = ibmvnic_send_crq(adapter, &crq);
4921 	if (rc) {
4922 		adapter->login_pending = false;
4923 		netdev_err(adapter->netdev, "Failed to send login, rc=%d\n", rc);
4924 		goto buf_send_failed;
4925 	}
4926 
4927 	return 0;
4928 
4929 buf_send_failed:
4930 	dma_unmap_single(dev, rsp_buffer_token, rsp_buffer_size,
4931 			 DMA_FROM_DEVICE);
4932 buf_rsp_map_failed:
4933 	kfree(login_rsp_buffer);
4934 	adapter->login_rsp_buf = NULL;
4935 buf_rsp_alloc_failed:
4936 	dma_unmap_single(dev, buffer_token, buffer_size, DMA_TO_DEVICE);
4937 buf_map_failed:
4938 	kfree(login_buffer);
4939 	adapter->login_buf = NULL;
4940 buf_alloc_failed:
4941 	return -ENOMEM;
4942 }
4943 
4944 static int send_request_map(struct ibmvnic_adapter *adapter, dma_addr_t addr,
4945 			    u32 len, u8 map_id)
4946 {
4947 	union ibmvnic_crq crq;
4948 
4949 	memset(&crq, 0, sizeof(crq));
4950 	crq.request_map.first = IBMVNIC_CRQ_CMD;
4951 	crq.request_map.cmd = REQUEST_MAP;
4952 	crq.request_map.map_id = map_id;
4953 	crq.request_map.ioba = cpu_to_be32(addr);
4954 	crq.request_map.len = cpu_to_be32(len);
4955 	return ibmvnic_send_crq(adapter, &crq);
4956 }
4957 
4958 static int send_request_unmap(struct ibmvnic_adapter *adapter, u8 map_id)
4959 {
4960 	union ibmvnic_crq crq;
4961 
4962 	memset(&crq, 0, sizeof(crq));
4963 	crq.request_unmap.first = IBMVNIC_CRQ_CMD;
4964 	crq.request_unmap.cmd = REQUEST_UNMAP;
4965 	crq.request_unmap.map_id = map_id;
4966 	return ibmvnic_send_crq(adapter, &crq);
4967 }
4968 
4969 static void send_query_map(struct ibmvnic_adapter *adapter)
4970 {
4971 	union ibmvnic_crq crq;
4972 
4973 	memset(&crq, 0, sizeof(crq));
4974 	crq.query_map.first = IBMVNIC_CRQ_CMD;
4975 	crq.query_map.cmd = QUERY_MAP;
4976 	ibmvnic_send_crq(adapter, &crq);
4977 }
4978 
4979 /* Send a series of CRQs requesting various capabilities of the VNIC server */
4980 static void send_query_cap(struct ibmvnic_adapter *adapter)
4981 {
4982 	union ibmvnic_crq crq;
4983 	int cap_reqs;
4984 
4985 	/* We send out 25 QUERY_CAPABILITY CRQs below.  Initialize this count
4986 	 * upfront. When the tasklet receives a response to all of these, it
4987 	 * can send out the next protocol messaage (REQUEST_CAPABILITY).
4988 	 */
4989 	cap_reqs = 25;
4990 
4991 	atomic_set(&adapter->running_cap_crqs, cap_reqs);
4992 
4993 	memset(&crq, 0, sizeof(crq));
4994 	crq.query_capability.first = IBMVNIC_CRQ_CMD;
4995 	crq.query_capability.cmd = QUERY_CAPABILITY;
4996 
4997 	crq.query_capability.capability = cpu_to_be16(MIN_TX_QUEUES);
4998 	ibmvnic_send_crq(adapter, &crq);
4999 	cap_reqs--;
5000 
5001 	crq.query_capability.capability = cpu_to_be16(MIN_RX_QUEUES);
5002 	ibmvnic_send_crq(adapter, &crq);
5003 	cap_reqs--;
5004 
5005 	crq.query_capability.capability = cpu_to_be16(MIN_RX_ADD_QUEUES);
5006 	ibmvnic_send_crq(adapter, &crq);
5007 	cap_reqs--;
5008 
5009 	crq.query_capability.capability = cpu_to_be16(MAX_TX_QUEUES);
5010 	ibmvnic_send_crq(adapter, &crq);
5011 	cap_reqs--;
5012 
5013 	crq.query_capability.capability = cpu_to_be16(MAX_RX_QUEUES);
5014 	ibmvnic_send_crq(adapter, &crq);
5015 	cap_reqs--;
5016 
5017 	crq.query_capability.capability = cpu_to_be16(MAX_RX_ADD_QUEUES);
5018 	ibmvnic_send_crq(adapter, &crq);
5019 	cap_reqs--;
5020 
5021 	crq.query_capability.capability =
5022 	    cpu_to_be16(MIN_TX_ENTRIES_PER_SUBCRQ);
5023 	ibmvnic_send_crq(adapter, &crq);
5024 	cap_reqs--;
5025 
5026 	crq.query_capability.capability =
5027 	    cpu_to_be16(MIN_RX_ADD_ENTRIES_PER_SUBCRQ);
5028 	ibmvnic_send_crq(adapter, &crq);
5029 	cap_reqs--;
5030 
5031 	crq.query_capability.capability =
5032 	    cpu_to_be16(MAX_TX_ENTRIES_PER_SUBCRQ);
5033 	ibmvnic_send_crq(adapter, &crq);
5034 	cap_reqs--;
5035 
5036 	crq.query_capability.capability =
5037 	    cpu_to_be16(MAX_RX_ADD_ENTRIES_PER_SUBCRQ);
5038 	ibmvnic_send_crq(adapter, &crq);
5039 	cap_reqs--;
5040 
5041 	crq.query_capability.capability = cpu_to_be16(TCP_IP_OFFLOAD);
5042 	ibmvnic_send_crq(adapter, &crq);
5043 	cap_reqs--;
5044 
5045 	crq.query_capability.capability = cpu_to_be16(PROMISC_SUPPORTED);
5046 	ibmvnic_send_crq(adapter, &crq);
5047 	cap_reqs--;
5048 
5049 	crq.query_capability.capability = cpu_to_be16(MIN_MTU);
5050 	ibmvnic_send_crq(adapter, &crq);
5051 	cap_reqs--;
5052 
5053 	crq.query_capability.capability = cpu_to_be16(MAX_MTU);
5054 	ibmvnic_send_crq(adapter, &crq);
5055 	cap_reqs--;
5056 
5057 	crq.query_capability.capability = cpu_to_be16(MAX_MULTICAST_FILTERS);
5058 	ibmvnic_send_crq(adapter, &crq);
5059 	cap_reqs--;
5060 
5061 	crq.query_capability.capability = cpu_to_be16(VLAN_HEADER_INSERTION);
5062 	ibmvnic_send_crq(adapter, &crq);
5063 	cap_reqs--;
5064 
5065 	crq.query_capability.capability = cpu_to_be16(RX_VLAN_HEADER_INSERTION);
5066 	ibmvnic_send_crq(adapter, &crq);
5067 	cap_reqs--;
5068 
5069 	crq.query_capability.capability = cpu_to_be16(MAX_TX_SG_ENTRIES);
5070 	ibmvnic_send_crq(adapter, &crq);
5071 	cap_reqs--;
5072 
5073 	crq.query_capability.capability = cpu_to_be16(RX_SG_SUPPORTED);
5074 	ibmvnic_send_crq(adapter, &crq);
5075 	cap_reqs--;
5076 
5077 	crq.query_capability.capability = cpu_to_be16(OPT_TX_COMP_SUB_QUEUES);
5078 	ibmvnic_send_crq(adapter, &crq);
5079 	cap_reqs--;
5080 
5081 	crq.query_capability.capability = cpu_to_be16(OPT_RX_COMP_QUEUES);
5082 	ibmvnic_send_crq(adapter, &crq);
5083 	cap_reqs--;
5084 
5085 	crq.query_capability.capability =
5086 			cpu_to_be16(OPT_RX_BUFADD_Q_PER_RX_COMP_Q);
5087 	ibmvnic_send_crq(adapter, &crq);
5088 	cap_reqs--;
5089 
5090 	crq.query_capability.capability =
5091 			cpu_to_be16(OPT_TX_ENTRIES_PER_SUBCRQ);
5092 	ibmvnic_send_crq(adapter, &crq);
5093 	cap_reqs--;
5094 
5095 	crq.query_capability.capability =
5096 			cpu_to_be16(OPT_RXBA_ENTRIES_PER_SUBCRQ);
5097 	ibmvnic_send_crq(adapter, &crq);
5098 	cap_reqs--;
5099 
5100 	crq.query_capability.capability = cpu_to_be16(TX_RX_DESC_REQ);
5101 
5102 	ibmvnic_send_crq(adapter, &crq);
5103 	cap_reqs--;
5104 
5105 	/* Keep at end to catch any discrepancy between expected and actual
5106 	 * CRQs sent.
5107 	 */
5108 	WARN_ON(cap_reqs != 0);
5109 }
5110 
5111 static void send_query_ip_offload(struct ibmvnic_adapter *adapter)
5112 {
5113 	int buf_sz = sizeof(struct ibmvnic_query_ip_offload_buffer);
5114 	struct device *dev = &adapter->vdev->dev;
5115 	union ibmvnic_crq crq;
5116 
5117 	adapter->ip_offload_tok =
5118 		dma_map_single(dev,
5119 			       &adapter->ip_offload_buf,
5120 			       buf_sz,
5121 			       DMA_FROM_DEVICE);
5122 
5123 	if (dma_mapping_error(dev, adapter->ip_offload_tok)) {
5124 		if (!firmware_has_feature(FW_FEATURE_CMO))
5125 			dev_err(dev, "Couldn't map offload buffer\n");
5126 		return;
5127 	}
5128 
5129 	memset(&crq, 0, sizeof(crq));
5130 	crq.query_ip_offload.first = IBMVNIC_CRQ_CMD;
5131 	crq.query_ip_offload.cmd = QUERY_IP_OFFLOAD;
5132 	crq.query_ip_offload.len = cpu_to_be32(buf_sz);
5133 	crq.query_ip_offload.ioba =
5134 	    cpu_to_be32(adapter->ip_offload_tok);
5135 
5136 	ibmvnic_send_crq(adapter, &crq);
5137 }
5138 
5139 static void send_control_ip_offload(struct ibmvnic_adapter *adapter)
5140 {
5141 	struct ibmvnic_control_ip_offload_buffer *ctrl_buf = &adapter->ip_offload_ctrl;
5142 	struct ibmvnic_query_ip_offload_buffer *buf = &adapter->ip_offload_buf;
5143 	struct device *dev = &adapter->vdev->dev;
5144 	netdev_features_t old_hw_features = 0;
5145 	union ibmvnic_crq crq;
5146 
5147 	adapter->ip_offload_ctrl_tok =
5148 		dma_map_single(dev,
5149 			       ctrl_buf,
5150 			       sizeof(adapter->ip_offload_ctrl),
5151 			       DMA_TO_DEVICE);
5152 
5153 	if (dma_mapping_error(dev, adapter->ip_offload_ctrl_tok)) {
5154 		dev_err(dev, "Couldn't map ip offload control buffer\n");
5155 		return;
5156 	}
5157 
5158 	ctrl_buf->len = cpu_to_be32(sizeof(adapter->ip_offload_ctrl));
5159 	ctrl_buf->version = cpu_to_be32(INITIAL_VERSION_IOB);
5160 	ctrl_buf->ipv4_chksum = buf->ipv4_chksum;
5161 	ctrl_buf->ipv6_chksum = buf->ipv6_chksum;
5162 	ctrl_buf->tcp_ipv4_chksum = buf->tcp_ipv4_chksum;
5163 	ctrl_buf->udp_ipv4_chksum = buf->udp_ipv4_chksum;
5164 	ctrl_buf->tcp_ipv6_chksum = buf->tcp_ipv6_chksum;
5165 	ctrl_buf->udp_ipv6_chksum = buf->udp_ipv6_chksum;
5166 	ctrl_buf->large_tx_ipv4 = buf->large_tx_ipv4;
5167 	ctrl_buf->large_tx_ipv6 = buf->large_tx_ipv6;
5168 
5169 	/* large_rx disabled for now, additional features needed */
5170 	ctrl_buf->large_rx_ipv4 = 0;
5171 	ctrl_buf->large_rx_ipv6 = 0;
5172 
5173 	if (adapter->state != VNIC_PROBING) {
5174 		old_hw_features = adapter->netdev->hw_features;
5175 		adapter->netdev->hw_features = 0;
5176 	}
5177 
5178 	adapter->netdev->hw_features = NETIF_F_SG | NETIF_F_GSO | NETIF_F_GRO;
5179 
5180 	if (buf->tcp_ipv4_chksum || buf->udp_ipv4_chksum)
5181 		adapter->netdev->hw_features |= NETIF_F_IP_CSUM;
5182 
5183 	if (buf->tcp_ipv6_chksum || buf->udp_ipv6_chksum)
5184 		adapter->netdev->hw_features |= NETIF_F_IPV6_CSUM;
5185 
5186 	if ((adapter->netdev->features &
5187 	    (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)))
5188 		adapter->netdev->hw_features |= NETIF_F_RXCSUM;
5189 
5190 	if (buf->large_tx_ipv4)
5191 		adapter->netdev->hw_features |= NETIF_F_TSO;
5192 	if (buf->large_tx_ipv6)
5193 		adapter->netdev->hw_features |= NETIF_F_TSO6;
5194 
5195 	if (adapter->state == VNIC_PROBING) {
5196 		adapter->netdev->features |= adapter->netdev->hw_features;
5197 	} else if (old_hw_features != adapter->netdev->hw_features) {
5198 		netdev_features_t tmp = 0;
5199 
5200 		/* disable features no longer supported */
5201 		adapter->netdev->features &= adapter->netdev->hw_features;
5202 		/* turn on features now supported if previously enabled */
5203 		tmp = (old_hw_features ^ adapter->netdev->hw_features) &
5204 			adapter->netdev->hw_features;
5205 		adapter->netdev->features |=
5206 				tmp & adapter->netdev->wanted_features;
5207 	}
5208 
5209 	memset(&crq, 0, sizeof(crq));
5210 	crq.control_ip_offload.first = IBMVNIC_CRQ_CMD;
5211 	crq.control_ip_offload.cmd = CONTROL_IP_OFFLOAD;
5212 	crq.control_ip_offload.len =
5213 	    cpu_to_be32(sizeof(adapter->ip_offload_ctrl));
5214 	crq.control_ip_offload.ioba = cpu_to_be32(adapter->ip_offload_ctrl_tok);
5215 	ibmvnic_send_crq(adapter, &crq);
5216 }
5217 
5218 static void handle_vpd_size_rsp(union ibmvnic_crq *crq,
5219 				struct ibmvnic_adapter *adapter)
5220 {
5221 	struct device *dev = &adapter->vdev->dev;
5222 
5223 	if (crq->get_vpd_size_rsp.rc.code) {
5224 		dev_err(dev, "Error retrieving VPD size, rc=%x\n",
5225 			crq->get_vpd_size_rsp.rc.code);
5226 		complete(&adapter->fw_done);
5227 		return;
5228 	}
5229 
5230 	adapter->vpd->len = be64_to_cpu(crq->get_vpd_size_rsp.len);
5231 	complete(&adapter->fw_done);
5232 }
5233 
5234 static void handle_vpd_rsp(union ibmvnic_crq *crq,
5235 			   struct ibmvnic_adapter *adapter)
5236 {
5237 	struct device *dev = &adapter->vdev->dev;
5238 	unsigned char *substr = NULL;
5239 	u8 fw_level_len = 0;
5240 
5241 	memset(adapter->fw_version, 0, 32);
5242 
5243 	dma_unmap_single(dev, adapter->vpd->dma_addr, adapter->vpd->len,
5244 			 DMA_FROM_DEVICE);
5245 
5246 	if (crq->get_vpd_rsp.rc.code) {
5247 		dev_err(dev, "Error retrieving VPD from device, rc=%x\n",
5248 			crq->get_vpd_rsp.rc.code);
5249 		goto complete;
5250 	}
5251 
5252 	/* get the position of the firmware version info
5253 	 * located after the ASCII 'RM' substring in the buffer
5254 	 */
5255 	substr = strnstr(adapter->vpd->buff, "RM", adapter->vpd->len);
5256 	if (!substr) {
5257 		dev_info(dev, "Warning - No FW level has been provided in the VPD buffer by the VIOS Server\n");
5258 		goto complete;
5259 	}
5260 
5261 	/* get length of firmware level ASCII substring */
5262 	if ((substr + 2) < (adapter->vpd->buff + adapter->vpd->len)) {
5263 		fw_level_len = *(substr + 2);
5264 	} else {
5265 		dev_info(dev, "Length of FW substr extrapolated VDP buff\n");
5266 		goto complete;
5267 	}
5268 
5269 	/* copy firmware version string from vpd into adapter */
5270 	if ((substr + 3 + fw_level_len) <
5271 	    (adapter->vpd->buff + adapter->vpd->len)) {
5272 		strscpy(adapter->fw_version, substr + 3,
5273 			sizeof(adapter->fw_version));
5274 	} else {
5275 		dev_info(dev, "FW substr extrapolated VPD buff\n");
5276 	}
5277 
5278 complete:
5279 	if (adapter->fw_version[0] == '\0')
5280 		strscpy((char *)adapter->fw_version, "N/A", sizeof(adapter->fw_version));
5281 	complete(&adapter->fw_done);
5282 }
5283 
5284 static void handle_query_ip_offload_rsp(struct ibmvnic_adapter *adapter)
5285 {
5286 	struct device *dev = &adapter->vdev->dev;
5287 	struct ibmvnic_query_ip_offload_buffer *buf = &adapter->ip_offload_buf;
5288 	int i;
5289 
5290 	dma_unmap_single(dev, adapter->ip_offload_tok,
5291 			 sizeof(adapter->ip_offload_buf), DMA_FROM_DEVICE);
5292 
5293 	netdev_dbg(adapter->netdev, "Query IP Offload Buffer:\n");
5294 	for (i = 0; i < (sizeof(adapter->ip_offload_buf) - 1) / 8 + 1; i++)
5295 		netdev_dbg(adapter->netdev, "%016lx\n",
5296 			   ((unsigned long *)(buf))[i]);
5297 
5298 	netdev_dbg(adapter->netdev, "ipv4_chksum = %d\n", buf->ipv4_chksum);
5299 	netdev_dbg(adapter->netdev, "ipv6_chksum = %d\n", buf->ipv6_chksum);
5300 	netdev_dbg(adapter->netdev, "tcp_ipv4_chksum = %d\n",
5301 		   buf->tcp_ipv4_chksum);
5302 	netdev_dbg(adapter->netdev, "tcp_ipv6_chksum = %d\n",
5303 		   buf->tcp_ipv6_chksum);
5304 	netdev_dbg(adapter->netdev, "udp_ipv4_chksum = %d\n",
5305 		   buf->udp_ipv4_chksum);
5306 	netdev_dbg(adapter->netdev, "udp_ipv6_chksum = %d\n",
5307 		   buf->udp_ipv6_chksum);
5308 	netdev_dbg(adapter->netdev, "large_tx_ipv4 = %d\n",
5309 		   buf->large_tx_ipv4);
5310 	netdev_dbg(adapter->netdev, "large_tx_ipv6 = %d\n",
5311 		   buf->large_tx_ipv6);
5312 	netdev_dbg(adapter->netdev, "large_rx_ipv4 = %d\n",
5313 		   buf->large_rx_ipv4);
5314 	netdev_dbg(adapter->netdev, "large_rx_ipv6 = %d\n",
5315 		   buf->large_rx_ipv6);
5316 	netdev_dbg(adapter->netdev, "max_ipv4_hdr_sz = %d\n",
5317 		   buf->max_ipv4_header_size);
5318 	netdev_dbg(adapter->netdev, "max_ipv6_hdr_sz = %d\n",
5319 		   buf->max_ipv6_header_size);
5320 	netdev_dbg(adapter->netdev, "max_tcp_hdr_size = %d\n",
5321 		   buf->max_tcp_header_size);
5322 	netdev_dbg(adapter->netdev, "max_udp_hdr_size = %d\n",
5323 		   buf->max_udp_header_size);
5324 	netdev_dbg(adapter->netdev, "max_large_tx_size = %d\n",
5325 		   buf->max_large_tx_size);
5326 	netdev_dbg(adapter->netdev, "max_large_rx_size = %d\n",
5327 		   buf->max_large_rx_size);
5328 	netdev_dbg(adapter->netdev, "ipv6_ext_hdr = %d\n",
5329 		   buf->ipv6_extension_header);
5330 	netdev_dbg(adapter->netdev, "tcp_pseudosum_req = %d\n",
5331 		   buf->tcp_pseudosum_req);
5332 	netdev_dbg(adapter->netdev, "num_ipv6_ext_hd = %d\n",
5333 		   buf->num_ipv6_ext_headers);
5334 	netdev_dbg(adapter->netdev, "off_ipv6_ext_hd = %d\n",
5335 		   buf->off_ipv6_ext_headers);
5336 
5337 	send_control_ip_offload(adapter);
5338 }
5339 
5340 static const char *ibmvnic_fw_err_cause(u16 cause)
5341 {
5342 	switch (cause) {
5343 	case ADAPTER_PROBLEM:
5344 		return "adapter problem";
5345 	case BUS_PROBLEM:
5346 		return "bus problem";
5347 	case FW_PROBLEM:
5348 		return "firmware problem";
5349 	case DD_PROBLEM:
5350 		return "device driver problem";
5351 	case EEH_RECOVERY:
5352 		return "EEH recovery";
5353 	case FW_UPDATED:
5354 		return "firmware updated";
5355 	case LOW_MEMORY:
5356 		return "low Memory";
5357 	default:
5358 		return "unknown";
5359 	}
5360 }
5361 
5362 static void handle_error_indication(union ibmvnic_crq *crq,
5363 				    struct ibmvnic_adapter *adapter)
5364 {
5365 	struct device *dev = &adapter->vdev->dev;
5366 	u16 cause;
5367 
5368 	cause = be16_to_cpu(crq->error_indication.error_cause);
5369 
5370 	dev_warn_ratelimited(dev,
5371 			     "Firmware reports %serror, cause: %s. Starting recovery...\n",
5372 			     crq->error_indication.flags
5373 				& IBMVNIC_FATAL_ERROR ? "FATAL " : "",
5374 			     ibmvnic_fw_err_cause(cause));
5375 
5376 	if (crq->error_indication.flags & IBMVNIC_FATAL_ERROR)
5377 		ibmvnic_reset(adapter, VNIC_RESET_FATAL);
5378 	else
5379 		ibmvnic_reset(adapter, VNIC_RESET_NON_FATAL);
5380 }
5381 
5382 static int handle_change_mac_rsp(union ibmvnic_crq *crq,
5383 				 struct ibmvnic_adapter *adapter)
5384 {
5385 	struct net_device *netdev = adapter->netdev;
5386 	struct device *dev = &adapter->vdev->dev;
5387 	long rc;
5388 
5389 	rc = crq->change_mac_addr_rsp.rc.code;
5390 	if (rc) {
5391 		dev_err(dev, "Error %ld in CHANGE_MAC_ADDR_RSP\n", rc);
5392 		goto out;
5393 	}
5394 	/* crq->change_mac_addr.mac_addr is the requested one
5395 	 * crq->change_mac_addr_rsp.mac_addr is the returned valid one.
5396 	 */
5397 	eth_hw_addr_set(netdev, &crq->change_mac_addr_rsp.mac_addr[0]);
5398 	ether_addr_copy(adapter->mac_addr,
5399 			&crq->change_mac_addr_rsp.mac_addr[0]);
5400 out:
5401 	complete(&adapter->fw_done);
5402 	return rc;
5403 }
5404 
5405 static void handle_request_cap_rsp(union ibmvnic_crq *crq,
5406 				   struct ibmvnic_adapter *adapter)
5407 {
5408 	struct device *dev = &adapter->vdev->dev;
5409 	u64 *req_value;
5410 	char *name;
5411 
5412 	atomic_dec(&adapter->running_cap_crqs);
5413 	netdev_dbg(adapter->netdev, "Outstanding request-caps: %d\n",
5414 		   atomic_read(&adapter->running_cap_crqs));
5415 	switch (be16_to_cpu(crq->request_capability_rsp.capability)) {
5416 	case REQ_TX_QUEUES:
5417 		req_value = &adapter->req_tx_queues;
5418 		name = "tx";
5419 		break;
5420 	case REQ_RX_QUEUES:
5421 		req_value = &adapter->req_rx_queues;
5422 		name = "rx";
5423 		break;
5424 	case REQ_RX_ADD_QUEUES:
5425 		req_value = &adapter->req_rx_add_queues;
5426 		name = "rx_add";
5427 		break;
5428 	case REQ_TX_ENTRIES_PER_SUBCRQ:
5429 		req_value = &adapter->req_tx_entries_per_subcrq;
5430 		name = "tx_entries_per_subcrq";
5431 		break;
5432 	case REQ_RX_ADD_ENTRIES_PER_SUBCRQ:
5433 		req_value = &adapter->req_rx_add_entries_per_subcrq;
5434 		name = "rx_add_entries_per_subcrq";
5435 		break;
5436 	case REQ_MTU:
5437 		req_value = &adapter->req_mtu;
5438 		name = "mtu";
5439 		break;
5440 	case PROMISC_REQUESTED:
5441 		req_value = &adapter->promisc;
5442 		name = "promisc";
5443 		break;
5444 	default:
5445 		dev_err(dev, "Got invalid cap request rsp %d\n",
5446 			crq->request_capability.capability);
5447 		return;
5448 	}
5449 
5450 	switch (crq->request_capability_rsp.rc.code) {
5451 	case SUCCESS:
5452 		break;
5453 	case PARTIALSUCCESS:
5454 		dev_info(dev, "req=%lld, rsp=%ld in %s queue, retrying.\n",
5455 			 *req_value,
5456 			 (long)be64_to_cpu(crq->request_capability_rsp.number),
5457 			 name);
5458 
5459 		if (be16_to_cpu(crq->request_capability_rsp.capability) ==
5460 		    REQ_MTU) {
5461 			pr_err("mtu of %llu is not supported. Reverting.\n",
5462 			       *req_value);
5463 			*req_value = adapter->fallback.mtu;
5464 		} else {
5465 			*req_value =
5466 				be64_to_cpu(crq->request_capability_rsp.number);
5467 		}
5468 
5469 		send_request_cap(adapter, 1);
5470 		return;
5471 	default:
5472 		dev_err(dev, "Error %d in request cap rsp\n",
5473 			crq->request_capability_rsp.rc.code);
5474 		return;
5475 	}
5476 
5477 	/* Done receiving requested capabilities, query IP offload support */
5478 	if (atomic_read(&adapter->running_cap_crqs) == 0)
5479 		send_query_ip_offload(adapter);
5480 }
5481 
5482 static int handle_login_rsp(union ibmvnic_crq *login_rsp_crq,
5483 			    struct ibmvnic_adapter *adapter)
5484 {
5485 	struct device *dev = &adapter->vdev->dev;
5486 	struct net_device *netdev = adapter->netdev;
5487 	struct ibmvnic_login_rsp_buffer *login_rsp = adapter->login_rsp_buf;
5488 	struct ibmvnic_login_buffer *login = adapter->login_buf;
5489 	u64 *tx_handle_array;
5490 	u64 *rx_handle_array;
5491 	int num_tx_pools;
5492 	int num_rx_pools;
5493 	u64 *size_array;
5494 	u32 rsp_len;
5495 	int i;
5496 
5497 	/* CHECK: Test/set of login_pending does not need to be atomic
5498 	 * because only ibmvnic_tasklet tests/clears this.
5499 	 */
5500 	if (!adapter->login_pending) {
5501 		netdev_warn(netdev, "Ignoring unexpected login response\n");
5502 		return 0;
5503 	}
5504 	adapter->login_pending = false;
5505 
5506 	/* If the number of queues requested can't be allocated by the
5507 	 * server, the login response will return with code 1. We will need
5508 	 * to resend the login buffer with fewer queues requested.
5509 	 */
5510 	if (login_rsp_crq->generic.rc.code) {
5511 		adapter->init_done_rc = login_rsp_crq->generic.rc.code;
5512 		complete(&adapter->init_done);
5513 		return 0;
5514 	}
5515 
5516 	if (adapter->failover_pending) {
5517 		adapter->init_done_rc = -EAGAIN;
5518 		netdev_dbg(netdev, "Failover pending, ignoring login response\n");
5519 		complete(&adapter->init_done);
5520 		/* login response buffer will be released on reset */
5521 		return 0;
5522 	}
5523 
5524 	netdev->mtu = adapter->req_mtu - ETH_HLEN;
5525 
5526 	netdev_dbg(adapter->netdev, "Login Response Buffer:\n");
5527 	for (i = 0; i < (adapter->login_rsp_buf_sz - 1) / 8 + 1; i++) {
5528 		netdev_dbg(adapter->netdev, "%016lx\n",
5529 			   ((unsigned long *)(adapter->login_rsp_buf))[i]);
5530 	}
5531 
5532 	/* Sanity checks */
5533 	if (login->num_txcomp_subcrqs != login_rsp->num_txsubm_subcrqs ||
5534 	    (be32_to_cpu(login->num_rxcomp_subcrqs) *
5535 	     adapter->req_rx_add_queues !=
5536 	     be32_to_cpu(login_rsp->num_rxadd_subcrqs))) {
5537 		dev_err(dev, "FATAL: Inconsistent login and login rsp\n");
5538 		ibmvnic_reset(adapter, VNIC_RESET_FATAL);
5539 		return -EIO;
5540 	}
5541 
5542 	rsp_len = be32_to_cpu(login_rsp->len);
5543 	if (be32_to_cpu(login->login_rsp_len) < rsp_len ||
5544 	    rsp_len <= be32_to_cpu(login_rsp->off_txsubm_subcrqs) ||
5545 	    rsp_len <= be32_to_cpu(login_rsp->off_rxadd_subcrqs) ||
5546 	    rsp_len <= be32_to_cpu(login_rsp->off_rxadd_buff_size) ||
5547 	    rsp_len <= be32_to_cpu(login_rsp->off_supp_tx_desc)) {
5548 		/* This can happen if a login request times out and there are
5549 		 * 2 outstanding login requests sent, the LOGIN_RSP crq
5550 		 * could have been for the older login request. So we are
5551 		 * parsing the newer response buffer which may be incomplete
5552 		 */
5553 		dev_err(dev, "FATAL: Login rsp offsets/lengths invalid\n");
5554 		ibmvnic_reset(adapter, VNIC_RESET_FATAL);
5555 		return -EIO;
5556 	}
5557 
5558 	size_array = (u64 *)((u8 *)(adapter->login_rsp_buf) +
5559 		be32_to_cpu(adapter->login_rsp_buf->off_rxadd_buff_size));
5560 	/* variable buffer sizes are not supported, so just read the
5561 	 * first entry.
5562 	 */
5563 	adapter->cur_rx_buf_sz = be64_to_cpu(size_array[0]);
5564 
5565 	num_tx_pools = be32_to_cpu(adapter->login_rsp_buf->num_txsubm_subcrqs);
5566 	num_rx_pools = be32_to_cpu(adapter->login_rsp_buf->num_rxadd_subcrqs);
5567 
5568 	tx_handle_array = (u64 *)((u8 *)(adapter->login_rsp_buf) +
5569 				  be32_to_cpu(adapter->login_rsp_buf->off_txsubm_subcrqs));
5570 	rx_handle_array = (u64 *)((u8 *)(adapter->login_rsp_buf) +
5571 				  be32_to_cpu(adapter->login_rsp_buf->off_rxadd_subcrqs));
5572 
5573 	for (i = 0; i < num_tx_pools; i++)
5574 		adapter->tx_scrq[i]->handle = tx_handle_array[i];
5575 
5576 	for (i = 0; i < num_rx_pools; i++)
5577 		adapter->rx_scrq[i]->handle = rx_handle_array[i];
5578 
5579 	adapter->num_active_tx_scrqs = num_tx_pools;
5580 	adapter->num_active_rx_scrqs = num_rx_pools;
5581 	release_login_rsp_buffer(adapter);
5582 	release_login_buffer(adapter);
5583 	complete(&adapter->init_done);
5584 
5585 	return 0;
5586 }
5587 
5588 static void handle_request_unmap_rsp(union ibmvnic_crq *crq,
5589 				     struct ibmvnic_adapter *adapter)
5590 {
5591 	struct device *dev = &adapter->vdev->dev;
5592 	long rc;
5593 
5594 	rc = crq->request_unmap_rsp.rc.code;
5595 	if (rc)
5596 		dev_err(dev, "Error %ld in REQUEST_UNMAP_RSP\n", rc);
5597 }
5598 
5599 static void handle_query_map_rsp(union ibmvnic_crq *crq,
5600 				 struct ibmvnic_adapter *adapter)
5601 {
5602 	struct net_device *netdev = adapter->netdev;
5603 	struct device *dev = &adapter->vdev->dev;
5604 	long rc;
5605 
5606 	rc = crq->query_map_rsp.rc.code;
5607 	if (rc) {
5608 		dev_err(dev, "Error %ld in QUERY_MAP_RSP\n", rc);
5609 		return;
5610 	}
5611 	netdev_dbg(netdev, "page_size = %d\ntot_pages = %u\nfree_pages = %u\n",
5612 		   crq->query_map_rsp.page_size,
5613 		   __be32_to_cpu(crq->query_map_rsp.tot_pages),
5614 		   __be32_to_cpu(crq->query_map_rsp.free_pages));
5615 }
5616 
5617 static void handle_query_cap_rsp(union ibmvnic_crq *crq,
5618 				 struct ibmvnic_adapter *adapter)
5619 {
5620 	struct net_device *netdev = adapter->netdev;
5621 	struct device *dev = &adapter->vdev->dev;
5622 	long rc;
5623 
5624 	atomic_dec(&adapter->running_cap_crqs);
5625 	netdev_dbg(netdev, "Outstanding queries: %d\n",
5626 		   atomic_read(&adapter->running_cap_crqs));
5627 	rc = crq->query_capability.rc.code;
5628 	if (rc) {
5629 		dev_err(dev, "Error %ld in QUERY_CAP_RSP\n", rc);
5630 		goto out;
5631 	}
5632 
5633 	switch (be16_to_cpu(crq->query_capability.capability)) {
5634 	case MIN_TX_QUEUES:
5635 		adapter->min_tx_queues =
5636 		    be64_to_cpu(crq->query_capability.number);
5637 		netdev_dbg(netdev, "min_tx_queues = %lld\n",
5638 			   adapter->min_tx_queues);
5639 		break;
5640 	case MIN_RX_QUEUES:
5641 		adapter->min_rx_queues =
5642 		    be64_to_cpu(crq->query_capability.number);
5643 		netdev_dbg(netdev, "min_rx_queues = %lld\n",
5644 			   adapter->min_rx_queues);
5645 		break;
5646 	case MIN_RX_ADD_QUEUES:
5647 		adapter->min_rx_add_queues =
5648 		    be64_to_cpu(crq->query_capability.number);
5649 		netdev_dbg(netdev, "min_rx_add_queues = %lld\n",
5650 			   adapter->min_rx_add_queues);
5651 		break;
5652 	case MAX_TX_QUEUES:
5653 		adapter->max_tx_queues =
5654 		    be64_to_cpu(crq->query_capability.number);
5655 		netdev_dbg(netdev, "max_tx_queues = %lld\n",
5656 			   adapter->max_tx_queues);
5657 		break;
5658 	case MAX_RX_QUEUES:
5659 		adapter->max_rx_queues =
5660 		    be64_to_cpu(crq->query_capability.number);
5661 		netdev_dbg(netdev, "max_rx_queues = %lld\n",
5662 			   adapter->max_rx_queues);
5663 		break;
5664 	case MAX_RX_ADD_QUEUES:
5665 		adapter->max_rx_add_queues =
5666 		    be64_to_cpu(crq->query_capability.number);
5667 		netdev_dbg(netdev, "max_rx_add_queues = %lld\n",
5668 			   adapter->max_rx_add_queues);
5669 		break;
5670 	case MIN_TX_ENTRIES_PER_SUBCRQ:
5671 		adapter->min_tx_entries_per_subcrq =
5672 		    be64_to_cpu(crq->query_capability.number);
5673 		netdev_dbg(netdev, "min_tx_entries_per_subcrq = %lld\n",
5674 			   adapter->min_tx_entries_per_subcrq);
5675 		break;
5676 	case MIN_RX_ADD_ENTRIES_PER_SUBCRQ:
5677 		adapter->min_rx_add_entries_per_subcrq =
5678 		    be64_to_cpu(crq->query_capability.number);
5679 		netdev_dbg(netdev, "min_rx_add_entrs_per_subcrq = %lld\n",
5680 			   adapter->min_rx_add_entries_per_subcrq);
5681 		break;
5682 	case MAX_TX_ENTRIES_PER_SUBCRQ:
5683 		adapter->max_tx_entries_per_subcrq =
5684 		    be64_to_cpu(crq->query_capability.number);
5685 		netdev_dbg(netdev, "max_tx_entries_per_subcrq = %lld\n",
5686 			   adapter->max_tx_entries_per_subcrq);
5687 		break;
5688 	case MAX_RX_ADD_ENTRIES_PER_SUBCRQ:
5689 		adapter->max_rx_add_entries_per_subcrq =
5690 		    be64_to_cpu(crq->query_capability.number);
5691 		netdev_dbg(netdev, "max_rx_add_entrs_per_subcrq = %lld\n",
5692 			   adapter->max_rx_add_entries_per_subcrq);
5693 		break;
5694 	case TCP_IP_OFFLOAD:
5695 		adapter->tcp_ip_offload =
5696 		    be64_to_cpu(crq->query_capability.number);
5697 		netdev_dbg(netdev, "tcp_ip_offload = %lld\n",
5698 			   adapter->tcp_ip_offload);
5699 		break;
5700 	case PROMISC_SUPPORTED:
5701 		adapter->promisc_supported =
5702 		    be64_to_cpu(crq->query_capability.number);
5703 		netdev_dbg(netdev, "promisc_supported = %lld\n",
5704 			   adapter->promisc_supported);
5705 		break;
5706 	case MIN_MTU:
5707 		adapter->min_mtu = be64_to_cpu(crq->query_capability.number);
5708 		netdev->min_mtu = adapter->min_mtu - ETH_HLEN;
5709 		netdev_dbg(netdev, "min_mtu = %lld\n", adapter->min_mtu);
5710 		break;
5711 	case MAX_MTU:
5712 		adapter->max_mtu = be64_to_cpu(crq->query_capability.number);
5713 		netdev->max_mtu = adapter->max_mtu - ETH_HLEN;
5714 		netdev_dbg(netdev, "max_mtu = %lld\n", adapter->max_mtu);
5715 		break;
5716 	case MAX_MULTICAST_FILTERS:
5717 		adapter->max_multicast_filters =
5718 		    be64_to_cpu(crq->query_capability.number);
5719 		netdev_dbg(netdev, "max_multicast_filters = %lld\n",
5720 			   adapter->max_multicast_filters);
5721 		break;
5722 	case VLAN_HEADER_INSERTION:
5723 		adapter->vlan_header_insertion =
5724 		    be64_to_cpu(crq->query_capability.number);
5725 		if (adapter->vlan_header_insertion)
5726 			netdev->features |= NETIF_F_HW_VLAN_STAG_TX;
5727 		netdev_dbg(netdev, "vlan_header_insertion = %lld\n",
5728 			   adapter->vlan_header_insertion);
5729 		break;
5730 	case RX_VLAN_HEADER_INSERTION:
5731 		adapter->rx_vlan_header_insertion =
5732 		    be64_to_cpu(crq->query_capability.number);
5733 		netdev_dbg(netdev, "rx_vlan_header_insertion = %lld\n",
5734 			   adapter->rx_vlan_header_insertion);
5735 		break;
5736 	case MAX_TX_SG_ENTRIES:
5737 		adapter->max_tx_sg_entries =
5738 		    be64_to_cpu(crq->query_capability.number);
5739 		netdev_dbg(netdev, "max_tx_sg_entries = %lld\n",
5740 			   adapter->max_tx_sg_entries);
5741 		break;
5742 	case RX_SG_SUPPORTED:
5743 		adapter->rx_sg_supported =
5744 		    be64_to_cpu(crq->query_capability.number);
5745 		netdev_dbg(netdev, "rx_sg_supported = %lld\n",
5746 			   adapter->rx_sg_supported);
5747 		break;
5748 	case OPT_TX_COMP_SUB_QUEUES:
5749 		adapter->opt_tx_comp_sub_queues =
5750 		    be64_to_cpu(crq->query_capability.number);
5751 		netdev_dbg(netdev, "opt_tx_comp_sub_queues = %lld\n",
5752 			   adapter->opt_tx_comp_sub_queues);
5753 		break;
5754 	case OPT_RX_COMP_QUEUES:
5755 		adapter->opt_rx_comp_queues =
5756 		    be64_to_cpu(crq->query_capability.number);
5757 		netdev_dbg(netdev, "opt_rx_comp_queues = %lld\n",
5758 			   adapter->opt_rx_comp_queues);
5759 		break;
5760 	case OPT_RX_BUFADD_Q_PER_RX_COMP_Q:
5761 		adapter->opt_rx_bufadd_q_per_rx_comp_q =
5762 		    be64_to_cpu(crq->query_capability.number);
5763 		netdev_dbg(netdev, "opt_rx_bufadd_q_per_rx_comp_q = %lld\n",
5764 			   adapter->opt_rx_bufadd_q_per_rx_comp_q);
5765 		break;
5766 	case OPT_TX_ENTRIES_PER_SUBCRQ:
5767 		adapter->opt_tx_entries_per_subcrq =
5768 		    be64_to_cpu(crq->query_capability.number);
5769 		netdev_dbg(netdev, "opt_tx_entries_per_subcrq = %lld\n",
5770 			   adapter->opt_tx_entries_per_subcrq);
5771 		break;
5772 	case OPT_RXBA_ENTRIES_PER_SUBCRQ:
5773 		adapter->opt_rxba_entries_per_subcrq =
5774 		    be64_to_cpu(crq->query_capability.number);
5775 		netdev_dbg(netdev, "opt_rxba_entries_per_subcrq = %lld\n",
5776 			   adapter->opt_rxba_entries_per_subcrq);
5777 		break;
5778 	case TX_RX_DESC_REQ:
5779 		adapter->tx_rx_desc_req = crq->query_capability.number;
5780 		netdev_dbg(netdev, "tx_rx_desc_req = %llx\n",
5781 			   adapter->tx_rx_desc_req);
5782 		break;
5783 
5784 	default:
5785 		netdev_err(netdev, "Got invalid cap rsp %d\n",
5786 			   crq->query_capability.capability);
5787 	}
5788 
5789 out:
5790 	if (atomic_read(&adapter->running_cap_crqs) == 0)
5791 		send_request_cap(adapter, 0);
5792 }
5793 
5794 static int send_query_phys_parms(struct ibmvnic_adapter *adapter)
5795 {
5796 	union ibmvnic_crq crq;
5797 	int rc;
5798 
5799 	memset(&crq, 0, sizeof(crq));
5800 	crq.query_phys_parms.first = IBMVNIC_CRQ_CMD;
5801 	crq.query_phys_parms.cmd = QUERY_PHYS_PARMS;
5802 
5803 	mutex_lock(&adapter->fw_lock);
5804 	adapter->fw_done_rc = 0;
5805 	reinit_completion(&adapter->fw_done);
5806 
5807 	rc = ibmvnic_send_crq(adapter, &crq);
5808 	if (rc) {
5809 		mutex_unlock(&adapter->fw_lock);
5810 		return rc;
5811 	}
5812 
5813 	rc = ibmvnic_wait_for_completion(adapter, &adapter->fw_done, 10000);
5814 	if (rc) {
5815 		mutex_unlock(&adapter->fw_lock);
5816 		return rc;
5817 	}
5818 
5819 	mutex_unlock(&adapter->fw_lock);
5820 	return adapter->fw_done_rc ? -EIO : 0;
5821 }
5822 
5823 static int handle_query_phys_parms_rsp(union ibmvnic_crq *crq,
5824 				       struct ibmvnic_adapter *adapter)
5825 {
5826 	struct net_device *netdev = adapter->netdev;
5827 	int rc;
5828 	__be32 rspeed = cpu_to_be32(crq->query_phys_parms_rsp.speed);
5829 
5830 	rc = crq->query_phys_parms_rsp.rc.code;
5831 	if (rc) {
5832 		netdev_err(netdev, "Error %d in QUERY_PHYS_PARMS\n", rc);
5833 		return rc;
5834 	}
5835 	switch (rspeed) {
5836 	case IBMVNIC_10MBPS:
5837 		adapter->speed = SPEED_10;
5838 		break;
5839 	case IBMVNIC_100MBPS:
5840 		adapter->speed = SPEED_100;
5841 		break;
5842 	case IBMVNIC_1GBPS:
5843 		adapter->speed = SPEED_1000;
5844 		break;
5845 	case IBMVNIC_10GBPS:
5846 		adapter->speed = SPEED_10000;
5847 		break;
5848 	case IBMVNIC_25GBPS:
5849 		adapter->speed = SPEED_25000;
5850 		break;
5851 	case IBMVNIC_40GBPS:
5852 		adapter->speed = SPEED_40000;
5853 		break;
5854 	case IBMVNIC_50GBPS:
5855 		adapter->speed = SPEED_50000;
5856 		break;
5857 	case IBMVNIC_100GBPS:
5858 		adapter->speed = SPEED_100000;
5859 		break;
5860 	case IBMVNIC_200GBPS:
5861 		adapter->speed = SPEED_200000;
5862 		break;
5863 	default:
5864 		if (netif_carrier_ok(netdev))
5865 			netdev_warn(netdev, "Unknown speed 0x%08x\n", rspeed);
5866 		adapter->speed = SPEED_UNKNOWN;
5867 	}
5868 	if (crq->query_phys_parms_rsp.flags1 & IBMVNIC_FULL_DUPLEX)
5869 		adapter->duplex = DUPLEX_FULL;
5870 	else if (crq->query_phys_parms_rsp.flags1 & IBMVNIC_HALF_DUPLEX)
5871 		adapter->duplex = DUPLEX_HALF;
5872 	else
5873 		adapter->duplex = DUPLEX_UNKNOWN;
5874 
5875 	return rc;
5876 }
5877 
5878 static void ibmvnic_handle_crq(union ibmvnic_crq *crq,
5879 			       struct ibmvnic_adapter *adapter)
5880 {
5881 	struct ibmvnic_generic_crq *gen_crq = &crq->generic;
5882 	struct net_device *netdev = adapter->netdev;
5883 	struct device *dev = &adapter->vdev->dev;
5884 	u64 *u64_crq = (u64 *)crq;
5885 	long rc;
5886 
5887 	netdev_dbg(netdev, "Handling CRQ: %016lx %016lx\n",
5888 		   (unsigned long)cpu_to_be64(u64_crq[0]),
5889 		   (unsigned long)cpu_to_be64(u64_crq[1]));
5890 	switch (gen_crq->first) {
5891 	case IBMVNIC_CRQ_INIT_RSP:
5892 		switch (gen_crq->cmd) {
5893 		case IBMVNIC_CRQ_INIT:
5894 			dev_info(dev, "Partner initialized\n");
5895 			adapter->from_passive_init = true;
5896 			/* Discard any stale login responses from prev reset.
5897 			 * CHECK: should we clear even on INIT_COMPLETE?
5898 			 */
5899 			adapter->login_pending = false;
5900 
5901 			if (adapter->state == VNIC_DOWN)
5902 				rc = ibmvnic_reset(adapter, VNIC_RESET_PASSIVE_INIT);
5903 			else
5904 				rc = ibmvnic_reset(adapter, VNIC_RESET_FAILOVER);
5905 
5906 			if (rc && rc != -EBUSY) {
5907 				/* We were unable to schedule the failover
5908 				 * reset either because the adapter was still
5909 				 * probing (eg: during kexec) or we could not
5910 				 * allocate memory. Clear the failover_pending
5911 				 * flag since no one else will. We ignore
5912 				 * EBUSY because it means either FAILOVER reset
5913 				 * is already scheduled or the adapter is
5914 				 * being removed.
5915 				 */
5916 				netdev_err(netdev,
5917 					   "Error %ld scheduling failover reset\n",
5918 					   rc);
5919 				adapter->failover_pending = false;
5920 			}
5921 
5922 			if (!completion_done(&adapter->init_done)) {
5923 				if (!adapter->init_done_rc)
5924 					adapter->init_done_rc = -EAGAIN;
5925 				complete(&adapter->init_done);
5926 			}
5927 
5928 			break;
5929 		case IBMVNIC_CRQ_INIT_COMPLETE:
5930 			dev_info(dev, "Partner initialization complete\n");
5931 			adapter->crq.active = true;
5932 			send_version_xchg(adapter);
5933 			break;
5934 		default:
5935 			dev_err(dev, "Unknown crq cmd: %d\n", gen_crq->cmd);
5936 		}
5937 		return;
5938 	case IBMVNIC_CRQ_XPORT_EVENT:
5939 		netif_carrier_off(netdev);
5940 		adapter->crq.active = false;
5941 		/* terminate any thread waiting for a response
5942 		 * from the device
5943 		 */
5944 		if (!completion_done(&adapter->fw_done)) {
5945 			adapter->fw_done_rc = -EIO;
5946 			complete(&adapter->fw_done);
5947 		}
5948 
5949 		/* if we got here during crq-init, retry crq-init */
5950 		if (!completion_done(&adapter->init_done)) {
5951 			adapter->init_done_rc = -EAGAIN;
5952 			complete(&adapter->init_done);
5953 		}
5954 
5955 		if (!completion_done(&adapter->stats_done))
5956 			complete(&adapter->stats_done);
5957 		if (test_bit(0, &adapter->resetting))
5958 			adapter->force_reset_recovery = true;
5959 		if (gen_crq->cmd == IBMVNIC_PARTITION_MIGRATED) {
5960 			dev_info(dev, "Migrated, re-enabling adapter\n");
5961 			ibmvnic_reset(adapter, VNIC_RESET_MOBILITY);
5962 		} else if (gen_crq->cmd == IBMVNIC_DEVICE_FAILOVER) {
5963 			dev_info(dev, "Backing device failover detected\n");
5964 			adapter->failover_pending = true;
5965 		} else {
5966 			/* The adapter lost the connection */
5967 			dev_err(dev, "Virtual Adapter failed (rc=%d)\n",
5968 				gen_crq->cmd);
5969 			ibmvnic_reset(adapter, VNIC_RESET_FATAL);
5970 		}
5971 		return;
5972 	case IBMVNIC_CRQ_CMD_RSP:
5973 		break;
5974 	default:
5975 		dev_err(dev, "Got an invalid msg type 0x%02x\n",
5976 			gen_crq->first);
5977 		return;
5978 	}
5979 
5980 	switch (gen_crq->cmd) {
5981 	case VERSION_EXCHANGE_RSP:
5982 		rc = crq->version_exchange_rsp.rc.code;
5983 		if (rc) {
5984 			dev_err(dev, "Error %ld in VERSION_EXCHG_RSP\n", rc);
5985 			break;
5986 		}
5987 		ibmvnic_version =
5988 			    be16_to_cpu(crq->version_exchange_rsp.version);
5989 		dev_info(dev, "Partner protocol version is %d\n",
5990 			 ibmvnic_version);
5991 		send_query_cap(adapter);
5992 		break;
5993 	case QUERY_CAPABILITY_RSP:
5994 		handle_query_cap_rsp(crq, adapter);
5995 		break;
5996 	case QUERY_MAP_RSP:
5997 		handle_query_map_rsp(crq, adapter);
5998 		break;
5999 	case REQUEST_MAP_RSP:
6000 		adapter->fw_done_rc = crq->request_map_rsp.rc.code;
6001 		complete(&adapter->fw_done);
6002 		break;
6003 	case REQUEST_UNMAP_RSP:
6004 		handle_request_unmap_rsp(crq, adapter);
6005 		break;
6006 	case REQUEST_CAPABILITY_RSP:
6007 		handle_request_cap_rsp(crq, adapter);
6008 		break;
6009 	case LOGIN_RSP:
6010 		netdev_dbg(netdev, "Got Login Response\n");
6011 		handle_login_rsp(crq, adapter);
6012 		break;
6013 	case LOGICAL_LINK_STATE_RSP:
6014 		netdev_dbg(netdev,
6015 			   "Got Logical Link State Response, state: %d rc: %d\n",
6016 			   crq->logical_link_state_rsp.link_state,
6017 			   crq->logical_link_state_rsp.rc.code);
6018 		adapter->logical_link_state =
6019 		    crq->logical_link_state_rsp.link_state;
6020 		adapter->init_done_rc = crq->logical_link_state_rsp.rc.code;
6021 		complete(&adapter->init_done);
6022 		break;
6023 	case LINK_STATE_INDICATION:
6024 		netdev_dbg(netdev, "Got Logical Link State Indication\n");
6025 		adapter->phys_link_state =
6026 		    crq->link_state_indication.phys_link_state;
6027 		adapter->logical_link_state =
6028 		    crq->link_state_indication.logical_link_state;
6029 		if (adapter->phys_link_state && adapter->logical_link_state)
6030 			netif_carrier_on(netdev);
6031 		else
6032 			netif_carrier_off(netdev);
6033 		break;
6034 	case CHANGE_MAC_ADDR_RSP:
6035 		netdev_dbg(netdev, "Got MAC address change Response\n");
6036 		adapter->fw_done_rc = handle_change_mac_rsp(crq, adapter);
6037 		break;
6038 	case ERROR_INDICATION:
6039 		netdev_dbg(netdev, "Got Error Indication\n");
6040 		handle_error_indication(crq, adapter);
6041 		break;
6042 	case REQUEST_STATISTICS_RSP:
6043 		netdev_dbg(netdev, "Got Statistics Response\n");
6044 		complete(&adapter->stats_done);
6045 		break;
6046 	case QUERY_IP_OFFLOAD_RSP:
6047 		netdev_dbg(netdev, "Got Query IP offload Response\n");
6048 		handle_query_ip_offload_rsp(adapter);
6049 		break;
6050 	case MULTICAST_CTRL_RSP:
6051 		netdev_dbg(netdev, "Got multicast control Response\n");
6052 		break;
6053 	case CONTROL_IP_OFFLOAD_RSP:
6054 		netdev_dbg(netdev, "Got Control IP offload Response\n");
6055 		dma_unmap_single(dev, adapter->ip_offload_ctrl_tok,
6056 				 sizeof(adapter->ip_offload_ctrl),
6057 				 DMA_TO_DEVICE);
6058 		complete(&adapter->init_done);
6059 		break;
6060 	case COLLECT_FW_TRACE_RSP:
6061 		netdev_dbg(netdev, "Got Collect firmware trace Response\n");
6062 		complete(&adapter->fw_done);
6063 		break;
6064 	case GET_VPD_SIZE_RSP:
6065 		handle_vpd_size_rsp(crq, adapter);
6066 		break;
6067 	case GET_VPD_RSP:
6068 		handle_vpd_rsp(crq, adapter);
6069 		break;
6070 	case QUERY_PHYS_PARMS_RSP:
6071 		adapter->fw_done_rc = handle_query_phys_parms_rsp(crq, adapter);
6072 		complete(&adapter->fw_done);
6073 		break;
6074 	default:
6075 		netdev_err(netdev, "Got an invalid cmd type 0x%02x\n",
6076 			   gen_crq->cmd);
6077 	}
6078 }
6079 
6080 static irqreturn_t ibmvnic_interrupt(int irq, void *instance)
6081 {
6082 	struct ibmvnic_adapter *adapter = instance;
6083 
6084 	tasklet_schedule(&adapter->tasklet);
6085 	return IRQ_HANDLED;
6086 }
6087 
6088 static void ibmvnic_tasklet(struct tasklet_struct *t)
6089 {
6090 	struct ibmvnic_adapter *adapter = from_tasklet(adapter, t, tasklet);
6091 	struct ibmvnic_crq_queue *queue = &adapter->crq;
6092 	union ibmvnic_crq *crq;
6093 	unsigned long flags;
6094 
6095 	spin_lock_irqsave(&queue->lock, flags);
6096 
6097 	/* Pull all the valid messages off the CRQ */
6098 	while ((crq = ibmvnic_next_crq(adapter)) != NULL) {
6099 		/* This barrier makes sure ibmvnic_next_crq()'s
6100 		 * crq->generic.first & IBMVNIC_CRQ_CMD_RSP is loaded
6101 		 * before ibmvnic_handle_crq()'s
6102 		 * switch(gen_crq->first) and switch(gen_crq->cmd).
6103 		 */
6104 		dma_rmb();
6105 		ibmvnic_handle_crq(crq, adapter);
6106 		crq->generic.first = 0;
6107 	}
6108 
6109 	spin_unlock_irqrestore(&queue->lock, flags);
6110 }
6111 
6112 static int ibmvnic_reenable_crq_queue(struct ibmvnic_adapter *adapter)
6113 {
6114 	struct vio_dev *vdev = adapter->vdev;
6115 	int rc;
6116 
6117 	do {
6118 		rc = plpar_hcall_norets(H_ENABLE_CRQ, vdev->unit_address);
6119 	} while (rc == H_IN_PROGRESS || rc == H_BUSY || H_IS_LONG_BUSY(rc));
6120 
6121 	if (rc)
6122 		dev_err(&vdev->dev, "Error enabling adapter (rc=%d)\n", rc);
6123 
6124 	return rc;
6125 }
6126 
6127 static int ibmvnic_reset_crq(struct ibmvnic_adapter *adapter)
6128 {
6129 	struct ibmvnic_crq_queue *crq = &adapter->crq;
6130 	struct device *dev = &adapter->vdev->dev;
6131 	struct vio_dev *vdev = adapter->vdev;
6132 	int rc;
6133 
6134 	/* Close the CRQ */
6135 	do {
6136 		rc = plpar_hcall_norets(H_FREE_CRQ, vdev->unit_address);
6137 	} while (rc == H_BUSY || H_IS_LONG_BUSY(rc));
6138 
6139 	/* Clean out the queue */
6140 	if (!crq->msgs)
6141 		return -EINVAL;
6142 
6143 	memset(crq->msgs, 0, PAGE_SIZE);
6144 	crq->cur = 0;
6145 	crq->active = false;
6146 
6147 	/* And re-open it again */
6148 	rc = plpar_hcall_norets(H_REG_CRQ, vdev->unit_address,
6149 				crq->msg_token, PAGE_SIZE);
6150 
6151 	if (rc == H_CLOSED)
6152 		/* Adapter is good, but other end is not ready */
6153 		dev_warn(dev, "Partner adapter not ready\n");
6154 	else if (rc != 0)
6155 		dev_warn(dev, "Couldn't register crq (rc=%d)\n", rc);
6156 
6157 	return rc;
6158 }
6159 
6160 static void release_crq_queue(struct ibmvnic_adapter *adapter)
6161 {
6162 	struct ibmvnic_crq_queue *crq = &adapter->crq;
6163 	struct vio_dev *vdev = adapter->vdev;
6164 	long rc;
6165 
6166 	if (!crq->msgs)
6167 		return;
6168 
6169 	netdev_dbg(adapter->netdev, "Releasing CRQ\n");
6170 	free_irq(vdev->irq, adapter);
6171 	tasklet_kill(&adapter->tasklet);
6172 	do {
6173 		rc = plpar_hcall_norets(H_FREE_CRQ, vdev->unit_address);
6174 	} while (rc == H_BUSY || H_IS_LONG_BUSY(rc));
6175 
6176 	dma_unmap_single(&vdev->dev, crq->msg_token, PAGE_SIZE,
6177 			 DMA_BIDIRECTIONAL);
6178 	free_page((unsigned long)crq->msgs);
6179 	crq->msgs = NULL;
6180 	crq->active = false;
6181 }
6182 
6183 static int init_crq_queue(struct ibmvnic_adapter *adapter)
6184 {
6185 	struct ibmvnic_crq_queue *crq = &adapter->crq;
6186 	struct device *dev = &adapter->vdev->dev;
6187 	struct vio_dev *vdev = adapter->vdev;
6188 	int rc, retrc = -ENOMEM;
6189 
6190 	if (crq->msgs)
6191 		return 0;
6192 
6193 	crq->msgs = (union ibmvnic_crq *)get_zeroed_page(GFP_KERNEL);
6194 	/* Should we allocate more than one page? */
6195 
6196 	if (!crq->msgs)
6197 		return -ENOMEM;
6198 
6199 	crq->size = PAGE_SIZE / sizeof(*crq->msgs);
6200 	crq->msg_token = dma_map_single(dev, crq->msgs, PAGE_SIZE,
6201 					DMA_BIDIRECTIONAL);
6202 	if (dma_mapping_error(dev, crq->msg_token))
6203 		goto map_failed;
6204 
6205 	rc = plpar_hcall_norets(H_REG_CRQ, vdev->unit_address,
6206 				crq->msg_token, PAGE_SIZE);
6207 
6208 	if (rc == H_RESOURCE)
6209 		/* maybe kexecing and resource is busy. try a reset */
6210 		rc = ibmvnic_reset_crq(adapter);
6211 	retrc = rc;
6212 
6213 	if (rc == H_CLOSED) {
6214 		dev_warn(dev, "Partner adapter not ready\n");
6215 	} else if (rc) {
6216 		dev_warn(dev, "Error %d opening adapter\n", rc);
6217 		goto reg_crq_failed;
6218 	}
6219 
6220 	retrc = 0;
6221 
6222 	tasklet_setup(&adapter->tasklet, (void *)ibmvnic_tasklet);
6223 
6224 	netdev_dbg(adapter->netdev, "registering irq 0x%x\n", vdev->irq);
6225 	snprintf(crq->name, sizeof(crq->name), "ibmvnic-%x",
6226 		 adapter->vdev->unit_address);
6227 	rc = request_irq(vdev->irq, ibmvnic_interrupt, 0, crq->name, adapter);
6228 	if (rc) {
6229 		dev_err(dev, "Couldn't register irq 0x%x. rc=%d\n",
6230 			vdev->irq, rc);
6231 		goto req_irq_failed;
6232 	}
6233 
6234 	rc = vio_enable_interrupts(vdev);
6235 	if (rc) {
6236 		dev_err(dev, "Error %d enabling interrupts\n", rc);
6237 		goto req_irq_failed;
6238 	}
6239 
6240 	crq->cur = 0;
6241 	spin_lock_init(&crq->lock);
6242 
6243 	/* process any CRQs that were queued before we enabled interrupts */
6244 	tasklet_schedule(&adapter->tasklet);
6245 
6246 	return retrc;
6247 
6248 req_irq_failed:
6249 	tasklet_kill(&adapter->tasklet);
6250 	do {
6251 		rc = plpar_hcall_norets(H_FREE_CRQ, vdev->unit_address);
6252 	} while (rc == H_BUSY || H_IS_LONG_BUSY(rc));
6253 reg_crq_failed:
6254 	dma_unmap_single(dev, crq->msg_token, PAGE_SIZE, DMA_BIDIRECTIONAL);
6255 map_failed:
6256 	free_page((unsigned long)crq->msgs);
6257 	crq->msgs = NULL;
6258 	return retrc;
6259 }
6260 
6261 static int ibmvnic_reset_init(struct ibmvnic_adapter *adapter, bool reset)
6262 {
6263 	struct device *dev = &adapter->vdev->dev;
6264 	unsigned long timeout = msecs_to_jiffies(20000);
6265 	u64 old_num_rx_queues = adapter->req_rx_queues;
6266 	u64 old_num_tx_queues = adapter->req_tx_queues;
6267 	int rc;
6268 
6269 	adapter->from_passive_init = false;
6270 
6271 	rc = ibmvnic_send_crq_init(adapter);
6272 	if (rc) {
6273 		dev_err(dev, "Send crq init failed with error %d\n", rc);
6274 		return rc;
6275 	}
6276 
6277 	if (!wait_for_completion_timeout(&adapter->init_done, timeout)) {
6278 		dev_err(dev, "Initialization sequence timed out\n");
6279 		return -ETIMEDOUT;
6280 	}
6281 
6282 	if (adapter->init_done_rc) {
6283 		release_crq_queue(adapter);
6284 		dev_err(dev, "CRQ-init failed, %d\n", adapter->init_done_rc);
6285 		return adapter->init_done_rc;
6286 	}
6287 
6288 	if (adapter->from_passive_init) {
6289 		adapter->state = VNIC_OPEN;
6290 		adapter->from_passive_init = false;
6291 		dev_err(dev, "CRQ-init failed, passive-init\n");
6292 		return -EINVAL;
6293 	}
6294 
6295 	if (reset &&
6296 	    test_bit(0, &adapter->resetting) && !adapter->wait_for_reset &&
6297 	    adapter->reset_reason != VNIC_RESET_MOBILITY) {
6298 		if (adapter->req_rx_queues != old_num_rx_queues ||
6299 		    adapter->req_tx_queues != old_num_tx_queues) {
6300 			release_sub_crqs(adapter, 0);
6301 			rc = init_sub_crqs(adapter);
6302 		} else {
6303 			/* no need to reinitialize completely, but we do
6304 			 * need to clean up transmits that were in flight
6305 			 * when we processed the reset.  Failure to do so
6306 			 * will confound the upper layer, usually TCP, by
6307 			 * creating the illusion of transmits that are
6308 			 * awaiting completion.
6309 			 */
6310 			clean_tx_pools(adapter);
6311 
6312 			rc = reset_sub_crq_queues(adapter);
6313 		}
6314 	} else {
6315 		rc = init_sub_crqs(adapter);
6316 	}
6317 
6318 	if (rc) {
6319 		dev_err(dev, "Initialization of sub crqs failed\n");
6320 		release_crq_queue(adapter);
6321 		return rc;
6322 	}
6323 
6324 	rc = init_sub_crq_irqs(adapter);
6325 	if (rc) {
6326 		dev_err(dev, "Failed to initialize sub crq irqs\n");
6327 		release_crq_queue(adapter);
6328 	}
6329 
6330 	return rc;
6331 }
6332 
6333 static struct device_attribute dev_attr_failover;
6334 
6335 static int ibmvnic_probe(struct vio_dev *dev, const struct vio_device_id *id)
6336 {
6337 	struct ibmvnic_adapter *adapter;
6338 	struct net_device *netdev;
6339 	unsigned char *mac_addr_p;
6340 	unsigned long flags;
6341 	bool init_success;
6342 	int rc;
6343 
6344 	dev_dbg(&dev->dev, "entering ibmvnic_probe for UA 0x%x\n",
6345 		dev->unit_address);
6346 
6347 	mac_addr_p = (unsigned char *)vio_get_attribute(dev,
6348 							VETH_MAC_ADDR, NULL);
6349 	if (!mac_addr_p) {
6350 		dev_err(&dev->dev,
6351 			"(%s:%3.3d) ERROR: Can't find MAC_ADDR attribute\n",
6352 			__FILE__, __LINE__);
6353 		return 0;
6354 	}
6355 
6356 	netdev = alloc_etherdev_mq(sizeof(struct ibmvnic_adapter),
6357 				   IBMVNIC_MAX_QUEUES);
6358 	if (!netdev)
6359 		return -ENOMEM;
6360 
6361 	adapter = netdev_priv(netdev);
6362 	adapter->state = VNIC_PROBING;
6363 	dev_set_drvdata(&dev->dev, netdev);
6364 	adapter->vdev = dev;
6365 	adapter->netdev = netdev;
6366 	adapter->login_pending = false;
6367 	memset(&adapter->map_ids, 0, sizeof(adapter->map_ids));
6368 	/* map_ids start at 1, so ensure map_id 0 is always "in-use" */
6369 	bitmap_set(adapter->map_ids, 0, 1);
6370 
6371 	ether_addr_copy(adapter->mac_addr, mac_addr_p);
6372 	eth_hw_addr_set(netdev, adapter->mac_addr);
6373 	netdev->irq = dev->irq;
6374 	netdev->netdev_ops = &ibmvnic_netdev_ops;
6375 	netdev->ethtool_ops = &ibmvnic_ethtool_ops;
6376 	SET_NETDEV_DEV(netdev, &dev->dev);
6377 
6378 	INIT_WORK(&adapter->ibmvnic_reset, __ibmvnic_reset);
6379 	INIT_DELAYED_WORK(&adapter->ibmvnic_delayed_reset,
6380 			  __ibmvnic_delayed_reset);
6381 	INIT_LIST_HEAD(&adapter->rwi_list);
6382 	spin_lock_init(&adapter->rwi_lock);
6383 	spin_lock_init(&adapter->state_lock);
6384 	mutex_init(&adapter->fw_lock);
6385 	init_completion(&adapter->probe_done);
6386 	init_completion(&adapter->init_done);
6387 	init_completion(&adapter->fw_done);
6388 	init_completion(&adapter->reset_done);
6389 	init_completion(&adapter->stats_done);
6390 	clear_bit(0, &adapter->resetting);
6391 	adapter->prev_rx_buf_sz = 0;
6392 	adapter->prev_mtu = 0;
6393 
6394 	init_success = false;
6395 	do {
6396 		reinit_init_done(adapter);
6397 
6398 		/* clear any failovers we got in the previous pass
6399 		 * since we are reinitializing the CRQ
6400 		 */
6401 		adapter->failover_pending = false;
6402 
6403 		/* If we had already initialized CRQ, we may have one or
6404 		 * more resets queued already. Discard those and release
6405 		 * the CRQ before initializing the CRQ again.
6406 		 */
6407 		release_crq_queue(adapter);
6408 
6409 		/* Since we are still in PROBING state, __ibmvnic_reset()
6410 		 * will not access the ->rwi_list and since we released CRQ,
6411 		 * we won't get _new_ transport events. But there maybe an
6412 		 * ongoing ibmvnic_reset() call. So serialize access to
6413 		 * rwi_list. If we win the race, ibvmnic_reset() could add
6414 		 * a reset after we purged but thats ok - we just may end
6415 		 * up with an extra reset (i.e similar to having two or more
6416 		 * resets in the queue at once).
6417 		 * CHECK.
6418 		 */
6419 		spin_lock_irqsave(&adapter->rwi_lock, flags);
6420 		flush_reset_queue(adapter);
6421 		spin_unlock_irqrestore(&adapter->rwi_lock, flags);
6422 
6423 		rc = init_crq_queue(adapter);
6424 		if (rc) {
6425 			dev_err(&dev->dev, "Couldn't initialize crq. rc=%d\n",
6426 				rc);
6427 			goto ibmvnic_init_fail;
6428 		}
6429 
6430 		rc = ibmvnic_reset_init(adapter, false);
6431 	} while (rc == -EAGAIN);
6432 
6433 	/* We are ignoring the error from ibmvnic_reset_init() assuming that the
6434 	 * partner is not ready. CRQ is not active. When the partner becomes
6435 	 * ready, we will do the passive init reset.
6436 	 */
6437 
6438 	if (!rc)
6439 		init_success = true;
6440 
6441 	rc = init_stats_buffers(adapter);
6442 	if (rc)
6443 		goto ibmvnic_init_fail;
6444 
6445 	rc = init_stats_token(adapter);
6446 	if (rc)
6447 		goto ibmvnic_stats_fail;
6448 
6449 	rc = device_create_file(&dev->dev, &dev_attr_failover);
6450 	if (rc)
6451 		goto ibmvnic_dev_file_err;
6452 
6453 	netif_carrier_off(netdev);
6454 
6455 	if (init_success) {
6456 		adapter->state = VNIC_PROBED;
6457 		netdev->mtu = adapter->req_mtu - ETH_HLEN;
6458 		netdev->min_mtu = adapter->min_mtu - ETH_HLEN;
6459 		netdev->max_mtu = adapter->max_mtu - ETH_HLEN;
6460 	} else {
6461 		adapter->state = VNIC_DOWN;
6462 	}
6463 
6464 	adapter->wait_for_reset = false;
6465 	adapter->last_reset_time = jiffies;
6466 
6467 	rc = register_netdev(netdev);
6468 	if (rc) {
6469 		dev_err(&dev->dev, "failed to register netdev rc=%d\n", rc);
6470 		goto ibmvnic_register_fail;
6471 	}
6472 	dev_info(&dev->dev, "ibmvnic registered\n");
6473 
6474 	rc = ibmvnic_cpu_notif_add(adapter);
6475 	if (rc) {
6476 		netdev_err(netdev, "Registering cpu notifier failed\n");
6477 		goto cpu_notif_add_failed;
6478 	}
6479 
6480 	complete(&adapter->probe_done);
6481 
6482 	return 0;
6483 
6484 cpu_notif_add_failed:
6485 	unregister_netdev(netdev);
6486 
6487 ibmvnic_register_fail:
6488 	device_remove_file(&dev->dev, &dev_attr_failover);
6489 
6490 ibmvnic_dev_file_err:
6491 	release_stats_token(adapter);
6492 
6493 ibmvnic_stats_fail:
6494 	release_stats_buffers(adapter);
6495 
6496 ibmvnic_init_fail:
6497 	release_sub_crqs(adapter, 1);
6498 	release_crq_queue(adapter);
6499 
6500 	/* cleanup worker thread after releasing CRQ so we don't get
6501 	 * transport events (i.e new work items for the worker thread).
6502 	 */
6503 	adapter->state = VNIC_REMOVING;
6504 	complete(&adapter->probe_done);
6505 	flush_work(&adapter->ibmvnic_reset);
6506 	flush_delayed_work(&adapter->ibmvnic_delayed_reset);
6507 
6508 	flush_reset_queue(adapter);
6509 
6510 	mutex_destroy(&adapter->fw_lock);
6511 	free_netdev(netdev);
6512 
6513 	return rc;
6514 }
6515 
6516 static void ibmvnic_remove(struct vio_dev *dev)
6517 {
6518 	struct net_device *netdev = dev_get_drvdata(&dev->dev);
6519 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
6520 	unsigned long flags;
6521 
6522 	spin_lock_irqsave(&adapter->state_lock, flags);
6523 
6524 	/* If ibmvnic_reset() is scheduling a reset, wait for it to
6525 	 * finish. Then, set the state to REMOVING to prevent it from
6526 	 * scheduling any more work and to have reset functions ignore
6527 	 * any resets that have already been scheduled. Drop the lock
6528 	 * after setting state, so __ibmvnic_reset() which is called
6529 	 * from the flush_work() below, can make progress.
6530 	 */
6531 	spin_lock(&adapter->rwi_lock);
6532 	adapter->state = VNIC_REMOVING;
6533 	spin_unlock(&adapter->rwi_lock);
6534 
6535 	spin_unlock_irqrestore(&adapter->state_lock, flags);
6536 
6537 	ibmvnic_cpu_notif_remove(adapter);
6538 
6539 	flush_work(&adapter->ibmvnic_reset);
6540 	flush_delayed_work(&adapter->ibmvnic_delayed_reset);
6541 
6542 	rtnl_lock();
6543 	unregister_netdevice(netdev);
6544 
6545 	release_resources(adapter);
6546 	release_rx_pools(adapter);
6547 	release_tx_pools(adapter);
6548 	release_sub_crqs(adapter, 1);
6549 	release_crq_queue(adapter);
6550 
6551 	release_stats_token(adapter);
6552 	release_stats_buffers(adapter);
6553 
6554 	adapter->state = VNIC_REMOVED;
6555 
6556 	rtnl_unlock();
6557 	mutex_destroy(&adapter->fw_lock);
6558 	device_remove_file(&dev->dev, &dev_attr_failover);
6559 	free_netdev(netdev);
6560 	dev_set_drvdata(&dev->dev, NULL);
6561 }
6562 
6563 static ssize_t failover_store(struct device *dev, struct device_attribute *attr,
6564 			      const char *buf, size_t count)
6565 {
6566 	struct net_device *netdev = dev_get_drvdata(dev);
6567 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
6568 	unsigned long retbuf[PLPAR_HCALL_BUFSIZE];
6569 	__be64 session_token;
6570 	long rc;
6571 
6572 	if (!sysfs_streq(buf, "1"))
6573 		return -EINVAL;
6574 
6575 	rc = plpar_hcall(H_VIOCTL, retbuf, adapter->vdev->unit_address,
6576 			 H_GET_SESSION_TOKEN, 0, 0, 0);
6577 	if (rc) {
6578 		netdev_err(netdev, "Couldn't retrieve session token, rc %ld\n",
6579 			   rc);
6580 		goto last_resort;
6581 	}
6582 
6583 	session_token = (__be64)retbuf[0];
6584 	netdev_dbg(netdev, "Initiating client failover, session id %llx\n",
6585 		   be64_to_cpu(session_token));
6586 	rc = plpar_hcall_norets(H_VIOCTL, adapter->vdev->unit_address,
6587 				H_SESSION_ERR_DETECTED, session_token, 0, 0);
6588 	if (rc) {
6589 		netdev_err(netdev,
6590 			   "H_VIOCTL initiated failover failed, rc %ld\n",
6591 			   rc);
6592 		goto last_resort;
6593 	}
6594 
6595 	return count;
6596 
6597 last_resort:
6598 	netdev_dbg(netdev, "Trying to send CRQ_CMD, the last resort\n");
6599 	ibmvnic_reset(adapter, VNIC_RESET_FAILOVER);
6600 
6601 	return count;
6602 }
6603 static DEVICE_ATTR_WO(failover);
6604 
6605 static unsigned long ibmvnic_get_desired_dma(struct vio_dev *vdev)
6606 {
6607 	struct net_device *netdev = dev_get_drvdata(&vdev->dev);
6608 	struct ibmvnic_adapter *adapter;
6609 	struct iommu_table *tbl;
6610 	unsigned long ret = 0;
6611 	int i;
6612 
6613 	tbl = get_iommu_table_base(&vdev->dev);
6614 
6615 	/* netdev inits at probe time along with the structures we need below*/
6616 	if (!netdev)
6617 		return IOMMU_PAGE_ALIGN(IBMVNIC_IO_ENTITLEMENT_DEFAULT, tbl);
6618 
6619 	adapter = netdev_priv(netdev);
6620 
6621 	ret += PAGE_SIZE; /* the crq message queue */
6622 	ret += IOMMU_PAGE_ALIGN(sizeof(struct ibmvnic_statistics), tbl);
6623 
6624 	for (i = 0; i < adapter->req_tx_queues + adapter->req_rx_queues; i++)
6625 		ret += 4 * PAGE_SIZE; /* the scrq message queue */
6626 
6627 	for (i = 0; i < adapter->num_active_rx_pools; i++)
6628 		ret += adapter->rx_pool[i].size *
6629 		    IOMMU_PAGE_ALIGN(adapter->rx_pool[i].buff_size, tbl);
6630 
6631 	return ret;
6632 }
6633 
6634 static int ibmvnic_resume(struct device *dev)
6635 {
6636 	struct net_device *netdev = dev_get_drvdata(dev);
6637 	struct ibmvnic_adapter *adapter = netdev_priv(netdev);
6638 
6639 	if (adapter->state != VNIC_OPEN)
6640 		return 0;
6641 
6642 	tasklet_schedule(&adapter->tasklet);
6643 
6644 	return 0;
6645 }
6646 
6647 static const struct vio_device_id ibmvnic_device_table[] = {
6648 	{"network", "IBM,vnic"},
6649 	{"", "" }
6650 };
6651 MODULE_DEVICE_TABLE(vio, ibmvnic_device_table);
6652 
6653 static const struct dev_pm_ops ibmvnic_pm_ops = {
6654 	.resume = ibmvnic_resume
6655 };
6656 
6657 static struct vio_driver ibmvnic_driver = {
6658 	.id_table       = ibmvnic_device_table,
6659 	.probe          = ibmvnic_probe,
6660 	.remove         = ibmvnic_remove,
6661 	.get_desired_dma = ibmvnic_get_desired_dma,
6662 	.name		= ibmvnic_driver_name,
6663 	.pm		= &ibmvnic_pm_ops,
6664 };
6665 
6666 /* module functions */
6667 static int __init ibmvnic_module_init(void)
6668 {
6669 	int ret;
6670 
6671 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "net/ibmvnic:online",
6672 				      ibmvnic_cpu_online,
6673 				      ibmvnic_cpu_down_prep);
6674 	if (ret < 0)
6675 		goto out;
6676 	ibmvnic_online = ret;
6677 	ret = cpuhp_setup_state_multi(CPUHP_IBMVNIC_DEAD, "net/ibmvnic:dead",
6678 				      NULL, ibmvnic_cpu_dead);
6679 	if (ret)
6680 		goto err_dead;
6681 
6682 	ret = vio_register_driver(&ibmvnic_driver);
6683 	if (ret)
6684 		goto err_vio_register;
6685 
6686 	pr_info("%s: %s %s\n", ibmvnic_driver_name, ibmvnic_driver_string,
6687 		IBMVNIC_DRIVER_VERSION);
6688 
6689 	return 0;
6690 err_vio_register:
6691 	cpuhp_remove_multi_state(CPUHP_IBMVNIC_DEAD);
6692 err_dead:
6693 	cpuhp_remove_multi_state(ibmvnic_online);
6694 out:
6695 	return ret;
6696 }
6697 
6698 static void __exit ibmvnic_module_exit(void)
6699 {
6700 	vio_unregister_driver(&ibmvnic_driver);
6701 	cpuhp_remove_multi_state(CPUHP_IBMVNIC_DEAD);
6702 	cpuhp_remove_multi_state(ibmvnic_online);
6703 }
6704 
6705 module_init(ibmvnic_module_init);
6706 module_exit(ibmvnic_module_exit);
6707