Documentation: embargoed-hardware-issues.rst: Add myself for Power
[sfrench/cifs-2.6.git] / drivers / scsi / lpfc / lpfc_init.c
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2024 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.  *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23
24 #include <linux/blkdev.h>
25 #include <linux/delay.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/idr.h>
28 #include <linux/interrupt.h>
29 #include <linux/module.h>
30 #include <linux/kthread.h>
31 #include <linux/pci.h>
32 #include <linux/spinlock.h>
33 #include <linux/sched/clock.h>
34 #include <linux/ctype.h>
35 #include <linux/slab.h>
36 #include <linux/firmware.h>
37 #include <linux/miscdevice.h>
38 #include <linux/percpu.h>
39 #include <linux/irq.h>
40 #include <linux/bitops.h>
41 #include <linux/crash_dump.h>
42 #include <linux/cpu.h>
43 #include <linux/cpuhotplug.h>
44
45 #include <scsi/scsi.h>
46 #include <scsi/scsi_device.h>
47 #include <scsi/scsi_host.h>
48 #include <scsi/scsi_transport_fc.h>
49 #include <scsi/scsi_tcq.h>
50 #include <scsi/fc/fc_fs.h>
51
52 #include "lpfc_hw4.h"
53 #include "lpfc_hw.h"
54 #include "lpfc_sli.h"
55 #include "lpfc_sli4.h"
56 #include "lpfc_nl.h"
57 #include "lpfc_disc.h"
58 #include "lpfc.h"
59 #include "lpfc_scsi.h"
60 #include "lpfc_nvme.h"
61 #include "lpfc_logmsg.h"
62 #include "lpfc_crtn.h"
63 #include "lpfc_vport.h"
64 #include "lpfc_version.h"
65 #include "lpfc_ids.h"
66
67 static enum cpuhp_state lpfc_cpuhp_state;
68 /* Used when mapping IRQ vectors in a driver centric manner */
69 static uint32_t lpfc_present_cpu;
70 static bool lpfc_pldv_detect;
71
72 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba);
73 static void lpfc_cpuhp_remove(struct lpfc_hba *phba);
74 static void lpfc_cpuhp_add(struct lpfc_hba *phba);
75 static void lpfc_get_hba_model_desc(struct lpfc_hba *, uint8_t *, uint8_t *);
76 static int lpfc_post_rcv_buf(struct lpfc_hba *);
77 static int lpfc_sli4_queue_verify(struct lpfc_hba *);
78 static int lpfc_create_bootstrap_mbox(struct lpfc_hba *);
79 static int lpfc_setup_endian_order(struct lpfc_hba *);
80 static void lpfc_destroy_bootstrap_mbox(struct lpfc_hba *);
81 static void lpfc_free_els_sgl_list(struct lpfc_hba *);
82 static void lpfc_free_nvmet_sgl_list(struct lpfc_hba *);
83 static void lpfc_init_sgl_list(struct lpfc_hba *);
84 static int lpfc_init_active_sgl_array(struct lpfc_hba *);
85 static void lpfc_free_active_sgl(struct lpfc_hba *);
86 static int lpfc_hba_down_post_s3(struct lpfc_hba *phba);
87 static int lpfc_hba_down_post_s4(struct lpfc_hba *phba);
88 static int lpfc_sli4_cq_event_pool_create(struct lpfc_hba *);
89 static void lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *);
90 static void lpfc_sli4_cq_event_release_all(struct lpfc_hba *);
91 static void lpfc_sli4_disable_intr(struct lpfc_hba *);
92 static uint32_t lpfc_sli4_enable_intr(struct lpfc_hba *, uint32_t);
93 static void lpfc_sli4_oas_verify(struct lpfc_hba *phba);
94 static uint16_t lpfc_find_cpu_handle(struct lpfc_hba *, uint16_t, int);
95 static void lpfc_setup_bg(struct lpfc_hba *, struct Scsi_Host *);
96 static int lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *);
97 static void lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba);
98 static void lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba);
99
100 static struct scsi_transport_template *lpfc_transport_template = NULL;
101 static struct scsi_transport_template *lpfc_vport_transport_template = NULL;
102 static DEFINE_IDR(lpfc_hba_index);
103 #define LPFC_NVMET_BUF_POST 254
104 static int lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport);
105 static void lpfc_cgn_update_tstamp(struct lpfc_hba *phba, struct lpfc_cgn_ts *ts);
106
107 /**
108  * lpfc_config_port_prep - Perform lpfc initialization prior to config port
109  * @phba: pointer to lpfc hba data structure.
110  *
111  * This routine will do LPFC initialization prior to issuing the CONFIG_PORT
112  * mailbox command. It retrieves the revision information from the HBA and
113  * collects the Vital Product Data (VPD) about the HBA for preparing the
114  * configuration of the HBA.
115  *
116  * Return codes:
117  *   0 - success.
118  *   -ERESTART - requests the SLI layer to reset the HBA and try again.
119  *   Any other value - indicates an error.
120  **/
121 int
122 lpfc_config_port_prep(struct lpfc_hba *phba)
123 {
124         lpfc_vpd_t *vp = &phba->vpd;
125         int i = 0, rc;
126         LPFC_MBOXQ_t *pmb;
127         MAILBOX_t *mb;
128         char *lpfc_vpd_data = NULL;
129         uint16_t offset = 0;
130         static char licensed[56] =
131                     "key unlock for use with gnu public licensed code only\0";
132         static int init_key = 1;
133
134         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
135         if (!pmb) {
136                 phba->link_state = LPFC_HBA_ERROR;
137                 return -ENOMEM;
138         }
139
140         mb = &pmb->u.mb;
141         phba->link_state = LPFC_INIT_MBX_CMDS;
142
143         if (lpfc_is_LC_HBA(phba->pcidev->device)) {
144                 if (init_key) {
145                         uint32_t *ptext = (uint32_t *) licensed;
146
147                         for (i = 0; i < 56; i += sizeof (uint32_t), ptext++)
148                                 *ptext = cpu_to_be32(*ptext);
149                         init_key = 0;
150                 }
151
152                 lpfc_read_nv(phba, pmb);
153                 memset((char*)mb->un.varRDnvp.rsvd3, 0,
154                         sizeof (mb->un.varRDnvp.rsvd3));
155                 memcpy((char*)mb->un.varRDnvp.rsvd3, licensed,
156                          sizeof (licensed));
157
158                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
159
160                 if (rc != MBX_SUCCESS) {
161                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
162                                         "0324 Config Port initialization "
163                                         "error, mbxCmd x%x READ_NVPARM, "
164                                         "mbxStatus x%x\n",
165                                         mb->mbxCommand, mb->mbxStatus);
166                         mempool_free(pmb, phba->mbox_mem_pool);
167                         return -ERESTART;
168                 }
169                 memcpy(phba->wwnn, (char *)mb->un.varRDnvp.nodename,
170                        sizeof(phba->wwnn));
171                 memcpy(phba->wwpn, (char *)mb->un.varRDnvp.portname,
172                        sizeof(phba->wwpn));
173         }
174
175         /*
176          * Clear all option bits except LPFC_SLI3_BG_ENABLED,
177          * which was already set in lpfc_get_cfgparam()
178          */
179         phba->sli3_options &= (uint32_t)LPFC_SLI3_BG_ENABLED;
180
181         /* Setup and issue mailbox READ REV command */
182         lpfc_read_rev(phba, pmb);
183         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
184         if (rc != MBX_SUCCESS) {
185                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
186                                 "0439 Adapter failed to init, mbxCmd x%x "
187                                 "READ_REV, mbxStatus x%x\n",
188                                 mb->mbxCommand, mb->mbxStatus);
189                 mempool_free( pmb, phba->mbox_mem_pool);
190                 return -ERESTART;
191         }
192
193
194         /*
195          * The value of rr must be 1 since the driver set the cv field to 1.
196          * This setting requires the FW to set all revision fields.
197          */
198         if (mb->un.varRdRev.rr == 0) {
199                 vp->rev.rBit = 0;
200                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
201                                 "0440 Adapter failed to init, READ_REV has "
202                                 "missing revision information.\n");
203                 mempool_free(pmb, phba->mbox_mem_pool);
204                 return -ERESTART;
205         }
206
207         if (phba->sli_rev == 3 && !mb->un.varRdRev.v3rsp) {
208                 mempool_free(pmb, phba->mbox_mem_pool);
209                 return -EINVAL;
210         }
211
212         /* Save information as VPD data */
213         vp->rev.rBit = 1;
214         memcpy(&vp->sli3Feat, &mb->un.varRdRev.sli3Feat, sizeof(uint32_t));
215         vp->rev.sli1FwRev = mb->un.varRdRev.sli1FwRev;
216         memcpy(vp->rev.sli1FwName, (char*) mb->un.varRdRev.sli1FwName, 16);
217         vp->rev.sli2FwRev = mb->un.varRdRev.sli2FwRev;
218         memcpy(vp->rev.sli2FwName, (char *) mb->un.varRdRev.sli2FwName, 16);
219         vp->rev.biuRev = mb->un.varRdRev.biuRev;
220         vp->rev.smRev = mb->un.varRdRev.smRev;
221         vp->rev.smFwRev = mb->un.varRdRev.un.smFwRev;
222         vp->rev.endecRev = mb->un.varRdRev.endecRev;
223         vp->rev.fcphHigh = mb->un.varRdRev.fcphHigh;
224         vp->rev.fcphLow = mb->un.varRdRev.fcphLow;
225         vp->rev.feaLevelHigh = mb->un.varRdRev.feaLevelHigh;
226         vp->rev.feaLevelLow = mb->un.varRdRev.feaLevelLow;
227         vp->rev.postKernRev = mb->un.varRdRev.postKernRev;
228         vp->rev.opFwRev = mb->un.varRdRev.opFwRev;
229
230         /* If the sli feature level is less then 9, we must
231          * tear down all RPIs and VPIs on link down if NPIV
232          * is enabled.
233          */
234         if (vp->rev.feaLevelHigh < 9)
235                 phba->sli3_options |= LPFC_SLI3_VPORT_TEARDOWN;
236
237         if (lpfc_is_LC_HBA(phba->pcidev->device))
238                 memcpy(phba->RandomData, (char *)&mb->un.varWords[24],
239                                                 sizeof (phba->RandomData));
240
241         /* Get adapter VPD information */
242         lpfc_vpd_data = kmalloc(DMP_VPD_SIZE, GFP_KERNEL);
243         if (!lpfc_vpd_data)
244                 goto out_free_mbox;
245         do {
246                 lpfc_dump_mem(phba, pmb, offset, DMP_REGION_VPD);
247                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
248
249                 if (rc != MBX_SUCCESS) {
250                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
251                                         "0441 VPD not present on adapter, "
252                                         "mbxCmd x%x DUMP VPD, mbxStatus x%x\n",
253                                         mb->mbxCommand, mb->mbxStatus);
254                         mb->un.varDmp.word_cnt = 0;
255                 }
256                 /* dump mem may return a zero when finished or we got a
257                  * mailbox error, either way we are done.
258                  */
259                 if (mb->un.varDmp.word_cnt == 0)
260                         break;
261
262                 if (mb->un.varDmp.word_cnt > DMP_VPD_SIZE - offset)
263                         mb->un.varDmp.word_cnt = DMP_VPD_SIZE - offset;
264                 lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
265                                       lpfc_vpd_data + offset,
266                                       mb->un.varDmp.word_cnt);
267                 offset += mb->un.varDmp.word_cnt;
268         } while (mb->un.varDmp.word_cnt && offset < DMP_VPD_SIZE);
269
270         lpfc_parse_vpd(phba, lpfc_vpd_data, offset);
271
272         kfree(lpfc_vpd_data);
273 out_free_mbox:
274         mempool_free(pmb, phba->mbox_mem_pool);
275         return 0;
276 }
277
278 /**
279  * lpfc_config_async_cmpl - Completion handler for config async event mbox cmd
280  * @phba: pointer to lpfc hba data structure.
281  * @pmboxq: pointer to the driver internal queue element for mailbox command.
282  *
283  * This is the completion handler for driver's configuring asynchronous event
284  * mailbox command to the device. If the mailbox command returns successfully,
285  * it will set internal async event support flag to 1; otherwise, it will
286  * set internal async event support flag to 0.
287  **/
288 static void
289 lpfc_config_async_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
290 {
291         if (pmboxq->u.mb.mbxStatus == MBX_SUCCESS)
292                 phba->temp_sensor_support = 1;
293         else
294                 phba->temp_sensor_support = 0;
295         mempool_free(pmboxq, phba->mbox_mem_pool);
296         return;
297 }
298
299 /**
300  * lpfc_dump_wakeup_param_cmpl - dump memory mailbox command completion handler
301  * @phba: pointer to lpfc hba data structure.
302  * @pmboxq: pointer to the driver internal queue element for mailbox command.
303  *
304  * This is the completion handler for dump mailbox command for getting
305  * wake up parameters. When this command complete, the response contain
306  * Option rom version of the HBA. This function translate the version number
307  * into a human readable string and store it in OptionROMVersion.
308  **/
309 static void
310 lpfc_dump_wakeup_param_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
311 {
312         struct prog_id *prg;
313         uint32_t prog_id_word;
314         char dist = ' ';
315         /* character array used for decoding dist type. */
316         char dist_char[] = "nabx";
317
318         if (pmboxq->u.mb.mbxStatus != MBX_SUCCESS) {
319                 mempool_free(pmboxq, phba->mbox_mem_pool);
320                 return;
321         }
322
323         prg = (struct prog_id *) &prog_id_word;
324
325         /* word 7 contain option rom version */
326         prog_id_word = pmboxq->u.mb.un.varWords[7];
327
328         /* Decode the Option rom version word to a readable string */
329         dist = dist_char[prg->dist];
330
331         if ((prg->dist == 3) && (prg->num == 0))
332                 snprintf(phba->OptionROMVersion, 32, "%d.%d%d",
333                         prg->ver, prg->rev, prg->lev);
334         else
335                 snprintf(phba->OptionROMVersion, 32, "%d.%d%d%c%d",
336                         prg->ver, prg->rev, prg->lev,
337                         dist, prg->num);
338         mempool_free(pmboxq, phba->mbox_mem_pool);
339         return;
340 }
341
342 /**
343  * lpfc_update_vport_wwn - Updates the fc_nodename, fc_portname,
344  * @vport: pointer to lpfc vport data structure.
345  *
346  *
347  * Return codes
348  *   None.
349  **/
350 void
351 lpfc_update_vport_wwn(struct lpfc_vport *vport)
352 {
353         struct lpfc_hba *phba = vport->phba;
354
355         /*
356          * If the name is empty or there exists a soft name
357          * then copy the service params name, otherwise use the fc name
358          */
359         if (vport->fc_nodename.u.wwn[0] == 0)
360                 memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
361                         sizeof(struct lpfc_name));
362         else
363                 memcpy(&vport->fc_sparam.nodeName, &vport->fc_nodename,
364                         sizeof(struct lpfc_name));
365
366         /*
367          * If the port name has changed, then set the Param changes flag
368          * to unreg the login
369          */
370         if (vport->fc_portname.u.wwn[0] != 0 &&
371                 memcmp(&vport->fc_portname, &vport->fc_sparam.portName,
372                        sizeof(struct lpfc_name))) {
373                 vport->vport_flag |= FAWWPN_PARAM_CHG;
374
375                 if (phba->sli_rev == LPFC_SLI_REV4 &&
376                     vport->port_type == LPFC_PHYSICAL_PORT &&
377                     phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_FABRIC) {
378                         if (!(phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG))
379                                 phba->sli4_hba.fawwpn_flag &=
380                                                 ~LPFC_FAWWPN_FABRIC;
381                         lpfc_printf_log(phba, KERN_INFO,
382                                         LOG_SLI | LOG_DISCOVERY | LOG_ELS,
383                                         "2701 FA-PWWN change WWPN from %llx to "
384                                         "%llx: vflag x%x fawwpn_flag x%x\n",
385                                         wwn_to_u64(vport->fc_portname.u.wwn),
386                                         wwn_to_u64
387                                            (vport->fc_sparam.portName.u.wwn),
388                                         vport->vport_flag,
389                                         phba->sli4_hba.fawwpn_flag);
390                         memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
391                                sizeof(struct lpfc_name));
392                 }
393         }
394
395         if (vport->fc_portname.u.wwn[0] == 0)
396                 memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
397                        sizeof(struct lpfc_name));
398         else
399                 memcpy(&vport->fc_sparam.portName, &vport->fc_portname,
400                        sizeof(struct lpfc_name));
401 }
402
403 /**
404  * lpfc_config_port_post - Perform lpfc initialization after config port
405  * @phba: pointer to lpfc hba data structure.
406  *
407  * This routine will do LPFC initialization after the CONFIG_PORT mailbox
408  * command call. It performs all internal resource and state setups on the
409  * port: post IOCB buffers, enable appropriate host interrupt attentions,
410  * ELS ring timers, etc.
411  *
412  * Return codes
413  *   0 - success.
414  *   Any other value - error.
415  **/
416 int
417 lpfc_config_port_post(struct lpfc_hba *phba)
418 {
419         struct lpfc_vport *vport = phba->pport;
420         struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
421         LPFC_MBOXQ_t *pmb;
422         MAILBOX_t *mb;
423         struct lpfc_dmabuf *mp;
424         struct lpfc_sli *psli = &phba->sli;
425         uint32_t status, timeout;
426         int i, j;
427         int rc;
428
429         spin_lock_irq(&phba->hbalock);
430         /*
431          * If the Config port completed correctly the HBA is not
432          * over heated any more.
433          */
434         if (phba->over_temp_state == HBA_OVER_TEMP)
435                 phba->over_temp_state = HBA_NORMAL_TEMP;
436         spin_unlock_irq(&phba->hbalock);
437
438         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
439         if (!pmb) {
440                 phba->link_state = LPFC_HBA_ERROR;
441                 return -ENOMEM;
442         }
443         mb = &pmb->u.mb;
444
445         /* Get login parameters for NID.  */
446         rc = lpfc_read_sparam(phba, pmb, 0);
447         if (rc) {
448                 mempool_free(pmb, phba->mbox_mem_pool);
449                 return -ENOMEM;
450         }
451
452         pmb->vport = vport;
453         if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
454                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
455                                 "0448 Adapter failed init, mbxCmd x%x "
456                                 "READ_SPARM mbxStatus x%x\n",
457                                 mb->mbxCommand, mb->mbxStatus);
458                 phba->link_state = LPFC_HBA_ERROR;
459                 lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
460                 return -EIO;
461         }
462
463         mp = (struct lpfc_dmabuf *)pmb->ctx_buf;
464
465         /* This dmabuf was allocated by lpfc_read_sparam. The dmabuf is no
466          * longer needed.  Prevent unintended ctx_buf access as the mbox is
467          * reused.
468          */
469         memcpy(&vport->fc_sparam, mp->virt, sizeof (struct serv_parm));
470         lpfc_mbuf_free(phba, mp->virt, mp->phys);
471         kfree(mp);
472         pmb->ctx_buf = NULL;
473         lpfc_update_vport_wwn(vport);
474
475         /* Update the fc_host data structures with new wwn. */
476         fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
477         fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
478         fc_host_max_npiv_vports(shost) = phba->max_vpi;
479
480         /* If no serial number in VPD data, use low 6 bytes of WWNN */
481         /* This should be consolidated into parse_vpd ? - mr */
482         if (phba->SerialNumber[0] == 0) {
483                 uint8_t *outptr;
484
485                 outptr = &vport->fc_nodename.u.s.IEEE[0];
486                 for (i = 0; i < 12; i++) {
487                         status = *outptr++;
488                         j = ((status & 0xf0) >> 4);
489                         if (j <= 9)
490                                 phba->SerialNumber[i] =
491                                     (char)((uint8_t) 0x30 + (uint8_t) j);
492                         else
493                                 phba->SerialNumber[i] =
494                                     (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
495                         i++;
496                         j = (status & 0xf);
497                         if (j <= 9)
498                                 phba->SerialNumber[i] =
499                                     (char)((uint8_t) 0x30 + (uint8_t) j);
500                         else
501                                 phba->SerialNumber[i] =
502                                     (char)((uint8_t) 0x61 + (uint8_t) (j - 10));
503                 }
504         }
505
506         lpfc_read_config(phba, pmb);
507         pmb->vport = vport;
508         if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
509                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
510                                 "0453 Adapter failed to init, mbxCmd x%x "
511                                 "READ_CONFIG, mbxStatus x%x\n",
512                                 mb->mbxCommand, mb->mbxStatus);
513                 phba->link_state = LPFC_HBA_ERROR;
514                 mempool_free( pmb, phba->mbox_mem_pool);
515                 return -EIO;
516         }
517
518         /* Check if the port is disabled */
519         lpfc_sli_read_link_ste(phba);
520
521         /* Reset the DFT_HBA_Q_DEPTH to the max xri  */
522         if (phba->cfg_hba_queue_depth > mb->un.varRdConfig.max_xri) {
523                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
524                                 "3359 HBA queue depth changed from %d to %d\n",
525                                 phba->cfg_hba_queue_depth,
526                                 mb->un.varRdConfig.max_xri);
527                 phba->cfg_hba_queue_depth = mb->un.varRdConfig.max_xri;
528         }
529
530         phba->lmt = mb->un.varRdConfig.lmt;
531
532         /* Get the default values for Model Name and Description */
533         lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
534
535         phba->link_state = LPFC_LINK_DOWN;
536
537         /* Only process IOCBs on ELS ring till hba_state is READY */
538         if (psli->sli3_ring[LPFC_EXTRA_RING].sli.sli3.cmdringaddr)
539                 psli->sli3_ring[LPFC_EXTRA_RING].flag |= LPFC_STOP_IOCB_EVENT;
540         if (psli->sli3_ring[LPFC_FCP_RING].sli.sli3.cmdringaddr)
541                 psli->sli3_ring[LPFC_FCP_RING].flag |= LPFC_STOP_IOCB_EVENT;
542
543         /* Post receive buffers for desired rings */
544         if (phba->sli_rev != 3)
545                 lpfc_post_rcv_buf(phba);
546
547         /*
548          * Configure HBA MSI-X attention conditions to messages if MSI-X mode
549          */
550         if (phba->intr_type == MSIX) {
551                 rc = lpfc_config_msi(phba, pmb);
552                 if (rc) {
553                         mempool_free(pmb, phba->mbox_mem_pool);
554                         return -EIO;
555                 }
556                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
557                 if (rc != MBX_SUCCESS) {
558                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
559                                         "0352 Config MSI mailbox command "
560                                         "failed, mbxCmd x%x, mbxStatus x%x\n",
561                                         pmb->u.mb.mbxCommand,
562                                         pmb->u.mb.mbxStatus);
563                         mempool_free(pmb, phba->mbox_mem_pool);
564                         return -EIO;
565                 }
566         }
567
568         spin_lock_irq(&phba->hbalock);
569         /* Initialize ERATT handling flag */
570         phba->hba_flag &= ~HBA_ERATT_HANDLED;
571
572         /* Enable appropriate host interrupts */
573         if (lpfc_readl(phba->HCregaddr, &status)) {
574                 spin_unlock_irq(&phba->hbalock);
575                 return -EIO;
576         }
577         status |= HC_MBINT_ENA | HC_ERINT_ENA | HC_LAINT_ENA;
578         if (psli->num_rings > 0)
579                 status |= HC_R0INT_ENA;
580         if (psli->num_rings > 1)
581                 status |= HC_R1INT_ENA;
582         if (psli->num_rings > 2)
583                 status |= HC_R2INT_ENA;
584         if (psli->num_rings > 3)
585                 status |= HC_R3INT_ENA;
586
587         if ((phba->cfg_poll & ENABLE_FCP_RING_POLLING) &&
588             (phba->cfg_poll & DISABLE_FCP_RING_INT))
589                 status &= ~(HC_R0INT_ENA);
590
591         writel(status, phba->HCregaddr);
592         readl(phba->HCregaddr); /* flush */
593         spin_unlock_irq(&phba->hbalock);
594
595         /* Set up ring-0 (ELS) timer */
596         timeout = phba->fc_ratov * 2;
597         mod_timer(&vport->els_tmofunc,
598                   jiffies + msecs_to_jiffies(1000 * timeout));
599         /* Set up heart beat (HB) timer */
600         mod_timer(&phba->hb_tmofunc,
601                   jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
602         phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
603         phba->last_completion_time = jiffies;
604         /* Set up error attention (ERATT) polling timer */
605         mod_timer(&phba->eratt_poll,
606                   jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
607
608         if (phba->hba_flag & LINK_DISABLED) {
609                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
610                                 "2598 Adapter Link is disabled.\n");
611                 lpfc_down_link(phba, pmb);
612                 pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
613                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
614                 if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
615                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
616                                         "2599 Adapter failed to issue DOWN_LINK"
617                                         " mbox command rc 0x%x\n", rc);
618
619                         mempool_free(pmb, phba->mbox_mem_pool);
620                         return -EIO;
621                 }
622         } else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
623                 mempool_free(pmb, phba->mbox_mem_pool);
624                 rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
625                 if (rc)
626                         return rc;
627         }
628         /* MBOX buffer will be freed in mbox compl */
629         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
630         if (!pmb) {
631                 phba->link_state = LPFC_HBA_ERROR;
632                 return -ENOMEM;
633         }
634
635         lpfc_config_async(phba, pmb, LPFC_ELS_RING);
636         pmb->mbox_cmpl = lpfc_config_async_cmpl;
637         pmb->vport = phba->pport;
638         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
639
640         if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
641                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
642                                 "0456 Adapter failed to issue "
643                                 "ASYNCEVT_ENABLE mbox status x%x\n",
644                                 rc);
645                 mempool_free(pmb, phba->mbox_mem_pool);
646         }
647
648         /* Get Option rom version */
649         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
650         if (!pmb) {
651                 phba->link_state = LPFC_HBA_ERROR;
652                 return -ENOMEM;
653         }
654
655         lpfc_dump_wakeup_param(phba, pmb);
656         pmb->mbox_cmpl = lpfc_dump_wakeup_param_cmpl;
657         pmb->vport = phba->pport;
658         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
659
660         if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
661                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
662                                 "0435 Adapter failed "
663                                 "to get Option ROM version status x%x\n", rc);
664                 mempool_free(pmb, phba->mbox_mem_pool);
665         }
666
667         return 0;
668 }
669
670 /**
671  * lpfc_sli4_refresh_params - update driver copy of params.
672  * @phba: Pointer to HBA context object.
673  *
674  * This is called to refresh driver copy of dynamic fields from the
675  * common_get_sli4_parameters descriptor.
676  **/
677 int
678 lpfc_sli4_refresh_params(struct lpfc_hba *phba)
679 {
680         LPFC_MBOXQ_t *mboxq;
681         struct lpfc_mqe *mqe;
682         struct lpfc_sli4_parameters *mbx_sli4_parameters;
683         int length, rc;
684
685         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
686         if (!mboxq)
687                 return -ENOMEM;
688
689         mqe = &mboxq->u.mqe;
690         /* Read the port's SLI4 Config Parameters */
691         length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
692                   sizeof(struct lpfc_sli4_cfg_mhdr));
693         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
694                          LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
695                          length, LPFC_SLI4_MBX_EMBED);
696
697         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
698         if (unlikely(rc)) {
699                 mempool_free(mboxq, phba->mbox_mem_pool);
700                 return rc;
701         }
702         mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
703         phba->sli4_hba.pc_sli4_params.mi_cap =
704                 bf_get(cfg_mi_ver, mbx_sli4_parameters);
705
706         /* Are we forcing MI off via module parameter? */
707         if (phba->cfg_enable_mi)
708                 phba->sli4_hba.pc_sli4_params.mi_ver =
709                         bf_get(cfg_mi_ver, mbx_sli4_parameters);
710         else
711                 phba->sli4_hba.pc_sli4_params.mi_ver = 0;
712
713         phba->sli4_hba.pc_sli4_params.cmf =
714                         bf_get(cfg_cmf, mbx_sli4_parameters);
715         phba->sli4_hba.pc_sli4_params.pls =
716                         bf_get(cfg_pvl, mbx_sli4_parameters);
717
718         mempool_free(mboxq, phba->mbox_mem_pool);
719         return rc;
720 }
721
722 /**
723  * lpfc_hba_init_link - Initialize the FC link
724  * @phba: pointer to lpfc hba data structure.
725  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
726  *
727  * This routine will issue the INIT_LINK mailbox command call.
728  * It is available to other drivers through the lpfc_hba data
729  * structure for use as a delayed link up mechanism with the
730  * module parameter lpfc_suppress_link_up.
731  *
732  * Return code
733  *              0 - success
734  *              Any other value - error
735  **/
736 static int
737 lpfc_hba_init_link(struct lpfc_hba *phba, uint32_t flag)
738 {
739         return lpfc_hba_init_link_fc_topology(phba, phba->cfg_topology, flag);
740 }
741
742 /**
743  * lpfc_hba_init_link_fc_topology - Initialize FC link with desired topology
744  * @phba: pointer to lpfc hba data structure.
745  * @fc_topology: desired fc topology.
746  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
747  *
748  * This routine will issue the INIT_LINK mailbox command call.
749  * It is available to other drivers through the lpfc_hba data
750  * structure for use as a delayed link up mechanism with the
751  * module parameter lpfc_suppress_link_up.
752  *
753  * Return code
754  *              0 - success
755  *              Any other value - error
756  **/
757 int
758 lpfc_hba_init_link_fc_topology(struct lpfc_hba *phba, uint32_t fc_topology,
759                                uint32_t flag)
760 {
761         struct lpfc_vport *vport = phba->pport;
762         LPFC_MBOXQ_t *pmb;
763         MAILBOX_t *mb;
764         int rc;
765
766         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
767         if (!pmb) {
768                 phba->link_state = LPFC_HBA_ERROR;
769                 return -ENOMEM;
770         }
771         mb = &pmb->u.mb;
772         pmb->vport = vport;
773
774         if ((phba->cfg_link_speed > LPFC_USER_LINK_SPEED_MAX) ||
775             ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_1G) &&
776              !(phba->lmt & LMT_1Gb)) ||
777             ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_2G) &&
778              !(phba->lmt & LMT_2Gb)) ||
779             ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_4G) &&
780              !(phba->lmt & LMT_4Gb)) ||
781             ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_8G) &&
782              !(phba->lmt & LMT_8Gb)) ||
783             ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_10G) &&
784              !(phba->lmt & LMT_10Gb)) ||
785             ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_16G) &&
786              !(phba->lmt & LMT_16Gb)) ||
787             ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_32G) &&
788              !(phba->lmt & LMT_32Gb)) ||
789             ((phba->cfg_link_speed == LPFC_USER_LINK_SPEED_64G) &&
790              !(phba->lmt & LMT_64Gb))) {
791                 /* Reset link speed to auto */
792                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
793                                 "1302 Invalid speed for this board:%d "
794                                 "Reset link speed to auto.\n",
795                                 phba->cfg_link_speed);
796                         phba->cfg_link_speed = LPFC_USER_LINK_SPEED_AUTO;
797         }
798         lpfc_init_link(phba, pmb, fc_topology, phba->cfg_link_speed);
799         pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
800         if (phba->sli_rev < LPFC_SLI_REV4)
801                 lpfc_set_loopback_flag(phba);
802         rc = lpfc_sli_issue_mbox(phba, pmb, flag);
803         if ((rc != MBX_BUSY) && (rc != MBX_SUCCESS)) {
804                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
805                                 "0498 Adapter failed to init, mbxCmd x%x "
806                                 "INIT_LINK, mbxStatus x%x\n",
807                                 mb->mbxCommand, mb->mbxStatus);
808                 if (phba->sli_rev <= LPFC_SLI_REV3) {
809                         /* Clear all interrupt enable conditions */
810                         writel(0, phba->HCregaddr);
811                         readl(phba->HCregaddr); /* flush */
812                         /* Clear all pending interrupts */
813                         writel(0xffffffff, phba->HAregaddr);
814                         readl(phba->HAregaddr); /* flush */
815                 }
816                 phba->link_state = LPFC_HBA_ERROR;
817                 if (rc != MBX_BUSY || flag == MBX_POLL)
818                         mempool_free(pmb, phba->mbox_mem_pool);
819                 return -EIO;
820         }
821         phba->cfg_suppress_link_up = LPFC_INITIALIZE_LINK;
822         if (flag == MBX_POLL)
823                 mempool_free(pmb, phba->mbox_mem_pool);
824
825         return 0;
826 }
827
828 /**
829  * lpfc_hba_down_link - this routine downs the FC link
830  * @phba: pointer to lpfc hba data structure.
831  * @flag: mailbox command issue mode - either MBX_POLL or MBX_NOWAIT
832  *
833  * This routine will issue the DOWN_LINK mailbox command call.
834  * It is available to other drivers through the lpfc_hba data
835  * structure for use to stop the link.
836  *
837  * Return code
838  *              0 - success
839  *              Any other value - error
840  **/
841 static int
842 lpfc_hba_down_link(struct lpfc_hba *phba, uint32_t flag)
843 {
844         LPFC_MBOXQ_t *pmb;
845         int rc;
846
847         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
848         if (!pmb) {
849                 phba->link_state = LPFC_HBA_ERROR;
850                 return -ENOMEM;
851         }
852
853         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
854                         "0491 Adapter Link is disabled.\n");
855         lpfc_down_link(phba, pmb);
856         pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
857         rc = lpfc_sli_issue_mbox(phba, pmb, flag);
858         if ((rc != MBX_SUCCESS) && (rc != MBX_BUSY)) {
859                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
860                                 "2522 Adapter failed to issue DOWN_LINK"
861                                 " mbox command rc 0x%x\n", rc);
862
863                 mempool_free(pmb, phba->mbox_mem_pool);
864                 return -EIO;
865         }
866         if (flag == MBX_POLL)
867                 mempool_free(pmb, phba->mbox_mem_pool);
868
869         return 0;
870 }
871
872 /**
873  * lpfc_hba_down_prep - Perform lpfc uninitialization prior to HBA reset
874  * @phba: pointer to lpfc HBA data structure.
875  *
876  * This routine will do LPFC uninitialization before the HBA is reset when
877  * bringing down the SLI Layer.
878  *
879  * Return codes
880  *   0 - success.
881  *   Any other value - error.
882  **/
883 int
884 lpfc_hba_down_prep(struct lpfc_hba *phba)
885 {
886         struct lpfc_vport **vports;
887         int i;
888
889         if (phba->sli_rev <= LPFC_SLI_REV3) {
890                 /* Disable interrupts */
891                 writel(0, phba->HCregaddr);
892                 readl(phba->HCregaddr); /* flush */
893         }
894
895         if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
896                 lpfc_cleanup_discovery_resources(phba->pport);
897         else {
898                 vports = lpfc_create_vport_work_array(phba);
899                 if (vports != NULL)
900                         for (i = 0; i <= phba->max_vports &&
901                                 vports[i] != NULL; i++)
902                                 lpfc_cleanup_discovery_resources(vports[i]);
903                 lpfc_destroy_vport_work_array(phba, vports);
904         }
905         return 0;
906 }
907
908 /**
909  * lpfc_sli4_free_sp_events - Cleanup sp_queue_events to free
910  * rspiocb which got deferred
911  *
912  * @phba: pointer to lpfc HBA data structure.
913  *
914  * This routine will cleanup completed slow path events after HBA is reset
915  * when bringing down the SLI Layer.
916  *
917  *
918  * Return codes
919  *   void.
920  **/
921 static void
922 lpfc_sli4_free_sp_events(struct lpfc_hba *phba)
923 {
924         struct lpfc_iocbq *rspiocbq;
925         struct hbq_dmabuf *dmabuf;
926         struct lpfc_cq_event *cq_event;
927
928         spin_lock_irq(&phba->hbalock);
929         phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
930         spin_unlock_irq(&phba->hbalock);
931
932         while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
933                 /* Get the response iocb from the head of work queue */
934                 spin_lock_irq(&phba->hbalock);
935                 list_remove_head(&phba->sli4_hba.sp_queue_event,
936                                  cq_event, struct lpfc_cq_event, list);
937                 spin_unlock_irq(&phba->hbalock);
938
939                 switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
940                 case CQE_CODE_COMPL_WQE:
941                         rspiocbq = container_of(cq_event, struct lpfc_iocbq,
942                                                  cq_event);
943                         lpfc_sli_release_iocbq(phba, rspiocbq);
944                         break;
945                 case CQE_CODE_RECEIVE:
946                 case CQE_CODE_RECEIVE_V1:
947                         dmabuf = container_of(cq_event, struct hbq_dmabuf,
948                                               cq_event);
949                         lpfc_in_buf_free(phba, &dmabuf->dbuf);
950                 }
951         }
952 }
953
954 /**
955  * lpfc_hba_free_post_buf - Perform lpfc uninitialization after HBA reset
956  * @phba: pointer to lpfc HBA data structure.
957  *
958  * This routine will cleanup posted ELS buffers after the HBA is reset
959  * when bringing down the SLI Layer.
960  *
961  *
962  * Return codes
963  *   void.
964  **/
965 static void
966 lpfc_hba_free_post_buf(struct lpfc_hba *phba)
967 {
968         struct lpfc_sli *psli = &phba->sli;
969         struct lpfc_sli_ring *pring;
970         struct lpfc_dmabuf *mp, *next_mp;
971         LIST_HEAD(buflist);
972         int count;
973
974         if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
975                 lpfc_sli_hbqbuf_free_all(phba);
976         else {
977                 /* Cleanup preposted buffers on the ELS ring */
978                 pring = &psli->sli3_ring[LPFC_ELS_RING];
979                 spin_lock_irq(&phba->hbalock);
980                 list_splice_init(&pring->postbufq, &buflist);
981                 spin_unlock_irq(&phba->hbalock);
982
983                 count = 0;
984                 list_for_each_entry_safe(mp, next_mp, &buflist, list) {
985                         list_del(&mp->list);
986                         count++;
987                         lpfc_mbuf_free(phba, mp->virt, mp->phys);
988                         kfree(mp);
989                 }
990
991                 spin_lock_irq(&phba->hbalock);
992                 pring->postbufq_cnt -= count;
993                 spin_unlock_irq(&phba->hbalock);
994         }
995 }
996
997 /**
998  * lpfc_hba_clean_txcmplq - Perform lpfc uninitialization after HBA reset
999  * @phba: pointer to lpfc HBA data structure.
1000  *
1001  * This routine will cleanup the txcmplq after the HBA is reset when bringing
1002  * down the SLI Layer.
1003  *
1004  * Return codes
1005  *   void
1006  **/
1007 static void
1008 lpfc_hba_clean_txcmplq(struct lpfc_hba *phba)
1009 {
1010         struct lpfc_sli *psli = &phba->sli;
1011         struct lpfc_queue *qp = NULL;
1012         struct lpfc_sli_ring *pring;
1013         LIST_HEAD(completions);
1014         int i;
1015         struct lpfc_iocbq *piocb, *next_iocb;
1016
1017         if (phba->sli_rev != LPFC_SLI_REV4) {
1018                 for (i = 0; i < psli->num_rings; i++) {
1019                         pring = &psli->sli3_ring[i];
1020                         spin_lock_irq(&phba->hbalock);
1021                         /* At this point in time the HBA is either reset or DOA
1022                          * Nothing should be on txcmplq as it will
1023                          * NEVER complete.
1024                          */
1025                         list_splice_init(&pring->txcmplq, &completions);
1026                         pring->txcmplq_cnt = 0;
1027                         spin_unlock_irq(&phba->hbalock);
1028
1029                         lpfc_sli_abort_iocb_ring(phba, pring);
1030                 }
1031                 /* Cancel all the IOCBs from the completions list */
1032                 lpfc_sli_cancel_iocbs(phba, &completions,
1033                                       IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1034                 return;
1035         }
1036         list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
1037                 pring = qp->pring;
1038                 if (!pring)
1039                         continue;
1040                 spin_lock_irq(&pring->ring_lock);
1041                 list_for_each_entry_safe(piocb, next_iocb,
1042                                          &pring->txcmplq, list)
1043                         piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
1044                 list_splice_init(&pring->txcmplq, &completions);
1045                 pring->txcmplq_cnt = 0;
1046                 spin_unlock_irq(&pring->ring_lock);
1047                 lpfc_sli_abort_iocb_ring(phba, pring);
1048         }
1049         /* Cancel all the IOCBs from the completions list */
1050         lpfc_sli_cancel_iocbs(phba, &completions,
1051                               IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
1052 }
1053
1054 /**
1055  * lpfc_hba_down_post_s3 - Perform lpfc uninitialization after HBA reset
1056  * @phba: pointer to lpfc HBA data structure.
1057  *
1058  * This routine will do uninitialization after the HBA is reset when bring
1059  * down the SLI Layer.
1060  *
1061  * Return codes
1062  *   0 - success.
1063  *   Any other value - error.
1064  **/
1065 static int
1066 lpfc_hba_down_post_s3(struct lpfc_hba *phba)
1067 {
1068         lpfc_hba_free_post_buf(phba);
1069         lpfc_hba_clean_txcmplq(phba);
1070         return 0;
1071 }
1072
1073 /**
1074  * lpfc_hba_down_post_s4 - Perform lpfc uninitialization after HBA reset
1075  * @phba: pointer to lpfc HBA data structure.
1076  *
1077  * This routine will do uninitialization after the HBA is reset when bring
1078  * down the SLI Layer.
1079  *
1080  * Return codes
1081  *   0 - success.
1082  *   Any other value - error.
1083  **/
1084 static int
1085 lpfc_hba_down_post_s4(struct lpfc_hba *phba)
1086 {
1087         struct lpfc_io_buf *psb, *psb_next;
1088         struct lpfc_async_xchg_ctx *ctxp, *ctxp_next;
1089         struct lpfc_sli4_hdw_queue *qp;
1090         LIST_HEAD(aborts);
1091         LIST_HEAD(nvme_aborts);
1092         LIST_HEAD(nvmet_aborts);
1093         struct lpfc_sglq *sglq_entry = NULL;
1094         int cnt, idx;
1095
1096
1097         lpfc_sli_hbqbuf_free_all(phba);
1098         lpfc_hba_clean_txcmplq(phba);
1099
1100         /* At this point in time the HBA is either reset or DOA. Either
1101          * way, nothing should be on lpfc_abts_els_sgl_list, it needs to be
1102          * on the lpfc_els_sgl_list so that it can either be freed if the
1103          * driver is unloading or reposted if the driver is restarting
1104          * the port.
1105          */
1106
1107         /* sgl_list_lock required because worker thread uses this
1108          * list.
1109          */
1110         spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
1111         list_for_each_entry(sglq_entry,
1112                 &phba->sli4_hba.lpfc_abts_els_sgl_list, list)
1113                 sglq_entry->state = SGL_FREED;
1114
1115         list_splice_init(&phba->sli4_hba.lpfc_abts_els_sgl_list,
1116                         &phba->sli4_hba.lpfc_els_sgl_list);
1117
1118
1119         spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
1120
1121         /* abts_xxxx_buf_list_lock required because worker thread uses this
1122          * list.
1123          */
1124         spin_lock_irq(&phba->hbalock);
1125         cnt = 0;
1126         for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
1127                 qp = &phba->sli4_hba.hdwq[idx];
1128
1129                 spin_lock(&qp->abts_io_buf_list_lock);
1130                 list_splice_init(&qp->lpfc_abts_io_buf_list,
1131                                  &aborts);
1132
1133                 list_for_each_entry_safe(psb, psb_next, &aborts, list) {
1134                         psb->pCmd = NULL;
1135                         psb->status = IOSTAT_SUCCESS;
1136                         cnt++;
1137                 }
1138                 spin_lock(&qp->io_buf_list_put_lock);
1139                 list_splice_init(&aborts, &qp->lpfc_io_buf_list_put);
1140                 qp->put_io_bufs += qp->abts_scsi_io_bufs;
1141                 qp->put_io_bufs += qp->abts_nvme_io_bufs;
1142                 qp->abts_scsi_io_bufs = 0;
1143                 qp->abts_nvme_io_bufs = 0;
1144                 spin_unlock(&qp->io_buf_list_put_lock);
1145                 spin_unlock(&qp->abts_io_buf_list_lock);
1146         }
1147         spin_unlock_irq(&phba->hbalock);
1148
1149         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
1150                 spin_lock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1151                 list_splice_init(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list,
1152                                  &nvmet_aborts);
1153                 spin_unlock_irq(&phba->sli4_hba.abts_nvmet_buf_list_lock);
1154                 list_for_each_entry_safe(ctxp, ctxp_next, &nvmet_aborts, list) {
1155                         ctxp->flag &= ~(LPFC_NVME_XBUSY | LPFC_NVME_ABORT_OP);
1156                         lpfc_nvmet_ctxbuf_post(phba, ctxp->ctxbuf);
1157                 }
1158         }
1159
1160         lpfc_sli4_free_sp_events(phba);
1161         return cnt;
1162 }
1163
1164 /**
1165  * lpfc_hba_down_post - Wrapper func for hba down post routine
1166  * @phba: pointer to lpfc HBA data structure.
1167  *
1168  * This routine wraps the actual SLI3 or SLI4 routine for performing
1169  * uninitialization after the HBA is reset when bring down the SLI Layer.
1170  *
1171  * Return codes
1172  *   0 - success.
1173  *   Any other value - error.
1174  **/
1175 int
1176 lpfc_hba_down_post(struct lpfc_hba *phba)
1177 {
1178         return (*phba->lpfc_hba_down_post)(phba);
1179 }
1180
1181 /**
1182  * lpfc_hb_timeout - The HBA-timer timeout handler
1183  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1184  *
1185  * This is the HBA-timer timeout handler registered to the lpfc driver. When
1186  * this timer fires, a HBA timeout event shall be posted to the lpfc driver
1187  * work-port-events bitmap and the worker thread is notified. This timeout
1188  * event will be used by the worker thread to invoke the actual timeout
1189  * handler routine, lpfc_hb_timeout_handler. Any periodical operations will
1190  * be performed in the timeout handler and the HBA timeout event bit shall
1191  * be cleared by the worker thread after it has taken the event bitmap out.
1192  **/
1193 static void
1194 lpfc_hb_timeout(struct timer_list *t)
1195 {
1196         struct lpfc_hba *phba;
1197         uint32_t tmo_posted;
1198         unsigned long iflag;
1199
1200         phba = from_timer(phba, t, hb_tmofunc);
1201
1202         /* Check for heart beat timeout conditions */
1203         spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1204         tmo_posted = phba->pport->work_port_events & WORKER_HB_TMO;
1205         if (!tmo_posted)
1206                 phba->pport->work_port_events |= WORKER_HB_TMO;
1207         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1208
1209         /* Tell the worker thread there is work to do */
1210         if (!tmo_posted)
1211                 lpfc_worker_wake_up(phba);
1212         return;
1213 }
1214
1215 /**
1216  * lpfc_rrq_timeout - The RRQ-timer timeout handler
1217  * @t: timer context used to obtain the pointer to lpfc hba data structure.
1218  *
1219  * This is the RRQ-timer timeout handler registered to the lpfc driver. When
1220  * this timer fires, a RRQ timeout event shall be posted to the lpfc driver
1221  * work-port-events bitmap and the worker thread is notified. This timeout
1222  * event will be used by the worker thread to invoke the actual timeout
1223  * handler routine, lpfc_rrq_handler. Any periodical operations will
1224  * be performed in the timeout handler and the RRQ timeout event bit shall
1225  * be cleared by the worker thread after it has taken the event bitmap out.
1226  **/
1227 static void
1228 lpfc_rrq_timeout(struct timer_list *t)
1229 {
1230         struct lpfc_hba *phba;
1231         unsigned long iflag;
1232
1233         phba = from_timer(phba, t, rrq_tmr);
1234         spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
1235         if (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
1236                 phba->hba_flag |= HBA_RRQ_ACTIVE;
1237         else
1238                 phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1239         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
1240
1241         if (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
1242                 lpfc_worker_wake_up(phba);
1243 }
1244
1245 /**
1246  * lpfc_hb_mbox_cmpl - The lpfc heart-beat mailbox command callback function
1247  * @phba: pointer to lpfc hba data structure.
1248  * @pmboxq: pointer to the driver internal queue element for mailbox command.
1249  *
1250  * This is the callback function to the lpfc heart-beat mailbox command.
1251  * If configured, the lpfc driver issues the heart-beat mailbox command to
1252  * the HBA every LPFC_HB_MBOX_INTERVAL (current 5) seconds. At the time the
1253  * heart-beat mailbox command is issued, the driver shall set up heart-beat
1254  * timeout timer to LPFC_HB_MBOX_TIMEOUT (current 30) seconds and marks
1255  * heart-beat outstanding state. Once the mailbox command comes back and
1256  * no error conditions detected, the heart-beat mailbox command timer is
1257  * reset to LPFC_HB_MBOX_INTERVAL seconds and the heart-beat outstanding
1258  * state is cleared for the next heart-beat. If the timer expired with the
1259  * heart-beat outstanding state set, the driver will put the HBA offline.
1260  **/
1261 static void
1262 lpfc_hb_mbox_cmpl(struct lpfc_hba * phba, LPFC_MBOXQ_t * pmboxq)
1263 {
1264         unsigned long drvr_flag;
1265
1266         spin_lock_irqsave(&phba->hbalock, drvr_flag);
1267         phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
1268         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
1269
1270         /* Check and reset heart-beat timer if necessary */
1271         mempool_free(pmboxq, phba->mbox_mem_pool);
1272         if (!test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag) &&
1273             !(phba->link_state == LPFC_HBA_ERROR) &&
1274             !test_bit(FC_UNLOADING, &phba->pport->load_flag))
1275                 mod_timer(&phba->hb_tmofunc,
1276                           jiffies +
1277                           msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
1278         return;
1279 }
1280
1281 /*
1282  * lpfc_idle_stat_delay_work - idle_stat tracking
1283  *
1284  * This routine tracks per-eq idle_stat and determines polling decisions.
1285  *
1286  * Return codes:
1287  *   None
1288  **/
1289 static void
1290 lpfc_idle_stat_delay_work(struct work_struct *work)
1291 {
1292         struct lpfc_hba *phba = container_of(to_delayed_work(work),
1293                                              struct lpfc_hba,
1294                                              idle_stat_delay_work);
1295         struct lpfc_queue *eq;
1296         struct lpfc_sli4_hdw_queue *hdwq;
1297         struct lpfc_idle_stat *idle_stat;
1298         u32 i, idle_percent;
1299         u64 wall, wall_idle, diff_wall, diff_idle, busy_time;
1300
1301         if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
1302                 return;
1303
1304         if (phba->link_state == LPFC_HBA_ERROR ||
1305             test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag) ||
1306             phba->cmf_active_mode != LPFC_CFG_OFF)
1307                 goto requeue;
1308
1309         for_each_present_cpu(i) {
1310                 hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
1311                 eq = hdwq->hba_eq;
1312
1313                 /* Skip if we've already handled this eq's primary CPU */
1314                 if (eq->chann != i)
1315                         continue;
1316
1317                 idle_stat = &phba->sli4_hba.idle_stat[i];
1318
1319                 /* get_cpu_idle_time returns values as running counters. Thus,
1320                  * to know the amount for this period, the prior counter values
1321                  * need to be subtracted from the current counter values.
1322                  * From there, the idle time stat can be calculated as a
1323                  * percentage of 100 - the sum of the other consumption times.
1324                  */
1325                 wall_idle = get_cpu_idle_time(i, &wall, 1);
1326                 diff_idle = wall_idle - idle_stat->prev_idle;
1327                 diff_wall = wall - idle_stat->prev_wall;
1328
1329                 if (diff_wall <= diff_idle)
1330                         busy_time = 0;
1331                 else
1332                         busy_time = diff_wall - diff_idle;
1333
1334                 idle_percent = div64_u64(100 * busy_time, diff_wall);
1335                 idle_percent = 100 - idle_percent;
1336
1337                 if (idle_percent < 15)
1338                         eq->poll_mode = LPFC_QUEUE_WORK;
1339                 else
1340                         eq->poll_mode = LPFC_THREADED_IRQ;
1341
1342                 idle_stat->prev_idle = wall_idle;
1343                 idle_stat->prev_wall = wall;
1344         }
1345
1346 requeue:
1347         schedule_delayed_work(&phba->idle_stat_delay_work,
1348                               msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
1349 }
1350
1351 static void
1352 lpfc_hb_eq_delay_work(struct work_struct *work)
1353 {
1354         struct lpfc_hba *phba = container_of(to_delayed_work(work),
1355                                              struct lpfc_hba, eq_delay_work);
1356         struct lpfc_eq_intr_info *eqi, *eqi_new;
1357         struct lpfc_queue *eq, *eq_next;
1358         unsigned char *ena_delay = NULL;
1359         uint32_t usdelay;
1360         int i;
1361
1362         if (!phba->cfg_auto_imax ||
1363             test_bit(FC_UNLOADING, &phba->pport->load_flag))
1364                 return;
1365
1366         if (phba->link_state == LPFC_HBA_ERROR ||
1367             test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
1368                 goto requeue;
1369
1370         ena_delay = kcalloc(phba->sli4_hba.num_possible_cpu, sizeof(*ena_delay),
1371                             GFP_KERNEL);
1372         if (!ena_delay)
1373                 goto requeue;
1374
1375         for (i = 0; i < phba->cfg_irq_chann; i++) {
1376                 /* Get the EQ corresponding to the IRQ vector */
1377                 eq = phba->sli4_hba.hba_eq_hdl[i].eq;
1378                 if (!eq)
1379                         continue;
1380                 if (eq->q_mode || eq->q_flag & HBA_EQ_DELAY_CHK) {
1381                         eq->q_flag &= ~HBA_EQ_DELAY_CHK;
1382                         ena_delay[eq->last_cpu] = 1;
1383                 }
1384         }
1385
1386         for_each_present_cpu(i) {
1387                 eqi = per_cpu_ptr(phba->sli4_hba.eq_info, i);
1388                 if (ena_delay[i]) {
1389                         usdelay = (eqi->icnt >> 10) * LPFC_EQ_DELAY_STEP;
1390                         if (usdelay > LPFC_MAX_AUTO_EQ_DELAY)
1391                                 usdelay = LPFC_MAX_AUTO_EQ_DELAY;
1392                 } else {
1393                         usdelay = 0;
1394                 }
1395
1396                 eqi->icnt = 0;
1397
1398                 list_for_each_entry_safe(eq, eq_next, &eqi->list, cpu_list) {
1399                         if (unlikely(eq->last_cpu != i)) {
1400                                 eqi_new = per_cpu_ptr(phba->sli4_hba.eq_info,
1401                                                       eq->last_cpu);
1402                                 list_move_tail(&eq->cpu_list, &eqi_new->list);
1403                                 continue;
1404                         }
1405                         if (usdelay != eq->q_mode)
1406                                 lpfc_modify_hba_eq_delay(phba, eq->hdwq, 1,
1407                                                          usdelay);
1408                 }
1409         }
1410
1411         kfree(ena_delay);
1412
1413 requeue:
1414         queue_delayed_work(phba->wq, &phba->eq_delay_work,
1415                            msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
1416 }
1417
1418 /**
1419  * lpfc_hb_mxp_handler - Multi-XRI pools handler to adjust XRI distribution
1420  * @phba: pointer to lpfc hba data structure.
1421  *
1422  * For each heartbeat, this routine does some heuristic methods to adjust
1423  * XRI distribution. The goal is to fully utilize free XRIs.
1424  **/
1425 static void lpfc_hb_mxp_handler(struct lpfc_hba *phba)
1426 {
1427         u32 i;
1428         u32 hwq_count;
1429
1430         hwq_count = phba->cfg_hdw_queue;
1431         for (i = 0; i < hwq_count; i++) {
1432                 /* Adjust XRIs in private pool */
1433                 lpfc_adjust_pvt_pool_count(phba, i);
1434
1435                 /* Adjust high watermark */
1436                 lpfc_adjust_high_watermark(phba, i);
1437
1438 #ifdef LPFC_MXP_STAT
1439                 /* Snapshot pbl, pvt and busy count */
1440                 lpfc_snapshot_mxp(phba, i);
1441 #endif
1442         }
1443 }
1444
1445 /**
1446  * lpfc_issue_hb_mbox - Issues heart-beat mailbox command
1447  * @phba: pointer to lpfc hba data structure.
1448  *
1449  * If a HB mbox is not already in progrees, this routine will allocate
1450  * a LPFC_MBOXQ_t, populate it with a MBX_HEARTBEAT (0x31) command,
1451  * and issue it. The HBA_HBEAT_INP flag means the command is in progress.
1452  **/
1453 int
1454 lpfc_issue_hb_mbox(struct lpfc_hba *phba)
1455 {
1456         LPFC_MBOXQ_t *pmboxq;
1457         int retval;
1458
1459         /* Is a Heartbeat mbox already in progress */
1460         if (phba->hba_flag & HBA_HBEAT_INP)
1461                 return 0;
1462
1463         pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1464         if (!pmboxq)
1465                 return -ENOMEM;
1466
1467         lpfc_heart_beat(phba, pmboxq);
1468         pmboxq->mbox_cmpl = lpfc_hb_mbox_cmpl;
1469         pmboxq->vport = phba->pport;
1470         retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
1471
1472         if (retval != MBX_BUSY && retval != MBX_SUCCESS) {
1473                 mempool_free(pmboxq, phba->mbox_mem_pool);
1474                 return -ENXIO;
1475         }
1476         phba->hba_flag |= HBA_HBEAT_INP;
1477
1478         return 0;
1479 }
1480
1481 /**
1482  * lpfc_issue_hb_tmo - Signals heartbeat timer to issue mbox command
1483  * @phba: pointer to lpfc hba data structure.
1484  *
1485  * The heartbeat timer (every 5 sec) will fire. If the HBA_HBEAT_TMO
1486  * flag is set, it will force a MBX_HEARTBEAT mbox command, regardless
1487  * of the value of lpfc_enable_hba_heartbeat.
1488  * If lpfc_enable_hba_heartbeat is set, the timeout routine will always
1489  * try to issue a MBX_HEARTBEAT mbox command.
1490  **/
1491 void
1492 lpfc_issue_hb_tmo(struct lpfc_hba *phba)
1493 {
1494         if (phba->cfg_enable_hba_heartbeat)
1495                 return;
1496         phba->hba_flag |= HBA_HBEAT_TMO;
1497 }
1498
1499 /**
1500  * lpfc_hb_timeout_handler - The HBA-timer timeout handler
1501  * @phba: pointer to lpfc hba data structure.
1502  *
1503  * This is the actual HBA-timer timeout handler to be invoked by the worker
1504  * thread whenever the HBA timer fired and HBA-timeout event posted. This
1505  * handler performs any periodic operations needed for the device. If such
1506  * periodic event has already been attended to either in the interrupt handler
1507  * or by processing slow-ring or fast-ring events within the HBA-timer
1508  * timeout window (LPFC_HB_MBOX_INTERVAL), this handler just simply resets
1509  * the timer for the next timeout period. If lpfc heart-beat mailbox command
1510  * is configured and there is no heart-beat mailbox command outstanding, a
1511  * heart-beat mailbox is issued and timer set properly. Otherwise, if there
1512  * has been a heart-beat mailbox command outstanding, the HBA shall be put
1513  * to offline.
1514  **/
1515 void
1516 lpfc_hb_timeout_handler(struct lpfc_hba *phba)
1517 {
1518         struct lpfc_vport **vports;
1519         struct lpfc_dmabuf *buf_ptr;
1520         int retval = 0;
1521         int i, tmo;
1522         struct lpfc_sli *psli = &phba->sli;
1523         LIST_HEAD(completions);
1524
1525         if (phba->cfg_xri_rebalancing) {
1526                 /* Multi-XRI pools handler */
1527                 lpfc_hb_mxp_handler(phba);
1528         }
1529
1530         vports = lpfc_create_vport_work_array(phba);
1531         if (vports != NULL)
1532                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
1533                         lpfc_rcv_seq_check_edtov(vports[i]);
1534                         lpfc_fdmi_change_check(vports[i]);
1535                 }
1536         lpfc_destroy_vport_work_array(phba, vports);
1537
1538         if (phba->link_state == LPFC_HBA_ERROR ||
1539             test_bit(FC_UNLOADING, &phba->pport->load_flag) ||
1540             test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
1541                 return;
1542
1543         if (phba->elsbuf_cnt &&
1544                 (phba->elsbuf_cnt == phba->elsbuf_prev_cnt)) {
1545                 spin_lock_irq(&phba->hbalock);
1546                 list_splice_init(&phba->elsbuf, &completions);
1547                 phba->elsbuf_cnt = 0;
1548                 phba->elsbuf_prev_cnt = 0;
1549                 spin_unlock_irq(&phba->hbalock);
1550
1551                 while (!list_empty(&completions)) {
1552                         list_remove_head(&completions, buf_ptr,
1553                                 struct lpfc_dmabuf, list);
1554                         lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
1555                         kfree(buf_ptr);
1556                 }
1557         }
1558         phba->elsbuf_prev_cnt = phba->elsbuf_cnt;
1559
1560         /* If there is no heart beat outstanding, issue a heartbeat command */
1561         if (phba->cfg_enable_hba_heartbeat) {
1562                 /* If IOs are completing, no need to issue a MBX_HEARTBEAT */
1563                 spin_lock_irq(&phba->pport->work_port_lock);
1564                 if (time_after(phba->last_completion_time +
1565                                 msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL),
1566                                 jiffies)) {
1567                         spin_unlock_irq(&phba->pport->work_port_lock);
1568                         if (phba->hba_flag & HBA_HBEAT_INP)
1569                                 tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1570                         else
1571                                 tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1572                         goto out;
1573                 }
1574                 spin_unlock_irq(&phba->pport->work_port_lock);
1575
1576                 /* Check if a MBX_HEARTBEAT is already in progress */
1577                 if (phba->hba_flag & HBA_HBEAT_INP) {
1578                         /*
1579                          * If heart beat timeout called with HBA_HBEAT_INP set
1580                          * we need to give the hb mailbox cmd a chance to
1581                          * complete or TMO.
1582                          */
1583                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
1584                                 "0459 Adapter heartbeat still outstanding: "
1585                                 "last compl time was %d ms.\n",
1586                                 jiffies_to_msecs(jiffies
1587                                          - phba->last_completion_time));
1588                         tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1589                 } else {
1590                         if ((!(psli->sli_flag & LPFC_SLI_MBOX_ACTIVE)) &&
1591                                 (list_empty(&psli->mboxq))) {
1592
1593                                 retval = lpfc_issue_hb_mbox(phba);
1594                                 if (retval) {
1595                                         tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1596                                         goto out;
1597                                 }
1598                                 phba->skipped_hb = 0;
1599                         } else if (time_before_eq(phba->last_completion_time,
1600                                         phba->skipped_hb)) {
1601                                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
1602                                         "2857 Last completion time not "
1603                                         " updated in %d ms\n",
1604                                         jiffies_to_msecs(jiffies
1605                                                  - phba->last_completion_time));
1606                         } else
1607                                 phba->skipped_hb = jiffies;
1608
1609                         tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1610                         goto out;
1611                 }
1612         } else {
1613                 /* Check to see if we want to force a MBX_HEARTBEAT */
1614                 if (phba->hba_flag & HBA_HBEAT_TMO) {
1615                         retval = lpfc_issue_hb_mbox(phba);
1616                         if (retval)
1617                                 tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1618                         else
1619                                 tmo = (1000 * LPFC_HB_MBOX_TIMEOUT);
1620                         goto out;
1621                 }
1622                 tmo = (1000 * LPFC_HB_MBOX_INTERVAL);
1623         }
1624 out:
1625         mod_timer(&phba->hb_tmofunc, jiffies + msecs_to_jiffies(tmo));
1626 }
1627
1628 /**
1629  * lpfc_offline_eratt - Bring lpfc offline on hardware error attention
1630  * @phba: pointer to lpfc hba data structure.
1631  *
1632  * This routine is called to bring the HBA offline when HBA hardware error
1633  * other than Port Error 6 has been detected.
1634  **/
1635 static void
1636 lpfc_offline_eratt(struct lpfc_hba *phba)
1637 {
1638         struct lpfc_sli   *psli = &phba->sli;
1639
1640         spin_lock_irq(&phba->hbalock);
1641         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1642         spin_unlock_irq(&phba->hbalock);
1643         lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1644
1645         lpfc_offline(phba);
1646         lpfc_reset_barrier(phba);
1647         spin_lock_irq(&phba->hbalock);
1648         lpfc_sli_brdreset(phba);
1649         spin_unlock_irq(&phba->hbalock);
1650         lpfc_hba_down_post(phba);
1651         lpfc_sli_brdready(phba, HS_MBRDY);
1652         lpfc_unblock_mgmt_io(phba);
1653         phba->link_state = LPFC_HBA_ERROR;
1654         return;
1655 }
1656
1657 /**
1658  * lpfc_sli4_offline_eratt - Bring lpfc offline on SLI4 hardware error attention
1659  * @phba: pointer to lpfc hba data structure.
1660  *
1661  * This routine is called to bring a SLI4 HBA offline when HBA hardware error
1662  * other than Port Error 6 has been detected.
1663  **/
1664 void
1665 lpfc_sli4_offline_eratt(struct lpfc_hba *phba)
1666 {
1667         spin_lock_irq(&phba->hbalock);
1668         if (phba->link_state == LPFC_HBA_ERROR &&
1669                 test_bit(HBA_PCI_ERR, &phba->bit_flags)) {
1670                 spin_unlock_irq(&phba->hbalock);
1671                 return;
1672         }
1673         phba->link_state = LPFC_HBA_ERROR;
1674         spin_unlock_irq(&phba->hbalock);
1675
1676         lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1677         lpfc_sli_flush_io_rings(phba);
1678         lpfc_offline(phba);
1679         lpfc_hba_down_post(phba);
1680         lpfc_unblock_mgmt_io(phba);
1681 }
1682
1683 /**
1684  * lpfc_handle_deferred_eratt - The HBA hardware deferred error handler
1685  * @phba: pointer to lpfc hba data structure.
1686  *
1687  * This routine is invoked to handle the deferred HBA hardware error
1688  * conditions. This type of error is indicated by HBA by setting ER1
1689  * and another ER bit in the host status register. The driver will
1690  * wait until the ER1 bit clears before handling the error condition.
1691  **/
1692 static void
1693 lpfc_handle_deferred_eratt(struct lpfc_hba *phba)
1694 {
1695         uint32_t old_host_status = phba->work_hs;
1696         struct lpfc_sli *psli = &phba->sli;
1697
1698         /* If the pci channel is offline, ignore possible errors,
1699          * since we cannot communicate with the pci card anyway.
1700          */
1701         if (pci_channel_offline(phba->pcidev)) {
1702                 spin_lock_irq(&phba->hbalock);
1703                 phba->hba_flag &= ~DEFER_ERATT;
1704                 spin_unlock_irq(&phba->hbalock);
1705                 return;
1706         }
1707
1708         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1709                         "0479 Deferred Adapter Hardware Error "
1710                         "Data: x%x x%x x%x\n",
1711                         phba->work_hs, phba->work_status[0],
1712                         phba->work_status[1]);
1713
1714         spin_lock_irq(&phba->hbalock);
1715         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1716         spin_unlock_irq(&phba->hbalock);
1717
1718
1719         /*
1720          * Firmware stops when it triggred erratt. That could cause the I/Os
1721          * dropped by the firmware. Error iocb (I/O) on txcmplq and let the
1722          * SCSI layer retry it after re-establishing link.
1723          */
1724         lpfc_sli_abort_fcp_rings(phba);
1725
1726         /*
1727          * There was a firmware error. Take the hba offline and then
1728          * attempt to restart it.
1729          */
1730         lpfc_offline_prep(phba, LPFC_MBX_WAIT);
1731         lpfc_offline(phba);
1732
1733         /* Wait for the ER1 bit to clear.*/
1734         while (phba->work_hs & HS_FFER1) {
1735                 msleep(100);
1736                 if (lpfc_readl(phba->HSregaddr, &phba->work_hs)) {
1737                         phba->work_hs = UNPLUG_ERR ;
1738                         break;
1739                 }
1740                 /* If driver is unloading let the worker thread continue */
1741                 if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1742                         phba->work_hs = 0;
1743                         break;
1744                 }
1745         }
1746
1747         /*
1748          * This is to ptrotect against a race condition in which
1749          * first write to the host attention register clear the
1750          * host status register.
1751          */
1752         if (!phba->work_hs && !test_bit(FC_UNLOADING, &phba->pport->load_flag))
1753                 phba->work_hs = old_host_status & ~HS_FFER1;
1754
1755         spin_lock_irq(&phba->hbalock);
1756         phba->hba_flag &= ~DEFER_ERATT;
1757         spin_unlock_irq(&phba->hbalock);
1758         phba->work_status[0] = readl(phba->MBslimaddr + 0xa8);
1759         phba->work_status[1] = readl(phba->MBslimaddr + 0xac);
1760 }
1761
1762 static void
1763 lpfc_board_errevt_to_mgmt(struct lpfc_hba *phba)
1764 {
1765         struct lpfc_board_event_header board_event;
1766         struct Scsi_Host *shost;
1767
1768         board_event.event_type = FC_REG_BOARD_EVENT;
1769         board_event.subcategory = LPFC_EVENT_PORTINTERR;
1770         shost = lpfc_shost_from_vport(phba->pport);
1771         fc_host_post_vendor_event(shost, fc_get_event_number(),
1772                                   sizeof(board_event),
1773                                   (char *) &board_event,
1774                                   LPFC_NL_VENDOR_ID);
1775 }
1776
1777 /**
1778  * lpfc_handle_eratt_s3 - The SLI3 HBA hardware error handler
1779  * @phba: pointer to lpfc hba data structure.
1780  *
1781  * This routine is invoked to handle the following HBA hardware error
1782  * conditions:
1783  * 1 - HBA error attention interrupt
1784  * 2 - DMA ring index out of range
1785  * 3 - Mailbox command came back as unknown
1786  **/
1787 static void
1788 lpfc_handle_eratt_s3(struct lpfc_hba *phba)
1789 {
1790         struct lpfc_vport *vport = phba->pport;
1791         struct lpfc_sli   *psli = &phba->sli;
1792         uint32_t event_data;
1793         unsigned long temperature;
1794         struct temp_event temp_event_data;
1795         struct Scsi_Host  *shost;
1796
1797         /* If the pci channel is offline, ignore possible errors,
1798          * since we cannot communicate with the pci card anyway.
1799          */
1800         if (pci_channel_offline(phba->pcidev)) {
1801                 spin_lock_irq(&phba->hbalock);
1802                 phba->hba_flag &= ~DEFER_ERATT;
1803                 spin_unlock_irq(&phba->hbalock);
1804                 return;
1805         }
1806
1807         /* If resets are disabled then leave the HBA alone and return */
1808         if (!phba->cfg_enable_hba_reset)
1809                 return;
1810
1811         /* Send an internal error event to mgmt application */
1812         lpfc_board_errevt_to_mgmt(phba);
1813
1814         if (phba->hba_flag & DEFER_ERATT)
1815                 lpfc_handle_deferred_eratt(phba);
1816
1817         if ((phba->work_hs & HS_FFER6) || (phba->work_hs & HS_FFER8)) {
1818                 if (phba->work_hs & HS_FFER6)
1819                         /* Re-establishing Link */
1820                         lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1821                                         "1301 Re-establishing Link "
1822                                         "Data: x%x x%x x%x\n",
1823                                         phba->work_hs, phba->work_status[0],
1824                                         phba->work_status[1]);
1825                 if (phba->work_hs & HS_FFER8)
1826                         /* Device Zeroization */
1827                         lpfc_printf_log(phba, KERN_INFO, LOG_LINK_EVENT,
1828                                         "2861 Host Authentication device "
1829                                         "zeroization Data:x%x x%x x%x\n",
1830                                         phba->work_hs, phba->work_status[0],
1831                                         phba->work_status[1]);
1832
1833                 spin_lock_irq(&phba->hbalock);
1834                 psli->sli_flag &= ~LPFC_SLI_ACTIVE;
1835                 spin_unlock_irq(&phba->hbalock);
1836
1837                 /*
1838                 * Firmware stops when it triggled erratt with HS_FFER6.
1839                 * That could cause the I/Os dropped by the firmware.
1840                 * Error iocb (I/O) on txcmplq and let the SCSI layer
1841                 * retry it after re-establishing link.
1842                 */
1843                 lpfc_sli_abort_fcp_rings(phba);
1844
1845                 /*
1846                  * There was a firmware error.  Take the hba offline and then
1847                  * attempt to restart it.
1848                  */
1849                 lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
1850                 lpfc_offline(phba);
1851                 lpfc_sli_brdrestart(phba);
1852                 if (lpfc_online(phba) == 0) {   /* Initialize the HBA */
1853                         lpfc_unblock_mgmt_io(phba);
1854                         return;
1855                 }
1856                 lpfc_unblock_mgmt_io(phba);
1857         } else if (phba->work_hs & HS_CRIT_TEMP) {
1858                 temperature = readl(phba->MBslimaddr + TEMPERATURE_OFFSET);
1859                 temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
1860                 temp_event_data.event_code = LPFC_CRIT_TEMP;
1861                 temp_event_data.data = (uint32_t)temperature;
1862
1863                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1864                                 "0406 Adapter maximum temperature exceeded "
1865                                 "(%ld), taking this port offline "
1866                                 "Data: x%x x%x x%x\n",
1867                                 temperature, phba->work_hs,
1868                                 phba->work_status[0], phba->work_status[1]);
1869
1870                 shost = lpfc_shost_from_vport(phba->pport);
1871                 fc_host_post_vendor_event(shost, fc_get_event_number(),
1872                                           sizeof(temp_event_data),
1873                                           (char *) &temp_event_data,
1874                                           SCSI_NL_VID_TYPE_PCI
1875                                           | PCI_VENDOR_ID_EMULEX);
1876
1877                 spin_lock_irq(&phba->hbalock);
1878                 phba->over_temp_state = HBA_OVER_TEMP;
1879                 spin_unlock_irq(&phba->hbalock);
1880                 lpfc_offline_eratt(phba);
1881
1882         } else {
1883                 /* The if clause above forces this code path when the status
1884                  * failure is a value other than FFER6. Do not call the offline
1885                  * twice. This is the adapter hardware error path.
1886                  */
1887                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1888                                 "0457 Adapter Hardware Error "
1889                                 "Data: x%x x%x x%x\n",
1890                                 phba->work_hs,
1891                                 phba->work_status[0], phba->work_status[1]);
1892
1893                 event_data = FC_REG_DUMP_EVENT;
1894                 shost = lpfc_shost_from_vport(vport);
1895                 fc_host_post_vendor_event(shost, fc_get_event_number(),
1896                                 sizeof(event_data), (char *) &event_data,
1897                                 SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
1898
1899                 lpfc_offline_eratt(phba);
1900         }
1901         return;
1902 }
1903
1904 /**
1905  * lpfc_sli4_port_sta_fn_reset - The SLI4 function reset due to port status reg
1906  * @phba: pointer to lpfc hba data structure.
1907  * @mbx_action: flag for mailbox shutdown action.
1908  * @en_rn_msg: send reset/port recovery message.
1909  * This routine is invoked to perform an SLI4 port PCI function reset in
1910  * response to port status register polling attention. It waits for port
1911  * status register (ERR, RDY, RN) bits before proceeding with function reset.
1912  * During this process, interrupt vectors are freed and later requested
1913  * for handling possible port resource change.
1914  **/
1915 static int
1916 lpfc_sli4_port_sta_fn_reset(struct lpfc_hba *phba, int mbx_action,
1917                             bool en_rn_msg)
1918 {
1919         int rc;
1920         uint32_t intr_mode;
1921         LPFC_MBOXQ_t *mboxq;
1922
1923         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
1924             LPFC_SLI_INTF_IF_TYPE_2) {
1925                 /*
1926                  * On error status condition, driver need to wait for port
1927                  * ready before performing reset.
1928                  */
1929                 rc = lpfc_sli4_pdev_status_reg_wait(phba);
1930                 if (rc)
1931                         return rc;
1932         }
1933
1934         /* need reset: attempt for port recovery */
1935         if (en_rn_msg)
1936                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1937                                 "2887 Reset Needed: Attempting Port "
1938                                 "Recovery...\n");
1939
1940         /* If we are no wait, the HBA has been reset and is not
1941          * functional, thus we should clear
1942          * (LPFC_SLI_ACTIVE | LPFC_SLI_MBOX_ACTIVE) flags.
1943          */
1944         if (mbx_action == LPFC_MBX_NO_WAIT) {
1945                 spin_lock_irq(&phba->hbalock);
1946                 phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
1947                 if (phba->sli.mbox_active) {
1948                         mboxq = phba->sli.mbox_active;
1949                         mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
1950                         __lpfc_mbox_cmpl_put(phba, mboxq);
1951                         phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
1952                         phba->sli.mbox_active = NULL;
1953                 }
1954                 spin_unlock_irq(&phba->hbalock);
1955         }
1956
1957         lpfc_offline_prep(phba, mbx_action);
1958         lpfc_sli_flush_io_rings(phba);
1959         lpfc_offline(phba);
1960         /* release interrupt for possible resource change */
1961         lpfc_sli4_disable_intr(phba);
1962         rc = lpfc_sli_brdrestart(phba);
1963         if (rc) {
1964                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1965                                 "6309 Failed to restart board\n");
1966                 return rc;
1967         }
1968         /* request and enable interrupt */
1969         intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
1970         if (intr_mode == LPFC_INTR_ERROR) {
1971                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1972                                 "3175 Failed to enable interrupt\n");
1973                 return -EIO;
1974         }
1975         phba->intr_mode = intr_mode;
1976         rc = lpfc_online(phba);
1977         if (rc == 0)
1978                 lpfc_unblock_mgmt_io(phba);
1979
1980         return rc;
1981 }
1982
1983 /**
1984  * lpfc_handle_eratt_s4 - The SLI4 HBA hardware error handler
1985  * @phba: pointer to lpfc hba data structure.
1986  *
1987  * This routine is invoked to handle the SLI4 HBA hardware error attention
1988  * conditions.
1989  **/
1990 static void
1991 lpfc_handle_eratt_s4(struct lpfc_hba *phba)
1992 {
1993         struct lpfc_vport *vport = phba->pport;
1994         uint32_t event_data;
1995         struct Scsi_Host *shost;
1996         uint32_t if_type;
1997         struct lpfc_register portstat_reg = {0};
1998         uint32_t reg_err1, reg_err2;
1999         uint32_t uerrlo_reg, uemasklo_reg;
2000         uint32_t smphr_port_status = 0, pci_rd_rc1, pci_rd_rc2;
2001         bool en_rn_msg = true;
2002         struct temp_event temp_event_data;
2003         struct lpfc_register portsmphr_reg;
2004         int rc, i;
2005
2006         /* If the pci channel is offline, ignore possible errors, since
2007          * we cannot communicate with the pci card anyway.
2008          */
2009         if (pci_channel_offline(phba->pcidev)) {
2010                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2011                                 "3166 pci channel is offline\n");
2012                 lpfc_sli_flush_io_rings(phba);
2013                 return;
2014         }
2015
2016         memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
2017         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
2018         switch (if_type) {
2019         case LPFC_SLI_INTF_IF_TYPE_0:
2020                 pci_rd_rc1 = lpfc_readl(
2021                                 phba->sli4_hba.u.if_type0.UERRLOregaddr,
2022                                 &uerrlo_reg);
2023                 pci_rd_rc2 = lpfc_readl(
2024                                 phba->sli4_hba.u.if_type0.UEMASKLOregaddr,
2025                                 &uemasklo_reg);
2026                 /* consider PCI bus read error as pci_channel_offline */
2027                 if (pci_rd_rc1 == -EIO && pci_rd_rc2 == -EIO)
2028                         return;
2029                 if (!(phba->hba_flag & HBA_RECOVERABLE_UE)) {
2030                         lpfc_sli4_offline_eratt(phba);
2031                         return;
2032                 }
2033                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2034                                 "7623 Checking UE recoverable");
2035
2036                 for (i = 0; i < phba->sli4_hba.ue_to_sr / 1000; i++) {
2037                         if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2038                                        &portsmphr_reg.word0))
2039                                 continue;
2040
2041                         smphr_port_status = bf_get(lpfc_port_smphr_port_status,
2042                                                    &portsmphr_reg);
2043                         if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2044                             LPFC_PORT_SEM_UE_RECOVERABLE)
2045                                 break;
2046                         /*Sleep for 1Sec, before checking SEMAPHORE */
2047                         msleep(1000);
2048                 }
2049
2050                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2051                                 "4827 smphr_port_status x%x : Waited %dSec",
2052                                 smphr_port_status, i);
2053
2054                 /* Recoverable UE, reset the HBA device */
2055                 if ((smphr_port_status & LPFC_PORT_SEM_MASK) ==
2056                     LPFC_PORT_SEM_UE_RECOVERABLE) {
2057                         for (i = 0; i < 20; i++) {
2058                                 msleep(1000);
2059                                 if (!lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
2060                                     &portsmphr_reg.word0) &&
2061                                     (LPFC_POST_STAGE_PORT_READY ==
2062                                      bf_get(lpfc_port_smphr_port_status,
2063                                      &portsmphr_reg))) {
2064                                         rc = lpfc_sli4_port_sta_fn_reset(phba,
2065                                                 LPFC_MBX_NO_WAIT, en_rn_msg);
2066                                         if (rc == 0)
2067                                                 return;
2068                                         lpfc_printf_log(phba, KERN_ERR,
2069                                                 LOG_TRACE_EVENT,
2070                                                 "4215 Failed to recover UE");
2071                                         break;
2072                                 }
2073                         }
2074                 }
2075                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2076                                 "7624 Firmware not ready: Failing UE recovery,"
2077                                 " waited %dSec", i);
2078                 phba->link_state = LPFC_HBA_ERROR;
2079                 break;
2080
2081         case LPFC_SLI_INTF_IF_TYPE_2:
2082         case LPFC_SLI_INTF_IF_TYPE_6:
2083                 pci_rd_rc1 = lpfc_readl(
2084                                 phba->sli4_hba.u.if_type2.STATUSregaddr,
2085                                 &portstat_reg.word0);
2086                 /* consider PCI bus read error as pci_channel_offline */
2087                 if (pci_rd_rc1 == -EIO) {
2088                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2089                                 "3151 PCI bus read access failure: x%x\n",
2090                                 readl(phba->sli4_hba.u.if_type2.STATUSregaddr));
2091                         lpfc_sli4_offline_eratt(phba);
2092                         return;
2093                 }
2094                 reg_err1 = readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
2095                 reg_err2 = readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
2096                 if (bf_get(lpfc_sliport_status_oti, &portstat_reg)) {
2097                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2098                                         "2889 Port Overtemperature event, "
2099                                         "taking port offline Data: x%x x%x\n",
2100                                         reg_err1, reg_err2);
2101
2102                         phba->sfp_alarm |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
2103                         temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
2104                         temp_event_data.event_code = LPFC_CRIT_TEMP;
2105                         temp_event_data.data = 0xFFFFFFFF;
2106
2107                         shost = lpfc_shost_from_vport(phba->pport);
2108                         fc_host_post_vendor_event(shost, fc_get_event_number(),
2109                                                   sizeof(temp_event_data),
2110                                                   (char *)&temp_event_data,
2111                                                   SCSI_NL_VID_TYPE_PCI
2112                                                   | PCI_VENDOR_ID_EMULEX);
2113
2114                         spin_lock_irq(&phba->hbalock);
2115                         phba->over_temp_state = HBA_OVER_TEMP;
2116                         spin_unlock_irq(&phba->hbalock);
2117                         lpfc_sli4_offline_eratt(phba);
2118                         return;
2119                 }
2120                 if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2121                     reg_err2 == SLIPORT_ERR2_REG_FW_RESTART) {
2122                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2123                                         "3143 Port Down: Firmware Update "
2124                                         "Detected\n");
2125                         en_rn_msg = false;
2126                 } else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2127                          reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2128                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2129                                         "3144 Port Down: Debug Dump\n");
2130                 else if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2131                          reg_err2 == SLIPORT_ERR2_REG_FUNC_PROVISON)
2132                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2133                                         "3145 Port Down: Provisioning\n");
2134
2135                 /* If resets are disabled then leave the HBA alone and return */
2136                 if (!phba->cfg_enable_hba_reset)
2137                         return;
2138
2139                 /* Check port status register for function reset */
2140                 rc = lpfc_sli4_port_sta_fn_reset(phba, LPFC_MBX_NO_WAIT,
2141                                 en_rn_msg);
2142                 if (rc == 0) {
2143                         /* don't report event on forced debug dump */
2144                         if (reg_err1 == SLIPORT_ERR1_REG_ERR_CODE_2 &&
2145                             reg_err2 == SLIPORT_ERR2_REG_FORCED_DUMP)
2146                                 return;
2147                         else
2148                                 break;
2149                 }
2150                 /* fall through for not able to recover */
2151                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2152                                 "3152 Unrecoverable error\n");
2153                 lpfc_sli4_offline_eratt(phba);
2154                 break;
2155         case LPFC_SLI_INTF_IF_TYPE_1:
2156         default:
2157                 break;
2158         }
2159         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
2160                         "3123 Report dump event to upper layer\n");
2161         /* Send an internal error event to mgmt application */
2162         lpfc_board_errevt_to_mgmt(phba);
2163
2164         event_data = FC_REG_DUMP_EVENT;
2165         shost = lpfc_shost_from_vport(vport);
2166         fc_host_post_vendor_event(shost, fc_get_event_number(),
2167                                   sizeof(event_data), (char *) &event_data,
2168                                   SCSI_NL_VID_TYPE_PCI | PCI_VENDOR_ID_EMULEX);
2169 }
2170
2171 /**
2172  * lpfc_handle_eratt - Wrapper func for handling hba error attention
2173  * @phba: pointer to lpfc HBA data structure.
2174  *
2175  * This routine wraps the actual SLI3 or SLI4 hba error attention handling
2176  * routine from the API jump table function pointer from the lpfc_hba struct.
2177  *
2178  * Return codes
2179  *   0 - success.
2180  *   Any other value - error.
2181  **/
2182 void
2183 lpfc_handle_eratt(struct lpfc_hba *phba)
2184 {
2185         (*phba->lpfc_handle_eratt)(phba);
2186 }
2187
2188 /**
2189  * lpfc_handle_latt - The HBA link event handler
2190  * @phba: pointer to lpfc hba data structure.
2191  *
2192  * This routine is invoked from the worker thread to handle a HBA host
2193  * attention link event. SLI3 only.
2194  **/
2195 void
2196 lpfc_handle_latt(struct lpfc_hba *phba)
2197 {
2198         struct lpfc_vport *vport = phba->pport;
2199         struct lpfc_sli   *psli = &phba->sli;
2200         LPFC_MBOXQ_t *pmb;
2201         volatile uint32_t control;
2202         int rc = 0;
2203
2204         pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
2205         if (!pmb) {
2206                 rc = 1;
2207                 goto lpfc_handle_latt_err_exit;
2208         }
2209
2210         rc = lpfc_mbox_rsrc_prep(phba, pmb);
2211         if (rc) {
2212                 rc = 2;
2213                 mempool_free(pmb, phba->mbox_mem_pool);
2214                 goto lpfc_handle_latt_err_exit;
2215         }
2216
2217         /* Cleanup any outstanding ELS commands */
2218         lpfc_els_flush_all_cmd(phba);
2219         psli->slistat.link_event++;
2220         lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
2221         pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
2222         pmb->vport = vport;
2223         /* Block ELS IOCBs until we have processed this mbox command */
2224         phba->sli.sli3_ring[LPFC_ELS_RING].flag |= LPFC_STOP_IOCB_EVENT;
2225         rc = lpfc_sli_issue_mbox (phba, pmb, MBX_NOWAIT);
2226         if (rc == MBX_NOT_FINISHED) {
2227                 rc = 4;
2228                 goto lpfc_handle_latt_free_mbuf;
2229         }
2230
2231         /* Clear Link Attention in HA REG */
2232         spin_lock_irq(&phba->hbalock);
2233         writel(HA_LATT, phba->HAregaddr);
2234         readl(phba->HAregaddr); /* flush */
2235         spin_unlock_irq(&phba->hbalock);
2236
2237         return;
2238
2239 lpfc_handle_latt_free_mbuf:
2240         phba->sli.sli3_ring[LPFC_ELS_RING].flag &= ~LPFC_STOP_IOCB_EVENT;
2241         lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2242 lpfc_handle_latt_err_exit:
2243         /* Enable Link attention interrupts */
2244         spin_lock_irq(&phba->hbalock);
2245         psli->sli_flag |= LPFC_PROCESS_LA;
2246         control = readl(phba->HCregaddr);
2247         control |= HC_LAINT_ENA;
2248         writel(control, phba->HCregaddr);
2249         readl(phba->HCregaddr); /* flush */
2250
2251         /* Clear Link Attention in HA REG */
2252         writel(HA_LATT, phba->HAregaddr);
2253         readl(phba->HAregaddr); /* flush */
2254         spin_unlock_irq(&phba->hbalock);
2255         lpfc_linkdown(phba);
2256         phba->link_state = LPFC_HBA_ERROR;
2257
2258         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2259                         "0300 LATT: Cannot issue READ_LA: Data:%d\n", rc);
2260
2261         return;
2262 }
2263
2264 static void
2265 lpfc_fill_vpd(struct lpfc_hba *phba, uint8_t *vpd, int length, int *pindex)
2266 {
2267         int i, j;
2268
2269         while (length > 0) {
2270                 /* Look for Serial Number */
2271                 if ((vpd[*pindex] == 'S') && (vpd[*pindex + 1] == 'N')) {
2272                         *pindex += 2;
2273                         i = vpd[*pindex];
2274                         *pindex += 1;
2275                         j = 0;
2276                         length -= (3+i);
2277                         while (i--) {
2278                                 phba->SerialNumber[j++] = vpd[(*pindex)++];
2279                                 if (j == 31)
2280                                         break;
2281                         }
2282                         phba->SerialNumber[j] = 0;
2283                         continue;
2284                 } else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '1')) {
2285                         phba->vpd_flag |= VPD_MODEL_DESC;
2286                         *pindex += 2;
2287                         i = vpd[*pindex];
2288                         *pindex += 1;
2289                         j = 0;
2290                         length -= (3+i);
2291                         while (i--) {
2292                                 phba->ModelDesc[j++] = vpd[(*pindex)++];
2293                                 if (j == 255)
2294                                         break;
2295                         }
2296                         phba->ModelDesc[j] = 0;
2297                         continue;
2298                 } else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '2')) {
2299                         phba->vpd_flag |= VPD_MODEL_NAME;
2300                         *pindex += 2;
2301                         i = vpd[*pindex];
2302                         *pindex += 1;
2303                         j = 0;
2304                         length -= (3+i);
2305                         while (i--) {
2306                                 phba->ModelName[j++] = vpd[(*pindex)++];
2307                                 if (j == 79)
2308                                         break;
2309                         }
2310                         phba->ModelName[j] = 0;
2311                         continue;
2312                 } else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '3')) {
2313                         phba->vpd_flag |= VPD_PROGRAM_TYPE;
2314                         *pindex += 2;
2315                         i = vpd[*pindex];
2316                         *pindex += 1;
2317                         j = 0;
2318                         length -= (3+i);
2319                         while (i--) {
2320                                 phba->ProgramType[j++] = vpd[(*pindex)++];
2321                                 if (j == 255)
2322                                         break;
2323                         }
2324                         phba->ProgramType[j] = 0;
2325                         continue;
2326                 } else if ((vpd[*pindex] == 'V') && (vpd[*pindex + 1] == '4')) {
2327                         phba->vpd_flag |= VPD_PORT;
2328                         *pindex += 2;
2329                         i = vpd[*pindex];
2330                         *pindex += 1;
2331                         j = 0;
2332                         length -= (3 + i);
2333                         while (i--) {
2334                                 if ((phba->sli_rev == LPFC_SLI_REV4) &&
2335                                     (phba->sli4_hba.pport_name_sta ==
2336                                      LPFC_SLI4_PPNAME_GET)) {
2337                                         j++;
2338                                         (*pindex)++;
2339                                 } else
2340                                         phba->Port[j++] = vpd[(*pindex)++];
2341                                 if (j == 19)
2342                                         break;
2343                         }
2344                         if ((phba->sli_rev != LPFC_SLI_REV4) ||
2345                             (phba->sli4_hba.pport_name_sta ==
2346                              LPFC_SLI4_PPNAME_NON))
2347                                 phba->Port[j] = 0;
2348                         continue;
2349                 } else {
2350                         *pindex += 2;
2351                         i = vpd[*pindex];
2352                         *pindex += 1;
2353                         *pindex += i;
2354                         length -= (3 + i);
2355                 }
2356         }
2357 }
2358
2359 /**
2360  * lpfc_parse_vpd - Parse VPD (Vital Product Data)
2361  * @phba: pointer to lpfc hba data structure.
2362  * @vpd: pointer to the vital product data.
2363  * @len: length of the vital product data in bytes.
2364  *
2365  * This routine parses the Vital Product Data (VPD). The VPD is treated as
2366  * an array of characters. In this routine, the ModelName, ProgramType, and
2367  * ModelDesc, etc. fields of the phba data structure will be populated.
2368  *
2369  * Return codes
2370  *   0 - pointer to the VPD passed in is NULL
2371  *   1 - success
2372  **/
2373 int
2374 lpfc_parse_vpd(struct lpfc_hba *phba, uint8_t *vpd, int len)
2375 {
2376         uint8_t lenlo, lenhi;
2377         int Length;
2378         int i;
2379         int finished = 0;
2380         int index = 0;
2381
2382         if (!vpd)
2383                 return 0;
2384
2385         /* Vital Product */
2386         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
2387                         "0455 Vital Product Data: x%x x%x x%x x%x\n",
2388                         (uint32_t) vpd[0], (uint32_t) vpd[1], (uint32_t) vpd[2],
2389                         (uint32_t) vpd[3]);
2390         while (!finished && (index < (len - 4))) {
2391                 switch (vpd[index]) {
2392                 case 0x82:
2393                 case 0x91:
2394                         index += 1;
2395                         lenlo = vpd[index];
2396                         index += 1;
2397                         lenhi = vpd[index];
2398                         index += 1;
2399                         i = ((((unsigned short)lenhi) << 8) + lenlo);
2400                         index += i;
2401                         break;
2402                 case 0x90:
2403                         index += 1;
2404                         lenlo = vpd[index];
2405                         index += 1;
2406                         lenhi = vpd[index];
2407                         index += 1;
2408                         Length = ((((unsigned short)lenhi) << 8) + lenlo);
2409                         if (Length > len - index)
2410                                 Length = len - index;
2411
2412                         lpfc_fill_vpd(phba, vpd, Length, &index);
2413                         finished = 0;
2414                         break;
2415                 case 0x78:
2416                         finished = 1;
2417                         break;
2418                 default:
2419                         index ++;
2420                         break;
2421                 }
2422         }
2423
2424         return(1);
2425 }
2426
2427 /**
2428  * lpfc_get_atto_model_desc - Retrieve ATTO HBA device model name and description
2429  * @phba: pointer to lpfc hba data structure.
2430  * @mdp: pointer to the data structure to hold the derived model name.
2431  * @descp: pointer to the data structure to hold the derived description.
2432  *
2433  * This routine retrieves HBA's description based on its registered PCI device
2434  * ID. The @descp passed into this function points to an array of 256 chars. It
2435  * shall be returned with the model name, maximum speed, and the host bus type.
2436  * The @mdp passed into this function points to an array of 80 chars. When the
2437  * function returns, the @mdp will be filled with the model name.
2438  **/
2439 static void
2440 lpfc_get_atto_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2441 {
2442         uint16_t sub_dev_id = phba->pcidev->subsystem_device;
2443         char *model = "<Unknown>";
2444         int tbolt = 0;
2445
2446         switch (sub_dev_id) {
2447         case PCI_DEVICE_ID_CLRY_161E:
2448                 model = "161E";
2449                 break;
2450         case PCI_DEVICE_ID_CLRY_162E:
2451                 model = "162E";
2452                 break;
2453         case PCI_DEVICE_ID_CLRY_164E:
2454                 model = "164E";
2455                 break;
2456         case PCI_DEVICE_ID_CLRY_161P:
2457                 model = "161P";
2458                 break;
2459         case PCI_DEVICE_ID_CLRY_162P:
2460                 model = "162P";
2461                 break;
2462         case PCI_DEVICE_ID_CLRY_164P:
2463                 model = "164P";
2464                 break;
2465         case PCI_DEVICE_ID_CLRY_321E:
2466                 model = "321E";
2467                 break;
2468         case PCI_DEVICE_ID_CLRY_322E:
2469                 model = "322E";
2470                 break;
2471         case PCI_DEVICE_ID_CLRY_324E:
2472                 model = "324E";
2473                 break;
2474         case PCI_DEVICE_ID_CLRY_321P:
2475                 model = "321P";
2476                 break;
2477         case PCI_DEVICE_ID_CLRY_322P:
2478                 model = "322P";
2479                 break;
2480         case PCI_DEVICE_ID_CLRY_324P:
2481                 model = "324P";
2482                 break;
2483         case PCI_DEVICE_ID_TLFC_2XX2:
2484                 model = "2XX2";
2485                 tbolt = 1;
2486                 break;
2487         case PCI_DEVICE_ID_TLFC_3162:
2488                 model = "3162";
2489                 tbolt = 1;
2490                 break;
2491         case PCI_DEVICE_ID_TLFC_3322:
2492                 model = "3322";
2493                 tbolt = 1;
2494                 break;
2495         default:
2496                 model = "Unknown";
2497                 break;
2498         }
2499
2500         if (mdp && mdp[0] == '\0')
2501                 snprintf(mdp, 79, "%s", model);
2502
2503         if (descp && descp[0] == '\0')
2504                 snprintf(descp, 255,
2505                          "ATTO %s%s, Fibre Channel Adapter Initiator, Port %s",
2506                          (tbolt) ? "ThunderLink FC " : "Celerity FC-",
2507                          model,
2508                          phba->Port);
2509 }
2510
2511 /**
2512  * lpfc_get_hba_model_desc - Retrieve HBA device model name and description
2513  * @phba: pointer to lpfc hba data structure.
2514  * @mdp: pointer to the data structure to hold the derived model name.
2515  * @descp: pointer to the data structure to hold the derived description.
2516  *
2517  * This routine retrieves HBA's description based on its registered PCI device
2518  * ID. The @descp passed into this function points to an array of 256 chars. It
2519  * shall be returned with the model name, maximum speed, and the host bus type.
2520  * The @mdp passed into this function points to an array of 80 chars. When the
2521  * function returns, the @mdp will be filled with the model name.
2522  **/
2523 static void
2524 lpfc_get_hba_model_desc(struct lpfc_hba *phba, uint8_t *mdp, uint8_t *descp)
2525 {
2526         lpfc_vpd_t *vp;
2527         uint16_t dev_id = phba->pcidev->device;
2528         int max_speed;
2529         int GE = 0;
2530         int oneConnect = 0; /* default is not a oneConnect */
2531         struct {
2532                 char *name;
2533                 char *bus;
2534                 char *function;
2535         } m = {"<Unknown>", "", ""};
2536
2537         if (mdp && mdp[0] != '\0'
2538                 && descp && descp[0] != '\0')
2539                 return;
2540
2541         if (phba->pcidev->vendor == PCI_VENDOR_ID_ATTO) {
2542                 lpfc_get_atto_model_desc(phba, mdp, descp);
2543                 return;
2544         }
2545
2546         if (phba->lmt & LMT_64Gb)
2547                 max_speed = 64;
2548         else if (phba->lmt & LMT_32Gb)
2549                 max_speed = 32;
2550         else if (phba->lmt & LMT_16Gb)
2551                 max_speed = 16;
2552         else if (phba->lmt & LMT_10Gb)
2553                 max_speed = 10;
2554         else if (phba->lmt & LMT_8Gb)
2555                 max_speed = 8;
2556         else if (phba->lmt & LMT_4Gb)
2557                 max_speed = 4;
2558         else if (phba->lmt & LMT_2Gb)
2559                 max_speed = 2;
2560         else if (phba->lmt & LMT_1Gb)
2561                 max_speed = 1;
2562         else
2563                 max_speed = 0;
2564
2565         vp = &phba->vpd;
2566
2567         switch (dev_id) {
2568         case PCI_DEVICE_ID_FIREFLY:
2569                 m = (typeof(m)){"LP6000", "PCI",
2570                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2571                 break;
2572         case PCI_DEVICE_ID_SUPERFLY:
2573                 if (vp->rev.biuRev >= 1 && vp->rev.biuRev <= 3)
2574                         m = (typeof(m)){"LP7000", "PCI", ""};
2575                 else
2576                         m = (typeof(m)){"LP7000E", "PCI", ""};
2577                 m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2578                 break;
2579         case PCI_DEVICE_ID_DRAGONFLY:
2580                 m = (typeof(m)){"LP8000", "PCI",
2581                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2582                 break;
2583         case PCI_DEVICE_ID_CENTAUR:
2584                 if (FC_JEDEC_ID(vp->rev.biuRev) == CENTAUR_2G_JEDEC_ID)
2585                         m = (typeof(m)){"LP9002", "PCI", ""};
2586                 else
2587                         m = (typeof(m)){"LP9000", "PCI", ""};
2588                 m.function = "Obsolete, Unsupported Fibre Channel Adapter";
2589                 break;
2590         case PCI_DEVICE_ID_RFLY:
2591                 m = (typeof(m)){"LP952", "PCI",
2592                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2593                 break;
2594         case PCI_DEVICE_ID_PEGASUS:
2595                 m = (typeof(m)){"LP9802", "PCI-X",
2596                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2597                 break;
2598         case PCI_DEVICE_ID_THOR:
2599                 m = (typeof(m)){"LP10000", "PCI-X",
2600                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2601                 break;
2602         case PCI_DEVICE_ID_VIPER:
2603                 m = (typeof(m)){"LPX1000",  "PCI-X",
2604                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2605                 break;
2606         case PCI_DEVICE_ID_PFLY:
2607                 m = (typeof(m)){"LP982", "PCI-X",
2608                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2609                 break;
2610         case PCI_DEVICE_ID_TFLY:
2611                 m = (typeof(m)){"LP1050", "PCI-X",
2612                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2613                 break;
2614         case PCI_DEVICE_ID_HELIOS:
2615                 m = (typeof(m)){"LP11000", "PCI-X2",
2616                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2617                 break;
2618         case PCI_DEVICE_ID_HELIOS_SCSP:
2619                 m = (typeof(m)){"LP11000-SP", "PCI-X2",
2620                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2621                 break;
2622         case PCI_DEVICE_ID_HELIOS_DCSP:
2623                 m = (typeof(m)){"LP11002-SP",  "PCI-X2",
2624                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2625                 break;
2626         case PCI_DEVICE_ID_NEPTUNE:
2627                 m = (typeof(m)){"LPe1000", "PCIe",
2628                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2629                 break;
2630         case PCI_DEVICE_ID_NEPTUNE_SCSP:
2631                 m = (typeof(m)){"LPe1000-SP", "PCIe",
2632                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2633                 break;
2634         case PCI_DEVICE_ID_NEPTUNE_DCSP:
2635                 m = (typeof(m)){"LPe1002-SP", "PCIe",
2636                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2637                 break;
2638         case PCI_DEVICE_ID_BMID:
2639                 m = (typeof(m)){"LP1150", "PCI-X2", "Fibre Channel Adapter"};
2640                 break;
2641         case PCI_DEVICE_ID_BSMB:
2642                 m = (typeof(m)){"LP111", "PCI-X2",
2643                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2644                 break;
2645         case PCI_DEVICE_ID_ZEPHYR:
2646                 m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2647                 break;
2648         case PCI_DEVICE_ID_ZEPHYR_SCSP:
2649                 m = (typeof(m)){"LPe11000", "PCIe", "Fibre Channel Adapter"};
2650                 break;
2651         case PCI_DEVICE_ID_ZEPHYR_DCSP:
2652                 m = (typeof(m)){"LP2105", "PCIe", "FCoE Adapter"};
2653                 GE = 1;
2654                 break;
2655         case PCI_DEVICE_ID_ZMID:
2656                 m = (typeof(m)){"LPe1150", "PCIe", "Fibre Channel Adapter"};
2657                 break;
2658         case PCI_DEVICE_ID_ZSMB:
2659                 m = (typeof(m)){"LPe111", "PCIe", "Fibre Channel Adapter"};
2660                 break;
2661         case PCI_DEVICE_ID_LP101:
2662                 m = (typeof(m)){"LP101", "PCI-X",
2663                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2664                 break;
2665         case PCI_DEVICE_ID_LP10000S:
2666                 m = (typeof(m)){"LP10000-S", "PCI",
2667                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2668                 break;
2669         case PCI_DEVICE_ID_LP11000S:
2670                 m = (typeof(m)){"LP11000-S", "PCI-X2",
2671                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2672                 break;
2673         case PCI_DEVICE_ID_LPE11000S:
2674                 m = (typeof(m)){"LPe11000-S", "PCIe",
2675                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2676                 break;
2677         case PCI_DEVICE_ID_SAT:
2678                 m = (typeof(m)){"LPe12000", "PCIe", "Fibre Channel Adapter"};
2679                 break;
2680         case PCI_DEVICE_ID_SAT_MID:
2681                 m = (typeof(m)){"LPe1250", "PCIe", "Fibre Channel Adapter"};
2682                 break;
2683         case PCI_DEVICE_ID_SAT_SMB:
2684                 m = (typeof(m)){"LPe121", "PCIe", "Fibre Channel Adapter"};
2685                 break;
2686         case PCI_DEVICE_ID_SAT_DCSP:
2687                 m = (typeof(m)){"LPe12002-SP", "PCIe", "Fibre Channel Adapter"};
2688                 break;
2689         case PCI_DEVICE_ID_SAT_SCSP:
2690                 m = (typeof(m)){"LPe12000-SP", "PCIe", "Fibre Channel Adapter"};
2691                 break;
2692         case PCI_DEVICE_ID_SAT_S:
2693                 m = (typeof(m)){"LPe12000-S", "PCIe", "Fibre Channel Adapter"};
2694                 break;
2695         case PCI_DEVICE_ID_PROTEUS_VF:
2696                 m = (typeof(m)){"LPev12000", "PCIe IOV",
2697                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2698                 break;
2699         case PCI_DEVICE_ID_PROTEUS_PF:
2700                 m = (typeof(m)){"LPev12000", "PCIe IOV",
2701                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2702                 break;
2703         case PCI_DEVICE_ID_PROTEUS_S:
2704                 m = (typeof(m)){"LPemv12002-S", "PCIe IOV",
2705                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2706                 break;
2707         case PCI_DEVICE_ID_TIGERSHARK:
2708                 oneConnect = 1;
2709                 m = (typeof(m)){"OCe10100", "PCIe", "FCoE"};
2710                 break;
2711         case PCI_DEVICE_ID_TOMCAT:
2712                 oneConnect = 1;
2713                 m = (typeof(m)){"OCe11100", "PCIe", "FCoE"};
2714                 break;
2715         case PCI_DEVICE_ID_FALCON:
2716                 m = (typeof(m)){"LPSe12002-ML1-E", "PCIe",
2717                                 "EmulexSecure Fibre"};
2718                 break;
2719         case PCI_DEVICE_ID_BALIUS:
2720                 m = (typeof(m)){"LPVe12002", "PCIe Shared I/O",
2721                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2722                 break;
2723         case PCI_DEVICE_ID_LANCER_FC:
2724                 m = (typeof(m)){"LPe16000", "PCIe", "Fibre Channel Adapter"};
2725                 break;
2726         case PCI_DEVICE_ID_LANCER_FC_VF:
2727                 m = (typeof(m)){"LPe16000", "PCIe",
2728                                 "Obsolete, Unsupported Fibre Channel Adapter"};
2729                 break;
2730         case PCI_DEVICE_ID_LANCER_FCOE:
2731                 oneConnect = 1;
2732                 m = (typeof(m)){"OCe15100", "PCIe", "FCoE"};
2733                 break;
2734         case PCI_DEVICE_ID_LANCER_FCOE_VF:
2735                 oneConnect = 1;
2736                 m = (typeof(m)){"OCe15100", "PCIe",
2737                                 "Obsolete, Unsupported FCoE"};
2738                 break;
2739         case PCI_DEVICE_ID_LANCER_G6_FC:
2740                 m = (typeof(m)){"LPe32000", "PCIe", "Fibre Channel Adapter"};
2741                 break;
2742         case PCI_DEVICE_ID_LANCER_G7_FC:
2743                 m = (typeof(m)){"LPe36000", "PCIe", "Fibre Channel Adapter"};
2744                 break;
2745         case PCI_DEVICE_ID_LANCER_G7P_FC:
2746                 m = (typeof(m)){"LPe38000", "PCIe", "Fibre Channel Adapter"};
2747                 break;
2748         case PCI_DEVICE_ID_SKYHAWK:
2749         case PCI_DEVICE_ID_SKYHAWK_VF:
2750                 oneConnect = 1;
2751                 m = (typeof(m)){"OCe14000", "PCIe", "FCoE"};
2752                 break;
2753         default:
2754                 m = (typeof(m)){"Unknown", "", ""};
2755                 break;
2756         }
2757
2758         if (mdp && mdp[0] == '\0')
2759                 snprintf(mdp, 79,"%s", m.name);
2760         /*
2761          * oneConnect hba requires special processing, they are all initiators
2762          * and we put the port number on the end
2763          */
2764         if (descp && descp[0] == '\0') {
2765                 if (oneConnect)
2766                         snprintf(descp, 255,
2767                                 "Emulex OneConnect %s, %s Initiator %s",
2768                                 m.name, m.function,
2769                                 phba->Port);
2770                 else if (max_speed == 0)
2771                         snprintf(descp, 255,
2772                                 "Emulex %s %s %s",
2773                                 m.name, m.bus, m.function);
2774                 else
2775                         snprintf(descp, 255,
2776                                 "Emulex %s %d%s %s %s",
2777                                 m.name, max_speed, (GE) ? "GE" : "Gb",
2778                                 m.bus, m.function);
2779         }
2780 }
2781
2782 /**
2783  * lpfc_sli3_post_buffer - Post IOCB(s) with DMA buffer descriptor(s) to a IOCB ring
2784  * @phba: pointer to lpfc hba data structure.
2785  * @pring: pointer to a IOCB ring.
2786  * @cnt: the number of IOCBs to be posted to the IOCB ring.
2787  *
2788  * This routine posts a given number of IOCBs with the associated DMA buffer
2789  * descriptors specified by the cnt argument to the given IOCB ring.
2790  *
2791  * Return codes
2792  *   The number of IOCBs NOT able to be posted to the IOCB ring.
2793  **/
2794 int
2795 lpfc_sli3_post_buffer(struct lpfc_hba *phba, struct lpfc_sli_ring *pring, int cnt)
2796 {
2797         IOCB_t *icmd;
2798         struct lpfc_iocbq *iocb;
2799         struct lpfc_dmabuf *mp1, *mp2;
2800
2801         cnt += pring->missbufcnt;
2802
2803         /* While there are buffers to post */
2804         while (cnt > 0) {
2805                 /* Allocate buffer for  command iocb */
2806                 iocb = lpfc_sli_get_iocbq(phba);
2807                 if (iocb == NULL) {
2808                         pring->missbufcnt = cnt;
2809                         return cnt;
2810                 }
2811                 icmd = &iocb->iocb;
2812
2813                 /* 2 buffers can be posted per command */
2814                 /* Allocate buffer to post */
2815                 mp1 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2816                 if (mp1)
2817                     mp1->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &mp1->phys);
2818                 if (!mp1 || !mp1->virt) {
2819                         kfree(mp1);
2820                         lpfc_sli_release_iocbq(phba, iocb);
2821                         pring->missbufcnt = cnt;
2822                         return cnt;
2823                 }
2824
2825                 INIT_LIST_HEAD(&mp1->list);
2826                 /* Allocate buffer to post */
2827                 if (cnt > 1) {
2828                         mp2 = kmalloc(sizeof (struct lpfc_dmabuf), GFP_KERNEL);
2829                         if (mp2)
2830                                 mp2->virt = lpfc_mbuf_alloc(phba, MEM_PRI,
2831                                                             &mp2->phys);
2832                         if (!mp2 || !mp2->virt) {
2833                                 kfree(mp2);
2834                                 lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2835                                 kfree(mp1);
2836                                 lpfc_sli_release_iocbq(phba, iocb);
2837                                 pring->missbufcnt = cnt;
2838                                 return cnt;
2839                         }
2840
2841                         INIT_LIST_HEAD(&mp2->list);
2842                 } else {
2843                         mp2 = NULL;
2844                 }
2845
2846                 icmd->un.cont64[0].addrHigh = putPaddrHigh(mp1->phys);
2847                 icmd->un.cont64[0].addrLow = putPaddrLow(mp1->phys);
2848                 icmd->un.cont64[0].tus.f.bdeSize = FCELSSIZE;
2849                 icmd->ulpBdeCount = 1;
2850                 cnt--;
2851                 if (mp2) {
2852                         icmd->un.cont64[1].addrHigh = putPaddrHigh(mp2->phys);
2853                         icmd->un.cont64[1].addrLow = putPaddrLow(mp2->phys);
2854                         icmd->un.cont64[1].tus.f.bdeSize = FCELSSIZE;
2855                         cnt--;
2856                         icmd->ulpBdeCount = 2;
2857                 }
2858
2859                 icmd->ulpCommand = CMD_QUE_RING_BUF64_CN;
2860                 icmd->ulpLe = 1;
2861
2862                 if (lpfc_sli_issue_iocb(phba, pring->ringno, iocb, 0) ==
2863                     IOCB_ERROR) {
2864                         lpfc_mbuf_free(phba, mp1->virt, mp1->phys);
2865                         kfree(mp1);
2866                         cnt++;
2867                         if (mp2) {
2868                                 lpfc_mbuf_free(phba, mp2->virt, mp2->phys);
2869                                 kfree(mp2);
2870                                 cnt++;
2871                         }
2872                         lpfc_sli_release_iocbq(phba, iocb);
2873                         pring->missbufcnt = cnt;
2874                         return cnt;
2875                 }
2876                 lpfc_sli_ringpostbuf_put(phba, pring, mp1);
2877                 if (mp2)
2878                         lpfc_sli_ringpostbuf_put(phba, pring, mp2);
2879         }
2880         pring->missbufcnt = 0;
2881         return 0;
2882 }
2883
2884 /**
2885  * lpfc_post_rcv_buf - Post the initial receive IOCB buffers to ELS ring
2886  * @phba: pointer to lpfc hba data structure.
2887  *
2888  * This routine posts initial receive IOCB buffers to the ELS ring. The
2889  * current number of initial IOCB buffers specified by LPFC_BUF_RING0 is
2890  * set to 64 IOCBs. SLI3 only.
2891  *
2892  * Return codes
2893  *   0 - success (currently always success)
2894  **/
2895 static int
2896 lpfc_post_rcv_buf(struct lpfc_hba *phba)
2897 {
2898         struct lpfc_sli *psli = &phba->sli;
2899
2900         /* Ring 0, ELS / CT buffers */
2901         lpfc_sli3_post_buffer(phba, &psli->sli3_ring[LPFC_ELS_RING], LPFC_BUF_RING0);
2902         /* Ring 2 - FCP no buffers needed */
2903
2904         return 0;
2905 }
2906
2907 #define S(N,V) (((V)<<(N))|((V)>>(32-(N))))
2908
2909 /**
2910  * lpfc_sha_init - Set up initial array of hash table entries
2911  * @HashResultPointer: pointer to an array as hash table.
2912  *
2913  * This routine sets up the initial values to the array of hash table entries
2914  * for the LC HBAs.
2915  **/
2916 static void
2917 lpfc_sha_init(uint32_t * HashResultPointer)
2918 {
2919         HashResultPointer[0] = 0x67452301;
2920         HashResultPointer[1] = 0xEFCDAB89;
2921         HashResultPointer[2] = 0x98BADCFE;
2922         HashResultPointer[3] = 0x10325476;
2923         HashResultPointer[4] = 0xC3D2E1F0;
2924 }
2925
2926 /**
2927  * lpfc_sha_iterate - Iterate initial hash table with the working hash table
2928  * @HashResultPointer: pointer to an initial/result hash table.
2929  * @HashWorkingPointer: pointer to an working hash table.
2930  *
2931  * This routine iterates an initial hash table pointed by @HashResultPointer
2932  * with the values from the working hash table pointeed by @HashWorkingPointer.
2933  * The results are putting back to the initial hash table, returned through
2934  * the @HashResultPointer as the result hash table.
2935  **/
2936 static void
2937 lpfc_sha_iterate(uint32_t * HashResultPointer, uint32_t * HashWorkingPointer)
2938 {
2939         int t;
2940         uint32_t TEMP;
2941         uint32_t A, B, C, D, E;
2942         t = 16;
2943         do {
2944                 HashWorkingPointer[t] =
2945                     S(1,
2946                       HashWorkingPointer[t - 3] ^ HashWorkingPointer[t -
2947                                                                      8] ^
2948                       HashWorkingPointer[t - 14] ^ HashWorkingPointer[t - 16]);
2949         } while (++t <= 79);
2950         t = 0;
2951         A = HashResultPointer[0];
2952         B = HashResultPointer[1];
2953         C = HashResultPointer[2];
2954         D = HashResultPointer[3];
2955         E = HashResultPointer[4];
2956
2957         do {
2958                 if (t < 20) {
2959                         TEMP = ((B & C) | ((~B) & D)) + 0x5A827999;
2960                 } else if (t < 40) {
2961                         TEMP = (B ^ C ^ D) + 0x6ED9EBA1;
2962                 } else if (t < 60) {
2963                         TEMP = ((B & C) | (B & D) | (C & D)) + 0x8F1BBCDC;
2964                 } else {
2965                         TEMP = (B ^ C ^ D) + 0xCA62C1D6;
2966                 }
2967                 TEMP += S(5, A) + E + HashWorkingPointer[t];
2968                 E = D;
2969                 D = C;
2970                 C = S(30, B);
2971                 B = A;
2972                 A = TEMP;
2973         } while (++t <= 79);
2974
2975         HashResultPointer[0] += A;
2976         HashResultPointer[1] += B;
2977         HashResultPointer[2] += C;
2978         HashResultPointer[3] += D;
2979         HashResultPointer[4] += E;
2980
2981 }
2982
2983 /**
2984  * lpfc_challenge_key - Create challenge key based on WWPN of the HBA
2985  * @RandomChallenge: pointer to the entry of host challenge random number array.
2986  * @HashWorking: pointer to the entry of the working hash array.
2987  *
2988  * This routine calculates the working hash array referred by @HashWorking
2989  * from the challenge random numbers associated with the host, referred by
2990  * @RandomChallenge. The result is put into the entry of the working hash
2991  * array and returned by reference through @HashWorking.
2992  **/
2993 static void
2994 lpfc_challenge_key(uint32_t * RandomChallenge, uint32_t * HashWorking)
2995 {
2996         *HashWorking = (*RandomChallenge ^ *HashWorking);
2997 }
2998
2999 /**
3000  * lpfc_hba_init - Perform special handling for LC HBA initialization
3001  * @phba: pointer to lpfc hba data structure.
3002  * @hbainit: pointer to an array of unsigned 32-bit integers.
3003  *
3004  * This routine performs the special handling for LC HBA initialization.
3005  **/
3006 void
3007 lpfc_hba_init(struct lpfc_hba *phba, uint32_t *hbainit)
3008 {
3009         int t;
3010         uint32_t *HashWorking;
3011         uint32_t *pwwnn = (uint32_t *) phba->wwnn;
3012
3013         HashWorking = kcalloc(80, sizeof(uint32_t), GFP_KERNEL);
3014         if (!HashWorking)
3015                 return;
3016
3017         HashWorking[0] = HashWorking[78] = *pwwnn++;
3018         HashWorking[1] = HashWorking[79] = *pwwnn;
3019
3020         for (t = 0; t < 7; t++)
3021                 lpfc_challenge_key(phba->RandomData + t, HashWorking + t);
3022
3023         lpfc_sha_init(hbainit);
3024         lpfc_sha_iterate(hbainit, HashWorking);
3025         kfree(HashWorking);
3026 }
3027
3028 /**
3029  * lpfc_cleanup - Performs vport cleanups before deleting a vport
3030  * @vport: pointer to a virtual N_Port data structure.
3031  *
3032  * This routine performs the necessary cleanups before deleting the @vport.
3033  * It invokes the discovery state machine to perform necessary state
3034  * transitions and to release the ndlps associated with the @vport. Note,
3035  * the physical port is treated as @vport 0.
3036  **/
3037 void
3038 lpfc_cleanup(struct lpfc_vport *vport)
3039 {
3040         struct lpfc_hba   *phba = vport->phba;
3041         struct lpfc_nodelist *ndlp, *next_ndlp;
3042         int i = 0;
3043
3044         if (phba->link_state > LPFC_LINK_DOWN)
3045                 lpfc_port_link_failure(vport);
3046
3047         /* Clean up VMID resources */
3048         if (lpfc_is_vmid_enabled(phba))
3049                 lpfc_vmid_vport_cleanup(vport);
3050
3051         list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
3052                 if (vport->port_type != LPFC_PHYSICAL_PORT &&
3053                     ndlp->nlp_DID == Fabric_DID) {
3054                         /* Just free up ndlp with Fabric_DID for vports */
3055                         lpfc_nlp_put(ndlp);
3056                         continue;
3057                 }
3058
3059                 if (ndlp->nlp_DID == Fabric_Cntl_DID &&
3060                     ndlp->nlp_state == NLP_STE_UNUSED_NODE) {
3061                         lpfc_nlp_put(ndlp);
3062                         continue;
3063                 }
3064
3065                 /* Fabric Ports not in UNMAPPED state are cleaned up in the
3066                  * DEVICE_RM event.
3067                  */
3068                 if (ndlp->nlp_type & NLP_FABRIC &&
3069                     ndlp->nlp_state == NLP_STE_UNMAPPED_NODE)
3070                         lpfc_disc_state_machine(vport, ndlp, NULL,
3071                                         NLP_EVT_DEVICE_RECOVERY);
3072
3073                 if (!(ndlp->fc4_xpt_flags & (NVME_XPT_REGD|SCSI_XPT_REGD)))
3074                         lpfc_disc_state_machine(vport, ndlp, NULL,
3075                                         NLP_EVT_DEVICE_RM);
3076         }
3077
3078         /* This is a special case flush to return all
3079          * IOs before entering this loop. There are
3080          * two points in the code where a flush is
3081          * avoided if the FC_UNLOADING flag is set.
3082          * one is in the multipool destroy,
3083          * (this prevents a crash) and the other is
3084          * in the nvme abort handler, ( also prevents
3085          * a crash). Both of these exceptions are
3086          * cases where the slot is still accessible.
3087          * The flush here is only when the pci slot
3088          * is offline.
3089          */
3090         if (test_bit(FC_UNLOADING, &vport->load_flag) &&
3091             pci_channel_offline(phba->pcidev))
3092                 lpfc_sli_flush_io_rings(vport->phba);
3093
3094         /* At this point, ALL ndlp's should be gone
3095          * because of the previous NLP_EVT_DEVICE_RM.
3096          * Lets wait for this to happen, if needed.
3097          */
3098         while (!list_empty(&vport->fc_nodes)) {
3099                 if (i++ > 3000) {
3100                         lpfc_printf_vlog(vport, KERN_ERR,
3101                                          LOG_TRACE_EVENT,
3102                                 "0233 Nodelist not empty\n");
3103                         list_for_each_entry_safe(ndlp, next_ndlp,
3104                                                 &vport->fc_nodes, nlp_listp) {
3105                                 lpfc_printf_vlog(ndlp->vport, KERN_ERR,
3106                                                  LOG_DISCOVERY,
3107                                                  "0282 did:x%x ndlp:x%px "
3108                                                  "refcnt:%d xflags x%x nflag x%x\n",
3109                                                  ndlp->nlp_DID, (void *)ndlp,
3110                                                  kref_read(&ndlp->kref),
3111                                                  ndlp->fc4_xpt_flags,
3112                                                  ndlp->nlp_flag);
3113                         }
3114                         break;
3115                 }
3116
3117                 /* Wait for any activity on ndlps to settle */
3118                 msleep(10);
3119         }
3120         lpfc_cleanup_vports_rrqs(vport, NULL);
3121 }
3122
3123 /**
3124  * lpfc_stop_vport_timers - Stop all the timers associated with a vport
3125  * @vport: pointer to a virtual N_Port data structure.
3126  *
3127  * This routine stops all the timers associated with a @vport. This function
3128  * is invoked before disabling or deleting a @vport. Note that the physical
3129  * port is treated as @vport 0.
3130  **/
3131 void
3132 lpfc_stop_vport_timers(struct lpfc_vport *vport)
3133 {
3134         del_timer_sync(&vport->els_tmofunc);
3135         del_timer_sync(&vport->delayed_disc_tmo);
3136         lpfc_can_disctmo(vport);
3137         return;
3138 }
3139
3140 /**
3141  * __lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3142  * @phba: pointer to lpfc hba data structure.
3143  *
3144  * This routine stops the SLI4 FCF rediscover wait timer if it's on. The
3145  * caller of this routine should already hold the host lock.
3146  **/
3147 void
3148 __lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3149 {
3150         /* Clear pending FCF rediscovery wait flag */
3151         phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
3152
3153         /* Now, try to stop the timer */
3154         del_timer(&phba->fcf.redisc_wait);
3155 }
3156
3157 /**
3158  * lpfc_sli4_stop_fcf_redisc_wait_timer - Stop FCF rediscovery wait timer
3159  * @phba: pointer to lpfc hba data structure.
3160  *
3161  * This routine stops the SLI4 FCF rediscover wait timer if it's on. It
3162  * checks whether the FCF rediscovery wait timer is pending with the host
3163  * lock held before proceeding with disabling the timer and clearing the
3164  * wait timer pendig flag.
3165  **/
3166 void
3167 lpfc_sli4_stop_fcf_redisc_wait_timer(struct lpfc_hba *phba)
3168 {
3169         spin_lock_irq(&phba->hbalock);
3170         if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
3171                 /* FCF rediscovery timer already fired or stopped */
3172                 spin_unlock_irq(&phba->hbalock);
3173                 return;
3174         }
3175         __lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3176         /* Clear failover in progress flags */
3177         phba->fcf.fcf_flag &= ~(FCF_DEAD_DISC | FCF_ACVL_DISC);
3178         spin_unlock_irq(&phba->hbalock);
3179 }
3180
3181 /**
3182  * lpfc_cmf_stop - Stop CMF processing
3183  * @phba: pointer to lpfc hba data structure.
3184  *
3185  * This is called when the link goes down or if CMF mode is turned OFF.
3186  * It is also called when going offline or unloaded just before the
3187  * congestion info buffer is unregistered.
3188  **/
3189 void
3190 lpfc_cmf_stop(struct lpfc_hba *phba)
3191 {
3192         int cpu;
3193         struct lpfc_cgn_stat *cgs;
3194
3195         /* We only do something if CMF is enabled */
3196         if (!phba->sli4_hba.pc_sli4_params.cmf)
3197                 return;
3198
3199         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3200                         "6221 Stop CMF / Cancel Timer\n");
3201
3202         /* Cancel the CMF timer */
3203         hrtimer_cancel(&phba->cmf_stats_timer);
3204         hrtimer_cancel(&phba->cmf_timer);
3205
3206         /* Zero CMF counters */
3207         atomic_set(&phba->cmf_busy, 0);
3208         for_each_present_cpu(cpu) {
3209                 cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3210                 atomic64_set(&cgs->total_bytes, 0);
3211                 atomic64_set(&cgs->rcv_bytes, 0);
3212                 atomic_set(&cgs->rx_io_cnt, 0);
3213                 atomic64_set(&cgs->rx_latency, 0);
3214         }
3215         atomic_set(&phba->cmf_bw_wait, 0);
3216
3217         /* Resume any blocked IO - Queue unblock on workqueue */
3218         queue_work(phba->wq, &phba->unblock_request_work);
3219 }
3220
3221 static inline uint64_t
3222 lpfc_get_max_line_rate(struct lpfc_hba *phba)
3223 {
3224         uint64_t rate = lpfc_sli_port_speed_get(phba);
3225
3226         return ((((unsigned long)rate) * 1024 * 1024) / 10);
3227 }
3228
3229 void
3230 lpfc_cmf_signal_init(struct lpfc_hba *phba)
3231 {
3232         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3233                         "6223 Signal CMF init\n");
3234
3235         /* Use the new fc_linkspeed to recalculate */
3236         phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
3237         phba->cmf_max_line_rate = lpfc_get_max_line_rate(phba);
3238         phba->cmf_link_byte_count = div_u64(phba->cmf_max_line_rate *
3239                                             phba->cmf_interval_rate, 1000);
3240         phba->cmf_max_bytes_per_interval = phba->cmf_link_byte_count;
3241
3242         /* This is a signal to firmware to sync up CMF BW with link speed */
3243         lpfc_issue_cmf_sync_wqe(phba, 0, 0);
3244 }
3245
3246 /**
3247  * lpfc_cmf_start - Start CMF processing
3248  * @phba: pointer to lpfc hba data structure.
3249  *
3250  * This is called when the link comes up or if CMF mode is turned OFF
3251  * to Monitor or Managed.
3252  **/
3253 void
3254 lpfc_cmf_start(struct lpfc_hba *phba)
3255 {
3256         struct lpfc_cgn_stat *cgs;
3257         int cpu;
3258
3259         /* We only do something if CMF is enabled */
3260         if (!phba->sli4_hba.pc_sli4_params.cmf ||
3261             phba->cmf_active_mode == LPFC_CFG_OFF)
3262                 return;
3263
3264         /* Reinitialize congestion buffer info */
3265         lpfc_init_congestion_buf(phba);
3266
3267         atomic_set(&phba->cgn_fabric_warn_cnt, 0);
3268         atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
3269         atomic_set(&phba->cgn_sync_alarm_cnt, 0);
3270         atomic_set(&phba->cgn_sync_warn_cnt, 0);
3271
3272         atomic_set(&phba->cmf_busy, 0);
3273         for_each_present_cpu(cpu) {
3274                 cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3275                 atomic64_set(&cgs->total_bytes, 0);
3276                 atomic64_set(&cgs->rcv_bytes, 0);
3277                 atomic_set(&cgs->rx_io_cnt, 0);
3278                 atomic64_set(&cgs->rx_latency, 0);
3279         }
3280         phba->cmf_latency.tv_sec = 0;
3281         phba->cmf_latency.tv_nsec = 0;
3282
3283         lpfc_cmf_signal_init(phba);
3284
3285         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
3286                         "6222 Start CMF / Timer\n");
3287
3288         phba->cmf_timer_cnt = 0;
3289         hrtimer_start(&phba->cmf_timer,
3290                       ktime_set(0, LPFC_CMF_INTERVAL * NSEC_PER_MSEC),
3291                       HRTIMER_MODE_REL);
3292         hrtimer_start(&phba->cmf_stats_timer,
3293                       ktime_set(0, LPFC_SEC_MIN * NSEC_PER_SEC),
3294                       HRTIMER_MODE_REL);
3295         /* Setup for latency check in IO cmpl routines */
3296         ktime_get_real_ts64(&phba->cmf_latency);
3297
3298         atomic_set(&phba->cmf_bw_wait, 0);
3299         atomic_set(&phba->cmf_stop_io, 0);
3300 }
3301
3302 /**
3303  * lpfc_stop_hba_timers - Stop all the timers associated with an HBA
3304  * @phba: pointer to lpfc hba data structure.
3305  *
3306  * This routine stops all the timers associated with a HBA. This function is
3307  * invoked before either putting a HBA offline or unloading the driver.
3308  **/
3309 void
3310 lpfc_stop_hba_timers(struct lpfc_hba *phba)
3311 {
3312         if (phba->pport)
3313                 lpfc_stop_vport_timers(phba->pport);
3314         cancel_delayed_work_sync(&phba->eq_delay_work);
3315         cancel_delayed_work_sync(&phba->idle_stat_delay_work);
3316         del_timer_sync(&phba->sli.mbox_tmo);
3317         del_timer_sync(&phba->fabric_block_timer);
3318         del_timer_sync(&phba->eratt_poll);
3319         del_timer_sync(&phba->hb_tmofunc);
3320         if (phba->sli_rev == LPFC_SLI_REV4) {
3321                 del_timer_sync(&phba->rrq_tmr);
3322                 phba->hba_flag &= ~HBA_RRQ_ACTIVE;
3323         }
3324         phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
3325
3326         switch (phba->pci_dev_grp) {
3327         case LPFC_PCI_DEV_LP:
3328                 /* Stop any LightPulse device specific driver timers */
3329                 del_timer_sync(&phba->fcp_poll_timer);
3330                 break;
3331         case LPFC_PCI_DEV_OC:
3332                 /* Stop any OneConnect device specific driver timers */
3333                 lpfc_sli4_stop_fcf_redisc_wait_timer(phba);
3334                 break;
3335         default:
3336                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3337                                 "0297 Invalid device group (x%x)\n",
3338                                 phba->pci_dev_grp);
3339                 break;
3340         }
3341         return;
3342 }
3343
3344 /**
3345  * lpfc_block_mgmt_io - Mark a HBA's management interface as blocked
3346  * @phba: pointer to lpfc hba data structure.
3347  * @mbx_action: flag for mailbox no wait action.
3348  *
3349  * This routine marks a HBA's management interface as blocked. Once the HBA's
3350  * management interface is marked as blocked, all the user space access to
3351  * the HBA, whether they are from sysfs interface or libdfc interface will
3352  * all be blocked. The HBA is set to block the management interface when the
3353  * driver prepares the HBA interface for online or offline.
3354  **/
3355 static void
3356 lpfc_block_mgmt_io(struct lpfc_hba *phba, int mbx_action)
3357 {
3358         unsigned long iflag;
3359         uint8_t actcmd = MBX_HEARTBEAT;
3360         unsigned long timeout;
3361
3362         spin_lock_irqsave(&phba->hbalock, iflag);
3363         phba->sli.sli_flag |= LPFC_BLOCK_MGMT_IO;
3364         spin_unlock_irqrestore(&phba->hbalock, iflag);
3365         if (mbx_action == LPFC_MBX_NO_WAIT)
3366                 return;
3367         timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
3368         spin_lock_irqsave(&phba->hbalock, iflag);
3369         if (phba->sli.mbox_active) {
3370                 actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
3371                 /* Determine how long we might wait for the active mailbox
3372                  * command to be gracefully completed by firmware.
3373                  */
3374                 timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
3375                                 phba->sli.mbox_active) * 1000) + jiffies;
3376         }
3377         spin_unlock_irqrestore(&phba->hbalock, iflag);
3378
3379         /* Wait for the outstnading mailbox command to complete */
3380         while (phba->sli.mbox_active) {
3381                 /* Check active mailbox complete status every 2ms */
3382                 msleep(2);
3383                 if (time_after(jiffies, timeout)) {
3384                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3385                                         "2813 Mgmt IO is Blocked %x "
3386                                         "- mbox cmd %x still active\n",
3387                                         phba->sli.sli_flag, actcmd);
3388                         break;
3389                 }
3390         }
3391 }
3392
3393 /**
3394  * lpfc_sli4_node_prep - Assign RPIs for active nodes.
3395  * @phba: pointer to lpfc hba data structure.
3396  *
3397  * Allocate RPIs for all active remote nodes. This is needed whenever
3398  * an SLI4 adapter is reset and the driver is not unloading. Its purpose
3399  * is to fixup the temporary rpi assignments.
3400  **/
3401 void
3402 lpfc_sli4_node_prep(struct lpfc_hba *phba)
3403 {
3404         struct lpfc_nodelist  *ndlp, *next_ndlp;
3405         struct lpfc_vport **vports;
3406         int i, rpi;
3407
3408         if (phba->sli_rev != LPFC_SLI_REV4)
3409                 return;
3410
3411         vports = lpfc_create_vport_work_array(phba);
3412         if (vports == NULL)
3413                 return;
3414
3415         for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3416                 if (test_bit(FC_UNLOADING, &vports[i]->load_flag))
3417                         continue;
3418
3419                 list_for_each_entry_safe(ndlp, next_ndlp,
3420                                          &vports[i]->fc_nodes,
3421                                          nlp_listp) {
3422                         rpi = lpfc_sli4_alloc_rpi(phba);
3423                         if (rpi == LPFC_RPI_ALLOC_ERROR) {
3424                                 /* TODO print log? */
3425                                 continue;
3426                         }
3427                         ndlp->nlp_rpi = rpi;
3428                         lpfc_printf_vlog(ndlp->vport, KERN_INFO,
3429                                          LOG_NODE | LOG_DISCOVERY,
3430                                          "0009 Assign RPI x%x to ndlp x%px "
3431                                          "DID:x%06x flg:x%x\n",
3432                                          ndlp->nlp_rpi, ndlp, ndlp->nlp_DID,
3433                                          ndlp->nlp_flag);
3434                 }
3435         }
3436         lpfc_destroy_vport_work_array(phba, vports);
3437 }
3438
3439 /**
3440  * lpfc_create_expedite_pool - create expedite pool
3441  * @phba: pointer to lpfc hba data structure.
3442  *
3443  * This routine moves a batch of XRIs from lpfc_io_buf_list_put of HWQ 0
3444  * to expedite pool. Mark them as expedite.
3445  **/
3446 static void lpfc_create_expedite_pool(struct lpfc_hba *phba)
3447 {
3448         struct lpfc_sli4_hdw_queue *qp;
3449         struct lpfc_io_buf *lpfc_ncmd;
3450         struct lpfc_io_buf *lpfc_ncmd_next;
3451         struct lpfc_epd_pool *epd_pool;
3452         unsigned long iflag;
3453
3454         epd_pool = &phba->epd_pool;
3455         qp = &phba->sli4_hba.hdwq[0];
3456
3457         spin_lock_init(&epd_pool->lock);
3458         spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3459         spin_lock(&epd_pool->lock);
3460         INIT_LIST_HEAD(&epd_pool->list);
3461         list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3462                                  &qp->lpfc_io_buf_list_put, list) {
3463                 list_move_tail(&lpfc_ncmd->list, &epd_pool->list);
3464                 lpfc_ncmd->expedite = true;
3465                 qp->put_io_bufs--;
3466                 epd_pool->count++;
3467                 if (epd_pool->count >= XRI_BATCH)
3468                         break;
3469         }
3470         spin_unlock(&epd_pool->lock);
3471         spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3472 }
3473
3474 /**
3475  * lpfc_destroy_expedite_pool - destroy expedite pool
3476  * @phba: pointer to lpfc hba data structure.
3477  *
3478  * This routine returns XRIs from expedite pool to lpfc_io_buf_list_put
3479  * of HWQ 0. Clear the mark.
3480  **/
3481 static void lpfc_destroy_expedite_pool(struct lpfc_hba *phba)
3482 {
3483         struct lpfc_sli4_hdw_queue *qp;
3484         struct lpfc_io_buf *lpfc_ncmd;
3485         struct lpfc_io_buf *lpfc_ncmd_next;
3486         struct lpfc_epd_pool *epd_pool;
3487         unsigned long iflag;
3488
3489         epd_pool = &phba->epd_pool;
3490         qp = &phba->sli4_hba.hdwq[0];
3491
3492         spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3493         spin_lock(&epd_pool->lock);
3494         list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3495                                  &epd_pool->list, list) {
3496                 list_move_tail(&lpfc_ncmd->list,
3497                                &qp->lpfc_io_buf_list_put);
3498                 lpfc_ncmd->flags = false;
3499                 qp->put_io_bufs++;
3500                 epd_pool->count--;
3501         }
3502         spin_unlock(&epd_pool->lock);
3503         spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3504 }
3505
3506 /**
3507  * lpfc_create_multixri_pools - create multi-XRI pools
3508  * @phba: pointer to lpfc hba data structure.
3509  *
3510  * This routine initialize public, private per HWQ. Then, move XRIs from
3511  * lpfc_io_buf_list_put to public pool. High and low watermark are also
3512  * Initialized.
3513  **/
3514 void lpfc_create_multixri_pools(struct lpfc_hba *phba)
3515 {
3516         u32 i, j;
3517         u32 hwq_count;
3518         u32 count_per_hwq;
3519         struct lpfc_io_buf *lpfc_ncmd;
3520         struct lpfc_io_buf *lpfc_ncmd_next;
3521         unsigned long iflag;
3522         struct lpfc_sli4_hdw_queue *qp;
3523         struct lpfc_multixri_pool *multixri_pool;
3524         struct lpfc_pbl_pool *pbl_pool;
3525         struct lpfc_pvt_pool *pvt_pool;
3526
3527         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3528                         "1234 num_hdw_queue=%d num_present_cpu=%d common_xri_cnt=%d\n",
3529                         phba->cfg_hdw_queue, phba->sli4_hba.num_present_cpu,
3530                         phba->sli4_hba.io_xri_cnt);
3531
3532         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3533                 lpfc_create_expedite_pool(phba);
3534
3535         hwq_count = phba->cfg_hdw_queue;
3536         count_per_hwq = phba->sli4_hba.io_xri_cnt / hwq_count;
3537
3538         for (i = 0; i < hwq_count; i++) {
3539                 multixri_pool = kzalloc(sizeof(*multixri_pool), GFP_KERNEL);
3540
3541                 if (!multixri_pool) {
3542                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3543                                         "1238 Failed to allocate memory for "
3544                                         "multixri_pool\n");
3545
3546                         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3547                                 lpfc_destroy_expedite_pool(phba);
3548
3549                         j = 0;
3550                         while (j < i) {
3551                                 qp = &phba->sli4_hba.hdwq[j];
3552                                 kfree(qp->p_multixri_pool);
3553                                 j++;
3554                         }
3555                         phba->cfg_xri_rebalancing = 0;
3556                         return;
3557                 }
3558
3559                 qp = &phba->sli4_hba.hdwq[i];
3560                 qp->p_multixri_pool = multixri_pool;
3561
3562                 multixri_pool->xri_limit = count_per_hwq;
3563                 multixri_pool->rrb_next_hwqid = i;
3564
3565                 /* Deal with public free xri pool */
3566                 pbl_pool = &multixri_pool->pbl_pool;
3567                 spin_lock_init(&pbl_pool->lock);
3568                 spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3569                 spin_lock(&pbl_pool->lock);
3570                 INIT_LIST_HEAD(&pbl_pool->list);
3571                 list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3572                                          &qp->lpfc_io_buf_list_put, list) {
3573                         list_move_tail(&lpfc_ncmd->list, &pbl_pool->list);
3574                         qp->put_io_bufs--;
3575                         pbl_pool->count++;
3576                 }
3577                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3578                                 "1235 Moved %d buffers from PUT list over to pbl_pool[%d]\n",
3579                                 pbl_pool->count, i);
3580                 spin_unlock(&pbl_pool->lock);
3581                 spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3582
3583                 /* Deal with private free xri pool */
3584                 pvt_pool = &multixri_pool->pvt_pool;
3585                 pvt_pool->high_watermark = multixri_pool->xri_limit / 2;
3586                 pvt_pool->low_watermark = XRI_BATCH;
3587                 spin_lock_init(&pvt_pool->lock);
3588                 spin_lock_irqsave(&pvt_pool->lock, iflag);
3589                 INIT_LIST_HEAD(&pvt_pool->list);
3590                 pvt_pool->count = 0;
3591                 spin_unlock_irqrestore(&pvt_pool->lock, iflag);
3592         }
3593 }
3594
3595 /**
3596  * lpfc_destroy_multixri_pools - destroy multi-XRI pools
3597  * @phba: pointer to lpfc hba data structure.
3598  *
3599  * This routine returns XRIs from public/private to lpfc_io_buf_list_put.
3600  **/
3601 static void lpfc_destroy_multixri_pools(struct lpfc_hba *phba)
3602 {
3603         u32 i;
3604         u32 hwq_count;
3605         struct lpfc_io_buf *lpfc_ncmd;
3606         struct lpfc_io_buf *lpfc_ncmd_next;
3607         unsigned long iflag;
3608         struct lpfc_sli4_hdw_queue *qp;
3609         struct lpfc_multixri_pool *multixri_pool;
3610         struct lpfc_pbl_pool *pbl_pool;
3611         struct lpfc_pvt_pool *pvt_pool;
3612
3613         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
3614                 lpfc_destroy_expedite_pool(phba);
3615
3616         if (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
3617                 lpfc_sli_flush_io_rings(phba);
3618
3619         hwq_count = phba->cfg_hdw_queue;
3620
3621         for (i = 0; i < hwq_count; i++) {
3622                 qp = &phba->sli4_hba.hdwq[i];
3623                 multixri_pool = qp->p_multixri_pool;
3624                 if (!multixri_pool)
3625                         continue;
3626
3627                 qp->p_multixri_pool = NULL;
3628
3629                 spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag);
3630
3631                 /* Deal with public free xri pool */
3632                 pbl_pool = &multixri_pool->pbl_pool;
3633                 spin_lock(&pbl_pool->lock);
3634
3635                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3636                                 "1236 Moving %d buffers from pbl_pool[%d] TO PUT list\n",
3637                                 pbl_pool->count, i);
3638
3639                 list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3640                                          &pbl_pool->list, list) {
3641                         list_move_tail(&lpfc_ncmd->list,
3642                                        &qp->lpfc_io_buf_list_put);
3643                         qp->put_io_bufs++;
3644                         pbl_pool->count--;
3645                 }
3646
3647                 INIT_LIST_HEAD(&pbl_pool->list);
3648                 pbl_pool->count = 0;
3649
3650                 spin_unlock(&pbl_pool->lock);
3651
3652                 /* Deal with private free xri pool */
3653                 pvt_pool = &multixri_pool->pvt_pool;
3654                 spin_lock(&pvt_pool->lock);
3655
3656                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3657                                 "1237 Moving %d buffers from pvt_pool[%d] TO PUT list\n",
3658                                 pvt_pool->count, i);
3659
3660                 list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
3661                                          &pvt_pool->list, list) {
3662                         list_move_tail(&lpfc_ncmd->list,
3663                                        &qp->lpfc_io_buf_list_put);
3664                         qp->put_io_bufs++;
3665                         pvt_pool->count--;
3666                 }
3667
3668                 INIT_LIST_HEAD(&pvt_pool->list);
3669                 pvt_pool->count = 0;
3670
3671                 spin_unlock(&pvt_pool->lock);
3672                 spin_unlock_irqrestore(&qp->io_buf_list_put_lock, iflag);
3673
3674                 kfree(multixri_pool);
3675         }
3676 }
3677
3678 /**
3679  * lpfc_online - Initialize and bring a HBA online
3680  * @phba: pointer to lpfc hba data structure.
3681  *
3682  * This routine initializes the HBA and brings a HBA online. During this
3683  * process, the management interface is blocked to prevent user space access
3684  * to the HBA interfering with the driver initialization.
3685  *
3686  * Return codes
3687  *   0 - successful
3688  *   1 - failed
3689  **/
3690 int
3691 lpfc_online(struct lpfc_hba *phba)
3692 {
3693         struct lpfc_vport *vport;
3694         struct lpfc_vport **vports;
3695         int i, error = 0;
3696         bool vpis_cleared = false;
3697
3698         if (!phba)
3699                 return 0;
3700         vport = phba->pport;
3701
3702         if (!test_bit(FC_OFFLINE_MODE, &vport->fc_flag))
3703                 return 0;
3704
3705         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3706                         "0458 Bring Adapter online\n");
3707
3708         lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
3709
3710         if (phba->sli_rev == LPFC_SLI_REV4) {
3711                 if (lpfc_sli4_hba_setup(phba)) { /* Initialize SLI4 HBA */
3712                         lpfc_unblock_mgmt_io(phba);
3713                         return 1;
3714                 }
3715                 spin_lock_irq(&phba->hbalock);
3716                 if (!phba->sli4_hba.max_cfg_param.vpi_used)
3717                         vpis_cleared = true;
3718                 spin_unlock_irq(&phba->hbalock);
3719
3720                 /* Reestablish the local initiator port.
3721                  * The offline process destroyed the previous lport.
3722                  */
3723                 if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME &&
3724                                 !phba->nvmet_support) {
3725                         error = lpfc_nvme_create_localport(phba->pport);
3726                         if (error)
3727                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3728                                         "6132 NVME restore reg failed "
3729                                         "on nvmei error x%x\n", error);
3730                 }
3731         } else {
3732                 lpfc_sli_queue_init(phba);
3733                 if (lpfc_sli_hba_setup(phba)) { /* Initialize SLI2/SLI3 HBA */
3734                         lpfc_unblock_mgmt_io(phba);
3735                         return 1;
3736                 }
3737         }
3738
3739         vports = lpfc_create_vport_work_array(phba);
3740         if (vports != NULL) {
3741                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3742                         clear_bit(FC_OFFLINE_MODE, &vports[i]->fc_flag);
3743                         if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED)
3744                                 set_bit(FC_VPORT_NEEDS_REG_VPI,
3745                                         &vports[i]->fc_flag);
3746                         if (phba->sli_rev == LPFC_SLI_REV4) {
3747                                 set_bit(FC_VPORT_NEEDS_INIT_VPI,
3748                                         &vports[i]->fc_flag);
3749                                 if ((vpis_cleared) &&
3750                                     (vports[i]->port_type !=
3751                                         LPFC_PHYSICAL_PORT))
3752                                         vports[i]->vpi = 0;
3753                         }
3754                 }
3755         }
3756         lpfc_destroy_vport_work_array(phba, vports);
3757
3758         if (phba->cfg_xri_rebalancing)
3759                 lpfc_create_multixri_pools(phba);
3760
3761         lpfc_cpuhp_add(phba);
3762
3763         lpfc_unblock_mgmt_io(phba);
3764         return 0;
3765 }
3766
3767 /**
3768  * lpfc_unblock_mgmt_io - Mark a HBA's management interface to be not blocked
3769  * @phba: pointer to lpfc hba data structure.
3770  *
3771  * This routine marks a HBA's management interface as not blocked. Once the
3772  * HBA's management interface is marked as not blocked, all the user space
3773  * access to the HBA, whether they are from sysfs interface or libdfc
3774  * interface will be allowed. The HBA is set to block the management interface
3775  * when the driver prepares the HBA interface for online or offline and then
3776  * set to unblock the management interface afterwards.
3777  **/
3778 void
3779 lpfc_unblock_mgmt_io(struct lpfc_hba * phba)
3780 {
3781         unsigned long iflag;
3782
3783         spin_lock_irqsave(&phba->hbalock, iflag);
3784         phba->sli.sli_flag &= ~LPFC_BLOCK_MGMT_IO;
3785         spin_unlock_irqrestore(&phba->hbalock, iflag);
3786 }
3787
3788 /**
3789  * lpfc_offline_prep - Prepare a HBA to be brought offline
3790  * @phba: pointer to lpfc hba data structure.
3791  * @mbx_action: flag for mailbox shutdown action.
3792  *
3793  * This routine is invoked to prepare a HBA to be brought offline. It performs
3794  * unregistration login to all the nodes on all vports and flushes the mailbox
3795  * queue to make it ready to be brought offline.
3796  **/
3797 void
3798 lpfc_offline_prep(struct lpfc_hba *phba, int mbx_action)
3799 {
3800         struct lpfc_vport *vport = phba->pport;
3801         struct lpfc_nodelist  *ndlp, *next_ndlp;
3802         struct lpfc_vport **vports;
3803         struct Scsi_Host *shost;
3804         int i;
3805         int offline;
3806         bool hba_pci_err;
3807
3808         if (test_bit(FC_OFFLINE_MODE, &vport->fc_flag))
3809                 return;
3810
3811         lpfc_block_mgmt_io(phba, mbx_action);
3812
3813         lpfc_linkdown(phba);
3814
3815         offline =  pci_channel_offline(phba->pcidev);
3816         hba_pci_err = test_bit(HBA_PCI_ERR, &phba->bit_flags);
3817
3818         /* Issue an unreg_login to all nodes on all vports */
3819         vports = lpfc_create_vport_work_array(phba);
3820         if (vports != NULL) {
3821                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3822                         if (test_bit(FC_UNLOADING, &vports[i]->load_flag))
3823                                 continue;
3824                         shost = lpfc_shost_from_vport(vports[i]);
3825                         spin_lock_irq(shost->host_lock);
3826                         vports[i]->vpi_state &= ~LPFC_VPI_REGISTERED;
3827                         spin_unlock_irq(shost->host_lock);
3828                         set_bit(FC_VPORT_NEEDS_REG_VPI, &vports[i]->fc_flag);
3829                         clear_bit(FC_VFI_REGISTERED, &vports[i]->fc_flag);
3830
3831                         list_for_each_entry_safe(ndlp, next_ndlp,
3832                                                  &vports[i]->fc_nodes,
3833                                                  nlp_listp) {
3834
3835                                 spin_lock_irq(&ndlp->lock);
3836                                 ndlp->nlp_flag &= ~NLP_NPR_ADISC;
3837                                 spin_unlock_irq(&ndlp->lock);
3838
3839                                 if (offline || hba_pci_err) {
3840                                         spin_lock_irq(&ndlp->lock);
3841                                         ndlp->nlp_flag &= ~(NLP_UNREG_INP |
3842                                                             NLP_RPI_REGISTERED);
3843                                         spin_unlock_irq(&ndlp->lock);
3844                                         if (phba->sli_rev == LPFC_SLI_REV4)
3845                                                 lpfc_sli_rpi_release(vports[i],
3846                                                                      ndlp);
3847                                 } else {
3848                                         lpfc_unreg_rpi(vports[i], ndlp);
3849                                 }
3850                                 /*
3851                                  * Whenever an SLI4 port goes offline, free the
3852                                  * RPI. Get a new RPI when the adapter port
3853                                  * comes back online.
3854                                  */
3855                                 if (phba->sli_rev == LPFC_SLI_REV4) {
3856                                         lpfc_printf_vlog(vports[i], KERN_INFO,
3857                                                  LOG_NODE | LOG_DISCOVERY,
3858                                                  "0011 Free RPI x%x on "
3859                                                  "ndlp: x%px did x%x\n",
3860                                                  ndlp->nlp_rpi, ndlp,
3861                                                  ndlp->nlp_DID);
3862                                         lpfc_sli4_free_rpi(phba, ndlp->nlp_rpi);
3863                                         ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
3864                                 }
3865
3866                                 if (ndlp->nlp_type & NLP_FABRIC) {
3867                                         lpfc_disc_state_machine(vports[i], ndlp,
3868                                                 NULL, NLP_EVT_DEVICE_RECOVERY);
3869
3870                                         /* Don't remove the node unless the node
3871                                          * has been unregistered with the
3872                                          * transport, and we're not in recovery
3873                                          * before dev_loss_tmo triggered.
3874                                          * Otherwise, let dev_loss take care of
3875                                          * the node.
3876                                          */
3877                                         if (!(ndlp->save_flags &
3878                                               NLP_IN_RECOV_POST_DEV_LOSS) &&
3879                                             !(ndlp->fc4_xpt_flags &
3880                                               (NVME_XPT_REGD | SCSI_XPT_REGD)))
3881                                                 lpfc_disc_state_machine
3882                                                         (vports[i], ndlp,
3883                                                          NULL,
3884                                                          NLP_EVT_DEVICE_RM);
3885                                 }
3886                         }
3887                 }
3888         }
3889         lpfc_destroy_vport_work_array(phba, vports);
3890
3891         lpfc_sli_mbox_sys_shutdown(phba, mbx_action);
3892
3893         if (phba->wq)
3894                 flush_workqueue(phba->wq);
3895 }
3896
3897 /**
3898  * lpfc_offline - Bring a HBA offline
3899  * @phba: pointer to lpfc hba data structure.
3900  *
3901  * This routine actually brings a HBA offline. It stops all the timers
3902  * associated with the HBA, brings down the SLI layer, and eventually
3903  * marks the HBA as in offline state for the upper layer protocol.
3904  **/
3905 void
3906 lpfc_offline(struct lpfc_hba *phba)
3907 {
3908         struct Scsi_Host  *shost;
3909         struct lpfc_vport **vports;
3910         int i;
3911
3912         if (test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
3913                 return;
3914
3915         /* stop port and all timers associated with this hba */
3916         lpfc_stop_port(phba);
3917
3918         /* Tear down the local and target port registrations.  The
3919          * nvme transports need to cleanup.
3920          */
3921         lpfc_nvmet_destroy_targetport(phba);
3922         lpfc_nvme_destroy_localport(phba->pport);
3923
3924         vports = lpfc_create_vport_work_array(phba);
3925         if (vports != NULL)
3926                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
3927                         lpfc_stop_vport_timers(vports[i]);
3928         lpfc_destroy_vport_work_array(phba, vports);
3929         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
3930                         "0460 Bring Adapter offline\n");
3931         /* Bring down the SLI Layer and cleanup.  The HBA is offline
3932            now.  */
3933         lpfc_sli_hba_down(phba);
3934         spin_lock_irq(&phba->hbalock);
3935         phba->work_ha = 0;
3936         spin_unlock_irq(&phba->hbalock);
3937         vports = lpfc_create_vport_work_array(phba);
3938         if (vports != NULL)
3939                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3940                         shost = lpfc_shost_from_vport(vports[i]);
3941                         spin_lock_irq(shost->host_lock);
3942                         vports[i]->work_port_events = 0;
3943                         spin_unlock_irq(shost->host_lock);
3944                         set_bit(FC_OFFLINE_MODE, &vports[i]->fc_flag);
3945                 }
3946         lpfc_destroy_vport_work_array(phba, vports);
3947         /* If OFFLINE flag is clear (i.e. unloading), cpuhp removal is handled
3948          * in hba_unset
3949          */
3950         if (test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
3951                 __lpfc_cpuhp_remove(phba);
3952
3953         if (phba->cfg_xri_rebalancing)
3954                 lpfc_destroy_multixri_pools(phba);
3955 }
3956
3957 /**
3958  * lpfc_scsi_free - Free all the SCSI buffers and IOCBs from driver lists
3959  * @phba: pointer to lpfc hba data structure.
3960  *
3961  * This routine is to free all the SCSI buffers and IOCBs from the driver
3962  * list back to kernel. It is called from lpfc_pci_remove_one to free
3963  * the internal resources before the device is removed from the system.
3964  **/
3965 static void
3966 lpfc_scsi_free(struct lpfc_hba *phba)
3967 {
3968         struct lpfc_io_buf *sb, *sb_next;
3969
3970         if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
3971                 return;
3972
3973         spin_lock_irq(&phba->hbalock);
3974
3975         /* Release all the lpfc_scsi_bufs maintained by this host. */
3976
3977         spin_lock(&phba->scsi_buf_list_put_lock);
3978         list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_put,
3979                                  list) {
3980                 list_del(&sb->list);
3981                 dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3982                               sb->dma_handle);
3983                 kfree(sb);
3984                 phba->total_scsi_bufs--;
3985         }
3986         spin_unlock(&phba->scsi_buf_list_put_lock);
3987
3988         spin_lock(&phba->scsi_buf_list_get_lock);
3989         list_for_each_entry_safe(sb, sb_next, &phba->lpfc_scsi_buf_list_get,
3990                                  list) {
3991                 list_del(&sb->list);
3992                 dma_pool_free(phba->lpfc_sg_dma_buf_pool, sb->data,
3993                               sb->dma_handle);
3994                 kfree(sb);
3995                 phba->total_scsi_bufs--;
3996         }
3997         spin_unlock(&phba->scsi_buf_list_get_lock);
3998         spin_unlock_irq(&phba->hbalock);
3999 }
4000
4001 /**
4002  * lpfc_io_free - Free all the IO buffers and IOCBs from driver lists
4003  * @phba: pointer to lpfc hba data structure.
4004  *
4005  * This routine is to free all the IO buffers and IOCBs from the driver
4006  * list back to kernel. It is called from lpfc_pci_remove_one to free
4007  * the internal resources before the device is removed from the system.
4008  **/
4009 void
4010 lpfc_io_free(struct lpfc_hba *phba)
4011 {
4012         struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
4013         struct lpfc_sli4_hdw_queue *qp;
4014         int idx;
4015
4016         for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4017                 qp = &phba->sli4_hba.hdwq[idx];
4018                 /* Release all the lpfc_nvme_bufs maintained by this host. */
4019                 spin_lock(&qp->io_buf_list_put_lock);
4020                 list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4021                                          &qp->lpfc_io_buf_list_put,
4022                                          list) {
4023                         list_del(&lpfc_ncmd->list);
4024                         qp->put_io_bufs--;
4025                         dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4026                                       lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4027                         if (phba->cfg_xpsgl && !phba->nvmet_support)
4028                                 lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4029                         lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4030                         kfree(lpfc_ncmd);
4031                         qp->total_io_bufs--;
4032                 }
4033                 spin_unlock(&qp->io_buf_list_put_lock);
4034
4035                 spin_lock(&qp->io_buf_list_get_lock);
4036                 list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4037                                          &qp->lpfc_io_buf_list_get,
4038                                          list) {
4039                         list_del(&lpfc_ncmd->list);
4040                         qp->get_io_bufs--;
4041                         dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4042                                       lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4043                         if (phba->cfg_xpsgl && !phba->nvmet_support)
4044                                 lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
4045                         lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
4046                         kfree(lpfc_ncmd);
4047                         qp->total_io_bufs--;
4048                 }
4049                 spin_unlock(&qp->io_buf_list_get_lock);
4050         }
4051 }
4052
4053 /**
4054  * lpfc_sli4_els_sgl_update - update ELS xri-sgl sizing and mapping
4055  * @phba: pointer to lpfc hba data structure.
4056  *
4057  * This routine first calculates the sizes of the current els and allocated
4058  * scsi sgl lists, and then goes through all sgls to updates the physical
4059  * XRIs assigned due to port function reset. During port initialization, the
4060  * current els and allocated scsi sgl lists are 0s.
4061  *
4062  * Return codes
4063  *   0 - successful (for now, it always returns 0)
4064  **/
4065 int
4066 lpfc_sli4_els_sgl_update(struct lpfc_hba *phba)
4067 {
4068         struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4069         uint16_t i, lxri, xri_cnt, els_xri_cnt;
4070         LIST_HEAD(els_sgl_list);
4071         int rc;
4072
4073         /*
4074          * update on pci function's els xri-sgl list
4075          */
4076         els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4077
4078         if (els_xri_cnt > phba->sli4_hba.els_xri_cnt) {
4079                 /* els xri-sgl expanded */
4080                 xri_cnt = els_xri_cnt - phba->sli4_hba.els_xri_cnt;
4081                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4082                                 "3157 ELS xri-sgl count increased from "
4083                                 "%d to %d\n", phba->sli4_hba.els_xri_cnt,
4084                                 els_xri_cnt);
4085                 /* allocate the additional els sgls */
4086                 for (i = 0; i < xri_cnt; i++) {
4087                         sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4088                                              GFP_KERNEL);
4089                         if (sglq_entry == NULL) {
4090                                 lpfc_printf_log(phba, KERN_ERR,
4091                                                 LOG_TRACE_EVENT,
4092                                                 "2562 Failure to allocate an "
4093                                                 "ELS sgl entry:%d\n", i);
4094                                 rc = -ENOMEM;
4095                                 goto out_free_mem;
4096                         }
4097                         sglq_entry->buff_type = GEN_BUFF_TYPE;
4098                         sglq_entry->virt = lpfc_mbuf_alloc(phba, 0,
4099                                                            &sglq_entry->phys);
4100                         if (sglq_entry->virt == NULL) {
4101                                 kfree(sglq_entry);
4102                                 lpfc_printf_log(phba, KERN_ERR,
4103                                                 LOG_TRACE_EVENT,
4104                                                 "2563 Failure to allocate an "
4105                                                 "ELS mbuf:%d\n", i);
4106                                 rc = -ENOMEM;
4107                                 goto out_free_mem;
4108                         }
4109                         sglq_entry->sgl = sglq_entry->virt;
4110                         memset(sglq_entry->sgl, 0, LPFC_BPL_SIZE);
4111                         sglq_entry->state = SGL_FREED;
4112                         list_add_tail(&sglq_entry->list, &els_sgl_list);
4113                 }
4114                 spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4115                 list_splice_init(&els_sgl_list,
4116                                  &phba->sli4_hba.lpfc_els_sgl_list);
4117                 spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4118         } else if (els_xri_cnt < phba->sli4_hba.els_xri_cnt) {
4119                 /* els xri-sgl shrinked */
4120                 xri_cnt = phba->sli4_hba.els_xri_cnt - els_xri_cnt;
4121                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4122                                 "3158 ELS xri-sgl count decreased from "
4123                                 "%d to %d\n", phba->sli4_hba.els_xri_cnt,
4124                                 els_xri_cnt);
4125                 spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
4126                 list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list,
4127                                  &els_sgl_list);
4128                 /* release extra els sgls from list */
4129                 for (i = 0; i < xri_cnt; i++) {
4130                         list_remove_head(&els_sgl_list,
4131                                          sglq_entry, struct lpfc_sglq, list);
4132                         if (sglq_entry) {
4133                                 __lpfc_mbuf_free(phba, sglq_entry->virt,
4134                                                  sglq_entry->phys);
4135                                 kfree(sglq_entry);
4136                         }
4137                 }
4138                 list_splice_init(&els_sgl_list,
4139                                  &phba->sli4_hba.lpfc_els_sgl_list);
4140                 spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
4141         } else
4142                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4143                                 "3163 ELS xri-sgl count unchanged: %d\n",
4144                                 els_xri_cnt);
4145         phba->sli4_hba.els_xri_cnt = els_xri_cnt;
4146
4147         /* update xris to els sgls on the list */
4148         sglq_entry = NULL;
4149         sglq_entry_next = NULL;
4150         list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4151                                  &phba->sli4_hba.lpfc_els_sgl_list, list) {
4152                 lxri = lpfc_sli4_next_xritag(phba);
4153                 if (lxri == NO_XRI) {
4154                         lpfc_printf_log(phba, KERN_ERR,
4155                                         LOG_TRACE_EVENT,
4156                                         "2400 Failed to allocate xri for "
4157                                         "ELS sgl\n");
4158                         rc = -ENOMEM;
4159                         goto out_free_mem;
4160                 }
4161                 sglq_entry->sli4_lxritag = lxri;
4162                 sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4163         }
4164         return 0;
4165
4166 out_free_mem:
4167         lpfc_free_els_sgl_list(phba);
4168         return rc;
4169 }
4170
4171 /**
4172  * lpfc_sli4_nvmet_sgl_update - update xri-sgl sizing and mapping
4173  * @phba: pointer to lpfc hba data structure.
4174  *
4175  * This routine first calculates the sizes of the current els and allocated
4176  * scsi sgl lists, and then goes through all sgls to updates the physical
4177  * XRIs assigned due to port function reset. During port initialization, the
4178  * current els and allocated scsi sgl lists are 0s.
4179  *
4180  * Return codes
4181  *   0 - successful (for now, it always returns 0)
4182  **/
4183 int
4184 lpfc_sli4_nvmet_sgl_update(struct lpfc_hba *phba)
4185 {
4186         struct lpfc_sglq *sglq_entry = NULL, *sglq_entry_next = NULL;
4187         uint16_t i, lxri, xri_cnt, els_xri_cnt;
4188         uint16_t nvmet_xri_cnt;
4189         LIST_HEAD(nvmet_sgl_list);
4190         int rc;
4191
4192         /*
4193          * update on pci function's nvmet xri-sgl list
4194          */
4195         els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4196
4197         /* For NVMET, ALL remaining XRIs are dedicated for IO processing */
4198         nvmet_xri_cnt = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4199         if (nvmet_xri_cnt > phba->sli4_hba.nvmet_xri_cnt) {
4200                 /* els xri-sgl expanded */
4201                 xri_cnt = nvmet_xri_cnt - phba->sli4_hba.nvmet_xri_cnt;
4202                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4203                                 "6302 NVMET xri-sgl cnt grew from %d to %d\n",
4204                                 phba->sli4_hba.nvmet_xri_cnt, nvmet_xri_cnt);
4205                 /* allocate the additional nvmet sgls */
4206                 for (i = 0; i < xri_cnt; i++) {
4207                         sglq_entry = kzalloc(sizeof(struct lpfc_sglq),
4208                                              GFP_KERNEL);
4209                         if (sglq_entry == NULL) {
4210                                 lpfc_printf_log(phba, KERN_ERR,
4211                                                 LOG_TRACE_EVENT,
4212                                                 "6303 Failure to allocate an "
4213                                                 "NVMET sgl entry:%d\n", i);
4214                                 rc = -ENOMEM;
4215                                 goto out_free_mem;
4216                         }
4217                         sglq_entry->buff_type = NVMET_BUFF_TYPE;
4218                         sglq_entry->virt = lpfc_nvmet_buf_alloc(phba, 0,
4219                                                            &sglq_entry->phys);
4220                         if (sglq_entry->virt == NULL) {
4221                                 kfree(sglq_entry);
4222                                 lpfc_printf_log(phba, KERN_ERR,
4223                                                 LOG_TRACE_EVENT,
4224                                                 "6304 Failure to allocate an "
4225                                                 "NVMET buf:%d\n", i);
4226                                 rc = -ENOMEM;
4227                                 goto out_free_mem;
4228                         }
4229                         sglq_entry->sgl = sglq_entry->virt;
4230                         memset(sglq_entry->sgl, 0,
4231                                phba->cfg_sg_dma_buf_size);
4232                         sglq_entry->state = SGL_FREED;
4233                         list_add_tail(&sglq_entry->list, &nvmet_sgl_list);
4234                 }
4235                 spin_lock_irq(&phba->hbalock);
4236                 spin_lock(&phba->sli4_hba.sgl_list_lock);
4237                 list_splice_init(&nvmet_sgl_list,
4238                                  &phba->sli4_hba.lpfc_nvmet_sgl_list);
4239                 spin_unlock(&phba->sli4_hba.sgl_list_lock);
4240                 spin_unlock_irq(&phba->hbalock);
4241         } else if (nvmet_xri_cnt < phba->sli4_hba.nvmet_xri_cnt) {
4242                 /* nvmet xri-sgl shrunk */
4243                 xri_cnt = phba->sli4_hba.nvmet_xri_cnt - nvmet_xri_cnt;
4244                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4245                                 "6305 NVMET xri-sgl count decreased from "
4246                                 "%d to %d\n", phba->sli4_hba.nvmet_xri_cnt,
4247                                 nvmet_xri_cnt);
4248                 spin_lock_irq(&phba->hbalock);
4249                 spin_lock(&phba->sli4_hba.sgl_list_lock);
4250                 list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list,
4251                                  &nvmet_sgl_list);
4252                 /* release extra nvmet sgls from list */
4253                 for (i = 0; i < xri_cnt; i++) {
4254                         list_remove_head(&nvmet_sgl_list,
4255                                          sglq_entry, struct lpfc_sglq, list);
4256                         if (sglq_entry) {
4257                                 lpfc_nvmet_buf_free(phba, sglq_entry->virt,
4258                                                     sglq_entry->phys);
4259                                 kfree(sglq_entry);
4260                         }
4261                 }
4262                 list_splice_init(&nvmet_sgl_list,
4263                                  &phba->sli4_hba.lpfc_nvmet_sgl_list);
4264                 spin_unlock(&phba->sli4_hba.sgl_list_lock);
4265                 spin_unlock_irq(&phba->hbalock);
4266         } else
4267                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4268                                 "6306 NVMET xri-sgl count unchanged: %d\n",
4269                                 nvmet_xri_cnt);
4270         phba->sli4_hba.nvmet_xri_cnt = nvmet_xri_cnt;
4271
4272         /* update xris to nvmet sgls on the list */
4273         sglq_entry = NULL;
4274         sglq_entry_next = NULL;
4275         list_for_each_entry_safe(sglq_entry, sglq_entry_next,
4276                                  &phba->sli4_hba.lpfc_nvmet_sgl_list, list) {
4277                 lxri = lpfc_sli4_next_xritag(phba);
4278                 if (lxri == NO_XRI) {
4279                         lpfc_printf_log(phba, KERN_ERR,
4280                                         LOG_TRACE_EVENT,
4281                                         "6307 Failed to allocate xri for "
4282                                         "NVMET sgl\n");
4283                         rc = -ENOMEM;
4284                         goto out_free_mem;
4285                 }
4286                 sglq_entry->sli4_lxritag = lxri;
4287                 sglq_entry->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4288         }
4289         return 0;
4290
4291 out_free_mem:
4292         lpfc_free_nvmet_sgl_list(phba);
4293         return rc;
4294 }
4295
4296 int
4297 lpfc_io_buf_flush(struct lpfc_hba *phba, struct list_head *cbuf)
4298 {
4299         LIST_HEAD(blist);
4300         struct lpfc_sli4_hdw_queue *qp;
4301         struct lpfc_io_buf *lpfc_cmd;
4302         struct lpfc_io_buf *iobufp, *prev_iobufp;
4303         int idx, cnt, xri, inserted;
4304
4305         cnt = 0;
4306         for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4307                 qp = &phba->sli4_hba.hdwq[idx];
4308                 spin_lock_irq(&qp->io_buf_list_get_lock);
4309                 spin_lock(&qp->io_buf_list_put_lock);
4310
4311                 /* Take everything off the get and put lists */
4312                 list_splice_init(&qp->lpfc_io_buf_list_get, &blist);
4313                 list_splice(&qp->lpfc_io_buf_list_put, &blist);
4314                 INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
4315                 INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
4316                 cnt += qp->get_io_bufs + qp->put_io_bufs;
4317                 qp->get_io_bufs = 0;
4318                 qp->put_io_bufs = 0;
4319                 qp->total_io_bufs = 0;
4320                 spin_unlock(&qp->io_buf_list_put_lock);
4321                 spin_unlock_irq(&qp->io_buf_list_get_lock);
4322         }
4323
4324         /*
4325          * Take IO buffers off blist and put on cbuf sorted by XRI.
4326          * This is because POST_SGL takes a sequential range of XRIs
4327          * to post to the firmware.
4328          */
4329         for (idx = 0; idx < cnt; idx++) {
4330                 list_remove_head(&blist, lpfc_cmd, struct lpfc_io_buf, list);
4331                 if (!lpfc_cmd)
4332                         return cnt;
4333                 if (idx == 0) {
4334                         list_add_tail(&lpfc_cmd->list, cbuf);
4335                         continue;
4336                 }
4337                 xri = lpfc_cmd->cur_iocbq.sli4_xritag;
4338                 inserted = 0;
4339                 prev_iobufp = NULL;
4340                 list_for_each_entry(iobufp, cbuf, list) {
4341                         if (xri < iobufp->cur_iocbq.sli4_xritag) {
4342                                 if (prev_iobufp)
4343                                         list_add(&lpfc_cmd->list,
4344                                                  &prev_iobufp->list);
4345                                 else
4346                                         list_add(&lpfc_cmd->list, cbuf);
4347                                 inserted = 1;
4348                                 break;
4349                         }
4350                         prev_iobufp = iobufp;
4351                 }
4352                 if (!inserted)
4353                         list_add_tail(&lpfc_cmd->list, cbuf);
4354         }
4355         return cnt;
4356 }
4357
4358 int
4359 lpfc_io_buf_replenish(struct lpfc_hba *phba, struct list_head *cbuf)
4360 {
4361         struct lpfc_sli4_hdw_queue *qp;
4362         struct lpfc_io_buf *lpfc_cmd;
4363         int idx, cnt;
4364         unsigned long iflags;
4365
4366         qp = phba->sli4_hba.hdwq;
4367         cnt = 0;
4368         while (!list_empty(cbuf)) {
4369                 for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
4370                         list_remove_head(cbuf, lpfc_cmd,
4371                                          struct lpfc_io_buf, list);
4372                         if (!lpfc_cmd)
4373                                 return cnt;
4374                         cnt++;
4375                         qp = &phba->sli4_hba.hdwq[idx];
4376                         lpfc_cmd->hdwq_no = idx;
4377                         lpfc_cmd->hdwq = qp;
4378                         lpfc_cmd->cur_iocbq.cmd_cmpl = NULL;
4379                         spin_lock_irqsave(&qp->io_buf_list_put_lock, iflags);
4380                         list_add_tail(&lpfc_cmd->list,
4381                                       &qp->lpfc_io_buf_list_put);
4382                         qp->put_io_bufs++;
4383                         qp->total_io_bufs++;
4384                         spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
4385                                                iflags);
4386                 }
4387         }
4388         return cnt;
4389 }
4390
4391 /**
4392  * lpfc_sli4_io_sgl_update - update xri-sgl sizing and mapping
4393  * @phba: pointer to lpfc hba data structure.
4394  *
4395  * This routine first calculates the sizes of the current els and allocated
4396  * scsi sgl lists, and then goes through all sgls to updates the physical
4397  * XRIs assigned due to port function reset. During port initialization, the
4398  * current els and allocated scsi sgl lists are 0s.
4399  *
4400  * Return codes
4401  *   0 - successful (for now, it always returns 0)
4402  **/
4403 int
4404 lpfc_sli4_io_sgl_update(struct lpfc_hba *phba)
4405 {
4406         struct lpfc_io_buf *lpfc_ncmd = NULL, *lpfc_ncmd_next = NULL;
4407         uint16_t i, lxri, els_xri_cnt;
4408         uint16_t io_xri_cnt, io_xri_max;
4409         LIST_HEAD(io_sgl_list);
4410         int rc, cnt;
4411
4412         /*
4413          * update on pci function's allocated nvme xri-sgl list
4414          */
4415
4416         /* maximum number of xris available for nvme buffers */
4417         els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
4418         io_xri_max = phba->sli4_hba.max_cfg_param.max_xri - els_xri_cnt;
4419         phba->sli4_hba.io_xri_max = io_xri_max;
4420
4421         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4422                         "6074 Current allocated XRI sgl count:%d, "
4423                         "maximum XRI count:%d els_xri_cnt:%d\n\n",
4424                         phba->sli4_hba.io_xri_cnt,
4425                         phba->sli4_hba.io_xri_max,
4426                         els_xri_cnt);
4427
4428         cnt = lpfc_io_buf_flush(phba, &io_sgl_list);
4429
4430         if (phba->sli4_hba.io_xri_cnt > phba->sli4_hba.io_xri_max) {
4431                 /* max nvme xri shrunk below the allocated nvme buffers */
4432                 io_xri_cnt = phba->sli4_hba.io_xri_cnt -
4433                                         phba->sli4_hba.io_xri_max;
4434                 /* release the extra allocated nvme buffers */
4435                 for (i = 0; i < io_xri_cnt; i++) {
4436                         list_remove_head(&io_sgl_list, lpfc_ncmd,
4437                                          struct lpfc_io_buf, list);
4438                         if (lpfc_ncmd) {
4439                                 dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4440                                               lpfc_ncmd->data,
4441                                               lpfc_ncmd->dma_handle);
4442                                 kfree(lpfc_ncmd);
4443                         }
4444                 }
4445                 phba->sli4_hba.io_xri_cnt -= io_xri_cnt;
4446         }
4447
4448         /* update xris associated to remaining allocated nvme buffers */
4449         lpfc_ncmd = NULL;
4450         lpfc_ncmd_next = NULL;
4451         phba->sli4_hba.io_xri_cnt = cnt;
4452         list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
4453                                  &io_sgl_list, list) {
4454                 lxri = lpfc_sli4_next_xritag(phba);
4455                 if (lxri == NO_XRI) {
4456                         lpfc_printf_log(phba, KERN_ERR,
4457                                         LOG_TRACE_EVENT,
4458                                         "6075 Failed to allocate xri for "
4459                                         "nvme buffer\n");
4460                         rc = -ENOMEM;
4461                         goto out_free_mem;
4462                 }
4463                 lpfc_ncmd->cur_iocbq.sli4_lxritag = lxri;
4464                 lpfc_ncmd->cur_iocbq.sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4465         }
4466         cnt = lpfc_io_buf_replenish(phba, &io_sgl_list);
4467         return 0;
4468
4469 out_free_mem:
4470         lpfc_io_free(phba);
4471         return rc;
4472 }
4473
4474 /**
4475  * lpfc_new_io_buf - IO buffer allocator for HBA with SLI4 IF spec
4476  * @phba: Pointer to lpfc hba data structure.
4477  * @num_to_alloc: The requested number of buffers to allocate.
4478  *
4479  * This routine allocates nvme buffers for device with SLI-4 interface spec,
4480  * the nvme buffer contains all the necessary information needed to initiate
4481  * an I/O. After allocating up to @num_to_allocate IO buffers and put
4482  * them on a list, it post them to the port by using SGL block post.
4483  *
4484  * Return codes:
4485  *   int - number of IO buffers that were allocated and posted.
4486  *   0 = failure, less than num_to_alloc is a partial failure.
4487  **/
4488 int
4489 lpfc_new_io_buf(struct lpfc_hba *phba, int num_to_alloc)
4490 {
4491         struct lpfc_io_buf *lpfc_ncmd;
4492         struct lpfc_iocbq *pwqeq;
4493         uint16_t iotag, lxri = 0;
4494         int bcnt, num_posted;
4495         LIST_HEAD(prep_nblist);
4496         LIST_HEAD(post_nblist);
4497         LIST_HEAD(nvme_nblist);
4498
4499         phba->sli4_hba.io_xri_cnt = 0;
4500         for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
4501                 lpfc_ncmd = kzalloc(sizeof(*lpfc_ncmd), GFP_KERNEL);
4502                 if (!lpfc_ncmd)
4503                         break;
4504                 /*
4505                  * Get memory from the pci pool to map the virt space to
4506                  * pci bus space for an I/O. The DMA buffer includes the
4507                  * number of SGE's necessary to support the sg_tablesize.
4508                  */
4509                 lpfc_ncmd->data = dma_pool_zalloc(phba->lpfc_sg_dma_buf_pool,
4510                                                   GFP_KERNEL,
4511                                                   &lpfc_ncmd->dma_handle);
4512                 if (!lpfc_ncmd->data) {
4513                         kfree(lpfc_ncmd);
4514                         break;
4515                 }
4516
4517                 if (phba->cfg_xpsgl && !phba->nvmet_support) {
4518                         INIT_LIST_HEAD(&lpfc_ncmd->dma_sgl_xtra_list);
4519                 } else {
4520                         /*
4521                          * 4K Page alignment is CRITICAL to BlockGuard, double
4522                          * check to be sure.
4523                          */
4524                         if ((phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
4525                             (((unsigned long)(lpfc_ncmd->data) &
4526                             (unsigned long)(SLI4_PAGE_SIZE - 1)) != 0)) {
4527                                 lpfc_printf_log(phba, KERN_ERR,
4528                                                 LOG_TRACE_EVENT,
4529                                                 "3369 Memory alignment err: "
4530                                                 "addr=%lx\n",
4531                                                 (unsigned long)lpfc_ncmd->data);
4532                                 dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4533                                               lpfc_ncmd->data,
4534                                               lpfc_ncmd->dma_handle);
4535                                 kfree(lpfc_ncmd);
4536                                 break;
4537                         }
4538                 }
4539
4540                 INIT_LIST_HEAD(&lpfc_ncmd->dma_cmd_rsp_list);
4541
4542                 lxri = lpfc_sli4_next_xritag(phba);
4543                 if (lxri == NO_XRI) {
4544                         dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4545                                       lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4546                         kfree(lpfc_ncmd);
4547                         break;
4548                 }
4549                 pwqeq = &lpfc_ncmd->cur_iocbq;
4550
4551                 /* Allocate iotag for lpfc_ncmd->cur_iocbq. */
4552                 iotag = lpfc_sli_next_iotag(phba, pwqeq);
4553                 if (iotag == 0) {
4554                         dma_pool_free(phba->lpfc_sg_dma_buf_pool,
4555                                       lpfc_ncmd->data, lpfc_ncmd->dma_handle);
4556                         kfree(lpfc_ncmd);
4557                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4558                                         "6121 Failed to allocate IOTAG for"
4559                                         " XRI:0x%x\n", lxri);
4560                         lpfc_sli4_free_xri(phba, lxri);
4561                         break;
4562                 }
4563                 pwqeq->sli4_lxritag = lxri;
4564                 pwqeq->sli4_xritag = phba->sli4_hba.xri_ids[lxri];
4565
4566                 /* Initialize local short-hand pointers. */
4567                 lpfc_ncmd->dma_sgl = lpfc_ncmd->data;
4568                 lpfc_ncmd->dma_phys_sgl = lpfc_ncmd->dma_handle;
4569                 lpfc_ncmd->cur_iocbq.io_buf = lpfc_ncmd;
4570                 spin_lock_init(&lpfc_ncmd->buf_lock);
4571
4572                 /* add the nvme buffer to a post list */
4573                 list_add_tail(&lpfc_ncmd->list, &post_nblist);
4574                 phba->sli4_hba.io_xri_cnt++;
4575         }
4576         lpfc_printf_log(phba, KERN_INFO, LOG_NVME,
4577                         "6114 Allocate %d out of %d requested new NVME "
4578                         "buffers of size x%zu bytes\n", bcnt, num_to_alloc,
4579                         sizeof(*lpfc_ncmd));
4580
4581
4582         /* post the list of nvme buffer sgls to port if available */
4583         if (!list_empty(&post_nblist))
4584                 num_posted = lpfc_sli4_post_io_sgl_list(
4585                                 phba, &post_nblist, bcnt);
4586         else
4587                 num_posted = 0;
4588
4589         return num_posted;
4590 }
4591
4592 static uint64_t
4593 lpfc_get_wwpn(struct lpfc_hba *phba)
4594 {
4595         uint64_t wwn;
4596         int rc;
4597         LPFC_MBOXQ_t *mboxq;
4598         MAILBOX_t *mb;
4599
4600         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
4601                                                 GFP_KERNEL);
4602         if (!mboxq)
4603                 return (uint64_t)-1;
4604
4605         /* First get WWN of HBA instance */
4606         lpfc_read_nv(phba, mboxq);
4607         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4608         if (rc != MBX_SUCCESS) {
4609                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4610                                 "6019 Mailbox failed , mbxCmd x%x "
4611                                 "READ_NV, mbxStatus x%x\n",
4612                                 bf_get(lpfc_mqe_command, &mboxq->u.mqe),
4613                                 bf_get(lpfc_mqe_status, &mboxq->u.mqe));
4614                 mempool_free(mboxq, phba->mbox_mem_pool);
4615                 return (uint64_t) -1;
4616         }
4617         mb = &mboxq->u.mb;
4618         memcpy(&wwn, (char *)mb->un.varRDnvp.portname, sizeof(uint64_t));
4619         /* wwn is WWPN of HBA instance */
4620         mempool_free(mboxq, phba->mbox_mem_pool);
4621         if (phba->sli_rev == LPFC_SLI_REV4)
4622                 return be64_to_cpu(wwn);
4623         else
4624                 return rol64(wwn, 32);
4625 }
4626
4627 static unsigned short lpfc_get_sg_tablesize(struct lpfc_hba *phba)
4628 {
4629         if (phba->sli_rev == LPFC_SLI_REV4)
4630                 if (phba->cfg_xpsgl && !phba->nvmet_support)
4631                         return LPFC_MAX_SG_TABLESIZE;
4632                 else
4633                         return phba->cfg_scsi_seg_cnt;
4634         else
4635                 return phba->cfg_sg_seg_cnt;
4636 }
4637
4638 /**
4639  * lpfc_vmid_res_alloc - Allocates resources for VMID
4640  * @phba: pointer to lpfc hba data structure.
4641  * @vport: pointer to vport data structure
4642  *
4643  * This routine allocated the resources needed for the VMID.
4644  *
4645  * Return codes
4646  *      0 on Success
4647  *      Non-0 on Failure
4648  */
4649 static int
4650 lpfc_vmid_res_alloc(struct lpfc_hba *phba, struct lpfc_vport *vport)
4651 {
4652         /* VMID feature is supported only on SLI4 */
4653         if (phba->sli_rev == LPFC_SLI_REV3) {
4654                 phba->cfg_vmid_app_header = 0;
4655                 phba->cfg_vmid_priority_tagging = 0;
4656         }
4657
4658         if (lpfc_is_vmid_enabled(phba)) {
4659                 vport->vmid =
4660                     kcalloc(phba->cfg_max_vmid, sizeof(struct lpfc_vmid),
4661                             GFP_KERNEL);
4662                 if (!vport->vmid)
4663                         return -ENOMEM;
4664
4665                 rwlock_init(&vport->vmid_lock);
4666
4667                 /* Set the VMID parameters for the vport */
4668                 vport->vmid_priority_tagging = phba->cfg_vmid_priority_tagging;
4669                 vport->vmid_inactivity_timeout =
4670                     phba->cfg_vmid_inactivity_timeout;
4671                 vport->max_vmid = phba->cfg_max_vmid;
4672                 vport->cur_vmid_cnt = 0;
4673
4674                 vport->vmid_priority_range = bitmap_zalloc
4675                         (LPFC_VMID_MAX_PRIORITY_RANGE, GFP_KERNEL);
4676
4677                 if (!vport->vmid_priority_range) {
4678                         kfree(vport->vmid);
4679                         return -ENOMEM;
4680                 }
4681
4682                 hash_init(vport->hash_table);
4683         }
4684         return 0;
4685 }
4686
4687 /**
4688  * lpfc_create_port - Create an FC port
4689  * @phba: pointer to lpfc hba data structure.
4690  * @instance: a unique integer ID to this FC port.
4691  * @dev: pointer to the device data structure.
4692  *
4693  * This routine creates a FC port for the upper layer protocol. The FC port
4694  * can be created on top of either a physical port or a virtual port provided
4695  * by the HBA. This routine also allocates a SCSI host data structure (shost)
4696  * and associates the FC port created before adding the shost into the SCSI
4697  * layer.
4698  *
4699  * Return codes
4700  *   @vport - pointer to the virtual N_Port data structure.
4701  *   NULL - port create failed.
4702  **/
4703 struct lpfc_vport *
4704 lpfc_create_port(struct lpfc_hba *phba, int instance, struct device *dev)
4705 {
4706         struct lpfc_vport *vport;
4707         struct Scsi_Host  *shost = NULL;
4708         struct scsi_host_template *template;
4709         int error = 0;
4710         int i;
4711         uint64_t wwn;
4712         bool use_no_reset_hba = false;
4713         int rc;
4714
4715         if (lpfc_no_hba_reset_cnt) {
4716                 if (phba->sli_rev < LPFC_SLI_REV4 &&
4717                     dev == &phba->pcidev->dev) {
4718                         /* Reset the port first */
4719                         lpfc_sli_brdrestart(phba);
4720                         rc = lpfc_sli_chipset_init(phba);
4721                         if (rc)
4722                                 return NULL;
4723                 }
4724                 wwn = lpfc_get_wwpn(phba);
4725         }
4726
4727         for (i = 0; i < lpfc_no_hba_reset_cnt; i++) {
4728                 if (wwn == lpfc_no_hba_reset[i]) {
4729                         lpfc_printf_log(phba, KERN_ERR,
4730                                         LOG_TRACE_EVENT,
4731                                         "6020 Setting use_no_reset port=%llx\n",
4732                                         wwn);
4733                         use_no_reset_hba = true;
4734                         break;
4735                 }
4736         }
4737
4738         /* Seed template for SCSI host registration */
4739         if (dev == &phba->pcidev->dev) {
4740                 if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
4741                         /* Seed physical port template */
4742                         template = &lpfc_template;
4743
4744                         if (use_no_reset_hba)
4745                                 /* template is for a no reset SCSI Host */
4746                                 template->eh_host_reset_handler = NULL;
4747
4748                         /* Seed updated value of sg_tablesize */
4749                         template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4750                 } else {
4751                         /* NVMET is for physical port only */
4752                         template = &lpfc_template_nvme;
4753                 }
4754         } else {
4755                 /* Seed vport template */
4756                 template = &lpfc_vport_template;
4757
4758                 /* Seed updated value of sg_tablesize */
4759                 template->sg_tablesize = lpfc_get_sg_tablesize(phba);
4760         }
4761
4762         shost = scsi_host_alloc(template, sizeof(struct lpfc_vport));
4763         if (!shost)
4764                 goto out;
4765
4766         vport = (struct lpfc_vport *) shost->hostdata;
4767         vport->phba = phba;
4768         set_bit(FC_LOADING, &vport->load_flag);
4769         set_bit(FC_VPORT_NEEDS_REG_VPI, &vport->fc_flag);
4770         vport->fc_rscn_flush = 0;
4771         atomic_set(&vport->fc_plogi_cnt, 0);
4772         atomic_set(&vport->fc_adisc_cnt, 0);
4773         atomic_set(&vport->fc_reglogin_cnt, 0);
4774         atomic_set(&vport->fc_prli_cnt, 0);
4775         atomic_set(&vport->fc_unmap_cnt, 0);
4776         atomic_set(&vport->fc_map_cnt, 0);
4777         atomic_set(&vport->fc_npr_cnt, 0);
4778         atomic_set(&vport->fc_unused_cnt, 0);
4779         lpfc_get_vport_cfgparam(vport);
4780
4781         /* Adjust value in vport */
4782         vport->cfg_enable_fc4_type = phba->cfg_enable_fc4_type;
4783
4784         shost->unique_id = instance;
4785         shost->max_id = LPFC_MAX_TARGET;
4786         shost->max_lun = vport->cfg_max_luns;
4787         shost->this_id = -1;
4788         shost->max_cmd_len = 16;
4789
4790         if (phba->sli_rev == LPFC_SLI_REV4) {
4791                 if (!phba->cfg_fcp_mq_threshold ||
4792                     phba->cfg_fcp_mq_threshold > phba->cfg_hdw_queue)
4793                         phba->cfg_fcp_mq_threshold = phba->cfg_hdw_queue;
4794
4795                 shost->nr_hw_queues = min_t(int, 2 * num_possible_nodes(),
4796                                             phba->cfg_fcp_mq_threshold);
4797
4798                 shost->dma_boundary =
4799                         phba->sli4_hba.pc_sli4_params.sge_supp_len-1;
4800         } else
4801                 /* SLI-3 has a limited number of hardware queues (3),
4802                  * thus there is only one for FCP processing.
4803                  */
4804                 shost->nr_hw_queues = 1;
4805
4806         /*
4807          * Set initial can_queue value since 0 is no longer supported and
4808          * scsi_add_host will fail. This will be adjusted later based on the
4809          * max xri value determined in hba setup.
4810          */
4811         shost->can_queue = phba->cfg_hba_queue_depth - 10;
4812         if (dev != &phba->pcidev->dev) {
4813                 shost->transportt = lpfc_vport_transport_template;
4814                 vport->port_type = LPFC_NPIV_PORT;
4815         } else {
4816                 shost->transportt = lpfc_transport_template;
4817                 vport->port_type = LPFC_PHYSICAL_PORT;
4818         }
4819
4820         lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
4821                         "9081 CreatePort TMPLATE type %x TBLsize %d "
4822                         "SEGcnt %d/%d\n",
4823                         vport->port_type, shost->sg_tablesize,
4824                         phba->cfg_scsi_seg_cnt, phba->cfg_sg_seg_cnt);
4825
4826         /* Allocate the resources for VMID */
4827         rc = lpfc_vmid_res_alloc(phba, vport);
4828
4829         if (rc)
4830                 goto out_put_shost;
4831
4832         /* Initialize all internally managed lists. */
4833         INIT_LIST_HEAD(&vport->fc_nodes);
4834         spin_lock_init(&vport->fc_nodes_list_lock);
4835         INIT_LIST_HEAD(&vport->rcv_buffer_list);
4836         spin_lock_init(&vport->work_port_lock);
4837
4838         timer_setup(&vport->fc_disctmo, lpfc_disc_timeout, 0);
4839
4840         timer_setup(&vport->els_tmofunc, lpfc_els_timeout, 0);
4841
4842         timer_setup(&vport->delayed_disc_tmo, lpfc_delayed_disc_tmo, 0);
4843
4844         if (phba->sli3_options & LPFC_SLI3_BG_ENABLED)
4845                 lpfc_setup_bg(phba, shost);
4846
4847         error = scsi_add_host_with_dma(shost, dev, &phba->pcidev->dev);
4848         if (error)
4849                 goto out_free_vmid;
4850
4851         spin_lock_irq(&phba->port_list_lock);
4852         list_add_tail(&vport->listentry, &phba->port_list);
4853         spin_unlock_irq(&phba->port_list_lock);
4854         return vport;
4855
4856 out_free_vmid:
4857         kfree(vport->vmid);
4858         bitmap_free(vport->vmid_priority_range);
4859 out_put_shost:
4860         scsi_host_put(shost);
4861 out:
4862         return NULL;
4863 }
4864
4865 /**
4866  * destroy_port -  destroy an FC port
4867  * @vport: pointer to an lpfc virtual N_Port data structure.
4868  *
4869  * This routine destroys a FC port from the upper layer protocol. All the
4870  * resources associated with the port are released.
4871  **/
4872 void
4873 destroy_port(struct lpfc_vport *vport)
4874 {
4875         struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
4876         struct lpfc_hba  *phba = vport->phba;
4877
4878         lpfc_debugfs_terminate(vport);
4879         fc_remove_host(shost);
4880         scsi_remove_host(shost);
4881
4882         spin_lock_irq(&phba->port_list_lock);
4883         list_del_init(&vport->listentry);
4884         spin_unlock_irq(&phba->port_list_lock);
4885
4886         lpfc_cleanup(vport);
4887         return;
4888 }
4889
4890 /**
4891  * lpfc_get_instance - Get a unique integer ID
4892  *
4893  * This routine allocates a unique integer ID from lpfc_hba_index pool. It
4894  * uses the kernel idr facility to perform the task.
4895  *
4896  * Return codes:
4897  *   instance - a unique integer ID allocated as the new instance.
4898  *   -1 - lpfc get instance failed.
4899  **/
4900 int
4901 lpfc_get_instance(void)
4902 {
4903         int ret;
4904
4905         ret = idr_alloc(&lpfc_hba_index, NULL, 0, 0, GFP_KERNEL);
4906         return ret < 0 ? -1 : ret;
4907 }
4908
4909 /**
4910  * lpfc_scan_finished - method for SCSI layer to detect whether scan is done
4911  * @shost: pointer to SCSI host data structure.
4912  * @time: elapsed time of the scan in jiffies.
4913  *
4914  * This routine is called by the SCSI layer with a SCSI host to determine
4915  * whether the scan host is finished.
4916  *
4917  * Note: there is no scan_start function as adapter initialization will have
4918  * asynchronously kicked off the link initialization.
4919  *
4920  * Return codes
4921  *   0 - SCSI host scan is not over yet.
4922  *   1 - SCSI host scan is over.
4923  **/
4924 int lpfc_scan_finished(struct Scsi_Host *shost, unsigned long time)
4925 {
4926         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
4927         struct lpfc_hba   *phba = vport->phba;
4928         int stat = 0;
4929
4930         spin_lock_irq(shost->host_lock);
4931
4932         if (test_bit(FC_UNLOADING, &vport->load_flag)) {
4933                 stat = 1;
4934                 goto finished;
4935         }
4936         if (time >= msecs_to_jiffies(30 * 1000)) {
4937                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4938                                 "0461 Scanning longer than 30 "
4939                                 "seconds.  Continuing initialization\n");
4940                 stat = 1;
4941                 goto finished;
4942         }
4943         if (time >= msecs_to_jiffies(15 * 1000) &&
4944             phba->link_state <= LPFC_LINK_DOWN) {
4945                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4946                                 "0465 Link down longer than 15 "
4947                                 "seconds.  Continuing initialization\n");
4948                 stat = 1;
4949                 goto finished;
4950         }
4951
4952         if (vport->port_state != LPFC_VPORT_READY)
4953                 goto finished;
4954         if (vport->num_disc_nodes || vport->fc_prli_sent)
4955                 goto finished;
4956         if (!atomic_read(&vport->fc_map_cnt) &&
4957             time < msecs_to_jiffies(2 * 1000))
4958                 goto finished;
4959         if ((phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) != 0)
4960                 goto finished;
4961
4962         stat = 1;
4963
4964 finished:
4965         spin_unlock_irq(shost->host_lock);
4966         return stat;
4967 }
4968
4969 static void lpfc_host_supported_speeds_set(struct Scsi_Host *shost)
4970 {
4971         struct lpfc_vport *vport = (struct lpfc_vport *)shost->hostdata;
4972         struct lpfc_hba   *phba = vport->phba;
4973
4974         fc_host_supported_speeds(shost) = 0;
4975         /*
4976          * Avoid reporting supported link speed for FCoE as it can't be
4977          * controlled via FCoE.
4978          */
4979         if (phba->hba_flag & HBA_FCOE_MODE)
4980                 return;
4981
4982         if (phba->lmt & LMT_256Gb)
4983                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_256GBIT;
4984         if (phba->lmt & LMT_128Gb)
4985                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_128GBIT;
4986         if (phba->lmt & LMT_64Gb)
4987                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_64GBIT;
4988         if (phba->lmt & LMT_32Gb)
4989                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_32GBIT;
4990         if (phba->lmt & LMT_16Gb)
4991                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_16GBIT;
4992         if (phba->lmt & LMT_10Gb)
4993                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_10GBIT;
4994         if (phba->lmt & LMT_8Gb)
4995                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_8GBIT;
4996         if (phba->lmt & LMT_4Gb)
4997                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_4GBIT;
4998         if (phba->lmt & LMT_2Gb)
4999                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_2GBIT;
5000         if (phba->lmt & LMT_1Gb)
5001                 fc_host_supported_speeds(shost) |= FC_PORTSPEED_1GBIT;
5002 }
5003
5004 /**
5005  * lpfc_host_attrib_init - Initialize SCSI host attributes on a FC port
5006  * @shost: pointer to SCSI host data structure.
5007  *
5008  * This routine initializes a given SCSI host attributes on a FC port. The
5009  * SCSI host can be either on top of a physical port or a virtual port.
5010  **/
5011 void lpfc_host_attrib_init(struct Scsi_Host *shost)
5012 {
5013         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5014         struct lpfc_hba   *phba = vport->phba;
5015         /*
5016          * Set fixed host attributes.  Must done after lpfc_sli_hba_setup().
5017          */
5018
5019         fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
5020         fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
5021         fc_host_supported_classes(shost) = FC_COS_CLASS3;
5022
5023         memset(fc_host_supported_fc4s(shost), 0,
5024                sizeof(fc_host_supported_fc4s(shost)));
5025         fc_host_supported_fc4s(shost)[2] = 1;
5026         fc_host_supported_fc4s(shost)[7] = 1;
5027
5028         lpfc_vport_symbolic_node_name(vport, fc_host_symbolic_name(shost),
5029                                  sizeof fc_host_symbolic_name(shost));
5030
5031         lpfc_host_supported_speeds_set(shost);
5032
5033         fc_host_maxframe_size(shost) =
5034                 (((uint32_t) vport->fc_sparam.cmn.bbRcvSizeMsb & 0x0F) << 8) |
5035                 (uint32_t) vport->fc_sparam.cmn.bbRcvSizeLsb;
5036
5037         fc_host_dev_loss_tmo(shost) = vport->cfg_devloss_tmo;
5038
5039         /* This value is also unchanging */
5040         memset(fc_host_active_fc4s(shost), 0,
5041                sizeof(fc_host_active_fc4s(shost)));
5042         fc_host_active_fc4s(shost)[2] = 1;
5043         fc_host_active_fc4s(shost)[7] = 1;
5044
5045         fc_host_max_npiv_vports(shost) = phba->max_vpi;
5046         clear_bit(FC_LOADING, &vport->load_flag);
5047 }
5048
5049 /**
5050  * lpfc_stop_port_s3 - Stop SLI3 device port
5051  * @phba: pointer to lpfc hba data structure.
5052  *
5053  * This routine is invoked to stop an SLI3 device port, it stops the device
5054  * from generating interrupts and stops the device driver's timers for the
5055  * device.
5056  **/
5057 static void
5058 lpfc_stop_port_s3(struct lpfc_hba *phba)
5059 {
5060         /* Clear all interrupt enable conditions */
5061         writel(0, phba->HCregaddr);
5062         readl(phba->HCregaddr); /* flush */
5063         /* Clear all pending interrupts */
5064         writel(0xffffffff, phba->HAregaddr);
5065         readl(phba->HAregaddr); /* flush */
5066
5067         /* Reset some HBA SLI setup states */
5068         lpfc_stop_hba_timers(phba);
5069         phba->pport->work_port_events = 0;
5070 }
5071
5072 /**
5073  * lpfc_stop_port_s4 - Stop SLI4 device port
5074  * @phba: pointer to lpfc hba data structure.
5075  *
5076  * This routine is invoked to stop an SLI4 device port, it stops the device
5077  * from generating interrupts and stops the device driver's timers for the
5078  * device.
5079  **/
5080 static void
5081 lpfc_stop_port_s4(struct lpfc_hba *phba)
5082 {
5083         /* Reset some HBA SLI4 setup states */
5084         lpfc_stop_hba_timers(phba);
5085         if (phba->pport)
5086                 phba->pport->work_port_events = 0;
5087         phba->sli4_hba.intr_enable = 0;
5088 }
5089
5090 /**
5091  * lpfc_stop_port - Wrapper function for stopping hba port
5092  * @phba: Pointer to HBA context object.
5093  *
5094  * This routine wraps the actual SLI3 or SLI4 hba stop port routine from
5095  * the API jump table function pointer from the lpfc_hba struct.
5096  **/
5097 void
5098 lpfc_stop_port(struct lpfc_hba *phba)
5099 {
5100         phba->lpfc_stop_port(phba);
5101
5102         if (phba->wq)
5103                 flush_workqueue(phba->wq);
5104 }
5105
5106 /**
5107  * lpfc_fcf_redisc_wait_start_timer - Start fcf rediscover wait timer
5108  * @phba: Pointer to hba for which this call is being executed.
5109  *
5110  * This routine starts the timer waiting for the FCF rediscovery to complete.
5111  **/
5112 void
5113 lpfc_fcf_redisc_wait_start_timer(struct lpfc_hba *phba)
5114 {
5115         unsigned long fcf_redisc_wait_tmo =
5116                 (jiffies + msecs_to_jiffies(LPFC_FCF_REDISCOVER_WAIT_TMO));
5117         /* Start fcf rediscovery wait period timer */
5118         mod_timer(&phba->fcf.redisc_wait, fcf_redisc_wait_tmo);
5119         spin_lock_irq(&phba->hbalock);
5120         /* Allow action to new fcf asynchronous event */
5121         phba->fcf.fcf_flag &= ~(FCF_AVAILABLE | FCF_SCAN_DONE);
5122         /* Mark the FCF rediscovery pending state */
5123         phba->fcf.fcf_flag |= FCF_REDISC_PEND;
5124         spin_unlock_irq(&phba->hbalock);
5125 }
5126
5127 /**
5128  * lpfc_sli4_fcf_redisc_wait_tmo - FCF table rediscover wait timeout
5129  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5130  *
5131  * This routine is invoked when waiting for FCF table rediscover has been
5132  * timed out. If new FCF record(s) has (have) been discovered during the
5133  * wait period, a new FCF event shall be added to the FCOE async event
5134  * list, and then worker thread shall be waked up for processing from the
5135  * worker thread context.
5136  **/
5137 static void
5138 lpfc_sli4_fcf_redisc_wait_tmo(struct timer_list *t)
5139 {
5140         struct lpfc_hba *phba = from_timer(phba, t, fcf.redisc_wait);
5141
5142         /* Don't send FCF rediscovery event if timer cancelled */
5143         spin_lock_irq(&phba->hbalock);
5144         if (!(phba->fcf.fcf_flag & FCF_REDISC_PEND)) {
5145                 spin_unlock_irq(&phba->hbalock);
5146                 return;
5147         }
5148         /* Clear FCF rediscovery timer pending flag */
5149         phba->fcf.fcf_flag &= ~FCF_REDISC_PEND;
5150         /* FCF rediscovery event to worker thread */
5151         phba->fcf.fcf_flag |= FCF_REDISC_EVT;
5152         spin_unlock_irq(&phba->hbalock);
5153         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
5154                         "2776 FCF rediscover quiescent timer expired\n");
5155         /* wake up worker thread */
5156         lpfc_worker_wake_up(phba);
5157 }
5158
5159 /**
5160  * lpfc_vmid_poll - VMID timeout detection
5161  * @t: Timer context used to obtain the pointer to lpfc hba data structure.
5162  *
5163  * This routine is invoked when there is no I/O on by a VM for the specified
5164  * amount of time. When this situation is detected, the VMID has to be
5165  * deregistered from the switch and all the local resources freed. The VMID
5166  * will be reassigned to the VM once the I/O begins.
5167  **/
5168 static void
5169 lpfc_vmid_poll(struct timer_list *t)
5170 {
5171         struct lpfc_hba *phba = from_timer(phba, t, inactive_vmid_poll);
5172         u32 wake_up = 0;
5173
5174         /* check if there is a need to issue QFPA */
5175         if (phba->pport->vmid_priority_tagging) {
5176                 wake_up = 1;
5177                 phba->pport->work_port_events |= WORKER_CHECK_VMID_ISSUE_QFPA;
5178         }
5179
5180         /* Is the vmid inactivity timer enabled */
5181         if (phba->pport->vmid_inactivity_timeout ||
5182             test_bit(FC_DEREGISTER_ALL_APP_ID, &phba->pport->load_flag)) {
5183                 wake_up = 1;
5184                 phba->pport->work_port_events |= WORKER_CHECK_INACTIVE_VMID;
5185         }
5186
5187         if (wake_up)
5188                 lpfc_worker_wake_up(phba);
5189
5190         /* restart the timer for the next iteration */
5191         mod_timer(&phba->inactive_vmid_poll, jiffies + msecs_to_jiffies(1000 *
5192                                                         LPFC_VMID_TIMER));
5193 }
5194
5195 /**
5196  * lpfc_sli4_parse_latt_fault - Parse sli4 link-attention link fault code
5197  * @phba: pointer to lpfc hba data structure.
5198  * @acqe_link: pointer to the async link completion queue entry.
5199  *
5200  * This routine is to parse the SLI4 link-attention link fault code.
5201  **/
5202 static void
5203 lpfc_sli4_parse_latt_fault(struct lpfc_hba *phba,
5204                            struct lpfc_acqe_link *acqe_link)
5205 {
5206         switch (bf_get(lpfc_acqe_fc_la_att_type, acqe_link)) {
5207         case LPFC_FC_LA_TYPE_LINK_DOWN:
5208         case LPFC_FC_LA_TYPE_TRUNKING_EVENT:
5209         case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
5210         case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
5211                 break;
5212         default:
5213                 switch (bf_get(lpfc_acqe_link_fault, acqe_link)) {
5214                 case LPFC_ASYNC_LINK_FAULT_NONE:
5215                 case LPFC_ASYNC_LINK_FAULT_LOCAL:
5216                 case LPFC_ASYNC_LINK_FAULT_REMOTE:
5217                 case LPFC_ASYNC_LINK_FAULT_LR_LRR:
5218                         break;
5219                 default:
5220                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5221                                         "0398 Unknown link fault code: x%x\n",
5222                                         bf_get(lpfc_acqe_link_fault, acqe_link));
5223                         break;
5224                 }
5225                 break;
5226         }
5227 }
5228
5229 /**
5230  * lpfc_sli4_parse_latt_type - Parse sli4 link attention type
5231  * @phba: pointer to lpfc hba data structure.
5232  * @acqe_link: pointer to the async link completion queue entry.
5233  *
5234  * This routine is to parse the SLI4 link attention type and translate it
5235  * into the base driver's link attention type coding.
5236  *
5237  * Return: Link attention type in terms of base driver's coding.
5238  **/
5239 static uint8_t
5240 lpfc_sli4_parse_latt_type(struct lpfc_hba *phba,
5241                           struct lpfc_acqe_link *acqe_link)
5242 {
5243         uint8_t att_type;
5244
5245         switch (bf_get(lpfc_acqe_link_status, acqe_link)) {
5246         case LPFC_ASYNC_LINK_STATUS_DOWN:
5247         case LPFC_ASYNC_LINK_STATUS_LOGICAL_DOWN:
5248                 att_type = LPFC_ATT_LINK_DOWN;
5249                 break;
5250         case LPFC_ASYNC_LINK_STATUS_UP:
5251                 /* Ignore physical link up events - wait for logical link up */
5252                 att_type = LPFC_ATT_RESERVED;
5253                 break;
5254         case LPFC_ASYNC_LINK_STATUS_LOGICAL_UP:
5255                 att_type = LPFC_ATT_LINK_UP;
5256                 break;
5257         default:
5258                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5259                                 "0399 Invalid link attention type: x%x\n",
5260                                 bf_get(lpfc_acqe_link_status, acqe_link));
5261                 att_type = LPFC_ATT_RESERVED;
5262                 break;
5263         }
5264         return att_type;
5265 }
5266
5267 /**
5268  * lpfc_sli_port_speed_get - Get sli3 link speed code to link speed
5269  * @phba: pointer to lpfc hba data structure.
5270  *
5271  * This routine is to get an SLI3 FC port's link speed in Mbps.
5272  *
5273  * Return: link speed in terms of Mbps.
5274  **/
5275 uint32_t
5276 lpfc_sli_port_speed_get(struct lpfc_hba *phba)
5277 {
5278         uint32_t link_speed;
5279
5280         if (!lpfc_is_link_up(phba))
5281                 return 0;
5282
5283         if (phba->sli_rev <= LPFC_SLI_REV3) {
5284                 switch (phba->fc_linkspeed) {
5285                 case LPFC_LINK_SPEED_1GHZ:
5286                         link_speed = 1000;
5287                         break;
5288                 case LPFC_LINK_SPEED_2GHZ:
5289                         link_speed = 2000;
5290                         break;
5291                 case LPFC_LINK_SPEED_4GHZ:
5292                         link_speed = 4000;
5293                         break;
5294                 case LPFC_LINK_SPEED_8GHZ:
5295                         link_speed = 8000;
5296                         break;
5297                 case LPFC_LINK_SPEED_10GHZ:
5298                         link_speed = 10000;
5299                         break;
5300                 case LPFC_LINK_SPEED_16GHZ:
5301                         link_speed = 16000;
5302                         break;
5303                 default:
5304                         link_speed = 0;
5305                 }
5306         } else {
5307                 if (phba->sli4_hba.link_state.logical_speed)
5308                         link_speed =
5309                               phba->sli4_hba.link_state.logical_speed;
5310                 else
5311                         link_speed = phba->sli4_hba.link_state.speed;
5312         }
5313         return link_speed;
5314 }
5315
5316 /**
5317  * lpfc_sli4_port_speed_parse - Parse async evt link speed code to link speed
5318  * @phba: pointer to lpfc hba data structure.
5319  * @evt_code: asynchronous event code.
5320  * @speed_code: asynchronous event link speed code.
5321  *
5322  * This routine is to parse the giving SLI4 async event link speed code into
5323  * value of Mbps for the link speed.
5324  *
5325  * Return: link speed in terms of Mbps.
5326  **/
5327 static uint32_t
5328 lpfc_sli4_port_speed_parse(struct lpfc_hba *phba, uint32_t evt_code,
5329                            uint8_t speed_code)
5330 {
5331         uint32_t port_speed;
5332
5333         switch (evt_code) {
5334         case LPFC_TRAILER_CODE_LINK:
5335                 switch (speed_code) {
5336                 case LPFC_ASYNC_LINK_SPEED_ZERO:
5337                         port_speed = 0;
5338                         break;
5339                 case LPFC_ASYNC_LINK_SPEED_10MBPS:
5340                         port_speed = 10;
5341                         break;
5342                 case LPFC_ASYNC_LINK_SPEED_100MBPS:
5343                         port_speed = 100;
5344                         break;
5345                 case LPFC_ASYNC_LINK_SPEED_1GBPS:
5346                         port_speed = 1000;
5347                         break;
5348                 case LPFC_ASYNC_LINK_SPEED_10GBPS:
5349                         port_speed = 10000;
5350                         break;
5351                 case LPFC_ASYNC_LINK_SPEED_20GBPS:
5352                         port_speed = 20000;
5353                         break;
5354                 case LPFC_ASYNC_LINK_SPEED_25GBPS:
5355                         port_speed = 25000;
5356                         break;
5357                 case LPFC_ASYNC_LINK_SPEED_40GBPS:
5358                         port_speed = 40000;
5359                         break;
5360                 case LPFC_ASYNC_LINK_SPEED_100GBPS:
5361                         port_speed = 100000;
5362                         break;
5363                 default:
5364                         port_speed = 0;
5365                 }
5366                 break;
5367         case LPFC_TRAILER_CODE_FC:
5368                 switch (speed_code) {
5369                 case LPFC_FC_LA_SPEED_UNKNOWN:
5370                         port_speed = 0;
5371                         break;
5372                 case LPFC_FC_LA_SPEED_1G:
5373                         port_speed = 1000;
5374                         break;
5375                 case LPFC_FC_LA_SPEED_2G:
5376                         port_speed = 2000;
5377                         break;
5378                 case LPFC_FC_LA_SPEED_4G:
5379                         port_speed = 4000;
5380                         break;
5381                 case LPFC_FC_LA_SPEED_8G:
5382                         port_speed = 8000;
5383                         break;
5384                 case LPFC_FC_LA_SPEED_10G:
5385                         port_speed = 10000;
5386                         break;
5387                 case LPFC_FC_LA_SPEED_16G:
5388                         port_speed = 16000;
5389                         break;
5390                 case LPFC_FC_LA_SPEED_32G:
5391                         port_speed = 32000;
5392                         break;
5393                 case LPFC_FC_LA_SPEED_64G:
5394                         port_speed = 64000;
5395                         break;
5396                 case LPFC_FC_LA_SPEED_128G:
5397                         port_speed = 128000;
5398                         break;
5399                 case LPFC_FC_LA_SPEED_256G:
5400                         port_speed = 256000;
5401                         break;
5402                 default:
5403                         port_speed = 0;
5404                 }
5405                 break;
5406         default:
5407                 port_speed = 0;
5408         }
5409         return port_speed;
5410 }
5411
5412 /**
5413  * lpfc_sli4_async_link_evt - Process the asynchronous FCoE link event
5414  * @phba: pointer to lpfc hba data structure.
5415  * @acqe_link: pointer to the async link completion queue entry.
5416  *
5417  * This routine is to handle the SLI4 asynchronous FCoE link event.
5418  **/
5419 static void
5420 lpfc_sli4_async_link_evt(struct lpfc_hba *phba,
5421                          struct lpfc_acqe_link *acqe_link)
5422 {
5423         LPFC_MBOXQ_t *pmb;
5424         MAILBOX_t *mb;
5425         struct lpfc_mbx_read_top *la;
5426         uint8_t att_type;
5427         int rc;
5428
5429         att_type = lpfc_sli4_parse_latt_type(phba, acqe_link);
5430         if (att_type != LPFC_ATT_LINK_DOWN && att_type != LPFC_ATT_LINK_UP)
5431                 return;
5432         phba->fcoe_eventtag = acqe_link->event_tag;
5433         pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5434         if (!pmb) {
5435                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5436                                 "0395 The mboxq allocation failed\n");
5437                 return;
5438         }
5439
5440         rc = lpfc_mbox_rsrc_prep(phba, pmb);
5441         if (rc) {
5442                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5443                                 "0396 mailbox allocation failed\n");
5444                 goto out_free_pmb;
5445         }
5446
5447         /* Cleanup any outstanding ELS commands */
5448         lpfc_els_flush_all_cmd(phba);
5449
5450         /* Block ELS IOCBs until we have done process link event */
5451         phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
5452
5453         /* Update link event statistics */
5454         phba->sli.slistat.link_event++;
5455
5456         /* Create lpfc_handle_latt mailbox command from link ACQE */
5457         lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
5458         pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
5459         pmb->vport = phba->pport;
5460
5461         /* Keep the link status for extra SLI4 state machine reference */
5462         phba->sli4_hba.link_state.speed =
5463                         lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_LINK,
5464                                 bf_get(lpfc_acqe_link_speed, acqe_link));
5465         phba->sli4_hba.link_state.duplex =
5466                                 bf_get(lpfc_acqe_link_duplex, acqe_link);
5467         phba->sli4_hba.link_state.status =
5468                                 bf_get(lpfc_acqe_link_status, acqe_link);
5469         phba->sli4_hba.link_state.type =
5470                                 bf_get(lpfc_acqe_link_type, acqe_link);
5471         phba->sli4_hba.link_state.number =
5472                                 bf_get(lpfc_acqe_link_number, acqe_link);
5473         phba->sli4_hba.link_state.fault =
5474                                 bf_get(lpfc_acqe_link_fault, acqe_link);
5475         phba->sli4_hba.link_state.logical_speed =
5476                         bf_get(lpfc_acqe_logical_link_speed, acqe_link) * 10;
5477
5478         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5479                         "2900 Async FC/FCoE Link event - Speed:%dGBit "
5480                         "duplex:x%x LA Type:x%x Port Type:%d Port Number:%d "
5481                         "Logical speed:%dMbps Fault:%d\n",
5482                         phba->sli4_hba.link_state.speed,
5483                         phba->sli4_hba.link_state.topology,
5484                         phba->sli4_hba.link_state.status,
5485                         phba->sli4_hba.link_state.type,
5486                         phba->sli4_hba.link_state.number,
5487                         phba->sli4_hba.link_state.logical_speed,
5488                         phba->sli4_hba.link_state.fault);
5489         /*
5490          * For FC Mode: issue the READ_TOPOLOGY mailbox command to fetch
5491          * topology info. Note: Optional for non FC-AL ports.
5492          */
5493         if (!(phba->hba_flag & HBA_FCOE_MODE)) {
5494                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5495                 if (rc == MBX_NOT_FINISHED)
5496                         goto out_free_pmb;
5497                 return;
5498         }
5499         /*
5500          * For FCoE Mode: fill in all the topology information we need and call
5501          * the READ_TOPOLOGY completion routine to continue without actually
5502          * sending the READ_TOPOLOGY mailbox command to the port.
5503          */
5504         /* Initialize completion status */
5505         mb = &pmb->u.mb;
5506         mb->mbxStatus = MBX_SUCCESS;
5507
5508         /* Parse port fault information field */
5509         lpfc_sli4_parse_latt_fault(phba, acqe_link);
5510
5511         /* Parse and translate link attention fields */
5512         la = (struct lpfc_mbx_read_top *) &pmb->u.mb.un.varReadTop;
5513         la->eventTag = acqe_link->event_tag;
5514         bf_set(lpfc_mbx_read_top_att_type, la, att_type);
5515         bf_set(lpfc_mbx_read_top_link_spd, la,
5516                (bf_get(lpfc_acqe_link_speed, acqe_link)));
5517
5518         /* Fake the following irrelevant fields */
5519         bf_set(lpfc_mbx_read_top_topology, la, LPFC_TOPOLOGY_PT_PT);
5520         bf_set(lpfc_mbx_read_top_alpa_granted, la, 0);
5521         bf_set(lpfc_mbx_read_top_il, la, 0);
5522         bf_set(lpfc_mbx_read_top_pb, la, 0);
5523         bf_set(lpfc_mbx_read_top_fa, la, 0);
5524         bf_set(lpfc_mbx_read_top_mm, la, 0);
5525
5526         /* Invoke the lpfc_handle_latt mailbox command callback function */
5527         lpfc_mbx_cmpl_read_topology(phba, pmb);
5528
5529         return;
5530
5531 out_free_pmb:
5532         lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
5533 }
5534
5535 /**
5536  * lpfc_async_link_speed_to_read_top - Parse async evt link speed code to read
5537  * topology.
5538  * @phba: pointer to lpfc hba data structure.
5539  * @speed_code: asynchronous event link speed code.
5540  *
5541  * This routine is to parse the giving SLI4 async event link speed code into
5542  * value of Read topology link speed.
5543  *
5544  * Return: link speed in terms of Read topology.
5545  **/
5546 static uint8_t
5547 lpfc_async_link_speed_to_read_top(struct lpfc_hba *phba, uint8_t speed_code)
5548 {
5549         uint8_t port_speed;
5550
5551         switch (speed_code) {
5552         case LPFC_FC_LA_SPEED_1G:
5553                 port_speed = LPFC_LINK_SPEED_1GHZ;
5554                 break;
5555         case LPFC_FC_LA_SPEED_2G:
5556                 port_speed = LPFC_LINK_SPEED_2GHZ;
5557                 break;
5558         case LPFC_FC_LA_SPEED_4G:
5559                 port_speed = LPFC_LINK_SPEED_4GHZ;
5560                 break;
5561         case LPFC_FC_LA_SPEED_8G:
5562                 port_speed = LPFC_LINK_SPEED_8GHZ;
5563                 break;
5564         case LPFC_FC_LA_SPEED_16G:
5565                 port_speed = LPFC_LINK_SPEED_16GHZ;
5566                 break;
5567         case LPFC_FC_LA_SPEED_32G:
5568                 port_speed = LPFC_LINK_SPEED_32GHZ;
5569                 break;
5570         case LPFC_FC_LA_SPEED_64G:
5571                 port_speed = LPFC_LINK_SPEED_64GHZ;
5572                 break;
5573         case LPFC_FC_LA_SPEED_128G:
5574                 port_speed = LPFC_LINK_SPEED_128GHZ;
5575                 break;
5576         case LPFC_FC_LA_SPEED_256G:
5577                 port_speed = LPFC_LINK_SPEED_256GHZ;
5578                 break;
5579         default:
5580                 port_speed = 0;
5581                 break;
5582         }
5583
5584         return port_speed;
5585 }
5586
5587 void
5588 lpfc_cgn_dump_rxmonitor(struct lpfc_hba *phba)
5589 {
5590         if (!phba->rx_monitor) {
5591                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5592                                 "4411 Rx Monitor Info is empty.\n");
5593         } else {
5594                 lpfc_rx_monitor_report(phba, phba->rx_monitor, NULL, 0,
5595                                        LPFC_MAX_RXMONITOR_DUMP);
5596         }
5597 }
5598
5599 /**
5600  * lpfc_cgn_update_stat - Save data into congestion stats buffer
5601  * @phba: pointer to lpfc hba data structure.
5602  * @dtag: FPIN descriptor received
5603  *
5604  * Increment the FPIN received counter/time when it happens.
5605  */
5606 void
5607 lpfc_cgn_update_stat(struct lpfc_hba *phba, uint32_t dtag)
5608 {
5609         struct lpfc_cgn_info *cp;
5610         u32 value;
5611
5612         /* Make sure we have a congestion info buffer */
5613         if (!phba->cgn_i)
5614                 return;
5615         cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5616
5617         /* Update congestion statistics */
5618         switch (dtag) {
5619         case ELS_DTAG_LNK_INTEGRITY:
5620                 le32_add_cpu(&cp->link_integ_notification, 1);
5621                 lpfc_cgn_update_tstamp(phba, &cp->stat_lnk);
5622                 break;
5623         case ELS_DTAG_DELIVERY:
5624                 le32_add_cpu(&cp->delivery_notification, 1);
5625                 lpfc_cgn_update_tstamp(phba, &cp->stat_delivery);
5626                 break;
5627         case ELS_DTAG_PEER_CONGEST:
5628                 le32_add_cpu(&cp->cgn_peer_notification, 1);
5629                 lpfc_cgn_update_tstamp(phba, &cp->stat_peer);
5630                 break;
5631         case ELS_DTAG_CONGESTION:
5632                 le32_add_cpu(&cp->cgn_notification, 1);
5633                 lpfc_cgn_update_tstamp(phba, &cp->stat_fpin);
5634         }
5635         if (phba->cgn_fpin_frequency &&
5636             phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5637                 value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5638                 cp->cgn_stat_npm = value;
5639         }
5640
5641         value = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5642                                     LPFC_CGN_CRC32_SEED);
5643         cp->cgn_info_crc = cpu_to_le32(value);
5644 }
5645
5646 /**
5647  * lpfc_cgn_update_tstamp - Update cmf timestamp
5648  * @phba: pointer to lpfc hba data structure.
5649  * @ts: structure to write the timestamp to.
5650  */
5651 void
5652 lpfc_cgn_update_tstamp(struct lpfc_hba *phba, struct lpfc_cgn_ts *ts)
5653 {
5654         struct timespec64 cur_time;
5655         struct tm tm_val;
5656
5657         ktime_get_real_ts64(&cur_time);
5658         time64_to_tm(cur_time.tv_sec, 0, &tm_val);
5659
5660         ts->month = tm_val.tm_mon + 1;
5661         ts->day = tm_val.tm_mday;
5662         ts->year = tm_val.tm_year - 100;
5663         ts->hour = tm_val.tm_hour;
5664         ts->minute = tm_val.tm_min;
5665         ts->second = tm_val.tm_sec;
5666
5667         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5668                         "2646 Updated CMF timestamp : "
5669                         "%u/%u/%u %u:%u:%u\n",
5670                         ts->day, ts->month,
5671                         ts->year, ts->hour,
5672                         ts->minute, ts->second);
5673 }
5674
5675 /**
5676  * lpfc_cmf_stats_timer - Save data into registered congestion buffer
5677  * @timer: Timer cookie to access lpfc private data
5678  *
5679  * Save the congestion event data every minute.
5680  * On the hour collapse all the minute data into hour data. Every day
5681  * collapse all the hour data into daily data. Separate driver
5682  * and fabrc congestion event counters that will be saved out
5683  * to the registered congestion buffer every minute.
5684  */
5685 static enum hrtimer_restart
5686 lpfc_cmf_stats_timer(struct hrtimer *timer)
5687 {
5688         struct lpfc_hba *phba;
5689         struct lpfc_cgn_info *cp;
5690         uint32_t i, index;
5691         uint16_t value, mvalue;
5692         uint64_t bps;
5693         uint32_t mbps;
5694         uint32_t dvalue, wvalue, lvalue, avalue;
5695         uint64_t latsum;
5696         __le16 *ptr;
5697         __le32 *lptr;
5698         __le16 *mptr;
5699
5700         phba = container_of(timer, struct lpfc_hba, cmf_stats_timer);
5701         /* Make sure we have a congestion info buffer */
5702         if (!phba->cgn_i)
5703                 return HRTIMER_NORESTART;
5704         cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
5705
5706         phba->cgn_evt_timestamp = jiffies +
5707                         msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
5708         phba->cgn_evt_minute++;
5709
5710         /* We should get to this point in the routine on 1 minute intervals */
5711         lpfc_cgn_update_tstamp(phba, &cp->base_time);
5712
5713         if (phba->cgn_fpin_frequency &&
5714             phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ) {
5715                 value = LPFC_CGN_TIMER_TO_MIN / phba->cgn_fpin_frequency;
5716                 cp->cgn_stat_npm = value;
5717         }
5718
5719         /* Read and clear the latency counters for this minute */
5720         lvalue = atomic_read(&phba->cgn_latency_evt_cnt);
5721         latsum = atomic64_read(&phba->cgn_latency_evt);
5722         atomic_set(&phba->cgn_latency_evt_cnt, 0);
5723         atomic64_set(&phba->cgn_latency_evt, 0);
5724
5725         /* We need to store MB/sec bandwidth in the congestion information.
5726          * block_cnt is count of 512 byte blocks for the entire minute,
5727          * bps will get bytes per sec before finally converting to MB/sec.
5728          */
5729         bps = div_u64(phba->rx_block_cnt, LPFC_SEC_MIN) * 512;
5730         phba->rx_block_cnt = 0;
5731         mvalue = bps / (1024 * 1024); /* convert to MB/sec */
5732
5733         /* Every minute */
5734         /* cgn parameters */
5735         cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
5736         cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
5737         cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
5738         cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
5739
5740         /* Fill in default LUN qdepth */
5741         value = (uint16_t)(phba->pport->cfg_lun_queue_depth);
5742         cp->cgn_lunq = cpu_to_le16(value);
5743
5744         /* Record congestion buffer info - every minute
5745          * cgn_driver_evt_cnt (Driver events)
5746          * cgn_fabric_warn_cnt (Congestion Warnings)
5747          * cgn_latency_evt_cnt / cgn_latency_evt (IO Latency)
5748          * cgn_fabric_alarm_cnt (Congestion Alarms)
5749          */
5750         index = ++cp->cgn_index_minute;
5751         if (cp->cgn_index_minute == LPFC_MIN_HOUR) {
5752                 cp->cgn_index_minute = 0;
5753                 index = 0;
5754         }
5755
5756         /* Get the number of driver events in this sample and reset counter */
5757         dvalue = atomic_read(&phba->cgn_driver_evt_cnt);
5758         atomic_set(&phba->cgn_driver_evt_cnt, 0);
5759
5760         /* Get the number of warning events - FPIN and Signal for this minute */
5761         wvalue = 0;
5762         if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_WARN) ||
5763             phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
5764             phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5765                 wvalue = atomic_read(&phba->cgn_fabric_warn_cnt);
5766         atomic_set(&phba->cgn_fabric_warn_cnt, 0);
5767
5768         /* Get the number of alarm events - FPIN and Signal for this minute */
5769         avalue = 0;
5770         if ((phba->cgn_reg_fpin & LPFC_CGN_FPIN_ALARM) ||
5771             phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM)
5772                 avalue = atomic_read(&phba->cgn_fabric_alarm_cnt);
5773         atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
5774
5775         /* Collect the driver, warning, alarm and latency counts for this
5776          * minute into the driver congestion buffer.
5777          */
5778         ptr = &cp->cgn_drvr_min[index];
5779         value = (uint16_t)dvalue;
5780         *ptr = cpu_to_le16(value);
5781
5782         ptr = &cp->cgn_warn_min[index];
5783         value = (uint16_t)wvalue;
5784         *ptr = cpu_to_le16(value);
5785
5786         ptr = &cp->cgn_alarm_min[index];
5787         value = (uint16_t)avalue;
5788         *ptr = cpu_to_le16(value);
5789
5790         lptr = &cp->cgn_latency_min[index];
5791         if (lvalue) {
5792                 lvalue = (uint32_t)div_u64(latsum, lvalue);
5793                 *lptr = cpu_to_le32(lvalue);
5794         } else {
5795                 *lptr = 0;
5796         }
5797
5798         /* Collect the bandwidth value into the driver's congesion buffer. */
5799         mptr = &cp->cgn_bw_min[index];
5800         *mptr = cpu_to_le16(mvalue);
5801
5802         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5803                         "2418 Congestion Info - minute (%d): %d %d %d %d %d\n",
5804                         index, dvalue, wvalue, *lptr, mvalue, avalue);
5805
5806         /* Every hour */
5807         if ((phba->cgn_evt_minute % LPFC_MIN_HOUR) == 0) {
5808                 /* Record congestion buffer info - every hour
5809                  * Collapse all minutes into an hour
5810                  */
5811                 index = ++cp->cgn_index_hour;
5812                 if (cp->cgn_index_hour == LPFC_HOUR_DAY) {
5813                         cp->cgn_index_hour = 0;
5814                         index = 0;
5815                 }
5816
5817                 dvalue = 0;
5818                 wvalue = 0;
5819                 lvalue = 0;
5820                 avalue = 0;
5821                 mvalue = 0;
5822                 mbps = 0;
5823                 for (i = 0; i < LPFC_MIN_HOUR; i++) {
5824                         dvalue += le16_to_cpu(cp->cgn_drvr_min[i]);
5825                         wvalue += le16_to_cpu(cp->cgn_warn_min[i]);
5826                         lvalue += le32_to_cpu(cp->cgn_latency_min[i]);
5827                         mbps += le16_to_cpu(cp->cgn_bw_min[i]);
5828                         avalue += le16_to_cpu(cp->cgn_alarm_min[i]);
5829                 }
5830                 if (lvalue)             /* Avg of latency averages */
5831                         lvalue /= LPFC_MIN_HOUR;
5832                 if (mbps)               /* Avg of Bandwidth averages */
5833                         mvalue = mbps / LPFC_MIN_HOUR;
5834
5835                 lptr = &cp->cgn_drvr_hr[index];
5836                 *lptr = cpu_to_le32(dvalue);
5837                 lptr = &cp->cgn_warn_hr[index];
5838                 *lptr = cpu_to_le32(wvalue);
5839                 lptr = &cp->cgn_latency_hr[index];
5840                 *lptr = cpu_to_le32(lvalue);
5841                 mptr = &cp->cgn_bw_hr[index];
5842                 *mptr = cpu_to_le16(mvalue);
5843                 lptr = &cp->cgn_alarm_hr[index];
5844                 *lptr = cpu_to_le32(avalue);
5845
5846                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5847                                 "2419 Congestion Info - hour "
5848                                 "(%d): %d %d %d %d %d\n",
5849                                 index, dvalue, wvalue, lvalue, mvalue, avalue);
5850         }
5851
5852         /* Every day */
5853         if ((phba->cgn_evt_minute % LPFC_MIN_DAY) == 0) {
5854                 /* Record congestion buffer info - every hour
5855                  * Collapse all hours into a day. Rotate days
5856                  * after LPFC_MAX_CGN_DAYS.
5857                  */
5858                 index = ++cp->cgn_index_day;
5859                 if (cp->cgn_index_day == LPFC_MAX_CGN_DAYS) {
5860                         cp->cgn_index_day = 0;
5861                         index = 0;
5862                 }
5863
5864                 dvalue = 0;
5865                 wvalue = 0;
5866                 lvalue = 0;
5867                 mvalue = 0;
5868                 mbps = 0;
5869                 avalue = 0;
5870                 for (i = 0; i < LPFC_HOUR_DAY; i++) {
5871                         dvalue += le32_to_cpu(cp->cgn_drvr_hr[i]);
5872                         wvalue += le32_to_cpu(cp->cgn_warn_hr[i]);
5873                         lvalue += le32_to_cpu(cp->cgn_latency_hr[i]);
5874                         mbps += le16_to_cpu(cp->cgn_bw_hr[i]);
5875                         avalue += le32_to_cpu(cp->cgn_alarm_hr[i]);
5876                 }
5877                 if (lvalue)             /* Avg of latency averages */
5878                         lvalue /= LPFC_HOUR_DAY;
5879                 if (mbps)               /* Avg of Bandwidth averages */
5880                         mvalue = mbps / LPFC_HOUR_DAY;
5881
5882                 lptr = &cp->cgn_drvr_day[index];
5883                 *lptr = cpu_to_le32(dvalue);
5884                 lptr = &cp->cgn_warn_day[index];
5885                 *lptr = cpu_to_le32(wvalue);
5886                 lptr = &cp->cgn_latency_day[index];
5887                 *lptr = cpu_to_le32(lvalue);
5888                 mptr = &cp->cgn_bw_day[index];
5889                 *mptr = cpu_to_le16(mvalue);
5890                 lptr = &cp->cgn_alarm_day[index];
5891                 *lptr = cpu_to_le32(avalue);
5892
5893                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5894                                 "2420 Congestion Info - daily (%d): "
5895                                 "%d %d %d %d %d\n",
5896                                 index, dvalue, wvalue, lvalue, mvalue, avalue);
5897         }
5898
5899         /* Use the frequency found in the last rcv'ed FPIN */
5900         value = phba->cgn_fpin_frequency;
5901         cp->cgn_warn_freq = cpu_to_le16(value);
5902         cp->cgn_alarm_freq = cpu_to_le16(value);
5903
5904         lvalue = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
5905                                      LPFC_CGN_CRC32_SEED);
5906         cp->cgn_info_crc = cpu_to_le32(lvalue);
5907
5908         hrtimer_forward_now(timer, ktime_set(0, LPFC_SEC_MIN * NSEC_PER_SEC));
5909
5910         return HRTIMER_RESTART;
5911 }
5912
5913 /**
5914  * lpfc_calc_cmf_latency - latency from start of rxate timer interval
5915  * @phba: The Hba for which this call is being executed.
5916  *
5917  * The routine calculates the latency from the beginning of the CMF timer
5918  * interval to the current point in time. It is called from IO completion
5919  * when we exceed our Bandwidth limitation for the time interval.
5920  */
5921 uint32_t
5922 lpfc_calc_cmf_latency(struct lpfc_hba *phba)
5923 {
5924         struct timespec64 cmpl_time;
5925         uint32_t msec = 0;
5926
5927         ktime_get_real_ts64(&cmpl_time);
5928
5929         /* This routine works on a ms granularity so sec and usec are
5930          * converted accordingly.
5931          */
5932         if (cmpl_time.tv_sec == phba->cmf_latency.tv_sec) {
5933                 msec = (cmpl_time.tv_nsec - phba->cmf_latency.tv_nsec) /
5934                         NSEC_PER_MSEC;
5935         } else {
5936                 if (cmpl_time.tv_nsec >= phba->cmf_latency.tv_nsec) {
5937                         msec = (cmpl_time.tv_sec -
5938                                 phba->cmf_latency.tv_sec) * MSEC_PER_SEC;
5939                         msec += ((cmpl_time.tv_nsec -
5940                                   phba->cmf_latency.tv_nsec) / NSEC_PER_MSEC);
5941                 } else {
5942                         msec = (cmpl_time.tv_sec - phba->cmf_latency.tv_sec -
5943                                 1) * MSEC_PER_SEC;
5944                         msec += (((NSEC_PER_SEC - phba->cmf_latency.tv_nsec) +
5945                                  cmpl_time.tv_nsec) / NSEC_PER_MSEC);
5946                 }
5947         }
5948         return msec;
5949 }
5950
5951 /**
5952  * lpfc_cmf_timer -  This is the timer function for one congestion
5953  * rate interval.
5954  * @timer: Pointer to the high resolution timer that expired
5955  */
5956 static enum hrtimer_restart
5957 lpfc_cmf_timer(struct hrtimer *timer)
5958 {
5959         struct lpfc_hba *phba = container_of(timer, struct lpfc_hba,
5960                                              cmf_timer);
5961         struct rx_info_entry entry;
5962         uint32_t io_cnt;
5963         uint32_t busy, max_read;
5964         uint64_t total, rcv, lat, mbpi, extra, cnt;
5965         int timer_interval = LPFC_CMF_INTERVAL;
5966         uint32_t ms;
5967         struct lpfc_cgn_stat *cgs;
5968         int cpu;
5969
5970         /* Only restart the timer if congestion mgmt is on */
5971         if (phba->cmf_active_mode == LPFC_CFG_OFF ||
5972             !phba->cmf_latency.tv_sec) {
5973                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
5974                                 "6224 CMF timer exit: %d %lld\n",
5975                                 phba->cmf_active_mode,
5976                                 (uint64_t)phba->cmf_latency.tv_sec);
5977                 return HRTIMER_NORESTART;
5978         }
5979
5980         /* If pport is not ready yet, just exit and wait for
5981          * the next timer cycle to hit.
5982          */
5983         if (!phba->pport)
5984                 goto skip;
5985
5986         /* Do not block SCSI IO while in the timer routine since
5987          * total_bytes will be cleared
5988          */
5989         atomic_set(&phba->cmf_stop_io, 1);
5990
5991         /* First we need to calculate the actual ms between
5992          * the last timer interrupt and this one. We ask for
5993          * LPFC_CMF_INTERVAL, however the actual time may
5994          * vary depending on system overhead.
5995          */
5996         ms = lpfc_calc_cmf_latency(phba);
5997
5998
5999         /* Immediately after we calculate the time since the last
6000          * timer interrupt, set the start time for the next
6001          * interrupt
6002          */
6003         ktime_get_real_ts64(&phba->cmf_latency);
6004
6005         phba->cmf_link_byte_count =
6006                 div_u64(phba->cmf_max_line_rate * LPFC_CMF_INTERVAL, 1000);
6007
6008         /* Collect all the stats from the prior timer interval */
6009         total = 0;
6010         io_cnt = 0;
6011         lat = 0;
6012         rcv = 0;
6013         for_each_present_cpu(cpu) {
6014                 cgs = per_cpu_ptr(phba->cmf_stat, cpu);
6015                 total += atomic64_xchg(&cgs->total_bytes, 0);
6016                 io_cnt += atomic_xchg(&cgs->rx_io_cnt, 0);
6017                 lat += atomic64_xchg(&cgs->rx_latency, 0);
6018                 rcv += atomic64_xchg(&cgs->rcv_bytes, 0);
6019         }
6020
6021         /* Before we issue another CMF_SYNC_WQE, retrieve the BW
6022          * returned from the last CMF_SYNC_WQE issued, from
6023          * cmf_last_sync_bw. This will be the target BW for
6024          * this next timer interval.
6025          */
6026         if (phba->cmf_active_mode == LPFC_CFG_MANAGED &&
6027             phba->link_state != LPFC_LINK_DOWN &&
6028             phba->hba_flag & HBA_SETUP) {
6029                 mbpi = phba->cmf_last_sync_bw;
6030                 phba->cmf_last_sync_bw = 0;
6031                 extra = 0;
6032
6033                 /* Calculate any extra bytes needed to account for the
6034                  * timer accuracy. If we are less than LPFC_CMF_INTERVAL
6035                  * calculate the adjustment needed for total to reflect
6036                  * a full LPFC_CMF_INTERVAL.
6037                  */
6038                 if (ms && ms < LPFC_CMF_INTERVAL) {
6039                         cnt = div_u64(total, ms); /* bytes per ms */
6040                         cnt *= LPFC_CMF_INTERVAL; /* what total should be */
6041                         extra = cnt - total;
6042                 }
6043                 lpfc_issue_cmf_sync_wqe(phba, LPFC_CMF_INTERVAL, total + extra);
6044         } else {
6045                 /* For Monitor mode or link down we want mbpi
6046                  * to be the full link speed
6047                  */
6048                 mbpi = phba->cmf_link_byte_count;
6049                 extra = 0;
6050         }
6051         phba->cmf_timer_cnt++;
6052
6053         if (io_cnt) {
6054                 /* Update congestion info buffer latency in us */
6055                 atomic_add(io_cnt, &phba->cgn_latency_evt_cnt);
6056                 atomic64_add(lat, &phba->cgn_latency_evt);
6057         }
6058         busy = atomic_xchg(&phba->cmf_busy, 0);
6059         max_read = atomic_xchg(&phba->rx_max_read_cnt, 0);
6060
6061         /* Calculate MBPI for the next timer interval */
6062         if (mbpi) {
6063                 if (mbpi > phba->cmf_link_byte_count ||
6064                     phba->cmf_active_mode == LPFC_CFG_MONITOR)
6065                         mbpi = phba->cmf_link_byte_count;
6066
6067                 /* Change max_bytes_per_interval to what the prior
6068                  * CMF_SYNC_WQE cmpl indicated.
6069                  */
6070                 if (mbpi != phba->cmf_max_bytes_per_interval)
6071                         phba->cmf_max_bytes_per_interval = mbpi;
6072         }
6073
6074         /* Save rxmonitor information for debug */
6075         if (phba->rx_monitor) {
6076                 entry.total_bytes = total;
6077                 entry.cmf_bytes = total + extra;
6078                 entry.rcv_bytes = rcv;
6079                 entry.cmf_busy = busy;
6080                 entry.cmf_info = phba->cmf_active_info;
6081                 if (io_cnt) {
6082                         entry.avg_io_latency = div_u64(lat, io_cnt);
6083                         entry.avg_io_size = div_u64(rcv, io_cnt);
6084                 } else {
6085                         entry.avg_io_latency = 0;
6086                         entry.avg_io_size = 0;
6087                 }
6088                 entry.max_read_cnt = max_read;
6089                 entry.io_cnt = io_cnt;
6090                 entry.max_bytes_per_interval = mbpi;
6091                 if (phba->cmf_active_mode == LPFC_CFG_MANAGED)
6092                         entry.timer_utilization = phba->cmf_last_ts;
6093                 else
6094                         entry.timer_utilization = ms;
6095                 entry.timer_interval = ms;
6096                 phba->cmf_last_ts = 0;
6097
6098                 lpfc_rx_monitor_record(phba->rx_monitor, &entry);
6099         }
6100
6101         if (phba->cmf_active_mode == LPFC_CFG_MONITOR) {
6102                 /* If Monitor mode, check if we are oversubscribed
6103                  * against the full line rate.
6104                  */
6105                 if (mbpi && total > mbpi)
6106                         atomic_inc(&phba->cgn_driver_evt_cnt);
6107         }
6108         phba->rx_block_cnt += div_u64(rcv, 512);  /* save 512 byte block cnt */
6109
6110         /* Since total_bytes has already been zero'ed, its okay to unblock
6111          * after max_bytes_per_interval is setup.
6112          */
6113         if (atomic_xchg(&phba->cmf_bw_wait, 0))
6114                 queue_work(phba->wq, &phba->unblock_request_work);
6115
6116         /* SCSI IO is now unblocked */
6117         atomic_set(&phba->cmf_stop_io, 0);
6118
6119 skip:
6120         hrtimer_forward_now(timer,
6121                             ktime_set(0, timer_interval * NSEC_PER_MSEC));
6122         return HRTIMER_RESTART;
6123 }
6124
6125 #define trunk_link_status(__idx)\
6126         bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6127                ((phba->trunk_link.link##__idx.state == LPFC_LINK_UP) ?\
6128                 "Link up" : "Link down") : "NA"
6129 /* Did port __idx reported an error */
6130 #define trunk_port_fault(__idx)\
6131         bf_get(lpfc_acqe_fc_la_trunk_config_port##__idx, acqe_fc) ?\
6132                (port_fault & (1 << __idx) ? "YES" : "NO") : "NA"
6133
6134 static void
6135 lpfc_update_trunk_link_status(struct lpfc_hba *phba,
6136                               struct lpfc_acqe_fc_la *acqe_fc)
6137 {
6138         uint8_t port_fault = bf_get(lpfc_acqe_fc_la_trunk_linkmask, acqe_fc);
6139         uint8_t err = bf_get(lpfc_acqe_fc_la_trunk_fault, acqe_fc);
6140         u8 cnt = 0;
6141
6142         phba->sli4_hba.link_state.speed =
6143                 lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6144                                 bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6145
6146         phba->sli4_hba.link_state.logical_speed =
6147                                 bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6148         /* We got FC link speed, convert to fc_linkspeed (READ_TOPOLOGY) */
6149         phba->fc_linkspeed =
6150                  lpfc_async_link_speed_to_read_top(
6151                                 phba,
6152                                 bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6153
6154         if (bf_get(lpfc_acqe_fc_la_trunk_config_port0, acqe_fc)) {
6155                 phba->trunk_link.link0.state =
6156                         bf_get(lpfc_acqe_fc_la_trunk_link_status_port0, acqe_fc)
6157                         ? LPFC_LINK_UP : LPFC_LINK_DOWN;
6158                 phba->trunk_link.link0.fault = port_fault & 0x1 ? err : 0;
6159                 cnt++;
6160         }
6161         if (bf_get(lpfc_acqe_fc_la_trunk_config_port1, acqe_fc)) {
6162                 phba->trunk_link.link1.state =
6163                         bf_get(lpfc_acqe_fc_la_trunk_link_status_port1, acqe_fc)
6164                         ? LPFC_LINK_UP : LPFC_LINK_DOWN;
6165                 phba->trunk_link.link1.fault = port_fault & 0x2 ? err : 0;
6166                 cnt++;
6167         }
6168         if (bf_get(lpfc_acqe_fc_la_trunk_config_port2, acqe_fc)) {
6169                 phba->trunk_link.link2.state =
6170                         bf_get(lpfc_acqe_fc_la_trunk_link_status_port2, acqe_fc)
6171                         ? LPFC_LINK_UP : LPFC_LINK_DOWN;
6172                 phba->trunk_link.link2.fault = port_fault & 0x4 ? err : 0;
6173                 cnt++;
6174         }
6175         if (bf_get(lpfc_acqe_fc_la_trunk_config_port3, acqe_fc)) {
6176                 phba->trunk_link.link3.state =
6177                         bf_get(lpfc_acqe_fc_la_trunk_link_status_port3, acqe_fc)
6178                         ? LPFC_LINK_UP : LPFC_LINK_DOWN;
6179                 phba->trunk_link.link3.fault = port_fault & 0x8 ? err : 0;
6180                 cnt++;
6181         }
6182
6183         if (cnt)
6184                 phba->trunk_link.phy_lnk_speed =
6185                         phba->sli4_hba.link_state.logical_speed / (cnt * 1000);
6186         else
6187                 phba->trunk_link.phy_lnk_speed = LPFC_LINK_SPEED_UNKNOWN;
6188
6189         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6190                         "2910 Async FC Trunking Event - Speed:%d\n"
6191                         "\tLogical speed:%d "
6192                         "port0: %s port1: %s port2: %s port3: %s\n",
6193                         phba->sli4_hba.link_state.speed,
6194                         phba->sli4_hba.link_state.logical_speed,
6195                         trunk_link_status(0), trunk_link_status(1),
6196                         trunk_link_status(2), trunk_link_status(3));
6197
6198         if (phba->cmf_active_mode != LPFC_CFG_OFF)
6199                 lpfc_cmf_signal_init(phba);
6200
6201         if (port_fault)
6202                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6203                                 "3202 trunk error:0x%x (%s) seen on port0:%s "
6204                                 /*
6205                                  * SLI-4: We have only 0xA error codes
6206                                  * defined as of now. print an appropriate
6207                                  * message in case driver needs to be updated.
6208                                  */
6209                                 "port1:%s port2:%s port3:%s\n", err, err > 0xA ?
6210                                 "UNDEFINED. update driver." : trunk_errmsg[err],
6211                                 trunk_port_fault(0), trunk_port_fault(1),
6212                                 trunk_port_fault(2), trunk_port_fault(3));
6213 }
6214
6215
6216 /**
6217  * lpfc_sli4_async_fc_evt - Process the asynchronous FC link event
6218  * @phba: pointer to lpfc hba data structure.
6219  * @acqe_fc: pointer to the async fc completion queue entry.
6220  *
6221  * This routine is to handle the SLI4 asynchronous FC event. It will simply log
6222  * that the event was received and then issue a read_topology mailbox command so
6223  * that the rest of the driver will treat it the same as SLI3.
6224  **/
6225 static void
6226 lpfc_sli4_async_fc_evt(struct lpfc_hba *phba, struct lpfc_acqe_fc_la *acqe_fc)
6227 {
6228         LPFC_MBOXQ_t *pmb;
6229         MAILBOX_t *mb;
6230         struct lpfc_mbx_read_top *la;
6231         char *log_level;
6232         int rc;
6233
6234         if (bf_get(lpfc_trailer_type, acqe_fc) !=
6235             LPFC_FC_LA_EVENT_TYPE_FC_LINK) {
6236                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6237                                 "2895 Non FC link Event detected.(%d)\n",
6238                                 bf_get(lpfc_trailer_type, acqe_fc));
6239                 return;
6240         }
6241
6242         if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6243             LPFC_FC_LA_TYPE_TRUNKING_EVENT) {
6244                 lpfc_update_trunk_link_status(phba, acqe_fc);
6245                 return;
6246         }
6247
6248         /* Keep the link status for extra SLI4 state machine reference */
6249         phba->sli4_hba.link_state.speed =
6250                         lpfc_sli4_port_speed_parse(phba, LPFC_TRAILER_CODE_FC,
6251                                 bf_get(lpfc_acqe_fc_la_speed, acqe_fc));
6252         phba->sli4_hba.link_state.duplex = LPFC_ASYNC_LINK_DUPLEX_FULL;
6253         phba->sli4_hba.link_state.topology =
6254                                 bf_get(lpfc_acqe_fc_la_topology, acqe_fc);
6255         phba->sli4_hba.link_state.status =
6256                                 bf_get(lpfc_acqe_fc_la_att_type, acqe_fc);
6257         phba->sli4_hba.link_state.type =
6258                                 bf_get(lpfc_acqe_fc_la_port_type, acqe_fc);
6259         phba->sli4_hba.link_state.number =
6260                                 bf_get(lpfc_acqe_fc_la_port_number, acqe_fc);
6261         phba->sli4_hba.link_state.fault =
6262                                 bf_get(lpfc_acqe_link_fault, acqe_fc);
6263         phba->sli4_hba.link_state.link_status =
6264                                 bf_get(lpfc_acqe_fc_la_link_status, acqe_fc);
6265
6266         /*
6267          * Only select attention types need logical speed modification to what
6268          * was previously set.
6269          */
6270         if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_LINK_UP &&
6271             phba->sli4_hba.link_state.status < LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6272                 if (bf_get(lpfc_acqe_fc_la_att_type, acqe_fc) ==
6273                     LPFC_FC_LA_TYPE_LINK_DOWN)
6274                         phba->sli4_hba.link_state.logical_speed = 0;
6275                 else if (!phba->sli4_hba.conf_trunk)
6276                         phba->sli4_hba.link_state.logical_speed =
6277                                 bf_get(lpfc_acqe_fc_la_llink_spd, acqe_fc) * 10;
6278         }
6279
6280         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6281                         "2896 Async FC event - Speed:%dGBaud Topology:x%x "
6282                         "LA Type:x%x Port Type:%d Port Number:%d Logical speed:"
6283                         "%dMbps Fault:x%x Link Status:x%x\n",
6284                         phba->sli4_hba.link_state.speed,
6285                         phba->sli4_hba.link_state.topology,
6286                         phba->sli4_hba.link_state.status,
6287                         phba->sli4_hba.link_state.type,
6288                         phba->sli4_hba.link_state.number,
6289                         phba->sli4_hba.link_state.logical_speed,
6290                         phba->sli4_hba.link_state.fault,
6291                         phba->sli4_hba.link_state.link_status);
6292
6293         /*
6294          * The following attention types are informational only, providing
6295          * further details about link status.  Overwrite the value of
6296          * link_state.status appropriately.  No further action is required.
6297          */
6298         if (phba->sli4_hba.link_state.status >= LPFC_FC_LA_TYPE_ACTIVATE_FAIL) {
6299                 switch (phba->sli4_hba.link_state.status) {
6300                 case LPFC_FC_LA_TYPE_ACTIVATE_FAIL:
6301                         log_level = KERN_WARNING;
6302                         phba->sli4_hba.link_state.status =
6303                                         LPFC_FC_LA_TYPE_LINK_DOWN;
6304                         break;
6305                 case LPFC_FC_LA_TYPE_LINK_RESET_PRTCL_EVT:
6306                         /*
6307                          * During bb credit recovery establishment, receiving
6308                          * this attention type is normal.  Link Up attention
6309                          * type is expected to occur before this informational
6310                          * attention type so keep the Link Up status.
6311                          */
6312                         log_level = KERN_INFO;
6313                         phba->sli4_hba.link_state.status =
6314                                         LPFC_FC_LA_TYPE_LINK_UP;
6315                         break;
6316                 default:
6317                         log_level = KERN_INFO;
6318                         break;
6319                 }
6320                 lpfc_log_msg(phba, log_level, LOG_SLI,
6321                              "2992 Async FC event - Informational Link "
6322                              "Attention Type x%x\n",
6323                              bf_get(lpfc_acqe_fc_la_att_type, acqe_fc));
6324                 return;
6325         }
6326
6327         pmb = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6328         if (!pmb) {
6329                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6330                                 "2897 The mboxq allocation failed\n");
6331                 return;
6332         }
6333         rc = lpfc_mbox_rsrc_prep(phba, pmb);
6334         if (rc) {
6335                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6336                                 "2898 The mboxq prep failed\n");
6337                 goto out_free_pmb;
6338         }
6339
6340         /* Cleanup any outstanding ELS commands */
6341         lpfc_els_flush_all_cmd(phba);
6342
6343         /* Block ELS IOCBs until we have done process link event */
6344         phba->sli4_hba.els_wq->pring->flag |= LPFC_STOP_IOCB_EVENT;
6345
6346         /* Update link event statistics */
6347         phba->sli.slistat.link_event++;
6348
6349         /* Create lpfc_handle_latt mailbox command from link ACQE */
6350         lpfc_read_topology(phba, pmb, (struct lpfc_dmabuf *)pmb->ctx_buf);
6351         pmb->mbox_cmpl = lpfc_mbx_cmpl_read_topology;
6352         pmb->vport = phba->pport;
6353
6354         if (phba->sli4_hba.link_state.status != LPFC_FC_LA_TYPE_LINK_UP) {
6355                 phba->link_flag &= ~(LS_MDS_LINK_DOWN | LS_MDS_LOOPBACK);
6356
6357                 switch (phba->sli4_hba.link_state.status) {
6358                 case LPFC_FC_LA_TYPE_MDS_LINK_DOWN:
6359                         phba->link_flag |= LS_MDS_LINK_DOWN;
6360                         break;
6361                 case LPFC_FC_LA_TYPE_MDS_LOOPBACK:
6362                         phba->link_flag |= LS_MDS_LOOPBACK;
6363                         break;
6364                 default:
6365                         break;
6366                 }
6367
6368                 /* Initialize completion status */
6369                 mb = &pmb->u.mb;
6370                 mb->mbxStatus = MBX_SUCCESS;
6371
6372                 /* Parse port fault information field */
6373                 lpfc_sli4_parse_latt_fault(phba, (void *)acqe_fc);
6374
6375                 /* Parse and translate link attention fields */
6376                 la = (struct lpfc_mbx_read_top *)&pmb->u.mb.un.varReadTop;
6377                 la->eventTag = acqe_fc->event_tag;
6378
6379                 if (phba->sli4_hba.link_state.status ==
6380                     LPFC_FC_LA_TYPE_UNEXP_WWPN) {
6381                         bf_set(lpfc_mbx_read_top_att_type, la,
6382                                LPFC_FC_LA_TYPE_UNEXP_WWPN);
6383                 } else {
6384                         bf_set(lpfc_mbx_read_top_att_type, la,
6385                                LPFC_FC_LA_TYPE_LINK_DOWN);
6386                 }
6387                 /* Invoke the mailbox command callback function */
6388                 lpfc_mbx_cmpl_read_topology(phba, pmb);
6389
6390                 return;
6391         }
6392
6393         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
6394         if (rc == MBX_NOT_FINISHED)
6395                 goto out_free_pmb;
6396         return;
6397
6398 out_free_pmb:
6399         lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
6400 }
6401
6402 /**
6403  * lpfc_sli4_async_sli_evt - Process the asynchronous SLI link event
6404  * @phba: pointer to lpfc hba data structure.
6405  * @acqe_sli: pointer to the async SLI completion queue entry.
6406  *
6407  * This routine is to handle the SLI4 asynchronous SLI events.
6408  **/
6409 static void
6410 lpfc_sli4_async_sli_evt(struct lpfc_hba *phba, struct lpfc_acqe_sli *acqe_sli)
6411 {
6412         char port_name;
6413         char message[128];
6414         uint8_t status;
6415         uint8_t evt_type;
6416         uint8_t operational = 0;
6417         struct temp_event temp_event_data;
6418         struct lpfc_acqe_misconfigured_event *misconfigured;
6419         struct lpfc_acqe_cgn_signal *cgn_signal;
6420         struct Scsi_Host  *shost;
6421         struct lpfc_vport **vports;
6422         int rc, i, cnt;
6423
6424         evt_type = bf_get(lpfc_trailer_type, acqe_sli);
6425
6426         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6427                         "2901 Async SLI event - Type:%d, Event Data: x%08x "
6428                         "x%08x x%08x x%08x\n", evt_type,
6429                         acqe_sli->event_data1, acqe_sli->event_data2,
6430                         acqe_sli->event_data3, acqe_sli->trailer);
6431
6432         port_name = phba->Port[0];
6433         if (port_name == 0x00)
6434                 port_name = '?'; /* get port name is empty */
6435
6436         switch (evt_type) {
6437         case LPFC_SLI_EVENT_TYPE_OVER_TEMP:
6438                 temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6439                 temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
6440                 temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6441
6442                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6443                                 "3190 Over Temperature:%d Celsius- Port Name %c\n",
6444                                 acqe_sli->event_data1, port_name);
6445
6446                 phba->sfp_warning |= LPFC_TRANSGRESSION_HIGH_TEMPERATURE;
6447                 shost = lpfc_shost_from_vport(phba->pport);
6448                 fc_host_post_vendor_event(shost, fc_get_event_number(),
6449                                           sizeof(temp_event_data),
6450                                           (char *)&temp_event_data,
6451                                           SCSI_NL_VID_TYPE_PCI
6452                                           | PCI_VENDOR_ID_EMULEX);
6453                 break;
6454         case LPFC_SLI_EVENT_TYPE_NORM_TEMP:
6455                 temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6456                 temp_event_data.event_code = LPFC_NORMAL_TEMP;
6457                 temp_event_data.data = (uint32_t)acqe_sli->event_data1;
6458
6459                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_LDS_EVENT,
6460                                 "3191 Normal Temperature:%d Celsius - Port Name %c\n",
6461                                 acqe_sli->event_data1, port_name);
6462
6463                 shost = lpfc_shost_from_vport(phba->pport);
6464                 fc_host_post_vendor_event(shost, fc_get_event_number(),
6465                                           sizeof(temp_event_data),
6466                                           (char *)&temp_event_data,
6467                                           SCSI_NL_VID_TYPE_PCI
6468                                           | PCI_VENDOR_ID_EMULEX);
6469                 break;
6470         case LPFC_SLI_EVENT_TYPE_MISCONFIGURED:
6471                 misconfigured = (struct lpfc_acqe_misconfigured_event *)
6472                                         &acqe_sli->event_data1;
6473
6474                 /* fetch the status for this port */
6475                 switch (phba->sli4_hba.lnk_info.lnk_no) {
6476                 case LPFC_LINK_NUMBER_0:
6477                         status = bf_get(lpfc_sli_misconfigured_port0_state,
6478                                         &misconfigured->theEvent);
6479                         operational = bf_get(lpfc_sli_misconfigured_port0_op,
6480                                         &misconfigured->theEvent);
6481                         break;
6482                 case LPFC_LINK_NUMBER_1:
6483                         status = bf_get(lpfc_sli_misconfigured_port1_state,
6484                                         &misconfigured->theEvent);
6485                         operational = bf_get(lpfc_sli_misconfigured_port1_op,
6486                                         &misconfigured->theEvent);
6487                         break;
6488                 case LPFC_LINK_NUMBER_2:
6489                         status = bf_get(lpfc_sli_misconfigured_port2_state,
6490                                         &misconfigured->theEvent);
6491                         operational = bf_get(lpfc_sli_misconfigured_port2_op,
6492                                         &misconfigured->theEvent);
6493                         break;
6494                 case LPFC_LINK_NUMBER_3:
6495                         status = bf_get(lpfc_sli_misconfigured_port3_state,
6496                                         &misconfigured->theEvent);
6497                         operational = bf_get(lpfc_sli_misconfigured_port3_op,
6498                                         &misconfigured->theEvent);
6499                         break;
6500                 default:
6501                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6502                                         "3296 "
6503                                         "LPFC_SLI_EVENT_TYPE_MISCONFIGURED "
6504                                         "event: Invalid link %d",
6505                                         phba->sli4_hba.lnk_info.lnk_no);
6506                         return;
6507                 }
6508
6509                 /* Skip if optic state unchanged */
6510                 if (phba->sli4_hba.lnk_info.optic_state == status)
6511                         return;
6512
6513                 switch (status) {
6514                 case LPFC_SLI_EVENT_STATUS_VALID:
6515                         sprintf(message, "Physical Link is functional");
6516                         break;
6517                 case LPFC_SLI_EVENT_STATUS_NOT_PRESENT:
6518                         sprintf(message, "Optics faulted/incorrectly "
6519                                 "installed/not installed - Reseat optics, "
6520                                 "if issue not resolved, replace.");
6521                         break;
6522                 case LPFC_SLI_EVENT_STATUS_WRONG_TYPE:
6523                         sprintf(message,
6524                                 "Optics of two types installed - Remove one "
6525                                 "optic or install matching pair of optics.");
6526                         break;
6527                 case LPFC_SLI_EVENT_STATUS_UNSUPPORTED:
6528                         sprintf(message, "Incompatible optics - Replace with "
6529                                 "compatible optics for card to function.");
6530                         break;
6531                 case LPFC_SLI_EVENT_STATUS_UNQUALIFIED:
6532                         sprintf(message, "Unqualified optics - Replace with "
6533                                 "Avago optics for Warranty and Technical "
6534                                 "Support - Link is%s operational",
6535                                 (operational) ? " not" : "");
6536                         break;
6537                 case LPFC_SLI_EVENT_STATUS_UNCERTIFIED:
6538                         sprintf(message, "Uncertified optics - Replace with "
6539                                 "Avago-certified optics to enable link "
6540                                 "operation - Link is%s operational",
6541                                 (operational) ? " not" : "");
6542                         break;
6543                 default:
6544                         /* firmware is reporting a status we don't know about */
6545                         sprintf(message, "Unknown event status x%02x", status);
6546                         break;
6547                 }
6548
6549                 /* Issue READ_CONFIG mbox command to refresh supported speeds */
6550                 rc = lpfc_sli4_read_config(phba);
6551                 if (rc) {
6552                         phba->lmt = 0;
6553                         lpfc_printf_log(phba, KERN_ERR,
6554                                         LOG_TRACE_EVENT,
6555                                         "3194 Unable to retrieve supported "
6556                                         "speeds, rc = 0x%x\n", rc);
6557                 }
6558                 rc = lpfc_sli4_refresh_params(phba);
6559                 if (rc) {
6560                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6561                                         "3174 Unable to update pls support, "
6562                                         "rc x%x\n", rc);
6563                 }
6564                 vports = lpfc_create_vport_work_array(phba);
6565                 if (vports != NULL) {
6566                         for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6567                                         i++) {
6568                                 shost = lpfc_shost_from_vport(vports[i]);
6569                                 lpfc_host_supported_speeds_set(shost);
6570                         }
6571                 }
6572                 lpfc_destroy_vport_work_array(phba, vports);
6573
6574                 phba->sli4_hba.lnk_info.optic_state = status;
6575                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6576                                 "3176 Port Name %c %s\n", port_name, message);
6577                 break;
6578         case LPFC_SLI_EVENT_TYPE_REMOTE_DPORT:
6579                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6580                                 "3192 Remote DPort Test Initiated - "
6581                                 "Event Data1:x%08x Event Data2: x%08x\n",
6582                                 acqe_sli->event_data1, acqe_sli->event_data2);
6583                 break;
6584         case LPFC_SLI_EVENT_TYPE_PORT_PARAMS_CHG:
6585                 /* Call FW to obtain active parms */
6586                 lpfc_sli4_cgn_parm_chg_evt(phba);
6587                 break;
6588         case LPFC_SLI_EVENT_TYPE_MISCONF_FAWWN:
6589                 /* Misconfigured WWN. Reports that the SLI Port is configured
6590                  * to use FA-WWN, but the attached device doesn’t support it.
6591                  * Event Data1 - N.A, Event Data2 - N.A
6592                  * This event only happens on the physical port.
6593                  */
6594                 lpfc_log_msg(phba, KERN_WARNING, LOG_SLI | LOG_DISCOVERY,
6595                              "2699 Misconfigured FA-PWWN - Attached device "
6596                              "does not support FA-PWWN\n");
6597                 phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_FABRIC;
6598                 memset(phba->pport->fc_portname.u.wwn, 0,
6599                        sizeof(struct lpfc_name));
6600                 break;
6601         case LPFC_SLI_EVENT_TYPE_EEPROM_FAILURE:
6602                 /* EEPROM failure. No driver action is required */
6603                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6604                              "2518 EEPROM failure - "
6605                              "Event Data1: x%08x Event Data2: x%08x\n",
6606                              acqe_sli->event_data1, acqe_sli->event_data2);
6607                 break;
6608         case LPFC_SLI_EVENT_TYPE_CGN_SIGNAL:
6609                 if (phba->cmf_active_mode == LPFC_CFG_OFF)
6610                         break;
6611                 cgn_signal = (struct lpfc_acqe_cgn_signal *)
6612                                         &acqe_sli->event_data1;
6613                 phba->cgn_acqe_cnt++;
6614
6615                 cnt = bf_get(lpfc_warn_acqe, cgn_signal);
6616                 atomic64_add(cnt, &phba->cgn_acqe_stat.warn);
6617                 atomic64_add(cgn_signal->alarm_cnt, &phba->cgn_acqe_stat.alarm);
6618
6619                 /* no threshold for CMF, even 1 signal will trigger an event */
6620
6621                 /* Alarm overrides warning, so check that first */
6622                 if (cgn_signal->alarm_cnt) {
6623                         if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6624                                 /* Keep track of alarm cnt for CMF_SYNC_WQE */
6625                                 atomic_add(cgn_signal->alarm_cnt,
6626                                            &phba->cgn_sync_alarm_cnt);
6627                         }
6628                 } else if (cnt) {
6629                         /* signal action needs to be taken */
6630                         if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
6631                             phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6632                                 /* Keep track of warning cnt for CMF_SYNC_WQE */
6633                                 atomic_add(cnt, &phba->cgn_sync_warn_cnt);
6634                         }
6635                 }
6636                 break;
6637         case LPFC_SLI_EVENT_TYPE_RD_SIGNAL:
6638                 /* May be accompanied by a temperature event */
6639                 lpfc_printf_log(phba, KERN_INFO,
6640                                 LOG_SLI | LOG_LINK_EVENT | LOG_LDS_EVENT,
6641                                 "2902 Remote Degrade Signaling: x%08x x%08x "
6642                                 "x%08x\n",
6643                                 acqe_sli->event_data1, acqe_sli->event_data2,
6644                                 acqe_sli->event_data3);
6645                 break;
6646         case LPFC_SLI_EVENT_TYPE_RESET_CM_STATS:
6647                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
6648                                 "2905 Reset CM statistics\n");
6649                 lpfc_sli4_async_cmstat_evt(phba);
6650                 break;
6651         default:
6652                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6653                                 "3193 Unrecognized SLI event, type: 0x%x",
6654                                 evt_type);
6655                 break;
6656         }
6657 }
6658
6659 /**
6660  * lpfc_sli4_perform_vport_cvl - Perform clear virtual link on a vport
6661  * @vport: pointer to vport data structure.
6662  *
6663  * This routine is to perform Clear Virtual Link (CVL) on a vport in
6664  * response to a CVL event.
6665  *
6666  * Return the pointer to the ndlp with the vport if successful, otherwise
6667  * return NULL.
6668  **/
6669 static struct lpfc_nodelist *
6670 lpfc_sli4_perform_vport_cvl(struct lpfc_vport *vport)
6671 {
6672         struct lpfc_nodelist *ndlp;
6673         struct Scsi_Host *shost;
6674         struct lpfc_hba *phba;
6675
6676         if (!vport)
6677                 return NULL;
6678         phba = vport->phba;
6679         if (!phba)
6680                 return NULL;
6681         ndlp = lpfc_findnode_did(vport, Fabric_DID);
6682         if (!ndlp) {
6683                 /* Cannot find existing Fabric ndlp, so allocate a new one */
6684                 ndlp = lpfc_nlp_init(vport, Fabric_DID);
6685                 if (!ndlp)
6686                         return NULL;
6687                 /* Set the node type */
6688                 ndlp->nlp_type |= NLP_FABRIC;
6689                 /* Put ndlp onto node list */
6690                 lpfc_enqueue_node(vport, ndlp);
6691         }
6692         if ((phba->pport->port_state < LPFC_FLOGI) &&
6693                 (phba->pport->port_state != LPFC_VPORT_FAILED))
6694                 return NULL;
6695         /* If virtual link is not yet instantiated ignore CVL */
6696         if ((vport != phba->pport) && (vport->port_state < LPFC_FDISC)
6697                 && (vport->port_state != LPFC_VPORT_FAILED))
6698                 return NULL;
6699         shost = lpfc_shost_from_vport(vport);
6700         if (!shost)
6701                 return NULL;
6702         lpfc_linkdown_port(vport);
6703         lpfc_cleanup_pending_mbox(vport);
6704         set_bit(FC_VPORT_CVL_RCVD, &vport->fc_flag);
6705
6706         return ndlp;
6707 }
6708
6709 /**
6710  * lpfc_sli4_perform_all_vport_cvl - Perform clear virtual link on all vports
6711  * @phba: pointer to lpfc hba data structure.
6712  *
6713  * This routine is to perform Clear Virtual Link (CVL) on all vports in
6714  * response to a FCF dead event.
6715  **/
6716 static void
6717 lpfc_sli4_perform_all_vport_cvl(struct lpfc_hba *phba)
6718 {
6719         struct lpfc_vport **vports;
6720         int i;
6721
6722         vports = lpfc_create_vport_work_array(phba);
6723         if (vports)
6724                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
6725                         lpfc_sli4_perform_vport_cvl(vports[i]);
6726         lpfc_destroy_vport_work_array(phba, vports);
6727 }
6728
6729 /**
6730  * lpfc_sli4_async_fip_evt - Process the asynchronous FCoE FIP event
6731  * @phba: pointer to lpfc hba data structure.
6732  * @acqe_fip: pointer to the async fcoe completion queue entry.
6733  *
6734  * This routine is to handle the SLI4 asynchronous fcoe event.
6735  **/
6736 static void
6737 lpfc_sli4_async_fip_evt(struct lpfc_hba *phba,
6738                         struct lpfc_acqe_fip *acqe_fip)
6739 {
6740         uint8_t event_type = bf_get(lpfc_trailer_type, acqe_fip);
6741         int rc;
6742         struct lpfc_vport *vport;
6743         struct lpfc_nodelist *ndlp;
6744         int active_vlink_present;
6745         struct lpfc_vport **vports;
6746         int i;
6747
6748         phba->fc_eventTag = acqe_fip->event_tag;
6749         phba->fcoe_eventtag = acqe_fip->event_tag;
6750         switch (event_type) {
6751         case LPFC_FIP_EVENT_TYPE_NEW_FCF:
6752         case LPFC_FIP_EVENT_TYPE_FCF_PARAM_MOD:
6753                 if (event_type == LPFC_FIP_EVENT_TYPE_NEW_FCF)
6754                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6755                                         "2546 New FCF event, evt_tag:x%x, "
6756                                         "index:x%x\n",
6757                                         acqe_fip->event_tag,
6758                                         acqe_fip->index);
6759                 else
6760                         lpfc_printf_log(phba, KERN_WARNING, LOG_FIP |
6761                                         LOG_DISCOVERY,
6762                                         "2788 FCF param modified event, "
6763                                         "evt_tag:x%x, index:x%x\n",
6764                                         acqe_fip->event_tag,
6765                                         acqe_fip->index);
6766                 if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6767                         /*
6768                          * During period of FCF discovery, read the FCF
6769                          * table record indexed by the event to update
6770                          * FCF roundrobin failover eligible FCF bmask.
6771                          */
6772                         lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6773                                         LOG_DISCOVERY,
6774                                         "2779 Read FCF (x%x) for updating "
6775                                         "roundrobin FCF failover bmask\n",
6776                                         acqe_fip->index);
6777                         rc = lpfc_sli4_read_fcf_rec(phba, acqe_fip->index);
6778                 }
6779
6780                 /* If the FCF discovery is in progress, do nothing. */
6781                 spin_lock_irq(&phba->hbalock);
6782                 if (phba->hba_flag & FCF_TS_INPROG) {
6783                         spin_unlock_irq(&phba->hbalock);
6784                         break;
6785                 }
6786                 /* If fast FCF failover rescan event is pending, do nothing */
6787                 if (phba->fcf.fcf_flag & (FCF_REDISC_EVT | FCF_REDISC_PEND)) {
6788                         spin_unlock_irq(&phba->hbalock);
6789                         break;
6790                 }
6791
6792                 /* If the FCF has been in discovered state, do nothing. */
6793                 if (phba->fcf.fcf_flag & FCF_SCAN_DONE) {
6794                         spin_unlock_irq(&phba->hbalock);
6795                         break;
6796                 }
6797                 spin_unlock_irq(&phba->hbalock);
6798
6799                 /* Otherwise, scan the entire FCF table and re-discover SAN */
6800                 lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6801                                 "2770 Start FCF table scan per async FCF "
6802                                 "event, evt_tag:x%x, index:x%x\n",
6803                                 acqe_fip->event_tag, acqe_fip->index);
6804                 rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba,
6805                                                      LPFC_FCOE_FCF_GET_FIRST);
6806                 if (rc)
6807                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6808                                         "2547 Issue FCF scan read FCF mailbox "
6809                                         "command failed (x%x)\n", rc);
6810                 break;
6811
6812         case LPFC_FIP_EVENT_TYPE_FCF_TABLE_FULL:
6813                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6814                                 "2548 FCF Table full count 0x%x tag 0x%x\n",
6815                                 bf_get(lpfc_acqe_fip_fcf_count, acqe_fip),
6816                                 acqe_fip->event_tag);
6817                 break;
6818
6819         case LPFC_FIP_EVENT_TYPE_FCF_DEAD:
6820                 phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6821                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6822                                 "2549 FCF (x%x) disconnected from network, "
6823                                  "tag:x%x\n", acqe_fip->index,
6824                                  acqe_fip->event_tag);
6825                 /*
6826                  * If we are in the middle of FCF failover process, clear
6827                  * the corresponding FCF bit in the roundrobin bitmap.
6828                  */
6829                 spin_lock_irq(&phba->hbalock);
6830                 if ((phba->fcf.fcf_flag & FCF_DISCOVERY) &&
6831                     (phba->fcf.current_rec.fcf_indx != acqe_fip->index)) {
6832                         spin_unlock_irq(&phba->hbalock);
6833                         /* Update FLOGI FCF failover eligible FCF bmask */
6834                         lpfc_sli4_fcf_rr_index_clear(phba, acqe_fip->index);
6835                         break;
6836                 }
6837                 spin_unlock_irq(&phba->hbalock);
6838
6839                 /* If the event is not for currently used fcf do nothing */
6840                 if (phba->fcf.current_rec.fcf_indx != acqe_fip->index)
6841                         break;
6842
6843                 /*
6844                  * Otherwise, request the port to rediscover the entire FCF
6845                  * table for a fast recovery from case that the current FCF
6846                  * is no longer valid as we are not in the middle of FCF
6847                  * failover process already.
6848                  */
6849                 spin_lock_irq(&phba->hbalock);
6850                 /* Mark the fast failover process in progress */
6851                 phba->fcf.fcf_flag |= FCF_DEAD_DISC;
6852                 spin_unlock_irq(&phba->hbalock);
6853
6854                 lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
6855                                 "2771 Start FCF fast failover process due to "
6856                                 "FCF DEAD event: evt_tag:x%x, fcf_index:x%x "
6857                                 "\n", acqe_fip->event_tag, acqe_fip->index);
6858                 rc = lpfc_sli4_redisc_fcf_table(phba);
6859                 if (rc) {
6860                         lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6861                                         LOG_TRACE_EVENT,
6862                                         "2772 Issue FCF rediscover mailbox "
6863                                         "command failed, fail through to FCF "
6864                                         "dead event\n");
6865                         spin_lock_irq(&phba->hbalock);
6866                         phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
6867                         spin_unlock_irq(&phba->hbalock);
6868                         /*
6869                          * Last resort will fail over by treating this
6870                          * as a link down to FCF registration.
6871                          */
6872                         lpfc_sli4_fcf_dead_failthrough(phba);
6873                 } else {
6874                         /* Reset FCF roundrobin bmask for new discovery */
6875                         lpfc_sli4_clear_fcf_rr_bmask(phba);
6876                         /*
6877                          * Handling fast FCF failover to a DEAD FCF event is
6878                          * considered equalivant to receiving CVL to all vports.
6879                          */
6880                         lpfc_sli4_perform_all_vport_cvl(phba);
6881                 }
6882                 break;
6883         case LPFC_FIP_EVENT_TYPE_CVL:
6884                 phba->fcoe_cvl_eventtag = acqe_fip->event_tag;
6885                 lpfc_printf_log(phba, KERN_ERR,
6886                                 LOG_TRACE_EVENT,
6887                         "2718 Clear Virtual Link Received for VPI 0x%x"
6888                         " tag 0x%x\n", acqe_fip->index, acqe_fip->event_tag);
6889
6890                 vport = lpfc_find_vport_by_vpid(phba,
6891                                                 acqe_fip->index);
6892                 ndlp = lpfc_sli4_perform_vport_cvl(vport);
6893                 if (!ndlp)
6894                         break;
6895                 active_vlink_present = 0;
6896
6897                 vports = lpfc_create_vport_work_array(phba);
6898                 if (vports) {
6899                         for (i = 0; i <= phba->max_vports && vports[i] != NULL;
6900                                         i++) {
6901                                 if (!test_bit(FC_VPORT_CVL_RCVD,
6902                                               &vports[i]->fc_flag) &&
6903                                     vports[i]->port_state > LPFC_FDISC) {
6904                                         active_vlink_present = 1;
6905                                         break;
6906                                 }
6907                         }
6908                         lpfc_destroy_vport_work_array(phba, vports);
6909                 }
6910
6911                 /*
6912                  * Don't re-instantiate if vport is marked for deletion.
6913                  * If we are here first then vport_delete is going to wait
6914                  * for discovery to complete.
6915                  */
6916                 if (!test_bit(FC_UNLOADING, &vport->load_flag) &&
6917                     active_vlink_present) {
6918                         /*
6919                          * If there are other active VLinks present,
6920                          * re-instantiate the Vlink using FDISC.
6921                          */
6922                         mod_timer(&ndlp->nlp_delayfunc,
6923                                   jiffies + msecs_to_jiffies(1000));
6924                         spin_lock_irq(&ndlp->lock);
6925                         ndlp->nlp_flag |= NLP_DELAY_TMO;
6926                         spin_unlock_irq(&ndlp->lock);
6927                         ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
6928                         vport->port_state = LPFC_FDISC;
6929                 } else {
6930                         /*
6931                          * Otherwise, we request port to rediscover
6932                          * the entire FCF table for a fast recovery
6933                          * from possible case that the current FCF
6934                          * is no longer valid if we are not already
6935                          * in the FCF failover process.
6936                          */
6937                         spin_lock_irq(&phba->hbalock);
6938                         if (phba->fcf.fcf_flag & FCF_DISCOVERY) {
6939                                 spin_unlock_irq(&phba->hbalock);
6940                                 break;
6941                         }
6942                         /* Mark the fast failover process in progress */
6943                         phba->fcf.fcf_flag |= FCF_ACVL_DISC;
6944                         spin_unlock_irq(&phba->hbalock);
6945                         lpfc_printf_log(phba, KERN_INFO, LOG_FIP |
6946                                         LOG_DISCOVERY,
6947                                         "2773 Start FCF failover per CVL, "
6948                                         "evt_tag:x%x\n", acqe_fip->event_tag);
6949                         rc = lpfc_sli4_redisc_fcf_table(phba);
6950                         if (rc) {
6951                                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP |
6952                                                 LOG_TRACE_EVENT,
6953                                                 "2774 Issue FCF rediscover "
6954                                                 "mailbox command failed, "
6955                                                 "through to CVL event\n");
6956                                 spin_lock_irq(&phba->hbalock);
6957                                 phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
6958                                 spin_unlock_irq(&phba->hbalock);
6959                                 /*
6960                                  * Last resort will be re-try on the
6961                                  * the current registered FCF entry.
6962                                  */
6963                                 lpfc_retry_pport_discovery(phba);
6964                         } else
6965                                 /*
6966                                  * Reset FCF roundrobin bmask for new
6967                                  * discovery.
6968                                  */
6969                                 lpfc_sli4_clear_fcf_rr_bmask(phba);
6970                 }
6971                 break;
6972         default:
6973                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6974                                 "0288 Unknown FCoE event type 0x%x event tag "
6975                                 "0x%x\n", event_type, acqe_fip->event_tag);
6976                 break;
6977         }
6978 }
6979
6980 /**
6981  * lpfc_sli4_async_dcbx_evt - Process the asynchronous dcbx event
6982  * @phba: pointer to lpfc hba data structure.
6983  * @acqe_dcbx: pointer to the async dcbx completion queue entry.
6984  *
6985  * This routine is to handle the SLI4 asynchronous dcbx event.
6986  **/
6987 static void
6988 lpfc_sli4_async_dcbx_evt(struct lpfc_hba *phba,
6989                          struct lpfc_acqe_dcbx *acqe_dcbx)
6990 {
6991         phba->fc_eventTag = acqe_dcbx->event_tag;
6992         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6993                         "0290 The SLI4 DCBX asynchronous event is not "
6994                         "handled yet\n");
6995 }
6996
6997 /**
6998  * lpfc_sli4_async_grp5_evt - Process the asynchronous group5 event
6999  * @phba: pointer to lpfc hba data structure.
7000  * @acqe_grp5: pointer to the async grp5 completion queue entry.
7001  *
7002  * This routine is to handle the SLI4 asynchronous grp5 event. A grp5 event
7003  * is an asynchronous notified of a logical link speed change.  The Port
7004  * reports the logical link speed in units of 10Mbps.
7005  **/
7006 static void
7007 lpfc_sli4_async_grp5_evt(struct lpfc_hba *phba,
7008                          struct lpfc_acqe_grp5 *acqe_grp5)
7009 {
7010         uint16_t prev_ll_spd;
7011
7012         phba->fc_eventTag = acqe_grp5->event_tag;
7013         phba->fcoe_eventtag = acqe_grp5->event_tag;
7014         prev_ll_spd = phba->sli4_hba.link_state.logical_speed;
7015         phba->sli4_hba.link_state.logical_speed =
7016                 (bf_get(lpfc_acqe_grp5_llink_spd, acqe_grp5)) * 10;
7017         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
7018                         "2789 GRP5 Async Event: Updating logical link speed "
7019                         "from %dMbps to %dMbps\n", prev_ll_spd,
7020                         phba->sli4_hba.link_state.logical_speed);
7021 }
7022
7023 /**
7024  * lpfc_sli4_async_cmstat_evt - Process the asynchronous cmstat event
7025  * @phba: pointer to lpfc hba data structure.
7026  *
7027  * This routine is to handle the SLI4 asynchronous cmstat event. A cmstat event
7028  * is an asynchronous notification of a request to reset CM stats.
7029  **/
7030 static void
7031 lpfc_sli4_async_cmstat_evt(struct lpfc_hba *phba)
7032 {
7033         if (!phba->cgn_i)
7034                 return;
7035         lpfc_init_congestion_stat(phba);
7036 }
7037
7038 /**
7039  * lpfc_cgn_params_val - Validate FW congestion parameters.
7040  * @phba: pointer to lpfc hba data structure.
7041  * @p_cfg_param: pointer to FW provided congestion parameters.
7042  *
7043  * This routine validates the congestion parameters passed
7044  * by the FW to the driver via an ACQE event.
7045  **/
7046 static void
7047 lpfc_cgn_params_val(struct lpfc_hba *phba, struct lpfc_cgn_param *p_cfg_param)
7048 {
7049         spin_lock_irq(&phba->hbalock);
7050
7051         if (!lpfc_rangecheck(p_cfg_param->cgn_param_mode, LPFC_CFG_OFF,
7052                              LPFC_CFG_MONITOR)) {
7053                 lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
7054                                 "6225 CMF mode param out of range: %d\n",
7055                                  p_cfg_param->cgn_param_mode);
7056                 p_cfg_param->cgn_param_mode = LPFC_CFG_OFF;
7057         }
7058
7059         spin_unlock_irq(&phba->hbalock);
7060 }
7061
7062 static const char * const lpfc_cmf_mode_to_str[] = {
7063         "OFF",
7064         "MANAGED",
7065         "MONITOR",
7066 };
7067
7068 /**
7069  * lpfc_cgn_params_parse - Process a FW cong parm change event
7070  * @phba: pointer to lpfc hba data structure.
7071  * @p_cgn_param: pointer to a data buffer with the FW cong params.
7072  * @len: the size of pdata in bytes.
7073  *
7074  * This routine validates the congestion management buffer signature
7075  * from the FW, validates the contents and makes corrections for
7076  * valid, in-range values.  If the signature magic is correct and
7077  * after parameter validation, the contents are copied to the driver's
7078  * @phba structure. If the magic is incorrect, an error message is
7079  * logged.
7080  **/
7081 static void
7082 lpfc_cgn_params_parse(struct lpfc_hba *phba,
7083                       struct lpfc_cgn_param *p_cgn_param, uint32_t len)
7084 {
7085         struct lpfc_cgn_info *cp;
7086         uint32_t crc, oldmode;
7087         char acr_string[4] = {0};
7088
7089         /* Make sure the FW has encoded the correct magic number to
7090          * validate the congestion parameter in FW memory.
7091          */
7092         if (p_cgn_param->cgn_param_magic == LPFC_CFG_PARAM_MAGIC_NUM) {
7093                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7094                                 "4668 FW cgn parm buffer data: "
7095                                 "magic 0x%x version %d mode %d "
7096                                 "level0 %d level1 %d "
7097                                 "level2 %d byte13 %d "
7098                                 "byte14 %d byte15 %d "
7099                                 "byte11 %d byte12 %d activeMode %d\n",
7100                                 p_cgn_param->cgn_param_magic,
7101                                 p_cgn_param->cgn_param_version,
7102                                 p_cgn_param->cgn_param_mode,
7103                                 p_cgn_param->cgn_param_level0,
7104                                 p_cgn_param->cgn_param_level1,
7105                                 p_cgn_param->cgn_param_level2,
7106                                 p_cgn_param->byte13,
7107                                 p_cgn_param->byte14,
7108                                 p_cgn_param->byte15,
7109                                 p_cgn_param->byte11,
7110                                 p_cgn_param->byte12,
7111                                 phba->cmf_active_mode);
7112
7113                 oldmode = phba->cmf_active_mode;
7114
7115                 /* Any parameters out of range are corrected to defaults
7116                  * by this routine.  No need to fail.
7117                  */
7118                 lpfc_cgn_params_val(phba, p_cgn_param);
7119
7120                 /* Parameters are verified, move them into driver storage */
7121                 spin_lock_irq(&phba->hbalock);
7122                 memcpy(&phba->cgn_p, p_cgn_param,
7123                        sizeof(struct lpfc_cgn_param));
7124
7125                 /* Update parameters in congestion info buffer now */
7126                 if (phba->cgn_i) {
7127                         cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
7128                         cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
7129                         cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
7130                         cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
7131                         cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
7132                         crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ,
7133                                                   LPFC_CGN_CRC32_SEED);
7134                         cp->cgn_info_crc = cpu_to_le32(crc);
7135                 }
7136                 spin_unlock_irq(&phba->hbalock);
7137
7138                 phba->cmf_active_mode = phba->cgn_p.cgn_param_mode;
7139
7140                 switch (oldmode) {
7141                 case LPFC_CFG_OFF:
7142                         if (phba->cgn_p.cgn_param_mode != LPFC_CFG_OFF) {
7143                                 /* Turning CMF on */
7144                                 lpfc_cmf_start(phba);
7145
7146                                 if (phba->link_state >= LPFC_LINK_UP) {
7147                                         phba->cgn_reg_fpin =
7148                                                 phba->cgn_init_reg_fpin;
7149                                         phba->cgn_reg_signal =
7150                                                 phba->cgn_init_reg_signal;
7151                                         lpfc_issue_els_edc(phba->pport, 0);
7152                                 }
7153                         }
7154                         break;
7155                 case LPFC_CFG_MANAGED:
7156                         switch (phba->cgn_p.cgn_param_mode) {
7157                         case LPFC_CFG_OFF:
7158                                 /* Turning CMF off */
7159                                 lpfc_cmf_stop(phba);
7160                                 if (phba->link_state >= LPFC_LINK_UP)
7161                                         lpfc_issue_els_edc(phba->pport, 0);
7162                                 break;
7163                         case LPFC_CFG_MONITOR:
7164                                 phba->cmf_max_bytes_per_interval =
7165                                         phba->cmf_link_byte_count;
7166
7167                                 /* Resume blocked IO - unblock on workqueue */
7168                                 queue_work(phba->wq,
7169                                            &phba->unblock_request_work);
7170                                 break;
7171                         }
7172                         break;
7173                 case LPFC_CFG_MONITOR:
7174                         switch (phba->cgn_p.cgn_param_mode) {
7175                         case LPFC_CFG_OFF:
7176                                 /* Turning CMF off */
7177                                 lpfc_cmf_stop(phba);
7178                                 if (phba->link_state >= LPFC_LINK_UP)
7179                                         lpfc_issue_els_edc(phba->pport, 0);
7180                                 break;
7181                         case LPFC_CFG_MANAGED:
7182                                 lpfc_cmf_signal_init(phba);
7183                                 break;
7184                         }
7185                         break;
7186                 }
7187                 if (oldmode != LPFC_CFG_OFF ||
7188                     oldmode != phba->cgn_p.cgn_param_mode) {
7189                         if (phba->cgn_p.cgn_param_mode == LPFC_CFG_MANAGED)
7190                                 scnprintf(acr_string, sizeof(acr_string), "%u",
7191                                           phba->cgn_p.cgn_param_level0);
7192                         else
7193                                 scnprintf(acr_string, sizeof(acr_string), "NA");
7194
7195                         dev_info(&phba->pcidev->dev, "%d: "
7196                                  "4663 CMF: Mode %s acr %s\n",
7197                                  phba->brd_no,
7198                                  lpfc_cmf_mode_to_str
7199                                  [phba->cgn_p.cgn_param_mode],
7200                                  acr_string);
7201                 }
7202         } else {
7203                 lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7204                                 "4669 FW cgn parm buf wrong magic 0x%x "
7205                                 "version %d\n", p_cgn_param->cgn_param_magic,
7206                                 p_cgn_param->cgn_param_version);
7207         }
7208 }
7209
7210 /**
7211  * lpfc_sli4_cgn_params_read - Read and Validate FW congestion parameters.
7212  * @phba: pointer to lpfc hba data structure.
7213  *
7214  * This routine issues a read_object mailbox command to
7215  * get the congestion management parameters from the FW
7216  * parses it and updates the driver maintained values.
7217  *
7218  * Returns
7219  *  0     if the object was empty
7220  *  -Eval if an error was encountered
7221  *  Count if bytes were read from object
7222  **/
7223 int
7224 lpfc_sli4_cgn_params_read(struct lpfc_hba *phba)
7225 {
7226         int ret = 0;
7227         struct lpfc_cgn_param *p_cgn_param = NULL;
7228         u32 *pdata = NULL;
7229         u32 len = 0;
7230
7231         /* Find out if the FW has a new set of congestion parameters. */
7232         len = sizeof(struct lpfc_cgn_param);
7233         pdata = kzalloc(len, GFP_KERNEL);
7234         if (!pdata)
7235                 return -ENOMEM;
7236         ret = lpfc_read_object(phba, (char *)LPFC_PORT_CFG_NAME,
7237                                pdata, len);
7238
7239         /* 0 means no data.  A negative means error.  A positive means
7240          * bytes were copied.
7241          */
7242         if (!ret) {
7243                 lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7244                                 "4670 CGN RD OBJ returns no data\n");
7245                 goto rd_obj_err;
7246         } else if (ret < 0) {
7247                 /* Some error.  Just exit and return it to the caller.*/
7248                 goto rd_obj_err;
7249         }
7250
7251         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT | LOG_INIT,
7252                         "6234 READ CGN PARAMS Successful %d\n", len);
7253
7254         /* Parse data pointer over len and update the phba congestion
7255          * parameters with values passed back.  The receive rate values
7256          * may have been altered in FW, but take no action here.
7257          */
7258         p_cgn_param = (struct lpfc_cgn_param *)pdata;
7259         lpfc_cgn_params_parse(phba, p_cgn_param, len);
7260
7261  rd_obj_err:
7262         kfree(pdata);
7263         return ret;
7264 }
7265
7266 /**
7267  * lpfc_sli4_cgn_parm_chg_evt - Process a FW congestion param change event
7268  * @phba: pointer to lpfc hba data structure.
7269  *
7270  * The FW generated Async ACQE SLI event calls this routine when
7271  * the event type is an SLI Internal Port Event and the Event Code
7272  * indicates a change to the FW maintained congestion parameters.
7273  *
7274  * This routine executes a Read_Object mailbox call to obtain the
7275  * current congestion parameters maintained in FW and corrects
7276  * the driver's active congestion parameters.
7277  *
7278  * The acqe event is not passed because there is no further data
7279  * required.
7280  *
7281  * Returns nonzero error if event processing encountered an error.
7282  * Zero otherwise for success.
7283  **/
7284 static int
7285 lpfc_sli4_cgn_parm_chg_evt(struct lpfc_hba *phba)
7286 {
7287         int ret = 0;
7288
7289         if (!phba->sli4_hba.pc_sli4_params.cmf) {
7290                 lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7291                                 "4664 Cgn Evt when E2E off. Drop event\n");
7292                 return -EACCES;
7293         }
7294
7295         /* If the event is claiming an empty object, it's ok.  A write
7296          * could have cleared it.  Only error is a negative return
7297          * status.
7298          */
7299         ret = lpfc_sli4_cgn_params_read(phba);
7300         if (ret < 0) {
7301                 lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7302                                 "4667 Error reading Cgn Params (%d)\n",
7303                                 ret);
7304         } else if (!ret) {
7305                 lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
7306                                 "4673 CGN Event empty object.\n");
7307         }
7308         return ret;
7309 }
7310
7311 /**
7312  * lpfc_sli4_async_event_proc - Process all the pending asynchronous event
7313  * @phba: pointer to lpfc hba data structure.
7314  *
7315  * This routine is invoked by the worker thread to process all the pending
7316  * SLI4 asynchronous events.
7317  **/
7318 void lpfc_sli4_async_event_proc(struct lpfc_hba *phba)
7319 {
7320         struct lpfc_cq_event *cq_event;
7321         unsigned long iflags;
7322
7323         /* First, declare the async event has been handled */
7324         spin_lock_irqsave(&phba->hbalock, iflags);
7325         phba->hba_flag &= ~ASYNC_EVENT;
7326         spin_unlock_irqrestore(&phba->hbalock, iflags);
7327
7328         /* Now, handle all the async events */
7329         spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7330         while (!list_empty(&phba->sli4_hba.sp_asynce_work_queue)) {
7331                 list_remove_head(&phba->sli4_hba.sp_asynce_work_queue,
7332                                  cq_event, struct lpfc_cq_event, list);
7333                 spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock,
7334                                        iflags);
7335
7336                 /* Process the asynchronous event */
7337                 switch (bf_get(lpfc_trailer_code, &cq_event->cqe.mcqe_cmpl)) {
7338                 case LPFC_TRAILER_CODE_LINK:
7339                         lpfc_sli4_async_link_evt(phba,
7340                                                  &cq_event->cqe.acqe_link);
7341                         break;
7342                 case LPFC_TRAILER_CODE_FCOE:
7343                         lpfc_sli4_async_fip_evt(phba, &cq_event->cqe.acqe_fip);
7344                         break;
7345                 case LPFC_TRAILER_CODE_DCBX:
7346                         lpfc_sli4_async_dcbx_evt(phba,
7347                                                  &cq_event->cqe.acqe_dcbx);
7348                         break;
7349                 case LPFC_TRAILER_CODE_GRP5:
7350                         lpfc_sli4_async_grp5_evt(phba,
7351                                                  &cq_event->cqe.acqe_grp5);
7352                         break;
7353                 case LPFC_TRAILER_CODE_FC:
7354                         lpfc_sli4_async_fc_evt(phba, &cq_event->cqe.acqe_fc);
7355                         break;
7356                 case LPFC_TRAILER_CODE_SLI:
7357                         lpfc_sli4_async_sli_evt(phba, &cq_event->cqe.acqe_sli);
7358                         break;
7359                 default:
7360                         lpfc_printf_log(phba, KERN_ERR,
7361                                         LOG_TRACE_EVENT,
7362                                         "1804 Invalid asynchronous event code: "
7363                                         "x%x\n", bf_get(lpfc_trailer_code,
7364                                         &cq_event->cqe.mcqe_cmpl));
7365                         break;
7366                 }
7367
7368                 /* Free the completion event processed to the free pool */
7369                 lpfc_sli4_cq_event_release(phba, cq_event);
7370                 spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
7371         }
7372         spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
7373 }
7374
7375 /**
7376  * lpfc_sli4_fcf_redisc_event_proc - Process fcf table rediscovery event
7377  * @phba: pointer to lpfc hba data structure.
7378  *
7379  * This routine is invoked by the worker thread to process FCF table
7380  * rediscovery pending completion event.
7381  **/
7382 void lpfc_sli4_fcf_redisc_event_proc(struct lpfc_hba *phba)
7383 {
7384         int rc;
7385
7386         spin_lock_irq(&phba->hbalock);
7387         /* Clear FCF rediscovery timeout event */
7388         phba->fcf.fcf_flag &= ~FCF_REDISC_EVT;
7389         /* Clear driver fast failover FCF record flag */
7390         phba->fcf.failover_rec.flag = 0;
7391         /* Set state for FCF fast failover */
7392         phba->fcf.fcf_flag |= FCF_REDISC_FOV;
7393         spin_unlock_irq(&phba->hbalock);
7394
7395         /* Scan FCF table from the first entry to re-discover SAN */
7396         lpfc_printf_log(phba, KERN_INFO, LOG_FIP | LOG_DISCOVERY,
7397                         "2777 Start post-quiescent FCF table scan\n");
7398         rc = lpfc_sli4_fcf_scan_read_fcf_rec(phba, LPFC_FCOE_FCF_GET_FIRST);
7399         if (rc)
7400                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7401                                 "2747 Issue FCF scan read FCF mailbox "
7402                                 "command failed 0x%x\n", rc);
7403 }
7404
7405 /**
7406  * lpfc_api_table_setup - Set up per hba pci-device group func api jump table
7407  * @phba: pointer to lpfc hba data structure.
7408  * @dev_grp: The HBA PCI-Device group number.
7409  *
7410  * This routine is invoked to set up the per HBA PCI-Device group function
7411  * API jump table entries.
7412  *
7413  * Return: 0 if success, otherwise -ENODEV
7414  **/
7415 int
7416 lpfc_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7417 {
7418         int rc;
7419
7420         /* Set up lpfc PCI-device group */
7421         phba->pci_dev_grp = dev_grp;
7422
7423         /* The LPFC_PCI_DEV_OC uses SLI4 */
7424         if (dev_grp == LPFC_PCI_DEV_OC)
7425                 phba->sli_rev = LPFC_SLI_REV4;
7426
7427         /* Set up device INIT API function jump table */
7428         rc = lpfc_init_api_table_setup(phba, dev_grp);
7429         if (rc)
7430                 return -ENODEV;
7431         /* Set up SCSI API function jump table */
7432         rc = lpfc_scsi_api_table_setup(phba, dev_grp);
7433         if (rc)
7434                 return -ENODEV;
7435         /* Set up SLI API function jump table */
7436         rc = lpfc_sli_api_table_setup(phba, dev_grp);
7437         if (rc)
7438                 return -ENODEV;
7439         /* Set up MBOX API function jump table */
7440         rc = lpfc_mbox_api_table_setup(phba, dev_grp);
7441         if (rc)
7442                 return -ENODEV;
7443
7444         return 0;
7445 }
7446
7447 /**
7448  * lpfc_log_intr_mode - Log the active interrupt mode
7449  * @phba: pointer to lpfc hba data structure.
7450  * @intr_mode: active interrupt mode adopted.
7451  *
7452  * This routine it invoked to log the currently used active interrupt mode
7453  * to the device.
7454  **/
7455 static void lpfc_log_intr_mode(struct lpfc_hba *phba, uint32_t intr_mode)
7456 {
7457         switch (intr_mode) {
7458         case 0:
7459                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7460                                 "0470 Enable INTx interrupt mode.\n");
7461                 break;
7462         case 1:
7463                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7464                                 "0481 Enabled MSI interrupt mode.\n");
7465                 break;
7466         case 2:
7467                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7468                                 "0480 Enabled MSI-X interrupt mode.\n");
7469                 break;
7470         default:
7471                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7472                                 "0482 Illegal interrupt mode.\n");
7473                 break;
7474         }
7475         return;
7476 }
7477
7478 /**
7479  * lpfc_enable_pci_dev - Enable a generic PCI device.
7480  * @phba: pointer to lpfc hba data structure.
7481  *
7482  * This routine is invoked to enable the PCI device that is common to all
7483  * PCI devices.
7484  *
7485  * Return codes
7486  *      0 - successful
7487  *      other values - error
7488  **/
7489 static int
7490 lpfc_enable_pci_dev(struct lpfc_hba *phba)
7491 {
7492         struct pci_dev *pdev;
7493
7494         /* Obtain PCI device reference */
7495         if (!phba->pcidev)
7496                 goto out_error;
7497         else
7498                 pdev = phba->pcidev;
7499         /* Enable PCI device */
7500         if (pci_enable_device_mem(pdev))
7501                 goto out_error;
7502         /* Request PCI resource for the device */
7503         if (pci_request_mem_regions(pdev, LPFC_DRIVER_NAME))
7504                 goto out_disable_device;
7505         /* Set up device as PCI master and save state for EEH */
7506         pci_set_master(pdev);
7507         pci_try_set_mwi(pdev);
7508         pci_save_state(pdev);
7509
7510         /* PCIe EEH recovery on powerpc platforms needs fundamental reset */
7511         if (pci_is_pcie(pdev))
7512                 pdev->needs_freset = 1;
7513
7514         return 0;
7515
7516 out_disable_device:
7517         pci_disable_device(pdev);
7518 out_error:
7519         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7520                         "1401 Failed to enable pci device\n");
7521         return -ENODEV;
7522 }
7523
7524 /**
7525  * lpfc_disable_pci_dev - Disable a generic PCI device.
7526  * @phba: pointer to lpfc hba data structure.
7527  *
7528  * This routine is invoked to disable the PCI device that is common to all
7529  * PCI devices.
7530  **/
7531 static void
7532 lpfc_disable_pci_dev(struct lpfc_hba *phba)
7533 {
7534         struct pci_dev *pdev;
7535
7536         /* Obtain PCI device reference */
7537         if (!phba->pcidev)
7538                 return;
7539         else
7540                 pdev = phba->pcidev;
7541         /* Release PCI resource and disable PCI device */
7542         pci_release_mem_regions(pdev);
7543         pci_disable_device(pdev);
7544
7545         return;
7546 }
7547
7548 /**
7549  * lpfc_reset_hba - Reset a hba
7550  * @phba: pointer to lpfc hba data structure.
7551  *
7552  * This routine is invoked to reset a hba device. It brings the HBA
7553  * offline, performs a board restart, and then brings the board back
7554  * online. The lpfc_offline calls lpfc_sli_hba_down which will clean up
7555  * on outstanding mailbox commands.
7556  **/
7557 void
7558 lpfc_reset_hba(struct lpfc_hba *phba)
7559 {
7560         int rc = 0;
7561
7562         /* If resets are disabled then set error state and return. */
7563         if (!phba->cfg_enable_hba_reset) {
7564                 phba->link_state = LPFC_HBA_ERROR;
7565                 return;
7566         }
7567
7568         /* If not LPFC_SLI_ACTIVE, force all IO to be flushed */
7569         if (phba->sli.sli_flag & LPFC_SLI_ACTIVE) {
7570                 lpfc_offline_prep(phba, LPFC_MBX_WAIT);
7571         } else {
7572                 if (test_bit(MBX_TMO_ERR, &phba->bit_flags)) {
7573                         /* Perform a PCI function reset to start from clean */
7574                         rc = lpfc_pci_function_reset(phba);
7575                         lpfc_els_flush_all_cmd(phba);
7576                 }
7577                 lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
7578                 lpfc_sli_flush_io_rings(phba);
7579         }
7580         lpfc_offline(phba);
7581         clear_bit(MBX_TMO_ERR, &phba->bit_flags);
7582         if (unlikely(rc)) {
7583                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7584                                 "8888 PCI function reset failed rc %x\n",
7585                                 rc);
7586         } else {
7587                 lpfc_sli_brdrestart(phba);
7588                 lpfc_online(phba);
7589                 lpfc_unblock_mgmt_io(phba);
7590         }
7591 }
7592
7593 /**
7594  * lpfc_sli_sriov_nr_virtfn_get - Get the number of sr-iov virtual functions
7595  * @phba: pointer to lpfc hba data structure.
7596  *
7597  * This function enables the PCI SR-IOV virtual functions to a physical
7598  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7599  * enable the number of virtual functions to the physical function. As
7600  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7601  * API call does not considered as an error condition for most of the device.
7602  **/
7603 uint16_t
7604 lpfc_sli_sriov_nr_virtfn_get(struct lpfc_hba *phba)
7605 {
7606         struct pci_dev *pdev = phba->pcidev;
7607         uint16_t nr_virtfn;
7608         int pos;
7609
7610         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
7611         if (pos == 0)
7612                 return 0;
7613
7614         pci_read_config_word(pdev, pos + PCI_SRIOV_TOTAL_VF, &nr_virtfn);
7615         return nr_virtfn;
7616 }
7617
7618 /**
7619  * lpfc_sli_probe_sriov_nr_virtfn - Enable a number of sr-iov virtual functions
7620  * @phba: pointer to lpfc hba data structure.
7621  * @nr_vfn: number of virtual functions to be enabled.
7622  *
7623  * This function enables the PCI SR-IOV virtual functions to a physical
7624  * function. It invokes the PCI SR-IOV api with the @nr_vfn provided to
7625  * enable the number of virtual functions to the physical function. As
7626  * not all devices support SR-IOV, the return code from the pci_enable_sriov()
7627  * API call does not considered as an error condition for most of the device.
7628  **/
7629 int
7630 lpfc_sli_probe_sriov_nr_virtfn(struct lpfc_hba *phba, int nr_vfn)
7631 {
7632         struct pci_dev *pdev = phba->pcidev;
7633         uint16_t max_nr_vfn;
7634         int rc;
7635
7636         max_nr_vfn = lpfc_sli_sriov_nr_virtfn_get(phba);
7637         if (nr_vfn > max_nr_vfn) {
7638                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7639                                 "3057 Requested vfs (%d) greater than "
7640                                 "supported vfs (%d)", nr_vfn, max_nr_vfn);
7641                 return -EINVAL;
7642         }
7643
7644         rc = pci_enable_sriov(pdev, nr_vfn);
7645         if (rc) {
7646                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7647                                 "2806 Failed to enable sriov on this device "
7648                                 "with vfn number nr_vf:%d, rc:%d\n",
7649                                 nr_vfn, rc);
7650         } else
7651                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7652                                 "2807 Successful enable sriov on this device "
7653                                 "with vfn number nr_vf:%d\n", nr_vfn);
7654         return rc;
7655 }
7656
7657 static void
7658 lpfc_unblock_requests_work(struct work_struct *work)
7659 {
7660         struct lpfc_hba *phba = container_of(work, struct lpfc_hba,
7661                                              unblock_request_work);
7662
7663         lpfc_unblock_requests(phba);
7664 }
7665
7666 /**
7667  * lpfc_setup_driver_resource_phase1 - Phase1 etup driver internal resources.
7668  * @phba: pointer to lpfc hba data structure.
7669  *
7670  * This routine is invoked to set up the driver internal resources before the
7671  * device specific resource setup to support the HBA device it attached to.
7672  *
7673  * Return codes
7674  *      0 - successful
7675  *      other values - error
7676  **/
7677 static int
7678 lpfc_setup_driver_resource_phase1(struct lpfc_hba *phba)
7679 {
7680         struct lpfc_sli *psli = &phba->sli;
7681
7682         /*
7683          * Driver resources common to all SLI revisions
7684          */
7685         atomic_set(&phba->fast_event_count, 0);
7686         atomic_set(&phba->dbg_log_idx, 0);
7687         atomic_set(&phba->dbg_log_cnt, 0);
7688         atomic_set(&phba->dbg_log_dmping, 0);
7689         spin_lock_init(&phba->hbalock);
7690
7691         /* Initialize port_list spinlock */
7692         spin_lock_init(&phba->port_list_lock);
7693         INIT_LIST_HEAD(&phba->port_list);
7694
7695         INIT_LIST_HEAD(&phba->work_list);
7696
7697         /* Initialize the wait queue head for the kernel thread */
7698         init_waitqueue_head(&phba->work_waitq);
7699
7700         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7701                         "1403 Protocols supported %s %s %s\n",
7702                         ((phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) ?
7703                                 "SCSI" : " "),
7704                         ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) ?
7705                                 "NVME" : " "),
7706                         (phba->nvmet_support ? "NVMET" : " "));
7707
7708         /* Initialize the IO buffer list used by driver for SLI3 SCSI */
7709         spin_lock_init(&phba->scsi_buf_list_get_lock);
7710         INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_get);
7711         spin_lock_init(&phba->scsi_buf_list_put_lock);
7712         INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_put);
7713
7714         /* Initialize the fabric iocb list */
7715         INIT_LIST_HEAD(&phba->fabric_iocb_list);
7716
7717         /* Initialize list to save ELS buffers */
7718         INIT_LIST_HEAD(&phba->elsbuf);
7719
7720         /* Initialize FCF connection rec list */
7721         INIT_LIST_HEAD(&phba->fcf_conn_rec_list);
7722
7723         /* Initialize OAS configuration list */
7724         spin_lock_init(&phba->devicelock);
7725         INIT_LIST_HEAD(&phba->luns);
7726
7727         /* MBOX heartbeat timer */
7728         timer_setup(&psli->mbox_tmo, lpfc_mbox_timeout, 0);
7729         /* Fabric block timer */
7730         timer_setup(&phba->fabric_block_timer, lpfc_fabric_block_timeout, 0);
7731         /* EA polling mode timer */
7732         timer_setup(&phba->eratt_poll, lpfc_poll_eratt, 0);
7733         /* Heartbeat timer */
7734         timer_setup(&phba->hb_tmofunc, lpfc_hb_timeout, 0);
7735
7736         INIT_DELAYED_WORK(&phba->eq_delay_work, lpfc_hb_eq_delay_work);
7737
7738         INIT_DELAYED_WORK(&phba->idle_stat_delay_work,
7739                           lpfc_idle_stat_delay_work);
7740         INIT_WORK(&phba->unblock_request_work, lpfc_unblock_requests_work);
7741         return 0;
7742 }
7743
7744 /**
7745  * lpfc_sli_driver_resource_setup - Setup driver internal resources for SLI3 dev
7746  * @phba: pointer to lpfc hba data structure.
7747  *
7748  * This routine is invoked to set up the driver internal resources specific to
7749  * support the SLI-3 HBA device it attached to.
7750  *
7751  * Return codes
7752  * 0 - successful
7753  * other values - error
7754  **/
7755 static int
7756 lpfc_sli_driver_resource_setup(struct lpfc_hba *phba)
7757 {
7758         int rc, entry_sz;
7759
7760         /*
7761          * Initialize timers used by driver
7762          */
7763
7764         /* FCP polling mode timer */
7765         timer_setup(&phba->fcp_poll_timer, lpfc_poll_timeout, 0);
7766
7767         /* Host attention work mask setup */
7768         phba->work_ha_mask = (HA_ERATT | HA_MBATT | HA_LATT);
7769         phba->work_ha_mask |= (HA_RXMASK << (LPFC_ELS_RING * 4));
7770
7771         /* Get all the module params for configuring this host */
7772         lpfc_get_cfgparam(phba);
7773         /* Set up phase-1 common device driver resources */
7774
7775         rc = lpfc_setup_driver_resource_phase1(phba);
7776         if (rc)
7777                 return -ENODEV;
7778
7779         if (!phba->sli.sli3_ring)
7780                 phba->sli.sli3_ring = kcalloc(LPFC_SLI3_MAX_RING,
7781                                               sizeof(struct lpfc_sli_ring),
7782                                               GFP_KERNEL);
7783         if (!phba->sli.sli3_ring)
7784                 return -ENOMEM;
7785
7786         /*
7787          * Since lpfc_sg_seg_cnt is module parameter, the sg_dma_buf_size
7788          * used to create the sg_dma_buf_pool must be dynamically calculated.
7789          */
7790
7791         if (phba->sli_rev == LPFC_SLI_REV4)
7792                 entry_sz = sizeof(struct sli4_sge);
7793         else
7794                 entry_sz = sizeof(struct ulp_bde64);
7795
7796         /* There are going to be 2 reserved BDEs: 1 FCP cmnd + 1 FCP rsp */
7797         if (phba->cfg_enable_bg) {
7798                 /*
7799                  * The scsi_buf for a T10-DIF I/O will hold the FCP cmnd,
7800                  * the FCP rsp, and a BDE for each. Sice we have no control
7801                  * over how many protection data segments the SCSI Layer
7802                  * will hand us (ie: there could be one for every block
7803                  * in the IO), we just allocate enough BDEs to accomidate
7804                  * our max amount and we need to limit lpfc_sg_seg_cnt to
7805                  * minimize the risk of running out.
7806                  */
7807                 phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7808                         sizeof(struct fcp_rsp) +
7809                         (LPFC_MAX_SG_SEG_CNT * entry_sz);
7810
7811                 if (phba->cfg_sg_seg_cnt > LPFC_MAX_SG_SEG_CNT_DIF)
7812                         phba->cfg_sg_seg_cnt = LPFC_MAX_SG_SEG_CNT_DIF;
7813
7814                 /* Total BDEs in BPL for scsi_sg_list and scsi_sg_prot_list */
7815                 phba->cfg_total_seg_cnt = LPFC_MAX_SG_SEG_CNT;
7816         } else {
7817                 /*
7818                  * The scsi_buf for a regular I/O will hold the FCP cmnd,
7819                  * the FCP rsp, a BDE for each, and a BDE for up to
7820                  * cfg_sg_seg_cnt data segments.
7821                  */
7822                 phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
7823                         sizeof(struct fcp_rsp) +
7824                         ((phba->cfg_sg_seg_cnt + 2) * entry_sz);
7825
7826                 /* Total BDEs in BPL for scsi_sg_list */
7827                 phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + 2;
7828         }
7829
7830         lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
7831                         "9088 INIT sg_tablesize:%d dmabuf_size:%d total_bde:%d\n",
7832                         phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
7833                         phba->cfg_total_seg_cnt);
7834
7835         phba->max_vpi = LPFC_MAX_VPI;
7836         /* This will be set to correct value after config_port mbox */
7837         phba->max_vports = 0;
7838
7839         /*
7840          * Initialize the SLI Layer to run with lpfc HBAs.
7841          */
7842         lpfc_sli_setup(phba);
7843         lpfc_sli_queue_init(phba);
7844
7845         /* Allocate device driver memory */
7846         if (lpfc_mem_alloc(phba, BPL_ALIGN_SZ))
7847                 return -ENOMEM;
7848
7849         phba->lpfc_sg_dma_buf_pool =
7850                 dma_pool_create("lpfc_sg_dma_buf_pool",
7851                                 &phba->pcidev->dev, phba->cfg_sg_dma_buf_size,
7852                                 BPL_ALIGN_SZ, 0);
7853
7854         if (!phba->lpfc_sg_dma_buf_pool)
7855                 goto fail_free_mem;
7856
7857         phba->lpfc_cmd_rsp_buf_pool =
7858                         dma_pool_create("lpfc_cmd_rsp_buf_pool",
7859                                         &phba->pcidev->dev,
7860                                         sizeof(struct fcp_cmnd) +
7861                                         sizeof(struct fcp_rsp),
7862                                         BPL_ALIGN_SZ, 0);
7863
7864         if (!phba->lpfc_cmd_rsp_buf_pool)
7865                 goto fail_free_dma_buf_pool;
7866
7867         /*
7868          * Enable sr-iov virtual functions if supported and configured
7869          * through the module parameter.
7870          */
7871         if (phba->cfg_sriov_nr_virtfn > 0) {
7872                 rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
7873                                                  phba->cfg_sriov_nr_virtfn);
7874                 if (rc) {
7875                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7876                                         "2808 Requested number of SR-IOV "
7877                                         "virtual functions (%d) is not "
7878                                         "supported\n",
7879                                         phba->cfg_sriov_nr_virtfn);
7880                         phba->cfg_sriov_nr_virtfn = 0;
7881                 }
7882         }
7883
7884         return 0;
7885
7886 fail_free_dma_buf_pool:
7887         dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
7888         phba->lpfc_sg_dma_buf_pool = NULL;
7889 fail_free_mem:
7890         lpfc_mem_free(phba);
7891         return -ENOMEM;
7892 }
7893
7894 /**
7895  * lpfc_sli_driver_resource_unset - Unset drvr internal resources for SLI3 dev
7896  * @phba: pointer to lpfc hba data structure.
7897  *
7898  * This routine is invoked to unset the driver internal resources set up
7899  * specific for supporting the SLI-3 HBA device it attached to.
7900  **/
7901 static void
7902 lpfc_sli_driver_resource_unset(struct lpfc_hba *phba)
7903 {
7904         /* Free device driver memory allocated */
7905         lpfc_mem_free_all(phba);
7906
7907         return;
7908 }
7909
7910 /**
7911  * lpfc_sli4_driver_resource_setup - Setup drvr internal resources for SLI4 dev
7912  * @phba: pointer to lpfc hba data structure.
7913  *
7914  * This routine is invoked to set up the driver internal resources specific to
7915  * support the SLI-4 HBA device it attached to.
7916  *
7917  * Return codes
7918  *      0 - successful
7919  *      other values - error
7920  **/
7921 static int
7922 lpfc_sli4_driver_resource_setup(struct lpfc_hba *phba)
7923 {
7924         LPFC_MBOXQ_t *mboxq;
7925         MAILBOX_t *mb;
7926         int rc, i, max_buf_size;
7927         int longs;
7928         int extra;
7929         uint64_t wwn;
7930         u32 if_type;
7931         u32 if_fam;
7932
7933         phba->sli4_hba.num_present_cpu = lpfc_present_cpu;
7934         phba->sli4_hba.num_possible_cpu = cpumask_last(cpu_possible_mask) + 1;
7935         phba->sli4_hba.curr_disp_cpu = 0;
7936
7937         /* Get all the module params for configuring this host */
7938         lpfc_get_cfgparam(phba);
7939
7940         /* Set up phase-1 common device driver resources */
7941         rc = lpfc_setup_driver_resource_phase1(phba);
7942         if (rc)
7943                 return -ENODEV;
7944
7945         /* Before proceed, wait for POST done and device ready */
7946         rc = lpfc_sli4_post_status_check(phba);
7947         if (rc)
7948                 return -ENODEV;
7949
7950         /* Allocate all driver workqueues here */
7951
7952         /* The lpfc_wq workqueue for deferred irq use */
7953         phba->wq = alloc_workqueue("lpfc_wq", WQ_MEM_RECLAIM, 0);
7954         if (!phba->wq)
7955                 return -ENOMEM;
7956
7957         /*
7958          * Initialize timers used by driver
7959          */
7960
7961         timer_setup(&phba->rrq_tmr, lpfc_rrq_timeout, 0);
7962
7963         /* FCF rediscover timer */
7964         timer_setup(&phba->fcf.redisc_wait, lpfc_sli4_fcf_redisc_wait_tmo, 0);
7965
7966         /* CMF congestion timer */
7967         hrtimer_init(&phba->cmf_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7968         phba->cmf_timer.function = lpfc_cmf_timer;
7969         /* CMF 1 minute stats collection timer */
7970         hrtimer_init(&phba->cmf_stats_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7971         phba->cmf_stats_timer.function = lpfc_cmf_stats_timer;
7972
7973         /*
7974          * Control structure for handling external multi-buffer mailbox
7975          * command pass-through.
7976          */
7977         memset((uint8_t *)&phba->mbox_ext_buf_ctx, 0,
7978                 sizeof(struct lpfc_mbox_ext_buf_ctx));
7979         INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
7980
7981         phba->max_vpi = LPFC_MAX_VPI;
7982
7983         /* This will be set to correct value after the read_config mbox */
7984         phba->max_vports = 0;
7985
7986         /* Program the default value of vlan_id and fc_map */
7987         phba->valid_vlan = 0;
7988         phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
7989         phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
7990         phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
7991
7992         /*
7993          * For SLI4, instead of using ring 0 (LPFC_FCP_RING) for FCP commands
7994          * we will associate a new ring, for each EQ/CQ/WQ tuple.
7995          * The WQ create will allocate the ring.
7996          */
7997
7998         /* Initialize buffer queue management fields */
7999         INIT_LIST_HEAD(&phba->hbqs[LPFC_ELS_HBQ].hbq_buffer_list);
8000         phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_sli4_rb_alloc;
8001         phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_sli4_rb_free;
8002
8003         /* for VMID idle timeout if VMID is enabled */
8004         if (lpfc_is_vmid_enabled(phba))
8005                 timer_setup(&phba->inactive_vmid_poll, lpfc_vmid_poll, 0);
8006
8007         /*
8008          * Initialize the SLI Layer to run with lpfc SLI4 HBAs.
8009          */
8010         /* Initialize the Abort buffer list used by driver */
8011         spin_lock_init(&phba->sli4_hba.abts_io_buf_list_lock);
8012         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_io_buf_list);
8013
8014         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8015                 /* Initialize the Abort nvme buffer list used by driver */
8016                 spin_lock_init(&phba->sli4_hba.abts_nvmet_buf_list_lock);
8017                 INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8018                 INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_io_wait_list);
8019                 spin_lock_init(&phba->sli4_hba.t_active_list_lock);
8020                 INIT_LIST_HEAD(&phba->sli4_hba.t_active_ctx_list);
8021         }
8022
8023         /* This abort list used by worker thread */
8024         spin_lock_init(&phba->sli4_hba.sgl_list_lock);
8025         spin_lock_init(&phba->sli4_hba.nvmet_io_wait_lock);
8026         spin_lock_init(&phba->sli4_hba.asynce_list_lock);
8027         spin_lock_init(&phba->sli4_hba.els_xri_abrt_list_lock);
8028
8029         /*
8030          * Initialize driver internal slow-path work queues
8031          */
8032
8033         /* Driver internel slow-path CQ Event pool */
8034         INIT_LIST_HEAD(&phba->sli4_hba.sp_cqe_event_pool);
8035         /* Response IOCB work queue list */
8036         INIT_LIST_HEAD(&phba->sli4_hba.sp_queue_event);
8037         /* Asynchronous event CQ Event work queue list */
8038         INIT_LIST_HEAD(&phba->sli4_hba.sp_asynce_work_queue);
8039         /* Slow-path XRI aborted CQ Event work queue list */
8040         INIT_LIST_HEAD(&phba->sli4_hba.sp_els_xri_aborted_work_queue);
8041         /* Receive queue CQ Event work queue list */
8042         INIT_LIST_HEAD(&phba->sli4_hba.sp_unsol_work_queue);
8043
8044         /* Initialize extent block lists. */
8045         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_blk_list);
8046         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_xri_blk_list);
8047         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_vfi_blk_list);
8048         INIT_LIST_HEAD(&phba->lpfc_vpi_blk_list);
8049
8050         /* Initialize mboxq lists. If the early init routines fail
8051          * these lists need to be correctly initialized.
8052          */
8053         INIT_LIST_HEAD(&phba->sli.mboxq);
8054         INIT_LIST_HEAD(&phba->sli.mboxq_cmpl);
8055
8056         /* initialize optic_state to 0xFF */
8057         phba->sli4_hba.lnk_info.optic_state = 0xff;
8058
8059         /* Allocate device driver memory */
8060         rc = lpfc_mem_alloc(phba, SGL_ALIGN_SZ);
8061         if (rc)
8062                 goto out_destroy_workqueue;
8063
8064         /* IF Type 2 ports get initialized now. */
8065         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
8066             LPFC_SLI_INTF_IF_TYPE_2) {
8067                 rc = lpfc_pci_function_reset(phba);
8068                 if (unlikely(rc)) {
8069                         rc = -ENODEV;
8070                         goto out_free_mem;
8071                 }
8072                 phba->temp_sensor_support = 1;
8073         }
8074
8075         /* Create the bootstrap mailbox command */
8076         rc = lpfc_create_bootstrap_mbox(phba);
8077         if (unlikely(rc))
8078                 goto out_free_mem;
8079
8080         /* Set up the host's endian order with the device. */
8081         rc = lpfc_setup_endian_order(phba);
8082         if (unlikely(rc))
8083                 goto out_free_bsmbx;
8084
8085         /* Set up the hba's configuration parameters. */
8086         rc = lpfc_sli4_read_config(phba);
8087         if (unlikely(rc))
8088                 goto out_free_bsmbx;
8089
8090         if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG) {
8091                 /* Right now the link is down, if FA-PWWN is configured the
8092                  * firmware will try FLOGI before the driver gets a link up.
8093                  * If it fails, the driver should get a MISCONFIGURED async
8094                  * event which will clear this flag. The only notification
8095                  * the driver gets is if it fails, if it succeeds there is no
8096                  * notification given. Assume success.
8097                  */
8098                 phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
8099         }
8100
8101         rc = lpfc_mem_alloc_active_rrq_pool_s4(phba);
8102         if (unlikely(rc))
8103                 goto out_free_bsmbx;
8104
8105         /* IF Type 0 ports get initialized now. */
8106         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8107             LPFC_SLI_INTF_IF_TYPE_0) {
8108                 rc = lpfc_pci_function_reset(phba);
8109                 if (unlikely(rc))
8110                         goto out_free_bsmbx;
8111         }
8112
8113         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
8114                                                        GFP_KERNEL);
8115         if (!mboxq) {
8116                 rc = -ENOMEM;
8117                 goto out_free_bsmbx;
8118         }
8119
8120         /* Check for NVMET being configured */
8121         phba->nvmet_support = 0;
8122         if (lpfc_enable_nvmet_cnt) {
8123
8124                 /* First get WWN of HBA instance */
8125                 lpfc_read_nv(phba, mboxq);
8126                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8127                 if (rc != MBX_SUCCESS) {
8128                         lpfc_printf_log(phba, KERN_ERR,
8129                                         LOG_TRACE_EVENT,
8130                                         "6016 Mailbox failed , mbxCmd x%x "
8131                                         "READ_NV, mbxStatus x%x\n",
8132                                         bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8133                                         bf_get(lpfc_mqe_status, &mboxq->u.mqe));
8134                         mempool_free(mboxq, phba->mbox_mem_pool);
8135                         rc = -EIO;
8136                         goto out_free_bsmbx;
8137                 }
8138                 mb = &mboxq->u.mb;
8139                 memcpy(&wwn, (char *)mb->un.varRDnvp.nodename,
8140                        sizeof(uint64_t));
8141                 wwn = cpu_to_be64(wwn);
8142                 phba->sli4_hba.wwnn.u.name = wwn;
8143                 memcpy(&wwn, (char *)mb->un.varRDnvp.portname,
8144                        sizeof(uint64_t));
8145                 /* wwn is WWPN of HBA instance */
8146                 wwn = cpu_to_be64(wwn);
8147                 phba->sli4_hba.wwpn.u.name = wwn;
8148
8149                 /* Check to see if it matches any module parameter */
8150                 for (i = 0; i < lpfc_enable_nvmet_cnt; i++) {
8151                         if (wwn == lpfc_enable_nvmet[i]) {
8152 #if (IS_ENABLED(CONFIG_NVME_TARGET_FC))
8153                                 if (lpfc_nvmet_mem_alloc(phba))
8154                                         break;
8155
8156                                 phba->nvmet_support = 1; /* a match */
8157
8158                                 lpfc_printf_log(phba, KERN_ERR,
8159                                                 LOG_TRACE_EVENT,
8160                                                 "6017 NVME Target %016llx\n",
8161                                                 wwn);
8162 #else
8163                                 lpfc_printf_log(phba, KERN_ERR,
8164                                                 LOG_TRACE_EVENT,
8165                                                 "6021 Can't enable NVME Target."
8166                                                 " NVME_TARGET_FC infrastructure"
8167                                                 " is not in kernel\n");
8168 #endif
8169                                 /* Not supported for NVMET */
8170                                 phba->cfg_xri_rebalancing = 0;
8171                                 if (phba->irq_chann_mode == NHT_MODE) {
8172                                         phba->cfg_irq_chann =
8173                                                 phba->sli4_hba.num_present_cpu;
8174                                         phba->cfg_hdw_queue =
8175                                                 phba->sli4_hba.num_present_cpu;
8176                                         phba->irq_chann_mode = NORMAL_MODE;
8177                                 }
8178                                 break;
8179                         }
8180                 }
8181         }
8182
8183         lpfc_nvme_mod_param_dep(phba);
8184
8185         /*
8186          * Get sli4 parameters that override parameters from Port capabilities.
8187          * If this call fails, it isn't critical unless the SLI4 parameters come
8188          * back in conflict.
8189          */
8190         rc = lpfc_get_sli4_parameters(phba, mboxq);
8191         if (rc) {
8192                 if_type = bf_get(lpfc_sli_intf_if_type,
8193                                  &phba->sli4_hba.sli_intf);
8194                 if_fam = bf_get(lpfc_sli_intf_sli_family,
8195                                 &phba->sli4_hba.sli_intf);
8196                 if (phba->sli4_hba.extents_in_use &&
8197                     phba->sli4_hba.rpi_hdrs_in_use) {
8198                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8199                                         "2999 Unsupported SLI4 Parameters "
8200                                         "Extents and RPI headers enabled.\n");
8201                         if (if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8202                             if_fam ==  LPFC_SLI_INTF_FAMILY_BE2) {
8203                                 mempool_free(mboxq, phba->mbox_mem_pool);
8204                                 rc = -EIO;
8205                                 goto out_free_bsmbx;
8206                         }
8207                 }
8208                 if (!(if_type == LPFC_SLI_INTF_IF_TYPE_0 &&
8209                       if_fam == LPFC_SLI_INTF_FAMILY_BE2)) {
8210                         mempool_free(mboxq, phba->mbox_mem_pool);
8211                         rc = -EIO;
8212                         goto out_free_bsmbx;
8213                 }
8214         }
8215
8216         /*
8217          * 1 for cmd, 1 for rsp, NVME adds an extra one
8218          * for boundary conditions in its max_sgl_segment template.
8219          */
8220         extra = 2;
8221         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
8222                 extra++;
8223
8224         /*
8225          * It doesn't matter what family our adapter is in, we are
8226          * limited to 2 Pages, 512 SGEs, for our SGL.
8227          * There are going to be 2 reserved SGEs: 1 FCP cmnd + 1 FCP rsp
8228          */
8229         max_buf_size = (2 * SLI4_PAGE_SIZE);
8230
8231         /*
8232          * Since lpfc_sg_seg_cnt is module param, the sg_dma_buf_size
8233          * used to create the sg_dma_buf_pool must be calculated.
8234          */
8235         if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8236                 /* Both cfg_enable_bg and cfg_external_dif code paths */
8237
8238                 /*
8239                  * The scsi_buf for a T10-DIF I/O holds the FCP cmnd,
8240                  * the FCP rsp, and a SGE. Sice we have no control
8241                  * over how many protection segments the SCSI Layer
8242                  * will hand us (ie: there could be one for every block
8243                  * in the IO), just allocate enough SGEs to accomidate
8244                  * our max amount and we need to limit lpfc_sg_seg_cnt
8245                  * to minimize the risk of running out.
8246                  */
8247                 phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
8248                                 sizeof(struct fcp_rsp) + max_buf_size;
8249
8250                 /* Total SGEs for scsi_sg_list and scsi_sg_prot_list */
8251                 phba->cfg_total_seg_cnt = LPFC_MAX_SGL_SEG_CNT;
8252
8253                 /*
8254                  * If supporting DIF, reduce the seg count for scsi to
8255                  * allow room for the DIF sges.
8256                  */
8257                 if (phba->cfg_enable_bg &&
8258                     phba->cfg_sg_seg_cnt > LPFC_MAX_BG_SLI4_SEG_CNT_DIF)
8259                         phba->cfg_scsi_seg_cnt = LPFC_MAX_BG_SLI4_SEG_CNT_DIF;
8260                 else
8261                         phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8262
8263         } else {
8264                 /*
8265                  * The scsi_buf for a regular I/O holds the FCP cmnd,
8266                  * the FCP rsp, a SGE for each, and a SGE for up to
8267                  * cfg_sg_seg_cnt data segments.
8268                  */
8269                 phba->cfg_sg_dma_buf_size = sizeof(struct fcp_cmnd) +
8270                                 sizeof(struct fcp_rsp) +
8271                                 ((phba->cfg_sg_seg_cnt + extra) *
8272                                 sizeof(struct sli4_sge));
8273
8274                 /* Total SGEs for scsi_sg_list */
8275                 phba->cfg_total_seg_cnt = phba->cfg_sg_seg_cnt + extra;
8276                 phba->cfg_scsi_seg_cnt = phba->cfg_sg_seg_cnt;
8277
8278                 /*
8279                  * NOTE: if (phba->cfg_sg_seg_cnt + extra) <= 256 we only
8280                  * need to post 1 page for the SGL.
8281                  */
8282         }
8283
8284         if (phba->cfg_xpsgl && !phba->nvmet_support)
8285                 phba->cfg_sg_dma_buf_size = LPFC_DEFAULT_XPSGL_SIZE;
8286         else if (phba->cfg_sg_dma_buf_size  <= LPFC_MIN_SG_SLI4_BUF_SZ)
8287                 phba->cfg_sg_dma_buf_size = LPFC_MIN_SG_SLI4_BUF_SZ;
8288         else
8289                 phba->cfg_sg_dma_buf_size =
8290                                 SLI4_PAGE_ALIGN(phba->cfg_sg_dma_buf_size);
8291
8292         phba->border_sge_num = phba->cfg_sg_dma_buf_size /
8293                                sizeof(struct sli4_sge);
8294
8295         /* Limit to LPFC_MAX_NVME_SEG_CNT for NVME. */
8296         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
8297                 if (phba->cfg_sg_seg_cnt > LPFC_MAX_NVME_SEG_CNT) {
8298                         lpfc_printf_log(phba, KERN_INFO, LOG_NVME | LOG_INIT,
8299                                         "6300 Reducing NVME sg segment "
8300                                         "cnt to %d\n",
8301                                         LPFC_MAX_NVME_SEG_CNT);
8302                         phba->cfg_nvme_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
8303                 } else
8304                         phba->cfg_nvme_seg_cnt = phba->cfg_sg_seg_cnt;
8305         }
8306
8307         lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP,
8308                         "9087 sg_seg_cnt:%d dmabuf_size:%d "
8309                         "total:%d scsi:%d nvme:%d\n",
8310                         phba->cfg_sg_seg_cnt, phba->cfg_sg_dma_buf_size,
8311                         phba->cfg_total_seg_cnt,  phba->cfg_scsi_seg_cnt,
8312                         phba->cfg_nvme_seg_cnt);
8313
8314         if (phba->cfg_sg_dma_buf_size < SLI4_PAGE_SIZE)
8315                 i = phba->cfg_sg_dma_buf_size;
8316         else
8317                 i = SLI4_PAGE_SIZE;
8318
8319         phba->lpfc_sg_dma_buf_pool =
8320                         dma_pool_create("lpfc_sg_dma_buf_pool",
8321                                         &phba->pcidev->dev,
8322                                         phba->cfg_sg_dma_buf_size,
8323                                         i, 0);
8324         if (!phba->lpfc_sg_dma_buf_pool) {
8325                 rc = -ENOMEM;
8326                 goto out_free_bsmbx;
8327         }
8328
8329         phba->lpfc_cmd_rsp_buf_pool =
8330                         dma_pool_create("lpfc_cmd_rsp_buf_pool",
8331                                         &phba->pcidev->dev,
8332                                         sizeof(struct fcp_cmnd) +
8333                                         sizeof(struct fcp_rsp),
8334                                         i, 0);
8335         if (!phba->lpfc_cmd_rsp_buf_pool) {
8336                 rc = -ENOMEM;
8337                 goto out_free_sg_dma_buf;
8338         }
8339
8340         mempool_free(mboxq, phba->mbox_mem_pool);
8341
8342         /* Verify OAS is supported */
8343         lpfc_sli4_oas_verify(phba);
8344
8345         /* Verify RAS support on adapter */
8346         lpfc_sli4_ras_init(phba);
8347
8348         /* Verify all the SLI4 queues */
8349         rc = lpfc_sli4_queue_verify(phba);
8350         if (rc)
8351                 goto out_free_cmd_rsp_buf;
8352
8353         /* Create driver internal CQE event pool */
8354         rc = lpfc_sli4_cq_event_pool_create(phba);
8355         if (rc)
8356                 goto out_free_cmd_rsp_buf;
8357
8358         /* Initialize sgl lists per host */
8359         lpfc_init_sgl_list(phba);
8360
8361         /* Allocate and initialize active sgl array */
8362         rc = lpfc_init_active_sgl_array(phba);
8363         if (rc) {
8364                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8365                                 "1430 Failed to initialize sgl list.\n");
8366                 goto out_destroy_cq_event_pool;
8367         }
8368         rc = lpfc_sli4_init_rpi_hdrs(phba);
8369         if (rc) {
8370                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8371                                 "1432 Failed to initialize rpi headers.\n");
8372                 goto out_free_active_sgl;
8373         }
8374
8375         /* Allocate eligible FCF bmask memory for FCF roundrobin failover */
8376         longs = (LPFC_SLI4_FCF_TBL_INDX_MAX + BITS_PER_LONG - 1)/BITS_PER_LONG;
8377         phba->fcf.fcf_rr_bmask = kcalloc(longs, sizeof(unsigned long),
8378                                          GFP_KERNEL);
8379         if (!phba->fcf.fcf_rr_bmask) {
8380                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8381                                 "2759 Failed allocate memory for FCF round "
8382                                 "robin failover bmask\n");
8383                 rc = -ENOMEM;
8384                 goto out_remove_rpi_hdrs;
8385         }
8386
8387         phba->sli4_hba.hba_eq_hdl = kcalloc(phba->cfg_irq_chann,
8388                                             sizeof(struct lpfc_hba_eq_hdl),
8389                                             GFP_KERNEL);
8390         if (!phba->sli4_hba.hba_eq_hdl) {
8391                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8392                                 "2572 Failed allocate memory for "
8393                                 "fast-path per-EQ handle array\n");
8394                 rc = -ENOMEM;
8395                 goto out_free_fcf_rr_bmask;
8396         }
8397
8398         phba->sli4_hba.cpu_map = kcalloc(phba->sli4_hba.num_possible_cpu,
8399                                         sizeof(struct lpfc_vector_map_info),
8400                                         GFP_KERNEL);
8401         if (!phba->sli4_hba.cpu_map) {
8402                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8403                                 "3327 Failed allocate memory for msi-x "
8404                                 "interrupt vector mapping\n");
8405                 rc = -ENOMEM;
8406                 goto out_free_hba_eq_hdl;
8407         }
8408
8409         phba->sli4_hba.eq_info = alloc_percpu(struct lpfc_eq_intr_info);
8410         if (!phba->sli4_hba.eq_info) {
8411                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8412                                 "3321 Failed allocation for per_cpu stats\n");
8413                 rc = -ENOMEM;
8414                 goto out_free_hba_cpu_map;
8415         }
8416
8417         phba->sli4_hba.idle_stat = kcalloc(phba->sli4_hba.num_possible_cpu,
8418                                            sizeof(*phba->sli4_hba.idle_stat),
8419                                            GFP_KERNEL);
8420         if (!phba->sli4_hba.idle_stat) {
8421                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8422                                 "3390 Failed allocation for idle_stat\n");
8423                 rc = -ENOMEM;
8424                 goto out_free_hba_eq_info;
8425         }
8426
8427 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8428         phba->sli4_hba.c_stat = alloc_percpu(struct lpfc_hdwq_stat);
8429         if (!phba->sli4_hba.c_stat) {
8430                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8431                                 "3332 Failed allocating per cpu hdwq stats\n");
8432                 rc = -ENOMEM;
8433                 goto out_free_hba_idle_stat;
8434         }
8435 #endif
8436
8437         phba->cmf_stat = alloc_percpu(struct lpfc_cgn_stat);
8438         if (!phba->cmf_stat) {
8439                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8440                                 "3331 Failed allocating per cpu cgn stats\n");
8441                 rc = -ENOMEM;
8442                 goto out_free_hba_hdwq_info;
8443         }
8444
8445         /*
8446          * Enable sr-iov virtual functions if supported and configured
8447          * through the module parameter.
8448          */
8449         if (phba->cfg_sriov_nr_virtfn > 0) {
8450                 rc = lpfc_sli_probe_sriov_nr_virtfn(phba,
8451                                                  phba->cfg_sriov_nr_virtfn);
8452                 if (rc) {
8453                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
8454                                         "3020 Requested number of SR-IOV "
8455                                         "virtual functions (%d) is not "
8456                                         "supported\n",
8457                                         phba->cfg_sriov_nr_virtfn);
8458                         phba->cfg_sriov_nr_virtfn = 0;
8459                 }
8460         }
8461
8462         return 0;
8463
8464 out_free_hba_hdwq_info:
8465 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8466         free_percpu(phba->sli4_hba.c_stat);
8467 out_free_hba_idle_stat:
8468 #endif
8469         kfree(phba->sli4_hba.idle_stat);
8470 out_free_hba_eq_info:
8471         free_percpu(phba->sli4_hba.eq_info);
8472 out_free_hba_cpu_map:
8473         kfree(phba->sli4_hba.cpu_map);
8474 out_free_hba_eq_hdl:
8475         kfree(phba->sli4_hba.hba_eq_hdl);
8476 out_free_fcf_rr_bmask:
8477         kfree(phba->fcf.fcf_rr_bmask);
8478 out_remove_rpi_hdrs:
8479         lpfc_sli4_remove_rpi_hdrs(phba);
8480 out_free_active_sgl:
8481         lpfc_free_active_sgl(phba);
8482 out_destroy_cq_event_pool:
8483         lpfc_sli4_cq_event_pool_destroy(phba);
8484 out_free_cmd_rsp_buf:
8485         dma_pool_destroy(phba->lpfc_cmd_rsp_buf_pool);
8486         phba->lpfc_cmd_rsp_buf_pool = NULL;
8487 out_free_sg_dma_buf:
8488         dma_pool_destroy(phba->lpfc_sg_dma_buf_pool);
8489         phba->lpfc_sg_dma_buf_pool = NULL;
8490 out_free_bsmbx:
8491         lpfc_destroy_bootstrap_mbox(phba);
8492 out_free_mem:
8493         lpfc_mem_free(phba);
8494 out_destroy_workqueue:
8495         destroy_workqueue(phba->wq);
8496         phba->wq = NULL;
8497         return rc;
8498 }
8499
8500 /**
8501  * lpfc_sli4_driver_resource_unset - Unset drvr internal resources for SLI4 dev
8502  * @phba: pointer to lpfc hba data structure.
8503  *
8504  * This routine is invoked to unset the driver internal resources set up
8505  * specific for supporting the SLI-4 HBA device it attached to.
8506  **/
8507 static void
8508 lpfc_sli4_driver_resource_unset(struct lpfc_hba *phba)
8509 {
8510         struct lpfc_fcf_conn_entry *conn_entry, *next_conn_entry;
8511
8512         free_percpu(phba->sli4_hba.eq_info);
8513 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
8514         free_percpu(phba->sli4_hba.c_stat);
8515 #endif
8516         free_percpu(phba->cmf_stat);
8517         kfree(phba->sli4_hba.idle_stat);
8518
8519         /* Free memory allocated for msi-x interrupt vector to CPU mapping */
8520         kfree(phba->sli4_hba.cpu_map);
8521         phba->sli4_hba.num_possible_cpu = 0;
8522         phba->sli4_hba.num_present_cpu = 0;
8523         phba->sli4_hba.curr_disp_cpu = 0;
8524         cpumask_clear(&phba->sli4_hba.irq_aff_mask);
8525
8526         /* Free memory allocated for fast-path work queue handles */
8527         kfree(phba->sli4_hba.hba_eq_hdl);
8528
8529         /* Free the allocated rpi headers. */
8530         lpfc_sli4_remove_rpi_hdrs(phba);
8531         lpfc_sli4_remove_rpis(phba);
8532
8533         /* Free eligible FCF index bmask */
8534         kfree(phba->fcf.fcf_rr_bmask);
8535
8536         /* Free the ELS sgl list */
8537         lpfc_free_active_sgl(phba);
8538         lpfc_free_els_sgl_list(phba);
8539         lpfc_free_nvmet_sgl_list(phba);
8540
8541         /* Free the completion queue EQ event pool */
8542         lpfc_sli4_cq_event_release_all(phba);
8543         lpfc_sli4_cq_event_pool_destroy(phba);
8544
8545         /* Release resource identifiers. */
8546         lpfc_sli4_dealloc_resource_identifiers(phba);
8547
8548         /* Free the bsmbx region. */
8549         lpfc_destroy_bootstrap_mbox(phba);
8550
8551         /* Free the SLI Layer memory with SLI4 HBAs */
8552         lpfc_mem_free_all(phba);
8553
8554         /* Free the current connect table */
8555         list_for_each_entry_safe(conn_entry, next_conn_entry,
8556                 &phba->fcf_conn_rec_list, list) {
8557                 list_del_init(&conn_entry->list);
8558                 kfree(conn_entry);
8559         }
8560
8561         return;
8562 }
8563
8564 /**
8565  * lpfc_init_api_table_setup - Set up init api function jump table
8566  * @phba: The hba struct for which this call is being executed.
8567  * @dev_grp: The HBA PCI-Device group number.
8568  *
8569  * This routine sets up the device INIT interface API function jump table
8570  * in @phba struct.
8571  *
8572  * Returns: 0 - success, -ENODEV - failure.
8573  **/
8574 int
8575 lpfc_init_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8576 {
8577         phba->lpfc_hba_init_link = lpfc_hba_init_link;
8578         phba->lpfc_hba_down_link = lpfc_hba_down_link;
8579         phba->lpfc_selective_reset = lpfc_selective_reset;
8580         switch (dev_grp) {
8581         case LPFC_PCI_DEV_LP:
8582                 phba->lpfc_hba_down_post = lpfc_hba_down_post_s3;
8583                 phba->lpfc_handle_eratt = lpfc_handle_eratt_s3;
8584                 phba->lpfc_stop_port = lpfc_stop_port_s3;
8585                 break;
8586         case LPFC_PCI_DEV_OC:
8587                 phba->lpfc_hba_down_post = lpfc_hba_down_post_s4;
8588                 phba->lpfc_handle_eratt = lpfc_handle_eratt_s4;
8589                 phba->lpfc_stop_port = lpfc_stop_port_s4;
8590                 break;
8591         default:
8592                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8593                                 "1431 Invalid HBA PCI-device group: 0x%x\n",
8594                                 dev_grp);
8595                 return -ENODEV;
8596         }
8597         return 0;
8598 }
8599
8600 /**
8601  * lpfc_setup_driver_resource_phase2 - Phase2 setup driver internal resources.
8602  * @phba: pointer to lpfc hba data structure.
8603  *
8604  * This routine is invoked to set up the driver internal resources after the
8605  * device specific resource setup to support the HBA device it attached to.
8606  *
8607  * Return codes
8608  *      0 - successful
8609  *      other values - error
8610  **/
8611 static int
8612 lpfc_setup_driver_resource_phase2(struct lpfc_hba *phba)
8613 {
8614         int error;
8615
8616         /* Startup the kernel thread for this host adapter. */
8617         phba->worker_thread = kthread_run(lpfc_do_work, phba,
8618                                           "lpfc_worker_%d", phba->brd_no);
8619         if (IS_ERR(phba->worker_thread)) {
8620                 error = PTR_ERR(phba->worker_thread);
8621                 return error;
8622         }
8623
8624         return 0;
8625 }
8626
8627 /**
8628  * lpfc_unset_driver_resource_phase2 - Phase2 unset driver internal resources.
8629  * @phba: pointer to lpfc hba data structure.
8630  *
8631  * This routine is invoked to unset the driver internal resources set up after
8632  * the device specific resource setup for supporting the HBA device it
8633  * attached to.
8634  **/
8635 static void
8636 lpfc_unset_driver_resource_phase2(struct lpfc_hba *phba)
8637 {
8638         if (phba->wq) {
8639                 destroy_workqueue(phba->wq);
8640                 phba->wq = NULL;
8641         }
8642
8643         /* Stop kernel worker thread */
8644         if (phba->worker_thread)
8645                 kthread_stop(phba->worker_thread);
8646 }
8647
8648 /**
8649  * lpfc_free_iocb_list - Free iocb list.
8650  * @phba: pointer to lpfc hba data structure.
8651  *
8652  * This routine is invoked to free the driver's IOCB list and memory.
8653  **/
8654 void
8655 lpfc_free_iocb_list(struct lpfc_hba *phba)
8656 {
8657         struct lpfc_iocbq *iocbq_entry = NULL, *iocbq_next = NULL;
8658
8659         spin_lock_irq(&phba->hbalock);
8660         list_for_each_entry_safe(iocbq_entry, iocbq_next,
8661                                  &phba->lpfc_iocb_list, list) {
8662                 list_del(&iocbq_entry->list);
8663                 kfree(iocbq_entry);
8664                 phba->total_iocbq_bufs--;
8665         }
8666         spin_unlock_irq(&phba->hbalock);
8667
8668         return;
8669 }
8670
8671 /**
8672  * lpfc_init_iocb_list - Allocate and initialize iocb list.
8673  * @phba: pointer to lpfc hba data structure.
8674  * @iocb_count: number of requested iocbs
8675  *
8676  * This routine is invoked to allocate and initizlize the driver's IOCB
8677  * list and set up the IOCB tag array accordingly.
8678  *
8679  * Return codes
8680  *      0 - successful
8681  *      other values - error
8682  **/
8683 int
8684 lpfc_init_iocb_list(struct lpfc_hba *phba, int iocb_count)
8685 {
8686         struct lpfc_iocbq *iocbq_entry = NULL;
8687         uint16_t iotag;
8688         int i;
8689
8690         /* Initialize and populate the iocb list per host.  */
8691         INIT_LIST_HEAD(&phba->lpfc_iocb_list);
8692         for (i = 0; i < iocb_count; i++) {
8693                 iocbq_entry = kzalloc(sizeof(struct lpfc_iocbq), GFP_KERNEL);
8694                 if (iocbq_entry == NULL) {
8695                         printk(KERN_ERR "%s: only allocated %d iocbs of "
8696                                 "expected %d count. Unloading driver.\n",
8697                                 __func__, i, iocb_count);
8698                         goto out_free_iocbq;
8699                 }
8700
8701                 iotag = lpfc_sli_next_iotag(phba, iocbq_entry);
8702                 if (iotag == 0) {
8703                         kfree(iocbq_entry);
8704                         printk(KERN_ERR "%s: failed to allocate IOTAG. "
8705                                 "Unloading driver.\n", __func__);
8706                         goto out_free_iocbq;
8707                 }
8708                 iocbq_entry->sli4_lxritag = NO_XRI;
8709                 iocbq_entry->sli4_xritag = NO_XRI;
8710
8711                 spin_lock_irq(&phba->hbalock);
8712                 list_add(&iocbq_entry->list, &phba->lpfc_iocb_list);
8713                 phba->total_iocbq_bufs++;
8714                 spin_unlock_irq(&phba->hbalock);
8715         }
8716
8717         return 0;
8718
8719 out_free_iocbq:
8720         lpfc_free_iocb_list(phba);
8721
8722         return -ENOMEM;
8723 }
8724
8725 /**
8726  * lpfc_free_sgl_list - Free a given sgl list.
8727  * @phba: pointer to lpfc hba data structure.
8728  * @sglq_list: pointer to the head of sgl list.
8729  *
8730  * This routine is invoked to free a give sgl list and memory.
8731  **/
8732 void
8733 lpfc_free_sgl_list(struct lpfc_hba *phba, struct list_head *sglq_list)
8734 {
8735         struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8736
8737         list_for_each_entry_safe(sglq_entry, sglq_next, sglq_list, list) {
8738                 list_del(&sglq_entry->list);
8739                 lpfc_mbuf_free(phba, sglq_entry->virt, sglq_entry->phys);
8740                 kfree(sglq_entry);
8741         }
8742 }
8743
8744 /**
8745  * lpfc_free_els_sgl_list - Free els sgl list.
8746  * @phba: pointer to lpfc hba data structure.
8747  *
8748  * This routine is invoked to free the driver's els sgl list and memory.
8749  **/
8750 static void
8751 lpfc_free_els_sgl_list(struct lpfc_hba *phba)
8752 {
8753         LIST_HEAD(sglq_list);
8754
8755         /* Retrieve all els sgls from driver list */
8756         spin_lock_irq(&phba->sli4_hba.sgl_list_lock);
8757         list_splice_init(&phba->sli4_hba.lpfc_els_sgl_list, &sglq_list);
8758         spin_unlock_irq(&phba->sli4_hba.sgl_list_lock);
8759
8760         /* Now free the sgl list */
8761         lpfc_free_sgl_list(phba, &sglq_list);
8762 }
8763
8764 /**
8765  * lpfc_free_nvmet_sgl_list - Free nvmet sgl list.
8766  * @phba: pointer to lpfc hba data structure.
8767  *
8768  * This routine is invoked to free the driver's nvmet sgl list and memory.
8769  **/
8770 static void
8771 lpfc_free_nvmet_sgl_list(struct lpfc_hba *phba)
8772 {
8773         struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
8774         LIST_HEAD(sglq_list);
8775
8776         /* Retrieve all nvmet sgls from driver list */
8777         spin_lock_irq(&phba->hbalock);
8778         spin_lock(&phba->sli4_hba.sgl_list_lock);
8779         list_splice_init(&phba->sli4_hba.lpfc_nvmet_sgl_list, &sglq_list);
8780         spin_unlock(&phba->sli4_hba.sgl_list_lock);
8781         spin_unlock_irq(&phba->hbalock);
8782
8783         /* Now free the sgl list */
8784         list_for_each_entry_safe(sglq_entry, sglq_next, &sglq_list, list) {
8785                 list_del(&sglq_entry->list);
8786                 lpfc_nvmet_buf_free(phba, sglq_entry->virt, sglq_entry->phys);
8787                 kfree(sglq_entry);
8788         }
8789
8790         /* Update the nvmet_xri_cnt to reflect no current sgls.
8791          * The next initialization cycle sets the count and allocates
8792          * the sgls over again.
8793          */
8794         phba->sli4_hba.nvmet_xri_cnt = 0;
8795 }
8796
8797 /**
8798  * lpfc_init_active_sgl_array - Allocate the buf to track active ELS XRIs.
8799  * @phba: pointer to lpfc hba data structure.
8800  *
8801  * This routine is invoked to allocate the driver's active sgl memory.
8802  * This array will hold the sglq_entry's for active IOs.
8803  **/
8804 static int
8805 lpfc_init_active_sgl_array(struct lpfc_hba *phba)
8806 {
8807         int size;
8808         size = sizeof(struct lpfc_sglq *);
8809         size *= phba->sli4_hba.max_cfg_param.max_xri;
8810
8811         phba->sli4_hba.lpfc_sglq_active_list =
8812                 kzalloc(size, GFP_KERNEL);
8813         if (!phba->sli4_hba.lpfc_sglq_active_list)
8814                 return -ENOMEM;
8815         return 0;
8816 }
8817
8818 /**
8819  * lpfc_free_active_sgl - Free the buf that tracks active ELS XRIs.
8820  * @phba: pointer to lpfc hba data structure.
8821  *
8822  * This routine is invoked to walk through the array of active sglq entries
8823  * and free all of the resources.
8824  * This is just a place holder for now.
8825  **/
8826 static void
8827 lpfc_free_active_sgl(struct lpfc_hba *phba)
8828 {
8829         kfree(phba->sli4_hba.lpfc_sglq_active_list);
8830 }
8831
8832 /**
8833  * lpfc_init_sgl_list - Allocate and initialize sgl list.
8834  * @phba: pointer to lpfc hba data structure.
8835  *
8836  * This routine is invoked to allocate and initizlize the driver's sgl
8837  * list and set up the sgl xritag tag array accordingly.
8838  *
8839  **/
8840 static void
8841 lpfc_init_sgl_list(struct lpfc_hba *phba)
8842 {
8843         /* Initialize and populate the sglq list per host/VF. */
8844         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_els_sgl_list);
8845         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_els_sgl_list);
8846         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_nvmet_sgl_list);
8847         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
8848
8849         /* els xri-sgl book keeping */
8850         phba->sli4_hba.els_xri_cnt = 0;
8851
8852         /* nvme xri-buffer book keeping */
8853         phba->sli4_hba.io_xri_cnt = 0;
8854 }
8855
8856 /**
8857  * lpfc_sli4_init_rpi_hdrs - Post the rpi header memory region to the port
8858  * @phba: pointer to lpfc hba data structure.
8859  *
8860  * This routine is invoked to post rpi header templates to the
8861  * port for those SLI4 ports that do not support extents.  This routine
8862  * posts a PAGE_SIZE memory region to the port to hold up to
8863  * PAGE_SIZE modulo 64 rpi context headers.  This is an initialization routine
8864  * and should be called only when interrupts are disabled.
8865  *
8866  * Return codes
8867  *      0 - successful
8868  *      -ERROR - otherwise.
8869  **/
8870 int
8871 lpfc_sli4_init_rpi_hdrs(struct lpfc_hba *phba)
8872 {
8873         int rc = 0;
8874         struct lpfc_rpi_hdr *rpi_hdr;
8875
8876         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_rpi_hdr_list);
8877         if (!phba->sli4_hba.rpi_hdrs_in_use)
8878                 return rc;
8879         if (phba->sli4_hba.extents_in_use)
8880                 return -EIO;
8881
8882         rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
8883         if (!rpi_hdr) {
8884                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8885                                 "0391 Error during rpi post operation\n");
8886                 lpfc_sli4_remove_rpis(phba);
8887                 rc = -ENODEV;
8888         }
8889
8890         return rc;
8891 }
8892
8893 /**
8894  * lpfc_sli4_create_rpi_hdr - Allocate an rpi header memory region
8895  * @phba: pointer to lpfc hba data structure.
8896  *
8897  * This routine is invoked to allocate a single 4KB memory region to
8898  * support rpis and stores them in the phba.  This single region
8899  * provides support for up to 64 rpis.  The region is used globally
8900  * by the device.
8901  *
8902  * Returns:
8903  *   A valid rpi hdr on success.
8904  *   A NULL pointer on any failure.
8905  **/
8906 struct lpfc_rpi_hdr *
8907 lpfc_sli4_create_rpi_hdr(struct lpfc_hba *phba)
8908 {
8909         uint16_t rpi_limit, curr_rpi_range;
8910         struct lpfc_dmabuf *dmabuf;
8911         struct lpfc_rpi_hdr *rpi_hdr;
8912
8913         /*
8914          * If the SLI4 port supports extents, posting the rpi header isn't
8915          * required.  Set the expected maximum count and let the actual value
8916          * get set when extents are fully allocated.
8917          */
8918         if (!phba->sli4_hba.rpi_hdrs_in_use)
8919                 return NULL;
8920         if (phba->sli4_hba.extents_in_use)
8921                 return NULL;
8922
8923         /* The limit on the logical index is just the max_rpi count. */
8924         rpi_limit = phba->sli4_hba.max_cfg_param.max_rpi;
8925
8926         spin_lock_irq(&phba->hbalock);
8927         /*
8928          * Establish the starting RPI in this header block.  The starting
8929          * rpi is normalized to a zero base because the physical rpi is
8930          * port based.
8931          */
8932         curr_rpi_range = phba->sli4_hba.next_rpi;
8933         spin_unlock_irq(&phba->hbalock);
8934
8935         /* Reached full RPI range */
8936         if (curr_rpi_range == rpi_limit)
8937                 return NULL;
8938
8939         /*
8940          * First allocate the protocol header region for the port.  The
8941          * port expects a 4KB DMA-mapped memory region that is 4K aligned.
8942          */
8943         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
8944         if (!dmabuf)
8945                 return NULL;
8946
8947         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
8948                                           LPFC_HDR_TEMPLATE_SIZE,
8949                                           &dmabuf->phys, GFP_KERNEL);
8950         if (!dmabuf->virt) {
8951                 rpi_hdr = NULL;
8952                 goto err_free_dmabuf;
8953         }
8954
8955         if (!IS_ALIGNED(dmabuf->phys, LPFC_HDR_TEMPLATE_SIZE)) {
8956                 rpi_hdr = NULL;
8957                 goto err_free_coherent;
8958         }
8959
8960         /* Save the rpi header data for cleanup later. */
8961         rpi_hdr = kzalloc(sizeof(struct lpfc_rpi_hdr), GFP_KERNEL);
8962         if (!rpi_hdr)
8963                 goto err_free_coherent;
8964
8965         rpi_hdr->dmabuf = dmabuf;
8966         rpi_hdr->len = LPFC_HDR_TEMPLATE_SIZE;
8967         rpi_hdr->page_count = 1;
8968         spin_lock_irq(&phba->hbalock);
8969
8970         /* The rpi_hdr stores the logical index only. */
8971         rpi_hdr->start_rpi = curr_rpi_range;
8972         rpi_hdr->next_rpi = phba->sli4_hba.next_rpi + LPFC_RPI_HDR_COUNT;
8973         list_add_tail(&rpi_hdr->list, &phba->sli4_hba.lpfc_rpi_hdr_list);
8974
8975         spin_unlock_irq(&phba->hbalock);
8976         return rpi_hdr;
8977
8978  err_free_coherent:
8979         dma_free_coherent(&phba->pcidev->dev, LPFC_HDR_TEMPLATE_SIZE,
8980                           dmabuf->virt, dmabuf->phys);
8981  err_free_dmabuf:
8982         kfree(dmabuf);
8983         return NULL;
8984 }
8985
8986 /**
8987  * lpfc_sli4_remove_rpi_hdrs - Remove all rpi header memory regions
8988  * @phba: pointer to lpfc hba data structure.
8989  *
8990  * This routine is invoked to remove all memory resources allocated
8991  * to support rpis for SLI4 ports not supporting extents. This routine
8992  * presumes the caller has released all rpis consumed by fabric or port
8993  * logins and is prepared to have the header pages removed.
8994  **/
8995 void
8996 lpfc_sli4_remove_rpi_hdrs(struct lpfc_hba *phba)
8997 {
8998         struct lpfc_rpi_hdr *rpi_hdr, *next_rpi_hdr;
8999
9000         if (!phba->sli4_hba.rpi_hdrs_in_use)
9001                 goto exit;
9002
9003         list_for_each_entry_safe(rpi_hdr, next_rpi_hdr,
9004                                  &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
9005                 list_del(&rpi_hdr->list);
9006                 dma_free_coherent(&phba->pcidev->dev, rpi_hdr->len,
9007                                   rpi_hdr->dmabuf->virt, rpi_hdr->dmabuf->phys);
9008                 kfree(rpi_hdr->dmabuf);
9009                 kfree(rpi_hdr);
9010         }
9011  exit:
9012         /* There are no rpis available to the port now. */
9013         phba->sli4_hba.next_rpi = 0;
9014 }
9015
9016 /**
9017  * lpfc_hba_alloc - Allocate driver hba data structure for a device.
9018  * @pdev: pointer to pci device data structure.
9019  *
9020  * This routine is invoked to allocate the driver hba data structure for an
9021  * HBA device. If the allocation is successful, the phba reference to the
9022  * PCI device data structure is set.
9023  *
9024  * Return codes
9025  *      pointer to @phba - successful
9026  *      NULL - error
9027  **/
9028 static struct lpfc_hba *
9029 lpfc_hba_alloc(struct pci_dev *pdev)
9030 {
9031         struct lpfc_hba *phba;
9032
9033         /* Allocate memory for HBA structure */
9034         phba = kzalloc(sizeof(struct lpfc_hba), GFP_KERNEL);
9035         if (!phba) {
9036                 dev_err(&pdev->dev, "failed to allocate hba struct\n");
9037                 return NULL;
9038         }
9039
9040         /* Set reference to PCI device in HBA structure */
9041         phba->pcidev = pdev;
9042
9043         /* Assign an unused board number */
9044         phba->brd_no = lpfc_get_instance();
9045         if (phba->brd_no < 0) {
9046                 kfree(phba);
9047                 return NULL;
9048         }
9049         phba->eratt_poll_interval = LPFC_ERATT_POLL_INTERVAL;
9050
9051         spin_lock_init(&phba->ct_ev_lock);
9052         INIT_LIST_HEAD(&phba->ct_ev_waiters);
9053
9054         return phba;
9055 }
9056
9057 /**
9058  * lpfc_hba_free - Free driver hba data structure with a device.
9059  * @phba: pointer to lpfc hba data structure.
9060  *
9061  * This routine is invoked to free the driver hba data structure with an
9062  * HBA device.
9063  **/
9064 static void
9065 lpfc_hba_free(struct lpfc_hba *phba)
9066 {
9067         if (phba->sli_rev == LPFC_SLI_REV4)
9068                 kfree(phba->sli4_hba.hdwq);
9069
9070         /* Release the driver assigned board number */
9071         idr_remove(&lpfc_hba_index, phba->brd_no);
9072
9073         /* Free memory allocated with sli3 rings */
9074         kfree(phba->sli.sli3_ring);
9075         phba->sli.sli3_ring = NULL;
9076
9077         kfree(phba);
9078         return;
9079 }
9080
9081 /**
9082  * lpfc_setup_fdmi_mask - Setup initial FDMI mask for HBA and Port attributes
9083  * @vport: pointer to lpfc vport data structure.
9084  *
9085  * This routine is will setup initial FDMI attribute masks for
9086  * FDMI2 or SmartSAN depending on module parameters. The driver will attempt
9087  * to get these attributes first before falling back, the attribute
9088  * fallback hierarchy is SmartSAN -> FDMI2 -> FMDI1
9089  **/
9090 void
9091 lpfc_setup_fdmi_mask(struct lpfc_vport *vport)
9092 {
9093         struct lpfc_hba *phba = vport->phba;
9094
9095         set_bit(FC_ALLOW_FDMI, &vport->load_flag);
9096         if (phba->cfg_enable_SmartSAN ||
9097             phba->cfg_fdmi_on == LPFC_FDMI_SUPPORT) {
9098                 /* Setup appropriate attribute masks */
9099                 vport->fdmi_hba_mask = LPFC_FDMI2_HBA_ATTR;
9100                 if (phba->cfg_enable_SmartSAN)
9101                         vport->fdmi_port_mask = LPFC_FDMI2_SMART_ATTR;
9102                 else
9103                         vport->fdmi_port_mask = LPFC_FDMI2_PORT_ATTR;
9104         }
9105
9106         lpfc_printf_log(phba, KERN_INFO, LOG_DISCOVERY,
9107                         "6077 Setup FDMI mask: hba x%x port x%x\n",
9108                         vport->fdmi_hba_mask, vport->fdmi_port_mask);
9109 }
9110
9111 /**
9112  * lpfc_create_shost - Create hba physical port with associated scsi host.
9113  * @phba: pointer to lpfc hba data structure.
9114  *
9115  * This routine is invoked to create HBA physical port and associate a SCSI
9116  * host with it.
9117  *
9118  * Return codes
9119  *      0 - successful
9120  *      other values - error
9121  **/
9122 static int
9123 lpfc_create_shost(struct lpfc_hba *phba)
9124 {
9125         struct lpfc_vport *vport;
9126         struct Scsi_Host  *shost;
9127
9128         /* Initialize HBA FC structure */
9129         phba->fc_edtov = FF_DEF_EDTOV;
9130         phba->fc_ratov = FF_DEF_RATOV;
9131         phba->fc_altov = FF_DEF_ALTOV;
9132         phba->fc_arbtov = FF_DEF_ARBTOV;
9133
9134         atomic_set(&phba->sdev_cnt, 0);
9135         vport = lpfc_create_port(phba, phba->brd_no, &phba->pcidev->dev);
9136         if (!vport)
9137                 return -ENODEV;
9138
9139         shost = lpfc_shost_from_vport(vport);
9140         phba->pport = vport;
9141
9142         if (phba->nvmet_support) {
9143                 /* Only 1 vport (pport) will support NVME target */
9144                 phba->targetport = NULL;
9145                 phba->cfg_enable_fc4_type = LPFC_ENABLE_NVME;
9146                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME_DISC,
9147                                 "6076 NVME Target Found\n");
9148         }
9149
9150         lpfc_debugfs_initialize(vport);
9151         /* Put reference to SCSI host to driver's device private data */
9152         pci_set_drvdata(phba->pcidev, shost);
9153
9154         lpfc_setup_fdmi_mask(vport);
9155
9156         /*
9157          * At this point we are fully registered with PSA. In addition,
9158          * any initial discovery should be completed.
9159          */
9160         return 0;
9161 }
9162
9163 /**
9164  * lpfc_destroy_shost - Destroy hba physical port with associated scsi host.
9165  * @phba: pointer to lpfc hba data structure.
9166  *
9167  * This routine is invoked to destroy HBA physical port and the associated
9168  * SCSI host.
9169  **/
9170 static void
9171 lpfc_destroy_shost(struct lpfc_hba *phba)
9172 {
9173         struct lpfc_vport *vport = phba->pport;
9174
9175         /* Destroy physical port that associated with the SCSI host */
9176         destroy_port(vport);
9177
9178         return;
9179 }
9180
9181 /**
9182  * lpfc_setup_bg - Setup Block guard structures and debug areas.
9183  * @phba: pointer to lpfc hba data structure.
9184  * @shost: the shost to be used to detect Block guard settings.
9185  *
9186  * This routine sets up the local Block guard protocol settings for @shost.
9187  * This routine also allocates memory for debugging bg buffers.
9188  **/
9189 static void
9190 lpfc_setup_bg(struct lpfc_hba *phba, struct Scsi_Host *shost)
9191 {
9192         uint32_t old_mask;
9193         uint32_t old_guard;
9194
9195         if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9196                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9197                                 "1478 Registering BlockGuard with the "
9198                                 "SCSI layer\n");
9199
9200                 old_mask = phba->cfg_prot_mask;
9201                 old_guard = phba->cfg_prot_guard;
9202
9203                 /* Only allow supported values */
9204                 phba->cfg_prot_mask &= (SHOST_DIF_TYPE1_PROTECTION |
9205                         SHOST_DIX_TYPE0_PROTECTION |
9206                         SHOST_DIX_TYPE1_PROTECTION);
9207                 phba->cfg_prot_guard &= (SHOST_DIX_GUARD_IP |
9208                                          SHOST_DIX_GUARD_CRC);
9209
9210                 /* DIF Type 1 protection for profiles AST1/C1 is end to end */
9211                 if (phba->cfg_prot_mask == SHOST_DIX_TYPE1_PROTECTION)
9212                         phba->cfg_prot_mask |= SHOST_DIF_TYPE1_PROTECTION;
9213
9214                 if (phba->cfg_prot_mask && phba->cfg_prot_guard) {
9215                         if ((old_mask != phba->cfg_prot_mask) ||
9216                                 (old_guard != phba->cfg_prot_guard))
9217                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9218                                         "1475 Registering BlockGuard with the "
9219                                         "SCSI layer: mask %d  guard %d\n",
9220                                         phba->cfg_prot_mask,
9221                                         phba->cfg_prot_guard);
9222
9223                         scsi_host_set_prot(shost, phba->cfg_prot_mask);
9224                         scsi_host_set_guard(shost, phba->cfg_prot_guard);
9225                 } else
9226                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9227                                 "1479 Not Registering BlockGuard with the SCSI "
9228                                 "layer, Bad protection parameters: %d %d\n",
9229                                 old_mask, old_guard);
9230         }
9231 }
9232
9233 /**
9234  * lpfc_post_init_setup - Perform necessary device post initialization setup.
9235  * @phba: pointer to lpfc hba data structure.
9236  *
9237  * This routine is invoked to perform all the necessary post initialization
9238  * setup for the device.
9239  **/
9240 static void
9241 lpfc_post_init_setup(struct lpfc_hba *phba)
9242 {
9243         struct Scsi_Host  *shost;
9244         struct lpfc_adapter_event_header adapter_event;
9245
9246         /* Get the default values for Model Name and Description */
9247         lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
9248
9249         /*
9250          * hba setup may have changed the hba_queue_depth so we need to
9251          * adjust the value of can_queue.
9252          */
9253         shost = pci_get_drvdata(phba->pcidev);
9254         shost->can_queue = phba->cfg_hba_queue_depth - 10;
9255
9256         lpfc_host_attrib_init(shost);
9257
9258         if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
9259                 spin_lock_irq(shost->host_lock);
9260                 lpfc_poll_start_timer(phba);
9261                 spin_unlock_irq(shost->host_lock);
9262         }
9263
9264         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9265                         "0428 Perform SCSI scan\n");
9266         /* Send board arrival event to upper layer */
9267         adapter_event.event_type = FC_REG_ADAPTER_EVENT;
9268         adapter_event.subcategory = LPFC_EVENT_ARRIVAL;
9269         fc_host_post_vendor_event(shost, fc_get_event_number(),
9270                                   sizeof(adapter_event),
9271                                   (char *) &adapter_event,
9272                                   LPFC_NL_VENDOR_ID);
9273         return;
9274 }
9275
9276 /**
9277  * lpfc_sli_pci_mem_setup - Setup SLI3 HBA PCI memory space.
9278  * @phba: pointer to lpfc hba data structure.
9279  *
9280  * This routine is invoked to set up the PCI device memory space for device
9281  * with SLI-3 interface spec.
9282  *
9283  * Return codes
9284  *      0 - successful
9285  *      other values - error
9286  **/
9287 static int
9288 lpfc_sli_pci_mem_setup(struct lpfc_hba *phba)
9289 {
9290         struct pci_dev *pdev = phba->pcidev;
9291         unsigned long bar0map_len, bar2map_len;
9292         int i, hbq_count;
9293         void *ptr;
9294         int error;
9295
9296         if (!pdev)
9297                 return -ENODEV;
9298
9299         /* Set the device DMA mask size */
9300         error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
9301         if (error)
9302                 error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
9303         if (error)
9304                 return error;
9305         error = -ENODEV;
9306
9307         /* Get the bus address of Bar0 and Bar2 and the number of bytes
9308          * required by each mapping.
9309          */
9310         phba->pci_bar0_map = pci_resource_start(pdev, 0);
9311         bar0map_len = pci_resource_len(pdev, 0);
9312
9313         phba->pci_bar2_map = pci_resource_start(pdev, 2);
9314         bar2map_len = pci_resource_len(pdev, 2);
9315
9316         /* Map HBA SLIM to a kernel virtual address. */
9317         phba->slim_memmap_p = ioremap(phba->pci_bar0_map, bar0map_len);
9318         if (!phba->slim_memmap_p) {
9319                 dev_printk(KERN_ERR, &pdev->dev,
9320                            "ioremap failed for SLIM memory.\n");
9321                 goto out;
9322         }
9323
9324         /* Map HBA Control Registers to a kernel virtual address. */
9325         phba->ctrl_regs_memmap_p = ioremap(phba->pci_bar2_map, bar2map_len);
9326         if (!phba->ctrl_regs_memmap_p) {
9327                 dev_printk(KERN_ERR, &pdev->dev,
9328                            "ioremap failed for HBA control registers.\n");
9329                 goto out_iounmap_slim;
9330         }
9331
9332         /* Allocate memory for SLI-2 structures */
9333         phba->slim2p.virt = dma_alloc_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9334                                                &phba->slim2p.phys, GFP_KERNEL);
9335         if (!phba->slim2p.virt)
9336                 goto out_iounmap;
9337
9338         phba->mbox = phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, mbx);
9339         phba->mbox_ext = (phba->slim2p.virt +
9340                 offsetof(struct lpfc_sli2_slim, mbx_ext_words));
9341         phba->pcb = (phba->slim2p.virt + offsetof(struct lpfc_sli2_slim, pcb));
9342         phba->IOCBs = (phba->slim2p.virt +
9343                        offsetof(struct lpfc_sli2_slim, IOCBs));
9344
9345         phba->hbqslimp.virt = dma_alloc_coherent(&pdev->dev,
9346                                                  lpfc_sli_hbq_size(),
9347                                                  &phba->hbqslimp.phys,
9348                                                  GFP_KERNEL);
9349         if (!phba->hbqslimp.virt)
9350                 goto out_free_slim;
9351
9352         hbq_count = lpfc_sli_hbq_count();
9353         ptr = phba->hbqslimp.virt;
9354         for (i = 0; i < hbq_count; ++i) {
9355                 phba->hbqs[i].hbq_virt = ptr;
9356                 INIT_LIST_HEAD(&phba->hbqs[i].hbq_buffer_list);
9357                 ptr += (lpfc_hbq_defs[i]->entry_count *
9358                         sizeof(struct lpfc_hbq_entry));
9359         }
9360         phba->hbqs[LPFC_ELS_HBQ].hbq_alloc_buffer = lpfc_els_hbq_alloc;
9361         phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer = lpfc_els_hbq_free;
9362
9363         memset(phba->hbqslimp.virt, 0, lpfc_sli_hbq_size());
9364
9365         phba->MBslimaddr = phba->slim_memmap_p;
9366         phba->HAregaddr = phba->ctrl_regs_memmap_p + HA_REG_OFFSET;
9367         phba->CAregaddr = phba->ctrl_regs_memmap_p + CA_REG_OFFSET;
9368         phba->HSregaddr = phba->ctrl_regs_memmap_p + HS_REG_OFFSET;
9369         phba->HCregaddr = phba->ctrl_regs_memmap_p + HC_REG_OFFSET;
9370
9371         return 0;
9372
9373 out_free_slim:
9374         dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9375                           phba->slim2p.virt, phba->slim2p.phys);
9376 out_iounmap:
9377         iounmap(phba->ctrl_regs_memmap_p);
9378 out_iounmap_slim:
9379         iounmap(phba->slim_memmap_p);
9380 out:
9381         return error;
9382 }
9383
9384 /**
9385  * lpfc_sli_pci_mem_unset - Unset SLI3 HBA PCI memory space.
9386  * @phba: pointer to lpfc hba data structure.
9387  *
9388  * This routine is invoked to unset the PCI device memory space for device
9389  * with SLI-3 interface spec.
9390  **/
9391 static void
9392 lpfc_sli_pci_mem_unset(struct lpfc_hba *phba)
9393 {
9394         struct pci_dev *pdev;
9395
9396         /* Obtain PCI device reference */
9397         if (!phba->pcidev)
9398                 return;
9399         else
9400                 pdev = phba->pcidev;
9401
9402         /* Free coherent DMA memory allocated */
9403         dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
9404                           phba->hbqslimp.virt, phba->hbqslimp.phys);
9405         dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
9406                           phba->slim2p.virt, phba->slim2p.phys);
9407
9408         /* I/O memory unmap */
9409         iounmap(phba->ctrl_regs_memmap_p);
9410         iounmap(phba->slim_memmap_p);
9411
9412         return;
9413 }
9414
9415 /**
9416  * lpfc_sli4_post_status_check - Wait for SLI4 POST done and check status
9417  * @phba: pointer to lpfc hba data structure.
9418  *
9419  * This routine is invoked to wait for SLI4 device Power On Self Test (POST)
9420  * done and check status.
9421  *
9422  * Return 0 if successful, otherwise -ENODEV.
9423  **/
9424 int
9425 lpfc_sli4_post_status_check(struct lpfc_hba *phba)
9426 {
9427         struct lpfc_register portsmphr_reg, uerrlo_reg, uerrhi_reg;
9428         struct lpfc_register reg_data;
9429         int i, port_error = 0;
9430         uint32_t if_type;
9431
9432         memset(&portsmphr_reg, 0, sizeof(portsmphr_reg));
9433         memset(&reg_data, 0, sizeof(reg_data));
9434         if (!phba->sli4_hba.PSMPHRregaddr)
9435                 return -ENODEV;
9436
9437         /* Wait up to 30 seconds for the SLI Port POST done and ready */
9438         for (i = 0; i < 3000; i++) {
9439                 if (lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
9440                         &portsmphr_reg.word0) ||
9441                         (bf_get(lpfc_port_smphr_perr, &portsmphr_reg))) {
9442                         /* Port has a fatal POST error, break out */
9443                         port_error = -ENODEV;
9444                         break;
9445                 }
9446                 if (LPFC_POST_STAGE_PORT_READY ==
9447                     bf_get(lpfc_port_smphr_port_status, &portsmphr_reg))
9448                         break;
9449                 msleep(10);
9450         }
9451
9452         /*
9453          * If there was a port error during POST, then don't proceed with
9454          * other register reads as the data may not be valid.  Just exit.
9455          */
9456         if (port_error) {
9457                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9458                         "1408 Port Failed POST - portsmphr=0x%x, "
9459                         "perr=x%x, sfi=x%x, nip=x%x, ipc=x%x, scr1=x%x, "
9460                         "scr2=x%x, hscratch=x%x, pstatus=x%x\n",
9461                         portsmphr_reg.word0,
9462                         bf_get(lpfc_port_smphr_perr, &portsmphr_reg),
9463                         bf_get(lpfc_port_smphr_sfi, &portsmphr_reg),
9464                         bf_get(lpfc_port_smphr_nip, &portsmphr_reg),
9465                         bf_get(lpfc_port_smphr_ipc, &portsmphr_reg),
9466                         bf_get(lpfc_port_smphr_scr1, &portsmphr_reg),
9467                         bf_get(lpfc_port_smphr_scr2, &portsmphr_reg),
9468                         bf_get(lpfc_port_smphr_host_scratch, &portsmphr_reg),
9469                         bf_get(lpfc_port_smphr_port_status, &portsmphr_reg));
9470         } else {
9471                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
9472                                 "2534 Device Info: SLIFamily=0x%x, "
9473                                 "SLIRev=0x%x, IFType=0x%x, SLIHint_1=0x%x, "
9474                                 "SLIHint_2=0x%x, FT=0x%x\n",
9475                                 bf_get(lpfc_sli_intf_sli_family,
9476                                        &phba->sli4_hba.sli_intf),
9477                                 bf_get(lpfc_sli_intf_slirev,
9478                                        &phba->sli4_hba.sli_intf),
9479                                 bf_get(lpfc_sli_intf_if_type,
9480                                        &phba->sli4_hba.sli_intf),
9481                                 bf_get(lpfc_sli_intf_sli_hint1,
9482                                        &phba->sli4_hba.sli_intf),
9483                                 bf_get(lpfc_sli_intf_sli_hint2,
9484                                        &phba->sli4_hba.sli_intf),
9485                                 bf_get(lpfc_sli_intf_func_type,
9486                                        &phba->sli4_hba.sli_intf));
9487                 /*
9488                  * Check for other Port errors during the initialization
9489                  * process.  Fail the load if the port did not come up
9490                  * correctly.
9491                  */
9492                 if_type = bf_get(lpfc_sli_intf_if_type,
9493                                  &phba->sli4_hba.sli_intf);
9494                 switch (if_type) {
9495                 case LPFC_SLI_INTF_IF_TYPE_0:
9496                         phba->sli4_hba.ue_mask_lo =
9497                               readl(phba->sli4_hba.u.if_type0.UEMASKLOregaddr);
9498                         phba->sli4_hba.ue_mask_hi =
9499                               readl(phba->sli4_hba.u.if_type0.UEMASKHIregaddr);
9500                         uerrlo_reg.word0 =
9501                               readl(phba->sli4_hba.u.if_type0.UERRLOregaddr);
9502                         uerrhi_reg.word0 =
9503                                 readl(phba->sli4_hba.u.if_type0.UERRHIregaddr);
9504                         if ((~phba->sli4_hba.ue_mask_lo & uerrlo_reg.word0) ||
9505                             (~phba->sli4_hba.ue_mask_hi & uerrhi_reg.word0)) {
9506                                 lpfc_printf_log(phba, KERN_ERR,
9507                                                 LOG_TRACE_EVENT,
9508                                                 "1422 Unrecoverable Error "
9509                                                 "Detected during POST "
9510                                                 "uerr_lo_reg=0x%x, "
9511                                                 "uerr_hi_reg=0x%x, "
9512                                                 "ue_mask_lo_reg=0x%x, "
9513                                                 "ue_mask_hi_reg=0x%x\n",
9514                                                 uerrlo_reg.word0,
9515                                                 uerrhi_reg.word0,
9516                                                 phba->sli4_hba.ue_mask_lo,
9517                                                 phba->sli4_hba.ue_mask_hi);
9518                                 port_error = -ENODEV;
9519                         }
9520                         break;
9521                 case LPFC_SLI_INTF_IF_TYPE_2:
9522                 case LPFC_SLI_INTF_IF_TYPE_6:
9523                         /* Final checks.  The port status should be clean. */
9524                         if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9525                                 &reg_data.word0) ||
9526                                 lpfc_sli4_unrecoverable_port(&reg_data)) {
9527                                 phba->work_status[0] =
9528                                         readl(phba->sli4_hba.u.if_type2.
9529                                               ERR1regaddr);
9530                                 phba->work_status[1] =
9531                                         readl(phba->sli4_hba.u.if_type2.
9532                                               ERR2regaddr);
9533                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9534                                         "2888 Unrecoverable port error "
9535                                         "following POST: port status reg "
9536                                         "0x%x, port_smphr reg 0x%x, "
9537                                         "error 1=0x%x, error 2=0x%x\n",
9538                                         reg_data.word0,
9539                                         portsmphr_reg.word0,
9540                                         phba->work_status[0],
9541                                         phba->work_status[1]);
9542                                 port_error = -ENODEV;
9543                                 break;
9544                         }
9545
9546                         if (lpfc_pldv_detect &&
9547                             bf_get(lpfc_sli_intf_sli_family,
9548                                    &phba->sli4_hba.sli_intf) ==
9549                                         LPFC_SLI_INTF_FAMILY_G6)
9550                                 pci_write_config_byte(phba->pcidev,
9551                                                       LPFC_SLI_INTF, CFG_PLD);
9552                         break;
9553                 case LPFC_SLI_INTF_IF_TYPE_1:
9554                 default:
9555                         break;
9556                 }
9557         }
9558         return port_error;
9559 }
9560
9561 /**
9562  * lpfc_sli4_bar0_register_memmap - Set up SLI4 BAR0 register memory map.
9563  * @phba: pointer to lpfc hba data structure.
9564  * @if_type:  The SLI4 interface type getting configured.
9565  *
9566  * This routine is invoked to set up SLI4 BAR0 PCI config space register
9567  * memory map.
9568  **/
9569 static void
9570 lpfc_sli4_bar0_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9571 {
9572         switch (if_type) {
9573         case LPFC_SLI_INTF_IF_TYPE_0:
9574                 phba->sli4_hba.u.if_type0.UERRLOregaddr =
9575                         phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_LO;
9576                 phba->sli4_hba.u.if_type0.UERRHIregaddr =
9577                         phba->sli4_hba.conf_regs_memmap_p + LPFC_UERR_STATUS_HI;
9578                 phba->sli4_hba.u.if_type0.UEMASKLOregaddr =
9579                         phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_LO;
9580                 phba->sli4_hba.u.if_type0.UEMASKHIregaddr =
9581                         phba->sli4_hba.conf_regs_memmap_p + LPFC_UE_MASK_HI;
9582                 phba->sli4_hba.SLIINTFregaddr =
9583                         phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9584                 break;
9585         case LPFC_SLI_INTF_IF_TYPE_2:
9586                 phba->sli4_hba.u.if_type2.EQDregaddr =
9587                         phba->sli4_hba.conf_regs_memmap_p +
9588                                                 LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9589                 phba->sli4_hba.u.if_type2.ERR1regaddr =
9590                         phba->sli4_hba.conf_regs_memmap_p +
9591                                                 LPFC_CTL_PORT_ER1_OFFSET;
9592                 phba->sli4_hba.u.if_type2.ERR2regaddr =
9593                         phba->sli4_hba.conf_regs_memmap_p +
9594                                                 LPFC_CTL_PORT_ER2_OFFSET;
9595                 phba->sli4_hba.u.if_type2.CTRLregaddr =
9596                         phba->sli4_hba.conf_regs_memmap_p +
9597                                                 LPFC_CTL_PORT_CTL_OFFSET;
9598                 phba->sli4_hba.u.if_type2.STATUSregaddr =
9599                         phba->sli4_hba.conf_regs_memmap_p +
9600                                                 LPFC_CTL_PORT_STA_OFFSET;
9601                 phba->sli4_hba.SLIINTFregaddr =
9602                         phba->sli4_hba.conf_regs_memmap_p + LPFC_SLI_INTF;
9603                 phba->sli4_hba.PSMPHRregaddr =
9604                         phba->sli4_hba.conf_regs_memmap_p +
9605                                                 LPFC_CTL_PORT_SEM_OFFSET;
9606                 phba->sli4_hba.RQDBregaddr =
9607                         phba->sli4_hba.conf_regs_memmap_p +
9608                                                 LPFC_ULP0_RQ_DOORBELL;
9609                 phba->sli4_hba.WQDBregaddr =
9610                         phba->sli4_hba.conf_regs_memmap_p +
9611                                                 LPFC_ULP0_WQ_DOORBELL;
9612                 phba->sli4_hba.CQDBregaddr =
9613                         phba->sli4_hba.conf_regs_memmap_p + LPFC_EQCQ_DOORBELL;
9614                 phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9615                 phba->sli4_hba.MQDBregaddr =
9616                         phba->sli4_hba.conf_regs_memmap_p + LPFC_MQ_DOORBELL;
9617                 phba->sli4_hba.BMBXregaddr =
9618                         phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9619                 break;
9620         case LPFC_SLI_INTF_IF_TYPE_6:
9621                 phba->sli4_hba.u.if_type2.EQDregaddr =
9622                         phba->sli4_hba.conf_regs_memmap_p +
9623                                                 LPFC_CTL_PORT_EQ_DELAY_OFFSET;
9624                 phba->sli4_hba.u.if_type2.ERR1regaddr =
9625                         phba->sli4_hba.conf_regs_memmap_p +
9626                                                 LPFC_CTL_PORT_ER1_OFFSET;
9627                 phba->sli4_hba.u.if_type2.ERR2regaddr =
9628                         phba->sli4_hba.conf_regs_memmap_p +
9629                                                 LPFC_CTL_PORT_ER2_OFFSET;
9630                 phba->sli4_hba.u.if_type2.CTRLregaddr =
9631                         phba->sli4_hba.conf_regs_memmap_p +
9632                                                 LPFC_CTL_PORT_CTL_OFFSET;
9633                 phba->sli4_hba.u.if_type2.STATUSregaddr =
9634                         phba->sli4_hba.conf_regs_memmap_p +
9635                                                 LPFC_CTL_PORT_STA_OFFSET;
9636                 phba->sli4_hba.PSMPHRregaddr =
9637                         phba->sli4_hba.conf_regs_memmap_p +
9638                                                 LPFC_CTL_PORT_SEM_OFFSET;
9639                 phba->sli4_hba.BMBXregaddr =
9640                         phba->sli4_hba.conf_regs_memmap_p + LPFC_BMBX;
9641                 break;
9642         case LPFC_SLI_INTF_IF_TYPE_1:
9643         default:
9644                 dev_printk(KERN_ERR, &phba->pcidev->dev,
9645                            "FATAL - unsupported SLI4 interface type - %d\n",
9646                            if_type);
9647                 break;
9648         }
9649 }
9650
9651 /**
9652  * lpfc_sli4_bar1_register_memmap - Set up SLI4 BAR1 register memory map.
9653  * @phba: pointer to lpfc hba data structure.
9654  * @if_type: sli if type to operate on.
9655  *
9656  * This routine is invoked to set up SLI4 BAR1 register memory map.
9657  **/
9658 static void
9659 lpfc_sli4_bar1_register_memmap(struct lpfc_hba *phba, uint32_t if_type)
9660 {
9661         switch (if_type) {
9662         case LPFC_SLI_INTF_IF_TYPE_0:
9663                 phba->sli4_hba.PSMPHRregaddr =
9664                         phba->sli4_hba.ctrl_regs_memmap_p +
9665                         LPFC_SLIPORT_IF0_SMPHR;
9666                 phba->sli4_hba.ISRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9667                         LPFC_HST_ISR0;
9668                 phba->sli4_hba.IMRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9669                         LPFC_HST_IMR0;
9670                 phba->sli4_hba.ISCRregaddr = phba->sli4_hba.ctrl_regs_memmap_p +
9671                         LPFC_HST_ISCR0;
9672                 break;
9673         case LPFC_SLI_INTF_IF_TYPE_6:
9674                 phba->sli4_hba.RQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9675                         LPFC_IF6_RQ_DOORBELL;
9676                 phba->sli4_hba.WQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9677                         LPFC_IF6_WQ_DOORBELL;
9678                 phba->sli4_hba.CQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9679                         LPFC_IF6_CQ_DOORBELL;
9680                 phba->sli4_hba.EQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9681                         LPFC_IF6_EQ_DOORBELL;
9682                 phba->sli4_hba.MQDBregaddr = phba->sli4_hba.drbl_regs_memmap_p +
9683                         LPFC_IF6_MQ_DOORBELL;
9684                 break;
9685         case LPFC_SLI_INTF_IF_TYPE_2:
9686         case LPFC_SLI_INTF_IF_TYPE_1:
9687         default:
9688                 dev_err(&phba->pcidev->dev,
9689                            "FATAL - unsupported SLI4 interface type - %d\n",
9690                            if_type);
9691                 break;
9692         }
9693 }
9694
9695 /**
9696  * lpfc_sli4_bar2_register_memmap - Set up SLI4 BAR2 register memory map.
9697  * @phba: pointer to lpfc hba data structure.
9698  * @vf: virtual function number
9699  *
9700  * This routine is invoked to set up SLI4 BAR2 doorbell register memory map
9701  * based on the given viftual function number, @vf.
9702  *
9703  * Return 0 if successful, otherwise -ENODEV.
9704  **/
9705 static int
9706 lpfc_sli4_bar2_register_memmap(struct lpfc_hba *phba, uint32_t vf)
9707 {
9708         if (vf > LPFC_VIR_FUNC_MAX)
9709                 return -ENODEV;
9710
9711         phba->sli4_hba.RQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9712                                 vf * LPFC_VFR_PAGE_SIZE +
9713                                         LPFC_ULP0_RQ_DOORBELL);
9714         phba->sli4_hba.WQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9715                                 vf * LPFC_VFR_PAGE_SIZE +
9716                                         LPFC_ULP0_WQ_DOORBELL);
9717         phba->sli4_hba.CQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9718                                 vf * LPFC_VFR_PAGE_SIZE +
9719                                         LPFC_EQCQ_DOORBELL);
9720         phba->sli4_hba.EQDBregaddr = phba->sli4_hba.CQDBregaddr;
9721         phba->sli4_hba.MQDBregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9722                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_MQ_DOORBELL);
9723         phba->sli4_hba.BMBXregaddr = (phba->sli4_hba.drbl_regs_memmap_p +
9724                                 vf * LPFC_VFR_PAGE_SIZE + LPFC_BMBX);
9725         return 0;
9726 }
9727
9728 /**
9729  * lpfc_create_bootstrap_mbox - Create the bootstrap mailbox
9730  * @phba: pointer to lpfc hba data structure.
9731  *
9732  * This routine is invoked to create the bootstrap mailbox
9733  * region consistent with the SLI-4 interface spec.  This
9734  * routine allocates all memory necessary to communicate
9735  * mailbox commands to the port and sets up all alignment
9736  * needs.  No locks are expected to be held when calling
9737  * this routine.
9738  *
9739  * Return codes
9740  *      0 - successful
9741  *      -ENOMEM - could not allocated memory.
9742  **/
9743 static int
9744 lpfc_create_bootstrap_mbox(struct lpfc_hba *phba)
9745 {
9746         uint32_t bmbx_size;
9747         struct lpfc_dmabuf *dmabuf;
9748         struct dma_address *dma_address;
9749         uint32_t pa_addr;
9750         uint64_t phys_addr;
9751
9752         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
9753         if (!dmabuf)
9754                 return -ENOMEM;
9755
9756         /*
9757          * The bootstrap mailbox region is comprised of 2 parts
9758          * plus an alignment restriction of 16 bytes.
9759          */
9760         bmbx_size = sizeof(struct lpfc_bmbx_create) + (LPFC_ALIGN_16_BYTE - 1);
9761         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, bmbx_size,
9762                                           &dmabuf->phys, GFP_KERNEL);
9763         if (!dmabuf->virt) {
9764                 kfree(dmabuf);
9765                 return -ENOMEM;
9766         }
9767
9768         /*
9769          * Initialize the bootstrap mailbox pointers now so that the register
9770          * operations are simple later.  The mailbox dma address is required
9771          * to be 16-byte aligned.  Also align the virtual memory as each
9772          * maibox is copied into the bmbx mailbox region before issuing the
9773          * command to the port.
9774          */
9775         phba->sli4_hba.bmbx.dmabuf = dmabuf;
9776         phba->sli4_hba.bmbx.bmbx_size = bmbx_size;
9777
9778         phba->sli4_hba.bmbx.avirt = PTR_ALIGN(dmabuf->virt,
9779                                               LPFC_ALIGN_16_BYTE);
9780         phba->sli4_hba.bmbx.aphys = ALIGN(dmabuf->phys,
9781                                               LPFC_ALIGN_16_BYTE);
9782
9783         /*
9784          * Set the high and low physical addresses now.  The SLI4 alignment
9785          * requirement is 16 bytes and the mailbox is posted to the port
9786          * as two 30-bit addresses.  The other data is a bit marking whether
9787          * the 30-bit address is the high or low address.
9788          * Upcast bmbx aphys to 64bits so shift instruction compiles
9789          * clean on 32 bit machines.
9790          */
9791         dma_address = &phba->sli4_hba.bmbx.dma_address;
9792         phys_addr = (uint64_t)phba->sli4_hba.bmbx.aphys;
9793         pa_addr = (uint32_t) ((phys_addr >> 34) & 0x3fffffff);
9794         dma_address->addr_hi = (uint32_t) ((pa_addr << 2) |
9795                                            LPFC_BMBX_BIT1_ADDR_HI);
9796
9797         pa_addr = (uint32_t) ((phba->sli4_hba.bmbx.aphys >> 4) & 0x3fffffff);
9798         dma_address->addr_lo = (uint32_t) ((pa_addr << 2) |
9799                                            LPFC_BMBX_BIT1_ADDR_LO);
9800         return 0;
9801 }
9802
9803 /**
9804  * lpfc_destroy_bootstrap_mbox - Destroy all bootstrap mailbox resources
9805  * @phba: pointer to lpfc hba data structure.
9806  *
9807  * This routine is invoked to teardown the bootstrap mailbox
9808  * region and release all host resources. This routine requires
9809  * the caller to ensure all mailbox commands recovered, no
9810  * additional mailbox comands are sent, and interrupts are disabled
9811  * before calling this routine.
9812  *
9813  **/
9814 static void
9815 lpfc_destroy_bootstrap_mbox(struct lpfc_hba *phba)
9816 {
9817         dma_free_coherent(&phba->pcidev->dev,
9818                           phba->sli4_hba.bmbx.bmbx_size,
9819                           phba->sli4_hba.bmbx.dmabuf->virt,
9820                           phba->sli4_hba.bmbx.dmabuf->phys);
9821
9822         kfree(phba->sli4_hba.bmbx.dmabuf);
9823         memset(&phba->sli4_hba.bmbx, 0, sizeof(struct lpfc_bmbx));
9824 }
9825
9826 static const char * const lpfc_topo_to_str[] = {
9827         "Loop then P2P",
9828         "Loopback",
9829         "P2P Only",
9830         "Unsupported",
9831         "Loop Only",
9832         "Unsupported",
9833         "P2P then Loop",
9834 };
9835
9836 #define LINK_FLAGS_DEF  0x0
9837 #define LINK_FLAGS_P2P  0x1
9838 #define LINK_FLAGS_LOOP 0x2
9839 /**
9840  * lpfc_map_topology - Map the topology read from READ_CONFIG
9841  * @phba: pointer to lpfc hba data structure.
9842  * @rd_config: pointer to read config data
9843  *
9844  * This routine is invoked to map the topology values as read
9845  * from the read config mailbox command. If the persistent
9846  * topology feature is supported, the firmware will provide the
9847  * saved topology information to be used in INIT_LINK
9848  **/
9849 static void
9850 lpfc_map_topology(struct lpfc_hba *phba, struct lpfc_mbx_read_config *rd_config)
9851 {
9852         u8 ptv, tf, pt;
9853
9854         ptv = bf_get(lpfc_mbx_rd_conf_ptv, rd_config);
9855         tf = bf_get(lpfc_mbx_rd_conf_tf, rd_config);
9856         pt = bf_get(lpfc_mbx_rd_conf_pt, rd_config);
9857
9858         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9859                         "2027 Read Config Data : ptv:0x%x, tf:0x%x pt:0x%x",
9860                          ptv, tf, pt);
9861         if (!ptv) {
9862                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9863                                 "2019 FW does not support persistent topology "
9864                                 "Using driver parameter defined value [%s]",
9865                                 lpfc_topo_to_str[phba->cfg_topology]);
9866                 return;
9867         }
9868         /* FW supports persistent topology - override module parameter value */
9869         phba->hba_flag |= HBA_PERSISTENT_TOPO;
9870
9871         /* if ASIC_GEN_NUM >= 0xC) */
9872         if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
9873                     LPFC_SLI_INTF_IF_TYPE_6) ||
9874             (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
9875                     LPFC_SLI_INTF_FAMILY_G6)) {
9876                 if (!tf) {
9877                         phba->cfg_topology = ((pt == LINK_FLAGS_LOOP)
9878                                         ? FLAGS_TOPOLOGY_MODE_LOOP
9879                                         : FLAGS_TOPOLOGY_MODE_PT_PT);
9880                 } else {
9881                         phba->hba_flag &= ~HBA_PERSISTENT_TOPO;
9882                 }
9883         } else { /* G5 */
9884                 if (tf) {
9885                         /* If topology failover set - pt is '0' or '1' */
9886                         phba->cfg_topology = (pt ? FLAGS_TOPOLOGY_MODE_PT_LOOP :
9887                                               FLAGS_TOPOLOGY_MODE_LOOP_PT);
9888                 } else {
9889                         phba->cfg_topology = ((pt == LINK_FLAGS_P2P)
9890                                         ? FLAGS_TOPOLOGY_MODE_PT_PT
9891                                         : FLAGS_TOPOLOGY_MODE_LOOP);
9892                 }
9893         }
9894         if (phba->hba_flag & HBA_PERSISTENT_TOPO) {
9895                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9896                                 "2020 Using persistent topology value [%s]",
9897                                 lpfc_topo_to_str[phba->cfg_topology]);
9898         } else {
9899                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9900                                 "2021 Invalid topology values from FW "
9901                                 "Using driver parameter defined value [%s]",
9902                                 lpfc_topo_to_str[phba->cfg_topology]);
9903         }
9904 }
9905
9906 /**
9907  * lpfc_sli4_read_config - Get the config parameters.
9908  * @phba: pointer to lpfc hba data structure.
9909  *
9910  * This routine is invoked to read the configuration parameters from the HBA.
9911  * The configuration parameters are used to set the base and maximum values
9912  * for RPI's XRI's VPI's VFI's and FCFIs. These values also affect the resource
9913  * allocation for the port.
9914  *
9915  * Return codes
9916  *      0 - successful
9917  *      -ENOMEM - No available memory
9918  *      -EIO - The mailbox failed to complete successfully.
9919  **/
9920 int
9921 lpfc_sli4_read_config(struct lpfc_hba *phba)
9922 {
9923         LPFC_MBOXQ_t *pmb;
9924         struct lpfc_mbx_read_config *rd_config;
9925         union  lpfc_sli4_cfg_shdr *shdr;
9926         uint32_t shdr_status, shdr_add_status;
9927         struct lpfc_mbx_get_func_cfg *get_func_cfg;
9928         struct lpfc_rsrc_desc_fcfcoe *desc;
9929         char *pdesc_0;
9930         uint16_t forced_link_speed;
9931         uint32_t if_type, qmin, fawwpn;
9932         int length, i, rc = 0, rc2;
9933
9934         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9935         if (!pmb) {
9936                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9937                                 "2011 Unable to allocate memory for issuing "
9938                                 "SLI_CONFIG_SPECIAL mailbox command\n");
9939                 return -ENOMEM;
9940         }
9941
9942         lpfc_read_config(phba, pmb);
9943
9944         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
9945         if (rc != MBX_SUCCESS) {
9946                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9947                                 "2012 Mailbox failed , mbxCmd x%x "
9948                                 "READ_CONFIG, mbxStatus x%x\n",
9949                                 bf_get(lpfc_mqe_command, &pmb->u.mqe),
9950                                 bf_get(lpfc_mqe_status, &pmb->u.mqe));
9951                 rc = -EIO;
9952         } else {
9953                 rd_config = &pmb->u.mqe.un.rd_config;
9954                 if (bf_get(lpfc_mbx_rd_conf_lnk_ldv, rd_config)) {
9955                         phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
9956                         phba->sli4_hba.lnk_info.lnk_tp =
9957                                 bf_get(lpfc_mbx_rd_conf_lnk_type, rd_config);
9958                         phba->sli4_hba.lnk_info.lnk_no =
9959                                 bf_get(lpfc_mbx_rd_conf_lnk_numb, rd_config);
9960                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9961                                         "3081 lnk_type:%d, lnk_numb:%d\n",
9962                                         phba->sli4_hba.lnk_info.lnk_tp,
9963                                         phba->sli4_hba.lnk_info.lnk_no);
9964                 } else
9965                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9966                                         "3082 Mailbox (x%x) returned ldv:x0\n",
9967                                         bf_get(lpfc_mqe_command, &pmb->u.mqe));
9968                 if (bf_get(lpfc_mbx_rd_conf_bbscn_def, rd_config)) {
9969                         phba->bbcredit_support = 1;
9970                         phba->sli4_hba.bbscn_params.word0 = rd_config->word8;
9971                 }
9972
9973                 fawwpn = bf_get(lpfc_mbx_rd_conf_fawwpn, rd_config);
9974
9975                 if (fawwpn) {
9976                         lpfc_printf_log(phba, KERN_INFO,
9977                                         LOG_INIT | LOG_DISCOVERY,
9978                                         "2702 READ_CONFIG: FA-PWWN is "
9979                                         "configured on\n");
9980                         phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_CONFIG;
9981                 } else {
9982                         /* Clear FW configured flag, preserve driver flag */
9983                         phba->sli4_hba.fawwpn_flag &= ~LPFC_FAWWPN_CONFIG;
9984                 }
9985
9986                 phba->sli4_hba.conf_trunk =
9987                         bf_get(lpfc_mbx_rd_conf_trunk, rd_config);
9988                 phba->sli4_hba.extents_in_use =
9989                         bf_get(lpfc_mbx_rd_conf_extnts_inuse, rd_config);
9990
9991                 phba->sli4_hba.max_cfg_param.max_xri =
9992                         bf_get(lpfc_mbx_rd_conf_xri_count, rd_config);
9993                 /* Reduce resource usage in kdump environment */
9994                 if (is_kdump_kernel() &&
9995                     phba->sli4_hba.max_cfg_param.max_xri > 512)
9996                         phba->sli4_hba.max_cfg_param.max_xri = 512;
9997                 phba->sli4_hba.max_cfg_param.xri_base =
9998                         bf_get(lpfc_mbx_rd_conf_xri_base, rd_config);
9999                 phba->sli4_hba.max_cfg_param.max_vpi =
10000                         bf_get(lpfc_mbx_rd_conf_vpi_count, rd_config);
10001                 /* Limit the max we support */
10002                 if (phba->sli4_hba.max_cfg_param.max_vpi > LPFC_MAX_VPORTS)
10003                         phba->sli4_hba.max_cfg_param.max_vpi = LPFC_MAX_VPORTS;
10004                 phba->sli4_hba.max_cfg_param.vpi_base =
10005                         bf_get(lpfc_mbx_rd_conf_vpi_base, rd_config);
10006                 phba->sli4_hba.max_cfg_param.max_rpi =
10007                         bf_get(lpfc_mbx_rd_conf_rpi_count, rd_config);
10008                 phba->sli4_hba.max_cfg_param.rpi_base =
10009                         bf_get(lpfc_mbx_rd_conf_rpi_base, rd_config);
10010                 phba->sli4_hba.max_cfg_param.max_vfi =
10011                         bf_get(lpfc_mbx_rd_conf_vfi_count, rd_config);
10012                 phba->sli4_hba.max_cfg_param.vfi_base =
10013                         bf_get(lpfc_mbx_rd_conf_vfi_base, rd_config);
10014                 phba->sli4_hba.max_cfg_param.max_fcfi =
10015                         bf_get(lpfc_mbx_rd_conf_fcfi_count, rd_config);
10016                 phba->sli4_hba.max_cfg_param.max_eq =
10017                         bf_get(lpfc_mbx_rd_conf_eq_count, rd_config);
10018                 phba->sli4_hba.max_cfg_param.max_rq =
10019                         bf_get(lpfc_mbx_rd_conf_rq_count, rd_config);
10020                 phba->sli4_hba.max_cfg_param.max_wq =
10021                         bf_get(lpfc_mbx_rd_conf_wq_count, rd_config);
10022                 phba->sli4_hba.max_cfg_param.max_cq =
10023                         bf_get(lpfc_mbx_rd_conf_cq_count, rd_config);
10024                 phba->lmt = bf_get(lpfc_mbx_rd_conf_lmt, rd_config);
10025                 phba->sli4_hba.next_xri = phba->sli4_hba.max_cfg_param.xri_base;
10026                 phba->vpi_base = phba->sli4_hba.max_cfg_param.vpi_base;
10027                 phba->vfi_base = phba->sli4_hba.max_cfg_param.vfi_base;
10028                 phba->max_vpi = (phba->sli4_hba.max_cfg_param.max_vpi > 0) ?
10029                                 (phba->sli4_hba.max_cfg_param.max_vpi - 1) : 0;
10030                 phba->max_vports = phba->max_vpi;
10031
10032                 /* Next decide on FPIN or Signal E2E CGN support
10033                  * For congestion alarms and warnings valid combination are:
10034                  * 1. FPIN alarms / FPIN warnings
10035                  * 2. Signal alarms / Signal warnings
10036                  * 3. FPIN alarms / Signal warnings
10037                  * 4. Signal alarms / FPIN warnings
10038                  *
10039                  * Initialize the adapter frequency to 100 mSecs
10040                  */
10041                 phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10042                 phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
10043                 phba->cgn_sig_freq = lpfc_fabric_cgn_frequency;
10044
10045                 if (lpfc_use_cgn_signal) {
10046                         if (bf_get(lpfc_mbx_rd_conf_wcs, rd_config)) {
10047                                 phba->cgn_reg_signal = EDC_CG_SIG_WARN_ONLY;
10048                                 phba->cgn_reg_fpin &= ~LPFC_CGN_FPIN_WARN;
10049                         }
10050                         if (bf_get(lpfc_mbx_rd_conf_acs, rd_config)) {
10051                                 /* MUST support both alarm and warning
10052                                  * because EDC does not support alarm alone.
10053                                  */
10054                                 if (phba->cgn_reg_signal !=
10055                                     EDC_CG_SIG_WARN_ONLY) {
10056                                         /* Must support both or none */
10057                                         phba->cgn_reg_fpin = LPFC_CGN_FPIN_BOTH;
10058                                         phba->cgn_reg_signal =
10059                                                 EDC_CG_SIG_NOTSUPPORTED;
10060                                 } else {
10061                                         phba->cgn_reg_signal =
10062                                                 EDC_CG_SIG_WARN_ALARM;
10063                                         phba->cgn_reg_fpin =
10064                                                 LPFC_CGN_FPIN_NONE;
10065                                 }
10066                         }
10067                 }
10068
10069                 /* Set the congestion initial signal and fpin values. */
10070                 phba->cgn_init_reg_fpin = phba->cgn_reg_fpin;
10071                 phba->cgn_init_reg_signal = phba->cgn_reg_signal;
10072
10073                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
10074                                 "6446 READ_CONFIG reg_sig x%x reg_fpin:x%x\n",
10075                                 phba->cgn_reg_signal, phba->cgn_reg_fpin);
10076
10077                 lpfc_map_topology(phba, rd_config);
10078                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10079                                 "2003 cfg params Extents? %d "
10080                                 "XRI(B:%d M:%d), "
10081                                 "VPI(B:%d M:%d) "
10082                                 "VFI(B:%d M:%d) "
10083                                 "RPI(B:%d M:%d) "
10084                                 "FCFI:%d EQ:%d CQ:%d WQ:%d RQ:%d lmt:x%x\n",
10085                                 phba->sli4_hba.extents_in_use,
10086                                 phba->sli4_hba.max_cfg_param.xri_base,
10087                                 phba->sli4_hba.max_cfg_param.max_xri,
10088                                 phba->sli4_hba.max_cfg_param.vpi_base,
10089                                 phba->sli4_hba.max_cfg_param.max_vpi,
10090                                 phba->sli4_hba.max_cfg_param.vfi_base,
10091                                 phba->sli4_hba.max_cfg_param.max_vfi,
10092                                 phba->sli4_hba.max_cfg_param.rpi_base,
10093                                 phba->sli4_hba.max_cfg_param.max_rpi,
10094                                 phba->sli4_hba.max_cfg_param.max_fcfi,
10095                                 phba->sli4_hba.max_cfg_param.max_eq,
10096                                 phba->sli4_hba.max_cfg_param.max_cq,
10097                                 phba->sli4_hba.max_cfg_param.max_wq,
10098                                 phba->sli4_hba.max_cfg_param.max_rq,
10099                                 phba->lmt);
10100
10101                 /*
10102                  * Calculate queue resources based on how
10103                  * many WQ/CQ/EQs are available.
10104                  */
10105                 qmin = phba->sli4_hba.max_cfg_param.max_wq;
10106                 if (phba->sli4_hba.max_cfg_param.max_cq < qmin)
10107                         qmin = phba->sli4_hba.max_cfg_param.max_cq;
10108                 /*
10109                  * Reserve 4 (ELS, NVME LS, MBOX, plus one extra) and
10110                  * the remainder can be used for NVME / FCP.
10111                  */
10112                 qmin -= 4;
10113                 if (phba->sli4_hba.max_cfg_param.max_eq < qmin)
10114                         qmin = phba->sli4_hba.max_cfg_param.max_eq;
10115
10116                 /* Check to see if there is enough for default cfg */
10117                 if ((phba->cfg_irq_chann > qmin) ||
10118                     (phba->cfg_hdw_queue > qmin)) {
10119                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10120                                         "2005 Reducing Queues - "
10121                                         "FW resource limitation: "
10122                                         "WQ %d CQ %d EQ %d: min %d: "
10123                                         "IRQ %d HDWQ %d\n",
10124                                         phba->sli4_hba.max_cfg_param.max_wq,
10125                                         phba->sli4_hba.max_cfg_param.max_cq,
10126                                         phba->sli4_hba.max_cfg_param.max_eq,
10127                                         qmin, phba->cfg_irq_chann,
10128                                         phba->cfg_hdw_queue);
10129
10130                         if (phba->cfg_irq_chann > qmin)
10131                                 phba->cfg_irq_chann = qmin;
10132                         if (phba->cfg_hdw_queue > qmin)
10133                                 phba->cfg_hdw_queue = qmin;
10134                 }
10135         }
10136
10137         if (rc)
10138                 goto read_cfg_out;
10139
10140         /* Update link speed if forced link speed is supported */
10141         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10142         if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10143                 forced_link_speed =
10144                         bf_get(lpfc_mbx_rd_conf_link_speed, rd_config);
10145                 if (forced_link_speed) {
10146                         phba->hba_flag |= HBA_FORCED_LINK_SPEED;
10147
10148                         switch (forced_link_speed) {
10149                         case LINK_SPEED_1G:
10150                                 phba->cfg_link_speed =
10151                                         LPFC_USER_LINK_SPEED_1G;
10152                                 break;
10153                         case LINK_SPEED_2G:
10154                                 phba->cfg_link_speed =
10155                                         LPFC_USER_LINK_SPEED_2G;
10156                                 break;
10157                         case LINK_SPEED_4G:
10158                                 phba->cfg_link_speed =
10159                                         LPFC_USER_LINK_SPEED_4G;
10160                                 break;
10161                         case LINK_SPEED_8G:
10162                                 phba->cfg_link_speed =
10163                                         LPFC_USER_LINK_SPEED_8G;
10164                                 break;
10165                         case LINK_SPEED_10G:
10166                                 phba->cfg_link_speed =
10167                                         LPFC_USER_LINK_SPEED_10G;
10168                                 break;
10169                         case LINK_SPEED_16G:
10170                                 phba->cfg_link_speed =
10171                                         LPFC_USER_LINK_SPEED_16G;
10172                                 break;
10173                         case LINK_SPEED_32G:
10174                                 phba->cfg_link_speed =
10175                                         LPFC_USER_LINK_SPEED_32G;
10176                                 break;
10177                         case LINK_SPEED_64G:
10178                                 phba->cfg_link_speed =
10179                                         LPFC_USER_LINK_SPEED_64G;
10180                                 break;
10181                         case 0xffff:
10182                                 phba->cfg_link_speed =
10183                                         LPFC_USER_LINK_SPEED_AUTO;
10184                                 break;
10185                         default:
10186                                 lpfc_printf_log(phba, KERN_ERR,
10187                                                 LOG_TRACE_EVENT,
10188                                                 "0047 Unrecognized link "
10189                                                 "speed : %d\n",
10190                                                 forced_link_speed);
10191                                 phba->cfg_link_speed =
10192                                         LPFC_USER_LINK_SPEED_AUTO;
10193                         }
10194                 }
10195         }
10196
10197         /* Reset the DFT_HBA_Q_DEPTH to the max xri  */
10198         length = phba->sli4_hba.max_cfg_param.max_xri -
10199                         lpfc_sli4_get_els_iocb_cnt(phba);
10200         if (phba->cfg_hba_queue_depth > length) {
10201                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10202                                 "3361 HBA queue depth changed from %d to %d\n",
10203                                 phba->cfg_hba_queue_depth, length);
10204                 phba->cfg_hba_queue_depth = length;
10205         }
10206
10207         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
10208             LPFC_SLI_INTF_IF_TYPE_2)
10209                 goto read_cfg_out;
10210
10211         /* get the pf# and vf# for SLI4 if_type 2 port */
10212         length = (sizeof(struct lpfc_mbx_get_func_cfg) -
10213                   sizeof(struct lpfc_sli4_cfg_mhdr));
10214         lpfc_sli4_config(phba, pmb, LPFC_MBOX_SUBSYSTEM_COMMON,
10215                          LPFC_MBOX_OPCODE_GET_FUNCTION_CONFIG,
10216                          length, LPFC_SLI4_MBX_EMBED);
10217
10218         rc2 = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
10219         shdr = (union lpfc_sli4_cfg_shdr *)
10220                                 &pmb->u.mqe.un.sli4_config.header.cfg_shdr;
10221         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10222         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10223         if (rc2 || shdr_status || shdr_add_status) {
10224                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10225                                 "3026 Mailbox failed , mbxCmd x%x "
10226                                 "GET_FUNCTION_CONFIG, mbxStatus x%x\n",
10227                                 bf_get(lpfc_mqe_command, &pmb->u.mqe),
10228                                 bf_get(lpfc_mqe_status, &pmb->u.mqe));
10229                 goto read_cfg_out;
10230         }
10231
10232         /* search for fc_fcoe resrouce descriptor */
10233         get_func_cfg = &pmb->u.mqe.un.get_func_cfg;
10234
10235         pdesc_0 = (char *)&get_func_cfg->func_cfg.desc[0];
10236         desc = (struct lpfc_rsrc_desc_fcfcoe *)pdesc_0;
10237         length = bf_get(lpfc_rsrc_desc_fcfcoe_length, desc);
10238         if (length == LPFC_RSRC_DESC_TYPE_FCFCOE_V0_RSVD)
10239                 length = LPFC_RSRC_DESC_TYPE_FCFCOE_V0_LENGTH;
10240         else if (length != LPFC_RSRC_DESC_TYPE_FCFCOE_V1_LENGTH)
10241                 goto read_cfg_out;
10242
10243         for (i = 0; i < LPFC_RSRC_DESC_MAX_NUM; i++) {
10244                 desc = (struct lpfc_rsrc_desc_fcfcoe *)(pdesc_0 + length * i);
10245                 if (LPFC_RSRC_DESC_TYPE_FCFCOE ==
10246                     bf_get(lpfc_rsrc_desc_fcfcoe_type, desc)) {
10247                         phba->sli4_hba.iov.pf_number =
10248                                 bf_get(lpfc_rsrc_desc_fcfcoe_pfnum, desc);
10249                         phba->sli4_hba.iov.vf_number =
10250                                 bf_get(lpfc_rsrc_desc_fcfcoe_vfnum, desc);
10251                         break;
10252                 }
10253         }
10254
10255         if (i < LPFC_RSRC_DESC_MAX_NUM)
10256                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10257                                 "3027 GET_FUNCTION_CONFIG: pf_number:%d, "
10258                                 "vf_number:%d\n", phba->sli4_hba.iov.pf_number,
10259                                 phba->sli4_hba.iov.vf_number);
10260         else
10261                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10262                                 "3028 GET_FUNCTION_CONFIG: failed to find "
10263                                 "Resource Descriptor:x%x\n",
10264                                 LPFC_RSRC_DESC_TYPE_FCFCOE);
10265
10266 read_cfg_out:
10267         mempool_free(pmb, phba->mbox_mem_pool);
10268         return rc;
10269 }
10270
10271 /**
10272  * lpfc_setup_endian_order - Write endian order to an SLI4 if_type 0 port.
10273  * @phba: pointer to lpfc hba data structure.
10274  *
10275  * This routine is invoked to setup the port-side endian order when
10276  * the port if_type is 0.  This routine has no function for other
10277  * if_types.
10278  *
10279  * Return codes
10280  *      0 - successful
10281  *      -ENOMEM - No available memory
10282  *      -EIO - The mailbox failed to complete successfully.
10283  **/
10284 static int
10285 lpfc_setup_endian_order(struct lpfc_hba *phba)
10286 {
10287         LPFC_MBOXQ_t *mboxq;
10288         uint32_t if_type, rc = 0;
10289         uint32_t endian_mb_data[2] = {HOST_ENDIAN_LOW_WORD0,
10290                                       HOST_ENDIAN_HIGH_WORD1};
10291
10292         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10293         switch (if_type) {
10294         case LPFC_SLI_INTF_IF_TYPE_0:
10295                 mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
10296                                                        GFP_KERNEL);
10297                 if (!mboxq) {
10298                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10299                                         "0492 Unable to allocate memory for "
10300                                         "issuing SLI_CONFIG_SPECIAL mailbox "
10301                                         "command\n");
10302                         return -ENOMEM;
10303                 }
10304
10305                 /*
10306                  * The SLI4_CONFIG_SPECIAL mailbox command requires the first
10307                  * two words to contain special data values and no other data.
10308                  */
10309                 memset(mboxq, 0, sizeof(LPFC_MBOXQ_t));
10310                 memcpy(&mboxq->u.mqe, &endian_mb_data, sizeof(endian_mb_data));
10311                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
10312                 if (rc != MBX_SUCCESS) {
10313                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10314                                         "0493 SLI_CONFIG_SPECIAL mailbox "
10315                                         "failed with status x%x\n",
10316                                         rc);
10317                         rc = -EIO;
10318                 }
10319                 mempool_free(mboxq, phba->mbox_mem_pool);
10320                 break;
10321         case LPFC_SLI_INTF_IF_TYPE_6:
10322         case LPFC_SLI_INTF_IF_TYPE_2:
10323         case LPFC_SLI_INTF_IF_TYPE_1:
10324         default:
10325                 break;
10326         }
10327         return rc;
10328 }
10329
10330 /**
10331  * lpfc_sli4_queue_verify - Verify and update EQ counts
10332  * @phba: pointer to lpfc hba data structure.
10333  *
10334  * This routine is invoked to check the user settable queue counts for EQs.
10335  * After this routine is called the counts will be set to valid values that
10336  * adhere to the constraints of the system's interrupt vectors and the port's
10337  * queue resources.
10338  *
10339  * Return codes
10340  *      0 - successful
10341  *      -ENOMEM - No available memory
10342  **/
10343 static int
10344 lpfc_sli4_queue_verify(struct lpfc_hba *phba)
10345 {
10346         /*
10347          * Sanity check for configured queue parameters against the run-time
10348          * device parameters
10349          */
10350
10351         if (phba->nvmet_support) {
10352                 if (phba->cfg_hdw_queue < phba->cfg_nvmet_mrq)
10353                         phba->cfg_nvmet_mrq = phba->cfg_hdw_queue;
10354                 if (phba->cfg_nvmet_mrq > LPFC_NVMET_MRQ_MAX)
10355                         phba->cfg_nvmet_mrq = LPFC_NVMET_MRQ_MAX;
10356         }
10357
10358         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10359                         "2574 IO channels: hdwQ %d IRQ %d MRQ: %d\n",
10360                         phba->cfg_hdw_queue, phba->cfg_irq_chann,
10361                         phba->cfg_nvmet_mrq);
10362
10363         /* Get EQ depth from module parameter, fake the default for now */
10364         phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10365         phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10366
10367         /* Get CQ depth from module parameter, fake the default for now */
10368         phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10369         phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10370         return 0;
10371 }
10372
10373 static int
10374 lpfc_alloc_io_wq_cq(struct lpfc_hba *phba, int idx)
10375 {
10376         struct lpfc_queue *qdesc;
10377         u32 wqesize;
10378         int cpu;
10379
10380         cpu = lpfc_find_cpu_handle(phba, idx, LPFC_FIND_BY_HDWQ);
10381         /* Create Fast Path IO CQs */
10382         if (phba->enab_exp_wqcq_pages)
10383                 /* Increase the CQ size when WQEs contain an embedded cdb */
10384                 qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10385                                               phba->sli4_hba.cq_esize,
10386                                               LPFC_CQE_EXP_COUNT, cpu);
10387
10388         else
10389                 qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10390                                               phba->sli4_hba.cq_esize,
10391                                               phba->sli4_hba.cq_ecount, cpu);
10392         if (!qdesc) {
10393                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10394                                 "0499 Failed allocate fast-path IO CQ (%d)\n",
10395                                 idx);
10396                 return 1;
10397         }
10398         qdesc->qe_valid = 1;
10399         qdesc->hdwq = idx;
10400         qdesc->chann = cpu;
10401         phba->sli4_hba.hdwq[idx].io_cq = qdesc;
10402
10403         /* Create Fast Path IO WQs */
10404         if (phba->enab_exp_wqcq_pages) {
10405                 /* Increase the WQ size when WQEs contain an embedded cdb */
10406                 wqesize = (phba->fcp_embed_io) ?
10407                         LPFC_WQE128_SIZE : phba->sli4_hba.wq_esize;
10408                 qdesc = lpfc_sli4_queue_alloc(phba, LPFC_EXPANDED_PAGE_SIZE,
10409                                               wqesize,
10410                                               LPFC_WQE_EXP_COUNT, cpu);
10411         } else
10412                 qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10413                                               phba->sli4_hba.wq_esize,
10414                                               phba->sli4_hba.wq_ecount, cpu);
10415
10416         if (!qdesc) {
10417                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10418                                 "0503 Failed allocate fast-path IO WQ (%d)\n",
10419                                 idx);
10420                 return 1;
10421         }
10422         qdesc->hdwq = idx;
10423         qdesc->chann = cpu;
10424         phba->sli4_hba.hdwq[idx].io_wq = qdesc;
10425         list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10426         return 0;
10427 }
10428
10429 /**
10430  * lpfc_sli4_queue_create - Create all the SLI4 queues
10431  * @phba: pointer to lpfc hba data structure.
10432  *
10433  * This routine is invoked to allocate all the SLI4 queues for the FCoE HBA
10434  * operation. For each SLI4 queue type, the parameters such as queue entry
10435  * count (queue depth) shall be taken from the module parameter. For now,
10436  * we just use some constant number as place holder.
10437  *
10438  * Return codes
10439  *      0 - successful
10440  *      -ENOMEM - No availble memory
10441  *      -EIO - The mailbox failed to complete successfully.
10442  **/
10443 int
10444 lpfc_sli4_queue_create(struct lpfc_hba *phba)
10445 {
10446         struct lpfc_queue *qdesc;
10447         int idx, cpu, eqcpu;
10448         struct lpfc_sli4_hdw_queue *qp;
10449         struct lpfc_vector_map_info *cpup;
10450         struct lpfc_vector_map_info *eqcpup;
10451         struct lpfc_eq_intr_info *eqi;
10452
10453         /*
10454          * Create HBA Record arrays.
10455          * Both NVME and FCP will share that same vectors / EQs
10456          */
10457         phba->sli4_hba.mq_esize = LPFC_MQE_SIZE;
10458         phba->sli4_hba.mq_ecount = LPFC_MQE_DEF_COUNT;
10459         phba->sli4_hba.wq_esize = LPFC_WQE_SIZE;
10460         phba->sli4_hba.wq_ecount = LPFC_WQE_DEF_COUNT;
10461         phba->sli4_hba.rq_esize = LPFC_RQE_SIZE;
10462         phba->sli4_hba.rq_ecount = LPFC_RQE_DEF_COUNT;
10463         phba->sli4_hba.eq_esize = LPFC_EQE_SIZE_4B;
10464         phba->sli4_hba.eq_ecount = LPFC_EQE_DEF_COUNT;
10465         phba->sli4_hba.cq_esize = LPFC_CQE_SIZE;
10466         phba->sli4_hba.cq_ecount = LPFC_CQE_DEF_COUNT;
10467
10468         if (!phba->sli4_hba.hdwq) {
10469                 phba->sli4_hba.hdwq = kcalloc(
10470                         phba->cfg_hdw_queue, sizeof(struct lpfc_sli4_hdw_queue),
10471                         GFP_KERNEL);
10472                 if (!phba->sli4_hba.hdwq) {
10473                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10474                                         "6427 Failed allocate memory for "
10475                                         "fast-path Hardware Queue array\n");
10476                         goto out_error;
10477                 }
10478                 /* Prepare hardware queues to take IO buffers */
10479                 for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10480                         qp = &phba->sli4_hba.hdwq[idx];
10481                         spin_lock_init(&qp->io_buf_list_get_lock);
10482                         spin_lock_init(&qp->io_buf_list_put_lock);
10483                         INIT_LIST_HEAD(&qp->lpfc_io_buf_list_get);
10484                         INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
10485                         qp->get_io_bufs = 0;
10486                         qp->put_io_bufs = 0;
10487                         qp->total_io_bufs = 0;
10488                         spin_lock_init(&qp->abts_io_buf_list_lock);
10489                         INIT_LIST_HEAD(&qp->lpfc_abts_io_buf_list);
10490                         qp->abts_scsi_io_bufs = 0;
10491                         qp->abts_nvme_io_bufs = 0;
10492                         INIT_LIST_HEAD(&qp->sgl_list);
10493                         INIT_LIST_HEAD(&qp->cmd_rsp_buf_list);
10494                         spin_lock_init(&qp->hdwq_lock);
10495                 }
10496         }
10497
10498         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10499                 if (phba->nvmet_support) {
10500                         phba->sli4_hba.nvmet_cqset = kcalloc(
10501                                         phba->cfg_nvmet_mrq,
10502                                         sizeof(struct lpfc_queue *),
10503                                         GFP_KERNEL);
10504                         if (!phba->sli4_hba.nvmet_cqset) {
10505                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10506                                         "3121 Fail allocate memory for "
10507                                         "fast-path CQ set array\n");
10508                                 goto out_error;
10509                         }
10510                         phba->sli4_hba.nvmet_mrq_hdr = kcalloc(
10511                                         phba->cfg_nvmet_mrq,
10512                                         sizeof(struct lpfc_queue *),
10513                                         GFP_KERNEL);
10514                         if (!phba->sli4_hba.nvmet_mrq_hdr) {
10515                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10516                                         "3122 Fail allocate memory for "
10517                                         "fast-path RQ set hdr array\n");
10518                                 goto out_error;
10519                         }
10520                         phba->sli4_hba.nvmet_mrq_data = kcalloc(
10521                                         phba->cfg_nvmet_mrq,
10522                                         sizeof(struct lpfc_queue *),
10523                                         GFP_KERNEL);
10524                         if (!phba->sli4_hba.nvmet_mrq_data) {
10525                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10526                                         "3124 Fail allocate memory for "
10527                                         "fast-path RQ set data array\n");
10528                                 goto out_error;
10529                         }
10530                 }
10531         }
10532
10533         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10534
10535         /* Create HBA Event Queues (EQs) */
10536         for_each_present_cpu(cpu) {
10537                 /* We only want to create 1 EQ per vector, even though
10538                  * multiple CPUs might be using that vector. so only
10539                  * selects the CPUs that are LPFC_CPU_FIRST_IRQ.
10540                  */
10541                 cpup = &phba->sli4_hba.cpu_map[cpu];
10542                 if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
10543                         continue;
10544
10545                 /* Get a ptr to the Hardware Queue associated with this CPU */
10546                 qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10547
10548                 /* Allocate an EQ */
10549                 qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10550                                               phba->sli4_hba.eq_esize,
10551                                               phba->sli4_hba.eq_ecount, cpu);
10552                 if (!qdesc) {
10553                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10554                                         "0497 Failed allocate EQ (%d)\n",
10555                                         cpup->hdwq);
10556                         goto out_error;
10557                 }
10558                 qdesc->qe_valid = 1;
10559                 qdesc->hdwq = cpup->hdwq;
10560                 qdesc->chann = cpu; /* First CPU this EQ is affinitized to */
10561                 qdesc->last_cpu = qdesc->chann;
10562
10563                 /* Save the allocated EQ in the Hardware Queue */
10564                 qp->hba_eq = qdesc;
10565
10566                 eqi = per_cpu_ptr(phba->sli4_hba.eq_info, qdesc->last_cpu);
10567                 list_add(&qdesc->cpu_list, &eqi->list);
10568         }
10569
10570         /* Now we need to populate the other Hardware Queues, that share
10571          * an IRQ vector, with the associated EQ ptr.
10572          */
10573         for_each_present_cpu(cpu) {
10574                 cpup = &phba->sli4_hba.cpu_map[cpu];
10575
10576                 /* Check for EQ already allocated in previous loop */
10577                 if (cpup->flag & LPFC_CPU_FIRST_IRQ)
10578                         continue;
10579
10580                 /* Check for multiple CPUs per hdwq */
10581                 qp = &phba->sli4_hba.hdwq[cpup->hdwq];
10582                 if (qp->hba_eq)
10583                         continue;
10584
10585                 /* We need to share an EQ for this hdwq */
10586                 eqcpu = lpfc_find_cpu_handle(phba, cpup->eq, LPFC_FIND_BY_EQ);
10587                 eqcpup = &phba->sli4_hba.cpu_map[eqcpu];
10588                 qp->hba_eq = phba->sli4_hba.hdwq[eqcpup->hdwq].hba_eq;
10589         }
10590
10591         /* Allocate IO Path SLI4 CQ/WQs */
10592         for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10593                 if (lpfc_alloc_io_wq_cq(phba, idx))
10594                         goto out_error;
10595         }
10596
10597         if (phba->nvmet_support) {
10598                 for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10599                         cpu = lpfc_find_cpu_handle(phba, idx,
10600                                                    LPFC_FIND_BY_HDWQ);
10601                         qdesc = lpfc_sli4_queue_alloc(phba,
10602                                                       LPFC_DEFAULT_PAGE_SIZE,
10603                                                       phba->sli4_hba.cq_esize,
10604                                                       phba->sli4_hba.cq_ecount,
10605                                                       cpu);
10606                         if (!qdesc) {
10607                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10608                                                 "3142 Failed allocate NVME "
10609                                                 "CQ Set (%d)\n", idx);
10610                                 goto out_error;
10611                         }
10612                         qdesc->qe_valid = 1;
10613                         qdesc->hdwq = idx;
10614                         qdesc->chann = cpu;
10615                         phba->sli4_hba.nvmet_cqset[idx] = qdesc;
10616                 }
10617         }
10618
10619         /*
10620          * Create Slow Path Completion Queues (CQs)
10621          */
10622
10623         cpu = lpfc_find_cpu_handle(phba, 0, LPFC_FIND_BY_EQ);
10624         /* Create slow-path Mailbox Command Complete Queue */
10625         qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10626                                       phba->sli4_hba.cq_esize,
10627                                       phba->sli4_hba.cq_ecount, cpu);
10628         if (!qdesc) {
10629                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10630                                 "0500 Failed allocate slow-path mailbox CQ\n");
10631                 goto out_error;
10632         }
10633         qdesc->qe_valid = 1;
10634         phba->sli4_hba.mbx_cq = qdesc;
10635
10636         /* Create slow-path ELS Complete Queue */
10637         qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10638                                       phba->sli4_hba.cq_esize,
10639                                       phba->sli4_hba.cq_ecount, cpu);
10640         if (!qdesc) {
10641                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10642                                 "0501 Failed allocate slow-path ELS CQ\n");
10643                 goto out_error;
10644         }
10645         qdesc->qe_valid = 1;
10646         qdesc->chann = cpu;
10647         phba->sli4_hba.els_cq = qdesc;
10648
10649
10650         /*
10651          * Create Slow Path Work Queues (WQs)
10652          */
10653
10654         /* Create Mailbox Command Queue */
10655
10656         qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10657                                       phba->sli4_hba.mq_esize,
10658                                       phba->sli4_hba.mq_ecount, cpu);
10659         if (!qdesc) {
10660                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10661                                 "0505 Failed allocate slow-path MQ\n");
10662                 goto out_error;
10663         }
10664         qdesc->chann = cpu;
10665         phba->sli4_hba.mbx_wq = qdesc;
10666
10667         /*
10668          * Create ELS Work Queues
10669          */
10670
10671         /* Create slow-path ELS Work Queue */
10672         qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10673                                       phba->sli4_hba.wq_esize,
10674                                       phba->sli4_hba.wq_ecount, cpu);
10675         if (!qdesc) {
10676                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10677                                 "0504 Failed allocate slow-path ELS WQ\n");
10678                 goto out_error;
10679         }
10680         qdesc->chann = cpu;
10681         phba->sli4_hba.els_wq = qdesc;
10682         list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10683
10684         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10685                 /* Create NVME LS Complete Queue */
10686                 qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10687                                               phba->sli4_hba.cq_esize,
10688                                               phba->sli4_hba.cq_ecount, cpu);
10689                 if (!qdesc) {
10690                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10691                                         "6079 Failed allocate NVME LS CQ\n");
10692                         goto out_error;
10693                 }
10694                 qdesc->chann = cpu;
10695                 qdesc->qe_valid = 1;
10696                 phba->sli4_hba.nvmels_cq = qdesc;
10697
10698                 /* Create NVME LS Work Queue */
10699                 qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10700                                               phba->sli4_hba.wq_esize,
10701                                               phba->sli4_hba.wq_ecount, cpu);
10702                 if (!qdesc) {
10703                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10704                                         "6080 Failed allocate NVME LS WQ\n");
10705                         goto out_error;
10706                 }
10707                 qdesc->chann = cpu;
10708                 phba->sli4_hba.nvmels_wq = qdesc;
10709                 list_add_tail(&qdesc->wq_list, &phba->sli4_hba.lpfc_wq_list);
10710         }
10711
10712         /*
10713          * Create Receive Queue (RQ)
10714          */
10715
10716         /* Create Receive Queue for header */
10717         qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10718                                       phba->sli4_hba.rq_esize,
10719                                       phba->sli4_hba.rq_ecount, cpu);
10720         if (!qdesc) {
10721                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10722                                 "0506 Failed allocate receive HRQ\n");
10723                 goto out_error;
10724         }
10725         phba->sli4_hba.hdr_rq = qdesc;
10726
10727         /* Create Receive Queue for data */
10728         qdesc = lpfc_sli4_queue_alloc(phba, LPFC_DEFAULT_PAGE_SIZE,
10729                                       phba->sli4_hba.rq_esize,
10730                                       phba->sli4_hba.rq_ecount, cpu);
10731         if (!qdesc) {
10732                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10733                                 "0507 Failed allocate receive DRQ\n");
10734                 goto out_error;
10735         }
10736         phba->sli4_hba.dat_rq = qdesc;
10737
10738         if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
10739             phba->nvmet_support) {
10740                 for (idx = 0; idx < phba->cfg_nvmet_mrq; idx++) {
10741                         cpu = lpfc_find_cpu_handle(phba, idx,
10742                                                    LPFC_FIND_BY_HDWQ);
10743                         /* Create NVMET Receive Queue for header */
10744                         qdesc = lpfc_sli4_queue_alloc(phba,
10745                                                       LPFC_DEFAULT_PAGE_SIZE,
10746                                                       phba->sli4_hba.rq_esize,
10747                                                       LPFC_NVMET_RQE_DEF_COUNT,
10748                                                       cpu);
10749                         if (!qdesc) {
10750                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10751                                                 "3146 Failed allocate "
10752                                                 "receive HRQ\n");
10753                                 goto out_error;
10754                         }
10755                         qdesc->hdwq = idx;
10756                         phba->sli4_hba.nvmet_mrq_hdr[idx] = qdesc;
10757
10758                         /* Only needed for header of RQ pair */
10759                         qdesc->rqbp = kzalloc_node(sizeof(*qdesc->rqbp),
10760                                                    GFP_KERNEL,
10761                                                    cpu_to_node(cpu));
10762                         if (qdesc->rqbp == NULL) {
10763                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10764                                                 "6131 Failed allocate "
10765                                                 "Header RQBP\n");
10766                                 goto out_error;
10767                         }
10768
10769                         /* Put list in known state in case driver load fails. */
10770                         INIT_LIST_HEAD(&qdesc->rqbp->rqb_buffer_list);
10771
10772                         /* Create NVMET Receive Queue for data */
10773                         qdesc = lpfc_sli4_queue_alloc(phba,
10774                                                       LPFC_DEFAULT_PAGE_SIZE,
10775                                                       phba->sli4_hba.rq_esize,
10776                                                       LPFC_NVMET_RQE_DEF_COUNT,
10777                                                       cpu);
10778                         if (!qdesc) {
10779                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10780                                                 "3156 Failed allocate "
10781                                                 "receive DRQ\n");
10782                                 goto out_error;
10783                         }
10784                         qdesc->hdwq = idx;
10785                         phba->sli4_hba.nvmet_mrq_data[idx] = qdesc;
10786                 }
10787         }
10788
10789         /* Clear NVME stats */
10790         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10791                 for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10792                         memset(&phba->sli4_hba.hdwq[idx].nvme_cstat, 0,
10793                                sizeof(phba->sli4_hba.hdwq[idx].nvme_cstat));
10794                 }
10795         }
10796
10797         /* Clear SCSI stats */
10798         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
10799                 for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10800                         memset(&phba->sli4_hba.hdwq[idx].scsi_cstat, 0,
10801                                sizeof(phba->sli4_hba.hdwq[idx].scsi_cstat));
10802                 }
10803         }
10804
10805         return 0;
10806
10807 out_error:
10808         lpfc_sli4_queue_destroy(phba);
10809         return -ENOMEM;
10810 }
10811
10812 static inline void
10813 __lpfc_sli4_release_queue(struct lpfc_queue **qp)
10814 {
10815         if (*qp != NULL) {
10816                 lpfc_sli4_queue_free(*qp);
10817                 *qp = NULL;
10818         }
10819 }
10820
10821 static inline void
10822 lpfc_sli4_release_queues(struct lpfc_queue ***qs, int max)
10823 {
10824         int idx;
10825
10826         if (*qs == NULL)
10827                 return;
10828
10829         for (idx = 0; idx < max; idx++)
10830                 __lpfc_sli4_release_queue(&(*qs)[idx]);
10831
10832         kfree(*qs);
10833         *qs = NULL;
10834 }
10835
10836 static inline void
10837 lpfc_sli4_release_hdwq(struct lpfc_hba *phba)
10838 {
10839         struct lpfc_sli4_hdw_queue *hdwq;
10840         struct lpfc_queue *eq;
10841         uint32_t idx;
10842
10843         hdwq = phba->sli4_hba.hdwq;
10844
10845         /* Loop thru all Hardware Queues */
10846         for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
10847                 /* Free the CQ/WQ corresponding to the Hardware Queue */
10848                 lpfc_sli4_queue_free(hdwq[idx].io_cq);
10849                 lpfc_sli4_queue_free(hdwq[idx].io_wq);
10850                 hdwq[idx].hba_eq = NULL;
10851                 hdwq[idx].io_cq = NULL;
10852                 hdwq[idx].io_wq = NULL;
10853                 if (phba->cfg_xpsgl && !phba->nvmet_support)
10854                         lpfc_free_sgl_per_hdwq(phba, &hdwq[idx]);
10855                 lpfc_free_cmd_rsp_buf_per_hdwq(phba, &hdwq[idx]);
10856         }
10857         /* Loop thru all IRQ vectors */
10858         for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
10859                 /* Free the EQ corresponding to the IRQ vector */
10860                 eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
10861                 lpfc_sli4_queue_free(eq);
10862                 phba->sli4_hba.hba_eq_hdl[idx].eq = NULL;
10863         }
10864 }
10865
10866 /**
10867  * lpfc_sli4_queue_destroy - Destroy all the SLI4 queues
10868  * @phba: pointer to lpfc hba data structure.
10869  *
10870  * This routine is invoked to release all the SLI4 queues with the FCoE HBA
10871  * operation.
10872  *
10873  * Return codes
10874  *      0 - successful
10875  *      -ENOMEM - No available memory
10876  *      -EIO - The mailbox failed to complete successfully.
10877  **/
10878 void
10879 lpfc_sli4_queue_destroy(struct lpfc_hba *phba)
10880 {
10881         /*
10882          * Set FREE_INIT before beginning to free the queues.
10883          * Wait until the users of queues to acknowledge to
10884          * release queues by clearing FREE_WAIT.
10885          */
10886         spin_lock_irq(&phba->hbalock);
10887         phba->sli.sli_flag |= LPFC_QUEUE_FREE_INIT;
10888         while (phba->sli.sli_flag & LPFC_QUEUE_FREE_WAIT) {
10889                 spin_unlock_irq(&phba->hbalock);
10890                 msleep(20);
10891                 spin_lock_irq(&phba->hbalock);
10892         }
10893         spin_unlock_irq(&phba->hbalock);
10894
10895         lpfc_sli4_cleanup_poll_list(phba);
10896
10897         /* Release HBA eqs */
10898         if (phba->sli4_hba.hdwq)
10899                 lpfc_sli4_release_hdwq(phba);
10900
10901         if (phba->nvmet_support) {
10902                 lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_cqset,
10903                                          phba->cfg_nvmet_mrq);
10904
10905                 lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_hdr,
10906                                          phba->cfg_nvmet_mrq);
10907                 lpfc_sli4_release_queues(&phba->sli4_hba.nvmet_mrq_data,
10908                                          phba->cfg_nvmet_mrq);
10909         }
10910
10911         /* Release mailbox command work queue */
10912         __lpfc_sli4_release_queue(&phba->sli4_hba.mbx_wq);
10913
10914         /* Release ELS work queue */
10915         __lpfc_sli4_release_queue(&phba->sli4_hba.els_wq);
10916
10917         /* Release ELS work queue */
10918         __lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_wq);
10919
10920         /* Release unsolicited receive queue */
10921         __lpfc_sli4_release_queue(&phba->sli4_hba.hdr_rq);
10922         __lpfc_sli4_release_queue(&phba->sli4_hba.dat_rq);
10923
10924         /* Release ELS complete queue */
10925         __lpfc_sli4_release_queue(&phba->sli4_hba.els_cq);
10926
10927         /* Release NVME LS complete queue */
10928         __lpfc_sli4_release_queue(&phba->sli4_hba.nvmels_cq);
10929
10930         /* Release mailbox command complete queue */
10931         __lpfc_sli4_release_queue(&phba->sli4_hba.mbx_cq);
10932
10933         /* Everything on this list has been freed */
10934         INIT_LIST_HEAD(&phba->sli4_hba.lpfc_wq_list);
10935
10936         /* Done with freeing the queues */
10937         spin_lock_irq(&phba->hbalock);
10938         phba->sli.sli_flag &= ~LPFC_QUEUE_FREE_INIT;
10939         spin_unlock_irq(&phba->hbalock);
10940 }
10941
10942 int
10943 lpfc_free_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *rq)
10944 {
10945         struct lpfc_rqb *rqbp;
10946         struct lpfc_dmabuf *h_buf;
10947         struct rqb_dmabuf *rqb_buffer;
10948
10949         rqbp = rq->rqbp;
10950         while (!list_empty(&rqbp->rqb_buffer_list)) {
10951                 list_remove_head(&rqbp->rqb_buffer_list, h_buf,
10952                                  struct lpfc_dmabuf, list);
10953
10954                 rqb_buffer = container_of(h_buf, struct rqb_dmabuf, hbuf);
10955                 (rqbp->rqb_free_buffer)(phba, rqb_buffer);
10956                 rqbp->buffer_count--;
10957         }
10958         return 1;
10959 }
10960
10961 static int
10962 lpfc_create_wq_cq(struct lpfc_hba *phba, struct lpfc_queue *eq,
10963         struct lpfc_queue *cq, struct lpfc_queue *wq, uint16_t *cq_map,
10964         int qidx, uint32_t qtype)
10965 {
10966         struct lpfc_sli_ring *pring;
10967         int rc;
10968
10969         if (!eq || !cq || !wq) {
10970                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10971                         "6085 Fast-path %s (%d) not allocated\n",
10972                         ((eq) ? ((cq) ? "WQ" : "CQ") : "EQ"), qidx);
10973                 return -ENOMEM;
10974         }
10975
10976         /* create the Cq first */
10977         rc = lpfc_cq_create(phba, cq, eq,
10978                         (qtype == LPFC_MBOX) ? LPFC_MCQ : LPFC_WCQ, qtype);
10979         if (rc) {
10980                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10981                                 "6086 Failed setup of CQ (%d), rc = 0x%x\n",
10982                                 qidx, (uint32_t)rc);
10983                 return rc;
10984         }
10985
10986         if (qtype != LPFC_MBOX) {
10987                 /* Setup cq_map for fast lookup */
10988                 if (cq_map)
10989                         *cq_map = cq->queue_id;
10990
10991                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10992                         "6087 CQ setup: cq[%d]-id=%d, parent eq[%d]-id=%d\n",
10993                         qidx, cq->queue_id, qidx, eq->queue_id);
10994
10995                 /* create the wq */
10996                 rc = lpfc_wq_create(phba, wq, cq, qtype);
10997                 if (rc) {
10998                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10999                                 "4618 Fail setup fastpath WQ (%d), rc = 0x%x\n",
11000                                 qidx, (uint32_t)rc);
11001                         /* no need to tear down cq - caller will do so */
11002                         return rc;
11003                 }
11004
11005                 /* Bind this CQ/WQ to the NVME ring */
11006                 pring = wq->pring;
11007                 pring->sli.sli4.wqp = (void *)wq;
11008                 cq->pring = pring;
11009
11010                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11011                         "2593 WQ setup: wq[%d]-id=%d assoc=%d, cq[%d]-id=%d\n",
11012                         qidx, wq->queue_id, wq->assoc_qid, qidx, cq->queue_id);
11013         } else {
11014                 rc = lpfc_mq_create(phba, wq, cq, LPFC_MBOX);
11015                 if (rc) {
11016                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11017                                         "0539 Failed setup of slow-path MQ: "
11018                                         "rc = 0x%x\n", rc);
11019                         /* no need to tear down cq - caller will do so */
11020                         return rc;
11021                 }
11022
11023                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11024                         "2589 MBX MQ setup: wq-id=%d, parent cq-id=%d\n",
11025                         phba->sli4_hba.mbx_wq->queue_id,
11026                         phba->sli4_hba.mbx_cq->queue_id);
11027         }
11028
11029         return 0;
11030 }
11031
11032 /**
11033  * lpfc_setup_cq_lookup - Setup the CQ lookup table
11034  * @phba: pointer to lpfc hba data structure.
11035  *
11036  * This routine will populate the cq_lookup table by all
11037  * available CQ queue_id's.
11038  **/
11039 static void
11040 lpfc_setup_cq_lookup(struct lpfc_hba *phba)
11041 {
11042         struct lpfc_queue *eq, *childq;
11043         int qidx;
11044
11045         memset(phba->sli4_hba.cq_lookup, 0,
11046                (sizeof(struct lpfc_queue *) * (phba->sli4_hba.cq_max + 1)));
11047         /* Loop thru all IRQ vectors */
11048         for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11049                 /* Get the EQ corresponding to the IRQ vector */
11050                 eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11051                 if (!eq)
11052                         continue;
11053                 /* Loop through all CQs associated with that EQ */
11054                 list_for_each_entry(childq, &eq->child_list, list) {
11055                         if (childq->queue_id > phba->sli4_hba.cq_max)
11056                                 continue;
11057                         if (childq->subtype == LPFC_IO)
11058                                 phba->sli4_hba.cq_lookup[childq->queue_id] =
11059                                         childq;
11060                 }
11061         }
11062 }
11063
11064 /**
11065  * lpfc_sli4_queue_setup - Set up all the SLI4 queues
11066  * @phba: pointer to lpfc hba data structure.
11067  *
11068  * This routine is invoked to set up all the SLI4 queues for the FCoE HBA
11069  * operation.
11070  *
11071  * Return codes
11072  *      0 - successful
11073  *      -ENOMEM - No available memory
11074  *      -EIO - The mailbox failed to complete successfully.
11075  **/
11076 int
11077 lpfc_sli4_queue_setup(struct lpfc_hba *phba)
11078 {
11079         uint32_t shdr_status, shdr_add_status;
11080         union lpfc_sli4_cfg_shdr *shdr;
11081         struct lpfc_vector_map_info *cpup;
11082         struct lpfc_sli4_hdw_queue *qp;
11083         LPFC_MBOXQ_t *mboxq;
11084         int qidx, cpu;
11085         uint32_t length, usdelay;
11086         int rc = -ENOMEM;
11087
11088         /* Check for dual-ULP support */
11089         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
11090         if (!mboxq) {
11091                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11092                                 "3249 Unable to allocate memory for "
11093                                 "QUERY_FW_CFG mailbox command\n");
11094                 return -ENOMEM;
11095         }
11096         length = (sizeof(struct lpfc_mbx_query_fw_config) -
11097                   sizeof(struct lpfc_sli4_cfg_mhdr));
11098         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11099                          LPFC_MBOX_OPCODE_QUERY_FW_CFG,
11100                          length, LPFC_SLI4_MBX_EMBED);
11101
11102         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11103
11104         shdr = (union lpfc_sli4_cfg_shdr *)
11105                         &mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11106         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11107         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
11108         if (shdr_status || shdr_add_status || rc) {
11109                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11110                                 "3250 QUERY_FW_CFG mailbox failed with status "
11111                                 "x%x add_status x%x, mbx status x%x\n",
11112                                 shdr_status, shdr_add_status, rc);
11113                 mempool_free(mboxq, phba->mbox_mem_pool);
11114                 rc = -ENXIO;
11115                 goto out_error;
11116         }
11117
11118         phba->sli4_hba.fw_func_mode =
11119                         mboxq->u.mqe.un.query_fw_cfg.rsp.function_mode;
11120         phba->sli4_hba.ulp0_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp0_mode;
11121         phba->sli4_hba.ulp1_mode = mboxq->u.mqe.un.query_fw_cfg.rsp.ulp1_mode;
11122         phba->sli4_hba.physical_port =
11123                         mboxq->u.mqe.un.query_fw_cfg.rsp.physical_port;
11124         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11125                         "3251 QUERY_FW_CFG: func_mode:x%x, ulp0_mode:x%x, "
11126                         "ulp1_mode:x%x\n", phba->sli4_hba.fw_func_mode,
11127                         phba->sli4_hba.ulp0_mode, phba->sli4_hba.ulp1_mode);
11128
11129         mempool_free(mboxq, phba->mbox_mem_pool);
11130
11131         /*
11132          * Set up HBA Event Queues (EQs)
11133          */
11134         qp = phba->sli4_hba.hdwq;
11135
11136         /* Set up HBA event queue */
11137         if (!qp) {
11138                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11139                                 "3147 Fast-path EQs not allocated\n");
11140                 rc = -ENOMEM;
11141                 goto out_error;
11142         }
11143
11144         /* Loop thru all IRQ vectors */
11145         for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11146                 /* Create HBA Event Queues (EQs) in order */
11147                 for_each_present_cpu(cpu) {
11148                         cpup = &phba->sli4_hba.cpu_map[cpu];
11149
11150                         /* Look for the CPU thats using that vector with
11151                          * LPFC_CPU_FIRST_IRQ set.
11152                          */
11153                         if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
11154                                 continue;
11155                         if (qidx != cpup->eq)
11156                                 continue;
11157
11158                         /* Create an EQ for that vector */
11159                         rc = lpfc_eq_create(phba, qp[cpup->hdwq].hba_eq,
11160                                             phba->cfg_fcp_imax);
11161                         if (rc) {
11162                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11163                                                 "0523 Failed setup of fast-path"
11164                                                 " EQ (%d), rc = 0x%x\n",
11165                                                 cpup->eq, (uint32_t)rc);
11166                                 goto out_destroy;
11167                         }
11168
11169                         /* Save the EQ for that vector in the hba_eq_hdl */
11170                         phba->sli4_hba.hba_eq_hdl[cpup->eq].eq =
11171                                 qp[cpup->hdwq].hba_eq;
11172
11173                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11174                                         "2584 HBA EQ setup: queue[%d]-id=%d\n",
11175                                         cpup->eq,
11176                                         qp[cpup->hdwq].hba_eq->queue_id);
11177                 }
11178         }
11179
11180         /* Loop thru all Hardware Queues */
11181         for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11182                 cpu = lpfc_find_cpu_handle(phba, qidx, LPFC_FIND_BY_HDWQ);
11183                 cpup = &phba->sli4_hba.cpu_map[cpu];
11184
11185                 /* Create the CQ/WQ corresponding to the Hardware Queue */
11186                 rc = lpfc_create_wq_cq(phba,
11187                                        phba->sli4_hba.hdwq[cpup->hdwq].hba_eq,
11188                                        qp[qidx].io_cq,
11189                                        qp[qidx].io_wq,
11190                                        &phba->sli4_hba.hdwq[qidx].io_cq_map,
11191                                        qidx,
11192                                        LPFC_IO);
11193                 if (rc) {
11194                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11195                                         "0535 Failed to setup fastpath "
11196                                         "IO WQ/CQ (%d), rc = 0x%x\n",
11197                                         qidx, (uint32_t)rc);
11198                         goto out_destroy;
11199                 }
11200         }
11201
11202         /*
11203          * Set up Slow Path Complete Queues (CQs)
11204          */
11205
11206         /* Set up slow-path MBOX CQ/MQ */
11207
11208         if (!phba->sli4_hba.mbx_cq || !phba->sli4_hba.mbx_wq) {
11209                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11210                                 "0528 %s not allocated\n",
11211                                 phba->sli4_hba.mbx_cq ?
11212                                 "Mailbox WQ" : "Mailbox CQ");
11213                 rc = -ENOMEM;
11214                 goto out_destroy;
11215         }
11216
11217         rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11218                                phba->sli4_hba.mbx_cq,
11219                                phba->sli4_hba.mbx_wq,
11220                                NULL, 0, LPFC_MBOX);
11221         if (rc) {
11222                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11223                         "0529 Failed setup of mailbox WQ/CQ: rc = 0x%x\n",
11224                         (uint32_t)rc);
11225                 goto out_destroy;
11226         }
11227         if (phba->nvmet_support) {
11228                 if (!phba->sli4_hba.nvmet_cqset) {
11229                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11230                                         "3165 Fast-path NVME CQ Set "
11231                                         "array not allocated\n");
11232                         rc = -ENOMEM;
11233                         goto out_destroy;
11234                 }
11235                 if (phba->cfg_nvmet_mrq > 1) {
11236                         rc = lpfc_cq_create_set(phba,
11237                                         phba->sli4_hba.nvmet_cqset,
11238                                         qp,
11239                                         LPFC_WCQ, LPFC_NVMET);
11240                         if (rc) {
11241                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11242                                                 "3164 Failed setup of NVME CQ "
11243                                                 "Set, rc = 0x%x\n",
11244                                                 (uint32_t)rc);
11245                                 goto out_destroy;
11246                         }
11247                 } else {
11248                         /* Set up NVMET Receive Complete Queue */
11249                         rc = lpfc_cq_create(phba, phba->sli4_hba.nvmet_cqset[0],
11250                                             qp[0].hba_eq,
11251                                             LPFC_WCQ, LPFC_NVMET);
11252                         if (rc) {
11253                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11254                                                 "6089 Failed setup NVMET CQ: "
11255                                                 "rc = 0x%x\n", (uint32_t)rc);
11256                                 goto out_destroy;
11257                         }
11258                         phba->sli4_hba.nvmet_cqset[0]->chann = 0;
11259
11260                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11261                                         "6090 NVMET CQ setup: cq-id=%d, "
11262                                         "parent eq-id=%d\n",
11263                                         phba->sli4_hba.nvmet_cqset[0]->queue_id,
11264                                         qp[0].hba_eq->queue_id);
11265                 }
11266         }
11267
11268         /* Set up slow-path ELS WQ/CQ */
11269         if (!phba->sli4_hba.els_cq || !phba->sli4_hba.els_wq) {
11270                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11271                                 "0530 ELS %s not allocated\n",
11272                                 phba->sli4_hba.els_cq ? "WQ" : "CQ");
11273                 rc = -ENOMEM;
11274                 goto out_destroy;
11275         }
11276         rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11277                                phba->sli4_hba.els_cq,
11278                                phba->sli4_hba.els_wq,
11279                                NULL, 0, LPFC_ELS);
11280         if (rc) {
11281                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11282                                 "0525 Failed setup of ELS WQ/CQ: rc = 0x%x\n",
11283                                 (uint32_t)rc);
11284                 goto out_destroy;
11285         }
11286         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11287                         "2590 ELS WQ setup: wq-id=%d, parent cq-id=%d\n",
11288                         phba->sli4_hba.els_wq->queue_id,
11289                         phba->sli4_hba.els_cq->queue_id);
11290
11291         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11292                 /* Set up NVME LS Complete Queue */
11293                 if (!phba->sli4_hba.nvmels_cq || !phba->sli4_hba.nvmels_wq) {
11294                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11295                                         "6091 LS %s not allocated\n",
11296                                         phba->sli4_hba.nvmels_cq ? "WQ" : "CQ");
11297                         rc = -ENOMEM;
11298                         goto out_destroy;
11299                 }
11300                 rc = lpfc_create_wq_cq(phba, qp[0].hba_eq,
11301                                        phba->sli4_hba.nvmels_cq,
11302                                        phba->sli4_hba.nvmels_wq,
11303                                        NULL, 0, LPFC_NVME_LS);
11304                 if (rc) {
11305                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11306                                         "0526 Failed setup of NVVME LS WQ/CQ: "
11307                                         "rc = 0x%x\n", (uint32_t)rc);
11308                         goto out_destroy;
11309                 }
11310
11311                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11312                                 "6096 ELS WQ setup: wq-id=%d, "
11313                                 "parent cq-id=%d\n",
11314                                 phba->sli4_hba.nvmels_wq->queue_id,
11315                                 phba->sli4_hba.nvmels_cq->queue_id);
11316         }
11317
11318         /*
11319          * Create NVMET Receive Queue (RQ)
11320          */
11321         if (phba->nvmet_support) {
11322                 if ((!phba->sli4_hba.nvmet_cqset) ||
11323                     (!phba->sli4_hba.nvmet_mrq_hdr) ||
11324                     (!phba->sli4_hba.nvmet_mrq_data)) {
11325                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11326                                         "6130 MRQ CQ Queues not "
11327                                         "allocated\n");
11328                         rc = -ENOMEM;
11329                         goto out_destroy;
11330                 }
11331                 if (phba->cfg_nvmet_mrq > 1) {
11332                         rc = lpfc_mrq_create(phba,
11333                                              phba->sli4_hba.nvmet_mrq_hdr,
11334                                              phba->sli4_hba.nvmet_mrq_data,
11335                                              phba->sli4_hba.nvmet_cqset,
11336                                              LPFC_NVMET);
11337                         if (rc) {
11338                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11339                                                 "6098 Failed setup of NVMET "
11340                                                 "MRQ: rc = 0x%x\n",
11341                                                 (uint32_t)rc);
11342                                 goto out_destroy;
11343                         }
11344
11345                 } else {
11346                         rc = lpfc_rq_create(phba,
11347                                             phba->sli4_hba.nvmet_mrq_hdr[0],
11348                                             phba->sli4_hba.nvmet_mrq_data[0],
11349                                             phba->sli4_hba.nvmet_cqset[0],
11350                                             LPFC_NVMET);
11351                         if (rc) {
11352                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11353                                                 "6057 Failed setup of NVMET "
11354                                                 "Receive Queue: rc = 0x%x\n",
11355                                                 (uint32_t)rc);
11356                                 goto out_destroy;
11357                         }
11358
11359                         lpfc_printf_log(
11360                                 phba, KERN_INFO, LOG_INIT,
11361                                 "6099 NVMET RQ setup: hdr-rq-id=%d, "
11362                                 "dat-rq-id=%d parent cq-id=%d\n",
11363                                 phba->sli4_hba.nvmet_mrq_hdr[0]->queue_id,
11364                                 phba->sli4_hba.nvmet_mrq_data[0]->queue_id,
11365                                 phba->sli4_hba.nvmet_cqset[0]->queue_id);
11366
11367                 }
11368         }
11369
11370         if (!phba->sli4_hba.hdr_rq || !phba->sli4_hba.dat_rq) {
11371                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11372                                 "0540 Receive Queue not allocated\n");
11373                 rc = -ENOMEM;
11374                 goto out_destroy;
11375         }
11376
11377         rc = lpfc_rq_create(phba, phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
11378                             phba->sli4_hba.els_cq, LPFC_USOL);
11379         if (rc) {
11380                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11381                                 "0541 Failed setup of Receive Queue: "
11382                                 "rc = 0x%x\n", (uint32_t)rc);
11383                 goto out_destroy;
11384         }
11385
11386         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
11387                         "2592 USL RQ setup: hdr-rq-id=%d, dat-rq-id=%d "
11388                         "parent cq-id=%d\n",
11389                         phba->sli4_hba.hdr_rq->queue_id,
11390                         phba->sli4_hba.dat_rq->queue_id,
11391                         phba->sli4_hba.els_cq->queue_id);
11392
11393         if (phba->cfg_fcp_imax)
11394                 usdelay = LPFC_SEC_TO_USEC / phba->cfg_fcp_imax;
11395         else
11396                 usdelay = 0;
11397
11398         for (qidx = 0; qidx < phba->cfg_irq_chann;
11399              qidx += LPFC_MAX_EQ_DELAY_EQID_CNT)
11400                 lpfc_modify_hba_eq_delay(phba, qidx, LPFC_MAX_EQ_DELAY_EQID_CNT,
11401                                          usdelay);
11402
11403         if (phba->sli4_hba.cq_max) {
11404                 kfree(phba->sli4_hba.cq_lookup);
11405                 phba->sli4_hba.cq_lookup = kcalloc((phba->sli4_hba.cq_max + 1),
11406                         sizeof(struct lpfc_queue *), GFP_KERNEL);
11407                 if (!phba->sli4_hba.cq_lookup) {
11408                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11409                                         "0549 Failed setup of CQ Lookup table: "
11410                                         "size 0x%x\n", phba->sli4_hba.cq_max);
11411                         rc = -ENOMEM;
11412                         goto out_destroy;
11413                 }
11414                 lpfc_setup_cq_lookup(phba);
11415         }
11416         return 0;
11417
11418 out_destroy:
11419         lpfc_sli4_queue_unset(phba);
11420 out_error:
11421         return rc;
11422 }
11423
11424 /**
11425  * lpfc_sli4_queue_unset - Unset all the SLI4 queues
11426  * @phba: pointer to lpfc hba data structure.
11427  *
11428  * This routine is invoked to unset all the SLI4 queues with the FCoE HBA
11429  * operation.
11430  *
11431  * Return codes
11432  *      0 - successful
11433  *      -ENOMEM - No available memory
11434  *      -EIO - The mailbox failed to complete successfully.
11435  **/
11436 void
11437 lpfc_sli4_queue_unset(struct lpfc_hba *phba)
11438 {
11439         struct lpfc_sli4_hdw_queue *qp;
11440         struct lpfc_queue *eq;
11441         int qidx;
11442
11443         /* Unset mailbox command work queue */
11444         if (phba->sli4_hba.mbx_wq)
11445                 lpfc_mq_destroy(phba, phba->sli4_hba.mbx_wq);
11446
11447         /* Unset NVME LS work queue */
11448         if (phba->sli4_hba.nvmels_wq)
11449                 lpfc_wq_destroy(phba, phba->sli4_hba.nvmels_wq);
11450
11451         /* Unset ELS work queue */
11452         if (phba->sli4_hba.els_wq)
11453                 lpfc_wq_destroy(phba, phba->sli4_hba.els_wq);
11454
11455         /* Unset unsolicited receive queue */
11456         if (phba->sli4_hba.hdr_rq)
11457                 lpfc_rq_destroy(phba, phba->sli4_hba.hdr_rq,
11458                                 phba->sli4_hba.dat_rq);
11459
11460         /* Unset mailbox command complete queue */
11461         if (phba->sli4_hba.mbx_cq)
11462                 lpfc_cq_destroy(phba, phba->sli4_hba.mbx_cq);
11463
11464         /* Unset ELS complete queue */
11465         if (phba->sli4_hba.els_cq)
11466                 lpfc_cq_destroy(phba, phba->sli4_hba.els_cq);
11467
11468         /* Unset NVME LS complete queue */
11469         if (phba->sli4_hba.nvmels_cq)
11470                 lpfc_cq_destroy(phba, phba->sli4_hba.nvmels_cq);
11471
11472         if (phba->nvmet_support) {
11473                 /* Unset NVMET MRQ queue */
11474                 if (phba->sli4_hba.nvmet_mrq_hdr) {
11475                         for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11476                                 lpfc_rq_destroy(
11477                                         phba,
11478                                         phba->sli4_hba.nvmet_mrq_hdr[qidx],
11479                                         phba->sli4_hba.nvmet_mrq_data[qidx]);
11480                 }
11481
11482                 /* Unset NVMET CQ Set complete queue */
11483                 if (phba->sli4_hba.nvmet_cqset) {
11484                         for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++)
11485                                 lpfc_cq_destroy(
11486                                         phba, phba->sli4_hba.nvmet_cqset[qidx]);
11487                 }
11488         }
11489
11490         /* Unset fast-path SLI4 queues */
11491         if (phba->sli4_hba.hdwq) {
11492                 /* Loop thru all Hardware Queues */
11493                 for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
11494                         /* Destroy the CQ/WQ corresponding to Hardware Queue */
11495                         qp = &phba->sli4_hba.hdwq[qidx];
11496                         lpfc_wq_destroy(phba, qp->io_wq);
11497                         lpfc_cq_destroy(phba, qp->io_cq);
11498                 }
11499                 /* Loop thru all IRQ vectors */
11500                 for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
11501                         /* Destroy the EQ corresponding to the IRQ vector */
11502                         eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
11503                         lpfc_eq_destroy(phba, eq);
11504                 }
11505         }
11506
11507         kfree(phba->sli4_hba.cq_lookup);
11508         phba->sli4_hba.cq_lookup = NULL;
11509         phba->sli4_hba.cq_max = 0;
11510 }
11511
11512 /**
11513  * lpfc_sli4_cq_event_pool_create - Create completion-queue event free pool
11514  * @phba: pointer to lpfc hba data structure.
11515  *
11516  * This routine is invoked to allocate and set up a pool of completion queue
11517  * events. The body of the completion queue event is a completion queue entry
11518  * CQE. For now, this pool is used for the interrupt service routine to queue
11519  * the following HBA completion queue events for the worker thread to process:
11520  *   - Mailbox asynchronous events
11521  *   - Receive queue completion unsolicited events
11522  * Later, this can be used for all the slow-path events.
11523  *
11524  * Return codes
11525  *      0 - successful
11526  *      -ENOMEM - No available memory
11527  **/
11528 static int
11529 lpfc_sli4_cq_event_pool_create(struct lpfc_hba *phba)
11530 {
11531         struct lpfc_cq_event *cq_event;
11532         int i;
11533
11534         for (i = 0; i < (4 * phba->sli4_hba.cq_ecount); i++) {
11535                 cq_event = kmalloc(sizeof(struct lpfc_cq_event), GFP_KERNEL);
11536                 if (!cq_event)
11537                         goto out_pool_create_fail;
11538                 list_add_tail(&cq_event->list,
11539                               &phba->sli4_hba.sp_cqe_event_pool);
11540         }
11541         return 0;
11542
11543 out_pool_create_fail:
11544         lpfc_sli4_cq_event_pool_destroy(phba);
11545         return -ENOMEM;
11546 }
11547
11548 /**
11549  * lpfc_sli4_cq_event_pool_destroy - Free completion-queue event free pool
11550  * @phba: pointer to lpfc hba data structure.
11551  *
11552  * This routine is invoked to free the pool of completion queue events at
11553  * driver unload time. Note that, it is the responsibility of the driver
11554  * cleanup routine to free all the outstanding completion-queue events
11555  * allocated from this pool back into the pool before invoking this routine
11556  * to destroy the pool.
11557  **/
11558 static void
11559 lpfc_sli4_cq_event_pool_destroy(struct lpfc_hba *phba)
11560 {
11561         struct lpfc_cq_event *cq_event, *next_cq_event;
11562
11563         list_for_each_entry_safe(cq_event, next_cq_event,
11564                                  &phba->sli4_hba.sp_cqe_event_pool, list) {
11565                 list_del(&cq_event->list);
11566                 kfree(cq_event);
11567         }
11568 }
11569
11570 /**
11571  * __lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11572  * @phba: pointer to lpfc hba data structure.
11573  *
11574  * This routine is the lock free version of the API invoked to allocate a
11575  * completion-queue event from the free pool.
11576  *
11577  * Return: Pointer to the newly allocated completion-queue event if successful
11578  *         NULL otherwise.
11579  **/
11580 struct lpfc_cq_event *
11581 __lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11582 {
11583         struct lpfc_cq_event *cq_event = NULL;
11584
11585         list_remove_head(&phba->sli4_hba.sp_cqe_event_pool, cq_event,
11586                          struct lpfc_cq_event, list);
11587         return cq_event;
11588 }
11589
11590 /**
11591  * lpfc_sli4_cq_event_alloc - Allocate a completion-queue event from free pool
11592  * @phba: pointer to lpfc hba data structure.
11593  *
11594  * This routine is the lock version of the API invoked to allocate a
11595  * completion-queue event from the free pool.
11596  *
11597  * Return: Pointer to the newly allocated completion-queue event if successful
11598  *         NULL otherwise.
11599  **/
11600 struct lpfc_cq_event *
11601 lpfc_sli4_cq_event_alloc(struct lpfc_hba *phba)
11602 {
11603         struct lpfc_cq_event *cq_event;
11604         unsigned long iflags;
11605
11606         spin_lock_irqsave(&phba->hbalock, iflags);
11607         cq_event = __lpfc_sli4_cq_event_alloc(phba);
11608         spin_unlock_irqrestore(&phba->hbalock, iflags);
11609         return cq_event;
11610 }
11611
11612 /**
11613  * __lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11614  * @phba: pointer to lpfc hba data structure.
11615  * @cq_event: pointer to the completion queue event to be freed.
11616  *
11617  * This routine is the lock free version of the API invoked to release a
11618  * completion-queue event back into the free pool.
11619  **/
11620 void
11621 __lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11622                              struct lpfc_cq_event *cq_event)
11623 {
11624         list_add_tail(&cq_event->list, &phba->sli4_hba.sp_cqe_event_pool);
11625 }
11626
11627 /**
11628  * lpfc_sli4_cq_event_release - Release a completion-queue event to free pool
11629  * @phba: pointer to lpfc hba data structure.
11630  * @cq_event: pointer to the completion queue event to be freed.
11631  *
11632  * This routine is the lock version of the API invoked to release a
11633  * completion-queue event back into the free pool.
11634  **/
11635 void
11636 lpfc_sli4_cq_event_release(struct lpfc_hba *phba,
11637                            struct lpfc_cq_event *cq_event)
11638 {
11639         unsigned long iflags;
11640         spin_lock_irqsave(&phba->hbalock, iflags);
11641         __lpfc_sli4_cq_event_release(phba, cq_event);
11642         spin_unlock_irqrestore(&phba->hbalock, iflags);
11643 }
11644
11645 /**
11646  * lpfc_sli4_cq_event_release_all - Release all cq events to the free pool
11647  * @phba: pointer to lpfc hba data structure.
11648  *
11649  * This routine is to free all the pending completion-queue events to the
11650  * back into the free pool for device reset.
11651  **/
11652 static void
11653 lpfc_sli4_cq_event_release_all(struct lpfc_hba *phba)
11654 {
11655         LIST_HEAD(cq_event_list);
11656         struct lpfc_cq_event *cq_event;
11657         unsigned long iflags;
11658
11659         /* Retrieve all the pending WCQEs from pending WCQE lists */
11660
11661         /* Pending ELS XRI abort events */
11662         spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11663         list_splice_init(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11664                          &cq_event_list);
11665         spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
11666
11667         /* Pending asynnc events */
11668         spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
11669         list_splice_init(&phba->sli4_hba.sp_asynce_work_queue,
11670                          &cq_event_list);
11671         spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
11672
11673         while (!list_empty(&cq_event_list)) {
11674                 list_remove_head(&cq_event_list, cq_event,
11675                                  struct lpfc_cq_event, list);
11676                 lpfc_sli4_cq_event_release(phba, cq_event);
11677         }
11678 }
11679
11680 /**
11681  * lpfc_pci_function_reset - Reset pci function.
11682  * @phba: pointer to lpfc hba data structure.
11683  *
11684  * This routine is invoked to request a PCI function reset. It will destroys
11685  * all resources assigned to the PCI function which originates this request.
11686  *
11687  * Return codes
11688  *      0 - successful
11689  *      -ENOMEM - No available memory
11690  *      -EIO - The mailbox failed to complete successfully.
11691  **/
11692 int
11693 lpfc_pci_function_reset(struct lpfc_hba *phba)
11694 {
11695         LPFC_MBOXQ_t *mboxq;
11696         uint32_t rc = 0, if_type;
11697         uint32_t shdr_status, shdr_add_status;
11698         uint32_t rdy_chk;
11699         uint32_t port_reset = 0;
11700         union lpfc_sli4_cfg_shdr *shdr;
11701         struct lpfc_register reg_data;
11702         uint16_t devid;
11703
11704         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11705         switch (if_type) {
11706         case LPFC_SLI_INTF_IF_TYPE_0:
11707                 mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool,
11708                                                        GFP_KERNEL);
11709                 if (!mboxq) {
11710                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11711                                         "0494 Unable to allocate memory for "
11712                                         "issuing SLI_FUNCTION_RESET mailbox "
11713                                         "command\n");
11714                         return -ENOMEM;
11715                 }
11716
11717                 /* Setup PCI function reset mailbox-ioctl command */
11718                 lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
11719                                  LPFC_MBOX_OPCODE_FUNCTION_RESET, 0,
11720                                  LPFC_SLI4_MBX_EMBED);
11721                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11722                 shdr = (union lpfc_sli4_cfg_shdr *)
11723                         &mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
11724                 shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11725                 shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
11726                                          &shdr->response);
11727                 mempool_free(mboxq, phba->mbox_mem_pool);
11728                 if (shdr_status || shdr_add_status || rc) {
11729                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11730                                         "0495 SLI_FUNCTION_RESET mailbox "
11731                                         "failed with status x%x add_status x%x,"
11732                                         " mbx status x%x\n",
11733                                         shdr_status, shdr_add_status, rc);
11734                         rc = -ENXIO;
11735                 }
11736                 break;
11737         case LPFC_SLI_INTF_IF_TYPE_2:
11738         case LPFC_SLI_INTF_IF_TYPE_6:
11739 wait:
11740                 /*
11741                  * Poll the Port Status Register and wait for RDY for
11742                  * up to 30 seconds. If the port doesn't respond, treat
11743                  * it as an error.
11744                  */
11745                 for (rdy_chk = 0; rdy_chk < 1500; rdy_chk++) {
11746                         if (lpfc_readl(phba->sli4_hba.u.if_type2.
11747                                 STATUSregaddr, &reg_data.word0)) {
11748                                 rc = -ENODEV;
11749                                 goto out;
11750                         }
11751                         if (bf_get(lpfc_sliport_status_rdy, &reg_data))
11752                                 break;
11753                         msleep(20);
11754                 }
11755
11756                 if (!bf_get(lpfc_sliport_status_rdy, &reg_data)) {
11757                         phba->work_status[0] = readl(
11758                                 phba->sli4_hba.u.if_type2.ERR1regaddr);
11759                         phba->work_status[1] = readl(
11760                                 phba->sli4_hba.u.if_type2.ERR2regaddr);
11761                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11762                                         "2890 Port not ready, port status reg "
11763                                         "0x%x error 1=0x%x, error 2=0x%x\n",
11764                                         reg_data.word0,
11765                                         phba->work_status[0],
11766                                         phba->work_status[1]);
11767                         rc = -ENODEV;
11768                         goto out;
11769                 }
11770
11771                 if (bf_get(lpfc_sliport_status_pldv, &reg_data))
11772                         lpfc_pldv_detect = true;
11773
11774                 if (!port_reset) {
11775                         /*
11776                          * Reset the port now
11777                          */
11778                         reg_data.word0 = 0;
11779                         bf_set(lpfc_sliport_ctrl_end, &reg_data,
11780                                LPFC_SLIPORT_LITTLE_ENDIAN);
11781                         bf_set(lpfc_sliport_ctrl_ip, &reg_data,
11782                                LPFC_SLIPORT_INIT_PORT);
11783                         writel(reg_data.word0, phba->sli4_hba.u.if_type2.
11784                                CTRLregaddr);
11785                         /* flush */
11786                         pci_read_config_word(phba->pcidev,
11787                                              PCI_DEVICE_ID, &devid);
11788
11789                         port_reset = 1;
11790                         msleep(20);
11791                         goto wait;
11792                 } else if (bf_get(lpfc_sliport_status_rn, &reg_data)) {
11793                         rc = -ENODEV;
11794                         goto out;
11795                 }
11796                 break;
11797
11798         case LPFC_SLI_INTF_IF_TYPE_1:
11799         default:
11800                 break;
11801         }
11802
11803 out:
11804         /* Catch the not-ready port failure after a port reset. */
11805         if (rc) {
11806                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11807                                 "3317 HBA not functional: IP Reset Failed "
11808                                 "try: echo fw_reset > board_mode\n");
11809                 rc = -ENODEV;
11810         }
11811
11812         return rc;
11813 }
11814
11815 /**
11816  * lpfc_sli4_pci_mem_setup - Setup SLI4 HBA PCI memory space.
11817  * @phba: pointer to lpfc hba data structure.
11818  *
11819  * This routine is invoked to set up the PCI device memory space for device
11820  * with SLI-4 interface spec.
11821  *
11822  * Return codes
11823  *      0 - successful
11824  *      other values - error
11825  **/
11826 static int
11827 lpfc_sli4_pci_mem_setup(struct lpfc_hba *phba)
11828 {
11829         struct pci_dev *pdev = phba->pcidev;
11830         unsigned long bar0map_len, bar1map_len, bar2map_len;
11831         int error;
11832         uint32_t if_type;
11833
11834         if (!pdev)
11835                 return -ENODEV;
11836
11837         /* Set the device DMA mask size */
11838         error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
11839         if (error)
11840                 error = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
11841         if (error)
11842                 return error;
11843
11844         /*
11845          * The BARs and register set definitions and offset locations are
11846          * dependent on the if_type.
11847          */
11848         if (pci_read_config_dword(pdev, LPFC_SLI_INTF,
11849                                   &phba->sli4_hba.sli_intf.word0)) {
11850                 return -ENODEV;
11851         }
11852
11853         /* There is no SLI3 failback for SLI4 devices. */
11854         if (bf_get(lpfc_sli_intf_valid, &phba->sli4_hba.sli_intf) !=
11855             LPFC_SLI_INTF_VALID) {
11856                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11857                                 "2894 SLI_INTF reg contents invalid "
11858                                 "sli_intf reg 0x%x\n",
11859                                 phba->sli4_hba.sli_intf.word0);
11860                 return -ENODEV;
11861         }
11862
11863         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
11864         /*
11865          * Get the bus address of SLI4 device Bar regions and the
11866          * number of bytes required by each mapping. The mapping of the
11867          * particular PCI BARs regions is dependent on the type of
11868          * SLI4 device.
11869          */
11870         if (pci_resource_start(pdev, PCI_64BIT_BAR0)) {
11871                 phba->pci_bar0_map = pci_resource_start(pdev, PCI_64BIT_BAR0);
11872                 bar0map_len = pci_resource_len(pdev, PCI_64BIT_BAR0);
11873
11874                 /*
11875                  * Map SLI4 PCI Config Space Register base to a kernel virtual
11876                  * addr
11877                  */
11878                 phba->sli4_hba.conf_regs_memmap_p =
11879                         ioremap(phba->pci_bar0_map, bar0map_len);
11880                 if (!phba->sli4_hba.conf_regs_memmap_p) {
11881                         dev_printk(KERN_ERR, &pdev->dev,
11882                                    "ioremap failed for SLI4 PCI config "
11883                                    "registers.\n");
11884                         return -ENODEV;
11885                 }
11886                 phba->pci_bar0_memmap_p = phba->sli4_hba.conf_regs_memmap_p;
11887                 /* Set up BAR0 PCI config space register memory map */
11888                 lpfc_sli4_bar0_register_memmap(phba, if_type);
11889         } else {
11890                 phba->pci_bar0_map = pci_resource_start(pdev, 1);
11891                 bar0map_len = pci_resource_len(pdev, 1);
11892                 if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
11893                         dev_printk(KERN_ERR, &pdev->dev,
11894                            "FATAL - No BAR0 mapping for SLI4, if_type 2\n");
11895                         return -ENODEV;
11896                 }
11897                 phba->sli4_hba.conf_regs_memmap_p =
11898                                 ioremap(phba->pci_bar0_map, bar0map_len);
11899                 if (!phba->sli4_hba.conf_regs_memmap_p) {
11900                         dev_printk(KERN_ERR, &pdev->dev,
11901                                 "ioremap failed for SLI4 PCI config "
11902                                 "registers.\n");
11903                         return -ENODEV;
11904                 }
11905                 lpfc_sli4_bar0_register_memmap(phba, if_type);
11906         }
11907
11908         if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11909                 if (pci_resource_start(pdev, PCI_64BIT_BAR2)) {
11910                         /*
11911                          * Map SLI4 if type 0 HBA Control Register base to a
11912                          * kernel virtual address and setup the registers.
11913                          */
11914                         phba->pci_bar1_map = pci_resource_start(pdev,
11915                                                                 PCI_64BIT_BAR2);
11916                         bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11917                         phba->sli4_hba.ctrl_regs_memmap_p =
11918                                         ioremap(phba->pci_bar1_map,
11919                                                 bar1map_len);
11920                         if (!phba->sli4_hba.ctrl_regs_memmap_p) {
11921                                 dev_err(&pdev->dev,
11922                                            "ioremap failed for SLI4 HBA "
11923                                             "control registers.\n");
11924                                 error = -ENOMEM;
11925                                 goto out_iounmap_conf;
11926                         }
11927                         phba->pci_bar2_memmap_p =
11928                                          phba->sli4_hba.ctrl_regs_memmap_p;
11929                         lpfc_sli4_bar1_register_memmap(phba, if_type);
11930                 } else {
11931                         error = -ENOMEM;
11932                         goto out_iounmap_conf;
11933                 }
11934         }
11935
11936         if ((if_type == LPFC_SLI_INTF_IF_TYPE_6) &&
11937             (pci_resource_start(pdev, PCI_64BIT_BAR2))) {
11938                 /*
11939                  * Map SLI4 if type 6 HBA Doorbell Register base to a kernel
11940                  * virtual address and setup the registers.
11941                  */
11942                 phba->pci_bar1_map = pci_resource_start(pdev, PCI_64BIT_BAR2);
11943                 bar1map_len = pci_resource_len(pdev, PCI_64BIT_BAR2);
11944                 phba->sli4_hba.drbl_regs_memmap_p =
11945                                 ioremap(phba->pci_bar1_map, bar1map_len);
11946                 if (!phba->sli4_hba.drbl_regs_memmap_p) {
11947                         dev_err(&pdev->dev,
11948                            "ioremap failed for SLI4 HBA doorbell registers.\n");
11949                         error = -ENOMEM;
11950                         goto out_iounmap_conf;
11951                 }
11952                 phba->pci_bar2_memmap_p = phba->sli4_hba.drbl_regs_memmap_p;
11953                 lpfc_sli4_bar1_register_memmap(phba, if_type);
11954         }
11955
11956         if (if_type == LPFC_SLI_INTF_IF_TYPE_0) {
11957                 if (pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11958                         /*
11959                          * Map SLI4 if type 0 HBA Doorbell Register base to
11960                          * a kernel virtual address and setup the registers.
11961                          */
11962                         phba->pci_bar2_map = pci_resource_start(pdev,
11963                                                                 PCI_64BIT_BAR4);
11964                         bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11965                         phba->sli4_hba.drbl_regs_memmap_p =
11966                                         ioremap(phba->pci_bar2_map,
11967                                                 bar2map_len);
11968                         if (!phba->sli4_hba.drbl_regs_memmap_p) {
11969                                 dev_err(&pdev->dev,
11970                                            "ioremap failed for SLI4 HBA"
11971                                            " doorbell registers.\n");
11972                                 error = -ENOMEM;
11973                                 goto out_iounmap_ctrl;
11974                         }
11975                         phba->pci_bar4_memmap_p =
11976                                         phba->sli4_hba.drbl_regs_memmap_p;
11977                         error = lpfc_sli4_bar2_register_memmap(phba, LPFC_VF0);
11978                         if (error)
11979                                 goto out_iounmap_all;
11980                 } else {
11981                         error = -ENOMEM;
11982                         goto out_iounmap_ctrl;
11983                 }
11984         }
11985
11986         if (if_type == LPFC_SLI_INTF_IF_TYPE_6 &&
11987             pci_resource_start(pdev, PCI_64BIT_BAR4)) {
11988                 /*
11989                  * Map SLI4 if type 6 HBA DPP Register base to a kernel
11990                  * virtual address and setup the registers.
11991                  */
11992                 phba->pci_bar2_map = pci_resource_start(pdev, PCI_64BIT_BAR4);
11993                 bar2map_len = pci_resource_len(pdev, PCI_64BIT_BAR4);
11994                 phba->sli4_hba.dpp_regs_memmap_p =
11995                                 ioremap(phba->pci_bar2_map, bar2map_len);
11996                 if (!phba->sli4_hba.dpp_regs_memmap_p) {
11997                         dev_err(&pdev->dev,
11998                            "ioremap failed for SLI4 HBA dpp registers.\n");
11999                         error = -ENOMEM;
12000                         goto out_iounmap_all;
12001                 }
12002                 phba->pci_bar4_memmap_p = phba->sli4_hba.dpp_regs_memmap_p;
12003         }
12004
12005         /* Set up the EQ/CQ register handeling functions now */
12006         switch (if_type) {
12007         case LPFC_SLI_INTF_IF_TYPE_0:
12008         case LPFC_SLI_INTF_IF_TYPE_2:
12009                 phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_eq_clr_intr;
12010                 phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_write_eq_db;
12011                 phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_write_cq_db;
12012                 break;
12013         case LPFC_SLI_INTF_IF_TYPE_6:
12014                 phba->sli4_hba.sli4_eq_clr_intr = lpfc_sli4_if6_eq_clr_intr;
12015                 phba->sli4_hba.sli4_write_eq_db = lpfc_sli4_if6_write_eq_db;
12016                 phba->sli4_hba.sli4_write_cq_db = lpfc_sli4_if6_write_cq_db;
12017                 break;
12018         default:
12019                 break;
12020         }
12021
12022         return 0;
12023
12024 out_iounmap_all:
12025         if (phba->sli4_hba.drbl_regs_memmap_p)
12026                 iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12027 out_iounmap_ctrl:
12028         if (phba->sli4_hba.ctrl_regs_memmap_p)
12029                 iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12030 out_iounmap_conf:
12031         iounmap(phba->sli4_hba.conf_regs_memmap_p);
12032
12033         return error;
12034 }
12035
12036 /**
12037  * lpfc_sli4_pci_mem_unset - Unset SLI4 HBA PCI memory space.
12038  * @phba: pointer to lpfc hba data structure.
12039  *
12040  * This routine is invoked to unset the PCI device memory space for device
12041  * with SLI-4 interface spec.
12042  **/
12043 static void
12044 lpfc_sli4_pci_mem_unset(struct lpfc_hba *phba)
12045 {
12046         uint32_t if_type;
12047         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12048
12049         switch (if_type) {
12050         case LPFC_SLI_INTF_IF_TYPE_0:
12051                 iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12052                 iounmap(phba->sli4_hba.ctrl_regs_memmap_p);
12053                 iounmap(phba->sli4_hba.conf_regs_memmap_p);
12054                 break;
12055         case LPFC_SLI_INTF_IF_TYPE_2:
12056                 iounmap(phba->sli4_hba.conf_regs_memmap_p);
12057                 break;
12058         case LPFC_SLI_INTF_IF_TYPE_6:
12059                 iounmap(phba->sli4_hba.drbl_regs_memmap_p);
12060                 iounmap(phba->sli4_hba.conf_regs_memmap_p);
12061                 if (phba->sli4_hba.dpp_regs_memmap_p)
12062                         iounmap(phba->sli4_hba.dpp_regs_memmap_p);
12063                 break;
12064         case LPFC_SLI_INTF_IF_TYPE_1:
12065                 break;
12066         default:
12067                 dev_printk(KERN_ERR, &phba->pcidev->dev,
12068                            "FATAL - unsupported SLI4 interface type - %d\n",
12069                            if_type);
12070                 break;
12071         }
12072 }
12073
12074 /**
12075  * lpfc_sli_enable_msix - Enable MSI-X interrupt mode on SLI-3 device
12076  * @phba: pointer to lpfc hba data structure.
12077  *
12078  * This routine is invoked to enable the MSI-X interrupt vectors to device
12079  * with SLI-3 interface specs.
12080  *
12081  * Return codes
12082  *   0 - successful
12083  *   other values - error
12084  **/
12085 static int
12086 lpfc_sli_enable_msix(struct lpfc_hba *phba)
12087 {
12088         int rc;
12089         LPFC_MBOXQ_t *pmb;
12090
12091         /* Set up MSI-X multi-message vectors */
12092         rc = pci_alloc_irq_vectors(phba->pcidev,
12093                         LPFC_MSIX_VECTORS, LPFC_MSIX_VECTORS, PCI_IRQ_MSIX);
12094         if (rc < 0) {
12095                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12096                                 "0420 PCI enable MSI-X failed (%d)\n", rc);
12097                 goto vec_fail_out;
12098         }
12099
12100         /*
12101          * Assign MSI-X vectors to interrupt handlers
12102          */
12103
12104         /* vector-0 is associated to slow-path handler */
12105         rc = request_irq(pci_irq_vector(phba->pcidev, 0),
12106                          &lpfc_sli_sp_intr_handler, 0,
12107                          LPFC_SP_DRIVER_HANDLER_NAME, phba);
12108         if (rc) {
12109                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12110                                 "0421 MSI-X slow-path request_irq failed "
12111                                 "(%d)\n", rc);
12112                 goto msi_fail_out;
12113         }
12114
12115         /* vector-1 is associated to fast-path handler */
12116         rc = request_irq(pci_irq_vector(phba->pcidev, 1),
12117                          &lpfc_sli_fp_intr_handler, 0,
12118                          LPFC_FP_DRIVER_HANDLER_NAME, phba);
12119
12120         if (rc) {
12121                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12122                                 "0429 MSI-X fast-path request_irq failed "
12123                                 "(%d)\n", rc);
12124                 goto irq_fail_out;
12125         }
12126
12127         /*
12128          * Configure HBA MSI-X attention conditions to messages
12129          */
12130         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12131
12132         if (!pmb) {
12133                 rc = -ENOMEM;
12134                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12135                                 "0474 Unable to allocate memory for issuing "
12136                                 "MBOX_CONFIG_MSI command\n");
12137                 goto mem_fail_out;
12138         }
12139         rc = lpfc_config_msi(phba, pmb);
12140         if (rc)
12141                 goto mbx_fail_out;
12142         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
12143         if (rc != MBX_SUCCESS) {
12144                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
12145                                 "0351 Config MSI mailbox command failed, "
12146                                 "mbxCmd x%x, mbxStatus x%x\n",
12147                                 pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus);
12148                 goto mbx_fail_out;
12149         }
12150
12151         /* Free memory allocated for mailbox command */
12152         mempool_free(pmb, phba->mbox_mem_pool);
12153         return rc;
12154
12155 mbx_fail_out:
12156         /* Free memory allocated for mailbox command */
12157         mempool_free(pmb, phba->mbox_mem_pool);
12158
12159 mem_fail_out:
12160         /* free the irq already requested */
12161         free_irq(pci_irq_vector(phba->pcidev, 1), phba);
12162
12163 irq_fail_out:
12164         /* free the irq already requested */
12165         free_irq(pci_irq_vector(phba->pcidev, 0), phba);
12166
12167 msi_fail_out:
12168         /* Unconfigure MSI-X capability structure */
12169         pci_free_irq_vectors(phba->pcidev);
12170
12171 vec_fail_out:
12172         return rc;
12173 }
12174
12175 /**
12176  * lpfc_sli_enable_msi - Enable MSI interrupt mode on SLI-3 device.
12177  * @phba: pointer to lpfc hba data structure.
12178  *
12179  * This routine is invoked to enable the MSI interrupt mode to device with
12180  * SLI-3 interface spec. The kernel function pci_enable_msi() is called to
12181  * enable the MSI vector. The device driver is responsible for calling the
12182  * request_irq() to register MSI vector with a interrupt the handler, which
12183  * is done in this function.
12184  *
12185  * Return codes
12186  *      0 - successful
12187  *      other values - error
12188  */
12189 static int
12190 lpfc_sli_enable_msi(struct lpfc_hba *phba)
12191 {
12192         int rc;
12193
12194         rc = pci_enable_msi(phba->pcidev);
12195         if (!rc)
12196                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12197                                 "0012 PCI enable MSI mode success.\n");
12198         else {
12199                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12200                                 "0471 PCI enable MSI mode failed (%d)\n", rc);
12201                 return rc;
12202         }
12203
12204         rc = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12205                          0, LPFC_DRIVER_NAME, phba);
12206         if (rc) {
12207                 pci_disable_msi(phba->pcidev);
12208                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
12209                                 "0478 MSI request_irq failed (%d)\n", rc);
12210         }
12211         return rc;
12212 }
12213
12214 /**
12215  * lpfc_sli_enable_intr - Enable device interrupt to SLI-3 device.
12216  * @phba: pointer to lpfc hba data structure.
12217  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
12218  *
12219  * This routine is invoked to enable device interrupt and associate driver's
12220  * interrupt handler(s) to interrupt vector(s) to device with SLI-3 interface
12221  * spec. Depends on the interrupt mode configured to the driver, the driver
12222  * will try to fallback from the configured interrupt mode to an interrupt
12223  * mode which is supported by the platform, kernel, and device in the order
12224  * of:
12225  * MSI-X -> MSI -> IRQ.
12226  *
12227  * Return codes
12228  *   0 - successful
12229  *   other values - error
12230  **/
12231 static uint32_t
12232 lpfc_sli_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
12233 {
12234         uint32_t intr_mode = LPFC_INTR_ERROR;
12235         int retval;
12236
12237         /* Need to issue conf_port mbox cmd before conf_msi mbox cmd */
12238         retval = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
12239         if (retval)
12240                 return intr_mode;
12241         phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
12242
12243         if (cfg_mode == 2) {
12244                 /* Now, try to enable MSI-X interrupt mode */
12245                 retval = lpfc_sli_enable_msix(phba);
12246                 if (!retval) {
12247                         /* Indicate initialization to MSI-X mode */
12248                         phba->intr_type = MSIX;
12249                         intr_mode = 2;
12250                 }
12251         }
12252
12253         /* Fallback to MSI if MSI-X initialization failed */
12254         if (cfg_mode >= 1 && phba->intr_type == NONE) {
12255                 retval = lpfc_sli_enable_msi(phba);
12256                 if (!retval) {
12257                         /* Indicate initialization to MSI mode */
12258                         phba->intr_type = MSI;
12259                         intr_mode = 1;
12260                 }
12261         }
12262
12263         /* Fallback to INTx if both MSI-X/MSI initalization failed */
12264         if (phba->intr_type == NONE) {
12265                 retval = request_irq(phba->pcidev->irq, lpfc_sli_intr_handler,
12266                                      IRQF_SHARED, LPFC_DRIVER_NAME, phba);
12267                 if (!retval) {
12268                         /* Indicate initialization to INTx mode */
12269                         phba->intr_type = INTx;
12270                         intr_mode = 0;
12271                 }
12272         }
12273         return intr_mode;
12274 }
12275
12276 /**
12277  * lpfc_sli_disable_intr - Disable device interrupt to SLI-3 device.
12278  * @phba: pointer to lpfc hba data structure.
12279  *
12280  * This routine is invoked to disable device interrupt and disassociate the
12281  * driver's interrupt handler(s) from interrupt vector(s) to device with
12282  * SLI-3 interface spec. Depending on the interrupt mode, the driver will
12283  * release the interrupt vector(s) for the message signaled interrupt.
12284  **/
12285 static void
12286 lpfc_sli_disable_intr(struct lpfc_hba *phba)
12287 {
12288         int nr_irqs, i;
12289
12290         if (phba->intr_type == MSIX)
12291                 nr_irqs = LPFC_MSIX_VECTORS;
12292         else
12293                 nr_irqs = 1;
12294
12295         for (i = 0; i < nr_irqs; i++)
12296                 free_irq(pci_irq_vector(phba->pcidev, i), phba);
12297         pci_free_irq_vectors(phba->pcidev);
12298
12299         /* Reset interrupt management states */
12300         phba->intr_type = NONE;
12301         phba->sli.slistat.sli_intr = 0;
12302 }
12303
12304 /**
12305  * lpfc_find_cpu_handle - Find the CPU that corresponds to the specified Queue
12306  * @phba: pointer to lpfc hba data structure.
12307  * @id: EQ vector index or Hardware Queue index
12308  * @match: LPFC_FIND_BY_EQ = match by EQ
12309  *         LPFC_FIND_BY_HDWQ = match by Hardware Queue
12310  * Return the CPU that matches the selection criteria
12311  */
12312 static uint16_t
12313 lpfc_find_cpu_handle(struct lpfc_hba *phba, uint16_t id, int match)
12314 {
12315         struct lpfc_vector_map_info *cpup;
12316         int cpu;
12317
12318         /* Loop through all CPUs */
12319         for_each_present_cpu(cpu) {
12320                 cpup = &phba->sli4_hba.cpu_map[cpu];
12321
12322                 /* If we are matching by EQ, there may be multiple CPUs using
12323                  * using the same vector, so select the one with
12324                  * LPFC_CPU_FIRST_IRQ set.
12325                  */
12326                 if ((match == LPFC_FIND_BY_EQ) &&
12327                     (cpup->flag & LPFC_CPU_FIRST_IRQ) &&
12328                     (cpup->eq == id))
12329                         return cpu;
12330
12331                 /* If matching by HDWQ, select the first CPU that matches */
12332                 if ((match == LPFC_FIND_BY_HDWQ) && (cpup->hdwq == id))
12333                         return cpu;
12334         }
12335         return 0;
12336 }
12337
12338 #ifdef CONFIG_X86
12339 /**
12340  * lpfc_find_hyper - Determine if the CPU map entry is hyper-threaded
12341  * @phba: pointer to lpfc hba data structure.
12342  * @cpu: CPU map index
12343  * @phys_id: CPU package physical id
12344  * @core_id: CPU core id
12345  */
12346 static int
12347 lpfc_find_hyper(struct lpfc_hba *phba, int cpu,
12348                 uint16_t phys_id, uint16_t core_id)
12349 {
12350         struct lpfc_vector_map_info *cpup;
12351         int idx;
12352
12353         for_each_present_cpu(idx) {
12354                 cpup = &phba->sli4_hba.cpu_map[idx];
12355                 /* Does the cpup match the one we are looking for */
12356                 if ((cpup->phys_id == phys_id) &&
12357                     (cpup->core_id == core_id) &&
12358                     (cpu != idx))
12359                         return 1;
12360         }
12361         return 0;
12362 }
12363 #endif
12364
12365 /*
12366  * lpfc_assign_eq_map_info - Assigns eq for vector_map structure
12367  * @phba: pointer to lpfc hba data structure.
12368  * @eqidx: index for eq and irq vector
12369  * @flag: flags to set for vector_map structure
12370  * @cpu: cpu used to index vector_map structure
12371  *
12372  * The routine assigns eq info into vector_map structure
12373  */
12374 static inline void
12375 lpfc_assign_eq_map_info(struct lpfc_hba *phba, uint16_t eqidx, uint16_t flag,
12376                         unsigned int cpu)
12377 {
12378         struct lpfc_vector_map_info *cpup = &phba->sli4_hba.cpu_map[cpu];
12379         struct lpfc_hba_eq_hdl *eqhdl = lpfc_get_eq_hdl(eqidx);
12380
12381         cpup->eq = eqidx;
12382         cpup->flag |= flag;
12383
12384         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12385                         "3336 Set Affinity: CPU %d irq %d eq %d flag x%x\n",
12386                         cpu, eqhdl->irq, cpup->eq, cpup->flag);
12387 }
12388
12389 /**
12390  * lpfc_cpu_map_array_init - Initialize cpu_map structure
12391  * @phba: pointer to lpfc hba data structure.
12392  *
12393  * The routine initializes the cpu_map array structure
12394  */
12395 static void
12396 lpfc_cpu_map_array_init(struct lpfc_hba *phba)
12397 {
12398         struct lpfc_vector_map_info *cpup;
12399         struct lpfc_eq_intr_info *eqi;
12400         int cpu;
12401
12402         for_each_possible_cpu(cpu) {
12403                 cpup = &phba->sli4_hba.cpu_map[cpu];
12404                 cpup->phys_id = LPFC_VECTOR_MAP_EMPTY;
12405                 cpup->core_id = LPFC_VECTOR_MAP_EMPTY;
12406                 cpup->hdwq = LPFC_VECTOR_MAP_EMPTY;
12407                 cpup->eq = LPFC_VECTOR_MAP_EMPTY;
12408                 cpup->flag = 0;
12409                 eqi = per_cpu_ptr(phba->sli4_hba.eq_info, cpu);
12410                 INIT_LIST_HEAD(&eqi->list);
12411                 eqi->icnt = 0;
12412         }
12413 }
12414
12415 /**
12416  * lpfc_hba_eq_hdl_array_init - Initialize hba_eq_hdl structure
12417  * @phba: pointer to lpfc hba data structure.
12418  *
12419  * The routine initializes the hba_eq_hdl array structure
12420  */
12421 static void
12422 lpfc_hba_eq_hdl_array_init(struct lpfc_hba *phba)
12423 {
12424         struct lpfc_hba_eq_hdl *eqhdl;
12425         int i;
12426
12427         for (i = 0; i < phba->cfg_irq_chann; i++) {
12428                 eqhdl = lpfc_get_eq_hdl(i);
12429                 eqhdl->irq = LPFC_IRQ_EMPTY;
12430                 eqhdl->phba = phba;
12431         }
12432 }
12433
12434 /**
12435  * lpfc_cpu_affinity_check - Check vector CPU affinity mappings
12436  * @phba: pointer to lpfc hba data structure.
12437  * @vectors: number of msix vectors allocated.
12438  *
12439  * The routine will figure out the CPU affinity assignment for every
12440  * MSI-X vector allocated for the HBA.
12441  * In addition, the CPU to IO channel mapping will be calculated
12442  * and the phba->sli4_hba.cpu_map array will reflect this.
12443  */
12444 static void
12445 lpfc_cpu_affinity_check(struct lpfc_hba *phba, int vectors)
12446 {
12447         int i, cpu, idx, next_idx, new_cpu, start_cpu, first_cpu;
12448         int max_phys_id, min_phys_id;
12449         int max_core_id, min_core_id;
12450         struct lpfc_vector_map_info *cpup;
12451         struct lpfc_vector_map_info *new_cpup;
12452 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12453         struct lpfc_hdwq_stat *c_stat;
12454 #endif
12455
12456         max_phys_id = 0;
12457         min_phys_id = LPFC_VECTOR_MAP_EMPTY;
12458         max_core_id = 0;
12459         min_core_id = LPFC_VECTOR_MAP_EMPTY;
12460
12461         /* Update CPU map with physical id and core id of each CPU */
12462         for_each_present_cpu(cpu) {
12463                 cpup = &phba->sli4_hba.cpu_map[cpu];
12464 #ifdef CONFIG_X86
12465                 cpup->phys_id = topology_physical_package_id(cpu);
12466                 cpup->core_id = topology_core_id(cpu);
12467                 if (lpfc_find_hyper(phba, cpu, cpup->phys_id, cpup->core_id))
12468                         cpup->flag |= LPFC_CPU_MAP_HYPER;
12469 #else
12470                 /* No distinction between CPUs for other platforms */
12471                 cpup->phys_id = 0;
12472                 cpup->core_id = cpu;
12473 #endif
12474
12475                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12476                                 "3328 CPU %d physid %d coreid %d flag x%x\n",
12477                                 cpu, cpup->phys_id, cpup->core_id, cpup->flag);
12478
12479                 if (cpup->phys_id > max_phys_id)
12480                         max_phys_id = cpup->phys_id;
12481                 if (cpup->phys_id < min_phys_id)
12482                         min_phys_id = cpup->phys_id;
12483
12484                 if (cpup->core_id > max_core_id)
12485                         max_core_id = cpup->core_id;
12486                 if (cpup->core_id < min_core_id)
12487                         min_core_id = cpup->core_id;
12488         }
12489
12490         /* After looking at each irq vector assigned to this pcidev, its
12491          * possible to see that not ALL CPUs have been accounted for.
12492          * Next we will set any unassigned (unaffinitized) cpu map
12493          * entries to a IRQ on the same phys_id.
12494          */
12495         first_cpu = cpumask_first(cpu_present_mask);
12496         start_cpu = first_cpu;
12497
12498         for_each_present_cpu(cpu) {
12499                 cpup = &phba->sli4_hba.cpu_map[cpu];
12500
12501                 /* Is this CPU entry unassigned */
12502                 if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12503                         /* Mark CPU as IRQ not assigned by the kernel */
12504                         cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12505
12506                         /* If so, find a new_cpup that is on the SAME
12507                          * phys_id as cpup. start_cpu will start where we
12508                          * left off so all unassigned entries don't get assgined
12509                          * the IRQ of the first entry.
12510                          */
12511                         new_cpu = start_cpu;
12512                         for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12513                                 new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12514                                 if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12515                                     (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY) &&
12516                                     (new_cpup->phys_id == cpup->phys_id))
12517                                         goto found_same;
12518                                 new_cpu = lpfc_next_present_cpu(new_cpu);
12519                         }
12520                         /* At this point, we leave the CPU as unassigned */
12521                         continue;
12522 found_same:
12523                         /* We found a matching phys_id, so copy the IRQ info */
12524                         cpup->eq = new_cpup->eq;
12525
12526                         /* Bump start_cpu to the next slot to minmize the
12527                          * chance of having multiple unassigned CPU entries
12528                          * selecting the same IRQ.
12529                          */
12530                         start_cpu = lpfc_next_present_cpu(new_cpu);
12531
12532                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12533                                         "3337 Set Affinity: CPU %d "
12534                                         "eq %d from peer cpu %d same "
12535                                         "phys_id (%d)\n",
12536                                         cpu, cpup->eq, new_cpu,
12537                                         cpup->phys_id);
12538                 }
12539         }
12540
12541         /* Set any unassigned cpu map entries to a IRQ on any phys_id */
12542         start_cpu = first_cpu;
12543
12544         for_each_present_cpu(cpu) {
12545                 cpup = &phba->sli4_hba.cpu_map[cpu];
12546
12547                 /* Is this entry unassigned */
12548                 if (cpup->eq == LPFC_VECTOR_MAP_EMPTY) {
12549                         /* Mark it as IRQ not assigned by the kernel */
12550                         cpup->flag |= LPFC_CPU_MAP_UNASSIGN;
12551
12552                         /* If so, find a new_cpup thats on ANY phys_id
12553                          * as the cpup. start_cpu will start where we
12554                          * left off so all unassigned entries don't get
12555                          * assigned the IRQ of the first entry.
12556                          */
12557                         new_cpu = start_cpu;
12558                         for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12559                                 new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12560                                 if (!(new_cpup->flag & LPFC_CPU_MAP_UNASSIGN) &&
12561                                     (new_cpup->eq != LPFC_VECTOR_MAP_EMPTY))
12562                                         goto found_any;
12563                                 new_cpu = lpfc_next_present_cpu(new_cpu);
12564                         }
12565                         /* We should never leave an entry unassigned */
12566                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12567                                         "3339 Set Affinity: CPU %d "
12568                                         "eq %d UNASSIGNED\n",
12569                                         cpup->hdwq, cpup->eq);
12570                         continue;
12571 found_any:
12572                         /* We found an available entry, copy the IRQ info */
12573                         cpup->eq = new_cpup->eq;
12574
12575                         /* Bump start_cpu to the next slot to minmize the
12576                          * chance of having multiple unassigned CPU entries
12577                          * selecting the same IRQ.
12578                          */
12579                         start_cpu = lpfc_next_present_cpu(new_cpu);
12580
12581                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12582                                         "3338 Set Affinity: CPU %d "
12583                                         "eq %d from peer cpu %d (%d/%d)\n",
12584                                         cpu, cpup->eq, new_cpu,
12585                                         new_cpup->phys_id, new_cpup->core_id);
12586                 }
12587         }
12588
12589         /* Assign hdwq indices that are unique across all cpus in the map
12590          * that are also FIRST_CPUs.
12591          */
12592         idx = 0;
12593         for_each_present_cpu(cpu) {
12594                 cpup = &phba->sli4_hba.cpu_map[cpu];
12595
12596                 /* Only FIRST IRQs get a hdwq index assignment. */
12597                 if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12598                         continue;
12599
12600                 /* 1 to 1, the first LPFC_CPU_FIRST_IRQ cpus to a unique hdwq */
12601                 cpup->hdwq = idx;
12602                 idx++;
12603                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12604                                 "3333 Set Affinity: CPU %d (phys %d core %d): "
12605                                 "hdwq %d eq %d flg x%x\n",
12606                                 cpu, cpup->phys_id, cpup->core_id,
12607                                 cpup->hdwq, cpup->eq, cpup->flag);
12608         }
12609         /* Associate a hdwq with each cpu_map entry
12610          * This will be 1 to 1 - hdwq to cpu, unless there are less
12611          * hardware queues then CPUs. For that case we will just round-robin
12612          * the available hardware queues as they get assigned to CPUs.
12613          * The next_idx is the idx from the FIRST_CPU loop above to account
12614          * for irq_chann < hdwq.  The idx is used for round-robin assignments
12615          * and needs to start at 0.
12616          */
12617         next_idx = idx;
12618         start_cpu = 0;
12619         idx = 0;
12620         for_each_present_cpu(cpu) {
12621                 cpup = &phba->sli4_hba.cpu_map[cpu];
12622
12623                 /* FIRST cpus are already mapped. */
12624                 if (cpup->flag & LPFC_CPU_FIRST_IRQ)
12625                         continue;
12626
12627                 /* If the cfg_irq_chann < cfg_hdw_queue, set the hdwq
12628                  * of the unassigned cpus to the next idx so that all
12629                  * hdw queues are fully utilized.
12630                  */
12631                 if (next_idx < phba->cfg_hdw_queue) {
12632                         cpup->hdwq = next_idx;
12633                         next_idx++;
12634                         continue;
12635                 }
12636
12637                 /* Not a First CPU and all hdw_queues are used.  Reuse a
12638                  * Hardware Queue for another CPU, so be smart about it
12639                  * and pick one that has its IRQ/EQ mapped to the same phys_id
12640                  * (CPU package) and core_id.
12641                  */
12642                 new_cpu = start_cpu;
12643                 for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12644                         new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12645                         if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12646                             new_cpup->phys_id == cpup->phys_id &&
12647                             new_cpup->core_id == cpup->core_id) {
12648                                 goto found_hdwq;
12649                         }
12650                         new_cpu = lpfc_next_present_cpu(new_cpu);
12651                 }
12652
12653                 /* If we can't match both phys_id and core_id,
12654                  * settle for just a phys_id match.
12655                  */
12656                 new_cpu = start_cpu;
12657                 for (i = 0; i < phba->sli4_hba.num_present_cpu; i++) {
12658                         new_cpup = &phba->sli4_hba.cpu_map[new_cpu];
12659                         if (new_cpup->hdwq != LPFC_VECTOR_MAP_EMPTY &&
12660                             new_cpup->phys_id == cpup->phys_id)
12661                                 goto found_hdwq;
12662                         new_cpu = lpfc_next_present_cpu(new_cpu);
12663                 }
12664
12665                 /* Otherwise just round robin on cfg_hdw_queue */
12666                 cpup->hdwq = idx % phba->cfg_hdw_queue;
12667                 idx++;
12668                 goto logit;
12669  found_hdwq:
12670                 /* We found an available entry, copy the IRQ info */
12671                 start_cpu = lpfc_next_present_cpu(new_cpu);
12672                 cpup->hdwq = new_cpup->hdwq;
12673  logit:
12674                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12675                                 "3335 Set Affinity: CPU %d (phys %d core %d): "
12676                                 "hdwq %d eq %d flg x%x\n",
12677                                 cpu, cpup->phys_id, cpup->core_id,
12678                                 cpup->hdwq, cpup->eq, cpup->flag);
12679         }
12680
12681         /*
12682          * Initialize the cpu_map slots for not-present cpus in case
12683          * a cpu is hot-added. Perform a simple hdwq round robin assignment.
12684          */
12685         idx = 0;
12686         for_each_possible_cpu(cpu) {
12687                 cpup = &phba->sli4_hba.cpu_map[cpu];
12688 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12689                 c_stat = per_cpu_ptr(phba->sli4_hba.c_stat, cpu);
12690                 c_stat->hdwq_no = cpup->hdwq;
12691 #endif
12692                 if (cpup->hdwq != LPFC_VECTOR_MAP_EMPTY)
12693                         continue;
12694
12695                 cpup->hdwq = idx++ % phba->cfg_hdw_queue;
12696 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
12697                 c_stat->hdwq_no = cpup->hdwq;
12698 #endif
12699                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12700                                 "3340 Set Affinity: not present "
12701                                 "CPU %d hdwq %d\n",
12702                                 cpu, cpup->hdwq);
12703         }
12704
12705         /* The cpu_map array will be used later during initialization
12706          * when EQ / CQ / WQs are allocated and configured.
12707          */
12708         return;
12709 }
12710
12711 /**
12712  * lpfc_cpuhp_get_eq
12713  *
12714  * @phba:   pointer to lpfc hba data structure.
12715  * @cpu:    cpu going offline
12716  * @eqlist: eq list to append to
12717  */
12718 static int
12719 lpfc_cpuhp_get_eq(struct lpfc_hba *phba, unsigned int cpu,
12720                   struct list_head *eqlist)
12721 {
12722         const struct cpumask *maskp;
12723         struct lpfc_queue *eq;
12724         struct cpumask *tmp;
12725         u16 idx;
12726
12727         tmp = kzalloc(cpumask_size(), GFP_KERNEL);
12728         if (!tmp)
12729                 return -ENOMEM;
12730
12731         for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12732                 maskp = pci_irq_get_affinity(phba->pcidev, idx);
12733                 if (!maskp)
12734                         continue;
12735                 /*
12736                  * if irq is not affinitized to the cpu going
12737                  * then we don't need to poll the eq attached
12738                  * to it.
12739                  */
12740                 if (!cpumask_and(tmp, maskp, cpumask_of(cpu)))
12741                         continue;
12742                 /* get the cpus that are online and are affini-
12743                  * tized to this irq vector.  If the count is
12744                  * more than 1 then cpuhp is not going to shut-
12745                  * down this vector.  Since this cpu has not
12746                  * gone offline yet, we need >1.
12747                  */
12748                 cpumask_and(tmp, maskp, cpu_online_mask);
12749                 if (cpumask_weight(tmp) > 1)
12750                         continue;
12751
12752                 /* Now that we have an irq to shutdown, get the eq
12753                  * mapped to this irq.  Note: multiple hdwq's in
12754                  * the software can share an eq, but eventually
12755                  * only eq will be mapped to this vector
12756                  */
12757                 eq = phba->sli4_hba.hba_eq_hdl[idx].eq;
12758                 list_add(&eq->_poll_list, eqlist);
12759         }
12760         kfree(tmp);
12761         return 0;
12762 }
12763
12764 static void __lpfc_cpuhp_remove(struct lpfc_hba *phba)
12765 {
12766         if (phba->sli_rev != LPFC_SLI_REV4)
12767                 return;
12768
12769         cpuhp_state_remove_instance_nocalls(lpfc_cpuhp_state,
12770                                             &phba->cpuhp);
12771         /*
12772          * unregistering the instance doesn't stop the polling
12773          * timer. Wait for the poll timer to retire.
12774          */
12775         synchronize_rcu();
12776         del_timer_sync(&phba->cpuhp_poll_timer);
12777 }
12778
12779 static void lpfc_cpuhp_remove(struct lpfc_hba *phba)
12780 {
12781         if (phba->pport &&
12782             test_bit(FC_OFFLINE_MODE, &phba->pport->fc_flag))
12783                 return;
12784
12785         __lpfc_cpuhp_remove(phba);
12786 }
12787
12788 static void lpfc_cpuhp_add(struct lpfc_hba *phba)
12789 {
12790         if (phba->sli_rev != LPFC_SLI_REV4)
12791                 return;
12792
12793         rcu_read_lock();
12794
12795         if (!list_empty(&phba->poll_list))
12796                 mod_timer(&phba->cpuhp_poll_timer,
12797                           jiffies + msecs_to_jiffies(LPFC_POLL_HB));
12798
12799         rcu_read_unlock();
12800
12801         cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state,
12802                                          &phba->cpuhp);
12803 }
12804
12805 static int __lpfc_cpuhp_checks(struct lpfc_hba *phba, int *retval)
12806 {
12807         if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
12808                 *retval = -EAGAIN;
12809                 return true;
12810         }
12811
12812         if (phba->sli_rev != LPFC_SLI_REV4) {
12813                 *retval = 0;
12814                 return true;
12815         }
12816
12817         /* proceed with the hotplug */
12818         return false;
12819 }
12820
12821 /**
12822  * lpfc_irq_set_aff - set IRQ affinity
12823  * @eqhdl: EQ handle
12824  * @cpu: cpu to set affinity
12825  *
12826  **/
12827 static inline void
12828 lpfc_irq_set_aff(struct lpfc_hba_eq_hdl *eqhdl, unsigned int cpu)
12829 {
12830         cpumask_clear(&eqhdl->aff_mask);
12831         cpumask_set_cpu(cpu, &eqhdl->aff_mask);
12832         irq_set_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12833         irq_set_affinity(eqhdl->irq, &eqhdl->aff_mask);
12834 }
12835
12836 /**
12837  * lpfc_irq_clear_aff - clear IRQ affinity
12838  * @eqhdl: EQ handle
12839  *
12840  **/
12841 static inline void
12842 lpfc_irq_clear_aff(struct lpfc_hba_eq_hdl *eqhdl)
12843 {
12844         cpumask_clear(&eqhdl->aff_mask);
12845         irq_clear_status_flags(eqhdl->irq, IRQ_NO_BALANCING);
12846 }
12847
12848 /**
12849  * lpfc_irq_rebalance - rebalances IRQ affinity according to cpuhp event
12850  * @phba: pointer to HBA context object.
12851  * @cpu: cpu going offline/online
12852  * @offline: true, cpu is going offline. false, cpu is coming online.
12853  *
12854  * If cpu is going offline, we'll try our best effort to find the next
12855  * online cpu on the phba's original_mask and migrate all offlining IRQ
12856  * affinities.
12857  *
12858  * If cpu is coming online, reaffinitize the IRQ back to the onlining cpu.
12859  *
12860  * Note: Call only if NUMA or NHT mode is enabled, otherwise rely on
12861  *       PCI_IRQ_AFFINITY to auto-manage IRQ affinity.
12862  *
12863  **/
12864 static void
12865 lpfc_irq_rebalance(struct lpfc_hba *phba, unsigned int cpu, bool offline)
12866 {
12867         struct lpfc_vector_map_info *cpup;
12868         struct cpumask *aff_mask;
12869         unsigned int cpu_select, cpu_next, idx;
12870         const struct cpumask *orig_mask;
12871
12872         if (phba->irq_chann_mode == NORMAL_MODE)
12873                 return;
12874
12875         orig_mask = &phba->sli4_hba.irq_aff_mask;
12876
12877         if (!cpumask_test_cpu(cpu, orig_mask))
12878                 return;
12879
12880         cpup = &phba->sli4_hba.cpu_map[cpu];
12881
12882         if (!(cpup->flag & LPFC_CPU_FIRST_IRQ))
12883                 return;
12884
12885         if (offline) {
12886                 /* Find next online CPU on original mask */
12887                 cpu_next = cpumask_next_wrap(cpu, orig_mask, cpu, true);
12888                 cpu_select = lpfc_next_online_cpu(orig_mask, cpu_next);
12889
12890                 /* Found a valid CPU */
12891                 if ((cpu_select < nr_cpu_ids) && (cpu_select != cpu)) {
12892                         /* Go through each eqhdl and ensure offlining
12893                          * cpu aff_mask is migrated
12894                          */
12895                         for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
12896                                 aff_mask = lpfc_get_aff_mask(idx);
12897
12898                                 /* Migrate affinity */
12899                                 if (cpumask_test_cpu(cpu, aff_mask))
12900                                         lpfc_irq_set_aff(lpfc_get_eq_hdl(idx),
12901                                                          cpu_select);
12902                         }
12903                 } else {
12904                         /* Rely on irqbalance if no online CPUs left on NUMA */
12905                         for (idx = 0; idx < phba->cfg_irq_chann; idx++)
12906                                 lpfc_irq_clear_aff(lpfc_get_eq_hdl(idx));
12907                 }
12908         } else {
12909                 /* Migrate affinity back to this CPU */
12910                 lpfc_irq_set_aff(lpfc_get_eq_hdl(cpup->eq), cpu);
12911         }
12912 }
12913
12914 static int lpfc_cpu_offline(unsigned int cpu, struct hlist_node *node)
12915 {
12916         struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12917         struct lpfc_queue *eq, *next;
12918         LIST_HEAD(eqlist);
12919         int retval;
12920
12921         if (!phba) {
12922                 WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12923                 return 0;
12924         }
12925
12926         if (__lpfc_cpuhp_checks(phba, &retval))
12927                 return retval;
12928
12929         lpfc_irq_rebalance(phba, cpu, true);
12930
12931         retval = lpfc_cpuhp_get_eq(phba, cpu, &eqlist);
12932         if (retval)
12933                 return retval;
12934
12935         /* start polling on these eq's */
12936         list_for_each_entry_safe(eq, next, &eqlist, _poll_list) {
12937                 list_del_init(&eq->_poll_list);
12938                 lpfc_sli4_start_polling(eq);
12939         }
12940
12941         return 0;
12942 }
12943
12944 static int lpfc_cpu_online(unsigned int cpu, struct hlist_node *node)
12945 {
12946         struct lpfc_hba *phba = hlist_entry_safe(node, struct lpfc_hba, cpuhp);
12947         struct lpfc_queue *eq, *next;
12948         unsigned int n;
12949         int retval;
12950
12951         if (!phba) {
12952                 WARN_ONCE(!phba, "cpu: %u. phba:NULL", raw_smp_processor_id());
12953                 return 0;
12954         }
12955
12956         if (__lpfc_cpuhp_checks(phba, &retval))
12957                 return retval;
12958
12959         lpfc_irq_rebalance(phba, cpu, false);
12960
12961         list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list) {
12962                 n = lpfc_find_cpu_handle(phba, eq->hdwq, LPFC_FIND_BY_HDWQ);
12963                 if (n == cpu)
12964                         lpfc_sli4_stop_polling(eq);
12965         }
12966
12967         return 0;
12968 }
12969
12970 /**
12971  * lpfc_sli4_enable_msix - Enable MSI-X interrupt mode to SLI-4 device
12972  * @phba: pointer to lpfc hba data structure.
12973  *
12974  * This routine is invoked to enable the MSI-X interrupt vectors to device
12975  * with SLI-4 interface spec.  It also allocates MSI-X vectors and maps them
12976  * to cpus on the system.
12977  *
12978  * When cfg_irq_numa is enabled, the adapter will only allocate vectors for
12979  * the number of cpus on the same numa node as this adapter.  The vectors are
12980  * allocated without requesting OS affinity mapping.  A vector will be
12981  * allocated and assigned to each online and offline cpu.  If the cpu is
12982  * online, then affinity will be set to that cpu.  If the cpu is offline, then
12983  * affinity will be set to the nearest peer cpu within the numa node that is
12984  * online.  If there are no online cpus within the numa node, affinity is not
12985  * assigned and the OS may do as it pleases. Note: cpu vector affinity mapping
12986  * is consistent with the way cpu online/offline is handled when cfg_irq_numa is
12987  * configured.
12988  *
12989  * If numa mode is not enabled and there is more than 1 vector allocated, then
12990  * the driver relies on the managed irq interface where the OS assigns vector to
12991  * cpu affinity.  The driver will then use that affinity mapping to setup its
12992  * cpu mapping table.
12993  *
12994  * Return codes
12995  * 0 - successful
12996  * other values - error
12997  **/
12998 static int
12999 lpfc_sli4_enable_msix(struct lpfc_hba *phba)
13000 {
13001         int vectors, rc, index;
13002         char *name;
13003         const struct cpumask *aff_mask = NULL;
13004         unsigned int cpu = 0, cpu_cnt = 0, cpu_select = nr_cpu_ids;
13005         struct lpfc_vector_map_info *cpup;
13006         struct lpfc_hba_eq_hdl *eqhdl;
13007         const struct cpumask *maskp;
13008         unsigned int flags = PCI_IRQ_MSIX;
13009
13010         /* Set up MSI-X multi-message vectors */
13011         vectors = phba->cfg_irq_chann;
13012
13013         if (phba->irq_chann_mode != NORMAL_MODE)
13014                 aff_mask = &phba->sli4_hba.irq_aff_mask;
13015
13016         if (aff_mask) {
13017                 cpu_cnt = cpumask_weight(aff_mask);
13018                 vectors = min(phba->cfg_irq_chann, cpu_cnt);
13019
13020                 /* cpu: iterates over aff_mask including offline or online
13021                  * cpu_select: iterates over online aff_mask to set affinity
13022                  */
13023                 cpu = cpumask_first(aff_mask);
13024                 cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13025         } else {
13026                 flags |= PCI_IRQ_AFFINITY;
13027         }
13028
13029         rc = pci_alloc_irq_vectors(phba->pcidev, 1, vectors, flags);
13030         if (rc < 0) {
13031                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13032                                 "0484 PCI enable MSI-X failed (%d)\n", rc);
13033                 goto vec_fail_out;
13034         }
13035         vectors = rc;
13036
13037         /* Assign MSI-X vectors to interrupt handlers */
13038         for (index = 0; index < vectors; index++) {
13039                 eqhdl = lpfc_get_eq_hdl(index);
13040                 name = eqhdl->handler_name;
13041                 memset(name, 0, LPFC_SLI4_HANDLER_NAME_SZ);
13042                 snprintf(name, LPFC_SLI4_HANDLER_NAME_SZ,
13043                          LPFC_DRIVER_HANDLER_NAME"%d", index);
13044
13045                 eqhdl->idx = index;
13046                 rc = pci_irq_vector(phba->pcidev, index);
13047                 if (rc < 0) {
13048                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13049                                         "0489 MSI-X fast-path (%d) "
13050                                         "pci_irq_vec failed (%d)\n", index, rc);
13051                         goto cfg_fail_out;
13052                 }
13053                 eqhdl->irq = rc;
13054
13055                 rc = request_threaded_irq(eqhdl->irq,
13056                                           &lpfc_sli4_hba_intr_handler,
13057                                           &lpfc_sli4_hba_intr_handler_th,
13058                                           IRQF_ONESHOT, name, eqhdl);
13059                 if (rc) {
13060                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13061                                         "0486 MSI-X fast-path (%d) "
13062                                         "request_irq failed (%d)\n", index, rc);
13063                         goto cfg_fail_out;
13064                 }
13065
13066                 if (aff_mask) {
13067                         /* If found a neighboring online cpu, set affinity */
13068                         if (cpu_select < nr_cpu_ids)
13069                                 lpfc_irq_set_aff(eqhdl, cpu_select);
13070
13071                         /* Assign EQ to cpu_map */
13072                         lpfc_assign_eq_map_info(phba, index,
13073                                                 LPFC_CPU_FIRST_IRQ,
13074                                                 cpu);
13075
13076                         /* Iterate to next offline or online cpu in aff_mask */
13077                         cpu = cpumask_next(cpu, aff_mask);
13078
13079                         /* Find next online cpu in aff_mask to set affinity */
13080                         cpu_select = lpfc_next_online_cpu(aff_mask, cpu);
13081                 } else if (vectors == 1) {
13082                         cpu = cpumask_first(cpu_present_mask);
13083                         lpfc_assign_eq_map_info(phba, index, LPFC_CPU_FIRST_IRQ,
13084                                                 cpu);
13085                 } else {
13086                         maskp = pci_irq_get_affinity(phba->pcidev, index);
13087
13088                         /* Loop through all CPUs associated with vector index */
13089                         for_each_cpu_and(cpu, maskp, cpu_present_mask) {
13090                                 cpup = &phba->sli4_hba.cpu_map[cpu];
13091
13092                                 /* If this is the first CPU thats assigned to
13093                                  * this vector, set LPFC_CPU_FIRST_IRQ.
13094                                  *
13095                                  * With certain platforms its possible that irq
13096                                  * vectors are affinitized to all the cpu's.
13097                                  * This can result in each cpu_map.eq to be set
13098                                  * to the last vector, resulting in overwrite
13099                                  * of all the previous cpu_map.eq.  Ensure that
13100                                  * each vector receives a place in cpu_map.
13101                                  * Later call to lpfc_cpu_affinity_check will
13102                                  * ensure we are nicely balanced out.
13103                                  */
13104                                 if (cpup->eq != LPFC_VECTOR_MAP_EMPTY)
13105                                         continue;
13106                                 lpfc_assign_eq_map_info(phba, index,
13107                                                         LPFC_CPU_FIRST_IRQ,
13108                                                         cpu);
13109                                 break;
13110                         }
13111                 }
13112         }
13113
13114         if (vectors != phba->cfg_irq_chann) {
13115                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13116                                 "3238 Reducing IO channels to match number of "
13117                                 "MSI-X vectors, requested %d got %d\n",
13118                                 phba->cfg_irq_chann, vectors);
13119                 if (phba->cfg_irq_chann > vectors)
13120                         phba->cfg_irq_chann = vectors;
13121         }
13122
13123         return rc;
13124
13125 cfg_fail_out:
13126         /* free the irq already requested */
13127         for (--index; index >= 0; index--) {
13128                 eqhdl = lpfc_get_eq_hdl(index);
13129                 lpfc_irq_clear_aff(eqhdl);
13130                 free_irq(eqhdl->irq, eqhdl);
13131         }
13132
13133         /* Unconfigure MSI-X capability structure */
13134         pci_free_irq_vectors(phba->pcidev);
13135
13136 vec_fail_out:
13137         return rc;
13138 }
13139
13140 /**
13141  * lpfc_sli4_enable_msi - Enable MSI interrupt mode to SLI-4 device
13142  * @phba: pointer to lpfc hba data structure.
13143  *
13144  * This routine is invoked to enable the MSI interrupt mode to device with
13145  * SLI-4 interface spec. The kernel function pci_alloc_irq_vectors() is
13146  * called to enable the MSI vector. The device driver is responsible for
13147  * calling the request_irq() to register MSI vector with a interrupt the
13148  * handler, which is done in this function.
13149  *
13150  * Return codes
13151  *      0 - successful
13152  *      other values - error
13153  **/
13154 static int
13155 lpfc_sli4_enable_msi(struct lpfc_hba *phba)
13156 {
13157         int rc, index;
13158         unsigned int cpu;
13159         struct lpfc_hba_eq_hdl *eqhdl;
13160
13161         rc = pci_alloc_irq_vectors(phba->pcidev, 1, 1,
13162                                    PCI_IRQ_MSI | PCI_IRQ_AFFINITY);
13163         if (rc > 0)
13164                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13165                                 "0487 PCI enable MSI mode success.\n");
13166         else {
13167                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13168                                 "0488 PCI enable MSI mode failed (%d)\n", rc);
13169                 return rc ? rc : -1;
13170         }
13171
13172         rc = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13173                          0, LPFC_DRIVER_NAME, phba);
13174         if (rc) {
13175                 pci_free_irq_vectors(phba->pcidev);
13176                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13177                                 "0490 MSI request_irq failed (%d)\n", rc);
13178                 return rc;
13179         }
13180
13181         eqhdl = lpfc_get_eq_hdl(0);
13182         rc = pci_irq_vector(phba->pcidev, 0);
13183         if (rc < 0) {
13184                 pci_free_irq_vectors(phba->pcidev);
13185                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13186                                 "0496 MSI pci_irq_vec failed (%d)\n", rc);
13187                 return rc;
13188         }
13189         eqhdl->irq = rc;
13190
13191         cpu = cpumask_first(cpu_present_mask);
13192         lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ, cpu);
13193
13194         for (index = 0; index < phba->cfg_irq_chann; index++) {
13195                 eqhdl = lpfc_get_eq_hdl(index);
13196                 eqhdl->idx = index;
13197         }
13198
13199         return 0;
13200 }
13201
13202 /**
13203  * lpfc_sli4_enable_intr - Enable device interrupt to SLI-4 device
13204  * @phba: pointer to lpfc hba data structure.
13205  * @cfg_mode: Interrupt configuration mode (INTx, MSI or MSI-X).
13206  *
13207  * This routine is invoked to enable device interrupt and associate driver's
13208  * interrupt handler(s) to interrupt vector(s) to device with SLI-4
13209  * interface spec. Depends on the interrupt mode configured to the driver,
13210  * the driver will try to fallback from the configured interrupt mode to an
13211  * interrupt mode which is supported by the platform, kernel, and device in
13212  * the order of:
13213  * MSI-X -> MSI -> IRQ.
13214  *
13215  * Return codes
13216  *      Interrupt mode (2, 1, 0) - successful
13217  *      LPFC_INTR_ERROR - error
13218  **/
13219 static uint32_t
13220 lpfc_sli4_enable_intr(struct lpfc_hba *phba, uint32_t cfg_mode)
13221 {
13222         uint32_t intr_mode = LPFC_INTR_ERROR;
13223         int retval, idx;
13224
13225         if (cfg_mode == 2) {
13226                 /* Preparation before conf_msi mbox cmd */
13227                 retval = 0;
13228                 if (!retval) {
13229                         /* Now, try to enable MSI-X interrupt mode */
13230                         retval = lpfc_sli4_enable_msix(phba);
13231                         if (!retval) {
13232                                 /* Indicate initialization to MSI-X mode */
13233                                 phba->intr_type = MSIX;
13234                                 intr_mode = 2;
13235                         }
13236                 }
13237         }
13238
13239         /* Fallback to MSI if MSI-X initialization failed */
13240         if (cfg_mode >= 1 && phba->intr_type == NONE) {
13241                 retval = lpfc_sli4_enable_msi(phba);
13242                 if (!retval) {
13243                         /* Indicate initialization to MSI mode */
13244                         phba->intr_type = MSI;
13245                         intr_mode = 1;
13246                 }
13247         }
13248
13249         /* Fallback to INTx if both MSI-X/MSI initalization failed */
13250         if (phba->intr_type == NONE) {
13251                 retval = request_irq(phba->pcidev->irq, lpfc_sli4_intr_handler,
13252                                      IRQF_SHARED, LPFC_DRIVER_NAME, phba);
13253                 if (!retval) {
13254                         struct lpfc_hba_eq_hdl *eqhdl;
13255                         unsigned int cpu;
13256
13257                         /* Indicate initialization to INTx mode */
13258                         phba->intr_type = INTx;
13259                         intr_mode = 0;
13260
13261                         eqhdl = lpfc_get_eq_hdl(0);
13262                         retval = pci_irq_vector(phba->pcidev, 0);
13263                         if (retval < 0) {
13264                                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
13265                                         "0502 INTR pci_irq_vec failed (%d)\n",
13266                                          retval);
13267                                 return LPFC_INTR_ERROR;
13268                         }
13269                         eqhdl->irq = retval;
13270
13271                         cpu = cpumask_first(cpu_present_mask);
13272                         lpfc_assign_eq_map_info(phba, 0, LPFC_CPU_FIRST_IRQ,
13273                                                 cpu);
13274                         for (idx = 0; idx < phba->cfg_irq_chann; idx++) {
13275                                 eqhdl = lpfc_get_eq_hdl(idx);
13276                                 eqhdl->idx = idx;
13277                         }
13278                 }
13279         }
13280         return intr_mode;
13281 }
13282
13283 /**
13284  * lpfc_sli4_disable_intr - Disable device interrupt to SLI-4 device
13285  * @phba: pointer to lpfc hba data structure.
13286  *
13287  * This routine is invoked to disable device interrupt and disassociate
13288  * the driver's interrupt handler(s) from interrupt vector(s) to device
13289  * with SLI-4 interface spec. Depending on the interrupt mode, the driver
13290  * will release the interrupt vector(s) for the message signaled interrupt.
13291  **/
13292 static void
13293 lpfc_sli4_disable_intr(struct lpfc_hba *phba)
13294 {
13295         /* Disable the currently initialized interrupt mode */
13296         if (phba->intr_type == MSIX) {
13297                 int index;
13298                 struct lpfc_hba_eq_hdl *eqhdl;
13299
13300                 /* Free up MSI-X multi-message vectors */
13301                 for (index = 0; index < phba->cfg_irq_chann; index++) {
13302                         eqhdl = lpfc_get_eq_hdl(index);
13303                         lpfc_irq_clear_aff(eqhdl);
13304                         free_irq(eqhdl->irq, eqhdl);
13305                 }
13306         } else {
13307                 free_irq(phba->pcidev->irq, phba);
13308         }
13309
13310         pci_free_irq_vectors(phba->pcidev);
13311
13312         /* Reset interrupt management states */
13313         phba->intr_type = NONE;
13314         phba->sli.slistat.sli_intr = 0;
13315 }
13316
13317 /**
13318  * lpfc_unset_hba - Unset SLI3 hba device initialization
13319  * @phba: pointer to lpfc hba data structure.
13320  *
13321  * This routine is invoked to unset the HBA device initialization steps to
13322  * a device with SLI-3 interface spec.
13323  **/
13324 static void
13325 lpfc_unset_hba(struct lpfc_hba *phba)
13326 {
13327         set_bit(FC_UNLOADING, &phba->pport->load_flag);
13328
13329         kfree(phba->vpi_bmask);
13330         kfree(phba->vpi_ids);
13331
13332         lpfc_stop_hba_timers(phba);
13333
13334         phba->pport->work_port_events = 0;
13335
13336         lpfc_sli_hba_down(phba);
13337
13338         lpfc_sli_brdrestart(phba);
13339
13340         lpfc_sli_disable_intr(phba);
13341
13342         return;
13343 }
13344
13345 /**
13346  * lpfc_sli4_xri_exchange_busy_wait - Wait for device XRI exchange busy
13347  * @phba: Pointer to HBA context object.
13348  *
13349  * This function is called in the SLI4 code path to wait for completion
13350  * of device's XRIs exchange busy. It will check the XRI exchange busy
13351  * on outstanding FCP and ELS I/Os every 10ms for up to 10 seconds; after
13352  * that, it will check the XRI exchange busy on outstanding FCP and ELS
13353  * I/Os every 30 seconds, log error message, and wait forever. Only when
13354  * all XRI exchange busy complete, the driver unload shall proceed with
13355  * invoking the function reset ioctl mailbox command to the CNA and the
13356  * the rest of the driver unload resource release.
13357  **/
13358 static void
13359 lpfc_sli4_xri_exchange_busy_wait(struct lpfc_hba *phba)
13360 {
13361         struct lpfc_sli4_hdw_queue *qp;
13362         int idx, ccnt;
13363         int wait_time = 0;
13364         int io_xri_cmpl = 1;
13365         int nvmet_xri_cmpl = 1;
13366         int els_xri_cmpl = list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13367
13368         /* Driver just aborted IOs during the hba_unset process.  Pause
13369          * here to give the HBA time to complete the IO and get entries
13370          * into the abts lists.
13371          */
13372         msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1 * 5);
13373
13374         /* Wait for NVME pending IO to flush back to transport. */
13375         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13376                 lpfc_nvme_wait_for_io_drain(phba);
13377
13378         ccnt = 0;
13379         for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13380                 qp = &phba->sli4_hba.hdwq[idx];
13381                 io_xri_cmpl = list_empty(&qp->lpfc_abts_io_buf_list);
13382                 if (!io_xri_cmpl) /* if list is NOT empty */
13383                         ccnt++;
13384         }
13385         if (ccnt)
13386                 io_xri_cmpl = 0;
13387
13388         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13389                 nvmet_xri_cmpl =
13390                         list_empty(&phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13391         }
13392
13393         while (!els_xri_cmpl || !io_xri_cmpl || !nvmet_xri_cmpl) {
13394                 if (wait_time > LPFC_XRI_EXCH_BUSY_WAIT_TMO) {
13395                         if (!nvmet_xri_cmpl)
13396                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13397                                                 "6424 NVMET XRI exchange busy "
13398                                                 "wait time: %d seconds.\n",
13399                                                 wait_time/1000);
13400                         if (!io_xri_cmpl)
13401                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13402                                                 "6100 IO XRI exchange busy "
13403                                                 "wait time: %d seconds.\n",
13404                                                 wait_time/1000);
13405                         if (!els_xri_cmpl)
13406                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13407                                                 "2878 ELS XRI exchange busy "
13408                                                 "wait time: %d seconds.\n",
13409                                                 wait_time/1000);
13410                         msleep(LPFC_XRI_EXCH_BUSY_WAIT_T2);
13411                         wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T2;
13412                 } else {
13413                         msleep(LPFC_XRI_EXCH_BUSY_WAIT_T1);
13414                         wait_time += LPFC_XRI_EXCH_BUSY_WAIT_T1;
13415                 }
13416
13417                 ccnt = 0;
13418                 for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
13419                         qp = &phba->sli4_hba.hdwq[idx];
13420                         io_xri_cmpl = list_empty(
13421                             &qp->lpfc_abts_io_buf_list);
13422                         if (!io_xri_cmpl) /* if list is NOT empty */
13423                                 ccnt++;
13424                 }
13425                 if (ccnt)
13426                         io_xri_cmpl = 0;
13427
13428                 if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13429                         nvmet_xri_cmpl = list_empty(
13430                                 &phba->sli4_hba.lpfc_abts_nvmet_ctx_list);
13431                 }
13432                 els_xri_cmpl =
13433                         list_empty(&phba->sli4_hba.lpfc_abts_els_sgl_list);
13434
13435         }
13436 }
13437
13438 /**
13439  * lpfc_sli4_hba_unset - Unset the fcoe hba
13440  * @phba: Pointer to HBA context object.
13441  *
13442  * This function is called in the SLI4 code path to reset the HBA's FCoE
13443  * function. The caller is not required to hold any lock. This routine
13444  * issues PCI function reset mailbox command to reset the FCoE function.
13445  * At the end of the function, it calls lpfc_hba_down_post function to
13446  * free any pending commands.
13447  **/
13448 static void
13449 lpfc_sli4_hba_unset(struct lpfc_hba *phba)
13450 {
13451         int wait_cnt = 0;
13452         LPFC_MBOXQ_t *mboxq;
13453         struct pci_dev *pdev = phba->pcidev;
13454
13455         lpfc_stop_hba_timers(phba);
13456         hrtimer_cancel(&phba->cmf_stats_timer);
13457         hrtimer_cancel(&phba->cmf_timer);
13458
13459         if (phba->pport)
13460                 phba->sli4_hba.intr_enable = 0;
13461
13462         /*
13463          * Gracefully wait out the potential current outstanding asynchronous
13464          * mailbox command.
13465          */
13466
13467         /* First, block any pending async mailbox command from posted */
13468         spin_lock_irq(&phba->hbalock);
13469         phba->sli.sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13470         spin_unlock_irq(&phba->hbalock);
13471         /* Now, trying to wait it out if we can */
13472         while (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13473                 msleep(10);
13474                 if (++wait_cnt > LPFC_ACTIVE_MBOX_WAIT_CNT)
13475                         break;
13476         }
13477         /* Forcefully release the outstanding mailbox command if timed out */
13478         if (phba->sli.sli_flag & LPFC_SLI_MBOX_ACTIVE) {
13479                 spin_lock_irq(&phba->hbalock);
13480                 mboxq = phba->sli.mbox_active;
13481                 mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
13482                 __lpfc_mbox_cmpl_put(phba, mboxq);
13483                 phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13484                 phba->sli.mbox_active = NULL;
13485                 spin_unlock_irq(&phba->hbalock);
13486         }
13487
13488         /* Abort all iocbs associated with the hba */
13489         lpfc_sli_hba_iocb_abort(phba);
13490
13491         if (!pci_channel_offline(phba->pcidev))
13492                 /* Wait for completion of device XRI exchange busy */
13493                 lpfc_sli4_xri_exchange_busy_wait(phba);
13494
13495         /* per-phba callback de-registration for hotplug event */
13496         if (phba->pport)
13497                 lpfc_cpuhp_remove(phba);
13498
13499         /* Disable PCI subsystem interrupt */
13500         lpfc_sli4_disable_intr(phba);
13501
13502         /* Disable SR-IOV if enabled */
13503         if (phba->cfg_sriov_nr_virtfn)
13504                 pci_disable_sriov(pdev);
13505
13506         /* Stop kthread signal shall trigger work_done one more time */
13507         kthread_stop(phba->worker_thread);
13508
13509         /* Disable FW logging to host memory */
13510         lpfc_ras_stop_fwlog(phba);
13511
13512         /* Reset SLI4 HBA FCoE function */
13513         lpfc_pci_function_reset(phba);
13514
13515         /* release all queue allocated resources. */
13516         lpfc_sli4_queue_destroy(phba);
13517
13518         /* Free RAS DMA memory */
13519         if (phba->ras_fwlog.ras_enabled)
13520                 lpfc_sli4_ras_dma_free(phba);
13521
13522         /* Stop the SLI4 device port */
13523         if (phba->pport)
13524                 phba->pport->work_port_events = 0;
13525 }
13526
13527 static uint32_t
13528 lpfc_cgn_crc32(uint32_t crc, u8 byte)
13529 {
13530         uint32_t msb = 0;
13531         uint32_t bit;
13532
13533         for (bit = 0; bit < 8; bit++) {
13534                 msb = (crc >> 31) & 1;
13535                 crc <<= 1;
13536
13537                 if (msb ^ (byte & 1)) {
13538                         crc ^= LPFC_CGN_CRC32_MAGIC_NUMBER;
13539                         crc |= 1;
13540                 }
13541                 byte >>= 1;
13542         }
13543         return crc;
13544 }
13545
13546 static uint32_t
13547 lpfc_cgn_reverse_bits(uint32_t wd)
13548 {
13549         uint32_t result = 0;
13550         uint32_t i;
13551
13552         for (i = 0; i < 32; i++) {
13553                 result <<= 1;
13554                 result |= (1 & (wd >> i));
13555         }
13556         return result;
13557 }
13558
13559 /*
13560  * The routine corresponds with the algorithm the HBA firmware
13561  * uses to validate the data integrity.
13562  */
13563 uint32_t
13564 lpfc_cgn_calc_crc32(void *ptr, uint32_t byteLen, uint32_t crc)
13565 {
13566         uint32_t  i;
13567         uint32_t result;
13568         uint8_t  *data = (uint8_t *)ptr;
13569
13570         for (i = 0; i < byteLen; ++i)
13571                 crc = lpfc_cgn_crc32(crc, data[i]);
13572
13573         result = ~lpfc_cgn_reverse_bits(crc);
13574         return result;
13575 }
13576
13577 void
13578 lpfc_init_congestion_buf(struct lpfc_hba *phba)
13579 {
13580         struct lpfc_cgn_info *cp;
13581         uint16_t size;
13582         uint32_t crc;
13583
13584         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13585                         "6235 INIT Congestion Buffer %p\n", phba->cgn_i);
13586
13587         if (!phba->cgn_i)
13588                 return;
13589         cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13590
13591         atomic_set(&phba->cgn_fabric_warn_cnt, 0);
13592         atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
13593         atomic_set(&phba->cgn_sync_alarm_cnt, 0);
13594         atomic_set(&phba->cgn_sync_warn_cnt, 0);
13595
13596         atomic_set(&phba->cgn_driver_evt_cnt, 0);
13597         atomic_set(&phba->cgn_latency_evt_cnt, 0);
13598         atomic64_set(&phba->cgn_latency_evt, 0);
13599         phba->cgn_evt_minute = 0;
13600
13601         memset(cp, 0xff, offsetof(struct lpfc_cgn_info, cgn_stat));
13602         cp->cgn_info_size = cpu_to_le16(LPFC_CGN_INFO_SZ);
13603         cp->cgn_info_version = LPFC_CGN_INFO_V4;
13604
13605         /* cgn parameters */
13606         cp->cgn_info_mode = phba->cgn_p.cgn_param_mode;
13607         cp->cgn_info_level0 = phba->cgn_p.cgn_param_level0;
13608         cp->cgn_info_level1 = phba->cgn_p.cgn_param_level1;
13609         cp->cgn_info_level2 = phba->cgn_p.cgn_param_level2;
13610
13611         lpfc_cgn_update_tstamp(phba, &cp->base_time);
13612
13613         /* Fill in default LUN qdepth */
13614         if (phba->pport) {
13615                 size = (uint16_t)(phba->pport->cfg_lun_queue_depth);
13616                 cp->cgn_lunq = cpu_to_le16(size);
13617         }
13618
13619         /* last used Index initialized to 0xff already */
13620
13621         cp->cgn_warn_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13622         cp->cgn_alarm_freq = cpu_to_le16(LPFC_FPIN_INIT_FREQ);
13623         crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13624         cp->cgn_info_crc = cpu_to_le32(crc);
13625
13626         phba->cgn_evt_timestamp = jiffies +
13627                 msecs_to_jiffies(LPFC_CGN_TIMER_TO_MIN);
13628 }
13629
13630 void
13631 lpfc_init_congestion_stat(struct lpfc_hba *phba)
13632 {
13633         struct lpfc_cgn_info *cp;
13634         uint32_t crc;
13635
13636         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
13637                         "6236 INIT Congestion Stat %p\n", phba->cgn_i);
13638
13639         if (!phba->cgn_i)
13640                 return;
13641
13642         cp = (struct lpfc_cgn_info *)phba->cgn_i->virt;
13643         memset(&cp->cgn_stat, 0, sizeof(cp->cgn_stat));
13644
13645         lpfc_cgn_update_tstamp(phba, &cp->stat_start);
13646         crc = lpfc_cgn_calc_crc32(cp, LPFC_CGN_INFO_SZ, LPFC_CGN_CRC32_SEED);
13647         cp->cgn_info_crc = cpu_to_le32(crc);
13648 }
13649
13650 /**
13651  * __lpfc_reg_congestion_buf - register congestion info buffer with HBA
13652  * @phba: Pointer to hba context object.
13653  * @reg: flag to determine register or unregister.
13654  */
13655 static int
13656 __lpfc_reg_congestion_buf(struct lpfc_hba *phba, int reg)
13657 {
13658         struct lpfc_mbx_reg_congestion_buf *reg_congestion_buf;
13659         union  lpfc_sli4_cfg_shdr *shdr;
13660         uint32_t shdr_status, shdr_add_status;
13661         LPFC_MBOXQ_t *mboxq;
13662         int length, rc;
13663
13664         if (!phba->cgn_i)
13665                 return -ENXIO;
13666
13667         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13668         if (!mboxq) {
13669                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13670                                 "2641 REG_CONGESTION_BUF mbox allocation fail: "
13671                                 "HBA state x%x reg %d\n",
13672                                 phba->pport->port_state, reg);
13673                 return -ENOMEM;
13674         }
13675
13676         length = (sizeof(struct lpfc_mbx_reg_congestion_buf) -
13677                 sizeof(struct lpfc_sli4_cfg_mhdr));
13678         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13679                          LPFC_MBOX_OPCODE_REG_CONGESTION_BUF, length,
13680                          LPFC_SLI4_MBX_EMBED);
13681         reg_congestion_buf = &mboxq->u.mqe.un.reg_congestion_buf;
13682         bf_set(lpfc_mbx_reg_cgn_buf_type, reg_congestion_buf, 1);
13683         if (reg > 0)
13684                 bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 1);
13685         else
13686                 bf_set(lpfc_mbx_reg_cgn_buf_cnt, reg_congestion_buf, 0);
13687         reg_congestion_buf->length = sizeof(struct lpfc_cgn_info);
13688         reg_congestion_buf->addr_lo =
13689                 putPaddrLow(phba->cgn_i->phys);
13690         reg_congestion_buf->addr_hi =
13691                 putPaddrHigh(phba->cgn_i->phys);
13692
13693         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13694         shdr = (union lpfc_sli4_cfg_shdr *)
13695                 &mboxq->u.mqe.un.sli4_config.header.cfg_shdr;
13696         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13697         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
13698                                  &shdr->response);
13699         mempool_free(mboxq, phba->mbox_mem_pool);
13700         if (shdr_status || shdr_add_status || rc) {
13701                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13702                                 "2642 REG_CONGESTION_BUF mailbox "
13703                                 "failed with status x%x add_status x%x,"
13704                                 " mbx status x%x reg %d\n",
13705                                 shdr_status, shdr_add_status, rc, reg);
13706                 return -ENXIO;
13707         }
13708         return 0;
13709 }
13710
13711 int
13712 lpfc_unreg_congestion_buf(struct lpfc_hba *phba)
13713 {
13714         lpfc_cmf_stop(phba);
13715         return __lpfc_reg_congestion_buf(phba, 0);
13716 }
13717
13718 int
13719 lpfc_reg_congestion_buf(struct lpfc_hba *phba)
13720 {
13721         return __lpfc_reg_congestion_buf(phba, 1);
13722 }
13723
13724 /**
13725  * lpfc_get_sli4_parameters - Get the SLI4 Config PARAMETERS.
13726  * @phba: Pointer to HBA context object.
13727  * @mboxq: Pointer to the mailboxq memory for the mailbox command response.
13728  *
13729  * This function is called in the SLI4 code path to read the port's
13730  * sli4 capabilities.
13731  *
13732  * This function may be be called from any context that can block-wait
13733  * for the completion.  The expectation is that this routine is called
13734  * typically from probe_one or from the online routine.
13735  **/
13736 int
13737 lpfc_get_sli4_parameters(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
13738 {
13739         int rc;
13740         struct lpfc_mqe *mqe = &mboxq->u.mqe;
13741         struct lpfc_pc_sli4_params *sli4_params;
13742         uint32_t mbox_tmo;
13743         int length;
13744         bool exp_wqcq_pages = true;
13745         struct lpfc_sli4_parameters *mbx_sli4_parameters;
13746
13747         /*
13748          * By default, the driver assumes the SLI4 port requires RPI
13749          * header postings.  The SLI4_PARAM response will correct this
13750          * assumption.
13751          */
13752         phba->sli4_hba.rpi_hdrs_in_use = 1;
13753
13754         /* Read the port's SLI4 Config Parameters */
13755         length = (sizeof(struct lpfc_mbx_get_sli4_parameters) -
13756                   sizeof(struct lpfc_sli4_cfg_mhdr));
13757         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
13758                          LPFC_MBOX_OPCODE_GET_SLI4_PARAMETERS,
13759                          length, LPFC_SLI4_MBX_EMBED);
13760         if (!phba->sli4_hba.intr_enable)
13761                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
13762         else {
13763                 mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
13764                 rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
13765         }
13766         if (unlikely(rc))
13767                 return rc;
13768         sli4_params = &phba->sli4_hba.pc_sli4_params;
13769         mbx_sli4_parameters = &mqe->un.get_sli4_parameters.sli4_parameters;
13770         sli4_params->if_type = bf_get(cfg_if_type, mbx_sli4_parameters);
13771         sli4_params->sli_rev = bf_get(cfg_sli_rev, mbx_sli4_parameters);
13772         sli4_params->sli_family = bf_get(cfg_sli_family, mbx_sli4_parameters);
13773         sli4_params->featurelevel_1 = bf_get(cfg_sli_hint_1,
13774                                              mbx_sli4_parameters);
13775         sli4_params->featurelevel_2 = bf_get(cfg_sli_hint_2,
13776                                              mbx_sli4_parameters);
13777         if (bf_get(cfg_phwq, mbx_sli4_parameters))
13778                 phba->sli3_options |= LPFC_SLI4_PHWQ_ENABLED;
13779         else
13780                 phba->sli3_options &= ~LPFC_SLI4_PHWQ_ENABLED;
13781         sli4_params->sge_supp_len = mbx_sli4_parameters->sge_supp_len;
13782         sli4_params->loopbk_scope = bf_get(cfg_loopbk_scope,
13783                                            mbx_sli4_parameters);
13784         sli4_params->oas_supported = bf_get(cfg_oas, mbx_sli4_parameters);
13785         sli4_params->cqv = bf_get(cfg_cqv, mbx_sli4_parameters);
13786         sli4_params->mqv = bf_get(cfg_mqv, mbx_sli4_parameters);
13787         sli4_params->wqv = bf_get(cfg_wqv, mbx_sli4_parameters);
13788         sli4_params->rqv = bf_get(cfg_rqv, mbx_sli4_parameters);
13789         sli4_params->eqav = bf_get(cfg_eqav, mbx_sli4_parameters);
13790         sli4_params->cqav = bf_get(cfg_cqav, mbx_sli4_parameters);
13791         sli4_params->wqsize = bf_get(cfg_wqsize, mbx_sli4_parameters);
13792         sli4_params->bv1s = bf_get(cfg_bv1s, mbx_sli4_parameters);
13793         sli4_params->pls = bf_get(cfg_pvl, mbx_sli4_parameters);
13794         sli4_params->sgl_pages_max = bf_get(cfg_sgl_page_cnt,
13795                                             mbx_sli4_parameters);
13796         sli4_params->wqpcnt = bf_get(cfg_wqpcnt, mbx_sli4_parameters);
13797         sli4_params->sgl_pp_align = bf_get(cfg_sgl_pp_align,
13798                                            mbx_sli4_parameters);
13799         phba->sli4_hba.extents_in_use = bf_get(cfg_ext, mbx_sli4_parameters);
13800         phba->sli4_hba.rpi_hdrs_in_use = bf_get(cfg_hdrr, mbx_sli4_parameters);
13801         sli4_params->mi_cap = bf_get(cfg_mi_ver, mbx_sli4_parameters);
13802
13803         /* Check for Extended Pre-Registered SGL support */
13804         phba->cfg_xpsgl = bf_get(cfg_xpsgl, mbx_sli4_parameters);
13805
13806         /* Check for firmware nvme support */
13807         rc = (bf_get(cfg_nvme, mbx_sli4_parameters) &&
13808                      bf_get(cfg_xib, mbx_sli4_parameters));
13809
13810         if (rc) {
13811                 /* Save this to indicate the Firmware supports NVME */
13812                 sli4_params->nvme = 1;
13813
13814                 /* Firmware NVME support, check driver FC4 NVME support */
13815                 if (phba->cfg_enable_fc4_type == LPFC_ENABLE_FCP) {
13816                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13817                                         "6133 Disabling NVME support: "
13818                                         "FC4 type not supported: x%x\n",
13819                                         phba->cfg_enable_fc4_type);
13820                         goto fcponly;
13821                 }
13822         } else {
13823                 /* No firmware NVME support, check driver FC4 NVME support */
13824                 sli4_params->nvme = 0;
13825                 if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13826                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_NVME,
13827                                         "6101 Disabling NVME support: Not "
13828                                         "supported by firmware (%d %d) x%x\n",
13829                                         bf_get(cfg_nvme, mbx_sli4_parameters),
13830                                         bf_get(cfg_xib, mbx_sli4_parameters),
13831                                         phba->cfg_enable_fc4_type);
13832 fcponly:
13833                         phba->nvmet_support = 0;
13834                         phba->cfg_nvmet_mrq = 0;
13835                         phba->cfg_nvme_seg_cnt = 0;
13836
13837                         /* If no FC4 type support, move to just SCSI support */
13838                         if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
13839                                 return -ENODEV;
13840                         phba->cfg_enable_fc4_type = LPFC_ENABLE_FCP;
13841                 }
13842         }
13843
13844         /* If the NVME FC4 type is enabled, scale the sg_seg_cnt to
13845          * accommodate 512K and 1M IOs in a single nvme buf.
13846          */
13847         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)
13848                 phba->cfg_sg_seg_cnt = LPFC_MAX_NVME_SEG_CNT;
13849
13850         /* Enable embedded Payload BDE if support is indicated */
13851         if (bf_get(cfg_pbde, mbx_sli4_parameters))
13852                 phba->cfg_enable_pbde = 1;
13853         else
13854                 phba->cfg_enable_pbde = 0;
13855
13856         /*
13857          * To support Suppress Response feature we must satisfy 3 conditions.
13858          * lpfc_suppress_rsp module parameter must be set (default).
13859          * In SLI4-Parameters Descriptor:
13860          * Extended Inline Buffers (XIB) must be supported.
13861          * Suppress Response IU Not Supported (SRIUNS) must NOT be supported
13862          * (double negative).
13863          */
13864         if (phba->cfg_suppress_rsp && bf_get(cfg_xib, mbx_sli4_parameters) &&
13865             !(bf_get(cfg_nosr, mbx_sli4_parameters)))
13866                 phba->sli.sli_flag |= LPFC_SLI_SUPPRESS_RSP;
13867         else
13868                 phba->cfg_suppress_rsp = 0;
13869
13870         if (bf_get(cfg_eqdr, mbx_sli4_parameters))
13871                 phba->sli.sli_flag |= LPFC_SLI_USE_EQDR;
13872
13873         /* Make sure that sge_supp_len can be handled by the driver */
13874         if (sli4_params->sge_supp_len > LPFC_MAX_SGE_SIZE)
13875                 sli4_params->sge_supp_len = LPFC_MAX_SGE_SIZE;
13876
13877         rc = dma_set_max_seg_size(&phba->pcidev->dev, sli4_params->sge_supp_len);
13878         if (unlikely(rc)) {
13879                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13880                                 "6400 Can't set dma maximum segment size\n");
13881                 return rc;
13882         }
13883
13884         /*
13885          * Check whether the adapter supports an embedded copy of the
13886          * FCP CMD IU within the WQE for FCP_Ixxx commands. In order
13887          * to use this option, 128-byte WQEs must be used.
13888          */
13889         if (bf_get(cfg_ext_embed_cb, mbx_sli4_parameters))
13890                 phba->fcp_embed_io = 1;
13891         else
13892                 phba->fcp_embed_io = 0;
13893
13894         lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_NVME,
13895                         "6422 XIB %d PBDE %d: FCP %d NVME %d %d %d\n",
13896                         bf_get(cfg_xib, mbx_sli4_parameters),
13897                         phba->cfg_enable_pbde,
13898                         phba->fcp_embed_io, sli4_params->nvme,
13899                         phba->cfg_nvme_embed_cmd, phba->cfg_suppress_rsp);
13900
13901         if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
13902             LPFC_SLI_INTF_IF_TYPE_2) &&
13903             (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
13904                  LPFC_SLI_INTF_FAMILY_LNCR_A0))
13905                 exp_wqcq_pages = false;
13906
13907         if ((bf_get(cfg_cqpsize, mbx_sli4_parameters) & LPFC_CQ_16K_PAGE_SZ) &&
13908             (bf_get(cfg_wqpsize, mbx_sli4_parameters) & LPFC_WQ_16K_PAGE_SZ) &&
13909             exp_wqcq_pages &&
13910             (sli4_params->wqsize & LPFC_WQ_SZ128_SUPPORT))
13911                 phba->enab_exp_wqcq_pages = 1;
13912         else
13913                 phba->enab_exp_wqcq_pages = 0;
13914         /*
13915          * Check if the SLI port supports MDS Diagnostics
13916          */
13917         if (bf_get(cfg_mds_diags, mbx_sli4_parameters))
13918                 phba->mds_diags_support = 1;
13919         else
13920                 phba->mds_diags_support = 0;
13921
13922         /*
13923          * Check if the SLI port supports NSLER
13924          */
13925         if (bf_get(cfg_nsler, mbx_sli4_parameters))
13926                 phba->nsler = 1;
13927         else
13928                 phba->nsler = 0;
13929
13930         return 0;
13931 }
13932
13933 /**
13934  * lpfc_pci_probe_one_s3 - PCI probe func to reg SLI-3 device to PCI subsystem.
13935  * @pdev: pointer to PCI device
13936  * @pid: pointer to PCI device identifier
13937  *
13938  * This routine is to be called to attach a device with SLI-3 interface spec
13939  * to the PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
13940  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
13941  * information of the device and driver to see if the driver state that it can
13942  * support this kind of device. If the match is successful, the driver core
13943  * invokes this routine. If this routine determines it can claim the HBA, it
13944  * does all the initialization that it needs to do to handle the HBA properly.
13945  *
13946  * Return code
13947  *      0 - driver can claim the device
13948  *      negative value - driver can not claim the device
13949  **/
13950 static int
13951 lpfc_pci_probe_one_s3(struct pci_dev *pdev, const struct pci_device_id *pid)
13952 {
13953         struct lpfc_hba   *phba;
13954         struct lpfc_vport *vport = NULL;
13955         struct Scsi_Host  *shost = NULL;
13956         int error;
13957         uint32_t cfg_mode, intr_mode;
13958
13959         /* Allocate memory for HBA structure */
13960         phba = lpfc_hba_alloc(pdev);
13961         if (!phba)
13962                 return -ENOMEM;
13963
13964         /* Perform generic PCI device enabling operation */
13965         error = lpfc_enable_pci_dev(phba);
13966         if (error)
13967                 goto out_free_phba;
13968
13969         /* Set up SLI API function jump table for PCI-device group-0 HBAs */
13970         error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_LP);
13971         if (error)
13972                 goto out_disable_pci_dev;
13973
13974         /* Set up SLI-3 specific device PCI memory space */
13975         error = lpfc_sli_pci_mem_setup(phba);
13976         if (error) {
13977                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13978                                 "1402 Failed to set up pci memory space.\n");
13979                 goto out_disable_pci_dev;
13980         }
13981
13982         /* Set up SLI-3 specific device driver resources */
13983         error = lpfc_sli_driver_resource_setup(phba);
13984         if (error) {
13985                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13986                                 "1404 Failed to set up driver resource.\n");
13987                 goto out_unset_pci_mem_s3;
13988         }
13989
13990         /* Initialize and populate the iocb list per host */
13991
13992         error = lpfc_init_iocb_list(phba, LPFC_IOCB_LIST_CNT);
13993         if (error) {
13994                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13995                                 "1405 Failed to initialize iocb list.\n");
13996                 goto out_unset_driver_resource_s3;
13997         }
13998
13999         /* Set up common device driver resources */
14000         error = lpfc_setup_driver_resource_phase2(phba);
14001         if (error) {
14002                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14003                                 "1406 Failed to set up driver resource.\n");
14004                 goto out_free_iocb_list;
14005         }
14006
14007         /* Get the default values for Model Name and Description */
14008         lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14009
14010         /* Create SCSI host to the physical port */
14011         error = lpfc_create_shost(phba);
14012         if (error) {
14013                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14014                                 "1407 Failed to create scsi host.\n");
14015                 goto out_unset_driver_resource;
14016         }
14017
14018         /* Configure sysfs attributes */
14019         vport = phba->pport;
14020         error = lpfc_alloc_sysfs_attr(vport);
14021         if (error) {
14022                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14023                                 "1476 Failed to allocate sysfs attr\n");
14024                 goto out_destroy_shost;
14025         }
14026
14027         shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14028         /* Now, trying to enable interrupt and bring up the device */
14029         cfg_mode = phba->cfg_use_msi;
14030         while (true) {
14031                 /* Put device to a known state before enabling interrupt */
14032                 lpfc_stop_port(phba);
14033                 /* Configure and enable interrupt */
14034                 intr_mode = lpfc_sli_enable_intr(phba, cfg_mode);
14035                 if (intr_mode == LPFC_INTR_ERROR) {
14036                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14037                                         "0431 Failed to enable interrupt.\n");
14038                         error = -ENODEV;
14039                         goto out_free_sysfs_attr;
14040                 }
14041                 /* SLI-3 HBA setup */
14042                 if (lpfc_sli_hba_setup(phba)) {
14043                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14044                                         "1477 Failed to set up hba\n");
14045                         error = -ENODEV;
14046                         goto out_remove_device;
14047                 }
14048
14049                 /* Wait 50ms for the interrupts of previous mailbox commands */
14050                 msleep(50);
14051                 /* Check active interrupts on message signaled interrupts */
14052                 if (intr_mode == 0 ||
14053                     phba->sli.slistat.sli_intr > LPFC_MSIX_VECTORS) {
14054                         /* Log the current active interrupt mode */
14055                         phba->intr_mode = intr_mode;
14056                         lpfc_log_intr_mode(phba, intr_mode);
14057                         break;
14058                 } else {
14059                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14060                                         "0447 Configure interrupt mode (%d) "
14061                                         "failed active interrupt test.\n",
14062                                         intr_mode);
14063                         /* Disable the current interrupt mode */
14064                         lpfc_sli_disable_intr(phba);
14065                         /* Try next level of interrupt mode */
14066                         cfg_mode = --intr_mode;
14067                 }
14068         }
14069
14070         /* Perform post initialization setup */
14071         lpfc_post_init_setup(phba);
14072
14073         /* Check if there are static vports to be created. */
14074         lpfc_create_static_vport(phba);
14075
14076         return 0;
14077
14078 out_remove_device:
14079         lpfc_unset_hba(phba);
14080 out_free_sysfs_attr:
14081         lpfc_free_sysfs_attr(vport);
14082 out_destroy_shost:
14083         lpfc_destroy_shost(phba);
14084 out_unset_driver_resource:
14085         lpfc_unset_driver_resource_phase2(phba);
14086 out_free_iocb_list:
14087         lpfc_free_iocb_list(phba);
14088 out_unset_driver_resource_s3:
14089         lpfc_sli_driver_resource_unset(phba);
14090 out_unset_pci_mem_s3:
14091         lpfc_sli_pci_mem_unset(phba);
14092 out_disable_pci_dev:
14093         lpfc_disable_pci_dev(phba);
14094         if (shost)
14095                 scsi_host_put(shost);
14096 out_free_phba:
14097         lpfc_hba_free(phba);
14098         return error;
14099 }
14100
14101 /**
14102  * lpfc_pci_remove_one_s3 - PCI func to unreg SLI-3 device from PCI subsystem.
14103  * @pdev: pointer to PCI device
14104  *
14105  * This routine is to be called to disattach a device with SLI-3 interface
14106  * spec from PCI subsystem. When an Emulex HBA with SLI-3 interface spec is
14107  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14108  * device to be removed from the PCI subsystem properly.
14109  **/
14110 static void
14111 lpfc_pci_remove_one_s3(struct pci_dev *pdev)
14112 {
14113         struct Scsi_Host  *shost = pci_get_drvdata(pdev);
14114         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14115         struct lpfc_vport **vports;
14116         struct lpfc_hba   *phba = vport->phba;
14117         int i;
14118
14119         set_bit(FC_UNLOADING, &vport->load_flag);
14120
14121         lpfc_free_sysfs_attr(vport);
14122
14123         /* Release all the vports against this physical port */
14124         vports = lpfc_create_vport_work_array(phba);
14125         if (vports != NULL)
14126                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14127                         if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14128                                 continue;
14129                         fc_vport_terminate(vports[i]->fc_vport);
14130                 }
14131         lpfc_destroy_vport_work_array(phba, vports);
14132
14133         /* Remove FC host with the physical port */
14134         fc_remove_host(shost);
14135         scsi_remove_host(shost);
14136
14137         /* Clean up all nodes, mailboxes and IOs. */
14138         lpfc_cleanup(vport);
14139
14140         /*
14141          * Bring down the SLI Layer. This step disable all interrupts,
14142          * clears the rings, discards all mailbox commands, and resets
14143          * the HBA.
14144          */
14145
14146         /* HBA interrupt will be disabled after this call */
14147         lpfc_sli_hba_down(phba);
14148         /* Stop kthread signal shall trigger work_done one more time */
14149         kthread_stop(phba->worker_thread);
14150         /* Final cleanup of txcmplq and reset the HBA */
14151         lpfc_sli_brdrestart(phba);
14152
14153         kfree(phba->vpi_bmask);
14154         kfree(phba->vpi_ids);
14155
14156         lpfc_stop_hba_timers(phba);
14157         spin_lock_irq(&phba->port_list_lock);
14158         list_del_init(&vport->listentry);
14159         spin_unlock_irq(&phba->port_list_lock);
14160
14161         lpfc_debugfs_terminate(vport);
14162
14163         /* Disable SR-IOV if enabled */
14164         if (phba->cfg_sriov_nr_virtfn)
14165                 pci_disable_sriov(pdev);
14166
14167         /* Disable interrupt */
14168         lpfc_sli_disable_intr(phba);
14169
14170         scsi_host_put(shost);
14171
14172         /*
14173          * Call scsi_free before mem_free since scsi bufs are released to their
14174          * corresponding pools here.
14175          */
14176         lpfc_scsi_free(phba);
14177         lpfc_free_iocb_list(phba);
14178
14179         lpfc_mem_free_all(phba);
14180
14181         dma_free_coherent(&pdev->dev, lpfc_sli_hbq_size(),
14182                           phba->hbqslimp.virt, phba->hbqslimp.phys);
14183
14184         /* Free resources associated with SLI2 interface */
14185         dma_free_coherent(&pdev->dev, SLI2_SLIM_SIZE,
14186                           phba->slim2p.virt, phba->slim2p.phys);
14187
14188         /* unmap adapter SLIM and Control Registers */
14189         iounmap(phba->ctrl_regs_memmap_p);
14190         iounmap(phba->slim_memmap_p);
14191
14192         lpfc_hba_free(phba);
14193
14194         pci_release_mem_regions(pdev);
14195         pci_disable_device(pdev);
14196 }
14197
14198 /**
14199  * lpfc_pci_suspend_one_s3 - PCI func to suspend SLI-3 device for power mgmnt
14200  * @dev_d: pointer to device
14201  *
14202  * This routine is to be called from the kernel's PCI subsystem to support
14203  * system Power Management (PM) to device with SLI-3 interface spec. When
14204  * PM invokes this method, it quiesces the device by stopping the driver's
14205  * worker thread for the device, turning off device's interrupt and DMA,
14206  * and bring the device offline. Note that as the driver implements the
14207  * minimum PM requirements to a power-aware driver's PM support for the
14208  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
14209  * to the suspend() method call will be treated as SUSPEND and the driver will
14210  * fully reinitialize its device during resume() method call, the driver will
14211  * set device to PCI_D3hot state in PCI config space instead of setting it
14212  * according to the @msg provided by the PM.
14213  *
14214  * Return code
14215  *      0 - driver suspended the device
14216  *      Error otherwise
14217  **/
14218 static int __maybe_unused
14219 lpfc_pci_suspend_one_s3(struct device *dev_d)
14220 {
14221         struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14222         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14223
14224         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14225                         "0473 PCI device Power Management suspend.\n");
14226
14227         /* Bring down the device */
14228         lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14229         lpfc_offline(phba);
14230         kthread_stop(phba->worker_thread);
14231
14232         /* Disable interrupt from device */
14233         lpfc_sli_disable_intr(phba);
14234
14235         return 0;
14236 }
14237
14238 /**
14239  * lpfc_pci_resume_one_s3 - PCI func to resume SLI-3 device for power mgmnt
14240  * @dev_d: pointer to device
14241  *
14242  * This routine is to be called from the kernel's PCI subsystem to support
14243  * system Power Management (PM) to device with SLI-3 interface spec. When PM
14244  * invokes this method, it restores the device's PCI config space state and
14245  * fully reinitializes the device and brings it online. Note that as the
14246  * driver implements the minimum PM requirements to a power-aware driver's
14247  * PM for suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE,
14248  * FREEZE) to the suspend() method call will be treated as SUSPEND and the
14249  * driver will fully reinitialize its device during resume() method call,
14250  * the device will be set to PCI_D0 directly in PCI config space before
14251  * restoring the state.
14252  *
14253  * Return code
14254  *      0 - driver suspended the device
14255  *      Error otherwise
14256  **/
14257 static int __maybe_unused
14258 lpfc_pci_resume_one_s3(struct device *dev_d)
14259 {
14260         struct Scsi_Host *shost = dev_get_drvdata(dev_d);
14261         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14262         uint32_t intr_mode;
14263         int error;
14264
14265         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14266                         "0452 PCI device Power Management resume.\n");
14267
14268         /* Startup the kernel thread for this host adapter. */
14269         phba->worker_thread = kthread_run(lpfc_do_work, phba,
14270                                         "lpfc_worker_%d", phba->brd_no);
14271         if (IS_ERR(phba->worker_thread)) {
14272                 error = PTR_ERR(phba->worker_thread);
14273                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14274                                 "0434 PM resume failed to start worker "
14275                                 "thread: error=x%x.\n", error);
14276                 return error;
14277         }
14278
14279         /* Init cpu_map array */
14280         lpfc_cpu_map_array_init(phba);
14281         /* Init hba_eq_hdl array */
14282         lpfc_hba_eq_hdl_array_init(phba);
14283         /* Configure and enable interrupt */
14284         intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14285         if (intr_mode == LPFC_INTR_ERROR) {
14286                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14287                                 "0430 PM resume Failed to enable interrupt\n");
14288                 return -EIO;
14289         } else
14290                 phba->intr_mode = intr_mode;
14291
14292         /* Restart HBA and bring it online */
14293         lpfc_sli_brdrestart(phba);
14294         lpfc_online(phba);
14295
14296         /* Log the current active interrupt mode */
14297         lpfc_log_intr_mode(phba, phba->intr_mode);
14298
14299         return 0;
14300 }
14301
14302 /**
14303  * lpfc_sli_prep_dev_for_recover - Prepare SLI3 device for pci slot recover
14304  * @phba: pointer to lpfc hba data structure.
14305  *
14306  * This routine is called to prepare the SLI3 device for PCI slot recover. It
14307  * aborts all the outstanding SCSI I/Os to the pci device.
14308  **/
14309 static void
14310 lpfc_sli_prep_dev_for_recover(struct lpfc_hba *phba)
14311 {
14312         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14313                         "2723 PCI channel I/O abort preparing for recovery\n");
14314
14315         /*
14316          * There may be errored I/Os through HBA, abort all I/Os on txcmplq
14317          * and let the SCSI mid-layer to retry them to recover.
14318          */
14319         lpfc_sli_abort_fcp_rings(phba);
14320 }
14321
14322 /**
14323  * lpfc_sli_prep_dev_for_reset - Prepare SLI3 device for pci slot reset
14324  * @phba: pointer to lpfc hba data structure.
14325  *
14326  * This routine is called to prepare the SLI3 device for PCI slot reset. It
14327  * disables the device interrupt and pci device, and aborts the internal FCP
14328  * pending I/Os.
14329  **/
14330 static void
14331 lpfc_sli_prep_dev_for_reset(struct lpfc_hba *phba)
14332 {
14333         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14334                         "2710 PCI channel disable preparing for reset\n");
14335
14336         /* Block any management I/Os to the device */
14337         lpfc_block_mgmt_io(phba, LPFC_MBX_WAIT);
14338
14339         /* Block all SCSI devices' I/Os on the host */
14340         lpfc_scsi_dev_block(phba);
14341
14342         /* Flush all driver's outstanding SCSI I/Os as we are to reset */
14343         lpfc_sli_flush_io_rings(phba);
14344
14345         /* stop all timers */
14346         lpfc_stop_hba_timers(phba);
14347
14348         /* Disable interrupt and pci device */
14349         lpfc_sli_disable_intr(phba);
14350         pci_disable_device(phba->pcidev);
14351 }
14352
14353 /**
14354  * lpfc_sli_prep_dev_for_perm_failure - Prepare SLI3 dev for pci slot disable
14355  * @phba: pointer to lpfc hba data structure.
14356  *
14357  * This routine is called to prepare the SLI3 device for PCI slot permanently
14358  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
14359  * pending I/Os.
14360  **/
14361 static void
14362 lpfc_sli_prep_dev_for_perm_failure(struct lpfc_hba *phba)
14363 {
14364         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14365                         "2711 PCI channel permanent disable for failure\n");
14366         /* Block all SCSI devices' I/Os on the host */
14367         lpfc_scsi_dev_block(phba);
14368         lpfc_sli4_prep_dev_for_reset(phba);
14369
14370         /* stop all timers */
14371         lpfc_stop_hba_timers(phba);
14372
14373         /* Clean up all driver's outstanding SCSI I/Os */
14374         lpfc_sli_flush_io_rings(phba);
14375 }
14376
14377 /**
14378  * lpfc_io_error_detected_s3 - Method for handling SLI-3 device PCI I/O error
14379  * @pdev: pointer to PCI device.
14380  * @state: the current PCI connection state.
14381  *
14382  * This routine is called from the PCI subsystem for I/O error handling to
14383  * device with SLI-3 interface spec. This function is called by the PCI
14384  * subsystem after a PCI bus error affecting this device has been detected.
14385  * When this function is invoked, it will need to stop all the I/Os and
14386  * interrupt(s) to the device. Once that is done, it will return
14387  * PCI_ERS_RESULT_NEED_RESET for the PCI subsystem to perform proper recovery
14388  * as desired.
14389  *
14390  * Return codes
14391  *      PCI_ERS_RESULT_CAN_RECOVER - can be recovered with reset_link
14392  *      PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
14393  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14394  **/
14395 static pci_ers_result_t
14396 lpfc_io_error_detected_s3(struct pci_dev *pdev, pci_channel_state_t state)
14397 {
14398         struct Scsi_Host *shost = pci_get_drvdata(pdev);
14399         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14400
14401         switch (state) {
14402         case pci_channel_io_normal:
14403                 /* Non-fatal error, prepare for recovery */
14404                 lpfc_sli_prep_dev_for_recover(phba);
14405                 return PCI_ERS_RESULT_CAN_RECOVER;
14406         case pci_channel_io_frozen:
14407                 /* Fatal error, prepare for slot reset */
14408                 lpfc_sli_prep_dev_for_reset(phba);
14409                 return PCI_ERS_RESULT_NEED_RESET;
14410         case pci_channel_io_perm_failure:
14411                 /* Permanent failure, prepare for device down */
14412                 lpfc_sli_prep_dev_for_perm_failure(phba);
14413                 return PCI_ERS_RESULT_DISCONNECT;
14414         default:
14415                 /* Unknown state, prepare and request slot reset */
14416                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14417                                 "0472 Unknown PCI error state: x%x\n", state);
14418                 lpfc_sli_prep_dev_for_reset(phba);
14419                 return PCI_ERS_RESULT_NEED_RESET;
14420         }
14421 }
14422
14423 /**
14424  * lpfc_io_slot_reset_s3 - Method for restarting PCI SLI-3 device from scratch.
14425  * @pdev: pointer to PCI device.
14426  *
14427  * This routine is called from the PCI subsystem for error handling to
14428  * device with SLI-3 interface spec. This is called after PCI bus has been
14429  * reset to restart the PCI card from scratch, as if from a cold-boot.
14430  * During the PCI subsystem error recovery, after driver returns
14431  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
14432  * recovery and then call this routine before calling the .resume method
14433  * to recover the device. This function will initialize the HBA device,
14434  * enable the interrupt, but it will just put the HBA to offline state
14435  * without passing any I/O traffic.
14436  *
14437  * Return codes
14438  *      PCI_ERS_RESULT_RECOVERED - the device has been recovered
14439  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
14440  */
14441 static pci_ers_result_t
14442 lpfc_io_slot_reset_s3(struct pci_dev *pdev)
14443 {
14444         struct Scsi_Host *shost = pci_get_drvdata(pdev);
14445         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14446         struct lpfc_sli *psli = &phba->sli;
14447         uint32_t intr_mode;
14448
14449         dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
14450         if (pci_enable_device_mem(pdev)) {
14451                 printk(KERN_ERR "lpfc: Cannot re-enable "
14452                         "PCI device after reset.\n");
14453                 return PCI_ERS_RESULT_DISCONNECT;
14454         }
14455
14456         pci_restore_state(pdev);
14457
14458         /*
14459          * As the new kernel behavior of pci_restore_state() API call clears
14460          * device saved_state flag, need to save the restored state again.
14461          */
14462         pci_save_state(pdev);
14463
14464         if (pdev->is_busmaster)
14465                 pci_set_master(pdev);
14466
14467         spin_lock_irq(&phba->hbalock);
14468         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
14469         spin_unlock_irq(&phba->hbalock);
14470
14471         /* Configure and enable interrupt */
14472         intr_mode = lpfc_sli_enable_intr(phba, phba->intr_mode);
14473         if (intr_mode == LPFC_INTR_ERROR) {
14474                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14475                                 "0427 Cannot re-enable interrupt after "
14476                                 "slot reset.\n");
14477                 return PCI_ERS_RESULT_DISCONNECT;
14478         } else
14479                 phba->intr_mode = intr_mode;
14480
14481         /* Take device offline, it will perform cleanup */
14482         lpfc_offline_prep(phba, LPFC_MBX_WAIT);
14483         lpfc_offline(phba);
14484         lpfc_sli_brdrestart(phba);
14485
14486         /* Log the current active interrupt mode */
14487         lpfc_log_intr_mode(phba, phba->intr_mode);
14488
14489         return PCI_ERS_RESULT_RECOVERED;
14490 }
14491
14492 /**
14493  * lpfc_io_resume_s3 - Method for resuming PCI I/O operation on SLI-3 device.
14494  * @pdev: pointer to PCI device
14495  *
14496  * This routine is called from the PCI subsystem for error handling to device
14497  * with SLI-3 interface spec. It is called when kernel error recovery tells
14498  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
14499  * error recovery. After this call, traffic can start to flow from this device
14500  * again.
14501  */
14502 static void
14503 lpfc_io_resume_s3(struct pci_dev *pdev)
14504 {
14505         struct Scsi_Host *shost = pci_get_drvdata(pdev);
14506         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
14507
14508         /* Bring device online, it will be no-op for non-fatal error resume */
14509         lpfc_online(phba);
14510 }
14511
14512 /**
14513  * lpfc_sli4_get_els_iocb_cnt - Calculate the # of ELS IOCBs to reserve
14514  * @phba: pointer to lpfc hba data structure.
14515  *
14516  * returns the number of ELS/CT IOCBs to reserve
14517  **/
14518 int
14519 lpfc_sli4_get_els_iocb_cnt(struct lpfc_hba *phba)
14520 {
14521         int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
14522
14523         if (phba->sli_rev == LPFC_SLI_REV4) {
14524                 if (max_xri <= 100)
14525                         return 10;
14526                 else if (max_xri <= 256)
14527                         return 25;
14528                 else if (max_xri <= 512)
14529                         return 50;
14530                 else if (max_xri <= 1024)
14531                         return 100;
14532                 else if (max_xri <= 1536)
14533                         return 150;
14534                 else if (max_xri <= 2048)
14535                         return 200;
14536                 else
14537                         return 250;
14538         } else
14539                 return 0;
14540 }
14541
14542 /**
14543  * lpfc_sli4_get_iocb_cnt - Calculate the # of total IOCBs to reserve
14544  * @phba: pointer to lpfc hba data structure.
14545  *
14546  * returns the number of ELS/CT + NVMET IOCBs to reserve
14547  **/
14548 int
14549 lpfc_sli4_get_iocb_cnt(struct lpfc_hba *phba)
14550 {
14551         int max_xri = lpfc_sli4_get_els_iocb_cnt(phba);
14552
14553         if (phba->nvmet_support)
14554                 max_xri += LPFC_NVMET_BUF_POST;
14555         return max_xri;
14556 }
14557
14558
14559 static int
14560 lpfc_log_write_firmware_error(struct lpfc_hba *phba, uint32_t offset,
14561         uint32_t magic_number, uint32_t ftype, uint32_t fid, uint32_t fsize,
14562         const struct firmware *fw)
14563 {
14564         int rc;
14565         u8 sli_family;
14566
14567         sli_family = bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf);
14568         /* Three cases:  (1) FW was not supported on the detected adapter.
14569          * (2) FW update has been locked out administratively.
14570          * (3) Some other error during FW update.
14571          * In each case, an unmaskable message is written to the console
14572          * for admin diagnosis.
14573          */
14574         if (offset == ADD_STATUS_FW_NOT_SUPPORTED ||
14575             (sli_family == LPFC_SLI_INTF_FAMILY_G6 &&
14576              magic_number != MAGIC_NUMBER_G6) ||
14577             (sli_family == LPFC_SLI_INTF_FAMILY_G7 &&
14578              magic_number != MAGIC_NUMBER_G7) ||
14579             (sli_family == LPFC_SLI_INTF_FAMILY_G7P &&
14580              magic_number != MAGIC_NUMBER_G7P)) {
14581                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14582                                 "3030 This firmware version is not supported on"
14583                                 " this HBA model. Device:%x Magic:%x Type:%x "
14584                                 "ID:%x Size %d %zd\n",
14585                                 phba->pcidev->device, magic_number, ftype, fid,
14586                                 fsize, fw->size);
14587                 rc = -EINVAL;
14588         } else if (offset == ADD_STATUS_FW_DOWNLOAD_HW_DISABLED) {
14589                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14590                                 "3021 Firmware downloads have been prohibited "
14591                                 "by a system configuration setting on "
14592                                 "Device:%x Magic:%x Type:%x ID:%x Size %d "
14593                                 "%zd\n",
14594                                 phba->pcidev->device, magic_number, ftype, fid,
14595                                 fsize, fw->size);
14596                 rc = -EACCES;
14597         } else {
14598                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14599                                 "3022 FW Download failed. Add Status x%x "
14600                                 "Device:%x Magic:%x Type:%x ID:%x Size %d "
14601                                 "%zd\n",
14602                                 offset, phba->pcidev->device, magic_number,
14603                                 ftype, fid, fsize, fw->size);
14604                 rc = -EIO;
14605         }
14606         return rc;
14607 }
14608
14609 /**
14610  * lpfc_write_firmware - attempt to write a firmware image to the port
14611  * @fw: pointer to firmware image returned from request_firmware.
14612  * @context: pointer to firmware image returned from request_firmware.
14613  *
14614  **/
14615 static void
14616 lpfc_write_firmware(const struct firmware *fw, void *context)
14617 {
14618         struct lpfc_hba *phba = (struct lpfc_hba *)context;
14619         char fwrev[FW_REV_STR_SIZE];
14620         struct lpfc_grp_hdr *image;
14621         struct list_head dma_buffer_list;
14622         int i, rc = 0;
14623         struct lpfc_dmabuf *dmabuf, *next;
14624         uint32_t offset = 0, temp_offset = 0;
14625         uint32_t magic_number, ftype, fid, fsize;
14626
14627         /* It can be null in no-wait mode, sanity check */
14628         if (!fw) {
14629                 rc = -ENXIO;
14630                 goto out;
14631         }
14632         image = (struct lpfc_grp_hdr *)fw->data;
14633
14634         magic_number = be32_to_cpu(image->magic_number);
14635         ftype = bf_get_be32(lpfc_grp_hdr_file_type, image);
14636         fid = bf_get_be32(lpfc_grp_hdr_id, image);
14637         fsize = be32_to_cpu(image->size);
14638
14639         INIT_LIST_HEAD(&dma_buffer_list);
14640         lpfc_decode_firmware_rev(phba, fwrev, 1);
14641         if (strncmp(fwrev, image->revision, strnlen(image->revision, 16))) {
14642                 lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14643                              "3023 Updating Firmware, Current Version:%s "
14644                              "New Version:%s\n",
14645                              fwrev, image->revision);
14646                 for (i = 0; i < LPFC_MBX_WR_CONFIG_MAX_BDE; i++) {
14647                         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
14648                                          GFP_KERNEL);
14649                         if (!dmabuf) {
14650                                 rc = -ENOMEM;
14651                                 goto release_out;
14652                         }
14653                         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14654                                                           SLI4_PAGE_SIZE,
14655                                                           &dmabuf->phys,
14656                                                           GFP_KERNEL);
14657                         if (!dmabuf->virt) {
14658                                 kfree(dmabuf);
14659                                 rc = -ENOMEM;
14660                                 goto release_out;
14661                         }
14662                         list_add_tail(&dmabuf->list, &dma_buffer_list);
14663                 }
14664                 while (offset < fw->size) {
14665                         temp_offset = offset;
14666                         list_for_each_entry(dmabuf, &dma_buffer_list, list) {
14667                                 if (temp_offset + SLI4_PAGE_SIZE > fw->size) {
14668                                         memcpy(dmabuf->virt,
14669                                                fw->data + temp_offset,
14670                                                fw->size - temp_offset);
14671                                         temp_offset = fw->size;
14672                                         break;
14673                                 }
14674                                 memcpy(dmabuf->virt, fw->data + temp_offset,
14675                                        SLI4_PAGE_SIZE);
14676                                 temp_offset += SLI4_PAGE_SIZE;
14677                         }
14678                         rc = lpfc_wr_object(phba, &dma_buffer_list,
14679                                     (fw->size - offset), &offset);
14680                         if (rc) {
14681                                 rc = lpfc_log_write_firmware_error(phba, offset,
14682                                                                    magic_number,
14683                                                                    ftype,
14684                                                                    fid,
14685                                                                    fsize,
14686                                                                    fw);
14687                                 goto release_out;
14688                         }
14689                 }
14690                 rc = offset;
14691         } else
14692                 lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14693                              "3029 Skipped Firmware update, Current "
14694                              "Version:%s New Version:%s\n",
14695                              fwrev, image->revision);
14696
14697 release_out:
14698         list_for_each_entry_safe(dmabuf, next, &dma_buffer_list, list) {
14699                 list_del(&dmabuf->list);
14700                 dma_free_coherent(&phba->pcidev->dev, SLI4_PAGE_SIZE,
14701                                   dmabuf->virt, dmabuf->phys);
14702                 kfree(dmabuf);
14703         }
14704         release_firmware(fw);
14705 out:
14706         if (rc < 0)
14707                 lpfc_log_msg(phba, KERN_ERR, LOG_INIT | LOG_SLI,
14708                              "3062 Firmware update error, status %d.\n", rc);
14709         else
14710                 lpfc_log_msg(phba, KERN_NOTICE, LOG_INIT | LOG_SLI,
14711                              "3024 Firmware update success: size %d.\n", rc);
14712 }
14713
14714 /**
14715  * lpfc_sli4_request_firmware_update - Request linux generic firmware upgrade
14716  * @phba: pointer to lpfc hba data structure.
14717  * @fw_upgrade: which firmware to update.
14718  *
14719  * This routine is called to perform Linux generic firmware upgrade on device
14720  * that supports such feature.
14721  **/
14722 int
14723 lpfc_sli4_request_firmware_update(struct lpfc_hba *phba, uint8_t fw_upgrade)
14724 {
14725         char file_name[ELX_FW_NAME_SIZE] = {0};
14726         int ret;
14727         const struct firmware *fw;
14728
14729         /* Only supported on SLI4 interface type 2 for now */
14730         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) <
14731             LPFC_SLI_INTF_IF_TYPE_2)
14732                 return -EPERM;
14733
14734         scnprintf(file_name, sizeof(file_name), "%s.grp", phba->ModelName);
14735
14736         if (fw_upgrade == INT_FW_UPGRADE) {
14737                 ret = request_firmware_nowait(THIS_MODULE, FW_ACTION_UEVENT,
14738                                         file_name, &phba->pcidev->dev,
14739                                         GFP_KERNEL, (void *)phba,
14740                                         lpfc_write_firmware);
14741         } else if (fw_upgrade == RUN_FW_UPGRADE) {
14742                 ret = request_firmware(&fw, file_name, &phba->pcidev->dev);
14743                 if (!ret)
14744                         lpfc_write_firmware(fw, (void *)phba);
14745         } else {
14746                 ret = -EINVAL;
14747         }
14748
14749         return ret;
14750 }
14751
14752 /**
14753  * lpfc_pci_probe_one_s4 - PCI probe func to reg SLI-4 device to PCI subsys
14754  * @pdev: pointer to PCI device
14755  * @pid: pointer to PCI device identifier
14756  *
14757  * This routine is called from the kernel's PCI subsystem to device with
14758  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14759  * presented on PCI bus, the kernel PCI subsystem looks at PCI device-specific
14760  * information of the device and driver to see if the driver state that it
14761  * can support this kind of device. If the match is successful, the driver
14762  * core invokes this routine. If this routine determines it can claim the HBA,
14763  * it does all the initialization that it needs to do to handle the HBA
14764  * properly.
14765  *
14766  * Return code
14767  *      0 - driver can claim the device
14768  *      negative value - driver can not claim the device
14769  **/
14770 static int
14771 lpfc_pci_probe_one_s4(struct pci_dev *pdev, const struct pci_device_id *pid)
14772 {
14773         struct lpfc_hba   *phba;
14774         struct lpfc_vport *vport = NULL;
14775         struct Scsi_Host  *shost = NULL;
14776         int error;
14777         uint32_t cfg_mode, intr_mode;
14778
14779         /* Allocate memory for HBA structure */
14780         phba = lpfc_hba_alloc(pdev);
14781         if (!phba)
14782                 return -ENOMEM;
14783
14784         INIT_LIST_HEAD(&phba->poll_list);
14785
14786         /* Perform generic PCI device enabling operation */
14787         error = lpfc_enable_pci_dev(phba);
14788         if (error)
14789                 goto out_free_phba;
14790
14791         /* Set up SLI API function jump table for PCI-device group-1 HBAs */
14792         error = lpfc_api_table_setup(phba, LPFC_PCI_DEV_OC);
14793         if (error)
14794                 goto out_disable_pci_dev;
14795
14796         /* Set up SLI-4 specific device PCI memory space */
14797         error = lpfc_sli4_pci_mem_setup(phba);
14798         if (error) {
14799                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14800                                 "1410 Failed to set up pci memory space.\n");
14801                 goto out_disable_pci_dev;
14802         }
14803
14804         /* Set up SLI-4 Specific device driver resources */
14805         error = lpfc_sli4_driver_resource_setup(phba);
14806         if (error) {
14807                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14808                                 "1412 Failed to set up driver resource.\n");
14809                 goto out_unset_pci_mem_s4;
14810         }
14811
14812         INIT_LIST_HEAD(&phba->active_rrq_list);
14813         INIT_LIST_HEAD(&phba->fcf.fcf_pri_list);
14814
14815         /* Set up common device driver resources */
14816         error = lpfc_setup_driver_resource_phase2(phba);
14817         if (error) {
14818                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14819                                 "1414 Failed to set up driver resource.\n");
14820                 goto out_unset_driver_resource_s4;
14821         }
14822
14823         /* Get the default values for Model Name and Description */
14824         lpfc_get_hba_model_desc(phba, phba->ModelName, phba->ModelDesc);
14825
14826         /* Now, trying to enable interrupt and bring up the device */
14827         cfg_mode = phba->cfg_use_msi;
14828
14829         /* Put device to a known state before enabling interrupt */
14830         phba->pport = NULL;
14831         lpfc_stop_port(phba);
14832
14833         /* Init cpu_map array */
14834         lpfc_cpu_map_array_init(phba);
14835
14836         /* Init hba_eq_hdl array */
14837         lpfc_hba_eq_hdl_array_init(phba);
14838
14839         /* Configure and enable interrupt */
14840         intr_mode = lpfc_sli4_enable_intr(phba, cfg_mode);
14841         if (intr_mode == LPFC_INTR_ERROR) {
14842                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14843                                 "0426 Failed to enable interrupt.\n");
14844                 error = -ENODEV;
14845                 goto out_unset_driver_resource;
14846         }
14847         /* Default to single EQ for non-MSI-X */
14848         if (phba->intr_type != MSIX) {
14849                 phba->cfg_irq_chann = 1;
14850                 if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14851                         if (phba->nvmet_support)
14852                                 phba->cfg_nvmet_mrq = 1;
14853                 }
14854         }
14855         lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
14856
14857         /* Create SCSI host to the physical port */
14858         error = lpfc_create_shost(phba);
14859         if (error) {
14860                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14861                                 "1415 Failed to create scsi host.\n");
14862                 goto out_disable_intr;
14863         }
14864         vport = phba->pport;
14865         shost = lpfc_shost_from_vport(vport); /* save shost for error cleanup */
14866
14867         /* Configure sysfs attributes */
14868         error = lpfc_alloc_sysfs_attr(vport);
14869         if (error) {
14870                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14871                                 "1416 Failed to allocate sysfs attr\n");
14872                 goto out_destroy_shost;
14873         }
14874
14875         /* Set up SLI-4 HBA */
14876         if (lpfc_sli4_hba_setup(phba)) {
14877                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14878                                 "1421 Failed to set up hba\n");
14879                 error = -ENODEV;
14880                 goto out_free_sysfs_attr;
14881         }
14882
14883         /* Log the current active interrupt mode */
14884         phba->intr_mode = intr_mode;
14885         lpfc_log_intr_mode(phba, intr_mode);
14886
14887         /* Perform post initialization setup */
14888         lpfc_post_init_setup(phba);
14889
14890         /* NVME support in FW earlier in the driver load corrects the
14891          * FC4 type making a check for nvme_support unnecessary.
14892          */
14893         if (phba->nvmet_support == 0) {
14894                 if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14895                         /* Create NVME binding with nvme_fc_transport. This
14896                          * ensures the vport is initialized.  If the localport
14897                          * create fails, it should not unload the driver to
14898                          * support field issues.
14899                          */
14900                         error = lpfc_nvme_create_localport(vport);
14901                         if (error) {
14902                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14903                                                 "6004 NVME registration "
14904                                                 "failed, error x%x\n",
14905                                                 error);
14906                         }
14907                 }
14908         }
14909
14910         /* check for firmware upgrade or downgrade */
14911         if (phba->cfg_request_firmware_upgrade)
14912                 lpfc_sli4_request_firmware_update(phba, INT_FW_UPGRADE);
14913
14914         /* Check if there are static vports to be created. */
14915         lpfc_create_static_vport(phba);
14916
14917         timer_setup(&phba->cpuhp_poll_timer, lpfc_sli4_poll_hbtimer, 0);
14918         cpuhp_state_add_instance_nocalls(lpfc_cpuhp_state, &phba->cpuhp);
14919
14920         return 0;
14921
14922 out_free_sysfs_attr:
14923         lpfc_free_sysfs_attr(vport);
14924 out_destroy_shost:
14925         lpfc_destroy_shost(phba);
14926 out_disable_intr:
14927         lpfc_sli4_disable_intr(phba);
14928 out_unset_driver_resource:
14929         lpfc_unset_driver_resource_phase2(phba);
14930 out_unset_driver_resource_s4:
14931         lpfc_sli4_driver_resource_unset(phba);
14932 out_unset_pci_mem_s4:
14933         lpfc_sli4_pci_mem_unset(phba);
14934 out_disable_pci_dev:
14935         lpfc_disable_pci_dev(phba);
14936         if (shost)
14937                 scsi_host_put(shost);
14938 out_free_phba:
14939         lpfc_hba_free(phba);
14940         return error;
14941 }
14942
14943 /**
14944  * lpfc_pci_remove_one_s4 - PCI func to unreg SLI-4 device from PCI subsystem
14945  * @pdev: pointer to PCI device
14946  *
14947  * This routine is called from the kernel's PCI subsystem to device with
14948  * SLI-4 interface spec. When an Emulex HBA with SLI-4 interface spec is
14949  * removed from PCI bus, it performs all the necessary cleanup for the HBA
14950  * device to be removed from the PCI subsystem properly.
14951  **/
14952 static void
14953 lpfc_pci_remove_one_s4(struct pci_dev *pdev)
14954 {
14955         struct Scsi_Host *shost = pci_get_drvdata(pdev);
14956         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
14957         struct lpfc_vport **vports;
14958         struct lpfc_hba *phba = vport->phba;
14959         int i;
14960
14961         /* Mark the device unloading flag */
14962         set_bit(FC_UNLOADING, &vport->load_flag);
14963         if (phba->cgn_i)
14964                 lpfc_unreg_congestion_buf(phba);
14965
14966         lpfc_free_sysfs_attr(vport);
14967
14968         /* Release all the vports against this physical port */
14969         vports = lpfc_create_vport_work_array(phba);
14970         if (vports != NULL)
14971                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
14972                         if (vports[i]->port_type == LPFC_PHYSICAL_PORT)
14973                                 continue;
14974                         fc_vport_terminate(vports[i]->fc_vport);
14975                 }
14976         lpfc_destroy_vport_work_array(phba, vports);
14977
14978         /* Remove FC host with the physical port */
14979         fc_remove_host(shost);
14980         scsi_remove_host(shost);
14981
14982         /* Perform ndlp cleanup on the physical port.  The nvme and nvmet
14983          * localports are destroyed after to cleanup all transport memory.
14984          */
14985         lpfc_cleanup(vport);
14986         lpfc_nvmet_destroy_targetport(phba);
14987         lpfc_nvme_destroy_localport(vport);
14988
14989         /* De-allocate multi-XRI pools */
14990         if (phba->cfg_xri_rebalancing)
14991                 lpfc_destroy_multixri_pools(phba);
14992
14993         /*
14994          * Bring down the SLI Layer. This step disables all interrupts,
14995          * clears the rings, discards all mailbox commands, and resets
14996          * the HBA FCoE function.
14997          */
14998         lpfc_debugfs_terminate(vport);
14999
15000         lpfc_stop_hba_timers(phba);
15001         spin_lock_irq(&phba->port_list_lock);
15002         list_del_init(&vport->listentry);
15003         spin_unlock_irq(&phba->port_list_lock);
15004
15005         /* Perform scsi free before driver resource_unset since scsi
15006          * buffers are released to their corresponding pools here.
15007          */
15008         lpfc_io_free(phba);
15009         lpfc_free_iocb_list(phba);
15010         lpfc_sli4_hba_unset(phba);
15011
15012         lpfc_unset_driver_resource_phase2(phba);
15013         lpfc_sli4_driver_resource_unset(phba);
15014
15015         /* Unmap adapter Control and Doorbell registers */
15016         lpfc_sli4_pci_mem_unset(phba);
15017
15018         /* Release PCI resources and disable device's PCI function */
15019         scsi_host_put(shost);
15020         lpfc_disable_pci_dev(phba);
15021
15022         /* Finally, free the driver's device data structure */
15023         lpfc_hba_free(phba);
15024
15025         return;
15026 }
15027
15028 /**
15029  * lpfc_pci_suspend_one_s4 - PCI func to suspend SLI-4 device for power mgmnt
15030  * @dev_d: pointer to device
15031  *
15032  * This routine is called from the kernel's PCI subsystem to support system
15033  * Power Management (PM) to device with SLI-4 interface spec. When PM invokes
15034  * this method, it quiesces the device by stopping the driver's worker
15035  * thread for the device, turning off device's interrupt and DMA, and bring
15036  * the device offline. Note that as the driver implements the minimum PM
15037  * requirements to a power-aware driver's PM support for suspend/resume -- all
15038  * the possible PM messages (SUSPEND, HIBERNATE, FREEZE) to the suspend()
15039  * method call will be treated as SUSPEND and the driver will fully
15040  * reinitialize its device during resume() method call, the driver will set
15041  * device to PCI_D3hot state in PCI config space instead of setting it
15042  * according to the @msg provided by the PM.
15043  *
15044  * Return code
15045  *      0 - driver suspended the device
15046  *      Error otherwise
15047  **/
15048 static int __maybe_unused
15049 lpfc_pci_suspend_one_s4(struct device *dev_d)
15050 {
15051         struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15052         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15053
15054         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15055                         "2843 PCI device Power Management suspend.\n");
15056
15057         /* Bring down the device */
15058         lpfc_offline_prep(phba, LPFC_MBX_WAIT);
15059         lpfc_offline(phba);
15060         kthread_stop(phba->worker_thread);
15061
15062         /* Disable interrupt from device */
15063         lpfc_sli4_disable_intr(phba);
15064         lpfc_sli4_queue_destroy(phba);
15065
15066         return 0;
15067 }
15068
15069 /**
15070  * lpfc_pci_resume_one_s4 - PCI func to resume SLI-4 device for power mgmnt
15071  * @dev_d: pointer to device
15072  *
15073  * This routine is called from the kernel's PCI subsystem to support system
15074  * Power Management (PM) to device with SLI-4 interface spac. When PM invokes
15075  * this method, it restores the device's PCI config space state and fully
15076  * reinitializes the device and brings it online. Note that as the driver
15077  * implements the minimum PM requirements to a power-aware driver's PM for
15078  * suspend/resume -- all the possible PM messages (SUSPEND, HIBERNATE, FREEZE)
15079  * to the suspend() method call will be treated as SUSPEND and the driver
15080  * will fully reinitialize its device during resume() method call, the device
15081  * will be set to PCI_D0 directly in PCI config space before restoring the
15082  * state.
15083  *
15084  * Return code
15085  *      0 - driver suspended the device
15086  *      Error otherwise
15087  **/
15088 static int __maybe_unused
15089 lpfc_pci_resume_one_s4(struct device *dev_d)
15090 {
15091         struct Scsi_Host *shost = dev_get_drvdata(dev_d);
15092         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15093         uint32_t intr_mode;
15094         int error;
15095
15096         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15097                         "0292 PCI device Power Management resume.\n");
15098
15099          /* Startup the kernel thread for this host adapter. */
15100         phba->worker_thread = kthread_run(lpfc_do_work, phba,
15101                                         "lpfc_worker_%d", phba->brd_no);
15102         if (IS_ERR(phba->worker_thread)) {
15103                 error = PTR_ERR(phba->worker_thread);
15104                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15105                                 "0293 PM resume failed to start worker "
15106                                 "thread: error=x%x.\n", error);
15107                 return error;
15108         }
15109
15110         /* Configure and enable interrupt */
15111         intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15112         if (intr_mode == LPFC_INTR_ERROR) {
15113                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15114                                 "0294 PM resume Failed to enable interrupt\n");
15115                 return -EIO;
15116         } else
15117                 phba->intr_mode = intr_mode;
15118
15119         /* Restart HBA and bring it online */
15120         lpfc_sli_brdrestart(phba);
15121         lpfc_online(phba);
15122
15123         /* Log the current active interrupt mode */
15124         lpfc_log_intr_mode(phba, phba->intr_mode);
15125
15126         return 0;
15127 }
15128
15129 /**
15130  * lpfc_sli4_prep_dev_for_recover - Prepare SLI4 device for pci slot recover
15131  * @phba: pointer to lpfc hba data structure.
15132  *
15133  * This routine is called to prepare the SLI4 device for PCI slot recover. It
15134  * aborts all the outstanding SCSI I/Os to the pci device.
15135  **/
15136 static void
15137 lpfc_sli4_prep_dev_for_recover(struct lpfc_hba *phba)
15138 {
15139         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15140                         "2828 PCI channel I/O abort preparing for recovery\n");
15141         /*
15142          * There may be errored I/Os through HBA, abort all I/Os on txcmplq
15143          * and let the SCSI mid-layer to retry them to recover.
15144          */
15145         lpfc_sli_abort_fcp_rings(phba);
15146 }
15147
15148 /**
15149  * lpfc_sli4_prep_dev_for_reset - Prepare SLI4 device for pci slot reset
15150  * @phba: pointer to lpfc hba data structure.
15151  *
15152  * This routine is called to prepare the SLI4 device for PCI slot reset. It
15153  * disables the device interrupt and pci device, and aborts the internal FCP
15154  * pending I/Os.
15155  **/
15156 static void
15157 lpfc_sli4_prep_dev_for_reset(struct lpfc_hba *phba)
15158 {
15159         int offline =  pci_channel_offline(phba->pcidev);
15160
15161         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15162                         "2826 PCI channel disable preparing for reset offline"
15163                         " %d\n", offline);
15164
15165         /* Block any management I/Os to the device */
15166         lpfc_block_mgmt_io(phba, LPFC_MBX_NO_WAIT);
15167
15168
15169         /* HBA_PCI_ERR was set in io_error_detect */
15170         lpfc_offline_prep(phba, LPFC_MBX_NO_WAIT);
15171         /* Flush all driver's outstanding I/Os as we are to reset */
15172         lpfc_sli_flush_io_rings(phba);
15173         lpfc_offline(phba);
15174
15175         /* stop all timers */
15176         lpfc_stop_hba_timers(phba);
15177
15178         lpfc_sli4_queue_destroy(phba);
15179         /* Disable interrupt and pci device */
15180         lpfc_sli4_disable_intr(phba);
15181         pci_disable_device(phba->pcidev);
15182 }
15183
15184 /**
15185  * lpfc_sli4_prep_dev_for_perm_failure - Prepare SLI4 dev for pci slot disable
15186  * @phba: pointer to lpfc hba data structure.
15187  *
15188  * This routine is called to prepare the SLI4 device for PCI slot permanently
15189  * disabling. It blocks the SCSI transport layer traffic and flushes the FCP
15190  * pending I/Os.
15191  **/
15192 static void
15193 lpfc_sli4_prep_dev_for_perm_failure(struct lpfc_hba *phba)
15194 {
15195         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15196                         "2827 PCI channel permanent disable for failure\n");
15197
15198         /* Block all SCSI devices' I/Os on the host */
15199         lpfc_scsi_dev_block(phba);
15200
15201         /* stop all timers */
15202         lpfc_stop_hba_timers(phba);
15203
15204         /* Clean up all driver's outstanding I/Os */
15205         lpfc_sli_flush_io_rings(phba);
15206 }
15207
15208 /**
15209  * lpfc_io_error_detected_s4 - Method for handling PCI I/O error to SLI-4 device
15210  * @pdev: pointer to PCI device.
15211  * @state: the current PCI connection state.
15212  *
15213  * This routine is called from the PCI subsystem for error handling to device
15214  * with SLI-4 interface spec. This function is called by the PCI subsystem
15215  * after a PCI bus error affecting this device has been detected. When this
15216  * function is invoked, it will need to stop all the I/Os and interrupt(s)
15217  * to the device. Once that is done, it will return PCI_ERS_RESULT_NEED_RESET
15218  * for the PCI subsystem to perform proper recovery as desired.
15219  *
15220  * Return codes
15221  *      PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15222  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15223  **/
15224 static pci_ers_result_t
15225 lpfc_io_error_detected_s4(struct pci_dev *pdev, pci_channel_state_t state)
15226 {
15227         struct Scsi_Host *shost = pci_get_drvdata(pdev);
15228         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15229         bool hba_pci_err;
15230
15231         switch (state) {
15232         case pci_channel_io_normal:
15233                 /* Non-fatal error, prepare for recovery */
15234                 lpfc_sli4_prep_dev_for_recover(phba);
15235                 return PCI_ERS_RESULT_CAN_RECOVER;
15236         case pci_channel_io_frozen:
15237                 hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15238                 /* Fatal error, prepare for slot reset */
15239                 if (!hba_pci_err)
15240                         lpfc_sli4_prep_dev_for_reset(phba);
15241                 else
15242                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15243                                         "2832  Already handling PCI error "
15244                                         "state: x%x\n", state);
15245                 return PCI_ERS_RESULT_NEED_RESET;
15246         case pci_channel_io_perm_failure:
15247                 set_bit(HBA_PCI_ERR, &phba->bit_flags);
15248                 /* Permanent failure, prepare for device down */
15249                 lpfc_sli4_prep_dev_for_perm_failure(phba);
15250                 return PCI_ERS_RESULT_DISCONNECT;
15251         default:
15252                 hba_pci_err = test_and_set_bit(HBA_PCI_ERR, &phba->bit_flags);
15253                 if (!hba_pci_err)
15254                         lpfc_sli4_prep_dev_for_reset(phba);
15255                 /* Unknown state, prepare and request slot reset */
15256                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15257                                 "2825 Unknown PCI error state: x%x\n", state);
15258                 lpfc_sli4_prep_dev_for_reset(phba);
15259                 return PCI_ERS_RESULT_NEED_RESET;
15260         }
15261 }
15262
15263 /**
15264  * lpfc_io_slot_reset_s4 - Method for restart PCI SLI-4 device from scratch
15265  * @pdev: pointer to PCI device.
15266  *
15267  * This routine is called from the PCI subsystem for error handling to device
15268  * with SLI-4 interface spec. It is called after PCI bus has been reset to
15269  * restart the PCI card from scratch, as if from a cold-boot. During the
15270  * PCI subsystem error recovery, after the driver returns
15271  * PCI_ERS_RESULT_NEED_RESET, the PCI subsystem will perform proper error
15272  * recovery and then call this routine before calling the .resume method to
15273  * recover the device. This function will initialize the HBA device, enable
15274  * the interrupt, but it will just put the HBA to offline state without
15275  * passing any I/O traffic.
15276  *
15277  * Return codes
15278  *      PCI_ERS_RESULT_RECOVERED - the device has been recovered
15279  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15280  */
15281 static pci_ers_result_t
15282 lpfc_io_slot_reset_s4(struct pci_dev *pdev)
15283 {
15284         struct Scsi_Host *shost = pci_get_drvdata(pdev);
15285         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15286         struct lpfc_sli *psli = &phba->sli;
15287         uint32_t intr_mode;
15288         bool hba_pci_err;
15289
15290         dev_printk(KERN_INFO, &pdev->dev, "recovering from a slot reset.\n");
15291         if (pci_enable_device_mem(pdev)) {
15292                 printk(KERN_ERR "lpfc: Cannot re-enable "
15293                        "PCI device after reset.\n");
15294                 return PCI_ERS_RESULT_DISCONNECT;
15295         }
15296
15297         pci_restore_state(pdev);
15298
15299         hba_pci_err = test_and_clear_bit(HBA_PCI_ERR, &phba->bit_flags);
15300         if (!hba_pci_err)
15301                 dev_info(&pdev->dev,
15302                          "hba_pci_err was not set, recovering slot reset.\n");
15303         /*
15304          * As the new kernel behavior of pci_restore_state() API call clears
15305          * device saved_state flag, need to save the restored state again.
15306          */
15307         pci_save_state(pdev);
15308
15309         if (pdev->is_busmaster)
15310                 pci_set_master(pdev);
15311
15312         spin_lock_irq(&phba->hbalock);
15313         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
15314         spin_unlock_irq(&phba->hbalock);
15315
15316         /* Init cpu_map array */
15317         lpfc_cpu_map_array_init(phba);
15318         /* Configure and enable interrupt */
15319         intr_mode = lpfc_sli4_enable_intr(phba, phba->intr_mode);
15320         if (intr_mode == LPFC_INTR_ERROR) {
15321                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15322                                 "2824 Cannot re-enable interrupt after "
15323                                 "slot reset.\n");
15324                 return PCI_ERS_RESULT_DISCONNECT;
15325         } else
15326                 phba->intr_mode = intr_mode;
15327         lpfc_cpu_affinity_check(phba, phba->cfg_irq_chann);
15328
15329         /* Log the current active interrupt mode */
15330         lpfc_log_intr_mode(phba, phba->intr_mode);
15331
15332         return PCI_ERS_RESULT_RECOVERED;
15333 }
15334
15335 /**
15336  * lpfc_io_resume_s4 - Method for resuming PCI I/O operation to SLI-4 device
15337  * @pdev: pointer to PCI device
15338  *
15339  * This routine is called from the PCI subsystem for error handling to device
15340  * with SLI-4 interface spec. It is called when kernel error recovery tells
15341  * the lpfc driver that it is ok to resume normal PCI operation after PCI bus
15342  * error recovery. After this call, traffic can start to flow from this device
15343  * again.
15344  **/
15345 static void
15346 lpfc_io_resume_s4(struct pci_dev *pdev)
15347 {
15348         struct Scsi_Host *shost = pci_get_drvdata(pdev);
15349         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15350
15351         /*
15352          * In case of slot reset, as function reset is performed through
15353          * mailbox command which needs DMA to be enabled, this operation
15354          * has to be moved to the io resume phase. Taking device offline
15355          * will perform the necessary cleanup.
15356          */
15357         if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)) {
15358                 /* Perform device reset */
15359                 lpfc_sli_brdrestart(phba);
15360                 /* Bring the device back online */
15361                 lpfc_online(phba);
15362         }
15363 }
15364
15365 /**
15366  * lpfc_pci_probe_one - lpfc PCI probe func to reg dev to PCI subsystem
15367  * @pdev: pointer to PCI device
15368  * @pid: pointer to PCI device identifier
15369  *
15370  * This routine is to be registered to the kernel's PCI subsystem. When an
15371  * Emulex HBA device is presented on PCI bus, the kernel PCI subsystem looks
15372  * at PCI device-specific information of the device and driver to see if the
15373  * driver state that it can support this kind of device. If the match is
15374  * successful, the driver core invokes this routine. This routine dispatches
15375  * the action to the proper SLI-3 or SLI-4 device probing routine, which will
15376  * do all the initialization that it needs to do to handle the HBA device
15377  * properly.
15378  *
15379  * Return code
15380  *      0 - driver can claim the device
15381  *      negative value - driver can not claim the device
15382  **/
15383 static int
15384 lpfc_pci_probe_one(struct pci_dev *pdev, const struct pci_device_id *pid)
15385 {
15386         int rc;
15387         struct lpfc_sli_intf intf;
15388
15389         if (pci_read_config_dword(pdev, LPFC_SLI_INTF, &intf.word0))
15390                 return -ENODEV;
15391
15392         if ((bf_get(lpfc_sli_intf_valid, &intf) == LPFC_SLI_INTF_VALID) &&
15393             (bf_get(lpfc_sli_intf_slirev, &intf) == LPFC_SLI_INTF_REV_SLI4))
15394                 rc = lpfc_pci_probe_one_s4(pdev, pid);
15395         else
15396                 rc = lpfc_pci_probe_one_s3(pdev, pid);
15397
15398         return rc;
15399 }
15400
15401 /**
15402  * lpfc_pci_remove_one - lpfc PCI func to unreg dev from PCI subsystem
15403  * @pdev: pointer to PCI device
15404  *
15405  * This routine is to be registered to the kernel's PCI subsystem. When an
15406  * Emulex HBA is removed from PCI bus, the driver core invokes this routine.
15407  * This routine dispatches the action to the proper SLI-3 or SLI-4 device
15408  * remove routine, which will perform all the necessary cleanup for the
15409  * device to be removed from the PCI subsystem properly.
15410  **/
15411 static void
15412 lpfc_pci_remove_one(struct pci_dev *pdev)
15413 {
15414         struct Scsi_Host *shost = pci_get_drvdata(pdev);
15415         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15416
15417         switch (phba->pci_dev_grp) {
15418         case LPFC_PCI_DEV_LP:
15419                 lpfc_pci_remove_one_s3(pdev);
15420                 break;
15421         case LPFC_PCI_DEV_OC:
15422                 lpfc_pci_remove_one_s4(pdev);
15423                 break;
15424         default:
15425                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15426                                 "1424 Invalid PCI device group: 0x%x\n",
15427                                 phba->pci_dev_grp);
15428                 break;
15429         }
15430         return;
15431 }
15432
15433 /**
15434  * lpfc_pci_suspend_one - lpfc PCI func to suspend dev for power management
15435  * @dev: pointer to device
15436  *
15437  * This routine is to be registered to the kernel's PCI subsystem to support
15438  * system Power Management (PM). When PM invokes this method, it dispatches
15439  * the action to the proper SLI-3 or SLI-4 device suspend routine, which will
15440  * suspend the device.
15441  *
15442  * Return code
15443  *      0 - driver suspended the device
15444  *      Error otherwise
15445  **/
15446 static int __maybe_unused
15447 lpfc_pci_suspend_one(struct device *dev)
15448 {
15449         struct Scsi_Host *shost = dev_get_drvdata(dev);
15450         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15451         int rc = -ENODEV;
15452
15453         switch (phba->pci_dev_grp) {
15454         case LPFC_PCI_DEV_LP:
15455                 rc = lpfc_pci_suspend_one_s3(dev);
15456                 break;
15457         case LPFC_PCI_DEV_OC:
15458                 rc = lpfc_pci_suspend_one_s4(dev);
15459                 break;
15460         default:
15461                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15462                                 "1425 Invalid PCI device group: 0x%x\n",
15463                                 phba->pci_dev_grp);
15464                 break;
15465         }
15466         return rc;
15467 }
15468
15469 /**
15470  * lpfc_pci_resume_one - lpfc PCI func to resume dev for power management
15471  * @dev: pointer to device
15472  *
15473  * This routine is to be registered to the kernel's PCI subsystem to support
15474  * system Power Management (PM). When PM invokes this method, it dispatches
15475  * the action to the proper SLI-3 or SLI-4 device resume routine, which will
15476  * resume the device.
15477  *
15478  * Return code
15479  *      0 - driver suspended the device
15480  *      Error otherwise
15481  **/
15482 static int __maybe_unused
15483 lpfc_pci_resume_one(struct device *dev)
15484 {
15485         struct Scsi_Host *shost = dev_get_drvdata(dev);
15486         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15487         int rc = -ENODEV;
15488
15489         switch (phba->pci_dev_grp) {
15490         case LPFC_PCI_DEV_LP:
15491                 rc = lpfc_pci_resume_one_s3(dev);
15492                 break;
15493         case LPFC_PCI_DEV_OC:
15494                 rc = lpfc_pci_resume_one_s4(dev);
15495                 break;
15496         default:
15497                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15498                                 "1426 Invalid PCI device group: 0x%x\n",
15499                                 phba->pci_dev_grp);
15500                 break;
15501         }
15502         return rc;
15503 }
15504
15505 /**
15506  * lpfc_io_error_detected - lpfc method for handling PCI I/O error
15507  * @pdev: pointer to PCI device.
15508  * @state: the current PCI connection state.
15509  *
15510  * This routine is registered to the PCI subsystem for error handling. This
15511  * function is called by the PCI subsystem after a PCI bus error affecting
15512  * this device has been detected. When this routine is invoked, it dispatches
15513  * the action to the proper SLI-3 or SLI-4 device error detected handling
15514  * routine, which will perform the proper error detected operation.
15515  *
15516  * Return codes
15517  *      PCI_ERS_RESULT_NEED_RESET - need to reset before recovery
15518  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15519  **/
15520 static pci_ers_result_t
15521 lpfc_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
15522 {
15523         struct Scsi_Host *shost = pci_get_drvdata(pdev);
15524         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15525         pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15526
15527         if (phba->link_state == LPFC_HBA_ERROR &&
15528             phba->hba_flag & HBA_IOQ_FLUSH)
15529                 return PCI_ERS_RESULT_NEED_RESET;
15530
15531         switch (phba->pci_dev_grp) {
15532         case LPFC_PCI_DEV_LP:
15533                 rc = lpfc_io_error_detected_s3(pdev, state);
15534                 break;
15535         case LPFC_PCI_DEV_OC:
15536                 rc = lpfc_io_error_detected_s4(pdev, state);
15537                 break;
15538         default:
15539                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15540                                 "1427 Invalid PCI device group: 0x%x\n",
15541                                 phba->pci_dev_grp);
15542                 break;
15543         }
15544         return rc;
15545 }
15546
15547 /**
15548  * lpfc_io_slot_reset - lpfc method for restart PCI dev from scratch
15549  * @pdev: pointer to PCI device.
15550  *
15551  * This routine is registered to the PCI subsystem for error handling. This
15552  * function is called after PCI bus has been reset to restart the PCI card
15553  * from scratch, as if from a cold-boot. When this routine is invoked, it
15554  * dispatches the action to the proper SLI-3 or SLI-4 device reset handling
15555  * routine, which will perform the proper device reset.
15556  *
15557  * Return codes
15558  *      PCI_ERS_RESULT_RECOVERED - the device has been recovered
15559  *      PCI_ERS_RESULT_DISCONNECT - device could not be recovered
15560  **/
15561 static pci_ers_result_t
15562 lpfc_io_slot_reset(struct pci_dev *pdev)
15563 {
15564         struct Scsi_Host *shost = pci_get_drvdata(pdev);
15565         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15566         pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
15567
15568         switch (phba->pci_dev_grp) {
15569         case LPFC_PCI_DEV_LP:
15570                 rc = lpfc_io_slot_reset_s3(pdev);
15571                 break;
15572         case LPFC_PCI_DEV_OC:
15573                 rc = lpfc_io_slot_reset_s4(pdev);
15574                 break;
15575         default:
15576                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15577                                 "1428 Invalid PCI device group: 0x%x\n",
15578                                 phba->pci_dev_grp);
15579                 break;
15580         }
15581         return rc;
15582 }
15583
15584 /**
15585  * lpfc_io_resume - lpfc method for resuming PCI I/O operation
15586  * @pdev: pointer to PCI device
15587  *
15588  * This routine is registered to the PCI subsystem for error handling. It
15589  * is called when kernel error recovery tells the lpfc driver that it is
15590  * OK to resume normal PCI operation after PCI bus error recovery. When
15591  * this routine is invoked, it dispatches the action to the proper SLI-3
15592  * or SLI-4 device io_resume routine, which will resume the device operation.
15593  **/
15594 static void
15595 lpfc_io_resume(struct pci_dev *pdev)
15596 {
15597         struct Scsi_Host *shost = pci_get_drvdata(pdev);
15598         struct lpfc_hba *phba = ((struct lpfc_vport *)shost->hostdata)->phba;
15599
15600         switch (phba->pci_dev_grp) {
15601         case LPFC_PCI_DEV_LP:
15602                 lpfc_io_resume_s3(pdev);
15603                 break;
15604         case LPFC_PCI_DEV_OC:
15605                 lpfc_io_resume_s4(pdev);
15606                 break;
15607         default:
15608                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15609                                 "1429 Invalid PCI device group: 0x%x\n",
15610                                 phba->pci_dev_grp);
15611                 break;
15612         }
15613         return;
15614 }
15615
15616 /**
15617  * lpfc_sli4_oas_verify - Verify OAS is supported by this adapter
15618  * @phba: pointer to lpfc hba data structure.
15619  *
15620  * This routine checks to see if OAS is supported for this adapter. If
15621  * supported, the configure Flash Optimized Fabric flag is set.  Otherwise,
15622  * the enable oas flag is cleared and the pool created for OAS device data
15623  * is destroyed.
15624  *
15625  **/
15626 static void
15627 lpfc_sli4_oas_verify(struct lpfc_hba *phba)
15628 {
15629
15630         if (!phba->cfg_EnableXLane)
15631                 return;
15632
15633         if (phba->sli4_hba.pc_sli4_params.oas_supported) {
15634                 phba->cfg_fof = 1;
15635         } else {
15636                 phba->cfg_fof = 0;
15637                 mempool_destroy(phba->device_data_mem_pool);
15638                 phba->device_data_mem_pool = NULL;
15639         }
15640
15641         return;
15642 }
15643
15644 /**
15645  * lpfc_sli4_ras_init - Verify RAS-FW log is supported by this adapter
15646  * @phba: pointer to lpfc hba data structure.
15647  *
15648  * This routine checks to see if RAS is supported by the adapter. Check the
15649  * function through which RAS support enablement is to be done.
15650  **/
15651 void
15652 lpfc_sli4_ras_init(struct lpfc_hba *phba)
15653 {
15654         /* if ASIC_GEN_NUM >= 0xC) */
15655         if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
15656                     LPFC_SLI_INTF_IF_TYPE_6) ||
15657             (bf_get(lpfc_sli_intf_sli_family, &phba->sli4_hba.sli_intf) ==
15658                     LPFC_SLI_INTF_FAMILY_G6)) {
15659                 phba->ras_fwlog.ras_hwsupport = true;
15660                 if (phba->cfg_ras_fwlog_func == PCI_FUNC(phba->pcidev->devfn) &&
15661                     phba->cfg_ras_fwlog_buffsize)
15662                         phba->ras_fwlog.ras_enabled = true;
15663                 else
15664                         phba->ras_fwlog.ras_enabled = false;
15665         } else {
15666                 phba->ras_fwlog.ras_hwsupport = false;
15667         }
15668 }
15669
15670
15671 MODULE_DEVICE_TABLE(pci, lpfc_id_table);
15672
15673 static const struct pci_error_handlers lpfc_err_handler = {
15674         .error_detected = lpfc_io_error_detected,
15675         .slot_reset = lpfc_io_slot_reset,
15676         .resume = lpfc_io_resume,
15677 };
15678
15679 static SIMPLE_DEV_PM_OPS(lpfc_pci_pm_ops_one,
15680                          lpfc_pci_suspend_one,
15681                          lpfc_pci_resume_one);
15682
15683 static struct pci_driver lpfc_driver = {
15684         .name           = LPFC_DRIVER_NAME,
15685         .id_table       = lpfc_id_table,
15686         .probe          = lpfc_pci_probe_one,
15687         .remove         = lpfc_pci_remove_one,
15688         .shutdown       = lpfc_pci_remove_one,
15689         .driver.pm      = &lpfc_pci_pm_ops_one,
15690         .err_handler    = &lpfc_err_handler,
15691 };
15692
15693 static const struct file_operations lpfc_mgmt_fop = {
15694         .owner = THIS_MODULE,
15695 };
15696
15697 static struct miscdevice lpfc_mgmt_dev = {
15698         .minor = MISC_DYNAMIC_MINOR,
15699         .name = "lpfcmgmt",
15700         .fops = &lpfc_mgmt_fop,
15701 };
15702
15703 /**
15704  * lpfc_init - lpfc module initialization routine
15705  *
15706  * This routine is to be invoked when the lpfc module is loaded into the
15707  * kernel. The special kernel macro module_init() is used to indicate the
15708  * role of this routine to the kernel as lpfc module entry point.
15709  *
15710  * Return codes
15711  *   0 - successful
15712  *   -ENOMEM - FC attach transport failed
15713  *   all others - failed
15714  */
15715 static int __init
15716 lpfc_init(void)
15717 {
15718         int error = 0;
15719
15720         pr_info(LPFC_MODULE_DESC "\n");
15721         pr_info(LPFC_COPYRIGHT "\n");
15722
15723         error = misc_register(&lpfc_mgmt_dev);
15724         if (error)
15725                 printk(KERN_ERR "Could not register lpfcmgmt device, "
15726                         "misc_register returned with status %d", error);
15727
15728         error = -ENOMEM;
15729         lpfc_transport_functions.vport_create = lpfc_vport_create;
15730         lpfc_transport_functions.vport_delete = lpfc_vport_delete;
15731         lpfc_transport_template =
15732                                 fc_attach_transport(&lpfc_transport_functions);
15733         if (lpfc_transport_template == NULL)
15734                 goto unregister;
15735         lpfc_vport_transport_template =
15736                 fc_attach_transport(&lpfc_vport_transport_functions);
15737         if (lpfc_vport_transport_template == NULL) {
15738                 fc_release_transport(lpfc_transport_template);
15739                 goto unregister;
15740         }
15741         lpfc_wqe_cmd_template();
15742         lpfc_nvmet_cmd_template();
15743
15744         /* Initialize in case vector mapping is needed */
15745         lpfc_present_cpu = num_present_cpus();
15746
15747         lpfc_pldv_detect = false;
15748
15749         error = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
15750                                         "lpfc/sli4:online",
15751                                         lpfc_cpu_online, lpfc_cpu_offline);
15752         if (error < 0)
15753                 goto cpuhp_failure;
15754         lpfc_cpuhp_state = error;
15755
15756         error = pci_register_driver(&lpfc_driver);
15757         if (error)
15758                 goto unwind;
15759
15760         return error;
15761
15762 unwind:
15763         cpuhp_remove_multi_state(lpfc_cpuhp_state);
15764 cpuhp_failure:
15765         fc_release_transport(lpfc_transport_template);
15766         fc_release_transport(lpfc_vport_transport_template);
15767 unregister:
15768         misc_deregister(&lpfc_mgmt_dev);
15769
15770         return error;
15771 }
15772
15773 void lpfc_dmp_dbg(struct lpfc_hba *phba)
15774 {
15775         unsigned int start_idx;
15776         unsigned int dbg_cnt;
15777         unsigned int temp_idx;
15778         int i;
15779         int j = 0;
15780         unsigned long rem_nsec;
15781
15782         if (atomic_cmpxchg(&phba->dbg_log_dmping, 0, 1) != 0)
15783                 return;
15784
15785         start_idx = (unsigned int)atomic_read(&phba->dbg_log_idx) % DBG_LOG_SZ;
15786         dbg_cnt = (unsigned int)atomic_read(&phba->dbg_log_cnt);
15787         if (!dbg_cnt)
15788                 goto out;
15789         temp_idx = start_idx;
15790         if (dbg_cnt >= DBG_LOG_SZ) {
15791                 dbg_cnt = DBG_LOG_SZ;
15792                 temp_idx -= 1;
15793         } else {
15794                 if ((start_idx + dbg_cnt) > (DBG_LOG_SZ - 1)) {
15795                         temp_idx = (start_idx + dbg_cnt) % DBG_LOG_SZ;
15796                 } else {
15797                         if (start_idx < dbg_cnt)
15798                                 start_idx = DBG_LOG_SZ - (dbg_cnt - start_idx);
15799                         else
15800                                 start_idx -= dbg_cnt;
15801                 }
15802         }
15803         dev_info(&phba->pcidev->dev, "start %d end %d cnt %d\n",
15804                  start_idx, temp_idx, dbg_cnt);
15805
15806         for (i = 0; i < dbg_cnt; i++) {
15807                 if ((start_idx + i) < DBG_LOG_SZ)
15808                         temp_idx = (start_idx + i) % DBG_LOG_SZ;
15809                 else
15810                         temp_idx = j++;
15811                 rem_nsec = do_div(phba->dbg_log[temp_idx].t_ns, NSEC_PER_SEC);
15812                 dev_info(&phba->pcidev->dev, "%d: [%5lu.%06lu] %s",
15813                          temp_idx,
15814                          (unsigned long)phba->dbg_log[temp_idx].t_ns,
15815                          rem_nsec / 1000,
15816                          phba->dbg_log[temp_idx].log);
15817         }
15818 out:
15819         atomic_set(&phba->dbg_log_cnt, 0);
15820         atomic_set(&phba->dbg_log_dmping, 0);
15821 }
15822
15823 __printf(2, 3)
15824 void lpfc_dbg_print(struct lpfc_hba *phba, const char *fmt, ...)
15825 {
15826         unsigned int idx;
15827         va_list args;
15828         int dbg_dmping = atomic_read(&phba->dbg_log_dmping);
15829         struct va_format vaf;
15830
15831
15832         va_start(args, fmt);
15833         if (unlikely(dbg_dmping)) {
15834                 vaf.fmt = fmt;
15835                 vaf.va = &args;
15836                 dev_info(&phba->pcidev->dev, "%pV", &vaf);
15837                 va_end(args);
15838                 return;
15839         }
15840         idx = (unsigned int)atomic_fetch_add(1, &phba->dbg_log_idx) %
15841                 DBG_LOG_SZ;
15842
15843         atomic_inc(&phba->dbg_log_cnt);
15844
15845         vscnprintf(phba->dbg_log[idx].log,
15846                    sizeof(phba->dbg_log[idx].log), fmt, args);
15847         va_end(args);
15848
15849         phba->dbg_log[idx].t_ns = local_clock();
15850 }
15851
15852 /**
15853  * lpfc_exit - lpfc module removal routine
15854  *
15855  * This routine is invoked when the lpfc module is removed from the kernel.
15856  * The special kernel macro module_exit() is used to indicate the role of
15857  * this routine to the kernel as lpfc module exit point.
15858  */
15859 static void __exit
15860 lpfc_exit(void)
15861 {
15862         misc_deregister(&lpfc_mgmt_dev);
15863         pci_unregister_driver(&lpfc_driver);
15864         cpuhp_remove_multi_state(lpfc_cpuhp_state);
15865         fc_release_transport(lpfc_transport_template);
15866         fc_release_transport(lpfc_vport_transport_template);
15867         idr_destroy(&lpfc_hba_index);
15868 }
15869
15870 module_init(lpfc_init);
15871 module_exit(lpfc_exit);
15872 MODULE_LICENSE("GPL");
15873 MODULE_DESCRIPTION(LPFC_MODULE_DESC);
15874 MODULE_AUTHOR("Broadcom");
15875 MODULE_VERSION("0:" LPFC_DRIVER_VERSION);