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