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