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