xref: /linux/drivers/net/ethernet/chelsio/cxgb4/cxgb4_main.c (revision 0408c58be5a475c99b271f08d85859f7b59ec767)
1 /*
2  * This file is part of the Chelsio T4 Ethernet driver for Linux.
3  *
4  * Copyright (c) 2003-2016 Chelsio Communications, Inc. All rights reserved.
5  *
6  * This software is available to you under a choice of one of two
7  * licenses.  You may choose to be licensed under the terms of the GNU
8  * General Public License (GPL) Version 2, available from the file
9  * COPYING in the main directory of this source tree, or the
10  * OpenIB.org BSD license below:
11  *
12  *     Redistribution and use in source and binary forms, with or
13  *     without modification, are permitted provided that the following
14  *     conditions are met:
15  *
16  *      - Redistributions of source code must retain the above
17  *        copyright notice, this list of conditions and the following
18  *        disclaimer.
19  *
20  *      - Redistributions in binary form must reproduce the above
21  *        copyright notice, this list of conditions and the following
22  *        disclaimer in the documentation and/or other materials
23  *        provided with the distribution.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
29  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
30  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
31  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32  * SOFTWARE.
33  */
34 
35 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
36 
37 #include <linux/bitmap.h>
38 #include <linux/crc32.h>
39 #include <linux/ctype.h>
40 #include <linux/debugfs.h>
41 #include <linux/err.h>
42 #include <linux/etherdevice.h>
43 #include <linux/firmware.h>
44 #include <linux/if.h>
45 #include <linux/if_vlan.h>
46 #include <linux/init.h>
47 #include <linux/log2.h>
48 #include <linux/mdio.h>
49 #include <linux/module.h>
50 #include <linux/moduleparam.h>
51 #include <linux/mutex.h>
52 #include <linux/netdevice.h>
53 #include <linux/pci.h>
54 #include <linux/aer.h>
55 #include <linux/rtnetlink.h>
56 #include <linux/sched.h>
57 #include <linux/seq_file.h>
58 #include <linux/sockios.h>
59 #include <linux/vmalloc.h>
60 #include <linux/workqueue.h>
61 #include <net/neighbour.h>
62 #include <net/netevent.h>
63 #include <net/addrconf.h>
64 #include <net/bonding.h>
65 #include <net/addrconf.h>
66 #include <linux/uaccess.h>
67 #include <linux/crash_dump.h>
68 
69 #include "cxgb4.h"
70 #include "cxgb4_filter.h"
71 #include "t4_regs.h"
72 #include "t4_values.h"
73 #include "t4_msg.h"
74 #include "t4fw_api.h"
75 #include "t4fw_version.h"
76 #include "cxgb4_dcb.h"
77 #include "cxgb4_debugfs.h"
78 #include "clip_tbl.h"
79 #include "l2t.h"
80 #include "sched.h"
81 #include "cxgb4_tc_u32.h"
82 
83 char cxgb4_driver_name[] = KBUILD_MODNAME;
84 
85 #ifdef DRV_VERSION
86 #undef DRV_VERSION
87 #endif
88 #define DRV_VERSION "2.0.0-ko"
89 const char cxgb4_driver_version[] = DRV_VERSION;
90 #define DRV_DESC "Chelsio T4/T5/T6 Network Driver"
91 
92 #define DFLT_MSG_ENABLE (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK | \
93 			 NETIF_MSG_TIMER | NETIF_MSG_IFDOWN | NETIF_MSG_IFUP |\
94 			 NETIF_MSG_RX_ERR | NETIF_MSG_TX_ERR)
95 
96 /* Macros needed to support the PCI Device ID Table ...
97  */
98 #define CH_PCI_DEVICE_ID_TABLE_DEFINE_BEGIN \
99 	static const struct pci_device_id cxgb4_pci_tbl[] = {
100 #define CH_PCI_DEVICE_ID_FUNCTION 0x4
101 
102 /* Include PCI Device IDs for both PF4 and PF0-3 so our PCI probe() routine is
103  * called for both.
104  */
105 #define CH_PCI_DEVICE_ID_FUNCTION2 0x0
106 
107 #define CH_PCI_ID_TABLE_ENTRY(devid) \
108 		{PCI_VDEVICE(CHELSIO, (devid)), 4}
109 
110 #define CH_PCI_DEVICE_ID_TABLE_DEFINE_END \
111 		{ 0, } \
112 	}
113 
114 #include "t4_pci_id_tbl.h"
115 
116 #define FW4_FNAME "cxgb4/t4fw.bin"
117 #define FW5_FNAME "cxgb4/t5fw.bin"
118 #define FW6_FNAME "cxgb4/t6fw.bin"
119 #define FW4_CFNAME "cxgb4/t4-config.txt"
120 #define FW5_CFNAME "cxgb4/t5-config.txt"
121 #define FW6_CFNAME "cxgb4/t6-config.txt"
122 #define PHY_AQ1202_FIRMWARE "cxgb4/aq1202_fw.cld"
123 #define PHY_BCM84834_FIRMWARE "cxgb4/bcm8483.bin"
124 #define PHY_AQ1202_DEVICEID 0x4409
125 #define PHY_BCM84834_DEVICEID 0x4486
126 
127 MODULE_DESCRIPTION(DRV_DESC);
128 MODULE_AUTHOR("Chelsio Communications");
129 MODULE_LICENSE("Dual BSD/GPL");
130 MODULE_VERSION(DRV_VERSION);
131 MODULE_DEVICE_TABLE(pci, cxgb4_pci_tbl);
132 MODULE_FIRMWARE(FW4_FNAME);
133 MODULE_FIRMWARE(FW5_FNAME);
134 MODULE_FIRMWARE(FW6_FNAME);
135 
136 /*
137  * The driver uses the best interrupt scheme available on a platform in the
138  * order MSI-X, MSI, legacy INTx interrupts.  This parameter determines which
139  * of these schemes the driver may consider as follows:
140  *
141  * msi = 2: choose from among all three options
142  * msi = 1: only consider MSI and INTx interrupts
143  * msi = 0: force INTx interrupts
144  */
145 static int msi = 2;
146 
147 module_param(msi, int, 0644);
148 MODULE_PARM_DESC(msi, "whether to use INTx (0), MSI (1) or MSI-X (2)");
149 
150 /*
151  * Normally we tell the chip to deliver Ingress Packets into our DMA buffers
152  * offset by 2 bytes in order to have the IP headers line up on 4-byte
153  * boundaries.  This is a requirement for many architectures which will throw
154  * a machine check fault if an attempt is made to access one of the 4-byte IP
155  * header fields on a non-4-byte boundary.  And it's a major performance issue
156  * even on some architectures which allow it like some implementations of the
157  * x86 ISA.  However, some architectures don't mind this and for some very
158  * edge-case performance sensitive applications (like forwarding large volumes
159  * of small packets), setting this DMA offset to 0 will decrease the number of
160  * PCI-E Bus transfers enough to measurably affect performance.
161  */
162 static int rx_dma_offset = 2;
163 
164 /* TX Queue select used to determine what algorithm to use for selecting TX
165  * queue. Select between the kernel provided function (select_queue=0) or user
166  * cxgb_select_queue function (select_queue=1)
167  *
168  * Default: select_queue=0
169  */
170 static int select_queue;
171 module_param(select_queue, int, 0644);
172 MODULE_PARM_DESC(select_queue,
173 		 "Select between kernel provided method of selecting or driver method of selecting TX queue. Default is kernel method.");
174 
175 static struct dentry *cxgb4_debugfs_root;
176 
177 LIST_HEAD(adapter_list);
178 DEFINE_MUTEX(uld_mutex);
179 
180 static void link_report(struct net_device *dev)
181 {
182 	if (!netif_carrier_ok(dev))
183 		netdev_info(dev, "link down\n");
184 	else {
185 		static const char *fc[] = { "no", "Rx", "Tx", "Tx/Rx" };
186 
187 		const char *s;
188 		const struct port_info *p = netdev_priv(dev);
189 
190 		switch (p->link_cfg.speed) {
191 		case 100:
192 			s = "100Mbps";
193 			break;
194 		case 1000:
195 			s = "1Gbps";
196 			break;
197 		case 10000:
198 			s = "10Gbps";
199 			break;
200 		case 25000:
201 			s = "25Gbps";
202 			break;
203 		case 40000:
204 			s = "40Gbps";
205 			break;
206 		case 100000:
207 			s = "100Gbps";
208 			break;
209 		default:
210 			pr_info("%s: unsupported speed: %d\n",
211 				dev->name, p->link_cfg.speed);
212 			return;
213 		}
214 
215 		netdev_info(dev, "link up, %s, full-duplex, %s PAUSE\n", s,
216 			    fc[p->link_cfg.fc]);
217 	}
218 }
219 
220 #ifdef CONFIG_CHELSIO_T4_DCB
221 /* Set up/tear down Data Center Bridging Priority mapping for a net device. */
222 static void dcb_tx_queue_prio_enable(struct net_device *dev, int enable)
223 {
224 	struct port_info *pi = netdev_priv(dev);
225 	struct adapter *adap = pi->adapter;
226 	struct sge_eth_txq *txq = &adap->sge.ethtxq[pi->first_qset];
227 	int i;
228 
229 	/* We use a simple mapping of Port TX Queue Index to DCB
230 	 * Priority when we're enabling DCB.
231 	 */
232 	for (i = 0; i < pi->nqsets; i++, txq++) {
233 		u32 name, value;
234 		int err;
235 
236 		name = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DMAQ) |
237 			FW_PARAMS_PARAM_X_V(
238 				FW_PARAMS_PARAM_DMAQ_EQ_DCBPRIO_ETH) |
239 			FW_PARAMS_PARAM_YZ_V(txq->q.cntxt_id));
240 		value = enable ? i : 0xffffffff;
241 
242 		/* Since we can be called while atomic (from "interrupt
243 		 * level") we need to issue the Set Parameters Commannd
244 		 * without sleeping (timeout < 0).
245 		 */
246 		err = t4_set_params_timeout(adap, adap->mbox, adap->pf, 0, 1,
247 					    &name, &value,
248 					    -FW_CMD_MAX_TIMEOUT);
249 
250 		if (err)
251 			dev_err(adap->pdev_dev,
252 				"Can't %s DCB Priority on port %d, TX Queue %d: err=%d\n",
253 				enable ? "set" : "unset", pi->port_id, i, -err);
254 		else
255 			txq->dcb_prio = value;
256 	}
257 }
258 
259 static int cxgb4_dcb_enabled(const struct net_device *dev)
260 {
261 	struct port_info *pi = netdev_priv(dev);
262 
263 	if (!pi->dcb.enabled)
264 		return 0;
265 
266 	return ((pi->dcb.state == CXGB4_DCB_STATE_FW_ALLSYNCED) ||
267 		(pi->dcb.state == CXGB4_DCB_STATE_HOST));
268 }
269 #endif /* CONFIG_CHELSIO_T4_DCB */
270 
271 void t4_os_link_changed(struct adapter *adapter, int port_id, int link_stat)
272 {
273 	struct net_device *dev = adapter->port[port_id];
274 
275 	/* Skip changes from disabled ports. */
276 	if (netif_running(dev) && link_stat != netif_carrier_ok(dev)) {
277 		if (link_stat)
278 			netif_carrier_on(dev);
279 		else {
280 #ifdef CONFIG_CHELSIO_T4_DCB
281 			if (cxgb4_dcb_enabled(dev)) {
282 				cxgb4_dcb_state_init(dev);
283 				dcb_tx_queue_prio_enable(dev, false);
284 			}
285 #endif /* CONFIG_CHELSIO_T4_DCB */
286 			netif_carrier_off(dev);
287 		}
288 
289 		link_report(dev);
290 	}
291 }
292 
293 void t4_os_portmod_changed(const struct adapter *adap, int port_id)
294 {
295 	static const char *mod_str[] = {
296 		NULL, "LR", "SR", "ER", "passive DA", "active DA", "LRM"
297 	};
298 
299 	const struct net_device *dev = adap->port[port_id];
300 	const struct port_info *pi = netdev_priv(dev);
301 
302 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
303 		netdev_info(dev, "port module unplugged\n");
304 	else if (pi->mod_type < ARRAY_SIZE(mod_str))
305 		netdev_info(dev, "%s module inserted\n", mod_str[pi->mod_type]);
306 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
307 		netdev_info(dev, "%s: unsupported port module inserted\n",
308 			    dev->name);
309 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
310 		netdev_info(dev, "%s: unknown port module inserted\n",
311 			    dev->name);
312 	else if (pi->mod_type == FW_PORT_MOD_TYPE_ERROR)
313 		netdev_info(dev, "%s: transceiver module error\n", dev->name);
314 	else
315 		netdev_info(dev, "%s: unknown module type %d inserted\n",
316 			    dev->name, pi->mod_type);
317 }
318 
319 int dbfifo_int_thresh = 10; /* 10 == 640 entry threshold */
320 module_param(dbfifo_int_thresh, int, 0644);
321 MODULE_PARM_DESC(dbfifo_int_thresh, "doorbell fifo interrupt threshold");
322 
323 /*
324  * usecs to sleep while draining the dbfifo
325  */
326 static int dbfifo_drain_delay = 1000;
327 module_param(dbfifo_drain_delay, int, 0644);
328 MODULE_PARM_DESC(dbfifo_drain_delay,
329 		 "usecs to sleep while draining the dbfifo");
330 
331 static inline int cxgb4_set_addr_hash(struct port_info *pi)
332 {
333 	struct adapter *adap = pi->adapter;
334 	u64 vec = 0;
335 	bool ucast = false;
336 	struct hash_mac_addr *entry;
337 
338 	/* Calculate the hash vector for the updated list and program it */
339 	list_for_each_entry(entry, &adap->mac_hlist, list) {
340 		ucast |= is_unicast_ether_addr(entry->addr);
341 		vec |= (1ULL << hash_mac_addr(entry->addr));
342 	}
343 	return t4_set_addr_hash(adap, adap->mbox, pi->viid, ucast,
344 				vec, false);
345 }
346 
347 static int cxgb4_mac_sync(struct net_device *netdev, const u8 *mac_addr)
348 {
349 	struct port_info *pi = netdev_priv(netdev);
350 	struct adapter *adap = pi->adapter;
351 	int ret;
352 	u64 mhash = 0;
353 	u64 uhash = 0;
354 	bool free = false;
355 	bool ucast = is_unicast_ether_addr(mac_addr);
356 	const u8 *maclist[1] = {mac_addr};
357 	struct hash_mac_addr *new_entry;
358 
359 	ret = t4_alloc_mac_filt(adap, adap->mbox, pi->viid, free, 1, maclist,
360 				NULL, ucast ? &uhash : &mhash, false);
361 	if (ret < 0)
362 		goto out;
363 	/* if hash != 0, then add the addr to hash addr list
364 	 * so on the end we will calculate the hash for the
365 	 * list and program it
366 	 */
367 	if (uhash || mhash) {
368 		new_entry = kzalloc(sizeof(*new_entry), GFP_ATOMIC);
369 		if (!new_entry)
370 			return -ENOMEM;
371 		ether_addr_copy(new_entry->addr, mac_addr);
372 		list_add_tail(&new_entry->list, &adap->mac_hlist);
373 		ret = cxgb4_set_addr_hash(pi);
374 	}
375 out:
376 	return ret < 0 ? ret : 0;
377 }
378 
379 static int cxgb4_mac_unsync(struct net_device *netdev, const u8 *mac_addr)
380 {
381 	struct port_info *pi = netdev_priv(netdev);
382 	struct adapter *adap = pi->adapter;
383 	int ret;
384 	const u8 *maclist[1] = {mac_addr};
385 	struct hash_mac_addr *entry, *tmp;
386 
387 	/* If the MAC address to be removed is in the hash addr
388 	 * list, delete it from the list and update hash vector
389 	 */
390 	list_for_each_entry_safe(entry, tmp, &adap->mac_hlist, list) {
391 		if (ether_addr_equal(entry->addr, mac_addr)) {
392 			list_del(&entry->list);
393 			kfree(entry);
394 			return cxgb4_set_addr_hash(pi);
395 		}
396 	}
397 
398 	ret = t4_free_mac_filt(adap, adap->mbox, pi->viid, 1, maclist, false);
399 	return ret < 0 ? -EINVAL : 0;
400 }
401 
402 /*
403  * Set Rx properties of a port, such as promiscruity, address filters, and MTU.
404  * If @mtu is -1 it is left unchanged.
405  */
406 static int set_rxmode(struct net_device *dev, int mtu, bool sleep_ok)
407 {
408 	struct port_info *pi = netdev_priv(dev);
409 	struct adapter *adapter = pi->adapter;
410 
411 	__dev_uc_sync(dev, cxgb4_mac_sync, cxgb4_mac_unsync);
412 	__dev_mc_sync(dev, cxgb4_mac_sync, cxgb4_mac_unsync);
413 
414 	return t4_set_rxmode(adapter, adapter->mbox, pi->viid, mtu,
415 			     (dev->flags & IFF_PROMISC) ? 1 : 0,
416 			     (dev->flags & IFF_ALLMULTI) ? 1 : 0, 1, -1,
417 			     sleep_ok);
418 }
419 
420 /**
421  *	link_start - enable a port
422  *	@dev: the port to enable
423  *
424  *	Performs the MAC and PHY actions needed to enable a port.
425  */
426 static int link_start(struct net_device *dev)
427 {
428 	int ret;
429 	struct port_info *pi = netdev_priv(dev);
430 	unsigned int mb = pi->adapter->pf;
431 
432 	/*
433 	 * We do not set address filters and promiscuity here, the stack does
434 	 * that step explicitly.
435 	 */
436 	ret = t4_set_rxmode(pi->adapter, mb, pi->viid, dev->mtu, -1, -1, -1,
437 			    !!(dev->features & NETIF_F_HW_VLAN_CTAG_RX), true);
438 	if (ret == 0) {
439 		ret = t4_change_mac(pi->adapter, mb, pi->viid,
440 				    pi->xact_addr_filt, dev->dev_addr, true,
441 				    true);
442 		if (ret >= 0) {
443 			pi->xact_addr_filt = ret;
444 			ret = 0;
445 		}
446 	}
447 	if (ret == 0)
448 		ret = t4_link_l1cfg(pi->adapter, mb, pi->tx_chan,
449 				    &pi->link_cfg);
450 	if (ret == 0) {
451 		local_bh_disable();
452 		ret = t4_enable_vi_params(pi->adapter, mb, pi->viid, true,
453 					  true, CXGB4_DCB_ENABLED);
454 		local_bh_enable();
455 	}
456 
457 	return ret;
458 }
459 
460 #ifdef CONFIG_CHELSIO_T4_DCB
461 /* Handle a Data Center Bridging update message from the firmware. */
462 static void dcb_rpl(struct adapter *adap, const struct fw_port_cmd *pcmd)
463 {
464 	int port = FW_PORT_CMD_PORTID_G(ntohl(pcmd->op_to_portid));
465 	struct net_device *dev = adap->port[adap->chan_map[port]];
466 	int old_dcb_enabled = cxgb4_dcb_enabled(dev);
467 	int new_dcb_enabled;
468 
469 	cxgb4_dcb_handle_fw_update(adap, pcmd);
470 	new_dcb_enabled = cxgb4_dcb_enabled(dev);
471 
472 	/* If the DCB has become enabled or disabled on the port then we're
473 	 * going to need to set up/tear down DCB Priority parameters for the
474 	 * TX Queues associated with the port.
475 	 */
476 	if (new_dcb_enabled != old_dcb_enabled)
477 		dcb_tx_queue_prio_enable(dev, new_dcb_enabled);
478 }
479 #endif /* CONFIG_CHELSIO_T4_DCB */
480 
481 /* Response queue handler for the FW event queue.
482  */
483 static int fwevtq_handler(struct sge_rspq *q, const __be64 *rsp,
484 			  const struct pkt_gl *gl)
485 {
486 	u8 opcode = ((const struct rss_header *)rsp)->opcode;
487 
488 	rsp++;                                          /* skip RSS header */
489 
490 	/* FW can send EGR_UPDATEs encapsulated in a CPL_FW4_MSG.
491 	 */
492 	if (unlikely(opcode == CPL_FW4_MSG &&
493 	   ((const struct cpl_fw4_msg *)rsp)->type == FW_TYPE_RSSCPL)) {
494 		rsp++;
495 		opcode = ((const struct rss_header *)rsp)->opcode;
496 		rsp++;
497 		if (opcode != CPL_SGE_EGR_UPDATE) {
498 			dev_err(q->adap->pdev_dev, "unexpected FW4/CPL %#x on FW event queue\n"
499 				, opcode);
500 			goto out;
501 		}
502 	}
503 
504 	if (likely(opcode == CPL_SGE_EGR_UPDATE)) {
505 		const struct cpl_sge_egr_update *p = (void *)rsp;
506 		unsigned int qid = EGR_QID_G(ntohl(p->opcode_qid));
507 		struct sge_txq *txq;
508 
509 		txq = q->adap->sge.egr_map[qid - q->adap->sge.egr_start];
510 		txq->restarts++;
511 		if (txq->q_type == CXGB4_TXQ_ETH) {
512 			struct sge_eth_txq *eq;
513 
514 			eq = container_of(txq, struct sge_eth_txq, q);
515 			netif_tx_wake_queue(eq->txq);
516 		} else {
517 			struct sge_uld_txq *oq;
518 
519 			oq = container_of(txq, struct sge_uld_txq, q);
520 			tasklet_schedule(&oq->qresume_tsk);
521 		}
522 	} else if (opcode == CPL_FW6_MSG || opcode == CPL_FW4_MSG) {
523 		const struct cpl_fw6_msg *p = (void *)rsp;
524 
525 #ifdef CONFIG_CHELSIO_T4_DCB
526 		const struct fw_port_cmd *pcmd = (const void *)p->data;
527 		unsigned int cmd = FW_CMD_OP_G(ntohl(pcmd->op_to_portid));
528 		unsigned int action =
529 			FW_PORT_CMD_ACTION_G(ntohl(pcmd->action_to_len16));
530 
531 		if (cmd == FW_PORT_CMD &&
532 		    action == FW_PORT_ACTION_GET_PORT_INFO) {
533 			int port = FW_PORT_CMD_PORTID_G(
534 					be32_to_cpu(pcmd->op_to_portid));
535 			struct net_device *dev =
536 				q->adap->port[q->adap->chan_map[port]];
537 			int state_input = ((pcmd->u.info.dcbxdis_pkd &
538 					    FW_PORT_CMD_DCBXDIS_F)
539 					   ? CXGB4_DCB_INPUT_FW_DISABLED
540 					   : CXGB4_DCB_INPUT_FW_ENABLED);
541 
542 			cxgb4_dcb_state_fsm(dev, state_input);
543 		}
544 
545 		if (cmd == FW_PORT_CMD &&
546 		    action == FW_PORT_ACTION_L2_DCB_CFG)
547 			dcb_rpl(q->adap, pcmd);
548 		else
549 #endif
550 			if (p->type == 0)
551 				t4_handle_fw_rpl(q->adap, p->data);
552 	} else if (opcode == CPL_L2T_WRITE_RPL) {
553 		const struct cpl_l2t_write_rpl *p = (void *)rsp;
554 
555 		do_l2t_write_rpl(q->adap, p);
556 	} else if (opcode == CPL_SET_TCB_RPL) {
557 		const struct cpl_set_tcb_rpl *p = (void *)rsp;
558 
559 		filter_rpl(q->adap, p);
560 	} else
561 		dev_err(q->adap->pdev_dev,
562 			"unexpected CPL %#x on FW event queue\n", opcode);
563 out:
564 	return 0;
565 }
566 
567 static void disable_msi(struct adapter *adapter)
568 {
569 	if (adapter->flags & USING_MSIX) {
570 		pci_disable_msix(adapter->pdev);
571 		adapter->flags &= ~USING_MSIX;
572 	} else if (adapter->flags & USING_MSI) {
573 		pci_disable_msi(adapter->pdev);
574 		adapter->flags &= ~USING_MSI;
575 	}
576 }
577 
578 /*
579  * Interrupt handler for non-data events used with MSI-X.
580  */
581 static irqreturn_t t4_nondata_intr(int irq, void *cookie)
582 {
583 	struct adapter *adap = cookie;
584 	u32 v = t4_read_reg(adap, MYPF_REG(PL_PF_INT_CAUSE_A));
585 
586 	if (v & PFSW_F) {
587 		adap->swintr = 1;
588 		t4_write_reg(adap, MYPF_REG(PL_PF_INT_CAUSE_A), v);
589 	}
590 	if (adap->flags & MASTER_PF)
591 		t4_slow_intr_handler(adap);
592 	return IRQ_HANDLED;
593 }
594 
595 /*
596  * Name the MSI-X interrupts.
597  */
598 static void name_msix_vecs(struct adapter *adap)
599 {
600 	int i, j, msi_idx = 2, n = sizeof(adap->msix_info[0].desc);
601 
602 	/* non-data interrupts */
603 	snprintf(adap->msix_info[0].desc, n, "%s", adap->port[0]->name);
604 
605 	/* FW events */
606 	snprintf(adap->msix_info[1].desc, n, "%s-FWeventq",
607 		 adap->port[0]->name);
608 
609 	/* Ethernet queues */
610 	for_each_port(adap, j) {
611 		struct net_device *d = adap->port[j];
612 		const struct port_info *pi = netdev_priv(d);
613 
614 		for (i = 0; i < pi->nqsets; i++, msi_idx++)
615 			snprintf(adap->msix_info[msi_idx].desc, n, "%s-Rx%d",
616 				 d->name, i);
617 	}
618 }
619 
620 static int request_msix_queue_irqs(struct adapter *adap)
621 {
622 	struct sge *s = &adap->sge;
623 	int err, ethqidx;
624 	int msi_index = 2;
625 
626 	err = request_irq(adap->msix_info[1].vec, t4_sge_intr_msix, 0,
627 			  adap->msix_info[1].desc, &s->fw_evtq);
628 	if (err)
629 		return err;
630 
631 	for_each_ethrxq(s, ethqidx) {
632 		err = request_irq(adap->msix_info[msi_index].vec,
633 				  t4_sge_intr_msix, 0,
634 				  adap->msix_info[msi_index].desc,
635 				  &s->ethrxq[ethqidx].rspq);
636 		if (err)
637 			goto unwind;
638 		msi_index++;
639 	}
640 	return 0;
641 
642 unwind:
643 	while (--ethqidx >= 0)
644 		free_irq(adap->msix_info[--msi_index].vec,
645 			 &s->ethrxq[ethqidx].rspq);
646 	free_irq(adap->msix_info[1].vec, &s->fw_evtq);
647 	return err;
648 }
649 
650 static void free_msix_queue_irqs(struct adapter *adap)
651 {
652 	int i, msi_index = 2;
653 	struct sge *s = &adap->sge;
654 
655 	free_irq(adap->msix_info[1].vec, &s->fw_evtq);
656 	for_each_ethrxq(s, i)
657 		free_irq(adap->msix_info[msi_index++].vec, &s->ethrxq[i].rspq);
658 }
659 
660 /**
661  *	cxgb4_write_rss - write the RSS table for a given port
662  *	@pi: the port
663  *	@queues: array of queue indices for RSS
664  *
665  *	Sets up the portion of the HW RSS table for the port's VI to distribute
666  *	packets to the Rx queues in @queues.
667  *	Should never be called before setting up sge eth rx queues
668  */
669 int cxgb4_write_rss(const struct port_info *pi, const u16 *queues)
670 {
671 	u16 *rss;
672 	int i, err;
673 	struct adapter *adapter = pi->adapter;
674 	const struct sge_eth_rxq *rxq;
675 
676 	rxq = &adapter->sge.ethrxq[pi->first_qset];
677 	rss = kmalloc(pi->rss_size * sizeof(u16), GFP_KERNEL);
678 	if (!rss)
679 		return -ENOMEM;
680 
681 	/* map the queue indices to queue ids */
682 	for (i = 0; i < pi->rss_size; i++, queues++)
683 		rss[i] = rxq[*queues].rspq.abs_id;
684 
685 	err = t4_config_rss_range(adapter, adapter->pf, pi->viid, 0,
686 				  pi->rss_size, rss, pi->rss_size);
687 	/* If Tunnel All Lookup isn't specified in the global RSS
688 	 * Configuration, then we need to specify a default Ingress
689 	 * Queue for any ingress packets which aren't hashed.  We'll
690 	 * use our first ingress queue ...
691 	 */
692 	if (!err)
693 		err = t4_config_vi_rss(adapter, adapter->mbox, pi->viid,
694 				       FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN_F |
695 				       FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN_F |
696 				       FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN_F |
697 				       FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN_F |
698 				       FW_RSS_VI_CONFIG_CMD_UDPEN_F,
699 				       rss[0]);
700 	kfree(rss);
701 	return err;
702 }
703 
704 /**
705  *	setup_rss - configure RSS
706  *	@adap: the adapter
707  *
708  *	Sets up RSS for each port.
709  */
710 static int setup_rss(struct adapter *adap)
711 {
712 	int i, j, err;
713 
714 	for_each_port(adap, i) {
715 		const struct port_info *pi = adap2pinfo(adap, i);
716 
717 		/* Fill default values with equal distribution */
718 		for (j = 0; j < pi->rss_size; j++)
719 			pi->rss[j] = j % pi->nqsets;
720 
721 		err = cxgb4_write_rss(pi, pi->rss);
722 		if (err)
723 			return err;
724 	}
725 	return 0;
726 }
727 
728 /*
729  * Return the channel of the ingress queue with the given qid.
730  */
731 static unsigned int rxq_to_chan(const struct sge *p, unsigned int qid)
732 {
733 	qid -= p->ingr_start;
734 	return netdev2pinfo(p->ingr_map[qid]->netdev)->tx_chan;
735 }
736 
737 /*
738  * Wait until all NAPI handlers are descheduled.
739  */
740 static void quiesce_rx(struct adapter *adap)
741 {
742 	int i;
743 
744 	for (i = 0; i < adap->sge.ingr_sz; i++) {
745 		struct sge_rspq *q = adap->sge.ingr_map[i];
746 
747 		if (q && q->handler)
748 			napi_disable(&q->napi);
749 	}
750 }
751 
752 /* Disable interrupt and napi handler */
753 static void disable_interrupts(struct adapter *adap)
754 {
755 	if (adap->flags & FULL_INIT_DONE) {
756 		t4_intr_disable(adap);
757 		if (adap->flags & USING_MSIX) {
758 			free_msix_queue_irqs(adap);
759 			free_irq(adap->msix_info[0].vec, adap);
760 		} else {
761 			free_irq(adap->pdev->irq, adap);
762 		}
763 		quiesce_rx(adap);
764 	}
765 }
766 
767 /*
768  * Enable NAPI scheduling and interrupt generation for all Rx queues.
769  */
770 static void enable_rx(struct adapter *adap)
771 {
772 	int i;
773 
774 	for (i = 0; i < adap->sge.ingr_sz; i++) {
775 		struct sge_rspq *q = adap->sge.ingr_map[i];
776 
777 		if (!q)
778 			continue;
779 		if (q->handler)
780 			napi_enable(&q->napi);
781 
782 		/* 0-increment GTS to start the timer and enable interrupts */
783 		t4_write_reg(adap, MYPF_REG(SGE_PF_GTS_A),
784 			     SEINTARM_V(q->intr_params) |
785 			     INGRESSQID_V(q->cntxt_id));
786 	}
787 }
788 
789 
790 static int setup_fw_sge_queues(struct adapter *adap)
791 {
792 	struct sge *s = &adap->sge;
793 	int err = 0;
794 
795 	bitmap_zero(s->starving_fl, s->egr_sz);
796 	bitmap_zero(s->txq_maperr, s->egr_sz);
797 
798 	if (adap->flags & USING_MSIX)
799 		adap->msi_idx = 1;         /* vector 0 is for non-queue interrupts */
800 	else {
801 		err = t4_sge_alloc_rxq(adap, &s->intrq, false, adap->port[0], 0,
802 				       NULL, NULL, NULL, -1);
803 		if (err)
804 			return err;
805 		adap->msi_idx = -((int)s->intrq.abs_id + 1);
806 	}
807 
808 	err = t4_sge_alloc_rxq(adap, &s->fw_evtq, true, adap->port[0],
809 			       adap->msi_idx, NULL, fwevtq_handler, NULL, -1);
810 	if (err)
811 		t4_free_sge_resources(adap);
812 	return err;
813 }
814 
815 /**
816  *	setup_sge_queues - configure SGE Tx/Rx/response queues
817  *	@adap: the adapter
818  *
819  *	Determines how many sets of SGE queues to use and initializes them.
820  *	We support multiple queue sets per port if we have MSI-X, otherwise
821  *	just one queue set per port.
822  */
823 static int setup_sge_queues(struct adapter *adap)
824 {
825 	int err, i, j;
826 	struct sge *s = &adap->sge;
827 	struct sge_uld_rxq_info *rxq_info = NULL;
828 	unsigned int cmplqid = 0;
829 
830 	if (is_uld(adap))
831 		rxq_info = s->uld_rxq_info[CXGB4_ULD_RDMA];
832 
833 	for_each_port(adap, i) {
834 		struct net_device *dev = adap->port[i];
835 		struct port_info *pi = netdev_priv(dev);
836 		struct sge_eth_rxq *q = &s->ethrxq[pi->first_qset];
837 		struct sge_eth_txq *t = &s->ethtxq[pi->first_qset];
838 
839 		for (j = 0; j < pi->nqsets; j++, q++) {
840 			if (adap->msi_idx > 0)
841 				adap->msi_idx++;
842 			err = t4_sge_alloc_rxq(adap, &q->rspq, false, dev,
843 					       adap->msi_idx, &q->fl,
844 					       t4_ethrx_handler,
845 					       NULL,
846 					       t4_get_tp_ch_map(adap,
847 								pi->tx_chan));
848 			if (err)
849 				goto freeout;
850 			q->rspq.idx = j;
851 			memset(&q->stats, 0, sizeof(q->stats));
852 		}
853 		for (j = 0; j < pi->nqsets; j++, t++) {
854 			err = t4_sge_alloc_eth_txq(adap, t, dev,
855 					netdev_get_tx_queue(dev, j),
856 					s->fw_evtq.cntxt_id);
857 			if (err)
858 				goto freeout;
859 		}
860 	}
861 
862 	for_each_port(adap, i) {
863 		/* Note that cmplqid below is 0 if we don't
864 		 * have RDMA queues, and that's the right value.
865 		 */
866 		if (rxq_info)
867 			cmplqid	= rxq_info->uldrxq[i].rspq.cntxt_id;
868 
869 		err = t4_sge_alloc_ctrl_txq(adap, &s->ctrlq[i], adap->port[i],
870 					    s->fw_evtq.cntxt_id, cmplqid);
871 		if (err)
872 			goto freeout;
873 	}
874 
875 	t4_write_reg(adap, is_t4(adap->params.chip) ?
876 				MPS_TRC_RSS_CONTROL_A :
877 				MPS_T5_TRC_RSS_CONTROL_A,
878 		     RSSCONTROL_V(netdev2pinfo(adap->port[0])->tx_chan) |
879 		     QUEUENUMBER_V(s->ethrxq[0].rspq.abs_id));
880 	return 0;
881 freeout:
882 	t4_free_sge_resources(adap);
883 	return err;
884 }
885 
886 static u16 cxgb_select_queue(struct net_device *dev, struct sk_buff *skb,
887 			     void *accel_priv, select_queue_fallback_t fallback)
888 {
889 	int txq;
890 
891 #ifdef CONFIG_CHELSIO_T4_DCB
892 	/* If a Data Center Bridging has been successfully negotiated on this
893 	 * link then we'll use the skb's priority to map it to a TX Queue.
894 	 * The skb's priority is determined via the VLAN Tag Priority Code
895 	 * Point field.
896 	 */
897 	if (cxgb4_dcb_enabled(dev) && !is_kdump_kernel()) {
898 		u16 vlan_tci;
899 		int err;
900 
901 		err = vlan_get_tag(skb, &vlan_tci);
902 		if (unlikely(err)) {
903 			if (net_ratelimit())
904 				netdev_warn(dev,
905 					    "TX Packet without VLAN Tag on DCB Link\n");
906 			txq = 0;
907 		} else {
908 			txq = (vlan_tci & VLAN_PRIO_MASK) >> VLAN_PRIO_SHIFT;
909 #ifdef CONFIG_CHELSIO_T4_FCOE
910 			if (skb->protocol == htons(ETH_P_FCOE))
911 				txq = skb->priority & 0x7;
912 #endif /* CONFIG_CHELSIO_T4_FCOE */
913 		}
914 		return txq;
915 	}
916 #endif /* CONFIG_CHELSIO_T4_DCB */
917 
918 	if (select_queue) {
919 		txq = (skb_rx_queue_recorded(skb)
920 			? skb_get_rx_queue(skb)
921 			: smp_processor_id());
922 
923 		while (unlikely(txq >= dev->real_num_tx_queues))
924 			txq -= dev->real_num_tx_queues;
925 
926 		return txq;
927 	}
928 
929 	return fallback(dev, skb) % dev->real_num_tx_queues;
930 }
931 
932 static int closest_timer(const struct sge *s, int time)
933 {
934 	int i, delta, match = 0, min_delta = INT_MAX;
935 
936 	for (i = 0; i < ARRAY_SIZE(s->timer_val); i++) {
937 		delta = time - s->timer_val[i];
938 		if (delta < 0)
939 			delta = -delta;
940 		if (delta < min_delta) {
941 			min_delta = delta;
942 			match = i;
943 		}
944 	}
945 	return match;
946 }
947 
948 static int closest_thres(const struct sge *s, int thres)
949 {
950 	int i, delta, match = 0, min_delta = INT_MAX;
951 
952 	for (i = 0; i < ARRAY_SIZE(s->counter_val); i++) {
953 		delta = thres - s->counter_val[i];
954 		if (delta < 0)
955 			delta = -delta;
956 		if (delta < min_delta) {
957 			min_delta = delta;
958 			match = i;
959 		}
960 	}
961 	return match;
962 }
963 
964 /**
965  *	cxgb4_set_rspq_intr_params - set a queue's interrupt holdoff parameters
966  *	@q: the Rx queue
967  *	@us: the hold-off time in us, or 0 to disable timer
968  *	@cnt: the hold-off packet count, or 0 to disable counter
969  *
970  *	Sets an Rx queue's interrupt hold-off time and packet count.  At least
971  *	one of the two needs to be enabled for the queue to generate interrupts.
972  */
973 int cxgb4_set_rspq_intr_params(struct sge_rspq *q,
974 			       unsigned int us, unsigned int cnt)
975 {
976 	struct adapter *adap = q->adap;
977 
978 	if ((us | cnt) == 0)
979 		cnt = 1;
980 
981 	if (cnt) {
982 		int err;
983 		u32 v, new_idx;
984 
985 		new_idx = closest_thres(&adap->sge, cnt);
986 		if (q->desc && q->pktcnt_idx != new_idx) {
987 			/* the queue has already been created, update it */
988 			v = FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DMAQ) |
989 			    FW_PARAMS_PARAM_X_V(
990 					FW_PARAMS_PARAM_DMAQ_IQ_INTCNTTHRESH) |
991 			    FW_PARAMS_PARAM_YZ_V(q->cntxt_id);
992 			err = t4_set_params(adap, adap->mbox, adap->pf, 0, 1,
993 					    &v, &new_idx);
994 			if (err)
995 				return err;
996 		}
997 		q->pktcnt_idx = new_idx;
998 	}
999 
1000 	us = us == 0 ? 6 : closest_timer(&adap->sge, us);
1001 	q->intr_params = QINTR_TIMER_IDX_V(us) | QINTR_CNT_EN_V(cnt > 0);
1002 	return 0;
1003 }
1004 
1005 static int cxgb_set_features(struct net_device *dev, netdev_features_t features)
1006 {
1007 	const struct port_info *pi = netdev_priv(dev);
1008 	netdev_features_t changed = dev->features ^ features;
1009 	int err;
1010 
1011 	if (!(changed & NETIF_F_HW_VLAN_CTAG_RX))
1012 		return 0;
1013 
1014 	err = t4_set_rxmode(pi->adapter, pi->adapter->pf, pi->viid, -1,
1015 			    -1, -1, -1,
1016 			    !!(features & NETIF_F_HW_VLAN_CTAG_RX), true);
1017 	if (unlikely(err))
1018 		dev->features = features ^ NETIF_F_HW_VLAN_CTAG_RX;
1019 	return err;
1020 }
1021 
1022 static int setup_debugfs(struct adapter *adap)
1023 {
1024 	if (IS_ERR_OR_NULL(adap->debugfs_root))
1025 		return -1;
1026 
1027 #ifdef CONFIG_DEBUG_FS
1028 	t4_setup_debugfs(adap);
1029 #endif
1030 	return 0;
1031 }
1032 
1033 /*
1034  * upper-layer driver support
1035  */
1036 
1037 /*
1038  * Allocate an active-open TID and set it to the supplied value.
1039  */
1040 int cxgb4_alloc_atid(struct tid_info *t, void *data)
1041 {
1042 	int atid = -1;
1043 
1044 	spin_lock_bh(&t->atid_lock);
1045 	if (t->afree) {
1046 		union aopen_entry *p = t->afree;
1047 
1048 		atid = (p - t->atid_tab) + t->atid_base;
1049 		t->afree = p->next;
1050 		p->data = data;
1051 		t->atids_in_use++;
1052 	}
1053 	spin_unlock_bh(&t->atid_lock);
1054 	return atid;
1055 }
1056 EXPORT_SYMBOL(cxgb4_alloc_atid);
1057 
1058 /*
1059  * Release an active-open TID.
1060  */
1061 void cxgb4_free_atid(struct tid_info *t, unsigned int atid)
1062 {
1063 	union aopen_entry *p = &t->atid_tab[atid - t->atid_base];
1064 
1065 	spin_lock_bh(&t->atid_lock);
1066 	p->next = t->afree;
1067 	t->afree = p;
1068 	t->atids_in_use--;
1069 	spin_unlock_bh(&t->atid_lock);
1070 }
1071 EXPORT_SYMBOL(cxgb4_free_atid);
1072 
1073 /*
1074  * Allocate a server TID and set it to the supplied value.
1075  */
1076 int cxgb4_alloc_stid(struct tid_info *t, int family, void *data)
1077 {
1078 	int stid;
1079 
1080 	spin_lock_bh(&t->stid_lock);
1081 	if (family == PF_INET) {
1082 		stid = find_first_zero_bit(t->stid_bmap, t->nstids);
1083 		if (stid < t->nstids)
1084 			__set_bit(stid, t->stid_bmap);
1085 		else
1086 			stid = -1;
1087 	} else {
1088 		stid = bitmap_find_free_region(t->stid_bmap, t->nstids, 1);
1089 		if (stid < 0)
1090 			stid = -1;
1091 	}
1092 	if (stid >= 0) {
1093 		t->stid_tab[stid].data = data;
1094 		stid += t->stid_base;
1095 		/* IPv6 requires max of 520 bits or 16 cells in TCAM
1096 		 * This is equivalent to 4 TIDs. With CLIP enabled it
1097 		 * needs 2 TIDs.
1098 		 */
1099 		if (family == PF_INET6) {
1100 			t->stids_in_use += 2;
1101 			t->v6_stids_in_use += 2;
1102 		} else {
1103 			t->stids_in_use++;
1104 		}
1105 	}
1106 	spin_unlock_bh(&t->stid_lock);
1107 	return stid;
1108 }
1109 EXPORT_SYMBOL(cxgb4_alloc_stid);
1110 
1111 /* Allocate a server filter TID and set it to the supplied value.
1112  */
1113 int cxgb4_alloc_sftid(struct tid_info *t, int family, void *data)
1114 {
1115 	int stid;
1116 
1117 	spin_lock_bh(&t->stid_lock);
1118 	if (family == PF_INET) {
1119 		stid = find_next_zero_bit(t->stid_bmap,
1120 				t->nstids + t->nsftids, t->nstids);
1121 		if (stid < (t->nstids + t->nsftids))
1122 			__set_bit(stid, t->stid_bmap);
1123 		else
1124 			stid = -1;
1125 	} else {
1126 		stid = -1;
1127 	}
1128 	if (stid >= 0) {
1129 		t->stid_tab[stid].data = data;
1130 		stid -= t->nstids;
1131 		stid += t->sftid_base;
1132 		t->sftids_in_use++;
1133 	}
1134 	spin_unlock_bh(&t->stid_lock);
1135 	return stid;
1136 }
1137 EXPORT_SYMBOL(cxgb4_alloc_sftid);
1138 
1139 /* Release a server TID.
1140  */
1141 void cxgb4_free_stid(struct tid_info *t, unsigned int stid, int family)
1142 {
1143 	/* Is it a server filter TID? */
1144 	if (t->nsftids && (stid >= t->sftid_base)) {
1145 		stid -= t->sftid_base;
1146 		stid += t->nstids;
1147 	} else {
1148 		stid -= t->stid_base;
1149 	}
1150 
1151 	spin_lock_bh(&t->stid_lock);
1152 	if (family == PF_INET)
1153 		__clear_bit(stid, t->stid_bmap);
1154 	else
1155 		bitmap_release_region(t->stid_bmap, stid, 1);
1156 	t->stid_tab[stid].data = NULL;
1157 	if (stid < t->nstids) {
1158 		if (family == PF_INET6) {
1159 			t->stids_in_use -= 2;
1160 			t->v6_stids_in_use -= 2;
1161 		} else {
1162 			t->stids_in_use--;
1163 		}
1164 	} else {
1165 		t->sftids_in_use--;
1166 	}
1167 
1168 	spin_unlock_bh(&t->stid_lock);
1169 }
1170 EXPORT_SYMBOL(cxgb4_free_stid);
1171 
1172 /*
1173  * Populate a TID_RELEASE WR.  Caller must properly size the skb.
1174  */
1175 static void mk_tid_release(struct sk_buff *skb, unsigned int chan,
1176 			   unsigned int tid)
1177 {
1178 	struct cpl_tid_release *req;
1179 
1180 	set_wr_txq(skb, CPL_PRIORITY_SETUP, chan);
1181 	req = __skb_put(skb, sizeof(*req));
1182 	INIT_TP_WR(req, tid);
1183 	OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_TID_RELEASE, tid));
1184 }
1185 
1186 /*
1187  * Queue a TID release request and if necessary schedule a work queue to
1188  * process it.
1189  */
1190 static void cxgb4_queue_tid_release(struct tid_info *t, unsigned int chan,
1191 				    unsigned int tid)
1192 {
1193 	void **p = &t->tid_tab[tid];
1194 	struct adapter *adap = container_of(t, struct adapter, tids);
1195 
1196 	spin_lock_bh(&adap->tid_release_lock);
1197 	*p = adap->tid_release_head;
1198 	/* Low 2 bits encode the Tx channel number */
1199 	adap->tid_release_head = (void **)((uintptr_t)p | chan);
1200 	if (!adap->tid_release_task_busy) {
1201 		adap->tid_release_task_busy = true;
1202 		queue_work(adap->workq, &adap->tid_release_task);
1203 	}
1204 	spin_unlock_bh(&adap->tid_release_lock);
1205 }
1206 
1207 /*
1208  * Process the list of pending TID release requests.
1209  */
1210 static void process_tid_release_list(struct work_struct *work)
1211 {
1212 	struct sk_buff *skb;
1213 	struct adapter *adap;
1214 
1215 	adap = container_of(work, struct adapter, tid_release_task);
1216 
1217 	spin_lock_bh(&adap->tid_release_lock);
1218 	while (adap->tid_release_head) {
1219 		void **p = adap->tid_release_head;
1220 		unsigned int chan = (uintptr_t)p & 3;
1221 		p = (void *)p - chan;
1222 
1223 		adap->tid_release_head = *p;
1224 		*p = NULL;
1225 		spin_unlock_bh(&adap->tid_release_lock);
1226 
1227 		while (!(skb = alloc_skb(sizeof(struct cpl_tid_release),
1228 					 GFP_KERNEL)))
1229 			schedule_timeout_uninterruptible(1);
1230 
1231 		mk_tid_release(skb, chan, p - adap->tids.tid_tab);
1232 		t4_ofld_send(adap, skb);
1233 		spin_lock_bh(&adap->tid_release_lock);
1234 	}
1235 	adap->tid_release_task_busy = false;
1236 	spin_unlock_bh(&adap->tid_release_lock);
1237 }
1238 
1239 /*
1240  * Release a TID and inform HW.  If we are unable to allocate the release
1241  * message we defer to a work queue.
1242  */
1243 void cxgb4_remove_tid(struct tid_info *t, unsigned int chan, unsigned int tid,
1244 		      unsigned short family)
1245 {
1246 	struct sk_buff *skb;
1247 	struct adapter *adap = container_of(t, struct adapter, tids);
1248 
1249 	WARN_ON(tid >= t->ntids);
1250 
1251 	if (t->tid_tab[tid]) {
1252 		t->tid_tab[tid] = NULL;
1253 		atomic_dec(&t->conns_in_use);
1254 		if (t->hash_base && (tid >= t->hash_base)) {
1255 			if (family == AF_INET6)
1256 				atomic_sub(2, &t->hash_tids_in_use);
1257 			else
1258 				atomic_dec(&t->hash_tids_in_use);
1259 		} else {
1260 			if (family == AF_INET6)
1261 				atomic_sub(2, &t->tids_in_use);
1262 			else
1263 				atomic_dec(&t->tids_in_use);
1264 		}
1265 	}
1266 
1267 	skb = alloc_skb(sizeof(struct cpl_tid_release), GFP_ATOMIC);
1268 	if (likely(skb)) {
1269 		mk_tid_release(skb, chan, tid);
1270 		t4_ofld_send(adap, skb);
1271 	} else
1272 		cxgb4_queue_tid_release(t, chan, tid);
1273 }
1274 EXPORT_SYMBOL(cxgb4_remove_tid);
1275 
1276 /*
1277  * Allocate and initialize the TID tables.  Returns 0 on success.
1278  */
1279 static int tid_init(struct tid_info *t)
1280 {
1281 	struct adapter *adap = container_of(t, struct adapter, tids);
1282 	unsigned int max_ftids = t->nftids + t->nsftids;
1283 	unsigned int natids = t->natids;
1284 	unsigned int stid_bmap_size;
1285 	unsigned int ftid_bmap_size;
1286 	size_t size;
1287 
1288 	stid_bmap_size = BITS_TO_LONGS(t->nstids + t->nsftids);
1289 	ftid_bmap_size = BITS_TO_LONGS(t->nftids);
1290 	size = t->ntids * sizeof(*t->tid_tab) +
1291 	       natids * sizeof(*t->atid_tab) +
1292 	       t->nstids * sizeof(*t->stid_tab) +
1293 	       t->nsftids * sizeof(*t->stid_tab) +
1294 	       stid_bmap_size * sizeof(long) +
1295 	       max_ftids * sizeof(*t->ftid_tab) +
1296 	       ftid_bmap_size * sizeof(long);
1297 
1298 	t->tid_tab = kvzalloc(size, GFP_KERNEL);
1299 	if (!t->tid_tab)
1300 		return -ENOMEM;
1301 
1302 	t->atid_tab = (union aopen_entry *)&t->tid_tab[t->ntids];
1303 	t->stid_tab = (struct serv_entry *)&t->atid_tab[natids];
1304 	t->stid_bmap = (unsigned long *)&t->stid_tab[t->nstids + t->nsftids];
1305 	t->ftid_tab = (struct filter_entry *)&t->stid_bmap[stid_bmap_size];
1306 	t->ftid_bmap = (unsigned long *)&t->ftid_tab[max_ftids];
1307 	spin_lock_init(&t->stid_lock);
1308 	spin_lock_init(&t->atid_lock);
1309 	spin_lock_init(&t->ftid_lock);
1310 
1311 	t->stids_in_use = 0;
1312 	t->v6_stids_in_use = 0;
1313 	t->sftids_in_use = 0;
1314 	t->afree = NULL;
1315 	t->atids_in_use = 0;
1316 	atomic_set(&t->tids_in_use, 0);
1317 	atomic_set(&t->conns_in_use, 0);
1318 	atomic_set(&t->hash_tids_in_use, 0);
1319 
1320 	/* Setup the free list for atid_tab and clear the stid bitmap. */
1321 	if (natids) {
1322 		while (--natids)
1323 			t->atid_tab[natids - 1].next = &t->atid_tab[natids];
1324 		t->afree = t->atid_tab;
1325 	}
1326 
1327 	if (is_offload(adap)) {
1328 		bitmap_zero(t->stid_bmap, t->nstids + t->nsftids);
1329 		/* Reserve stid 0 for T4/T5 adapters */
1330 		if (!t->stid_base &&
1331 		    CHELSIO_CHIP_VERSION(adap->params.chip) <= CHELSIO_T5)
1332 			__set_bit(0, t->stid_bmap);
1333 	}
1334 
1335 	bitmap_zero(t->ftid_bmap, t->nftids);
1336 	return 0;
1337 }
1338 
1339 /**
1340  *	cxgb4_create_server - create an IP server
1341  *	@dev: the device
1342  *	@stid: the server TID
1343  *	@sip: local IP address to bind server to
1344  *	@sport: the server's TCP port
1345  *	@queue: queue to direct messages from this server to
1346  *
1347  *	Create an IP server for the given port and address.
1348  *	Returns <0 on error and one of the %NET_XMIT_* values on success.
1349  */
1350 int cxgb4_create_server(const struct net_device *dev, unsigned int stid,
1351 			__be32 sip, __be16 sport, __be16 vlan,
1352 			unsigned int queue)
1353 {
1354 	unsigned int chan;
1355 	struct sk_buff *skb;
1356 	struct adapter *adap;
1357 	struct cpl_pass_open_req *req;
1358 	int ret;
1359 
1360 	skb = alloc_skb(sizeof(*req), GFP_KERNEL);
1361 	if (!skb)
1362 		return -ENOMEM;
1363 
1364 	adap = netdev2adap(dev);
1365 	req = __skb_put(skb, sizeof(*req));
1366 	INIT_TP_WR(req, 0);
1367 	OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_PASS_OPEN_REQ, stid));
1368 	req->local_port = sport;
1369 	req->peer_port = htons(0);
1370 	req->local_ip = sip;
1371 	req->peer_ip = htonl(0);
1372 	chan = rxq_to_chan(&adap->sge, queue);
1373 	req->opt0 = cpu_to_be64(TX_CHAN_V(chan));
1374 	req->opt1 = cpu_to_be64(CONN_POLICY_V(CPL_CONN_POLICY_ASK) |
1375 				SYN_RSS_ENABLE_F | SYN_RSS_QUEUE_V(queue));
1376 	ret = t4_mgmt_tx(adap, skb);
1377 	return net_xmit_eval(ret);
1378 }
1379 EXPORT_SYMBOL(cxgb4_create_server);
1380 
1381 /*	cxgb4_create_server6 - create an IPv6 server
1382  *	@dev: the device
1383  *	@stid: the server TID
1384  *	@sip: local IPv6 address to bind server to
1385  *	@sport: the server's TCP port
1386  *	@queue: queue to direct messages from this server to
1387  *
1388  *	Create an IPv6 server for the given port and address.
1389  *	Returns <0 on error and one of the %NET_XMIT_* values on success.
1390  */
1391 int cxgb4_create_server6(const struct net_device *dev, unsigned int stid,
1392 			 const struct in6_addr *sip, __be16 sport,
1393 			 unsigned int queue)
1394 {
1395 	unsigned int chan;
1396 	struct sk_buff *skb;
1397 	struct adapter *adap;
1398 	struct cpl_pass_open_req6 *req;
1399 	int ret;
1400 
1401 	skb = alloc_skb(sizeof(*req), GFP_KERNEL);
1402 	if (!skb)
1403 		return -ENOMEM;
1404 
1405 	adap = netdev2adap(dev);
1406 	req = __skb_put(skb, sizeof(*req));
1407 	INIT_TP_WR(req, 0);
1408 	OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_PASS_OPEN_REQ6, stid));
1409 	req->local_port = sport;
1410 	req->peer_port = htons(0);
1411 	req->local_ip_hi = *(__be64 *)(sip->s6_addr);
1412 	req->local_ip_lo = *(__be64 *)(sip->s6_addr + 8);
1413 	req->peer_ip_hi = cpu_to_be64(0);
1414 	req->peer_ip_lo = cpu_to_be64(0);
1415 	chan = rxq_to_chan(&adap->sge, queue);
1416 	req->opt0 = cpu_to_be64(TX_CHAN_V(chan));
1417 	req->opt1 = cpu_to_be64(CONN_POLICY_V(CPL_CONN_POLICY_ASK) |
1418 				SYN_RSS_ENABLE_F | SYN_RSS_QUEUE_V(queue));
1419 	ret = t4_mgmt_tx(adap, skb);
1420 	return net_xmit_eval(ret);
1421 }
1422 EXPORT_SYMBOL(cxgb4_create_server6);
1423 
1424 int cxgb4_remove_server(const struct net_device *dev, unsigned int stid,
1425 			unsigned int queue, bool ipv6)
1426 {
1427 	struct sk_buff *skb;
1428 	struct adapter *adap;
1429 	struct cpl_close_listsvr_req *req;
1430 	int ret;
1431 
1432 	adap = netdev2adap(dev);
1433 
1434 	skb = alloc_skb(sizeof(*req), GFP_KERNEL);
1435 	if (!skb)
1436 		return -ENOMEM;
1437 
1438 	req = __skb_put(skb, sizeof(*req));
1439 	INIT_TP_WR(req, 0);
1440 	OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_CLOSE_LISTSRV_REQ, stid));
1441 	req->reply_ctrl = htons(NO_REPLY_V(0) | (ipv6 ? LISTSVR_IPV6_V(1) :
1442 				LISTSVR_IPV6_V(0)) | QUEUENO_V(queue));
1443 	ret = t4_mgmt_tx(adap, skb);
1444 	return net_xmit_eval(ret);
1445 }
1446 EXPORT_SYMBOL(cxgb4_remove_server);
1447 
1448 /**
1449  *	cxgb4_best_mtu - find the entry in the MTU table closest to an MTU
1450  *	@mtus: the HW MTU table
1451  *	@mtu: the target MTU
1452  *	@idx: index of selected entry in the MTU table
1453  *
1454  *	Returns the index and the value in the HW MTU table that is closest to
1455  *	but does not exceed @mtu, unless @mtu is smaller than any value in the
1456  *	table, in which case that smallest available value is selected.
1457  */
1458 unsigned int cxgb4_best_mtu(const unsigned short *mtus, unsigned short mtu,
1459 			    unsigned int *idx)
1460 {
1461 	unsigned int i = 0;
1462 
1463 	while (i < NMTUS - 1 && mtus[i + 1] <= mtu)
1464 		++i;
1465 	if (idx)
1466 		*idx = i;
1467 	return mtus[i];
1468 }
1469 EXPORT_SYMBOL(cxgb4_best_mtu);
1470 
1471 /**
1472  *     cxgb4_best_aligned_mtu - find best MTU, [hopefully] data size aligned
1473  *     @mtus: the HW MTU table
1474  *     @header_size: Header Size
1475  *     @data_size_max: maximum Data Segment Size
1476  *     @data_size_align: desired Data Segment Size Alignment (2^N)
1477  *     @mtu_idxp: HW MTU Table Index return value pointer (possibly NULL)
1478  *
1479  *     Similar to cxgb4_best_mtu() but instead of searching the Hardware
1480  *     MTU Table based solely on a Maximum MTU parameter, we break that
1481  *     parameter up into a Header Size and Maximum Data Segment Size, and
1482  *     provide a desired Data Segment Size Alignment.  If we find an MTU in
1483  *     the Hardware MTU Table which will result in a Data Segment Size with
1484  *     the requested alignment _and_ that MTU isn't "too far" from the
1485  *     closest MTU, then we'll return that rather than the closest MTU.
1486  */
1487 unsigned int cxgb4_best_aligned_mtu(const unsigned short *mtus,
1488 				    unsigned short header_size,
1489 				    unsigned short data_size_max,
1490 				    unsigned short data_size_align,
1491 				    unsigned int *mtu_idxp)
1492 {
1493 	unsigned short max_mtu = header_size + data_size_max;
1494 	unsigned short data_size_align_mask = data_size_align - 1;
1495 	int mtu_idx, aligned_mtu_idx;
1496 
1497 	/* Scan the MTU Table till we find an MTU which is larger than our
1498 	 * Maximum MTU or we reach the end of the table.  Along the way,
1499 	 * record the last MTU found, if any, which will result in a Data
1500 	 * Segment Length matching the requested alignment.
1501 	 */
1502 	for (mtu_idx = 0, aligned_mtu_idx = -1; mtu_idx < NMTUS; mtu_idx++) {
1503 		unsigned short data_size = mtus[mtu_idx] - header_size;
1504 
1505 		/* If this MTU minus the Header Size would result in a
1506 		 * Data Segment Size of the desired alignment, remember it.
1507 		 */
1508 		if ((data_size & data_size_align_mask) == 0)
1509 			aligned_mtu_idx = mtu_idx;
1510 
1511 		/* If we're not at the end of the Hardware MTU Table and the
1512 		 * next element is larger than our Maximum MTU, drop out of
1513 		 * the loop.
1514 		 */
1515 		if (mtu_idx+1 < NMTUS && mtus[mtu_idx+1] > max_mtu)
1516 			break;
1517 	}
1518 
1519 	/* If we fell out of the loop because we ran to the end of the table,
1520 	 * then we just have to use the last [largest] entry.
1521 	 */
1522 	if (mtu_idx == NMTUS)
1523 		mtu_idx--;
1524 
1525 	/* If we found an MTU which resulted in the requested Data Segment
1526 	 * Length alignment and that's "not far" from the largest MTU which is
1527 	 * less than or equal to the maximum MTU, then use that.
1528 	 */
1529 	if (aligned_mtu_idx >= 0 &&
1530 	    mtu_idx - aligned_mtu_idx <= 1)
1531 		mtu_idx = aligned_mtu_idx;
1532 
1533 	/* If the caller has passed in an MTU Index pointer, pass the
1534 	 * MTU Index back.  Return the MTU value.
1535 	 */
1536 	if (mtu_idxp)
1537 		*mtu_idxp = mtu_idx;
1538 	return mtus[mtu_idx];
1539 }
1540 EXPORT_SYMBOL(cxgb4_best_aligned_mtu);
1541 
1542 /**
1543  *	cxgb4_tp_smt_idx - Get the Source Mac Table index for this VI
1544  *	@chip: chip type
1545  *	@viid: VI id of the given port
1546  *
1547  *	Return the SMT index for this VI.
1548  */
1549 unsigned int cxgb4_tp_smt_idx(enum chip_type chip, unsigned int viid)
1550 {
1551 	/* In T4/T5, SMT contains 256 SMAC entries organized in
1552 	 * 128 rows of 2 entries each.
1553 	 * In T6, SMT contains 256 SMAC entries in 256 rows.
1554 	 * TODO: The below code needs to be updated when we add support
1555 	 * for 256 VFs.
1556 	 */
1557 	if (CHELSIO_CHIP_VERSION(chip) <= CHELSIO_T5)
1558 		return ((viid & 0x7f) << 1);
1559 	else
1560 		return (viid & 0x7f);
1561 }
1562 EXPORT_SYMBOL(cxgb4_tp_smt_idx);
1563 
1564 /**
1565  *	cxgb4_port_chan - get the HW channel of a port
1566  *	@dev: the net device for the port
1567  *
1568  *	Return the HW Tx channel of the given port.
1569  */
1570 unsigned int cxgb4_port_chan(const struct net_device *dev)
1571 {
1572 	return netdev2pinfo(dev)->tx_chan;
1573 }
1574 EXPORT_SYMBOL(cxgb4_port_chan);
1575 
1576 unsigned int cxgb4_dbfifo_count(const struct net_device *dev, int lpfifo)
1577 {
1578 	struct adapter *adap = netdev2adap(dev);
1579 	u32 v1, v2, lp_count, hp_count;
1580 
1581 	v1 = t4_read_reg(adap, SGE_DBFIFO_STATUS_A);
1582 	v2 = t4_read_reg(adap, SGE_DBFIFO_STATUS2_A);
1583 	if (is_t4(adap->params.chip)) {
1584 		lp_count = LP_COUNT_G(v1);
1585 		hp_count = HP_COUNT_G(v1);
1586 	} else {
1587 		lp_count = LP_COUNT_T5_G(v1);
1588 		hp_count = HP_COUNT_T5_G(v2);
1589 	}
1590 	return lpfifo ? lp_count : hp_count;
1591 }
1592 EXPORT_SYMBOL(cxgb4_dbfifo_count);
1593 
1594 /**
1595  *	cxgb4_port_viid - get the VI id of a port
1596  *	@dev: the net device for the port
1597  *
1598  *	Return the VI id of the given port.
1599  */
1600 unsigned int cxgb4_port_viid(const struct net_device *dev)
1601 {
1602 	return netdev2pinfo(dev)->viid;
1603 }
1604 EXPORT_SYMBOL(cxgb4_port_viid);
1605 
1606 /**
1607  *	cxgb4_port_idx - get the index of a port
1608  *	@dev: the net device for the port
1609  *
1610  *	Return the index of the given port.
1611  */
1612 unsigned int cxgb4_port_idx(const struct net_device *dev)
1613 {
1614 	return netdev2pinfo(dev)->port_id;
1615 }
1616 EXPORT_SYMBOL(cxgb4_port_idx);
1617 
1618 void cxgb4_get_tcp_stats(struct pci_dev *pdev, struct tp_tcp_stats *v4,
1619 			 struct tp_tcp_stats *v6)
1620 {
1621 	struct adapter *adap = pci_get_drvdata(pdev);
1622 
1623 	spin_lock(&adap->stats_lock);
1624 	t4_tp_get_tcp_stats(adap, v4, v6);
1625 	spin_unlock(&adap->stats_lock);
1626 }
1627 EXPORT_SYMBOL(cxgb4_get_tcp_stats);
1628 
1629 void cxgb4_iscsi_init(struct net_device *dev, unsigned int tag_mask,
1630 		      const unsigned int *pgsz_order)
1631 {
1632 	struct adapter *adap = netdev2adap(dev);
1633 
1634 	t4_write_reg(adap, ULP_RX_ISCSI_TAGMASK_A, tag_mask);
1635 	t4_write_reg(adap, ULP_RX_ISCSI_PSZ_A, HPZ0_V(pgsz_order[0]) |
1636 		     HPZ1_V(pgsz_order[1]) | HPZ2_V(pgsz_order[2]) |
1637 		     HPZ3_V(pgsz_order[3]));
1638 }
1639 EXPORT_SYMBOL(cxgb4_iscsi_init);
1640 
1641 int cxgb4_flush_eq_cache(struct net_device *dev)
1642 {
1643 	struct adapter *adap = netdev2adap(dev);
1644 
1645 	return t4_sge_ctxt_flush(adap, adap->mbox);
1646 }
1647 EXPORT_SYMBOL(cxgb4_flush_eq_cache);
1648 
1649 static int read_eq_indices(struct adapter *adap, u16 qid, u16 *pidx, u16 *cidx)
1650 {
1651 	u32 addr = t4_read_reg(adap, SGE_DBQ_CTXT_BADDR_A) + 24 * qid + 8;
1652 	__be64 indices;
1653 	int ret;
1654 
1655 	spin_lock(&adap->win0_lock);
1656 	ret = t4_memory_rw(adap, 0, MEM_EDC0, addr,
1657 			   sizeof(indices), (__be32 *)&indices,
1658 			   T4_MEMORY_READ);
1659 	spin_unlock(&adap->win0_lock);
1660 	if (!ret) {
1661 		*cidx = (be64_to_cpu(indices) >> 25) & 0xffff;
1662 		*pidx = (be64_to_cpu(indices) >> 9) & 0xffff;
1663 	}
1664 	return ret;
1665 }
1666 
1667 int cxgb4_sync_txq_pidx(struct net_device *dev, u16 qid, u16 pidx,
1668 			u16 size)
1669 {
1670 	struct adapter *adap = netdev2adap(dev);
1671 	u16 hw_pidx, hw_cidx;
1672 	int ret;
1673 
1674 	ret = read_eq_indices(adap, qid, &hw_pidx, &hw_cidx);
1675 	if (ret)
1676 		goto out;
1677 
1678 	if (pidx != hw_pidx) {
1679 		u16 delta;
1680 		u32 val;
1681 
1682 		if (pidx >= hw_pidx)
1683 			delta = pidx - hw_pidx;
1684 		else
1685 			delta = size - hw_pidx + pidx;
1686 
1687 		if (is_t4(adap->params.chip))
1688 			val = PIDX_V(delta);
1689 		else
1690 			val = PIDX_T5_V(delta);
1691 		wmb();
1692 		t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL_A),
1693 			     QID_V(qid) | val);
1694 	}
1695 out:
1696 	return ret;
1697 }
1698 EXPORT_SYMBOL(cxgb4_sync_txq_pidx);
1699 
1700 int cxgb4_read_tpte(struct net_device *dev, u32 stag, __be32 *tpte)
1701 {
1702 	struct adapter *adap;
1703 	u32 offset, memtype, memaddr;
1704 	u32 edc0_size, edc1_size, mc0_size, mc1_size, size;
1705 	u32 edc0_end, edc1_end, mc0_end, mc1_end;
1706 	int ret;
1707 
1708 	adap = netdev2adap(dev);
1709 
1710 	offset = ((stag >> 8) * 32) + adap->vres.stag.start;
1711 
1712 	/* Figure out where the offset lands in the Memory Type/Address scheme.
1713 	 * This code assumes that the memory is laid out starting at offset 0
1714 	 * with no breaks as: EDC0, EDC1, MC0, MC1. All cards have both EDC0
1715 	 * and EDC1.  Some cards will have neither MC0 nor MC1, most cards have
1716 	 * MC0, and some have both MC0 and MC1.
1717 	 */
1718 	size = t4_read_reg(adap, MA_EDRAM0_BAR_A);
1719 	edc0_size = EDRAM0_SIZE_G(size) << 20;
1720 	size = t4_read_reg(adap, MA_EDRAM1_BAR_A);
1721 	edc1_size = EDRAM1_SIZE_G(size) << 20;
1722 	size = t4_read_reg(adap, MA_EXT_MEMORY0_BAR_A);
1723 	mc0_size = EXT_MEM0_SIZE_G(size) << 20;
1724 
1725 	edc0_end = edc0_size;
1726 	edc1_end = edc0_end + edc1_size;
1727 	mc0_end = edc1_end + mc0_size;
1728 
1729 	if (offset < edc0_end) {
1730 		memtype = MEM_EDC0;
1731 		memaddr = offset;
1732 	} else if (offset < edc1_end) {
1733 		memtype = MEM_EDC1;
1734 		memaddr = offset - edc0_end;
1735 	} else {
1736 		if (offset < mc0_end) {
1737 			memtype = MEM_MC0;
1738 			memaddr = offset - edc1_end;
1739 		} else if (is_t5(adap->params.chip)) {
1740 			size = t4_read_reg(adap, MA_EXT_MEMORY1_BAR_A);
1741 			mc1_size = EXT_MEM1_SIZE_G(size) << 20;
1742 			mc1_end = mc0_end + mc1_size;
1743 			if (offset < mc1_end) {
1744 				memtype = MEM_MC1;
1745 				memaddr = offset - mc0_end;
1746 			} else {
1747 				/* offset beyond the end of any memory */
1748 				goto err;
1749 			}
1750 		} else {
1751 			/* T4/T6 only has a single memory channel */
1752 			goto err;
1753 		}
1754 	}
1755 
1756 	spin_lock(&adap->win0_lock);
1757 	ret = t4_memory_rw(adap, 0, memtype, memaddr, 32, tpte, T4_MEMORY_READ);
1758 	spin_unlock(&adap->win0_lock);
1759 	return ret;
1760 
1761 err:
1762 	dev_err(adap->pdev_dev, "stag %#x, offset %#x out of range\n",
1763 		stag, offset);
1764 	return -EINVAL;
1765 }
1766 EXPORT_SYMBOL(cxgb4_read_tpte);
1767 
1768 u64 cxgb4_read_sge_timestamp(struct net_device *dev)
1769 {
1770 	u32 hi, lo;
1771 	struct adapter *adap;
1772 
1773 	adap = netdev2adap(dev);
1774 	lo = t4_read_reg(adap, SGE_TIMESTAMP_LO_A);
1775 	hi = TSVAL_G(t4_read_reg(adap, SGE_TIMESTAMP_HI_A));
1776 
1777 	return ((u64)hi << 32) | (u64)lo;
1778 }
1779 EXPORT_SYMBOL(cxgb4_read_sge_timestamp);
1780 
1781 int cxgb4_bar2_sge_qregs(struct net_device *dev,
1782 			 unsigned int qid,
1783 			 enum cxgb4_bar2_qtype qtype,
1784 			 int user,
1785 			 u64 *pbar2_qoffset,
1786 			 unsigned int *pbar2_qid)
1787 {
1788 	return t4_bar2_sge_qregs(netdev2adap(dev),
1789 				 qid,
1790 				 (qtype == CXGB4_BAR2_QTYPE_EGRESS
1791 				  ? T4_BAR2_QTYPE_EGRESS
1792 				  : T4_BAR2_QTYPE_INGRESS),
1793 				 user,
1794 				 pbar2_qoffset,
1795 				 pbar2_qid);
1796 }
1797 EXPORT_SYMBOL(cxgb4_bar2_sge_qregs);
1798 
1799 static struct pci_driver cxgb4_driver;
1800 
1801 static void check_neigh_update(struct neighbour *neigh)
1802 {
1803 	const struct device *parent;
1804 	const struct net_device *netdev = neigh->dev;
1805 
1806 	if (is_vlan_dev(netdev))
1807 		netdev = vlan_dev_real_dev(netdev);
1808 	parent = netdev->dev.parent;
1809 	if (parent && parent->driver == &cxgb4_driver.driver)
1810 		t4_l2t_update(dev_get_drvdata(parent), neigh);
1811 }
1812 
1813 static int netevent_cb(struct notifier_block *nb, unsigned long event,
1814 		       void *data)
1815 {
1816 	switch (event) {
1817 	case NETEVENT_NEIGH_UPDATE:
1818 		check_neigh_update(data);
1819 		break;
1820 	case NETEVENT_REDIRECT:
1821 	default:
1822 		break;
1823 	}
1824 	return 0;
1825 }
1826 
1827 static bool netevent_registered;
1828 static struct notifier_block cxgb4_netevent_nb = {
1829 	.notifier_call = netevent_cb
1830 };
1831 
1832 static void drain_db_fifo(struct adapter *adap, int usecs)
1833 {
1834 	u32 v1, v2, lp_count, hp_count;
1835 
1836 	do {
1837 		v1 = t4_read_reg(adap, SGE_DBFIFO_STATUS_A);
1838 		v2 = t4_read_reg(adap, SGE_DBFIFO_STATUS2_A);
1839 		if (is_t4(adap->params.chip)) {
1840 			lp_count = LP_COUNT_G(v1);
1841 			hp_count = HP_COUNT_G(v1);
1842 		} else {
1843 			lp_count = LP_COUNT_T5_G(v1);
1844 			hp_count = HP_COUNT_T5_G(v2);
1845 		}
1846 
1847 		if (lp_count == 0 && hp_count == 0)
1848 			break;
1849 		set_current_state(TASK_UNINTERRUPTIBLE);
1850 		schedule_timeout(usecs_to_jiffies(usecs));
1851 	} while (1);
1852 }
1853 
1854 static void disable_txq_db(struct sge_txq *q)
1855 {
1856 	unsigned long flags;
1857 
1858 	spin_lock_irqsave(&q->db_lock, flags);
1859 	q->db_disabled = 1;
1860 	spin_unlock_irqrestore(&q->db_lock, flags);
1861 }
1862 
1863 static void enable_txq_db(struct adapter *adap, struct sge_txq *q)
1864 {
1865 	spin_lock_irq(&q->db_lock);
1866 	if (q->db_pidx_inc) {
1867 		/* Make sure that all writes to the TX descriptors
1868 		 * are committed before we tell HW about them.
1869 		 */
1870 		wmb();
1871 		t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL_A),
1872 			     QID_V(q->cntxt_id) | PIDX_V(q->db_pidx_inc));
1873 		q->db_pidx_inc = 0;
1874 	}
1875 	q->db_disabled = 0;
1876 	spin_unlock_irq(&q->db_lock);
1877 }
1878 
1879 static void disable_dbs(struct adapter *adap)
1880 {
1881 	int i;
1882 
1883 	for_each_ethrxq(&adap->sge, i)
1884 		disable_txq_db(&adap->sge.ethtxq[i].q);
1885 	if (is_offload(adap)) {
1886 		struct sge_uld_txq_info *txq_info =
1887 			adap->sge.uld_txq_info[CXGB4_TX_OFLD];
1888 
1889 		if (txq_info) {
1890 			for_each_ofldtxq(&adap->sge, i) {
1891 				struct sge_uld_txq *txq = &txq_info->uldtxq[i];
1892 
1893 				disable_txq_db(&txq->q);
1894 			}
1895 		}
1896 	}
1897 	for_each_port(adap, i)
1898 		disable_txq_db(&adap->sge.ctrlq[i].q);
1899 }
1900 
1901 static void enable_dbs(struct adapter *adap)
1902 {
1903 	int i;
1904 
1905 	for_each_ethrxq(&adap->sge, i)
1906 		enable_txq_db(adap, &adap->sge.ethtxq[i].q);
1907 	if (is_offload(adap)) {
1908 		struct sge_uld_txq_info *txq_info =
1909 			adap->sge.uld_txq_info[CXGB4_TX_OFLD];
1910 
1911 		if (txq_info) {
1912 			for_each_ofldtxq(&adap->sge, i) {
1913 				struct sge_uld_txq *txq = &txq_info->uldtxq[i];
1914 
1915 				enable_txq_db(adap, &txq->q);
1916 			}
1917 		}
1918 	}
1919 	for_each_port(adap, i)
1920 		enable_txq_db(adap, &adap->sge.ctrlq[i].q);
1921 }
1922 
1923 static void notify_rdma_uld(struct adapter *adap, enum cxgb4_control cmd)
1924 {
1925 	enum cxgb4_uld type = CXGB4_ULD_RDMA;
1926 
1927 	if (adap->uld && adap->uld[type].handle)
1928 		adap->uld[type].control(adap->uld[type].handle, cmd);
1929 }
1930 
1931 static void process_db_full(struct work_struct *work)
1932 {
1933 	struct adapter *adap;
1934 
1935 	adap = container_of(work, struct adapter, db_full_task);
1936 
1937 	drain_db_fifo(adap, dbfifo_drain_delay);
1938 	enable_dbs(adap);
1939 	notify_rdma_uld(adap, CXGB4_CONTROL_DB_EMPTY);
1940 	if (CHELSIO_CHIP_VERSION(adap->params.chip) <= CHELSIO_T5)
1941 		t4_set_reg_field(adap, SGE_INT_ENABLE3_A,
1942 				 DBFIFO_HP_INT_F | DBFIFO_LP_INT_F,
1943 				 DBFIFO_HP_INT_F | DBFIFO_LP_INT_F);
1944 	else
1945 		t4_set_reg_field(adap, SGE_INT_ENABLE3_A,
1946 				 DBFIFO_LP_INT_F, DBFIFO_LP_INT_F);
1947 }
1948 
1949 static void sync_txq_pidx(struct adapter *adap, struct sge_txq *q)
1950 {
1951 	u16 hw_pidx, hw_cidx;
1952 	int ret;
1953 
1954 	spin_lock_irq(&q->db_lock);
1955 	ret = read_eq_indices(adap, (u16)q->cntxt_id, &hw_pidx, &hw_cidx);
1956 	if (ret)
1957 		goto out;
1958 	if (q->db_pidx != hw_pidx) {
1959 		u16 delta;
1960 		u32 val;
1961 
1962 		if (q->db_pidx >= hw_pidx)
1963 			delta = q->db_pidx - hw_pidx;
1964 		else
1965 			delta = q->size - hw_pidx + q->db_pidx;
1966 
1967 		if (is_t4(adap->params.chip))
1968 			val = PIDX_V(delta);
1969 		else
1970 			val = PIDX_T5_V(delta);
1971 		wmb();
1972 		t4_write_reg(adap, MYPF_REG(SGE_PF_KDOORBELL_A),
1973 			     QID_V(q->cntxt_id) | val);
1974 	}
1975 out:
1976 	q->db_disabled = 0;
1977 	q->db_pidx_inc = 0;
1978 	spin_unlock_irq(&q->db_lock);
1979 	if (ret)
1980 		CH_WARN(adap, "DB drop recovery failed.\n");
1981 }
1982 
1983 static void recover_all_queues(struct adapter *adap)
1984 {
1985 	int i;
1986 
1987 	for_each_ethrxq(&adap->sge, i)
1988 		sync_txq_pidx(adap, &adap->sge.ethtxq[i].q);
1989 	if (is_offload(adap)) {
1990 		struct sge_uld_txq_info *txq_info =
1991 			adap->sge.uld_txq_info[CXGB4_TX_OFLD];
1992 		if (txq_info) {
1993 			for_each_ofldtxq(&adap->sge, i) {
1994 				struct sge_uld_txq *txq = &txq_info->uldtxq[i];
1995 
1996 				sync_txq_pidx(adap, &txq->q);
1997 			}
1998 		}
1999 	}
2000 	for_each_port(adap, i)
2001 		sync_txq_pidx(adap, &adap->sge.ctrlq[i].q);
2002 }
2003 
2004 static void process_db_drop(struct work_struct *work)
2005 {
2006 	struct adapter *adap;
2007 
2008 	adap = container_of(work, struct adapter, db_drop_task);
2009 
2010 	if (is_t4(adap->params.chip)) {
2011 		drain_db_fifo(adap, dbfifo_drain_delay);
2012 		notify_rdma_uld(adap, CXGB4_CONTROL_DB_DROP);
2013 		drain_db_fifo(adap, dbfifo_drain_delay);
2014 		recover_all_queues(adap);
2015 		drain_db_fifo(adap, dbfifo_drain_delay);
2016 		enable_dbs(adap);
2017 		notify_rdma_uld(adap, CXGB4_CONTROL_DB_EMPTY);
2018 	} else if (is_t5(adap->params.chip)) {
2019 		u32 dropped_db = t4_read_reg(adap, 0x010ac);
2020 		u16 qid = (dropped_db >> 15) & 0x1ffff;
2021 		u16 pidx_inc = dropped_db & 0x1fff;
2022 		u64 bar2_qoffset;
2023 		unsigned int bar2_qid;
2024 		int ret;
2025 
2026 		ret = t4_bar2_sge_qregs(adap, qid, T4_BAR2_QTYPE_EGRESS,
2027 					0, &bar2_qoffset, &bar2_qid);
2028 		if (ret)
2029 			dev_err(adap->pdev_dev, "doorbell drop recovery: "
2030 				"qid=%d, pidx_inc=%d\n", qid, pidx_inc);
2031 		else
2032 			writel(PIDX_T5_V(pidx_inc) | QID_V(bar2_qid),
2033 			       adap->bar2 + bar2_qoffset + SGE_UDB_KDOORBELL);
2034 
2035 		/* Re-enable BAR2 WC */
2036 		t4_set_reg_field(adap, 0x10b0, 1<<15, 1<<15);
2037 	}
2038 
2039 	if (CHELSIO_CHIP_VERSION(adap->params.chip) <= CHELSIO_T5)
2040 		t4_set_reg_field(adap, SGE_DOORBELL_CONTROL_A, DROPPED_DB_F, 0);
2041 }
2042 
2043 void t4_db_full(struct adapter *adap)
2044 {
2045 	if (is_t4(adap->params.chip)) {
2046 		disable_dbs(adap);
2047 		notify_rdma_uld(adap, CXGB4_CONTROL_DB_FULL);
2048 		t4_set_reg_field(adap, SGE_INT_ENABLE3_A,
2049 				 DBFIFO_HP_INT_F | DBFIFO_LP_INT_F, 0);
2050 		queue_work(adap->workq, &adap->db_full_task);
2051 	}
2052 }
2053 
2054 void t4_db_dropped(struct adapter *adap)
2055 {
2056 	if (is_t4(adap->params.chip)) {
2057 		disable_dbs(adap);
2058 		notify_rdma_uld(adap, CXGB4_CONTROL_DB_FULL);
2059 	}
2060 	queue_work(adap->workq, &adap->db_drop_task);
2061 }
2062 
2063 void t4_register_netevent_notifier(void)
2064 {
2065 	if (!netevent_registered) {
2066 		register_netevent_notifier(&cxgb4_netevent_nb);
2067 		netevent_registered = true;
2068 	}
2069 }
2070 
2071 static void detach_ulds(struct adapter *adap)
2072 {
2073 	unsigned int i;
2074 
2075 	mutex_lock(&uld_mutex);
2076 	list_del(&adap->list_node);
2077 	for (i = 0; i < CXGB4_ULD_MAX; i++)
2078 		if (adap->uld && adap->uld[i].handle) {
2079 			adap->uld[i].state_change(adap->uld[i].handle,
2080 					     CXGB4_STATE_DETACH);
2081 			adap->uld[i].handle = NULL;
2082 		}
2083 	if (netevent_registered && list_empty(&adapter_list)) {
2084 		unregister_netevent_notifier(&cxgb4_netevent_nb);
2085 		netevent_registered = false;
2086 	}
2087 	mutex_unlock(&uld_mutex);
2088 }
2089 
2090 static void notify_ulds(struct adapter *adap, enum cxgb4_state new_state)
2091 {
2092 	unsigned int i;
2093 
2094 	mutex_lock(&uld_mutex);
2095 	for (i = 0; i < CXGB4_ULD_MAX; i++)
2096 		if (adap->uld && adap->uld[i].handle)
2097 			adap->uld[i].state_change(adap->uld[i].handle,
2098 						  new_state);
2099 	mutex_unlock(&uld_mutex);
2100 }
2101 
2102 #if IS_ENABLED(CONFIG_IPV6)
2103 static int cxgb4_inet6addr_handler(struct notifier_block *this,
2104 				   unsigned long event, void *data)
2105 {
2106 	struct inet6_ifaddr *ifa = data;
2107 	struct net_device *event_dev = ifa->idev->dev;
2108 	const struct device *parent = NULL;
2109 #if IS_ENABLED(CONFIG_BONDING)
2110 	struct adapter *adap;
2111 #endif
2112 	if (is_vlan_dev(event_dev))
2113 		event_dev = vlan_dev_real_dev(event_dev);
2114 #if IS_ENABLED(CONFIG_BONDING)
2115 	if (event_dev->flags & IFF_MASTER) {
2116 		list_for_each_entry(adap, &adapter_list, list_node) {
2117 			switch (event) {
2118 			case NETDEV_UP:
2119 				cxgb4_clip_get(adap->port[0],
2120 					       (const u32 *)ifa, 1);
2121 				break;
2122 			case NETDEV_DOWN:
2123 				cxgb4_clip_release(adap->port[0],
2124 						   (const u32 *)ifa, 1);
2125 				break;
2126 			default:
2127 				break;
2128 			}
2129 		}
2130 		return NOTIFY_OK;
2131 	}
2132 #endif
2133 
2134 	if (event_dev)
2135 		parent = event_dev->dev.parent;
2136 
2137 	if (parent && parent->driver == &cxgb4_driver.driver) {
2138 		switch (event) {
2139 		case NETDEV_UP:
2140 			cxgb4_clip_get(event_dev, (const u32 *)ifa, 1);
2141 			break;
2142 		case NETDEV_DOWN:
2143 			cxgb4_clip_release(event_dev, (const u32 *)ifa, 1);
2144 			break;
2145 		default:
2146 			break;
2147 		}
2148 	}
2149 	return NOTIFY_OK;
2150 }
2151 
2152 static bool inet6addr_registered;
2153 static struct notifier_block cxgb4_inet6addr_notifier = {
2154 	.notifier_call = cxgb4_inet6addr_handler
2155 };
2156 
2157 static void update_clip(const struct adapter *adap)
2158 {
2159 	int i;
2160 	struct net_device *dev;
2161 	int ret;
2162 
2163 	rcu_read_lock();
2164 
2165 	for (i = 0; i < MAX_NPORTS; i++) {
2166 		dev = adap->port[i];
2167 		ret = 0;
2168 
2169 		if (dev)
2170 			ret = cxgb4_update_root_dev_clip(dev);
2171 
2172 		if (ret < 0)
2173 			break;
2174 	}
2175 	rcu_read_unlock();
2176 }
2177 #endif /* IS_ENABLED(CONFIG_IPV6) */
2178 
2179 /**
2180  *	cxgb_up - enable the adapter
2181  *	@adap: adapter being enabled
2182  *
2183  *	Called when the first port is enabled, this function performs the
2184  *	actions necessary to make an adapter operational, such as completing
2185  *	the initialization of HW modules, and enabling interrupts.
2186  *
2187  *	Must be called with the rtnl lock held.
2188  */
2189 static int cxgb_up(struct adapter *adap)
2190 {
2191 	int err;
2192 
2193 	mutex_lock(&uld_mutex);
2194 	err = setup_sge_queues(adap);
2195 	if (err)
2196 		goto rel_lock;
2197 	err = setup_rss(adap);
2198 	if (err)
2199 		goto freeq;
2200 
2201 	if (adap->flags & USING_MSIX) {
2202 		name_msix_vecs(adap);
2203 		err = request_irq(adap->msix_info[0].vec, t4_nondata_intr, 0,
2204 				  adap->msix_info[0].desc, adap);
2205 		if (err)
2206 			goto irq_err;
2207 		err = request_msix_queue_irqs(adap);
2208 		if (err) {
2209 			free_irq(adap->msix_info[0].vec, adap);
2210 			goto irq_err;
2211 		}
2212 	} else {
2213 		err = request_irq(adap->pdev->irq, t4_intr_handler(adap),
2214 				  (adap->flags & USING_MSI) ? 0 : IRQF_SHARED,
2215 				  adap->port[0]->name, adap);
2216 		if (err)
2217 			goto irq_err;
2218 	}
2219 
2220 	enable_rx(adap);
2221 	t4_sge_start(adap);
2222 	t4_intr_enable(adap);
2223 	adap->flags |= FULL_INIT_DONE;
2224 	mutex_unlock(&uld_mutex);
2225 
2226 	notify_ulds(adap, CXGB4_STATE_UP);
2227 #if IS_ENABLED(CONFIG_IPV6)
2228 	update_clip(adap);
2229 #endif
2230 	/* Initialize hash mac addr list*/
2231 	INIT_LIST_HEAD(&adap->mac_hlist);
2232 	return err;
2233 
2234  irq_err:
2235 	dev_err(adap->pdev_dev, "request_irq failed, err %d\n", err);
2236  freeq:
2237 	t4_free_sge_resources(adap);
2238  rel_lock:
2239 	mutex_unlock(&uld_mutex);
2240 	return err;
2241 }
2242 
2243 static void cxgb_down(struct adapter *adapter)
2244 {
2245 	cancel_work_sync(&adapter->tid_release_task);
2246 	cancel_work_sync(&adapter->db_full_task);
2247 	cancel_work_sync(&adapter->db_drop_task);
2248 	adapter->tid_release_task_busy = false;
2249 	adapter->tid_release_head = NULL;
2250 
2251 	t4_sge_stop(adapter);
2252 	t4_free_sge_resources(adapter);
2253 	adapter->flags &= ~FULL_INIT_DONE;
2254 }
2255 
2256 /*
2257  * net_device operations
2258  */
2259 static int cxgb_open(struct net_device *dev)
2260 {
2261 	int err;
2262 	struct port_info *pi = netdev_priv(dev);
2263 	struct adapter *adapter = pi->adapter;
2264 
2265 	netif_carrier_off(dev);
2266 
2267 	if (!(adapter->flags & FULL_INIT_DONE)) {
2268 		err = cxgb_up(adapter);
2269 		if (err < 0)
2270 			return err;
2271 	}
2272 
2273 	/* It's possible that the basic port information could have
2274 	 * changed since we first read it.
2275 	 */
2276 	err = t4_update_port_info(pi);
2277 	if (err < 0)
2278 		return err;
2279 
2280 	err = link_start(dev);
2281 	if (!err)
2282 		netif_tx_start_all_queues(dev);
2283 	return err;
2284 }
2285 
2286 static int cxgb_close(struct net_device *dev)
2287 {
2288 	struct port_info *pi = netdev_priv(dev);
2289 	struct adapter *adapter = pi->adapter;
2290 
2291 	netif_tx_stop_all_queues(dev);
2292 	netif_carrier_off(dev);
2293 	return t4_enable_vi(adapter, adapter->pf, pi->viid, false, false);
2294 }
2295 
2296 int cxgb4_create_server_filter(const struct net_device *dev, unsigned int stid,
2297 		__be32 sip, __be16 sport, __be16 vlan,
2298 		unsigned int queue, unsigned char port, unsigned char mask)
2299 {
2300 	int ret;
2301 	struct filter_entry *f;
2302 	struct adapter *adap;
2303 	int i;
2304 	u8 *val;
2305 
2306 	adap = netdev2adap(dev);
2307 
2308 	/* Adjust stid to correct filter index */
2309 	stid -= adap->tids.sftid_base;
2310 	stid += adap->tids.nftids;
2311 
2312 	/* Check to make sure the filter requested is writable ...
2313 	 */
2314 	f = &adap->tids.ftid_tab[stid];
2315 	ret = writable_filter(f);
2316 	if (ret)
2317 		return ret;
2318 
2319 	/* Clear out any old resources being used by the filter before
2320 	 * we start constructing the new filter.
2321 	 */
2322 	if (f->valid)
2323 		clear_filter(adap, f);
2324 
2325 	/* Clear out filter specifications */
2326 	memset(&f->fs, 0, sizeof(struct ch_filter_specification));
2327 	f->fs.val.lport = cpu_to_be16(sport);
2328 	f->fs.mask.lport  = ~0;
2329 	val = (u8 *)&sip;
2330 	if ((val[0] | val[1] | val[2] | val[3]) != 0) {
2331 		for (i = 0; i < 4; i++) {
2332 			f->fs.val.lip[i] = val[i];
2333 			f->fs.mask.lip[i] = ~0;
2334 		}
2335 		if (adap->params.tp.vlan_pri_map & PORT_F) {
2336 			f->fs.val.iport = port;
2337 			f->fs.mask.iport = mask;
2338 		}
2339 	}
2340 
2341 	if (adap->params.tp.vlan_pri_map & PROTOCOL_F) {
2342 		f->fs.val.proto = IPPROTO_TCP;
2343 		f->fs.mask.proto = ~0;
2344 	}
2345 
2346 	f->fs.dirsteer = 1;
2347 	f->fs.iq = queue;
2348 	/* Mark filter as locked */
2349 	f->locked = 1;
2350 	f->fs.rpttid = 1;
2351 
2352 	/* Save the actual tid. We need this to get the corresponding
2353 	 * filter entry structure in filter_rpl.
2354 	 */
2355 	f->tid = stid + adap->tids.ftid_base;
2356 	ret = set_filter_wr(adap, stid);
2357 	if (ret) {
2358 		clear_filter(adap, f);
2359 		return ret;
2360 	}
2361 
2362 	return 0;
2363 }
2364 EXPORT_SYMBOL(cxgb4_create_server_filter);
2365 
2366 int cxgb4_remove_server_filter(const struct net_device *dev, unsigned int stid,
2367 		unsigned int queue, bool ipv6)
2368 {
2369 	struct filter_entry *f;
2370 	struct adapter *adap;
2371 
2372 	adap = netdev2adap(dev);
2373 
2374 	/* Adjust stid to correct filter index */
2375 	stid -= adap->tids.sftid_base;
2376 	stid += adap->tids.nftids;
2377 
2378 	f = &adap->tids.ftid_tab[stid];
2379 	/* Unlock the filter */
2380 	f->locked = 0;
2381 
2382 	return delete_filter(adap, stid);
2383 }
2384 EXPORT_SYMBOL(cxgb4_remove_server_filter);
2385 
2386 static void cxgb_get_stats(struct net_device *dev,
2387 			   struct rtnl_link_stats64 *ns)
2388 {
2389 	struct port_stats stats;
2390 	struct port_info *p = netdev_priv(dev);
2391 	struct adapter *adapter = p->adapter;
2392 
2393 	/* Block retrieving statistics during EEH error
2394 	 * recovery. Otherwise, the recovery might fail
2395 	 * and the PCI device will be removed permanently
2396 	 */
2397 	spin_lock(&adapter->stats_lock);
2398 	if (!netif_device_present(dev)) {
2399 		spin_unlock(&adapter->stats_lock);
2400 		return;
2401 	}
2402 	t4_get_port_stats_offset(adapter, p->tx_chan, &stats,
2403 				 &p->stats_base);
2404 	spin_unlock(&adapter->stats_lock);
2405 
2406 	ns->tx_bytes   = stats.tx_octets;
2407 	ns->tx_packets = stats.tx_frames;
2408 	ns->rx_bytes   = stats.rx_octets;
2409 	ns->rx_packets = stats.rx_frames;
2410 	ns->multicast  = stats.rx_mcast_frames;
2411 
2412 	/* detailed rx_errors */
2413 	ns->rx_length_errors = stats.rx_jabber + stats.rx_too_long +
2414 			       stats.rx_runt;
2415 	ns->rx_over_errors   = 0;
2416 	ns->rx_crc_errors    = stats.rx_fcs_err;
2417 	ns->rx_frame_errors  = stats.rx_symbol_err;
2418 	ns->rx_dropped	     = stats.rx_ovflow0 + stats.rx_ovflow1 +
2419 			       stats.rx_ovflow2 + stats.rx_ovflow3 +
2420 			       stats.rx_trunc0 + stats.rx_trunc1 +
2421 			       stats.rx_trunc2 + stats.rx_trunc3;
2422 	ns->rx_missed_errors = 0;
2423 
2424 	/* detailed tx_errors */
2425 	ns->tx_aborted_errors   = 0;
2426 	ns->tx_carrier_errors   = 0;
2427 	ns->tx_fifo_errors      = 0;
2428 	ns->tx_heartbeat_errors = 0;
2429 	ns->tx_window_errors    = 0;
2430 
2431 	ns->tx_errors = stats.tx_error_frames;
2432 	ns->rx_errors = stats.rx_symbol_err + stats.rx_fcs_err +
2433 		ns->rx_length_errors + stats.rx_len_err + ns->rx_fifo_errors;
2434 }
2435 
2436 static int cxgb_ioctl(struct net_device *dev, struct ifreq *req, int cmd)
2437 {
2438 	unsigned int mbox;
2439 	int ret = 0, prtad, devad;
2440 	struct port_info *pi = netdev_priv(dev);
2441 	struct mii_ioctl_data *data = (struct mii_ioctl_data *)&req->ifr_data;
2442 
2443 	switch (cmd) {
2444 	case SIOCGMIIPHY:
2445 		if (pi->mdio_addr < 0)
2446 			return -EOPNOTSUPP;
2447 		data->phy_id = pi->mdio_addr;
2448 		break;
2449 	case SIOCGMIIREG:
2450 	case SIOCSMIIREG:
2451 		if (mdio_phy_id_is_c45(data->phy_id)) {
2452 			prtad = mdio_phy_id_prtad(data->phy_id);
2453 			devad = mdio_phy_id_devad(data->phy_id);
2454 		} else if (data->phy_id < 32) {
2455 			prtad = data->phy_id;
2456 			devad = 0;
2457 			data->reg_num &= 0x1f;
2458 		} else
2459 			return -EINVAL;
2460 
2461 		mbox = pi->adapter->pf;
2462 		if (cmd == SIOCGMIIREG)
2463 			ret = t4_mdio_rd(pi->adapter, mbox, prtad, devad,
2464 					 data->reg_num, &data->val_out);
2465 		else
2466 			ret = t4_mdio_wr(pi->adapter, mbox, prtad, devad,
2467 					 data->reg_num, data->val_in);
2468 		break;
2469 	case SIOCGHWTSTAMP:
2470 		return copy_to_user(req->ifr_data, &pi->tstamp_config,
2471 				    sizeof(pi->tstamp_config)) ?
2472 			-EFAULT : 0;
2473 	case SIOCSHWTSTAMP:
2474 		if (copy_from_user(&pi->tstamp_config, req->ifr_data,
2475 				   sizeof(pi->tstamp_config)))
2476 			return -EFAULT;
2477 
2478 		switch (pi->tstamp_config.rx_filter) {
2479 		case HWTSTAMP_FILTER_NONE:
2480 			pi->rxtstamp = false;
2481 			break;
2482 		case HWTSTAMP_FILTER_ALL:
2483 			pi->rxtstamp = true;
2484 			break;
2485 		default:
2486 			pi->tstamp_config.rx_filter = HWTSTAMP_FILTER_NONE;
2487 			return -ERANGE;
2488 		}
2489 
2490 		return copy_to_user(req->ifr_data, &pi->tstamp_config,
2491 				    sizeof(pi->tstamp_config)) ?
2492 			-EFAULT : 0;
2493 	default:
2494 		return -EOPNOTSUPP;
2495 	}
2496 	return ret;
2497 }
2498 
2499 static void cxgb_set_rxmode(struct net_device *dev)
2500 {
2501 	/* unfortunately we can't return errors to the stack */
2502 	set_rxmode(dev, -1, false);
2503 }
2504 
2505 static int cxgb_change_mtu(struct net_device *dev, int new_mtu)
2506 {
2507 	int ret;
2508 	struct port_info *pi = netdev_priv(dev);
2509 
2510 	ret = t4_set_rxmode(pi->adapter, pi->adapter->pf, pi->viid, new_mtu, -1,
2511 			    -1, -1, -1, true);
2512 	if (!ret)
2513 		dev->mtu = new_mtu;
2514 	return ret;
2515 }
2516 
2517 #ifdef CONFIG_PCI_IOV
2518 static int dummy_open(struct net_device *dev)
2519 {
2520 	/* Turn carrier off since we don't have to transmit anything on this
2521 	 * interface.
2522 	 */
2523 	netif_carrier_off(dev);
2524 	return 0;
2525 }
2526 
2527 /* Fill MAC address that will be assigned by the FW */
2528 static void fill_vf_station_mac_addr(struct adapter *adap)
2529 {
2530 	unsigned int i;
2531 	u8 hw_addr[ETH_ALEN], macaddr[ETH_ALEN];
2532 	int err;
2533 	u8 *na;
2534 	u16 a, b;
2535 
2536 	err = t4_get_raw_vpd_params(adap, &adap->params.vpd);
2537 	if (!err) {
2538 		na = adap->params.vpd.na;
2539 		for (i = 0; i < ETH_ALEN; i++)
2540 			hw_addr[i] = (hex2val(na[2 * i + 0]) * 16 +
2541 				      hex2val(na[2 * i + 1]));
2542 		a = (hw_addr[0] << 8) | hw_addr[1];
2543 		b = (hw_addr[1] << 8) | hw_addr[2];
2544 		a ^= b;
2545 		a |= 0x0200;    /* locally assigned Ethernet MAC address */
2546 		a &= ~0x0100;   /* not a multicast Ethernet MAC address */
2547 		macaddr[0] = a >> 8;
2548 		macaddr[1] = a & 0xff;
2549 
2550 		for (i = 2; i < 5; i++)
2551 			macaddr[i] = hw_addr[i + 1];
2552 
2553 		for (i = 0; i < adap->num_vfs; i++) {
2554 			macaddr[5] = adap->pf * 16 + i;
2555 			ether_addr_copy(adap->vfinfo[i].vf_mac_addr, macaddr);
2556 		}
2557 	}
2558 }
2559 
2560 static int cxgb_set_vf_mac(struct net_device *dev, int vf, u8 *mac)
2561 {
2562 	struct port_info *pi = netdev_priv(dev);
2563 	struct adapter *adap = pi->adapter;
2564 	int ret;
2565 
2566 	/* verify MAC addr is valid */
2567 	if (!is_valid_ether_addr(mac)) {
2568 		dev_err(pi->adapter->pdev_dev,
2569 			"Invalid Ethernet address %pM for VF %d\n",
2570 			mac, vf);
2571 		return -EINVAL;
2572 	}
2573 
2574 	dev_info(pi->adapter->pdev_dev,
2575 		 "Setting MAC %pM on VF %d\n", mac, vf);
2576 	ret = t4_set_vf_mac_acl(adap, vf + 1, 1, mac);
2577 	if (!ret)
2578 		ether_addr_copy(adap->vfinfo[vf].vf_mac_addr, mac);
2579 	return ret;
2580 }
2581 
2582 static int cxgb_get_vf_config(struct net_device *dev,
2583 			      int vf, struct ifla_vf_info *ivi)
2584 {
2585 	struct port_info *pi = netdev_priv(dev);
2586 	struct adapter *adap = pi->adapter;
2587 
2588 	if (vf >= adap->num_vfs)
2589 		return -EINVAL;
2590 	ivi->vf = vf;
2591 	ivi->max_tx_rate = adap->vfinfo[vf].tx_rate;
2592 	ivi->min_tx_rate = 0;
2593 	ether_addr_copy(ivi->mac, adap->vfinfo[vf].vf_mac_addr);
2594 	return 0;
2595 }
2596 
2597 static int cxgb_get_phys_port_id(struct net_device *dev,
2598 				 struct netdev_phys_item_id *ppid)
2599 {
2600 	struct port_info *pi = netdev_priv(dev);
2601 	unsigned int phy_port_id;
2602 
2603 	phy_port_id = pi->adapter->adap_idx * 10 + pi->port_id;
2604 	ppid->id_len = sizeof(phy_port_id);
2605 	memcpy(ppid->id, &phy_port_id, ppid->id_len);
2606 	return 0;
2607 }
2608 
2609 static int cxgb_set_vf_rate(struct net_device *dev, int vf, int min_tx_rate,
2610 			    int max_tx_rate)
2611 {
2612 	struct port_info *pi = netdev_priv(dev);
2613 	struct adapter *adap = pi->adapter;
2614 	struct fw_port_cmd port_cmd, port_rpl;
2615 	u32 link_status, speed = 0;
2616 	u32 fw_pfvf, fw_class;
2617 	int class_id = vf;
2618 	int link_ok, ret;
2619 	u16 pktsize;
2620 
2621 	if (vf >= adap->num_vfs)
2622 		return -EINVAL;
2623 
2624 	if (min_tx_rate) {
2625 		dev_err(adap->pdev_dev,
2626 			"Min tx rate (%d) (> 0) for VF %d is Invalid.\n",
2627 			min_tx_rate, vf);
2628 		return -EINVAL;
2629 	}
2630 	/* Retrieve link details for VF port */
2631 	memset(&port_cmd, 0, sizeof(port_cmd));
2632 	port_cmd.op_to_portid = cpu_to_be32(FW_CMD_OP_V(FW_PORT_CMD) |
2633 					    FW_CMD_REQUEST_F |
2634 					    FW_CMD_READ_F |
2635 					    FW_PORT_CMD_PORTID_V(pi->port_id));
2636 	port_cmd.action_to_len16 =
2637 		cpu_to_be32(FW_PORT_CMD_ACTION_V(FW_PORT_ACTION_GET_PORT_INFO) |
2638 			    FW_LEN16(port_cmd));
2639 	ret = t4_wr_mbox(adap, adap->mbox, &port_cmd, sizeof(port_cmd),
2640 			 &port_rpl);
2641 	if (ret != FW_SUCCESS) {
2642 		dev_err(adap->pdev_dev,
2643 			"Failed to get link status for VF %d\n", vf);
2644 		return -EINVAL;
2645 	}
2646 	link_status = be32_to_cpu(port_rpl.u.info.lstatus_to_modtype);
2647 	link_ok = (link_status & FW_PORT_CMD_LSTATUS_F) != 0;
2648 	if (!link_ok) {
2649 		dev_err(adap->pdev_dev, "Link down for VF %d\n", vf);
2650 		return -EINVAL;
2651 	}
2652 	/* Determine link speed */
2653 	if (link_status & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_100M))
2654 		speed = 100;
2655 	else if (link_status & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_1G))
2656 		speed = 1000;
2657 	else if (link_status & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_10G))
2658 		speed = 10000;
2659 	else if (link_status & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_25G))
2660 		speed = 25000;
2661 	else if (link_status & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_40G))
2662 		speed = 40000;
2663 	else if (link_status & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_100G))
2664 		speed = 100000;
2665 
2666 	if (max_tx_rate > speed) {
2667 		dev_err(adap->pdev_dev,
2668 			"Max tx rate %d for VF %d can't be > link-speed %u",
2669 			max_tx_rate, vf, speed);
2670 		return -EINVAL;
2671 	}
2672 	pktsize = be16_to_cpu(port_rpl.u.info.mtu);
2673 	/* subtract ethhdr size and 4 bytes crc since, f/w appends it */
2674 	pktsize = pktsize - sizeof(struct ethhdr) - 4;
2675 	/* subtract ipv4 hdr size, tcp hdr size to get typical IPv4 MSS size */
2676 	pktsize = pktsize - sizeof(struct iphdr) - sizeof(struct tcphdr);
2677 	/* configure Traffic Class for rate-limiting */
2678 	ret = t4_sched_params(adap, SCHED_CLASS_TYPE_PACKET,
2679 			      SCHED_CLASS_LEVEL_CL_RL,
2680 			      SCHED_CLASS_MODE_CLASS,
2681 			      SCHED_CLASS_RATEUNIT_BITS,
2682 			      SCHED_CLASS_RATEMODE_ABS,
2683 			      pi->port_id, class_id, 0,
2684 			      max_tx_rate * 1000, 0, pktsize);
2685 	if (ret) {
2686 		dev_err(adap->pdev_dev, "Err %d for Traffic Class config\n",
2687 			ret);
2688 		return -EINVAL;
2689 	}
2690 	dev_info(adap->pdev_dev,
2691 		 "Class %d with MSS %u configured with rate %u\n",
2692 		 class_id, pktsize, max_tx_rate);
2693 
2694 	/* bind VF to configured Traffic Class */
2695 	fw_pfvf = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_PFVF) |
2696 		   FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_PFVF_SCHEDCLASS_ETH));
2697 	fw_class = class_id;
2698 	ret = t4_set_params(adap, adap->mbox, adap->pf, vf + 1, 1, &fw_pfvf,
2699 			    &fw_class);
2700 	if (ret) {
2701 		dev_err(adap->pdev_dev,
2702 			"Err %d in binding VF %d to Traffic Class %d\n",
2703 			ret, vf, class_id);
2704 		return -EINVAL;
2705 	}
2706 	dev_info(adap->pdev_dev, "PF %d VF %d is bound to Class %d\n",
2707 		 adap->pf, vf, class_id);
2708 	adap->vfinfo[vf].tx_rate = max_tx_rate;
2709 	return 0;
2710 }
2711 
2712 #endif
2713 
2714 static int cxgb_set_mac_addr(struct net_device *dev, void *p)
2715 {
2716 	int ret;
2717 	struct sockaddr *addr = p;
2718 	struct port_info *pi = netdev_priv(dev);
2719 
2720 	if (!is_valid_ether_addr(addr->sa_data))
2721 		return -EADDRNOTAVAIL;
2722 
2723 	ret = t4_change_mac(pi->adapter, pi->adapter->pf, pi->viid,
2724 			    pi->xact_addr_filt, addr->sa_data, true, true);
2725 	if (ret < 0)
2726 		return ret;
2727 
2728 	memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
2729 	pi->xact_addr_filt = ret;
2730 	return 0;
2731 }
2732 
2733 #ifdef CONFIG_NET_POLL_CONTROLLER
2734 static void cxgb_netpoll(struct net_device *dev)
2735 {
2736 	struct port_info *pi = netdev_priv(dev);
2737 	struct adapter *adap = pi->adapter;
2738 
2739 	if (adap->flags & USING_MSIX) {
2740 		int i;
2741 		struct sge_eth_rxq *rx = &adap->sge.ethrxq[pi->first_qset];
2742 
2743 		for (i = pi->nqsets; i; i--, rx++)
2744 			t4_sge_intr_msix(0, &rx->rspq);
2745 	} else
2746 		t4_intr_handler(adap)(0, adap);
2747 }
2748 #endif
2749 
2750 static int cxgb_set_tx_maxrate(struct net_device *dev, int index, u32 rate)
2751 {
2752 	struct port_info *pi = netdev_priv(dev);
2753 	struct adapter *adap = pi->adapter;
2754 	struct sched_class *e;
2755 	struct ch_sched_params p;
2756 	struct ch_sched_queue qe;
2757 	u32 req_rate;
2758 	int err = 0;
2759 
2760 	if (!can_sched(dev))
2761 		return -ENOTSUPP;
2762 
2763 	if (index < 0 || index > pi->nqsets - 1)
2764 		return -EINVAL;
2765 
2766 	if (!(adap->flags & FULL_INIT_DONE)) {
2767 		dev_err(adap->pdev_dev,
2768 			"Failed to rate limit on queue %d. Link Down?\n",
2769 			index);
2770 		return -EINVAL;
2771 	}
2772 
2773 	/* Convert from Mbps to Kbps */
2774 	req_rate = rate << 10;
2775 
2776 	/* Max rate is 10 Gbps */
2777 	if (req_rate >= SCHED_MAX_RATE_KBPS) {
2778 		dev_err(adap->pdev_dev,
2779 			"Invalid rate %u Mbps, Max rate is %u Gbps\n",
2780 			rate, SCHED_MAX_RATE_KBPS);
2781 		return -ERANGE;
2782 	}
2783 
2784 	/* First unbind the queue from any existing class */
2785 	memset(&qe, 0, sizeof(qe));
2786 	qe.queue = index;
2787 	qe.class = SCHED_CLS_NONE;
2788 
2789 	err = cxgb4_sched_class_unbind(dev, (void *)(&qe), SCHED_QUEUE);
2790 	if (err) {
2791 		dev_err(adap->pdev_dev,
2792 			"Unbinding Queue %d on port %d fail. Err: %d\n",
2793 			index, pi->port_id, err);
2794 		return err;
2795 	}
2796 
2797 	/* Queue already unbound */
2798 	if (!req_rate)
2799 		return 0;
2800 
2801 	/* Fetch any available unused or matching scheduling class */
2802 	memset(&p, 0, sizeof(p));
2803 	p.type = SCHED_CLASS_TYPE_PACKET;
2804 	p.u.params.level    = SCHED_CLASS_LEVEL_CL_RL;
2805 	p.u.params.mode     = SCHED_CLASS_MODE_CLASS;
2806 	p.u.params.rateunit = SCHED_CLASS_RATEUNIT_BITS;
2807 	p.u.params.ratemode = SCHED_CLASS_RATEMODE_ABS;
2808 	p.u.params.channel  = pi->tx_chan;
2809 	p.u.params.class    = SCHED_CLS_NONE;
2810 	p.u.params.minrate  = 0;
2811 	p.u.params.maxrate  = req_rate;
2812 	p.u.params.weight   = 0;
2813 	p.u.params.pktsize  = dev->mtu;
2814 
2815 	e = cxgb4_sched_class_alloc(dev, &p);
2816 	if (!e)
2817 		return -ENOMEM;
2818 
2819 	/* Bind the queue to a scheduling class */
2820 	memset(&qe, 0, sizeof(qe));
2821 	qe.queue = index;
2822 	qe.class = e->idx;
2823 
2824 	err = cxgb4_sched_class_bind(dev, (void *)(&qe), SCHED_QUEUE);
2825 	if (err)
2826 		dev_err(adap->pdev_dev,
2827 			"Queue rate limiting failed. Err: %d\n", err);
2828 	return err;
2829 }
2830 
2831 static int cxgb_setup_tc(struct net_device *dev, u32 handle, u32 chain_index,
2832 			 __be16 proto, struct tc_to_netdev *tc)
2833 {
2834 	struct port_info *pi = netdev2pinfo(dev);
2835 	struct adapter *adap = netdev2adap(dev);
2836 
2837 	if (chain_index)
2838 		return -EOPNOTSUPP;
2839 
2840 	if (!(adap->flags & FULL_INIT_DONE)) {
2841 		dev_err(adap->pdev_dev,
2842 			"Failed to setup tc on port %d. Link Down?\n",
2843 			pi->port_id);
2844 		return -EINVAL;
2845 	}
2846 
2847 	if (TC_H_MAJ(handle) == TC_H_MAJ(TC_H_INGRESS) &&
2848 	    tc->type == TC_SETUP_CLSU32) {
2849 		switch (tc->cls_u32->command) {
2850 		case TC_CLSU32_NEW_KNODE:
2851 		case TC_CLSU32_REPLACE_KNODE:
2852 			return cxgb4_config_knode(dev, proto, tc->cls_u32);
2853 		case TC_CLSU32_DELETE_KNODE:
2854 			return cxgb4_delete_knode(dev, proto, tc->cls_u32);
2855 		default:
2856 			return -EOPNOTSUPP;
2857 		}
2858 	}
2859 
2860 	return -EOPNOTSUPP;
2861 }
2862 
2863 static netdev_features_t cxgb_fix_features(struct net_device *dev,
2864 					   netdev_features_t features)
2865 {
2866 	/* Disable GRO, if RX_CSUM is disabled */
2867 	if (!(features & NETIF_F_RXCSUM))
2868 		features &= ~NETIF_F_GRO;
2869 
2870 	return features;
2871 }
2872 
2873 static const struct net_device_ops cxgb4_netdev_ops = {
2874 	.ndo_open             = cxgb_open,
2875 	.ndo_stop             = cxgb_close,
2876 	.ndo_start_xmit       = t4_eth_xmit,
2877 	.ndo_select_queue     =	cxgb_select_queue,
2878 	.ndo_get_stats64      = cxgb_get_stats,
2879 	.ndo_set_rx_mode      = cxgb_set_rxmode,
2880 	.ndo_set_mac_address  = cxgb_set_mac_addr,
2881 	.ndo_set_features     = cxgb_set_features,
2882 	.ndo_validate_addr    = eth_validate_addr,
2883 	.ndo_do_ioctl         = cxgb_ioctl,
2884 	.ndo_change_mtu       = cxgb_change_mtu,
2885 #ifdef CONFIG_NET_POLL_CONTROLLER
2886 	.ndo_poll_controller  = cxgb_netpoll,
2887 #endif
2888 #ifdef CONFIG_CHELSIO_T4_FCOE
2889 	.ndo_fcoe_enable      = cxgb_fcoe_enable,
2890 	.ndo_fcoe_disable     = cxgb_fcoe_disable,
2891 #endif /* CONFIG_CHELSIO_T4_FCOE */
2892 	.ndo_set_tx_maxrate   = cxgb_set_tx_maxrate,
2893 	.ndo_setup_tc         = cxgb_setup_tc,
2894 	.ndo_fix_features     = cxgb_fix_features,
2895 };
2896 
2897 #ifdef CONFIG_PCI_IOV
2898 static const struct net_device_ops cxgb4_mgmt_netdev_ops = {
2899 	.ndo_open             = dummy_open,
2900 	.ndo_set_vf_mac       = cxgb_set_vf_mac,
2901 	.ndo_get_vf_config    = cxgb_get_vf_config,
2902 	.ndo_set_vf_rate      = cxgb_set_vf_rate,
2903 	.ndo_get_phys_port_id = cxgb_get_phys_port_id,
2904 };
2905 #endif
2906 
2907 static void get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
2908 {
2909 	struct adapter *adapter = netdev2adap(dev);
2910 
2911 	strlcpy(info->driver, cxgb4_driver_name, sizeof(info->driver));
2912 	strlcpy(info->version, cxgb4_driver_version,
2913 		sizeof(info->version));
2914 	strlcpy(info->bus_info, pci_name(adapter->pdev),
2915 		sizeof(info->bus_info));
2916 }
2917 
2918 static const struct ethtool_ops cxgb4_mgmt_ethtool_ops = {
2919 	.get_drvinfo       = get_drvinfo,
2920 };
2921 
2922 void t4_fatal_err(struct adapter *adap)
2923 {
2924 	int port;
2925 
2926 	if (pci_channel_offline(adap->pdev))
2927 		return;
2928 
2929 	/* Disable the SGE since ULDs are going to free resources that
2930 	 * could be exposed to the adapter.  RDMA MWs for example...
2931 	 */
2932 	t4_shutdown_adapter(adap);
2933 	for_each_port(adap, port) {
2934 		struct net_device *dev = adap->port[port];
2935 
2936 		/* If we get here in very early initialization the network
2937 		 * devices may not have been set up yet.
2938 		 */
2939 		if (!dev)
2940 			continue;
2941 
2942 		netif_tx_stop_all_queues(dev);
2943 		netif_carrier_off(dev);
2944 	}
2945 	dev_alert(adap->pdev_dev, "encountered fatal error, adapter stopped\n");
2946 }
2947 
2948 static void setup_memwin(struct adapter *adap)
2949 {
2950 	u32 nic_win_base = t4_get_util_window(adap);
2951 
2952 	t4_setup_memwin(adap, nic_win_base, MEMWIN_NIC);
2953 }
2954 
2955 static void setup_memwin_rdma(struct adapter *adap)
2956 {
2957 	if (adap->vres.ocq.size) {
2958 		u32 start;
2959 		unsigned int sz_kb;
2960 
2961 		start = t4_read_pcie_cfg4(adap, PCI_BASE_ADDRESS_2);
2962 		start &= PCI_BASE_ADDRESS_MEM_MASK;
2963 		start += OCQ_WIN_OFFSET(adap->pdev, &adap->vres);
2964 		sz_kb = roundup_pow_of_two(adap->vres.ocq.size) >> 10;
2965 		t4_write_reg(adap,
2966 			     PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_BASE_WIN_A, 3),
2967 			     start | BIR_V(1) | WINDOW_V(ilog2(sz_kb)));
2968 		t4_write_reg(adap,
2969 			     PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_OFFSET_A, 3),
2970 			     adap->vres.ocq.start);
2971 		t4_read_reg(adap,
2972 			    PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_OFFSET_A, 3));
2973 	}
2974 }
2975 
2976 static int adap_init1(struct adapter *adap, struct fw_caps_config_cmd *c)
2977 {
2978 	u32 v;
2979 	int ret;
2980 
2981 	/* get device capabilities */
2982 	memset(c, 0, sizeof(*c));
2983 	c->op_to_write = htonl(FW_CMD_OP_V(FW_CAPS_CONFIG_CMD) |
2984 			       FW_CMD_REQUEST_F | FW_CMD_READ_F);
2985 	c->cfvalid_to_len16 = htonl(FW_LEN16(*c));
2986 	ret = t4_wr_mbox(adap, adap->mbox, c, sizeof(*c), c);
2987 	if (ret < 0)
2988 		return ret;
2989 
2990 	c->op_to_write = htonl(FW_CMD_OP_V(FW_CAPS_CONFIG_CMD) |
2991 			       FW_CMD_REQUEST_F | FW_CMD_WRITE_F);
2992 	ret = t4_wr_mbox(adap, adap->mbox, c, sizeof(*c), NULL);
2993 	if (ret < 0)
2994 		return ret;
2995 
2996 	ret = t4_config_glbl_rss(adap, adap->pf,
2997 				 FW_RSS_GLB_CONFIG_CMD_MODE_BASICVIRTUAL,
2998 				 FW_RSS_GLB_CONFIG_CMD_TNLMAPEN_F |
2999 				 FW_RSS_GLB_CONFIG_CMD_TNLALLLKP_F);
3000 	if (ret < 0)
3001 		return ret;
3002 
3003 	ret = t4_cfg_pfvf(adap, adap->mbox, adap->pf, 0, adap->sge.egr_sz, 64,
3004 			  MAX_INGQ, 0, 0, 4, 0xf, 0xf, 16, FW_CMD_CAP_PF,
3005 			  FW_CMD_CAP_PF);
3006 	if (ret < 0)
3007 		return ret;
3008 
3009 	t4_sge_init(adap);
3010 
3011 	/* tweak some settings */
3012 	t4_write_reg(adap, TP_SHIFT_CNT_A, 0x64f8849);
3013 	t4_write_reg(adap, ULP_RX_TDDP_PSZ_A, HPZ0_V(PAGE_SHIFT - 12));
3014 	t4_write_reg(adap, TP_PIO_ADDR_A, TP_INGRESS_CONFIG_A);
3015 	v = t4_read_reg(adap, TP_PIO_DATA_A);
3016 	t4_write_reg(adap, TP_PIO_DATA_A, v & ~CSUM_HAS_PSEUDO_HDR_F);
3017 
3018 	/* first 4 Tx modulation queues point to consecutive Tx channels */
3019 	adap->params.tp.tx_modq_map = 0xE4;
3020 	t4_write_reg(adap, TP_TX_MOD_QUEUE_REQ_MAP_A,
3021 		     TX_MOD_QUEUE_REQ_MAP_V(adap->params.tp.tx_modq_map));
3022 
3023 	/* associate each Tx modulation queue with consecutive Tx channels */
3024 	v = 0x84218421;
3025 	t4_write_indirect(adap, TP_PIO_ADDR_A, TP_PIO_DATA_A,
3026 			  &v, 1, TP_TX_SCHED_HDR_A);
3027 	t4_write_indirect(adap, TP_PIO_ADDR_A, TP_PIO_DATA_A,
3028 			  &v, 1, TP_TX_SCHED_FIFO_A);
3029 	t4_write_indirect(adap, TP_PIO_ADDR_A, TP_PIO_DATA_A,
3030 			  &v, 1, TP_TX_SCHED_PCMD_A);
3031 
3032 #define T4_TX_MODQ_10G_WEIGHT_DEFAULT 16 /* in KB units */
3033 	if (is_offload(adap)) {
3034 		t4_write_reg(adap, TP_TX_MOD_QUEUE_WEIGHT0_A,
3035 			     TX_MODQ_WEIGHT0_V(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
3036 			     TX_MODQ_WEIGHT1_V(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
3037 			     TX_MODQ_WEIGHT2_V(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
3038 			     TX_MODQ_WEIGHT3_V(T4_TX_MODQ_10G_WEIGHT_DEFAULT));
3039 		t4_write_reg(adap, TP_TX_MOD_CHANNEL_WEIGHT_A,
3040 			     TX_MODQ_WEIGHT0_V(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
3041 			     TX_MODQ_WEIGHT1_V(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
3042 			     TX_MODQ_WEIGHT2_V(T4_TX_MODQ_10G_WEIGHT_DEFAULT) |
3043 			     TX_MODQ_WEIGHT3_V(T4_TX_MODQ_10G_WEIGHT_DEFAULT));
3044 	}
3045 
3046 	/* get basic stuff going */
3047 	return t4_early_init(adap, adap->pf);
3048 }
3049 
3050 /*
3051  * Max # of ATIDs.  The absolute HW max is 16K but we keep it lower.
3052  */
3053 #define MAX_ATIDS 8192U
3054 
3055 /*
3056  * Phase 0 of initialization: contact FW, obtain config, perform basic init.
3057  *
3058  * If the firmware we're dealing with has Configuration File support, then
3059  * we use that to perform all configuration
3060  */
3061 
3062 /*
3063  * Tweak configuration based on module parameters, etc.  Most of these have
3064  * defaults assigned to them by Firmware Configuration Files (if we're using
3065  * them) but need to be explicitly set if we're using hard-coded
3066  * initialization.  But even in the case of using Firmware Configuration
3067  * Files, we'd like to expose the ability to change these via module
3068  * parameters so these are essentially common tweaks/settings for
3069  * Configuration Files and hard-coded initialization ...
3070  */
3071 static int adap_init0_tweaks(struct adapter *adapter)
3072 {
3073 	/*
3074 	 * Fix up various Host-Dependent Parameters like Page Size, Cache
3075 	 * Line Size, etc.  The firmware default is for a 4KB Page Size and
3076 	 * 64B Cache Line Size ...
3077 	 */
3078 	t4_fixup_host_params(adapter, PAGE_SIZE, L1_CACHE_BYTES);
3079 
3080 	/*
3081 	 * Process module parameters which affect early initialization.
3082 	 */
3083 	if (rx_dma_offset != 2 && rx_dma_offset != 0) {
3084 		dev_err(&adapter->pdev->dev,
3085 			"Ignoring illegal rx_dma_offset=%d, using 2\n",
3086 			rx_dma_offset);
3087 		rx_dma_offset = 2;
3088 	}
3089 	t4_set_reg_field(adapter, SGE_CONTROL_A,
3090 			 PKTSHIFT_V(PKTSHIFT_M),
3091 			 PKTSHIFT_V(rx_dma_offset));
3092 
3093 	/*
3094 	 * Don't include the "IP Pseudo Header" in CPL_RX_PKT checksums: Linux
3095 	 * adds the pseudo header itself.
3096 	 */
3097 	t4_tp_wr_bits_indirect(adapter, TP_INGRESS_CONFIG_A,
3098 			       CSUM_HAS_PSEUDO_HDR_F, 0);
3099 
3100 	return 0;
3101 }
3102 
3103 /* 10Gb/s-BT PHY Support. chip-external 10Gb/s-BT PHYs are complex chips
3104  * unto themselves and they contain their own firmware to perform their
3105  * tasks ...
3106  */
3107 static int phy_aq1202_version(const u8 *phy_fw_data,
3108 			      size_t phy_fw_size)
3109 {
3110 	int offset;
3111 
3112 	/* At offset 0x8 you're looking for the primary image's
3113 	 * starting offset which is 3 Bytes wide
3114 	 *
3115 	 * At offset 0xa of the primary image, you look for the offset
3116 	 * of the DRAM segment which is 3 Bytes wide.
3117 	 *
3118 	 * The FW version is at offset 0x27e of the DRAM and is 2 Bytes
3119 	 * wide
3120 	 */
3121 	#define be16(__p) (((__p)[0] << 8) | (__p)[1])
3122 	#define le16(__p) ((__p)[0] | ((__p)[1] << 8))
3123 	#define le24(__p) (le16(__p) | ((__p)[2] << 16))
3124 
3125 	offset = le24(phy_fw_data + 0x8) << 12;
3126 	offset = le24(phy_fw_data + offset + 0xa);
3127 	return be16(phy_fw_data + offset + 0x27e);
3128 
3129 	#undef be16
3130 	#undef le16
3131 	#undef le24
3132 }
3133 
3134 static struct info_10gbt_phy_fw {
3135 	unsigned int phy_fw_id;		/* PCI Device ID */
3136 	char *phy_fw_file;		/* /lib/firmware/ PHY Firmware file */
3137 	int (*phy_fw_version)(const u8 *phy_fw_data, size_t phy_fw_size);
3138 	int phy_flash;			/* Has FLASH for PHY Firmware */
3139 } phy_info_array[] = {
3140 	{
3141 		PHY_AQ1202_DEVICEID,
3142 		PHY_AQ1202_FIRMWARE,
3143 		phy_aq1202_version,
3144 		1,
3145 	},
3146 	{
3147 		PHY_BCM84834_DEVICEID,
3148 		PHY_BCM84834_FIRMWARE,
3149 		NULL,
3150 		0,
3151 	},
3152 	{ 0, NULL, NULL },
3153 };
3154 
3155 static struct info_10gbt_phy_fw *find_phy_info(int devid)
3156 {
3157 	int i;
3158 
3159 	for (i = 0; i < ARRAY_SIZE(phy_info_array); i++) {
3160 		if (phy_info_array[i].phy_fw_id == devid)
3161 			return &phy_info_array[i];
3162 	}
3163 	return NULL;
3164 }
3165 
3166 /* Handle updating of chip-external 10Gb/s-BT PHY firmware.  This needs to
3167  * happen after the FW_RESET_CMD but before the FW_INITIALIZE_CMD.  On error
3168  * we return a negative error number.  If we transfer new firmware we return 1
3169  * (from t4_load_phy_fw()).  If we don't do anything we return 0.
3170  */
3171 static int adap_init0_phy(struct adapter *adap)
3172 {
3173 	const struct firmware *phyf;
3174 	int ret;
3175 	struct info_10gbt_phy_fw *phy_info;
3176 
3177 	/* Use the device ID to determine which PHY file to flash.
3178 	 */
3179 	phy_info = find_phy_info(adap->pdev->device);
3180 	if (!phy_info) {
3181 		dev_warn(adap->pdev_dev,
3182 			 "No PHY Firmware file found for this PHY\n");
3183 		return -EOPNOTSUPP;
3184 	}
3185 
3186 	/* If we have a T4 PHY firmware file under /lib/firmware/cxgb4/, then
3187 	 * use that. The adapter firmware provides us with a memory buffer
3188 	 * where we can load a PHY firmware file from the host if we want to
3189 	 * override the PHY firmware File in flash.
3190 	 */
3191 	ret = request_firmware_direct(&phyf, phy_info->phy_fw_file,
3192 				      adap->pdev_dev);
3193 	if (ret < 0) {
3194 		/* For adapters without FLASH attached to PHY for their
3195 		 * firmware, it's obviously a fatal error if we can't get the
3196 		 * firmware to the adapter.  For adapters with PHY firmware
3197 		 * FLASH storage, it's worth a warning if we can't find the
3198 		 * PHY Firmware but we'll neuter the error ...
3199 		 */
3200 		dev_err(adap->pdev_dev, "unable to find PHY Firmware image "
3201 			"/lib/firmware/%s, error %d\n",
3202 			phy_info->phy_fw_file, -ret);
3203 		if (phy_info->phy_flash) {
3204 			int cur_phy_fw_ver = 0;
3205 
3206 			t4_phy_fw_ver(adap, &cur_phy_fw_ver);
3207 			dev_warn(adap->pdev_dev, "continuing with, on-adapter "
3208 				 "FLASH copy, version %#x\n", cur_phy_fw_ver);
3209 			ret = 0;
3210 		}
3211 
3212 		return ret;
3213 	}
3214 
3215 	/* Load PHY Firmware onto adapter.
3216 	 */
3217 	ret = t4_load_phy_fw(adap, MEMWIN_NIC, &adap->win0_lock,
3218 			     phy_info->phy_fw_version,
3219 			     (u8 *)phyf->data, phyf->size);
3220 	if (ret < 0)
3221 		dev_err(adap->pdev_dev, "PHY Firmware transfer error %d\n",
3222 			-ret);
3223 	else if (ret > 0) {
3224 		int new_phy_fw_ver = 0;
3225 
3226 		if (phy_info->phy_fw_version)
3227 			new_phy_fw_ver = phy_info->phy_fw_version(phyf->data,
3228 								  phyf->size);
3229 		dev_info(adap->pdev_dev, "Successfully transferred PHY "
3230 			 "Firmware /lib/firmware/%s, version %#x\n",
3231 			 phy_info->phy_fw_file, new_phy_fw_ver);
3232 	}
3233 
3234 	release_firmware(phyf);
3235 
3236 	return ret;
3237 }
3238 
3239 /*
3240  * Attempt to initialize the adapter via a Firmware Configuration File.
3241  */
3242 static int adap_init0_config(struct adapter *adapter, int reset)
3243 {
3244 	struct fw_caps_config_cmd caps_cmd;
3245 	const struct firmware *cf;
3246 	unsigned long mtype = 0, maddr = 0;
3247 	u32 finiver, finicsum, cfcsum;
3248 	int ret;
3249 	int config_issued = 0;
3250 	char *fw_config_file, fw_config_file_path[256];
3251 	char *config_name = NULL;
3252 
3253 	/*
3254 	 * Reset device if necessary.
3255 	 */
3256 	if (reset) {
3257 		ret = t4_fw_reset(adapter, adapter->mbox,
3258 				  PIORSTMODE_F | PIORST_F);
3259 		if (ret < 0)
3260 			goto bye;
3261 	}
3262 
3263 	/* If this is a 10Gb/s-BT adapter make sure the chip-external
3264 	 * 10Gb/s-BT PHYs have up-to-date firmware.  Note that this step needs
3265 	 * to be performed after any global adapter RESET above since some
3266 	 * PHYs only have local RAM copies of the PHY firmware.
3267 	 */
3268 	if (is_10gbt_device(adapter->pdev->device)) {
3269 		ret = adap_init0_phy(adapter);
3270 		if (ret < 0)
3271 			goto bye;
3272 	}
3273 	/*
3274 	 * If we have a T4 configuration file under /lib/firmware/cxgb4/,
3275 	 * then use that.  Otherwise, use the configuration file stored
3276 	 * in the adapter flash ...
3277 	 */
3278 	switch (CHELSIO_CHIP_VERSION(adapter->params.chip)) {
3279 	case CHELSIO_T4:
3280 		fw_config_file = FW4_CFNAME;
3281 		break;
3282 	case CHELSIO_T5:
3283 		fw_config_file = FW5_CFNAME;
3284 		break;
3285 	case CHELSIO_T6:
3286 		fw_config_file = FW6_CFNAME;
3287 		break;
3288 	default:
3289 		dev_err(adapter->pdev_dev, "Device %d is not supported\n",
3290 		       adapter->pdev->device);
3291 		ret = -EINVAL;
3292 		goto bye;
3293 	}
3294 
3295 	ret = request_firmware(&cf, fw_config_file, adapter->pdev_dev);
3296 	if (ret < 0) {
3297 		config_name = "On FLASH";
3298 		mtype = FW_MEMTYPE_CF_FLASH;
3299 		maddr = t4_flash_cfg_addr(adapter);
3300 	} else {
3301 		u32 params[7], val[7];
3302 
3303 		sprintf(fw_config_file_path,
3304 			"/lib/firmware/%s", fw_config_file);
3305 		config_name = fw_config_file_path;
3306 
3307 		if (cf->size >= FLASH_CFG_MAX_SIZE)
3308 			ret = -ENOMEM;
3309 		else {
3310 			params[0] = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
3311 			     FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_CF));
3312 			ret = t4_query_params(adapter, adapter->mbox,
3313 					      adapter->pf, 0, 1, params, val);
3314 			if (ret == 0) {
3315 				/*
3316 				 * For t4_memory_rw() below addresses and
3317 				 * sizes have to be in terms of multiples of 4
3318 				 * bytes.  So, if the Configuration File isn't
3319 				 * a multiple of 4 bytes in length we'll have
3320 				 * to write that out separately since we can't
3321 				 * guarantee that the bytes following the
3322 				 * residual byte in the buffer returned by
3323 				 * request_firmware() are zeroed out ...
3324 				 */
3325 				size_t resid = cf->size & 0x3;
3326 				size_t size = cf->size & ~0x3;
3327 				__be32 *data = (__be32 *)cf->data;
3328 
3329 				mtype = FW_PARAMS_PARAM_Y_G(val[0]);
3330 				maddr = FW_PARAMS_PARAM_Z_G(val[0]) << 16;
3331 
3332 				spin_lock(&adapter->win0_lock);
3333 				ret = t4_memory_rw(adapter, 0, mtype, maddr,
3334 						   size, data, T4_MEMORY_WRITE);
3335 				if (ret == 0 && resid != 0) {
3336 					union {
3337 						__be32 word;
3338 						char buf[4];
3339 					} last;
3340 					int i;
3341 
3342 					last.word = data[size >> 2];
3343 					for (i = resid; i < 4; i++)
3344 						last.buf[i] = 0;
3345 					ret = t4_memory_rw(adapter, 0, mtype,
3346 							   maddr + size,
3347 							   4, &last.word,
3348 							   T4_MEMORY_WRITE);
3349 				}
3350 				spin_unlock(&adapter->win0_lock);
3351 			}
3352 		}
3353 
3354 		release_firmware(cf);
3355 		if (ret)
3356 			goto bye;
3357 	}
3358 
3359 	/*
3360 	 * Issue a Capability Configuration command to the firmware to get it
3361 	 * to parse the Configuration File.  We don't use t4_fw_config_file()
3362 	 * because we want the ability to modify various features after we've
3363 	 * processed the configuration file ...
3364 	 */
3365 	memset(&caps_cmd, 0, sizeof(caps_cmd));
3366 	caps_cmd.op_to_write =
3367 		htonl(FW_CMD_OP_V(FW_CAPS_CONFIG_CMD) |
3368 		      FW_CMD_REQUEST_F |
3369 		      FW_CMD_READ_F);
3370 	caps_cmd.cfvalid_to_len16 =
3371 		htonl(FW_CAPS_CONFIG_CMD_CFVALID_F |
3372 		      FW_CAPS_CONFIG_CMD_MEMTYPE_CF_V(mtype) |
3373 		      FW_CAPS_CONFIG_CMD_MEMADDR64K_CF_V(maddr >> 16) |
3374 		      FW_LEN16(caps_cmd));
3375 	ret = t4_wr_mbox(adapter, adapter->mbox, &caps_cmd, sizeof(caps_cmd),
3376 			 &caps_cmd);
3377 
3378 	/* If the CAPS_CONFIG failed with an ENOENT (for a Firmware
3379 	 * Configuration File in FLASH), our last gasp effort is to use the
3380 	 * Firmware Configuration File which is embedded in the firmware.  A
3381 	 * very few early versions of the firmware didn't have one embedded
3382 	 * but we can ignore those.
3383 	 */
3384 	if (ret == -ENOENT) {
3385 		memset(&caps_cmd, 0, sizeof(caps_cmd));
3386 		caps_cmd.op_to_write =
3387 			htonl(FW_CMD_OP_V(FW_CAPS_CONFIG_CMD) |
3388 					FW_CMD_REQUEST_F |
3389 					FW_CMD_READ_F);
3390 		caps_cmd.cfvalid_to_len16 = htonl(FW_LEN16(caps_cmd));
3391 		ret = t4_wr_mbox(adapter, adapter->mbox, &caps_cmd,
3392 				sizeof(caps_cmd), &caps_cmd);
3393 		config_name = "Firmware Default";
3394 	}
3395 
3396 	config_issued = 1;
3397 	if (ret < 0)
3398 		goto bye;
3399 
3400 	finiver = ntohl(caps_cmd.finiver);
3401 	finicsum = ntohl(caps_cmd.finicsum);
3402 	cfcsum = ntohl(caps_cmd.cfcsum);
3403 	if (finicsum != cfcsum)
3404 		dev_warn(adapter->pdev_dev, "Configuration File checksum "\
3405 			 "mismatch: [fini] csum=%#x, computed csum=%#x\n",
3406 			 finicsum, cfcsum);
3407 
3408 	/*
3409 	 * And now tell the firmware to use the configuration we just loaded.
3410 	 */
3411 	caps_cmd.op_to_write =
3412 		htonl(FW_CMD_OP_V(FW_CAPS_CONFIG_CMD) |
3413 		      FW_CMD_REQUEST_F |
3414 		      FW_CMD_WRITE_F);
3415 	caps_cmd.cfvalid_to_len16 = htonl(FW_LEN16(caps_cmd));
3416 	ret = t4_wr_mbox(adapter, adapter->mbox, &caps_cmd, sizeof(caps_cmd),
3417 			 NULL);
3418 	if (ret < 0)
3419 		goto bye;
3420 
3421 	/*
3422 	 * Tweak configuration based on system architecture, module
3423 	 * parameters, etc.
3424 	 */
3425 	ret = adap_init0_tweaks(adapter);
3426 	if (ret < 0)
3427 		goto bye;
3428 
3429 	/*
3430 	 * And finally tell the firmware to initialize itself using the
3431 	 * parameters from the Configuration File.
3432 	 */
3433 	ret = t4_fw_initialize(adapter, adapter->mbox);
3434 	if (ret < 0)
3435 		goto bye;
3436 
3437 	/* Emit Firmware Configuration File information and return
3438 	 * successfully.
3439 	 */
3440 	dev_info(adapter->pdev_dev, "Successfully configured using Firmware "\
3441 		 "Configuration File \"%s\", version %#x, computed checksum %#x\n",
3442 		 config_name, finiver, cfcsum);
3443 	return 0;
3444 
3445 	/*
3446 	 * Something bad happened.  Return the error ...  (If the "error"
3447 	 * is that there's no Configuration File on the adapter we don't
3448 	 * want to issue a warning since this is fairly common.)
3449 	 */
3450 bye:
3451 	if (config_issued && ret != -ENOENT)
3452 		dev_warn(adapter->pdev_dev, "\"%s\" configuration file error %d\n",
3453 			 config_name, -ret);
3454 	return ret;
3455 }
3456 
3457 static struct fw_info fw_info_array[] = {
3458 	{
3459 		.chip = CHELSIO_T4,
3460 		.fs_name = FW4_CFNAME,
3461 		.fw_mod_name = FW4_FNAME,
3462 		.fw_hdr = {
3463 			.chip = FW_HDR_CHIP_T4,
3464 			.fw_ver = __cpu_to_be32(FW_VERSION(T4)),
3465 			.intfver_nic = FW_INTFVER(T4, NIC),
3466 			.intfver_vnic = FW_INTFVER(T4, VNIC),
3467 			.intfver_ri = FW_INTFVER(T4, RI),
3468 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
3469 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
3470 		},
3471 	}, {
3472 		.chip = CHELSIO_T5,
3473 		.fs_name = FW5_CFNAME,
3474 		.fw_mod_name = FW5_FNAME,
3475 		.fw_hdr = {
3476 			.chip = FW_HDR_CHIP_T5,
3477 			.fw_ver = __cpu_to_be32(FW_VERSION(T5)),
3478 			.intfver_nic = FW_INTFVER(T5, NIC),
3479 			.intfver_vnic = FW_INTFVER(T5, VNIC),
3480 			.intfver_ri = FW_INTFVER(T5, RI),
3481 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
3482 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
3483 		},
3484 	}, {
3485 		.chip = CHELSIO_T6,
3486 		.fs_name = FW6_CFNAME,
3487 		.fw_mod_name = FW6_FNAME,
3488 		.fw_hdr = {
3489 			.chip = FW_HDR_CHIP_T6,
3490 			.fw_ver = __cpu_to_be32(FW_VERSION(T6)),
3491 			.intfver_nic = FW_INTFVER(T6, NIC),
3492 			.intfver_vnic = FW_INTFVER(T6, VNIC),
3493 			.intfver_ofld = FW_INTFVER(T6, OFLD),
3494 			.intfver_ri = FW_INTFVER(T6, RI),
3495 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
3496 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
3497 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
3498 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
3499 		},
3500 	}
3501 
3502 };
3503 
3504 static struct fw_info *find_fw_info(int chip)
3505 {
3506 	int i;
3507 
3508 	for (i = 0; i < ARRAY_SIZE(fw_info_array); i++) {
3509 		if (fw_info_array[i].chip == chip)
3510 			return &fw_info_array[i];
3511 	}
3512 	return NULL;
3513 }
3514 
3515 /*
3516  * Phase 0 of initialization: contact FW, obtain config, perform basic init.
3517  */
3518 static int adap_init0(struct adapter *adap)
3519 {
3520 	int ret;
3521 	u32 v, port_vec;
3522 	enum dev_state state;
3523 	u32 params[7], val[7];
3524 	struct fw_caps_config_cmd caps_cmd;
3525 	int reset = 1;
3526 
3527 	/* Grab Firmware Device Log parameters as early as possible so we have
3528 	 * access to it for debugging, etc.
3529 	 */
3530 	ret = t4_init_devlog_params(adap);
3531 	if (ret < 0)
3532 		return ret;
3533 
3534 	/* Contact FW, advertising Master capability */
3535 	ret = t4_fw_hello(adap, adap->mbox, adap->mbox,
3536 			  is_kdump_kernel() ? MASTER_MUST : MASTER_MAY, &state);
3537 	if (ret < 0) {
3538 		dev_err(adap->pdev_dev, "could not connect to FW, error %d\n",
3539 			ret);
3540 		return ret;
3541 	}
3542 	if (ret == adap->mbox)
3543 		adap->flags |= MASTER_PF;
3544 
3545 	/*
3546 	 * If we're the Master PF Driver and the device is uninitialized,
3547 	 * then let's consider upgrading the firmware ...  (We always want
3548 	 * to check the firmware version number in order to A. get it for
3549 	 * later reporting and B. to warn if the currently loaded firmware
3550 	 * is excessively mismatched relative to the driver.)
3551 	 */
3552 	t4_get_fw_version(adap, &adap->params.fw_vers);
3553 	t4_get_bs_version(adap, &adap->params.bs_vers);
3554 	t4_get_tp_version(adap, &adap->params.tp_vers);
3555 	t4_get_exprom_version(adap, &adap->params.er_vers);
3556 
3557 	ret = t4_check_fw_version(adap);
3558 	/* If firmware is too old (not supported by driver) force an update. */
3559 	if (ret)
3560 		state = DEV_STATE_UNINIT;
3561 	if ((adap->flags & MASTER_PF) && state != DEV_STATE_INIT) {
3562 		struct fw_info *fw_info;
3563 		struct fw_hdr *card_fw;
3564 		const struct firmware *fw;
3565 		const u8 *fw_data = NULL;
3566 		unsigned int fw_size = 0;
3567 
3568 		/* This is the firmware whose headers the driver was compiled
3569 		 * against
3570 		 */
3571 		fw_info = find_fw_info(CHELSIO_CHIP_VERSION(adap->params.chip));
3572 		if (fw_info == NULL) {
3573 			dev_err(adap->pdev_dev,
3574 				"unable to get firmware info for chip %d.\n",
3575 				CHELSIO_CHIP_VERSION(adap->params.chip));
3576 			return -EINVAL;
3577 		}
3578 
3579 		/* allocate memory to read the header of the firmware on the
3580 		 * card
3581 		 */
3582 		card_fw = kvzalloc(sizeof(*card_fw), GFP_KERNEL);
3583 
3584 		/* Get FW from from /lib/firmware/ */
3585 		ret = request_firmware(&fw, fw_info->fw_mod_name,
3586 				       adap->pdev_dev);
3587 		if (ret < 0) {
3588 			dev_err(adap->pdev_dev,
3589 				"unable to load firmware image %s, error %d\n",
3590 				fw_info->fw_mod_name, ret);
3591 		} else {
3592 			fw_data = fw->data;
3593 			fw_size = fw->size;
3594 		}
3595 
3596 		/* upgrade FW logic */
3597 		ret = t4_prep_fw(adap, fw_info, fw_data, fw_size, card_fw,
3598 				 state, &reset);
3599 
3600 		/* Cleaning up */
3601 		release_firmware(fw);
3602 		kvfree(card_fw);
3603 
3604 		if (ret < 0)
3605 			goto bye;
3606 	}
3607 
3608 	/*
3609 	 * Grab VPD parameters.  This should be done after we establish a
3610 	 * connection to the firmware since some of the VPD parameters
3611 	 * (notably the Core Clock frequency) are retrieved via requests to
3612 	 * the firmware.  On the other hand, we need these fairly early on
3613 	 * so we do this right after getting ahold of the firmware.
3614 	 */
3615 	ret = t4_get_vpd_params(adap, &adap->params.vpd);
3616 	if (ret < 0)
3617 		goto bye;
3618 
3619 	/*
3620 	 * Find out what ports are available to us.  Note that we need to do
3621 	 * this before calling adap_init0_no_config() since it needs nports
3622 	 * and portvec ...
3623 	 */
3624 	v =
3625 	    FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
3626 	    FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_PORTVEC);
3627 	ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 1, &v, &port_vec);
3628 	if (ret < 0)
3629 		goto bye;
3630 
3631 	adap->params.nports = hweight32(port_vec);
3632 	adap->params.portvec = port_vec;
3633 
3634 	/* If the firmware is initialized already, emit a simply note to that
3635 	 * effect. Otherwise, it's time to try initializing the adapter.
3636 	 */
3637 	if (state == DEV_STATE_INIT) {
3638 		dev_info(adap->pdev_dev, "Coming up as %s: "\
3639 			 "Adapter already initialized\n",
3640 			 adap->flags & MASTER_PF ? "MASTER" : "SLAVE");
3641 	} else {
3642 		dev_info(adap->pdev_dev, "Coming up as MASTER: "\
3643 			 "Initializing adapter\n");
3644 
3645 		/* Find out whether we're dealing with a version of the
3646 		 * firmware which has configuration file support.
3647 		 */
3648 		params[0] = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
3649 			     FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_CF));
3650 		ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 1,
3651 				      params, val);
3652 
3653 		/* If the firmware doesn't support Configuration Files,
3654 		 * return an error.
3655 		 */
3656 		if (ret < 0) {
3657 			dev_err(adap->pdev_dev, "firmware doesn't support "
3658 				"Firmware Configuration Files\n");
3659 			goto bye;
3660 		}
3661 
3662 		/* The firmware provides us with a memory buffer where we can
3663 		 * load a Configuration File from the host if we want to
3664 		 * override the Configuration File in flash.
3665 		 */
3666 		ret = adap_init0_config(adap, reset);
3667 		if (ret == -ENOENT) {
3668 			dev_err(adap->pdev_dev, "no Configuration File "
3669 				"present on adapter.\n");
3670 			goto bye;
3671 		}
3672 		if (ret < 0) {
3673 			dev_err(adap->pdev_dev, "could not initialize "
3674 				"adapter, error %d\n", -ret);
3675 			goto bye;
3676 		}
3677 	}
3678 
3679 	/* Give the SGE code a chance to pull in anything that it needs ...
3680 	 * Note that this must be called after we retrieve our VPD parameters
3681 	 * in order to know how to convert core ticks to seconds, etc.
3682 	 */
3683 	ret = t4_sge_init(adap);
3684 	if (ret < 0)
3685 		goto bye;
3686 
3687 	if (is_bypass_device(adap->pdev->device))
3688 		adap->params.bypass = 1;
3689 
3690 	/*
3691 	 * Grab some of our basic fundamental operating parameters.
3692 	 */
3693 #define FW_PARAM_DEV(param) \
3694 	(FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) | \
3695 	FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_##param))
3696 
3697 #define FW_PARAM_PFVF(param) \
3698 	FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_PFVF) | \
3699 	FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_PFVF_##param)|  \
3700 	FW_PARAMS_PARAM_Y_V(0) | \
3701 	FW_PARAMS_PARAM_Z_V(0)
3702 
3703 	params[0] = FW_PARAM_PFVF(EQ_START);
3704 	params[1] = FW_PARAM_PFVF(L2T_START);
3705 	params[2] = FW_PARAM_PFVF(L2T_END);
3706 	params[3] = FW_PARAM_PFVF(FILTER_START);
3707 	params[4] = FW_PARAM_PFVF(FILTER_END);
3708 	params[5] = FW_PARAM_PFVF(IQFLINT_START);
3709 	ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 6, params, val);
3710 	if (ret < 0)
3711 		goto bye;
3712 	adap->sge.egr_start = val[0];
3713 	adap->l2t_start = val[1];
3714 	adap->l2t_end = val[2];
3715 	adap->tids.ftid_base = val[3];
3716 	adap->tids.nftids = val[4] - val[3] + 1;
3717 	adap->sge.ingr_start = val[5];
3718 
3719 	/* qids (ingress/egress) returned from firmware can be anywhere
3720 	 * in the range from EQ(IQFLINT)_START to EQ(IQFLINT)_END.
3721 	 * Hence driver needs to allocate memory for this range to
3722 	 * store the queue info. Get the highest IQFLINT/EQ index returned
3723 	 * in FW_EQ_*_CMD.alloc command.
3724 	 */
3725 	params[0] = FW_PARAM_PFVF(EQ_END);
3726 	params[1] = FW_PARAM_PFVF(IQFLINT_END);
3727 	ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 2, params, val);
3728 	if (ret < 0)
3729 		goto bye;
3730 	adap->sge.egr_sz = val[0] - adap->sge.egr_start + 1;
3731 	adap->sge.ingr_sz = val[1] - adap->sge.ingr_start + 1;
3732 
3733 	adap->sge.egr_map = kcalloc(adap->sge.egr_sz,
3734 				    sizeof(*adap->sge.egr_map), GFP_KERNEL);
3735 	if (!adap->sge.egr_map) {
3736 		ret = -ENOMEM;
3737 		goto bye;
3738 	}
3739 
3740 	adap->sge.ingr_map = kcalloc(adap->sge.ingr_sz,
3741 				     sizeof(*adap->sge.ingr_map), GFP_KERNEL);
3742 	if (!adap->sge.ingr_map) {
3743 		ret = -ENOMEM;
3744 		goto bye;
3745 	}
3746 
3747 	/* Allocate the memory for the vaious egress queue bitmaps
3748 	 * ie starving_fl, txq_maperr and blocked_fl.
3749 	 */
3750 	adap->sge.starving_fl =	kcalloc(BITS_TO_LONGS(adap->sge.egr_sz),
3751 					sizeof(long), GFP_KERNEL);
3752 	if (!adap->sge.starving_fl) {
3753 		ret = -ENOMEM;
3754 		goto bye;
3755 	}
3756 
3757 	adap->sge.txq_maperr = kcalloc(BITS_TO_LONGS(adap->sge.egr_sz),
3758 				       sizeof(long), GFP_KERNEL);
3759 	if (!adap->sge.txq_maperr) {
3760 		ret = -ENOMEM;
3761 		goto bye;
3762 	}
3763 
3764 #ifdef CONFIG_DEBUG_FS
3765 	adap->sge.blocked_fl = kcalloc(BITS_TO_LONGS(adap->sge.egr_sz),
3766 				       sizeof(long), GFP_KERNEL);
3767 	if (!adap->sge.blocked_fl) {
3768 		ret = -ENOMEM;
3769 		goto bye;
3770 	}
3771 #endif
3772 
3773 	params[0] = FW_PARAM_PFVF(CLIP_START);
3774 	params[1] = FW_PARAM_PFVF(CLIP_END);
3775 	ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 2, params, val);
3776 	if (ret < 0)
3777 		goto bye;
3778 	adap->clipt_start = val[0];
3779 	adap->clipt_end = val[1];
3780 
3781 	/* We don't yet have a PARAMs calls to retrieve the number of Traffic
3782 	 * Classes supported by the hardware/firmware so we hard code it here
3783 	 * for now.
3784 	 */
3785 	adap->params.nsched_cls = is_t4(adap->params.chip) ? 15 : 16;
3786 
3787 	/* query params related to active filter region */
3788 	params[0] = FW_PARAM_PFVF(ACTIVE_FILTER_START);
3789 	params[1] = FW_PARAM_PFVF(ACTIVE_FILTER_END);
3790 	ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 2, params, val);
3791 	/* If Active filter size is set we enable establishing
3792 	 * offload connection through firmware work request
3793 	 */
3794 	if ((val[0] != val[1]) && (ret >= 0)) {
3795 		adap->flags |= FW_OFLD_CONN;
3796 		adap->tids.aftid_base = val[0];
3797 		adap->tids.aftid_end = val[1];
3798 	}
3799 
3800 	/* If we're running on newer firmware, let it know that we're
3801 	 * prepared to deal with encapsulated CPL messages.  Older
3802 	 * firmware won't understand this and we'll just get
3803 	 * unencapsulated messages ...
3804 	 */
3805 	params[0] = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
3806 	val[0] = 1;
3807 	(void)t4_set_params(adap, adap->mbox, adap->pf, 0, 1, params, val);
3808 
3809 	/*
3810 	 * Find out whether we're allowed to use the T5+ ULPTX MEMWRITE DSGL
3811 	 * capability.  Earlier versions of the firmware didn't have the
3812 	 * ULPTX_MEMWRITE_DSGL so we'll interpret a query failure as no
3813 	 * permission to use ULPTX MEMWRITE DSGL.
3814 	 */
3815 	if (is_t4(adap->params.chip)) {
3816 		adap->params.ulptx_memwrite_dsgl = false;
3817 	} else {
3818 		params[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
3819 		ret = t4_query_params(adap, adap->mbox, adap->pf, 0,
3820 				      1, params, val);
3821 		adap->params.ulptx_memwrite_dsgl = (ret == 0 && val[0] != 0);
3822 	}
3823 
3824 	/* See if FW supports FW_RI_FR_NSMR_TPTE_WR work request */
3825 	params[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
3826 	ret = t4_query_params(adap, adap->mbox, adap->pf, 0,
3827 			      1, params, val);
3828 	adap->params.fr_nsmr_tpte_wr_support = (ret == 0 && val[0] != 0);
3829 
3830 	/*
3831 	 * Get device capabilities so we can determine what resources we need
3832 	 * to manage.
3833 	 */
3834 	memset(&caps_cmd, 0, sizeof(caps_cmd));
3835 	caps_cmd.op_to_write = htonl(FW_CMD_OP_V(FW_CAPS_CONFIG_CMD) |
3836 				     FW_CMD_REQUEST_F | FW_CMD_READ_F);
3837 	caps_cmd.cfvalid_to_len16 = htonl(FW_LEN16(caps_cmd));
3838 	ret = t4_wr_mbox(adap, adap->mbox, &caps_cmd, sizeof(caps_cmd),
3839 			 &caps_cmd);
3840 	if (ret < 0)
3841 		goto bye;
3842 
3843 	if (caps_cmd.ofldcaps) {
3844 		/* query offload-related parameters */
3845 		params[0] = FW_PARAM_DEV(NTID);
3846 		params[1] = FW_PARAM_PFVF(SERVER_START);
3847 		params[2] = FW_PARAM_PFVF(SERVER_END);
3848 		params[3] = FW_PARAM_PFVF(TDDP_START);
3849 		params[4] = FW_PARAM_PFVF(TDDP_END);
3850 		params[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
3851 		ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 6,
3852 				      params, val);
3853 		if (ret < 0)
3854 			goto bye;
3855 		adap->tids.ntids = val[0];
3856 		adap->tids.natids = min(adap->tids.ntids / 2, MAX_ATIDS);
3857 		adap->tids.stid_base = val[1];
3858 		adap->tids.nstids = val[2] - val[1] + 1;
3859 		/*
3860 		 * Setup server filter region. Divide the available filter
3861 		 * region into two parts. Regular filters get 1/3rd and server
3862 		 * filters get 2/3rd part. This is only enabled if workarond
3863 		 * path is enabled.
3864 		 * 1. For regular filters.
3865 		 * 2. Server filter: This are special filters which are used
3866 		 * to redirect SYN packets to offload queue.
3867 		 */
3868 		if (adap->flags & FW_OFLD_CONN && !is_bypass(adap)) {
3869 			adap->tids.sftid_base = adap->tids.ftid_base +
3870 					DIV_ROUND_UP(adap->tids.nftids, 3);
3871 			adap->tids.nsftids = adap->tids.nftids -
3872 					 DIV_ROUND_UP(adap->tids.nftids, 3);
3873 			adap->tids.nftids = adap->tids.sftid_base -
3874 						adap->tids.ftid_base;
3875 		}
3876 		adap->vres.ddp.start = val[3];
3877 		adap->vres.ddp.size = val[4] - val[3] + 1;
3878 		adap->params.ofldq_wr_cred = val[5];
3879 
3880 		adap->params.offload = 1;
3881 		adap->num_ofld_uld += 1;
3882 	}
3883 	if (caps_cmd.rdmacaps) {
3884 		params[0] = FW_PARAM_PFVF(STAG_START);
3885 		params[1] = FW_PARAM_PFVF(STAG_END);
3886 		params[2] = FW_PARAM_PFVF(RQ_START);
3887 		params[3] = FW_PARAM_PFVF(RQ_END);
3888 		params[4] = FW_PARAM_PFVF(PBL_START);
3889 		params[5] = FW_PARAM_PFVF(PBL_END);
3890 		ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 6,
3891 				      params, val);
3892 		if (ret < 0)
3893 			goto bye;
3894 		adap->vres.stag.start = val[0];
3895 		adap->vres.stag.size = val[1] - val[0] + 1;
3896 		adap->vres.rq.start = val[2];
3897 		adap->vres.rq.size = val[3] - val[2] + 1;
3898 		adap->vres.pbl.start = val[4];
3899 		adap->vres.pbl.size = val[5] - val[4] + 1;
3900 
3901 		params[0] = FW_PARAM_PFVF(SQRQ_START);
3902 		params[1] = FW_PARAM_PFVF(SQRQ_END);
3903 		params[2] = FW_PARAM_PFVF(CQ_START);
3904 		params[3] = FW_PARAM_PFVF(CQ_END);
3905 		params[4] = FW_PARAM_PFVF(OCQ_START);
3906 		params[5] = FW_PARAM_PFVF(OCQ_END);
3907 		ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 6, params,
3908 				      val);
3909 		if (ret < 0)
3910 			goto bye;
3911 		adap->vres.qp.start = val[0];
3912 		adap->vres.qp.size = val[1] - val[0] + 1;
3913 		adap->vres.cq.start = val[2];
3914 		adap->vres.cq.size = val[3] - val[2] + 1;
3915 		adap->vres.ocq.start = val[4];
3916 		adap->vres.ocq.size = val[5] - val[4] + 1;
3917 
3918 		params[0] = FW_PARAM_DEV(MAXORDIRD_QP);
3919 		params[1] = FW_PARAM_DEV(MAXIRD_ADAPTER);
3920 		ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 2, params,
3921 				      val);
3922 		if (ret < 0) {
3923 			adap->params.max_ordird_qp = 8;
3924 			adap->params.max_ird_adapter = 32 * adap->tids.ntids;
3925 			ret = 0;
3926 		} else {
3927 			adap->params.max_ordird_qp = val[0];
3928 			adap->params.max_ird_adapter = val[1];
3929 		}
3930 		dev_info(adap->pdev_dev,
3931 			 "max_ordird_qp %d max_ird_adapter %d\n",
3932 			 adap->params.max_ordird_qp,
3933 			 adap->params.max_ird_adapter);
3934 		adap->num_ofld_uld += 2;
3935 	}
3936 	if (caps_cmd.iscsicaps) {
3937 		params[0] = FW_PARAM_PFVF(ISCSI_START);
3938 		params[1] = FW_PARAM_PFVF(ISCSI_END);
3939 		ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 2,
3940 				      params, val);
3941 		if (ret < 0)
3942 			goto bye;
3943 		adap->vres.iscsi.start = val[0];
3944 		adap->vres.iscsi.size = val[1] - val[0] + 1;
3945 		/* LIO target and cxgb4i initiaitor */
3946 		adap->num_ofld_uld += 2;
3947 	}
3948 	if (caps_cmd.cryptocaps) {
3949 		/* Should query params here...TODO */
3950 		params[0] = FW_PARAM_PFVF(NCRYPTO_LOOKASIDE);
3951 		ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 2,
3952 				      params, val);
3953 		if (ret < 0) {
3954 			if (ret != -EINVAL)
3955 				goto bye;
3956 		} else {
3957 			adap->vres.ncrypto_fc = val[0];
3958 		}
3959 		adap->params.crypto |= ULP_CRYPTO_LOOKASIDE;
3960 		adap->num_uld += 1;
3961 	}
3962 #undef FW_PARAM_PFVF
3963 #undef FW_PARAM_DEV
3964 
3965 	/* The MTU/MSS Table is initialized by now, so load their values.  If
3966 	 * we're initializing the adapter, then we'll make any modifications
3967 	 * we want to the MTU/MSS Table and also initialize the congestion
3968 	 * parameters.
3969 	 */
3970 	t4_read_mtu_tbl(adap, adap->params.mtus, NULL);
3971 	if (state != DEV_STATE_INIT) {
3972 		int i;
3973 
3974 		/* The default MTU Table contains values 1492 and 1500.
3975 		 * However, for TCP, it's better to have two values which are
3976 		 * a multiple of 8 +/- 4 bytes apart near this popular MTU.
3977 		 * This allows us to have a TCP Data Payload which is a
3978 		 * multiple of 8 regardless of what combination of TCP Options
3979 		 * are in use (always a multiple of 4 bytes) which is
3980 		 * important for performance reasons.  For instance, if no
3981 		 * options are in use, then we have a 20-byte IP header and a
3982 		 * 20-byte TCP header.  In this case, a 1500-byte MSS would
3983 		 * result in a TCP Data Payload of 1500 - 40 == 1460 bytes
3984 		 * which is not a multiple of 8.  So using an MSS of 1488 in
3985 		 * this case results in a TCP Data Payload of 1448 bytes which
3986 		 * is a multiple of 8.  On the other hand, if 12-byte TCP Time
3987 		 * Stamps have been negotiated, then an MTU of 1500 bytes
3988 		 * results in a TCP Data Payload of 1448 bytes which, as
3989 		 * above, is a multiple of 8 bytes ...
3990 		 */
3991 		for (i = 0; i < NMTUS; i++)
3992 			if (adap->params.mtus[i] == 1492) {
3993 				adap->params.mtus[i] = 1488;
3994 				break;
3995 			}
3996 
3997 		t4_load_mtus(adap, adap->params.mtus, adap->params.a_wnd,
3998 			     adap->params.b_wnd);
3999 	}
4000 	t4_init_sge_params(adap);
4001 	adap->flags |= FW_OK;
4002 	t4_init_tp_params(adap);
4003 	return 0;
4004 
4005 	/*
4006 	 * Something bad happened.  If a command timed out or failed with EIO
4007 	 * FW does not operate within its spec or something catastrophic
4008 	 * happened to HW/FW, stop issuing commands.
4009 	 */
4010 bye:
4011 	kfree(adap->sge.egr_map);
4012 	kfree(adap->sge.ingr_map);
4013 	kfree(adap->sge.starving_fl);
4014 	kfree(adap->sge.txq_maperr);
4015 #ifdef CONFIG_DEBUG_FS
4016 	kfree(adap->sge.blocked_fl);
4017 #endif
4018 	if (ret != -ETIMEDOUT && ret != -EIO)
4019 		t4_fw_bye(adap, adap->mbox);
4020 	return ret;
4021 }
4022 
4023 /* EEH callbacks */
4024 
4025 static pci_ers_result_t eeh_err_detected(struct pci_dev *pdev,
4026 					 pci_channel_state_t state)
4027 {
4028 	int i;
4029 	struct adapter *adap = pci_get_drvdata(pdev);
4030 
4031 	if (!adap)
4032 		goto out;
4033 
4034 	rtnl_lock();
4035 	adap->flags &= ~FW_OK;
4036 	notify_ulds(adap, CXGB4_STATE_START_RECOVERY);
4037 	spin_lock(&adap->stats_lock);
4038 	for_each_port(adap, i) {
4039 		struct net_device *dev = adap->port[i];
4040 		if (dev) {
4041 			netif_device_detach(dev);
4042 			netif_carrier_off(dev);
4043 		}
4044 	}
4045 	spin_unlock(&adap->stats_lock);
4046 	disable_interrupts(adap);
4047 	if (adap->flags & FULL_INIT_DONE)
4048 		cxgb_down(adap);
4049 	rtnl_unlock();
4050 	if ((adap->flags & DEV_ENABLED)) {
4051 		pci_disable_device(pdev);
4052 		adap->flags &= ~DEV_ENABLED;
4053 	}
4054 out:	return state == pci_channel_io_perm_failure ?
4055 		PCI_ERS_RESULT_DISCONNECT : PCI_ERS_RESULT_NEED_RESET;
4056 }
4057 
4058 static pci_ers_result_t eeh_slot_reset(struct pci_dev *pdev)
4059 {
4060 	int i, ret;
4061 	struct fw_caps_config_cmd c;
4062 	struct adapter *adap = pci_get_drvdata(pdev);
4063 
4064 	if (!adap) {
4065 		pci_restore_state(pdev);
4066 		pci_save_state(pdev);
4067 		return PCI_ERS_RESULT_RECOVERED;
4068 	}
4069 
4070 	if (!(adap->flags & DEV_ENABLED)) {
4071 		if (pci_enable_device(pdev)) {
4072 			dev_err(&pdev->dev, "Cannot reenable PCI "
4073 					    "device after reset\n");
4074 			return PCI_ERS_RESULT_DISCONNECT;
4075 		}
4076 		adap->flags |= DEV_ENABLED;
4077 	}
4078 
4079 	pci_set_master(pdev);
4080 	pci_restore_state(pdev);
4081 	pci_save_state(pdev);
4082 	pci_cleanup_aer_uncorrect_error_status(pdev);
4083 
4084 	if (t4_wait_dev_ready(adap->regs) < 0)
4085 		return PCI_ERS_RESULT_DISCONNECT;
4086 	if (t4_fw_hello(adap, adap->mbox, adap->pf, MASTER_MUST, NULL) < 0)
4087 		return PCI_ERS_RESULT_DISCONNECT;
4088 	adap->flags |= FW_OK;
4089 	if (adap_init1(adap, &c))
4090 		return PCI_ERS_RESULT_DISCONNECT;
4091 
4092 	for_each_port(adap, i) {
4093 		struct port_info *p = adap2pinfo(adap, i);
4094 
4095 		ret = t4_alloc_vi(adap, adap->mbox, p->tx_chan, adap->pf, 0, 1,
4096 				  NULL, NULL);
4097 		if (ret < 0)
4098 			return PCI_ERS_RESULT_DISCONNECT;
4099 		p->viid = ret;
4100 		p->xact_addr_filt = -1;
4101 	}
4102 
4103 	t4_load_mtus(adap, adap->params.mtus, adap->params.a_wnd,
4104 		     adap->params.b_wnd);
4105 	setup_memwin(adap);
4106 	if (cxgb_up(adap))
4107 		return PCI_ERS_RESULT_DISCONNECT;
4108 	return PCI_ERS_RESULT_RECOVERED;
4109 }
4110 
4111 static void eeh_resume(struct pci_dev *pdev)
4112 {
4113 	int i;
4114 	struct adapter *adap = pci_get_drvdata(pdev);
4115 
4116 	if (!adap)
4117 		return;
4118 
4119 	rtnl_lock();
4120 	for_each_port(adap, i) {
4121 		struct net_device *dev = adap->port[i];
4122 		if (dev) {
4123 			if (netif_running(dev)) {
4124 				link_start(dev);
4125 				cxgb_set_rxmode(dev);
4126 			}
4127 			netif_device_attach(dev);
4128 		}
4129 	}
4130 	rtnl_unlock();
4131 }
4132 
4133 static const struct pci_error_handlers cxgb4_eeh = {
4134 	.error_detected = eeh_err_detected,
4135 	.slot_reset     = eeh_slot_reset,
4136 	.resume         = eeh_resume,
4137 };
4138 
4139 /* Return true if the Link Configuration supports "High Speeds" (those greater
4140  * than 1Gb/s).
4141  */
4142 static inline bool is_x_10g_port(const struct link_config *lc)
4143 {
4144 	unsigned int speeds, high_speeds;
4145 
4146 	speeds = FW_PORT_CAP_SPEED_V(FW_PORT_CAP_SPEED_G(lc->supported));
4147 	high_speeds = speeds & ~(FW_PORT_CAP_SPEED_100M | FW_PORT_CAP_SPEED_1G);
4148 
4149 	return high_speeds != 0;
4150 }
4151 
4152 /*
4153  * Perform default configuration of DMA queues depending on the number and type
4154  * of ports we found and the number of available CPUs.  Most settings can be
4155  * modified by the admin prior to actual use.
4156  */
4157 static void cfg_queues(struct adapter *adap)
4158 {
4159 	struct sge *s = &adap->sge;
4160 	int i = 0, n10g = 0, qidx = 0;
4161 #ifndef CONFIG_CHELSIO_T4_DCB
4162 	int q10g = 0;
4163 #endif
4164 
4165 	/* Reduce memory usage in kdump environment, disable all offload.
4166 	 */
4167 	if (is_kdump_kernel() || (is_uld(adap) && t4_uld_mem_alloc(adap))) {
4168 		adap->params.offload = 0;
4169 		adap->params.crypto = 0;
4170 	}
4171 
4172 	n10g += is_x_10g_port(&adap2pinfo(adap, i)->link_cfg);
4173 #ifdef CONFIG_CHELSIO_T4_DCB
4174 	/* For Data Center Bridging support we need to be able to support up
4175 	 * to 8 Traffic Priorities; each of which will be assigned to its
4176 	 * own TX Queue in order to prevent Head-Of-Line Blocking.
4177 	 */
4178 	if (adap->params.nports * 8 > MAX_ETH_QSETS) {
4179 		dev_err(adap->pdev_dev, "MAX_ETH_QSETS=%d < %d!\n",
4180 			MAX_ETH_QSETS, adap->params.nports * 8);
4181 		BUG_ON(1);
4182 	}
4183 
4184 	for_each_port(adap, i) {
4185 		struct port_info *pi = adap2pinfo(adap, i);
4186 
4187 		pi->first_qset = qidx;
4188 		pi->nqsets = is_kdump_kernel() ? 1 : 8;
4189 		qidx += pi->nqsets;
4190 	}
4191 #else /* !CONFIG_CHELSIO_T4_DCB */
4192 	/*
4193 	 * We default to 1 queue per non-10G port and up to # of cores queues
4194 	 * per 10G port.
4195 	 */
4196 	if (n10g)
4197 		q10g = (MAX_ETH_QSETS - (adap->params.nports - n10g)) / n10g;
4198 	if (q10g > netif_get_num_default_rss_queues())
4199 		q10g = netif_get_num_default_rss_queues();
4200 
4201 	if (is_kdump_kernel())
4202 		q10g = 1;
4203 
4204 	for_each_port(adap, i) {
4205 		struct port_info *pi = adap2pinfo(adap, i);
4206 
4207 		pi->first_qset = qidx;
4208 		pi->nqsets = is_x_10g_port(&pi->link_cfg) ? q10g : 1;
4209 		qidx += pi->nqsets;
4210 	}
4211 #endif /* !CONFIG_CHELSIO_T4_DCB */
4212 
4213 	s->ethqsets = qidx;
4214 	s->max_ethqsets = qidx;   /* MSI-X may lower it later */
4215 
4216 	if (is_uld(adap)) {
4217 		/*
4218 		 * For offload we use 1 queue/channel if all ports are up to 1G,
4219 		 * otherwise we divide all available queues amongst the channels
4220 		 * capped by the number of available cores.
4221 		 */
4222 		if (n10g) {
4223 			i = min_t(int, MAX_OFLD_QSETS, num_online_cpus());
4224 			s->ofldqsets = roundup(i, adap->params.nports);
4225 		} else {
4226 			s->ofldqsets = adap->params.nports;
4227 		}
4228 	}
4229 
4230 	for (i = 0; i < ARRAY_SIZE(s->ethrxq); i++) {
4231 		struct sge_eth_rxq *r = &s->ethrxq[i];
4232 
4233 		init_rspq(adap, &r->rspq, 5, 10, 1024, 64);
4234 		r->fl.size = 72;
4235 	}
4236 
4237 	for (i = 0; i < ARRAY_SIZE(s->ethtxq); i++)
4238 		s->ethtxq[i].q.size = 1024;
4239 
4240 	for (i = 0; i < ARRAY_SIZE(s->ctrlq); i++)
4241 		s->ctrlq[i].q.size = 512;
4242 
4243 	init_rspq(adap, &s->fw_evtq, 0, 1, 1024, 64);
4244 	init_rspq(adap, &s->intrq, 0, 1, 512, 64);
4245 }
4246 
4247 /*
4248  * Reduce the number of Ethernet queues across all ports to at most n.
4249  * n provides at least one queue per port.
4250  */
4251 static void reduce_ethqs(struct adapter *adap, int n)
4252 {
4253 	int i;
4254 	struct port_info *pi;
4255 
4256 	while (n < adap->sge.ethqsets)
4257 		for_each_port(adap, i) {
4258 			pi = adap2pinfo(adap, i);
4259 			if (pi->nqsets > 1) {
4260 				pi->nqsets--;
4261 				adap->sge.ethqsets--;
4262 				if (adap->sge.ethqsets <= n)
4263 					break;
4264 			}
4265 		}
4266 
4267 	n = 0;
4268 	for_each_port(adap, i) {
4269 		pi = adap2pinfo(adap, i);
4270 		pi->first_qset = n;
4271 		n += pi->nqsets;
4272 	}
4273 }
4274 
4275 static int get_msix_info(struct adapter *adap)
4276 {
4277 	struct uld_msix_info *msix_info;
4278 	unsigned int max_ingq = 0;
4279 
4280 	if (is_offload(adap))
4281 		max_ingq += MAX_OFLD_QSETS * adap->num_ofld_uld;
4282 	if (is_pci_uld(adap))
4283 		max_ingq += MAX_OFLD_QSETS * adap->num_uld;
4284 
4285 	if (!max_ingq)
4286 		goto out;
4287 
4288 	msix_info = kcalloc(max_ingq, sizeof(*msix_info), GFP_KERNEL);
4289 	if (!msix_info)
4290 		return -ENOMEM;
4291 
4292 	adap->msix_bmap_ulds.msix_bmap = kcalloc(BITS_TO_LONGS(max_ingq),
4293 						 sizeof(long), GFP_KERNEL);
4294 	if (!adap->msix_bmap_ulds.msix_bmap) {
4295 		kfree(msix_info);
4296 		return -ENOMEM;
4297 	}
4298 	spin_lock_init(&adap->msix_bmap_ulds.lock);
4299 	adap->msix_info_ulds = msix_info;
4300 out:
4301 	return 0;
4302 }
4303 
4304 static void free_msix_info(struct adapter *adap)
4305 {
4306 	if (!(adap->num_uld && adap->num_ofld_uld))
4307 		return;
4308 
4309 	kfree(adap->msix_info_ulds);
4310 	kfree(adap->msix_bmap_ulds.msix_bmap);
4311 }
4312 
4313 /* 2 MSI-X vectors needed for the FW queue and non-data interrupts */
4314 #define EXTRA_VECS 2
4315 
4316 static int enable_msix(struct adapter *adap)
4317 {
4318 	int ofld_need = 0, uld_need = 0;
4319 	int i, j, want, need, allocated;
4320 	struct sge *s = &adap->sge;
4321 	unsigned int nchan = adap->params.nports;
4322 	struct msix_entry *entries;
4323 	int max_ingq = MAX_INGQ;
4324 
4325 	if (is_pci_uld(adap))
4326 		max_ingq += (MAX_OFLD_QSETS * adap->num_uld);
4327 	if (is_offload(adap))
4328 		max_ingq += (MAX_OFLD_QSETS * adap->num_ofld_uld);
4329 	entries = kmalloc(sizeof(*entries) * (max_ingq + 1),
4330 			  GFP_KERNEL);
4331 	if (!entries)
4332 		return -ENOMEM;
4333 
4334 	/* map for msix */
4335 	if (get_msix_info(adap)) {
4336 		adap->params.offload = 0;
4337 		adap->params.crypto = 0;
4338 	}
4339 
4340 	for (i = 0; i < max_ingq + 1; ++i)
4341 		entries[i].entry = i;
4342 
4343 	want = s->max_ethqsets + EXTRA_VECS;
4344 	if (is_offload(adap)) {
4345 		want += adap->num_ofld_uld * s->ofldqsets;
4346 		ofld_need = adap->num_ofld_uld * nchan;
4347 	}
4348 	if (is_pci_uld(adap)) {
4349 		want += adap->num_uld * s->ofldqsets;
4350 		uld_need = adap->num_uld * nchan;
4351 	}
4352 #ifdef CONFIG_CHELSIO_T4_DCB
4353 	/* For Data Center Bridging we need 8 Ethernet TX Priority Queues for
4354 	 * each port.
4355 	 */
4356 	need = 8 * adap->params.nports + EXTRA_VECS + ofld_need + uld_need;
4357 #else
4358 	need = adap->params.nports + EXTRA_VECS + ofld_need + uld_need;
4359 #endif
4360 	allocated = pci_enable_msix_range(adap->pdev, entries, need, want);
4361 	if (allocated < 0) {
4362 		dev_info(adap->pdev_dev, "not enough MSI-X vectors left,"
4363 			 " not using MSI-X\n");
4364 		kfree(entries);
4365 		return allocated;
4366 	}
4367 
4368 	/* Distribute available vectors to the various queue groups.
4369 	 * Every group gets its minimum requirement and NIC gets top
4370 	 * priority for leftovers.
4371 	 */
4372 	i = allocated - EXTRA_VECS - ofld_need - uld_need;
4373 	if (i < s->max_ethqsets) {
4374 		s->max_ethqsets = i;
4375 		if (i < s->ethqsets)
4376 			reduce_ethqs(adap, i);
4377 	}
4378 	if (is_uld(adap)) {
4379 		if (allocated < want)
4380 			s->nqs_per_uld = nchan;
4381 		else
4382 			s->nqs_per_uld = s->ofldqsets;
4383 	}
4384 
4385 	for (i = 0; i < (s->max_ethqsets + EXTRA_VECS); ++i)
4386 		adap->msix_info[i].vec = entries[i].vector;
4387 	if (is_uld(adap)) {
4388 		for (j = 0 ; i < allocated; ++i, j++) {
4389 			adap->msix_info_ulds[j].vec = entries[i].vector;
4390 			adap->msix_info_ulds[j].idx = i;
4391 		}
4392 		adap->msix_bmap_ulds.mapsize = j;
4393 	}
4394 	dev_info(adap->pdev_dev, "%d MSI-X vectors allocated, "
4395 		 "nic %d per uld %d\n",
4396 		 allocated, s->max_ethqsets, s->nqs_per_uld);
4397 
4398 	kfree(entries);
4399 	return 0;
4400 }
4401 
4402 #undef EXTRA_VECS
4403 
4404 static int init_rss(struct adapter *adap)
4405 {
4406 	unsigned int i;
4407 	int err;
4408 
4409 	err = t4_init_rss_mode(adap, adap->mbox);
4410 	if (err)
4411 		return err;
4412 
4413 	for_each_port(adap, i) {
4414 		struct port_info *pi = adap2pinfo(adap, i);
4415 
4416 		pi->rss = kcalloc(pi->rss_size, sizeof(u16), GFP_KERNEL);
4417 		if (!pi->rss)
4418 			return -ENOMEM;
4419 	}
4420 	return 0;
4421 }
4422 
4423 static int cxgb4_get_pcie_dev_link_caps(struct adapter *adap,
4424 					enum pci_bus_speed *speed,
4425 					enum pcie_link_width *width)
4426 {
4427 	u32 lnkcap1, lnkcap2;
4428 	int err1, err2;
4429 
4430 #define  PCIE_MLW_CAP_SHIFT 4   /* start of MLW mask in link capabilities */
4431 
4432 	*speed = PCI_SPEED_UNKNOWN;
4433 	*width = PCIE_LNK_WIDTH_UNKNOWN;
4434 
4435 	err1 = pcie_capability_read_dword(adap->pdev, PCI_EXP_LNKCAP,
4436 					  &lnkcap1);
4437 	err2 = pcie_capability_read_dword(adap->pdev, PCI_EXP_LNKCAP2,
4438 					  &lnkcap2);
4439 	if (!err2 && lnkcap2) { /* PCIe r3.0-compliant */
4440 		if (lnkcap2 & PCI_EXP_LNKCAP2_SLS_8_0GB)
4441 			*speed = PCIE_SPEED_8_0GT;
4442 		else if (lnkcap2 & PCI_EXP_LNKCAP2_SLS_5_0GB)
4443 			*speed = PCIE_SPEED_5_0GT;
4444 		else if (lnkcap2 & PCI_EXP_LNKCAP2_SLS_2_5GB)
4445 			*speed = PCIE_SPEED_2_5GT;
4446 	}
4447 	if (!err1) {
4448 		*width = (lnkcap1 & PCI_EXP_LNKCAP_MLW) >> PCIE_MLW_CAP_SHIFT;
4449 		if (!lnkcap2) { /* pre-r3.0 */
4450 			if (lnkcap1 & PCI_EXP_LNKCAP_SLS_5_0GB)
4451 				*speed = PCIE_SPEED_5_0GT;
4452 			else if (lnkcap1 & PCI_EXP_LNKCAP_SLS_2_5GB)
4453 				*speed = PCIE_SPEED_2_5GT;
4454 		}
4455 	}
4456 
4457 	if (*speed == PCI_SPEED_UNKNOWN || *width == PCIE_LNK_WIDTH_UNKNOWN)
4458 		return err1 ? err1 : err2 ? err2 : -EINVAL;
4459 	return 0;
4460 }
4461 
4462 static void cxgb4_check_pcie_caps(struct adapter *adap)
4463 {
4464 	enum pcie_link_width width, width_cap;
4465 	enum pci_bus_speed speed, speed_cap;
4466 
4467 #define PCIE_SPEED_STR(speed) \
4468 	(speed == PCIE_SPEED_8_0GT ? "8.0GT/s" : \
4469 	 speed == PCIE_SPEED_5_0GT ? "5.0GT/s" : \
4470 	 speed == PCIE_SPEED_2_5GT ? "2.5GT/s" : \
4471 	 "Unknown")
4472 
4473 	if (cxgb4_get_pcie_dev_link_caps(adap, &speed_cap, &width_cap)) {
4474 		dev_warn(adap->pdev_dev,
4475 			 "Unable to determine PCIe device BW capabilities\n");
4476 		return;
4477 	}
4478 
4479 	if (pcie_get_minimum_link(adap->pdev, &speed, &width) ||
4480 	    speed == PCI_SPEED_UNKNOWN || width == PCIE_LNK_WIDTH_UNKNOWN) {
4481 		dev_warn(adap->pdev_dev,
4482 			 "Unable to determine PCI Express bandwidth.\n");
4483 		return;
4484 	}
4485 
4486 	dev_info(adap->pdev_dev, "PCIe link speed is %s, device supports %s\n",
4487 		 PCIE_SPEED_STR(speed), PCIE_SPEED_STR(speed_cap));
4488 	dev_info(adap->pdev_dev, "PCIe link width is x%d, device supports x%d\n",
4489 		 width, width_cap);
4490 	if (speed < speed_cap || width < width_cap)
4491 		dev_info(adap->pdev_dev,
4492 			 "A slot with more lanes and/or higher speed is "
4493 			 "suggested for optimal performance.\n");
4494 }
4495 
4496 /* Dump basic information about the adapter */
4497 static void print_adapter_info(struct adapter *adapter)
4498 {
4499 	/* Device information */
4500 	dev_info(adapter->pdev_dev, "Chelsio %s rev %d\n",
4501 		 adapter->params.vpd.id,
4502 		 CHELSIO_CHIP_RELEASE(adapter->params.chip));
4503 	dev_info(adapter->pdev_dev, "S/N: %s, P/N: %s\n",
4504 		 adapter->params.vpd.sn, adapter->params.vpd.pn);
4505 
4506 	/* Firmware Version */
4507 	if (!adapter->params.fw_vers)
4508 		dev_warn(adapter->pdev_dev, "No firmware loaded\n");
4509 	else
4510 		dev_info(adapter->pdev_dev, "Firmware version: %u.%u.%u.%u\n",
4511 			 FW_HDR_FW_VER_MAJOR_G(adapter->params.fw_vers),
4512 			 FW_HDR_FW_VER_MINOR_G(adapter->params.fw_vers),
4513 			 FW_HDR_FW_VER_MICRO_G(adapter->params.fw_vers),
4514 			 FW_HDR_FW_VER_BUILD_G(adapter->params.fw_vers));
4515 
4516 	/* Bootstrap Firmware Version. (Some adapters don't have Bootstrap
4517 	 * Firmware, so dev_info() is more appropriate here.)
4518 	 */
4519 	if (!adapter->params.bs_vers)
4520 		dev_info(adapter->pdev_dev, "No bootstrap loaded\n");
4521 	else
4522 		dev_info(adapter->pdev_dev, "Bootstrap version: %u.%u.%u.%u\n",
4523 			 FW_HDR_FW_VER_MAJOR_G(adapter->params.bs_vers),
4524 			 FW_HDR_FW_VER_MINOR_G(adapter->params.bs_vers),
4525 			 FW_HDR_FW_VER_MICRO_G(adapter->params.bs_vers),
4526 			 FW_HDR_FW_VER_BUILD_G(adapter->params.bs_vers));
4527 
4528 	/* TP Microcode Version */
4529 	if (!adapter->params.tp_vers)
4530 		dev_warn(adapter->pdev_dev, "No TP Microcode loaded\n");
4531 	else
4532 		dev_info(adapter->pdev_dev,
4533 			 "TP Microcode version: %u.%u.%u.%u\n",
4534 			 FW_HDR_FW_VER_MAJOR_G(adapter->params.tp_vers),
4535 			 FW_HDR_FW_VER_MINOR_G(adapter->params.tp_vers),
4536 			 FW_HDR_FW_VER_MICRO_G(adapter->params.tp_vers),
4537 			 FW_HDR_FW_VER_BUILD_G(adapter->params.tp_vers));
4538 
4539 	/* Expansion ROM version */
4540 	if (!adapter->params.er_vers)
4541 		dev_info(adapter->pdev_dev, "No Expansion ROM loaded\n");
4542 	else
4543 		dev_info(adapter->pdev_dev,
4544 			 "Expansion ROM version: %u.%u.%u.%u\n",
4545 			 FW_HDR_FW_VER_MAJOR_G(adapter->params.er_vers),
4546 			 FW_HDR_FW_VER_MINOR_G(adapter->params.er_vers),
4547 			 FW_HDR_FW_VER_MICRO_G(adapter->params.er_vers),
4548 			 FW_HDR_FW_VER_BUILD_G(adapter->params.er_vers));
4549 
4550 	/* Software/Hardware configuration */
4551 	dev_info(adapter->pdev_dev, "Configuration: %sNIC %s, %s capable\n",
4552 		 is_offload(adapter) ? "R" : "",
4553 		 ((adapter->flags & USING_MSIX) ? "MSI-X" :
4554 		  (adapter->flags & USING_MSI) ? "MSI" : ""),
4555 		 is_offload(adapter) ? "Offload" : "non-Offload");
4556 }
4557 
4558 static void print_port_info(const struct net_device *dev)
4559 {
4560 	char buf[80];
4561 	char *bufp = buf;
4562 	const char *spd = "";
4563 	const struct port_info *pi = netdev_priv(dev);
4564 	const struct adapter *adap = pi->adapter;
4565 
4566 	if (adap->params.pci.speed == PCI_EXP_LNKSTA_CLS_2_5GB)
4567 		spd = " 2.5 GT/s";
4568 	else if (adap->params.pci.speed == PCI_EXP_LNKSTA_CLS_5_0GB)
4569 		spd = " 5 GT/s";
4570 	else if (adap->params.pci.speed == PCI_EXP_LNKSTA_CLS_8_0GB)
4571 		spd = " 8 GT/s";
4572 
4573 	if (pi->link_cfg.supported & FW_PORT_CAP_SPEED_100M)
4574 		bufp += sprintf(bufp, "100M/");
4575 	if (pi->link_cfg.supported & FW_PORT_CAP_SPEED_1G)
4576 		bufp += sprintf(bufp, "1G/");
4577 	if (pi->link_cfg.supported & FW_PORT_CAP_SPEED_10G)
4578 		bufp += sprintf(bufp, "10G/");
4579 	if (pi->link_cfg.supported & FW_PORT_CAP_SPEED_25G)
4580 		bufp += sprintf(bufp, "25G/");
4581 	if (pi->link_cfg.supported & FW_PORT_CAP_SPEED_40G)
4582 		bufp += sprintf(bufp, "40G/");
4583 	if (pi->link_cfg.supported & FW_PORT_CAP_SPEED_100G)
4584 		bufp += sprintf(bufp, "100G/");
4585 	if (bufp != buf)
4586 		--bufp;
4587 	sprintf(bufp, "BASE-%s", t4_get_port_type_description(pi->port_type));
4588 
4589 	netdev_info(dev, "%s: Chelsio %s (%s) %s\n",
4590 		    dev->name, adap->params.vpd.id, adap->name, buf);
4591 }
4592 
4593 static void enable_pcie_relaxed_ordering(struct pci_dev *dev)
4594 {
4595 	pcie_capability_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_RELAX_EN);
4596 }
4597 
4598 /*
4599  * Free the following resources:
4600  * - memory used for tables
4601  * - MSI/MSI-X
4602  * - net devices
4603  * - resources FW is holding for us
4604  */
4605 static void free_some_resources(struct adapter *adapter)
4606 {
4607 	unsigned int i;
4608 
4609 	kvfree(adapter->l2t);
4610 	t4_cleanup_sched(adapter);
4611 	kvfree(adapter->tids.tid_tab);
4612 	cxgb4_cleanup_tc_u32(adapter);
4613 	kfree(adapter->sge.egr_map);
4614 	kfree(adapter->sge.ingr_map);
4615 	kfree(adapter->sge.starving_fl);
4616 	kfree(adapter->sge.txq_maperr);
4617 #ifdef CONFIG_DEBUG_FS
4618 	kfree(adapter->sge.blocked_fl);
4619 #endif
4620 	disable_msi(adapter);
4621 
4622 	for_each_port(adapter, i)
4623 		if (adapter->port[i]) {
4624 			struct port_info *pi = adap2pinfo(adapter, i);
4625 
4626 			if (pi->viid != 0)
4627 				t4_free_vi(adapter, adapter->mbox, adapter->pf,
4628 					   0, pi->viid);
4629 			kfree(adap2pinfo(adapter, i)->rss);
4630 			free_netdev(adapter->port[i]);
4631 		}
4632 	if (adapter->flags & FW_OK)
4633 		t4_fw_bye(adapter, adapter->pf);
4634 }
4635 
4636 #define TSO_FLAGS (NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_TSO_ECN)
4637 #define VLAN_FEAT (NETIF_F_SG | NETIF_F_IP_CSUM | TSO_FLAGS | \
4638 		   NETIF_F_IPV6_CSUM | NETIF_F_HIGHDMA)
4639 #define SEGMENT_SIZE 128
4640 
4641 static int get_chip_type(struct pci_dev *pdev, u32 pl_rev)
4642 {
4643 	u16 device_id;
4644 
4645 	/* Retrieve adapter's device ID */
4646 	pci_read_config_word(pdev, PCI_DEVICE_ID, &device_id);
4647 
4648 	switch (device_id >> 12) {
4649 	case CHELSIO_T4:
4650 		return CHELSIO_CHIP_CODE(CHELSIO_T4, pl_rev);
4651 	case CHELSIO_T5:
4652 		return CHELSIO_CHIP_CODE(CHELSIO_T5, pl_rev);
4653 	case CHELSIO_T6:
4654 		return CHELSIO_CHIP_CODE(CHELSIO_T6, pl_rev);
4655 	default:
4656 		dev_err(&pdev->dev, "Device %d is not supported\n",
4657 			device_id);
4658 	}
4659 	return -EINVAL;
4660 }
4661 
4662 #ifdef CONFIG_PCI_IOV
4663 static void dummy_setup(struct net_device *dev)
4664 {
4665 	dev->type = ARPHRD_NONE;
4666 	dev->mtu = 0;
4667 	dev->hard_header_len = 0;
4668 	dev->addr_len = 0;
4669 	dev->tx_queue_len = 0;
4670 	dev->flags |= IFF_NOARP;
4671 	dev->priv_flags |= IFF_NO_QUEUE;
4672 
4673 	/* Initialize the device structure. */
4674 	dev->netdev_ops = &cxgb4_mgmt_netdev_ops;
4675 	dev->ethtool_ops = &cxgb4_mgmt_ethtool_ops;
4676 	dev->needs_free_netdev = true;
4677 }
4678 
4679 static int config_mgmt_dev(struct pci_dev *pdev)
4680 {
4681 	struct adapter *adap = pci_get_drvdata(pdev);
4682 	struct net_device *netdev;
4683 	struct port_info *pi;
4684 	char name[IFNAMSIZ];
4685 	int err;
4686 
4687 	snprintf(name, IFNAMSIZ, "mgmtpf%d%d", adap->adap_idx, adap->pf);
4688 	netdev = alloc_netdev(sizeof(struct port_info), name, NET_NAME_UNKNOWN,
4689 			      dummy_setup);
4690 	if (!netdev)
4691 		return -ENOMEM;
4692 
4693 	pi = netdev_priv(netdev);
4694 	pi->adapter = adap;
4695 	pi->port_id = adap->pf % adap->params.nports;
4696 	SET_NETDEV_DEV(netdev, &pdev->dev);
4697 
4698 	adap->port[0] = netdev;
4699 
4700 	err = register_netdev(adap->port[0]);
4701 	if (err) {
4702 		pr_info("Unable to register VF mgmt netdev %s\n", name);
4703 		free_netdev(adap->port[0]);
4704 		adap->port[0] = NULL;
4705 		return err;
4706 	}
4707 	return 0;
4708 }
4709 
4710 static int cxgb4_iov_configure(struct pci_dev *pdev, int num_vfs)
4711 {
4712 	struct adapter *adap = pci_get_drvdata(pdev);
4713 	int err = 0;
4714 	int current_vfs = pci_num_vf(pdev);
4715 	u32 pcie_fw;
4716 
4717 	pcie_fw = readl(adap->regs + PCIE_FW_A);
4718 	/* Check if cxgb4 is the MASTER and fw is initialized */
4719 	if (!(pcie_fw & PCIE_FW_INIT_F) ||
4720 	    !(pcie_fw & PCIE_FW_MASTER_VLD_F) ||
4721 	    PCIE_FW_MASTER_G(pcie_fw) != 4) {
4722 		dev_warn(&pdev->dev,
4723 			 "cxgb4 driver needs to be MASTER to support SRIOV\n");
4724 		return -EOPNOTSUPP;
4725 	}
4726 
4727 	/* If any of the VF's is already assigned to Guest OS, then
4728 	 * SRIOV for the same cannot be modified
4729 	 */
4730 	if (current_vfs && pci_vfs_assigned(pdev)) {
4731 		dev_err(&pdev->dev,
4732 			"Cannot modify SR-IOV while VFs are assigned\n");
4733 		num_vfs = current_vfs;
4734 		return num_vfs;
4735 	}
4736 
4737 	/* Disable SRIOV when zero is passed.
4738 	 * One needs to disable SRIOV before modifying it, else
4739 	 * stack throws the below warning:
4740 	 * " 'n' VFs already enabled. Disable before enabling 'm' VFs."
4741 	 */
4742 	if (!num_vfs) {
4743 		pci_disable_sriov(pdev);
4744 		if (adap->port[0]) {
4745 			unregister_netdev(adap->port[0]);
4746 			adap->port[0] = NULL;
4747 		}
4748 		/* free VF resources */
4749 		kfree(adap->vfinfo);
4750 		adap->vfinfo = NULL;
4751 		adap->num_vfs = 0;
4752 		return num_vfs;
4753 	}
4754 
4755 	if (num_vfs != current_vfs) {
4756 		err = pci_enable_sriov(pdev, num_vfs);
4757 		if (err)
4758 			return err;
4759 
4760 		adap->num_vfs = num_vfs;
4761 		err = config_mgmt_dev(pdev);
4762 		if (err)
4763 			return err;
4764 	}
4765 
4766 	adap->vfinfo = kcalloc(adap->num_vfs,
4767 			       sizeof(struct vf_info), GFP_KERNEL);
4768 	if (adap->vfinfo)
4769 		fill_vf_station_mac_addr(adap);
4770 	return num_vfs;
4771 }
4772 #endif
4773 
4774 static int init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
4775 {
4776 	int func, i, err, s_qpp, qpp, num_seg;
4777 	struct port_info *pi;
4778 	bool highdma = false;
4779 	struct adapter *adapter = NULL;
4780 	struct net_device *netdev;
4781 	void __iomem *regs;
4782 	u32 whoami, pl_rev;
4783 	enum chip_type chip;
4784 	static int adap_idx = 1;
4785 #ifdef CONFIG_PCI_IOV
4786 	u32 v, port_vec;
4787 #endif
4788 
4789 	printk_once(KERN_INFO "%s - version %s\n", DRV_DESC, DRV_VERSION);
4790 
4791 	err = pci_request_regions(pdev, KBUILD_MODNAME);
4792 	if (err) {
4793 		/* Just info, some other driver may have claimed the device. */
4794 		dev_info(&pdev->dev, "cannot obtain PCI resources\n");
4795 		return err;
4796 	}
4797 
4798 	err = pci_enable_device(pdev);
4799 	if (err) {
4800 		dev_err(&pdev->dev, "cannot enable PCI device\n");
4801 		goto out_release_regions;
4802 	}
4803 
4804 	regs = pci_ioremap_bar(pdev, 0);
4805 	if (!regs) {
4806 		dev_err(&pdev->dev, "cannot map device registers\n");
4807 		err = -ENOMEM;
4808 		goto out_disable_device;
4809 	}
4810 
4811 	err = t4_wait_dev_ready(regs);
4812 	if (err < 0)
4813 		goto out_unmap_bar0;
4814 
4815 	/* We control everything through one PF */
4816 	whoami = readl(regs + PL_WHOAMI_A);
4817 	pl_rev = REV_G(readl(regs + PL_REV_A));
4818 	chip = get_chip_type(pdev, pl_rev);
4819 	func = CHELSIO_CHIP_VERSION(chip) <= CHELSIO_T5 ?
4820 		SOURCEPF_G(whoami) : T6_SOURCEPF_G(whoami);
4821 	if (func != ent->driver_data) {
4822 #ifndef CONFIG_PCI_IOV
4823 		iounmap(regs);
4824 #endif
4825 		pci_disable_device(pdev);
4826 		pci_save_state(pdev);        /* to restore SR-IOV later */
4827 		goto sriov;
4828 	}
4829 
4830 	if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
4831 		highdma = true;
4832 		err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
4833 		if (err) {
4834 			dev_err(&pdev->dev, "unable to obtain 64-bit DMA for "
4835 				"coherent allocations\n");
4836 			goto out_unmap_bar0;
4837 		}
4838 	} else {
4839 		err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
4840 		if (err) {
4841 			dev_err(&pdev->dev, "no usable DMA configuration\n");
4842 			goto out_unmap_bar0;
4843 		}
4844 	}
4845 
4846 	pci_enable_pcie_error_reporting(pdev);
4847 	enable_pcie_relaxed_ordering(pdev);
4848 	pci_set_master(pdev);
4849 	pci_save_state(pdev);
4850 
4851 	adapter = kzalloc(sizeof(*adapter), GFP_KERNEL);
4852 	if (!adapter) {
4853 		err = -ENOMEM;
4854 		goto out_unmap_bar0;
4855 	}
4856 	adap_idx++;
4857 
4858 	adapter->workq = create_singlethread_workqueue("cxgb4");
4859 	if (!adapter->workq) {
4860 		err = -ENOMEM;
4861 		goto out_free_adapter;
4862 	}
4863 
4864 	adapter->mbox_log = kzalloc(sizeof(*adapter->mbox_log) +
4865 				    (sizeof(struct mbox_cmd) *
4866 				     T4_OS_LOG_MBOX_CMDS),
4867 				    GFP_KERNEL);
4868 	if (!adapter->mbox_log) {
4869 		err = -ENOMEM;
4870 		goto out_free_adapter;
4871 	}
4872 	adapter->mbox_log->size = T4_OS_LOG_MBOX_CMDS;
4873 
4874 	/* PCI device has been enabled */
4875 	adapter->flags |= DEV_ENABLED;
4876 
4877 	adapter->regs = regs;
4878 	adapter->pdev = pdev;
4879 	adapter->pdev_dev = &pdev->dev;
4880 	adapter->name = pci_name(pdev);
4881 	adapter->mbox = func;
4882 	adapter->pf = func;
4883 	adapter->msg_enable = DFLT_MSG_ENABLE;
4884 	memset(adapter->chan_map, 0xff, sizeof(adapter->chan_map));
4885 
4886 	spin_lock_init(&adapter->stats_lock);
4887 	spin_lock_init(&adapter->tid_release_lock);
4888 	spin_lock_init(&adapter->win0_lock);
4889 	spin_lock_init(&adapter->mbox_lock);
4890 
4891 	INIT_LIST_HEAD(&adapter->mlist.list);
4892 
4893 	INIT_WORK(&adapter->tid_release_task, process_tid_release_list);
4894 	INIT_WORK(&adapter->db_full_task, process_db_full);
4895 	INIT_WORK(&adapter->db_drop_task, process_db_drop);
4896 
4897 	err = t4_prep_adapter(adapter);
4898 	if (err)
4899 		goto out_free_adapter;
4900 
4901 
4902 	if (!is_t4(adapter->params.chip)) {
4903 		s_qpp = (QUEUESPERPAGEPF0_S +
4904 			(QUEUESPERPAGEPF1_S - QUEUESPERPAGEPF0_S) *
4905 			adapter->pf);
4906 		qpp = 1 << QUEUESPERPAGEPF0_G(t4_read_reg(adapter,
4907 		      SGE_EGRESS_QUEUES_PER_PAGE_PF_A) >> s_qpp);
4908 		num_seg = PAGE_SIZE / SEGMENT_SIZE;
4909 
4910 		/* Each segment size is 128B. Write coalescing is enabled only
4911 		 * when SGE_EGRESS_QUEUES_PER_PAGE_PF reg value for the
4912 		 * queue is less no of segments that can be accommodated in
4913 		 * a page size.
4914 		 */
4915 		if (qpp > num_seg) {
4916 			dev_err(&pdev->dev,
4917 				"Incorrect number of egress queues per page\n");
4918 			err = -EINVAL;
4919 			goto out_free_adapter;
4920 		}
4921 		adapter->bar2 = ioremap_wc(pci_resource_start(pdev, 2),
4922 		pci_resource_len(pdev, 2));
4923 		if (!adapter->bar2) {
4924 			dev_err(&pdev->dev, "cannot map device bar2 region\n");
4925 			err = -ENOMEM;
4926 			goto out_free_adapter;
4927 		}
4928 	}
4929 
4930 	setup_memwin(adapter);
4931 	err = adap_init0(adapter);
4932 #ifdef CONFIG_DEBUG_FS
4933 	bitmap_zero(adapter->sge.blocked_fl, adapter->sge.egr_sz);
4934 #endif
4935 	setup_memwin_rdma(adapter);
4936 	if (err)
4937 		goto out_unmap_bar;
4938 
4939 	/* configure SGE_STAT_CFG_A to read WC stats */
4940 	if (!is_t4(adapter->params.chip))
4941 		t4_write_reg(adapter, SGE_STAT_CFG_A, STATSOURCE_T5_V(7) |
4942 			     (is_t5(adapter->params.chip) ? STATMODE_V(0) :
4943 			      T6_STATMODE_V(0)));
4944 
4945 	for_each_port(adapter, i) {
4946 		netdev = alloc_etherdev_mq(sizeof(struct port_info),
4947 					   MAX_ETH_QSETS);
4948 		if (!netdev) {
4949 			err = -ENOMEM;
4950 			goto out_free_dev;
4951 		}
4952 
4953 		SET_NETDEV_DEV(netdev, &pdev->dev);
4954 
4955 		adapter->port[i] = netdev;
4956 		pi = netdev_priv(netdev);
4957 		pi->adapter = adapter;
4958 		pi->xact_addr_filt = -1;
4959 		pi->port_id = i;
4960 		netdev->irq = pdev->irq;
4961 
4962 		netdev->hw_features = NETIF_F_SG | TSO_FLAGS |
4963 			NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM |
4964 			NETIF_F_RXCSUM | NETIF_F_RXHASH |
4965 			NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX |
4966 			NETIF_F_HW_TC;
4967 		if (highdma)
4968 			netdev->hw_features |= NETIF_F_HIGHDMA;
4969 		netdev->features |= netdev->hw_features;
4970 		netdev->vlan_features = netdev->features & VLAN_FEAT;
4971 
4972 		netdev->priv_flags |= IFF_UNICAST_FLT;
4973 
4974 		/* MTU range: 81 - 9600 */
4975 		netdev->min_mtu = 81;
4976 		netdev->max_mtu = MAX_MTU;
4977 
4978 		netdev->netdev_ops = &cxgb4_netdev_ops;
4979 #ifdef CONFIG_CHELSIO_T4_DCB
4980 		netdev->dcbnl_ops = &cxgb4_dcb_ops;
4981 		cxgb4_dcb_state_init(netdev);
4982 #endif
4983 		cxgb4_set_ethtool_ops(netdev);
4984 	}
4985 
4986 	pci_set_drvdata(pdev, adapter);
4987 
4988 	if (adapter->flags & FW_OK) {
4989 		err = t4_port_init(adapter, func, func, 0);
4990 		if (err)
4991 			goto out_free_dev;
4992 	} else if (adapter->params.nports == 1) {
4993 		/* If we don't have a connection to the firmware -- possibly
4994 		 * because of an error -- grab the raw VPD parameters so we
4995 		 * can set the proper MAC Address on the debug network
4996 		 * interface that we've created.
4997 		 */
4998 		u8 hw_addr[ETH_ALEN];
4999 		u8 *na = adapter->params.vpd.na;
5000 
5001 		err = t4_get_raw_vpd_params(adapter, &adapter->params.vpd);
5002 		if (!err) {
5003 			for (i = 0; i < ETH_ALEN; i++)
5004 				hw_addr[i] = (hex2val(na[2 * i + 0]) * 16 +
5005 					      hex2val(na[2 * i + 1]));
5006 			t4_set_hw_addr(adapter, 0, hw_addr);
5007 		}
5008 	}
5009 
5010 	/* Configure queues and allocate tables now, they can be needed as
5011 	 * soon as the first register_netdev completes.
5012 	 */
5013 	cfg_queues(adapter);
5014 
5015 	adapter->l2t = t4_init_l2t(adapter->l2t_start, adapter->l2t_end);
5016 	if (!adapter->l2t) {
5017 		/* We tolerate a lack of L2T, giving up some functionality */
5018 		dev_warn(&pdev->dev, "could not allocate L2T, continuing\n");
5019 		adapter->params.offload = 0;
5020 	}
5021 
5022 #if IS_ENABLED(CONFIG_IPV6)
5023 	if ((CHELSIO_CHIP_VERSION(adapter->params.chip) <= CHELSIO_T5) &&
5024 	    (!(t4_read_reg(adapter, LE_DB_CONFIG_A) & ASLIPCOMPEN_F))) {
5025 		/* CLIP functionality is not present in hardware,
5026 		 * hence disable all offload features
5027 		 */
5028 		dev_warn(&pdev->dev,
5029 			 "CLIP not enabled in hardware, continuing\n");
5030 		adapter->params.offload = 0;
5031 	} else {
5032 		adapter->clipt = t4_init_clip_tbl(adapter->clipt_start,
5033 						  adapter->clipt_end);
5034 		if (!adapter->clipt) {
5035 			/* We tolerate a lack of clip_table, giving up
5036 			 * some functionality
5037 			 */
5038 			dev_warn(&pdev->dev,
5039 				 "could not allocate Clip table, continuing\n");
5040 			adapter->params.offload = 0;
5041 		}
5042 	}
5043 #endif
5044 
5045 	for_each_port(adapter, i) {
5046 		pi = adap2pinfo(adapter, i);
5047 		pi->sched_tbl = t4_init_sched(adapter->params.nsched_cls);
5048 		if (!pi->sched_tbl)
5049 			dev_warn(&pdev->dev,
5050 				 "could not activate scheduling on port %d\n",
5051 				 i);
5052 	}
5053 
5054 	if (tid_init(&adapter->tids) < 0) {
5055 		dev_warn(&pdev->dev, "could not allocate TID table, "
5056 			 "continuing\n");
5057 		adapter->params.offload = 0;
5058 	} else {
5059 		adapter->tc_u32 = cxgb4_init_tc_u32(adapter);
5060 		if (!adapter->tc_u32)
5061 			dev_warn(&pdev->dev,
5062 				 "could not offload tc u32, continuing\n");
5063 	}
5064 
5065 	if (is_offload(adapter)) {
5066 		if (t4_read_reg(adapter, LE_DB_CONFIG_A) & HASHEN_F) {
5067 			u32 hash_base, hash_reg;
5068 
5069 			if (chip <= CHELSIO_T5) {
5070 				hash_reg = LE_DB_TID_HASHBASE_A;
5071 				hash_base = t4_read_reg(adapter, hash_reg);
5072 				adapter->tids.hash_base = hash_base / 4;
5073 			} else {
5074 				hash_reg = T6_LE_DB_HASH_TID_BASE_A;
5075 				hash_base = t4_read_reg(adapter, hash_reg);
5076 				adapter->tids.hash_base = hash_base;
5077 			}
5078 		}
5079 	}
5080 
5081 	/* See what interrupts we'll be using */
5082 	if (msi > 1 && enable_msix(adapter) == 0)
5083 		adapter->flags |= USING_MSIX;
5084 	else if (msi > 0 && pci_enable_msi(pdev) == 0) {
5085 		adapter->flags |= USING_MSI;
5086 		if (msi > 1)
5087 			free_msix_info(adapter);
5088 	}
5089 
5090 	/* check for PCI Express bandwidth capabiltites */
5091 	cxgb4_check_pcie_caps(adapter);
5092 
5093 	err = init_rss(adapter);
5094 	if (err)
5095 		goto out_free_dev;
5096 
5097 	/*
5098 	 * The card is now ready to go.  If any errors occur during device
5099 	 * registration we do not fail the whole card but rather proceed only
5100 	 * with the ports we manage to register successfully.  However we must
5101 	 * register at least one net device.
5102 	 */
5103 	for_each_port(adapter, i) {
5104 		pi = adap2pinfo(adapter, i);
5105 		adapter->port[i]->dev_port = pi->lport;
5106 		netif_set_real_num_tx_queues(adapter->port[i], pi->nqsets);
5107 		netif_set_real_num_rx_queues(adapter->port[i], pi->nqsets);
5108 
5109 		netif_carrier_off(adapter->port[i]);
5110 
5111 		err = register_netdev(adapter->port[i]);
5112 		if (err)
5113 			break;
5114 		adapter->chan_map[pi->tx_chan] = i;
5115 		print_port_info(adapter->port[i]);
5116 	}
5117 	if (i == 0) {
5118 		dev_err(&pdev->dev, "could not register any net devices\n");
5119 		goto out_free_dev;
5120 	}
5121 	if (err) {
5122 		dev_warn(&pdev->dev, "only %d net devices registered\n", i);
5123 		err = 0;
5124 	}
5125 
5126 	if (cxgb4_debugfs_root) {
5127 		adapter->debugfs_root = debugfs_create_dir(pci_name(pdev),
5128 							   cxgb4_debugfs_root);
5129 		setup_debugfs(adapter);
5130 	}
5131 
5132 	/* PCIe EEH recovery on powerpc platforms needs fundamental reset */
5133 	pdev->needs_freset = 1;
5134 
5135 	if (is_uld(adapter)) {
5136 		mutex_lock(&uld_mutex);
5137 		list_add_tail(&adapter->list_node, &adapter_list);
5138 		mutex_unlock(&uld_mutex);
5139 	}
5140 
5141 	print_adapter_info(adapter);
5142 	setup_fw_sge_queues(adapter);
5143 	return 0;
5144 
5145 sriov:
5146 #ifdef CONFIG_PCI_IOV
5147 	adapter = kzalloc(sizeof(*adapter), GFP_KERNEL);
5148 	if (!adapter) {
5149 		err = -ENOMEM;
5150 		goto free_pci_region;
5151 	}
5152 
5153 	adapter->pdev = pdev;
5154 	adapter->pdev_dev = &pdev->dev;
5155 	adapter->name = pci_name(pdev);
5156 	adapter->mbox = func;
5157 	adapter->pf = func;
5158 	adapter->regs = regs;
5159 	adapter->adap_idx = adap_idx;
5160 	adapter->mbox_log = kzalloc(sizeof(*adapter->mbox_log) +
5161 				    (sizeof(struct mbox_cmd) *
5162 				     T4_OS_LOG_MBOX_CMDS),
5163 				    GFP_KERNEL);
5164 	if (!adapter->mbox_log) {
5165 		err = -ENOMEM;
5166 		goto free_adapter;
5167 	}
5168 	spin_lock_init(&adapter->mbox_lock);
5169 	INIT_LIST_HEAD(&adapter->mlist.list);
5170 
5171 	v = FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
5172 	    FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_PORTVEC);
5173 	err = t4_query_params(adapter, adapter->mbox, adapter->pf, 0, 1,
5174 			      &v, &port_vec);
5175 	if (err < 0) {
5176 		dev_err(adapter->pdev_dev, "Could not fetch port params\n");
5177 		goto free_mbox_log;
5178 	}
5179 
5180 	adapter->params.nports = hweight32(port_vec);
5181 	pci_set_drvdata(pdev, adapter);
5182 	return 0;
5183 
5184 free_mbox_log:
5185 	kfree(adapter->mbox_log);
5186  free_adapter:
5187 	kfree(adapter);
5188  free_pci_region:
5189 	iounmap(regs);
5190 	pci_disable_sriov(pdev);
5191 	pci_release_regions(pdev);
5192 	return err;
5193 #else
5194 	return 0;
5195 #endif
5196 
5197  out_free_dev:
5198 	free_some_resources(adapter);
5199 	if (adapter->flags & USING_MSIX)
5200 		free_msix_info(adapter);
5201 	if (adapter->num_uld || adapter->num_ofld_uld)
5202 		t4_uld_mem_free(adapter);
5203  out_unmap_bar:
5204 	if (!is_t4(adapter->params.chip))
5205 		iounmap(adapter->bar2);
5206  out_free_adapter:
5207 	if (adapter->workq)
5208 		destroy_workqueue(adapter->workq);
5209 
5210 	kfree(adapter->mbox_log);
5211 	kfree(adapter);
5212  out_unmap_bar0:
5213 	iounmap(regs);
5214  out_disable_device:
5215 	pci_disable_pcie_error_reporting(pdev);
5216 	pci_disable_device(pdev);
5217  out_release_regions:
5218 	pci_release_regions(pdev);
5219 	return err;
5220 }
5221 
5222 static void remove_one(struct pci_dev *pdev)
5223 {
5224 	struct adapter *adapter = pci_get_drvdata(pdev);
5225 
5226 	if (!adapter) {
5227 		pci_release_regions(pdev);
5228 		return;
5229 	}
5230 
5231 	if (adapter->pf == 4) {
5232 		int i;
5233 
5234 		/* Tear down per-adapter Work Queue first since it can contain
5235 		 * references to our adapter data structure.
5236 		 */
5237 		destroy_workqueue(adapter->workq);
5238 
5239 		if (is_uld(adapter))
5240 			detach_ulds(adapter);
5241 
5242 		disable_interrupts(adapter);
5243 
5244 		for_each_port(adapter, i)
5245 			if (adapter->port[i]->reg_state == NETREG_REGISTERED)
5246 				unregister_netdev(adapter->port[i]);
5247 
5248 		debugfs_remove_recursive(adapter->debugfs_root);
5249 
5250 		/* If we allocated filters, free up state associated with any
5251 		 * valid filters ...
5252 		 */
5253 		clear_all_filters(adapter);
5254 
5255 		if (adapter->flags & FULL_INIT_DONE)
5256 			cxgb_down(adapter);
5257 
5258 		if (adapter->flags & USING_MSIX)
5259 			free_msix_info(adapter);
5260 		if (adapter->num_uld || adapter->num_ofld_uld)
5261 			t4_uld_mem_free(adapter);
5262 		free_some_resources(adapter);
5263 #if IS_ENABLED(CONFIG_IPV6)
5264 		t4_cleanup_clip_tbl(adapter);
5265 #endif
5266 		iounmap(adapter->regs);
5267 		if (!is_t4(adapter->params.chip))
5268 			iounmap(adapter->bar2);
5269 		pci_disable_pcie_error_reporting(pdev);
5270 		if ((adapter->flags & DEV_ENABLED)) {
5271 			pci_disable_device(pdev);
5272 			adapter->flags &= ~DEV_ENABLED;
5273 		}
5274 		pci_release_regions(pdev);
5275 		kfree(adapter->mbox_log);
5276 		synchronize_rcu();
5277 		kfree(adapter);
5278 	}
5279 #ifdef CONFIG_PCI_IOV
5280 	else {
5281 		if (adapter->port[0])
5282 			unregister_netdev(adapter->port[0]);
5283 		iounmap(adapter->regs);
5284 		kfree(adapter->vfinfo);
5285 		kfree(adapter->mbox_log);
5286 		kfree(adapter);
5287 		pci_disable_sriov(pdev);
5288 		pci_release_regions(pdev);
5289 	}
5290 #endif
5291 }
5292 
5293 /* "Shutdown" quiesces the device, stopping Ingress Packet and Interrupt
5294  * delivery.  This is essentially a stripped down version of the PCI remove()
5295  * function where we do the minimal amount of work necessary to shutdown any
5296  * further activity.
5297  */
5298 static void shutdown_one(struct pci_dev *pdev)
5299 {
5300 	struct adapter *adapter = pci_get_drvdata(pdev);
5301 
5302 	/* As with remove_one() above (see extended comment), we only want do
5303 	 * do cleanup on PCI Devices which went all the way through init_one()
5304 	 * ...
5305 	 */
5306 	if (!adapter) {
5307 		pci_release_regions(pdev);
5308 		return;
5309 	}
5310 
5311 	if (adapter->pf == 4) {
5312 		int i;
5313 
5314 		for_each_port(adapter, i)
5315 			if (adapter->port[i]->reg_state == NETREG_REGISTERED)
5316 				cxgb_close(adapter->port[i]);
5317 
5318 		t4_uld_clean_up(adapter);
5319 		disable_interrupts(adapter);
5320 		disable_msi(adapter);
5321 
5322 		t4_sge_stop(adapter);
5323 		if (adapter->flags & FW_OK)
5324 			t4_fw_bye(adapter, adapter->mbox);
5325 	}
5326 #ifdef CONFIG_PCI_IOV
5327 	else {
5328 		if (adapter->port[0])
5329 			unregister_netdev(adapter->port[0]);
5330 		iounmap(adapter->regs);
5331 		kfree(adapter->vfinfo);
5332 		kfree(adapter->mbox_log);
5333 		kfree(adapter);
5334 		pci_disable_sriov(pdev);
5335 		pci_release_regions(pdev);
5336 	}
5337 #endif
5338 }
5339 
5340 static struct pci_driver cxgb4_driver = {
5341 	.name     = KBUILD_MODNAME,
5342 	.id_table = cxgb4_pci_tbl,
5343 	.probe    = init_one,
5344 	.remove   = remove_one,
5345 	.shutdown = shutdown_one,
5346 #ifdef CONFIG_PCI_IOV
5347 	.sriov_configure = cxgb4_iov_configure,
5348 #endif
5349 	.err_handler = &cxgb4_eeh,
5350 };
5351 
5352 static int __init cxgb4_init_module(void)
5353 {
5354 	int ret;
5355 
5356 	/* Debugfs support is optional, just warn if this fails */
5357 	cxgb4_debugfs_root = debugfs_create_dir(KBUILD_MODNAME, NULL);
5358 	if (!cxgb4_debugfs_root)
5359 		pr_warn("could not create debugfs entry, continuing\n");
5360 
5361 	ret = pci_register_driver(&cxgb4_driver);
5362 	if (ret < 0)
5363 		debugfs_remove(cxgb4_debugfs_root);
5364 
5365 #if IS_ENABLED(CONFIG_IPV6)
5366 	if (!inet6addr_registered) {
5367 		register_inet6addr_notifier(&cxgb4_inet6addr_notifier);
5368 		inet6addr_registered = true;
5369 	}
5370 #endif
5371 
5372 	return ret;
5373 }
5374 
5375 static void __exit cxgb4_cleanup_module(void)
5376 {
5377 #if IS_ENABLED(CONFIG_IPV6)
5378 	if (inet6addr_registered) {
5379 		unregister_inet6addr_notifier(&cxgb4_inet6addr_notifier);
5380 		inet6addr_registered = false;
5381 	}
5382 #endif
5383 	pci_unregister_driver(&cxgb4_driver);
5384 	debugfs_remove(cxgb4_debugfs_root);  /* NULL ok */
5385 }
5386 
5387 module_init(cxgb4_init_module);
5388 module_exit(cxgb4_cleanup_module);
5389