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