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